source: mainline/kernel/generic/src/proc/scheduler.c@ df58e44

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since df58e44 was df58e44, checked in by Martin Decky <martin@…>, 14 years ago
  • add support for printing uspace stack traces from kernel console (as a last resort debugging means)
  • change the semantics of waitq_interrupt_sleep() (require threads_lock to be held even before it is called)
  • minor cstyle
  • Property mode set to 100644
File size: 17.6 KB
Line 
1/*
2 * Copyright (c) 2010 Jakub Jermar
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/** @addtogroup genericproc
30 * @{
31 */
32
33/**
34 * @file
35 * @brief Scheduler and load balancing.
36 *
37 * This file contains the scheduler and kcpulb kernel thread which
38 * performs load-balancing of per-CPU run queues.
39 */
40
41#include <proc/scheduler.h>
42#include <proc/thread.h>
43#include <proc/task.h>
44#include <mm/frame.h>
45#include <mm/page.h>
46#include <mm/as.h>
47#include <time/timeout.h>
48#include <time/delay.h>
49#include <arch/asm.h>
50#include <arch/faddr.h>
51#include <arch/cycle.h>
52#include <atomic.h>
53#include <synch/spinlock.h>
54#include <config.h>
55#include <context.h>
56#include <fpu_context.h>
57#include <func.h>
58#include <arch.h>
59#include <adt/list.h>
60#include <panic.h>
61#include <cpu.h>
62#include <print.h>
63#include <debug.h>
64#include <stacktrace.h>
65
66static void scheduler_separated_stack(void);
67
68atomic_t nrdy; /**< Number of ready threads in the system. */
69
70/** Carry out actions before new task runs. */
71static void before_task_runs(void)
72{
73 before_task_runs_arch();
74}
75
76/** Take actions before new thread runs.
77 *
78 * Perform actions that need to be
79 * taken before the newly selected
80 * thread is passed control.
81 *
82 * THREAD->lock is locked on entry
83 *
84 */
85static void before_thread_runs(void)
86{
87 before_thread_runs_arch();
88
89#ifdef CONFIG_FPU_LAZY
90 if (THREAD == CPU->fpu_owner)
91 fpu_enable();
92 else
93 fpu_disable();
94#else
95 fpu_enable();
96 if (THREAD->fpu_context_exists)
97 fpu_context_restore(THREAD->saved_fpu_context);
98 else {
99 fpu_init();
100 THREAD->fpu_context_exists = 1;
101 }
102#endif
103
104 if (THREAD->btrace) {
105 istate_t *istate = THREAD->udebug.uspace_state;
106 if (istate != NULL) {
107 printf("Thread %" PRIu64 " stack trace:\n", THREAD->tid);
108 stack_trace_istate(istate);
109 }
110
111 THREAD->btrace = false;
112 }
113}
114
115/** Take actions after THREAD had run.
116 *
117 * Perform actions that need to be
118 * taken after the running thread
119 * had been preempted by the scheduler.
120 *
121 * THREAD->lock is locked on entry
122 *
123 */
124static void after_thread_ran(void)
125{
126 after_thread_ran_arch();
127}
128
129#ifdef CONFIG_FPU_LAZY
130void scheduler_fpu_lazy_request(void)
131{
132restart:
133 fpu_enable();
134 irq_spinlock_lock(&CPU->lock, false);
135
136 /* Save old context */
137 if (CPU->fpu_owner != NULL) {
138 irq_spinlock_lock(&CPU->fpu_owner->lock, false);
139 fpu_context_save(CPU->fpu_owner->saved_fpu_context);
140
141 /* Don't prevent migration */
142 CPU->fpu_owner->fpu_context_engaged = 0;
143 irq_spinlock_unlock(&CPU->fpu_owner->lock, false);
144 CPU->fpu_owner = NULL;
145 }
146
147 irq_spinlock_lock(&THREAD->lock, false);
148 if (THREAD->fpu_context_exists) {
149 fpu_context_restore(THREAD->saved_fpu_context);
150 } else {
151 /* Allocate FPU context */
152 if (!THREAD->saved_fpu_context) {
153 /* Might sleep */
154 irq_spinlock_unlock(&THREAD->lock, false);
155 irq_spinlock_unlock(&CPU->lock, false);
156 THREAD->saved_fpu_context =
157 (fpu_context_t *) slab_alloc(fpu_context_slab, 0);
158
159 /* We may have switched CPUs during slab_alloc */
160 goto restart;
161 }
162 fpu_init();
163 THREAD->fpu_context_exists = 1;
164 }
165
166 CPU->fpu_owner = THREAD;
167 THREAD->fpu_context_engaged = 1;
168 irq_spinlock_unlock(&THREAD->lock, false);
169
170 irq_spinlock_unlock(&CPU->lock, false);
171}
172#endif /* CONFIG_FPU_LAZY */
173
174/** Initialize scheduler
175 *
176 * Initialize kernel scheduler.
177 *
178 */
179void scheduler_init(void)
180{
181}
182
183/** Get thread to be scheduled
184 *
185 * Get the optimal thread to be scheduled
186 * according to thread accounting and scheduler
187 * policy.
188 *
189 * @return Thread to be scheduled.
190 *
191 */
192static thread_t *find_best_thread(void)
193{
194 ASSERT(CPU != NULL);
195
196loop:
197
198 if (atomic_get(&CPU->nrdy) == 0) {
199 /*
200 * For there was nothing to run, the CPU goes to sleep
201 * until a hardware interrupt or an IPI comes.
202 * This improves energy saving and hyperthreading.
203 */
204 irq_spinlock_lock(&CPU->lock, false);
205 CPU->idle = true;
206 irq_spinlock_unlock(&CPU->lock, false);
207 interrupts_enable();
208
209 /*
210 * An interrupt might occur right now and wake up a thread.
211 * In such case, the CPU will continue to go to sleep
212 * even though there is a runnable thread.
213 */
214 cpu_sleep();
215 interrupts_disable();
216 goto loop;
217 }
218
219 unsigned int i;
220 for (i = 0; i < RQ_COUNT; i++) {
221 irq_spinlock_lock(&(CPU->rq[i].lock), false);
222 if (CPU->rq[i].n == 0) {
223 /*
224 * If this queue is empty, try a lower-priority queue.
225 */
226 irq_spinlock_unlock(&(CPU->rq[i].lock), false);
227 continue;
228 }
229
230 atomic_dec(&CPU->nrdy);
231 atomic_dec(&nrdy);
232 CPU->rq[i].n--;
233
234 /*
235 * Take the first thread from the queue.
236 */
237 thread_t *thread =
238 list_get_instance(CPU->rq[i].rq_head.next, thread_t, rq_link);
239 list_remove(&thread->rq_link);
240
241 irq_spinlock_pass(&(CPU->rq[i].lock), &thread->lock);
242
243 thread->cpu = CPU;
244 thread->ticks = us2ticks((i + 1) * 10000);
245 thread->priority = i; /* Correct rq index */
246
247 /*
248 * Clear the THREAD_FLAG_STOLEN flag so that t can be migrated
249 * when load balancing needs emerge.
250 */
251 thread->flags &= ~THREAD_FLAG_STOLEN;
252 irq_spinlock_unlock(&thread->lock, false);
253
254 return thread;
255 }
256
257 goto loop;
258}
259
260/** Prevent rq starvation
261 *
262 * Prevent low priority threads from starving in rq's.
263 *
264 * When the function decides to relink rq's, it reconnects
265 * respective pointers so that in result threads with 'pri'
266 * greater or equal start are moved to a higher-priority queue.
267 *
268 * @param start Threshold priority.
269 *
270 */
271static void relink_rq(int start)
272{
273 link_t head;
274
275 list_initialize(&head);
276 irq_spinlock_lock(&CPU->lock, false);
277
278 if (CPU->needs_relink > NEEDS_RELINK_MAX) {
279 int i;
280 for (i = start; i < RQ_COUNT - 1; i++) {
281 /* Remember and empty rq[i + 1] */
282
283 irq_spinlock_lock(&CPU->rq[i + 1].lock, false);
284 list_concat(&head, &CPU->rq[i + 1].rq_head);
285 size_t n = CPU->rq[i + 1].n;
286 CPU->rq[i + 1].n = 0;
287 irq_spinlock_unlock(&CPU->rq[i + 1].lock, false);
288
289 /* Append rq[i + 1] to rq[i] */
290
291 irq_spinlock_lock(&CPU->rq[i].lock, false);
292 list_concat(&CPU->rq[i].rq_head, &head);
293 CPU->rq[i].n += n;
294 irq_spinlock_unlock(&CPU->rq[i].lock, false);
295 }
296
297 CPU->needs_relink = 0;
298 }
299
300 irq_spinlock_unlock(&CPU->lock, false);
301}
302
303/** The scheduler
304 *
305 * The thread scheduling procedure.
306 * Passes control directly to
307 * scheduler_separated_stack().
308 *
309 */
310void scheduler(void)
311{
312 volatile ipl_t ipl;
313
314 ASSERT(CPU != NULL);
315
316 ipl = interrupts_disable();
317
318 if (atomic_get(&haltstate))
319 halt();
320
321 if (THREAD) {
322 irq_spinlock_lock(&THREAD->lock, false);
323
324 /* Update thread kernel accounting */
325 THREAD->kcycles += get_cycle() - THREAD->last_cycle;
326
327#ifndef CONFIG_FPU_LAZY
328 fpu_context_save(THREAD->saved_fpu_context);
329#endif
330 if (!context_save(&THREAD->saved_context)) {
331 /*
332 * This is the place where threads leave scheduler();
333 */
334
335 /* Save current CPU cycle */
336 THREAD->last_cycle = get_cycle();
337
338 irq_spinlock_unlock(&THREAD->lock, false);
339 interrupts_restore(THREAD->saved_context.ipl);
340
341 return;
342 }
343
344 /*
345 * Interrupt priority level of preempted thread is recorded
346 * here to facilitate scheduler() invocations from
347 * interrupts_disable()'d code (e.g. waitq_sleep_timeout()).
348 *
349 */
350 THREAD->saved_context.ipl = ipl;
351 }
352
353 /*
354 * Through the 'THE' structure, we keep track of THREAD, TASK, CPU, VM
355 * and preemption counter. At this point THE could be coming either
356 * from THREAD's or CPU's stack.
357 *
358 */
359 the_copy(THE, (the_t *) CPU->stack);
360
361 /*
362 * We may not keep the old stack.
363 * Reason: If we kept the old stack and got blocked, for instance, in
364 * find_best_thread(), the old thread could get rescheduled by another
365 * CPU and overwrite the part of its own stack that was also used by
366 * the scheduler on this CPU.
367 *
368 * Moreover, we have to bypass the compiler-generated POP sequence
369 * which is fooled by SP being set to the very top of the stack.
370 * Therefore the scheduler() function continues in
371 * scheduler_separated_stack().
372 *
373 */
374 context_save(&CPU->saved_context);
375 context_set(&CPU->saved_context, FADDR(scheduler_separated_stack),
376 (uintptr_t) CPU->stack, CPU_STACK_SIZE);
377 context_restore(&CPU->saved_context);
378
379 /* Not reached */
380}
381
382/** Scheduler stack switch wrapper
383 *
384 * Second part of the scheduler() function
385 * using new stack. Handling the actual context
386 * switch to a new thread.
387 *
388 */
389void scheduler_separated_stack(void)
390{
391 DEADLOCK_PROBE_INIT(p_joinwq);
392 task_t *old_task = TASK;
393 as_t *old_as = AS;
394
395 ASSERT((!THREAD) || (irq_spinlock_locked(&THREAD->lock)));
396 ASSERT(CPU != NULL);
397
398 /*
399 * Hold the current task and the address space to prevent their
400 * possible destruction should thread_destroy() be called on this or any
401 * other processor while the scheduler is still using them.
402 */
403 if (old_task)
404 task_hold(old_task);
405
406 if (old_as)
407 as_hold(old_as);
408
409 if (THREAD) {
410 /* Must be run after the switch to scheduler stack */
411 after_thread_ran();
412
413 switch (THREAD->state) {
414 case Running:
415 irq_spinlock_unlock(&THREAD->lock, false);
416 thread_ready(THREAD);
417 break;
418
419 case Exiting:
420repeat:
421 if (THREAD->detached) {
422 thread_destroy(THREAD, false);
423 } else {
424 /*
425 * The thread structure is kept allocated until
426 * somebody calls thread_detach() on it.
427 */
428 if (!irq_spinlock_trylock(&THREAD->join_wq.lock)) {
429 /*
430 * Avoid deadlock.
431 */
432 irq_spinlock_unlock(&THREAD->lock, false);
433 delay(HZ);
434 irq_spinlock_lock(&THREAD->lock, false);
435 DEADLOCK_PROBE(p_joinwq,
436 DEADLOCK_THRESHOLD);
437 goto repeat;
438 }
439 _waitq_wakeup_unsafe(&THREAD->join_wq,
440 WAKEUP_FIRST);
441 irq_spinlock_unlock(&THREAD->join_wq.lock, false);
442
443 THREAD->state = Lingering;
444 irq_spinlock_unlock(&THREAD->lock, false);
445 }
446 break;
447
448 case Sleeping:
449 /*
450 * Prefer the thread after it's woken up.
451 */
452 THREAD->priority = -1;
453
454 /*
455 * We need to release wq->lock which we locked in
456 * waitq_sleep(). Address of wq->lock is kept in
457 * THREAD->sleep_queue.
458 */
459 irq_spinlock_unlock(&THREAD->sleep_queue->lock, false);
460
461 irq_spinlock_unlock(&THREAD->lock, false);
462 break;
463
464 default:
465 /*
466 * Entering state is unexpected.
467 */
468 panic("tid%" PRIu64 ": unexpected state %s.",
469 THREAD->tid, thread_states[THREAD->state]);
470 break;
471 }
472
473 THREAD = NULL;
474 }
475
476 THREAD = find_best_thread();
477
478 irq_spinlock_lock(&THREAD->lock, false);
479 int priority = THREAD->priority;
480 irq_spinlock_unlock(&THREAD->lock, false);
481
482 relink_rq(priority);
483
484 /*
485 * If both the old and the new task are the same,
486 * lots of work is avoided.
487 */
488 if (TASK != THREAD->task) {
489 as_t *new_as = THREAD->task->as;
490
491 /*
492 * Note that it is possible for two tasks
493 * to share one address space.
494 */
495 if (old_as != new_as) {
496 /*
497 * Both tasks and address spaces are different.
498 * Replace the old one with the new one.
499 */
500 as_switch(old_as, new_as);
501 }
502
503 TASK = THREAD->task;
504 before_task_runs();
505 }
506
507 if (old_task)
508 task_release(old_task);
509
510 if (old_as)
511 as_release(old_as);
512
513 irq_spinlock_lock(&THREAD->lock, false);
514 THREAD->state = Running;
515
516#ifdef SCHEDULER_VERBOSE
517 printf("cpu%u: tid %" PRIu64 " (priority=%d, ticks=%" PRIu64
518 ", nrdy=%ld)\n", CPU->id, THREAD->tid, THREAD->priority,
519 THREAD->ticks, atomic_get(&CPU->nrdy));
520#endif
521
522 /*
523 * Some architectures provide late kernel PA2KA(identity)
524 * mapping in a page fault handler. However, the page fault
525 * handler uses the kernel stack of the running thread and
526 * therefore cannot be used to map it. The kernel stack, if
527 * necessary, is to be mapped in before_thread_runs(). This
528 * function must be executed before the switch to the new stack.
529 */
530 before_thread_runs();
531
532 /*
533 * Copy the knowledge of CPU, TASK, THREAD and preemption counter to
534 * thread's stack.
535 */
536 the_copy(THE, (the_t *) THREAD->kstack);
537
538 context_restore(&THREAD->saved_context);
539
540 /* Not reached */
541}
542
543#ifdef CONFIG_SMP
544/** Load balancing thread
545 *
546 * SMP load balancing thread, supervising thread supplies
547 * for the CPU it's wired to.
548 *
549 * @param arg Generic thread argument (unused).
550 *
551 */
552void kcpulb(void *arg)
553{
554 atomic_count_t average;
555 atomic_count_t rdy;
556
557 /*
558 * Detach kcpulb as nobody will call thread_join_timeout() on it.
559 */
560 thread_detach(THREAD);
561
562loop:
563 /*
564 * Work in 1s intervals.
565 */
566 thread_sleep(1);
567
568not_satisfied:
569 /*
570 * Calculate the number of threads that will be migrated/stolen from
571 * other CPU's. Note that situation can have changed between two
572 * passes. Each time get the most up to date counts.
573 *
574 */
575 average = atomic_get(&nrdy) / config.cpu_active + 1;
576 rdy = atomic_get(&CPU->nrdy);
577
578 if (average <= rdy)
579 goto satisfied;
580
581 atomic_count_t count = average - rdy;
582
583 /*
584 * Searching least priority queues on all CPU's first and most priority
585 * queues on all CPU's last.
586 *
587 */
588 size_t acpu;
589 size_t acpu_bias = 0;
590 int rq;
591
592 for (rq = RQ_COUNT - 1; rq >= 0; rq--) {
593 for (acpu = 0; acpu < config.cpu_active; acpu++) {
594 cpu_t *cpu = &cpus[(acpu + acpu_bias) % config.cpu_active];
595
596 /*
597 * Not interested in ourselves.
598 * Doesn't require interrupt disabling for kcpulb has
599 * THREAD_FLAG_WIRED.
600 *
601 */
602 if (CPU == cpu)
603 continue;
604
605 if (atomic_get(&cpu->nrdy) <= average)
606 continue;
607
608 irq_spinlock_lock(&(cpu->rq[rq].lock), true);
609 if (cpu->rq[rq].n == 0) {
610 irq_spinlock_unlock(&(cpu->rq[rq].lock), true);
611 continue;
612 }
613
614 thread_t *thread = NULL;
615
616 /* Search rq from the back */
617 link_t *link = cpu->rq[rq].rq_head.prev;
618
619 while (link != &(cpu->rq[rq].rq_head)) {
620 thread = (thread_t *) list_get_instance(link, thread_t, rq_link);
621
622 /*
623 * We don't want to steal CPU-wired threads
624 * neither threads already stolen. The latter
625 * prevents threads from migrating between CPU's
626 * without ever being run. We don't want to
627 * steal threads whose FPU context is still in
628 * CPU.
629 *
630 */
631 irq_spinlock_lock(&thread->lock, false);
632
633 if ((!(thread->flags & (THREAD_FLAG_WIRED | THREAD_FLAG_STOLEN)))
634 && (!(thread->fpu_context_engaged))) {
635 /*
636 * Remove thread from ready queue.
637 */
638 irq_spinlock_unlock(&thread->lock, false);
639
640 atomic_dec(&cpu->nrdy);
641 atomic_dec(&nrdy);
642
643 cpu->rq[rq].n--;
644 list_remove(&thread->rq_link);
645
646 break;
647 }
648
649 irq_spinlock_unlock(&thread->lock, false);
650
651 link = link->prev;
652 thread = NULL;
653 }
654
655 if (thread) {
656 /*
657 * Ready thread on local CPU
658 */
659
660 irq_spinlock_pass(&(cpu->rq[rq].lock), &thread->lock);
661
662#ifdef KCPULB_VERBOSE
663 printf("kcpulb%u: TID %" PRIu64 " -> cpu%u, "
664 "nrdy=%ld, avg=%ld\n", CPU->id, t->tid,
665 CPU->id, atomic_get(&CPU->nrdy),
666 atomic_get(&nrdy) / config.cpu_active);
667#endif
668
669 thread->flags |= THREAD_FLAG_STOLEN;
670 thread->state = Entering;
671
672 irq_spinlock_unlock(&thread->lock, true);
673 thread_ready(thread);
674
675 if (--count == 0)
676 goto satisfied;
677
678 /*
679 * We are not satisfied yet, focus on another
680 * CPU next time.
681 *
682 */
683 acpu_bias++;
684
685 continue;
686 } else
687 irq_spinlock_unlock(&(cpu->rq[rq].lock), true);
688
689 }
690 }
691
692 if (atomic_get(&CPU->nrdy)) {
693 /*
694 * Be a little bit light-weight and let migrated threads run.
695 *
696 */
697 scheduler();
698 } else {
699 /*
700 * We failed to migrate a single thread.
701 * Give up this turn.
702 *
703 */
704 goto loop;
705 }
706
707 goto not_satisfied;
708
709satisfied:
710 goto loop;
711}
712#endif /* CONFIG_SMP */
713
714/** Print information about threads & scheduler queues
715 *
716 */
717void sched_print_list(void)
718{
719 size_t cpu;
720 for (cpu = 0; cpu < config.cpu_count; cpu++) {
721 if (!cpus[cpu].active)
722 continue;
723
724 irq_spinlock_lock(&cpus[cpu].lock, true);
725
726 printf("cpu%u: address=%p, nrdy=%" PRIua ", needs_relink=%zu\n",
727 cpus[cpu].id, &cpus[cpu], atomic_get(&cpus[cpu].nrdy),
728 cpus[cpu].needs_relink);
729
730 unsigned int i;
731 for (i = 0; i < RQ_COUNT; i++) {
732 irq_spinlock_lock(&(cpus[cpu].rq[i].lock), false);
733 if (cpus[cpu].rq[i].n == 0) {
734 irq_spinlock_unlock(&(cpus[cpu].rq[i].lock), false);
735 continue;
736 }
737
738 printf("\trq[%u]: ", i);
739 link_t *cur;
740 for (cur = cpus[cpu].rq[i].rq_head.next;
741 cur != &(cpus[cpu].rq[i].rq_head);
742 cur = cur->next) {
743 thread_t *thread = list_get_instance(cur, thread_t, rq_link);
744 printf("%" PRIu64 "(%s) ", thread->tid,
745 thread_states[thread->state]);
746 }
747 printf("\n");
748
749 irq_spinlock_unlock(&(cpus[cpu].rq[i].lock), false);
750 }
751
752 irq_spinlock_unlock(&cpus[cpu].lock, true);
753 }
754}
755
756/** @}
757 */
Note: See TracBrowser for help on using the repository browser.