Merge tag 'v2.9.0-rc3'
[qemu/ar7.git] / translate-all.c
blobb6d103417a7804317627c0e2b9ab723090768073
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 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/>.
19 #ifdef _WIN32
20 #include <windows.h>
21 #endif
22 #include "qemu/osdep.h"
24 #include "qemu-common.h"
25 #define NO_CPU_IO_DEFS
26 #include "cpu.h"
27 #include "trace-root.h"
28 #include "disas/disas.h"
29 #include "exec/exec-all.h"
30 #include "tcg.h"
31 #if defined(CONFIG_USER_ONLY)
32 #include "qemu.h"
33 #if defined(TARGET_X86_64)
34 #include "vsyscall.h"
35 #endif
36 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
37 #include <sys/param.h>
38 #if __FreeBSD_version >= 700104
39 #define HAVE_KINFO_GETVMMAP
40 #define sigqueue sigqueue_freebsd /* avoid redefinition */
41 #include <sys/proc.h>
42 #include <machine/profile.h>
43 #define _KERNEL
44 #include <sys/user.h>
45 #undef _KERNEL
46 #undef sigqueue
47 #include <libutil.h>
48 #endif
49 #endif
50 #else
51 #include "exec/address-spaces.h"
52 #endif
54 #include "exec/cputlb.h"
55 #include "exec/tb-hash.h"
56 #include "translate-all.h"
57 #include "qemu/bitmap.h"
58 #include "qemu/timer.h"
59 #include "qemu/main-loop.h"
60 #include "exec/log.h"
61 #include "sysemu/cpus.h"
63 /* #define DEBUG_TB_INVALIDATE */
64 /* #define DEBUG_TB_FLUSH */
65 /* make various TB consistency checks */
66 /* #define DEBUG_TB_CHECK */
68 #if !defined(CONFIG_USER_ONLY)
69 /* TB consistency checks only implemented for usermode emulation. */
70 #undef DEBUG_TB_CHECK
71 #endif
73 /* Access to the various translations structures need to be serialised via locks
74 * for consistency. This is automatic for SoftMMU based system
75 * emulation due to its single threaded nature. In user-mode emulation
76 * access to the memory related structures are protected with the
77 * mmap_lock.
79 #ifdef CONFIG_SOFTMMU
80 #define assert_memory_lock() tcg_debug_assert(have_tb_lock)
81 #else
82 #define assert_memory_lock() tcg_debug_assert(have_mmap_lock())
83 #endif
85 #define SMC_BITMAP_USE_THRESHOLD 10
87 typedef struct PageDesc {
88 /* list of TBs intersecting this ram page */
89 TranslationBlock *first_tb;
90 #ifdef CONFIG_SOFTMMU
91 /* in order to optimize self modifying code, we count the number
92 of lookups we do to a given page to use a bitmap */
93 unsigned int code_write_count;
94 unsigned long *code_bitmap;
95 #else
96 unsigned long flags;
97 #endif
98 } PageDesc;
100 /* In system mode we want L1_MAP to be based on ram offsets,
101 while in user mode we want it to be based on virtual addresses. */
102 #if !defined(CONFIG_USER_ONLY)
103 #if HOST_LONG_BITS < TARGET_PHYS_ADDR_SPACE_BITS
104 # define L1_MAP_ADDR_SPACE_BITS HOST_LONG_BITS
105 #else
106 # define L1_MAP_ADDR_SPACE_BITS TARGET_PHYS_ADDR_SPACE_BITS
107 #endif
108 #else
109 # define L1_MAP_ADDR_SPACE_BITS TARGET_VIRT_ADDR_SPACE_BITS
110 #endif
112 /* Size of the L2 (and L3, etc) page tables. */
113 #define V_L2_BITS 10
114 #define V_L2_SIZE (1 << V_L2_BITS)
116 uintptr_t qemu_host_page_size;
117 intptr_t qemu_host_page_mask;
120 * L1 Mapping properties
122 static int v_l1_size;
123 static int v_l1_shift;
124 static int v_l2_levels;
126 /* The bottom level has pointers to PageDesc, and is indexed by
127 * anything from 4 to (V_L2_BITS + 3) bits, depending on target page size.
129 #define V_L1_MIN_BITS 4
130 #define V_L1_MAX_BITS (V_L2_BITS + 3)
131 #define V_L1_MAX_SIZE (1 << V_L1_MAX_BITS)
133 static void *l1_map[V_L1_MAX_SIZE];
135 /* code generation context */
136 TCGContext tcg_ctx;
137 bool parallel_cpus;
139 /* translation block context */
140 __thread int have_tb_lock;
142 static void page_table_config_init(void)
144 uint32_t v_l1_bits;
146 assert(TARGET_PAGE_BITS);
147 /* The bits remaining after N lower levels of page tables. */
148 v_l1_bits = (L1_MAP_ADDR_SPACE_BITS - TARGET_PAGE_BITS) % V_L2_BITS;
149 if (v_l1_bits < V_L1_MIN_BITS) {
150 v_l1_bits += V_L2_BITS;
153 v_l1_size = 1 << v_l1_bits;
154 v_l1_shift = L1_MAP_ADDR_SPACE_BITS - TARGET_PAGE_BITS - v_l1_bits;
155 v_l2_levels = v_l1_shift / V_L2_BITS - 1;
157 assert(v_l1_bits <= V_L1_MAX_BITS);
158 assert(v_l1_shift % V_L2_BITS == 0);
159 assert(v_l2_levels >= 0);
162 #define assert_tb_locked() tcg_debug_assert(have_tb_lock)
163 #define assert_tb_unlocked() tcg_debug_assert(!have_tb_lock)
165 void tb_lock(void)
167 assert_tb_unlocked();
168 qemu_mutex_lock(&tcg_ctx.tb_ctx.tb_lock);
169 have_tb_lock++;
172 void tb_unlock(void)
174 assert_tb_locked();
175 have_tb_lock--;
176 qemu_mutex_unlock(&tcg_ctx.tb_ctx.tb_lock);
179 void tb_lock_reset(void)
181 if (have_tb_lock) {
182 qemu_mutex_unlock(&tcg_ctx.tb_ctx.tb_lock);
183 have_tb_lock = 0;
187 static TranslationBlock *tb_find_pc(uintptr_t tc_ptr);
189 void cpu_gen_init(void)
191 tcg_context_init(&tcg_ctx);
194 /* Encode VAL as a signed leb128 sequence at P.
195 Return P incremented past the encoded value. */
196 static uint8_t *encode_sleb128(uint8_t *p, target_long val)
198 int more, byte;
200 do {
201 byte = val & 0x7f;
202 val >>= 7;
203 more = !((val == 0 && (byte & 0x40) == 0)
204 || (val == -1 && (byte & 0x40) != 0));
205 if (more) {
206 byte |= 0x80;
208 *p++ = byte;
209 } while (more);
211 return p;
214 /* Decode a signed leb128 sequence at *PP; increment *PP past the
215 decoded value. Return the decoded value. */
216 static target_long decode_sleb128(uint8_t **pp)
218 uint8_t *p = *pp;
219 target_long val = 0;
220 int byte, shift = 0;
222 do {
223 byte = *p++;
224 val |= (target_ulong)(byte & 0x7f) << shift;
225 shift += 7;
226 } while (byte & 0x80);
227 if (shift < TARGET_LONG_BITS && (byte & 0x40)) {
228 val |= -(target_ulong)1 << shift;
231 *pp = p;
232 return val;
235 /* Encode the data collected about the instructions while compiling TB.
236 Place the data at BLOCK, and return the number of bytes consumed.
238 The logical table consisits of TARGET_INSN_START_WORDS target_ulong's,
239 which come from the target's insn_start data, followed by a uintptr_t
240 which comes from the host pc of the end of the code implementing the insn.
242 Each line of the table is encoded as sleb128 deltas from the previous
243 line. The seed for the first line is { tb->pc, 0..., tb->tc_ptr }.
244 That is, the first column is seeded with the guest pc, the last column
245 with the host pc, and the middle columns with zeros. */
247 static int encode_search(TranslationBlock *tb, uint8_t *block)
249 uint8_t *highwater = tcg_ctx.code_gen_highwater;
250 uint8_t *p = block;
251 int i, j, n;
253 tb->tc_search = block;
255 for (i = 0, n = tb->icount; i < n; ++i) {
256 target_ulong prev;
258 for (j = 0; j < TARGET_INSN_START_WORDS; ++j) {
259 if (i == 0) {
260 prev = (j == 0 ? tb->pc : 0);
261 } else {
262 prev = tcg_ctx.gen_insn_data[i - 1][j];
264 p = encode_sleb128(p, tcg_ctx.gen_insn_data[i][j] - prev);
266 prev = (i == 0 ? 0 : tcg_ctx.gen_insn_end_off[i - 1]);
267 p = encode_sleb128(p, tcg_ctx.gen_insn_end_off[i] - prev);
269 /* Test for (pending) buffer overflow. The assumption is that any
270 one row beginning below the high water mark cannot overrun
271 the buffer completely. Thus we can test for overflow after
272 encoding a row without having to check during encoding. */
273 if (unlikely(p > highwater)) {
274 return -1;
278 return p - block;
281 /* The cpu state corresponding to 'searched_pc' is restored.
282 * Called with tb_lock held.
284 static int cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,
285 uintptr_t searched_pc)
287 target_ulong data[TARGET_INSN_START_WORDS] = { tb->pc };
288 uintptr_t host_pc = (uintptr_t)tb->tc_ptr;
289 CPUArchState *env = cpu->env_ptr;
290 uint8_t *p = tb->tc_search;
291 int i, j, num_insns = tb->icount;
292 #ifdef CONFIG_PROFILER
293 int64_t ti = profile_getclock();
294 #endif
296 searched_pc -= GETPC_ADJ;
298 if (searched_pc < host_pc) {
299 return -1;
302 /* Reconstruct the stored insn data while looking for the point at
303 which the end of the insn exceeds the searched_pc. */
304 for (i = 0; i < num_insns; ++i) {
305 for (j = 0; j < TARGET_INSN_START_WORDS; ++j) {
306 data[j] += decode_sleb128(&p);
308 host_pc += decode_sleb128(&p);
309 if (host_pc > searched_pc) {
310 goto found;
313 return -1;
315 found:
316 if (tb->cflags & CF_USE_ICOUNT) {
317 assert(use_icount);
318 /* Reset the cycle counter to the start of the block. */
319 cpu->icount_decr.u16.low += num_insns;
320 /* Clear the IO flag. */
321 cpu->can_do_io = 0;
323 cpu->icount_decr.u16.low -= i;
324 restore_state_to_opc(env, tb, data);
326 #ifdef CONFIG_PROFILER
327 tcg_ctx.restore_time += profile_getclock() - ti;
328 tcg_ctx.restore_count++;
329 #endif
330 return 0;
333 bool cpu_restore_state(CPUState *cpu, uintptr_t retaddr)
335 TranslationBlock *tb;
336 bool r = false;
338 /* A retaddr of zero is invalid so we really shouldn't have ended
339 * up here. The target code has likely forgotten to check retaddr
340 * != 0 before attempting to restore state. We return early to
341 * avoid blowing up on a recursive tb_lock(). The target must have
342 * previously survived a failed cpu_restore_state because
343 * tb_find_pc(0) would have failed anyway. It still should be
344 * fixed though.
347 if (!retaddr) {
348 return r;
351 tb_lock();
352 tb = tb_find_pc(retaddr);
353 if (tb) {
354 cpu_restore_state_from_tb(cpu, tb, retaddr);
355 if (tb->cflags & CF_NOCACHE) {
356 /* one-shot translation, invalidate it immediately */
357 tb_phys_invalidate(tb, -1);
358 tb_free(tb);
360 r = true;
362 tb_unlock();
364 return r;
367 void page_size_init(void)
369 /* NOTE: we can always suppose that qemu_host_page_size >=
370 TARGET_PAGE_SIZE */
371 qemu_real_host_page_size = getpagesize();
372 qemu_real_host_page_mask = -(intptr_t)qemu_real_host_page_size;
373 if (qemu_host_page_size == 0) {
374 qemu_host_page_size = qemu_real_host_page_size;
376 if (qemu_host_page_size < TARGET_PAGE_SIZE) {
377 qemu_host_page_size = TARGET_PAGE_SIZE;
379 qemu_host_page_mask = -(intptr_t)qemu_host_page_size;
382 static void page_init(void)
384 page_size_init();
385 page_table_config_init();
387 #if defined(CONFIG_BSD) && defined(CONFIG_USER_ONLY)
389 #ifdef HAVE_KINFO_GETVMMAP
390 struct kinfo_vmentry *freep;
391 int i, cnt;
393 freep = kinfo_getvmmap(getpid(), &cnt);
394 if (freep) {
395 mmap_lock();
396 for (i = 0; i < cnt; i++) {
397 unsigned long startaddr, endaddr;
399 startaddr = freep[i].kve_start;
400 endaddr = freep[i].kve_end;
401 if (h2g_valid(startaddr)) {
402 startaddr = h2g(startaddr) & TARGET_PAGE_MASK;
404 if (h2g_valid(endaddr)) {
405 endaddr = h2g(endaddr);
406 page_set_flags(startaddr, endaddr, PAGE_RESERVED);
407 } else {
408 #if TARGET_ABI_BITS <= L1_MAP_ADDR_SPACE_BITS
409 endaddr = ~0ul;
410 page_set_flags(startaddr, endaddr, PAGE_RESERVED);
411 #endif
415 free(freep);
416 mmap_unlock();
418 #else
419 FILE *f;
421 last_brk = (unsigned long)sbrk(0);
423 f = fopen("/compat/linux/proc/self/maps", "r");
424 if (f) {
425 mmap_lock();
427 do {
428 unsigned long startaddr, endaddr;
429 int n;
431 n = fscanf(f, "%lx-%lx %*[^\n]\n", &startaddr, &endaddr);
433 if (n == 2 && h2g_valid(startaddr)) {
434 startaddr = h2g(startaddr) & TARGET_PAGE_MASK;
436 if (h2g_valid(endaddr)) {
437 endaddr = h2g(endaddr);
438 } else {
439 endaddr = ~0ul;
441 page_set_flags(startaddr, endaddr, PAGE_RESERVED);
443 } while (!feof(f));
445 fclose(f);
446 mmap_unlock();
448 #endif
450 #endif
453 /* If alloc=1:
454 * Called with tb_lock held for system emulation.
455 * Called with mmap_lock held for user-mode emulation.
457 static PageDesc *page_find_alloc(tb_page_addr_t index, int alloc)
459 PageDesc *pd;
460 void **lp;
461 int i;
463 if (alloc) {
464 assert_memory_lock();
467 /* Level 1. Always allocated. */
468 lp = l1_map + ((index >> v_l1_shift) & (v_l1_size - 1));
470 /* Level 2..N-1. */
471 for (i = v_l2_levels; i > 0; i--) {
472 void **p = atomic_rcu_read(lp);
474 if (p == NULL) {
475 if (!alloc) {
476 return NULL;
478 p = g_new0(void *, V_L2_SIZE);
479 atomic_rcu_set(lp, p);
482 lp = p + ((index >> (i * V_L2_BITS)) & (V_L2_SIZE - 1));
485 pd = atomic_rcu_read(lp);
486 if (pd == NULL) {
487 if (!alloc) {
488 return NULL;
490 pd = g_new0(PageDesc, V_L2_SIZE);
491 atomic_rcu_set(lp, pd);
494 return pd + (index & (V_L2_SIZE - 1));
497 static inline PageDesc *page_find(tb_page_addr_t index)
499 return page_find_alloc(index, 0);
502 #if defined(CONFIG_USER_ONLY)
503 /* Currently it is not recommended to allocate big chunks of data in
504 user mode. It will change when a dedicated libc will be used. */
505 /* ??? 64-bit hosts ought to have no problem mmaping data outside the
506 region in which the guest needs to run. Revisit this. */
507 #define USE_STATIC_CODE_GEN_BUFFER
508 #endif
510 /* Minimum size of the code gen buffer. This number is randomly chosen,
511 but not so small that we can't have a fair number of TB's live. */
512 #define MIN_CODE_GEN_BUFFER_SIZE (1024u * 1024)
514 /* Maximum size of the code gen buffer we'd like to use. Unless otherwise
515 indicated, this is constrained by the range of direct branches on the
516 host cpu, as used by the TCG implementation of goto_tb. */
517 #if defined(__x86_64__)
518 # define MAX_CODE_GEN_BUFFER_SIZE (2ul * 1024 * 1024 * 1024)
519 #elif defined(__sparc__)
520 # define MAX_CODE_GEN_BUFFER_SIZE (2ul * 1024 * 1024 * 1024)
521 #elif defined(__powerpc64__)
522 # define MAX_CODE_GEN_BUFFER_SIZE (2ul * 1024 * 1024 * 1024)
523 #elif defined(__powerpc__)
524 # define MAX_CODE_GEN_BUFFER_SIZE (32u * 1024 * 1024)
525 #elif defined(__aarch64__)
526 # define MAX_CODE_GEN_BUFFER_SIZE (128ul * 1024 * 1024)
527 #elif defined(__arm__)
528 # define MAX_CODE_GEN_BUFFER_SIZE (16u * 1024 * 1024)
529 #elif defined(__s390x__)
530 /* We have a +- 4GB range on the branches; leave some slop. */
531 # define MAX_CODE_GEN_BUFFER_SIZE (3ul * 1024 * 1024 * 1024)
532 #elif defined(__mips__)
533 /* We have a 256MB branch region, but leave room to make sure the
534 main executable is also within that region. */
535 # define MAX_CODE_GEN_BUFFER_SIZE (128ul * 1024 * 1024)
536 #else
537 # define MAX_CODE_GEN_BUFFER_SIZE ((size_t)-1)
538 #endif
540 #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (32u * 1024 * 1024)
542 #define DEFAULT_CODE_GEN_BUFFER_SIZE \
543 (DEFAULT_CODE_GEN_BUFFER_SIZE_1 < MAX_CODE_GEN_BUFFER_SIZE \
544 ? DEFAULT_CODE_GEN_BUFFER_SIZE_1 : MAX_CODE_GEN_BUFFER_SIZE)
546 static inline size_t size_code_gen_buffer(size_t tb_size)
548 /* Size the buffer. */
549 if (tb_size == 0) {
550 #ifdef USE_STATIC_CODE_GEN_BUFFER
551 tb_size = DEFAULT_CODE_GEN_BUFFER_SIZE;
552 #else
553 /* ??? Needs adjustments. */
554 /* ??? If we relax the requirement that CONFIG_USER_ONLY use the
555 static buffer, we could size this on RESERVED_VA, on the text
556 segment size of the executable, or continue to use the default. */
557 tb_size = (unsigned long)(ram_size / 4);
558 #endif
560 if (tb_size < MIN_CODE_GEN_BUFFER_SIZE) {
561 tb_size = MIN_CODE_GEN_BUFFER_SIZE;
563 if (tb_size > MAX_CODE_GEN_BUFFER_SIZE) {
564 tb_size = MAX_CODE_GEN_BUFFER_SIZE;
566 return tb_size;
569 #ifdef __mips__
570 /* In order to use J and JAL within the code_gen_buffer, we require
571 that the buffer not cross a 256MB boundary. */
572 static inline bool cross_256mb(void *addr, size_t size)
574 return ((uintptr_t)addr ^ ((uintptr_t)addr + size)) & ~0x0ffffffful;
577 /* We weren't able to allocate a buffer without crossing that boundary,
578 so make do with the larger portion of the buffer that doesn't cross.
579 Returns the new base of the buffer, and adjusts code_gen_buffer_size. */
580 static inline void *split_cross_256mb(void *buf1, size_t size1)
582 void *buf2 = (void *)(((uintptr_t)buf1 + size1) & ~0x0ffffffful);
583 size_t size2 = buf1 + size1 - buf2;
585 size1 = buf2 - buf1;
586 if (size1 < size2) {
587 size1 = size2;
588 buf1 = buf2;
591 tcg_ctx.code_gen_buffer_size = size1;
592 return buf1;
594 #endif
596 #ifdef USE_STATIC_CODE_GEN_BUFFER
597 static uint8_t static_code_gen_buffer[DEFAULT_CODE_GEN_BUFFER_SIZE]
598 __attribute__((aligned(CODE_GEN_ALIGN)));
600 # ifdef _WIN32
601 static inline void do_protect(void *addr, long size, int prot)
603 DWORD old_protect;
604 VirtualProtect(addr, size, prot, &old_protect);
607 static inline void map_exec(void *addr, long size)
609 do_protect(addr, size, PAGE_EXECUTE_READWRITE);
612 static inline void map_none(void *addr, long size)
614 do_protect(addr, size, PAGE_NOACCESS);
616 # else
617 static inline void do_protect(void *addr, long size, int prot)
619 uintptr_t start, end;
621 start = (uintptr_t)addr;
622 start &= qemu_real_host_page_mask;
624 end = (uintptr_t)addr + size;
625 end = ROUND_UP(end, qemu_real_host_page_size);
627 mprotect((void *)start, end - start, prot);
630 static inline void map_exec(void *addr, long size)
632 do_protect(addr, size, PROT_READ | PROT_WRITE | PROT_EXEC);
635 static inline void map_none(void *addr, long size)
637 do_protect(addr, size, PROT_NONE);
639 # endif /* WIN32 */
641 static inline void *alloc_code_gen_buffer(void)
643 void *buf = static_code_gen_buffer;
644 size_t full_size, size;
646 /* The size of the buffer, rounded down to end on a page boundary. */
647 full_size = (((uintptr_t)buf + sizeof(static_code_gen_buffer))
648 & qemu_real_host_page_mask) - (uintptr_t)buf;
650 /* Reserve a guard page. */
651 size = full_size - qemu_real_host_page_size;
653 /* Honor a command-line option limiting the size of the buffer. */
654 if (size > tcg_ctx.code_gen_buffer_size) {
655 size = (((uintptr_t)buf + tcg_ctx.code_gen_buffer_size)
656 & qemu_real_host_page_mask) - (uintptr_t)buf;
658 tcg_ctx.code_gen_buffer_size = size;
660 #ifdef __mips__
661 if (cross_256mb(buf, size)) {
662 buf = split_cross_256mb(buf, size);
663 size = tcg_ctx.code_gen_buffer_size;
665 #endif
667 map_exec(buf, size);
668 map_none(buf + size, qemu_real_host_page_size);
669 qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);
671 return buf;
673 #elif defined(_WIN32)
674 static inline void *alloc_code_gen_buffer(void)
676 size_t size = tcg_ctx.code_gen_buffer_size;
677 void *buf1, *buf2;
679 /* Perform the allocation in two steps, so that the guard page
680 is reserved but uncommitted. */
681 buf1 = VirtualAlloc(NULL, size + qemu_real_host_page_size,
682 MEM_RESERVE, PAGE_NOACCESS);
683 if (buf1 != NULL) {
684 buf2 = VirtualAlloc(buf1, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
685 assert(buf1 == buf2);
688 return buf1;
690 #else
691 static inline void *alloc_code_gen_buffer(void)
693 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
694 uintptr_t start = 0;
695 size_t size = tcg_ctx.code_gen_buffer_size;
696 void *buf;
698 /* Constrain the position of the buffer based on the host cpu.
699 Note that these addresses are chosen in concert with the
700 addresses assigned in the relevant linker script file. */
701 # if defined(__PIE__) || defined(__PIC__)
702 /* Don't bother setting a preferred location if we're building
703 a position-independent executable. We're more likely to get
704 an address near the main executable if we let the kernel
705 choose the address. */
706 # elif defined(__x86_64__) && defined(MAP_32BIT)
707 /* Force the memory down into low memory with the executable.
708 Leave the choice of exact location with the kernel. */
709 flags |= MAP_32BIT;
710 /* Cannot expect to map more than 800MB in low memory. */
711 if (size > 800u * 1024 * 1024) {
712 tcg_ctx.code_gen_buffer_size = size = 800u * 1024 * 1024;
714 # elif defined(__sparc__)
715 start = 0x40000000ul;
716 # elif defined(__s390x__)
717 start = 0x90000000ul;
718 # elif defined(__mips__)
719 # if _MIPS_SIM == _ABI64
720 start = 0x128000000ul;
721 # else
722 start = 0x08000000ul;
723 # endif
724 # endif
726 buf = mmap((void *)start, size + qemu_real_host_page_size,
727 PROT_NONE, flags, -1, 0);
728 if (buf == MAP_FAILED) {
729 return NULL;
732 #ifdef __mips__
733 if (cross_256mb(buf, size)) {
734 /* Try again, with the original still mapped, to avoid re-acquiring
735 that 256mb crossing. This time don't specify an address. */
736 size_t size2;
737 void *buf2 = mmap(NULL, size + qemu_real_host_page_size,
738 PROT_NONE, flags, -1, 0);
739 switch ((int)(buf2 != MAP_FAILED)) {
740 case 1:
741 if (!cross_256mb(buf2, size)) {
742 /* Success! Use the new buffer. */
743 munmap(buf, size + qemu_real_host_page_size);
744 break;
746 /* Failure. Work with what we had. */
747 munmap(buf2, size + qemu_real_host_page_size);
748 /* fallthru */
749 default:
750 /* Split the original buffer. Free the smaller half. */
751 buf2 = split_cross_256mb(buf, size);
752 size2 = tcg_ctx.code_gen_buffer_size;
753 if (buf == buf2) {
754 munmap(buf + size2 + qemu_real_host_page_size, size - size2);
755 } else {
756 munmap(buf, size - size2);
758 size = size2;
759 break;
761 buf = buf2;
763 #endif
765 /* Make the final buffer accessible. The guard page at the end
766 will remain inaccessible with PROT_NONE. */
767 mprotect(buf, size, PROT_WRITE | PROT_READ | PROT_EXEC);
769 /* Request large pages for the buffer. */
770 qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);
772 return buf;
774 #endif /* USE_STATIC_CODE_GEN_BUFFER, WIN32, POSIX */
776 static inline void code_gen_alloc(size_t tb_size)
778 tcg_ctx.code_gen_buffer_size = size_code_gen_buffer(tb_size);
779 tcg_ctx.code_gen_buffer = alloc_code_gen_buffer();
780 if (tcg_ctx.code_gen_buffer == NULL) {
781 fprintf(stderr, "Could not allocate dynamic translator buffer\n");
782 exit(1);
785 /* Estimate a good size for the number of TBs we can support. We
786 still haven't deducted the prologue from the buffer size here,
787 but that's minimal and won't affect the estimate much. */
788 tcg_ctx.code_gen_max_blocks
789 = tcg_ctx.code_gen_buffer_size / CODE_GEN_AVG_BLOCK_SIZE;
790 tcg_ctx.tb_ctx.tbs = g_new(TranslationBlock, tcg_ctx.code_gen_max_blocks);
792 qemu_mutex_init(&tcg_ctx.tb_ctx.tb_lock);
795 static void tb_htable_init(void)
797 unsigned int mode = QHT_MODE_AUTO_RESIZE;
799 qht_init(&tcg_ctx.tb_ctx.htable, CODE_GEN_HTABLE_SIZE, mode);
802 /* Must be called before using the QEMU cpus. 'tb_size' is the size
803 (in bytes) allocated to the translation buffer. Zero means default
804 size. */
805 void tcg_exec_init(uintptr_t tb_size)
807 cpu_gen_init();
808 page_init();
809 tb_htable_init();
810 code_gen_alloc(tb_size);
811 #if defined(CONFIG_SOFTMMU)
812 /* There's no guest base to take into account, so go ahead and
813 initialize the prologue now. */
814 tcg_prologue_init(&tcg_ctx);
815 #endif
818 bool tcg_enabled(void)
820 return tcg_ctx.code_gen_buffer != NULL;
824 * Allocate a new translation block. Flush the translation buffer if
825 * too many translation blocks or too much generated code.
827 * Called with tb_lock held.
829 static TranslationBlock *tb_alloc(target_ulong pc)
831 TranslationBlock *tb;
833 assert_tb_locked();
835 if (tcg_ctx.tb_ctx.nb_tbs >= tcg_ctx.code_gen_max_blocks) {
836 return NULL;
838 tb = &tcg_ctx.tb_ctx.tbs[tcg_ctx.tb_ctx.nb_tbs++];
839 tb->pc = pc;
840 tb->cflags = 0;
841 tb->invalid = false;
842 return tb;
845 /* Called with tb_lock held. */
846 void tb_free(TranslationBlock *tb)
848 assert_tb_locked();
850 /* In practice this is mostly used for single use temporary TB
851 Ignore the hard cases and just back up if this TB happens to
852 be the last one generated. */
853 if (tcg_ctx.tb_ctx.nb_tbs > 0 &&
854 tb == &tcg_ctx.tb_ctx.tbs[tcg_ctx.tb_ctx.nb_tbs - 1]) {
855 tcg_ctx.code_gen_ptr = tb->tc_ptr;
856 tcg_ctx.tb_ctx.nb_tbs--;
860 static inline void invalidate_page_bitmap(PageDesc *p)
862 #ifdef CONFIG_SOFTMMU
863 g_free(p->code_bitmap);
864 p->code_bitmap = NULL;
865 p->code_write_count = 0;
866 #endif
869 /* Set to NULL all the 'first_tb' fields in all PageDescs. */
870 static void page_flush_tb_1(int level, void **lp)
872 int i;
874 if (*lp == NULL) {
875 return;
877 if (level == 0) {
878 PageDesc *pd = *lp;
880 for (i = 0; i < V_L2_SIZE; ++i) {
881 pd[i].first_tb = NULL;
882 invalidate_page_bitmap(pd + i);
884 } else {
885 void **pp = *lp;
887 for (i = 0; i < V_L2_SIZE; ++i) {
888 page_flush_tb_1(level - 1, pp + i);
893 static void page_flush_tb(void)
895 int i, l1_sz = v_l1_size;
897 for (i = 0; i < l1_sz; i++) {
898 page_flush_tb_1(v_l2_levels, l1_map + i);
902 /* flush all the translation blocks */
903 static void do_tb_flush(CPUState *cpu, run_on_cpu_data tb_flush_count)
905 tb_lock();
907 /* If it is already been done on request of another CPU,
908 * just retry.
910 if (tcg_ctx.tb_ctx.tb_flush_count != tb_flush_count.host_int) {
911 goto done;
914 #if defined(DEBUG_TB_FLUSH)
915 printf("qemu: flush code_size=%ld nb_tbs=%d avg_tb_size=%ld\n",
916 (unsigned long)(tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer),
917 tcg_ctx.tb_ctx.nb_tbs, tcg_ctx.tb_ctx.nb_tbs > 0 ?
918 ((unsigned long)(tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer)) /
919 tcg_ctx.tb_ctx.nb_tbs : 0);
920 #endif
921 if ((unsigned long)(tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer)
922 > tcg_ctx.code_gen_buffer_size) {
923 cpu_abort(cpu, "Internal error: code buffer overflow\n");
926 CPU_FOREACH(cpu) {
927 int i;
929 for (i = 0; i < TB_JMP_CACHE_SIZE; ++i) {
930 atomic_set(&cpu->tb_jmp_cache[i], NULL);
934 tcg_ctx.tb_ctx.nb_tbs = 0;
935 qht_reset_size(&tcg_ctx.tb_ctx.htable, CODE_GEN_HTABLE_SIZE);
936 page_flush_tb();
938 tcg_ctx.code_gen_ptr = tcg_ctx.code_gen_buffer;
939 /* XXX: flush processor icache at this point if cache flush is
940 expensive */
941 atomic_mb_set(&tcg_ctx.tb_ctx.tb_flush_count,
942 tcg_ctx.tb_ctx.tb_flush_count + 1);
944 done:
945 tb_unlock();
948 void tb_flush(CPUState *cpu)
950 if (tcg_enabled()) {
951 unsigned tb_flush_count = atomic_mb_read(&tcg_ctx.tb_ctx.tb_flush_count);
952 async_safe_run_on_cpu(cpu, do_tb_flush,
953 RUN_ON_CPU_HOST_INT(tb_flush_count));
957 #ifdef DEBUG_TB_CHECK
959 static void
960 do_tb_invalidate_check(struct qht *ht, void *p, uint32_t hash, void *userp)
962 TranslationBlock *tb = p;
963 target_ulong addr = *(target_ulong *)userp;
965 if (!(addr + TARGET_PAGE_SIZE <= tb->pc || addr >= tb->pc + tb->size)) {
966 printf("ERROR invalidate: address=" TARGET_FMT_lx
967 " PC=%08lx size=%04x\n", addr, (long)tb->pc, tb->size);
971 /* verify that all the pages have correct rights for code
973 * Called with tb_lock held.
975 static void tb_invalidate_check(target_ulong address)
977 address &= TARGET_PAGE_MASK;
978 qht_iter(&tcg_ctx.tb_ctx.htable, do_tb_invalidate_check, &address);
981 static void
982 do_tb_page_check(struct qht *ht, void *p, uint32_t hash, void *userp)
984 TranslationBlock *tb = p;
985 int flags1, flags2;
987 flags1 = page_get_flags(tb->pc);
988 flags2 = page_get_flags(tb->pc + tb->size - 1);
989 if ((flags1 & PAGE_WRITE) || (flags2 & PAGE_WRITE)) {
990 printf("ERROR page flags: PC=%08lx size=%04x f1=%x f2=%x\n",
991 (long)tb->pc, tb->size, flags1, flags2);
995 /* verify that all the pages have correct rights for code */
996 static void tb_page_check(void)
998 qht_iter(&tcg_ctx.tb_ctx.htable, do_tb_page_check, NULL);
1001 #endif
1003 static inline void tb_page_remove(TranslationBlock **ptb, TranslationBlock *tb)
1005 TranslationBlock *tb1;
1006 unsigned int n1;
1008 for (;;) {
1009 tb1 = *ptb;
1010 n1 = (uintptr_t)tb1 & 3;
1011 tb1 = (TranslationBlock *)((uintptr_t)tb1 & ~3);
1012 if (tb1 == tb) {
1013 *ptb = tb1->page_next[n1];
1014 break;
1016 ptb = &tb1->page_next[n1];
1020 /* remove the TB from a list of TBs jumping to the n-th jump target of the TB */
1021 static inline void tb_remove_from_jmp_list(TranslationBlock *tb, int n)
1023 TranslationBlock *tb1;
1024 uintptr_t *ptb, ntb;
1025 unsigned int n1;
1027 ptb = &tb->jmp_list_next[n];
1028 if (*ptb) {
1029 /* find tb(n) in circular list */
1030 for (;;) {
1031 ntb = *ptb;
1032 n1 = ntb & 3;
1033 tb1 = (TranslationBlock *)(ntb & ~3);
1034 if (n1 == n && tb1 == tb) {
1035 break;
1037 if (n1 == 2) {
1038 ptb = &tb1->jmp_list_first;
1039 } else {
1040 ptb = &tb1->jmp_list_next[n1];
1043 /* now we can suppress tb(n) from the list */
1044 *ptb = tb->jmp_list_next[n];
1046 tb->jmp_list_next[n] = (uintptr_t)NULL;
1050 /* reset the jump entry 'n' of a TB so that it is not chained to
1051 another TB */
1052 static inline void tb_reset_jump(TranslationBlock *tb, int n)
1054 uintptr_t addr = (uintptr_t)(tb->tc_ptr + tb->jmp_reset_offset[n]);
1055 tb_set_jmp_target(tb, n, addr);
1058 /* remove any jumps to the TB */
1059 static inline void tb_jmp_unlink(TranslationBlock *tb)
1061 TranslationBlock *tb1;
1062 uintptr_t *ptb, ntb;
1063 unsigned int n1;
1065 ptb = &tb->jmp_list_first;
1066 for (;;) {
1067 ntb = *ptb;
1068 n1 = ntb & 3;
1069 tb1 = (TranslationBlock *)(ntb & ~3);
1070 if (n1 == 2) {
1071 break;
1073 tb_reset_jump(tb1, n1);
1074 *ptb = tb1->jmp_list_next[n1];
1075 tb1->jmp_list_next[n1] = (uintptr_t)NULL;
1079 /* invalidate one TB
1081 * Called with tb_lock held.
1083 void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr)
1085 CPUState *cpu;
1086 PageDesc *p;
1087 uint32_t h;
1088 tb_page_addr_t phys_pc;
1090 assert_tb_locked();
1092 atomic_set(&tb->invalid, true);
1094 /* remove the TB from the hash list */
1095 phys_pc = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);
1096 h = tb_hash_func(phys_pc, tb->pc, tb->flags);
1097 qht_remove(&tcg_ctx.tb_ctx.htable, tb, h);
1099 /* remove the TB from the page list */
1100 if (tb->page_addr[0] != page_addr) {
1101 p = page_find(tb->page_addr[0] >> TARGET_PAGE_BITS);
1102 tb_page_remove(&p->first_tb, tb);
1103 invalidate_page_bitmap(p);
1105 if (tb->page_addr[1] != -1 && tb->page_addr[1] != page_addr) {
1106 p = page_find(tb->page_addr[1] >> TARGET_PAGE_BITS);
1107 tb_page_remove(&p->first_tb, tb);
1108 invalidate_page_bitmap(p);
1111 /* remove the TB from the hash list */
1112 h = tb_jmp_cache_hash_func(tb->pc);
1113 CPU_FOREACH(cpu) {
1114 if (atomic_read(&cpu->tb_jmp_cache[h]) == tb) {
1115 atomic_set(&cpu->tb_jmp_cache[h], NULL);
1119 /* suppress this TB from the two jump lists */
1120 tb_remove_from_jmp_list(tb, 0);
1121 tb_remove_from_jmp_list(tb, 1);
1123 /* suppress any remaining jumps to this TB */
1124 tb_jmp_unlink(tb);
1126 tcg_ctx.tb_ctx.tb_phys_invalidate_count++;
1129 #ifdef CONFIG_SOFTMMU
1130 static void build_page_bitmap(PageDesc *p)
1132 int n, tb_start, tb_end;
1133 TranslationBlock *tb;
1135 p->code_bitmap = bitmap_new(TARGET_PAGE_SIZE);
1137 tb = p->first_tb;
1138 while (tb != NULL) {
1139 n = (uintptr_t)tb & 3;
1140 tb = (TranslationBlock *)((uintptr_t)tb & ~3);
1141 /* NOTE: this is subtle as a TB may span two physical pages */
1142 if (n == 0) {
1143 /* NOTE: tb_end may be after the end of the page, but
1144 it is not a problem */
1145 tb_start = tb->pc & ~TARGET_PAGE_MASK;
1146 tb_end = tb_start + tb->size;
1147 if (tb_end > TARGET_PAGE_SIZE) {
1148 tb_end = TARGET_PAGE_SIZE;
1150 } else {
1151 tb_start = 0;
1152 tb_end = ((tb->pc + tb->size) & ~TARGET_PAGE_MASK);
1154 bitmap_set(p->code_bitmap, tb_start, tb_end - tb_start);
1155 tb = tb->page_next[n];
1158 #endif
1160 /* add the tb in the target page and protect it if necessary
1162 * Called with mmap_lock held for user-mode emulation.
1164 static inline void tb_alloc_page(TranslationBlock *tb,
1165 unsigned int n, tb_page_addr_t page_addr)
1167 PageDesc *p;
1168 #ifndef CONFIG_USER_ONLY
1169 bool page_already_protected;
1170 #endif
1172 assert_memory_lock();
1174 tb->page_addr[n] = page_addr;
1175 p = page_find_alloc(page_addr >> TARGET_PAGE_BITS, 1);
1176 tb->page_next[n] = p->first_tb;
1177 #ifndef CONFIG_USER_ONLY
1178 page_already_protected = p->first_tb != NULL;
1179 #endif
1180 p->first_tb = (TranslationBlock *)((uintptr_t)tb | n);
1181 invalidate_page_bitmap(p);
1183 #if defined(CONFIG_USER_ONLY)
1184 if (p->flags & PAGE_WRITE) {
1185 target_ulong addr;
1186 PageDesc *p2;
1187 int prot;
1189 /* force the host page as non writable (writes will have a
1190 page fault + mprotect overhead) */
1191 page_addr &= qemu_host_page_mask;
1192 prot = 0;
1193 for (addr = page_addr; addr < page_addr + qemu_host_page_size;
1194 addr += TARGET_PAGE_SIZE) {
1196 p2 = page_find(addr >> TARGET_PAGE_BITS);
1197 if (!p2) {
1198 continue;
1200 prot |= p2->flags;
1201 p2->flags &= ~PAGE_WRITE;
1203 mprotect(g2h(page_addr), qemu_host_page_size,
1204 (prot & PAGE_BITS) & ~PAGE_WRITE);
1205 #ifdef DEBUG_TB_INVALIDATE
1206 printf("protecting code page: 0x" TARGET_FMT_lx "\n",
1207 page_addr);
1208 #endif
1210 #else
1211 /* if some code is already present, then the pages are already
1212 protected. So we handle the case where only the first TB is
1213 allocated in a physical page */
1214 if (!page_already_protected) {
1215 tlb_protect_code(page_addr);
1217 #endif
1220 /* add a new TB and link it to the physical page tables. phys_page2 is
1221 * (-1) to indicate that only one page contains the TB.
1223 * Called with mmap_lock held for user-mode emulation.
1225 static void tb_link_page(TranslationBlock *tb, tb_page_addr_t phys_pc,
1226 tb_page_addr_t phys_page2)
1228 uint32_t h;
1230 assert_memory_lock();
1232 /* add in the page list */
1233 tb_alloc_page(tb, 0, phys_pc & TARGET_PAGE_MASK);
1234 if (phys_page2 != -1) {
1235 tb_alloc_page(tb, 1, phys_page2);
1236 } else {
1237 tb->page_addr[1] = -1;
1240 /* add in the hash table */
1241 h = tb_hash_func(phys_pc, tb->pc, tb->flags);
1242 qht_insert(&tcg_ctx.tb_ctx.htable, tb, h);
1244 #ifdef DEBUG_TB_CHECK
1245 tb_page_check();
1246 #endif
1249 /* Called with mmap_lock held for user mode emulation. */
1250 TranslationBlock *tb_gen_code(CPUState *cpu,
1251 target_ulong pc, target_ulong cs_base,
1252 uint32_t flags, int cflags)
1254 CPUArchState *env = cpu->env_ptr;
1255 TranslationBlock *tb;
1256 tb_page_addr_t phys_pc, phys_page2;
1257 target_ulong virt_page2;
1258 tcg_insn_unit *gen_code_buf;
1259 int gen_code_size, search_size;
1260 #ifdef CONFIG_PROFILER
1261 int64_t ti;
1262 #endif
1263 assert_memory_lock();
1265 phys_pc = get_page_addr_code(env, pc);
1266 if (use_icount && !(cflags & CF_IGNORE_ICOUNT)) {
1267 cflags |= CF_USE_ICOUNT;
1270 tb = tb_alloc(pc);
1271 if (unlikely(!tb)) {
1272 buffer_overflow:
1273 /* flush must be done */
1274 tb_flush(cpu);
1275 mmap_unlock();
1276 /* Make the execution loop process the flush as soon as possible. */
1277 cpu->exception_index = EXCP_INTERRUPT;
1278 cpu_loop_exit(cpu);
1281 gen_code_buf = tcg_ctx.code_gen_ptr;
1282 tb->tc_ptr = gen_code_buf;
1283 tb->cs_base = cs_base;
1284 tb->flags = flags;
1285 tb->cflags = cflags;
1287 #ifdef CONFIG_PROFILER
1288 tcg_ctx.tb_count1++; /* includes aborted translations because of
1289 exceptions */
1290 ti = profile_getclock();
1291 #endif
1293 tcg_func_start(&tcg_ctx);
1295 tcg_ctx.cpu = ENV_GET_CPU(env);
1296 gen_intermediate_code(env, tb);
1297 tcg_ctx.cpu = NULL;
1299 trace_translate_block(tb, tb->pc, tb->tc_ptr);
1301 /* generate machine code */
1302 tb->jmp_reset_offset[0] = TB_JMP_RESET_OFFSET_INVALID;
1303 tb->jmp_reset_offset[1] = TB_JMP_RESET_OFFSET_INVALID;
1304 tcg_ctx.tb_jmp_reset_offset = tb->jmp_reset_offset;
1305 #ifdef USE_DIRECT_JUMP
1306 tcg_ctx.tb_jmp_insn_offset = tb->jmp_insn_offset;
1307 tcg_ctx.tb_jmp_target_addr = NULL;
1308 #else
1309 tcg_ctx.tb_jmp_insn_offset = NULL;
1310 tcg_ctx.tb_jmp_target_addr = tb->jmp_target_addr;
1311 #endif
1313 #ifdef CONFIG_PROFILER
1314 tcg_ctx.tb_count++;
1315 tcg_ctx.interm_time += profile_getclock() - ti;
1316 tcg_ctx.code_time -= profile_getclock();
1317 #endif
1319 /* ??? Overflow could be handled better here. In particular, we
1320 don't need to re-do gen_intermediate_code, nor should we re-do
1321 the tcg optimization currently hidden inside tcg_gen_code. All
1322 that should be required is to flush the TBs, allocate a new TB,
1323 re-initialize it per above, and re-do the actual code generation. */
1324 gen_code_size = tcg_gen_code(&tcg_ctx, tb);
1325 if (unlikely(gen_code_size < 0)) {
1326 goto buffer_overflow;
1328 search_size = encode_search(tb, (void *)gen_code_buf + gen_code_size);
1329 if (unlikely(search_size < 0)) {
1330 goto buffer_overflow;
1333 #ifdef CONFIG_PROFILER
1334 tcg_ctx.code_time += profile_getclock();
1335 tcg_ctx.code_in_len += tb->size;
1336 tcg_ctx.code_out_len += gen_code_size;
1337 tcg_ctx.search_out_len += search_size;
1338 #endif
1340 #ifdef DEBUG_DISAS
1341 if (qemu_loglevel_mask(CPU_LOG_TB_OUT_ASM) &&
1342 qemu_log_in_addr_range(tb->pc)) {
1343 qemu_log_lock();
1344 qemu_log("OUT: [size=%d]\n", gen_code_size);
1345 log_disas(tb->tc_ptr, gen_code_size);
1346 qemu_log("\n");
1347 qemu_log_flush();
1348 qemu_log_unlock();
1350 #endif
1352 tcg_ctx.code_gen_ptr = (void *)
1353 ROUND_UP((uintptr_t)gen_code_buf + gen_code_size + search_size,
1354 CODE_GEN_ALIGN);
1356 #if defined(CONFIG_USER_ONLY) && defined(TARGET_X86_64)
1357 /* if we are doing vsyscall don't link the page as it lies in high memory
1358 and tb_alloc_page will abort due to page_l1_map returning NULL */
1359 if (unlikely(phys_pc >= TARGET_VSYSCALL_START
1360 && phys_pc < TARGET_VSYSCALL_END))
1361 return tb;
1362 #endif
1364 /* init jump list */
1365 assert(((uintptr_t)tb & 3) == 0);
1366 tb->jmp_list_first = (uintptr_t)tb | 2;
1367 tb->jmp_list_next[0] = (uintptr_t)NULL;
1368 tb->jmp_list_next[1] = (uintptr_t)NULL;
1370 /* init original jump addresses wich has been set during tcg_gen_code() */
1371 if (tb->jmp_reset_offset[0] != TB_JMP_RESET_OFFSET_INVALID) {
1372 tb_reset_jump(tb, 0);
1374 if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) {
1375 tb_reset_jump(tb, 1);
1378 /* check next page if needed */
1379 virt_page2 = (pc + tb->size - 1) & TARGET_PAGE_MASK;
1380 phys_page2 = -1;
1381 if ((pc & TARGET_PAGE_MASK) != virt_page2) {
1382 phys_page2 = get_page_addr_code(env, virt_page2);
1384 /* As long as consistency of the TB stuff is provided by tb_lock in user
1385 * mode and is implicit in single-threaded softmmu emulation, no explicit
1386 * memory barrier is required before tb_link_page() makes the TB visible
1387 * through the physical hash table and physical page list.
1389 tb_link_page(tb, phys_pc, phys_page2);
1390 return tb;
1394 * Invalidate all TBs which intersect with the target physical address range
1395 * [start;end[. NOTE: start and end may refer to *different* physical pages.
1396 * 'is_cpu_write_access' should be true if called from a real cpu write
1397 * access: the virtual CPU will exit the current TB if code is modified inside
1398 * this TB.
1400 * Called with mmap_lock held for user-mode emulation, grabs tb_lock
1401 * Called with tb_lock held for system-mode emulation
1403 static void tb_invalidate_phys_range_1(tb_page_addr_t start, tb_page_addr_t end)
1405 while (start < end) {
1406 tb_invalidate_phys_page_range(start, end, 0);
1407 start &= TARGET_PAGE_MASK;
1408 start += TARGET_PAGE_SIZE;
1412 #ifdef CONFIG_SOFTMMU
1413 void tb_invalidate_phys_range(tb_page_addr_t start, tb_page_addr_t end)
1415 assert_tb_locked();
1416 tb_invalidate_phys_range_1(start, end);
1418 #else
1419 void tb_invalidate_phys_range(tb_page_addr_t start, tb_page_addr_t end)
1421 assert_memory_lock();
1422 tb_lock();
1423 tb_invalidate_phys_range_1(start, end);
1424 tb_unlock();
1426 #endif
1428 * Invalidate all TBs which intersect with the target physical address range
1429 * [start;end[. NOTE: start and end must refer to the *same* physical page.
1430 * 'is_cpu_write_access' should be true if called from a real cpu write
1431 * access: the virtual CPU will exit the current TB if code is modified inside
1432 * this TB.
1434 * Called with tb_lock/mmap_lock held for user-mode emulation
1435 * Called with tb_lock held for system-mode emulation
1437 void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end,
1438 int is_cpu_write_access)
1440 TranslationBlock *tb, *tb_next;
1441 #if defined(TARGET_HAS_PRECISE_SMC)
1442 CPUState *cpu = current_cpu;
1443 CPUArchState *env = NULL;
1444 #endif
1445 tb_page_addr_t tb_start, tb_end;
1446 PageDesc *p;
1447 int n;
1448 #ifdef TARGET_HAS_PRECISE_SMC
1449 int current_tb_not_found = is_cpu_write_access;
1450 TranslationBlock *current_tb = NULL;
1451 int current_tb_modified = 0;
1452 target_ulong current_pc = 0;
1453 target_ulong current_cs_base = 0;
1454 uint32_t current_flags = 0;
1455 #endif /* TARGET_HAS_PRECISE_SMC */
1457 assert_memory_lock();
1458 assert_tb_locked();
1460 p = page_find(start >> TARGET_PAGE_BITS);
1461 if (!p) {
1462 return;
1464 #if defined(TARGET_HAS_PRECISE_SMC)
1465 if (cpu != NULL) {
1466 env = cpu->env_ptr;
1468 #endif
1470 /* we remove all the TBs in the range [start, end[ */
1471 /* XXX: see if in some cases it could be faster to invalidate all
1472 the code */
1473 tb = p->first_tb;
1474 while (tb != NULL) {
1475 n = (uintptr_t)tb & 3;
1476 tb = (TranslationBlock *)((uintptr_t)tb & ~3);
1477 tb_next = tb->page_next[n];
1478 /* NOTE: this is subtle as a TB may span two physical pages */
1479 if (n == 0) {
1480 /* NOTE: tb_end may be after the end of the page, but
1481 it is not a problem */
1482 tb_start = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);
1483 tb_end = tb_start + tb->size;
1484 } else {
1485 tb_start = tb->page_addr[1];
1486 tb_end = tb_start + ((tb->pc + tb->size) & ~TARGET_PAGE_MASK);
1488 if (!(tb_end <= start || tb_start >= end)) {
1489 #ifdef TARGET_HAS_PRECISE_SMC
1490 if (current_tb_not_found) {
1491 current_tb_not_found = 0;
1492 current_tb = NULL;
1493 if (cpu->mem_io_pc) {
1494 /* now we have a real cpu fault */
1495 current_tb = tb_find_pc(cpu->mem_io_pc);
1498 if (current_tb == tb &&
1499 (current_tb->cflags & CF_COUNT_MASK) != 1) {
1500 /* If we are modifying the current TB, we must stop
1501 its execution. We could be more precise by checking
1502 that the modification is after the current PC, but it
1503 would require a specialized function to partially
1504 restore the CPU state */
1506 current_tb_modified = 1;
1507 cpu_restore_state_from_tb(cpu, current_tb, cpu->mem_io_pc);
1508 cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base,
1509 &current_flags);
1511 #endif /* TARGET_HAS_PRECISE_SMC */
1512 tb_phys_invalidate(tb, -1);
1514 tb = tb_next;
1516 #if !defined(CONFIG_USER_ONLY)
1517 /* if no code remaining, no need to continue to use slow writes */
1518 if (!p->first_tb) {
1519 invalidate_page_bitmap(p);
1520 tlb_unprotect_code(start);
1522 #endif
1523 #ifdef TARGET_HAS_PRECISE_SMC
1524 if (current_tb_modified) {
1525 /* we generate a block containing just the instruction
1526 modifying the memory. It will ensure that it cannot modify
1527 itself */
1528 tb_gen_code(cpu, current_pc, current_cs_base, current_flags, 1);
1529 cpu_loop_exit_noexc(cpu);
1531 #endif
1534 #ifdef CONFIG_SOFTMMU
1535 /* len must be <= 8 and start must be a multiple of len.
1536 * Called via softmmu_template.h when code areas are written to with
1537 * iothread mutex not held.
1539 void tb_invalidate_phys_page_fast(tb_page_addr_t start, int len)
1541 PageDesc *p;
1543 #if 0
1544 if (1) {
1545 qemu_log("modifying code at 0x%x size=%d EIP=%x PC=%08x\n",
1546 cpu_single_env->mem_io_vaddr, len,
1547 cpu_single_env->eip,
1548 cpu_single_env->eip +
1549 (intptr_t)cpu_single_env->segs[R_CS].base);
1551 #endif
1552 assert_memory_lock();
1554 p = page_find(start >> TARGET_PAGE_BITS);
1555 if (!p) {
1556 return;
1558 if (!p->code_bitmap &&
1559 ++p->code_write_count >= SMC_BITMAP_USE_THRESHOLD) {
1560 /* build code bitmap. FIXME: writes should be protected by
1561 * tb_lock, reads by tb_lock or RCU.
1563 build_page_bitmap(p);
1565 if (p->code_bitmap) {
1566 unsigned int nr;
1567 unsigned long b;
1569 nr = start & ~TARGET_PAGE_MASK;
1570 b = p->code_bitmap[BIT_WORD(nr)] >> (nr & (BITS_PER_LONG - 1));
1571 if (b & ((1 << len) - 1)) {
1572 goto do_invalidate;
1574 } else {
1575 do_invalidate:
1576 tb_invalidate_phys_page_range(start, start + len, 1);
1579 #else
1580 /* Called with mmap_lock held. If pc is not 0 then it indicates the
1581 * host PC of the faulting store instruction that caused this invalidate.
1582 * Returns true if the caller needs to abort execution of the current
1583 * TB (because it was modified by this store and the guest CPU has
1584 * precise-SMC semantics).
1586 static bool tb_invalidate_phys_page(tb_page_addr_t addr, uintptr_t pc)
1588 TranslationBlock *tb;
1589 PageDesc *p;
1590 int n;
1591 #ifdef TARGET_HAS_PRECISE_SMC
1592 TranslationBlock *current_tb = NULL;
1593 CPUState *cpu = current_cpu;
1594 CPUArchState *env = NULL;
1595 int current_tb_modified = 0;
1596 target_ulong current_pc = 0;
1597 target_ulong current_cs_base = 0;
1598 uint32_t current_flags = 0;
1599 #endif
1601 assert_memory_lock();
1603 addr &= TARGET_PAGE_MASK;
1604 p = page_find(addr >> TARGET_PAGE_BITS);
1605 if (!p) {
1606 return false;
1609 tb_lock();
1610 tb = p->first_tb;
1611 #ifdef TARGET_HAS_PRECISE_SMC
1612 if (tb && pc != 0) {
1613 current_tb = tb_find_pc(pc);
1615 if (cpu != NULL) {
1616 env = cpu->env_ptr;
1618 #endif
1619 while (tb != NULL) {
1620 n = (uintptr_t)tb & 3;
1621 tb = (TranslationBlock *)((uintptr_t)tb & ~3);
1622 #ifdef TARGET_HAS_PRECISE_SMC
1623 if (current_tb == tb &&
1624 (current_tb->cflags & CF_COUNT_MASK) != 1) {
1625 /* If we are modifying the current TB, we must stop
1626 its execution. We could be more precise by checking
1627 that the modification is after the current PC, but it
1628 would require a specialized function to partially
1629 restore the CPU state */
1631 current_tb_modified = 1;
1632 cpu_restore_state_from_tb(cpu, current_tb, pc);
1633 cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base,
1634 &current_flags);
1636 #endif /* TARGET_HAS_PRECISE_SMC */
1637 tb_phys_invalidate(tb, addr);
1638 tb = tb->page_next[n];
1640 p->first_tb = NULL;
1641 #ifdef TARGET_HAS_PRECISE_SMC
1642 if (current_tb_modified) {
1643 /* we generate a block containing just the instruction
1644 modifying the memory. It will ensure that it cannot modify
1645 itself */
1646 tb_gen_code(cpu, current_pc, current_cs_base, current_flags, 1);
1647 /* tb_lock will be reset after cpu_loop_exit_noexc longjmps
1648 * back into the cpu_exec loop. */
1649 return true;
1651 #endif
1652 tb_unlock();
1654 return false;
1656 #endif
1658 /* find the TB 'tb' such that tb[0].tc_ptr <= tc_ptr <
1659 tb[1].tc_ptr. Return NULL if not found */
1660 static TranslationBlock *tb_find_pc(uintptr_t tc_ptr)
1662 int m_min, m_max, m;
1663 uintptr_t v;
1664 TranslationBlock *tb;
1666 if (tcg_ctx.tb_ctx.nb_tbs <= 0) {
1667 return NULL;
1669 if (tc_ptr < (uintptr_t)tcg_ctx.code_gen_buffer ||
1670 tc_ptr >= (uintptr_t)tcg_ctx.code_gen_ptr) {
1671 return NULL;
1673 /* binary search (cf Knuth) */
1674 m_min = 0;
1675 m_max = tcg_ctx.tb_ctx.nb_tbs - 1;
1676 while (m_min <= m_max) {
1677 m = (m_min + m_max) >> 1;
1678 tb = &tcg_ctx.tb_ctx.tbs[m];
1679 v = (uintptr_t)tb->tc_ptr;
1680 if (v == tc_ptr) {
1681 return tb;
1682 } else if (tc_ptr < v) {
1683 m_max = m - 1;
1684 } else {
1685 m_min = m + 1;
1688 return &tcg_ctx.tb_ctx.tbs[m_max];
1691 #if !defined(CONFIG_USER_ONLY)
1692 void tb_invalidate_phys_addr(AddressSpace *as, hwaddr addr)
1694 ram_addr_t ram_addr;
1695 MemoryRegion *mr;
1696 hwaddr l = 1;
1698 rcu_read_lock();
1699 mr = address_space_translate(as, addr, &addr, &l, false);
1700 if (!(memory_region_is_ram(mr)
1701 || memory_region_is_romd(mr))) {
1702 rcu_read_unlock();
1703 return;
1705 ram_addr = memory_region_get_ram_addr(mr) + addr;
1706 tb_lock();
1707 tb_invalidate_phys_page_range(ram_addr, ram_addr + 1, 0);
1708 tb_unlock();
1709 rcu_read_unlock();
1711 #endif /* !defined(CONFIG_USER_ONLY) */
1713 /* Called with tb_lock held. */
1714 void tb_check_watchpoint(CPUState *cpu)
1716 TranslationBlock *tb;
1718 tb = tb_find_pc(cpu->mem_io_pc);
1719 if (tb) {
1720 /* We can use retranslation to find the PC. */
1721 cpu_restore_state_from_tb(cpu, tb, cpu->mem_io_pc);
1722 tb_phys_invalidate(tb, -1);
1723 } else {
1724 /* The exception probably happened in a helper. The CPU state should
1725 have been saved before calling it. Fetch the PC from there. */
1726 CPUArchState *env = cpu->env_ptr;
1727 target_ulong pc, cs_base;
1728 tb_page_addr_t addr;
1729 uint32_t flags;
1731 cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags);
1732 addr = get_page_addr_code(env, pc);
1733 tb_invalidate_phys_range(addr, addr + 1);
1737 #ifndef CONFIG_USER_ONLY
1738 /* in deterministic execution mode, instructions doing device I/Os
1739 * must be at the end of the TB.
1741 * Called by softmmu_template.h, with iothread mutex not held.
1743 void cpu_io_recompile(CPUState *cpu, uintptr_t retaddr)
1745 #if defined(TARGET_MIPS) || defined(TARGET_SH4)
1746 CPUArchState *env = cpu->env_ptr;
1747 #endif
1748 TranslationBlock *tb;
1749 uint32_t n, cflags;
1750 target_ulong pc, cs_base;
1751 uint32_t flags;
1753 tb_lock();
1754 tb = tb_find_pc(retaddr);
1755 if (!tb) {
1756 cpu_abort(cpu, "cpu_io_recompile: could not find TB for pc=%p",
1757 (void *)retaddr);
1759 n = cpu->icount_decr.u16.low + tb->icount;
1760 cpu_restore_state_from_tb(cpu, tb, retaddr);
1761 /* Calculate how many instructions had been executed before the fault
1762 occurred. */
1763 n = n - cpu->icount_decr.u16.low;
1764 /* Generate a new TB ending on the I/O insn. */
1765 n++;
1766 /* On MIPS and SH, delay slot instructions can only be restarted if
1767 they were already the first instruction in the TB. If this is not
1768 the first instruction in a TB then re-execute the preceding
1769 branch. */
1770 #if defined(TARGET_MIPS)
1771 if ((env->hflags & MIPS_HFLAG_BMASK) != 0 && n > 1) {
1772 env->active_tc.PC -= (env->hflags & MIPS_HFLAG_B16 ? 2 : 4);
1773 cpu->icount_decr.u16.low++;
1774 env->hflags &= ~MIPS_HFLAG_BMASK;
1776 #elif defined(TARGET_SH4)
1777 if ((env->flags & ((DELAY_SLOT | DELAY_SLOT_CONDITIONAL))) != 0
1778 && n > 1) {
1779 env->pc -= 2;
1780 cpu->icount_decr.u16.low++;
1781 env->flags &= ~(DELAY_SLOT | DELAY_SLOT_CONDITIONAL);
1783 #endif
1784 /* This should never happen. */
1785 if (n > CF_COUNT_MASK) {
1786 cpu_abort(cpu, "TB too big during recompile");
1789 cflags = n | CF_LAST_IO;
1790 pc = tb->pc;
1791 cs_base = tb->cs_base;
1792 flags = tb->flags;
1793 tb_phys_invalidate(tb, -1);
1794 if (tb->cflags & CF_NOCACHE) {
1795 if (tb->orig_tb) {
1796 /* Invalidate original TB if this TB was generated in
1797 * cpu_exec_nocache() */
1798 tb_phys_invalidate(tb->orig_tb, -1);
1800 tb_free(tb);
1802 /* FIXME: In theory this could raise an exception. In practice
1803 we have already translated the block once so it's probably ok. */
1804 tb_gen_code(cpu, pc, cs_base, flags, cflags);
1806 /* TODO: If env->pc != tb->pc (i.e. the faulting instruction was not
1807 * the first in the TB) then we end up generating a whole new TB and
1808 * repeating the fault, which is horribly inefficient.
1809 * Better would be to execute just this insn uncached, or generate a
1810 * second new TB.
1812 * cpu_loop_exit_noexc will longjmp back to cpu_exec where the
1813 * tb_lock gets reset.
1815 cpu_loop_exit_noexc(cpu);
1818 void tb_flush_jmp_cache(CPUState *cpu, target_ulong addr)
1820 unsigned int i;
1822 /* Discard jump cache entries for any tb which might potentially
1823 overlap the flushed page. */
1824 i = tb_jmp_cache_hash_page(addr - TARGET_PAGE_SIZE);
1825 memset(&cpu->tb_jmp_cache[i], 0,
1826 TB_JMP_PAGE_SIZE * sizeof(TranslationBlock *));
1828 i = tb_jmp_cache_hash_page(addr);
1829 memset(&cpu->tb_jmp_cache[i], 0,
1830 TB_JMP_PAGE_SIZE * sizeof(TranslationBlock *));
1833 static void print_qht_statistics(FILE *f, fprintf_function cpu_fprintf,
1834 struct qht_stats hst)
1836 uint32_t hgram_opts;
1837 size_t hgram_bins;
1838 char *hgram;
1840 if (!hst.head_buckets) {
1841 return;
1843 cpu_fprintf(f, "TB hash buckets %zu/%zu (%0.2f%% head buckets used)\n",
1844 hst.used_head_buckets, hst.head_buckets,
1845 (double)hst.used_head_buckets / hst.head_buckets * 100);
1847 hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
1848 hgram_opts |= QDIST_PR_100X | QDIST_PR_PERCENT;
1849 if (qdist_xmax(&hst.occupancy) - qdist_xmin(&hst.occupancy) == 1) {
1850 hgram_opts |= QDIST_PR_NODECIMAL;
1852 hgram = qdist_pr(&hst.occupancy, 10, hgram_opts);
1853 cpu_fprintf(f, "TB hash occupancy %0.2f%% avg chain occ. Histogram: %s\n",
1854 qdist_avg(&hst.occupancy) * 100, hgram);
1855 g_free(hgram);
1857 hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
1858 hgram_bins = qdist_xmax(&hst.chain) - qdist_xmin(&hst.chain);
1859 if (hgram_bins > 10) {
1860 hgram_bins = 10;
1861 } else {
1862 hgram_bins = 0;
1863 hgram_opts |= QDIST_PR_NODECIMAL | QDIST_PR_NOBINRANGE;
1865 hgram = qdist_pr(&hst.chain, hgram_bins, hgram_opts);
1866 cpu_fprintf(f, "TB hash avg chain %0.3f buckets. Histogram: %s\n",
1867 qdist_avg(&hst.chain), hgram);
1868 g_free(hgram);
1871 void dump_exec_info(FILE *f, fprintf_function cpu_fprintf)
1873 int i, target_code_size, max_target_code_size;
1874 int direct_jmp_count, direct_jmp2_count, cross_page;
1875 TranslationBlock *tb;
1876 struct qht_stats hst;
1878 tb_lock();
1880 target_code_size = 0;
1881 max_target_code_size = 0;
1882 cross_page = 0;
1883 direct_jmp_count = 0;
1884 direct_jmp2_count = 0;
1885 for (i = 0; i < tcg_ctx.tb_ctx.nb_tbs; i++) {
1886 tb = &tcg_ctx.tb_ctx.tbs[i];
1887 target_code_size += tb->size;
1888 if (tb->size > max_target_code_size) {
1889 max_target_code_size = tb->size;
1891 if (tb->page_addr[1] != -1) {
1892 cross_page++;
1894 if (tb->jmp_reset_offset[0] != TB_JMP_RESET_OFFSET_INVALID) {
1895 direct_jmp_count++;
1896 if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) {
1897 direct_jmp2_count++;
1901 /* XXX: avoid using doubles ? */
1902 cpu_fprintf(f, "Translation buffer state:\n");
1903 cpu_fprintf(f, "gen code size %td/%zd\n",
1904 tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer,
1905 tcg_ctx.code_gen_highwater - tcg_ctx.code_gen_buffer);
1906 cpu_fprintf(f, "TB count %d/%d\n",
1907 tcg_ctx.tb_ctx.nb_tbs, tcg_ctx.code_gen_max_blocks);
1908 cpu_fprintf(f, "TB avg target size %d max=%d bytes\n",
1909 tcg_ctx.tb_ctx.nb_tbs ? target_code_size /
1910 tcg_ctx.tb_ctx.nb_tbs : 0,
1911 max_target_code_size);
1912 cpu_fprintf(f, "TB avg host size %td bytes (expansion ratio: %0.1f)\n",
1913 tcg_ctx.tb_ctx.nb_tbs ? (tcg_ctx.code_gen_ptr -
1914 tcg_ctx.code_gen_buffer) /
1915 tcg_ctx.tb_ctx.nb_tbs : 0,
1916 target_code_size ? (double) (tcg_ctx.code_gen_ptr -
1917 tcg_ctx.code_gen_buffer) /
1918 target_code_size : 0);
1919 cpu_fprintf(f, "cross page TB count %d (%d%%)\n", cross_page,
1920 tcg_ctx.tb_ctx.nb_tbs ? (cross_page * 100) /
1921 tcg_ctx.tb_ctx.nb_tbs : 0);
1922 cpu_fprintf(f, "direct jump count %d (%d%%) (2 jumps=%d %d%%)\n",
1923 direct_jmp_count,
1924 tcg_ctx.tb_ctx.nb_tbs ? (direct_jmp_count * 100) /
1925 tcg_ctx.tb_ctx.nb_tbs : 0,
1926 direct_jmp2_count,
1927 tcg_ctx.tb_ctx.nb_tbs ? (direct_jmp2_count * 100) /
1928 tcg_ctx.tb_ctx.nb_tbs : 0);
1930 qht_statistics_init(&tcg_ctx.tb_ctx.htable, &hst);
1931 print_qht_statistics(f, cpu_fprintf, hst);
1932 qht_statistics_destroy(&hst);
1934 cpu_fprintf(f, "\nStatistics:\n");
1935 cpu_fprintf(f, "TB flush count %u\n",
1936 atomic_read(&tcg_ctx.tb_ctx.tb_flush_count));
1937 cpu_fprintf(f, "TB invalidate count %d\n",
1938 tcg_ctx.tb_ctx.tb_phys_invalidate_count);
1939 cpu_fprintf(f, "TLB flush count %d\n", tlb_flush_count);
1940 tcg_dump_info(f, cpu_fprintf);
1942 tb_unlock();
1945 void dump_opcount_info(FILE *f, fprintf_function cpu_fprintf)
1947 tcg_dump_op_count(f, cpu_fprintf);
1950 #else /* CONFIG_USER_ONLY */
1952 void cpu_interrupt(CPUState *cpu, int mask)
1954 g_assert(qemu_mutex_iothread_locked());
1955 cpu->interrupt_request |= mask;
1956 cpu->icount_decr.u16.high = -1;
1960 * Walks guest process memory "regions" one by one
1961 * and calls callback function 'fn' for each region.
1963 struct walk_memory_regions_data {
1964 walk_memory_regions_fn fn;
1965 void *priv;
1966 target_ulong start;
1967 int prot;
1970 static int walk_memory_regions_end(struct walk_memory_regions_data *data,
1971 target_ulong end, int new_prot)
1973 if (data->start != -1u) {
1974 int rc = data->fn(data->priv, data->start, end, data->prot);
1975 if (rc != 0) {
1976 return rc;
1980 data->start = (new_prot ? end : -1u);
1981 data->prot = new_prot;
1983 return 0;
1986 static int walk_memory_regions_1(struct walk_memory_regions_data *data,
1987 target_ulong base, int level, void **lp)
1989 target_ulong pa;
1990 int i, rc;
1992 if (*lp == NULL) {
1993 return walk_memory_regions_end(data, base, 0);
1996 if (level == 0) {
1997 PageDesc *pd = *lp;
1999 for (i = 0; i < V_L2_SIZE; ++i) {
2000 int prot = pd[i].flags;
2002 pa = base | (i << TARGET_PAGE_BITS);
2003 if (prot != data->prot) {
2004 rc = walk_memory_regions_end(data, pa, prot);
2005 if (rc != 0) {
2006 return rc;
2010 } else {
2011 void **pp = *lp;
2013 for (i = 0; i < V_L2_SIZE; ++i) {
2014 pa = base | ((target_ulong)i <<
2015 (TARGET_PAGE_BITS + V_L2_BITS * level));
2016 rc = walk_memory_regions_1(data, pa, level - 1, pp + i);
2017 if (rc != 0) {
2018 return rc;
2023 return 0;
2026 int walk_memory_regions(void *priv, walk_memory_regions_fn fn)
2028 struct walk_memory_regions_data data;
2029 uintptr_t i, l1_sz = v_l1_size;
2031 data.fn = fn;
2032 data.priv = priv;
2033 data.start = -1u;
2034 data.prot = 0;
2036 for (i = 0; i < l1_sz; i++) {
2037 target_ulong base = i << (v_l1_shift + TARGET_PAGE_BITS);
2038 int rc = walk_memory_regions_1(&data, base, v_l2_levels, l1_map + i);
2039 if (rc != 0) {
2040 return rc;
2044 return walk_memory_regions_end(&data, 0, 0);
2047 static int dump_region(void *priv, target_ulong start,
2048 target_ulong end, abi_ulong prot)
2050 FILE *f = (FILE *)priv;
2052 (void) fprintf(f, TARGET_FMT_lx"-"TARGET_FMT_lx
2053 " "TARGET_FMT_lx" %c%c%c\n",
2054 start, end, end - start,
2055 ((prot & PAGE_READ) ? 'r' : '-'),
2056 ((prot & PAGE_WRITE) ? 'w' : '-'),
2057 ((prot & PAGE_EXEC) ? 'x' : '-'));
2059 return 0;
2062 /* dump memory mappings */
2063 void page_dump(FILE *f)
2065 const int length = sizeof(target_ulong) * 2;
2066 (void) fprintf(f, "%-*s %-*s %-*s %s\n",
2067 length, "start", length, "end", length, "size", "prot");
2068 walk_memory_regions(f, dump_region);
2071 int page_get_flags(target_ulong address)
2073 PageDesc *p;
2075 p = page_find(address >> TARGET_PAGE_BITS);
2076 if (!p) {
2077 return 0;
2079 return p->flags;
2082 /* Modify the flags of a page and invalidate the code if necessary.
2083 The flag PAGE_WRITE_ORG is positioned automatically depending
2084 on PAGE_WRITE. The mmap_lock should already be held. */
2085 void page_set_flags(target_ulong start, target_ulong end, int flags)
2087 target_ulong addr, len;
2089 /* This function should never be called with addresses outside the
2090 guest address space. If this assert fires, it probably indicates
2091 a missing call to h2g_valid. */
2092 #if TARGET_ABI_BITS > L1_MAP_ADDR_SPACE_BITS
2093 assert(end < ((target_ulong)1 << L1_MAP_ADDR_SPACE_BITS));
2094 #endif
2095 assert(start < end);
2096 assert_memory_lock();
2098 start = start & TARGET_PAGE_MASK;
2099 end = TARGET_PAGE_ALIGN(end);
2101 if (flags & PAGE_WRITE) {
2102 flags |= PAGE_WRITE_ORG;
2105 for (addr = start, len = end - start;
2106 len != 0;
2107 len -= TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {
2108 PageDesc *p = page_find_alloc(addr >> TARGET_PAGE_BITS, 1);
2110 /* If the write protection bit is set, then we invalidate
2111 the code inside. */
2112 if (!(p->flags & PAGE_WRITE) &&
2113 (flags & PAGE_WRITE) &&
2114 p->first_tb) {
2115 tb_invalidate_phys_page(addr, 0);
2117 p->flags = flags;
2121 int page_check_range(target_ulong start, target_ulong len, int flags)
2123 PageDesc *p;
2124 target_ulong end;
2125 target_ulong addr;
2127 /* This function should never be called with addresses outside the
2128 guest address space. If this assert fires, it probably indicates
2129 a missing call to h2g_valid. */
2130 #if TARGET_ABI_BITS > L1_MAP_ADDR_SPACE_BITS
2131 assert(start < ((target_ulong)1 << L1_MAP_ADDR_SPACE_BITS));
2132 #endif
2134 if (len == 0) {
2135 return 0;
2137 if (start + len - 1 < start) {
2138 /* We've wrapped around. */
2139 return -1;
2142 /* must do before we loose bits in the next step */
2143 end = TARGET_PAGE_ALIGN(start + len);
2144 start = start & TARGET_PAGE_MASK;
2146 for (addr = start, len = end - start;
2147 len != 0;
2148 len -= TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {
2149 p = page_find(addr >> TARGET_PAGE_BITS);
2150 if (!p) {
2151 return -1;
2153 if (!(p->flags & PAGE_VALID)) {
2154 return -1;
2157 if ((flags & PAGE_READ) && !(p->flags & PAGE_READ)) {
2158 return -1;
2160 if (flags & PAGE_WRITE) {
2161 if (!(p->flags & PAGE_WRITE_ORG)) {
2162 return -1;
2164 /* unprotect the page if it was put read-only because it
2165 contains translated code */
2166 if (!(p->flags & PAGE_WRITE)) {
2167 if (!page_unprotect(addr, 0)) {
2168 return -1;
2173 return 0;
2176 /* called from signal handler: invalidate the code and unprotect the
2177 * page. Return 0 if the fault was not handled, 1 if it was handled,
2178 * and 2 if it was handled but the caller must cause the TB to be
2179 * immediately exited. (We can only return 2 if the 'pc' argument is
2180 * non-zero.)
2182 int page_unprotect(target_ulong address, uintptr_t pc)
2184 unsigned int prot;
2185 bool current_tb_invalidated;
2186 PageDesc *p;
2187 target_ulong host_start, host_end, addr;
2189 /* Technically this isn't safe inside a signal handler. However we
2190 know this only ever happens in a synchronous SEGV handler, so in
2191 practice it seems to be ok. */
2192 mmap_lock();
2194 p = page_find(address >> TARGET_PAGE_BITS);
2195 if (!p) {
2196 mmap_unlock();
2197 return 0;
2200 /* if the page was really writable, then we change its
2201 protection back to writable */
2202 if ((p->flags & PAGE_WRITE_ORG) && !(p->flags & PAGE_WRITE)) {
2203 host_start = address & qemu_host_page_mask;
2204 host_end = host_start + qemu_host_page_size;
2206 prot = 0;
2207 current_tb_invalidated = false;
2208 for (addr = host_start ; addr < host_end ; addr += TARGET_PAGE_SIZE) {
2209 p = page_find(addr >> TARGET_PAGE_BITS);
2210 p->flags |= PAGE_WRITE;
2211 prot |= p->flags;
2213 /* and since the content will be modified, we must invalidate
2214 the corresponding translated code. */
2215 current_tb_invalidated |= tb_invalidate_phys_page(addr, pc);
2216 #ifdef DEBUG_TB_CHECK
2217 tb_invalidate_check(addr);
2218 #endif
2220 mprotect((void *)g2h(host_start), qemu_host_page_size,
2221 prot & PAGE_BITS);
2223 mmap_unlock();
2224 /* If current TB was invalidated return to main loop */
2225 return current_tb_invalidated ? 2 : 1;
2227 mmap_unlock();
2228 return 0;
2230 #endif /* CONFIG_USER_ONLY */