Subversion Repositories HelenOS

Rev

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

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