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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 077842c was 077842c, checked in by Jiří Zárevúcky <jiri.zarevucky@…>, 7 years ago

Convert atomic_t to atomic_size_t (1): remove PRIua macro

  • Property mode set to 100644
File size: 17.5 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 <assert.h>
42#include <atomic.h>
43#include <proc/scheduler.h>
44#include <proc/thread.h>
45#include <proc/task.h>
46#include <mm/frame.h>
47#include <mm/page.h>
48#include <mm/as.h>
49#include <time/timeout.h>
50#include <time/delay.h>
51#include <arch/asm.h>
52#include <arch/faddr.h>
53#include <arch/cycle.h>
54#include <atomic.h>
55#include <synch/spinlock.h>
56#include <synch/workqueue.h>
57#include <synch/rcu.h>
58#include <config.h>
59#include <context.h>
60#include <fpu_context.h>
61#include <halt.h>
62#include <arch.h>
63#include <adt/list.h>
64#include <panic.h>
65#include <cpu.h>
66#include <print.h>
67#include <log.h>
68#include <stacktrace.h>
69
70static void scheduler_separated_stack(void);
71
72atomic_t nrdy; /**< Number of ready threads in the system. */
73
74/** Carry out actions before new task runs. */
75static void before_task_runs(void)
76{
77 before_task_runs_arch();
78}
79
80/** Take actions before new thread runs.
81 *
82 * Perform actions that need to be
83 * taken before the newly selected
84 * thread is passed control.
85 *
86 * THREAD->lock is locked on entry
87 *
88 */
89static void before_thread_runs(void)
90{
91 before_thread_runs_arch();
92 rcu_before_thread_runs();
93
94#ifdef CONFIG_FPU_LAZY
95 if (THREAD == CPU->fpu_owner)
96 fpu_enable();
97 else
98 fpu_disable();
99#elif defined CONFIG_FPU
100 fpu_enable();
101 if (THREAD->fpu_context_exists)
102 fpu_context_restore(THREAD->saved_fpu_context);
103 else {
104 fpu_init();
105 THREAD->fpu_context_exists = true;
106 }
107#endif
108
109#ifdef CONFIG_UDEBUG
110 if (THREAD->btrace) {
111 istate_t *istate = THREAD->udebug.uspace_state;
112 if (istate != NULL) {
113 printf("Thread %" PRIu64 " stack trace:\n", THREAD->tid);
114 stack_trace_istate(istate);
115 }
116
117 THREAD->btrace = false;
118 }
119#endif
120}
121
122/** Take actions after THREAD had run.
123 *
124 * Perform actions that need to be
125 * taken after the running thread
126 * had been preempted by the scheduler.
127 *
128 * THREAD->lock is locked on entry
129 *
130 */
131static void after_thread_ran(void)
132{
133 workq_after_thread_ran();
134 rcu_after_thread_ran();
135 after_thread_ran_arch();
136}
137
138#ifdef CONFIG_FPU_LAZY
139void scheduler_fpu_lazy_request(void)
140{
141restart:
142 fpu_enable();
143 irq_spinlock_lock(&CPU->lock, false);
144
145 /* Save old context */
146 if (CPU->fpu_owner != NULL) {
147 irq_spinlock_lock(&CPU->fpu_owner->lock, false);
148 fpu_context_save(CPU->fpu_owner->saved_fpu_context);
149
150 /* Don't prevent migration */
151 CPU->fpu_owner->fpu_context_engaged = false;
152 irq_spinlock_unlock(&CPU->fpu_owner->lock, false);
153 CPU->fpu_owner = NULL;
154 }
155
156 irq_spinlock_lock(&THREAD->lock, false);
157 if (THREAD->fpu_context_exists) {
158 fpu_context_restore(THREAD->saved_fpu_context);
159 } else {
160 /* Allocate FPU context */
161 if (!THREAD->saved_fpu_context) {
162 /* Might sleep */
163 irq_spinlock_unlock(&THREAD->lock, false);
164 irq_spinlock_unlock(&CPU->lock, false);
165 THREAD->saved_fpu_context =
166 (fpu_context_t *) slab_alloc(fpu_context_cache, 0);
167
168 /* We may have switched CPUs during slab_alloc */
169 goto restart;
170 }
171 fpu_init();
172 THREAD->fpu_context_exists = true;
173 }
174
175 CPU->fpu_owner = THREAD;
176 THREAD->fpu_context_engaged = true;
177 irq_spinlock_unlock(&THREAD->lock, false);
178
179 irq_spinlock_unlock(&CPU->lock, false);
180}
181#endif /* CONFIG_FPU_LAZY */
182
183/** Initialize scheduler
184 *
185 * Initialize kernel scheduler.
186 *
187 */
188void scheduler_init(void)
189{
190}
191
192/** Get thread to be scheduled
193 *
194 * Get the optimal thread to be scheduled
195 * according to thread accounting and scheduler
196 * policy.
197 *
198 * @return Thread to be scheduled.
199 *
200 */
201static thread_t *find_best_thread(void)
202{
203 assert(CPU != NULL);
204
205loop:
206
207 if (atomic_get(&CPU->nrdy) == 0) {
208 /*
209 * For there was nothing to run, the CPU goes to sleep
210 * until a hardware interrupt or an IPI comes.
211 * This improves energy saving and hyperthreading.
212 */
213 irq_spinlock_lock(&CPU->lock, false);
214 CPU->idle = true;
215 irq_spinlock_unlock(&CPU->lock, false);
216 interrupts_enable();
217
218 /*
219 * An interrupt might occur right now and wake up a thread.
220 * In such case, the CPU will continue to go to sleep
221 * even though there is a runnable thread.
222 */
223 cpu_sleep();
224 interrupts_disable();
225 goto loop;
226 }
227
228 assert(!CPU->idle);
229
230 unsigned int i;
231 for (i = 0; i < RQ_COUNT; i++) {
232 irq_spinlock_lock(&(CPU->rq[i].lock), false);
233 if (CPU->rq[i].n == 0) {
234 /*
235 * If this queue is empty, try a lower-priority queue.
236 */
237 irq_spinlock_unlock(&(CPU->rq[i].lock), false);
238 continue;
239 }
240
241 atomic_dec(&CPU->nrdy);
242 atomic_dec(&nrdy);
243 CPU->rq[i].n--;
244
245 /*
246 * Take the first thread from the queue.
247 */
248 thread_t *thread = list_get_instance(
249 list_first(&CPU->rq[i].rq), thread_t, rq_link);
250 list_remove(&thread->rq_link);
251
252 irq_spinlock_pass(&(CPU->rq[i].lock), &thread->lock);
253
254 thread->cpu = CPU;
255 thread->ticks = us2ticks((i + 1) * 10000);
256 thread->priority = i; /* Correct rq index */
257
258 /*
259 * Clear the stolen flag so that it can be migrated
260 * when load balancing needs emerge.
261 */
262 thread->stolen = false;
263 irq_spinlock_unlock(&thread->lock, false);
264
265 return thread;
266 }
267
268 goto loop;
269}
270
271/** Prevent rq starvation
272 *
273 * Prevent low priority threads from starving in rq's.
274 *
275 * When the function decides to relink rq's, it reconnects
276 * respective pointers so that in result threads with 'pri'
277 * greater or equal start are moved to a higher-priority queue.
278 *
279 * @param start Threshold priority.
280 *
281 */
282static void relink_rq(int start)
283{
284 list_t list;
285
286 list_initialize(&list);
287 irq_spinlock_lock(&CPU->lock, false);
288
289 if (CPU->needs_relink > NEEDS_RELINK_MAX) {
290 int i;
291 for (i = start; i < RQ_COUNT - 1; i++) {
292 /* Remember and empty rq[i + 1] */
293
294 irq_spinlock_lock(&CPU->rq[i + 1].lock, false);
295 list_concat(&list, &CPU->rq[i + 1].rq);
296 size_t n = CPU->rq[i + 1].n;
297 CPU->rq[i + 1].n = 0;
298 irq_spinlock_unlock(&CPU->rq[i + 1].lock, false);
299
300 /* Append rq[i + 1] to rq[i] */
301
302 irq_spinlock_lock(&CPU->rq[i].lock, false);
303 list_concat(&CPU->rq[i].rq, &list);
304 CPU->rq[i].n += n;
305 irq_spinlock_unlock(&CPU->rq[i].lock, false);
306 }
307
308 CPU->needs_relink = 0;
309 }
310
311 irq_spinlock_unlock(&CPU->lock, false);
312}
313
314/** The scheduler
315 *
316 * The thread scheduling procedure.
317 * Passes control directly to
318 * scheduler_separated_stack().
319 *
320 */
321void scheduler(void)
322{
323 volatile ipl_t ipl;
324
325 assert(CPU != NULL);
326
327 ipl = interrupts_disable();
328
329 if (atomic_get(&haltstate))
330 halt();
331
332 if (THREAD) {
333 irq_spinlock_lock(&THREAD->lock, false);
334
335 /* Update thread kernel accounting */
336 THREAD->kcycles += get_cycle() - THREAD->last_cycle;
337
338#if (defined CONFIG_FPU) && (!defined CONFIG_FPU_LAZY)
339 fpu_context_save(THREAD->saved_fpu_context);
340#endif
341 if (!context_save(&THREAD->saved_context)) {
342 /*
343 * This is the place where threads leave scheduler();
344 */
345
346 /* Save current CPU cycle */
347 THREAD->last_cycle = get_cycle();
348
349 irq_spinlock_unlock(&THREAD->lock, false);
350 interrupts_restore(THREAD->saved_context.ipl);
351
352 return;
353 }
354
355 /*
356 * Interrupt priority level of preempted thread is recorded
357 * here to facilitate scheduler() invocations from
358 * interrupts_disable()'d code (e.g. waitq_sleep_timeout()).
359 *
360 */
361 THREAD->saved_context.ipl = ipl;
362 }
363
364 /*
365 * Through the 'THE' structure, we keep track of THREAD, TASK, CPU, AS
366 * and preemption counter. At this point THE could be coming either
367 * from THREAD's or CPU's stack.
368 *
369 */
370 the_copy(THE, (the_t *) CPU->stack);
371
372 /*
373 * We may not keep the old stack.
374 * Reason: If we kept the old stack and got blocked, for instance, in
375 * find_best_thread(), the old thread could get rescheduled by another
376 * CPU and overwrite the part of its own stack that was also used by
377 * the scheduler on this CPU.
378 *
379 * Moreover, we have to bypass the compiler-generated POP sequence
380 * which is fooled by SP being set to the very top of the stack.
381 * Therefore the scheduler() function continues in
382 * scheduler_separated_stack().
383 *
384 */
385 context_save(&CPU->saved_context);
386 context_set(&CPU->saved_context, FADDR(scheduler_separated_stack),
387 (uintptr_t) CPU->stack, STACK_SIZE);
388 context_restore(&CPU->saved_context);
389
390 /* Not reached */
391}
392
393/** Scheduler stack switch wrapper
394 *
395 * Second part of the scheduler() function
396 * using new stack. Handling the actual context
397 * switch to a new thread.
398 *
399 */
400void scheduler_separated_stack(void)
401{
402 DEADLOCK_PROBE_INIT(p_joinwq);
403 task_t *old_task = TASK;
404 as_t *old_as = AS;
405
406 assert((!THREAD) || (irq_spinlock_locked(&THREAD->lock)));
407 assert(CPU != NULL);
408 assert(interrupts_disabled());
409
410 /*
411 * Hold the current task and the address space to prevent their
412 * possible destruction should thread_destroy() be called on this or any
413 * other processor while the scheduler is still using them.
414 */
415 if (old_task)
416 task_hold(old_task);
417
418 if (old_as)
419 as_hold(old_as);
420
421 if (THREAD) {
422 /* Must be run after the switch to scheduler stack */
423 after_thread_ran();
424
425 switch (THREAD->state) {
426 case Running:
427 irq_spinlock_unlock(&THREAD->lock, false);
428 thread_ready(THREAD);
429 break;
430
431 case Exiting:
432 rcu_thread_exiting();
433 repeat:
434 if (THREAD->detached) {
435 thread_destroy(THREAD, false);
436 } else {
437 /*
438 * The thread structure is kept allocated until
439 * somebody calls thread_detach() on it.
440 */
441 if (!irq_spinlock_trylock(&THREAD->join_wq.lock)) {
442 /*
443 * Avoid deadlock.
444 */
445 irq_spinlock_unlock(&THREAD->lock, false);
446 delay(HZ);
447 irq_spinlock_lock(&THREAD->lock, false);
448 DEADLOCK_PROBE(p_joinwq,
449 DEADLOCK_THRESHOLD);
450 goto repeat;
451 }
452 _waitq_wakeup_unsafe(&THREAD->join_wq,
453 WAKEUP_FIRST);
454 irq_spinlock_unlock(&THREAD->join_wq.lock, false);
455
456 THREAD->state = Lingering;
457 irq_spinlock_unlock(&THREAD->lock, false);
458 }
459 break;
460
461 case Sleeping:
462 /*
463 * Prefer the thread after it's woken up.
464 */
465 THREAD->priority = -1;
466
467 /*
468 * We need to release wq->lock which we locked in
469 * waitq_sleep(). Address of wq->lock is kept in
470 * THREAD->sleep_queue.
471 */
472 irq_spinlock_unlock(&THREAD->sleep_queue->lock, false);
473
474 irq_spinlock_unlock(&THREAD->lock, false);
475 break;
476
477 default:
478 /*
479 * Entering state is unexpected.
480 */
481 panic("tid%" PRIu64 ": unexpected state %s.",
482 THREAD->tid, thread_states[THREAD->state]);
483 break;
484 }
485
486 THREAD = NULL;
487 }
488
489 THREAD = find_best_thread();
490
491 irq_spinlock_lock(&THREAD->lock, false);
492 int priority = THREAD->priority;
493 irq_spinlock_unlock(&THREAD->lock, false);
494
495 relink_rq(priority);
496
497 /*
498 * If both the old and the new task are the same,
499 * lots of work is avoided.
500 */
501 if (TASK != THREAD->task) {
502 as_t *new_as = THREAD->task->as;
503
504 /*
505 * Note that it is possible for two tasks
506 * to share one address space.
507 */
508 if (old_as != new_as) {
509 /*
510 * Both tasks and address spaces are different.
511 * Replace the old one with the new one.
512 */
513 as_switch(old_as, new_as);
514 }
515
516 TASK = THREAD->task;
517 before_task_runs();
518 }
519
520 if (old_task)
521 task_release(old_task);
522
523 if (old_as)
524 as_release(old_as);
525
526 irq_spinlock_lock(&THREAD->lock, false);
527 THREAD->state = Running;
528
529#ifdef SCHEDULER_VERBOSE
530 log(LF_OTHER, LVL_DEBUG,
531 "cpu%u: tid %" PRIu64 " (priority=%d, ticks=%" PRIu64
532 ", nrdy=%zu)", 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 log(LF_OTHER, LVL_DEBUG,
678 "kcpulb%u: TID %" PRIu64 " -> cpu%u, "
679 "nrdy=%ld, avg=%ld", CPU->id, t->tid,
680 CPU->id, atomic_get(&CPU->nrdy),
681 atomic_get(&nrdy) / config.cpu_active);
682#endif
683
684 thread->stolen = true;
685 thread->state = Entering;
686
687 irq_spinlock_unlock(&thread->lock, true);
688 thread_ready(thread);
689
690 if (--count == 0)
691 goto satisfied;
692
693 /*
694 * We are not satisfied yet, focus on another
695 * CPU next time.
696 *
697 */
698 acpu_bias++;
699
700 continue;
701 } else
702 irq_spinlock_unlock(&(cpu->rq[rq].lock), true);
703
704 }
705 }
706
707 if (atomic_get(&CPU->nrdy)) {
708 /*
709 * Be a little bit light-weight and let migrated threads run.
710 *
711 */
712 scheduler();
713 } else {
714 /*
715 * We failed to migrate a single thread.
716 * Give up this turn.
717 *
718 */
719 goto loop;
720 }
721
722 goto not_satisfied;
723
724satisfied:
725 goto loop;
726}
727#endif /* CONFIG_SMP */
728
729/** Print information about threads & scheduler queues
730 *
731 */
732void sched_print_list(void)
733{
734 size_t cpu;
735 for (cpu = 0; cpu < config.cpu_count; cpu++) {
736 if (!cpus[cpu].active)
737 continue;
738
739 irq_spinlock_lock(&cpus[cpu].lock, true);
740
741 printf("cpu%u: address=%p, nrdy=%zu, needs_relink=%zu\n",
742 cpus[cpu].id, &cpus[cpu], atomic_get(&cpus[cpu].nrdy),
743 cpus[cpu].needs_relink);
744
745 unsigned int i;
746 for (i = 0; i < RQ_COUNT; i++) {
747 irq_spinlock_lock(&(cpus[cpu].rq[i].lock), false);
748 if (cpus[cpu].rq[i].n == 0) {
749 irq_spinlock_unlock(&(cpus[cpu].rq[i].lock), false);
750 continue;
751 }
752
753 printf("\trq[%u]: ", i);
754 list_foreach(cpus[cpu].rq[i].rq, rq_link, thread_t,
755 thread) {
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.