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, struct user_context *ctx);
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);
42 static void save_vc_fp_state(struct preempt_data *vcpd);
43 static void restore_vc_fp_state(struct preempt_data *vcpd);
46 #define PID_MAX 32767 // goes from 0 to 32767, with 0 reserved
47 static DECL_BITMASK(pid_bmask, PID_MAX + 1);
48 spinlock_t pid_bmask_lock = SPINLOCK_INITIALIZER;
49 struct hashtable *pid_hash;
50 spinlock_t pid_hash_lock; // initialized in proc_init
52 /* Finds the next free entry (zero) entry in the pid_bitmask. Set means busy.
53 * PID 0 is reserved (in proc_init). A return value of 0 is a failure (and
54 * you'll also see a warning, for now). Consider doing this with atomics. */
55 static pid_t get_free_pid(void)
57 static pid_t next_free_pid = 1;
60 spin_lock(&pid_bmask_lock);
61 // atomically (can lock for now, then change to atomic_and_return
62 FOR_CIRC_BUFFER(next_free_pid, PID_MAX + 1, i) {
63 // always points to the next to test
64 next_free_pid = (next_free_pid + 1) % (PID_MAX + 1);
65 if (!GET_BITMASK_BIT(pid_bmask, i)) {
66 SET_BITMASK_BIT(pid_bmask, i);
71 spin_unlock(&pid_bmask_lock);
73 warn("Shazbot! Unable to find a PID! You need to deal with this!\n");
77 /* Return a pid to the pid bitmask */
78 static void put_free_pid(pid_t pid)
80 spin_lock(&pid_bmask_lock);
81 CLR_BITMASK_BIT(pid_bmask, pid);
82 spin_unlock(&pid_bmask_lock);
85 /* While this could be done with just an assignment, this gives us the
86 * opportunity to check for bad transitions. Might compile these out later, so
87 * we shouldn't rely on them for sanity checking from userspace. */
88 int __proc_set_state(struct proc *p, uint32_t state)
90 uint32_t curstate = p->state;
109 * These ought to be implemented later (allowed, not thought through yet).
113 #if 1 // some sort of correctness flag
116 if (!(state & (PROC_RUNNABLE_S | PROC_DYING)))
117 panic("Invalid State Transition! PROC_CREATED to %02x", state);
119 case PROC_RUNNABLE_S:
120 if (!(state & (PROC_RUNNING_S | PROC_DYING)))
121 panic("Invalid State Transition! PROC_RUNNABLE_S to %02x", state);
124 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
126 panic("Invalid State Transition! PROC_RUNNING_S to %02x", state);
129 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNING_S | PROC_RUNNABLE_M |
131 panic("Invalid State Transition! PROC_WAITING to %02x", state);
134 if (state != PROC_CREATED) // when it is reused (TODO)
135 panic("Invalid State Transition! PROC_DYING to %02x", state);
137 case PROC_RUNNABLE_M:
138 if (!(state & (PROC_RUNNING_M | PROC_DYING)))
139 panic("Invalid State Transition! PROC_RUNNABLE_M to %02x", state);
142 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
144 panic("Invalid State Transition! PROC_RUNNING_M to %02x", state);
152 /* Returns a pointer to the proc with the given pid, or 0 if there is none.
153 * This uses get_not_zero, since it is possible the refcnt is 0, which means the
154 * process is dying and we should not have the ref (and thus return 0). We need
155 * to lock to protect us from getting p, (someone else removes and frees p),
156 * then get_not_zero() on p.
157 * Don't push the locking into the hashtable without dealing with this. */
158 struct proc *pid2proc(pid_t pid)
160 spin_lock(&pid_hash_lock);
161 struct proc *p = hashtable_search(pid_hash, (void*)(long)pid);
163 if (!kref_get_not_zero(&p->p_kref, 1))
165 spin_unlock(&pid_hash_lock);
169 /* Performs any initialization related to processes, such as create the proc
170 * cache, prep the scheduler, etc. When this returns, we should be ready to use
171 * any process related function. */
174 /* Catch issues with the vcoremap and TAILQ_ENTRY sizes */
175 static_assert(sizeof(TAILQ_ENTRY(vcore)) == sizeof(void*) * 2);
176 proc_cache = kmem_cache_create("proc", sizeof(struct proc),
177 MAX(ARCH_CL_SIZE, __alignof__(struct proc)), 0, 0, 0);
178 /* Init PID mask and hash. pid 0 is reserved. */
179 SET_BITMASK_BIT(pid_bmask, 0);
180 spinlock_init(&pid_hash_lock);
181 spin_lock(&pid_hash_lock);
182 pid_hash = create_hashtable(100, __generic_hash, __generic_eq);
183 spin_unlock(&pid_hash_lock);
186 atomic_init(&num_envs, 0);
189 /* Be sure you init'd the vcore lists before calling this. */
190 static void proc_init_procinfo(struct proc* p)
192 p->procinfo->pid = p->pid;
193 p->procinfo->ppid = p->ppid;
194 p->procinfo->max_vcores = max_vcores(p);
195 p->procinfo->tsc_freq = system_timing.tsc_freq;
196 p->procinfo->timing_overhead = system_timing.timing_overhead;
197 p->procinfo->heap_bottom = (void*)UTEXT;
198 /* 0'ing the arguments. Some higher function will need to set them */
199 memset(p->procinfo->argp, 0, sizeof(p->procinfo->argp));
200 memset(p->procinfo->argbuf, 0, sizeof(p->procinfo->argbuf));
201 memset(p->procinfo->res_grant, 0, sizeof(p->procinfo->res_grant));
202 /* 0'ing the vcore/pcore map. Will link the vcores later. */
203 memset(&p->procinfo->vcoremap, 0, sizeof(p->procinfo->vcoremap));
204 memset(&p->procinfo->pcoremap, 0, sizeof(p->procinfo->pcoremap));
205 p->procinfo->num_vcores = 0;
206 p->procinfo->is_mcp = FALSE;
207 p->procinfo->coremap_seqctr = SEQCTR_INITIALIZER;
208 /* For now, we'll go up to the max num_cpus (at runtime). In the future,
209 * there may be cases where we can have more vcores than num_cpus, but for
210 * now we'll leave it like this. */
211 for (int i = 0; i < num_cpus; i++) {
212 TAILQ_INSERT_TAIL(&p->inactive_vcs, &p->procinfo->vcoremap[i], list);
216 static void proc_init_procdata(struct proc *p)
218 memset(p->procdata, 0, sizeof(struct procdata));
219 /* processes can't go into vc context on vc 0 til they unset this. This is
220 * for processes that block before initing uthread code (like rtld). */
221 atomic_set(&p->procdata->vcore_preempt_data[0].flags, VC_SCP_NOVCCTX);
224 /* Allocates and initializes a process, with the given parent. Currently
225 * writes the *p into **pp, and returns 0 on success, < 0 for an error.
227 * - ENOFREEPID if it can't get a PID
228 * - ENOMEM on memory exhaustion */
229 error_t proc_alloc(struct proc **pp, struct proc *parent)
234 if (!(p = kmem_cache_alloc(proc_cache, 0)))
236 /* zero everything by default, other specific items are set below */
237 memset(p, 0, sizeof(struct proc));
241 /* only one ref, which we pass back. the old 'existence' ref is managed by
243 kref_init(&p->p_kref, __proc_free, 1);
244 // Setup the default map of where to get cache colors from
245 p->cache_colors_map = global_cache_colors_map;
246 p->next_cache_color = 0;
247 /* Initialize the address space */
248 if ((r = env_setup_vm(p)) < 0) {
249 kmem_cache_free(proc_cache, p);
252 if (!(p->pid = get_free_pid())) {
253 kmem_cache_free(proc_cache, p);
256 /* Set the basic status variables. */
257 spinlock_init(&p->proc_lock);
258 p->exitcode = 1337; /* so we can see processes killed by the kernel */
260 p->ppid = parent->pid;
261 /* using the CV's lock to protect anything related to child waiting */
262 cv_lock(&parent->child_wait);
263 TAILQ_INSERT_TAIL(&parent->children, p, sibling_link);
264 cv_unlock(&parent->child_wait);
268 TAILQ_INIT(&p->children);
269 cv_init(&p->child_wait);
270 p->state = PROC_CREATED; /* shouldn't go through state machine for init */
272 p->env_entry = 0; // cheating. this really gets set later
273 p->heap_top = (void*)UTEXT; /* heap_bottom set in proc_init_procinfo */
274 spinlock_init(&p->mm_lock);
275 TAILQ_INIT(&p->vm_regions); /* could init this in the slab */
276 /* Initialize the vcore lists, we'll build the inactive list so that it includes
277 * all vcores when we initialize procinfo. Do this before initing procinfo. */
278 TAILQ_INIT(&p->online_vcs);
279 TAILQ_INIT(&p->bulk_preempted_vcs);
280 TAILQ_INIT(&p->inactive_vcs);
281 /* Init procinfo/procdata. Procinfo's argp/argb are 0'd */
282 proc_init_procinfo(p);
283 proc_init_procdata(p);
285 /* Initialize the generic sysevent ring buffer */
286 SHARED_RING_INIT(&p->procdata->syseventring);
287 /* Initialize the frontend of the sysevent ring buffer */
288 FRONT_RING_INIT(&p->syseventfrontring,
289 &p->procdata->syseventring,
292 /* Init FS structures TODO: cleanup (might pull this out) */
293 kref_get(&default_ns.kref, 1);
295 spinlock_init(&p->fs_env.lock);
296 p->fs_env.umask = parent ? parent->fs_env.umask : S_IWGRP | S_IWOTH;
297 p->fs_env.root = p->ns->root->mnt_root;
298 kref_get(&p->fs_env.root->d_kref, 1);
299 p->fs_env.pwd = parent ? parent->fs_env.pwd : p->fs_env.root;
300 kref_get(&p->fs_env.pwd->d_kref, 1);
301 memset(&p->open_files, 0, sizeof(p->open_files)); /* slightly ghetto */
302 spinlock_init(&p->open_files.lock);
303 p->open_files.max_files = NR_OPEN_FILES_DEFAULT;
304 p->open_files.max_fdset = NR_FILE_DESC_DEFAULT;
305 p->open_files.fd = p->open_files.fd_array;
306 p->open_files.open_fds = (struct fd_set*)&p->open_files.open_fds_init;
307 /* Init the ucq hash lock */
308 p->ucq_hashlock = (struct hashlock*)&p->ucq_hl_noref;
309 hashlock_init_irqsave(p->ucq_hashlock, HASHLOCK_DEFAULT_SZ);
311 atomic_inc(&num_envs);
312 frontend_proc_init(p);
313 printd("[%08x] new process %08x\n", current ? current->pid : 0, p->pid);
319 /* We have a bunch of different ways to make processes. Call this once the
320 * process is ready to be used by the rest of the system. For now, this just
321 * means when it is ready to be named via the pidhash. In the future, we might
322 * push setting the state to CREATED into here. */
323 void __proc_ready(struct proc *p)
325 /* Tell the ksched about us. TODO: do we need to worry about the ksched
326 * doing stuff to us before we're added to the pid_hash? */
327 __sched_proc_register(p);
328 spin_lock(&pid_hash_lock);
329 hashtable_insert(pid_hash, (void*)(long)p->pid, p);
330 spin_unlock(&pid_hash_lock);
333 /* Creates a process from the specified file, argvs, and envps. Tempted to get
334 * rid of proc_alloc's style, but it is so quaint... */
335 struct proc *proc_create(struct file *prog, char **argv, char **envp)
339 if ((r = proc_alloc(&p, current)) < 0)
340 panic("proc_create: %e", r); /* one of 3 quaint usages of %e */
341 procinfo_pack_args(p->procinfo, argv, envp);
342 assert(load_elf(p, prog) == 0);
343 /* Connect to stdin, stdout, stderr */
344 assert(insert_file(&p->open_files, dev_stdin, 0) == 0);
345 assert(insert_file(&p->open_files, dev_stdout, 0) == 1);
346 assert(insert_file(&p->open_files, dev_stderr, 0) == 2);
351 /* This is called by kref_put(), once the last reference to the process is
352 * gone. Don't call this otherwise (it will panic). It will clean up the
353 * address space and deallocate any other used memory. */
354 static void __proc_free(struct kref *kref)
356 struct proc *p = container_of(kref, struct proc, p_kref);
359 printd("[PID %d] freeing proc: %d\n", current ? current->pid : 0, p->pid);
360 // All parts of the kernel should have decref'd before __proc_free is called
361 assert(kref_refcnt(&p->p_kref) == 0);
363 kref_put(&p->fs_env.root->d_kref);
364 kref_put(&p->fs_env.pwd->d_kref);
366 frontend_proc_free(p); /* TODO: please remove me one day */
367 /* Free any colors allocated to this process */
368 if (p->cache_colors_map != global_cache_colors_map) {
369 for(int i = 0; i < llc_cache->num_colors; i++)
370 cache_color_free(llc_cache, p->cache_colors_map);
371 cache_colors_map_free(p->cache_colors_map);
373 /* Remove us from the pid_hash and give our PID back (in that order). */
374 spin_lock(&pid_hash_lock);
375 if (!hashtable_remove(pid_hash, (void*)(long)p->pid))
376 panic("Proc not in the pid table in %s", __FUNCTION__);
377 spin_unlock(&pid_hash_lock);
378 put_free_pid(p->pid);
379 /* Flush all mapped pages in the user portion of the address space */
380 env_user_mem_free(p, 0, UVPT);
381 /* These need to be free again, since they were allocated with a refcnt. */
382 free_cont_pages(p->procinfo, LOG2_UP(PROCINFO_NUM_PAGES));
383 free_cont_pages(p->procdata, LOG2_UP(PROCDATA_NUM_PAGES));
385 env_pagetable_free(p);
389 atomic_dec(&num_envs);
391 /* Dealloc the struct proc */
392 kmem_cache_free(proc_cache, p);
395 /* Whether or not actor can control target. TODO: do something reasonable here.
396 * Just checking for the parent is a bit limiting. Could walk the parent-child
397 * tree, check user ids, or some combination. Make sure actors can always
398 * control themselves. */
399 bool proc_controls(struct proc *actor, struct proc *target)
403 return ((actor == target) || (target->ppid == actor->pid));
407 /* Helper to incref by val. Using the helper to help debug/interpose on proc
408 * ref counting. Note that pid2proc doesn't use this interface. */
409 void proc_incref(struct proc *p, unsigned int val)
411 kref_get(&p->p_kref, val);
414 /* Helper to decref for debugging. Don't directly kref_put() for now. */
415 void proc_decref(struct proc *p)
417 kref_put(&p->p_kref);
420 /* Helper, makes p the 'current' process, dropping the old current/cr3. This no
421 * longer assumes the passed in reference already counted 'current'. It will
422 * incref internally when needed. */
423 static void __set_proc_current(struct proc *p)
425 /* We use the pcpui to access 'current' to cut down on the core_id() calls,
426 * though who know how expensive/painful they are. */
427 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
428 /* If the process wasn't here, then we need to load its address space. */
429 if (p != pcpui->cur_proc) {
432 /* This is "leaving the process context" of the previous proc. The
433 * previous lcr3 unloaded the previous proc's context. This should
434 * rarely happen, since we usually proactively leave process context,
435 * but this is the fallback. */
437 proc_decref(pcpui->cur_proc);
442 /* Flag says if vcore context is not ready, which is set in init_procdata. The
443 * process must turn off this flag on vcore0 at some point. It's off by default
444 * on all other vcores. */
445 static bool scp_is_vcctx_ready(struct preempt_data *vcpd)
447 return !(atomic_read(&vcpd->flags) & VC_SCP_NOVCCTX);
450 /* Dispatches a _S process to run on the current core. This should never be
451 * called to "restart" a core.
453 * This will always return, regardless of whether or not the calling core is
454 * being given to a process. (it used to pop the tf directly, before we had
457 * Since it always returns, it will never "eat" your reference (old
458 * documentation talks about this a bit). */
459 void proc_run_s(struct proc *p)
461 uint32_t coreid = core_id();
462 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
463 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
464 spin_lock(&p->proc_lock);
467 spin_unlock(&p->proc_lock);
468 printk("[kernel] _S %d not starting due to async death\n", p->pid);
470 case (PROC_RUNNABLE_S):
471 __proc_set_state(p, PROC_RUNNING_S);
472 /* We will want to know where this process is running, even if it is
473 * only in RUNNING_S. can use the vcoremap, which makes death easy.
474 * Also, this is the signal used in trap.c to know to save the tf in
476 __seq_start_write(&p->procinfo->coremap_seqctr);
477 p->procinfo->num_vcores = 0; /* TODO (VC#) */
478 /* TODO: For now, we won't count this as an active vcore (on the
479 * lists). This gets unmapped in resource.c and yield_s, and needs
481 __map_vcore(p, 0, coreid); /* not treated like a true vcore */
482 __seq_end_write(&p->procinfo->coremap_seqctr);
483 /* incref, since we're saving a reference in owning proc later */
485 /* lock was protecting the state and VC mapping, not pcpui stuff */
486 spin_unlock(&p->proc_lock);
487 /* redundant with proc_startcore, might be able to remove that one*/
488 __set_proc_current(p);
489 /* set us up as owning_proc. ksched bug if there is already one,
490 * for now. can simply clear_owning if we want to. */
491 assert(!pcpui->owning_proc);
492 pcpui->owning_proc = p;
493 pcpui->owning_vcoreid = 0; /* TODO (VC#) */
494 restore_vc_fp_state(vcpd);
495 /* similar to the old __startcore, start them in vcore context if
496 * they have notifs and aren't already in vcore context. o/w, start
497 * them wherever they were before (could be either vc ctx or not) */
498 if (!vcpd->notif_disabled && vcpd->notif_pending
499 && scp_is_vcctx_ready(vcpd)) {
500 vcpd->notif_disabled = TRUE;
501 /* save the _S's ctx in the uthread slot, build and pop a new
502 * one in actual/cur_ctx. */
503 vcpd->uthread_ctx = p->scp_ctx;
504 pcpui->cur_ctx = &pcpui->actual_ctx;
505 memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
506 proc_init_ctx(pcpui->cur_ctx, 0, p->env_entry,
507 vcpd->transition_stack);
509 /* If they have no transition stack, then they can't receive
510 * events. The most they are getting is a wakeup from the
511 * kernel. They won't even turn off notif_pending, so we'll do
513 if (!scp_is_vcctx_ready(vcpd))
514 vcpd->notif_pending = FALSE;
515 /* this is one of the few times cur_ctx != &actual_ctx */
516 pcpui->cur_ctx = &p->scp_ctx;
518 /* When the calling core idles, it'll call restartcore and run the
519 * _S process's context. */
522 spin_unlock(&p->proc_lock);
523 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
527 /* Helper: sends preempt messages to all vcores on the bulk preempt list, and
528 * moves them to the inactive list. */
529 static void __send_bulkp_events(struct proc *p)
531 struct vcore *vc_i, *vc_temp;
532 struct event_msg preempt_msg = {0};
533 /* Whenever we send msgs with the proc locked, we need at least 1 online */
534 assert(!TAILQ_EMPTY(&p->online_vcs));
535 /* Send preempt messages for any left on the BP list. No need to set any
536 * flags, it all was done on the real preempt. Now we're just telling the
537 * process about any that didn't get restarted and are still preempted. */
538 TAILQ_FOREACH_SAFE(vc_i, &p->bulk_preempted_vcs, list, vc_temp) {
539 /* Note that if there are no active vcores, send_k_e will post to our
540 * own vcore, the last of which will be put on the inactive list and be
541 * the first to be started. We could have issues with deadlocking,
542 * since send_k_e() could grab the proclock (if there are no active
544 preempt_msg.ev_type = EV_VCORE_PREEMPT;
545 preempt_msg.ev_arg2 = vcore2vcoreid(p, vc_i); /* arg2 is 32 bits */
546 send_kernel_event(p, &preempt_msg, 0);
547 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that.
548 * We need a loop for the messages, but not necessarily for the list
550 TAILQ_REMOVE(&p->bulk_preempted_vcs, vc_i, list);
551 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
555 /* Run an _M. Can be called safely on one that is already running. Hold the
556 * lock before calling. Other than state checks, this just starts up the _M's
557 * vcores, much like the second part of give_cores_running. More specifically,
558 * give_cores_runnable puts cores on the online list, which this then sends
559 * messages to. give_cores_running immediately puts them on the list and sends
560 * the message. the two-step style may go out of fashion soon.
562 * This expects that the "instructions" for which core(s) to run this on will be
563 * in the vcoremap, which needs to be set externally (give_cores()). */
564 void __proc_run_m(struct proc *p)
570 warn("ksched tried to run proc %d in state %s\n", p->pid,
571 procstate2str(p->state));
573 case (PROC_RUNNABLE_M):
574 /* vcoremap[i] holds the coreid of the physical core allocated to
575 * this process. It is set outside proc_run. */
576 if (p->procinfo->num_vcores) {
577 __send_bulkp_events(p);
578 __proc_set_state(p, PROC_RUNNING_M);
579 /* Up the refcnt, to avoid the n refcnt upping on the
580 * destination cores. Keep in sync with __startcore */
581 proc_incref(p, p->procinfo->num_vcores * 2);
582 /* Send kernel messages to all online vcores (which were added
583 * to the list and mapped in __proc_give_cores()), making them
585 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
586 send_kernel_message(vc_i->pcoreid, __startcore, (long)p,
587 (long)vcore2vcoreid(p, vc_i),
588 (long)vc_i->nr_preempts_sent,
592 warn("Tried to proc_run() an _M with no vcores!");
594 /* There a subtle race avoidance here (when we unlock after sending
595 * the message). __proc_startcore can handle a death message, but
596 * we can't have the startcore come after the death message.
597 * Otherwise, it would look like a new process. So we hold the lock
598 * til after we send our message, which prevents a possible death
600 * - Note there is no guarantee this core's interrupts were on, so
601 * it may not get the message for a while... */
603 case (PROC_RUNNING_M):
606 /* unlock just so the monitor can call something that might lock*/
607 spin_unlock(&p->proc_lock);
608 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
612 /* Actually runs the given context (trapframe) of process p on the core this
613 * code executes on. This is called directly by __startcore, which needs to
614 * bypass the routine_kmsg check. Interrupts should be off when you call this.
616 * A note on refcnting: this function will not return, and your proc reference
617 * will end up stored in current. This will make no changes to p's refcnt, so
618 * do your accounting such that there is only the +1 for current. This means if
619 * it is already in current (like in the trap return path), don't up it. If
620 * it's already in current and you have another reference (like pid2proc or from
621 * an IPI), then down it (which is what happens in __startcore()). If it's not
622 * in current and you have one reference, like proc_run(non_current_p), then
623 * also do nothing. The refcnt for your *p will count for the reference stored
625 static void __proc_startcore(struct proc *p, struct user_context *ctx)
627 assert(!irq_is_enabled());
628 __set_proc_current(p);
629 /* Clear the current_ctx, since it is no longer used */
630 current_ctx = 0; /* TODO: might not need this... */
634 /* Restarts/runs the current_ctx, which must be for the current process, on the
635 * core this code executes on. Calls an internal function to do the work.
637 * In case there are pending routine messages, like __death, __preempt, or
638 * __notify, we need to run them. Alternatively, if there are any, we could
639 * self_ipi, and run the messages immediately after popping back to userspace,
640 * but that would have crappy overhead.
642 * Refcnting: this will not return, and it assumes that you've accounted for
643 * your reference as if it was the ref for "current" (which is what happens when
644 * returning from local traps and such. */
645 void proc_restartcore(void)
647 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
648 assert(!pcpui->cur_sysc);
649 /* TODO: can probably remove this enable_irq. it was an optimization for
651 /* Try and get any interrupts before we pop back to userspace. If we didn't
652 * do this, we'd just get them in userspace, but this might save us some
653 * effort/overhead. */
655 /* Need ints disabled when we return from processing (race on missing
658 process_routine_kmsg();
659 /* If there is no owning process, just idle, since we don't know what to do.
660 * This could be because the process had been restarted a long time ago and
661 * has since left the core, or due to a KMSG like __preempt or __death. */
662 if (!pcpui->owning_proc) {
666 assert(pcpui->cur_ctx);
667 __proc_startcore(pcpui->owning_proc, pcpui->cur_ctx);
670 /* Destroys the process. It will destroy the process and return any cores
671 * to the ksched via the __sched_proc_destroy() CB.
673 * Here's the way process death works:
674 * 0. grab the lock (protects state transition and core map)
675 * 1. set state to dying. that keeps the kernel from doing anything for the
676 * process (like proc_running it).
677 * 2. figure out where the process is running (cross-core/async or RUNNING_M)
678 * 3. IPI to clean up those cores (decref, etc).
680 * 5. Clean up your core, if applicable
681 * (Last core/kernel thread to decref cleans up and deallocates resources.)
683 * Note that some cores can be processing async calls, but will eventually
684 * decref. Should think about this more, like some sort of callback/revocation.
686 * This function will now always return (it used to not return if the calling
687 * core was dying). However, when it returns, a kernel message will eventually
688 * come in, making you abandon_core, as if you weren't running. It may be that
689 * the only reference to p is the one you passed in, and when you decref, it'll
690 * get __proc_free()d. */
691 void proc_destroy(struct proc *p)
693 uint32_t nr_cores_revoked = 0;
694 struct kthread *sleeper;
695 struct proc *child_i, *temp;
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 /* Disown any children. If we want to have init inherit or something,
747 * change __disown to set the ppid accordingly and concat this with init's
748 * list (instead of emptying it like disown does). Careful of lock ordering
749 * between procs (need to lock to protect lists) */
750 TAILQ_FOREACH_SAFE(child_i, &p->children, sibling_link, temp) {
751 int ret = __proc_disown_child(p, child_i);
752 /* should never fail, lock should cover the race. invariant: any child
753 * on the list should have us as a parent */
756 spin_unlock(&p->proc_lock);
757 /* Wake any of our kthreads waiting on children, so they can abort */
758 cv_broadcast(&p->child_wait);
759 /* This prevents processes from accessing their old files while dying, and
760 * will help if these files (or similar objects in the future) hold
761 * references to p (preventing a __proc_free()). Need to unlock before
762 * doing this - the proclock doesn't protect the files (not proc state), and
763 * closing these might block (can't block while spinning). */
764 /* TODO: might need some sync protection */
765 close_all_files(&p->open_files, FALSE);
766 /* Tell the ksched about our death, and which cores we freed up */
767 __sched_proc_destroy(p, pc_arr, nr_cores_revoked);
768 /* Tell our parent about our state change (to DYING) */
769 proc_signal_parent(p);
772 /* Can use this to signal anything that might cause a parent to wait on the
773 * child, such as termination, or (in the future) signals. Change the state or
774 * whatever before calling. */
775 void proc_signal_parent(struct proc *child)
777 struct kthread *sleeper;
778 struct proc *parent = pid2proc(child->ppid);
781 /* there could be multiple kthreads sleeping for various reasons. even an
782 * SCP could have multiple async syscalls. */
783 cv_broadcast(&parent->child_wait);
784 /* if the parent was waiting, there's a __launch kthread KMSG out there */
788 /* Called when a parent is done with its child, and no longer wants to track the
789 * child, nor to allow the child to track it. Call with a lock (cv) held.
790 * Returns 0 if we disowned, -1 on failure. */
791 int __proc_disown_child(struct proc *parent, struct proc *child)
793 /* Bail out if the child has already been reaped */
796 assert(child->ppid == parent->pid);
797 /* lock protects from concurrent inserts / removals from the list */
798 TAILQ_REMOVE(&parent->children, child, sibling_link);
799 /* After this, the child won't be able to get more refs to us, but it may
800 * still have some references in running code. */
802 proc_decref(child); /* ref that was keeping the child alive after dying */
806 /* Turns *p into an MCP. Needs to be called from a local syscall of a RUNNING_S
807 * process. Returns 0 if it succeeded, an error code otherwise. */
808 int proc_change_to_m(struct proc *p)
811 spin_lock(&p->proc_lock);
812 /* in case userspace erroneously tries to change more than once */
813 if (__proc_is_mcp(p))
816 case (PROC_RUNNING_S):
817 /* issue with if we're async or not (need to preempt it)
818 * either of these should trip it. TODO: (ACR) async core req
819 * TODO: relies on vcore0 being the caller (VC#) */
820 if ((current != p) || (get_pcoreid(p, 0) != core_id()))
821 panic("We don't handle async RUNNING_S core requests yet.");
822 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
824 /* Copy uthread0's context to VC 0's uthread slot */
825 vcpd->uthread_ctx = *current_ctx;
826 clear_owning_proc(core_id()); /* so we don't restart */
827 save_vc_fp_state(vcpd);
828 /* Userspace needs to not fuck with notif_disabled before
829 * transitioning to _M. */
830 if (vcpd->notif_disabled) {
831 printk("[kernel] user bug: notifs disabled for vcore 0\n");
832 vcpd->notif_disabled = FALSE;
834 /* in the async case, we'll need to remotely stop and bundle
835 * vcore0's TF. this is already done for the sync case (local
837 /* this process no longer runs on its old location (which is
838 * this core, for now, since we don't handle async calls) */
839 __seq_start_write(&p->procinfo->coremap_seqctr);
840 // TODO: (VC#) might need to adjust num_vcores
841 // TODO: (ACR) will need to unmap remotely (receive-side)
842 __unmap_vcore(p, 0); /* VC# keep in sync with proc_run_s */
843 __seq_end_write(&p->procinfo->coremap_seqctr);
844 /* change to runnable_m (it's TF is already saved) */
845 __proc_set_state(p, PROC_RUNNABLE_M);
846 p->procinfo->is_mcp = TRUE;
847 spin_unlock(&p->proc_lock);
848 /* Tell the ksched that we're a real MCP now! */
849 __sched_proc_change_to_m(p);
851 case (PROC_RUNNABLE_S):
852 /* Issues: being on the runnable_list, proc_set_state not liking
853 * it, and not clearly thinking through how this would happen.
854 * Perhaps an async call that gets serviced after you're
856 warn("Not supporting RUNNABLE_S -> RUNNABLE_M yet.\n");
859 warn("Dying, core request coming from %d\n", core_id());
865 spin_unlock(&p->proc_lock);
869 /* Old code to turn a RUNNING_M to a RUNNING_S, with the calling context
870 * becoming the new 'thread0'. Don't use this. Caller needs to send in a
871 * pc_arr big enough for all vcores. Will return the number of cores given up
873 uint32_t __proc_change_to_s(struct proc *p, uint32_t *pc_arr)
875 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
876 uint32_t num_revoked;
877 printk("[kernel] trying to transition _M -> _S (deprecated)!\n");
878 assert(p->state == PROC_RUNNING_M); // TODO: (ACR) async core req
879 /* save the context, to be restarted in _S mode */
881 p->scp_ctx = *current_ctx;
882 clear_owning_proc(core_id()); /* so we don't restart */
883 save_vc_fp_state(vcpd);
884 /* sending death, since it's not our job to save contexts or anything in
886 num_revoked = __proc_take_allcores(p, pc_arr, FALSE);
887 __proc_set_state(p, PROC_RUNNABLE_S);
891 /* Helper function. Is the given pcore a mapped vcore? No locking involved, be
893 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid)
895 return p->procinfo->pcoremap[pcoreid].valid;
898 /* Helper function. Find the vcoreid for a given physical core id for proc p.
899 * No locking involved, be careful. Panics on failure. */
900 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid)
902 assert(is_mapped_vcore(p, pcoreid));
903 return p->procinfo->pcoremap[pcoreid].vcoreid;
906 /* Helper function. Try to find the pcoreid for a given virtual core id for
907 * proc p. No locking involved, be careful. Use this when you can tolerate a
908 * stale or otherwise 'wrong' answer. */
909 static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid)
911 return p->procinfo->vcoremap[vcoreid].pcoreid;
914 /* Helper function. Find the pcoreid for a given virtual core id for proc p.
915 * No locking involved, be careful. Panics on failure. */
916 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid)
918 assert(vcore_is_mapped(p, vcoreid));
919 return try_get_pcoreid(p, vcoreid);
922 /* Saves the FP state of the calling core into VCPD. Pairs with
923 * restore_vc_fp_state(). On x86, the best case overhead of the flags:
927 * Flagged FXSAVE: 50 ns
928 * Flagged FXRSTR: 66 ns
929 * Excess flagged FXRSTR: 42 ns
930 * If we don't do it, we'll need to initialize every VCPD at process creation
931 * time with a good FPU state (x86 control words are initialized as 0s, like the
933 static void save_vc_fp_state(struct preempt_data *vcpd)
935 save_fp_state(&vcpd->preempt_anc);
936 vcpd->rflags |= VC_FPU_SAVED;
939 /* Conditionally restores the FP state from VCPD. If the state was not valid,
940 * we don't bother restoring and just initialize the FPU. */
941 static void restore_vc_fp_state(struct preempt_data *vcpd)
943 if (vcpd->rflags & VC_FPU_SAVED) {
944 restore_fp_state(&vcpd->preempt_anc);
945 vcpd->rflags &= ~VC_FPU_SAVED;
951 /* Helper for SCPs, saves the core's FPU state into the VCPD vc0 slot */
952 void __proc_save_fpu_s(struct proc *p)
954 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
955 save_vc_fp_state(vcpd);
958 /* Helper: saves the SCP's GP tf state and unmaps vcore 0. This does *not* save
961 * In the future, we'll probably use vc0's space for scp_ctx and the silly
962 * state. If we ever do that, we'll need to stop using scp_ctx (soon to be in
963 * VCPD) as a location for pcpui->cur_ctx to point (dangerous) */
964 void __proc_save_context_s(struct proc *p, struct user_context *ctx)
967 __unmap_vcore(p, 0); /* VC# keep in sync with proc_run_s */
970 /* Yields the calling core. Must be called locally (not async) for now.
971 * - If RUNNING_S, you just give up your time slice and will eventually return,
972 * possibly after WAITING on an event.
973 * - If RUNNING_M, you give up the current vcore (which never returns), and
974 * adjust the amount of cores wanted/granted.
975 * - If you have only one vcore, you switch to WAITING. There's no 'classic
976 * yield' for MCPs (at least not now). When you run again, you'll have one
977 * guaranteed core, starting from the entry point.
979 * If the call is being nice, it means different things for SCPs and MCPs. For
980 * MCPs, it means that it is in response to a preemption (which needs to be
981 * checked). If there is no preemption pending, just return. For SCPs, it
982 * means the proc wants to give up the core, but still has work to do. If not,
983 * the proc is trying to wait on an event. It's not being nice to others, it
984 * just has no work to do.
986 * This usually does not return (smp_idle()), so it will eat your reference.
987 * Also note that it needs a non-current/edible reference, since it will abandon
988 * and continue to use the *p (current == 0, no cr3, etc).
990 * We disable interrupts for most of it too, since we need to protect
991 * current_ctx and not race with __notify (which doesn't play well with
992 * concurrent yielders). */
993 void proc_yield(struct proc *SAFE p, bool being_nice)
995 uint32_t vcoreid, pcoreid = core_id();
996 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
998 struct preempt_data *vcpd;
999 /* Need to lock to prevent concurrent vcore changes (online, inactive, the
1000 * mapping, etc). This plus checking the nr_preempts is enough to tell if
1001 * our vcoreid and cur_ctx ought to be here still or if we should abort */
1002 spin_lock(&p->proc_lock); /* horrible scalability. =( */
1004 case (PROC_RUNNING_S):
1006 /* waiting for an event to unblock us */
1007 vcpd = &p->procdata->vcore_preempt_data[0];
1008 /* syncing with event's SCP code. we set waiting, then check
1009 * pending. they set pending, then check waiting. it's not
1010 * possible for us to miss the notif *and* for them to miss
1011 * WAITING. one (or both) of us will see and make sure the proc
1013 __proc_set_state(p, PROC_WAITING);
1014 wrmb(); /* don't let the state write pass the notif read */
1015 if (vcpd->notif_pending) {
1016 __proc_set_state(p, PROC_RUNNING_S);
1017 /* they can't handle events, just need to prevent a yield.
1018 * (note the notif_pendings are collapsed). */
1019 if (!scp_is_vcctx_ready(vcpd))
1020 vcpd->notif_pending = FALSE;
1023 /* if we're here, we want to sleep. a concurrent event that
1024 * hasn't already written notif_pending will have seen WAITING,
1025 * and will be spinning while we do this. */
1026 __proc_save_context_s(p, current_ctx);
1027 spin_unlock(&p->proc_lock);
1029 /* yielding to allow other processes to run. we're briefly
1030 * WAITING, til we are woken up */
1031 __proc_set_state(p, PROC_WAITING);
1032 __proc_save_context_s(p, current_ctx);
1033 spin_unlock(&p->proc_lock);
1034 /* immediately wake up the proc (makes it runnable) */
1037 goto out_yield_core;
1038 case (PROC_RUNNING_M):
1039 break; /* will handle this stuff below */
1040 case (PROC_DYING): /* incoming __death */
1041 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1044 panic("Weird state(%s) in %s()", procstate2str(p->state),
1047 /* This is which vcore this pcore thinks it is, regardless of any unmappings
1048 * that may have happened remotely (with __PRs waiting to run) */
1049 vcoreid = pcpui->owning_vcoreid;
1050 vc = vcoreid2vcore(p, vcoreid);
1051 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1052 /* This is how we detect whether or not a __PR happened. */
1053 if (vc->nr_preempts_sent != vc->nr_preempts_done)
1055 /* Sanity checks. If we were preempted or are dying, we should have noticed
1057 assert(is_mapped_vcore(p, pcoreid));
1058 assert(vcoreid == get_vcoreid(p, pcoreid));
1059 /* no reason to be nice, return */
1060 if (being_nice && !vc->preempt_pending)
1062 /* At this point, AFAIK there should be no preempt/death messages on the
1063 * way, and we're on the online list. So we'll go ahead and do the yielding
1065 /* If there's a preempt pending, we don't need to preempt later since we are
1066 * yielding (nice or otherwise). If not, this is just a regular yield. */
1067 if (vc->preempt_pending) {
1068 vc->preempt_pending = 0;
1070 /* Optional: on a normal yield, check to see if we are putting them
1071 * below amt_wanted (help with user races) and bail. */
1072 if (p->procdata->res_req[RES_CORES].amt_wanted >=
1073 p->procinfo->num_vcores)
1076 /* Don't let them yield if they are missing a notification. Userspace must
1077 * not leave vcore context without dealing with notif_pending.
1078 * pop_user_ctx() handles leaving via uthread context. This handles leaving
1081 * This early check is an optimization. The real check is below when it
1082 * works with the online_vcs list (syncing with event.c and INDIR/IPI
1084 if (vcpd->notif_pending)
1086 /* Now we'll actually try to yield */
1087 printd("[K] Process %d (%p) is yielding on vcore %d\n", p->pid, p,
1088 get_vcoreid(p, pcoreid));
1089 /* Remove from the online list, add to the yielded list, and unmap
1090 * the vcore, which gives up the core. */
1091 TAILQ_REMOVE(&p->online_vcs, vc, list);
1092 /* Now that we're off the online list, check to see if an alert made
1093 * it through (event.c sets this) */
1094 wrmb(); /* prev write must hit before reading notif_pending */
1095 /* Note we need interrupts disabled, since a __notify can come in
1096 * and set pending to FALSE */
1097 if (vcpd->notif_pending) {
1098 /* We lost, put it back on the list and abort the yield. If we ever
1099 * build an myield, we'll need a way to deal with this for all vcores */
1100 TAILQ_INSERT_TAIL(&p->online_vcs, vc, list); /* could go HEAD */
1103 /* We won the race with event sending, we can safely yield */
1104 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1105 /* Note this protects stuff userspace should look at, which doesn't
1106 * include the TAILQs. */
1107 __seq_start_write(&p->procinfo->coremap_seqctr);
1108 /* Next time the vcore starts, it starts fresh */
1109 vcpd->notif_disabled = FALSE;
1110 __unmap_vcore(p, vcoreid);
1111 p->procinfo->num_vcores--;
1112 p->procinfo->res_grant[RES_CORES] = p->procinfo->num_vcores;
1113 __seq_end_write(&p->procinfo->coremap_seqctr);
1114 /* No more vcores? Then we wait on an event */
1115 if (p->procinfo->num_vcores == 0) {
1116 /* consider a ksched op to tell it about us WAITING */
1117 __proc_set_state(p, PROC_WAITING);
1119 spin_unlock(&p->proc_lock);
1120 /* Hand the now-idle core to the ksched */
1121 __sched_put_idle_core(p, pcoreid);
1122 goto out_yield_core;
1124 /* for some reason we just want to return, either to take a KMSG that cleans
1125 * us up, or because we shouldn't yield (ex: notif_pending). */
1126 spin_unlock(&p->proc_lock);
1128 out_yield_core: /* successfully yielded the core */
1129 proc_decref(p); /* need to eat the ref passed in */
1130 /* Clean up the core and idle. */
1131 clear_owning_proc(pcoreid); /* so we don't restart */
1136 /* Sends a notification (aka active notification, aka IPI) to p's vcore. We
1137 * only send a notification if one they are enabled. There's a bunch of weird
1138 * cases with this, and how pending / enabled are signals between the user and
1139 * kernel - check the documentation. Note that pending is more about messages.
1140 * The process needs to be in vcore_context, and the reason is usually a
1141 * message. We set pending here in case we were called to prod them into vcore
1142 * context (like via a sys_self_notify). Also note that this works for _S
1143 * procs, if you send to vcore 0 (and the proc is running). */
1144 void proc_notify(struct proc *p, uint32_t vcoreid)
1146 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1147 vcpd->notif_pending = TRUE;
1148 wrmb(); /* must write notif_pending before reading notif_disabled */
1149 if (!vcpd->notif_disabled) {
1150 /* GIANT WARNING: we aren't using the proc-lock to protect the
1151 * vcoremap. We want to be able to use this from interrupt context,
1152 * and don't want the proc_lock to be an irqsave. Spurious
1153 * __notify() kmsgs are okay (it checks to see if the right receiver
1155 if (vcore_is_mapped(p, vcoreid)) {
1156 printd("[kernel] sending notif to vcore %d\n", vcoreid);
1157 /* This use of try_get_pcoreid is racy, might be unmapped */
1158 send_kernel_message(try_get_pcoreid(p, vcoreid), __notify, (long)p,
1159 0, 0, KMSG_ROUTINE);
1164 /* Makes sure p is runnable. Callers may spam this, so it needs to handle
1165 * repeated calls for the same event. Callers include event delivery, SCP
1166 * yield, and new SCPs. Will trigger __sched_.cp_wakeup() CBs. Will only
1167 * trigger the CB once, regardless of how many times we are called, *until* the
1168 * proc becomes WAITING again, presumably because of something the ksched did.*/
1169 void proc_wakeup(struct proc *p)
1171 spin_lock(&p->proc_lock);
1172 if (__proc_is_mcp(p)) {
1173 /* we only wake up WAITING mcps */
1174 if (p->state != PROC_WAITING) {
1175 spin_unlock(&p->proc_lock);
1178 __proc_set_state(p, PROC_RUNNABLE_M);
1179 spin_unlock(&p->proc_lock);
1180 __sched_mcp_wakeup(p);
1183 /* SCPs can wake up for a variety of reasons. the only times we need
1184 * to do something is if it was waiting or just created. other cases
1185 * are either benign (just go out), or potential bugs (_Ms) */
1187 case (PROC_CREATED):
1188 case (PROC_WAITING):
1189 __proc_set_state(p, PROC_RUNNABLE_S);
1191 case (PROC_RUNNABLE_S):
1192 case (PROC_RUNNING_S):
1194 spin_unlock(&p->proc_lock);
1196 case (PROC_RUNNABLE_M):
1197 case (PROC_RUNNING_M):
1198 warn("Weird state(%s) in %s()", procstate2str(p->state),
1200 spin_unlock(&p->proc_lock);
1203 printd("[kernel] FYI, waking up an _S proc\n"); /* thanks, past brho! */
1204 spin_unlock(&p->proc_lock);
1205 __sched_scp_wakeup(p);
1209 /* Is the process in multi_mode / is an MCP or not? */
1210 bool __proc_is_mcp(struct proc *p)
1212 /* in lieu of using the amount of cores requested, or having a bunch of
1213 * states (like PROC_WAITING_M and _S), I'll just track it with a bool. */
1214 return p->procinfo->is_mcp;
1217 /************************ Preemption Functions ******************************
1218 * Don't rely on these much - I'll be sure to change them up a bit.
1220 * Careful about what takes a vcoreid and what takes a pcoreid. Also, there may
1221 * be weird glitches with setting the state to RUNNABLE_M. It is somewhat in
1222 * flux. The num_vcores is changed after take_cores, but some of the messages
1223 * (or local traps) may not yet be ready to handle seeing their future state.
1224 * But they should be, so fix those when they pop up.
1226 * Another thing to do would be to make the _core functions take a pcorelist,
1227 * and not just one pcoreid. */
1229 /* Sets a preempt_pending warning for p's vcore, to go off 'when'. If you care
1230 * about locking, do it before calling. Takes a vcoreid! */
1231 void __proc_preempt_warn(struct proc *p, uint32_t vcoreid, uint64_t when)
1233 struct event_msg local_msg = {0};
1234 /* danger with doing this unlocked: preempt_pending is set, but never 0'd,
1235 * since it is unmapped and not dealt with (TODO)*/
1236 p->procinfo->vcoremap[vcoreid].preempt_pending = when;
1238 /* Send the event (which internally checks to see how they want it) */
1239 local_msg.ev_type = EV_PREEMPT_PENDING;
1240 local_msg.ev_arg1 = vcoreid;
1241 /* Whenever we send msgs with the proc locked, we need at least 1 online.
1242 * Caller needs to make sure the core was online/mapped. */
1243 assert(!TAILQ_EMPTY(&p->online_vcs));
1244 send_kernel_event(p, &local_msg, vcoreid);
1246 /* TODO: consider putting in some lookup place for the alarm to find it.
1247 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1250 /* Warns all active vcores of an impending preemption. Hold the lock if you
1251 * care about the mapping (and you should). */
1252 void __proc_preempt_warnall(struct proc *p, uint64_t when)
1255 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1256 __proc_preempt_warn(p, vcore2vcoreid(p, vc_i), when);
1257 /* TODO: consider putting in some lookup place for the alarm to find it.
1258 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1261 // TODO: function to set an alarm, if none is outstanding
1263 /* Raw function to preempt a single core. If you care about locking, do it
1264 * before calling. */
1265 void __proc_preempt_core(struct proc *p, uint32_t pcoreid)
1267 uint32_t vcoreid = get_vcoreid(p, pcoreid);
1268 struct event_msg preempt_msg = {0};
1269 /* works with nr_preempts_done to signal completion of a preemption */
1270 p->procinfo->vcoremap[vcoreid].nr_preempts_sent++;
1271 // expects a pcorelist. assumes pcore is mapped and running_m
1272 __proc_take_corelist(p, &pcoreid, 1, TRUE);
1273 /* Only send the message if we have an online core. o/w, it would fuck
1274 * us up (deadlock), and hey don't need a message. the core we just took
1275 * will be the first one to be restarted. It will look like a notif. in
1276 * the future, we could send the event if we want, but the caller needs to
1277 * do that (after unlocking). */
1278 if (!TAILQ_EMPTY(&p->online_vcs)) {
1279 preempt_msg.ev_type = EV_VCORE_PREEMPT;
1280 preempt_msg.ev_arg2 = vcoreid;
1281 send_kernel_event(p, &preempt_msg, 0);
1285 /* Raw function to preempt every vcore. If you care about locking, do it before
1287 uint32_t __proc_preempt_all(struct proc *p, uint32_t *pc_arr)
1290 /* TODO:(BULK) PREEMPT - don't bother with this, set a proc wide flag, or
1291 * just make us RUNNABLE_M. Note this is also used by __map_vcore. */
1292 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1293 vc_i->nr_preempts_sent++;
1294 return __proc_take_allcores(p, pc_arr, TRUE);
1297 /* Warns and preempts a vcore from p. No delaying / alarming, or anything. The
1298 * warning will be for u usec from now. Returns TRUE if the core belonged to
1299 * the proc (and thus preempted), False if the proc no longer has the core. */
1300 bool proc_preempt_core(struct proc *p, uint32_t pcoreid, uint64_t usec)
1302 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1303 bool retval = FALSE;
1304 if (p->state != PROC_RUNNING_M) {
1305 /* more of an FYI for brho. should be harmless to just return. */
1306 warn("Tried to preempt from a non RUNNING_M proc!");
1309 spin_lock(&p->proc_lock);
1310 if (is_mapped_vcore(p, pcoreid)) {
1311 __proc_preempt_warn(p, get_vcoreid(p, pcoreid), warn_time);
1312 __proc_preempt_core(p, pcoreid);
1313 /* we might have taken the last core */
1314 if (!p->procinfo->num_vcores)
1315 __proc_set_state(p, PROC_RUNNABLE_M);
1318 spin_unlock(&p->proc_lock);
1322 /* Warns and preempts all from p. No delaying / alarming, or anything. The
1323 * warning will be for u usec from now. */
1324 void proc_preempt_all(struct proc *p, uint64_t usec)
1326 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1327 uint32_t num_revoked = 0;
1328 spin_lock(&p->proc_lock);
1329 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
1330 uint32_t pc_arr[p->procinfo->num_vcores];
1331 /* DYING could be okay */
1332 if (p->state != PROC_RUNNING_M) {
1333 warn("Tried to preempt from a non RUNNING_M proc!");
1334 spin_unlock(&p->proc_lock);
1337 __proc_preempt_warnall(p, warn_time);
1338 num_revoked = __proc_preempt_all(p, pc_arr);
1339 assert(!p->procinfo->num_vcores);
1340 __proc_set_state(p, PROC_RUNNABLE_M);
1341 spin_unlock(&p->proc_lock);
1342 /* TODO: when we revise this func, look at __put_idle */
1343 /* Return the cores to the ksched */
1345 __sched_put_idle_cores(p, pc_arr, num_revoked);
1348 /* Give the specific pcore to proc p. Lots of assumptions, so don't really use
1349 * this. The proc needs to be _M and prepared for it. the pcore needs to be
1351 void proc_give(struct proc *p, uint32_t pcoreid)
1353 warn("Your idlecoremap is now screwed up"); /* TODO (IDLE) */
1354 spin_lock(&p->proc_lock);
1355 // expects a pcorelist, we give it a list of one
1356 __proc_give_cores(p, &pcoreid, 1);
1357 spin_unlock(&p->proc_lock);
1360 /* Global version of the helper, for sys_get_vcoreid (might phase that syscall
1362 uint32_t proc_get_vcoreid(struct proc *p)
1364 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1365 if (pcpui->owning_proc == p) {
1366 return pcpui->owning_vcoreid;
1368 warn("Asked for vcoreid for %p, but %p is pwns", p, pcpui->owning_proc);
1369 return (uint32_t)-1;
1373 /* TODO: make all of these static inlines when we gut the env crap */
1374 bool vcore_is_mapped(struct proc *p, uint32_t vcoreid)
1376 return p->procinfo->vcoremap[vcoreid].valid;
1379 /* Can do this, or just create a new field and save it in the vcoremap */
1380 uint32_t vcore2vcoreid(struct proc *p, struct vcore *vc)
1382 return (vc - p->procinfo->vcoremap);
1385 struct vcore *vcoreid2vcore(struct proc *p, uint32_t vcoreid)
1387 return &p->procinfo->vcoremap[vcoreid];
1390 /********** Core granting (bulk and single) ***********/
1392 /* Helper: gives pcore to the process, mapping it to the next available vcore
1393 * from list vc_list. Returns TRUE if we succeeded (non-empty). If you pass in
1394 * **vc, we'll tell you which vcore it was. */
1395 static bool __proc_give_a_pcore(struct proc *p, uint32_t pcore,
1396 struct vcore_tailq *vc_list, struct vcore **vc)
1398 struct vcore *new_vc;
1399 new_vc = TAILQ_FIRST(vc_list);
1402 printd("setting vcore %d to pcore %d\n", vcore2vcoreid(p, new_vc),
1404 TAILQ_REMOVE(vc_list, new_vc, list);
1405 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1406 __map_vcore(p, vcore2vcoreid(p, new_vc), pcore);
1412 static void __proc_give_cores_runnable(struct proc *p, uint32_t *pc_arr,
1415 assert(p->state == PROC_RUNNABLE_M);
1416 assert(num); /* catch bugs */
1417 /* add new items to the vcoremap */
1418 __seq_start_write(&p->procinfo->coremap_seqctr);/* unncessary if offline */
1419 p->procinfo->num_vcores += num;
1420 for (int i = 0; i < num; i++) {
1421 /* Try from the bulk list first */
1422 if (__proc_give_a_pcore(p, pc_arr[i], &p->bulk_preempted_vcs, 0))
1424 /* o/w, try from the inactive list. at one point, i thought there might
1425 * be a legit way in which the inactive list could be empty, but that i
1426 * wanted to catch it via an assert. */
1427 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, 0));
1429 __seq_end_write(&p->procinfo->coremap_seqctr);
1432 static void __proc_give_cores_running(struct proc *p, uint32_t *pc_arr,
1436 /* Up the refcnt, since num cores are going to start using this
1437 * process and have it loaded in their owning_proc and 'current'. */
1438 proc_incref(p, num * 2); /* keep in sync with __startcore */
1439 __seq_start_write(&p->procinfo->coremap_seqctr);
1440 p->procinfo->num_vcores += num;
1441 assert(TAILQ_EMPTY(&p->bulk_preempted_vcs));
1442 for (int i = 0; i < num; i++) {
1443 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, &vc_i));
1444 send_kernel_message(pc_arr[i], __startcore, (long)p,
1445 (long)vcore2vcoreid(p, vc_i),
1446 (long)vc_i->nr_preempts_sent, KMSG_ROUTINE);
1448 __seq_end_write(&p->procinfo->coremap_seqctr);
1451 /* Gives process p the additional num cores listed in pcorelist. If the proc is
1452 * not RUNNABLE_M or RUNNING_M, this will fail and allocate none of the core
1453 * (and return -1). If you're RUNNING_M, this will startup your new cores at
1454 * the entry point with their virtual IDs (or restore a preemption). If you're
1455 * RUNNABLE_M, you should call __proc_run_m after this so that the process can
1456 * start to use its cores. In either case, this returns 0.
1458 * If you're *_S, make sure your core0's TF is set (which is done when coming in
1459 * via arch/trap.c and we are RUNNING_S), change your state, then call this.
1460 * Then call __proc_run_m().
1462 * The reason I didn't bring the _S cases from core_request over here is so we
1463 * can keep this family of calls dealing with only *_Ms, to avoiding caring if
1464 * this is called from another core, and to avoid the _S -> _M transition.
1466 * WARNING: You must hold the proc_lock before calling this! */
1467 int __proc_give_cores(struct proc *p, uint32_t *pc_arr, uint32_t num)
1469 /* should never happen: */
1470 assert(num + p->procinfo->num_vcores <= MAX_NUM_CPUS);
1472 case (PROC_RUNNABLE_S):
1473 case (PROC_RUNNING_S):
1474 warn("Don't give cores to a process in a *_S state!\n");
1477 case (PROC_WAITING):
1478 /* can't accept, just fail */
1480 case (PROC_RUNNABLE_M):
1481 __proc_give_cores_runnable(p, pc_arr, num);
1483 case (PROC_RUNNING_M):
1484 __proc_give_cores_running(p, pc_arr, num);
1487 panic("Weird state(%s) in %s()", procstate2str(p->state),
1490 /* TODO: considering moving to the ksched (hard, due to yield) */
1491 p->procinfo->res_grant[RES_CORES] += num;
1495 /********** Core revocation (bulk and single) ***********/
1497 /* Revokes a single vcore from a process (unmaps or sends a KMSG to unmap). */
1498 static void __proc_revoke_core(struct proc *p, uint32_t vcoreid, bool preempt)
1500 uint32_t pcoreid = get_pcoreid(p, vcoreid);
1501 struct preempt_data *vcpd;
1503 /* Lock the vcore's state (necessary for preemption recovery) */
1504 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1505 atomic_or(&vcpd->flags, VC_K_LOCK);
1506 send_kernel_message(pcoreid, __preempt, (long)p, 0, 0, KMSG_ROUTINE);
1508 send_kernel_message(pcoreid, __death, 0, 0, 0, KMSG_ROUTINE);
1512 /* Revokes all cores from the process (unmaps or sends a KMSGS). */
1513 static void __proc_revoke_allcores(struct proc *p, bool preempt)
1516 /* TODO: if we ever get broadcast messaging, use it here (still need to lock
1517 * the vcores' states for preemption) */
1518 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1519 __proc_revoke_core(p, vcore2vcoreid(p, vc_i), preempt);
1522 /* Might be faster to scan the vcoremap than to walk the list... */
1523 static void __proc_unmap_allcores(struct proc *p)
1526 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1527 __unmap_vcore(p, vcore2vcoreid(p, vc_i));
1530 /* Takes (revoke via kmsg or unmap) from process p the num cores listed in
1531 * pc_arr. Will preempt if 'preempt' is set. o/w, no state will be saved, etc.
1532 * Don't use this for taking all of a process's cores.
1534 * Make sure you hold the lock when you call this, and make sure that the pcore
1535 * actually belongs to the proc, non-trivial due to other __preempt messages. */
1536 void __proc_take_corelist(struct proc *p, uint32_t *pc_arr, uint32_t num,
1541 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1542 __seq_start_write(&p->procinfo->coremap_seqctr);
1543 for (int i = 0; i < num; i++) {
1544 vcoreid = get_vcoreid(p, pc_arr[i]);
1546 assert(pc_arr[i] == get_pcoreid(p, vcoreid));
1547 /* Revoke / unmap core */
1548 if (p->state == PROC_RUNNING_M)
1549 __proc_revoke_core(p, vcoreid, preempt);
1550 __unmap_vcore(p, vcoreid);
1551 /* Change lists for the vcore. Note, the vcore is already unmapped
1552 * and/or the messages are already in flight. The only code that looks
1553 * at the lists without holding the lock is event code. */
1554 vc = vcoreid2vcore(p, vcoreid);
1555 TAILQ_REMOVE(&p->online_vcs, vc, list);
1556 /* even for single preempts, we use the inactive list. bulk preempt is
1557 * only used for when we take everything. */
1558 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1560 p->procinfo->num_vcores -= num;
1561 __seq_end_write(&p->procinfo->coremap_seqctr);
1562 p->procinfo->res_grant[RES_CORES] -= num;
1565 /* Takes all cores from a process (revoke via kmsg or unmap), putting them on
1566 * the appropriate vcore list, and fills pc_arr with the pcores revoked, and
1567 * returns the number of entries in pc_arr.
1569 * Make sure pc_arr is big enough to handle num_vcores().
1570 * Make sure you hold the lock when you call this. */
1571 uint32_t __proc_take_allcores(struct proc *p, uint32_t *pc_arr, bool preempt)
1573 struct vcore *vc_i, *vc_temp;
1575 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1576 __seq_start_write(&p->procinfo->coremap_seqctr);
1577 /* Write out which pcores we're going to take */
1578 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1579 pc_arr[num++] = vc_i->pcoreid;
1580 /* Revoke if they are running, and unmap. Both of these need the online
1581 * list to not be changed yet. */
1582 if (p->state == PROC_RUNNING_M)
1583 __proc_revoke_allcores(p, preempt);
1584 __proc_unmap_allcores(p);
1585 /* Move the vcores from online to the head of the appropriate list */
1586 TAILQ_FOREACH_SAFE(vc_i, &p->online_vcs, list, vc_temp) {
1587 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that */
1588 TAILQ_REMOVE(&p->online_vcs, vc_i, list);
1589 /* Put the cores on the appropriate list */
1591 TAILQ_INSERT_HEAD(&p->bulk_preempted_vcs, vc_i, list);
1593 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
1595 assert(TAILQ_EMPTY(&p->online_vcs));
1596 assert(num == p->procinfo->num_vcores);
1597 p->procinfo->num_vcores = 0;
1598 __seq_end_write(&p->procinfo->coremap_seqctr);
1599 p->procinfo->res_grant[RES_CORES] = 0;
1603 /* Helper to do the vcore->pcore and inverse mapping. Hold the lock when
1605 void __map_vcore(struct proc *p, uint32_t vcoreid, uint32_t pcoreid)
1607 p->procinfo->vcoremap[vcoreid].pcoreid = pcoreid;
1608 p->procinfo->vcoremap[vcoreid].valid = TRUE;
1609 p->procinfo->pcoremap[pcoreid].vcoreid = vcoreid;
1610 p->procinfo->pcoremap[pcoreid].valid = TRUE;
1613 /* Helper to unmap the vcore->pcore and inverse mapping. Hold the lock when
1615 void __unmap_vcore(struct proc *p, uint32_t vcoreid)
1617 p->procinfo->pcoremap[p->procinfo->vcoremap[vcoreid].pcoreid].valid = FALSE;
1618 p->procinfo->vcoremap[vcoreid].valid = FALSE;
1621 /* Stop running whatever context is on this core and load a known-good cr3.
1622 * Note this leaves no trace of what was running. This "leaves the process's
1625 * This does not clear the owning proc. Use the other helper for that. */
1626 void abandon_core(void)
1628 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1629 /* Syscalls that don't return will ultimately call abadon_core(), so we need
1630 * to make sure we don't think we are still working on a syscall. */
1631 pcpui->cur_sysc = 0;
1632 if (pcpui->cur_proc)
1636 /* Helper to clear the core's owning processor and manage refcnting. Pass in
1637 * core_id() to save a couple core_id() calls. */
1638 void clear_owning_proc(uint32_t coreid)
1640 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1641 struct proc *p = pcpui->owning_proc;
1642 pcpui->owning_proc = 0;
1643 pcpui->owning_vcoreid = 0xdeadbeef;
1644 pcpui->cur_ctx = 0; /* catch bugs for now (may go away) */
1649 /* Switches to the address space/context of new_p, doing nothing if we are
1650 * already in new_p. This won't add extra refcnts or anything, and needs to be
1651 * paired with switch_back() at the end of whatever function you are in. Don't
1652 * migrate cores in the middle of a pair. Specifically, the uncounted refs are
1653 * one for the old_proc, which is passed back to the caller, and new_p is
1654 * getting placed in cur_proc. */
1655 struct proc *switch_to(struct proc *new_p)
1657 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1658 struct proc *old_proc;
1659 old_proc = pcpui->cur_proc; /* uncounted ref */
1660 /* If we aren't the proc already, then switch to it */
1661 if (old_proc != new_p) {
1662 pcpui->cur_proc = new_p; /* uncounted ref */
1663 lcr3(new_p->env_cr3);
1668 /* This switches back to old_proc from new_p. Pair it with switch_to(), and
1669 * pass in its return value for old_proc. */
1670 void switch_back(struct proc *new_p, struct proc *old_proc)
1672 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1673 if (old_proc != new_p) {
1674 pcpui->cur_proc = old_proc;
1676 lcr3(old_proc->env_cr3);
1682 /* Will send a TLB shootdown message to every vcore in the main address space
1683 * (aka, all vcores for now). The message will take the start and end virtual
1684 * addresses as well, in case we want to be more clever about how much we
1685 * shootdown and batching our messages. Should do the sanity about rounding up
1686 * and down in this function too.
1688 * Would be nice to have a broadcast kmsg at this point. Note this may send a
1689 * message to the calling core (interrupting it, possibly while holding the
1690 * proc_lock). We don't need to process routine messages since it's an
1691 * immediate message. */
1692 void proc_tlbshootdown(struct proc *p, uintptr_t start, uintptr_t end)
1695 /* TODO: we might be able to avoid locking here in the future (we must hit
1696 * all online, and we can check __mapped). it'll be complicated. */
1697 spin_lock(&p->proc_lock);
1699 case (PROC_RUNNING_S):
1702 case (PROC_RUNNING_M):
1703 /* TODO: (TLB) sanity checks and rounding on the ranges */
1704 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
1705 send_kernel_message(vc_i->pcoreid, __tlbshootdown, start, end,
1710 /* if it is dying, death messages are already on the way to all
1711 * cores, including ours, which will clear the TLB. */
1714 /* will probably get this when we have the short handlers */
1715 warn("Unexpected case %s in %s", procstate2str(p->state),
1718 spin_unlock(&p->proc_lock);
1721 /* Helper, used by __startcore and __set_curctx, which sets up cur_ctx to run a
1722 * given process's vcore. Caller needs to set up things like owning_proc and
1723 * whatnot. Note that we might not have p loaded as current. */
1724 static void __set_curctx_to_vcoreid(struct proc *p, uint32_t vcoreid,
1725 uint32_t old_nr_preempts_sent)
1727 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1728 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1729 struct vcore *vc = vcoreid2vcore(p, vcoreid);
1730 /* Spin until our vcore's old preemption is done. When __SC was sent, we
1731 * were told what the nr_preempts_sent was at that time. Once that many are
1732 * done, it is time for us to run. This forces a 'happens-before' ordering
1733 * on a __PR of our VC before this __SC of the VC. Note the nr_done should
1734 * not exceed old_nr_sent, since further __PR are behind this __SC in the
1736 while (old_nr_preempts_sent != vc->nr_preempts_done)
1738 cmb(); /* read nr_done before any other rd or wr. CPU mb in the atomic. */
1739 /* Mark that this vcore as no longer preempted. No danger of clobbering
1740 * other writes, since this would get turned on in __preempt (which can't be
1741 * concurrent with this function on this core), and the atomic is just
1742 * toggling the one bit (a concurrent VC_K_LOCK will work) */
1743 atomic_and(&vcpd->flags, ~VC_PREEMPTED);
1744 /* Once the VC is no longer preempted, we allow it to receive msgs. We
1745 * could let userspace do it, but handling it here makes it easier for them
1746 * to handle_indirs (when they turn this flag off). Note the atomics
1747 * provide the needed barriers (cmb and mb on flags). */
1748 atomic_or(&vcpd->flags, VC_CAN_RCV_MSG);
1749 printd("[kernel] startcore on physical core %d for process %d's vcore %d\n",
1750 core_id(), p->pid, vcoreid);
1751 /* If notifs are disabled, the vcore was in vcore context and we need to
1752 * restart the vcore_ctx. o/w, we give them a fresh vcore (which is also
1753 * what happens the first time a vcore comes online). No matter what,
1754 * they'll restart in vcore context. It's just a matter of whether or not
1755 * it is the old, interrupted vcore context. */
1756 if (vcpd->notif_disabled) {
1757 /* copy-in the tf we'll pop, then set all security-related fields */
1758 pcpui->actual_ctx = vcpd->vcore_ctx;
1759 proc_secure_ctx(&pcpui->actual_ctx);
1760 } else { /* not restarting from a preemption, use a fresh vcore */
1761 assert(vcpd->transition_stack);
1762 proc_init_ctx(&pcpui->actual_ctx, vcoreid, p->env_entry,
1763 vcpd->transition_stack);
1764 /* Disable/mask active notifications for fresh vcores */
1765 vcpd->notif_disabled = TRUE;
1767 /* Regardless of whether or not we have a 'fresh' VC, we need to restore the
1768 * FPU state for the VC according to VCPD (which means either a saved FPU
1769 * state or a brand new init). Starting a fresh VC is just referring to the
1770 * GP context we run. The vcore itself needs to have the FPU state loaded
1771 * from when it previously ran and was saved (or a fresh FPU if it wasn't
1772 * saved). For fresh FPUs, the main purpose is for limiting info leakage.
1773 * I think VCs that don't need FPU state for some reason (like having a
1774 * current_uthread) can handle any sort of FPU state, since it gets sorted
1775 * when they pop their next uthread.
1777 * Note this can cause a GP fault on x86 if the state is corrupt. In lieu
1778 * of reading in the huge FP state and mucking with mxcsr_mask, we should
1779 * handle this like a KPF on user code. */
1780 restore_vc_fp_state(vcpd);
1781 /* cur_ctx was built above (in actual_ctx), now use it */
1782 pcpui->cur_ctx = &pcpui->actual_ctx;
1783 /* this cur_ctx will get run when the kernel returns / idles */
1786 /* Changes calling vcore to be vcoreid. enable_my_notif tells us about how the
1787 * state calling vcore wants to be left in. It will look like caller_vcoreid
1788 * was preempted. Note we don't care about notif_pending.
1791 * 0 if we successfully changed to the target vcore.
1792 * -EBUSY if the target vcore is already mapped (a good kind of failure)
1793 * -EAGAIN if we failed for some other reason and need to try again. For
1794 * example, the caller could be preempted, and we never even attempted to
1796 * -EINVAL some userspace bug */
1797 int proc_change_to_vcore(struct proc *p, uint32_t new_vcoreid,
1798 bool enable_my_notif)
1800 uint32_t caller_vcoreid, pcoreid = core_id();
1801 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1802 struct preempt_data *caller_vcpd;
1803 struct vcore *caller_vc, *new_vc;
1804 struct event_msg preempt_msg = {0};
1805 int retval = -EAGAIN; /* by default, try again */
1806 /* Need to not reach outside the vcoremap, which might be smaller in the
1807 * future, but should always be as big as max_vcores */
1808 if (new_vcoreid >= p->procinfo->max_vcores)
1810 /* Need to lock to prevent concurrent vcore changes, like in yield. */
1811 spin_lock(&p->proc_lock);
1812 /* new_vcoreid is already runing, abort */
1813 if (vcore_is_mapped(p, new_vcoreid)) {
1817 /* Need to make sure our vcore is allowed to switch. We might have a
1818 * __preempt, __death, etc, coming in. Similar to yield. */
1820 case (PROC_RUNNING_M):
1821 break; /* the only case we can proceed */
1822 case (PROC_RUNNING_S): /* user bug, just return */
1823 case (PROC_DYING): /* incoming __death */
1824 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1827 panic("Weird state(%s) in %s()", procstate2str(p->state),
1830 /* This is which vcore this pcore thinks it is, regardless of any unmappings
1831 * that may have happened remotely (with __PRs waiting to run) */
1832 caller_vcoreid = pcpui->owning_vcoreid;
1833 caller_vc = vcoreid2vcore(p, caller_vcoreid);
1834 caller_vcpd = &p->procdata->vcore_preempt_data[caller_vcoreid];
1835 /* This is how we detect whether or not a __PR happened. If it did, just
1836 * abort and handle the kmsg. No new __PRs are coming since we hold the
1837 * lock. This also detects a __PR followed by a __SC for the same VC. */
1838 if (caller_vc->nr_preempts_sent != caller_vc->nr_preempts_done)
1840 /* Sanity checks. If we were preempted or are dying, we should have noticed
1842 assert(is_mapped_vcore(p, pcoreid));
1843 assert(caller_vcoreid == get_vcoreid(p, pcoreid));
1844 /* Should only call from vcore context */
1845 if (!caller_vcpd->notif_disabled) {
1847 printk("[kernel] You tried to change vcores from uthread ctx\n");
1850 /* Ok, we're clear to do the switch. Lets figure out who the new one is */
1851 new_vc = vcoreid2vcore(p, new_vcoreid);
1852 printd("[kernel] changing vcore %d to vcore %d\n", caller_vcoreid,
1854 /* enable_my_notif signals how we'll be restarted */
1855 if (enable_my_notif) {
1856 /* if they set this flag, then the vcore can just restart from scratch,
1857 * and we don't care about either the uthread_ctx or the vcore_ctx. */
1858 caller_vcpd->notif_disabled = FALSE;
1859 /* Don't need to save the FPU. There should be no uthread or other
1860 * reason to return to the FPU state. */
1862 /* need to set up the calling vcore's ctx so that it'll get restarted by
1863 * __startcore, to make the caller look like it was preempted. */
1864 caller_vcpd->vcore_ctx = *current_ctx;
1865 save_vc_fp_state(caller_vcpd);
1866 /* Mark our core as preempted (for userspace recovery). */
1867 atomic_or(&caller_vcpd->flags, VC_PREEMPTED);
1869 /* Either way, unmap and offline our current vcore */
1870 /* Move the caller from online to inactive */
1871 TAILQ_REMOVE(&p->online_vcs, caller_vc, list);
1872 /* We don't bother with the notif_pending race. note that notif_pending
1873 * could still be set. this was a preempted vcore, and userspace will need
1874 * to deal with missed messages (preempt_recover() will handle that) */
1875 TAILQ_INSERT_HEAD(&p->inactive_vcs, caller_vc, list);
1876 /* Move the new one from inactive to online */
1877 TAILQ_REMOVE(&p->inactive_vcs, new_vc, list);
1878 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1879 /* Change the vcore map */
1880 __seq_start_write(&p->procinfo->coremap_seqctr);
1881 __unmap_vcore(p, caller_vcoreid);
1882 __map_vcore(p, new_vcoreid, pcoreid);
1883 __seq_end_write(&p->procinfo->coremap_seqctr);
1884 /* Send either a PREEMPT msg or a CHECK_MSGS msg. If they said to
1885 * enable_my_notif, then all userspace needs is to check messages, not a
1886 * full preemption recovery. */
1887 preempt_msg.ev_type = (enable_my_notif ? EV_CHECK_MSGS : EV_VCORE_PREEMPT);
1888 preempt_msg.ev_arg2 = caller_vcoreid; /* arg2 is 32 bits */
1889 /* Whenever we send msgs with the proc locked, we need at least 1 online.
1890 * In this case, it's the one we just changed to. */
1891 assert(!TAILQ_EMPTY(&p->online_vcs));
1892 send_kernel_event(p, &preempt_msg, new_vcoreid);
1893 /* So this core knows which vcore is here. (cur_proc and owning_proc are
1894 * already correct): */
1895 pcpui->owning_vcoreid = new_vcoreid;
1896 /* Until we set_curctx, we don't really have a valid current tf. The stuff
1897 * in that old one is from our previous vcore, not the current
1898 * owning_vcoreid. This matters for other KMSGS that will run before
1899 * __set_curctx (like __notify). */
1901 /* Need to send a kmsg to finish. We can't set_curctx til the __PR is done,
1902 * but we can't spin right here while holding the lock (can't spin while
1903 * waiting on a message, roughly) */
1904 send_kernel_message(pcoreid, __set_curctx, (long)p, (long)new_vcoreid,
1905 (long)new_vc->nr_preempts_sent, KMSG_ROUTINE);
1907 /* Fall through to exit */
1909 spin_unlock(&p->proc_lock);
1913 /* Kernel message handler to start a process's context on this core, when the
1914 * core next considers running a process. Tightly coupled with __proc_run_m().
1915 * Interrupts are disabled. */
1916 void __startcore(uint32_t srcid, long a0, long a1, long a2)
1918 uint32_t vcoreid = (uint32_t)a1;
1919 uint32_t coreid = core_id();
1920 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1921 struct proc *p_to_run = (struct proc *CT(1))a0;
1922 uint32_t old_nr_preempts_sent = (uint32_t)a2;
1925 /* Can not be any TF from a process here already */
1926 assert(!pcpui->owning_proc);
1927 /* the sender of the kmsg increfed already for this saved ref to p_to_run */
1928 pcpui->owning_proc = p_to_run;
1929 pcpui->owning_vcoreid = vcoreid;
1930 /* sender increfed again, assuming we'd install to cur_proc. only do this
1931 * if no one else is there. this is an optimization, since we expect to
1932 * send these __startcores to idles cores, and this saves a scramble to
1933 * incref when all of the cores restartcore/startcore later. Keep in sync
1934 * with __proc_give_cores() and __proc_run_m(). */
1935 if (!pcpui->cur_proc) {
1936 pcpui->cur_proc = p_to_run; /* install the ref to cur_proc */
1937 lcr3(p_to_run->env_cr3); /* load the page tables to match cur_proc */
1939 proc_decref(p_to_run); /* can't install, decref the extra one */
1941 /* Note we are not necessarily in the cr3 of p_to_run */
1942 /* Now that we sorted refcnts and know p / which vcore it should be, set up
1943 * pcpui->cur_ctx so that it will run that particular vcore */
1944 __set_curctx_to_vcoreid(p_to_run, vcoreid, old_nr_preempts_sent);
1947 /* Kernel message handler to load a proc's vcore context on this core. Similar
1948 * to __startcore, except it is used when p already controls the core (e.g.
1949 * change_to). Since the core is already controlled, pcpui such as owning proc,
1950 * vcoreid, and cur_proc are all already set. */
1951 void __set_curctx(uint32_t srcid, long a0, long a1, long a2)
1953 struct proc *p = (struct proc*)a0;
1954 uint32_t vcoreid = (uint32_t)a1;
1955 uint32_t old_nr_preempts_sent = (uint32_t)a2;
1956 __set_curctx_to_vcoreid(p, vcoreid, old_nr_preempts_sent);
1959 /* Bail out if it's the wrong process, or if they no longer want a notif. Try
1960 * not to grab locks or write access to anything that isn't per-core in here. */
1961 void __notify(uint32_t srcid, long a0, long a1, long a2)
1963 uint32_t vcoreid, coreid = core_id();
1964 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1965 struct preempt_data *vcpd;
1966 struct proc *p = (struct proc*)a0;
1968 /* Not the right proc */
1969 if (p != pcpui->owning_proc)
1971 /* the core might be owned, but not have a valid cur_ctx (if we're in the
1972 * process of changing */
1973 if (!pcpui->cur_ctx)
1975 /* Common cur_ctx sanity checks. Note cur_ctx could be an _S's scp_ctx */
1976 vcoreid = pcpui->owning_vcoreid;
1977 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1978 /* for SCPs that haven't (and might never) call vc_event_init, like rtld.
1979 * this is harmless for MCPS to check this */
1980 if (!scp_is_vcctx_ready(vcpd))
1982 printd("received active notification for proc %d's vcore %d on pcore %d\n",
1983 p->procinfo->pid, vcoreid, coreid);
1984 /* sort signals. notifs are now masked, like an interrupt gate */
1985 if (vcpd->notif_disabled)
1987 vcpd->notif_disabled = TRUE;
1988 /* save the old ctx in the uthread slot, build and pop a new one. Note that
1989 * silly state isn't our business for a notification. */
1990 vcpd->uthread_ctx = *pcpui->cur_ctx;
1991 memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
1992 proc_init_ctx(pcpui->cur_ctx, vcoreid, p->env_entry,
1993 vcpd->transition_stack);
1994 /* this cur_ctx will get run when the kernel returns / idles */
1997 void __preempt(uint32_t srcid, long a0, long a1, long a2)
1999 uint32_t vcoreid, coreid = core_id();
2000 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2001 struct preempt_data *vcpd;
2002 struct proc *p = (struct proc*)a0;
2005 if (p != pcpui->owning_proc) {
2006 panic("__preempt arrived for a process (%p) that was not owning (%p)!",
2007 p, pcpui->owning_proc);
2009 /* Common cur_ctx sanity checks */
2010 assert(pcpui->cur_ctx);
2011 assert(pcpui->cur_ctx == &pcpui->actual_ctx);
2012 vcoreid = pcpui->owning_vcoreid;
2013 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
2014 printd("[kernel] received __preempt for proc %d's vcore %d on pcore %d\n",
2015 p->procinfo->pid, vcoreid, coreid);
2016 /* if notifs are disabled, the vcore is in vcore context (as far as we're
2017 * concerned), and we save it in the vcore slot. o/w, we save the process's
2018 * cur_ctx in the uthread slot, and it'll appear to the vcore when it comes
2019 * back up the uthread just took a notification. */
2020 if (vcpd->notif_disabled)
2021 vcpd->vcore_ctx = *pcpui->cur_ctx;
2023 vcpd->uthread_ctx = *pcpui->cur_ctx;
2024 /* Userspace in a preemption handler on another core might be copying FP
2025 * state from memory (VCPD) at the moment, and if so we don't want to
2026 * clobber it. In this rare case, our current core's FPU state should be
2027 * the same as whatever is in VCPD, so this shouldn't be necessary, but the
2028 * arch-specific save function might do something other than write out
2029 * bit-for-bit the exact same data. Checking STEALING suffices, since we
2030 * hold the K_LOCK (preventing userspace from starting a fresh STEALING
2031 * phase concurrently). */
2032 if (!(atomic_read(&vcpd->flags) & VC_UTHREAD_STEALING))
2033 save_vc_fp_state(vcpd);
2034 /* Mark the vcore as preempted and unlock (was locked by the sender). */
2035 atomic_or(&vcpd->flags, VC_PREEMPTED);
2036 atomic_and(&vcpd->flags, ~VC_K_LOCK);
2037 /* either __preempt or proc_yield() ends the preempt phase. */
2038 p->procinfo->vcoremap[vcoreid].preempt_pending = 0;
2039 wmb(); /* make sure everything else hits before we finish the preempt */
2040 /* up the nr_done, which signals the next __startcore for this vc */
2041 p->procinfo->vcoremap[vcoreid].nr_preempts_done++;
2042 /* We won't restart the process later. current gets cleared later when we
2043 * notice there is no owning_proc and we have nothing to do (smp_idle,
2044 * restartcore, etc) */
2045 clear_owning_proc(coreid);
2048 /* Kernel message handler to clean up the core when a process is dying.
2049 * Note this leaves no trace of what was running.
2050 * It's okay if death comes to a core that's already idling and has no current.
2051 * It could happen if a process decref'd before __proc_startcore could incref. */
2052 void __death(uint32_t srcid, long a0, long a1, long a2)
2054 uint32_t vcoreid, coreid = core_id();
2055 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2056 struct proc *p = pcpui->owning_proc;
2058 vcoreid = pcpui->owning_vcoreid;
2059 printd("[kernel] death on physical core %d for process %d's vcore %d\n",
2060 coreid, p->pid, vcoreid);
2061 /* We won't restart the process later. current gets cleared later when
2062 * we notice there is no owning_proc and we have nothing to do
2063 * (smp_idle, restartcore, etc) */
2064 clear_owning_proc(coreid);
2068 /* Kernel message handler, usually sent IMMEDIATE, to shoot down virtual
2069 * addresses from a0 to a1. */
2070 void __tlbshootdown(uint32_t srcid, long a0, long a1, long a2)
2072 /* TODO: (TLB) something more intelligent with the range */
2076 void print_allpids(void)
2078 void print_proc_state(void *item)
2080 struct proc *p = (struct proc*)item;
2082 printk("%8d %-10s %6d\n", p->pid, procstate2str(p->state), p->ppid);
2084 printk(" PID STATE Parent \n");
2085 printk("------------------------------\n");
2086 spin_lock(&pid_hash_lock);
2087 hash_for_each(pid_hash, print_proc_state);
2088 spin_unlock(&pid_hash_lock);
2091 void print_proc_info(pid_t pid)
2094 struct proc *child, *p = pid2proc(pid);
2097 printk("Bad PID.\n");
2100 spinlock_debug(&p->proc_lock);
2101 //spin_lock(&p->proc_lock); // No locking!!
2102 printk("struct proc: %p\n", p);
2103 printk("PID: %d\n", p->pid);
2104 printk("PPID: %d\n", p->ppid);
2105 printk("State: %s (%p)\n", procstate2str(p->state), p->state);
2106 printk("Refcnt: %d\n", atomic_read(&p->p_kref.refcount) - 1);
2107 printk("Flags: 0x%08x\n", p->env_flags);
2108 printk("CR3(phys): 0x%08x\n", p->env_cr3);
2109 printk("Num Vcores: %d\n", p->procinfo->num_vcores);
2110 printk("Vcore Lists (may be in flux w/o locking):\n----------------------\n");
2111 printk("Online:\n");
2112 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
2113 printk("\tVcore %d -> Pcore %d\n", vcore2vcoreid(p, vc_i), vc_i->pcoreid);
2114 printk("Bulk Preempted:\n");
2115 TAILQ_FOREACH(vc_i, &p->bulk_preempted_vcs, list)
2116 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2117 printk("Inactive / Yielded:\n");
2118 TAILQ_FOREACH(vc_i, &p->inactive_vcs, list)
2119 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2120 printk("Resources:\n------------------------\n");
2121 for (int i = 0; i < MAX_NUM_RESOURCES; i++)
2122 printk("\tRes type: %02d, amt wanted: %08d, amt granted: %08d\n", i,
2123 p->procdata->res_req[i].amt_wanted, p->procinfo->res_grant[i]);
2124 printk("Open Files:\n");
2125 struct files_struct *files = &p->open_files;
2126 spin_lock(&files->lock);
2127 for (int i = 0; i < files->max_files; i++)
2128 if (files->fd_array[i].fd_file) {
2129 printk("\tFD: %02d, File: %08p, File name: %s\n", i,
2130 files->fd_array[i].fd_file,
2131 file_name(files->fd_array[i].fd_file));
2133 spin_unlock(&files->lock);
2134 printk("Children: (PID (struct proc *))\n");
2135 TAILQ_FOREACH(child, &p->children, sibling_link)
2136 printk("\t%d (%08p)\n", child->pid, child);
2137 /* no locking / unlocking or refcnting */
2138 // spin_unlock(&p->proc_lock);
2142 /* Debugging function, checks what (process, vcore) is supposed to run on this
2143 * pcore. Meant to be called from smp_idle() before halting. */
2144 void check_my_owner(void)
2146 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2147 void shazbot(void *item)
2149 struct proc *p = (struct proc*)item;
2152 spin_lock(&p->proc_lock);
2153 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
2154 /* this isn't true, a __startcore could be on the way and we're
2155 * already "online" */
2156 if (vc_i->pcoreid == core_id()) {
2157 /* Immediate message was sent, we should get it when we enable
2158 * interrupts, which should cause us to skip cpu_halt() */
2159 if (!STAILQ_EMPTY(&pcpui->immed_amsgs))
2161 printk("Owned pcore (%d) has no owner, by %08p, vc %d!\n",
2162 core_id(), p, vcore2vcoreid(p, vc_i));
2163 spin_unlock(&p->proc_lock);
2164 spin_unlock(&pid_hash_lock);
2168 spin_unlock(&p->proc_lock);
2170 assert(!irq_is_enabled());
2172 if (!booting && !pcpui->owning_proc) {
2173 spin_lock(&pid_hash_lock);
2174 hash_for_each(pid_hash, shazbot);
2175 spin_unlock(&pid_hash_lock);