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