xref: /openbmc/qemu/accel/tcg/cpu-exec.c (revision e6a41a04)
1 /*
2  *  emulator main execution loop
3  *
4  *  Copyright (c) 2003-2005 Fabrice Bellard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "qemu/osdep.h"
21 #include "qemu-common.h"
22 #include "qemu/qemu-print.h"
23 #include "cpu.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/compiler.h"
31 #include "sysemu/qtest.h"
32 #include "qemu/timer.h"
33 #include "qemu/rcu.h"
34 #include "exec/tb-hash.h"
35 #include "exec/tb-lookup.h"
36 #include "exec/log.h"
37 #include "qemu/main-loop.h"
38 #if defined(TARGET_I386) && !defined(CONFIG_USER_ONLY)
39 #include "hw/i386/apic.h"
40 #endif
41 #include "sysemu/cpus.h"
42 #include "exec/cpu-all.h"
43 #include "sysemu/cpu-timers.h"
44 #include "sysemu/replay.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 static int64_t max_delay;
66 static 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 /* Execute a TB, and fix up the CPU state afterwards if necessary */
150 /*
151  * Disable CFI checks.
152  * TCG creates binary blobs at runtime, with the transformed code.
153  * A TB is a blob of binary code, created at runtime and called with an
154  * indirect function call. Since such function did not exist at compile time,
155  * the CFI runtime has no way to verify its signature and would fail.
156  * TCG is not considered a security-sensitive part of QEMU so this does not
157  * affect the impact of CFI in environment with high security requirements
158  */
159 static inline TranslationBlock * QEMU_DISABLE_CFI
160 cpu_tb_exec(CPUState *cpu, TranslationBlock *itb, int *tb_exit)
161 {
162     CPUArchState *env = cpu->env_ptr;
163     uintptr_t ret;
164     TranslationBlock *last_tb;
165     const void *tb_ptr = itb->tc.ptr;
166 
167     qemu_log_mask_and_addr(CPU_LOG_EXEC, itb->pc,
168                            "Trace %d: %p ["
169                            TARGET_FMT_lx "/" TARGET_FMT_lx "/%#x] %s\n",
170                            cpu->cpu_index, itb->tc.ptr,
171                            itb->cs_base, itb->pc, itb->flags,
172                            lookup_symbol(itb->pc));
173 
174 #if defined(DEBUG_DISAS)
175     if (qemu_loglevel_mask(CPU_LOG_TB_CPU)
176         && qemu_log_in_addr_range(itb->pc)) {
177         FILE *logfile = qemu_log_lock();
178         int flags = 0;
179         if (qemu_loglevel_mask(CPU_LOG_TB_FPU)) {
180             flags |= CPU_DUMP_FPU;
181         }
182 #if defined(TARGET_I386)
183         flags |= CPU_DUMP_CCOP;
184 #endif
185         log_cpu_state(cpu, flags);
186         qemu_log_unlock(logfile);
187     }
188 #endif /* DEBUG_DISAS */
189 
190     qemu_thread_jit_execute();
191     ret = tcg_qemu_tb_exec(env, tb_ptr);
192     cpu->can_do_io = 1;
193     /*
194      * TODO: Delay swapping back to the read-write region of the TB
195      * until we actually need to modify the TB.  The read-only copy,
196      * coming from the rx region, shares the same host TLB entry as
197      * the code that executed the exit_tb opcode that arrived here.
198      * If we insist on touching both the RX and the RW pages, we
199      * double the host TLB pressure.
200      */
201     last_tb = tcg_splitwx_to_rw((void *)(ret & ~TB_EXIT_MASK));
202     *tb_exit = ret & TB_EXIT_MASK;
203 
204     trace_exec_tb_exit(last_tb, *tb_exit);
205 
206     if (*tb_exit > TB_EXIT_IDX1) {
207         /* We didn't start executing this TB (eg because the instruction
208          * counter hit zero); we must restore the guest PC to the address
209          * of the start of the TB.
210          */
211         CPUClass *cc = CPU_GET_CLASS(cpu);
212         qemu_log_mask_and_addr(CPU_LOG_EXEC, last_tb->pc,
213                                "Stopped execution of TB chain before %p ["
214                                TARGET_FMT_lx "] %s\n",
215                                last_tb->tc.ptr, last_tb->pc,
216                                lookup_symbol(last_tb->pc));
217         if (cc->tcg_ops->synchronize_from_tb) {
218             cc->tcg_ops->synchronize_from_tb(cpu, last_tb);
219         } else {
220             assert(cc->set_pc);
221             cc->set_pc(cpu, last_tb->pc);
222         }
223     }
224     return last_tb;
225 }
226 
227 #ifndef CONFIG_USER_ONLY
228 /* Execute the code without caching the generated code. An interpreter
229    could be used if available. */
230 static void cpu_exec_nocache(CPUState *cpu, int max_cycles,
231                              TranslationBlock *orig_tb, bool ignore_icount)
232 {
233     TranslationBlock *tb;
234     uint32_t cflags = curr_cflags() | CF_NOCACHE;
235     int tb_exit;
236 
237     if (ignore_icount) {
238         cflags &= ~CF_USE_ICOUNT;
239     }
240 
241     /* Should never happen.
242        We only end up here when an existing TB is too long.  */
243     cflags |= MIN(max_cycles, CF_COUNT_MASK);
244 
245     mmap_lock();
246     tb = tb_gen_code(cpu, orig_tb->pc, orig_tb->cs_base,
247                      orig_tb->flags, cflags);
248     tb->orig_tb = orig_tb;
249     mmap_unlock();
250 
251     /* execute the generated code */
252     trace_exec_tb_nocache(tb, tb->pc);
253     cpu_tb_exec(cpu, tb, &tb_exit);
254 
255     mmap_lock();
256     tb_phys_invalidate(tb, -1);
257     mmap_unlock();
258     tcg_tb_remove(tb);
259 }
260 #endif
261 
262 static void cpu_exec_enter(CPUState *cpu)
263 {
264     CPUClass *cc = CPU_GET_CLASS(cpu);
265 
266     if (cc->tcg_ops->cpu_exec_enter) {
267         cc->tcg_ops->cpu_exec_enter(cpu);
268     }
269 }
270 
271 static void cpu_exec_exit(CPUState *cpu)
272 {
273     CPUClass *cc = CPU_GET_CLASS(cpu);
274 
275     if (cc->tcg_ops->cpu_exec_exit) {
276         cc->tcg_ops->cpu_exec_exit(cpu);
277     }
278 }
279 
280 void cpu_exec_step_atomic(CPUState *cpu)
281 {
282     TranslationBlock *tb;
283     target_ulong cs_base, pc;
284     uint32_t flags;
285     uint32_t cflags = 1;
286     uint32_t cf_mask = cflags & CF_HASH_MASK;
287     int tb_exit;
288 
289     if (sigsetjmp(cpu->jmp_env, 0) == 0) {
290         start_exclusive();
291         g_assert(cpu == current_cpu);
292         g_assert(!cpu->running);
293         cpu->running = true;
294 
295         tb = tb_lookup__cpu_state(cpu, &pc, &cs_base, &flags, cf_mask);
296         if (tb == NULL) {
297             mmap_lock();
298             tb = tb_gen_code(cpu, pc, cs_base, flags, cflags);
299             mmap_unlock();
300         }
301 
302         /* Since we got here, we know that parallel_cpus must be true.  */
303         parallel_cpus = false;
304         cpu_exec_enter(cpu);
305         /* execute the generated code */
306         trace_exec_tb(tb, pc);
307         cpu_tb_exec(cpu, tb, &tb_exit);
308         cpu_exec_exit(cpu);
309     } else {
310         /*
311          * The mmap_lock is dropped by tb_gen_code if it runs out of
312          * memory.
313          */
314 #ifndef CONFIG_SOFTMMU
315         tcg_debug_assert(!have_mmap_lock());
316 #endif
317         if (qemu_mutex_iothread_locked()) {
318             qemu_mutex_unlock_iothread();
319         }
320         assert_no_pages_locked();
321         qemu_plugin_disable_mem_helpers(cpu);
322     }
323 
324 
325     /*
326      * As we start the exclusive region before codegen we must still
327      * be in the region if we longjump out of either the codegen or
328      * the execution.
329      */
330     g_assert(cpu_in_exclusive_context(cpu));
331     parallel_cpus = true;
332     cpu->running = false;
333     end_exclusive();
334 }
335 
336 struct tb_desc {
337     target_ulong pc;
338     target_ulong cs_base;
339     CPUArchState *env;
340     tb_page_addr_t phys_page1;
341     uint32_t flags;
342     uint32_t cf_mask;
343     uint32_t trace_vcpu_dstate;
344 };
345 
346 static bool tb_lookup_cmp(const void *p, const void *d)
347 {
348     const TranslationBlock *tb = p;
349     const struct tb_desc *desc = d;
350 
351     if (tb->pc == desc->pc &&
352         tb->page_addr[0] == desc->phys_page1 &&
353         tb->cs_base == desc->cs_base &&
354         tb->flags == desc->flags &&
355         tb->trace_vcpu_dstate == desc->trace_vcpu_dstate &&
356         (tb_cflags(tb) & (CF_HASH_MASK | CF_INVALID)) == desc->cf_mask) {
357         /* check next page if needed */
358         if (tb->page_addr[1] == -1) {
359             return true;
360         } else {
361             tb_page_addr_t phys_page2;
362             target_ulong virt_page2;
363 
364             virt_page2 = (desc->pc & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;
365             phys_page2 = get_page_addr_code(desc->env, virt_page2);
366             if (tb->page_addr[1] == phys_page2) {
367                 return true;
368             }
369         }
370     }
371     return false;
372 }
373 
374 TranslationBlock *tb_htable_lookup(CPUState *cpu, target_ulong pc,
375                                    target_ulong cs_base, uint32_t flags,
376                                    uint32_t cf_mask)
377 {
378     tb_page_addr_t phys_pc;
379     struct tb_desc desc;
380     uint32_t h;
381 
382     desc.env = (CPUArchState *)cpu->env_ptr;
383     desc.cs_base = cs_base;
384     desc.flags = flags;
385     desc.cf_mask = cf_mask;
386     desc.trace_vcpu_dstate = *cpu->trace_dstate;
387     desc.pc = pc;
388     phys_pc = get_page_addr_code(desc.env, pc);
389     if (phys_pc == -1) {
390         return NULL;
391     }
392     desc.phys_page1 = phys_pc & TARGET_PAGE_MASK;
393     h = tb_hash_func(phys_pc, pc, flags, cf_mask, *cpu->trace_dstate);
394     return qht_lookup_custom(&tb_ctx.htable, &desc, h, tb_lookup_cmp);
395 }
396 
397 void tb_set_jmp_target(TranslationBlock *tb, int n, uintptr_t addr)
398 {
399     if (TCG_TARGET_HAS_direct_jump) {
400         uintptr_t offset = tb->jmp_target_arg[n];
401         uintptr_t tc_ptr = (uintptr_t)tb->tc.ptr;
402         uintptr_t jmp_rx = tc_ptr + offset;
403         uintptr_t jmp_rw = jmp_rx - tcg_splitwx_diff;
404         tb_target_set_jmp_target(tc_ptr, jmp_rx, jmp_rw, addr);
405     } else {
406         tb->jmp_target_arg[n] = addr;
407     }
408 }
409 
410 static inline void tb_add_jump(TranslationBlock *tb, int n,
411                                TranslationBlock *tb_next)
412 {
413     uintptr_t old;
414 
415     qemu_thread_jit_write();
416     assert(n < ARRAY_SIZE(tb->jmp_list_next));
417     qemu_spin_lock(&tb_next->jmp_lock);
418 
419     /* make sure the destination TB is valid */
420     if (tb_next->cflags & CF_INVALID) {
421         goto out_unlock_next;
422     }
423     /* Atomically claim the jump destination slot only if it was NULL */
424     old = qatomic_cmpxchg(&tb->jmp_dest[n], (uintptr_t)NULL,
425                           (uintptr_t)tb_next);
426     if (old) {
427         goto out_unlock_next;
428     }
429 
430     /* patch the native jump address */
431     tb_set_jmp_target(tb, n, (uintptr_t)tb_next->tc.ptr);
432 
433     /* add in TB jmp list */
434     tb->jmp_list_next[n] = tb_next->jmp_list_head;
435     tb_next->jmp_list_head = (uintptr_t)tb | n;
436 
437     qemu_spin_unlock(&tb_next->jmp_lock);
438 
439     qemu_log_mask_and_addr(CPU_LOG_EXEC, tb->pc,
440                            "Linking TBs %p [" TARGET_FMT_lx
441                            "] index %d -> %p [" TARGET_FMT_lx "]\n",
442                            tb->tc.ptr, tb->pc, n,
443                            tb_next->tc.ptr, tb_next->pc);
444     return;
445 
446  out_unlock_next:
447     qemu_spin_unlock(&tb_next->jmp_lock);
448     return;
449 }
450 
451 static inline TranslationBlock *tb_find(CPUState *cpu,
452                                         TranslationBlock *last_tb,
453                                         int tb_exit, uint32_t cf_mask)
454 {
455     TranslationBlock *tb;
456     target_ulong cs_base, pc;
457     uint32_t flags;
458 
459     tb = tb_lookup__cpu_state(cpu, &pc, &cs_base, &flags, cf_mask);
460     if (tb == NULL) {
461         mmap_lock();
462         tb = tb_gen_code(cpu, pc, cs_base, flags, cf_mask);
463         mmap_unlock();
464         /* We add the TB in the virtual pc hash table for the fast lookup */
465         qatomic_set(&cpu->tb_jmp_cache[tb_jmp_cache_hash_func(pc)], tb);
466     }
467 #ifndef CONFIG_USER_ONLY
468     /* We don't take care of direct jumps when address mapping changes in
469      * system emulation. So it's not safe to make a direct jump to a TB
470      * spanning two pages because the mapping for the second page can change.
471      */
472     if (tb->page_addr[1] != -1) {
473         last_tb = NULL;
474     }
475 #endif
476     /* See if we can patch the calling TB. */
477     if (last_tb) {
478         tb_add_jump(last_tb, tb_exit, tb);
479     }
480     return tb;
481 }
482 
483 static inline bool cpu_handle_halt(CPUState *cpu)
484 {
485     if (cpu->halted) {
486 #if defined(TARGET_I386) && !defined(CONFIG_USER_ONLY)
487         if (cpu->interrupt_request & CPU_INTERRUPT_POLL) {
488             X86CPU *x86_cpu = X86_CPU(cpu);
489             qemu_mutex_lock_iothread();
490             apic_poll_irq(x86_cpu->apic_state);
491             cpu_reset_interrupt(cpu, CPU_INTERRUPT_POLL);
492             qemu_mutex_unlock_iothread();
493         }
494 #endif
495         if (!cpu_has_work(cpu)) {
496             return true;
497         }
498 
499         cpu->halted = 0;
500     }
501 
502     return false;
503 }
504 
505 static inline void cpu_handle_debug_exception(CPUState *cpu)
506 {
507     CPUClass *cc = CPU_GET_CLASS(cpu);
508     CPUWatchpoint *wp;
509 
510     if (!cpu->watchpoint_hit) {
511         QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
512             wp->flags &= ~BP_WATCHPOINT_HIT;
513         }
514     }
515 
516     if (cc->tcg_ops->debug_excp_handler) {
517         cc->tcg_ops->debug_excp_handler(cpu);
518     }
519 }
520 
521 static inline bool cpu_handle_exception(CPUState *cpu, int *ret)
522 {
523     if (cpu->exception_index < 0) {
524 #ifndef CONFIG_USER_ONLY
525         if (replay_has_exception()
526             && cpu_neg(cpu)->icount_decr.u16.low + cpu->icount_extra == 0) {
527             /* try to cause an exception pending in the log */
528             cpu_exec_nocache(cpu, 1, tb_find(cpu, NULL, 0, curr_cflags()), true);
529         }
530 #endif
531         if (cpu->exception_index < 0) {
532             return false;
533         }
534     }
535 
536     if (cpu->exception_index >= EXCP_INTERRUPT) {
537         /* exit request from the cpu execution loop */
538         *ret = cpu->exception_index;
539         if (*ret == EXCP_DEBUG) {
540             cpu_handle_debug_exception(cpu);
541         }
542         cpu->exception_index = -1;
543         return true;
544     } else {
545 #if defined(CONFIG_USER_ONLY)
546         /* if user mode only, we simulate a fake exception
547            which will be handled outside the cpu execution
548            loop */
549 #if defined(TARGET_I386)
550         CPUClass *cc = CPU_GET_CLASS(cpu);
551         cc->tcg_ops->do_interrupt(cpu);
552 #endif
553         *ret = cpu->exception_index;
554         cpu->exception_index = -1;
555         return true;
556 #else
557         if (replay_exception()) {
558             CPUClass *cc = CPU_GET_CLASS(cpu);
559             qemu_mutex_lock_iothread();
560             cc->tcg_ops->do_interrupt(cpu);
561             qemu_mutex_unlock_iothread();
562             cpu->exception_index = -1;
563 
564             if (unlikely(cpu->singlestep_enabled)) {
565                 /*
566                  * After processing the exception, ensure an EXCP_DEBUG is
567                  * raised when single-stepping so that GDB doesn't miss the
568                  * next instruction.
569                  */
570                 *ret = EXCP_DEBUG;
571                 cpu_handle_debug_exception(cpu);
572                 return true;
573             }
574         } else if (!replay_has_interrupt()) {
575             /* give a chance to iothread in replay mode */
576             *ret = EXCP_INTERRUPT;
577             return true;
578         }
579 #endif
580     }
581 
582     return false;
583 }
584 
585 /*
586  * CPU_INTERRUPT_POLL is a virtual event which gets converted into a
587  * "real" interrupt event later. It does not need to be recorded for
588  * replay purposes.
589  */
590 static inline bool need_replay_interrupt(int interrupt_request)
591 {
592 #if defined(TARGET_I386)
593     return !(interrupt_request & CPU_INTERRUPT_POLL);
594 #else
595     return true;
596 #endif
597 }
598 
599 static inline bool cpu_handle_interrupt(CPUState *cpu,
600                                         TranslationBlock **last_tb)
601 {
602     CPUClass *cc = CPU_GET_CLASS(cpu);
603 
604     /* Clear the interrupt flag now since we're processing
605      * cpu->interrupt_request and cpu->exit_request.
606      * Ensure zeroing happens before reading cpu->exit_request or
607      * cpu->interrupt_request (see also smp_wmb in cpu_exit())
608      */
609     qatomic_mb_set(&cpu_neg(cpu)->icount_decr.u16.high, 0);
610 
611     if (unlikely(qatomic_read(&cpu->interrupt_request))) {
612         int interrupt_request;
613         qemu_mutex_lock_iothread();
614         interrupt_request = cpu->interrupt_request;
615         if (unlikely(cpu->singlestep_enabled & SSTEP_NOIRQ)) {
616             /* Mask out external interrupts for this step. */
617             interrupt_request &= ~CPU_INTERRUPT_SSTEP_MASK;
618         }
619         if (interrupt_request & CPU_INTERRUPT_DEBUG) {
620             cpu->interrupt_request &= ~CPU_INTERRUPT_DEBUG;
621             cpu->exception_index = EXCP_DEBUG;
622             qemu_mutex_unlock_iothread();
623             return true;
624         }
625         if (replay_mode == REPLAY_MODE_PLAY && !replay_has_interrupt()) {
626             /* Do nothing */
627         } else if (interrupt_request & CPU_INTERRUPT_HALT) {
628             replay_interrupt();
629             cpu->interrupt_request &= ~CPU_INTERRUPT_HALT;
630             cpu->halted = 1;
631             cpu->exception_index = EXCP_HLT;
632             qemu_mutex_unlock_iothread();
633             return true;
634         }
635 #if defined(TARGET_I386)
636         else if (interrupt_request & CPU_INTERRUPT_INIT) {
637             X86CPU *x86_cpu = X86_CPU(cpu);
638             CPUArchState *env = &x86_cpu->env;
639             replay_interrupt();
640             cpu_svm_check_intercept_param(env, SVM_EXIT_INIT, 0, 0);
641             do_cpu_init(x86_cpu);
642             cpu->exception_index = EXCP_HALTED;
643             qemu_mutex_unlock_iothread();
644             return true;
645         }
646 #else
647         else if (interrupt_request & CPU_INTERRUPT_RESET) {
648             replay_interrupt();
649             cpu_reset(cpu);
650             qemu_mutex_unlock_iothread();
651             return true;
652         }
653 #endif
654         /* The target hook has 3 exit conditions:
655            False when the interrupt isn't processed,
656            True when it is, and we should restart on a new TB,
657            and via longjmp via cpu_loop_exit.  */
658         else {
659             if (cc->tcg_ops->cpu_exec_interrupt &&
660                 cc->tcg_ops->cpu_exec_interrupt(cpu, interrupt_request)) {
661                 if (need_replay_interrupt(interrupt_request)) {
662                     replay_interrupt();
663                 }
664                 /*
665                  * After processing the interrupt, ensure an EXCP_DEBUG is
666                  * raised when single-stepping so that GDB doesn't miss the
667                  * next instruction.
668                  */
669                 cpu->exception_index =
670                     (cpu->singlestep_enabled ? EXCP_DEBUG : -1);
671                 *last_tb = NULL;
672             }
673             /* The target hook may have updated the 'cpu->interrupt_request';
674              * reload the 'interrupt_request' value */
675             interrupt_request = cpu->interrupt_request;
676         }
677         if (interrupt_request & CPU_INTERRUPT_EXITTB) {
678             cpu->interrupt_request &= ~CPU_INTERRUPT_EXITTB;
679             /* ensure that no TB jump will be modified as
680                the program flow was changed */
681             *last_tb = NULL;
682         }
683 
684         /* If we exit via cpu_loop_exit/longjmp it is reset in cpu_exec */
685         qemu_mutex_unlock_iothread();
686     }
687 
688     /* Finally, check if we need to exit to the main loop.  */
689     if (unlikely(qatomic_read(&cpu->exit_request))
690         || (icount_enabled()
691             && cpu_neg(cpu)->icount_decr.u16.low + cpu->icount_extra == 0)) {
692         qatomic_set(&cpu->exit_request, 0);
693         if (cpu->exception_index == -1) {
694             cpu->exception_index = EXCP_INTERRUPT;
695         }
696         return true;
697     }
698 
699     return false;
700 }
701 
702 static inline void cpu_loop_exec_tb(CPUState *cpu, TranslationBlock *tb,
703                                     TranslationBlock **last_tb, int *tb_exit)
704 {
705     int32_t insns_left;
706 
707     trace_exec_tb(tb, tb->pc);
708     tb = cpu_tb_exec(cpu, tb, tb_exit);
709     if (*tb_exit != TB_EXIT_REQUESTED) {
710         *last_tb = tb;
711         return;
712     }
713 
714     *last_tb = NULL;
715     insns_left = qatomic_read(&cpu_neg(cpu)->icount_decr.u32);
716     if (insns_left < 0) {
717         /* Something asked us to stop executing chained TBs; just
718          * continue round the main loop. Whatever requested the exit
719          * will also have set something else (eg exit_request or
720          * interrupt_request) which will be handled by
721          * cpu_handle_interrupt.  cpu_handle_interrupt will also
722          * clear cpu->icount_decr.u16.high.
723          */
724         return;
725     }
726 
727     /* Instruction counter expired.  */
728     assert(icount_enabled());
729 #ifndef CONFIG_USER_ONLY
730     /* Ensure global icount has gone forward */
731     icount_update(cpu);
732     /* Refill decrementer and continue execution.  */
733     insns_left = MIN(0xffff, cpu->icount_budget);
734     cpu_neg(cpu)->icount_decr.u16.low = insns_left;
735     cpu->icount_extra = cpu->icount_budget - insns_left;
736     if (!cpu->icount_extra && insns_left < tb->icount) {
737         /* Execute any remaining instructions, then let the main loop
738          * handle the next event.
739          */
740         if (insns_left > 0) {
741             cpu_exec_nocache(cpu, insns_left, tb, false);
742         }
743     }
744 #endif
745 }
746 
747 /* main execution loop */
748 
749 int cpu_exec(CPUState *cpu)
750 {
751     CPUClass *cc = CPU_GET_CLASS(cpu);
752     int ret;
753     SyncClocks sc = { 0 };
754 
755     /* replay_interrupt may need current_cpu */
756     current_cpu = cpu;
757 
758     if (cpu_handle_halt(cpu)) {
759         return EXCP_HALTED;
760     }
761 
762     rcu_read_lock();
763 
764     cpu_exec_enter(cpu);
765 
766     /* Calculate difference between guest clock and host clock.
767      * This delay includes the delay of the last cycle, so
768      * what we have to do is sleep until it is 0. As for the
769      * advance/delay we gain here, we try to fix it next time.
770      */
771     init_delay_params(&sc, cpu);
772 
773     /* prepare setjmp context for exception handling */
774     if (sigsetjmp(cpu->jmp_env, 0) != 0) {
775 #if defined(__clang__)
776         /*
777          * Some compilers wrongly smash all local variables after
778          * siglongjmp (the spec requires that only non-volatile locals
779          * which are changed between the sigsetjmp and siglongjmp are
780          * permitted to be trashed). There were bug reports for gcc
781          * 4.5.0 and clang.  The bug is fixed in all versions of gcc
782          * that we support, but is still unfixed in clang:
783          *   https://bugs.llvm.org/show_bug.cgi?id=21183
784          *
785          * Reload essential local variables here for those compilers.
786          * Newer versions of gcc would complain about this code (-Wclobbered),
787          * so we only perform the workaround for clang.
788          */
789         cpu = current_cpu;
790         cc = CPU_GET_CLASS(cpu);
791 #else
792         /*
793          * Non-buggy compilers preserve these locals; assert that
794          * they have the correct value.
795          */
796         g_assert(cpu == current_cpu);
797         g_assert(cc == CPU_GET_CLASS(cpu));
798 #endif
799 
800 #ifndef CONFIG_SOFTMMU
801         tcg_debug_assert(!have_mmap_lock());
802 #endif
803         if (qemu_mutex_iothread_locked()) {
804             qemu_mutex_unlock_iothread();
805         }
806         qemu_plugin_disable_mem_helpers(cpu);
807 
808         assert_no_pages_locked();
809     }
810 
811     /* if an exception is pending, we execute it here */
812     while (!cpu_handle_exception(cpu, &ret)) {
813         TranslationBlock *last_tb = NULL;
814         int tb_exit = 0;
815 
816         while (!cpu_handle_interrupt(cpu, &last_tb)) {
817             uint32_t cflags = cpu->cflags_next_tb;
818             TranslationBlock *tb;
819 
820             /* When requested, use an exact setting for cflags for the next
821                execution.  This is used for icount, precise smc, and stop-
822                after-access watchpoints.  Since this request should never
823                have CF_INVALID set, -1 is a convenient invalid value that
824                does not require tcg headers for cpu_common_reset.  */
825             if (cflags == -1) {
826                 cflags = curr_cflags();
827             } else {
828                 cpu->cflags_next_tb = -1;
829             }
830 
831             tb = tb_find(cpu, last_tb, tb_exit, cflags);
832             cpu_loop_exec_tb(cpu, tb, &last_tb, &tb_exit);
833             /* Try to align the host and virtual clocks
834                if the guest is in advance */
835             align_clocks(&sc, cpu);
836         }
837     }
838 
839     cpu_exec_exit(cpu);
840     rcu_read_unlock();
841 
842     return ret;
843 }
844 
845 void tcg_exec_realizefn(CPUState *cpu, Error **errp)
846 {
847     static bool tcg_target_initialized;
848     CPUClass *cc = CPU_GET_CLASS(cpu);
849 
850     if (!tcg_target_initialized) {
851         cc->tcg_ops->initialize();
852         tcg_target_initialized = true;
853     }
854     tlb_init(cpu);
855     qemu_plugin_vcpu_init_hook(cpu);
856 
857 #ifndef CONFIG_USER_ONLY
858     tcg_iommu_init_notifier_list(cpu);
859 #endif /* !CONFIG_USER_ONLY */
860 }
861 
862 /* undo the initializations in reverse order */
863 void tcg_exec_unrealizefn(CPUState *cpu)
864 {
865 #ifndef CONFIG_USER_ONLY
866     tcg_iommu_free_notifier_list(cpu);
867 #endif /* !CONFIG_USER_ONLY */
868 
869     qemu_plugin_vcpu_exit_hook(cpu);
870     tlb_destroy(cpu);
871 }
872 
873 #ifndef CONFIG_USER_ONLY
874 
875 void dump_drift_info(void)
876 {
877     if (!icount_enabled()) {
878         return;
879     }
880 
881     qemu_printf("Host - Guest clock  %"PRIi64" ms\n",
882                 (cpu_get_clock() - icount_get()) / SCALE_MS);
883     if (icount_align_option) {
884         qemu_printf("Max guest delay     %"PRIi64" ms\n",
885                     -max_delay / SCALE_MS);
886         qemu_printf("Max guest advance   %"PRIi64" ms\n",
887                     max_advance / SCALE_MS);
888     } else {
889         qemu_printf("Max guest delay     NA\n");
890         qemu_printf("Max guest advance   NA\n");
891     }
892 }
893 
894 #endif /* !CONFIG_USER_ONLY */
895