Subversion Repositories HelenOS-historic

Rev

Rev 1229 | Rev 1264 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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