Subversion Repositories HelenOS-historic

Rev

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

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