port.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. /*
  2. * FreeRTOS Kernel V10.5.1 (ESP-IDF SMP modified)
  3. * Copyright (C) 2020 Cambridge Consultants Ltd.
  4. *
  5. * SPDX-FileCopyrightText: 2020 Cambridge Consultants Ltd
  6. *
  7. * SPDX-License-Identifier: MIT
  8. *
  9. * SPDX-FileContributor: 2023 Espressif Systems (Shanghai) CO LTD
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  12. * this software and associated documentation files (the "Software"), to deal in
  13. * the Software without restriction, including without limitation the rights to
  14. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  15. * the Software, and to permit persons to whom the Software is furnished to do so,
  16. * subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in all
  19. * copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  23. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  24. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  25. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  26. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. *
  28. * https://www.FreeRTOS.org
  29. * https://github.com/FreeRTOS
  30. *
  31. */
  32. /*-----------------------------------------------------------
  33. * Implementation of functions defined in portable.h for the Posix port.
  34. *
  35. * Each task has a pthread which eases use of standard debuggers
  36. * (allowing backtraces of tasks etc). Threads for tasks that are not
  37. * running are blocked in sigwait().
  38. *
  39. * Task switch is done by resuming the thread for the next task by
  40. * signaling the condition variable and then waiting on a condition variable
  41. * with the current thread.
  42. *
  43. * The timer interrupt uses SIGALRM and care is taken to ensure that
  44. * the signal handler runs only on the thread for the current task.
  45. *
  46. * Use of part of the standard C library requires care as some
  47. * functions can take pthread mutexes internally which can result in
  48. * deadlocks as the FreeRTOS kernel can switch tasks while they're
  49. * holding a pthread mutex.
  50. *
  51. * stdio (printf() and friends) should be called from a single task
  52. * only or serialized with a FreeRTOS primitive such as a binary
  53. * semaphore or mutex.
  54. *----------------------------------------------------------*/
  55. #include <errno.h>
  56. #include <pthread.h>
  57. #include <signal.h>
  58. #include <stdio.h>
  59. #include <stdlib.h>
  60. #include <string.h>
  61. #include <sys/time.h>
  62. #include <sys/times.h>
  63. #include <time.h>
  64. /* Scheduler includes. */
  65. #include "FreeRTOS.h"
  66. #include "task.h"
  67. #include "timers.h"
  68. #include "utils/wait_for_event.h"
  69. /*-----------------------------------------------------------*/
  70. #define SIG_RESUME SIGUSR1
  71. typedef struct THREAD
  72. {
  73. pthread_t pthread;
  74. TaskFunction_t pxCode;
  75. void *pvParams;
  76. BaseType_t xDying;
  77. struct event *ev;
  78. } Thread_t;
  79. /*
  80. * The additional per-thread data is stored at the beginning of the
  81. * task's stack.
  82. */
  83. static inline Thread_t *prvGetThreadFromTask(TaskHandle_t xTask)
  84. {
  85. StackType_t *pxTopOfStack = *(StackType_t **)xTask;
  86. return (Thread_t *)(pxTopOfStack + 1);
  87. }
  88. /*-----------------------------------------------------------*/
  89. static pthread_once_t hSigSetupThread = PTHREAD_ONCE_INIT;
  90. static sigset_t xAllSignals;
  91. static sigset_t xSchedulerOriginalSignalMask;
  92. static pthread_t hMainThread = ( pthread_t )NULL;
  93. static volatile BaseType_t uxCriticalNesting;
  94. /*-----------------------------------------------------------*/
  95. static BaseType_t xSchedulerEnd = pdFALSE;
  96. /*-----------------------------------------------------------*/
  97. static void prvSetupSignalsAndSchedulerPolicy( void );
  98. static void prvSetupTimerInterrupt( void );
  99. static void *prvWaitForStart( void * pvParams );
  100. static void prvSwitchThread( Thread_t * xThreadToResume,
  101. Thread_t *xThreadToSuspend );
  102. static void prvSuspendSelf( Thread_t * thread);
  103. static void prvResumeThread( Thread_t * xThreadId );
  104. static void vPortSystemTickHandler( int sig );
  105. static void vPortStartFirstTask( void );
  106. /*-----------------------------------------------------------*/
  107. static void prvFatalError( const char *pcCall, int iErrno )
  108. {
  109. fprintf( stderr, "%s: %s\n", pcCall, strerror( iErrno ) );
  110. abort();
  111. }
  112. /*
  113. * See header file for description.
  114. */
  115. StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack,
  116. StackType_t *pxEndOfStack,
  117. TaskFunction_t pxCode,
  118. void *pvParameters )
  119. {
  120. Thread_t *thread;
  121. pthread_attr_t xThreadAttributes;
  122. size_t ulStackSize;
  123. int iRet;
  124. (void)pthread_once( &hSigSetupThread, prvSetupSignalsAndSchedulerPolicy );
  125. /*
  126. * Store the additional thread data at the start of the stack.
  127. */
  128. thread = (Thread_t *)(pxTopOfStack + 1) - 1;
  129. pxTopOfStack = (StackType_t *)thread - 1;
  130. ulStackSize = (pxTopOfStack + 1 - pxEndOfStack) * sizeof(*pxTopOfStack);
  131. thread->pxCode = pxCode;
  132. thread->pvParams = pvParameters;
  133. thread->xDying = pdFALSE;
  134. pthread_attr_init( &xThreadAttributes );
  135. pthread_attr_setstack( &xThreadAttributes, pxEndOfStack, ulStackSize );
  136. thread->ev = event_create();
  137. vPortEnterCritical();
  138. iRet = pthread_create( &thread->pthread, &xThreadAttributes,
  139. prvWaitForStart, thread );
  140. if ( iRet )
  141. {
  142. prvFatalError( "pthread_create", iRet );
  143. }
  144. vPortExitCritical();
  145. return pxTopOfStack;
  146. }
  147. /*-----------------------------------------------------------*/
  148. void vPortStartFirstTask( void )
  149. {
  150. Thread_t *pxFirstThread = prvGetThreadFromTask( xTaskGetCurrentTaskHandle() );
  151. /* Start the first task. */
  152. prvResumeThread( pxFirstThread );
  153. }
  154. /*-----------------------------------------------------------*/
  155. /*
  156. * See header file for description.
  157. */
  158. BaseType_t xPortStartScheduler( void )
  159. {
  160. int iSignal;
  161. sigset_t xSignals;
  162. hMainThread = pthread_self();
  163. /* Start the timer that generates the tick ISR(SIGALRM).
  164. Interrupts are disabled here already. */
  165. prvSetupTimerInterrupt();
  166. /* Start the first task. */
  167. vPortStartFirstTask();
  168. /* Wait until signaled by vPortEndScheduler(). */
  169. sigemptyset( &xSignals );
  170. sigaddset( &xSignals, SIG_RESUME );
  171. while ( !xSchedulerEnd )
  172. {
  173. sigwait( &xSignals, &iSignal );
  174. }
  175. /* Cancel the Idle task and free its resources */
  176. #if ( INCLUDE_xTaskGetIdleTaskHandle == 1 )
  177. vPortCancelThread( xTaskGetIdleTaskHandle() );
  178. #endif
  179. #if ( configUSE_TIMERS == 1 )
  180. /* Cancel the Timer task and free its resources */
  181. vPortCancelThread( xTimerGetTimerDaemonTaskHandle() );
  182. #endif /* configUSE_TIMERS */
  183. /* Restore original signal mask. */
  184. (void)pthread_sigmask( SIG_SETMASK, &xSchedulerOriginalSignalMask, NULL );
  185. return 0;
  186. }
  187. /*-----------------------------------------------------------*/
  188. void vPortEndScheduler( void )
  189. {
  190. struct itimerval itimer;
  191. struct sigaction sigtick;
  192. Thread_t *xCurrentThread;
  193. /* Stop the timer and ignore any pending SIGALRMs that would end
  194. * up running on the main thread when it is resumed. */
  195. itimer.it_value.tv_sec = 0;
  196. itimer.it_value.tv_usec = 0;
  197. itimer.it_interval.tv_sec = 0;
  198. itimer.it_interval.tv_usec = 0;
  199. (void)setitimer( ITIMER_REAL, &itimer, NULL );
  200. sigtick.sa_flags = 0;
  201. sigtick.sa_handler = SIG_IGN;
  202. sigemptyset( &sigtick.sa_mask );
  203. sigaction( SIGALRM, &sigtick, NULL );
  204. /* Signal the scheduler to exit its loop. */
  205. xSchedulerEnd = pdTRUE;
  206. (void)pthread_kill( hMainThread, SIG_RESUME );
  207. xCurrentThread = prvGetThreadFromTask( xTaskGetCurrentTaskHandle() );
  208. prvSuspendSelf(xCurrentThread);
  209. }
  210. /*-----------------------------------------------------------*/
  211. void vPortEnterCritical( void )
  212. {
  213. if ( uxCriticalNesting == 0 )
  214. {
  215. vPortDisableInterrupts();
  216. }
  217. uxCriticalNesting++;
  218. }
  219. /*-----------------------------------------------------------*/
  220. void vPortExitCritical( void )
  221. {
  222. uxCriticalNesting--;
  223. /* If we have reached 0 then re-enable the interrupts. */
  224. if( uxCriticalNesting == 0 )
  225. {
  226. vPortEnableInterrupts();
  227. }
  228. }
  229. /*-----------------------------------------------------------*/
  230. void vPortYieldFromISR( void )
  231. {
  232. Thread_t *xThreadToSuspend;
  233. Thread_t *xThreadToResume;
  234. xThreadToSuspend = prvGetThreadFromTask( xTaskGetCurrentTaskHandle() );
  235. vTaskSwitchContext();
  236. xThreadToResume = prvGetThreadFromTask( xTaskGetCurrentTaskHandle() );
  237. prvSwitchThread( xThreadToResume, xThreadToSuspend );
  238. }
  239. /*-----------------------------------------------------------*/
  240. void vPortYield( void )
  241. {
  242. vPortEnterCritical();
  243. vPortYieldFromISR();
  244. vPortExitCritical();
  245. }
  246. /*-----------------------------------------------------------*/
  247. void vPortDisableInterrupts( void )
  248. {
  249. pthread_sigmask( SIG_BLOCK, &xAllSignals, NULL );
  250. }
  251. /*-----------------------------------------------------------*/
  252. void vPortEnableInterrupts( void )
  253. {
  254. pthread_sigmask( SIG_UNBLOCK, &xAllSignals, NULL );
  255. }
  256. /*-----------------------------------------------------------*/
  257. BaseType_t xPortSetInterruptMask( void )
  258. {
  259. /* Interrupts are always disabled inside ISRs (signals
  260. handlers). */
  261. return pdTRUE;
  262. }
  263. /*-----------------------------------------------------------*/
  264. void vPortClearInterruptMask( BaseType_t xMask )
  265. {
  266. }
  267. /*-----------------------------------------------------------*/
  268. static uint64_t prvGetTimeNs(void)
  269. {
  270. struct timespec t;
  271. clock_gettime(CLOCK_MONOTONIC, &t);
  272. return t.tv_sec * 1000000000ull + t.tv_nsec;
  273. }
  274. static uint64_t prvStartTimeNs;
  275. /* commented as part of the code below in vPortSystemTickHandler,
  276. * to adjust timing according to full demo requirements */
  277. /* static uint64_t prvTickCount; */
  278. /*
  279. * Setup the systick timer to generate the tick interrupts at the required
  280. * frequency.
  281. */
  282. void prvSetupTimerInterrupt( void )
  283. {
  284. struct itimerval itimer;
  285. int iRet;
  286. /* Initialise the structure with the current timer information. */
  287. iRet = getitimer( ITIMER_REAL, &itimer );
  288. if ( iRet )
  289. {
  290. prvFatalError( "getitimer", errno );
  291. }
  292. /* Set the interval between timer events. */
  293. itimer.it_interval.tv_sec = 0;
  294. itimer.it_interval.tv_usec = portTICK_RATE_MICROSECONDS;
  295. /* Set the current count-down. */
  296. itimer.it_value.tv_sec = 0;
  297. itimer.it_value.tv_usec = portTICK_RATE_MICROSECONDS;
  298. /* Set-up the timer interrupt. */
  299. iRet = setitimer( ITIMER_REAL, &itimer, NULL );
  300. if ( iRet )
  301. {
  302. prvFatalError( "setitimer", errno );
  303. }
  304. prvStartTimeNs = prvGetTimeNs();
  305. }
  306. /*-----------------------------------------------------------*/
  307. static void vPortSystemTickHandler( int sig )
  308. {
  309. Thread_t *pxThreadToSuspend;
  310. Thread_t *pxThreadToResume;
  311. /* uint64_t xExpectedTicks; */
  312. uxCriticalNesting++; /* Signals are blocked in this signal handler. */
  313. #if ( configUSE_PREEMPTION == 1 )
  314. pxThreadToSuspend = prvGetThreadFromTask( xTaskGetCurrentTaskHandle() );
  315. #endif
  316. /* Tick Increment, accounting for any lost signals or drift in
  317. * the timer. */
  318. /*
  319. * Comment code to adjust timing according to full demo requirements
  320. * xExpectedTicks = (prvGetTimeNs() - prvStartTimeNs)
  321. * / (portTICK_RATE_MICROSECONDS * 1000);
  322. * do { */
  323. xTaskIncrementTick();
  324. /* prvTickCount++;
  325. * } while (prvTickCount < xExpectedTicks);
  326. */
  327. #if ( configUSE_PREEMPTION == 1 )
  328. /* Select Next Task. */
  329. vTaskSwitchContext();
  330. pxThreadToResume = prvGetThreadFromTask( xTaskGetCurrentTaskHandle() );
  331. prvSwitchThread(pxThreadToResume, pxThreadToSuspend);
  332. #endif
  333. uxCriticalNesting--;
  334. }
  335. /*-----------------------------------------------------------*/
  336. void vPortThreadDying( void *pxTaskToDelete, volatile BaseType_t *pxPendYield )
  337. {
  338. Thread_t *pxThread = prvGetThreadFromTask( pxTaskToDelete );
  339. pxThread->xDying = pdTRUE;
  340. }
  341. void vPortCancelThread( void *pxTaskToDelete )
  342. {
  343. Thread_t *pxThreadToCancel = prvGetThreadFromTask( pxTaskToDelete );
  344. /*
  345. * The thread has already been suspended so it can be safely cancelled.
  346. */
  347. pthread_cancel( pxThreadToCancel->pthread );
  348. pthread_join( pxThreadToCancel->pthread, NULL );
  349. event_delete( pxThreadToCancel->ev );
  350. }
  351. /*-----------------------------------------------------------*/
  352. static void *prvWaitForStart( void * pvParams )
  353. {
  354. Thread_t *pxThread = pvParams;
  355. prvSuspendSelf(pxThread);
  356. /* Resumed for the first time, unblocks all signals. */
  357. uxCriticalNesting = 0;
  358. vPortEnableInterrupts();
  359. /* Call the task's entry point. */
  360. pxThread->pxCode( pxThread->pvParams );
  361. /* A function that implements a task must not exit or attempt to return to
  362. * its caller as there is nothing to return to. If a task wants to exit it
  363. * should instead call vTaskDelete( NULL ). Artificially force an assert()
  364. * to be triggered if configASSERT() is defined, so application writers can
  365. * catch the error. */
  366. configASSERT( pdFALSE );
  367. return NULL;
  368. }
  369. /*-----------------------------------------------------------*/
  370. static void prvSwitchThread( Thread_t *pxThreadToResume,
  371. Thread_t *pxThreadToSuspend )
  372. {
  373. BaseType_t uxSavedCriticalNesting;
  374. if ( pxThreadToSuspend != pxThreadToResume )
  375. {
  376. /*
  377. * Switch tasks.
  378. *
  379. * The critical section nesting is per-task, so save it on the
  380. * stack of the current (suspending thread), restoring it when
  381. * we switch back to this task.
  382. */
  383. uxSavedCriticalNesting = uxCriticalNesting;
  384. prvResumeThread( pxThreadToResume );
  385. if ( pxThreadToSuspend->xDying )
  386. {
  387. pthread_exit( NULL );
  388. }
  389. prvSuspendSelf( pxThreadToSuspend );
  390. uxCriticalNesting = uxSavedCriticalNesting;
  391. }
  392. }
  393. /*-----------------------------------------------------------*/
  394. static void prvSuspendSelf( Thread_t *thread )
  395. {
  396. /*
  397. * Suspend this thread by waiting for a pthread_cond_signal event.
  398. *
  399. * A suspended thread must not handle signals (interrupts) so
  400. * all signals must be blocked by calling this from:
  401. *
  402. * - Inside a critical section (vPortEnterCritical() /
  403. * vPortExitCritical()).
  404. *
  405. * - From a signal handler that has all signals masked.
  406. *
  407. * - A thread with all signals blocked with pthread_sigmask().
  408. */
  409. event_wait(thread->ev);
  410. }
  411. /*-----------------------------------------------------------*/
  412. static void prvResumeThread( Thread_t *xThreadId )
  413. {
  414. if ( pthread_self() != xThreadId->pthread )
  415. {
  416. event_signal(xThreadId->ev);
  417. }
  418. }
  419. /*-----------------------------------------------------------*/
  420. static void prvSetupSignalsAndSchedulerPolicy( void )
  421. {
  422. struct sigaction sigresume, sigtick;
  423. int iRet;
  424. hMainThread = pthread_self();
  425. /* Initialise common signal masks. */
  426. sigfillset( &xAllSignals );
  427. /* Don't block SIGINT so this can be used to break into GDB while
  428. * in a critical section. */
  429. sigdelset( &xAllSignals, SIGINT );
  430. /*
  431. * Block all signals in this thread so all new threads
  432. * inherits this mask.
  433. *
  434. * When a thread is resumed for the first time, all signals
  435. * will be unblocked.
  436. */
  437. (void)pthread_sigmask( SIG_SETMASK, &xAllSignals,
  438. &xSchedulerOriginalSignalMask );
  439. /* SIG_RESUME is only used with sigwait() so doesn't need a
  440. handler. */
  441. sigresume.sa_flags = 0;
  442. sigresume.sa_handler = SIG_IGN;
  443. sigfillset( &sigresume.sa_mask );
  444. sigtick.sa_flags = 0;
  445. sigtick.sa_handler = vPortSystemTickHandler;
  446. sigfillset( &sigtick.sa_mask );
  447. iRet = sigaction( SIG_RESUME, &sigresume, NULL );
  448. if ( iRet )
  449. {
  450. prvFatalError( "sigaction", errno );
  451. }
  452. iRet = sigaction( SIGALRM, &sigtick, NULL );
  453. if ( iRet )
  454. {
  455. prvFatalError( "sigaction", errno );
  456. }
  457. }
  458. /*-----------------------------------------------------------*/
  459. unsigned long ulPortGetRunTime( void )
  460. {
  461. struct tms xTimes;
  462. times( &xTimes );
  463. return ( unsigned long ) xTimes.tms_utime;
  464. }
  465. /*-----------------------------------------------------------*/