socket-util: New function get_socket_rcvbuf().
[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 /* Max time to wait in next call to poll_block(), in milliseconds, or -1 to
59  * wait forever. */
60 static int timeout = -1;
61
62 /* Location where waiter created. */
63 static const char *timeout_where;
64
65 /* Array of file descriptors from last run of poll_block(). */
66 static struct pollfd *pollfds;
67
68 /* Allocated size of pollfds. */
69 static size_t max_pollfds;
70
71 /* Current number of elements in pollfds. */
72 static int n_pollfds;
73
74 static struct poll_waiter *new_waiter(int fd, short int events,
75                                       const char *where);
76
77 /* Registers 'fd' as waiting for the specified 'events' (which should be POLLIN
78  * or POLLOUT or POLLIN | POLLOUT).  The following call to poll_block() will
79  * wake up when 'fd' becomes ready for one or more of the requested events.
80  *
81  * The event registration is one-shot: only the following call to poll_block()
82  * is affected.  The event will need to be re-registered after poll_block() is
83  * called if it is to persist.
84  *
85  * Ordinarily the 'where' argument is supplied automatically; see poll-loop.h
86  * for more information. */
87 struct poll_waiter *
88 poll_fd_wait(int fd, short int events, const char *where)
89 {
90     COVERAGE_INC(poll_fd_wait);
91     return new_waiter(fd, events, where);
92 }
93
94 /* The caller must ensure that 'msec' is not negative. */
95 static void
96 poll_timer_wait__(int msec, const char *where)
97 {
98     if (timeout < 0 || msec < timeout) {
99         timeout = msec;
100         timeout_where = where;
101     }
102 }
103
104 /* Causes the following call to poll_block() to block for no more than 'msec'
105  * milliseconds.  If 'msec' is nonpositive, the following call to poll_block()
106  * will not block at all.
107  *
108  * The timer registration is one-shot: only the following call to poll_block()
109  * is affected.  The timer will need to be re-registered after poll_block() is
110  * called if it is to persist.
111  *
112  * Ordinarily the 'where' argument is supplied automatically; see poll-loop.h
113  * for more information. */
114 void
115 poll_timer_wait(long long int msec, const char *where)
116 {
117     poll_timer_wait__((msec < 0 ? 0
118                        : msec > INT_MAX ? INT_MAX
119                        : msec),
120                       where);
121 }
122
123 /* Causes the following call to poll_block() to wake up when the current time,
124  * as returned by time_msec(), reaches 'msec' or later.  If 'msec' is earlier
125  * than the current time, the following call to poll_block() will not block at
126  * all.
127  *
128  * The timer registration is one-shot: only the following call to poll_block()
129  * is affected.  The timer will need to be re-registered after poll_block() is
130  * called if it is to persist.
131  *
132  * Ordinarily the 'where' argument is supplied automatically; see poll-loop.h
133  * for more information. */
134 void
135 poll_timer_wait_until(long long int msec, const char *where)
136 {
137     long long int now = time_msec();
138     poll_timer_wait__((msec <= now ? 0
139                        : msec < now + INT_MAX ? msec - now
140                        : INT_MAX),
141                       where);
142 }
143
144 /* Causes the following call to poll_block() to wake up immediately, without
145  * blocking.
146  *
147  * Ordinarily the 'where' argument is supplied automatically; see poll-loop.h
148  * for more information. */
149 void
150 poll_immediate_wake(const char *where)
151 {
152     poll_timer_wait(0, where);
153 }
154
155 /* Logs, if appropriate, that the poll loop was awakened by an event
156  * registered at 'where' (typically a source file and line number).  The other
157  * arguments have two possible interpretations:
158  *
159  *   - If 'pollfd' is nonnull then it should be the "struct pollfd" that caused
160  *     the wakeup.  'timeout' is ignored.
161  *
162  *   - If 'pollfd' is NULL then 'timeout' is the number of milliseconds after
163  *     which the poll loop woke up.
164  */
165 static void
166 log_wakeup(const char *where, const struct pollfd *pollfd, int timeout)
167 {
168     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(120, 120);
169     enum vlog_level level;
170     int cpu_usage;
171     struct ds s;
172
173     cpu_usage = get_cpu_usage();
174     if (VLOG_IS_DBG_ENABLED()) {
175         level = VLL_DBG;
176     } else if (cpu_usage > 50 && !VLOG_DROP_WARN(&rl)) {
177         level = VLL_WARN;
178     } else {
179         return;
180     }
181
182     ds_init(&s);
183     ds_put_cstr(&s, "wakeup due to ");
184     if (pollfd) {
185         char *description = describe_fd(pollfd->fd);
186         if (pollfd->revents & POLLIN) {
187             ds_put_cstr(&s, "[POLLIN]");
188         }
189         if (pollfd->revents & POLLOUT) {
190             ds_put_cstr(&s, "[POLLOUT]");
191         }
192         if (pollfd->revents & POLLERR) {
193             ds_put_cstr(&s, "[POLLERR]");
194         }
195         if (pollfd->revents & POLLHUP) {
196             ds_put_cstr(&s, "[POLLHUP]");
197         }
198         if (pollfd->revents & POLLNVAL) {
199             ds_put_cstr(&s, "[POLLNVAL]");
200         }
201         ds_put_format(&s, " on fd %d (%s)", pollfd->fd, description);
202         free(description);
203     } else {
204         ds_put_format(&s, "%d-ms timeout", timeout);
205     }
206     if (where) {
207         ds_put_format(&s, " at %s", where);
208     }
209     if (cpu_usage >= 0) {
210         ds_put_format(&s, " (%d%% CPU usage)", cpu_usage);
211     }
212     VLOG(level, "%s", ds_cstr(&s));
213     ds_destroy(&s);
214 }
215
216 /* Blocks until one or more of the events registered with poll_fd_wait()
217  * occurs, or until the minimum duration registered with poll_timer_wait()
218  * elapses, or not at all if poll_immediate_wake() has been called. */
219 void
220 poll_block(void)
221 {
222     struct poll_waiter *pw, *next;
223     int n_waiters;
224     int retval;
225
226     /* Register fatal signal events before actually doing any real work for
227      * poll_block. */
228     fatal_signal_wait();
229
230     n_waiters = list_size(&waiters);
231     if (max_pollfds < n_waiters) {
232         max_pollfds = n_waiters;
233         pollfds = xrealloc(pollfds, max_pollfds * sizeof *pollfds);
234     }
235
236     n_pollfds = 0;
237     LIST_FOR_EACH (pw, node, &waiters) {
238         pw->pollfd = &pollfds[n_pollfds];
239         pollfds[n_pollfds].fd = pw->fd;
240         pollfds[n_pollfds].events = pw->events;
241         pollfds[n_pollfds].revents = 0;
242         n_pollfds++;
243     }
244
245     if (!timeout) {
246         COVERAGE_INC(poll_zero_timeout);
247     }
248     retval = time_poll(pollfds, n_pollfds, timeout);
249     if (retval < 0) {
250         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
251         VLOG_ERR_RL(&rl, "poll: %s", strerror(-retval));
252     } else if (!retval) {
253         log_wakeup(timeout_where, NULL, timeout);
254     }
255
256     LIST_FOR_EACH_SAFE (pw, next, node, &waiters) {
257         if (pw->pollfd->revents) {
258             log_wakeup(pw->where, pw->pollfd, 0);
259         }
260         poll_cancel(pw);
261     }
262
263     timeout = -1;
264     timeout_where = NULL;
265
266     /* Handle any pending signals before doing anything else. */
267     fatal_signal_run();
268 }
269
270 /* Cancels the file descriptor event registered with poll_fd_wait() using 'pw',
271  * the struct poll_waiter returned by that function.
272  *
273  * An event registered with poll_fd_wait() may be canceled from its time of
274  * registration until the next call to poll_block().  At that point, the event
275  * is automatically canceled by the system and its poll_waiter is freed. */
276 void
277 poll_cancel(struct poll_waiter *pw)
278 {
279     if (pw) {
280         list_remove(&pw->node);
281         free(pw);
282     }
283 }
284
285 /* Checks whether the given file descriptor caused the poll loop to wake up
286  * in the previous iteration.  If it did, returns a bitmask of the events
287  * that caused the wakeup.  Otherwise returns 0;
288  */
289 short int
290 poll_fd_woke(int fd)
291 {
292     int i;
293     short int events = 0;
294
295     for (i = 0; i < n_pollfds; i++) {
296         if (pollfds[i].fd == fd) {
297             events |= pollfds[i].revents;
298         }
299     }
300
301     return events;
302 }
303 \f
304 /* Creates and returns a new poll_waiter for 'fd' and 'events'. */
305 static struct poll_waiter *
306 new_waiter(int fd, short int events, const char *where)
307 {
308     struct poll_waiter *waiter = xzalloc(sizeof *waiter);
309     assert(fd >= 0);
310     waiter->fd = fd;
311     waiter->events = events;
312     waiter->where = where;
313     list_push_back(&waiters, &waiter->node);
314     return waiter;
315 }