Merge remote-tracking branch 'qemu/master'
[qemu/ar7.git] / accel / tcg / translate-all.c
blob6b9d259004e791a736489ea45a0f1e7137091555
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.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/error-report.h"
59 #include "qemu/timer.h"
60 #include "qemu/main-loop.h"
61 #include "exec/log.h"
62 #include "sysemu/cpus.h"
64 /* #define DEBUG_TB_INVALIDATE */
65 /* #define DEBUG_TB_FLUSH */
66 /* make various TB consistency checks */
67 /* #define DEBUG_TB_CHECK */
69 #ifdef DEBUG_TB_INVALIDATE
70 #define DEBUG_TB_INVALIDATE_GATE 1
71 #else
72 #define DEBUG_TB_INVALIDATE_GATE 0
73 #endif
75 #ifdef DEBUG_TB_FLUSH
76 #define DEBUG_TB_FLUSH_GATE 1
77 #else
78 #define DEBUG_TB_FLUSH_GATE 0
79 #endif
81 #if !defined(CONFIG_USER_ONLY)
82 /* TB consistency checks only implemented for usermode emulation. */
83 #undef DEBUG_TB_CHECK
84 #endif
86 #ifdef DEBUG_TB_CHECK
87 #define DEBUG_TB_CHECK_GATE 1
88 #else
89 #define DEBUG_TB_CHECK_GATE 0
90 #endif
92 /* Access to the various translations structures need to be serialised via locks
93 * for consistency. This is automatic for SoftMMU based system
94 * emulation due to its single threaded nature. In user-mode emulation
95 * access to the memory related structures are protected with the
96 * mmap_lock.
98 #ifdef CONFIG_SOFTMMU
99 #define assert_memory_lock() tcg_debug_assert(have_tb_lock)
100 #else
101 #define assert_memory_lock() tcg_debug_assert(have_mmap_lock())
102 #endif
104 #define SMC_BITMAP_USE_THRESHOLD 10
106 typedef struct PageDesc {
107 /* list of TBs intersecting this ram page */
108 TranslationBlock *first_tb;
109 #ifdef CONFIG_SOFTMMU
110 /* in order to optimize self modifying code, we count the number
111 of lookups we do to a given page to use a bitmap */
112 unsigned int code_write_count;
113 unsigned long *code_bitmap;
114 #else
115 unsigned long flags;
116 #endif
117 } PageDesc;
119 /* In system mode we want L1_MAP to be based on ram offsets,
120 while in user mode we want it to be based on virtual addresses. */
121 #if !defined(CONFIG_USER_ONLY)
122 #if HOST_LONG_BITS < TARGET_PHYS_ADDR_SPACE_BITS
123 # define L1_MAP_ADDR_SPACE_BITS HOST_LONG_BITS
124 #else
125 # define L1_MAP_ADDR_SPACE_BITS TARGET_PHYS_ADDR_SPACE_BITS
126 #endif
127 #else
128 # define L1_MAP_ADDR_SPACE_BITS TARGET_VIRT_ADDR_SPACE_BITS
129 #endif
131 /* Size of the L2 (and L3, etc) page tables. */
132 #define V_L2_BITS 10
133 #define V_L2_SIZE (1 << V_L2_BITS)
135 /* Make sure all possible CPU event bits fit in tb->trace_vcpu_dstate */
136 QEMU_BUILD_BUG_ON(CPU_TRACE_DSTATE_MAX_EVENTS >
137 sizeof(((TranslationBlock *)0)->trace_vcpu_dstate)
138 * BITS_PER_BYTE);
141 * L1 Mapping properties
143 static int v_l1_size;
144 static int v_l1_shift;
145 static int v_l2_levels;
147 /* The bottom level has pointers to PageDesc, and is indexed by
148 * anything from 4 to (V_L2_BITS + 3) bits, depending on target page size.
150 #define V_L1_MIN_BITS 4
151 #define V_L1_MAX_BITS (V_L2_BITS + 3)
152 #define V_L1_MAX_SIZE (1 << V_L1_MAX_BITS)
154 static void *l1_map[V_L1_MAX_SIZE];
156 /* code generation context */
157 TCGContext tcg_init_ctx;
158 __thread TCGContext *tcg_ctx;
159 TBContext tb_ctx;
160 bool parallel_cpus;
162 /* translation block context */
163 static __thread int have_tb_lock;
165 static void page_table_config_init(void)
167 uint32_t v_l1_bits;
169 assert(TARGET_PAGE_BITS);
170 /* The bits remaining after N lower levels of page tables. */
171 v_l1_bits = (L1_MAP_ADDR_SPACE_BITS - TARGET_PAGE_BITS) % V_L2_BITS;
172 if (v_l1_bits < V_L1_MIN_BITS) {
173 v_l1_bits += V_L2_BITS;
176 v_l1_size = 1 << v_l1_bits;
177 v_l1_shift = L1_MAP_ADDR_SPACE_BITS - TARGET_PAGE_BITS - v_l1_bits;
178 v_l2_levels = v_l1_shift / V_L2_BITS - 1;
180 assert(v_l1_bits <= V_L1_MAX_BITS);
181 assert(v_l1_shift % V_L2_BITS == 0);
182 assert(v_l2_levels >= 0);
185 #define assert_tb_locked() tcg_debug_assert(have_tb_lock)
186 #define assert_tb_unlocked() tcg_debug_assert(!have_tb_lock)
188 void tb_lock(void)
190 assert_tb_unlocked();
191 qemu_mutex_lock(&tb_ctx.tb_lock);
192 have_tb_lock++;
195 void tb_unlock(void)
197 assert_tb_locked();
198 have_tb_lock--;
199 qemu_mutex_unlock(&tb_ctx.tb_lock);
202 void tb_lock_reset(void)
204 if (have_tb_lock) {
205 qemu_mutex_unlock(&tb_ctx.tb_lock);
206 have_tb_lock = 0;
210 static TranslationBlock *tb_find_pc(uintptr_t tc_ptr);
212 void cpu_gen_init(void)
214 tcg_context_init(&tcg_init_ctx);
217 /* Encode VAL as a signed leb128 sequence at P.
218 Return P incremented past the encoded value. */
219 static uint8_t *encode_sleb128(uint8_t *p, target_long val)
221 int more, byte;
223 do {
224 byte = val & 0x7f;
225 val >>= 7;
226 more = !((val == 0 && (byte & 0x40) == 0)
227 || (val == -1 && (byte & 0x40) != 0));
228 if (more) {
229 byte |= 0x80;
231 *p++ = byte;
232 } while (more);
234 return p;
237 /* Decode a signed leb128 sequence at *PP; increment *PP past the
238 decoded value. Return the decoded value. */
239 static target_long decode_sleb128(uint8_t **pp)
241 uint8_t *p = *pp;
242 target_long val = 0;
243 int byte, shift = 0;
245 do {
246 byte = *p++;
247 val |= (target_ulong)(byte & 0x7f) << shift;
248 shift += 7;
249 } while (byte & 0x80);
250 if (shift < TARGET_LONG_BITS && (byte & 0x40)) {
251 val |= -(target_ulong)1 << shift;
254 *pp = p;
255 return val;
258 /* Encode the data collected about the instructions while compiling TB.
259 Place the data at BLOCK, and return the number of bytes consumed.
261 The logical table consists of TARGET_INSN_START_WORDS target_ulong's,
262 which come from the target's insn_start data, followed by a uintptr_t
263 which comes from the host pc of the end of the code implementing the insn.
265 Each line of the table is encoded as sleb128 deltas from the previous
266 line. The seed for the first line is { tb->pc, 0..., tb->tc.ptr }.
267 That is, the first column is seeded with the guest pc, the last column
268 with the host pc, and the middle columns with zeros. */
270 static int encode_search(TranslationBlock *tb, uint8_t *block)
272 uint8_t *highwater = tcg_ctx->code_gen_highwater;
273 uint8_t *p = block;
274 int i, j, n;
276 for (i = 0, n = tb->icount; i < n; ++i) {
277 target_ulong prev;
279 for (j = 0; j < TARGET_INSN_START_WORDS; ++j) {
280 if (i == 0) {
281 prev = (j == 0 ? tb->pc : 0);
282 } else {
283 prev = tcg_ctx->gen_insn_data[i - 1][j];
285 p = encode_sleb128(p, tcg_ctx->gen_insn_data[i][j] - prev);
287 prev = (i == 0 ? 0 : tcg_ctx->gen_insn_end_off[i - 1]);
288 p = encode_sleb128(p, tcg_ctx->gen_insn_end_off[i] - prev);
290 /* Test for (pending) buffer overflow. The assumption is that any
291 one row beginning below the high water mark cannot overrun
292 the buffer completely. Thus we can test for overflow after
293 encoding a row without having to check during encoding. */
294 if (unlikely(p > highwater)) {
295 return -1;
299 return p - block;
302 /* The cpu state corresponding to 'searched_pc' is restored.
303 * Called with tb_lock held.
305 static int cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,
306 uintptr_t searched_pc)
308 target_ulong data[TARGET_INSN_START_WORDS] = { tb->pc };
309 uintptr_t host_pc = (uintptr_t)tb->tc.ptr;
310 CPUArchState *env = cpu->env_ptr;
311 uint8_t *p = tb->tc.ptr + tb->tc.size;
312 int i, j, num_insns = tb->icount;
313 #ifdef CONFIG_PROFILER
314 TCGProfile *prof = &tcg_ctx->prof;
315 int64_t ti = profile_getclock();
316 #endif
318 searched_pc -= GETPC_ADJ;
320 if (searched_pc < host_pc) {
321 return -1;
324 /* Reconstruct the stored insn data while looking for the point at
325 which the end of the insn exceeds the searched_pc. */
326 for (i = 0; i < num_insns; ++i) {
327 for (j = 0; j < TARGET_INSN_START_WORDS; ++j) {
328 data[j] += decode_sleb128(&p);
330 host_pc += decode_sleb128(&p);
331 if (host_pc > searched_pc) {
332 goto found;
335 return -1;
337 found:
338 if (tb->cflags & CF_USE_ICOUNT) {
339 assert(use_icount);
340 /* Reset the cycle counter to the start of the block. */
341 cpu->icount_decr.u16.low += num_insns;
342 /* Clear the IO flag. */
343 cpu->can_do_io = 0;
345 cpu->icount_decr.u16.low -= i;
346 restore_state_to_opc(env, tb, data);
348 #ifdef CONFIG_PROFILER
349 atomic_set(&prof->restore_time,
350 prof->restore_time + profile_getclock() - ti);
351 atomic_set(&prof->restore_count, prof->restore_count + 1);
352 #endif
353 return 0;
356 bool cpu_restore_state(CPUState *cpu, uintptr_t host_pc)
358 TranslationBlock *tb;
359 bool r = false;
360 uintptr_t check_offset;
362 /* The host_pc has to be in the region of current code buffer. If
363 * it is not we will not be able to resolve it here. The two cases
364 * where host_pc will not be correct are:
366 * - fault during translation (instruction fetch)
367 * - fault from helper (not using GETPC() macro)
369 * Either way we need return early to avoid blowing up on a
370 * recursive tb_lock() as we can't resolve it here.
372 * We are using unsigned arithmetic so if host_pc <
373 * tcg_init_ctx.code_gen_buffer check_offset will wrap to way
374 * above the code_gen_buffer_size
376 check_offset = host_pc - (uintptr_t) tcg_init_ctx.code_gen_buffer;
378 if (check_offset < tcg_init_ctx.code_gen_buffer_size) {
379 tb_lock();
380 tb = tb_find_pc(host_pc);
381 if (tb) {
382 cpu_restore_state_from_tb(cpu, tb, host_pc);
383 if (tb->cflags & CF_NOCACHE) {
384 /* one-shot translation, invalidate it immediately */
385 tb_phys_invalidate(tb, -1);
386 tb_remove(tb);
388 r = true;
390 tb_unlock();
393 return r;
396 static void page_init(void)
398 page_size_init();
399 page_table_config_init();
401 #if defined(CONFIG_BSD) && defined(CONFIG_USER_ONLY)
403 #ifdef HAVE_KINFO_GETVMMAP
404 struct kinfo_vmentry *freep;
405 int i, cnt;
407 freep = kinfo_getvmmap(getpid(), &cnt);
408 if (freep) {
409 mmap_lock();
410 for (i = 0; i < cnt; i++) {
411 unsigned long startaddr, endaddr;
413 startaddr = freep[i].kve_start;
414 endaddr = freep[i].kve_end;
415 if (h2g_valid(startaddr)) {
416 startaddr = h2g(startaddr) & TARGET_PAGE_MASK;
418 if (h2g_valid(endaddr)) {
419 endaddr = h2g(endaddr);
420 page_set_flags(startaddr, endaddr, PAGE_RESERVED);
421 } else {
422 #if TARGET_ABI_BITS <= L1_MAP_ADDR_SPACE_BITS
423 endaddr = ~0ul;
424 page_set_flags(startaddr, endaddr, PAGE_RESERVED);
425 #endif
429 free(freep);
430 mmap_unlock();
432 #else
433 FILE *f;
435 last_brk = (unsigned long)sbrk(0);
437 f = fopen("/compat/linux/proc/self/maps", "r");
438 if (f) {
439 mmap_lock();
441 do {
442 unsigned long startaddr, endaddr;
443 int n;
445 n = fscanf(f, "%lx-%lx %*[^\n]\n", &startaddr, &endaddr);
447 if (n == 2 && h2g_valid(startaddr)) {
448 startaddr = h2g(startaddr) & TARGET_PAGE_MASK;
450 if (h2g_valid(endaddr)) {
451 endaddr = h2g(endaddr);
452 } else {
453 endaddr = ~0ul;
455 page_set_flags(startaddr, endaddr, PAGE_RESERVED);
457 } while (!feof(f));
459 fclose(f);
460 mmap_unlock();
462 #endif
464 #endif
467 /* If alloc=1:
468 * Called with tb_lock held for system emulation.
469 * Called with mmap_lock held for user-mode emulation.
471 static PageDesc *page_find_alloc(tb_page_addr_t index, int alloc)
473 PageDesc *pd;
474 void **lp;
475 int i;
477 if (alloc) {
478 assert_memory_lock();
481 /* Level 1. Always allocated. */
482 lp = l1_map + ((index >> v_l1_shift) & (v_l1_size - 1));
484 /* Level 2..N-1. */
485 for (i = v_l2_levels; i > 0; i--) {
486 void **p = atomic_rcu_read(lp);
488 if (p == NULL) {
489 if (!alloc) {
490 return NULL;
492 p = g_new0(void *, V_L2_SIZE);
493 atomic_rcu_set(lp, p);
496 lp = p + ((index >> (i * V_L2_BITS)) & (V_L2_SIZE - 1));
499 pd = atomic_rcu_read(lp);
500 if (pd == NULL) {
501 if (!alloc) {
502 return NULL;
504 pd = g_new0(PageDesc, V_L2_SIZE);
505 atomic_rcu_set(lp, pd);
508 return pd + (index & (V_L2_SIZE - 1));
511 static inline PageDesc *page_find(tb_page_addr_t index)
513 return page_find_alloc(index, 0);
516 #if defined(CONFIG_USER_ONLY)
517 /* Currently it is not recommended to allocate big chunks of data in
518 user mode. It will change when a dedicated libc will be used. */
519 /* ??? 64-bit hosts ought to have no problem mmaping data outside the
520 region in which the guest needs to run. Revisit this. */
521 #define USE_STATIC_CODE_GEN_BUFFER
522 #endif
524 /* Minimum size of the code gen buffer. This number is randomly chosen,
525 but not so small that we can't have a fair number of TB's live. */
526 #define MIN_CODE_GEN_BUFFER_SIZE (1024u * 1024)
528 /* Maximum size of the code gen buffer we'd like to use. Unless otherwise
529 indicated, this is constrained by the range of direct branches on the
530 host cpu, as used by the TCG implementation of goto_tb. */
531 #if defined(__x86_64__)
532 # define MAX_CODE_GEN_BUFFER_SIZE (2ul * 1024 * 1024 * 1024)
533 #elif defined(__sparc__)
534 # define MAX_CODE_GEN_BUFFER_SIZE (2ul * 1024 * 1024 * 1024)
535 #elif defined(__powerpc64__)
536 # define MAX_CODE_GEN_BUFFER_SIZE (2ul * 1024 * 1024 * 1024)
537 #elif defined(__powerpc__)
538 # define MAX_CODE_GEN_BUFFER_SIZE (32u * 1024 * 1024)
539 #elif defined(__aarch64__)
540 # define MAX_CODE_GEN_BUFFER_SIZE (2ul * 1024 * 1024 * 1024)
541 #elif defined(__s390x__)
542 /* We have a +- 4GB range on the branches; leave some slop. */
543 # define MAX_CODE_GEN_BUFFER_SIZE (3ul * 1024 * 1024 * 1024)
544 #elif defined(__mips__)
545 /* We have a 256MB branch region, but leave room to make sure the
546 main executable is also within that region. */
547 # define MAX_CODE_GEN_BUFFER_SIZE (128ul * 1024 * 1024)
548 #else
549 # define MAX_CODE_GEN_BUFFER_SIZE ((size_t)-1)
550 #endif
552 #define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (32u * 1024 * 1024)
554 #define DEFAULT_CODE_GEN_BUFFER_SIZE \
555 (DEFAULT_CODE_GEN_BUFFER_SIZE_1 < MAX_CODE_GEN_BUFFER_SIZE \
556 ? DEFAULT_CODE_GEN_BUFFER_SIZE_1 : MAX_CODE_GEN_BUFFER_SIZE)
558 static inline size_t size_code_gen_buffer(size_t tb_size)
560 /* Size the buffer. */
561 if (tb_size == 0) {
562 #ifdef USE_STATIC_CODE_GEN_BUFFER
563 tb_size = DEFAULT_CODE_GEN_BUFFER_SIZE;
564 #else
565 /* ??? Needs adjustments. */
566 /* ??? If we relax the requirement that CONFIG_USER_ONLY use the
567 static buffer, we could size this on RESERVED_VA, on the text
568 segment size of the executable, or continue to use the default. */
569 tb_size = (unsigned long)(ram_size / 4);
570 #endif
572 if (tb_size < MIN_CODE_GEN_BUFFER_SIZE) {
573 tb_size = MIN_CODE_GEN_BUFFER_SIZE;
575 if (tb_size > MAX_CODE_GEN_BUFFER_SIZE) {
576 tb_size = MAX_CODE_GEN_BUFFER_SIZE;
578 return tb_size;
581 #ifdef __mips__
582 /* In order to use J and JAL within the code_gen_buffer, we require
583 that the buffer not cross a 256MB boundary. */
584 static inline bool cross_256mb(void *addr, size_t size)
586 return ((uintptr_t)addr ^ ((uintptr_t)addr + size)) & ~0x0ffffffful;
589 /* We weren't able to allocate a buffer without crossing that boundary,
590 so make do with the larger portion of the buffer that doesn't cross.
591 Returns the new base of the buffer, and adjusts code_gen_buffer_size. */
592 static inline void *split_cross_256mb(void *buf1, size_t size1)
594 void *buf2 = (void *)(((uintptr_t)buf1 + size1) & ~0x0ffffffful);
595 size_t size2 = buf1 + size1 - buf2;
597 size1 = buf2 - buf1;
598 if (size1 < size2) {
599 size1 = size2;
600 buf1 = buf2;
603 tcg_ctx->code_gen_buffer_size = size1;
604 return buf1;
606 #endif
608 #ifdef USE_STATIC_CODE_GEN_BUFFER
609 static uint8_t static_code_gen_buffer[DEFAULT_CODE_GEN_BUFFER_SIZE]
610 __attribute__((aligned(CODE_GEN_ALIGN)));
612 static inline void *alloc_code_gen_buffer(void)
614 void *buf = static_code_gen_buffer;
615 void *end = static_code_gen_buffer + sizeof(static_code_gen_buffer);
616 size_t size;
618 /* page-align the beginning and end of the buffer */
619 buf = QEMU_ALIGN_PTR_UP(buf, qemu_real_host_page_size);
620 end = QEMU_ALIGN_PTR_DOWN(end, qemu_real_host_page_size);
622 size = end - buf;
624 /* Honor a command-line option limiting the size of the buffer. */
625 if (size > tcg_ctx->code_gen_buffer_size) {
626 size = QEMU_ALIGN_DOWN(tcg_ctx->code_gen_buffer_size,
627 qemu_real_host_page_size);
629 tcg_ctx->code_gen_buffer_size = size;
631 #ifdef __mips__
632 if (cross_256mb(buf, size)) {
633 buf = split_cross_256mb(buf, size);
634 size = tcg_ctx->code_gen_buffer_size;
636 #endif
638 if (qemu_mprotect_rwx(buf, size)) {
639 abort();
641 qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);
643 return buf;
645 #elif defined(_WIN32)
646 static inline void *alloc_code_gen_buffer(void)
648 size_t size = tcg_ctx->code_gen_buffer_size;
649 void *buf;
651 buf = VirtualAlloc(NULL, size, MEM_RESERVE | MEM_COMMIT,
652 PAGE_EXECUTE_READWRITE);
653 return buf;
655 #else
656 static inline void *alloc_code_gen_buffer(void)
658 int prot = PROT_WRITE | PROT_READ | PROT_EXEC;
659 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
660 uintptr_t start = 0;
661 size_t size = tcg_ctx->code_gen_buffer_size;
662 void *buf;
664 /* Constrain the position of the buffer based on the host cpu.
665 Note that these addresses are chosen in concert with the
666 addresses assigned in the relevant linker script file. */
667 # if defined(__PIE__) || defined(__PIC__)
668 /* Don't bother setting a preferred location if we're building
669 a position-independent executable. We're more likely to get
670 an address near the main executable if we let the kernel
671 choose the address. */
672 # elif defined(__x86_64__) && defined(MAP_32BIT)
673 /* Force the memory down into low memory with the executable.
674 Leave the choice of exact location with the kernel. */
675 flags |= MAP_32BIT;
676 /* Cannot expect to map more than 800MB in low memory. */
677 if (size > 800u * 1024 * 1024) {
678 tcg_ctx->code_gen_buffer_size = size = 800u * 1024 * 1024;
680 # elif defined(__sparc__)
681 start = 0x40000000ul;
682 # elif defined(__s390x__)
683 start = 0x90000000ul;
684 # elif defined(__mips__)
685 # if _MIPS_SIM == _ABI64
686 start = 0x128000000ul;
687 # else
688 start = 0x08000000ul;
689 # endif
690 # endif
692 buf = mmap((void *)start, size, prot, flags, -1, 0);
693 if (buf == MAP_FAILED) {
694 return NULL;
697 #ifdef __mips__
698 if (cross_256mb(buf, size)) {
699 /* Try again, with the original still mapped, to avoid re-acquiring
700 that 256mb crossing. This time don't specify an address. */
701 size_t size2;
702 void *buf2 = mmap(NULL, size, prot, flags, -1, 0);
703 switch ((int)(buf2 != MAP_FAILED)) {
704 case 1:
705 if (!cross_256mb(buf2, size)) {
706 /* Success! Use the new buffer. */
707 munmap(buf, size);
708 break;
710 /* Failure. Work with what we had. */
711 munmap(buf2, size);
712 /* fallthru */
713 default:
714 /* Split the original buffer. Free the smaller half. */
715 buf2 = split_cross_256mb(buf, size);
716 size2 = tcg_ctx->code_gen_buffer_size;
717 if (buf == buf2) {
718 munmap(buf + size2, size - size2);
719 } else {
720 munmap(buf, size - size2);
722 size = size2;
723 break;
725 buf = buf2;
727 #endif
729 /* Request large pages for the buffer. */
730 qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);
732 return buf;
734 #endif /* USE_STATIC_CODE_GEN_BUFFER, WIN32, POSIX */
736 /* compare a pointer @ptr and a tb_tc @s */
737 static int ptr_cmp_tb_tc(const void *ptr, const struct tb_tc *s)
739 if (ptr >= s->ptr + s->size) {
740 return 1;
741 } else if (ptr < s->ptr) {
742 return -1;
744 return 0;
747 static gint tb_tc_cmp(gconstpointer ap, gconstpointer bp)
749 const struct tb_tc *a = ap;
750 const struct tb_tc *b = bp;
753 * When both sizes are set, we know this isn't a lookup.
754 * This is the most likely case: every TB must be inserted; lookups
755 * are a lot less frequent.
757 if (likely(a->size && b->size)) {
758 if (a->ptr > b->ptr) {
759 return 1;
760 } else if (a->ptr < b->ptr) {
761 return -1;
763 /* a->ptr == b->ptr should happen only on deletions */
764 g_assert(a->size == b->size);
765 return 0;
768 * All lookups have either .size field set to 0.
769 * From the glib sources we see that @ap is always the lookup key. However
770 * the docs provide no guarantee, so we just mark this case as likely.
772 if (likely(a->size == 0)) {
773 return ptr_cmp_tb_tc(a->ptr, b);
775 return ptr_cmp_tb_tc(b->ptr, a);
778 static inline void code_gen_alloc(size_t tb_size)
780 tcg_ctx->code_gen_buffer_size = size_code_gen_buffer(tb_size);
781 tcg_ctx->code_gen_buffer = alloc_code_gen_buffer();
782 if (tcg_ctx->code_gen_buffer == NULL) {
783 fprintf(stderr, "Could not allocate dynamic translator buffer\n");
784 exit(1);
786 tb_ctx.tb_tree = g_tree_new(tb_tc_cmp);
787 qemu_mutex_init(&tb_ctx.tb_lock);
790 static void tb_htable_init(void)
792 unsigned int mode = QHT_MODE_AUTO_RESIZE;
794 qht_init(&tb_ctx.htable, CODE_GEN_HTABLE_SIZE, mode);
797 /* Must be called before using the QEMU cpus. 'tb_size' is the size
798 (in bytes) allocated to the translation buffer. Zero means default
799 size. */
800 void tcg_exec_init(uintptr_t tb_size)
802 tcg_allowed = true;
803 cpu_gen_init();
804 page_init();
805 tb_htable_init();
806 code_gen_alloc(tb_size);
807 #if defined(CONFIG_SOFTMMU)
808 /* There's no guest base to take into account, so go ahead and
809 initialize the prologue now. */
810 tcg_prologue_init(tcg_ctx);
811 #endif
815 * Allocate a new translation block. Flush the translation buffer if
816 * too many translation blocks or too much generated code.
818 * Called with tb_lock held.
820 static TranslationBlock *tb_alloc(target_ulong pc)
822 TranslationBlock *tb;
824 assert_tb_locked();
826 tb = tcg_tb_alloc(tcg_ctx);
827 if (unlikely(tb == NULL)) {
828 return NULL;
830 return tb;
833 /* Called with tb_lock held. */
834 void tb_remove(TranslationBlock *tb)
836 assert_tb_locked();
838 g_tree_remove(tb_ctx.tb_tree, &tb->tc);
841 static inline void invalidate_page_bitmap(PageDesc *p)
843 #ifdef CONFIG_SOFTMMU
844 g_free(p->code_bitmap);
845 p->code_bitmap = NULL;
846 p->code_write_count = 0;
847 #endif
850 /* Set to NULL all the 'first_tb' fields in all PageDescs. */
851 static void page_flush_tb_1(int level, void **lp)
853 int i;
855 if (*lp == NULL) {
856 return;
858 if (level == 0) {
859 PageDesc *pd = *lp;
861 for (i = 0; i < V_L2_SIZE; ++i) {
862 pd[i].first_tb = NULL;
863 invalidate_page_bitmap(pd + i);
865 } else {
866 void **pp = *lp;
868 for (i = 0; i < V_L2_SIZE; ++i) {
869 page_flush_tb_1(level - 1, pp + i);
874 static void page_flush_tb(void)
876 int i, l1_sz = v_l1_size;
878 for (i = 0; i < l1_sz; i++) {
879 page_flush_tb_1(v_l2_levels, l1_map + i);
883 static gboolean tb_host_size_iter(gpointer key, gpointer value, gpointer data)
885 const TranslationBlock *tb = value;
886 size_t *size = data;
888 *size += tb->tc.size;
889 return false;
892 /* flush all the translation blocks */
893 static void do_tb_flush(CPUState *cpu, run_on_cpu_data tb_flush_count)
895 tb_lock();
897 /* If it is already been done on request of another CPU,
898 * just retry.
900 if (tb_ctx.tb_flush_count != tb_flush_count.host_int) {
901 goto done;
904 if (DEBUG_TB_FLUSH_GATE) {
905 size_t nb_tbs = g_tree_nnodes(tb_ctx.tb_tree);
906 size_t host_size = 0;
908 g_tree_foreach(tb_ctx.tb_tree, tb_host_size_iter, &host_size);
909 printf("qemu: flush code_size=%zu nb_tbs=%zu avg_tb_size=%zu\n",
910 tcg_code_size(), nb_tbs, nb_tbs > 0 ? host_size / nb_tbs : 0);
913 CPU_FOREACH(cpu) {
914 cpu_tb_jmp_cache_clear(cpu);
917 /* Increment the refcount first so that destroy acts as a reset */
918 g_tree_ref(tb_ctx.tb_tree);
919 g_tree_destroy(tb_ctx.tb_tree);
921 qht_reset_size(&tb_ctx.htable, CODE_GEN_HTABLE_SIZE);
922 page_flush_tb();
924 tcg_region_reset_all();
925 /* XXX: flush processor icache at this point if cache flush is
926 expensive */
927 atomic_mb_set(&tb_ctx.tb_flush_count, tb_ctx.tb_flush_count + 1);
929 done:
930 tb_unlock();
933 void tb_flush(CPUState *cpu)
935 if (tcg_enabled()) {
936 unsigned tb_flush_count = atomic_mb_read(&tb_ctx.tb_flush_count);
937 async_safe_run_on_cpu(cpu, do_tb_flush,
938 RUN_ON_CPU_HOST_INT(tb_flush_count));
943 * Formerly ifdef DEBUG_TB_CHECK. These debug functions are user-mode-only,
944 * so in order to prevent bit rot we compile them unconditionally in user-mode,
945 * and let the optimizer get rid of them by wrapping their user-only callers
946 * with if (DEBUG_TB_CHECK_GATE).
948 #ifdef CONFIG_USER_ONLY
950 static void
951 do_tb_invalidate_check(struct qht *ht, void *p, uint32_t hash, void *userp)
953 TranslationBlock *tb = p;
954 target_ulong addr = *(target_ulong *)userp;
956 if (!(addr + TARGET_PAGE_SIZE <= tb->pc || addr >= tb->pc + tb->size)) {
957 printf("ERROR invalidate: address=" TARGET_FMT_lx
958 " PC=%08lx size=%04x\n", addr, (long)tb->pc, tb->size);
962 /* verify that all the pages have correct rights for code
964 * Called with tb_lock held.
966 static void tb_invalidate_check(target_ulong address)
968 address &= TARGET_PAGE_MASK;
969 qht_iter(&tb_ctx.htable, do_tb_invalidate_check, &address);
972 static void
973 do_tb_page_check(struct qht *ht, void *p, uint32_t hash, void *userp)
975 TranslationBlock *tb = p;
976 int flags1, flags2;
978 flags1 = page_get_flags(tb->pc);
979 flags2 = page_get_flags(tb->pc + tb->size - 1);
980 if ((flags1 & PAGE_WRITE) || (flags2 & PAGE_WRITE)) {
981 printf("ERROR page flags: PC=%08lx size=%04x f1=%x f2=%x\n",
982 (long)tb->pc, tb->size, flags1, flags2);
986 /* verify that all the pages have correct rights for code */
987 static void tb_page_check(void)
989 qht_iter(&tb_ctx.htable, do_tb_page_check, NULL);
992 #endif /* CONFIG_USER_ONLY */
994 static inline void tb_page_remove(TranslationBlock **ptb, TranslationBlock *tb)
996 TranslationBlock *tb1;
997 unsigned int n1;
999 for (;;) {
1000 tb1 = *ptb;
1001 n1 = (uintptr_t)tb1 & 3;
1002 tb1 = (TranslationBlock *)((uintptr_t)tb1 & ~3);
1003 if (tb1 == tb) {
1004 *ptb = tb1->page_next[n1];
1005 break;
1007 ptb = &tb1->page_next[n1];
1011 /* remove the TB from a list of TBs jumping to the n-th jump target of the TB */
1012 static inline void tb_remove_from_jmp_list(TranslationBlock *tb, int n)
1014 TranslationBlock *tb1;
1015 uintptr_t *ptb, ntb;
1016 unsigned int n1;
1018 ptb = &tb->jmp_list_next[n];
1019 if (*ptb) {
1020 /* find tb(n) in circular list */
1021 for (;;) {
1022 ntb = *ptb;
1023 n1 = ntb & 3;
1024 tb1 = (TranslationBlock *)(ntb & ~3);
1025 if (n1 == n && tb1 == tb) {
1026 break;
1028 if (n1 == 2) {
1029 ptb = &tb1->jmp_list_first;
1030 } else {
1031 ptb = &tb1->jmp_list_next[n1];
1034 /* now we can suppress tb(n) from the list */
1035 *ptb = tb->jmp_list_next[n];
1037 tb->jmp_list_next[n] = (uintptr_t)NULL;
1041 /* reset the jump entry 'n' of a TB so that it is not chained to
1042 another TB */
1043 static inline void tb_reset_jump(TranslationBlock *tb, int n)
1045 uintptr_t addr = (uintptr_t)(tb->tc.ptr + tb->jmp_reset_offset[n]);
1046 tb_set_jmp_target(tb, n, addr);
1049 /* remove any jumps to the TB */
1050 static inline void tb_jmp_unlink(TranslationBlock *tb)
1052 TranslationBlock *tb1;
1053 uintptr_t *ptb, ntb;
1054 unsigned int n1;
1056 ptb = &tb->jmp_list_first;
1057 for (;;) {
1058 ntb = *ptb;
1059 n1 = ntb & 3;
1060 tb1 = (TranslationBlock *)(ntb & ~3);
1061 if (n1 == 2) {
1062 break;
1064 tb_reset_jump(tb1, n1);
1065 *ptb = tb1->jmp_list_next[n1];
1066 tb1->jmp_list_next[n1] = (uintptr_t)NULL;
1070 /* invalidate one TB
1072 * Called with tb_lock held.
1074 void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr)
1076 CPUState *cpu;
1077 PageDesc *p;
1078 uint32_t h;
1079 tb_page_addr_t phys_pc;
1081 assert_tb_locked();
1083 atomic_set(&tb->cflags, tb->cflags | CF_INVALID);
1085 /* remove the TB from the hash list */
1086 phys_pc = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);
1087 h = tb_hash_func(phys_pc, tb->pc, tb->flags, tb->cflags & CF_HASH_MASK,
1088 tb->trace_vcpu_dstate);
1089 if (!qht_remove(&tb_ctx.htable, tb, h)) {
1090 return;
1093 /* remove the TB from the page list */
1094 if (tb->page_addr[0] != page_addr) {
1095 p = page_find(tb->page_addr[0] >> TARGET_PAGE_BITS);
1096 tb_page_remove(&p->first_tb, tb);
1097 invalidate_page_bitmap(p);
1099 if (tb->page_addr[1] != -1 && tb->page_addr[1] != page_addr) {
1100 p = page_find(tb->page_addr[1] >> TARGET_PAGE_BITS);
1101 tb_page_remove(&p->first_tb, tb);
1102 invalidate_page_bitmap(p);
1105 /* remove the TB from the hash list */
1106 h = tb_jmp_cache_hash_func(tb->pc);
1107 CPU_FOREACH(cpu) {
1108 if (atomic_read(&cpu->tb_jmp_cache[h]) == tb) {
1109 atomic_set(&cpu->tb_jmp_cache[h], NULL);
1113 /* suppress this TB from the two jump lists */
1114 tb_remove_from_jmp_list(tb, 0);
1115 tb_remove_from_jmp_list(tb, 1);
1117 /* suppress any remaining jumps to this TB */
1118 tb_jmp_unlink(tb);
1120 tb_ctx.tb_phys_invalidate_count++;
1123 #ifdef CONFIG_SOFTMMU
1124 static void build_page_bitmap(PageDesc *p)
1126 int n, tb_start, tb_end;
1127 TranslationBlock *tb;
1129 p->code_bitmap = bitmap_new(TARGET_PAGE_SIZE);
1131 tb = p->first_tb;
1132 while (tb != NULL) {
1133 n = (uintptr_t)tb & 3;
1134 tb = (TranslationBlock *)((uintptr_t)tb & ~3);
1135 /* NOTE: this is subtle as a TB may span two physical pages */
1136 if (n == 0) {
1137 /* NOTE: tb_end may be after the end of the page, but
1138 it is not a problem */
1139 tb_start = tb->pc & ~TARGET_PAGE_MASK;
1140 tb_end = tb_start + tb->size;
1141 if (tb_end > TARGET_PAGE_SIZE) {
1142 tb_end = TARGET_PAGE_SIZE;
1144 } else {
1145 tb_start = 0;
1146 tb_end = ((tb->pc + tb->size) & ~TARGET_PAGE_MASK);
1148 bitmap_set(p->code_bitmap, tb_start, tb_end - tb_start);
1149 tb = tb->page_next[n];
1152 #endif
1154 /* add the tb in the target page and protect it if necessary
1156 * Called with mmap_lock held for user-mode emulation.
1158 static inline void tb_alloc_page(TranslationBlock *tb,
1159 unsigned int n, tb_page_addr_t page_addr)
1161 PageDesc *p;
1162 #ifndef CONFIG_USER_ONLY
1163 bool page_already_protected;
1164 #endif
1166 assert_memory_lock();
1168 tb->page_addr[n] = page_addr;
1169 p = page_find_alloc(page_addr >> TARGET_PAGE_BITS, 1);
1170 tb->page_next[n] = p->first_tb;
1171 #ifndef CONFIG_USER_ONLY
1172 page_already_protected = p->first_tb != NULL;
1173 #endif
1174 p->first_tb = (TranslationBlock *)((uintptr_t)tb | n);
1175 invalidate_page_bitmap(p);
1177 #if defined(CONFIG_USER_ONLY)
1178 if (p->flags & PAGE_WRITE) {
1179 target_ulong addr;
1180 PageDesc *p2;
1181 int prot;
1183 /* force the host page as non writable (writes will have a
1184 page fault + mprotect overhead) */
1185 page_addr &= qemu_host_page_mask;
1186 prot = 0;
1187 for (addr = page_addr; addr < page_addr + qemu_host_page_size;
1188 addr += TARGET_PAGE_SIZE) {
1190 p2 = page_find(addr >> TARGET_PAGE_BITS);
1191 if (!p2) {
1192 continue;
1194 prot |= p2->flags;
1195 p2->flags &= ~PAGE_WRITE;
1197 mprotect(g2h(page_addr), qemu_host_page_size,
1198 (prot & PAGE_BITS) & ~PAGE_WRITE);
1199 if (DEBUG_TB_INVALIDATE_GATE) {
1200 printf("protecting code page: 0x" TB_PAGE_ADDR_FMT "\n", page_addr);
1203 #else
1204 /* if some code is already present, then the pages are already
1205 protected. So we handle the case where only the first TB is
1206 allocated in a physical page */
1207 if (!page_already_protected) {
1208 tlb_protect_code(page_addr);
1210 #endif
1213 /* add a new TB and link it to the physical page tables. phys_page2 is
1214 * (-1) to indicate that only one page contains the TB.
1216 * Called with mmap_lock held for user-mode emulation.
1218 static void tb_link_page(TranslationBlock *tb, tb_page_addr_t phys_pc,
1219 tb_page_addr_t phys_page2)
1221 uint32_t h;
1223 assert_memory_lock();
1225 /* add in the page list */
1226 tb_alloc_page(tb, 0, phys_pc & TARGET_PAGE_MASK);
1227 if (phys_page2 != -1) {
1228 tb_alloc_page(tb, 1, phys_page2);
1229 } else {
1230 tb->page_addr[1] = -1;
1233 /* add in the hash table */
1234 h = tb_hash_func(phys_pc, tb->pc, tb->flags, tb->cflags & CF_HASH_MASK,
1235 tb->trace_vcpu_dstate);
1236 qht_insert(&tb_ctx.htable, tb, h);
1238 #ifdef CONFIG_USER_ONLY
1239 if (DEBUG_TB_CHECK_GATE) {
1240 tb_page_check();
1242 #endif
1245 /* Called with mmap_lock held for user mode emulation. */
1246 TranslationBlock *tb_gen_code(CPUState *cpu,
1247 target_ulong pc, target_ulong cs_base,
1248 uint32_t flags, int cflags)
1250 CPUArchState *env = cpu->env_ptr;
1251 TranslationBlock *tb;
1252 tb_page_addr_t phys_pc, phys_page2;
1253 target_ulong virt_page2;
1254 tcg_insn_unit *gen_code_buf;
1255 int gen_code_size, search_size;
1256 #ifdef CONFIG_PROFILER
1257 TCGProfile *prof = &tcg_ctx->prof;
1258 int64_t ti;
1259 #endif
1260 assert_memory_lock();
1262 phys_pc = get_page_addr_code(env, pc);
1264 buffer_overflow:
1265 tb = tb_alloc(pc);
1266 if (unlikely(!tb)) {
1267 /* flush must be done */
1268 tb_flush(cpu);
1269 mmap_unlock();
1270 /* Make the execution loop process the flush as soon as possible. */
1271 cpu->exception_index = EXCP_INTERRUPT;
1272 cpu_loop_exit(cpu);
1275 gen_code_buf = tcg_ctx->code_gen_ptr;
1276 tb->tc.ptr = gen_code_buf;
1277 tb->pc = pc;
1278 tb->cs_base = cs_base;
1279 tb->flags = flags;
1280 tb->cflags = cflags;
1281 tb->trace_vcpu_dstate = *cpu->trace_dstate;
1282 tcg_ctx->tb_cflags = cflags;
1284 #ifdef CONFIG_PROFILER
1285 /* includes aborted translations because of exceptions */
1286 atomic_set(&prof->tb_count1, prof->tb_count1 + 1);
1287 ti = profile_getclock();
1288 #endif
1290 tcg_func_start(tcg_ctx);
1292 tcg_ctx->cpu = ENV_GET_CPU(env);
1293 gen_intermediate_code(cpu, tb);
1294 tcg_ctx->cpu = NULL;
1296 trace_translate_block(tb, tb->pc, tb->tc.ptr);
1298 /* generate machine code */
1299 tb->jmp_reset_offset[0] = TB_JMP_RESET_OFFSET_INVALID;
1300 tb->jmp_reset_offset[1] = TB_JMP_RESET_OFFSET_INVALID;
1301 tcg_ctx->tb_jmp_reset_offset = tb->jmp_reset_offset;
1302 if (TCG_TARGET_HAS_direct_jump) {
1303 tcg_ctx->tb_jmp_insn_offset = tb->jmp_target_arg;
1304 tcg_ctx->tb_jmp_target_addr = NULL;
1305 } else {
1306 tcg_ctx->tb_jmp_insn_offset = NULL;
1307 tcg_ctx->tb_jmp_target_addr = tb->jmp_target_arg;
1310 #ifdef CONFIG_PROFILER
1311 atomic_set(&prof->tb_count, prof->tb_count + 1);
1312 atomic_set(&prof->interm_time, prof->interm_time + profile_getclock() - ti);
1313 ti = profile_getclock();
1314 #endif
1316 /* ??? Overflow could be handled better here. In particular, we
1317 don't need to re-do gen_intermediate_code, nor should we re-do
1318 the tcg optimization currently hidden inside tcg_gen_code. All
1319 that should be required is to flush the TBs, allocate a new TB,
1320 re-initialize it per above, and re-do the actual code generation. */
1321 gen_code_size = tcg_gen_code(tcg_ctx, tb);
1322 if (unlikely(gen_code_size < 0)) {
1323 goto buffer_overflow;
1325 search_size = encode_search(tb, (void *)gen_code_buf + gen_code_size);
1326 if (unlikely(search_size < 0)) {
1327 goto buffer_overflow;
1329 tb->tc.size = gen_code_size;
1331 #ifdef CONFIG_PROFILER
1332 atomic_set(&prof->code_time, prof->code_time + profile_getclock() - ti);
1333 atomic_set(&prof->code_in_len, prof->code_in_len + tb->size);
1334 atomic_set(&prof->code_out_len, prof->code_out_len + gen_code_size);
1335 atomic_set(&prof->search_out_len, prof->search_out_len + search_size);
1336 #endif
1338 #ifdef DEBUG_DISAS
1339 if (qemu_loglevel_mask(CPU_LOG_TB_OUT_ASM) &&
1340 qemu_log_in_addr_range(tb->pc)) {
1341 qemu_log_lock();
1342 qemu_log("OUT: [size=%d]\n", gen_code_size);
1343 if (tcg_ctx->data_gen_ptr) {
1344 size_t code_size = tcg_ctx->data_gen_ptr - tb->tc.ptr;
1345 size_t data_size = gen_code_size - code_size;
1346 size_t i;
1348 log_disas(tb->tc.ptr, code_size);
1350 for (i = 0; i < data_size; i += sizeof(tcg_target_ulong)) {
1351 if (sizeof(tcg_target_ulong) == 8) {
1352 qemu_log("0x%08" PRIxPTR ": .quad 0x%016" PRIx64 "\n",
1353 (uintptr_t)tcg_ctx->data_gen_ptr + i,
1354 *(uint64_t *)(tcg_ctx->data_gen_ptr + i));
1355 } else {
1356 qemu_log("0x%08" PRIxPTR ": .long 0x%08x\n",
1357 (uintptr_t)tcg_ctx->data_gen_ptr + i,
1358 *(uint32_t *)(tcg_ctx->data_gen_ptr + i));
1361 } else {
1362 log_disas(tb->tc.ptr, gen_code_size);
1364 qemu_log("\n");
1365 qemu_log_flush();
1366 qemu_log_unlock();
1368 #endif
1370 atomic_set(&tcg_ctx->code_gen_ptr, (void *)
1371 ROUND_UP((uintptr_t)gen_code_buf + gen_code_size + search_size,
1372 CODE_GEN_ALIGN));
1374 #if defined(CONFIG_USER_ONLY) && defined(TARGET_X86_64)
1375 /* if we are doing vsyscall don't link the page as it lies in high memory
1376 and tb_alloc_page will abort due to page_l1_map returning NULL */
1377 if (unlikely(phys_pc >= TARGET_VSYSCALL_START
1378 && phys_pc < TARGET_VSYSCALL_END))
1379 return tb;
1380 #endif
1382 /* init jump list */
1383 assert(((uintptr_t)tb & 3) == 0);
1384 tb->jmp_list_first = (uintptr_t)tb | 2;
1385 tb->jmp_list_next[0] = (uintptr_t)NULL;
1386 tb->jmp_list_next[1] = (uintptr_t)NULL;
1388 /* init original jump addresses wich has been set during tcg_gen_code() */
1389 if (tb->jmp_reset_offset[0] != TB_JMP_RESET_OFFSET_INVALID) {
1390 tb_reset_jump(tb, 0);
1392 if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) {
1393 tb_reset_jump(tb, 1);
1396 /* check next page if needed */
1397 virt_page2 = (pc + tb->size - 1) & TARGET_PAGE_MASK;
1398 phys_page2 = -1;
1399 if ((pc & TARGET_PAGE_MASK) != virt_page2) {
1400 phys_page2 = get_page_addr_code(env, virt_page2);
1402 /* As long as consistency of the TB stuff is provided by tb_lock in user
1403 * mode and is implicit in single-threaded softmmu emulation, no explicit
1404 * memory barrier is required before tb_link_page() makes the TB visible
1405 * through the physical hash table and physical page list.
1407 tb_link_page(tb, phys_pc, phys_page2);
1408 g_tree_insert(tb_ctx.tb_tree, &tb->tc, tb);
1409 return tb;
1413 * Invalidate all TBs which intersect with the target physical address range
1414 * [start;end[. NOTE: start and end may refer to *different* physical pages.
1415 * 'is_cpu_write_access' should be true if called from a real cpu write
1416 * access: the virtual CPU will exit the current TB if code is modified inside
1417 * this TB.
1419 * Called with mmap_lock held for user-mode emulation, grabs tb_lock
1420 * Called with tb_lock held for system-mode emulation
1422 static void tb_invalidate_phys_range_1(tb_page_addr_t start, tb_page_addr_t end)
1424 while (start < end) {
1425 tb_invalidate_phys_page_range(start, end, 0);
1426 start &= TARGET_PAGE_MASK;
1427 start += TARGET_PAGE_SIZE;
1431 #ifdef CONFIG_SOFTMMU
1432 void tb_invalidate_phys_range(tb_page_addr_t start, tb_page_addr_t end)
1434 assert_tb_locked();
1435 tb_invalidate_phys_range_1(start, end);
1437 #else
1438 void tb_invalidate_phys_range(tb_page_addr_t start, tb_page_addr_t end)
1440 assert_memory_lock();
1441 tb_lock();
1442 tb_invalidate_phys_range_1(start, end);
1443 tb_unlock();
1445 #endif
1447 * Invalidate all TBs which intersect with the target physical address range
1448 * [start;end[. NOTE: start and end must refer to the *same* physical page.
1449 * 'is_cpu_write_access' should be true if called from a real cpu write
1450 * access: the virtual CPU will exit the current TB if code is modified inside
1451 * this TB.
1453 * Called with tb_lock/mmap_lock held for user-mode emulation
1454 * Called with tb_lock held for system-mode emulation
1456 void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end,
1457 int is_cpu_write_access)
1459 TranslationBlock *tb, *tb_next;
1460 tb_page_addr_t tb_start, tb_end;
1461 PageDesc *p;
1462 int n;
1463 #ifdef TARGET_HAS_PRECISE_SMC
1464 CPUState *cpu = current_cpu;
1465 CPUArchState *env = NULL;
1466 int current_tb_not_found = is_cpu_write_access;
1467 TranslationBlock *current_tb = NULL;
1468 int current_tb_modified = 0;
1469 target_ulong current_pc = 0;
1470 target_ulong current_cs_base = 0;
1471 uint32_t current_flags = 0;
1472 #endif /* TARGET_HAS_PRECISE_SMC */
1474 assert_memory_lock();
1475 assert_tb_locked();
1477 p = page_find(start >> TARGET_PAGE_BITS);
1478 if (!p) {
1479 return;
1481 #if defined(TARGET_HAS_PRECISE_SMC)
1482 if (cpu != NULL) {
1483 env = cpu->env_ptr;
1485 #endif
1487 /* we remove all the TBs in the range [start, end[ */
1488 /* XXX: see if in some cases it could be faster to invalidate all
1489 the code */
1490 tb = p->first_tb;
1491 while (tb != NULL) {
1492 n = (uintptr_t)tb & 3;
1493 tb = (TranslationBlock *)((uintptr_t)tb & ~3);
1494 tb_next = tb->page_next[n];
1495 /* NOTE: this is subtle as a TB may span two physical pages */
1496 if (n == 0) {
1497 /* NOTE: tb_end may be after the end of the page, but
1498 it is not a problem */
1499 tb_start = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);
1500 tb_end = tb_start + tb->size;
1501 } else {
1502 tb_start = tb->page_addr[1];
1503 tb_end = tb_start + ((tb->pc + tb->size) & ~TARGET_PAGE_MASK);
1505 if (!(tb_end <= start || tb_start >= end)) {
1506 #ifdef TARGET_HAS_PRECISE_SMC
1507 if (current_tb_not_found) {
1508 current_tb_not_found = 0;
1509 current_tb = NULL;
1510 if (cpu->mem_io_pc) {
1511 /* now we have a real cpu fault */
1512 current_tb = tb_find_pc(cpu->mem_io_pc);
1515 if (current_tb == tb &&
1516 (current_tb->cflags & CF_COUNT_MASK) != 1) {
1517 /* If we are modifying the current TB, we must stop
1518 its execution. We could be more precise by checking
1519 that the modification is after the current PC, but it
1520 would require a specialized function to partially
1521 restore the CPU state */
1523 current_tb_modified = 1;
1524 cpu_restore_state_from_tb(cpu, current_tb, cpu->mem_io_pc);
1525 cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base,
1526 &current_flags);
1528 #endif /* TARGET_HAS_PRECISE_SMC */
1529 tb_phys_invalidate(tb, -1);
1531 tb = tb_next;
1533 #if !defined(CONFIG_USER_ONLY)
1534 /* if no code remaining, no need to continue to use slow writes */
1535 if (!p->first_tb) {
1536 invalidate_page_bitmap(p);
1537 tlb_unprotect_code(start);
1539 #endif
1540 #ifdef TARGET_HAS_PRECISE_SMC
1541 if (current_tb_modified) {
1542 /* Force execution of one insn next time. */
1543 cpu->cflags_next_tb = 1 | curr_cflags();
1544 cpu_loop_exit_noexc(cpu);
1546 #endif
1549 #ifdef CONFIG_SOFTMMU
1550 /* len must be <= 8 and start must be a multiple of len.
1551 * Called via softmmu_template.h when code areas are written to with
1552 * iothread mutex not held.
1554 void tb_invalidate_phys_page_fast(tb_page_addr_t start, int len)
1556 PageDesc *p;
1558 #if 0
1559 if (1) {
1560 qemu_log("modifying code at 0x%x size=%d EIP=%x PC=%08x\n",
1561 cpu_single_env->mem_io_vaddr, len,
1562 cpu_single_env->eip,
1563 cpu_single_env->eip +
1564 (intptr_t)cpu_single_env->segs[R_CS].base);
1566 #endif
1567 assert_memory_lock();
1569 p = page_find(start >> TARGET_PAGE_BITS);
1570 if (!p) {
1571 return;
1573 if (!p->code_bitmap &&
1574 ++p->code_write_count >= SMC_BITMAP_USE_THRESHOLD) {
1575 /* build code bitmap. FIXME: writes should be protected by
1576 * tb_lock, reads by tb_lock or RCU.
1578 build_page_bitmap(p);
1580 if (p->code_bitmap) {
1581 unsigned int nr;
1582 unsigned long b;
1584 nr = start & ~TARGET_PAGE_MASK;
1585 b = p->code_bitmap[BIT_WORD(nr)] >> (nr & (BITS_PER_LONG - 1));
1586 if (b & ((1 << len) - 1)) {
1587 goto do_invalidate;
1589 } else {
1590 do_invalidate:
1591 tb_invalidate_phys_page_range(start, start + len, 1);
1594 #else
1595 /* Called with mmap_lock held. If pc is not 0 then it indicates the
1596 * host PC of the faulting store instruction that caused this invalidate.
1597 * Returns true if the caller needs to abort execution of the current
1598 * TB (because it was modified by this store and the guest CPU has
1599 * precise-SMC semantics).
1601 static bool tb_invalidate_phys_page(tb_page_addr_t addr, uintptr_t pc)
1603 TranslationBlock *tb;
1604 PageDesc *p;
1605 int n;
1606 #ifdef TARGET_HAS_PRECISE_SMC
1607 TranslationBlock *current_tb = NULL;
1608 CPUState *cpu = current_cpu;
1609 CPUArchState *env = NULL;
1610 int current_tb_modified = 0;
1611 target_ulong current_pc = 0;
1612 target_ulong current_cs_base = 0;
1613 uint32_t current_flags = 0;
1614 #endif
1616 assert_memory_lock();
1618 addr &= TARGET_PAGE_MASK;
1619 p = page_find(addr >> TARGET_PAGE_BITS);
1620 if (!p) {
1621 return false;
1624 tb_lock();
1625 tb = p->first_tb;
1626 #ifdef TARGET_HAS_PRECISE_SMC
1627 if (tb && pc != 0) {
1628 current_tb = tb_find_pc(pc);
1630 if (cpu != NULL) {
1631 env = cpu->env_ptr;
1633 #endif
1634 while (tb != NULL) {
1635 n = (uintptr_t)tb & 3;
1636 tb = (TranslationBlock *)((uintptr_t)tb & ~3);
1637 #ifdef TARGET_HAS_PRECISE_SMC
1638 if (current_tb == tb &&
1639 (current_tb->cflags & CF_COUNT_MASK) != 1) {
1640 /* If we are modifying the current TB, we must stop
1641 its execution. We could be more precise by checking
1642 that the modification is after the current PC, but it
1643 would require a specialized function to partially
1644 restore the CPU state */
1646 current_tb_modified = 1;
1647 cpu_restore_state_from_tb(cpu, current_tb, pc);
1648 cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base,
1649 &current_flags);
1651 #endif /* TARGET_HAS_PRECISE_SMC */
1652 tb_phys_invalidate(tb, addr);
1653 tb = tb->page_next[n];
1655 p->first_tb = NULL;
1656 #ifdef TARGET_HAS_PRECISE_SMC
1657 if (current_tb_modified) {
1658 /* Force execution of one insn next time. */
1659 cpu->cflags_next_tb = 1 | curr_cflags();
1660 /* tb_lock will be reset after cpu_loop_exit_noexc longjmps
1661 * back into the cpu_exec loop. */
1662 return true;
1664 #endif
1665 tb_unlock();
1667 return false;
1669 #endif
1672 * Find the TB 'tb' such that
1673 * tb->tc.ptr <= tc_ptr < tb->tc.ptr + tb->tc.size
1674 * Return NULL if not found.
1676 static TranslationBlock *tb_find_pc(uintptr_t tc_ptr)
1678 struct tb_tc s = { .ptr = (void *)tc_ptr };
1680 return g_tree_lookup(tb_ctx.tb_tree, &s);
1683 #if !defined(CONFIG_USER_ONLY)
1684 void tb_invalidate_phys_addr(AddressSpace *as, hwaddr addr)
1686 ram_addr_t ram_addr;
1687 MemoryRegion *mr;
1688 hwaddr l = 1;
1690 rcu_read_lock();
1691 mr = address_space_translate(as, addr, &addr, &l, false);
1692 if (!(memory_region_is_ram(mr)
1693 || memory_region_is_romd(mr))) {
1694 rcu_read_unlock();
1695 return;
1697 ram_addr = memory_region_get_ram_addr(mr) + addr;
1698 tb_lock();
1699 tb_invalidate_phys_page_range(ram_addr, ram_addr + 1, 0);
1700 tb_unlock();
1701 rcu_read_unlock();
1703 #endif /* !defined(CONFIG_USER_ONLY) */
1705 /* Called with tb_lock held. */
1706 void tb_check_watchpoint(CPUState *cpu)
1708 TranslationBlock *tb;
1710 tb = tb_find_pc(cpu->mem_io_pc);
1711 if (tb) {
1712 /* We can use retranslation to find the PC. */
1713 cpu_restore_state_from_tb(cpu, tb, cpu->mem_io_pc);
1714 tb_phys_invalidate(tb, -1);
1715 } else {
1716 /* The exception probably happened in a helper. The CPU state should
1717 have been saved before calling it. Fetch the PC from there. */
1718 CPUArchState *env = cpu->env_ptr;
1719 target_ulong pc, cs_base;
1720 tb_page_addr_t addr;
1721 uint32_t flags;
1723 cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags);
1724 addr = get_page_addr_code(env, pc);
1725 tb_invalidate_phys_range(addr, addr + 1);
1729 #ifndef CONFIG_USER_ONLY
1730 /* in deterministic execution mode, instructions doing device I/Os
1731 * must be at the end of the TB.
1733 * Called by softmmu_template.h, with iothread mutex not held.
1735 void cpu_io_recompile(CPUState *cpu, uintptr_t retaddr)
1737 #if defined(TARGET_MIPS) || defined(TARGET_SH4)
1738 CPUArchState *env = cpu->env_ptr;
1739 #endif
1740 TranslationBlock *tb;
1741 uint32_t n;
1743 tb_lock();
1744 tb = tb_find_pc(retaddr);
1745 if (!tb) {
1746 cpu_abort(cpu, "cpu_io_recompile: could not find TB for pc=%p",
1747 (void *)retaddr);
1749 n = cpu->icount_decr.u16.low + tb->icount;
1750 cpu_restore_state_from_tb(cpu, tb, retaddr);
1751 /* Calculate how many instructions had been executed before the fault
1752 occurred. */
1753 n = n - cpu->icount_decr.u16.low;
1754 /* Generate a new TB ending on the I/O insn. */
1755 n++;
1756 /* On MIPS and SH, delay slot instructions can only be restarted if
1757 they were already the first instruction in the TB. If this is not
1758 the first instruction in a TB then re-execute the preceding
1759 branch. */
1760 #if defined(TARGET_MIPS)
1761 if ((env->hflags & MIPS_HFLAG_BMASK) != 0 && n > 1) {
1762 env->active_tc.PC -= (env->hflags & MIPS_HFLAG_B16 ? 2 : 4);
1763 cpu->icount_decr.u16.low++;
1764 env->hflags &= ~MIPS_HFLAG_BMASK;
1766 #elif defined(TARGET_SH4)
1767 if ((env->flags & ((DELAY_SLOT | DELAY_SLOT_CONDITIONAL))) != 0
1768 && n > 1) {
1769 env->pc -= 2;
1770 cpu->icount_decr.u16.low++;
1771 env->flags &= ~(DELAY_SLOT | DELAY_SLOT_CONDITIONAL);
1773 #endif
1774 /* This should never happen. */
1775 if (n > CF_COUNT_MASK) {
1776 cpu_abort(cpu, "TB too big during recompile");
1779 /* Adjust the execution state of the next TB. */
1780 cpu->cflags_next_tb = curr_cflags() | CF_LAST_IO | n;
1782 if (tb->cflags & CF_NOCACHE) {
1783 if (tb->orig_tb) {
1784 /* Invalidate original TB if this TB was generated in
1785 * cpu_exec_nocache() */
1786 tb_phys_invalidate(tb->orig_tb, -1);
1788 tb_remove(tb);
1791 /* TODO: If env->pc != tb->pc (i.e. the faulting instruction was not
1792 * the first in the TB) then we end up generating a whole new TB and
1793 * repeating the fault, which is horribly inefficient.
1794 * Better would be to execute just this insn uncached, or generate a
1795 * second new TB.
1797 * cpu_loop_exit_noexc will longjmp back to cpu_exec where the
1798 * tb_lock gets reset.
1800 cpu_loop_exit_noexc(cpu);
1803 static void tb_jmp_cache_clear_page(CPUState *cpu, target_ulong page_addr)
1805 unsigned int i, i0 = tb_jmp_cache_hash_page(page_addr);
1807 for (i = 0; i < TB_JMP_PAGE_SIZE; i++) {
1808 atomic_set(&cpu->tb_jmp_cache[i0 + i], NULL);
1812 void tb_flush_jmp_cache(CPUState *cpu, target_ulong addr)
1814 /* Discard jump cache entries for any tb which might potentially
1815 overlap the flushed page. */
1816 tb_jmp_cache_clear_page(cpu, addr - TARGET_PAGE_SIZE);
1817 tb_jmp_cache_clear_page(cpu, addr);
1820 static void print_qht_statistics(FILE *f, fprintf_function cpu_fprintf,
1821 struct qht_stats hst)
1823 uint32_t hgram_opts;
1824 size_t hgram_bins;
1825 char *hgram;
1827 if (!hst.head_buckets) {
1828 return;
1830 cpu_fprintf(f, "TB hash buckets %zu/%zu (%0.2f%% head buckets used)\n",
1831 hst.used_head_buckets, hst.head_buckets,
1832 (double)hst.used_head_buckets / hst.head_buckets * 100);
1834 hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
1835 hgram_opts |= QDIST_PR_100X | QDIST_PR_PERCENT;
1836 if (qdist_xmax(&hst.occupancy) - qdist_xmin(&hst.occupancy) == 1) {
1837 hgram_opts |= QDIST_PR_NODECIMAL;
1839 hgram = qdist_pr(&hst.occupancy, 10, hgram_opts);
1840 cpu_fprintf(f, "TB hash occupancy %0.2f%% avg chain occ. Histogram: %s\n",
1841 qdist_avg(&hst.occupancy) * 100, hgram);
1842 g_free(hgram);
1844 hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
1845 hgram_bins = qdist_xmax(&hst.chain) - qdist_xmin(&hst.chain);
1846 if (hgram_bins > 10) {
1847 hgram_bins = 10;
1848 } else {
1849 hgram_bins = 0;
1850 hgram_opts |= QDIST_PR_NODECIMAL | QDIST_PR_NOBINRANGE;
1852 hgram = qdist_pr(&hst.chain, hgram_bins, hgram_opts);
1853 cpu_fprintf(f, "TB hash avg chain %0.3f buckets. Histogram: %s\n",
1854 qdist_avg(&hst.chain), hgram);
1855 g_free(hgram);
1858 struct tb_tree_stats {
1859 size_t host_size;
1860 size_t target_size;
1861 size_t max_target_size;
1862 size_t direct_jmp_count;
1863 size_t direct_jmp2_count;
1864 size_t cross_page;
1867 static gboolean tb_tree_stats_iter(gpointer key, gpointer value, gpointer data)
1869 const TranslationBlock *tb = value;
1870 struct tb_tree_stats *tst = data;
1872 tst->host_size += tb->tc.size;
1873 tst->target_size += tb->size;
1874 if (tb->size > tst->max_target_size) {
1875 tst->max_target_size = tb->size;
1877 if (tb->page_addr[1] != -1) {
1878 tst->cross_page++;
1880 if (tb->jmp_reset_offset[0] != TB_JMP_RESET_OFFSET_INVALID) {
1881 tst->direct_jmp_count++;
1882 if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) {
1883 tst->direct_jmp2_count++;
1886 return false;
1889 void dump_exec_info(FILE *f, fprintf_function cpu_fprintf)
1891 struct tb_tree_stats tst = {};
1892 struct qht_stats hst;
1893 size_t nb_tbs;
1895 tb_lock();
1897 nb_tbs = g_tree_nnodes(tb_ctx.tb_tree);
1898 g_tree_foreach(tb_ctx.tb_tree, tb_tree_stats_iter, &tst);
1899 /* XXX: avoid using doubles ? */
1900 cpu_fprintf(f, "Translation buffer state:\n");
1902 * Report total code size including the padding and TB structs;
1903 * otherwise users might think "-tb-size" is not honoured.
1904 * For avg host size we use the precise numbers from tb_tree_stats though.
1906 cpu_fprintf(f, "gen code size %zu/%zu\n",
1907 tcg_code_size(), tcg_code_capacity());
1908 cpu_fprintf(f, "TB count %zu\n", nb_tbs);
1909 cpu_fprintf(f, "TB avg target size %zu max=%zu bytes\n",
1910 nb_tbs ? tst.target_size / nb_tbs : 0,
1911 tst.max_target_size);
1912 cpu_fprintf(f, "TB avg host size %zu bytes (expansion ratio: %0.1f)\n",
1913 nb_tbs ? tst.host_size / nb_tbs : 0,
1914 tst.target_size ? (double)tst.host_size / tst.target_size : 0);
1915 cpu_fprintf(f, "cross page TB count %zu (%zu%%)\n", tst.cross_page,
1916 nb_tbs ? (tst.cross_page * 100) / nb_tbs : 0);
1917 cpu_fprintf(f, "direct jump count %zu (%zu%%) (2 jumps=%zu %zu%%)\n",
1918 tst.direct_jmp_count,
1919 nb_tbs ? (tst.direct_jmp_count * 100) / nb_tbs : 0,
1920 tst.direct_jmp2_count,
1921 nb_tbs ? (tst.direct_jmp2_count * 100) / nb_tbs : 0);
1923 qht_statistics_init(&tb_ctx.htable, &hst);
1924 print_qht_statistics(f, cpu_fprintf, hst);
1925 qht_statistics_destroy(&hst);
1927 cpu_fprintf(f, "\nStatistics:\n");
1928 cpu_fprintf(f, "TB flush count %u\n",
1929 atomic_read(&tb_ctx.tb_flush_count));
1930 cpu_fprintf(f, "TB invalidate count %d\n", tb_ctx.tb_phys_invalidate_count);
1931 cpu_fprintf(f, "TLB flush count %zu\n", tlb_flush_count());
1932 tcg_dump_info(f, cpu_fprintf);
1934 tb_unlock();
1937 void dump_opcount_info(FILE *f, fprintf_function cpu_fprintf)
1939 tcg_dump_op_count(f, cpu_fprintf);
1942 #else /* CONFIG_USER_ONLY */
1944 void cpu_interrupt(CPUState *cpu, int mask)
1946 g_assert(qemu_mutex_iothread_locked());
1947 cpu->interrupt_request |= mask;
1948 cpu->icount_decr.u16.high = -1;
1952 * Walks guest process memory "regions" one by one
1953 * and calls callback function 'fn' for each region.
1955 struct walk_memory_regions_data {
1956 walk_memory_regions_fn fn;
1957 void *priv;
1958 target_ulong start;
1959 int prot;
1962 static int walk_memory_regions_end(struct walk_memory_regions_data *data,
1963 target_ulong end, int new_prot)
1965 if (data->start != -1u) {
1966 int rc = data->fn(data->priv, data->start, end, data->prot);
1967 if (rc != 0) {
1968 return rc;
1972 data->start = (new_prot ? end : -1u);
1973 data->prot = new_prot;
1975 return 0;
1978 static int walk_memory_regions_1(struct walk_memory_regions_data *data,
1979 target_ulong base, int level, void **lp)
1981 target_ulong pa;
1982 int i, rc;
1984 if (*lp == NULL) {
1985 return walk_memory_regions_end(data, base, 0);
1988 if (level == 0) {
1989 PageDesc *pd = *lp;
1991 for (i = 0; i < V_L2_SIZE; ++i) {
1992 int prot = pd[i].flags;
1994 pa = base | (i << TARGET_PAGE_BITS);
1995 if (prot != data->prot) {
1996 rc = walk_memory_regions_end(data, pa, prot);
1997 if (rc != 0) {
1998 return rc;
2002 } else {
2003 void **pp = *lp;
2005 for (i = 0; i < V_L2_SIZE; ++i) {
2006 pa = base | ((target_ulong)i <<
2007 (TARGET_PAGE_BITS + V_L2_BITS * level));
2008 rc = walk_memory_regions_1(data, pa, level - 1, pp + i);
2009 if (rc != 0) {
2010 return rc;
2015 return 0;
2018 int walk_memory_regions(void *priv, walk_memory_regions_fn fn)
2020 struct walk_memory_regions_data data;
2021 uintptr_t i, l1_sz = v_l1_size;
2023 data.fn = fn;
2024 data.priv = priv;
2025 data.start = -1u;
2026 data.prot = 0;
2028 for (i = 0; i < l1_sz; i++) {
2029 target_ulong base = i << (v_l1_shift + TARGET_PAGE_BITS);
2030 int rc = walk_memory_regions_1(&data, base, v_l2_levels, l1_map + i);
2031 if (rc != 0) {
2032 return rc;
2036 return walk_memory_regions_end(&data, 0, 0);
2039 static int dump_region(void *priv, target_ulong start,
2040 target_ulong end, abi_ulong prot)
2042 FILE *f = (FILE *)priv;
2044 (void) fprintf(f, TARGET_FMT_lx"-"TARGET_FMT_lx
2045 " "TARGET_FMT_lx" %c%c%c\n",
2046 start, end, end - start,
2047 ((prot & PAGE_READ) ? 'r' : '-'),
2048 ((prot & PAGE_WRITE) ? 'w' : '-'),
2049 ((prot & PAGE_EXEC) ? 'x' : '-'));
2051 return 0;
2054 /* dump memory mappings */
2055 void page_dump(FILE *f)
2057 const int length = sizeof(target_ulong) * 2;
2058 (void) fprintf(f, "%-*s %-*s %-*s %s\n",
2059 length, "start", length, "end", length, "size", "prot");
2060 walk_memory_regions(f, dump_region);
2063 int page_get_flags(target_ulong address)
2065 PageDesc *p;
2067 p = page_find(address >> TARGET_PAGE_BITS);
2068 if (!p) {
2069 return 0;
2071 return p->flags;
2074 /* Modify the flags of a page and invalidate the code if necessary.
2075 The flag PAGE_WRITE_ORG is positioned automatically depending
2076 on PAGE_WRITE. The mmap_lock should already be held. */
2077 void page_set_flags(target_ulong start, target_ulong end, int flags)
2079 target_ulong addr, len;
2081 /* This function should never be called with addresses outside the
2082 guest address space. If this assert fires, it probably indicates
2083 a missing call to h2g_valid. */
2084 #if TARGET_ABI_BITS > L1_MAP_ADDR_SPACE_BITS
2085 assert(end <= ((target_ulong)1 << L1_MAP_ADDR_SPACE_BITS));
2086 #endif
2087 assert(start < end);
2088 assert_memory_lock();
2090 start = start & TARGET_PAGE_MASK;
2091 end = TARGET_PAGE_ALIGN(end);
2093 if (flags & PAGE_WRITE) {
2094 flags |= PAGE_WRITE_ORG;
2097 for (addr = start, len = end - start;
2098 len != 0;
2099 len -= TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {
2100 PageDesc *p = page_find_alloc(addr >> TARGET_PAGE_BITS, 1);
2102 /* If the write protection bit is set, then we invalidate
2103 the code inside. */
2104 if (!(p->flags & PAGE_WRITE) &&
2105 (flags & PAGE_WRITE) &&
2106 p->first_tb) {
2107 tb_invalidate_phys_page(addr, 0);
2109 p->flags = flags;
2113 int page_check_range(target_ulong start, target_ulong len, int flags)
2115 PageDesc *p;
2116 target_ulong end;
2117 target_ulong addr;
2119 /* This function should never be called with addresses outside the
2120 guest address space. If this assert fires, it probably indicates
2121 a missing call to h2g_valid. */
2122 #if TARGET_ABI_BITS > L1_MAP_ADDR_SPACE_BITS
2123 assert(start < ((target_ulong)1 << L1_MAP_ADDR_SPACE_BITS));
2124 #endif
2126 if (len == 0) {
2127 return 0;
2129 if (start + len - 1 < start) {
2130 /* We've wrapped around. */
2131 return -1;
2134 /* must do before we loose bits in the next step */
2135 end = TARGET_PAGE_ALIGN(start + len);
2136 start = start & TARGET_PAGE_MASK;
2138 for (addr = start, len = end - start;
2139 len != 0;
2140 len -= TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {
2141 p = page_find(addr >> TARGET_PAGE_BITS);
2142 if (!p) {
2143 return -1;
2145 if (!(p->flags & PAGE_VALID)) {
2146 return -1;
2149 if ((flags & PAGE_READ) && !(p->flags & PAGE_READ)) {
2150 return -1;
2152 if (flags & PAGE_WRITE) {
2153 if (!(p->flags & PAGE_WRITE_ORG)) {
2154 return -1;
2156 /* unprotect the page if it was put read-only because it
2157 contains translated code */
2158 if (!(p->flags & PAGE_WRITE)) {
2159 if (!page_unprotect(addr, 0)) {
2160 return -1;
2165 return 0;
2168 /* called from signal handler: invalidate the code and unprotect the
2169 * page. Return 0 if the fault was not handled, 1 if it was handled,
2170 * and 2 if it was handled but the caller must cause the TB to be
2171 * immediately exited. (We can only return 2 if the 'pc' argument is
2172 * non-zero.)
2174 int page_unprotect(target_ulong address, uintptr_t pc)
2176 unsigned int prot;
2177 bool current_tb_invalidated;
2178 PageDesc *p;
2179 target_ulong host_start, host_end, addr;
2181 /* Technically this isn't safe inside a signal handler. However we
2182 know this only ever happens in a synchronous SEGV handler, so in
2183 practice it seems to be ok. */
2184 mmap_lock();
2186 p = page_find(address >> TARGET_PAGE_BITS);
2187 if (!p) {
2188 mmap_unlock();
2189 return 0;
2192 /* if the page was really writable, then we change its
2193 protection back to writable */
2194 if ((p->flags & PAGE_WRITE_ORG) && !(p->flags & PAGE_WRITE)) {
2195 host_start = address & qemu_host_page_mask;
2196 host_end = host_start + qemu_host_page_size;
2198 prot = 0;
2199 current_tb_invalidated = false;
2200 for (addr = host_start ; addr < host_end ; addr += TARGET_PAGE_SIZE) {
2201 p = page_find(addr >> TARGET_PAGE_BITS);
2202 p->flags |= PAGE_WRITE;
2203 prot |= p->flags;
2205 /* and since the content will be modified, we must invalidate
2206 the corresponding translated code. */
2207 current_tb_invalidated |= tb_invalidate_phys_page(addr, pc);
2208 #ifdef CONFIG_USER_ONLY
2209 if (DEBUG_TB_CHECK_GATE) {
2210 tb_invalidate_check(addr);
2212 #endif
2214 mprotect((void *)g2h(host_start), qemu_host_page_size,
2215 prot & PAGE_BITS);
2217 mmap_unlock();
2218 /* If current TB was invalidated return to main loop */
2219 return current_tb_invalidated ? 2 : 1;
2221 mmap_unlock();
2222 return 0;
2224 #endif /* CONFIG_USER_ONLY */
2226 /* This is a wrapper for common code that can not use CONFIG_SOFTMMU */
2227 void tcg_flush_softmmu_tlb(CPUState *cs)
2229 #ifdef CONFIG_SOFTMMU
2230 tlb_flush(cs);
2231 #endif