Subversion Repositories HelenOS-historic

Rev

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

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