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