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 assert(!core_id()); /* want the alarm on core0 for now */
89 init_awaiter(&ksched_waiter, __kalarm);
91 /* Ghetto old idle core init */
92 /* Init idle cores. Core 0 is the management core. */
93 spin_lock(&idle_lock);
94 #ifdef __CONFIG_DISABLE_SMT__
95 /* assumes core0 is the only management core (NIC and monitor functionality
96 * are run there too. it just adds the odd cores to the idlecoremap */
97 assert(!(num_cpus % 2));
98 // TODO: consider checking x86 for machines that actually hyperthread
99 num_idlecores = num_cpus >> 1;
100 #ifdef __CONFIG_ARSC_SERVER__
101 // Dedicate one core (core 2) to sysserver, might be able to share wit NIC
103 assert(num_cpus >= num_mgmtcores);
104 send_kernel_message(2, (amr_t)arsc_server, 0,0,0, KMSG_ROUTINE);
106 for (int i = 0; i < num_idlecores; i++)
107 idlecoremap[i] = (i * 2) + 1;
109 // __CONFIG_DISABLE_SMT__
110 #ifdef __CONFIG_NETWORKING__
111 num_mgmtcores++; // Next core is dedicated to the NIC
112 assert(num_cpus >= num_mgmtcores);
114 #ifdef __CONFIG_APPSERVER__
115 #ifdef __CONFIG_DEDICATED_MONITOR__
116 num_mgmtcores++; // Next core dedicated to running the kernel monitor
117 assert(num_cpus >= num_mgmtcores);
118 // Need to subtract 1 from the num_mgmtcores # to get the cores index
119 send_kernel_message(num_mgmtcores-1, (amr_t)monitor, 0,0,0, KMSG_ROUTINE);
122 #ifdef __CONFIG_ARSC_SERVER__
123 // Dedicate one core (core 2) to sysserver, might be able to share with NIC
125 assert(num_cpus >= num_mgmtcores);
126 send_kernel_message(num_mgmtcores-1, (amr_t)arsc_server, 0,0,0, KMSG_ROUTINE);
128 num_idlecores = num_cpus - num_mgmtcores;
129 for (int i = 0; i < num_idlecores; i++)
130 idlecoremap[i] = i + num_mgmtcores;
131 #endif /* __CONFIG_DISABLE_SMT__ */
132 spin_unlock(&idle_lock);
136 /* Round-robins on whatever list it's on */
137 static void add_to_list(struct proc *p, struct proc_list *new)
139 TAILQ_INSERT_TAIL(new, p, ksched_data.proc_link);
140 p->ksched_data.cur_list = new;
143 static void remove_from_list(struct proc *p, struct proc_list *old)
145 assert(p->ksched_data.cur_list == old);
146 TAILQ_REMOVE(old, p, ksched_data.proc_link);
149 static void switch_lists(struct proc *p, struct proc_list *old,
150 struct proc_list *new)
152 remove_from_list(p, old);
156 static void __remove_from_any_list(struct proc *p)
158 if (p->ksched_data.cur_list)
159 TAILQ_REMOVE(p->ksched_data.cur_list, p, ksched_data.proc_link);
162 /* Removes from whatever list p is on */
163 static void remove_from_any_list(struct proc *p)
165 assert(p->ksched_data.cur_list);
166 TAILQ_REMOVE(p->ksched_data.cur_list, p, ksched_data.proc_link);
169 void register_proc(struct proc *p)
171 /* one ref for the proc's existence, cradle-to-grave */
172 proc_incref(p, 1); /* need at least this OR the 'one for existing' */
173 spin_lock(&sched_lock);
174 add_to_list(p, &unrunnable_scps);
175 spin_unlock(&sched_lock);
178 /* Returns 0 if it succeeded, an error code otherwise. */
179 int proc_change_to_m(struct proc *p)
182 spin_lock(&sched_lock);
183 /* Should only be necessary to lock around the change_to_m call. It's
184 * definitely necessary to hold the sched lock the whole time - need to
185 * atomically change the proc's state and have the ksched take action (and
186 * not squeeze a proc_destroy in there or something). */
187 spin_lock(&p->proc_lock);
188 retval = __proc_change_to_m(p);
189 spin_unlock(&p->proc_lock);
191 /* Failed for some reason. */
192 spin_unlock(&sched_lock);
195 /* Catch user bugs */
196 if (!p->procdata->res_req[RES_CORES].amt_wanted) {
197 printk("[kernel] process needs to specify amt_wanted\n");
198 p->procdata->res_req[RES_CORES].amt_wanted = 1;
200 /* For now, this should only ever be called on an unrunnable. It's
201 * probably a bug, at this stage in development, to do o/w. */
202 remove_from_list(p, &unrunnable_scps);
203 //remove_from_any_list(p); /* ^^ instead of this */
204 add_to_list(p, &all_mcps);
205 spin_unlock(&sched_lock);
206 //poke_ksched(p, RES_CORES);
210 /* Makes sure p is runnable. Callers may spam this, so it needs to handle
211 * repeated calls for the same event. Callers include event delivery, SCP
212 * yield, and new SCPs. Most every scheduler should do something like this -
213 * grab whatever lock you have, then call the proc helper. */
214 void proc_wakeup(struct proc *p)
216 spin_lock(&sched_lock);
217 /* will trigger one of the __sched_.cp_wakeup()s */
219 spin_unlock(&sched_lock);
222 /* Destroys the given process. This may be called from another process, a light
223 * kernel thread (no real process context), asynchronously/cross-core, or from
224 * the process on its own core.
226 * An external, edible ref is passed in. when we return and they decref,
227 * __proc_free will be called */
228 void proc_destroy(struct proc *p)
230 uint32_t nr_cores_revoked = 0;
231 spin_lock(&sched_lock);
232 spin_lock(&p->proc_lock);
233 /* storage for pc_arr is alloced at decl, which is after grabbing the lock*/
234 uint32_t pc_arr[p->procinfo->num_vcores];
235 /* If this returns true, it means we successfully destroyed the proc */
236 if (__proc_destroy(p, pc_arr, &nr_cores_revoked)) {
237 /* Do our cleanup. note that proc_free won't run since we have an
238 * external reference, passed in */
240 /* Remove from whatever list we are on */
241 remove_from_any_list(p);
242 /* Drop the cradle-to-the-grave reference, jet-li */
244 /* Put the cores back on the idlecore map. For future changes, be
245 * careful with the idle_lock. It's safe to call this here or outside
246 * the sched lock (for now). */
247 if (nr_cores_revoked)
248 put_idle_cores(pc_arr, nr_cores_revoked);
250 spin_unlock(&p->proc_lock);
251 spin_unlock(&sched_lock);
254 /* mgmt/LL cores should call this to schedule the calling core and give it to an
255 * SCP. will also prune the dead SCPs from the list. hold the lock before
256 * calling. returns TRUE if it scheduled a proc. */
257 static bool __schedule_scp(void)
260 uint32_t pcoreid = core_id();
261 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
263 /* if there are any runnables, run them here and put any currently running
264 * SCP on the tail of the runnable queue. */
265 if ((p = TAILQ_FIRST(&runnable_scps))) {
266 /* protect owning proc, cur_tf, etc. note this nests with the
267 * calls in proc_yield_s */
268 disable_irqsave(&state);
269 /* someone is currently running, dequeue them */
270 if (pcpui->owning_proc) {
271 printd("Descheduled %d in favor of %d\n", pcpui->owning_proc->pid,
273 /* locking just to be safe */
274 spin_lock(&p->proc_lock);
275 __proc_set_state(pcpui->owning_proc, PROC_RUNNABLE_S);
276 __proc_save_context_s(pcpui->owning_proc, pcpui->cur_tf);
277 spin_unlock(&p->proc_lock);
278 /* round-robin the SCPs (inserts at the end of the queue) */
279 switch_lists(pcpui->owning_proc, &unrunnable_scps, &runnable_scps);
280 clear_owning_proc(pcoreid);
281 /* Note we abandon core. It's not strictly necessary. If
282 * we didn't, the TLB would still be loaded with the old
283 * one, til we proc_run_s, and the various paths in
284 * proc_run_s would pick it up. This way is a bit safer for
285 * future changes, but has an extra (empty) TLB flush. */
288 /* Run the new proc */
289 switch_lists(p, &runnable_scps, &unrunnable_scps);
290 printd("PID of the SCP i'm running: %d\n", p->pid);
291 proc_run_s(p); /* gives it core we're running on */
292 enable_irqsave(&state);
298 /* Something has changed, and for whatever reason the scheduler should
301 * Don't call this from interrupt context (grabs proclocks). */
304 struct proc *p, *temp;
305 spin_lock(&sched_lock);
306 /* trivially try to handle the needs of all our MCPS. smarter schedulers
307 * would do something other than FCFS */
308 TAILQ_FOREACH_SAFE(p, &all_mcps, ksched_data.proc_link, temp) {
309 printd("Ksched has MCP %08p (%d)\n", p, p->pid);
312 /* TODO: might use amt_wanted as a proxy. right now, they have
313 * amt_wanted == 1, even though they are waiting.
314 * TODO: this is RACY too - just like with DYING. */
315 if (p->state == PROC_WAITING)
319 if (management_core())
321 spin_unlock(&sched_lock);
324 /* A process is asking the ksched to look at its resource desires. The
325 * scheduler is free to ignore this, for its own reasons, so long as it
326 * eventually gets around to looking at resource desires. */
327 void poke_ksched(struct proc *p, int res_type)
329 /* TODO: probably want something to trigger all res_types */
330 spin_lock(&sched_lock);
333 /* ignore core requests from non-mcps (note we have races if we ever
334 * allow procs to switch back). */
335 if (!__proc_is_mcp(p))
342 spin_unlock(&sched_lock);
345 /* ksched callbacks. p just woke up, is unlocked, and the ksched lock is held */
346 void __sched_mcp_wakeup(struct proc *p)
348 /* the essence of poke_ksched for RES_CORES */
352 /* ksched callbacks. p just woke up, is unlocked, and the ksched lock is held */
353 void __sched_scp_wakeup(struct proc *p)
355 /* might not be on a list if it is new. o/w, it should be unrunnable */
356 __remove_from_any_list(p);
357 add_to_list(p, &runnable_scps);
360 /* The calling cpu/core has nothing to do and plans to idle/halt. This is an
361 * opportunity to pick the nature of that halting (low power state, etc), or
362 * provide some other work (_Ss on LL cores). Note that interrupts are
363 * disabled, and if you return, the core will cpu_halt(). */
366 bool new_proc = FALSE;
367 if (!management_core())
369 spin_lock(&sched_lock);
370 new_proc = __schedule_scp();
371 spin_unlock(&sched_lock);
372 /* if we just scheduled a proc, we need to manually restart it, instead of
373 * returning. if we return, the core will halt. */
378 /* Could drop into the monitor if there are no processes at all. For now,
379 * the 'call of the giraffe' suffices. */
382 /* Helper function to return a core to the idlemap. It causes some more lock
383 * acquisitions (like in a for loop), but it's a little easier. Plus, one day
384 * we might be able to do this without locks (for the putting).
386 * This is a trigger, telling us we have more cores. We could/should make a
387 * scheduling decision (or at least plan to). */
388 void put_idle_core(uint32_t coreid)
390 spin_lock(&idle_lock);
391 idlecoremap[num_idlecores++] = coreid;
392 spin_unlock(&idle_lock);
395 /* Helper for put_idle and core_req. */
396 static void __put_idle_cores(uint32_t *pc_arr, uint32_t num)
398 spin_lock(&idle_lock);
399 for (int i = 0; i < num; i++)
400 idlecoremap[num_idlecores++] = pc_arr[i];
401 spin_unlock(&idle_lock);
404 /* Bulk interface for put_idle */
405 void put_idle_cores(uint32_t *pc_arr, uint32_t num)
407 /* could trigger a sched decision here */
408 __put_idle_cores(pc_arr, num);
411 /* Available resources changed (plus or minus). Some parts of the kernel may
412 * call this if a particular resource that is 'quantity-based' changes. Things
413 * like available RAM to processes, bandwidth, etc. Cores would probably be
414 * inappropriate, since we need to know which specific core is now free. */
415 void avail_res_changed(int res_type, long change)
417 printk("[kernel] ksched doesn't track any resources yet!\n");
420 /* Normally it'll be the max number of CG cores ever */
421 uint32_t max_vcores(struct proc *p)
423 #ifdef __CONFIG_DISABLE_SMT__
424 return num_cpus >> 1;
426 return MAX(1, num_cpus - num_mgmtcores);
427 #endif /* __CONFIG_DISABLE_SMT__ */
430 /* Ghetto helper, just hands out up to 'amt_new' cores (no sense of locality or
432 static uint32_t get_idle_cores(struct proc *p, uint32_t *pc_arr,
435 uint32_t num_granted = 0;
436 spin_lock(&idle_lock);
437 for (int i = 0; i < num_idlecores && i < amt_new; i++) {
438 /* grab the last one on the list */
439 pc_arr[i] = idlecoremap[num_idlecores - 1];
443 spin_unlock(&idle_lock);
447 /* This deals with a request for more cores. The request is already stored in
448 * the proc's amt_wanted (it is compared to amt_granted). */
449 static void __core_request(struct proc *p)
451 uint32_t num_granted, amt_wanted, amt_granted;
452 uint32_t corelist[num_cpus];
454 /* TODO: consider copy-in for amt_wanted too. */
455 amt_wanted = p->procdata->res_req[RES_CORES].amt_wanted;
456 amt_granted = p->procinfo->res_grant[RES_CORES];
458 /* Help them out - if they ask for something impossible, give them 1 so they
459 * can make some progress. (this is racy). */
460 if (amt_wanted > p->procinfo->max_vcores) {
461 p->procdata->res_req[RES_CORES].amt_wanted = 1;
463 /* if they are satisfied, we're done. There's a slight chance they have
464 * cores, but they aren't running (sched gave them cores while they were
465 * yielding, and now we see them on the run queue). */
466 if (amt_wanted <= amt_granted)
468 /* Otherwise, see what they want, and try to give out as many as possible.
469 * Current models are simple - it's just a raw number of cores, and we just
470 * give out what we can. */
471 num_granted = get_idle_cores(p, corelist, amt_wanted - amt_granted);
472 /* Now, actually give them out */
474 /* give them the cores. this will start up the extras if RUNNING_M. */
475 spin_lock(&p->proc_lock);
476 /* if they fail, it is because they are WAITING or DYING. we could give
477 * the cores to another proc or whatever. for the current type of
478 * ksched, we'll just put them back on the pile and return. Note, the
479 * ksched could check the states after locking, but it isn't necessary:
480 * just need to check at some point in the ksched loop. */
481 if (__proc_give_cores(p, corelist, num_granted)) {
482 __put_idle_cores(corelist, num_granted);
484 /* at some point after giving cores, call proc_run_m() (harmless on
485 * RUNNING_Ms). You can give small groups of cores, then run them
486 * (which is more efficient than interleaving runs with the gives
487 * for bulk preempted processes). */
490 spin_unlock(&p->proc_lock);
494 /************** Debugging **************/
495 void sched_diag(void)
498 spin_lock(&sched_lock);
499 TAILQ_FOREACH(p, &runnable_scps, ksched_data.proc_link)
500 printk("Runnable _S PID: %d\n", p->pid);
501 TAILQ_FOREACH(p, &unrunnable_scps, ksched_data.proc_link)
502 printk("Unrunnable _S PID: %d\n", p->pid);
503 TAILQ_FOREACH(p, &all_mcps, ksched_data.proc_link)
504 printk("MCP PID: %d\n", p->pid);
505 spin_unlock(&sched_lock);
509 void print_idlecoremap(void)
511 spin_lock(&idle_lock);
512 printk("There are %d idle cores.\n", num_idlecores);
513 for (int i = 0; i < num_idlecores; i++)
514 printk("idlecoremap[%d] = %d\n", i, idlecoremap[i]);
515 spin_unlock(&idle_lock);
518 void print_resources(struct proc *p)
520 printk("--------------------\n");
521 printk("PID: %d\n", p->pid);
522 printk("--------------------\n");
523 for (int i = 0; i < MAX_NUM_RESOURCES; i++)
524 printk("Res type: %02d, amt wanted: %08d, amt granted: %08d\n", i,
525 p->procdata->res_req[i].amt_wanted, p->procinfo->res_grant[i]);
528 void print_all_resources(void)
531 void __print_resources(void *item)
533 print_resources((struct proc*)item);
535 spin_lock(&pid_hash_lock);
536 hash_for_each(pid_hash, __print_resources);
537 spin_unlock(&pid_hash_lock);