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