Monado OpenXR Runtime
Loading...
Searching...
No Matches
os_fd.h
Go to the documentation of this file.
1// Copyright 2019, Collabora, Ltd.
2// Copyright 2026, Beyley Cardellio
3// Copyright 2026, Finn Zeruhn
4// SPDX-License-Identifier: BSL-1.0
5/*!
6 * @file
7 * @brief Reading from file descriptors, shared by the Linux hid and serial code.
8 * @author Jakob Bornecrantz <jakob@collabora.com>
9 * @author Rylie Pavlik <rylie.pavlik@collabora.com>
10 * @author Beyley Cardellio <ep1cm1n10n123@gmail.com>
11 * @author Finn Zeruhn <fzeruhn@icloud.com>
12 * @ingroup aux_os
13 */
14
15#pragma once
16
17#include "xrt/xrt_config_os.h"
18
19#ifndef XRT_OS_LINUX
20#error Linux-specific file.
21#endif
22
23#include "os/os_time.h"
24
25#include <stdint.h>
26#include <errno.h>
27#include <poll.h>
28#include <unistd.h>
29
30
31/*!
32 * Waits up to @p milliseconds for @p fd to be readable, then reads from it.
33 * A negative @p milliseconds reads without waiting. Retries on EINTR.
34 *
35 * @return Bytes read, 0 on timeout, -1 on error.
36 */
37static inline ssize_t
38os_fd_read(int fd, uint8_t *data, size_t size, int milliseconds)
39{
40 ssize_t ret;
41
42 if (milliseconds >= 0) {
43 int64_t deadline_ns = os_monotonic_get_ns() + (int64_t)milliseconds * U_TIME_1MS_IN_NS;
44 int timeout = milliseconds;
45 struct pollfd fds = {
46 .fd = fd,
47 .events = POLLIN,
48 };
49
50 while ((ret = poll(&fds, 1, timeout)) < 0 && errno == EINTR) {
51 int64_t left_ns = deadline_ns - os_monotonic_get_ns();
52 if (left_ns <= 0) {
53 ret = 0;
54 break;
55 }
56 timeout = (int)((left_ns + U_TIME_1MS_IN_NS - 1) / U_TIME_1MS_IN_NS);
57 }
58
59 if (ret == -1 || ret == 0) {
60 // Error or timeout.
61 return ret;
62 }
63 if (fds.revents & (POLLERR | POLLHUP | POLLNVAL)) {
64 // Device disconnect?
65 return -1;
66 }
67 }
68
69 do {
70 ret = read(fd, data, size);
71 } while (ret < 0 && errno == EINTR);
72
73 if (ret < 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
74 // Process most likely received a signal.
75 ret = 0;
76 }
77
78 return ret;
79}
static int64_t os_monotonic_get_ns(void)
Return a monotonic clock in nanoseconds.
Definition os_time.h:317
static ssize_t os_fd_read(int fd, uint8_t *data, size_t size, int milliseconds)
Waits up to milliseconds for fd to be readable, then reads from it.
Definition os_fd.h:38
Wrapper around OS native time functions.
#define U_TIME_1MS_IN_NS
The number of nanoseconds in a millisecond.
Definition u_time.h:54
Auto detect OS and certain features.