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 /* only one ref, which we pass back. the old 'existence' ref is managed by
235 kref_init(&p->p_kref, __proc_free, 1);
236 // Setup the default map of where to get cache colors from
237 p->cache_colors_map = global_cache_colors_map;
238 p->next_cache_color = 0;
239 /* Initialize the address space */
240 if ((r = env_setup_vm(p)) < 0) {
241 kmem_cache_free(proc_cache, p);
244 if (!(p->pid = get_free_pid())) {
245 kmem_cache_free(proc_cache, p);
248 /* Set the basic status variables. */
249 spinlock_init(&p->proc_lock);
250 p->exitcode = 1337; /* so we can see processes killed by the kernel */
251 init_sem(&p->state_change, 0);
252 p->ppid = parent ? parent->pid : 0;
253 p->state = PROC_CREATED; /* shouldn't go through state machine for init */
255 p->env_entry = 0; // cheating. this really gets set later
256 p->heap_top = (void*)UTEXT; /* heap_bottom set in proc_init_procinfo */
257 memset(&p->env_ancillary_state, 0, sizeof(p->env_ancillary_state));
258 memset(&p->env_tf, 0, sizeof(p->env_tf));
259 spinlock_init(&p->mm_lock);
260 TAILQ_INIT(&p->vm_regions); /* could init this in the slab */
261 /* Initialize the vcore lists, we'll build the inactive list so that it includes
262 * all vcores when we initialize procinfo. Do this before initing procinfo. */
263 TAILQ_INIT(&p->online_vcs);
264 TAILQ_INIT(&p->bulk_preempted_vcs);
265 TAILQ_INIT(&p->inactive_vcs);
266 /* Init procinfo/procdata. Procinfo's argp/argb are 0'd */
267 proc_init_procinfo(p);
268 proc_init_procdata(p);
270 /* Initialize the generic sysevent ring buffer */
271 SHARED_RING_INIT(&p->procdata->syseventring);
272 /* Initialize the frontend of the sysevent ring buffer */
273 FRONT_RING_INIT(&p->syseventfrontring,
274 &p->procdata->syseventring,
277 /* Init FS structures TODO: cleanup (might pull this out) */
278 kref_get(&default_ns.kref, 1);
280 spinlock_init(&p->fs_env.lock);
281 p->fs_env.umask = parent ? parent->fs_env.umask : S_IWGRP | S_IWOTH;
282 p->fs_env.root = p->ns->root->mnt_root;
283 kref_get(&p->fs_env.root->d_kref, 1);
284 p->fs_env.pwd = parent ? parent->fs_env.pwd : p->fs_env.root;
285 kref_get(&p->fs_env.pwd->d_kref, 1);
286 memset(&p->open_files, 0, sizeof(p->open_files)); /* slightly ghetto */
287 spinlock_init(&p->open_files.lock);
288 p->open_files.max_files = NR_OPEN_FILES_DEFAULT;
289 p->open_files.max_fdset = NR_FILE_DESC_DEFAULT;
290 p->open_files.fd = p->open_files.fd_array;
291 p->open_files.open_fds = (struct fd_set*)&p->open_files.open_fds_init;
292 /* Init the ucq hash lock */
293 p->ucq_hashlock = (struct hashlock*)&p->ucq_hl_noref;
294 hashlock_init(p->ucq_hashlock, HASHLOCK_DEFAULT_SZ);
296 atomic_inc(&num_envs);
297 frontend_proc_init(p);
298 printd("[%08x] new process %08x\n", current ? current->pid : 0, p->pid);
304 /* We have a bunch of different ways to make processes. Call this once the
305 * process is ready to be used by the rest of the system. For now, this just
306 * means when it is ready to be named via the pidhash. In the future, we might
307 * push setting the state to CREATED into here. */
308 void __proc_ready(struct proc *p)
310 /* Tell the ksched about us. TODO: do we need to worry about the ksched
311 * doing stuff to us before we're added to the pid_hash? */
312 __sched_proc_register(p);
313 spin_lock(&pid_hash_lock);
314 hashtable_insert(pid_hash, (void*)(long)p->pid, p);
315 spin_unlock(&pid_hash_lock);
318 /* Creates a process from the specified file, argvs, and envps. Tempted to get
319 * rid of proc_alloc's style, but it is so quaint... */
320 struct proc *proc_create(struct file *prog, char **argv, char **envp)
324 if ((r = proc_alloc(&p, current)) < 0)
325 panic("proc_create: %e", r); /* one of 3 quaint usages of %e */
326 procinfo_pack_args(p->procinfo, argv, envp);
327 assert(load_elf(p, prog) == 0);
328 /* Connect to stdin, stdout, stderr */
329 assert(insert_file(&p->open_files, dev_stdin, 0) == 0);
330 assert(insert_file(&p->open_files, dev_stdout, 0) == 1);
331 assert(insert_file(&p->open_files, dev_stderr, 0) == 2);
336 /* This is called by kref_put(), once the last reference to the process is
337 * gone. Don't call this otherwise (it will panic). It will clean up the
338 * address space and deallocate any other used memory. */
339 static void __proc_free(struct kref *kref)
341 struct proc *p = container_of(kref, struct proc, p_kref);
344 printd("[PID %d] freeing proc: %d\n", current ? current->pid : 0, p->pid);
345 // All parts of the kernel should have decref'd before __proc_free is called
346 assert(kref_refcnt(&p->p_kref) == 0);
348 kref_put(&p->fs_env.root->d_kref);
349 kref_put(&p->fs_env.pwd->d_kref);
351 frontend_proc_free(p); /* TODO: please remove me one day */
352 /* Free any colors allocated to this process */
353 if (p->cache_colors_map != global_cache_colors_map) {
354 for(int i = 0; i < llc_cache->num_colors; i++)
355 cache_color_free(llc_cache, p->cache_colors_map);
356 cache_colors_map_free(p->cache_colors_map);
358 /* Remove us from the pid_hash and give our PID back (in that order). */
359 spin_lock(&pid_hash_lock);
360 if (!hashtable_remove(pid_hash, (void*)(long)p->pid))
361 panic("Proc not in the pid table in %s", __FUNCTION__);
362 spin_unlock(&pid_hash_lock);
363 put_free_pid(p->pid);
364 /* Flush all mapped pages in the user portion of the address space */
365 env_user_mem_free(p, 0, UVPT);
366 /* These need to be free again, since they were allocated with a refcnt. */
367 free_cont_pages(p->procinfo, LOG2_UP(PROCINFO_NUM_PAGES));
368 free_cont_pages(p->procdata, LOG2_UP(PROCDATA_NUM_PAGES));
370 env_pagetable_free(p);
374 atomic_dec(&num_envs);
376 /* Dealloc the struct proc */
377 kmem_cache_free(proc_cache, p);
380 /* Whether or not actor can control target. Note we currently don't need
381 * locking for this. TODO: think about that, esp wrt proc's dying. */
382 bool proc_controls(struct proc *actor, struct proc *target)
384 return ((actor == target) || (target->ppid == actor->pid));
387 /* Helper to incref by val. Using the helper to help debug/interpose on proc
388 * ref counting. Note that pid2proc doesn't use this interface. */
389 void proc_incref(struct proc *p, unsigned int val)
391 kref_get(&p->p_kref, val);
394 /* Helper to decref for debugging. Don't directly kref_put() for now. */
395 void proc_decref(struct proc *p)
397 kref_put(&p->p_kref);
400 /* Helper, makes p the 'current' process, dropping the old current/cr3. This no
401 * longer assumes the passed in reference already counted 'current'. It will
402 * incref internally when needed. */
403 static void __set_proc_current(struct proc *p)
405 /* We use the pcpui to access 'current' to cut down on the core_id() calls,
406 * though who know how expensive/painful they are. */
407 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
408 /* If the process wasn't here, then we need to load its address space. */
409 if (p != pcpui->cur_proc) {
412 /* This is "leaving the process context" of the previous proc. The
413 * previous lcr3 unloaded the previous proc's context. This should
414 * rarely happen, since we usually proactively leave process context,
415 * but this is the fallback. */
417 proc_decref(pcpui->cur_proc);
422 /* Flag says if vcore context is not ready, which is set in init_procdata. The
423 * process must turn off this flag on vcore0 at some point. It's off by default
424 * on all other vcores. */
425 static bool scp_is_vcctx_ready(struct preempt_data *vcpd)
427 return !(atomic_read(&vcpd->flags) & VC_SCP_NOVCCTX);
430 /* Dispatches a _S process to run on the current core. This should never be
431 * called to "restart" a core.
433 * This will always return, regardless of whether or not the calling core is
434 * being given to a process. (it used to pop the tf directly, before we had
437 * Since it always returns, it will never "eat" your reference (old
438 * documentation talks about this a bit). */
439 void proc_run_s(struct proc *p)
442 uint32_t coreid = core_id();
443 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
444 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
445 spin_lock(&p->proc_lock);
448 spin_unlock(&p->proc_lock);
449 printk("[kernel] _S %d not starting due to async death\n", p->pid);
451 case (PROC_RUNNABLE_S):
452 __proc_set_state(p, PROC_RUNNING_S);
453 /* We will want to know where this process is running, even if it is
454 * only in RUNNING_S. can use the vcoremap, which makes death easy.
455 * Also, this is the signal used in trap.c to know to save the tf in
457 __seq_start_write(&p->procinfo->coremap_seqctr);
458 p->procinfo->num_vcores = 0; /* TODO (VC#) */
459 /* TODO: For now, we won't count this as an active vcore (on the
460 * lists). This gets unmapped in resource.c and yield_s, and needs
462 __map_vcore(p, 0, coreid); /* not treated like a true vcore */
463 __seq_end_write(&p->procinfo->coremap_seqctr);
464 /* incref, since we're saving a reference in owning proc later */
466 /* disable interrupts to protect cur_tf, owning_proc, and current */
467 disable_irqsave(&state);
468 /* wait til ints are disabled before unlocking, in case someone else
469 * grabs the lock and IPIs us before we get set up in cur_tf */
470 spin_unlock(&p->proc_lock);
471 /* redundant with proc_startcore, might be able to remove that one*/
472 __set_proc_current(p);
473 /* set us up as owning_proc. ksched bug if there is already one,
474 * for now. can simply clear_owning if we want to. */
475 assert(!pcpui->owning_proc);
476 pcpui->owning_proc = p;
477 pcpui->owning_vcoreid = 0; /* TODO (VC#) */
478 /* TODO: (HSS) set silly state here (__startcore does it instantly) */
479 /* similar to the old __startcore, start them in vcore context if
480 * they have notifs and aren't already in vcore context. o/w, start
481 * them wherever they were before (could be either vc ctx or not) */
482 if (!vcpd->notif_disabled && vcpd->notif_pending
483 && scp_is_vcctx_ready(vcpd)) {
484 vcpd->notif_disabled = TRUE;
485 /* save the _S's tf in the notify slot, build and pop a new one
486 * in actual/cur_tf. */
487 vcpd->notif_tf = p->env_tf;
488 pcpui->cur_tf = &pcpui->actual_tf;
489 memset(pcpui->cur_tf, 0, sizeof(struct trapframe));
490 proc_init_trapframe(pcpui->cur_tf, 0, p->env_entry,
491 vcpd->transition_stack);
493 /* If they have no transition stack, then they can't receive
494 * events. The most they are getting is a wakeup from the
495 * kernel. They won't even turn off notif_pending, so we'll do
497 if (!scp_is_vcctx_ready(vcpd))
498 vcpd->notif_pending = FALSE;
499 /* this is one of the few times cur_tf != &actual_tf */
500 pcpui->cur_tf = &p->env_tf;
502 enable_irqsave(&state);
503 /* When the calling core idles, it'll call restartcore and run the
504 * _S process's context. */
507 spin_unlock(&p->proc_lock);
508 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
512 /* Helper: sends preempt messages to all vcores on the bulk preempt list, and
513 * moves them to the inactive list. */
514 static void __send_bulkp_events(struct proc *p)
516 struct vcore *vc_i, *vc_temp;
517 struct event_msg preempt_msg = {0};
518 /* Whenever we send msgs with the proc locked, we need at least 1 online */
519 assert(!TAILQ_EMPTY(&p->online_vcs));
520 /* Send preempt messages for any left on the BP list. No need to set any
521 * flags, it all was done on the real preempt. Now we're just telling the
522 * process about any that didn't get restarted and are still preempted. */
523 TAILQ_FOREACH_SAFE(vc_i, &p->bulk_preempted_vcs, list, vc_temp) {
524 /* Note that if there are no active vcores, send_k_e will post to our
525 * own vcore, the last of which will be put on the inactive list and be
526 * the first to be started. We could have issues with deadlocking,
527 * since send_k_e() could grab the proclock (if there are no active
529 preempt_msg.ev_type = EV_VCORE_PREEMPT;
530 preempt_msg.ev_arg2 = vcore2vcoreid(p, vc_i); /* arg2 is 32 bits */
531 send_kernel_event(p, &preempt_msg, 0);
532 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that.
533 * We need a loop for the messages, but not necessarily for the list
535 TAILQ_REMOVE(&p->bulk_preempted_vcs, vc_i, list);
536 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
540 /* Run an _M. Can be called safely on one that is already running. Hold the
541 * lock before calling. Other than state checks, this just starts up the _M's
542 * vcores, much like the second part of give_cores_running. More specifically,
543 * give_cores_runnable puts cores on the online list, which this then sends
544 * messages to. give_cores_running immediately puts them on the list and sends
545 * the message. the two-step style may go out of fashion soon.
547 * This expects that the "instructions" for which core(s) to run this on will be
548 * in the vcoremap, which needs to be set externally (give_cores()). */
549 void __proc_run_m(struct proc *p)
555 warn("ksched tried to run proc %d in state %s\n", p->pid,
556 procstate2str(p->state));
558 case (PROC_RUNNABLE_M):
559 /* vcoremap[i] holds the coreid of the physical core allocated to
560 * this process. It is set outside proc_run. For the kernel
561 * message, a0 = struct proc*, a1 = struct trapframe*. */
562 if (p->procinfo->num_vcores) {
563 __send_bulkp_events(p);
564 __proc_set_state(p, PROC_RUNNING_M);
565 /* Up the refcnt, to avoid the n refcnt upping on the
566 * destination cores. Keep in sync with __startcore */
567 proc_incref(p, p->procinfo->num_vcores * 2);
568 /* Send kernel messages to all online vcores (which were added
569 * to the list and mapped in __proc_give_cores()), making them
571 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
572 send_kernel_message(vc_i->pcoreid, __startcore, (long)p,
573 (long)vcore2vcoreid(p, vc_i), 0,
577 warn("Tried to proc_run() an _M with no vcores!");
579 /* There a subtle race avoidance here (when we unlock after sending
580 * the message). __proc_startcore can handle a death message, but
581 * we can't have the startcore come after the death message.
582 * Otherwise, it would look like a new process. So we hold the lock
583 * til after we send our message, which prevents a possible death
585 * - Note there is no guarantee this core's interrupts were on, so
586 * it may not get the message for a while... */
588 case (PROC_RUNNING_M):
591 /* unlock just so the monitor can call something that might lock*/
592 spin_unlock(&p->proc_lock);
593 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
597 /* Actually runs the given context (trapframe) of process p on the core this
598 * code executes on. This is called directly by __startcore, which needs to
599 * bypass the routine_kmsg check. Interrupts should be off when you call this.
601 * A note on refcnting: this function will not return, and your proc reference
602 * will end up stored in current. This will make no changes to p's refcnt, so
603 * do your accounting such that there is only the +1 for current. This means if
604 * it is already in current (like in the trap return path), don't up it. If
605 * it's already in current and you have another reference (like pid2proc or from
606 * an IPI), then down it (which is what happens in __startcore()). If it's not
607 * in current and you have one reference, like proc_run(non_current_p), then
608 * also do nothing. The refcnt for your *p will count for the reference stored
610 static void __proc_startcore(struct proc *p, trapframe_t *tf)
612 assert(!irq_is_enabled());
613 __set_proc_current(p);
614 /* need to load our silly state, preferably somewhere other than here so we
615 * can avoid the case where the context was just running here. it's not
616 * sufficient to do it in the "new process" if-block above (could be things
617 * like page faults that cause us to keep the same process, but want a
619 * for now, we load this silly state here. (TODO) (HSS)
620 * We also need this to be per trapframe, and not per process...
621 * For now / OSDI, only load it when in _S mode. _M mode was handled in
623 if (p->state == PROC_RUNNING_S)
624 env_pop_ancillary_state(p);
625 /* Clear the current_tf, since it is no longer used */
626 current_tf = 0; /* TODO: might not need this... */
630 /* Restarts/runs the current_tf, which must be for the current process, on the
631 * core this code executes on. Calls an internal function to do the work.
633 * In case there are pending routine messages, like __death, __preempt, or
634 * __notify, we need to run them. Alternatively, if there are any, we could
635 * self_ipi, and run the messages immediately after popping back to userspace,
636 * but that would have crappy overhead.
638 * Refcnting: this will not return, and it assumes that you've accounted for
639 * your reference as if it was the ref for "current" (which is what happens when
640 * returning from local traps and such. */
641 void proc_restartcore(void)
643 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
644 assert(!pcpui->cur_sysc);
645 /* TODO: can probably remove this enable_irq. it was an optimization for
647 /* Try and get any interrupts before we pop back to userspace. If we didn't
648 * do this, we'd just get them in userspace, but this might save us some
649 * effort/overhead. */
651 /* Need ints disabled when we return from processing (race on missing
654 process_routine_kmsg(pcpui->cur_tf);
655 /* If there is no owning process, just idle, since we don't know what to do.
656 * This could be because the process had been restarted a long time ago and
657 * has since left the core, or due to a KMSG like __preempt or __death. */
658 if (!pcpui->owning_proc) {
662 assert(pcpui->cur_tf);
663 __proc_startcore(pcpui->owning_proc, pcpui->cur_tf);
666 /* Destroys the process. It will destroy the process and return any cores
667 * to the ksched via the __sched_proc_destroy() CB.
669 * Here's the way process death works:
670 * 0. grab the lock (protects state transition and core map)
671 * 1. set state to dying. that keeps the kernel from doing anything for the
672 * process (like proc_running it).
673 * 2. figure out where the process is running (cross-core/async or RUNNING_M)
674 * 3. IPI to clean up those cores (decref, etc).
676 * 5. Clean up your core, if applicable
677 * (Last core/kernel thread to decref cleans up and deallocates resources.)
679 * Note that some cores can be processing async calls, but will eventually
680 * decref. Should think about this more, like some sort of callback/revocation.
682 * This function will now always return (it used to not return if the calling
683 * core was dying). However, when it returns, a kernel message will eventually
684 * come in, making you abandon_core, as if you weren't running. It may be that
685 * the only reference to p is the one you passed in, and when you decref, it'll
686 * get __proc_free()d. */
687 void proc_destroy(struct proc *p)
689 uint32_t nr_cores_revoked = 0;
690 struct kthread *sleeper;
691 /* Can't spin on the proc lock with irq disabled. This is a problem for all
692 * places where we grab the lock, but it is particularly bad for destroy,
693 * since we tend to call this from trap and irq handlers */
694 assert(irq_is_enabled());
695 spin_lock(&p->proc_lock);
696 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
697 uint32_t pc_arr[p->procinfo->num_vcores];
699 case PROC_DYING: /* someone else killed this already. */
700 spin_unlock(&p->proc_lock);
703 case PROC_RUNNABLE_S:
706 case PROC_RUNNABLE_M:
708 /* Need to reclaim any cores this proc might have, even if it's not
709 * running yet. Those running will receive a __death */
710 nr_cores_revoked = __proc_take_allcores(p, pc_arr, FALSE);
714 // here's how to do it manually
717 proc_decref(p); /* this decref is for the cr3 */
721 send_kernel_message(get_pcoreid(p, 0), __death, 0, 0, 0,
723 __seq_start_write(&p->procinfo->coremap_seqctr);
724 // TODO: might need to sort num_vcores too later (VC#)
725 /* vcore is unmapped on the receive side */
726 __seq_end_write(&p->procinfo->coremap_seqctr);
727 /* If we ever have RUNNING_S run on non-mgmt cores, we'll need to
728 * tell the ksched about this now-idle core (after unlocking) */
731 warn("Weird state(%s) in %s()", procstate2str(p->state),
733 spin_unlock(&p->proc_lock);
736 /* At this point, a death IPI should be on its way, either from the
737 * RUNNING_S one, or from proc_take_cores with a __death. in general,
738 * interrupts should be on when you call proc_destroy locally, but currently
739 * aren't for all things (like traphandlers). */
740 __proc_set_state(p, PROC_DYING);
741 spin_unlock(&p->proc_lock);
742 /* This prevents processes from accessing their old files while dying, and
743 * will help if these files (or similar objects in the future) hold
744 * references to p (preventing a __proc_free()). Need to unlock before
745 * doing this - the proclock doesn't protect the files (not proc state), and
746 * closing these might block (can't block while spinning). */
747 /* TODO: might need some sync protection */
748 close_all_files(&p->open_files, FALSE);
749 /* Tell the ksched about our death, and which cores we freed up */
750 __sched_proc_destroy(p, pc_arr, nr_cores_revoked);
751 /* Signal our state change. Assuming we only have one waiter right now. */
752 sleeper = __up_sem(&p->state_change, TRUE);
754 kthread_runnable(sleeper);
757 /* Turns *p into an MCP. Needs to be called from a local syscall of a RUNNING_S
758 * process. Returns 0 if it succeeded, an error code otherwise. */
759 int proc_change_to_m(struct proc *p)
763 spin_lock(&p->proc_lock);
764 /* in case userspace erroneously tries to change more than once */
765 if (__proc_is_mcp(p))
768 case (PROC_RUNNING_S):
769 /* issue with if we're async or not (need to preempt it)
770 * either of these should trip it. TODO: (ACR) async core req
771 * TODO: relies on vcore0 being the caller (VC#) */
772 if ((current != p) || (get_pcoreid(p, 0) != core_id()))
773 panic("We don't handle async RUNNING_S core requests yet.");
774 /* save the tf so userspace can restart it. Like in __notify,
775 * this assumes a user tf is the same as a kernel tf. We save
776 * it in the preempt slot so that we can also save the silly
778 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
779 disable_irqsave(&state); /* protect cur_tf */
780 /* Note this won't play well with concurrent proc kmsgs, but
781 * since we're _S and locked, we shouldn't have any. */
783 /* Copy uthread0's context to the notif slot */
784 vcpd->notif_tf = *current_tf;
785 clear_owning_proc(core_id()); /* so we don't restart */
786 save_fp_state(&vcpd->preempt_anc);
787 enable_irqsave(&state);
788 /* Userspace needs to not fuck with notif_disabled before
789 * transitioning to _M. */
790 if (vcpd->notif_disabled) {
791 printk("[kernel] user bug: notifs disabled for vcore 0\n");
792 vcpd->notif_disabled = FALSE;
794 /* in the async case, we'll need to remotely stop and bundle
795 * vcore0's TF. this is already done for the sync case (local
797 /* this process no longer runs on its old location (which is
798 * this core, for now, since we don't handle async calls) */
799 __seq_start_write(&p->procinfo->coremap_seqctr);
800 // TODO: (VC#) might need to adjust num_vcores
801 // TODO: (ACR) will need to unmap remotely (receive-side)
802 __unmap_vcore(p, 0); /* VC# keep in sync with proc_run_s */
803 __seq_end_write(&p->procinfo->coremap_seqctr);
804 /* change to runnable_m (it's TF is already saved) */
805 __proc_set_state(p, PROC_RUNNABLE_M);
806 p->procinfo->is_mcp = TRUE;
807 spin_unlock(&p->proc_lock);
808 /* Tell the ksched that we're a real MCP now! */
809 __sched_proc_change_to_m(p);
811 case (PROC_RUNNABLE_S):
812 /* Issues: being on the runnable_list, proc_set_state not liking
813 * it, and not clearly thinking through how this would happen.
814 * Perhaps an async call that gets serviced after you're
816 warn("Not supporting RUNNABLE_S -> RUNNABLE_M yet.\n");
819 warn("Dying, core request coming from %d\n", core_id());
825 spin_unlock(&p->proc_lock);
829 /* Old code to turn a RUNNING_M to a RUNNING_S, with the calling context
830 * becoming the new 'thread0'. Don't use this. Caller needs to send in a
831 * pc_arr big enough for all vcores. Will return the number of cores given up
833 uint32_t __proc_change_to_s(struct proc *p, uint32_t *pc_arr)
836 uint32_t num_revoked;
837 printk("[kernel] trying to transition _M -> _S (deprecated)!\n");
838 assert(p->state == PROC_RUNNING_M); // TODO: (ACR) async core req
839 /* save the context, to be restarted in _S mode */
840 disable_irqsave(&state); /* protect cur_tf */
842 p->env_tf = *current_tf;
843 clear_owning_proc(core_id()); /* so we don't restart */
844 enable_irqsave(&state);
845 env_push_ancillary_state(p); // TODO: (HSS)
846 /* sending death, since it's not our job to save contexts or anything in
848 num_revoked = __proc_take_allcores(p, pc_arr, FALSE);
849 __proc_set_state(p, PROC_RUNNABLE_S);
853 /* Helper function. Is the given pcore a mapped vcore? No locking involved, be
855 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid)
857 return p->procinfo->pcoremap[pcoreid].valid;
860 /* Helper function. Find the vcoreid for a given physical core id for proc p.
861 * No locking involved, be careful. Panics on failure. */
862 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid)
864 assert(is_mapped_vcore(p, pcoreid));
865 return p->procinfo->pcoremap[pcoreid].vcoreid;
868 /* Helper function. Try to find the pcoreid for a given virtual core id for
869 * proc p. No locking involved, be careful. Use this when you can tolerate a
870 * stale or otherwise 'wrong' answer. */
871 static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid)
873 return p->procinfo->vcoremap[vcoreid].pcoreid;
876 /* Helper function. Find the pcoreid for a given virtual core id for proc p.
877 * No locking involved, be careful. Panics on failure. */
878 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid)
880 assert(vcore_is_mapped(p, vcoreid));
881 return try_get_pcoreid(p, vcoreid);
884 /* Helper: saves the SCP's tf state and unmaps vcore 0. In the future, we'll
885 * probably use vc0's space for env_tf and the silly state. */
886 void __proc_save_context_s(struct proc *p, struct trapframe *tf)
889 env_push_ancillary_state(p); /* TODO: (HSS) */
890 __unmap_vcore(p, 0); /* VC# keep in sync with proc_run_s */
893 /* Yields the calling core. Must be called locally (not async) for now.
894 * - If RUNNING_S, you just give up your time slice and will eventually return,
895 * possibly after WAITING on an event.
896 * - If RUNNING_M, you give up the current vcore (which never returns), and
897 * adjust the amount of cores wanted/granted.
898 * - If you have only one vcore, you switch to WAITING. There's no 'classic
899 * yield' for MCPs (at least not now). When you run again, you'll have one
900 * guaranteed core, starting from the entry point.
902 * If the call is being nice, it means different things for SCPs and MCPs. For
903 * MCPs, it means that it is in response to a preemption (which needs to be
904 * checked). If there is no preemption pending, just return. For SCPs, it
905 * means the proc wants to give up the core, but still has work to do. If not,
906 * the proc is trying to wait on an event. It's not being nice to others, it
907 * just has no work to do.
909 * This usually does not return (smp_idle()), so it will eat your reference.
910 * Also note that it needs a non-current/edible reference, since it will abandon
911 * and continue to use the *p (current == 0, no cr3, etc).
913 * We disable interrupts for most of it too, since we need to protect current_tf
914 * and not race with __notify (which doesn't play well with concurrent
916 void proc_yield(struct proc *SAFE p, bool being_nice)
918 uint32_t vcoreid, pcoreid = core_id();
920 struct preempt_data *vcpd;
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. =( */
930 /* Need to disable before even reading vcoreid, since we could be unmapped
931 * by a __preempt or __death. _S also needs ints disabled, so we'll just do
932 * it immediately. Finally, we need to disable AFTER locking. It is a bug
933 * to grab the lock while irq's are disabled. */
934 disable_irqsave(&state);
936 case (PROC_RUNNING_S):
938 /* waiting for an event to unblock us */
939 vcpd = &p->procdata->vcore_preempt_data[0];
940 /* this check is an early optimization (check, signal, check
941 * again pattern). We could also lock before spamming the
942 * vcore in event.c */
943 if (vcpd->notif_pending) {
944 /* they can't handle events, just need to prevent a yield.
945 * (note the notif_pendings are collapsed). */
946 if (!scp_is_vcctx_ready(vcpd))
947 vcpd->notif_pending = FALSE;
950 /* syncing with event's SCP code. we set waiting, then check
951 * pending. they set pending, then check waiting. it's not
952 * possible for us to miss the notif *and* for them to miss
953 * WAITING. one (or both) of us will see and make sure the proc
955 __proc_set_state(p, PROC_WAITING);
956 wrmb(); /* don't let the state write pass the notif read */
957 if (vcpd->notif_pending) {
958 __proc_set_state(p, PROC_RUNNING_S);
959 if (!scp_is_vcctx_ready(vcpd))
960 vcpd->notif_pending = FALSE;
963 /* if we're here, we want to sleep. a concurrent event that
964 * hasn't already written notif_pending will have seen WAITING,
965 * and will be spinning while we do this. */
966 __proc_save_context_s(p, current_tf);
967 spin_unlock(&p->proc_lock); /* note irqs are not enabled yet */
969 /* yielding to allow other processes to run. we're briefly
970 * WAITING, til we are woken up */
971 __proc_set_state(p, PROC_WAITING);
972 __proc_save_context_s(p, current_tf);
973 spin_unlock(&p->proc_lock); /* note irqs are not enabled yet */
974 /* immediately wake up the proc (makes it runnable) */
978 case (PROC_RUNNING_M):
979 break; /* will handle this stuff below */
980 case (PROC_DYING): /* incoming __death */
981 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
984 panic("Weird state(%s) in %s()", procstate2str(p->state),
987 /* If we're already unmapped (__preempt or a __death was sent and the caller
988 * unmapped us), bail out. Note that if a __death hit us, we should have
989 * bailed when we saw PROC_DYING. Also note we might not have received the
990 * __preempt or __death kmsg yet. */
991 if (!is_mapped_vcore(p, pcoreid))
993 vcoreid = get_vcoreid(p, pcoreid);
994 vc = vcoreid2vcore(p, vcoreid);
995 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
996 /* no reason to be nice, return */
997 if (being_nice && !vc->preempt_pending)
999 /* Sanity check, can remove after a while (we should have been unmapped) */
1000 assert(!vc->preempt_served);
1001 /* At this point, AFAIK there should be no preempt/death messages on the
1002 * way, and we're on the online list. So we'll go ahead and do the yielding
1004 /* If there's a preempt pending, we don't need to preempt later since we are
1005 * yielding (nice or otherwise). If not, this is just a regular yield. */
1006 if (vc->preempt_pending) {
1007 vc->preempt_pending = 0;
1009 /* Optional: on a normal yield, check to see if we are putting them
1010 * below amt_wanted (help with user races) and bail. */
1011 if (p->procdata->res_req[RES_CORES].amt_wanted >=
1012 p->procinfo->num_vcores)
1015 /* Don't let them yield if they are missing a notification. Userspace must
1016 * not leave vcore context without dealing with notif_pending. pop_ros_tf()
1017 * handles leaving via uthread context. This handles leaving via a yield.
1019 * This early check is an optimization. The real check is below when it
1020 * works with the online_vcs list (syncing with event.c and INDIR/IPI
1022 if (vcpd->notif_pending)
1024 /* Now we'll actually try to yield */
1025 printd("[K] Process %d (%p) is yielding on vcore %d\n", p->pid, p,
1026 get_vcoreid(p, coreid));
1027 /* Remove from the online list, add to the yielded list, and unmap
1028 * the vcore, which gives up the core. */
1029 TAILQ_REMOVE(&p->online_vcs, vc, list);
1030 /* Now that we're off the online list, check to see if an alert made
1031 * it through (event.c sets this) */
1032 wrmb(); /* prev write must hit before reading notif_pending */
1033 /* Note we need interrupts disabled, since a __notify can come in
1034 * and set pending to FALSE */
1035 if (vcpd->notif_pending) {
1036 /* We lost, put it back on the list and abort the yield */
1037 TAILQ_INSERT_TAIL(&p->online_vcs, vc, list); /* could go HEAD */
1040 /* We won the race with event sending, we can safely yield */
1041 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1042 /* Note this protects stuff userspace should look at, which doesn't
1043 * include the TAILQs. */
1044 __seq_start_write(&p->procinfo->coremap_seqctr);
1045 /* Next time the vcore starts, it starts fresh */
1046 vcpd->notif_disabled = FALSE;
1047 __unmap_vcore(p, vcoreid);
1048 p->procinfo->num_vcores--;
1049 p->procinfo->res_grant[RES_CORES] = p->procinfo->num_vcores;
1050 __seq_end_write(&p->procinfo->coremap_seqctr);
1051 /* No more vcores? Then we wait on an event */
1052 if (p->procinfo->num_vcores == 0) {
1053 /* consider a ksched op to tell it about us WAITING */
1054 __proc_set_state(p, PROC_WAITING);
1056 spin_unlock(&p->proc_lock);
1057 /* Hand the now-idle core to the ksched */
1058 __sched_put_idle_core(p, pcoreid);
1059 goto out_yield_core;
1061 /* for some reason we just want to return, either to take a KMSG that cleans
1062 * us up, or because we shouldn't yield (ex: notif_pending). */
1063 spin_unlock(&p->proc_lock);
1064 enable_irqsave(&state);
1066 out_yield_core: /* successfully yielded the core */
1067 proc_decref(p); /* need to eat the ref passed in */
1068 /* Clean up the core and idle. Need to do this before enabling interrupts,
1069 * since once we call __sched_put_idle_core(), we could get a startcore. */
1070 clear_owning_proc(pcoreid); /* so we don't restart */
1072 smp_idle(); /* will reenable interrupts */
1075 /* Sends a notification (aka active notification, aka IPI) to p's vcore. We
1076 * only send a notification if one they are enabled. There's a bunch of weird
1077 * cases with this, and how pending / enabled are signals between the user and
1078 * kernel - check the documentation. Note that pending is more about messages.
1079 * The process needs to be in vcore_context, and the reason is usually a
1080 * message. We set pending here in case we were called to prod them into vcore
1081 * context (like via a sys_self_notify). Also note that this works for _S
1082 * procs, if you send to vcore 0 (and the proc is running). */
1083 void proc_notify(struct proc *p, uint32_t vcoreid)
1085 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1086 vcpd->notif_pending = TRUE;
1087 wrmb(); /* must write notif_pending before reading notif_disabled */
1088 if (!vcpd->notif_disabled) {
1089 /* GIANT WARNING: we aren't using the proc-lock to protect the
1090 * vcoremap. We want to be able to use this from interrupt context,
1091 * and don't want the proc_lock to be an irqsave. Spurious
1092 * __notify() kmsgs are okay (it checks to see if the right receiver
1094 if (vcore_is_mapped(p, vcoreid)) {
1095 printd("[kernel] sending notif to vcore %d\n", vcoreid);
1096 /* This use of try_get_pcoreid is racy, might be unmapped */
1097 send_kernel_message(try_get_pcoreid(p, vcoreid), __notify, (long)p,
1098 0, 0, KMSG_IMMEDIATE);
1103 /* Makes sure p is runnable. Callers may spam this, so it needs to handle
1104 * repeated calls for the same event. Callers include event delivery, SCP
1105 * yield, and new SCPs. Will trigger __sched_.cp_wakeup() CBs. Will only
1106 * trigger the CB once, regardless of how many times we are called, *until* the
1107 * proc becomes WAITING again, presumably because of something the ksched did.*/
1108 void proc_wakeup(struct proc *p)
1110 spin_lock(&p->proc_lock);
1111 if (__proc_is_mcp(p)) {
1112 /* we only wake up WAITING mcps */
1113 if (p->state != PROC_WAITING) {
1114 spin_unlock(&p->proc_lock);
1117 __proc_set_state(p, PROC_RUNNABLE_M);
1118 spin_unlock(&p->proc_lock);
1119 __sched_mcp_wakeup(p);
1122 /* SCPs can wake up for a variety of reasons. the only times we need
1123 * to do something is if it was waiting or just created. other cases
1124 * are either benign (just go out), or potential bugs (_Ms) */
1126 case (PROC_CREATED):
1127 case (PROC_WAITING):
1128 __proc_set_state(p, PROC_RUNNABLE_S);
1130 case (PROC_RUNNABLE_S):
1131 case (PROC_RUNNING_S):
1133 spin_unlock(&p->proc_lock);
1135 case (PROC_RUNNABLE_M):
1136 case (PROC_RUNNING_M):
1137 warn("Weird state(%s) in %s()", procstate2str(p->state),
1139 spin_unlock(&p->proc_lock);
1142 printd("[kernel] FYI, waking up an _S proc\n"); /* thanks, past brho! */
1143 spin_unlock(&p->proc_lock);
1144 __sched_scp_wakeup(p);
1148 /* Is the process in multi_mode / is an MCP or not? */
1149 bool __proc_is_mcp(struct proc *p)
1151 /* in lieu of using the amount of cores requested, or having a bunch of
1152 * states (like PROC_WAITING_M and _S), I'll just track it with a bool. */
1153 return p->procinfo->is_mcp;
1156 /************************ Preemption Functions ******************************
1157 * Don't rely on these much - I'll be sure to change them up a bit.
1159 * Careful about what takes a vcoreid and what takes a pcoreid. Also, there may
1160 * be weird glitches with setting the state to RUNNABLE_M. It is somewhat in
1161 * flux. The num_vcores is changed after take_cores, but some of the messages
1162 * (or local traps) may not yet be ready to handle seeing their future state.
1163 * But they should be, so fix those when they pop up.
1165 * Another thing to do would be to make the _core functions take a pcorelist,
1166 * and not just one pcoreid. */
1168 /* Sets a preempt_pending warning for p's vcore, to go off 'when'. If you care
1169 * about locking, do it before calling. Takes a vcoreid! */
1170 void __proc_preempt_warn(struct proc *p, uint32_t vcoreid, uint64_t when)
1172 struct event_msg local_msg = {0};
1173 /* danger with doing this unlocked: preempt_pending is set, but never 0'd,
1174 * since it is unmapped and not dealt with (TODO)*/
1175 p->procinfo->vcoremap[vcoreid].preempt_pending = when;
1177 /* Send the event (which internally checks to see how they want it) */
1178 local_msg.ev_type = EV_PREEMPT_PENDING;
1179 local_msg.ev_arg1 = vcoreid;
1180 /* Whenever we send msgs with the proc locked, we need at least 1 online.
1181 * Caller needs to make sure the core was online/mapped. */
1182 assert(!TAILQ_EMPTY(&p->online_vcs));
1183 send_kernel_event(p, &local_msg, vcoreid);
1185 /* TODO: consider putting in some lookup place for the alarm to find it.
1186 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1189 /* Warns all active vcores of an impending preemption. Hold the lock if you
1190 * care about the mapping (and you should). */
1191 void __proc_preempt_warnall(struct proc *p, uint64_t when)
1194 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1195 __proc_preempt_warn(p, vcore2vcoreid(p, vc_i), when);
1196 /* TODO: consider putting in some lookup place for the alarm to find it.
1197 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1200 // TODO: function to set an alarm, if none is outstanding
1202 /* Raw function to preempt a single core. If you care about locking, do it
1203 * before calling. */
1204 void __proc_preempt_core(struct proc *p, uint32_t pcoreid)
1206 uint32_t vcoreid = get_vcoreid(p, pcoreid);
1207 struct event_msg preempt_msg = {0};
1208 p->procinfo->vcoremap[vcoreid].preempt_served = TRUE;
1209 // expects a pcorelist. assumes pcore is mapped and running_m
1210 __proc_take_corelist(p, &pcoreid, 1, TRUE);
1211 /* Only send the message if we have an online core. o/w, it would fuck
1212 * us up (deadlock), and hey don't need a message. the core we just took
1213 * will be the first one to be restarted. It will look like a notif. in
1214 * the future, we could send the event if we want, but the caller needs to
1215 * do that (after unlocking). */
1216 if (!TAILQ_EMPTY(&p->online_vcs)) {
1217 preempt_msg.ev_type = EV_VCORE_PREEMPT;
1218 preempt_msg.ev_arg2 = vcoreid;
1219 send_kernel_event(p, &preempt_msg, 0);
1223 /* Raw function to preempt every vcore. If you care about locking, do it before
1225 uint32_t __proc_preempt_all(struct proc *p, uint32_t *pc_arr)
1227 /* instead of doing this, we could just preempt_served all possible vcores,
1228 * and not just the active ones. We would need to sort out a way to deal
1229 * with stale preempt_serveds first. This might be just as fast anyways. */
1231 /* TODO:(BULK) PREEMPT - don't bother with this, set a proc wide flag, or
1232 * just make us RUNNABLE_M. Note this is also used by __map_vcore. */
1233 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1234 vc_i->preempt_served = TRUE;
1235 return __proc_take_allcores(p, pc_arr, TRUE);
1238 /* Warns and preempts a vcore from p. No delaying / alarming, or anything. The
1239 * warning will be for u usec from now. Returns TRUE if the core belonged to
1240 * the proc (and thus preempted), False if the proc no longer has the core. */
1241 bool proc_preempt_core(struct proc *p, uint32_t pcoreid, uint64_t usec)
1243 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1244 bool retval = FALSE;
1245 if (p->state != PROC_RUNNING_M) {
1246 /* more of an FYI for brho. should be harmless to just return. */
1247 warn("Tried to preempt from a non RUNNING_M proc!");
1250 spin_lock(&p->proc_lock);
1251 if (is_mapped_vcore(p, pcoreid)) {
1252 __proc_preempt_warn(p, get_vcoreid(p, pcoreid), warn_time);
1253 __proc_preempt_core(p, pcoreid);
1254 /* we might have taken the last core */
1255 if (!p->procinfo->num_vcores)
1256 __proc_set_state(p, PROC_RUNNABLE_M);
1259 spin_unlock(&p->proc_lock);
1263 /* Warns and preempts all from p. No delaying / alarming, or anything. The
1264 * warning will be for u usec from now. */
1265 void proc_preempt_all(struct proc *p, uint64_t usec)
1267 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1268 uint32_t num_revoked = 0;
1269 spin_lock(&p->proc_lock);
1270 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
1271 uint32_t pc_arr[p->procinfo->num_vcores];
1272 /* DYING could be okay */
1273 if (p->state != PROC_RUNNING_M) {
1274 warn("Tried to preempt from a non RUNNING_M proc!");
1275 spin_unlock(&p->proc_lock);
1278 __proc_preempt_warnall(p, warn_time);
1279 num_revoked = __proc_preempt_all(p, pc_arr);
1280 assert(!p->procinfo->num_vcores);
1281 __proc_set_state(p, PROC_RUNNABLE_M);
1282 spin_unlock(&p->proc_lock);
1283 /* TODO: when we revise this func, look at __put_idle */
1284 /* Return the cores to the ksched */
1286 __sched_put_idle_cores(p, pc_arr, num_revoked);
1289 /* Give the specific pcore to proc p. Lots of assumptions, so don't really use
1290 * this. The proc needs to be _M and prepared for it. the pcore needs to be
1292 void proc_give(struct proc *p, uint32_t pcoreid)
1294 warn("Your idlecoremap is now screwed up"); /* TODO (IDLE) */
1295 spin_lock(&p->proc_lock);
1296 // expects a pcorelist, we give it a list of one
1297 __proc_give_cores(p, &pcoreid, 1);
1298 spin_unlock(&p->proc_lock);
1301 /* Global version of the helper, for sys_get_vcoreid (might phase that syscall
1303 uint32_t proc_get_vcoreid(struct proc *p)
1305 return per_cpu_info[core_id()].owning_vcoreid;
1308 /* TODO: make all of these static inlines when we gut the env crap */
1309 bool vcore_is_mapped(struct proc *p, uint32_t vcoreid)
1311 return p->procinfo->vcoremap[vcoreid].valid;
1314 /* Can do this, or just create a new field and save it in the vcoremap */
1315 uint32_t vcore2vcoreid(struct proc *p, struct vcore *vc)
1317 return (vc - p->procinfo->vcoremap);
1320 struct vcore *vcoreid2vcore(struct proc *p, uint32_t vcoreid)
1322 return &p->procinfo->vcoremap[vcoreid];
1325 /********** Core granting (bulk and single) ***********/
1327 /* Helper: gives pcore to the process, mapping it to the next available vcore
1328 * from list vc_list. Returns TRUE if we succeeded (non-empty). If you pass in
1329 * **vc, we'll tell you which vcore it was. */
1330 static bool __proc_give_a_pcore(struct proc *p, uint32_t pcore,
1331 struct vcore_tailq *vc_list, struct vcore **vc)
1333 struct vcore *new_vc;
1334 new_vc = TAILQ_FIRST(vc_list);
1337 printd("setting vcore %d to pcore %d\n", vcore2vcoreid(p, new_vc),
1339 TAILQ_REMOVE(vc_list, new_vc, list);
1340 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1341 __map_vcore(p, vcore2vcoreid(p, new_vc), pcore);
1347 static void __proc_give_cores_runnable(struct proc *p, uint32_t *pc_arr,
1350 assert(p->state == PROC_RUNNABLE_M);
1351 assert(num); /* catch bugs */
1352 /* add new items to the vcoremap */
1353 __seq_start_write(&p->procinfo->coremap_seqctr);/* unncessary if offline */
1354 p->procinfo->num_vcores += num;
1355 for (int i = 0; i < num; i++) {
1356 /* Try from the bulk list first */
1357 if (__proc_give_a_pcore(p, pc_arr[i], &p->bulk_preempted_vcs, 0))
1359 /* o/w, try from the inactive list. at one point, i thought there might
1360 * be a legit way in which the inactive list could be empty, but that i
1361 * wanted to catch it via an assert. */
1362 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, 0));
1364 __seq_end_write(&p->procinfo->coremap_seqctr);
1367 static void __proc_give_cores_running(struct proc *p, uint32_t *pc_arr,
1371 /* Up the refcnt, since num cores are going to start using this
1372 * process and have it loaded in their owning_proc and 'current'. */
1373 proc_incref(p, num * 2); /* keep in sync with __startcore */
1374 __seq_start_write(&p->procinfo->coremap_seqctr);
1375 p->procinfo->num_vcores += num;
1376 assert(TAILQ_EMPTY(&p->bulk_preempted_vcs));
1377 for (int i = 0; i < num; i++) {
1378 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, &vc_i));
1379 send_kernel_message(pc_arr[i], __startcore, (long)p,
1380 (long)vcore2vcoreid(p, vc_i), 0, KMSG_IMMEDIATE);
1382 __seq_end_write(&p->procinfo->coremap_seqctr);
1385 /* Gives process p the additional num cores listed in pcorelist. If the proc is
1386 * not RUNNABLE_M or RUNNING_M, this will fail and allocate none of the core
1387 * (and return -1). If you're RUNNING_M, this will startup your new cores at
1388 * the entry point with their virtual IDs (or restore a preemption). If you're
1389 * RUNNABLE_M, you should call __proc_run_m after this so that the process can
1390 * start to use its cores. In either case, this returns 0.
1392 * If you're *_S, make sure your core0's TF is set (which is done when coming in
1393 * via arch/trap.c and we are RUNNING_S), change your state, then call this.
1394 * Then call __proc_run_m().
1396 * The reason I didn't bring the _S cases from core_request over here is so we
1397 * can keep this family of calls dealing with only *_Ms, to avoiding caring if
1398 * this is called from another core, and to avoid the _S -> _M transition.
1400 * WARNING: You must hold the proc_lock before calling this! */
1401 int __proc_give_cores(struct proc *p, uint32_t *pc_arr, uint32_t num)
1403 /* should never happen: */
1404 assert(num + p->procinfo->num_vcores <= MAX_NUM_CPUS);
1406 case (PROC_RUNNABLE_S):
1407 case (PROC_RUNNING_S):
1408 warn("Don't give cores to a process in a *_S state!\n");
1411 case (PROC_WAITING):
1412 /* can't accept, just fail */
1414 case (PROC_RUNNABLE_M):
1415 __proc_give_cores_runnable(p, pc_arr, num);
1417 case (PROC_RUNNING_M):
1418 __proc_give_cores_running(p, pc_arr, num);
1421 panic("Weird state(%s) in %s()", procstate2str(p->state),
1424 /* TODO: considering moving to the ksched (hard, due to yield) */
1425 p->procinfo->res_grant[RES_CORES] += num;
1429 /********** Core revocation (bulk and single) ***********/
1431 /* Revokes a single vcore from a process (unmaps or sends a KMSG to unmap). */
1432 static void __proc_revoke_core(struct proc *p, uint32_t vcoreid, bool preempt)
1434 uint32_t pcoreid = get_pcoreid(p, vcoreid);
1435 struct preempt_data *vcpd;
1437 /* Lock the vcore's state (necessary for preemption recovery) */
1438 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1439 atomic_or(&vcpd->flags, VC_K_LOCK);
1440 send_kernel_message(pcoreid, __preempt, (long)p, 0, 0, KMSG_IMMEDIATE);
1442 send_kernel_message(pcoreid, __death, 0, 0, 0, KMSG_IMMEDIATE);
1446 /* Revokes all cores from the process (unmaps or sends a KMSGS). */
1447 static void __proc_revoke_allcores(struct proc *p, bool preempt)
1450 /* TODO: if we ever get broadcast messaging, use it here (still need to lock
1451 * the vcores' states for preemption) */
1452 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1453 __proc_revoke_core(p, vcore2vcoreid(p, vc_i), preempt);
1456 /* Might be faster to scan the vcoremap than to walk the list... */
1457 static void __proc_unmap_allcores(struct proc *p)
1460 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1461 __unmap_vcore(p, vcore2vcoreid(p, vc_i));
1464 /* Takes (revoke via kmsg or unmap) from process p the num cores listed in
1465 * pc_arr. Will preempt if 'preempt' is set. o/w, no state will be saved, etc.
1466 * Don't use this for taking all of a process's cores.
1468 * Make sure you hold the lock when you call this, and make sure that the pcore
1469 * actually belongs to the proc, non-trivial due to other __preempt messages. */
1470 void __proc_take_corelist(struct proc *p, uint32_t *pc_arr, uint32_t num,
1475 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1476 __seq_start_write(&p->procinfo->coremap_seqctr);
1477 for (int i = 0; i < num; i++) {
1478 vcoreid = get_vcoreid(p, pc_arr[i]);
1480 assert(pc_arr[i] == get_pcoreid(p, vcoreid));
1481 /* Revoke / unmap core */
1482 if (p->state == PROC_RUNNING_M)
1483 __proc_revoke_core(p, vcoreid, preempt);
1484 __unmap_vcore(p, vcoreid);
1485 /* Change lists for the vcore. Note, the vcore is already unmapped
1486 * and/or the messages are already in flight. The only code that looks
1487 * at the lists without holding the lock is event code. */
1488 vc = vcoreid2vcore(p, vcoreid);
1489 TAILQ_REMOVE(&p->online_vcs, vc, list);
1490 /* even for single preempts, we use the inactive list. bulk preempt is
1491 * only used for when we take everything. */
1492 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1494 p->procinfo->num_vcores -= num;
1495 __seq_end_write(&p->procinfo->coremap_seqctr);
1496 p->procinfo->res_grant[RES_CORES] -= num;
1499 /* Takes all cores from a process (revoke via kmsg or unmap), putting them on
1500 * the appropriate vcore list, and fills pc_arr with the pcores revoked, and
1501 * returns the number of entries in pc_arr.
1503 * Make sure pc_arr is big enough to handle num_vcores().
1504 * Make sure you hold the lock when you call this. */
1505 uint32_t __proc_take_allcores(struct proc *p, uint32_t *pc_arr, bool preempt)
1507 struct vcore *vc_i, *vc_temp;
1509 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1510 __seq_start_write(&p->procinfo->coremap_seqctr);
1511 /* Write out which pcores we're going to take */
1512 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1513 pc_arr[num++] = vc_i->pcoreid;
1514 /* Revoke if they are running, and unmap. Both of these need the online
1515 * list to not be changed yet. */
1516 if (p->state == PROC_RUNNING_M)
1517 __proc_revoke_allcores(p, preempt);
1518 __proc_unmap_allcores(p);
1519 /* Move the vcores from online to the head of the appropriate list */
1520 TAILQ_FOREACH_SAFE(vc_i, &p->online_vcs, list, vc_temp) {
1521 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that */
1522 TAILQ_REMOVE(&p->online_vcs, vc_i, list);
1523 /* Put the cores on the appropriate list */
1525 TAILQ_INSERT_HEAD(&p->bulk_preempted_vcs, vc_i, list);
1527 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
1529 assert(TAILQ_EMPTY(&p->online_vcs));
1530 assert(num == p->procinfo->num_vcores);
1531 p->procinfo->num_vcores = 0;
1532 __seq_end_write(&p->procinfo->coremap_seqctr);
1533 p->procinfo->res_grant[RES_CORES] = 0;
1537 /* Helper to do the vcore->pcore and inverse mapping. Hold the lock when
1539 void __map_vcore(struct proc *p, uint32_t vcoreid, uint32_t pcoreid)
1541 /* Need to spin until __preempt is done saving state and whatnot before we
1542 * give the core back out. Note that __preempt doesn't need the mapping: we
1543 * just need to not give out the same vcore (via a __startcore) until the
1544 * state is saved so __startcore has something to start. (and spinning in
1545 * startcore won't work, since startcore has no versioning). */
1546 while (p->procinfo->vcoremap[vcoreid].preempt_served)
1548 p->procinfo->vcoremap[vcoreid].pcoreid = pcoreid;
1549 p->procinfo->vcoremap[vcoreid].valid = TRUE;
1550 p->procinfo->pcoremap[pcoreid].vcoreid = vcoreid;
1551 p->procinfo->pcoremap[pcoreid].valid = TRUE;
1554 /* Helper to unmap the vcore->pcore and inverse mapping. Hold the lock when
1556 void __unmap_vcore(struct proc *p, uint32_t vcoreid)
1558 p->procinfo->pcoremap[p->procinfo->vcoremap[vcoreid].pcoreid].valid = FALSE;
1559 p->procinfo->vcoremap[vcoreid].valid = FALSE;
1562 /* Stop running whatever context is on this core and load a known-good cr3.
1563 * Note this leaves no trace of what was running. This "leaves the process's
1564 * context. Also, we want interrupts disabled, to not conflict with kmsgs
1565 * (__launch_kthread, proc mgmt, etc).
1567 * This does not clear the owning proc. Use the other helper for that. */
1568 void abandon_core(void)
1570 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1571 assert(!irq_is_enabled());
1572 /* Syscalls that don't return will ultimately call abadon_core(), so we need
1573 * to make sure we don't think we are still working on a syscall. */
1574 pcpui->cur_sysc = 0;
1575 if (pcpui->cur_proc)
1579 /* Helper to clear the core's owning processor and manage refcnting. Pass in
1580 * core_id() to save a couple core_id() calls. */
1581 void clear_owning_proc(uint32_t coreid)
1583 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1584 struct proc *p = pcpui->owning_proc;
1585 assert(!irq_is_enabled());
1586 pcpui->owning_proc = 0;
1587 pcpui->owning_vcoreid = 0xdeadbeef;
1588 pcpui->cur_tf = 0; /* catch bugs for now (will go away soon) */
1593 /* Switches to the address space/context of new_p, doing nothing if we are
1594 * already in new_p. This won't add extra refcnts or anything, and needs to be
1595 * paired with switch_back() at the end of whatever function you are in. Don't
1596 * migrate cores in the middle of a pair. Specifically, the uncounted refs are
1597 * one for the old_proc, which is passed back to the caller, and new_p is
1598 * getting placed in cur_proc. */
1599 struct proc *switch_to(struct proc *new_p)
1601 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1602 struct proc *old_proc;
1603 int8_t irq_state = 0;
1604 disable_irqsave(&irq_state);
1605 old_proc = pcpui->cur_proc; /* uncounted ref */
1606 /* If we aren't the proc already, then switch to it */
1607 if (old_proc != new_p) {
1608 pcpui->cur_proc = new_p; /* uncounted ref */
1609 lcr3(new_p->env_cr3);
1611 enable_irqsave(&irq_state);
1615 /* This switches back to old_proc from new_p. Pair it with switch_to(), and
1616 * pass in its return value for old_proc. */
1617 void switch_back(struct proc *new_p, struct proc *old_proc)
1619 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1620 int8_t irq_state = 0;
1621 if (old_proc != new_p) {
1622 disable_irqsave(&irq_state);
1623 pcpui->cur_proc = old_proc;
1625 lcr3(old_proc->env_cr3);
1628 enable_irqsave(&irq_state);
1632 /* Will send a TLB shootdown message to every vcore in the main address space
1633 * (aka, all vcores for now). The message will take the start and end virtual
1634 * addresses as well, in case we want to be more clever about how much we
1635 * shootdown and batching our messages. Should do the sanity about rounding up
1636 * and down in this function too.
1638 * Would be nice to have a broadcast kmsg at this point. Note this may send a
1639 * message to the calling core (interrupting it, possibly while holding the
1640 * proc_lock). We don't need to process routine messages since it's an
1641 * immediate message. */
1642 void proc_tlbshootdown(struct proc *p, uintptr_t start, uintptr_t end)
1645 /* TODO: we might be able to avoid locking here in the future (we must hit
1646 * all online, and we can check __mapped). it'll be complicated. */
1647 spin_lock(&p->proc_lock);
1649 case (PROC_RUNNING_S):
1652 case (PROC_RUNNING_M):
1653 /* TODO: (TLB) sanity checks and rounding on the ranges */
1654 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
1655 send_kernel_message(vc_i->pcoreid, __tlbshootdown, start, end,
1660 /* if it is dying, death messages are already on the way to all
1661 * cores, including ours, which will clear the TLB. */
1664 /* will probably get this when we have the short handlers */
1665 warn("Unexpected case %s in %s", procstate2str(p->state),
1668 spin_unlock(&p->proc_lock);
1671 /* Helper, used by __startcore and change_to_vcore, which sets up cur_tf to run
1672 * a given process's vcore. Caller needs to set up things like owning_proc and
1673 * whatnot. Note that we might not have p loaded as current. */
1674 static void __set_curtf_to_vcoreid(struct proc *p, uint32_t vcoreid)
1676 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1677 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1679 /* Mark that this vcore as no longer preempted. No danger of clobbering
1680 * other writes, since this would get turned on in __preempt (which can't be
1681 * concurrent with this function on this core), and the atomic is just
1682 * toggling the one bit (a concurrent VC_K_LOCK will work) */
1683 atomic_and(&vcpd->flags, ~VC_PREEMPTED);
1684 /* Once the VC is no longer preempted, we allow it to receive msgs. We
1685 * could let userspace do it, but handling it here makes it easier for them
1686 * to handle_indirs (when they turn this flag off). Note the atomics
1687 * provide the needed barriers (cmb and mb on flags). */
1688 atomic_or(&vcpd->flags, VC_CAN_RCV_MSG);
1689 printd("[kernel] startcore on physical core %d for process %d's vcore %d\n",
1690 core_id(), p->pid, vcoreid);
1691 /* If notifs are disabled, the vcore was in vcore context and we need to
1692 * restart the preempt_tf. o/w, we give them a fresh vcore (which is also
1693 * what happens the first time a vcore comes online). No matter what,
1694 * they'll restart in vcore context. It's just a matter of whether or not
1695 * it is the old, interrupted vcore context. */
1696 if (vcpd->notif_disabled) {
1697 restore_fp_state(&vcpd->preempt_anc);
1698 /* copy-in the tf we'll pop, then set all security-related fields */
1699 pcpui->actual_tf = vcpd->preempt_tf;
1700 proc_secure_trapframe(&pcpui->actual_tf);
1701 } else { /* not restarting from a preemption, use a fresh vcore */
1702 assert(vcpd->transition_stack);
1703 /* TODO: consider 0'ing the FP state. We're probably leaking. */
1704 proc_init_trapframe(&pcpui->actual_tf, vcoreid, p->env_entry,
1705 vcpd->transition_stack);
1706 /* Disable/mask active notifications for fresh vcores */
1707 vcpd->notif_disabled = TRUE;
1709 /* cur_tf was built above (in actual_tf), now use it */
1710 pcpui->cur_tf = &pcpui->actual_tf;
1711 /* this cur_tf will get run when the kernel returns / idles */
1714 /* Changes calling vcore to be vcoreid. enable_my_notif tells us about how the
1715 * state calling vcore wants to be left in. It will look like caller_vcoreid
1716 * was preempted. Note we don't care about notif_pending.
1719 * 0 if we successfully changed to the target vcore.
1720 * -EBUSY if the target vcore is already mapped (a good kind of failure)
1721 * -EAGAIN if we failed for some other reason and need to try again. For
1722 * example, the caller could be preempted, and we never even attempted to
1724 * -EINVAL some userspace bug */
1725 int proc_change_to_vcore(struct proc *p, uint32_t new_vcoreid,
1726 bool enable_my_notif)
1728 uint32_t caller_vcoreid, pcoreid = core_id();
1729 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1730 struct preempt_data *caller_vcpd;
1731 struct vcore *caller_vc, *new_vc;
1732 struct event_msg preempt_msg = {0};
1734 int retval = -EAGAIN; /* by default, try again */
1735 /* Need to not reach outside the vcoremap, which might be smaller in the
1736 * future, but should always be as big as max_vcores */
1737 if (new_vcoreid >= p->procinfo->max_vcores)
1739 /* Need to lock before reading the vcoremap, like in yield. Need to do this
1740 * before disabling irqs (deadlock with incoming proc mgmt kmsgs) */
1741 spin_lock(&p->proc_lock);
1742 /* Need to disable before even reading caller_vcoreid, since we could be
1743 * unmapped by a __preempt or __death, like in yield. */
1744 disable_irqsave(&state);
1745 /* new_vcoreid is already runing, abort */
1746 if (vcore_is_mapped(p, new_vcoreid)) {
1750 /* Need to make sure our vcore is allowed to switch. We might have a
1751 * __preempt, __death, etc, coming in. Similar to yield. */
1753 case (PROC_RUNNING_M):
1754 break; /* the only case we can proceed */
1755 case (PROC_RUNNING_S): /* user bug, just return */
1756 case (PROC_DYING): /* incoming __death */
1757 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1760 panic("Weird state(%s) in %s()", procstate2str(p->state),
1763 /* Make sure we're still mapped in the proc. */
1764 if (!is_mapped_vcore(p, pcoreid))
1766 /* Get all our info */
1767 caller_vcoreid = get_vcoreid(p, pcoreid);
1768 assert(caller_vcoreid == pcpui->owning_vcoreid);
1769 caller_vcpd = &p->procdata->vcore_preempt_data[caller_vcoreid];
1770 caller_vc = vcoreid2vcore(p, caller_vcoreid);
1771 /* Should only call from vcore context */
1772 if (!caller_vcpd->notif_disabled) {
1774 printk("[kernel] You tried to change vcores from uthread ctx\n");
1777 /* Sanity check, can remove after a while (we should have been unmapped) */
1778 assert(!caller_vc->preempt_served);
1779 /* Ok, we're clear to do the switch. Lets figure out who the new one is */
1780 new_vc = vcoreid2vcore(p, new_vcoreid);
1781 printd("[kernel] changing vcore %d to vcore %d\n", caller_vcoreid,
1783 /* enable_my_notif signals how we'll be restarted */
1784 if (enable_my_notif) {
1785 /* if they set this flag, then the vcore can just restart from scratch,
1786 * and we don't care about either the notif_tf or the preempt_tf. */
1787 caller_vcpd->notif_disabled = FALSE;
1789 /* need to set up the calling vcore's tf so that it'll get restarted by
1790 * __startcore, to make the caller look like it was preempted. */
1791 caller_vcpd->preempt_tf = *current_tf;
1792 save_fp_state(&caller_vcpd->preempt_anc);
1793 /* Mark our core as preempted (for userspace recovery). */
1794 atomic_or(&caller_vcpd->flags, VC_PREEMPTED);
1796 /* Either way, unmap and offline our current vcore */
1797 /* Move the caller from online to inactive */
1798 TAILQ_REMOVE(&p->online_vcs, caller_vc, list);
1799 /* We don't bother with the notif_pending race. note that notif_pending
1800 * could still be set. this was a preempted vcore, and userspace will need
1801 * to deal with missed messages (preempt_recover() will handle that) */
1802 TAILQ_INSERT_HEAD(&p->inactive_vcs, caller_vc, list);
1803 /* Move the new one from inactive to online */
1804 TAILQ_REMOVE(&p->inactive_vcs, new_vc, list);
1805 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1806 /* Change the vcore map (TODO: might get rid of this seqctr) */
1807 __seq_start_write(&p->procinfo->coremap_seqctr);
1808 __unmap_vcore(p, caller_vcoreid);
1809 __map_vcore(p, new_vcoreid, pcoreid);
1810 __seq_end_write(&p->procinfo->coremap_seqctr);
1811 /* So this core knows which vcore is here: */
1812 pcpui->owning_vcoreid = new_vcoreid;
1813 /* Send either a PREEMPT msg or a CHECK_MSGS msg. If they said to
1814 * enable_my_notif, then all userspace needs is to check messages, not a
1815 * full preemption recovery. */
1816 preempt_msg.ev_type = (enable_my_notif ? EV_CHECK_MSGS : EV_VCORE_PREEMPT);
1817 preempt_msg.ev_arg2 = caller_vcoreid; /* arg2 is 32 bits */
1818 /* Whenever we send msgs with the proc locked, we need at least 1 online.
1819 * In this case, it's the one we just changed to. */
1820 assert(!TAILQ_EMPTY(&p->online_vcs));
1821 send_kernel_event(p, &preempt_msg, new_vcoreid);
1822 /* Change cur_tf so we'll be the new vcoreid */
1823 __set_curtf_to_vcoreid(p, new_vcoreid);
1825 /* Fall through to exit */
1827 spin_unlock(&p->proc_lock);
1828 enable_irqsave(&state);
1832 /* Kernel message handler to start a process's context on this core, when the
1833 * core next considers running a process. Tightly coupled with __proc_run_m().
1834 * Interrupts are disabled. */
1835 void __startcore(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1837 uint32_t vcoreid = (uint32_t)a1;
1838 uint32_t coreid = core_id();
1839 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1840 struct proc *p_to_run = (struct proc *CT(1))a0;
1843 /* Can not be any TF from a process here already */
1844 assert(!pcpui->owning_proc);
1845 /* the sender of the amsg increfed already for this saved ref to p_to_run */
1846 pcpui->owning_proc = p_to_run;
1847 pcpui->owning_vcoreid = vcoreid;
1848 /* sender increfed again, assuming we'd install to cur_proc. only do this
1849 * if no one else is there. this is an optimization, since we expect to
1850 * send these __startcores to idles cores, and this saves a scramble to
1851 * incref when all of the cores restartcore/startcore later. Keep in sync
1852 * with __proc_give_cores() and __proc_run_m(). */
1853 if (!pcpui->cur_proc) {
1854 pcpui->cur_proc = p_to_run; /* install the ref to cur_proc */
1855 lcr3(p_to_run->env_cr3); /* load the page tables to match cur_proc */
1857 proc_decref(p_to_run); /* can't install, decref the extra one */
1859 /* Note we are not necessarily in the cr3 of p_to_run */
1860 /* Now that we sorted refcnts and know p / which vcore it should be, set up
1861 * pcpui->cur_tf so that it will run that particular vcore */
1862 __set_curtf_to_vcoreid(p_to_run, vcoreid);
1865 /* Bail out if it's the wrong process, or if they no longer want a notif. Don't
1866 * use the TF we passed in, we care about cur_tf. Try not to grab locks or
1867 * write access to anything that isn't per-core in here. */
1868 void __notify(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1870 uint32_t vcoreid, coreid = core_id();
1871 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1872 struct preempt_data *vcpd;
1873 struct proc *p = (struct proc*)a0;
1875 /* Not the right proc */
1876 if (p != pcpui->owning_proc)
1878 /* Common cur_tf sanity checks. Note cur_tf could be an _S's env_tf */
1879 assert(pcpui->cur_tf);
1880 assert(!in_kernel(pcpui->cur_tf));
1881 vcoreid = pcpui->owning_vcoreid;
1882 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1883 /* for SCPs that haven't (and might never) call vc_event_init, like rtld.
1884 * this is harmless for MCPS to check this */
1885 if (!scp_is_vcctx_ready(vcpd))
1887 printd("received active notification for proc %d's vcore %d on pcore %d\n",
1888 p->procinfo->pid, vcoreid, coreid);
1889 /* sort signals. notifs are now masked, like an interrupt gate */
1890 if (vcpd->notif_disabled)
1892 vcpd->notif_disabled = TRUE;
1893 /* save the old tf in the notify slot, build and pop a new one. Note that
1894 * silly state isn't our business for a notification. */
1895 vcpd->notif_tf = *pcpui->cur_tf;
1896 memset(pcpui->cur_tf, 0, sizeof(struct trapframe));
1897 proc_init_trapframe(pcpui->cur_tf, vcoreid, p->env_entry,
1898 vcpd->transition_stack);
1899 /* this cur_tf will get run when the kernel returns / idles */
1902 void __preempt(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1904 uint32_t vcoreid, coreid = core_id();
1905 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1906 struct preempt_data *vcpd;
1907 struct proc *p = (struct proc*)a0;
1910 if (p != pcpui->owning_proc) {
1911 panic("__preempt arrived for a process (%p) that was not owning (%p)!",
1912 p, pcpui->owning_proc);
1914 /* Common cur_tf sanity checks */
1915 assert(pcpui->cur_tf);
1916 assert(pcpui->cur_tf == &pcpui->actual_tf);
1917 assert(!in_kernel(pcpui->cur_tf));
1918 vcoreid = pcpui->owning_vcoreid;
1919 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1920 printd("[kernel] received __preempt for proc %d's vcore %d on pcore %d\n",
1921 p->procinfo->pid, vcoreid, coreid);
1922 /* if notifs are disabled, the vcore is in vcore context (as far as we're
1923 * concerned), and we save it in the preempt slot. o/w, we save the
1924 * process's cur_tf in the notif slot, and it'll appear to the vcore when it
1925 * comes back up that it just took a notification. */
1926 if (vcpd->notif_disabled)
1927 vcpd->preempt_tf = *pcpui->cur_tf;
1929 vcpd->notif_tf = *pcpui->cur_tf;
1930 /* either way, we save the silly state (FP) */
1931 save_fp_state(&vcpd->preempt_anc);
1932 /* Mark the vcore as preempted and unlock (was locked by the sender). */
1933 atomic_or(&vcpd->flags, VC_PREEMPTED);
1934 atomic_and(&vcpd->flags, ~VC_K_LOCK);
1935 wmb(); /* make sure everything else hits before we finish the preempt */
1936 p->procinfo->vcoremap[vcoreid].preempt_served = FALSE;
1937 /* either __preempt or proc_yield() ends the preempt phase. */
1938 p->procinfo->vcoremap[vcoreid].preempt_pending = 0;
1939 /* We won't restart the process later. current gets cleared later when we
1940 * notice there is no owning_proc and we have nothing to do (smp_idle,
1941 * restartcore, etc) */
1942 clear_owning_proc(coreid);
1945 /* Kernel message handler to clean up the core when a process is dying.
1946 * Note this leaves no trace of what was running.
1947 * It's okay if death comes to a core that's already idling and has no current.
1948 * It could happen if a process decref'd before __proc_startcore could incref. */
1949 void __death(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1951 uint32_t vcoreid, coreid = core_id();
1952 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1953 struct proc *p = pcpui->owning_proc;
1955 vcoreid = pcpui->owning_vcoreid;
1956 printd("[kernel] death on physical core %d for process %d's vcore %d\n",
1957 coreid, p->pid, vcoreid);
1958 /* We won't restart the process later. current gets cleared later when
1959 * we notice there is no owning_proc and we have nothing to do
1960 * (smp_idle, restartcore, etc) */
1961 clear_owning_proc(coreid);
1965 /* Kernel message handler, usually sent IMMEDIATE, to shoot down virtual
1966 * addresses from a0 to a1. */
1967 void __tlbshootdown(struct trapframe *tf, uint32_t srcid, long a0, long a1,
1970 /* TODO: (TLB) something more intelligent with the range */
1974 void print_allpids(void)
1976 void print_proc_state(void *item)
1978 struct proc *p = (struct proc*)item;
1980 printk("%8d %s\n", p->pid, procstate2str(p->state));
1982 printk("PID STATE \n");
1983 printk("------------------\n");
1984 spin_lock(&pid_hash_lock);
1985 hash_for_each(pid_hash, print_proc_state);
1986 spin_unlock(&pid_hash_lock);
1989 void print_proc_info(pid_t pid)
1992 struct proc *p = pid2proc(pid);
1995 printk("Bad PID.\n");
1998 spinlock_debug(&p->proc_lock);
1999 //spin_lock(&p->proc_lock); // No locking!!
2000 printk("struct proc: %p\n", p);
2001 printk("PID: %d\n", p->pid);
2002 printk("PPID: %d\n", p->ppid);
2003 printk("State: %s (%p)\n", procstate2str(p->state), p->state);
2004 printk("Refcnt: %d\n", atomic_read(&p->p_kref.refcount) - 1);
2005 printk("Flags: 0x%08x\n", p->env_flags);
2006 printk("CR3(phys): 0x%08x\n", p->env_cr3);
2007 printk("Num Vcores: %d\n", p->procinfo->num_vcores);
2008 printk("Vcore Lists (may be in flux w/o locking):\n----------------------\n");
2009 printk("Online:\n");
2010 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
2011 printk("\tVcore %d -> Pcore %d\n", vcore2vcoreid(p, vc_i), vc_i->pcoreid);
2012 printk("Bulk Preempted:\n");
2013 TAILQ_FOREACH(vc_i, &p->bulk_preempted_vcs, list)
2014 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2015 printk("Inactive / Yielded:\n");
2016 TAILQ_FOREACH(vc_i, &p->inactive_vcs, list)
2017 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2018 printk("Resources:\n------------------------\n");
2019 for (int i = 0; i < MAX_NUM_RESOURCES; i++)
2020 printk("\tRes type: %02d, amt wanted: %08d, amt granted: %08d\n", i,
2021 p->procdata->res_req[i].amt_wanted, p->procinfo->res_grant[i]);
2022 printk("Open Files:\n");
2023 struct files_struct *files = &p->open_files;
2024 spin_lock(&files->lock);
2025 for (int i = 0; i < files->max_files; i++)
2026 if (files->fd_array[i].fd_file) {
2027 printk("\tFD: %02d, File: %08p, File name: %s\n", i,
2028 files->fd_array[i].fd_file,
2029 file_name(files->fd_array[i].fd_file));
2031 spin_unlock(&files->lock);
2032 /* No one cares, and it clutters the terminal */
2033 //printk("Vcore 0's Last Trapframe:\n");
2034 //print_trapframe(&p->env_tf);
2035 /* no locking / unlocking or refcnting */
2036 // spin_unlock(&p->proc_lock);
2040 /* Debugging function, checks what (process, vcore) is supposed to run on this
2041 * pcore. Meant to be called from smp_idle() before halting. */
2042 void check_my_owner(void)
2044 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2045 void shazbot(void *item)
2047 struct proc *p = (struct proc*)item;
2050 spin_lock(&p->proc_lock);
2051 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
2052 /* this isn't true, a __startcore could be on the way and we're
2053 * already "online" */
2054 if (vc_i->pcoreid == core_id()) {
2055 /* Immediate message was sent, we should get it when we enable
2056 * interrupts, which should cause us to skip cpu_halt() */
2057 if (!STAILQ_EMPTY(&pcpui->immed_amsgs))
2059 printk("Owned pcore (%d) has no owner, by %08p, vc %d!\n",
2060 core_id(), p, vcore2vcoreid(p, vc_i));
2061 spin_unlock(&p->proc_lock);
2062 spin_unlock(&pid_hash_lock);
2066 spin_unlock(&p->proc_lock);
2068 assert(!irq_is_enabled());
2070 if (!booting && !pcpui->owning_proc) {
2071 spin_lock(&pid_hash_lock);
2072 hash_for_each(pid_hash, shazbot);
2073 spin_unlock(&pid_hash_lock);