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