blob: 67b0fd38c360d8a8f655d391bb71c6f9f72fdaec [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 *
Pau Espin Pedrol25729cf2023-03-14 12:06:27 +0100215 * Caller is responsible for ensuring the fd is really registered before calling this API.
Pau Espin Pedrol153519f2023-03-14 12:01:37 +0100216 * This function must be called before changing the value of the fd field in
217 * the struct osmo_fd.
Harald Welteba6988b2011-08-17 12:46:48 +0200218 */
Pablo Neira Ayusof7f89d02011-05-07 12:42:40 +0200219void osmo_fd_unregister(struct osmo_fd *fd)
Harald Welteec8b4502010-02-20 20:34:29 +0100220{
Philipp Maierb2888532016-12-09 14:07:18 +0100221 /* Note: when fd is inside the osmo_fds list (not registered before)
222 * this function will crash! If in doubt, check file descriptor with
223 * osmo_fd_is_registered() */
Harald Welteec8b4502010-02-20 20:34:29 +0100224 unregistered_count++;
225 llist_del(&fd->list);
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100226 OSMO_ASSERT(fd->fd >= 0);
227 OSMO_ASSERT(fd->fd <= maxfd);
228 osmo_fd_lookup.table[fd->fd] = NULL;
Harald Welteb904e422020-10-18 21:24:13 +0200229#ifndef FORCE_IO_SELECT
230 g_poll.num_registered--;
231#endif /* FORCE_IO_SELECT */
Philipp Maierb1ef8f52021-12-06 16:31:02 +0100232
233 /* If existent, free any statistical data */
234 osmo_stats_tcp_osmo_fd_unregister(fd);
Harald Welteec8b4502010-02-20 20:34:29 +0100235}
236
Harald Welteea91a512017-07-13 14:28:30 +0200237/*! Close a file descriptor, mark it as closed + unregister from select loop abstraction
238 * \param[in] fd osmocom file descriptor to be unregistered + closed
239 *
240 * If \a fd is registered, we unregister it from the select() loop
241 * abstraction. We then close the fd and set it to -1, as well as
242 * unsetting any 'when' flags */
243void osmo_fd_close(struct osmo_fd *fd)
244{
245 if (osmo_fd_is_registered(fd))
246 osmo_fd_unregister(fd);
247 if (fd->fd != -1)
248 close(fd->fd);
249 fd->fd = -1;
250 fd->when = 0;
251}
252
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200253/*! Populate the fd_sets and return the highest fd number
Holger Hans Peter Freytherff206412017-03-07 14:28:38 +0100254 * \param[in] _rset The readfds to populate
255 * \param[in] _wset The wrtiefds to populate
256 * \param[in] _eset The errorfds to populate
257 *
258 * \returns The highest file descriptor seen or 0 on an empty list
259 */
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100260inline int osmo_fd_fill_fds(void *_rset, void *_wset, void *_eset)
Harald Welteec8b4502010-02-20 20:34:29 +0100261{
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100262 fd_set *readset = _rset, *writeset = _wset, *exceptset = _eset;
263 struct osmo_fd *ufd;
Holger Hans Peter Freytherff206412017-03-07 14:28:38 +0100264 int highfd = 0;
Harald Welteec8b4502010-02-20 20:34:29 +0100265
Pablo Neira Ayusof7f89d02011-05-07 12:42:40 +0200266 llist_for_each_entry(ufd, &osmo_fds, list) {
Harald Welte16886992019-03-20 10:26:39 +0100267 if (ufd->when & OSMO_FD_READ)
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100268 FD_SET(ufd->fd, readset);
Harald Welteec8b4502010-02-20 20:34:29 +0100269
Harald Welte16886992019-03-20 10:26:39 +0100270 if (ufd->when & OSMO_FD_WRITE)
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100271 FD_SET(ufd->fd, writeset);
Harald Welteec8b4502010-02-20 20:34:29 +0100272
Harald Welte16886992019-03-20 10:26:39 +0100273 if (ufd->when & OSMO_FD_EXCEPT)
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100274 FD_SET(ufd->fd, exceptset);
Holger Hans Peter Freytherff206412017-03-07 14:28:38 +0100275
276 if (ufd->fd > highfd)
277 highfd = ufd->fd;
Harald Welteec8b4502010-02-20 20:34:29 +0100278 }
279
Holger Hans Peter Freytherff206412017-03-07 14:28:38 +0100280 return highfd;
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100281}
Harald Welteec8b4502010-02-20 20:34:29 +0100282
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100283inline int osmo_fd_disp_fds(void *_rset, void *_wset, void *_eset)
284{
285 struct osmo_fd *ufd, *tmp;
286 int work = 0;
287 fd_set *readset = _rset, *writeset = _wset, *exceptset = _eset;
Harald Welteec8b4502010-02-20 20:34:29 +0100288
Harald Welteec8b4502010-02-20 20:34:29 +0100289restart:
290 unregistered_count = 0;
Pablo Neira Ayusof7f89d02011-05-07 12:42:40 +0200291 llist_for_each_entry_safe(ufd, tmp, &osmo_fds, list) {
Harald Welteec8b4502010-02-20 20:34:29 +0100292 int flags = 0;
293
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100294 if (FD_ISSET(ufd->fd, readset)) {
Harald Welte16886992019-03-20 10:26:39 +0100295 flags |= OSMO_FD_READ;
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100296 FD_CLR(ufd->fd, readset);
Harald Welteec8b4502010-02-20 20:34:29 +0100297 }
298
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100299 if (FD_ISSET(ufd->fd, writeset)) {
Harald Welte16886992019-03-20 10:26:39 +0100300 flags |= OSMO_FD_WRITE;
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100301 FD_CLR(ufd->fd, writeset);
Harald Welteec8b4502010-02-20 20:34:29 +0100302 }
303
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100304 if (FD_ISSET(ufd->fd, exceptset)) {
Harald Welte16886992019-03-20 10:26:39 +0100305 flags |= OSMO_FD_EXCEPT;
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100306 FD_CLR(ufd->fd, exceptset);
Harald Welteec8b4502010-02-20 20:34:29 +0100307 }
308
309 if (flags) {
310 work = 1;
Harald Welte52a83752019-02-21 16:37:10 +0100311 /* make sure to clear any log context before processing the next incoming message
312 * as part of some file descriptor callback. This effectively prevents "context
313 * leaking" from processing of one message into processing of the next message as part
314 * of one iteration through the list of file descriptors here. See OS#3813 */
315 log_reset_context();
Harald Welteec8b4502010-02-20 20:34:29 +0100316 ufd->cb(ufd, flags);
317 }
Holger Hans Peter Freyther92e1e702014-04-09 17:24:00 +0200318 /* ugly, ugly hack. If more than one filedescriptor was
Harald Welteec8b4502010-02-20 20:34:29 +0100319 * unregistered, they might have been consecutive and
320 * llist_for_each_entry_safe() is no longer safe */
Holger Hans Peter Freyther23ba4742010-04-11 17:33:19 +0200321 /* this seems to happen with the last element of the list as well */
322 if (unregistered_count >= 1)
Harald Welteec8b4502010-02-20 20:34:29 +0100323 goto restart;
324 }
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100325
Harald Welteec8b4502010-02-20 20:34:29 +0100326 return work;
327}
328
Harald Welteb904e422020-10-18 21:24:13 +0200329
330#ifndef FORCE_IO_SELECT
331/* fill g_poll.poll and return the number of entries filled */
332static unsigned int poll_fill_fds(void)
333{
334 struct osmo_fd *ufd;
335 unsigned int i = 0;
336
337 llist_for_each_entry(ufd, &osmo_fds, list) {
338 struct pollfd *p;
339
340 if (!ufd->when)
341 continue;
342
343 p = &g_poll.poll[i++];
344
345 p->fd = ufd->fd;
346 p->events = 0;
347 p->revents = 0;
348
349 /* use the same mapping as the Linux kernel does in fs/select.c */
350 if (ufd->when & OSMO_FD_READ)
351 p->events |= POLLIN | POLLHUP | POLLERR;
352
353 if (ufd->when & OSMO_FD_WRITE)
354 p->events |= POLLOUT | POLLERR;
355
356 if (ufd->when & OSMO_FD_EXCEPT)
357 p->events |= POLLPRI;
358
359 }
360
361 return i;
362}
363
364/* iterate over first n_fd entries of g_poll.poll + dispatch */
Harald Welte0b08d512022-01-09 12:03:12 +0100365static int poll_disp_fds(unsigned int n_fd)
Harald Welteb904e422020-10-18 21:24:13 +0200366{
367 struct osmo_fd *ufd;
368 unsigned int i;
369 int work = 0;
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200370 int shutdown_pending_writes = 0;
Harald Welteb904e422020-10-18 21:24:13 +0200371
372 for (i = 0; i < n_fd; i++) {
373 struct pollfd *p = &g_poll.poll[i];
374 int flags = 0;
375
376 if (!p->revents)
377 continue;
378
379 ufd = osmo_fd_get_by_fd(p->fd);
380 if (!ufd) {
381 /* FD might have been unregistered meanwhile */
382 continue;
383 }
384 /* use the same mapping as the Linux kernel does in fs/select.c */
385 if (p->revents & (POLLIN | POLLHUP | POLLERR))
386 flags |= OSMO_FD_READ;
387 if (p->revents & (POLLOUT | POLLERR))
388 flags |= OSMO_FD_WRITE;
389 if (p->revents & POLLPRI)
390 flags |= OSMO_FD_EXCEPT;
391
392 /* make sure we never report more than the user requested */
393 flags &= ufd->when;
394
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200395 if (_osmo_select_shutdown_requested > 0) {
396 if (ufd->when & OSMO_FD_WRITE)
397 shutdown_pending_writes++;
398 }
399
Harald Welteb904e422020-10-18 21:24:13 +0200400 if (flags) {
401 work = 1;
402 /* make sure to clear any log context before processing the next incoming message
403 * as part of some file descriptor callback. This effectively prevents "context
404 * leaking" from processing of one message into processing of the next message as part
405 * of one iteration through the list of file descriptors here. See OS#3813 */
406 log_reset_context();
407 ufd->cb(ufd, flags);
408 }
409 }
410
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200411 if (_osmo_select_shutdown_requested > 0 && !shutdown_pending_writes)
412 _osmo_select_shutdown_done = true;
413
Harald Welteb904e422020-10-18 21:24:13 +0200414 return work;
415}
416
417static int _osmo_select_main(int polling)
418{
419 unsigned int n_poll;
420 int rc;
Oliver Smithd841bec2021-12-21 19:17:51 +0100421 int timeout = 0;
Harald Welteb904e422020-10-18 21:24:13 +0200422
423 /* prepare read and write fdsets */
424 n_poll = poll_fill_fds();
425
Oliver Smithd841bec2021-12-21 19:17:51 +0100426 if (!polling) {
Harald Welteb904e422020-10-18 21:24:13 +0200427 osmo_timers_prepare();
Oliver Smithd841bec2021-12-21 19:17:51 +0100428 timeout = osmo_timers_nearest_ms();
Harald Welteb904e422020-10-18 21:24:13 +0200429
Oliver Smithd841bec2021-12-21 19:17:51 +0100430 if (_osmo_select_shutdown_requested && timeout == -1)
431 timeout = 0;
432 }
433
434 rc = poll(g_poll.poll, n_poll, timeout);
Harald Welteb904e422020-10-18 21:24:13 +0200435 if (rc < 0)
436 return 0;
437
438 /* fire timers */
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200439 if (!_osmo_select_shutdown_requested)
440 osmo_timers_update();
Harald Welteb904e422020-10-18 21:24:13 +0200441
442 OSMO_ASSERT(osmo_ctx->select);
443
444 /* call registered callback functions */
445 return poll_disp_fds(n_poll);
446}
447#else /* FORCE_IO_SELECT */
448/* the old implementation based on select, used 2008-2020 */
Harald Welte2d906112019-03-18 17:17:43 +0100449static int _osmo_select_main(int polling)
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100450{
451 fd_set readset, writeset, exceptset;
452 int rc;
453 struct timeval no_time = {0, 0};
454
455 FD_ZERO(&readset);
456 FD_ZERO(&writeset);
457 FD_ZERO(&exceptset);
458
459 /* prepare read and write fdsets */
460 osmo_fd_fill_fds(&readset, &writeset, &exceptset);
461
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100462 if (!polling)
463 osmo_timers_prepare();
464 rc = select(maxfd+1, &readset, &writeset, &exceptset, polling ? &no_time : osmo_timers_nearest());
465 if (rc < 0)
466 return 0;
467
468 /* fire timers */
469 osmo_timers_update();
470
Harald Welte2d906112019-03-18 17:17:43 +0100471 OSMO_ASSERT(osmo_ctx->select);
472
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100473 /* call registered callback functions */
474 return osmo_fd_disp_fds(&readset, &writeset, &exceptset);
475}
Harald Welteb904e422020-10-18 21:24:13 +0200476#endif /* FORCE_IO_SELECT */
Holger Hans Peter Freyther61f28882016-03-21 09:55:05 +0100477
Harald Welte2d906112019-03-18 17:17:43 +0100478/*! select main loop integration
479 * \param[in] polling should we pollonly (1) or block on select (0)
480 * \returns 0 if no fd handled; 1 if fd handled; negative in case of error
481 */
482int osmo_select_main(int polling)
483{
484 int rc = _osmo_select_main(polling);
485#ifndef EMBEDDED
486 if (talloc_total_size(osmo_ctx->select) != 0) {
487 osmo_panic("You cannot use the 'select' volatile "
488 "context if you don't use osmo_select_main_ctx()!\n");
489 }
490#endif
491 return rc;
492}
493
494#ifndef EMBEDDED
495/*! select main loop integration with temporary select-dispatch talloc context
496 * \param[in] polling should we pollonly (1) or block on select (0)
497 * \returns 0 if no fd handled; 1 if fd handled; negative in case of error
498 */
499int osmo_select_main_ctx(int polling)
500{
501 int rc = _osmo_select_main(polling);
502 /* free all the children of the volatile 'select' scope context */
503 talloc_free_children(osmo_ctx->select);
504 return rc;
505}
506#endif
507
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200508/*! find an osmo_fd based on the integer fd
Harald Welte2d2e2cc2016-04-25 12:11:20 +0200509 * \param[in] fd file descriptor to use as search key
510 * \returns \ref osmo_fd for \ref fd; NULL in case it doesn't exist */
Harald Welte6c33ae22016-03-19 21:17:58 +0100511struct osmo_fd *osmo_fd_get_by_fd(int fd)
512{
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100513 if (fd > maxfd)
514 return NULL;
515 return osmo_fd_lookup.table[fd];
Harald Welte6c33ae22016-03-19 21:17:58 +0100516}
517
Harald Welte7a010b12019-04-06 13:46:40 +0200518/*! initialize the osmocom select abstraction for the current thread */
519void osmo_select_init(void)
520{
521 INIT_LLIST_HEAD(&osmo_fds);
Pau Espin Pedrolc46a15d2023-03-09 17:37:15 +0100522 osmo_fd_lookup_table_extend(0);
Harald Welte7a010b12019-04-06 13:46:40 +0200523}
524
525/* ensure main thread always has pre-initialized osmo_fds */
526static __attribute__((constructor)) void on_dso_load_select(void)
527{
528 osmo_select_init();
529}
530
Harald Welteea4d8932017-12-03 16:13:39 +0100531#ifdef HAVE_SYS_TIMERFD_H
532#include <sys/timerfd.h>
533
534/*! disable the osmocom-wrapped timerfd */
535int osmo_timerfd_disable(struct osmo_fd *ofd)
536{
537 const struct itimerspec its_null = {
538 .it_value = { 0, 0 },
539 .it_interval = { 0, 0 },
540 };
541 return timerfd_settime(ofd->fd, 0, &its_null, NULL);
542}
543
Alexander Chemerise8ec2142020-05-09 01:57:16 +0300544/*! schedule the osmocom-wrapped timerfd to occur first at \a first, then periodically at \a interval
Harald Welteea4d8932017-12-03 16:13:39 +0100545 * \param[in] ofd Osmocom wrapped timerfd
546 * \param[in] first Relative time at which the timer should first execute (NULL = \a interval)
547 * \param[in] interval Time interval at which subsequent timer shall fire
548 * \returns 0 on success; negative on error */
549int osmo_timerfd_schedule(struct osmo_fd *ofd, const struct timespec *first,
550 const struct timespec *interval)
551{
552 struct itimerspec its;
553
554 if (ofd->fd < 0)
555 return -EINVAL;
556
557 /* first expiration */
558 if (first)
559 its.it_value = *first;
560 else
561 its.it_value = *interval;
562 /* repeating interval */
563 its.it_interval = *interval;
564
565 return timerfd_settime(ofd->fd, 0, &its, NULL);
566}
567
568/*! setup osmocom-wrapped timerfd
569 * \param[inout] ofd Osmocom-wrapped timerfd on which to operate
570 * \param[in] cb Call-back function called when timerfd becomes readable
571 * \param[in] data Opaque data to be passed on to call-back
572 * \returns 0 on success; negative on error
573 *
574 * We simply initialize the data structures here, but do not yet
575 * schedule the timer.
576 */
577int osmo_timerfd_setup(struct osmo_fd *ofd, int (*cb)(struct osmo_fd *, unsigned int), void *data)
578{
579 ofd->cb = cb;
580 ofd->data = data;
Harald Welte16886992019-03-20 10:26:39 +0100581 ofd->when = OSMO_FD_READ;
Harald Welteea4d8932017-12-03 16:13:39 +0100582
583 if (ofd->fd < 0) {
Harald Welte37608f92018-10-21 12:32:55 +0200584 int rc;
585
Harald Welteea4d8932017-12-03 16:13:39 +0100586 ofd->fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
587 if (ofd->fd < 0)
588 return ofd->fd;
589
Harald Welte37608f92018-10-21 12:32:55 +0200590 rc = osmo_fd_register(ofd);
591 if (rc < 0) {
Harald Welte100e44e2020-04-18 21:16:43 +0200592 osmo_fd_unregister(ofd);
Harald Welte37608f92018-10-21 12:32:55 +0200593 close(ofd->fd);
594 ofd->fd = -1;
595 return rc;
596 }
Harald Welteea4d8932017-12-03 16:13:39 +0100597 }
598 return 0;
599}
600
601#endif /* HAVE_SYS_TIMERFD_H */
602
Harald Weltea70ac852020-04-17 19:20:01 +0200603#ifdef HAVE_SYS_SIGNALFD_H
604#include <sys/signalfd.h>
605
606static int signalfd_callback(struct osmo_fd *ofd, unsigned int what)
607{
608 struct osmo_signalfd *osfd = ofd->data;
609 struct signalfd_siginfo fdsi;
610 int rc;
611
612 rc = read(ofd->fd, &fdsi, sizeof(fdsi));
613 if (rc < 0) {
614 osmo_fd_unregister(ofd);
615 close(ofd->fd);
616 ofd->fd = -1;
617 return rc;
618 }
619
620 osfd->cb(osfd, &fdsi);
621
622 return 0;
623};
624
625/*! create a signalfd and register it with osmocom select loop.
626 * \param[in] ctx talloc context from which osmo_signalfd is to be allocated
627 * \param[in] set of signals to be accept via this file descriptor
628 * \param[in] cb call-back function to be called for each arriving signal
629 * \param[in] data opaque user-provided data to pass to callback
630 * \returns pointer to newly-allocated + registered osmo_signalfd; NULL on error */
631struct osmo_signalfd *
632osmo_signalfd_setup(void *ctx, sigset_t set, osmo_signalfd_cb *cb, void *data)
633{
634 struct osmo_signalfd *osfd = talloc_size(ctx, sizeof(*osfd));
635 int fd, rc;
636
637 if (!osfd)
638 return NULL;
639
640 osfd->data = data;
641 osfd->sigset = set;
642 osfd->cb = cb;
643
644 fd = signalfd(-1, &osfd->sigset, SFD_NONBLOCK);
645 if (fd < 0) {
646 talloc_free(osfd);
647 return NULL;
648 }
649
650 osmo_fd_setup(&osfd->ofd, fd, OSMO_FD_READ, signalfd_callback, osfd, 0);
651 rc = osmo_fd_register(&osfd->ofd);
652 if (rc < 0) {
653 close(fd);
654 talloc_free(osfd);
655 return NULL;
656 }
657
658 return osfd;
659}
660
661#endif /* HAVE_SYS_SIGNALFD_H */
Harald Welteea4d8932017-12-03 16:13:39 +0100662
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200663/*! Request osmo_select_* to only service pending OSMO_FD_WRITE requests. Once all writes are done,
664 * osmo_select_shutdown_done() returns true. This allows for example to send all outbound packets before terminating the
665 * process.
666 *
667 * Usage example:
668 *
669 * static void signal_handler(int signum)
670 * {
671 * fprintf(stdout, "signal %u received\n", signum);
672 *
673 * switch (signum) {
674 * case SIGINT:
675 * case SIGTERM:
676 * // If the user hits Ctrl-C the third time, just terminate immediately.
677 * if (osmo_select_shutdown_requested() >= 2)
678 * exit(-1);
679 * // Request write-only mode in osmo_select_main_ctx()
680 * osmo_select_shutdown_request();
681 * break;
682 * [...]
683 * }
684 *
685 * main()
686 * {
687 * signal(SIGINT, &signal_handler);
688 * signal(SIGTERM, &signal_handler);
689 *
690 * [...]
691 *
692 * // After the signal_handler issued osmo_select_shutdown_request(), osmo_select_shutdown_done() returns true
693 * // as soon as all write queues are empty.
694 * while (!osmo_select_shutdown_done()) {
695 * osmo_select_main_ctx(0);
696 * }
697 * }
698 */
Harald Weltee61d4592022-11-03 11:05:58 +0100699void osmo_select_shutdown_request(void)
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200700{
701 _osmo_select_shutdown_requested++;
702};
703
704/*! Return the number of times osmo_select_shutdown_request() was called before. */
Harald Weltee61d4592022-11-03 11:05:58 +0100705int osmo_select_shutdown_requested(void)
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200706{
707 return _osmo_select_shutdown_requested;
708};
709
710/*! Return true after osmo_select_shutdown_requested() was called, and after an osmo_select poll loop found no more
711 * pending OSMO_FD_WRITE on any registered socket. */
Harald Weltee61d4592022-11-03 11:05:58 +0100712bool osmo_select_shutdown_done(void) {
Neels Hofmeyrac49bda2021-06-04 16:30:04 +0200713 return _osmo_select_shutdown_done;
714};
715
Sylvain Munautdca7d2c2012-04-18 21:53:23 +0200716/*! @} */
Harald Welteba6988b2011-08-17 12:46:48 +0200717
Harald Welteec8b4502010-02-20 20:34:29 +0100718#endif /* _HAVE_SYS_SELECT_H */