fatal-signal: Run signal hooks outside of actual signal handlers.
[sliver-openvswitch.git] / lib / poll-loop.c
1 /*
2  * Copyright (c) 2008, 2009 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 "backtrace.h"
26 #include "coverage.h"
27 #include "dynamic-string.h"
28 #include "fatal-signal.h"
29 #include "list.h"
30 #include "timeval.h"
31
32 #define THIS_MODULE VLM_poll_loop
33 #include "vlog.h"
34
35 /* An event that will wake the following call to poll_block(). */
36 struct poll_waiter {
37     /* Set when the waiter is created. */
38     struct list node;           /* Element in global waiters list. */
39     int fd;                     /* File descriptor. */
40     short int events;           /* Events to wait for (POLLIN, POLLOUT). */
41     poll_fd_func *function;     /* Callback function, if any, or null. */
42     void *aux;                  /* Argument to callback function. */
43     struct backtrace *backtrace; /* Optionally, event that created waiter. */
44
45     /* Set only when poll_block() is called. */
46     struct pollfd *pollfd;      /* Pointer to element of the pollfds array
47                                    (null if added from a callback). */
48 };
49
50 /* All active poll waiters. */
51 static struct list waiters = LIST_INITIALIZER(&waiters);
52
53 /* Number of elements in the waiters list. */
54 static size_t n_waiters;
55
56 /* Max time to wait in next call to poll_block(), in milliseconds, or -1 to
57  * wait forever. */
58 static int timeout = -1;
59
60 /* Backtrace of 'timeout''s registration, if debugging is enabled. */
61 static struct backtrace timeout_backtrace;
62
63 /* Callback currently running, to allow verifying that poll_cancel() is not
64  * being called on a running callback. */
65 #ifndef NDEBUG
66 static struct poll_waiter *running_cb;
67 #endif
68
69 static struct poll_waiter *new_waiter(int fd, short int events);
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 struct poll_waiter *
79 poll_fd_wait(int fd, short int events)
80 {
81     COVERAGE_INC(poll_fd_wait);
82     return new_waiter(fd, events);
83 }
84
85 /* Causes the following call to poll_block() to block for no more than 'msec'
86  * milliseconds.  If 'msec' is nonpositive, the following call to poll_block()
87  * will not block at all.
88  *
89  * The timer registration is one-shot: only the following call to poll_block()
90  * is affected.  The timer will need to be re-registered after poll_block() is
91  * called if it is to persist. */
92 void
93 poll_timer_wait(int msec)
94 {
95     if (timeout < 0 || msec < timeout) {
96         timeout = MAX(0, msec);
97         if (VLOG_IS_DBG_ENABLED()) {
98             backtrace_capture(&timeout_backtrace);
99         }
100     }
101 }
102
103 /* Causes the following call to poll_block() to wake up immediately, without
104  * blocking. */
105 void
106 poll_immediate_wake(void)
107 {
108     poll_timer_wait(0);
109 }
110
111 static void PRINTF_FORMAT(2, 3)
112 log_wakeup(const struct backtrace *backtrace, const char *format, ...)
113 {
114     struct ds ds;
115     va_list args;
116
117     ds_init(&ds);
118     va_start(args, format);
119     ds_put_format_valist(&ds, format, args);
120     va_end(args);
121
122     if (backtrace) {
123         int i;
124
125         ds_put_char(&ds, ':');
126         for (i = 0; i < backtrace->n_frames; i++) {
127             ds_put_format(&ds, " 0x%"PRIxPTR, backtrace->frames[i]);
128         }
129     }
130     VLOG_DBG("%s", ds_cstr(&ds));
131     ds_destroy(&ds);
132 }
133
134 /* Blocks until one or more of the events registered with poll_fd_wait()
135  * occurs, or until the minimum duration registered with poll_timer_wait()
136  * elapses, or not at all if poll_immediate_wake() has been called.
137  *
138  * Also executes any autonomous subroutines registered with poll_fd_callback(),
139  * if their file descriptors have become ready. */
140 void
141 poll_block(void)
142 {
143     static struct pollfd *pollfds;
144     static size_t max_pollfds;
145
146     struct poll_waiter *pw;
147     struct list *node;
148     int n_pollfds;
149     int retval;
150
151     /* Register fatal signal events before actually doing any real work for
152      * poll_block. */
153     fatal_signal_wait();
154
155     assert(!running_cb);
156     if (max_pollfds < n_waiters) {
157         max_pollfds = n_waiters;
158         pollfds = xrealloc(pollfds, max_pollfds * sizeof *pollfds);
159     }
160
161     n_pollfds = 0;
162     LIST_FOR_EACH (pw, struct poll_waiter, node, &waiters) {
163         pw->pollfd = &pollfds[n_pollfds];
164         pollfds[n_pollfds].fd = pw->fd;
165         pollfds[n_pollfds].events = pw->events;
166         pollfds[n_pollfds].revents = 0;
167         n_pollfds++;
168     }
169
170     if (!timeout) {
171         COVERAGE_INC(poll_zero_timeout);
172     }
173     retval = time_poll(pollfds, n_pollfds, timeout);
174     if (retval < 0) {
175         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
176         VLOG_ERR_RL(&rl, "poll: %s", strerror(-retval));
177     } else if (!retval && VLOG_IS_DBG_ENABLED()) {
178         log_wakeup(&timeout_backtrace, "%d-ms timeout", timeout);
179     }
180
181     for (node = waiters.next; node != &waiters; ) {
182         pw = CONTAINER_OF(node, struct poll_waiter, node);
183         if (!pw->pollfd || !pw->pollfd->revents) {
184             if (pw->function) {
185                 node = node->next;
186                 continue;
187             }
188         } else {
189             if (VLOG_IS_DBG_ENABLED()) {
190                 log_wakeup(pw->backtrace, "%s%s%s%s%s on fd %d",
191                            pw->pollfd->revents & POLLIN ? "[POLLIN]" : "",
192                            pw->pollfd->revents & POLLOUT ? "[POLLOUT]" : "",
193                            pw->pollfd->revents & POLLERR ? "[POLLERR]" : "",
194                            pw->pollfd->revents & POLLHUP ? "[POLLHUP]" : "",
195                            pw->pollfd->revents & POLLNVAL ? "[POLLNVAL]" : "",
196                            pw->fd);
197             }
198
199             if (pw->function) {
200 #ifndef NDEBUG
201                 running_cb = pw;
202 #endif
203                 pw->function(pw->fd, pw->pollfd->revents, pw->aux);
204 #ifndef NDEBUG
205                 running_cb = NULL;
206 #endif
207             }
208         }
209         node = node->next;
210         poll_cancel(pw);
211     }
212
213     timeout = -1;
214     timeout_backtrace.n_frames = 0;
215
216     /* Handle any pending signals before doing anything else. */
217     fatal_signal_run();
218 }
219
220 /* Registers 'function' to be called with argument 'aux' by poll_block() when
221  * 'fd' becomes ready for one of the events in 'events', which should be POLLIN
222  * or POLLOUT or POLLIN | POLLOUT.
223  *
224  * The callback registration persists until the event actually occurs.  At that
225  * point, it is automatically de-registered.  The callback function must
226  * re-register the event by calling poll_fd_callback() again within the
227  * callback, if it wants to be called back again later. */
228 struct poll_waiter *
229 poll_fd_callback(int fd, short int events, poll_fd_func *function, void *aux)
230 {
231     struct poll_waiter *pw = new_waiter(fd, events);
232     pw->function = function;
233     pw->aux = aux;
234     return pw;
235 }
236
237 /* Cancels the file descriptor event registered with poll_fd_wait() or
238  * poll_fd_callback().  'pw' must be the struct poll_waiter returned by one of
239  * those functions.
240  *
241  * An event registered with poll_fd_wait() may be canceled from its time of
242  * registration until the next call to poll_block().  At that point, the event
243  * is automatically canceled by the system and its poll_waiter is freed.
244  *
245  * An event registered with poll_fd_callback() may be canceled from its time of
246  * registration until its callback is actually called.  At that point, the
247  * event is automatically canceled by the system and its poll_waiter is
248  * freed. */
249 void
250 poll_cancel(struct poll_waiter *pw)
251 {
252     if (pw) {
253         assert(pw != running_cb);
254         list_remove(&pw->node);
255         free(pw->backtrace);
256         free(pw);
257         n_waiters--;
258     }
259 }
260 \f
261 /* Creates and returns a new poll_waiter for 'fd' and 'events'. */
262 static struct poll_waiter *
263 new_waiter(int fd, short int events)
264 {
265     struct poll_waiter *waiter = xzalloc(sizeof *waiter);
266     assert(fd >= 0);
267     waiter->fd = fd;
268     waiter->events = events;
269     if (VLOG_IS_DBG_ENABLED()) {
270         waiter->backtrace = xmalloc(sizeof *waiter->backtrace);
271         backtrace_capture(waiter->backtrace);
272     }
273     list_push_back(&waiters, &waiter->node);
274     n_waiters++;
275     return waiter;
276 }