blob: 584de24223c8157247bb306b09e961462e276eec [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
Pau Espin Pedrol153519f2023-03-14 12:01:37 +0100154 *
155 * The API expects fd field of the struct osmo_fd to remain unchanged while
156 * registered, ie until osmo_fd_unregister() is called on it.
Harald Welteba6988b2011-08-17 12:46:48 +0200157 */
Pablo Neira Ayusof7f89d02011-05-07 12:42:40 +0200158int osmo_fd_register(struct osmo_fd *fd)
Harald Welteec8b4502010-02-20 20:34:29 +0100159{
160 int flags;
161
162 /* make FD nonblocking */
163 flags = fcntl(fd->fd, F_GETFL);
164 if (flags < 0)
165 return flags;
166 flags |= O_NONBLOCK;
167 flags = fcntl(fd->fd, F_SETFL, flags);
168 if (flags < 0)
169 return flags;
170
Harald Welte32e1f232011-06-26 13:07:18 +0200171 /* set close-on-exec flag */
172 flags = fcntl(fd->fd, F_GETFD);
173 if (flags < 0)
174 return flags;
175 flags |= FD_CLOEXEC;
176 flags = fcntl(fd->fd, F_SETFD, flags);
177 if (flags < 0)
178 return flags;
179
Harald Welteec8b4502010-02-20 20:34:29 +0100180 /* Register FD */
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100181 if (fd->fd > maxfd) {
Harald Welteec8b4502010-02-20 20:34:29 +0100182 maxfd = fd->fd;
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100183 osmo_fd_lookup_table_extend(maxfd);
184 }
Harald Welteec8b4502010-02-20 20:34:29 +0100185
Pau Espin Pedrold05def02020-05-09 19:24:21 +0200186#ifdef OSMO_FD_CHECK
Philipp Maierb2888532016-12-09 14:07:18 +0100187 if (osmo_fd_is_registered(fd)) {
188 fprintf(stderr, "Adding a osmo_fd that is already in the list.\n");
189 return 0;
Holger Hans Peter Freyther43558312010-08-06 06:48:43 +0800190 }
191#endif
Harald Welteb904e422020-10-18 21:24:13 +0200192#ifndef FORCE_IO_SELECT
193 if (g_poll.num_registered + 1 > g_poll.poll_size) {
194 struct pollfd *p;
195 unsigned int new_size = g_poll.poll_size ? g_poll.poll_size * 2 : 1024;
196 p = talloc_realloc(OTC_GLOBAL, g_poll.poll, struct pollfd, new_size);
197 if (!p)
198 return -ENOMEM;
199 memset(p + g_poll.poll_size, 0, new_size - g_poll.poll_size);
200 g_poll.poll = p;
201 g_poll.poll_size = new_size;
202 }
203 g_poll.num_registered++;
204#endif /* FORCE_IO_SELECT */
Holger Hans Peter Freyther43558312010-08-06 06:48:43 +0800205
Pablo Neira Ayusof7f89d02011-05-07 12:42:40 +0200206 llist_add_tail(&fd->list, &osmo_fds);
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100207 osmo_fd_lookup.table[fd->fd] = fd;
Harald Welteec8b4502010-02-20 20:34:29 +0100208
209 return 0;
210}
211
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200212/*! Unregister a file descriptor from select loop abstraction
Harald Welteba6988b2011-08-17 12:46:48 +0200213 * \param[in] fd osmocom file descriptor to be unregistered
Pau Espin Pedrol153519f2023-03-14 12:01:37 +0100214 *
215 * This function must be called before changing the value of the fd field in
216 * the struct osmo_fd.
Harald Welteba6988b2011-08-17 12:46:48 +0200217 */
Pablo Neira Ayusof7f89d02011-05-07 12:42:40 +0200218void osmo_fd_unregister(struct osmo_fd *fd)
Harald Welteec8b4502010-02-20 20:34:29 +0100219{
Philipp Maierb2888532016-12-09 14:07:18 +0100220 /* Note: when fd is inside the osmo_fds list (not registered before)
221 * this function will crash! If in doubt, check file descriptor with
222 * osmo_fd_is_registered() */
Harald Welteec8b4502010-02-20 20:34:29 +0100223 unregistered_count++;
224 llist_del(&fd->list);
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100225 OSMO_ASSERT(fd->fd >= 0);
226 OSMO_ASSERT(fd->fd <= maxfd);
227 osmo_fd_lookup.table[fd->fd] = NULL;
Harald Welteb904e422020-10-18 21:24:13 +0200228#ifndef FORCE_IO_SELECT
229 g_poll.num_registered--;
230#endif /* FORCE_IO_SELECT */
Philipp Maierb1ef8f52021-12-06 16:31:02 +0100231
232 /* If existent, free any statistical data */
233 osmo_stats_tcp_osmo_fd_unregister(fd);
Harald Welteec8b4502010-02-20 20:34:29 +0100234}
235
Harald Welteea91a512017-07-13 14:28:30 +0200236/*! Close a file descriptor, mark it as closed + unregister from select loop abstraction
237 * \param[in] fd osmocom file descriptor to be unregistered + closed
238 *
239 * If \a fd is registered, we unregister it from the select() loop
240 * abstraction. We then close the fd and set it to -1, as well as
241 * unsetting any 'when' flags */
242void osmo_fd_close(struct osmo_fd *fd)
243{
244 if (osmo_fd_is_registered(fd))
245 osmo_fd_unregister(fd);
246 if (fd->fd != -1)
247 close(fd->fd);
248 fd->fd = -1;
249 fd->when = 0;
250}
251
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200252/*! Populate the fd_sets and return the highest fd number
Holger Hans Peter Freytherff206412017-03-07 14:28:38 +0100253 * \param[in] _rset The readfds to populate
254 * \param[in] _wset The wrtiefds to populate
255 * \param[in] _eset The errorfds to populate
256 *
257 * \returns The highest file descriptor seen or 0 on an empty list
258 */
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100259inline int osmo_fd_fill_fds(void *_rset, void *_wset, void *_eset)
Harald Welteec8b4502010-02-20 20:34:29 +0100260{
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100261 fd_set *readset = _rset, *writeset = _wset, *exceptset = _eset;
262 struct osmo_fd *ufd;
Holger Hans Peter Freytherff206412017-03-07 14:28:38 +0100263 int highfd = 0;
Harald Welteec8b4502010-02-20 20:34:29 +0100264
Pablo Neira Ayusof7f89d02011-05-07 12:42:40 +0200265 llist_for_each_entry(ufd, &osmo_fds, list) {
Harald Welte16886992019-03-20 10:26:39 +0100266 if (ufd->when & OSMO_FD_READ)
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100267 FD_SET(ufd->fd, readset);
Harald Welteec8b4502010-02-20 20:34:29 +0100268
Harald Welte16886992019-03-20 10:26:39 +0100269 if (ufd->when & OSMO_FD_WRITE)
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100270 FD_SET(ufd->fd, writeset);
Harald Welteec8b4502010-02-20 20:34:29 +0100271
Harald Welte16886992019-03-20 10:26:39 +0100272 if (ufd->when & OSMO_FD_EXCEPT)
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100273 FD_SET(ufd->fd, exceptset);
Holger Hans Peter Freytherff206412017-03-07 14:28:38 +0100274
275 if (ufd->fd > highfd)
276 highfd = ufd->fd;
Harald Welteec8b4502010-02-20 20:34:29 +0100277 }
278
Holger Hans Peter Freytherff206412017-03-07 14:28:38 +0100279 return highfd;
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100280}
Harald Welteec8b4502010-02-20 20:34:29 +0100281
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100282inline int osmo_fd_disp_fds(void *_rset, void *_wset, void *_eset)
283{
284 struct osmo_fd *ufd, *tmp;
285 int work = 0;
286 fd_set *readset = _rset, *writeset = _wset, *exceptset = _eset;
Harald Welteec8b4502010-02-20 20:34:29 +0100287
Harald Welteec8b4502010-02-20 20:34:29 +0100288restart:
289 unregistered_count = 0;
Pablo Neira Ayusof7f89d02011-05-07 12:42:40 +0200290 llist_for_each_entry_safe(ufd, tmp, &osmo_fds, list) {
Harald Welteec8b4502010-02-20 20:34:29 +0100291 int flags = 0;
292
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100293 if (FD_ISSET(ufd->fd, readset)) {
Harald Welte16886992019-03-20 10:26:39 +0100294 flags |= OSMO_FD_READ;
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100295 FD_CLR(ufd->fd, readset);
Harald Welteec8b4502010-02-20 20:34:29 +0100296 }
297
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100298 if (FD_ISSET(ufd->fd, writeset)) {
Harald Welte16886992019-03-20 10:26:39 +0100299 flags |= OSMO_FD_WRITE;
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100300 FD_CLR(ufd->fd, writeset);
Harald Welteec8b4502010-02-20 20:34:29 +0100301 }
302
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100303 if (FD_ISSET(ufd->fd, exceptset)) {
Harald Welte16886992019-03-20 10:26:39 +0100304 flags |= OSMO_FD_EXCEPT;
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100305 FD_CLR(ufd->fd, exceptset);
Harald Welteec8b4502010-02-20 20:34:29 +0100306 }
307
308 if (flags) {
309 work = 1;
Harald Welte52a83752019-02-21 16:37:10 +0100310 /* make sure to clear any log context before processing the next incoming message
311 * as part of some file descriptor callback. This effectively prevents "context
312 * leaking" from processing of one message into processing of the next message as part
313 * of one iteration through the list of file descriptors here. See OS#3813 */
314 log_reset_context();
Harald Welteec8b4502010-02-20 20:34:29 +0100315 ufd->cb(ufd, flags);
316 }
Holger Hans Peter Freyther92e1e702014-04-09 17:24:00 +0200317 /* ugly, ugly hack. If more than one filedescriptor was
Harald Welteec8b4502010-02-20 20:34:29 +0100318 * unregistered, they might have been consecutive and
319 * llist_for_each_entry_safe() is no longer safe */
Holger Hans Peter Freyther23ba4742010-04-11 17:33:19 +0200320 /* this seems to happen with the last element of the list as well */
321 if (unregistered_count >= 1)
Harald Welteec8b4502010-02-20 20:34:29 +0100322 goto restart;
323 }
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100324
Harald Welteec8b4502010-02-20 20:34:29 +0100325 return work;
326}
327
Harald Welteb904e422020-10-18 21:24:13 +0200328
329#ifndef FORCE_IO_SELECT
330/* fill g_poll.poll and return the number of entries filled */
331static unsigned int poll_fill_fds(void)
332{
333 struct osmo_fd *ufd;
334 unsigned int i = 0;
335
336 llist_for_each_entry(ufd, &osmo_fds, list) {
337 struct pollfd *p;
338
339 if (!ufd->when)
340 continue;
341
342 p = &g_poll.poll[i++];
343
344 p->fd = ufd->fd;
345 p->events = 0;
346 p->revents = 0;
347
348 /* use the same mapping as the Linux kernel does in fs/select.c */
349 if (ufd->when & OSMO_FD_READ)
350 p->events |= POLLIN | POLLHUP | POLLERR;
351
352 if (ufd->when & OSMO_FD_WRITE)
353 p->events |= POLLOUT | POLLERR;
354
355 if (ufd->when & OSMO_FD_EXCEPT)
356 p->events |= POLLPRI;
357
358 }
359
360 return i;
361}
362
363/* iterate over first n_fd entries of g_poll.poll + dispatch */
Harald Welte0b08d512022-01-09 12:03:12 +0100364static int poll_disp_fds(unsigned int n_fd)
Harald Welteb904e422020-10-18 21:24:13 +0200365{
366 struct osmo_fd *ufd;
367 unsigned int i;
368 int work = 0;
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200369 int shutdown_pending_writes = 0;
Harald Welteb904e422020-10-18 21:24:13 +0200370
371 for (i = 0; i < n_fd; i++) {
372 struct pollfd *p = &g_poll.poll[i];
373 int flags = 0;
374
375 if (!p->revents)
376 continue;
377
378 ufd = osmo_fd_get_by_fd(p->fd);
379 if (!ufd) {
380 /* FD might have been unregistered meanwhile */
381 continue;
382 }
383 /* use the same mapping as the Linux kernel does in fs/select.c */
384 if (p->revents & (POLLIN | POLLHUP | POLLERR))
385 flags |= OSMO_FD_READ;
386 if (p->revents & (POLLOUT | POLLERR))
387 flags |= OSMO_FD_WRITE;
388 if (p->revents & POLLPRI)
389 flags |= OSMO_FD_EXCEPT;
390
391 /* make sure we never report more than the user requested */
392 flags &= ufd->when;
393
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200394 if (_osmo_select_shutdown_requested > 0) {
395 if (ufd->when & OSMO_FD_WRITE)
396 shutdown_pending_writes++;
397 }
398
Harald Welteb904e422020-10-18 21:24:13 +0200399 if (flags) {
400 work = 1;
401 /* make sure to clear any log context before processing the next incoming message
402 * as part of some file descriptor callback. This effectively prevents "context
403 * leaking" from processing of one message into processing of the next message as part
404 * of one iteration through the list of file descriptors here. See OS#3813 */
405 log_reset_context();
406 ufd->cb(ufd, flags);
407 }
408 }
409
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200410 if (_osmo_select_shutdown_requested > 0 && !shutdown_pending_writes)
411 _osmo_select_shutdown_done = true;
412
Harald Welteb904e422020-10-18 21:24:13 +0200413 return work;
414}
415
416static int _osmo_select_main(int polling)
417{
418 unsigned int n_poll;
419 int rc;
Oliver Smithd841bec2021-12-21 19:17:51 +0100420 int timeout = 0;
Harald Welteb904e422020-10-18 21:24:13 +0200421
422 /* prepare read and write fdsets */
423 n_poll = poll_fill_fds();
424
Oliver Smithd841bec2021-12-21 19:17:51 +0100425 if (!polling) {
Harald Welteb904e422020-10-18 21:24:13 +0200426 osmo_timers_prepare();
Oliver Smithd841bec2021-12-21 19:17:51 +0100427 timeout = osmo_timers_nearest_ms();
Harald Welteb904e422020-10-18 21:24:13 +0200428
Oliver Smithd841bec2021-12-21 19:17:51 +0100429 if (_osmo_select_shutdown_requested && timeout == -1)
430 timeout = 0;
431 }
432
433 rc = poll(g_poll.poll, n_poll, timeout);
Harald Welteb904e422020-10-18 21:24:13 +0200434 if (rc < 0)
435 return 0;
436
437 /* fire timers */
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200438 if (!_osmo_select_shutdown_requested)
439 osmo_timers_update();
Harald Welteb904e422020-10-18 21:24:13 +0200440
441 OSMO_ASSERT(osmo_ctx->select);
442
443 /* call registered callback functions */
444 return poll_disp_fds(n_poll);
445}
446#else /* FORCE_IO_SELECT */
447/* the old implementation based on select, used 2008-2020 */
Harald Welte2d906112019-03-18 17:17:43 +0100448static int _osmo_select_main(int polling)
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100449{
450 fd_set readset, writeset, exceptset;
451 int rc;
452 struct timeval no_time = {0, 0};
453
454 FD_ZERO(&readset);
455 FD_ZERO(&writeset);
456 FD_ZERO(&exceptset);
457
458 /* prepare read and write fdsets */
459 osmo_fd_fill_fds(&readset, &writeset, &exceptset);
460
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100461 if (!polling)
462 osmo_timers_prepare();
463 rc = select(maxfd+1, &readset, &writeset, &exceptset, polling ? &no_time : osmo_timers_nearest());
464 if (rc < 0)
465 return 0;
466
467 /* fire timers */
468 osmo_timers_update();
469
Harald Welte2d906112019-03-18 17:17:43 +0100470 OSMO_ASSERT(osmo_ctx->select);
471
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100472 /* call registered callback functions */
473 return osmo_fd_disp_fds(&readset, &writeset, &exceptset);
474}
Harald Welteb904e422020-10-18 21:24:13 +0200475#endif /* FORCE_IO_SELECT */
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100476
Harald Welte2d906112019-03-18 17:17:43 +0100477/*! select main loop integration
478 * \param[in] polling should we pollonly (1) or block on select (0)
479 * \returns 0 if no fd handled; 1 if fd handled; negative in case of error
480 */
481int osmo_select_main(int polling)
482{
483 int rc = _osmo_select_main(polling);
484#ifndef EMBEDDED
485 if (talloc_total_size(osmo_ctx->select) != 0) {
486 osmo_panic("You cannot use the 'select' volatile "
487 "context if you don't use osmo_select_main_ctx()!\n");
488 }
489#endif
490 return rc;
491}
492
493#ifndef EMBEDDED
494/*! select main loop integration with temporary select-dispatch talloc context
495 * \param[in] polling should we pollonly (1) or block on select (0)
496 * \returns 0 if no fd handled; 1 if fd handled; negative in case of error
497 */
498int osmo_select_main_ctx(int polling)
499{
500 int rc = _osmo_select_main(polling);
501 /* free all the children of the volatile 'select' scope context */
502 talloc_free_children(osmo_ctx->select);
503 return rc;
504}
505#endif
506
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200507/*! find an osmo_fd based on the integer fd
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200508 * \param[in] fd file descriptor to use as search key
509 * \returns \ref osmo_fd for \ref fd; NULL in case it doesn't exist */
Harald Welte6c33ae22016-03-19 21:17:58 +0100510struct osmo_fd *osmo_fd_get_by_fd(int fd)
511{
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100512 if (fd > maxfd)
513 return NULL;
514 return osmo_fd_lookup.table[fd];
Harald Welte6c33ae22016-03-19 21:17:58 +0100515}
516
Harald Welte7a010b12019-04-06 13:46:40 +0200517/*! initialize the osmocom select abstraction for the current thread */
518void osmo_select_init(void)
519{
520 INIT_LLIST_HEAD(&osmo_fds);
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100521 osmo_fd_lookup_table_extend(0);
Harald Welte7a010b12019-04-06 13:46:40 +0200522}
523
524/* ensure main thread always has pre-initialized osmo_fds */
525static __attribute__((constructor)) void on_dso_load_select(void)
526{
527 osmo_select_init();
528}
529
Harald Welteea4d8932017-12-03 16:13:39 +0100530#ifdef HAVE_SYS_TIMERFD_H
531#include <sys/timerfd.h>
532
533/*! disable the osmocom-wrapped timerfd */
534int osmo_timerfd_disable(struct osmo_fd *ofd)
535{
536 const struct itimerspec its_null = {
537 .it_value = { 0, 0 },
538 .it_interval = { 0, 0 },
539 };
540 return timerfd_settime(ofd->fd, 0, &its_null, NULL);
541}
542
Alexander Chemerise8ec2142020-05-09 01:57:16 +0300543/*! schedule the osmocom-wrapped timerfd to occur first at \a first, then periodically at \a interval
Harald Welteea4d8932017-12-03 16:13:39 +0100544 * \param[in] ofd Osmocom wrapped timerfd
545 * \param[in] first Relative time at which the timer should first execute (NULL = \a interval)
546 * \param[in] interval Time interval at which subsequent timer shall fire
547 * \returns 0 on success; negative on error */
548int osmo_timerfd_schedule(struct osmo_fd *ofd, const struct timespec *first,
549 const struct timespec *interval)
550{
551 struct itimerspec its;
552
553 if (ofd->fd < 0)
554 return -EINVAL;
555
556 /* first expiration */
557 if (first)
558 its.it_value = *first;
559 else
560 its.it_value = *interval;
561 /* repeating interval */
562 its.it_interval = *interval;
563
564 return timerfd_settime(ofd->fd, 0, &its, NULL);
565}
566
567/*! setup osmocom-wrapped timerfd
568 * \param[inout] ofd Osmocom-wrapped timerfd on which to operate
569 * \param[in] cb Call-back function called when timerfd becomes readable
570 * \param[in] data Opaque data to be passed on to call-back
571 * \returns 0 on success; negative on error
572 *
573 * We simply initialize the data structures here, but do not yet
574 * schedule the timer.
575 */
576int osmo_timerfd_setup(struct osmo_fd *ofd, int (*cb)(struct osmo_fd *, unsigned int), void *data)
577{
578 ofd->cb = cb;
579 ofd->data = data;
Harald Welte16886992019-03-20 10:26:39 +0100580 ofd->when = OSMO_FD_READ;
Harald Welteea4d8932017-12-03 16:13:39 +0100581
582 if (ofd->fd < 0) {
Harald Welte37608f92018-10-21 12:32:55 +0200583 int rc;
584
Harald Welteea4d8932017-12-03 16:13:39 +0100585 ofd->fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
586 if (ofd->fd < 0)
587 return ofd->fd;
588
Harald Welte37608f92018-10-21 12:32:55 +0200589 rc = osmo_fd_register(ofd);
590 if (rc < 0) {
Harald Welte100e44e2020-04-18 21:16:43 +0200591 osmo_fd_unregister(ofd);
Harald Welte37608f92018-10-21 12:32:55 +0200592 close(ofd->fd);
593 ofd->fd = -1;
594 return rc;
595 }
Harald Welteea4d8932017-12-03 16:13:39 +0100596 }
597 return 0;
598}
599
600#endif /* HAVE_SYS_TIMERFD_H */
601
Harald Weltea70ac852020-04-17 19:20:01 +0200602#ifdef HAVE_SYS_SIGNALFD_H
603#include <sys/signalfd.h>
604
605static int signalfd_callback(struct osmo_fd *ofd, unsigned int what)
606{
607 struct osmo_signalfd *osfd = ofd->data;
608 struct signalfd_siginfo fdsi;
609 int rc;
610
611 rc = read(ofd->fd, &fdsi, sizeof(fdsi));
612 if (rc < 0) {
613 osmo_fd_unregister(ofd);
614 close(ofd->fd);
615 ofd->fd = -1;
616 return rc;
617 }
618
619 osfd->cb(osfd, &fdsi);
620
621 return 0;
622};
623
624/*! create a signalfd and register it with osmocom select loop.
625 * \param[in] ctx talloc context from which osmo_signalfd is to be allocated
626 * \param[in] set of signals to be accept via this file descriptor
627 * \param[in] cb call-back function to be called for each arriving signal
628 * \param[in] data opaque user-provided data to pass to callback
629 * \returns pointer to newly-allocated + registered osmo_signalfd; NULL on error */
630struct osmo_signalfd *
631osmo_signalfd_setup(void *ctx, sigset_t set, osmo_signalfd_cb *cb, void *data)
632{
633 struct osmo_signalfd *osfd = talloc_size(ctx, sizeof(*osfd));
634 int fd, rc;
635
636 if (!osfd)
637 return NULL;
638
639 osfd->data = data;
640 osfd->sigset = set;
641 osfd->cb = cb;
642
643 fd = signalfd(-1, &osfd->sigset, SFD_NONBLOCK);
644 if (fd < 0) {
645 talloc_free(osfd);
646 return NULL;
647 }
648
649 osmo_fd_setup(&osfd->ofd, fd, OSMO_FD_READ, signalfd_callback, osfd, 0);
650 rc = osmo_fd_register(&osfd->ofd);
651 if (rc < 0) {
652 close(fd);
653 talloc_free(osfd);
654 return NULL;
655 }
656
657 return osfd;
658}
659
660#endif /* HAVE_SYS_SIGNALFD_H */
Harald Welteea4d8932017-12-03 16:13:39 +0100661
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200662/*! Request osmo_select_* to only service pending OSMO_FD_WRITE requests. Once all writes are done,
663 * osmo_select_shutdown_done() returns true. This allows for example to send all outbound packets before terminating the
664 * process.
665 *
666 * Usage example:
667 *
668 * static void signal_handler(int signum)
669 * {
670 * fprintf(stdout, "signal %u received\n", signum);
671 *
672 * switch (signum) {
673 * case SIGINT:
674 * case SIGTERM:
675 * // If the user hits Ctrl-C the third time, just terminate immediately.
676 * if (osmo_select_shutdown_requested() >= 2)
677 * exit(-1);
678 * // Request write-only mode in osmo_select_main_ctx()
679 * osmo_select_shutdown_request();
680 * break;
681 * [...]
682 * }
683 *
684 * main()
685 * {
686 * signal(SIGINT, &signal_handler);
687 * signal(SIGTERM, &signal_handler);
688 *
689 * [...]
690 *
691 * // After the signal_handler issued osmo_select_shutdown_request(), osmo_select_shutdown_done() returns true
692 * // as soon as all write queues are empty.
693 * while (!osmo_select_shutdown_done()) {
694 * osmo_select_main_ctx(0);
695 * }
696 * }
697 */
Harald Weltee61d4592022-11-03 11:05:58 +0100698void osmo_select_shutdown_request(void)
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200699{
700 _osmo_select_shutdown_requested++;
701};
702
703/*! Return the number of times osmo_select_shutdown_request() was called before. */
Harald Weltee61d4592022-11-03 11:05:58 +0100704int osmo_select_shutdown_requested(void)
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200705{
706 return _osmo_select_shutdown_requested;
707};
708
709/*! Return true after osmo_select_shutdown_requested() was called, and after an osmo_select poll loop found no more
710 * pending OSMO_FD_WRITE on any registered socket. */
Harald Weltee61d4592022-11-03 11:05:58 +0100711bool osmo_select_shutdown_done(void) {
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200712 return _osmo_select_shutdown_done;
713};
714
Sylvain Munautdca7d2c2012-04-18 21:53:23 +0200715/*! @} */
Harald Welteba6988b2011-08-17 12:46:48 +0200716
Harald Welteec8b4502010-02-20 20:34:29 +0100717#endif /* _HAVE_SYS_SELECT_H */