xref: /qemu/util/main-loop.c (revision cc944932ecef3b7a56ae62d89dd92fb9e56c5cc8)
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/osdep.h"
26 #include "qapi/error.h"
27 #include "qemu/cutils.h"
28 #include "qemu/timer.h"
29 #include "system/cpu-timers.h"
30 #include "exec/icount.h"
31 #include "system/replay.h"
32 #include "qemu/main-loop.h"
33 #include "block/aio.h"
34 #include "block/thread-pool.h"
35 #include "qemu/error-report.h"
36 #include "qemu/queue.h"
37 #include "qom/object.h"
38 
39 #ifndef _WIN32
40 #include <sys/wait.h>
41 #endif
42 
43 #ifndef _WIN32
44 
45 /* If we have signalfd, we mask out the signals we want to handle and then
46  * use signalfd to listen for them.  We rely on whatever the current signal
47  * handler is to dispatch the signals when we receive them.
48  */
49 /*
50  * Disable CFI checks.
51  * We are going to call a signal handler directly. Such handler may or may not
52  * have been defined in our binary, so there's no guarantee that the pointer
53  * used to set the handler is a cfi-valid pointer. Since the handlers are
54  * stored in kernel memory, changing the handler to an attacker-defined
55  * function requires being able to call a sigaction() syscall,
56  * which is not as easy as overwriting a pointer in memory.
57  */
58 QEMU_DISABLE_CFI
59 static void sigfd_handler(void *opaque)
60 {
61     int fd = (intptr_t)opaque;
62     struct qemu_signalfd_siginfo info;
63     struct sigaction action;
64     ssize_t len;
65 
66     while (1) {
67         len = RETRY_ON_EINTR(read(fd, &info, sizeof(info)));
68 
69         if (len == -1 && errno == EAGAIN) {
70             break;
71         }
72 
73         if (len != sizeof(info)) {
74             error_report("read from sigfd returned %zd: %s", len,
75                          g_strerror(errno));
76             return;
77         }
78 
79         sigaction(info.ssi_signo, NULL, &action);
80         if ((action.sa_flags & SA_SIGINFO) && action.sa_sigaction) {
81             sigaction_invoke(&action, &info);
82         } else if (action.sa_handler) {
83             action.sa_handler(info.ssi_signo);
84         }
85     }
86 }
87 
88 static int qemu_signal_init(Error **errp)
89 {
90     int sigfd;
91     sigset_t set;
92 
93     /*
94      * SIG_IPI must be blocked in the main thread and must not be caught
95      * by sigwait() in the signal thread. Otherwise, the cpu thread will
96      * not catch it reliably.
97      */
98     sigemptyset(&set);
99     sigaddset(&set, SIG_IPI);
100     sigaddset(&set, SIGIO);
101     sigaddset(&set, SIGALRM);
102     sigaddset(&set, SIGBUS);
103     /* SIGINT cannot be handled via signalfd, so that ^C can be used
104      * to interrupt QEMU when it is being run under gdb.  SIGHUP and
105      * SIGTERM are also handled asynchronously, even though it is not
106      * strictly necessary, because they use the same handler as SIGINT.
107      */
108     pthread_sigmask(SIG_BLOCK, &set, NULL);
109 
110     sigdelset(&set, SIG_IPI);
111     sigfd = qemu_signalfd(&set);
112     if (sigfd == -1) {
113         error_setg_errno(errp, errno, "failed to create signalfd");
114         return -errno;
115     }
116 
117     g_unix_set_fd_nonblocking(sigfd, true, NULL);
118 
119     qemu_set_fd_handler(sigfd, sigfd_handler, NULL, (void *)(intptr_t)sigfd);
120 
121     return 0;
122 }
123 
124 #else /* _WIN32 */
125 
126 static int qemu_signal_init(Error **errp)
127 {
128     return 0;
129 }
130 #endif
131 
132 static AioContext *qemu_aio_context;
133 static QEMUBH *qemu_notify_bh;
134 
135 static void notify_event_cb(void *opaque)
136 {
137     /* No need to do anything; this bottom half is only used to
138      * kick the kernel out of ppoll/poll/WaitForMultipleObjects.
139      */
140 }
141 
142 AioContext *qemu_get_aio_context(void)
143 {
144     return qemu_aio_context;
145 }
146 
147 void qemu_notify_event(void)
148 {
149     if (!qemu_aio_context) {
150         return;
151     }
152     qemu_bh_schedule(qemu_notify_bh);
153 }
154 
155 static GArray *gpollfds;
156 
157 int qemu_init_main_loop(Error **errp)
158 {
159     int ret;
160     GSource *src;
161 
162     init_clocks(qemu_timer_notify_cb);
163 
164     ret = qemu_signal_init(errp);
165     if (ret) {
166         return ret;
167     }
168 
169     qemu_aio_context = aio_context_new(errp);
170     if (!qemu_aio_context) {
171         return -EMFILE;
172     }
173     qemu_set_current_aio_context(qemu_aio_context);
174     qemu_notify_bh = qemu_bh_new(notify_event_cb, NULL);
175     gpollfds = g_array_new(FALSE, FALSE, sizeof(GPollFD));
176     src = aio_get_g_source(qemu_aio_context);
177     g_source_set_name(src, "aio-context");
178     g_source_attach(src, NULL);
179     g_source_unref(src);
180     src = iohandler_get_g_source();
181     g_source_set_name(src, "io-handler");
182     g_source_attach(src, NULL);
183     g_source_unref(src);
184     return 0;
185 }
186 
187 static void main_loop_update_params(EventLoopBase *base, Error **errp)
188 {
189     ERRP_GUARD();
190 
191     if (!qemu_aio_context) {
192         error_setg(errp, "qemu aio context not ready");
193         return;
194     }
195 
196     aio_context_set_aio_params(qemu_aio_context, base->aio_max_batch);
197 
198     aio_context_set_thread_pool_params(qemu_aio_context, base->thread_pool_min,
199                                        base->thread_pool_max, errp);
200 }
201 
202 MainLoop *mloop;
203 
204 static void main_loop_init(EventLoopBase *base, Error **errp)
205 {
206     MainLoop *m = MAIN_LOOP(base);
207 
208     if (mloop) {
209         error_setg(errp, "only one main-loop instance allowed");
210         return;
211     }
212 
213     main_loop_update_params(base, errp);
214 
215     mloop = m;
216     return;
217 }
218 
219 static bool main_loop_can_be_deleted(EventLoopBase *base)
220 {
221     return false;
222 }
223 
224 static void main_loop_class_init(ObjectClass *oc, void *class_data)
225 {
226     EventLoopBaseClass *bc = EVENT_LOOP_BASE_CLASS(oc);
227 
228     bc->init = main_loop_init;
229     bc->update_params = main_loop_update_params;
230     bc->can_be_deleted = main_loop_can_be_deleted;
231 }
232 
233 static const TypeInfo main_loop_info = {
234     .name = TYPE_MAIN_LOOP,
235     .parent = TYPE_EVENT_LOOP_BASE,
236     .class_init = main_loop_class_init,
237     .instance_size = sizeof(MainLoop),
238 };
239 
240 static void main_loop_register_types(void)
241 {
242     type_register_static(&main_loop_info);
243 }
244 
245 type_init(main_loop_register_types)
246 
247 static int max_priority;
248 
249 #ifndef _WIN32
250 static int glib_pollfds_idx;
251 static int glib_n_poll_fds;
252 
253 static void glib_pollfds_fill(int64_t *cur_timeout)
254 {
255     GMainContext *context = g_main_context_default();
256     int timeout = 0;
257     int64_t timeout_ns;
258     int n;
259 
260     g_main_context_prepare(context, &max_priority);
261 
262     glib_pollfds_idx = gpollfds->len;
263     n = glib_n_poll_fds;
264     do {
265         GPollFD *pfds;
266         glib_n_poll_fds = n;
267         g_array_set_size(gpollfds, glib_pollfds_idx + glib_n_poll_fds);
268         pfds = &g_array_index(gpollfds, GPollFD, glib_pollfds_idx);
269         n = g_main_context_query(context, max_priority, &timeout, pfds,
270                                  glib_n_poll_fds);
271     } while (n != glib_n_poll_fds);
272 
273     if (timeout < 0) {
274         timeout_ns = -1;
275     } else {
276         timeout_ns = (int64_t)timeout * (int64_t)SCALE_MS;
277     }
278 
279     *cur_timeout = qemu_soonest_timeout(timeout_ns, *cur_timeout);
280 }
281 
282 static void glib_pollfds_poll(void)
283 {
284     GMainContext *context = g_main_context_default();
285     GPollFD *pfds = &g_array_index(gpollfds, GPollFD, glib_pollfds_idx);
286 
287     if (g_main_context_check(context, max_priority, pfds, glib_n_poll_fds)) {
288         g_main_context_dispatch(context);
289     }
290 }
291 
292 #define MAX_MAIN_LOOP_SPIN (1000)
293 
294 static int os_host_main_loop_wait(int64_t timeout)
295 {
296     GMainContext *context = g_main_context_default();
297     int ret;
298 
299     g_main_context_acquire(context);
300 
301     glib_pollfds_fill(&timeout);
302 
303     bql_unlock();
304     replay_mutex_unlock();
305 
306     ret = qemu_poll_ns((GPollFD *)gpollfds->data, gpollfds->len, timeout);
307 
308     replay_mutex_lock();
309     bql_lock();
310 
311     glib_pollfds_poll();
312 
313     g_main_context_release(context);
314 
315     return ret;
316 }
317 #else
318 /***********************************************************/
319 /* Polling handling */
320 
321 typedef struct PollingEntry {
322     PollingFunc *func;
323     void *opaque;
324     struct PollingEntry *next;
325 } PollingEntry;
326 
327 static PollingEntry *first_polling_entry;
328 
329 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
330 {
331     PollingEntry **ppe, *pe;
332     pe = g_new0(PollingEntry, 1);
333     pe->func = func;
334     pe->opaque = opaque;
335     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
336     *ppe = pe;
337     return 0;
338 }
339 
340 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
341 {
342     PollingEntry **ppe, *pe;
343     for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
344         pe = *ppe;
345         if (pe->func == func && pe->opaque == opaque) {
346             *ppe = pe->next;
347             g_free(pe);
348             break;
349         }
350     }
351 }
352 
353 /***********************************************************/
354 /* Wait objects support */
355 typedef struct WaitObjects {
356     int num;
357     int revents[MAXIMUM_WAIT_OBJECTS];
358     HANDLE events[MAXIMUM_WAIT_OBJECTS];
359     WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS];
360     void *opaque[MAXIMUM_WAIT_OBJECTS];
361 } WaitObjects;
362 
363 static WaitObjects wait_objects = {0};
364 
365 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
366 {
367     int i;
368     WaitObjects *w = &wait_objects;
369 
370     if (w->num >= MAXIMUM_WAIT_OBJECTS) {
371         return -1;
372     }
373 
374     for (i = 0; i < w->num; i++) {
375         /* check if the same handle is added twice */
376         if (w->events[i] == handle) {
377             return -1;
378         }
379     }
380 
381     w->events[w->num] = handle;
382     w->func[w->num] = func;
383     w->opaque[w->num] = opaque;
384     w->revents[w->num] = 0;
385     w->num++;
386     return 0;
387 }
388 
389 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
390 {
391     int i, found;
392     WaitObjects *w = &wait_objects;
393 
394     found = 0;
395     for (i = 0; i < w->num; i++) {
396         if (w->events[i] == handle) {
397             found = 1;
398         }
399         if (found && i < (MAXIMUM_WAIT_OBJECTS - 1)) {
400             w->events[i] = w->events[i + 1];
401             w->func[i] = w->func[i + 1];
402             w->opaque[i] = w->opaque[i + 1];
403             w->revents[i] = w->revents[i + 1];
404         }
405     }
406     if (found) {
407         w->num--;
408     }
409 }
410 
411 static int pollfds_fill(GArray *pollfds, fd_set *rfds, fd_set *wfds,
412                         fd_set *xfds)
413 {
414     int nfds = -1;
415     int i;
416 
417     for (i = 0; i < pollfds->len; i++) {
418         GPollFD *pfd = &g_array_index(pollfds, GPollFD, i);
419         int fd = pfd->fd;
420         int events = pfd->events;
421         if (events & G_IO_IN) {
422             FD_SET(fd, rfds);
423             nfds = MAX(nfds, fd);
424         }
425         if (events & G_IO_OUT) {
426             FD_SET(fd, wfds);
427             nfds = MAX(nfds, fd);
428         }
429         if (events & G_IO_PRI) {
430             FD_SET(fd, xfds);
431             nfds = MAX(nfds, fd);
432         }
433     }
434     return nfds;
435 }
436 
437 static void pollfds_poll(GArray *pollfds, int nfds, fd_set *rfds,
438                          fd_set *wfds, fd_set *xfds)
439 {
440     int i;
441 
442     for (i = 0; i < pollfds->len; i++) {
443         GPollFD *pfd = &g_array_index(pollfds, GPollFD, i);
444         int fd = pfd->fd;
445         int revents = 0;
446 
447         if (FD_ISSET(fd, rfds)) {
448             revents |= G_IO_IN;
449         }
450         if (FD_ISSET(fd, wfds)) {
451             revents |= G_IO_OUT;
452         }
453         if (FD_ISSET(fd, xfds)) {
454             revents |= G_IO_PRI;
455         }
456         pfd->revents = revents & pfd->events;
457     }
458 }
459 
460 static int os_host_main_loop_wait(int64_t timeout)
461 {
462     GMainContext *context = g_main_context_default();
463     GPollFD poll_fds[1024 * 2]; /* this is probably overkill */
464     int select_ret = 0;
465     int g_poll_ret, ret, i, n_poll_fds;
466     PollingEntry *pe;
467     WaitObjects *w = &wait_objects;
468     gint poll_timeout;
469     int64_t poll_timeout_ns;
470     static struct timeval tv0;
471     fd_set rfds, wfds, xfds;
472     int nfds;
473 
474     g_main_context_acquire(context);
475 
476     /* XXX: need to suppress polling by better using win32 events */
477     ret = 0;
478     for (pe = first_polling_entry; pe != NULL; pe = pe->next) {
479         ret |= pe->func(pe->opaque);
480     }
481     if (ret != 0) {
482         g_main_context_release(context);
483         return ret;
484     }
485 
486     FD_ZERO(&rfds);
487     FD_ZERO(&wfds);
488     FD_ZERO(&xfds);
489     nfds = pollfds_fill(gpollfds, &rfds, &wfds, &xfds);
490     if (nfds >= 0) {
491         select_ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv0);
492         if (select_ret != 0) {
493             timeout = 0;
494         }
495         if (select_ret > 0) {
496             pollfds_poll(gpollfds, nfds, &rfds, &wfds, &xfds);
497         }
498     }
499 
500     g_main_context_prepare(context, &max_priority);
501     n_poll_fds = g_main_context_query(context, max_priority, &poll_timeout,
502                                       poll_fds, ARRAY_SIZE(poll_fds));
503     g_assert(n_poll_fds + w->num <= ARRAY_SIZE(poll_fds));
504 
505     for (i = 0; i < w->num; i++) {
506         poll_fds[n_poll_fds + i].fd = (DWORD_PTR)w->events[i];
507         poll_fds[n_poll_fds + i].events = G_IO_IN;
508     }
509 
510     if (poll_timeout < 0) {
511         poll_timeout_ns = -1;
512     } else {
513         poll_timeout_ns = (int64_t)poll_timeout * (int64_t)SCALE_MS;
514     }
515 
516     poll_timeout_ns = qemu_soonest_timeout(poll_timeout_ns, timeout);
517 
518     bql_unlock();
519 
520     replay_mutex_unlock();
521 
522     g_poll_ret = qemu_poll_ns(poll_fds, n_poll_fds + w->num, poll_timeout_ns);
523 
524     replay_mutex_lock();
525 
526     bql_lock();
527     if (g_poll_ret > 0) {
528         for (i = 0; i < w->num; i++) {
529             w->revents[i] = poll_fds[n_poll_fds + i].revents;
530         }
531         for (i = 0; i < w->num; i++) {
532             if (w->revents[i] && w->func[i]) {
533                 w->func[i](w->opaque[i]);
534             }
535         }
536     }
537 
538     if (g_main_context_check(context, max_priority, poll_fds, n_poll_fds)) {
539         g_main_context_dispatch(context);
540     }
541 
542     g_main_context_release(context);
543 
544     return select_ret || g_poll_ret;
545 }
546 #endif
547 
548 static NotifierList main_loop_poll_notifiers =
549     NOTIFIER_LIST_INITIALIZER(main_loop_poll_notifiers);
550 
551 void main_loop_poll_add_notifier(Notifier *notify)
552 {
553     notifier_list_add(&main_loop_poll_notifiers, notify);
554 }
555 
556 void main_loop_poll_remove_notifier(Notifier *notify)
557 {
558     notifier_remove(notify);
559 }
560 
561 void main_loop_wait(int nonblocking)
562 {
563     MainLoopPoll mlpoll = {
564         .state = MAIN_LOOP_POLL_FILL,
565         .timeout = UINT32_MAX,
566         .pollfds = gpollfds,
567     };
568     int ret;
569     int64_t timeout_ns;
570 
571     if (nonblocking) {
572         mlpoll.timeout = 0;
573     }
574 
575     /* poll any events */
576     g_array_set_size(gpollfds, 0); /* reset for new iteration */
577     /* XXX: separate device handlers from system ones */
578     notifier_list_notify(&main_loop_poll_notifiers, &mlpoll);
579 
580     if (mlpoll.timeout == UINT32_MAX) {
581         timeout_ns = -1;
582     } else {
583         timeout_ns = (uint64_t)mlpoll.timeout * (int64_t)(SCALE_MS);
584     }
585 
586     timeout_ns = qemu_soonest_timeout(timeout_ns,
587                                       timerlistgroup_deadline_ns(
588                                           &main_loop_tlg));
589 
590     ret = os_host_main_loop_wait(timeout_ns);
591     mlpoll.state = ret < 0 ? MAIN_LOOP_POLL_ERR : MAIN_LOOP_POLL_OK;
592     notifier_list_notify(&main_loop_poll_notifiers, &mlpoll);
593 
594     if (icount_enabled()) {
595         /*
596          * CPU thread can infinitely wait for event after
597          * missing the warp
598          */
599         icount_start_warp_timer();
600     }
601     qemu_clock_run_all_timers();
602 }
603 
604 /* Functions to operate on the main QEMU AioContext.  */
605 
606 QEMUBH *qemu_bh_new_full(QEMUBHFunc *cb, void *opaque, const char *name,
607                          MemReentrancyGuard *reentrancy_guard)
608 {
609     return aio_bh_new_full(qemu_aio_context, cb, opaque, name,
610                            reentrancy_guard);
611 }
612 
613 /*
614  * Functions to operate on the I/O handler AioContext.
615  * This context runs on top of main loop. We can't reuse qemu_aio_context
616  * because iohandlers mustn't be polled by aio_poll(qemu_aio_context).
617  */
618 static AioContext *iohandler_ctx;
619 
620 static void iohandler_init(void)
621 {
622     if (!iohandler_ctx) {
623         iohandler_ctx = aio_context_new(&error_abort);
624     }
625 }
626 
627 AioContext *iohandler_get_aio_context(void)
628 {
629     iohandler_init();
630     return iohandler_ctx;
631 }
632 
633 GSource *iohandler_get_g_source(void)
634 {
635     iohandler_init();
636     return aio_get_g_source(iohandler_ctx);
637 }
638 
639 void qemu_set_fd_handler(int fd,
640                          IOHandler *fd_read,
641                          IOHandler *fd_write,
642                          void *opaque)
643 {
644     iohandler_init();
645     aio_set_fd_handler(iohandler_ctx, fd, fd_read, fd_write, NULL, NULL,
646                        opaque);
647 }
648 
649 void event_notifier_set_handler(EventNotifier *e,
650                                 EventNotifierHandler *handler)
651 {
652     iohandler_init();
653     aio_set_event_notifier(iohandler_ctx, e, handler, NULL, NULL);
654 }
655