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)))
230 /* zero everything by default, other specific items are set below */
231 memset(p, 0, sizeof(struct proc));
235 /* only one ref, which we pass back. the old 'existence' ref is managed by
237 kref_init(&p->p_kref, __proc_free, 1);
238 // Setup the default map of where to get cache colors from
239 p->cache_colors_map = global_cache_colors_map;
240 p->next_cache_color = 0;
241 /* Initialize the address space */
242 if ((r = env_setup_vm(p)) < 0) {
243 kmem_cache_free(proc_cache, p);
246 if (!(p->pid = get_free_pid())) {
247 kmem_cache_free(proc_cache, p);
250 /* Set the basic status variables. */
251 spinlock_init(&p->proc_lock);
252 p->exitcode = 1337; /* so we can see processes killed by the kernel */
254 p->ppid = parent->pid;
255 /* using the CV's lock to protect anything related to child waiting */
256 cv_lock(&parent->child_wait);
257 TAILQ_INSERT_TAIL(&parent->children, p, sibling_link);
258 cv_unlock(&parent->child_wait);
262 TAILQ_INIT(&p->children);
263 cv_init(&p->child_wait);
264 p->state = PROC_CREATED; /* shouldn't go through state machine for init */
266 p->env_entry = 0; // cheating. this really gets set later
267 p->heap_top = (void*)UTEXT; /* heap_bottom set in proc_init_procinfo */
268 spinlock_init(&p->mm_lock);
269 TAILQ_INIT(&p->vm_regions); /* could init this in the slab */
270 /* Initialize the vcore lists, we'll build the inactive list so that it includes
271 * all vcores when we initialize procinfo. Do this before initing procinfo. */
272 TAILQ_INIT(&p->online_vcs);
273 TAILQ_INIT(&p->bulk_preempted_vcs);
274 TAILQ_INIT(&p->inactive_vcs);
275 /* Init procinfo/procdata. Procinfo's argp/argb are 0'd */
276 proc_init_procinfo(p);
277 proc_init_procdata(p);
279 /* Initialize the generic sysevent ring buffer */
280 SHARED_RING_INIT(&p->procdata->syseventring);
281 /* Initialize the frontend of the sysevent ring buffer */
282 FRONT_RING_INIT(&p->syseventfrontring,
283 &p->procdata->syseventring,
286 /* Init FS structures TODO: cleanup (might pull this out) */
287 kref_get(&default_ns.kref, 1);
289 spinlock_init(&p->fs_env.lock);
290 p->fs_env.umask = parent ? parent->fs_env.umask : S_IWGRP | S_IWOTH;
291 p->fs_env.root = p->ns->root->mnt_root;
292 kref_get(&p->fs_env.root->d_kref, 1);
293 p->fs_env.pwd = parent ? parent->fs_env.pwd : p->fs_env.root;
294 kref_get(&p->fs_env.pwd->d_kref, 1);
295 memset(&p->open_files, 0, sizeof(p->open_files)); /* slightly ghetto */
296 spinlock_init(&p->open_files.lock);
297 p->open_files.max_files = NR_OPEN_FILES_DEFAULT;
298 p->open_files.max_fdset = NR_FILE_DESC_DEFAULT;
299 p->open_files.fd = p->open_files.fd_array;
300 p->open_files.open_fds = (struct fd_set*)&p->open_files.open_fds_init;
301 /* Init the ucq hash lock */
302 p->ucq_hashlock = (struct hashlock*)&p->ucq_hl_noref;
303 hashlock_init_irqsave(p->ucq_hashlock, HASHLOCK_DEFAULT_SZ);
305 atomic_inc(&num_envs);
306 frontend_proc_init(p);
307 printd("[%08x] new process %08x\n", current ? current->pid : 0, p->pid);
313 /* We have a bunch of different ways to make processes. Call this once the
314 * process is ready to be used by the rest of the system. For now, this just
315 * means when it is ready to be named via the pidhash. In the future, we might
316 * push setting the state to CREATED into here. */
317 void __proc_ready(struct proc *p)
319 /* Tell the ksched about us. TODO: do we need to worry about the ksched
320 * doing stuff to us before we're added to the pid_hash? */
321 __sched_proc_register(p);
322 spin_lock(&pid_hash_lock);
323 hashtable_insert(pid_hash, (void*)(long)p->pid, p);
324 spin_unlock(&pid_hash_lock);
327 /* Creates a process from the specified file, argvs, and envps. Tempted to get
328 * rid of proc_alloc's style, but it is so quaint... */
329 struct proc *proc_create(struct file *prog, char **argv, char **envp)
333 if ((r = proc_alloc(&p, current)) < 0)
334 panic("proc_create: %e", r); /* one of 3 quaint usages of %e */
335 procinfo_pack_args(p->procinfo, argv, envp);
336 assert(load_elf(p, prog) == 0);
337 /* Connect to stdin, stdout, stderr */
338 assert(insert_file(&p->open_files, dev_stdin, 0) == 0);
339 assert(insert_file(&p->open_files, dev_stdout, 0) == 1);
340 assert(insert_file(&p->open_files, dev_stderr, 0) == 2);
345 /* This is called by kref_put(), once the last reference to the process is
346 * gone. Don't call this otherwise (it will panic). It will clean up the
347 * address space and deallocate any other used memory. */
348 static void __proc_free(struct kref *kref)
350 struct proc *p = container_of(kref, struct proc, p_kref);
353 printd("[PID %d] freeing proc: %d\n", current ? current->pid : 0, p->pid);
354 // All parts of the kernel should have decref'd before __proc_free is called
355 assert(kref_refcnt(&p->p_kref) == 0);
357 kref_put(&p->fs_env.root->d_kref);
358 kref_put(&p->fs_env.pwd->d_kref);
360 frontend_proc_free(p); /* TODO: please remove me one day */
361 /* Free any colors allocated to this process */
362 if (p->cache_colors_map != global_cache_colors_map) {
363 for(int i = 0; i < llc_cache->num_colors; i++)
364 cache_color_free(llc_cache, p->cache_colors_map);
365 cache_colors_map_free(p->cache_colors_map);
367 /* Remove us from the pid_hash and give our PID back (in that order). */
368 spin_lock(&pid_hash_lock);
369 if (!hashtable_remove(pid_hash, (void*)(long)p->pid))
370 panic("Proc not in the pid table in %s", __FUNCTION__);
371 spin_unlock(&pid_hash_lock);
372 put_free_pid(p->pid);
373 /* Flush all mapped pages in the user portion of the address space */
374 env_user_mem_free(p, 0, UVPT);
375 /* These need to be free again, since they were allocated with a refcnt. */
376 free_cont_pages(p->procinfo, LOG2_UP(PROCINFO_NUM_PAGES));
377 free_cont_pages(p->procdata, LOG2_UP(PROCDATA_NUM_PAGES));
379 env_pagetable_free(p);
383 atomic_dec(&num_envs);
385 /* Dealloc the struct proc */
386 kmem_cache_free(proc_cache, p);
389 /* Whether or not actor can control target. Note we currently don't need
390 * locking for this. TODO: think about that, esp wrt proc's dying. */
391 bool proc_controls(struct proc *actor, struct proc *target)
393 return ((actor == target) || (target->ppid == actor->pid));
396 /* Helper to incref by val. Using the helper to help debug/interpose on proc
397 * ref counting. Note that pid2proc doesn't use this interface. */
398 void proc_incref(struct proc *p, unsigned int val)
400 kref_get(&p->p_kref, val);
403 /* Helper to decref for debugging. Don't directly kref_put() for now. */
404 void proc_decref(struct proc *p)
406 kref_put(&p->p_kref);
409 /* Helper, makes p the 'current' process, dropping the old current/cr3. This no
410 * longer assumes the passed in reference already counted 'current'. It will
411 * incref internally when needed. */
412 static void __set_proc_current(struct proc *p)
414 /* We use the pcpui to access 'current' to cut down on the core_id() calls,
415 * though who know how expensive/painful they are. */
416 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
417 /* If the process wasn't here, then we need to load its address space. */
418 if (p != pcpui->cur_proc) {
421 /* This is "leaving the process context" of the previous proc. The
422 * previous lcr3 unloaded the previous proc's context. This should
423 * rarely happen, since we usually proactively leave process context,
424 * but this is the fallback. */
426 proc_decref(pcpui->cur_proc);
431 /* Flag says if vcore context is not ready, which is set in init_procdata. The
432 * process must turn off this flag on vcore0 at some point. It's off by default
433 * on all other vcores. */
434 static bool scp_is_vcctx_ready(struct preempt_data *vcpd)
436 return !(atomic_read(&vcpd->flags) & VC_SCP_NOVCCTX);
439 /* Dispatches a _S process to run on the current core. This should never be
440 * called to "restart" a core.
442 * This will always return, regardless of whether or not the calling core is
443 * being given to a process. (it used to pop the tf directly, before we had
446 * Since it always returns, it will never "eat" your reference (old
447 * documentation talks about this a bit). */
448 void proc_run_s(struct proc *p)
450 uint32_t coreid = core_id();
451 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
452 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
453 spin_lock(&p->proc_lock);
456 spin_unlock(&p->proc_lock);
457 printk("[kernel] _S %d not starting due to async death\n", p->pid);
459 case (PROC_RUNNABLE_S):
460 __proc_set_state(p, PROC_RUNNING_S);
461 /* We will want to know where this process is running, even if it is
462 * only in RUNNING_S. can use the vcoremap, which makes death easy.
463 * Also, this is the signal used in trap.c to know to save the tf in
465 __seq_start_write(&p->procinfo->coremap_seqctr);
466 p->procinfo->num_vcores = 0; /* TODO (VC#) */
467 /* TODO: For now, we won't count this as an active vcore (on the
468 * lists). This gets unmapped in resource.c and yield_s, and needs
470 __map_vcore(p, 0, coreid); /* not treated like a true vcore */
471 __seq_end_write(&p->procinfo->coremap_seqctr);
472 /* incref, since we're saving a reference in owning proc later */
474 /* lock was protecting the state and VC mapping, not pcpui stuff */
475 spin_unlock(&p->proc_lock);
476 /* redundant with proc_startcore, might be able to remove that one*/
477 __set_proc_current(p);
478 /* set us up as owning_proc. ksched bug if there is already one,
479 * for now. can simply clear_owning if we want to. */
480 assert(!pcpui->owning_proc);
481 pcpui->owning_proc = p;
482 pcpui->owning_vcoreid = 0; /* TODO (VC#) */
483 /* TODO: (HSS) set silly state here (__startcore does it instantly) */
484 /* similar to the old __startcore, start them in vcore context if
485 * they have notifs and aren't already in vcore context. o/w, start
486 * them wherever they were before (could be either vc ctx or not) */
487 if (!vcpd->notif_disabled && vcpd->notif_pending
488 && scp_is_vcctx_ready(vcpd)) {
489 vcpd->notif_disabled = TRUE;
490 /* save the _S's tf in the notify slot, build and pop a new one
491 * in actual/cur_tf. */
492 vcpd->notif_tf = p->env_tf;
493 pcpui->cur_tf = &pcpui->actual_tf;
494 memset(pcpui->cur_tf, 0, sizeof(struct trapframe));
495 proc_init_trapframe(pcpui->cur_tf, 0, p->env_entry,
496 vcpd->transition_stack);
498 /* If they have no transition stack, then they can't receive
499 * events. The most they are getting is a wakeup from the
500 * kernel. They won't even turn off notif_pending, so we'll do
502 if (!scp_is_vcctx_ready(vcpd))
503 vcpd->notif_pending = FALSE;
504 /* this is one of the few times cur_tf != &actual_tf */
505 pcpui->cur_tf = &p->env_tf;
507 /* When the calling core idles, it'll call restartcore and run the
508 * _S process's context. */
511 spin_unlock(&p->proc_lock);
512 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
516 /* Helper: sends preempt messages to all vcores on the bulk preempt list, and
517 * moves them to the inactive list. */
518 static void __send_bulkp_events(struct proc *p)
520 struct vcore *vc_i, *vc_temp;
521 struct event_msg preempt_msg = {0};
522 /* Whenever we send msgs with the proc locked, we need at least 1 online */
523 assert(!TAILQ_EMPTY(&p->online_vcs));
524 /* Send preempt messages for any left on the BP list. No need to set any
525 * flags, it all was done on the real preempt. Now we're just telling the
526 * process about any that didn't get restarted and are still preempted. */
527 TAILQ_FOREACH_SAFE(vc_i, &p->bulk_preempted_vcs, list, vc_temp) {
528 /* Note that if there are no active vcores, send_k_e will post to our
529 * own vcore, the last of which will be put on the inactive list and be
530 * the first to be started. We could have issues with deadlocking,
531 * since send_k_e() could grab the proclock (if there are no active
533 preempt_msg.ev_type = EV_VCORE_PREEMPT;
534 preempt_msg.ev_arg2 = vcore2vcoreid(p, vc_i); /* arg2 is 32 bits */
535 send_kernel_event(p, &preempt_msg, 0);
536 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that.
537 * We need a loop for the messages, but not necessarily for the list
539 TAILQ_REMOVE(&p->bulk_preempted_vcs, vc_i, list);
540 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
544 /* Run an _M. Can be called safely on one that is already running. Hold the
545 * lock before calling. Other than state checks, this just starts up the _M's
546 * vcores, much like the second part of give_cores_running. More specifically,
547 * give_cores_runnable puts cores on the online list, which this then sends
548 * messages to. give_cores_running immediately puts them on the list and sends
549 * the message. the two-step style may go out of fashion soon.
551 * This expects that the "instructions" for which core(s) to run this on will be
552 * in the vcoremap, which needs to be set externally (give_cores()). */
553 void __proc_run_m(struct proc *p)
559 warn("ksched tried to run proc %d in state %s\n", p->pid,
560 procstate2str(p->state));
562 case (PROC_RUNNABLE_M):
563 /* vcoremap[i] holds the coreid of the physical core allocated to
564 * this process. It is set outside proc_run. For the kernel
565 * message, a0 = struct proc*, a1 = struct trapframe*. */
566 if (p->procinfo->num_vcores) {
567 __send_bulkp_events(p);
568 __proc_set_state(p, PROC_RUNNING_M);
569 /* Up the refcnt, to avoid the n refcnt upping on the
570 * destination cores. Keep in sync with __startcore */
571 proc_incref(p, p->procinfo->num_vcores * 2);
572 /* Send kernel messages to all online vcores (which were added
573 * to the list and mapped in __proc_give_cores()), making them
575 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
576 send_kernel_message(vc_i->pcoreid, __startcore, (long)p,
577 (long)vcore2vcoreid(p, vc_i),
578 (long)vc_i->nr_preempts_sent,
582 warn("Tried to proc_run() an _M with no vcores!");
584 /* There a subtle race avoidance here (when we unlock after sending
585 * the message). __proc_startcore can handle a death message, but
586 * we can't have the startcore come after the death message.
587 * Otherwise, it would look like a new process. So we hold the lock
588 * til after we send our message, which prevents a possible death
590 * - Note there is no guarantee this core's interrupts were on, so
591 * it may not get the message for a while... */
593 case (PROC_RUNNING_M):
596 /* unlock just so the monitor can call something that might lock*/
597 spin_unlock(&p->proc_lock);
598 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
602 /* Actually runs the given context (trapframe) of process p on the core this
603 * code executes on. This is called directly by __startcore, which needs to
604 * bypass the routine_kmsg check. Interrupts should be off when you call this.
606 * A note on refcnting: this function will not return, and your proc reference
607 * will end up stored in current. This will make no changes to p's refcnt, so
608 * do your accounting such that there is only the +1 for current. This means if
609 * it is already in current (like in the trap return path), don't up it. If
610 * it's already in current and you have another reference (like pid2proc or from
611 * an IPI), then down it (which is what happens in __startcore()). If it's not
612 * in current and you have one reference, like proc_run(non_current_p), then
613 * also do nothing. The refcnt for your *p will count for the reference stored
615 static void __proc_startcore(struct proc *p, trapframe_t *tf)
617 assert(!irq_is_enabled());
618 __set_proc_current(p);
619 /* need to load our silly state, preferably somewhere other than here so we
620 * can avoid the case where the context was just running here. it's not
621 * sufficient to do it in the "new process" if-block above (could be things
622 * like page faults that cause us to keep the same process, but want a
624 * for now, we load this silly state here. (TODO) (HSS)
625 * We also need this to be per trapframe, and not per process...
626 * For now / OSDI, only load it when in _S mode. _M mode was handled in
628 if (p->state == PROC_RUNNING_S)
629 env_pop_ancillary_state(p);
630 /* Clear the current_tf, since it is no longer used */
631 current_tf = 0; /* TODO: might not need this... */
635 /* Restarts/runs the current_tf, which must be for the current process, on the
636 * core this code executes on. Calls an internal function to do the work.
638 * In case there are pending routine messages, like __death, __preempt, or
639 * __notify, we need to run them. Alternatively, if there are any, we could
640 * self_ipi, and run the messages immediately after popping back to userspace,
641 * but that would have crappy overhead.
643 * Refcnting: this will not return, and it assumes that you've accounted for
644 * your reference as if it was the ref for "current" (which is what happens when
645 * returning from local traps and such. */
646 void proc_restartcore(void)
648 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
649 assert(!pcpui->cur_sysc);
650 /* TODO: can probably remove this enable_irq. it was an optimization for
652 /* Try and get any interrupts before we pop back to userspace. If we didn't
653 * do this, we'd just get them in userspace, but this might save us some
654 * effort/overhead. */
656 /* Need ints disabled when we return from processing (race on missing
659 process_routine_kmsg();
660 /* If there is no owning process, just idle, since we don't know what to do.
661 * This could be because the process had been restarted a long time ago and
662 * has since left the core, or due to a KMSG like __preempt or __death. */
663 if (!pcpui->owning_proc) {
667 assert(pcpui->cur_tf);
668 __proc_startcore(pcpui->owning_proc, pcpui->cur_tf);
671 /* Destroys the process. It will destroy the process and return any cores
672 * to the ksched via the __sched_proc_destroy() CB.
674 * Here's the way process death works:
675 * 0. grab the lock (protects state transition and core map)
676 * 1. set state to dying. that keeps the kernel from doing anything for the
677 * process (like proc_running it).
678 * 2. figure out where the process is running (cross-core/async or RUNNING_M)
679 * 3. IPI to clean up those cores (decref, etc).
681 * 5. Clean up your core, if applicable
682 * (Last core/kernel thread to decref cleans up and deallocates resources.)
684 * Note that some cores can be processing async calls, but will eventually
685 * decref. Should think about this more, like some sort of callback/revocation.
687 * This function will now always return (it used to not return if the calling
688 * core was dying). However, when it returns, a kernel message will eventually
689 * come in, making you abandon_core, as if you weren't running. It may be that
690 * the only reference to p is the one you passed in, and when you decref, it'll
691 * get __proc_free()d. */
692 void proc_destroy(struct proc *p)
694 uint32_t nr_cores_revoked = 0;
695 struct kthread *sleeper;
696 /* Can't spin on the proc lock with irq disabled. This is a problem for all
697 * places where we grab the lock, but it is particularly bad for destroy,
698 * since we tend to call this from trap and irq handlers */
699 assert(irq_is_enabled());
700 spin_lock(&p->proc_lock);
701 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
702 uint32_t pc_arr[p->procinfo->num_vcores];
704 case PROC_DYING: /* someone else killed this already. */
705 spin_unlock(&p->proc_lock);
708 case PROC_RUNNABLE_S:
711 case PROC_RUNNABLE_M:
713 /* Need to reclaim any cores this proc might have, even if it's not
714 * running yet. Those running will receive a __death */
715 nr_cores_revoked = __proc_take_allcores(p, pc_arr, FALSE);
719 // here's how to do it manually
722 proc_decref(p); /* this decref is for the cr3 */
726 send_kernel_message(get_pcoreid(p, 0), __death, 0, 0, 0,
728 __seq_start_write(&p->procinfo->coremap_seqctr);
729 // TODO: might need to sort num_vcores too later (VC#)
730 /* vcore is unmapped on the receive side */
731 __seq_end_write(&p->procinfo->coremap_seqctr);
732 /* If we ever have RUNNING_S run on non-mgmt cores, we'll need to
733 * tell the ksched about this now-idle core (after unlocking) */
736 warn("Weird state(%s) in %s()", procstate2str(p->state),
738 spin_unlock(&p->proc_lock);
741 /* At this point, a death IPI should be on its way, either from the
742 * RUNNING_S one, or from proc_take_cores with a __death. in general,
743 * interrupts should be on when you call proc_destroy locally, but currently
744 * aren't for all things (like traphandlers). */
745 __proc_set_state(p, PROC_DYING);
746 spin_unlock(&p->proc_lock);
747 /* This prevents processes from accessing their old files while dying, and
748 * will help if these files (or similar objects in the future) hold
749 * references to p (preventing a __proc_free()). Need to unlock before
750 * doing this - the proclock doesn't protect the files (not proc state), and
751 * closing these might block (can't block while spinning). */
752 /* TODO: might need some sync protection */
753 close_all_files(&p->open_files, FALSE);
754 /* Tell the ksched about our death, and which cores we freed up */
755 __sched_proc_destroy(p, pc_arr, nr_cores_revoked);
756 /* Tell our parent about our state change (to DYING) */
757 proc_signal_parent(p);
760 /* Can use this to signal anything that might cause a parent to wait on the
761 * child, such as termination, or (in the future) signals. Change the state or
762 * whatever before calling. */
763 void proc_signal_parent(struct proc *child)
765 struct kthread *sleeper;
766 struct proc *parent = pid2proc(child->ppid);
769 /* there could be multiple kthreads sleeping for various reasons. even an
770 * SCP could have multiple async syscalls. */
771 cv_broadcast(&parent->child_wait);
772 /* if the parent was waiting, there's a __launch kthread KMSG out there */
776 /* Called when a parent is done with its child, and no longer wants to track the
777 * child, nor to allow the child to track it. Call with a lock (cv) held.
778 * Returns 0 if we disowned, -1 on failure. */
779 int __proc_disown_child(struct proc *parent, struct proc *child)
781 /* Bail out if the child has already been reaped */
784 assert(child->ppid == parent->pid);
785 /* lock protects from concurrent inserts / removals from the list */
786 TAILQ_REMOVE(&parent->children, child, sibling_link);
787 /* After this, the child won't be able to get more refs to us, but it may
788 * still have some references in running code. */
790 proc_decref(child); /* ref that was keeping the child alive after dying */
794 /* Turns *p into an MCP. Needs to be called from a local syscall of a RUNNING_S
795 * process. Returns 0 if it succeeded, an error code otherwise. */
796 int proc_change_to_m(struct proc *p)
799 spin_lock(&p->proc_lock);
800 /* in case userspace erroneously tries to change more than once */
801 if (__proc_is_mcp(p))
804 case (PROC_RUNNING_S):
805 /* issue with if we're async or not (need to preempt it)
806 * either of these should trip it. TODO: (ACR) async core req
807 * TODO: relies on vcore0 being the caller (VC#) */
808 if ((current != p) || (get_pcoreid(p, 0) != core_id()))
809 panic("We don't handle async RUNNING_S core requests yet.");
810 /* save the tf so userspace can restart it. Like in __notify,
811 * this assumes a user tf is the same as a kernel tf. We save
812 * it in the preempt slot so that we can also save the silly
814 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
816 /* Copy uthread0's context to the notif slot */
817 vcpd->notif_tf = *current_tf;
818 clear_owning_proc(core_id()); /* so we don't restart */
819 save_fp_state(&vcpd->preempt_anc);
820 /* Userspace needs to not fuck with notif_disabled before
821 * transitioning to _M. */
822 if (vcpd->notif_disabled) {
823 printk("[kernel] user bug: notifs disabled for vcore 0\n");
824 vcpd->notif_disabled = FALSE;
826 /* in the async case, we'll need to remotely stop and bundle
827 * vcore0's TF. this is already done for the sync case (local
829 /* this process no longer runs on its old location (which is
830 * this core, for now, since we don't handle async calls) */
831 __seq_start_write(&p->procinfo->coremap_seqctr);
832 // TODO: (VC#) might need to adjust num_vcores
833 // TODO: (ACR) will need to unmap remotely (receive-side)
834 __unmap_vcore(p, 0); /* VC# keep in sync with proc_run_s */
835 __seq_end_write(&p->procinfo->coremap_seqctr);
836 /* change to runnable_m (it's TF is already saved) */
837 __proc_set_state(p, PROC_RUNNABLE_M);
838 p->procinfo->is_mcp = TRUE;
839 spin_unlock(&p->proc_lock);
840 /* Tell the ksched that we're a real MCP now! */
841 __sched_proc_change_to_m(p);
843 case (PROC_RUNNABLE_S):
844 /* Issues: being on the runnable_list, proc_set_state not liking
845 * it, and not clearly thinking through how this would happen.
846 * Perhaps an async call that gets serviced after you're
848 warn("Not supporting RUNNABLE_S -> RUNNABLE_M yet.\n");
851 warn("Dying, core request coming from %d\n", core_id());
857 spin_unlock(&p->proc_lock);
861 /* Old code to turn a RUNNING_M to a RUNNING_S, with the calling context
862 * becoming the new 'thread0'. Don't use this. Caller needs to send in a
863 * pc_arr big enough for all vcores. Will return the number of cores given up
865 uint32_t __proc_change_to_s(struct proc *p, uint32_t *pc_arr)
867 uint32_t num_revoked;
868 printk("[kernel] trying to transition _M -> _S (deprecated)!\n");
869 assert(p->state == PROC_RUNNING_M); // TODO: (ACR) async core req
870 /* save the context, to be restarted in _S mode */
872 p->env_tf = *current_tf;
873 clear_owning_proc(core_id()); /* so we don't restart */
874 env_push_ancillary_state(p); // TODO: (HSS)
875 /* sending death, since it's not our job to save contexts or anything in
877 num_revoked = __proc_take_allcores(p, pc_arr, FALSE);
878 __proc_set_state(p, PROC_RUNNABLE_S);
882 /* Helper function. Is the given pcore a mapped vcore? No locking involved, be
884 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid)
886 return p->procinfo->pcoremap[pcoreid].valid;
889 /* Helper function. Find the vcoreid for a given physical core id for proc p.
890 * No locking involved, be careful. Panics on failure. */
891 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid)
893 assert(is_mapped_vcore(p, pcoreid));
894 return p->procinfo->pcoremap[pcoreid].vcoreid;
897 /* Helper function. Try to find the pcoreid for a given virtual core id for
898 * proc p. No locking involved, be careful. Use this when you can tolerate a
899 * stale or otherwise 'wrong' answer. */
900 static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid)
902 return p->procinfo->vcoremap[vcoreid].pcoreid;
905 /* Helper function. Find the pcoreid for a given virtual core id for proc p.
906 * No locking involved, be careful. Panics on failure. */
907 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid)
909 assert(vcore_is_mapped(p, vcoreid));
910 return try_get_pcoreid(p, vcoreid);
913 /* Helper: saves the SCP's tf state and unmaps vcore 0. In the future, we'll
914 * probably use vc0's space for env_tf and the silly state. */
915 void __proc_save_context_s(struct proc *p, struct trapframe *tf)
918 env_push_ancillary_state(p); /* TODO: (HSS) */
919 __unmap_vcore(p, 0); /* VC# keep in sync with proc_run_s */
922 /* Yields the calling core. Must be called locally (not async) for now.
923 * - If RUNNING_S, you just give up your time slice and will eventually return,
924 * possibly after WAITING on an event.
925 * - If RUNNING_M, you give up the current vcore (which never returns), and
926 * adjust the amount of cores wanted/granted.
927 * - If you have only one vcore, you switch to WAITING. There's no 'classic
928 * yield' for MCPs (at least not now). When you run again, you'll have one
929 * guaranteed core, starting from the entry point.
931 * If the call is being nice, it means different things for SCPs and MCPs. For
932 * MCPs, it means that it is in response to a preemption (which needs to be
933 * checked). If there is no preemption pending, just return. For SCPs, it
934 * means the proc wants to give up the core, but still has work to do. If not,
935 * the proc is trying to wait on an event. It's not being nice to others, it
936 * just has no work to do.
938 * This usually does not return (smp_idle()), so it will eat your reference.
939 * Also note that it needs a non-current/edible reference, since it will abandon
940 * and continue to use the *p (current == 0, no cr3, etc).
942 * We disable interrupts for most of it too, since we need to protect current_tf
943 * and not race with __notify (which doesn't play well with concurrent
945 void proc_yield(struct proc *SAFE p, bool being_nice)
947 uint32_t vcoreid, pcoreid = core_id();
948 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
950 struct preempt_data *vcpd;
951 /* Need to lock to prevent concurrent vcore changes (online, inactive, the
952 * mapping, etc). This plus checking the nr_preempts is enough to tell if
953 * our vcoreid and cur_tf ought to be here still or if we should abort */
954 spin_lock(&p->proc_lock); /* horrible scalability. =( */
956 case (PROC_RUNNING_S):
958 /* waiting for an event to unblock us */
959 vcpd = &p->procdata->vcore_preempt_data[0];
960 /* this check is an early optimization (check, signal, check
961 * again pattern). We could also lock before spamming the
962 * vcore in event.c */
963 if (vcpd->notif_pending) {
964 /* they can't handle events, just need to prevent a yield.
965 * (note the notif_pendings are collapsed). */
966 if (!scp_is_vcctx_ready(vcpd))
967 vcpd->notif_pending = FALSE;
970 /* syncing with event's SCP code. we set waiting, then check
971 * pending. they set pending, then check waiting. it's not
972 * possible for us to miss the notif *and* for them to miss
973 * WAITING. one (or both) of us will see and make sure the proc
975 __proc_set_state(p, PROC_WAITING);
976 wrmb(); /* don't let the state write pass the notif read */
977 if (vcpd->notif_pending) {
978 __proc_set_state(p, PROC_RUNNING_S);
979 if (!scp_is_vcctx_ready(vcpd))
980 vcpd->notif_pending = FALSE;
983 /* if we're here, we want to sleep. a concurrent event that
984 * hasn't already written notif_pending will have seen WAITING,
985 * and will be spinning while we do this. */
986 __proc_save_context_s(p, current_tf);
987 spin_unlock(&p->proc_lock);
989 /* yielding to allow other processes to run. we're briefly
990 * WAITING, til we are woken up */
991 __proc_set_state(p, PROC_WAITING);
992 __proc_save_context_s(p, current_tf);
993 spin_unlock(&p->proc_lock);
994 /* immediately wake up the proc (makes it runnable) */
998 case (PROC_RUNNING_M):
999 break; /* will handle this stuff below */
1000 case (PROC_DYING): /* incoming __death */
1001 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1004 panic("Weird state(%s) in %s()", procstate2str(p->state),
1007 /* This is which vcore this pcore thinks it is, regardless of any unmappings
1008 * that may have happened remotely (with __PRs waiting to run) */
1009 vcoreid = pcpui->owning_vcoreid;
1010 vc = vcoreid2vcore(p, vcoreid);
1011 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1012 /* This is how we detect whether or not a __PR happened. */
1013 if (vc->nr_preempts_sent != vc->nr_preempts_done)
1015 /* Sanity checks. If we were preempted or are dying, we should have noticed
1017 assert(is_mapped_vcore(p, pcoreid));
1018 assert(vcoreid == get_vcoreid(p, pcoreid));
1019 /* no reason to be nice, return */
1020 if (being_nice && !vc->preempt_pending)
1022 /* At this point, AFAIK there should be no preempt/death messages on the
1023 * way, and we're on the online list. So we'll go ahead and do the yielding
1025 /* If there's a preempt pending, we don't need to preempt later since we are
1026 * yielding (nice or otherwise). If not, this is just a regular yield. */
1027 if (vc->preempt_pending) {
1028 vc->preempt_pending = 0;
1030 /* Optional: on a normal yield, check to see if we are putting them
1031 * below amt_wanted (help with user races) and bail. */
1032 if (p->procdata->res_req[RES_CORES].amt_wanted >=
1033 p->procinfo->num_vcores)
1036 /* Don't let them yield if they are missing a notification. Userspace must
1037 * not leave vcore context without dealing with notif_pending. pop_ros_tf()
1038 * handles leaving via uthread context. This handles leaving via a yield.
1040 * This early check is an optimization. The real check is below when it
1041 * works with the online_vcs list (syncing with event.c and INDIR/IPI
1043 if (vcpd->notif_pending)
1045 /* Now we'll actually try to yield */
1046 printd("[K] Process %d (%p) is yielding on vcore %d\n", p->pid, p,
1047 get_vcoreid(p, pcoreid));
1048 /* Remove from the online list, add to the yielded list, and unmap
1049 * the vcore, which gives up the core. */
1050 TAILQ_REMOVE(&p->online_vcs, vc, list);
1051 /* Now that we're off the online list, check to see if an alert made
1052 * it through (event.c sets this) */
1053 wrmb(); /* prev write must hit before reading notif_pending */
1054 /* Note we need interrupts disabled, since a __notify can come in
1055 * and set pending to FALSE */
1056 if (vcpd->notif_pending) {
1057 /* We lost, put it back on the list and abort the yield */
1058 TAILQ_INSERT_TAIL(&p->online_vcs, vc, list); /* could go HEAD */
1061 /* We won the race with event sending, we can safely yield */
1062 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1063 /* Note this protects stuff userspace should look at, which doesn't
1064 * include the TAILQs. */
1065 __seq_start_write(&p->procinfo->coremap_seqctr);
1066 /* Next time the vcore starts, it starts fresh */
1067 vcpd->notif_disabled = FALSE;
1068 __unmap_vcore(p, vcoreid);
1069 p->procinfo->num_vcores--;
1070 p->procinfo->res_grant[RES_CORES] = p->procinfo->num_vcores;
1071 __seq_end_write(&p->procinfo->coremap_seqctr);
1072 /* No more vcores? Then we wait on an event */
1073 if (p->procinfo->num_vcores == 0) {
1074 /* consider a ksched op to tell it about us WAITING */
1075 __proc_set_state(p, PROC_WAITING);
1077 spin_unlock(&p->proc_lock);
1078 /* Hand the now-idle core to the ksched */
1079 __sched_put_idle_core(p, pcoreid);
1080 goto out_yield_core;
1082 /* for some reason we just want to return, either to take a KMSG that cleans
1083 * us up, or because we shouldn't yield (ex: notif_pending). */
1084 spin_unlock(&p->proc_lock);
1086 out_yield_core: /* successfully yielded the core */
1087 proc_decref(p); /* need to eat the ref passed in */
1088 /* Clean up the core and idle. */
1089 clear_owning_proc(pcoreid); /* so we don't restart */
1094 /* Sends a notification (aka active notification, aka IPI) to p's vcore. We
1095 * only send a notification if one they are enabled. There's a bunch of weird
1096 * cases with this, and how pending / enabled are signals between the user and
1097 * kernel - check the documentation. Note that pending is more about messages.
1098 * The process needs to be in vcore_context, and the reason is usually a
1099 * message. We set pending here in case we were called to prod them into vcore
1100 * context (like via a sys_self_notify). Also note that this works for _S
1101 * procs, if you send to vcore 0 (and the proc is running). */
1102 void proc_notify(struct proc *p, uint32_t vcoreid)
1104 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1105 vcpd->notif_pending = TRUE;
1106 wrmb(); /* must write notif_pending before reading notif_disabled */
1107 if (!vcpd->notif_disabled) {
1108 /* GIANT WARNING: we aren't using the proc-lock to protect the
1109 * vcoremap. We want to be able to use this from interrupt context,
1110 * and don't want the proc_lock to be an irqsave. Spurious
1111 * __notify() kmsgs are okay (it checks to see if the right receiver
1113 if (vcore_is_mapped(p, vcoreid)) {
1114 printd("[kernel] sending notif to vcore %d\n", vcoreid);
1115 /* This use of try_get_pcoreid is racy, might be unmapped */
1116 send_kernel_message(try_get_pcoreid(p, vcoreid), __notify, (long)p,
1117 0, 0, KMSG_ROUTINE);
1122 /* Makes sure p is runnable. Callers may spam this, so it needs to handle
1123 * repeated calls for the same event. Callers include event delivery, SCP
1124 * yield, and new SCPs. Will trigger __sched_.cp_wakeup() CBs. Will only
1125 * trigger the CB once, regardless of how many times we are called, *until* the
1126 * proc becomes WAITING again, presumably because of something the ksched did.*/
1127 void proc_wakeup(struct proc *p)
1129 spin_lock(&p->proc_lock);
1130 if (__proc_is_mcp(p)) {
1131 /* we only wake up WAITING mcps */
1132 if (p->state != PROC_WAITING) {
1133 spin_unlock(&p->proc_lock);
1136 __proc_set_state(p, PROC_RUNNABLE_M);
1137 spin_unlock(&p->proc_lock);
1138 __sched_mcp_wakeup(p);
1141 /* SCPs can wake up for a variety of reasons. the only times we need
1142 * to do something is if it was waiting or just created. other cases
1143 * are either benign (just go out), or potential bugs (_Ms) */
1145 case (PROC_CREATED):
1146 case (PROC_WAITING):
1147 __proc_set_state(p, PROC_RUNNABLE_S);
1149 case (PROC_RUNNABLE_S):
1150 case (PROC_RUNNING_S):
1152 spin_unlock(&p->proc_lock);
1154 case (PROC_RUNNABLE_M):
1155 case (PROC_RUNNING_M):
1156 warn("Weird state(%s) in %s()", procstate2str(p->state),
1158 spin_unlock(&p->proc_lock);
1161 printd("[kernel] FYI, waking up an _S proc\n"); /* thanks, past brho! */
1162 spin_unlock(&p->proc_lock);
1163 __sched_scp_wakeup(p);
1167 /* Is the process in multi_mode / is an MCP or not? */
1168 bool __proc_is_mcp(struct proc *p)
1170 /* in lieu of using the amount of cores requested, or having a bunch of
1171 * states (like PROC_WAITING_M and _S), I'll just track it with a bool. */
1172 return p->procinfo->is_mcp;
1175 /************************ Preemption Functions ******************************
1176 * Don't rely on these much - I'll be sure to change them up a bit.
1178 * Careful about what takes a vcoreid and what takes a pcoreid. Also, there may
1179 * be weird glitches with setting the state to RUNNABLE_M. It is somewhat in
1180 * flux. The num_vcores is changed after take_cores, but some of the messages
1181 * (or local traps) may not yet be ready to handle seeing their future state.
1182 * But they should be, so fix those when they pop up.
1184 * Another thing to do would be to make the _core functions take a pcorelist,
1185 * and not just one pcoreid. */
1187 /* Sets a preempt_pending warning for p's vcore, to go off 'when'. If you care
1188 * about locking, do it before calling. Takes a vcoreid! */
1189 void __proc_preempt_warn(struct proc *p, uint32_t vcoreid, uint64_t when)
1191 struct event_msg local_msg = {0};
1192 /* danger with doing this unlocked: preempt_pending is set, but never 0'd,
1193 * since it is unmapped and not dealt with (TODO)*/
1194 p->procinfo->vcoremap[vcoreid].preempt_pending = when;
1196 /* Send the event (which internally checks to see how they want it) */
1197 local_msg.ev_type = EV_PREEMPT_PENDING;
1198 local_msg.ev_arg1 = vcoreid;
1199 /* Whenever we send msgs with the proc locked, we need at least 1 online.
1200 * Caller needs to make sure the core was online/mapped. */
1201 assert(!TAILQ_EMPTY(&p->online_vcs));
1202 send_kernel_event(p, &local_msg, vcoreid);
1204 /* TODO: consider putting in some lookup place for the alarm to find it.
1205 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1208 /* Warns all active vcores of an impending preemption. Hold the lock if you
1209 * care about the mapping (and you should). */
1210 void __proc_preempt_warnall(struct proc *p, uint64_t when)
1213 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1214 __proc_preempt_warn(p, vcore2vcoreid(p, vc_i), when);
1215 /* TODO: consider putting in some lookup place for the alarm to find it.
1216 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1219 // TODO: function to set an alarm, if none is outstanding
1221 /* Raw function to preempt a single core. If you care about locking, do it
1222 * before calling. */
1223 void __proc_preempt_core(struct proc *p, uint32_t pcoreid)
1225 uint32_t vcoreid = get_vcoreid(p, pcoreid);
1226 struct event_msg preempt_msg = {0};
1227 /* works with nr_preempts_done to signal completion of a preemption */
1228 p->procinfo->vcoremap[vcoreid].nr_preempts_sent++;
1229 // expects a pcorelist. assumes pcore is mapped and running_m
1230 __proc_take_corelist(p, &pcoreid, 1, TRUE);
1231 /* Only send the message if we have an online core. o/w, it would fuck
1232 * us up (deadlock), and hey don't need a message. the core we just took
1233 * will be the first one to be restarted. It will look like a notif. in
1234 * the future, we could send the event if we want, but the caller needs to
1235 * do that (after unlocking). */
1236 if (!TAILQ_EMPTY(&p->online_vcs)) {
1237 preempt_msg.ev_type = EV_VCORE_PREEMPT;
1238 preempt_msg.ev_arg2 = vcoreid;
1239 send_kernel_event(p, &preempt_msg, 0);
1243 /* Raw function to preempt every vcore. If you care about locking, do it before
1245 uint32_t __proc_preempt_all(struct proc *p, uint32_t *pc_arr)
1248 /* TODO:(BULK) PREEMPT - don't bother with this, set a proc wide flag, or
1249 * just make us RUNNABLE_M. Note this is also used by __map_vcore. */
1250 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1251 vc_i->nr_preempts_sent++;
1252 return __proc_take_allcores(p, pc_arr, TRUE);
1255 /* Warns and preempts a vcore from p. No delaying / alarming, or anything. The
1256 * warning will be for u usec from now. Returns TRUE if the core belonged to
1257 * the proc (and thus preempted), False if the proc no longer has the core. */
1258 bool proc_preempt_core(struct proc *p, uint32_t pcoreid, uint64_t usec)
1260 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1261 bool retval = FALSE;
1262 if (p->state != PROC_RUNNING_M) {
1263 /* more of an FYI for brho. should be harmless to just return. */
1264 warn("Tried to preempt from a non RUNNING_M proc!");
1267 spin_lock(&p->proc_lock);
1268 if (is_mapped_vcore(p, pcoreid)) {
1269 __proc_preempt_warn(p, get_vcoreid(p, pcoreid), warn_time);
1270 __proc_preempt_core(p, pcoreid);
1271 /* we might have taken the last core */
1272 if (!p->procinfo->num_vcores)
1273 __proc_set_state(p, PROC_RUNNABLE_M);
1276 spin_unlock(&p->proc_lock);
1280 /* Warns and preempts all from p. No delaying / alarming, or anything. The
1281 * warning will be for u usec from now. */
1282 void proc_preempt_all(struct proc *p, uint64_t usec)
1284 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1285 uint32_t num_revoked = 0;
1286 spin_lock(&p->proc_lock);
1287 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
1288 uint32_t pc_arr[p->procinfo->num_vcores];
1289 /* DYING could be okay */
1290 if (p->state != PROC_RUNNING_M) {
1291 warn("Tried to preempt from a non RUNNING_M proc!");
1292 spin_unlock(&p->proc_lock);
1295 __proc_preempt_warnall(p, warn_time);
1296 num_revoked = __proc_preempt_all(p, pc_arr);
1297 assert(!p->procinfo->num_vcores);
1298 __proc_set_state(p, PROC_RUNNABLE_M);
1299 spin_unlock(&p->proc_lock);
1300 /* TODO: when we revise this func, look at __put_idle */
1301 /* Return the cores to the ksched */
1303 __sched_put_idle_cores(p, pc_arr, num_revoked);
1306 /* Give the specific pcore to proc p. Lots of assumptions, so don't really use
1307 * this. The proc needs to be _M and prepared for it. the pcore needs to be
1309 void proc_give(struct proc *p, uint32_t pcoreid)
1311 warn("Your idlecoremap is now screwed up"); /* TODO (IDLE) */
1312 spin_lock(&p->proc_lock);
1313 // expects a pcorelist, we give it a list of one
1314 __proc_give_cores(p, &pcoreid, 1);
1315 spin_unlock(&p->proc_lock);
1318 /* Global version of the helper, for sys_get_vcoreid (might phase that syscall
1320 uint32_t proc_get_vcoreid(struct proc *p)
1322 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1323 if (pcpui->owning_proc == p) {
1324 return pcpui->owning_vcoreid;
1326 warn("Asked for vcoreid for %p, but %p is pwns", p, pcpui->owning_proc);
1327 return (uint32_t)-1;
1331 /* TODO: make all of these static inlines when we gut the env crap */
1332 bool vcore_is_mapped(struct proc *p, uint32_t vcoreid)
1334 return p->procinfo->vcoremap[vcoreid].valid;
1337 /* Can do this, or just create a new field and save it in the vcoremap */
1338 uint32_t vcore2vcoreid(struct proc *p, struct vcore *vc)
1340 return (vc - p->procinfo->vcoremap);
1343 struct vcore *vcoreid2vcore(struct proc *p, uint32_t vcoreid)
1345 return &p->procinfo->vcoremap[vcoreid];
1348 /********** Core granting (bulk and single) ***********/
1350 /* Helper: gives pcore to the process, mapping it to the next available vcore
1351 * from list vc_list. Returns TRUE if we succeeded (non-empty). If you pass in
1352 * **vc, we'll tell you which vcore it was. */
1353 static bool __proc_give_a_pcore(struct proc *p, uint32_t pcore,
1354 struct vcore_tailq *vc_list, struct vcore **vc)
1356 struct vcore *new_vc;
1357 new_vc = TAILQ_FIRST(vc_list);
1360 printd("setting vcore %d to pcore %d\n", vcore2vcoreid(p, new_vc),
1362 TAILQ_REMOVE(vc_list, new_vc, list);
1363 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1364 __map_vcore(p, vcore2vcoreid(p, new_vc), pcore);
1370 static void __proc_give_cores_runnable(struct proc *p, uint32_t *pc_arr,
1373 assert(p->state == PROC_RUNNABLE_M);
1374 assert(num); /* catch bugs */
1375 /* add new items to the vcoremap */
1376 __seq_start_write(&p->procinfo->coremap_seqctr);/* unncessary if offline */
1377 p->procinfo->num_vcores += num;
1378 for (int i = 0; i < num; i++) {
1379 /* Try from the bulk list first */
1380 if (__proc_give_a_pcore(p, pc_arr[i], &p->bulk_preempted_vcs, 0))
1382 /* o/w, try from the inactive list. at one point, i thought there might
1383 * be a legit way in which the inactive list could be empty, but that i
1384 * wanted to catch it via an assert. */
1385 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, 0));
1387 __seq_end_write(&p->procinfo->coremap_seqctr);
1390 static void __proc_give_cores_running(struct proc *p, uint32_t *pc_arr,
1394 /* Up the refcnt, since num cores are going to start using this
1395 * process and have it loaded in their owning_proc and 'current'. */
1396 proc_incref(p, num * 2); /* keep in sync with __startcore */
1397 __seq_start_write(&p->procinfo->coremap_seqctr);
1398 p->procinfo->num_vcores += num;
1399 assert(TAILQ_EMPTY(&p->bulk_preempted_vcs));
1400 for (int i = 0; i < num; i++) {
1401 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, &vc_i));
1402 send_kernel_message(pc_arr[i], __startcore, (long)p,
1403 (long)vcore2vcoreid(p, vc_i),
1404 (long)vc_i->nr_preempts_sent, KMSG_ROUTINE);
1406 __seq_end_write(&p->procinfo->coremap_seqctr);
1409 /* Gives process p the additional num cores listed in pcorelist. If the proc is
1410 * not RUNNABLE_M or RUNNING_M, this will fail and allocate none of the core
1411 * (and return -1). If you're RUNNING_M, this will startup your new cores at
1412 * the entry point with their virtual IDs (or restore a preemption). If you're
1413 * RUNNABLE_M, you should call __proc_run_m after this so that the process can
1414 * start to use its cores. In either case, this returns 0.
1416 * If you're *_S, make sure your core0's TF is set (which is done when coming in
1417 * via arch/trap.c and we are RUNNING_S), change your state, then call this.
1418 * Then call __proc_run_m().
1420 * The reason I didn't bring the _S cases from core_request over here is so we
1421 * can keep this family of calls dealing with only *_Ms, to avoiding caring if
1422 * this is called from another core, and to avoid the _S -> _M transition.
1424 * WARNING: You must hold the proc_lock before calling this! */
1425 int __proc_give_cores(struct proc *p, uint32_t *pc_arr, uint32_t num)
1427 /* should never happen: */
1428 assert(num + p->procinfo->num_vcores <= MAX_NUM_CPUS);
1430 case (PROC_RUNNABLE_S):
1431 case (PROC_RUNNING_S):
1432 warn("Don't give cores to a process in a *_S state!\n");
1435 case (PROC_WAITING):
1436 /* can't accept, just fail */
1438 case (PROC_RUNNABLE_M):
1439 __proc_give_cores_runnable(p, pc_arr, num);
1441 case (PROC_RUNNING_M):
1442 __proc_give_cores_running(p, pc_arr, num);
1445 panic("Weird state(%s) in %s()", procstate2str(p->state),
1448 /* TODO: considering moving to the ksched (hard, due to yield) */
1449 p->procinfo->res_grant[RES_CORES] += num;
1453 /********** Core revocation (bulk and single) ***********/
1455 /* Revokes a single vcore from a process (unmaps or sends a KMSG to unmap). */
1456 static void __proc_revoke_core(struct proc *p, uint32_t vcoreid, bool preempt)
1458 uint32_t pcoreid = get_pcoreid(p, vcoreid);
1459 struct preempt_data *vcpd;
1461 /* Lock the vcore's state (necessary for preemption recovery) */
1462 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1463 atomic_or(&vcpd->flags, VC_K_LOCK);
1464 send_kernel_message(pcoreid, __preempt, (long)p, 0, 0, KMSG_ROUTINE);
1466 send_kernel_message(pcoreid, __death, 0, 0, 0, KMSG_ROUTINE);
1470 /* Revokes all cores from the process (unmaps or sends a KMSGS). */
1471 static void __proc_revoke_allcores(struct proc *p, bool preempt)
1474 /* TODO: if we ever get broadcast messaging, use it here (still need to lock
1475 * the vcores' states for preemption) */
1476 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1477 __proc_revoke_core(p, vcore2vcoreid(p, vc_i), preempt);
1480 /* Might be faster to scan the vcoremap than to walk the list... */
1481 static void __proc_unmap_allcores(struct proc *p)
1484 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1485 __unmap_vcore(p, vcore2vcoreid(p, vc_i));
1488 /* Takes (revoke via kmsg or unmap) from process p the num cores listed in
1489 * pc_arr. Will preempt if 'preempt' is set. o/w, no state will be saved, etc.
1490 * Don't use this for taking all of a process's cores.
1492 * Make sure you hold the lock when you call this, and make sure that the pcore
1493 * actually belongs to the proc, non-trivial due to other __preempt messages. */
1494 void __proc_take_corelist(struct proc *p, uint32_t *pc_arr, uint32_t num,
1499 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1500 __seq_start_write(&p->procinfo->coremap_seqctr);
1501 for (int i = 0; i < num; i++) {
1502 vcoreid = get_vcoreid(p, pc_arr[i]);
1504 assert(pc_arr[i] == get_pcoreid(p, vcoreid));
1505 /* Revoke / unmap core */
1506 if (p->state == PROC_RUNNING_M)
1507 __proc_revoke_core(p, vcoreid, preempt);
1508 __unmap_vcore(p, vcoreid);
1509 /* Change lists for the vcore. Note, the vcore is already unmapped
1510 * and/or the messages are already in flight. The only code that looks
1511 * at the lists without holding the lock is event code. */
1512 vc = vcoreid2vcore(p, vcoreid);
1513 TAILQ_REMOVE(&p->online_vcs, vc, list);
1514 /* even for single preempts, we use the inactive list. bulk preempt is
1515 * only used for when we take everything. */
1516 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1518 p->procinfo->num_vcores -= num;
1519 __seq_end_write(&p->procinfo->coremap_seqctr);
1520 p->procinfo->res_grant[RES_CORES] -= num;
1523 /* Takes all cores from a process (revoke via kmsg or unmap), putting them on
1524 * the appropriate vcore list, and fills pc_arr with the pcores revoked, and
1525 * returns the number of entries in pc_arr.
1527 * Make sure pc_arr is big enough to handle num_vcores().
1528 * Make sure you hold the lock when you call this. */
1529 uint32_t __proc_take_allcores(struct proc *p, uint32_t *pc_arr, bool preempt)
1531 struct vcore *vc_i, *vc_temp;
1533 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1534 __seq_start_write(&p->procinfo->coremap_seqctr);
1535 /* Write out which pcores we're going to take */
1536 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1537 pc_arr[num++] = vc_i->pcoreid;
1538 /* Revoke if they are running, and unmap. Both of these need the online
1539 * list to not be changed yet. */
1540 if (p->state == PROC_RUNNING_M)
1541 __proc_revoke_allcores(p, preempt);
1542 __proc_unmap_allcores(p);
1543 /* Move the vcores from online to the head of the appropriate list */
1544 TAILQ_FOREACH_SAFE(vc_i, &p->online_vcs, list, vc_temp) {
1545 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that */
1546 TAILQ_REMOVE(&p->online_vcs, vc_i, list);
1547 /* Put the cores on the appropriate list */
1549 TAILQ_INSERT_HEAD(&p->bulk_preempted_vcs, vc_i, list);
1551 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
1553 assert(TAILQ_EMPTY(&p->online_vcs));
1554 assert(num == p->procinfo->num_vcores);
1555 p->procinfo->num_vcores = 0;
1556 __seq_end_write(&p->procinfo->coremap_seqctr);
1557 p->procinfo->res_grant[RES_CORES] = 0;
1561 /* Helper to do the vcore->pcore and inverse mapping. Hold the lock when
1563 void __map_vcore(struct proc *p, uint32_t vcoreid, uint32_t pcoreid)
1565 p->procinfo->vcoremap[vcoreid].pcoreid = pcoreid;
1566 p->procinfo->vcoremap[vcoreid].valid = TRUE;
1567 p->procinfo->pcoremap[pcoreid].vcoreid = vcoreid;
1568 p->procinfo->pcoremap[pcoreid].valid = TRUE;
1571 /* Helper to unmap the vcore->pcore and inverse mapping. Hold the lock when
1573 void __unmap_vcore(struct proc *p, uint32_t vcoreid)
1575 p->procinfo->pcoremap[p->procinfo->vcoremap[vcoreid].pcoreid].valid = FALSE;
1576 p->procinfo->vcoremap[vcoreid].valid = FALSE;
1579 /* Stop running whatever context is on this core and load a known-good cr3.
1580 * Note this leaves no trace of what was running. This "leaves the process's
1583 * This does not clear the owning proc. Use the other helper for that. */
1584 void abandon_core(void)
1586 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1587 /* Syscalls that don't return will ultimately call abadon_core(), so we need
1588 * to make sure we don't think we are still working on a syscall. */
1589 pcpui->cur_sysc = 0;
1590 if (pcpui->cur_proc)
1594 /* Helper to clear the core's owning processor and manage refcnting. Pass in
1595 * core_id() to save a couple core_id() calls. */
1596 void clear_owning_proc(uint32_t coreid)
1598 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1599 struct proc *p = pcpui->owning_proc;
1600 pcpui->owning_proc = 0;
1601 pcpui->owning_vcoreid = 0xdeadbeef;
1602 pcpui->cur_tf = 0; /* catch bugs for now (will go away soon) */
1607 /* Switches to the address space/context of new_p, doing nothing if we are
1608 * already in new_p. This won't add extra refcnts or anything, and needs to be
1609 * paired with switch_back() at the end of whatever function you are in. Don't
1610 * migrate cores in the middle of a pair. Specifically, the uncounted refs are
1611 * one for the old_proc, which is passed back to the caller, and new_p is
1612 * getting placed in cur_proc. */
1613 struct proc *switch_to(struct proc *new_p)
1615 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1616 struct proc *old_proc;
1617 old_proc = pcpui->cur_proc; /* uncounted ref */
1618 /* If we aren't the proc already, then switch to it */
1619 if (old_proc != new_p) {
1620 pcpui->cur_proc = new_p; /* uncounted ref */
1621 lcr3(new_p->env_cr3);
1626 /* This switches back to old_proc from new_p. Pair it with switch_to(), and
1627 * pass in its return value for old_proc. */
1628 void switch_back(struct proc *new_p, struct proc *old_proc)
1630 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1631 if (old_proc != new_p) {
1632 pcpui->cur_proc = old_proc;
1634 lcr3(old_proc->env_cr3);
1640 /* Will send a TLB shootdown message to every vcore in the main address space
1641 * (aka, all vcores for now). The message will take the start and end virtual
1642 * addresses as well, in case we want to be more clever about how much we
1643 * shootdown and batching our messages. Should do the sanity about rounding up
1644 * and down in this function too.
1646 * Would be nice to have a broadcast kmsg at this point. Note this may send a
1647 * message to the calling core (interrupting it, possibly while holding the
1648 * proc_lock). We don't need to process routine messages since it's an
1649 * immediate message. */
1650 void proc_tlbshootdown(struct proc *p, uintptr_t start, uintptr_t end)
1653 /* TODO: we might be able to avoid locking here in the future (we must hit
1654 * all online, and we can check __mapped). it'll be complicated. */
1655 spin_lock(&p->proc_lock);
1657 case (PROC_RUNNING_S):
1660 case (PROC_RUNNING_M):
1661 /* TODO: (TLB) sanity checks and rounding on the ranges */
1662 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
1663 send_kernel_message(vc_i->pcoreid, __tlbshootdown, start, end,
1668 /* if it is dying, death messages are already on the way to all
1669 * cores, including ours, which will clear the TLB. */
1672 /* will probably get this when we have the short handlers */
1673 warn("Unexpected case %s in %s", procstate2str(p->state),
1676 spin_unlock(&p->proc_lock);
1679 /* Helper, used by __startcore and __set_curtf, which sets up cur_tf to run a
1680 * given process's vcore. Caller needs to set up things like owning_proc and
1681 * whatnot. Note that we might not have p loaded as current. */
1682 static void __set_curtf_to_vcoreid(struct proc *p, uint32_t vcoreid,
1683 uint32_t old_nr_preempts_sent)
1685 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1686 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1687 struct vcore *vc = vcoreid2vcore(p, vcoreid);
1688 /* Spin until our vcore's old preemption is done. When __SC was sent, we
1689 * were told what the nr_preempts_sent was at that time. Once that many are
1690 * done, it is time for us to run. This forces a 'happens-before' ordering
1691 * on a __PR of our VC before this __SC of the VC. Note the nr_done should
1692 * not exceed old_nr_sent, since further __PR are behind this __SC in the
1694 while (old_nr_preempts_sent != vc->nr_preempts_done)
1696 cmb(); /* read nr_done before any other rd or wr. CPU mb in the atomic. */
1697 /* Mark that this vcore as no longer preempted. No danger of clobbering
1698 * other writes, since this would get turned on in __preempt (which can't be
1699 * concurrent with this function on this core), and the atomic is just
1700 * toggling the one bit (a concurrent VC_K_LOCK will work) */
1701 atomic_and(&vcpd->flags, ~VC_PREEMPTED);
1702 /* Once the VC is no longer preempted, we allow it to receive msgs. We
1703 * could let userspace do it, but handling it here makes it easier for them
1704 * to handle_indirs (when they turn this flag off). Note the atomics
1705 * provide the needed barriers (cmb and mb on flags). */
1706 atomic_or(&vcpd->flags, VC_CAN_RCV_MSG);
1707 printd("[kernel] startcore on physical core %d for process %d's vcore %d\n",
1708 core_id(), p->pid, vcoreid);
1709 /* If notifs are disabled, the vcore was in vcore context and we need to
1710 * restart the preempt_tf. o/w, we give them a fresh vcore (which is also
1711 * what happens the first time a vcore comes online). No matter what,
1712 * they'll restart in vcore context. It's just a matter of whether or not
1713 * it is the old, interrupted vcore context. */
1714 if (vcpd->notif_disabled) {
1715 restore_fp_state(&vcpd->preempt_anc);
1716 /* copy-in the tf we'll pop, then set all security-related fields */
1717 pcpui->actual_tf = vcpd->preempt_tf;
1718 proc_secure_trapframe(&pcpui->actual_tf);
1719 } else { /* not restarting from a preemption, use a fresh vcore */
1720 assert(vcpd->transition_stack);
1721 /* TODO: consider 0'ing the FP state. We're probably leaking. */
1722 proc_init_trapframe(&pcpui->actual_tf, vcoreid, p->env_entry,
1723 vcpd->transition_stack);
1724 /* Disable/mask active notifications for fresh vcores */
1725 vcpd->notif_disabled = TRUE;
1727 /* cur_tf was built above (in actual_tf), now use it */
1728 pcpui->cur_tf = &pcpui->actual_tf;
1729 /* this cur_tf will get run when the kernel returns / idles */
1732 /* Changes calling vcore to be vcoreid. enable_my_notif tells us about how the
1733 * state calling vcore wants to be left in. It will look like caller_vcoreid
1734 * was preempted. Note we don't care about notif_pending.
1737 * 0 if we successfully changed to the target vcore.
1738 * -EBUSY if the target vcore is already mapped (a good kind of failure)
1739 * -EAGAIN if we failed for some other reason and need to try again. For
1740 * example, the caller could be preempted, and we never even attempted to
1742 * -EINVAL some userspace bug */
1743 int proc_change_to_vcore(struct proc *p, uint32_t new_vcoreid,
1744 bool enable_my_notif)
1746 uint32_t caller_vcoreid, pcoreid = core_id();
1747 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1748 struct preempt_data *caller_vcpd;
1749 struct vcore *caller_vc, *new_vc;
1750 struct event_msg preempt_msg = {0};
1751 int retval = -EAGAIN; /* by default, try again */
1752 /* Need to not reach outside the vcoremap, which might be smaller in the
1753 * future, but should always be as big as max_vcores */
1754 if (new_vcoreid >= p->procinfo->max_vcores)
1756 /* Need to lock to prevent concurrent vcore changes, like in yield. */
1757 spin_lock(&p->proc_lock);
1758 /* new_vcoreid is already runing, abort */
1759 if (vcore_is_mapped(p, new_vcoreid)) {
1763 /* Need to make sure our vcore is allowed to switch. We might have a
1764 * __preempt, __death, etc, coming in. Similar to yield. */
1766 case (PROC_RUNNING_M):
1767 break; /* the only case we can proceed */
1768 case (PROC_RUNNING_S): /* user bug, just return */
1769 case (PROC_DYING): /* incoming __death */
1770 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1773 panic("Weird state(%s) in %s()", procstate2str(p->state),
1776 /* This is which vcore this pcore thinks it is, regardless of any unmappings
1777 * that may have happened remotely (with __PRs waiting to run) */
1778 caller_vcoreid = pcpui->owning_vcoreid;
1779 caller_vc = vcoreid2vcore(p, caller_vcoreid);
1780 caller_vcpd = &p->procdata->vcore_preempt_data[caller_vcoreid];
1781 /* This is how we detect whether or not a __PR happened. If it did, just
1782 * abort and handle the kmsg. No new __PRs are coming since we hold the
1783 * lock. This also detects a __PR followed by a __SC for the same VC. */
1784 if (caller_vc->nr_preempts_sent != caller_vc->nr_preempts_done)
1786 /* Sanity checks. If we were preempted or are dying, we should have noticed
1788 assert(is_mapped_vcore(p, pcoreid));
1789 assert(caller_vcoreid == get_vcoreid(p, pcoreid));
1790 /* Should only call from vcore context */
1791 if (!caller_vcpd->notif_disabled) {
1793 printk("[kernel] You tried to change vcores from uthread ctx\n");
1796 /* Ok, we're clear to do the switch. Lets figure out who the new one is */
1797 new_vc = vcoreid2vcore(p, new_vcoreid);
1798 printd("[kernel] changing vcore %d to vcore %d\n", caller_vcoreid,
1800 /* enable_my_notif signals how we'll be restarted */
1801 if (enable_my_notif) {
1802 /* if they set this flag, then the vcore can just restart from scratch,
1803 * and we don't care about either the notif_tf or the preempt_tf. */
1804 caller_vcpd->notif_disabled = FALSE;
1806 /* need to set up the calling vcore's tf so that it'll get restarted by
1807 * __startcore, to make the caller look like it was preempted. */
1808 caller_vcpd->preempt_tf = *current_tf;
1809 save_fp_state(&caller_vcpd->preempt_anc);
1810 /* Mark our core as preempted (for userspace recovery). */
1811 atomic_or(&caller_vcpd->flags, VC_PREEMPTED);
1813 /* Either way, unmap and offline our current vcore */
1814 /* Move the caller from online to inactive */
1815 TAILQ_REMOVE(&p->online_vcs, caller_vc, list);
1816 /* We don't bother with the notif_pending race. note that notif_pending
1817 * could still be set. this was a preempted vcore, and userspace will need
1818 * to deal with missed messages (preempt_recover() will handle that) */
1819 TAILQ_INSERT_HEAD(&p->inactive_vcs, caller_vc, list);
1820 /* Move the new one from inactive to online */
1821 TAILQ_REMOVE(&p->inactive_vcs, new_vc, list);
1822 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1823 /* Change the vcore map */
1824 __seq_start_write(&p->procinfo->coremap_seqctr);
1825 __unmap_vcore(p, caller_vcoreid);
1826 __map_vcore(p, new_vcoreid, pcoreid);
1827 __seq_end_write(&p->procinfo->coremap_seqctr);
1828 /* Send either a PREEMPT msg or a CHECK_MSGS msg. If they said to
1829 * enable_my_notif, then all userspace needs is to check messages, not a
1830 * full preemption recovery. */
1831 preempt_msg.ev_type = (enable_my_notif ? EV_CHECK_MSGS : EV_VCORE_PREEMPT);
1832 preempt_msg.ev_arg2 = caller_vcoreid; /* arg2 is 32 bits */
1833 /* Whenever we send msgs with the proc locked, we need at least 1 online.
1834 * In this case, it's the one we just changed to. */
1835 assert(!TAILQ_EMPTY(&p->online_vcs));
1836 send_kernel_event(p, &preempt_msg, new_vcoreid);
1837 /* So this core knows which vcore is here. (cur_proc and owning_proc are
1838 * already correct): */
1839 pcpui->owning_vcoreid = new_vcoreid;
1840 /* Until we set_curtf, we don't really have a valid current tf. The stuff
1841 * in that old one is from our previous vcore, not the current
1842 * owning_vcoreid. This matters for other KMSGS that will run before
1843 * __set_curtf (like __notify). */
1845 /* Need to send a kmsg to finish. We can't set_curtf til the __PR is done,
1846 * but we can't spin right here while holding the lock (can't spin while
1847 * waiting on a message, roughly) */
1848 send_kernel_message(pcoreid, __set_curtf, (long)p, (long)new_vcoreid,
1849 (long)new_vc->nr_preempts_sent, KMSG_ROUTINE);
1851 /* Fall through to exit */
1853 spin_unlock(&p->proc_lock);
1857 /* Kernel message handler to start a process's context on this core, when the
1858 * core next considers running a process. Tightly coupled with __proc_run_m().
1859 * Interrupts are disabled. */
1860 void __startcore(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1862 uint32_t vcoreid = (uint32_t)a1;
1863 uint32_t coreid = core_id();
1864 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1865 struct proc *p_to_run = (struct proc *CT(1))a0;
1866 uint32_t old_nr_preempts_sent = (uint32_t)a2;
1869 /* Can not be any TF from a process here already */
1870 assert(!pcpui->owning_proc);
1871 /* the sender of the kmsg increfed already for this saved ref to p_to_run */
1872 pcpui->owning_proc = p_to_run;
1873 pcpui->owning_vcoreid = vcoreid;
1874 /* sender increfed again, assuming we'd install to cur_proc. only do this
1875 * if no one else is there. this is an optimization, since we expect to
1876 * send these __startcores to idles cores, and this saves a scramble to
1877 * incref when all of the cores restartcore/startcore later. Keep in sync
1878 * with __proc_give_cores() and __proc_run_m(). */
1879 if (!pcpui->cur_proc) {
1880 pcpui->cur_proc = p_to_run; /* install the ref to cur_proc */
1881 lcr3(p_to_run->env_cr3); /* load the page tables to match cur_proc */
1883 proc_decref(p_to_run); /* can't install, decref the extra one */
1885 /* Note we are not necessarily in the cr3 of p_to_run */
1886 /* Now that we sorted refcnts and know p / which vcore it should be, set up
1887 * pcpui->cur_tf so that it will run that particular vcore */
1888 __set_curtf_to_vcoreid(p_to_run, vcoreid, old_nr_preempts_sent);
1891 /* Kernel message handler to load a proc's vcore context on this core. Similar
1892 * to __startcore, except it is used when p already controls the core (e.g.
1893 * change_to). Since the core is already controlled, pcpui such as owning proc,
1894 * vcoreid, and cur_proc are all already set. */
1895 void __set_curtf(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1897 struct proc *p = (struct proc*)a0;
1898 uint32_t vcoreid = (uint32_t)a1;
1899 uint32_t old_nr_preempts_sent = (uint32_t)a2;
1900 __set_curtf_to_vcoreid(p, vcoreid, old_nr_preempts_sent);
1903 /* Bail out if it's the wrong process, or if they no longer want a notif. Don't
1904 * use the TF we passed in, we care about cur_tf. Try not to grab locks or
1905 * write access to anything that isn't per-core in here. */
1906 void __notify(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1908 uint32_t vcoreid, coreid = core_id();
1909 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1910 struct preempt_data *vcpd;
1911 struct proc *p = (struct proc*)a0;
1913 /* Not the right proc */
1914 if (p != pcpui->owning_proc)
1916 /* the core might be owned, but not have a valid cur_tf (if we're in the
1917 * process of changing */
1920 /* Common cur_tf sanity checks. Note cur_tf could be an _S's env_tf */
1921 assert(!in_kernel(pcpui->cur_tf));
1922 vcoreid = pcpui->owning_vcoreid;
1923 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1924 /* for SCPs that haven't (and might never) call vc_event_init, like rtld.
1925 * this is harmless for MCPS to check this */
1926 if (!scp_is_vcctx_ready(vcpd))
1928 printd("received active notification for proc %d's vcore %d on pcore %d\n",
1929 p->procinfo->pid, vcoreid, coreid);
1930 /* sort signals. notifs are now masked, like an interrupt gate */
1931 if (vcpd->notif_disabled)
1933 vcpd->notif_disabled = TRUE;
1934 /* save the old tf in the notify slot, build and pop a new one. Note that
1935 * silly state isn't our business for a notification. */
1936 vcpd->notif_tf = *pcpui->cur_tf;
1937 memset(pcpui->cur_tf, 0, sizeof(struct trapframe));
1938 proc_init_trapframe(pcpui->cur_tf, vcoreid, p->env_entry,
1939 vcpd->transition_stack);
1940 /* this cur_tf will get run when the kernel returns / idles */
1943 void __preempt(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1945 uint32_t vcoreid, coreid = core_id();
1946 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1947 struct preempt_data *vcpd;
1948 struct proc *p = (struct proc*)a0;
1951 if (p != pcpui->owning_proc) {
1952 panic("__preempt arrived for a process (%p) that was not owning (%p)!",
1953 p, pcpui->owning_proc);
1955 /* Common cur_tf sanity checks */
1956 assert(pcpui->cur_tf);
1957 assert(pcpui->cur_tf == &pcpui->actual_tf);
1958 assert(!in_kernel(pcpui->cur_tf));
1959 vcoreid = pcpui->owning_vcoreid;
1960 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1961 printd("[kernel] received __preempt for proc %d's vcore %d on pcore %d\n",
1962 p->procinfo->pid, vcoreid, coreid);
1963 /* if notifs are disabled, the vcore is in vcore context (as far as we're
1964 * concerned), and we save it in the preempt slot. o/w, we save the
1965 * process's cur_tf in the notif slot, and it'll appear to the vcore when it
1966 * comes back up that it just took a notification. */
1967 if (vcpd->notif_disabled)
1968 vcpd->preempt_tf = *pcpui->cur_tf;
1970 vcpd->notif_tf = *pcpui->cur_tf;
1971 /* either way, we save the silly state (FP) */
1972 save_fp_state(&vcpd->preempt_anc);
1973 /* Mark the vcore as preempted and unlock (was locked by the sender). */
1974 atomic_or(&vcpd->flags, VC_PREEMPTED);
1975 atomic_and(&vcpd->flags, ~VC_K_LOCK);
1976 /* either __preempt or proc_yield() ends the preempt phase. */
1977 p->procinfo->vcoremap[vcoreid].preempt_pending = 0;
1978 wmb(); /* make sure everything else hits before we finish the preempt */
1979 /* up the nr_done, which signals the next __startcore for this vc */
1980 p->procinfo->vcoremap[vcoreid].nr_preempts_done++;
1981 /* We won't restart the process later. current gets cleared later when we
1982 * notice there is no owning_proc and we have nothing to do (smp_idle,
1983 * restartcore, etc) */
1984 clear_owning_proc(coreid);
1987 /* Kernel message handler to clean up the core when a process is dying.
1988 * Note this leaves no trace of what was running.
1989 * It's okay if death comes to a core that's already idling and has no current.
1990 * It could happen if a process decref'd before __proc_startcore could incref. */
1991 void __death(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1993 uint32_t vcoreid, coreid = core_id();
1994 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1995 struct proc *p = pcpui->owning_proc;
1997 vcoreid = pcpui->owning_vcoreid;
1998 printd("[kernel] death on physical core %d for process %d's vcore %d\n",
1999 coreid, p->pid, vcoreid);
2000 /* We won't restart the process later. current gets cleared later when
2001 * we notice there is no owning_proc and we have nothing to do
2002 * (smp_idle, restartcore, etc) */
2003 clear_owning_proc(coreid);
2007 /* Kernel message handler, usually sent IMMEDIATE, to shoot down virtual
2008 * addresses from a0 to a1. */
2009 void __tlbshootdown(struct trapframe *tf, uint32_t srcid, long a0, long a1,
2012 /* TODO: (TLB) something more intelligent with the range */
2016 void print_allpids(void)
2018 void print_proc_state(void *item)
2020 struct proc *p = (struct proc*)item;
2022 printk("%8d %-10s %6d\n", p->pid, procstate2str(p->state), p->ppid);
2024 printk(" PID STATE Parent \n");
2025 printk("------------------------------\n");
2026 spin_lock(&pid_hash_lock);
2027 hash_for_each(pid_hash, print_proc_state);
2028 spin_unlock(&pid_hash_lock);
2031 void print_proc_info(pid_t pid)
2034 struct proc *child, *p = pid2proc(pid);
2037 printk("Bad PID.\n");
2040 spinlock_debug(&p->proc_lock);
2041 //spin_lock(&p->proc_lock); // No locking!!
2042 printk("struct proc: %p\n", p);
2043 printk("PID: %d\n", p->pid);
2044 printk("PPID: %d\n", p->ppid);
2045 printk("State: %s (%p)\n", procstate2str(p->state), p->state);
2046 printk("Refcnt: %d\n", atomic_read(&p->p_kref.refcount) - 1);
2047 printk("Flags: 0x%08x\n", p->env_flags);
2048 printk("CR3(phys): 0x%08x\n", p->env_cr3);
2049 printk("Num Vcores: %d\n", p->procinfo->num_vcores);
2050 printk("Vcore Lists (may be in flux w/o locking):\n----------------------\n");
2051 printk("Online:\n");
2052 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
2053 printk("\tVcore %d -> Pcore %d\n", vcore2vcoreid(p, vc_i), vc_i->pcoreid);
2054 printk("Bulk Preempted:\n");
2055 TAILQ_FOREACH(vc_i, &p->bulk_preempted_vcs, list)
2056 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2057 printk("Inactive / Yielded:\n");
2058 TAILQ_FOREACH(vc_i, &p->inactive_vcs, list)
2059 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2060 printk("Resources:\n------------------------\n");
2061 for (int i = 0; i < MAX_NUM_RESOURCES; i++)
2062 printk("\tRes type: %02d, amt wanted: %08d, amt granted: %08d\n", i,
2063 p->procdata->res_req[i].amt_wanted, p->procinfo->res_grant[i]);
2064 printk("Open Files:\n");
2065 struct files_struct *files = &p->open_files;
2066 spin_lock(&files->lock);
2067 for (int i = 0; i < files->max_files; i++)
2068 if (files->fd_array[i].fd_file) {
2069 printk("\tFD: %02d, File: %08p, File name: %s\n", i,
2070 files->fd_array[i].fd_file,
2071 file_name(files->fd_array[i].fd_file));
2073 spin_unlock(&files->lock);
2074 printk("Children: (PID (struct proc *))\n");
2075 TAILQ_FOREACH(child, &p->children, sibling_link)
2076 printk("\t%d (%08p)\n", child->pid, child);
2077 /* no locking / unlocking or refcnting */
2078 // spin_unlock(&p->proc_lock);
2082 /* Debugging function, checks what (process, vcore) is supposed to run on this
2083 * pcore. Meant to be called from smp_idle() before halting. */
2084 void check_my_owner(void)
2086 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2087 void shazbot(void *item)
2089 struct proc *p = (struct proc*)item;
2092 spin_lock(&p->proc_lock);
2093 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
2094 /* this isn't true, a __startcore could be on the way and we're
2095 * already "online" */
2096 if (vc_i->pcoreid == core_id()) {
2097 /* Immediate message was sent, we should get it when we enable
2098 * interrupts, which should cause us to skip cpu_halt() */
2099 if (!STAILQ_EMPTY(&pcpui->immed_amsgs))
2101 printk("Owned pcore (%d) has no owner, by %08p, vc %d!\n",
2102 core_id(), p, vcore2vcoreid(p, vc_i));
2103 spin_unlock(&p->proc_lock);
2104 spin_unlock(&pid_hash_lock);
2108 spin_unlock(&p->proc_lock);
2110 assert(!irq_is_enabled());
2112 if (!booting && !pcpui->owning_proc) {
2113 spin_lock(&pid_hash_lock);
2114 hash_for_each(pid_hash, shazbot);
2115 spin_unlock(&pid_hash_lock);