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