poll-loop: Make wakeup logging more portable and easier to understand.
[sliver-openvswitch.git] / lib / poll-loop.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "poll-loop.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <poll.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include "coverage.h"
26 #include "dynamic-string.h"
27 #include "fatal-signal.h"
28 #include "list.h"
29 #include "socket-util.h"
30 #include "timeval.h"
31 #include "vlog.h"
32
33 #undef poll_fd_wait
34 #undef poll_timer_wait
35 #undef poll_timer_wait_until
36 #undef poll_immediate_wake
37
38 VLOG_DEFINE_THIS_MODULE(poll_loop);
39
40 COVERAGE_DEFINE(poll_fd_wait);
41 COVERAGE_DEFINE(poll_zero_timeout);
42
43 /* An event that will wake the following call to poll_block(). */
44 struct poll_waiter {
45     /* Set when the waiter is created. */
46     struct list node;           /* Element in global waiters list. */
47     int fd;                     /* File descriptor. */
48     short int events;           /* Events to wait for (POLLIN, POLLOUT). */
49     const char *where;          /* Where the waiter was created. */
50
51     /* Set only when poll_block() is called. */
52     struct pollfd *pollfd;      /* Pointer to element of the pollfds array. */
53 };
54
55 /* All active poll waiters. */
56 static struct list waiters = LIST_INITIALIZER(&waiters);
57
58 /* Number of elements in the waiters list. */
59 static size_t n_waiters;
60
61 /* Max time to wait in next call to poll_block(), in milliseconds, or -1 to
62  * wait forever. */
63 static int timeout = -1;
64
65 /* Location where waiter created. */
66 static const char *timeout_where;
67
68 static struct poll_waiter *new_waiter(int fd, short int events,
69                                       const char *where);
70
71 /* Registers 'fd' as waiting for the specified 'events' (which should be POLLIN
72  * or POLLOUT or POLLIN | POLLOUT).  The following call to poll_block() will
73  * wake up when 'fd' becomes ready for one or more of the requested events.
74  *
75  * The event registration is one-shot: only the following call to poll_block()
76  * is affected.  The event will need to be re-registered after poll_block() is
77  * called if it is to persist.
78  *
79  * Ordinarily the 'where' argument is supplied automatically; see poll-loop.h
80  * for more information. */
81 struct poll_waiter *
82 poll_fd_wait(int fd, short int events, const char *where)
83 {
84     COVERAGE_INC(poll_fd_wait);
85     return new_waiter(fd, events, where);
86 }
87
88 /* The caller must ensure that 'msec' is not negative. */
89 static void
90 poll_timer_wait__(int msec, const char *where)
91 {
92     if (timeout < 0 || msec < timeout) {
93         timeout = msec;
94         timeout_where = where;
95     }
96 }
97
98 /* Causes the following call to poll_block() to block for no more than 'msec'
99  * milliseconds.  If 'msec' is nonpositive, the following call to poll_block()
100  * will not block at all.
101  *
102  * The timer registration is one-shot: only the following call to poll_block()
103  * is affected.  The timer will need to be re-registered after poll_block() is
104  * called if it is to persist.
105  *
106  * Ordinarily the 'where' argument is supplied automatically; see poll-loop.h
107  * for more information. */
108 void
109 poll_timer_wait(long long int msec, const char *where)
110 {
111     poll_timer_wait__((msec < 0 ? 0
112                        : msec > INT_MAX ? INT_MAX
113                        : msec),
114                       where);
115 }
116
117 /* Causes the following call to poll_block() to wake up when the current time,
118  * as returned by time_msec(), reaches 'msec' or later.  If 'msec' is earlier
119  * than the current time, the following call to poll_block() will not block at
120  * all.
121  *
122  * The timer registration is one-shot: only the following call to poll_block()
123  * is affected.  The timer will need to be re-registered after poll_block() is
124  * called if it is to persist.
125  *
126  * Ordinarily the 'where' argument is supplied automatically; see poll-loop.h
127  * for more information. */
128 void
129 poll_timer_wait_until(long long int msec, const char *where)
130 {
131     long long int now = time_msec();
132     poll_timer_wait__((msec <= now ? 0
133                        : msec < now + INT_MAX ? msec - now
134                        : INT_MAX),
135                       where);
136 }
137
138 /* Causes the following call to poll_block() to wake up immediately, without
139  * blocking.
140  *
141  * Ordinarily the 'where' argument is supplied automatically; see poll-loop.h
142  * for more information. */
143 void
144 poll_immediate_wake(const char *where)
145 {
146     poll_timer_wait(0, where);
147 }
148
149 static void PRINTF_FORMAT(2, 3)
150 log_wakeup(const char *where, const char *format, ...)
151 {
152     struct ds ds;
153     va_list args;
154
155     ds_init(&ds);
156     va_start(args, format);
157     ds_put_format_valist(&ds, format, args);
158     va_end(args);
159
160     if (where) {
161         ds_put_format(&ds, " at %s", where);
162     }
163
164     VLOG_DBG("%s", ds_cstr(&ds));
165     ds_destroy(&ds);
166 }
167
168 /* Blocks until one or more of the events registered with poll_fd_wait()
169  * occurs, or until the minimum duration registered with poll_timer_wait()
170  * elapses, or not at all if poll_immediate_wake() has been called. */
171 void
172 poll_block(void)
173 {
174     static struct pollfd *pollfds;
175     static size_t max_pollfds;
176
177     struct poll_waiter *pw, *next;
178     int n_pollfds;
179     int retval;
180
181     /* Register fatal signal events before actually doing any real work for
182      * poll_block. */
183     fatal_signal_wait();
184
185     if (max_pollfds < n_waiters) {
186         max_pollfds = n_waiters;
187         pollfds = xrealloc(pollfds, max_pollfds * sizeof *pollfds);
188     }
189
190     n_pollfds = 0;
191     LIST_FOR_EACH (pw, node, &waiters) {
192         pw->pollfd = &pollfds[n_pollfds];
193         pollfds[n_pollfds].fd = pw->fd;
194         pollfds[n_pollfds].events = pw->events;
195         pollfds[n_pollfds].revents = 0;
196         n_pollfds++;
197     }
198
199     if (!timeout) {
200         COVERAGE_INC(poll_zero_timeout);
201     }
202     retval = time_poll(pollfds, n_pollfds, timeout);
203     if (retval < 0) {
204         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
205         VLOG_ERR_RL(&rl, "poll: %s", strerror(-retval));
206     } else if (!retval && VLOG_IS_DBG_ENABLED()) {
207         log_wakeup(timeout_where, "%d-ms timeout", timeout);
208     }
209
210     LIST_FOR_EACH_SAFE (pw, next, node, &waiters) {
211         if (pw->pollfd->revents && VLOG_IS_DBG_ENABLED()) {
212             char *description = describe_fd(pw->fd);
213             log_wakeup(pw->where, "%s%s%s%s%s on fd %d (%s)",
214                        pw->pollfd->revents & POLLIN ? "[POLLIN]" : "",
215                        pw->pollfd->revents & POLLOUT ? "[POLLOUT]" : "",
216                        pw->pollfd->revents & POLLERR ? "[POLLERR]" : "",
217                        pw->pollfd->revents & POLLHUP ? "[POLLHUP]" : "",
218                        pw->pollfd->revents & POLLNVAL ? "[POLLNVAL]" : "",
219                        pw->fd, description);
220             free(description);
221         }
222         poll_cancel(pw);
223     }
224
225     timeout = -1;
226     timeout_where = NULL;
227
228     /* Handle any pending signals before doing anything else. */
229     fatal_signal_run();
230 }
231
232 /* Cancels the file descriptor event registered with poll_fd_wait() using 'pw',
233  * the struct poll_waiter returned by that function.
234  *
235  * An event registered with poll_fd_wait() may be canceled from its time of
236  * registration until the next call to poll_block().  At that point, the event
237  * is automatically canceled by the system and its poll_waiter is freed. */
238 void
239 poll_cancel(struct poll_waiter *pw)
240 {
241     if (pw) {
242         list_remove(&pw->node);
243         free(pw);
244         n_waiters--;
245     }
246 }
247 \f
248 /* Creates and returns a new poll_waiter for 'fd' and 'events'. */
249 static struct poll_waiter *
250 new_waiter(int fd, short int events, const char *where)
251 {
252     struct poll_waiter *waiter = xzalloc(sizeof *waiter);
253     assert(fd >= 0);
254     waiter->fd = fd;
255     waiter->events = events;
256     waiter->where = where;
257     list_push_back(&waiters, &waiter->node);
258     n_waiters++;
259     return waiter;
260 }