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