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