target/sh4: Create superh_io_recompile_replay_branch
[qemu/kevin.git] / accel / tcg / translate-all.c
blobc0b98e76b9ddd455258250fd4fd49b69779f4ea7
1 /*
2 * Host code generation
4 * Copyright (c) 2003 Fabrice Bellard
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.
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.
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/>.
20 #include "qemu/osdep.h"
21 #include "qemu/units.h"
22 #include "qemu-common.h"
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
50 #include "exec/cputlb.h"
51 #include "exec/tb-hash.h"
52 #include "exec/translate-all.h"
53 #include "qemu/bitmap.h"
54 #include "qemu/error-report.h"
55 #include "qemu/qemu-print.h"
56 #include "qemu/timer.h"
57 #include "qemu/main-loop.h"
58 #include "exec/log.h"
59 #include "sysemu/cpus.h"
60 #include "sysemu/cpu-timers.h"
61 #include "sysemu/tcg.h"
62 #include "qapi/error.h"
63 #include "hw/core/tcg-cpu-ops.h"
64 #include "internal.h"
66 /* #define DEBUG_TB_INVALIDATE */
67 /* #define DEBUG_TB_FLUSH */
68 /* make various TB consistency checks */
69 /* #define DEBUG_TB_CHECK */
71 #ifdef DEBUG_TB_INVALIDATE
72 #define DEBUG_TB_INVALIDATE_GATE 1
73 #else
74 #define DEBUG_TB_INVALIDATE_GATE 0
75 #endif
77 #ifdef DEBUG_TB_FLUSH
78 #define DEBUG_TB_FLUSH_GATE 1
79 #else
80 #define DEBUG_TB_FLUSH_GATE 0
81 #endif
83 #if !defined(CONFIG_USER_ONLY)
84 /* TB consistency checks only implemented for usermode emulation. */
85 #undef DEBUG_TB_CHECK
86 #endif
88 #ifdef DEBUG_TB_CHECK
89 #define DEBUG_TB_CHECK_GATE 1
90 #else
91 #define DEBUG_TB_CHECK_GATE 0
92 #endif
94 /* Access to the various translations structures need to be serialised via locks
95 * for consistency.
96 * In user-mode emulation access to the memory related structures are protected
97 * with mmap_lock.
98 * In !user-mode we use per-page locks.
100 #ifdef CONFIG_SOFTMMU
101 #define assert_memory_lock()
102 #else
103 #define assert_memory_lock() tcg_debug_assert(have_mmap_lock())
104 #endif
106 #define SMC_BITMAP_USE_THRESHOLD 10
108 typedef struct PageDesc {
109 /* list of TBs intersecting this ram page */
110 uintptr_t first_tb;
111 #ifdef CONFIG_SOFTMMU
112 /* in order to optimize self modifying code, we count the number
113 of lookups we do to a given page to use a bitmap */
114 unsigned long *code_bitmap;
115 unsigned int code_write_count;
116 #else
117 unsigned long flags;
118 void *target_data;
119 #endif
120 #ifndef CONFIG_USER_ONLY
121 QemuSpin lock;
122 #endif
123 } PageDesc;
126 * struct page_entry - page descriptor entry
127 * @pd: pointer to the &struct PageDesc of the page this entry represents
128 * @index: page index of the page
129 * @locked: whether the page is locked
131 * This struct helps us keep track of the locked state of a page, without
132 * bloating &struct PageDesc.
134 * A page lock protects accesses to all fields of &struct PageDesc.
136 * See also: &struct page_collection.
138 struct page_entry {
139 PageDesc *pd;
140 tb_page_addr_t index;
141 bool locked;
145 * struct page_collection - tracks a set of pages (i.e. &struct page_entry's)
146 * @tree: Binary search tree (BST) of the pages, with key == page index
147 * @max: Pointer to the page in @tree with the highest page index
149 * To avoid deadlock we lock pages in ascending order of page index.
150 * When operating on a set of pages, we need to keep track of them so that
151 * we can lock them in order and also unlock them later. For this we collect
152 * pages (i.e. &struct page_entry's) in a binary search @tree. Given that the
153 * @tree implementation we use does not provide an O(1) operation to obtain the
154 * highest-ranked element, we use @max to keep track of the inserted page
155 * with the highest index. This is valuable because if a page is not in
156 * the tree and its index is higher than @max's, then we can lock it
157 * without breaking the locking order rule.
159 * Note on naming: 'struct page_set' would be shorter, but we already have a few
160 * page_set_*() helpers, so page_collection is used instead to avoid confusion.
162 * See also: page_collection_lock().
164 struct page_collection {
165 GTree *tree;
166 struct page_entry *max;
169 /* list iterators for lists of tagged pointers in TranslationBlock */
170 #define TB_FOR_EACH_TAGGED(head, tb, n, field) \
171 for (n = (head) & 1, tb = (TranslationBlock *)((head) & ~1); \
172 tb; tb = (TranslationBlock *)tb->field[n], n = (uintptr_t)tb & 1, \
173 tb = (TranslationBlock *)((uintptr_t)tb & ~1))
175 #define PAGE_FOR_EACH_TB(pagedesc, tb, n) \
176 TB_FOR_EACH_TAGGED((pagedesc)->first_tb, tb, n, page_next)
178 #define TB_FOR_EACH_JMP(head_tb, tb, n) \
179 TB_FOR_EACH_TAGGED((head_tb)->jmp_list_head, tb, n, jmp_list_next)
182 * In system mode we want L1_MAP to be based on ram offsets,
183 * while in user mode we want it to be based on virtual addresses.
185 * TODO: For user mode, see the caveat re host vs guest virtual
186 * address spaces near GUEST_ADDR_MAX.
188 #if !defined(CONFIG_USER_ONLY)
189 #if HOST_LONG_BITS < TARGET_PHYS_ADDR_SPACE_BITS
190 # define L1_MAP_ADDR_SPACE_BITS HOST_LONG_BITS
191 #else
192 # define L1_MAP_ADDR_SPACE_BITS TARGET_PHYS_ADDR_SPACE_BITS
193 #endif
194 #else
195 # define L1_MAP_ADDR_SPACE_BITS MIN(HOST_LONG_BITS, TARGET_ABI_BITS)
196 #endif
198 /* Size of the L2 (and L3, etc) page tables. */
199 #define V_L2_BITS 10
200 #define V_L2_SIZE (1 << V_L2_BITS)
202 /* Make sure all possible CPU event bits fit in tb->trace_vcpu_dstate */
203 QEMU_BUILD_BUG_ON(CPU_TRACE_DSTATE_MAX_EVENTS >
204 sizeof_field(TranslationBlock, trace_vcpu_dstate)
205 * BITS_PER_BYTE);
208 * L1 Mapping properties
210 static int v_l1_size;
211 static int v_l1_shift;
212 static int v_l2_levels;
214 /* The bottom level has pointers to PageDesc, and is indexed by
215 * anything from 4 to (V_L2_BITS + 3) bits, depending on target page size.
217 #define V_L1_MIN_BITS 4
218 #define V_L1_MAX_BITS (V_L2_BITS + 3)
219 #define V_L1_MAX_SIZE (1 << V_L1_MAX_BITS)
221 static void *l1_map[V_L1_MAX_SIZE];
223 /* code generation context */
224 TCGContext tcg_init_ctx;
225 __thread TCGContext *tcg_ctx;
226 TBContext tb_ctx;
227 bool parallel_cpus;
229 static void page_table_config_init(void)
231 uint32_t v_l1_bits;
233 assert(TARGET_PAGE_BITS);
234 /* The bits remaining after N lower levels of page tables. */
235 v_l1_bits = (L1_MAP_ADDR_SPACE_BITS - TARGET_PAGE_BITS) % V_L2_BITS;
236 if (v_l1_bits < V_L1_MIN_BITS) {
237 v_l1_bits += V_L2_BITS;
240 v_l1_size = 1 << v_l1_bits;
241 v_l1_shift = L1_MAP_ADDR_SPACE_BITS - TARGET_PAGE_BITS - v_l1_bits;
242 v_l2_levels = v_l1_shift / V_L2_BITS - 1;
244 assert(v_l1_bits <= V_L1_MAX_BITS);
245 assert(v_l1_shift % V_L2_BITS == 0);
246 assert(v_l2_levels >= 0);
249 static void cpu_gen_init(void)
251 tcg_context_init(&tcg_init_ctx);
254 /* Encode VAL as a signed leb128 sequence at P.
255 Return P incremented past the encoded value. */
256 static uint8_t *encode_sleb128(uint8_t *p, target_long val)
258 int more, byte;
260 do {
261 byte = val & 0x7f;
262 val >>= 7;
263 more = !((val == 0 && (byte & 0x40) == 0)
264 || (val == -1 && (byte & 0x40) != 0));
265 if (more) {
266 byte |= 0x80;
268 *p++ = byte;
269 } while (more);
271 return p;
274 /* Decode a signed leb128 sequence at *PP; increment *PP past the
275 decoded value. Return the decoded value. */
276 static target_long decode_sleb128(const uint8_t **pp)
278 const uint8_t *p = *pp;
279 target_long val = 0;
280 int byte, shift = 0;
282 do {
283 byte = *p++;
284 val |= (target_ulong)(byte & 0x7f) << shift;
285 shift += 7;
286 } while (byte & 0x80);
287 if (shift < TARGET_LONG_BITS && (byte & 0x40)) {
288 val |= -(target_ulong)1 << shift;
291 *pp = p;
292 return val;
295 /* Encode the data collected about the instructions while compiling TB.
296 Place the data at BLOCK, and return the number of bytes consumed.
298 The logical table consists of TARGET_INSN_START_WORDS target_ulong's,
299 which come from the target's insn_start data, followed by a uintptr_t
300 which comes from the host pc of the end of the code implementing the insn.
302 Each line of the table is encoded as sleb128 deltas from the previous
303 line. The seed for the first line is { tb->pc, 0..., tb->tc.ptr }.
304 That is, the first column is seeded with the guest pc, the last column
305 with the host pc, and the middle columns with zeros. */
307 static int encode_search(TranslationBlock *tb, uint8_t *block)
309 uint8_t *highwater = tcg_ctx->code_gen_highwater;
310 uint8_t *p = block;
311 int i, j, n;
313 for (i = 0, n = tb->icount; i < n; ++i) {
314 target_ulong prev;
316 for (j = 0; j < TARGET_INSN_START_WORDS; ++j) {
317 if (i == 0) {
318 prev = (j == 0 ? tb->pc : 0);
319 } else {
320 prev = tcg_ctx->gen_insn_data[i - 1][j];
322 p = encode_sleb128(p, tcg_ctx->gen_insn_data[i][j] - prev);
324 prev = (i == 0 ? 0 : tcg_ctx->gen_insn_end_off[i - 1]);
325 p = encode_sleb128(p, tcg_ctx->gen_insn_end_off[i] - prev);
327 /* Test for (pending) buffer overflow. The assumption is that any
328 one row beginning below the high water mark cannot overrun
329 the buffer completely. Thus we can test for overflow after
330 encoding a row without having to check during encoding. */
331 if (unlikely(p > highwater)) {
332 return -1;
336 return p - block;
339 /* The cpu state corresponding to 'searched_pc' is restored.
340 * When reset_icount is true, current TB will be interrupted and
341 * icount should be recalculated.
343 static int cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,
344 uintptr_t searched_pc, bool reset_icount)
346 target_ulong data[TARGET_INSN_START_WORDS] = { tb->pc };
347 uintptr_t host_pc = (uintptr_t)tb->tc.ptr;
348 CPUArchState *env = cpu->env_ptr;
349 const uint8_t *p = tb->tc.ptr + tb->tc.size;
350 int i, j, num_insns = tb->icount;
351 #ifdef CONFIG_PROFILER
352 TCGProfile *prof = &tcg_ctx->prof;
353 int64_t ti = profile_getclock();
354 #endif
356 searched_pc -= GETPC_ADJ;
358 if (searched_pc < host_pc) {
359 return -1;
362 /* Reconstruct the stored insn data while looking for the point at
363 which the end of the insn exceeds the searched_pc. */
364 for (i = 0; i < num_insns; ++i) {
365 for (j = 0; j < TARGET_INSN_START_WORDS; ++j) {
366 data[j] += decode_sleb128(&p);
368 host_pc += decode_sleb128(&p);
369 if (host_pc > searched_pc) {
370 goto found;
373 return -1;
375 found:
376 if (reset_icount && (tb_cflags(tb) & CF_USE_ICOUNT)) {
377 assert(icount_enabled());
378 /* Reset the cycle counter to the start of the block
379 and shift if to the number of actually executed instructions */
380 cpu_neg(cpu)->icount_decr.u16.low += num_insns - i;
382 restore_state_to_opc(env, tb, data);
384 #ifdef CONFIG_PROFILER
385 qatomic_set(&prof->restore_time,
386 prof->restore_time + profile_getclock() - ti);
387 qatomic_set(&prof->restore_count, prof->restore_count + 1);
388 #endif
389 return 0;
392 void tb_destroy(TranslationBlock *tb)
394 qemu_spin_destroy(&tb->jmp_lock);
397 bool cpu_restore_state(CPUState *cpu, uintptr_t host_pc, bool will_exit)
400 * The host_pc has to be in the rx region of the code buffer.
401 * If it is not we will not be able to resolve it here.
402 * The two cases where host_pc will not be correct are:
404 * - fault during translation (instruction fetch)
405 * - fault from helper (not using GETPC() macro)
407 * Either way we need return early as we can't resolve it here.
409 if (in_code_gen_buffer((const void *)(host_pc - tcg_splitwx_diff))) {
410 TranslationBlock *tb = tcg_tb_lookup(host_pc);
411 if (tb) {
412 cpu_restore_state_from_tb(cpu, tb, host_pc, will_exit);
413 if (tb_cflags(tb) & CF_NOCACHE) {
414 /* one-shot translation, invalidate it immediately */
415 tb_phys_invalidate(tb, -1);
416 tcg_tb_remove(tb);
417 tb_destroy(tb);
419 return true;
422 return false;
425 static void page_init(void)
427 page_size_init();
428 page_table_config_init();
430 #if defined(CONFIG_BSD) && defined(CONFIG_USER_ONLY)
432 #ifdef HAVE_KINFO_GETVMMAP
433 struct kinfo_vmentry *freep;
434 int i, cnt;
436 freep = kinfo_getvmmap(getpid(), &cnt);
437 if (freep) {
438 mmap_lock();
439 for (i = 0; i < cnt; i++) {
440 unsigned long startaddr, endaddr;
442 startaddr = freep[i].kve_start;
443 endaddr = freep[i].kve_end;
444 if (h2g_valid(startaddr)) {
445 startaddr = h2g(startaddr) & TARGET_PAGE_MASK;
447 if (h2g_valid(endaddr)) {
448 endaddr = h2g(endaddr);
449 page_set_flags(startaddr, endaddr, PAGE_RESERVED);
450 } else {
451 #if TARGET_ABI_BITS <= L1_MAP_ADDR_SPACE_BITS
452 endaddr = ~0ul;
453 page_set_flags(startaddr, endaddr, PAGE_RESERVED);
454 #endif
458 free(freep);
459 mmap_unlock();
461 #else
462 FILE *f;
464 last_brk = (unsigned long)sbrk(0);
466 f = fopen("/compat/linux/proc/self/maps", "r");
467 if (f) {
468 mmap_lock();
470 do {
471 unsigned long startaddr, endaddr;
472 int n;
474 n = fscanf(f, "%lx-%lx %*[^\n]\n", &startaddr, &endaddr);
476 if (n == 2 && h2g_valid(startaddr)) {
477 startaddr = h2g(startaddr) & TARGET_PAGE_MASK;
479 if (h2g_valid(endaddr)) {
480 endaddr = h2g(endaddr);
481 } else {
482 endaddr = ~0ul;
484 page_set_flags(startaddr, endaddr, PAGE_RESERVED);
486 } while (!feof(f));
488 fclose(f);
489 mmap_unlock();
491 #endif
493 #endif
496 static PageDesc *page_find_alloc(tb_page_addr_t index, int alloc)
498 PageDesc *pd;
499 void **lp;
500 int i;
502 /* Level 1. Always allocated. */
503 lp = l1_map + ((index >> v_l1_shift) & (v_l1_size - 1));
505 /* Level 2..N-1. */
506 for (i = v_l2_levels; i > 0; i--) {
507 void **p = qatomic_rcu_read(lp);
509 if (p == NULL) {
510 void *existing;
512 if (!alloc) {
513 return NULL;
515 p = g_new0(void *, V_L2_SIZE);
516 existing = qatomic_cmpxchg(lp, NULL, p);
517 if (unlikely(existing)) {
518 g_free(p);
519 p = existing;
523 lp = p + ((index >> (i * V_L2_BITS)) & (V_L2_SIZE - 1));
526 pd = qatomic_rcu_read(lp);
527 if (pd == NULL) {
528 void *existing;
530 if (!alloc) {
531 return NULL;
533 pd = g_new0(PageDesc, V_L2_SIZE);
534 #ifndef CONFIG_USER_ONLY
536 int i;
538 for (i = 0; i < V_L2_SIZE; i++) {
539 qemu_spin_init(&pd[i].lock);
542 #endif
543 existing = qatomic_cmpxchg(lp, NULL, pd);
544 if (unlikely(existing)) {
545 #ifndef CONFIG_USER_ONLY
547 int i;
549 for (i = 0; i < V_L2_SIZE; i++) {
550 qemu_spin_destroy(&pd[i].lock);
553 #endif
554 g_free(pd);
555 pd = existing;
559 return pd + (index & (V_L2_SIZE - 1));
562 static inline PageDesc *page_find(tb_page_addr_t index)
564 return page_find_alloc(index, 0);
567 static void page_lock_pair(PageDesc **ret_p1, tb_page_addr_t phys1,
568 PageDesc **ret_p2, tb_page_addr_t phys2, int alloc);
570 /* In user-mode page locks aren't used; mmap_lock is enough */
571 #ifdef CONFIG_USER_ONLY
573 #define assert_page_locked(pd) tcg_debug_assert(have_mmap_lock())
575 static inline void page_lock(PageDesc *pd)
578 static inline void page_unlock(PageDesc *pd)
581 static inline void page_lock_tb(const TranslationBlock *tb)
584 static inline void page_unlock_tb(const TranslationBlock *tb)
587 struct page_collection *
588 page_collection_lock(tb_page_addr_t start, tb_page_addr_t end)
590 return NULL;
593 void page_collection_unlock(struct page_collection *set)
595 #else /* !CONFIG_USER_ONLY */
597 #ifdef CONFIG_DEBUG_TCG
599 static __thread GHashTable *ht_pages_locked_debug;
601 static void ht_pages_locked_debug_init(void)
603 if (ht_pages_locked_debug) {
604 return;
606 ht_pages_locked_debug = g_hash_table_new(NULL, NULL);
609 static bool page_is_locked(const PageDesc *pd)
611 PageDesc *found;
613 ht_pages_locked_debug_init();
614 found = g_hash_table_lookup(ht_pages_locked_debug, pd);
615 return !!found;
618 static void page_lock__debug(PageDesc *pd)
620 ht_pages_locked_debug_init();
621 g_assert(!page_is_locked(pd));
622 g_hash_table_insert(ht_pages_locked_debug, pd, pd);
625 static void page_unlock__debug(const PageDesc *pd)
627 bool removed;
629 ht_pages_locked_debug_init();
630 g_assert(page_is_locked(pd));
631 removed = g_hash_table_remove(ht_pages_locked_debug, pd);
632 g_assert(removed);
635 static void
636 do_assert_page_locked(const PageDesc *pd, const char *file, int line)
638 if (unlikely(!page_is_locked(pd))) {
639 error_report("assert_page_lock: PageDesc %p not locked @ %s:%d",
640 pd, file, line);
641 abort();
645 #define assert_page_locked(pd) do_assert_page_locked(pd, __FILE__, __LINE__)
647 void assert_no_pages_locked(void)
649 ht_pages_locked_debug_init();
650 g_assert(g_hash_table_size(ht_pages_locked_debug) == 0);
653 #else /* !CONFIG_DEBUG_TCG */
655 #define assert_page_locked(pd)
657 static inline void page_lock__debug(const PageDesc *pd)
661 static inline void page_unlock__debug(const PageDesc *pd)
665 #endif /* CONFIG_DEBUG_TCG */
667 static inline void page_lock(PageDesc *pd)
669 page_lock__debug(pd);
670 qemu_spin_lock(&pd->lock);
673 static inline void page_unlock(PageDesc *pd)
675 qemu_spin_unlock(&pd->lock);
676 page_unlock__debug(pd);
679 /* lock the page(s) of a TB in the correct acquisition order */
680 static inline void page_lock_tb(const TranslationBlock *tb)
682 page_lock_pair(NULL, tb->page_addr[0], NULL, tb->page_addr[1], 0);
685 static inline void page_unlock_tb(const TranslationBlock *tb)
687 PageDesc *p1 = page_find(tb->page_addr[0] >> TARGET_PAGE_BITS);
689 page_unlock(p1);
690 if (unlikely(tb->page_addr[1] != -1)) {
691 PageDesc *p2 = page_find(tb->page_addr[1] >> TARGET_PAGE_BITS);
693 if (p2 != p1) {
694 page_unlock(p2);
699 static inline struct page_entry *
700 page_entry_new(PageDesc *pd, tb_page_addr_t index)
702 struct page_entry *pe = g_malloc(sizeof(*pe));
704 pe->index = index;
705 pe->pd = pd;
706 pe->locked = false;
707 return pe;
710 static void page_entry_destroy(gpointer p)
712 struct page_entry *pe = p;
714 g_assert(pe->locked);
715 page_unlock(pe->pd);
716 g_free(pe);
719 /* returns false on success */
720 static bool page_entry_trylock(struct page_entry *pe)
722 bool busy;
724 busy = qemu_spin_trylock(&pe->pd->lock);
725 if (!busy) {
726 g_assert(!pe->locked);
727 pe->locked = true;
728 page_lock__debug(pe->pd);
730 return busy;
733 static void do_page_entry_lock(struct page_entry *pe)
735 page_lock(pe->pd);
736 g_assert(!pe->locked);
737 pe->locked = true;
740 static gboolean page_entry_lock(gpointer key, gpointer value, gpointer data)
742 struct page_entry *pe = value;
744 do_page_entry_lock(pe);
745 return FALSE;
748 static gboolean page_entry_unlock(gpointer key, gpointer value, gpointer data)
750 struct page_entry *pe = value;
752 if (pe->locked) {
753 pe->locked = false;
754 page_unlock(pe->pd);
756 return FALSE;
760 * Trylock a page, and if successful, add the page to a collection.
761 * Returns true ("busy") if the page could not be locked; false otherwise.
763 static bool page_trylock_add(struct page_collection *set, tb_page_addr_t addr)
765 tb_page_addr_t index = addr >> TARGET_PAGE_BITS;
766 struct page_entry *pe;
767 PageDesc *pd;
769 pe = g_tree_lookup(set->tree, &index);
770 if (pe) {
771 return false;
774 pd = page_find(index);
775 if (pd == NULL) {
776 return false;
779 pe = page_entry_new(pd, index);
780 g_tree_insert(set->tree, &pe->index, pe);
783 * If this is either (1) the first insertion or (2) a page whose index
784 * is higher than any other so far, just lock the page and move on.
786 if (set->max == NULL || pe->index > set->max->index) {
787 set->max = pe;
788 do_page_entry_lock(pe);
789 return false;
792 * Try to acquire out-of-order lock; if busy, return busy so that we acquire
793 * locks in order.
795 return page_entry_trylock(pe);
798 static gint tb_page_addr_cmp(gconstpointer ap, gconstpointer bp, gpointer udata)
800 tb_page_addr_t a = *(const tb_page_addr_t *)ap;
801 tb_page_addr_t b = *(const tb_page_addr_t *)bp;
803 if (a == b) {
804 return 0;
805 } else if (a < b) {
806 return -1;
808 return 1;
812 * Lock a range of pages ([@start,@end[) as well as the pages of all
813 * intersecting TBs.
814 * Locking order: acquire locks in ascending order of page index.
816 struct page_collection *
817 page_collection_lock(tb_page_addr_t start, tb_page_addr_t end)
819 struct page_collection *set = g_malloc(sizeof(*set));
820 tb_page_addr_t index;
821 PageDesc *pd;
823 start >>= TARGET_PAGE_BITS;
824 end >>= TARGET_PAGE_BITS;
825 g_assert(start <= end);
827 set->tree = g_tree_new_full(tb_page_addr_cmp, NULL, NULL,
828 page_entry_destroy);
829 set->max = NULL;
830 assert_no_pages_locked();
832 retry:
833 g_tree_foreach(set->tree, page_entry_lock, NULL);
835 for (index = start; index <= end; index++) {
836 TranslationBlock *tb;
837 int n;
839 pd = page_find(index);
840 if (pd == NULL) {
841 continue;
843 if (page_trylock_add(set, index << TARGET_PAGE_BITS)) {
844 g_tree_foreach(set->tree, page_entry_unlock, NULL);
845 goto retry;
847 assert_page_locked(pd);
848 PAGE_FOR_EACH_TB(pd, tb, n) {
849 if (page_trylock_add(set, tb->page_addr[0]) ||
850 (tb->page_addr[1] != -1 &&
851 page_trylock_add(set, tb->page_addr[1]))) {
852 /* drop all locks, and reacquire in order */
853 g_tree_foreach(set->tree, page_entry_unlock, NULL);
854 goto retry;
858 return set;
861 void page_collection_unlock(struct page_collection *set)
863 /* entries are unlocked and freed via page_entry_destroy */
864 g_tree_destroy(set->tree);
865 g_free(set);
868 #endif /* !CONFIG_USER_ONLY */
870 static void page_lock_pair(PageDesc **ret_p1, tb_page_addr_t phys1,
871 PageDesc **ret_p2, tb_page_addr_t phys2, int alloc)
873 PageDesc *p1, *p2;
874 tb_page_addr_t page1;
875 tb_page_addr_t page2;
877 assert_memory_lock();
878 g_assert(phys1 != -1);
880 page1 = phys1 >> TARGET_PAGE_BITS;
881 page2 = phys2 >> TARGET_PAGE_BITS;
883 p1 = page_find_alloc(page1, alloc);
884 if (ret_p1) {
885 *ret_p1 = p1;
887 if (likely(phys2 == -1)) {
888 page_lock(p1);
889 return;
890 } else if (page1 == page2) {
891 page_lock(p1);
892 if (ret_p2) {
893 *ret_p2 = p1;
895 return;
897 p2 = page_find_alloc(page2, alloc);
898 if (ret_p2) {
899 *ret_p2 = p2;
901 if (page1 < page2) {
902 page_lock(p1);
903 page_lock(p2);
904 } else {
905 page_lock(p2);
906 page_lock(p1);
910 /* Minimum size of the code gen buffer. This number is randomly chosen,
911 but not so small that we can't have a fair number of TB's live. */
912 #define MIN_CODE_GEN_BUFFER_SIZE (1 * MiB)
914 /* Maximum size of the code gen buffer we'd like to use. Unless otherwise
915 indicated, this is constrained by the range of direct branches on the
916 host cpu, as used by the TCG implementation of goto_tb. */
917 #if defined(__x86_64__)
918 # define MAX_CODE_GEN_BUFFER_SIZE (2 * GiB)
919 #elif defined(__sparc__)
920 # define MAX_CODE_GEN_BUFFER_SIZE (2 * GiB)
921 #elif defined(__powerpc64__)
922 # define MAX_CODE_GEN_BUFFER_SIZE (2 * GiB)
923 #elif defined(__powerpc__)
924 # define MAX_CODE_GEN_BUFFER_SIZE (32 * MiB)
925 #elif defined(__aarch64__)
926 # define MAX_CODE_GEN_BUFFER_SIZE (2 * GiB)
927 #elif defined(__s390x__)
928 /* We have a +- 4GB range on the branches; leave some slop. */
929 # define MAX_CODE_GEN_BUFFER_SIZE (3 * GiB)
930 #elif defined(__mips__)
931 /* We have a 256MB branch region, but leave room to make sure the
932 main executable is also within that region. */
933 # define MAX_CODE_GEN_BUFFER_SIZE (128 * MiB)
934 #else
935 # define MAX_CODE_GEN_BUFFER_SIZE ((size_t)-1)
936 #endif
938 #if TCG_TARGET_REG_BITS == 32
939 #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (32 * MiB)
940 #ifdef CONFIG_USER_ONLY
942 * For user mode on smaller 32 bit systems we may run into trouble
943 * allocating big chunks of data in the right place. On these systems
944 * we utilise a static code generation buffer directly in the binary.
946 #define USE_STATIC_CODE_GEN_BUFFER
947 #endif
948 #else /* TCG_TARGET_REG_BITS == 64 */
949 #ifdef CONFIG_USER_ONLY
951 * As user-mode emulation typically means running multiple instances
952 * of the translator don't go too nuts with our default code gen
953 * buffer lest we make things too hard for the OS.
955 #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (128 * MiB)
956 #else
958 * We expect most system emulation to run one or two guests per host.
959 * Users running large scale system emulation may want to tweak their
960 * runtime setup via the tb-size control on the command line.
962 #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (1 * GiB)
963 #endif
964 #endif
966 #define DEFAULT_CODE_GEN_BUFFER_SIZE \
967 (DEFAULT_CODE_GEN_BUFFER_SIZE_1 < MAX_CODE_GEN_BUFFER_SIZE \
968 ? DEFAULT_CODE_GEN_BUFFER_SIZE_1 : MAX_CODE_GEN_BUFFER_SIZE)
970 static size_t size_code_gen_buffer(size_t tb_size)
972 /* Size the buffer. */
973 if (tb_size == 0) {
974 size_t phys_mem = qemu_get_host_physmem();
975 if (phys_mem == 0) {
976 tb_size = DEFAULT_CODE_GEN_BUFFER_SIZE;
977 } else {
978 tb_size = MIN(DEFAULT_CODE_GEN_BUFFER_SIZE, phys_mem / 8);
981 if (tb_size < MIN_CODE_GEN_BUFFER_SIZE) {
982 tb_size = MIN_CODE_GEN_BUFFER_SIZE;
984 if (tb_size > MAX_CODE_GEN_BUFFER_SIZE) {
985 tb_size = MAX_CODE_GEN_BUFFER_SIZE;
987 return tb_size;
990 #ifdef __mips__
991 /* In order to use J and JAL within the code_gen_buffer, we require
992 that the buffer not cross a 256MB boundary. */
993 static inline bool cross_256mb(void *addr, size_t size)
995 return ((uintptr_t)addr ^ ((uintptr_t)addr + size)) & ~0x0ffffffful;
998 /* We weren't able to allocate a buffer without crossing that boundary,
999 so make do with the larger portion of the buffer that doesn't cross.
1000 Returns the new base of the buffer, and adjusts code_gen_buffer_size. */
1001 static inline void *split_cross_256mb(void *buf1, size_t size1)
1003 void *buf2 = (void *)(((uintptr_t)buf1 + size1) & ~0x0ffffffful);
1004 size_t size2 = buf1 + size1 - buf2;
1006 size1 = buf2 - buf1;
1007 if (size1 < size2) {
1008 size1 = size2;
1009 buf1 = buf2;
1012 tcg_ctx->code_gen_buffer_size = size1;
1013 return buf1;
1015 #endif
1017 #ifdef USE_STATIC_CODE_GEN_BUFFER
1018 static uint8_t static_code_gen_buffer[DEFAULT_CODE_GEN_BUFFER_SIZE]
1019 __attribute__((aligned(CODE_GEN_ALIGN)));
1021 static bool alloc_code_gen_buffer(size_t tb_size, int splitwx, Error **errp)
1023 void *buf, *end;
1024 size_t size;
1026 if (splitwx > 0) {
1027 error_setg(errp, "jit split-wx not supported");
1028 return false;
1031 /* page-align the beginning and end of the buffer */
1032 buf = static_code_gen_buffer;
1033 end = static_code_gen_buffer + sizeof(static_code_gen_buffer);
1034 buf = QEMU_ALIGN_PTR_UP(buf, qemu_real_host_page_size);
1035 end = QEMU_ALIGN_PTR_DOWN(end, qemu_real_host_page_size);
1037 size = end - buf;
1039 /* Honor a command-line option limiting the size of the buffer. */
1040 if (size > tb_size) {
1041 size = QEMU_ALIGN_DOWN(tb_size, qemu_real_host_page_size);
1043 tcg_ctx->code_gen_buffer_size = size;
1045 #ifdef __mips__
1046 if (cross_256mb(buf, size)) {
1047 buf = split_cross_256mb(buf, size);
1048 size = tcg_ctx->code_gen_buffer_size;
1050 #endif
1052 if (qemu_mprotect_rwx(buf, size)) {
1053 error_setg_errno(errp, errno, "mprotect of jit buffer");
1054 return false;
1056 qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);
1058 tcg_ctx->code_gen_buffer = buf;
1059 return true;
1061 #elif defined(_WIN32)
1062 static bool alloc_code_gen_buffer(size_t size, int splitwx, Error **errp)
1064 void *buf;
1066 if (splitwx > 0) {
1067 error_setg(errp, "jit split-wx not supported");
1068 return false;
1071 buf = VirtualAlloc(NULL, size, MEM_RESERVE | MEM_COMMIT,
1072 PAGE_EXECUTE_READWRITE);
1073 if (buf == NULL) {
1074 error_setg_win32(errp, GetLastError(),
1075 "allocate %zu bytes for jit buffer", size);
1076 return false;
1079 tcg_ctx->code_gen_buffer = buf;
1080 tcg_ctx->code_gen_buffer_size = size;
1081 return true;
1083 #else
1084 static bool alloc_code_gen_buffer_anon(size_t size, int prot,
1085 int flags, Error **errp)
1087 void *buf;
1089 buf = mmap(NULL, size, prot, flags, -1, 0);
1090 if (buf == MAP_FAILED) {
1091 error_setg_errno(errp, errno,
1092 "allocate %zu bytes for jit buffer", size);
1093 return false;
1095 tcg_ctx->code_gen_buffer_size = size;
1097 #ifdef __mips__
1098 if (cross_256mb(buf, size)) {
1100 * Try again, with the original still mapped, to avoid re-acquiring
1101 * the same 256mb crossing.
1103 size_t size2;
1104 void *buf2 = mmap(NULL, size, prot, flags, -1, 0);
1105 switch ((int)(buf2 != MAP_FAILED)) {
1106 case 1:
1107 if (!cross_256mb(buf2, size)) {
1108 /* Success! Use the new buffer. */
1109 munmap(buf, size);
1110 break;
1112 /* Failure. Work with what we had. */
1113 munmap(buf2, size);
1114 /* fallthru */
1115 default:
1116 /* Split the original buffer. Free the smaller half. */
1117 buf2 = split_cross_256mb(buf, size);
1118 size2 = tcg_ctx->code_gen_buffer_size;
1119 if (buf == buf2) {
1120 munmap(buf + size2, size - size2);
1121 } else {
1122 munmap(buf, size - size2);
1124 size = size2;
1125 break;
1127 buf = buf2;
1129 #endif
1131 /* Request large pages for the buffer. */
1132 qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);
1134 tcg_ctx->code_gen_buffer = buf;
1135 return true;
1138 #ifndef CONFIG_TCG_INTERPRETER
1139 #ifdef CONFIG_POSIX
1140 #include "qemu/memfd.h"
1142 static bool alloc_code_gen_buffer_splitwx_memfd(size_t size, Error **errp)
1144 void *buf_rw = NULL, *buf_rx = MAP_FAILED;
1145 int fd = -1;
1147 #ifdef __mips__
1148 /* Find space for the RX mapping, vs the 256MiB regions. */
1149 if (!alloc_code_gen_buffer_anon(size, PROT_NONE,
1150 MAP_PRIVATE | MAP_ANONYMOUS |
1151 MAP_NORESERVE, errp)) {
1152 return false;
1154 /* The size of the mapping may have been adjusted. */
1155 size = tcg_ctx->code_gen_buffer_size;
1156 buf_rx = tcg_ctx->code_gen_buffer;
1157 #endif
1159 buf_rw = qemu_memfd_alloc("tcg-jit", size, 0, &fd, errp);
1160 if (buf_rw == NULL) {
1161 goto fail;
1164 #ifdef __mips__
1165 void *tmp = mmap(buf_rx, size, PROT_READ | PROT_EXEC,
1166 MAP_SHARED | MAP_FIXED, fd, 0);
1167 if (tmp != buf_rx) {
1168 goto fail_rx;
1170 #else
1171 buf_rx = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0);
1172 if (buf_rx == MAP_FAILED) {
1173 goto fail_rx;
1175 #endif
1177 close(fd);
1178 tcg_ctx->code_gen_buffer = buf_rw;
1179 tcg_ctx->code_gen_buffer_size = size;
1180 tcg_splitwx_diff = buf_rx - buf_rw;
1182 /* Request large pages for the buffer and the splitwx. */
1183 qemu_madvise(buf_rw, size, QEMU_MADV_HUGEPAGE);
1184 qemu_madvise(buf_rx, size, QEMU_MADV_HUGEPAGE);
1185 return true;
1187 fail_rx:
1188 error_setg_errno(errp, errno, "failed to map shared memory for execute");
1189 fail:
1190 if (buf_rx != MAP_FAILED) {
1191 munmap(buf_rx, size);
1193 if (buf_rw) {
1194 munmap(buf_rw, size);
1196 if (fd >= 0) {
1197 close(fd);
1199 return false;
1201 #endif /* CONFIG_POSIX */
1203 #ifdef CONFIG_DARWIN
1204 #include <mach/mach.h>
1206 extern kern_return_t mach_vm_remap(vm_map_t target_task,
1207 mach_vm_address_t *target_address,
1208 mach_vm_size_t size,
1209 mach_vm_offset_t mask,
1210 int flags,
1211 vm_map_t src_task,
1212 mach_vm_address_t src_address,
1213 boolean_t copy,
1214 vm_prot_t *cur_protection,
1215 vm_prot_t *max_protection,
1216 vm_inherit_t inheritance);
1218 static bool alloc_code_gen_buffer_splitwx_vmremap(size_t size, Error **errp)
1220 kern_return_t ret;
1221 mach_vm_address_t buf_rw, buf_rx;
1222 vm_prot_t cur_prot, max_prot;
1224 /* Map the read-write portion via normal anon memory. */
1225 if (!alloc_code_gen_buffer_anon(size, PROT_READ | PROT_WRITE,
1226 MAP_PRIVATE | MAP_ANONYMOUS, errp)) {
1227 return false;
1230 buf_rw = (mach_vm_address_t)tcg_ctx->code_gen_buffer;
1231 buf_rx = 0;
1232 ret = mach_vm_remap(mach_task_self(),
1233 &buf_rx,
1234 size,
1236 VM_FLAGS_ANYWHERE,
1237 mach_task_self(),
1238 buf_rw,
1239 false,
1240 &cur_prot,
1241 &max_prot,
1242 VM_INHERIT_NONE);
1243 if (ret != KERN_SUCCESS) {
1244 /* TODO: Convert "ret" to a human readable error message. */
1245 error_setg(errp, "vm_remap for jit splitwx failed");
1246 munmap((void *)buf_rw, size);
1247 return false;
1250 if (mprotect((void *)buf_rx, size, PROT_READ | PROT_EXEC) != 0) {
1251 error_setg_errno(errp, errno, "mprotect for jit splitwx");
1252 munmap((void *)buf_rx, size);
1253 munmap((void *)buf_rw, size);
1254 return false;
1257 tcg_splitwx_diff = buf_rx - buf_rw;
1258 return true;
1260 #endif /* CONFIG_DARWIN */
1261 #endif /* CONFIG_TCG_INTERPRETER */
1263 static bool alloc_code_gen_buffer_splitwx(size_t size, Error **errp)
1265 #ifndef CONFIG_TCG_INTERPRETER
1266 # ifdef CONFIG_DARWIN
1267 return alloc_code_gen_buffer_splitwx_vmremap(size, errp);
1268 # endif
1269 # ifdef CONFIG_POSIX
1270 return alloc_code_gen_buffer_splitwx_memfd(size, errp);
1271 # endif
1272 #endif
1273 error_setg(errp, "jit split-wx not supported");
1274 return false;
1277 static bool alloc_code_gen_buffer(size_t size, int splitwx, Error **errp)
1279 ERRP_GUARD();
1280 int prot, flags;
1282 if (splitwx) {
1283 if (alloc_code_gen_buffer_splitwx(size, errp)) {
1284 return true;
1287 * If splitwx force-on (1), fail;
1288 * if splitwx default-on (-1), fall through to splitwx off.
1290 if (splitwx > 0) {
1291 return false;
1293 error_free_or_abort(errp);
1296 prot = PROT_READ | PROT_WRITE | PROT_EXEC;
1297 flags = MAP_PRIVATE | MAP_ANONYMOUS;
1298 #ifdef CONFIG_TCG_INTERPRETER
1299 /* The tcg interpreter does not need execute permission. */
1300 prot = PROT_READ | PROT_WRITE;
1301 #elif defined(CONFIG_DARWIN)
1302 /* Applicable to both iOS and macOS (Apple Silicon). */
1303 if (!splitwx) {
1304 flags |= MAP_JIT;
1306 #endif
1308 return alloc_code_gen_buffer_anon(size, prot, flags, errp);
1310 #endif /* USE_STATIC_CODE_GEN_BUFFER, WIN32, POSIX */
1312 static bool tb_cmp(const void *ap, const void *bp)
1314 const TranslationBlock *a = ap;
1315 const TranslationBlock *b = bp;
1317 return a->pc == b->pc &&
1318 a->cs_base == b->cs_base &&
1319 a->flags == b->flags &&
1320 (tb_cflags(a) & CF_HASH_MASK) == (tb_cflags(b) & CF_HASH_MASK) &&
1321 a->trace_vcpu_dstate == b->trace_vcpu_dstate &&
1322 a->page_addr[0] == b->page_addr[0] &&
1323 a->page_addr[1] == b->page_addr[1];
1326 static void tb_htable_init(void)
1328 unsigned int mode = QHT_MODE_AUTO_RESIZE;
1330 qht_init(&tb_ctx.htable, tb_cmp, CODE_GEN_HTABLE_SIZE, mode);
1333 /* Must be called before using the QEMU cpus. 'tb_size' is the size
1334 (in bytes) allocated to the translation buffer. Zero means default
1335 size. */
1336 void tcg_exec_init(unsigned long tb_size, int splitwx)
1338 bool ok;
1340 tcg_allowed = true;
1341 cpu_gen_init();
1342 page_init();
1343 tb_htable_init();
1345 ok = alloc_code_gen_buffer(size_code_gen_buffer(tb_size),
1346 splitwx, &error_fatal);
1347 assert(ok);
1349 #if defined(CONFIG_SOFTMMU)
1350 /* There's no guest base to take into account, so go ahead and
1351 initialize the prologue now. */
1352 tcg_prologue_init(tcg_ctx);
1353 #endif
1356 /* call with @p->lock held */
1357 static inline void invalidate_page_bitmap(PageDesc *p)
1359 assert_page_locked(p);
1360 #ifdef CONFIG_SOFTMMU
1361 g_free(p->code_bitmap);
1362 p->code_bitmap = NULL;
1363 p->code_write_count = 0;
1364 #endif
1367 /* Set to NULL all the 'first_tb' fields in all PageDescs. */
1368 static void page_flush_tb_1(int level, void **lp)
1370 int i;
1372 if (*lp == NULL) {
1373 return;
1375 if (level == 0) {
1376 PageDesc *pd = *lp;
1378 for (i = 0; i < V_L2_SIZE; ++i) {
1379 page_lock(&pd[i]);
1380 pd[i].first_tb = (uintptr_t)NULL;
1381 invalidate_page_bitmap(pd + i);
1382 page_unlock(&pd[i]);
1384 } else {
1385 void **pp = *lp;
1387 for (i = 0; i < V_L2_SIZE; ++i) {
1388 page_flush_tb_1(level - 1, pp + i);
1393 static void page_flush_tb(void)
1395 int i, l1_sz = v_l1_size;
1397 for (i = 0; i < l1_sz; i++) {
1398 page_flush_tb_1(v_l2_levels, l1_map + i);
1402 static gboolean tb_host_size_iter(gpointer key, gpointer value, gpointer data)
1404 const TranslationBlock *tb = value;
1405 size_t *size = data;
1407 *size += tb->tc.size;
1408 return false;
1411 /* flush all the translation blocks */
1412 static void do_tb_flush(CPUState *cpu, run_on_cpu_data tb_flush_count)
1414 bool did_flush = false;
1416 mmap_lock();
1417 /* If it is already been done on request of another CPU,
1418 * just retry.
1420 if (tb_ctx.tb_flush_count != tb_flush_count.host_int) {
1421 goto done;
1423 did_flush = true;
1425 if (DEBUG_TB_FLUSH_GATE) {
1426 size_t nb_tbs = tcg_nb_tbs();
1427 size_t host_size = 0;
1429 tcg_tb_foreach(tb_host_size_iter, &host_size);
1430 printf("qemu: flush code_size=%zu nb_tbs=%zu avg_tb_size=%zu\n",
1431 tcg_code_size(), nb_tbs, nb_tbs > 0 ? host_size / nb_tbs : 0);
1434 CPU_FOREACH(cpu) {
1435 cpu_tb_jmp_cache_clear(cpu);
1438 qht_reset_size(&tb_ctx.htable, CODE_GEN_HTABLE_SIZE);
1439 page_flush_tb();
1441 tcg_region_reset_all();
1442 /* XXX: flush processor icache at this point if cache flush is
1443 expensive */
1444 qatomic_mb_set(&tb_ctx.tb_flush_count, tb_ctx.tb_flush_count + 1);
1446 done:
1447 mmap_unlock();
1448 if (did_flush) {
1449 qemu_plugin_flush_cb();
1453 void tb_flush(CPUState *cpu)
1455 if (tcg_enabled()) {
1456 unsigned tb_flush_count = qatomic_mb_read(&tb_ctx.tb_flush_count);
1458 if (cpu_in_exclusive_context(cpu)) {
1459 do_tb_flush(cpu, RUN_ON_CPU_HOST_INT(tb_flush_count));
1460 } else {
1461 async_safe_run_on_cpu(cpu, do_tb_flush,
1462 RUN_ON_CPU_HOST_INT(tb_flush_count));
1468 * Formerly ifdef DEBUG_TB_CHECK. These debug functions are user-mode-only,
1469 * so in order to prevent bit rot we compile them unconditionally in user-mode,
1470 * and let the optimizer get rid of them by wrapping their user-only callers
1471 * with if (DEBUG_TB_CHECK_GATE).
1473 #ifdef CONFIG_USER_ONLY
1475 static void do_tb_invalidate_check(void *p, uint32_t hash, void *userp)
1477 TranslationBlock *tb = p;
1478 target_ulong addr = *(target_ulong *)userp;
1480 if (!(addr + TARGET_PAGE_SIZE <= tb->pc || addr >= tb->pc + tb->size)) {
1481 printf("ERROR invalidate: address=" TARGET_FMT_lx
1482 " PC=%08lx size=%04x\n", addr, (long)tb->pc, tb->size);
1486 /* verify that all the pages have correct rights for code
1488 * Called with mmap_lock held.
1490 static void tb_invalidate_check(target_ulong address)
1492 address &= TARGET_PAGE_MASK;
1493 qht_iter(&tb_ctx.htable, do_tb_invalidate_check, &address);
1496 static void do_tb_page_check(void *p, uint32_t hash, void *userp)
1498 TranslationBlock *tb = p;
1499 int flags1, flags2;
1501 flags1 = page_get_flags(tb->pc);
1502 flags2 = page_get_flags(tb->pc + tb->size - 1);
1503 if ((flags1 & PAGE_WRITE) || (flags2 & PAGE_WRITE)) {
1504 printf("ERROR page flags: PC=%08lx size=%04x f1=%x f2=%x\n",
1505 (long)tb->pc, tb->size, flags1, flags2);
1509 /* verify that all the pages have correct rights for code */
1510 static void tb_page_check(void)
1512 qht_iter(&tb_ctx.htable, do_tb_page_check, NULL);
1515 #endif /* CONFIG_USER_ONLY */
1518 * user-mode: call with mmap_lock held
1519 * !user-mode: call with @pd->lock held
1521 static inline void tb_page_remove(PageDesc *pd, TranslationBlock *tb)
1523 TranslationBlock *tb1;
1524 uintptr_t *pprev;
1525 unsigned int n1;
1527 assert_page_locked(pd);
1528 pprev = &pd->first_tb;
1529 PAGE_FOR_EACH_TB(pd, tb1, n1) {
1530 if (tb1 == tb) {
1531 *pprev = tb1->page_next[n1];
1532 return;
1534 pprev = &tb1->page_next[n1];
1536 g_assert_not_reached();
1539 /* remove @orig from its @n_orig-th jump list */
1540 static inline void tb_remove_from_jmp_list(TranslationBlock *orig, int n_orig)
1542 uintptr_t ptr, ptr_locked;
1543 TranslationBlock *dest;
1544 TranslationBlock *tb;
1545 uintptr_t *pprev;
1546 int n;
1548 /* mark the LSB of jmp_dest[] so that no further jumps can be inserted */
1549 ptr = qatomic_or_fetch(&orig->jmp_dest[n_orig], 1);
1550 dest = (TranslationBlock *)(ptr & ~1);
1551 if (dest == NULL) {
1552 return;
1555 qemu_spin_lock(&dest->jmp_lock);
1557 * While acquiring the lock, the jump might have been removed if the
1558 * destination TB was invalidated; check again.
1560 ptr_locked = qatomic_read(&orig->jmp_dest[n_orig]);
1561 if (ptr_locked != ptr) {
1562 qemu_spin_unlock(&dest->jmp_lock);
1564 * The only possibility is that the jump was unlinked via
1565 * tb_jump_unlink(dest). Seeing here another destination would be a bug,
1566 * because we set the LSB above.
1568 g_assert(ptr_locked == 1 && dest->cflags & CF_INVALID);
1569 return;
1572 * We first acquired the lock, and since the destination pointer matches,
1573 * we know for sure that @orig is in the jmp list.
1575 pprev = &dest->jmp_list_head;
1576 TB_FOR_EACH_JMP(dest, tb, n) {
1577 if (tb == orig && n == n_orig) {
1578 *pprev = tb->jmp_list_next[n];
1579 /* no need to set orig->jmp_dest[n]; setting the LSB was enough */
1580 qemu_spin_unlock(&dest->jmp_lock);
1581 return;
1583 pprev = &tb->jmp_list_next[n];
1585 g_assert_not_reached();
1588 /* reset the jump entry 'n' of a TB so that it is not chained to
1589 another TB */
1590 static inline void tb_reset_jump(TranslationBlock *tb, int n)
1592 uintptr_t addr = (uintptr_t)(tb->tc.ptr + tb->jmp_reset_offset[n]);
1593 tb_set_jmp_target(tb, n, addr);
1596 /* remove any jumps to the TB */
1597 static inline void tb_jmp_unlink(TranslationBlock *dest)
1599 TranslationBlock *tb;
1600 int n;
1602 qemu_spin_lock(&dest->jmp_lock);
1604 TB_FOR_EACH_JMP(dest, tb, n) {
1605 tb_reset_jump(tb, n);
1606 qatomic_and(&tb->jmp_dest[n], (uintptr_t)NULL | 1);
1607 /* No need to clear the list entry; setting the dest ptr is enough */
1609 dest->jmp_list_head = (uintptr_t)NULL;
1611 qemu_spin_unlock(&dest->jmp_lock);
1615 * In user-mode, call with mmap_lock held.
1616 * In !user-mode, if @rm_from_page_list is set, call with the TB's pages'
1617 * locks held.
1619 static void do_tb_phys_invalidate(TranslationBlock *tb, bool rm_from_page_list)
1621 CPUState *cpu;
1622 PageDesc *p;
1623 uint32_t h;
1624 tb_page_addr_t phys_pc;
1626 assert_memory_lock();
1628 /* make sure no further incoming jumps will be chained to this TB */
1629 qemu_spin_lock(&tb->jmp_lock);
1630 qatomic_set(&tb->cflags, tb->cflags | CF_INVALID);
1631 qemu_spin_unlock(&tb->jmp_lock);
1633 /* remove the TB from the hash list */
1634 phys_pc = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);
1635 h = tb_hash_func(phys_pc, tb->pc, tb->flags, tb_cflags(tb) & CF_HASH_MASK,
1636 tb->trace_vcpu_dstate);
1637 if (!(tb->cflags & CF_NOCACHE) &&
1638 !qht_remove(&tb_ctx.htable, tb, h)) {
1639 return;
1642 /* remove the TB from the page list */
1643 if (rm_from_page_list) {
1644 p = page_find(tb->page_addr[0] >> TARGET_PAGE_BITS);
1645 tb_page_remove(p, tb);
1646 invalidate_page_bitmap(p);
1647 if (tb->page_addr[1] != -1) {
1648 p = page_find(tb->page_addr[1] >> TARGET_PAGE_BITS);
1649 tb_page_remove(p, tb);
1650 invalidate_page_bitmap(p);
1654 /* remove the TB from the hash list */
1655 h = tb_jmp_cache_hash_func(tb->pc);
1656 CPU_FOREACH(cpu) {
1657 if (qatomic_read(&cpu->tb_jmp_cache[h]) == tb) {
1658 qatomic_set(&cpu->tb_jmp_cache[h], NULL);
1662 /* suppress this TB from the two jump lists */
1663 tb_remove_from_jmp_list(tb, 0);
1664 tb_remove_from_jmp_list(tb, 1);
1666 /* suppress any remaining jumps to this TB */
1667 tb_jmp_unlink(tb);
1669 qatomic_set(&tcg_ctx->tb_phys_invalidate_count,
1670 tcg_ctx->tb_phys_invalidate_count + 1);
1673 static void tb_phys_invalidate__locked(TranslationBlock *tb)
1675 qemu_thread_jit_write();
1676 do_tb_phys_invalidate(tb, true);
1677 qemu_thread_jit_execute();
1680 /* invalidate one TB
1682 * Called with mmap_lock held in user-mode.
1684 void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr)
1686 if (page_addr == -1 && tb->page_addr[0] != -1) {
1687 page_lock_tb(tb);
1688 do_tb_phys_invalidate(tb, true);
1689 page_unlock_tb(tb);
1690 } else {
1691 do_tb_phys_invalidate(tb, false);
1695 #ifdef CONFIG_SOFTMMU
1696 /* call with @p->lock held */
1697 static void build_page_bitmap(PageDesc *p)
1699 int n, tb_start, tb_end;
1700 TranslationBlock *tb;
1702 assert_page_locked(p);
1703 p->code_bitmap = bitmap_new(TARGET_PAGE_SIZE);
1705 PAGE_FOR_EACH_TB(p, tb, n) {
1706 /* NOTE: this is subtle as a TB may span two physical pages */
1707 if (n == 0) {
1708 /* NOTE: tb_end may be after the end of the page, but
1709 it is not a problem */
1710 tb_start = tb->pc & ~TARGET_PAGE_MASK;
1711 tb_end = tb_start + tb->size;
1712 if (tb_end > TARGET_PAGE_SIZE) {
1713 tb_end = TARGET_PAGE_SIZE;
1715 } else {
1716 tb_start = 0;
1717 tb_end = ((tb->pc + tb->size) & ~TARGET_PAGE_MASK);
1719 bitmap_set(p->code_bitmap, tb_start, tb_end - tb_start);
1722 #endif
1724 /* add the tb in the target page and protect it if necessary
1726 * Called with mmap_lock held for user-mode emulation.
1727 * Called with @p->lock held in !user-mode.
1729 static inline void tb_page_add(PageDesc *p, TranslationBlock *tb,
1730 unsigned int n, tb_page_addr_t page_addr)
1732 #ifndef CONFIG_USER_ONLY
1733 bool page_already_protected;
1734 #endif
1736 assert_page_locked(p);
1738 tb->page_addr[n] = page_addr;
1739 tb->page_next[n] = p->first_tb;
1740 #ifndef CONFIG_USER_ONLY
1741 page_already_protected = p->first_tb != (uintptr_t)NULL;
1742 #endif
1743 p->first_tb = (uintptr_t)tb | n;
1744 invalidate_page_bitmap(p);
1746 #if defined(CONFIG_USER_ONLY)
1747 if (p->flags & PAGE_WRITE) {
1748 target_ulong addr;
1749 PageDesc *p2;
1750 int prot;
1752 /* force the host page as non writable (writes will have a
1753 page fault + mprotect overhead) */
1754 page_addr &= qemu_host_page_mask;
1755 prot = 0;
1756 for (addr = page_addr; addr < page_addr + qemu_host_page_size;
1757 addr += TARGET_PAGE_SIZE) {
1759 p2 = page_find(addr >> TARGET_PAGE_BITS);
1760 if (!p2) {
1761 continue;
1763 prot |= p2->flags;
1764 p2->flags &= ~PAGE_WRITE;
1766 mprotect(g2h_untagged(page_addr), qemu_host_page_size,
1767 (prot & PAGE_BITS) & ~PAGE_WRITE);
1768 if (DEBUG_TB_INVALIDATE_GATE) {
1769 printf("protecting code page: 0x" TB_PAGE_ADDR_FMT "\n", page_addr);
1772 #else
1773 /* if some code is already present, then the pages are already
1774 protected. So we handle the case where only the first TB is
1775 allocated in a physical page */
1776 if (!page_already_protected) {
1777 tlb_protect_code(page_addr);
1779 #endif
1782 /* add a new TB and link it to the physical page tables. phys_page2 is
1783 * (-1) to indicate that only one page contains the TB.
1785 * Called with mmap_lock held for user-mode emulation.
1787 * Returns a pointer @tb, or a pointer to an existing TB that matches @tb.
1788 * Note that in !user-mode, another thread might have already added a TB
1789 * for the same block of guest code that @tb corresponds to. In that case,
1790 * the caller should discard the original @tb, and use instead the returned TB.
1792 static TranslationBlock *
1793 tb_link_page(TranslationBlock *tb, tb_page_addr_t phys_pc,
1794 tb_page_addr_t phys_page2)
1796 PageDesc *p;
1797 PageDesc *p2 = NULL;
1799 assert_memory_lock();
1801 if (phys_pc == -1) {
1803 * If the TB is not associated with a physical RAM page then
1804 * it must be a temporary one-insn TB, and we have nothing to do
1805 * except fill in the page_addr[] fields.
1807 assert(tb->cflags & CF_NOCACHE);
1808 tb->page_addr[0] = tb->page_addr[1] = -1;
1809 return tb;
1813 * Add the TB to the page list, acquiring first the pages's locks.
1814 * We keep the locks held until after inserting the TB in the hash table,
1815 * so that if the insertion fails we know for sure that the TBs are still
1816 * in the page descriptors.
1817 * Note that inserting into the hash table first isn't an option, since
1818 * we can only insert TBs that are fully initialized.
1820 page_lock_pair(&p, phys_pc, &p2, phys_page2, 1);
1821 tb_page_add(p, tb, 0, phys_pc & TARGET_PAGE_MASK);
1822 if (p2) {
1823 tb_page_add(p2, tb, 1, phys_page2);
1824 } else {
1825 tb->page_addr[1] = -1;
1828 if (!(tb->cflags & CF_NOCACHE)) {
1829 void *existing_tb = NULL;
1830 uint32_t h;
1832 /* add in the hash table */
1833 h = tb_hash_func(phys_pc, tb->pc, tb->flags, tb->cflags & CF_HASH_MASK,
1834 tb->trace_vcpu_dstate);
1835 qht_insert(&tb_ctx.htable, tb, h, &existing_tb);
1837 /* remove TB from the page(s) if we couldn't insert it */
1838 if (unlikely(existing_tb)) {
1839 tb_page_remove(p, tb);
1840 invalidate_page_bitmap(p);
1841 if (p2) {
1842 tb_page_remove(p2, tb);
1843 invalidate_page_bitmap(p2);
1845 tb = existing_tb;
1849 if (p2 && p2 != p) {
1850 page_unlock(p2);
1852 page_unlock(p);
1854 #ifdef CONFIG_USER_ONLY
1855 if (DEBUG_TB_CHECK_GATE) {
1856 tb_page_check();
1858 #endif
1859 return tb;
1862 /* Called with mmap_lock held for user mode emulation. */
1863 TranslationBlock *tb_gen_code(CPUState *cpu,
1864 target_ulong pc, target_ulong cs_base,
1865 uint32_t flags, int cflags)
1867 CPUArchState *env = cpu->env_ptr;
1868 TranslationBlock *tb, *existing_tb;
1869 tb_page_addr_t phys_pc, phys_page2;
1870 target_ulong virt_page2;
1871 tcg_insn_unit *gen_code_buf;
1872 int gen_code_size, search_size, max_insns;
1873 #ifdef CONFIG_PROFILER
1874 TCGProfile *prof = &tcg_ctx->prof;
1875 int64_t ti;
1876 #endif
1878 assert_memory_lock();
1879 qemu_thread_jit_write();
1881 phys_pc = get_page_addr_code(env, pc);
1883 if (phys_pc == -1) {
1884 /* Generate a temporary TB with 1 insn in it */
1885 cflags &= ~CF_COUNT_MASK;
1886 cflags |= CF_NOCACHE | 1;
1889 cflags &= ~CF_CLUSTER_MASK;
1890 cflags |= cpu->cluster_index << CF_CLUSTER_SHIFT;
1892 max_insns = cflags & CF_COUNT_MASK;
1893 if (max_insns == 0) {
1894 max_insns = CF_COUNT_MASK;
1896 if (max_insns > TCG_MAX_INSNS) {
1897 max_insns = TCG_MAX_INSNS;
1899 if (cpu->singlestep_enabled || singlestep) {
1900 max_insns = 1;
1903 buffer_overflow:
1904 tb = tcg_tb_alloc(tcg_ctx);
1905 if (unlikely(!tb)) {
1906 /* flush must be done */
1907 tb_flush(cpu);
1908 mmap_unlock();
1909 /* Make the execution loop process the flush as soon as possible. */
1910 cpu->exception_index = EXCP_INTERRUPT;
1911 cpu_loop_exit(cpu);
1914 gen_code_buf = tcg_ctx->code_gen_ptr;
1915 tb->tc.ptr = tcg_splitwx_to_rx(gen_code_buf);
1916 tb->pc = pc;
1917 tb->cs_base = cs_base;
1918 tb->flags = flags;
1919 tb->cflags = cflags;
1920 tb->orig_tb = NULL;
1921 tb->trace_vcpu_dstate = *cpu->trace_dstate;
1922 tcg_ctx->tb_cflags = cflags;
1923 tb_overflow:
1925 #ifdef CONFIG_PROFILER
1926 /* includes aborted translations because of exceptions */
1927 qatomic_set(&prof->tb_count1, prof->tb_count1 + 1);
1928 ti = profile_getclock();
1929 #endif
1931 gen_code_size = sigsetjmp(tcg_ctx->jmp_trans, 0);
1932 if (unlikely(gen_code_size != 0)) {
1933 goto error_return;
1936 tcg_func_start(tcg_ctx);
1938 tcg_ctx->cpu = env_cpu(env);
1939 gen_intermediate_code(cpu, tb, max_insns);
1940 tcg_ctx->cpu = NULL;
1941 max_insns = tb->icount;
1943 trace_translate_block(tb, tb->pc, tb->tc.ptr);
1945 /* generate machine code */
1946 tb->jmp_reset_offset[0] = TB_JMP_RESET_OFFSET_INVALID;
1947 tb->jmp_reset_offset[1] = TB_JMP_RESET_OFFSET_INVALID;
1948 tcg_ctx->tb_jmp_reset_offset = tb->jmp_reset_offset;
1949 if (TCG_TARGET_HAS_direct_jump) {
1950 tcg_ctx->tb_jmp_insn_offset = tb->jmp_target_arg;
1951 tcg_ctx->tb_jmp_target_addr = NULL;
1952 } else {
1953 tcg_ctx->tb_jmp_insn_offset = NULL;
1954 tcg_ctx->tb_jmp_target_addr = tb->jmp_target_arg;
1957 #ifdef CONFIG_PROFILER
1958 qatomic_set(&prof->tb_count, prof->tb_count + 1);
1959 qatomic_set(&prof->interm_time,
1960 prof->interm_time + profile_getclock() - ti);
1961 ti = profile_getclock();
1962 #endif
1964 gen_code_size = tcg_gen_code(tcg_ctx, tb);
1965 if (unlikely(gen_code_size < 0)) {
1966 error_return:
1967 switch (gen_code_size) {
1968 case -1:
1970 * Overflow of code_gen_buffer, or the current slice of it.
1972 * TODO: We don't need to re-do gen_intermediate_code, nor
1973 * should we re-do the tcg optimization currently hidden
1974 * inside tcg_gen_code. All that should be required is to
1975 * flush the TBs, allocate a new TB, re-initialize it per
1976 * above, and re-do the actual code generation.
1978 qemu_log_mask(CPU_LOG_TB_OP | CPU_LOG_TB_OP_OPT,
1979 "Restarting code generation for "
1980 "code_gen_buffer overflow\n");
1981 goto buffer_overflow;
1983 case -2:
1985 * The code generated for the TranslationBlock is too large.
1986 * The maximum size allowed by the unwind info is 64k.
1987 * There may be stricter constraints from relocations
1988 * in the tcg backend.
1990 * Try again with half as many insns as we attempted this time.
1991 * If a single insn overflows, there's a bug somewhere...
1993 assert(max_insns > 1);
1994 max_insns /= 2;
1995 qemu_log_mask(CPU_LOG_TB_OP | CPU_LOG_TB_OP_OPT,
1996 "Restarting code generation with "
1997 "smaller translation block (max %d insns)\n",
1998 max_insns);
1999 goto tb_overflow;
2001 default:
2002 g_assert_not_reached();
2005 search_size = encode_search(tb, (void *)gen_code_buf + gen_code_size);
2006 if (unlikely(search_size < 0)) {
2007 goto buffer_overflow;
2009 tb->tc.size = gen_code_size;
2011 #ifdef CONFIG_PROFILER
2012 qatomic_set(&prof->code_time, prof->code_time + profile_getclock() - ti);
2013 qatomic_set(&prof->code_in_len, prof->code_in_len + tb->size);
2014 qatomic_set(&prof->code_out_len, prof->code_out_len + gen_code_size);
2015 qatomic_set(&prof->search_out_len, prof->search_out_len + search_size);
2016 #endif
2018 #ifdef DEBUG_DISAS
2019 if (qemu_loglevel_mask(CPU_LOG_TB_OUT_ASM) &&
2020 qemu_log_in_addr_range(tb->pc)) {
2021 FILE *logfile = qemu_log_lock();
2022 int code_size, data_size;
2023 const tcg_target_ulong *rx_data_gen_ptr;
2024 size_t chunk_start;
2025 int insn = 0;
2027 if (tcg_ctx->data_gen_ptr) {
2028 rx_data_gen_ptr = tcg_splitwx_to_rx(tcg_ctx->data_gen_ptr);
2029 code_size = (const void *)rx_data_gen_ptr - tb->tc.ptr;
2030 data_size = gen_code_size - code_size;
2031 } else {
2032 rx_data_gen_ptr = 0;
2033 code_size = gen_code_size;
2034 data_size = 0;
2037 /* Dump header and the first instruction */
2038 qemu_log("OUT: [size=%d]\n", gen_code_size);
2039 qemu_log(" -- guest addr 0x" TARGET_FMT_lx " + tb prologue\n",
2040 tcg_ctx->gen_insn_data[insn][0]);
2041 chunk_start = tcg_ctx->gen_insn_end_off[insn];
2042 log_disas(tb->tc.ptr, chunk_start);
2045 * Dump each instruction chunk, wrapping up empty chunks into
2046 * the next instruction. The whole array is offset so the
2047 * first entry is the beginning of the 2nd instruction.
2049 while (insn < tb->icount) {
2050 size_t chunk_end = tcg_ctx->gen_insn_end_off[insn];
2051 if (chunk_end > chunk_start) {
2052 qemu_log(" -- guest addr 0x" TARGET_FMT_lx "\n",
2053 tcg_ctx->gen_insn_data[insn][0]);
2054 log_disas(tb->tc.ptr + chunk_start, chunk_end - chunk_start);
2055 chunk_start = chunk_end;
2057 insn++;
2060 if (chunk_start < code_size) {
2061 qemu_log(" -- tb slow paths + alignment\n");
2062 log_disas(tb->tc.ptr + chunk_start, code_size - chunk_start);
2065 /* Finally dump any data we may have after the block */
2066 if (data_size) {
2067 int i;
2068 qemu_log(" data: [size=%d]\n", data_size);
2069 for (i = 0; i < data_size / sizeof(tcg_target_ulong); i++) {
2070 qemu_log("0x%08" PRIxPTR ": .quad 0x%" TCG_PRIlx "\n",
2071 (uintptr_t)&rx_data_gen_ptr[i], rx_data_gen_ptr[i]);
2074 qemu_log("\n");
2075 qemu_log_flush();
2076 qemu_log_unlock(logfile);
2078 #endif
2080 qatomic_set(&tcg_ctx->code_gen_ptr, (void *)
2081 ROUND_UP((uintptr_t)gen_code_buf + gen_code_size + search_size,
2082 CODE_GEN_ALIGN));
2084 /* init jump list */
2085 qemu_spin_init(&tb->jmp_lock);
2086 tb->jmp_list_head = (uintptr_t)NULL;
2087 tb->jmp_list_next[0] = (uintptr_t)NULL;
2088 tb->jmp_list_next[1] = (uintptr_t)NULL;
2089 tb->jmp_dest[0] = (uintptr_t)NULL;
2090 tb->jmp_dest[1] = (uintptr_t)NULL;
2092 /* init original jump addresses which have been set during tcg_gen_code() */
2093 if (tb->jmp_reset_offset[0] != TB_JMP_RESET_OFFSET_INVALID) {
2094 tb_reset_jump(tb, 0);
2096 if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) {
2097 tb_reset_jump(tb, 1);
2100 /* check next page if needed */
2101 virt_page2 = (pc + tb->size - 1) & TARGET_PAGE_MASK;
2102 phys_page2 = -1;
2103 if ((pc & TARGET_PAGE_MASK) != virt_page2) {
2104 phys_page2 = get_page_addr_code(env, virt_page2);
2107 * No explicit memory barrier is required -- tb_link_page() makes the
2108 * TB visible in a consistent state.
2110 existing_tb = tb_link_page(tb, phys_pc, phys_page2);
2111 /* if the TB already exists, discard what we just translated */
2112 if (unlikely(existing_tb != tb)) {
2113 uintptr_t orig_aligned = (uintptr_t)gen_code_buf;
2115 orig_aligned -= ROUND_UP(sizeof(*tb), qemu_icache_linesize);
2116 qatomic_set(&tcg_ctx->code_gen_ptr, (void *)orig_aligned);
2117 tb_destroy(tb);
2118 return existing_tb;
2120 tcg_tb_insert(tb);
2121 return tb;
2125 * @p must be non-NULL.
2126 * user-mode: call with mmap_lock held.
2127 * !user-mode: call with all @pages locked.
2129 static void
2130 tb_invalidate_phys_page_range__locked(struct page_collection *pages,
2131 PageDesc *p, tb_page_addr_t start,
2132 tb_page_addr_t end,
2133 uintptr_t retaddr)
2135 TranslationBlock *tb;
2136 tb_page_addr_t tb_start, tb_end;
2137 int n;
2138 #ifdef TARGET_HAS_PRECISE_SMC
2139 CPUState *cpu = current_cpu;
2140 CPUArchState *env = NULL;
2141 bool current_tb_not_found = retaddr != 0;
2142 bool current_tb_modified = false;
2143 TranslationBlock *current_tb = NULL;
2144 target_ulong current_pc = 0;
2145 target_ulong current_cs_base = 0;
2146 uint32_t current_flags = 0;
2147 #endif /* TARGET_HAS_PRECISE_SMC */
2149 assert_page_locked(p);
2151 #if defined(TARGET_HAS_PRECISE_SMC)
2152 if (cpu != NULL) {
2153 env = cpu->env_ptr;
2155 #endif
2157 /* we remove all the TBs in the range [start, end[ */
2158 /* XXX: see if in some cases it could be faster to invalidate all
2159 the code */
2160 PAGE_FOR_EACH_TB(p, tb, n) {
2161 assert_page_locked(p);
2162 /* NOTE: this is subtle as a TB may span two physical pages */
2163 if (n == 0) {
2164 /* NOTE: tb_end may be after the end of the page, but
2165 it is not a problem */
2166 tb_start = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);
2167 tb_end = tb_start + tb->size;
2168 } else {
2169 tb_start = tb->page_addr[1];
2170 tb_end = tb_start + ((tb->pc + tb->size) & ~TARGET_PAGE_MASK);
2172 if (!(tb_end <= start || tb_start >= end)) {
2173 #ifdef TARGET_HAS_PRECISE_SMC
2174 if (current_tb_not_found) {
2175 current_tb_not_found = false;
2176 /* now we have a real cpu fault */
2177 current_tb = tcg_tb_lookup(retaddr);
2179 if (current_tb == tb &&
2180 (tb_cflags(current_tb) & CF_COUNT_MASK) != 1) {
2182 * If we are modifying the current TB, we must stop
2183 * its execution. We could be more precise by checking
2184 * that the modification is after the current PC, but it
2185 * would require a specialized function to partially
2186 * restore the CPU state.
2188 current_tb_modified = true;
2189 cpu_restore_state_from_tb(cpu, current_tb, retaddr, true);
2190 cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base,
2191 &current_flags);
2193 #endif /* TARGET_HAS_PRECISE_SMC */
2194 tb_phys_invalidate__locked(tb);
2197 #if !defined(CONFIG_USER_ONLY)
2198 /* if no code remaining, no need to continue to use slow writes */
2199 if (!p->first_tb) {
2200 invalidate_page_bitmap(p);
2201 tlb_unprotect_code(start);
2203 #endif
2204 #ifdef TARGET_HAS_PRECISE_SMC
2205 if (current_tb_modified) {
2206 page_collection_unlock(pages);
2207 /* Force execution of one insn next time. */
2208 cpu->cflags_next_tb = 1 | curr_cflags();
2209 mmap_unlock();
2210 cpu_loop_exit_noexc(cpu);
2212 #endif
2216 * Invalidate all TBs which intersect with the target physical address range
2217 * [start;end[. NOTE: start and end must refer to the *same* physical page.
2218 * 'is_cpu_write_access' should be true if called from a real cpu write
2219 * access: the virtual CPU will exit the current TB if code is modified inside
2220 * this TB.
2222 * Called with mmap_lock held for user-mode emulation
2224 void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end)
2226 struct page_collection *pages;
2227 PageDesc *p;
2229 assert_memory_lock();
2231 p = page_find(start >> TARGET_PAGE_BITS);
2232 if (p == NULL) {
2233 return;
2235 pages = page_collection_lock(start, end);
2236 tb_invalidate_phys_page_range__locked(pages, p, start, end, 0);
2237 page_collection_unlock(pages);
2241 * Invalidate all TBs which intersect with the target physical address range
2242 * [start;end[. NOTE: start and end may refer to *different* physical pages.
2243 * 'is_cpu_write_access' should be true if called from a real cpu write
2244 * access: the virtual CPU will exit the current TB if code is modified inside
2245 * this TB.
2247 * Called with mmap_lock held for user-mode emulation.
2249 #ifdef CONFIG_SOFTMMU
2250 void tb_invalidate_phys_range(ram_addr_t start, ram_addr_t end)
2251 #else
2252 void tb_invalidate_phys_range(target_ulong start, target_ulong end)
2253 #endif
2255 struct page_collection *pages;
2256 tb_page_addr_t next;
2258 assert_memory_lock();
2260 pages = page_collection_lock(start, end);
2261 for (next = (start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;
2262 start < end;
2263 start = next, next += TARGET_PAGE_SIZE) {
2264 PageDesc *pd = page_find(start >> TARGET_PAGE_BITS);
2265 tb_page_addr_t bound = MIN(next, end);
2267 if (pd == NULL) {
2268 continue;
2270 tb_invalidate_phys_page_range__locked(pages, pd, start, bound, 0);
2272 page_collection_unlock(pages);
2275 #ifdef CONFIG_SOFTMMU
2276 /* len must be <= 8 and start must be a multiple of len.
2277 * Called via softmmu_template.h when code areas are written to with
2278 * iothread mutex not held.
2280 * Call with all @pages in the range [@start, @start + len[ locked.
2282 void tb_invalidate_phys_page_fast(struct page_collection *pages,
2283 tb_page_addr_t start, int len,
2284 uintptr_t retaddr)
2286 PageDesc *p;
2288 assert_memory_lock();
2290 p = page_find(start >> TARGET_PAGE_BITS);
2291 if (!p) {
2292 return;
2295 assert_page_locked(p);
2296 if (!p->code_bitmap &&
2297 ++p->code_write_count >= SMC_BITMAP_USE_THRESHOLD) {
2298 build_page_bitmap(p);
2300 if (p->code_bitmap) {
2301 unsigned int nr;
2302 unsigned long b;
2304 nr = start & ~TARGET_PAGE_MASK;
2305 b = p->code_bitmap[BIT_WORD(nr)] >> (nr & (BITS_PER_LONG - 1));
2306 if (b & ((1 << len) - 1)) {
2307 goto do_invalidate;
2309 } else {
2310 do_invalidate:
2311 tb_invalidate_phys_page_range__locked(pages, p, start, start + len,
2312 retaddr);
2315 #else
2316 /* Called with mmap_lock held. If pc is not 0 then it indicates the
2317 * host PC of the faulting store instruction that caused this invalidate.
2318 * Returns true if the caller needs to abort execution of the current
2319 * TB (because it was modified by this store and the guest CPU has
2320 * precise-SMC semantics).
2322 static bool tb_invalidate_phys_page(tb_page_addr_t addr, uintptr_t pc)
2324 TranslationBlock *tb;
2325 PageDesc *p;
2326 int n;
2327 #ifdef TARGET_HAS_PRECISE_SMC
2328 TranslationBlock *current_tb = NULL;
2329 CPUState *cpu = current_cpu;
2330 CPUArchState *env = NULL;
2331 int current_tb_modified = 0;
2332 target_ulong current_pc = 0;
2333 target_ulong current_cs_base = 0;
2334 uint32_t current_flags = 0;
2335 #endif
2337 assert_memory_lock();
2339 addr &= TARGET_PAGE_MASK;
2340 p = page_find(addr >> TARGET_PAGE_BITS);
2341 if (!p) {
2342 return false;
2345 #ifdef TARGET_HAS_PRECISE_SMC
2346 if (p->first_tb && pc != 0) {
2347 current_tb = tcg_tb_lookup(pc);
2349 if (cpu != NULL) {
2350 env = cpu->env_ptr;
2352 #endif
2353 assert_page_locked(p);
2354 PAGE_FOR_EACH_TB(p, tb, n) {
2355 #ifdef TARGET_HAS_PRECISE_SMC
2356 if (current_tb == tb &&
2357 (tb_cflags(current_tb) & CF_COUNT_MASK) != 1) {
2358 /* If we are modifying the current TB, we must stop
2359 its execution. We could be more precise by checking
2360 that the modification is after the current PC, but it
2361 would require a specialized function to partially
2362 restore the CPU state */
2364 current_tb_modified = 1;
2365 cpu_restore_state_from_tb(cpu, current_tb, pc, true);
2366 cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base,
2367 &current_flags);
2369 #endif /* TARGET_HAS_PRECISE_SMC */
2370 tb_phys_invalidate(tb, addr);
2372 p->first_tb = (uintptr_t)NULL;
2373 #ifdef TARGET_HAS_PRECISE_SMC
2374 if (current_tb_modified) {
2375 /* Force execution of one insn next time. */
2376 cpu->cflags_next_tb = 1 | curr_cflags();
2377 return true;
2379 #endif
2381 return false;
2383 #endif
2385 /* user-mode: call with mmap_lock held */
2386 void tb_check_watchpoint(CPUState *cpu, uintptr_t retaddr)
2388 TranslationBlock *tb;
2390 assert_memory_lock();
2392 tb = tcg_tb_lookup(retaddr);
2393 if (tb) {
2394 /* We can use retranslation to find the PC. */
2395 cpu_restore_state_from_tb(cpu, tb, retaddr, true);
2396 tb_phys_invalidate(tb, -1);
2397 } else {
2398 /* The exception probably happened in a helper. The CPU state should
2399 have been saved before calling it. Fetch the PC from there. */
2400 CPUArchState *env = cpu->env_ptr;
2401 target_ulong pc, cs_base;
2402 tb_page_addr_t addr;
2403 uint32_t flags;
2405 cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags);
2406 addr = get_page_addr_code(env, pc);
2407 if (addr != -1) {
2408 tb_invalidate_phys_range(addr, addr + 1);
2413 #ifndef CONFIG_USER_ONLY
2414 /* in deterministic execution mode, instructions doing device I/Os
2415 * must be at the end of the TB.
2417 * Called by softmmu_template.h, with iothread mutex not held.
2419 void cpu_io_recompile(CPUState *cpu, uintptr_t retaddr)
2421 TranslationBlock *tb;
2422 CPUClass *cc;
2423 uint32_t n;
2425 tb = tcg_tb_lookup(retaddr);
2426 if (!tb) {
2427 cpu_abort(cpu, "cpu_io_recompile: could not find TB for pc=%p",
2428 (void *)retaddr);
2430 cpu_restore_state_from_tb(cpu, tb, retaddr, true);
2433 * Some guests must re-execute the branch when re-executing a delay
2434 * slot instruction. When this is the case, adjust icount and N
2435 * to account for the re-execution of the branch.
2437 n = 1;
2438 cc = CPU_GET_CLASS(cpu);
2439 if (cc->tcg_ops->io_recompile_replay_branch &&
2440 cc->tcg_ops->io_recompile_replay_branch(cpu, tb)) {
2441 cpu_neg(cpu)->icount_decr.u16.low++;
2442 n = 2;
2445 /* Generate a new TB executing the I/O insn. */
2446 cpu->cflags_next_tb = curr_cflags() | CF_LAST_IO | n;
2448 if (tb_cflags(tb) & CF_NOCACHE) {
2449 if (tb->orig_tb) {
2450 /* Invalidate original TB if this TB was generated in
2451 * cpu_exec_nocache() */
2452 tb_phys_invalidate(tb->orig_tb, -1);
2454 tcg_tb_remove(tb);
2455 tb_destroy(tb);
2458 qemu_log_mask_and_addr(CPU_LOG_EXEC, tb->pc,
2459 "cpu_io_recompile: rewound execution of TB to "
2460 TARGET_FMT_lx "\n", tb->pc);
2462 /* TODO: If env->pc != tb->pc (i.e. the faulting instruction was not
2463 * the first in the TB) then we end up generating a whole new TB and
2464 * repeating the fault, which is horribly inefficient.
2465 * Better would be to execute just this insn uncached, or generate a
2466 * second new TB.
2468 cpu_loop_exit_noexc(cpu);
2471 static void print_qht_statistics(struct qht_stats hst)
2473 uint32_t hgram_opts;
2474 size_t hgram_bins;
2475 char *hgram;
2477 if (!hst.head_buckets) {
2478 return;
2480 qemu_printf("TB hash buckets %zu/%zu (%0.2f%% head buckets used)\n",
2481 hst.used_head_buckets, hst.head_buckets,
2482 (double)hst.used_head_buckets / hst.head_buckets * 100);
2484 hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
2485 hgram_opts |= QDIST_PR_100X | QDIST_PR_PERCENT;
2486 if (qdist_xmax(&hst.occupancy) - qdist_xmin(&hst.occupancy) == 1) {
2487 hgram_opts |= QDIST_PR_NODECIMAL;
2489 hgram = qdist_pr(&hst.occupancy, 10, hgram_opts);
2490 qemu_printf("TB hash occupancy %0.2f%% avg chain occ. Histogram: %s\n",
2491 qdist_avg(&hst.occupancy) * 100, hgram);
2492 g_free(hgram);
2494 hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
2495 hgram_bins = qdist_xmax(&hst.chain) - qdist_xmin(&hst.chain);
2496 if (hgram_bins > 10) {
2497 hgram_bins = 10;
2498 } else {
2499 hgram_bins = 0;
2500 hgram_opts |= QDIST_PR_NODECIMAL | QDIST_PR_NOBINRANGE;
2502 hgram = qdist_pr(&hst.chain, hgram_bins, hgram_opts);
2503 qemu_printf("TB hash avg chain %0.3f buckets. Histogram: %s\n",
2504 qdist_avg(&hst.chain), hgram);
2505 g_free(hgram);
2508 struct tb_tree_stats {
2509 size_t nb_tbs;
2510 size_t host_size;
2511 size_t target_size;
2512 size_t max_target_size;
2513 size_t direct_jmp_count;
2514 size_t direct_jmp2_count;
2515 size_t cross_page;
2518 static gboolean tb_tree_stats_iter(gpointer key, gpointer value, gpointer data)
2520 const TranslationBlock *tb = value;
2521 struct tb_tree_stats *tst = data;
2523 tst->nb_tbs++;
2524 tst->host_size += tb->tc.size;
2525 tst->target_size += tb->size;
2526 if (tb->size > tst->max_target_size) {
2527 tst->max_target_size = tb->size;
2529 if (tb->page_addr[1] != -1) {
2530 tst->cross_page++;
2532 if (tb->jmp_reset_offset[0] != TB_JMP_RESET_OFFSET_INVALID) {
2533 tst->direct_jmp_count++;
2534 if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) {
2535 tst->direct_jmp2_count++;
2538 return false;
2541 void dump_exec_info(void)
2543 struct tb_tree_stats tst = {};
2544 struct qht_stats hst;
2545 size_t nb_tbs, flush_full, flush_part, flush_elide;
2547 tcg_tb_foreach(tb_tree_stats_iter, &tst);
2548 nb_tbs = tst.nb_tbs;
2549 /* XXX: avoid using doubles ? */
2550 qemu_printf("Translation buffer state:\n");
2552 * Report total code size including the padding and TB structs;
2553 * otherwise users might think "-accel tcg,tb-size" is not honoured.
2554 * For avg host size we use the precise numbers from tb_tree_stats though.
2556 qemu_printf("gen code size %zu/%zu\n",
2557 tcg_code_size(), tcg_code_capacity());
2558 qemu_printf("TB count %zu\n", nb_tbs);
2559 qemu_printf("TB avg target size %zu max=%zu bytes\n",
2560 nb_tbs ? tst.target_size / nb_tbs : 0,
2561 tst.max_target_size);
2562 qemu_printf("TB avg host size %zu bytes (expansion ratio: %0.1f)\n",
2563 nb_tbs ? tst.host_size / nb_tbs : 0,
2564 tst.target_size ? (double)tst.host_size / tst.target_size : 0);
2565 qemu_printf("cross page TB count %zu (%zu%%)\n", tst.cross_page,
2566 nb_tbs ? (tst.cross_page * 100) / nb_tbs : 0);
2567 qemu_printf("direct jump count %zu (%zu%%) (2 jumps=%zu %zu%%)\n",
2568 tst.direct_jmp_count,
2569 nb_tbs ? (tst.direct_jmp_count * 100) / nb_tbs : 0,
2570 tst.direct_jmp2_count,
2571 nb_tbs ? (tst.direct_jmp2_count * 100) / nb_tbs : 0);
2573 qht_statistics_init(&tb_ctx.htable, &hst);
2574 print_qht_statistics(hst);
2575 qht_statistics_destroy(&hst);
2577 qemu_printf("\nStatistics:\n");
2578 qemu_printf("TB flush count %u\n",
2579 qatomic_read(&tb_ctx.tb_flush_count));
2580 qemu_printf("TB invalidate count %zu\n",
2581 tcg_tb_phys_invalidate_count());
2583 tlb_flush_counts(&flush_full, &flush_part, &flush_elide);
2584 qemu_printf("TLB full flushes %zu\n", flush_full);
2585 qemu_printf("TLB partial flushes %zu\n", flush_part);
2586 qemu_printf("TLB elided flushes %zu\n", flush_elide);
2587 tcg_dump_info();
2590 void dump_opcount_info(void)
2592 tcg_dump_op_count();
2595 #else /* CONFIG_USER_ONLY */
2597 void cpu_interrupt(CPUState *cpu, int mask)
2599 g_assert(qemu_mutex_iothread_locked());
2600 cpu->interrupt_request |= mask;
2601 qatomic_set(&cpu_neg(cpu)->icount_decr.u16.high, -1);
2605 * Walks guest process memory "regions" one by one
2606 * and calls callback function 'fn' for each region.
2608 struct walk_memory_regions_data {
2609 walk_memory_regions_fn fn;
2610 void *priv;
2611 target_ulong start;
2612 int prot;
2615 static int walk_memory_regions_end(struct walk_memory_regions_data *data,
2616 target_ulong end, int new_prot)
2618 if (data->start != -1u) {
2619 int rc = data->fn(data->priv, data->start, end, data->prot);
2620 if (rc != 0) {
2621 return rc;
2625 data->start = (new_prot ? end : -1u);
2626 data->prot = new_prot;
2628 return 0;
2631 static int walk_memory_regions_1(struct walk_memory_regions_data *data,
2632 target_ulong base, int level, void **lp)
2634 target_ulong pa;
2635 int i, rc;
2637 if (*lp == NULL) {
2638 return walk_memory_regions_end(data, base, 0);
2641 if (level == 0) {
2642 PageDesc *pd = *lp;
2644 for (i = 0; i < V_L2_SIZE; ++i) {
2645 int prot = pd[i].flags;
2647 pa = base | (i << TARGET_PAGE_BITS);
2648 if (prot != data->prot) {
2649 rc = walk_memory_regions_end(data, pa, prot);
2650 if (rc != 0) {
2651 return rc;
2655 } else {
2656 void **pp = *lp;
2658 for (i = 0; i < V_L2_SIZE; ++i) {
2659 pa = base | ((target_ulong)i <<
2660 (TARGET_PAGE_BITS + V_L2_BITS * level));
2661 rc = walk_memory_regions_1(data, pa, level - 1, pp + i);
2662 if (rc != 0) {
2663 return rc;
2668 return 0;
2671 int walk_memory_regions(void *priv, walk_memory_regions_fn fn)
2673 struct walk_memory_regions_data data;
2674 uintptr_t i, l1_sz = v_l1_size;
2676 data.fn = fn;
2677 data.priv = priv;
2678 data.start = -1u;
2679 data.prot = 0;
2681 for (i = 0; i < l1_sz; i++) {
2682 target_ulong base = i << (v_l1_shift + TARGET_PAGE_BITS);
2683 int rc = walk_memory_regions_1(&data, base, v_l2_levels, l1_map + i);
2684 if (rc != 0) {
2685 return rc;
2689 return walk_memory_regions_end(&data, 0, 0);
2692 static int dump_region(void *priv, target_ulong start,
2693 target_ulong end, unsigned long prot)
2695 FILE *f = (FILE *)priv;
2697 (void) fprintf(f, TARGET_FMT_lx"-"TARGET_FMT_lx
2698 " "TARGET_FMT_lx" %c%c%c\n",
2699 start, end, end - start,
2700 ((prot & PAGE_READ) ? 'r' : '-'),
2701 ((prot & PAGE_WRITE) ? 'w' : '-'),
2702 ((prot & PAGE_EXEC) ? 'x' : '-'));
2704 return 0;
2707 /* dump memory mappings */
2708 void page_dump(FILE *f)
2710 const int length = sizeof(target_ulong) * 2;
2711 (void) fprintf(f, "%-*s %-*s %-*s %s\n",
2712 length, "start", length, "end", length, "size", "prot");
2713 walk_memory_regions(f, dump_region);
2716 int page_get_flags(target_ulong address)
2718 PageDesc *p;
2720 p = page_find(address >> TARGET_PAGE_BITS);
2721 if (!p) {
2722 return 0;
2724 return p->flags;
2727 /* Modify the flags of a page and invalidate the code if necessary.
2728 The flag PAGE_WRITE_ORG is positioned automatically depending
2729 on PAGE_WRITE. The mmap_lock should already be held. */
2730 void page_set_flags(target_ulong start, target_ulong end, int flags)
2732 target_ulong addr, len;
2733 bool reset_target_data;
2735 /* This function should never be called with addresses outside the
2736 guest address space. If this assert fires, it probably indicates
2737 a missing call to h2g_valid. */
2738 assert(end - 1 <= GUEST_ADDR_MAX);
2739 assert(start < end);
2740 assert_memory_lock();
2742 start = start & TARGET_PAGE_MASK;
2743 end = TARGET_PAGE_ALIGN(end);
2745 if (flags & PAGE_WRITE) {
2746 flags |= PAGE_WRITE_ORG;
2748 reset_target_data = !(flags & PAGE_VALID) || (flags & PAGE_RESET);
2749 flags &= ~PAGE_RESET;
2751 for (addr = start, len = end - start;
2752 len != 0;
2753 len -= TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {
2754 PageDesc *p = page_find_alloc(addr >> TARGET_PAGE_BITS, 1);
2756 /* If the write protection bit is set, then we invalidate
2757 the code inside. */
2758 if (!(p->flags & PAGE_WRITE) &&
2759 (flags & PAGE_WRITE) &&
2760 p->first_tb) {
2761 tb_invalidate_phys_page(addr, 0);
2763 if (reset_target_data && p->target_data) {
2764 g_free(p->target_data);
2765 p->target_data = NULL;
2767 p->flags = flags;
2771 void *page_get_target_data(target_ulong address)
2773 PageDesc *p = page_find(address >> TARGET_PAGE_BITS);
2774 return p ? p->target_data : NULL;
2777 void *page_alloc_target_data(target_ulong address, size_t size)
2779 PageDesc *p = page_find(address >> TARGET_PAGE_BITS);
2780 void *ret = NULL;
2782 if (p->flags & PAGE_VALID) {
2783 ret = p->target_data;
2784 if (!ret) {
2785 p->target_data = ret = g_malloc0(size);
2788 return ret;
2791 int page_check_range(target_ulong start, target_ulong len, int flags)
2793 PageDesc *p;
2794 target_ulong end;
2795 target_ulong addr;
2797 /* This function should never be called with addresses outside the
2798 guest address space. If this assert fires, it probably indicates
2799 a missing call to h2g_valid. */
2800 if (TARGET_ABI_BITS > L1_MAP_ADDR_SPACE_BITS) {
2801 assert(start < ((target_ulong)1 << L1_MAP_ADDR_SPACE_BITS));
2804 if (len == 0) {
2805 return 0;
2807 if (start + len - 1 < start) {
2808 /* We've wrapped around. */
2809 return -1;
2812 /* must do before we loose bits in the next step */
2813 end = TARGET_PAGE_ALIGN(start + len);
2814 start = start & TARGET_PAGE_MASK;
2816 for (addr = start, len = end - start;
2817 len != 0;
2818 len -= TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {
2819 p = page_find(addr >> TARGET_PAGE_BITS);
2820 if (!p) {
2821 return -1;
2823 if (!(p->flags & PAGE_VALID)) {
2824 return -1;
2827 if ((flags & PAGE_READ) && !(p->flags & PAGE_READ)) {
2828 return -1;
2830 if (flags & PAGE_WRITE) {
2831 if (!(p->flags & PAGE_WRITE_ORG)) {
2832 return -1;
2834 /* unprotect the page if it was put read-only because it
2835 contains translated code */
2836 if (!(p->flags & PAGE_WRITE)) {
2837 if (!page_unprotect(addr, 0)) {
2838 return -1;
2843 return 0;
2846 /* called from signal handler: invalidate the code and unprotect the
2847 * page. Return 0 if the fault was not handled, 1 if it was handled,
2848 * and 2 if it was handled but the caller must cause the TB to be
2849 * immediately exited. (We can only return 2 if the 'pc' argument is
2850 * non-zero.)
2852 int page_unprotect(target_ulong address, uintptr_t pc)
2854 unsigned int prot;
2855 bool current_tb_invalidated;
2856 PageDesc *p;
2857 target_ulong host_start, host_end, addr;
2859 /* Technically this isn't safe inside a signal handler. However we
2860 know this only ever happens in a synchronous SEGV handler, so in
2861 practice it seems to be ok. */
2862 mmap_lock();
2864 p = page_find(address >> TARGET_PAGE_BITS);
2865 if (!p) {
2866 mmap_unlock();
2867 return 0;
2870 /* if the page was really writable, then we change its
2871 protection back to writable */
2872 if (p->flags & PAGE_WRITE_ORG) {
2873 current_tb_invalidated = false;
2874 if (p->flags & PAGE_WRITE) {
2875 /* If the page is actually marked WRITE then assume this is because
2876 * this thread raced with another one which got here first and
2877 * set the page to PAGE_WRITE and did the TB invalidate for us.
2879 #ifdef TARGET_HAS_PRECISE_SMC
2880 TranslationBlock *current_tb = tcg_tb_lookup(pc);
2881 if (current_tb) {
2882 current_tb_invalidated = tb_cflags(current_tb) & CF_INVALID;
2884 #endif
2885 } else {
2886 host_start = address & qemu_host_page_mask;
2887 host_end = host_start + qemu_host_page_size;
2889 prot = 0;
2890 for (addr = host_start; addr < host_end; addr += TARGET_PAGE_SIZE) {
2891 p = page_find(addr >> TARGET_PAGE_BITS);
2892 p->flags |= PAGE_WRITE;
2893 prot |= p->flags;
2895 /* and since the content will be modified, we must invalidate
2896 the corresponding translated code. */
2897 current_tb_invalidated |= tb_invalidate_phys_page(addr, pc);
2898 #ifdef CONFIG_USER_ONLY
2899 if (DEBUG_TB_CHECK_GATE) {
2900 tb_invalidate_check(addr);
2902 #endif
2904 mprotect((void *)g2h_untagged(host_start), qemu_host_page_size,
2905 prot & PAGE_BITS);
2907 mmap_unlock();
2908 /* If current TB was invalidated return to main loop */
2909 return current_tb_invalidated ? 2 : 1;
2911 mmap_unlock();
2912 return 0;
2914 #endif /* CONFIG_USER_ONLY */
2916 /* This is a wrapper for common code that can not use CONFIG_SOFTMMU */
2917 void tcg_flush_softmmu_tlb(CPUState *cs)
2919 #ifdef CONFIG_SOFTMMU
2920 tlb_flush(cs);
2921 #endif