Subversion Repositories HelenOS

Rev

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

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