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