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

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

Replace CPU→needs_relink with CPU→relink_deadline

This removes a bit of unnecessary locking in clock().

  • Property mode set to 100644
File size: 17.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/** 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->priority = i; /* Correct rq index */
239
240 /* Time allocation in microseconds. */
241 uint64_t time_to_run = (i + 1) * 10000;
242
243 /* This is safe because interrupts are disabled. */
244 CPU->preempt_deadline = CPU->current_clock_tick + us2ticks(time_to_run);
245
246 /*
247 * Clear the stolen flag so that it can be migrated
248 * when load balancing needs emerge.
249 */
250 thread->stolen = false;
251 irq_spinlock_unlock(&thread->lock, false);
252
253 return thread;
254 }
255
256 goto loop;
257}
258
259/** Prevent rq starvation
260 *
261 * Prevent low priority threads from starving in rq's.
262 *
263 * When the function decides to relink rq's, it reconnects
264 * respective pointers so that in result threads with 'pri'
265 * greater or equal start are moved to a higher-priority queue.
266 *
267 * @param start Threshold priority.
268 *
269 */
270static void relink_rq(int start)
271{
272 if (CPU->current_clock_tick < CPU->relink_deadline)
273 return;
274
275 CPU->relink_deadline = CPU->current_clock_tick + NEEDS_RELINK_MAX;
276
277 list_t list;
278 list_initialize(&list);
279
280 irq_spinlock_lock(&CPU->lock, false);
281
282 for (int i = start; i < RQ_COUNT - 1; i++) {
283 /* Remember and empty rq[i + 1] */
284
285 irq_spinlock_lock(&CPU->rq[i + 1].lock, false);
286 list_concat(&list, &CPU->rq[i + 1].rq);
287 size_t n = CPU->rq[i + 1].n;
288 CPU->rq[i + 1].n = 0;
289 irq_spinlock_unlock(&CPU->rq[i + 1].lock, false);
290
291 /* Append rq[i + 1] to rq[i] */
292
293 irq_spinlock_lock(&CPU->rq[i].lock, false);
294 list_concat(&CPU->rq[i].rq, &list);
295 CPU->rq[i].n += n;
296 irq_spinlock_unlock(&CPU->rq[i].lock, false);
297 }
298
299 irq_spinlock_unlock(&CPU->lock, false);
300}
301
302/** The scheduler
303 *
304 * The thread scheduling procedure.
305 * Passes control directly to
306 * scheduler_separated_stack().
307 *
308 */
309void scheduler(void)
310{
311 volatile ipl_t ipl;
312
313 assert(CPU != NULL);
314
315 ipl = interrupts_disable();
316
317 if (atomic_load(&haltstate))
318 halt();
319
320 if (THREAD) {
321 irq_spinlock_lock(&THREAD->lock, false);
322
323 /* Update thread kernel accounting */
324 THREAD->kcycles += get_cycle() - THREAD->last_cycle;
325
326#if (defined CONFIG_FPU) && (!defined CONFIG_FPU_LAZY)
327 fpu_context_save(THREAD->saved_fpu_context);
328#endif
329 if (!context_save(&THREAD->saved_context)) {
330 /*
331 * This is the place where threads leave scheduler();
332 */
333
334 /* Save current CPU cycle */
335 THREAD->last_cycle = get_cycle();
336
337 irq_spinlock_unlock(&THREAD->lock, false);
338 interrupts_restore(THREAD->saved_context.ipl);
339
340 return;
341 }
342
343 /*
344 * Interrupt priority level of preempted thread is recorded
345 * here to facilitate scheduler() invocations from
346 * interrupts_disable()'d code (e.g. waitq_sleep_timeout()).
347 *
348 */
349 THREAD->saved_context.ipl = ipl;
350 }
351
352 /*
353 * Through the 'CURRENT' structure, we keep track of THREAD, TASK, CPU, AS
354 * and preemption counter. At this point CURRENT could be coming either
355 * from THREAD's or CPU's stack.
356 *
357 */
358 current_copy(CURRENT, (current_t *) CPU->stack);
359
360 /*
361 * We may not keep the old stack.
362 * Reason: If we kept the old stack and got blocked, for instance, in
363 * find_best_thread(), the old thread could get rescheduled by another
364 * CPU and overwrite the part of its own stack that was also used by
365 * the scheduler on this CPU.
366 *
367 * Moreover, we have to bypass the compiler-generated POP sequence
368 * which is fooled by SP being set to the very top of the stack.
369 * Therefore the scheduler() function continues in
370 * scheduler_separated_stack().
371 *
372 */
373 context_save(&CPU->saved_context);
374 context_set(&CPU->saved_context, FADDR(scheduler_separated_stack),
375 (uintptr_t) CPU->stack, STACK_SIZE);
376 context_restore(&CPU->saved_context);
377
378 /* Not reached */
379}
380
381/** Scheduler stack switch wrapper
382 *
383 * Second part of the scheduler() function
384 * using new stack. Handling the actual context
385 * switch to a new thread.
386 *
387 */
388void scheduler_separated_stack(void)
389{
390 DEADLOCK_PROBE_INIT(p_joinwq);
391 task_t *old_task = TASK;
392 as_t *old_as = AS;
393
394 assert((!THREAD) || (irq_spinlock_locked(&THREAD->lock)));
395 assert(CPU != NULL);
396 assert(interrupts_disabled());
397
398 /*
399 * Hold the current task and the address space to prevent their
400 * possible destruction should thread_destroy() be called on this or any
401 * other processor while the scheduler is still using them.
402 */
403 if (old_task)
404 task_hold(old_task);
405
406 if (old_as)
407 as_hold(old_as);
408
409 if (THREAD) {
410 /* Must be run after the switch to scheduler stack */
411 after_thread_ran();
412
413 switch (THREAD->state) {
414 case Running:
415 irq_spinlock_unlock(&THREAD->lock, false);
416 thread_ready(THREAD);
417 break;
418
419 case Exiting:
420 repeat:
421 if (THREAD->detached) {
422 thread_destroy(THREAD, false);
423 } else {
424 /*
425 * The thread structure is kept allocated until
426 * somebody calls thread_detach() on it.
427 */
428 if (!irq_spinlock_trylock(&THREAD->join_wq.lock)) {
429 /*
430 * Avoid deadlock.
431 */
432 irq_spinlock_unlock(&THREAD->lock, false);
433 delay(HZ);
434 irq_spinlock_lock(&THREAD->lock, false);
435 DEADLOCK_PROBE(p_joinwq,
436 DEADLOCK_THRESHOLD);
437 goto repeat;
438 }
439 _waitq_wakeup_unsafe(&THREAD->join_wq,
440 WAKEUP_FIRST);
441 irq_spinlock_unlock(&THREAD->join_wq.lock, false);
442
443 THREAD->state = Lingering;
444 irq_spinlock_unlock(&THREAD->lock, false);
445 }
446 break;
447
448 case Sleeping:
449 /*
450 * Prefer the thread after it's woken up.
451 */
452 THREAD->priority = -1;
453
454 /*
455 * We need to release wq->lock which we locked in
456 * waitq_sleep(). Address of wq->lock is kept in
457 * THREAD->sleep_queue.
458 */
459 irq_spinlock_unlock(&THREAD->sleep_queue->lock, false);
460
461 irq_spinlock_unlock(&THREAD->lock, false);
462 break;
463
464 default:
465 /*
466 * Entering state is unexpected.
467 */
468 panic("tid%" PRIu64 ": unexpected state %s.",
469 THREAD->tid, thread_states[THREAD->state]);
470 break;
471 }
472
473 THREAD = NULL;
474 }
475
476 THREAD = find_best_thread();
477
478 irq_spinlock_lock(&THREAD->lock, false);
479 int priority = THREAD->priority;
480 irq_spinlock_unlock(&THREAD->lock, false);
481
482 relink_rq(priority);
483
484 /*
485 * If both the old and the new task are the same,
486 * lots of work is avoided.
487 */
488 if (TASK != THREAD->task) {
489 as_t *new_as = THREAD->task->as;
490
491 /*
492 * Note that it is possible for two tasks
493 * to share one address space.
494 */
495 if (old_as != new_as) {
496 /*
497 * Both tasks and address spaces are different.
498 * Replace the old one with the new one.
499 */
500 as_switch(old_as, new_as);
501 }
502
503 TASK = THREAD->task;
504 before_task_runs();
505 }
506
507 if (old_task)
508 task_release(old_task);
509
510 if (old_as)
511 as_release(old_as);
512
513 irq_spinlock_lock(&THREAD->lock, false);
514 THREAD->state = Running;
515
516#ifdef SCHEDULER_VERBOSE
517 log(LF_OTHER, LVL_DEBUG,
518 "cpu%u: tid %" PRIu64 " (priority=%d, ticks=%" PRIu64
519 ", nrdy=%zu)", CPU->id, THREAD->tid, THREAD->priority,
520 THREAD->ticks, atomic_load(&CPU->nrdy));
521#endif
522
523 /*
524 * Some architectures provide late kernel PA2KA(identity)
525 * mapping in a page fault handler. However, the page fault
526 * handler uses the kernel stack of the running thread and
527 * therefore cannot be used to map it. The kernel stack, if
528 * necessary, is to be mapped in before_thread_runs(). This
529 * function must be executed before the switch to the new stack.
530 */
531 before_thread_runs();
532
533 /*
534 * Copy the knowledge of CPU, TASK, THREAD and preemption counter to
535 * thread's stack.
536 */
537 current_copy(CURRENT, (current_t *) THREAD->kstack);
538
539 context_restore(&THREAD->saved_context);
540
541 /* Not reached */
542}
543
544#ifdef CONFIG_SMP
545/** Load balancing thread
546 *
547 * SMP load balancing thread, supervising thread supplies
548 * for the CPU it's wired to.
549 *
550 * @param arg Generic thread argument (unused).
551 *
552 */
553void kcpulb(void *arg)
554{
555 size_t average;
556 size_t rdy;
557
558 /*
559 * Detach kcpulb as nobody will call thread_join_timeout() on it.
560 */
561 thread_detach(THREAD);
562
563loop:
564 /*
565 * Work in 1s intervals.
566 */
567 thread_sleep(1);
568
569not_satisfied:
570 /*
571 * Calculate the number of threads that will be migrated/stolen from
572 * other CPU's. Note that situation can have changed between two
573 * passes. Each time get the most up to date counts.
574 *
575 */
576 average = atomic_load(&nrdy) / config.cpu_active + 1;
577 rdy = atomic_load(&CPU->nrdy);
578
579 if (average <= rdy)
580 goto satisfied;
581
582 size_t count = average - rdy;
583
584 /*
585 * Searching least priority queues on all CPU's first and most priority
586 * queues on all CPU's last.
587 */
588 size_t acpu;
589 size_t acpu_bias = 0;
590 int rq;
591
592 for (rq = RQ_COUNT - 1; rq >= 0; rq--) {
593 for (acpu = 0; acpu < config.cpu_active; acpu++) {
594 cpu_t *cpu = &cpus[(acpu + acpu_bias) % config.cpu_active];
595
596 /*
597 * Not interested in ourselves.
598 * Doesn't require interrupt disabling for kcpulb has
599 * THREAD_FLAG_WIRED.
600 *
601 */
602 if (CPU == cpu)
603 continue;
604
605 if (atomic_load(&cpu->nrdy) <= average)
606 continue;
607
608 irq_spinlock_lock(&(cpu->rq[rq].lock), true);
609 if (cpu->rq[rq].n == 0) {
610 irq_spinlock_unlock(&(cpu->rq[rq].lock), true);
611 continue;
612 }
613
614 thread_t *thread = NULL;
615
616 /* Search rq from the back */
617 link_t *link = list_last(&cpu->rq[rq].rq);
618
619 while (link != NULL) {
620 thread = (thread_t *) list_get_instance(link,
621 thread_t, rq_link);
622
623 /*
624 * Do not steal CPU-wired threads, threads
625 * already stolen, threads for which migration
626 * was temporarily disabled or threads whose
627 * FPU context is still in the CPU.
628 */
629 irq_spinlock_lock(&thread->lock, false);
630
631 if ((!thread->wired) && (!thread->stolen) &&
632 (!thread->nomigrate) &&
633 (!thread->fpu_context_engaged)) {
634 /*
635 * Remove thread from ready queue.
636 */
637 irq_spinlock_unlock(&thread->lock,
638 false);
639
640 atomic_dec(&cpu->nrdy);
641 atomic_dec(&nrdy);
642
643 cpu->rq[rq].n--;
644 list_remove(&thread->rq_link);
645
646 break;
647 }
648
649 irq_spinlock_unlock(&thread->lock, false);
650
651 link = list_prev(link, &cpu->rq[rq].rq);
652 thread = NULL;
653 }
654
655 if (thread) {
656 /*
657 * Ready thread on local CPU
658 */
659
660 irq_spinlock_pass(&(cpu->rq[rq].lock),
661 &thread->lock);
662
663#ifdef KCPULB_VERBOSE
664 log(LF_OTHER, LVL_DEBUG,
665 "kcpulb%u: TID %" PRIu64 " -> cpu%u, "
666 "nrdy=%ld, avg=%ld", CPU->id, thread->tid,
667 CPU->id, atomic_load(&CPU->nrdy),
668 atomic_load(&nrdy) / config.cpu_active);
669#endif
670
671 thread->stolen = true;
672 thread->state = Entering;
673
674 irq_spinlock_unlock(&thread->lock, true);
675 thread_ready(thread);
676
677 if (--count == 0)
678 goto satisfied;
679
680 /*
681 * We are not satisfied yet, focus on another
682 * CPU next time.
683 *
684 */
685 acpu_bias++;
686
687 continue;
688 } else
689 irq_spinlock_unlock(&(cpu->rq[rq].lock), true);
690
691 }
692 }
693
694 if (atomic_load(&CPU->nrdy)) {
695 /*
696 * Be a little bit light-weight and let migrated threads run.
697 *
698 */
699 scheduler();
700 } else {
701 /*
702 * We failed to migrate a single thread.
703 * Give up this turn.
704 *
705 */
706 goto loop;
707 }
708
709 goto not_satisfied;
710
711satisfied:
712 goto loop;
713}
714#endif /* CONFIG_SMP */
715
716/** Print information about threads & scheduler queues
717 *
718 */
719void sched_print_list(void)
720{
721 size_t cpu;
722 for (cpu = 0; cpu < config.cpu_count; cpu++) {
723 if (!cpus[cpu].active)
724 continue;
725
726 irq_spinlock_lock(&cpus[cpu].lock, true);
727
728 /* Technically a data race, but we don't really care in this case. */
729 int needs_relink = cpus[cpu].relink_deadline - cpus[cpu].current_clock_tick;
730
731 printf("cpu%u: address=%p, nrdy=%zu, needs_relink=%d\n",
732 cpus[cpu].id, &cpus[cpu], atomic_load(&cpus[cpu].nrdy),
733 needs_relink);
734
735 unsigned int i;
736 for (i = 0; i < RQ_COUNT; i++) {
737 irq_spinlock_lock(&(cpus[cpu].rq[i].lock), false);
738 if (cpus[cpu].rq[i].n == 0) {
739 irq_spinlock_unlock(&(cpus[cpu].rq[i].lock), false);
740 continue;
741 }
742
743 printf("\trq[%u]: ", i);
744 list_foreach(cpus[cpu].rq[i].rq, rq_link, thread_t,
745 thread) {
746 printf("%" PRIu64 "(%s) ", thread->tid,
747 thread_states[thread->state]);
748 }
749 printf("\n");
750
751 irq_spinlock_unlock(&(cpus[cpu].rq[i].lock), false);
752 }
753
754 irq_spinlock_unlock(&cpus[cpu].lock, true);
755 }
756}
757
758/** @}
759 */
Note: See TracBrowser for help on using the repository browser.