xref: /btstack/platform/posix/btstack_run_loop_posix.c (revision 50b47281dcd786f25b8e20527b26e5aaa0460809)
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 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 #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_run_loop_base.h"
53 #include "btstack_util.h"
54 #include "btstack_linked_list.h"
55 #include "btstack_debug.h"
56 
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <sys/select.h>
60 #include <sys/time.h>
61 #include <time.h>
62 #include <unistd.h>
63 
64 // the run loop
65 static int data_sources_modified;
66 
67 // start time. tv_usec/tv_nsec = 0
68 #ifdef _POSIX_MONOTONIC_CLOCK
69 // use monotonic clock if available
70 static struct timespec init_ts;
71 #else
72 // fallback to gettimeofday
73 static struct timeval init_tv;
74 #endif
75 
76 /**
77  * Add data_source to run_loop
78  */
79 static void btstack_run_loop_posix_add_data_source(btstack_data_source_t *ds){
80     data_sources_modified = 1;
81     btstack_run_loop_base_add_data_source(ds);
82 }
83 
84 /**
85  * Remove data_source from run loop
86  */
87 static bool btstack_run_loop_posix_remove_data_source(btstack_data_source_t *ds){
88     data_sources_modified = 1;
89     return btstack_run_loop_base_remove_data_source(ds);
90 }
91 
92 #ifdef _POSIX_MONOTONIC_CLOCK
93 /**
94  * @brief Returns the timespec which represents the time(stop - start). It might be negative
95  */
96 static void timespec_diff(struct timespec *start, struct timespec *stop, struct timespec *result){
97     result->tv_sec = stop->tv_sec - start->tv_sec;
98     if ((stop->tv_nsec - start->tv_nsec) < 0) {
99         result->tv_sec = stop->tv_sec - start->tv_sec - 1;
100         result->tv_nsec = stop->tv_nsec - start->tv_nsec + 1000000000;
101     } else {
102         result->tv_sec = stop->tv_sec - start->tv_sec;
103         result->tv_nsec = stop->tv_nsec - start->tv_nsec;
104     }
105 }
106 
107 /**
108  * @brief Convert timespec to miliseconds, might overflow
109  */
110 static uint64_t timespec_to_milliseconds(struct timespec *a){
111     uint64_t ret = 0;
112     uint64_t sec_val = (uint64_t)(a->tv_sec);
113     uint64_t nsec_val = (uint64_t)(a->tv_nsec);
114     ret = (sec_val*1000) + (nsec_val/1000000);
115     return ret;
116 }
117 
118 /**
119  * @brief Returns the milisecond value of (stop - start). Might overflow
120  */
121 static uint64_t timespec_diff_milis(struct timespec* start, struct timespec* stop){
122     struct timespec diff_ts;
123     timespec_diff(start, stop, &diff_ts);
124     return timespec_to_milliseconds(&diff_ts);
125 }
126 #endif
127 
128 /**
129  * @brief Queries the current time in ms since start
130  */
131 static uint32_t btstack_run_loop_posix_get_time_ms(void){
132     uint32_t time_ms;
133 #ifdef _POSIX_MONOTONIC_CLOCK
134     struct timespec now_ts;
135     clock_gettime(CLOCK_MONOTONIC, &now_ts);
136     time_ms = (uint32_t) timespec_diff_milis(&init_ts, &now_ts);
137 #else
138     struct timeval tv;
139     gettimeofday(&tv, NULL);
140     time_ms = (uint32_t) ((tv.tv_sec  - init_tv.tv_sec) * 1000) + (tv.tv_usec / 1000);
141 #endif
142     return time_ms;
143 }
144 
145 /**
146  * Execute run_loop
147  */
148 static void btstack_run_loop_posix_execute(void) {
149     fd_set descriptors_read;
150     fd_set descriptors_write;
151 
152     btstack_linked_list_iterator_t it;
153     struct timeval * timeout;
154     struct timeval tv;
155     uint32_t now_ms;
156 
157 #ifdef _POSIX_MONOTONIC_CLOCK
158     log_info("POSIX run loop with monotonic clock");
159 #else
160     log_info("POSIX run loop using ettimeofday fallback.");
161 #endif
162 
163     while (true) {
164         // collect FDs
165         FD_ZERO(&descriptors_read);
166         FD_ZERO(&descriptors_write);
167         int highest_fd = -1;
168         btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources);
169         while (btstack_linked_list_iterator_has_next(&it)){
170             btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it);
171             if (ds->source.fd < 0) continue;
172             if (ds->flags & DATA_SOURCE_CALLBACK_READ){
173                 FD_SET(ds->source.fd, &descriptors_read);
174                 if (ds->source.fd > highest_fd) {
175                     highest_fd = ds->source.fd;
176                 }
177                 log_debug("btstack_run_loop_execute adding fd %u for read", ds->source.fd);
178             }
179             if (ds->flags & DATA_SOURCE_CALLBACK_WRITE){
180                 FD_SET(ds->source.fd, &descriptors_write);
181                 if (ds->source.fd > highest_fd) {
182                     highest_fd = ds->source.fd;
183                 }
184                 log_debug("btstack_run_loop_execute adding fd %u for write", ds->source.fd);
185             }
186         }
187 
188         // get next timeout
189         timeout = NULL;
190         now_ms = btstack_run_loop_posix_get_time_ms();
191         int32_t delta_ms = btstack_run_loop_base_get_time_until_timeout(now_ms);
192         if (delta_ms >= 0) {
193             timeout = &tv;
194             tv.tv_sec  = delta_ms / 1000;
195             tv.tv_usec = (int) (delta_ms - (tv.tv_sec * 1000)) * 1000;
196             log_debug("btstack_run_loop_execute next timeout in %u ms", delta_ms);
197         }
198 
199         // wait for ready FDs
200         select( highest_fd+1 , &descriptors_read, &descriptors_write, NULL, timeout);
201 
202 
203         data_sources_modified = 0;
204         btstack_linked_list_iterator_init(&it, &btstack_run_loop_base_data_sources);
205         while (btstack_linked_list_iterator_has_next(&it) && !data_sources_modified){
206             btstack_data_source_t *ds = (btstack_data_source_t*) btstack_linked_list_iterator_next(&it);
207             log_debug("btstack_run_loop_posix_execute: check ds %p with fd %u\n", ds, ds->source.fd);
208             if (FD_ISSET(ds->source.fd, &descriptors_read)) {
209                 log_debug("btstack_run_loop_posix_execute: process read ds %p with fd %u\n", ds, ds->source.fd);
210                 ds->process(ds, DATA_SOURCE_CALLBACK_READ);
211             }
212             if (data_sources_modified) break;
213             if (FD_ISSET(ds->source.fd, &descriptors_write)) {
214                 log_debug("btstack_run_loop_posix_execute: process write ds %p with fd %u\n", ds, ds->source.fd);
215                 ds->process(ds, DATA_SOURCE_CALLBACK_WRITE);
216             }
217         }
218         log_debug("btstack_run_loop_posix_execute: after ds check\n");
219 
220         // process timers
221         now_ms = btstack_run_loop_posix_get_time_ms();
222         btstack_run_loop_base_process_timers(now_ms);
223     }
224 }
225 
226 // set timer
227 static void btstack_run_loop_posix_set_timer(btstack_timer_source_t *a, uint32_t timeout_in_ms){
228     uint32_t time_ms = btstack_run_loop_posix_get_time_ms();
229     a->timeout = time_ms + timeout_in_ms;
230     log_debug("btstack_run_loop_posix_set_timer to %u ms (now %u, timeout %u)", a->timeout, time_ms, timeout_in_ms);
231 }
232 
233 static void btstack_run_loop_posix_init(void){
234     btstack_run_loop_base_init();
235 
236 #ifdef _POSIX_MONOTONIC_CLOCK
237     clock_gettime(CLOCK_MONOTONIC, &init_ts);
238     init_ts.tv_nsec = 0;
239 #else
240     // just assume that we started at tv_usec == 0
241     gettimeofday(&init_tv, NULL);
242     init_tv.tv_usec = 0;
243 #endif
244 }
245 
246 
247 static const btstack_run_loop_t btstack_run_loop_posix = {
248     &btstack_run_loop_posix_init,
249     &btstack_run_loop_posix_add_data_source,
250     &btstack_run_loop_posix_remove_data_source,
251     &btstack_run_loop_base_enable_data_source_callbacks,
252     &btstack_run_loop_base_disable_data_source_callbacks,
253     &btstack_run_loop_posix_set_timer,
254     &btstack_run_loop_base_add_timer,
255     &btstack_run_loop_base_remove_timer,
256     &btstack_run_loop_posix_execute,
257     &btstack_run_loop_base_dump_timer,
258     &btstack_run_loop_posix_get_time_ms,
259 };
260 
261 /**
262  * Provide btstack_run_loop_posix instance
263  */
264 const btstack_run_loop_t * btstack_run_loop_posix_get_instance(void){
265     return &btstack_run_loop_posix;
266 }
267 
268