xref: /qemu/accel/tcg/cpu-exec.c (revision 8be545ba5a315a9aaf7307f143a4a7926a6e605c)
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-ops.h"
26 #include "trace.h"
27 #include "disas/disas.h"
28 #include "exec/cpu-common.h"
29 #include "exec/page-protection.h"
30 #include "exec/mmap-lock.h"
31 #include "exec/translation-block.h"
32 #include "tcg/tcg.h"
33 #include "qemu/atomic.h"
34 #include "qemu/rcu.h"
35 #include "exec/log.h"
36 #include "qemu/main-loop.h"
37 #include "exec/cpu-all.h"
38 #include "system/cpu-timers.h"
39 #include "exec/replay-core.h"
40 #include "system/tcg.h"
41 #include "exec/helper-proto-common.h"
42 #include "tb-jmp-cache.h"
43 #include "tb-hash.h"
44 #include "tb-context.h"
45 #include "tb-internal.h"
46 #include "internal-common.h"
47 #include "internal-target.h"
48 
49 /* -icount align implementation. */
50 
51 typedef struct SyncClocks {
52     int64_t diff_clk;
53     int64_t last_cpu_icount;
54     int64_t realtime_clock;
55 } SyncClocks;
56 
57 #if !defined(CONFIG_USER_ONLY)
58 /* Allow the guest to have a max 3ms advance.
59  * The difference between the 2 clocks could therefore
60  * oscillate around 0.
61  */
62 #define VM_CLOCK_ADVANCE 3000000
63 #define THRESHOLD_REDUCE 1.5
64 #define MAX_DELAY_PRINT_RATE 2000000000LL
65 #define MAX_NB_PRINTS 100
66 
67 int64_t max_delay;
68 int64_t max_advance;
69 
70 static void align_clocks(SyncClocks *sc, CPUState *cpu)
71 {
72     int64_t cpu_icount;
73 
74     if (!icount_align_option) {
75         return;
76     }
77 
78     cpu_icount = cpu->icount_extra + cpu->neg.icount_decr.u16.low;
79     sc->diff_clk += icount_to_ns(sc->last_cpu_icount - cpu_icount);
80     sc->last_cpu_icount = cpu_icount;
81 
82     if (sc->diff_clk > VM_CLOCK_ADVANCE) {
83 #ifndef _WIN32
84         struct timespec sleep_delay, rem_delay;
85         sleep_delay.tv_sec = sc->diff_clk / 1000000000LL;
86         sleep_delay.tv_nsec = sc->diff_clk % 1000000000LL;
87         if (nanosleep(&sleep_delay, &rem_delay) < 0) {
88             sc->diff_clk = rem_delay.tv_sec * 1000000000LL + rem_delay.tv_nsec;
89         } else {
90             sc->diff_clk = 0;
91         }
92 #else
93         Sleep(sc->diff_clk / SCALE_MS);
94         sc->diff_clk = 0;
95 #endif
96     }
97 }
98 
99 static void print_delay(const SyncClocks *sc)
100 {
101     static float threshold_delay;
102     static int64_t last_realtime_clock;
103     static int nb_prints;
104 
105     if (icount_align_option &&
106         sc->realtime_clock - last_realtime_clock >= MAX_DELAY_PRINT_RATE &&
107         nb_prints < MAX_NB_PRINTS) {
108         if ((-sc->diff_clk / (float)1000000000LL > threshold_delay) ||
109             (-sc->diff_clk / (float)1000000000LL <
110              (threshold_delay - THRESHOLD_REDUCE))) {
111             threshold_delay = (-sc->diff_clk / 1000000000LL) + 1;
112             qemu_printf("Warning: The guest is now late by %.1f to %.1f seconds\n",
113                         threshold_delay - 1,
114                         threshold_delay);
115             nb_prints++;
116             last_realtime_clock = sc->realtime_clock;
117         }
118     }
119 }
120 
121 static void init_delay_params(SyncClocks *sc, CPUState *cpu)
122 {
123     if (!icount_align_option) {
124         return;
125     }
126     sc->realtime_clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT);
127     sc->diff_clk = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) - sc->realtime_clock;
128     sc->last_cpu_icount
129         = cpu->icount_extra + cpu->neg.icount_decr.u16.low;
130     if (sc->diff_clk < max_delay) {
131         max_delay = sc->diff_clk;
132     }
133     if (sc->diff_clk > max_advance) {
134         max_advance = sc->diff_clk;
135     }
136 
137     /* Print every 2s max if the guest is late. We limit the number
138        of printed messages to NB_PRINT_MAX(currently 100) */
139     print_delay(sc);
140 }
141 #else
142 static void align_clocks(SyncClocks *sc, const CPUState *cpu)
143 {
144 }
145 
146 static void init_delay_params(SyncClocks *sc, const CPUState *cpu)
147 {
148 }
149 #endif /* CONFIG USER ONLY */
150 
151 struct tb_desc {
152     vaddr pc;
153     uint64_t cs_base;
154     CPUArchState *env;
155     tb_page_addr_t page_addr0;
156     uint32_t flags;
157     uint32_t cflags;
158 };
159 
160 static bool tb_lookup_cmp(const void *p, const void *d)
161 {
162     const TranslationBlock *tb = p;
163     const struct tb_desc *desc = d;
164 
165     if ((tb_cflags(tb) & CF_PCREL || tb->pc == desc->pc) &&
166         tb_page_addr0(tb) == desc->page_addr0 &&
167         tb->cs_base == desc->cs_base &&
168         tb->flags == desc->flags &&
169         tb_cflags(tb) == desc->cflags) {
170         /* check next page if needed */
171         tb_page_addr_t tb_phys_page1 = tb_page_addr1(tb);
172         if (tb_phys_page1 == -1) {
173             return true;
174         } else {
175             tb_page_addr_t phys_page1;
176             vaddr virt_page1;
177 
178             /*
179              * We know that the first page matched, and an otherwise valid TB
180              * encountered an incomplete instruction at the end of that page,
181              * therefore we know that generating a new TB from the current PC
182              * must also require reading from the next page -- even if the
183              * second pages do not match, and therefore the resulting insn
184              * is different for the new TB.  Therefore any exception raised
185              * here by the faulting lookup is not premature.
186              */
187             virt_page1 = TARGET_PAGE_ALIGN(desc->pc);
188             phys_page1 = get_page_addr_code(desc->env, virt_page1);
189             if (tb_phys_page1 == phys_page1) {
190                 return true;
191             }
192         }
193     }
194     return false;
195 }
196 
197 static TranslationBlock *tb_htable_lookup(CPUState *cpu, vaddr pc,
198                                           uint64_t cs_base, uint32_t flags,
199                                           uint32_t cflags)
200 {
201     tb_page_addr_t phys_pc;
202     struct tb_desc desc;
203     uint32_t h;
204 
205     desc.env = cpu_env(cpu);
206     desc.cs_base = cs_base;
207     desc.flags = flags;
208     desc.cflags = cflags;
209     desc.pc = pc;
210     phys_pc = get_page_addr_code(desc.env, pc);
211     if (phys_pc == -1) {
212         return NULL;
213     }
214     desc.page_addr0 = phys_pc;
215     h = tb_hash_func(phys_pc, (cflags & CF_PCREL ? 0 : pc),
216                      flags, cs_base, cflags);
217     return qht_lookup_custom(&tb_ctx.htable, &desc, h, tb_lookup_cmp);
218 }
219 
220 /**
221  * tb_lookup:
222  * @cpu: CPU that will execute the returned translation block
223  * @pc: guest PC
224  * @cs_base: arch-specific value associated with translation block
225  * @flags: arch-specific translation block flags
226  * @cflags: CF_* flags
227  *
228  * Look up a translation block inside the QHT using @pc, @cs_base, @flags and
229  * @cflags. Uses @cpu's tb_jmp_cache. Might cause an exception, so have a
230  * longjmp destination ready.
231  *
232  * Returns: an existing translation block or NULL.
233  */
234 static inline TranslationBlock *tb_lookup(CPUState *cpu, vaddr pc,
235                                           uint64_t cs_base, uint32_t flags,
236                                           uint32_t cflags)
237 {
238     TranslationBlock *tb;
239     CPUJumpCache *jc;
240     uint32_t hash;
241 
242     /* we should never be trying to look up an INVALID tb */
243     tcg_debug_assert(!(cflags & CF_INVALID));
244 
245     hash = tb_jmp_cache_hash_func(pc);
246     jc = cpu->tb_jmp_cache;
247 
248     tb = qatomic_read(&jc->array[hash].tb);
249     if (likely(tb &&
250                jc->array[hash].pc == pc &&
251                tb->cs_base == cs_base &&
252                tb->flags == flags &&
253                tb_cflags(tb) == cflags)) {
254         goto hit;
255     }
256 
257     tb = tb_htable_lookup(cpu, pc, cs_base, flags, cflags);
258     if (tb == NULL) {
259         return NULL;
260     }
261 
262     jc->array[hash].pc = pc;
263     qatomic_set(&jc->array[hash].tb, tb);
264 
265 hit:
266     /*
267      * As long as tb is not NULL, the contents are consistent.  Therefore,
268      * the virtual PC has to match for non-CF_PCREL translations.
269      */
270     assert((tb_cflags(tb) & CF_PCREL) || tb->pc == pc);
271     return tb;
272 }
273 
274 static void log_cpu_exec(vaddr pc, CPUState *cpu,
275                          const TranslationBlock *tb)
276 {
277     if (qemu_log_in_addr_range(pc)) {
278         qemu_log_mask(CPU_LOG_EXEC,
279                       "Trace %d: %p [%08" PRIx64
280                       "/%016" VADDR_PRIx "/%08x/%08x] %s\n",
281                       cpu->cpu_index, tb->tc.ptr, tb->cs_base, pc,
282                       tb->flags, tb->cflags, lookup_symbol(pc));
283 
284         if (qemu_loglevel_mask(CPU_LOG_TB_CPU)) {
285             FILE *logfile = qemu_log_trylock();
286             if (logfile) {
287                 int flags = 0;
288 
289                 if (qemu_loglevel_mask(CPU_LOG_TB_FPU)) {
290                     flags |= CPU_DUMP_FPU;
291                 }
292 #if defined(TARGET_I386)
293                 flags |= CPU_DUMP_CCOP;
294 #endif
295                 if (qemu_loglevel_mask(CPU_LOG_TB_VPU)) {
296                     flags |= CPU_DUMP_VPU;
297                 }
298                 cpu_dump_state(cpu, logfile, flags);
299                 qemu_log_unlock(logfile);
300             }
301         }
302     }
303 }
304 
305 static bool check_for_breakpoints_slow(CPUState *cpu, vaddr pc,
306                                        uint32_t *cflags)
307 {
308     CPUBreakpoint *bp;
309     bool match_page = false;
310 
311     /*
312      * Singlestep overrides breakpoints.
313      * This requirement is visible in the record-replay tests, where
314      * we would fail to make forward progress in reverse-continue.
315      *
316      * TODO: gdb singlestep should only override gdb breakpoints,
317      * so that one could (gdb) singlestep into the guest kernel's
318      * architectural breakpoint handler.
319      */
320     if (cpu->singlestep_enabled) {
321         return false;
322     }
323 
324     QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {
325         /*
326          * If we have an exact pc match, trigger the breakpoint.
327          * Otherwise, note matches within the page.
328          */
329         if (pc == bp->pc) {
330             bool match_bp = false;
331 
332             if (bp->flags & BP_GDB) {
333                 match_bp = true;
334             } else if (bp->flags & BP_CPU) {
335 #ifdef CONFIG_USER_ONLY
336                 g_assert_not_reached();
337 #else
338                 const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
339                 assert(tcg_ops->debug_check_breakpoint);
340                 match_bp = tcg_ops->debug_check_breakpoint(cpu);
341 #endif
342             }
343 
344             if (match_bp) {
345                 cpu->exception_index = EXCP_DEBUG;
346                 return true;
347             }
348         } else if (((pc ^ bp->pc) & TARGET_PAGE_MASK) == 0) {
349             match_page = true;
350         }
351     }
352 
353     /*
354      * Within the same page as a breakpoint, single-step,
355      * returning to helper_lookup_tb_ptr after each insn looking
356      * for the actual breakpoint.
357      *
358      * TODO: Perhaps better to record all of the TBs associated
359      * with a given virtual page that contains a breakpoint, and
360      * then invalidate them when a new overlapping breakpoint is
361      * set on the page.  Non-overlapping TBs would not be
362      * invalidated, nor would any TB need to be invalidated as
363      * breakpoints are removed.
364      */
365     if (match_page) {
366         *cflags = (*cflags & ~CF_COUNT_MASK) | CF_NO_GOTO_TB | CF_BP_PAGE | 1;
367     }
368     return false;
369 }
370 
371 static inline bool check_for_breakpoints(CPUState *cpu, vaddr pc,
372                                          uint32_t *cflags)
373 {
374     return unlikely(!QTAILQ_EMPTY(&cpu->breakpoints)) &&
375         check_for_breakpoints_slow(cpu, pc, cflags);
376 }
377 
378 /**
379  * helper_lookup_tb_ptr: quick check for next tb
380  * @env: current cpu state
381  *
382  * Look for an existing TB matching the current cpu state.
383  * If found, return the code pointer.  If not found, return
384  * the tcg epilogue so that we return into cpu_tb_exec.
385  */
386 const void *HELPER(lookup_tb_ptr)(CPUArchState *env)
387 {
388     CPUState *cpu = env_cpu(env);
389     TranslationBlock *tb;
390     vaddr pc;
391     uint64_t cs_base;
392     uint32_t flags, cflags;
393 
394     /*
395      * By definition we've just finished a TB, so I/O is OK.
396      * Avoid the possibility of calling cpu_io_recompile() if
397      * a page table walk triggered by tb_lookup() calling
398      * probe_access_internal() happens to touch an MMIO device.
399      * The next TB, if we chain to it, will clear the flag again.
400      */
401     cpu->neg.can_do_io = true;
402     cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags);
403 
404     cflags = curr_cflags(cpu);
405     if (check_for_breakpoints(cpu, pc, &cflags)) {
406         cpu_loop_exit(cpu);
407     }
408 
409     tb = tb_lookup(cpu, pc, cs_base, flags, cflags);
410     if (tb == NULL) {
411         return tcg_code_gen_epilogue;
412     }
413 
414     if (qemu_loglevel_mask(CPU_LOG_TB_CPU | CPU_LOG_EXEC)) {
415         log_cpu_exec(pc, cpu, tb);
416     }
417 
418     return tb->tc.ptr;
419 }
420 
421 /* Return the current PC from CPU, which may be cached in TB. */
422 static vaddr log_pc(CPUState *cpu, const TranslationBlock *tb)
423 {
424     if (tb_cflags(tb) & CF_PCREL) {
425         return cpu->cc->get_pc(cpu);
426     } else {
427         return tb->pc;
428     }
429 }
430 
431 /* Execute a TB, and fix up the CPU state afterwards if necessary */
432 /*
433  * Disable CFI checks.
434  * TCG creates binary blobs at runtime, with the transformed code.
435  * A TB is a blob of binary code, created at runtime and called with an
436  * indirect function call. Since such function did not exist at compile time,
437  * the CFI runtime has no way to verify its signature and would fail.
438  * TCG is not considered a security-sensitive part of QEMU so this does not
439  * affect the impact of CFI in environment with high security requirements
440  */
441 static inline TranslationBlock * QEMU_DISABLE_CFI
442 cpu_tb_exec(CPUState *cpu, TranslationBlock *itb, int *tb_exit)
443 {
444     uintptr_t ret;
445     TranslationBlock *last_tb;
446     const void *tb_ptr = itb->tc.ptr;
447 
448     if (qemu_loglevel_mask(CPU_LOG_TB_CPU | CPU_LOG_EXEC)) {
449         log_cpu_exec(log_pc(cpu, itb), cpu, itb);
450     }
451 
452     qemu_thread_jit_execute();
453     ret = tcg_qemu_tb_exec(cpu_env(cpu), tb_ptr);
454     cpu->neg.can_do_io = true;
455     qemu_plugin_disable_mem_helpers(cpu);
456     /*
457      * TODO: Delay swapping back to the read-write region of the TB
458      * until we actually need to modify the TB.  The read-only copy,
459      * coming from the rx region, shares the same host TLB entry as
460      * the code that executed the exit_tb opcode that arrived here.
461      * If we insist on touching both the RX and the RW pages, we
462      * double the host TLB pressure.
463      */
464     last_tb = tcg_splitwx_to_rw((void *)(ret & ~TB_EXIT_MASK));
465     *tb_exit = ret & TB_EXIT_MASK;
466 
467     trace_exec_tb_exit(last_tb, *tb_exit);
468 
469     if (*tb_exit > TB_EXIT_IDX1) {
470         /* We didn't start executing this TB (eg because the instruction
471          * counter hit zero); we must restore the guest PC to the address
472          * of the start of the TB.
473          */
474         CPUClass *cc = cpu->cc;
475         const TCGCPUOps *tcg_ops = cc->tcg_ops;
476 
477         if (tcg_ops->synchronize_from_tb) {
478             tcg_ops->synchronize_from_tb(cpu, last_tb);
479         } else {
480             tcg_debug_assert(!(tb_cflags(last_tb) & CF_PCREL));
481             assert(cc->set_pc);
482             cc->set_pc(cpu, last_tb->pc);
483         }
484         if (qemu_loglevel_mask(CPU_LOG_EXEC)) {
485             vaddr pc = log_pc(cpu, last_tb);
486             if (qemu_log_in_addr_range(pc)) {
487                 qemu_log("Stopped execution of TB chain before %p [%016"
488                          VADDR_PRIx "] %s\n",
489                          last_tb->tc.ptr, pc, lookup_symbol(pc));
490             }
491         }
492     }
493 
494     /*
495      * If gdb single-step, and we haven't raised another exception,
496      * raise a debug exception.  Single-step with another exception
497      * is handled in cpu_handle_exception.
498      */
499     if (unlikely(cpu->singlestep_enabled) && cpu->exception_index == -1) {
500         cpu->exception_index = EXCP_DEBUG;
501         cpu_loop_exit(cpu);
502     }
503 
504     return last_tb;
505 }
506 
507 
508 static void cpu_exec_enter(CPUState *cpu)
509 {
510     const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
511 
512     if (tcg_ops->cpu_exec_enter) {
513         tcg_ops->cpu_exec_enter(cpu);
514     }
515 }
516 
517 static void cpu_exec_exit(CPUState *cpu)
518 {
519     const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
520 
521     if (tcg_ops->cpu_exec_exit) {
522         tcg_ops->cpu_exec_exit(cpu);
523     }
524 }
525 
526 static void cpu_exec_longjmp_cleanup(CPUState *cpu)
527 {
528     /* Non-buggy compilers preserve this; assert the correct value. */
529     g_assert(cpu == current_cpu);
530 
531 #ifdef CONFIG_USER_ONLY
532     clear_helper_retaddr();
533     if (have_mmap_lock()) {
534         mmap_unlock();
535     }
536 #else
537     /*
538      * For softmmu, a tlb_fill fault during translation will land here,
539      * and we need to release any page locks held.  In system mode we
540      * have one tcg_ctx per thread, so we know it was this cpu doing
541      * the translation.
542      *
543      * Alternative 1: Install a cleanup to be called via an exception
544      * handling safe longjmp.  It seems plausible that all our hosts
545      * support such a thing.  We'd have to properly register unwind info
546      * for the JIT for EH, rather that just for GDB.
547      *
548      * Alternative 2: Set and restore cpu->jmp_env in tb_gen_code to
549      * capture the cpu_loop_exit longjmp, perform the cleanup, and
550      * jump again to arrive here.
551      */
552     if (tcg_ctx->gen_tb) {
553         tb_unlock_pages(tcg_ctx->gen_tb);
554         tcg_ctx->gen_tb = NULL;
555     }
556 #endif
557     if (bql_locked()) {
558         bql_unlock();
559     }
560     assert_no_pages_locked();
561 }
562 
563 void cpu_exec_step_atomic(CPUState *cpu)
564 {
565     CPUArchState *env = cpu_env(cpu);
566     TranslationBlock *tb;
567     vaddr pc;
568     uint64_t cs_base;
569     uint32_t flags, cflags;
570     int tb_exit;
571 
572     if (sigsetjmp(cpu->jmp_env, 0) == 0) {
573         start_exclusive();
574         g_assert(cpu == current_cpu);
575         g_assert(!cpu->running);
576         cpu->running = true;
577 
578         cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags);
579 
580         cflags = curr_cflags(cpu);
581         /* Execute in a serial context. */
582         cflags &= ~CF_PARALLEL;
583         /* After 1 insn, return and release the exclusive lock. */
584         cflags |= CF_NO_GOTO_TB | CF_NO_GOTO_PTR | 1;
585         /*
586          * No need to check_for_breakpoints here.
587          * We only arrive in cpu_exec_step_atomic after beginning execution
588          * of an insn that includes an atomic operation we can't handle.
589          * Any breakpoint for this insn will have been recognized earlier.
590          */
591 
592         tb = tb_lookup(cpu, pc, cs_base, flags, cflags);
593         if (tb == NULL) {
594             mmap_lock();
595             tb = tb_gen_code(cpu, pc, cs_base, flags, cflags);
596             mmap_unlock();
597         }
598 
599         cpu_exec_enter(cpu);
600         /* execute the generated code */
601         trace_exec_tb(tb, pc);
602         cpu_tb_exec(cpu, tb, &tb_exit);
603         cpu_exec_exit(cpu);
604     } else {
605         cpu_exec_longjmp_cleanup(cpu);
606     }
607 
608     /*
609      * As we start the exclusive region before codegen we must still
610      * be in the region if we longjump out of either the codegen or
611      * the execution.
612      */
613     g_assert(cpu_in_exclusive_context(cpu));
614     cpu->running = false;
615     end_exclusive();
616 }
617 
618 void tb_set_jmp_target(TranslationBlock *tb, int n, uintptr_t addr)
619 {
620     /*
621      * Get the rx view of the structure, from which we find the
622      * executable code address, and tb_target_set_jmp_target can
623      * produce a pc-relative displacement to jmp_target_addr[n].
624      */
625     const TranslationBlock *c_tb = tcg_splitwx_to_rx(tb);
626     uintptr_t offset = tb->jmp_insn_offset[n];
627     uintptr_t jmp_rx = (uintptr_t)tb->tc.ptr + offset;
628     uintptr_t jmp_rw = jmp_rx - tcg_splitwx_diff;
629 
630     tb->jmp_target_addr[n] = addr;
631     tb_target_set_jmp_target(c_tb, n, jmp_rx, jmp_rw);
632 }
633 
634 static inline void tb_add_jump(TranslationBlock *tb, int n,
635                                TranslationBlock *tb_next)
636 {
637     uintptr_t old;
638 
639     qemu_thread_jit_write();
640     assert(n < ARRAY_SIZE(tb->jmp_list_next));
641     qemu_spin_lock(&tb_next->jmp_lock);
642 
643     /* make sure the destination TB is valid */
644     if (tb_next->cflags & CF_INVALID) {
645         goto out_unlock_next;
646     }
647     /* Atomically claim the jump destination slot only if it was NULL */
648     old = qatomic_cmpxchg(&tb->jmp_dest[n], (uintptr_t)NULL,
649                           (uintptr_t)tb_next);
650     if (old) {
651         goto out_unlock_next;
652     }
653 
654     /* patch the native jump address */
655     tb_set_jmp_target(tb, n, (uintptr_t)tb_next->tc.ptr);
656 
657     /* add in TB jmp list */
658     tb->jmp_list_next[n] = tb_next->jmp_list_head;
659     tb_next->jmp_list_head = (uintptr_t)tb | n;
660 
661     qemu_spin_unlock(&tb_next->jmp_lock);
662 
663     qemu_log_mask(CPU_LOG_EXEC, "Linking TBs %p index %d -> %p\n",
664                   tb->tc.ptr, n, tb_next->tc.ptr);
665     return;
666 
667  out_unlock_next:
668     qemu_spin_unlock(&tb_next->jmp_lock);
669     return;
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         tcg_ops->initialize();
1079         tcg_target_initialized = true;
1080     }
1081 
1082     cpu->tb_jmp_cache = g_new0(CPUJumpCache, 1);
1083     tlb_init(cpu);
1084 #ifndef CONFIG_USER_ONLY
1085     tcg_iommu_init_notifier_list(cpu);
1086 #endif /* !CONFIG_USER_ONLY */
1087     /* qemu_plugin_vcpu_init_hook delayed until cpu_index assigned. */
1088 
1089     return true;
1090 }
1091 
1092 /* undo the initializations in reverse order */
1093 void tcg_exec_unrealizefn(CPUState *cpu)
1094 {
1095 #ifndef CONFIG_USER_ONLY
1096     tcg_iommu_free_notifier_list(cpu);
1097 #endif /* !CONFIG_USER_ONLY */
1098 
1099     tlb_destroy(cpu);
1100     g_free_rcu(cpu->tb_jmp_cache, rcu);
1101 }
1102