1 /* Copyright (c) 2009, 2010 The Regents of the University of California
2 * Barret Rhoden <brho@cs.berkeley.edu>
3 * See LICENSE for details. */
19 #include <hashtable.h>
21 #include <sys/queue.h>
25 #include <arsc_server.h>
29 struct kmem_cache *proc_cache;
31 /* Other helpers, implemented later. */
32 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid);
33 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid);
34 static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid);
35 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid);
36 static void __proc_free(struct kref *kref);
37 static bool scp_is_vcctx_ready(struct preempt_data *vcpd);
38 static void save_vc_fp_state(struct preempt_data *vcpd);
39 static void restore_vc_fp_state(struct preempt_data *vcpd);
42 #define PID_MAX 32767 // goes from 0 to 32767, with 0 reserved
43 static DECL_BITMASK(pid_bmask, PID_MAX + 1);
44 spinlock_t pid_bmask_lock = SPINLOCK_INITIALIZER;
45 struct hashtable *pid_hash;
46 spinlock_t pid_hash_lock; // initialized in proc_init
48 /* Finds the next free entry (zero) entry in the pid_bitmask. Set means busy.
49 * PID 0 is reserved (in proc_init). A return value of 0 is a failure (and
50 * you'll also see a warning, for now). Consider doing this with atomics. */
51 static pid_t get_free_pid(void)
53 static pid_t next_free_pid = 1;
56 spin_lock(&pid_bmask_lock);
57 // atomically (can lock for now, then change to atomic_and_return
58 FOR_CIRC_BUFFER(next_free_pid, PID_MAX + 1, i) {
59 // always points to the next to test
60 next_free_pid = (next_free_pid + 1) % (PID_MAX + 1);
61 if (!GET_BITMASK_BIT(pid_bmask, i)) {
62 SET_BITMASK_BIT(pid_bmask, i);
67 spin_unlock(&pid_bmask_lock);
69 warn("Shazbot! Unable to find a PID! You need to deal with this!\n");
73 /* Return a pid to the pid bitmask */
74 static void put_free_pid(pid_t pid)
76 spin_lock(&pid_bmask_lock);
77 CLR_BITMASK_BIT(pid_bmask, pid);
78 spin_unlock(&pid_bmask_lock);
81 /* 'resume' is the time int ticks of the most recent onlining. 'total' is the
82 * amount of time in ticks consumed up to and including the current offlining.
84 * We could move these to the map and unmap of vcores, though not every place
85 * uses that (SCPs, in particular). However, maps/unmaps happen remotely;
86 * something to consider. If we do it remotely, we can batch them up and do one
87 * rdtsc() for all of them. For now, I want to do them on the core, around when
88 * we do the context change. It'll also parallelize the accounting a bit. */
89 void vcore_account_online(struct proc *p, uint32_t vcoreid)
91 struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
92 vc->resume_ticks = read_tsc();
95 void vcore_account_offline(struct proc *p, uint32_t vcoreid)
97 struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
98 vc->total_ticks += read_tsc() - vc->resume_ticks;
101 uint64_t vcore_account_gettotal(struct proc *p, uint32_t vcoreid)
103 struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
104 return vc->total_ticks;
107 /* While this could be done with just an assignment, this gives us the
108 * opportunity to check for bad transitions. Might compile these out later, so
109 * we shouldn't rely on them for sanity checking from userspace. */
110 int __proc_set_state(struct proc *p, uint32_t state)
112 uint32_t curstate = p->state;
113 /* Valid transitions:
131 * These ought to be implemented later (allowed, not thought through yet).
135 #if 1 // some sort of correctness flag
138 if (!(state & (PROC_RUNNABLE_S | PROC_DYING)))
139 panic("Invalid State Transition! PROC_CREATED to %02x", state);
141 case PROC_RUNNABLE_S:
142 if (!(state & (PROC_RUNNING_S | PROC_DYING)))
143 panic("Invalid State Transition! PROC_RUNNABLE_S to %02x", state);
146 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
148 panic("Invalid State Transition! PROC_RUNNING_S to %02x", state);
151 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNING_S | PROC_RUNNABLE_M |
153 panic("Invalid State Transition! PROC_WAITING to %02x", state);
156 if (state != PROC_CREATED) // when it is reused (TODO)
157 panic("Invalid State Transition! PROC_DYING to %02x", state);
159 case PROC_RUNNABLE_M:
160 if (!(state & (PROC_RUNNING_M | PROC_DYING)))
161 panic("Invalid State Transition! PROC_RUNNABLE_M to %02x", state);
164 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
166 panic("Invalid State Transition! PROC_RUNNING_M to %02x", state);
174 /* Returns a pointer to the proc with the given pid, or 0 if there is none.
175 * This uses get_not_zero, since it is possible the refcnt is 0, which means the
176 * process is dying and we should not have the ref (and thus return 0). We need
177 * to lock to protect us from getting p, (someone else removes and frees p),
178 * then get_not_zero() on p.
179 * Don't push the locking into the hashtable without dealing with this. */
180 struct proc *pid2proc(pid_t pid)
182 spin_lock(&pid_hash_lock);
183 struct proc *p = hashtable_search(pid_hash, (void*)(long)pid);
185 if (!kref_get_not_zero(&p->p_kref, 1))
187 spin_unlock(&pid_hash_lock);
191 /* Used by devproc for successive reads of the proc table.
192 * Returns a pointer to the nth proc, or 0 if there is none.
193 * This uses get_not_zero, since it is possible the refcnt is 0, which means the
194 * process is dying and we should not have the ref (and thus return 0). We need
195 * to lock to protect us from getting p, (someone else removes and frees p),
196 * then get_not_zero() on p.
197 * Don't push the locking into the hashtable without dealing with this. */
198 struct proc *pid_nth(unsigned int n)
201 spin_lock(&pid_hash_lock);
202 if (!hashtable_count(pid_hash)) {
203 spin_unlock(&pid_hash_lock);
206 struct hashtable_itr *iter = hashtable_iterator(pid_hash);
207 p = hashtable_iterator_value(iter);
210 /* if this process is not valid, it doesn't count,
214 if (kref_get_not_zero(&p->p_kref, 1)){
215 /* this one counts */
217 printd("pid_nth: at end, p %p\n", p);
220 kref_put(&p->p_kref);
223 if (!hashtable_iterator_advance(iter)){
227 p = hashtable_iterator_value(iter);
230 spin_unlock(&pid_hash_lock);
235 /* Performs any initialization related to processes, such as create the proc
236 * cache, prep the scheduler, etc. When this returns, we should be ready to use
237 * any process related function. */
240 /* Catch issues with the vcoremap and TAILQ_ENTRY sizes */
241 static_assert(sizeof(TAILQ_ENTRY(vcore)) == sizeof(void*) * 2);
242 proc_cache = kmem_cache_create("proc", sizeof(struct proc),
243 MAX(ARCH_CL_SIZE, __alignof__(struct proc)), 0, 0, 0);
244 /* Init PID mask and hash. pid 0 is reserved. */
245 SET_BITMASK_BIT(pid_bmask, 0);
246 spinlock_init(&pid_hash_lock);
247 spin_lock(&pid_hash_lock);
248 pid_hash = create_hashtable(100, __generic_hash, __generic_eq);
249 spin_unlock(&pid_hash_lock);
252 atomic_init(&num_envs, 0);
255 void proc_set_progname(struct proc *p, char *name)
258 name = DEFAULT_PROGNAME;
260 /* might have an issue if a dentry name isn't null terminated, and we'd get
261 * extra junk up to progname_sz. Or crash. */
262 strlcpy(p->progname, name, PROC_PROGNAME_SZ);
265 void proc_replace_binary_path(struct proc *p, char *path)
268 free_path(p, p->binary_path);
269 p->binary_path = path;
272 /* Be sure you init'd the vcore lists before calling this. */
273 void proc_init_procinfo(struct proc* p)
275 p->procinfo->pid = p->pid;
276 p->procinfo->ppid = p->ppid;
277 p->procinfo->max_vcores = max_vcores(p);
278 p->procinfo->tsc_freq = system_timing.tsc_freq;
279 p->procinfo->timing_overhead = system_timing.timing_overhead;
280 p->procinfo->heap_bottom = 0;
281 /* 0'ing the arguments. Some higher function will need to set them */
282 memset(p->procinfo->res_grant, 0, sizeof(p->procinfo->res_grant));
283 /* 0'ing the vcore/pcore map. Will link the vcores later. */
284 memset(&p->procinfo->vcoremap, 0, sizeof(p->procinfo->vcoremap));
285 memset(&p->procinfo->pcoremap, 0, sizeof(p->procinfo->pcoremap));
286 p->procinfo->num_vcores = 0;
287 p->procinfo->is_mcp = FALSE;
288 p->procinfo->coremap_seqctr = SEQCTR_INITIALIZER;
289 /* It's a bug in the kernel if we let them ask for more than max */
290 for (int i = 0; i < p->procinfo->max_vcores; i++) {
291 TAILQ_INSERT_TAIL(&p->inactive_vcs, &p->procinfo->vcoremap[i], list);
295 void proc_init_procdata(struct proc *p)
297 memset(p->procdata, 0, sizeof(struct procdata));
298 /* processes can't go into vc context on vc 0 til they unset this. This is
299 * for processes that block before initing uthread code (like rtld). */
300 atomic_set(&p->procdata->vcore_preempt_data[0].flags, VC_SCP_NOVCCTX);
303 /* Allocates and initializes a process, with the given parent. Currently
304 * writes the *p into **pp, and returns 0 on success, < 0 for an error.
306 * - ENOFREEPID if it can't get a PID
307 * - ENOMEM on memory exhaustion */
308 error_t proc_alloc(struct proc **pp, struct proc *parent, int flags)
313 if (!(p = kmem_cache_alloc(proc_cache, 0)))
315 /* zero everything by default, other specific items are set below */
316 memset(p, 0, sizeof(*p));
318 /* only one ref, which we pass back. the old 'existence' ref is managed by
320 kref_init(&p->p_kref, __proc_free, 1);
321 // Setup the default map of where to get cache colors from
322 p->cache_colors_map = global_cache_colors_map;
323 p->next_cache_color = 0;
324 /* Initialize the address space */
325 if ((r = env_setup_vm(p)) < 0) {
326 kmem_cache_free(proc_cache, p);
329 if (!(p->pid = get_free_pid())) {
330 kmem_cache_free(proc_cache, p);
333 if (parent && parent->binary_path)
334 kstrdup(&p->binary_path, parent->binary_path);
335 /* Set the basic status variables. */
336 spinlock_init(&p->proc_lock);
337 p->exitcode = 1337; /* so we can see processes killed by the kernel */
339 p->ppid = parent->pid;
340 proc_incref(p, 1); /* storing a ref in the parent */
341 /* using the CV's lock to protect anything related to child waiting */
342 cv_lock(&parent->child_wait);
343 TAILQ_INSERT_TAIL(&parent->children, p, sibling_link);
344 cv_unlock(&parent->child_wait);
348 TAILQ_INIT(&p->children);
349 cv_init(&p->child_wait);
350 p->state = PROC_CREATED; /* shouldn't go through state machine for init */
353 spinlock_init(&p->vmr_lock);
354 spinlock_init(&p->pte_lock);
355 TAILQ_INIT(&p->vm_regions); /* could init this in the slab */
357 /* Initialize the vcore lists, we'll build the inactive list so that it
358 * includes all vcores when we initialize procinfo. Do this before initing
360 TAILQ_INIT(&p->online_vcs);
361 TAILQ_INIT(&p->bulk_preempted_vcs);
362 TAILQ_INIT(&p->inactive_vcs);
363 /* Init procinfo/procdata. Procinfo's argp/argb are 0'd */
364 proc_init_procinfo(p);
365 proc_init_procdata(p);
367 /* Initialize the generic sysevent ring buffer */
368 SHARED_RING_INIT(&p->procdata->syseventring);
369 /* Initialize the frontend of the sysevent ring buffer */
370 FRONT_RING_INIT(&p->syseventfrontring,
371 &p->procdata->syseventring,
374 /* Init FS structures TODO: cleanup (might pull this out) */
375 kref_get(&default_ns.kref, 1);
377 spinlock_init(&p->fs_env.lock);
378 p->fs_env.umask = parent ? parent->fs_env.umask : S_IWGRP | S_IWOTH;
379 p->fs_env.root = p->ns->root->mnt_root;
380 kref_get(&p->fs_env.root->d_kref, 1);
381 p->fs_env.pwd = parent ? parent->fs_env.pwd : p->fs_env.root;
382 kref_get(&p->fs_env.pwd->d_kref, 1);
383 memset(&p->open_files, 0, sizeof(p->open_files)); /* slightly ghetto */
384 spinlock_init(&p->open_files.lock);
385 p->open_files.max_files = NR_OPEN_FILES_DEFAULT;
386 p->open_files.max_fdset = NR_FILE_DESC_DEFAULT;
387 p->open_files.fd = p->open_files.fd_array;
388 p->open_files.open_fds = (struct fd_set*)&p->open_files.open_fds_init;
390 if (flags & PROC_DUP_FGRP)
391 clone_fdt(&parent->open_files, &p->open_files);
393 /* no parent, we're created from the kernel */
395 fd = insert_file(&p->open_files, dev_stdin, 0, TRUE, FALSE);
397 fd = insert_file(&p->open_files, dev_stdout, 1, TRUE, FALSE);
399 fd = insert_file(&p->open_files, dev_stderr, 2, TRUE, FALSE);
402 /* Init the ucq hash lock */
403 p->ucq_hashlock = (struct hashlock*)&p->ucq_hl_noref;
404 hashlock_init_irqsave(p->ucq_hashlock, HASHLOCK_DEFAULT_SZ);
406 atomic_inc(&num_envs);
407 frontend_proc_init(p);
408 plan9setup(p, parent, flags);
410 TAILQ_INIT(&p->abortable_sleepers);
411 spinlock_init_irqsave(&p->abort_list_lock);
412 memset(&p->vmm, 0, sizeof(struct vmm));
413 qlock_init(&p->vmm.qlock);
414 printd("[%08x] new process %08x\n", current ? current->pid : 0, p->pid);
419 /* We have a bunch of different ways to make processes. Call this once the
420 * process is ready to be used by the rest of the system. For now, this just
421 * means when it is ready to be named via the pidhash. In the future, we might
422 * push setting the state to CREATED into here. */
423 void __proc_ready(struct proc *p)
425 /* Tell the ksched about us. TODO: do we need to worry about the ksched
426 * doing stuff to us before we're added to the pid_hash? */
427 __sched_proc_register(p);
428 spin_lock(&pid_hash_lock);
429 hashtable_insert(pid_hash, (void*)(long)p->pid, p);
430 spin_unlock(&pid_hash_lock);
433 /* Creates a process from the specified file, argvs, and envps. Tempted to get
434 * rid of proc_alloc's style, but it is so quaint... */
435 struct proc *proc_create(struct file *prog, char **argv, char **envp)
439 if ((r = proc_alloc(&p, current, 0 /* flags */)) < 0)
440 panic("proc_create: %e", r); /* one of 3 quaint usages of %e */
441 int argc = 0, envc = 0;
442 if(argv) while(argv[argc]) argc++;
443 if(envp) while(envp[envc]) envc++;
444 proc_set_progname(p, argc ? argv[0] : NULL);
445 assert(load_elf(p, prog, argc, argv, envc, envp) == 0);
450 static int __cb_assert_no_pg(struct proc *p, pte_t pte, void *va, void *arg)
452 assert(pte_is_unmapped(pte));
456 /* This is called by kref_put(), once the last reference to the process is
457 * gone. Don't call this otherwise (it will panic). It will clean up the
458 * address space and deallocate any other used memory. */
459 static void __proc_free(struct kref *kref)
461 struct proc *p = container_of(kref, struct proc, p_kref);
465 printd("[PID %d] freeing proc: %d\n", current ? current->pid : 0, p->pid);
466 // All parts of the kernel should have decref'd before __proc_free is called
467 assert(kref_refcnt(&p->p_kref) == 0);
468 assert(TAILQ_EMPTY(&p->alarmset.list));
470 __vmm_struct_cleanup(p);
472 free_path(p, p->binary_path);
475 p->dot = p->slash = 0; /* catch bugs */
476 kref_put(&p->fs_env.root->d_kref);
477 kref_put(&p->fs_env.pwd->d_kref);
478 /* now we'll finally decref files for the file-backed vmrs */
479 unmap_and_destroy_vmrs(p);
480 frontend_proc_free(p); /* TODO: please remove me one day */
481 /* Free any colors allocated to this process */
482 if (p->cache_colors_map != global_cache_colors_map) {
483 for(int i = 0; i < llc_cache->num_colors; i++)
484 cache_color_free(llc_cache, p->cache_colors_map);
485 cache_colors_map_free(p->cache_colors_map);
487 /* Remove us from the pid_hash and give our PID back (in that order). */
488 spin_lock(&pid_hash_lock);
489 hash_ret = hashtable_remove(pid_hash, (void*)(long)p->pid);
490 spin_unlock(&pid_hash_lock);
491 /* might not be in the hash/ready, if we failed during proc creation */
493 put_free_pid(p->pid);
495 printd("[kernel] pid %d not in the PID hash in %s\n", p->pid,
497 /* all memory below UMAPTOP should have been freed via the VMRs. the stuff
498 * above is the global page and procinfo/procdata */
499 env_user_mem_free(p, (void*)UMAPTOP, UVPT - UMAPTOP); /* 3rd arg = len... */
500 env_user_mem_walk(p, 0, UMAPTOP, __cb_assert_no_pg, 0);
501 /* These need to be freed again, since they were allocated with a refcnt. */
502 free_cont_pages(p->procinfo, LOG2_UP(PROCINFO_NUM_PAGES));
503 free_cont_pages(p->procdata, LOG2_UP(PROCDATA_NUM_PAGES));
505 env_pagetable_free(p);
506 arch_pgdir_clear(&p->env_pgdir);
509 atomic_dec(&num_envs);
511 /* Dealloc the struct proc */
512 kmem_cache_free(proc_cache, p);
515 /* Whether or not actor can control target. TODO: do something reasonable here.
516 * Just checking for the parent is a bit limiting. Could walk the parent-child
517 * tree, check user ids, or some combination. Make sure actors can always
518 * control themselves. */
519 bool proc_controls(struct proc *actor, struct proc *target)
523 return ((actor == target) || (target->ppid == actor->pid));
527 /* Helper to incref by val. Using the helper to help debug/interpose on proc
528 * ref counting. Note that pid2proc doesn't use this interface. */
529 void proc_incref(struct proc *p, unsigned int val)
531 kref_get(&p->p_kref, val);
534 /* Helper to decref for debugging. Don't directly kref_put() for now. */
535 void proc_decref(struct proc *p)
537 kref_put(&p->p_kref);
540 /* Helper, makes p the 'current' process, dropping the old current/cr3. This no
541 * longer assumes the passed in reference already counted 'current'. It will
542 * incref internally when needed. */
543 static void __set_proc_current(struct proc *p)
545 /* We use the pcpui to access 'current' to cut down on the core_id() calls,
546 * though who know how expensive/painful they are. */
547 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
548 /* If the process wasn't here, then we need to load its address space. */
549 if (p != pcpui->cur_proc) {
552 /* This is "leaving the process context" of the previous proc. The
553 * previous lcr3 unloaded the previous proc's context. This should
554 * rarely happen, since we usually proactively leave process context,
555 * but this is the fallback. */
557 proc_decref(pcpui->cur_proc);
562 /* Flag says if vcore context is not ready, which is set in init_procdata. The
563 * process must turn off this flag on vcore0 at some point. It's off by default
564 * on all other vcores. */
565 static bool scp_is_vcctx_ready(struct preempt_data *vcpd)
567 return !(atomic_read(&vcpd->flags) & VC_SCP_NOVCCTX);
570 /* Dispatches a _S process to run on the current core. This should never be
571 * called to "restart" a core.
573 * This will always return, regardless of whether or not the calling core is
574 * being given to a process. (it used to pop the tf directly, before we had
577 * Since it always returns, it will never "eat" your reference (old
578 * documentation talks about this a bit). */
579 void proc_run_s(struct proc *p)
581 uint32_t coreid = core_id();
582 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
583 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
584 spin_lock(&p->proc_lock);
587 spin_unlock(&p->proc_lock);
588 printk("[kernel] _S %d not starting due to async death\n", p->pid);
590 case (PROC_RUNNABLE_S):
591 __proc_set_state(p, PROC_RUNNING_S);
592 /* SCPs don't have full vcores, but they act like they have vcore 0.
593 * We map the vcore, since we will want to know where this process
594 * is running, even if it is only in RUNNING_S. We can use the
595 * vcoremap, which makes death easy. num_vcores is still 0, and we
596 * do account the time online and offline. */
597 __seq_start_write(&p->procinfo->coremap_seqctr);
598 p->procinfo->num_vcores = 0;
599 __map_vcore(p, 0, coreid);
600 vcore_account_online(p, 0);
601 __seq_end_write(&p->procinfo->coremap_seqctr);
602 /* incref, since we're saving a reference in owning proc later */
604 /* lock was protecting the state and VC mapping, not pcpui stuff */
605 spin_unlock(&p->proc_lock);
606 /* redundant with proc_startcore, might be able to remove that one*/
607 __set_proc_current(p);
608 /* set us up as owning_proc. ksched bug if there is already one,
609 * for now. can simply clear_owning if we want to. */
610 assert(!pcpui->owning_proc);
611 pcpui->owning_proc = p;
612 pcpui->owning_vcoreid = 0;
613 restore_vc_fp_state(vcpd);
614 /* similar to the old __startcore, start them in vcore context if
615 * they have notifs and aren't already in vcore context. o/w, start
616 * them wherever they were before (could be either vc ctx or not) */
617 if (!vcpd->notif_disabled && vcpd->notif_pending
618 && scp_is_vcctx_ready(vcpd)) {
619 vcpd->notif_disabled = TRUE;
620 /* save the _S's ctx in the uthread slot, build and pop a new
621 * one in actual/cur_ctx. */
622 vcpd->uthread_ctx = p->scp_ctx;
623 pcpui->cur_ctx = &pcpui->actual_ctx;
624 memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
625 proc_init_ctx(pcpui->cur_ctx, 0, vcpd->vcore_entry,
626 vcpd->vcore_stack, vcpd->vcore_tls_desc);
628 /* If they have no transition stack, then they can't receive
629 * events. The most they are getting is a wakeup from the
630 * kernel. They won't even turn off notif_pending, so we'll do
632 if (!scp_is_vcctx_ready(vcpd))
633 vcpd->notif_pending = FALSE;
634 /* this is one of the few times cur_ctx != &actual_ctx */
635 pcpui->cur_ctx = &p->scp_ctx;
637 /* When the calling core idles, it'll call restartcore and run the
638 * _S process's context. */
641 spin_unlock(&p->proc_lock);
642 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
646 /* Helper: sends preempt messages to all vcores on the bulk preempt list, and
647 * moves them to the inactive list. */
648 static void __send_bulkp_events(struct proc *p)
650 struct vcore *vc_i, *vc_temp;
651 struct event_msg preempt_msg = {0};
652 /* Whenever we send msgs with the proc locked, we need at least 1 online */
653 assert(!TAILQ_EMPTY(&p->online_vcs));
654 /* Send preempt messages for any left on the BP list. No need to set any
655 * flags, it all was done on the real preempt. Now we're just telling the
656 * process about any that didn't get restarted and are still preempted. */
657 TAILQ_FOREACH_SAFE(vc_i, &p->bulk_preempted_vcs, list, vc_temp) {
658 /* Note that if there are no active vcores, send_k_e will post to our
659 * own vcore, the last of which will be put on the inactive list and be
660 * the first to be started. We could have issues with deadlocking,
661 * since send_k_e() could grab the proclock (if there are no active
663 preempt_msg.ev_type = EV_VCORE_PREEMPT;
664 preempt_msg.ev_arg2 = vcore2vcoreid(p, vc_i); /* arg2 is 32 bits */
665 send_kernel_event(p, &preempt_msg, 0);
666 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that.
667 * We need a loop for the messages, but not necessarily for the list
669 TAILQ_REMOVE(&p->bulk_preempted_vcs, vc_i, list);
670 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
674 /* Run an _M. Can be called safely on one that is already running. Hold the
675 * lock before calling. Other than state checks, this just starts up the _M's
676 * vcores, much like the second part of give_cores_running. More specifically,
677 * give_cores_runnable puts cores on the online list, which this then sends
678 * messages to. give_cores_running immediately puts them on the list and sends
679 * the message. the two-step style may go out of fashion soon.
681 * This expects that the "instructions" for which core(s) to run this on will be
682 * in the vcoremap, which needs to be set externally (give_cores()). */
683 void __proc_run_m(struct proc *p)
689 warn("ksched tried to run proc %d in state %s\n", p->pid,
690 procstate2str(p->state));
692 case (PROC_RUNNABLE_M):
693 /* vcoremap[i] holds the coreid of the physical core allocated to
694 * this process. It is set outside proc_run. */
695 if (p->procinfo->num_vcores) {
696 __send_bulkp_events(p);
697 __proc_set_state(p, PROC_RUNNING_M);
698 /* Up the refcnt, to avoid the n refcnt upping on the
699 * destination cores. Keep in sync with __startcore */
700 proc_incref(p, p->procinfo->num_vcores * 2);
701 /* Send kernel messages to all online vcores (which were added
702 * to the list and mapped in __proc_give_cores()), making them
704 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
705 send_kernel_message(vc_i->pcoreid, __startcore, (long)p,
706 (long)vcore2vcoreid(p, vc_i),
707 (long)vc_i->nr_preempts_sent,
711 warn("Tried to proc_run() an _M with no vcores!");
713 /* There a subtle race avoidance here (when we unlock after sending
714 * the message). __proc_startcore can handle a death message, but
715 * we can't have the startcore come after the death message.
716 * Otherwise, it would look like a new process. So we hold the lock
717 * til after we send our message, which prevents a possible death
719 * - Note there is no guarantee this core's interrupts were on, so
720 * it may not get the message for a while... */
722 case (PROC_RUNNING_M):
725 /* unlock just so the monitor can call something that might lock*/
726 spin_unlock(&p->proc_lock);
727 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
731 /* You must disable IRQs and PRKM before calling this.
733 * Actually runs the given context (trapframe) of process p on the core this
734 * code executes on. This is called directly by __startcore, which needs to
735 * bypass the routine_kmsg check. Interrupts should be off when you call this.
737 * A note on refcnting: this function will not return, and your proc reference
738 * will end up stored in current. This will make no changes to p's refcnt, so
739 * do your accounting such that there is only the +1 for current. This means if
740 * it is already in current (like in the trap return path), don't up it. If
741 * it's already in current and you have another reference (like pid2proc or from
742 * an IPI), then down it (which is what happens in __startcore()). If it's not
743 * in current and you have one reference, like proc_run(non_current_p), then
744 * also do nothing. The refcnt for your *p will count for the reference stored
746 void __proc_startcore(struct proc *p, struct user_context *ctx)
748 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
749 assert(!irq_is_enabled());
750 /* Should never have ktask still set. If we do, future syscalls could try
751 * to block later and lose track of our address space. */
752 assert(!pcpui->cur_kthread->is_ktask);
753 __set_proc_current(p);
754 /* Clear the current_ctx, since it is no longer used */
755 current_ctx = 0; /* TODO: might not need this... */
756 __set_cpu_state(pcpui, CPU_STATE_USER);
760 /* Restarts/runs the current_ctx, which must be for the current process, on the
761 * core this code executes on. Calls an internal function to do the work.
763 * In case there are pending routine messages, like __death, __preempt, or
764 * __notify, we need to run them. Alternatively, if there are any, we could
765 * self_ipi, and run the messages immediately after popping back to userspace,
766 * but that would have crappy overhead. */
767 void proc_restartcore(void)
769 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
770 assert(!pcpui->cur_kthread->sysc);
771 /* TODO: can probably remove this enable_irq. it was an optimization for
773 /* Try and get any interrupts before we pop back to userspace. If we didn't
774 * do this, we'd just get them in userspace, but this might save us some
775 * effort/overhead. */
777 /* Need ints disabled when we return from PRKM (race on missing
780 process_routine_kmsg();
781 /* If there is no owning process, just idle, since we don't know what to do.
782 * This could be because the process had been restarted a long time ago and
783 * has since left the core, or due to a KMSG like __preempt or __death. */
784 if (!pcpui->owning_proc) {
788 assert(pcpui->cur_ctx);
789 __proc_startcore(pcpui->owning_proc, pcpui->cur_ctx);
792 /* Destroys the process. It will destroy the process and return any cores
793 * to the ksched via the __sched_proc_destroy() CB.
795 * Here's the way process death works:
796 * 0. grab the lock (protects state transition and core map)
797 * 1. set state to dying. that keeps the kernel from doing anything for the
798 * process (like proc_running it).
799 * 2. figure out where the process is running (cross-core/async or RUNNING_M)
800 * 3. IPI to clean up those cores (decref, etc).
802 * 5. Clean up your core, if applicable
803 * (Last core/kernel thread to decref cleans up and deallocates resources.)
805 * Note that some cores can be processing async calls, but will eventually
806 * decref. Should think about this more, like some sort of callback/revocation.
808 * This function will now always return (it used to not return if the calling
809 * core was dying). However, when it returns, a kernel message will eventually
810 * come in, making you abandon_core, as if you weren't running. It may be that
811 * the only reference to p is the one you passed in, and when you decref, it'll
812 * get __proc_free()d. */
813 void proc_destroy(struct proc *p)
815 uint32_t nr_cores_revoked = 0;
816 struct kthread *sleeper;
817 struct proc *child_i, *temp;
818 /* Can't spin on the proc lock with irq disabled. This is a problem for all
819 * places where we grab the lock, but it is particularly bad for destroy,
820 * since we tend to call this from trap and irq handlers */
821 assert(irq_is_enabled());
822 spin_lock(&p->proc_lock);
823 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
824 uint32_t pc_arr[p->procinfo->num_vcores];
826 case PROC_DYING: /* someone else killed this already. */
827 spin_unlock(&p->proc_lock);
830 case PROC_RUNNABLE_S:
833 case PROC_RUNNABLE_M:
835 /* Need to reclaim any cores this proc might have, even if it's not
836 * running yet. Those running will receive a __death */
837 nr_cores_revoked = __proc_take_allcores(p, pc_arr, FALSE);
841 // here's how to do it manually
844 proc_decref(p); /* this decref is for the cr3 */
848 send_kernel_message(get_pcoreid(p, 0), __death, 0, 0, 0,
850 __seq_start_write(&p->procinfo->coremap_seqctr);
852 __seq_end_write(&p->procinfo->coremap_seqctr);
853 /* If we ever have RUNNING_S run on non-mgmt cores, we'll need to
854 * tell the ksched about this now-idle core (after unlocking) */
857 warn("Weird state(%s) in %s()", procstate2str(p->state),
859 spin_unlock(&p->proc_lock);
862 /* At this point, a death IPI should be on its way, either from the
863 * RUNNING_S one, or from proc_take_cores with a __death. in general,
864 * interrupts should be on when you call proc_destroy locally, but currently
865 * aren't for all things (like traphandlers). */
866 __proc_set_state(p, PROC_DYING);
867 /* Disown any children. If we want to have init inherit or something,
868 * change __disown to set the ppid accordingly and concat this with init's
869 * list (instead of emptying it like disown does). Careful of lock ordering
870 * between procs (need to lock to protect lists) */
871 TAILQ_FOREACH_SAFE(child_i, &p->children, sibling_link, temp) {
872 int ret = __proc_disown_child(p, child_i);
873 /* should never fail, lock should cover the race. invariant: any child
874 * on the list should have us as a parent */
877 spin_unlock(&p->proc_lock);
878 /* Wake any of our kthreads waiting on children, so they can abort */
879 cv_broadcast(&p->child_wait);
880 /* Abort any abortable syscalls. This won't catch every sleeper, but future
881 * abortable sleepers are already prevented via the DYING state. (signalled
882 * DYING, no new sleepers will block, and now we wake all old sleepers). */
884 /* we need to close files here, and not in free, since we could have a
885 * refcnt indirectly related to one of our files. specifically, if we have
886 * a parent sleeping on our pipe, that parent won't wake up to decref until
887 * the pipe closes. And if the parent doesnt decref, we don't free.
888 * alternatively, we could send a SIGCHILD to the parent, but that would
889 * require parent's to never ignore that signal (or risk never reaping).
891 * Also note that any mmap'd files will still be mmapped. You can close the
892 * file after mmapping, with no effect. */
893 close_fdt(&p->open_files, FALSE);
894 /* Tell the ksched about our death, and which cores we freed up */
895 __sched_proc_destroy(p, pc_arr, nr_cores_revoked);
896 /* Tell our parent about our state change (to DYING) */
897 proc_signal_parent(p);
900 /* Can use this to signal anything that might cause a parent to wait on the
901 * child, such as termination, or (in the future) signals. Change the state or
902 * whatever before calling. */
903 void proc_signal_parent(struct proc *child)
905 struct kthread *sleeper;
906 struct proc *parent = pid2proc(child->ppid);
909 /* there could be multiple kthreads sleeping for various reasons. even an
910 * SCP could have multiple async syscalls. */
911 cv_broadcast(&parent->child_wait);
912 /* if the parent was waiting, there's a __launch kthread KMSG out there */
916 /* Called when a parent is done with its child, and no longer wants to track the
917 * child, nor to allow the child to track it. Call with a lock (cv) held.
918 * Returns 0 if we disowned, -1 on failure. */
919 int __proc_disown_child(struct proc *parent, struct proc *child)
921 /* Bail out if the child has already been reaped */
924 assert(child->ppid == parent->pid);
925 /* lock protects from concurrent inserts / removals from the list */
926 TAILQ_REMOVE(&parent->children, child, sibling_link);
927 /* After this, the child won't be able to get more refs to us, but it may
928 * still have some references in running code. */
930 proc_decref(child); /* ref that was keeping the child alive on the list */
934 /* Turns *p into an MCP. Needs to be called from a local syscall of a RUNNING_S
935 * process. Returns 0 if it succeeded, an error code otherwise. */
936 int proc_change_to_m(struct proc *p)
939 spin_lock(&p->proc_lock);
940 /* in case userspace erroneously tries to change more than once */
941 if (__proc_is_mcp(p))
944 case (PROC_RUNNING_S):
945 /* issue with if we're async or not (need to preempt it)
946 * either of these should trip it. TODO: (ACR) async core req */
947 if ((current != p) || (get_pcoreid(p, 0) != core_id()))
948 panic("We don't handle async RUNNING_S core requests yet.");
949 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
951 /* Copy uthread0's context to VC 0's uthread slot */
952 copy_current_ctx_to(&vcpd->uthread_ctx);
953 clear_owning_proc(core_id()); /* so we don't restart */
954 save_vc_fp_state(vcpd);
955 /* Userspace needs to not fuck with notif_disabled before
956 * transitioning to _M. */
957 if (vcpd->notif_disabled) {
958 printk("[kernel] user bug: notifs disabled for vcore 0\n");
959 vcpd->notif_disabled = FALSE;
961 /* in the async case, we'll need to remotely stop and bundle
962 * vcore0's TF. this is already done for the sync case (local
964 /* this process no longer runs on its old location (which is
965 * this core, for now, since we don't handle async calls) */
966 __seq_start_write(&p->procinfo->coremap_seqctr);
967 // TODO: (ACR) will need to unmap remotely (receive-side)
969 vcore_account_offline(p, 0);
970 __seq_end_write(&p->procinfo->coremap_seqctr);
971 /* change to runnable_m (it's TF is already saved) */
972 __proc_set_state(p, PROC_RUNNABLE_M);
973 p->procinfo->is_mcp = TRUE;
974 spin_unlock(&p->proc_lock);
975 /* Tell the ksched that we're a real MCP now! */
976 __sched_proc_change_to_m(p);
978 case (PROC_RUNNABLE_S):
979 /* Issues: being on the runnable_list, proc_set_state not liking
980 * it, and not clearly thinking through how this would happen.
981 * Perhaps an async call that gets serviced after you're
983 warn("Not supporting RUNNABLE_S -> RUNNABLE_M yet.\n");
986 warn("Dying, core request coming from %d\n", core_id());
992 spin_unlock(&p->proc_lock);
996 /* Old code to turn a RUNNING_M to a RUNNING_S, with the calling context
997 * becoming the new 'thread0'. Don't use this. Caller needs to send in a
998 * pc_arr big enough for all vcores. Will return the number of cores given up
1000 uint32_t __proc_change_to_s(struct proc *p, uint32_t *pc_arr)
1002 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1003 uint32_t num_revoked;
1004 /* Not handling vcore accounting. Do so if we ever use this */
1005 printk("[kernel] trying to transition _M -> _S (deprecated)!\n");
1006 assert(p->state == PROC_RUNNING_M); // TODO: (ACR) async core req
1007 /* save the context, to be restarted in _S mode */
1008 assert(current_ctx);
1009 copy_current_ctx_to(&p->scp_ctx);
1010 clear_owning_proc(core_id()); /* so we don't restart */
1011 save_vc_fp_state(vcpd);
1012 /* sending death, since it's not our job to save contexts or anything in
1014 num_revoked = __proc_take_allcores(p, pc_arr, FALSE);
1015 __proc_set_state(p, PROC_RUNNABLE_S);
1019 /* Helper function. Is the given pcore a mapped vcore? No locking involved, be
1021 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid)
1023 return p->procinfo->pcoremap[pcoreid].valid;
1026 /* Helper function. Find the vcoreid for a given physical core id for proc p.
1027 * No locking involved, be careful. Panics on failure. */
1028 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid)
1030 assert(is_mapped_vcore(p, pcoreid));
1031 return p->procinfo->pcoremap[pcoreid].vcoreid;
1034 /* Helper function. Try to find the pcoreid for a given virtual core id for
1035 * proc p. No locking involved, be careful. Use this when you can tolerate a
1036 * stale or otherwise 'wrong' answer. */
1037 static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid)
1039 return p->procinfo->vcoremap[vcoreid].pcoreid;
1042 /* Helper function. Find the pcoreid for a given virtual core id for proc p.
1043 * No locking involved, be careful. Panics on failure. */
1044 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid)
1046 assert(vcore_is_mapped(p, vcoreid));
1047 return try_get_pcoreid(p, vcoreid);
1050 /* Saves the FP state of the calling core into VCPD. Pairs with
1051 * restore_vc_fp_state(). On x86, the best case overhead of the flags:
1055 * Flagged FXSAVE: 50 ns
1056 * Flagged FXRSTR: 66 ns
1057 * Excess flagged FXRSTR: 42 ns
1058 * If we don't do it, we'll need to initialize every VCPD at process creation
1059 * time with a good FPU state (x86 control words are initialized as 0s, like the
1061 static void save_vc_fp_state(struct preempt_data *vcpd)
1063 save_fp_state(&vcpd->preempt_anc);
1064 vcpd->rflags |= VC_FPU_SAVED;
1067 /* Conditionally restores the FP state from VCPD. If the state was not valid,
1068 * we don't bother restoring and just initialize the FPU. */
1069 static void restore_vc_fp_state(struct preempt_data *vcpd)
1071 if (vcpd->rflags & VC_FPU_SAVED) {
1072 restore_fp_state(&vcpd->preempt_anc);
1073 vcpd->rflags &= ~VC_FPU_SAVED;
1079 /* Helper for SCPs, saves the core's FPU state into the VCPD vc0 slot */
1080 void __proc_save_fpu_s(struct proc *p)
1082 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1083 save_vc_fp_state(vcpd);
1086 /* Helper: saves the SCP's GP tf state and unmaps vcore 0. This does *not* save
1089 * In the future, we'll probably use vc0's space for scp_ctx and the silly
1090 * state. If we ever do that, we'll need to stop using scp_ctx (soon to be in
1091 * VCPD) as a location for pcpui->cur_ctx to point (dangerous) */
1092 void __proc_save_context_s(struct proc *p)
1094 copy_current_ctx_to(&p->scp_ctx);
1095 __seq_start_write(&p->procinfo->coremap_seqctr);
1096 __unmap_vcore(p, 0);
1097 __seq_end_write(&p->procinfo->coremap_seqctr);
1098 vcore_account_offline(p, 0);
1101 /* Yields the calling core. Must be called locally (not async) for now.
1102 * - If RUNNING_S, you just give up your time slice and will eventually return,
1103 * possibly after WAITING on an event.
1104 * - If RUNNING_M, you give up the current vcore (which never returns), and
1105 * adjust the amount of cores wanted/granted.
1106 * - If you have only one vcore, you switch to WAITING. There's no 'classic
1107 * yield' for MCPs (at least not now). When you run again, you'll have one
1108 * guaranteed core, starting from the entry point.
1110 * If the call is being nice, it means different things for SCPs and MCPs. For
1111 * MCPs, it means that it is in response to a preemption (which needs to be
1112 * checked). If there is no preemption pending, just return. For SCPs, it
1113 * means the proc wants to give up the core, but still has work to do. If not,
1114 * the proc is trying to wait on an event. It's not being nice to others, it
1115 * just has no work to do.
1117 * This usually does not return (smp_idle()), so it will eat your reference.
1118 * Also note that it needs a non-current/edible reference, since it will abandon
1119 * and continue to use the *p (current == 0, no cr3, etc).
1121 * We disable interrupts for most of it too, since we need to protect
1122 * current_ctx and not race with __notify (which doesn't play well with
1123 * concurrent yielders). */
1124 void proc_yield(struct proc *p, bool being_nice)
1126 uint32_t vcoreid, pcoreid = core_id();
1127 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1129 struct preempt_data *vcpd;
1130 /* Need to lock to prevent concurrent vcore changes (online, inactive, the
1131 * mapping, etc). This plus checking the nr_preempts is enough to tell if
1132 * our vcoreid and cur_ctx ought to be here still or if we should abort */
1133 spin_lock(&p->proc_lock); /* horrible scalability. =( */
1135 case (PROC_RUNNING_S):
1137 /* waiting for an event to unblock us */
1138 vcpd = &p->procdata->vcore_preempt_data[0];
1139 /* syncing with event's SCP code. we set waiting, then check
1140 * pending. they set pending, then check waiting. it's not
1141 * possible for us to miss the notif *and* for them to miss
1142 * WAITING. one (or both) of us will see and make sure the proc
1144 __proc_set_state(p, PROC_WAITING);
1145 wrmb(); /* don't let the state write pass the notif read */
1146 if (vcpd->notif_pending) {
1147 __proc_set_state(p, PROC_RUNNING_S);
1148 /* they can't handle events, just need to prevent a yield.
1149 * (note the notif_pendings are collapsed). */
1150 if (!scp_is_vcctx_ready(vcpd))
1151 vcpd->notif_pending = FALSE;
1154 /* if we're here, we want to sleep. a concurrent event that
1155 * hasn't already written notif_pending will have seen WAITING,
1156 * and will be spinning while we do this. */
1157 __proc_save_context_s(p);
1158 spin_unlock(&p->proc_lock);
1160 /* yielding to allow other processes to run. we're briefly
1161 * WAITING, til we are woken up */
1162 __proc_set_state(p, PROC_WAITING);
1163 __proc_save_context_s(p);
1164 spin_unlock(&p->proc_lock);
1165 /* immediately wake up the proc (makes it runnable) */
1168 goto out_yield_core;
1169 case (PROC_RUNNING_M):
1170 break; /* will handle this stuff below */
1171 case (PROC_DYING): /* incoming __death */
1172 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1175 panic("Weird state(%s) in %s()", procstate2str(p->state),
1178 /* This is which vcore this pcore thinks it is, regardless of any unmappings
1179 * that may have happened remotely (with __PRs waiting to run) */
1180 vcoreid = pcpui->owning_vcoreid;
1181 vc = vcoreid2vcore(p, vcoreid);
1182 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1183 /* This is how we detect whether or not a __PR happened. */
1184 if (vc->nr_preempts_sent != vc->nr_preempts_done)
1186 /* Sanity checks. If we were preempted or are dying, we should have noticed
1188 assert(is_mapped_vcore(p, pcoreid));
1189 assert(vcoreid == get_vcoreid(p, pcoreid));
1190 /* no reason to be nice, return */
1191 if (being_nice && !vc->preempt_pending)
1193 /* At this point, AFAIK there should be no preempt/death messages on the
1194 * way, and we're on the online list. So we'll go ahead and do the yielding
1196 /* If there's a preempt pending, we don't need to preempt later since we are
1197 * yielding (nice or otherwise). If not, this is just a regular yield. */
1198 if (vc->preempt_pending) {
1199 vc->preempt_pending = 0;
1201 /* Optional: on a normal yield, check to see if we are putting them
1202 * below amt_wanted (help with user races) and bail. */
1203 if (p->procdata->res_req[RES_CORES].amt_wanted >=
1204 p->procinfo->num_vcores)
1207 /* Don't let them yield if they are missing a notification. Userspace must
1208 * not leave vcore context without dealing with notif_pending.
1209 * pop_user_ctx() handles leaving via uthread context. This handles leaving
1212 * This early check is an optimization. The real check is below when it
1213 * works with the online_vcs list (syncing with event.c and INDIR/IPI
1215 if (vcpd->notif_pending)
1217 /* Now we'll actually try to yield */
1218 printd("[K] Process %d (%p) is yielding on vcore %d\n", p->pid, p,
1219 get_vcoreid(p, pcoreid));
1220 /* Remove from the online list, add to the yielded list, and unmap
1221 * the vcore, which gives up the core. */
1222 TAILQ_REMOVE(&p->online_vcs, vc, list);
1223 /* Now that we're off the online list, check to see if an alert made
1224 * it through (event.c sets this) */
1225 wrmb(); /* prev write must hit before reading notif_pending */
1226 /* Note we need interrupts disabled, since a __notify can come in
1227 * and set pending to FALSE */
1228 if (vcpd->notif_pending) {
1229 /* We lost, put it back on the list and abort the yield. If we ever
1230 * build an myield, we'll need a way to deal with this for all vcores */
1231 TAILQ_INSERT_TAIL(&p->online_vcs, vc, list); /* could go HEAD */
1234 /* Not really a kmsg, but it acts like one w.r.t. proc mgmt */
1235 pcpui_trace_kmsg(pcpui, (uintptr_t)proc_yield);
1236 /* We won the race with event sending, we can safely yield */
1237 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1238 /* Note this protects stuff userspace should look at, which doesn't
1239 * include the TAILQs. */
1240 __seq_start_write(&p->procinfo->coremap_seqctr);
1241 /* Next time the vcore starts, it starts fresh */
1242 vcpd->notif_disabled = FALSE;
1243 __unmap_vcore(p, vcoreid);
1244 p->procinfo->num_vcores--;
1245 p->procinfo->res_grant[RES_CORES] = p->procinfo->num_vcores;
1246 __seq_end_write(&p->procinfo->coremap_seqctr);
1247 vcore_account_offline(p, vcoreid);
1248 /* No more vcores? Then we wait on an event */
1249 if (p->procinfo->num_vcores == 0) {
1250 /* consider a ksched op to tell it about us WAITING */
1251 __proc_set_state(p, PROC_WAITING);
1253 spin_unlock(&p->proc_lock);
1254 /* Hand the now-idle core to the ksched */
1255 __sched_put_idle_core(p, pcoreid);
1256 goto out_yield_core;
1258 /* for some reason we just want to return, either to take a KMSG that cleans
1259 * us up, or because we shouldn't yield (ex: notif_pending). */
1260 spin_unlock(&p->proc_lock);
1262 out_yield_core: /* successfully yielded the core */
1263 proc_decref(p); /* need to eat the ref passed in */
1264 /* Clean up the core and idle. */
1265 clear_owning_proc(pcoreid); /* so we don't restart */
1270 /* Sends a notification (aka active notification, aka IPI) to p's vcore. We
1271 * only send a notification if one they are enabled. There's a bunch of weird
1272 * cases with this, and how pending / enabled are signals between the user and
1273 * kernel - check the documentation. Note that pending is more about messages.
1274 * The process needs to be in vcore_context, and the reason is usually a
1275 * message. We set pending here in case we were called to prod them into vcore
1276 * context (like via a sys_self_notify). Also note that this works for _S
1277 * procs, if you send to vcore 0 (and the proc is running). */
1278 void proc_notify(struct proc *p, uint32_t vcoreid)
1280 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1281 vcpd->notif_pending = TRUE;
1282 wrmb(); /* must write notif_pending before reading notif_disabled */
1283 if (!vcpd->notif_disabled) {
1284 /* GIANT WARNING: we aren't using the proc-lock to protect the
1285 * vcoremap. We want to be able to use this from interrupt context,
1286 * and don't want the proc_lock to be an irqsave. Spurious
1287 * __notify() kmsgs are okay (it checks to see if the right receiver
1289 if (vcore_is_mapped(p, vcoreid)) {
1290 printd("[kernel] sending notif to vcore %d\n", vcoreid);
1291 /* This use of try_get_pcoreid is racy, might be unmapped */
1292 send_kernel_message(try_get_pcoreid(p, vcoreid), __notify, (long)p,
1293 0, 0, KMSG_ROUTINE);
1298 /* Makes sure p is runnable. Callers may spam this, so it needs to handle
1299 * repeated calls for the same event. Callers include event delivery, SCP
1300 * yield, and new SCPs. Will trigger __sched_.cp_wakeup() CBs. Will only
1301 * trigger the CB once, regardless of how many times we are called, *until* the
1302 * proc becomes WAITING again, presumably because of something the ksched did.*/
1303 void proc_wakeup(struct proc *p)
1305 spin_lock(&p->proc_lock);
1306 if (__proc_is_mcp(p)) {
1307 /* we only wake up WAITING mcps */
1308 if (p->state != PROC_WAITING) {
1309 spin_unlock(&p->proc_lock);
1312 __proc_set_state(p, PROC_RUNNABLE_M);
1313 spin_unlock(&p->proc_lock);
1314 __sched_mcp_wakeup(p);
1317 /* SCPs can wake up for a variety of reasons. the only times we need
1318 * to do something is if it was waiting or just created. other cases
1319 * are either benign (just go out), or potential bugs (_Ms) */
1321 case (PROC_CREATED):
1322 case (PROC_WAITING):
1323 __proc_set_state(p, PROC_RUNNABLE_S);
1325 case (PROC_RUNNABLE_S):
1326 case (PROC_RUNNING_S):
1328 spin_unlock(&p->proc_lock);
1330 case (PROC_RUNNABLE_M):
1331 case (PROC_RUNNING_M):
1332 warn("Weird state(%s) in %s()", procstate2str(p->state),
1334 spin_unlock(&p->proc_lock);
1337 printd("[kernel] FYI, waking up an _S proc\n"); /* thanks, past brho! */
1338 spin_unlock(&p->proc_lock);
1339 __sched_scp_wakeup(p);
1343 /* Is the process in multi_mode / is an MCP or not? */
1344 bool __proc_is_mcp(struct proc *p)
1346 /* in lieu of using the amount of cores requested, or having a bunch of
1347 * states (like PROC_WAITING_M and _S), I'll just track it with a bool. */
1348 return p->procinfo->is_mcp;
1351 bool proc_is_vcctx_ready(struct proc *p)
1353 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1354 return scp_is_vcctx_ready(vcpd);
1357 /************************ Preemption Functions ******************************
1358 * Don't rely on these much - I'll be sure to change them up a bit.
1360 * Careful about what takes a vcoreid and what takes a pcoreid. Also, there may
1361 * be weird glitches with setting the state to RUNNABLE_M. It is somewhat in
1362 * flux. The num_vcores is changed after take_cores, but some of the messages
1363 * (or local traps) may not yet be ready to handle seeing their future state.
1364 * But they should be, so fix those when they pop up.
1366 * Another thing to do would be to make the _core functions take a pcorelist,
1367 * and not just one pcoreid. */
1369 /* Sets a preempt_pending warning for p's vcore, to go off 'when'. If you care
1370 * about locking, do it before calling. Takes a vcoreid! */
1371 void __proc_preempt_warn(struct proc *p, uint32_t vcoreid, uint64_t when)
1373 struct event_msg local_msg = {0};
1374 /* danger with doing this unlocked: preempt_pending is set, but never 0'd,
1375 * since it is unmapped and not dealt with (TODO)*/
1376 p->procinfo->vcoremap[vcoreid].preempt_pending = when;
1378 /* Send the event (which internally checks to see how they want it) */
1379 local_msg.ev_type = EV_PREEMPT_PENDING;
1380 local_msg.ev_arg1 = vcoreid;
1381 /* Whenever we send msgs with the proc locked, we need at least 1 online.
1382 * Caller needs to make sure the core was online/mapped. */
1383 assert(!TAILQ_EMPTY(&p->online_vcs));
1384 send_kernel_event(p, &local_msg, vcoreid);
1386 /* TODO: consider putting in some lookup place for the alarm to find it.
1387 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1390 /* Warns all active vcores of an impending preemption. Hold the lock if you
1391 * care about the mapping (and you should). */
1392 void __proc_preempt_warnall(struct proc *p, uint64_t when)
1395 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1396 __proc_preempt_warn(p, vcore2vcoreid(p, vc_i), when);
1397 /* TODO: consider putting in some lookup place for the alarm to find it.
1398 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1401 // TODO: function to set an alarm, if none is outstanding
1403 /* Raw function to preempt a single core. If you care about locking, do it
1404 * before calling. */
1405 void __proc_preempt_core(struct proc *p, uint32_t pcoreid)
1407 uint32_t vcoreid = get_vcoreid(p, pcoreid);
1408 struct event_msg preempt_msg = {0};
1409 /* works with nr_preempts_done to signal completion of a preemption */
1410 p->procinfo->vcoremap[vcoreid].nr_preempts_sent++;
1411 // expects a pcorelist. assumes pcore is mapped and running_m
1412 __proc_take_corelist(p, &pcoreid, 1, TRUE);
1413 /* Only send the message if we have an online core. o/w, it would fuck
1414 * us up (deadlock), and hey don't need a message. the core we just took
1415 * will be the first one to be restarted. It will look like a notif. in
1416 * the future, we could send the event if we want, but the caller needs to
1417 * do that (after unlocking). */
1418 if (!TAILQ_EMPTY(&p->online_vcs)) {
1419 preempt_msg.ev_type = EV_VCORE_PREEMPT;
1420 preempt_msg.ev_arg2 = vcoreid;
1421 send_kernel_event(p, &preempt_msg, 0);
1425 /* Raw function to preempt every vcore. If you care about locking, do it before
1427 uint32_t __proc_preempt_all(struct proc *p, uint32_t *pc_arr)
1430 /* TODO:(BULK) PREEMPT - don't bother with this, set a proc wide flag, or
1431 * just make us RUNNABLE_M. Note this is also used by __map_vcore. */
1432 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1433 vc_i->nr_preempts_sent++;
1434 return __proc_take_allcores(p, pc_arr, TRUE);
1437 /* Warns and preempts a vcore from p. No delaying / alarming, or anything. The
1438 * warning will be for u usec from now. Returns TRUE if the core belonged to
1439 * the proc (and thus preempted), False if the proc no longer has the core. */
1440 bool proc_preempt_core(struct proc *p, uint32_t pcoreid, uint64_t usec)
1442 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1443 bool retval = FALSE;
1444 if (p->state != PROC_RUNNING_M) {
1445 /* more of an FYI for brho. should be harmless to just return. */
1446 warn("Tried to preempt from a non RUNNING_M proc!");
1449 spin_lock(&p->proc_lock);
1450 if (is_mapped_vcore(p, pcoreid)) {
1451 __proc_preempt_warn(p, get_vcoreid(p, pcoreid), warn_time);
1452 __proc_preempt_core(p, pcoreid);
1453 /* we might have taken the last core */
1454 if (!p->procinfo->num_vcores)
1455 __proc_set_state(p, PROC_RUNNABLE_M);
1458 spin_unlock(&p->proc_lock);
1462 /* Warns and preempts all from p. No delaying / alarming, or anything. The
1463 * warning will be for u usec from now. */
1464 void proc_preempt_all(struct proc *p, uint64_t usec)
1466 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1467 uint32_t num_revoked = 0;
1468 spin_lock(&p->proc_lock);
1469 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
1470 uint32_t pc_arr[p->procinfo->num_vcores];
1471 /* DYING could be okay */
1472 if (p->state != PROC_RUNNING_M) {
1473 warn("Tried to preempt from a non RUNNING_M proc!");
1474 spin_unlock(&p->proc_lock);
1477 __proc_preempt_warnall(p, warn_time);
1478 num_revoked = __proc_preempt_all(p, pc_arr);
1479 assert(!p->procinfo->num_vcores);
1480 __proc_set_state(p, PROC_RUNNABLE_M);
1481 spin_unlock(&p->proc_lock);
1482 /* TODO: when we revise this func, look at __put_idle */
1483 /* Return the cores to the ksched */
1485 __sched_put_idle_cores(p, pc_arr, num_revoked);
1488 /* Give the specific pcore to proc p. Lots of assumptions, so don't really use
1489 * this. The proc needs to be _M and prepared for it. the pcore needs to be
1491 void proc_give(struct proc *p, uint32_t pcoreid)
1493 warn("Your idlecoremap is now screwed up"); /* TODO (IDLE) */
1494 spin_lock(&p->proc_lock);
1495 // expects a pcorelist, we give it a list of one
1496 __proc_give_cores(p, &pcoreid, 1);
1497 spin_unlock(&p->proc_lock);
1500 /* Global version of the helper, for sys_get_vcoreid (might phase that syscall
1502 uint32_t proc_get_vcoreid(struct proc *p)
1504 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1505 if (pcpui->owning_proc == p) {
1506 return pcpui->owning_vcoreid;
1508 warn("Asked for vcoreid for %p, but %p is pwns", p, pcpui->owning_proc);
1509 return (uint32_t)-1;
1513 /* TODO: make all of these static inlines when we gut the env crap */
1514 bool vcore_is_mapped(struct proc *p, uint32_t vcoreid)
1516 return p->procinfo->vcoremap[vcoreid].valid;
1519 /* Can do this, or just create a new field and save it in the vcoremap */
1520 uint32_t vcore2vcoreid(struct proc *p, struct vcore *vc)
1522 return (vc - p->procinfo->vcoremap);
1525 struct vcore *vcoreid2vcore(struct proc *p, uint32_t vcoreid)
1527 return &p->procinfo->vcoremap[vcoreid];
1530 /********** Core granting (bulk and single) ***********/
1532 /* Helper: gives pcore to the process, mapping it to the next available vcore
1533 * from list vc_list. Returns TRUE if we succeeded (non-empty). If you pass in
1534 * **vc, we'll tell you which vcore it was. */
1535 static bool __proc_give_a_pcore(struct proc *p, uint32_t pcore,
1536 struct vcore_tailq *vc_list, struct vcore **vc)
1538 struct vcore *new_vc;
1539 new_vc = TAILQ_FIRST(vc_list);
1542 printd("setting vcore %d to pcore %d\n", vcore2vcoreid(p, new_vc),
1544 TAILQ_REMOVE(vc_list, new_vc, list);
1545 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1546 __map_vcore(p, vcore2vcoreid(p, new_vc), pcore);
1552 static void __proc_give_cores_runnable(struct proc *p, uint32_t *pc_arr,
1555 assert(p->state == PROC_RUNNABLE_M);
1556 assert(num); /* catch bugs */
1557 /* add new items to the vcoremap */
1558 __seq_start_write(&p->procinfo->coremap_seqctr);/* unncessary if offline */
1559 p->procinfo->num_vcores += num;
1560 for (int i = 0; i < num; i++) {
1561 /* Try from the bulk list first */
1562 if (__proc_give_a_pcore(p, pc_arr[i], &p->bulk_preempted_vcs, 0))
1564 /* o/w, try from the inactive list. at one point, i thought there might
1565 * be a legit way in which the inactive list could be empty, but that i
1566 * wanted to catch it via an assert. */
1567 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, 0));
1569 __seq_end_write(&p->procinfo->coremap_seqctr);
1572 static void __proc_give_cores_running(struct proc *p, uint32_t *pc_arr,
1576 /* Up the refcnt, since num cores are going to start using this
1577 * process and have it loaded in their owning_proc and 'current'. */
1578 proc_incref(p, num * 2); /* keep in sync with __startcore */
1579 __seq_start_write(&p->procinfo->coremap_seqctr);
1580 p->procinfo->num_vcores += num;
1581 assert(TAILQ_EMPTY(&p->bulk_preempted_vcs));
1582 for (int i = 0; i < num; i++) {
1583 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, &vc_i));
1584 send_kernel_message(pc_arr[i], __startcore, (long)p,
1585 (long)vcore2vcoreid(p, vc_i),
1586 (long)vc_i->nr_preempts_sent, KMSG_ROUTINE);
1588 __seq_end_write(&p->procinfo->coremap_seqctr);
1591 /* Gives process p the additional num cores listed in pcorelist. If the proc is
1592 * not RUNNABLE_M or RUNNING_M, this will fail and allocate none of the core
1593 * (and return -1). If you're RUNNING_M, this will startup your new cores at
1594 * the entry point with their virtual IDs (or restore a preemption). If you're
1595 * RUNNABLE_M, you should call __proc_run_m after this so that the process can
1596 * start to use its cores. In either case, this returns 0.
1598 * If you're *_S, make sure your core0's TF is set (which is done when coming in
1599 * via arch/trap.c and we are RUNNING_S), change your state, then call this.
1600 * Then call __proc_run_m().
1602 * The reason I didn't bring the _S cases from core_request over here is so we
1603 * can keep this family of calls dealing with only *_Ms, to avoiding caring if
1604 * this is called from another core, and to avoid the _S -> _M transition.
1606 * WARNING: You must hold the proc_lock before calling this! */
1607 int __proc_give_cores(struct proc *p, uint32_t *pc_arr, uint32_t num)
1609 /* should never happen: */
1610 assert(num + p->procinfo->num_vcores <= MAX_NUM_CORES);
1612 case (PROC_RUNNABLE_S):
1613 case (PROC_RUNNING_S):
1614 warn("Don't give cores to a process in a *_S state!\n");
1617 case (PROC_WAITING):
1618 /* can't accept, just fail */
1620 case (PROC_RUNNABLE_M):
1621 __proc_give_cores_runnable(p, pc_arr, num);
1623 case (PROC_RUNNING_M):
1624 __proc_give_cores_running(p, pc_arr, num);
1627 panic("Weird state(%s) in %s()", procstate2str(p->state),
1630 /* TODO: considering moving to the ksched (hard, due to yield) */
1631 p->procinfo->res_grant[RES_CORES] += num;
1635 /********** Core revocation (bulk and single) ***********/
1637 /* Revokes a single vcore from a process (unmaps or sends a KMSG to unmap). */
1638 static void __proc_revoke_core(struct proc *p, uint32_t vcoreid, bool preempt)
1640 uint32_t pcoreid = get_pcoreid(p, vcoreid);
1641 struct preempt_data *vcpd;
1643 /* Lock the vcore's state (necessary for preemption recovery) */
1644 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1645 atomic_or(&vcpd->flags, VC_K_LOCK);
1646 send_kernel_message(pcoreid, __preempt, (long)p, 0, 0, KMSG_ROUTINE);
1648 send_kernel_message(pcoreid, __death, 0, 0, 0, KMSG_ROUTINE);
1652 /* Revokes all cores from the process (unmaps or sends a KMSGS). */
1653 static void __proc_revoke_allcores(struct proc *p, bool preempt)
1656 /* TODO: if we ever get broadcast messaging, use it here (still need to lock
1657 * the vcores' states for preemption) */
1658 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1659 __proc_revoke_core(p, vcore2vcoreid(p, vc_i), preempt);
1662 /* Might be faster to scan the vcoremap than to walk the list... */
1663 static void __proc_unmap_allcores(struct proc *p)
1666 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1667 __unmap_vcore(p, vcore2vcoreid(p, vc_i));
1670 /* Takes (revoke via kmsg or unmap) from process p the num cores listed in
1671 * pc_arr. Will preempt if 'preempt' is set. o/w, no state will be saved, etc.
1672 * Don't use this for taking all of a process's cores.
1674 * Make sure you hold the lock when you call this, and make sure that the pcore
1675 * actually belongs to the proc, non-trivial due to other __preempt messages. */
1676 void __proc_take_corelist(struct proc *p, uint32_t *pc_arr, uint32_t num,
1681 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1682 __seq_start_write(&p->procinfo->coremap_seqctr);
1683 for (int i = 0; i < num; i++) {
1684 vcoreid = get_vcoreid(p, pc_arr[i]);
1686 assert(pc_arr[i] == get_pcoreid(p, vcoreid));
1687 /* Revoke / unmap core */
1688 if (p->state == PROC_RUNNING_M)
1689 __proc_revoke_core(p, vcoreid, preempt);
1690 __unmap_vcore(p, vcoreid);
1691 /* Change lists for the vcore. Note, the vcore is already unmapped
1692 * and/or the messages are already in flight. The only code that looks
1693 * at the lists without holding the lock is event code. */
1694 vc = vcoreid2vcore(p, vcoreid);
1695 TAILQ_REMOVE(&p->online_vcs, vc, list);
1696 /* even for single preempts, we use the inactive list. bulk preempt is
1697 * only used for when we take everything. */
1698 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1700 p->procinfo->num_vcores -= num;
1701 __seq_end_write(&p->procinfo->coremap_seqctr);
1702 p->procinfo->res_grant[RES_CORES] -= num;
1705 /* Takes all cores from a process (revoke via kmsg or unmap), putting them on
1706 * the appropriate vcore list, and fills pc_arr with the pcores revoked, and
1707 * returns the number of entries in pc_arr.
1709 * Make sure pc_arr is big enough to handle num_vcores().
1710 * Make sure you hold the lock when you call this. */
1711 uint32_t __proc_take_allcores(struct proc *p, uint32_t *pc_arr, bool preempt)
1713 struct vcore *vc_i, *vc_temp;
1715 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1716 __seq_start_write(&p->procinfo->coremap_seqctr);
1717 /* Write out which pcores we're going to take */
1718 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1719 pc_arr[num++] = vc_i->pcoreid;
1720 /* Revoke if they are running, and unmap. Both of these need the online
1721 * list to not be changed yet. */
1722 if (p->state == PROC_RUNNING_M)
1723 __proc_revoke_allcores(p, preempt);
1724 __proc_unmap_allcores(p);
1725 /* Move the vcores from online to the head of the appropriate list */
1726 TAILQ_FOREACH_SAFE(vc_i, &p->online_vcs, list, vc_temp) {
1727 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that */
1728 TAILQ_REMOVE(&p->online_vcs, vc_i, list);
1729 /* Put the cores on the appropriate list */
1731 TAILQ_INSERT_HEAD(&p->bulk_preempted_vcs, vc_i, list);
1733 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
1735 assert(TAILQ_EMPTY(&p->online_vcs));
1736 assert(num == p->procinfo->num_vcores);
1737 p->procinfo->num_vcores = 0;
1738 __seq_end_write(&p->procinfo->coremap_seqctr);
1739 p->procinfo->res_grant[RES_CORES] = 0;
1743 /* Helper to do the vcore->pcore and inverse mapping. Hold the lock when
1745 void __map_vcore(struct proc *p, uint32_t vcoreid, uint32_t pcoreid)
1747 p->procinfo->vcoremap[vcoreid].pcoreid = pcoreid;
1748 p->procinfo->vcoremap[vcoreid].valid = TRUE;
1749 p->procinfo->pcoremap[pcoreid].vcoreid = vcoreid;
1750 p->procinfo->pcoremap[pcoreid].valid = TRUE;
1753 /* Helper to unmap the vcore->pcore and inverse mapping. Hold the lock when
1755 void __unmap_vcore(struct proc *p, uint32_t vcoreid)
1757 p->procinfo->pcoremap[p->procinfo->vcoremap[vcoreid].pcoreid].valid = FALSE;
1758 p->procinfo->vcoremap[vcoreid].valid = FALSE;
1761 /* Stop running whatever context is on this core and load a known-good cr3.
1762 * Note this leaves no trace of what was running. This "leaves the process's
1765 * This does not clear the owning proc. Use the other helper for that. */
1766 void abandon_core(void)
1768 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1769 /* Syscalls that don't return will ultimately call abadon_core(), so we need
1770 * to make sure we don't think we are still working on a syscall. */
1771 pcpui->cur_kthread->sysc = 0;
1772 pcpui->cur_kthread->errbuf = 0; /* just in case */
1773 if (pcpui->cur_proc)
1777 /* Helper to clear the core's owning processor and manage refcnting. Pass in
1778 * core_id() to save a couple core_id() calls. */
1779 void clear_owning_proc(uint32_t coreid)
1781 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1782 struct proc *p = pcpui->owning_proc;
1783 pcpui->owning_proc = 0;
1784 pcpui->owning_vcoreid = 0xdeadbeef;
1785 pcpui->cur_ctx = 0; /* catch bugs for now (may go away) */
1790 /* Switches to the address space/context of new_p, doing nothing if we are
1791 * already in new_p. This won't add extra refcnts or anything, and needs to be
1792 * paired with switch_back() at the end of whatever function you are in. Don't
1793 * migrate cores in the middle of a pair. Specifically, the uncounted refs are
1794 * one for the old_proc, which is passed back to the caller, and new_p is
1795 * getting placed in cur_proc. */
1796 struct proc *switch_to(struct proc *new_p)
1798 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1799 struct proc *old_proc;
1800 old_proc = pcpui->cur_proc; /* uncounted ref */
1801 /* If we aren't the proc already, then switch to it */
1802 if (old_proc != new_p) {
1803 pcpui->cur_proc = new_p; /* uncounted ref */
1805 lcr3(new_p->env_cr3);
1812 /* This switches back to old_proc from new_p. Pair it with switch_to(), and
1813 * pass in its return value for old_proc. */
1814 void switch_back(struct proc *new_p, struct proc *old_proc)
1816 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1817 if (old_proc != new_p) {
1818 pcpui->cur_proc = old_proc;
1820 lcr3(old_proc->env_cr3);
1826 /* Will send a TLB shootdown message to every vcore in the main address space
1827 * (aka, all vcores for now). The message will take the start and end virtual
1828 * addresses as well, in case we want to be more clever about how much we
1829 * shootdown and batching our messages. Should do the sanity about rounding up
1830 * and down in this function too.
1832 * Would be nice to have a broadcast kmsg at this point. Note this may send a
1833 * message to the calling core (interrupting it, possibly while holding the
1834 * proc_lock). We don't need to process routine messages since it's an
1835 * immediate message. */
1836 void proc_tlbshootdown(struct proc *p, uintptr_t start, uintptr_t end)
1838 /* TODO: need a better way to find cores running our address space. we can
1839 * have kthreads running syscalls, async calls, processes being created. */
1841 /* TODO: we might be able to avoid locking here in the future (we must hit
1842 * all online, and we can check __mapped). it'll be complicated. */
1843 spin_lock(&p->proc_lock);
1845 case (PROC_RUNNING_S):
1848 case (PROC_RUNNING_M):
1849 /* TODO: (TLB) sanity checks and rounding on the ranges */
1850 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
1851 send_kernel_message(vc_i->pcoreid, __tlbshootdown, start, end,
1856 /* TODO: til we fix shootdowns, there are some odd cases where we
1857 * have the address space loaded, but the state is in transition. */
1861 spin_unlock(&p->proc_lock);
1864 /* Helper, used by __startcore and __set_curctx, which sets up cur_ctx to run a
1865 * given process's vcore. Caller needs to set up things like owning_proc and
1866 * whatnot. Note that we might not have p loaded as current. */
1867 static void __set_curctx_to_vcoreid(struct proc *p, uint32_t vcoreid,
1868 uint32_t old_nr_preempts_sent)
1870 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1871 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1872 struct vcore *vc = vcoreid2vcore(p, vcoreid);
1873 /* Spin until our vcore's old preemption is done. When __SC was sent, we
1874 * were told what the nr_preempts_sent was at that time. Once that many are
1875 * done, it is time for us to run. This forces a 'happens-before' ordering
1876 * on a __PR of our VC before this __SC of the VC. Note the nr_done should
1877 * not exceed old_nr_sent, since further __PR are behind this __SC in the
1879 while (old_nr_preempts_sent != vc->nr_preempts_done)
1881 cmb(); /* read nr_done before any other rd or wr. CPU mb in the atomic. */
1882 /* Mark that this vcore as no longer preempted. No danger of clobbering
1883 * other writes, since this would get turned on in __preempt (which can't be
1884 * concurrent with this function on this core), and the atomic is just
1885 * toggling the one bit (a concurrent VC_K_LOCK will work) */
1886 atomic_and(&vcpd->flags, ~VC_PREEMPTED);
1887 /* Once the VC is no longer preempted, we allow it to receive msgs. We
1888 * could let userspace do it, but handling it here makes it easier for them
1889 * to handle_indirs (when they turn this flag off). Note the atomics
1890 * provide the needed barriers (cmb and mb on flags). */
1891 atomic_or(&vcpd->flags, VC_CAN_RCV_MSG);
1892 printd("[kernel] startcore on physical core %d for process %d's vcore %d\n",
1893 core_id(), p->pid, vcoreid);
1894 /* If notifs are disabled, the vcore was in vcore context and we need to
1895 * restart the vcore_ctx. o/w, we give them a fresh vcore (which is also
1896 * what happens the first time a vcore comes online). No matter what,
1897 * they'll restart in vcore context. It's just a matter of whether or not
1898 * it is the old, interrupted vcore context. */
1899 if (vcpd->notif_disabled) {
1900 /* copy-in the tf we'll pop, then set all security-related fields */
1901 pcpui->actual_ctx = vcpd->vcore_ctx;
1902 proc_secure_ctx(&pcpui->actual_ctx);
1903 } else { /* not restarting from a preemption, use a fresh vcore */
1904 assert(vcpd->vcore_stack);
1905 proc_init_ctx(&pcpui->actual_ctx, vcoreid, vcpd->vcore_entry,
1906 vcpd->vcore_stack, vcpd->vcore_tls_desc);
1907 /* Disable/mask active notifications for fresh vcores */
1908 vcpd->notif_disabled = TRUE;
1910 /* Regardless of whether or not we have a 'fresh' VC, we need to restore the
1911 * FPU state for the VC according to VCPD (which means either a saved FPU
1912 * state or a brand new init). Starting a fresh VC is just referring to the
1913 * GP context we run. The vcore itself needs to have the FPU state loaded
1914 * from when it previously ran and was saved (or a fresh FPU if it wasn't
1915 * saved). For fresh FPUs, the main purpose is for limiting info leakage.
1916 * I think VCs that don't need FPU state for some reason (like having a
1917 * current_uthread) can handle any sort of FPU state, since it gets sorted
1918 * when they pop their next uthread.
1920 * Note this can cause a GP fault on x86 if the state is corrupt. In lieu
1921 * of reading in the huge FP state and mucking with mxcsr_mask, we should
1922 * handle this like a KPF on user code. */
1923 restore_vc_fp_state(vcpd);
1924 /* cur_ctx was built above (in actual_ctx), now use it */
1925 pcpui->cur_ctx = &pcpui->actual_ctx;
1926 /* this cur_ctx will get run when the kernel returns / idles */
1927 vcore_account_online(p, vcoreid);
1930 /* Changes calling vcore to be vcoreid. enable_my_notif tells us about how the
1931 * state calling vcore wants to be left in. It will look like caller_vcoreid
1932 * was preempted. Note we don't care about notif_pending.
1935 * 0 if we successfully changed to the target vcore.
1936 * -EBUSY if the target vcore is already mapped (a good kind of failure)
1937 * -EAGAIN if we failed for some other reason and need to try again. For
1938 * example, the caller could be preempted, and we never even attempted to
1940 * -EINVAL some userspace bug */
1941 int proc_change_to_vcore(struct proc *p, uint32_t new_vcoreid,
1942 bool enable_my_notif)
1944 uint32_t caller_vcoreid, pcoreid = core_id();
1945 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1946 struct preempt_data *caller_vcpd;
1947 struct vcore *caller_vc, *new_vc;
1948 struct event_msg preempt_msg = {0};
1949 int retval = -EAGAIN; /* by default, try again */
1950 /* Need to not reach outside the vcoremap, which might be smaller in the
1951 * future, but should always be as big as max_vcores */
1952 if (new_vcoreid >= p->procinfo->max_vcores)
1954 /* Need to lock to prevent concurrent vcore changes, like in yield. */
1955 spin_lock(&p->proc_lock);
1956 /* new_vcoreid is already runing, abort */
1957 if (vcore_is_mapped(p, new_vcoreid)) {
1961 /* Need to make sure our vcore is allowed to switch. We might have a
1962 * __preempt, __death, etc, coming in. Similar to yield. */
1964 case (PROC_RUNNING_M):
1965 break; /* the only case we can proceed */
1966 case (PROC_RUNNING_S): /* user bug, just return */
1967 case (PROC_DYING): /* incoming __death */
1968 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1971 panic("Weird state(%s) in %s()", procstate2str(p->state),
1974 /* This is which vcore this pcore thinks it is, regardless of any unmappings
1975 * that may have happened remotely (with __PRs waiting to run) */
1976 caller_vcoreid = pcpui->owning_vcoreid;
1977 caller_vc = vcoreid2vcore(p, caller_vcoreid);
1978 caller_vcpd = &p->procdata->vcore_preempt_data[caller_vcoreid];
1979 /* This is how we detect whether or not a __PR happened. If it did, just
1980 * abort and handle the kmsg. No new __PRs are coming since we hold the
1981 * lock. This also detects a __PR followed by a __SC for the same VC. */
1982 if (caller_vc->nr_preempts_sent != caller_vc->nr_preempts_done)
1984 /* Sanity checks. If we were preempted or are dying, we should have noticed
1986 assert(is_mapped_vcore(p, pcoreid));
1987 assert(caller_vcoreid == get_vcoreid(p, pcoreid));
1988 /* Should only call from vcore context */
1989 if (!caller_vcpd->notif_disabled) {
1991 printk("[kernel] You tried to change vcores from uthread ctx\n");
1994 /* Ok, we're clear to do the switch. Lets figure out who the new one is */
1995 new_vc = vcoreid2vcore(p, new_vcoreid);
1996 printd("[kernel] changing vcore %d to vcore %d\n", caller_vcoreid,
1998 /* enable_my_notif signals how we'll be restarted */
1999 if (enable_my_notif) {
2000 /* if they set this flag, then the vcore can just restart from scratch,
2001 * and we don't care about either the uthread_ctx or the vcore_ctx. */
2002 caller_vcpd->notif_disabled = FALSE;
2003 /* Don't need to save the FPU. There should be no uthread or other
2004 * reason to return to the FPU state. */
2006 /* need to set up the calling vcore's ctx so that it'll get restarted by
2007 * __startcore, to make the caller look like it was preempted. */
2008 copy_current_ctx_to(&caller_vcpd->vcore_ctx);
2009 save_vc_fp_state(caller_vcpd);
2011 /* Mark our core as preempted (for userspace recovery). Userspace checks
2012 * this in handle_indirs, and it needs to check the mbox regardless of
2013 * enable_my_notif. This does mean cores that change-to with no intent to
2014 * return will be tracked as PREEMPTED until they start back up (maybe
2016 atomic_or(&caller_vcpd->flags, VC_PREEMPTED);
2017 /* Either way, unmap and offline our current vcore */
2018 /* Move the caller from online to inactive */
2019 TAILQ_REMOVE(&p->online_vcs, caller_vc, list);
2020 /* We don't bother with the notif_pending race. note that notif_pending
2021 * could still be set. this was a preempted vcore, and userspace will need
2022 * to deal with missed messages (preempt_recover() will handle that) */
2023 TAILQ_INSERT_HEAD(&p->inactive_vcs, caller_vc, list);
2024 /* Move the new one from inactive to online */
2025 TAILQ_REMOVE(&p->inactive_vcs, new_vc, list);
2026 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
2027 /* Change the vcore map */
2028 __seq_start_write(&p->procinfo->coremap_seqctr);
2029 __unmap_vcore(p, caller_vcoreid);
2030 __map_vcore(p, new_vcoreid, pcoreid);
2031 __seq_end_write(&p->procinfo->coremap_seqctr);
2032 vcore_account_offline(p, caller_vcoreid);
2033 /* Send either a PREEMPT msg or a CHECK_MSGS msg. If they said to
2034 * enable_my_notif, then all userspace needs is to check messages, not a
2035 * full preemption recovery. */
2036 preempt_msg.ev_type = (enable_my_notif ? EV_CHECK_MSGS : EV_VCORE_PREEMPT);
2037 preempt_msg.ev_arg2 = caller_vcoreid; /* arg2 is 32 bits */
2038 /* Whenever we send msgs with the proc locked, we need at least 1 online.
2039 * In this case, it's the one we just changed to. */
2040 assert(!TAILQ_EMPTY(&p->online_vcs));
2041 send_kernel_event(p, &preempt_msg, new_vcoreid);
2042 /* So this core knows which vcore is here. (cur_proc and owning_proc are
2043 * already correct): */
2044 pcpui->owning_vcoreid = new_vcoreid;
2045 /* Until we set_curctx, we don't really have a valid current tf. The stuff
2046 * in that old one is from our previous vcore, not the current
2047 * owning_vcoreid. This matters for other KMSGS that will run before
2048 * __set_curctx (like __notify). */
2050 /* Need to send a kmsg to finish. We can't set_curctx til the __PR is done,
2051 * but we can't spin right here while holding the lock (can't spin while
2052 * waiting on a message, roughly) */
2053 send_kernel_message(pcoreid, __set_curctx, (long)p, (long)new_vcoreid,
2054 (long)new_vc->nr_preempts_sent, KMSG_ROUTINE);
2056 /* Fall through to exit */
2058 spin_unlock(&p->proc_lock);
2062 /* Kernel message handler to start a process's context on this core, when the
2063 * core next considers running a process. Tightly coupled with __proc_run_m().
2064 * Interrupts are disabled. */
2065 void __startcore(uint32_t srcid, long a0, long a1, long a2)
2067 uint32_t vcoreid = (uint32_t)a1;
2068 uint32_t coreid = core_id();
2069 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2070 struct proc *p_to_run = (struct proc *)a0;
2071 uint32_t old_nr_preempts_sent = (uint32_t)a2;
2074 /* Can not be any TF from a process here already */
2075 assert(!pcpui->owning_proc);
2076 /* the sender of the kmsg increfed already for this saved ref to p_to_run */
2077 pcpui->owning_proc = p_to_run;
2078 pcpui->owning_vcoreid = vcoreid;
2079 /* sender increfed again, assuming we'd install to cur_proc. only do this
2080 * if no one else is there. this is an optimization, since we expect to
2081 * send these __startcores to idles cores, and this saves a scramble to
2082 * incref when all of the cores restartcore/startcore later. Keep in sync
2083 * with __proc_give_cores() and __proc_run_m(). */
2084 if (!pcpui->cur_proc) {
2085 pcpui->cur_proc = p_to_run; /* install the ref to cur_proc */
2086 lcr3(p_to_run->env_cr3); /* load the page tables to match cur_proc */
2088 proc_decref(p_to_run); /* can't install, decref the extra one */
2090 /* Note we are not necessarily in the cr3 of p_to_run */
2091 /* Now that we sorted refcnts and know p / which vcore it should be, set up
2092 * pcpui->cur_ctx so that it will run that particular vcore */
2093 __set_curctx_to_vcoreid(p_to_run, vcoreid, old_nr_preempts_sent);
2096 /* Kernel message handler to load a proc's vcore context on this core. Similar
2097 * to __startcore, except it is used when p already controls the core (e.g.
2098 * change_to). Since the core is already controlled, pcpui such as owning proc,
2099 * vcoreid, and cur_proc are all already set. */
2100 void __set_curctx(uint32_t srcid, long a0, long a1, long a2)
2102 struct proc *p = (struct proc*)a0;
2103 uint32_t vcoreid = (uint32_t)a1;
2104 uint32_t old_nr_preempts_sent = (uint32_t)a2;
2105 __set_curctx_to_vcoreid(p, vcoreid, old_nr_preempts_sent);
2108 /* Bail out if it's the wrong process, or if they no longer want a notif. Try
2109 * not to grab locks or write access to anything that isn't per-core in here. */
2110 void __notify(uint32_t srcid, long a0, long a1, long a2)
2112 uint32_t vcoreid, coreid = core_id();
2113 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2114 struct preempt_data *vcpd;
2115 struct proc *p = (struct proc*)a0;
2117 /* Not the right proc */
2118 if (p != pcpui->owning_proc)
2120 /* the core might be owned, but not have a valid cur_ctx (if we're in the
2121 * process of changing */
2122 if (!pcpui->cur_ctx)
2124 /* Common cur_ctx sanity checks. Note cur_ctx could be an _S's scp_ctx */
2125 vcoreid = pcpui->owning_vcoreid;
2126 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
2127 /* for SCPs that haven't (and might never) call vc_event_init, like rtld.
2128 * this is harmless for MCPS to check this */
2129 if (!scp_is_vcctx_ready(vcpd))
2131 printd("received active notification for proc %d's vcore %d on pcore %d\n",
2132 p->procinfo->pid, vcoreid, coreid);
2133 /* sort signals. notifs are now masked, like an interrupt gate */
2134 if (vcpd->notif_disabled)
2136 vcpd->notif_disabled = TRUE;
2137 /* save the old ctx in the uthread slot, build and pop a new one. Note that
2138 * silly state isn't our business for a notification. */
2139 copy_current_ctx_to(&vcpd->uthread_ctx);
2140 memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
2141 proc_init_ctx(pcpui->cur_ctx, vcoreid, vcpd->vcore_entry,
2142 vcpd->vcore_stack, vcpd->vcore_tls_desc);
2143 /* this cur_ctx will get run when the kernel returns / idles */
2146 void __preempt(uint32_t srcid, long a0, long a1, long a2)
2148 uint32_t vcoreid, coreid = core_id();
2149 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2150 struct preempt_data *vcpd;
2151 struct proc *p = (struct proc*)a0;
2154 if (p != pcpui->owning_proc) {
2155 panic("__preempt arrived for a process (%p) that was not owning (%p)!",
2156 p, pcpui->owning_proc);
2158 /* Common cur_ctx sanity checks */
2159 assert(pcpui->cur_ctx);
2160 assert(pcpui->cur_ctx == &pcpui->actual_ctx);
2161 vcoreid = pcpui->owning_vcoreid;
2162 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
2163 printd("[kernel] received __preempt for proc %d's vcore %d on pcore %d\n",
2164 p->procinfo->pid, vcoreid, coreid);
2165 /* if notifs are disabled, the vcore is in vcore context (as far as we're
2166 * concerned), and we save it in the vcore slot. o/w, we save the process's
2167 * cur_ctx in the uthread slot, and it'll appear to the vcore when it comes
2168 * back up the uthread just took a notification. */
2169 if (vcpd->notif_disabled)
2170 copy_current_ctx_to(&vcpd->vcore_ctx);
2172 copy_current_ctx_to(&vcpd->uthread_ctx);
2173 /* Userspace in a preemption handler on another core might be copying FP
2174 * state from memory (VCPD) at the moment, and if so we don't want to
2175 * clobber it. In this rare case, our current core's FPU state should be
2176 * the same as whatever is in VCPD, so this shouldn't be necessary, but the
2177 * arch-specific save function might do something other than write out
2178 * bit-for-bit the exact same data. Checking STEALING suffices, since we
2179 * hold the K_LOCK (preventing userspace from starting a fresh STEALING
2180 * phase concurrently). */
2181 if (!(atomic_read(&vcpd->flags) & VC_UTHREAD_STEALING))
2182 save_vc_fp_state(vcpd);
2183 /* Mark the vcore as preempted and unlock (was locked by the sender). */
2184 atomic_or(&vcpd->flags, VC_PREEMPTED);
2185 atomic_and(&vcpd->flags, ~VC_K_LOCK);
2186 /* either __preempt or proc_yield() ends the preempt phase. */
2187 p->procinfo->vcoremap[vcoreid].preempt_pending = 0;
2188 vcore_account_offline(p, vcoreid);
2189 wmb(); /* make sure everything else hits before we finish the preempt */
2190 /* up the nr_done, which signals the next __startcore for this vc */
2191 p->procinfo->vcoremap[vcoreid].nr_preempts_done++;
2192 /* We won't restart the process later. current gets cleared later when we
2193 * notice there is no owning_proc and we have nothing to do (smp_idle,
2194 * restartcore, etc) */
2195 clear_owning_proc(coreid);
2198 /* Kernel message handler to clean up the core when a process is dying.
2199 * Note this leaves no trace of what was running.
2200 * It's okay if death comes to a core that's already idling and has no current.
2201 * It could happen if a process decref'd before __proc_startcore could incref. */
2202 void __death(uint32_t srcid, long a0, long a1, long a2)
2204 uint32_t vcoreid, coreid = core_id();
2205 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2206 struct proc *p = pcpui->owning_proc;
2208 vcoreid = pcpui->owning_vcoreid;
2209 printd("[kernel] death on physical core %d for process %d's vcore %d\n",
2210 coreid, p->pid, vcoreid);
2211 vcore_account_offline(p, vcoreid); /* in case anyone is counting */
2212 /* We won't restart the process later. current gets cleared later when
2213 * we notice there is no owning_proc and we have nothing to do
2214 * (smp_idle, restartcore, etc) */
2215 clear_owning_proc(coreid);
2219 /* Kernel message handler, usually sent IMMEDIATE, to shoot down virtual
2220 * addresses from a0 to a1. */
2221 void __tlbshootdown(uint32_t srcid, long a0, long a1, long a2)
2223 /* TODO: (TLB) something more intelligent with the range */
2227 void print_allpids(void)
2229 void print_proc_state(void *item, void *opaque)
2231 struct proc *p = (struct proc*)item;
2233 /* this actually adds an extra space, since no progname is ever
2234 * PROGNAME_SZ bytes, due to the \0 counted in PROGNAME. */
2235 printk("%8d %-*s %-10s %6d\n", p->pid, PROC_PROGNAME_SZ, p->progname,
2236 procstate2str(p->state), p->ppid);
2238 char dashes[PROC_PROGNAME_SZ];
2239 memset(dashes, '-', PROC_PROGNAME_SZ);
2240 dashes[PROC_PROGNAME_SZ - 1] = '\0';
2241 /* -5, for 'Name ' */
2242 printk(" PID Name %-*s State Parent \n",
2243 PROC_PROGNAME_SZ - 5, "");
2244 printk("------------------------------%s\n", dashes);
2245 spin_lock(&pid_hash_lock);
2246 hash_for_each(pid_hash, print_proc_state, NULL);
2247 spin_unlock(&pid_hash_lock);
2250 void proc_get_set(struct process_set *pset)
2252 void enum_proc(void *item, void *opaque)
2254 struct proc *p = (struct proc*) item;
2255 struct process_set *pset = (struct process_set *) opaque;
2257 if (pset->num_processes < pset->size) {
2260 pset->procs[pset->num_processes] = p;
2261 pset->num_processes++;
2265 static const size_t num_extra_alloc = 16;
2270 proc_free_set(pset);
2271 pset->size = atomic_read(&num_envs) + num_extra_alloc;
2272 pset->num_processes = 0;
2273 pset->procs = (struct proc **)
2274 kzmalloc(pset->size * sizeof(struct proc *), KMALLOC_WAIT);
2276 error(-ENOMEM, NULL);
2278 spin_lock(&pid_hash_lock);
2279 hash_for_each(pid_hash, enum_proc, pset);
2280 spin_unlock(&pid_hash_lock);
2282 } while (pset->num_processes == pset->size);
2285 void proc_free_set(struct process_set *pset)
2287 for (size_t i = 0; i < pset->num_processes; i++)
2288 proc_decref(pset->procs[i]);
2292 void print_proc_info(pid_t pid)
2295 uint64_t total_time = 0;
2296 struct proc *child, *p = pid2proc(pid);
2299 printk("Bad PID.\n");
2302 spinlock_debug(&p->proc_lock);
2303 //spin_lock(&p->proc_lock); // No locking!!
2304 printk("struct proc: %p\n", p);
2305 printk("Program name: %s\n", p->progname);
2306 printk("PID: %d\n", p->pid);
2307 printk("PPID: %d\n", p->ppid);
2308 printk("State: %s (%p)\n", procstate2str(p->state), p->state);
2309 printk("\tIs %san MCP\n", p->procinfo->is_mcp ? "" : "not ");
2310 printk("Refcnt: %d\n", atomic_read(&p->p_kref.refcount) - 1);
2311 printk("Flags: 0x%08x\n", p->env_flags);
2312 printk("CR3(phys): %p\n", p->env_cr3);
2313 printk("Num Vcores: %d\n", p->procinfo->num_vcores);
2314 printk("Vcore Lists (may be in flux w/o locking):\n----------------------\n");
2315 printk("Online:\n");
2316 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
2317 printk("\tVcore %d -> Pcore %d\n", vcore2vcoreid(p, vc_i), vc_i->pcoreid);
2318 printk("Bulk Preempted:\n");
2319 TAILQ_FOREACH(vc_i, &p->bulk_preempted_vcs, list)
2320 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2321 printk("Inactive / Yielded:\n");
2322 TAILQ_FOREACH(vc_i, &p->inactive_vcs, list)
2323 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2324 printk("Nsec Online, up to the last offlining:\n------------------------");
2325 for (int i = 0; i < p->procinfo->max_vcores; i++) {
2326 uint64_t vc_time = tsc2nsec(vcore_account_gettotal(p, i));
2329 printk(" VC %3d: %14llu", i, vc_time);
2330 total_time += vc_time;
2333 printk("Total CPU-NSEC: %llu\n", total_time);
2334 printk("Resources:\n------------------------\n");
2335 for (int i = 0; i < MAX_NUM_RESOURCES; i++)
2336 printk("\tRes type: %02d, amt wanted: %08d, amt granted: %08d\n", i,
2337 p->procdata->res_req[i].amt_wanted, p->procinfo->res_grant[i]);
2338 printk("Open Files:\n");
2339 struct fd_table *files = &p->open_files;
2340 if (spin_locked(&files->lock)) {
2341 spinlock_debug(&files->lock);
2342 printk("FILE LOCK HELD, ABORTING\n");
2346 spin_lock(&files->lock);
2347 for (int i = 0; i < files->max_files; i++) {
2348 if (GET_BITMASK_BIT(files->open_fds->fds_bits, i)) {
2349 printk("\tFD: %02d, ", i);
2350 if (files->fd[i].fd_file) {
2351 printk("File: %p, File name: %s\n", files->fd[i].fd_file,
2352 file_name(files->fd[i].fd_file));
2354 assert(files->fd[i].fd_chan);
2355 print_chaninfo(files->fd[i].fd_chan);
2359 spin_unlock(&files->lock);
2360 printk("Children: (PID (struct proc *))\n");
2361 TAILQ_FOREACH(child, &p->children, sibling_link)
2362 printk("\t%d (%p)\n", child->pid, child);
2363 /* no locking / unlocking or refcnting */
2364 // spin_unlock(&p->proc_lock);
2368 /* Debugging function, checks what (process, vcore) is supposed to run on this
2369 * pcore. Meant to be called from smp_idle() before halting. */
2370 void check_my_owner(void)
2372 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2373 void shazbot(void *item, void *opaque)
2375 struct proc *p = (struct proc*)item;
2378 spin_lock(&p->proc_lock);
2379 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
2380 /* this isn't true, a __startcore could be on the way and we're
2381 * already "online" */
2382 if (vc_i->pcoreid == core_id()) {
2383 /* Immediate message was sent, we should get it when we enable
2384 * interrupts, which should cause us to skip cpu_halt() */
2385 if (!STAILQ_EMPTY(&pcpui->immed_amsgs))
2387 printk("Owned pcore (%d) has no owner, by %p, vc %d!\n",
2388 core_id(), p, vcore2vcoreid(p, vc_i));
2389 spin_unlock(&p->proc_lock);
2390 spin_unlock(&pid_hash_lock);
2394 spin_unlock(&p->proc_lock);
2396 assert(!irq_is_enabled());
2398 if (!booting && !pcpui->owning_proc) {
2399 spin_lock(&pid_hash_lock);
2400 hash_for_each(pid_hash, shazbot, NULL);
2401 spin_unlock(&pid_hash_lock);