Subversion Repositories HelenOS

Rev

Rev 1757 | Rev 1766 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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