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