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