1 /* Copyright (c) 2009, 2010 The Regents of the University of California
2 * Barret Rhoden <brho@cs.berkeley.edu>
3 * See LICENSE for details. */
11 #include <arch/arch.h>
23 #include <hashtable.h>
25 #include <sys/queue.h>
30 #include <arsc_server.h>
34 struct proc_list proc_runnablelist = TAILQ_HEAD_INITIALIZER(proc_runnablelist);
35 spinlock_t runnablelist_lock = SPINLOCK_INITIALIZER;
36 struct kmem_cache *proc_cache;
38 /* Tracks which cores are idle, similar to the vcoremap. Each value is the
39 * physical coreid of an unallocated core. */
40 spinlock_t idle_lock = SPINLOCK_INITIALIZER;
41 uint32_t LCKD(&idle_lock) (RO idlecoremap)[MAX_NUM_CPUS];
42 uint32_t LCKD(&idle_lock) num_idlecores = 0;
43 uint32_t num_mgmtcores = 1;
45 /* Helper function to return a core to the idlemap. It causes some more lock
46 * acquisitions (like in a for loop), but it's a little easier. Plus, one day
47 * we might be able to do this without locks (for the putting). */
48 void put_idle_core(uint32_t coreid)
50 spin_lock(&idle_lock);
51 idlecoremap[num_idlecores++] = coreid;
52 spin_unlock(&idle_lock);
55 /* Other helpers, implemented later. */
56 static void __proc_startcore(struct proc *p, trapframe_t *tf);
57 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid);
58 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid);
59 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid);
60 static void __proc_free(struct kref *kref);
63 #define PID_MAX 32767 // goes from 0 to 32767, with 0 reserved
64 static DECL_BITMASK(pid_bmask, PID_MAX + 1);
65 spinlock_t pid_bmask_lock = SPINLOCK_INITIALIZER;
66 struct hashtable *pid_hash;
67 spinlock_t pid_hash_lock; // initialized in proc_init
69 /* Finds the next free entry (zero) entry in the pid_bitmask. Set means busy.
70 * PID 0 is reserved (in proc_init). A return value of 0 is a failure (and
71 * you'll also see a warning, for now). Consider doing this with atomics. */
72 static pid_t get_free_pid(void)
74 static pid_t next_free_pid = 1;
77 spin_lock(&pid_bmask_lock);
78 // atomically (can lock for now, then change to atomic_and_return
79 FOR_CIRC_BUFFER(next_free_pid, PID_MAX + 1, i) {
80 // always points to the next to test
81 next_free_pid = (next_free_pid + 1) % (PID_MAX + 1);
82 if (!GET_BITMASK_BIT(pid_bmask, i)) {
83 SET_BITMASK_BIT(pid_bmask, i);
88 spin_unlock(&pid_bmask_lock);
90 warn("Shazbot! Unable to find a PID! You need to deal with this!\n");
94 /* Return a pid to the pid bitmask */
95 static void put_free_pid(pid_t pid)
97 spin_lock(&pid_bmask_lock);
98 CLR_BITMASK_BIT(pid_bmask, pid);
99 spin_unlock(&pid_bmask_lock);
102 /* While this could be done with just an assignment, this gives us the
103 * opportunity to check for bad transitions. Might compile these out later, so
104 * we shouldn't rely on them for sanity checking from userspace. */
105 int __proc_set_state(struct proc *p, uint32_t state)
107 uint32_t curstate = p->state;
108 /* Valid transitions:
124 * These ought to be implemented later (allowed, not thought through yet).
128 #if 1 // some sort of correctness flag
131 if (!(state & (PROC_RUNNABLE_S | PROC_DYING)))
132 panic("Invalid State Transition! PROC_CREATED to %02x", state);
134 case PROC_RUNNABLE_S:
135 if (!(state & (PROC_RUNNING_S | PROC_DYING)))
136 panic("Invalid State Transition! PROC_RUNNABLE_S to %02x", state);
139 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
141 panic("Invalid State Transition! PROC_RUNNING_S to %02x", state);
144 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M)))
145 panic("Invalid State Transition! PROC_WAITING to %02x", state);
148 if (state != PROC_CREATED) // when it is reused (TODO)
149 panic("Invalid State Transition! PROC_DYING to %02x", state);
151 case PROC_RUNNABLE_M:
152 if (!(state & (PROC_RUNNING_M | PROC_DYING)))
153 panic("Invalid State Transition! PROC_RUNNABLE_M to %02x", state);
156 if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING |
158 panic("Invalid State Transition! PROC_RUNNING_M to %02x", state);
166 /* Returns a pointer to the proc with the given pid, or 0 if there is none.
167 * This uses get_not_zero, since it is possible the refcnt is 0, which means the
168 * process is dying and we should not have the ref (and thus return 0). We need
169 * to lock to protect us from getting p, (someone else removes and frees p),
170 * then get_not_zero() on p.
171 * Don't push the locking into the hashtable without dealing with this. */
172 struct proc *pid2proc(pid_t pid)
174 spin_lock(&pid_hash_lock);
175 struct proc *p = hashtable_search(pid_hash, (void*)pid);
177 if (!kref_get_not_zero(&p->p_kref, 1))
179 spin_unlock(&pid_hash_lock);
183 /* Performs any initialization related to processes, such as create the proc
184 * cache, prep the scheduler, etc. When this returns, we should be ready to use
185 * any process related function. */
188 /* Catch issues with the vcoremap and TAILQ_ENTRY sizes */
189 static_assert(sizeof(TAILQ_ENTRY(vcore)) == sizeof(void*) * 2);
190 proc_cache = kmem_cache_create("proc", sizeof(struct proc),
191 MAX(HW_CACHE_ALIGN, __alignof__(struct proc)), 0, 0, 0);
192 /* Init PID mask and hash. pid 0 is reserved. */
193 SET_BITMASK_BIT(pid_bmask, 0);
194 spinlock_init(&pid_hash_lock);
195 spin_lock(&pid_hash_lock);
196 pid_hash = create_hashtable(100, __generic_hash, __generic_eq);
197 spin_unlock(&pid_hash_lock);
199 /* Init idle cores. Core 0 is the management core. */
200 spin_lock(&idle_lock);
201 #ifdef __CONFIG_DISABLE_SMT__
202 /* assumes core0 is the only management core (NIC and monitor functionality
203 * are run there too. it just adds the odd cores to the idlecoremap */
204 assert(!(num_cpus % 2));
205 // TODO: consider checking x86 for machines that actually hyperthread
206 num_idlecores = num_cpus >> 1;
207 #ifdef __CONFIG_ARSC_SERVER__
208 // Dedicate one core (core 2) to sysserver, might be able to share wit NIC
210 assert(num_cpus >= num_mgmtcores);
211 send_kernel_message(2, (amr_t)arsc_server, 0,0,0, KMSG_ROUTINE);
213 for (int i = 0; i < num_idlecores; i++)
214 idlecoremap[i] = (i * 2) + 1;
216 // __CONFIG_DISABLE_SMT__
217 #ifdef __CONFIG_NETWORKING__
218 num_mgmtcores++; // Next core is dedicated to the NIC
219 assert(num_cpus >= num_mgmtcores);
221 #ifdef __CONFIG_APPSERVER__
222 #ifdef __CONFIG_DEDICATED_MONITOR__
223 num_mgmtcores++; // Next core dedicated to running the kernel monitor
224 assert(num_cpus >= num_mgmtcores);
225 // Need to subtract 1 from the num_mgmtcores # to get the cores index
226 send_kernel_message(num_mgmtcores-1, (amr_t)monitor, 0,0,0, KMSG_ROUTINE);
229 #ifdef __CONFIG_ARSC_SERVER__
230 // Dedicate one core (core 2) to sysserver, might be able to share wit NIC
232 assert(num_cpus >= num_mgmtcores);
233 send_kernel_message(num_mgmtcores-1, (amr_t)arsc_server, 0,0,0, KMSG_ROUTINE);
235 num_idlecores = num_cpus - num_mgmtcores;
236 for (int i = 0; i < num_idlecores; i++)
237 idlecoremap[i] = i + num_mgmtcores;
238 #endif /* __CONFIG_DISABLE_SMT__ */
240 spin_unlock(&idle_lock);
241 atomic_init(&num_envs, 0);
244 /* Be sure you init'd the vcore lists before calling this. */
245 static void proc_init_procinfo(struct proc* p)
247 p->procinfo->pid = p->pid;
248 p->procinfo->ppid = p->ppid;
249 // TODO: maybe do something smarter here
250 #ifdef __CONFIG_DISABLE_SMT__
251 p->procinfo->max_vcores = num_cpus >> 1;
253 p->procinfo->max_vcores = MAX(1,num_cpus-num_mgmtcores);
254 #endif /* __CONFIG_DISABLE_SMT__ */
255 p->procinfo->tsc_freq = system_timing.tsc_freq;
256 p->procinfo->heap_bottom = (void*)UTEXT;
257 /* 0'ing the arguments. Some higher function will need to set them */
258 memset(p->procinfo->argp, 0, sizeof(p->procinfo->argp));
259 memset(p->procinfo->argbuf, 0, sizeof(p->procinfo->argbuf));
260 /* 0'ing the vcore/pcore map. Will link the vcores later. */
261 memset(&p->procinfo->vcoremap, 0, sizeof(p->procinfo->vcoremap));
262 memset(&p->procinfo->pcoremap, 0, sizeof(p->procinfo->pcoremap));
263 p->procinfo->num_vcores = 0;
264 p->procinfo->coremap_seqctr = SEQCTR_INITIALIZER;
265 /* For now, we'll go up to the max num_cpus (at runtime). In the future,
266 * there may be cases where we can have more vcores than num_cpus, but for
267 * now we'll leave it like this. */
268 for (int i = 0; i < num_cpus; i++) {
269 TAILQ_INSERT_TAIL(&p->inactive_vcs, &p->procinfo->vcoremap[i], list);
273 static void proc_init_procdata(struct proc *p)
275 memset(p->procdata, 0, sizeof(struct procdata));
278 /* Allocates and initializes a process, with the given parent. Currently
279 * writes the *p into **pp, and returns 0 on success, < 0 for an error.
281 * - ENOFREEPID if it can't get a PID
282 * - ENOMEM on memory exhaustion */
283 error_t proc_alloc(struct proc **pp, struct proc *parent)
288 if (!(p = kmem_cache_alloc(proc_cache, 0)))
293 /* one reference for the proc existing, and one for the ref we pass back. */
294 kref_init(&p->p_kref, __proc_free, 2);
295 // Setup the default map of where to get cache colors from
296 p->cache_colors_map = global_cache_colors_map;
297 p->next_cache_color = 0;
298 /* Initialize the address space */
299 if ((r = env_setup_vm(p)) < 0) {
300 kmem_cache_free(proc_cache, p);
303 if (!(p->pid = get_free_pid())) {
304 kmem_cache_free(proc_cache, p);
307 /* Set the basic status variables. */
308 spinlock_init(&p->proc_lock);
309 p->exitcode = 1337; /* so we can see processes killed by the kernel */
310 p->ppid = parent ? parent->pid : 0;
311 p->state = PROC_CREATED; /* shouldn't go through state machine for init */
314 p->env_entry = 0; // cheating. this really gets set later
315 p->heap_top = (void*)UTEXT; /* heap_bottom set in proc_init_procinfo */
316 memset(&p->resources, 0, sizeof(p->resources));
317 memset(&p->env_ancillary_state, 0, sizeof(p->env_ancillary_state));
318 memset(&p->env_tf, 0, sizeof(p->env_tf));
319 spinlock_init(&p->mm_lock);
320 TAILQ_INIT(&p->vm_regions); /* could init this in the slab */
321 /* Initialize the vcore lists, we'll build the inactive list so that it includes
322 * all vcores when we initialize procinfo. Do this before initing procinfo. */
323 TAILQ_INIT(&p->online_vcs);
324 TAILQ_INIT(&p->bulk_preempted_vcs);
325 TAILQ_INIT(&p->inactive_vcs);
326 /* Init procinfo/procdata. Procinfo's argp/argb are 0'd */
327 proc_init_procinfo(p);
328 proc_init_procdata(p);
330 /* Initialize the generic sysevent ring buffer */
331 SHARED_RING_INIT(&p->procdata->syseventring);
332 /* Initialize the frontend of the sysevent ring buffer */
333 FRONT_RING_INIT(&p->syseventfrontring,
334 &p->procdata->syseventring,
337 /* Init FS structures TODO: cleanup (might pull this out) */
338 kref_get(&default_ns.kref, 1);
340 spinlock_init(&p->fs_env.lock);
341 p->fs_env.umask = parent ? parent->fs_env.umask : S_IWGRP | S_IWOTH;
342 p->fs_env.root = p->ns->root->mnt_root;
343 kref_get(&p->fs_env.root->d_kref, 1);
344 p->fs_env.pwd = parent ? parent->fs_env.pwd : p->fs_env.root;
345 kref_get(&p->fs_env.pwd->d_kref, 1);
346 memset(&p->open_files, 0, sizeof(p->open_files)); /* slightly ghetto */
347 spinlock_init(&p->open_files.lock);
348 p->open_files.max_files = NR_OPEN_FILES_DEFAULT;
349 p->open_files.max_fdset = NR_FILE_DESC_DEFAULT;
350 p->open_files.fd = p->open_files.fd_array;
351 p->open_files.open_fds = (struct fd_set*)&p->open_files.open_fds_init;
352 /* Init the ucq hash lock */
353 p->ucq_hashlock = (struct hashlock*)&p->ucq_hl_noref;
354 hashlock_init(p->ucq_hashlock, HASHLOCK_DEFAULT_SZ);
356 atomic_inc(&num_envs);
357 frontend_proc_init(p);
358 printd("[%08x] new process %08x\n", current ? current->pid : 0, p->pid);
364 /* We have a bunch of different ways to make processes. Call this once the
365 * process is ready to be used by the rest of the system. For now, this just
366 * means when it is ready to be named via the pidhash. In the future, we might
367 * push setting the state to CREATED into here. */
368 void __proc_ready(struct proc *p)
370 spin_lock(&pid_hash_lock);
371 hashtable_insert(pid_hash, (void*)p->pid, p);
372 spin_unlock(&pid_hash_lock);
375 /* Creates a process from the specified file, argvs, and envps. Tempted to get
376 * rid of proc_alloc's style, but it is so quaint... */
377 struct proc *proc_create(struct file *prog, char **argv, char **envp)
381 if ((r = proc_alloc(&p, current)) < 0)
382 panic("proc_create: %e", r); /* one of 3 quaint usages of %e */
383 procinfo_pack_args(p->procinfo, argv, envp);
384 assert(load_elf(p, prog) == 0);
385 /* Connect to stdin, stdout, stderr */
386 assert(insert_file(&p->open_files, dev_stdin, 0) == 0);
387 assert(insert_file(&p->open_files, dev_stdout, 0) == 1);
388 assert(insert_file(&p->open_files, dev_stderr, 0) == 2);
393 /* This is called by kref_put(), once the last reference to the process is
394 * gone. Don't call this otherwise (it will panic). It will clean up the
395 * address space and deallocate any other used memory. */
396 static void __proc_free(struct kref *kref)
398 struct proc *p = container_of(kref, struct proc, p_kref);
401 printd("[PID %d] freeing proc: %d\n", current ? current->pid : 0, p->pid);
402 // All parts of the kernel should have decref'd before __proc_free is called
403 assert(kref_refcnt(&p->p_kref) == 0);
405 kref_put(&p->fs_env.root->d_kref);
406 kref_put(&p->fs_env.pwd->d_kref);
408 frontend_proc_free(p); /* TODO: please remove me one day */
409 /* Free any colors allocated to this process */
410 if (p->cache_colors_map != global_cache_colors_map) {
411 for(int i = 0; i < llc_cache->num_colors; i++)
412 cache_color_free(llc_cache, p->cache_colors_map);
413 cache_colors_map_free(p->cache_colors_map);
415 /* Remove us from the pid_hash and give our PID back (in that order). */
416 spin_lock(&pid_hash_lock);
417 if (!hashtable_remove(pid_hash, (void*)p->pid))
418 panic("Proc not in the pid table in %s", __FUNCTION__);
419 spin_unlock(&pid_hash_lock);
420 put_free_pid(p->pid);
421 /* Flush all mapped pages in the user portion of the address space */
422 env_user_mem_free(p, 0, UVPT);
423 /* These need to be free again, since they were allocated with a refcnt. */
424 free_cont_pages(p->procinfo, LOG2_UP(PROCINFO_NUM_PAGES));
425 free_cont_pages(p->procdata, LOG2_UP(PROCDATA_NUM_PAGES));
427 env_pagetable_free(p);
431 atomic_dec(&num_envs);
433 /* Dealloc the struct proc */
434 kmem_cache_free(proc_cache, p);
437 /* Whether or not actor can control target. Note we currently don't need
438 * locking for this. TODO: think about that, esp wrt proc's dying. */
439 bool proc_controls(struct proc *actor, struct proc *target)
441 return ((actor == target) || (target->ppid == actor->pid));
444 /* Helper to incref by val. Using the helper to help debug/interpose on proc
445 * ref counting. Note that pid2proc doesn't use this interface. */
446 void proc_incref(struct proc *p, unsigned int val)
448 kref_get(&p->p_kref, val);
451 /* Helper to decref for debugging. Don't directly kref_put() for now. */
452 void proc_decref(struct proc *p)
454 kref_put(&p->p_kref);
457 /* Helper, makes p the 'current' process, dropping the old current/cr3. Don't
458 * incref - this assumes the passed in reference already counted 'current'. */
459 static void __set_proc_current(struct proc *p)
461 /* We use the pcpui to access 'current' to cut down on the core_id() calls,
462 * though who know how expensive/painful they are. */
463 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
464 /* If the process wasn't here, then we need to load its address space. */
465 if (p != pcpui->cur_proc) {
466 /* Do not incref here. We were given the reference to current,
469 /* This is "leaving the process context" of the previous proc. The
470 * previous lcr3 unloaded the previous proc's context. This should
471 * rarely happen, since we usually proactively leave process context,
472 * but this is the fallback. */
474 proc_decref(pcpui->cur_proc);
479 /* Dispatches a process to run, either on the current core in the case of a
480 * RUNNABLE_S, or on its partition in the case of a RUNNABLE_M. This should
481 * never be called to "restart" a core. This expects that the "instructions"
482 * for which core(s) to run this on will be in the vcoremap, which needs to be
485 * When a process goes from RUNNABLE_M to RUNNING_M, its vcoremap will be
486 * "packed" (no holes in the vcore->pcore mapping), vcore0 will continue to run
487 * it's old core0 context, and the other cores will come in at the entry point.
488 * Including in the case of preemption.
490 * This won't return if the current core is going to be one of the processes
491 * cores (either for _S mode or for _M if it's in the vcoremap). proc_run will
492 * eat your reference if it does not return. */
493 void proc_run(struct proc *p)
495 bool self_ipi_pending = FALSE;
497 spin_lock(&p->proc_lock);
501 spin_unlock(&p->proc_lock);
502 printk("Process %d not starting due to async death\n", p->pid);
503 // if we're a worker core, smp_idle, o/w return
504 if (!management_core())
505 smp_idle(); // this never returns
507 case (PROC_RUNNABLE_S):
508 assert(current != p);
509 __proc_set_state(p, PROC_RUNNING_S);
510 /* We will want to know where this process is running, even if it is
511 * only in RUNNING_S. can use the vcoremap, which makes death easy.
512 * Also, this is the signal used in trap.c to know to save the tf in
514 __seq_start_write(&p->procinfo->coremap_seqctr);
515 p->procinfo->num_vcores = 0; /* TODO (VC#) */
516 /* TODO: For now, we won't count this as an active vcore (on the
517 * lists). This gets unmapped in resource.c, and needs work. */
518 __map_vcore(p, 0, core_id()); // sort of. this needs work.
519 __seq_end_write(&p->procinfo->coremap_seqctr);
520 /* __set_proc_current assumes the reference we give it is for
521 * current. Decref if current is already properly set, otherwise
522 * ensure current is set. */
526 __set_proc_current(p);
527 /* We restartcore, instead of startcore, since startcore is a bit
528 * lower level and we want a chance to process kmsgs before starting
530 spin_unlock(&p->proc_lock);
531 current_tf = &p->env_tf;
534 case (PROC_RUNNABLE_M):
535 /* vcoremap[i] holds the coreid of the physical core allocated to
536 * this process. It is set outside proc_run. For the kernel
537 * message, a0 = struct proc*, a1 = struct trapframe*. */
538 if (p->procinfo->num_vcores) {
539 __proc_set_state(p, PROC_RUNNING_M);
540 /* Up the refcnt, since num_vcores are going to start using this
541 * process and have it loaded in their 'current'. */
542 proc_incref(p, p->procinfo->num_vcores);
543 /* If the core we are running on is in the vcoremap, we will get
544 * an IPI (once we reenable interrupts) and never return. */
545 if (is_mapped_vcore(p, core_id()))
546 self_ipi_pending = TRUE;
547 /* Send kernel messages to all online vcores (which were added
548 * to the list and mapped in __proc_give_cores()), making them
550 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
551 send_kernel_message(vc_i->pcoreid, __startcore, (long)p,
555 warn("Tried to proc_run() an _M with no vcores!");
557 /* Unlock and decref/wait for the IPI if one is pending. This will
558 * eat the reference if we aren't returning.
560 * There a subtle race avoidance here. __proc_startcore can handle
561 * a death message, but we can't have the startcore come after the
562 * death message. Otherwise, it would look like a new process. So
563 * we hold the lock til after we send our message, which prevents a
564 * possible death message.
565 * - Note there is no guarantee this core's interrupts were on, so
566 * it may not get the message for a while... */
567 spin_unlock(&p->proc_lock);
568 __proc_kmsg_pending(p, self_ipi_pending);
571 spin_unlock(&p->proc_lock);
572 panic("Invalid process state %p in proc_run()!!", p->state);
576 /* Actually runs the given context (trapframe) of process p on the core this
577 * code executes on. This is called directly by __startcore, which needs to
578 * bypass the routine_kmsg check. Interrupts should be off when you call this.
580 * A note on refcnting: this function will not return, and your proc reference
581 * will end up stored in current. This will make no changes to p's refcnt, so
582 * do your accounting such that there is only the +1 for current. This means if
583 * it is already in current (like in the trap return path), don't up it. If
584 * it's already in current and you have another reference (like pid2proc or from
585 * an IPI), then down it (which is what happens in __startcore()). If it's not
586 * in current and you have one reference, like proc_run(non_current_p), then
587 * also do nothing. The refcnt for your *p will count for the reference stored
589 static void __proc_startcore(struct proc *p, trapframe_t *tf)
591 assert(!irq_is_enabled());
592 __set_proc_current(p);
593 /* need to load our silly state, preferably somewhere other than here so we
594 * can avoid the case where the context was just running here. it's not
595 * sufficient to do it in the "new process" if-block above (could be things
596 * like page faults that cause us to keep the same process, but want a
598 * for now, we load this silly state here. (TODO) (HSS)
599 * We also need this to be per trapframe, and not per process...
600 * For now / OSDI, only load it when in _S mode. _M mode was handled in
602 if (p->state == PROC_RUNNING_S)
603 env_pop_ancillary_state(p);
604 /* Clear the current_tf, since it is no longer used */
609 /* Restarts/runs the current_tf, which must be for the current process, on the
610 * core this code executes on. Calls an internal function to do the work.
612 * In case there are pending routine messages, like __death, __preempt, or
613 * __notify, we need to run them. Alternatively, if there are any, we could
614 * self_ipi, and run the messages immediately after popping back to userspace,
615 * but that would have crappy overhead.
617 * Refcnting: this will not return, and it assumes that you've accounted for
618 * your reference as if it was the ref for "current" (which is what happens when
619 * returning from local traps and such. */
620 void proc_restartcore(void)
622 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
623 assert(!pcpui->cur_sysc);
624 /* If there is no cur_tf, it is because the old one was already restarted
625 * (and we weren't interrupting another one to finish). In which case, we
626 * should just smp_idle() */
627 if (!pcpui->cur_tf) {
628 /* It is possible for us to have current loaded if a kthread restarted
629 * after the process yielded the core. */
633 /* Need ints disabled when we return from processing (race) */
635 /* Need to be current (set by the caller), in case a kmsg is there that
636 * tries to clobber us. */
637 process_routine_kmsg(pcpui->cur_tf);
638 __proc_startcore(pcpui->cur_proc, pcpui->cur_tf);
642 * Destroys the given process. This may be called from another process, a light
643 * kernel thread (no real process context), asynchronously/cross-core, or from
644 * the process on its own core.
646 * Here's the way process death works:
647 * 0. grab the lock (protects state transition and core map)
648 * 1. set state to dying. that keeps the kernel from doing anything for the
649 * process (like proc_running it).
650 * 2. figure out where the process is running (cross-core/async or RUNNING_M)
651 * 3. IPI to clean up those cores (decref, etc).
653 * 5. Clean up your core, if applicable
654 * (Last core/kernel thread to decref cleans up and deallocates resources.)
656 * Note that some cores can be processing async calls, but will eventually
657 * decref. Should think about this more, like some sort of callback/revocation.
659 * This will eat your reference if it won't return. Note that this function
660 * needs to change anyways when we make __death more like __preempt. (TODO) */
661 void proc_destroy(struct proc *p)
663 bool self_ipi_pending = FALSE;
665 spin_lock(&p->proc_lock);
666 /* TODO: (DEATH) look at this again when we sort the __death IPI */
668 self_ipi_pending = TRUE;
671 case PROC_DYING: // someone else killed this already.
672 spin_unlock(&p->proc_lock);
673 __proc_kmsg_pending(p, self_ipi_pending);
675 case PROC_RUNNABLE_M:
676 /* Need to reclaim any cores this proc might have, even though it's
677 * not running yet. */
678 __proc_take_allcores(p, 0, 0, 0, 0);
680 case PROC_RUNNABLE_S:
681 // Think about other lists, like WAITING, or better ways to do this
686 // here's how to do it manually
689 proc_decref(p); /* this decref is for the cr3 */
693 send_kernel_message(get_pcoreid(p, 0), __death, 0, 0, 0,
695 __seq_start_write(&p->procinfo->coremap_seqctr);
696 // TODO: might need to sort num_vcores too later (VC#)
697 /* vcore is unmapped on the receive side */
698 __seq_end_write(&p->procinfo->coremap_seqctr);
700 /* right now, RUNNING_S only runs on a mgmt core (0), not cores
701 * managed by the idlecoremap. so don't do this yet. */
702 put_idle_core(get_pcoreid(p, 0));
706 /* Send the DEATH message to every core running this process, and
707 * deallocate the cores.
708 * The rule is that the vcoremap is set before proc_run, and reset
709 * within proc_destroy */
710 __proc_take_allcores(p, __death, 0, 0, 0);
715 panic("Weird state(%s) in %s()", procstate2str(p->state),
718 __proc_set_state(p, PROC_DYING);
719 /* This prevents processes from accessing their old files while dying, and
720 * will help if these files (or similar objects in the future) hold
721 * references to p (preventing a __proc_free()). */
722 close_all_files(&p->open_files, FALSE);
723 /* This decref is for the process's existence. */
725 /* Unlock and possible decref and wait. A death IPI should be on its way,
726 * either from the RUNNING_S one, or from proc_take_cores with a __death.
727 * in general, interrupts should be on when you call proc_destroy locally,
728 * but currently aren't for all things (like traphandlers). */
729 spin_unlock(&p->proc_lock);
730 /* at this point, we normally have one ref to be eaten in kmsg_pending and
731 * one for every 'current'. and maybe one for a parent */
732 __proc_kmsg_pending(p, self_ipi_pending);
736 /* Helper function. Is the given pcore a mapped vcore? No locking involved, be
738 static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid)
740 return p->procinfo->pcoremap[pcoreid].valid;
743 /* Helper function. Find the vcoreid for a given physical core id for proc p.
744 * No locking involved, be careful. Panics on failure. */
745 static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid)
747 assert(is_mapped_vcore(p, pcoreid));
748 return p->procinfo->pcoremap[pcoreid].vcoreid;
751 /* Helper function. Find the pcoreid for a given virtual core id for proc p.
752 * No locking involved, be careful. Panics on failure. */
753 static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid)
755 assert(vcore_is_mapped(p, vcoreid));
756 return p->procinfo->vcoremap[vcoreid].pcoreid;
759 /* Helper function: yields / wraps up current_tf and schedules the _S */
760 void __proc_yield_s(struct proc *p, struct trapframe *tf)
762 assert(p->state == PROC_RUNNING_S);
764 env_push_ancillary_state(p); /* TODO: (HSS) */
765 __proc_set_state(p, PROC_RUNNABLE_S);
769 /* Yields the calling core. Must be called locally (not async) for now.
770 * - If RUNNING_S, you just give up your time slice and will eventually return.
771 * - If RUNNING_M, you give up the current vcore (which never returns), and
772 * adjust the amount of cores wanted/granted.
773 * - If you have only one vcore, you switch to RUNNABLE_M. When you run again,
774 * you'll have one guaranteed core, starting from the entry point.
776 * - RES_CORES amt_wanted will be the amount running after taking away the
777 * yielder, unless there are none left, in which case it will be 1.
779 * If the call is being nice, it means that it is in response to a preemption
780 * (which needs to be checked). If there is no preemption pending, just return.
781 * No matter what, don't adjust the number of cores wanted.
783 * This usually does not return (abandon_core()), so it will eat your reference.
785 void proc_yield(struct proc *SAFE p, bool being_nice)
787 uint32_t vcoreid = get_vcoreid(p, core_id());
788 struct vcore *vc = vcoreid2vcore(p, vcoreid);
789 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
791 /* no reason to be nice, return */
792 if (being_nice && !vc->preempt_pending)
795 spin_lock(&p->proc_lock); /* horrible scalability. =( */
797 /* fate is sealed, return and take the preempt message on the way out.
798 * we're making this check while holding the lock, since the preemptor
799 * should hold the lock when sending messages. */
800 if (vc->preempt_served) {
801 spin_unlock(&p->proc_lock);
804 /* no need to preempt later, since we are yielding (nice or otherwise) */
805 if (vc->preempt_pending)
806 vc->preempt_pending = 0;
807 /* Don't let them yield if they are missing a notification. Userspace must
808 * not leave vcore context without dealing with notif_pending. pop_ros_tf()
809 * handles leaving via uthread context. This handles leaving via a yield.
811 * This early check is an optimization. The real check is below when it
812 * works with the online_vcs list (syncing with event.c and INDIR/IPI
814 if (vcpd->notif_pending) {
815 spin_unlock(&p->proc_lock);
819 case (PROC_RUNNING_S):
820 __proc_yield_s(p, current_tf); /* current_tf 0'd in abandon core */
822 case (PROC_RUNNING_M):
823 printd("[K] Process %d (%p) is yielding on vcore %d\n", p->pid, p,
824 get_vcoreid(p, core_id()));
825 /* Remove from the online list, add to the yielded list, and unmap
826 * the vcore, which gives up the core. */
827 TAILQ_REMOVE(&p->online_vcs, vc, list);
828 /* Now that we're off the online list, check to see if an alert made
829 * it through (event.c sets this) */
831 if (vcpd->notif_pending) {
832 /* We lost, put it back on the list and abort the yield */
833 TAILQ_INSERT_TAIL(&p->online_vcs, vc, list); /* could go HEAD */
834 spin_unlock(&p->proc_lock);
837 /* We won the race with event sending, we can safely yield */
838 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
839 /* Note this protects stuff userspace should look at, which doesn't
840 * include the TAILQs. */
841 __seq_start_write(&p->procinfo->coremap_seqctr);
842 __unmap_vcore(p, vcoreid);
843 /* Adjust implied resource desires */
844 p->resources[RES_CORES].amt_granted = --(p->procinfo->num_vcores);
846 p->resources[RES_CORES].amt_wanted = p->procinfo->num_vcores;
847 __seq_end_write(&p->procinfo->coremap_seqctr);
849 put_idle_core(core_id()); /* TODO: prod the ksched? */
850 // last vcore? then we really want 1, and to yield the gang
851 if (p->procinfo->num_vcores == 0) {
852 p->resources[RES_CORES].amt_wanted = 1;
853 /* wait on an event (not supporting 'being nice' for now */
854 __proc_set_state(p, PROC_WAITING);
858 /* just return and take the death message (which should be otw) */
859 spin_unlock(&p->proc_lock);
862 // there are races that can lead to this (async death, preempt, etc)
863 panic("Weird state(%s) in %s()", procstate2str(p->state),
866 spin_unlock(&p->proc_lock);
867 proc_decref(p); /* need to eat the ref passed in */
868 /* TODO: (RMS) If there was a change to the idle cores, try and give our
869 * core to someone who was preempted. */
870 /* Clean up the core and idle. For mgmt cores, they will ultimately call
871 * manager, which will call schedule() and will repick the yielding proc. */
876 /* Sends a notification (aka active notification, aka IPI) to p's vcore. We
877 * only send a notification if one isn't already pending and they are enabled.
878 * There's a bunch of weird cases with this, and how pending / enabled are
879 * signals between the user and kernel - check the documentation.
881 * If you expect to notify yourself, cleanup state and process_routine_kmsg() */
882 void proc_notify(struct proc *p, uint32_t vcoreid)
884 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
885 /* TODO: Currently, there is a race for notif_pending, and multiple senders
886 * can send an IPI. Worst thing is that the process gets interrupted
887 * briefly and the kernel immediately returns back once it realizes notifs
888 * are masked. To fix it, we'll need atomic_swapb() (right answer), or not
889 * use a bool. (wrong answer). */
890 if (!vcpd->notif_pending) {
891 vcpd->notif_pending = TRUE;
892 if (vcpd->notif_enabled) {
893 /* GIANT WARNING: we aren't using the proc-lock to protect the
894 * vcoremap. We want to be able to use this from interrupt context,
895 * and don't want the proc_lock to be an irqsave. Spurious
896 * __notify() kmsgs are okay (it checks to see if the right receiver
898 if ((p->state & PROC_RUNNING_M) && // TODO: (VC#) (_S state)
899 vcore_is_mapped(p, vcoreid)) {
900 printd("[kernel] sending notif to vcore %d\n", vcoreid);
901 send_kernel_message(get_pcoreid(p, vcoreid), __notify, (long)p,
908 /* Hold the lock before calling this. If the process is WAITING, it will wake
909 * it up and schedule it. */
910 void __proc_wakeup(struct proc *p)
912 if (p->state != PROC_WAITING)
914 if (__proc_is_mcp(p))
915 __proc_set_state(p, PROC_RUNNABLE_M);
917 __proc_set_state(p, PROC_RUNNABLE_S);
921 /* Is the process in multi_mode / is an MCP or not? */
922 bool __proc_is_mcp(struct proc *p)
924 /* in lieu of using the amount of cores requested, or having a bunch of
925 * states (like PROC_WAITING_M and _S), I'll just track it with a bool. */
929 /************************ Preemption Functions ******************************
930 * Don't rely on these much - I'll be sure to change them up a bit.
932 * Careful about what takes a vcoreid and what takes a pcoreid. Also, there may
933 * be weird glitches with setting the state to RUNNABLE_M. It is somewhat in
934 * flux. The num_vcores is changed after take_cores, but some of the messages
935 * (or local traps) may not yet be ready to handle seeing their future state.
936 * But they should be, so fix those when they pop up.
938 * TODO: (RMS) we need to actually make the scheduler handle RUNNABLE_Ms and
939 * then schedule these, or change proc_destroy to not assume they need to be
942 * Another thing to do would be to make the _core functions take a pcorelist,
943 * and not just one pcoreid. */
945 /* Sets a preempt_pending warning for p's vcore, to go off 'when'. If you care
946 * about locking, do it before calling. Takes a vcoreid! */
947 void __proc_preempt_warn(struct proc *p, uint32_t vcoreid, uint64_t when)
949 struct event_msg local_msg = {0};
950 /* danger with doing this unlocked: preempt_pending is set, but never 0'd,
951 * since it is unmapped and not dealt with (TODO)*/
952 p->procinfo->vcoremap[vcoreid].preempt_pending = when;
954 /* Send the event (which internally checks to see how they want it) */
955 local_msg.ev_type = EV_PREEMPT_PENDING;
956 local_msg.ev_arg1 = vcoreid;
957 send_kernel_event(p, &local_msg, vcoreid);
959 /* TODO: consider putting in some lookup place for the alarm to find it.
960 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
963 /* Warns all active vcores of an impending preemption. Hold the lock if you
964 * care about the mapping (and you should). */
965 void __proc_preempt_warnall(struct proc *p, uint64_t when)
968 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
969 __proc_preempt_warn(p, vcore2vcoreid(p, vc_i), when);
970 /* TODO: consider putting in some lookup place for the alarm to find it.
971 * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
974 // TODO: function to set an alarm, if none is outstanding
976 /* Raw function to preempt a single core. Returns TRUE if the calling core will
977 * get a kmsg. If you care about locking, do it before calling. */
978 bool __proc_preempt_core(struct proc *p, uint32_t pcoreid)
980 uint32_t vcoreid = get_vcoreid(p, pcoreid);
982 p->procinfo->vcoremap[vcoreid].preempt_served = TRUE;
983 // expects a pcorelist. assumes pcore is mapped and running_m
984 return __proc_take_cores(p, &pcoreid, 1, __preempt, (long)p, 0, 0);
987 /* Raw function to preempt every vcore. Returns TRUE if the calling core will
988 * get a kmsg. If you care about locking, do it before calling. */
989 bool __proc_preempt_all(struct proc *p)
991 /* instead of doing this, we could just preempt_served all possible vcores,
992 * and not just the active ones. We would need to sort out a way to deal
993 * with stale preempt_serveds first. This might be just as fast anyways. */
995 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
996 vc_i->preempt_served = TRUE;
997 return __proc_take_allcores(p, __preempt, (long)p, 0, 0);
1000 /* Warns and preempts a vcore from p. No delaying / alarming, or anything. The
1001 * warning will be for u usec from now. */
1002 void proc_preempt_core(struct proc *p, uint32_t pcoreid, uint64_t usec)
1004 bool self_ipi_pending = FALSE;
1005 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1007 /* DYING could be okay */
1008 if (p->state != PROC_RUNNING_M) {
1009 warn("Tried to preempt from a non RUNNING_M proc!");
1012 spin_lock(&p->proc_lock);
1013 if (is_mapped_vcore(p, pcoreid)) {
1014 __proc_preempt_warn(p, get_vcoreid(p, pcoreid), warn_time);
1015 self_ipi_pending = __proc_preempt_core(p, pcoreid);
1017 warn("Pcore doesn't belong to the process!!");
1019 /* TODO: (RMS) do this once a scheduler can handle RUNNABLE_M, and make sure
1022 if (!p->procinfo->num_vcores) {
1023 __proc_set_state(p, PROC_RUNNABLE_M);
1027 spin_unlock(&p->proc_lock);
1028 __proc_kmsg_pending(p, self_ipi_pending);
1031 /* Warns and preempts all from p. No delaying / alarming, or anything. The
1032 * warning will be for u usec from now. */
1033 void proc_preempt_all(struct proc *p, uint64_t usec)
1035 bool self_ipi_pending = FALSE;
1036 uint64_t warn_time = read_tsc() + usec2tsc(usec);
1038 spin_lock(&p->proc_lock);
1039 /* DYING could be okay */
1040 if (p->state != PROC_RUNNING_M) {
1041 warn("Tried to preempt from a non RUNNING_M proc!");
1042 spin_unlock(&p->proc_lock);
1045 __proc_preempt_warnall(p, warn_time);
1046 self_ipi_pending = __proc_preempt_all(p);
1047 assert(!p->procinfo->num_vcores);
1048 /* TODO: (RMS) do this once a scheduler can handle RUNNABLE_M, and make sure
1051 __proc_set_state(p, PROC_RUNNABLE_M);
1054 spin_unlock(&p->proc_lock);
1055 __proc_kmsg_pending(p, self_ipi_pending);
1058 /* Give the specific pcore to proc p. Lots of assumptions, so don't really use
1059 * this. The proc needs to be _M and prepared for it. the pcore needs to be
1061 void proc_give(struct proc *p, uint32_t pcoreid)
1063 bool self_ipi_pending = FALSE;
1065 spin_lock(&p->proc_lock);
1066 // expects a pcorelist, we give it a list of one
1067 self_ipi_pending = __proc_give_cores(p, &pcoreid, 1);
1068 spin_unlock(&p->proc_lock);
1069 __proc_kmsg_pending(p, self_ipi_pending);
1072 /* Global version of the helper, for sys_get_vcoreid (might phase that syscall
1074 uint32_t proc_get_vcoreid(struct proc *SAFE p, uint32_t pcoreid)
1077 // TODO: the code currently doesn't track the vcoreid properly for _S (VC#)
1078 spin_lock(&p->proc_lock);
1080 case PROC_RUNNING_S:
1081 spin_unlock(&p->proc_lock);
1082 return 0; // TODO: here's the ugly part
1083 case PROC_RUNNING_M:
1084 vcoreid = get_vcoreid(p, pcoreid);
1085 spin_unlock(&p->proc_lock);
1087 case PROC_DYING: // death message is on the way
1088 spin_unlock(&p->proc_lock);
1091 spin_unlock(&p->proc_lock);
1092 panic("Weird state(%s) in %s()", procstate2str(p->state),
1097 /* TODO: make all of these static inlines when we gut the env crap */
1098 bool vcore_is_mapped(struct proc *p, uint32_t vcoreid)
1100 return p->procinfo->vcoremap[vcoreid].valid;
1103 /* Can do this, or just create a new field and save it in the vcoremap */
1104 uint32_t vcore2vcoreid(struct proc *p, struct vcore *vc)
1106 return (vc - p->procinfo->vcoremap);
1109 struct vcore *vcoreid2vcore(struct proc *p, uint32_t vcoreid)
1111 return &p->procinfo->vcoremap[vcoreid];
1114 /* Helper: gives pcore to the process, mapping it to the next available vcore */
1115 static void __proc_give_a_pcore(struct proc *p, uint32_t pcore)
1117 struct vcore *new_vc;
1118 new_vc = TAILQ_FIRST(&p->inactive_vcs);
1119 /* there are cases where this isn't true; deal with it later */
1121 printd("setting vcore %d to pcore %d\n", vcore2vcoreid(p, new_vc),
1123 TAILQ_REMOVE(&p->inactive_vcs, new_vc, list);
1124 TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1125 __map_vcore(p, vcore2vcoreid(p, new_vc), pcore);
1128 /* Gives process p the additional num cores listed in pcorelist. You must be
1129 * RUNNABLE_M or RUNNING_M before calling this. If you're RUNNING_M, this will
1130 * startup your new cores at the entry point with their virtual IDs (or restore
1131 * a preemption). If you're RUNNABLE_M, you should call proc_run after this so
1132 * that the process can start to use its cores.
1134 * If you're *_S, make sure your core0's TF is set (which is done when coming in
1135 * via arch/trap.c and we are RUNNING_S), change your state, then call this.
1136 * Then call proc_run().
1138 * The reason I didn't bring the _S cases from core_request over here is so we
1139 * can keep this family of calls dealing with only *_Ms, to avoiding caring if
1140 * this is called from another core, and to avoid the need_to_idle business.
1141 * The other way would be to have this function have the side effect of changing
1142 * state, and finding another way to do the need_to_idle.
1144 * The returned bool signals whether or not a stack-crushing IPI will come in
1145 * once you unlock after this function.
1147 * WARNING: You must hold the proc_lock before calling this! */
1148 bool __proc_give_cores(struct proc *SAFE p, uint32_t *pcorelist, size_t num)
1150 bool self_ipi_pending = FALSE;
1152 case (PROC_RUNNABLE_S):
1153 case (PROC_RUNNING_S):
1154 panic("Don't give cores to a process in a *_S state!\n");
1157 panic("Attempted to give cores to a DYING process.\n");
1159 case (PROC_RUNNABLE_M):
1160 // set up vcoremap. list should be empty, but could be called
1161 // multiple times before proc_running (someone changed their mind?)
1162 if (p->procinfo->num_vcores) {
1163 printk("[kernel] Yaaaaaarrrrr! Giving extra cores, are we?\n");
1164 // debugging: if we aren't packed, then there's a problem
1165 // somewhere, like someone forgot to take vcores after
1167 for (int i = 0; i < p->procinfo->num_vcores; i++)
1168 assert(vcore_is_mapped(p, i));
1170 // add new items to the vcoremap
1171 __seq_start_write(&p->procinfo->coremap_seqctr);
1172 p->procinfo->num_vcores += num;
1173 /* TODO: consider bulk preemption */
1174 for (int i = 0; i < num; i++)
1175 __proc_give_a_pcore(p, pcorelist[i]);
1176 __seq_end_write(&p->procinfo->coremap_seqctr);
1178 case (PROC_RUNNING_M):
1179 /* Up the refcnt, since num cores are going to start using this
1180 * process and have it loaded in their 'current'. */
1181 proc_incref(p, num);
1182 __seq_start_write(&p->procinfo->coremap_seqctr);
1183 p->procinfo->num_vcores += num;
1184 for (int i = 0; i < num; i++) {
1185 __proc_give_a_pcore(p, pcorelist[i]);
1186 send_kernel_message(pcorelist[i], __startcore, (long)p, 0, 0,
1188 if (pcorelist[i] == core_id())
1189 self_ipi_pending = TRUE;
1191 __seq_end_write(&p->procinfo->coremap_seqctr);
1194 panic("Weird state(%s) in %s()", procstate2str(p->state),
1197 p->resources[RES_CORES].amt_granted += num;
1198 return self_ipi_pending;
1201 /* Makes process p's coremap look like pcorelist (add, remove, etc). Caller
1202 * needs to know what cores are free after this call (removed, failed, etc).
1203 * This info will be returned via corelist and *num. This will send message to
1204 * any cores that are getting removed.
1206 * Before implementing this, we should probably think about when this will be
1207 * used. Implies preempting for the message. The more that I think about this,
1208 * the less I like it. For now, don't use this, and think hard before
1211 * WARNING: You must hold the proc_lock before calling this! */
1212 bool __proc_set_allcores(struct proc *SAFE p, uint32_t *pcorelist,
1213 size_t *num, amr_t message,TV(a0t) arg0,
1214 TV(a1t) arg1, TV(a2t) arg2)
1216 panic("Set all cores not implemented.\n");
1219 /* Helper for the take_cores calls: takes a specific vcore from p, optionally
1220 * sending the message (or just unmapping), gives the pcore to the idlecoremap,
1221 * and returns TRUE if a self_ipi is pending. */
1222 static bool __proc_take_a_core(struct proc *p, struct vcore *vc, amr_t message,
1223 long arg0, long arg1, long arg2)
1225 bool self_ipi_pending = FALSE;
1226 /* Change lists for the vcore. We do this before either unmapping or
1227 * sending the message, so the lists represent what will be very soon
1228 * (before we unlock, the messages are in flight). */
1229 TAILQ_REMOVE(&p->online_vcs, vc, list);
1230 TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1232 if (vc->pcoreid == core_id())
1233 self_ipi_pending = TRUE;
1234 send_kernel_message(vc->pcoreid, message, arg0, arg1, arg2,
1237 /* if there was a msg, the vcore is unmapped on the receive side.
1238 * o/w, we need to do it here. */
1239 __unmap_vcore(p, vcore2vcoreid(p, vc));
1241 /* give the pcore back to the idlecoremap */
1242 put_idle_core(vc->pcoreid);
1243 return self_ipi_pending;
1246 /* Takes from process p the num cores listed in pcorelist, using the given
1247 * message for the kernel message (__death, __preempt, etc). Like the others
1248 * in this function group, bool signals whether or not an IPI is pending.
1250 * WARNING: You must hold the proc_lock before calling this! */
1251 bool __proc_take_cores(struct proc *p, uint32_t *pcorelist, size_t num,
1252 amr_t message, long arg0, long arg1, long arg2)
1255 bool self_ipi_pending = FALSE;
1257 case (PROC_RUNNABLE_M):
1260 case (PROC_RUNNING_M):
1264 panic("Weird state(%s) in %s()", procstate2str(p->state),
1267 spin_lock(&idle_lock);
1268 assert((num <= p->procinfo->num_vcores) &&
1269 (num_idlecores + num <= num_cpus));
1270 spin_unlock(&idle_lock);
1271 __seq_start_write(&p->procinfo->coremap_seqctr);
1272 for (int i = 0; i < num; i++) {
1273 vcoreid = get_vcoreid(p, pcorelist[i]);
1275 assert(pcorelist[i] == get_pcoreid(p, vcoreid));
1276 self_ipi_pending = __proc_take_a_core(p, vcoreid2vcore(p, vcoreid),
1277 message, arg0, arg1, arg2);
1279 p->procinfo->num_vcores -= num;
1280 __seq_end_write(&p->procinfo->coremap_seqctr);
1281 p->resources[RES_CORES].amt_granted -= num;
1282 return self_ipi_pending;
1285 /* Takes all cores from a process, which must be in an _M state. Cores are
1286 * placed back in the idlecoremap. If there's a message, such as __death or
1287 * __preempt, it will be sent to the cores. The bool signals whether or not an
1288 * IPI is coming in once you unlock.
1290 * WARNING: You must hold the proc_lock before calling this! */
1291 bool __proc_take_allcores(struct proc *p, amr_t message, long arg0, long arg1,
1294 struct vcore *vc_i, *vc_temp;
1295 bool self_ipi_pending = FALSE;
1297 case (PROC_RUNNABLE_M):
1300 case (PROC_RUNNING_M):
1304 panic("Weird state(%s) in %s()", procstate2str(p->state),
1307 spin_lock(&idle_lock);
1308 assert(num_idlecores + p->procinfo->num_vcores <= num_cpus); // sanity
1309 spin_unlock(&idle_lock);
1310 __seq_start_write(&p->procinfo->coremap_seqctr);
1311 TAILQ_FOREACH_SAFE(vc_i, &p->online_vcs, list, vc_temp) {
1312 self_ipi_pending = __proc_take_a_core(p, vc_i,
1313 message, arg0, arg1, arg2);
1315 p->procinfo->num_vcores = 0;
1316 assert(TAILQ_EMPTY(&p->online_vcs));
1317 __seq_end_write(&p->procinfo->coremap_seqctr);
1318 p->resources[RES_CORES].amt_granted = 0;
1319 return self_ipi_pending;
1322 /* Helper, to be used when a proc management kmsg should be on its way. This
1323 * used to also unlock and then handle the message, back when the proc_lock was
1324 * an irqsave, and we had an IPI pending. Now we use routine kmsgs. If a msg
1325 * is pending, this needs to decref (to eat the reference of the caller) and
1326 * then process the message. Unlock before calling this, since you might not
1329 * There should already be a kmsg waiting for us, since when we checked state to
1330 * see a message was coming, the message had already been sent before unlocking.
1331 * Note we do not need interrupts enabled for this to work (you can receive a
1332 * message before its IPI by polling), though in most cases they will be.
1334 * TODO: consider inlining this, so __FUNCTION__ works (will require effort in
1335 * core_request(). */
1336 void __proc_kmsg_pending(struct proc *p, bool ipi_pending)
1340 process_routine_kmsg(0);
1341 panic("stack-killing kmsg not found in %s!!!", __FUNCTION__);
1345 /* Helper to do the vcore->pcore and inverse mapping. Hold the lock when
1347 void __map_vcore(struct proc *p, uint32_t vcoreid, uint32_t pcoreid)
1349 p->procinfo->vcoremap[vcoreid].pcoreid = pcoreid;
1350 p->procinfo->vcoremap[vcoreid].valid = TRUE;
1351 p->procinfo->pcoremap[pcoreid].vcoreid = vcoreid;
1352 p->procinfo->pcoremap[pcoreid].valid = TRUE;
1355 /* Helper to unmap the vcore->pcore and inverse mapping. Hold the lock when
1357 void __unmap_vcore(struct proc *p, uint32_t vcoreid)
1359 p->procinfo->vcoremap[vcoreid].valid = FALSE;
1360 p->procinfo->pcoremap[p->procinfo->vcoremap[vcoreid].pcoreid].valid = FALSE;
1363 /* Stop running whatever context is on this core, load a known-good cr3, and
1364 * 'idle'. Note this leaves no trace of what was running. This "leaves the
1365 * process's context. */
1366 void abandon_core(void)
1368 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1369 /* Syscalls that don't return will ultimately call abadon_core(), so we need
1370 * to make sure we don't think we are still working on a syscall. */
1371 pcpui->cur_sysc = 0;
1372 if (pcpui->cur_proc) {
1378 /* Switches to the address space/context of new_p, doing nothing if we are
1379 * already in new_p. This won't add extra refcnts or anything, and needs to be
1380 * paired with switch_back() at the end of whatever function you are in. Don't
1381 * migrate cores in the middle of a pair. Specifically, the uncounted refs are
1382 * one for the old_proc, which is passed back to the caller, and new_p is
1383 * getting placed in cur_proc. */
1384 struct proc *switch_to(struct proc *new_p)
1386 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1387 struct proc *old_proc = pcpui->cur_proc; /* uncounted ref */
1388 /* If we aren't the proc already, then switch to it */
1389 if (old_proc != new_p) {
1390 pcpui->cur_proc = new_p; /* uncounted ref */
1391 lcr3(new_p->env_cr3);
1396 /* This switches back to old_proc from new_p. Pair it with switch_to(), and
1397 * pass in its return value for old_proc. */
1398 void switch_back(struct proc *new_p, struct proc *old_proc)
1400 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1401 if (old_proc != new_p) {
1402 pcpui->cur_proc = old_proc;
1404 lcr3(old_proc->env_cr3);
1410 /* Will send a TLB shootdown message to every vcore in the main address space
1411 * (aka, all vcores for now). The message will take the start and end virtual
1412 * addresses as well, in case we want to be more clever about how much we
1413 * shootdown and batching our messages. Should do the sanity about rounding up
1414 * and down in this function too.
1416 * Would be nice to have a broadcast kmsg at this point. Note this may send a
1417 * message to the calling core (interrupting it, possibly while holding the
1418 * proc_lock). We don't need to process routine messages since it's an
1419 * immediate message. */
1420 void proc_tlbshootdown(struct proc *p, uintptr_t start, uintptr_t end)
1423 /* TODO: we might be able to avoid locking here in the future (we must hit
1424 * all online, and we can check __mapped). it'll be complicated. */
1425 spin_lock(&p->proc_lock);
1427 case (PROC_RUNNING_S):
1430 case (PROC_RUNNING_M):
1431 /* TODO: (TLB) sanity checks and rounding on the ranges */
1432 TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
1433 send_kernel_message(vc_i->pcoreid, __tlbshootdown, start, end,
1438 /* if it is dying, death messages are already on the way to all
1439 * cores, including ours, which will clear the TLB. */
1442 /* will probably get this when we have the short handlers */
1443 warn("Unexpected case %s in %s", procstate2str(p->state),
1446 spin_unlock(&p->proc_lock);
1449 /* Kernel message handler to start a process's context on this core. Tightly
1450 * coupled with proc_run(). Interrupts are disabled. */
1451 void __startcore(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1453 uint32_t pcoreid = core_id(), vcoreid;
1454 struct proc *p_to_run = (struct proc *CT(1))a0;
1455 struct trapframe local_tf;
1456 struct preempt_data *vcpd;
1459 /* the sender of the amsg increfed, thinking we weren't running current. */
1460 if (p_to_run == current)
1461 proc_decref(p_to_run);
1462 vcoreid = get_vcoreid(p_to_run, pcoreid);
1463 vcpd = &p_to_run->procdata->vcore_preempt_data[vcoreid];
1464 /* We could let userspace do this, though they come into vcore entry many
1465 * times, and we just need this to happen when the cores comes online the
1466 * first time. That, and they want this turned on as soon as we know a
1467 * vcore *WILL* be online. We could also do this earlier, when we map the
1468 * vcore to its pcore, though we don't always have current loaded or
1469 * otherwise mess with the VCPD in those code paths. */
1470 vcpd->can_rcv_msg = TRUE;
1471 printd("[kernel] startcore on physical core %d for process %d's vcore %d\n",
1472 pcoreid, p_to_run->pid, vcoreid);
1473 if (seq_is_locked(vcpd->preempt_tf_valid)) {
1474 __seq_end_write(&vcpd->preempt_tf_valid); /* mark tf as invalid */
1475 restore_fp_state(&vcpd->preempt_anc);
1476 /* notif_pending and enabled means the proc wants to receive the IPI,
1477 * but might have missed it. copy over the tf so they can restart it
1478 * later, and give them a fresh vcore. */
1479 if (vcpd->notif_pending && vcpd->notif_enabled) {
1480 vcpd->notif_tf = vcpd->preempt_tf; // could memset
1481 proc_init_trapframe(&local_tf, vcoreid, p_to_run->env_entry,
1482 vcpd->transition_stack);
1483 if (!vcpd->transition_stack)
1484 warn("No transition stack!");
1485 vcpd->notif_enabled = FALSE;
1486 vcpd->notif_pending = FALSE;
1488 /* copy-in the tf we'll pop, then set all security-related fields */
1489 local_tf = vcpd->preempt_tf;
1490 proc_secure_trapframe(&local_tf);
1492 } else { /* not restarting from a preemption, use a fresh vcore */
1493 assert(vcpd->transition_stack);
1494 proc_init_trapframe(&local_tf, vcoreid, p_to_run->env_entry,
1495 vcpd->transition_stack);
1496 /* Disable/mask active notifications for fresh vcores */
1497 vcpd->notif_enabled = FALSE;
1499 __proc_startcore(p_to_run, &local_tf); // TODO: (HSS) pass silly state *?
1502 /* Bail out if it's the wrong process, or if they no longer want a notif. Make
1503 * sure that you are passing in a user tf (otherwise, it's a bug). Try not to
1504 * grab locks or write access to anything that isn't per-core in here. */
1505 void __notify(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1507 struct user_trapframe local_tf;
1508 struct preempt_data *vcpd;
1510 struct proc *p = (struct proc*)a0;
1514 assert(!in_kernel(tf));
1515 /* We shouldn't need to lock here, since unmapping happens on the pcore and
1516 * mapping would only happen if the vcore was free, which it isn't until
1517 * after we unmap. */
1518 assert(tf == current_tf);
1519 vcoreid = get_vcoreid(p, core_id());
1520 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1521 printd("received active notification for proc %d's vcore %d on pcore %d\n",
1522 p->procinfo->pid, vcoreid, core_id());
1523 /* sort signals. notifs are now masked, like an interrupt gate */
1524 if (!vcpd->notif_enabled)
1526 vcpd->notif_enabled = FALSE;
1527 vcpd->notif_pending = FALSE; // no longer pending - it made it here
1528 /* save the old tf in the notify slot, build and pop a new one. Note that
1529 * silly state isn't our business for a notification. */
1530 // TODO: this is assuming the struct user_tf is the same as a regular TF
1531 vcpd->notif_tf = *tf;
1532 memset(&local_tf, 0, sizeof(local_tf));
1533 proc_init_trapframe(&local_tf, vcoreid, p->env_entry,
1534 vcpd->transition_stack);
1535 __proc_startcore(p, &local_tf);
1538 void __preempt(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1540 struct preempt_data *vcpd;
1541 uint32_t vcoreid, coreid = core_id();
1542 struct proc *p = (struct proc*)a0;
1545 panic("__preempt arrived for a process (%p) that was not current (%p)!",
1547 assert(!in_kernel(tf));
1548 /* We shouldn't need to lock here, since unmapping happens on the pcore and
1549 * mapping would only happen if the vcore was free, which it isn't until
1550 * after we unmap. */
1551 vcoreid = get_vcoreid(p, coreid);
1552 p->procinfo->vcoremap[vcoreid].preempt_served = FALSE;
1553 /* either __preempt or proc_yield() ends the preempt phase. */
1554 p->procinfo->vcoremap[vcoreid].preempt_pending = 0;
1555 vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1556 printd("[kernel] received __preempt for proc %d's vcore %d on pcore %d\n",
1557 p->procinfo->pid, vcoreid, core_id());
1559 /* save the old tf in the preempt slot, save the silly state, and signal the
1560 * state is a valid tf. when it is 'written,' it is valid. Using the
1561 * seq_ctrs so userspace can tell between different valid versions. If the
1562 * TF was already valid, it will panic (if CONFIGed that way). */
1563 // TODO: this is assuming the struct user_tf is the same as a regular TF
1564 vcpd->preempt_tf = *tf;
1565 save_fp_state(&vcpd->preempt_anc);
1566 __seq_start_write(&vcpd->preempt_tf_valid);
1567 __unmap_vcore(p, vcoreid);
1572 /* Kernel message handler to clean up the core when a process is dying.
1573 * Note this leaves no trace of what was running.
1574 * It's okay if death comes to a core that's already idling and has no current.
1575 * It could happen if a process decref'd before __proc_startcore could incref. */
1576 void __death(struct trapframe *tf, uint32_t srcid, long a0, long a1, long a2)
1578 uint32_t vcoreid, coreid = core_id();
1580 vcoreid = get_vcoreid(current, coreid);
1581 printd("[kernel] death on physical core %d for process %d's vcore %d\n",
1582 coreid, current->pid, vcoreid);
1583 __unmap_vcore(current, vcoreid);
1589 /* Kernel message handler, usually sent IMMEDIATE, to shoot down virtual
1590 * addresses from a0 to a1. */
1591 void __tlbshootdown(struct trapframe *tf, uint32_t srcid, long a0, long a1,
1594 /* TODO: (TLB) something more intelligent with the range */
1598 void print_idlecoremap(void)
1600 spin_lock(&idle_lock);
1601 printk("There are %d idle cores.\n", num_idlecores);
1602 for (int i = 0; i < num_idlecores; i++)
1603 printk("idlecoremap[%d] = %d\n", i, idlecoremap[i]);
1604 spin_unlock(&idle_lock);
1607 void print_allpids(void)
1609 void print_proc_state(void *item)
1611 struct proc *p = (struct proc*)item;
1613 printk("%8d %s\n", p->pid, procstate2str(p->state));
1615 printk("PID STATE \n");
1616 printk("------------------\n");
1617 spin_lock(&pid_hash_lock);
1618 hash_for_each(pid_hash, print_proc_state);
1619 spin_unlock(&pid_hash_lock);
1622 void print_proc_info(pid_t pid)
1625 struct proc *p = pid2proc(pid);
1628 printk("Bad PID.\n");
1631 spinlock_debug(&p->proc_lock);
1632 //spin_lock(&p->proc_lock); // No locking!!
1633 printk("struct proc: %p\n", p);
1634 printk("PID: %d\n", p->pid);
1635 printk("PPID: %d\n", p->ppid);
1636 printk("State: 0x%08x (%s)\n", p->state, p->is_mcp ? "M" : "S");
1637 printk("Refcnt: %d\n", atomic_read(&p->p_kref.refcount) - 1);
1638 printk("Flags: 0x%08x\n", p->env_flags);
1639 printk("CR3(phys): 0x%08x\n", p->env_cr3);
1640 printk("Num Vcores: %d\n", p->procinfo->num_vcores);
1641 printk("Vcore Lists (may be in flux w/o locking):\n----------------------\n");
1642 printk("Online:\n");
1643 TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1644 printk("\tVcore %d -> Pcore %d\n", vcore2vcoreid(p, vc_i), vc_i->pcoreid);
1645 printk("Bulk Preempted:\n");
1646 TAILQ_FOREACH(vc_i, &p->bulk_preempted_vcs, list)
1647 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
1648 printk("Inactive / Yielded:\n");
1649 TAILQ_FOREACH(vc_i, &p->inactive_vcs, list)
1650 printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
1651 printk("Resources:\n------------------------\n");
1652 for (int i = 0; i < MAX_NUM_RESOURCES; i++)
1653 printk("\tRes type: %02d, amt wanted: %08d, amt granted: %08d\n", i,
1654 p->resources[i].amt_wanted, p->resources[i].amt_granted);
1655 printk("Open Files:\n");
1656 struct files_struct *files = &p->open_files;
1657 spin_lock(&files->lock);
1658 for (int i = 0; i < files->max_files; i++)
1659 if (files->fd_array[i].fd_file) {
1660 printk("\tFD: %02d, File: %08p, File name: %s\n", i,
1661 files->fd_array[i].fd_file,
1662 file_name(files->fd_array[i].fd_file));
1664 spin_unlock(&files->lock);
1665 /* No one cares, and it clutters the terminal */
1666 //printk("Vcore 0's Last Trapframe:\n");
1667 //print_trapframe(&p->env_tf);
1668 /* no locking / unlocking or refcnting */
1669 // spin_unlock(&p->proc_lock);