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

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

rcu: Added preemptible RCU's core API implementation.

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