Merge remote-tracking branch 'ovs-dev/master'
[sliver-openvswitch.git] / lib / poll-loop.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 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 "socket-util.h"
30 #include "timeval.h"
31 #include "vlog.h"
32
33 VLOG_DEFINE_THIS_MODULE(poll_loop);
34
35 COVERAGE_DEFINE(poll_fd_wait);
36 COVERAGE_DEFINE(poll_zero_timeout);
37
38 struct poll_loop {
39     /* All active poll waiters. */
40     struct pollfd *pollfds;     /* Events to pass to poll(). */
41     const char **where;         /* Where each pollfd was created. */
42     size_t n_waiters;           /* Number of elems in 'where' and 'pollfds'. */
43     size_t allocated_waiters;   /* Allocated elems in 'where' and 'pollfds'. */
44
45     /* Time at which to wake up the next call to poll_block(), LLONG_MIN to
46      * wake up immediately, or LLONG_MAX to wait forever. */
47     long long int timeout_when; /* In msecs as returned by time_msec(). */
48     const char *timeout_where;  /* Where 'timeout_when' was set. */
49 };
50
51 static struct poll_loop *poll_loop(void);
52
53 /* Registers 'fd' as waiting for the specified 'events' (which should be POLLIN
54  * or POLLOUT or POLLIN | POLLOUT).  The following call to poll_block() will
55  * wake up when 'fd' becomes ready for one or more of the requested events.
56  *
57  * The event registration is one-shot: only the following call to poll_block()
58  * is affected.  The event will need to be re-registered after poll_block() is
59  * called if it is to persist.
60  *
61  * ('where' is used in debug logging.  Commonly one would use poll_fd_wait() to
62  * automatically provide the caller's source file and line number for
63  * 'where'.) */
64 void
65 poll_fd_wait_at(int fd, short int events, const char *where)
66 {
67     struct poll_loop *loop = poll_loop();
68
69     COVERAGE_INC(poll_fd_wait);
70     if (loop->n_waiters >= loop->allocated_waiters) {
71         loop->where = x2nrealloc(loop->where, &loop->allocated_waiters,
72                                  sizeof *loop->where);
73         loop->pollfds = xrealloc(loop->pollfds,
74                                  (loop->allocated_waiters
75                                   * sizeof *loop->pollfds));
76     }
77
78     loop->where[loop->n_waiters] = where;
79     loop->pollfds[loop->n_waiters].fd = fd;
80     loop->pollfds[loop->n_waiters].events = events;
81     loop->n_waiters++;
82 }
83
84 /* Causes the following call to poll_block() to block for no more than 'msec'
85  * milliseconds.  If 'msec' is nonpositive, the following call to poll_block()
86  * will not block at all.
87  *
88  * The timer registration is one-shot: only the following call to poll_block()
89  * is affected.  The timer will need to be re-registered after poll_block() is
90  * called if it is to persist.
91  *
92  * ('where' is used in debug logging.  Commonly one would use poll_timer_wait()
93  * to automatically provide the caller's source file and line number for
94  * 'where'.) */
95 void
96 poll_timer_wait_at(long long int msec, const char *where)
97 {
98     long long int now = time_msec();
99     long long int when;
100
101     if (msec <= 0) {
102         /* Wake up immediately. */
103         when = LLONG_MIN;
104     } else if ((unsigned long long int) now + msec <= LLONG_MAX) {
105         /* Normal case. */
106         when = now + msec;
107     } else {
108         /* now + msec would overflow. */
109         when = LLONG_MAX;
110     }
111
112     poll_timer_wait_until_at(when, where);
113 }
114
115 /* Causes the following call to poll_block() to wake up when the current time,
116  * as returned by time_msec(), reaches 'when' or later.  If 'when' is earlier
117  * than the current time, the following call to poll_block() will not block at
118  * all.
119  *
120  * The timer registration is one-shot: only the following call to poll_block()
121  * is affected.  The timer will need to be re-registered after poll_block() is
122  * called if it is to persist.
123  *
124  * ('where' is used in debug logging.  Commonly one would use
125  * poll_timer_wait_until() to automatically provide the caller's source file
126  * and line number for 'where'.) */
127 void
128 poll_timer_wait_until_at(long long int when, const char *where)
129 {
130     struct poll_loop *loop = poll_loop();
131     if (when < loop->timeout_when) {
132         loop->timeout_when = when;
133         loop->timeout_where = where;
134     }
135 }
136
137 /* Causes the following call to poll_block() to wake up immediately, without
138  * blocking.
139  *
140  * ('where' is used in debug logging.  Commonly one would use
141  * poll_immediate_wake() to automatically provide the caller's source file and
142  * line number for 'where'.) */
143 void
144 poll_immediate_wake_at(const char *where)
145 {
146     poll_timer_wait_at(0, where);
147 }
148
149 /* Logs, if appropriate, that the poll loop was awakened by an event
150  * registered at 'where' (typically a source file and line number).  The other
151  * arguments have two possible interpretations:
152  *
153  *   - If 'pollfd' is nonnull then it should be the "struct pollfd" that caused
154  *     the wakeup.  'timeout' is ignored.
155  *
156  *   - If 'pollfd' is NULL then 'timeout' is the number of milliseconds after
157  *     which the poll loop woke up.
158  */
159 static void
160 log_wakeup(const char *where, const struct pollfd *pollfd, int timeout)
161 {
162     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
163     enum vlog_level level;
164     int cpu_usage;
165     struct ds s;
166
167     cpu_usage = get_cpu_usage();
168     if (VLOG_IS_DBG_ENABLED()) {
169         level = VLL_DBG;
170     } else if (cpu_usage > 50 && !VLOG_DROP_INFO(&rl)) {
171         level = VLL_INFO;
172     } else {
173         return;
174     }
175
176     ds_init(&s);
177     ds_put_cstr(&s, "wakeup due to ");
178     if (pollfd) {
179         char *description = describe_fd(pollfd->fd);
180         if (pollfd->revents & POLLIN) {
181             ds_put_cstr(&s, "[POLLIN]");
182         }
183         if (pollfd->revents & POLLOUT) {
184             ds_put_cstr(&s, "[POLLOUT]");
185         }
186         if (pollfd->revents & POLLERR) {
187             ds_put_cstr(&s, "[POLLERR]");
188         }
189         if (pollfd->revents & POLLHUP) {
190             ds_put_cstr(&s, "[POLLHUP]");
191         }
192         if (pollfd->revents & POLLNVAL) {
193             ds_put_cstr(&s, "[POLLNVAL]");
194         }
195         ds_put_format(&s, " on fd %d (%s)", pollfd->fd, description);
196         free(description);
197     } else {
198         ds_put_format(&s, "%d-ms timeout", timeout);
199     }
200     if (where) {
201         ds_put_format(&s, " at %s", where);
202     }
203     if (cpu_usage >= 0) {
204         ds_put_format(&s, " (%d%% CPU usage)", cpu_usage);
205     }
206     VLOG(level, "%s", ds_cstr(&s));
207     ds_destroy(&s);
208 }
209
210 /* Blocks until one or more of the events registered with poll_fd_wait()
211  * occurs, or until the minimum duration registered with poll_timer_wait()
212  * elapses, or not at all if poll_immediate_wake() has been called. */
213 void
214 poll_block(void)
215 {
216     struct poll_loop *loop = poll_loop();
217     int elapsed;
218     int retval;
219
220     /* Register fatal signal events before actually doing any real work for
221      * poll_block. */
222     fatal_signal_wait();
223
224     if (loop->timeout_when == LLONG_MIN) {
225         COVERAGE_INC(poll_zero_timeout);
226     }
227
228     retval = time_poll(loop->pollfds, loop->n_waiters,
229                        loop->timeout_when, &elapsed);
230     if (retval < 0) {
231         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
232         VLOG_ERR_RL(&rl, "poll: %s", ovs_strerror(-retval));
233     } else if (!retval) {
234         log_wakeup(loop->timeout_where, NULL, elapsed);
235     } else if (get_cpu_usage() > 50 || VLOG_IS_DBG_ENABLED()) {
236         size_t i;
237
238         for (i = 0; i < loop->n_waiters; i++) {
239             if (loop->pollfds[i].revents) {
240                 log_wakeup(loop->where[i], &loop->pollfds[i], 0);
241             }
242         }
243     }
244
245     loop->timeout_when = LLONG_MAX;
246     loop->timeout_where = NULL;
247     loop->n_waiters = 0;
248
249     /* Handle any pending signals before doing anything else. */
250     fatal_signal_run();
251 }
252 \f
253 static void
254 free_poll_loop(void *loop_)
255 {
256     struct poll_loop *loop = loop_;
257
258     free(loop->pollfds);
259     free(loop->where);
260     free(loop);
261 }
262
263 static struct poll_loop *
264 poll_loop(void)
265 {
266     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
267     static pthread_key_t key;
268     struct poll_loop *loop;
269
270     if (ovsthread_once_start(&once)) {
271         xpthread_key_create(&key, free_poll_loop);
272         ovsthread_once_done(&once);
273     }
274
275     loop = pthread_getspecific(key);
276     if (!loop) {
277         loop = xzalloc(sizeof *loop);
278         pthread_setspecific(key, loop);
279     }
280     return loop;
281 }
282