source: mainline/kernel/generic/src/proc/task.c@ 162ad53

Last change on this file since 162ad53 was 162ad53, checked in by GitHub <noreply@…>, 42 hours ago

Merge 455241b37bedd3719ed3b5b025fdf26f44fd565b into 5caad1d4a9774280b120ed9f9da51f4bb6f1f4bf

  • Property mode set to 100644
File size: 16.2 KB
Line 
1/*
2 * Copyright (c) 2025 Jiri Svoboda
3 * Copyright (c) 2010 Jakub Jermar
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30/** @addtogroup kernel_generic_proc
31 * @{
32 */
33
34/**
35 * @file
36 * @brief Task management.
37 */
38
39#include <assert.h>
40#include <proc/thread.h>
41#include <proc/task.h>
42#include <mm/as.h>
43#include <mm/slab.h>
44#include <atomic.h>
45#include <synch/spinlock.h>
46#include <synch/waitq.h>
47#include <arch.h>
48#include <barrier.h>
49#include <adt/list.h>
50#include <adt/odict.h>
51#include <cap/cap.h>
52#include <ipc/ipc.h>
53#include <ipc/ipcrsc.h>
54#include <ipc/event.h>
55#include <stdio.h>
56#include <errno.h>
57#include <halt.h>
58#include <str.h>
59#include <syscall/copy.h>
60#include <macros.h>
61
62/** Spinlock protecting the @c tasks ordered dictionary. */
63IRQ_SPINLOCK_INITIALIZE(tasks_lock);
64
65/** Ordered dictionary of active tasks by task ID.
66 *
67 * Members are task_t structures.
68 *
69 * The task is guaranteed to exist after it was found in the @c tasks
70 * dictionary as long as:
71 *
72 * @li the tasks_lock is held,
73 * @li the task's lock is held when task's lock is acquired before releasing
74 * tasks_lock or
75 * @li the task's refcount is greater than 0
76 *
77 */
78odict_t tasks;
79
80static task_id_t task_counter = 0;
81
82static slab_cache_t *task_cache;
83
84/* Forward declarations. */
85static void task_kill_internal(task_t *);
86static errno_t tsk_constructor(void *, unsigned int);
87static size_t tsk_destructor(void *);
88
89static void *tasks_getkey(odlink_t *);
90static int tasks_cmp(void *, void *);
91
92/** Initialize kernel tasks support.
93 *
94 */
95void task_init(void)
96{
97 TASK = NULL;
98 odict_initialize(&tasks, tasks_getkey, tasks_cmp);
99 task_cache = slab_cache_create("task_t", sizeof(task_t), 0,
100 tsk_constructor, tsk_destructor, 0);
101}
102
103/** Kill all tasks except the current task.
104 *
105 */
106void task_done(task_t *cur_task)
107{
108 size_t tasks_left;
109 task_t *task;
110
111 if (ipc_box_0) {
112 task_t *task_0 = ipc_box_0->task;
113 ipc_box_0 = NULL;
114
115 /*
116 * The first task is held by kinit(), we need to release it or
117 * it will never finish cleanup.
118 */
119 task_release(task_0);
120 }
121
122 /* Repeat until there are any tasks except TASK */
123 do {
124#ifdef CONFIG_DEBUG
125 printf("Killing tasks... ");
126#endif
127 irq_spinlock_lock(&tasks_lock, true);
128 tasks_left = 0;
129
130 task = task_first();
131 while (task != NULL) {
132 if (task != cur_task) {
133 tasks_left++;
134#ifdef CONFIG_DEBUG
135 printf("[%" PRIu64 "] ", task->taskid);
136#endif
137 task_kill_internal(task);
138 }
139
140 task = task_next(task);
141 }
142
143 irq_spinlock_unlock(&tasks_lock, true);
144
145 thread_sleep(1);
146
147#ifdef CONFIG_DEBUG
148 printf("\n");
149#endif
150 } while (tasks_left > 0);
151}
152
153errno_t tsk_constructor(void *obj, unsigned int kmflags)
154{
155 task_t *task = (task_t *) obj;
156
157 errno_t rc = caps_task_alloc(task);
158 if (rc != EOK)
159 return rc;
160
161 atomic_store(&task->lifecount, 0);
162
163 irq_spinlock_initialize(&task->lock, "task_t_lock");
164
165 list_initialize(&task->threads);
166
167 ipc_answerbox_init(&task->answerbox, task);
168
169 spinlock_initialize(&task->active_calls_lock, "active_calls_lock");
170 list_initialize(&task->active_calls);
171
172#ifdef CONFIG_UDEBUG
173 /* Init kbox stuff */
174 task->kb.thread = NULL;
175 ipc_answerbox_init(&task->kb.box, task);
176 mutex_initialize(&task->kb.cleanup_lock, MUTEX_PASSIVE);
177#endif
178
179 return EOK;
180}
181
182size_t tsk_destructor(void *obj)
183{
184 task_t *task = (task_t *) obj;
185
186 caps_task_free(task);
187 return 0;
188}
189
190/** Create new task with no threads.
191 *
192 * @param as Task's address space.
193 * @param name Symbolic name (a copy is made).
194 *
195 * @return New task's structure.
196 *
197 */
198task_t *task_create(as_t *as, const char *name)
199{
200 task_t *task = (task_t *) slab_alloc(task_cache, FRAME_ATOMIC);
201 if (!task)
202 return NULL;
203
204 if (caps_task_init(task) != EOK) {
205 slab_free(task_cache, task);
206 return NULL;
207 }
208
209 refcount_init(&task->refcount);
210
211 task_create_arch(task);
212
213 task->as = as;
214 str_cpy(task->name, TASK_NAME_BUFLEN, name);
215
216 task->container = CONTAINER;
217 task->perms = 0;
218 task->ucycles = 0;
219 task->kcycles = 0;
220
221 task->ipc_info.call_sent = 0;
222 task->ipc_info.call_received = 0;
223 task->ipc_info.answer_sent = 0;
224 task->ipc_info.answer_received = 0;
225 task->ipc_info.irq_notif_received = 0;
226 task->ipc_info.forwarded = 0;
227
228 event_task_init(task);
229
230 task->answerbox.active = true;
231
232 task->debug_sections = NULL;
233
234#ifdef CONFIG_UDEBUG
235 /* Init debugging stuff */
236 udebug_task_init(&task->udebug);
237
238 /* Init kbox stuff */
239 task->kb.box.active = true;
240 task->kb.finished = false;
241#endif
242
243 if ((ipc_box_0) &&
244 (container_check(ipc_box_0->task->container, task->container))) {
245 cap_phone_handle_t phone_handle;
246 errno_t rc = phone_alloc(task, true, &phone_handle, NULL);
247 if (rc != EOK) {
248 task->as = NULL;
249 task_destroy_arch(task);
250 slab_free(task_cache, task);
251 return NULL;
252 }
253
254 phone_t *phone = phone_from_kobject(
255 kobject_get(task, phone_handle, KOBJECT_TYPE_PHONE));
256 (void) ipc_phone_connect(phone, ipc_box_0);
257 }
258
259 irq_spinlock_lock(&tasks_lock, true);
260
261 task->taskid = ++task_counter;
262 odlink_initialize(&task->ltasks);
263 odict_insert(&task->ltasks, &tasks, NULL);
264
265 irq_spinlock_unlock(&tasks_lock, true);
266
267 return task;
268}
269
270/** Destroy task.
271 *
272 * @param task Task to be destroyed.
273 *
274 */
275static void task_destroy(task_t *task)
276{
277 /*
278 * Remove the task from the task odict.
279 */
280 irq_spinlock_lock(&tasks_lock, true);
281 odict_remove(&task->ltasks);
282 irq_spinlock_unlock(&tasks_lock, true);
283
284 /*
285 * Perform architecture specific task destruction.
286 */
287 task_destroy_arch(task);
288
289 /*
290 * Drop our reference to the address space.
291 */
292 as_release(task->as);
293
294 caps_task_clear(task);
295
296 slab_free(task_cache, task);
297}
298
299/** Hold a reference to a task.
300 *
301 * Holding a reference to a task prevents destruction of that task.
302 *
303 * @param task Task to be held.
304 *
305 */
306void task_hold(task_t *task)
307{
308 refcount_up(&task->refcount);
309}
310
311/** Release a reference to a task.
312 *
313 * The last one to release a reference to a task destroys the task.
314 *
315 * @param task Task to be released.
316 *
317 */
318void task_release(task_t *task)
319{
320 if (refcount_down(&task->refcount))
321 task_destroy(task);
322}
323
324#ifdef __32_BITS__
325
326/** Syscall for reading task ID from userspace (32 bits)
327 *
328 * @param uspace_taskid Pointer to user-space buffer
329 * where to store current task ID.
330 *
331 * @return Zero on success or an error code from @ref errno.h.
332 *
333 */
334sys_errno_t sys_task_get_id(uspace_ptr_sysarg64_t uspace_taskid)
335{
336 /*
337 * No need to acquire lock on TASK because taskid remains constant for
338 * the lifespan of the task.
339 */
340 return (sys_errno_t) copy_to_uspace(uspace_taskid, &TASK->taskid,
341 sizeof(TASK->taskid));
342}
343
344#endif /* __32_BITS__ */
345
346#ifdef __64_BITS__
347
348/** Syscall for reading task ID from userspace (64 bits)
349 *
350 * @return Current task ID.
351 *
352 */
353sysarg_t sys_task_get_id(void)
354{
355 /*
356 * No need to acquire lock on TASK because taskid remains constant for
357 * the lifespan of the task.
358 */
359 return TASK->taskid;
360}
361
362#endif /* __64_BITS__ */
363
364/** Syscall for setting the task name.
365 *
366 * The name simplifies identifying the task in the task list.
367 *
368 * @param name The new name for the task. (typically the same
369 * as the command used to execute it).
370 *
371 * @return 0 on success or an error code from @ref errno.h.
372 *
373 */
374sys_errno_t sys_task_set_name(const uspace_ptr_char uspace_name, size_t name_len)
375{
376 char namebuf[TASK_NAME_BUFLEN];
377
378 /* Cap length of name and copy it from userspace. */
379 if (name_len > TASK_NAME_BUFLEN - 1)
380 name_len = TASK_NAME_BUFLEN - 1;
381
382 errno_t rc = copy_from_uspace(namebuf, uspace_name, name_len);
383 if (rc != EOK)
384 return (sys_errno_t) rc;
385
386 namebuf[name_len] = '\0';
387
388 /*
389 * As the task name is referenced also from the
390 * threads, lock the threads' lock for the course
391 * of the update.
392 */
393
394 irq_spinlock_lock(&tasks_lock, true);
395 irq_spinlock_lock(&TASK->lock, false);
396
397 /* Set task name */
398 str_cpy(TASK->name, TASK_NAME_BUFLEN, namebuf);
399
400 irq_spinlock_unlock(&TASK->lock, false);
401 irq_spinlock_unlock(&tasks_lock, true);
402
403 return EOK;
404}
405
406/** Syscall to forcefully terminate a task
407 *
408 * @param uspace_taskid Pointer to task ID in user space.
409 *
410 * @return 0 on success or an error code from @ref errno.h.
411 *
412 */
413sys_errno_t sys_task_kill(uspace_ptr_task_id_t uspace_taskid)
414{
415 task_id_t taskid;
416 errno_t rc = copy_from_uspace(&taskid, uspace_taskid, sizeof(taskid));
417 if (rc != EOK)
418 return (sys_errno_t) rc;
419
420 return (sys_errno_t) task_kill(taskid);
421}
422
423/** Find task structure corresponding to task ID.
424 *
425 * @param id Task ID.
426 *
427 * @return Task reference or NULL if there is no such task ID.
428 *
429 */
430task_t *task_find_by_id(task_id_t id)
431{
432 task_t *task = NULL;
433
434 irq_spinlock_lock(&tasks_lock, true);
435
436 odlink_t *odlink = odict_find_eq(&tasks, &id, NULL);
437 if (odlink != NULL) {
438 task = odict_get_instance(odlink, task_t, ltasks);
439
440 /*
441 * The directory of tasks can't hold a reference, since that would
442 * prevent task from ever being destroyed. That means we have to
443 * check for the case where the task is already being destroyed, but
444 * not yet removed from the directory.
445 */
446 if (!refcount_try_up(&task->refcount))
447 task = NULL;
448 }
449
450 irq_spinlock_unlock(&tasks_lock, true);
451
452 return task;
453}
454
455/** Get count of tasks.
456 *
457 * @return Number of tasks in the system
458 */
459size_t task_count(void)
460{
461 assert(interrupts_disabled());
462 assert(irq_spinlock_locked(&tasks_lock));
463
464 return odict_count(&tasks);
465}
466
467/** Get first task (task with lowest ID).
468 *
469 * @return Pointer to first task or @c NULL if there are none.
470 */
471task_t *task_first(void)
472{
473 odlink_t *odlink;
474
475 assert(interrupts_disabled());
476 assert(irq_spinlock_locked(&tasks_lock));
477
478 odlink = odict_first(&tasks);
479 if (odlink == NULL)
480 return NULL;
481
482 return odict_get_instance(odlink, task_t, ltasks);
483}
484
485/** Get next task (with higher task ID).
486 *
487 * @param cur Current task
488 * @return Pointer to next task or @c NULL if there are no more tasks.
489 */
490task_t *task_next(task_t *cur)
491{
492 odlink_t *odlink;
493
494 assert(interrupts_disabled());
495 assert(irq_spinlock_locked(&tasks_lock));
496
497 odlink = odict_next(&cur->ltasks, &tasks);
498 if (odlink == NULL)
499 return NULL;
500
501 return odict_get_instance(odlink, task_t, ltasks);
502}
503
504/** Get accounting data of given task.
505 *
506 * Note that task lock of 'task' must be already held and interrupts must be
507 * already disabled.
508 *
509 * @param task Pointer to the task.
510 * @param ucycles Out pointer to sum of all user cycles.
511 * @param kcycles Out pointer to sum of all kernel cycles.
512 *
513 */
514void task_get_accounting(task_t *task, uint64_t *ucycles, uint64_t *kcycles)
515{
516 assert(interrupts_disabled());
517 assert(irq_spinlock_locked(&task->lock));
518
519 /* Accumulated values of task */
520 uint64_t uret = task->ucycles;
521 uint64_t kret = task->kcycles;
522
523 /* Current values of threads */
524 list_foreach(task->threads, th_link, thread_t, thread) {
525 /* Process only counted threads */
526 if (!thread->uncounted) {
527 if (thread == THREAD) {
528 /* Update accounting of current thread */
529 thread_update_accounting(false);
530 }
531
532 uret += atomic_time_read(&thread->ucycles);
533 kret += atomic_time_read(&thread->kcycles);
534 }
535 }
536
537 *ucycles = uret;
538 *kcycles = kret;
539}
540
541static void task_kill_internal(task_t *task)
542{
543 irq_spinlock_lock(&task->lock, true);
544
545 /*
546 * Interrupt all threads.
547 */
548
549 list_foreach(task->threads, th_link, thread_t, thread) {
550 thread_interrupt(thread);
551 }
552
553 irq_spinlock_unlock(&task->lock, true);
554}
555
556/** Kill task.
557 *
558 * This function is idempotent.
559 * It signals all the task's threads to bail it out.
560 *
561 * @param id ID of the task to be killed.
562 *
563 * @return Zero on success or an error code from errno.h.
564 *
565 */
566errno_t task_kill(task_id_t id)
567{
568 if (id == 1)
569 return EPERM;
570
571 task_t *task = task_find_by_id(id);
572 if (!task)
573 return ENOENT;
574
575 task_kill_internal(task);
576 task_release(task);
577 return EOK;
578}
579
580/** Kill the currently running task.
581 *
582 * @param notify Send out fault notifications.
583 *
584 * @return Zero on success or an error code from errno.h.
585 *
586 */
587void task_kill_self(bool notify)
588{
589 /*
590 * User space can subscribe for FAULT events to take action
591 * whenever a task faults (to take a dump, run a debugger, etc.).
592 * The notification is always available, but unless udebug is enabled,
593 * that's all you get.
594 */
595 if (notify) {
596 /* Notify the subscriber that a fault occurred. */
597 if (event_notify_3(EVENT_FAULT, false, LOWER32(TASK->taskid),
598 UPPER32(TASK->taskid), (sysarg_t) THREAD) == EOK) {
599#ifdef CONFIG_UDEBUG
600 /* Wait for a debugging session. */
601 udebug_thread_fault();
602#endif
603 }
604 }
605
606 task_kill_internal(TASK);
607 thread_exit();
608}
609
610/** Process syscall to terminate the current task.
611 *
612 * @param notify Send out fault notifications.
613 *
614 */
615sys_errno_t sys_task_exit(sysarg_t notify)
616{
617 task_kill_self(notify);
618 unreachable();
619}
620
621static void task_print(task_t *task, bool additional)
622{
623 irq_spinlock_lock(&task->lock, false);
624
625 uint64_t ucycles;
626 uint64_t kcycles;
627 char usuffix, ksuffix;
628 task_get_accounting(task, &ucycles, &kcycles);
629 order_suffix(ucycles, &ucycles, &usuffix);
630 order_suffix(kcycles, &kcycles, &ksuffix);
631
632#ifdef __32_BITS__
633 if (additional)
634 printf("%-8" PRIu64 " %9zu", task->taskid,
635 atomic_load(&task->lifecount));
636 else
637 printf("%-8" PRIu64 " %-14s %-5" PRIu32 " %10p %10p"
638 " %9" PRIu64 "%c %9" PRIu64 "%c\n", task->taskid,
639 task->name, task->container, task, task->as,
640 ucycles, usuffix, kcycles, ksuffix);
641#endif
642
643#ifdef __64_BITS__
644 if (additional)
645 printf("%-8" PRIu64 " %9" PRIu64 "%c %9" PRIu64 "%c "
646 "%9zu\n", task->taskid, ucycles, usuffix, kcycles,
647 ksuffix, atomic_load(&task->lifecount));
648 else
649 printf("%-8" PRIu64 " %-14s %-5" PRIu32 " %18p %18p\n",
650 task->taskid, task->name, task->container, task, task->as);
651#endif
652
653 irq_spinlock_unlock(&task->lock, false);
654}
655
656/** Print task list
657 *
658 * @param additional Print additional information.
659 *
660 */
661void task_print_list(bool additional)
662{
663 /* Messing with task structures, avoid deadlock */
664 irq_spinlock_lock(&tasks_lock, true);
665
666#ifdef __32_BITS__
667 if (additional)
668 printf("[id ] [threads] [calls] [callee\n");
669 else
670 printf("[id ] [name ] [ctn] [address ] [as ]"
671 " [ucycles ] [kcycles ]\n");
672#endif
673
674#ifdef __64_BITS__
675 if (additional)
676 printf("[id ] [ucycles ] [kcycles ] [threads] [calls]"
677 " [callee\n");
678 else
679 printf("[id ] [name ] [ctn] [address ]"
680 " [as ]\n");
681#endif
682
683 task_t *task;
684
685 task = task_first();
686 while (task != NULL) {
687 task_print(task, additional);
688 task = task_next(task);
689 }
690
691 irq_spinlock_unlock(&tasks_lock, true);
692}
693
694/** Get key function for the @c tasks ordered dictionary.
695 *
696 * @param odlink Link
697 * @return Pointer to task ID cast as 'void *'
698 */
699static void *tasks_getkey(odlink_t *odlink)
700{
701 task_t *task = odict_get_instance(odlink, task_t, ltasks);
702 return (void *) &task->taskid;
703}
704
705/** Key comparison function for the @c tasks ordered dictionary.
706 *
707 * @param a Pointer to thread A ID
708 * @param b Pointer to thread B ID
709 * @return -1, 0, 1 iff ID A is less than, equal to, greater than B
710 */
711static int tasks_cmp(void *a, void *b)
712{
713 task_id_t ida = *(task_id_t *)a;
714 task_id_t idb = *(task_id_t *)b;
715
716 if (ida < idb)
717 return -1;
718 else if (ida == idb)
719 return 0;
720 else
721 return +1;
722}
723
724/** @}
725 */
Note: See TracBrowser for help on using the repository browser.