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