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

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

Always allocate FPU context ahead of time, even when switching is lazy

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