Subversion Repositories HelenOS-historic

Rev

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

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