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