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