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