xref: /qemu/accel/tcg/cpu-exec.c (revision 51209c2aed343a45f79b522706c807abbdcf01a3)
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 }
672 
673 static inline bool cpu_handle_halt(CPUState *cpu)
674 {
675 #ifndef CONFIG_USER_ONLY
676     if (cpu->halted) {
677         const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
678         bool leave_halt = tcg_ops->cpu_exec_halt(cpu);
679 
680         if (!leave_halt) {
681             return true;
682         }
683 
684         cpu->halted = 0;
685     }
686 #endif /* !CONFIG_USER_ONLY */
687 
688     return false;
689 }
690 
691 static inline void cpu_handle_debug_exception(CPUState *cpu)
692 {
693     const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
694     CPUWatchpoint *wp;
695 
696     if (!cpu->watchpoint_hit) {
697         QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
698             wp->flags &= ~BP_WATCHPOINT_HIT;
699         }
700     }
701 
702     if (tcg_ops->debug_excp_handler) {
703         tcg_ops->debug_excp_handler(cpu);
704     }
705 }
706 
707 static inline bool cpu_handle_exception(CPUState *cpu, int *ret)
708 {
709     if (cpu->exception_index < 0) {
710 #ifndef CONFIG_USER_ONLY
711         if (replay_has_exception()
712             && cpu->neg.icount_decr.u16.low + cpu->icount_extra == 0) {
713             /* Execute just one insn to trigger exception pending in the log */
714             cpu->cflags_next_tb = (curr_cflags(cpu) & ~CF_USE_ICOUNT)
715                 | CF_NOIRQ | 1;
716         }
717 #endif
718         return false;
719     }
720 
721     if (cpu->exception_index >= EXCP_INTERRUPT) {
722         /* exit request from the cpu execution loop */
723         *ret = cpu->exception_index;
724         if (*ret == EXCP_DEBUG) {
725             cpu_handle_debug_exception(cpu);
726         }
727         cpu->exception_index = -1;
728         return true;
729     }
730 
731 #if defined(CONFIG_USER_ONLY)
732     /*
733      * If user mode only, we simulate a fake exception which will be
734      * handled outside the cpu execution loop.
735      */
736 #if defined(TARGET_I386)
737     const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
738     tcg_ops->fake_user_interrupt(cpu);
739 #endif /* TARGET_I386 */
740     *ret = cpu->exception_index;
741     cpu->exception_index = -1;
742     return true;
743 #else
744     if (replay_exception()) {
745         const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
746 
747         bql_lock();
748         tcg_ops->do_interrupt(cpu);
749         bql_unlock();
750         cpu->exception_index = -1;
751 
752         if (unlikely(cpu->singlestep_enabled)) {
753             /*
754              * After processing the exception, ensure an EXCP_DEBUG is
755              * raised when single-stepping so that GDB doesn't miss the
756              * next instruction.
757              */
758             *ret = EXCP_DEBUG;
759             cpu_handle_debug_exception(cpu);
760             return true;
761         }
762     } else if (!replay_has_interrupt()) {
763         /* give a chance to iothread in replay mode */
764         *ret = EXCP_INTERRUPT;
765         return true;
766     }
767 #endif
768 
769     return false;
770 }
771 
772 static inline bool icount_exit_request(CPUState *cpu)
773 {
774     if (!icount_enabled()) {
775         return false;
776     }
777     if (cpu->cflags_next_tb != -1 && !(cpu->cflags_next_tb & CF_USE_ICOUNT)) {
778         return false;
779     }
780     return cpu->neg.icount_decr.u16.low + cpu->icount_extra == 0;
781 }
782 
783 static inline bool cpu_handle_interrupt(CPUState *cpu,
784                                         TranslationBlock **last_tb)
785 {
786     /*
787      * If we have requested custom cflags with CF_NOIRQ we should
788      * skip checking here. Any pending interrupts will get picked up
789      * by the next TB we execute under normal cflags.
790      */
791     if (cpu->cflags_next_tb != -1 && cpu->cflags_next_tb & CF_NOIRQ) {
792         return false;
793     }
794 
795     /* Clear the interrupt flag now since we're processing
796      * cpu->interrupt_request and cpu->exit_request.
797      * Ensure zeroing happens before reading cpu->exit_request or
798      * cpu->interrupt_request (see also smp_wmb in cpu_exit())
799      */
800     qatomic_set_mb(&cpu->neg.icount_decr.u16.high, 0);
801 
802     if (unlikely(qatomic_read(&cpu->interrupt_request))) {
803         int interrupt_request;
804         bql_lock();
805         interrupt_request = cpu->interrupt_request;
806         if (unlikely(cpu->singlestep_enabled & SSTEP_NOIRQ)) {
807             /* Mask out external interrupts for this step. */
808             interrupt_request &= ~CPU_INTERRUPT_SSTEP_MASK;
809         }
810         if (interrupt_request & CPU_INTERRUPT_DEBUG) {
811             cpu->interrupt_request &= ~CPU_INTERRUPT_DEBUG;
812             cpu->exception_index = EXCP_DEBUG;
813             bql_unlock();
814             return true;
815         }
816 #if !defined(CONFIG_USER_ONLY)
817         if (replay_mode == REPLAY_MODE_PLAY && !replay_has_interrupt()) {
818             /* Do nothing */
819         } else if (interrupt_request & CPU_INTERRUPT_HALT) {
820             replay_interrupt();
821             cpu->interrupt_request &= ~CPU_INTERRUPT_HALT;
822             cpu->halted = 1;
823             cpu->exception_index = EXCP_HLT;
824             bql_unlock();
825             return true;
826         }
827 #if defined(TARGET_I386)
828         else if (interrupt_request & CPU_INTERRUPT_INIT) {
829             X86CPU *x86_cpu = X86_CPU(cpu);
830             CPUArchState *env = &x86_cpu->env;
831             replay_interrupt();
832             cpu_svm_check_intercept_param(env, SVM_EXIT_INIT, 0, 0);
833             do_cpu_init(x86_cpu);
834             cpu->exception_index = EXCP_HALTED;
835             bql_unlock();
836             return true;
837         }
838 #else
839         else if (interrupt_request & CPU_INTERRUPT_RESET) {
840             replay_interrupt();
841             cpu_reset(cpu);
842             bql_unlock();
843             return true;
844         }
845 #endif /* !TARGET_I386 */
846         /* The target hook has 3 exit conditions:
847            False when the interrupt isn't processed,
848            True when it is, and we should restart on a new TB,
849            and via longjmp via cpu_loop_exit.  */
850         else {
851             const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
852 
853             if (tcg_ops->cpu_exec_interrupt(cpu, interrupt_request)) {
854                 if (!tcg_ops->need_replay_interrupt ||
855                     tcg_ops->need_replay_interrupt(interrupt_request)) {
856                     replay_interrupt();
857                 }
858                 /*
859                  * After processing the interrupt, ensure an EXCP_DEBUG is
860                  * raised when single-stepping so that GDB doesn't miss the
861                  * next instruction.
862                  */
863                 if (unlikely(cpu->singlestep_enabled)) {
864                     cpu->exception_index = EXCP_DEBUG;
865                     bql_unlock();
866                     return true;
867                 }
868                 cpu->exception_index = -1;
869                 *last_tb = NULL;
870             }
871             /* The target hook may have updated the 'cpu->interrupt_request';
872              * reload the 'interrupt_request' value */
873             interrupt_request = cpu->interrupt_request;
874         }
875 #endif /* !CONFIG_USER_ONLY */
876         if (interrupt_request & CPU_INTERRUPT_EXITTB) {
877             cpu->interrupt_request &= ~CPU_INTERRUPT_EXITTB;
878             /* ensure that no TB jump will be modified as
879                the program flow was changed */
880             *last_tb = NULL;
881         }
882 
883         /* If we exit via cpu_loop_exit/longjmp it is reset in cpu_exec */
884         bql_unlock();
885     }
886 
887     /* Finally, check if we need to exit to the main loop.  */
888     if (unlikely(qatomic_read(&cpu->exit_request)) || icount_exit_request(cpu)) {
889         qatomic_set(&cpu->exit_request, 0);
890         if (cpu->exception_index == -1) {
891             cpu->exception_index = EXCP_INTERRUPT;
892         }
893         return true;
894     }
895 
896     return false;
897 }
898 
899 static inline void cpu_loop_exec_tb(CPUState *cpu, TranslationBlock *tb,
900                                     vaddr pc, TranslationBlock **last_tb,
901                                     int *tb_exit)
902 {
903     trace_exec_tb(tb, pc);
904     tb = cpu_tb_exec(cpu, tb, tb_exit);
905     if (*tb_exit != TB_EXIT_REQUESTED) {
906         *last_tb = tb;
907         return;
908     }
909 
910     *last_tb = NULL;
911     if (cpu_loop_exit_requested(cpu)) {
912         /* Something asked us to stop executing chained TBs; just
913          * continue round the main loop. Whatever requested the exit
914          * will also have set something else (eg exit_request or
915          * interrupt_request) which will be handled by
916          * cpu_handle_interrupt.  cpu_handle_interrupt will also
917          * clear cpu->icount_decr.u16.high.
918          */
919         return;
920     }
921 
922     /* Instruction counter expired.  */
923     assert(icount_enabled());
924 #ifndef CONFIG_USER_ONLY
925     /* Ensure global icount has gone forward */
926     icount_update(cpu);
927     /* Refill decrementer and continue execution.  */
928     int32_t insns_left = MIN(0xffff, cpu->icount_budget);
929     cpu->neg.icount_decr.u16.low = insns_left;
930     cpu->icount_extra = cpu->icount_budget - insns_left;
931 
932     /*
933      * If the next tb has more instructions than we have left to
934      * execute we need to ensure we find/generate a TB with exactly
935      * insns_left instructions in it.
936      */
937     if (insns_left > 0 && insns_left < tb->icount)  {
938         assert(insns_left <= CF_COUNT_MASK);
939         assert(cpu->icount_extra == 0);
940         cpu->cflags_next_tb = (tb->cflags & ~CF_COUNT_MASK) | insns_left;
941     }
942 #endif
943 }
944 
945 /* main execution loop */
946 
947 static int __attribute__((noinline))
948 cpu_exec_loop(CPUState *cpu, SyncClocks *sc)
949 {
950     int ret;
951 
952     /* if an exception is pending, we execute it here */
953     while (!cpu_handle_exception(cpu, &ret)) {
954         TranslationBlock *last_tb = NULL;
955         int tb_exit = 0;
956 
957         while (!cpu_handle_interrupt(cpu, &last_tb)) {
958             TranslationBlock *tb;
959             vaddr pc;
960             uint64_t cs_base;
961             uint32_t flags, cflags;
962 
963             cpu_get_tb_cpu_state(cpu_env(cpu), &pc, &cs_base, &flags);
964 
965             /*
966              * When requested, use an exact setting for cflags for the next
967              * execution.  This is used for icount, precise smc, and stop-
968              * after-access watchpoints.  Since this request should never
969              * have CF_INVALID set, -1 is a convenient invalid value that
970              * does not require tcg headers for cpu_common_reset.
971              */
972             cflags = cpu->cflags_next_tb;
973             if (cflags == -1) {
974                 cflags = curr_cflags(cpu);
975             } else {
976                 cpu->cflags_next_tb = -1;
977             }
978 
979             if (check_for_breakpoints(cpu, pc, &cflags)) {
980                 break;
981             }
982 
983             tb = tb_lookup(cpu, pc, cs_base, flags, cflags);
984             if (tb == NULL) {
985                 CPUJumpCache *jc;
986                 uint32_t h;
987 
988                 mmap_lock();
989                 tb = tb_gen_code(cpu, pc, cs_base, flags, cflags);
990                 mmap_unlock();
991 
992                 /*
993                  * We add the TB in the virtual pc hash table
994                  * for the fast lookup
995                  */
996                 h = tb_jmp_cache_hash_func(pc);
997                 jc = cpu->tb_jmp_cache;
998                 jc->array[h].pc = pc;
999                 qatomic_set(&jc->array[h].tb, tb);
1000             }
1001 
1002 #ifndef CONFIG_USER_ONLY
1003             /*
1004              * We don't take care of direct jumps when address mapping
1005              * changes in system emulation.  So it's not safe to make a
1006              * direct jump to a TB spanning two pages because the mapping
1007              * for the second page can change.
1008              */
1009             if (tb_page_addr1(tb) != -1) {
1010                 last_tb = NULL;
1011             }
1012 #endif
1013             /* See if we can patch the calling TB. */
1014             if (last_tb) {
1015                 tb_add_jump(last_tb, tb_exit, tb);
1016             }
1017 
1018             cpu_loop_exec_tb(cpu, tb, pc, &last_tb, &tb_exit);
1019 
1020             /* Try to align the host and virtual clocks
1021                if the guest is in advance */
1022             align_clocks(sc, cpu);
1023         }
1024     }
1025     return ret;
1026 }
1027 
1028 static int cpu_exec_setjmp(CPUState *cpu, SyncClocks *sc)
1029 {
1030     /* Prepare setjmp context for exception handling. */
1031     if (unlikely(sigsetjmp(cpu->jmp_env, 0) != 0)) {
1032         cpu_exec_longjmp_cleanup(cpu);
1033     }
1034 
1035     return cpu_exec_loop(cpu, sc);
1036 }
1037 
1038 int cpu_exec(CPUState *cpu)
1039 {
1040     int ret;
1041     SyncClocks sc = { 0 };
1042 
1043     /* replay_interrupt may need current_cpu */
1044     current_cpu = cpu;
1045 
1046     if (cpu_handle_halt(cpu)) {
1047         return EXCP_HALTED;
1048     }
1049 
1050     RCU_READ_LOCK_GUARD();
1051     cpu_exec_enter(cpu);
1052 
1053     /*
1054      * Calculate difference between guest clock and host clock.
1055      * This delay includes the delay of the last cycle, so
1056      * what we have to do is sleep until it is 0. As for the
1057      * advance/delay we gain here, we try to fix it next time.
1058      */
1059     init_delay_params(&sc, cpu);
1060 
1061     ret = cpu_exec_setjmp(cpu, &sc);
1062 
1063     cpu_exec_exit(cpu);
1064     return ret;
1065 }
1066 
1067 bool tcg_exec_realizefn(CPUState *cpu, Error **errp)
1068 {
1069     static bool tcg_target_initialized;
1070 
1071     if (!tcg_target_initialized) {
1072         /* Check mandatory TCGCPUOps handlers */
1073         const TCGCPUOps *tcg_ops = cpu->cc->tcg_ops;
1074 #ifndef CONFIG_USER_ONLY
1075         assert(tcg_ops->cpu_exec_halt);
1076         assert(tcg_ops->cpu_exec_interrupt);
1077 #endif /* !CONFIG_USER_ONLY */
1078         assert(tcg_ops->translate_code);
1079         assert(tcg_ops->mmu_index);
1080         tcg_ops->initialize();
1081         tcg_target_initialized = true;
1082     }
1083 
1084     cpu->tb_jmp_cache = g_new0(CPUJumpCache, 1);
1085     tlb_init(cpu);
1086 #ifndef CONFIG_USER_ONLY
1087     tcg_iommu_init_notifier_list(cpu);
1088 #endif /* !CONFIG_USER_ONLY */
1089     /* qemu_plugin_vcpu_init_hook delayed until cpu_index assigned. */
1090 
1091     return true;
1092 }
1093 
1094 /* undo the initializations in reverse order */
1095 void tcg_exec_unrealizefn(CPUState *cpu)
1096 {
1097 #ifndef CONFIG_USER_ONLY
1098     tcg_iommu_free_notifier_list(cpu);
1099 #endif /* !CONFIG_USER_ONLY */
1100 
1101     tlb_destroy(cpu);
1102     g_free_rcu(cpu->tb_jmp_cache, rcu);
1103 }
1104