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 while (btstack_run_loop_posix_exit_requested == false) { 176 // collect FDs 177 FD_ZERO(&descriptors_read); 178 FD_ZERO(&descriptors_write); 179 int highest_fd = -1; 180 btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources); 181 while (btstack_linked_list_iterator_has_next(&it)){ 182 btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it); 183 if (ds->source.fd < 0) continue; 184 if (ds->flags & DATA_SOURCE_CALLBACK_READ){ 185 FD_SET(ds->source.fd, &descriptors_read); 186 if (ds->source.fd > highest_fd) { 187 highest_fd = ds->source.fd; 188 } 189 log_debug("btstack_run_loop_execute adding fd %u for read", ds->source.fd); 190 } 191 if (ds->flags & DATA_SOURCE_CALLBACK_WRITE){ 192 FD_SET(ds->source.fd, &descriptors_write); 193 if (ds->source.fd > highest_fd) { 194 highest_fd = ds->source.fd; 195 } 196 log_debug("btstack_run_loop_execute adding fd %u for write", ds->source.fd); 197 } 198 } 199 200 // get next timeout 201 timeout = NULL; 202 now_ms = btstack_run_loop_posix_get_time_ms(); 203 int32_t delta_ms = btstack_run_loop_base_get_time_until_timeout(now_ms); 204 if (delta_ms >= 0) { 205 timeout = &tv; 206 tv.tv_sec = delta_ms / 1000; 207 tv.tv_usec = (int) (delta_ms - (tv.tv_sec * 1000)) * 1000; 208 log_debug("btstack_run_loop_execute next timeout in %u ms", delta_ms); 209 } 210 211 // wait for ready FDs 212 int res = select( highest_fd+1 , &descriptors_read, &descriptors_write, NULL, timeout); 213 if (res < 0){ 214 log_error("btstack_run_loop_posix_execute: select -> errno %u", errno); 215 } 216 if (res > 0){ 217 btstack_run_loop_posix_data_sources_modified = 0; 218 btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources); 219 while (btstack_linked_list_iterator_has_next(&it) && !btstack_run_loop_posix_data_sources_modified){ 220 btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it); 221 log_debug("btstack_run_loop_posix_execute: check ds %p with fd %u\n", ds, ds->source.fd); 222 if (FD_ISSET(ds->source.fd, &descriptors_read)) { 223 log_debug("btstack_run_loop_posix_execute: process read ds %p with fd %u\n", ds, ds->source.fd); 224 ds->process(ds, DATA_SOURCE_CALLBACK_READ); 225 } 226 if (btstack_run_loop_posix_data_sources_modified) break; 227 if (FD_ISSET(ds->source.fd, &descriptors_write)) { 228 log_debug("btstack_run_loop_posix_execute: process write ds %p with fd %u\n", ds, ds->source.fd); 229 ds->process(ds, DATA_SOURCE_CALLBACK_WRITE); 230 } 231 } 232 } 233 log_debug("btstack_run_loop_posix_execute: after ds check\n"); 234 235 // process timers 236 now_ms = btstack_run_loop_posix_get_time_ms(); 237 btstack_run_loop_base_process_timers(now_ms); 238 } 239 } 240 241 static void btstack_run_loop_posix_trigger_exit(void){ 242 btstack_run_loop_posix_exit_requested = true; 243 } 244 245 // set timer 246 static void btstack_run_loop_posix_set_timer(btstack_timer_source_t *a, uint32_t timeout_in_ms){ 247 uint32_t time_ms = btstack_run_loop_posix_get_time_ms(); 248 a->timeout = time_ms + timeout_in_ms; 249 log_debug("btstack_run_loop_posix_set_timer to %u ms (now %u, timeout %u)", a->timeout, time_ms, timeout_in_ms); 250 } 251 252 // trigger pipe 253 static void btstack_run_loop_posix_trigger_pipe(int fd){ 254 if (fd < 0) return; 255 const uint8_t x = (uint8_t) 'x'; 256 ssize_t bytes_written = write(fd, &x, 1); 257 UNUSED(bytes_written); 258 } 259 260 // poll data sources from irq 261 262 static void btstack_run_loop_posix_poll_data_sources_handler(btstack_data_source_t * ds, btstack_data_source_callback_type_t callback_type){ 263 UNUSED(callback_type); 264 uint8_t buffer[1]; 265 ssize_t bytes_read = read(ds->source.fd, buffer, 1); 266 UNUSED(bytes_read); 267 // poll data sources 268 btstack_run_loop_base_poll_data_sources(); 269 } 270 271 static void btstack_run_loop_posix_poll_data_sources_from_irq(void){ 272 // trigger run loop 273 btstack_run_loop_posix_trigger_pipe(btstack_run_loop_posix_poll_data_sources_fd); 274 } 275 276 // execute on main thread from same or different thread 277 278 static void btstack_run_loop_posix_process_callbacks_handler(btstack_data_source_t * ds, btstack_data_source_callback_type_t callback_type){ 279 UNUSED(callback_type); 280 uint8_t buffer[1]; 281 ssize_t bytes_read = read(ds->source.fd, buffer, 1); 282 UNUSED(bytes_read); 283 // execute callbacks - protect list with mutex 284 while (1){ 285 pthread_mutex_lock(&btstack_run_loop_posix_callbacks_mutex); 286 btstack_context_callback_registration_t * callback_registration = (btstack_context_callback_registration_t *) btstack_linked_list_pop(&btstack_run_loop_base_callbacks); 287 pthread_mutex_unlock(&btstack_run_loop_posix_callbacks_mutex); 288 if (callback_registration == NULL){ 289 break; 290 } 291 (*callback_registration->callback)(callback_registration->context); 292 } 293 } 294 295 static void btstack_run_loop_posix_execute_on_main_thread(btstack_context_callback_registration_t * callback_registration){ 296 // protect list with mutex 297 pthread_mutex_lock(&btstack_run_loop_posix_callbacks_mutex); 298 btstack_run_loop_base_add_callback(callback_registration); 299 pthread_mutex_unlock(&btstack_run_loop_posix_callbacks_mutex); 300 // trigger run loop 301 btstack_run_loop_posix_trigger_pipe(btstack_run_loop_posix_process_callbacks_fd); 302 } 303 304 //init 305 306 // @return fd >= 0 on success 307 static int btstack_run_loop_posix_register_pipe_datasource(btstack_data_source_t * data_source){ 308 int fildes[2]; // 0 = read, 1 = write 309 int status = pipe(fildes); 310 if (status != 0){ 311 log_error("pipe() failed"); 312 return -1; 313 } 314 data_source->source.fd = fildes[0]; 315 data_source->flags = DATA_SOURCE_CALLBACK_READ; 316 btstack_run_loop_base_add_data_source(data_source); 317 log_info("Pipe: in %u, out %u", fildes[1], fildes[0]); 318 return fildes[1]; 319 } 320 321 static void btstack_run_loop_posix_init(void){ 322 btstack_run_loop_base_init(); 323 324 #ifdef _POSIX_MONOTONIC_CLOCK 325 clock_gettime(CLOCK_MONOTONIC, &init_ts); 326 init_ts.tv_nsec = 0; 327 #else 328 // just assume that we started at tv_usec == 0 329 gettimeofday(&init_tv, NULL); 330 init_tv.tv_usec = 0; 331 #endif 332 333 // setup pipe to trigger process callbacks 334 btstack_run_loop_posix_process_callbacks_ds.process = &btstack_run_loop_posix_process_callbacks_handler; 335 btstack_run_loop_posix_process_callbacks_fd = btstack_run_loop_posix_register_pipe_datasource(&btstack_run_loop_posix_process_callbacks_ds); 336 337 // setup pipe to poll data sources 338 btstack_run_loop_posix_poll_data_sources_ds.process = &btstack_run_loop_posix_poll_data_sources_handler; 339 btstack_run_loop_posix_poll_data_sources_fd = btstack_run_loop_posix_register_pipe_datasource(&btstack_run_loop_posix_poll_data_sources_ds); 340 } 341 342 static const btstack_run_loop_t btstack_run_loop_posix = { 343 &btstack_run_loop_posix_init, 344 &btstack_run_loop_posix_add_data_source, 345 &btstack_run_loop_posix_remove_data_source, 346 &btstack_run_loop_base_enable_data_source_callbacks, 347 &btstack_run_loop_base_disable_data_source_callbacks, 348 &btstack_run_loop_posix_set_timer, 349 &btstack_run_loop_base_add_timer, 350 &btstack_run_loop_base_remove_timer, 351 &btstack_run_loop_posix_execute, 352 &btstack_run_loop_base_dump_timer, 353 &btstack_run_loop_posix_get_time_ms, 354 &btstack_run_loop_posix_poll_data_sources_from_irq, 355 &btstack_run_loop_posix_execute_on_main_thread, 356 &btstack_run_loop_posix_trigger_exit, 357 }; 358 359 /** 360 * Provide btstack_run_loop_posix instance 361 */ 362 const btstack_run_loop_t * btstack_run_loop_posix_get_instance(void){ 363 return &btstack_run_loop_posix; 364 } 365 366