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