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