KallistiOS  ##version##
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups
thread.h
Go to the documentation of this file.
1 /* KallistiOS ##version##
2 
3  include/kos/thread.h
4  Copyright (C) 2000, 2001, 2002, 2003 Dan Potter
5  Copyright (C) 2009, 2010 Lawrence Sebald
6 
7 */
8 
9 #ifndef __KOS_THREAD_H
10 #define __KOS_THREAD_H
11 
12 #include <sys/cdefs.h>
13 __BEGIN_DECLS
14 
15 #include <kos/tls.h>
16 #include <arch/types.h>
17 #include <arch/irq.h>
18 #include <arch/arch.h>
19 #include <sys/queue.h>
20 #include <sys/reent.h>
21 
22 /** \file kos/thread.h
23  \brief Threading support.
24 
25  This file contains the interface to the threading system of KOS. Timer
26  interrupts are used to reschedule threads within the system while in
27  preemptive mode. There is also some support for a cooperative threading
28  mode (where each thread must manually give up its timeslice to swap out
29  threads).
30 
31  The thread scheduler itself is a relatively simplistic priority scheduler.
32  There is no provision for priorities to erode over time, so keep that in
33  mind. That practically means that if you have 2 high priority threads that
34  are always runnable and one low priority thread that is always runnable, the
35  low priority thread will never actually run (since it will never get to the
36  front of the run queue because of the high priority threads).
37 
38  The scheduler supports two distinct types of threads: joinable and detached
39  threads. A joinable thread is one that can return a value to the creating
40  thread (or for that matter, any other thread that wishes to join it). A
41  detached thread is one taht is completely detached from the rest of the
42  system and cannot return values by "normal" means. Detached threads
43  automatically clean up all of the internal resources associated with the
44  thread when it exits. Joinable threads, on the other hand, must keep some
45  state available for the ability to return values. To make sure that all
46  memory allocated by the thread's internal structures gets freed, you must
47  either join with the thread (with thd_join()) or detach it (with
48  thd_detach()). The old KOS threading system only had what would be
49  considered detached threads.
50 
51  \author Dan Potter
52  \author Lawrence Sebald
53  \see arch/timer.h
54  \see kos/genwait.h
55  \see kos/mutex.h
56  \see kos/once.h
57  \see kos/recursive_lock.h
58  \see kos/rwsem.h
59  \see kos/sem.h
60  \see kos/tls.h
61 */
62 
63 /** \brief Maximal thread priority.
64  This macro defines the maximum value for a thread's priority. Note that the
65  larger this number, the lower the priority of the thread.
66 */
67 #define PRIO_MAX 4096
68 
69 /** \brief Default thread priority.
70  Threads are created by default with the priority specified.
71 */
72 #define PRIO_DEFAULT 10
73 
74 /* Pre-define list/queue types */
75 struct kthread;
76 
77 /* \cond */
78 TAILQ_HEAD(ktqueue, kthread);
79 LIST_HEAD(ktlist, kthread);
80 /* \endcond */
81 
82 /** \brief Structure describing one running thread.
83 
84  Each thread has one of this structure assigned to it, which hold all the
85  data associated with the thread. There are various functions to manipulate
86  the data in here, so you shouldn't generally do so manually.
87 
88  \headerfile kos/thread.h
89 */
90 typedef struct kthread {
91  /** \brief Thread list handle. Not a function. */
92  LIST_ENTRY(kthread) t_list;
93 
94  /** \brief Run/Wait queue handle. Once again, not a function. */
95  TAILQ_ENTRY(kthread) thdq;
96 
97  /** \brief Timer queue handle (if applicable). Also not a function. */
98  TAILQ_ENTRY(kthread) timerq;
99 
100  /** \brief Kernel thread id. */
102 
103  /** \brief Static priority: 0..PRIO_MAX (higher means lower priority). */
105 
106  /** \brief Thread flags.
107  \see thd_flags */
109 
110  /** \brief Process state.
111  \see thd_states */
112  int state;
113 
114  /** \brief Generic wait target, if waiting.
115  \see kos/genwait.h */
116  void * wait_obj;
117 
118  /** \brief Generic wait message, if waiting.
119  \see kos/genwait.h */
120  const char * wait_msg;
121 
122  /** \brief Wait timeout callback.
123 
124  If the genwait times out while waiting, this function will be called.
125  This allows hooks for things like fixing up semaphore count values, etc.
126 
127  \param obj The object that we were waiting on.
128  */
129  void (*wait_callback)(void * obj);
130 
131  /** \brief Next scheduled time.
132  This value is used for sleep and timed block operations. This value is
133  in milliseconds since the start of timer_ms_gettime(). This should be
134  enough for something like 2 million years of wait time. ;) */
136 
137  /** \brief Thread label.
138  This value is used when printing out a user-readable process listing. */
139  char label[256];
140 
141  /** \brief Current file system path. */
142  char pwd[256];
143 
144  /** \brief Register store -- used to save thread context. */
146 
147  /** \brief Thread private stack.
148  This should be a pointer to the base of a stack page. */
150 
151  /** \brief Size of the thread's stack, in bytes. */
153 
154  /** \brief Thread errno variable. */
156 
157  /** \brief Our reent struct for newlib. */
158  struct _reent thd_reent;
159 
160  /** \brief Thread-local storage.
161  \see kos/tls.h */
162  struct kthread_tls_kv_list tls_list;
163 
164  /** \brief Return value of the thread function.
165  This is only used in joinable threads. */
166  void *rv;
167 } kthread_t;
168 
169 /** \defgroup thd_flags Thread flag values
170 
171  These are possible values for the flags field on the kthread_t structure.
172  These can be ORed together.
173 
174  @{
175 */
176 #define THD_DEFAULTS 0 /**< \brief Defaults: no flags */
177 #define THD_USER 1 /**< \brief Thread runs in user mode */
178 #define THD_QUEUED 2 /**< \brief Thread is in the run queue */
179 #define THD_DETACHED 4 /**< \brief Thread is detached */
180 /** @} */
181 
182 /** \defgroup thd_states Thread states
183 
184  Each thread in the system is in exactly one of this set of states.
185 
186  @{
187 */
188 #define STATE_ZOMBIE 0x0000 /**< \brief Waiting to die */
189 #define STATE_RUNNING 0x0001 /**< \brief Process is "current" */
190 #define STATE_READY 0x0002 /**< \brief Ready to be scheduled */
191 #define STATE_WAIT 0x0003 /**< \brief Blocked on a genwait */
192 #define STATE_FINISHED 0x0004 /**< \brief Finished execution */
193 /** @} */
194 
195 /** \brief Are threads cooperative or preemptive?
196 
197  Do not modify this variable directly. Instead, use the thd_set_mode()
198  function to switch threading modes.
199 
200  \see thd_modes
201 */
202 extern int thd_mode;
203 
204 /** \defgroup thd_modes Threading system modes
205 
206  The thd_mode variable will always have one of this set of values. This
207  represents the type of scheduling done by the system (or the special case of
208  threads not having been initialized yet).
209 
210  @{
211 */
212 #define THD_MODE_NONE -1 /**< \brief Threads not running */
213 #define THD_MODE_COOP 0 /**< \brief Cooperative threading mode */
214 #define THD_MODE_PREEMPT 1 /**< \brief Preemptive threading mode */
215 /** @} */
216 
217 /** \brief The currently executing thread.
218 
219  Do not manipulate this variable directly!
220 */
221 extern kthread_t *thd_current;
222 
223 /** \brief "Jiffy" count.
224 
225  This variable counts the number of context switches done by the threading
226  system. Do not manipulate this variable directly!
227 */
228 extern vuint32 jiffies;
229 
230 /** \brief Block the current thread.
231 
232  Blocks the calling thread and performs a reschedule as if a context switch
233  timer had been executed. This is useful for, e.g., blocking on sync
234  primitives. The param 'mycxt' should point to the calling thread's context
235  block. This is implemented in arch-specific code.
236 
237  The meaningfulness of the return value depends on whether the unblocker set
238  a return value or not.
239 
240  \param mycxt The IRQ context of the calling thread.
241 
242  \return Whatever the unblocker deems necessary to return.
243 */
244 int thd_block_now(irq_context_t * mycxt);
245 
246 /** \brief Find a new thread to swap in.
247 
248  This function looks at the state of the system and returns a new thread
249  context to swap in. This is called from thd_block_now() and from the
250  preemptive context switcher. Note that thd_current might be NULL on entering
251  this function, if the caller blocked itself.
252 
253  It is assumed that by the time this returns, the irq_srt_addr and
254  thd_current will be updated.
255 
256  \return The IRQ context of the thread selected.
257 */
259 
260 /** \brief Given a thread ID, locates the thread structure.
261  \param tid The thread ID to retrieve.
262 
263  \return The thread on success, NULL on failure.
264 */
266 
267 /** \brief Enqueue a process in the runnable queue.
268 
269  This function adds a thread to the runnable queue after the process group of
270  the same priority if front_of_line is zero, otherwise queues it at the front
271  of its priority group. Generally, you will not have to do this manually.
272 
273  \param t The thread to queue.
274  \param front_of_line Set to 1 to put this thread in front of other
275  threads of the same priority, 0 to put it behind the
276  other threads (normal behavior).
277 */
278 void thd_add_to_runnable(kthread_t *t, int front_of_line);
279 
280 /** \brief Removes a thread from the runnable queue, if it's there.
281 
282  This function removes a thread from the runnable queue, if it is currently
283  in that queue. Generally, you shouldn't have to do this manually, as waiting
284  on synchronization primitives and the like will do this for you if needed.
285 
286  \param thd The thread to remove from the runnable queue.
287 
288  \retval 0 On success, or if the thread isn't runnable.
289 */
291 
292 /** \brief Create a new thread.
293 
294  This function creates a new kernel thread with default parameters to run the
295  given routine. The thread will terminate and clean up resources when the
296  routine completes if the thread is created detached, otherwise you must
297  join the thread with thd_join() to clean up after it.
298 
299  \param detach Set to 1 to create a detached thread. Set to 0 to
300  create a joinable thread.
301  \param routine The function to call in the new thread.
302  \param param A parameter to pass to the function called.
303 
304  \return The new thread on success, NULL on failure.
305 */
306 kthread_t *thd_create(int detach, void * (*routine)(void *param), void *param);
307 
308 /** \brief Brutally kill the given thread.
309 
310  This function kills the given thread, removing it from the execution chain,
311  cleaning up thread-local data and other internal structures. You should
312  never call this function on the current thread. In general, you shouldn't
313  call this function at all.
314 
315  \param thd The thread to destroy.
316  \retval 0 On success.
317 */
318 int thd_destroy(kthread_t *thd);
319 
320 /** \brief Exit the current thread.
321 
322  This function ends the execution of the current thread, removing it from all
323  execution queues. This function will never return to the thread. Returning
324  from the thread's function is equivalent to calling this function.
325 
326  \param rv The return value of the thread.
327 */
328 void thd_exit(void *rv) __noreturn;
329 
330 /** \brief Force a thread reschedule.
331 
332  This function is the thread scheduler, and is generally called from a timer
333  interrupt, at least in preemptive mode. You will most likely never have a
334  reason to call this function directly.
335 
336  For most cases, you'll want to set front_of_line to zero, but read the
337  comments in kernel/thread/thread.c for more info, especially if you need to
338  guarantee low latencies. This function just updates irq_srt_addr and
339  thd_current. Set 'now' to non-zero if you want to use a particular system
340  time for checking timeouts.
341 
342  \param front_of_line Set to 0, unless you have a good reason not to.
343  \param now Set to 0, unless you have a good reason not to.
344 */
345 void thd_schedule(int front_of_line, uint64 now);
346 
347 /** \brief Force a given thread to the front of the queue.
348 
349  This function promotes the given thread to be the next one that will be
350  swapped in by the scheduler. This function is only callable inside an
351  interrupt context (it simply returns otherwise).
352 */
353 void thd_schedule_next(kthread_t *thd);
354 
355 /** \brief Throw away the current thread's timeslice.
356 
357  This function manually yields the current thread's timeslice to the system,
358  forcing a reschedule to occur.
359 */
360 void thd_pass();
361 
362 /** \brief Sleep for a given number of milliseconds.
363 
364  This function puts the current thread to sleep for the specified amount of
365  time. The thread will be removed from the runnable queue until the given
366  number of milliseconds passes. That is to say that the thread will sleep for
367  at least the given number of milliseconds. If another thread is running, it
368  will likely sleep longer.
369 
370  \param ms The number of milliseconds to sleep.
371 */
372 void thd_sleep(int ms);
373 
374 /** \brief Set a thread's priority value.
375 
376  This function is used to change the priority value of a thread. If the
377  thread is scheduled already, it will be rescheduled with the new priority
378  value.
379 
380  \param thd The thread to change the priority of.
381  \param prio The priority value to assign to the thread.
382 
383  \retval 0 On success.
384 */
385 int thd_set_prio(kthread_t *thd, prio_t prio);
386 
387 /** \brief Retrieve the current thread's kthread struct.
388  \return The current thread's structure.
389 */
391 
392 /** \brief Retrieve the thread's label.
393  \param thd The thread to retrieve from.
394 
395  \return The human-readable label of the thread.
396 */
397 const char *thd_get_label(kthread_t *thd);
398 
399 /** \brief Set the thread's label.
400 
401  This function sets the label of a thread, which is simply a human-readable
402  string that is used to identify the thread. These labels aren't used for
403  anything internally, and you can give them any label you want. These are
404  mainly seen in the printouts from thd_pslist() or thd_pslist_queue().
405 
406  \param thd The thread to set the label of.
407  \param label The string to set as the label.
408 */
409 void thd_set_label(kthread_t *thd, const char *label);
410 
411 /** \brief Retrieve the thread's current working directory.
412 
413  This function retrieves the working directory of a thread. Generally, you
414  will want to use either fs_getwd() or one of the standard C functions for
415  doing this, but this is here in case you need it when the thread isn't
416  active for some reason.
417 
418  \param thd The thread to retrieve from.
419 
420  \return The thread's working directory.
421 */
422 const char *thd_get_pwd(kthread_t *thd);
423 
424 /** \brief Set the thread's current working directory.
425 
426  This function will set the working directory of a thread. Generally, you
427  will want to use either fs_chdir() or the standard C chdir() function to
428  do this, but this is here in case you need to do it while the thread isn't
429  active for some reason.
430 
431  \param thd The thread to set the working directory of.
432  \param pwd The directory to set as active.
433 */
434 void thd_set_pwd(kthread_t *thd, const char *pwd);
435 
436 /** \brief Retrieve a pointer to the thread errno.
437 
438  This function retrieves a pointer to the errno value for the thread. You
439  should generally just use the errno variable to access this.
440 
441  \param thd The thread to retrieve from.
442 
443  \return A pointer to the thread's errno.
444 */
445 int * thd_get_errno(kthread_t *thd);
446 
447 /** \brief Retrieve a pointer to the thread reent struct.
448 
449  This function is used to retrieve some internal state that is used by
450  newlib to provide a reentrant libc.
451 
452  \param thd The thread to retrieve from.
453 
454  \return The thread's reent struct.
455 */
456 struct _reent * thd_get_reent(kthread_t *thd);
457 
458 /** \brief Change threading modes.
459 
460  This function changes the current threading mode of the system.
461 
462  \param mode One of the \ref thd_modes values.
463 
464  \return The old mode of the threading system.
465 */
466 int thd_set_mode(int mode);
467 
468 /** \brief Wait for a thread to exit.
469 
470  This function "joins" a joinable thread. This means effectively that the
471  calling thread blocks until the speified thread completes execution. It is
472  invalid to join a detached thread, only joinable threads may be joined.
473 
474  \param thd The joinable thread to join.
475  \param value_ptr A pointer to storage for the thread's return value,
476  or NULL if you don't care about it.
477 
478  \return 0 on success, or less than 0 if the thread is
479  non-existant or not joinable.
480 */
481 int thd_join(kthread_t * thd, void **value_ptr);
482 
483 /** \brief Detach a joinable thread.
484 
485  This function switches the specified thread's mode from THD_MODE_JOINABLE
486  to THD_MODE_DETACHED. This will ensure that the thread cleans up all of its
487  internal resources when it exits.
488 
489  \param thd The joinable thread to detach.
490 
491  \return 0 on success or less than 0 if the thread is
492  non-existant or already detached.
493  \see thd_join()
494 */
495 int thd_detach(kthread_t *thd);
496 
497 /** \brief Print a list of all threads using the given print function.
498 
499  \param pf The printf-like function to print with.
500 
501  \retval 0 On success.
502 */
503 int thd_pslist(int (*pf)(const char *fmt, ...));
504 
505 /** \brief Print a list of all queued threads using the given print function.
506 
507  \param pf The printf-like function to print with.
508 
509  \retval 0 On success.
510 */
511 int thd_pslist_queue(int (*pf)(const char *fmt, ...));
512 
513 
514 /** \brief Initialize the threading system.
515 
516  This is normally done for you by default when KOS starts. This will also
517  initialize all the various synchronization primitives.
518 
519  \param mode One of the \ref thd_modes values.
520 
521  \retval -1 If threads are already initialized.
522  \retval 0 On success.
523 */
524 int thd_init(int mode);
525 
526 /** \brief Shutdown the threading system.
527 
528  This is done for you by the normal shutdown procedure of KOS. This will
529  also shutdown all the various synchronization primitives.
530 */
531 void thd_shutdown();
532 
533 __END_DECLS
534 
535 #endif /* __KOS_THREAD_H */
536 
Thread-local storage support.
vuint32 jiffies
"Jiffy" count.
char pwd[256]
Current file system path.
Definition: thread.h:142
Common integer types.
tid_t tid
Kernel thread id.
Definition: thread.h:101
void thd_add_to_runnable(kthread_t *t, int front_of_line)
Enqueue a process in the runnable queue.
typedef LIST_HEAD(nmmgr_list, nmmgr_handler) nmmgr_list_t
Name handler list type.
void * wait_obj
Generic wait target, if waiting.
Definition: thread.h:116
kthread_t * thd_get_current()
Retrieve the current thread's kthread struct.
struct kthread_tls_kv_list tls_list
Thread-local storage.
Definition: thread.h:162
void thd_set_label(kthread_t *thd, const char *label)
Set the thread's label.
void thd_schedule(int front_of_line, uint64 now)
Force a thread reschedule.
void thd_pass()
Throw away the current thread's timeslice.
void thd_set_pwd(kthread_t *thd, const char *pwd)
Set the thread's current working directory.
int thd_block_now(irq_context_t *mycxt)
Block the current thread.
char label[256]
Thread label. This value is used when printing out a user-readable process listing.
Definition: thread.h:139
prio_t prio
Static priority: 0..PRIO_MAX (higher means lower priority).
Definition: thread.h:104
Architecture-specific structure for holding the processor state.
Definition: irq.h:46
handle_t tid_t
Thread ID type.
Definition: types.h:80
int thd_set_mode(int mode)
Change threading modes.
const char * wait_msg
Generic wait message, if waiting.
Definition: thread.h:120
struct _reent thd_reent
Our reent struct for newlib.
Definition: thread.h:158
int thd_detach(kthread_t *thd)
Detach a joinable thread.
int thd_set_prio(kthread_t *thd, prio_t prio)
Set a thread's priority value.
unsigned long long uint64
64-bit unsigned integer
Definition: types.h:27
void * rv
Return value of the thread function. This is only used in joinable threads.
Definition: thread.h:166
int * thd_get_errno(kthread_t *thd)
Retrieve a pointer to the thread errno.
volatile uint32 vuint32
32-bit volatile unsigned type
Definition: types.h:38
void thd_schedule_next(kthread_t *thd)
Force a given thread to the front of the queue.
uint32 stack_size
Size of the thread's stack, in bytes.
Definition: thread.h:152
int thd_destroy(kthread_t *thd)
Brutally kill the given thread.
int thd_join(kthread_t *thd, void **value_ptr)
Wait for a thread to exit.
kthread_t * thd_by_tid(tid_t tid)
Given a thread ID, locates the thread structure.
int thd_pslist(int(*pf)(const char *fmt,...))
Print a list of all threads using the given print function.
void(* wait_callback)(void *obj)
Wait timeout callback.
Definition: thread.h:129
struct kthread kthread_t
Structure describing one running thread.
unsigned long uint32
32-bit unsigned integer
Definition: types.h:28
uint64 wait_timeout
Next scheduled time. This value is used for sleep and timed block operations. This value is in millis...
Definition: thread.h:135
void thd_exit(void *rv) __noreturn
Exit the current thread.
LIST_ENTRY(kthread) t_list
Thread list handle. Not a function.
Structure describing one running thread.
Definition: thread.h:90
const char * thd_get_pwd(kthread_t *thd)
Retrieve the thread's current working directory.
irq_context_t context
Register store – used to save thread context.
Definition: thread.h:145
int thd_remove_from_runnable(kthread_t *thd)
Removes a thread from the runnable queue, if it's there.
kthread_t * thd_current
The currently executing thread.
int state
Process state.
Definition: thread.h:112
kthread_t * thd_create(int detach, void *(*routine)(void *param), void *param)
Create a new thread.
#define __noreturn
Identify a function that will never return.
Definition: cdefs.h:37
uint32 flags
Thread flags.
Definition: thread.h:108
Dreamcast architecture specific options.
irq_context_t * thd_choose_new()
Find a new thread to swap in.
TAILQ_ENTRY(kthread) thdq
Run/Wait queue handle. Once again, not a function.
void thd_sleep(int ms)
Sleep for a given number of milliseconds.
Interrupt and exception handling.
const char * thd_get_label(kthread_t *thd)
Retrieve the thread's label.
int thd_errno
Thread errno variable.
Definition: thread.h:155
uint32 * stack
Thread private stack. This should be a pointer to the base of a stack page.
Definition: thread.h:149
struct _reent * thd_get_reent(kthread_t *thd)
Retrieve a pointer to the thread reent struct.
void thd_shutdown()
Shutdown the threading system.
handle_t prio_t
Priority value type.
Definition: types.h:81
int thd_mode
Are threads cooperative or preemptive?
int thd_pslist_queue(int(*pf)(const char *fmt,...))
Print a list of all queued threads using the given print function.
int thd_init(int mode)
Initialize the threading system.