Subversion Repositories HelenOS-historic

Rev

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

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