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