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