Subversion Repositories HelenOS-historic

Rev

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

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