1 /*
2  * This file is part of the MicroPython project, http://micropython.org/
3  *
4  * The MIT License (MIT)
5  *
6  * Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
7  * Copyright (c) 2017 Pycom Limited
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25  * THE SOFTWARE.
26  */
27 
28 #include "stdio.h"
29 
30 #include "py/runtime.h"
31 #include "py/gc.h"
32 #include "py/mpthread.h"
33 #include "py/mphal.h"
34 #include "mpthreadport.h"
35 
36 #include "esp_task.h"
37 
38 #if MICROPY_PY_THREAD
39 
40 #define MP_THREAD_MIN_STACK_SIZE                        (4 * 1024)
41 #define MP_THREAD_DEFAULT_STACK_SIZE                    (MP_THREAD_MIN_STACK_SIZE + 1024)
42 #define MP_THREAD_PRIORITY                              (ESP_TASK_PRIO_MIN + 1)
43 
44 // this structure forms a linked list, one node per active thread
45 typedef struct _thread_t {
46     TaskHandle_t id;        // system id of thread
47     int ready;              // whether the thread is ready and running
48     void *arg;              // thread Python args, a GC root pointer
49     void *stack;            // pointer to the stack
50     size_t stack_len;       // number of words in the stack
51     struct _thread_t *next;
52 } thread_t;
53 
54 // the mutex controls access to the linked list
55 STATIC mp_thread_mutex_t thread_mutex;
56 STATIC thread_t thread_entry0;
57 STATIC thread_t *thread = NULL; // root pointer, handled by mp_thread_gc_others
58 
mp_thread_init(void * stack,uint32_t stack_len)59 void mp_thread_init(void *stack, uint32_t stack_len) {
60     mp_thread_set_state(&mp_state_ctx.thread);
61     // create the first entry in the linked list of all threads
62     thread = &thread_entry0;
63     thread->id = xTaskGetCurrentTaskHandle();
64     thread->ready = 1;
65     thread->arg = NULL;
66     thread->stack = stack;
67     thread->stack_len = stack_len;
68     thread->next = NULL;
69     mp_thread_mutex_init(&thread_mutex);
70 }
71 
mp_thread_gc_others(void)72 void mp_thread_gc_others(void) {
73     mp_thread_mutex_lock(&thread_mutex, 1);
74     for (thread_t *th = thread; th != NULL; th = th->next) {
75         gc_collect_root((void **)&th, 1);
76         gc_collect_root(&th->arg, 1); // probably not needed
77         if (th->id == xTaskGetCurrentTaskHandle()) {
78             continue;
79         }
80         if (!th->ready) {
81             continue;
82         }
83         gc_collect_root(th->stack, th->stack_len);
84     }
85     mp_thread_mutex_unlock(&thread_mutex);
86 }
87 
mp_thread_get_state(void)88 mp_state_thread_t *mp_thread_get_state(void) {
89     return pvTaskGetThreadLocalStoragePointer(NULL, 1);
90 }
91 
mp_thread_set_state(mp_state_thread_t * state)92 void mp_thread_set_state(mp_state_thread_t *state) {
93     vTaskSetThreadLocalStoragePointer(NULL, 1, state);
94 }
95 
mp_thread_start(void)96 void mp_thread_start(void) {
97     mp_thread_mutex_lock(&thread_mutex, 1);
98     for (thread_t *th = thread; th != NULL; th = th->next) {
99         if (th->id == xTaskGetCurrentTaskHandle()) {
100             th->ready = 1;
101             break;
102         }
103     }
104     mp_thread_mutex_unlock(&thread_mutex);
105 }
106 
107 STATIC void *(*ext_thread_entry)(void *) = NULL;
108 
freertos_entry(void * arg)109 STATIC void freertos_entry(void *arg) {
110     if (ext_thread_entry) {
111         ext_thread_entry(arg);
112     }
113     vTaskDelete(NULL);
114     for (;;) {;
115     }
116 }
117 
mp_thread_create_ex(void * (* entry)(void *),void * arg,size_t * stack_size,int priority,char * name)118 void mp_thread_create_ex(void *(*entry)(void *), void *arg, size_t *stack_size, int priority, char *name) {
119     // store thread entry function into a global variable so we can access it
120     ext_thread_entry = entry;
121 
122     if (*stack_size == 0) {
123         *stack_size = MP_THREAD_DEFAULT_STACK_SIZE; // default stack size
124     } else if (*stack_size < MP_THREAD_MIN_STACK_SIZE) {
125         *stack_size = MP_THREAD_MIN_STACK_SIZE; // minimum stack size
126     }
127 
128     // Allocate linked-list node (must be outside thread_mutex lock)
129     thread_t *th = m_new_obj(thread_t);
130 
131     mp_thread_mutex_lock(&thread_mutex, 1);
132 
133     // create thread
134     BaseType_t result = xTaskCreatePinnedToCore(freertos_entry, name, *stack_size / sizeof(StackType_t), arg, priority, &th->id, MP_TASK_COREID);
135     if (result != pdPASS) {
136         mp_thread_mutex_unlock(&thread_mutex);
137         mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't create thread"));
138     }
139 
140     // add thread to linked list of all threads
141     th->ready = 0;
142     th->arg = arg;
143     th->stack = pxTaskGetStackStart(th->id);
144     th->stack_len = *stack_size / sizeof(uintptr_t);
145     th->next = thread;
146     thread = th;
147 
148     // adjust the stack_size to provide room to recover from hitting the limit
149     *stack_size -= 1024;
150 
151     mp_thread_mutex_unlock(&thread_mutex);
152 }
153 
mp_thread_create(void * (* entry)(void *),void * arg,size_t * stack_size)154 void mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size) {
155     mp_thread_create_ex(entry, arg, stack_size, MP_THREAD_PRIORITY, "mp_thread");
156 }
157 
mp_thread_finish(void)158 void mp_thread_finish(void) {
159     mp_thread_mutex_lock(&thread_mutex, 1);
160     for (thread_t *th = thread; th != NULL; th = th->next) {
161         if (th->id == xTaskGetCurrentTaskHandle()) {
162             th->ready = 0;
163             break;
164         }
165     }
166     mp_thread_mutex_unlock(&thread_mutex);
167 }
168 
169 // This is called from the FreeRTOS idle task and is not within Python context,
170 // so MP_STATE_THREAD is not valid and it does not have the GIL.
vPortCleanUpTCB(void * tcb)171 void vPortCleanUpTCB(void *tcb) {
172     if (thread == NULL) {
173         // threading not yet initialised
174         return;
175     }
176     thread_t *prev = NULL;
177     mp_thread_mutex_lock(&thread_mutex, 1);
178     for (thread_t *th = thread; th != NULL; prev = th, th = th->next) {
179         // unlink the node from the list
180         if ((void *)th->id == tcb) {
181             if (prev != NULL) {
182                 prev->next = th->next;
183             } else {
184                 // move the start pointer
185                 thread = th->next;
186             }
187             // The "th" memory will eventually be reclaimed by the GC.
188             break;
189         }
190     }
191     mp_thread_mutex_unlock(&thread_mutex);
192 }
193 
mp_thread_mutex_init(mp_thread_mutex_t * mutex)194 void mp_thread_mutex_init(mp_thread_mutex_t *mutex) {
195     // Need a binary semaphore so a lock can be acquired on one Python thread
196     // and then released on another.
197     mutex->handle = xSemaphoreCreateBinaryStatic(&mutex->buffer);
198     xSemaphoreGive(mutex->handle);
199 }
200 
mp_thread_mutex_lock(mp_thread_mutex_t * mutex,int wait)201 int mp_thread_mutex_lock(mp_thread_mutex_t *mutex, int wait) {
202     return pdTRUE == xSemaphoreTake(mutex->handle, wait ? portMAX_DELAY : 0);
203 }
204 
mp_thread_mutex_unlock(mp_thread_mutex_t * mutex)205 void mp_thread_mutex_unlock(mp_thread_mutex_t *mutex) {
206     xSemaphoreGive(mutex->handle);
207 }
208 
mp_thread_deinit(void)209 void mp_thread_deinit(void) {
210     for (;;) {
211         // Find a task to delete
212         TaskHandle_t id = NULL;
213         mp_thread_mutex_lock(&thread_mutex, 1);
214         for (thread_t *th = thread; th != NULL; th = th->next) {
215             // Don't delete the current task
216             if (th->id != xTaskGetCurrentTaskHandle()) {
217                 id = th->id;
218                 break;
219             }
220         }
221         mp_thread_mutex_unlock(&thread_mutex);
222 
223         if (id == NULL) {
224             // No tasks left to delete
225             break;
226         } else {
227             // Call FreeRTOS to delete the task (it will call vPortCleanUpTCB)
228             vTaskDelete(id);
229         }
230     }
231 }
232 
233 #else
234 
vPortCleanUpTCB(void * tcb)235 void vPortCleanUpTCB(void *tcb) {
236 }
237 
238 #endif // MICROPY_PY_THREAD
239