Subversion Repositories HelenOS-historic

Rev

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

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