thread.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. #ifndef _SYS_THREAD_H_
  2. #define _SYS_THREAD_H_
  3. /*
  4. * Copyright (C) 2001-2006 by egnite Software GmbH. 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. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * 2. 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. * 3. Neither the name of the copyright holders nor the names of
  16. * contributors may be used to endorse or promote products derived
  17. * from this software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  22. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  23. * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  24. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  25. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  26. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  27. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  28. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  29. * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  30. * SUCH DAMAGE.
  31. *
  32. * For additional information see http://www.ethernut.de/
  33. *
  34. * -
  35. * Portions Copyright (C) 2000 David J. Hudson <dave@humbug.demon.co.uk>
  36. *
  37. * This file is distributed in the hope that it will be useful, but WITHOUT
  38. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  39. * FITNESS FOR A PARTICULAR PURPOSE.
  40. *
  41. * You can redistribute this file and/or modify it under the terms of the GNU
  42. * General Public License (GPL) as published by the Free Software Foundation;
  43. * either version 2 of the License, or (at your discretion) any later version.
  44. * See the accompanying file "copying-gpl.txt" for more details.
  45. *
  46. * As a special exception to the GPL, permission is granted for additional
  47. * uses of the text contained in this file. See the accompanying file
  48. * "copying-liquorice.txt" for details.
  49. */
  50. /*!
  51. * \file sys/thread.h
  52. * \brief Multi-threading support.
  53. *
  54. * \verbatim File version $Id: thread.h 4477 2012-08-20 17:50:01Z haraldkipp $ \endverbatim
  55. */
  56. #include <compiler.h>
  57. #include <sys/types.h>
  58. #include <cfg/memory.h>
  59. #include <stdint.h>
  60. #define DEADBEEF 0xDEADBEEF
  61. /*!
  62. * \addtogroup xgThread Thread Management
  63. * \ingroup xgNutOS
  64. * \anchor xrThread
  65. * \brief Cooperative multi-threading support.
  66. *
  67. * Typically Nut/OS is at its most useful where there are several
  68. * concurrent tasks that need to be undertaken at the same time.
  69. * To support this requirement, Nut/OS offers some kind of light
  70. * processes called threads. In this context a thread is a sequence
  71. * of executing software that can be considered to be logically
  72. * independent from other software that is running on the same CPU.
  73. *
  74. * All threads are executing in the same address space using the
  75. * same hardware resources, which significantly reduces task switching
  76. * overhead. Therefore it is important to stop them from causing
  77. * each other problems. This is particularly an issue where two or
  78. * more threads need to share a resources like memory locations or
  79. * peripheral devices.
  80. *
  81. * The system works on the principle that the most urgent thread
  82. * always runs. One exception to this is if a CPU interrupt arrives
  83. * and the interrupt has not been disabled. Each thread has a
  84. * priority which is used to determine how urgent it is. This
  85. * priority ranges from 0 to 255, with the lowest value indicating
  86. * the most urgent.
  87. *
  88. * Nut/OS implements cooperative multithreading. That means,
  89. * that threads are not bound to a fixed timeslice. Unless
  90. * they are waiting for specific event or explicitly yielding
  91. * the CPU, they can rely on not being stopped unexpectedly.
  92. * However, they may be interrupted by hardware interrupt
  93. * signals. In opposite to pre-emptive multithreading,
  94. * cooperative multithreading simplifies resource sharing
  95. * and results in faster and smaller code.
  96. *
  97. * \todo Using the special priority 255 to kill a thread is not
  98. * required and should be removed.
  99. *
  100. * To specify a function named Back as an independent thread, one can write
  101. * \code
  102. * #include <sys/thread.h>
  103. *
  104. * THREAD(Back, arg)
  105. * {
  106. * for (;;) {
  107. * NutSleep(1000);
  108. * }
  109. * }
  110. * \endcode
  111. *
  112. * To start this thread, use
  113. * \code
  114. * #include <sys/thread.h>
  115. *
  116. * // Other code here...
  117. * NutThreadCreate("Bg", Back, NULL, 512);
  118. * // Execution continues here and concurrently in the background thread.
  119. * \endcode
  120. *
  121. * The functions listed below are hardware independent. Additional
  122. * API calls are located in the architecture dependant sections.
  123. * - \ref xgNutArchAvrOsContextGcc "AVR with GNU Compiler"
  124. * - \ref xgNutArchAvrOsContextIcc "AVR with ImageCraft Compiler"
  125. * - \ref xgNutAvr32OsContext "AVR32 with GNU Compiler"
  126. * - \ref xgNutArchArmOsContext "ARM with GNU Compiler"
  127. * - \ref xgNutArchCm3OsContext "Cortex M3"
  128. * - \ref xgNutArchUnixOsContext "Emulator (UNIX)"
  129. */
  130. /*@{*/
  131. /*!
  132. * Thread information structure type.
  133. */
  134. typedef struct _NUTTHREADINFO NUTTHREADINFO;
  135. /*!
  136. * \struct _NUTTHREADINFO thread.h sys/thread.h
  137. * \brief Thread information structure.
  138. *
  139. * \todo Sort items while considering alignment.
  140. */
  141. struct _NUTTHREADINFO {
  142. NUTTHREADINFO *td_next; /*!< \brief Linked list of all threads. */
  143. NUTTHREADINFO *td_qnxt; /*!< \brief Linked list of all queued thread. */
  144. volatile unsigned int td_qpec; /*!< \brief Pending event counter. */
  145. char td_name[9]; /*!< \brief Name of this thread. */
  146. uint8_t td_state; /*!< \brief Operating state. One of TDS_ */
  147. uintptr_t td_sp; /*!< \brief Stack pointer. */
  148. uint8_t td_priority; /*!< \brief Priority level. 0 is highest priority. */
  149. uint8_t *td_memory; /*!< \brief Pointer to heap memory used for stack. */
  150. HANDLE td_timer; /*!< \brief Event timer. */
  151. volatile HANDLE td_queue; /*!< \brief Root entry of the waiting queue. */
  152. #ifdef __NUT_EMULATION__
  153. pthread_t td_pthread; /*!< \brief pthread for unix emulations. */
  154. void (*td_fn) (void *); /*!< \brief thread function */
  155. void *td_arg; /*!< \brief args given to NutCreateThread */
  156. pthread_cond_t td_cv; /*!< \brief conditional variable for unix emulations. */
  157. uint16_t td_cs_level; /*! \brief number critical sections has been entered without leaving */
  158. #endif
  159. };
  160. /*!
  161. * \name Thread States
  162. */
  163. /*@{*/
  164. #define TDS_TERM 0 /*!< Thread has exited. */
  165. #define TDS_RUNNING 1 /*!< Thread is running. */
  166. #define TDS_READY 2 /*!< Thread is ready to run. */
  167. #define TDS_SLEEP 3 /*!< Thread is sleeping. */
  168. /*@}*/
  169. #define SLEEP_MODE_NONE 0xff
  170. /*!
  171. * \brief Stack size factor.
  172. *
  173. * Configured stack sizes are multiplied with this value.
  174. *
  175. * All stack size settings of internal Nut/OS threads had been calculated
  176. * for size optimized code. Probably more stack space is required with
  177. * other compiler settings.
  178. *
  179. * For example, when GCC generates non-optimized code for source code
  180. * debugging, a factor of 3 should be applied to all stack sizes.
  181. *
  182. * Application code may also make use of this macro.
  183. *
  184. * \code
  185. * #include <sys/thread.h>
  186. *
  187. * #define MY_THREAD_STACK ((384 * NUT_THREAD_STACK_MULT) + NUT_THREAD_STACK_ADD)
  188. *
  189. * NutThreadCreate("myth", ThreadFunc, 0, MY_THREAD_STACK);
  190. * \endcode
  191. *
  192. * See also \ref NUT_THREAD_STACK_ADD.
  193. */
  194. #ifndef NUT_THREAD_STACK_MULT
  195. #define NUT_THREAD_STACK_MULT 1
  196. #endif
  197. /*!
  198. * \brief Stack size summand.
  199. *
  200. * The specified value will be added to all configured stack sizes.
  201. *
  202. * See \ref NUT_THREAD_STACK_MULT.
  203. */
  204. #ifndef NUT_THREAD_STACK_ADD
  205. #define NUT_THREAD_STACK_ADD 0
  206. #endif
  207. /*!
  208. * \brief Currently running thread.
  209. *
  210. * Pointer to the NUTTHREADINFO structure of the currently
  211. * running thread.
  212. */
  213. extern NUTTHREADINFO *runningThread;
  214. /*!
  215. * \brief List of all created threads.
  216. *
  217. * Linked list of NUTTHREADINFO structures of all threads.
  218. * New threads are put in front. This list contains at
  219. * least two threads, the main application thread followed
  220. * by the idle thread.
  221. */
  222. extern NUTTHREADINFO *nutThreadList;
  223. /*!
  224. * \brief List of ready-to-run threads.
  225. *
  226. * Priority ordered linked list of NUTTHREADINFO structures
  227. * of all threads which are ready to run. The idle thread
  228. * will always remain at the end of this list.
  229. */
  230. extern NUTTHREADINFO *runQueue;
  231. #ifndef __NUT_EMULATION__
  232. /*!
  233. * \private
  234. * \brief Initialize thread handling in the Linux emulation.
  235. *
  236. * Used in the Liux emulation only. Has to be initialized once.
  237. */
  238. extern void NutThreadInit(void);
  239. #endif
  240. #if defined(__GNUC__) && defined (__AVR_ENHANCED__)
  241. extern uint8_t NutThreadSetSleepMode(uint8_t mode);
  242. #endif
  243. /*!
  244. * \brief Create a new thread.
  245. *
  246. * If the current thread's priority is lower or equal than the default
  247. * priority (64), then the current thread is stopped and the new one
  248. * is started.
  249. *
  250. * \param name String containing the symbolic name of the new thread,
  251. * up to 8 characters long.
  252. * \param fn The thread's entry point, typically created by the
  253. * THREAD macro.
  254. * \param arg Argument pointer passed to the new thread.
  255. * \param stackSize Number of bytes of the stack space allocated for
  256. * the new thread.
  257. *
  258. * \note On ARM some targets the thread must run in ARM mode.
  259. * Thumb mode is not supported.
  260. *
  261. * \return Pointer to the NUTTHREADINFO structure or NULL to indicate an
  262. * error.
  263. */
  264. extern HANDLE NutThreadCreate(char *name, void (*fn) (void *), void *arg, size_t stackSize);
  265. /*!
  266. * \brief Set the current thread's priority.
  267. *
  268. * The priority of newly created threads is set to 64,
  269. * but may be changed when the thread starts running.
  270. *
  271. * Changing the priority level to 255 will kill the
  272. * calling thread.
  273. *
  274. * When another thread with a higher or equal priority
  275. * is ready to run, the current thread will be stopped
  276. * and control of the CPU is passed to the other thread.
  277. *
  278. * The function returns the old priority, which makes it
  279. * easy to temporarily switch to another priority and
  280. * later set back the old one.
  281. *
  282. * \param level New priority level or 255 to kill the thread. Zero
  283. * specifies the highest priority. The idle thread is
  284. * running at level 254 (lowest priority). Application
  285. * threads should use levels from 32 to 253.
  286. *
  287. * \return The old priority of this thread.
  288. *
  289. * \todo Using a specific priority level for killing a thread is actually
  290. * not the best idea. NutThreadKill() can be used instead.
  291. */
  292. extern uint8_t NutThreadSetPriority(uint8_t level);
  293. /*!
  294. * \brief Kill the running thread.
  295. *
  296. * The thread is moved from the schedule que and
  297. *
  298. * Applications generally do not call this function.
  299. */
  300. extern void NutThreadKill(void);
  301. /*!
  302. * \brief Free a thread that was previously killed and release memory
  303. * back to the OS.
  304. *
  305. * Called when another thread is killed and by the idle thread.
  306. *
  307. * Applications generally do not call this function, however you could
  308. * call it to try to reclaim memory.
  309. */
  310. extern void NutThreadDestroy(void);
  311. /*!
  312. * \brief End the current thread
  313. *
  314. * Terminates the current thread, in due course the memory associated
  315. * with the thread will be released back to the OS this is done by the
  316. * idle thread.
  317. *
  318. * \todo NutThreadKill() can be used instead of setting the priority level
  319. * to 255.
  320. */
  321. extern void NutThreadExit(void);
  322. /*!
  323. * \private
  324. * \brief Continue with the highest priority thread, which is ready to run.
  325. *
  326. * If the currently running thread lost its top position in the queue
  327. * of ready-to-run threads, then the context will be switched.
  328. *
  329. * \todo Removing a single thread from a wait queue only improves context
  330. * switching, but may result in an event time-out for remaining
  331. * threads, although events had been posted already.
  332. */
  333. extern void NutThreadResume(void);
  334. /*!
  335. * \private
  336. * \brief Resume a previously suspended thread.
  337. *
  338. * This routine is called by the system when a
  339. * sleep timer elapses.
  340. *
  341. * \note This routine is used as a timer callback
  342. * for NutSleep implementation
  343. * Applications typically do not call this
  344. * function.
  345. *
  346. * \param timer Handle of the elapsed timer.
  347. * \param th Handle of the thread to wake up.
  348. *
  349. * \todo Used by the timer module. Should be moved there, because not all
  350. * applications will use of NutSleep().
  351. */
  352. extern void NutThreadWake(HANDLE timer, HANDLE th);
  353. /*!
  354. * \brief Give up the CPU.
  355. *
  356. * If another thread within the same or higher priority
  357. * is ready to run, then the current thread is stopped
  358. * and the other one is started.
  359. *
  360. */
  361. extern void NutThreadYield(void);
  362. /*!
  363. * \private
  364. * \brief Add a thread to a prioritiy ordered queue.
  365. *
  366. * Insert the thread into a specified queue behind
  367. * the last thread with lower or equal priority.
  368. *
  369. * \param td Pointer to NUTTHREADINFO of the thread to be
  370. * inserted in the queue.
  371. * \param tqpp Pointer to the root of the queue.
  372. */
  373. extern void NutThreadAddPriQueue(NUTTHREADINFO * td, NUTTHREADINFO * volatile *tqpp);
  374. /*!
  375. * \private
  376. * \brief Remove a thread from a specified queue.
  377. *
  378. * \note Depending on the given queue, CPU interrupts must have
  379. * been disabled before calling this function.
  380. *
  381. * \param td Pointer to NUTTHREADINFO of the thread to be
  382. * removed from the queue.
  383. * \param tqpp Pointer to the root of the queue.
  384. */
  385. extern void NutThreadRemoveQueue(NUTTHREADINFO * td, NUTTHREADINFO * volatile *tqpp);
  386. /*!
  387. * \private
  388. * \brief Switch to another thread.
  389. *
  390. * Stop the current thread, saving its context. Then start the
  391. * one with the highest priority, which is ready to run.
  392. *
  393. * Application programs typically do not call this function.
  394. *
  395. * \note CPU interrupts must be disabled before calling this function.
  396. *
  397. */
  398. extern void NutThreadSwitch(void);
  399. /*!
  400. * \brief Query handle of a thread with a specific name.
  401. *
  402. * \param name Case sensitive symbolic name of the thread.
  403. *
  404. * \return Handle of the thread, if it exists. Otherwise NULL is returned.
  405. *
  406. * \todo Rarely used helper function. Should be placed in a seperate module.
  407. */
  408. extern HANDLE GetThreadByName(char *name);
  409. /*!
  410. * \brief Check all Nut/OS threads for sufficient stack space.
  411. *
  412. * See NutThreadStackAvailable() for further informations.
  413. *
  414. * \param minleft Number of bytes that should have been unused.
  415. *
  416. * \return Pointer to the first thread that used too much stack
  417. * space or NULL, if enough stack space has been available
  418. * so far in all threads.
  419. */
  420. extern NUTTHREADINFO *NutThreadStackCheck(size_t minsiz);
  421. /*!
  422. * \brief Return the size of unused stack space.
  423. *
  424. * The stack will be treated as an array of 32-bit values, which
  425. * are initially set to \ref DEADBEEF. Starting at the stack's
  426. * bottom, this function will simply count the number of array
  427. * members, which still contain the original value.
  428. *
  429. * This implicates at least three limitations:
  430. *
  431. * - Overflows may be undetected, if some local variables are unmodified.
  432. * - The result may be wrong, if local variables contain the DEADBEEF value.
  433. * - The result is a multiple of 4 bytes.
  434. *
  435. * This function is available only if NUTDEBUG_CHECK_STACK has
  436. * been defined during system build.
  437. *
  438. * \param name Symbolic name of the thread.
  439. *
  440. * \return The number of bytes which never had been touched.
  441. */
  442. extern size_t NutThreadStackAvailable(char *name);
  443. /*!
  444. * \brief Macro for thread entry definitions.
  445. */
  446. #define THREAD(threadfn, arg) \
  447. void threadfn(void *arg) __attribute__ ((noreturn)); \
  448. void threadfn(void *arg)
  449. /*@}*/
  450. #endif