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