Subversion Repositories HelenOS

Rev

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

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