Import from old repository commit 61ef2b42a9c4ba8e1600f15bb0236765edc2ad45.
[cascardo/ovs.git] / lib / poll-loop.c
1 /*
2  * Copyright (c) 2008, 2009 Nicira Networks.
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include <config.h>
18 #include "poll-loop.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <poll.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include "backtrace.h"
25 #include "coverage.h"
26 #include "dynamic-string.h"
27 #include "list.h"
28 #include "timeval.h"
29
30 #define THIS_MODULE VLM_poll_loop
31 #include "vlog.h"
32
33 /* An event that will wake the following call to poll_block(). */
34 struct poll_waiter {
35     /* Set when the waiter is created. */
36     struct list node;           /* Element in global waiters list. */
37     int fd;                     /* File descriptor. */
38     short int events;           /* Events to wait for (POLLIN, POLLOUT). */
39     poll_fd_func *function;     /* Callback function, if any, or null. */
40     void *aux;                  /* Argument to callback function. */
41     struct backtrace *backtrace; /* Optionally, event that created waiter. */
42
43     /* Set only when poll_block() is called. */
44     struct pollfd *pollfd;      /* Pointer to element of the pollfds array
45                                    (null if added from a callback). */
46 };
47
48 /* All active poll waiters. */
49 static struct list waiters = LIST_INITIALIZER(&waiters);
50
51 /* Number of elements in the waiters list. */
52 static size_t n_waiters;
53
54 /* Max time to wait in next call to poll_block(), in milliseconds, or -1 to
55  * wait forever. */
56 static int timeout = -1;
57
58 /* Backtrace of 'timeout''s registration, if debugging is enabled. */
59 static struct backtrace timeout_backtrace;
60
61 /* Callback currently running, to allow verifying that poll_cancel() is not
62  * being called on a running callback. */
63 #ifndef NDEBUG
64 static struct poll_waiter *running_cb;
65 #endif
66
67 static struct poll_waiter *new_waiter(int fd, short int events);
68
69 /* Registers 'fd' as waiting for the specified 'events' (which should be POLLIN
70  * or POLLOUT or POLLIN | POLLOUT).  The following call to poll_block() will
71  * wake up when 'fd' becomes ready for one or more of the requested events.
72  *
73  * The event registration is one-shot: only the following call to poll_block()
74  * is affected.  The event will need to be re-registered after poll_block() is
75  * called if it is to persist. */
76 struct poll_waiter *
77 poll_fd_wait(int fd, short int events)
78 {
79     COVERAGE_INC(poll_fd_wait);
80     return new_waiter(fd, events);
81 }
82
83 /* Causes the following call to poll_block() to block for no more than 'msec'
84  * milliseconds.  If 'msec' is nonpositive, the following call to poll_block()
85  * will not block at all.
86  *
87  * The timer registration is one-shot: only the following call to poll_block()
88  * is affected.  The timer will need to be re-registered after poll_block() is
89  * called if it is to persist. */
90 void
91 poll_timer_wait(int msec)
92 {
93     if (timeout < 0 || msec < timeout) {
94         timeout = MAX(0, msec);
95         if (VLOG_IS_DBG_ENABLED()) {
96             backtrace_capture(&timeout_backtrace);
97         }
98     }
99 }
100
101 /* Causes the following call to poll_block() to wake up immediately, without
102  * blocking. */
103 void
104 poll_immediate_wake(void)
105 {
106     poll_timer_wait(0);
107 }
108
109 static void PRINTF_FORMAT(2, 3)
110 log_wakeup(const struct backtrace *backtrace, const char *format, ...)
111 {
112     struct ds ds;
113     va_list args;
114
115     ds_init(&ds);
116     va_start(args, format);
117     ds_put_format_valist(&ds, format, args);
118     va_end(args);
119
120     if (backtrace) {
121         int i;
122
123         ds_put_char(&ds, ':');
124         for (i = 0; i < backtrace->n_frames; i++) {
125             ds_put_format(&ds, " 0x%x", backtrace->frames[i]);
126         }
127     }
128     VLOG_DBG("%s", ds_cstr(&ds));
129     ds_destroy(&ds);
130 }
131
132 /* Blocks until one or more of the events registered with poll_fd_wait()
133  * occurs, or until the minimum duration registered with poll_timer_wait()
134  * elapses, or not at all if poll_immediate_wake() has been called.
135  *
136  * Also executes any autonomous subroutines registered with poll_fd_callback(),
137  * if their file descriptors have become ready. */
138 void
139 poll_block(void)
140 {
141     static struct pollfd *pollfds;
142     static size_t max_pollfds;
143
144     struct poll_waiter *pw;
145     struct list *node;
146     int n_pollfds;
147     int retval;
148
149     assert(!running_cb);
150     if (max_pollfds < n_waiters) {
151         max_pollfds = n_waiters;
152         pollfds = xrealloc(pollfds, max_pollfds * sizeof *pollfds);
153     }
154
155     n_pollfds = 0;
156     LIST_FOR_EACH (pw, struct poll_waiter, node, &waiters) {
157         pw->pollfd = &pollfds[n_pollfds];
158         pollfds[n_pollfds].fd = pw->fd;
159         pollfds[n_pollfds].events = pw->events;
160         pollfds[n_pollfds].revents = 0;
161         n_pollfds++;
162     }
163
164     if (!timeout) {
165         COVERAGE_INC(poll_zero_timeout);
166     }
167     retval = time_poll(pollfds, n_pollfds, timeout);
168     if (retval < 0) {
169         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
170         VLOG_ERR_RL(&rl, "poll: %s", strerror(-retval));
171     } else if (!retval && VLOG_IS_DBG_ENABLED()) {
172         log_wakeup(&timeout_backtrace, "%d-ms timeout", timeout);
173     }
174
175     for (node = waiters.next; node != &waiters; ) {
176         pw = CONTAINER_OF(node, struct poll_waiter, node);
177         if (!pw->pollfd || !pw->pollfd->revents) {
178             if (pw->function) {
179                 node = node->next;
180                 continue;
181             }
182         } else {
183             if (VLOG_IS_DBG_ENABLED()) {
184                 log_wakeup(pw->backtrace, "%s%s%s%s%s on fd %d",
185                            pw->pollfd->revents & POLLIN ? "[POLLIN]" : "",
186                            pw->pollfd->revents & POLLOUT ? "[POLLOUT]" : "",
187                            pw->pollfd->revents & POLLERR ? "[POLLERR]" : "",
188                            pw->pollfd->revents & POLLHUP ? "[POLLHUP]" : "",
189                            pw->pollfd->revents & POLLNVAL ? "[POLLNVAL]" : "",
190                            pw->fd);
191             }
192
193             if (pw->function) {
194 #ifndef NDEBUG
195                 running_cb = pw;
196 #endif
197                 pw->function(pw->fd, pw->pollfd->revents, pw->aux);
198 #ifndef NDEBUG
199                 running_cb = NULL;
200 #endif
201             }
202         }
203         node = node->next;
204         poll_cancel(pw);
205     }
206
207     timeout = -1;
208     timeout_backtrace.n_frames = 0;
209 }
210
211 /* Registers 'function' to be called with argument 'aux' by poll_block() when
212  * 'fd' becomes ready for one of the events in 'events', which should be POLLIN
213  * or POLLOUT or POLLIN | POLLOUT.
214  *
215  * The callback registration persists until the event actually occurs.  At that
216  * point, it is automatically de-registered.  The callback function must
217  * re-register the event by calling poll_fd_callback() again within the
218  * callback, if it wants to be called back again later. */
219 struct poll_waiter *
220 poll_fd_callback(int fd, short int events, poll_fd_func *function, void *aux)
221 {
222     struct poll_waiter *pw = new_waiter(fd, events);
223     pw->function = function;
224     pw->aux = aux;
225     return pw;
226 }
227
228 /* Cancels the file descriptor event registered with poll_fd_wait() or
229  * poll_fd_callback().  'pw' must be the struct poll_waiter returned by one of
230  * those functions.
231  *
232  * An event registered with poll_fd_wait() may be canceled from its time of
233  * registration until the next call to poll_block().  At that point, the event
234  * is automatically canceled by the system and its poll_waiter is freed.
235  *
236  * An event registered with poll_fd_callback() may be canceled from its time of
237  * registration until its callback is actually called.  At that point, the
238  * event is automatically canceled by the system and its poll_waiter is
239  * freed. */
240 void
241 poll_cancel(struct poll_waiter *pw)
242 {
243     if (pw) {
244         assert(pw != running_cb);
245         list_remove(&pw->node);
246         free(pw->backtrace);
247         free(pw);
248         n_waiters--;
249     }
250 }
251 \f
252 /* Creates and returns a new poll_waiter for 'fd' and 'events'. */
253 static struct poll_waiter *
254 new_waiter(int fd, short int events)
255 {
256     struct poll_waiter *waiter = xcalloc(1, sizeof *waiter);
257     assert(fd >= 0);
258     waiter->fd = fd;
259     waiter->events = events;
260     if (VLOG_IS_DBG_ENABLED()) {
261         waiter->backtrace = xmalloc(sizeof *waiter->backtrace);
262         backtrace_capture(waiter->backtrace);
263     }
264     list_push_back(&waiters, &waiter->node);
265     n_waiters++;
266     return waiter;
267 }