1 /* 2 * Copyright (C) 2014 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 #define BTSTACK_FILE__ "btstack_run_loop_posix.c" 39 40 /* 41 * btstack_run_loop.c 42 * 43 * Created by Matthias Ringwald on 6/6/09. 44 */ 45 46 // enable POSIX functions (needed for -std=c99) 47 #define _POSIX_C_SOURCE 200809 48 49 #include "btstack_run_loop_posix.h" 50 51 #include "btstack_run_loop.h" 52 #include "btstack_util.h" 53 #include "btstack_linked_list.h" 54 #include "btstack_debug.h" 55 56 #include <stdio.h> 57 #include <stdlib.h> 58 #include <sys/errno.h> 59 #include <sys/select.h> 60 #include <sys/time.h> 61 #include <time.h> 62 #include <unistd.h> 63 #include <pthread.h> 64 65 // the run loop 66 static int btstack_run_loop_posix_data_sources_modified; 67 68 static bool btstack_run_loop_posix_exit_requested; 69 70 // to trigger process callbacks other thread 71 static pthread_mutex_t btstack_run_loop_posix_callbacks_mutex = PTHREAD_MUTEX_INITIALIZER; 72 static int btstack_run_loop_posix_process_callbacks_fd; 73 static btstack_data_source_t btstack_run_loop_posix_process_callbacks_ds; 74 75 // to trigger poll data sources from irq 76 static int btstack_run_loop_posix_poll_data_sources_fd; 77 static btstack_data_source_t btstack_run_loop_posix_poll_data_sources_ds; 78 79 // start time. tv_usec/tv_nsec = 0 80 #ifdef _POSIX_MONOTONIC_CLOCK 81 // use monotonic clock if available 82 static struct timespec init_ts; 83 #else 84 // fallback to gettimeofday 85 static struct timeval init_tv; 86 #endif 87 88 /** 89 * Add data_source to run_loop 90 */ 91 static void btstack_run_loop_posix_add_data_source(btstack_data_source_t *ds){ 92 btstack_run_loop_posix_data_sources_modified = 1; 93 btstack_run_loop_base_add_data_source(ds); 94 } 95 96 /** 97 * Remove data_source from run loop 98 */ 99 static bool btstack_run_loop_posix_remove_data_source(btstack_data_source_t *ds){ 100 btstack_run_loop_posix_data_sources_modified = 1; 101 return btstack_run_loop_base_remove_data_source(ds); 102 } 103 104 #ifdef _POSIX_MONOTONIC_CLOCK 105 /** 106 * @brief Returns the timespec which represents the time(stop - start). It might be negative 107 */ 108 static void timespec_diff(struct timespec *start, struct timespec *stop, struct timespec *result){ 109 result->tv_sec = stop->tv_sec - start->tv_sec; 110 if ((stop->tv_nsec - start->tv_nsec) < 0) { 111 result->tv_sec = stop->tv_sec - start->tv_sec - 1; 112 result->tv_nsec = stop->tv_nsec - start->tv_nsec + 1000000000; 113 } else { 114 result->tv_sec = stop->tv_sec - start->tv_sec; 115 result->tv_nsec = stop->tv_nsec - start->tv_nsec; 116 } 117 } 118 119 /** 120 * @brief Convert timespec to miliseconds, might overflow 121 */ 122 static uint64_t timespec_to_milliseconds(struct timespec *a){ 123 uint64_t ret = 0; 124 uint64_t sec_val = (uint64_t)(a->tv_sec); 125 uint64_t nsec_val = (uint64_t)(a->tv_nsec); 126 ret = (sec_val*1000) + (nsec_val/1000000); 127 return ret; 128 } 129 130 /** 131 * @brief Returns the milisecond value of (stop - start). Might overflow 132 */ 133 static uint64_t timespec_diff_milis(struct timespec* start, struct timespec* stop){ 134 struct timespec diff_ts; 135 timespec_diff(start, stop, &diff_ts); 136 return timespec_to_milliseconds(&diff_ts); 137 } 138 #endif 139 140 /** 141 * @brief Queries the current time in ms since start 142 */ 143 static uint32_t btstack_run_loop_posix_get_time_ms(void){ 144 uint32_t time_ms; 145 #ifdef _POSIX_MONOTONIC_CLOCK 146 struct timespec now_ts; 147 clock_gettime(CLOCK_MONOTONIC, &now_ts); 148 time_ms = (uint32_t) timespec_diff_milis(&init_ts, &now_ts); 149 #else 150 struct timeval tv; 151 gettimeofday(&tv, NULL); 152 time_ms = (uint32_t) ((tv.tv_sec - init_tv.tv_sec) * 1000) + (tv.tv_usec / 1000); 153 #endif 154 return time_ms; 155 } 156 157 /** 158 * Execute run_loop 159 */ 160 static void btstack_run_loop_posix_execute(void) { 161 fd_set descriptors_read; 162 fd_set descriptors_write; 163 164 btstack_linked_list_iterator_t it; 165 struct timeval * timeout; 166 struct timeval tv; 167 uint32_t now_ms; 168 169 #ifdef _POSIX_MONOTONIC_CLOCK 170 log_info("POSIX run loop with monotonic clock"); 171 #else 172 log_info("POSIX run loop using ettimeofday fallback."); 173 #endif 174 175 // clear exit flag 176 btstack_run_loop_posix_exit_requested = false; 177 178 while (btstack_run_loop_posix_exit_requested == false) { 179 // collect FDs 180 FD_ZERO(&descriptors_read); 181 FD_ZERO(&descriptors_write); 182 int highest_fd = -1; 183 btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources); 184 while (btstack_linked_list_iterator_has_next(&it)){ 185 btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it); 186 if (ds->source.fd < 0) continue; 187 if (ds->flags & DATA_SOURCE_CALLBACK_READ){ 188 FD_SET(ds->source.fd, &descriptors_read); 189 if (ds->source.fd > highest_fd) { 190 highest_fd = ds->source.fd; 191 } 192 log_debug("btstack_run_loop_execute adding fd %u for read", ds->source.fd); 193 } 194 if (ds->flags & DATA_SOURCE_CALLBACK_WRITE){ 195 FD_SET(ds->source.fd, &descriptors_write); 196 if (ds->source.fd > highest_fd) { 197 highest_fd = ds->source.fd; 198 } 199 log_debug("btstack_run_loop_execute adding fd %u for write", ds->source.fd); 200 } 201 } 202 203 // get next timeout 204 timeout = NULL; 205 now_ms = btstack_run_loop_posix_get_time_ms(); 206 int32_t delta_ms = btstack_run_loop_base_get_time_until_timeout(now_ms); 207 if (delta_ms >= 0) { 208 timeout = &tv; 209 tv.tv_sec = delta_ms / 1000; 210 tv.tv_usec = (int) (delta_ms - (tv.tv_sec * 1000)) * 1000; 211 log_debug("btstack_run_loop_execute next timeout in %u ms", delta_ms); 212 } 213 214 // wait for ready FDs 215 int res = select( highest_fd+1 , &descriptors_read, &descriptors_write, NULL, timeout); 216 if (res < 0){ 217 log_error("btstack_run_loop_posix_execute: select -> errno %u", errno); 218 } 219 if (res > 0){ 220 btstack_run_loop_posix_data_sources_modified = 0; 221 btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources); 222 while (btstack_linked_list_iterator_has_next(&it) && !btstack_run_loop_posix_data_sources_modified){ 223 btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it); 224 log_debug("btstack_run_loop_posix_execute: check ds %p with fd %u\n", ds, ds->source.fd); 225 if (FD_ISSET(ds->source.fd, &descriptors_read)) { 226 log_debug("btstack_run_loop_posix_execute: process read ds %p with fd %u\n", ds, ds->source.fd); 227 ds->process(ds, DATA_SOURCE_CALLBACK_READ); 228 } 229 if (btstack_run_loop_posix_data_sources_modified) break; 230 if (FD_ISSET(ds->source.fd, &descriptors_write)) { 231 log_debug("btstack_run_loop_posix_execute: process write ds %p with fd %u\n", ds, ds->source.fd); 232 ds->process(ds, DATA_SOURCE_CALLBACK_WRITE); 233 } 234 } 235 } 236 log_debug("btstack_run_loop_posix_execute: after ds check\n"); 237 238 // process timers 239 now_ms = btstack_run_loop_posix_get_time_ms(); 240 btstack_run_loop_base_process_timers(now_ms); 241 } 242 } 243 244 static void btstack_run_loop_posix_trigger_exit(void){ 245 btstack_run_loop_posix_exit_requested = true; 246 } 247 248 // set timer 249 static void btstack_run_loop_posix_set_timer(btstack_timer_source_t *a, uint32_t timeout_in_ms){ 250 uint32_t time_ms = btstack_run_loop_posix_get_time_ms(); 251 a->timeout = time_ms + timeout_in_ms; 252 log_debug("btstack_run_loop_posix_set_timer to %u ms (now %u, timeout %u)", a->timeout, time_ms, timeout_in_ms); 253 } 254 255 // trigger pipe 256 static void btstack_run_loop_posix_trigger_pipe(int fd){ 257 if (fd < 0) return; 258 const uint8_t x = (uint8_t) 'x'; 259 ssize_t bytes_written = write(fd, &x, 1); 260 UNUSED(bytes_written); 261 } 262 263 // poll data sources from irq 264 265 static void btstack_run_loop_posix_poll_data_sources_handler(btstack_data_source_t * ds, btstack_data_source_callback_type_t callback_type){ 266 UNUSED(callback_type); 267 uint8_t buffer[1]; 268 ssize_t bytes_read = read(ds->source.fd, buffer, 1); 269 UNUSED(bytes_read); 270 // poll data sources 271 btstack_run_loop_base_poll_data_sources(); 272 } 273 274 static void btstack_run_loop_posix_poll_data_sources_from_irq(void){ 275 // trigger run loop 276 btstack_run_loop_posix_trigger_pipe(btstack_run_loop_posix_poll_data_sources_fd); 277 } 278 279 // execute on main thread from same or different thread 280 281 static void btstack_run_loop_posix_process_callbacks_handler(btstack_data_source_t * ds, btstack_data_source_callback_type_t callback_type){ 282 UNUSED(callback_type); 283 uint8_t buffer[1]; 284 ssize_t bytes_read = read(ds->source.fd, buffer, 1); 285 UNUSED(bytes_read); 286 // execute callbacks - protect list with mutex 287 while (1){ 288 pthread_mutex_lock(&btstack_run_loop_posix_callbacks_mutex); 289 btstack_context_callback_registration_t * callback_registration = (btstack_context_callback_registration_t *) btstack_linked_list_pop(&btstack_run_loop_base_callbacks); 290 pthread_mutex_unlock(&btstack_run_loop_posix_callbacks_mutex); 291 if (callback_registration == NULL){ 292 break; 293 } 294 (*callback_registration->callback)(callback_registration->context); 295 } 296 } 297 298 static void btstack_run_loop_posix_execute_on_main_thread(btstack_context_callback_registration_t * callback_registration){ 299 // protect list with mutex 300 pthread_mutex_lock(&btstack_run_loop_posix_callbacks_mutex); 301 btstack_run_loop_base_add_callback(callback_registration); 302 pthread_mutex_unlock(&btstack_run_loop_posix_callbacks_mutex); 303 // trigger run loop 304 btstack_run_loop_posix_trigger_pipe(btstack_run_loop_posix_process_callbacks_fd); 305 } 306 307 //init 308 309 // @return fd >= 0 on success 310 static int btstack_run_loop_posix_register_pipe_datasource(btstack_data_source_t * data_source){ 311 int fildes[2]; // 0 = read, 1 = write 312 int status = pipe(fildes); 313 if (status != 0){ 314 log_error("pipe() failed"); 315 return -1; 316 } 317 data_source->source.fd = fildes[0]; 318 data_source->flags = DATA_SOURCE_CALLBACK_READ; 319 btstack_run_loop_base_add_data_source(data_source); 320 log_info("Pipe: in %u, out %u", fildes[1], fildes[0]); 321 return fildes[1]; 322 } 323 324 static void btstack_run_loop_posix_init(void){ 325 btstack_run_loop_base_init(); 326 327 #ifdef _POSIX_MONOTONIC_CLOCK 328 clock_gettime(CLOCK_MONOTONIC, &init_ts); 329 init_ts.tv_nsec = 0; 330 #else 331 // just assume that we started at tv_usec == 0 332 gettimeofday(&init_tv, NULL); 333 init_tv.tv_usec = 0; 334 #endif 335 336 // setup pipe to trigger process callbacks 337 btstack_run_loop_posix_process_callbacks_ds.process = &btstack_run_loop_posix_process_callbacks_handler; 338 btstack_run_loop_posix_process_callbacks_fd = btstack_run_loop_posix_register_pipe_datasource(&btstack_run_loop_posix_process_callbacks_ds); 339 340 // setup pipe to poll data sources 341 btstack_run_loop_posix_poll_data_sources_ds.process = &btstack_run_loop_posix_poll_data_sources_handler; 342 btstack_run_loop_posix_poll_data_sources_fd = btstack_run_loop_posix_register_pipe_datasource(&btstack_run_loop_posix_poll_data_sources_ds); 343 } 344 345 static const btstack_run_loop_t btstack_run_loop_posix = { 346 &btstack_run_loop_posix_init, 347 &btstack_run_loop_posix_add_data_source, 348 &btstack_run_loop_posix_remove_data_source, 349 &btstack_run_loop_base_enable_data_source_callbacks, 350 &btstack_run_loop_base_disable_data_source_callbacks, 351 &btstack_run_loop_posix_set_timer, 352 &btstack_run_loop_base_add_timer, 353 &btstack_run_loop_base_remove_timer, 354 &btstack_run_loop_posix_execute, 355 &btstack_run_loop_base_dump_timer, 356 &btstack_run_loop_posix_get_time_ms, 357 &btstack_run_loop_posix_poll_data_sources_from_irq, 358 &btstack_run_loop_posix_execute_on_main_thread, 359 &btstack_run_loop_posix_trigger_exit, 360 }; 361 362 /** 363 * Provide btstack_run_loop_posix instance 364 */ 365 const btstack_run_loop_t * btstack_run_loop_posix_get_instance(void){ 366 return &btstack_run_loop_posix; 367 } 368 369