xref: /btstack/platform/freertos/btstack_run_loop_freertos.c (revision c51a1d5a2d27174e1664798afd0c3660d7fa205a)
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 MATTHIAS
24  * RINGWALD 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 #else
66 #include "FreeRTOS.h"
67 #include "task.h"
68 #include "queue.h"
69 #include "event_groups.h"
70 #include "semphr.h"
71 #endif
72 
73 typedef struct function_call {
74     void (*fn)(void * arg);
75     void * arg;
76 } function_call_t;
77 
78 // pick allocation style, prefer static
79 #if( configSUPPORT_STATIC_ALLOCATION == 1 )
80 #define USE_STATIC_ALLOC
81 #elif( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
82 // ok, nothing to do
83 #else
84 #error "Either configSUPPORT_STATIC_ALLOCATION or configSUPPORT_DYNAMIC_ALLOCATION in FreeRTOSConfig.h must be 1"
85 #endif
86 
87 // queue to receive events: up to 2 calls from transport, rest for app
88 #define RUN_LOOP_QUEUE_LENGTH 20
89 #define RUN_LOOP_QUEUE_ITEM_SIZE sizeof(function_call_t)
90 
91 #ifdef USE_STATIC_ALLOC
92 static StaticQueue_t btstack_run_loop_queue_object;
93 static uint8_t btstack_run_loop_queue_storage[ RUN_LOOP_QUEUE_LENGTH * RUN_LOOP_QUEUE_ITEM_SIZE ];
94 static StaticSemaphore_t btstack_run_loop_callback_mutex_object;
95 #endif
96 
97 static QueueHandle_t        btstack_run_loop_queue;
98 static TaskHandle_t         btstack_run_loop_task;
99 static SemaphoreHandle_t    btstack_run_loop_callbacks_mutex;
100 
101 #ifndef HAVE_FREERTOS_TASK_NOTIFICATIONS
102 static EventGroupHandle_t   btstack_run_loop_event_group;
103 #endif
104 
105 // bit 0 event group reserved to wakeup run loop
106 #define EVENT_GROUP_FLAG_RUN_LOOP 1
107 
108 // the run loop
109 static bool run_loop_exit_requested;
110 
111 static uint32_t btstack_run_loop_freertos_get_time_ms(void){
112     return hal_time_ms();
113 }
114 
115 // set timer
116 static void btstack_run_loop_freertos_set_timer(btstack_timer_source_t *ts, uint32_t timeout_in_ms){
117     ts->timeout = btstack_run_loop_freertos_get_time_ms() + timeout_in_ms + 1;
118 }
119 
120 static void btstack_run_loop_freertos_trigger_from_thread(void){
121 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS
122     xTaskNotify(btstack_run_loop_task, EVENT_GROUP_FLAG_RUN_LOOP, eSetBits);
123 #else
124     xEventGroupSetBits(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP);
125 #endif
126 }
127 
128 #if defined(HAVE_FREERTOS_TASK_NOTIFICATIONS) || (INCLUDE_xEventGroupSetBitFromISR == 1)
129 static void btstack_run_loop_freertos_poll_data_sources_from_irq(void){
130     BaseType_t xHigherPriorityTaskWoken;
131 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS
132     xTaskNotifyFromISR(btstack_run_loop_task, EVENT_GROUP_FLAG_RUN_LOOP, eSetBits, &xHigherPriorityTaskWoken);
133     if (xHigherPriorityTaskWoken) {
134 #ifdef ESP_PLATFORM
135         portYIELD_FROM_ISR();
136 #else
137         portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
138 #endif
139     }
140 #else
141     xEventGroupSetBitsFromISR(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP, &xHigherPriorityTaskWoken);
142 #endif
143 }
144 #endif
145 
146 static void btstack_run_loop_freertos_trigger_exit_internal(void){
147     run_loop_exit_requested = true;
148 }
149 
150 /**
151  * Execute run_loop
152  */
153 static void btstack_run_loop_freertos_execute(void) {
154     log_debug("RL: execute");
155 
156     run_loop_exit_requested = false;
157 
158     while (true) {
159 
160         // process data sources
161         btstack_run_loop_base_poll_data_sources();
162 
163         // execute callbacks - protect list with mutex
164         while (1){
165             xSemaphoreTake(btstack_run_loop_callbacks_mutex, portMAX_DELAY);
166             btstack_context_callback_registration_t * callback_registration = (btstack_context_callback_registration_t *) btstack_linked_list_pop(&btstack_run_loop_base_callbacks);
167             xSemaphoreGive(btstack_run_loop_callbacks_mutex);
168             if (callback_registration == NULL){
169                 break;
170             }
171             (*callback_registration->callback)(callback_registration->context);
172         }
173 
174         // process registered function calls on run loop thread (deprecated)
175         while (true){
176             function_call_t message = { NULL, NULL };
177             BaseType_t res = xQueueReceive( btstack_run_loop_queue, &message, 0);
178             if (res == pdFALSE) break;
179             if (message.fn){
180                 message.fn(message.arg);
181             }
182         }
183 
184         // process timers
185         uint32_t now = btstack_run_loop_freertos_get_time_ms();
186         btstack_run_loop_base_process_timers(now);
187 
188         // exit triggered by btstack_run_loop_trigger_exit (main thread or other thread)
189         if (run_loop_exit_requested) break;
190 
191         // wait for timeout or event group/task notification
192         int32_t timeout_next_timer_ms = btstack_run_loop_base_get_time_until_timeout(now);
193 
194         uint32_t timeout_ms = portMAX_DELAY;
195         if (timeout_next_timer_ms >= 0){
196             timeout_ms = (uint32_t) timeout_next_timer_ms;
197         }
198 
199         log_debug("RL: wait with timeout %u", (int) timeout_ms);
200 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS
201         xTaskNotifyWait(pdFALSE, 0xffffffff, NULL, pdMS_TO_TICKS(timeout_ms));
202 #else
203         xEventGroupWaitBits(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP, 1, 0, pdMS_TO_TICKS(timeout_ms));
204 #endif
205     }
206 }
207 
208 static void btstack_run_loop_freertos_execute_on_main_thread(btstack_context_callback_registration_t * callback_registration){
209     // protect list with mutex
210     xSemaphoreTake(btstack_run_loop_callbacks_mutex, portMAX_DELAY);
211     btstack_run_loop_base_add_callback(callback_registration);
212     xSemaphoreGive(btstack_run_loop_callbacks_mutex);
213     btstack_run_loop_freertos_trigger_from_thread();
214 }
215 
216 static void btstack_run_loop_freertos_init(void){
217     btstack_run_loop_base_init();
218 
219 #ifdef USE_STATIC_ALLOC
220     btstack_run_loop_queue = xQueueCreateStatic(RUN_LOOP_QUEUE_LENGTH, RUN_LOOP_QUEUE_ITEM_SIZE, btstack_run_loop_queue_storage, &btstack_run_loop_queue_object);
221     btstack_run_loop_mutex = xSemaphoreCreateMutexStatic(&btstack_run_loop_callback_mutex_object);
222 #else
223     btstack_run_loop_queue = xQueueCreate(RUN_LOOP_QUEUE_LENGTH, RUN_LOOP_QUEUE_ITEM_SIZE);
224     btstack_run_loop_callbacks_mutex = xSemaphoreCreateMutex();
225 #endif
226 
227 #ifndef HAVE_FREERTOS_TASK_NOTIFICATIONS
228     // event group to wake run loop
229     btstack_run_loop_event_group = xEventGroupCreate();
230 #endif
231 
232     // task to handle to optimize 'run on main thread'
233     btstack_run_loop_task = xTaskGetCurrentTaskHandle();
234 
235     log_info("run loop init, task %p, queue item size %u", btstack_run_loop_task, (int) sizeof(function_call_t));
236 }
237 
238 /**
239  * @brief Provide btstack_run_loop_posix instance for use with btstack_run_loop_init
240  */
241 
242 static const btstack_run_loop_t btstack_run_loop_freertos = {
243     &btstack_run_loop_freertos_init,
244     &btstack_run_loop_base_add_data_source,
245     &btstack_run_loop_base_remove_data_source,
246     &btstack_run_loop_base_enable_data_source_callbacks,
247     &btstack_run_loop_base_disable_data_source_callbacks,
248     &btstack_run_loop_freertos_set_timer,
249     &btstack_run_loop_base_add_timer,
250     &btstack_run_loop_base_remove_timer,
251     &btstack_run_loop_freertos_execute,
252     &btstack_run_loop_base_dump_timer,
253     &btstack_run_loop_freertos_get_time_ms,
254 #if defined(HAVE_FREERTOS_TASK_NOTIFICATIONS) || (INCLUDE_xEventGroupSetBitFromISR == 1)
255     &btstack_run_loop_freertos_poll_data_sources_from_irq,
256 #else
257     NULL,
258 #endif
259     btstack_run_loop_freertos_execute_on_main_thread,
260     &btstack_run_loop_freertos_trigger_exit_internal,
261 };
262 
263 const btstack_run_loop_t * btstack_run_loop_freertos_get_instance(void){
264     return &btstack_run_loop_freertos;
265 }
266 
267 
268 // @deprecated functions
269 
270 // schedules execution from regular thread
271 void btstack_run_loop_freertos_trigger(void){
272     btstack_run_loop_freertos_trigger_from_thread();
273 }
274 
275 void btstack_run_loop_freertos_execute_code_on_main_thread(void (*fn)(void *arg), void * arg){
276     // directly call function if already on btstack task
277     if (xTaskGetCurrentTaskHandle() == btstack_run_loop_task){
278         (*fn)(arg);
279         return;
280     }
281 
282     function_call_t message;
283     message.fn  = fn;
284     message.arg = arg;
285     BaseType_t res = xQueueSendToBack(btstack_run_loop_queue, &message, 0); // portMAX_DELAY);
286     if (res != pdTRUE){
287         log_error("Failed to post fn %p", fn);
288     }
289     btstack_run_loop_freertos_trigger();
290 }
291 
292 void btstack_run_loop_freertos_trigger_exit(void){
293     btstack_run_loop_freertos_trigger_exit_internal();
294 }
295 
296 #if defined(HAVE_FREERTOS_TASK_NOTIFICATIONS) || (INCLUDE_xEventGroupSetBitFromISR == 1)
297 void btstack_run_loop_freertos_trigger_from_isr(void){
298     btstack_run_loop_freertos_trigger_from_isr();
299 }
300 #endif
301