Subversion Repositories HelenOS

Rev

Rev 784 | Rev 787 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 jermar 1
/*
2
 * Copyright (C) 2001-2004 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
#include <proc/scheduler.h>
30
#include <proc/thread.h>
31
#include <proc/task.h>
378 jermar 32
#include <mm/heap.h>
33
#include <mm/frame.h>
34
#include <mm/page.h>
703 jermar 35
#include <mm/as.h>
378 jermar 36
#include <arch/asm.h>
37
#include <arch/faddr.h>
38
#include <arch/atomic.h>
39
#include <synch/spinlock.h>
1 jermar 40
#include <config.h>
41
#include <context.h>
42
#include <func.h>
43
#include <arch.h>
44
#include <list.h>
68 decky 45
#include <panic.h>
1 jermar 46
#include <typedefs.h>
378 jermar 47
#include <cpu.h>
195 vana 48
#include <print.h>
227 jermar 49
#include <debug.h>
1 jermar 50
 
475 jermar 51
atomic_t nrdy;
195 vana 52
 
118 jermar 53
/** Take actions before new thread runs
107 decky 54
 *
118 jermar 55
 * Perform actions that need to be
56
 * taken before the newly selected
57
 * tread is passed control.
107 decky 58
 *
59
 */
52 vana 60
void before_thread_runs(void)
61
{
309 palkovsky 62
    before_thread_runs_arch();
458 decky 63
#ifdef CONFIG_FPU_LAZY
309 palkovsky 64
    if(THREAD==CPU->fpu_owner)
65
        fpu_enable();
66
    else
67
        fpu_disable();
68
#else
69
    fpu_enable();
70
    if (THREAD->fpu_context_exists)
71
        fpu_context_restore(&(THREAD->saved_fpu_context));
72
    else {
73
        fpu_init();
74
        THREAD->fpu_context_exists=1;
75
    }
76
#endif
52 vana 77
}
78
 
458 decky 79
#ifdef CONFIG_FPU_LAZY
309 palkovsky 80
void scheduler_fpu_lazy_request(void)
81
{
82
    fpu_enable();
83
    if (CPU->fpu_owner != NULL) {  
84
        fpu_context_save(&CPU->fpu_owner->saved_fpu_context);
85
        /* don't prevent migration */
86
        CPU->fpu_owner->fpu_context_engaged=0;
87
    }
88
    if (THREAD->fpu_context_exists)
89
        fpu_context_restore(&THREAD->saved_fpu_context);
90
    else {
91
        fpu_init();
92
        THREAD->fpu_context_exists=1;
93
    }
94
    CPU->fpu_owner=THREAD;
95
    THREAD->fpu_context_engaged = 1;
96
}
97
#endif
52 vana 98
 
107 decky 99
/** Initialize scheduler
100
 *
101
 * Initialize kernel scheduler.
102
 *
103
 */
1 jermar 104
void scheduler_init(void)
105
{
106
}
107
 
107 decky 108
 
109
/** Get thread to be scheduled
110
 *
111
 * Get the optimal thread to be scheduled
109 jermar 112
 * according to thread accounting and scheduler
107 decky 113
 * policy.
114
 *
115
 * @return Thread to be scheduled.
116
 *
117
 */
483 jermar 118
static thread_t *find_best_thread(void)
1 jermar 119
{
120
    thread_t *t;
121
    runq_t *r;
783 palkovsky 122
    int i;
1 jermar 123
 
227 jermar 124
    ASSERT(CPU != NULL);
125
 
1 jermar 126
loop:
413 jermar 127
    interrupts_enable();
1 jermar 128
 
783 palkovsky 129
    if (atomic_get(&CPU->nrdy) == 0) {
1 jermar 130
        /*
131
         * For there was nothing to run, the CPU goes to sleep
132
         * until a hardware interrupt or an IPI comes.
133
         * This improves energy saving and hyperthreading.
134
         */
785 jermar 135
 
136
        /*
137
         * An interrupt might occur right now and wake up a thread.
138
         * In such case, the CPU will continue to go to sleep
139
         * even though there is a runnable thread.
140
         */
141
 
1 jermar 142
         cpu_sleep();
143
         goto loop;
144
    }
145
 
413 jermar 146
    interrupts_disable();
114 jermar 147
 
148
    i = 0;
149
    for (; i<RQ_COUNT; i++) {
15 jermar 150
        r = &CPU->rq[i];
1 jermar 151
        spinlock_lock(&r->lock);
152
        if (r->n == 0) {
153
            /*
154
             * If this queue is empty, try a lower-priority queue.
155
             */
156
            spinlock_unlock(&r->lock);
157
            continue;
158
        }
213 jermar 159
 
783 palkovsky 160
        atomic_dec(&CPU->nrdy);
475 jermar 161
        atomic_dec(&nrdy);
1 jermar 162
        r->n--;
163
 
164
        /*
165
         * Take the first thread from the queue.
166
         */
167
        t = list_get_instance(r->rq_head.next, thread_t, rq_link);
168
        list_remove(&t->rq_link);
169
 
170
        spinlock_unlock(&r->lock);
171
 
172
        spinlock_lock(&t->lock);
15 jermar 173
        t->cpu = CPU;
1 jermar 174
 
175
        t->ticks = us2ticks((i+1)*10000);
413 jermar 176
        t->priority = i;    /* eventually correct rq index */
1 jermar 177
 
178
        /*
179
         * Clear the X_STOLEN flag so that t can be migrated when load balancing needs emerge.
180
         */
181
        t->flags &= ~X_STOLEN;
182
        spinlock_unlock(&t->lock);
183
 
184
        return t;
185
    }
186
    goto loop;
187
 
188
}
189
 
107 decky 190
 
191
/** Prevent rq starvation
192
 *
193
 * Prevent low priority threads from starving in rq's.
194
 *
195
 * When the function decides to relink rq's, it reconnects
196
 * respective pointers so that in result threads with 'pri'
197
 * greater or equal 'start' are moved to a higher-priority queue.
198
 *
199
 * @param start Threshold priority.
200
 *
1 jermar 201
 */
452 decky 202
static void relink_rq(int start)
1 jermar 203
{
204
    link_t head;
205
    runq_t *r;
206
    int i, n;
207
 
208
    list_initialize(&head);
15 jermar 209
    spinlock_lock(&CPU->lock);
210
    if (CPU->needs_relink > NEEDS_RELINK_MAX) {
1 jermar 211
        for (i = start; i<RQ_COUNT-1; i++) {
212
            /* remember and empty rq[i + 1] */
15 jermar 213
            r = &CPU->rq[i + 1];
1 jermar 214
            spinlock_lock(&r->lock);
215
            list_concat(&head, &r->rq_head);
216
            n = r->n;
217
            r->n = 0;
218
            spinlock_unlock(&r->lock);
219
 
220
            /* append rq[i + 1] to rq[i] */
15 jermar 221
            r = &CPU->rq[i];
1 jermar 222
            spinlock_lock(&r->lock);
223
            list_concat(&r->rq_head, &head);
224
            r->n += n;
225
            spinlock_unlock(&r->lock);
226
        }
15 jermar 227
        CPU->needs_relink = 0;
1 jermar 228
    }
784 palkovsky 229
    spinlock_unlock(&CPU->lock);
1 jermar 230
 
231
}
232
 
107 decky 233
 
234
/** Scheduler stack switch wrapper
235
 *
236
 * Second part of the scheduler() function
237
 * using new stack. Handling the actual context
238
 * switch to a new thread.
239
 *
240
 */
452 decky 241
static void scheduler_separated_stack(void)
1 jermar 242
{
243
    int priority;
244
 
227 jermar 245
    ASSERT(CPU != NULL);
246
 
15 jermar 247
    if (THREAD) {
248
        switch (THREAD->state) {
1 jermar 249
            case Running:
125 jermar 250
            THREAD->state = Ready;
251
            spinlock_unlock(&THREAD->lock);
252
            thread_ready(THREAD);
253
            break;
1 jermar 254
 
255
            case Exiting:
125 jermar 256
            frame_free((__address) THREAD->kstack);
257
            if (THREAD->ustack) {
258
                frame_free((__address) THREAD->ustack);
259
            }
1 jermar 260
 
125 jermar 261
            /*
262
             * Detach from the containing task.
263
             */
264
            spinlock_lock(&TASK->lock);
265
            list_remove(&THREAD->th_link);
266
            spinlock_unlock(&TASK->lock);
73 vana 267
 
125 jermar 268
            spinlock_unlock(&THREAD->lock);
269
 
270
            spinlock_lock(&threads_lock);
271
            list_remove(&THREAD->threads_link);
272
            spinlock_unlock(&threads_lock);
73 vana 273
 
125 jermar 274
            spinlock_lock(&CPU->lock);
650 jermar 275
            if(CPU->fpu_owner==THREAD)
276
                CPU->fpu_owner=NULL;
125 jermar 277
            spinlock_unlock(&CPU->lock);
278
 
279
            free(THREAD);
280
 
281
            break;
282
 
1 jermar 283
            case Sleeping:
125 jermar 284
            /*
285
             * Prefer the thread after it's woken up.
286
             */
413 jermar 287
            THREAD->priority = -1;
1 jermar 288
 
125 jermar 289
            /*
290
             * We need to release wq->lock which we locked in waitq_sleep().
291
             * Address of wq->lock is kept in THREAD->sleep_queue.
292
             */
293
            spinlock_unlock(&THREAD->sleep_queue->lock);
1 jermar 294
 
125 jermar 295
            /*
296
             * Check for possible requests for out-of-context invocation.
297
             */
298
            if (THREAD->call_me) {
299
                THREAD->call_me(THREAD->call_me_with);
300
                THREAD->call_me = NULL;
301
                THREAD->call_me_with = NULL;
302
            }
1 jermar 303
 
125 jermar 304
            spinlock_unlock(&THREAD->lock);
1 jermar 305
 
125 jermar 306
            break;
307
 
1 jermar 308
            default:
125 jermar 309
            /*
310
             * Entering state is unexpected.
311
             */
312
            panic("tid%d: unexpected state %s\n", THREAD->tid, thread_states[THREAD->state]);
313
            break;
1 jermar 314
        }
15 jermar 315
        THREAD = NULL;
1 jermar 316
    }
198 jermar 317
 
214 vana 318
 
15 jermar 319
    THREAD = find_best_thread();
1 jermar 320
 
15 jermar 321
    spinlock_lock(&THREAD->lock);
413 jermar 322
    priority = THREAD->priority;
15 jermar 323
    spinlock_unlock(&THREAD->lock);
192 jermar 324
 
1 jermar 325
    relink_rq(priority);       
326
 
15 jermar 327
    spinlock_lock(&THREAD->lock);  
1 jermar 328
 
329
    /*
330
     * If both the old and the new task are the same, lots of work is avoided.
331
     */
15 jermar 332
    if (TASK != THREAD->task) {
703 jermar 333
        as_t *as1 = NULL;
334
        as_t *as2;
1 jermar 335
 
15 jermar 336
        if (TASK) {
337
            spinlock_lock(&TASK->lock);
703 jermar 338
            as1 = TASK->as;
15 jermar 339
            spinlock_unlock(&TASK->lock);
1 jermar 340
        }
341
 
15 jermar 342
        spinlock_lock(&THREAD->task->lock);
703 jermar 343
        as2 = THREAD->task->as;
15 jermar 344
        spinlock_unlock(&THREAD->task->lock);
1 jermar 345
 
346
        /*
703 jermar 347
         * Note that it is possible for two tasks to share one address space.
1 jermar 348
         */
703 jermar 349
        if (as1 != as2) {
1 jermar 350
            /*
703 jermar 351
             * Both tasks and address spaces are different.
1 jermar 352
             * Replace the old one with the new one.
353
             */
703 jermar 354
            as_install(as2);
1 jermar 355
        }
15 jermar 356
        TASK = THREAD->task;   
1 jermar 357
    }
358
 
15 jermar 359
    THREAD->state = Running;
1 jermar 360
 
361
    #ifdef SCHEDULER_VERBOSE
413 jermar 362
    printf("cpu%d: tid %d (priority=%d,ticks=%d,nrdy=%d)\n", CPU->id, THREAD->tid, THREAD->priority, THREAD->ticks, CPU->nrdy);
1 jermar 363
    #endif  
364
 
213 jermar 365
    /*
366
     * Copy the knowledge of CPU, TASK, THREAD and preemption counter to thread's stack.
367
     */
184 jermar 368
    the_copy(THE, (the_t *) THREAD->kstack);
369
 
15 jermar 370
    context_restore(&THREAD->saved_context);
1 jermar 371
    /* not reached */
372
}
373
 
107 decky 374
 
452 decky 375
/** The scheduler
376
 *
377
 * The thread scheduling procedure.
675 jermar 378
 * Passes control directly to
379
 * scheduler_separated_stack().
452 decky 380
 *
381
 */
382
void scheduler(void)
383
{
384
    volatile ipl_t ipl;
385
 
386
    ASSERT(CPU != NULL);
387
 
388
    ipl = interrupts_disable();
389
 
631 palkovsky 390
    if (atomic_get(&haltstate))
452 decky 391
        halt();
392
 
393
    if (THREAD) {
394
        spinlock_lock(&THREAD->lock);
458 decky 395
#ifndef CONFIG_FPU_LAZY
452 decky 396
        fpu_context_save(&(THREAD->saved_fpu_context));
397
#endif
398
        if (!context_save(&THREAD->saved_context)) {
399
            /*
400
             * This is the place where threads leave scheduler();
401
             */
402
            before_thread_runs();
403
            spinlock_unlock(&THREAD->lock);
404
            interrupts_restore(THREAD->saved_context.ipl);
405
            return;
406
        }
407
 
408
        /*
409
         * Interrupt priority level of preempted thread is recorded here
410
         * to facilitate scheduler() invocations from interrupts_disable()'d
411
         * code (e.g. waitq_sleep_timeout()).
412
         */
413
        THREAD->saved_context.ipl = ipl;
414
    }
415
 
416
    /*
557 jermar 417
     * Through the 'THE' structure, we keep track of THREAD, TASK, CPU, VM
452 decky 418
     * and preemption counter. At this point THE could be coming either
419
     * from THREAD's or CPU's stack.
420
     */
421
    the_copy(THE, (the_t *) CPU->stack);
422
 
423
    /*
424
     * We may not keep the old stack.
425
     * Reason: If we kept the old stack and got blocked, for instance, in
426
     * find_best_thread(), the old thread could get rescheduled by another
427
     * CPU and overwrite the part of its own stack that was also used by
428
     * the scheduler on this CPU.
429
     *
430
     * Moreover, we have to bypass the compiler-generated POP sequence
431
     * which is fooled by SP being set to the very top of the stack.
432
     * Therefore the scheduler() function continues in
433
     * scheduler_separated_stack().
434
     */
435
    context_save(&CPU->saved_context);
436
    context_set(&CPU->saved_context, FADDR(scheduler_separated_stack), (__address) CPU->stack, CPU_STACK_SIZE);
437
    context_restore(&CPU->saved_context);
438
    /* not reached */
439
}
440
 
441
 
442
 
443
 
444
 
458 decky 445
#ifdef CONFIG_SMP
107 decky 446
/** Load balancing thread
447
 *
448
 * SMP load balancing thread, supervising thread supplies
449
 * for the CPU it's wired to.
450
 *
451
 * @param arg Generic thread argument (unused).
452
 *
1 jermar 453
 */
454
void kcpulb(void *arg)
455
{
456
    thread_t *t;
783 palkovsky 457
    int count, average, i, j, k = 0;
413 jermar 458
    ipl_t ipl;
1 jermar 459
 
460
loop:
461
    /*
779 jermar 462
     * Work in 1s intervals.
1 jermar 463
     */
779 jermar 464
    thread_sleep(1);
1 jermar 465
 
466
not_satisfied:
467
    /*
468
     * Calculate the number of threads that will be migrated/stolen from
469
     * other CPU's. Note that situation can have changed between two
470
     * passes. Each time get the most up to date counts.
471
     */
784 palkovsky 472
    average = atomic_get(&nrdy) / config.cpu_active + 1;
783 palkovsky 473
    count = average - atomic_get(&CPU->nrdy);
1 jermar 474
 
784 palkovsky 475
    if (count <= 0)
1 jermar 476
        goto satisfied;
477
 
478
    /*
479
     * Searching least priority queues on all CPU's first and most priority queues on all CPU's last.
480
     */
481
    for (j=RQ_COUNT-1; j >= 0; j--) {
482
        for (i=0; i < config.cpu_active; i++) {
483
            link_t *l;
484
            runq_t *r;
485
            cpu_t *cpu;
486
 
487
            cpu = &cpus[(i + k) % config.cpu_active];
488
 
489
            /*
490
             * Not interested in ourselves.
491
             * Doesn't require interrupt disabling for kcpulb is X_WIRED.
492
             */
15 jermar 493
            if (CPU == cpu)
783 palkovsky 494
                continue;
495
            if (atomic_get(&cpu->nrdy) <= average)
496
                continue;
1 jermar 497
 
784 palkovsky 498
            ipl = interrupts_disable();
115 jermar 499
            r = &cpu->rq[j];
1 jermar 500
            spinlock_lock(&r->lock);
501
            if (r->n == 0) {
502
                spinlock_unlock(&r->lock);
413 jermar 503
                interrupts_restore(ipl);
1 jermar 504
                continue;
505
            }
506
 
507
            t = NULL;
508
            l = r->rq_head.prev;    /* search rq from the back */
509
            while (l != &r->rq_head) {
510
                t = list_get_instance(l, thread_t, rq_link);
511
                /*
125 jermar 512
                 * We don't want to steal CPU-wired threads neither threads already stolen.
1 jermar 513
                 * The latter prevents threads from migrating between CPU's without ever being run.
125 jermar 514
                 * We don't want to steal threads whose FPU context is still in CPU.
73 vana 515
                 */
1 jermar 516
                spinlock_lock(&t->lock);
73 vana 517
                if ( (!(t->flags & (X_WIRED | X_STOLEN))) && (!(t->fpu_context_engaged)) ) {
1 jermar 518
                    /*
519
                     * Remove t from r.
520
                     */
521
                    spinlock_unlock(&t->lock);
522
 
783 palkovsky 523
                    atomic_dec(&cpu->nrdy);
475 jermar 524
                    atomic_dec(&nrdy);
1 jermar 525
 
125 jermar 526
                    r->n--;
1 jermar 527
                    list_remove(&t->rq_link);
528
 
529
                    break;
530
                }
531
                spinlock_unlock(&t->lock);
532
                l = l->prev;
533
                t = NULL;
534
            }
535
            spinlock_unlock(&r->lock);
536
 
537
            if (t) {
538
                /*
539
                 * Ready t on local CPU
540
                 */
541
                spinlock_lock(&t->lock);
542
                #ifdef KCPULB_VERBOSE
783 palkovsky 543
                printf("kcpulb%d: TID %d -> cpu%d, nrdy=%d, avg=%d\n", CPU->id, t->tid, CPU->id, atomic_get(&CPU->nrdy), atomic_get(&nrdy) / config.cpu_active);
1 jermar 544
                #endif
545
                t->flags |= X_STOLEN;
546
                spinlock_unlock(&t->lock);
547
 
548
                thread_ready(t);
549
 
413 jermar 550
                interrupts_restore(ipl);
1 jermar 551
 
552
                if (--count == 0)
553
                    goto satisfied;
554
 
555
                /*
125 jermar 556
                 * We are not satisfied yet, focus on another CPU next time.
1 jermar 557
                 */
558
                k++;
559
 
560
                continue;
561
            }
413 jermar 562
            interrupts_restore(ipl);
1 jermar 563
        }
564
    }
565
 
783 palkovsky 566
    if (atomic_get(&CPU->nrdy)) {
1 jermar 567
        /*
568
         * Be a little bit light-weight and let migrated threads run.
569
         */
570
        scheduler();
779 jermar 571
    } else {
1 jermar 572
        /*
573
         * We failed to migrate a single thread.
779 jermar 574
         * Give up this turn.
1 jermar 575
         */
779 jermar 576
        goto loop;
1 jermar 577
    }
578
 
579
    goto not_satisfied;
125 jermar 580
 
1 jermar 581
satisfied:
582
    goto loop;
583
}
584
 
458 decky 585
#endif /* CONFIG_SMP */
775 palkovsky 586
 
587
 
588
/** Print information about threads & scheduler queues */
589
void sched_print_list(void)
590
{
591
    ipl_t ipl;
592
    int cpu,i;
593
    runq_t *r;
594
    thread_t *t;
595
    link_t *cur;
596
 
597
    /* We are going to mess with scheduler structures,
598
     * let's not be interrupted */
599
    ipl = interrupts_disable();
600
    printf("*********** Scheduler dump ***********\n");
601
    for (cpu=0;cpu < config.cpu_count; cpu++) {
602
        if (!cpus[cpu].active)
603
            continue;
604
        spinlock_lock(&cpus[cpu].lock);
605
        printf("cpu%d: nrdy: %d needs_relink: %d\n",
783 palkovsky 606
               cpus[cpu].id, atomic_get(&cpus[cpu].nrdy), cpus[cpu].needs_relink);
775 palkovsky 607
 
608
        for (i=0; i<RQ_COUNT; i++) {
609
            r = &cpus[cpu].rq[i];
610
            spinlock_lock(&r->lock);
611
            if (!r->n) {
612
                spinlock_unlock(&r->lock);
613
                continue;
614
            }
779 jermar 615
            printf("\tRq %d: ", i);
775 palkovsky 616
            for (cur=r->rq_head.next; cur!=&r->rq_head; cur=cur->next) {
617
                t = list_get_instance(cur, thread_t, rq_link);
618
                printf("%d(%s) ", t->tid,
619
                       thread_states[t->state]);
620
            }
621
            printf("\n");
622
            spinlock_unlock(&r->lock);
623
        }
624
        spinlock_unlock(&cpus[cpu].lock);
625
    }
626
 
627
    interrupts_restore(ipl);
628
}