Subversion Repositories HelenOS-historic

Rev

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

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