Subversion Repositories HelenOS-historic

Rev

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

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