Subversion Repositories HelenOS-historic

Rev

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

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