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