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

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

Wrap fpu handling code in named functions

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