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

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

Split find_best_thread() into two functions

try_find_thread() attempts to get a thread from runqueues and returns
NULL when there's none available. find_best_thread() functions as
before and goes to sleep between attempts to find a thread to run.

The purpose of this split is that we can use the non-sleeping version
in the context of a previously running thread to avoid an additional
context switch in case new thread is immediately available.

  • Property mode set to 100644
File size: 16.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 kernel_generic_proc
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 <config.h>
57#include <context.h>
58#include <fpu_context.h>
59#include <halt.h>
60#include <arch.h>
61#include <adt/list.h>
62#include <panic.h>
63#include <cpu.h>
64#include <stdio.h>
65#include <log.h>
66#include <stacktrace.h>
67
68static void scheduler_separated_stack(void);
69
70atomic_size_t nrdy; /**< Number of ready threads in the system. */
71
72/** Take actions before new thread runs.
73 *
74 * Perform actions that need to be
75 * taken before the newly selected
76 * thread is passed control.
77 *
78 * THREAD->lock is locked on entry
79 *
80 */
81static void before_thread_runs(void)
82{
83 before_thread_runs_arch();
84
85#ifdef CONFIG_FPU_LAZY
86 /*
87 * The only concurrent modification possible for fpu_owner here is
88 * another thread changing it from itself to NULL in its destructor.
89 */
90 thread_t *owner = atomic_load_explicit(&CPU->fpu_owner,
91 memory_order_relaxed);
92
93 if (THREAD == owner)
94 fpu_enable();
95 else
96 fpu_disable();
97#elif defined CONFIG_FPU
98 fpu_enable();
99 if (THREAD->fpu_context_exists)
100 fpu_context_restore(&THREAD->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 after_thread_ran_arch();
132}
133
134#ifdef CONFIG_FPU_LAZY
135void scheduler_fpu_lazy_request(void)
136{
137 fpu_enable();
138
139 /* We need this lock to ensure synchronization with thread destructor. */
140 irq_spinlock_lock(&CPU->fpu_lock, false);
141
142 /* Save old context */
143 thread_t *owner = atomic_load_explicit(&CPU->fpu_owner, memory_order_relaxed);
144 if (owner != NULL) {
145 fpu_context_save(&owner->fpu_context);
146 atomic_store_explicit(&CPU->fpu_owner, NULL, memory_order_relaxed);
147 }
148
149 irq_spinlock_unlock(&CPU->fpu_lock, false);
150
151 if (THREAD->fpu_context_exists) {
152 fpu_context_restore(&THREAD->fpu_context);
153 } else {
154 fpu_init();
155 THREAD->fpu_context_exists = true;
156 }
157
158 atomic_store_explicit(&CPU->fpu_owner, THREAD, memory_order_relaxed);
159}
160#endif /* CONFIG_FPU_LAZY */
161
162/** Initialize scheduler
163 *
164 * Initialize kernel scheduler.
165 *
166 */
167void scheduler_init(void)
168{
169}
170
171/** Get thread to be scheduled
172 *
173 * Get the optimal thread to be scheduled
174 * according to thread accounting and scheduler
175 * policy.
176 *
177 * @return Thread to be scheduled.
178 *
179 */
180static thread_t *try_find_thread(int *rq_index)
181{
182 assert(interrupts_disabled());
183 assert(CPU != NULL);
184
185 if (atomic_load(&CPU->nrdy) == 0)
186 return NULL;
187
188 for (int i = 0; i < RQ_COUNT; i++) {
189 irq_spinlock_lock(&(CPU->rq[i].lock), false);
190 if (CPU->rq[i].n == 0) {
191 /*
192 * If this queue is empty, try a lower-priority queue.
193 */
194 irq_spinlock_unlock(&(CPU->rq[i].lock), false);
195 continue;
196 }
197
198 atomic_dec(&CPU->nrdy);
199 atomic_dec(&nrdy);
200 CPU->rq[i].n--;
201
202 /*
203 * Take the first thread from the queue.
204 */
205 thread_t *thread = list_get_instance(
206 list_first(&CPU->rq[i].rq), thread_t, rq_link);
207 list_remove(&thread->rq_link);
208
209 irq_spinlock_pass(&(CPU->rq[i].lock), &thread->lock);
210
211 thread->cpu = CPU;
212 thread->priority = i; /* Correct rq index */
213
214 /* Time allocation in microseconds. */
215 uint64_t time_to_run = (i + 1) * 10000;
216
217 /* This is safe because interrupts are disabled. */
218 CPU->preempt_deadline = CPU->current_clock_tick + us2ticks(time_to_run);
219
220 /*
221 * Clear the stolen flag so that it can be migrated
222 * when load balancing needs emerge.
223 */
224 thread->stolen = false;
225 irq_spinlock_unlock(&thread->lock, false);
226
227 *rq_index = i;
228 return thread;
229 }
230
231 return NULL;
232}
233
234/** Get thread to be scheduled
235 *
236 * Get the optimal thread to be scheduled
237 * according to thread accounting and scheduler
238 * policy.
239 *
240 * @return Thread to be scheduled.
241 *
242 */
243static thread_t *find_best_thread(int *rq_index)
244{
245 assert(interrupts_disabled());
246 assert(CPU != NULL);
247
248 while (true) {
249 thread_t *thread = try_find_thread(rq_index);
250
251 if (thread != NULL)
252 return thread;
253
254 /*
255 * For there was nothing to run, the CPU goes to sleep
256 * until a hardware interrupt or an IPI comes.
257 * This improves energy saving and hyperthreading.
258 */
259 CPU->idle = true;
260
261 /*
262 * Go to sleep with interrupts enabled.
263 * Ideally, this should be atomic, but this is not guaranteed on
264 * all platforms yet, so it is possible we will go sleep when
265 * a thread has just become available.
266 */
267 cpu_interruptible_sleep();
268 }
269}
270
271static void switch_task(task_t *task)
272{
273 /* If the task stays the same, a lot of work is avoided. */
274 if (TASK == task)
275 return;
276
277 as_t *old_as = AS;
278 as_t *new_as = task->as;
279
280 /* It is possible for two tasks to share one address space. */
281 if (old_as != new_as)
282 as_switch(old_as, new_as);
283
284 if (TASK)
285 task_release(TASK);
286
287 TASK = task;
288
289 task_hold(TASK);
290
291 before_task_runs_arch();
292}
293
294/** Prevent rq starvation
295 *
296 * Prevent low priority threads from starving in rq's.
297 *
298 * When the function decides to relink rq's, it reconnects
299 * respective pointers so that in result threads with 'pri'
300 * greater or equal start are moved to a higher-priority queue.
301 *
302 * @param start Threshold priority.
303 *
304 */
305static void relink_rq(int start)
306{
307 if (CPU->current_clock_tick < CPU->relink_deadline)
308 return;
309
310 CPU->relink_deadline = CPU->current_clock_tick + NEEDS_RELINK_MAX;
311
312 /* Temporary cache for lists we are moving. */
313 list_t list;
314 list_initialize(&list);
315
316 size_t n = 0;
317
318 /* Move every list (except the one with highest priority) one level up. */
319 for (int i = RQ_COUNT - 1; i > start; i--) {
320 irq_spinlock_lock(&CPU->rq[i].lock, false);
321
322 /* Swap lists. */
323 list_swap(&CPU->rq[i].rq, &list);
324
325 /* Swap number of items. */
326 size_t tmpn = CPU->rq[i].n;
327 CPU->rq[i].n = n;
328 n = tmpn;
329
330 irq_spinlock_unlock(&CPU->rq[i].lock, false);
331 }
332
333 /* Append the contents of rq[start + 1] to rq[start]. */
334 if (n != 0) {
335 irq_spinlock_lock(&CPU->rq[start].lock, false);
336 list_concat(&CPU->rq[start].rq, &list);
337 CPU->rq[start].n += n;
338 irq_spinlock_unlock(&CPU->rq[start].lock, false);
339 }
340}
341
342void scheduler(void)
343{
344 ipl_t ipl = interrupts_disable();
345
346 if (atomic_load(&haltstate))
347 halt();
348
349 if (THREAD) {
350 irq_spinlock_lock(&THREAD->lock, false);
351 }
352
353 scheduler_locked(ipl);
354}
355
356/** The scheduler
357 *
358 * The thread scheduling procedure.
359 * Passes control directly to
360 * scheduler_separated_stack().
361 *
362 */
363void scheduler_locked(ipl_t ipl)
364{
365 assert(CPU != NULL);
366
367 if (THREAD) {
368 /* Update thread kernel accounting */
369 THREAD->kcycles += get_cycle() - THREAD->last_cycle;
370
371#if (defined CONFIG_FPU) && (!defined CONFIG_FPU_LAZY)
372 fpu_context_save(&THREAD->fpu_context);
373#endif
374 if (!context_save(&THREAD->saved_context)) {
375 /*
376 * This is the place where threads leave scheduler();
377 */
378
379 /* Save current CPU cycle */
380 THREAD->last_cycle = get_cycle();
381
382 irq_spinlock_unlock(&THREAD->lock, false);
383 interrupts_restore(THREAD->saved_ipl);
384
385 return;
386 }
387
388 /*
389 * Interrupt priority level of preempted thread is recorded
390 * here to facilitate scheduler() invocations from
391 * interrupts_disable()'d code (e.g. waitq_sleep_timeout()).
392 *
393 */
394 THREAD->saved_ipl = ipl;
395 }
396
397 /*
398 * Through the 'CURRENT' structure, we keep track of THREAD, TASK, CPU, AS
399 * and preemption counter. At this point CURRENT could be coming either
400 * from THREAD's or CPU's stack.
401 *
402 */
403 current_copy(CURRENT, (current_t *) CPU->stack);
404
405 /*
406 * We may not keep the old stack.
407 * Reason: If we kept the old stack and got blocked, for instance, in
408 * find_best_thread(), the old thread could get rescheduled by another
409 * CPU and overwrite the part of its own stack that was also used by
410 * the scheduler on this CPU.
411 *
412 * Moreover, we have to bypass the compiler-generated POP sequence
413 * which is fooled by SP being set to the very top of the stack.
414 * Therefore the scheduler() function continues in
415 * scheduler_separated_stack().
416 *
417 */
418 context_t ctx;
419 context_save(&ctx);
420 context_set(&ctx, FADDR(scheduler_separated_stack),
421 (uintptr_t) CPU->stack, STACK_SIZE);
422 context_restore(&ctx);
423
424 /* Not reached */
425}
426
427/** Scheduler stack switch wrapper
428 *
429 * Second part of the scheduler() function
430 * using new stack. Handling the actual context
431 * switch to a new thread.
432 *
433 */
434void scheduler_separated_stack(void)
435{
436 assert((!THREAD) || (irq_spinlock_locked(&THREAD->lock)));
437 assert(CPU != NULL);
438 assert(interrupts_disabled());
439
440 if (THREAD) {
441 /* Must be run after the switch to scheduler stack */
442 after_thread_ran();
443
444 switch (THREAD->state) {
445 case Running:
446 irq_spinlock_unlock(&THREAD->lock, false);
447 thread_ready(THREAD);
448 break;
449
450 case Exiting:
451 irq_spinlock_unlock(&THREAD->lock, false);
452 waitq_close(&THREAD->join_wq);
453
454 /*
455 * Release the reference CPU has for the thread.
456 * If there are no other references (e.g. threads calling join),
457 * the thread structure is deallocated.
458 */
459 thread_put(THREAD);
460 break;
461
462 case Sleeping:
463 /*
464 * Prefer the thread after it's woken up.
465 */
466 THREAD->priority = -1;
467 irq_spinlock_unlock(&THREAD->lock, false);
468 break;
469
470 default:
471 /*
472 * Entering state is unexpected.
473 */
474 panic("tid%" PRIu64 ": unexpected state %s.",
475 THREAD->tid, thread_states[THREAD->state]);
476 break;
477 }
478
479 THREAD = NULL;
480 }
481
482 int rq_index;
483 THREAD = find_best_thread(&rq_index);
484
485 relink_rq(rq_index);
486
487 switch_task(THREAD->task);
488
489 irq_spinlock_lock(&THREAD->lock, false);
490 THREAD->state = Running;
491
492#ifdef SCHEDULER_VERBOSE
493 log(LF_OTHER, LVL_DEBUG,
494 "cpu%u: tid %" PRIu64 " (priority=%d, ticks=%" PRIu64
495 ", nrdy=%zu)", CPU->id, THREAD->tid, THREAD->priority,
496 THREAD->ticks, atomic_load(&CPU->nrdy));
497#endif
498
499 /*
500 * Some architectures provide late kernel PA2KA(identity)
501 * mapping in a page fault handler. However, the page fault
502 * handler uses the kernel stack of the running thread and
503 * therefore cannot be used to map it. The kernel stack, if
504 * necessary, is to be mapped in before_thread_runs(). This
505 * function must be executed before the switch to the new stack.
506 */
507 before_thread_runs();
508
509 /*
510 * Copy the knowledge of CPU, TASK, THREAD and preemption counter to
511 * thread's stack.
512 */
513 current_copy(CURRENT, (current_t *) THREAD->kstack);
514
515 context_restore(&THREAD->saved_context);
516
517 /* Not reached */
518}
519
520#ifdef CONFIG_SMP
521
522static thread_t *steal_thread_from(cpu_t *old_cpu, int i)
523{
524 runq_t *old_rq = &old_cpu->rq[i];
525 runq_t *new_rq = &CPU->rq[i];
526
527 ipl_t ipl = interrupts_disable();
528
529 irq_spinlock_lock(&old_rq->lock, false);
530
531 /*
532 * If fpu_owner is any thread in the list, its store is seen here thanks to
533 * the runqueue lock.
534 */
535 thread_t *fpu_owner = atomic_load_explicit(&old_cpu->fpu_owner,
536 memory_order_relaxed);
537
538 /* Search rq from the back */
539 list_foreach_rev(old_rq->rq, rq_link, thread_t, thread) {
540
541 irq_spinlock_lock(&thread->lock, false);
542
543 /*
544 * Do not steal CPU-wired threads, threads
545 * already stolen, threads for which migration
546 * was temporarily disabled or threads whose
547 * FPU context is still in the CPU.
548 */
549 if (thread->stolen || thread->nomigrate ||
550 thread == fpu_owner) {
551 irq_spinlock_unlock(&thread->lock, false);
552 continue;
553 }
554
555 thread->stolen = true;
556 thread->cpu = CPU;
557
558 irq_spinlock_unlock(&thread->lock, false);
559
560 /*
561 * Ready thread on local CPU
562 */
563
564#ifdef KCPULB_VERBOSE
565 log(LF_OTHER, LVL_DEBUG,
566 "kcpulb%u: TID %" PRIu64 " -> cpu%u, "
567 "nrdy=%ld, avg=%ld", CPU->id, thread->tid,
568 CPU->id, atomic_load(&CPU->nrdy),
569 atomic_load(&nrdy) / config.cpu_active);
570#endif
571
572 /* Remove thread from ready queue. */
573 old_rq->n--;
574 list_remove(&thread->rq_link);
575 irq_spinlock_unlock(&old_rq->lock, false);
576
577 /* Append thread to local queue. */
578 irq_spinlock_lock(&new_rq->lock, false);
579 list_append(&thread->rq_link, &new_rq->rq);
580 new_rq->n++;
581 irq_spinlock_unlock(&new_rq->lock, false);
582
583 atomic_dec(&old_cpu->nrdy);
584 atomic_inc(&CPU->nrdy);
585 interrupts_restore(ipl);
586 return thread;
587 }
588
589 irq_spinlock_unlock(&old_rq->lock, false);
590 interrupts_restore(ipl);
591 return NULL;
592}
593
594/** Load balancing thread
595 *
596 * SMP load balancing thread, supervising thread supplies
597 * for the CPU it's wired to.
598 *
599 * @param arg Generic thread argument (unused).
600 *
601 */
602void kcpulb(void *arg)
603{
604 size_t average;
605 size_t rdy;
606
607loop:
608 /*
609 * Work in 1s intervals.
610 */
611 thread_sleep(1);
612
613not_satisfied:
614 /*
615 * Calculate the number of threads that will be migrated/stolen from
616 * other CPU's. Note that situation can have changed between two
617 * passes. Each time get the most up to date counts.
618 *
619 */
620 average = atomic_load(&nrdy) / config.cpu_active + 1;
621 rdy = atomic_load(&CPU->nrdy);
622
623 if (average <= rdy)
624 goto satisfied;
625
626 size_t count = average - rdy;
627
628 /*
629 * Searching least priority queues on all CPU's first and most priority
630 * queues on all CPU's last.
631 */
632 size_t acpu;
633 int rq;
634
635 for (rq = RQ_COUNT - 1; rq >= 0; rq--) {
636 for (acpu = 0; acpu < config.cpu_active; acpu++) {
637 cpu_t *cpu = &cpus[acpu];
638
639 /*
640 * Not interested in ourselves.
641 * Doesn't require interrupt disabling for kcpulb has
642 * THREAD_FLAG_WIRED.
643 *
644 */
645 if (CPU == cpu)
646 continue;
647
648 if (atomic_load(&cpu->nrdy) <= average)
649 continue;
650
651 if (steal_thread_from(cpu, rq) && --count == 0)
652 goto satisfied;
653 }
654 }
655
656 if (atomic_load(&CPU->nrdy)) {
657 /*
658 * Be a little bit light-weight and let migrated threads run.
659 *
660 */
661 scheduler();
662 } else {
663 /*
664 * We failed to migrate a single thread.
665 * Give up this turn.
666 *
667 */
668 goto loop;
669 }
670
671 goto not_satisfied;
672
673satisfied:
674 goto loop;
675}
676#endif /* CONFIG_SMP */
677
678/** Print information about threads & scheduler queues
679 *
680 */
681void sched_print_list(void)
682{
683 size_t cpu;
684 for (cpu = 0; cpu < config.cpu_count; cpu++) {
685 if (!cpus[cpu].active)
686 continue;
687
688 /* Technically a data race, but we don't really care in this case. */
689 int needs_relink = cpus[cpu].relink_deadline - cpus[cpu].current_clock_tick;
690
691 printf("cpu%u: address=%p, nrdy=%zu, needs_relink=%d\n",
692 cpus[cpu].id, &cpus[cpu], atomic_load(&cpus[cpu].nrdy),
693 needs_relink);
694
695 unsigned int i;
696 for (i = 0; i < RQ_COUNT; i++) {
697 irq_spinlock_lock(&(cpus[cpu].rq[i].lock), false);
698 if (cpus[cpu].rq[i].n == 0) {
699 irq_spinlock_unlock(&(cpus[cpu].rq[i].lock), false);
700 continue;
701 }
702
703 printf("\trq[%u]: ", i);
704 list_foreach(cpus[cpu].rq[i].rq, rq_link, thread_t,
705 thread) {
706 printf("%" PRIu64 "(%s) ", thread->tid,
707 thread_states[thread->state]);
708 }
709 printf("\n");
710
711 irq_spinlock_unlock(&(cpus[cpu].rq[i].lock), false);
712 }
713 }
714}
715
716/** @}
717 */
Note: See TracBrowser for help on using the repository browser.