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 #endif 71 72 typedef struct function_call { 73 void (*fn)(void * arg); 74 void * arg; 75 } function_call_t; 76 77 // pick allocation style, prefer static 78 #if( configSUPPORT_STATIC_ALLOCATION == 1 ) 79 #define USE_STATIC_ALLOC 80 #elif( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) 81 // ok, nothing to do 82 #else 83 #error "Either configSUPPORT_STATIC_ALLOCATION or configSUPPORT_DYNAMIC_ALLOCATION in FreeRTOSConfig.h must be 1" 84 #endif 85 86 // queue to receive events: up to 2 calls from transport, rest for app 87 #define RUN_LOOP_QUEUE_LENGTH 20 88 #define RUN_LOOP_QUEUE_ITEM_SIZE sizeof(function_call_t) 89 90 #ifdef USE_STATIC_ALLOC 91 static StaticQueue_t btstack_run_loop_queue_object; 92 static uint8_t btstack_run_loop_queue_storage[ RUN_LOOP_QUEUE_LENGTH * RUN_LOOP_QUEUE_ITEM_SIZE ]; 93 #endif 94 95 static QueueHandle_t btstack_run_loop_queue; 96 static TaskHandle_t btstack_run_loop_task; 97 98 #ifndef HAVE_FREERTOS_TASK_NOTIFICATIONS 99 static EventGroupHandle_t btstack_run_loop_event_group; 100 #endif 101 102 // bit 0 event group reserved to wakeup run loop 103 #define EVENT_GROUP_FLAG_RUN_LOOP 1 104 105 // the run loop 106 static btstack_linked_list_t timers; 107 static btstack_linked_list_t data_sources; 108 static bool run_loop_exit_requested; 109 110 static uint32_t btstack_run_loop_freertos_get_time_ms(void){ 111 return hal_time_ms(); 112 } 113 114 // set timer 115 static void btstack_run_loop_freertos_set_timer(btstack_timer_source_t *ts, uint32_t timeout_in_ms){ 116 ts->timeout = btstack_run_loop_freertos_get_time_ms() + timeout_in_ms + 1; 117 } 118 119 /** 120 * Add timer to run_loop (keep list sorted) 121 */ 122 static void btstack_run_loop_freertos_add_timer(btstack_timer_source_t *ts){ 123 btstack_linked_item_t *it; 124 for (it = (btstack_linked_item_t *) &timers; it->next ; it = it->next){ 125 // don't add timer that's already in there 126 btstack_timer_source_t * next = (btstack_timer_source_t *) it->next; 127 if (next == ts){ 128 log_error( "btstack_run_loop_timer_add error: timer to add already in list!"); 129 return; 130 } 131 // exit if new timeout before list timeout 132 int32_t delta = btstack_time_delta(ts->timeout, next->timeout); 133 if (delta < 0) break; 134 } 135 ts->item.next = it->next; 136 it->next = (btstack_linked_item_t *) ts; 137 } 138 139 /** 140 * Remove timer from run loop 141 */ 142 static bool btstack_run_loop_freertos_remove_timer(btstack_timer_source_t *ts){ 143 return btstack_linked_list_remove(&timers, (btstack_linked_item_t *) ts); 144 } 145 146 static void btstack_run_loop_freertos_dump_timer(void){ 147 #ifdef ENABLE_LOG_INFO 148 btstack_linked_item_t *it; 149 int i = 0; 150 for (it = (btstack_linked_item_t *) timers; it ; it = it->next){ 151 btstack_timer_source_t *ts = (btstack_timer_source_t*) it; 152 log_info("timer %u, timeout %u\n", i, (unsigned int) ts->timeout); 153 } 154 #endif 155 } 156 157 // schedules execution from regular thread 158 void btstack_run_loop_freertos_trigger(void){ 159 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS 160 xTaskNotify(btstack_run_loop_task, EVENT_GROUP_FLAG_RUN_LOOP, eSetBits); 161 #else 162 xEventGroupSetBits(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP); 163 #endif 164 } 165 166 void btstack_run_loop_freertos_execute_code_on_main_thread(void (*fn)(void *arg), void * arg){ 167 168 // directly call function if already on btstack task 169 if (xTaskGetCurrentTaskHandle() == btstack_run_loop_task){ 170 (*fn)(arg); 171 return; 172 } 173 174 function_call_t message; 175 message.fn = fn; 176 message.arg = arg; 177 BaseType_t res = xQueueSendToBack(btstack_run_loop_queue, &message, 0); // portMAX_DELAY); 178 if (res != pdTRUE){ 179 log_error("Failed to post fn %p", fn); 180 } 181 btstack_run_loop_freertos_trigger(); 182 } 183 184 #if defined(HAVE_FREERTOS_TASK_NOTIFICATIONS) || (INCLUDE_xEventGroupSetBitFromISR == 1) 185 void btstack_run_loop_freertos_trigger_from_isr(void){ 186 BaseType_t xHigherPriorityTaskWoken; 187 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS 188 xTaskNotifyFromISR(btstack_run_loop_task, EVENT_GROUP_FLAG_RUN_LOOP, eSetBits, &xHigherPriorityTaskWoken); 189 if (xHigherPriorityTaskWoken) { 190 #ifdef ESP_PLATFORM 191 portYIELD_FROM_ISR(); 192 #else 193 portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); 194 #endif 195 } 196 #else 197 xEventGroupSetBitsFromISR(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP, &xHigherPriorityTaskWoken); 198 #endif 199 } 200 201 void btstack_run_loop_freertos_execute_code_on_main_thread_from_isr(void (*fn)(void *arg), void * arg){ 202 function_call_t message; 203 message.fn = fn; 204 message.arg = arg; 205 BaseType_t xHigherPriorityTaskWoken; 206 xQueueSendToBackFromISR(btstack_run_loop_queue, &message, &xHigherPriorityTaskWoken); 207 btstack_run_loop_freertos_trigger_from_isr(); 208 } 209 #endif 210 211 void btstack_run_loop_freertos_trigger_exit(void){ 212 run_loop_exit_requested = true; 213 } 214 215 /** 216 * Execute run_loop 217 */ 218 static void btstack_run_loop_freertos_execute(void) { 219 log_debug("RL: execute"); 220 221 run_loop_exit_requested = false; 222 223 while (true) { 224 225 // process data sources 226 btstack_data_source_t *ds; 227 btstack_data_source_t *next; 228 for (ds = (btstack_data_source_t *) data_sources; ds != NULL ; ds = next){ 229 next = (btstack_data_source_t *) ds->item.next; // cache pointer to next data_source to allow data source to remove itself 230 if (ds->flags & DATA_SOURCE_CALLBACK_POLL){ 231 ds->process(ds, DATA_SOURCE_CALLBACK_POLL); 232 } 233 } 234 235 // process registered function calls on run loop thread 236 while (true){ 237 function_call_t message = { NULL, NULL }; 238 BaseType_t res = xQueueReceive( btstack_run_loop_queue, &message, 0); 239 if (res == pdFALSE) break; 240 if (message.fn){ 241 message.fn(message.arg); 242 } 243 } 244 245 // process timers and get next timeout 246 uint32_t timeout_ms = portMAX_DELAY; 247 log_debug("RL: portMAX_DELAY %u", portMAX_DELAY); 248 while (timers) { 249 btstack_timer_source_t * ts = (btstack_timer_source_t *) timers; 250 uint32_t now = btstack_run_loop_freertos_get_time_ms(); 251 int32_t delta_ms = btstack_time_delta(ts->timeout, now); 252 log_debug("RL: now %u, expires %u -> delta %d", now, ts->timeout, delta_ms); 253 if (delta_ms > 0){ 254 timeout_ms = delta_ms; 255 break; 256 } 257 // remove timer before processing it to allow handler to re-register with run loop 258 btstack_run_loop_freertos_remove_timer(ts); 259 log_debug("RL: first timer %p", ts->process); 260 ts->process(ts); 261 } 262 263 // exit triggered by btstack_run_loop_freertos_trigger_exit (from data source, timer, run on main thread) 264 if (run_loop_exit_requested) break; 265 266 // wait for timeout or event group/task notification 267 log_debug("RL: wait with timeout %u", (int) timeout_ms); 268 #ifdef HAVE_FREERTOS_TASK_NOTIFICATIONS 269 xTaskNotifyWait(pdFALSE, 0xffffffff, NULL, pdMS_TO_TICKS(timeout_ms)); 270 #else 271 xEventGroupWaitBits(btstack_run_loop_event_group, EVENT_GROUP_FLAG_RUN_LOOP, 1, 0, pdMS_TO_TICKS(timeout_ms)); 272 #endif 273 } 274 } 275 276 static void btstack_run_loop_freertos_add_data_source(btstack_data_source_t *ds){ 277 btstack_linked_list_add(&data_sources, (btstack_linked_item_t *) ds); 278 } 279 280 static bool btstack_run_loop_freertos_remove_data_source(btstack_data_source_t *ds){ 281 return btstack_linked_list_remove(&data_sources, (btstack_linked_item_t *) ds); 282 } 283 284 static void btstack_run_loop_freertos_enable_data_source_callbacks(btstack_data_source_t * ds, uint16_t callback_types){ 285 ds->flags |= callback_types; 286 } 287 288 static void btstack_run_loop_freertos_disable_data_source_callbacks(btstack_data_source_t * ds, uint16_t callback_types){ 289 ds->flags &= ~callback_types; 290 } 291 292 static void btstack_run_loop_freertos_init(void){ 293 timers = NULL; 294 295 #ifdef USE_STATIC_ALLOC 296 btstack_run_loop_queue = xQueueCreateStatic(RUN_LOOP_QUEUE_LENGTH, RUN_LOOP_QUEUE_ITEM_SIZE, btstack_run_loop_queue_storage, &btstack_run_loop_queue_object); 297 #else 298 btstack_run_loop_queue = xQueueCreate(RUN_LOOP_QUEUE_LENGTH, RUN_LOOP_QUEUE_ITEM_SIZE); 299 #endif 300 301 #ifndef HAVE_FREERTOS_TASK_NOTIFICATIONS 302 // event group to wake run loop 303 btstack_run_loop_event_group = xEventGroupCreate(); 304 #endif 305 306 // task to handle to optimize 'run on main thread' 307 btstack_run_loop_task = xTaskGetCurrentTaskHandle(); 308 309 log_info("run loop init, task %p, queue item size %u", btstack_run_loop_task, (int) sizeof(function_call_t)); 310 } 311 312 /** 313 * @brief Provide btstack_run_loop_posix instance for use with btstack_run_loop_init 314 */ 315 316 static const btstack_run_loop_t btstack_run_loop_freertos = { 317 &btstack_run_loop_freertos_init, 318 &btstack_run_loop_freertos_add_data_source, 319 &btstack_run_loop_freertos_remove_data_source, 320 &btstack_run_loop_freertos_enable_data_source_callbacks, 321 &btstack_run_loop_freertos_disable_data_source_callbacks, 322 &btstack_run_loop_freertos_set_timer, 323 &btstack_run_loop_freertos_add_timer, 324 &btstack_run_loop_freertos_remove_timer, 325 &btstack_run_loop_freertos_execute, 326 &btstack_run_loop_freertos_dump_timer, 327 &btstack_run_loop_freertos_get_time_ms, 328 }; 329 330 const btstack_run_loop_t * btstack_run_loop_freertos_get_instance(void){ 331 return &btstack_run_loop_freertos; 332 } 333