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