xref: /openbmc/qemu/accel/tcg/cpu-exec.c (revision 740b1759)
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 += cpu_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             && replay_interrupt()) {
441             X86CPU *x86_cpu = X86_CPU(cpu);
442             qemu_mutex_lock_iothread();
443             apic_poll_irq(x86_cpu->apic_state);
444             cpu_reset_interrupt(cpu, CPU_INTERRUPT_POLL);
445             qemu_mutex_unlock_iothread();
446         }
447 #endif
448         if (!cpu_has_work(cpu)) {
449             return true;
450         }
451 
452         cpu->halted = 0;
453     }
454 
455     return false;
456 }
457 
458 static inline void cpu_handle_debug_exception(CPUState *cpu)
459 {
460     CPUClass *cc = CPU_GET_CLASS(cpu);
461     CPUWatchpoint *wp;
462 
463     if (!cpu->watchpoint_hit) {
464         QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {
465             wp->flags &= ~BP_WATCHPOINT_HIT;
466         }
467     }
468 
469     cc->debug_excp_handler(cpu);
470 }
471 
472 static inline bool cpu_handle_exception(CPUState *cpu, int *ret)
473 {
474     if (cpu->exception_index < 0) {
475 #ifndef CONFIG_USER_ONLY
476         if (replay_has_exception()
477             && cpu_neg(cpu)->icount_decr.u16.low + cpu->icount_extra == 0) {
478             /* try to cause an exception pending in the log */
479             cpu_exec_nocache(cpu, 1, tb_find(cpu, NULL, 0, curr_cflags()), true);
480         }
481 #endif
482         if (cpu->exception_index < 0) {
483             return false;
484         }
485     }
486 
487     if (cpu->exception_index >= EXCP_INTERRUPT) {
488         /* exit request from the cpu execution loop */
489         *ret = cpu->exception_index;
490         if (*ret == EXCP_DEBUG) {
491             cpu_handle_debug_exception(cpu);
492         }
493         cpu->exception_index = -1;
494         return true;
495     } else {
496 #if defined(CONFIG_USER_ONLY)
497         /* if user mode only, we simulate a fake exception
498            which will be handled outside the cpu execution
499            loop */
500 #if defined(TARGET_I386)
501         CPUClass *cc = CPU_GET_CLASS(cpu);
502         cc->do_interrupt(cpu);
503 #endif
504         *ret = cpu->exception_index;
505         cpu->exception_index = -1;
506         return true;
507 #else
508         if (replay_exception()) {
509             CPUClass *cc = CPU_GET_CLASS(cpu);
510             qemu_mutex_lock_iothread();
511             cc->do_interrupt(cpu);
512             qemu_mutex_unlock_iothread();
513             cpu->exception_index = -1;
514 
515             if (unlikely(cpu->singlestep_enabled)) {
516                 /*
517                  * After processing the exception, ensure an EXCP_DEBUG is
518                  * raised when single-stepping so that GDB doesn't miss the
519                  * next instruction.
520                  */
521                 *ret = EXCP_DEBUG;
522                 cpu_handle_debug_exception(cpu);
523                 return true;
524             }
525         } else if (!replay_has_interrupt()) {
526             /* give a chance to iothread in replay mode */
527             *ret = EXCP_INTERRUPT;
528             return true;
529         }
530 #endif
531     }
532 
533     return false;
534 }
535 
536 static inline bool cpu_handle_interrupt(CPUState *cpu,
537                                         TranslationBlock **last_tb)
538 {
539     CPUClass *cc = CPU_GET_CLASS(cpu);
540 
541     /* Clear the interrupt flag now since we're processing
542      * cpu->interrupt_request and cpu->exit_request.
543      * Ensure zeroing happens before reading cpu->exit_request or
544      * cpu->interrupt_request (see also smp_wmb in cpu_exit())
545      */
546     qatomic_mb_set(&cpu_neg(cpu)->icount_decr.u16.high, 0);
547 
548     if (unlikely(qatomic_read(&cpu->interrupt_request))) {
549         int interrupt_request;
550         qemu_mutex_lock_iothread();
551         interrupt_request = cpu->interrupt_request;
552         if (unlikely(cpu->singlestep_enabled & SSTEP_NOIRQ)) {
553             /* Mask out external interrupts for this step. */
554             interrupt_request &= ~CPU_INTERRUPT_SSTEP_MASK;
555         }
556         if (interrupt_request & CPU_INTERRUPT_DEBUG) {
557             cpu->interrupt_request &= ~CPU_INTERRUPT_DEBUG;
558             cpu->exception_index = EXCP_DEBUG;
559             qemu_mutex_unlock_iothread();
560             return true;
561         }
562         if (replay_mode == REPLAY_MODE_PLAY && !replay_has_interrupt()) {
563             /* Do nothing */
564         } else if (interrupt_request & CPU_INTERRUPT_HALT) {
565             replay_interrupt();
566             cpu->interrupt_request &= ~CPU_INTERRUPT_HALT;
567             cpu->halted = 1;
568             cpu->exception_index = EXCP_HLT;
569             qemu_mutex_unlock_iothread();
570             return true;
571         }
572 #if defined(TARGET_I386)
573         else if (interrupt_request & CPU_INTERRUPT_INIT) {
574             X86CPU *x86_cpu = X86_CPU(cpu);
575             CPUArchState *env = &x86_cpu->env;
576             replay_interrupt();
577             cpu_svm_check_intercept_param(env, SVM_EXIT_INIT, 0, 0);
578             do_cpu_init(x86_cpu);
579             cpu->exception_index = EXCP_HALTED;
580             qemu_mutex_unlock_iothread();
581             return true;
582         }
583 #else
584         else if (interrupt_request & CPU_INTERRUPT_RESET) {
585             replay_interrupt();
586             cpu_reset(cpu);
587             qemu_mutex_unlock_iothread();
588             return true;
589         }
590 #endif
591         /* The target hook has 3 exit conditions:
592            False when the interrupt isn't processed,
593            True when it is, and we should restart on a new TB,
594            and via longjmp via cpu_loop_exit.  */
595         else {
596             if (cc->cpu_exec_interrupt(cpu, interrupt_request)) {
597                 replay_interrupt();
598                 /*
599                  * After processing the interrupt, ensure an EXCP_DEBUG is
600                  * raised when single-stepping so that GDB doesn't miss the
601                  * next instruction.
602                  */
603                 cpu->exception_index =
604                     (cpu->singlestep_enabled ? EXCP_DEBUG : -1);
605                 *last_tb = NULL;
606             }
607             /* The target hook may have updated the 'cpu->interrupt_request';
608              * reload the 'interrupt_request' value */
609             interrupt_request = cpu->interrupt_request;
610         }
611         if (interrupt_request & CPU_INTERRUPT_EXITTB) {
612             cpu->interrupt_request &= ~CPU_INTERRUPT_EXITTB;
613             /* ensure that no TB jump will be modified as
614                the program flow was changed */
615             *last_tb = NULL;
616         }
617 
618         /* If we exit via cpu_loop_exit/longjmp it is reset in cpu_exec */
619         qemu_mutex_unlock_iothread();
620     }
621 
622     /* Finally, check if we need to exit to the main loop.  */
623     if (unlikely(qatomic_read(&cpu->exit_request))
624         || (icount_enabled()
625             && cpu_neg(cpu)->icount_decr.u16.low + cpu->icount_extra == 0)) {
626         qatomic_set(&cpu->exit_request, 0);
627         if (cpu->exception_index == -1) {
628             cpu->exception_index = EXCP_INTERRUPT;
629         }
630         return true;
631     }
632 
633     return false;
634 }
635 
636 static inline void cpu_loop_exec_tb(CPUState *cpu, TranslationBlock *tb,
637                                     TranslationBlock **last_tb, int *tb_exit)
638 {
639     uintptr_t ret;
640     int32_t insns_left;
641 
642     trace_exec_tb(tb, tb->pc);
643     ret = cpu_tb_exec(cpu, tb);
644     tb = (TranslationBlock *)(ret & ~TB_EXIT_MASK);
645     *tb_exit = ret & TB_EXIT_MASK;
646     if (*tb_exit != TB_EXIT_REQUESTED) {
647         *last_tb = tb;
648         return;
649     }
650 
651     *last_tb = NULL;
652     insns_left = qatomic_read(&cpu_neg(cpu)->icount_decr.u32);
653     if (insns_left < 0) {
654         /* Something asked us to stop executing chained TBs; just
655          * continue round the main loop. Whatever requested the exit
656          * will also have set something else (eg exit_request or
657          * interrupt_request) which will be handled by
658          * cpu_handle_interrupt.  cpu_handle_interrupt will also
659          * clear cpu->icount_decr.u16.high.
660          */
661         return;
662     }
663 
664     /* Instruction counter expired.  */
665     assert(icount_enabled());
666 #ifndef CONFIG_USER_ONLY
667     /* Ensure global icount has gone forward */
668     cpu_update_icount(cpu);
669     /* Refill decrementer and continue execution.  */
670     insns_left = MIN(0xffff, cpu->icount_budget);
671     cpu_neg(cpu)->icount_decr.u16.low = insns_left;
672     cpu->icount_extra = cpu->icount_budget - insns_left;
673     if (!cpu->icount_extra) {
674         /* Execute any remaining instructions, then let the main loop
675          * handle the next event.
676          */
677         if (insns_left > 0) {
678             cpu_exec_nocache(cpu, insns_left, tb, false);
679         }
680     }
681 #endif
682 }
683 
684 /* main execution loop */
685 
686 int cpu_exec(CPUState *cpu)
687 {
688     CPUClass *cc = CPU_GET_CLASS(cpu);
689     int ret;
690     SyncClocks sc = { 0 };
691 
692     /* replay_interrupt may need current_cpu */
693     current_cpu = cpu;
694 
695     if (cpu_handle_halt(cpu)) {
696         return EXCP_HALTED;
697     }
698 
699     rcu_read_lock();
700 
701     cc->cpu_exec_enter(cpu);
702 
703     /* Calculate difference between guest clock and host clock.
704      * This delay includes the delay of the last cycle, so
705      * what we have to do is sleep until it is 0. As for the
706      * advance/delay we gain here, we try to fix it next time.
707      */
708     init_delay_params(&sc, cpu);
709 
710     /* prepare setjmp context for exception handling */
711     if (sigsetjmp(cpu->jmp_env, 0) != 0) {
712 #if defined(__clang__) || !QEMU_GNUC_PREREQ(4, 6)
713         /* Some compilers wrongly smash all local variables after
714          * siglongjmp. There were bug reports for gcc 4.5.0 and clang.
715          * Reload essential local variables here for those compilers.
716          * Newer versions of gcc would complain about this code (-Wclobbered). */
717         cpu = current_cpu;
718         cc = CPU_GET_CLASS(cpu);
719 #else /* buggy compiler */
720         /* Assert that the compiler does not smash local variables. */
721         g_assert(cpu == current_cpu);
722         g_assert(cc == CPU_GET_CLASS(cpu));
723 #endif /* buggy compiler */
724 #ifndef CONFIG_SOFTMMU
725         tcg_debug_assert(!have_mmap_lock());
726 #endif
727         if (qemu_mutex_iothread_locked()) {
728             qemu_mutex_unlock_iothread();
729         }
730         qemu_plugin_disable_mem_helpers(cpu);
731 
732         assert_no_pages_locked();
733     }
734 
735     /* if an exception is pending, we execute it here */
736     while (!cpu_handle_exception(cpu, &ret)) {
737         TranslationBlock *last_tb = NULL;
738         int tb_exit = 0;
739 
740         while (!cpu_handle_interrupt(cpu, &last_tb)) {
741             uint32_t cflags = cpu->cflags_next_tb;
742             TranslationBlock *tb;
743 
744             /* When requested, use an exact setting for cflags for the next
745                execution.  This is used for icount, precise smc, and stop-
746                after-access watchpoints.  Since this request should never
747                have CF_INVALID set, -1 is a convenient invalid value that
748                does not require tcg headers for cpu_common_reset.  */
749             if (cflags == -1) {
750                 cflags = curr_cflags();
751             } else {
752                 cpu->cflags_next_tb = -1;
753             }
754 
755             tb = tb_find(cpu, last_tb, tb_exit, cflags);
756             cpu_loop_exec_tb(cpu, tb, &last_tb, &tb_exit);
757             /* Try to align the host and virtual clocks
758                if the guest is in advance */
759             align_clocks(&sc, cpu);
760         }
761     }
762 
763     cc->cpu_exec_exit(cpu);
764     rcu_read_unlock();
765 
766     return ret;
767 }
768 
769 #ifndef CONFIG_USER_ONLY
770 
771 void dump_drift_info(void)
772 {
773     if (!icount_enabled()) {
774         return;
775     }
776 
777     qemu_printf("Host - Guest clock  %"PRIi64" ms\n",
778                 (cpu_get_clock() - cpu_get_icount()) / SCALE_MS);
779     if (icount_align_option) {
780         qemu_printf("Max guest delay     %"PRIi64" ms\n",
781                     -max_delay / SCALE_MS);
782         qemu_printf("Max guest advance   %"PRIi64" ms\n",
783                     max_advance / SCALE_MS);
784     } else {
785         qemu_printf("Max guest delay     NA\n");
786         qemu_printf("Max guest advance   NA\n");
787     }
788 }
789 
790 #endif /* !CONFIG_USER_ONLY */
791