Thread.cpp 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /*
  2. * Copyright (C) 2016 Intel Corporation. All rights reserved.
  3. *
  4. * This file is free software: you can redistribute it and/or modify it
  5. * under the terms of the GNU General Public License as published by the
  6. * Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This file is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  12. * See the GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License along
  15. * with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include "Thread.h"
  18. #include <alloca.h>
  19. #include <limits.h>
  20. #include <sys/types.h>
  21. #include <stdio.h>
  22. #include <unistd.h>
  23. #include <utility>
  24. #include <AP_HAL/AP_HAL.h>
  25. #include <AP_Math/AP_Math.h>
  26. #include "Scheduler.h"
  27. #define STACK_POISON 0xBEBACAFE
  28. extern const AP_HAL::HAL &hal;
  29. namespace Linux {
  30. void *Thread::_run_trampoline(void *arg)
  31. {
  32. Thread *thread = static_cast<Thread *>(arg);
  33. thread->_poison_stack();
  34. thread->_run();
  35. if (thread->_auto_free) {
  36. delete thread;
  37. }
  38. return nullptr;
  39. }
  40. bool Thread::_run()
  41. {
  42. if (!_task) {
  43. return false;
  44. }
  45. _task();
  46. return true;
  47. }
  48. /* Round up to the specified alignment.
  49. *
  50. * Let u be the address p rounded up to the alignment a. Then:
  51. * u = p + a - 1 - r, where r = (p + a - 1) % a
  52. *
  53. * If p % a = 0, i.e. if p is already aligned, then:
  54. * r = a - 1 ==> u = p
  55. *
  56. * Otherwise:
  57. * r = p % a -1 ==> u = p + a - p % a
  58. *
  59. * p can be written p = q + p % a, where q is rounded down to the
  60. * alignment a. Then u = q + a.
  61. */
  62. static inline void *align_to(void *p, size_t align)
  63. {
  64. return (void *)(((uintptr_t)p + align - 1) & ~(align - 1));
  65. }
  66. void Thread::_poison_stack()
  67. {
  68. pthread_attr_t attr;
  69. size_t stack_size, guard_size;
  70. void *stackp;
  71. uint32_t *p, *curr, *begin, *end;
  72. if (pthread_getattr_np(_ctx, &attr) != 0 ||
  73. pthread_attr_getstack(&attr, &stackp, &stack_size) != 0 ||
  74. pthread_attr_getguardsize(&attr, &guard_size) != 0) {
  75. return;
  76. }
  77. stack_size /= sizeof(uint32_t);
  78. guard_size /= sizeof(uint32_t);
  79. /* The stack either grows upward or downard. The guard part always
  80. * protects the end */
  81. end = (uint32_t *)stackp;
  82. begin = end + stack_size;
  83. curr = (uint32_t *)align_to(alloca(sizeof(uint32_t)), alignof(uint32_t));
  84. /* if curr is closer to @end, the stack actually grows from low to high
  85. * virtual address: this is because this function should be executing very
  86. * early in the thread's life and close to the thread creation, assuming
  87. * the actual stack size is greater than the guard size and the stack
  88. * until now is resonably small */
  89. if (abs(curr - begin) > abs(curr - end)) {
  90. std::swap(end, begin);
  91. end -= guard_size;
  92. for (p = end; p > curr; p--) {
  93. *p = STACK_POISON;
  94. }
  95. } else {
  96. end += guard_size;
  97. /* we aligned curr to the up boundary, make sure this didn't cause us
  98. * to lose some bytes */
  99. curr--;
  100. for (p = end; p < curr; p++) {
  101. *p = STACK_POISON;
  102. }
  103. }
  104. _stack_debug.start = begin;
  105. _stack_debug.end = end;
  106. }
  107. size_t Thread::get_stack_usage()
  108. {
  109. uint32_t *p;
  110. size_t result = 0;
  111. /* Make sure we are tracking usage for this thread */
  112. if (_stack_debug.start == 0 || _stack_debug.end == 0) {
  113. return 0;
  114. }
  115. if (_stack_debug.start < _stack_debug.end) {
  116. for (p = _stack_debug.end; p > _stack_debug.start; p--) {
  117. if (*p != STACK_POISON) {
  118. break;
  119. }
  120. }
  121. result = p - _stack_debug.start;
  122. } else {
  123. for (p = _stack_debug.end; p < _stack_debug.start; p++) {
  124. if (*p != STACK_POISON) {
  125. break;
  126. }
  127. }
  128. result = _stack_debug.start - p;
  129. }
  130. return result;
  131. }
  132. bool Thread::start(const char *name, int policy, int prio)
  133. {
  134. if (_started) {
  135. return false;
  136. }
  137. struct sched_param param = { .sched_priority = prio };
  138. pthread_attr_t attr;
  139. int r;
  140. pthread_attr_init(&attr);
  141. /*
  142. we need to run as root to get realtime scheduling. Allow it to
  143. run as non-root for debugging purposes, plus to allow the Replay
  144. tool to run
  145. */
  146. if (geteuid() == 0) {
  147. if ((r = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED)) != 0 ||
  148. (r = pthread_attr_setschedpolicy(&attr, policy)) != 0 ||
  149. (r = pthread_attr_setschedparam(&attr, &param)) != 0) {
  150. AP_HAL::panic("Failed to set attributes for thread '%s': %s",
  151. name, strerror(r));
  152. }
  153. }
  154. if (_stack_size) {
  155. if (pthread_attr_setstacksize(&attr, _stack_size) != 0) {
  156. return false;
  157. }
  158. }
  159. r = pthread_create(&_ctx, &attr, &Thread::_run_trampoline, this);
  160. if (r != 0) {
  161. AP_HAL::panic("Failed to create thread '%s': %s",
  162. name, strerror(r));
  163. }
  164. pthread_attr_destroy(&attr);
  165. if (name) {
  166. pthread_setname_np(_ctx, name);
  167. }
  168. _started = true;
  169. return true;
  170. }
  171. bool Thread::is_current_thread()
  172. {
  173. return pthread_equal(pthread_self(), _ctx);
  174. }
  175. bool Thread::join()
  176. {
  177. void *ret;
  178. if (_ctx == 0) {
  179. return false;
  180. }
  181. if (pthread_join(_ctx, &ret) != 0 ||
  182. (intptr_t)ret != 0) {
  183. return false;
  184. }
  185. return true;
  186. }
  187. bool PeriodicThread::set_rate(uint32_t rate_hz)
  188. {
  189. if (_started || rate_hz == 0) {
  190. return false;
  191. }
  192. _period_usec = hz_to_usec(rate_hz);
  193. return true;
  194. }
  195. bool Thread::set_stack_size(size_t stack_size)
  196. {
  197. if (_started) {
  198. return false;
  199. }
  200. _stack_size = MAX(stack_size, (size_t) PTHREAD_STACK_MIN);
  201. return true;
  202. }
  203. bool PeriodicThread::_run()
  204. {
  205. if (_period_usec == 0) {
  206. return false;
  207. }
  208. uint64_t next_run_usec = AP_HAL::micros64() + _period_usec;
  209. while (!_should_exit) {
  210. uint64_t dt = next_run_usec - AP_HAL::micros64();
  211. if (dt > _period_usec) {
  212. // we've lost sync - restart
  213. next_run_usec = AP_HAL::micros64();
  214. } else {
  215. Scheduler::from(hal.scheduler)->microsleep(dt);
  216. }
  217. next_run_usec += _period_usec;
  218. _task();
  219. }
  220. _started = false;
  221. _should_exit = false;
  222. return true;
  223. }
  224. bool PeriodicThread::stop()
  225. {
  226. if (!is_started()) {
  227. return false;
  228. }
  229. _should_exit = true;
  230. return true;
  231. }
  232. }