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