Merge "rtp_engine/res_rtp_asterisk: Fix RTP struct reentrancy crashes."
[asterisk/asterisk.git] / res / res_timing_kqueue.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2010, Digium, Inc.
5  *
6  * Tilghman Lesher <tlesher AT digium DOT com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  * \author Tilghman Lesher \verbatim <tlesher AT digium DOT com> \endverbatim
22  *
23  * \brief kqueue timing interface
24  *
25  * \ingroup resource
26  */
27
28 /*** MODULEINFO
29         <depend>kqueue</depend>
30         <conflict>launchd</conflict>
31         <support_level>extended</support_level>
32  ***/
33
34 #include "asterisk.h"
35
36 #include <sys/types.h>
37 #include <sys/event.h>
38 #include <sys/time.h>
39
40 #include "asterisk/module.h"
41 #include "asterisk/astobj2.h"
42 #include "asterisk/timing.h"
43 #include "asterisk/logger.h"
44 #include "asterisk/utils.h"
45 #include "asterisk/time.h"
46 #include "asterisk/test.h"
47 #include "asterisk/poll-compat.h"       /* for ast_poll() */
48
49 static void *timing_funcs_handle;
50
51 static void *kqueue_timer_open(void);
52 static void kqueue_timer_close(void *data);
53 static int kqueue_timer_set_rate(void *data, unsigned int rate);
54 static int kqueue_timer_ack(void *data, unsigned int quantity);
55 static int kqueue_timer_enable_continuous(void *data);
56 static int kqueue_timer_disable_continuous(void *data);
57 static enum ast_timer_event kqueue_timer_get_event(void *data);
58 static unsigned int kqueue_timer_get_max_rate(void *data);
59 static int kqueue_timer_fd(void *data);
60
61 static struct ast_timing_interface kqueue_timing = {
62         .name = "kqueue",
63         .priority = 150,
64         .timer_open = kqueue_timer_open,
65         .timer_close = kqueue_timer_close,
66         .timer_set_rate = kqueue_timer_set_rate,
67         .timer_ack = kqueue_timer_ack,
68         .timer_enable_continuous = kqueue_timer_enable_continuous,
69         .timer_disable_continuous = kqueue_timer_disable_continuous,
70         .timer_get_event = kqueue_timer_get_event,
71         .timer_get_max_rate = kqueue_timer_get_max_rate,
72         .timer_fd = kqueue_timer_fd,
73 };
74
75 struct kqueue_timer {
76         intptr_t period;
77         int handle;
78 #ifndef EVFILT_USER
79         int continuous_fd;
80         unsigned int continuous_fd_valid:1;
81 #endif
82         unsigned int is_continuous:1;
83 };
84
85 #ifdef EVFILT_USER
86 #define CONTINUOUS_EVFILT_TYPE EVFILT_USER
87 static int kqueue_timer_init_continuous_event(struct kqueue_timer *timer)
88 {
89         return 0;
90 }
91
92 static int kqueue_timer_enable_continuous_event(struct kqueue_timer *timer)
93 {
94         struct kevent kev[2];
95
96         EV_SET(&kev[0], (uintptr_t)timer, EVFILT_USER, EV_ADD | EV_ENABLE,
97                 0, 0, NULL);
98         EV_SET(&kev[1], (uintptr_t)timer, EVFILT_USER, 0, NOTE_TRIGGER,
99                 0, NULL);
100         return kevent(timer->handle, kev, 2, NULL, 0, NULL);
101 }
102
103 static int kqueue_timer_disable_continuous_event(struct kqueue_timer *timer)
104 {
105         struct kevent kev;
106
107         EV_SET(&kev, (uintptr_t)timer, EVFILT_USER, EV_DELETE, 0, 0, NULL);
108         return kevent(timer->handle, &kev, 1, NULL, 0, NULL);
109 }
110
111 static void kqueue_timer_fini_continuous_event(struct kqueue_timer *timer)
112 {
113 }
114
115 #else /* EVFILT_USER */
116
117 #define CONTINUOUS_EVFILT_TYPE EVFILT_READ
118 static int kqueue_timer_init_continuous_event(struct kqueue_timer *timer)
119 {
120         int pipefds[2];
121         int retval;
122
123         retval = pipe(pipefds);
124         if (retval == 0) {
125                 timer->continuous_fd = pipefds[0];
126                 timer->continuous_fd_valid = 1;
127                 close(pipefds[1]);
128         }
129         return retval;
130 }
131
132 static void kqueue_timer_fini_continuous_event(struct kqueue_timer *timer)
133 {
134         if (timer->continuous_fd_valid) {
135                 close(timer->continuous_fd);
136         }
137 }
138
139 static int kqueue_timer_enable_continuous_event(struct kqueue_timer *timer)
140 {
141         struct kevent kev;
142
143         EV_SET(&kev, timer->continuous_fd, EVFILT_READ, EV_ADD | EV_ENABLE,
144                 0, 0, NULL);
145         return kevent(timer->handle, &kev, 1, NULL, 0, NULL);
146 }
147
148 static int kqueue_timer_disable_continuous_event(struct kqueue_timer *timer)
149 {
150         struct kevent kev;
151
152         EV_SET(&kev, timer->continuous_fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
153         return kevent(timer->handle, &kev, 1, NULL, 0, NULL);
154 }
155 #endif
156
157 static void timer_destroy(void *obj)
158 {
159         struct kqueue_timer *timer = obj;
160         ast_debug(5, "[%d]: Timer Destroy\n", timer->handle);
161         kqueue_timer_fini_continuous_event(timer);
162         if (timer->handle > -1) {
163                 close(timer->handle);
164         }
165 }
166
167 static void *kqueue_timer_open(void)
168 {
169         struct kqueue_timer *timer;
170
171         if (!(timer = ao2_alloc(sizeof(*timer), timer_destroy))) {
172                 ast_log(LOG_ERROR, "Alloc failed for kqueue_timer structure\n");
173                 return NULL;
174         }
175
176         if ((timer->handle = kqueue()) < 0) {
177                 ast_log(LOG_ERROR, "Failed to create kqueue fd: %s\n",
178                         strerror(errno));
179                 ao2_ref(timer, -1);
180                 return NULL;
181         }
182
183         if (kqueue_timer_init_continuous_event(timer) != 0) {
184                 ast_log(LOG_ERROR, "Failed to create continuous event: %s\n",
185                         strerror(errno));
186                 ao2_ref(timer, -1);
187                 return NULL;
188         }
189         ast_debug(5, "[%d]: Create timer\n", timer->handle);
190         return timer;
191 }
192
193 static void kqueue_timer_close(void *data)
194 {
195         struct kqueue_timer *timer = data;
196
197         ast_debug(5, "[%d]: Timer Close\n", timer->handle);
198         ao2_ref(timer, -1);
199 }
200
201 /*
202  * Use the highest precision available that does not overflow
203  * the datatype kevent is using for time.
204  */
205 static intptr_t kqueue_scale_period(unsigned int period_ns, int *units)
206 {
207         uint64_t period = period_ns;
208         *units = 0;
209 #ifdef NOTE_NSECONDS
210         if (period < INTPTR_MAX) {
211                 *units = NOTE_NSECONDS;
212         } else {
213 #ifdef NOTE_USECONDS
214                 period /= 1000;
215                 if (period < INTPTR_MAX) {
216                         *units = NOTE_USECONDS;
217                 } else {
218                         period /= 1000;
219 #ifdef NOTE_MSECONDS
220                         *units = NOTE_MSECONDS;
221 #endif  /* NOTE_MSECONDS */
222                 }
223 #else   /* NOTE_USECONDS */
224                 period /= 1000000;
225 #ifdef NOTE_MSECONDS
226                 *units = NOTE_MSECONDS;
227 #endif  /* NOTE_MSECONDS */
228 #endif  /* NOTE_USECONDS */
229         }
230 #else   /* NOTE_NSECONDS */
231         period /= 1000000;
232 #endif
233         if (period > INTPTR_MAX) {
234                 period = INTPTR_MAX;
235         }
236         return period;
237 }
238
239 static int kqueue_timer_set_rate(void *data, unsigned int rate)
240 {
241         struct kevent kev;
242         struct kqueue_timer *timer = data;
243         uint64_t period_ns;
244         int flags;
245         int units;
246         int retval;
247
248         ao2_lock(timer);
249
250         if (rate == 0) {
251                 if (timer->period == 0) {
252                         ao2_unlock(timer);
253                         return (0);
254                 }
255                 flags = EV_DELETE;
256                 timer->period = 0;
257                 units = 0;
258         } else  {
259                 flags = EV_ADD | EV_ENABLE;
260                 period_ns = (uint64_t)1000000000 / rate;
261                 timer->period = kqueue_scale_period(period_ns, &units);
262         }
263         ast_debug(5, "[%d]: Set rate %u:%ju\n",
264                 timer->handle, units, (uintmax_t)timer->period);
265         EV_SET(&kev, timer->handle, EVFILT_TIMER, flags, units,
266                 timer->period, NULL);
267         retval = kevent(timer->handle, &kev, 1, NULL, 0, NULL);
268
269         if (retval == -1) {
270                 ast_log(LOG_ERROR, "[%d]: Error queing timer: %s\n",
271                         timer->handle, strerror(errno));
272         }
273
274         ao2_unlock(timer);
275
276         return 0;
277 }
278
279 static int kqueue_timer_ack(void *data, unsigned int quantity)
280 {
281         static struct timespec ts_nowait = { 0, 0 };
282         struct kqueue_timer *timer = data;
283         struct kevent kev[2];
284         int i, retval;
285
286         ao2_lock(timer);
287
288         retval = kevent(timer->handle, NULL, 0, kev, 2, &ts_nowait);
289         if (retval == -1) {
290                 ast_log(LOG_ERROR, "[%d]: Error sampling kqueue: %s\n",
291                         timer->handle, strerror(errno));
292                 ao2_unlock(timer);
293                 return -1;
294         }
295
296         for (i = 0; i < retval; i++) {
297                 switch (kev[i].filter) {
298                 case EVFILT_TIMER:
299                         if (kev[i].data > quantity) {
300                                 ast_log(LOG_ERROR, "[%d]: Missed %ju\n",
301                                         timer->handle,
302                                         (uintmax_t)kev[i].data - quantity);
303                         }
304                         break;
305                 case CONTINUOUS_EVFILT_TYPE:
306                         if (!timer->is_continuous) {
307                                 ast_log(LOG_ERROR,
308                                         "[%d]: Spurious user event\n",
309                                         timer->handle);
310                         }
311                         break;
312                 default:
313                         ast_log(LOG_ERROR, "[%d]: Spurious kevent type %d.\n",
314                                 timer->handle, kev[i].filter);
315                 }
316         }
317
318         ao2_unlock(timer);
319
320         return 0;
321 }
322
323 static int kqueue_timer_enable_continuous(void *data)
324 {
325         struct kqueue_timer *timer = data;
326         int retval;
327
328         ao2_lock(timer);
329
330         if (!timer->is_continuous) {
331                 ast_debug(5, "[%d]: Enable Continuous\n", timer->handle);
332                 retval = kqueue_timer_enable_continuous_event(timer);
333                 if (retval == -1) {
334                         ast_log(LOG_ERROR,
335                                 "[%d]: Error signaling continuous event: %s\n",
336                                 timer->handle, strerror(errno));
337                 }
338                 timer->is_continuous = 1;
339         }
340
341         ao2_unlock(timer);
342
343         return 0;
344 }
345
346 static int kqueue_timer_disable_continuous(void *data)
347 {
348         struct kqueue_timer *timer = data;
349         int retval;
350
351         ao2_lock(timer);
352
353         if (timer->is_continuous) {
354                 ast_debug(5, "[%d]: Disable Continuous\n", timer->handle);
355                 retval = kqueue_timer_disable_continuous_event(timer);
356                 if (retval == -1) {
357                         ast_log(LOG_ERROR,
358                                 "[%d]: Error clearing continuous event: %s\n",
359                                 timer->handle, strerror(errno));
360                 }
361                 timer->is_continuous = 0;
362         }
363
364         ao2_unlock(timer);
365
366         return 0;
367 }
368
369 static enum ast_timer_event kqueue_timer_get_event(void *data)
370 {
371         struct kqueue_timer *timer = data;
372         enum ast_timer_event res;
373
374         if (timer->is_continuous) {
375                 res = AST_TIMING_EVENT_CONTINUOUS;
376         } else {
377                 res = AST_TIMING_EVENT_EXPIRED;
378         }
379
380         return res;
381 }
382
383 static unsigned int kqueue_timer_get_max_rate(void *data)
384 {
385         return INTPTR_MAX > UINT_MAX ? UINT_MAX : INTPTR_MAX;
386 }
387
388 static int kqueue_timer_fd(void *data)
389 {
390         struct kqueue_timer *timer = data;
391
392         return timer->handle;
393 }
394
395 #ifdef TEST_FRAMEWORK
396 AST_TEST_DEFINE(test_kqueue_timing)
397 {
398         int res = AST_TEST_PASS, i;
399         uint64_t diff;
400         struct pollfd pfd = { 0, POLLIN, 0 };
401         struct kqueue_timer *kt;
402         struct timeval start;
403
404         switch (cmd) {
405         case TEST_INIT:
406                 info->name = "test_kqueue_timing";
407                 info->category = "/res/res_timing_kqueue/";
408                 info->summary = "Test KQueue timing interface";
409                 info->description = "Verify that the KQueue timing interface correctly generates timing events";
410                 return AST_TEST_NOT_RUN;
411         case TEST_EXECUTE:
412                 break;
413         }
414
415         if (!(kt = kqueue_timer_open())) {
416                 ast_test_status_update(test, "Cannot open timer!\n");
417                 return AST_TEST_FAIL;
418         }
419
420         do {
421                 pfd.fd = kqueue_timer_fd(kt);
422                 if (kqueue_timer_set_rate(kt, 1000)) {
423                         ast_test_status_update(test, "Cannot set timer rate to 1000/s\n");
424                         res = AST_TEST_FAIL;
425                         break;
426                 }
427                 if (ast_poll(&pfd, 1, 1000) < 1) {
428                         ast_test_status_update(test, "Polling on a kqueue doesn't work\n");
429                         res = AST_TEST_FAIL;
430                         break;
431                 }
432                 if (pfd.revents != POLLIN) {
433                         ast_test_status_update(test, "poll() should have returned POLLIN, but instead returned %hd\n", pfd.revents);
434                         res = AST_TEST_FAIL;
435                         break;
436                 }
437                 if (kqueue_timer_get_event(kt) <= 0) {
438                         ast_test_status_update(test, "No events generated after a poll returned successfully?!!\n");
439                         res = AST_TEST_FAIL;
440                         break;
441                 }
442                 if (kqueue_timer_ack(kt, 1) != 0) {
443                         ast_test_status_update(test, "Acking event failed.\n");
444                         res = AST_TEST_FAIL;
445                         break;
446                 }
447
448                 kqueue_timer_enable_continuous(kt);
449                 start = ast_tvnow();
450                 for (i = 0; i < 100; i++) {
451                         if (ast_poll(&pfd, 1, 1000) < 1) {
452                                 ast_test_status_update(test, "Polling on a kqueue doesn't work\n");
453                                 res = AST_TEST_FAIL;
454                                 break;
455                         }
456                         if (kqueue_timer_get_event(kt) <= 0) {
457                                 ast_test_status_update(test, "No events generated in continuous mode after 1 microsecond?!!\n");
458                                 res = AST_TEST_FAIL;
459                                 break;
460                         }
461                         if (kqueue_timer_ack(kt, 1) != 0) {
462                                 ast_test_status_update(test, "Acking event failed.\n");
463                                 res = AST_TEST_FAIL;
464                                 break;
465                         }
466
467                 }
468                 diff = ast_tvdiff_us(ast_tvnow(), start);
469                 ast_test_status_update(test, "diff is %llu\n", diff);
470         } while (0);
471         kqueue_timer_close(kt);
472         return res;
473 }
474 #endif
475
476 /*!
477  * \brief Load the module
478  *
479  * Module loading including tests for configuration or dependencies.
480  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
481  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
482  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
483  * configuration file or other non-critical problem return
484  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
485  */
486 static int load_module(void)
487 {
488         if (!(timing_funcs_handle = ast_register_timing_interface(&kqueue_timing))) {
489                 return AST_MODULE_LOAD_DECLINE;
490         }
491
492         AST_TEST_REGISTER(test_kqueue_timing);
493         return AST_MODULE_LOAD_SUCCESS;
494 }
495
496 static int unload_module(void)
497 {
498         AST_TEST_UNREGISTER(test_kqueue_timing);
499
500         return ast_unregister_timing_interface(timing_funcs_handle);
501 }
502
503 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "KQueue Timing Interface",
504         .support_level = AST_MODULE_SUPPORT_EXTENDED,
505         .load = load_module,
506         .unload = unload_module,
507         .load_pri = AST_MODPRI_CHANNEL_DEPEND,
508 );