Subversion Repositories HelenOS

Rev

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

Rev 2042 Rev 2050
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. For locking rules, see declaration thereof. */
83
/** Lock protecting the threads_btree B+tree. For locking rules, see declaration thereof. */
84
SPINLOCK_INITIALIZE(threads_lock);
84
SPINLOCK_INITIALIZE(threads_lock);
85
 
85
 
86
/** B+tree of all threads.
86
/** B+tree of all threads.
87
 *
87
 *
88
 * When a thread is found in the threads_btree B+tree, it is guaranteed to exist as long
88
 * When a thread is found in the threads_btree B+tree, it is guaranteed to exist as long
89
 * as the threads_lock is held.
89
 * as the threads_lock is held.
90
 */
90
 */
91
btree_t threads_btree;     
91
btree_t threads_btree;     
92
 
92
 
93
SPINLOCK_INITIALIZE(tidlock);
93
SPINLOCK_INITIALIZE(tidlock);
94
uint32_t last_tid = 0;
94
uint32_t last_tid = 0;
95
 
95
 
96
static slab_cache_t *thread_slab;
96
static slab_cache_t *thread_slab;
97
#ifdef ARCH_HAS_FPU
97
#ifdef ARCH_HAS_FPU
98
slab_cache_t *fpu_context_slab;
98
slab_cache_t *fpu_context_slab;
99
#endif
99
#endif
100
 
100
 
101
/** Thread wrapper
101
/** Thread wrapper
102
 *
102
 *
103
 * This wrapper is provided to ensure that every thread
103
 * This wrapper is provided to ensure that every thread
104
 * makes a call to thread_exit() when its implementing
104
 * makes a call to thread_exit() when its implementing
105
 * function returns.
105
 * function returns.
106
 *
106
 *
107
 * interrupts_disable() is assumed.
107
 * interrupts_disable() is assumed.
108
 *
108
 *
109
 */
109
 */
110
static void cushion(void)
110
static void cushion(void)
111
{
111
{
112
    void (*f)(void *) = THREAD->thread_code;
112
    void (*f)(void *) = THREAD->thread_code;
113
    void *arg = THREAD->thread_arg;
113
    void *arg = THREAD->thread_arg;
114
    THREAD->last_cycle = get_cycle();
114
    THREAD->last_cycle = get_cycle();
115
 
115
 
116
    /* This is where each thread wakes up after its creation */
116
    /* This is where each thread wakes up after its creation */
117
    spinlock_unlock(&THREAD->lock);
117
    spinlock_unlock(&THREAD->lock);
118
    interrupts_enable();
118
    interrupts_enable();
119
 
119
 
120
    f(arg);
120
    f(arg);
121
   
121
   
122
    /* Accumulate accounting to the task */
122
    /* Accumulate accounting to the task */
123
    ipl_t ipl = interrupts_disable();
123
    ipl_t ipl = interrupts_disable();
124
   
124
   
125
    spinlock_lock(&THREAD->lock);
125
    spinlock_lock(&THREAD->lock);
126
    if (!THREAD->uncounted) {
126
    if (!THREAD->uncounted) {
127
        thread_update_accounting();
127
        thread_update_accounting();
128
        uint64_t cycles = THREAD->cycles;
128
        uint64_t cycles = THREAD->cycles;
129
        THREAD->cycles = 0;
129
        THREAD->cycles = 0;
130
        spinlock_unlock(&THREAD->lock);
130
        spinlock_unlock(&THREAD->lock);
131
       
131
       
132
        spinlock_lock(&TASK->lock);
132
        spinlock_lock(&TASK->lock);
133
        TASK->cycles += cycles;
133
        TASK->cycles += cycles;
134
        spinlock_unlock(&TASK->lock);
134
        spinlock_unlock(&TASK->lock);
135
    } else
135
    } else
136
        spinlock_unlock(&THREAD->lock);
136
        spinlock_unlock(&THREAD->lock);
137
   
137
   
138
    interrupts_restore(ipl);
138
    interrupts_restore(ipl);
139
   
139
   
140
    thread_exit();
140
    thread_exit();
141
    /* not reached */
141
    /* not reached */
142
}
142
}
143
 
143
 
144
/** Initialization and allocation for thread_t structure */
144
/** Initialization and allocation for thread_t structure */
145
static int thr_constructor(void *obj, int kmflags)
145
static int thr_constructor(void *obj, int kmflags)
146
{
146
{
147
    thread_t *t = (thread_t *) obj;
147
    thread_t *t = (thread_t *) obj;
148
 
148
 
149
    spinlock_initialize(&t->lock, "thread_t_lock");
149
    spinlock_initialize(&t->lock, "thread_t_lock");
150
    link_initialize(&t->rq_link);
150
    link_initialize(&t->rq_link);
151
    link_initialize(&t->wq_link);
151
    link_initialize(&t->wq_link);
152
    link_initialize(&t->th_link);
152
    link_initialize(&t->th_link);
153
 
153
 
154
    /* call the architecture-specific part of the constructor */
154
    /* call the architecture-specific part of the constructor */
155
    thr_constructor_arch(t);
155
    thr_constructor_arch(t);
156
   
156
   
157
#ifdef ARCH_HAS_FPU
157
#ifdef ARCH_HAS_FPU
158
#  ifdef CONFIG_FPU_LAZY
158
#  ifdef CONFIG_FPU_LAZY
159
    t->saved_fpu_context = NULL;
159
    t->saved_fpu_context = NULL;
160
#  else
160
#  else
161
    t->saved_fpu_context = slab_alloc(fpu_context_slab,kmflags);
161
    t->saved_fpu_context = slab_alloc(fpu_context_slab,kmflags);
162
    if (!t->saved_fpu_context)
162
    if (!t->saved_fpu_context)
163
        return -1;
163
        return -1;
164
#  endif
164
#  endif
165
#endif  
165
#endif  
166
 
166
 
167
    t->kstack = frame_alloc(STACK_FRAMES, FRAME_KA | kmflags);
167
    t->kstack = frame_alloc(STACK_FRAMES, FRAME_KA | kmflags);
168
    if (! t->kstack) {
168
    if (! t->kstack) {
169
#ifdef ARCH_HAS_FPU
169
#ifdef ARCH_HAS_FPU
170
        if (t->saved_fpu_context)
170
        if (t->saved_fpu_context)
171
            slab_free(fpu_context_slab,t->saved_fpu_context);
171
            slab_free(fpu_context_slab,t->saved_fpu_context);
172
#endif
172
#endif
173
        return -1;
173
        return -1;
174
    }
174
    }
175
 
175
 
176
    return 0;
176
    return 0;
177
}
177
}
178
 
178
 
179
/** Destruction of thread_t object */
179
/** Destruction of thread_t object */
180
static int thr_destructor(void *obj)
180
static int thr_destructor(void *obj)
181
{
181
{
182
    thread_t *t = (thread_t *) obj;
182
    thread_t *t = (thread_t *) obj;
183
 
183
 
184
    /* call the architecture-specific part of the destructor */
184
    /* call the architecture-specific part of the destructor */
185
    thr_destructor_arch(t);
185
    thr_destructor_arch(t);
186
 
186
 
187
    frame_free(KA2PA(t->kstack));
187
    frame_free(KA2PA(t->kstack));
188
#ifdef ARCH_HAS_FPU
188
#ifdef ARCH_HAS_FPU
189
    if (t->saved_fpu_context)
189
    if (t->saved_fpu_context)
190
        slab_free(fpu_context_slab,t->saved_fpu_context);
190
        slab_free(fpu_context_slab,t->saved_fpu_context);
191
#endif
191
#endif
192
    return 1; /* One page freed */
192
    return 1; /* One page freed */
193
}
193
}
194
 
194
 
195
/** Initialize threads
195
/** Initialize threads
196
 *
196
 *
197
 * Initialize kernel threads support.
197
 * Initialize kernel threads support.
198
 *
198
 *
199
 */
199
 */
200
void thread_init(void)
200
void thread_init(void)
201
{
201
{
202
    THREAD = NULL;
202
    THREAD = NULL;
203
    atomic_set(&nrdy,0);
203
    atomic_set(&nrdy,0);
204
    thread_slab = slab_cache_create("thread_slab",
204
    thread_slab = slab_cache_create("thread_slab",
205
                    sizeof(thread_t),0,
205
                    sizeof(thread_t),0,
206
                    thr_constructor, thr_destructor, 0);
206
                    thr_constructor, thr_destructor, 0);
207
#ifdef ARCH_HAS_FPU
207
#ifdef ARCH_HAS_FPU
208
    fpu_context_slab = slab_cache_create("fpu_slab",
208
    fpu_context_slab = slab_cache_create("fpu_slab",
209
                         sizeof(fpu_context_t),
209
                         sizeof(fpu_context_t),
210
                         FPU_CONTEXT_ALIGN,
210
                         FPU_CONTEXT_ALIGN,
211
                         NULL, NULL, 0);
211
                         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 accounting.
313
 * @param uncounted Thread's accounting doesn't affect accumulated task accounting.
314
 *
314
 *
315
 * @return New thread's structure on success, NULL on failure.
315
 * @return New thread's structure on success, NULL on failure.
316
 *
316
 *
317
 */
317
 */
318
thread_t *thread_create(void (* func)(void *), void *arg, task_t *task, int flags, char *name, bool uncounted)
318
thread_t *thread_create(void (* func)(void *), void *arg, task_t *task, int flags, char *name, bool uncounted)
319
{
319
{
320
    thread_t *t;
320
    thread_t *t;
321
    ipl_t ipl;
321
    ipl_t ipl;
322
   
322
   
323
    t = (thread_t *) slab_alloc(thread_slab, 0);
323
    t = (thread_t *) slab_alloc(thread_slab, 0);
324
    if (!t)
324
    if (!t)
325
        return NULL;
325
        return NULL;
326
   
326
   
327
    /* Not needed, but good for debugging */
327
    /* Not needed, but good for debugging */
328
    memsetb((uintptr_t) t->kstack, THREAD_STACK_SIZE * 1 << STACK_FRAMES, 0);
328
    memsetb((uintptr_t) t->kstack, THREAD_STACK_SIZE * 1 << STACK_FRAMES, 0);
329
   
329
   
330
    ipl = interrupts_disable();
330
    ipl = interrupts_disable();
331
    spinlock_lock(&tidlock);
331
    spinlock_lock(&tidlock);
332
    t->tid = ++last_tid;
332
    t->tid = ++last_tid;
333
    spinlock_unlock(&tidlock);
333
    spinlock_unlock(&tidlock);
334
    interrupts_restore(ipl);
334
    interrupts_restore(ipl);
335
   
335
   
336
    context_save(&t->saved_context);
336
    context_save(&t->saved_context);
337
    context_set(&t->saved_context, FADDR(cushion), (uintptr_t) t->kstack, THREAD_STACK_SIZE);
337
    context_set(&t->saved_context, FADDR(cushion), (uintptr_t) t->kstack, THREAD_STACK_SIZE);
338
   
338
   
339
    the_initialize((the_t *) t->kstack);
339
    the_initialize((the_t *) t->kstack);
340
   
340
   
341
    ipl = interrupts_disable();
341
    ipl = interrupts_disable();
342
    t->saved_context.ipl = interrupts_read();
342
    t->saved_context.ipl = interrupts_read();
343
    interrupts_restore(ipl);
343
    interrupts_restore(ipl);
344
   
344
   
345
    memcpy(t->name, name, THREAD_NAME_BUFLEN);
345
    memcpy(t->name, name, THREAD_NAME_BUFLEN);
346
   
346
   
347
    t->thread_code = func;
347
    t->thread_code = func;
348
    t->thread_arg = arg;
348
    t->thread_arg = arg;
349
    t->ticks = -1;
349
    t->ticks = -1;
350
    t->cycles = 0;
350
    t->cycles = 0;
351
    t->uncounted = uncounted;
351
    t->uncounted = uncounted;
352
    t->priority = -1;       /* start in rq[0] */
352
    t->priority = -1;       /* start in rq[0] */
353
    t->cpu = NULL;
353
    t->cpu = NULL;
354
    t->flags = flags;
354
    t->flags = flags;
355
    t->state = Entering;
355
    t->state = Entering;
356
    t->call_me = NULL;
356
    t->call_me = NULL;
357
    t->call_me_with = NULL;
357
    t->call_me_with = NULL;
358
   
358
   
359
    timeout_initialize(&t->sleep_timeout);
359
    timeout_initialize(&t->sleep_timeout);
360
    t->sleep_interruptible = false;
360
    t->sleep_interruptible = false;
361
    t->sleep_queue = NULL;
361
    t->sleep_queue = NULL;
362
    t->timeout_pending = 0;
362
    t->timeout_pending = 0;
363
 
363
 
364
    t->in_copy_from_uspace = false;
364
    t->in_copy_from_uspace = false;
365
    t->in_copy_to_uspace = false;
365
    t->in_copy_to_uspace = false;
366
 
366
 
367
    t->interrupted = false;
367
    t->interrupted = false;
368
    t->join_type = None;
368
    t->join_type = None;
369
    t->detached = false;
369
    t->detached = false;
370
    waitq_initialize(&t->join_wq);
370
    waitq_initialize(&t->join_wq);
371
   
371
   
372
    t->rwlock_holder_type = RWLOCK_NONE;
372
    t->rwlock_holder_type = RWLOCK_NONE;
373
       
373
       
374
    t->task = task;
374
    t->task = task;
375
   
375
   
376
    t->fpu_context_exists = 0;
376
    t->fpu_context_exists = 0;
377
    t->fpu_context_engaged = 0;
377
    t->fpu_context_engaged = 0;
378
 
378
 
379
    thread_create_arch(t);      /* might depend on previous initialization */
379
    thread_create_arch(t);      /* might depend on previous initialization */
380
   
380
   
381
    /*
381
    /*
382
     * Attach to the containing task.
382
     * Attach to the containing task.
383
     */
383
     */
384
    ipl = interrupts_disable();  
384
    ipl = interrupts_disable();  
385
    spinlock_lock(&task->lock);
385
    spinlock_lock(&task->lock);
386
    if (!task->accept_new_threads) {
386
    if (!task->accept_new_threads) {
387
        spinlock_unlock(&task->lock);
387
        spinlock_unlock(&task->lock);
388
        slab_free(thread_slab, t);
388
        slab_free(thread_slab, t);
389
        interrupts_restore(ipl);
389
        interrupts_restore(ipl);
390
        return NULL;
390
        return NULL;
391
    }
391
    }
392
    list_append(&t->th_link, &task->th_head);
392
    list_append(&t->th_link, &task->th_head);
393
    if (task->refcount++ == 0)
393
    if (task->refcount++ == 0)
394
        task->main_thread = t;
394
        task->main_thread = t;
395
    spinlock_unlock(&task->lock);
395
    spinlock_unlock(&task->lock);
396
 
396
 
397
    /*
397
    /*
398
     * Register this thread in the system-wide list.
398
     * Register this thread in the system-wide list.
399
     */
399
     */
400
    spinlock_lock(&threads_lock);
400
    spinlock_lock(&threads_lock);
401
    btree_insert(&threads_btree, (btree_key_t) ((uintptr_t) t), (void *) t, NULL);
401
    btree_insert(&threads_btree, (btree_key_t) ((uintptr_t) t), (void *) t, NULL);
402
    spinlock_unlock(&threads_lock);
402
    spinlock_unlock(&threads_lock);
403
   
403
   
404
    interrupts_restore(ipl);
404
    interrupts_restore(ipl);
405
   
405
   
406
    return t;
406
    return t;
407
}
407
}
408
 
408
 
409
/** Terminate thread.
409
/** Terminate thread.
410
 *
410
 *
411
 * End current thread execution and switch it to the exiting
411
 * End current thread execution and switch it to the exiting
412
 * state. All pending timeouts are executed.
412
 * state. All pending timeouts are executed.
413
 *
413
 *
414
 */
414
 */
415
void thread_exit(void)
415
void thread_exit(void)
416
{
416
{
417
    ipl_t ipl;
417
    ipl_t ipl;
418
 
418
 
419
restart:
419
restart:
420
    ipl = interrupts_disable();
420
    ipl = interrupts_disable();
421
    spinlock_lock(&THREAD->lock);
421
    spinlock_lock(&THREAD->lock);
422
    if (THREAD->timeout_pending) { /* busy waiting for timeouts in progress */
422
    if (THREAD->timeout_pending) { /* busy waiting for timeouts in progress */
423
        spinlock_unlock(&THREAD->lock);
423
        spinlock_unlock(&THREAD->lock);
424
        interrupts_restore(ipl);
424
        interrupts_restore(ipl);
425
        goto restart;
425
        goto restart;
426
    }
426
    }
427
    THREAD->state = Exiting;
427
    THREAD->state = Exiting;
428
    spinlock_unlock(&THREAD->lock);
428
    spinlock_unlock(&THREAD->lock);
429
    scheduler();
429
    scheduler();
430
 
430
 
431
    /* Not reached */
431
    /* Not reached */
432
    while (1)
432
    while (1)
433
        ;
433
        ;
434
}
434
}
435
 
435
 
436
 
436
 
437
/** Thread sleep
437
/** Thread sleep
438
 *
438
 *
439
 * Suspend execution of the current thread.
439
 * Suspend execution of the current thread.
440
 *
440
 *
441
 * @param sec Number of seconds to sleep.
441
 * @param sec Number of seconds to sleep.
442
 *
442
 *
443
 */
443
 */
444
void thread_sleep(uint32_t sec)
444
void thread_sleep(uint32_t sec)
445
{
445
{
446
    thread_usleep(sec*1000000);
446
    thread_usleep(sec*1000000);
447
}
447
}
448
 
448
 
449
/** Wait for another thread to exit.
449
/** Wait for another thread to exit.
450
 *
450
 *
451
 * @param t Thread to join on exit.
451
 * @param t Thread to join on exit.
452
 * @param usec Timeout in microseconds.
452
 * @param usec Timeout in microseconds.
453
 * @param flags Mode of operation.
453
 * @param flags Mode of operation.
454
 *
454
 *
455
 * @return An error code from errno.h or an error code from synch.h.
455
 * @return An error code from errno.h or an error code from synch.h.
456
 */
456
 */
457
int thread_join_timeout(thread_t *t, uint32_t usec, int flags)
457
int thread_join_timeout(thread_t *t, uint32_t usec, int flags)
458
{
458
{
459
    ipl_t ipl;
459
    ipl_t ipl;
460
    int rc;
460
    int rc;
461
 
461
 
462
    if (t == THREAD)
462
    if (t == THREAD)
463
        return EINVAL;
463
        return EINVAL;
464
 
464
 
465
    /*
465
    /*
466
     * Since thread join can only be called once on an undetached thread,
466
     * Since thread join can only be called once on an undetached thread,
467
     * the thread pointer is guaranteed to be still valid.
467
     * the thread pointer is guaranteed to be still valid.
468
     */
468
     */
469
   
469
   
470
    ipl = interrupts_disable();
470
    ipl = interrupts_disable();
471
    spinlock_lock(&t->lock);
471
    spinlock_lock(&t->lock);
472
    ASSERT(!t->detached);
472
    ASSERT(!t->detached);
473
    spinlock_unlock(&t->lock);
473
    spinlock_unlock(&t->lock);
474
    interrupts_restore(ipl);
474
    interrupts_restore(ipl);
475
   
475
   
476
    rc = waitq_sleep_timeout(&t->join_wq, usec, flags);
476
    rc = waitq_sleep_timeout(&t->join_wq, usec, flags);
477
   
477
   
478
    return rc; 
478
    return rc; 
479
}
479
}
480
 
480
 
481
/** Detach thread.
481
/** Detach thread.
482
 *
482
 *
483
 * Mark the thread as detached, if the thread is already in the Undead state,
483
 * Mark the thread as detached, if the thread is already in the Undead state,
484
 * deallocate its resources.
484
 * deallocate its resources.
485
 *
485
 *
486
 * @param t Thread to be detached.
486
 * @param t Thread to be detached.
487
 */
487
 */
488
void thread_detach(thread_t *t)
488
void thread_detach(thread_t *t)
489
{
489
{
490
    ipl_t ipl;
490
    ipl_t ipl;
491
 
491
 
492
    /*
492
    /*
493
     * Since the thread is expected to not be already detached,
493
     * Since the thread is expected to not be already detached,
494
     * pointer to it must be still valid.
494
     * pointer to it must be still valid.
495
     */
495
     */
496
    ipl = interrupts_disable();
496
    ipl = interrupts_disable();
497
    spinlock_lock(&t->lock);
497
    spinlock_lock(&t->lock);
498
    ASSERT(!t->detached);
498
    ASSERT(!t->detached);
499
    if (t->state == Undead) {
499
    if (t->state == Undead) {
500
        thread_destroy(t);  /* unlocks &t->lock */
500
        thread_destroy(t);  /* unlocks &t->lock */
501
        interrupts_restore(ipl);
501
        interrupts_restore(ipl);
502
        return;
502
        return;
503
    } else {
503
    } else {
504
        t->detached = true;
504
        t->detached = true;
505
    }
505
    }
506
    spinlock_unlock(&t->lock);
506
    spinlock_unlock(&t->lock);
507
    interrupts_restore(ipl);
507
    interrupts_restore(ipl);
508
}
508
}
509
 
509
 
510
/** Thread usleep
510
/** Thread usleep
511
 *
511
 *
512
 * Suspend execution of the current thread.
512
 * Suspend execution of the current thread.
513
 *
513
 *
514
 * @param usec Number of microseconds to sleep.
514
 * @param usec Number of microseconds to sleep.
515
 *
515
 *
516
 */
516
 */
517
void thread_usleep(uint32_t usec)
517
void thread_usleep(uint32_t usec)
518
{
518
{
519
    waitq_t wq;
519
    waitq_t wq;
520
                 
520
                 
521
    waitq_initialize(&wq);
521
    waitq_initialize(&wq);
522
 
522
 
523
    (void) waitq_sleep_timeout(&wq, usec, SYNCH_FLAGS_NON_BLOCKING);
523
    (void) waitq_sleep_timeout(&wq, usec, SYNCH_FLAGS_NON_BLOCKING);
524
}
524
}
525
 
525
 
526
/** Register thread out-of-context invocation
526
/** Register thread out-of-context invocation
527
 *
527
 *
528
 * Register a function and its argument to be executed
528
 * Register a function and its argument to be executed
529
 * on next context switch to the current thread.
529
 * on next context switch to the current thread.
530
 *
530
 *
531
 * @param call_me      Out-of-context function.
531
 * @param call_me      Out-of-context function.
532
 * @param call_me_with Out-of-context function argument.
532
 * @param call_me_with Out-of-context function argument.
533
 *
533
 *
534
 */
534
 */
535
void thread_register_call_me(void (* call_me)(void *), void *call_me_with)
535
void thread_register_call_me(void (* call_me)(void *), void *call_me_with)
536
{
536
{
537
    ipl_t ipl;
537
    ipl_t ipl;
538
   
538
   
539
    ipl = interrupts_disable();
539
    ipl = interrupts_disable();
540
    spinlock_lock(&THREAD->lock);
540
    spinlock_lock(&THREAD->lock);
541
    THREAD->call_me = call_me;
541
    THREAD->call_me = call_me;
542
    THREAD->call_me_with = call_me_with;
542
    THREAD->call_me_with = call_me_with;
543
    spinlock_unlock(&THREAD->lock);
543
    spinlock_unlock(&THREAD->lock);
544
    interrupts_restore(ipl);
544
    interrupts_restore(ipl);
545
}
545
}
546
 
546
 
547
/** Print list of threads debug info */
547
/** Print list of threads debug info */
548
void thread_print_list(void)
548
void thread_print_list(void)
549
{
549
{
550
    link_t *cur;
550
    link_t *cur;
551
    ipl_t ipl;
551
    ipl_t ipl;
552
   
552
   
553
    /* Messing with thread structures, avoid deadlock */
553
    /* Messing with thread structures, avoid deadlock */
554
    ipl = interrupts_disable();
554
    ipl = interrupts_disable();
555
    spinlock_lock(&threads_lock);
555
    spinlock_lock(&threads_lock);
556
   
556
   
557
    printf("tid    name       address    state    task       ctx code       stack      cycles     cpu  kstack     waitqueue\n");
557
    printf("tid    name       address    state    task       ctx code       stack      cycles     cpu  kstack     waitqueue\n");
558
    printf("------ ---------- ---------- -------- ---------- --- ---------- ---------- ---------- ---- ---------- ----------\n");
558
    printf("------ ---------- ---------- -------- ---------- --- ---------- ---------- ---------- ---- ---------- ----------\n");
559
 
559
 
560
    for (cur = threads_btree.leaf_head.next; cur != &threads_btree.leaf_head; cur = cur->next) {
560
    for (cur = threads_btree.leaf_head.next; cur != &threads_btree.leaf_head; cur = cur->next) {
561
        btree_node_t *node;
561
        btree_node_t *node;
562
        int i;
562
        int i;
563
 
563
 
564
        node = list_get_instance(cur, btree_node_t, leaf_link);
564
        node = list_get_instance(cur, btree_node_t, leaf_link);
565
        for (i = 0; i < node->keys; i++) {
565
        for (i = 0; i < node->keys; i++) {
566
            thread_t *t;
566
            thread_t *t;
567
       
567
       
568
            t = (thread_t *) node->value[i];
568
            t = (thread_t *) node->value[i];
569
           
569
           
570
            uint64_t cycles;
570
            uint64_t cycles;
571
            char suffix;
571
            char suffix;
572
           
-
 
573
            if (t->cycles > 1000000000000000000LL) {
-
 
574
                cycles = t->cycles / 1000000000000000000LL;
-
 
575
                suffix = 'E';
-
 
576
            } else if (t->cycles > 1000000000000LL) {
-
 
577
                cycles = t->cycles / 1000000000000LL;
-
 
578
                suffix = 'T';
-
 
579
            } else if (t->cycles > 1000000LL) {
-
 
580
                cycles = t->cycles / 1000000LL;
572
            order(t->cycles, &cycles, &suffix);
581
                suffix = 'M';
-
 
582
            } else {
-
 
583
                cycles = t->cycles;
-
 
584
                suffix = ' ';
-
 
585
            }
-
 
586
           
573
           
587
            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);
574
            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);
588
           
575
           
589
            if (t->cpu)
576
            if (t->cpu)
590
                printf("%-4zd", t->cpu->id);
577
                printf("%-4zd", t->cpu->id);
591
            else
578
            else
592
                printf("none");
579
                printf("none");
593
           
580
           
594
            if (t->state == Sleeping)
581
            if (t->state == Sleeping)
595
                printf(" %#10zx %#10zx", t->kstack, t->sleep_queue);
582
                printf(" %#10zx %#10zx", t->kstack, t->sleep_queue);
596
           
583
           
597
            printf("\n");
584
            printf("\n");
598
        }
585
        }
599
    }
586
    }
600
 
587
 
601
    spinlock_unlock(&threads_lock);
588
    spinlock_unlock(&threads_lock);
602
    interrupts_restore(ipl);
589
    interrupts_restore(ipl);
603
}
590
}
604
 
591
 
605
/** Check whether thread exists.
592
/** Check whether thread exists.
606
 *
593
 *
607
 * Note that threads_lock must be already held and
594
 * Note that threads_lock must be already held and
608
 * interrupts must be already disabled.
595
 * interrupts must be already disabled.
609
 *
596
 *
610
 * @param t Pointer to thread.
597
 * @param t Pointer to thread.
611
 *
598
 *
612
 * @return True if thread t is known to the system, false otherwise.
599
 * @return True if thread t is known to the system, false otherwise.
613
 */
600
 */
614
bool thread_exists(thread_t *t)
601
bool thread_exists(thread_t *t)
615
{
602
{
616
    btree_node_t *leaf;
603
    btree_node_t *leaf;
617
   
604
   
618
    return btree_search(&threads_btree, (btree_key_t) ((uintptr_t) t), &leaf) != NULL;
605
    return btree_search(&threads_btree, (btree_key_t) ((uintptr_t) t), &leaf) != NULL;
619
}
606
}
620
 
607
 
621
 
608
 
622
/** Update accounting of current thread.
609
/** Update accounting of current thread.
623
 *
610
 *
624
 * Note that thread_lock on THREAD must be already held and
611
 * Note that thread_lock on THREAD must be already held and
625
 * interrupts must be already disabled.
612
 * interrupts must be already disabled.
626
 *
613
 *
627
 */
614
 */
628
void thread_update_accounting(void)
615
void thread_update_accounting(void)
629
{
616
{
630
    uint64_t time = get_cycle();
617
    uint64_t time = get_cycle();
631
    THREAD->cycles += time - THREAD->last_cycle;
618
    THREAD->cycles += time - THREAD->last_cycle;
632
    THREAD->last_cycle = time;
619
    THREAD->last_cycle = time;
633
}
620
}
634
 
621
 
635
/** Process syscall to create new thread.
622
/** Process syscall to create new thread.
636
 *
623
 *
637
 */
624
 */
638
unative_t sys_thread_create(uspace_arg_t *uspace_uarg, char *uspace_name)
625
unative_t sys_thread_create(uspace_arg_t *uspace_uarg, char *uspace_name)
639
{
626
{
640
    thread_t *t;
627
    thread_t *t;
641
    char namebuf[THREAD_NAME_BUFLEN];
628
    char namebuf[THREAD_NAME_BUFLEN];
642
    uspace_arg_t *kernel_uarg;
629
    uspace_arg_t *kernel_uarg;
643
    uint32_t tid;
630
    uint32_t tid;
644
    int rc;
631
    int rc;
645
 
632
 
646
    rc = copy_from_uspace(namebuf, uspace_name, THREAD_NAME_BUFLEN);
633
    rc = copy_from_uspace(namebuf, uspace_name, THREAD_NAME_BUFLEN);
647
    if (rc != 0)
634
    if (rc != 0)
648
        return (unative_t) rc;
635
        return (unative_t) rc;
649
 
636
 
650
    kernel_uarg = (uspace_arg_t *) malloc(sizeof(uspace_arg_t), 0);
637
    kernel_uarg = (uspace_arg_t *) malloc(sizeof(uspace_arg_t), 0);
651
    rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
638
    rc = copy_from_uspace(kernel_uarg, uspace_uarg, sizeof(uspace_arg_t));
652
    if (rc != 0) {
639
    if (rc != 0) {
653
        free(kernel_uarg);
640
        free(kernel_uarg);
654
        return (unative_t) rc;
641
        return (unative_t) rc;
655
    }
642
    }
656
 
643
 
657
    if ((t = thread_create(uinit, kernel_uarg, TASK, THREAD_FLAG_USPACE, namebuf, false))) {
644
    if ((t = thread_create(uinit, kernel_uarg, TASK, THREAD_FLAG_USPACE, namebuf, false))) {
658
        tid = t->tid;
645
        tid = t->tid;
659
        thread_ready(t);
646
        thread_ready(t);
660
        return (unative_t) tid;
647
        return (unative_t) tid;
661
    } else {
648
    } else {
662
        free(kernel_uarg);
649
        free(kernel_uarg);
663
    }
650
    }
664
 
651
 
665
    return (unative_t) ENOMEM;
652
    return (unative_t) ENOMEM;
666
}
653
}
667
 
654
 
668
/** Process syscall to terminate thread.
655
/** Process syscall to terminate thread.
669
 *
656
 *
670
 */
657
 */
671
unative_t sys_thread_exit(int uspace_status)
658
unative_t sys_thread_exit(int uspace_status)
672
{
659
{
673
    thread_exit();
660
    thread_exit();
674
    /* Unreachable */
661
    /* Unreachable */
675
    return 0;
662
    return 0;
676
}
663
}
677
 
664
 
678
/** @}
665
/** @}
679
 */
666
 */
680
 
667