abd44d1be709c8c902302011a26a2c9f30f84f3f
[sliver-openvswitch.git] / lib / poll-loop.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
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 <errno.h>
20 #include <inttypes.h>
21 #include <poll.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include "coverage.h"
25 #include "dynamic-string.h"
26 #include "fatal-signal.h"
27 #include "list.h"
28 #include "ovs-thread.h"
29 #include "seq.h"
30 #include "socket-util.h"
31 #include "timeval.h"
32 #include "vlog.h"
33 #include "hmap.h"
34 #include "hash.h"
35
36 VLOG_DEFINE_THIS_MODULE(poll_loop);
37
38 COVERAGE_DEFINE(poll_fd_wait);
39 COVERAGE_DEFINE(poll_zero_timeout);
40
41 struct poll_node {
42     struct hmap_node hmap_node;
43     struct pollfd pollfd;       /* Events to pass to time_poll(). */
44     HANDLE wevent;              /* Events for WaitForMultipleObjects(). */
45     const char *where;          /* Where poll_node was created. */
46 };
47
48 struct poll_loop {
49     /* All active poll waiters. */
50     struct hmap poll_nodes;
51
52     /* Time at which to wake up the next call to poll_block(), LLONG_MIN to
53      * wake up immediately, or LLONG_MAX to wait forever. */
54     long long int timeout_when; /* In msecs as returned by time_msec(). */
55     const char *timeout_where;  /* Where 'timeout_when' was set. */
56 };
57
58 static struct poll_loop *poll_loop(void);
59
60 /* Look up the node with same fd and wevent. */
61 static struct poll_node *
62 find_poll_node(struct poll_loop *loop, int fd, uint32_t wevent)
63 {
64     struct poll_node *node;
65
66     HMAP_FOR_EACH_WITH_HASH (node, hmap_node, hash_2words(fd, wevent),
67                              &loop->poll_nodes) {
68         if (node->pollfd.fd == fd && node->wevent == wevent) {
69             return node;
70         }
71     }
72     return NULL;
73 }
74
75 /* On Unix based systems:
76  *
77  *     Registers 'fd' as waiting for the specified 'events' (which should be
78  *     POLLIN or POLLOUT or POLLIN | POLLOUT).  The following call to
79  *     poll_block() will wake up when 'fd' becomes ready for one or more of the
80  *     requested events.  the 'fd's are given to poll() function later.
81  *
82  * On Windows system:
83  *
84  *     Register 'wevent' handle for the specified 'events'.  These wevents are
85  *     given to the handleMultipleObjects() to be polled.  The event
86  *     registration is one-shot: only the following call to poll_block() is
87  *     affected.  The event will need to be re-registered after poll_block() is
88  *     called if it is to persist.
89  *
90  * ('where' is used in debug logging.  Commonly one would use poll_fd_wait() to
91  * automatically provide the caller's source file and line number for
92  * 'where'.) */
93 void
94 poll_fd_wait_at(int fd, HANDLE wevent, short int events, const char *where)
95 {
96     struct poll_loop *loop = poll_loop();
97     struct poll_node *node;
98
99     COVERAGE_INC(poll_fd_wait);
100
101 #ifdef _WIN32
102     /* Null event cannot be polled. */
103     if (wevent == 0) {
104         VLOG_ERR("No event to wait fd %d", fd);
105         return;
106     }
107 #endif
108
109     /* Check for duplicate.  If found, "or" the event. */
110     node = find_poll_node(loop, fd, wevent);
111     if (node) {
112         node->pollfd.events |= events;
113     } else {
114         node = xzalloc(sizeof *node);
115         hmap_insert(&loop->poll_nodes, &node->hmap_node,
116                     hash_2words(fd, wevent));
117         node->pollfd.fd = fd;
118         node->pollfd.events = events;
119         node->wevent = wevent;
120         node->where = where;
121     }
122 }
123
124 /* Causes the following call to poll_block() to block for no more than 'msec'
125  * milliseconds.  If 'msec' is nonpositive, the following call to poll_block()
126  * will not block at 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  * ('where' is used in debug logging.  Commonly one would use poll_timer_wait()
133  * to automatically provide the caller's source file and line number for
134  * 'where'.) */
135 void
136 poll_timer_wait_at(long long int msec, const char *where)
137 {
138     long long int now = time_msec();
139     long long int when;
140
141     if (msec <= 0) {
142         /* Wake up immediately. */
143         when = LLONG_MIN;
144     } else if ((unsigned long long int) now + msec <= LLONG_MAX) {
145         /* Normal case. */
146         when = now + msec;
147     } else {
148         /* now + msec would overflow. */
149         when = LLONG_MAX;
150     }
151
152     poll_timer_wait_until_at(when, where);
153 }
154
155 /* Causes the following call to poll_block() to wake up when the current time,
156  * as returned by time_msec(), reaches 'when' or later.  If 'when' is earlier
157  * than the current time, the following call to poll_block() will not block at
158  * all.
159  *
160  * The timer registration is one-shot: only the following call to poll_block()
161  * is affected.  The timer will need to be re-registered after poll_block() is
162  * called if it is to persist.
163  *
164  * ('where' is used in debug logging.  Commonly one would use
165  * poll_timer_wait_until() to automatically provide the caller's source file
166  * and line number for 'where'.) */
167 void
168 poll_timer_wait_until_at(long long int when, const char *where)
169 {
170     struct poll_loop *loop = poll_loop();
171     if (when < loop->timeout_when) {
172         loop->timeout_when = when;
173         loop->timeout_where = where;
174     }
175 }
176
177 /* Causes the following call to poll_block() to wake up immediately, without
178  * blocking.
179  *
180  * ('where' is used in debug logging.  Commonly one would use
181  * poll_immediate_wake() to automatically provide the caller's source file and
182  * line number for 'where'.) */
183 void
184 poll_immediate_wake_at(const char *where)
185 {
186     poll_timer_wait_at(0, where);
187 }
188
189 /* Logs, if appropriate, that the poll loop was awakened by an event
190  * registered at 'where' (typically a source file and line number).  The other
191  * arguments have two possible interpretations:
192  *
193  *   - If 'pollfd' is nonnull then it should be the "struct pollfd" that caused
194  *     the wakeup.  'timeout' is ignored.
195  *
196  *   - If 'pollfd' is NULL then 'timeout' is the number of milliseconds after
197  *     which the poll loop woke up.
198  */
199 static void
200 log_wakeup(const char *where, const struct pollfd *pollfd, int timeout)
201 {
202     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
203     enum vlog_level level;
204     int cpu_usage;
205     struct ds s;
206
207     cpu_usage = get_cpu_usage();
208     if (VLOG_IS_DBG_ENABLED()) {
209         level = VLL_DBG;
210     } else if (cpu_usage > 50 && !VLOG_DROP_INFO(&rl)) {
211         level = VLL_INFO;
212     } else {
213         return;
214     }
215
216     ds_init(&s);
217     ds_put_cstr(&s, "wakeup due to ");
218     if (pollfd) {
219         char *description = describe_fd(pollfd->fd);
220         if (pollfd->revents & POLLIN) {
221             ds_put_cstr(&s, "[POLLIN]");
222         }
223         if (pollfd->revents & POLLOUT) {
224             ds_put_cstr(&s, "[POLLOUT]");
225         }
226         if (pollfd->revents & POLLERR) {
227             ds_put_cstr(&s, "[POLLERR]");
228         }
229         if (pollfd->revents & POLLHUP) {
230             ds_put_cstr(&s, "[POLLHUP]");
231         }
232         if (pollfd->revents & POLLNVAL) {
233             ds_put_cstr(&s, "[POLLNVAL]");
234         }
235         ds_put_format(&s, " on fd %d (%s)", pollfd->fd, description);
236         free(description);
237     } else {
238         ds_put_format(&s, "%d-ms timeout", timeout);
239     }
240     if (where) {
241         ds_put_format(&s, " at %s", where);
242     }
243     if (cpu_usage >= 0) {
244         ds_put_format(&s, " (%d%% CPU usage)", cpu_usage);
245     }
246     VLOG(level, "%s", ds_cstr(&s));
247     ds_destroy(&s);
248 }
249
250 static void
251 free_poll_nodes(struct poll_loop *loop)
252 {
253     struct poll_node *node, *next;
254
255     HMAP_FOR_EACH_SAFE (node, next, hmap_node, &loop->poll_nodes) {
256         hmap_remove(&loop->poll_nodes, &node->hmap_node);
257         free(node);
258     }
259 }
260
261 /* Blocks until one or more of the events registered with poll_fd_wait()
262  * occurs, or until the minimum duration registered with poll_timer_wait()
263  * elapses, or not at all if poll_immediate_wake() has been called. */
264 void
265 poll_block(void)
266 {
267     struct poll_loop *loop = poll_loop();
268     struct poll_node *node;
269     struct pollfd *pollfds;
270     HANDLE *wevents = NULL;
271     int elapsed;
272     int retval;
273     int i;
274
275     /* Register fatal signal events before actually doing any real work for
276      * poll_block. */
277     fatal_signal_wait();
278
279     if (loop->timeout_when == LLONG_MIN) {
280         COVERAGE_INC(poll_zero_timeout);
281     }
282
283     timewarp_wait();
284     pollfds = xmalloc(hmap_count(&loop->poll_nodes) * sizeof *pollfds);
285
286 #ifdef _WIN32
287     wevents = xmalloc(hmap_count(&loop->poll_nodes) * sizeof *wevents);
288 #endif
289
290     /* Populate with all the fds and events. */
291     i = 0;
292     HMAP_FOR_EACH (node, hmap_node, &loop->poll_nodes) {
293         pollfds[i] = node->pollfd;
294 #ifdef _WIN32
295         wevents[i] = node->wevent;
296 #endif
297         i++;
298     }
299
300     retval = time_poll(pollfds, hmap_count(&loop->poll_nodes), wevents,
301                        loop->timeout_when, &elapsed);
302     if (retval < 0) {
303         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
304         VLOG_ERR_RL(&rl, "poll: %s", ovs_strerror(-retval));
305     } else if (!retval) {
306         log_wakeup(loop->timeout_where, NULL, elapsed);
307     } else if (get_cpu_usage() > 50 || VLOG_IS_DBG_ENABLED()) {
308         i = 0;
309         HMAP_FOR_EACH (node, hmap_node, &loop->poll_nodes) {
310             if (pollfds[i].revents) {
311                 log_wakeup(node->where, &pollfds[i], 0);
312             }
313             i++;
314         }
315     }
316
317     free_poll_nodes(loop);
318     loop->timeout_when = LLONG_MAX;
319     loop->timeout_where = NULL;
320     free(pollfds);
321     free(wevents);
322
323     /* Handle any pending signals before doing anything else. */
324     fatal_signal_run();
325
326     seq_woke();
327 }
328 \f
329 static void
330 free_poll_loop(void *loop_)
331 {
332     struct poll_loop *loop = loop_;
333
334     free_poll_nodes(loop);
335     hmap_destroy(&loop->poll_nodes);
336     free(loop);
337 }
338
339 static struct poll_loop *
340 poll_loop(void)
341 {
342     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
343     static pthread_key_t key;
344     struct poll_loop *loop;
345
346     if (ovsthread_once_start(&once)) {
347         xpthread_key_create(&key, free_poll_loop);
348         ovsthread_once_done(&once);
349     }
350
351     loop = pthread_getspecific(key);
352     if (!loop) {
353         loop = xzalloc(sizeof *loop);
354         hmap_init(&loop->poll_nodes);
355         xpthread_setspecific(key, loop);
356     }
357     return loop;
358 }
359