1 /*
2 * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <esp_expression_with_stack.h>
8 #include <setjmp.h>
9 #include <string.h>
10 #include "freertos/FreeRTOS.h"
11 #include "freertos/portmacro.h"
12
13 StackType_t *xtensa_shared_stack;
14 shared_stack_function xtensa_shared_stack_callback;
15 jmp_buf xtensa_shared_stack_env;
16 bool xtensa_shared_stack_function_done = false;
17 static portMUX_TYPE xtensa_shared_stack_spinlock = portMUX_INITIALIZER_UNLOCKED;
18 static void *current_task_stack = NULL;
19
20 extern void esp_shared_stack_invoke_function(void);
21
esp_switch_stack_setup(StackType_t * stack,size_t stack_size)22 static void esp_switch_stack_setup(StackType_t *stack, size_t stack_size)
23 {
24 //We need also to tweak current task stackpointer to avoid erroneous
25 //stack overflow indication, so fills the stack with freertos known pattern:
26 memset(stack, 0xa5U, stack_size * sizeof(StackType_t));
27
28 StaticTask_t *current = (StaticTask_t *)xTaskGetCurrentTaskHandle();
29 //Then put the fake stack inside of TCB:
30 current_task_stack = current->pxDummy6;
31 current->pxDummy6 = (void *)stack;
32
33 StackType_t *top_of_stack = stack + stack_size;
34
35 //Align stack to a 16byte boundary, as required by CPU specific:
36 top_of_stack = (StackType_t *)(((UBaseType_t)(top_of_stack - 16) & ~0xf));
37
38 #if CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK
39 vPortSetStackWatchpoint(stack);
40 #endif
41
42 xtensa_shared_stack = top_of_stack;
43 }
44
45
esp_execute_shared_stack_function(SemaphoreHandle_t lock,void * stack,size_t stack_size,shared_stack_function function)46 void esp_execute_shared_stack_function(SemaphoreHandle_t lock, void *stack, size_t stack_size, shared_stack_function function)
47 {
48 assert(lock);
49 assert(stack);
50 assert(stack_size > 0 && stack_size >= CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE);
51 assert(function);
52
53 xSemaphoreTake(lock, portMAX_DELAY);
54 portENTER_CRITICAL(&xtensa_shared_stack_spinlock);
55 xtensa_shared_stack_function_done = false;
56 esp_switch_stack_setup(stack, stack_size);
57 xtensa_shared_stack_callback = function;
58 portEXIT_CRITICAL(&xtensa_shared_stack_spinlock);
59
60 setjmp(xtensa_shared_stack_env);
61 if(!xtensa_shared_stack_function_done) {
62 esp_shared_stack_invoke_function();
63 }
64
65 portENTER_CRITICAL(&xtensa_shared_stack_spinlock);
66 StaticTask_t *current = (StaticTask_t *)xTaskGetCurrentTaskHandle();
67
68 //Restore current task stack:
69 current->pxDummy6 = (StackType_t *)current_task_stack;
70 #if CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK
71 vPortSetStackWatchpoint(current->pxDummy6);
72 #endif
73 portEXIT_CRITICAL(&xtensa_shared_stack_spinlock);
74
75 xSemaphoreGive(lock);
76 }
77