1 /* 2 * emulator main execution loop 3 * 4 * Copyright (c) 2003-2005 Fabrice Bellard 5 * 6 * This library is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU Lesser General Public 8 * License as published by the Free Software Foundation; either 9 * version 2.1 of the License, or (at your option) any later version. 10 * 11 * This library is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 * Lesser General Public License for more details. 15 * 16 * You should have received a copy of the GNU Lesser General Public 17 * License along with this library; if not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 #include "qemu/osdep.h" 21 #include "qemu/qemu-print.h" 22 #include "qapi/error.h" 23 #include "qapi/type-helpers.h" 24 #include "hw/core/cpu.h" 25 #include "accel/tcg/cpu-ldst.h" 26 #include "accel/tcg/cpu-ops.h" 27 #include "trace.h" 28 #include "disas/disas.h" 29 #include "exec/cpu-common.h" 30 #include "exec/cpu-interrupt.h" 31 #include "exec/page-protection.h" 32 #include "exec/mmap-lock.h" 33 #include "exec/translation-block.h" 34 #include "tcg/tcg.h" 35 #include "qemu/atomic.h" 36 #include "qemu/rcu.h" 37 #include "exec/log.h" 38 #include "qemu/main-loop.h" 39 #include "cpu.h" 40 #include "exec/icount.h" 41 #include "exec/replay-core.h" 42 #include "system/tcg.h" 43 #include "exec/helper-proto-common.h" 44 #include "tb-jmp-cache.h" 45 #include "tb-hash.h" 46 #include "tb-context.h" 47 #include "tb-internal.h" 48 #include "internal-common.h" 49 50 /* -icount align implementation. */ 51 52 typedef struct SyncClocks { 53 int64_t diff_clk; 54 int64_t last_cpu_icount; 55 int64_t realtime_clock; 56 } SyncClocks; 57 58 #if !defined(CONFIG_USER_ONLY) 59 /* Allow the guest to have a max 3ms advance. 60 * The difference between the 2 clocks could therefore 61 * oscillate around 0. 62 */ 63 #define VM_CLOCK_ADVANCE 3000000 64 #define THRESHOLD_REDUCE 1.5 65 #define MAX_DELAY_PRINT_RATE 2000000000LL 66 #define MAX_NB_PRINTS 100 67 68 int64_t max_delay; 69 int64_t max_advance; 70 71 static void align_clocks(SyncClocks *sc, CPUState *cpu) 72 { 73 int64_t cpu_icount; 74 75 if (!icount_align_option) { 76 return; 77 } 78 79 cpu_icount = cpu->icount_extra + cpu->neg.icount_decr.u16.low; 80 sc->diff_clk += icount_to_ns(sc->last_cpu_icount - cpu_icount); 81 sc->last_cpu_icount = cpu_icount; 82 83 if (sc->diff_clk > VM_CLOCK_ADVANCE) { 84 #ifndef _WIN32 85 struct timespec sleep_delay, rem_delay; 86 sleep_delay.tv_sec = sc->diff_clk / 1000000000LL; 87 sleep_delay.tv_nsec = sc->diff_clk % 1000000000LL; 88 if (nanosleep(&sleep_delay, &rem_delay) < 0) { 89 sc->diff_clk = rem_delay.tv_sec * 1000000000LL + rem_delay.tv_nsec; 90 } else { 91 sc->diff_clk = 0; 92 } 93 #else 94 Sleep(sc->diff_clk / SCALE_MS); 95 sc->diff_clk = 0; 96 #endif 97 } 98 } 99 100 static void print_delay(const SyncClocks *sc) 101 { 102 static float threshold_delay; 103 static int64_t last_realtime_clock; 104 static int nb_prints; 105 106 if (icount_align_option && 107 sc->realtime_clock - last_realtime_clock >= MAX_DELAY_PRINT_RATE && 108 nb_prints < MAX_NB_PRINTS) { 109 if ((-sc->diff_clk / (float)1000000000LL > threshold_delay) || 110 (-sc->diff_clk / (float)1000000000LL < 111 (threshold_delay - THRESHOLD_REDUCE))) { 112 threshold_delay = (-sc->diff_clk / 1000000000LL) + 1; 113 qemu_printf("Warning: The guest is now late by %.1f to %.1f seconds\n", 114 threshold_delay - 1, 115 threshold_delay); 116 nb_prints++; 117 last_realtime_clock = sc->realtime_clock; 118 } 119 } 120 } 121 122 static void init_delay_params(SyncClocks *sc, CPUState *cpu) 123 { 124 if (!icount_align_option) { 125 return; 126 } 127 sc->realtime_clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT); 128 sc->diff_clk = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) - sc->realtime_clock; 129 sc->last_cpu_icount 130 = cpu->icount_extra + cpu->neg.icount_decr.u16.low; 131 if (sc->diff_clk < max_delay) { 132 max_delay = sc->diff_clk; 133 } 134 if (sc->diff_clk > max_advance) { 135 max_advance = sc->diff_clk; 136 } 137 138 /* Print every 2s max if the guest is late. We limit the number 139 of printed messages to NB_PRINT_MAX(currently 100) */ 140 print_delay(sc); 141 } 142 #else 143 static void align_clocks(SyncClocks *sc, const CPUState *cpu) 144 { 145 } 146 147 static void init_delay_params(SyncClocks *sc, const CPUState *cpu) 148 { 149 } 150 #endif /* CONFIG USER ONLY */ 151 152 struct tb_desc { 153 vaddr pc; 154 uint64_t cs_base; 155 CPUArchState *env; 156 tb_page_addr_t page_addr0; 157 uint32_t flags; 158 uint32_t cflags; 159 }; 160 161 static bool tb_lookup_cmp(const void *p, const void *d) 162 { 163 const TranslationBlock *tb = p; 164 const struct tb_desc *desc = d; 165 166 if ((tb_cflags(tb) & CF_PCREL || tb->pc == desc->pc) && 167 tb_page_addr0(tb) == desc->page_addr0 && 168 tb->cs_base == desc->cs_base && 169 tb->flags == desc->flags && 170 tb_cflags(tb) == desc->cflags) { 171 /* check next page if needed */ 172 tb_page_addr_t tb_phys_page1 = tb_page_addr1(tb); 173 if (tb_phys_page1 == -1) { 174 return true; 175 } else { 176 tb_page_addr_t phys_page1; 177 vaddr virt_page1; 178 179 /* 180 * We know that the first page matched, and an otherwise valid TB 181 * encountered an incomplete instruction at the end of that page, 182 * therefore we know that generating a new TB from the current PC 183 * must also require reading from the next page -- even if the 184 * second pages do not match, and therefore the resulting insn 185 * is different for the new TB. Therefore any exception raised 186 * here by the faulting lookup is not premature. 187 */ 188 virt_page1 = TARGET_PAGE_ALIGN(desc->pc); 189 phys_page1 = get_page_addr_code(desc->env, virt_page1); 190 if (tb_phys_page1 == phys_page1) { 191 return true; 192 } 193 } 194 } 195 return false; 196 } 197 198 static TranslationBlock *tb_htable_lookup(CPUState *cpu, vaddr pc, 199 uint64_t cs_base, uint32_t flags, 200 uint32_t cflags) 201 { 202 tb_page_addr_t phys_pc; 203 struct tb_desc desc; 204 uint32_t h; 205 206 desc.env = cpu_env(cpu); 207 desc.cs_base = cs_base; 208 desc.flags = flags; 209 desc.cflags = cflags; 210 desc.pc = pc; 211 phys_pc = get_page_addr_code(desc.env, pc); 212 if (phys_pc == -1) { 213 return NULL; 214 } 215 desc.page_addr0 = phys_pc; 216 h = tb_hash_func(phys_pc, (cflags & CF_PCREL ? 0 : pc), 217 flags, cs_base, cflags); 218 return qht_lookup_custom(&tb_ctx.htable, &desc, h, tb_lookup_cmp); 219 } 220 221 /** 222 * tb_lookup: 223 * @cpu: CPU that will execute the returned translation block 224 * @pc: guest PC 225 * @cs_base: arch-specific value associated with translation block 226 * @flags: arch-specific translation block flags 227 * @cflags: CF_* flags 228 * 229 * Look up a translation block inside the QHT using @pc, @cs_base, @flags and 230 * @cflags. Uses @cpu's tb_jmp_cache. Might cause an exception, so have a 231 * longjmp destination ready. 232 * 233 * Returns: an existing translation block or NULL. 234 */ 235 static inline TranslationBlock *tb_lookup(CPUState *cpu, vaddr pc, 236 uint64_t cs_base, uint32_t flags, 237 uint32_t cflags) 238 { 239 TranslationBlock *tb; 240 CPUJumpCache *jc; 241 uint32_t hash; 242 243 /* we should never be trying to look up an INVALID tb */ 244 tcg_debug_assert(!(cflags & CF_INVALID)); 245 246 hash = tb_jmp_cache_hash_func(pc); 247 jc = cpu->tb_jmp_cache; 248 249 tb = qatomic_read(&jc->array[hash].tb); 250 if (likely(tb && 251 jc->array[hash].pc == pc && 252 tb->cs_base == cs_base && 253 tb->flags == flags && 254 tb_cflags(tb) == cflags)) { 255 goto hit; 256 } 257 258 tb = tb_htable_lookup(cpu, pc, cs_base, flags, cflags); 259 if (tb == NULL) { 260 return NULL; 261 } 262 263 jc->array[hash].pc = pc; 264 qatomic_set(&jc->array[hash].tb, tb); 265 266 hit: 267 /* 268 * As long as tb is not NULL, the contents are consistent. Therefore, 269 * the virtual PC has to match for non-CF_PCREL translations. 270 */ 271 assert((tb_cflags(tb) & CF_PCREL) || tb->pc == pc); 272 return tb; 273 } 274 275 static void log_cpu_exec(vaddr pc, CPUState *cpu, 276 const TranslationBlock *tb) 277 { 278 if (qemu_log_in_addr_range(pc)) { 279 qemu_log_mask(CPU_LOG_EXEC, 280 "Trace %d: %p [%08" PRIx64 281 "/%016" VADDR_PRIx "/%08x/%08x] %s\n", 282 cpu->cpu_index, tb->tc.ptr, tb->cs_base, pc, 283 tb->flags, tb->cflags, lookup_symbol(pc)); 284 285 if (qemu_loglevel_mask(CPU_LOG_TB_CPU)) { 286 FILE *logfile = qemu_log_trylock(); 287 if (logfile) { 288 int flags = 0; 289 290 if (qemu_loglevel_mask(CPU_LOG_TB_FPU)) { 291 flags |= CPU_DUMP_FPU; 292 } 293 #if defined(TARGET_I386) 294 flags |= CPU_DUMP_CCOP; 295 #endif 296 if (qemu_loglevel_mask(CPU_LOG_TB_VPU)) { 297 flags |= CPU_DUMP_VPU; 298 } 299 cpu_dump_state(cpu, logfile, flags); 300 qemu_log_unlock(logfile); 301 } 302 } 303 } 304 } 305 306 static bool check_for_breakpoints_slow(CPUState *cpu, vaddr pc, 307 uint32_t *cflags) 308 { 309 CPUBreakpoint *bp; 310 bool match_page = false; 311 312 /* 313 * Singlestep overrides breakpoints. 314 * This requirement is visible in the record-replay tests, where 315 * we would fail to make forward progress in reverse-continue. 316 * 317 * TODO: gdb singlestep should only override gdb breakpoints, 318 * so that one could (gdb) singlestep into the guest kernel's 319 * architectural breakpoint handler. 320 */ 321 if (cpu->singlestep_enabled) { 322 return false; 323 } 324 325 QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) { 326 /* 327 * If we have an exact pc match, trigger the breakpoint. 328 * Otherwise, note matches within the page. 329 */ 330 if (pc == bp->pc) { 331 bool match_bp = false; 332 333 if (bp->flags & BP_GDB) { 334 match_bp = true; 335 } else if (bp->flags & BP_CPU) { 336 #ifdef CONFIG_USER_ONLY 337 g_assert_not_reached(); 338 #else 339 const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops; 340 assert(tcg_ops->debug_check_breakpoint); 341 match_bp = tcg_ops->debug_check_breakpoint(cpu); 342 #endif 343 } 344 345 if (match_bp) { 346 cpu->exception_index = EXCP_DEBUG; 347 return true; 348 } 349 } else if (((pc ^ bp->pc) & TARGET_PAGE_MASK) == 0) { 350 match_page = true; 351 } 352 } 353 354 /* 355 * Within the same page as a breakpoint, single-step, 356 * returning to helper_lookup_tb_ptr after each insn looking 357 * for the actual breakpoint. 358 * 359 * TODO: Perhaps better to record all of the TBs associated 360 * with a given virtual page that contains a breakpoint, and 361 * then invalidate them when a new overlapping breakpoint is 362 * set on the page. Non-overlapping TBs would not be 363 * invalidated, nor would any TB need to be invalidated as 364 * breakpoints are removed. 365 */ 366 if (match_page) { 367 *cflags = (*cflags & ~CF_COUNT_MASK) | CF_NO_GOTO_TB | CF_BP_PAGE | 1; 368 } 369 return false; 370 } 371 372 static inline bool check_for_breakpoints(CPUState *cpu, vaddr pc, 373 uint32_t *cflags) 374 { 375 return unlikely(!QTAILQ_EMPTY(&cpu->breakpoints)) && 376 check_for_breakpoints_slow(cpu, pc, cflags); 377 } 378 379 /** 380 * helper_lookup_tb_ptr: quick check for next tb 381 * @env: current cpu state 382 * 383 * Look for an existing TB matching the current cpu state. 384 * If found, return the code pointer. If not found, return 385 * the tcg epilogue so that we return into cpu_tb_exec. 386 */ 387 const void *HELPER(lookup_tb_ptr)(CPUArchState *env) 388 { 389 CPUState *cpu = env_cpu(env); 390 TranslationBlock *tb; 391 vaddr pc; 392 uint64_t cs_base; 393 uint32_t flags, cflags; 394 395 /* 396 * By definition we've just finished a TB, so I/O is OK. 397 * Avoid the possibility of calling cpu_io_recompile() if 398 * a page table walk triggered by tb_lookup() calling 399 * probe_access_internal() happens to touch an MMIO device. 400 * The next TB, if we chain to it, will clear the flag again. 401 */ 402 cpu->neg.can_do_io = true; 403 cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags); 404 405 cflags = curr_cflags(cpu); 406 if (check_for_breakpoints(cpu, pc, &cflags)) { 407 cpu_loop_exit(cpu); 408 } 409 410 tb = tb_lookup(cpu, pc, cs_base, flags, cflags); 411 if (tb == NULL) { 412 return tcg_code_gen_epilogue; 413 } 414 415 if (qemu_loglevel_mask(CPU_LOG_TB_CPU | CPU_LOG_EXEC)) { 416 log_cpu_exec(pc, cpu, tb); 417 } 418 419 return tb->tc.ptr; 420 } 421 422 /* Return the current PC from CPU, which may be cached in TB. */ 423 static vaddr log_pc(CPUState *cpu, const TranslationBlock *tb) 424 { 425 if (tb_cflags(tb) & CF_PCREL) { 426 return cpu->cc->get_pc(cpu); 427 } else { 428 return tb->pc; 429 } 430 } 431 432 /* Execute a TB, and fix up the CPU state afterwards if necessary */ 433 /* 434 * Disable CFI checks. 435 * TCG creates binary blobs at runtime, with the transformed code. 436 * A TB is a blob of binary code, created at runtime and called with an 437 * indirect function call. Since such function did not exist at compile time, 438 * the CFI runtime has no way to verify its signature and would fail. 439 * TCG is not considered a security-sensitive part of QEMU so this does not 440 * affect the impact of CFI in environment with high security requirements 441 */ 442 static inline TranslationBlock * QEMU_DISABLE_CFI 443 cpu_tb_exec(CPUState *cpu, TranslationBlock *itb, int *tb_exit) 444 { 445 uintptr_t ret; 446 TranslationBlock *last_tb; 447 const void *tb_ptr = itb->tc.ptr; 448 449 if (qemu_loglevel_mask(CPU_LOG_TB_CPU | CPU_LOG_EXEC)) { 450 log_cpu_exec(log_pc(cpu, itb), cpu, itb); 451 } 452 453 qemu_thread_jit_execute(); 454 ret = tcg_qemu_tb_exec(cpu_env(cpu), tb_ptr); 455 cpu->neg.can_do_io = true; 456 qemu_plugin_disable_mem_helpers(cpu); 457 /* 458 * TODO: Delay swapping back to the read-write region of the TB 459 * until we actually need to modify the TB. The read-only copy, 460 * coming from the rx region, shares the same host TLB entry as 461 * the code that executed the exit_tb opcode that arrived here. 462 * If we insist on touching both the RX and the RW pages, we 463 * double the host TLB pressure. 464 */ 465 last_tb = tcg_splitwx_to_rw((void *)(ret & ~TB_EXIT_MASK)); 466 *tb_exit = ret & TB_EXIT_MASK; 467 468 trace_exec_tb_exit(last_tb, *tb_exit); 469 470 if (*tb_exit > TB_EXIT_IDX1) { 471 /* We didn't start executing this TB (eg because the instruction 472 * counter hit zero); we must restore the guest PC to the address 473 * of the start of the TB. 474 */ 475 CPUClass *cc = cpu->cc; 476 const TCGCPUOps *tcg_ops = cc->tcg_ops; 477 478 if (tcg_ops->synchronize_from_tb) { 479 tcg_ops->synchronize_from_tb(cpu, last_tb); 480 } else { 481 tcg_debug_assert(!(tb_cflags(last_tb) & CF_PCREL)); 482 assert(cc->set_pc); 483 cc->set_pc(cpu, last_tb->pc); 484 } 485 if (qemu_loglevel_mask(CPU_LOG_EXEC)) { 486 vaddr pc = log_pc(cpu, last_tb); 487 if (qemu_log_in_addr_range(pc)) { 488 qemu_log("Stopped execution of TB chain before %p [%016" 489 VADDR_PRIx "] %s\n", 490 last_tb->tc.ptr, pc, lookup_symbol(pc)); 491 } 492 } 493 } 494 495 /* 496 * If gdb single-step, and we haven't raised another exception, 497 * raise a debug exception. Single-step with another exception 498 * is handled in cpu_handle_exception. 499 */ 500 if (unlikely(cpu->singlestep_enabled) && cpu->exception_index == -1) { 501 cpu->exception_index = EXCP_DEBUG; 502 cpu_loop_exit(cpu); 503 } 504 505 return last_tb; 506 } 507 508 509 static void cpu_exec_enter(CPUState *cpu) 510 { 511 const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops; 512 513 if (tcg_ops->cpu_exec_enter) { 514 tcg_ops->cpu_exec_enter(cpu); 515 } 516 } 517 518 static void cpu_exec_exit(CPUState *cpu) 519 { 520 const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops; 521 522 if (tcg_ops->cpu_exec_exit) { 523 tcg_ops->cpu_exec_exit(cpu); 524 } 525 } 526 527 static void cpu_exec_longjmp_cleanup(CPUState *cpu) 528 { 529 /* Non-buggy compilers preserve this; assert the correct value. */ 530 g_assert(cpu == current_cpu); 531 532 #ifdef CONFIG_USER_ONLY 533 clear_helper_retaddr(); 534 if (have_mmap_lock()) { 535 mmap_unlock(); 536 } 537 #else 538 /* 539 * For softmmu, a tlb_fill fault during translation will land here, 540 * and we need to release any page locks held. In system mode we 541 * have one tcg_ctx per thread, so we know it was this cpu doing 542 * the translation. 543 * 544 * Alternative 1: Install a cleanup to be called via an exception 545 * handling safe longjmp. It seems plausible that all our hosts 546 * support such a thing. We'd have to properly register unwind info 547 * for the JIT for EH, rather that just for GDB. 548 * 549 * Alternative 2: Set and restore cpu->jmp_env in tb_gen_code to 550 * capture the cpu_loop_exit longjmp, perform the cleanup, and 551 * jump again to arrive here. 552 */ 553 if (tcg_ctx->gen_tb) { 554 tb_unlock_pages(tcg_ctx->gen_tb); 555 tcg_ctx->gen_tb = NULL; 556 } 557 #endif 558 if (bql_locked()) { 559 bql_unlock(); 560 } 561 assert_no_pages_locked(); 562 } 563 564 void cpu_exec_step_atomic(CPUState *cpu) 565 { 566 CPUArchState *env = cpu_env(cpu); 567 TranslationBlock *tb; 568 vaddr pc; 569 uint64_t cs_base; 570 uint32_t flags, cflags; 571 int tb_exit; 572 573 if (sigsetjmp(cpu->jmp_env, 0) == 0) { 574 start_exclusive(); 575 g_assert(cpu == current_cpu); 576 g_assert(!cpu->running); 577 cpu->running = true; 578 579 cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags); 580 581 cflags = curr_cflags(cpu); 582 /* Execute in a serial context. */ 583 cflags &= ~CF_PARALLEL; 584 /* After 1 insn, return and release the exclusive lock. */ 585 cflags |= CF_NO_GOTO_TB | CF_NO_GOTO_PTR | 1; 586 /* 587 * No need to check_for_breakpoints here. 588 * We only arrive in cpu_exec_step_atomic after beginning execution 589 * of an insn that includes an atomic operation we can't handle. 590 * Any breakpoint for this insn will have been recognized earlier. 591 */ 592 593 tb = tb_lookup(cpu, pc, cs_base, flags, cflags); 594 if (tb == NULL) { 595 mmap_lock(); 596 tb = tb_gen_code(cpu, pc, cs_base, flags, cflags); 597 mmap_unlock(); 598 } 599 600 cpu_exec_enter(cpu); 601 /* execute the generated code */ 602 trace_exec_tb(tb, pc); 603 cpu_tb_exec(cpu, tb, &tb_exit); 604 cpu_exec_exit(cpu); 605 } else { 606 cpu_exec_longjmp_cleanup(cpu); 607 } 608 609 /* 610 * As we start the exclusive region before codegen we must still 611 * be in the region if we longjump out of either the codegen or 612 * the execution. 613 */ 614 g_assert(cpu_in_exclusive_context(cpu)); 615 cpu->running = false; 616 end_exclusive(); 617 } 618 619 void tb_set_jmp_target(TranslationBlock *tb, int n, uintptr_t addr) 620 { 621 /* 622 * Get the rx view of the structure, from which we find the 623 * executable code address, and tb_target_set_jmp_target can 624 * produce a pc-relative displacement to jmp_target_addr[n]. 625 */ 626 const TranslationBlock *c_tb = tcg_splitwx_to_rx(tb); 627 uintptr_t offset = tb->jmp_insn_offset[n]; 628 uintptr_t jmp_rx = (uintptr_t)tb->tc.ptr + offset; 629 uintptr_t jmp_rw = jmp_rx - tcg_splitwx_diff; 630 631 tb->jmp_target_addr[n] = addr; 632 tb_target_set_jmp_target(c_tb, n, jmp_rx, jmp_rw); 633 } 634 635 static inline void tb_add_jump(TranslationBlock *tb, int n, 636 TranslationBlock *tb_next) 637 { 638 uintptr_t old; 639 640 qemu_thread_jit_write(); 641 assert(n < ARRAY_SIZE(tb->jmp_list_next)); 642 qemu_spin_lock(&tb_next->jmp_lock); 643 644 /* make sure the destination TB is valid */ 645 if (tb_next->cflags & CF_INVALID) { 646 goto out_unlock_next; 647 } 648 /* Atomically claim the jump destination slot only if it was NULL */ 649 old = qatomic_cmpxchg(&tb->jmp_dest[n], (uintptr_t)NULL, 650 (uintptr_t)tb_next); 651 if (old) { 652 goto out_unlock_next; 653 } 654 655 /* patch the native jump address */ 656 tb_set_jmp_target(tb, n, (uintptr_t)tb_next->tc.ptr); 657 658 /* add in TB jmp list */ 659 tb->jmp_list_next[n] = tb_next->jmp_list_head; 660 tb_next->jmp_list_head = (uintptr_t)tb | n; 661 662 qemu_spin_unlock(&tb_next->jmp_lock); 663 664 qemu_log_mask(CPU_LOG_EXEC, "Linking TBs %p index %d -> %p\n", 665 tb->tc.ptr, n, tb_next->tc.ptr); 666 return; 667 668 out_unlock_next: 669 qemu_spin_unlock(&tb_next->jmp_lock); 670 } 671 672 static inline bool cpu_handle_halt(CPUState *cpu) 673 { 674 #ifndef CONFIG_USER_ONLY 675 if (cpu->halted) { 676 const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops; 677 bool leave_halt = tcg_ops->cpu_exec_halt(cpu); 678 679 if (!leave_halt) { 680 return true; 681 } 682 683 cpu->halted = 0; 684 } 685 #endif /* !CONFIG_USER_ONLY */ 686 687 return false; 688 } 689 690 static inline void cpu_handle_debug_exception(CPUState *cpu) 691 { 692 const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops; 693 CPUWatchpoint *wp; 694 695 if (!cpu->watchpoint_hit) { 696 QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) { 697 wp->flags &= ~BP_WATCHPOINT_HIT; 698 } 699 } 700 701 if (tcg_ops->debug_excp_handler) { 702 tcg_ops->debug_excp_handler(cpu); 703 } 704 } 705 706 static inline bool cpu_handle_exception(CPUState *cpu, int *ret) 707 { 708 if (cpu->exception_index < 0) { 709 #ifndef CONFIG_USER_ONLY 710 if (replay_has_exception() 711 && cpu->neg.icount_decr.u16.low + cpu->icount_extra == 0) { 712 /* Execute just one insn to trigger exception pending in the log */ 713 cpu->cflags_next_tb = (curr_cflags(cpu) & ~CF_USE_ICOUNT) 714 | CF_NOIRQ | 1; 715 } 716 #endif 717 return false; 718 } 719 720 if (cpu->exception_index >= EXCP_INTERRUPT) { 721 /* exit request from the cpu execution loop */ 722 *ret = cpu->exception_index; 723 if (*ret == EXCP_DEBUG) { 724 cpu_handle_debug_exception(cpu); 725 } 726 cpu->exception_index = -1; 727 return true; 728 } 729 730 #if defined(CONFIG_USER_ONLY) 731 /* 732 * If user mode only, we simulate a fake exception which will be 733 * handled outside the cpu execution loop. 734 */ 735 #if defined(TARGET_I386) 736 const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops; 737 tcg_ops->fake_user_interrupt(cpu); 738 #endif /* TARGET_I386 */ 739 *ret = cpu->exception_index; 740 cpu->exception_index = -1; 741 return true; 742 #else 743 if (replay_exception()) { 744 const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops; 745 746 bql_lock(); 747 tcg_ops->do_interrupt(cpu); 748 bql_unlock(); 749 cpu->exception_index = -1; 750 751 if (unlikely(cpu->singlestep_enabled)) { 752 /* 753 * After processing the exception, ensure an EXCP_DEBUG is 754 * raised when single-stepping so that GDB doesn't miss the 755 * next instruction. 756 */ 757 *ret = EXCP_DEBUG; 758 cpu_handle_debug_exception(cpu); 759 return true; 760 } 761 } else if (!replay_has_interrupt()) { 762 /* give a chance to iothread in replay mode */ 763 *ret = EXCP_INTERRUPT; 764 return true; 765 } 766 #endif 767 768 return false; 769 } 770 771 static inline bool icount_exit_request(CPUState *cpu) 772 { 773 if (!icount_enabled()) { 774 return false; 775 } 776 if (cpu->cflags_next_tb != -1 && !(cpu->cflags_next_tb & CF_USE_ICOUNT)) { 777 return false; 778 } 779 return cpu->neg.icount_decr.u16.low + cpu->icount_extra == 0; 780 } 781 782 static inline bool cpu_handle_interrupt(CPUState *cpu, 783 TranslationBlock **last_tb) 784 { 785 /* 786 * If we have requested custom cflags with CF_NOIRQ we should 787 * skip checking here. Any pending interrupts will get picked up 788 * by the next TB we execute under normal cflags. 789 */ 790 if (cpu->cflags_next_tb != -1 && cpu->cflags_next_tb & CF_NOIRQ) { 791 return false; 792 } 793 794 /* Clear the interrupt flag now since we're processing 795 * cpu->interrupt_request and cpu->exit_request. 796 * Ensure zeroing happens before reading cpu->exit_request or 797 * cpu->interrupt_request (see also smp_wmb in cpu_exit()) 798 */ 799 qatomic_set_mb(&cpu->neg.icount_decr.u16.high, 0); 800 801 if (unlikely(qatomic_read(&cpu->interrupt_request))) { 802 int interrupt_request; 803 bql_lock(); 804 interrupt_request = cpu->interrupt_request; 805 if (unlikely(cpu->singlestep_enabled & SSTEP_NOIRQ)) { 806 /* Mask out external interrupts for this step. */ 807 interrupt_request &= ~CPU_INTERRUPT_SSTEP_MASK; 808 } 809 if (interrupt_request & CPU_INTERRUPT_DEBUG) { 810 cpu->interrupt_request &= ~CPU_INTERRUPT_DEBUG; 811 cpu->exception_index = EXCP_DEBUG; 812 bql_unlock(); 813 return true; 814 } 815 #if !defined(CONFIG_USER_ONLY) 816 if (replay_mode == REPLAY_MODE_PLAY && !replay_has_interrupt()) { 817 /* Do nothing */ 818 } else if (interrupt_request & CPU_INTERRUPT_HALT) { 819 replay_interrupt(); 820 cpu->interrupt_request &= ~CPU_INTERRUPT_HALT; 821 cpu->halted = 1; 822 cpu->exception_index = EXCP_HLT; 823 bql_unlock(); 824 return true; 825 } 826 #if defined(TARGET_I386) 827 else if (interrupt_request & CPU_INTERRUPT_INIT) { 828 X86CPU *x86_cpu = X86_CPU(cpu); 829 CPUArchState *env = &x86_cpu->env; 830 replay_interrupt(); 831 cpu_svm_check_intercept_param(env, SVM_EXIT_INIT, 0, 0); 832 do_cpu_init(x86_cpu); 833 cpu->exception_index = EXCP_HALTED; 834 bql_unlock(); 835 return true; 836 } 837 #else 838 else if (interrupt_request & CPU_INTERRUPT_RESET) { 839 replay_interrupt(); 840 cpu_reset(cpu); 841 bql_unlock(); 842 return true; 843 } 844 #endif /* !TARGET_I386 */ 845 /* The target hook has 3 exit conditions: 846 False when the interrupt isn't processed, 847 True when it is, and we should restart on a new TB, 848 and via longjmp via cpu_loop_exit. */ 849 else { 850 const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops; 851 852 if (tcg_ops->cpu_exec_interrupt(cpu, interrupt_request)) { 853 if (!tcg_ops->need_replay_interrupt || 854 tcg_ops->need_replay_interrupt(interrupt_request)) { 855 replay_interrupt(); 856 } 857 /* 858 * After processing the interrupt, ensure an EXCP_DEBUG is 859 * raised when single-stepping so that GDB doesn't miss the 860 * next instruction. 861 */ 862 if (unlikely(cpu->singlestep_enabled)) { 863 cpu->exception_index = EXCP_DEBUG; 864 bql_unlock(); 865 return true; 866 } 867 cpu->exception_index = -1; 868 *last_tb = NULL; 869 } 870 /* The target hook may have updated the 'cpu->interrupt_request'; 871 * reload the 'interrupt_request' value */ 872 interrupt_request = cpu->interrupt_request; 873 } 874 #endif /* !CONFIG_USER_ONLY */ 875 if (interrupt_request & CPU_INTERRUPT_EXITTB) { 876 cpu->interrupt_request &= ~CPU_INTERRUPT_EXITTB; 877 /* ensure that no TB jump will be modified as 878 the program flow was changed */ 879 *last_tb = NULL; 880 } 881 882 /* If we exit via cpu_loop_exit/longjmp it is reset in cpu_exec */ 883 bql_unlock(); 884 } 885 886 /* Finally, check if we need to exit to the main loop. */ 887 if (unlikely(qatomic_read(&cpu->exit_request)) || icount_exit_request(cpu)) { 888 qatomic_set(&cpu->exit_request, 0); 889 if (cpu->exception_index == -1) { 890 cpu->exception_index = EXCP_INTERRUPT; 891 } 892 return true; 893 } 894 895 return false; 896 } 897 898 static inline void cpu_loop_exec_tb(CPUState *cpu, TranslationBlock *tb, 899 vaddr pc, TranslationBlock **last_tb, 900 int *tb_exit) 901 { 902 trace_exec_tb(tb, pc); 903 tb = cpu_tb_exec(cpu, tb, tb_exit); 904 if (*tb_exit != TB_EXIT_REQUESTED) { 905 *last_tb = tb; 906 return; 907 } 908 909 *last_tb = NULL; 910 if (cpu_loop_exit_requested(cpu)) { 911 /* Something asked us to stop executing chained TBs; just 912 * continue round the main loop. Whatever requested the exit 913 * will also have set something else (eg exit_request or 914 * interrupt_request) which will be handled by 915 * cpu_handle_interrupt. cpu_handle_interrupt will also 916 * clear cpu->icount_decr.u16.high. 917 */ 918 return; 919 } 920 921 /* Instruction counter expired. */ 922 assert(icount_enabled()); 923 #ifndef CONFIG_USER_ONLY 924 /* Ensure global icount has gone forward */ 925 icount_update(cpu); 926 /* Refill decrementer and continue execution. */ 927 int32_t insns_left = MIN(0xffff, cpu->icount_budget); 928 cpu->neg.icount_decr.u16.low = insns_left; 929 cpu->icount_extra = cpu->icount_budget - insns_left; 930 931 /* 932 * If the next tb has more instructions than we have left to 933 * execute we need to ensure we find/generate a TB with exactly 934 * insns_left instructions in it. 935 */ 936 if (insns_left > 0 && insns_left < tb->icount) { 937 assert(insns_left <= CF_COUNT_MASK); 938 assert(cpu->icount_extra == 0); 939 cpu->cflags_next_tb = (tb->cflags & ~CF_COUNT_MASK) | insns_left; 940 } 941 #endif 942 } 943 944 /* main execution loop */ 945 946 static int __attribute__((noinline)) 947 cpu_exec_loop(CPUState *cpu, SyncClocks *sc) 948 { 949 int ret; 950 951 /* if an exception is pending, we execute it here */ 952 while (!cpu_handle_exception(cpu, &ret)) { 953 TranslationBlock *last_tb = NULL; 954 int tb_exit = 0; 955 956 while (!cpu_handle_interrupt(cpu, &last_tb)) { 957 TranslationBlock *tb; 958 vaddr pc; 959 uint64_t cs_base; 960 uint32_t flags, cflags; 961 962 cpu_get_tb_cpu_state(cpu_env(cpu), &pc, &cs_base, &flags); 963 964 /* 965 * When requested, use an exact setting for cflags for the next 966 * execution. This is used for icount, precise smc, and stop- 967 * after-access watchpoints. Since this request should never 968 * have CF_INVALID set, -1 is a convenient invalid value that 969 * does not require tcg headers for cpu_common_reset. 970 */ 971 cflags = cpu->cflags_next_tb; 972 if (cflags == -1) { 973 cflags = curr_cflags(cpu); 974 } else { 975 cpu->cflags_next_tb = -1; 976 } 977 978 if (check_for_breakpoints(cpu, pc, &cflags)) { 979 break; 980 } 981 982 tb = tb_lookup(cpu, pc, cs_base, flags, cflags); 983 if (tb == NULL) { 984 CPUJumpCache *jc; 985 uint32_t h; 986 987 mmap_lock(); 988 tb = tb_gen_code(cpu, pc, cs_base, flags, cflags); 989 mmap_unlock(); 990 991 /* 992 * We add the TB in the virtual pc hash table 993 * for the fast lookup 994 */ 995 h = tb_jmp_cache_hash_func(pc); 996 jc = cpu->tb_jmp_cache; 997 jc->array[h].pc = pc; 998 qatomic_set(&jc->array[h].tb, tb); 999 } 1000 1001 #ifndef CONFIG_USER_ONLY 1002 /* 1003 * We don't take care of direct jumps when address mapping 1004 * changes in system emulation. So it's not safe to make a 1005 * direct jump to a TB spanning two pages because the mapping 1006 * for the second page can change. 1007 */ 1008 if (tb_page_addr1(tb) != -1) { 1009 last_tb = NULL; 1010 } 1011 #endif 1012 /* See if we can patch the calling TB. */ 1013 if (last_tb) { 1014 tb_add_jump(last_tb, tb_exit, tb); 1015 } 1016 1017 cpu_loop_exec_tb(cpu, tb, pc, &last_tb, &tb_exit); 1018 1019 /* Try to align the host and virtual clocks 1020 if the guest is in advance */ 1021 align_clocks(sc, cpu); 1022 } 1023 } 1024 return ret; 1025 } 1026 1027 static int cpu_exec_setjmp(CPUState *cpu, SyncClocks *sc) 1028 { 1029 /* Prepare setjmp context for exception handling. */ 1030 if (unlikely(sigsetjmp(cpu->jmp_env, 0) != 0)) { 1031 cpu_exec_longjmp_cleanup(cpu); 1032 } 1033 1034 return cpu_exec_loop(cpu, sc); 1035 } 1036 1037 int cpu_exec(CPUState *cpu) 1038 { 1039 int ret; 1040 SyncClocks sc = { 0 }; 1041 1042 /* replay_interrupt may need current_cpu */ 1043 current_cpu = cpu; 1044 1045 if (cpu_handle_halt(cpu)) { 1046 return EXCP_HALTED; 1047 } 1048 1049 RCU_READ_LOCK_GUARD(); 1050 cpu_exec_enter(cpu); 1051 1052 /* 1053 * Calculate difference between guest clock and host clock. 1054 * This delay includes the delay of the last cycle, so 1055 * what we have to do is sleep until it is 0. As for the 1056 * advance/delay we gain here, we try to fix it next time. 1057 */ 1058 init_delay_params(&sc, cpu); 1059 1060 ret = cpu_exec_setjmp(cpu, &sc); 1061 1062 cpu_exec_exit(cpu); 1063 return ret; 1064 } 1065 1066 bool tcg_exec_realizefn(CPUState *cpu, Error **errp) 1067 { 1068 static bool tcg_target_initialized; 1069 1070 if (!tcg_target_initialized) { 1071 /* Check mandatory TCGCPUOps handlers */ 1072 const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops; 1073 #ifndef CONFIG_USER_ONLY 1074 assert(tcg_ops->cpu_exec_halt); 1075 assert(tcg_ops->cpu_exec_interrupt); 1076 #endif /* !CONFIG_USER_ONLY */ 1077 assert(tcg_ops->translate_code); 1078 assert(tcg_ops->mmu_index); 1079 tcg_ops->initialize(); 1080 tcg_target_initialized = true; 1081 } 1082 1083 cpu->tb_jmp_cache = g_new0(CPUJumpCache, 1); 1084 tlb_init(cpu); 1085 #ifndef CONFIG_USER_ONLY 1086 tcg_iommu_init_notifier_list(cpu); 1087 #endif /* !CONFIG_USER_ONLY */ 1088 /* qemu_plugin_vcpu_init_hook delayed until cpu_index assigned. */ 1089 1090 return true; 1091 } 1092 1093 /* undo the initializations in reverse order */ 1094 void tcg_exec_unrealizefn(CPUState *cpu) 1095 { 1096 #ifndef CONFIG_USER_ONLY 1097 tcg_iommu_free_notifier_list(cpu); 1098 #endif /* !CONFIG_USER_ONLY */ 1099 1100 tlb_destroy(cpu); 1101 g_free_rcu(cpu->tb_jmp_cache, rcu); 1102 } 1103