1 /* Copyright (c) 2009, 2010 The Regents of the University of California
2 * Barret Rhoden <brho@cs.berkeley.edu>
3 * See LICENSE for details. */
10 #include <arch/arch.h>
22 #include <hashtable.h>
24 #include <sys/queue.h>
28 #include <arsc_server.h>
32 struct kmem_cache *proc_cache;
34 /* Other helpers, implemented later. */
35 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid);
36 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid);
37 static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid);
38 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid);
39 static void __proc_free(struct kref *kref);
40 static bool scp_is_vcctx_ready(struct preempt_data *vcpd);
41 static void save_vc_fp_state(struct preempt_data *vcpd);
42 static void restore_vc_fp_state(struct preempt_data *vcpd);
45 #define PID_MAX 32767 // goes from 0 to 32767, with 0 reserved
46 static DECL_BITMASK(pid_bmask, PID_MAX + 1);
47 spinlock_t pid_bmask_lock = SPINLOCK_INITIALIZER;
48 struct hashtable *pid_hash;
49 spinlock_t pid_hash_lock; // initialized in proc_init
51 /* Finds the next free entry (zero) entry in the pid_bitmask. Set means busy.
52 * PID 0 is reserved (in proc_init). A return value of 0 is a failure (and
53 * you'll also see a warning, for now). Consider doing this with atomics. */
54 static pid_t get_free_pid(void)
56 static pid_t next_free_pid = 1;
59 spin_lock(&pid_bmask_lock);
60 // atomically (can lock for now, then change to atomic_and_return
61 FOR_CIRC_BUFFER(next_free_pid, PID_MAX + 1, i) {
62 // always points to the next to test
63 next_free_pid = (next_free_pid + 1) % (PID_MAX + 1);
64 if (!GET_BITMASK_BIT(pid_bmask, i)) {
65 SET_BITMASK_BIT(pid_bmask, i);
70 spin_unlock(&pid_bmask_lock);
72 warn("Shazbot! Unable to find a PID! You need to deal with this!\n");
76 /* Return a pid to the pid bitmask */
77 static void put_free_pid(pid_t pid)
79 spin_lock(&pid_bmask_lock);
80 CLR_BITMASK_BIT(pid_bmask, pid);
81 spin_unlock(&pid_bmask_lock);
84 /* 'resume' is the time int ticks of the most recent onlining. 'total' is the
85 * amount of time in ticks consumed up to and including the current offlining.
87 * We could move these to the map and unmap of vcores, though not every place
88 * uses that (SCPs, in particular). However, maps/unmaps happen remotely;
89 * something to consider. If we do it remotely, we can batch them up and do one
90 * rdtsc() for all of them. For now, I want to do them on the core, around when
91 * we do the context change. It'll also parallelize the accounting a bit. */
92 void vcore_account_online(struct proc *p, uint32_t vcoreid)
94 struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
95 vc->resume_ticks = read_tsc();
98 void vcore_account_offline(struct proc *p, uint32_t vcoreid)
100 struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
101 vc->total_ticks += read_tsc() - vc->resume_ticks;
104 uint64_t vcore_account_gettotal(struct proc *p, uint32_t vcoreid)
106 struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
107 return vc->total_ticks;
110 /* While this could be done with just an assignment, this gives us the
111 * opportunity to check for bad transitions. Might compile these out later, so
112 * we shouldn't rely on them for sanity checking from userspace. */
113 int __proc_set_state(struct proc *p, uint32_t state)
115 uint32_t curstate = p->state;
116 /* Valid transitions:
134 * These ought to be implemented later (allowed, not thought through yet).
138 #if 1 // some sort of correctness flag
141 if (!(state & (PROC_RUNNABLE_S | PROC_DYING)))
142 panic("Invalid State Transition! PROC_CREATED to %02x", state);
144 case PROC_RUNNABLE_S:
145 if (!(state & (PROC_RUNNING_S | PROC_DYING)))
146 panic("Invalid State Transition! PROC_RUNNABLE_S to %02x", state);
149 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
151 panic("Invalid State Transition! PROC_RUNNING_S to %02x", state);
154 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNING_S | PROC_RUNNABLE_M |
156 panic("Invalid State Transition! PROC_WAITING to %02x", state);
159 if (state != PROC_CREATED) // when it is reused (TODO)
160 panic("Invalid State Transition! PROC_DYING to %02x", state);
162 case PROC_RUNNABLE_M:
163 if (!(state & (PROC_RUNNING_M | PROC_DYING)))
164 panic("Invalid State Transition! PROC_RUNNABLE_M to %02x", state);
167 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
169 panic("Invalid State Transition! PROC_RUNNING_M to %02x", state);
177 /* Returns a pointer to the proc with the given pid, or 0 if there is none.
178 * This uses get_not_zero, since it is possible the refcnt is 0, which means the
179 * process is dying and we should not have the ref (and thus return 0). We need
180 * to lock to protect us from getting p, (someone else removes and frees p),
181 * then get_not_zero() on p.
182 * Don't push the locking into the hashtable without dealing with this. */
183 struct proc *pid2proc(pid_t pid)
185 spin_lock(&pid_hash_lock);
186 struct proc *p = hashtable_search(pid_hash, (void*)(long)pid);
188 if (!kref_get_not_zero(&p->p_kref, 1))
190 spin_unlock(&pid_hash_lock);
194 /* Used by devproc for successive reads of the proc table.
195 * Returns a pointer to the nth proc, or 0 if there is none.
196 * This uses get_not_zero, since it is possible the refcnt is 0, which means the
197 * process is dying and we should not have the ref (and thus return 0). We need
198 * to lock to protect us from getting p, (someone else removes and frees p),
199 * then get_not_zero() on p.
200 * Don't push the locking into the hashtable without dealing with this. */
201 struct proc *pid_nth(unsigned int n)
204 spin_lock(&pid_hash_lock);
205 if (!hashtable_count(pid_hash)) {
206 spin_unlock(&pid_hash_lock);
209 struct hashtable_itr *iter = hashtable_iterator(pid_hash);
210 p = hashtable_iterator_value(iter);
213 /* if this process is not valid, it doesn't count,
217 if (kref_get_not_zero(&p->p_kref, 1)){
218 /* this one counts */
220 printd("pid_nth: at end, p %p\n", p);
223 kref_put(&p->p_kref);
226 if (!hashtable_iterator_advance(iter)){
230 p = hashtable_iterator_value(iter);
233 spin_unlock(&pid_hash_lock);
238 /* Performs any initialization related to processes, such as create the proc
239 * cache, prep the scheduler, etc. When this returns, we should be ready to use
240 * any process related function. */
243 /* Catch issues with the vcoremap and TAILQ_ENTRY sizes */
244 static_assert(sizeof(TAILQ_ENTRY(vcore)) == sizeof(void*) * 2);
245 proc_cache = kmem_cache_create("proc", sizeof(struct proc),
246 MAX(ARCH_CL_SIZE, __alignof__(struct proc)), 0, 0, 0);
247 /* Init PID mask and hash. pid 0 is reserved. */
248 SET_BITMASK_BIT(pid_bmask, 0);
249 spinlock_init(&pid_hash_lock);
250 spin_lock(&pid_hash_lock);
251 pid_hash = create_hashtable(100, __generic_hash, __generic_eq);
252 spin_unlock(&pid_hash_lock);
255 atomic_init(&num_envs, 0);
258 void proc_set_progname(struct proc *p, char *name)
260 /* might have an issue if a dentry name isn't null terminated, and we'd get
261 * extra junk up to progname_sz. */
262 strncpy(p->progname, name, PROC_PROGNAME_SZ);
263 p->progname[PROC_PROGNAME_SZ - 1] = '\0';
266 /* Be sure you init'd the vcore lists before calling this. */
267 static void proc_init_procinfo(struct proc* p)
269 p->procinfo->pid = p->pid;
270 p->procinfo->ppid = p->ppid;
271 p->procinfo->max_vcores = max_vcores(p);
272 p->procinfo->tsc_freq = system_timing.tsc_freq;
273 p->procinfo->timing_overhead = system_timing.timing_overhead;
274 p->procinfo->heap_bottom = 0;
275 /* 0'ing the arguments. Some higher function will need to set them */
276 memset(p->procinfo->argp, 0, sizeof(p->procinfo->argp));
277 memset(p->procinfo->argbuf, 0, sizeof(p->procinfo->argbuf));
278 memset(p->procinfo->res_grant, 0, sizeof(p->procinfo->res_grant));
279 /* 0'ing the vcore/pcore map. Will link the vcores later. */
280 memset(&p->procinfo->vcoremap, 0, sizeof(p->procinfo->vcoremap));
281 memset(&p->procinfo->pcoremap, 0, sizeof(p->procinfo->pcoremap));
282 p->procinfo->num_vcores = 0;
283 p->procinfo->is_mcp = FALSE;
284 p->procinfo->coremap_seqctr = SEQCTR_INITIALIZER;
285 /* It's a bug in the kernel if we let them ask for more than max */
286 for (int i = 0; i < p->procinfo->max_vcores; i++) {
287 TAILQ_INSERT_TAIL(&p->inactive_vcs, &p->procinfo->vcoremap[i], list);
291 static void proc_init_procdata(struct proc *p)
293 memset(p->procdata, 0, sizeof(struct procdata));
294 /* processes can't go into vc context on vc 0 til they unset this. This is
295 * for processes that block before initing uthread code (like rtld). */
296 atomic_set(&p->procdata->vcore_preempt_data[0].flags, VC_SCP_NOVCCTX);
299 /* Allocates and initializes a process, with the given parent. Currently
300 * writes the *p into **pp, and returns 0 on success, < 0 for an error.
302 * - ENOFREEPID if it can't get a PID
303 * - ENOMEM on memory exhaustion */
304 error_t proc_alloc(struct proc **pp, struct proc *parent, int flags)
309 if (!(p = kmem_cache_alloc(proc_cache, 0)))
311 /* zero everything by default, other specific items are set below */
312 memset(p, 0, sizeof(struct proc));
316 /* only one ref, which we pass back. the old 'existence' ref is managed by
318 kref_init(&p->p_kref, __proc_free, 1);
319 // Setup the default map of where to get cache colors from
320 p->cache_colors_map = global_cache_colors_map;
321 p->next_cache_color = 0;
322 /* Initialize the address space */
323 if ((r = env_setup_vm(p)) < 0) {
324 kmem_cache_free(proc_cache, p);
327 if (!(p->pid = get_free_pid())) {
328 kmem_cache_free(proc_cache, p);
331 /* Set the basic status variables. */
332 spinlock_init(&p->proc_lock);
333 p->exitcode = 1337; /* so we can see processes killed by the kernel */
335 p->ppid = parent->pid;
336 proc_incref(p, 1); /* storing a ref in the parent */
337 /* using the CV's lock to protect anything related to child waiting */
338 cv_lock(&parent->child_wait);
339 TAILQ_INSERT_TAIL(&parent->children, p, sibling_link);
340 cv_unlock(&parent->child_wait);
344 TAILQ_INIT(&p->children);
345 cv_init(&p->child_wait);
346 p->state = PROC_CREATED; /* shouldn't go through state machine for init */
348 p->env_entry = 0; // cheating. this really gets set later
350 spinlock_init(&p->vmr_lock);
351 spinlock_init(&p->pte_lock);
352 TAILQ_INIT(&p->vm_regions); /* could init this in the slab */
354 /* Initialize the vcore lists, we'll build the inactive list so that it
355 * includes all vcores when we initialize procinfo. Do this before initing
357 TAILQ_INIT(&p->online_vcs);
358 TAILQ_INIT(&p->bulk_preempted_vcs);
359 TAILQ_INIT(&p->inactive_vcs);
360 /* Init procinfo/procdata. Procinfo's argp/argb are 0'd */
361 proc_init_procinfo(p);
362 proc_init_procdata(p);
364 /* Initialize the generic sysevent ring buffer */
365 SHARED_RING_INIT(&p->procdata->syseventring);
366 /* Initialize the frontend of the sysevent ring buffer */
367 FRONT_RING_INIT(&p->syseventfrontring,
368 &p->procdata->syseventring,
371 /* Init FS structures TODO: cleanup (might pull this out) */
372 kref_get(&default_ns.kref, 1);
374 spinlock_init(&p->fs_env.lock);
375 p->fs_env.umask = parent ? parent->fs_env.umask : S_IWGRP | S_IWOTH;
376 p->fs_env.root = p->ns->root->mnt_root;
377 kref_get(&p->fs_env.root->d_kref, 1);
378 p->fs_env.pwd = parent ? parent->fs_env.pwd : p->fs_env.root;
379 kref_get(&p->fs_env.pwd->d_kref, 1);
380 memset(&p->open_files, 0, sizeof(p->open_files)); /* slightly ghetto */
381 spinlock_init(&p->open_files.lock);
382 p->open_files.max_files = NR_OPEN_FILES_DEFAULT;
383 p->open_files.max_fdset = NR_FILE_DESC_DEFAULT;
384 p->open_files.fd = p->open_files.fd_array;
385 p->open_files.open_fds = (struct fd_set*)&p->open_files.open_fds_init;
387 if (flags & PROC_DUP_FGRP)
388 clone_files(&parent->open_files, &p->open_files);
390 /* no parent, we're created from the kernel */
391 assert(insert_file(&p->open_files, dev_stdin, 0, TRUE) == 0);
392 assert(insert_file(&p->open_files, dev_stdout, 1, TRUE) == 1);
393 assert(insert_file(&p->open_files, dev_stderr, 2, TRUE) == 2);
395 /* Init the ucq hash lock */
396 p->ucq_hashlock = (struct hashlock*)&p->ucq_hl_noref;
397 hashlock_init_irqsave(p->ucq_hashlock, HASHLOCK_DEFAULT_SZ);
399 atomic_inc(&num_envs);
400 frontend_proc_init(p);
401 /* this does all the 9ns setup, much of which is done throughout this func
402 * for the VFS, including duping the fgrp */
403 plan9setup(p, parent, flags);
405 TAILQ_INIT(&p->abortable_sleepers);
406 spinlock_init_irqsave(&p->abort_list_lock);
407 printd("[%08x] new process %08x\n", current ? current->pid : 0, p->pid);
413 /* We have a bunch of different ways to make processes. Call this once the
414 * process is ready to be used by the rest of the system. For now, this just
415 * means when it is ready to be named via the pidhash. In the future, we might
416 * push setting the state to CREATED into here. */
417 void __proc_ready(struct proc *p)
419 /* Tell the ksched about us. TODO: do we need to worry about the ksched
420 * doing stuff to us before we're added to the pid_hash? */
421 __sched_proc_register(p);
422 spin_lock(&pid_hash_lock);
423 hashtable_insert(pid_hash, (void*)(long)p->pid, p);
424 spin_unlock(&pid_hash_lock);
427 /* Creates a process from the specified file, argvs, and envps. Tempted to get
428 * rid of proc_alloc's style, but it is so quaint... */
429 struct proc *proc_create(struct file *prog, char **argv, char **envp)
433 if ((r = proc_alloc(&p, current, 0 /* flags */)) < 0)
434 panic("proc_create: %e", r); /* one of 3 quaint usages of %e */
435 proc_set_progname(p, argv[0]);
436 procinfo_pack_args(p->procinfo, argv, envp);
437 assert(load_elf(p, prog) == 0);
442 static int __cb_assert_no_pg(struct proc *p, pte_t *pte, void *va, void *arg)
448 /* This is called by kref_put(), once the last reference to the process is
449 * gone. Don't call this otherwise (it will panic). It will clean up the
450 * address space and deallocate any other used memory. */
451 static void __proc_free(struct kref *kref)
453 struct proc *p = container_of(kref, struct proc, p_kref);
457 printd("[PID %d] freeing proc: %d\n", current ? current->pid : 0, p->pid);
458 // All parts of the kernel should have decref'd before __proc_free is called
459 assert(kref_refcnt(&p->p_kref) == 0);
460 assert(TAILQ_EMPTY(&p->alarmset.list));
465 p->dot = p->slash = 0; /* catch bugs */
466 /* can safely free the fgrp, now that no one is accessing it */
469 kref_put(&p->fs_env.root->d_kref);
470 kref_put(&p->fs_env.pwd->d_kref);
471 /* now we'll finally decref files for the file-backed vmrs */
472 unmap_and_destroy_vmrs(p);
473 frontend_proc_free(p); /* TODO: please remove me one day */
474 /* Free any colors allocated to this process */
475 if (p->cache_colors_map != global_cache_colors_map) {
476 for(int i = 0; i < llc_cache->num_colors; i++)
477 cache_color_free(llc_cache, p->cache_colors_map);
478 cache_colors_map_free(p->cache_colors_map);
480 /* Remove us from the pid_hash and give our PID back (in that order). */
481 spin_lock(&pid_hash_lock);
482 hash_ret = hashtable_remove(pid_hash, (void*)(long)p->pid);
483 spin_unlock(&pid_hash_lock);
484 /* might not be in the hash/ready, if we failed during proc creation */
486 put_free_pid(p->pid);
488 printd("[kernel] pid %d not in the PID hash in %s\n", p->pid,
490 /* all memory below UMAPTOP should have been freed via the VMRs. the stuff
491 * above is the global page and procinfo/procdata */
492 env_user_mem_free(p, (void*)UMAPTOP, UVPT - UMAPTOP); /* 3rd arg = len... */
493 env_user_mem_walk(p, 0, UMAPTOP, __cb_assert_no_pg, 0);
494 /* These need to be freed again, since they were allocated with a refcnt. */
495 free_cont_pages(p->procinfo, LOG2_UP(PROCINFO_NUM_PAGES));
496 free_cont_pages(p->procdata, LOG2_UP(PROCDATA_NUM_PAGES));
498 env_pagetable_free(p);
502 atomic_dec(&num_envs);
504 /* Dealloc the struct proc */
505 kmem_cache_free(proc_cache, p);
508 /* Whether or not actor can control target. TODO: do something reasonable here.
509 * Just checking for the parent is a bit limiting. Could walk the parent-child
510 * tree, check user ids, or some combination. Make sure actors can always
511 * control themselves. */
512 bool proc_controls(struct proc *actor, struct proc *target)
516 return ((actor == target) || (target->ppid == actor->pid));
520 /* Helper to incref by val. Using the helper to help debug/interpose on proc
521 * ref counting. Note that pid2proc doesn't use this interface. */
522 void proc_incref(struct proc *p, unsigned int val)
524 kref_get(&p->p_kref, val);
527 /* Helper to decref for debugging. Don't directly kref_put() for now. */
528 void proc_decref(struct proc *p)
530 kref_put(&p->p_kref);
533 /* Helper, makes p the 'current' process, dropping the old current/cr3. This no
534 * longer assumes the passed in reference already counted 'current'. It will
535 * incref internally when needed. */
536 static void __set_proc_current(struct proc *p)
538 /* We use the pcpui to access 'current' to cut down on the core_id() calls,
539 * though who know how expensive/painful they are. */
540 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
541 /* If the process wasn't here, then we need to load its address space. */
542 if (p != pcpui->cur_proc) {
545 /* This is "leaving the process context" of the previous proc. The
546 * previous lcr3 unloaded the previous proc's context. This should
547 * rarely happen, since we usually proactively leave process context,
548 * but this is the fallback. */
550 proc_decref(pcpui->cur_proc);
555 /* Flag says if vcore context is not ready, which is set in init_procdata. The
556 * process must turn off this flag on vcore0 at some point. It's off by default
557 * on all other vcores. */
558 static bool scp_is_vcctx_ready(struct preempt_data *vcpd)
560 return !(atomic_read(&vcpd->flags) & VC_SCP_NOVCCTX);
563 /* Dispatches a _S process to run on the current core. This should never be
564 * called to "restart" a core.
566 * This will always return, regardless of whether or not the calling core is
567 * being given to a process. (it used to pop the tf directly, before we had
570 * Since it always returns, it will never "eat" your reference (old
571 * documentation talks about this a bit). */
572 void proc_run_s(struct proc *p)
574 uint32_t coreid = core_id();
575 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
576 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
577 spin_lock(&p->proc_lock);
580 spin_unlock(&p->proc_lock);
581 printk("[kernel] _S %d not starting due to async death\n", p->pid);
583 case (PROC_RUNNABLE_S):
584 __proc_set_state(p, PROC_RUNNING_S);
585 /* We will want to know where this process is running, even if it is
586 * only in RUNNING_S. can use the vcoremap, which makes death easy.
587 * Also, this is the signal used in trap.c to know to save the tf in
589 __seq_start_write(&p->procinfo->coremap_seqctr);
590 p->procinfo->num_vcores = 0; /* TODO (VC#) */
591 /* TODO: For now, we won't count this as an active vcore (on the
592 * lists). This gets unmapped in resource.c and yield_s, and needs
594 __map_vcore(p, 0, coreid); /* not treated like a true vcore */
595 vcore_account_online(p, 0); /* VC# */
596 __seq_end_write(&p->procinfo->coremap_seqctr);
597 /* incref, since we're saving a reference in owning proc later */
599 /* lock was protecting the state and VC mapping, not pcpui stuff */
600 spin_unlock(&p->proc_lock);
601 /* redundant with proc_startcore, might be able to remove that one*/
602 __set_proc_current(p);
603 /* set us up as owning_proc. ksched bug if there is already one,
604 * for now. can simply clear_owning if we want to. */
605 assert(!pcpui->owning_proc);
606 pcpui->owning_proc = p;
607 pcpui->owning_vcoreid = 0; /* TODO (VC#) */
608 restore_vc_fp_state(vcpd);
609 /* similar to the old __startcore, start them in vcore context if
610 * they have notifs and aren't already in vcore context. o/w, start
611 * them wherever they were before (could be either vc ctx or not) */
612 if (!vcpd->notif_disabled && vcpd->notif_pending
613 && scp_is_vcctx_ready(vcpd)) {
614 vcpd->notif_disabled = TRUE;
615 /* save the _S's ctx in the uthread slot, build and pop a new
616 * one in actual/cur_ctx. */
617 vcpd->uthread_ctx = p->scp_ctx;
618 pcpui->cur_ctx = &pcpui->actual_ctx;
619 memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
620 proc_init_ctx(pcpui->cur_ctx, 0, p->env_entry,
621 vcpd->transition_stack, vcpd->vcore_tls_desc);
623 /* If they have no transition stack, then they can't receive
624 * events. The most they are getting is a wakeup from the
625 * kernel. They won't even turn off notif_pending, so we'll do
627 if (!scp_is_vcctx_ready(vcpd))
628 vcpd->notif_pending = FALSE;
629 /* this is one of the few times cur_ctx != &actual_ctx */
630 pcpui->cur_ctx = &p->scp_ctx;
632 /* When the calling core idles, it'll call restartcore and run the
633 * _S process's context. */
636 spin_unlock(&p->proc_lock);
637 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
641 /* Helper: sends preempt messages to all vcores on the bulk preempt list, and
642 * moves them to the inactive list. */
643 static void __send_bulkp_events(struct proc *p)
645 struct vcore *vc_i, *vc_temp;
646 struct event_msg preempt_msg = {0};
647 /* Whenever we send msgs with the proc locked, we need at least 1 online */
648 assert(!TAILQ_EMPTY(&p->online_vcs));
649 /* Send preempt messages for any left on the BP list. No need to set any
650 * flags, it all was done on the real preempt. Now we're just telling the
651 * process about any that didn't get restarted and are still preempted. */
652 TAILQ_FOREACH_SAFE(vc_i, &p->bulk_preempted_vcs, list, vc_temp) {
653 /* Note that if there are no active vcores, send_k_e will post to our
654 * own vcore, the last of which will be put on the inactive list and be
655 * the first to be started. We could have issues with deadlocking,
656 * since send_k_e() could grab the proclock (if there are no active
658 preempt_msg.ev_type = EV_VCORE_PREEMPT;
659 preempt_msg.ev_arg2 = vcore2vcoreid(p, vc_i); /* arg2 is 32 bits */
660 send_kernel_event(p, &preempt_msg, 0);
661 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that.
662 * We need a loop for the messages, but not necessarily for the list
664 TAILQ_REMOVE(&p->bulk_preempted_vcs, vc_i, list);
665 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
669 /* Run an _M. Can be called safely on one that is already running. Hold the
670 * lock before calling. Other than state checks, this just starts up the _M's
671 * vcores, much like the second part of give_cores_running. More specifically,
672 * give_cores_runnable puts cores on the online list, which this then sends
673 * messages to. give_cores_running immediately puts them on the list and sends
674 * the message. the two-step style may go out of fashion soon.
676 * This expects that the "instructions" for which core(s) to run this on will be
677 * in the vcoremap, which needs to be set externally (give_cores()). */
678 void __proc_run_m(struct proc *p)
684 warn("ksched tried to run proc %d in state %s\n", p->pid,
685 procstate2str(p->state));
687 case (PROC_RUNNABLE_M):
688 /* vcoremap[i] holds the coreid of the physical core allocated to
689 * this process. It is set outside proc_run. */
690 if (p->procinfo->num_vcores) {
691 __send_bulkp_events(p);
692 __proc_set_state(p, PROC_RUNNING_M);
693 /* Up the refcnt, to avoid the n refcnt upping on the
694 * destination cores. Keep in sync with __startcore */
695 proc_incref(p, p->procinfo->num_vcores * 2);
696 /* Send kernel messages to all online vcores (which were added
697 * to the list and mapped in __proc_give_cores()), making them
699 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
700 send_kernel_message(vc_i->pcoreid, __startcore, (long)p,
701 (long)vcore2vcoreid(p, vc_i),
702 (long)vc_i->nr_preempts_sent,
706 warn("Tried to proc_run() an _M with no vcores!");
708 /* There a subtle race avoidance here (when we unlock after sending
709 * the message). __proc_startcore can handle a death message, but
710 * we can't have the startcore come after the death message.
711 * Otherwise, it would look like a new process. So we hold the lock
712 * til after we send our message, which prevents a possible death
714 * - Note there is no guarantee this core's interrupts were on, so
715 * it may not get the message for a while... */
717 case (PROC_RUNNING_M):
720 /* unlock just so the monitor can call something that might lock*/
721 spin_unlock(&p->proc_lock);
722 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
726 /* You must disable IRQs and PRKM before calling this.
728 * Actually runs the given context (trapframe) of process p on the core this
729 * code executes on. This is called directly by __startcore, which needs to
730 * bypass the routine_kmsg check. Interrupts should be off when you call this.
732 * A note on refcnting: this function will not return, and your proc reference
733 * will end up stored in current. This will make no changes to p's refcnt, so
734 * do your accounting such that there is only the +1 for current. This means if
735 * it is already in current (like in the trap return path), don't up it. If
736 * it's already in current and you have another reference (like pid2proc or from
737 * an IPI), then down it (which is what happens in __startcore()). If it's not
738 * in current and you have one reference, like proc_run(non_current_p), then
739 * also do nothing. The refcnt for your *p will count for the reference stored
741 void __proc_startcore(struct proc *p, struct user_context *ctx)
743 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
744 assert(!irq_is_enabled());
745 /* Should never have ktask still set. If we do, future syscalls could try
746 * to block later and lose track of our address space. */
747 assert(!pcpui->cur_kthread->is_ktask);
748 __set_proc_current(p);
749 /* Clear the current_ctx, since it is no longer used */
750 current_ctx = 0; /* TODO: might not need this... */
751 __set_cpu_state(pcpui, CPU_STATE_USER);
755 /* Restarts/runs the current_ctx, which must be for the current process, on the
756 * core this code executes on. Calls an internal function to do the work.
758 * In case there are pending routine messages, like __death, __preempt, or
759 * __notify, we need to run them. Alternatively, if there are any, we could
760 * self_ipi, and run the messages immediately after popping back to userspace,
761 * but that would have crappy overhead. */
762 void proc_restartcore(void)
764 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
765 assert(!pcpui->cur_kthread->sysc);
766 /* TODO: can probably remove this enable_irq. it was an optimization for
768 /* Try and get any interrupts before we pop back to userspace. If we didn't
769 * do this, we'd just get them in userspace, but this might save us some
770 * effort/overhead. */
772 /* Need ints disabled when we return from PRKM (race on missing
775 process_routine_kmsg();
776 /* If there is no owning process, just idle, since we don't know what to do.
777 * This could be because the process had been restarted a long time ago and
778 * has since left the core, or due to a KMSG like __preempt or __death. */
779 if (!pcpui->owning_proc) {
783 assert(pcpui->cur_ctx);
784 __proc_startcore(pcpui->owning_proc, pcpui->cur_ctx);
787 /* Destroys the process. It will destroy the process and return any cores
788 * to the ksched via the __sched_proc_destroy() CB.
790 * Here's the way process death works:
791 * 0. grab the lock (protects state transition and core map)
792 * 1. set state to dying. that keeps the kernel from doing anything for the
793 * process (like proc_running it).
794 * 2. figure out where the process is running (cross-core/async or RUNNING_M)
795 * 3. IPI to clean up those cores (decref, etc).
797 * 5. Clean up your core, if applicable
798 * (Last core/kernel thread to decref cleans up and deallocates resources.)
800 * Note that some cores can be processing async calls, but will eventually
801 * decref. Should think about this more, like some sort of callback/revocation.
803 * This function will now always return (it used to not return if the calling
804 * core was dying). However, when it returns, a kernel message will eventually
805 * come in, making you abandon_core, as if you weren't running. It may be that
806 * the only reference to p is the one you passed in, and when you decref, it'll
807 * get __proc_free()d. */
808 void proc_destroy(struct proc *p)
810 uint32_t nr_cores_revoked = 0;
811 struct kthread *sleeper;
812 struct proc *child_i, *temp;
813 /* Can't spin on the proc lock with irq disabled. This is a problem for all
814 * places where we grab the lock, but it is particularly bad for destroy,
815 * since we tend to call this from trap and irq handlers */
816 assert(irq_is_enabled());
817 spin_lock(&p->proc_lock);
818 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
819 uint32_t pc_arr[p->procinfo->num_vcores];
821 case PROC_DYING: /* someone else killed this already. */
822 spin_unlock(&p->proc_lock);
825 case PROC_RUNNABLE_S:
828 case PROC_RUNNABLE_M:
830 /* Need to reclaim any cores this proc might have, even if it's not
831 * running yet. Those running will receive a __death */
832 nr_cores_revoked = __proc_take_allcores(p, pc_arr, FALSE);
836 // here's how to do it manually
839 proc_decref(p); /* this decref is for the cr3 */
843 send_kernel_message(get_pcoreid(p, 0), __death, 0, 0, 0,
845 __seq_start_write(&p->procinfo->coremap_seqctr);
846 // TODO: might need to sort num_vcores too later (VC#)
847 /* vcore is unmapped on the receive side */
848 __seq_end_write(&p->procinfo->coremap_seqctr);
849 /* If we ever have RUNNING_S run on non-mgmt cores, we'll need to
850 * tell the ksched about this now-idle core (after unlocking) */
853 warn("Weird state(%s) in %s()", procstate2str(p->state),
855 spin_unlock(&p->proc_lock);
858 /* At this point, a death IPI should be on its way, either from the
859 * RUNNING_S one, or from proc_take_cores with a __death. in general,
860 * interrupts should be on when you call proc_destroy locally, but currently
861 * aren't for all things (like traphandlers). */
862 __proc_set_state(p, PROC_DYING);
863 /* Disown any children. If we want to have init inherit or something,
864 * change __disown to set the ppid accordingly and concat this with init's
865 * list (instead of emptying it like disown does). Careful of lock ordering
866 * between procs (need to lock to protect lists) */
867 TAILQ_FOREACH_SAFE(child_i, &p->children, sibling_link, temp) {
868 int ret = __proc_disown_child(p, child_i);
869 /* should never fail, lock should cover the race. invariant: any child
870 * on the list should have us as a parent */
873 spin_unlock(&p->proc_lock);
874 /* Wake any of our kthreads waiting on children, so they can abort */
875 cv_broadcast(&p->child_wait);
876 /* Abort any abortable syscalls. This won't catch every sleeper, but future
877 * abortable sleepers are already prevented via the DYING state. (signalled
878 * DYING, no new sleepers will block, and now we wake all old sleepers). */
880 /* we need to close files here, and not in free, since we could have a
881 * refcnt indirectly related to one of our files. specifically, if we have
882 * a parent sleeping on our pipe, that parent won't wake up to decref until
883 * the pipe closes. And if the parent doesnt decref, we don't free.
884 * alternatively, we could send a SIGCHILD to the parent, but that would
885 * require parent's to never ignore that signal (or risk never reaping).
887 * Also note that any mmap'd files will still be mmapped. You can close the
888 * file after mmapping, with no effect. */
889 close_9ns_files(p, FALSE);
890 close_all_files(&p->open_files, FALSE);
891 /* Tell the ksched about our death, and which cores we freed up */
892 __sched_proc_destroy(p, pc_arr, nr_cores_revoked);
893 /* Tell our parent about our state change (to DYING) */
894 proc_signal_parent(p);
897 /* Can use this to signal anything that might cause a parent to wait on the
898 * child, such as termination, or (in the future) signals. Change the state or
899 * whatever before calling. */
900 void proc_signal_parent(struct proc *child)
902 struct kthread *sleeper;
903 struct proc *parent = pid2proc(child->ppid);
906 /* there could be multiple kthreads sleeping for various reasons. even an
907 * SCP could have multiple async syscalls. */
908 cv_broadcast(&parent->child_wait);
909 /* if the parent was waiting, there's a __launch kthread KMSG out there */
913 /* Called when a parent is done with its child, and no longer wants to track the
914 * child, nor to allow the child to track it. Call with a lock (cv) held.
915 * Returns 0 if we disowned, -1 on failure. */
916 int __proc_disown_child(struct proc *parent, struct proc *child)
918 /* Bail out if the child has already been reaped */
921 assert(child->ppid == parent->pid);
922 /* lock protects from concurrent inserts / removals from the list */
923 TAILQ_REMOVE(&parent->children, child, sibling_link);
924 /* After this, the child won't be able to get more refs to us, but it may
925 * still have some references in running code. */
927 proc_decref(child); /* ref that was keeping the child alive on the list */
931 /* Turns *p into an MCP. Needs to be called from a local syscall of a RUNNING_S
932 * process. Returns 0 if it succeeded, an error code otherwise. */
933 int proc_change_to_m(struct proc *p)
936 spin_lock(&p->proc_lock);
937 /* in case userspace erroneously tries to change more than once */
938 if (__proc_is_mcp(p))
941 case (PROC_RUNNING_S):
942 /* issue with if we're async or not (need to preempt it)
943 * either of these should trip it. TODO: (ACR) async core req
944 * TODO: relies on vcore0 being the caller (VC#) */
945 if ((current != p) || (get_pcoreid(p, 0) != core_id()))
946 panic("We don't handle async RUNNING_S core requests yet.");
947 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
949 /* Copy uthread0's context to VC 0's uthread slot */
950 vcpd->uthread_ctx = *current_ctx;
951 clear_owning_proc(core_id()); /* so we don't restart */
952 save_vc_fp_state(vcpd);
953 /* Userspace needs to not fuck with notif_disabled before
954 * transitioning to _M. */
955 if (vcpd->notif_disabled) {
956 printk("[kernel] user bug: notifs disabled for vcore 0\n");
957 vcpd->notif_disabled = FALSE;
959 /* in the async case, we'll need to remotely stop and bundle
960 * vcore0's TF. this is already done for the sync case (local
962 /* this process no longer runs on its old location (which is
963 * this core, for now, since we don't handle async calls) */
964 __seq_start_write(&p->procinfo->coremap_seqctr);
965 // TODO: (VC#) might need to adjust num_vcores
966 // TODO: (ACR) will need to unmap remotely (receive-side)
967 __unmap_vcore(p, 0); /* VC# keep in sync with proc_run_s */
968 vcore_account_offline(p, 0); /* VC# */
969 __seq_end_write(&p->procinfo->coremap_seqctr);
970 /* change to runnable_m (it's TF is already saved) */
971 __proc_set_state(p, PROC_RUNNABLE_M);
972 p->procinfo->is_mcp = TRUE;
973 spin_unlock(&p->proc_lock);
974 /* Tell the ksched that we're a real MCP now! */
975 __sched_proc_change_to_m(p);
977 case (PROC_RUNNABLE_S):
978 /* Issues: being on the runnable_list, proc_set_state not liking
979 * it, and not clearly thinking through how this would happen.
980 * Perhaps an async call that gets serviced after you're
982 warn("Not supporting RUNNABLE_S -> RUNNABLE_M yet.\n");
985 warn("Dying, core request coming from %d\n", core_id());
991 spin_unlock(&p->proc_lock);
995 /* Old code to turn a RUNNING_M to a RUNNING_S, with the calling context
996 * becoming the new 'thread0'. Don't use this. Caller needs to send in a
997 * pc_arr big enough for all vcores. Will return the number of cores given up
999 uint32_t __proc_change_to_s(struct proc *p, uint32_t *pc_arr)
1001 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1002 uint32_t num_revoked;
1003 /* Not handling vcore accounting. Do so if we ever use this */
1004 printk("[kernel] trying to transition _M -> _S (deprecated)!\n");
1005 assert(p->state == PROC_RUNNING_M); // TODO: (ACR) async core req
1006 /* save the context, to be restarted in _S mode */
1007 assert(current_ctx);
1008 p->scp_ctx = *current_ctx;
1009 clear_owning_proc(core_id()); /* so we don't restart */
1010 save_vc_fp_state(vcpd);
1011 /* sending death, since it's not our job to save contexts or anything in
1013 num_revoked = __proc_take_allcores(p, pc_arr, FALSE);
1014 __proc_set_state(p, PROC_RUNNABLE_S);
1018 /* Helper function. Is the given pcore a mapped vcore? No locking involved, be
1020 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid)
1022 return p->procinfo->pcoremap[pcoreid].valid;
1025 /* Helper function. Find the vcoreid for a given physical core id for proc p.
1026 * No locking involved, be careful. Panics on failure. */
1027 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid)
1029 assert(is_mapped_vcore(p, pcoreid));
1030 return p->procinfo->pcoremap[pcoreid].vcoreid;
1033 /* Helper function. Try to find the pcoreid for a given virtual core id for
1034 * proc p. No locking involved, be careful. Use this when you can tolerate a
1035 * stale or otherwise 'wrong' answer. */
1036 static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid)
1038 return p->procinfo->vcoremap[vcoreid].pcoreid;
1041 /* Helper function. Find the pcoreid for a given virtual core id for proc p.
1042 * No locking involved, be careful. Panics on failure. */
1043 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid)
1045 assert(vcore_is_mapped(p, vcoreid));
1046 return try_get_pcoreid(p, vcoreid);
1049 /* Saves the FP state of the calling core into VCPD. Pairs with
1050 * restore_vc_fp_state(). On x86, the best case overhead of the flags:
1054 * Flagged FXSAVE: 50 ns
1055 * Flagged FXRSTR: 66 ns
1056 * Excess flagged FXRSTR: 42 ns
1057 * If we don't do it, we'll need to initialize every VCPD at process creation
1058 * time with a good FPU state (x86 control words are initialized as 0s, like the
1060 static void save_vc_fp_state(struct preempt_data *vcpd)
1062 save_fp_state(&vcpd->preempt_anc);
1063 vcpd->rflags |= VC_FPU_SAVED;
1066 /* Conditionally restores the FP state from VCPD. If the state was not valid,
1067 * we don't bother restoring and just initialize the FPU. */
1068 static void restore_vc_fp_state(struct preempt_data *vcpd)
1070 if (vcpd->rflags & VC_FPU_SAVED) {
1071 restore_fp_state(&vcpd->preempt_anc);
1072 vcpd->rflags &= ~VC_FPU_SAVED;
1078 /* Helper for SCPs, saves the core's FPU state into the VCPD vc0 slot */
1079 void __proc_save_fpu_s(struct proc *p)
1081 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1082 save_vc_fp_state(vcpd);
1085 /* Helper: saves the SCP's GP tf state and unmaps vcore 0. This does *not* save
1088 * In the future, we'll probably use vc0's space for scp_ctx and the silly
1089 * state. If we ever do that, we'll need to stop using scp_ctx (soon to be in
1090 * VCPD) as a location for pcpui->cur_ctx to point (dangerous) */
1091 void __proc_save_context_s(struct proc *p, struct user_context *ctx)
1094 __unmap_vcore(p, 0); /* VC# keep in sync with proc_run_s */
1095 vcore_account_offline(p, 0); /* VC# */
1098 /* Yields the calling core. Must be called locally (not async) for now.
1099 * - If RUNNING_S, you just give up your time slice and will eventually return,
1100 * possibly after WAITING on an event.
1101 * - If RUNNING_M, you give up the current vcore (which never returns), and
1102 * adjust the amount of cores wanted/granted.
1103 * - If you have only one vcore, you switch to WAITING. There's no 'classic
1104 * yield' for MCPs (at least not now). When you run again, you'll have one
1105 * guaranteed core, starting from the entry point.
1107 * If the call is being nice, it means different things for SCPs and MCPs. For
1108 * MCPs, it means that it is in response to a preemption (which needs to be
1109 * checked). If there is no preemption pending, just return. For SCPs, it
1110 * means the proc wants to give up the core, but still has work to do. If not,
1111 * the proc is trying to wait on an event. It's not being nice to others, it
1112 * just has no work to do.
1114 * This usually does not return (smp_idle()), so it will eat your reference.
1115 * Also note that it needs a non-current/edible reference, since it will abandon
1116 * and continue to use the *p (current == 0, no cr3, etc).
1118 * We disable interrupts for most of it too, since we need to protect
1119 * current_ctx and not race with __notify (which doesn't play well with
1120 * concurrent yielders). */
1121 void proc_yield(struct proc *SAFE p, bool being_nice)
1123 uint32_t vcoreid, pcoreid = core_id();
1124 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1126 struct preempt_data *vcpd;
1127 /* Need to lock to prevent concurrent vcore changes (online, inactive, the
1128 * mapping, etc). This plus checking the nr_preempts is enough to tell if
1129 * our vcoreid and cur_ctx ought to be here still or if we should abort */
1130 spin_lock(&p->proc_lock); /* horrible scalability. =( */
1132 case (PROC_RUNNING_S):
1134 /* waiting for an event to unblock us */
1135 vcpd = &p->procdata->vcore_preempt_data[0];
1136 /* syncing with event's SCP code. we set waiting, then check
1137 * pending. they set pending, then check waiting. it's not
1138 * possible for us to miss the notif *and* for them to miss
1139 * WAITING. one (or both) of us will see and make sure the proc
1141 __proc_set_state(p, PROC_WAITING);
1142 wrmb(); /* don't let the state write pass the notif read */
1143 if (vcpd->notif_pending) {
1144 __proc_set_state(p, PROC_RUNNING_S);
1145 /* they can't handle events, just need to prevent a yield.
1146 * (note the notif_pendings are collapsed). */
1147 if (!scp_is_vcctx_ready(vcpd))
1148 vcpd->notif_pending = FALSE;
1151 /* if we're here, we want to sleep. a concurrent event that
1152 * hasn't already written notif_pending will have seen WAITING,
1153 * and will be spinning while we do this. */
1154 __proc_save_context_s(p, current_ctx);
1155 spin_unlock(&p->proc_lock);
1157 /* yielding to allow other processes to run. we're briefly
1158 * WAITING, til we are woken up */
1159 __proc_set_state(p, PROC_WAITING);
1160 __proc_save_context_s(p, current_ctx);
1161 spin_unlock(&p->proc_lock);
1162 /* immediately wake up the proc (makes it runnable) */
1165 goto out_yield_core;
1166 case (PROC_RUNNING_M):
1167 break; /* will handle this stuff below */
1168 case (PROC_DYING): /* incoming __death */
1169 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1172 panic("Weird state(%s) in %s()", procstate2str(p->state),
1175 /* This is which vcore this pcore thinks it is, regardless of any unmappings
1176 * that may have happened remotely (with __PRs waiting to run) */
1177 vcoreid = pcpui->owning_vcoreid;
1178 vc = vcoreid2vcore(p, vcoreid);
1179 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1180 /* This is how we detect whether or not a __PR happened. */
1181 if (vc->nr_preempts_sent != vc->nr_preempts_done)
1183 /* Sanity checks. If we were preempted or are dying, we should have noticed
1185 assert(is_mapped_vcore(p, pcoreid));
1186 assert(vcoreid == get_vcoreid(p, pcoreid));
1187 /* no reason to be nice, return */
1188 if (being_nice && !vc->preempt_pending)
1190 /* At this point, AFAIK there should be no preempt/death messages on the
1191 * way, and we're on the online list. So we'll go ahead and do the yielding
1193 /* If there's a preempt pending, we don't need to preempt later since we are
1194 * yielding (nice or otherwise). If not, this is just a regular yield. */
1195 if (vc->preempt_pending) {
1196 vc->preempt_pending = 0;
1198 /* Optional: on a normal yield, check to see if we are putting them
1199 * below amt_wanted (help with user races) and bail. */
1200 if (p->procdata->res_req[RES_CORES].amt_wanted >=
1201 p->procinfo->num_vcores)
1204 /* Don't let them yield if they are missing a notification. Userspace must
1205 * not leave vcore context without dealing with notif_pending.
1206 * pop_user_ctx() handles leaving via uthread context. This handles leaving
1209 * This early check is an optimization. The real check is below when it
1210 * works with the online_vcs list (syncing with event.c and INDIR/IPI
1212 if (vcpd->notif_pending)
1214 /* Now we'll actually try to yield */
1215 printd("[K] Process %d (%p) is yielding on vcore %d\n", p->pid, p,
1216 get_vcoreid(p, pcoreid));
1217 /* Remove from the online list, add to the yielded list, and unmap
1218 * the vcore, which gives up the core. */
1219 TAILQ_REMOVE(&p->online_vcs, vc, list);
1220 /* Now that we're off the online list, check to see if an alert made
1221 * it through (event.c sets this) */
1222 wrmb(); /* prev write must hit before reading notif_pending */
1223 /* Note we need interrupts disabled, since a __notify can come in
1224 * and set pending to FALSE */
1225 if (vcpd->notif_pending) {
1226 /* We lost, put it back on the list and abort the yield. If we ever
1227 * build an myield, we'll need a way to deal with this for all vcores */
1228 TAILQ_INSERT_TAIL(&p->online_vcs, vc, list); /* could go HEAD */
1231 /* Not really a kmsg, but it acts like one w.r.t. proc mgmt */
1232 pcpui_trace_kmsg(pcpui, (uintptr_t)proc_yield);
1233 /* We won the race with event sending, we can safely yield */
1234 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1235 /* Note this protects stuff userspace should look at, which doesn't
1236 * include the TAILQs. */
1237 __seq_start_write(&p->procinfo->coremap_seqctr);
1238 /* Next time the vcore starts, it starts fresh */
1239 vcpd->notif_disabled = FALSE;
1240 __unmap_vcore(p, vcoreid);
1241 p->procinfo->num_vcores--;
1242 p->procinfo->res_grant[RES_CORES] = p->procinfo->num_vcores;
1243 __seq_end_write(&p->procinfo->coremap_seqctr);
1244 vcore_account_offline(p, vcoreid);
1245 /* No more vcores? Then we wait on an event */
1246 if (p->procinfo->num_vcores == 0) {
1247 /* consider a ksched op to tell it about us WAITING */
1248 __proc_set_state(p, PROC_WAITING);
1250 spin_unlock(&p->proc_lock);
1251 /* Hand the now-idle core to the ksched */
1252 __sched_put_idle_core(p, pcoreid);
1253 goto out_yield_core;
1255 /* for some reason we just want to return, either to take a KMSG that cleans
1256 * us up, or because we shouldn't yield (ex: notif_pending). */
1257 spin_unlock(&p->proc_lock);
1259 out_yield_core: /* successfully yielded the core */
1260 proc_decref(p); /* need to eat the ref passed in */
1261 /* Clean up the core and idle. */
1262 clear_owning_proc(pcoreid); /* so we don't restart */
1267 /* Sends a notification (aka active notification, aka IPI) to p's vcore. We
1268 * only send a notification if one they are enabled. There's a bunch of weird
1269 * cases with this, and how pending / enabled are signals between the user and
1270 * kernel - check the documentation. Note that pending is more about messages.
1271 * The process needs to be in vcore_context, and the reason is usually a
1272 * message. We set pending here in case we were called to prod them into vcore
1273 * context (like via a sys_self_notify). Also note that this works for _S
1274 * procs, if you send to vcore 0 (and the proc is running). */
1275 void proc_notify(struct proc *p, uint32_t vcoreid)
1277 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1278 vcpd->notif_pending = TRUE;
1279 wrmb(); /* must write notif_pending before reading notif_disabled */
1280 if (!vcpd->notif_disabled) {
1281 /* GIANT WARNING: we aren't using the proc-lock to protect the
1282 * vcoremap. We want to be able to use this from interrupt context,
1283 * and don't want the proc_lock to be an irqsave. Spurious
1284 * __notify() kmsgs are okay (it checks to see if the right receiver
1286 if (vcore_is_mapped(p, vcoreid)) {
1287 printd("[kernel] sending notif to vcore %d\n", vcoreid);
1288 /* This use of try_get_pcoreid is racy, might be unmapped */
1289 send_kernel_message(try_get_pcoreid(p, vcoreid), __notify, (long)p,
1290 0, 0, KMSG_ROUTINE);
1295 /* Makes sure p is runnable. Callers may spam this, so it needs to handle
1296 * repeated calls for the same event. Callers include event delivery, SCP
1297 * yield, and new SCPs. Will trigger __sched_.cp_wakeup() CBs. Will only
1298 * trigger the CB once, regardless of how many times we are called, *until* the
1299 * proc becomes WAITING again, presumably because of something the ksched did.*/
1300 void proc_wakeup(struct proc *p)
1302 spin_lock(&p->proc_lock);
1303 if (__proc_is_mcp(p)) {
1304 /* we only wake up WAITING mcps */
1305 if (p->state != PROC_WAITING) {
1306 spin_unlock(&p->proc_lock);
1309 __proc_set_state(p, PROC_RUNNABLE_M);
1310 spin_unlock(&p->proc_lock);
1311 __sched_mcp_wakeup(p);
1314 /* SCPs can wake up for a variety of reasons. the only times we need
1315 * to do something is if it was waiting or just created. other cases
1316 * are either benign (just go out), or potential bugs (_Ms) */
1318 case (PROC_CREATED):
1319 case (PROC_WAITING):
1320 __proc_set_state(p, PROC_RUNNABLE_S);
1322 case (PROC_RUNNABLE_S):
1323 case (PROC_RUNNING_S):
1325 spin_unlock(&p->proc_lock);
1327 case (PROC_RUNNABLE_M):
1328 case (PROC_RUNNING_M):
1329 warn("Weird state(%s) in %s()", procstate2str(p->state),
1331 spin_unlock(&p->proc_lock);
1334 printd("[kernel] FYI, waking up an _S proc\n"); /* thanks, past brho! */
1335 spin_unlock(&p->proc_lock);
1336 __sched_scp_wakeup(p);
1340 /* Is the process in multi_mode / is an MCP or not? */
1341 bool __proc_is_mcp(struct proc *p)
1343 /* in lieu of using the amount of cores requested, or having a bunch of
1344 * states (like PROC_WAITING_M and _S), I'll just track it with a bool. */
1345 return p->procinfo->is_mcp;
1348 /************************ Preemption Functions ******************************
1349 * Don't rely on these much - I'll be sure to change them up a bit.
1351 * Careful about what takes a vcoreid and what takes a pcoreid. Also, there may
1352 * be weird glitches with setting the state to RUNNABLE_M. It is somewhat in
1353 * flux. The num_vcores is changed after take_cores, but some of the messages
1354 * (or local traps) may not yet be ready to handle seeing their future state.
1355 * But they should be, so fix those when they pop up.
1357 * Another thing to do would be to make the _core functions take a pcorelist,
1358 * and not just one pcoreid. */
1360 /* Sets a preempt_pending warning for p's vcore, to go off 'when'. If you care
1361 * about locking, do it before calling. Takes a vcoreid! */
1362 void __proc_preempt_warn(struct proc *p, uint32_t vcoreid, uint64_t when)
1364 struct event_msg local_msg = {0};
1365 /* danger with doing this unlocked: preempt_pending is set, but never 0'd,
1366 * since it is unmapped and not dealt with (TODO)*/
1367 p->procinfo->vcoremap[vcoreid].preempt_pending = when;
1369 /* Send the event (which internally checks to see how they want it) */
1370 local_msg.ev_type = EV_PREEMPT_PENDING;
1371 local_msg.ev_arg1 = vcoreid;
1372 /* Whenever we send msgs with the proc locked, we need at least 1 online.
1373 * Caller needs to make sure the core was online/mapped. */
1374 assert(!TAILQ_EMPTY(&p->online_vcs));
1375 send_kernel_event(p, &local_msg, vcoreid);
1377 /* TODO: consider putting in some lookup place for the alarm to find it.
1378 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1381 /* Warns all active vcores of an impending preemption. Hold the lock if you
1382 * care about the mapping (and you should). */
1383 void __proc_preempt_warnall(struct proc *p, uint64_t when)
1386 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1387 __proc_preempt_warn(p, vcore2vcoreid(p, vc_i), when);
1388 /* TODO: consider putting in some lookup place for the alarm to find it.
1389 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1392 // TODO: function to set an alarm, if none is outstanding
1394 /* Raw function to preempt a single core. If you care about locking, do it
1395 * before calling. */
1396 void __proc_preempt_core(struct proc *p, uint32_t pcoreid)
1398 uint32_t vcoreid = get_vcoreid(p, pcoreid);
1399 struct event_msg preempt_msg = {0};
1400 /* works with nr_preempts_done to signal completion of a preemption */
1401 p->procinfo->vcoremap[vcoreid].nr_preempts_sent++;
1402 // expects a pcorelist. assumes pcore is mapped and running_m
1403 __proc_take_corelist(p, &pcoreid, 1, TRUE);
1404 /* Only send the message if we have an online core. o/w, it would fuck
1405 * us up (deadlock), and hey don't need a message. the core we just took
1406 * will be the first one to be restarted. It will look like a notif. in
1407 * the future, we could send the event if we want, but the caller needs to
1408 * do that (after unlocking). */
1409 if (!TAILQ_EMPTY(&p->online_vcs)) {
1410 preempt_msg.ev_type = EV_VCORE_PREEMPT;
1411 preempt_msg.ev_arg2 = vcoreid;
1412 send_kernel_event(p, &preempt_msg, 0);
1416 /* Raw function to preempt every vcore. If you care about locking, do it before
1418 uint32_t __proc_preempt_all(struct proc *p, uint32_t *pc_arr)
1421 /* TODO:(BULK) PREEMPT - don't bother with this, set a proc wide flag, or
1422 * just make us RUNNABLE_M. Note this is also used by __map_vcore. */
1423 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1424 vc_i->nr_preempts_sent++;
1425 return __proc_take_allcores(p, pc_arr, TRUE);
1428 /* Warns and preempts a vcore from p. No delaying / alarming, or anything. The
1429 * warning will be for u usec from now. Returns TRUE if the core belonged to
1430 * the proc (and thus preempted), False if the proc no longer has the core. */
1431 bool proc_preempt_core(struct proc *p, uint32_t pcoreid, uint64_t usec)
1433 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1434 bool retval = FALSE;
1435 if (p->state != PROC_RUNNING_M) {
1436 /* more of an FYI for brho. should be harmless to just return. */
1437 warn("Tried to preempt from a non RUNNING_M proc!");
1440 spin_lock(&p->proc_lock);
1441 if (is_mapped_vcore(p, pcoreid)) {
1442 __proc_preempt_warn(p, get_vcoreid(p, pcoreid), warn_time);
1443 __proc_preempt_core(p, pcoreid);
1444 /* we might have taken the last core */
1445 if (!p->procinfo->num_vcores)
1446 __proc_set_state(p, PROC_RUNNABLE_M);
1449 spin_unlock(&p->proc_lock);
1453 /* Warns and preempts all from p. No delaying / alarming, or anything. The
1454 * warning will be for u usec from now. */
1455 void proc_preempt_all(struct proc *p, uint64_t usec)
1457 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1458 uint32_t num_revoked = 0;
1459 spin_lock(&p->proc_lock);
1460 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
1461 uint32_t pc_arr[p->procinfo->num_vcores];
1462 /* DYING could be okay */
1463 if (p->state != PROC_RUNNING_M) {
1464 warn("Tried to preempt from a non RUNNING_M proc!");
1465 spin_unlock(&p->proc_lock);
1468 __proc_preempt_warnall(p, warn_time);
1469 num_revoked = __proc_preempt_all(p, pc_arr);
1470 assert(!p->procinfo->num_vcores);
1471 __proc_set_state(p, PROC_RUNNABLE_M);
1472 spin_unlock(&p->proc_lock);
1473 /* TODO: when we revise this func, look at __put_idle */
1474 /* Return the cores to the ksched */
1476 __sched_put_idle_cores(p, pc_arr, num_revoked);
1479 /* Give the specific pcore to proc p. Lots of assumptions, so don't really use
1480 * this. The proc needs to be _M and prepared for it. the pcore needs to be
1482 void proc_give(struct proc *p, uint32_t pcoreid)
1484 warn("Your idlecoremap is now screwed up"); /* TODO (IDLE) */
1485 spin_lock(&p->proc_lock);
1486 // expects a pcorelist, we give it a list of one
1487 __proc_give_cores(p, &pcoreid, 1);
1488 spin_unlock(&p->proc_lock);
1491 /* Global version of the helper, for sys_get_vcoreid (might phase that syscall
1493 uint32_t proc_get_vcoreid(struct proc *p)
1495 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1496 if (pcpui->owning_proc == p) {
1497 return pcpui->owning_vcoreid;
1499 warn("Asked for vcoreid for %p, but %p is pwns", p, pcpui->owning_proc);
1500 return (uint32_t)-1;
1504 /* TODO: make all of these static inlines when we gut the env crap */
1505 bool vcore_is_mapped(struct proc *p, uint32_t vcoreid)
1507 return p->procinfo->vcoremap[vcoreid].valid;
1510 /* Can do this, or just create a new field and save it in the vcoremap */
1511 uint32_t vcore2vcoreid(struct proc *p, struct vcore *vc)
1513 return (vc - p->procinfo->vcoremap);
1516 struct vcore *vcoreid2vcore(struct proc *p, uint32_t vcoreid)
1518 return &p->procinfo->vcoremap[vcoreid];
1521 /********** Core granting (bulk and single) ***********/
1523 /* Helper: gives pcore to the process, mapping it to the next available vcore
1524 * from list vc_list. Returns TRUE if we succeeded (non-empty). If you pass in
1525 * **vc, we'll tell you which vcore it was. */
1526 static bool __proc_give_a_pcore(struct proc *p, uint32_t pcore,
1527 struct vcore_tailq *vc_list, struct vcore **vc)
1529 struct vcore *new_vc;
1530 new_vc = TAILQ_FIRST(vc_list);
1533 printd("setting vcore %d to pcore %d\n", vcore2vcoreid(p, new_vc),
1535 TAILQ_REMOVE(vc_list, new_vc, list);
1536 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1537 __map_vcore(p, vcore2vcoreid(p, new_vc), pcore);
1543 static void __proc_give_cores_runnable(struct proc *p, uint32_t *pc_arr,
1546 assert(p->state == PROC_RUNNABLE_M);
1547 assert(num); /* catch bugs */
1548 /* add new items to the vcoremap */
1549 __seq_start_write(&p->procinfo->coremap_seqctr);/* unncessary if offline */
1550 p->procinfo->num_vcores += num;
1551 for (int i = 0; i < num; i++) {
1552 /* Try from the bulk list first */
1553 if (__proc_give_a_pcore(p, pc_arr[i], &p->bulk_preempted_vcs, 0))
1555 /* o/w, try from the inactive list. at one point, i thought there might
1556 * be a legit way in which the inactive list could be empty, but that i
1557 * wanted to catch it via an assert. */
1558 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, 0));
1560 __seq_end_write(&p->procinfo->coremap_seqctr);
1563 static void __proc_give_cores_running(struct proc *p, uint32_t *pc_arr,
1567 /* Up the refcnt, since num cores are going to start using this
1568 * process and have it loaded in their owning_proc and 'current'. */
1569 proc_incref(p, num * 2); /* keep in sync with __startcore */
1570 __seq_start_write(&p->procinfo->coremap_seqctr);
1571 p->procinfo->num_vcores += num;
1572 assert(TAILQ_EMPTY(&p->bulk_preempted_vcs));
1573 for (int i = 0; i < num; i++) {
1574 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, &vc_i));
1575 send_kernel_message(pc_arr[i], __startcore, (long)p,
1576 (long)vcore2vcoreid(p, vc_i),
1577 (long)vc_i->nr_preempts_sent, KMSG_ROUTINE);
1579 __seq_end_write(&p->procinfo->coremap_seqctr);
1582 /* Gives process p the additional num cores listed in pcorelist. If the proc is
1583 * not RUNNABLE_M or RUNNING_M, this will fail and allocate none of the core
1584 * (and return -1). If you're RUNNING_M, this will startup your new cores at
1585 * the entry point with their virtual IDs (or restore a preemption). If you're
1586 * RUNNABLE_M, you should call __proc_run_m after this so that the process can
1587 * start to use its cores. In either case, this returns 0.
1589 * If you're *_S, make sure your core0's TF is set (which is done when coming in
1590 * via arch/trap.c and we are RUNNING_S), change your state, then call this.
1591 * Then call __proc_run_m().
1593 * The reason I didn't bring the _S cases from core_request over here is so we
1594 * can keep this family of calls dealing with only *_Ms, to avoiding caring if
1595 * this is called from another core, and to avoid the _S -> _M transition.
1597 * WARNING: You must hold the proc_lock before calling this! */
1598 int __proc_give_cores(struct proc *p, uint32_t *pc_arr, uint32_t num)
1600 /* should never happen: */
1601 assert(num + p->procinfo->num_vcores <= MAX_NUM_CPUS);
1603 case (PROC_RUNNABLE_S):
1604 case (PROC_RUNNING_S):
1605 warn("Don't give cores to a process in a *_S state!\n");
1608 case (PROC_WAITING):
1609 /* can't accept, just fail */
1611 case (PROC_RUNNABLE_M):
1612 __proc_give_cores_runnable(p, pc_arr, num);
1614 case (PROC_RUNNING_M):
1615 __proc_give_cores_running(p, pc_arr, num);
1618 panic("Weird state(%s) in %s()", procstate2str(p->state),
1621 /* TODO: considering moving to the ksched (hard, due to yield) */
1622 p->procinfo->res_grant[RES_CORES] += num;
1626 /********** Core revocation (bulk and single) ***********/
1628 /* Revokes a single vcore from a process (unmaps or sends a KMSG to unmap). */
1629 static void __proc_revoke_core(struct proc *p, uint32_t vcoreid, bool preempt)
1631 uint32_t pcoreid = get_pcoreid(p, vcoreid);
1632 struct preempt_data *vcpd;
1634 /* Lock the vcore's state (necessary for preemption recovery) */
1635 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1636 atomic_or(&vcpd->flags, VC_K_LOCK);
1637 send_kernel_message(pcoreid, __preempt, (long)p, 0, 0, KMSG_ROUTINE);
1639 send_kernel_message(pcoreid, __death, 0, 0, 0, KMSG_ROUTINE);
1643 /* Revokes all cores from the process (unmaps or sends a KMSGS). */
1644 static void __proc_revoke_allcores(struct proc *p, bool preempt)
1647 /* TODO: if we ever get broadcast messaging, use it here (still need to lock
1648 * the vcores' states for preemption) */
1649 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1650 __proc_revoke_core(p, vcore2vcoreid(p, vc_i), preempt);
1653 /* Might be faster to scan the vcoremap than to walk the list... */
1654 static void __proc_unmap_allcores(struct proc *p)
1657 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1658 __unmap_vcore(p, vcore2vcoreid(p, vc_i));
1661 /* Takes (revoke via kmsg or unmap) from process p the num cores listed in
1662 * pc_arr. Will preempt if 'preempt' is set. o/w, no state will be saved, etc.
1663 * Don't use this for taking all of a process's cores.
1665 * Make sure you hold the lock when you call this, and make sure that the pcore
1666 * actually belongs to the proc, non-trivial due to other __preempt messages. */
1667 void __proc_take_corelist(struct proc *p, uint32_t *pc_arr, uint32_t num,
1672 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1673 __seq_start_write(&p->procinfo->coremap_seqctr);
1674 for (int i = 0; i < num; i++) {
1675 vcoreid = get_vcoreid(p, pc_arr[i]);
1677 assert(pc_arr[i] == get_pcoreid(p, vcoreid));
1678 /* Revoke / unmap core */
1679 if (p->state == PROC_RUNNING_M)
1680 __proc_revoke_core(p, vcoreid, preempt);
1681 __unmap_vcore(p, vcoreid);
1682 /* Change lists for the vcore. Note, the vcore is already unmapped
1683 * and/or the messages are already in flight. The only code that looks
1684 * at the lists without holding the lock is event code. */
1685 vc = vcoreid2vcore(p, vcoreid);
1686 TAILQ_REMOVE(&p->online_vcs, vc, list);
1687 /* even for single preempts, we use the inactive list. bulk preempt is
1688 * only used for when we take everything. */
1689 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1691 p->procinfo->num_vcores -= num;
1692 __seq_end_write(&p->procinfo->coremap_seqctr);
1693 p->procinfo->res_grant[RES_CORES] -= num;
1696 /* Takes all cores from a process (revoke via kmsg or unmap), putting them on
1697 * the appropriate vcore list, and fills pc_arr with the pcores revoked, and
1698 * returns the number of entries in pc_arr.
1700 * Make sure pc_arr is big enough to handle num_vcores().
1701 * Make sure you hold the lock when you call this. */
1702 uint32_t __proc_take_allcores(struct proc *p, uint32_t *pc_arr, bool preempt)
1704 struct vcore *vc_i, *vc_temp;
1706 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1707 __seq_start_write(&p->procinfo->coremap_seqctr);
1708 /* Write out which pcores we're going to take */
1709 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1710 pc_arr[num++] = vc_i->pcoreid;
1711 /* Revoke if they are running, and unmap. Both of these need the online
1712 * list to not be changed yet. */
1713 if (p->state == PROC_RUNNING_M)
1714 __proc_revoke_allcores(p, preempt);
1715 __proc_unmap_allcores(p);
1716 /* Move the vcores from online to the head of the appropriate list */
1717 TAILQ_FOREACH_SAFE(vc_i, &p->online_vcs, list, vc_temp) {
1718 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that */
1719 TAILQ_REMOVE(&p->online_vcs, vc_i, list);
1720 /* Put the cores on the appropriate list */
1722 TAILQ_INSERT_HEAD(&p->bulk_preempted_vcs, vc_i, list);
1724 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
1726 assert(TAILQ_EMPTY(&p->online_vcs));
1727 assert(num == p->procinfo->num_vcores);
1728 p->procinfo->num_vcores = 0;
1729 __seq_end_write(&p->procinfo->coremap_seqctr);
1730 p->procinfo->res_grant[RES_CORES] = 0;
1734 /* Helper to do the vcore->pcore and inverse mapping. Hold the lock when
1736 void __map_vcore(struct proc *p, uint32_t vcoreid, uint32_t pcoreid)
1738 p->procinfo->vcoremap[vcoreid].pcoreid = pcoreid;
1739 p->procinfo->vcoremap[vcoreid].valid = TRUE;
1740 p->procinfo->pcoremap[pcoreid].vcoreid = vcoreid;
1741 p->procinfo->pcoremap[pcoreid].valid = TRUE;
1744 /* Helper to unmap the vcore->pcore and inverse mapping. Hold the lock when
1746 void __unmap_vcore(struct proc *p, uint32_t vcoreid)
1748 p->procinfo->pcoremap[p->procinfo->vcoremap[vcoreid].pcoreid].valid = FALSE;
1749 p->procinfo->vcoremap[vcoreid].valid = FALSE;
1752 /* Stop running whatever context is on this core and load a known-good cr3.
1753 * Note this leaves no trace of what was running. This "leaves the process's
1756 * This does not clear the owning proc. Use the other helper for that. */
1757 void abandon_core(void)
1759 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1760 /* Syscalls that don't return will ultimately call abadon_core(), so we need
1761 * to make sure we don't think we are still working on a syscall. */
1762 pcpui->cur_kthread->sysc = 0;
1763 pcpui->cur_kthread->errbuf = 0; /* just in case */
1764 if (pcpui->cur_proc)
1768 /* Helper to clear the core's owning processor and manage refcnting. Pass in
1769 * core_id() to save a couple core_id() calls. */
1770 void clear_owning_proc(uint32_t coreid)
1772 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1773 struct proc *p = pcpui->owning_proc;
1774 pcpui->owning_proc = 0;
1775 pcpui->owning_vcoreid = 0xdeadbeef;
1776 pcpui->cur_ctx = 0; /* catch bugs for now (may go away) */
1781 /* Switches to the address space/context of new_p, doing nothing if we are
1782 * already in new_p. This won't add extra refcnts or anything, and needs to be
1783 * paired with switch_back() at the end of whatever function you are in. Don't
1784 * migrate cores in the middle of a pair. Specifically, the uncounted refs are
1785 * one for the old_proc, which is passed back to the caller, and new_p is
1786 * getting placed in cur_proc. */
1787 struct proc *switch_to(struct proc *new_p)
1789 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1790 struct proc *old_proc;
1791 old_proc = pcpui->cur_proc; /* uncounted ref */
1792 /* If we aren't the proc already, then switch to it */
1793 if (old_proc != new_p) {
1794 pcpui->cur_proc = new_p; /* uncounted ref */
1796 lcr3(new_p->env_cr3);
1803 /* This switches back to old_proc from new_p. Pair it with switch_to(), and
1804 * pass in its return value for old_proc. */
1805 void switch_back(struct proc *new_p, struct proc *old_proc)
1807 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1808 if (old_proc != new_p) {
1809 pcpui->cur_proc = old_proc;
1811 lcr3(old_proc->env_cr3);
1817 /* Will send a TLB shootdown message to every vcore in the main address space
1818 * (aka, all vcores for now). The message will take the start and end virtual
1819 * addresses as well, in case we want to be more clever about how much we
1820 * shootdown and batching our messages. Should do the sanity about rounding up
1821 * and down in this function too.
1823 * Would be nice to have a broadcast kmsg at this point. Note this may send a
1824 * message to the calling core (interrupting it, possibly while holding the
1825 * proc_lock). We don't need to process routine messages since it's an
1826 * immediate message. */
1827 void proc_tlbshootdown(struct proc *p, uintptr_t start, uintptr_t end)
1829 /* TODO: need a better way to find cores running our address space. we can
1830 * have kthreads running syscalls, async calls, processes being created. */
1832 /* TODO: we might be able to avoid locking here in the future (we must hit
1833 * all online, and we can check __mapped). it'll be complicated. */
1834 spin_lock(&p->proc_lock);
1836 case (PROC_RUNNING_S):
1839 case (PROC_RUNNING_M):
1840 /* TODO: (TLB) sanity checks and rounding on the ranges */
1841 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
1842 send_kernel_message(vc_i->pcoreid, __tlbshootdown, start, end,
1847 /* TODO: til we fix shootdowns, there are some odd cases where we
1848 * have the address space loaded, but the state is in transition. */
1852 spin_unlock(&p->proc_lock);
1855 /* Helper, used by __startcore and __set_curctx, which sets up cur_ctx to run a
1856 * given process's vcore. Caller needs to set up things like owning_proc and
1857 * whatnot. Note that we might not have p loaded as current. */
1858 static void __set_curctx_to_vcoreid(struct proc *p, uint32_t vcoreid,
1859 uint32_t old_nr_preempts_sent)
1861 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1862 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1863 struct vcore *vc = vcoreid2vcore(p, vcoreid);
1864 /* Spin until our vcore's old preemption is done. When __SC was sent, we
1865 * were told what the nr_preempts_sent was at that time. Once that many are
1866 * done, it is time for us to run. This forces a 'happens-before' ordering
1867 * on a __PR of our VC before this __SC of the VC. Note the nr_done should
1868 * not exceed old_nr_sent, since further __PR are behind this __SC in the
1870 while (old_nr_preempts_sent != vc->nr_preempts_done)
1872 cmb(); /* read nr_done before any other rd or wr. CPU mb in the atomic. */
1873 /* Mark that this vcore as no longer preempted. No danger of clobbering
1874 * other writes, since this would get turned on in __preempt (which can't be
1875 * concurrent with this function on this core), and the atomic is just
1876 * toggling the one bit (a concurrent VC_K_LOCK will work) */
1877 atomic_and(&vcpd->flags, ~VC_PREEMPTED);
1878 /* Once the VC is no longer preempted, we allow it to receive msgs. We
1879 * could let userspace do it, but handling it here makes it easier for them
1880 * to handle_indirs (when they turn this flag off). Note the atomics
1881 * provide the needed barriers (cmb and mb on flags). */
1882 atomic_or(&vcpd->flags, VC_CAN_RCV_MSG);
1883 printd("[kernel] startcore on physical core %d for process %d's vcore %d\n",
1884 core_id(), p->pid, vcoreid);
1885 /* If notifs are disabled, the vcore was in vcore context and we need to
1886 * restart the vcore_ctx. o/w, we give them a fresh vcore (which is also
1887 * what happens the first time a vcore comes online). No matter what,
1888 * they'll restart in vcore context. It's just a matter of whether or not
1889 * it is the old, interrupted vcore context. */
1890 if (vcpd->notif_disabled) {
1891 /* copy-in the tf we'll pop, then set all security-related fields */
1892 pcpui->actual_ctx = vcpd->vcore_ctx;
1893 proc_secure_ctx(&pcpui->actual_ctx);
1894 } else { /* not restarting from a preemption, use a fresh vcore */
1895 assert(vcpd->transition_stack);
1896 proc_init_ctx(&pcpui->actual_ctx, vcoreid, p->env_entry,
1897 vcpd->transition_stack, vcpd->vcore_tls_desc);
1898 /* Disable/mask active notifications for fresh vcores */
1899 vcpd->notif_disabled = TRUE;
1901 /* Regardless of whether or not we have a 'fresh' VC, we need to restore the
1902 * FPU state for the VC according to VCPD (which means either a saved FPU
1903 * state or a brand new init). Starting a fresh VC is just referring to the
1904 * GP context we run. The vcore itself needs to have the FPU state loaded
1905 * from when it previously ran and was saved (or a fresh FPU if it wasn't
1906 * saved). For fresh FPUs, the main purpose is for limiting info leakage.
1907 * I think VCs that don't need FPU state for some reason (like having a
1908 * current_uthread) can handle any sort of FPU state, since it gets sorted
1909 * when they pop their next uthread.
1911 * Note this can cause a GP fault on x86 if the state is corrupt. In lieu
1912 * of reading in the huge FP state and mucking with mxcsr_mask, we should
1913 * handle this like a KPF on user code. */
1914 restore_vc_fp_state(vcpd);
1915 /* cur_ctx was built above (in actual_ctx), now use it */
1916 pcpui->cur_ctx = &pcpui->actual_ctx;
1917 /* this cur_ctx will get run when the kernel returns / idles */
1918 vcore_account_online(p, vcoreid);
1921 /* Changes calling vcore to be vcoreid. enable_my_notif tells us about how the
1922 * state calling vcore wants to be left in. It will look like caller_vcoreid
1923 * was preempted. Note we don't care about notif_pending.
1926 * 0 if we successfully changed to the target vcore.
1927 * -EBUSY if the target vcore is already mapped (a good kind of failure)
1928 * -EAGAIN if we failed for some other reason and need to try again. For
1929 * example, the caller could be preempted, and we never even attempted to
1931 * -EINVAL some userspace bug */
1932 int proc_change_to_vcore(struct proc *p, uint32_t new_vcoreid,
1933 bool enable_my_notif)
1935 uint32_t caller_vcoreid, pcoreid = core_id();
1936 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1937 struct preempt_data *caller_vcpd;
1938 struct vcore *caller_vc, *new_vc;
1939 struct event_msg preempt_msg = {0};
1940 int retval = -EAGAIN; /* by default, try again */
1941 /* Need to not reach outside the vcoremap, which might be smaller in the
1942 * future, but should always be as big as max_vcores */
1943 if (new_vcoreid >= p->procinfo->max_vcores)
1945 /* Need to lock to prevent concurrent vcore changes, like in yield. */
1946 spin_lock(&p->proc_lock);
1947 /* new_vcoreid is already runing, abort */
1948 if (vcore_is_mapped(p, new_vcoreid)) {
1952 /* Need to make sure our vcore is allowed to switch. We might have a
1953 * __preempt, __death, etc, coming in. Similar to yield. */
1955 case (PROC_RUNNING_M):
1956 break; /* the only case we can proceed */
1957 case (PROC_RUNNING_S): /* user bug, just return */
1958 case (PROC_DYING): /* incoming __death */
1959 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1962 panic("Weird state(%s) in %s()", procstate2str(p->state),
1965 /* This is which vcore this pcore thinks it is, regardless of any unmappings
1966 * that may have happened remotely (with __PRs waiting to run) */
1967 caller_vcoreid = pcpui->owning_vcoreid;
1968 caller_vc = vcoreid2vcore(p, caller_vcoreid);
1969 caller_vcpd = &p->procdata->vcore_preempt_data[caller_vcoreid];
1970 /* This is how we detect whether or not a __PR happened. If it did, just
1971 * abort and handle the kmsg. No new __PRs are coming since we hold the
1972 * lock. This also detects a __PR followed by a __SC for the same VC. */
1973 if (caller_vc->nr_preempts_sent != caller_vc->nr_preempts_done)
1975 /* Sanity checks. If we were preempted or are dying, we should have noticed
1977 assert(is_mapped_vcore(p, pcoreid));
1978 assert(caller_vcoreid == get_vcoreid(p, pcoreid));
1979 /* Should only call from vcore context */
1980 if (!caller_vcpd->notif_disabled) {
1982 printk("[kernel] You tried to change vcores from uthread ctx\n");
1985 /* Ok, we're clear to do the switch. Lets figure out who the new one is */
1986 new_vc = vcoreid2vcore(p, new_vcoreid);
1987 printd("[kernel] changing vcore %d to vcore %d\n", caller_vcoreid,
1989 /* enable_my_notif signals how we'll be restarted */
1990 if (enable_my_notif) {
1991 /* if they set this flag, then the vcore can just restart from scratch,
1992 * and we don't care about either the uthread_ctx or the vcore_ctx. */
1993 caller_vcpd->notif_disabled = FALSE;
1994 /* Don't need to save the FPU. There should be no uthread or other
1995 * reason to return to the FPU state. */
1997 /* need to set up the calling vcore's ctx so that it'll get restarted by
1998 * __startcore, to make the caller look like it was preempted. */
1999 caller_vcpd->vcore_ctx = *current_ctx;
2000 save_vc_fp_state(caller_vcpd);
2002 /* Mark our core as preempted (for userspace recovery). Userspace checks
2003 * this in handle_indirs, and it needs to check the mbox regardless of
2004 * enable_my_notif. This does mean cores that change-to with no intent to
2005 * return will be tracked as PREEMPTED until they start back up (maybe
2007 atomic_or(&caller_vcpd->flags, VC_PREEMPTED);
2008 /* Either way, unmap and offline our current vcore */
2009 /* Move the caller from online to inactive */
2010 TAILQ_REMOVE(&p->online_vcs, caller_vc, list);
2011 /* We don't bother with the notif_pending race. note that notif_pending
2012 * could still be set. this was a preempted vcore, and userspace will need
2013 * to deal with missed messages (preempt_recover() will handle that) */
2014 TAILQ_INSERT_HEAD(&p->inactive_vcs, caller_vc, list);
2015 /* Move the new one from inactive to online */
2016 TAILQ_REMOVE(&p->inactive_vcs, new_vc, list);
2017 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
2018 /* Change the vcore map */
2019 __seq_start_write(&p->procinfo->coremap_seqctr);
2020 __unmap_vcore(p, caller_vcoreid);
2021 __map_vcore(p, new_vcoreid, pcoreid);
2022 __seq_end_write(&p->procinfo->coremap_seqctr);
2023 vcore_account_offline(p, caller_vcoreid);
2024 /* Send either a PREEMPT msg or a CHECK_MSGS msg. If they said to
2025 * enable_my_notif, then all userspace needs is to check messages, not a
2026 * full preemption recovery. */
2027 preempt_msg.ev_type = (enable_my_notif ? EV_CHECK_MSGS : EV_VCORE_PREEMPT);
2028 preempt_msg.ev_arg2 = caller_vcoreid; /* arg2 is 32 bits */
2029 /* Whenever we send msgs with the proc locked, we need at least 1 online.
2030 * In this case, it's the one we just changed to. */
2031 assert(!TAILQ_EMPTY(&p->online_vcs));
2032 send_kernel_event(p, &preempt_msg, new_vcoreid);
2033 /* So this core knows which vcore is here. (cur_proc and owning_proc are
2034 * already correct): */
2035 pcpui->owning_vcoreid = new_vcoreid;
2036 /* Until we set_curctx, we don't really have a valid current tf. The stuff
2037 * in that old one is from our previous vcore, not the current
2038 * owning_vcoreid. This matters for other KMSGS that will run before
2039 * __set_curctx (like __notify). */
2041 /* Need to send a kmsg to finish. We can't set_curctx til the __PR is done,
2042 * but we can't spin right here while holding the lock (can't spin while
2043 * waiting on a message, roughly) */
2044 send_kernel_message(pcoreid, __set_curctx, (long)p, (long)new_vcoreid,
2045 (long)new_vc->nr_preempts_sent, KMSG_ROUTINE);
2047 /* Fall through to exit */
2049 spin_unlock(&p->proc_lock);
2053 /* Kernel message handler to start a process's context on this core, when the
2054 * core next considers running a process. Tightly coupled with __proc_run_m().
2055 * Interrupts are disabled. */
2056 void __startcore(uint32_t srcid, long a0, long a1, long a2)
2058 uint32_t vcoreid = (uint32_t)a1;
2059 uint32_t coreid = core_id();
2060 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2061 struct proc *p_to_run = (struct proc *CT(1))a0;
2062 uint32_t old_nr_preempts_sent = (uint32_t)a2;
2065 /* Can not be any TF from a process here already */
2066 assert(!pcpui->owning_proc);
2067 /* the sender of the kmsg increfed already for this saved ref to p_to_run */
2068 pcpui->owning_proc = p_to_run;
2069 pcpui->owning_vcoreid = vcoreid;
2070 /* sender increfed again, assuming we'd install to cur_proc. only do this
2071 * if no one else is there. this is an optimization, since we expect to
2072 * send these __startcores to idles cores, and this saves a scramble to
2073 * incref when all of the cores restartcore/startcore later. Keep in sync
2074 * with __proc_give_cores() and __proc_run_m(). */
2075 if (!pcpui->cur_proc) {
2076 pcpui->cur_proc = p_to_run; /* install the ref to cur_proc */
2077 lcr3(p_to_run->env_cr3); /* load the page tables to match cur_proc */
2079 proc_decref(p_to_run); /* can't install, decref the extra one */
2081 /* Note we are not necessarily in the cr3 of p_to_run */
2082 /* Now that we sorted refcnts and know p / which vcore it should be, set up
2083 * pcpui->cur_ctx so that it will run that particular vcore */
2084 __set_curctx_to_vcoreid(p_to_run, vcoreid, old_nr_preempts_sent);
2087 /* Kernel message handler to load a proc's vcore context on this core. Similar
2088 * to __startcore, except it is used when p already controls the core (e.g.
2089 * change_to). Since the core is already controlled, pcpui such as owning proc,
2090 * vcoreid, and cur_proc are all already set. */
2091 void __set_curctx(uint32_t srcid, long a0, long a1, long a2)
2093 struct proc *p = (struct proc*)a0;
2094 uint32_t vcoreid = (uint32_t)a1;
2095 uint32_t old_nr_preempts_sent = (uint32_t)a2;
2096 __set_curctx_to_vcoreid(p, vcoreid, old_nr_preempts_sent);
2099 /* Bail out if it's the wrong process, or if they no longer want a notif. Try
2100 * not to grab locks or write access to anything that isn't per-core in here. */
2101 void __notify(uint32_t srcid, long a0, long a1, long a2)
2103 uint32_t vcoreid, coreid = core_id();
2104 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2105 struct preempt_data *vcpd;
2106 struct proc *p = (struct proc*)a0;
2108 /* Not the right proc */
2109 if (p != pcpui->owning_proc)
2111 /* the core might be owned, but not have a valid cur_ctx (if we're in the
2112 * process of changing */
2113 if (!pcpui->cur_ctx)
2115 /* Common cur_ctx sanity checks. Note cur_ctx could be an _S's scp_ctx */
2116 vcoreid = pcpui->owning_vcoreid;
2117 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
2118 /* for SCPs that haven't (and might never) call vc_event_init, like rtld.
2119 * this is harmless for MCPS to check this */
2120 if (!scp_is_vcctx_ready(vcpd))
2122 printd("received active notification for proc %d's vcore %d on pcore %d\n",
2123 p->procinfo->pid, vcoreid, coreid);
2124 /* sort signals. notifs are now masked, like an interrupt gate */
2125 if (vcpd->notif_disabled)
2127 vcpd->notif_disabled = TRUE;
2128 /* save the old ctx in the uthread slot, build and pop a new one. Note that
2129 * silly state isn't our business for a notification. */
2130 vcpd->uthread_ctx = *pcpui->cur_ctx;
2131 memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
2132 proc_init_ctx(pcpui->cur_ctx, vcoreid, p->env_entry,
2133 vcpd->transition_stack, vcpd->vcore_tls_desc);
2134 /* this cur_ctx will get run when the kernel returns / idles */
2137 void __preempt(uint32_t srcid, long a0, long a1, long a2)
2139 uint32_t vcoreid, coreid = core_id();
2140 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2141 struct preempt_data *vcpd;
2142 struct proc *p = (struct proc*)a0;
2145 if (p != pcpui->owning_proc) {
2146 panic("__preempt arrived for a process (%p) that was not owning (%p)!",
2147 p, pcpui->owning_proc);
2149 /* Common cur_ctx sanity checks */
2150 assert(pcpui->cur_ctx);
2151 assert(pcpui->cur_ctx == &pcpui->actual_ctx);
2152 vcoreid = pcpui->owning_vcoreid;
2153 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
2154 printd("[kernel] received __preempt for proc %d's vcore %d on pcore %d\n",
2155 p->procinfo->pid, vcoreid, coreid);
2156 /* if notifs are disabled, the vcore is in vcore context (as far as we're
2157 * concerned), and we save it in the vcore slot. o/w, we save the process's
2158 * cur_ctx in the uthread slot, and it'll appear to the vcore when it comes
2159 * back up the uthread just took a notification. */
2160 if (vcpd->notif_disabled)
2161 vcpd->vcore_ctx = *pcpui->cur_ctx;
2163 vcpd->uthread_ctx = *pcpui->cur_ctx;
2164 /* Userspace in a preemption handler on another core might be copying FP
2165 * state from memory (VCPD) at the moment, and if so we don't want to
2166 * clobber it. In this rare case, our current core's FPU state should be
2167 * the same as whatever is in VCPD, so this shouldn't be necessary, but the
2168 * arch-specific save function might do something other than write out
2169 * bit-for-bit the exact same data. Checking STEALING suffices, since we
2170 * hold the K_LOCK (preventing userspace from starting a fresh STEALING
2171 * phase concurrently). */
2172 if (!(atomic_read(&vcpd->flags) & VC_UTHREAD_STEALING))
2173 save_vc_fp_state(vcpd);
2174 /* Mark the vcore as preempted and unlock (was locked by the sender). */
2175 atomic_or(&vcpd->flags, VC_PREEMPTED);
2176 atomic_and(&vcpd->flags, ~VC_K_LOCK);
2177 /* either __preempt or proc_yield() ends the preempt phase. */
2178 p->procinfo->vcoremap[vcoreid].preempt_pending = 0;
2179 vcore_account_offline(p, vcoreid);
2180 wmb(); /* make sure everything else hits before we finish the preempt */
2181 /* up the nr_done, which signals the next __startcore for this vc */
2182 p->procinfo->vcoremap[vcoreid].nr_preempts_done++;
2183 /* We won't restart the process later. current gets cleared later when we
2184 * notice there is no owning_proc and we have nothing to do (smp_idle,
2185 * restartcore, etc) */
2186 clear_owning_proc(coreid);
2189 /* Kernel message handler to clean up the core when a process is dying.
2190 * Note this leaves no trace of what was running.
2191 * It's okay if death comes to a core that's already idling and has no current.
2192 * It could happen if a process decref'd before __proc_startcore could incref. */
2193 void __death(uint32_t srcid, long a0, long a1, long a2)
2195 uint32_t vcoreid, coreid = core_id();
2196 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2197 struct proc *p = pcpui->owning_proc;
2199 vcoreid = pcpui->owning_vcoreid;
2200 printd("[kernel] death on physical core %d for process %d's vcore %d\n",
2201 coreid, p->pid, vcoreid);
2202 vcore_account_offline(p, vcoreid); /* in case anyone is counting */
2203 /* We won't restart the process later. current gets cleared later when
2204 * we notice there is no owning_proc and we have nothing to do
2205 * (smp_idle, restartcore, etc) */
2206 clear_owning_proc(coreid);
2210 /* Kernel message handler, usually sent IMMEDIATE, to shoot down virtual
2211 * addresses from a0 to a1. */
2212 void __tlbshootdown(uint32_t srcid, long a0, long a1, long a2)
2214 /* TODO: (TLB) something more intelligent with the range */
2218 void print_allpids(void)
2220 void print_proc_state(void *item)
2222 struct proc *p = (struct proc*)item;
2224 /* this actually adds an extra space, since no progname is ever
2225 * PROGNAME_SZ bytes, due to the \0 counted in PROGNAME. */
2226 printk("%8d %-*s %-10s %6d\n", p->pid, PROC_PROGNAME_SZ, p->progname,
2227 procstate2str(p->state), p->ppid);
2229 char dashes[PROC_PROGNAME_SZ];
2230 memset(dashes, '-', PROC_PROGNAME_SZ);
2231 dashes[PROC_PROGNAME_SZ - 1] = '\0';
2232 /* -5, for 'Name ' */
2233 printk(" PID Name %-*s State Parent \n",
2234 PROC_PROGNAME_SZ - 5, "");
2235 printk("------------------------------%s\n", dashes);
2236 spin_lock(&pid_hash_lock);
2237 hash_for_each(pid_hash, print_proc_state);
2238 spin_unlock(&pid_hash_lock);
2241 void print_proc_info(pid_t pid)
2244 uint64_t total_time = 0;
2245 struct proc *child, *p = pid2proc(pid);
2248 printk("Bad PID.\n");
2251 spinlock_debug(&p->proc_lock);
2252 //spin_lock(&p->proc_lock); // No locking!!
2253 printk("struct proc: %p\n", p);
2254 printk("Program name: %s\n", p->progname);
2255 printk("PID: %d\n", p->pid);
2256 printk("PPID: %d\n", p->ppid);
2257 printk("State: %s (%p)\n", procstate2str(p->state), p->state);
2258 printk("\tIs %san MCP\n", p->procinfo->is_mcp ? "" : "not ");
2259 printk("Refcnt: %d\n", atomic_read(&p->p_kref.refcount) - 1);
2260 printk("Flags: 0x%08x\n", p->env_flags);
2261 printk("CR3(phys): %p\n", p->env_cr3);
2262 printk("Num Vcores: %d\n", p->procinfo->num_vcores);
2263 printk("Vcore Lists (may be in flux w/o locking):\n----------------------\n");
2264 printk("Online:\n");
2265 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
2266 printk("\tVcore %d -> Pcore %d\n", vcore2vcoreid(p, vc_i), vc_i->pcoreid);
2267 printk("Bulk Preempted:\n");
2268 TAILQ_FOREACH(vc_i, &p->bulk_preempted_vcs, list)
2269 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2270 printk("Inactive / Yielded:\n");
2271 TAILQ_FOREACH(vc_i, &p->inactive_vcs, list)
2272 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2273 printk("Nsec Online, up to the last offlining:\n------------------------");
2274 for (int i = 0; i < p->procinfo->max_vcores; i++) {
2275 uint64_t vc_time = tsc2nsec(vcore_account_gettotal(p, i));
2278 printk(" VC %3d: %14llu", i, vc_time);
2279 total_time += vc_time;
2282 printk("Total CPU-NSEC: %llu\n", total_time);
2283 printk("Resources:\n------------------------\n");
2284 for (int i = 0; i < MAX_NUM_RESOURCES; i++)
2285 printk("\tRes type: %02d, amt wanted: %08d, amt granted: %08d\n", i,
2286 p->procdata->res_req[i].amt_wanted, p->procinfo->res_grant[i]);
2287 printk("Open Files:\n");
2288 struct files_struct *files = &p->open_files;
2289 if (spin_locked(&files->lock)) {
2290 spinlock_debug(&files->lock);
2291 printk("FILE LOCK HELD, ABORTING\n");
2295 spin_lock(&files->lock);
2296 for (int i = 0; i < files->max_files; i++)
2297 if (GET_BITMASK_BIT(files->open_fds->fds_bits, i) &&
2298 (files->fd[i].fd_file)) {
2299 printk("\tFD: %02d, File: %p, File name: %s\n", i,
2300 files->fd[i].fd_file, file_name(files->fd[i].fd_file));
2302 spin_unlock(&files->lock);
2304 printk("Children: (PID (struct proc *))\n");
2305 TAILQ_FOREACH(child, &p->children, sibling_link)
2306 printk("\t%d (%p)\n", child->pid, child);
2307 /* no locking / unlocking or refcnting */
2308 // spin_unlock(&p->proc_lock);
2312 /* Debugging function, checks what (process, vcore) is supposed to run on this
2313 * pcore. Meant to be called from smp_idle() before halting. */
2314 void check_my_owner(void)
2316 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2317 void shazbot(void *item)
2319 struct proc *p = (struct proc*)item;
2322 spin_lock(&p->proc_lock);
2323 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
2324 /* this isn't true, a __startcore could be on the way and we're
2325 * already "online" */
2326 if (vc_i->pcoreid == core_id()) {
2327 /* Immediate message was sent, we should get it when we enable
2328 * interrupts, which should cause us to skip cpu_halt() */
2329 if (!STAILQ_EMPTY(&pcpui->immed_amsgs))
2331 printk("Owned pcore (%d) has no owner, by %p, vc %d!\n",
2332 core_id(), p, vcore2vcoreid(p, vc_i));
2333 spin_unlock(&p->proc_lock);
2334 spin_unlock(&pid_hash_lock);
2338 spin_unlock(&p->proc_lock);
2340 assert(!irq_is_enabled());
2342 if (!booting && !pcpui->owning_proc) {
2343 spin_lock(&pid_hash_lock);
2344 hash_for_each(pid_hash, shazbot);
2345 spin_unlock(&pid_hash_lock);
2349 /* Use this via kfunc */
2350 void print_9ns(void)
2352 void print_proc_9ns(void *item)
2354 struct proc *p = (struct proc*)item;
2357 spin_lock(&pid_hash_lock);
2358 hash_for_each(pid_hash, print_proc_9ns);
2359 spin_unlock(&pid_hash_lock);