1 /*
2 * FreeRTOS Kernel V10.4.3
3 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 * the Software, and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software. If you wish to use our Amazon
14 * FreeRTOS name, please do so in a fair use way that does not cause confusion.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 * https://www.FreeRTOS.org
24 * https://github.com/FreeRTOS
25 *
26 * 1 tab == 4 spaces!
27 */
28
29 /*
30 * Copyright (c) 2015-2019 Cadence Design Systems, Inc.
31 *
32 * Permission is hereby granted, free of charge, to any person obtaining
33 * a copy of this software and associated documentation files (the
34 * "Software"), to deal in the Software without restriction, including
35 * without limitation the rights to use, copy, modify, merge, publish,
36 * distribute, sublicense, and/or sell copies of the Software, and to
37 * permit persons to whom the Software is furnished to do so, subject to
38 * the following conditions:
39 *
40 * The above copyright notice and this permission notice shall be included
41 * in all copies or substantial portions of the Software.
42 *
43 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
44 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
45 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
46 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
47 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
48 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
49 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
50 */
51
52 #include "sdkconfig.h"
53 #include <stdint.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <stdarg.h>
57 #include <xtensa/config/core.h>
58 #include <xtensa/xtensa_context.h>
59 #include "soc/soc_caps.h"
60 #include "esp_private/crosscore_int.h"
61 #include "esp_system.h"
62 #include "esp_log.h"
63 #include "esp_int_wdt.h"
64 #include "esp_app_trace.h" /* Required for esp_apptrace_init. [refactor-todo] */
65 #include "FreeRTOS.h" /* This pulls in portmacro.h */
66 #include "task.h" /* Required for TaskHandle_t, tskNO_AFFINITY, and vTaskStartScheduler */
67 #include "port_systick.h"
68
69 _Static_assert(tskNO_AFFINITY == CONFIG_FREERTOS_NO_AFFINITY, "incorrect tskNO_AFFINITY value");
70
71
72 /* ---------------------------------------------------- Variables ------------------------------------------------------
73 *
74 * ------------------------------------------------------------------------------------------------------------------ */
75
76 static const char *TAG = "cpu_start"; /* [refactor-todo]: might be appropriate to change in the future, but for now maintain the same log output */
77 extern volatile int port_xSchedulerRunning[portNUM_PROCESSORS];
78 unsigned port_interruptNesting[portNUM_PROCESSORS] = {0}; // Interrupt nesting level. Increased/decreased in portasm.c, _frxt_int_enter/_frxt_int_exit
79 BaseType_t port_uxCriticalNesting[portNUM_PROCESSORS] = {0};
80 BaseType_t port_uxOldInterruptState[portNUM_PROCESSORS] = {0};
81
82
83 /* ------------------------------------------------ FreeRTOS Portable --------------------------------------------------
84 * - Provides implementation for functions required by FreeRTOS
85 * - Declared in portable.h
86 * ------------------------------------------------------------------------------------------------------------------ */
87
88 // ----------------- Scheduler Start/End -------------------
89
90 /* Defined in xtensa_context.S */
91 extern void _xt_coproc_init(void);
92
xPortStartScheduler(void)93 BaseType_t xPortStartScheduler( void )
94 {
95 portDISABLE_INTERRUPTS();
96 // Interrupts are disabled at this point and stack contains PS with enabled interrupts when task context is restored
97
98 #if XCHAL_CP_NUM > 0
99 /* Initialize co-processor management for tasks. Leave CPENABLE alone. */
100 _xt_coproc_init();
101 #endif
102
103 /* Setup the hardware to generate the tick. */
104 vPortSetupTimer();
105
106 port_xSchedulerRunning[xPortGetCoreID()] = 1;
107
108 // Cannot be directly called from C; never returns
109 __asm__ volatile ("call0 _frxt_dispatch\n");
110
111 /* Should not get here. */
112 return pdTRUE;
113 }
114
vPortEndScheduler(void)115 void vPortEndScheduler( void )
116 {
117 /* It is unlikely that the Xtensa port will get stopped. If required simply
118 disable the tick interrupt here. */
119 abort();
120 }
121
122 // ------------------------ Stack --------------------------
123
124 // User exception dispatcher when exiting
125 void _xt_user_exit(void);
126
127 #if CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER
128 // Wrapper to allow task functions to return (increases stack overhead by 16 bytes)
vPortTaskWrapper(TaskFunction_t pxCode,void * pvParameters)129 static void vPortTaskWrapper(TaskFunction_t pxCode, void *pvParameters)
130 {
131 pxCode(pvParameters);
132 //FreeRTOS tasks should not return. Log the task name and abort.
133 char *pcTaskName = pcTaskGetTaskName(NULL);
134 ESP_LOGE("FreeRTOS", "FreeRTOS Task \"%s\" should not return, Aborting now!", pcTaskName);
135 abort();
136 }
137 #endif
138
139 #if portUSING_MPU_WRAPPERS
pxPortInitialiseStack(StackType_t * pxTopOfStack,TaskFunction_t pxCode,void * pvParameters,BaseType_t xRunPrivileged)140 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged )
141 #else
142 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
143 #endif
144 {
145 StackType_t *sp, *tp;
146 XtExcFrame *frame;
147 #if XCHAL_CP_NUM > 0
148 uint32_t *p;
149 #endif
150 uint32_t *threadptr;
151 void *task_thread_local_start;
152 extern int _thread_local_start, _thread_local_end, _flash_rodata_start, _flash_rodata_align;
153 // TODO: check that TLS area fits the stack
154 uint32_t thread_local_sz = (uint8_t *)&_thread_local_end - (uint8_t *)&_thread_local_start;
155
156 thread_local_sz = ALIGNUP(0x10, thread_local_sz);
157
158 /* Initialize task's stack so that we have the following structure at the top:
159
160 ----LOW ADDRESSES ----------------------------------------HIGH ADDRESSES----------
161 task stack | interrupt stack frame | thread local vars | co-processor save area |
162 ----------------------------------------------------------------------------------
163 | |
164 SP pxTopOfStack
165
166 All parts are aligned to 16 byte boundary. */
167 sp = (StackType_t *) (((UBaseType_t)pxTopOfStack - XT_CP_SIZE - thread_local_sz - XT_STK_FRMSZ) & ~0xf);
168
169 /* Clear the entire frame (do not use memset() because we don't depend on C library) */
170 for (tp = sp; tp <= pxTopOfStack; ++tp) {
171 *tp = 0;
172 }
173
174 frame = (XtExcFrame *) sp;
175
176 /* Explicitly initialize certain saved registers */
177 #if CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER
178 frame->pc = (UBaseType_t) vPortTaskWrapper; /* task wrapper */
179 #else
180 frame->pc = (UBaseType_t) pxCode; /* task entrypoint */
181 #endif
182 frame->a0 = 0; /* to terminate GDB backtrace */
183 frame->a1 = (UBaseType_t) sp + XT_STK_FRMSZ; /* physical top of stack frame */
184 frame->exit = (UBaseType_t) _xt_user_exit; /* user exception exit dispatcher */
185
186 /* Set initial PS to int level 0, EXCM disabled ('rfe' will enable), user mode. */
187 /* Also set entry point argument parameter. */
188 #ifdef __XTENSA_CALL0_ABI__
189 #if CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER
190 frame->a2 = (UBaseType_t) pxCode;
191 frame->a3 = (UBaseType_t) pvParameters;
192 #else
193 frame->a2 = (UBaseType_t) pvParameters;
194 #endif
195 frame->ps = PS_UM | PS_EXCM;
196 #else /* __XTENSA_CALL0_ABI__ */
197 /* + for windowed ABI also set WOE and CALLINC (pretend task was 'call4'd). */
198 #if CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER
199 frame->a6 = (UBaseType_t) pxCode;
200 frame->a7 = (UBaseType_t) pvParameters;
201 #else
202 frame->a6 = (UBaseType_t) pvParameters;
203 #endif
204 frame->ps = PS_UM | PS_EXCM | PS_WOE | PS_CALLINC(1);
205 #endif /* __XTENSA_CALL0_ABI__ */
206
207 #ifdef XT_USE_SWPRI
208 /* Set the initial virtual priority mask value to all 1's. */
209 frame->vpri = 0xFFFFFFFF;
210 #endif
211
212 /* Init threadptr register and set up TLS run-time area.
213 * The diagram in port/riscv/port.c illustrates the calculations below.
214 */
215 task_thread_local_start = (void *)(((uint32_t)pxTopOfStack - XT_CP_SIZE - thread_local_sz) & ~0xf);
216 memcpy(task_thread_local_start, &_thread_local_start, thread_local_sz);
217 threadptr = (uint32_t *)(sp + XT_STK_EXTRA);
218 /* Calculate THREADPTR value.
219 * The generated code will add THREADPTR value to a constant value determined at link time,
220 * to get the address of the TLS variable.
221 * The constant value is calculated by the linker as follows
222 * (search for 'tpoff' in elf32-xtensa.c in BFD):
223 * offset = address - tls_section_vma + align_up(TCB_SIZE, tls_section_alignment)
224 * where TCB_SIZE is hardcoded to 8.
225 * Note this is slightly different compared to the RISC-V port, where offset = address - tls_section_vma.
226 */
227 const uint32_t tls_section_alignment = (uint32_t) &_flash_rodata_align; /* ALIGN value of .flash.rodata section */
228 const uint32_t tcb_size = 8; /* Unrelated to FreeRTOS, this is the constant from BFD */
229 const uint32_t base = (tcb_size + tls_section_alignment - 1) & (~(tls_section_alignment - 1));
230 *threadptr = (uint32_t)task_thread_local_start - ((uint32_t)&_thread_local_start - (uint32_t)&_flash_rodata_start) - base;
231
232 #if XCHAL_CP_NUM > 0
233 /* Init the coprocessor save area (see xtensa_context.h) */
234 /* No access to TCB here, so derive indirectly. Stack growth is top to bottom.
235 * //p = (uint32_t *) xMPUSettings->coproc_area;
236 */
237 p = (uint32_t *)(((uint32_t) pxTopOfStack - XT_CP_SIZE) & ~0xf);
238 configASSERT( ( uint32_t ) p >= frame->a1 );
239 p[0] = 0;
240 p[1] = 0;
241 p[2] = (((uint32_t) p) + 12 + XCHAL_TOTAL_SA_ALIGN - 1) & -XCHAL_TOTAL_SA_ALIGN;
242 #endif /* XCHAL_CP_NUM */
243
244 return sp;
245 }
246
247
248
249 /* ---------------------------------------------- Port Implementations -------------------------------------------------
250 *
251 * ------------------------------------------------------------------------------------------------------------------ */
252
253 // --------------------- Interrupts ------------------------
254
xPortInIsrContext(void)255 BaseType_t xPortInIsrContext(void)
256 {
257 unsigned int irqStatus;
258 BaseType_t ret;
259 irqStatus = portSET_INTERRUPT_MASK_FROM_ISR();
260 ret = (port_interruptNesting[xPortGetCoreID()] != 0);
261 portCLEAR_INTERRUPT_MASK_FROM_ISR(irqStatus);
262 return ret;
263 }
264
vPortAssertIfInISR(void)265 void vPortAssertIfInISR(void)
266 {
267 configASSERT(xPortInIsrContext());
268 }
269
xPortInterruptedFromISRContext(void)270 BaseType_t IRAM_ATTR xPortInterruptedFromISRContext(void)
271 {
272 return (port_interruptNesting[xPortGetCoreID()] != 0);
273 }
274
275 // ------------------ Critical Sections --------------------
276
xPortEnterCriticalTimeout(portMUX_TYPE * mux,BaseType_t timeout)277 BaseType_t __attribute__((optimize("-O3"))) xPortEnterCriticalTimeout(portMUX_TYPE *mux, BaseType_t timeout)
278 {
279 /* Interrupts may already be disabled (if this function is called in nested
280 * manner). However, there's no atomic operation that will allow us to check,
281 * thus we have to disable interrupts again anyways.
282 *
283 * However, if this is call is NOT nested (i.e., the first call to enter a
284 * critical section), we will save the previous interrupt level so that the
285 * saved level can be restored on the last call to exit the critical.
286 */
287 BaseType_t xOldInterruptLevel = portSET_INTERRUPT_MASK_FROM_ISR();
288 if (!spinlock_acquire(mux, timeout)) {
289 //Timed out attempting to get spinlock. Restore previous interrupt level and return
290 portCLEAR_INTERRUPT_MASK_FROM_ISR(xOldInterruptLevel);
291 return pdFAIL;
292 }
293 //Spinlock acquired. Increment the critical nesting count.
294 BaseType_t coreID = xPortGetCoreID();
295 BaseType_t newNesting = port_uxCriticalNesting[coreID] + 1;
296 port_uxCriticalNesting[coreID] = newNesting;
297 //If this is the first entry to a critical section. Save the old interrupt level.
298 if ( newNesting == 1 ) {
299 port_uxOldInterruptState[coreID] = xOldInterruptLevel;
300 }
301 return pdPASS;
302 }
303
vPortExitCritical(portMUX_TYPE * mux)304 void __attribute__((optimize("-O3"))) vPortExitCritical(portMUX_TYPE *mux)
305 {
306 /* This function may be called in a nested manner. Therefore, we only need
307 * to reenable interrupts if this is the last call to exit the critical. We
308 * can use the nesting count to determine whether this is the last exit call.
309 */
310 spinlock_release(mux);
311 BaseType_t coreID = xPortGetCoreID();
312 BaseType_t nesting = port_uxCriticalNesting[coreID];
313
314 if (nesting > 0) {
315 nesting--;
316 port_uxCriticalNesting[coreID] = nesting;
317 //This is the last exit call, restore the saved interrupt level
318 if ( nesting == 0 ) {
319 portCLEAR_INTERRUPT_MASK_FROM_ISR(port_uxOldInterruptState[coreID]);
320 }
321 }
322 }
323
xPortEnterCriticalTimeoutCompliance(portMUX_TYPE * mux,BaseType_t timeout)324 BaseType_t xPortEnterCriticalTimeoutCompliance(portMUX_TYPE *mux, BaseType_t timeout)
325 {
326 BaseType_t ret;
327 if (!xPortInIsrContext()) {
328 ret = xPortEnterCriticalTimeout(mux, timeout);
329 } else {
330 esp_rom_printf("port*_CRITICAL called from ISR context. Aborting!\n");
331 abort();
332 ret = pdFAIL;
333 }
334 return ret;
335 }
336
vPortExitCriticalCompliance(portMUX_TYPE * mux)337 void vPortExitCriticalCompliance(portMUX_TYPE *mux)
338 {
339 if (!xPortInIsrContext()) {
340 vPortExitCritical(mux);
341 } else {
342 esp_rom_printf("port*_CRITICAL called from ISR context. Aborting!\n");
343 abort();
344 }
345 }
346
347 // ---------------------- Yielding -------------------------
348
vPortYieldOtherCore(BaseType_t coreid)349 void vPortYieldOtherCore( BaseType_t coreid )
350 {
351 esp_crosscore_int_send_yield( coreid );
352 }
353
354 extern void _frxt_setup_switch( void ); //Defined in portasm.S
355
vPortEvaluateYieldFromISR(int argc,...)356 void IRAM_ATTR vPortEvaluateYieldFromISR(int argc, ...)
357 {
358 BaseType_t xYield;
359 va_list ap;
360 va_start(ap, argc);
361
362 if (argc) {
363 xYield = (BaseType_t)va_arg(ap, int);
364 va_end(ap);
365 } else {
366 //it is a empty parameter vPortYieldFromISR macro call:
367 va_end(ap);
368 traceISR_EXIT_TO_SCHEDULER();
369 _frxt_setup_switch();
370 return;
371 }
372
373 //Yield exists, so need evaluate it first then switch:
374 if (xYield == pdTRUE) {
375 traceISR_EXIT_TO_SCHEDULER();
376 _frxt_setup_switch();
377 }
378 }
379
380 // ------------------- Hook Functions ----------------------
381
vApplicationStackOverflowHook(TaskHandle_t xTask,char * pcTaskName)382 void __attribute__((weak)) vApplicationStackOverflowHook( TaskHandle_t xTask, char *pcTaskName )
383 {
384 #define ERR_STR1 "***ERROR*** A stack overflow in task "
385 #define ERR_STR2 " has been detected."
386 const char *str[] = {ERR_STR1, pcTaskName, ERR_STR2};
387
388 char buf[sizeof(ERR_STR1) + CONFIG_FREERTOS_MAX_TASK_NAME_LEN + sizeof(ERR_STR2) + 1 /* null char */] = { 0 };
389
390 char *dest = buf;
391 for (size_t i = 0 ; i < sizeof(str) / sizeof(str[0]); i++) {
392 dest = strcat(dest, str[i]);
393 }
394 esp_system_abort(buf);
395 }
396
397 // ----------------------- System --------------------------
398
xPortGetTickRateHz(void)399 uint32_t xPortGetTickRateHz(void)
400 {
401 return (uint32_t)configTICK_RATE_HZ;
402 }
403
404
405 #define STACK_WATCH_AREA_SIZE 32
406 #define STACK_WATCH_POINT_NUMBER (SOC_CPU_WATCHPOINTS_NUM - 1)
407
vPortSetStackWatchpoint(void * pxStackStart)408 void vPortSetStackWatchpoint( void *pxStackStart )
409 {
410 //Set watchpoint 1 to watch the last 32 bytes of the stack.
411 //Unfortunately, the Xtensa watchpoints can't set a watchpoint on a random [base - base+n] region because
412 //the size works by masking off the lowest address bits. For that reason, we futz a bit and watch the lowest 32
413 //bytes of the stack we can actually watch. In general, this can cause the watchpoint to be triggered at most
414 //28 bytes early. The value 32 is chosen because it's larger than the stack canary, which in FreeRTOS is 20 bytes.
415 //This way, we make sure we trigger before/when the stack canary is corrupted, not after.
416 int addr = (int)pxStackStart;
417 addr = (addr + 31) & (~31);
418 esp_cpu_set_watchpoint(STACK_WATCH_POINT_NUMBER, (char *)addr, 32, ESP_WATCHPOINT_STORE);
419 }
420
421 /* ---------------------------------------------- Misc Implementations -------------------------------------------------
422 *
423 * ------------------------------------------------------------------------------------------------------------------ */
424
425 // -------------------- Co-Processor -----------------------
426
427 /*
428 * Used to set coprocessor area in stack. Current hack is to reuse MPU pointer for coprocessor area.
429 */
430 #if portUSING_MPU_WRAPPERS
vPortStoreTaskMPUSettings(xMPU_SETTINGS * xMPUSettings,const struct xMEMORY_REGION * const xRegions,StackType_t * pxBottomOfStack,uint32_t usStackDepth)431 void vPortStoreTaskMPUSettings( xMPU_SETTINGS *xMPUSettings, const struct xMEMORY_REGION *const xRegions, StackType_t *pxBottomOfStack, uint32_t usStackDepth )
432 {
433 #if XCHAL_CP_NUM > 0
434 xMPUSettings->coproc_area = ( StackType_t * ) ( ( uint32_t ) ( pxBottomOfStack + usStackDepth - 1 ));
435 xMPUSettings->coproc_area = ( StackType_t * ) ( ( ( portPOINTER_SIZE_TYPE ) xMPUSettings->coproc_area ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) );
436 xMPUSettings->coproc_area = ( StackType_t * ) ( ( ( uint32_t ) xMPUSettings->coproc_area - XT_CP_SIZE ) & ~0xf );
437
438
439 /* NOTE: we cannot initialize the coprocessor save area here because FreeRTOS is going to
440 * clear the stack area after we return. This is done in pxPortInitialiseStack().
441 */
442 #endif
443 }
444
vPortReleaseTaskMPUSettings(xMPU_SETTINGS * xMPUSettings)445 void vPortReleaseTaskMPUSettings( xMPU_SETTINGS *xMPUSettings )
446 {
447 /* If task has live floating point registers somewhere, release them */
448 _xt_coproc_release( xMPUSettings->coproc_area );
449 }
450 #endif /* portUSING_MPU_WRAPPERS */
451
452 // --------------------- App Start-up ----------------------
453
454 #if !CONFIG_FREERTOS_UNICORE
esp_startup_start_app_other_cores(void)455 void esp_startup_start_app_other_cores(void)
456 {
457 // For now, we only support up to two core: 0 and 1.
458 if (xPortGetCoreID() >= 2) {
459 abort();
460 }
461
462 // Wait for FreeRTOS initialization to finish on PRO CPU
463 while (port_xSchedulerRunning[0] == 0) {
464 ;
465 }
466
467 #if CONFIG_APPTRACE_ENABLE
468 // [refactor-todo] move to esp_system initialization
469 esp_err_t err = esp_apptrace_init();
470 assert(err == ESP_OK && "Failed to init apptrace module on APP CPU!");
471 #endif
472
473 #if CONFIG_ESP_INT_WDT
474 //Initialize the interrupt watch dog for CPU1.
475 esp_int_wdt_cpu_init();
476 #endif
477
478 esp_crosscore_int_init();
479
480 ESP_EARLY_LOGI(TAG, "Starting scheduler on APP CPU.");
481 xPortStartScheduler();
482 abort(); /* Only get to here if FreeRTOS somehow very broken */
483 }
484 #endif // !CONFIG_FREERTOS_UNICORE
485
486 extern void esp_startup_start_app_common(void);
487
esp_startup_start_app(void)488 void esp_startup_start_app(void)
489 {
490 #if !CONFIG_ESP_INT_WDT
491 #if CONFIG_ESP32_ECO3_CACHE_LOCK_FIX
492 assert(!soc_has_cache_lock_bug() && "ESP32 Rev 3 + Dual Core + PSRAM requires INT WDT enabled in project config!");
493 #endif
494 #endif
495
496 esp_startup_start_app_common();
497
498 ESP_LOGI(TAG, "Starting scheduler on PRO CPU.");
499 vTaskStartScheduler();
500 }
501