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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 1066041 was 1066041, checked in by Adam Hraska <adam.hraska+hos@…>, 13 years ago

preemption_disable: Turned functions into macros. Moved THREAD, AS, TASK, CPU into thread.h, as.h, task.h, cpu.h to fix the include hell that ensued.

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