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

Last change on this file since 8996582 was 8996582, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 18 months ago

Move context switch preparation to a new separate function

This puts everything that's needed before activating a new
thread into a single place, and removes one lock/unlock pair.

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