linux-user: Support f_flags in statfs64 when available.
[qemu/ar7.git] / accel / tcg / translate-all.c
blobd76097296df10a5ac9176209e312534ca3818d73
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 "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"
63 /* #define DEBUG_TB_INVALIDATE */
64 /* #define DEBUG_TB_FLUSH */
65 /* make various TB consistency checks */
66 /* #define DEBUG_TB_CHECK */
68 #ifdef DEBUG_TB_INVALIDATE
69 #define DEBUG_TB_INVALIDATE_GATE 1
70 #else
71 #define DEBUG_TB_INVALIDATE_GATE 0
72 #endif
74 #ifdef DEBUG_TB_FLUSH
75 #define DEBUG_TB_FLUSH_GATE 1
76 #else
77 #define DEBUG_TB_FLUSH_GATE 0
78 #endif
80 #if !defined(CONFIG_USER_ONLY)
81 /* TB consistency checks only implemented for usermode emulation. */
82 #undef DEBUG_TB_CHECK
83 #endif
85 #ifdef DEBUG_TB_CHECK
86 #define DEBUG_TB_CHECK_GATE 1
87 #else
88 #define DEBUG_TB_CHECK_GATE 0
89 #endif
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.
97 #ifdef CONFIG_SOFTMMU
98 #define assert_memory_lock()
99 #else
100 #define assert_memory_lock() tcg_debug_assert(have_mmap_lock())
101 #endif
103 #define SMC_BITMAP_USE_THRESHOLD 10
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;
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
127 * This struct helps us keep track of the locked state of a page, without
128 * bloating &struct PageDesc.
130 * A page lock protects accesses to all fields of &struct PageDesc.
132 * See also: &struct page_collection.
134 struct page_entry {
135 PageDesc *pd;
136 tb_page_addr_t index;
137 bool locked;
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
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.
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.
158 * See also: page_collection_lock().
160 struct page_collection {
161 GTree *tree;
162 struct page_entry *max;
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))
171 #define PAGE_FOR_EACH_TB(pagedesc, tb, n) \
172 TB_FOR_EACH_TAGGED((pagedesc)->first_tb, tb, n, page_next)
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)
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.
181 * TODO: For user mode, see the caveat re host vs guest virtual
182 * address spaces near GUEST_ADDR_MAX.
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
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)
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);
204 * L1 Mapping properties
206 static int v_l1_size;
207 static int v_l1_shift;
208 static int v_l2_levels;
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.
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)
217 static void *l1_map[V_L1_MAX_SIZE];
219 /* code generation context */
220 TCGContext tcg_init_ctx;
221 __thread TCGContext *tcg_ctx;
222 TBContext tb_ctx;
223 bool parallel_cpus;
225 static void page_table_config_init(void)
227 uint32_t v_l1_bits;
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;
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;
240 assert(v_l1_bits <= V_L1_MAX_BITS);
241 assert(v_l1_shift % V_L2_BITS == 0);
242 assert(v_l2_levels >= 0);
245 void cpu_gen_init(void)
247 tcg_context_init(&tcg_init_ctx);
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)
254 int more, byte;
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;
264 *p++ = byte;
265 } while (more);
267 return p;
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)
274 uint8_t *p = *pp;
275 target_long val = 0;
276 int byte, shift = 0;
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;
287 *pp = p;
288 return val;
291 /* Encode the data collected about the instructions while compiling TB.
292 Place the data at BLOCK, and return the number of bytes consumed.
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.
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. */
303 static int encode_search(TranslationBlock *tb, uint8_t *block)
305 uint8_t *highwater = tcg_ctx->code_gen_highwater;
306 uint8_t *p = block;
307 int i, j, n;
309 for (i = 0, n = tb->icount; i < n; ++i) {
310 target_ulong prev;
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];
318 p = encode_sleb128(p, tcg_ctx->gen_insn_data[i][j] - prev);
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);
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;
332 return p - block;
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.
339 static int cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,
340 uintptr_t searched_pc, bool reset_icount)
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
352 searched_pc -= GETPC_ADJ;
354 if (searched_pc < host_pc) {
355 return -1;
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);
364 host_pc += decode_sleb128(&p);
365 if (host_pc > searched_pc) {
366 goto found;
369 return -1;
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;
378 restore_state_to_opc(env, tb, data);
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;
388 void tb_destroy(TranslationBlock *tb)
390 qemu_spin_destroy(&tb->jmp_lock);
393 bool cpu_restore_state(CPUState *cpu, uintptr_t host_pc, bool will_exit)
395 TranslationBlock *tb;
396 bool r = false;
397 uintptr_t check_offset;
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:
403 * - fault during translation (instruction fetch)
404 * - fault from helper (not using GETPC() macro)
406 * Either way we need return early as we can't resolve it here.
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
412 check_offset = host_pc - (uintptr_t) tcg_init_ctx.code_gen_buffer;
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);
424 r = true;
428 return r;
431 static void page_init(void)
433 page_size_init();
434 page_table_config_init();
436 #if defined(CONFIG_BSD) && defined(CONFIG_USER_ONLY)
438 #ifdef HAVE_KINFO_GETVMMAP
439 struct kinfo_vmentry *freep;
440 int i, cnt;
442 freep = kinfo_getvmmap(getpid(), &cnt);
443 if (freep) {
444 mmap_lock();
445 for (i = 0; i < cnt; i++) {
446 unsigned long startaddr, endaddr;
448 startaddr = freep[i].kve_start;
449 endaddr = freep[i].kve_end;
450 if (h2g_valid(startaddr)) {
451 startaddr = h2g(startaddr) & TARGET_PAGE_MASK;
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
464 free(freep);
465 mmap_unlock();
467 #else
468 FILE *f;
470 last_brk = (unsigned long)sbrk(0);
472 f = fopen("/compat/linux/proc/self/maps", "r");
473 if (f) {
474 mmap_lock();
476 do {
477 unsigned long startaddr, endaddr;
478 int n;
480 n = fscanf(f, "%lx-%lx %*[^\n]\n", &startaddr, &endaddr);
482 if (n == 2 && h2g_valid(startaddr)) {
483 startaddr = h2g(startaddr) & TARGET_PAGE_MASK;
485 if (h2g_valid(endaddr)) {
486 endaddr = h2g(endaddr);
487 } else {
488 endaddr = ~0ul;
490 page_set_flags(startaddr, endaddr, PAGE_RESERVED);
492 } while (!feof(f));
494 fclose(f);
495 mmap_unlock();
497 #endif
499 #endif
502 static PageDesc *page_find_alloc(tb_page_addr_t index, int alloc)
504 PageDesc *pd;
505 void **lp;
506 int i;
508 /* Level 1. Always allocated. */
509 lp = l1_map + ((index >> v_l1_shift) & (v_l1_size - 1));
511 /* Level 2..N-1. */
512 for (i = v_l2_levels; i > 0; i--) {
513 void **p = qatomic_rcu_read(lp);
515 if (p == NULL) {
516 void *existing;
518 if (!alloc) {
519 return NULL;
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;
529 lp = p + ((index >> (i * V_L2_BITS)) & (V_L2_SIZE - 1));
532 pd = qatomic_rcu_read(lp);
533 if (pd == NULL) {
534 void *existing;
536 if (!alloc) {
537 return NULL;
539 pd = g_new0(PageDesc, V_L2_SIZE);
540 #ifndef CONFIG_USER_ONLY
542 int i;
544 for (i = 0; i < V_L2_SIZE; i++) {
545 qemu_spin_init(&pd[i].lock);
548 #endif
549 existing = qatomic_cmpxchg(lp, NULL, pd);
550 if (unlikely(existing)) {
551 #ifndef CONFIG_USER_ONLY
553 int i;
555 for (i = 0; i < V_L2_SIZE; i++) {
556 qemu_spin_destroy(&pd[i].lock);
559 #endif
560 g_free(pd);
561 pd = existing;
565 return pd + (index & (V_L2_SIZE - 1));
568 static inline PageDesc *page_find(tb_page_addr_t index)
570 return page_find_alloc(index, 0);
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);
576 /* In user-mode page locks aren't used; mmap_lock is enough */
577 #ifdef CONFIG_USER_ONLY
579 #define assert_page_locked(pd) tcg_debug_assert(have_mmap_lock())
581 static inline void page_lock(PageDesc *pd)
584 static inline void page_unlock(PageDesc *pd)
587 static inline void page_lock_tb(const TranslationBlock *tb)
590 static inline void page_unlock_tb(const TranslationBlock *tb)
593 struct page_collection *
594 page_collection_lock(tb_page_addr_t start, tb_page_addr_t end)
596 return NULL;
599 void page_collection_unlock(struct page_collection *set)
601 #else /* !CONFIG_USER_ONLY */
603 #ifdef CONFIG_DEBUG_TCG
605 static __thread GHashTable *ht_pages_locked_debug;
607 static void ht_pages_locked_debug_init(void)
609 if (ht_pages_locked_debug) {
610 return;
612 ht_pages_locked_debug = g_hash_table_new(NULL, NULL);
615 static bool page_is_locked(const PageDesc *pd)
617 PageDesc *found;
619 ht_pages_locked_debug_init();
620 found = g_hash_table_lookup(ht_pages_locked_debug, pd);
621 return !!found;
624 static void page_lock__debug(PageDesc *pd)
626 ht_pages_locked_debug_init();
627 g_assert(!page_is_locked(pd));
628 g_hash_table_insert(ht_pages_locked_debug, pd, pd);
631 static void page_unlock__debug(const PageDesc *pd)
633 bool removed;
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);
641 static void
642 do_assert_page_locked(const PageDesc *pd, const char *file, int line)
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();
651 #define assert_page_locked(pd) do_assert_page_locked(pd, __FILE__, __LINE__)
653 void assert_no_pages_locked(void)
655 ht_pages_locked_debug_init();
656 g_assert(g_hash_table_size(ht_pages_locked_debug) == 0);
659 #else /* !CONFIG_DEBUG_TCG */
661 #define assert_page_locked(pd)
663 static inline void page_lock__debug(const PageDesc *pd)
667 static inline void page_unlock__debug(const PageDesc *pd)
671 #endif /* CONFIG_DEBUG_TCG */
673 static inline void page_lock(PageDesc *pd)
675 page_lock__debug(pd);
676 qemu_spin_lock(&pd->lock);
679 static inline void page_unlock(PageDesc *pd)
681 qemu_spin_unlock(&pd->lock);
682 page_unlock__debug(pd);
685 /* lock the page(s) of a TB in the correct acquisition order */
686 static inline void page_lock_tb(const TranslationBlock *tb)
688 page_lock_pair(NULL, tb->page_addr[0], NULL, tb->page_addr[1], 0);
691 static inline void page_unlock_tb(const TranslationBlock *tb)
693 PageDesc *p1 = page_find(tb->page_addr[0] >> TARGET_PAGE_BITS);
695 page_unlock(p1);
696 if (unlikely(tb->page_addr[1] != -1)) {
697 PageDesc *p2 = page_find(tb->page_addr[1] >> TARGET_PAGE_BITS);
699 if (p2 != p1) {
700 page_unlock(p2);
705 static inline struct page_entry *
706 page_entry_new(PageDesc *pd, tb_page_addr_t index)
708 struct page_entry *pe = g_malloc(sizeof(*pe));
710 pe->index = index;
711 pe->pd = pd;
712 pe->locked = false;
713 return pe;
716 static void page_entry_destroy(gpointer p)
718 struct page_entry *pe = p;
720 g_assert(pe->locked);
721 page_unlock(pe->pd);
722 g_free(pe);
725 /* returns false on success */
726 static bool page_entry_trylock(struct page_entry *pe)
728 bool busy;
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);
736 return busy;
739 static void do_page_entry_lock(struct page_entry *pe)
741 page_lock(pe->pd);
742 g_assert(!pe->locked);
743 pe->locked = true;
746 static gboolean page_entry_lock(gpointer key, gpointer value, gpointer data)
748 struct page_entry *pe = value;
750 do_page_entry_lock(pe);
751 return FALSE;
754 static gboolean page_entry_unlock(gpointer key, gpointer value, gpointer data)
756 struct page_entry *pe = value;
758 if (pe->locked) {
759 pe->locked = false;
760 page_unlock(pe->pd);
762 return FALSE;
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.
769 static bool page_trylock_add(struct page_collection *set, tb_page_addr_t addr)
771 tb_page_addr_t index = addr >> TARGET_PAGE_BITS;
772 struct page_entry *pe;
773 PageDesc *pd;
775 pe = g_tree_lookup(set->tree, &index);
776 if (pe) {
777 return false;
780 pd = page_find(index);
781 if (pd == NULL) {
782 return false;
785 pe = page_entry_new(pd, index);
786 g_tree_insert(set->tree, &pe->index, pe);
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.
792 if (set->max == NULL || pe->index > set->max->index) {
793 set->max = pe;
794 do_page_entry_lock(pe);
795 return false;
798 * Try to acquire out-of-order lock; if busy, return busy so that we acquire
799 * locks in order.
801 return page_entry_trylock(pe);
804 static gint tb_page_addr_cmp(gconstpointer ap, gconstpointer bp, gpointer udata)
806 tb_page_addr_t a = *(const tb_page_addr_t *)ap;
807 tb_page_addr_t b = *(const tb_page_addr_t *)bp;
809 if (a == b) {
810 return 0;
811 } else if (a < b) {
812 return -1;
814 return 1;
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.
822 struct page_collection *
823 page_collection_lock(tb_page_addr_t start, tb_page_addr_t end)
825 struct page_collection *set = g_malloc(sizeof(*set));
826 tb_page_addr_t index;
827 PageDesc *pd;
829 start >>= TARGET_PAGE_BITS;
830 end >>= TARGET_PAGE_BITS;
831 g_assert(start <= end);
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();
838 retry:
839 g_tree_foreach(set->tree, page_entry_lock, NULL);
841 for (index = start; index <= end; index++) {
842 TranslationBlock *tb;
843 int n;
845 pd = page_find(index);
846 if (pd == NULL) {
847 continue;
849 if (page_trylock_add(set, index << TARGET_PAGE_BITS)) {
850 g_tree_foreach(set->tree, page_entry_unlock, NULL);
851 goto retry;
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;
864 return set;
867 void page_collection_unlock(struct page_collection *set)
869 /* entries are unlocked and freed via page_entry_destroy */
870 g_tree_destroy(set->tree);
871 g_free(set);
874 #endif /* !CONFIG_USER_ONLY */
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)
879 PageDesc *p1, *p2;
880 tb_page_addr_t page1;
881 tb_page_addr_t page2;
883 assert_memory_lock();
884 g_assert(phys1 != -1);
886 page1 = phys1 >> TARGET_PAGE_BITS;
887 page2 = phys2 >> TARGET_PAGE_BITS;
889 p1 = page_find_alloc(page1, alloc);
890 if (ret_p1) {
891 *ret_p1 = p1;
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;
901 return;
903 p2 = page_find_alloc(page2, alloc);
904 if (ret_p2) {
905 *ret_p2 = p2;
907 if (page1 < page2) {
908 page_lock(p1);
909 page_lock(p2);
910 } else {
911 page_lock(p2);
912 page_lock(p1);
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)
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
944 #if TCG_TARGET_REG_BITS == 32
945 #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (32 * MiB)
946 #ifdef CONFIG_USER_ONLY
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.
952 #define USE_STATIC_CODE_GEN_BUFFER
953 #endif
954 #else /* TCG_TARGET_REG_BITS == 64 */
955 #ifdef CONFIG_USER_ONLY
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.
961 #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (128 * MiB)
962 #else
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.
968 #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (1 * GiB)
969 #endif
970 #endif
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)
976 static inline size_t size_code_gen_buffer(size_t tb_size)
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);
987 if (tb_size < MIN_CODE_GEN_BUFFER_SIZE) {
988 tb_size = MIN_CODE_GEN_BUFFER_SIZE;
990 if (tb_size > MAX_CODE_GEN_BUFFER_SIZE) {
991 tb_size = MAX_CODE_GEN_BUFFER_SIZE;
993 return tb_size;
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)
1001 return ((uintptr_t)addr ^ ((uintptr_t)addr + size)) & ~0x0ffffffful;
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)
1009 void *buf2 = (void *)(((uintptr_t)buf1 + size1) & ~0x0ffffffful);
1010 size_t size2 = buf1 + size1 - buf2;
1012 size1 = buf2 - buf1;
1013 if (size1 < size2) {
1014 size1 = size2;
1015 buf1 = buf2;
1018 tcg_ctx->code_gen_buffer_size = size1;
1019 return buf1;
1021 #endif
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)));
1027 static inline void *alloc_code_gen_buffer(void)
1029 void *buf = static_code_gen_buffer;
1030 void *end = static_code_gen_buffer + sizeof(static_code_gen_buffer);
1031 size_t size;
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);
1037 size = end - buf;
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);
1044 tcg_ctx->code_gen_buffer_size = size;
1046 #ifdef __mips__
1047 if (cross_256mb(buf, size)) {
1048 buf = split_cross_256mb(buf, size);
1049 size = tcg_ctx->code_gen_buffer_size;
1051 #endif
1053 if (qemu_mprotect_rwx(buf, size)) {
1054 abort();
1056 qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);
1058 return buf;
1060 #elif defined(_WIN32)
1061 static inline void *alloc_code_gen_buffer(void)
1063 size_t size = tcg_ctx->code_gen_buffer_size;
1064 return VirtualAlloc(NULL, size, MEM_RESERVE | MEM_COMMIT,
1065 PAGE_EXECUTE_READWRITE);
1067 #else
1068 static inline void *alloc_code_gen_buffer(void)
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;
1075 buf = mmap(NULL, size, prot, flags, -1, 0);
1076 if (buf == MAP_FAILED) {
1077 return NULL;
1080 #ifdef __mips__
1081 if (cross_256mb(buf, size)) {
1083 * Try again, with the original still mapped, to avoid re-acquiring
1084 * the same 256mb crossing.
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;
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);
1107 size = size2;
1108 break;
1110 buf = buf2;
1112 #endif
1114 /* Request large pages for the buffer. */
1115 qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);
1117 return buf;
1119 #endif /* USE_STATIC_CODE_GEN_BUFFER, WIN32, POSIX */
1121 static inline void code_gen_alloc(size_t tb_size)
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);
1131 static bool tb_cmp(const void *ap, const void *bp)
1133 const TranslationBlock *a = ap;
1134 const TranslationBlock *b = bp;
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];
1145 static void tb_htable_init(void)
1147 unsigned int mode = QHT_MODE_AUTO_RESIZE;
1149 qht_init(&tb_ctx.htable, tb_cmp, CODE_GEN_HTABLE_SIZE, mode);
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)
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
1169 /* call with @p->lock held */
1170 static inline void invalidate_page_bitmap(PageDesc *p)
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
1180 /* Set to NULL all the 'first_tb' fields in all PageDescs. */
1181 static void page_flush_tb_1(int level, void **lp)
1183 int i;
1185 if (*lp == NULL) {
1186 return;
1188 if (level == 0) {
1189 PageDesc *pd = *lp;
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]);
1197 } else {
1198 void **pp = *lp;
1200 for (i = 0; i < V_L2_SIZE; ++i) {
1201 page_flush_tb_1(level - 1, pp + i);
1206 static void page_flush_tb(void)
1208 int i, l1_sz = v_l1_size;
1210 for (i = 0; i < l1_sz; i++) {
1211 page_flush_tb_1(v_l2_levels, l1_map + i);
1215 static gboolean tb_host_size_iter(gpointer key, gpointer value, gpointer data)
1217 const TranslationBlock *tb = value;
1218 size_t *size = data;
1220 *size += tb->tc.size;
1221 return false;
1224 /* flush all the translation blocks */
1225 static void do_tb_flush(CPUState *cpu, run_on_cpu_data tb_flush_count)
1227 bool did_flush = false;
1229 mmap_lock();
1230 /* If it is already been done on request of another CPU,
1231 * just retry.
1233 if (tb_ctx.tb_flush_count != tb_flush_count.host_int) {
1234 goto done;
1236 did_flush = true;
1238 if (DEBUG_TB_FLUSH_GATE) {
1239 size_t nb_tbs = tcg_nb_tbs();
1240 size_t host_size = 0;
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);
1247 CPU_FOREACH(cpu) {
1248 cpu_tb_jmp_cache_clear(cpu);
1251 qht_reset_size(&tb_ctx.htable, CODE_GEN_HTABLE_SIZE);
1252 page_flush_tb();
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);
1259 done:
1260 mmap_unlock();
1261 if (did_flush) {
1262 qemu_plugin_flush_cb();
1266 void tb_flush(CPUState *cpu)
1268 if (tcg_enabled()) {
1269 unsigned tb_flush_count = qatomic_mb_read(&tb_ctx.tb_flush_count);
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));
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).
1286 #ifdef CONFIG_USER_ONLY
1288 static void do_tb_invalidate_check(void *p, uint32_t hash, void *userp)
1290 TranslationBlock *tb = p;
1291 target_ulong addr = *(target_ulong *)userp;
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);
1299 /* verify that all the pages have correct rights for code
1301 * Called with mmap_lock held.
1303 static void tb_invalidate_check(target_ulong address)
1305 address &= TARGET_PAGE_MASK;
1306 qht_iter(&tb_ctx.htable, do_tb_invalidate_check, &address);
1309 static void do_tb_page_check(void *p, uint32_t hash, void *userp)
1311 TranslationBlock *tb = p;
1312 int flags1, flags2;
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);
1322 /* verify that all the pages have correct rights for code */
1323 static void tb_page_check(void)
1325 qht_iter(&tb_ctx.htable, do_tb_page_check, NULL);
1328 #endif /* CONFIG_USER_ONLY */
1331 * user-mode: call with mmap_lock held
1332 * !user-mode: call with @pd->lock held
1334 static inline void tb_page_remove(PageDesc *pd, TranslationBlock *tb)
1336 TranslationBlock *tb1;
1337 uintptr_t *pprev;
1338 unsigned int n1;
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;
1347 pprev = &tb1->page_next[n1];
1349 g_assert_not_reached();
1352 /* remove @orig from its @n_orig-th jump list */
1353 static inline void tb_remove_from_jmp_list(TranslationBlock *orig, int n_orig)
1355 uintptr_t ptr, ptr_locked;
1356 TranslationBlock *dest;
1357 TranslationBlock *tb;
1358 uintptr_t *pprev;
1359 int n;
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;
1368 qemu_spin_lock(&dest->jmp_lock);
1370 * While acquiring the lock, the jump might have been removed if the
1371 * destination TB was invalidated; check again.
1373 ptr_locked = qatomic_read(&orig->jmp_dest[n_orig]);
1374 if (ptr_locked != ptr) {
1375 qemu_spin_unlock(&dest->jmp_lock);
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.
1381 g_assert(ptr_locked == 1 && dest->cflags & CF_INVALID);
1382 return;
1385 * We first acquired the lock, and since the destination pointer matches,
1386 * we know for sure that @orig is in the jmp list.
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;
1396 pprev = &tb->jmp_list_next[n];
1398 g_assert_not_reached();
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)
1405 uintptr_t addr = (uintptr_t)(tb->tc.ptr + tb->jmp_reset_offset[n]);
1406 tb_set_jmp_target(tb, n, addr);
1409 /* remove any jumps to the TB */
1410 static inline void tb_jmp_unlink(TranslationBlock *dest)
1412 TranslationBlock *tb;
1413 int n;
1415 qemu_spin_lock(&dest->jmp_lock);
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 */
1422 dest->jmp_list_head = (uintptr_t)NULL;
1424 qemu_spin_unlock(&dest->jmp_lock);
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.
1432 static void do_tb_phys_invalidate(TranslationBlock *tb, bool rm_from_page_list)
1434 CPUState *cpu;
1435 PageDesc *p;
1436 uint32_t h;
1437 tb_page_addr_t phys_pc;
1439 assert_memory_lock();
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);
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;
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);
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);
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);
1479 /* suppress any remaining jumps to this TB */
1480 tb_jmp_unlink(tb);
1482 qatomic_set(&tcg_ctx->tb_phys_invalidate_count,
1483 tcg_ctx->tb_phys_invalidate_count + 1);
1486 static void tb_phys_invalidate__locked(TranslationBlock *tb)
1488 do_tb_phys_invalidate(tb, true);
1491 /* invalidate one TB
1493 * Called with mmap_lock held in user-mode.
1495 void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr)
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);
1506 #ifdef CONFIG_SOFTMMU
1507 /* call with @p->lock held */
1508 static void build_page_bitmap(PageDesc *p)
1510 int n, tb_start, tb_end;
1511 TranslationBlock *tb;
1513 assert_page_locked(p);
1514 p->code_bitmap = bitmap_new(TARGET_PAGE_SIZE);
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;
1526 } else {
1527 tb_start = 0;
1528 tb_end = ((tb->pc + tb->size) & ~TARGET_PAGE_MASK);
1530 bitmap_set(p->code_bitmap, tb_start, tb_end - tb_start);
1533 #endif
1535 /* add the tb in the target page and protect it if necessary
1537 * Called with mmap_lock held for user-mode emulation.
1538 * Called with @p->lock held in !user-mode.
1540 static inline void tb_page_add(PageDesc *p, TranslationBlock *tb,
1541 unsigned int n, tb_page_addr_t page_addr)
1543 #ifndef CONFIG_USER_ONLY
1544 bool page_already_protected;
1545 #endif
1547 assert_page_locked(p);
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);
1557 #if defined(CONFIG_USER_ONLY)
1558 if (p->flags & PAGE_WRITE) {
1559 target_ulong addr;
1560 PageDesc *p2;
1561 int prot;
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) {
1570 p2 = page_find(addr >> TARGET_PAGE_BITS);
1571 if (!p2) {
1572 continue;
1574 prot |= p2->flags;
1575 p2->flags &= ~PAGE_WRITE;
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);
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);
1590 #endif
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.
1596 * Called with mmap_lock held for user-mode emulation.
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.
1603 static TranslationBlock *
1604 tb_link_page(TranslationBlock *tb, tb_page_addr_t phys_pc,
1605 tb_page_addr_t phys_page2)
1607 PageDesc *p;
1608 PageDesc *p2 = NULL;
1610 assert_memory_lock();
1612 if (phys_pc == -1) {
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.
1618 assert(tb->cflags & CF_NOCACHE);
1619 tb->page_addr[0] = tb->page_addr[1] = -1;
1620 return tb;
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.
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;
1639 if (!(tb->cflags & CF_NOCACHE)) {
1640 void *existing_tb = NULL;
1641 uint32_t h;
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);
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);
1656 tb = existing_tb;
1660 if (p2 && p2 != p) {
1661 page_unlock(p2);
1663 page_unlock(p);
1665 #ifdef CONFIG_USER_ONLY
1666 if (DEBUG_TB_CHECK_GATE) {
1667 tb_page_check();
1669 #endif
1670 return tb;
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)
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
1689 assert_memory_lock();
1691 phys_pc = get_page_addr_code(env, pc);
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;
1699 cflags &= ~CF_CLUSTER_MASK;
1700 cflags |= cpu->cluster_index << CF_CLUSTER_SHIFT;
1702 max_insns = cflags & CF_COUNT_MASK;
1703 if (max_insns == 0) {
1704 max_insns = CF_COUNT_MASK;
1706 if (max_insns > TCG_MAX_INSNS) {
1707 max_insns = TCG_MAX_INSNS;
1709 if (cpu->singlestep_enabled || singlestep) {
1710 max_insns = 1;
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);
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:
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
1741 tcg_func_start(tcg_ctx);
1743 tcg_ctx->cpu = env_cpu(env);
1744 gen_intermediate_code(cpu, tb, max_insns);
1745 tcg_ctx->cpu = NULL;
1747 trace_translate_block(tb, tb->pc, tb->tc.ptr);
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;
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
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:
1773 * Overflow of code_gen_buffer, or the current slice of it.
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.
1781 goto buffer_overflow;
1783 case -2:
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.
1790 * Try again with half as many insns as we attempted this time.
1791 * If a single insn overflows, there's a bug somewhere...
1793 max_insns = tb->icount;
1794 assert(max_insns > 1);
1795 max_insns /= 2;
1796 goto tb_overflow;
1798 default:
1799 g_assert_not_reached();
1802 search_size = encode_search(tb, (void *)gen_code_buf + gen_code_size);
1803 if (unlikely(search_size < 0)) {
1804 goto buffer_overflow;
1806 tb->tc.size = gen_code_size;
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
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;
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;
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);
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.
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;
1850 insn++;
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);
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));
1874 qemu_log("\n");
1875 qemu_log_flush();
1876 qemu_log_unlock(logfile);
1878 #endif
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));
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;
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);
1896 if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) {
1897 tb_reset_jump(tb, 1);
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);
1907 * No explicit memory barrier is required -- tb_link_page() makes the
1908 * TB visible in a consistent state.
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;
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;
1920 tcg_tb_insert(tb);
1921 return tb;
1925 * @p must be non-NULL.
1926 * user-mode: call with mmap_lock held.
1927 * !user-mode: call with all @pages locked.
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)
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 */
1949 assert_page_locked(p);
1951 #if defined(TARGET_HAS_PRECISE_SMC)
1952 if (cpu != NULL) {
1953 env = cpu->env_ptr;
1955 #endif
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);
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);
1979 if (current_tb == tb &&
1980 (tb_cflags(current_tb) & CF_COUNT_MASK) != 1) {
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.
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);
1993 #endif /* TARGET_HAS_PRECISE_SMC */
1994 tb_phys_invalidate__locked(tb);
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);
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);
2012 #endif
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.
2022 * Called with mmap_lock held for user-mode emulation
2024 void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end)
2026 struct page_collection *pages;
2027 PageDesc *p;
2029 assert_memory_lock();
2031 p = page_find(start >> TARGET_PAGE_BITS);
2032 if (p == NULL) {
2033 return;
2035 pages = page_collection_lock(start, end);
2036 tb_invalidate_phys_page_range__locked(pages, p, start, end, 0);
2037 page_collection_unlock(pages);
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.
2047 * Called with mmap_lock held for user-mode emulation.
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
2055 struct page_collection *pages;
2056 tb_page_addr_t next;
2058 assert_memory_lock();
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);
2067 if (pd == NULL) {
2068 continue;
2070 tb_invalidate_phys_page_range__locked(pages, pd, start, bound, 0);
2072 page_collection_unlock(pages);
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.
2080 * Call with all @pages in the range [@start, @start + len[ locked.
2082 void tb_invalidate_phys_page_fast(struct page_collection *pages,
2083 tb_page_addr_t start, int len,
2084 uintptr_t retaddr)
2086 PageDesc *p;
2088 assert_memory_lock();
2090 p = page_find(start >> TARGET_PAGE_BITS);
2091 if (!p) {
2092 return;
2095 assert_page_locked(p);
2096 if (!p->code_bitmap &&
2097 ++p->code_write_count >= SMC_BITMAP_USE_THRESHOLD) {
2098 build_page_bitmap(p);
2100 if (p->code_bitmap) {
2101 unsigned int nr;
2102 unsigned long b;
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;
2109 } else {
2110 do_invalidate:
2111 tb_invalidate_phys_page_range__locked(pages, p, start, start + len,
2112 retaddr);
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).
2122 static bool tb_invalidate_phys_page(tb_page_addr_t addr, uintptr_t pc)
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
2137 assert_memory_lock();
2139 addr &= TARGET_PAGE_MASK;
2140 p = page_find(addr >> TARGET_PAGE_BITS);
2141 if (!p) {
2142 return false;
2145 #ifdef TARGET_HAS_PRECISE_SMC
2146 if (p->first_tb && pc != 0) {
2147 current_tb = tcg_tb_lookup(pc);
2149 if (cpu != NULL) {
2150 env = cpu->env_ptr;
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 */
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);
2169 #endif /* TARGET_HAS_PRECISE_SMC */
2170 tb_phys_invalidate(tb, addr);
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;
2179 #endif
2181 return false;
2183 #endif
2185 /* user-mode: call with mmap_lock held */
2186 void tb_check_watchpoint(CPUState *cpu, uintptr_t retaddr)
2188 TranslationBlock *tb;
2190 assert_memory_lock();
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;
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);
2213 #ifndef CONFIG_USER_ONLY
2214 /* in deterministic execution mode, instructions doing device I/Os
2215 * must be at the end of the TB.
2217 * Called by softmmu_template.h, with iothread mutex not held.
2219 void cpu_io_recompile(CPUState *cpu, uintptr_t retaddr)
2221 #if defined(TARGET_MIPS) || defined(TARGET_SH4)
2222 CPUArchState *env = cpu->env_ptr;
2223 #endif
2224 TranslationBlock *tb;
2225 uint32_t n;
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);
2232 cpu_restore_state_from_tb(cpu, tb, retaddr, true);
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;
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;
2255 #endif
2257 /* Generate a new TB executing the I/O insn. */
2258 cpu->cflags_next_tb = curr_cflags() | CF_LAST_IO | n;
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);
2266 tcg_tb_remove(tb);
2267 tb_destroy(tb);
2270 /* TODO: If env->pc != tb->pc (i.e. the faulting instruction was not
2271 * the first in the TB) then we end up generating a whole new TB and
2272 * repeating the fault, which is horribly inefficient.
2273 * Better would be to execute just this insn uncached, or generate a
2274 * second new TB.
2276 cpu_loop_exit_noexc(cpu);
2279 static void tb_jmp_cache_clear_page(CPUState *cpu, target_ulong page_addr)
2281 unsigned int i, i0 = tb_jmp_cache_hash_page(page_addr);
2283 for (i = 0; i < TB_JMP_PAGE_SIZE; i++) {
2284 qatomic_set(&cpu->tb_jmp_cache[i0 + i], NULL);
2288 void tb_flush_jmp_cache(CPUState *cpu, target_ulong addr)
2290 /* Discard jump cache entries for any tb which might potentially
2291 overlap the flushed page. */
2292 tb_jmp_cache_clear_page(cpu, addr - TARGET_PAGE_SIZE);
2293 tb_jmp_cache_clear_page(cpu, addr);
2296 static void print_qht_statistics(struct qht_stats hst)
2298 uint32_t hgram_opts;
2299 size_t hgram_bins;
2300 char *hgram;
2302 if (!hst.head_buckets) {
2303 return;
2305 qemu_printf("TB hash buckets %zu/%zu (%0.2f%% head buckets used)\n",
2306 hst.used_head_buckets, hst.head_buckets,
2307 (double)hst.used_head_buckets / hst.head_buckets * 100);
2309 hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
2310 hgram_opts |= QDIST_PR_100X | QDIST_PR_PERCENT;
2311 if (qdist_xmax(&hst.occupancy) - qdist_xmin(&hst.occupancy) == 1) {
2312 hgram_opts |= QDIST_PR_NODECIMAL;
2314 hgram = qdist_pr(&hst.occupancy, 10, hgram_opts);
2315 qemu_printf("TB hash occupancy %0.2f%% avg chain occ. Histogram: %s\n",
2316 qdist_avg(&hst.occupancy) * 100, hgram);
2317 g_free(hgram);
2319 hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
2320 hgram_bins = qdist_xmax(&hst.chain) - qdist_xmin(&hst.chain);
2321 if (hgram_bins > 10) {
2322 hgram_bins = 10;
2323 } else {
2324 hgram_bins = 0;
2325 hgram_opts |= QDIST_PR_NODECIMAL | QDIST_PR_NOBINRANGE;
2327 hgram = qdist_pr(&hst.chain, hgram_bins, hgram_opts);
2328 qemu_printf("TB hash avg chain %0.3f buckets. Histogram: %s\n",
2329 qdist_avg(&hst.chain), hgram);
2330 g_free(hgram);
2333 struct tb_tree_stats {
2334 size_t nb_tbs;
2335 size_t host_size;
2336 size_t target_size;
2337 size_t max_target_size;
2338 size_t direct_jmp_count;
2339 size_t direct_jmp2_count;
2340 size_t cross_page;
2343 static gboolean tb_tree_stats_iter(gpointer key, gpointer value, gpointer data)
2345 const TranslationBlock *tb = value;
2346 struct tb_tree_stats *tst = data;
2348 tst->nb_tbs++;
2349 tst->host_size += tb->tc.size;
2350 tst->target_size += tb->size;
2351 if (tb->size > tst->max_target_size) {
2352 tst->max_target_size = tb->size;
2354 if (tb->page_addr[1] != -1) {
2355 tst->cross_page++;
2357 if (tb->jmp_reset_offset[0] != TB_JMP_RESET_OFFSET_INVALID) {
2358 tst->direct_jmp_count++;
2359 if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) {
2360 tst->direct_jmp2_count++;
2363 return false;
2366 void dump_exec_info(void)
2368 struct tb_tree_stats tst = {};
2369 struct qht_stats hst;
2370 size_t nb_tbs, flush_full, flush_part, flush_elide;
2372 tcg_tb_foreach(tb_tree_stats_iter, &tst);
2373 nb_tbs = tst.nb_tbs;
2374 /* XXX: avoid using doubles ? */
2375 qemu_printf("Translation buffer state:\n");
2377 * Report total code size including the padding and TB structs;
2378 * otherwise users might think "-tb-size" is not honoured.
2379 * For avg host size we use the precise numbers from tb_tree_stats though.
2381 qemu_printf("gen code size %zu/%zu\n",
2382 tcg_code_size(), tcg_code_capacity());
2383 qemu_printf("TB count %zu\n", nb_tbs);
2384 qemu_printf("TB avg target size %zu max=%zu bytes\n",
2385 nb_tbs ? tst.target_size / nb_tbs : 0,
2386 tst.max_target_size);
2387 qemu_printf("TB avg host size %zu bytes (expansion ratio: %0.1f)\n",
2388 nb_tbs ? tst.host_size / nb_tbs : 0,
2389 tst.target_size ? (double)tst.host_size / tst.target_size : 0);
2390 qemu_printf("cross page TB count %zu (%zu%%)\n", tst.cross_page,
2391 nb_tbs ? (tst.cross_page * 100) / nb_tbs : 0);
2392 qemu_printf("direct jump count %zu (%zu%%) (2 jumps=%zu %zu%%)\n",
2393 tst.direct_jmp_count,
2394 nb_tbs ? (tst.direct_jmp_count * 100) / nb_tbs : 0,
2395 tst.direct_jmp2_count,
2396 nb_tbs ? (tst.direct_jmp2_count * 100) / nb_tbs : 0);
2398 qht_statistics_init(&tb_ctx.htable, &hst);
2399 print_qht_statistics(hst);
2400 qht_statistics_destroy(&hst);
2402 qemu_printf("\nStatistics:\n");
2403 qemu_printf("TB flush count %u\n",
2404 qatomic_read(&tb_ctx.tb_flush_count));
2405 qemu_printf("TB invalidate count %zu\n",
2406 tcg_tb_phys_invalidate_count());
2408 tlb_flush_counts(&flush_full, &flush_part, &flush_elide);
2409 qemu_printf("TLB full flushes %zu\n", flush_full);
2410 qemu_printf("TLB partial flushes %zu\n", flush_part);
2411 qemu_printf("TLB elided flushes %zu\n", flush_elide);
2412 tcg_dump_info();
2415 void dump_opcount_info(void)
2417 tcg_dump_op_count();
2420 #else /* CONFIG_USER_ONLY */
2422 void cpu_interrupt(CPUState *cpu, int mask)
2424 g_assert(qemu_mutex_iothread_locked());
2425 cpu->interrupt_request |= mask;
2426 qatomic_set(&cpu_neg(cpu)->icount_decr.u16.high, -1);
2430 * Walks guest process memory "regions" one by one
2431 * and calls callback function 'fn' for each region.
2433 struct walk_memory_regions_data {
2434 walk_memory_regions_fn fn;
2435 void *priv;
2436 target_ulong start;
2437 int prot;
2440 static int walk_memory_regions_end(struct walk_memory_regions_data *data,
2441 target_ulong end, int new_prot)
2443 if (data->start != -1u) {
2444 int rc = data->fn(data->priv, data->start, end, data->prot);
2445 if (rc != 0) {
2446 return rc;
2450 data->start = (new_prot ? end : -1u);
2451 data->prot = new_prot;
2453 return 0;
2456 static int walk_memory_regions_1(struct walk_memory_regions_data *data,
2457 target_ulong base, int level, void **lp)
2459 target_ulong pa;
2460 int i, rc;
2462 if (*lp == NULL) {
2463 return walk_memory_regions_end(data, base, 0);
2466 if (level == 0) {
2467 PageDesc *pd = *lp;
2469 for (i = 0; i < V_L2_SIZE; ++i) {
2470 int prot = pd[i].flags;
2472 pa = base | (i << TARGET_PAGE_BITS);
2473 if (prot != data->prot) {
2474 rc = walk_memory_regions_end(data, pa, prot);
2475 if (rc != 0) {
2476 return rc;
2480 } else {
2481 void **pp = *lp;
2483 for (i = 0; i < V_L2_SIZE; ++i) {
2484 pa = base | ((target_ulong)i <<
2485 (TARGET_PAGE_BITS + V_L2_BITS * level));
2486 rc = walk_memory_regions_1(data, pa, level - 1, pp + i);
2487 if (rc != 0) {
2488 return rc;
2493 return 0;
2496 int walk_memory_regions(void *priv, walk_memory_regions_fn fn)
2498 struct walk_memory_regions_data data;
2499 uintptr_t i, l1_sz = v_l1_size;
2501 data.fn = fn;
2502 data.priv = priv;
2503 data.start = -1u;
2504 data.prot = 0;
2506 for (i = 0; i < l1_sz; i++) {
2507 target_ulong base = i << (v_l1_shift + TARGET_PAGE_BITS);
2508 int rc = walk_memory_regions_1(&data, base, v_l2_levels, l1_map + i);
2509 if (rc != 0) {
2510 return rc;
2514 return walk_memory_regions_end(&data, 0, 0);
2517 static int dump_region(void *priv, target_ulong start,
2518 target_ulong end, unsigned long prot)
2520 FILE *f = (FILE *)priv;
2522 (void) fprintf(f, TARGET_FMT_lx"-"TARGET_FMT_lx
2523 " "TARGET_FMT_lx" %c%c%c\n",
2524 start, end, end - start,
2525 ((prot & PAGE_READ) ? 'r' : '-'),
2526 ((prot & PAGE_WRITE) ? 'w' : '-'),
2527 ((prot & PAGE_EXEC) ? 'x' : '-'));
2529 return 0;
2532 /* dump memory mappings */
2533 void page_dump(FILE *f)
2535 const int length = sizeof(target_ulong) * 2;
2536 (void) fprintf(f, "%-*s %-*s %-*s %s\n",
2537 length, "start", length, "end", length, "size", "prot");
2538 walk_memory_regions(f, dump_region);
2541 int page_get_flags(target_ulong address)
2543 PageDesc *p;
2545 p = page_find(address >> TARGET_PAGE_BITS);
2546 if (!p) {
2547 return 0;
2549 return p->flags;
2552 /* Modify the flags of a page and invalidate the code if necessary.
2553 The flag PAGE_WRITE_ORG is positioned automatically depending
2554 on PAGE_WRITE. The mmap_lock should already be held. */
2555 void page_set_flags(target_ulong start, target_ulong end, int flags)
2557 target_ulong addr, len;
2559 /* This function should never be called with addresses outside the
2560 guest address space. If this assert fires, it probably indicates
2561 a missing call to h2g_valid. */
2562 assert(end - 1 <= GUEST_ADDR_MAX);
2563 assert(start < end);
2564 assert_memory_lock();
2566 start = start & TARGET_PAGE_MASK;
2567 end = TARGET_PAGE_ALIGN(end);
2569 if (flags & PAGE_WRITE) {
2570 flags |= PAGE_WRITE_ORG;
2573 for (addr = start, len = end - start;
2574 len != 0;
2575 len -= TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {
2576 PageDesc *p = page_find_alloc(addr >> TARGET_PAGE_BITS, 1);
2578 /* If the write protection bit is set, then we invalidate
2579 the code inside. */
2580 if (!(p->flags & PAGE_WRITE) &&
2581 (flags & PAGE_WRITE) &&
2582 p->first_tb) {
2583 tb_invalidate_phys_page(addr, 0);
2585 p->flags = flags;
2589 int page_check_range(target_ulong start, target_ulong len, int flags)
2591 PageDesc *p;
2592 target_ulong end;
2593 target_ulong addr;
2595 /* This function should never be called with addresses outside the
2596 guest address space. If this assert fires, it probably indicates
2597 a missing call to h2g_valid. */
2598 if (TARGET_ABI_BITS > L1_MAP_ADDR_SPACE_BITS) {
2599 assert(start < ((target_ulong)1 << L1_MAP_ADDR_SPACE_BITS));
2602 if (len == 0) {
2603 return 0;
2605 if (start + len - 1 < start) {
2606 /* We've wrapped around. */
2607 return -1;
2610 /* must do before we loose bits in the next step */
2611 end = TARGET_PAGE_ALIGN(start + len);
2612 start = start & TARGET_PAGE_MASK;
2614 for (addr = start, len = end - start;
2615 len != 0;
2616 len -= TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {
2617 p = page_find(addr >> TARGET_PAGE_BITS);
2618 if (!p) {
2619 return -1;
2621 if (!(p->flags & PAGE_VALID)) {
2622 return -1;
2625 if ((flags & PAGE_READ) && !(p->flags & PAGE_READ)) {
2626 return -1;
2628 if (flags & PAGE_WRITE) {
2629 if (!(p->flags & PAGE_WRITE_ORG)) {
2630 return -1;
2632 /* unprotect the page if it was put read-only because it
2633 contains translated code */
2634 if (!(p->flags & PAGE_WRITE)) {
2635 if (!page_unprotect(addr, 0)) {
2636 return -1;
2641 return 0;
2644 /* called from signal handler: invalidate the code and unprotect the
2645 * page. Return 0 if the fault was not handled, 1 if it was handled,
2646 * and 2 if it was handled but the caller must cause the TB to be
2647 * immediately exited. (We can only return 2 if the 'pc' argument is
2648 * non-zero.)
2650 int page_unprotect(target_ulong address, uintptr_t pc)
2652 unsigned int prot;
2653 bool current_tb_invalidated;
2654 PageDesc *p;
2655 target_ulong host_start, host_end, addr;
2657 /* Technically this isn't safe inside a signal handler. However we
2658 know this only ever happens in a synchronous SEGV handler, so in
2659 practice it seems to be ok. */
2660 mmap_lock();
2662 p = page_find(address >> TARGET_PAGE_BITS);
2663 if (!p) {
2664 mmap_unlock();
2665 return 0;
2668 /* if the page was really writable, then we change its
2669 protection back to writable */
2670 if (p->flags & PAGE_WRITE_ORG) {
2671 current_tb_invalidated = false;
2672 if (p->flags & PAGE_WRITE) {
2673 /* If the page is actually marked WRITE then assume this is because
2674 * this thread raced with another one which got here first and
2675 * set the page to PAGE_WRITE and did the TB invalidate for us.
2677 #ifdef TARGET_HAS_PRECISE_SMC
2678 TranslationBlock *current_tb = tcg_tb_lookup(pc);
2679 if (current_tb) {
2680 current_tb_invalidated = tb_cflags(current_tb) & CF_INVALID;
2682 #endif
2683 } else {
2684 host_start = address & qemu_host_page_mask;
2685 host_end = host_start + qemu_host_page_size;
2687 prot = 0;
2688 for (addr = host_start; addr < host_end; addr += TARGET_PAGE_SIZE) {
2689 p = page_find(addr >> TARGET_PAGE_BITS);
2690 p->flags |= PAGE_WRITE;
2691 prot |= p->flags;
2693 /* and since the content will be modified, we must invalidate
2694 the corresponding translated code. */
2695 current_tb_invalidated |= tb_invalidate_phys_page(addr, pc);
2696 #ifdef CONFIG_USER_ONLY
2697 if (DEBUG_TB_CHECK_GATE) {
2698 tb_invalidate_check(addr);
2700 #endif
2702 mprotect((void *)g2h(host_start), qemu_host_page_size,
2703 prot & PAGE_BITS);
2705 mmap_unlock();
2706 /* If current TB was invalidated return to main loop */
2707 return current_tb_invalidated ? 2 : 1;
2709 mmap_unlock();
2710 return 0;
2712 #endif /* CONFIG_USER_ONLY */
2714 /* This is a wrapper for common code that can not use CONFIG_SOFTMMU */
2715 void tcg_flush_softmmu_tlb(CPUState *cs)
2717 #ifdef CONFIG_SOFTMMU
2718 tlb_flush(cs);
2719 #endif