Subversion Repositories HelenOS

Rev

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

Rev 2268 Rev 2436
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
/** @addtogroup genericproc
29
/** @addtogroup genericproc
30
 * @{
30
 * @{
31
 */
31
 */
32
 
32
 
33
/**
33
/**
34
 * @file
34
 * @file
35
 * @brief   Thread management functions.
35
 * @brief   Thread management functions.
36
 */
36
 */
37
 
37
 
38
#include <proc/scheduler.h>
38
#include <proc/scheduler.h>
39
#include <proc/thread.h>
39
#include <proc/thread.h>
40
#include <proc/task.h>
40
#include <proc/task.h>
41
#include <proc/uarg.h>
41
#include <proc/uarg.h>
42
#include <mm/frame.h>
42
#include <mm/frame.h>
43
#include <mm/page.h>
43
#include <mm/page.h>
44
#include <arch/asm.h>
44
#include <arch/asm.h>
45
#include <arch/cycle.h>
45
#include <arch/cycle.h>
46
#include <arch.h>
46
#include <arch.h>
47
#include <synch/synch.h>
47
#include <synch/synch.h>
48
#include <synch/spinlock.h>
48
#include <synch/spinlock.h>
49
#include <synch/waitq.h>
49
#include <synch/waitq.h>
50
#include <synch/rwlock.h>
50
#include <synch/rwlock.h>
51
#include <cpu.h>
51
#include <cpu.h>
52
#include <func.h>
52
#include <func.h>
53
#include <context.h>
53
#include <context.h>
54
#include <adt/btree.h>
54
#include <adt/btree.h>
55
#include <adt/list.h>
55
#include <adt/list.h>
56
#include <time/clock.h>
56
#include <time/clock.h>
57
#include <time/timeout.h>
57
#include <time/timeout.h>
58
#include <config.h>
58
#include <config.h>
59
#include <arch/interrupt.h>
59
#include <arch/interrupt.h>
60
#include <smp/ipi.h>
60
#include <smp/ipi.h>
61
#include <arch/faddr.h>
61
#include <arch/faddr.h>
62
#include <atomic.h>
62
#include <atomic.h>
63
#include <memstr.h>
63
#include <memstr.h>
64
#include <print.h>
64
#include <print.h>
65
#include <mm/slab.h>
65
#include <mm/slab.h>
66
#include <debug.h>
66
#include <debug.h>
67
#include <main/uinit.h>
67
#include <main/uinit.h>
68
#include <syscall/copy.h>
68
#include <syscall/copy.h>
69
#include <errno.h>
69
#include <errno.h>
70
 
70
 
71
 
71
 
72
/** Thread states */
72
/** Thread states */
73
char *thread_states[] = {
73
char *thread_states[] = {
74
    "Invalid",
74
    "Invalid",
75
    "Running",
75
    "Running",
76
    "Sleeping",
76
    "Sleeping",
77
    "Ready",
77
    "Ready",
78
    "Entering",
78
    "Entering",
79
    "Exiting",
79
    "Exiting",
80
    "Undead"
80
    "Undead"
81
};
81
};
82
 
82
 
83
/** Lock protecting the threads_btree B+tree.
83
/** Lock protecting the threads_btree B+tree.
84
 *
84
 *
85
 * For locking rules, see declaration thereof.
85
 * For locking rules, see declaration thereof.
86
 */
86
 */
87
SPINLOCK_INITIALIZE(threads_lock);
87
SPINLOCK_INITIALIZE(threads_lock);
88
 
88
 
89
/** B+tree of all threads.
89
/** B+tree of all threads.
90
 *
90
 *
91
 * When a thread is found in the threads_btree B+tree, it is guaranteed to
91
 * When a thread is found in the threads_btree B+tree, it is guaranteed to
92
 * exist as long as the threads_lock is held.
92
 * exist as long as the threads_lock is held.
93
 */
93
 */
94
btree_t threads_btree;     
94
btree_t threads_btree;     
95
 
95
 
96
SPINLOCK_INITIALIZE(tidlock);
96
SPINLOCK_INITIALIZE(tidlock);
97
thread_id_t last_tid = 0;
97
thread_id_t last_tid = 0;
98
 
98
 
99
static slab_cache_t *thread_slab;
99
static slab_cache_t *thread_slab;
100
#ifdef ARCH_HAS_FPU
100
#ifdef ARCH_HAS_FPU
101
slab_cache_t *fpu_context_slab;
101
slab_cache_t *fpu_context_slab;
102
#endif
102
#endif
103
 
103
 
104
/** Thread wrapper.
104
/** Thread wrapper.
105
 *
105
 *
106
 * This wrapper is provided to ensure that every thread makes a call to
106
 * This wrapper is provided to ensure that every thread makes a call to
107
 * thread_exit() when its implementing function returns.
107
 * thread_exit() when its implementing function returns.
108
 *
108
 *
109
 * interrupts_disable() is assumed.
109
 * interrupts_disable() is assumed.
110
 *
110
 *
111
 */
111
 */
112
static void cushion(void)
112
static void cushion(void)
113
{
113
{
114
    void (*f)(void *) = THREAD->thread_code;
114
    void (*f)(void *) = THREAD->thread_code;
115
    void *arg = THREAD->thread_arg;
115
    void *arg = THREAD->thread_arg;
116
    THREAD->last_cycle = get_cycle();
116
    THREAD->last_cycle = get_cycle();
117
 
117
 
118
    /* This is where each thread wakes up after its creation */
118
    /* This is where each thread wakes up after its creation */
119
    spinlock_unlock(&THREAD->lock);
119
    spinlock_unlock(&THREAD->lock);
120
    interrupts_enable();
120
    interrupts_enable();
121
 
121
 
122
    f(arg);
122
    f(arg);
123
   
123
   
124
    /* Accumulate accounting to the task */
124
    /* Accumulate accounting to the task */
125
    ipl_t ipl = interrupts_disable();
125
    ipl_t ipl = interrupts_disable();
126
   
126
   
127
    spinlock_lock(&THREAD->lock);
127
    spinlock_lock(&THREAD->lock);
128
    if (!THREAD->uncounted) {
128
    if (!THREAD->uncounted) {
129
        thread_update_accounting();
129
        thread_update_accounting();
130
        uint64_t cycles = THREAD->cycles;
130
        uint64_t cycles = THREAD->cycles;
131
        THREAD->cycles = 0;
131
        THREAD->cycles = 0;
132
        spinlock_unlock(&THREAD->lock);
132
        spinlock_unlock(&THREAD->lock);
133
       
133
       
134
        spinlock_lock(&TASK->lock);
134
        spinlock_lock(&TASK->lock);
135
        TASK->cycles += cycles;
135
        TASK->cycles += cycles;
136
        spinlock_unlock(&TASK->lock);
136
        spinlock_unlock(&TASK->lock);
137
    } else
137
    } else
138
        spinlock_unlock(&THREAD->lock);
138
        spinlock_unlock(&THREAD->lock);
139
   
139
   
140
    interrupts_restore(ipl);
140
    interrupts_restore(ipl);
141
   
141
   
142
    thread_exit();
142
    thread_exit();
143
    /* not reached */
143
    /* not reached */
144
}
144
}
145
 
145
 
146
/** Initialization and allocation for thread_t structure */
146
/** Initialization and allocation for thread_t structure */
147
static int thr_constructor(void *obj, int kmflags)
147
static int thr_constructor(void *obj, int kmflags)
148
{
148
{
149
    thread_t *t = (thread_t *) obj;
149
    thread_t *t = (thread_t *) obj;
150
 
150
 
151
    spinlock_initialize(&t->lock, "thread_t_lock");
151
    spinlock_initialize(&t->lock, "thread_t_lock");
152
    link_initialize(&t->rq_link);
152
    link_initialize(&t->rq_link);
153
    link_initialize(&t->wq_link);
153
    link_initialize(&t->wq_link);
154
    link_initialize(&t->th_link);
154
    link_initialize(&t->th_link);
155
 
155
 
156
    /* call the architecture-specific part of the constructor */
156
    /* call the architecture-specific part of the constructor */
157
    thr_constructor_arch(t);
157
    thr_constructor_arch(t);
158
   
158
   
159
#ifdef ARCH_HAS_FPU
159
#ifdef ARCH_HAS_FPU
160
#  ifdef CONFIG_FPU_LAZY
160
#  ifdef CONFIG_FPU_LAZY
161
    t->saved_fpu_context = NULL;
161
    t->saved_fpu_context = NULL;
162
#  else
162
#  else
163
    t->saved_fpu_context = slab_alloc(fpu_context_slab,kmflags);
163
    t->saved_fpu_context = slab_alloc(fpu_context_slab,kmflags);
164
    if (!t->saved_fpu_context)
164
    if (!t->saved_fpu_context)
165
        return -1;
165
        return -1;
166
#  endif
166
#  endif
167
#endif  
167
#endif  
168
 
168
 
169
    t->kstack = (uint8_t *) frame_alloc(STACK_FRAMES, FRAME_KA | kmflags);
169
    t->kstack = (uint8_t *) frame_alloc(STACK_FRAMES, FRAME_KA | kmflags);
170
    if (! t->kstack) {
170
    if (! t->kstack) {
171
#ifdef ARCH_HAS_FPU
171
#ifdef ARCH_HAS_FPU
172
        if (t->saved_fpu_context)
172
        if (t->saved_fpu_context)
173
            slab_free(fpu_context_slab,t->saved_fpu_context);
173
            slab_free(fpu_context_slab,t->saved_fpu_context);
174
#endif
174
#endif
175
        return -1;
175
        return -1;
176
    }
176
    }
177
 
177
 
178
    return 0;
178
    return 0;
179
}
179
}
180
 
180
 
181
/** Destruction of thread_t object */
181
/** Destruction of thread_t object */
182
static int thr_destructor(void *obj)
182
static int thr_destructor(void *obj)
183
{
183
{
184
    thread_t *t = (thread_t *) obj;
184
    thread_t *t = (thread_t *) obj;
185
 
185
 
186
    /* call the architecture-specific part of the destructor */
186
    /* call the architecture-specific part of the destructor */
187
    thr_destructor_arch(t);
187
    thr_destructor_arch(t);
188
 
188
 
189
    frame_free(KA2PA(t->kstack));
189
    frame_free(KA2PA(t->kstack));
190
#ifdef ARCH_HAS_FPU
190
#ifdef ARCH_HAS_FPU
191
    if (t->saved_fpu_context)
191
    if (t->saved_fpu_context)
192
        slab_free(fpu_context_slab,t->saved_fpu_context);
192
        slab_free(fpu_context_slab,t->saved_fpu_context);
193
#endif
193
#endif
194
    return 1; /* One page freed */
194
    return 1; /* One page freed */
195
}
195
}
196
 
196
 
197
/** Initialize threads
197
/** Initialize threads
198
 *
198
 *
199
 * Initialize kernel threads support.
199
 * Initialize kernel threads support.
200
 *
200
 *
201
 */
201
 */
202
void thread_init(void)
202
void thread_init(void)
203
{
203
{
204
    THREAD = NULL;
204
    THREAD = NULL;
205
    atomic_set(&nrdy,0);
205
    atomic_set(&nrdy,0);
206
    thread_slab = slab_cache_create("thread_slab", sizeof(thread_t), 0,
206
    thread_slab = slab_cache_create("thread_slab", sizeof(thread_t), 0,
207
        thr_constructor, thr_destructor, 0);
207
        thr_constructor, thr_destructor, 0);
208
 
208
 
209
#ifdef ARCH_HAS_FPU
209
#ifdef ARCH_HAS_FPU
210
    fpu_context_slab = slab_cache_create("fpu_slab", sizeof(fpu_context_t),
210
    fpu_context_slab = slab_cache_create("fpu_slab", sizeof(fpu_context_t),
211
        FPU_CONTEXT_ALIGN, NULL, NULL, 0);
211
        FPU_CONTEXT_ALIGN, NULL, NULL, 0);
212
#endif
212
#endif
213
 
213
 
214
    btree_create(&threads_btree);
214
    btree_create(&threads_btree);
215
}
215
}
216
 
216
 
217
/** Make thread ready
217
/** Make thread ready
218
 *
218
 *
219
 * Switch thread t to the ready state.
219
 * Switch thread t to the ready state.
220
 *
220
 *
221
 * @param t Thread to make ready.
221
 * @param t Thread to make ready.
222
 *
222
 *
223
 */
223
 */
224
void thread_ready(thread_t *t)
224
void thread_ready(thread_t *t)
225
{
225
{
226
    cpu_t *cpu;
226
    cpu_t *cpu;
227
    runq_t *r;
227
    runq_t *r;
228
    ipl_t ipl;
228
    ipl_t ipl;
229
    int i, avg;
229
    int i, avg;
230
 
230
 
231
    ipl = interrupts_disable();
231
    ipl = interrupts_disable();
232
 
232
 
233
    spinlock_lock(&t->lock);
233
    spinlock_lock(&t->lock);
234
 
234
 
235
    ASSERT(! (t->state == Ready));
235
    ASSERT(! (t->state == Ready));
236
 
236
 
237
    i = (t->priority < RQ_COUNT - 1) ? ++t->priority : t->priority;
237
    i = (t->priority < RQ_COUNT - 1) ? ++t->priority : t->priority;
238
   
238
   
239
    cpu = CPU;
239
    cpu = CPU;
240
    if (t->flags & THREAD_FLAG_WIRED) {
240
    if (t->flags & THREAD_FLAG_WIRED) {
241
        ASSERT(t->cpu != NULL);
241
        ASSERT(t->cpu != NULL);
242
        cpu = t->cpu;
242
        cpu = t->cpu;
243
    }
243
    }
244
    t->state = Ready;
244
    t->state = Ready;
245
    spinlock_unlock(&t->lock);
245
    spinlock_unlock(&t->lock);
246
   
246
   
247
    /*
247
    /*
248
     * Append t to respective ready queue on respective processor.
248
     * Append t to respective ready queue on respective processor.
249
     */
249
     */
250
    r = &cpu->rq[i];
250
    r = &cpu->rq[i];
251
    spinlock_lock(&r->lock);
251
    spinlock_lock(&r->lock);
252
    list_append(&t->rq_link, &r->rq_head);
252
    list_append(&t->rq_link, &r->rq_head);
253
    r->n++;
253
    r->n++;
254
    spinlock_unlock(&r->lock);
254
    spinlock_unlock(&r->lock);
255
 
255
 
256
    atomic_inc(&nrdy);
256
    atomic_inc(&nrdy);
257
    avg = atomic_get(&nrdy) / config.cpu_active;
257
    avg = atomic_get(&nrdy) / config.cpu_active;
258
    atomic_inc(&cpu->nrdy);
258
    atomic_inc(&cpu->nrdy);
259
 
259
 
260
    interrupts_restore(ipl);
260
    interrupts_restore(ipl);
261
}
261
}
262
 
262
 
263
/** Destroy thread memory structure
263
/** Destroy thread memory structure
264
 *
264
 *
265
 * Detach thread from all queues, cpus etc. and destroy it.
265
 * Detach thread from all queues, cpus etc. and destroy it.
266
 *
266
 *
267
 * Assume thread->lock is held!!
267
 * Assume thread->lock is held!!
268
 */
268
 */
269
void thread_destroy(thread_t *t)
269
void thread_destroy(thread_t *t)
270
{
270
{
271
    bool destroy_task = false;
271
    bool destroy_task = false;
272
 
272
 
273
    ASSERT(t->state == Exiting || t->state == Undead);
273
    ASSERT(t->state == Exiting || t->state == Undead);
274
    ASSERT(t->task);
274
    ASSERT(t->task);
275
    ASSERT(t->cpu);
275
    ASSERT(t->cpu);
276
 
276
 
277
    spinlock_lock(&t->cpu->lock);
277
    spinlock_lock(&t->cpu->lock);
278
    if(t->cpu->fpu_owner == t)
278
    if(t->cpu->fpu_owner == t)
279
        t->cpu->fpu_owner = NULL;
279
        t->cpu->fpu_owner = NULL;
280
    spinlock_unlock(&t->cpu->lock);
280
    spinlock_unlock(&t->cpu->lock);
281
 
281
 
282
    spinlock_unlock(&t->lock);
282
    spinlock_unlock(&t->lock);
283
 
283
 
284
    spinlock_lock(&threads_lock);
284
    spinlock_lock(&threads_lock);
285
    btree_remove(&threads_btree, (btree_key_t) ((uintptr_t ) t), NULL);
285
    btree_remove(&threads_btree, (btree_key_t) ((uintptr_t ) t), NULL);
286
    spinlock_unlock(&threads_lock);
286
    spinlock_unlock(&threads_lock);
287
 
287
 
288
    /*
288
    /*
289
     * Detach from the containing task.
289
     * Detach from the containing task.
290
     */
290
     */
291
    spinlock_lock(&t->task->lock);
291
    spinlock_lock(&t->task->lock);
292
    list_remove(&t->th_link);
292
    list_remove(&t->th_link);
293
    if (--t->task->refcount == 0) {
293
    if (--t->task->refcount == 0) {
294
        t->task->accept_new_threads = false;
294
        t->task->accept_new_threads = false;
295
        destroy_task = true;
295
        destroy_task = true;
296
    }
296
    }
297
    spinlock_unlock(&t->task->lock);   
297
    spinlock_unlock(&t->task->lock);   
298
   
298
   
299
    if (destroy_task)
299
    if (destroy_task)
300
        task_destroy(t->task);
300
        task_destroy(t->task);
301
   
301
   
-
 
302
    /*
-
 
303
     * If the thread had a userspace context, free up its kernel_uarg
-
 
304
     * structure.
-
 
305
     */
-
 
306
    if (t->flags & THREAD_FLAG_USPACE) {
-
 
307
        ASSERT(t->thread_arg);
-
 
308
        free(t->thread_arg);
-
 
309
    }
-
 
310
 
302
    slab_free(thread_slab, t);
311
    slab_free(thread_slab, t);
303
}
312
}
304
 
313
 
305
/** Create new thread
314
/** Create new thread
306
 *
315
 *
307
 * Create a new thread.
316
 * Create a new thread.
308
 *
317
 *
309
 * @param func      Thread's implementing function.
318
 * @param func      Thread's implementing function.
310
 * @param arg       Thread's implementing function argument.
319
 * @param arg       Thread's implementing function argument.
311
 * @param task      Task to which the thread belongs.
320
 * @param task      Task to which the thread belongs.
312
 * @param flags     Thread flags.
321
 * @param flags     Thread flags.
313
 * @param name      Symbolic name.
322
 * @param name      Symbolic name.
314
 * @param uncounted Thread's accounting doesn't affect accumulated task
323
 * @param uncounted Thread's accounting doesn't affect accumulated task
315
 *   accounting.
324
 *          accounting.
316
 *
325
 *
317
 * @return New thread's structure on success, NULL on failure.
326
 * @return New thread's structure on success, NULL on failure.
318
 *
327
 *
319
 */
328
 */
320
thread_t *thread_create(void (* func)(void *), void *arg, task_t *task,
329
thread_t *thread_create(void (* func)(void *), void *arg, task_t *task,
321
    int flags, char *name, bool uncounted)
330
    int flags, char *name, bool uncounted)
322
{
331
{
323
    thread_t *t;
332
    thread_t *t;
324
    ipl_t ipl;
333
    ipl_t ipl;
325
   
334
   
326
    t = (thread_t *) slab_alloc(thread_slab, 0);
335
    t = (thread_t *) slab_alloc(thread_slab, 0);
327
    if (!t)
336
    if (!t)
328
        return NULL;
337
        return NULL;
329
   
338
   
330
    /* Not needed, but good for debugging */
339
    /* Not needed, but good for debugging */
331
    memsetb((uintptr_t) t->kstack, THREAD_STACK_SIZE * 1 << STACK_FRAMES,
340
    memsetb((uintptr_t) t->kstack, THREAD_STACK_SIZE * 1 << STACK_FRAMES,
332
        0);
341
        0);
333
   
342
   
334
    ipl = interrupts_disable();
343
    ipl = interrupts_disable();
335
    spinlock_lock(&tidlock);
344
    spinlock_lock(&tidlock);
336
    t->tid = ++last_tid;
345
    t->tid = ++last_tid;
337
    spinlock_unlock(&tidlock);
346
    spinlock_unlock(&tidlock);
338
    interrupts_restore(ipl);
347
    interrupts_restore(ipl);
339
   
348
   
340
    context_save(&t->saved_context);
349
    context_save(&t->saved_context);
341
    context_set(&t->saved_context, FADDR(cushion), (uintptr_t) t->kstack,
350
    context_set(&t->saved_context, FADDR(cushion), (uintptr_t) t->kstack,
342
        THREAD_STACK_SIZE);
351
        THREAD_STACK_SIZE);
343
   
352
   
344
    the_initialize((the_t *) t->kstack);
353
    the_initialize((the_t *) t->kstack);
345
   
354
   
346
    ipl = interrupts_disable();
355
    ipl = interrupts_disable();
347
    t->saved_context.ipl = interrupts_read();
356
    t->saved_context.ipl = interrupts_read();
348
    interrupts_restore(ipl);
357
    interrupts_restore(ipl);
349
   
358
   
350
    memcpy(t->name, name, THREAD_NAME_BUFLEN);
359
    memcpy(t->name, name, THREAD_NAME_BUFLEN);
351
   
360
   
352
    t->thread_code = func;
361
    t->thread_code = func;
353
    t->thread_arg = arg;
362
    t->thread_arg = arg;
354
    t->ticks = -1;
363
    t->ticks = -1;
355
    t->cycles = 0;
364
    t->cycles = 0;
356
    t->uncounted = uncounted;
365
    t->uncounted = uncounted;
357
    t->priority = -1;       /* start in rq[0] */
366
    t->priority = -1;       /* start in rq[0] */
358
    t->cpu = NULL;
367
    t->cpu = NULL;
359
    t->flags = flags;
368
    t->flags = flags;
360
    t->state = Entering;
369
    t->state = Entering;
361
    t->call_me = NULL;
370
    t->call_me = NULL;
362
    t->call_me_with = NULL;
371
    t->call_me_with = NULL;
363
   
372
   
364
    timeout_initialize(&t->sleep_timeout);
373
    timeout_initialize(&t->sleep_timeout);
365
    t->sleep_interruptible = false;
374
    t->sleep_interruptible = false;
366
    t->sleep_queue = NULL;
375
    t->sleep_queue = NULL;
367
    t->timeout_pending = 0;
376
    t->timeout_pending = 0;
368
 
377
 
369
    t->in_copy_from_uspace = false;
378
    t->in_copy_from_uspace = false;
370
    t->in_copy_to_uspace = false;
379
    t->in_copy_to_uspace = false;
371
 
380
 
372
    t->interrupted = false;
381
    t->interrupted = false;
373
    t->join_type = None;
382
    t->join_type = None;
374
    t->detached = false;
383
    t->detached = false;
375
    waitq_initialize(&t->join_wq);
384
    waitq_initialize(&t->join_wq);
376
   
385
   
377
    t->rwlock_holder_type = RWLOCK_NONE;
386
    t->rwlock_holder_type = RWLOCK_NONE;
378
       
387
       
379
    t->task = task;
388
    t->task = task;
380
   
389
   
381
    t->fpu_context_exists = 0;
390
    t->fpu_context_exists = 0;
382
    t->fpu_context_engaged = 0;
391
    t->fpu_context_engaged = 0;
383
 
392
 
384
    /* might depend on previous initialization */
393
    /* might depend on previous initialization */
385
    thread_create_arch(t); 
394
    thread_create_arch(t); 
386
   
395
   
387
    /*
396
    /*
388
     * Attach to the containing task.
397
     * Attach to the containing task.
389
     */
398
     */
390
    ipl = interrupts_disable();  
399
    ipl = interrupts_disable();  
391
    spinlock_lock(&task->lock);
400
    spinlock_lock(&task->lock);
392
    if (!task->accept_new_threads) {
401
    if (!task->accept_new_threads) {
393
        spinlock_unlock(&task->lock);
402
        spinlock_unlock(&task->lock);
394
        slab_free(thread_slab, t);
403
        slab_free(thread_slab, t);
395
        interrupts_restore(ipl);
404
        interrupts_restore(ipl);
396
        return NULL;
405
        return NULL;
397
    }
406
    }
398
    list_append(&t->th_link, &task->th_head);
407
    list_append(&t->th_link, &task->th_head);
399
    if (task->refcount++ == 0)
408
    if (task->refcount++ == 0)
400
        task->main_thread = t;
409
        task->main_thread = t;
401
    spinlock_unlock(&task->lock);
410
    spinlock_unlock(&task->lock);
402
 
411
 
403
    /*
412
    /*
404
     * Register this thread in the system-wide list.
413
     * Register this thread in the system-wide list.
405
     */
414
     */
406
    spinlock_lock(&threads_lock);
415
    spinlock_lock(&threads_lock);
407
    btree_insert(&threads_btree, (btree_key_t) ((uintptr_t) t), (void *) t,
416
    btree_insert(&threads_btree, (btree_key_t) ((uintptr_t) t), (void *) t,
408
        NULL);
417
        NULL);
409
    spinlock_unlock(&threads_lock);
418
    spinlock_unlock(&threads_lock);
410
   
419
   
411
    interrupts_restore(ipl);
420
    interrupts_restore(ipl);
412
   
421
   
413
    return t;
422
    return t;
414
}
423
}
415
 
424
 
416
/** Terminate thread.
425
/** Terminate thread.
417
 *
426
 *
418
 * End current thread execution and switch it to the exiting state. All pending
427
 * End current thread execution and switch it to the exiting state. All pending
419
 * timeouts are executed.
428
 * timeouts are executed.
420
 */
429
 */
421
void thread_exit(void)
430
void thread_exit(void)
422
{
431
{
423
    ipl_t ipl;
432
    ipl_t ipl;
424
 
433
 
425
restart:
434
restart:
426
    ipl = interrupts_disable();
435
    ipl = interrupts_disable();
427
    spinlock_lock(&THREAD->lock);
436
    spinlock_lock(&THREAD->lock);
428
    if (THREAD->timeout_pending) {
437
    if (THREAD->timeout_pending) {
429
        /* busy waiting for timeouts in progress */
438
        /* busy waiting for timeouts in progress */
430
        spinlock_unlock(&THREAD->lock);
439
        spinlock_unlock(&THREAD->lock);
431
        interrupts_restore(ipl);
440
        interrupts_restore(ipl);
432
        goto restart;
441
        goto restart;
433
    }
442
    }
434
    THREAD->state = Exiting;
443
    THREAD->state = Exiting;
435
    spinlock_unlock(&THREAD->lock);
444
    spinlock_unlock(&THREAD->lock);
436
    scheduler();
445
    scheduler();
437
 
446
 
438
    /* Not reached */
447
    /* Not reached */
439
    while (1)
448
    while (1)
440
        ;
449
        ;
441
}
450
}
442
 
451
 
443
 
452
 
444
/** Thread sleep
453
/** Thread sleep
445
 *
454
 *
446
 * Suspend execution of the current thread.
455
 * Suspend execution of the current thread.
447
 *
456
 *
448
 * @param sec Number of seconds to sleep.
457
 * @param sec Number of seconds to sleep.
449
 *
458
 *
450
 */
459
 */
451
void thread_sleep(uint32_t sec)
460
void thread_sleep(uint32_t sec)
452
{
461
{
453
    thread_usleep(sec * 1000000);
462
    thread_usleep(sec * 1000000);
454
}
463
}
455
 
464
 
456
/** Wait for another thread to exit.
465
/** Wait for another thread to exit.
457
 *
466
 *
458
 * @param t Thread to join on exit.
467
 * @param t Thread to join on exit.
459
 * @param usec Timeout in microseconds.
468
 * @param usec Timeout in microseconds.
460
 * @param flags Mode of operation.
469
 * @param flags Mode of operation.
461
 *
470
 *
462
 * @return An error code from errno.h or an error code from synch.h.
471
 * @return An error code from errno.h or an error code from synch.h.
463
 */
472
 */
464
int thread_join_timeout(thread_t *t, uint32_t usec, int flags)
473
int thread_join_timeout(thread_t *t, uint32_t usec, int flags)
465
{
474
{
466
    ipl_t ipl;
475
    ipl_t ipl;
467
    int rc;
476
    int rc;
468
 
477
 
469
    if (t == THREAD)
478
    if (t == THREAD)
470
        return EINVAL;
479
        return EINVAL;
471
 
480
 
472
    /*
481
    /*
473
     * Since thread join can only be called once on an undetached thread,
482
     * Since thread join can only be called once on an undetached thread,
474
     * the thread pointer is guaranteed to be still valid.
483
     * the thread pointer is guaranteed to be still valid.
475
     */
484
     */
476
   
485
   
477
    ipl = interrupts_disable();
486
    ipl = interrupts_disable();
478
    spinlock_lock(&t->lock);
487
    spinlock_lock(&t->lock);
479
    ASSERT(!t->detached);
488
    ASSERT(!t->detached);
480
    spinlock_unlock(&t->lock);
489
    spinlock_unlock(&t->lock);
481
    interrupts_restore(ipl);
490
    interrupts_restore(ipl);
482
   
491
   
483
    rc = waitq_sleep_timeout(&t->join_wq, usec, flags);
492
    rc = waitq_sleep_timeout(&t->join_wq, usec, flags);
484
   
493
   
485
    return rc; 
494
    return rc; 
486
}
495
}
487
 
496
 
488
/** Detach thread.
497
/** Detach thread.
489
 *
498
 *
490
 * Mark the thread as detached, if the thread is already in the Undead state,
499
 * Mark the thread as detached, if the thread is already in the Undead state,
491
 * deallocate its resources.
500
 * deallocate its resources.
492
 *
501
 *
493
 * @param t Thread to be detached.
502
 * @param t Thread to be detached.
494
 */
503
 */
495
void thread_detach(thread_t *t)
504
void thread_detach(thread_t *t)
496
{
505
{
497
    ipl_t ipl;
506
    ipl_t ipl;
498
 
507
 
499
    /*
508
    /*
500
     * Since the thread is expected not to be already detached,
509
     * Since the thread is expected not to be already detached,
501
     * pointer to it must be still valid.
510
     * pointer to it must be still valid.
502
     */
511
     */
503
    ipl = interrupts_disable();
512
    ipl = interrupts_disable();
504
    spinlock_lock(&t->lock);
513
    spinlock_lock(&t->lock);
505
    ASSERT(!t->detached);
514
    ASSERT(!t->detached);
506
    if (t->state == Undead) {
515
    if (t->state == Undead) {
507
        thread_destroy(t);  /* unlocks &t->lock */
516
        thread_destroy(t);  /* unlocks &t->lock */
508
        interrupts_restore(ipl);
517
        interrupts_restore(ipl);
509
        return;
518
        return;
510
    } else {
519
    } else {
511
        t->detached = true;
520
        t->detached = true;
512
    }
521
    }
513
    spinlock_unlock(&t->lock);
522
    spinlock_unlock(&t->lock);
514
    interrupts_restore(ipl);
523
    interrupts_restore(ipl);
515
}
524
}
516
 
525
 
517
/** Thread usleep
526
/** Thread usleep
518
 *
527
 *
519
 * Suspend execution of the current thread.
528
 * Suspend execution of the current thread.
520
 *
529
 *
521
 * @param usec Number of microseconds to sleep.
530
 * @param usec Number of microseconds to sleep.
522
 *
531
 *
523
 */
532
 */
524
void thread_usleep(uint32_t usec)
533
void thread_usleep(uint32_t usec)
525
{
534
{
526
    waitq_t wq;
535
    waitq_t wq;
527
                 
536
                 
528
    waitq_initialize(&wq);
537
    waitq_initialize(&wq);
529
 
538
 
530
    (void) waitq_sleep_timeout(&wq, usec, SYNCH_FLAGS_NON_BLOCKING);
539
    (void) waitq_sleep_timeout(&wq, usec, SYNCH_FLAGS_NON_BLOCKING);
531
}
540
}
532
 
541
 
533
/** Register thread out-of-context invocation
542
/** Register thread out-of-context invocation
534
 *
543
 *
535
 * Register a function and its argument to be executed
544
 * Register a function and its argument to be executed
536
 * on next context switch to the current thread.
545
 * on next context switch to the current thread.
537
 *
546
 *
538
 * @param call_me      Out-of-context function.
547
 * @param call_me      Out-of-context function.
539
 * @param call_me_with Out-of-context function argument.
548
 * @param call_me_with Out-of-context function argument.
540
 *
549
 *
541
 */
550
 */
542
void thread_register_call_me(void (* call_me)(void *), void *call_me_with)
551
void thread_register_call_me(void (* call_me)(void *), void *call_me_with)
543
{
552
{
544
    ipl_t ipl;
553
    ipl_t ipl;
545
   
554
   
546
    ipl = interrupts_disable();
555
    ipl = interrupts_disable();
547
    spinlock_lock(&THREAD->lock);
556
    spinlock_lock(&THREAD->lock);
548
    THREAD->call_me = call_me;
557
    THREAD->call_me = call_me;
549
    THREAD->call_me_with = call_me_with;
558
    THREAD->call_me_with = call_me_with;
550
    spinlock_unlock(&THREAD->lock);
559
    spinlock_unlock(&THREAD->lock);
551
    interrupts_restore(ipl);
560
    interrupts_restore(ipl);
552
}
561
}
553
 
562
 
554
/** Print list of threads debug info */
563
/** Print list of threads debug info */
555
void thread_print_list(void)
564
void thread_print_list(void)
556
{
565
{
557
    link_t *cur;
566
    link_t *cur;
558
    ipl_t ipl;
567
    ipl_t ipl;
559
   
568
   
560
    /* Messing with thread structures, avoid deadlock */
569
    /* Messing with thread structures, avoid deadlock */
561
    ipl = interrupts_disable();
570
    ipl = interrupts_disable();
562
    spinlock_lock(&threads_lock);
571
    spinlock_lock(&threads_lock);
563
   
572
   
564
    printf("tid    name       address    state    task       ctx code    "
573
    printf("tid    name       address    state    task       ctx code    "
565
        "   stack      cycles     cpu  kstack     waitqueue\n");
574
        "   stack      cycles     cpu  kstack     waitqueue\n");
566
    printf("------ ---------- ---------- -------- ---------- --- --------"
575
    printf("------ ---------- ---------- -------- ---------- --- --------"
567
        "-- ---------- ---------- ---- ---------- ----------\n");
576
        "-- ---------- ---------- ---- ---------- ----------\n");
568
 
577
 
569
    for (cur = threads_btree.leaf_head.next;
578
    for (cur = threads_btree.leaf_head.next;
570
        cur != &threads_btree.leaf_head; cur = cur->next) {
579
        cur != &threads_btree.leaf_head; cur = cur->next) {
571
        btree_node_t *node;
580
        btree_node_t *node;
572
        unsigned int i;
581
        unsigned int i;
573
 
582
 
574
        node = list_get_instance(cur, btree_node_t, leaf_link);
583
        node = list_get_instance(cur, btree_node_t, leaf_link);
575
        for (i = 0; i < node->keys; i++) {
584
        for (i = 0; i < node->keys; i++) {
576
            thread_t *t;
585
            thread_t *t;
577
       
586
       
578
            t = (thread_t *) node->value[i];
587
            t = (thread_t *) node->value[i];
579
           
588
           
580
            uint64_t cycles;
589
            uint64_t cycles;
581
            char suffix;
590
            char suffix;
582
            order(t->cycles, &cycles, &suffix);
591
            order(t->cycles, &cycles, &suffix);
583
           
592
           
584
            printf("%-6llu %-10s %#10zx %-8s %#10zx %-3ld %#10zx "
593
            printf("%-6llu %-10s %#10zx %-8s %#10zx %-3ld %#10zx "
585
                "%#10zx %9llu%c ", t->tid, t->name, t,
594
                "%#10zx %9llu%c ", t->tid, t->name, t,
586
                thread_states[t->state], t->task, t->task->context,
595
                thread_states[t->state], t->task, t->task->context,
587
                t->thread_code, t->kstack, cycles, suffix);
596
                t->thread_code, t->kstack, cycles, suffix);
588
           
597
           
589
            if (t->cpu)
598
            if (t->cpu)
590
                printf("%-4zd", t->cpu->id);
599
                printf("%-4zd", t->cpu->id);
591
            else
600
            else
592
                printf("none");
601
                printf("none");
593
           
602
           
594
            if (t->state == Sleeping)
603
            if (t->state == Sleeping)
595
                printf(" %#10zx %#10zx", t->kstack,
604
                printf(" %#10zx %#10zx", t->kstack,
596
                    t->sleep_queue);
605
                    t->sleep_queue);
597
           
606
           
598
            printf("\n");
607
            printf("\n");
599
        }
608
        }
600
    }
609
    }
601
 
610
 
602
    spinlock_unlock(&threads_lock);
611
    spinlock_unlock(&threads_lock);
603
    interrupts_restore(ipl);
612
    interrupts_restore(ipl);
604
}
613
}
605
 
614
 
606
/** Check whether thread exists.
615
/** Check whether thread exists.
607
 *
616
 *
608
 * Note that threads_lock must be already held and
617
 * Note that threads_lock must be already held and
609
 * interrupts must be already disabled.
618
 * interrupts must be already disabled.
610
 *
619
 *
611
 * @param t Pointer to thread.
620
 * @param t Pointer to thread.
612
 *
621
 *
613
 * @return True if thread t is known to the system, false otherwise.
622
 * @return True if thread t is known to the system, false otherwise.
614
 */
623
 */
615
bool thread_exists(thread_t *t)
624
bool thread_exists(thread_t *t)
616
{
625
{
617
    btree_node_t *leaf;
626
    btree_node_t *leaf;
618
   
627
   
619
    return btree_search(&threads_btree, (btree_key_t) ((uintptr_t) t),
628
    return btree_search(&threads_btree, (btree_key_t) ((uintptr_t) t),
620
        &leaf) != NULL;
629
        &leaf) != NULL;
621
}
630
}
622
 
631
 
623
 
632
 
624
/** Update accounting of current thread.
633
/** Update accounting of current thread.
625
 *
634
 *
626
 * Note that thread_lock on THREAD must be already held and
635
 * Note that thread_lock on THREAD must be already held and
627
 * interrupts must be already disabled.
636
 * interrupts must be already disabled.
628
 *
637
 *
629
 */
638
 */
630
void thread_update_accounting(void)
639
void thread_update_accounting(void)
631
{
640
{
632
    uint64_t time = get_cycle();
641
    uint64_t time = get_cycle();
633
    THREAD->cycles += time - THREAD->last_cycle;
642
    THREAD->cycles += time - THREAD->last_cycle;
634
    THREAD->last_cycle = time;
643
    THREAD->last_cycle = time;
635
}
644
}
636
 
645
 
637
/** Process syscall to create new thread.
646
/** Process syscall to create new thread.
638
 *
647
 *
639
 */
648
 */
640
unative_t sys_thread_create(uspace_arg_t *uspace_uarg, char *uspace_name, thread_id_t *uspace_thread_id)
649
unative_t sys_thread_create(uspace_arg_t *uspace_uarg, char *uspace_name,
-
 
650
    thread_id_t *uspace_thread_id)
641
{
651
{
642
    thread_t *t;
652
    thread_t *t;
643
    char namebuf[THREAD_NAME_BUFLEN];
653
    char namebuf[THREAD_NAME_BUFLEN];
644
    uspace_arg_t *kernel_uarg;
654
    uspace_arg_t *kernel_uarg;
645
    int rc;
655
    int rc;
646
 
656
 
647
    rc = copy_from_uspace(namebuf, uspace_name, THREAD_NAME_BUFLEN);
657
    rc = copy_from_uspace(namebuf, uspace_name, THREAD_NAME_BUFLEN);
648
    if (rc != 0)
658
    if (rc != 0)
649
        return (unative_t) rc;
659
        return (unative_t) rc;
650
 
660
 
651
    kernel_uarg = (uspace_arg_t *) malloc(sizeof(uspace_arg_t), 0);
661
    kernel_uarg = (uspace_arg_t *) malloc(sizeof(uspace_arg_t), 0);
652
    rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
662
    rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
653
    if (rc != 0) {
663
    if (rc != 0) {
654
        free(kernel_uarg);
664
        free(kernel_uarg);
655
        return (unative_t) rc;
665
        return (unative_t) rc;
656
    }
666
    }
657
 
667
 
658
    t = thread_create(uinit, kernel_uarg, TASK, THREAD_FLAG_USPACE, namebuf,
668
    t = thread_create(uinit, kernel_uarg, TASK, THREAD_FLAG_USPACE, namebuf,
659
        false);
669
        false);
660
    if (t) {
670
    if (t) {
661
        thread_ready(t);
671
        thread_ready(t);
662
        if (uspace_thread_id != NULL)
672
        if (uspace_thread_id != NULL)
663
            return (unative_t) copy_to_uspace(uspace_thread_id, &t->tid,
673
            return (unative_t) copy_to_uspace(uspace_thread_id,
664
                sizeof(t->tid));
674
                &t->tid, sizeof(t->tid));
665
        else
675
        else
666
            return 0;
676
            return 0;
667
    } else
677
    } else
668
        free(kernel_uarg);
678
        free(kernel_uarg);
669
 
679
 
670
    return (unative_t) ENOMEM;
680
    return (unative_t) ENOMEM;
671
}
681
}
672
 
682
 
673
/** Process syscall to terminate thread.
683
/** Process syscall to terminate thread.
674
 *
684
 *
675
 */
685
 */
676
unative_t sys_thread_exit(int uspace_status)
686
unative_t sys_thread_exit(int uspace_status)
677
{
687
{
678
    thread_exit();
688
    thread_exit();
679
    /* Unreachable */
689
    /* Unreachable */
680
    return 0;
690
    return 0;
681
}
691
}
682
 
692
 
683
/** Syscall for getting TID.
693
/** Syscall for getting TID.
684
 *
694
 *
685
 * @param uspace_thread_id Userspace address of 8-byte buffer where to store
695
 * @param uspace_thread_id Userspace address of 8-byte buffer where to store
686
 * current thread ID.
696
 * current thread ID.
687
 *
697
 *
688
 * @return 0 on success or an error code from @ref errno.h.
698
 * @return 0 on success or an error code from @ref errno.h.
689
 */
699
 */
690
unative_t sys_thread_get_id(thread_id_t *uspace_thread_id)
700
unative_t sys_thread_get_id(thread_id_t *uspace_thread_id)
691
{
701
{
692
    /*
702
    /*
693
     * No need to acquire lock on THREAD because tid
703
     * No need to acquire lock on THREAD because tid
694
     * remains constant for the lifespan of the thread.
704
     * remains constant for the lifespan of the thread.
695
     */
705
     */
696
    return (unative_t) copy_to_uspace(uspace_thread_id, &THREAD->tid,
706
    return (unative_t) copy_to_uspace(uspace_thread_id, &THREAD->tid,
697
        sizeof(THREAD->tid));
707
        sizeof(THREAD->tid));
698
}
708
}
699
 
709
 
700
/** @}
710
/** @}
701
 */
711
 */
702
 
712