1 /* Copyright (c) 2009, 2010 The Regents of the University of California
2 * Barret Rhoden <brho@cs.berkeley.edu>
3 * See LICENSE for details. */
18 #include <hashtable.h>
20 #include <sys/queue.h>
24 #include <arsc_server.h>
28 struct kmem_cache *proc_cache;
30 /* Other helpers, implemented later. */
31 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid);
32 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid);
33 static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid);
34 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid);
35 static void __proc_free(struct kref *kref);
36 static bool scp_is_vcctx_ready(struct preempt_data *vcpd);
37 static void save_vc_fp_state(struct preempt_data *vcpd);
38 static void restore_vc_fp_state(struct preempt_data *vcpd);
41 #define PID_MAX 32767 // goes from 0 to 32767, with 0 reserved
42 static DECL_BITMASK(pid_bmask, PID_MAX + 1);
43 spinlock_t pid_bmask_lock = SPINLOCK_INITIALIZER;
44 struct hashtable *pid_hash;
45 spinlock_t pid_hash_lock; // initialized in proc_init
47 /* Finds the next free entry (zero) entry in the pid_bitmask. Set means busy.
48 * PID 0 is reserved (in proc_init). A return value of 0 is a failure (and
49 * you'll also see a warning, for now). Consider doing this with atomics. */
50 static pid_t get_free_pid(void)
52 static pid_t next_free_pid = 1;
55 spin_lock(&pid_bmask_lock);
56 // atomically (can lock for now, then change to atomic_and_return
57 FOR_CIRC_BUFFER(next_free_pid, PID_MAX + 1, i) {
58 // always points to the next to test
59 next_free_pid = (next_free_pid + 1) % (PID_MAX + 1);
60 if (!GET_BITMASK_BIT(pid_bmask, i)) {
61 SET_BITMASK_BIT(pid_bmask, i);
66 spin_unlock(&pid_bmask_lock);
68 warn("Shazbot! Unable to find a PID! You need to deal with this!\n");
72 /* Return a pid to the pid bitmask */
73 static void put_free_pid(pid_t pid)
75 spin_lock(&pid_bmask_lock);
76 CLR_BITMASK_BIT(pid_bmask, pid);
77 spin_unlock(&pid_bmask_lock);
80 /* 'resume' is the time int ticks of the most recent onlining. 'total' is the
81 * amount of time in ticks consumed up to and including the current offlining.
83 * We could move these to the map and unmap of vcores, though not every place
84 * uses that (SCPs, in particular). However, maps/unmaps happen remotely;
85 * something to consider. If we do it remotely, we can batch them up and do one
86 * rdtsc() for all of them. For now, I want to do them on the core, around when
87 * we do the context change. It'll also parallelize the accounting a bit. */
88 void vcore_account_online(struct proc *p, uint32_t vcoreid)
90 struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
91 vc->resume_ticks = read_tsc();
94 void vcore_account_offline(struct proc *p, uint32_t vcoreid)
96 struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
97 vc->total_ticks += read_tsc() - vc->resume_ticks;
100 uint64_t vcore_account_gettotal(struct proc *p, uint32_t vcoreid)
102 struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
103 return vc->total_ticks;
106 /* While this could be done with just an assignment, this gives us the
107 * opportunity to check for bad transitions. Might compile these out later, so
108 * we shouldn't rely on them for sanity checking from userspace. */
109 int __proc_set_state(struct proc *p, uint32_t state)
111 uint32_t curstate = p->state;
112 /* Valid transitions:
130 * These ought to be implemented later (allowed, not thought through yet).
134 #if 1 // some sort of correctness flag
137 if (!(state & (PROC_RUNNABLE_S | PROC_DYING)))
138 panic("Invalid State Transition! PROC_CREATED to %02x", state);
140 case PROC_RUNNABLE_S:
141 if (!(state & (PROC_RUNNING_S | PROC_DYING)))
142 panic("Invalid State Transition! PROC_RUNNABLE_S to %02x", state);
145 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
147 panic("Invalid State Transition! PROC_RUNNING_S to %02x", state);
150 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNING_S | PROC_RUNNABLE_M |
152 panic("Invalid State Transition! PROC_WAITING to %02x", state);
155 if (state != PROC_CREATED) // when it is reused (TODO)
156 panic("Invalid State Transition! PROC_DYING to %02x", state);
158 case PROC_RUNNABLE_M:
159 if (!(state & (PROC_RUNNING_M | PROC_DYING)))
160 panic("Invalid State Transition! PROC_RUNNABLE_M to %02x", state);
163 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
165 panic("Invalid State Transition! PROC_RUNNING_M to %02x", state);
173 /* Returns a pointer to the proc with the given pid, or 0 if there is none.
174 * This uses get_not_zero, since it is possible the refcnt is 0, which means the
175 * process is dying and we should not have the ref (and thus return 0). We need
176 * to lock to protect us from getting p, (someone else removes and frees p),
177 * then get_not_zero() on p.
178 * Don't push the locking into the hashtable without dealing with this. */
179 struct proc *pid2proc(pid_t pid)
181 spin_lock(&pid_hash_lock);
182 struct proc *p = hashtable_search(pid_hash, (void*)(long)pid);
184 if (!kref_get_not_zero(&p->p_kref, 1))
186 spin_unlock(&pid_hash_lock);
190 /* Used by devproc for successive reads of the proc table.
191 * Returns a pointer to the nth proc, or 0 if there is none.
192 * This uses get_not_zero, since it is possible the refcnt is 0, which means the
193 * process is dying and we should not have the ref (and thus return 0). We need
194 * to lock to protect us from getting p, (someone else removes and frees p),
195 * then get_not_zero() on p.
196 * Don't push the locking into the hashtable without dealing with this. */
197 struct proc *pid_nth(unsigned int n)
200 spin_lock(&pid_hash_lock);
201 if (!hashtable_count(pid_hash)) {
202 spin_unlock(&pid_hash_lock);
205 struct hashtable_itr *iter = hashtable_iterator(pid_hash);
206 p = hashtable_iterator_value(iter);
209 /* if this process is not valid, it doesn't count,
213 if (kref_get_not_zero(&p->p_kref, 1)){
214 /* this one counts */
216 printd("pid_nth: at end, p %p\n", p);
219 kref_put(&p->p_kref);
222 if (!hashtable_iterator_advance(iter)){
226 p = hashtable_iterator_value(iter);
229 spin_unlock(&pid_hash_lock);
234 /* Performs any initialization related to processes, such as create the proc
235 * cache, prep the scheduler, etc. When this returns, we should be ready to use
236 * any process related function. */
239 /* Catch issues with the vcoremap and TAILQ_ENTRY sizes */
240 static_assert(sizeof(TAILQ_ENTRY(vcore)) == sizeof(void*) * 2);
241 proc_cache = kmem_cache_create("proc", sizeof(struct proc),
242 MAX(ARCH_CL_SIZE, __alignof__(struct proc)), 0, 0, 0);
243 /* Init PID mask and hash. pid 0 is reserved. */
244 SET_BITMASK_BIT(pid_bmask, 0);
245 spinlock_init(&pid_hash_lock);
246 spin_lock(&pid_hash_lock);
247 pid_hash = create_hashtable(100, __generic_hash, __generic_eq);
248 spin_unlock(&pid_hash_lock);
251 atomic_init(&num_envs, 0);
254 void proc_set_progname(struct proc *p, char *name)
257 name = DEFAULT_PROGNAME;
259 /* might have an issue if a dentry name isn't null terminated, and we'd get
260 * extra junk up to progname_sz. */
261 strncpy(p->progname, name, PROC_PROGNAME_SZ);
262 p->progname[PROC_PROGNAME_SZ - 1] = '\0';
265 /* Be sure you init'd the vcore lists before calling this. */
266 static void proc_init_procinfo(struct proc* p)
268 p->procinfo->pid = p->pid;
269 p->procinfo->ppid = p->ppid;
270 p->procinfo->max_vcores = max_vcores(p);
271 p->procinfo->tsc_freq = system_timing.tsc_freq;
272 p->procinfo->timing_overhead = system_timing.timing_overhead;
273 p->procinfo->heap_bottom = 0;
274 /* 0'ing the arguments. Some higher function will need to set them */
275 memset(p->procinfo->res_grant, 0, sizeof(p->procinfo->res_grant));
276 /* 0'ing the vcore/pcore map. Will link the vcores later. */
277 memset(&p->procinfo->vcoremap, 0, sizeof(p->procinfo->vcoremap));
278 memset(&p->procinfo->pcoremap, 0, sizeof(p->procinfo->pcoremap));
279 p->procinfo->num_vcores = 0;
280 p->procinfo->is_mcp = FALSE;
281 p->procinfo->coremap_seqctr = SEQCTR_INITIALIZER;
282 /* It's a bug in the kernel if we let them ask for more than max */
283 for (int i = 0; i < p->procinfo->max_vcores; i++) {
284 TAILQ_INSERT_TAIL(&p->inactive_vcs, &p->procinfo->vcoremap[i], list);
288 static void proc_init_procdata(struct proc *p)
290 memset(p->procdata, 0, sizeof(struct procdata));
291 /* processes can't go into vc context on vc 0 til they unset this. This is
292 * for processes that block before initing uthread code (like rtld). */
293 atomic_set(&p->procdata->vcore_preempt_data[0].flags, VC_SCP_NOVCCTX);
296 /* Allocates and initializes a process, with the given parent. Currently
297 * writes the *p into **pp, and returns 0 on success, < 0 for an error.
299 * - ENOFREEPID if it can't get a PID
300 * - ENOMEM on memory exhaustion */
301 error_t proc_alloc(struct proc **pp, struct proc *parent, int flags)
306 if (!(p = kmem_cache_alloc(proc_cache, 0)))
308 /* zero everything by default, other specific items are set below */
309 memset(p, 0, sizeof(struct proc));
311 /* only one ref, which we pass back. the old 'existence' ref is managed by
313 kref_init(&p->p_kref, __proc_free, 1);
314 // Setup the default map of where to get cache colors from
315 p->cache_colors_map = global_cache_colors_map;
316 p->next_cache_color = 0;
317 /* Initialize the address space */
318 if ((r = env_setup_vm(p)) < 0) {
319 kmem_cache_free(proc_cache, p);
322 if (!(p->pid = get_free_pid())) {
323 kmem_cache_free(proc_cache, p);
326 /* Set the basic status variables. */
327 spinlock_init(&p->proc_lock);
328 p->exitcode = 1337; /* so we can see processes killed by the kernel */
330 p->ppid = parent->pid;
331 proc_incref(p, 1); /* storing a ref in the parent */
332 /* using the CV's lock to protect anything related to child waiting */
333 cv_lock(&parent->child_wait);
334 TAILQ_INSERT_TAIL(&parent->children, p, sibling_link);
335 cv_unlock(&parent->child_wait);
339 TAILQ_INIT(&p->children);
340 cv_init(&p->child_wait);
341 p->state = PROC_CREATED; /* shouldn't go through state machine for init */
344 spinlock_init(&p->vmr_lock);
345 spinlock_init(&p->pte_lock);
346 TAILQ_INIT(&p->vm_regions); /* could init this in the slab */
348 /* Initialize the vcore lists, we'll build the inactive list so that it
349 * includes all vcores when we initialize procinfo. Do this before initing
351 TAILQ_INIT(&p->online_vcs);
352 TAILQ_INIT(&p->bulk_preempted_vcs);
353 TAILQ_INIT(&p->inactive_vcs);
354 /* Init procinfo/procdata. Procinfo's argp/argb are 0'd */
355 proc_init_procinfo(p);
356 proc_init_procdata(p);
358 /* Initialize the generic sysevent ring buffer */
359 SHARED_RING_INIT(&p->procdata->syseventring);
360 /* Initialize the frontend of the sysevent ring buffer */
361 FRONT_RING_INIT(&p->syseventfrontring,
362 &p->procdata->syseventring,
365 /* Init FS structures TODO: cleanup (might pull this out) */
366 kref_get(&default_ns.kref, 1);
368 spinlock_init(&p->fs_env.lock);
369 p->fs_env.umask = parent ? parent->fs_env.umask : S_IWGRP | S_IWOTH;
370 p->fs_env.root = p->ns->root->mnt_root;
371 kref_get(&p->fs_env.root->d_kref, 1);
372 p->fs_env.pwd = parent ? parent->fs_env.pwd : p->fs_env.root;
373 kref_get(&p->fs_env.pwd->d_kref, 1);
374 memset(&p->open_files, 0, sizeof(p->open_files)); /* slightly ghetto */
375 spinlock_init(&p->open_files.lock);
376 p->open_files.max_files = NR_OPEN_FILES_DEFAULT;
377 p->open_files.max_fdset = NR_FILE_DESC_DEFAULT;
378 p->open_files.fd = p->open_files.fd_array;
379 p->open_files.open_fds = (struct fd_set*)&p->open_files.open_fds_init;
381 if (flags & PROC_DUP_FGRP)
382 clone_fdt(&parent->open_files, &p->open_files);
384 /* no parent, we're created from the kernel */
386 fd = insert_file(&p->open_files, dev_stdin, 0, TRUE, FALSE);
388 fd = insert_file(&p->open_files, dev_stdout, 1, TRUE, FALSE);
390 fd = insert_file(&p->open_files, dev_stderr, 2, TRUE, FALSE);
393 /* Init the ucq hash lock */
394 p->ucq_hashlock = (struct hashlock*)&p->ucq_hl_noref;
395 hashlock_init_irqsave(p->ucq_hashlock, HASHLOCK_DEFAULT_SZ);
397 atomic_inc(&num_envs);
398 frontend_proc_init(p);
399 /* this does all the 9ns setup, much of which is done throughout this func
400 * for the VFS, including duping the fgrp */
401 plan9setup(p, parent, flags);
403 TAILQ_INIT(&p->abortable_sleepers);
404 spinlock_init_irqsave(&p->abort_list_lock);
405 memset(&p->vmm, 0, sizeof(struct vmm));
406 qlock_init(&p->vmm.qlock);
407 printd("[%08x] new process %08x\n", current ? current->pid : 0, p->pid);
412 /* We have a bunch of different ways to make processes. Call this once the
413 * process is ready to be used by the rest of the system. For now, this just
414 * means when it is ready to be named via the pidhash. In the future, we might
415 * push setting the state to CREATED into here. */
416 void __proc_ready(struct proc *p)
418 /* Tell the ksched about us. TODO: do we need to worry about the ksched
419 * doing stuff to us before we're added to the pid_hash? */
420 __sched_proc_register(p);
421 spin_lock(&pid_hash_lock);
422 hashtable_insert(pid_hash, (void*)(long)p->pid, p);
423 spin_unlock(&pid_hash_lock);
426 /* Creates a process from the specified file, argvs, and envps. Tempted to get
427 * rid of proc_alloc's style, but it is so quaint... */
428 struct proc *proc_create(struct file *prog, char **argv, char **envp)
432 if ((r = proc_alloc(&p, current, 0 /* flags */)) < 0)
433 panic("proc_create: %e", r); /* one of 3 quaint usages of %e */
434 int argc = 0, envc = 0;
435 if(argv) while(argv[argc]) argc++;
436 if(envp) while(envp[envc]) envc++;
437 proc_set_progname(p, argc ? argv[0] : NULL);
438 assert(load_elf(p, prog, argc, argv, envc, envp) == 0);
443 static int __cb_assert_no_pg(struct proc *p, pte_t pte, void *va, void *arg)
445 assert(pte_is_unmapped(pte));
449 /* This is called by kref_put(), once the last reference to the process is
450 * gone. Don't call this otherwise (it will panic). It will clean up the
451 * address space and deallocate any other used memory. */
452 static void __proc_free(struct kref *kref)
454 struct proc *p = container_of(kref, struct proc, p_kref);
458 printd("[PID %d] freeing proc: %d\n", current ? current->pid : 0, p->pid);
459 // All parts of the kernel should have decref'd before __proc_free is called
460 assert(kref_refcnt(&p->p_kref) == 0);
461 assert(TAILQ_EMPTY(&p->alarmset.list));
463 __vmm_struct_cleanup(p);
467 p->dot = p->slash = 0; /* catch bugs */
468 /* can safely free the fgrp, now that no one is accessing it */
469 kfree(p->open_files.fgrp->fd);
470 kfree(p->open_files.fgrp);
471 kref_put(&p->fs_env.root->d_kref);
472 kref_put(&p->fs_env.pwd->d_kref);
473 /* now we'll finally decref files for the file-backed vmrs */
474 unmap_and_destroy_vmrs(p);
475 frontend_proc_free(p); /* TODO: please remove me one day */
476 /* Free any colors allocated to this process */
477 if (p->cache_colors_map != global_cache_colors_map) {
478 for(int i = 0; i < llc_cache->num_colors; i++)
479 cache_color_free(llc_cache, p->cache_colors_map);
480 cache_colors_map_free(p->cache_colors_map);
482 /* Remove us from the pid_hash and give our PID back (in that order). */
483 spin_lock(&pid_hash_lock);
484 hash_ret = hashtable_remove(pid_hash, (void*)(long)p->pid);
485 spin_unlock(&pid_hash_lock);
486 /* might not be in the hash/ready, if we failed during proc creation */
488 put_free_pid(p->pid);
490 printd("[kernel] pid %d not in the PID hash in %s\n", p->pid,
492 /* all memory below UMAPTOP should have been freed via the VMRs. the stuff
493 * above is the global page and procinfo/procdata */
494 env_user_mem_free(p, (void*)UMAPTOP, UVPT - UMAPTOP); /* 3rd arg = len... */
495 env_user_mem_walk(p, 0, UMAPTOP, __cb_assert_no_pg, 0);
496 /* These need to be freed again, since they were allocated with a refcnt. */
497 free_cont_pages(p->procinfo, LOG2_UP(PROCINFO_NUM_PAGES));
498 free_cont_pages(p->procdata, LOG2_UP(PROCDATA_NUM_PAGES));
500 env_pagetable_free(p);
501 arch_pgdir_clear(&p->env_pgdir);
504 atomic_dec(&num_envs);
506 /* Dealloc the struct proc */
507 kmem_cache_free(proc_cache, p);
510 /* Whether or not actor can control target. TODO: do something reasonable here.
511 * Just checking for the parent is a bit limiting. Could walk the parent-child
512 * tree, check user ids, or some combination. Make sure actors can always
513 * control themselves. */
514 bool proc_controls(struct proc *actor, struct proc *target)
518 return ((actor == target) || (target->ppid == actor->pid));
522 /* Helper to incref by val. Using the helper to help debug/interpose on proc
523 * ref counting. Note that pid2proc doesn't use this interface. */
524 void proc_incref(struct proc *p, unsigned int val)
526 kref_get(&p->p_kref, val);
529 /* Helper to decref for debugging. Don't directly kref_put() for now. */
530 void proc_decref(struct proc *p)
532 kref_put(&p->p_kref);
535 /* Helper, makes p the 'current' process, dropping the old current/cr3. This no
536 * longer assumes the passed in reference already counted 'current'. It will
537 * incref internally when needed. */
538 static void __set_proc_current(struct proc *p)
540 /* We use the pcpui to access 'current' to cut down on the core_id() calls,
541 * though who know how expensive/painful they are. */
542 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
543 /* If the process wasn't here, then we need to load its address space. */
544 if (p != pcpui->cur_proc) {
547 /* This is "leaving the process context" of the previous proc. The
548 * previous lcr3 unloaded the previous proc's context. This should
549 * rarely happen, since we usually proactively leave process context,
550 * but this is the fallback. */
552 proc_decref(pcpui->cur_proc);
557 /* Flag says if vcore context is not ready, which is set in init_procdata. The
558 * process must turn off this flag on vcore0 at some point. It's off by default
559 * on all other vcores. */
560 static bool scp_is_vcctx_ready(struct preempt_data *vcpd)
562 return !(atomic_read(&vcpd->flags) & VC_SCP_NOVCCTX);
565 /* Dispatches a _S process to run on the current core. This should never be
566 * called to "restart" a core.
568 * This will always return, regardless of whether or not the calling core is
569 * being given to a process. (it used to pop the tf directly, before we had
572 * Since it always returns, it will never "eat" your reference (old
573 * documentation talks about this a bit). */
574 void proc_run_s(struct proc *p)
576 uint32_t coreid = core_id();
577 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
578 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
579 spin_lock(&p->proc_lock);
582 spin_unlock(&p->proc_lock);
583 printk("[kernel] _S %d not starting due to async death\n", p->pid);
585 case (PROC_RUNNABLE_S):
586 __proc_set_state(p, PROC_RUNNING_S);
587 /* SCPs don't have full vcores, but they act like they have vcore 0.
588 * We map the vcore, since we will want to know where this process
589 * is running, even if it is only in RUNNING_S. We can use the
590 * vcoremap, which makes death easy. num_vcores is still 0, and we
591 * do account the time online and offline. */
592 __seq_start_write(&p->procinfo->coremap_seqctr);
593 p->procinfo->num_vcores = 0;
594 __map_vcore(p, 0, coreid);
595 vcore_account_online(p, 0);
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;
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, vcpd->vcore_entry,
621 vcpd->vcore_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);
847 __seq_end_write(&p->procinfo->coremap_seqctr);
848 /* If we ever have RUNNING_S run on non-mgmt cores, we'll need to
849 * tell the ksched about this now-idle core (after unlocking) */
852 warn("Weird state(%s) in %s()", procstate2str(p->state),
854 spin_unlock(&p->proc_lock);
857 /* At this point, a death IPI should be on its way, either from the
858 * RUNNING_S one, or from proc_take_cores with a __death. in general,
859 * interrupts should be on when you call proc_destroy locally, but currently
860 * aren't for all things (like traphandlers). */
861 __proc_set_state(p, PROC_DYING);
862 /* Disown any children. If we want to have init inherit or something,
863 * change __disown to set the ppid accordingly and concat this with init's
864 * list (instead of emptying it like disown does). Careful of lock ordering
865 * between procs (need to lock to protect lists) */
866 TAILQ_FOREACH_SAFE(child_i, &p->children, sibling_link, temp) {
867 int ret = __proc_disown_child(p, child_i);
868 /* should never fail, lock should cover the race. invariant: any child
869 * on the list should have us as a parent */
872 spin_unlock(&p->proc_lock);
873 /* Wake any of our kthreads waiting on children, so they can abort */
874 cv_broadcast(&p->child_wait);
875 /* Abort any abortable syscalls. This won't catch every sleeper, but future
876 * abortable sleepers are already prevented via the DYING state. (signalled
877 * DYING, no new sleepers will block, and now we wake all old sleepers). */
879 /* we need to close files here, and not in free, since we could have a
880 * refcnt indirectly related to one of our files. specifically, if we have
881 * a parent sleeping on our pipe, that parent won't wake up to decref until
882 * the pipe closes. And if the parent doesnt decref, we don't free.
883 * alternatively, we could send a SIGCHILD to the parent, but that would
884 * require parent's to never ignore that signal (or risk never reaping).
886 * Also note that any mmap'd files will still be mmapped. You can close the
887 * file after mmapping, with no effect. */
888 close_9ns_files(p, FALSE);
889 close_fdt(&p->open_files, FALSE);
890 /* Tell the ksched about our death, and which cores we freed up */
891 __sched_proc_destroy(p, pc_arr, nr_cores_revoked);
892 /* Tell our parent about our state change (to DYING) */
893 proc_signal_parent(p);
896 /* Can use this to signal anything that might cause a parent to wait on the
897 * child, such as termination, or (in the future) signals. Change the state or
898 * whatever before calling. */
899 void proc_signal_parent(struct proc *child)
901 struct kthread *sleeper;
902 struct proc *parent = pid2proc(child->ppid);
905 /* there could be multiple kthreads sleeping for various reasons. even an
906 * SCP could have multiple async syscalls. */
907 cv_broadcast(&parent->child_wait);
908 /* if the parent was waiting, there's a __launch kthread KMSG out there */
912 /* Called when a parent is done with its child, and no longer wants to track the
913 * child, nor to allow the child to track it. Call with a lock (cv) held.
914 * Returns 0 if we disowned, -1 on failure. */
915 int __proc_disown_child(struct proc *parent, struct proc *child)
917 /* Bail out if the child has already been reaped */
920 assert(child->ppid == parent->pid);
921 /* lock protects from concurrent inserts / removals from the list */
922 TAILQ_REMOVE(&parent->children, child, sibling_link);
923 /* After this, the child won't be able to get more refs to us, but it may
924 * still have some references in running code. */
926 proc_decref(child); /* ref that was keeping the child alive on the list */
930 /* Turns *p into an MCP. Needs to be called from a local syscall of a RUNNING_S
931 * process. Returns 0 if it succeeded, an error code otherwise. */
932 int proc_change_to_m(struct proc *p)
935 spin_lock(&p->proc_lock);
936 /* in case userspace erroneously tries to change more than once */
937 if (__proc_is_mcp(p))
940 case (PROC_RUNNING_S):
941 /* issue with if we're async or not (need to preempt it)
942 * either of these should trip it. TODO: (ACR) async core req */
943 if ((current != p) || (get_pcoreid(p, 0) != core_id()))
944 panic("We don't handle async RUNNING_S core requests yet.");
945 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
947 /* Copy uthread0's context to VC 0's uthread slot */
948 vcpd->uthread_ctx = *current_ctx;
949 clear_owning_proc(core_id()); /* so we don't restart */
950 save_vc_fp_state(vcpd);
951 /* Userspace needs to not fuck with notif_disabled before
952 * transitioning to _M. */
953 if (vcpd->notif_disabled) {
954 printk("[kernel] user bug: notifs disabled for vcore 0\n");
955 vcpd->notif_disabled = FALSE;
957 /* in the async case, we'll need to remotely stop and bundle
958 * vcore0's TF. this is already done for the sync case (local
960 /* this process no longer runs on its old location (which is
961 * this core, for now, since we don't handle async calls) */
962 __seq_start_write(&p->procinfo->coremap_seqctr);
963 // TODO: (ACR) will need to unmap remotely (receive-side)
965 vcore_account_offline(p, 0);
966 __seq_end_write(&p->procinfo->coremap_seqctr);
967 /* change to runnable_m (it's TF is already saved) */
968 __proc_set_state(p, PROC_RUNNABLE_M);
969 p->procinfo->is_mcp = TRUE;
970 spin_unlock(&p->proc_lock);
971 /* Tell the ksched that we're a real MCP now! */
972 __sched_proc_change_to_m(p);
974 case (PROC_RUNNABLE_S):
975 /* Issues: being on the runnable_list, proc_set_state not liking
976 * it, and not clearly thinking through how this would happen.
977 * Perhaps an async call that gets serviced after you're
979 warn("Not supporting RUNNABLE_S -> RUNNABLE_M yet.\n");
982 warn("Dying, core request coming from %d\n", core_id());
988 spin_unlock(&p->proc_lock);
992 /* Old code to turn a RUNNING_M to a RUNNING_S, with the calling context
993 * becoming the new 'thread0'. Don't use this. Caller needs to send in a
994 * pc_arr big enough for all vcores. Will return the number of cores given up
996 uint32_t __proc_change_to_s(struct proc *p, uint32_t *pc_arr)
998 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
999 uint32_t num_revoked;
1000 /* Not handling vcore accounting. Do so if we ever use this */
1001 printk("[kernel] trying to transition _M -> _S (deprecated)!\n");
1002 assert(p->state == PROC_RUNNING_M); // TODO: (ACR) async core req
1003 /* save the context, to be restarted in _S mode */
1004 assert(current_ctx);
1005 p->scp_ctx = *current_ctx;
1006 clear_owning_proc(core_id()); /* so we don't restart */
1007 save_vc_fp_state(vcpd);
1008 /* sending death, since it's not our job to save contexts or anything in
1010 num_revoked = __proc_take_allcores(p, pc_arr, FALSE);
1011 __proc_set_state(p, PROC_RUNNABLE_S);
1015 /* Helper function. Is the given pcore a mapped vcore? No locking involved, be
1017 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid)
1019 return p->procinfo->pcoremap[pcoreid].valid;
1022 /* Helper function. Find the vcoreid for a given physical core id for proc p.
1023 * No locking involved, be careful. Panics on failure. */
1024 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid)
1026 assert(is_mapped_vcore(p, pcoreid));
1027 return p->procinfo->pcoremap[pcoreid].vcoreid;
1030 /* Helper function. Try to find the pcoreid for a given virtual core id for
1031 * proc p. No locking involved, be careful. Use this when you can tolerate a
1032 * stale or otherwise 'wrong' answer. */
1033 static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid)
1035 return p->procinfo->vcoremap[vcoreid].pcoreid;
1038 /* Helper function. Find the pcoreid for a given virtual core id for proc p.
1039 * No locking involved, be careful. Panics on failure. */
1040 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid)
1042 assert(vcore_is_mapped(p, vcoreid));
1043 return try_get_pcoreid(p, vcoreid);
1046 /* Saves the FP state of the calling core into VCPD. Pairs with
1047 * restore_vc_fp_state(). On x86, the best case overhead of the flags:
1051 * Flagged FXSAVE: 50 ns
1052 * Flagged FXRSTR: 66 ns
1053 * Excess flagged FXRSTR: 42 ns
1054 * If we don't do it, we'll need to initialize every VCPD at process creation
1055 * time with a good FPU state (x86 control words are initialized as 0s, like the
1057 static void save_vc_fp_state(struct preempt_data *vcpd)
1059 save_fp_state(&vcpd->preempt_anc);
1060 vcpd->rflags |= VC_FPU_SAVED;
1063 /* Conditionally restores the FP state from VCPD. If the state was not valid,
1064 * we don't bother restoring and just initialize the FPU. */
1065 static void restore_vc_fp_state(struct preempt_data *vcpd)
1067 if (vcpd->rflags & VC_FPU_SAVED) {
1068 restore_fp_state(&vcpd->preempt_anc);
1069 vcpd->rflags &= ~VC_FPU_SAVED;
1075 /* Helper for SCPs, saves the core's FPU state into the VCPD vc0 slot */
1076 void __proc_save_fpu_s(struct proc *p)
1078 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1079 save_vc_fp_state(vcpd);
1082 /* Helper: saves the SCP's GP tf state and unmaps vcore 0. This does *not* save
1085 * In the future, we'll probably use vc0's space for scp_ctx and the silly
1086 * state. If we ever do that, we'll need to stop using scp_ctx (soon to be in
1087 * VCPD) as a location for pcpui->cur_ctx to point (dangerous) */
1088 void __proc_save_context_s(struct proc *p, struct user_context *ctx)
1091 __seq_start_write(&p->procinfo->coremap_seqctr);
1092 __unmap_vcore(p, 0);
1093 __seq_end_write(&p->procinfo->coremap_seqctr);
1094 vcore_account_offline(p, 0);
1097 /* Yields the calling core. Must be called locally (not async) for now.
1098 * - If RUNNING_S, you just give up your time slice and will eventually return,
1099 * possibly after WAITING on an event.
1100 * - If RUNNING_M, you give up the current vcore (which never returns), and
1101 * adjust the amount of cores wanted/granted.
1102 * - If you have only one vcore, you switch to WAITING. There's no 'classic
1103 * yield' for MCPs (at least not now). When you run again, you'll have one
1104 * guaranteed core, starting from the entry point.
1106 * If the call is being nice, it means different things for SCPs and MCPs. For
1107 * MCPs, it means that it is in response to a preemption (which needs to be
1108 * checked). If there is no preemption pending, just return. For SCPs, it
1109 * means the proc wants to give up the core, but still has work to do. If not,
1110 * the proc is trying to wait on an event. It's not being nice to others, it
1111 * just has no work to do.
1113 * This usually does not return (smp_idle()), so it will eat your reference.
1114 * Also note that it needs a non-current/edible reference, since it will abandon
1115 * and continue to use the *p (current == 0, no cr3, etc).
1117 * We disable interrupts for most of it too, since we need to protect
1118 * current_ctx and not race with __notify (which doesn't play well with
1119 * concurrent yielders). */
1120 void proc_yield(struct proc *p, bool being_nice)
1122 uint32_t vcoreid, pcoreid = core_id();
1123 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1125 struct preempt_data *vcpd;
1126 /* Need to lock to prevent concurrent vcore changes (online, inactive, the
1127 * mapping, etc). This plus checking the nr_preempts is enough to tell if
1128 * our vcoreid and cur_ctx ought to be here still or if we should abort */
1129 spin_lock(&p->proc_lock); /* horrible scalability. =( */
1131 case (PROC_RUNNING_S):
1133 /* waiting for an event to unblock us */
1134 vcpd = &p->procdata->vcore_preempt_data[0];
1135 /* syncing with event's SCP code. we set waiting, then check
1136 * pending. they set pending, then check waiting. it's not
1137 * possible for us to miss the notif *and* for them to miss
1138 * WAITING. one (or both) of us will see and make sure the proc
1140 __proc_set_state(p, PROC_WAITING);
1141 wrmb(); /* don't let the state write pass the notif read */
1142 if (vcpd->notif_pending) {
1143 __proc_set_state(p, PROC_RUNNING_S);
1144 /* they can't handle events, just need to prevent a yield.
1145 * (note the notif_pendings are collapsed). */
1146 if (!scp_is_vcctx_ready(vcpd))
1147 vcpd->notif_pending = FALSE;
1150 /* if we're here, we want to sleep. a concurrent event that
1151 * hasn't already written notif_pending will have seen WAITING,
1152 * and will be spinning while we do this. */
1153 __proc_save_context_s(p, current_ctx);
1154 spin_unlock(&p->proc_lock);
1156 /* yielding to allow other processes to run. we're briefly
1157 * WAITING, til we are woken up */
1158 __proc_set_state(p, PROC_WAITING);
1159 __proc_save_context_s(p, current_ctx);
1160 spin_unlock(&p->proc_lock);
1161 /* immediately wake up the proc (makes it runnable) */
1164 goto out_yield_core;
1165 case (PROC_RUNNING_M):
1166 break; /* will handle this stuff below */
1167 case (PROC_DYING): /* incoming __death */
1168 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1171 panic("Weird state(%s) in %s()", procstate2str(p->state),
1174 /* This is which vcore this pcore thinks it is, regardless of any unmappings
1175 * that may have happened remotely (with __PRs waiting to run) */
1176 vcoreid = pcpui->owning_vcoreid;
1177 vc = vcoreid2vcore(p, vcoreid);
1178 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1179 /* This is how we detect whether or not a __PR happened. */
1180 if (vc->nr_preempts_sent != vc->nr_preempts_done)
1182 /* Sanity checks. If we were preempted or are dying, we should have noticed
1184 assert(is_mapped_vcore(p, pcoreid));
1185 assert(vcoreid == get_vcoreid(p, pcoreid));
1186 /* no reason to be nice, return */
1187 if (being_nice && !vc->preempt_pending)
1189 /* At this point, AFAIK there should be no preempt/death messages on the
1190 * way, and we're on the online list. So we'll go ahead and do the yielding
1192 /* If there's a preempt pending, we don't need to preempt later since we are
1193 * yielding (nice or otherwise). If not, this is just a regular yield. */
1194 if (vc->preempt_pending) {
1195 vc->preempt_pending = 0;
1197 /* Optional: on a normal yield, check to see if we are putting them
1198 * below amt_wanted (help with user races) and bail. */
1199 if (p->procdata->res_req[RES_CORES].amt_wanted >=
1200 p->procinfo->num_vcores)
1203 /* Don't let them yield if they are missing a notification. Userspace must
1204 * not leave vcore context without dealing with notif_pending.
1205 * pop_user_ctx() handles leaving via uthread context. This handles leaving
1208 * This early check is an optimization. The real check is below when it
1209 * works with the online_vcs list (syncing with event.c and INDIR/IPI
1211 if (vcpd->notif_pending)
1213 /* Now we'll actually try to yield */
1214 printd("[K] Process %d (%p) is yielding on vcore %d\n", p->pid, p,
1215 get_vcoreid(p, pcoreid));
1216 /* Remove from the online list, add to the yielded list, and unmap
1217 * the vcore, which gives up the core. */
1218 TAILQ_REMOVE(&p->online_vcs, vc, list);
1219 /* Now that we're off the online list, check to see if an alert made
1220 * it through (event.c sets this) */
1221 wrmb(); /* prev write must hit before reading notif_pending */
1222 /* Note we need interrupts disabled, since a __notify can come in
1223 * and set pending to FALSE */
1224 if (vcpd->notif_pending) {
1225 /* We lost, put it back on the list and abort the yield. If we ever
1226 * build an myield, we'll need a way to deal with this for all vcores */
1227 TAILQ_INSERT_TAIL(&p->online_vcs, vc, list); /* could go HEAD */
1230 /* Not really a kmsg, but it acts like one w.r.t. proc mgmt */
1231 pcpui_trace_kmsg(pcpui, (uintptr_t)proc_yield);
1232 /* We won the race with event sending, we can safely yield */
1233 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1234 /* Note this protects stuff userspace should look at, which doesn't
1235 * include the TAILQs. */
1236 __seq_start_write(&p->procinfo->coremap_seqctr);
1237 /* Next time the vcore starts, it starts fresh */
1238 vcpd->notif_disabled = FALSE;
1239 __unmap_vcore(p, vcoreid);
1240 p->procinfo->num_vcores--;
1241 p->procinfo->res_grant[RES_CORES] = p->procinfo->num_vcores;
1242 __seq_end_write(&p->procinfo->coremap_seqctr);
1243 vcore_account_offline(p, vcoreid);
1244 /* No more vcores? Then we wait on an event */
1245 if (p->procinfo->num_vcores == 0) {
1246 /* consider a ksched op to tell it about us WAITING */
1247 __proc_set_state(p, PROC_WAITING);
1249 spin_unlock(&p->proc_lock);
1250 /* Hand the now-idle core to the ksched */
1251 __sched_put_idle_core(p, pcoreid);
1252 goto out_yield_core;
1254 /* for some reason we just want to return, either to take a KMSG that cleans
1255 * us up, or because we shouldn't yield (ex: notif_pending). */
1256 spin_unlock(&p->proc_lock);
1258 out_yield_core: /* successfully yielded the core */
1259 proc_decref(p); /* need to eat the ref passed in */
1260 /* Clean up the core and idle. */
1261 clear_owning_proc(pcoreid); /* so we don't restart */
1266 /* Sends a notification (aka active notification, aka IPI) to p's vcore. We
1267 * only send a notification if one they are enabled. There's a bunch of weird
1268 * cases with this, and how pending / enabled are signals between the user and
1269 * kernel - check the documentation. Note that pending is more about messages.
1270 * The process needs to be in vcore_context, and the reason is usually a
1271 * message. We set pending here in case we were called to prod them into vcore
1272 * context (like via a sys_self_notify). Also note that this works for _S
1273 * procs, if you send to vcore 0 (and the proc is running). */
1274 void proc_notify(struct proc *p, uint32_t vcoreid)
1276 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1277 vcpd->notif_pending = TRUE;
1278 wrmb(); /* must write notif_pending before reading notif_disabled */
1279 if (!vcpd->notif_disabled) {
1280 /* GIANT WARNING: we aren't using the proc-lock to protect the
1281 * vcoremap. We want to be able to use this from interrupt context,
1282 * and don't want the proc_lock to be an irqsave. Spurious
1283 * __notify() kmsgs are okay (it checks to see if the right receiver
1285 if (vcore_is_mapped(p, vcoreid)) {
1286 printd("[kernel] sending notif to vcore %d\n", vcoreid);
1287 /* This use of try_get_pcoreid is racy, might be unmapped */
1288 send_kernel_message(try_get_pcoreid(p, vcoreid), __notify, (long)p,
1289 0, 0, KMSG_ROUTINE);
1294 /* Makes sure p is runnable. Callers may spam this, so it needs to handle
1295 * repeated calls for the same event. Callers include event delivery, SCP
1296 * yield, and new SCPs. Will trigger __sched_.cp_wakeup() CBs. Will only
1297 * trigger the CB once, regardless of how many times we are called, *until* the
1298 * proc becomes WAITING again, presumably because of something the ksched did.*/
1299 void proc_wakeup(struct proc *p)
1301 spin_lock(&p->proc_lock);
1302 if (__proc_is_mcp(p)) {
1303 /* we only wake up WAITING mcps */
1304 if (p->state != PROC_WAITING) {
1305 spin_unlock(&p->proc_lock);
1308 __proc_set_state(p, PROC_RUNNABLE_M);
1309 spin_unlock(&p->proc_lock);
1310 __sched_mcp_wakeup(p);
1313 /* SCPs can wake up for a variety of reasons. the only times we need
1314 * to do something is if it was waiting or just created. other cases
1315 * are either benign (just go out), or potential bugs (_Ms) */
1317 case (PROC_CREATED):
1318 case (PROC_WAITING):
1319 __proc_set_state(p, PROC_RUNNABLE_S);
1321 case (PROC_RUNNABLE_S):
1322 case (PROC_RUNNING_S):
1324 spin_unlock(&p->proc_lock);
1326 case (PROC_RUNNABLE_M):
1327 case (PROC_RUNNING_M):
1328 warn("Weird state(%s) in %s()", procstate2str(p->state),
1330 spin_unlock(&p->proc_lock);
1333 printd("[kernel] FYI, waking up an _S proc\n"); /* thanks, past brho! */
1334 spin_unlock(&p->proc_lock);
1335 __sched_scp_wakeup(p);
1339 /* Is the process in multi_mode / is an MCP or not? */
1340 bool __proc_is_mcp(struct proc *p)
1342 /* in lieu of using the amount of cores requested, or having a bunch of
1343 * states (like PROC_WAITING_M and _S), I'll just track it with a bool. */
1344 return p->procinfo->is_mcp;
1347 bool proc_is_vcctx_ready(struct proc *p)
1349 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1350 return scp_is_vcctx_ready(vcpd);
1353 /************************ Preemption Functions ******************************
1354 * Don't rely on these much - I'll be sure to change them up a bit.
1356 * Careful about what takes a vcoreid and what takes a pcoreid. Also, there may
1357 * be weird glitches with setting the state to RUNNABLE_M. It is somewhat in
1358 * flux. The num_vcores is changed after take_cores, but some of the messages
1359 * (or local traps) may not yet be ready to handle seeing their future state.
1360 * But they should be, so fix those when they pop up.
1362 * Another thing to do would be to make the _core functions take a pcorelist,
1363 * and not just one pcoreid. */
1365 /* Sets a preempt_pending warning for p's vcore, to go off 'when'. If you care
1366 * about locking, do it before calling. Takes a vcoreid! */
1367 void __proc_preempt_warn(struct proc *p, uint32_t vcoreid, uint64_t when)
1369 struct event_msg local_msg = {0};
1370 /* danger with doing this unlocked: preempt_pending is set, but never 0'd,
1371 * since it is unmapped and not dealt with (TODO)*/
1372 p->procinfo->vcoremap[vcoreid].preempt_pending = when;
1374 /* Send the event (which internally checks to see how they want it) */
1375 local_msg.ev_type = EV_PREEMPT_PENDING;
1376 local_msg.ev_arg1 = vcoreid;
1377 /* Whenever we send msgs with the proc locked, we need at least 1 online.
1378 * Caller needs to make sure the core was online/mapped. */
1379 assert(!TAILQ_EMPTY(&p->online_vcs));
1380 send_kernel_event(p, &local_msg, vcoreid);
1382 /* TODO: consider putting in some lookup place for the alarm to find it.
1383 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1386 /* Warns all active vcores of an impending preemption. Hold the lock if you
1387 * care about the mapping (and you should). */
1388 void __proc_preempt_warnall(struct proc *p, uint64_t when)
1391 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1392 __proc_preempt_warn(p, vcore2vcoreid(p, vc_i), when);
1393 /* TODO: consider putting in some lookup place for the alarm to find it.
1394 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1397 // TODO: function to set an alarm, if none is outstanding
1399 /* Raw function to preempt a single core. If you care about locking, do it
1400 * before calling. */
1401 void __proc_preempt_core(struct proc *p, uint32_t pcoreid)
1403 uint32_t vcoreid = get_vcoreid(p, pcoreid);
1404 struct event_msg preempt_msg = {0};
1405 /* works with nr_preempts_done to signal completion of a preemption */
1406 p->procinfo->vcoremap[vcoreid].nr_preempts_sent++;
1407 // expects a pcorelist. assumes pcore is mapped and running_m
1408 __proc_take_corelist(p, &pcoreid, 1, TRUE);
1409 /* Only send the message if we have an online core. o/w, it would fuck
1410 * us up (deadlock), and hey don't need a message. the core we just took
1411 * will be the first one to be restarted. It will look like a notif. in
1412 * the future, we could send the event if we want, but the caller needs to
1413 * do that (after unlocking). */
1414 if (!TAILQ_EMPTY(&p->online_vcs)) {
1415 preempt_msg.ev_type = EV_VCORE_PREEMPT;
1416 preempt_msg.ev_arg2 = vcoreid;
1417 send_kernel_event(p, &preempt_msg, 0);
1421 /* Raw function to preempt every vcore. If you care about locking, do it before
1423 uint32_t __proc_preempt_all(struct proc *p, uint32_t *pc_arr)
1426 /* TODO:(BULK) PREEMPT - don't bother with this, set a proc wide flag, or
1427 * just make us RUNNABLE_M. Note this is also used by __map_vcore. */
1428 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1429 vc_i->nr_preempts_sent++;
1430 return __proc_take_allcores(p, pc_arr, TRUE);
1433 /* Warns and preempts a vcore from p. No delaying / alarming, or anything. The
1434 * warning will be for u usec from now. Returns TRUE if the core belonged to
1435 * the proc (and thus preempted), False if the proc no longer has the core. */
1436 bool proc_preempt_core(struct proc *p, uint32_t pcoreid, uint64_t usec)
1438 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1439 bool retval = FALSE;
1440 if (p->state != PROC_RUNNING_M) {
1441 /* more of an FYI for brho. should be harmless to just return. */
1442 warn("Tried to preempt from a non RUNNING_M proc!");
1445 spin_lock(&p->proc_lock);
1446 if (is_mapped_vcore(p, pcoreid)) {
1447 __proc_preempt_warn(p, get_vcoreid(p, pcoreid), warn_time);
1448 __proc_preempt_core(p, pcoreid);
1449 /* we might have taken the last core */
1450 if (!p->procinfo->num_vcores)
1451 __proc_set_state(p, PROC_RUNNABLE_M);
1454 spin_unlock(&p->proc_lock);
1458 /* Warns and preempts all from p. No delaying / alarming, or anything. The
1459 * warning will be for u usec from now. */
1460 void proc_preempt_all(struct proc *p, uint64_t usec)
1462 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1463 uint32_t num_revoked = 0;
1464 spin_lock(&p->proc_lock);
1465 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
1466 uint32_t pc_arr[p->procinfo->num_vcores];
1467 /* DYING could be okay */
1468 if (p->state != PROC_RUNNING_M) {
1469 warn("Tried to preempt from a non RUNNING_M proc!");
1470 spin_unlock(&p->proc_lock);
1473 __proc_preempt_warnall(p, warn_time);
1474 num_revoked = __proc_preempt_all(p, pc_arr);
1475 assert(!p->procinfo->num_vcores);
1476 __proc_set_state(p, PROC_RUNNABLE_M);
1477 spin_unlock(&p->proc_lock);
1478 /* TODO: when we revise this func, look at __put_idle */
1479 /* Return the cores to the ksched */
1481 __sched_put_idle_cores(p, pc_arr, num_revoked);
1484 /* Give the specific pcore to proc p. Lots of assumptions, so don't really use
1485 * this. The proc needs to be _M and prepared for it. the pcore needs to be
1487 void proc_give(struct proc *p, uint32_t pcoreid)
1489 warn("Your idlecoremap is now screwed up"); /* TODO (IDLE) */
1490 spin_lock(&p->proc_lock);
1491 // expects a pcorelist, we give it a list of one
1492 __proc_give_cores(p, &pcoreid, 1);
1493 spin_unlock(&p->proc_lock);
1496 /* Global version of the helper, for sys_get_vcoreid (might phase that syscall
1498 uint32_t proc_get_vcoreid(struct proc *p)
1500 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1501 if (pcpui->owning_proc == p) {
1502 return pcpui->owning_vcoreid;
1504 warn("Asked for vcoreid for %p, but %p is pwns", p, pcpui->owning_proc);
1505 return (uint32_t)-1;
1509 /* TODO: make all of these static inlines when we gut the env crap */
1510 bool vcore_is_mapped(struct proc *p, uint32_t vcoreid)
1512 return p->procinfo->vcoremap[vcoreid].valid;
1515 /* Can do this, or just create a new field and save it in the vcoremap */
1516 uint32_t vcore2vcoreid(struct proc *p, struct vcore *vc)
1518 return (vc - p->procinfo->vcoremap);
1521 struct vcore *vcoreid2vcore(struct proc *p, uint32_t vcoreid)
1523 return &p->procinfo->vcoremap[vcoreid];
1526 /********** Core granting (bulk and single) ***********/
1528 /* Helper: gives pcore to the process, mapping it to the next available vcore
1529 * from list vc_list. Returns TRUE if we succeeded (non-empty). If you pass in
1530 * **vc, we'll tell you which vcore it was. */
1531 static bool __proc_give_a_pcore(struct proc *p, uint32_t pcore,
1532 struct vcore_tailq *vc_list, struct vcore **vc)
1534 struct vcore *new_vc;
1535 new_vc = TAILQ_FIRST(vc_list);
1538 printd("setting vcore %d to pcore %d\n", vcore2vcoreid(p, new_vc),
1540 TAILQ_REMOVE(vc_list, new_vc, list);
1541 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1542 __map_vcore(p, vcore2vcoreid(p, new_vc), pcore);
1548 static void __proc_give_cores_runnable(struct proc *p, uint32_t *pc_arr,
1551 assert(p->state == PROC_RUNNABLE_M);
1552 assert(num); /* catch bugs */
1553 /* add new items to the vcoremap */
1554 __seq_start_write(&p->procinfo->coremap_seqctr);/* unncessary if offline */
1555 p->procinfo->num_vcores += num;
1556 for (int i = 0; i < num; i++) {
1557 /* Try from the bulk list first */
1558 if (__proc_give_a_pcore(p, pc_arr[i], &p->bulk_preempted_vcs, 0))
1560 /* o/w, try from the inactive list. at one point, i thought there might
1561 * be a legit way in which the inactive list could be empty, but that i
1562 * wanted to catch it via an assert. */
1563 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, 0));
1565 __seq_end_write(&p->procinfo->coremap_seqctr);
1568 static void __proc_give_cores_running(struct proc *p, uint32_t *pc_arr,
1572 /* Up the refcnt, since num cores are going to start using this
1573 * process and have it loaded in their owning_proc and 'current'. */
1574 proc_incref(p, num * 2); /* keep in sync with __startcore */
1575 __seq_start_write(&p->procinfo->coremap_seqctr);
1576 p->procinfo->num_vcores += num;
1577 assert(TAILQ_EMPTY(&p->bulk_preempted_vcs));
1578 for (int i = 0; i < num; i++) {
1579 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, &vc_i));
1580 send_kernel_message(pc_arr[i], __startcore, (long)p,
1581 (long)vcore2vcoreid(p, vc_i),
1582 (long)vc_i->nr_preempts_sent, KMSG_ROUTINE);
1584 __seq_end_write(&p->procinfo->coremap_seqctr);
1587 /* Gives process p the additional num cores listed in pcorelist. If the proc is
1588 * not RUNNABLE_M or RUNNING_M, this will fail and allocate none of the core
1589 * (and return -1). If you're RUNNING_M, this will startup your new cores at
1590 * the entry point with their virtual IDs (or restore a preemption). If you're
1591 * RUNNABLE_M, you should call __proc_run_m after this so that the process can
1592 * start to use its cores. In either case, this returns 0.
1594 * If you're *_S, make sure your core0's TF is set (which is done when coming in
1595 * via arch/trap.c and we are RUNNING_S), change your state, then call this.
1596 * Then call __proc_run_m().
1598 * The reason I didn't bring the _S cases from core_request over here is so we
1599 * can keep this family of calls dealing with only *_Ms, to avoiding caring if
1600 * this is called from another core, and to avoid the _S -> _M transition.
1602 * WARNING: You must hold the proc_lock before calling this! */
1603 int __proc_give_cores(struct proc *p, uint32_t *pc_arr, uint32_t num)
1605 /* should never happen: */
1606 assert(num + p->procinfo->num_vcores <= MAX_NUM_CORES);
1608 case (PROC_RUNNABLE_S):
1609 case (PROC_RUNNING_S):
1610 warn("Don't give cores to a process in a *_S state!\n");
1613 case (PROC_WAITING):
1614 /* can't accept, just fail */
1616 case (PROC_RUNNABLE_M):
1617 __proc_give_cores_runnable(p, pc_arr, num);
1619 case (PROC_RUNNING_M):
1620 __proc_give_cores_running(p, pc_arr, num);
1623 panic("Weird state(%s) in %s()", procstate2str(p->state),
1626 /* TODO: considering moving to the ksched (hard, due to yield) */
1627 p->procinfo->res_grant[RES_CORES] += num;
1631 /********** Core revocation (bulk and single) ***********/
1633 /* Revokes a single vcore from a process (unmaps or sends a KMSG to unmap). */
1634 static void __proc_revoke_core(struct proc *p, uint32_t vcoreid, bool preempt)
1636 uint32_t pcoreid = get_pcoreid(p, vcoreid);
1637 struct preempt_data *vcpd;
1639 /* Lock the vcore's state (necessary for preemption recovery) */
1640 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1641 atomic_or(&vcpd->flags, VC_K_LOCK);
1642 send_kernel_message(pcoreid, __preempt, (long)p, 0, 0, KMSG_ROUTINE);
1644 send_kernel_message(pcoreid, __death, 0, 0, 0, KMSG_ROUTINE);
1648 /* Revokes all cores from the process (unmaps or sends a KMSGS). */
1649 static void __proc_revoke_allcores(struct proc *p, bool preempt)
1652 /* TODO: if we ever get broadcast messaging, use it here (still need to lock
1653 * the vcores' states for preemption) */
1654 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1655 __proc_revoke_core(p, vcore2vcoreid(p, vc_i), preempt);
1658 /* Might be faster to scan the vcoremap than to walk the list... */
1659 static void __proc_unmap_allcores(struct proc *p)
1662 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1663 __unmap_vcore(p, vcore2vcoreid(p, vc_i));
1666 /* Takes (revoke via kmsg or unmap) from process p the num cores listed in
1667 * pc_arr. Will preempt if 'preempt' is set. o/w, no state will be saved, etc.
1668 * Don't use this for taking all of a process's cores.
1670 * Make sure you hold the lock when you call this, and make sure that the pcore
1671 * actually belongs to the proc, non-trivial due to other __preempt messages. */
1672 void __proc_take_corelist(struct proc *p, uint32_t *pc_arr, uint32_t num,
1677 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1678 __seq_start_write(&p->procinfo->coremap_seqctr);
1679 for (int i = 0; i < num; i++) {
1680 vcoreid = get_vcoreid(p, pc_arr[i]);
1682 assert(pc_arr[i] == get_pcoreid(p, vcoreid));
1683 /* Revoke / unmap core */
1684 if (p->state == PROC_RUNNING_M)
1685 __proc_revoke_core(p, vcoreid, preempt);
1686 __unmap_vcore(p, vcoreid);
1687 /* Change lists for the vcore. Note, the vcore is already unmapped
1688 * and/or the messages are already in flight. The only code that looks
1689 * at the lists without holding the lock is event code. */
1690 vc = vcoreid2vcore(p, vcoreid);
1691 TAILQ_REMOVE(&p->online_vcs, vc, list);
1692 /* even for single preempts, we use the inactive list. bulk preempt is
1693 * only used for when we take everything. */
1694 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1696 p->procinfo->num_vcores -= num;
1697 __seq_end_write(&p->procinfo->coremap_seqctr);
1698 p->procinfo->res_grant[RES_CORES] -= num;
1701 /* Takes all cores from a process (revoke via kmsg or unmap), putting them on
1702 * the appropriate vcore list, and fills pc_arr with the pcores revoked, and
1703 * returns the number of entries in pc_arr.
1705 * Make sure pc_arr is big enough to handle num_vcores().
1706 * Make sure you hold the lock when you call this. */
1707 uint32_t __proc_take_allcores(struct proc *p, uint32_t *pc_arr, bool preempt)
1709 struct vcore *vc_i, *vc_temp;
1711 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1712 __seq_start_write(&p->procinfo->coremap_seqctr);
1713 /* Write out which pcores we're going to take */
1714 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1715 pc_arr[num++] = vc_i->pcoreid;
1716 /* Revoke if they are running, and unmap. Both of these need the online
1717 * list to not be changed yet. */
1718 if (p->state == PROC_RUNNING_M)
1719 __proc_revoke_allcores(p, preempt);
1720 __proc_unmap_allcores(p);
1721 /* Move the vcores from online to the head of the appropriate list */
1722 TAILQ_FOREACH_SAFE(vc_i, &p->online_vcs, list, vc_temp) {
1723 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that */
1724 TAILQ_REMOVE(&p->online_vcs, vc_i, list);
1725 /* Put the cores on the appropriate list */
1727 TAILQ_INSERT_HEAD(&p->bulk_preempted_vcs, vc_i, list);
1729 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
1731 assert(TAILQ_EMPTY(&p->online_vcs));
1732 assert(num == p->procinfo->num_vcores);
1733 p->procinfo->num_vcores = 0;
1734 __seq_end_write(&p->procinfo->coremap_seqctr);
1735 p->procinfo->res_grant[RES_CORES] = 0;
1739 /* Helper to do the vcore->pcore and inverse mapping. Hold the lock when
1741 void __map_vcore(struct proc *p, uint32_t vcoreid, uint32_t pcoreid)
1743 p->procinfo->vcoremap[vcoreid].pcoreid = pcoreid;
1744 p->procinfo->vcoremap[vcoreid].valid = TRUE;
1745 p->procinfo->pcoremap[pcoreid].vcoreid = vcoreid;
1746 p->procinfo->pcoremap[pcoreid].valid = TRUE;
1749 /* Helper to unmap the vcore->pcore and inverse mapping. Hold the lock when
1751 void __unmap_vcore(struct proc *p, uint32_t vcoreid)
1753 p->procinfo->pcoremap[p->procinfo->vcoremap[vcoreid].pcoreid].valid = FALSE;
1754 p->procinfo->vcoremap[vcoreid].valid = FALSE;
1757 /* Stop running whatever context is on this core and load a known-good cr3.
1758 * Note this leaves no trace of what was running. This "leaves the process's
1761 * This does not clear the owning proc. Use the other helper for that. */
1762 void abandon_core(void)
1764 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1765 /* Syscalls that don't return will ultimately call abadon_core(), so we need
1766 * to make sure we don't think we are still working on a syscall. */
1767 pcpui->cur_kthread->sysc = 0;
1768 pcpui->cur_kthread->errbuf = 0; /* just in case */
1769 if (pcpui->cur_proc)
1773 /* Helper to clear the core's owning processor and manage refcnting. Pass in
1774 * core_id() to save a couple core_id() calls. */
1775 void clear_owning_proc(uint32_t coreid)
1777 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1778 struct proc *p = pcpui->owning_proc;
1779 pcpui->owning_proc = 0;
1780 pcpui->owning_vcoreid = 0xdeadbeef;
1781 pcpui->cur_ctx = 0; /* catch bugs for now (may go away) */
1786 /* Switches to the address space/context of new_p, doing nothing if we are
1787 * already in new_p. This won't add extra refcnts or anything, and needs to be
1788 * paired with switch_back() at the end of whatever function you are in. Don't
1789 * migrate cores in the middle of a pair. Specifically, the uncounted refs are
1790 * one for the old_proc, which is passed back to the caller, and new_p is
1791 * getting placed in cur_proc. */
1792 struct proc *switch_to(struct proc *new_p)
1794 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1795 struct proc *old_proc;
1796 old_proc = pcpui->cur_proc; /* uncounted ref */
1797 /* If we aren't the proc already, then switch to it */
1798 if (old_proc != new_p) {
1799 pcpui->cur_proc = new_p; /* uncounted ref */
1801 lcr3(new_p->env_cr3);
1808 /* This switches back to old_proc from new_p. Pair it with switch_to(), and
1809 * pass in its return value for old_proc. */
1810 void switch_back(struct proc *new_p, struct proc *old_proc)
1812 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1813 if (old_proc != new_p) {
1814 pcpui->cur_proc = old_proc;
1816 lcr3(old_proc->env_cr3);
1822 /* Will send a TLB shootdown message to every vcore in the main address space
1823 * (aka, all vcores for now). The message will take the start and end virtual
1824 * addresses as well, in case we want to be more clever about how much we
1825 * shootdown and batching our messages. Should do the sanity about rounding up
1826 * and down in this function too.
1828 * Would be nice to have a broadcast kmsg at this point. Note this may send a
1829 * message to the calling core (interrupting it, possibly while holding the
1830 * proc_lock). We don't need to process routine messages since it's an
1831 * immediate message. */
1832 void proc_tlbshootdown(struct proc *p, uintptr_t start, uintptr_t end)
1834 /* TODO: need a better way to find cores running our address space. we can
1835 * have kthreads running syscalls, async calls, processes being created. */
1837 /* TODO: we might be able to avoid locking here in the future (we must hit
1838 * all online, and we can check __mapped). it'll be complicated. */
1839 spin_lock(&p->proc_lock);
1841 case (PROC_RUNNING_S):
1844 case (PROC_RUNNING_M):
1845 /* TODO: (TLB) sanity checks and rounding on the ranges */
1846 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
1847 send_kernel_message(vc_i->pcoreid, __tlbshootdown, start, end,
1852 /* TODO: til we fix shootdowns, there are some odd cases where we
1853 * have the address space loaded, but the state is in transition. */
1857 spin_unlock(&p->proc_lock);
1860 /* Helper, used by __startcore and __set_curctx, which sets up cur_ctx to run a
1861 * given process's vcore. Caller needs to set up things like owning_proc and
1862 * whatnot. Note that we might not have p loaded as current. */
1863 static void __set_curctx_to_vcoreid(struct proc *p, uint32_t vcoreid,
1864 uint32_t old_nr_preempts_sent)
1866 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1867 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1868 struct vcore *vc = vcoreid2vcore(p, vcoreid);
1869 /* Spin until our vcore's old preemption is done. When __SC was sent, we
1870 * were told what the nr_preempts_sent was at that time. Once that many are
1871 * done, it is time for us to run. This forces a 'happens-before' ordering
1872 * on a __PR of our VC before this __SC of the VC. Note the nr_done should
1873 * not exceed old_nr_sent, since further __PR are behind this __SC in the
1875 while (old_nr_preempts_sent != vc->nr_preempts_done)
1877 cmb(); /* read nr_done before any other rd or wr. CPU mb in the atomic. */
1878 /* Mark that this vcore as no longer preempted. No danger of clobbering
1879 * other writes, since this would get turned on in __preempt (which can't be
1880 * concurrent with this function on this core), and the atomic is just
1881 * toggling the one bit (a concurrent VC_K_LOCK will work) */
1882 atomic_and(&vcpd->flags, ~VC_PREEMPTED);
1883 /* Once the VC is no longer preempted, we allow it to receive msgs. We
1884 * could let userspace do it, but handling it here makes it easier for them
1885 * to handle_indirs (when they turn this flag off). Note the atomics
1886 * provide the needed barriers (cmb and mb on flags). */
1887 atomic_or(&vcpd->flags, VC_CAN_RCV_MSG);
1888 printd("[kernel] startcore on physical core %d for process %d's vcore %d\n",
1889 core_id(), p->pid, vcoreid);
1890 /* If notifs are disabled, the vcore was in vcore context and we need to
1891 * restart the vcore_ctx. o/w, we give them a fresh vcore (which is also
1892 * what happens the first time a vcore comes online). No matter what,
1893 * they'll restart in vcore context. It's just a matter of whether or not
1894 * it is the old, interrupted vcore context. */
1895 if (vcpd->notif_disabled) {
1896 /* copy-in the tf we'll pop, then set all security-related fields */
1897 pcpui->actual_ctx = vcpd->vcore_ctx;
1898 proc_secure_ctx(&pcpui->actual_ctx);
1899 } else { /* not restarting from a preemption, use a fresh vcore */
1900 assert(vcpd->vcore_stack);
1901 proc_init_ctx(&pcpui->actual_ctx, vcoreid, vcpd->vcore_entry,
1902 vcpd->vcore_stack, vcpd->vcore_tls_desc);
1903 /* Disable/mask active notifications for fresh vcores */
1904 vcpd->notif_disabled = TRUE;
1906 /* Regardless of whether or not we have a 'fresh' VC, we need to restore the
1907 * FPU state for the VC according to VCPD (which means either a saved FPU
1908 * state or a brand new init). Starting a fresh VC is just referring to the
1909 * GP context we run. The vcore itself needs to have the FPU state loaded
1910 * from when it previously ran and was saved (or a fresh FPU if it wasn't
1911 * saved). For fresh FPUs, the main purpose is for limiting info leakage.
1912 * I think VCs that don't need FPU state for some reason (like having a
1913 * current_uthread) can handle any sort of FPU state, since it gets sorted
1914 * when they pop their next uthread.
1916 * Note this can cause a GP fault on x86 if the state is corrupt. In lieu
1917 * of reading in the huge FP state and mucking with mxcsr_mask, we should
1918 * handle this like a KPF on user code. */
1919 restore_vc_fp_state(vcpd);
1920 /* cur_ctx was built above (in actual_ctx), now use it */
1921 pcpui->cur_ctx = &pcpui->actual_ctx;
1922 /* this cur_ctx will get run when the kernel returns / idles */
1923 vcore_account_online(p, vcoreid);
1926 /* Changes calling vcore to be vcoreid. enable_my_notif tells us about how the
1927 * state calling vcore wants to be left in. It will look like caller_vcoreid
1928 * was preempted. Note we don't care about notif_pending.
1931 * 0 if we successfully changed to the target vcore.
1932 * -EBUSY if the target vcore is already mapped (a good kind of failure)
1933 * -EAGAIN if we failed for some other reason and need to try again. For
1934 * example, the caller could be preempted, and we never even attempted to
1936 * -EINVAL some userspace bug */
1937 int proc_change_to_vcore(struct proc *p, uint32_t new_vcoreid,
1938 bool enable_my_notif)
1940 uint32_t caller_vcoreid, pcoreid = core_id();
1941 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1942 struct preempt_data *caller_vcpd;
1943 struct vcore *caller_vc, *new_vc;
1944 struct event_msg preempt_msg = {0};
1945 int retval = -EAGAIN; /* by default, try again */
1946 /* Need to not reach outside the vcoremap, which might be smaller in the
1947 * future, but should always be as big as max_vcores */
1948 if (new_vcoreid >= p->procinfo->max_vcores)
1950 /* Need to lock to prevent concurrent vcore changes, like in yield. */
1951 spin_lock(&p->proc_lock);
1952 /* new_vcoreid is already runing, abort */
1953 if (vcore_is_mapped(p, new_vcoreid)) {
1957 /* Need to make sure our vcore is allowed to switch. We might have a
1958 * __preempt, __death, etc, coming in. Similar to yield. */
1960 case (PROC_RUNNING_M):
1961 break; /* the only case we can proceed */
1962 case (PROC_RUNNING_S): /* user bug, just return */
1963 case (PROC_DYING): /* incoming __death */
1964 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1967 panic("Weird state(%s) in %s()", procstate2str(p->state),
1970 /* This is which vcore this pcore thinks it is, regardless of any unmappings
1971 * that may have happened remotely (with __PRs waiting to run) */
1972 caller_vcoreid = pcpui->owning_vcoreid;
1973 caller_vc = vcoreid2vcore(p, caller_vcoreid);
1974 caller_vcpd = &p->procdata->vcore_preempt_data[caller_vcoreid];
1975 /* This is how we detect whether or not a __PR happened. If it did, just
1976 * abort and handle the kmsg. No new __PRs are coming since we hold the
1977 * lock. This also detects a __PR followed by a __SC for the same VC. */
1978 if (caller_vc->nr_preempts_sent != caller_vc->nr_preempts_done)
1980 /* Sanity checks. If we were preempted or are dying, we should have noticed
1982 assert(is_mapped_vcore(p, pcoreid));
1983 assert(caller_vcoreid == get_vcoreid(p, pcoreid));
1984 /* Should only call from vcore context */
1985 if (!caller_vcpd->notif_disabled) {
1987 printk("[kernel] You tried to change vcores from uthread ctx\n");
1990 /* Ok, we're clear to do the switch. Lets figure out who the new one is */
1991 new_vc = vcoreid2vcore(p, new_vcoreid);
1992 printd("[kernel] changing vcore %d to vcore %d\n", caller_vcoreid,
1994 /* enable_my_notif signals how we'll be restarted */
1995 if (enable_my_notif) {
1996 /* if they set this flag, then the vcore can just restart from scratch,
1997 * and we don't care about either the uthread_ctx or the vcore_ctx. */
1998 caller_vcpd->notif_disabled = FALSE;
1999 /* Don't need to save the FPU. There should be no uthread or other
2000 * reason to return to the FPU state. */
2002 /* need to set up the calling vcore's ctx so that it'll get restarted by
2003 * __startcore, to make the caller look like it was preempted. */
2004 caller_vcpd->vcore_ctx = *current_ctx;
2005 save_vc_fp_state(caller_vcpd);
2007 /* Mark our core as preempted (for userspace recovery). Userspace checks
2008 * this in handle_indirs, and it needs to check the mbox regardless of
2009 * enable_my_notif. This does mean cores that change-to with no intent to
2010 * return will be tracked as PREEMPTED until they start back up (maybe
2012 atomic_or(&caller_vcpd->flags, VC_PREEMPTED);
2013 /* Either way, unmap and offline our current vcore */
2014 /* Move the caller from online to inactive */
2015 TAILQ_REMOVE(&p->online_vcs, caller_vc, list);
2016 /* We don't bother with the notif_pending race. note that notif_pending
2017 * could still be set. this was a preempted vcore, and userspace will need
2018 * to deal with missed messages (preempt_recover() will handle that) */
2019 TAILQ_INSERT_HEAD(&p->inactive_vcs, caller_vc, list);
2020 /* Move the new one from inactive to online */
2021 TAILQ_REMOVE(&p->inactive_vcs, new_vc, list);
2022 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
2023 /* Change the vcore map */
2024 __seq_start_write(&p->procinfo->coremap_seqctr);
2025 __unmap_vcore(p, caller_vcoreid);
2026 __map_vcore(p, new_vcoreid, pcoreid);
2027 __seq_end_write(&p->procinfo->coremap_seqctr);
2028 vcore_account_offline(p, caller_vcoreid);
2029 /* Send either a PREEMPT msg or a CHECK_MSGS msg. If they said to
2030 * enable_my_notif, then all userspace needs is to check messages, not a
2031 * full preemption recovery. */
2032 preempt_msg.ev_type = (enable_my_notif ? EV_CHECK_MSGS : EV_VCORE_PREEMPT);
2033 preempt_msg.ev_arg2 = caller_vcoreid; /* arg2 is 32 bits */
2034 /* Whenever we send msgs with the proc locked, we need at least 1 online.
2035 * In this case, it's the one we just changed to. */
2036 assert(!TAILQ_EMPTY(&p->online_vcs));
2037 send_kernel_event(p, &preempt_msg, new_vcoreid);
2038 /* So this core knows which vcore is here. (cur_proc and owning_proc are
2039 * already correct): */
2040 pcpui->owning_vcoreid = new_vcoreid;
2041 /* Until we set_curctx, we don't really have a valid current tf. The stuff
2042 * in that old one is from our previous vcore, not the current
2043 * owning_vcoreid. This matters for other KMSGS that will run before
2044 * __set_curctx (like __notify). */
2046 /* Need to send a kmsg to finish. We can't set_curctx til the __PR is done,
2047 * but we can't spin right here while holding the lock (can't spin while
2048 * waiting on a message, roughly) */
2049 send_kernel_message(pcoreid, __set_curctx, (long)p, (long)new_vcoreid,
2050 (long)new_vc->nr_preempts_sent, KMSG_ROUTINE);
2052 /* Fall through to exit */
2054 spin_unlock(&p->proc_lock);
2058 /* Kernel message handler to start a process's context on this core, when the
2059 * core next considers running a process. Tightly coupled with __proc_run_m().
2060 * Interrupts are disabled. */
2061 void __startcore(uint32_t srcid, long a0, long a1, long a2)
2063 uint32_t vcoreid = (uint32_t)a1;
2064 uint32_t coreid = core_id();
2065 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2066 struct proc *p_to_run = (struct proc *)a0;
2067 uint32_t old_nr_preempts_sent = (uint32_t)a2;
2070 /* Can not be any TF from a process here already */
2071 assert(!pcpui->owning_proc);
2072 /* the sender of the kmsg increfed already for this saved ref to p_to_run */
2073 pcpui->owning_proc = p_to_run;
2074 pcpui->owning_vcoreid = vcoreid;
2075 /* sender increfed again, assuming we'd install to cur_proc. only do this
2076 * if no one else is there. this is an optimization, since we expect to
2077 * send these __startcores to idles cores, and this saves a scramble to
2078 * incref when all of the cores restartcore/startcore later. Keep in sync
2079 * with __proc_give_cores() and __proc_run_m(). */
2080 if (!pcpui->cur_proc) {
2081 pcpui->cur_proc = p_to_run; /* install the ref to cur_proc */
2082 lcr3(p_to_run->env_cr3); /* load the page tables to match cur_proc */
2084 proc_decref(p_to_run); /* can't install, decref the extra one */
2086 /* Note we are not necessarily in the cr3 of p_to_run */
2087 /* Now that we sorted refcnts and know p / which vcore it should be, set up
2088 * pcpui->cur_ctx so that it will run that particular vcore */
2089 __set_curctx_to_vcoreid(p_to_run, vcoreid, old_nr_preempts_sent);
2092 /* Kernel message handler to load a proc's vcore context on this core. Similar
2093 * to __startcore, except it is used when p already controls the core (e.g.
2094 * change_to). Since the core is already controlled, pcpui such as owning proc,
2095 * vcoreid, and cur_proc are all already set. */
2096 void __set_curctx(uint32_t srcid, long a0, long a1, long a2)
2098 struct proc *p = (struct proc*)a0;
2099 uint32_t vcoreid = (uint32_t)a1;
2100 uint32_t old_nr_preempts_sent = (uint32_t)a2;
2101 __set_curctx_to_vcoreid(p, vcoreid, old_nr_preempts_sent);
2104 /* Bail out if it's the wrong process, or if they no longer want a notif. Try
2105 * not to grab locks or write access to anything that isn't per-core in here. */
2106 void __notify(uint32_t srcid, long a0, long a1, long a2)
2108 uint32_t vcoreid, coreid = core_id();
2109 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2110 struct preempt_data *vcpd;
2111 struct proc *p = (struct proc*)a0;
2113 /* Not the right proc */
2114 if (p != pcpui->owning_proc)
2116 /* the core might be owned, but not have a valid cur_ctx (if we're in the
2117 * process of changing */
2118 if (!pcpui->cur_ctx)
2120 /* Common cur_ctx sanity checks. Note cur_ctx could be an _S's scp_ctx */
2121 vcoreid = pcpui->owning_vcoreid;
2122 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
2123 /* for SCPs that haven't (and might never) call vc_event_init, like rtld.
2124 * this is harmless for MCPS to check this */
2125 if (!scp_is_vcctx_ready(vcpd))
2127 printd("received active notification for proc %d's vcore %d on pcore %d\n",
2128 p->procinfo->pid, vcoreid, coreid);
2129 /* sort signals. notifs are now masked, like an interrupt gate */
2130 if (vcpd->notif_disabled)
2132 vcpd->notif_disabled = TRUE;
2133 /* save the old ctx in the uthread slot, build and pop a new one. Note that
2134 * silly state isn't our business for a notification. */
2135 vcpd->uthread_ctx = *pcpui->cur_ctx;
2136 memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
2137 proc_init_ctx(pcpui->cur_ctx, vcoreid, vcpd->vcore_entry,
2138 vcpd->vcore_stack, vcpd->vcore_tls_desc);
2139 /* this cur_ctx will get run when the kernel returns / idles */
2142 void __preempt(uint32_t srcid, long a0, long a1, long a2)
2144 uint32_t vcoreid, coreid = core_id();
2145 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2146 struct preempt_data *vcpd;
2147 struct proc *p = (struct proc*)a0;
2150 if (p != pcpui->owning_proc) {
2151 panic("__preempt arrived for a process (%p) that was not owning (%p)!",
2152 p, pcpui->owning_proc);
2154 /* Common cur_ctx sanity checks */
2155 assert(pcpui->cur_ctx);
2156 assert(pcpui->cur_ctx == &pcpui->actual_ctx);
2157 vcoreid = pcpui->owning_vcoreid;
2158 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
2159 printd("[kernel] received __preempt for proc %d's vcore %d on pcore %d\n",
2160 p->procinfo->pid, vcoreid, coreid);
2161 /* if notifs are disabled, the vcore is in vcore context (as far as we're
2162 * concerned), and we save it in the vcore slot. o/w, we save the process's
2163 * cur_ctx in the uthread slot, and it'll appear to the vcore when it comes
2164 * back up the uthread just took a notification. */
2165 if (vcpd->notif_disabled)
2166 vcpd->vcore_ctx = *pcpui->cur_ctx;
2168 vcpd->uthread_ctx = *pcpui->cur_ctx;
2169 /* Userspace in a preemption handler on another core might be copying FP
2170 * state from memory (VCPD) at the moment, and if so we don't want to
2171 * clobber it. In this rare case, our current core's FPU state should be
2172 * the same as whatever is in VCPD, so this shouldn't be necessary, but the
2173 * arch-specific save function might do something other than write out
2174 * bit-for-bit the exact same data. Checking STEALING suffices, since we
2175 * hold the K_LOCK (preventing userspace from starting a fresh STEALING
2176 * phase concurrently). */
2177 if (!(atomic_read(&vcpd->flags) & VC_UTHREAD_STEALING))
2178 save_vc_fp_state(vcpd);
2179 /* Mark the vcore as preempted and unlock (was locked by the sender). */
2180 atomic_or(&vcpd->flags, VC_PREEMPTED);
2181 atomic_and(&vcpd->flags, ~VC_K_LOCK);
2182 /* either __preempt or proc_yield() ends the preempt phase. */
2183 p->procinfo->vcoremap[vcoreid].preempt_pending = 0;
2184 vcore_account_offline(p, vcoreid);
2185 wmb(); /* make sure everything else hits before we finish the preempt */
2186 /* up the nr_done, which signals the next __startcore for this vc */
2187 p->procinfo->vcoremap[vcoreid].nr_preempts_done++;
2188 /* We won't restart the process later. current gets cleared later when we
2189 * notice there is no owning_proc and we have nothing to do (smp_idle,
2190 * restartcore, etc) */
2191 clear_owning_proc(coreid);
2194 /* Kernel message handler to clean up the core when a process is dying.
2195 * Note this leaves no trace of what was running.
2196 * It's okay if death comes to a core that's already idling and has no current.
2197 * It could happen if a process decref'd before __proc_startcore could incref. */
2198 void __death(uint32_t srcid, long a0, long a1, long a2)
2200 uint32_t vcoreid, coreid = core_id();
2201 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2202 struct proc *p = pcpui->owning_proc;
2204 vcoreid = pcpui->owning_vcoreid;
2205 printd("[kernel] death on physical core %d for process %d's vcore %d\n",
2206 coreid, p->pid, vcoreid);
2207 vcore_account_offline(p, vcoreid); /* in case anyone is counting */
2208 /* We won't restart the process later. current gets cleared later when
2209 * we notice there is no owning_proc and we have nothing to do
2210 * (smp_idle, restartcore, etc) */
2211 clear_owning_proc(coreid);
2215 /* Kernel message handler, usually sent IMMEDIATE, to shoot down virtual
2216 * addresses from a0 to a1. */
2217 void __tlbshootdown(uint32_t srcid, long a0, long a1, long a2)
2219 /* TODO: (TLB) something more intelligent with the range */
2223 void print_allpids(void)
2225 void print_proc_state(void *item)
2227 struct proc *p = (struct proc*)item;
2229 /* this actually adds an extra space, since no progname is ever
2230 * PROGNAME_SZ bytes, due to the \0 counted in PROGNAME. */
2231 printk("%8d %-*s %-10s %6d\n", p->pid, PROC_PROGNAME_SZ, p->progname,
2232 procstate2str(p->state), p->ppid);
2234 char dashes[PROC_PROGNAME_SZ];
2235 memset(dashes, '-', PROC_PROGNAME_SZ);
2236 dashes[PROC_PROGNAME_SZ - 1] = '\0';
2237 /* -5, for 'Name ' */
2238 printk(" PID Name %-*s State Parent \n",
2239 PROC_PROGNAME_SZ - 5, "");
2240 printk("------------------------------%s\n", dashes);
2241 spin_lock(&pid_hash_lock);
2242 hash_for_each(pid_hash, print_proc_state);
2243 spin_unlock(&pid_hash_lock);
2246 void print_proc_info(pid_t pid)
2249 uint64_t total_time = 0;
2250 struct proc *child, *p = pid2proc(pid);
2253 printk("Bad PID.\n");
2256 spinlock_debug(&p->proc_lock);
2257 //spin_lock(&p->proc_lock); // No locking!!
2258 printk("struct proc: %p\n", p);
2259 printk("Program name: %s\n", p->progname);
2260 printk("PID: %d\n", p->pid);
2261 printk("PPID: %d\n", p->ppid);
2262 printk("State: %s (%p)\n", procstate2str(p->state), p->state);
2263 printk("\tIs %san MCP\n", p->procinfo->is_mcp ? "" : "not ");
2264 printk("Refcnt: %d\n", atomic_read(&p->p_kref.refcount) - 1);
2265 printk("Flags: 0x%08x\n", p->env_flags);
2266 printk("CR3(phys): %p\n", p->env_cr3);
2267 printk("Num Vcores: %d\n", p->procinfo->num_vcores);
2268 printk("Vcore Lists (may be in flux w/o locking):\n----------------------\n");
2269 printk("Online:\n");
2270 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
2271 printk("\tVcore %d -> Pcore %d\n", vcore2vcoreid(p, vc_i), vc_i->pcoreid);
2272 printk("Bulk Preempted:\n");
2273 TAILQ_FOREACH(vc_i, &p->bulk_preempted_vcs, list)
2274 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2275 printk("Inactive / Yielded:\n");
2276 TAILQ_FOREACH(vc_i, &p->inactive_vcs, list)
2277 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2278 printk("Nsec Online, up to the last offlining:\n------------------------");
2279 for (int i = 0; i < p->procinfo->max_vcores; i++) {
2280 uint64_t vc_time = tsc2nsec(vcore_account_gettotal(p, i));
2283 printk(" VC %3d: %14llu", i, vc_time);
2284 total_time += vc_time;
2287 printk("Total CPU-NSEC: %llu\n", total_time);
2288 printk("Resources:\n------------------------\n");
2289 for (int i = 0; i < MAX_NUM_RESOURCES; i++)
2290 printk("\tRes type: %02d, amt wanted: %08d, amt granted: %08d\n", i,
2291 p->procdata->res_req[i].amt_wanted, p->procinfo->res_grant[i]);
2292 printk("Open Files:\n");
2293 struct fd_table *files = &p->open_files;
2294 if (spin_locked(&files->lock)) {
2295 spinlock_debug(&files->lock);
2296 printk("FILE LOCK HELD, ABORTING\n");
2300 spin_lock(&files->lock);
2301 for (int i = 0; i < files->max_files; i++) {
2302 if (GET_BITMASK_BIT(files->open_fds->fds_bits, i)) {
2303 printk("\tFD: %02d, ", i);
2304 if (files->fd[i].fd_file) {
2305 printk("File: %p, File name: %s\n", files->fd[i].fd_file,
2306 file_name(files->fd[i].fd_file));
2308 assert(files->fd[i].fd_chan);
2309 print_chaninfo(files->fd[i].fd_chan);
2313 spin_unlock(&files->lock);
2314 printk("Children: (PID (struct proc *))\n");
2315 TAILQ_FOREACH(child, &p->children, sibling_link)
2316 printk("\t%d (%p)\n", child->pid, child);
2317 /* no locking / unlocking or refcnting */
2318 // spin_unlock(&p->proc_lock);
2322 /* Debugging function, checks what (process, vcore) is supposed to run on this
2323 * pcore. Meant to be called from smp_idle() before halting. */
2324 void check_my_owner(void)
2326 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2327 void shazbot(void *item)
2329 struct proc *p = (struct proc*)item;
2332 spin_lock(&p->proc_lock);
2333 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
2334 /* this isn't true, a __startcore could be on the way and we're
2335 * already "online" */
2336 if (vc_i->pcoreid == core_id()) {
2337 /* Immediate message was sent, we should get it when we enable
2338 * interrupts, which should cause us to skip cpu_halt() */
2339 if (!STAILQ_EMPTY(&pcpui->immed_amsgs))
2341 printk("Owned pcore (%d) has no owner, by %p, vc %d!\n",
2342 core_id(), p, vcore2vcoreid(p, vc_i));
2343 spin_unlock(&p->proc_lock);
2344 spin_unlock(&pid_hash_lock);
2348 spin_unlock(&p->proc_lock);
2350 assert(!irq_is_enabled());
2352 if (!booting && !pcpui->owning_proc) {
2353 spin_lock(&pid_hash_lock);
2354 hash_for_each(pid_hash, shazbot);
2355 spin_unlock(&pid_hash_lock);
2359 /* Use this via kfunc */
2360 void print_9ns(void)
2362 void print_proc_9ns(void *item)
2364 struct proc *p = (struct proc*)item;
2367 spin_lock(&pid_hash_lock);
2368 hash_for_each(pid_hash, print_proc_9ns);
2369 spin_unlock(&pid_hash_lock);