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