1 /* Copyright (c) 2009, 2010 The Regents of the University of California
2 * Barret Rhoden <brho@cs.berkeley.edu>
3 * See LICENSE for details. */
11 #include <arch/arch.h>
23 #include <hashtable.h>
25 #include <sys/queue.h>
29 #include <arsc_server.h>
32 struct kmem_cache *proc_cache;
34 /* Other helpers, implemented later. */
35 static void __proc_startcore(struct proc *p, trapframe_t *tf);
36 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid);
37 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid);
38 static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid);
39 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid);
40 static void __proc_free(struct kref *kref);
41 static bool scp_is_vcctx_ready(struct preempt_data *vcpd);
44 #define PID_MAX 32767 // goes from 0 to 32767, with 0 reserved
45 static DECL_BITMASK(pid_bmask, PID_MAX + 1);
46 spinlock_t pid_bmask_lock = SPINLOCK_INITIALIZER;
47 struct hashtable *pid_hash;
48 spinlock_t pid_hash_lock; // initialized in proc_init
50 /* Finds the next free entry (zero) entry in the pid_bitmask. Set means busy.
51 * PID 0 is reserved (in proc_init). A return value of 0 is a failure (and
52 * you'll also see a warning, for now). Consider doing this with atomics. */
53 static pid_t get_free_pid(void)
55 static pid_t next_free_pid = 1;
58 spin_lock(&pid_bmask_lock);
59 // atomically (can lock for now, then change to atomic_and_return
60 FOR_CIRC_BUFFER(next_free_pid, PID_MAX + 1, i) {
61 // always points to the next to test
62 next_free_pid = (next_free_pid + 1) % (PID_MAX + 1);
63 if (!GET_BITMASK_BIT(pid_bmask, i)) {
64 SET_BITMASK_BIT(pid_bmask, i);
69 spin_unlock(&pid_bmask_lock);
71 warn("Shazbot! Unable to find a PID! You need to deal with this!\n");
75 /* Return a pid to the pid bitmask */
76 static void put_free_pid(pid_t pid)
78 spin_lock(&pid_bmask_lock);
79 CLR_BITMASK_BIT(pid_bmask, pid);
80 spin_unlock(&pid_bmask_lock);
83 /* While this could be done with just an assignment, this gives us the
84 * opportunity to check for bad transitions. Might compile these out later, so
85 * we shouldn't rely on them for sanity checking from userspace. */
86 int __proc_set_state(struct proc *p, uint32_t state)
88 uint32_t curstate = p->state;
105 * These ought to be implemented later (allowed, not thought through yet).
109 #if 1 // some sort of correctness flag
112 if (!(state & (PROC_RUNNABLE_S | PROC_DYING)))
113 panic("Invalid State Transition! PROC_CREATED to %02x", state);
115 case PROC_RUNNABLE_S:
116 if (!(state & (PROC_RUNNING_S | PROC_DYING)))
117 panic("Invalid State Transition! PROC_RUNNABLE_S to %02x", state);
120 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
122 panic("Invalid State Transition! PROC_RUNNING_S to %02x", state);
125 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M)))
126 panic("Invalid State Transition! PROC_WAITING to %02x", state);
129 if (state != PROC_CREATED) // when it is reused (TODO)
130 panic("Invalid State Transition! PROC_DYING to %02x", state);
132 case PROC_RUNNABLE_M:
133 if (!(state & (PROC_RUNNING_M | PROC_DYING)))
134 panic("Invalid State Transition! PROC_RUNNABLE_M to %02x", state);
137 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
139 panic("Invalid State Transition! PROC_RUNNING_M to %02x", state);
147 /* Returns a pointer to the proc with the given pid, or 0 if there is none.
148 * This uses get_not_zero, since it is possible the refcnt is 0, which means the
149 * process is dying and we should not have the ref (and thus return 0). We need
150 * to lock to protect us from getting p, (someone else removes and frees p),
151 * then get_not_zero() on p.
152 * Don't push the locking into the hashtable without dealing with this. */
153 struct proc *pid2proc(pid_t pid)
155 spin_lock(&pid_hash_lock);
156 struct proc *p = hashtable_search(pid_hash, (void*)(long)pid);
158 if (!kref_get_not_zero(&p->p_kref, 1))
160 spin_unlock(&pid_hash_lock);
164 /* Performs any initialization related to processes, such as create the proc
165 * cache, prep the scheduler, etc. When this returns, we should be ready to use
166 * any process related function. */
169 /* Catch issues with the vcoremap and TAILQ_ENTRY sizes */
170 static_assert(sizeof(TAILQ_ENTRY(vcore)) == sizeof(void*) * 2);
171 proc_cache = kmem_cache_create("proc", sizeof(struct proc),
172 MAX(HW_CACHE_ALIGN, __alignof__(struct proc)), 0, 0, 0);
173 /* Init PID mask and hash. pid 0 is reserved. */
174 SET_BITMASK_BIT(pid_bmask, 0);
175 spinlock_init(&pid_hash_lock);
176 spin_lock(&pid_hash_lock);
177 pid_hash = create_hashtable(100, __generic_hash, __generic_eq);
178 spin_unlock(&pid_hash_lock);
181 atomic_init(&num_envs, 0);
184 /* Be sure you init'd the vcore lists before calling this. */
185 static void proc_init_procinfo(struct proc* p)
187 p->procinfo->pid = p->pid;
188 p->procinfo->ppid = p->ppid;
189 p->procinfo->max_vcores = max_vcores(p);
190 p->procinfo->tsc_freq = system_timing.tsc_freq;
191 p->procinfo->heap_bottom = (void*)UTEXT;
192 /* 0'ing the arguments. Some higher function will need to set them */
193 memset(p->procinfo->argp, 0, sizeof(p->procinfo->argp));
194 memset(p->procinfo->argbuf, 0, sizeof(p->procinfo->argbuf));
195 memset(p->procinfo->res_grant, 0, sizeof(p->procinfo->res_grant));
196 /* 0'ing the vcore/pcore map. Will link the vcores later. */
197 memset(&p->procinfo->vcoremap, 0, sizeof(p->procinfo->vcoremap));
198 memset(&p->procinfo->pcoremap, 0, sizeof(p->procinfo->pcoremap));
199 p->procinfo->num_vcores = 0;
200 p->procinfo->is_mcp = FALSE;
201 p->procinfo->coremap_seqctr = SEQCTR_INITIALIZER;
202 /* For now, we'll go up to the max num_cpus (at runtime). In the future,
203 * there may be cases where we can have more vcores than num_cpus, but for
204 * now we'll leave it like this. */
205 for (int i = 0; i < num_cpus; i++) {
206 TAILQ_INSERT_TAIL(&p->inactive_vcs, &p->procinfo->vcoremap[i], list);
210 static void proc_init_procdata(struct proc *p)
212 memset(p->procdata, 0, sizeof(struct procdata));
213 /* processes can't go into vc context on vc 0 til they unset this. This is
214 * for processes that block before initing uthread code (like rtld). */
215 atomic_set(&p->procdata->vcore_preempt_data[0].flags, VC_SCP_NOVCCTX);
218 /* Allocates and initializes a process, with the given parent. Currently
219 * writes the *p into **pp, and returns 0 on success, < 0 for an error.
221 * - ENOFREEPID if it can't get a PID
222 * - ENOMEM on memory exhaustion */
223 error_t proc_alloc(struct proc **pp, struct proc *parent)
228 if (!(p = kmem_cache_alloc(proc_cache, 0)))
233 /* one reference for the proc existing, and one for the ref we pass back. */
234 kref_init(&p->p_kref, __proc_free, 2);
235 // Setup the default map of where to get cache colors from
236 p->cache_colors_map = global_cache_colors_map;
237 p->next_cache_color = 0;
238 /* Initialize the address space */
239 if ((r = env_setup_vm(p)) < 0) {
240 kmem_cache_free(proc_cache, p);
243 if (!(p->pid = get_free_pid())) {
244 kmem_cache_free(proc_cache, p);
247 /* Set the basic status variables. */
248 spinlock_init(&p->proc_lock);
249 p->exitcode = 1337; /* so we can see processes killed by the kernel */
250 init_sem(&p->state_change, 0);
251 p->ppid = parent ? parent->pid : 0;
252 p->state = PROC_CREATED; /* shouldn't go through state machine for init */
254 p->env_entry = 0; // cheating. this really gets set later
255 p->heap_top = (void*)UTEXT; /* heap_bottom set in proc_init_procinfo */
256 memset(&p->env_ancillary_state, 0, sizeof(p->env_ancillary_state));
257 memset(&p->env_tf, 0, sizeof(p->env_tf));
258 spinlock_init(&p->mm_lock);
259 TAILQ_INIT(&p->vm_regions); /* could init this in the slab */
260 /* Initialize the vcore lists, we'll build the inactive list so that it includes
261 * all vcores when we initialize procinfo. Do this before initing procinfo. */
262 TAILQ_INIT(&p->online_vcs);
263 TAILQ_INIT(&p->bulk_preempted_vcs);
264 TAILQ_INIT(&p->inactive_vcs);
265 /* Init procinfo/procdata. Procinfo's argp/argb are 0'd */
266 proc_init_procinfo(p);
267 proc_init_procdata(p);
269 /* Initialize the generic sysevent ring buffer */
270 SHARED_RING_INIT(&p->procdata->syseventring);
271 /* Initialize the frontend of the sysevent ring buffer */
272 FRONT_RING_INIT(&p->syseventfrontring,
273 &p->procdata->syseventring,
276 /* Init FS structures TODO: cleanup (might pull this out) */
277 kref_get(&default_ns.kref, 1);
279 spinlock_init(&p->fs_env.lock);
280 p->fs_env.umask = parent ? parent->fs_env.umask : S_IWGRP | S_IWOTH;
281 p->fs_env.root = p->ns->root->mnt_root;
282 kref_get(&p->fs_env.root->d_kref, 1);
283 p->fs_env.pwd = parent ? parent->fs_env.pwd : p->fs_env.root;
284 kref_get(&p->fs_env.pwd->d_kref, 1);
285 memset(&p->open_files, 0, sizeof(p->open_files)); /* slightly ghetto */
286 spinlock_init(&p->open_files.lock);
287 p->open_files.max_files = NR_OPEN_FILES_DEFAULT;
288 p->open_files.max_fdset = NR_FILE_DESC_DEFAULT;
289 p->open_files.fd = p->open_files.fd_array;
290 p->open_files.open_fds = (struct fd_set*)&p->open_files.open_fds_init;
291 /* Init the ucq hash lock */
292 p->ucq_hashlock = (struct hashlock*)&p->ucq_hl_noref;
293 hashlock_init(p->ucq_hashlock, HASHLOCK_DEFAULT_SZ);
295 atomic_inc(&num_envs);
296 frontend_proc_init(p);
297 printd("[%08x] new process %08x\n", current ? current->pid : 0, p->pid);
303 /* We have a bunch of different ways to make processes. Call this once the
304 * process is ready to be used by the rest of the system. For now, this just
305 * means when it is ready to be named via the pidhash. In the future, we might
306 * push setting the state to CREATED into here. */
307 void __proc_ready(struct proc *p)
309 spin_lock(&pid_hash_lock);
310 hashtable_insert(pid_hash, (void*)(long)p->pid, p);
311 spin_unlock(&pid_hash_lock);
314 /* Creates a process from the specified file, argvs, and envps. Tempted to get
315 * rid of proc_alloc's style, but it is so quaint... */
316 struct proc *proc_create(struct file *prog, char **argv, char **envp)
320 if ((r = proc_alloc(&p, current)) < 0)
321 panic("proc_create: %e", r); /* one of 3 quaint usages of %e */
322 procinfo_pack_args(p->procinfo, argv, envp);
323 assert(load_elf(p, prog) == 0);
324 /* Connect to stdin, stdout, stderr */
325 assert(insert_file(&p->open_files, dev_stdin, 0) == 0);
326 assert(insert_file(&p->open_files, dev_stdout, 0) == 1);
327 assert(insert_file(&p->open_files, dev_stderr, 0) == 2);
332 /* This is called by kref_put(), once the last reference to the process is
333 * gone. Don't call this otherwise (it will panic). It will clean up the
334 * address space and deallocate any other used memory. */
335 static void __proc_free(struct kref *kref)
337 struct proc *p = container_of(kref, struct proc, p_kref);
340 printd("[PID %d] freeing proc: %d\n", current ? current->pid : 0, p->pid);
341 // All parts of the kernel should have decref'd before __proc_free is called
342 assert(kref_refcnt(&p->p_kref) == 0);
344 kref_put(&p->fs_env.root->d_kref);
345 kref_put(&p->fs_env.pwd->d_kref);
347 frontend_proc_free(p); /* TODO: please remove me one day */
348 /* Free any colors allocated to this process */
349 if (p->cache_colors_map != global_cache_colors_map) {
350 for(int i = 0; i < llc_cache->num_colors; i++)
351 cache_color_free(llc_cache, p->cache_colors_map);
352 cache_colors_map_free(p->cache_colors_map);
354 /* Remove us from the pid_hash and give our PID back (in that order). */
355 spin_lock(&pid_hash_lock);
356 if (!hashtable_remove(pid_hash, (void*)(long)p->pid))
357 panic("Proc not in the pid table in %s", __FUNCTION__);
358 spin_unlock(&pid_hash_lock);
359 put_free_pid(p->pid);
360 /* Flush all mapped pages in the user portion of the address space */
361 env_user_mem_free(p, 0, UVPT);
362 /* These need to be free again, since they were allocated with a refcnt. */
363 free_cont_pages(p->procinfo, LOG2_UP(PROCINFO_NUM_PAGES));
364 free_cont_pages(p->procdata, LOG2_UP(PROCDATA_NUM_PAGES));
366 env_pagetable_free(p);
370 atomic_dec(&num_envs);
372 /* Dealloc the struct proc */
373 kmem_cache_free(proc_cache, p);
376 /* Whether or not actor can control target. Note we currently don't need
377 * locking for this. TODO: think about that, esp wrt proc's dying. */
378 bool proc_controls(struct proc *actor, struct proc *target)
380 return ((actor == target) || (target->ppid == actor->pid));
383 /* Helper to incref by val. Using the helper to help debug/interpose on proc
384 * ref counting. Note that pid2proc doesn't use this interface. */
385 void proc_incref(struct proc *p, unsigned int val)
387 kref_get(&p->p_kref, val);
390 /* Helper to decref for debugging. Don't directly kref_put() for now. */
391 void proc_decref(struct proc *p)
393 kref_put(&p->p_kref);
396 /* Helper, makes p the 'current' process, dropping the old current/cr3. This no
397 * longer assumes the passed in reference already counted 'current'. It will
398 * incref internally when needed. */
399 static void __set_proc_current(struct proc *p)
401 /* We use the pcpui to access 'current' to cut down on the core_id() calls,
402 * though who know how expensive/painful they are. */
403 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
404 /* If the process wasn't here, then we need to load its address space. */
405 if (p != pcpui->cur_proc) {
408 /* This is "leaving the process context" of the previous proc. The
409 * previous lcr3 unloaded the previous proc's context. This should
410 * rarely happen, since we usually proactively leave process context,
411 * but this is the fallback. */
413 proc_decref(pcpui->cur_proc);
418 /* Flag says if vcore context is not ready, which is set in init_procdata. The
419 * process must turn off this flag on vcore0 at some point. It's off by default
420 * on all other vcores. */
421 static bool scp_is_vcctx_ready(struct preempt_data *vcpd)
423 return !(atomic_read(&vcpd->flags) & VC_SCP_NOVCCTX);
426 /* Dispatches a _S process to run on the current core. This should never be
427 * called to "restart" a core.
429 * This will always return, regardless of whether or not the calling core is
430 * being given to a process. (it used to pop the tf directly, before we had
433 * Since it always returns, it will never "eat" your reference (old
434 * documentation talks about this a bit). */
435 void proc_run_s(struct proc *p)
438 uint32_t coreid = core_id();
439 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
440 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
441 spin_lock(&p->proc_lock);
444 spin_unlock(&p->proc_lock);
445 printk("[kernel] _S %d not starting due to async death\n", p->pid);
447 case (PROC_RUNNABLE_S):
448 __proc_set_state(p, PROC_RUNNING_S);
449 /* We will want to know where this process is running, even if it is
450 * only in RUNNING_S. can use the vcoremap, which makes death easy.
451 * Also, this is the signal used in trap.c to know to save the tf in
453 __seq_start_write(&p->procinfo->coremap_seqctr);
454 p->procinfo->num_vcores = 0; /* TODO (VC#) */
455 /* TODO: For now, we won't count this as an active vcore (on the
456 * lists). This gets unmapped in resource.c and yield_s, and needs
458 __map_vcore(p, 0, coreid); /* not treated like a true vcore */
459 __seq_end_write(&p->procinfo->coremap_seqctr);
460 /* incref, since we're saving a reference in owning proc later */
462 /* disable interrupts to protect cur_tf, owning_proc, and current */
463 disable_irqsave(&state);
464 /* wait til ints are disabled before unlocking, in case someone else
465 * grabs the lock and IPIs us before we get set up in cur_tf */
466 spin_unlock(&p->proc_lock);
467 /* redundant with proc_startcore, might be able to remove that one*/
468 __set_proc_current(p);
469 /* set us up as owning_proc. ksched bug if there is already one,
470 * for now. can simply clear_owning if we want to. */
471 assert(!pcpui->owning_proc);
472 pcpui->owning_proc = p;
473 /* TODO: (HSS) set silly state here (__startcore does it instantly) */
474 /* similar to the old __startcore, start them in vcore context if
475 * they have notifs and aren't already in vcore context. o/w, start
476 * them wherever they were before (could be either vc ctx or not) */
477 if (!vcpd->notif_disabled && vcpd->notif_pending
478 && scp_is_vcctx_ready(vcpd)) {
479 vcpd->notif_disabled = TRUE;
480 /* save the _S's tf in the notify slot, build and pop a new one
481 * in actual/cur_tf. */
482 vcpd->notif_tf = p->env_tf;
483 pcpui->cur_tf = &pcpui->actual_tf;
484 memset(pcpui->cur_tf, 0, sizeof(struct trapframe));
485 proc_init_trapframe(pcpui->cur_tf, 0, p->env_entry,
486 vcpd->transition_stack);
488 /* If they have no transition stack, then they can't receive
489 * events. The most they are getting is a wakeup from the
490 * kernel. They won't even turn off notif_pending, so we'll do
492 if (!scp_is_vcctx_ready(vcpd))
493 vcpd->notif_pending = FALSE;
494 /* this is one of the few times cur_tf != &actual_tf */
495 pcpui->cur_tf = &p->env_tf;
497 enable_irqsave(&state);
498 /* When the calling core idles, it'll call restartcore and run the
499 * _S process's context. */
502 spin_unlock(&p->proc_lock);
503 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
507 /* Helper: sends preempt messages to all vcores on the bulk preempt list, and
508 * moves them to the inactive list. */
509 static void __send_bulkp_events(struct proc *p)
511 struct vcore *vc_i, *vc_temp;
512 struct event_msg preempt_msg = {0};
513 /* Send preempt messages for any left on the BP list. No need to set any
514 * flags, it all was done on the real preempt. Now we're just telling the
515 * process about any that didn't get restarted and are still preempted. */
516 TAILQ_FOREACH_SAFE(vc_i, &p->bulk_preempted_vcs, list, vc_temp) {
517 /* Note that if there are no active vcores, send_k_e will post to our
518 * own vcore, the last of which will be put on the inactive list and be
519 * the first to be started. We could have issues with deadlocking,
520 * since send_k_e() could grab the proclock (if there are no active
522 preempt_msg.ev_type = EV_VCORE_PREEMPT;
523 preempt_msg.ev_arg2 = vcore2vcoreid(p, vc_i); /* arg2 is 32 bits */
524 send_kernel_event(p, &preempt_msg, 0);
525 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that.
526 * We need a loop for the messages, but not necessarily for the list
528 TAILQ_REMOVE(&p->bulk_preempted_vcs, vc_i, list);
529 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
533 /* Run an _M. Can be called safely on one that is already running. Hold the
534 * lock before calling. Other than state checks, this just starts up the _M's
535 * vcores, much like the second part of give_cores_running. More specifically,
536 * give_cores_runnable puts cores on the online list, which this then sends
537 * messages to. give_cores_running immediately puts them on the list and sends
538 * the message. the two-step style may go out of fashion soon.
540 * This expects that the "instructions" for which core(s) to run this on will be
541 * in the vcoremap, which needs to be set externally (give_cores()). */
542 void __proc_run_m(struct proc *p)
548 warn("ksched tried to run proc %d in state %s\n", p->pid,
549 procstate2str(p->state));
551 case (PROC_RUNNABLE_M):
552 /* vcoremap[i] holds the coreid of the physical core allocated to
553 * this process. It is set outside proc_run. For the kernel
554 * message, a0 = struct proc*, a1 = struct trapframe*. */
555 if (p->procinfo->num_vcores) {
556 __send_bulkp_events(p);
557 __proc_set_state(p, PROC_RUNNING_M);
558 /* Up the refcnt, to avoid the n refcnt upping on the
559 * destination cores. Keep in sync with __startcore */
560 proc_incref(p, p->procinfo->num_vcores * 2);
561 /* Send kernel messages to all online vcores (which were added
562 * to the list and mapped in __proc_give_cores()), making them
564 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
565 send_kernel_message(vc_i->pcoreid, __startcore, (long)p,
566 0, 0, KMSG_IMMEDIATE);
569 warn("Tried to proc_run() an _M with no vcores!");
571 /* There a subtle race avoidance here (when we unlock after sending
572 * the message). __proc_startcore can handle a death message, but
573 * we can't have the startcore come after the death message.
574 * Otherwise, it would look like a new process. So we hold the lock
575 * til after we send our message, which prevents a possible death
577 * - Note there is no guarantee this core's interrupts were on, so
578 * it may not get the message for a while... */
580 case (PROC_RUNNING_M):
583 /* unlock just so the monitor can call something that might lock*/
584 spin_unlock(&p->proc_lock);
585 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
589 /* Actually runs the given context (trapframe) of process p on the core this
590 * code executes on. This is called directly by __startcore, which needs to
591 * bypass the routine_kmsg check. Interrupts should be off when you call this.
593 * A note on refcnting: this function will not return, and your proc reference
594 * will end up stored in current. This will make no changes to p's refcnt, so
595 * do your accounting such that there is only the +1 for current. This means if
596 * it is already in current (like in the trap return path), don't up it. If
597 * it's already in current and you have another reference (like pid2proc or from
598 * an IPI), then down it (which is what happens in __startcore()). If it's not
599 * in current and you have one reference, like proc_run(non_current_p), then
600 * also do nothing. The refcnt for your *p will count for the reference stored
602 static void __proc_startcore(struct proc *p, trapframe_t *tf)
604 assert(!irq_is_enabled());
605 __set_proc_current(p);
606 /* need to load our silly state, preferably somewhere other than here so we
607 * can avoid the case where the context was just running here. it's not
608 * sufficient to do it in the "new process" if-block above (could be things
609 * like page faults that cause us to keep the same process, but want a
611 * for now, we load this silly state here. (TODO) (HSS)
612 * We also need this to be per trapframe, and not per process...
613 * For now / OSDI, only load it when in _S mode. _M mode was handled in
615 if (p->state == PROC_RUNNING_S)
616 env_pop_ancillary_state(p);
617 /* Clear the current_tf, since it is no longer used */
618 current_tf = 0; /* TODO: might not need this... */
622 /* Restarts/runs the current_tf, which must be for the current process, on the
623 * core this code executes on. Calls an internal function to do the work.
625 * In case there are pending routine messages, like __death, __preempt, or
626 * __notify, we need to run them. Alternatively, if there are any, we could
627 * self_ipi, and run the messages immediately after popping back to userspace,
628 * but that would have crappy overhead.
630 * Refcnting: this will not return, and it assumes that you've accounted for
631 * your reference as if it was the ref for "current" (which is what happens when
632 * returning from local traps and such. */
633 void proc_restartcore(void)
635 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
636 assert(!pcpui->cur_sysc);
637 /* Try and get any interrupts before we pop back to userspace. If we didn't
638 * do this, we'd just get them in userspace, but this might save us some
639 * effort/overhead. */
641 /* Need ints disabled when we return from processing (race on missing
644 process_routine_kmsg(pcpui->cur_tf);
645 /* If there is no owning process, just idle, since we don't know what to do.
646 * This could be because the process had been restarted a long time ago and
647 * has since left the core, or due to a KMSG like __preempt or __death. */
648 if (!pcpui->owning_proc) {
652 assert(pcpui->cur_tf);
653 __proc_startcore(pcpui->owning_proc, pcpui->cur_tf);
657 * Destroys the given process. This may be called from another process, a light
658 * kernel thread (no real process context), asynchronously/cross-core, or from
659 * the process on its own core.
661 * Here's the way process death works:
662 * 0. grab the lock (protects state transition and core map)
663 * 1. set state to dying. that keeps the kernel from doing anything for the
664 * process (like proc_running it).
665 * 2. figure out where the process is running (cross-core/async or RUNNING_M)
666 * 3. IPI to clean up those cores (decref, etc).
668 * 5. Clean up your core, if applicable
669 * (Last core/kernel thread to decref cleans up and deallocates resources.)
671 * Note that some cores can be processing async calls, but will eventually
672 * decref. Should think about this more, like some sort of callback/revocation.
674 * This function will now always return (it used to not return if the calling
675 * core was dying). However, when it returns, a kernel message will eventually
676 * come in, making you abandon_core, as if you weren't running. It may be that
677 * the only reference to p is the one you passed in, and when you decref, it'll
678 * get __proc_free()d. */
679 void proc_destroy(struct proc *p)
681 uint32_t num_revoked = 0;
682 struct kthread *sleeper;
683 spin_lock(&p->proc_lock);
684 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
685 uint32_t pc_arr[p->procinfo->num_vcores];
687 case PROC_DYING: // someone else killed this already.
688 spin_unlock(&p->proc_lock);
690 case PROC_RUNNABLE_M:
691 /* Need to reclaim any cores this proc might have, even though it's
692 * not running yet. */
693 num_revoked = __proc_take_allcores(p, pc_arr, FALSE);
695 case PROC_RUNNABLE_S:
696 /* might need to pull from lists, though i'm currently a fan of the
697 * model where external refs notice DYING (if it matters to them)
698 * and decref when they are done. the ksched will notice the proc
699 * is dying and handle it accordingly (which delay the reaping til
700 * the next call to schedule()) */
704 // here's how to do it manually
707 proc_decref(p); /* this decref is for the cr3 */
711 send_kernel_message(get_pcoreid(p, 0), __death, 0, 0, 0,
713 __seq_start_write(&p->procinfo->coremap_seqctr);
714 // TODO: might need to sort num_vcores too later (VC#)
715 /* vcore is unmapped on the receive side */
716 __seq_end_write(&p->procinfo->coremap_seqctr);
717 /* If we ever have RUNNING_S run on non-mgmt cores, we'll need to
718 * tell the ksched about this now-idle core (after unlocking) */
721 /* Send the DEATH message to every core running this process, and
722 * deallocate the cores.
723 * The rule is that the vcoremap is set before proc_run, and reset
724 * within proc_destroy */
725 num_revoked = __proc_take_allcores(p, pc_arr, FALSE);
730 panic("Weird state(%s) in %s()", procstate2str(p->state),
733 __proc_set_state(p, PROC_DYING);
734 /* This prevents processes from accessing their old files while dying, and
735 * will help if these files (or similar objects in the future) hold
736 * references to p (preventing a __proc_free()). */
737 close_all_files(&p->open_files, FALSE);
738 /* This decref is for the process's existence. */
740 /* Signal our state change. Assuming we only have one waiter right now. */
741 sleeper = __up_sem(&p->state_change, TRUE);
743 kthread_runnable(sleeper);
744 /* Unlock. A death IPI should be on its way, either from the RUNNING_S one,
745 * or from proc_take_cores with a __death. in general, interrupts should be
746 * on when you call proc_destroy locally, but currently aren't for all
747 * things (like traphandlers). */
748 spin_unlock(&p->proc_lock);
749 /* Return the cores to the ksched */
751 put_idle_cores(pc_arr, num_revoked);
755 /* Turns *p into an MCP. Needs to be called from a local syscall of a RUNNING_S
756 * process. Currently, this ignores whether or not you are an _M already. You
757 * should hold the lock before calling. */
758 void __proc_change_to_m(struct proc *p)
762 case (PROC_RUNNING_S):
763 /* issue with if we're async or not (need to preempt it)
764 * either of these should trip it. TODO: (ACR) async core req
765 * TODO: relies on vcore0 being the caller (VC#) */
766 if ((current != p) || (get_pcoreid(p, 0) != core_id()))
767 panic("We don't handle async RUNNING_S core requests yet.");
768 /* save the tf so userspace can restart it. Like in __notify,
769 * this assumes a user tf is the same as a kernel tf. We save
770 * it in the preempt slot so that we can also save the silly
772 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
773 disable_irqsave(&state); /* protect cur_tf */
774 /* Note this won't play well with concurrent proc kmsgs, but
775 * since we're _S and locked, we shouldn't have any. */
777 /* Copy uthread0's context to the notif slot */
778 vcpd->notif_tf = *current_tf;
779 clear_owning_proc(core_id()); /* so we don't restart */
780 save_fp_state(&vcpd->preempt_anc);
781 enable_irqsave(&state);
782 /* Userspace needs to not fuck with notif_disabled before
783 * transitioning to _M. */
784 if (vcpd->notif_disabled) {
785 printk("[kernel] user bug: notifs disabled for vcore 0\n");
786 vcpd->notif_disabled = FALSE;
788 /* in the async case, we'll need to remotely stop and bundle
789 * vcore0's TF. this is already done for the sync case (local
791 /* this process no longer runs on its old location (which is
792 * this core, for now, since we don't handle async calls) */
793 __seq_start_write(&p->procinfo->coremap_seqctr);
794 // TODO: (VC#) might need to adjust num_vcores
795 // TODO: (ACR) will need to unmap remotely (receive-side)
796 __unmap_vcore(p, 0); /* VC# keep in sync with proc_run_s */
797 __seq_end_write(&p->procinfo->coremap_seqctr);
798 /* change to runnable_m (it's TF is already saved) */
799 __proc_set_state(p, PROC_RUNNABLE_M);
800 p->procinfo->is_mcp = TRUE;
802 case (PROC_RUNNABLE_S):
803 /* Issues: being on the runnable_list, proc_set_state not liking
804 * it, and not clearly thinking through how this would happen.
805 * Perhaps an async call that gets serviced after you're
807 panic("Not supporting RUNNABLE_S -> RUNNABLE_M yet.\n");
810 warn("Dying, core request coming from %d\n", core_id());
816 /* Old code to turn a RUNNING_M to a RUNNING_S, with the calling context
817 * becoming the new 'thread0'. Don't use this. Caller needs to send in a
818 * pc_arr big enough for all vcores. Will return the number of cores given up
820 uint32_t __proc_change_to_s(struct proc *p, uint32_t *pc_arr)
823 uint32_t num_revoked;
824 printk("[kernel] trying to transition _M -> _S (deprecated)!\n");
825 assert(p->state == PROC_RUNNING_M); // TODO: (ACR) async core req
826 /* save the context, to be restarted in _S mode */
827 disable_irqsave(&state); /* protect cur_tf */
829 p->env_tf = *current_tf;
830 clear_owning_proc(core_id()); /* so we don't restart */
831 enable_irqsave(&state);
832 env_push_ancillary_state(p); // TODO: (HSS)
833 /* sending death, since it's not our job to save contexts or anything in
835 num_revoked = __proc_take_allcores(p, pc_arr, FALSE);
836 __proc_set_state(p, PROC_RUNNABLE_S);
840 /* Helper function. Is the given pcore a mapped vcore? No locking involved, be
842 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid)
844 return p->procinfo->pcoremap[pcoreid].valid;
847 /* Helper function. Find the vcoreid for a given physical core id for proc p.
848 * No locking involved, be careful. Panics on failure. */
849 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid)
851 assert(is_mapped_vcore(p, pcoreid));
852 return p->procinfo->pcoremap[pcoreid].vcoreid;
855 /* Helper function. Try to find the pcoreid for a given virtual core id for
856 * proc p. No locking involved, be careful. Use this when you can tolerate a
857 * stale or otherwise 'wrong' answer. */
858 static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid)
860 return p->procinfo->vcoremap[vcoreid].pcoreid;
863 /* Helper function. Find the pcoreid for a given virtual core id for proc p.
864 * No locking involved, be careful. Panics on failure. */
865 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid)
867 assert(vcore_is_mapped(p, vcoreid));
868 return try_get_pcoreid(p, vcoreid);
871 /* Helper: saves the SCP's tf state and unmaps vcore 0. In the future, we'll
872 * probably use vc0's space for env_tf and the silly state. */
873 static void __proc_save_context_s(struct proc *p, struct trapframe *tf)
876 env_push_ancillary_state(p); /* TODO: (HSS) */
877 __unmap_vcore(p, 0); /* VC# keep in sync with proc_run_s */
880 /* Helper function: yields / wraps up current_tf */
881 void __proc_yield_s(struct proc *p, struct trapframe *tf)
883 assert(p->state == PROC_RUNNING_S);
884 __proc_set_state(p, PROC_RUNNABLE_S);
885 __proc_save_context_s(p, tf);
889 /* Yields the calling core. Must be called locally (not async) for now.
890 * - If RUNNING_S, you just give up your time slice and will eventually return,
891 * possibly after WAITING on an event.
892 * - If RUNNING_M, you give up the current vcore (which never returns), and
893 * adjust the amount of cores wanted/granted.
894 * - If you have only one vcore, you switch to WAITING. There's no 'classic
895 * yield' for MCPs (at least not now). When you run again, you'll have one
896 * guaranteed core, starting from the entry point.
898 * If the call is being nice, it means different things for SCPs and MCPs. For
899 * MCPs, it means that it is in response to a preemption (which needs to be
900 * checked). If there is no preemption pending, just return. For SCPs, it
901 * means the proc wants to give up the core, but still has work to do. If not,
902 * the proc is trying to wait on an event. It's not being nice to others, it
903 * just has no work to do.
905 * This usually does not return (smp_idle()), so it will eat your reference.
906 * Also note that it needs a non-current/edible reference, since it will abandon
907 * and continue to use the *p (current == 0, no cr3, etc).
909 * We disable interrupts for most of it too, since we need to protect current_tf
910 * and not race with __notify (which doesn't play well with concurrent
912 void proc_yield(struct proc *SAFE p, bool being_nice)
914 uint32_t vcoreid, pcoreid = core_id();
916 struct preempt_data *vcpd;
918 /* Need to disable before even reading vcoreid, since we could be unmapped
919 * by a __preempt or __death. _S also needs ints disabled, so we'll just do
921 disable_irqsave(&state);
922 /* Need to lock before checking the vcoremap to find out who we are, in case
923 * we're getting __preempted and __startcored, from a remote core (in which
924 * case we might have come in thinking we were vcore X, but had X preempted
925 * and Y restarted on this pcore, and we suddenly are the wrong vcore
926 * yielding). Arguably, this is incredibly rare, since you'd need to
927 * preempt the core, then decide to give it back with another grant in
929 spin_lock(&p->proc_lock); /* horrible scalability. =( */
931 case (PROC_RUNNING_S):
933 /* waiting for an event to unblock us */
934 vcpd = &p->procdata->vcore_preempt_data[0];
935 /* this check is an early optimization (check, signal, check
936 * again pattern). We could also lock before spamming the
937 * vcore in event.c */
938 if (vcpd->notif_pending) {
939 /* they can't handle events, just need to prevent a yield.
940 * (note the notif_pendings are collapsed). */
941 if (!scp_is_vcctx_ready(vcpd))
942 vcpd->notif_pending = FALSE;
945 /* syncing with event's SCP code. we set waiting, then check
946 * pending. they set pending, then check waiting. it's not
947 * possible for us to miss the notif *and* for them to miss
948 * WAITING. one (or both) of us will see and make sure the proc
950 __proc_set_state(p, PROC_WAITING);
951 wrmb(); /* don't let the state write pass the notif read */
952 if (vcpd->notif_pending) {
953 __proc_set_state(p, PROC_RUNNING_S);
954 if (!scp_is_vcctx_ready(vcpd))
955 vcpd->notif_pending = FALSE;
958 /* if we're here, we want to sleep. a concurrent event that
959 * hasn't already written notif_pending will have seen WAITING,
960 * and will be spinning while we do this. */
961 __proc_save_context_s(p, current_tf);
963 /* yielding to allow other processes to run */
964 __proc_yield_s(p, current_tf);
966 spin_unlock(&p->proc_lock); /* note that irqs are not enabled yet */
968 case (PROC_RUNNING_M):
969 break; /* will handle this stuff below */
970 case (PROC_DYING): /* incoming __death */
971 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
974 panic("Weird state(%s) in %s()", procstate2str(p->state),
977 /* If we're already unmapped (__preempt or a __death hit us), bail out.
978 * Note that if a __death hit us, we should have bailed when we saw
980 if (!is_mapped_vcore(p, pcoreid))
982 vcoreid = get_vcoreid(p, pcoreid);
983 vc = vcoreid2vcore(p, vcoreid);
984 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
985 /* no reason to be nice, return */
986 if (being_nice && !vc->preempt_pending)
988 /* Fate is sealed, return and take the preempt message when we enable_irqs.
989 * Note this keeps us from mucking with our lists, since we were already
990 * removed from the online_list. We have a similar concern with __death,
991 * but we check for DYING to handle that. */
992 if (vc->preempt_served)
994 /* At this point, AFAIK there should be no preempt/death messages on the
995 * way, and we're on the online list. So we'll go ahead and do the yielding
997 /* no need to preempt later, since we are yielding (nice or otherwise) */
998 if (vc->preempt_pending)
999 vc->preempt_pending = 0;
1000 /* Don't let them yield if they are missing a notification. Userspace must
1001 * not leave vcore context without dealing with notif_pending. pop_ros_tf()
1002 * handles leaving via uthread context. This handles leaving via a yield.
1004 * This early check is an optimization. The real check is below when it
1005 * works with the online_vcs list (syncing with event.c and INDIR/IPI
1007 if (vcpd->notif_pending)
1009 /* Optional: check to see if we are putting them below amt_wanted (help with
1010 * correctness-benign user races) and bail */
1011 if (p->procdata->res_req[RES_CORES].amt_wanted >= p->procinfo->num_vcores)
1013 /* Now we'll actually try to yield */
1014 printd("[K] Process %d (%p) is yielding on vcore %d\n", p->pid, p,
1015 get_vcoreid(p, coreid));
1016 /* Remove from the online list, add to the yielded list, and unmap
1017 * the vcore, which gives up the core. */
1018 TAILQ_REMOVE(&p->online_vcs, vc, list);
1019 /* Now that we're off the online list, check to see if an alert made
1020 * it through (event.c sets this) */
1021 wrmb(); /* prev write must hit before reading notif_pending */
1022 /* Note we need interrupts disabled, since a __notify can come in
1023 * and set pending to FALSE */
1024 if (vcpd->notif_pending) {
1025 /* We lost, put it back on the list and abort the yield */
1026 TAILQ_INSERT_TAIL(&p->online_vcs, vc, list); /* could go HEAD */
1029 /* We won the race with event sending, we can safely yield */
1030 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1031 /* Note this protects stuff userspace should look at, which doesn't
1032 * include the TAILQs. */
1033 __seq_start_write(&p->procinfo->coremap_seqctr);
1034 /* Next time the vcore starts, it starts fresh */
1035 vcpd->notif_disabled = FALSE;
1036 __unmap_vcore(p, vcoreid);
1037 p->procinfo->num_vcores--;
1038 p->procinfo->res_grant[RES_CORES] = p->procinfo->num_vcores;
1039 __seq_end_write(&p->procinfo->coremap_seqctr);
1040 /* No more vcores? Then we wait on an event */
1041 if (p->procinfo->num_vcores == 0) {
1042 /* consider a ksched op to tell it about us WAITING */
1043 __proc_set_state(p, PROC_WAITING);
1045 spin_unlock(&p->proc_lock);
1046 /* Hand the now-idle core to the ksched */
1047 put_idle_core(pcoreid);
1048 goto out_yield_core;
1050 /* for some reason we just want to return, either to take a KMSG that cleans
1051 * us up, or because we shouldn't yield (ex: notif_pending). */
1052 spin_unlock(&p->proc_lock);
1053 enable_irqsave(&state);
1055 out_yield_core: /* successfully yielded the core */
1056 proc_decref(p); /* need to eat the ref passed in */
1057 /* Clean up the core and idle. Need to do this before enabling interrupts,
1058 * since once we put_idle_core() and unlock, we could get a startcore. */
1059 clear_owning_proc(pcoreid); /* so we don't restart */
1061 smp_idle(); /* will reenable interrupts */
1064 /* Sends a notification (aka active notification, aka IPI) to p's vcore. We
1065 * only send a notification if one they are enabled. There's a bunch of weird
1066 * cases with this, and how pending / enabled are signals between the user and
1067 * kernel - check the documentation. Note that pending is more about messages.
1068 * The process needs to be in vcore_context, and the reason is usually a
1069 * message. We set pending here in case we were called to prod them into vcore
1070 * context (like via a sys_self_notify). Also note that this works for _S
1071 * procs, if you send to vcore 0 (and the proc is running). */
1072 void proc_notify(struct proc *p, uint32_t vcoreid)
1074 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1075 vcpd->notif_pending = TRUE;
1076 wrmb(); /* must write notif_pending before reading notif_disabled */
1077 if (!vcpd->notif_disabled) {
1078 /* GIANT WARNING: we aren't using the proc-lock to protect the
1079 * vcoremap. We want to be able to use this from interrupt context,
1080 * and don't want the proc_lock to be an irqsave. Spurious
1081 * __notify() kmsgs are okay (it checks to see if the right receiver
1083 if (vcore_is_mapped(p, vcoreid)) {
1084 printd("[kernel] sending notif to vcore %d\n", vcoreid);
1085 /* This use of try_get_pcoreid is racy, might be unmapped */
1086 send_kernel_message(try_get_pcoreid(p, vcoreid), __notify, (long)p,
1087 0, 0, KMSG_IMMEDIATE);
1092 /* Hold the lock before calling this. If the process is WAITING, it will wake
1093 * it up and schedule it. */
1094 void __proc_wakeup(struct proc *p)
1096 if (p->state != PROC_WAITING)
1098 if (__proc_is_mcp(p)) {
1099 /* Need to make sure they want at least 1 vcore, so the ksched gives
1100 * them something. Might do this via short handler later. */
1101 if (!p->procdata->res_req[RES_CORES].amt_wanted)
1102 p->procdata->res_req[RES_CORES].amt_wanted = 1;
1103 __proc_set_state(p, PROC_RUNNABLE_M);
1105 printd("[kernel] FYI, waking up an _S proc\n"); /* thanks, past brho! */
1106 __proc_set_state(p, PROC_RUNNABLE_S);
1111 /* Is the process in multi_mode / is an MCP or not? */
1112 bool __proc_is_mcp(struct proc *p)
1114 /* in lieu of using the amount of cores requested, or having a bunch of
1115 * states (like PROC_WAITING_M and _S), I'll just track it with a bool. */
1116 return p->procinfo->is_mcp;
1119 /************************ Preemption Functions ******************************
1120 * Don't rely on these much - I'll be sure to change them up a bit.
1122 * Careful about what takes a vcoreid and what takes a pcoreid. Also, there may
1123 * be weird glitches with setting the state to RUNNABLE_M. It is somewhat in
1124 * flux. The num_vcores is changed after take_cores, but some of the messages
1125 * (or local traps) may not yet be ready to handle seeing their future state.
1126 * But they should be, so fix those when they pop up.
1128 * Another thing to do would be to make the _core functions take a pcorelist,
1129 * and not just one pcoreid. */
1131 /* Sets a preempt_pending warning for p's vcore, to go off 'when'. If you care
1132 * about locking, do it before calling. Takes a vcoreid! */
1133 void __proc_preempt_warn(struct proc *p, uint32_t vcoreid, uint64_t when)
1135 struct event_msg local_msg = {0};
1136 /* danger with doing this unlocked: preempt_pending is set, but never 0'd,
1137 * since it is unmapped and not dealt with (TODO)*/
1138 p->procinfo->vcoremap[vcoreid].preempt_pending = when;
1140 /* Send the event (which internally checks to see how they want it) */
1141 local_msg.ev_type = EV_PREEMPT_PENDING;
1142 local_msg.ev_arg1 = vcoreid;
1143 send_kernel_event(p, &local_msg, vcoreid);
1145 /* TODO: consider putting in some lookup place for the alarm to find it.
1146 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1149 /* Warns all active vcores of an impending preemption. Hold the lock if you
1150 * care about the mapping (and you should). */
1151 void __proc_preempt_warnall(struct proc *p, uint64_t when)
1154 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1155 __proc_preempt_warn(p, vcore2vcoreid(p, vc_i), when);
1156 /* TODO: consider putting in some lookup place for the alarm to find it.
1157 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1160 // TODO: function to set an alarm, if none is outstanding
1162 /* Raw function to preempt a single core. If you care about locking, do it
1163 * before calling. */
1164 void __proc_preempt_core(struct proc *p, uint32_t pcoreid)
1166 uint32_t vcoreid = get_vcoreid(p, pcoreid);
1167 struct event_msg preempt_msg = {0};
1168 p->procinfo->vcoremap[vcoreid].preempt_served = TRUE;
1169 // expects a pcorelist. assumes pcore is mapped and running_m
1170 __proc_take_corelist(p, &pcoreid, 1, TRUE);
1171 /* Send a message about the preemption. */
1172 preempt_msg.ev_type = EV_VCORE_PREEMPT;
1173 preempt_msg.ev_arg2 = vcoreid;
1174 send_kernel_event(p, &preempt_msg, 0);
1177 /* Raw function to preempt every vcore. If you care about locking, do it before
1179 uint32_t __proc_preempt_all(struct proc *p, uint32_t *pc_arr)
1181 /* instead of doing this, we could just preempt_served all possible vcores,
1182 * and not just the active ones. We would need to sort out a way to deal
1183 * with stale preempt_serveds first. This might be just as fast anyways. */
1185 /* TODO:(BULK) PREEMPT - don't bother with this, set a proc wide flag, or
1186 * just make us RUNNABLE_M. */
1187 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1188 vc_i->preempt_served = TRUE;
1189 return __proc_take_allcores(p, pc_arr, TRUE);
1192 /* Warns and preempts a vcore from p. No delaying / alarming, or anything. The
1193 * warning will be for u usec from now. */
1194 void proc_preempt_core(struct proc *p, uint32_t pcoreid, uint64_t usec)
1196 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1197 bool preempted = FALSE;
1198 /* DYING could be okay */
1199 if (p->state != PROC_RUNNING_M) {
1200 warn("Tried to preempt from a non RUNNING_M proc!");
1203 spin_lock(&p->proc_lock);
1204 /* TODO: this is racy, could be messages in flight that haven't unmapped
1205 * yet, so we need to do something more complicated */
1206 if (is_mapped_vcore(p, pcoreid)) {
1207 __proc_preempt_warn(p, get_vcoreid(p, pcoreid), warn_time);
1208 __proc_preempt_core(p, pcoreid);
1211 warn("Pcore doesn't belong to the process!!");
1213 if (!p->procinfo->num_vcores) {
1214 __proc_set_state(p, PROC_RUNNABLE_M);
1216 spin_unlock(&p->proc_lock);
1218 put_idle_core(pcoreid);
1221 /* Warns and preempts all from p. No delaying / alarming, or anything. The
1222 * warning will be for u usec from now. */
1223 void proc_preempt_all(struct proc *p, uint64_t usec)
1225 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1226 uint32_t num_revoked = 0;
1227 spin_lock(&p->proc_lock);
1228 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
1229 uint32_t pc_arr[p->procinfo->num_vcores];
1230 /* DYING could be okay */
1231 if (p->state != PROC_RUNNING_M) {
1232 warn("Tried to preempt from a non RUNNING_M proc!");
1233 spin_unlock(&p->proc_lock);
1236 __proc_preempt_warnall(p, warn_time);
1237 num_revoked = __proc_preempt_all(p, pc_arr);
1238 assert(!p->procinfo->num_vcores);
1239 __proc_set_state(p, PROC_RUNNABLE_M);
1240 spin_unlock(&p->proc_lock);
1241 /* Return the cores to the ksched */
1243 put_idle_cores(pc_arr, num_revoked);
1246 /* Give the specific pcore to proc p. Lots of assumptions, so don't really use
1247 * this. The proc needs to be _M and prepared for it. the pcore needs to be
1249 void proc_give(struct proc *p, uint32_t pcoreid)
1251 warn("Your idlecoremap is now screwed up"); /* TODO (IDLE) */
1252 spin_lock(&p->proc_lock);
1253 // expects a pcorelist, we give it a list of one
1254 __proc_give_cores(p, &pcoreid, 1);
1255 spin_unlock(&p->proc_lock);
1258 /* Global version of the helper, for sys_get_vcoreid (might phase that syscall
1260 uint32_t proc_get_vcoreid(struct proc *SAFE p, uint32_t pcoreid)
1263 // TODO: the code currently doesn't track the vcoreid properly for _S (VC#)
1264 spin_lock(&p->proc_lock);
1266 case PROC_RUNNING_S:
1267 spin_unlock(&p->proc_lock);
1268 return 0; // TODO: here's the ugly part
1269 case PROC_RUNNING_M:
1270 vcoreid = get_vcoreid(p, pcoreid);
1271 spin_unlock(&p->proc_lock);
1273 case PROC_DYING: // death message is on the way
1274 spin_unlock(&p->proc_lock);
1277 spin_unlock(&p->proc_lock);
1278 panic("Weird state(%s) in %s()", procstate2str(p->state),
1283 /* TODO: make all of these static inlines when we gut the env crap */
1284 bool vcore_is_mapped(struct proc *p, uint32_t vcoreid)
1286 return p->procinfo->vcoremap[vcoreid].valid;
1289 /* Can do this, or just create a new field and save it in the vcoremap */
1290 uint32_t vcore2vcoreid(struct proc *p, struct vcore *vc)
1292 return (vc - p->procinfo->vcoremap);
1295 struct vcore *vcoreid2vcore(struct proc *p, uint32_t vcoreid)
1297 return &p->procinfo->vcoremap[vcoreid];
1300 /********** Core granting (bulk and single) ***********/
1302 /* Helper: gives pcore to the process, mapping it to the next available vcore
1303 * from list vc_list. Returns TRUE if we succeeded (non-empty). */
1304 static bool __proc_give_a_pcore(struct proc *p, uint32_t pcore,
1305 struct vcore_tailq *vc_list)
1307 struct vcore *new_vc;
1308 new_vc = TAILQ_FIRST(vc_list);
1311 printd("setting vcore %d to pcore %d\n", vcore2vcoreid(p, new_vc),
1313 TAILQ_REMOVE(vc_list, new_vc, list);
1314 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1315 __map_vcore(p, vcore2vcoreid(p, new_vc), pcore);
1319 static void __proc_give_cores_runnable(struct proc *p, uint32_t *pc_arr,
1322 assert(p->state == PROC_RUNNABLE_M);
1323 assert(num); /* catch bugs */
1324 /* add new items to the vcoremap */
1325 __seq_start_write(&p->procinfo->coremap_seqctr);/* unncessary if offline */
1326 p->procinfo->num_vcores += num;
1327 for (int i = 0; i < num; i++) {
1328 /* Try from the bulk list first */
1329 if (__proc_give_a_pcore(p, pc_arr[i], &p->bulk_preempted_vcs))
1331 /* o/w, try from the inactive list. at one point, i thought there might
1332 * be a legit way in which the inactive list could be empty, but that i
1333 * wanted to catch it via an assert. */
1334 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs));
1336 __seq_end_write(&p->procinfo->coremap_seqctr);
1339 static void __proc_give_cores_running(struct proc *p, uint32_t *pc_arr,
1342 /* Up the refcnt, since num cores are going to start using this
1343 * process and have it loaded in their owning_proc and 'current'. */
1344 proc_incref(p, num * 2); /* keep in sync with __startcore */
1345 __seq_start_write(&p->procinfo->coremap_seqctr);
1346 p->procinfo->num_vcores += num;
1347 assert(TAILQ_EMPTY(&p->bulk_preempted_vcs));
1348 for (int i = 0; i < num; i++) {
1349 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs));
1350 send_kernel_message(pc_arr[i], __startcore, (long)p, 0, 0,
1353 __seq_end_write(&p->procinfo->coremap_seqctr);
1356 /* Gives process p the additional num cores listed in pcorelist. If the proc is
1357 * not RUNNABLE_M or RUNNING_M, this will fail and allocate none of the core
1358 * (and return -1). If you're RUNNING_M, this will startup your new cores at
1359 * the entry point with their virtual IDs (or restore a preemption). If you're
1360 * RUNNABLE_M, you should call __proc_run_m after this so that the process can
1361 * start to use its cores. In either case, this returns 0.
1363 * If you're *_S, make sure your core0's TF is set (which is done when coming in
1364 * via arch/trap.c and we are RUNNING_S), change your state, then call this.
1365 * Then call __proc_run_m().
1367 * The reason I didn't bring the _S cases from core_request over here is so we
1368 * can keep this family of calls dealing with only *_Ms, to avoiding caring if
1369 * this is called from another core, and to avoid the _S -> _M transition.
1371 * WARNING: You must hold the proc_lock before calling this! */
1372 int __proc_give_cores(struct proc *p, uint32_t *pc_arr, uint32_t num)
1374 /* should never happen: */
1375 assert(num + p->procinfo->num_vcores <= MAX_NUM_CPUS);
1377 case (PROC_RUNNABLE_S):
1378 case (PROC_RUNNING_S):
1379 warn("Don't give cores to a process in a *_S state!\n");
1382 case (PROC_WAITING):
1383 /* can't accept, just fail */
1385 case (PROC_RUNNABLE_M):
1386 __proc_give_cores_runnable(p, pc_arr, num);
1388 case (PROC_RUNNING_M):
1389 __proc_give_cores_running(p, pc_arr, num);
1392 panic("Weird state(%s) in %s()", procstate2str(p->state),
1395 /* TODO: considering moving to the ksched (hard, due to yield) */
1396 p->procinfo->res_grant[RES_CORES] += num;
1400 /********** Core revocation (bulk and single) ***********/
1402 /* Revokes a single vcore from a process (unmaps or sends a KMSG to unmap). */
1403 static void __proc_revoke_core(struct proc *p, uint32_t vcoreid, bool preempt)
1405 uint32_t pcoreid = get_pcoreid(p, vcoreid);
1406 struct preempt_data *vcpd;
1408 /* Lock the vcore's state (necessary for preemption recovery) */
1409 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1410 atomic_or(&vcpd->flags, VC_K_LOCK);
1411 send_kernel_message(pcoreid, __preempt, (long)p, 0, 0, KMSG_IMMEDIATE);
1413 send_kernel_message(pcoreid, __death, 0, 0, 0, KMSG_IMMEDIATE);
1417 /* Revokes all cores from the process (unmaps or sends a KMSGS). */
1418 static void __proc_revoke_allcores(struct proc *p, bool preempt)
1421 /* TODO: if we ever get broadcast messaging, use it here (still need to lock
1422 * the vcores' states for preemption) */
1423 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1424 __proc_revoke_core(p, vcore2vcoreid(p, vc_i), preempt);
1427 /* Might be faster to scan the vcoremap than to walk the list... */
1428 static void __proc_unmap_allcores(struct proc *p)
1431 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1432 __unmap_vcore(p, vcore2vcoreid(p, vc_i));
1435 /* Takes (revoke via kmsg or unmap) from process p the num cores listed in
1436 * pc_arr. Will preempt if 'preempt' is set. o/w, no state will be saved, etc.
1437 * Don't use this for taking all of a process's cores.
1439 * Make sure you hold the lock when you call this, and make sure that the pcore
1440 * actually belongs to the proc, non-trivial due to other __preempt messages. */
1441 void __proc_take_corelist(struct proc *p, uint32_t *pc_arr, uint32_t num,
1446 __seq_start_write(&p->procinfo->coremap_seqctr);
1447 for (int i = 0; i < num; i++) {
1448 vcoreid = get_vcoreid(p, pc_arr[i]);
1450 assert(pc_arr[i] == get_pcoreid(p, vcoreid));
1451 /* Revoke / unmap core */
1452 if (p->state == PROC_RUNNING_M) {
1453 __proc_revoke_core(p, vcoreid, preempt);
1455 assert(p->state == PROC_RUNNABLE_M);
1456 __unmap_vcore(p, vcoreid);
1458 /* Change lists for the vcore. Note, the messages are already in flight
1459 * (or the vcore is already unmapped), if applicable. The only code
1460 * that looks at the lists without holding the lock is event code, and
1461 * it doesn't care if the vcore was unmapped (it handles that) */
1462 vc = vcoreid2vcore(p, vcoreid);
1463 TAILQ_REMOVE(&p->online_vcs, vc, list);
1464 /* even for single preempts, we use the inactive list. bulk preempt is
1465 * only used for when we take everything. */
1466 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1468 p->procinfo->num_vcores -= num;
1469 __seq_end_write(&p->procinfo->coremap_seqctr);
1470 p->procinfo->res_grant[RES_CORES] -= num;
1473 /* Takes all cores from a process (revoke via kmsg or unmap), putting them on
1474 * the appropriate vcore list, and fills pc_arr with the pcores revoked, and
1475 * returns the number of entries in pc_arr.
1477 * Make sure pc_arr is big enough to handle num_vcores().
1478 * Make sure you hold the lock when you call this. */
1479 uint32_t __proc_take_allcores(struct proc *p, uint32_t *pc_arr, bool preempt)
1481 struct vcore *vc_i, *vc_temp;
1483 __seq_start_write(&p->procinfo->coremap_seqctr);
1484 /* Write out which pcores we're going to take */
1485 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1486 pc_arr[num++] = vc_i->pcoreid;
1487 /* Revoke if they are running, o/w unmap. Both of these need the online
1488 * list to not be changed yet. */
1489 if (p->state == PROC_RUNNING_M) {
1490 __proc_revoke_allcores(p, preempt);
1492 assert(p->state == PROC_RUNNABLE_M);
1493 __proc_unmap_allcores(p);
1495 /* Move the vcores from online to the head of the appropriate list */
1496 TAILQ_FOREACH_SAFE(vc_i, &p->online_vcs, list, vc_temp) {
1497 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that */
1498 TAILQ_REMOVE(&p->online_vcs, vc_i, list);
1499 /* Put the cores on the appropriate list */
1501 TAILQ_INSERT_HEAD(&p->bulk_preempted_vcs, vc_i, list);
1503 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
1505 assert(TAILQ_EMPTY(&p->online_vcs));
1506 assert(num == p->procinfo->num_vcores);
1507 p->procinfo->num_vcores = 0;
1508 __seq_end_write(&p->procinfo->coremap_seqctr);
1509 p->procinfo->res_grant[RES_CORES] = 0;
1513 /* Helper to do the vcore->pcore and inverse mapping. Hold the lock when
1515 void __map_vcore(struct proc *p, uint32_t vcoreid, uint32_t pcoreid)
1517 while (p->procinfo->vcoremap[vcoreid].valid)
1519 p->procinfo->vcoremap[vcoreid].pcoreid = pcoreid;
1521 p->procinfo->vcoremap[vcoreid].valid = TRUE;
1522 p->procinfo->pcoremap[pcoreid].vcoreid = vcoreid;
1524 p->procinfo->pcoremap[pcoreid].valid = TRUE;
1527 /* Helper to unmap the vcore->pcore and inverse mapping. Hold the lock when
1529 void __unmap_vcore(struct proc *p, uint32_t vcoreid)
1531 p->procinfo->pcoremap[p->procinfo->vcoremap[vcoreid].pcoreid].valid = FALSE;
1533 p->procinfo->vcoremap[vcoreid].valid = FALSE;
1536 /* Stop running whatever context is on this core and load a known-good cr3.
1537 * Note this leaves no trace of what was running. This "leaves the process's
1538 * context. Also, we want interrupts disabled, to not conflict with kmsgs
1539 * (__launch_kthread, proc mgmt, etc).
1541 * This does not clear the owning proc. Use the other helper for that. */
1542 void abandon_core(void)
1544 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1545 assert(!irq_is_enabled());
1546 /* Syscalls that don't return will ultimately call abadon_core(), so we need
1547 * to make sure we don't think we are still working on a syscall. */
1548 pcpui->cur_sysc = 0;
1549 if (pcpui->cur_proc)
1553 /* Helper to clear the core's owning processor and manage refcnting. Pass in
1554 * core_id() to save a couple core_id() calls. */
1555 void clear_owning_proc(uint32_t coreid)
1557 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1558 struct proc *p = pcpui->owning_proc;
1559 assert(!irq_is_enabled());
1560 pcpui->owning_proc = 0;
1561 pcpui->cur_tf = 0; /* catch bugs for now (will go away soon) */
1566 /* Switches to the address space/context of new_p, doing nothing if we are
1567 * already in new_p. This won't add extra refcnts or anything, and needs to be
1568 * paired with switch_back() at the end of whatever function you are in. Don't
1569 * migrate cores in the middle of a pair. Specifically, the uncounted refs are
1570 * one for the old_proc, which is passed back to the caller, and new_p is
1571 * getting placed in cur_proc. */
1572 struct proc *switch_to(struct proc *new_p)
1574 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1575 struct proc *old_proc;
1576 int8_t irq_state = 0;
1577 disable_irqsave(&irq_state);
1578 old_proc = pcpui->cur_proc; /* uncounted ref */
1579 /* If we aren't the proc already, then switch to it */
1580 if (old_proc != new_p) {
1581 pcpui->cur_proc = new_p; /* uncounted ref */
1582 lcr3(new_p->env_cr3);
1584 enable_irqsave(&irq_state);
1588 /* This switches back to old_proc from new_p. Pair it with switch_to(), and
1589 * pass in its return value for old_proc. */
1590 void switch_back(struct proc *new_p, struct proc *old_proc)
1592 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1593 int8_t irq_state = 0;
1594 if (old_proc != new_p) {
1595 disable_irqsave(&irq_state);
1596 pcpui->cur_proc = old_proc;
1598 lcr3(old_proc->env_cr3);
1601 enable_irqsave(&irq_state);
1605 /* Will send a TLB shootdown message to every vcore in the main address space
1606 * (aka, all vcores for now). The message will take the start and end virtual
1607 * addresses as well, in case we want to be more clever about how much we
1608 * shootdown and batching our messages. Should do the sanity about rounding up
1609 * and down in this function too.
1611 * Would be nice to have a broadcast kmsg at this point. Note this may send a
1612 * message to the calling core (interrupting it, possibly while holding the
1613 * proc_lock). We don't need to process routine messages since it's an
1614 * immediate message. */
1615 void proc_tlbshootdown(struct proc *p, uintptr_t start, uintptr_t end)
1618 /* TODO: we might be able to avoid locking here in the future (we must hit
1619 * all online, and we can check __mapped). it'll be complicated. */
1620 spin_lock(&p->proc_lock);
1622 case (PROC_RUNNING_S):
1625 case (PROC_RUNNING_M):
1626 /* TODO: (TLB) sanity checks and rounding on the ranges */
1627 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
1628 send_kernel_message(vc_i->pcoreid, __tlbshootdown, start, end,
1633 /* if it is dying, death messages are already on the way to all
1634 * cores, including ours, which will clear the TLB. */
1637 /* will probably get this when we have the short handlers */
1638 warn("Unexpected case %s in %s", procstate2str(p->state),
1641 spin_unlock(&p->proc_lock);
1644 /* Helper, used by __startcore and change_to_vcore, which sets up cur_tf to run
1645 * a given process's vcore. Caller needs to set up things like owning_proc and
1646 * whatnot. Note that we might not have p loaded as current. */
1647 static void __set_curtf_to_vcoreid(struct proc *p, uint32_t vcoreid)
1649 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1650 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1652 /* We could let userspace do this, though they come into vcore entry many
1653 * times, and we just need this to happen when the cores comes online the
1654 * first time. That, and they want this turned on as soon as we know a
1655 * vcore *WILL* be online. We could also do this earlier, when we map the
1656 * vcore to its pcore, though we don't always have current loaded or
1657 * otherwise mess with the VCPD in those code paths. */
1658 vcpd->can_rcv_msg = TRUE;
1659 /* Mark that this vcore as no longer preempted. No danger of clobbering
1660 * other writes, since this would get turned on in __preempt (which can't be
1661 * concurrent with this function on this core), and the atomic is just
1662 * toggling the one bit (a concurrent VC_K_LOCK will work) */
1663 atomic_and(&vcpd->flags, ~VC_PREEMPTED);
1664 printd("[kernel] startcore on physical core %d for process %d's vcore %d\n",
1665 core_id(), p->pid, vcoreid);
1666 /* If notifs are disabled, the vcore was in vcore context and we need to
1667 * restart the preempt_tf. o/w, we give them a fresh vcore (which is also
1668 * what happens the first time a vcore comes online). No matter what,
1669 * they'll restart in vcore context. It's just a matter of whether or not
1670 * it is the old, interrupted vcore context. */
1671 if (vcpd->notif_disabled) {
1672 restore_fp_state(&vcpd->preempt_anc);
1673 /* copy-in the tf we'll pop, then set all security-related fields */
1674 pcpui->actual_tf = vcpd->preempt_tf;
1675 proc_secure_trapframe(&pcpui->actual_tf);
1676 } else { /* not restarting from a preemption, use a fresh vcore */
1677 assert(vcpd->transition_stack);
1678 /* TODO: consider 0'ing the FP state. We're probably leaking. */
1679 proc_init_trapframe(&pcpui->actual_tf, vcoreid, p->env_entry,
1680 vcpd->transition_stack);
1681 /* Disable/mask active notifications for fresh vcores */
1682 vcpd->notif_disabled = TRUE;
1684 /* cur_tf was built above (in actual_tf), now use it */
1685 pcpui->cur_tf = &pcpui->actual_tf;
1686 /* this cur_tf will get run when the kernel returns / idles */
1689 /* Changes calling vcore to be vcoreid. enable_my_notif tells us about how the
1690 * state calling vcore wants to be left in. It will look like caller_vcoreid
1691 * was preempted. Note we don't care about notif_pending. */
1692 void proc_change_to_vcore(struct proc *p, uint32_t new_vcoreid,
1693 bool enable_my_notif)
1695 uint32_t caller_vcoreid, pcoreid = core_id();
1696 struct preempt_data *caller_vcpd;
1697 struct vcore *caller_vc, *new_vc;
1698 struct event_msg preempt_msg = {0};
1700 /* Need to disable before even reading caller_vcoreid, since we could be
1701 * unmapped by a __preempt or __death, like in yield. */
1702 disable_irqsave(&state);
1703 /* Need to lock before reading the vcoremap, like in yield */
1704 spin_lock(&p->proc_lock);
1705 /* new_vcoreid is already runing, abort */
1706 if (vcore_is_mapped(p, new_vcoreid))
1708 /* Need to make sure our vcore is allowed to switch. We might have a
1709 * __preempt, __death, etc, coming in. Similar to yield. */
1711 case (PROC_RUNNING_M):
1712 break; /* the only case we can proceed */
1713 case (PROC_RUNNING_S): /* user bug, just return */
1714 case (PROC_DYING): /* incoming __death */
1715 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1718 panic("Weird state(%s) in %s()", procstate2str(p->state),
1721 /* Make sure we're still mapped in the proc. */
1722 if (!is_mapped_vcore(p, pcoreid))
1724 /* Get all our info */
1725 caller_vcoreid = get_vcoreid(p, pcoreid);
1726 caller_vcpd = &p->procdata->vcore_preempt_data[caller_vcoreid];
1727 caller_vc = vcoreid2vcore(p, caller_vcoreid);
1728 /* Should only call from vcore context */
1729 if (!caller_vcpd->notif_disabled) {
1730 printk("[kernel] You tried to change vcores from uthread ctx\n");
1733 /* Return and take the preempt message when we enable_irqs. */
1734 if (caller_vc->preempt_served)
1736 /* Ok, we're clear to do the switch. Lets figure out who the new one is */
1737 new_vc = vcoreid2vcore(p, new_vcoreid);
1738 printd("[kernel] changing vcore %d to vcore %d\n", caller_vcoreid,
1740 /* enable_my_notif signals how we'll be restarted */
1741 if (enable_my_notif) {
1742 /* if they set this flag, then the vcore can just restart from scratch,
1743 * and we don't care about either the notif_tf or the preempt_tf. */
1744 caller_vcpd->notif_disabled = FALSE;
1746 /* need to set up the calling vcore's tf so that it'll get restarted by
1747 * __startcore, to make the caller look like it was preempted. */
1748 caller_vcpd->preempt_tf = *current_tf;
1749 save_fp_state(&caller_vcpd->preempt_anc);
1750 /* Mark our core as preempted (for userspace recovery). */
1751 atomic_or(&caller_vcpd->flags, VC_PREEMPTED);
1753 /* Either way, unmap and offline our current vcore */
1754 /* Move the caller from online to inactive */
1755 TAILQ_REMOVE(&p->online_vcs, caller_vc, list);
1756 /* We don't bother with the notif_pending race. note that notif_pending
1757 * could still be set. this was a preempted vcore, and userspace will need
1758 * to deal with missed messages (preempt_recover() will handle that) */
1759 TAILQ_INSERT_HEAD(&p->inactive_vcs, caller_vc, list);
1760 /* Move the new one from inactive to online */
1761 TAILQ_REMOVE(&p->inactive_vcs, new_vc, list);
1762 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1763 /* Change the vcore map (TODO: might get rid of this seqctr) */
1764 __seq_start_write(&p->procinfo->coremap_seqctr);
1765 __unmap_vcore(p, caller_vcoreid);
1766 __map_vcore(p, new_vcoreid, pcoreid);
1767 __seq_end_write(&p->procinfo->coremap_seqctr);
1768 /* Send either a PREEMPT msg or a CHECK_MSGS msg. If they said to
1769 * enable_my_notif, then all userspace needs is to check messages, not a
1770 * full preemption recovery. */
1771 preempt_msg.ev_type = (enable_my_notif ? EV_CHECK_MSGS : EV_VCORE_PREEMPT);
1772 preempt_msg.ev_arg2 = caller_vcoreid; /* arg2 is 32 bits */
1773 send_kernel_event(p, &preempt_msg, new_vcoreid);
1774 /* Change cur_tf so we'll be the new vcoreid */
1775 __set_curtf_to_vcoreid(p, new_vcoreid);
1776 /* Fall through to exit (we didn't fail) */
1778 spin_unlock(&p->proc_lock);
1779 enable_irqsave(&state);
1782 /* Kernel message handler to start a process's context on this core, when the
1783 * core next considers running a process. Tightly coupled with __proc_run_m().
1784 * Interrupts are disabled. */
1785 void __startcore(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1787 uint32_t vcoreid, coreid = core_id();
1788 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1789 struct proc *p_to_run = (struct proc *CT(1))a0;
1792 /* Can not be any TF from a process here already */
1793 assert(!pcpui->owning_proc);
1794 /* the sender of the amsg increfed already for this saved ref to p_to_run */
1795 pcpui->owning_proc = p_to_run;
1796 /* sender increfed again, assuming we'd install to cur_proc. only do this
1797 * if no one else is there. this is an optimization, since we expect to
1798 * send these __startcores to idles cores, and this saves a scramble to
1799 * incref when all of the cores restartcore/startcore later. Keep in sync
1800 * with __proc_give_cores() and __proc_run_m(). */
1801 if (!pcpui->cur_proc) {
1802 pcpui->cur_proc = p_to_run; /* install the ref to cur_proc */
1803 lcr3(p_to_run->env_cr3); /* load the page tables to match cur_proc */
1805 proc_decref(p_to_run); /* can't install, decref the extra one */
1807 /* Note we are not necessarily in the cr3 of p_to_run */
1808 vcoreid = get_vcoreid(p_to_run, coreid);
1809 /* Now that we sorted refcnts and know p / which vcore it should be, set up
1810 * pcpui->cur_tf so that it will run that particular vcore */
1811 __set_curtf_to_vcoreid(p_to_run, vcoreid);
1814 /* Bail out if it's the wrong process, or if they no longer want a notif. Don't
1815 * use the TF we passed in, we care about cur_tf. Try not to grab locks or
1816 * write access to anything that isn't per-core in here. */
1817 void __notify(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1819 uint32_t vcoreid, coreid = core_id();
1820 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1821 struct preempt_data *vcpd;
1822 struct proc *p = (struct proc*)a0;
1824 /* Not the right proc */
1825 if (p != pcpui->owning_proc)
1827 /* Common cur_tf sanity checks. Note cur_tf could be an _S's env_tf */
1828 assert(pcpui->cur_tf);
1829 assert(!in_kernel(pcpui->cur_tf));
1830 /* We shouldn't need to lock here, since unmapping happens on the pcore and
1831 * mapping would only happen if the vcore was free, which it isn't until
1832 * after we unmap. */
1833 vcoreid = get_vcoreid(p, coreid);
1834 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1835 /* for SCPs that haven't (and might never) call vc_event_init, like rtld.
1836 * this is harmless for MCPS to check this */
1837 if (!scp_is_vcctx_ready(vcpd))
1839 printd("received active notification for proc %d's vcore %d on pcore %d\n",
1840 p->procinfo->pid, vcoreid, coreid);
1841 /* sort signals. notifs are now masked, like an interrupt gate */
1842 if (vcpd->notif_disabled)
1844 vcpd->notif_disabled = TRUE;
1845 /* save the old tf in the notify slot, build and pop a new one. Note that
1846 * silly state isn't our business for a notification. */
1847 vcpd->notif_tf = *pcpui->cur_tf;
1848 memset(pcpui->cur_tf, 0, sizeof(struct trapframe));
1849 proc_init_trapframe(pcpui->cur_tf, vcoreid, p->env_entry,
1850 vcpd->transition_stack);
1851 /* this cur_tf will get run when the kernel returns / idles */
1854 void __preempt(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1856 uint32_t vcoreid, coreid = core_id();
1857 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1858 struct preempt_data *vcpd;
1859 struct proc *p = (struct proc*)a0;
1862 if (p != pcpui->owning_proc) {
1863 panic("__preempt arrived for a process (%p) that was not owning (%p)!",
1864 p, pcpui->owning_proc);
1866 /* Common cur_tf sanity checks */
1867 assert(pcpui->cur_tf);
1868 assert(pcpui->cur_tf == &pcpui->actual_tf);
1869 assert(!in_kernel(pcpui->cur_tf));
1870 /* We shouldn't need to lock here, since unmapping happens on the pcore and
1871 * mapping would only happen if the vcore was free, which it isn't until
1872 * after we unmap. */
1873 vcoreid = get_vcoreid(p, coreid);
1874 p->procinfo->vcoremap[vcoreid].preempt_served = FALSE;
1875 /* either __preempt or proc_yield() ends the preempt phase. */
1876 p->procinfo->vcoremap[vcoreid].preempt_pending = 0;
1877 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1878 printd("[kernel] received __preempt for proc %d's vcore %d on pcore %d\n",
1879 p->procinfo->pid, vcoreid, coreid);
1880 /* if notifs are disabled, the vcore is in vcore context (as far as we're
1881 * concerned), and we save it in the preempt slot. o/w, we save the
1882 * process's cur_tf in the notif slot, and it'll appear to the vcore when it
1883 * comes back up that it just took a notification. */
1884 if (vcpd->notif_disabled)
1885 vcpd->preempt_tf = *pcpui->cur_tf;
1887 vcpd->notif_tf = *pcpui->cur_tf;
1888 /* either way, we save the silly state (FP) */
1889 save_fp_state(&vcpd->preempt_anc);
1890 /* Mark the vcore as preempted and unlock (was locked by the sender). */
1891 atomic_or(&vcpd->flags, VC_PREEMPTED);
1892 atomic_and(&vcpd->flags, ~VC_K_LOCK);
1893 wmb(); /* make sure everything else hits before we unmap */
1894 __unmap_vcore(p, vcoreid);
1895 /* We won't restart the process later. current gets cleared later when we
1896 * notice there is no owning_proc and we have nothing to do (smp_idle,
1897 * restartcore, etc) */
1898 clear_owning_proc(coreid);
1901 /* Kernel message handler to clean up the core when a process is dying.
1902 * Note this leaves no trace of what was running.
1903 * It's okay if death comes to a core that's already idling and has no current.
1904 * It could happen if a process decref'd before __proc_startcore could incref. */
1905 void __death(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1907 uint32_t vcoreid, coreid = core_id();
1908 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1909 struct proc *p = pcpui->owning_proc;
1911 vcoreid = get_vcoreid(p, coreid);
1912 printd("[kernel] death on physical core %d for process %d's vcore %d\n",
1913 coreid, p->pid, vcoreid);
1914 __unmap_vcore(p, vcoreid);
1915 /* We won't restart the process later. current gets cleared later when
1916 * we notice there is no owning_proc and we have nothing to do
1917 * (smp_idle, restartcore, etc) */
1918 clear_owning_proc(coreid);
1922 /* Kernel message handler, usually sent IMMEDIATE, to shoot down virtual
1923 * addresses from a0 to a1. */
1924 void __tlbshootdown(struct trapframe *tf, uint32_t srcid, long a0, long a1,
1927 /* TODO: (TLB) something more intelligent with the range */
1931 void print_allpids(void)
1933 void print_proc_state(void *item)
1935 struct proc *p = (struct proc*)item;
1937 printk("%8d %s\n", p->pid, procstate2str(p->state));
1939 printk("PID STATE \n");
1940 printk("------------------\n");
1941 spin_lock(&pid_hash_lock);
1942 hash_for_each(pid_hash, print_proc_state);
1943 spin_unlock(&pid_hash_lock);
1946 void print_proc_info(pid_t pid)
1949 struct proc *p = pid2proc(pid);
1952 printk("Bad PID.\n");
1955 spinlock_debug(&p->proc_lock);
1956 //spin_lock(&p->proc_lock); // No locking!!
1957 printk("struct proc: %p\n", p);
1958 printk("PID: %d\n", p->pid);
1959 printk("PPID: %d\n", p->ppid);
1960 printk("State: %s (%p)\n", procstate2str(p->state), p->state);
1961 printk("Refcnt: %d\n", atomic_read(&p->p_kref.refcount) - 1);
1962 printk("Flags: 0x%08x\n", p->env_flags);
1963 printk("CR3(phys): 0x%08x\n", p->env_cr3);
1964 printk("Num Vcores: %d\n", p->procinfo->num_vcores);
1965 printk("Vcore Lists (may be in flux w/o locking):\n----------------------\n");
1966 printk("Online:\n");
1967 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1968 printk("\tVcore %d -> Pcore %d\n", vcore2vcoreid(p, vc_i), vc_i->pcoreid);
1969 printk("Bulk Preempted:\n");
1970 TAILQ_FOREACH(vc_i, &p->bulk_preempted_vcs, list)
1971 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
1972 printk("Inactive / Yielded:\n");
1973 TAILQ_FOREACH(vc_i, &p->inactive_vcs, list)
1974 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
1975 printk("Resources:\n------------------------\n");
1976 for (int i = 0; i < MAX_NUM_RESOURCES; i++)
1977 printk("\tRes type: %02d, amt wanted: %08d, amt granted: %08d\n", i,
1978 p->procdata->res_req[i].amt_wanted, p->procinfo->res_grant[i]);
1979 printk("Open Files:\n");
1980 struct files_struct *files = &p->open_files;
1981 spin_lock(&files->lock);
1982 for (int i = 0; i < files->max_files; i++)
1983 if (files->fd_array[i].fd_file) {
1984 printk("\tFD: %02d, File: %08p, File name: %s\n", i,
1985 files->fd_array[i].fd_file,
1986 file_name(files->fd_array[i].fd_file));
1988 spin_unlock(&files->lock);
1989 /* No one cares, and it clutters the terminal */
1990 //printk("Vcore 0's Last Trapframe:\n");
1991 //print_trapframe(&p->env_tf);
1992 /* no locking / unlocking or refcnting */
1993 // spin_unlock(&p->proc_lock);
1997 /* Debugging function, checks what (process, vcore) is supposed to run on this
1998 * pcore. Meant to be called from smp_idle() before halting. */
1999 void check_my_owner(void)
2001 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2002 void shazbot(void *item)
2004 struct proc *p = (struct proc*)item;
2007 spin_lock(&p->proc_lock);
2008 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
2009 /* this isn't true, a __startcore could be on the way and we're
2010 * already "online" */
2011 if (vc_i->pcoreid == core_id()) {
2012 /* Immediate message was sent, we should get it when we enable
2013 * interrupts, which should cause us to skip cpu_halt() */
2014 if (!STAILQ_EMPTY(&pcpui->immed_amsgs))
2016 printk("Owned pcore (%d) has no owner, by %08p, vc %d!\n",
2017 core_id(), p, vcore2vcoreid(p, vc_i));
2018 spin_unlock(&p->proc_lock);
2019 spin_unlock(&pid_hash_lock);
2023 spin_unlock(&p->proc_lock);
2025 assert(!irq_is_enabled());
2027 if (!booting && !pcpui->owning_proc) {
2028 spin_lock(&pid_hash_lock);
2029 hash_for_each(pid_hash, shazbot);
2030 spin_unlock(&pid_hash_lock);