xref: /openbmc/qemu/accel/tcg/translate-all.c (revision 95ab7c22)
1 /*
2  *  Host code generation
3  *
4  *  Copyright (c) 2003 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/units.h"
22 #include "qemu-common.h"
23 
24 #define NO_CPU_IO_DEFS
25 #include "cpu.h"
26 #include "trace.h"
27 #include "disas/disas.h"
28 #include "exec/exec-all.h"
29 #include "tcg/tcg.h"
30 #if defined(CONFIG_USER_ONLY)
31 #include "qemu.h"
32 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
33 #include <sys/param.h>
34 #if __FreeBSD_version >= 700104
35 #define HAVE_KINFO_GETVMMAP
36 #define sigqueue sigqueue_freebsd  /* avoid redefinition */
37 #include <sys/proc.h>
38 #include <machine/profile.h>
39 #define _KERNEL
40 #include <sys/user.h>
41 #undef _KERNEL
42 #undef sigqueue
43 #include <libutil.h>
44 #endif
45 #endif
46 #else
47 #include "exec/ram_addr.h"
48 #endif
49 
50 #include "exec/cputlb.h"
51 #include "exec/tb-hash.h"
52 #include "exec/translate-all.h"
53 #include "qemu/bitmap.h"
54 #include "qemu/error-report.h"
55 #include "qemu/qemu-print.h"
56 #include "qemu/timer.h"
57 #include "qemu/main-loop.h"
58 #include "exec/log.h"
59 #include "sysemu/cpus.h"
60 #include "sysemu/cpu-timers.h"
61 #include "sysemu/tcg.h"
62 #include "qapi/error.h"
63 #include "hw/core/tcg-cpu-ops.h"
64 #include "internal.h"
65 
66 /* #define DEBUG_TB_INVALIDATE */
67 /* #define DEBUG_TB_FLUSH */
68 /* make various TB consistency checks */
69 /* #define DEBUG_TB_CHECK */
70 
71 #ifdef DEBUG_TB_INVALIDATE
72 #define DEBUG_TB_INVALIDATE_GATE 1
73 #else
74 #define DEBUG_TB_INVALIDATE_GATE 0
75 #endif
76 
77 #ifdef DEBUG_TB_FLUSH
78 #define DEBUG_TB_FLUSH_GATE 1
79 #else
80 #define DEBUG_TB_FLUSH_GATE 0
81 #endif
82 
83 #if !defined(CONFIG_USER_ONLY)
84 /* TB consistency checks only implemented for usermode emulation.  */
85 #undef DEBUG_TB_CHECK
86 #endif
87 
88 #ifdef DEBUG_TB_CHECK
89 #define DEBUG_TB_CHECK_GATE 1
90 #else
91 #define DEBUG_TB_CHECK_GATE 0
92 #endif
93 
94 /* Access to the various translations structures need to be serialised via locks
95  * for consistency.
96  * In user-mode emulation access to the memory related structures are protected
97  * with mmap_lock.
98  * In !user-mode we use per-page locks.
99  */
100 #ifdef CONFIG_SOFTMMU
101 #define assert_memory_lock()
102 #else
103 #define assert_memory_lock() tcg_debug_assert(have_mmap_lock())
104 #endif
105 
106 #define SMC_BITMAP_USE_THRESHOLD 10
107 
108 typedef struct PageDesc {
109     /* list of TBs intersecting this ram page */
110     uintptr_t first_tb;
111 #ifdef CONFIG_SOFTMMU
112     /* in order to optimize self modifying code, we count the number
113        of lookups we do to a given page to use a bitmap */
114     unsigned long *code_bitmap;
115     unsigned int code_write_count;
116 #else
117     unsigned long flags;
118     void *target_data;
119 #endif
120 #ifndef CONFIG_USER_ONLY
121     QemuSpin lock;
122 #endif
123 } PageDesc;
124 
125 /**
126  * struct page_entry - page descriptor entry
127  * @pd:     pointer to the &struct PageDesc of the page this entry represents
128  * @index:  page index of the page
129  * @locked: whether the page is locked
130  *
131  * This struct helps us keep track of the locked state of a page, without
132  * bloating &struct PageDesc.
133  *
134  * A page lock protects accesses to all fields of &struct PageDesc.
135  *
136  * See also: &struct page_collection.
137  */
138 struct page_entry {
139     PageDesc *pd;
140     tb_page_addr_t index;
141     bool locked;
142 };
143 
144 /**
145  * struct page_collection - tracks a set of pages (i.e. &struct page_entry's)
146  * @tree:   Binary search tree (BST) of the pages, with key == page index
147  * @max:    Pointer to the page in @tree with the highest page index
148  *
149  * To avoid deadlock we lock pages in ascending order of page index.
150  * When operating on a set of pages, we need to keep track of them so that
151  * we can lock them in order and also unlock them later. For this we collect
152  * pages (i.e. &struct page_entry's) in a binary search @tree. Given that the
153  * @tree implementation we use does not provide an O(1) operation to obtain the
154  * highest-ranked element, we use @max to keep track of the inserted page
155  * with the highest index. This is valuable because if a page is not in
156  * the tree and its index is higher than @max's, then we can lock it
157  * without breaking the locking order rule.
158  *
159  * Note on naming: 'struct page_set' would be shorter, but we already have a few
160  * page_set_*() helpers, so page_collection is used instead to avoid confusion.
161  *
162  * See also: page_collection_lock().
163  */
164 struct page_collection {
165     GTree *tree;
166     struct page_entry *max;
167 };
168 
169 /* list iterators for lists of tagged pointers in TranslationBlock */
170 #define TB_FOR_EACH_TAGGED(head, tb, n, field)                          \
171     for (n = (head) & 1, tb = (TranslationBlock *)((head) & ~1);        \
172          tb; tb = (TranslationBlock *)tb->field[n], n = (uintptr_t)tb & 1, \
173              tb = (TranslationBlock *)((uintptr_t)tb & ~1))
174 
175 #define PAGE_FOR_EACH_TB(pagedesc, tb, n)                       \
176     TB_FOR_EACH_TAGGED((pagedesc)->first_tb, tb, n, page_next)
177 
178 #define TB_FOR_EACH_JMP(head_tb, tb, n)                                 \
179     TB_FOR_EACH_TAGGED((head_tb)->jmp_list_head, tb, n, jmp_list_next)
180 
181 /*
182  * In system mode we want L1_MAP to be based on ram offsets,
183  * while in user mode we want it to be based on virtual addresses.
184  *
185  * TODO: For user mode, see the caveat re host vs guest virtual
186  * address spaces near GUEST_ADDR_MAX.
187  */
188 #if !defined(CONFIG_USER_ONLY)
189 #if HOST_LONG_BITS < TARGET_PHYS_ADDR_SPACE_BITS
190 # define L1_MAP_ADDR_SPACE_BITS  HOST_LONG_BITS
191 #else
192 # define L1_MAP_ADDR_SPACE_BITS  TARGET_PHYS_ADDR_SPACE_BITS
193 #endif
194 #else
195 # define L1_MAP_ADDR_SPACE_BITS  MIN(HOST_LONG_BITS, TARGET_ABI_BITS)
196 #endif
197 
198 /* Size of the L2 (and L3, etc) page tables.  */
199 #define V_L2_BITS 10
200 #define V_L2_SIZE (1 << V_L2_BITS)
201 
202 /* Make sure all possible CPU event bits fit in tb->trace_vcpu_dstate */
203 QEMU_BUILD_BUG_ON(CPU_TRACE_DSTATE_MAX_EVENTS >
204                   sizeof_field(TranslationBlock, trace_vcpu_dstate)
205                   * BITS_PER_BYTE);
206 
207 /*
208  * L1 Mapping properties
209  */
210 static int v_l1_size;
211 static int v_l1_shift;
212 static int v_l2_levels;
213 
214 /* The bottom level has pointers to PageDesc, and is indexed by
215  * anything from 4 to (V_L2_BITS + 3) bits, depending on target page size.
216  */
217 #define V_L1_MIN_BITS 4
218 #define V_L1_MAX_BITS (V_L2_BITS + 3)
219 #define V_L1_MAX_SIZE (1 << V_L1_MAX_BITS)
220 
221 static void *l1_map[V_L1_MAX_SIZE];
222 
223 /* code generation context */
224 TCGContext tcg_init_ctx;
225 __thread TCGContext *tcg_ctx;
226 TBContext tb_ctx;
227 bool parallel_cpus;
228 
229 static void page_table_config_init(void)
230 {
231     uint32_t v_l1_bits;
232 
233     assert(TARGET_PAGE_BITS);
234     /* The bits remaining after N lower levels of page tables.  */
235     v_l1_bits = (L1_MAP_ADDR_SPACE_BITS - TARGET_PAGE_BITS) % V_L2_BITS;
236     if (v_l1_bits < V_L1_MIN_BITS) {
237         v_l1_bits += V_L2_BITS;
238     }
239 
240     v_l1_size = 1 << v_l1_bits;
241     v_l1_shift = L1_MAP_ADDR_SPACE_BITS - TARGET_PAGE_BITS - v_l1_bits;
242     v_l2_levels = v_l1_shift / V_L2_BITS - 1;
243 
244     assert(v_l1_bits <= V_L1_MAX_BITS);
245     assert(v_l1_shift % V_L2_BITS == 0);
246     assert(v_l2_levels >= 0);
247 }
248 
249 static void cpu_gen_init(void)
250 {
251     tcg_context_init(&tcg_init_ctx);
252 }
253 
254 /* Encode VAL as a signed leb128 sequence at P.
255    Return P incremented past the encoded value.  */
256 static uint8_t *encode_sleb128(uint8_t *p, target_long val)
257 {
258     int more, byte;
259 
260     do {
261         byte = val & 0x7f;
262         val >>= 7;
263         more = !((val == 0 && (byte & 0x40) == 0)
264                  || (val == -1 && (byte & 0x40) != 0));
265         if (more) {
266             byte |= 0x80;
267         }
268         *p++ = byte;
269     } while (more);
270 
271     return p;
272 }
273 
274 /* Decode a signed leb128 sequence at *PP; increment *PP past the
275    decoded value.  Return the decoded value.  */
276 static target_long decode_sleb128(const uint8_t **pp)
277 {
278     const uint8_t *p = *pp;
279     target_long val = 0;
280     int byte, shift = 0;
281 
282     do {
283         byte = *p++;
284         val |= (target_ulong)(byte & 0x7f) << shift;
285         shift += 7;
286     } while (byte & 0x80);
287     if (shift < TARGET_LONG_BITS && (byte & 0x40)) {
288         val |= -(target_ulong)1 << shift;
289     }
290 
291     *pp = p;
292     return val;
293 }
294 
295 /* Encode the data collected about the instructions while compiling TB.
296    Place the data at BLOCK, and return the number of bytes consumed.
297 
298    The logical table consists of TARGET_INSN_START_WORDS target_ulong's,
299    which come from the target's insn_start data, followed by a uintptr_t
300    which comes from the host pc of the end of the code implementing the insn.
301 
302    Each line of the table is encoded as sleb128 deltas from the previous
303    line.  The seed for the first line is { tb->pc, 0..., tb->tc.ptr }.
304    That is, the first column is seeded with the guest pc, the last column
305    with the host pc, and the middle columns with zeros.  */
306 
307 static int encode_search(TranslationBlock *tb, uint8_t *block)
308 {
309     uint8_t *highwater = tcg_ctx->code_gen_highwater;
310     uint8_t *p = block;
311     int i, j, n;
312 
313     for (i = 0, n = tb->icount; i < n; ++i) {
314         target_ulong prev;
315 
316         for (j = 0; j < TARGET_INSN_START_WORDS; ++j) {
317             if (i == 0) {
318                 prev = (j == 0 ? tb->pc : 0);
319             } else {
320                 prev = tcg_ctx->gen_insn_data[i - 1][j];
321             }
322             p = encode_sleb128(p, tcg_ctx->gen_insn_data[i][j] - prev);
323         }
324         prev = (i == 0 ? 0 : tcg_ctx->gen_insn_end_off[i - 1]);
325         p = encode_sleb128(p, tcg_ctx->gen_insn_end_off[i] - prev);
326 
327         /* Test for (pending) buffer overflow.  The assumption is that any
328            one row beginning below the high water mark cannot overrun
329            the buffer completely.  Thus we can test for overflow after
330            encoding a row without having to check during encoding.  */
331         if (unlikely(p > highwater)) {
332             return -1;
333         }
334     }
335 
336     return p - block;
337 }
338 
339 /* The cpu state corresponding to 'searched_pc' is restored.
340  * When reset_icount is true, current TB will be interrupted and
341  * icount should be recalculated.
342  */
343 static int cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,
344                                      uintptr_t searched_pc, bool reset_icount)
345 {
346     target_ulong data[TARGET_INSN_START_WORDS] = { tb->pc };
347     uintptr_t host_pc = (uintptr_t)tb->tc.ptr;
348     CPUArchState *env = cpu->env_ptr;
349     const uint8_t *p = tb->tc.ptr + tb->tc.size;
350     int i, j, num_insns = tb->icount;
351 #ifdef CONFIG_PROFILER
352     TCGProfile *prof = &tcg_ctx->prof;
353     int64_t ti = profile_getclock();
354 #endif
355 
356     searched_pc -= GETPC_ADJ;
357 
358     if (searched_pc < host_pc) {
359         return -1;
360     }
361 
362     /* Reconstruct the stored insn data while looking for the point at
363        which the end of the insn exceeds the searched_pc.  */
364     for (i = 0; i < num_insns; ++i) {
365         for (j = 0; j < TARGET_INSN_START_WORDS; ++j) {
366             data[j] += decode_sleb128(&p);
367         }
368         host_pc += decode_sleb128(&p);
369         if (host_pc > searched_pc) {
370             goto found;
371         }
372     }
373     return -1;
374 
375  found:
376     if (reset_icount && (tb_cflags(tb) & CF_USE_ICOUNT)) {
377         assert(icount_enabled());
378         /* Reset the cycle counter to the start of the block
379            and shift if to the number of actually executed instructions */
380         cpu_neg(cpu)->icount_decr.u16.low += num_insns - i;
381     }
382     restore_state_to_opc(env, tb, data);
383 
384 #ifdef CONFIG_PROFILER
385     qatomic_set(&prof->restore_time,
386                 prof->restore_time + profile_getclock() - ti);
387     qatomic_set(&prof->restore_count, prof->restore_count + 1);
388 #endif
389     return 0;
390 }
391 
392 void tb_destroy(TranslationBlock *tb)
393 {
394     qemu_spin_destroy(&tb->jmp_lock);
395 }
396 
397 bool cpu_restore_state(CPUState *cpu, uintptr_t host_pc, bool will_exit)
398 {
399     /*
400      * The host_pc has to be in the rx region of the code buffer.
401      * If it is not we will not be able to resolve it here.
402      * The two cases where host_pc will not be correct are:
403      *
404      *  - fault during translation (instruction fetch)
405      *  - fault from helper (not using GETPC() macro)
406      *
407      * Either way we need return early as we can't resolve it here.
408      */
409     if (in_code_gen_buffer((const void *)(host_pc - tcg_splitwx_diff))) {
410         TranslationBlock *tb = tcg_tb_lookup(host_pc);
411         if (tb) {
412             cpu_restore_state_from_tb(cpu, tb, host_pc, will_exit);
413             if (tb_cflags(tb) & CF_NOCACHE) {
414                 /* one-shot translation, invalidate it immediately */
415                 tb_phys_invalidate(tb, -1);
416                 tcg_tb_remove(tb);
417                 tb_destroy(tb);
418             }
419             return true;
420         }
421     }
422     return false;
423 }
424 
425 static void page_init(void)
426 {
427     page_size_init();
428     page_table_config_init();
429 
430 #if defined(CONFIG_BSD) && defined(CONFIG_USER_ONLY)
431     {
432 #ifdef HAVE_KINFO_GETVMMAP
433         struct kinfo_vmentry *freep;
434         int i, cnt;
435 
436         freep = kinfo_getvmmap(getpid(), &cnt);
437         if (freep) {
438             mmap_lock();
439             for (i = 0; i < cnt; i++) {
440                 unsigned long startaddr, endaddr;
441 
442                 startaddr = freep[i].kve_start;
443                 endaddr = freep[i].kve_end;
444                 if (h2g_valid(startaddr)) {
445                     startaddr = h2g(startaddr) & TARGET_PAGE_MASK;
446 
447                     if (h2g_valid(endaddr)) {
448                         endaddr = h2g(endaddr);
449                         page_set_flags(startaddr, endaddr, PAGE_RESERVED);
450                     } else {
451 #if TARGET_ABI_BITS <= L1_MAP_ADDR_SPACE_BITS
452                         endaddr = ~0ul;
453                         page_set_flags(startaddr, endaddr, PAGE_RESERVED);
454 #endif
455                     }
456                 }
457             }
458             free(freep);
459             mmap_unlock();
460         }
461 #else
462         FILE *f;
463 
464         last_brk = (unsigned long)sbrk(0);
465 
466         f = fopen("/compat/linux/proc/self/maps", "r");
467         if (f) {
468             mmap_lock();
469 
470             do {
471                 unsigned long startaddr, endaddr;
472                 int n;
473 
474                 n = fscanf(f, "%lx-%lx %*[^\n]\n", &startaddr, &endaddr);
475 
476                 if (n == 2 && h2g_valid(startaddr)) {
477                     startaddr = h2g(startaddr) & TARGET_PAGE_MASK;
478 
479                     if (h2g_valid(endaddr)) {
480                         endaddr = h2g(endaddr);
481                     } else {
482                         endaddr = ~0ul;
483                     }
484                     page_set_flags(startaddr, endaddr, PAGE_RESERVED);
485                 }
486             } while (!feof(f));
487 
488             fclose(f);
489             mmap_unlock();
490         }
491 #endif
492     }
493 #endif
494 }
495 
496 static PageDesc *page_find_alloc(tb_page_addr_t index, int alloc)
497 {
498     PageDesc *pd;
499     void **lp;
500     int i;
501 
502     /* Level 1.  Always allocated.  */
503     lp = l1_map + ((index >> v_l1_shift) & (v_l1_size - 1));
504 
505     /* Level 2..N-1.  */
506     for (i = v_l2_levels; i > 0; i--) {
507         void **p = qatomic_rcu_read(lp);
508 
509         if (p == NULL) {
510             void *existing;
511 
512             if (!alloc) {
513                 return NULL;
514             }
515             p = g_new0(void *, V_L2_SIZE);
516             existing = qatomic_cmpxchg(lp, NULL, p);
517             if (unlikely(existing)) {
518                 g_free(p);
519                 p = existing;
520             }
521         }
522 
523         lp = p + ((index >> (i * V_L2_BITS)) & (V_L2_SIZE - 1));
524     }
525 
526     pd = qatomic_rcu_read(lp);
527     if (pd == NULL) {
528         void *existing;
529 
530         if (!alloc) {
531             return NULL;
532         }
533         pd = g_new0(PageDesc, V_L2_SIZE);
534 #ifndef CONFIG_USER_ONLY
535         {
536             int i;
537 
538             for (i = 0; i < V_L2_SIZE; i++) {
539                 qemu_spin_init(&pd[i].lock);
540             }
541         }
542 #endif
543         existing = qatomic_cmpxchg(lp, NULL, pd);
544         if (unlikely(existing)) {
545 #ifndef CONFIG_USER_ONLY
546             {
547                 int i;
548 
549                 for (i = 0; i < V_L2_SIZE; i++) {
550                     qemu_spin_destroy(&pd[i].lock);
551                 }
552             }
553 #endif
554             g_free(pd);
555             pd = existing;
556         }
557     }
558 
559     return pd + (index & (V_L2_SIZE - 1));
560 }
561 
562 static inline PageDesc *page_find(tb_page_addr_t index)
563 {
564     return page_find_alloc(index, 0);
565 }
566 
567 static void page_lock_pair(PageDesc **ret_p1, tb_page_addr_t phys1,
568                            PageDesc **ret_p2, tb_page_addr_t phys2, int alloc);
569 
570 /* In user-mode page locks aren't used; mmap_lock is enough */
571 #ifdef CONFIG_USER_ONLY
572 
573 #define assert_page_locked(pd) tcg_debug_assert(have_mmap_lock())
574 
575 static inline void page_lock(PageDesc *pd)
576 { }
577 
578 static inline void page_unlock(PageDesc *pd)
579 { }
580 
581 static inline void page_lock_tb(const TranslationBlock *tb)
582 { }
583 
584 static inline void page_unlock_tb(const TranslationBlock *tb)
585 { }
586 
587 struct page_collection *
588 page_collection_lock(tb_page_addr_t start, tb_page_addr_t end)
589 {
590     return NULL;
591 }
592 
593 void page_collection_unlock(struct page_collection *set)
594 { }
595 #else /* !CONFIG_USER_ONLY */
596 
597 #ifdef CONFIG_DEBUG_TCG
598 
599 static __thread GHashTable *ht_pages_locked_debug;
600 
601 static void ht_pages_locked_debug_init(void)
602 {
603     if (ht_pages_locked_debug) {
604         return;
605     }
606     ht_pages_locked_debug = g_hash_table_new(NULL, NULL);
607 }
608 
609 static bool page_is_locked(const PageDesc *pd)
610 {
611     PageDesc *found;
612 
613     ht_pages_locked_debug_init();
614     found = g_hash_table_lookup(ht_pages_locked_debug, pd);
615     return !!found;
616 }
617 
618 static void page_lock__debug(PageDesc *pd)
619 {
620     ht_pages_locked_debug_init();
621     g_assert(!page_is_locked(pd));
622     g_hash_table_insert(ht_pages_locked_debug, pd, pd);
623 }
624 
625 static void page_unlock__debug(const PageDesc *pd)
626 {
627     bool removed;
628 
629     ht_pages_locked_debug_init();
630     g_assert(page_is_locked(pd));
631     removed = g_hash_table_remove(ht_pages_locked_debug, pd);
632     g_assert(removed);
633 }
634 
635 static void
636 do_assert_page_locked(const PageDesc *pd, const char *file, int line)
637 {
638     if (unlikely(!page_is_locked(pd))) {
639         error_report("assert_page_lock: PageDesc %p not locked @ %s:%d",
640                      pd, file, line);
641         abort();
642     }
643 }
644 
645 #define assert_page_locked(pd) do_assert_page_locked(pd, __FILE__, __LINE__)
646 
647 void assert_no_pages_locked(void)
648 {
649     ht_pages_locked_debug_init();
650     g_assert(g_hash_table_size(ht_pages_locked_debug) == 0);
651 }
652 
653 #else /* !CONFIG_DEBUG_TCG */
654 
655 #define assert_page_locked(pd)
656 
657 static inline void page_lock__debug(const PageDesc *pd)
658 {
659 }
660 
661 static inline void page_unlock__debug(const PageDesc *pd)
662 {
663 }
664 
665 #endif /* CONFIG_DEBUG_TCG */
666 
667 static inline void page_lock(PageDesc *pd)
668 {
669     page_lock__debug(pd);
670     qemu_spin_lock(&pd->lock);
671 }
672 
673 static inline void page_unlock(PageDesc *pd)
674 {
675     qemu_spin_unlock(&pd->lock);
676     page_unlock__debug(pd);
677 }
678 
679 /* lock the page(s) of a TB in the correct acquisition order */
680 static inline void page_lock_tb(const TranslationBlock *tb)
681 {
682     page_lock_pair(NULL, tb->page_addr[0], NULL, tb->page_addr[1], 0);
683 }
684 
685 static inline void page_unlock_tb(const TranslationBlock *tb)
686 {
687     PageDesc *p1 = page_find(tb->page_addr[0] >> TARGET_PAGE_BITS);
688 
689     page_unlock(p1);
690     if (unlikely(tb->page_addr[1] != -1)) {
691         PageDesc *p2 = page_find(tb->page_addr[1] >> TARGET_PAGE_BITS);
692 
693         if (p2 != p1) {
694             page_unlock(p2);
695         }
696     }
697 }
698 
699 static inline struct page_entry *
700 page_entry_new(PageDesc *pd, tb_page_addr_t index)
701 {
702     struct page_entry *pe = g_malloc(sizeof(*pe));
703 
704     pe->index = index;
705     pe->pd = pd;
706     pe->locked = false;
707     return pe;
708 }
709 
710 static void page_entry_destroy(gpointer p)
711 {
712     struct page_entry *pe = p;
713 
714     g_assert(pe->locked);
715     page_unlock(pe->pd);
716     g_free(pe);
717 }
718 
719 /* returns false on success */
720 static bool page_entry_trylock(struct page_entry *pe)
721 {
722     bool busy;
723 
724     busy = qemu_spin_trylock(&pe->pd->lock);
725     if (!busy) {
726         g_assert(!pe->locked);
727         pe->locked = true;
728         page_lock__debug(pe->pd);
729     }
730     return busy;
731 }
732 
733 static void do_page_entry_lock(struct page_entry *pe)
734 {
735     page_lock(pe->pd);
736     g_assert(!pe->locked);
737     pe->locked = true;
738 }
739 
740 static gboolean page_entry_lock(gpointer key, gpointer value, gpointer data)
741 {
742     struct page_entry *pe = value;
743 
744     do_page_entry_lock(pe);
745     return FALSE;
746 }
747 
748 static gboolean page_entry_unlock(gpointer key, gpointer value, gpointer data)
749 {
750     struct page_entry *pe = value;
751 
752     if (pe->locked) {
753         pe->locked = false;
754         page_unlock(pe->pd);
755     }
756     return FALSE;
757 }
758 
759 /*
760  * Trylock a page, and if successful, add the page to a collection.
761  * Returns true ("busy") if the page could not be locked; false otherwise.
762  */
763 static bool page_trylock_add(struct page_collection *set, tb_page_addr_t addr)
764 {
765     tb_page_addr_t index = addr >> TARGET_PAGE_BITS;
766     struct page_entry *pe;
767     PageDesc *pd;
768 
769     pe = g_tree_lookup(set->tree, &index);
770     if (pe) {
771         return false;
772     }
773 
774     pd = page_find(index);
775     if (pd == NULL) {
776         return false;
777     }
778 
779     pe = page_entry_new(pd, index);
780     g_tree_insert(set->tree, &pe->index, pe);
781 
782     /*
783      * If this is either (1) the first insertion or (2) a page whose index
784      * is higher than any other so far, just lock the page and move on.
785      */
786     if (set->max == NULL || pe->index > set->max->index) {
787         set->max = pe;
788         do_page_entry_lock(pe);
789         return false;
790     }
791     /*
792      * Try to acquire out-of-order lock; if busy, return busy so that we acquire
793      * locks in order.
794      */
795     return page_entry_trylock(pe);
796 }
797 
798 static gint tb_page_addr_cmp(gconstpointer ap, gconstpointer bp, gpointer udata)
799 {
800     tb_page_addr_t a = *(const tb_page_addr_t *)ap;
801     tb_page_addr_t b = *(const tb_page_addr_t *)bp;
802 
803     if (a == b) {
804         return 0;
805     } else if (a < b) {
806         return -1;
807     }
808     return 1;
809 }
810 
811 /*
812  * Lock a range of pages ([@start,@end[) as well as the pages of all
813  * intersecting TBs.
814  * Locking order: acquire locks in ascending order of page index.
815  */
816 struct page_collection *
817 page_collection_lock(tb_page_addr_t start, tb_page_addr_t end)
818 {
819     struct page_collection *set = g_malloc(sizeof(*set));
820     tb_page_addr_t index;
821     PageDesc *pd;
822 
823     start >>= TARGET_PAGE_BITS;
824     end   >>= TARGET_PAGE_BITS;
825     g_assert(start <= end);
826 
827     set->tree = g_tree_new_full(tb_page_addr_cmp, NULL, NULL,
828                                 page_entry_destroy);
829     set->max = NULL;
830     assert_no_pages_locked();
831 
832  retry:
833     g_tree_foreach(set->tree, page_entry_lock, NULL);
834 
835     for (index = start; index <= end; index++) {
836         TranslationBlock *tb;
837         int n;
838 
839         pd = page_find(index);
840         if (pd == NULL) {
841             continue;
842         }
843         if (page_trylock_add(set, index << TARGET_PAGE_BITS)) {
844             g_tree_foreach(set->tree, page_entry_unlock, NULL);
845             goto retry;
846         }
847         assert_page_locked(pd);
848         PAGE_FOR_EACH_TB(pd, tb, n) {
849             if (page_trylock_add(set, tb->page_addr[0]) ||
850                 (tb->page_addr[1] != -1 &&
851                  page_trylock_add(set, tb->page_addr[1]))) {
852                 /* drop all locks, and reacquire in order */
853                 g_tree_foreach(set->tree, page_entry_unlock, NULL);
854                 goto retry;
855             }
856         }
857     }
858     return set;
859 }
860 
861 void page_collection_unlock(struct page_collection *set)
862 {
863     /* entries are unlocked and freed via page_entry_destroy */
864     g_tree_destroy(set->tree);
865     g_free(set);
866 }
867 
868 #endif /* !CONFIG_USER_ONLY */
869 
870 static void page_lock_pair(PageDesc **ret_p1, tb_page_addr_t phys1,
871                            PageDesc **ret_p2, tb_page_addr_t phys2, int alloc)
872 {
873     PageDesc *p1, *p2;
874     tb_page_addr_t page1;
875     tb_page_addr_t page2;
876 
877     assert_memory_lock();
878     g_assert(phys1 != -1);
879 
880     page1 = phys1 >> TARGET_PAGE_BITS;
881     page2 = phys2 >> TARGET_PAGE_BITS;
882 
883     p1 = page_find_alloc(page1, alloc);
884     if (ret_p1) {
885         *ret_p1 = p1;
886     }
887     if (likely(phys2 == -1)) {
888         page_lock(p1);
889         return;
890     } else if (page1 == page2) {
891         page_lock(p1);
892         if (ret_p2) {
893             *ret_p2 = p1;
894         }
895         return;
896     }
897     p2 = page_find_alloc(page2, alloc);
898     if (ret_p2) {
899         *ret_p2 = p2;
900     }
901     if (page1 < page2) {
902         page_lock(p1);
903         page_lock(p2);
904     } else {
905         page_lock(p2);
906         page_lock(p1);
907     }
908 }
909 
910 /* Minimum size of the code gen buffer.  This number is randomly chosen,
911    but not so small that we can't have a fair number of TB's live.  */
912 #define MIN_CODE_GEN_BUFFER_SIZE     (1 * MiB)
913 
914 /* Maximum size of the code gen buffer we'd like to use.  Unless otherwise
915    indicated, this is constrained by the range of direct branches on the
916    host cpu, as used by the TCG implementation of goto_tb.  */
917 #if defined(__x86_64__)
918 # define MAX_CODE_GEN_BUFFER_SIZE  (2 * GiB)
919 #elif defined(__sparc__)
920 # define MAX_CODE_GEN_BUFFER_SIZE  (2 * GiB)
921 #elif defined(__powerpc64__)
922 # define MAX_CODE_GEN_BUFFER_SIZE  (2 * GiB)
923 #elif defined(__powerpc__)
924 # define MAX_CODE_GEN_BUFFER_SIZE  (32 * MiB)
925 #elif defined(__aarch64__)
926 # define MAX_CODE_GEN_BUFFER_SIZE  (2 * GiB)
927 #elif defined(__s390x__)
928   /* We have a +- 4GB range on the branches; leave some slop.  */
929 # define MAX_CODE_GEN_BUFFER_SIZE  (3 * GiB)
930 #elif defined(__mips__)
931   /* We have a 256MB branch region, but leave room to make sure the
932      main executable is also within that region.  */
933 # define MAX_CODE_GEN_BUFFER_SIZE  (128 * MiB)
934 #else
935 # define MAX_CODE_GEN_BUFFER_SIZE  ((size_t)-1)
936 #endif
937 
938 #if TCG_TARGET_REG_BITS == 32
939 #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (32 * MiB)
940 #ifdef CONFIG_USER_ONLY
941 /*
942  * For user mode on smaller 32 bit systems we may run into trouble
943  * allocating big chunks of data in the right place. On these systems
944  * we utilise a static code generation buffer directly in the binary.
945  */
946 #define USE_STATIC_CODE_GEN_BUFFER
947 #endif
948 #else /* TCG_TARGET_REG_BITS == 64 */
949 #ifdef CONFIG_USER_ONLY
950 /*
951  * As user-mode emulation typically means running multiple instances
952  * of the translator don't go too nuts with our default code gen
953  * buffer lest we make things too hard for the OS.
954  */
955 #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (128 * MiB)
956 #else
957 /*
958  * We expect most system emulation to run one or two guests per host.
959  * Users running large scale system emulation may want to tweak their
960  * runtime setup via the tb-size control on the command line.
961  */
962 #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (1 * GiB)
963 #endif
964 #endif
965 
966 #define DEFAULT_CODE_GEN_BUFFER_SIZE \
967   (DEFAULT_CODE_GEN_BUFFER_SIZE_1 < MAX_CODE_GEN_BUFFER_SIZE \
968    ? DEFAULT_CODE_GEN_BUFFER_SIZE_1 : MAX_CODE_GEN_BUFFER_SIZE)
969 
970 static size_t size_code_gen_buffer(size_t tb_size)
971 {
972     /* Size the buffer.  */
973     if (tb_size == 0) {
974         size_t phys_mem = qemu_get_host_physmem();
975         if (phys_mem == 0) {
976             tb_size = DEFAULT_CODE_GEN_BUFFER_SIZE;
977         } else {
978             tb_size = MIN(DEFAULT_CODE_GEN_BUFFER_SIZE, phys_mem / 8);
979         }
980     }
981     if (tb_size < MIN_CODE_GEN_BUFFER_SIZE) {
982         tb_size = MIN_CODE_GEN_BUFFER_SIZE;
983     }
984     if (tb_size > MAX_CODE_GEN_BUFFER_SIZE) {
985         tb_size = MAX_CODE_GEN_BUFFER_SIZE;
986     }
987     return tb_size;
988 }
989 
990 #ifdef __mips__
991 /* In order to use J and JAL within the code_gen_buffer, we require
992    that the buffer not cross a 256MB boundary.  */
993 static inline bool cross_256mb(void *addr, size_t size)
994 {
995     return ((uintptr_t)addr ^ ((uintptr_t)addr + size)) & ~0x0ffffffful;
996 }
997 
998 /* We weren't able to allocate a buffer without crossing that boundary,
999    so make do with the larger portion of the buffer that doesn't cross.
1000    Returns the new base of the buffer, and adjusts code_gen_buffer_size.  */
1001 static inline void *split_cross_256mb(void *buf1, size_t size1)
1002 {
1003     void *buf2 = (void *)(((uintptr_t)buf1 + size1) & ~0x0ffffffful);
1004     size_t size2 = buf1 + size1 - buf2;
1005 
1006     size1 = buf2 - buf1;
1007     if (size1 < size2) {
1008         size1 = size2;
1009         buf1 = buf2;
1010     }
1011 
1012     tcg_ctx->code_gen_buffer_size = size1;
1013     return buf1;
1014 }
1015 #endif
1016 
1017 #ifdef USE_STATIC_CODE_GEN_BUFFER
1018 static uint8_t static_code_gen_buffer[DEFAULT_CODE_GEN_BUFFER_SIZE]
1019     __attribute__((aligned(CODE_GEN_ALIGN)));
1020 
1021 static bool alloc_code_gen_buffer(size_t tb_size, int splitwx, Error **errp)
1022 {
1023     void *buf, *end;
1024     size_t size;
1025 
1026     if (splitwx > 0) {
1027         error_setg(errp, "jit split-wx not supported");
1028         return false;
1029     }
1030 
1031     /* page-align the beginning and end of the buffer */
1032     buf = static_code_gen_buffer;
1033     end = static_code_gen_buffer + sizeof(static_code_gen_buffer);
1034     buf = QEMU_ALIGN_PTR_UP(buf, qemu_real_host_page_size);
1035     end = QEMU_ALIGN_PTR_DOWN(end, qemu_real_host_page_size);
1036 
1037     size = end - buf;
1038 
1039     /* Honor a command-line option limiting the size of the buffer.  */
1040     if (size > tb_size) {
1041         size = QEMU_ALIGN_DOWN(tb_size, qemu_real_host_page_size);
1042     }
1043     tcg_ctx->code_gen_buffer_size = size;
1044 
1045 #ifdef __mips__
1046     if (cross_256mb(buf, size)) {
1047         buf = split_cross_256mb(buf, size);
1048         size = tcg_ctx->code_gen_buffer_size;
1049     }
1050 #endif
1051 
1052     if (qemu_mprotect_rwx(buf, size)) {
1053         error_setg_errno(errp, errno, "mprotect of jit buffer");
1054         return false;
1055     }
1056     qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);
1057 
1058     tcg_ctx->code_gen_buffer = buf;
1059     return true;
1060 }
1061 #elif defined(_WIN32)
1062 static bool alloc_code_gen_buffer(size_t size, int splitwx, Error **errp)
1063 {
1064     void *buf;
1065 
1066     if (splitwx > 0) {
1067         error_setg(errp, "jit split-wx not supported");
1068         return false;
1069     }
1070 
1071     buf = VirtualAlloc(NULL, size, MEM_RESERVE | MEM_COMMIT,
1072                              PAGE_EXECUTE_READWRITE);
1073     if (buf == NULL) {
1074         error_setg_win32(errp, GetLastError(),
1075                          "allocate %zu bytes for jit buffer", size);
1076         return false;
1077     }
1078 
1079     tcg_ctx->code_gen_buffer = buf;
1080     tcg_ctx->code_gen_buffer_size = size;
1081     return true;
1082 }
1083 #else
1084 static bool alloc_code_gen_buffer_anon(size_t size, int prot,
1085                                        int flags, Error **errp)
1086 {
1087     void *buf;
1088 
1089     buf = mmap(NULL, size, prot, flags, -1, 0);
1090     if (buf == MAP_FAILED) {
1091         error_setg_errno(errp, errno,
1092                          "allocate %zu bytes for jit buffer", size);
1093         return false;
1094     }
1095     tcg_ctx->code_gen_buffer_size = size;
1096 
1097 #ifdef __mips__
1098     if (cross_256mb(buf, size)) {
1099         /*
1100          * Try again, with the original still mapped, to avoid re-acquiring
1101          * the same 256mb crossing.
1102          */
1103         size_t size2;
1104         void *buf2 = mmap(NULL, size, prot, flags, -1, 0);
1105         switch ((int)(buf2 != MAP_FAILED)) {
1106         case 1:
1107             if (!cross_256mb(buf2, size)) {
1108                 /* Success!  Use the new buffer.  */
1109                 munmap(buf, size);
1110                 break;
1111             }
1112             /* Failure.  Work with what we had.  */
1113             munmap(buf2, size);
1114             /* fallthru */
1115         default:
1116             /* Split the original buffer.  Free the smaller half.  */
1117             buf2 = split_cross_256mb(buf, size);
1118             size2 = tcg_ctx->code_gen_buffer_size;
1119             if (buf == buf2) {
1120                 munmap(buf + size2, size - size2);
1121             } else {
1122                 munmap(buf, size - size2);
1123             }
1124             size = size2;
1125             break;
1126         }
1127         buf = buf2;
1128     }
1129 #endif
1130 
1131     /* Request large pages for the buffer.  */
1132     qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);
1133 
1134     tcg_ctx->code_gen_buffer = buf;
1135     return true;
1136 }
1137 
1138 #ifndef CONFIG_TCG_INTERPRETER
1139 #ifdef CONFIG_POSIX
1140 #include "qemu/memfd.h"
1141 
1142 static bool alloc_code_gen_buffer_splitwx_memfd(size_t size, Error **errp)
1143 {
1144     void *buf_rw = NULL, *buf_rx = MAP_FAILED;
1145     int fd = -1;
1146 
1147 #ifdef __mips__
1148     /* Find space for the RX mapping, vs the 256MiB regions. */
1149     if (!alloc_code_gen_buffer_anon(size, PROT_NONE,
1150                                     MAP_PRIVATE | MAP_ANONYMOUS |
1151                                     MAP_NORESERVE, errp)) {
1152         return false;
1153     }
1154     /* The size of the mapping may have been adjusted. */
1155     size = tcg_ctx->code_gen_buffer_size;
1156     buf_rx = tcg_ctx->code_gen_buffer;
1157 #endif
1158 
1159     buf_rw = qemu_memfd_alloc("tcg-jit", size, 0, &fd, errp);
1160     if (buf_rw == NULL) {
1161         goto fail;
1162     }
1163 
1164 #ifdef __mips__
1165     void *tmp = mmap(buf_rx, size, PROT_READ | PROT_EXEC,
1166                      MAP_SHARED | MAP_FIXED, fd, 0);
1167     if (tmp != buf_rx) {
1168         goto fail_rx;
1169     }
1170 #else
1171     buf_rx = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0);
1172     if (buf_rx == MAP_FAILED) {
1173         goto fail_rx;
1174     }
1175 #endif
1176 
1177     close(fd);
1178     tcg_ctx->code_gen_buffer = buf_rw;
1179     tcg_ctx->code_gen_buffer_size = size;
1180     tcg_splitwx_diff = buf_rx - buf_rw;
1181 
1182     /* Request large pages for the buffer and the splitwx.  */
1183     qemu_madvise(buf_rw, size, QEMU_MADV_HUGEPAGE);
1184     qemu_madvise(buf_rx, size, QEMU_MADV_HUGEPAGE);
1185     return true;
1186 
1187  fail_rx:
1188     error_setg_errno(errp, errno, "failed to map shared memory for execute");
1189  fail:
1190     if (buf_rx != MAP_FAILED) {
1191         munmap(buf_rx, size);
1192     }
1193     if (buf_rw) {
1194         munmap(buf_rw, size);
1195     }
1196     if (fd >= 0) {
1197         close(fd);
1198     }
1199     return false;
1200 }
1201 #endif /* CONFIG_POSIX */
1202 
1203 #ifdef CONFIG_DARWIN
1204 #include <mach/mach.h>
1205 
1206 extern kern_return_t mach_vm_remap(vm_map_t target_task,
1207                                    mach_vm_address_t *target_address,
1208                                    mach_vm_size_t size,
1209                                    mach_vm_offset_t mask,
1210                                    int flags,
1211                                    vm_map_t src_task,
1212                                    mach_vm_address_t src_address,
1213                                    boolean_t copy,
1214                                    vm_prot_t *cur_protection,
1215                                    vm_prot_t *max_protection,
1216                                    vm_inherit_t inheritance);
1217 
1218 static bool alloc_code_gen_buffer_splitwx_vmremap(size_t size, Error **errp)
1219 {
1220     kern_return_t ret;
1221     mach_vm_address_t buf_rw, buf_rx;
1222     vm_prot_t cur_prot, max_prot;
1223 
1224     /* Map the read-write portion via normal anon memory. */
1225     if (!alloc_code_gen_buffer_anon(size, PROT_READ | PROT_WRITE,
1226                                     MAP_PRIVATE | MAP_ANONYMOUS, errp)) {
1227         return false;
1228     }
1229 
1230     buf_rw = (mach_vm_address_t)tcg_ctx->code_gen_buffer;
1231     buf_rx = 0;
1232     ret = mach_vm_remap(mach_task_self(),
1233                         &buf_rx,
1234                         size,
1235                         0,
1236                         VM_FLAGS_ANYWHERE,
1237                         mach_task_self(),
1238                         buf_rw,
1239                         false,
1240                         &cur_prot,
1241                         &max_prot,
1242                         VM_INHERIT_NONE);
1243     if (ret != KERN_SUCCESS) {
1244         /* TODO: Convert "ret" to a human readable error message. */
1245         error_setg(errp, "vm_remap for jit splitwx failed");
1246         munmap((void *)buf_rw, size);
1247         return false;
1248     }
1249 
1250     if (mprotect((void *)buf_rx, size, PROT_READ | PROT_EXEC) != 0) {
1251         error_setg_errno(errp, errno, "mprotect for jit splitwx");
1252         munmap((void *)buf_rx, size);
1253         munmap((void *)buf_rw, size);
1254         return false;
1255     }
1256 
1257     tcg_splitwx_diff = buf_rx - buf_rw;
1258     return true;
1259 }
1260 #endif /* CONFIG_DARWIN */
1261 #endif /* CONFIG_TCG_INTERPRETER */
1262 
1263 static bool alloc_code_gen_buffer_splitwx(size_t size, Error **errp)
1264 {
1265 #ifndef CONFIG_TCG_INTERPRETER
1266 # ifdef CONFIG_DARWIN
1267     return alloc_code_gen_buffer_splitwx_vmremap(size, errp);
1268 # endif
1269 # ifdef CONFIG_POSIX
1270     return alloc_code_gen_buffer_splitwx_memfd(size, errp);
1271 # endif
1272 #endif
1273     error_setg(errp, "jit split-wx not supported");
1274     return false;
1275 }
1276 
1277 static bool alloc_code_gen_buffer(size_t size, int splitwx, Error **errp)
1278 {
1279     ERRP_GUARD();
1280     int prot, flags;
1281 
1282     if (splitwx) {
1283         if (alloc_code_gen_buffer_splitwx(size, errp)) {
1284             return true;
1285         }
1286         /*
1287          * If splitwx force-on (1), fail;
1288          * if splitwx default-on (-1), fall through to splitwx off.
1289          */
1290         if (splitwx > 0) {
1291             return false;
1292         }
1293         error_free_or_abort(errp);
1294     }
1295 
1296     prot = PROT_READ | PROT_WRITE | PROT_EXEC;
1297     flags = MAP_PRIVATE | MAP_ANONYMOUS;
1298 #ifdef CONFIG_TCG_INTERPRETER
1299     /* The tcg interpreter does not need execute permission. */
1300     prot = PROT_READ | PROT_WRITE;
1301 #elif defined(CONFIG_DARWIN)
1302     /* Applicable to both iOS and macOS (Apple Silicon). */
1303     if (!splitwx) {
1304         flags |= MAP_JIT;
1305     }
1306 #endif
1307 
1308     return alloc_code_gen_buffer_anon(size, prot, flags, errp);
1309 }
1310 #endif /* USE_STATIC_CODE_GEN_BUFFER, WIN32, POSIX */
1311 
1312 static bool tb_cmp(const void *ap, const void *bp)
1313 {
1314     const TranslationBlock *a = ap;
1315     const TranslationBlock *b = bp;
1316 
1317     return a->pc == b->pc &&
1318         a->cs_base == b->cs_base &&
1319         a->flags == b->flags &&
1320         (tb_cflags(a) & CF_HASH_MASK) == (tb_cflags(b) & CF_HASH_MASK) &&
1321         a->trace_vcpu_dstate == b->trace_vcpu_dstate &&
1322         a->page_addr[0] == b->page_addr[0] &&
1323         a->page_addr[1] == b->page_addr[1];
1324 }
1325 
1326 static void tb_htable_init(void)
1327 {
1328     unsigned int mode = QHT_MODE_AUTO_RESIZE;
1329 
1330     qht_init(&tb_ctx.htable, tb_cmp, CODE_GEN_HTABLE_SIZE, mode);
1331 }
1332 
1333 /* Must be called before using the QEMU cpus. 'tb_size' is the size
1334    (in bytes) allocated to the translation buffer. Zero means default
1335    size. */
1336 void tcg_exec_init(unsigned long tb_size, int splitwx)
1337 {
1338     bool ok;
1339 
1340     tcg_allowed = true;
1341     cpu_gen_init();
1342     page_init();
1343     tb_htable_init();
1344 
1345     ok = alloc_code_gen_buffer(size_code_gen_buffer(tb_size),
1346                                splitwx, &error_fatal);
1347     assert(ok);
1348 
1349 #if defined(CONFIG_SOFTMMU)
1350     /* There's no guest base to take into account, so go ahead and
1351        initialize the prologue now.  */
1352     tcg_prologue_init(tcg_ctx);
1353 #endif
1354 }
1355 
1356 /* call with @p->lock held */
1357 static inline void invalidate_page_bitmap(PageDesc *p)
1358 {
1359     assert_page_locked(p);
1360 #ifdef CONFIG_SOFTMMU
1361     g_free(p->code_bitmap);
1362     p->code_bitmap = NULL;
1363     p->code_write_count = 0;
1364 #endif
1365 }
1366 
1367 /* Set to NULL all the 'first_tb' fields in all PageDescs. */
1368 static void page_flush_tb_1(int level, void **lp)
1369 {
1370     int i;
1371 
1372     if (*lp == NULL) {
1373         return;
1374     }
1375     if (level == 0) {
1376         PageDesc *pd = *lp;
1377 
1378         for (i = 0; i < V_L2_SIZE; ++i) {
1379             page_lock(&pd[i]);
1380             pd[i].first_tb = (uintptr_t)NULL;
1381             invalidate_page_bitmap(pd + i);
1382             page_unlock(&pd[i]);
1383         }
1384     } else {
1385         void **pp = *lp;
1386 
1387         for (i = 0; i < V_L2_SIZE; ++i) {
1388             page_flush_tb_1(level - 1, pp + i);
1389         }
1390     }
1391 }
1392 
1393 static void page_flush_tb(void)
1394 {
1395     int i, l1_sz = v_l1_size;
1396 
1397     for (i = 0; i < l1_sz; i++) {
1398         page_flush_tb_1(v_l2_levels, l1_map + i);
1399     }
1400 }
1401 
1402 static gboolean tb_host_size_iter(gpointer key, gpointer value, gpointer data)
1403 {
1404     const TranslationBlock *tb = value;
1405     size_t *size = data;
1406 
1407     *size += tb->tc.size;
1408     return false;
1409 }
1410 
1411 /* flush all the translation blocks */
1412 static void do_tb_flush(CPUState *cpu, run_on_cpu_data tb_flush_count)
1413 {
1414     bool did_flush = false;
1415 
1416     mmap_lock();
1417     /* If it is already been done on request of another CPU,
1418      * just retry.
1419      */
1420     if (tb_ctx.tb_flush_count != tb_flush_count.host_int) {
1421         goto done;
1422     }
1423     did_flush = true;
1424 
1425     if (DEBUG_TB_FLUSH_GATE) {
1426         size_t nb_tbs = tcg_nb_tbs();
1427         size_t host_size = 0;
1428 
1429         tcg_tb_foreach(tb_host_size_iter, &host_size);
1430         printf("qemu: flush code_size=%zu nb_tbs=%zu avg_tb_size=%zu\n",
1431                tcg_code_size(), nb_tbs, nb_tbs > 0 ? host_size / nb_tbs : 0);
1432     }
1433 
1434     CPU_FOREACH(cpu) {
1435         cpu_tb_jmp_cache_clear(cpu);
1436     }
1437 
1438     qht_reset_size(&tb_ctx.htable, CODE_GEN_HTABLE_SIZE);
1439     page_flush_tb();
1440 
1441     tcg_region_reset_all();
1442     /* XXX: flush processor icache at this point if cache flush is
1443        expensive */
1444     qatomic_mb_set(&tb_ctx.tb_flush_count, tb_ctx.tb_flush_count + 1);
1445 
1446 done:
1447     mmap_unlock();
1448     if (did_flush) {
1449         qemu_plugin_flush_cb();
1450     }
1451 }
1452 
1453 void tb_flush(CPUState *cpu)
1454 {
1455     if (tcg_enabled()) {
1456         unsigned tb_flush_count = qatomic_mb_read(&tb_ctx.tb_flush_count);
1457 
1458         if (cpu_in_exclusive_context(cpu)) {
1459             do_tb_flush(cpu, RUN_ON_CPU_HOST_INT(tb_flush_count));
1460         } else {
1461             async_safe_run_on_cpu(cpu, do_tb_flush,
1462                                   RUN_ON_CPU_HOST_INT(tb_flush_count));
1463         }
1464     }
1465 }
1466 
1467 /*
1468  * Formerly ifdef DEBUG_TB_CHECK. These debug functions are user-mode-only,
1469  * so in order to prevent bit rot we compile them unconditionally in user-mode,
1470  * and let the optimizer get rid of them by wrapping their user-only callers
1471  * with if (DEBUG_TB_CHECK_GATE).
1472  */
1473 #ifdef CONFIG_USER_ONLY
1474 
1475 static void do_tb_invalidate_check(void *p, uint32_t hash, void *userp)
1476 {
1477     TranslationBlock *tb = p;
1478     target_ulong addr = *(target_ulong *)userp;
1479 
1480     if (!(addr + TARGET_PAGE_SIZE <= tb->pc || addr >= tb->pc + tb->size)) {
1481         printf("ERROR invalidate: address=" TARGET_FMT_lx
1482                " PC=%08lx size=%04x\n", addr, (long)tb->pc, tb->size);
1483     }
1484 }
1485 
1486 /* verify that all the pages have correct rights for code
1487  *
1488  * Called with mmap_lock held.
1489  */
1490 static void tb_invalidate_check(target_ulong address)
1491 {
1492     address &= TARGET_PAGE_MASK;
1493     qht_iter(&tb_ctx.htable, do_tb_invalidate_check, &address);
1494 }
1495 
1496 static void do_tb_page_check(void *p, uint32_t hash, void *userp)
1497 {
1498     TranslationBlock *tb = p;
1499     int flags1, flags2;
1500 
1501     flags1 = page_get_flags(tb->pc);
1502     flags2 = page_get_flags(tb->pc + tb->size - 1);
1503     if ((flags1 & PAGE_WRITE) || (flags2 & PAGE_WRITE)) {
1504         printf("ERROR page flags: PC=%08lx size=%04x f1=%x f2=%x\n",
1505                (long)tb->pc, tb->size, flags1, flags2);
1506     }
1507 }
1508 
1509 /* verify that all the pages have correct rights for code */
1510 static void tb_page_check(void)
1511 {
1512     qht_iter(&tb_ctx.htable, do_tb_page_check, NULL);
1513 }
1514 
1515 #endif /* CONFIG_USER_ONLY */
1516 
1517 /*
1518  * user-mode: call with mmap_lock held
1519  * !user-mode: call with @pd->lock held
1520  */
1521 static inline void tb_page_remove(PageDesc *pd, TranslationBlock *tb)
1522 {
1523     TranslationBlock *tb1;
1524     uintptr_t *pprev;
1525     unsigned int n1;
1526 
1527     assert_page_locked(pd);
1528     pprev = &pd->first_tb;
1529     PAGE_FOR_EACH_TB(pd, tb1, n1) {
1530         if (tb1 == tb) {
1531             *pprev = tb1->page_next[n1];
1532             return;
1533         }
1534         pprev = &tb1->page_next[n1];
1535     }
1536     g_assert_not_reached();
1537 }
1538 
1539 /* remove @orig from its @n_orig-th jump list */
1540 static inline void tb_remove_from_jmp_list(TranslationBlock *orig, int n_orig)
1541 {
1542     uintptr_t ptr, ptr_locked;
1543     TranslationBlock *dest;
1544     TranslationBlock *tb;
1545     uintptr_t *pprev;
1546     int n;
1547 
1548     /* mark the LSB of jmp_dest[] so that no further jumps can be inserted */
1549     ptr = qatomic_or_fetch(&orig->jmp_dest[n_orig], 1);
1550     dest = (TranslationBlock *)(ptr & ~1);
1551     if (dest == NULL) {
1552         return;
1553     }
1554 
1555     qemu_spin_lock(&dest->jmp_lock);
1556     /*
1557      * While acquiring the lock, the jump might have been removed if the
1558      * destination TB was invalidated; check again.
1559      */
1560     ptr_locked = qatomic_read(&orig->jmp_dest[n_orig]);
1561     if (ptr_locked != ptr) {
1562         qemu_spin_unlock(&dest->jmp_lock);
1563         /*
1564          * The only possibility is that the jump was unlinked via
1565          * tb_jump_unlink(dest). Seeing here another destination would be a bug,
1566          * because we set the LSB above.
1567          */
1568         g_assert(ptr_locked == 1 && dest->cflags & CF_INVALID);
1569         return;
1570     }
1571     /*
1572      * We first acquired the lock, and since the destination pointer matches,
1573      * we know for sure that @orig is in the jmp list.
1574      */
1575     pprev = &dest->jmp_list_head;
1576     TB_FOR_EACH_JMP(dest, tb, n) {
1577         if (tb == orig && n == n_orig) {
1578             *pprev = tb->jmp_list_next[n];
1579             /* no need to set orig->jmp_dest[n]; setting the LSB was enough */
1580             qemu_spin_unlock(&dest->jmp_lock);
1581             return;
1582         }
1583         pprev = &tb->jmp_list_next[n];
1584     }
1585     g_assert_not_reached();
1586 }
1587 
1588 /* reset the jump entry 'n' of a TB so that it is not chained to
1589    another TB */
1590 static inline void tb_reset_jump(TranslationBlock *tb, int n)
1591 {
1592     uintptr_t addr = (uintptr_t)(tb->tc.ptr + tb->jmp_reset_offset[n]);
1593     tb_set_jmp_target(tb, n, addr);
1594 }
1595 
1596 /* remove any jumps to the TB */
1597 static inline void tb_jmp_unlink(TranslationBlock *dest)
1598 {
1599     TranslationBlock *tb;
1600     int n;
1601 
1602     qemu_spin_lock(&dest->jmp_lock);
1603 
1604     TB_FOR_EACH_JMP(dest, tb, n) {
1605         tb_reset_jump(tb, n);
1606         qatomic_and(&tb->jmp_dest[n], (uintptr_t)NULL | 1);
1607         /* No need to clear the list entry; setting the dest ptr is enough */
1608     }
1609     dest->jmp_list_head = (uintptr_t)NULL;
1610 
1611     qemu_spin_unlock(&dest->jmp_lock);
1612 }
1613 
1614 /*
1615  * In user-mode, call with mmap_lock held.
1616  * In !user-mode, if @rm_from_page_list is set, call with the TB's pages'
1617  * locks held.
1618  */
1619 static void do_tb_phys_invalidate(TranslationBlock *tb, bool rm_from_page_list)
1620 {
1621     CPUState *cpu;
1622     PageDesc *p;
1623     uint32_t h;
1624     tb_page_addr_t phys_pc;
1625 
1626     assert_memory_lock();
1627 
1628     /* make sure no further incoming jumps will be chained to this TB */
1629     qemu_spin_lock(&tb->jmp_lock);
1630     qatomic_set(&tb->cflags, tb->cflags | CF_INVALID);
1631     qemu_spin_unlock(&tb->jmp_lock);
1632 
1633     /* remove the TB from the hash list */
1634     phys_pc = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);
1635     h = tb_hash_func(phys_pc, tb->pc, tb->flags, tb_cflags(tb) & CF_HASH_MASK,
1636                      tb->trace_vcpu_dstate);
1637     if (!(tb->cflags & CF_NOCACHE) &&
1638         !qht_remove(&tb_ctx.htable, tb, h)) {
1639         return;
1640     }
1641 
1642     /* remove the TB from the page list */
1643     if (rm_from_page_list) {
1644         p = page_find(tb->page_addr[0] >> TARGET_PAGE_BITS);
1645         tb_page_remove(p, tb);
1646         invalidate_page_bitmap(p);
1647         if (tb->page_addr[1] != -1) {
1648             p = page_find(tb->page_addr[1] >> TARGET_PAGE_BITS);
1649             tb_page_remove(p, tb);
1650             invalidate_page_bitmap(p);
1651         }
1652     }
1653 
1654     /* remove the TB from the hash list */
1655     h = tb_jmp_cache_hash_func(tb->pc);
1656     CPU_FOREACH(cpu) {
1657         if (qatomic_read(&cpu->tb_jmp_cache[h]) == tb) {
1658             qatomic_set(&cpu->tb_jmp_cache[h], NULL);
1659         }
1660     }
1661 
1662     /* suppress this TB from the two jump lists */
1663     tb_remove_from_jmp_list(tb, 0);
1664     tb_remove_from_jmp_list(tb, 1);
1665 
1666     /* suppress any remaining jumps to this TB */
1667     tb_jmp_unlink(tb);
1668 
1669     qatomic_set(&tcg_ctx->tb_phys_invalidate_count,
1670                tcg_ctx->tb_phys_invalidate_count + 1);
1671 }
1672 
1673 static void tb_phys_invalidate__locked(TranslationBlock *tb)
1674 {
1675     qemu_thread_jit_write();
1676     do_tb_phys_invalidate(tb, true);
1677     qemu_thread_jit_execute();
1678 }
1679 
1680 /* invalidate one TB
1681  *
1682  * Called with mmap_lock held in user-mode.
1683  */
1684 void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr)
1685 {
1686     if (page_addr == -1 && tb->page_addr[0] != -1) {
1687         page_lock_tb(tb);
1688         do_tb_phys_invalidate(tb, true);
1689         page_unlock_tb(tb);
1690     } else {
1691         do_tb_phys_invalidate(tb, false);
1692     }
1693 }
1694 
1695 #ifdef CONFIG_SOFTMMU
1696 /* call with @p->lock held */
1697 static void build_page_bitmap(PageDesc *p)
1698 {
1699     int n, tb_start, tb_end;
1700     TranslationBlock *tb;
1701 
1702     assert_page_locked(p);
1703     p->code_bitmap = bitmap_new(TARGET_PAGE_SIZE);
1704 
1705     PAGE_FOR_EACH_TB(p, tb, n) {
1706         /* NOTE: this is subtle as a TB may span two physical pages */
1707         if (n == 0) {
1708             /* NOTE: tb_end may be after the end of the page, but
1709                it is not a problem */
1710             tb_start = tb->pc & ~TARGET_PAGE_MASK;
1711             tb_end = tb_start + tb->size;
1712             if (tb_end > TARGET_PAGE_SIZE) {
1713                 tb_end = TARGET_PAGE_SIZE;
1714              }
1715         } else {
1716             tb_start = 0;
1717             tb_end = ((tb->pc + tb->size) & ~TARGET_PAGE_MASK);
1718         }
1719         bitmap_set(p->code_bitmap, tb_start, tb_end - tb_start);
1720     }
1721 }
1722 #endif
1723 
1724 /* add the tb in the target page and protect it if necessary
1725  *
1726  * Called with mmap_lock held for user-mode emulation.
1727  * Called with @p->lock held in !user-mode.
1728  */
1729 static inline void tb_page_add(PageDesc *p, TranslationBlock *tb,
1730                                unsigned int n, tb_page_addr_t page_addr)
1731 {
1732 #ifndef CONFIG_USER_ONLY
1733     bool page_already_protected;
1734 #endif
1735 
1736     assert_page_locked(p);
1737 
1738     tb->page_addr[n] = page_addr;
1739     tb->page_next[n] = p->first_tb;
1740 #ifndef CONFIG_USER_ONLY
1741     page_already_protected = p->first_tb != (uintptr_t)NULL;
1742 #endif
1743     p->first_tb = (uintptr_t)tb | n;
1744     invalidate_page_bitmap(p);
1745 
1746 #if defined(CONFIG_USER_ONLY)
1747     if (p->flags & PAGE_WRITE) {
1748         target_ulong addr;
1749         PageDesc *p2;
1750         int prot;
1751 
1752         /* force the host page as non writable (writes will have a
1753            page fault + mprotect overhead) */
1754         page_addr &= qemu_host_page_mask;
1755         prot = 0;
1756         for (addr = page_addr; addr < page_addr + qemu_host_page_size;
1757             addr += TARGET_PAGE_SIZE) {
1758 
1759             p2 = page_find(addr >> TARGET_PAGE_BITS);
1760             if (!p2) {
1761                 continue;
1762             }
1763             prot |= p2->flags;
1764             p2->flags &= ~PAGE_WRITE;
1765           }
1766         mprotect(g2h_untagged(page_addr), qemu_host_page_size,
1767                  (prot & PAGE_BITS) & ~PAGE_WRITE);
1768         if (DEBUG_TB_INVALIDATE_GATE) {
1769             printf("protecting code page: 0x" TB_PAGE_ADDR_FMT "\n", page_addr);
1770         }
1771     }
1772 #else
1773     /* if some code is already present, then the pages are already
1774        protected. So we handle the case where only the first TB is
1775        allocated in a physical page */
1776     if (!page_already_protected) {
1777         tlb_protect_code(page_addr);
1778     }
1779 #endif
1780 }
1781 
1782 /* add a new TB and link it to the physical page tables. phys_page2 is
1783  * (-1) to indicate that only one page contains the TB.
1784  *
1785  * Called with mmap_lock held for user-mode emulation.
1786  *
1787  * Returns a pointer @tb, or a pointer to an existing TB that matches @tb.
1788  * Note that in !user-mode, another thread might have already added a TB
1789  * for the same block of guest code that @tb corresponds to. In that case,
1790  * the caller should discard the original @tb, and use instead the returned TB.
1791  */
1792 static TranslationBlock *
1793 tb_link_page(TranslationBlock *tb, tb_page_addr_t phys_pc,
1794              tb_page_addr_t phys_page2)
1795 {
1796     PageDesc *p;
1797     PageDesc *p2 = NULL;
1798 
1799     assert_memory_lock();
1800 
1801     if (phys_pc == -1) {
1802         /*
1803          * If the TB is not associated with a physical RAM page then
1804          * it must be a temporary one-insn TB, and we have nothing to do
1805          * except fill in the page_addr[] fields.
1806          */
1807         assert(tb->cflags & CF_NOCACHE);
1808         tb->page_addr[0] = tb->page_addr[1] = -1;
1809         return tb;
1810     }
1811 
1812     /*
1813      * Add the TB to the page list, acquiring first the pages's locks.
1814      * We keep the locks held until after inserting the TB in the hash table,
1815      * so that if the insertion fails we know for sure that the TBs are still
1816      * in the page descriptors.
1817      * Note that inserting into the hash table first isn't an option, since
1818      * we can only insert TBs that are fully initialized.
1819      */
1820     page_lock_pair(&p, phys_pc, &p2, phys_page2, 1);
1821     tb_page_add(p, tb, 0, phys_pc & TARGET_PAGE_MASK);
1822     if (p2) {
1823         tb_page_add(p2, tb, 1, phys_page2);
1824     } else {
1825         tb->page_addr[1] = -1;
1826     }
1827 
1828     if (!(tb->cflags & CF_NOCACHE)) {
1829         void *existing_tb = NULL;
1830         uint32_t h;
1831 
1832         /* add in the hash table */
1833         h = tb_hash_func(phys_pc, tb->pc, tb->flags, tb->cflags & CF_HASH_MASK,
1834                          tb->trace_vcpu_dstate);
1835         qht_insert(&tb_ctx.htable, tb, h, &existing_tb);
1836 
1837         /* remove TB from the page(s) if we couldn't insert it */
1838         if (unlikely(existing_tb)) {
1839             tb_page_remove(p, tb);
1840             invalidate_page_bitmap(p);
1841             if (p2) {
1842                 tb_page_remove(p2, tb);
1843                 invalidate_page_bitmap(p2);
1844             }
1845             tb = existing_tb;
1846         }
1847     }
1848 
1849     if (p2 && p2 != p) {
1850         page_unlock(p2);
1851     }
1852     page_unlock(p);
1853 
1854 #ifdef CONFIG_USER_ONLY
1855     if (DEBUG_TB_CHECK_GATE) {
1856         tb_page_check();
1857     }
1858 #endif
1859     return tb;
1860 }
1861 
1862 /* Called with mmap_lock held for user mode emulation.  */
1863 TranslationBlock *tb_gen_code(CPUState *cpu,
1864                               target_ulong pc, target_ulong cs_base,
1865                               uint32_t flags, int cflags)
1866 {
1867     CPUArchState *env = cpu->env_ptr;
1868     TranslationBlock *tb, *existing_tb;
1869     tb_page_addr_t phys_pc, phys_page2;
1870     target_ulong virt_page2;
1871     tcg_insn_unit *gen_code_buf;
1872     int gen_code_size, search_size, max_insns;
1873 #ifdef CONFIG_PROFILER
1874     TCGProfile *prof = &tcg_ctx->prof;
1875     int64_t ti;
1876 #endif
1877 
1878     assert_memory_lock();
1879     qemu_thread_jit_write();
1880 
1881     phys_pc = get_page_addr_code(env, pc);
1882 
1883     if (phys_pc == -1) {
1884         /* Generate a temporary TB with 1 insn in it */
1885         cflags &= ~CF_COUNT_MASK;
1886         cflags |= CF_NOCACHE | 1;
1887     }
1888 
1889     cflags &= ~CF_CLUSTER_MASK;
1890     cflags |= cpu->cluster_index << CF_CLUSTER_SHIFT;
1891 
1892     max_insns = cflags & CF_COUNT_MASK;
1893     if (max_insns == 0) {
1894         max_insns = CF_COUNT_MASK;
1895     }
1896     if (max_insns > TCG_MAX_INSNS) {
1897         max_insns = TCG_MAX_INSNS;
1898     }
1899     if (cpu->singlestep_enabled || singlestep) {
1900         max_insns = 1;
1901     }
1902 
1903  buffer_overflow:
1904     tb = tcg_tb_alloc(tcg_ctx);
1905     if (unlikely(!tb)) {
1906         /* flush must be done */
1907         tb_flush(cpu);
1908         mmap_unlock();
1909         /* Make the execution loop process the flush as soon as possible.  */
1910         cpu->exception_index = EXCP_INTERRUPT;
1911         cpu_loop_exit(cpu);
1912     }
1913 
1914     gen_code_buf = tcg_ctx->code_gen_ptr;
1915     tb->tc.ptr = tcg_splitwx_to_rx(gen_code_buf);
1916     tb->pc = pc;
1917     tb->cs_base = cs_base;
1918     tb->flags = flags;
1919     tb->cflags = cflags;
1920     tb->orig_tb = NULL;
1921     tb->trace_vcpu_dstate = *cpu->trace_dstate;
1922     tcg_ctx->tb_cflags = cflags;
1923  tb_overflow:
1924 
1925 #ifdef CONFIG_PROFILER
1926     /* includes aborted translations because of exceptions */
1927     qatomic_set(&prof->tb_count1, prof->tb_count1 + 1);
1928     ti = profile_getclock();
1929 #endif
1930 
1931     gen_code_size = sigsetjmp(tcg_ctx->jmp_trans, 0);
1932     if (unlikely(gen_code_size != 0)) {
1933         goto error_return;
1934     }
1935 
1936     tcg_func_start(tcg_ctx);
1937 
1938     tcg_ctx->cpu = env_cpu(env);
1939     gen_intermediate_code(cpu, tb, max_insns);
1940     tcg_ctx->cpu = NULL;
1941     max_insns = tb->icount;
1942 
1943     trace_translate_block(tb, tb->pc, tb->tc.ptr);
1944 
1945     /* generate machine code */
1946     tb->jmp_reset_offset[0] = TB_JMP_RESET_OFFSET_INVALID;
1947     tb->jmp_reset_offset[1] = TB_JMP_RESET_OFFSET_INVALID;
1948     tcg_ctx->tb_jmp_reset_offset = tb->jmp_reset_offset;
1949     if (TCG_TARGET_HAS_direct_jump) {
1950         tcg_ctx->tb_jmp_insn_offset = tb->jmp_target_arg;
1951         tcg_ctx->tb_jmp_target_addr = NULL;
1952     } else {
1953         tcg_ctx->tb_jmp_insn_offset = NULL;
1954         tcg_ctx->tb_jmp_target_addr = tb->jmp_target_arg;
1955     }
1956 
1957 #ifdef CONFIG_PROFILER
1958     qatomic_set(&prof->tb_count, prof->tb_count + 1);
1959     qatomic_set(&prof->interm_time,
1960                 prof->interm_time + profile_getclock() - ti);
1961     ti = profile_getclock();
1962 #endif
1963 
1964     gen_code_size = tcg_gen_code(tcg_ctx, tb);
1965     if (unlikely(gen_code_size < 0)) {
1966  error_return:
1967         switch (gen_code_size) {
1968         case -1:
1969             /*
1970              * Overflow of code_gen_buffer, or the current slice of it.
1971              *
1972              * TODO: We don't need to re-do gen_intermediate_code, nor
1973              * should we re-do the tcg optimization currently hidden
1974              * inside tcg_gen_code.  All that should be required is to
1975              * flush the TBs, allocate a new TB, re-initialize it per
1976              * above, and re-do the actual code generation.
1977              */
1978             qemu_log_mask(CPU_LOG_TB_OP | CPU_LOG_TB_OP_OPT,
1979                           "Restarting code generation for "
1980                           "code_gen_buffer overflow\n");
1981             goto buffer_overflow;
1982 
1983         case -2:
1984             /*
1985              * The code generated for the TranslationBlock is too large.
1986              * The maximum size allowed by the unwind info is 64k.
1987              * There may be stricter constraints from relocations
1988              * in the tcg backend.
1989              *
1990              * Try again with half as many insns as we attempted this time.
1991              * If a single insn overflows, there's a bug somewhere...
1992              */
1993             assert(max_insns > 1);
1994             max_insns /= 2;
1995             qemu_log_mask(CPU_LOG_TB_OP | CPU_LOG_TB_OP_OPT,
1996                           "Restarting code generation with "
1997                           "smaller translation block (max %d insns)\n",
1998                           max_insns);
1999             goto tb_overflow;
2000 
2001         default:
2002             g_assert_not_reached();
2003         }
2004     }
2005     search_size = encode_search(tb, (void *)gen_code_buf + gen_code_size);
2006     if (unlikely(search_size < 0)) {
2007         goto buffer_overflow;
2008     }
2009     tb->tc.size = gen_code_size;
2010 
2011 #ifdef CONFIG_PROFILER
2012     qatomic_set(&prof->code_time, prof->code_time + profile_getclock() - ti);
2013     qatomic_set(&prof->code_in_len, prof->code_in_len + tb->size);
2014     qatomic_set(&prof->code_out_len, prof->code_out_len + gen_code_size);
2015     qatomic_set(&prof->search_out_len, prof->search_out_len + search_size);
2016 #endif
2017 
2018 #ifdef DEBUG_DISAS
2019     if (qemu_loglevel_mask(CPU_LOG_TB_OUT_ASM) &&
2020         qemu_log_in_addr_range(tb->pc)) {
2021         FILE *logfile = qemu_log_lock();
2022         int code_size, data_size;
2023         const tcg_target_ulong *rx_data_gen_ptr;
2024         size_t chunk_start;
2025         int insn = 0;
2026 
2027         if (tcg_ctx->data_gen_ptr) {
2028             rx_data_gen_ptr = tcg_splitwx_to_rx(tcg_ctx->data_gen_ptr);
2029             code_size = (const void *)rx_data_gen_ptr - tb->tc.ptr;
2030             data_size = gen_code_size - code_size;
2031         } else {
2032             rx_data_gen_ptr = 0;
2033             code_size = gen_code_size;
2034             data_size = 0;
2035         }
2036 
2037         /* Dump header and the first instruction */
2038         qemu_log("OUT: [size=%d]\n", gen_code_size);
2039         qemu_log("  -- guest addr 0x" TARGET_FMT_lx " + tb prologue\n",
2040                  tcg_ctx->gen_insn_data[insn][0]);
2041         chunk_start = tcg_ctx->gen_insn_end_off[insn];
2042         log_disas(tb->tc.ptr, chunk_start);
2043 
2044         /*
2045          * Dump each instruction chunk, wrapping up empty chunks into
2046          * the next instruction. The whole array is offset so the
2047          * first entry is the beginning of the 2nd instruction.
2048          */
2049         while (insn < tb->icount) {
2050             size_t chunk_end = tcg_ctx->gen_insn_end_off[insn];
2051             if (chunk_end > chunk_start) {
2052                 qemu_log("  -- guest addr 0x" TARGET_FMT_lx "\n",
2053                          tcg_ctx->gen_insn_data[insn][0]);
2054                 log_disas(tb->tc.ptr + chunk_start, chunk_end - chunk_start);
2055                 chunk_start = chunk_end;
2056             }
2057             insn++;
2058         }
2059 
2060         if (chunk_start < code_size) {
2061             qemu_log("  -- tb slow paths + alignment\n");
2062             log_disas(tb->tc.ptr + chunk_start, code_size - chunk_start);
2063         }
2064 
2065         /* Finally dump any data we may have after the block */
2066         if (data_size) {
2067             int i;
2068             qemu_log("  data: [size=%d]\n", data_size);
2069             for (i = 0; i < data_size / sizeof(tcg_target_ulong); i++) {
2070                 qemu_log("0x%08" PRIxPTR ":  .quad  0x%" TCG_PRIlx "\n",
2071                          (uintptr_t)&rx_data_gen_ptr[i], rx_data_gen_ptr[i]);
2072             }
2073         }
2074         qemu_log("\n");
2075         qemu_log_flush();
2076         qemu_log_unlock(logfile);
2077     }
2078 #endif
2079 
2080     qatomic_set(&tcg_ctx->code_gen_ptr, (void *)
2081         ROUND_UP((uintptr_t)gen_code_buf + gen_code_size + search_size,
2082                  CODE_GEN_ALIGN));
2083 
2084     /* init jump list */
2085     qemu_spin_init(&tb->jmp_lock);
2086     tb->jmp_list_head = (uintptr_t)NULL;
2087     tb->jmp_list_next[0] = (uintptr_t)NULL;
2088     tb->jmp_list_next[1] = (uintptr_t)NULL;
2089     tb->jmp_dest[0] = (uintptr_t)NULL;
2090     tb->jmp_dest[1] = (uintptr_t)NULL;
2091 
2092     /* init original jump addresses which have been set during tcg_gen_code() */
2093     if (tb->jmp_reset_offset[0] != TB_JMP_RESET_OFFSET_INVALID) {
2094         tb_reset_jump(tb, 0);
2095     }
2096     if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) {
2097         tb_reset_jump(tb, 1);
2098     }
2099 
2100     /* check next page if needed */
2101     virt_page2 = (pc + tb->size - 1) & TARGET_PAGE_MASK;
2102     phys_page2 = -1;
2103     if ((pc & TARGET_PAGE_MASK) != virt_page2) {
2104         phys_page2 = get_page_addr_code(env, virt_page2);
2105     }
2106     /*
2107      * No explicit memory barrier is required -- tb_link_page() makes the
2108      * TB visible in a consistent state.
2109      */
2110     existing_tb = tb_link_page(tb, phys_pc, phys_page2);
2111     /* if the TB already exists, discard what we just translated */
2112     if (unlikely(existing_tb != tb)) {
2113         uintptr_t orig_aligned = (uintptr_t)gen_code_buf;
2114 
2115         orig_aligned -= ROUND_UP(sizeof(*tb), qemu_icache_linesize);
2116         qatomic_set(&tcg_ctx->code_gen_ptr, (void *)orig_aligned);
2117         tb_destroy(tb);
2118         return existing_tb;
2119     }
2120     tcg_tb_insert(tb);
2121     return tb;
2122 }
2123 
2124 /*
2125  * @p must be non-NULL.
2126  * user-mode: call with mmap_lock held.
2127  * !user-mode: call with all @pages locked.
2128  */
2129 static void
2130 tb_invalidate_phys_page_range__locked(struct page_collection *pages,
2131                                       PageDesc *p, tb_page_addr_t start,
2132                                       tb_page_addr_t end,
2133                                       uintptr_t retaddr)
2134 {
2135     TranslationBlock *tb;
2136     tb_page_addr_t tb_start, tb_end;
2137     int n;
2138 #ifdef TARGET_HAS_PRECISE_SMC
2139     CPUState *cpu = current_cpu;
2140     CPUArchState *env = NULL;
2141     bool current_tb_not_found = retaddr != 0;
2142     bool current_tb_modified = false;
2143     TranslationBlock *current_tb = NULL;
2144     target_ulong current_pc = 0;
2145     target_ulong current_cs_base = 0;
2146     uint32_t current_flags = 0;
2147 #endif /* TARGET_HAS_PRECISE_SMC */
2148 
2149     assert_page_locked(p);
2150 
2151 #if defined(TARGET_HAS_PRECISE_SMC)
2152     if (cpu != NULL) {
2153         env = cpu->env_ptr;
2154     }
2155 #endif
2156 
2157     /* we remove all the TBs in the range [start, end[ */
2158     /* XXX: see if in some cases it could be faster to invalidate all
2159        the code */
2160     PAGE_FOR_EACH_TB(p, tb, n) {
2161         assert_page_locked(p);
2162         /* NOTE: this is subtle as a TB may span two physical pages */
2163         if (n == 0) {
2164             /* NOTE: tb_end may be after the end of the page, but
2165                it is not a problem */
2166             tb_start = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);
2167             tb_end = tb_start + tb->size;
2168         } else {
2169             tb_start = tb->page_addr[1];
2170             tb_end = tb_start + ((tb->pc + tb->size) & ~TARGET_PAGE_MASK);
2171         }
2172         if (!(tb_end <= start || tb_start >= end)) {
2173 #ifdef TARGET_HAS_PRECISE_SMC
2174             if (current_tb_not_found) {
2175                 current_tb_not_found = false;
2176                 /* now we have a real cpu fault */
2177                 current_tb = tcg_tb_lookup(retaddr);
2178             }
2179             if (current_tb == tb &&
2180                 (tb_cflags(current_tb) & CF_COUNT_MASK) != 1) {
2181                 /*
2182                  * If we are modifying the current TB, we must stop
2183                  * its execution. We could be more precise by checking
2184                  * that the modification is after the current PC, but it
2185                  * would require a specialized function to partially
2186                  * restore the CPU state.
2187                  */
2188                 current_tb_modified = true;
2189                 cpu_restore_state_from_tb(cpu, current_tb, retaddr, true);
2190                 cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base,
2191                                      &current_flags);
2192             }
2193 #endif /* TARGET_HAS_PRECISE_SMC */
2194             tb_phys_invalidate__locked(tb);
2195         }
2196     }
2197 #if !defined(CONFIG_USER_ONLY)
2198     /* if no code remaining, no need to continue to use slow writes */
2199     if (!p->first_tb) {
2200         invalidate_page_bitmap(p);
2201         tlb_unprotect_code(start);
2202     }
2203 #endif
2204 #ifdef TARGET_HAS_PRECISE_SMC
2205     if (current_tb_modified) {
2206         page_collection_unlock(pages);
2207         /* Force execution of one insn next time.  */
2208         cpu->cflags_next_tb = 1 | curr_cflags();
2209         mmap_unlock();
2210         cpu_loop_exit_noexc(cpu);
2211     }
2212 #endif
2213 }
2214 
2215 /*
2216  * Invalidate all TBs which intersect with the target physical address range
2217  * [start;end[. NOTE: start and end must refer to the *same* physical page.
2218  * 'is_cpu_write_access' should be true if called from a real cpu write
2219  * access: the virtual CPU will exit the current TB if code is modified inside
2220  * this TB.
2221  *
2222  * Called with mmap_lock held for user-mode emulation
2223  */
2224 void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end)
2225 {
2226     struct page_collection *pages;
2227     PageDesc *p;
2228 
2229     assert_memory_lock();
2230 
2231     p = page_find(start >> TARGET_PAGE_BITS);
2232     if (p == NULL) {
2233         return;
2234     }
2235     pages = page_collection_lock(start, end);
2236     tb_invalidate_phys_page_range__locked(pages, p, start, end, 0);
2237     page_collection_unlock(pages);
2238 }
2239 
2240 /*
2241  * Invalidate all TBs which intersect with the target physical address range
2242  * [start;end[. NOTE: start and end may refer to *different* physical pages.
2243  * 'is_cpu_write_access' should be true if called from a real cpu write
2244  * access: the virtual CPU will exit the current TB if code is modified inside
2245  * this TB.
2246  *
2247  * Called with mmap_lock held for user-mode emulation.
2248  */
2249 #ifdef CONFIG_SOFTMMU
2250 void tb_invalidate_phys_range(ram_addr_t start, ram_addr_t end)
2251 #else
2252 void tb_invalidate_phys_range(target_ulong start, target_ulong end)
2253 #endif
2254 {
2255     struct page_collection *pages;
2256     tb_page_addr_t next;
2257 
2258     assert_memory_lock();
2259 
2260     pages = page_collection_lock(start, end);
2261     for (next = (start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;
2262          start < end;
2263          start = next, next += TARGET_PAGE_SIZE) {
2264         PageDesc *pd = page_find(start >> TARGET_PAGE_BITS);
2265         tb_page_addr_t bound = MIN(next, end);
2266 
2267         if (pd == NULL) {
2268             continue;
2269         }
2270         tb_invalidate_phys_page_range__locked(pages, pd, start, bound, 0);
2271     }
2272     page_collection_unlock(pages);
2273 }
2274 
2275 #ifdef CONFIG_SOFTMMU
2276 /* len must be <= 8 and start must be a multiple of len.
2277  * Called via softmmu_template.h when code areas are written to with
2278  * iothread mutex not held.
2279  *
2280  * Call with all @pages in the range [@start, @start + len[ locked.
2281  */
2282 void tb_invalidate_phys_page_fast(struct page_collection *pages,
2283                                   tb_page_addr_t start, int len,
2284                                   uintptr_t retaddr)
2285 {
2286     PageDesc *p;
2287 
2288     assert_memory_lock();
2289 
2290     p = page_find(start >> TARGET_PAGE_BITS);
2291     if (!p) {
2292         return;
2293     }
2294 
2295     assert_page_locked(p);
2296     if (!p->code_bitmap &&
2297         ++p->code_write_count >= SMC_BITMAP_USE_THRESHOLD) {
2298         build_page_bitmap(p);
2299     }
2300     if (p->code_bitmap) {
2301         unsigned int nr;
2302         unsigned long b;
2303 
2304         nr = start & ~TARGET_PAGE_MASK;
2305         b = p->code_bitmap[BIT_WORD(nr)] >> (nr & (BITS_PER_LONG - 1));
2306         if (b & ((1 << len) - 1)) {
2307             goto do_invalidate;
2308         }
2309     } else {
2310     do_invalidate:
2311         tb_invalidate_phys_page_range__locked(pages, p, start, start + len,
2312                                               retaddr);
2313     }
2314 }
2315 #else
2316 /* Called with mmap_lock held. If pc is not 0 then it indicates the
2317  * host PC of the faulting store instruction that caused this invalidate.
2318  * Returns true if the caller needs to abort execution of the current
2319  * TB (because it was modified by this store and the guest CPU has
2320  * precise-SMC semantics).
2321  */
2322 static bool tb_invalidate_phys_page(tb_page_addr_t addr, uintptr_t pc)
2323 {
2324     TranslationBlock *tb;
2325     PageDesc *p;
2326     int n;
2327 #ifdef TARGET_HAS_PRECISE_SMC
2328     TranslationBlock *current_tb = NULL;
2329     CPUState *cpu = current_cpu;
2330     CPUArchState *env = NULL;
2331     int current_tb_modified = 0;
2332     target_ulong current_pc = 0;
2333     target_ulong current_cs_base = 0;
2334     uint32_t current_flags = 0;
2335 #endif
2336 
2337     assert_memory_lock();
2338 
2339     addr &= TARGET_PAGE_MASK;
2340     p = page_find(addr >> TARGET_PAGE_BITS);
2341     if (!p) {
2342         return false;
2343     }
2344 
2345 #ifdef TARGET_HAS_PRECISE_SMC
2346     if (p->first_tb && pc != 0) {
2347         current_tb = tcg_tb_lookup(pc);
2348     }
2349     if (cpu != NULL) {
2350         env = cpu->env_ptr;
2351     }
2352 #endif
2353     assert_page_locked(p);
2354     PAGE_FOR_EACH_TB(p, tb, n) {
2355 #ifdef TARGET_HAS_PRECISE_SMC
2356         if (current_tb == tb &&
2357             (tb_cflags(current_tb) & CF_COUNT_MASK) != 1) {
2358                 /* If we are modifying the current TB, we must stop
2359                    its execution. We could be more precise by checking
2360                    that the modification is after the current PC, but it
2361                    would require a specialized function to partially
2362                    restore the CPU state */
2363 
2364             current_tb_modified = 1;
2365             cpu_restore_state_from_tb(cpu, current_tb, pc, true);
2366             cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base,
2367                                  &current_flags);
2368         }
2369 #endif /* TARGET_HAS_PRECISE_SMC */
2370         tb_phys_invalidate(tb, addr);
2371     }
2372     p->first_tb = (uintptr_t)NULL;
2373 #ifdef TARGET_HAS_PRECISE_SMC
2374     if (current_tb_modified) {
2375         /* Force execution of one insn next time.  */
2376         cpu->cflags_next_tb = 1 | curr_cflags();
2377         return true;
2378     }
2379 #endif
2380 
2381     return false;
2382 }
2383 #endif
2384 
2385 /* user-mode: call with mmap_lock held */
2386 void tb_check_watchpoint(CPUState *cpu, uintptr_t retaddr)
2387 {
2388     TranslationBlock *tb;
2389 
2390     assert_memory_lock();
2391 
2392     tb = tcg_tb_lookup(retaddr);
2393     if (tb) {
2394         /* We can use retranslation to find the PC.  */
2395         cpu_restore_state_from_tb(cpu, tb, retaddr, true);
2396         tb_phys_invalidate(tb, -1);
2397     } else {
2398         /* The exception probably happened in a helper.  The CPU state should
2399            have been saved before calling it. Fetch the PC from there.  */
2400         CPUArchState *env = cpu->env_ptr;
2401         target_ulong pc, cs_base;
2402         tb_page_addr_t addr;
2403         uint32_t flags;
2404 
2405         cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags);
2406         addr = get_page_addr_code(env, pc);
2407         if (addr != -1) {
2408             tb_invalidate_phys_range(addr, addr + 1);
2409         }
2410     }
2411 }
2412 
2413 #ifndef CONFIG_USER_ONLY
2414 /* in deterministic execution mode, instructions doing device I/Os
2415  * must be at the end of the TB.
2416  *
2417  * Called by softmmu_template.h, with iothread mutex not held.
2418  */
2419 void cpu_io_recompile(CPUState *cpu, uintptr_t retaddr)
2420 {
2421 #if defined(TARGET_SH4)
2422     CPUArchState *env = cpu->env_ptr;
2423 #endif
2424     TranslationBlock *tb;
2425     CPUClass *cc;
2426     uint32_t n;
2427 
2428     tb = tcg_tb_lookup(retaddr);
2429     if (!tb) {
2430         cpu_abort(cpu, "cpu_io_recompile: could not find TB for pc=%p",
2431                   (void *)retaddr);
2432     }
2433     cpu_restore_state_from_tb(cpu, tb, retaddr, true);
2434 
2435     /*
2436      * Some guests must re-execute the branch when re-executing a delay
2437      * slot instruction.  When this is the case, adjust icount and N
2438      * to account for the re-execution of the branch.
2439      */
2440     n = 1;
2441     cc = CPU_GET_CLASS(cpu);
2442     if (cc->tcg_ops->io_recompile_replay_branch &&
2443         cc->tcg_ops->io_recompile_replay_branch(cpu, tb)) {
2444         cpu_neg(cpu)->icount_decr.u16.low++;
2445         n = 2;
2446     }
2447 #if defined(TARGET_SH4)
2448     if ((env->flags & ((DELAY_SLOT | DELAY_SLOT_CONDITIONAL))) != 0
2449         && env->pc != tb->pc) {
2450         env->pc -= 2;
2451         cpu_neg(cpu)->icount_decr.u16.low++;
2452         env->flags &= ~(DELAY_SLOT | DELAY_SLOT_CONDITIONAL);
2453         n = 2;
2454     }
2455 #endif
2456 
2457     /* Generate a new TB executing the I/O insn.  */
2458     cpu->cflags_next_tb = curr_cflags() | CF_LAST_IO | n;
2459 
2460     if (tb_cflags(tb) & CF_NOCACHE) {
2461         if (tb->orig_tb) {
2462             /* Invalidate original TB if this TB was generated in
2463              * cpu_exec_nocache() */
2464             tb_phys_invalidate(tb->orig_tb, -1);
2465         }
2466         tcg_tb_remove(tb);
2467         tb_destroy(tb);
2468     }
2469 
2470     qemu_log_mask_and_addr(CPU_LOG_EXEC, tb->pc,
2471                            "cpu_io_recompile: rewound execution of TB to "
2472                            TARGET_FMT_lx "\n", tb->pc);
2473 
2474     /* TODO: If env->pc != tb->pc (i.e. the faulting instruction was not
2475      * the first in the TB) then we end up generating a whole new TB and
2476      *  repeating the fault, which is horribly inefficient.
2477      *  Better would be to execute just this insn uncached, or generate a
2478      *  second new TB.
2479      */
2480     cpu_loop_exit_noexc(cpu);
2481 }
2482 
2483 static void print_qht_statistics(struct qht_stats hst)
2484 {
2485     uint32_t hgram_opts;
2486     size_t hgram_bins;
2487     char *hgram;
2488 
2489     if (!hst.head_buckets) {
2490         return;
2491     }
2492     qemu_printf("TB hash buckets     %zu/%zu (%0.2f%% head buckets used)\n",
2493                 hst.used_head_buckets, hst.head_buckets,
2494                 (double)hst.used_head_buckets / hst.head_buckets * 100);
2495 
2496     hgram_opts =  QDIST_PR_BORDER | QDIST_PR_LABELS;
2497     hgram_opts |= QDIST_PR_100X   | QDIST_PR_PERCENT;
2498     if (qdist_xmax(&hst.occupancy) - qdist_xmin(&hst.occupancy) == 1) {
2499         hgram_opts |= QDIST_PR_NODECIMAL;
2500     }
2501     hgram = qdist_pr(&hst.occupancy, 10, hgram_opts);
2502     qemu_printf("TB hash occupancy   %0.2f%% avg chain occ. Histogram: %s\n",
2503                 qdist_avg(&hst.occupancy) * 100, hgram);
2504     g_free(hgram);
2505 
2506     hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
2507     hgram_bins = qdist_xmax(&hst.chain) - qdist_xmin(&hst.chain);
2508     if (hgram_bins > 10) {
2509         hgram_bins = 10;
2510     } else {
2511         hgram_bins = 0;
2512         hgram_opts |= QDIST_PR_NODECIMAL | QDIST_PR_NOBINRANGE;
2513     }
2514     hgram = qdist_pr(&hst.chain, hgram_bins, hgram_opts);
2515     qemu_printf("TB hash avg chain   %0.3f buckets. Histogram: %s\n",
2516                 qdist_avg(&hst.chain), hgram);
2517     g_free(hgram);
2518 }
2519 
2520 struct tb_tree_stats {
2521     size_t nb_tbs;
2522     size_t host_size;
2523     size_t target_size;
2524     size_t max_target_size;
2525     size_t direct_jmp_count;
2526     size_t direct_jmp2_count;
2527     size_t cross_page;
2528 };
2529 
2530 static gboolean tb_tree_stats_iter(gpointer key, gpointer value, gpointer data)
2531 {
2532     const TranslationBlock *tb = value;
2533     struct tb_tree_stats *tst = data;
2534 
2535     tst->nb_tbs++;
2536     tst->host_size += tb->tc.size;
2537     tst->target_size += tb->size;
2538     if (tb->size > tst->max_target_size) {
2539         tst->max_target_size = tb->size;
2540     }
2541     if (tb->page_addr[1] != -1) {
2542         tst->cross_page++;
2543     }
2544     if (tb->jmp_reset_offset[0] != TB_JMP_RESET_OFFSET_INVALID) {
2545         tst->direct_jmp_count++;
2546         if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) {
2547             tst->direct_jmp2_count++;
2548         }
2549     }
2550     return false;
2551 }
2552 
2553 void dump_exec_info(void)
2554 {
2555     struct tb_tree_stats tst = {};
2556     struct qht_stats hst;
2557     size_t nb_tbs, flush_full, flush_part, flush_elide;
2558 
2559     tcg_tb_foreach(tb_tree_stats_iter, &tst);
2560     nb_tbs = tst.nb_tbs;
2561     /* XXX: avoid using doubles ? */
2562     qemu_printf("Translation buffer state:\n");
2563     /*
2564      * Report total code size including the padding and TB structs;
2565      * otherwise users might think "-accel tcg,tb-size" is not honoured.
2566      * For avg host size we use the precise numbers from tb_tree_stats though.
2567      */
2568     qemu_printf("gen code size       %zu/%zu\n",
2569                 tcg_code_size(), tcg_code_capacity());
2570     qemu_printf("TB count            %zu\n", nb_tbs);
2571     qemu_printf("TB avg target size  %zu max=%zu bytes\n",
2572                 nb_tbs ? tst.target_size / nb_tbs : 0,
2573                 tst.max_target_size);
2574     qemu_printf("TB avg host size    %zu bytes (expansion ratio: %0.1f)\n",
2575                 nb_tbs ? tst.host_size / nb_tbs : 0,
2576                 tst.target_size ? (double)tst.host_size / tst.target_size : 0);
2577     qemu_printf("cross page TB count %zu (%zu%%)\n", tst.cross_page,
2578                 nb_tbs ? (tst.cross_page * 100) / nb_tbs : 0);
2579     qemu_printf("direct jump count   %zu (%zu%%) (2 jumps=%zu %zu%%)\n",
2580                 tst.direct_jmp_count,
2581                 nb_tbs ? (tst.direct_jmp_count * 100) / nb_tbs : 0,
2582                 tst.direct_jmp2_count,
2583                 nb_tbs ? (tst.direct_jmp2_count * 100) / nb_tbs : 0);
2584 
2585     qht_statistics_init(&tb_ctx.htable, &hst);
2586     print_qht_statistics(hst);
2587     qht_statistics_destroy(&hst);
2588 
2589     qemu_printf("\nStatistics:\n");
2590     qemu_printf("TB flush count      %u\n",
2591                 qatomic_read(&tb_ctx.tb_flush_count));
2592     qemu_printf("TB invalidate count %zu\n",
2593                 tcg_tb_phys_invalidate_count());
2594 
2595     tlb_flush_counts(&flush_full, &flush_part, &flush_elide);
2596     qemu_printf("TLB full flushes    %zu\n", flush_full);
2597     qemu_printf("TLB partial flushes %zu\n", flush_part);
2598     qemu_printf("TLB elided flushes  %zu\n", flush_elide);
2599     tcg_dump_info();
2600 }
2601 
2602 void dump_opcount_info(void)
2603 {
2604     tcg_dump_op_count();
2605 }
2606 
2607 #else /* CONFIG_USER_ONLY */
2608 
2609 void cpu_interrupt(CPUState *cpu, int mask)
2610 {
2611     g_assert(qemu_mutex_iothread_locked());
2612     cpu->interrupt_request |= mask;
2613     qatomic_set(&cpu_neg(cpu)->icount_decr.u16.high, -1);
2614 }
2615 
2616 /*
2617  * Walks guest process memory "regions" one by one
2618  * and calls callback function 'fn' for each region.
2619  */
2620 struct walk_memory_regions_data {
2621     walk_memory_regions_fn fn;
2622     void *priv;
2623     target_ulong start;
2624     int prot;
2625 };
2626 
2627 static int walk_memory_regions_end(struct walk_memory_regions_data *data,
2628                                    target_ulong end, int new_prot)
2629 {
2630     if (data->start != -1u) {
2631         int rc = data->fn(data->priv, data->start, end, data->prot);
2632         if (rc != 0) {
2633             return rc;
2634         }
2635     }
2636 
2637     data->start = (new_prot ? end : -1u);
2638     data->prot = new_prot;
2639 
2640     return 0;
2641 }
2642 
2643 static int walk_memory_regions_1(struct walk_memory_regions_data *data,
2644                                  target_ulong base, int level, void **lp)
2645 {
2646     target_ulong pa;
2647     int i, rc;
2648 
2649     if (*lp == NULL) {
2650         return walk_memory_regions_end(data, base, 0);
2651     }
2652 
2653     if (level == 0) {
2654         PageDesc *pd = *lp;
2655 
2656         for (i = 0; i < V_L2_SIZE; ++i) {
2657             int prot = pd[i].flags;
2658 
2659             pa = base | (i << TARGET_PAGE_BITS);
2660             if (prot != data->prot) {
2661                 rc = walk_memory_regions_end(data, pa, prot);
2662                 if (rc != 0) {
2663                     return rc;
2664                 }
2665             }
2666         }
2667     } else {
2668         void **pp = *lp;
2669 
2670         for (i = 0; i < V_L2_SIZE; ++i) {
2671             pa = base | ((target_ulong)i <<
2672                 (TARGET_PAGE_BITS + V_L2_BITS * level));
2673             rc = walk_memory_regions_1(data, pa, level - 1, pp + i);
2674             if (rc != 0) {
2675                 return rc;
2676             }
2677         }
2678     }
2679 
2680     return 0;
2681 }
2682 
2683 int walk_memory_regions(void *priv, walk_memory_regions_fn fn)
2684 {
2685     struct walk_memory_regions_data data;
2686     uintptr_t i, l1_sz = v_l1_size;
2687 
2688     data.fn = fn;
2689     data.priv = priv;
2690     data.start = -1u;
2691     data.prot = 0;
2692 
2693     for (i = 0; i < l1_sz; i++) {
2694         target_ulong base = i << (v_l1_shift + TARGET_PAGE_BITS);
2695         int rc = walk_memory_regions_1(&data, base, v_l2_levels, l1_map + i);
2696         if (rc != 0) {
2697             return rc;
2698         }
2699     }
2700 
2701     return walk_memory_regions_end(&data, 0, 0);
2702 }
2703 
2704 static int dump_region(void *priv, target_ulong start,
2705     target_ulong end, unsigned long prot)
2706 {
2707     FILE *f = (FILE *)priv;
2708 
2709     (void) fprintf(f, TARGET_FMT_lx"-"TARGET_FMT_lx
2710         " "TARGET_FMT_lx" %c%c%c\n",
2711         start, end, end - start,
2712         ((prot & PAGE_READ) ? 'r' : '-'),
2713         ((prot & PAGE_WRITE) ? 'w' : '-'),
2714         ((prot & PAGE_EXEC) ? 'x' : '-'));
2715 
2716     return 0;
2717 }
2718 
2719 /* dump memory mappings */
2720 void page_dump(FILE *f)
2721 {
2722     const int length = sizeof(target_ulong) * 2;
2723     (void) fprintf(f, "%-*s %-*s %-*s %s\n",
2724             length, "start", length, "end", length, "size", "prot");
2725     walk_memory_regions(f, dump_region);
2726 }
2727 
2728 int page_get_flags(target_ulong address)
2729 {
2730     PageDesc *p;
2731 
2732     p = page_find(address >> TARGET_PAGE_BITS);
2733     if (!p) {
2734         return 0;
2735     }
2736     return p->flags;
2737 }
2738 
2739 /* Modify the flags of a page and invalidate the code if necessary.
2740    The flag PAGE_WRITE_ORG is positioned automatically depending
2741    on PAGE_WRITE.  The mmap_lock should already be held.  */
2742 void page_set_flags(target_ulong start, target_ulong end, int flags)
2743 {
2744     target_ulong addr, len;
2745     bool reset_target_data;
2746 
2747     /* This function should never be called with addresses outside the
2748        guest address space.  If this assert fires, it probably indicates
2749        a missing call to h2g_valid.  */
2750     assert(end - 1 <= GUEST_ADDR_MAX);
2751     assert(start < end);
2752     assert_memory_lock();
2753 
2754     start = start & TARGET_PAGE_MASK;
2755     end = TARGET_PAGE_ALIGN(end);
2756 
2757     if (flags & PAGE_WRITE) {
2758         flags |= PAGE_WRITE_ORG;
2759     }
2760     reset_target_data = !(flags & PAGE_VALID) || (flags & PAGE_RESET);
2761     flags &= ~PAGE_RESET;
2762 
2763     for (addr = start, len = end - start;
2764          len != 0;
2765          len -= TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {
2766         PageDesc *p = page_find_alloc(addr >> TARGET_PAGE_BITS, 1);
2767 
2768         /* If the write protection bit is set, then we invalidate
2769            the code inside.  */
2770         if (!(p->flags & PAGE_WRITE) &&
2771             (flags & PAGE_WRITE) &&
2772             p->first_tb) {
2773             tb_invalidate_phys_page(addr, 0);
2774         }
2775         if (reset_target_data && p->target_data) {
2776             g_free(p->target_data);
2777             p->target_data = NULL;
2778         }
2779         p->flags = flags;
2780     }
2781 }
2782 
2783 void *page_get_target_data(target_ulong address)
2784 {
2785     PageDesc *p = page_find(address >> TARGET_PAGE_BITS);
2786     return p ? p->target_data : NULL;
2787 }
2788 
2789 void *page_alloc_target_data(target_ulong address, size_t size)
2790 {
2791     PageDesc *p = page_find(address >> TARGET_PAGE_BITS);
2792     void *ret = NULL;
2793 
2794     if (p->flags & PAGE_VALID) {
2795         ret = p->target_data;
2796         if (!ret) {
2797             p->target_data = ret = g_malloc0(size);
2798         }
2799     }
2800     return ret;
2801 }
2802 
2803 int page_check_range(target_ulong start, target_ulong len, int flags)
2804 {
2805     PageDesc *p;
2806     target_ulong end;
2807     target_ulong addr;
2808 
2809     /* This function should never be called with addresses outside the
2810        guest address space.  If this assert fires, it probably indicates
2811        a missing call to h2g_valid.  */
2812     if (TARGET_ABI_BITS > L1_MAP_ADDR_SPACE_BITS) {
2813         assert(start < ((target_ulong)1 << L1_MAP_ADDR_SPACE_BITS));
2814     }
2815 
2816     if (len == 0) {
2817         return 0;
2818     }
2819     if (start + len - 1 < start) {
2820         /* We've wrapped around.  */
2821         return -1;
2822     }
2823 
2824     /* must do before we loose bits in the next step */
2825     end = TARGET_PAGE_ALIGN(start + len);
2826     start = start & TARGET_PAGE_MASK;
2827 
2828     for (addr = start, len = end - start;
2829          len != 0;
2830          len -= TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {
2831         p = page_find(addr >> TARGET_PAGE_BITS);
2832         if (!p) {
2833             return -1;
2834         }
2835         if (!(p->flags & PAGE_VALID)) {
2836             return -1;
2837         }
2838 
2839         if ((flags & PAGE_READ) && !(p->flags & PAGE_READ)) {
2840             return -1;
2841         }
2842         if (flags & PAGE_WRITE) {
2843             if (!(p->flags & PAGE_WRITE_ORG)) {
2844                 return -1;
2845             }
2846             /* unprotect the page if it was put read-only because it
2847                contains translated code */
2848             if (!(p->flags & PAGE_WRITE)) {
2849                 if (!page_unprotect(addr, 0)) {
2850                     return -1;
2851                 }
2852             }
2853         }
2854     }
2855     return 0;
2856 }
2857 
2858 /* called from signal handler: invalidate the code and unprotect the
2859  * page. Return 0 if the fault was not handled, 1 if it was handled,
2860  * and 2 if it was handled but the caller must cause the TB to be
2861  * immediately exited. (We can only return 2 if the 'pc' argument is
2862  * non-zero.)
2863  */
2864 int page_unprotect(target_ulong address, uintptr_t pc)
2865 {
2866     unsigned int prot;
2867     bool current_tb_invalidated;
2868     PageDesc *p;
2869     target_ulong host_start, host_end, addr;
2870 
2871     /* Technically this isn't safe inside a signal handler.  However we
2872        know this only ever happens in a synchronous SEGV handler, so in
2873        practice it seems to be ok.  */
2874     mmap_lock();
2875 
2876     p = page_find(address >> TARGET_PAGE_BITS);
2877     if (!p) {
2878         mmap_unlock();
2879         return 0;
2880     }
2881 
2882     /* if the page was really writable, then we change its
2883        protection back to writable */
2884     if (p->flags & PAGE_WRITE_ORG) {
2885         current_tb_invalidated = false;
2886         if (p->flags & PAGE_WRITE) {
2887             /* If the page is actually marked WRITE then assume this is because
2888              * this thread raced with another one which got here first and
2889              * set the page to PAGE_WRITE and did the TB invalidate for us.
2890              */
2891 #ifdef TARGET_HAS_PRECISE_SMC
2892             TranslationBlock *current_tb = tcg_tb_lookup(pc);
2893             if (current_tb) {
2894                 current_tb_invalidated = tb_cflags(current_tb) & CF_INVALID;
2895             }
2896 #endif
2897         } else {
2898             host_start = address & qemu_host_page_mask;
2899             host_end = host_start + qemu_host_page_size;
2900 
2901             prot = 0;
2902             for (addr = host_start; addr < host_end; addr += TARGET_PAGE_SIZE) {
2903                 p = page_find(addr >> TARGET_PAGE_BITS);
2904                 p->flags |= PAGE_WRITE;
2905                 prot |= p->flags;
2906 
2907                 /* and since the content will be modified, we must invalidate
2908                    the corresponding translated code. */
2909                 current_tb_invalidated |= tb_invalidate_phys_page(addr, pc);
2910 #ifdef CONFIG_USER_ONLY
2911                 if (DEBUG_TB_CHECK_GATE) {
2912                     tb_invalidate_check(addr);
2913                 }
2914 #endif
2915             }
2916             mprotect((void *)g2h_untagged(host_start), qemu_host_page_size,
2917                      prot & PAGE_BITS);
2918         }
2919         mmap_unlock();
2920         /* If current TB was invalidated return to main loop */
2921         return current_tb_invalidated ? 2 : 1;
2922     }
2923     mmap_unlock();
2924     return 0;
2925 }
2926 #endif /* CONFIG_USER_ONLY */
2927 
2928 /* This is a wrapper for common code that can not use CONFIG_SOFTMMU */
2929 void tcg_flush_softmmu_tlb(CPUState *cs)
2930 {
2931 #ifdef CONFIG_SOFTMMU
2932     tlb_flush(cs);
2933 #endif
2934 }
2935