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

Last change on this file since bb65ccb3 was c680333, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 3 years ago

Move task switch handling into a separate function

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