Subversion Repositories HelenOS-historic

Rev

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

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