Refactor some hax related codes.
[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 "qemu/main-loop.h"
29 #include "block/aio.h"
30
31 #include "sysemu/hax.h"
32
33 #ifndef _WIN32
34
35 #include "qemu/compatfd.h"
36
37 /* If we have signalfd, we mask out the signals we want to handle and then
38  * use signalfd to listen for them.  We rely on whatever the current signal
39  * handler is to dispatch the signals when we receive them.
40  */
41 static void sigfd_handler(void *opaque)
42 {
43     int fd = (intptr_t)opaque;
44     struct qemu_signalfd_siginfo info;
45     struct sigaction action;
46     ssize_t len;
47
48     while (1) {
49         do {
50             len = read(fd, &info, sizeof(info));
51         } while (len == -1 && errno == EINTR);
52
53         if (len == -1 && errno == EAGAIN) {
54             break;
55         }
56
57         if (len != sizeof(info)) {
58             printf("read from sigfd returned %zd: %m\n", len);
59             return;
60         }
61
62         sigaction(info.ssi_signo, NULL, &action);
63         if ((action.sa_flags & SA_SIGINFO) && action.sa_sigaction) {
64             action.sa_sigaction(info.ssi_signo,
65                                 (siginfo_t *)&info, NULL);
66         } else if (action.sa_handler) {
67             action.sa_handler(info.ssi_signo);
68         }
69     }
70 }
71
72 static int qemu_signal_init(void)
73 {
74     int sigfd;
75     sigset_t set;
76
77     /*
78      * SIG_IPI must be blocked in the main thread and must not be caught
79      * by sigwait() in the signal thread. Otherwise, the cpu thread will
80      * not catch it reliably.
81      */
82     sigemptyset(&set);
83     sigaddset(&set, SIG_IPI);
84     sigaddset(&set, SIGIO);
85     sigaddset(&set, SIGALRM);
86     sigaddset(&set, SIGBUS);
87     pthread_sigmask(SIG_BLOCK, &set, NULL);
88
89     sigdelset(&set, SIG_IPI);
90     sigfd = qemu_signalfd(&set);
91     if (sigfd == -1) {
92         fprintf(stderr, "failed to create signalfd\n");
93         return -errno;
94     }
95
96     fcntl_setfl(sigfd, O_NONBLOCK);
97
98     qemu_set_fd_handler2(sigfd, NULL, sigfd_handler, NULL,
99                          (void *)(intptr_t)sigfd);
100
101     return 0;
102 }
103
104 #else /* _WIN32 */
105
106 static int qemu_signal_init(void)
107 {
108     return 0;
109 }
110 #endif
111
112 static AioContext *qemu_aio_context;
113
114 AioContext *qemu_get_aio_context(void)
115 {
116     return qemu_aio_context;
117 }
118
119 #ifdef CONFIG_HAX
120 static void qemu_notify_hax_event(void)
121 {
122    CPUArchState *env = NULL;
123
124    if (hax_enabled()) {
125        for (env = first_cpu; env != NULL; env = env->next_cpu) {
126            hax_raise_event(env);
127        }
128    }
129 }
130 #endif
131
132 void qemu_notify_event(void)
133 {
134     if (!qemu_aio_context) {
135         return;
136     }
137 #ifdef CONFIG_HAX
138     qemu_notify_hax_event();
139 #endif
140     aio_notify(qemu_aio_context);
141 }
142
143 static GArray *gpollfds;
144
145 int qemu_init_main_loop(void)
146 {
147     int ret;
148     GSource *src;
149
150     init_clocks();
151     if (init_timer_alarm() < 0) {
152         fprintf(stderr, "could not initialize alarm timer\n");
153         exit(1);
154     }
155
156     ret = qemu_signal_init();
157     if (ret) {
158         return ret;
159     }
160
161     gpollfds = g_array_new(FALSE, FALSE, sizeof(GPollFD));
162     qemu_aio_context = aio_context_new();
163     src = aio_get_g_source(qemu_aio_context);
164     g_source_attach(src, NULL);
165     g_source_unref(src);
166     return 0;
167 }
168
169 static int max_priority;
170
171 #ifndef _WIN32
172 static int glib_pollfds_idx;
173 static int glib_n_poll_fds;
174
175 static void glib_pollfds_fill(uint32_t *cur_timeout)
176 {
177     GMainContext *context = g_main_context_default();
178     int timeout = 0;
179     int n;
180
181     g_main_context_prepare(context, &max_priority);
182
183     glib_pollfds_idx = gpollfds->len;
184     n = glib_n_poll_fds;
185     do {
186         GPollFD *pfds;
187         glib_n_poll_fds = n;
188         g_array_set_size(gpollfds, glib_pollfds_idx + glib_n_poll_fds);
189         pfds = &g_array_index(gpollfds, GPollFD, glib_pollfds_idx);
190         n = g_main_context_query(context, max_priority, &timeout, pfds,
191                                  glib_n_poll_fds);
192     } while (n != glib_n_poll_fds);
193
194     if (timeout >= 0 && timeout < *cur_timeout) {
195         *cur_timeout = timeout;
196     }
197 }
198
199 static void glib_pollfds_poll(void)
200 {
201     GMainContext *context = g_main_context_default();
202     GPollFD *pfds = &g_array_index(gpollfds, GPollFD, glib_pollfds_idx);
203
204     if (g_main_context_check(context, max_priority, pfds, glib_n_poll_fds)) {
205         g_main_context_dispatch(context);
206     }
207 }
208
209 #define MAX_MAIN_LOOP_SPIN (1000)
210
211 static int os_host_main_loop_wait(uint32_t timeout)
212 {
213     int ret;
214     static int spin_counter;
215
216     glib_pollfds_fill(&timeout);
217
218     /* If the I/O thread is very busy or we are incorrectly busy waiting in
219      * the I/O thread, this can lead to starvation of the BQL such that the
220      * VCPU threads never run.  To make sure we can detect the later case,
221      * print a message to the screen.  If we run into this condition, create
222      * a fake timeout in order to give the VCPU threads a chance to run.
223      */
224     if (spin_counter > MAX_MAIN_LOOP_SPIN) {
225         static bool notified;
226
227         if (!notified) {
228             fprintf(stderr,
229                     "main-loop: WARNING: I/O thread spun for %d iterations\n",
230                     MAX_MAIN_LOOP_SPIN);
231             notified = true;
232         }
233
234         timeout = 1;
235     }
236
237     if (timeout > 0) {
238         spin_counter = 0;
239         qemu_mutex_unlock_iothread();
240     } else {
241         spin_counter++;
242     }
243
244     ret = g_poll((GPollFD *)gpollfds->data, gpollfds->len, timeout);
245
246     if (timeout > 0) {
247         qemu_mutex_lock_iothread();
248     }
249
250     glib_pollfds_poll();
251     return ret;
252 }
253 #else
254 /***********************************************************/
255 /* Polling handling */
256
257 typedef struct PollingEntry {
258     PollingFunc *func;
259     void *opaque;
260     struct PollingEntry *next;
261 } PollingEntry;
262
263 static PollingEntry *first_polling_entry;
264
265 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
266 {
267     PollingEntry **ppe, *pe;
268     pe = g_malloc0(sizeof(PollingEntry));
269     pe->func = func;
270     pe->opaque = opaque;
271     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
272     *ppe = pe;
273     return 0;
274 }
275
276 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
277 {
278     PollingEntry **ppe, *pe;
279     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
280         pe = *ppe;
281         if (pe->func == func && pe->opaque == opaque) {
282             *ppe = pe->next;
283             g_free(pe);
284             break;
285         }
286     }
287 }
288
289 /***********************************************************/
290 /* Wait objects support */
291 typedef struct WaitObjects {
292     int num;
293     int revents[MAXIMUM_WAIT_OBJECTS + 1];
294     HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
295     WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
296     void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
297 } WaitObjects;
298
299 static WaitObjects wait_objects = {0};
300
301 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
302 {
303     WaitObjects *w = &wait_objects;
304     if (w->num >= MAXIMUM_WAIT_OBJECTS) {
305         return -1;
306     }
307     w->events[w->num] = handle;
308     w->func[w->num] = func;
309     w->opaque[w->num] = opaque;
310     w->revents[w->num] = 0;
311     w->num++;
312     return 0;
313 }
314
315 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
316 {
317     int i, found;
318     WaitObjects *w = &wait_objects;
319
320     found = 0;
321     for (i = 0; i < w->num; i++) {
322         if (w->events[i] == handle) {
323             found = 1;
324         }
325         if (found) {
326             w->events[i] = w->events[i + 1];
327             w->func[i] = w->func[i + 1];
328             w->opaque[i] = w->opaque[i + 1];
329             w->revents[i] = w->revents[i + 1];
330         }
331     }
332     if (found) {
333         w->num--;
334     }
335 }
336
337 void qemu_fd_register(int fd)
338 {
339     WSAEventSelect(fd, event_notifier_get_handle(&qemu_aio_context->notifier),
340                    FD_READ | FD_ACCEPT | FD_CLOSE |
341                    FD_CONNECT | FD_WRITE | FD_OOB);
342 }
343
344 static int pollfds_fill(GArray *pollfds, fd_set *rfds, fd_set *wfds,
345                         fd_set *xfds)
346 {
347     int nfds = -1;
348     int i;
349
350     for (i = 0; i < pollfds->len; i++) {
351         GPollFD *pfd = &g_array_index(pollfds, GPollFD, i);
352         int fd = pfd->fd;
353         int events = pfd->events;
354         if (events & G_IO_IN) {
355             FD_SET(fd, rfds);
356             nfds = MAX(nfds, fd);
357         }
358         if (events & G_IO_OUT) {
359             FD_SET(fd, wfds);
360             nfds = MAX(nfds, fd);
361         }
362         if (events & G_IO_PRI) {
363             FD_SET(fd, xfds);
364             nfds = MAX(nfds, fd);
365         }
366     }
367     return nfds;
368 }
369
370 static void pollfds_poll(GArray *pollfds, int nfds, fd_set *rfds,
371                          fd_set *wfds, fd_set *xfds)
372 {
373     int i;
374
375     for (i = 0; i < pollfds->len; i++) {
376         GPollFD *pfd = &g_array_index(pollfds, GPollFD, i);
377         int fd = pfd->fd;
378         int revents = 0;
379
380         if (FD_ISSET(fd, rfds)) {
381             revents |= G_IO_IN;
382         }
383         if (FD_ISSET(fd, wfds)) {
384             revents |= G_IO_OUT;
385         }
386         if (FD_ISSET(fd, xfds)) {
387             revents |= G_IO_PRI;
388         }
389         pfd->revents = revents & pfd->events;
390     }
391 }
392
393 static int os_host_main_loop_wait(uint32_t timeout)
394 {
395     GMainContext *context = g_main_context_default();
396     GPollFD poll_fds[1024 * 2]; /* this is probably overkill */
397     int select_ret = 0;
398     int g_poll_ret, ret, i, n_poll_fds;
399     PollingEntry *pe;
400     WaitObjects *w = &wait_objects;
401     gint poll_timeout;
402     static struct timeval tv0;
403     fd_set rfds, wfds, xfds;
404     int nfds;
405
406     /* XXX: need to suppress polling by better using win32 events */
407     ret = 0;
408     for (pe = first_polling_entry; pe != NULL; pe = pe->next) {
409         ret |= pe->func(pe->opaque);
410     }
411     if (ret != 0) {
412         return ret;
413     }
414
415     FD_ZERO(&rfds);
416     FD_ZERO(&wfds);
417     FD_ZERO(&xfds);
418     nfds = pollfds_fill(gpollfds, &rfds, &wfds, &xfds);
419     if (nfds >= 0) {
420         select_ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv0);
421         if (select_ret != 0) {
422             timeout = 0;
423         }
424         if (select_ret > 0) {
425             pollfds_poll(gpollfds, nfds, &rfds, &wfds, &xfds);
426         }
427     }
428
429     g_main_context_prepare(context, &max_priority);
430     n_poll_fds = g_main_context_query(context, max_priority, &poll_timeout,
431                                       poll_fds, ARRAY_SIZE(poll_fds));
432     g_assert(n_poll_fds <= ARRAY_SIZE(poll_fds));
433
434     for (i = 0; i < w->num; i++) {
435         poll_fds[n_poll_fds + i].fd = (DWORD_PTR)w->events[i];
436         poll_fds[n_poll_fds + i].events = G_IO_IN;
437     }
438
439     if (poll_timeout < 0 || timeout < poll_timeout) {
440         poll_timeout = timeout;
441     }
442
443     qemu_mutex_unlock_iothread();
444     g_poll_ret = g_poll(poll_fds, n_poll_fds + w->num, poll_timeout);
445     qemu_mutex_lock_iothread();
446     if (g_poll_ret > 0) {
447         for (i = 0; i < w->num; i++) {
448             w->revents[i] = poll_fds[n_poll_fds + i].revents;
449         }
450         for (i = 0; i < w->num; i++) {
451             if (w->revents[i] && w->func[i]) {
452                 w->func[i](w->opaque[i]);
453             }
454         }
455     }
456
457     if (g_main_context_check(context, max_priority, poll_fds, n_poll_fds)) {
458         g_main_context_dispatch(context);
459     }
460
461     return select_ret || g_poll_ret;
462 }
463 #endif
464
465 int main_loop_wait(int nonblocking)
466 {
467     int ret;
468     uint32_t timeout = UINT32_MAX;
469
470     if (nonblocking) {
471         timeout = 0;
472     }
473
474     /* poll any events */
475     g_array_set_size(gpollfds, 0); /* reset for new iteration */
476     /* XXX: separate device handlers from system ones */
477 #ifdef CONFIG_SLIRP
478     slirp_update_timeout(&timeout);
479     slirp_pollfds_fill(gpollfds);
480 #endif
481     qemu_iohandler_fill(gpollfds);
482     ret = os_host_main_loop_wait(timeout);
483     qemu_iohandler_poll(gpollfds, ret);
484 #ifdef CONFIG_SLIRP
485     slirp_pollfds_poll(gpollfds, (ret < 0));
486 #endif
487
488     qemu_run_all_timers();
489
490     return ret;
491 }
492
493 /* Functions to operate on the main QEMU AioContext.  */
494
495 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
496 {
497     return aio_bh_new(qemu_aio_context, cb, opaque);
498 }
499
500 bool qemu_aio_wait(void)
501 {
502     return aio_poll(qemu_aio_context, true);
503 }
504
505 #ifdef CONFIG_POSIX
506 void qemu_aio_set_fd_handler(int fd,
507                              IOHandler *io_read,
508                              IOHandler *io_write,
509                              AioFlushHandler *io_flush,
510                              void *opaque)
511 {
512     aio_set_fd_handler(qemu_aio_context, fd, io_read, io_write, io_flush,
513                        opaque);
514 }
515 #endif
516
517 void qemu_aio_set_event_notifier(EventNotifier *notifier,
518                                  EventNotifierHandler *io_read,
519                                  AioFlushEventNotifierHandler *io_flush)
520 {
521     aio_set_event_notifier(qemu_aio_context, notifier, io_read, io_flush);
522 }