Merge remote-tracking branch 'bonzini/split-main-loop-for-anthony' into staging
[qemu.git] / main-loop.c
blobbfecdb776922d7a0f8e00a222f9d6389bebbf807
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "config-host.h"
25 #include <unistd.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <stdbool.h>
32 #ifdef _WIN32
33 #include <windows.h>
34 #include <winsock2.h>
35 #include <ws2tcpip.h>
36 #else
37 #include <sys/socket.h>
38 #include <netinet/in.h>
39 #include <net/if.h>
40 #include <arpa/inet.h>
41 #include <sys/select.h>
42 #include <sys/stat.h>
43 #include "compatfd.h"
44 #endif
46 #include <glib.h>
48 #include "main-loop.h"
49 #include "qemu-timer.h"
50 #include "slirp/libslirp.h"
52 #ifndef _WIN32
54 static int io_thread_fd = -1;
56 void qemu_notify_event(void)
58 /* Write 8 bytes to be compatible with eventfd. */
59 static const uint64_t val = 1;
60 ssize_t ret;
62 if (io_thread_fd == -1) {
63 return;
65 do {
66 ret = write(io_thread_fd, &val, sizeof(val));
67 } while (ret < 0 && errno == EINTR);
69 /* EAGAIN is fine, a read must be pending. */
70 if (ret < 0 && errno != EAGAIN) {
71 fprintf(stderr, "qemu_notify_event: write() failed: %s\n",
72 strerror(errno));
73 exit(1);
77 static void qemu_event_read(void *opaque)
79 int fd = (intptr_t)opaque;
80 ssize_t len;
81 char buffer[512];
83 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
84 do {
85 len = read(fd, buffer, sizeof(buffer));
86 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
89 static int qemu_event_init(void)
91 int err;
92 int fds[2];
94 err = qemu_eventfd(fds);
95 if (err == -1) {
96 return -errno;
98 err = fcntl_setfl(fds[0], O_NONBLOCK);
99 if (err < 0) {
100 goto fail;
102 err = fcntl_setfl(fds[1], O_NONBLOCK);
103 if (err < 0) {
104 goto fail;
106 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
107 (void *)(intptr_t)fds[0]);
109 io_thread_fd = fds[1];
110 return 0;
112 fail:
113 close(fds[0]);
114 close(fds[1]);
115 return err;
118 /* If we have signalfd, we mask out the signals we want to handle and then
119 * use signalfd to listen for them. We rely on whatever the current signal
120 * handler is to dispatch the signals when we receive them.
122 static void sigfd_handler(void *opaque)
124 int fd = (intptr_t)opaque;
125 struct qemu_signalfd_siginfo info;
126 struct sigaction action;
127 ssize_t len;
129 while (1) {
130 do {
131 len = read(fd, &info, sizeof(info));
132 } while (len == -1 && errno == EINTR);
134 if (len == -1 && errno == EAGAIN) {
135 break;
138 if (len != sizeof(info)) {
139 printf("read from sigfd returned %zd: %m\n", len);
140 return;
143 sigaction(info.ssi_signo, NULL, &action);
144 if ((action.sa_flags & SA_SIGINFO) && action.sa_sigaction) {
145 action.sa_sigaction(info.ssi_signo,
146 (siginfo_t *)&info, NULL);
147 } else if (action.sa_handler) {
148 action.sa_handler(info.ssi_signo);
153 static int qemu_signal_init(void)
155 int sigfd;
156 sigset_t set;
159 * SIG_IPI must be blocked in the main thread and must not be caught
160 * by sigwait() in the signal thread. Otherwise, the cpu thread will
161 * not catch it reliably.
163 sigemptyset(&set);
164 sigaddset(&set, SIG_IPI);
165 pthread_sigmask(SIG_BLOCK, &set, NULL);
167 sigemptyset(&set);
168 sigaddset(&set, SIGIO);
169 sigaddset(&set, SIGALRM);
170 sigaddset(&set, SIGBUS);
171 pthread_sigmask(SIG_BLOCK, &set, NULL);
173 sigfd = qemu_signalfd(&set);
174 if (sigfd == -1) {
175 fprintf(stderr, "failed to create signalfd\n");
176 return -errno;
179 fcntl_setfl(sigfd, O_NONBLOCK);
181 qemu_set_fd_handler2(sigfd, NULL, sigfd_handler, NULL,
182 (void *)(intptr_t)sigfd);
184 return 0;
187 #else /* _WIN32 */
189 HANDLE qemu_event_handle;
191 static void dummy_event_handler(void *opaque)
195 static int qemu_event_init(void)
197 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
198 if (!qemu_event_handle) {
199 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
200 return -1;
202 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
203 return 0;
206 void qemu_notify_event(void)
208 if (!SetEvent(qemu_event_handle)) {
209 fprintf(stderr, "qemu_notify_event: SetEvent failed: %ld\n",
210 GetLastError());
211 exit(1);
215 static int qemu_signal_init(void)
217 return 0;
219 #endif
221 int qemu_init_main_loop(void)
223 int ret;
225 qemu_mutex_lock_iothread();
226 ret = qemu_signal_init();
227 if (ret) {
228 return ret;
231 /* Note eventfd must be drained before signalfd handlers run */
232 ret = qemu_event_init();
233 if (ret) {
234 return ret;
237 return 0;
241 static GPollFD poll_fds[1024 * 2]; /* this is probably overkill */
242 static int n_poll_fds;
243 static int max_priority;
245 static void glib_select_fill(int *max_fd, fd_set *rfds, fd_set *wfds,
246 fd_set *xfds, struct timeval *tv)
248 GMainContext *context = g_main_context_default();
249 int i;
250 int timeout = 0, cur_timeout;
252 g_main_context_prepare(context, &max_priority);
254 n_poll_fds = g_main_context_query(context, max_priority, &timeout,
255 poll_fds, ARRAY_SIZE(poll_fds));
256 g_assert(n_poll_fds <= ARRAY_SIZE(poll_fds));
258 for (i = 0; i < n_poll_fds; i++) {
259 GPollFD *p = &poll_fds[i];
261 if ((p->events & G_IO_IN)) {
262 FD_SET(p->fd, rfds);
263 *max_fd = MAX(*max_fd, p->fd);
265 if ((p->events & G_IO_OUT)) {
266 FD_SET(p->fd, wfds);
267 *max_fd = MAX(*max_fd, p->fd);
269 if ((p->events & G_IO_ERR)) {
270 FD_SET(p->fd, xfds);
271 *max_fd = MAX(*max_fd, p->fd);
275 cur_timeout = (tv->tv_sec * 1000) + ((tv->tv_usec + 500) / 1000);
276 if (timeout >= 0 && timeout < cur_timeout) {
277 tv->tv_sec = timeout / 1000;
278 tv->tv_usec = (timeout % 1000) * 1000;
282 static void glib_select_poll(fd_set *rfds, fd_set *wfds, fd_set *xfds,
283 bool err)
285 GMainContext *context = g_main_context_default();
287 if (!err) {
288 int i;
290 for (i = 0; i < n_poll_fds; i++) {
291 GPollFD *p = &poll_fds[i];
293 if ((p->events & G_IO_IN) && FD_ISSET(p->fd, rfds)) {
294 p->revents |= G_IO_IN;
296 if ((p->events & G_IO_OUT) && FD_ISSET(p->fd, wfds)) {
297 p->revents |= G_IO_OUT;
299 if ((p->events & G_IO_ERR) && FD_ISSET(p->fd, xfds)) {
300 p->revents |= G_IO_ERR;
305 if (g_main_context_check(context, max_priority, poll_fds, n_poll_fds)) {
306 g_main_context_dispatch(context);
310 #ifdef _WIN32
311 /***********************************************************/
312 /* Polling handling */
314 typedef struct PollingEntry {
315 PollingFunc *func;
316 void *opaque;
317 struct PollingEntry *next;
318 } PollingEntry;
320 static PollingEntry *first_polling_entry;
322 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
324 PollingEntry **ppe, *pe;
325 pe = g_malloc0(sizeof(PollingEntry));
326 pe->func = func;
327 pe->opaque = opaque;
328 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
329 *ppe = pe;
330 return 0;
333 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
335 PollingEntry **ppe, *pe;
336 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
337 pe = *ppe;
338 if (pe->func == func && pe->opaque == opaque) {
339 *ppe = pe->next;
340 g_free(pe);
341 break;
346 /***********************************************************/
347 /* Wait objects support */
348 typedef struct WaitObjects {
349 int num;
350 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
351 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
352 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
353 } WaitObjects;
355 static WaitObjects wait_objects = {0};
357 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
359 WaitObjects *w = &wait_objects;
360 if (w->num >= MAXIMUM_WAIT_OBJECTS) {
361 return -1;
363 w->events[w->num] = handle;
364 w->func[w->num] = func;
365 w->opaque[w->num] = opaque;
366 w->num++;
367 return 0;
370 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
372 int i, found;
373 WaitObjects *w = &wait_objects;
375 found = 0;
376 for (i = 0; i < w->num; i++) {
377 if (w->events[i] == handle) {
378 found = 1;
380 if (found) {
381 w->events[i] = w->events[i + 1];
382 w->func[i] = w->func[i + 1];
383 w->opaque[i] = w->opaque[i + 1];
386 if (found) {
387 w->num--;
391 static void os_host_main_loop_wait(int *timeout)
393 int ret, ret2, i;
394 PollingEntry *pe;
396 /* XXX: need to suppress polling by better using win32 events */
397 ret = 0;
398 for (pe = first_polling_entry; pe != NULL; pe = pe->next) {
399 ret |= pe->func(pe->opaque);
401 if (ret == 0) {
402 int err;
403 WaitObjects *w = &wait_objects;
405 qemu_mutex_unlock_iothread();
406 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
407 qemu_mutex_lock_iothread();
408 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
409 if (w->func[ret - WAIT_OBJECT_0]) {
410 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
413 /* Check for additional signaled events */
414 for (i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
415 /* Check if event is signaled */
416 ret2 = WaitForSingleObject(w->events[i], 0);
417 if (ret2 == WAIT_OBJECT_0) {
418 if (w->func[i]) {
419 w->func[i](w->opaque[i]);
421 } else if (ret2 != WAIT_TIMEOUT) {
422 err = GetLastError();
423 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
426 } else if (ret != WAIT_TIMEOUT) {
427 err = GetLastError();
428 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
432 *timeout = 0;
434 #else
435 static inline void os_host_main_loop_wait(int *timeout)
438 #endif
440 int main_loop_wait(int nonblocking)
442 fd_set rfds, wfds, xfds;
443 int ret, nfds;
444 struct timeval tv;
445 int timeout;
447 if (nonblocking) {
448 timeout = 0;
449 } else {
450 timeout = qemu_calculate_timeout();
451 qemu_bh_update_timeout(&timeout);
454 os_host_main_loop_wait(&timeout);
456 tv.tv_sec = timeout / 1000;
457 tv.tv_usec = (timeout % 1000) * 1000;
459 /* poll any events */
460 /* XXX: separate device handlers from system ones */
461 nfds = -1;
462 FD_ZERO(&rfds);
463 FD_ZERO(&wfds);
464 FD_ZERO(&xfds);
466 #ifdef CONFIG_SLIRP
467 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
468 #endif
469 qemu_iohandler_fill(&nfds, &rfds, &wfds, &xfds);
470 glib_select_fill(&nfds, &rfds, &wfds, &xfds, &tv);
472 if (timeout > 0) {
473 qemu_mutex_unlock_iothread();
476 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
478 if (timeout > 0) {
479 qemu_mutex_lock_iothread();
482 glib_select_poll(&rfds, &wfds, &xfds, (ret < 0));
483 qemu_iohandler_poll(&rfds, &wfds, &xfds, ret);
484 #ifdef CONFIG_SLIRP
485 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
486 #endif
488 qemu_run_all_timers();
490 /* Check bottom-halves last in case any of the earlier events triggered
491 them. */
492 qemu_bh_poll();
494 return ret;