blob: 9960fb419382d2e3c6c0f56cdd31dcb5775da382 [file] [log] [blame]
Harald Welte8857f3b2022-11-18 13:54:44 +01001/*! \file osmo_io.c
2 * New osmocom async I/O API.
3 *
4 * (C) 2022 by Harald Welte <laforge@osmocom.org>
5 * (C) 2022-2023 by sysmocom - s.f.m.c. GmbH <info@sysmocom.de>
6 * Author: Daniel Willmann <dwillmann@sysmocom.de>
7 *
8 * All Rights Reserved.
9 *
10 * SPDX-License-Identifier: GPL-2.0+
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * 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.
16 *
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.
21 */
22
23#include "../config.h"
24#if defined(__linux__)
25
26#include <fcntl.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <talloc.h>
30#include <unistd.h>
31#include <string.h>
32#include <stdbool.h>
33#include <errno.h>
34
35#include <osmocom/core/osmo_io.h>
36#include <osmocom/core/linuxlist.h>
37#include <osmocom/core/logging.h>
38#include <osmocom/core/msgb.h>
39#include <osmocom/core/socket.h>
40#include <osmocom/core/talloc.h>
41#include <osmocom/core/utils.h>
42
43#include "osmo_io_internal.h"
44
45/*! This environment variable can be set to manually set the backend used in osmo_io */
46#define OSMO_IO_BACKEND_ENV "LIBOSMO_IO_BACKEND"
47
48const struct value_string osmo_io_backend_names[] = {
49 { OSMO_IO_BACKEND_POLL, "poll" },
50 { 0, NULL }
51};
52
53static enum osmo_io_backend g_io_backend;
54
55/* Used by some tests, can't be static */
56struct iofd_backend_ops osmo_iofd_ops;
57
58/*! initialize osmo_io for the current thread */
59void osmo_iofd_init(void)
60{
61 switch (g_io_backend) {
62 case OSMO_IO_BACKEND_POLL:
63 break;
64 default:
65 OSMO_ASSERT(0);
66 break;
67 }
68}
69
70/* ensure main thread always has pre-initialized osmo_io
71 * priority 103: run after on_dso_load_select */
72static __attribute__((constructor(103))) void on_dso_load_osmo_io(void)
73{
74 char *backend = getenv(OSMO_IO_BACKEND_ENV);
75 if (backend == NULL)
76 backend = OSMO_IO_BACKEND_DEFAULT;
77
78 if (!strcmp("POLL", backend)) {
79 g_io_backend = OSMO_IO_BACKEND_POLL;
80 osmo_iofd_ops = iofd_poll_ops;
81 } else {
82 fprintf(stderr, "Invalid osmo_io backend requested: \"%s\"\nCheck the environment variable %s\n", backend, OSMO_IO_BACKEND_ENV);
83 exit(1);
84 }
85
86 osmo_iofd_init();
87}
88
89/*! Allocate the msghdr
90 * \param[in] iofd the osmo_io file structure
91 * \param[in] action the action this msg(hdr) is for (read, write, ..)
92 * \param[in] msg the msg buffer to use. Will allocate a new one if NULL
93 * \returns the newly allocated msghdr or NULL in case of error */
94struct iofd_msghdr *iofd_msghdr_alloc(struct osmo_io_fd *iofd, enum iofd_msg_action action, struct msgb *msg)
95{
96 struct iofd_msghdr *hdr = talloc_zero(iofd, struct iofd_msghdr);
97 if (!hdr)
98 return NULL;
99 if (!msg) {
100 msg = iofd_msgb_alloc(iofd);
101 if (!msg) {
102 talloc_free(hdr);
103 return NULL;
104 }
105 }
106
107 hdr->action = action;
108 hdr->iofd = iofd;
109 hdr->msg = msg;
110
111 return hdr;
112}
113
114/*! Free the msghdr
115 * \param[in] msghdr the msghdr to free
116 */
117void iofd_msghdr_free(struct iofd_msghdr *msghdr)
118{
119 /* msghdr->msg is never owned by msghdr, it will either be freed in the send path or
120 * or passed on to the read callback which takes ownership. */
121 talloc_free(msghdr);
122}
123
124/*! convenience wrapper to call msgb_alloc with parameters from osmo_io_fd */
125struct msgb *iofd_msgb_alloc(struct osmo_io_fd *iofd)
126{
127 uint16_t headroom = iofd->msgb_alloc.headroom;
128
129 OSMO_ASSERT(iofd->msgb_alloc.size < 0xffff - headroom);
130 return msgb_alloc_headroom_c(iofd->msgb_alloc.ctx,
131 iofd->msgb_alloc.size + headroom, headroom, iofd->name);
132}
133
134/*! return the pending msgb in iofd or NULL if there is none*/
135struct msgb *iofd_msgb_pending(struct osmo_io_fd *iofd)
136{
137 struct msgb *msg = NULL;
138
139 msg = iofd->pending;
140 iofd->pending = NULL;
141
142 return msg;
143}
144
145/*! Return the pending msgb or allocate and return a new one */
146struct msgb *iofd_msgb_pending_or_alloc(struct osmo_io_fd *iofd)
147{
148 struct msgb *msg = NULL;
149
150 msg = iofd_msgb_pending(iofd);
151 if (!msg)
152 msg = iofd_msgb_alloc(iofd);
153
154 return msg;
155}
156
157/*! Enqueue a message to be sent
158 *
159 * Enqueues the message at the back of the queue provided there is enough space.
160 * \param[in] iofd the file descriptor
161 * \param[in] msghdr the message to enqueue
162 * \returns 0 if the message was enqueued succcessfully,
163 * -ENOSPC if the queue already contains the maximum number of messages
164 */
165int iofd_txqueue_enqueue(struct osmo_io_fd *iofd, struct iofd_msghdr *msghdr)
166{
167 if (iofd->tx_queue.current_length >= iofd->tx_queue.max_length)
168 return -ENOSPC;
169
170 llist_add_tail(&msghdr->list, &iofd->tx_queue.msg_queue);
171 iofd->tx_queue.current_length++;
172
173 if (iofd->write_enabled && iofd->tx_queue.current_length == 1)
174 osmo_iofd_ops.write_enable(iofd);
175
176 return 0;
177}
178
179/*! Enqueue a message at the front
180 *
181 * Used to enqueue a msgb from a partial send again. This function will always
182 * enqueue the message, even if the maximum number of messages is reached.
183 * \param[in] iofd the file descriptor
184 * \param[in] msghdr the message to enqueue
185 */
186void iofd_txqueue_enqueue_front(struct osmo_io_fd *iofd, struct iofd_msghdr *msghdr)
187{
188 llist_add(&msghdr->list, &iofd->tx_queue.msg_queue);
189 iofd->tx_queue.current_length++;
190}
191
192/*! Dequeue a message from the front
193 *
194 * \param[in] iofd the file descriptor
195 * \returns the msghdr from the front of the queue or NULL if the queue is empty
196 */
197struct iofd_msghdr *iofd_txqueue_dequeue(struct osmo_io_fd *iofd)
198{
199 struct llist_head *lh;
200
201 if (iofd->tx_queue.current_length == 0)
202 return NULL;
203
204 lh = iofd->tx_queue.msg_queue.next;
205
206 OSMO_ASSERT(lh);
207 iofd->tx_queue.current_length--;
208 llist_del(lh);
209
210 if (iofd->tx_queue.current_length == 0)
211 osmo_iofd_ops.write_disable(iofd);
212
213 return llist_entry(lh, struct iofd_msghdr, list);
214}
215
216/*! Handle segmentation of the msg. If this function returns *_HANDLE_ONE or MORE then the data in msg will contain
217 * one complete message.
218 * If there are bytes left over, *pending_out will point to a msgb with the remaining data.
219*/
220static enum iofd_seg_act iofd_handle_segmentation(struct osmo_io_fd *iofd, struct msgb *msg, struct msgb **pending_out)
221{
Daniel Willmannd4d03702023-05-17 12:38:14 +0200222 int extra_len, msg_len;
Harald Welte8857f3b2022-11-18 13:54:44 +0100223 struct msgb *msg_pending;
224
225 msg_len = msgb_length(msg);
226
227 if (!iofd->io_ops.segmentation_cb) {
228 *pending_out = NULL;
229 return IOFD_SEG_ACT_HANDLE_ONE;
230 }
231
Daniel Willmannd4d03702023-05-17 12:38:14 +0200232 int len = iofd->io_ops.segmentation_cb(msg);
233 if (len == -EAGAIN) {
234 goto defer;
235 } else if (len < 0) {
236 /* Something is wrong, skip this msgb */
237 LOGPIO(iofd, LOGL_ERROR, "segmentation_cb returned error (%d), skipping msg of size %d\n", len, msg_len);
Harald Welte8857f3b2022-11-18 13:54:44 +0100238 *pending_out = NULL;
Daniel Willmannd4d03702023-05-17 12:38:14 +0200239 msgb_free(msg);
Harald Welte8857f3b2022-11-18 13:54:44 +0100240 return IOFD_SEG_ACT_DEFER;
241 }
242
Daniel Willmannd4d03702023-05-17 12:38:14 +0200243 extra_len = msg_len - len;
244 /* No segmentation needed, return the whole msgb */
245 if (extra_len == 0) {
246 *pending_out = NULL;
247 return IOFD_SEG_ACT_HANDLE_ONE;
248 /* segment is incomplete */
249 } else if (extra_len < 0) {
250 goto defer;
251 }
252
253 /* msgb contains more than one segment */
254 /* Copy the trailing data over */
Harald Welte8857f3b2022-11-18 13:54:44 +0100255 msg_pending = iofd_msgb_alloc(iofd);
Daniel Willmannd4d03702023-05-17 12:38:14 +0200256 memcpy(msgb_data(msg_pending), msgb_data(msg) + len, extra_len);
257 msgb_put(msg_pending, extra_len);
Harald Welte8857f3b2022-11-18 13:54:44 +0100258 *pending_out = msg_pending;
259
260 /* Trim the original msgb to size */
261 msgb_trim(msg, len);
262 return IOFD_SEG_ACT_HANDLE_MORE;
Daniel Willmannd4d03702023-05-17 12:38:14 +0200263
264defer:
265 *pending_out = msg;
266 return IOFD_SEG_ACT_DEFER;
Harald Welte8857f3b2022-11-18 13:54:44 +0100267}
268
269/*! Restore message boundaries on read() and pass individual messages to the read callback
270 */
271void iofd_handle_segmented_read(struct osmo_io_fd *iofd, struct msgb *msg, int rc)
272{
273 int res;
274 struct msgb *pending = NULL;
275
276 if (rc <= 0) {
277 iofd->io_ops.read_cb(iofd, rc, msg);
278 return;
279 }
280
281 do {
282 res = iofd_handle_segmentation(iofd, msg, &pending);
283 if (res != IOFD_SEG_ACT_DEFER || rc < 0)
284 iofd->io_ops.read_cb(iofd, rc, msg);
285 if (res == IOFD_SEG_ACT_HANDLE_MORE)
286 msg = pending;
287 } while (res == IOFD_SEG_ACT_HANDLE_MORE);
288
289 OSMO_ASSERT(iofd->pending == NULL);
290 iofd->pending = pending;
291}
292
293/* Public functions */
294
295/*! Send a message through a connected socket
296 *
297 * Appends the message to the internal transmit queue.
298 * If the function returns success (0) it will take ownership of the msgb and
299 * internally call msgb_free() after the write request completes.
300 * In case of an error the msgb needs to be freed by the caller.
301 * \param[in] iofd file descriptor to write to
302 * \param[in] msg message buffer to write
303 * \returns 0 in case of success; a negative value in case of error
304 */
305int osmo_iofd_write_msgb(struct osmo_io_fd *iofd, struct msgb *msg)
306{
307 int rc;
308 struct iofd_msghdr *msghdr = iofd_msghdr_alloc(iofd, IOFD_ACT_WRITE, msg);
309 if (!msghdr)
310 return -ENOMEM;
311
312 msghdr->flags = 0;
313 msghdr->iov[0].iov_base = msgb_data(msghdr->msg);
314 msghdr->iov[0].iov_len = msgb_length(msghdr->msg);
315 msghdr->hdr.msg_iov = &msghdr->iov[0];
316 msghdr->hdr.msg_iovlen = 1;
317
318 rc = iofd_txqueue_enqueue(iofd, msghdr);
319 if (rc < 0) {
320 iofd_msghdr_free(msghdr);
321 LOGPIO(iofd, LOGL_ERROR, "enqueueing message failed (%d). Rejecting msgb\n", rc);
322 return rc;
323 }
324
325 return 0;
326}
327
328/*! Send a message through an unconnected socket
329 *
330 * Appends the message to the internal transmit queue.
331 * If the function returns success (0), it will take ownership of the msgb and
332 * internally call msgb_free() after the write request completes.
333 * In case of an error the msgb needs to be freed by the caller.
334 * \param[in] iofd file descriptor to write to
335 * \param[in] msg message buffer to send
336 * \param[in] sendto_flags Flags to pass to the send call
337 * \param[in] dest destination address to send the message to
338 * \returns 0 in case of success; a negative value in case of error
339 */
340int osmo_iofd_sendto_msgb(struct osmo_io_fd *iofd, struct msgb *msg, int sendto_flags, const struct osmo_sockaddr *dest)
341{
342 int rc;
343
344 OSMO_ASSERT(iofd->mode == OSMO_IO_FD_MODE_RECVFROM_SENDTO);
345
346 struct iofd_msghdr *msghdr = iofd_msghdr_alloc(iofd, IOFD_ACT_SENDTO, msg);
347 if (!msghdr)
348 return -ENOMEM;
349
350 if (dest) {
351 msghdr->osa = *dest;
352 msghdr->hdr.msg_name = &msghdr->osa.u.sa;
353 msghdr->hdr.msg_namelen = osmo_sockaddr_size(&msghdr->osa);
354 }
355 msghdr->flags = sendto_flags;
356 msghdr->iov[0].iov_base = msgb_data(msghdr->msg);
357 msghdr->iov[0].iov_len = msgb_length(msghdr->msg);
358 msghdr->hdr.msg_iov = &msghdr->iov[0];
359 msghdr->hdr.msg_iovlen = 1;
360
361 rc = iofd_txqueue_enqueue(iofd, msghdr);
362 if (rc < 0) {
363 iofd_msghdr_free(msghdr);
364 LOGPIO(iofd, LOGL_ERROR, "enqueueing message failed (%d). Rejecting msgb\n", rc);
365 return rc;
366 }
367
368 return 0;
369}
370
371/*! Enable reading from this iofd
372 *
373 * \param[in] iofd the file descriptor
374 */
375void osmo_iofd_read_enable(struct osmo_io_fd *iofd)
376{
377 iofd->read_enabled = true;
378 osmo_iofd_ops.read_enable(iofd);
379}
380
381/*! Disable reading from this iofd
382 *
383 * \param[in] iofd the file descriptor
384 */
385void osmo_iofd_read_disable(struct osmo_io_fd *iofd)
386{
387 iofd->read_enabled = false;
388 osmo_iofd_ops.read_disable(iofd);
389}
390
391/*! Enable writing to this iofd
392 *
393 * \param[in] iofd the file descriptor
394 */
395void osmo_iofd_write_enable(struct osmo_io_fd *iofd)
396{
397 iofd->write_enabled = true;
Daniel Willmanncbbd17e2023-05-17 17:08:10 +0200398 osmo_iofd_ops.write_enable(iofd);
Harald Welte8857f3b2022-11-18 13:54:44 +0100399}
400
401/*! Disable writing to this iofd
402 *
403 * \param[in] iofd the file descriptor
404 */
405void osmo_iofd_write_disable(struct osmo_io_fd *iofd)
406{
407 iofd->write_enabled = false;
408 osmo_iofd_ops.write_disable(iofd);
409}
410
411/*! Allocate and setup a new iofd
412 * \param[in] ctx the parent context from which to allocate
413 * \param[in] fd the underlying system file descriptor
414 * \param[in] name the name of the iofd
415 * \param[in] mode the mode of the iofd, whether it should use read()/write(), sendto()/recvfrom()
416 * \param[in] ioops structure with read/write/send/recv callbacks
417 * \param[in] data user data pointer accessible by the ioops callbacks
418 * \returns The newly allocated osmo_io_fd struct or NULL on failure
419 */
420struct osmo_io_fd *osmo_iofd_setup(const void *ctx, int fd, const char *name, enum osmo_io_fd_mode mode,
421 const struct osmo_io_ops *ioops, void *data)
422{
423 struct osmo_io_fd *iofd = talloc_zero(ctx, struct osmo_io_fd);
424 if (!iofd)
425 return NULL;
426
427 iofd->fd = fd;
428 iofd->mode = mode;
429
430 iofd->name = talloc_strdup(iofd, name);
431
432 if (ioops)
433 iofd->io_ops = *ioops;
434
435 iofd->pending = NULL;
436
437 iofd->data = data;
438
439 iofd->msgb_alloc.ctx = ctx;
440 iofd->msgb_alloc.size = OSMO_IO_DEFAULT_MSGB_SIZE;
441 iofd->msgb_alloc.headroom = OSMO_IO_DEFAULT_MSGB_HEADROOM;
442
443 iofd->tx_queue.max_length = 32;
444 INIT_LLIST_HEAD(&iofd->tx_queue.msg_queue);
445
446 return iofd;
447}
448
449/*! Register the fd with the underlying backend
450 *
451 * \param[in] iofd the iofd file descriptor
452 * \param[in] fd the system fd number that will be registeres. If negative will use the one already set.
453 * \returns zero on success, a negative value on error
454*/
455int osmo_iofd_register(struct osmo_io_fd *iofd, int fd)
456{
457 if (fd >= 0)
458 iofd->fd = fd;
459 iofd->closed = false;
460
461 if (osmo_iofd_ops.register_fd)
462 return osmo_iofd_ops.register_fd(iofd);
463
464 return 0;
465}
466
467/*! Unregister the fd from the underlying backend
468 *
469 * \param[in] iofd the file descriptor
470 * \returns zero on success, a negative value on error
471 */
472int osmo_iofd_unregister(struct osmo_io_fd *iofd)
473{
474 if (osmo_iofd_ops.unregister_fd)
475 return osmo_iofd_ops.unregister_fd(iofd);
476
477 return 0;
478}
479
480/*! Get the number of messages in the tx queue
481 *
482 * \param[in] iofd the file descriptor
483 */
484unsigned int osmo_iofd_txqueue_len(struct osmo_io_fd *iofd)
485{
486 return iofd->tx_queue.current_length;
487}
488
489/*! Clear the transmit queue of the the iofd
490 *
491 * This function frees all messages currently pending in the transmit queue
492 * \param[in] iofd the file descriptor
493 */
494void osmo_iofd_txqueue_clear(struct osmo_io_fd *iofd)
495{
496 struct iofd_msghdr *hdr;
497 while ((hdr = iofd_txqueue_dequeue(iofd))) {
498 msgb_free(hdr->msg);
499 iofd_msghdr_free(hdr);
500 }
501}
502
503/*! Free the iofd
504 *
505 * This function is safe to use in the read/write callbacks and will defer freeing it until safe to do so.
506 * The iofd will be closed before.
507 * \param[in] iofd the file descriptor
508 */
509void osmo_iofd_free(struct osmo_io_fd *iofd)
510{
511 if (!iofd)
512 return;
513
514 osmo_iofd_close(iofd);
515
516 if (!iofd->in_callback) {
517 talloc_free(iofd);
518 } else {
519 /* Prevent our parent context from freeing us prematurely */
520 talloc_steal(NULL, iofd);
521 iofd->to_free = true;
522 }
523}
524
525/*! Close the iofd
526 *
527 * This function closes the underlying fd and clears any messages in the tx queue
528 * The iofd is not freed and can be assigned a new file descriptor with osmo_iofd_register()
529 * \param[in] iofd the file descriptor
530 * \ returns 0 on success, a negative value otherwise
531 */
532int osmo_iofd_close(struct osmo_io_fd *iofd)
533{
534 int rc = 0;
535
536 if (iofd->closed)
537 return rc;
538
539 iofd->closed = true;
540
541 /* Free pending msgs in tx queue */
542 osmo_iofd_txqueue_clear(iofd);
543 msgb_free(iofd->pending);
544
545 iofd->pending = NULL;
546
547 if (osmo_iofd_ops.close)
548 rc = osmo_iofd_ops.close(iofd);
549 iofd->fd = -1;
550 return rc;
551}
552
553/*! Set the size and headroom of the msgb allocated when receiving messages
554 * \param[in] size the size of the msgb when receiving data
555 * \param[in] headroom the headroom of the msgb when receiving data
556 */
557void osmo_iofd_set_alloc_info(struct osmo_io_fd *iofd, unsigned int size, unsigned int headroom)
558{
559 iofd->msgb_alloc.headroom = headroom;
560 iofd->msgb_alloc.size = size;
561}
562
563/*! Get the associated user-data from an iofd
564 * \param[in] iofd the file descriptor
565 * \returns the data that was previously set with \ref osmo_iofd_setup()
566 */
567void *osmo_iofd_get_data(const struct osmo_io_fd *iofd)
568{
569 return iofd->data;
570}
571
572/*! Set the associated user-data from an iofd
573 * \param[in] iofd the file descriptor
574 * \param[in] data the data to set
575 */
576void osmo_iofd_set_data(struct osmo_io_fd *iofd, void *data)
577{
578 iofd->data = data;
579}
580
581/*! Get the private number from an iofd
582 * \param[in] iofd the file descriptor
583 * \returns the private number that was previously set with \ref osmo_iofd_set_priv_nr()
584 */
585unsigned int osmo_iofd_get_priv_nr(const struct osmo_io_fd *iofd)
586{
587 return iofd->priv_nr;
588}
589
590/*! Set the private number from an iofd
591 * \param[in] iofd the file descriptor
592 * \param[in] priv_nr the private number to set
593 */
594void osmo_iofd_set_priv_nr(struct osmo_io_fd *iofd, unsigned int priv_nr)
595{
596 iofd->priv_nr = priv_nr;
597}
598
599/*! Get the underlying file descriptor from an iofd
600 * \param[in] iofd the file descriptor
601 * \returns the underlying file descriptor number */
602int osmo_iofd_get_fd(const struct osmo_io_fd *iofd)
603{
604 return iofd->fd;
605}
606
607/*! Get the name of the file descriptor
608 * \param[in] iofd the file descriptor
609 * \returns the name of the iofd as given in \ref osmo_iofd_setup() */
610const char *osmo_iofd_get_name(const struct osmo_io_fd *iofd)
611{
612 return iofd->name;
613}
614
arehbein0c374c62023-05-14 21:43:11 +0200615/*! Set the osmo_io_ops for an iofd
616 * \param[in] iofd Target iofd file descriptor
617 * \param[in] ioops osmo_io_ops structure to be set */
618void osmo_iofd_set_ioops(struct osmo_io_fd *iofd, const struct osmo_io_ops *ioops)
619{
620 iofd->io_ops = *ioops;
621}
622
Harald Welte8857f3b2022-11-18 13:54:44 +0100623#endif /* defined(__linux__) */