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>
27 #include <ros/procinfo.h>
30 struct kmem_cache *proc_cache;
32 /* Other helpers, implemented later. */
33 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid);
34 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid);
35 static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid);
36 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid);
37 static void __proc_free(struct kref *kref);
38 static bool scp_is_vcctx_ready(struct preempt_data *vcpd);
39 static void save_vc_fp_state(struct preempt_data *vcpd);
40 static void restore_vc_fp_state(struct preempt_data *vcpd);
43 #define PID_MAX 32767 // goes from 0 to 32767, with 0 reserved
44 static DECL_BITMASK(pid_bmask, PID_MAX + 1);
45 spinlock_t pid_bmask_lock = SPINLOCK_INITIALIZER;
46 struct hashtable *pid_hash;
47 spinlock_t pid_hash_lock; // initialized in proc_init
49 /* Finds the next free entry (zero) entry in the pid_bitmask. Set means busy.
50 * PID 0 is reserved (in proc_init). A return value of 0 is a failure (and
51 * you'll also see a warning, for now). Consider doing this with atomics. */
52 static pid_t get_free_pid(void)
54 static pid_t next_free_pid = 1;
57 spin_lock(&pid_bmask_lock);
58 // atomically (can lock for now, then change to atomic_and_return
59 FOR_CIRC_BUFFER(next_free_pid, PID_MAX + 1, i) {
60 // always points to the next to test
61 next_free_pid = (next_free_pid + 1) % (PID_MAX + 1);
62 if (!GET_BITMASK_BIT(pid_bmask, i)) {
63 SET_BITMASK_BIT(pid_bmask, i);
68 spin_unlock(&pid_bmask_lock);
70 warn("Shazbot! Unable to find a PID! You need to deal with this!\n");
74 /* Return a pid to the pid bitmask */
75 static void put_free_pid(pid_t pid)
77 spin_lock(&pid_bmask_lock);
78 CLR_BITMASK_BIT(pid_bmask, pid);
79 spin_unlock(&pid_bmask_lock);
82 /* 'resume' is the time int ticks of the most recent onlining. 'total' is the
83 * amount of time in ticks consumed up to and including the current offlining.
85 * We could move these to the map and unmap of vcores, though not every place
86 * uses that (SCPs, in particular). However, maps/unmaps happen remotely;
87 * something to consider. If we do it remotely, we can batch them up and do one
88 * rdtsc() for all of them. For now, I want to do them on the core, around when
89 * we do the context change. It'll also parallelize the accounting a bit. */
90 void vcore_account_online(struct proc *p, uint32_t vcoreid)
92 struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
93 vc->resume_ticks = read_tsc();
96 void vcore_account_offline(struct proc *p, uint32_t vcoreid)
98 struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
99 vc->total_ticks += read_tsc() - vc->resume_ticks;
102 uint64_t vcore_account_gettotal(struct proc *p, uint32_t vcoreid)
104 struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
105 return vc->total_ticks;
108 /* While this could be done with just an assignment, this gives us the
109 * opportunity to check for bad transitions. Might compile these out later, so
110 * we shouldn't rely on them for sanity checking from userspace. */
111 int __proc_set_state(struct proc *p, uint32_t state)
113 uint32_t curstate = p->state;
114 /* Valid transitions:
133 * These ought to be implemented later (allowed, not thought through yet).
137 #if 1 // some sort of correctness flag
140 if (!(state & (PROC_RUNNABLE_S | PROC_DYING)))
141 panic("Invalid State Transition! PROC_CREATED to %02x", state);
143 case PROC_RUNNABLE_S:
144 if (!(state & (PROC_RUNNING_S | PROC_DYING)))
145 panic("Invalid State Transition! PROC_RUNNABLE_S to %02x", state);
148 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
150 panic("Invalid State Transition! PROC_RUNNING_S to %02x", state);
153 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNING_S | PROC_RUNNABLE_M |
155 panic("Invalid State Transition! PROC_WAITING to %02x", state);
158 if (state != PROC_DYING_ABORT)
159 panic("Invalid State Transition! PROC_DYING to %02x", state);
161 case PROC_DYING_ABORT:
162 panic("Invalid State Transition! PROC_DYING to %02x", state);
164 case PROC_RUNNABLE_M:
165 if (!(state & (PROC_RUNNING_M | PROC_DYING)))
166 panic("Invalid State Transition! PROC_RUNNABLE_M to %02x", state);
169 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
171 panic("Invalid State Transition! PROC_RUNNING_M to %02x", state);
179 /* Returns a pointer to the proc with the given pid, or 0 if there is none.
180 * This uses get_not_zero, since it is possible the refcnt is 0, which means the
181 * process is dying and we should not have the ref (and thus return 0). We need
182 * to lock to protect us from getting p, (someone else removes and frees p),
183 * then get_not_zero() on p.
184 * Don't push the locking into the hashtable without dealing with this. */
185 struct proc *pid2proc(pid_t pid)
187 spin_lock(&pid_hash_lock);
188 struct proc *p = hashtable_search(pid_hash, (void*)(long)pid);
190 if (!kref_get_not_zero(&p->p_kref, 1))
192 spin_unlock(&pid_hash_lock);
196 /* Used by devproc for successive reads of the proc table.
197 * Returns a pointer to the nth proc, or 0 if there is none.
198 * This uses get_not_zero, since it is possible the refcnt is 0, which means the
199 * process is dying and we should not have the ref (and thus return 0). We need
200 * to lock to protect us from getting p, (someone else removes and frees p),
201 * then get_not_zero() on p.
202 * Don't push the locking into the hashtable without dealing with this. */
203 struct proc *pid_nth(unsigned int n)
206 spin_lock(&pid_hash_lock);
207 if (!hashtable_count(pid_hash)) {
208 spin_unlock(&pid_hash_lock);
211 struct hashtable_itr *iter = hashtable_iterator(pid_hash);
212 p = hashtable_iterator_value(iter);
215 /* if this process is not valid, it doesn't count,
219 if (kref_get_not_zero(&p->p_kref, 1)) {
220 /* this one counts */
222 printd("pid_nth: at end, p %p\n", p);
225 kref_put(&p->p_kref);
228 if (!hashtable_iterator_advance(iter)) {
232 p = hashtable_iterator_value(iter);
235 spin_unlock(&pid_hash_lock);
240 /* Performs any initialization related to processes, such as create the proc
241 * cache, prep the scheduler, etc. When this returns, we should be ready to use
242 * any process related function. */
245 /* Catch issues with the vcoremap and TAILQ_ENTRY sizes */
246 static_assert(sizeof(TAILQ_ENTRY(vcore)) == sizeof(void*) * 2);
247 proc_cache = kmem_cache_create("proc", sizeof(struct proc),
249 __alignof__(struct proc)), 0, NULL, 0,
251 /* Init PID mask and hash. pid 0 is reserved. */
252 SET_BITMASK_BIT(pid_bmask, 0);
253 spinlock_init(&pid_hash_lock);
254 spin_lock(&pid_hash_lock);
255 pid_hash = create_hashtable(100, __generic_hash, __generic_eq);
256 spin_unlock(&pid_hash_lock);
259 atomic_init(&num_envs, 0);
262 void proc_set_username(struct proc *p, char *name)
264 set_username(&p->user, name);
268 * Copies username from the parent process. This is the only case where a
269 * reader blocks writing, just to be extra safe during process initialization.
271 * Note that since this is intended to be called during initialization, the
272 * child's name lock is NOT used for writing. Nothing else should be able to
273 * read or write yet, so this can be a simple memcpy once the parent is locked.
275 void proc_inherit_parent_username(struct proc *child, struct proc *parent)
277 spin_lock(&parent->user.name_lock);
279 // copy entire parent buffer for constant runtime
280 memcpy(child->user.name, parent->user.name, sizeof(child->user.name));
282 spin_unlock(&parent->user.name_lock);
285 void proc_set_progname(struct proc *p, char *name)
288 name = DEFAULT_PROGNAME;
290 /* might have an issue if a dentry name isn't null terminated, and we'd get
291 * extra junk up to progname_sz. Or crash. */
292 strlcpy(p->progname, name, PROC_PROGNAME_SZ);
295 void proc_replace_binary_path(struct proc *p, char *path)
298 free_path(p, p->binary_path);
299 p->binary_path = path;
302 /* Be sure you init'd the vcore lists before calling this. */
303 void proc_init_procinfo(struct proc* p)
305 p->procinfo->pid = p->pid;
306 p->procinfo->ppid = p->ppid;
307 p->procinfo->max_vcores = max_vcores(p);
308 p->procinfo->tsc_freq = __proc_global_info.tsc_freq;
309 p->procinfo->timing_overhead = __proc_global_info.tsc_overhead;
310 p->procinfo->program_end = 0;
311 /* 0'ing the arguments. Some higher function will need to set them */
312 memset(p->procinfo->res_grant, 0, sizeof(p->procinfo->res_grant));
313 /* 0'ing the vcore/pcore map. Will link the vcores later. */
314 memset(&p->procinfo->vcoremap, 0, sizeof(p->procinfo->vcoremap));
315 memset(&p->procinfo->pcoremap, 0, sizeof(p->procinfo->pcoremap));
316 p->procinfo->num_vcores = 0;
317 p->procinfo->is_mcp = FALSE;
318 p->procinfo->coremap_seqctr = SEQCTR_INITIALIZER;
319 /* It's a bug in the kernel if we let them ask for more than max */
320 for (int i = 0; i < p->procinfo->max_vcores; i++) {
321 TAILQ_INSERT_TAIL(&p->inactive_vcs, &p->procinfo->vcoremap[i], list);
325 void proc_init_procdata(struct proc *p)
327 memset(p->procdata, 0, sizeof(struct procdata));
328 /* processes can't go into vc context on vc 0 til they unset this. This is
329 * for processes that block before initing uthread code (like rtld). */
330 atomic_set(&p->procdata->vcore_preempt_data[0].flags, VC_SCP_NOVCCTX);
333 static void proc_open_stdfds(struct proc *p)
336 struct proc *old_current = current;
338 /* Due to the way the syscall helpers assume the target process is current,
339 * we need to set current temporarily. We don't use switch_to, since that
340 * actually loads the process's address space, which might be empty or
341 * incomplete. These syscalls shouldn't access user memory, especially
342 * considering how we're probably in the boot pgdir. */
344 fd = sysopenat(AT_FDCWD, "#cons/stdin", O_READ);
346 fd = sysopenat(AT_FDCWD, "#cons/stdout", O_WRITE);
348 fd = sysopenat(AT_FDCWD, "#cons/stderr", O_WRITE);
350 current = old_current;
353 /* Allocates and initializes a process, with the given parent. Currently
354 * writes the *p into **pp, and returns 0 on success, < 0 for an error.
356 * - ENOFREEPID if it can't get a PID
357 * - ENOMEM on memory exhaustion */
358 error_t proc_alloc(struct proc **pp, struct proc *parent, int flags)
363 if (!(p = kmem_cache_alloc(proc_cache, 0)))
365 /* zero everything by default, other specific items are set below */
366 memset(p, 0, sizeof(*p));
368 /* only one ref, which we pass back. the old 'existence' ref is managed by
370 kref_init(&p->p_kref, __proc_free, 1);
371 /* Initialize the address space */
372 if ((r = env_setup_vm(p)) < 0) {
373 kmem_cache_free(proc_cache, p);
376 if (!(p->pid = get_free_pid())) {
377 kmem_cache_free(proc_cache, p);
380 if (parent && parent->binary_path)
381 kstrdup(&p->binary_path, parent->binary_path);
382 /* Set the basic status variables. */
383 spinlock_init(&p->proc_lock);
384 spinlock_init(&p->user.name_lock);
385 p->exitcode = 1337; /* so we can see processes killed by the kernel */
387 p->ppid = parent->pid;
388 proc_inherit_parent_username(p, parent);
389 proc_incref(p, 1); /* storing a ref in the parent */
390 /* using the CV's lock to protect anything related to child waiting */
391 cv_lock(&parent->child_wait);
392 TAILQ_INSERT_TAIL(&parent->children, p, sibling_link);
393 cv_unlock(&parent->child_wait);
396 memset(p->user.name, 0, sizeof(p->user.name));
397 if (strcmp(p->user.name, eve.name) != 0) {
398 printk("Parentless process assigned username \"\"\n");
399 printk("User \"\" does not have hostowner privileges\n");
402 TAILQ_INIT(&p->children);
403 cv_init(&p->child_wait);
404 p->state = PROC_CREATED; /* shouldn't go through state machine for init */
406 spinlock_init(&p->vmr_lock);
407 spinlock_init(&p->pte_lock);
408 TAILQ_INIT(&p->vm_regions); /* could init this in the slab */
410 /* Initialize the vcore lists, we'll build the inactive list so that it
411 * includes all vcores when we initialize procinfo. Do this before initing
413 TAILQ_INIT(&p->online_vcs);
414 TAILQ_INIT(&p->bulk_preempted_vcs);
415 TAILQ_INIT(&p->inactive_vcs);
416 /* Init procinfo/procdata. Procinfo's argp/argb are 0'd */
417 proc_init_procinfo(p);
418 proc_init_procdata(p);
420 /* Initialize the generic sysevent ring buffer */
421 SHARED_RING_INIT(&p->procdata->syseventring);
422 /* Initialize the frontend of the sysevent ring buffer */
423 FRONT_RING_INIT(&p->syseventfrontring,
424 &p->procdata->syseventring,
427 /* Init FS structures TODO: cleanup (might pull this out) */
428 kref_get(&default_ns.kref, 1);
430 spinlock_init(&p->fs_env.lock);
431 p->fs_env.umask = parent ? parent->fs_env.umask : S_IWGRP | S_IWOTH;
432 p->fs_env.root = p->ns->root->mnt_root;
433 kref_get(&p->fs_env.root->d_kref, 1);
434 p->fs_env.pwd = parent ? parent->fs_env.pwd : p->fs_env.root;
435 kref_get(&p->fs_env.pwd->d_kref, 1);
436 memset(&p->open_files, 0, sizeof(p->open_files)); /* slightly ghetto */
437 spinlock_init(&p->open_files.lock);
438 p->open_files.max_files = NR_OPEN_FILES_DEFAULT;
439 p->open_files.max_fdset = NR_FILE_DESC_DEFAULT;
440 p->open_files.fd = p->open_files.fd_array;
441 p->open_files.open_fds = (struct fd_set*)&p->open_files.open_fds_init;
443 if (flags & PROC_DUP_FGRP)
444 clone_fdt(&parent->open_files, &p->open_files);
446 /* no parent, we're created from the kernel */
449 /* Init the ucq hash lock */
450 p->ucq_hashlock = (struct hashlock*)&p->ucq_hl_noref;
451 hashlock_init_irqsave(p->ucq_hashlock, HASHLOCK_DEFAULT_SZ);
453 atomic_inc(&num_envs);
454 frontend_proc_init(p);
455 plan9setup(p, parent, flags);
457 TAILQ_INIT(&p->abortable_sleepers);
458 spinlock_init_irqsave(&p->abort_list_lock);
459 memset(&p->vmm, 0, sizeof(struct vmm));
460 spinlock_init(&p->vmm.lock);
461 qlock_init(&p->vmm.qlock);
462 printd("[%08x] new process %08x\n", current ? current->pid : 0, p->pid);
467 /* We have a bunch of different ways to make processes. Call this once the
468 * process is ready to be used by the rest of the system. For now, this just
469 * means when it is ready to be named via the pidhash. In the future, we might
470 * push setting the state to CREATED into here. */
471 void __proc_ready(struct proc *p)
473 /* Tell the ksched about us. TODO: do we need to worry about the ksched
474 * doing stuff to us before we're added to the pid_hash? */
475 __sched_proc_register(p);
476 spin_lock(&pid_hash_lock);
477 hashtable_insert(pid_hash, (void*)(long)p->pid, p);
478 spin_unlock(&pid_hash_lock);
481 /* Creates a process from the specified file, argvs, and envps. */
482 struct proc *proc_create(struct file *prog, char **argv, char **envp)
486 if ((r = proc_alloc(&p, current, 0 /* flags */)) < 0)
487 panic("proc_create: %d", r);
488 int argc = 0, envc = 0;
489 if(argv) while(argv[argc]) argc++;
490 if(envp) while(envp[envc]) envc++;
491 proc_set_progname(p, argc ? argv[0] : NULL);
492 assert(load_elf(p, prog, argc, argv, envc, envp) == 0);
497 static int __cb_assert_no_pg(struct proc *p, pte_t pte, void *va, void *arg)
499 assert(pte_is_unmapped(pte));
503 /* This is called by kref_put(), once the last reference to the process is
504 * gone. Don't call this otherwise (it will panic). It will clean up the
505 * address space and deallocate any other used memory. */
506 static void __proc_free(struct kref *kref)
508 struct proc *p = container_of(kref, struct proc, p_kref);
512 printd("[PID %d] freeing proc: %d\n", current ? current->pid : 0, p->pid);
513 // All parts of the kernel should have decref'd before __proc_free is called
514 assert(kref_refcnt(&p->p_kref) == 0);
515 assert(TAILQ_EMPTY(&p->alarmset.list));
518 kref_put(&p->strace->procs);
519 kref_put(&p->strace->users);
521 __vmm_struct_cleanup(p);
523 free_path(p, p->binary_path);
526 p->dot = p->slash = 0; /* catch bugs */
527 kref_put(&p->fs_env.root->d_kref);
528 kref_put(&p->fs_env.pwd->d_kref);
529 /* now we'll finally decref files for the file-backed vmrs */
530 unmap_and_destroy_vmrs(p);
531 frontend_proc_free(p); /* TODO: please remove me one day */
532 /* Remove us from the pid_hash and give our PID back (in that order). */
533 spin_lock(&pid_hash_lock);
534 hash_ret = hashtable_remove(pid_hash, (void*)(long)p->pid);
535 spin_unlock(&pid_hash_lock);
536 /* might not be in the hash/ready, if we failed during proc creation */
538 put_free_pid(p->pid);
540 printd("[kernel] pid %d not in the PID hash in %s\n", p->pid,
542 /* All memory below UMAPTOP should have been freed via the VMRs. The stuff
543 * above is the global info/page and procinfo/procdata. We free procinfo
544 * and procdata, but not the global memory - that's system wide. We could
545 * clear the PTEs of the upper stuff (UMAPTOP to UVPT), but we shouldn't
547 env_user_mem_walk(p, 0, UMAPTOP, __cb_assert_no_pg, 0);
548 kpages_free(p->procinfo, PROCINFO_NUM_PAGES * PGSIZE);
549 kpages_free(p->procdata, PROCDATA_NUM_PAGES * PGSIZE);
551 env_pagetable_free(p);
552 arch_pgdir_clear(&p->env_pgdir);
555 atomic_dec(&num_envs);
557 /* Dealloc the struct proc */
558 kmem_cache_free(proc_cache, p);
561 /* Whether or not actor can control target. TODO: do something reasonable here.
562 * Just checking for the parent is a bit limiting. Could walk the parent-child
563 * tree, check user ids, or some combination. Make sure actors can always
564 * control themselves. */
565 bool proc_controls(struct proc *actor, struct proc *target)
569 return ((actor == target) || (target->ppid == actor->pid));
573 /* Helper to incref by val. Using the helper to help debug/interpose on proc
574 * ref counting. Note that pid2proc doesn't use this interface. */
575 void proc_incref(struct proc *p, unsigned int val)
577 kref_get(&p->p_kref, val);
580 /* Helper to decref for debugging. Don't directly kref_put() for now. */
581 void proc_decref(struct proc *p)
583 kref_put(&p->p_kref);
586 /* Helper, makes p the 'current' process, dropping the old current/cr3. This no
587 * longer assumes the passed in reference already counted 'current'. It will
588 * incref internally when needed. */
589 static void __set_proc_current(struct proc *p)
591 /* We use the pcpui to access 'current' to cut down on the core_id() calls,
592 * though who know how expensive/painful they are. */
593 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
594 /* If the process wasn't here, then we need to load its address space. */
595 if (p != pcpui->cur_proc) {
598 /* This is "leaving the process context" of the previous proc. The
599 * previous lcr3 unloaded the previous proc's context. This should
600 * rarely happen, since we usually proactively leave process context,
601 * but this is the fallback. */
603 proc_decref(pcpui->cur_proc);
608 /* Flag says if vcore context is not ready, which is set in init_procdata. The
609 * process must turn off this flag on vcore0 at some point. It's off by default
610 * on all other vcores. */
611 static bool scp_is_vcctx_ready(struct preempt_data *vcpd)
613 return !(atomic_read(&vcpd->flags) & VC_SCP_NOVCCTX);
616 /* Dispatches a _S process to run on the current core. This should never be
617 * called to "restart" a core.
619 * This will always return, regardless of whether or not the calling core is
620 * being given to a process. (it used to pop the tf directly, before we had
623 * Since it always returns, it will never "eat" your reference (old
624 * documentation talks about this a bit). */
625 void proc_run_s(struct proc *p)
627 uint32_t coreid = core_id();
628 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
629 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
630 spin_lock(&p->proc_lock);
633 case (PROC_DYING_ABORT):
634 spin_unlock(&p->proc_lock);
635 printk("[kernel] _S %d not starting due to async death\n", p->pid);
637 case (PROC_RUNNABLE_S):
638 __proc_set_state(p, PROC_RUNNING_S);
639 /* SCPs don't have full vcores, but they act like they have vcore 0.
640 * We map the vcore, since we will want to know where this process
641 * is running, even if it is only in RUNNING_S. We can use the
642 * vcoremap, which makes death easy. num_vcores is still 0, and we
643 * do account the time online and offline. */
644 __seq_start_write(&p->procinfo->coremap_seqctr);
645 p->procinfo->num_vcores = 0;
646 __map_vcore(p, 0, coreid);
647 vcore_account_online(p, 0);
648 __seq_end_write(&p->procinfo->coremap_seqctr);
649 /* incref, since we're saving a reference in owning proc later */
651 /* lock was protecting the state and VC mapping, not pcpui stuff */
652 spin_unlock(&p->proc_lock);
653 /* redundant with proc_startcore, might be able to remove that one*/
654 __set_proc_current(p);
655 /* set us up as owning_proc. ksched bug if there is already one,
656 * for now. can simply clear_owning if we want to. */
657 assert(!pcpui->owning_proc);
658 pcpui->owning_proc = p;
659 pcpui->owning_vcoreid = 0;
660 restore_vc_fp_state(vcpd);
661 /* similar to the old __startcore, start them in vcore context if
662 * they have notifs and aren't already in vcore context. o/w, start
663 * them wherever they were before (could be either vc ctx or not) */
664 if (!vcpd->notif_disabled && vcpd->notif_pending
665 && scp_is_vcctx_ready(vcpd)) {
666 vcpd->notif_disabled = TRUE;
667 /* save the _S's ctx in the uthread slot, build and pop a new
668 * one in actual/cur_ctx. */
669 vcpd->uthread_ctx = p->scp_ctx;
670 pcpui->cur_ctx = &pcpui->actual_ctx;
671 memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
672 proc_init_ctx(pcpui->cur_ctx, 0, vcpd->vcore_entry,
673 vcpd->vcore_stack, vcpd->vcore_tls_desc);
675 /* If they have no transition stack, then they can't receive
676 * events. The most they are getting is a wakeup from the
677 * kernel. They won't even turn off notif_pending, so we'll do
679 if (!scp_is_vcctx_ready(vcpd))
680 vcpd->notif_pending = FALSE;
681 /* this is one of the few times cur_ctx != &actual_ctx */
682 pcpui->cur_ctx = &p->scp_ctx;
684 /* When the calling core idles, it'll call restartcore and run the
685 * _S process's context. */
688 spin_unlock(&p->proc_lock);
689 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
693 /* Helper: sends preempt messages to all vcores on the bulk preempt list, and
694 * moves them to the inactive list. */
695 static void __send_bulkp_events(struct proc *p)
697 struct vcore *vc_i, *vc_temp;
698 struct event_msg preempt_msg = {0};
699 /* Whenever we send msgs with the proc locked, we need at least 1 online */
700 assert(!TAILQ_EMPTY(&p->online_vcs));
701 /* Send preempt messages for any left on the BP list. No need to set any
702 * flags, it all was done on the real preempt. Now we're just telling the
703 * process about any that didn't get restarted and are still preempted. */
704 TAILQ_FOREACH_SAFE(vc_i, &p->bulk_preempted_vcs, list, vc_temp) {
705 /* Note that if there are no active vcores, send_k_e will post to our
706 * own vcore, the last of which will be put on the inactive list and be
707 * the first to be started. We could have issues with deadlocking,
708 * since send_k_e() could grab the proclock (if there are no active
710 preempt_msg.ev_type = EV_VCORE_PREEMPT;
711 preempt_msg.ev_arg2 = vcore2vcoreid(p, vc_i); /* arg2 is 32 bits */
712 send_kernel_event(p, &preempt_msg, 0);
713 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that.
714 * We need a loop for the messages, but not necessarily for the list
716 TAILQ_REMOVE(&p->bulk_preempted_vcs, vc_i, list);
717 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
721 /* Run an _M. Can be called safely on one that is already running. Hold the
722 * lock before calling. Other than state checks, this just starts up the _M's
723 * vcores, much like the second part of give_cores_running. More specifically,
724 * give_cores_runnable puts cores on the online list, which this then sends
725 * messages to. give_cores_running immediately puts them on the list and sends
726 * the message. the two-step style may go out of fashion soon.
728 * This expects that the "instructions" for which core(s) to run this on will be
729 * in the vcoremap, which needs to be set externally (give_cores()). */
730 void __proc_run_m(struct proc *p)
736 case (PROC_DYING_ABORT):
737 warn("ksched tried to run proc %d in state %s\n", p->pid,
738 procstate2str(p->state));
740 case (PROC_RUNNABLE_M):
741 /* vcoremap[i] holds the coreid of the physical core allocated to
742 * this process. It is set outside proc_run. */
743 if (p->procinfo->num_vcores) {
744 __send_bulkp_events(p);
745 __proc_set_state(p, PROC_RUNNING_M);
746 /* Up the refcnt, to avoid the n refcnt upping on the
747 * destination cores. Keep in sync with __startcore */
748 proc_incref(p, p->procinfo->num_vcores * 2);
749 /* Send kernel messages to all online vcores (which were added
750 * to the list and mapped in __proc_give_cores()), making them
752 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
753 send_kernel_message(vc_i->pcoreid, __startcore, (long)p,
754 (long)vcore2vcoreid(p, vc_i),
755 (long)vc_i->nr_preempts_sent,
759 warn("Tried to proc_run() an _M with no vcores!");
761 /* There a subtle race avoidance here (when we unlock after sending
762 * the message). __proc_startcore can handle a death message, but
763 * we can't have the startcore come after the death message.
764 * Otherwise, it would look like a new process. So we hold the lock
765 * til after we send our message, which prevents a possible death
767 * - Note there is no guarantee this core's interrupts were on, so
768 * it may not get the message for a while... */
770 case (PROC_RUNNING_M):
773 /* unlock just so the monitor can call something that might lock*/
774 spin_unlock(&p->proc_lock);
775 panic("Invalid process state %p in %s()!!", p->state, __FUNCTION__);
779 /* You must disable IRQs and PRKM before calling this.
781 * Actually runs the given context (trapframe) of process p on the core this
782 * code executes on. This is called directly by __startcore, which needs to
783 * bypass the routine_kmsg check. Interrupts should be off when you call this.
785 * A note on refcnting: this function will not return, and your proc reference
786 * will be ignored (not decreffed). It may be incref'd, if cur_proc was not
787 * set. Pass in an already-accounted-for ref, such as owning_proc. */
788 void __proc_startcore(struct proc *p, struct user_context *ctx)
790 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
791 assert(!irq_is_enabled());
792 /* Should never have ktask still set. If we do, future syscalls could try
793 * to block later and lose track of our address space. */
794 assert(!is_ktask(pcpui->cur_kthread));
795 __set_proc_current(p);
796 __set_cpu_state(pcpui, CPU_STATE_USER);
800 /* Restarts/runs the current_ctx, which must be for the current process, on the
801 * core this code executes on. Calls an internal function to do the work.
803 * In case there are pending routine messages, like __death, __preempt, or
804 * __notify, we need to run them. Alternatively, if there are any, we could
805 * self_ipi, and run the messages immediately after popping back to userspace,
806 * but that would have crappy overhead. */
807 void proc_restartcore(void)
809 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
811 assert(!pcpui->cur_kthread->sysc);
812 process_routine_kmsg();
813 /* If there is no owning process, just idle, since we don't know what to do.
814 * This could be because the process had been restarted a long time ago and
815 * has since left the core, or due to a KMSG like __preempt or __death. */
816 if (!pcpui->owning_proc) {
820 assert(pcpui->cur_ctx);
821 __proc_startcore(pcpui->owning_proc, pcpui->cur_ctx);
824 /* Destroys the process. It will destroy the process and return any cores
825 * to the ksched via the __sched_proc_destroy() CB.
827 * Here's the way process death works:
828 * 0. grab the lock (protects state transition and core map)
829 * 1. set state to dying. that keeps the kernel from doing anything for the
830 * process (like proc_running it).
831 * 2. figure out where the process is running (cross-core/async or RUNNING_M)
832 * 3. IPI to clean up those cores (decref, etc).
834 * 5. Clean up your core, if applicable
835 * (Last core/kernel thread to decref cleans up and deallocates resources.)
837 * Note that some cores can be processing async calls, but will eventually
838 * decref. Should think about this more, like some sort of callback/revocation.
840 * This function will now always return (it used to not return if the calling
841 * core was dying). However, when it returns, a kernel message will eventually
842 * come in, making you abandon_core, as if you weren't running. It may be that
843 * the only reference to p is the one you passed in, and when you decref, it'll
844 * get __proc_free()d. */
845 void proc_destroy(struct proc *p)
847 uint32_t nr_cores_revoked = 0;
848 struct kthread *sleeper;
849 struct proc *child_i, *temp;
851 spin_lock(&p->proc_lock);
852 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
853 uint32_t pc_arr[p->procinfo->num_vcores];
855 case PROC_DYING: /* someone else killed this already. */
856 case (PROC_DYING_ABORT):
857 spin_unlock(&p->proc_lock);
860 case PROC_RUNNABLE_S:
863 case PROC_RUNNABLE_M:
865 /* Need to reclaim any cores this proc might have, even if it's not
866 * running yet. Those running will receive a __death */
867 nr_cores_revoked = __proc_take_allcores(p, pc_arr, FALSE);
871 // here's how to do it manually
874 proc_decref(p); /* this decref is for the cr3 */
878 send_kernel_message(get_pcoreid(p, 0), __death, 0, 0, 0,
880 __seq_start_write(&p->procinfo->coremap_seqctr);
882 __seq_end_write(&p->procinfo->coremap_seqctr);
883 /* If we ever have RUNNING_S run on non-mgmt cores, we'll need to
884 * tell the ksched about this now-idle core (after unlocking) */
887 warn("Weird state(%s) in %s()", procstate2str(p->state),
889 spin_unlock(&p->proc_lock);
892 /* At this point, a death IPI should be on its way, either from the
893 * RUNNING_S one, or from proc_take_cores with a __death. in general,
894 * interrupts should be on when you call proc_destroy locally, but currently
895 * aren't for all things (like traphandlers). */
896 __proc_set_state(p, PROC_DYING);
897 /* Disown any children. If we want to have init inherit or something,
898 * change __disown to set the ppid accordingly and concat this with init's
899 * list (instead of emptying it like disown does). Careful of lock ordering
900 * between procs (need to lock to protect lists) */
901 TAILQ_FOREACH_SAFE(child_i, &p->children, sibling_link, temp) {
902 int ret = __proc_disown_child(p, child_i);
903 /* should never fail, lock should cover the race. invariant: any child
904 * on the list should have us as a parent */
907 spin_unlock(&p->proc_lock);
908 /* Wake any of our kthreads waiting on children, so they can abort */
909 cv_broadcast(&p->child_wait);
910 /* we need to close files here, and not in free, since we could have a
911 * refcnt indirectly related to one of our files. specifically, if we have
912 * a parent sleeping on our pipe, that parent won't wake up to decref until
913 * the pipe closes. And if the parent doesnt decref, we don't free.
914 * Even if we send a SIGCHLD to the parent, that would require that the
915 * parent to never ignores that signal (or we risk never reaping).
917 * Also note that any mmap'd files will still be mmapped. You can close the
918 * file after mmapping, with no effect. */
919 close_fdt(&p->open_files, FALSE);
920 /* Abort any abortable syscalls. This won't catch every sleeper, but future
921 * abortable sleepers are already prevented via the DYING_ABORT state.
922 * (signalled DYING_ABORT, no new sleepers will block, and now we wake all
924 __proc_set_state(p, PROC_DYING_ABORT);
926 /* Tell the ksched about our death, and which cores we freed up */
927 __sched_proc_destroy(p, pc_arr, nr_cores_revoked);
928 /* Tell our parent about our state change (to DYING) */
929 proc_signal_parent(p);
932 /* Can use this to signal anything that might cause a parent to wait on the
933 * child, such as termination, or signals. Change the state or whatever before
935 void proc_signal_parent(struct proc *child)
937 struct kthread *sleeper;
938 struct proc *parent = pid2proc(child->ppid);
941 send_posix_signal(parent, SIGCHLD);
942 /* there could be multiple kthreads sleeping for various reasons. even an
943 * SCP could have multiple async syscalls. */
944 cv_broadcast(&parent->child_wait);
945 /* if the parent was waiting, there's a __launch kthread KMSG out there */
949 /* Called when a parent is done with its child, and no longer wants to track the
950 * child, nor to allow the child to track it. Call with a lock (cv) held.
951 * Returns 0 if we disowned, -1 on failure. */
952 int __proc_disown_child(struct proc *parent, struct proc *child)
954 /* Bail out if the child has already been reaped */
957 assert(child->ppid == parent->pid);
958 /* lock protects from concurrent inserts / removals from the list */
959 TAILQ_REMOVE(&parent->children, child, sibling_link);
960 /* After this, the child won't be able to get more refs to us, but it may
961 * still have some references in running code. */
963 proc_decref(child); /* ref that was keeping the child alive on the list */
967 /* Turns *p into an MCP. Needs to be called from a local syscall of a RUNNING_S
968 * process. Returns 0 if it succeeded, an error code otherwise. */
969 int proc_change_to_m(struct proc *p)
972 spin_lock(&p->proc_lock);
973 /* in case userspace erroneously tries to change more than once */
974 if (__proc_is_mcp(p))
977 case (PROC_RUNNING_S):
978 /* issue with if we're async or not (need to preempt it)
979 * either of these should trip it. TODO: (ACR) async core req */
980 if ((current != p) || (get_pcoreid(p, 0) != core_id()))
981 panic("We don't handle async RUNNING_S core requests yet.");
982 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
984 /* Copy uthread0's context to VC 0's uthread slot */
985 copy_current_ctx_to(&vcpd->uthread_ctx);
986 clear_owning_proc(core_id()); /* so we don't restart */
987 save_vc_fp_state(vcpd);
988 /* Userspace needs to not fuck with notif_disabled before
989 * transitioning to _M. */
990 if (vcpd->notif_disabled) {
991 printk("[kernel] user bug: notifs disabled for vcore 0\n");
992 vcpd->notif_disabled = FALSE;
994 /* in the async case, we'll need to remotely stop and bundle
995 * vcore0's TF. this is already done for the sync case (local
997 /* this process no longer runs on its old location (which is
998 * this core, for now, since we don't handle async calls) */
999 __seq_start_write(&p->procinfo->coremap_seqctr);
1000 // TODO: (ACR) will need to unmap remotely (receive-side)
1001 __unmap_vcore(p, 0);
1002 vcore_account_offline(p, 0);
1003 __seq_end_write(&p->procinfo->coremap_seqctr);
1004 /* change to runnable_m (it's TF is already saved) */
1005 __proc_set_state(p, PROC_RUNNABLE_M);
1006 p->procinfo->is_mcp = TRUE;
1007 spin_unlock(&p->proc_lock);
1008 /* Tell the ksched that we're a real MCP now! */
1009 __sched_proc_change_to_m(p);
1011 case (PROC_RUNNABLE_S):
1012 /* Issues: being on the runnable_list, proc_set_state not liking
1013 * it, and not clearly thinking through how this would happen.
1014 * Perhaps an async call that gets serviced after you're
1016 warn("Not supporting RUNNABLE_S -> RUNNABLE_M yet.\n");
1019 case (PROC_DYING_ABORT):
1020 warn("Dying, core request coming from %d\n", core_id());
1026 spin_unlock(&p->proc_lock);
1030 /* Old code to turn a RUNNING_M to a RUNNING_S, with the calling context
1031 * becoming the new 'thread0'. Don't use this. Caller needs to send in a
1032 * pc_arr big enough for all vcores. Will return the number of cores given up
1034 uint32_t __proc_change_to_s(struct proc *p, uint32_t *pc_arr)
1036 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1037 uint32_t num_revoked;
1038 /* Not handling vcore accounting. Do so if we ever use this */
1039 printk("[kernel] trying to transition _M -> _S (deprecated)!\n");
1040 assert(p->state == PROC_RUNNING_M); // TODO: (ACR) async core req
1041 /* save the context, to be restarted in _S mode */
1042 assert(current_ctx);
1043 copy_current_ctx_to(&p->scp_ctx);
1044 clear_owning_proc(core_id()); /* so we don't restart */
1045 save_vc_fp_state(vcpd);
1046 /* sending death, since it's not our job to save contexts or anything in
1048 num_revoked = __proc_take_allcores(p, pc_arr, FALSE);
1049 __proc_set_state(p, PROC_RUNNABLE_S);
1053 /* Helper function. Is the given pcore a mapped vcore? No locking involved, be
1055 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid)
1057 return p->procinfo->pcoremap[pcoreid].valid;
1060 /* Helper function. Find the vcoreid for a given physical core id for proc p.
1061 * No locking involved, be careful. Panics on failure. */
1062 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid)
1064 assert(is_mapped_vcore(p, pcoreid));
1065 return p->procinfo->pcoremap[pcoreid].vcoreid;
1068 /* Helper function. Try to find the pcoreid for a given virtual core id for
1069 * proc p. No locking involved, be careful. Use this when you can tolerate a
1070 * stale or otherwise 'wrong' answer. */
1071 static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid)
1073 return p->procinfo->vcoremap[vcoreid].pcoreid;
1076 /* Helper function. Find the pcoreid for a given virtual core id for proc p.
1077 * No locking involved, be careful. Panics on failure. */
1078 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid)
1080 assert(vcore_is_mapped(p, vcoreid));
1081 return try_get_pcoreid(p, vcoreid);
1084 /* Saves the FP state of the calling core into VCPD. Pairs with
1085 * restore_vc_fp_state(). On x86, the best case overhead of the flags:
1089 * Flagged FXSAVE: 50 ns
1090 * Flagged FXRSTR: 66 ns
1091 * Excess flagged FXRSTR: 42 ns
1092 * If we don't do it, we'll need to initialize every VCPD at process creation
1093 * time with a good FPU state (x86 control words are initialized as 0s, like the
1095 static void save_vc_fp_state(struct preempt_data *vcpd)
1097 save_fp_state(&vcpd->preempt_anc);
1098 vcpd->rflags |= VC_FPU_SAVED;
1101 /* Conditionally restores the FP state from VCPD. If the state was not valid,
1102 * we don't bother restoring and just initialize the FPU. */
1103 static void restore_vc_fp_state(struct preempt_data *vcpd)
1105 if (vcpd->rflags & VC_FPU_SAVED) {
1106 restore_fp_state(&vcpd->preempt_anc);
1107 vcpd->rflags &= ~VC_FPU_SAVED;
1113 /* Helper for SCPs, saves the core's FPU state into the VCPD vc0 slot */
1114 void __proc_save_fpu_s(struct proc *p)
1116 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1117 save_vc_fp_state(vcpd);
1120 /* Helper: saves the SCP's GP tf state and unmaps vcore 0. This does *not* save
1123 * In the future, we'll probably use vc0's space for scp_ctx and the silly
1124 * state. If we ever do that, we'll need to stop using scp_ctx (soon to be in
1125 * VCPD) as a location for pcpui->cur_ctx to point (dangerous) */
1126 void __proc_save_context_s(struct proc *p)
1128 copy_current_ctx_to(&p->scp_ctx);
1129 __seq_start_write(&p->procinfo->coremap_seqctr);
1130 __unmap_vcore(p, 0);
1131 __seq_end_write(&p->procinfo->coremap_seqctr);
1132 vcore_account_offline(p, 0);
1135 /* Yields the calling core. Must be called locally (not async) for now.
1136 * - If RUNNING_S, you just give up your time slice and will eventually return,
1137 * possibly after WAITING on an event.
1138 * - If RUNNING_M, you give up the current vcore (which never returns), and
1139 * adjust the amount of cores wanted/granted.
1140 * - If you have only one vcore, you switch to WAITING. There's no 'classic
1141 * yield' for MCPs (at least not now). When you run again, you'll have one
1142 * guaranteed core, starting from the entry point.
1144 * If the call is being nice, it means different things for SCPs and MCPs. For
1145 * MCPs, it means that it is in response to a preemption (which needs to be
1146 * checked). If there is no preemption pending, just return. For SCPs, it
1147 * means the proc wants to give up the core, but still has work to do. If not,
1148 * the proc is trying to wait on an event. It's not being nice to others, it
1149 * just has no work to do.
1151 * This usually does not return (smp_idle()), so it will eat your reference.
1152 * Also note that it needs a non-current/edible reference, since it will abandon
1153 * and continue to use the *p (current == 0, no cr3, etc).
1155 * We disable interrupts for most of it too, since we need to protect
1156 * current_ctx and not race with __notify (which doesn't play well with
1157 * concurrent yielders). */
1158 void proc_yield(struct proc *p, bool being_nice)
1160 uint32_t vcoreid, pcoreid = core_id();
1161 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1163 struct preempt_data *vcpd;
1164 /* Need to lock to prevent concurrent vcore changes (online, inactive, the
1165 * mapping, etc). This plus checking the nr_preempts is enough to tell if
1166 * our vcoreid and cur_ctx ought to be here still or if we should abort */
1167 spin_lock(&p->proc_lock); /* horrible scalability. =( */
1169 case (PROC_RUNNING_S):
1171 /* waiting for an event to unblock us */
1172 vcpd = &p->procdata->vcore_preempt_data[0];
1173 /* syncing with event's SCP code. we set waiting, then check
1174 * pending. they set pending, then check waiting. it's not
1175 * possible for us to miss the notif *and* for them to miss
1176 * WAITING. one (or both) of us will see and make sure the proc
1178 __proc_set_state(p, PROC_WAITING);
1179 wrmb(); /* don't let the state write pass the notif read */
1180 if (vcpd->notif_pending) {
1181 __proc_set_state(p, PROC_RUNNING_S);
1182 /* they can't handle events, just need to prevent a yield.
1183 * (note the notif_pendings are collapsed). */
1184 if (!scp_is_vcctx_ready(vcpd))
1185 vcpd->notif_pending = FALSE;
1188 /* if we're here, we want to sleep. a concurrent event that
1189 * hasn't already written notif_pending will have seen WAITING,
1190 * and will be spinning while we do this. */
1191 __proc_save_context_s(p);
1192 spin_unlock(&p->proc_lock);
1194 /* yielding to allow other processes to run. we're briefly
1195 * WAITING, til we are woken up */
1196 __proc_set_state(p, PROC_WAITING);
1197 __proc_save_context_s(p);
1198 spin_unlock(&p->proc_lock);
1199 /* immediately wake up the proc (makes it runnable) */
1202 goto out_yield_core;
1203 case (PROC_RUNNING_M):
1204 break; /* will handle this stuff below */
1205 case (PROC_DYING): /* incoming __death */
1206 case (PROC_DYING_ABORT):
1207 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1210 panic("Weird state(%s) in %s()", procstate2str(p->state),
1213 /* This is which vcore this pcore thinks it is, regardless of any unmappings
1214 * that may have happened remotely (with __PRs waiting to run) */
1215 vcoreid = pcpui->owning_vcoreid;
1216 vc = vcoreid2vcore(p, vcoreid);
1217 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1218 /* This is how we detect whether or not a __PR happened. */
1219 if (vc->nr_preempts_sent != vc->nr_preempts_done)
1221 /* Sanity checks. If we were preempted or are dying, we should have noticed
1223 assert(is_mapped_vcore(p, pcoreid));
1224 assert(vcoreid == get_vcoreid(p, pcoreid));
1225 /* no reason to be nice, return */
1226 if (being_nice && !vc->preempt_pending)
1228 /* At this point, AFAIK there should be no preempt/death messages on the
1229 * way, and we're on the online list. So we'll go ahead and do the yielding
1231 /* If there's a preempt pending, we don't need to preempt later since we are
1232 * yielding (nice or otherwise). If not, this is just a regular yield. */
1233 if (vc->preempt_pending) {
1234 vc->preempt_pending = 0;
1236 /* Optional: on a normal yield, check to see if we are putting them
1237 * below amt_wanted (help with user races) and bail. */
1238 if (p->procdata->res_req[RES_CORES].amt_wanted >=
1239 p->procinfo->num_vcores)
1242 /* Don't let them yield if they are missing a notification. Userspace must
1243 * not leave vcore context without dealing with notif_pending.
1244 * pop_user_ctx() handles leaving via uthread context. This handles leaving
1247 * This early check is an optimization. The real check is below when it
1248 * works with the online_vcs list (syncing with event.c and INDIR/IPI
1250 if (vcpd->notif_pending)
1252 /* Now we'll actually try to yield */
1253 printd("[K] Process %d (%p) is yielding on vcore %d\n", p->pid, p,
1254 get_vcoreid(p, pcoreid));
1255 /* Remove from the online list, add to the yielded list, and unmap
1256 * the vcore, which gives up the core. */
1257 TAILQ_REMOVE(&p->online_vcs, vc, list);
1258 /* Now that we're off the online list, check to see if an alert made
1259 * it through (event.c sets this) */
1260 wrmb(); /* prev write must hit before reading notif_pending */
1261 /* Note we need interrupts disabled, since a __notify can come in
1262 * and set pending to FALSE */
1263 if (vcpd->notif_pending) {
1264 /* We lost, put it back on the list and abort the yield. If we ever
1265 * build an myield, we'll need a way to deal with this for all vcores */
1266 TAILQ_INSERT_TAIL(&p->online_vcs, vc, list); /* could go HEAD */
1269 /* Not really a kmsg, but it acts like one w.r.t. proc mgmt */
1270 pcpui_trace_kmsg(pcpui, (uintptr_t)proc_yield);
1271 /* We won the race with event sending, we can safely yield */
1272 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1273 /* Note this protects stuff userspace should look at, which doesn't
1274 * include the TAILQs. */
1275 __seq_start_write(&p->procinfo->coremap_seqctr);
1276 /* Next time the vcore starts, it starts fresh */
1277 vcpd->notif_disabled = FALSE;
1278 __unmap_vcore(p, vcoreid);
1279 p->procinfo->num_vcores--;
1280 p->procinfo->res_grant[RES_CORES] = p->procinfo->num_vcores;
1281 __seq_end_write(&p->procinfo->coremap_seqctr);
1282 vcore_account_offline(p, vcoreid);
1283 /* No more vcores? Then we wait on an event */
1284 if (p->procinfo->num_vcores == 0) {
1285 /* consider a ksched op to tell it about us WAITING */
1286 __proc_set_state(p, PROC_WAITING);
1288 spin_unlock(&p->proc_lock);
1289 /* We discard the current context, but we still need to restore the core */
1290 arch_finalize_ctx(pcpui->cur_ctx);
1291 /* Hand the now-idle core to the ksched */
1292 __sched_put_idle_core(p, pcoreid);
1293 goto out_yield_core;
1295 /* for some reason we just want to return, either to take a KMSG that cleans
1296 * us up, or because we shouldn't yield (ex: notif_pending). */
1297 spin_unlock(&p->proc_lock);
1299 out_yield_core: /* successfully yielded the core */
1300 proc_decref(p); /* need to eat the ref passed in */
1301 /* Clean up the core and idle. */
1302 clear_owning_proc(pcoreid); /* so we don't restart */
1307 /* Sends a notification (aka active notification, aka IPI) to p's vcore. We
1308 * only send a notification if one they are enabled. There's a bunch of weird
1309 * cases with this, and how pending / enabled are signals between the user and
1310 * kernel - check the documentation. Note that pending is more about messages.
1311 * The process needs to be in vcore_context, and the reason is usually a
1312 * message. We set pending here in case we were called to prod them into vcore
1313 * context (like via a sys_self_notify). Also note that this works for _S
1314 * procs, if you send to vcore 0 (and the proc is running). */
1315 void proc_notify(struct proc *p, uint32_t vcoreid)
1317 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1319 /* If you're thinking about checking notif_pending and then returning if it
1320 * is already set, note that some callers (e.g. the event system) set
1321 * notif_pending when they deliver a message, regardless of whether there is
1322 * an IPI or not. Those callers assume that we don't care about
1323 * notif_pending, only notif_disabled. So don't change this without
1324 * changing them (probably can't without a lot of thought - that
1325 * notif_pending is about missing messages. It might be possible to say "no
1326 * IPI, but don't let me miss messages that were delivered." */
1327 vcpd->notif_pending = TRUE;
1328 wrmb(); /* must write notif_pending before reading notif_disabled */
1329 if (!vcpd->notif_disabled) {
1330 /* GIANT WARNING: we aren't using the proc-lock to protect the
1331 * vcoremap. We want to be able to use this from interrupt context,
1332 * and don't want the proc_lock to be an irqsave. Spurious
1333 * __notify() kmsgs are okay (it checks to see if the right receiver
1335 if (vcore_is_mapped(p, vcoreid)) {
1336 printd("[kernel] sending notif to vcore %d\n", vcoreid);
1337 /* This use of try_get_pcoreid is racy, might be unmapped */
1338 send_kernel_message(try_get_pcoreid(p, vcoreid), __notify, (long)p,
1339 0, 0, KMSG_ROUTINE);
1344 /* Makes sure p is runnable. Callers may spam this, so it needs to handle
1345 * repeated calls for the same event. Callers include event delivery, SCP
1346 * yield, and new SCPs. Will trigger __sched_.cp_wakeup() CBs. Will only
1347 * trigger the CB once, regardless of how many times we are called, *until* the
1348 * proc becomes WAITING again, presumably because of something the ksched did.*/
1349 void proc_wakeup(struct proc *p)
1351 spin_lock(&p->proc_lock);
1352 if (__proc_is_mcp(p)) {
1353 /* we only wake up WAITING mcps */
1354 if (p->state != PROC_WAITING) {
1355 spin_unlock(&p->proc_lock);
1358 __proc_set_state(p, PROC_RUNNABLE_M);
1359 spin_unlock(&p->proc_lock);
1360 __sched_mcp_wakeup(p);
1363 /* SCPs can wake up for a variety of reasons. the only times we need
1364 * to do something is if it was waiting or just created. other cases
1365 * are either benign (just go out), or potential bugs (_Ms) */
1367 case (PROC_CREATED):
1368 case (PROC_WAITING):
1369 __proc_set_state(p, PROC_RUNNABLE_S);
1371 case (PROC_RUNNABLE_S):
1372 case (PROC_RUNNING_S):
1374 case (PROC_DYING_ABORT):
1375 spin_unlock(&p->proc_lock);
1377 case (PROC_RUNNABLE_M):
1378 case (PROC_RUNNING_M):
1379 warn("Weird state(%s) in %s()", procstate2str(p->state),
1381 spin_unlock(&p->proc_lock);
1384 printd("[kernel] FYI, waking up an _S proc\n"); /* thanks, past brho! */
1385 spin_unlock(&p->proc_lock);
1386 __sched_scp_wakeup(p);
1390 /* Is the process in multi_mode / is an MCP or not? */
1391 bool __proc_is_mcp(struct proc *p)
1393 /* in lieu of using the amount of cores requested, or having a bunch of
1394 * states (like PROC_WAITING_M and _S), I'll just track it with a bool. */
1395 return p->procinfo->is_mcp;
1398 bool proc_is_vcctx_ready(struct proc *p)
1400 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1401 return scp_is_vcctx_ready(vcpd);
1404 /************************ Preemption Functions ******************************
1405 * Don't rely on these much - I'll be sure to change them up a bit.
1407 * Careful about what takes a vcoreid and what takes a pcoreid. Also, there may
1408 * be weird glitches with setting the state to RUNNABLE_M. It is somewhat in
1409 * flux. The num_vcores is changed after take_cores, but some of the messages
1410 * (or local traps) may not yet be ready to handle seeing their future state.
1411 * But they should be, so fix those when they pop up.
1413 * Another thing to do would be to make the _core functions take a pcorelist,
1414 * and not just one pcoreid. */
1416 /* Sets a preempt_pending warning for p's vcore, to go off 'when'. If you care
1417 * about locking, do it before calling. Takes a vcoreid! */
1418 void __proc_preempt_warn(struct proc *p, uint32_t vcoreid, uint64_t when)
1420 struct event_msg local_msg = {0};
1421 /* danger with doing this unlocked: preempt_pending is set, but never 0'd,
1422 * since it is unmapped and not dealt with (TODO)*/
1423 p->procinfo->vcoremap[vcoreid].preempt_pending = when;
1425 /* Send the event (which internally checks to see how they want it) */
1426 local_msg.ev_type = EV_PREEMPT_PENDING;
1427 local_msg.ev_arg1 = vcoreid;
1428 /* Whenever we send msgs with the proc locked, we need at least 1 online.
1429 * Caller needs to make sure the core was online/mapped. */
1430 assert(!TAILQ_EMPTY(&p->online_vcs));
1431 send_kernel_event(p, &local_msg, vcoreid);
1433 /* TODO: consider putting in some lookup place for the alarm to find it.
1434 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1437 /* Warns all active vcores of an impending preemption. Hold the lock if you
1438 * care about the mapping (and you should). */
1439 void __proc_preempt_warnall(struct proc *p, uint64_t when)
1442 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1443 __proc_preempt_warn(p, vcore2vcoreid(p, vc_i), when);
1444 /* TODO: consider putting in some lookup place for the alarm to find it.
1445 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1448 // TODO: function to set an alarm, if none is outstanding
1450 /* Raw function to preempt a single core. If you care about locking, do it
1451 * before calling. */
1452 void __proc_preempt_core(struct proc *p, uint32_t pcoreid)
1454 uint32_t vcoreid = get_vcoreid(p, pcoreid);
1455 struct event_msg preempt_msg = {0};
1456 /* works with nr_preempts_done to signal completion of a preemption */
1457 p->procinfo->vcoremap[vcoreid].nr_preempts_sent++;
1458 // expects a pcorelist. assumes pcore is mapped and running_m
1459 __proc_take_corelist(p, &pcoreid, 1, TRUE);
1460 /* Only send the message if we have an online core. o/w, it would fuck
1461 * us up (deadlock), and hey don't need a message. the core we just took
1462 * will be the first one to be restarted. It will look like a notif. in
1463 * the future, we could send the event if we want, but the caller needs to
1464 * do that (after unlocking). */
1465 if (!TAILQ_EMPTY(&p->online_vcs)) {
1466 preempt_msg.ev_type = EV_VCORE_PREEMPT;
1467 preempt_msg.ev_arg2 = vcoreid;
1468 send_kernel_event(p, &preempt_msg, 0);
1472 /* Raw function to preempt every vcore. If you care about locking, do it before
1474 uint32_t __proc_preempt_all(struct proc *p, uint32_t *pc_arr)
1477 /* TODO:(BULK) PREEMPT - don't bother with this, set a proc wide flag, or
1478 * just make us RUNNABLE_M. Note this is also used by __map_vcore. */
1479 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1480 vc_i->nr_preempts_sent++;
1481 return __proc_take_allcores(p, pc_arr, TRUE);
1484 /* Warns and preempts a vcore from p. No delaying / alarming, or anything. The
1485 * warning will be for u usec from now. Returns TRUE if the core belonged to
1486 * the proc (and thus preempted), False if the proc no longer has the core. */
1487 bool proc_preempt_core(struct proc *p, uint32_t pcoreid, uint64_t usec)
1489 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1490 bool retval = FALSE;
1491 if (p->state != PROC_RUNNING_M) {
1492 /* more of an FYI for brho. should be harmless to just return. */
1493 warn("Tried to preempt from a non RUNNING_M proc!");
1496 spin_lock(&p->proc_lock);
1497 if (is_mapped_vcore(p, pcoreid)) {
1498 __proc_preempt_warn(p, get_vcoreid(p, pcoreid), warn_time);
1499 __proc_preempt_core(p, pcoreid);
1500 /* we might have taken the last core */
1501 if (!p->procinfo->num_vcores)
1502 __proc_set_state(p, PROC_RUNNABLE_M);
1505 spin_unlock(&p->proc_lock);
1509 /* Warns and preempts all from p. No delaying / alarming, or anything. The
1510 * warning will be for u usec from now. */
1511 void proc_preempt_all(struct proc *p, uint64_t usec)
1513 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1514 uint32_t num_revoked = 0;
1515 spin_lock(&p->proc_lock);
1516 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
1517 uint32_t pc_arr[p->procinfo->num_vcores];
1518 /* DYING could be okay */
1519 if (p->state != PROC_RUNNING_M) {
1520 warn("Tried to preempt from a non RUNNING_M proc!");
1521 spin_unlock(&p->proc_lock);
1524 __proc_preempt_warnall(p, warn_time);
1525 num_revoked = __proc_preempt_all(p, pc_arr);
1526 assert(!p->procinfo->num_vcores);
1527 __proc_set_state(p, PROC_RUNNABLE_M);
1528 spin_unlock(&p->proc_lock);
1529 /* TODO: when we revise this func, look at __put_idle */
1530 /* Return the cores to the ksched */
1532 __sched_put_idle_cores(p, pc_arr, num_revoked);
1535 /* Give the specific pcore to proc p. Lots of assumptions, so don't really use
1536 * this. The proc needs to be _M and prepared for it. the pcore needs to be
1538 void proc_give(struct proc *p, uint32_t pcoreid)
1540 warn("Your idlecoremap is now screwed up"); /* TODO (IDLE) */
1541 spin_lock(&p->proc_lock);
1542 // expects a pcorelist, we give it a list of one
1543 __proc_give_cores(p, &pcoreid, 1);
1544 spin_unlock(&p->proc_lock);
1547 /* Global version of the helper, for sys_get_vcoreid (might phase that syscall
1549 uint32_t proc_get_vcoreid(struct proc *p)
1551 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1552 if (pcpui->owning_proc == p) {
1553 return pcpui->owning_vcoreid;
1555 warn("Asked for vcoreid for %p, but %p is pwns", p, pcpui->owning_proc);
1556 return (uint32_t)-1;
1560 /* TODO: make all of these static inlines when we gut the env crap */
1561 bool vcore_is_mapped(struct proc *p, uint32_t vcoreid)
1563 return p->procinfo->vcoremap[vcoreid].valid;
1566 /* Can do this, or just create a new field and save it in the vcoremap */
1567 uint32_t vcore2vcoreid(struct proc *p, struct vcore *vc)
1569 return (vc - p->procinfo->vcoremap);
1572 struct vcore *vcoreid2vcore(struct proc *p, uint32_t vcoreid)
1574 return &p->procinfo->vcoremap[vcoreid];
1577 /********** Core granting (bulk and single) ***********/
1579 /* Helper: gives pcore to the process, mapping it to the next available vcore
1580 * from list vc_list. Returns TRUE if we succeeded (non-empty). If you pass in
1581 * **vc, we'll tell you which vcore it was. */
1582 static bool __proc_give_a_pcore(struct proc *p, uint32_t pcore,
1583 struct vcore_tailq *vc_list, struct vcore **vc)
1585 struct vcore *new_vc;
1586 new_vc = TAILQ_FIRST(vc_list);
1589 printd("setting vcore %d to pcore %d\n", vcore2vcoreid(p, new_vc),
1591 TAILQ_REMOVE(vc_list, new_vc, list);
1592 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1593 __map_vcore(p, vcore2vcoreid(p, new_vc), pcore);
1599 static void __proc_give_cores_runnable(struct proc *p, uint32_t *pc_arr,
1602 assert(p->state == PROC_RUNNABLE_M);
1603 assert(num); /* catch bugs */
1604 /* add new items to the vcoremap */
1605 __seq_start_write(&p->procinfo->coremap_seqctr);/* unncessary if offline */
1606 p->procinfo->num_vcores += num;
1607 for (int i = 0; i < num; i++) {
1608 /* Try from the bulk list first */
1609 if (__proc_give_a_pcore(p, pc_arr[i], &p->bulk_preempted_vcs, 0))
1611 /* o/w, try from the inactive list. at one point, i thought there might
1612 * be a legit way in which the inactive list could be empty, but that i
1613 * wanted to catch it via an assert. */
1614 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, 0));
1616 __seq_end_write(&p->procinfo->coremap_seqctr);
1619 static void __proc_give_cores_running(struct proc *p, uint32_t *pc_arr,
1623 /* Up the refcnt, since num cores are going to start using this
1624 * process and have it loaded in their owning_proc and 'current'. */
1625 proc_incref(p, num * 2); /* keep in sync with __startcore */
1626 __seq_start_write(&p->procinfo->coremap_seqctr);
1627 p->procinfo->num_vcores += num;
1628 assert(TAILQ_EMPTY(&p->bulk_preempted_vcs));
1629 for (int i = 0; i < num; i++) {
1630 assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, &vc_i));
1631 send_kernel_message(pc_arr[i], __startcore, (long)p,
1632 (long)vcore2vcoreid(p, vc_i),
1633 (long)vc_i->nr_preempts_sent, KMSG_ROUTINE);
1635 __seq_end_write(&p->procinfo->coremap_seqctr);
1638 /* Gives process p the additional num cores listed in pcorelist. If the proc is
1639 * not RUNNABLE_M or RUNNING_M, this will fail and allocate none of the core
1640 * (and return -1). If you're RUNNING_M, this will startup your new cores at
1641 * the entry point with their virtual IDs (or restore a preemption). If you're
1642 * RUNNABLE_M, you should call __proc_run_m after this so that the process can
1643 * start to use its cores. In either case, this returns 0.
1645 * If you're *_S, make sure your core0's TF is set (which is done when coming in
1646 * via arch/trap.c and we are RUNNING_S), change your state, then call this.
1647 * Then call __proc_run_m().
1649 * The reason I didn't bring the _S cases from core_request over here is so we
1650 * can keep this family of calls dealing with only *_Ms, to avoiding caring if
1651 * this is called from another core, and to avoid the _S -> _M transition.
1653 * WARNING: You must hold the proc_lock before calling this! */
1654 int __proc_give_cores(struct proc *p, uint32_t *pc_arr, uint32_t num)
1656 /* should never happen: */
1657 assert(num + p->procinfo->num_vcores <= MAX_NUM_CORES);
1659 case (PROC_RUNNABLE_S):
1660 case (PROC_RUNNING_S):
1661 warn("Don't give cores to a process in a *_S state!\n");
1664 case (PROC_DYING_ABORT):
1665 case (PROC_WAITING):
1666 /* can't accept, just fail */
1668 case (PROC_RUNNABLE_M):
1669 __proc_give_cores_runnable(p, pc_arr, num);
1671 case (PROC_RUNNING_M):
1672 __proc_give_cores_running(p, pc_arr, num);
1675 panic("Weird state(%s) in %s()", procstate2str(p->state),
1678 /* TODO: considering moving to the ksched (hard, due to yield) */
1679 p->procinfo->res_grant[RES_CORES] += num;
1683 /********** Core revocation (bulk and single) ***********/
1685 /* Revokes a single vcore from a process (unmaps or sends a KMSG to unmap). */
1686 static void __proc_revoke_core(struct proc *p, uint32_t vcoreid, bool preempt)
1688 uint32_t pcoreid = get_pcoreid(p, vcoreid);
1689 struct preempt_data *vcpd;
1691 /* Lock the vcore's state (necessary for preemption recovery) */
1692 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1693 atomic_or(&vcpd->flags, VC_K_LOCK);
1694 send_kernel_message(pcoreid, __preempt, (long)p, 0, 0, KMSG_ROUTINE);
1696 send_kernel_message(pcoreid, __death, 0, 0, 0, KMSG_ROUTINE);
1700 /* Revokes all cores from the process (unmaps or sends a KMSGS). */
1701 static void __proc_revoke_allcores(struct proc *p, bool preempt)
1704 /* TODO: if we ever get broadcast messaging, use it here (still need to lock
1705 * the vcores' states for preemption) */
1706 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1707 __proc_revoke_core(p, vcore2vcoreid(p, vc_i), preempt);
1710 /* Might be faster to scan the vcoremap than to walk the list... */
1711 static void __proc_unmap_allcores(struct proc *p)
1714 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1715 __unmap_vcore(p, vcore2vcoreid(p, vc_i));
1718 /* Takes (revoke via kmsg or unmap) from process p the num cores listed in
1719 * pc_arr. Will preempt if 'preempt' is set. o/w, no state will be saved, etc.
1720 * Don't use this for taking all of a process's cores.
1722 * Make sure you hold the lock when you call this, and make sure that the pcore
1723 * actually belongs to the proc, non-trivial due to other __preempt messages. */
1724 void __proc_take_corelist(struct proc *p, uint32_t *pc_arr, uint32_t num,
1729 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1730 __seq_start_write(&p->procinfo->coremap_seqctr);
1731 for (int i = 0; i < num; i++) {
1732 vcoreid = get_vcoreid(p, pc_arr[i]);
1734 assert(pc_arr[i] == get_pcoreid(p, vcoreid));
1735 /* Revoke / unmap core */
1736 if (p->state == PROC_RUNNING_M)
1737 __proc_revoke_core(p, vcoreid, preempt);
1738 __unmap_vcore(p, vcoreid);
1739 /* Change lists for the vcore. Note, the vcore is already unmapped
1740 * and/or the messages are already in flight. The only code that looks
1741 * at the lists without holding the lock is event code. */
1742 vc = vcoreid2vcore(p, vcoreid);
1743 TAILQ_REMOVE(&p->online_vcs, vc, list);
1744 /* even for single preempts, we use the inactive list. bulk preempt is
1745 * only used for when we take everything. */
1746 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1748 p->procinfo->num_vcores -= num;
1749 __seq_end_write(&p->procinfo->coremap_seqctr);
1750 p->procinfo->res_grant[RES_CORES] -= num;
1753 /* Takes all cores from a process (revoke via kmsg or unmap), putting them on
1754 * the appropriate vcore list, and fills pc_arr with the pcores revoked, and
1755 * returns the number of entries in pc_arr.
1757 * Make sure pc_arr is big enough to handle num_vcores().
1758 * Make sure you hold the lock when you call this. */
1759 uint32_t __proc_take_allcores(struct proc *p, uint32_t *pc_arr, bool preempt)
1761 struct vcore *vc_i, *vc_temp;
1763 assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1764 __seq_start_write(&p->procinfo->coremap_seqctr);
1765 /* Write out which pcores we're going to take */
1766 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1767 pc_arr[num++] = vc_i->pcoreid;
1768 /* Revoke if they are running, and unmap. Both of these need the online
1769 * list to not be changed yet. */
1770 if (p->state == PROC_RUNNING_M)
1771 __proc_revoke_allcores(p, preempt);
1772 __proc_unmap_allcores(p);
1773 /* Move the vcores from online to the head of the appropriate list */
1774 TAILQ_FOREACH_SAFE(vc_i, &p->online_vcs, list, vc_temp) {
1775 /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does that */
1776 TAILQ_REMOVE(&p->online_vcs, vc_i, list);
1777 /* Put the cores on the appropriate list */
1779 TAILQ_INSERT_HEAD(&p->bulk_preempted_vcs, vc_i, list);
1781 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
1783 assert(TAILQ_EMPTY(&p->online_vcs));
1784 assert(num == p->procinfo->num_vcores);
1785 p->procinfo->num_vcores = 0;
1786 __seq_end_write(&p->procinfo->coremap_seqctr);
1787 p->procinfo->res_grant[RES_CORES] = 0;
1791 /* Helper to do the vcore->pcore and inverse mapping. Hold the lock when
1793 void __map_vcore(struct proc *p, uint32_t vcoreid, uint32_t pcoreid)
1795 p->procinfo->vcoremap[vcoreid].pcoreid = pcoreid;
1796 p->procinfo->vcoremap[vcoreid].valid = TRUE;
1797 p->procinfo->pcoremap[pcoreid].vcoreid = vcoreid;
1798 p->procinfo->pcoremap[pcoreid].valid = TRUE;
1801 /* Helper to unmap the vcore->pcore and inverse mapping. Hold the lock when
1803 void __unmap_vcore(struct proc *p, uint32_t vcoreid)
1805 p->procinfo->pcoremap[p->procinfo->vcoremap[vcoreid].pcoreid].valid = FALSE;
1806 p->procinfo->vcoremap[vcoreid].valid = FALSE;
1809 /* Stop running whatever context is on this core and load a known-good cr3.
1810 * Note this leaves no trace of what was running. This "leaves the process's
1813 * This does not clear the owning proc. Use the other helper for that. */
1814 void abandon_core(void)
1816 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1817 /* Syscalls that don't return will ultimately call abadon_core(), so we need
1818 * to make sure we don't think we are still working on a syscall. */
1819 pcpui->cur_kthread->sysc = 0;
1820 pcpui->cur_kthread->errbuf = 0; /* just in case */
1821 if (pcpui->cur_proc)
1825 /* Helper to clear the core's owning processor and manage refcnting. Pass in
1826 * core_id() to save a couple core_id() calls. */
1827 void clear_owning_proc(uint32_t coreid)
1829 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1830 struct proc *p = pcpui->owning_proc;
1832 __clear_owning_proc(coreid);
1833 pcpui->owning_proc = 0;
1834 pcpui->owning_vcoreid = 0xdeadbeef;
1835 pcpui->cur_ctx = 0; /* catch bugs for now (may go away) */
1840 /* Switches to the address space/context of new_p, doing nothing if we are
1841 * already in new_p. This won't add extra refcnts or anything, and needs to be
1842 * paired with switch_back() at the end of whatever function you are in.
1843 * Specifically, the uncounted refs are one for the old_proc, which is passed
1844 * back to the caller, and new_p is getting placed in cur_proc. */
1845 uintptr_t switch_to(struct proc *new_p)
1847 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1848 struct kthread *kth = pcpui->cur_kthread;
1849 struct proc *old_proc;
1852 old_proc = pcpui->cur_proc; /* uncounted ref */
1853 /* If we aren't the proc already, then switch to it */
1854 if (old_proc != new_p) {
1855 pcpui->cur_proc = new_p; /* uncounted ref */
1857 lcr3(new_p->env_cr3);
1861 ret = (uintptr_t)old_proc;
1862 if (is_ktask(kth)) {
1863 if (!(kth->flags & KTH_SAVE_ADDR_SPACE)) {
1864 kth->flags |= KTH_SAVE_ADDR_SPACE;
1865 /* proc pointers are aligned; we can use the lower bit as a signal
1866 * to turn off SAVE_ADDR_SPACE. */
1873 /* This switches back from new_p to the original process. Pair it with
1874 * switch_to(), and pass in its return value for old_ret. */
1875 void switch_back(struct proc *new_p, uintptr_t old_ret)
1877 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1878 struct kthread *kth = pcpui->cur_kthread;
1879 struct proc *old_proc;
1881 if (is_ktask(kth)) {
1882 if (old_ret & 0x1) {
1883 kth->flags &= ~KTH_SAVE_ADDR_SPACE;
1887 old_proc = (struct proc*)old_ret;
1888 if (old_proc != new_p) {
1889 pcpui->cur_proc = old_proc;
1891 lcr3(old_proc->env_cr3);
1897 /* Will send a TLB shootdown message to every vcore in the main address space
1898 * (aka, all vcores for now). The message will take the start and end virtual
1899 * addresses as well, in case we want to be more clever about how much we
1900 * shootdown and batching our messages. Should do the sanity about rounding up
1901 * and down in this function too.
1903 * Would be nice to have a broadcast kmsg at this point. Note this may send a
1904 * message to the calling core (interrupting it, possibly while holding the
1905 * proc_lock). We don't need to process routine messages since it's an
1906 * immediate message. */
1907 void proc_tlbshootdown(struct proc *p, uintptr_t start, uintptr_t end)
1909 /* TODO: need a better way to find cores running our address space. we can
1910 * have kthreads running syscalls, async calls, processes being created. */
1912 /* TODO: we might be able to avoid locking here in the future (we must hit
1913 * all online, and we can check __mapped). it'll be complicated. */
1914 spin_lock(&p->proc_lock);
1916 case (PROC_RUNNING_S):
1919 case (PROC_RUNNING_M):
1920 /* TODO: (TLB) sanity checks and rounding on the ranges.
1922 * We need to make sure that once a core that was online has been
1923 * removed from the online list, then it must receive a TLB flush
1924 * (abandon_core()) before running the process again. Either that,
1925 * or make other decisions about who to TLB-shootdown. */
1926 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
1927 send_kernel_message(vc_i->pcoreid, __tlbshootdown, start, end,
1932 /* TODO: til we fix shootdowns, there are some odd cases where we
1933 * have the address space loaded, but the state is in transition. */
1937 spin_unlock(&p->proc_lock);
1940 /* Helper, used by __startcore and __set_curctx, which sets up cur_ctx to run a
1941 * given process's vcore. Caller needs to set up things like owning_proc and
1942 * whatnot. Note that we might not have p loaded as current. */
1943 static void __set_curctx_to_vcoreid(struct proc *p, uint32_t vcoreid,
1944 uint32_t old_nr_preempts_sent)
1946 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1947 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1948 struct vcore *vc = vcoreid2vcore(p, vcoreid);
1949 /* Spin until our vcore's old preemption is done. When __SC was sent, we
1950 * were told what the nr_preempts_sent was at that time. Once that many are
1951 * done, it is time for us to run. This forces a 'happens-before' ordering
1952 * on a __PR of our VC before this __SC of the VC. Note the nr_done should
1953 * not exceed old_nr_sent, since further __PR are behind this __SC in the
1955 while (old_nr_preempts_sent != vc->nr_preempts_done)
1957 cmb(); /* read nr_done before any other rd or wr. CPU mb in the atomic. */
1958 /* Mark that this vcore as no longer preempted. No danger of clobbering
1959 * other writes, since this would get turned on in __preempt (which can't be
1960 * concurrent with this function on this core), and the atomic is just
1961 * toggling the one bit (a concurrent VC_K_LOCK will work) */
1962 atomic_and(&vcpd->flags, ~VC_PREEMPTED);
1963 /* Once the VC is no longer preempted, we allow it to receive msgs. We
1964 * could let userspace do it, but handling it here makes it easier for them
1965 * to handle_indirs (when they turn this flag off). Note the atomics
1966 * provide the needed barriers (cmb and mb on flags). */
1967 atomic_or(&vcpd->flags, VC_CAN_RCV_MSG);
1968 printd("[kernel] startcore on physical core %d for process %d's vcore %d\n",
1969 core_id(), p->pid, vcoreid);
1970 /* If notifs are disabled, the vcore was in vcore context and we need to
1971 * restart the vcore_ctx. o/w, we give them a fresh vcore (which is also
1972 * what happens the first time a vcore comes online). No matter what,
1973 * they'll restart in vcore context. It's just a matter of whether or not
1974 * it is the old, interrupted vcore context. */
1975 if (vcpd->notif_disabled) {
1976 /* copy-in the tf we'll pop, then set all security-related fields */
1977 pcpui->actual_ctx = vcpd->vcore_ctx;
1978 proc_secure_ctx(&pcpui->actual_ctx);
1979 } else { /* not restarting from a preemption, use a fresh vcore */
1980 assert(vcpd->vcore_stack);
1981 proc_init_ctx(&pcpui->actual_ctx, vcoreid, vcpd->vcore_entry,
1982 vcpd->vcore_stack, vcpd->vcore_tls_desc);
1983 /* Disable/mask active notifications for fresh vcores */
1984 vcpd->notif_disabled = TRUE;
1986 /* Regardless of whether or not we have a 'fresh' VC, we need to restore the
1987 * FPU state for the VC according to VCPD (which means either a saved FPU
1988 * state or a brand new init). Starting a fresh VC is just referring to the
1989 * GP context we run. The vcore itself needs to have the FPU state loaded
1990 * from when it previously ran and was saved (or a fresh FPU if it wasn't
1991 * saved). For fresh FPUs, the main purpose is for limiting info leakage.
1992 * I think VCs that don't need FPU state for some reason (like having a
1993 * current_uthread) can handle any sort of FPU state, since it gets sorted
1994 * when they pop their next uthread.
1996 * Note this can cause a GP fault on x86 if the state is corrupt. In lieu
1997 * of reading in the huge FP state and mucking with mxcsr_mask, we should
1998 * handle this like a KPF on user code. */
1999 restore_vc_fp_state(vcpd);
2000 /* cur_ctx was built above (in actual_ctx), now use it */
2001 pcpui->cur_ctx = &pcpui->actual_ctx;
2002 /* this cur_ctx will get run when the kernel returns / idles */
2003 vcore_account_online(p, vcoreid);
2006 /* Changes calling vcore to be vcoreid. enable_my_notif tells us about how the
2007 * state calling vcore wants to be left in. It will look like caller_vcoreid
2008 * was preempted. Note we don't care about notif_pending.
2011 * 0 if we successfully changed to the target vcore.
2012 * -EBUSY if the target vcore is already mapped (a good kind of failure)
2013 * -EAGAIN if we failed for some other reason and need to try again. For
2014 * example, the caller could be preempted, and we never even attempted to
2016 * -EINVAL some userspace bug */
2017 int proc_change_to_vcore(struct proc *p, uint32_t new_vcoreid,
2018 bool enable_my_notif)
2020 uint32_t caller_vcoreid, pcoreid = core_id();
2021 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
2022 struct preempt_data *caller_vcpd;
2023 struct vcore *caller_vc, *new_vc;
2024 struct event_msg preempt_msg = {0};
2025 int retval = -EAGAIN; /* by default, try again */
2026 /* Need to not reach outside the vcoremap, which might be smaller in the
2027 * future, but should always be as big as max_vcores */
2028 if (new_vcoreid >= p->procinfo->max_vcores)
2030 /* Need to lock to prevent concurrent vcore changes, like in yield. */
2031 spin_lock(&p->proc_lock);
2032 /* new_vcoreid is already runing, abort */
2033 if (vcore_is_mapped(p, new_vcoreid)) {
2037 /* Need to make sure our vcore is allowed to switch. We might have a
2038 * __preempt, __death, etc, coming in. Similar to yield. */
2040 case (PROC_RUNNING_M):
2041 break; /* the only case we can proceed */
2042 case (PROC_RUNNING_S): /* user bug, just return */
2043 case (PROC_DYING): /* incoming __death */
2044 case (PROC_DYING_ABORT):
2045 case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
2048 panic("Weird state(%s) in %s()", procstate2str(p->state),
2051 /* This is which vcore this pcore thinks it is, regardless of any unmappings
2052 * that may have happened remotely (with __PRs waiting to run) */
2053 caller_vcoreid = pcpui->owning_vcoreid;
2054 caller_vc = vcoreid2vcore(p, caller_vcoreid);
2055 caller_vcpd = &p->procdata->vcore_preempt_data[caller_vcoreid];
2056 /* This is how we detect whether or not a __PR happened. If it did, just
2057 * abort and handle the kmsg. No new __PRs are coming since we hold the
2058 * lock. This also detects a __PR followed by a __SC for the same VC. */
2059 if (caller_vc->nr_preempts_sent != caller_vc->nr_preempts_done)
2061 /* Sanity checks. If we were preempted or are dying, we should have noticed
2063 assert(is_mapped_vcore(p, pcoreid));
2064 assert(caller_vcoreid == get_vcoreid(p, pcoreid));
2065 /* Should only call from vcore context */
2066 if (!caller_vcpd->notif_disabled) {
2068 printk("[kernel] You tried to change vcores from uthread ctx\n");
2071 /* Ok, we're clear to do the switch. Lets figure out who the new one is */
2072 new_vc = vcoreid2vcore(p, new_vcoreid);
2073 printd("[kernel] changing vcore %d to vcore %d\n", caller_vcoreid,
2075 /* enable_my_notif signals how we'll be restarted */
2076 if (enable_my_notif) {
2077 /* if they set this flag, then the vcore can just restart from scratch,
2078 * and we don't care about either the uthread_ctx or the vcore_ctx. */
2079 caller_vcpd->notif_disabled = FALSE;
2080 /* Don't need to save the FPU. There should be no uthread or other
2081 * reason to return to the FPU state. But we do need to finalize the
2082 * context, even though we are throwing it away. We need to return the
2083 * pcore to a state where it can run any context and not be bound to
2084 * the old context. */
2085 arch_finalize_ctx(pcpui->cur_ctx);
2087 /* need to set up the calling vcore's ctx so that it'll get restarted by
2088 * __startcore, to make the caller look like it was preempted. */
2089 copy_current_ctx_to(&caller_vcpd->vcore_ctx);
2090 save_vc_fp_state(caller_vcpd);
2092 /* Mark our core as preempted (for userspace recovery). Userspace checks
2093 * this in handle_indirs, and it needs to check the mbox regardless of
2094 * enable_my_notif. This does mean cores that change-to with no intent to
2095 * return will be tracked as PREEMPTED until they start back up (maybe
2097 atomic_or(&caller_vcpd->flags, VC_PREEMPTED);
2098 /* Either way, unmap and offline our current vcore */
2099 /* Move the caller from online to inactive */
2100 TAILQ_REMOVE(&p->online_vcs, caller_vc, list);
2101 /* We don't bother with the notif_pending race. note that notif_pending
2102 * could still be set. this was a preempted vcore, and userspace will need
2103 * to deal with missed messages (preempt_recover() will handle that) */
2104 TAILQ_INSERT_HEAD(&p->inactive_vcs, caller_vc, list);
2105 /* Move the new one from inactive to online */
2106 TAILQ_REMOVE(&p->inactive_vcs, new_vc, list);
2107 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
2108 /* Change the vcore map */
2109 __seq_start_write(&p->procinfo->coremap_seqctr);
2110 __unmap_vcore(p, caller_vcoreid);
2111 __map_vcore(p, new_vcoreid, pcoreid);
2112 __seq_end_write(&p->procinfo->coremap_seqctr);
2113 vcore_account_offline(p, caller_vcoreid);
2114 /* Send either a PREEMPT msg or a CHECK_MSGS msg. If they said to
2115 * enable_my_notif, then all userspace needs is to check messages, not a
2116 * full preemption recovery. */
2117 preempt_msg.ev_type = (enable_my_notif ? EV_CHECK_MSGS : EV_VCORE_PREEMPT);
2118 preempt_msg.ev_arg2 = caller_vcoreid; /* arg2 is 32 bits */
2119 /* Whenever we send msgs with the proc locked, we need at least 1 online.
2120 * In this case, it's the one we just changed to. */
2121 assert(!TAILQ_EMPTY(&p->online_vcs));
2122 send_kernel_event(p, &preempt_msg, new_vcoreid);
2123 /* So this core knows which vcore is here. (cur_proc and owning_proc are
2124 * already correct): */
2125 pcpui->owning_vcoreid = new_vcoreid;
2126 /* Until we set_curctx, we don't really have a valid current tf. The stuff
2127 * in that old one is from our previous vcore, not the current
2128 * owning_vcoreid. This matters for other KMSGS that will run before
2129 * __set_curctx (like __notify). */
2131 /* Need to send a kmsg to finish. We can't set_curctx til the __PR is done,
2132 * but we can't spin right here while holding the lock (can't spin while
2133 * waiting on a message, roughly) */
2134 send_kernel_message(pcoreid, __set_curctx, (long)p, (long)new_vcoreid,
2135 (long)new_vc->nr_preempts_sent, KMSG_ROUTINE);
2137 /* Fall through to exit */
2139 spin_unlock(&p->proc_lock);
2143 /* Kernel message handler to start a process's context on this core, when the
2144 * core next considers running a process. Tightly coupled with __proc_run_m().
2145 * Interrupts are disabled. */
2146 void __startcore(uint32_t srcid, long a0, long a1, long a2)
2148 uint32_t vcoreid = (uint32_t)a1;
2149 uint32_t coreid = core_id();
2150 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2151 struct proc *p_to_run = (struct proc *)a0;
2152 uint32_t old_nr_preempts_sent = (uint32_t)a2;
2155 /* Can not be any TF from a process here already */
2156 assert(!pcpui->owning_proc);
2157 /* the sender of the kmsg increfed already for this saved ref to p_to_run */
2158 pcpui->owning_proc = p_to_run;
2159 pcpui->owning_vcoreid = vcoreid;
2160 /* sender increfed again, assuming we'd install to cur_proc. only do this
2161 * if no one else is there. this is an optimization, since we expect to
2162 * send these __startcores to idles cores, and this saves a scramble to
2163 * incref when all of the cores restartcore/startcore later. Keep in sync
2164 * with __proc_give_cores() and __proc_run_m(). */
2165 if (!pcpui->cur_proc) {
2166 pcpui->cur_proc = p_to_run; /* install the ref to cur_proc */
2167 lcr3(p_to_run->env_cr3); /* load the page tables to match cur_proc */
2169 proc_decref(p_to_run); /* can't install, decref the extra one */
2171 /* Note we are not necessarily in the cr3 of p_to_run */
2172 /* Now that we sorted refcnts and know p / which vcore it should be, set up
2173 * pcpui->cur_ctx so that it will run that particular vcore */
2174 __set_curctx_to_vcoreid(p_to_run, vcoreid, old_nr_preempts_sent);
2177 /* Kernel message handler to load a proc's vcore context on this core. Similar
2178 * to __startcore, except it is used when p already controls the core (e.g.
2179 * change_to). Since the core is already controlled, pcpui such as owning proc,
2180 * vcoreid, and cur_proc are all already set. */
2181 void __set_curctx(uint32_t srcid, long a0, long a1, long a2)
2183 struct proc *p = (struct proc*)a0;
2184 uint32_t vcoreid = (uint32_t)a1;
2185 uint32_t old_nr_preempts_sent = (uint32_t)a2;
2186 __set_curctx_to_vcoreid(p, vcoreid, old_nr_preempts_sent);
2189 /* Bail out if it's the wrong process, or if they no longer want a notif. Try
2190 * not to grab locks or write access to anything that isn't per-core in here. */
2191 void __notify(uint32_t srcid, long a0, long a1, long a2)
2193 uint32_t vcoreid, coreid = core_id();
2194 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2195 struct preempt_data *vcpd;
2196 struct proc *p = (struct proc*)a0;
2198 /* Not the right proc */
2199 if (p != pcpui->owning_proc)
2201 /* the core might be owned, but not have a valid cur_ctx (if we're in the
2202 * process of changing */
2203 if (!pcpui->cur_ctx)
2205 /* Common cur_ctx sanity checks. Note cur_ctx could be an _S's scp_ctx */
2206 vcoreid = pcpui->owning_vcoreid;
2207 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
2208 /* for SCPs that haven't (and might never) call vc_event_init, like rtld.
2209 * this is harmless for MCPS to check this */
2210 if (!scp_is_vcctx_ready(vcpd))
2212 printd("received active notification for proc %d's vcore %d on pcore %d\n",
2213 p->procinfo->pid, vcoreid, coreid);
2214 /* sort signals. notifs are now masked, like an interrupt gate */
2215 if (vcpd->notif_disabled)
2217 vcpd->notif_disabled = TRUE;
2218 /* save the old ctx in the uthread slot, build and pop a new one. Note that
2219 * silly state isn't our business for a notification. */
2220 copy_current_ctx_to(&vcpd->uthread_ctx);
2221 memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
2222 proc_init_ctx(pcpui->cur_ctx, vcoreid, vcpd->vcore_entry,
2223 vcpd->vcore_stack, vcpd->vcore_tls_desc);
2224 /* this cur_ctx will get run when the kernel returns / idles */
2227 void __preempt(uint32_t srcid, long a0, long a1, long a2)
2229 uint32_t vcoreid, coreid = core_id();
2230 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2231 struct preempt_data *vcpd;
2232 struct proc *p = (struct proc*)a0;
2235 if (p != pcpui->owning_proc) {
2236 panic("__preempt arrived for a process (%p) that was not owning (%p)!",
2237 p, pcpui->owning_proc);
2239 /* Common cur_ctx sanity checks */
2240 assert(pcpui->cur_ctx);
2241 assert(pcpui->cur_ctx == &pcpui->actual_ctx);
2242 vcoreid = pcpui->owning_vcoreid;
2243 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
2244 printd("[kernel] received __preempt for proc %d's vcore %d on pcore %d\n",
2245 p->procinfo->pid, vcoreid, coreid);
2246 /* if notifs are disabled, the vcore is in vcore context (as far as we're
2247 * concerned), and we save it in the vcore slot. o/w, we save the process's
2248 * cur_ctx in the uthread slot, and it'll appear to the vcore when it comes
2249 * back up the uthread just took a notification. */
2250 if (vcpd->notif_disabled)
2251 copy_current_ctx_to(&vcpd->vcore_ctx);
2253 copy_current_ctx_to(&vcpd->uthread_ctx);
2254 /* Userspace in a preemption handler on another core might be copying FP
2255 * state from memory (VCPD) at the moment, and if so we don't want to
2256 * clobber it. In this rare case, our current core's FPU state should be
2257 * the same as whatever is in VCPD, so this shouldn't be necessary, but the
2258 * arch-specific save function might do something other than write out
2259 * bit-for-bit the exact same data. Checking STEALING suffices, since we
2260 * hold the K_LOCK (preventing userspace from starting a fresh STEALING
2261 * phase concurrently). */
2262 if (!(atomic_read(&vcpd->flags) & VC_UTHREAD_STEALING))
2263 save_vc_fp_state(vcpd);
2264 /* Mark the vcore as preempted and unlock (was locked by the sender). */
2265 atomic_or(&vcpd->flags, VC_PREEMPTED);
2266 atomic_and(&vcpd->flags, ~VC_K_LOCK);
2267 /* either __preempt or proc_yield() ends the preempt phase. */
2268 p->procinfo->vcoremap[vcoreid].preempt_pending = 0;
2269 vcore_account_offline(p, vcoreid);
2270 wmb(); /* make sure everything else hits before we finish the preempt */
2271 /* up the nr_done, which signals the next __startcore for this vc */
2272 p->procinfo->vcoremap[vcoreid].nr_preempts_done++;
2273 /* We won't restart the process later. current gets cleared later when we
2274 * notice there is no owning_proc and we have nothing to do (smp_idle,
2275 * restartcore, etc) */
2276 clear_owning_proc(coreid);
2279 /* Kernel message handler to clean up the core when a process is dying.
2280 * Note this leaves no trace of what was running.
2281 * It's okay if death comes to a core that's already idling and has no current.
2282 * It could happen if a process decref'd before __proc_startcore could incref. */
2283 void __death(uint32_t srcid, long a0, long a1, long a2)
2285 uint32_t vcoreid, coreid = core_id();
2286 struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2287 struct proc *p = pcpui->owning_proc;
2289 vcoreid = pcpui->owning_vcoreid;
2290 printd("[kernel] death on physical core %d for process %d's vcore %d\n",
2291 coreid, p->pid, vcoreid);
2292 vcore_account_offline(p, vcoreid); /* in case anyone is counting */
2293 /* We won't restart the process later. current gets cleared later when
2294 * we notice there is no owning_proc and we have nothing to do
2295 * (smp_idle, restartcore, etc). */
2296 arch_finalize_ctx(pcpui->cur_ctx);
2297 clear_owning_proc(coreid);
2301 /* Kernel message handler, usually sent IMMEDIATE, to shoot down virtual
2302 * addresses from a0 to a1. */
2303 void __tlbshootdown(uint32_t srcid, long a0, long a1, long a2)
2305 /* TODO: (TLB) something more intelligent with the range */
2309 void print_allpids(void)
2311 void print_proc_state(void *item, void *opaque)
2313 struct proc *p = (struct proc*)item;
2315 /* this actually adds an extra space, since no progname is ever
2316 * PROGNAME_SZ bytes, due to the \0 counted in PROGNAME. */
2317 printk("%8d %-*s %-10s %6d\n", p->pid, PROC_PROGNAME_SZ, p->progname,
2318 procstate2str(p->state), p->ppid);
2320 char dashes[PROC_PROGNAME_SZ];
2321 memset(dashes, '-', PROC_PROGNAME_SZ);
2322 dashes[PROC_PROGNAME_SZ - 1] = '\0';
2323 /* -5, for 'Name ' */
2324 printk(" PID Name %-*s State Parent \n",
2325 PROC_PROGNAME_SZ - 5, "");
2326 printk("------------------------------%s\n", dashes);
2327 spin_lock(&pid_hash_lock);
2328 hash_for_each(pid_hash, print_proc_state, NULL);
2329 spin_unlock(&pid_hash_lock);
2332 void proc_get_set(struct process_set *pset)
2334 void enum_proc(void *item, void *opaque)
2336 struct proc *p = (struct proc*) item;
2337 struct process_set *pset = (struct process_set *) opaque;
2339 if (pset->num_processes < pset->size) {
2342 pset->procs[pset->num_processes] = p;
2343 pset->num_processes++;
2347 static const size_t num_extra_alloc = 16;
2352 proc_free_set(pset);
2353 pset->size = atomic_read(&num_envs) + num_extra_alloc;
2354 pset->num_processes = 0;
2355 pset->procs = (struct proc **)
2356 kzmalloc(pset->size * sizeof(struct proc *), MEM_WAIT);
2358 error(-ENOMEM, ERROR_FIXME);
2360 spin_lock(&pid_hash_lock);
2361 hash_for_each(pid_hash, enum_proc, pset);
2362 spin_unlock(&pid_hash_lock);
2364 } while (pset->num_processes == pset->size);
2367 void proc_free_set(struct process_set *pset)
2369 for (size_t i = 0; i < pset->num_processes; i++)
2370 proc_decref(pset->procs[i]);
2374 void print_proc_info(pid_t pid)
2377 uint64_t total_time = 0;
2378 struct proc *child, *p = pid2proc(pid);
2380 struct preempt_data *vcpd;
2383 printk("Bad PID.\n");
2386 vcpd = &p->procdata->vcore_preempt_data[0];
2387 spinlock_debug(&p->proc_lock);
2388 //spin_lock(&p->proc_lock); // No locking!!
2389 printk("struct proc: %p\n", p);
2390 printk("Program name: %s\n", p->progname);
2391 printk("PID: %d\n", p->pid);
2392 printk("PPID: %d\n", p->ppid);
2393 printk("State: %s (%p)\n", procstate2str(p->state), p->state);
2394 printk("\tIs %san MCP\n", p->procinfo->is_mcp ? "" : "not ");
2395 if (!scp_is_vcctx_ready(vcpd))
2396 printk("\tIs NOT vcctx ready\n");
2397 printk("Refcnt: %d\n", atomic_read(&p->p_kref.refcount) - 1);
2398 printk("Flags: 0x%08x\n", p->env_flags);
2399 printk("CR3(phys): %p\n", p->env_cr3);
2400 printk("Num Vcores: %d\n", p->procinfo->num_vcores);
2401 printk("Vcore Lists (may be in flux w/o locking):\n----------------------\n");
2402 printk("Online:\n");
2403 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
2404 printk("\tVcore %d -> Pcore %d\n", vcore2vcoreid(p, vc_i), vc_i->pcoreid);
2405 printk("Bulk Preempted:\n");
2406 TAILQ_FOREACH(vc_i, &p->bulk_preempted_vcs, list)
2407 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2408 printk("Inactive / Yielded:\n");
2409 TAILQ_FOREACH(vc_i, &p->inactive_vcs, list)
2410 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2411 printk("Nsec Online, up to the last offlining:\n------------------------");
2412 for (int i = 0; i < p->procinfo->max_vcores; i++) {
2413 uint64_t vc_time = tsc2nsec(vcore_account_gettotal(p, i));
2416 printk(" VC %3d: %14llu", i, vc_time);
2417 total_time += vc_time;
2420 printk("Total CPU-NSEC: %llu\n", total_time);
2421 printk("Resources:\n------------------------\n");
2422 for (int i = 0; i < MAX_NUM_RESOURCES; i++)
2423 printk("\tRes type: %02d, amt wanted: %08d, amt granted: %08d\n", i,
2424 p->procdata->res_req[i].amt_wanted, p->procinfo->res_grant[i]);
2425 printk("Open Files:\n");
2426 struct fd_table *files = &p->open_files;
2427 if (spin_locked(&files->lock)) {
2428 spinlock_debug(&files->lock);
2429 printk("FILE LOCK HELD, ABORTING\n");
2433 spin_lock(&files->lock);
2434 for (int i = 0; i < files->max_files; i++) {
2435 if (GET_BITMASK_BIT(files->open_fds->fds_bits, i)) {
2436 printk("\tFD: %02d, ", i);
2437 if (files->fd[i].fd_file) {
2438 printk("File: %p, File name: %s\n", files->fd[i].fd_file,
2439 file_name(files->fd[i].fd_file));
2441 assert(files->fd[i].fd_chan);
2442 print_chaninfo(files->fd[i].fd_chan);
2446 spin_unlock(&files->lock);
2447 printk("Children: (PID (struct proc *))\n");
2448 TAILQ_FOREACH(child, &p->children, sibling_link)
2449 printk("\t%d (%p)\n", child->pid, child);
2450 /* no locking / unlocking or refcnting */
2451 // spin_unlock(&p->proc_lock);
2455 /* Debugging function, checks what (process, vcore) is supposed to run on this
2456 * pcore. Meant to be called from smp_idle() before halting. */
2457 void check_my_owner(void)
2459 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2460 void shazbot(void *item, void *opaque)
2462 struct proc *p = (struct proc*)item;
2465 spin_lock(&p->proc_lock);
2466 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
2467 /* this isn't true, a __startcore could be on the way and we're
2468 * already "online" */
2469 if (vc_i->pcoreid == core_id()) {
2470 /* Immediate message was sent, we should get it when we enable
2471 * interrupts, which should cause us to skip cpu_halt() */
2472 if (!STAILQ_EMPTY(&pcpui->immed_amsgs))
2474 printk("Owned pcore (%d) has no owner, by %p, vc %d!\n",
2475 core_id(), p, vcore2vcoreid(p, vc_i));
2476 spin_unlock(&p->proc_lock);
2477 spin_unlock(&pid_hash_lock);
2481 spin_unlock(&p->proc_lock);
2483 assert(!irq_is_enabled());
2484 if (!booting && !pcpui->owning_proc) {
2485 spin_lock(&pid_hash_lock);
2486 hash_for_each(pid_hash, shazbot, NULL);
2487 spin_unlock(&pid_hash_lock);