1 /* Copyright (c) 2009, 2012 The Regents of the University of California
2 * Barret Rhoden <brho@cs.berkeley.edu>
3 * See LICENSE for details.
5 * Scheduling and dispatching. */
20 #include <sys/queue.h>
22 /* Process Lists. 'unrunnable' is a holding list for SCPs that are running or
23 * waiting or otherwise not considered for sched decisions. */
24 struct proc_list unrunnable_scps = TAILQ_HEAD_INITIALIZER(unrunnable_scps);
25 struct proc_list runnable_scps = TAILQ_HEAD_INITIALIZER(runnable_scps);
26 struct proc_list all_mcps = TAILQ_HEAD_INITIALIZER(all_mcps);
27 spinlock_t sched_lock = SPINLOCK_INITIALIZER;
29 // This could be useful for making scheduling decisions.
30 /* Physical coremap: each index is a physical core id, with a proc ptr for
31 * whoever *should be or is* running. Very similar to current, which is what
32 * process is *really* running there. */
33 struct proc *pcoremap[MAX_NUM_CPUS];
35 /* Tracks which cores are idle, similar to the vcoremap. Each value is the
36 * physical coreid of an unallocated core. */
37 spinlock_t idle_lock = SPINLOCK_INITIALIZER;
38 uint32_t idlecoremap[MAX_NUM_CPUS];
39 uint32_t num_idlecores = 0;
40 uint32_t num_mgmtcores = 1;
42 /* Helper, defined below */
43 static void __core_request(struct proc *p);
44 static void __put_idle_cores(uint32_t *pc_arr, uint32_t num);
45 static void add_to_list(struct proc *p, struct proc_list *list);
46 static void remove_from_list(struct proc *p, struct proc_list *list);
47 static void switch_lists(struct proc *p, struct proc_list *old,
48 struct proc_list *new);
50 /* Alarm struct, for our example 'timer tick' */
51 struct alarm_waiter ksched_waiter;
53 #define TIMER_TICK_USEC 10000 /* 10msec */
55 /* Helper: Sets up a timer tick on the calling core to go off 10 msec from now.
56 * This assumes the calling core is an LL core, etc. */
57 static void set_ksched_alarm(void)
59 set_awaiter_rel(&ksched_waiter, TIMER_TICK_USEC);
60 set_alarm(&per_cpu_info[core_id()].tchain, &ksched_waiter);
63 /* Kmsg, to run the scheduler tick (not in interrupt context) and reset the
64 * alarm. Note that interrupts will be disabled, but this is not the same as
65 * interrupt context. We're a routine kmsg, which means the core is in a
67 static void __ksched_tick(struct trapframe *tf, uint32_t srcid, long a0,
70 /* TODO: imagine doing some accounting here */
72 /* Set our alarm to go off, incrementing from our last tick (instead of
73 * setting it relative to now, since some time has passed since the alarm
74 * first went off. Note, this may be now or in the past! */
75 set_awaiter_inc(&ksched_waiter, TIMER_TICK_USEC);
76 set_alarm(&per_cpu_info[core_id()].tchain, &ksched_waiter);
79 /* Interrupt/alarm handler: tells our core to run the scheduler (out of
80 * interrupt context). */
81 static void __kalarm(struct alarm_waiter *waiter)
83 send_kernel_message(core_id(), __ksched_tick, 0, 0, 0, KMSG_ROUTINE);
86 void schedule_init(void)
88 TAILQ_INIT(&runnable_scps);
89 TAILQ_INIT(&all_mcps);
90 assert(!core_id()); /* want the alarm on core0 for now */
91 init_awaiter(&ksched_waiter, __kalarm);
94 /* Ghetto old idle core init */
95 /* Init idle cores. Core 0 is the management core. */
96 spin_lock(&idle_lock);
97 #ifdef __CONFIG_DISABLE_SMT__
98 /* assumes core0 is the only management core (NIC and monitor functionality
99 * are run there too. it just adds the odd cores to the idlecoremap */
100 assert(!(num_cpus % 2));
101 // TODO: consider checking x86 for machines that actually hyperthread
102 num_idlecores = num_cpus >> 1;
103 #ifdef __CONFIG_ARSC_SERVER__
104 // Dedicate one core (core 2) to sysserver, might be able to share wit NIC
106 assert(num_cpus >= num_mgmtcores);
107 send_kernel_message(2, (amr_t)arsc_server, 0,0,0, KMSG_ROUTINE);
109 for (int i = 0; i < num_idlecores; i++)
110 idlecoremap[i] = (i * 2) + 1;
112 // __CONFIG_DISABLE_SMT__
113 #ifdef __CONFIG_NETWORKING__
114 num_mgmtcores++; // Next core is dedicated to the NIC
115 assert(num_cpus >= num_mgmtcores);
117 #ifdef __CONFIG_APPSERVER__
118 #ifdef __CONFIG_DEDICATED_MONITOR__
119 num_mgmtcores++; // Next core dedicated to running the kernel monitor
120 assert(num_cpus >= num_mgmtcores);
121 // Need to subtract 1 from the num_mgmtcores # to get the cores index
122 send_kernel_message(num_mgmtcores-1, (amr_t)monitor, 0,0,0, KMSG_ROUTINE);
125 #ifdef __CONFIG_ARSC_SERVER__
126 // Dedicate one core (core 2) to sysserver, might be able to share with NIC
128 assert(num_cpus >= num_mgmtcores);
129 send_kernel_message(num_mgmtcores-1, (amr_t)arsc_server, 0,0,0, KMSG_ROUTINE);
131 num_idlecores = num_cpus - num_mgmtcores;
132 for (int i = 0; i < num_idlecores; i++)
133 idlecoremap[i] = i + num_mgmtcores;
134 #endif /* __CONFIG_DISABLE_SMT__ */
135 spin_unlock(&idle_lock);
139 /* Round-robins on whatever list it's on */
140 static void add_to_list(struct proc *p, struct proc_list *new)
142 TAILQ_INSERT_TAIL(new, p, ksched_data.proc_link);
143 p->ksched_data.cur_list = new;
146 static void remove_from_list(struct proc *p, struct proc_list *old)
148 assert(p->ksched_data.cur_list == old);
149 TAILQ_REMOVE(old, p, ksched_data.proc_link);
152 static void switch_lists(struct proc *p, struct proc_list *old,
153 struct proc_list *new)
155 remove_from_list(p, old);
159 /* Removes from whatever list p is on */
160 static void remove_from_any_list(struct proc *p)
162 assert(p->ksched_data.cur_list);
163 TAILQ_REMOVE(p->ksched_data.cur_list, p, ksched_data.proc_link);
166 void register_proc(struct proc *p)
168 /* one ref for the proc's existence, cradle-to-grave */
169 proc_incref(p, 1); /* need at least this OR the 'one for existing' */
170 spin_lock(&sched_lock);
171 add_to_list(p, &unrunnable_scps);
172 spin_unlock(&sched_lock);
175 /* TODO: the proc lock is currently held for sched and register */
176 /* sched_scp tells us to try and run the scp
177 * TODO: change this horrible name */
178 void schedule_scp(struct proc *p)
180 spin_lock(&sched_lock);
181 printd("Scheduling PID: %d\n", p->pid);
182 switch_lists(p, &unrunnable_scps, &runnable_scps);
183 spin_unlock(&sched_lock);
186 /* Returns 0 if it succeeded, an error code otherwise. */
187 int proc_change_to_m(struct proc *p)
190 spin_lock(&sched_lock);
191 /* Should only be necessary to lock around the change_to_m call. It's
192 * definitely necessary to hold the sched lock the whole time - need to
193 * atomically change the proc's state and have the ksched take action (and
194 * not squeeze a proc_destroy in there or something). */
195 spin_lock(&p->proc_lock);
196 retval = __proc_change_to_m(p);
197 spin_unlock(&p->proc_lock);
199 /* Failed for some reason. */
200 spin_unlock(&sched_lock);
203 /* Catch user bugs */
204 if (!p->procdata->res_req[RES_CORES].amt_wanted) {
205 printk("[kernel] process needs to specify amt_wanted\n");
206 p->procdata->res_req[RES_CORES].amt_wanted = 1;
208 /* For now, this should only ever be called on an unrunnable. It's
209 * probably a bug, at this stage in development, to do o/w. */
210 remove_from_list(p, &unrunnable_scps);
211 //remove_from_any_list(p); /* ^^ instead of this */
212 add_to_list(p, &all_mcps);
213 spin_unlock(&sched_lock);
214 //poke_ksched(p, RES_CORES);
218 /* Destroys the given process. This may be called from another process, a light
219 * kernel thread (no real process context), asynchronously/cross-core, or from
220 * the process on its own core.
222 * An external, edible ref is passed in. when we return and they decref,
223 * __proc_free will be called */
224 void proc_destroy(struct proc *p)
226 uint32_t nr_cores_revoked = 0;
227 spin_lock(&sched_lock);
228 spin_lock(&p->proc_lock);
229 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
230 uint32_t pc_arr[p->procinfo->num_vcores];
231 /* If this returns true, it means we successfully destroyed the proc */
232 if (__proc_destroy(p, pc_arr, &nr_cores_revoked)) {
233 /* Do our cleanup. note that proc_free won't run since we have an
234 * external reference, passed in */
236 /* Remove from whatever list we are on */
237 remove_from_any_list(p);
238 /* Drop the cradle-to-the-grave reference, jet-li */
240 /* Put the cores back on the idlecore map. For future changes, be
241 * careful with the idle_lock. It's safe to call this here or outside
242 * the sched lock (for now). */
243 if (nr_cores_revoked)
244 put_idle_cores(pc_arr, nr_cores_revoked);
246 spin_unlock(&p->proc_lock);
247 spin_unlock(&sched_lock);
250 /* mgmt/LL cores should call this to schedule the calling core and give it to an
251 * SCP. will also prune the dead SCPs from the list. hold the lock before
252 * calling. returns TRUE if it scheduled a proc. */
253 static bool __schedule_scp(void)
256 uint32_t pcoreid = core_id();
257 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
259 /* if there are any runnables, run them here and put any currently running
260 * SCP on the tail of the runnable queue. */
261 if ((p = TAILQ_FIRST(&runnable_scps))) {
262 /* protect owning proc, cur_tf, etc. note this nests with the
263 * calls in proc_yield_s */
264 disable_irqsave(&state);
265 /* someone is currently running, dequeue them */
266 if (pcpui->owning_proc) {
267 printd("Descheduled %d in favor of %d\n", pcpui->owning_proc->pid,
269 __proc_yield_s(pcpui->owning_proc, pcpui->cur_tf);
270 /* round-robin the SCPs (inserts at the end of the queue) */
271 switch_lists(pcpui->owning_proc, &unrunnable_scps, &runnable_scps);
272 clear_owning_proc(pcoreid);
273 /* Note we abandon core. It's not strictly necessary. If
274 * we didn't, the TLB would still be loaded with the old
275 * one, til we proc_run_s, and the various paths in
276 * proc_run_s would pick it up. This way is a bit safer for
277 * future changes, but has an extra (empty) TLB flush. */
280 /* Run the new proc */
281 switch_lists(p, &runnable_scps, &unrunnable_scps);
282 printd("PID of the SCP i'm running: %d\n", p->pid);
283 proc_run_s(p); /* gives it core we're running on */
284 enable_irqsave(&state);
290 /* Something has changed, and for whatever reason the scheduler should
293 * Don't call this from interrupt context (grabs proclocks). */
296 struct proc *p, *temp;
297 spin_lock(&sched_lock);
298 /* trivially try to handle the needs of all our MCPS. smarter schedulers
299 * would do something other than FCFS */
300 TAILQ_FOREACH_SAFE(p, &all_mcps, ksched_data.proc_link, temp) {
301 printd("Ksched has MCP %08p (%d)\n", p, p->pid);
304 /* TODO: might use amt_wanted as a proxy. right now, they have
305 * amt_wanted == 1, even though they are waiting.
306 * TODO: this is RACY too - just like with DYING. */
307 if (p->state == PROC_WAITING)
311 if (management_core())
313 spin_unlock(&sched_lock);
316 /* A process is asking the ksched to look at its resource desires. The
317 * scheduler is free to ignore this, for its own reasons, so long as it
318 * eventually gets around to looking at resource desires. */
319 void poke_ksched(struct proc *p, int res_type)
321 /* TODO: probably want something to trigger all res_types */
322 spin_lock(&sched_lock);
325 /* ignore core requests from non-mcps (note we have races if we ever
326 * allow procs to switch back). */
327 if (!__proc_is_mcp(p))
334 spin_unlock(&sched_lock);
337 /* Proc p just woke up (due to an event). Our dumb ksched will just try to deal
338 * with its core desires.
339 * TODO: this may get called multiple times per unblock */
340 void ksched_proc_unblocked(struct proc *p)
342 /* TODO: this now gets called when an _S unblocks. schedule_scp() also gets
343 * called, so the process is on the _S runqueue. Might merge the two in the
345 poke_ksched(p, RES_CORES);
348 /* The calling cpu/core has nothing to do and plans to idle/halt. This is an
349 * opportunity to pick the nature of that halting (low power state, etc), or
350 * provide some other work (_Ss on LL cores). Note that interrupts are
351 * disabled, and if you return, the core will cpu_halt(). */
354 bool new_proc = FALSE;
355 if (!management_core())
357 spin_lock(&sched_lock);
358 new_proc = __schedule_scp();
359 spin_unlock(&sched_lock);
360 /* if we just scheduled a proc, we need to manually restart it, instead of
361 * returning. if we return, the core will halt. */
366 /* Could drop into the monitor if there are no processes at all. For now,
367 * the 'call of the giraffe' suffices. */
370 /* Helper function to return a core to the idlemap. It causes some more lock
371 * acquisitions (like in a for loop), but it's a little easier. Plus, one day
372 * we might be able to do this without locks (for the putting).
374 * This is a trigger, telling us we have more cores. We could/should make a
375 * scheduling decision (or at least plan to). */
376 void put_idle_core(uint32_t coreid)
378 spin_lock(&idle_lock);
379 idlecoremap[num_idlecores++] = coreid;
380 spin_unlock(&idle_lock);
383 /* Helper for put_idle and core_req. */
384 static void __put_idle_cores(uint32_t *pc_arr, uint32_t num)
386 spin_lock(&idle_lock);
387 for (int i = 0; i < num; i++)
388 idlecoremap[num_idlecores++] = pc_arr[i];
389 spin_unlock(&idle_lock);
392 /* Bulk interface for put_idle */
393 void put_idle_cores(uint32_t *pc_arr, uint32_t num)
395 /* could trigger a sched decision here */
396 __put_idle_cores(pc_arr, num);
399 /* Available resources changed (plus or minus). Some parts of the kernel may
400 * call this if a particular resource that is 'quantity-based' changes. Things
401 * like available RAM to processes, bandwidth, etc. Cores would probably be
402 * inappropriate, since we need to know which specific core is now free. */
403 void avail_res_changed(int res_type, long change)
405 printk("[kernel] ksched doesn't track any resources yet!\n");
408 /* Normally it'll be the max number of CG cores ever */
409 uint32_t max_vcores(struct proc *p)
411 #ifdef __CONFIG_DISABLE_SMT__
412 return num_cpus >> 1;
414 return MAX(1, num_cpus - num_mgmtcores);
415 #endif /* __CONFIG_DISABLE_SMT__ */
418 /* Ghetto helper, just hands out up to 'amt_new' cores (no sense of locality or
420 static uint32_t get_idle_cores(struct proc *p, uint32_t *pc_arr,
423 uint32_t num_granted = 0;
424 spin_lock(&idle_lock);
425 for (int i = 0; i < num_idlecores && i < amt_new; i++) {
426 /* grab the last one on the list */
427 pc_arr[i] = idlecoremap[num_idlecores - 1];
431 spin_unlock(&idle_lock);
435 /* This deals with a request for more cores. The request is already stored in
436 * the proc's amt_wanted (it is compared to amt_granted). */
437 static void __core_request(struct proc *p)
439 uint32_t num_granted, amt_wanted, amt_granted;
440 uint32_t corelist[num_cpus];
442 /* TODO: consider copy-in for amt_wanted too. */
443 amt_wanted = p->procdata->res_req[RES_CORES].amt_wanted;
444 amt_granted = p->procinfo->res_grant[RES_CORES];
446 /* Help them out - if they ask for something impossible, give them 1 so they
447 * can make some progress. (this is racy). */
448 if (amt_wanted > p->procinfo->max_vcores) {
449 p->procdata->res_req[RES_CORES].amt_wanted = 1;
451 /* if they are satisfied, we're done. There's a slight chance they have
452 * cores, but they aren't running (sched gave them cores while they were
453 * yielding, and now we see them on the run queue). */
454 if (amt_wanted <= amt_granted)
456 /* Otherwise, see what they want, and try to give out as many as possible.
457 * Current models are simple - it's just a raw number of cores, and we just
458 * give out what we can. */
459 num_granted = get_idle_cores(p, corelist, amt_wanted - amt_granted);
460 /* Now, actually give them out */
462 /* give them the cores. this will start up the extras if RUNNING_M. */
463 spin_lock(&p->proc_lock);
464 /* if they fail, it is because they are WAITING or DYING. we could give
465 * the cores to another proc or whatever. for the current type of
466 * ksched, we'll just put them back on the pile and return. Note, the
467 * ksched could check the states after locking, but it isn't necessary:
468 * just need to check at some point in the ksched loop. */
469 if (__proc_give_cores(p, corelist, num_granted)) {
470 __put_idle_cores(corelist, num_granted);
472 /* at some point after giving cores, call proc_run_m() (harmless on
473 * RUNNING_Ms). You can give small groups of cores, then run them
474 * (which is more efficient than interleaving runs with the gives
475 * for bulk preempted processes). */
478 spin_unlock(&p->proc_lock);
482 /************** Debugging **************/
483 void sched_diag(void)
486 spin_lock(&sched_lock);
487 TAILQ_FOREACH(p, &runnable_scps, ksched_data.proc_link)
488 printk("Runnable _S PID: %d\n", p->pid);
489 TAILQ_FOREACH(p, &unrunnable_scps, ksched_data.proc_link)
490 printk("Unrunnable _S PID: %d\n", p->pid);
491 TAILQ_FOREACH(p, &all_mcps, ksched_data.proc_link)
492 printk("MCP PID: %d\n", p->pid);
493 spin_unlock(&sched_lock);
497 void print_idlecoremap(void)
499 spin_lock(&idle_lock);
500 printk("There are %d idle cores.\n", num_idlecores);
501 for (int i = 0; i < num_idlecores; i++)
502 printk("idlecoremap[%d] = %d\n", i, idlecoremap[i]);
503 spin_unlock(&idle_lock);
506 void print_resources(struct proc *p)
508 printk("--------------------\n");
509 printk("PID: %d\n", p->pid);
510 printk("--------------------\n");
511 for (int i = 0; i < MAX_NUM_RESOURCES; i++)
512 printk("Res type: %02d, amt wanted: %08d, amt granted: %08d\n", i,
513 p->procdata->res_req[i].amt_wanted, p->procinfo->res_grant[i]);
516 void print_all_resources(void)
519 void __print_resources(void *item)
521 print_resources((struct proc*)item);
523 spin_lock(&pid_hash_lock);
524 hash_for_each(pid_hash, __print_resources);
525 spin_unlock(&pid_hash_lock);