xref: /btstack/platform/freertos/btstack_run_loop_freertos.c (revision a64cbea79fa5fb9daa58e135a19c6cce10f3e642)
1 /*
2  * Copyright (C) 2017 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
24  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 /*
39  *  btstack_run_loop_freertos.c
40  *
41  *  Run loop on dedicated thread on FreeRTOS
42  *  The run loop is triggered from other task/ISRs either via Event Groups
43  *  or Task Notifications if HAVE_FREERTOS_TASK_NOTIFICATIONS is defined
44  */
45 
46 #define BTSTACK_FILE__ "btstack_run_loop_freertos.c"
47 
48 #include <stddef.h> // NULL
49 
50 #include "btstack_run_loop_freertos.h"
51 
52 #include "btstack_linked_list.h"
53 #include "btstack_debug.h"
54 #include "btstack_util.h"
55 #include "hal_time_ms.h"
56 
57 // some SDKs, e.g. esp-idf, place FreeRTOS headers into an 'freertos' folder to avoid name collisions (e.g. list.h, queue.h, ..)
58 // wih this flag, the headers are properly found
59 
60 #ifdef HAVE_FREERTOS_INCLUDE_PREFIX
61 #include "freertos/FreeRTOS.h"
62 #include "freertos/task.h"
63 #include "freertos/queue.h"
64 #include "freertos/event_groups.h"
65 #include "freertos/semphr.h"
66 #else
67 #include "FreeRTOS.h"
68 #include "task.h"
69 #include "queue.h"
70 #include "event_groups.h"
71 #include "semphr.h"
72 #endif
73 
74 typedef struct function_call {
75     void (*fn)(void * arg);
76     void * arg;
77 } function_call_t;
78 
79 // pick allocation style, prefer static
80 #if( configSUPPORT_STATIC_ALLOCATION == 1 )
81 #define USE_STATIC_ALLOC
82 #elif( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
83 // ok, nothing to do
84 #else
85 #error "Either configSUPPORT_STATIC_ALLOCATION or configSUPPORT_DYNAMIC_ALLOCATION in FreeRTOSConfig.h must be 1"
86 #endif
87 
88 // queue to receive events: up to 2 calls from transport, rest for app
89 #define RUN_LOOP_QUEUE_LENGTH 20
90 #define RUN_LOOP_QUEUE_ITEM_SIZE sizeof(function_call_t)
91 
92 #ifdef USE_STATIC_ALLOC
93 static StaticQueue_t btstack_run_loop_queue_object;
94 static uint8_t btstack_run_loop_queue_storage[ RUN_LOOP_QUEUE_LENGTH * RUN_LOOP_QUEUE_ITEM_SIZE ];
95 static StaticSemaphore_t btstack_run_loop_callback_mutex_object;
96 #endif
97 
98 static QueueHandle_t        btstack_run_loop_queue;
99 static TaskHandle_t         btstack_run_loop_task;
100 static SemaphoreHandle_t    btstack_run_loop_callbacks_mutex;
101 
102 #ifndef HAVE_FREERTOS_TASK_NOTIFICATIONS
103 static EventGroupHandle_t   btstack_run_loop_event_group;
104 #endif
105 
106 // bit 0 event group reserved to wakeup run loop
107 #define EVENT_GROUP_FLAG_RUN_LOOP 1
108 
109 // the run loop
110 static bool run_loop_exit_requested;
111 
112 static uint32_t btstack_run_loop_freertos_get_time_ms(void){
113     return hal_time_ms();
114 }
115 
116 // set timer
117 static void btstack_run_loop_freertos_set_timer(btstack_timer_source_t *ts, uint32_t timeout_in_ms){
118     ts->timeout = btstack_run_loop_freertos_get_time_ms() + timeout_in_ms + 1;
119 }
120 
121 static void btstack_run_loop_freertos_trigger_from_thread(void){
122 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS
123     xTaskNotify(btstack_run_loop_task, EVENT_GROUP_FLAG_RUN_LOOP, eSetBits);
124 #else
125     xEventGroupSetBits(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP);
126 #endif
127 }
128 
129 #if defined(HAVE_FREERTOS_TASK_NOTIFICATIONS) || (INCLUDE_xEventGroupSetBitFromISR == 1)
130 static void btstack_run_loop_freertos_poll_data_sources_from_irq(void){
131     BaseType_t xHigherPriorityTaskWoken;
132 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS
133     xTaskNotifyFromISR(btstack_run_loop_task, EVENT_GROUP_FLAG_RUN_LOOP, eSetBits, &xHigherPriorityTaskWoken);
134     if (xHigherPriorityTaskWoken) {
135 #ifdef ESP_PLATFORM
136         portYIELD_FROM_ISR();
137 #else
138         portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
139 #endif
140     }
141 #else
142     xEventGroupSetBitsFromISR(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP, &xHigherPriorityTaskWoken);
143 #endif
144 }
145 #endif
146 
147 static void btstack_run_loop_freertos_trigger_exit_internal(void){
148     run_loop_exit_requested = true;
149 }
150 
151 /**
152  * Execute run_loop
153  */
154 static void btstack_run_loop_freertos_execute(void) {
155     log_debug("RL: execute");
156 
157     run_loop_exit_requested = false;
158 
159     while (true) {
160 
161         // process data sources
162         btstack_run_loop_base_poll_data_sources();
163 
164         // execute callbacks - protect list with mutex
165         while (1){
166             xSemaphoreTake(btstack_run_loop_callbacks_mutex, portMAX_DELAY);
167             btstack_context_callback_registration_t * callback_registration = (btstack_context_callback_registration_t *) btstack_linked_list_pop(&btstack_run_loop_base_callbacks);
168             xSemaphoreGive(btstack_run_loop_callbacks_mutex);
169             if (callback_registration == NULL){
170                 break;
171             }
172             (*callback_registration->callback)(callback_registration->context);
173         }
174 
175         // process registered function calls on run loop thread (deprecated)
176         while (true){
177             function_call_t message = { NULL, NULL };
178             BaseType_t res = xQueueReceive( btstack_run_loop_queue, &message, 0);
179             if (res == pdFALSE) break;
180             if (message.fn){
181                 message.fn(message.arg);
182             }
183         }
184 
185         // process timers
186         uint32_t now = btstack_run_loop_freertos_get_time_ms();
187         btstack_run_loop_base_process_timers(now);
188 
189         // exit triggered by btstack_run_loop_trigger_exit (main thread or other thread)
190         if (run_loop_exit_requested) break;
191 
192         // wait for timeout or event group/task notification
193         int32_t timeout_next_timer_ms = btstack_run_loop_base_get_time_until_timeout(now);
194 
195         uint32_t timeout_ms = portMAX_DELAY;
196         if (timeout_next_timer_ms >= 0){
197             timeout_ms = (uint32_t) timeout_next_timer_ms;
198         }
199 
200         log_debug("RL: wait with timeout %u", (int) timeout_ms);
201 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS
202         xTaskNotifyWait(pdFALSE, 0xffffffff, NULL, pdMS_TO_TICKS(timeout_ms));
203 #else
204         xEventGroupWaitBits(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP, 1, 0, pdMS_TO_TICKS(timeout_ms));
205 #endif
206     }
207 }
208 
209 static void btstack_run_loop_freertos_execute_on_main_thread(btstack_context_callback_registration_t * callback_registration){
210     // protect list with mutex
211     xSemaphoreTake(btstack_run_loop_callbacks_mutex, portMAX_DELAY);
212     btstack_run_loop_base_add_callback(callback_registration);
213     xSemaphoreGive(btstack_run_loop_callbacks_mutex);
214     btstack_run_loop_freertos_trigger_from_thread();
215 }
216 
217 static void btstack_run_loop_freertos_init(void){
218     btstack_run_loop_base_init();
219 
220 #ifdef USE_STATIC_ALLOC
221     btstack_run_loop_queue = xQueueCreateStatic(RUN_LOOP_QUEUE_LENGTH, RUN_LOOP_QUEUE_ITEM_SIZE, btstack_run_loop_queue_storage, &btstack_run_loop_queue_object);
222     btstack_run_loop_callbacks_mutex = xSemaphoreCreateMutexStatic(&btstack_run_loop_callback_mutex_object);
223 #else
224     btstack_run_loop_queue = xQueueCreate(RUN_LOOP_QUEUE_LENGTH, RUN_LOOP_QUEUE_ITEM_SIZE);
225     btstack_run_loop_callbacks_mutex = xSemaphoreCreateMutex();
226 #endif
227 
228 #ifndef HAVE_FREERTOS_TASK_NOTIFICATIONS
229     // event group to wake run loop
230     btstack_run_loop_event_group = xEventGroupCreate();
231 #endif
232 
233     // task to handle to optimize 'run on main thread'
234     btstack_run_loop_task = xTaskGetCurrentTaskHandle();
235 
236     log_info("run loop init, task %p, queue item size %u", btstack_run_loop_task, (int) sizeof(function_call_t));
237 }
238 
239 /**
240  * @brief Provide btstack_run_loop_posix instance for use with btstack_run_loop_init
241  */
242 
243 static const btstack_run_loop_t btstack_run_loop_freertos = {
244     &btstack_run_loop_freertos_init,
245     &btstack_run_loop_base_add_data_source,
246     &btstack_run_loop_base_remove_data_source,
247     &btstack_run_loop_base_enable_data_source_callbacks,
248     &btstack_run_loop_base_disable_data_source_callbacks,
249     &btstack_run_loop_freertos_set_timer,
250     &btstack_run_loop_base_add_timer,
251     &btstack_run_loop_base_remove_timer,
252     &btstack_run_loop_freertos_execute,
253     &btstack_run_loop_base_dump_timer,
254     &btstack_run_loop_freertos_get_time_ms,
255 #if defined(HAVE_FREERTOS_TASK_NOTIFICATIONS) || (INCLUDE_xEventGroupSetBitFromISR == 1)
256     &btstack_run_loop_freertos_poll_data_sources_from_irq,
257 #else
258     NULL,
259 #endif
260     btstack_run_loop_freertos_execute_on_main_thread,
261     &btstack_run_loop_freertos_trigger_exit_internal,
262 };
263 
264 const btstack_run_loop_t * btstack_run_loop_freertos_get_instance(void){
265     return &btstack_run_loop_freertos;
266 }
267 
268 
269 // @deprecated functions
270 
271 // schedules execution from regular thread
272 void btstack_run_loop_freertos_trigger(void){
273     btstack_run_loop_freertos_trigger_from_thread();
274 }
275 
276 void btstack_run_loop_freertos_execute_code_on_main_thread(void (*fn)(void *arg), void * arg){
277     // directly call function if already on btstack task
278     if (xTaskGetCurrentTaskHandle() == btstack_run_loop_task){
279         (*fn)(arg);
280         return;
281     }
282 
283     function_call_t message;
284     message.fn  = fn;
285     message.arg = arg;
286     BaseType_t res = xQueueSendToBack(btstack_run_loop_queue, &message, 0); // portMAX_DELAY);
287     if (res != pdTRUE){
288         log_error("Failed to post fn %p", fn);
289     }
290     btstack_run_loop_freertos_trigger();
291 }
292 
293 void btstack_run_loop_freertos_trigger_exit(void){
294     btstack_run_loop_freertos_trigger_exit_internal();
295 }
296 
297 #if defined(HAVE_FREERTOS_TASK_NOTIFICATIONS) || (INCLUDE_xEventGroupSetBitFromISR == 1)
298 void btstack_run_loop_freertos_trigger_from_isr(void){
299     btstack_run_loop_freertos_poll_data_sources_from_irq();
300 }
301 #endif
302