sync with latest
[sdk/emulator/qemu.git] / main-loop.c
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24
25 #include "qemu-common.h"
26 #include "qemu-timer.h"
27 #include "slirp/slirp.h"
28 #include "main-loop.h"
29
30 #ifndef _WIN32
31
32 #include "compatfd.h"
33
34 static int io_thread_fd = -1;
35
36 void qemu_notify_event(void)
37 {
38     /* Write 8 bytes to be compatible with eventfd.  */
39     static const uint64_t val = 1;
40     ssize_t ret;
41
42     if (io_thread_fd == -1) {
43         return;
44     }
45
46     qemu_notify_hax_event();
47
48     do {
49         ret = write(io_thread_fd, &val, sizeof(val));
50     } while (ret < 0 && errno == EINTR);
51
52     /* EAGAIN is fine, a read must be pending.  */
53     if (ret < 0 && errno != EAGAIN) {
54         fprintf(stderr, "qemu_notify_event: write() failed: %s\n",
55                 strerror(errno));
56         exit(1);
57     }
58 }
59
60 static void qemu_event_read(void *opaque)
61 {
62     int fd = (intptr_t)opaque;
63     ssize_t len;
64     char buffer[512];
65
66     /* Drain the notify pipe.  For eventfd, only 8 bytes will be read.  */
67     do {
68         len = read(fd, buffer, sizeof(buffer));
69     } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
70 }
71
72 static int qemu_event_init(void)
73 {
74     int err;
75     int fds[2];
76
77     err = qemu_eventfd(fds);
78     if (err == -1) {
79         return -errno;
80     }
81     err = fcntl_setfl(fds[0], O_NONBLOCK);
82     if (err < 0) {
83         goto fail;
84     }
85     err = fcntl_setfl(fds[1], O_NONBLOCK);
86     if (err < 0) {
87         goto fail;
88     }
89     qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
90                          (void *)(intptr_t)fds[0]);
91
92     io_thread_fd = fds[1];
93     return 0;
94
95 fail:
96     close(fds[0]);
97     close(fds[1]);
98     return err;
99 }
100
101 /* If we have signalfd, we mask out the signals we want to handle and then
102  * use signalfd to listen for them.  We rely on whatever the current signal
103  * handler is to dispatch the signals when we receive them.
104  */
105 static void sigfd_handler(void *opaque)
106 {
107     int fd = (intptr_t)opaque;
108     struct qemu_signalfd_siginfo info;
109     struct sigaction action;
110     ssize_t len;
111
112     while (1) {
113         do {
114             len = read(fd, &info, sizeof(info));
115         } while (len == -1 && errno == EINTR);
116
117         if (len == -1 && errno == EAGAIN) {
118             break;
119         }
120
121         if (len != sizeof(info)) {
122             printf("read from sigfd returned %zd: %m\n", len);
123             return;
124         }
125
126         sigaction(info.ssi_signo, NULL, &action);
127         if ((action.sa_flags & SA_SIGINFO) && action.sa_sigaction) {
128             action.sa_sigaction(info.ssi_signo,
129                                 (siginfo_t *)&info, NULL);
130         } else if (action.sa_handler) {
131             action.sa_handler(info.ssi_signo);
132         }
133     }
134 }
135
136 static int qemu_signal_init(void)
137 {
138     int sigfd;
139     sigset_t set;
140
141     /*
142      * SIG_IPI must be blocked in the main thread and must not be caught
143      * by sigwait() in the signal thread. Otherwise, the cpu thread will
144      * not catch it reliably.
145      */
146     sigemptyset(&set);
147     sigaddset(&set, SIG_IPI);
148     sigaddset(&set, SIGIO);
149     sigaddset(&set, SIGALRM);
150     sigaddset(&set, SIGBUS);
151     pthread_sigmask(SIG_BLOCK, &set, NULL);
152
153     sigdelset(&set, SIG_IPI);
154     sigfd = qemu_signalfd(&set);
155     if (sigfd == -1) {
156         fprintf(stderr, "failed to create signalfd\n");
157         return -errno;
158     }
159
160     fcntl_setfl(sigfd, O_NONBLOCK);
161
162     qemu_set_fd_handler2(sigfd, NULL, sigfd_handler, NULL,
163                          (void *)(intptr_t)sigfd);
164
165     return 0;
166 }
167
168 #else /* _WIN32 */
169
170 static HANDLE qemu_event_handle = NULL;
171
172 static void dummy_event_handler(void *opaque)
173 {
174 }
175
176 static int qemu_event_init(void)
177 {
178     qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
179     if (!qemu_event_handle) {
180         fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
181         return -1;
182     }
183     qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
184     return 0;
185 }
186
187 void qemu_notify_event(void)
188 {
189     if (!qemu_event_handle) {
190         return;
191     }
192
193     qemu_notify_hax_event();
194
195     if (!SetEvent(qemu_event_handle)) {
196         fprintf(stderr, "qemu_notify_event: SetEvent failed: %ld\n",
197                 GetLastError());
198         exit(1);
199     }
200 }
201
202 static int qemu_signal_init(void)
203 {
204     return 0;
205 }
206 #endif
207
208 int main_loop_init(void)
209 {
210     int ret;
211
212     qemu_mutex_lock_iothread();
213     ret = qemu_signal_init();
214     if (ret) {
215         return ret;
216     }
217
218     /* Note eventfd must be drained before signalfd handlers run */
219     ret = qemu_event_init();
220     if (ret) {
221         return ret;
222     }
223
224     return 0;
225 }
226
227 static fd_set rfds, wfds, xfds;
228 static int nfds;
229 static GPollFD poll_fds[1024 * 2]; /* this is probably overkill */
230 static int n_poll_fds;
231 static int max_priority;
232
233 #ifndef _WIN32
234 static void glib_select_fill(int *max_fd, fd_set *rfds, fd_set *wfds,
235                              fd_set *xfds, uint32_t *cur_timeout)
236 {
237     GMainContext *context = g_main_context_default();
238     int i;
239     int timeout = 0;
240
241     g_main_context_prepare(context, &max_priority);
242
243     n_poll_fds = g_main_context_query(context, max_priority, &timeout,
244                                       poll_fds, ARRAY_SIZE(poll_fds));
245     g_assert(n_poll_fds <= ARRAY_SIZE(poll_fds));
246
247     for (i = 0; i < n_poll_fds; i++) {
248         GPollFD *p = &poll_fds[i];
249
250         if ((p->events & G_IO_IN)) {
251             FD_SET(p->fd, rfds);
252             *max_fd = MAX(*max_fd, p->fd);
253         }
254         if ((p->events & G_IO_OUT)) {
255             FD_SET(p->fd, wfds);
256             *max_fd = MAX(*max_fd, p->fd);
257         }
258         if ((p->events & G_IO_ERR)) {
259             FD_SET(p->fd, xfds);
260             *max_fd = MAX(*max_fd, p->fd);
261         }
262     }
263
264     if (timeout >= 0 && timeout < *cur_timeout) {
265         *cur_timeout = timeout;
266     }
267 }
268
269 static void glib_select_poll(fd_set *rfds, fd_set *wfds, fd_set *xfds,
270                              bool err)
271 {
272     GMainContext *context = g_main_context_default();
273
274     if (!err) {
275         int i;
276
277         for (i = 0; i < n_poll_fds; i++) {
278             GPollFD *p = &poll_fds[i];
279
280             if ((p->events & G_IO_IN) && FD_ISSET(p->fd, rfds)) {
281                 p->revents |= G_IO_IN;
282             }
283             if ((p->events & G_IO_OUT) && FD_ISSET(p->fd, wfds)) {
284                 p->revents |= G_IO_OUT;
285             }
286             if ((p->events & G_IO_ERR) && FD_ISSET(p->fd, xfds)) {
287                 p->revents |= G_IO_ERR;
288             }
289         }
290     }
291
292     if (g_main_context_check(context, max_priority, poll_fds, n_poll_fds)) {
293         g_main_context_dispatch(context);
294     }
295 }
296
297 static int os_host_main_loop_wait(uint32_t timeout)
298 {
299     struct timeval tv, *tvarg = NULL;
300     int ret;
301
302     glib_select_fill(&nfds, &rfds, &wfds, &xfds, &timeout);
303
304     if (timeout < UINT32_MAX) {
305         tvarg = &tv;
306         tv.tv_sec = timeout / 1000;
307         tv.tv_usec = (timeout % 1000) * 1000;
308     }
309
310     if (timeout > 0) {
311         qemu_mutex_unlock_iothread();
312     }
313
314     ret = select(nfds + 1, &rfds, &wfds, &xfds, tvarg);
315
316     if (timeout > 0) {
317         qemu_mutex_lock_iothread();
318     }
319
320     glib_select_poll(&rfds, &wfds, &xfds, (ret < 0));
321     return ret;
322 }
323 #else
324 /***********************************************************/
325 /* Polling handling */
326
327 typedef struct PollingEntry {
328     PollingFunc *func;
329     void *opaque;
330     struct PollingEntry *next;
331 } PollingEntry;
332
333 static PollingEntry *first_polling_entry;
334
335 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
336 {
337     PollingEntry **ppe, *pe;
338     pe = g_malloc0(sizeof(PollingEntry));
339     pe->func = func;
340     pe->opaque = opaque;
341     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
342     *ppe = pe;
343     return 0;
344 }
345
346 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
347 {
348     PollingEntry **ppe, *pe;
349     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
350         pe = *ppe;
351         if (pe->func == func && pe->opaque == opaque) {
352             *ppe = pe->next;
353             g_free(pe);
354             break;
355         }
356     }
357 }
358
359 /***********************************************************/
360 /* Wait objects support */
361 typedef struct WaitObjects {
362     int num;
363     int revents[MAXIMUM_WAIT_OBJECTS + 1];
364     HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
365     WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
366     void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
367 } WaitObjects;
368
369 static WaitObjects wait_objects = {0};
370
371 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
372 {
373     WaitObjects *w = &wait_objects;
374     if (w->num >= MAXIMUM_WAIT_OBJECTS) {
375         return -1;
376     }
377     w->events[w->num] = handle;
378     w->func[w->num] = func;
379     w->opaque[w->num] = opaque;
380     w->revents[w->num] = 0;
381     w->num++;
382     return 0;
383 }
384
385 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
386 {
387     int i, found;
388     WaitObjects *w = &wait_objects;
389
390     found = 0;
391     for (i = 0; i < w->num; i++) {
392         if (w->events[i] == handle) {
393             found = 1;
394         }
395         if (found) {
396             w->events[i] = w->events[i + 1];
397             w->func[i] = w->func[i + 1];
398             w->opaque[i] = w->opaque[i + 1];
399             w->revents[i] = w->revents[i + 1];
400         }
401     }
402     if (found) {
403         w->num--;
404     }
405 }
406
407 void qemu_fd_register(int fd)
408 {
409     WSAEventSelect(fd, qemu_event_handle, FD_READ | FD_ACCEPT | FD_CLOSE |
410                    FD_CONNECT | FD_WRITE | FD_OOB);
411 }
412
413 static int os_host_main_loop_wait(uint32_t timeout)
414 {
415     GMainContext *context = g_main_context_default();
416     int ret, i;
417     PollingEntry *pe;
418     WaitObjects *w = &wait_objects;
419     gint poll_timeout;
420     static struct timeval tv0;
421
422     /* XXX: need to suppress polling by better using win32 events */
423     ret = 0;
424     for (pe = first_polling_entry; pe != NULL; pe = pe->next) {
425         ret |= pe->func(pe->opaque);
426     }
427     if (ret != 0) {
428         return ret;
429     }
430
431     if (nfds >= 0) {
432         ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv0);
433         if (ret != 0) {
434             timeout = 0;
435         }
436     }
437
438     g_main_context_prepare(context, &max_priority);
439     n_poll_fds = g_main_context_query(context, max_priority, &poll_timeout,
440                                       poll_fds, ARRAY_SIZE(poll_fds));
441     g_assert(n_poll_fds <= ARRAY_SIZE(poll_fds));
442
443     for (i = 0; i < w->num; i++) {
444         poll_fds[n_poll_fds + i].fd = (DWORD_PTR)w->events[i];
445         poll_fds[n_poll_fds + i].events = G_IO_IN;
446     }
447
448     if (poll_timeout < 0 || timeout < poll_timeout) {
449         poll_timeout = timeout;
450     }
451
452     qemu_mutex_unlock_iothread();
453     ret = g_poll(poll_fds, n_poll_fds + w->num, poll_timeout);
454     qemu_mutex_lock_iothread();
455     if (ret > 0) {
456         for (i = 0; i < w->num; i++) {
457             w->revents[i] = poll_fds[n_poll_fds + i].revents;
458         }
459         for (i = 0; i < w->num; i++) {
460             if (w->revents[i] && w->func[i]) {
461                 w->func[i](w->opaque[i]);
462             }
463         }
464     }
465
466     if (g_main_context_check(context, max_priority, poll_fds, n_poll_fds)) {
467         g_main_context_dispatch(context);
468     }
469
470     /* If an edge-triggered socket event occurred, select will return a
471      * positive result on the next iteration.  We do not need to do anything
472      * here.
473      */
474
475     return ret;
476 }
477 #endif
478
479 int main_loop_wait(int nonblocking)
480 {
481     int ret;
482     uint32_t timeout = UINT32_MAX;
483
484     if (nonblocking) {
485         timeout = 0;
486     } else {
487         qemu_bh_update_timeout(&timeout);
488     }
489
490     /* poll any events */
491     /* XXX: separate device handlers from system ones */
492     nfds = -1;
493     FD_ZERO(&rfds);
494     FD_ZERO(&wfds);
495     FD_ZERO(&xfds);
496
497 #ifdef CONFIG_SLIRP
498     slirp_update_timeout(&timeout);
499     slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
500 #endif
501     qemu_iohandler_fill(&nfds, &rfds, &wfds, &xfds);
502     ret = os_host_main_loop_wait(timeout);
503     qemu_iohandler_poll(&rfds, &wfds, &xfds, ret);
504 #ifdef CONFIG_SLIRP
505     slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
506 #endif
507
508     qemu_run_all_timers();
509
510     /* Check bottom-halves last in case any of the earlier events triggered
511        them.  */
512     qemu_bh_poll();
513
514     return ret;
515 }