poll.c 2.12 KB
Newer Older
Philippe Gerum's avatar
Philippe Gerum committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
 * SPDX-License-Identifier: MIT
 *
 * Copyright (C) 2019 Philippe Gerum  <rpm@xenomai.org>
 */

#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <evl/poll.h>
#include "internal.h"

int evl_new_poll(void)
{
	return epoll_create1(EPOLL_CLOEXEC);
}

19
20
int evl_add_pollfd(int efd, int newfd, unsigned int events,
	union evl_value pollval)
Philippe Gerum's avatar
Philippe Gerum committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
{
	struct epoll_event ev;
	int ret;

	if (efd == newfd)
		return -ELOOP;

	ev.events = events;
	ev.data.fd = newfd;

	ret = epoll_ctl(efd, EPOLL_CTL_ADD, newfd, &ev);
	if (ret)
		return -errno;

	return 0;
}

int evl_del_pollfd(int efd, int delfd)
{
	int ret;

	ret = epoll_ctl(efd, EPOLL_CTL_DEL, delfd, NULL);
	if (ret)
		return -errno;

	return 0;
}

49
50
int evl_mod_pollfd(int efd, int modfd, unsigned int events,
	union evl_value pollval)
Philippe Gerum's avatar
Philippe Gerum committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
{
	struct epoll_event ev;
	int ret;

	ev.events = events;
	ev.data.fd = modfd;

	ret = epoll_ctl(efd, EPOLL_CTL_MOD, modfd, &ev);
	if (ret)
		return -errno;

	return 0;
}

/*
 * Use a fast stack-based array for monitoring a small number of
 * events.
 */
#define FAST_EVENT_NR  8

static int do_timedpoll(int efd, struct evl_poll_event *pollset,
			int nrset, int msecs)
{
	struct epoll_event fast_evs[FAST_EVENT_NR], *evs = fast_evs;
	int ret, n;

	if (nrset == 0)
		return 0;

	if (nrset < 0)
		return -EINVAL;

	if (nrset > FAST_EVENT_NR) {
		evs = malloc(sizeof(*evs) * nrset);
		if (evs == NULL)
			return -ENOMEM;
	}

	ret = epoll_wait(efd, evs, nrset, msecs);
	if (ret < 0) {
		ret = -errno;
		goto out;
	}

	if (ret == 0) {
		ret = -ETIMEDOUT;
		goto out;
	}

	for (n = 0; n < nrset; n++) {
		pollset[n].fd = evs[n].data.fd;
		pollset[n].events = evs[n].events;
	}
out:
	if (evs != fast_evs)
		free(evs);

	return ret;
}

int evl_timedpoll(int efd, struct evl_poll_event *pollset,
		int nrset, struct timespec *timeout)
{
	int msecs;

	if (timeout->tv_sec < 0 || timeout->tv_nsec >= 1000000000L)
		return -EINVAL;

	msecs = timeout->tv_sec * 1000 + timeout->tv_nsec / 1000000;

	return do_timedpoll(efd, pollset, nrset, msecs);
}

int evl_poll(int efd, struct evl_poll_event *pollset, int nrset)
{
	return do_timedpoll(efd, pollset, nrset, -1);
}