Subversion Repositories HelenOS-historic

Rev

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

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