blob: f98360142d5944b77727693b8cf90656b244c2c7 [file] [log] [blame]
Neels Hofmeyr17518fe2017-06-20 04:35:06 +02001/*! \file select.c
2 * select filedescriptor handling.
3 * Taken from:
Harald Welteec8b4502010-02-20 20:34:29 +01004 * userspace logging daemon for the iptables ULOG target
Neels Hofmeyr17518fe2017-06-20 04:35:06 +02005 * of the linux 2.4 netfilter subsystem. */
6/*
Harald Welteb904e422020-10-18 21:24:13 +02007 * (C) 2000-2020 by Harald Welte <laforge@gnumonks.org>
Harald Welte6dda35a2022-11-09 16:54:50 +01008 * All Rights Reserved.
Harald Weltee08da972017-11-13 01:00:26 +09009 *
10 * SPDX-License-Identifier: GPL-2.0+
Harald Welteec8b4502010-02-20 20:34:29 +010011 *
12 * This program is free software; you can redistribute it and/or modify
Harald Welte9d92f0e2010-10-31 13:56:45 +010013 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
Harald Welteec8b4502010-02-20 20:34:29 +010016 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
Harald Welteec8b4502010-02-20 20:34:29 +010021 */
22
23#include <fcntl.h>
Holger Hans Peter Freyther43558312010-08-06 06:48:43 +080024#include <stdio.h>
Harald Welteea91a512017-07-13 14:28:30 +020025#include <unistd.h>
Harald Welte9e166e82014-03-10 17:28:33 +010026#include <string.h>
Philipp Maierb2888532016-12-09 14:07:18 +010027#include <stdbool.h>
Harald Welteea4d8932017-12-03 16:13:39 +010028#include <errno.h>
Holger Hans Peter Freyther43558312010-08-06 06:48:43 +080029
Pablo Neira Ayuso83419342011-03-22 16:36:13 +010030#include <osmocom/core/select.h>
31#include <osmocom/core/linuxlist.h>
32#include <osmocom/core/timer.h>
Harald Welte52a83752019-02-21 16:37:10 +010033#include <osmocom/core/logging.h>
Harald Welte2d906112019-03-18 17:17:43 +010034#include <osmocom/core/talloc.h>
35#include <osmocom/core/utils.h>
Philipp Maierb1ef8f52021-12-06 16:31:02 +010036#include <osmocom/core/stat_item.h>
37#include <osmocom/core/stats_tcp.h>
Harald Welteec8b4502010-02-20 20:34:29 +010038
Pau Espin Pedrol88955fb2023-01-18 18:54:00 +010039#include "config.h"
Harald Welte54844802010-02-20 22:23:08 +010040
Harald Welteb904e422020-10-18 21:24:13 +020041#if defined(HAVE_SYS_SELECT_H) && defined(HAVE_POLL_H)
Harald Welte1d604d82017-05-17 15:32:35 +010042#include <sys/select.h>
Harald Welteb904e422020-10-18 21:24:13 +020043#include <poll.h>
Harald Welteec8b4502010-02-20 20:34:29 +010044
Harald Welteba6988b2011-08-17 12:46:48 +020045/*! \addtogroup select
46 * @{
Neels Hofmeyr87e45502017-06-20 00:17:59 +020047 * select() loop abstraction
Neels Hofmeyr17518fe2017-06-20 04:35:06 +020048 *
49 * \file select.c */
Harald Welteba6988b2011-08-17 12:46:48 +020050
Harald Welte7a010b12019-04-06 13:46:40 +020051/* keep a set of file descriptors per-thread, so that each thread can have its own
52 * distinct set of file descriptors to interact with */
53static __thread int maxfd = 0;
54static __thread struct llist_head osmo_fds; /* TLS cannot use LLIST_HEAD() */
55static __thread int unregistered_count;
Harald Welteec8b4502010-02-20 20:34:29 +010056
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +010057/* Array of struct osmo_fd * (size "max_fd") ordered by "ofd->fd" */
58static __thread struct {
59 struct osmo_fd **table;
60 unsigned int size;
61} osmo_fd_lookup;
62
63static void osmo_fd_lookup_table_extend(unsigned int new_max_fd)
64{
65 unsigned int min_new_size;
66 unsigned int pw2;
67 unsigned int new_size;
68
69 /* First calculate the minimally required new size of the array in bytes: */
70 min_new_size = (new_max_fd + 1) * sizeof(struct osmo_fd *);
71 /* Now find the lower power of two of min_new_size (in bytes): */
72 pw2 = 32 - __builtin_clz(min_new_size);
73 /* get next (upper side) power of 2: */
74 pw2++;
75 OSMO_ASSERT(pw2 <= 31); /* Avoid shifting more than 31 bits */
76 new_size = 1 << (pw2 + 1);
77
78 /* Let's make it at least 1024B, to avoid reallocating quickly at startup */
79 if (new_size < 1024)
80 new_size = 1024;
81 if (new_size > osmo_fd_lookup.size) {
82 uint8_t *ptr = talloc_realloc_size(OTC_GLOBAL, osmo_fd_lookup.table, new_size);
83 OSMO_ASSERT(ptr);
84 memset(ptr + osmo_fd_lookup.size, 0, new_size - osmo_fd_lookup.size);
85 osmo_fd_lookup.table = (struct osmo_fd **)ptr;
86 osmo_fd_lookup.size = new_size;
87 }
88}
89
Harald Welteb904e422020-10-18 21:24:13 +020090#ifndef FORCE_IO_SELECT
91struct poll_state {
92 /* array of pollfd */
93 struct pollfd *poll;
94 /* number of entries in pollfd allocated */
95 unsigned int poll_size;
96 /* number of osmo_fd registered */
97 unsigned int num_registered;
98};
99static __thread struct poll_state g_poll;
100#endif /* FORCE_IO_SELECT */
101
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200102/*! See osmo_select_shutdown_request() */
103static int _osmo_select_shutdown_requested = 0;
104/*! See osmo_select_shutdown_request() */
105static bool _osmo_select_shutdown_done = false;
106
Harald Welte6c0a0e62017-08-12 11:43:14 +0200107/*! Set up an osmo-fd. Will not register it.
108 * \param[inout] ofd Osmo FD to be set-up
109 * \param[in] fd OS-level file descriptor number
Harald Welte16886992019-03-20 10:26:39 +0100110 * \param[in] when bit-mask of OSMO_FD_{READ,WRITE,EXECEPT}
Harald Welte6c0a0e62017-08-12 11:43:14 +0200111 * \param[in] cb Call-back function to be called
112 * \param[in] data Private context pointer
113 * \param[in] priv_nr Private number
114 */
115void osmo_fd_setup(struct osmo_fd *ofd, int fd, unsigned int when,
116 int (*cb)(struct osmo_fd *fd, unsigned int what),
117 void *data, unsigned int priv_nr)
118{
119 ofd->fd = fd;
120 ofd->when = when;
121 ofd->cb = cb;
122 ofd->data = data;
123 ofd->priv_nr = priv_nr;
124}
Philipp Maierb2888532016-12-09 14:07:18 +0100125
Harald Welte7e657912020-10-18 22:07:21 +0200126/*! Update the 'when' field of osmo_fd. "ofd->when = (ofd->when & when_mask) | when".
127 * Use this function instead of directly modifying ofd->when, as the latter will be
128 * removed soon. */
129void osmo_fd_update_when(struct osmo_fd *ofd, unsigned int when_mask, unsigned int when)
130{
131 ofd->when &= when_mask;
132 ofd->when |= when;
133}
134
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200135/*! Check if a file descriptor is already registered
Philipp Maierb2888532016-12-09 14:07:18 +0100136 * \param[in] fd osmocom file descriptor to be checked
137 * \returns true if registered; otherwise false
138 */
139bool osmo_fd_is_registered(struct osmo_fd *fd)
140{
141 struct osmo_fd *entry;
142 llist_for_each_entry(entry, &osmo_fds, list) {
143 if (entry == fd) {
144 return true;
145 }
146 }
147
148 return false;
149}
150
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200151/*! Register a new file descriptor with select loop abstraction
Harald Welteba6988b2011-08-17 12:46:48 +0200152 * \param[in] fd osmocom file descriptor to be registered
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200153 * \returns 0 on success; negative in case of error
Harald Welteba6988b2011-08-17 12:46:48 +0200154 */
Pablo Neira Ayusof7f89d02011-05-07 12:42:40 +0200155int osmo_fd_register(struct osmo_fd *fd)
Harald Welteec8b4502010-02-20 20:34:29 +0100156{
157 int flags;
158
159 /* make FD nonblocking */
160 flags = fcntl(fd->fd, F_GETFL);
161 if (flags < 0)
162 return flags;
163 flags |= O_NONBLOCK;
164 flags = fcntl(fd->fd, F_SETFL, flags);
165 if (flags < 0)
166 return flags;
167
Harald Welte32e1f232011-06-26 13:07:18 +0200168 /* set close-on-exec flag */
169 flags = fcntl(fd->fd, F_GETFD);
170 if (flags < 0)
171 return flags;
172 flags |= FD_CLOEXEC;
173 flags = fcntl(fd->fd, F_SETFD, flags);
174 if (flags < 0)
175 return flags;
176
Harald Welteec8b4502010-02-20 20:34:29 +0100177 /* Register FD */
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100178 if (fd->fd > maxfd) {
Harald Welteec8b4502010-02-20 20:34:29 +0100179 maxfd = fd->fd;
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100180 osmo_fd_lookup_table_extend(maxfd);
181 }
Harald Welteec8b4502010-02-20 20:34:29 +0100182
Pau Espin Pedrold05def02020-05-09 19:24:21 +0200183#ifdef OSMO_FD_CHECK
Philipp Maierb2888532016-12-09 14:07:18 +0100184 if (osmo_fd_is_registered(fd)) {
185 fprintf(stderr, "Adding a osmo_fd that is already in the list.\n");
186 return 0;
Holger Hans Peter Freyther43558312010-08-06 06:48:43 +0800187 }
188#endif
Harald Welteb904e422020-10-18 21:24:13 +0200189#ifndef FORCE_IO_SELECT
190 if (g_poll.num_registered + 1 > g_poll.poll_size) {
191 struct pollfd *p;
192 unsigned int new_size = g_poll.poll_size ? g_poll.poll_size * 2 : 1024;
193 p = talloc_realloc(OTC_GLOBAL, g_poll.poll, struct pollfd, new_size);
194 if (!p)
195 return -ENOMEM;
196 memset(p + g_poll.poll_size, 0, new_size - g_poll.poll_size);
197 g_poll.poll = p;
198 g_poll.poll_size = new_size;
199 }
200 g_poll.num_registered++;
201#endif /* FORCE_IO_SELECT */
Holger Hans Peter Freyther43558312010-08-06 06:48:43 +0800202
Pablo Neira Ayusof7f89d02011-05-07 12:42:40 +0200203 llist_add_tail(&fd->list, &osmo_fds);
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100204 osmo_fd_lookup.table[fd->fd] = fd;
Harald Welteec8b4502010-02-20 20:34:29 +0100205
206 return 0;
207}
208
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200209/*! Unregister a file descriptor from select loop abstraction
Harald Welteba6988b2011-08-17 12:46:48 +0200210 * \param[in] fd osmocom file descriptor to be unregistered
211 */
Pablo Neira Ayusof7f89d02011-05-07 12:42:40 +0200212void osmo_fd_unregister(struct osmo_fd *fd)
Harald Welteec8b4502010-02-20 20:34:29 +0100213{
Philipp Maierb2888532016-12-09 14:07:18 +0100214 /* Note: when fd is inside the osmo_fds list (not registered before)
215 * this function will crash! If in doubt, check file descriptor with
216 * osmo_fd_is_registered() */
Harald Welteec8b4502010-02-20 20:34:29 +0100217 unregistered_count++;
218 llist_del(&fd->list);
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100219 OSMO_ASSERT(fd->fd >= 0);
220 OSMO_ASSERT(fd->fd <= maxfd);
221 osmo_fd_lookup.table[fd->fd] = NULL;
Harald Welteb904e422020-10-18 21:24:13 +0200222#ifndef FORCE_IO_SELECT
223 g_poll.num_registered--;
224#endif /* FORCE_IO_SELECT */
Philipp Maierb1ef8f52021-12-06 16:31:02 +0100225
226 /* If existent, free any statistical data */
227 osmo_stats_tcp_osmo_fd_unregister(fd);
Harald Welteec8b4502010-02-20 20:34:29 +0100228}
229
Harald Welteea91a512017-07-13 14:28:30 +0200230/*! Close a file descriptor, mark it as closed + unregister from select loop abstraction
231 * \param[in] fd osmocom file descriptor to be unregistered + closed
232 *
233 * If \a fd is registered, we unregister it from the select() loop
234 * abstraction. We then close the fd and set it to -1, as well as
235 * unsetting any 'when' flags */
236void osmo_fd_close(struct osmo_fd *fd)
237{
238 if (osmo_fd_is_registered(fd))
239 osmo_fd_unregister(fd);
240 if (fd->fd != -1)
241 close(fd->fd);
242 fd->fd = -1;
243 fd->when = 0;
244}
245
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200246/*! Populate the fd_sets and return the highest fd number
Holger Hans Peter Freytherff206412017-03-07 14:28:38 +0100247 * \param[in] _rset The readfds to populate
248 * \param[in] _wset The wrtiefds to populate
249 * \param[in] _eset The errorfds to populate
250 *
251 * \returns The highest file descriptor seen or 0 on an empty list
252 */
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100253inline int osmo_fd_fill_fds(void *_rset, void *_wset, void *_eset)
Harald Welteec8b4502010-02-20 20:34:29 +0100254{
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100255 fd_set *readset = _rset, *writeset = _wset, *exceptset = _eset;
256 struct osmo_fd *ufd;
Holger Hans Peter Freytherff206412017-03-07 14:28:38 +0100257 int highfd = 0;
Harald Welteec8b4502010-02-20 20:34:29 +0100258
Pablo Neira Ayusof7f89d02011-05-07 12:42:40 +0200259 llist_for_each_entry(ufd, &osmo_fds, list) {
Harald Welte16886992019-03-20 10:26:39 +0100260 if (ufd->when & OSMO_FD_READ)
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100261 FD_SET(ufd->fd, readset);
Harald Welteec8b4502010-02-20 20:34:29 +0100262
Harald Welte16886992019-03-20 10:26:39 +0100263 if (ufd->when & OSMO_FD_WRITE)
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100264 FD_SET(ufd->fd, writeset);
Harald Welteec8b4502010-02-20 20:34:29 +0100265
Harald Welte16886992019-03-20 10:26:39 +0100266 if (ufd->when & OSMO_FD_EXCEPT)
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100267 FD_SET(ufd->fd, exceptset);
Holger Hans Peter Freytherff206412017-03-07 14:28:38 +0100268
269 if (ufd->fd > highfd)
270 highfd = ufd->fd;
Harald Welteec8b4502010-02-20 20:34:29 +0100271 }
272
Holger Hans Peter Freytherff206412017-03-07 14:28:38 +0100273 return highfd;
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100274}
Harald Welteec8b4502010-02-20 20:34:29 +0100275
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100276inline int osmo_fd_disp_fds(void *_rset, void *_wset, void *_eset)
277{
278 struct osmo_fd *ufd, *tmp;
279 int work = 0;
280 fd_set *readset = _rset, *writeset = _wset, *exceptset = _eset;
Harald Welteec8b4502010-02-20 20:34:29 +0100281
Harald Welteec8b4502010-02-20 20:34:29 +0100282restart:
283 unregistered_count = 0;
Pablo Neira Ayusof7f89d02011-05-07 12:42:40 +0200284 llist_for_each_entry_safe(ufd, tmp, &osmo_fds, list) {
Harald Welteec8b4502010-02-20 20:34:29 +0100285 int flags = 0;
286
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100287 if (FD_ISSET(ufd->fd, readset)) {
Harald Welte16886992019-03-20 10:26:39 +0100288 flags |= OSMO_FD_READ;
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100289 FD_CLR(ufd->fd, readset);
Harald Welteec8b4502010-02-20 20:34:29 +0100290 }
291
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100292 if (FD_ISSET(ufd->fd, writeset)) {
Harald Welte16886992019-03-20 10:26:39 +0100293 flags |= OSMO_FD_WRITE;
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100294 FD_CLR(ufd->fd, writeset);
Harald Welteec8b4502010-02-20 20:34:29 +0100295 }
296
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100297 if (FD_ISSET(ufd->fd, exceptset)) {
Harald Welte16886992019-03-20 10:26:39 +0100298 flags |= OSMO_FD_EXCEPT;
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100299 FD_CLR(ufd->fd, exceptset);
Harald Welteec8b4502010-02-20 20:34:29 +0100300 }
301
302 if (flags) {
303 work = 1;
Harald Welte52a83752019-02-21 16:37:10 +0100304 /* make sure to clear any log context before processing the next incoming message
305 * as part of some file descriptor callback. This effectively prevents "context
306 * leaking" from processing of one message into processing of the next message as part
307 * of one iteration through the list of file descriptors here. See OS#3813 */
308 log_reset_context();
Harald Welteec8b4502010-02-20 20:34:29 +0100309 ufd->cb(ufd, flags);
310 }
Holger Hans Peter Freyther92e1e702014-04-09 17:24:00 +0200311 /* ugly, ugly hack. If more than one filedescriptor was
Harald Welteec8b4502010-02-20 20:34:29 +0100312 * unregistered, they might have been consecutive and
313 * llist_for_each_entry_safe() is no longer safe */
Holger Hans Peter Freyther23ba4742010-04-11 17:33:19 +0200314 /* this seems to happen with the last element of the list as well */
315 if (unregistered_count >= 1)
Harald Welteec8b4502010-02-20 20:34:29 +0100316 goto restart;
317 }
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100318
Harald Welteec8b4502010-02-20 20:34:29 +0100319 return work;
320}
321
Harald Welteb904e422020-10-18 21:24:13 +0200322
323#ifndef FORCE_IO_SELECT
324/* fill g_poll.poll and return the number of entries filled */
325static unsigned int poll_fill_fds(void)
326{
327 struct osmo_fd *ufd;
328 unsigned int i = 0;
329
330 llist_for_each_entry(ufd, &osmo_fds, list) {
331 struct pollfd *p;
332
333 if (!ufd->when)
334 continue;
335
336 p = &g_poll.poll[i++];
337
338 p->fd = ufd->fd;
339 p->events = 0;
340 p->revents = 0;
341
342 /* use the same mapping as the Linux kernel does in fs/select.c */
343 if (ufd->when & OSMO_FD_READ)
344 p->events |= POLLIN | POLLHUP | POLLERR;
345
346 if (ufd->when & OSMO_FD_WRITE)
347 p->events |= POLLOUT | POLLERR;
348
349 if (ufd->when & OSMO_FD_EXCEPT)
350 p->events |= POLLPRI;
351
352 }
353
354 return i;
355}
356
357/* iterate over first n_fd entries of g_poll.poll + dispatch */
Harald Welte0b08d512022-01-09 12:03:12 +0100358static int poll_disp_fds(unsigned int n_fd)
Harald Welteb904e422020-10-18 21:24:13 +0200359{
360 struct osmo_fd *ufd;
361 unsigned int i;
362 int work = 0;
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200363 int shutdown_pending_writes = 0;
Harald Welteb904e422020-10-18 21:24:13 +0200364
365 for (i = 0; i < n_fd; i++) {
366 struct pollfd *p = &g_poll.poll[i];
367 int flags = 0;
368
369 if (!p->revents)
370 continue;
371
372 ufd = osmo_fd_get_by_fd(p->fd);
373 if (!ufd) {
374 /* FD might have been unregistered meanwhile */
375 continue;
376 }
377 /* use the same mapping as the Linux kernel does in fs/select.c */
378 if (p->revents & (POLLIN | POLLHUP | POLLERR))
379 flags |= OSMO_FD_READ;
380 if (p->revents & (POLLOUT | POLLERR))
381 flags |= OSMO_FD_WRITE;
382 if (p->revents & POLLPRI)
383 flags |= OSMO_FD_EXCEPT;
384
385 /* make sure we never report more than the user requested */
386 flags &= ufd->when;
387
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200388 if (_osmo_select_shutdown_requested > 0) {
389 if (ufd->when & OSMO_FD_WRITE)
390 shutdown_pending_writes++;
391 }
392
Harald Welteb904e422020-10-18 21:24:13 +0200393 if (flags) {
394 work = 1;
395 /* make sure to clear any log context before processing the next incoming message
396 * as part of some file descriptor callback. This effectively prevents "context
397 * leaking" from processing of one message into processing of the next message as part
398 * of one iteration through the list of file descriptors here. See OS#3813 */
399 log_reset_context();
400 ufd->cb(ufd, flags);
401 }
402 }
403
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200404 if (_osmo_select_shutdown_requested > 0 && !shutdown_pending_writes)
405 _osmo_select_shutdown_done = true;
406
Harald Welteb904e422020-10-18 21:24:13 +0200407 return work;
408}
409
410static int _osmo_select_main(int polling)
411{
412 unsigned int n_poll;
413 int rc;
Oliver Smithd841bec2021-12-21 19:17:51 +0100414 int timeout = 0;
Harald Welteb904e422020-10-18 21:24:13 +0200415
416 /* prepare read and write fdsets */
417 n_poll = poll_fill_fds();
418
Oliver Smithd841bec2021-12-21 19:17:51 +0100419 if (!polling) {
Harald Welteb904e422020-10-18 21:24:13 +0200420 osmo_timers_prepare();
Oliver Smithd841bec2021-12-21 19:17:51 +0100421 timeout = osmo_timers_nearest_ms();
Harald Welteb904e422020-10-18 21:24:13 +0200422
Oliver Smithd841bec2021-12-21 19:17:51 +0100423 if (_osmo_select_shutdown_requested && timeout == -1)
424 timeout = 0;
425 }
426
427 rc = poll(g_poll.poll, n_poll, timeout);
Harald Welteb904e422020-10-18 21:24:13 +0200428 if (rc < 0)
429 return 0;
430
431 /* fire timers */
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200432 if (!_osmo_select_shutdown_requested)
433 osmo_timers_update();
Harald Welteb904e422020-10-18 21:24:13 +0200434
435 OSMO_ASSERT(osmo_ctx->select);
436
437 /* call registered callback functions */
438 return poll_disp_fds(n_poll);
439}
440#else /* FORCE_IO_SELECT */
441/* the old implementation based on select, used 2008-2020 */
Harald Welte2d906112019-03-18 17:17:43 +0100442static int _osmo_select_main(int polling)
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100443{
444 fd_set readset, writeset, exceptset;
445 int rc;
446 struct timeval no_time = {0, 0};
447
448 FD_ZERO(&readset);
449 FD_ZERO(&writeset);
450 FD_ZERO(&exceptset);
451
452 /* prepare read and write fdsets */
453 osmo_fd_fill_fds(&readset, &writeset, &exceptset);
454
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100455 if (!polling)
456 osmo_timers_prepare();
457 rc = select(maxfd+1, &readset, &writeset, &exceptset, polling ? &no_time : osmo_timers_nearest());
458 if (rc < 0)
459 return 0;
460
461 /* fire timers */
462 osmo_timers_update();
463
Harald Welte2d906112019-03-18 17:17:43 +0100464 OSMO_ASSERT(osmo_ctx->select);
465
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100466 /* call registered callback functions */
467 return osmo_fd_disp_fds(&readset, &writeset, &exceptset);
468}
Harald Welteb904e422020-10-18 21:24:13 +0200469#endif /* FORCE_IO_SELECT */
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100470
Harald Welte2d906112019-03-18 17:17:43 +0100471/*! select main loop integration
472 * \param[in] polling should we pollonly (1) or block on select (0)
473 * \returns 0 if no fd handled; 1 if fd handled; negative in case of error
474 */
475int osmo_select_main(int polling)
476{
477 int rc = _osmo_select_main(polling);
478#ifndef EMBEDDED
479 if (talloc_total_size(osmo_ctx->select) != 0) {
480 osmo_panic("You cannot use the 'select' volatile "
481 "context if you don't use osmo_select_main_ctx()!\n");
482 }
483#endif
484 return rc;
485}
486
487#ifndef EMBEDDED
488/*! select main loop integration with temporary select-dispatch talloc context
489 * \param[in] polling should we pollonly (1) or block on select (0)
490 * \returns 0 if no fd handled; 1 if fd handled; negative in case of error
491 */
492int osmo_select_main_ctx(int polling)
493{
494 int rc = _osmo_select_main(polling);
495 /* free all the children of the volatile 'select' scope context */
496 talloc_free_children(osmo_ctx->select);
497 return rc;
498}
499#endif
500
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200501/*! find an osmo_fd based on the integer fd
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200502 * \param[in] fd file descriptor to use as search key
503 * \returns \ref osmo_fd for \ref fd; NULL in case it doesn't exist */
Harald Welte6c33ae22016-03-19 21:17:58 +0100504struct osmo_fd *osmo_fd_get_by_fd(int fd)
505{
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100506 if (fd > maxfd)
507 return NULL;
508 return osmo_fd_lookup.table[fd];
Harald Welte6c33ae22016-03-19 21:17:58 +0100509}
510
Harald Welte7a010b12019-04-06 13:46:40 +0200511/*! initialize the osmocom select abstraction for the current thread */
512void osmo_select_init(void)
513{
514 INIT_LLIST_HEAD(&osmo_fds);
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100515 osmo_fd_lookup_table_extend(0);
Harald Welte7a010b12019-04-06 13:46:40 +0200516}
517
518/* ensure main thread always has pre-initialized osmo_fds */
519static __attribute__((constructor)) void on_dso_load_select(void)
520{
521 osmo_select_init();
522}
523
Harald Welteea4d8932017-12-03 16:13:39 +0100524#ifdef HAVE_SYS_TIMERFD_H
525#include <sys/timerfd.h>
526
527/*! disable the osmocom-wrapped timerfd */
528int osmo_timerfd_disable(struct osmo_fd *ofd)
529{
530 const struct itimerspec its_null = {
531 .it_value = { 0, 0 },
532 .it_interval = { 0, 0 },
533 };
534 return timerfd_settime(ofd->fd, 0, &its_null, NULL);
535}
536
Alexander Chemerise8ec2142020-05-09 01:57:16 +0300537/*! schedule the osmocom-wrapped timerfd to occur first at \a first, then periodically at \a interval
Harald Welteea4d8932017-12-03 16:13:39 +0100538 * \param[in] ofd Osmocom wrapped timerfd
539 * \param[in] first Relative time at which the timer should first execute (NULL = \a interval)
540 * \param[in] interval Time interval at which subsequent timer shall fire
541 * \returns 0 on success; negative on error */
542int osmo_timerfd_schedule(struct osmo_fd *ofd, const struct timespec *first,
543 const struct timespec *interval)
544{
545 struct itimerspec its;
546
547 if (ofd->fd < 0)
548 return -EINVAL;
549
550 /* first expiration */
551 if (first)
552 its.it_value = *first;
553 else
554 its.it_value = *interval;
555 /* repeating interval */
556 its.it_interval = *interval;
557
558 return timerfd_settime(ofd->fd, 0, &its, NULL);
559}
560
561/*! setup osmocom-wrapped timerfd
562 * \param[inout] ofd Osmocom-wrapped timerfd on which to operate
563 * \param[in] cb Call-back function called when timerfd becomes readable
564 * \param[in] data Opaque data to be passed on to call-back
565 * \returns 0 on success; negative on error
566 *
567 * We simply initialize the data structures here, but do not yet
568 * schedule the timer.
569 */
570int osmo_timerfd_setup(struct osmo_fd *ofd, int (*cb)(struct osmo_fd *, unsigned int), void *data)
571{
572 ofd->cb = cb;
573 ofd->data = data;
Harald Welte16886992019-03-20 10:26:39 +0100574 ofd->when = OSMO_FD_READ;
Harald Welteea4d8932017-12-03 16:13:39 +0100575
576 if (ofd->fd < 0) {
Harald Welte37608f92018-10-21 12:32:55 +0200577 int rc;
578
Harald Welteea4d8932017-12-03 16:13:39 +0100579 ofd->fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
580 if (ofd->fd < 0)
581 return ofd->fd;
582
Harald Welte37608f92018-10-21 12:32:55 +0200583 rc = osmo_fd_register(ofd);
584 if (rc < 0) {
Harald Welte100e44e2020-04-18 21:16:43 +0200585 osmo_fd_unregister(ofd);
Harald Welte37608f92018-10-21 12:32:55 +0200586 close(ofd->fd);
587 ofd->fd = -1;
588 return rc;
589 }
Harald Welteea4d8932017-12-03 16:13:39 +0100590 }
591 return 0;
592}
593
594#endif /* HAVE_SYS_TIMERFD_H */
595
Harald Weltea70ac852020-04-17 19:20:01 +0200596#ifdef HAVE_SYS_SIGNALFD_H
597#include <sys/signalfd.h>
598
599static int signalfd_callback(struct osmo_fd *ofd, unsigned int what)
600{
601 struct osmo_signalfd *osfd = ofd->data;
602 struct signalfd_siginfo fdsi;
603 int rc;
604
605 rc = read(ofd->fd, &fdsi, sizeof(fdsi));
606 if (rc < 0) {
607 osmo_fd_unregister(ofd);
608 close(ofd->fd);
609 ofd->fd = -1;
610 return rc;
611 }
612
613 osfd->cb(osfd, &fdsi);
614
615 return 0;
616};
617
618/*! create a signalfd and register it with osmocom select loop.
619 * \param[in] ctx talloc context from which osmo_signalfd is to be allocated
620 * \param[in] set of signals to be accept via this file descriptor
621 * \param[in] cb call-back function to be called for each arriving signal
622 * \param[in] data opaque user-provided data to pass to callback
623 * \returns pointer to newly-allocated + registered osmo_signalfd; NULL on error */
624struct osmo_signalfd *
625osmo_signalfd_setup(void *ctx, sigset_t set, osmo_signalfd_cb *cb, void *data)
626{
627 struct osmo_signalfd *osfd = talloc_size(ctx, sizeof(*osfd));
628 int fd, rc;
629
630 if (!osfd)
631 return NULL;
632
633 osfd->data = data;
634 osfd->sigset = set;
635 osfd->cb = cb;
636
637 fd = signalfd(-1, &osfd->sigset, SFD_NONBLOCK);
638 if (fd < 0) {
639 talloc_free(osfd);
640 return NULL;
641 }
642
643 osmo_fd_setup(&osfd->ofd, fd, OSMO_FD_READ, signalfd_callback, osfd, 0);
644 rc = osmo_fd_register(&osfd->ofd);
645 if (rc < 0) {
646 close(fd);
647 talloc_free(osfd);
648 return NULL;
649 }
650
651 return osfd;
652}
653
654#endif /* HAVE_SYS_SIGNALFD_H */
Harald Welteea4d8932017-12-03 16:13:39 +0100655
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200656/*! Request osmo_select_* to only service pending OSMO_FD_WRITE requests. Once all writes are done,
657 * osmo_select_shutdown_done() returns true. This allows for example to send all outbound packets before terminating the
658 * process.
659 *
660 * Usage example:
661 *
662 * static void signal_handler(int signum)
663 * {
664 * fprintf(stdout, "signal %u received\n", signum);
665 *
666 * switch (signum) {
667 * case SIGINT:
668 * case SIGTERM:
669 * // If the user hits Ctrl-C the third time, just terminate immediately.
670 * if (osmo_select_shutdown_requested() >= 2)
671 * exit(-1);
672 * // Request write-only mode in osmo_select_main_ctx()
673 * osmo_select_shutdown_request();
674 * break;
675 * [...]
676 * }
677 *
678 * main()
679 * {
680 * signal(SIGINT, &signal_handler);
681 * signal(SIGTERM, &signal_handler);
682 *
683 * [...]
684 *
685 * // After the signal_handler issued osmo_select_shutdown_request(), osmo_select_shutdown_done() returns true
686 * // as soon as all write queues are empty.
687 * while (!osmo_select_shutdown_done()) {
688 * osmo_select_main_ctx(0);
689 * }
690 * }
691 */
Harald Weltee61d4592022-11-03 11:05:58 +0100692void osmo_select_shutdown_request(void)
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200693{
694 _osmo_select_shutdown_requested++;
695};
696
697/*! Return the number of times osmo_select_shutdown_request() was called before. */
Harald Weltee61d4592022-11-03 11:05:58 +0100698int osmo_select_shutdown_requested(void)
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200699{
700 return _osmo_select_shutdown_requested;
701};
702
703/*! Return true after osmo_select_shutdown_requested() was called, and after an osmo_select poll loop found no more
704 * pending OSMO_FD_WRITE on any registered socket. */
Harald Weltee61d4592022-11-03 11:05:58 +0100705bool osmo_select_shutdown_done(void) {
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200706 return _osmo_select_shutdown_done;
707};
708
Sylvain Munautdca7d2c2012-04-18 21:53:23 +0200709/*! @} */
Harald Welteba6988b2011-08-17 12:46:48 +0200710
Harald Welteec8b4502010-02-20 20:34:29 +0100711#endif /* _HAVE_SYS_SELECT_H */