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