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