]> git.proxmox.com Git - mirror_qemu.git/blame - accel/tcg/translate-all.c
osdep: introduce qemu_mprotect_rwx/none
[mirror_qemu.git] / accel / tcg / translate-all.c
CommitLineData
d19893da
FB
1/*
2 * Host code generation
5fafdf24 3 *
d19893da
FB
4 * Copyright (c) 2003 Fabrice Bellard
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
8167ee88 17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
d19893da 18 */
5b6dd868
BS
19#ifdef _WIN32
20#include <windows.h>
5b6dd868 21#endif
7b31bbc2 22#include "qemu/osdep.h"
d19893da 23
2054396a 24
5b6dd868 25#include "qemu-common.h"
af5ad107 26#define NO_CPU_IO_DEFS
d3eead2e 27#include "cpu.h"
244f1441 28#include "trace.h"
76cad711 29#include "disas/disas.h"
63c91552 30#include "exec/exec-all.h"
57fec1fe 31#include "tcg.h"
5b6dd868
BS
32#if defined(CONFIG_USER_ONLY)
33#include "qemu.h"
301e40ed 34#include "exec/exec-all.h"
5b6dd868
BS
35#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
36#include <sys/param.h>
37#if __FreeBSD_version >= 700104
38#define HAVE_KINFO_GETVMMAP
39#define sigqueue sigqueue_freebsd /* avoid redefinition */
5b6dd868
BS
40#include <sys/proc.h>
41#include <machine/profile.h>
42#define _KERNEL
43#include <sys/user.h>
44#undef _KERNEL
45#undef sigqueue
46#include <libutil.h>
47#endif
48#endif
0bc3cd62
PB
49#else
50#include "exec/address-spaces.h"
5b6dd868
BS
51#endif
52
022c62cb 53#include "exec/cputlb.h"
e1b89321 54#include "exec/tb-hash.h"
5b6dd868 55#include "translate-all.h"
510a647f 56#include "qemu/bitmap.h"
61a67f71 57#include "qemu/error-report.h"
0aa09897 58#include "qemu/timer.h"
8d04fb55 59#include "qemu/main-loop.h"
508127e2 60#include "exec/log.h"
d2528bdc 61#include "sysemu/cpus.h"
5b6dd868 62
955939a2
AB
63/* #define DEBUG_TB_INVALIDATE */
64/* #define DEBUG_TB_FLUSH */
5b6dd868 65/* make various TB consistency checks */
955939a2 66/* #define DEBUG_TB_CHECK */
5b6dd868 67
dae9e03a
EC
68#ifdef DEBUG_TB_INVALIDATE
69#define DEBUG_TB_INVALIDATE_GATE 1
70#else
71#define DEBUG_TB_INVALIDATE_GATE 0
72#endif
73
424079c1
EC
74#ifdef DEBUG_TB_FLUSH
75#define DEBUG_TB_FLUSH_GATE 1
76#else
77#define DEBUG_TB_FLUSH_GATE 0
78#endif
79
5b6dd868
BS
80#if !defined(CONFIG_USER_ONLY)
81/* TB consistency checks only implemented for usermode emulation. */
82#undef DEBUG_TB_CHECK
83#endif
84
6eb062ab
EC
85#ifdef DEBUG_TB_CHECK
86#define DEBUG_TB_CHECK_GATE 1
87#else
88#define DEBUG_TB_CHECK_GATE 0
89#endif
90
301e40ed
AB
91/* Access to the various translations structures need to be serialised via locks
92 * for consistency. This is automatic for SoftMMU based system
93 * emulation due to its single threaded nature. In user-mode emulation
94 * access to the memory related structures are protected with the
95 * mmap_lock.
96 */
301e40ed 97#ifdef CONFIG_SOFTMMU
2f169606 98#define assert_memory_lock() tcg_debug_assert(have_tb_lock)
301e40ed 99#else
6ac3d7e8 100#define assert_memory_lock() tcg_debug_assert(have_mmap_lock())
301e40ed
AB
101#endif
102
5b6dd868
BS
103#define SMC_BITMAP_USE_THRESHOLD 10
104
5b6dd868
BS
105typedef struct PageDesc {
106 /* list of TBs intersecting this ram page */
107 TranslationBlock *first_tb;
6fad459c 108#ifdef CONFIG_SOFTMMU
5b6dd868
BS
109 /* in order to optimize self modifying code, we count the number
110 of lookups we do to a given page to use a bitmap */
111 unsigned int code_write_count;
510a647f 112 unsigned long *code_bitmap;
6fad459c 113#else
5b6dd868
BS
114 unsigned long flags;
115#endif
116} PageDesc;
117
118/* In system mode we want L1_MAP to be based on ram offsets,
119 while in user mode we want it to be based on virtual addresses. */
120#if !defined(CONFIG_USER_ONLY)
121#if HOST_LONG_BITS < TARGET_PHYS_ADDR_SPACE_BITS
122# define L1_MAP_ADDR_SPACE_BITS HOST_LONG_BITS
123#else
124# define L1_MAP_ADDR_SPACE_BITS TARGET_PHYS_ADDR_SPACE_BITS
125#endif
126#else
127# define L1_MAP_ADDR_SPACE_BITS TARGET_VIRT_ADDR_SPACE_BITS
128#endif
129
03f49957
PB
130/* Size of the L2 (and L3, etc) page tables. */
131#define V_L2_BITS 10
132#define V_L2_SIZE (1 << V_L2_BITS)
133
61a67f71
LV
134/* Make sure all possible CPU event bits fit in tb->trace_vcpu_dstate */
135QEMU_BUILD_BUG_ON(CPU_TRACE_DSTATE_MAX_EVENTS >
136 sizeof(((TranslationBlock *)0)->trace_vcpu_dstate)
137 * BITS_PER_BYTE);
138
66ec9f49
VK
139/*
140 * L1 Mapping properties
141 */
142static int v_l1_size;
143static int v_l1_shift;
144static int v_l2_levels;
145
146/* The bottom level has pointers to PageDesc, and is indexed by
147 * anything from 4 to (V_L2_BITS + 3) bits, depending on target page size.
148 */
149#define V_L1_MIN_BITS 4
150#define V_L1_MAX_BITS (V_L2_BITS + 3)
151#define V_L1_MAX_SIZE (1 << V_L1_MAX_BITS)
152
153static void *l1_map[V_L1_MAX_SIZE];
5b6dd868 154
57fec1fe 155/* code generation context */
b1311c4a
EC
156TCGContext tcg_init_ctx;
157TCGContext *tcg_ctx;
44ded3d0 158TBContext tb_ctx;
fdbc2b57 159bool parallel_cpus;
d19893da 160
677ef623 161/* translation block context */
13e10947 162static __thread int have_tb_lock;
677ef623 163
66ec9f49
VK
164static void page_table_config_init(void)
165{
166 uint32_t v_l1_bits;
167
168 assert(TARGET_PAGE_BITS);
169 /* The bits remaining after N lower levels of page tables. */
170 v_l1_bits = (L1_MAP_ADDR_SPACE_BITS - TARGET_PAGE_BITS) % V_L2_BITS;
171 if (v_l1_bits < V_L1_MIN_BITS) {
172 v_l1_bits += V_L2_BITS;
173 }
174
175 v_l1_size = 1 << v_l1_bits;
176 v_l1_shift = L1_MAP_ADDR_SPACE_BITS - TARGET_PAGE_BITS - v_l1_bits;
177 v_l2_levels = v_l1_shift / V_L2_BITS - 1;
178
179 assert(v_l1_bits <= V_L1_MAX_BITS);
180 assert(v_l1_shift % V_L2_BITS == 0);
181 assert(v_l2_levels >= 0);
182}
183
6ac3d7e8
PK
184#define assert_tb_locked() tcg_debug_assert(have_tb_lock)
185#define assert_tb_unlocked() tcg_debug_assert(!have_tb_lock)
6ac3d7e8 186
677ef623
FK
187void tb_lock(void)
188{
6ac3d7e8 189 assert_tb_unlocked();
44ded3d0 190 qemu_mutex_lock(&tb_ctx.tb_lock);
677ef623 191 have_tb_lock++;
677ef623
FK
192}
193
194void tb_unlock(void)
195{
6ac3d7e8 196 assert_tb_locked();
677ef623 197 have_tb_lock--;
44ded3d0 198 qemu_mutex_unlock(&tb_ctx.tb_lock);
677ef623
FK
199}
200
201void tb_lock_reset(void)
202{
677ef623 203 if (have_tb_lock) {
44ded3d0 204 qemu_mutex_unlock(&tb_ctx.tb_lock);
677ef623
FK
205 have_tb_lock = 0;
206 }
677ef623
FK
207}
208
a8a826a3 209static TranslationBlock *tb_find_pc(uintptr_t tc_ptr);
5b6dd868 210
57fec1fe
FB
211void cpu_gen_init(void)
212{
b1311c4a 213 tcg_context_init(&tcg_init_ctx);
57fec1fe
FB
214}
215
fca8a500
RH
216/* Encode VAL as a signed leb128 sequence at P.
217 Return P incremented past the encoded value. */
218static uint8_t *encode_sleb128(uint8_t *p, target_long val)
219{
220 int more, byte;
221
222 do {
223 byte = val & 0x7f;
224 val >>= 7;
225 more = !((val == 0 && (byte & 0x40) == 0)
226 || (val == -1 && (byte & 0x40) != 0));
227 if (more) {
228 byte |= 0x80;
229 }
230 *p++ = byte;
231 } while (more);
232
233 return p;
234}
235
236/* Decode a signed leb128 sequence at *PP; increment *PP past the
237 decoded value. Return the decoded value. */
238static target_long decode_sleb128(uint8_t **pp)
239{
240 uint8_t *p = *pp;
241 target_long val = 0;
242 int byte, shift = 0;
243
244 do {
245 byte = *p++;
246 val |= (target_ulong)(byte & 0x7f) << shift;
247 shift += 7;
248 } while (byte & 0x80);
249 if (shift < TARGET_LONG_BITS && (byte & 0x40)) {
250 val |= -(target_ulong)1 << shift;
251 }
252
253 *pp = p;
254 return val;
255}
256
257/* Encode the data collected about the instructions while compiling TB.
258 Place the data at BLOCK, and return the number of bytes consumed.
259
260 The logical table consisits of TARGET_INSN_START_WORDS target_ulong's,
261 which come from the target's insn_start data, followed by a uintptr_t
262 which comes from the host pc of the end of the code implementing the insn.
263
264 Each line of the table is encoded as sleb128 deltas from the previous
e7e168f4 265 line. The seed for the first line is { tb->pc, 0..., tb->tc.ptr }.
fca8a500
RH
266 That is, the first column is seeded with the guest pc, the last column
267 with the host pc, and the middle columns with zeros. */
268
269static int encode_search(TranslationBlock *tb, uint8_t *block)
270{
b1311c4a 271 uint8_t *highwater = tcg_ctx->code_gen_highwater;
fca8a500
RH
272 uint8_t *p = block;
273 int i, j, n;
274
fca8a500
RH
275 for (i = 0, n = tb->icount; i < n; ++i) {
276 target_ulong prev;
277
278 for (j = 0; j < TARGET_INSN_START_WORDS; ++j) {
279 if (i == 0) {
280 prev = (j == 0 ? tb->pc : 0);
281 } else {
b1311c4a 282 prev = tcg_ctx->gen_insn_data[i - 1][j];
fca8a500 283 }
b1311c4a 284 p = encode_sleb128(p, tcg_ctx->gen_insn_data[i][j] - prev);
fca8a500 285 }
b1311c4a
EC
286 prev = (i == 0 ? 0 : tcg_ctx->gen_insn_end_off[i - 1]);
287 p = encode_sleb128(p, tcg_ctx->gen_insn_end_off[i] - prev);
b125f9dc
RH
288
289 /* Test for (pending) buffer overflow. The assumption is that any
290 one row beginning below the high water mark cannot overrun
291 the buffer completely. Thus we can test for overflow after
292 encoding a row without having to check during encoding. */
293 if (unlikely(p > highwater)) {
294 return -1;
295 }
fca8a500
RH
296 }
297
298 return p - block;
299}
300
7d7500d9
PB
301/* The cpu state corresponding to 'searched_pc' is restored.
302 * Called with tb_lock held.
303 */
74f10515 304static int cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,
a8a826a3 305 uintptr_t searched_pc)
d19893da 306{
fca8a500 307 target_ulong data[TARGET_INSN_START_WORDS] = { tb->pc };
e7e168f4 308 uintptr_t host_pc = (uintptr_t)tb->tc.ptr;
74f10515 309 CPUArchState *env = cpu->env_ptr;
2ac01d6d 310 uint8_t *p = tb->tc.ptr + tb->tc.size;
fca8a500 311 int i, j, num_insns = tb->icount;
57fec1fe 312#ifdef CONFIG_PROFILER
c3fac113 313 TCGProfile *prof = &tcg_ctx->prof;
fca8a500 314 int64_t ti = profile_getclock();
57fec1fe
FB
315#endif
316
01ecaf43
RH
317 searched_pc -= GETPC_ADJ;
318
fca8a500
RH
319 if (searched_pc < host_pc) {
320 return -1;
321 }
d19893da 322
fca8a500
RH
323 /* Reconstruct the stored insn data while looking for the point at
324 which the end of the insn exceeds the searched_pc. */
325 for (i = 0; i < num_insns; ++i) {
326 for (j = 0; j < TARGET_INSN_START_WORDS; ++j) {
327 data[j] += decode_sleb128(&p);
328 }
329 host_pc += decode_sleb128(&p);
330 if (host_pc > searched_pc) {
331 goto found;
332 }
333 }
334 return -1;
3b46e624 335
fca8a500 336 found:
bd79255d 337 if (tb->cflags & CF_USE_ICOUNT) {
414b15c9 338 assert(use_icount);
2e70f6ef 339 /* Reset the cycle counter to the start of the block. */
fca8a500 340 cpu->icount_decr.u16.low += num_insns;
2e70f6ef 341 /* Clear the IO flag. */
99df7dce 342 cpu->can_do_io = 0;
2e70f6ef 343 }
fca8a500
RH
344 cpu->icount_decr.u16.low -= i;
345 restore_state_to_opc(env, tb, data);
57fec1fe
FB
346
347#ifdef CONFIG_PROFILER
c3fac113
EC
348 atomic_set(&prof->restore_time,
349 prof->restore_time + profile_getclock() - ti);
350 atomic_set(&prof->restore_count, prof->restore_count + 1);
57fec1fe 351#endif
d19893da
FB
352 return 0;
353}
5b6dd868 354
3f38f309 355bool cpu_restore_state(CPUState *cpu, uintptr_t retaddr)
a8a826a3
BS
356{
357 TranslationBlock *tb;
a5e99826 358 bool r = false;
a8a826a3 359
d8b2239b
AB
360 /* A retaddr of zero is invalid so we really shouldn't have ended
361 * up here. The target code has likely forgotten to check retaddr
362 * != 0 before attempting to restore state. We return early to
363 * avoid blowing up on a recursive tb_lock(). The target must have
364 * previously survived a failed cpu_restore_state because
365 * tb_find_pc(0) would have failed anyway. It still should be
366 * fixed though.
367 */
368
369 if (!retaddr) {
370 return r;
371 }
372
a5e99826 373 tb_lock();
a8a826a3
BS
374 tb = tb_find_pc(retaddr);
375 if (tb) {
74f10515 376 cpu_restore_state_from_tb(cpu, tb, retaddr);
d8a499f1
PD
377 if (tb->cflags & CF_NOCACHE) {
378 /* one-shot translation, invalidate it immediately */
d8a499f1 379 tb_phys_invalidate(tb, -1);
be1e0117 380 tb_remove(tb);
d8a499f1 381 }
a5e99826 382 r = true;
a8a826a3 383 }
a5e99826
FK
384 tb_unlock();
385
386 return r;
a8a826a3
BS
387}
388
47c16ed5
AK
389static void page_init(void)
390{
391 page_size_init();
66ec9f49
VK
392 page_table_config_init();
393
5b6dd868
BS
394#if defined(CONFIG_BSD) && defined(CONFIG_USER_ONLY)
395 {
396#ifdef HAVE_KINFO_GETVMMAP
397 struct kinfo_vmentry *freep;
398 int i, cnt;
399
400 freep = kinfo_getvmmap(getpid(), &cnt);
401 if (freep) {
402 mmap_lock();
403 for (i = 0; i < cnt; i++) {
404 unsigned long startaddr, endaddr;
405
406 startaddr = freep[i].kve_start;
407 endaddr = freep[i].kve_end;
408 if (h2g_valid(startaddr)) {
409 startaddr = h2g(startaddr) & TARGET_PAGE_MASK;
410
411 if (h2g_valid(endaddr)) {
412 endaddr = h2g(endaddr);
413 page_set_flags(startaddr, endaddr, PAGE_RESERVED);
414 } else {
415#if TARGET_ABI_BITS <= L1_MAP_ADDR_SPACE_BITS
416 endaddr = ~0ul;
417 page_set_flags(startaddr, endaddr, PAGE_RESERVED);
418#endif
419 }
420 }
421 }
422 free(freep);
423 mmap_unlock();
424 }
425#else
426 FILE *f;
427
428 last_brk = (unsigned long)sbrk(0);
429
430 f = fopen("/compat/linux/proc/self/maps", "r");
431 if (f) {
432 mmap_lock();
433
434 do {
435 unsigned long startaddr, endaddr;
436 int n;
437
438 n = fscanf(f, "%lx-%lx %*[^\n]\n", &startaddr, &endaddr);
439
440 if (n == 2 && h2g_valid(startaddr)) {
441 startaddr = h2g(startaddr) & TARGET_PAGE_MASK;
442
443 if (h2g_valid(endaddr)) {
444 endaddr = h2g(endaddr);
445 } else {
446 endaddr = ~0ul;
447 }
448 page_set_flags(startaddr, endaddr, PAGE_RESERVED);
449 }
450 } while (!feof(f));
451
452 fclose(f);
453 mmap_unlock();
454 }
455#endif
456 }
457#endif
458}
459
75692087 460/* If alloc=1:
7d7500d9 461 * Called with tb_lock held for system emulation.
75692087
PB
462 * Called with mmap_lock held for user-mode emulation.
463 */
5b6dd868
BS
464static PageDesc *page_find_alloc(tb_page_addr_t index, int alloc)
465{
466 PageDesc *pd;
467 void **lp;
468 int i;
469
e505a063
AB
470 if (alloc) {
471 assert_memory_lock();
472 }
473
5b6dd868 474 /* Level 1. Always allocated. */
66ec9f49 475 lp = l1_map + ((index >> v_l1_shift) & (v_l1_size - 1));
5b6dd868
BS
476
477 /* Level 2..N-1. */
66ec9f49 478 for (i = v_l2_levels; i > 0; i--) {
6940fab8 479 void **p = atomic_rcu_read(lp);
5b6dd868
BS
480
481 if (p == NULL) {
482 if (!alloc) {
483 return NULL;
484 }
e3a0abfd 485 p = g_new0(void *, V_L2_SIZE);
6940fab8 486 atomic_rcu_set(lp, p);
5b6dd868
BS
487 }
488
03f49957 489 lp = p + ((index >> (i * V_L2_BITS)) & (V_L2_SIZE - 1));
5b6dd868
BS
490 }
491
6940fab8 492 pd = atomic_rcu_read(lp);
5b6dd868
BS
493 if (pd == NULL) {
494 if (!alloc) {
495 return NULL;
496 }
e3a0abfd 497 pd = g_new0(PageDesc, V_L2_SIZE);
6940fab8 498 atomic_rcu_set(lp, pd);
5b6dd868
BS
499 }
500
03f49957 501 return pd + (index & (V_L2_SIZE - 1));
5b6dd868
BS
502}
503
504static inline PageDesc *page_find(tb_page_addr_t index)
505{
506 return page_find_alloc(index, 0);
507}
508
5b6dd868
BS
509#if defined(CONFIG_USER_ONLY)
510/* Currently it is not recommended to allocate big chunks of data in
511 user mode. It will change when a dedicated libc will be used. */
512/* ??? 64-bit hosts ought to have no problem mmaping data outside the
513 region in which the guest needs to run. Revisit this. */
514#define USE_STATIC_CODE_GEN_BUFFER
515#endif
516
5b6dd868
BS
517/* Minimum size of the code gen buffer. This number is randomly chosen,
518 but not so small that we can't have a fair number of TB's live. */
519#define MIN_CODE_GEN_BUFFER_SIZE (1024u * 1024)
520
521/* Maximum size of the code gen buffer we'd like to use. Unless otherwise
522 indicated, this is constrained by the range of direct branches on the
523 host cpu, as used by the TCG implementation of goto_tb. */
524#if defined(__x86_64__)
525# define MAX_CODE_GEN_BUFFER_SIZE (2ul * 1024 * 1024 * 1024)
526#elif defined(__sparc__)
527# define MAX_CODE_GEN_BUFFER_SIZE (2ul * 1024 * 1024 * 1024)
5bfd75a3
RH
528#elif defined(__powerpc64__)
529# define MAX_CODE_GEN_BUFFER_SIZE (2ul * 1024 * 1024 * 1024)
399f1648
SF
530#elif defined(__powerpc__)
531# define MAX_CODE_GEN_BUFFER_SIZE (32u * 1024 * 1024)
4a136e0a 532#elif defined(__aarch64__)
b68686bd 533# define MAX_CODE_GEN_BUFFER_SIZE (2ul * 1024 * 1024 * 1024)
5b6dd868
BS
534#elif defined(__s390x__)
535 /* We have a +- 4GB range on the branches; leave some slop. */
536# define MAX_CODE_GEN_BUFFER_SIZE (3ul * 1024 * 1024 * 1024)
479eb121
RH
537#elif defined(__mips__)
538 /* We have a 256MB branch region, but leave room to make sure the
539 main executable is also within that region. */
540# define MAX_CODE_GEN_BUFFER_SIZE (128ul * 1024 * 1024)
5b6dd868
BS
541#else
542# define MAX_CODE_GEN_BUFFER_SIZE ((size_t)-1)
543#endif
544
545#define DEFAULT_CODE_GEN_BUFFER_SIZE_1 (32u * 1024 * 1024)
546
547#define DEFAULT_CODE_GEN_BUFFER_SIZE \
548 (DEFAULT_CODE_GEN_BUFFER_SIZE_1 < MAX_CODE_GEN_BUFFER_SIZE \
549 ? DEFAULT_CODE_GEN_BUFFER_SIZE_1 : MAX_CODE_GEN_BUFFER_SIZE)
550
551static inline size_t size_code_gen_buffer(size_t tb_size)
552{
553 /* Size the buffer. */
554 if (tb_size == 0) {
555#ifdef USE_STATIC_CODE_GEN_BUFFER
556 tb_size = DEFAULT_CODE_GEN_BUFFER_SIZE;
557#else
558 /* ??? Needs adjustments. */
559 /* ??? If we relax the requirement that CONFIG_USER_ONLY use the
560 static buffer, we could size this on RESERVED_VA, on the text
561 segment size of the executable, or continue to use the default. */
562 tb_size = (unsigned long)(ram_size / 4);
563#endif
564 }
565 if (tb_size < MIN_CODE_GEN_BUFFER_SIZE) {
566 tb_size = MIN_CODE_GEN_BUFFER_SIZE;
567 }
568 if (tb_size > MAX_CODE_GEN_BUFFER_SIZE) {
569 tb_size = MAX_CODE_GEN_BUFFER_SIZE;
570 }
5b6dd868
BS
571 return tb_size;
572}
573
483c76e1
RH
574#ifdef __mips__
575/* In order to use J and JAL within the code_gen_buffer, we require
576 that the buffer not cross a 256MB boundary. */
577static inline bool cross_256mb(void *addr, size_t size)
578{
7ba6a512 579 return ((uintptr_t)addr ^ ((uintptr_t)addr + size)) & ~0x0ffffffful;
483c76e1
RH
580}
581
582/* We weren't able to allocate a buffer without crossing that boundary,
583 so make do with the larger portion of the buffer that doesn't cross.
584 Returns the new base of the buffer, and adjusts code_gen_buffer_size. */
585static inline void *split_cross_256mb(void *buf1, size_t size1)
586{
7ba6a512 587 void *buf2 = (void *)(((uintptr_t)buf1 + size1) & ~0x0ffffffful);
483c76e1
RH
588 size_t size2 = buf1 + size1 - buf2;
589
590 size1 = buf2 - buf1;
591 if (size1 < size2) {
592 size1 = size2;
593 buf1 = buf2;
594 }
595
b1311c4a 596 tcg_ctx->code_gen_buffer_size = size1;
483c76e1
RH
597 return buf1;
598}
599#endif
600
5b6dd868
BS
601#ifdef USE_STATIC_CODE_GEN_BUFFER
602static uint8_t static_code_gen_buffer[DEFAULT_CODE_GEN_BUFFER_SIZE]
603 __attribute__((aligned(CODE_GEN_ALIGN)));
604
f293709c
RH
605# ifdef _WIN32
606static inline void do_protect(void *addr, long size, int prot)
607{
608 DWORD old_protect;
609 VirtualProtect(addr, size, prot, &old_protect);
610}
611
612static inline void map_exec(void *addr, long size)
613{
614 do_protect(addr, size, PAGE_EXECUTE_READWRITE);
615}
616
617static inline void map_none(void *addr, long size)
618{
619 do_protect(addr, size, PAGE_NOACCESS);
620}
621# else
622static inline void do_protect(void *addr, long size, int prot)
623{
624 uintptr_t start, end;
625
626 start = (uintptr_t)addr;
627 start &= qemu_real_host_page_mask;
628
629 end = (uintptr_t)addr + size;
630 end = ROUND_UP(end, qemu_real_host_page_size);
631
632 mprotect((void *)start, end - start, prot);
633}
634
635static inline void map_exec(void *addr, long size)
636{
637 do_protect(addr, size, PROT_READ | PROT_WRITE | PROT_EXEC);
638}
639
640static inline void map_none(void *addr, long size)
641{
642 do_protect(addr, size, PROT_NONE);
643}
644# endif /* WIN32 */
645
5b6dd868
BS
646static inline void *alloc_code_gen_buffer(void)
647{
483c76e1 648 void *buf = static_code_gen_buffer;
f293709c
RH
649 size_t full_size, size;
650
651 /* The size of the buffer, rounded down to end on a page boundary. */
652 full_size = (((uintptr_t)buf + sizeof(static_code_gen_buffer))
653 & qemu_real_host_page_mask) - (uintptr_t)buf;
654
655 /* Reserve a guard page. */
656 size = full_size - qemu_real_host_page_size;
657
658 /* Honor a command-line option limiting the size of the buffer. */
b1311c4a
EC
659 if (size > tcg_ctx->code_gen_buffer_size) {
660 size = (((uintptr_t)buf + tcg_ctx->code_gen_buffer_size)
f293709c
RH
661 & qemu_real_host_page_mask) - (uintptr_t)buf;
662 }
b1311c4a 663 tcg_ctx->code_gen_buffer_size = size;
f293709c 664
483c76e1 665#ifdef __mips__
f293709c
RH
666 if (cross_256mb(buf, size)) {
667 buf = split_cross_256mb(buf, size);
b1311c4a 668 size = tcg_ctx->code_gen_buffer_size;
483c76e1
RH
669 }
670#endif
f293709c
RH
671
672 map_exec(buf, size);
673 map_none(buf + size, qemu_real_host_page_size);
674 qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);
675
483c76e1 676 return buf;
5b6dd868 677}
f293709c
RH
678#elif defined(_WIN32)
679static inline void *alloc_code_gen_buffer(void)
680{
b1311c4a 681 size_t size = tcg_ctx->code_gen_buffer_size;
f293709c
RH
682 void *buf1, *buf2;
683
684 /* Perform the allocation in two steps, so that the guard page
685 is reserved but uncommitted. */
686 buf1 = VirtualAlloc(NULL, size + qemu_real_host_page_size,
687 MEM_RESERVE, PAGE_NOACCESS);
688 if (buf1 != NULL) {
689 buf2 = VirtualAlloc(buf1, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
690 assert(buf1 == buf2);
691 }
692
693 return buf1;
694}
695#else
5b6dd868
BS
696static inline void *alloc_code_gen_buffer(void)
697{
698 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
699 uintptr_t start = 0;
b1311c4a 700 size_t size = tcg_ctx->code_gen_buffer_size;
5b6dd868
BS
701 void *buf;
702
703 /* Constrain the position of the buffer based on the host cpu.
704 Note that these addresses are chosen in concert with the
705 addresses assigned in the relevant linker script file. */
706# if defined(__PIE__) || defined(__PIC__)
707 /* Don't bother setting a preferred location if we're building
708 a position-independent executable. We're more likely to get
709 an address near the main executable if we let the kernel
710 choose the address. */
711# elif defined(__x86_64__) && defined(MAP_32BIT)
712 /* Force the memory down into low memory with the executable.
713 Leave the choice of exact location with the kernel. */
714 flags |= MAP_32BIT;
715 /* Cannot expect to map more than 800MB in low memory. */
f293709c 716 if (size > 800u * 1024 * 1024) {
b1311c4a 717 tcg_ctx->code_gen_buffer_size = size = 800u * 1024 * 1024;
5b6dd868
BS
718 }
719# elif defined(__sparc__)
720 start = 0x40000000ul;
721# elif defined(__s390x__)
722 start = 0x90000000ul;
479eb121 723# elif defined(__mips__)
f293709c 724# if _MIPS_SIM == _ABI64
479eb121
RH
725 start = 0x128000000ul;
726# else
727 start = 0x08000000ul;
728# endif
5b6dd868
BS
729# endif
730
f293709c
RH
731 buf = mmap((void *)start, size + qemu_real_host_page_size,
732 PROT_NONE, flags, -1, 0);
483c76e1
RH
733 if (buf == MAP_FAILED) {
734 return NULL;
735 }
736
737#ifdef __mips__
f293709c 738 if (cross_256mb(buf, size)) {
5d831be2 739 /* Try again, with the original still mapped, to avoid re-acquiring
483c76e1 740 that 256mb crossing. This time don't specify an address. */
f293709c
RH
741 size_t size2;
742 void *buf2 = mmap(NULL, size + qemu_real_host_page_size,
743 PROT_NONE, flags, -1, 0);
f68808c7 744 switch ((int)(buf2 != MAP_FAILED)) {
f293709c
RH
745 case 1:
746 if (!cross_256mb(buf2, size)) {
483c76e1 747 /* Success! Use the new buffer. */
8bdf4997 748 munmap(buf, size + qemu_real_host_page_size);
f293709c 749 break;
483c76e1
RH
750 }
751 /* Failure. Work with what we had. */
8bdf4997 752 munmap(buf2, size + qemu_real_host_page_size);
f293709c
RH
753 /* fallthru */
754 default:
755 /* Split the original buffer. Free the smaller half. */
756 buf2 = split_cross_256mb(buf, size);
b1311c4a 757 size2 = tcg_ctx->code_gen_buffer_size;
f293709c
RH
758 if (buf == buf2) {
759 munmap(buf + size2 + qemu_real_host_page_size, size - size2);
760 } else {
761 munmap(buf, size - size2);
762 }
763 size = size2;
764 break;
483c76e1 765 }
f293709c 766 buf = buf2;
483c76e1
RH
767 }
768#endif
769
f293709c
RH
770 /* Make the final buffer accessible. The guard page at the end
771 will remain inaccessible with PROT_NONE. */
772 mprotect(buf, size, PROT_WRITE | PROT_READ | PROT_EXEC);
483c76e1 773
f293709c
RH
774 /* Request large pages for the buffer. */
775 qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);
483c76e1 776
5b6dd868
BS
777 return buf;
778}
f293709c 779#endif /* USE_STATIC_CODE_GEN_BUFFER, WIN32, POSIX */
5b6dd868 780
2ac01d6d
EC
781/* compare a pointer @ptr and a tb_tc @s */
782static int ptr_cmp_tb_tc(const void *ptr, const struct tb_tc *s)
783{
784 if (ptr >= s->ptr + s->size) {
785 return 1;
786 } else if (ptr < s->ptr) {
787 return -1;
788 }
789 return 0;
790}
791
792static gint tb_tc_cmp(gconstpointer ap, gconstpointer bp)
793{
794 const struct tb_tc *a = ap;
795 const struct tb_tc *b = bp;
796
797 /*
798 * When both sizes are set, we know this isn't a lookup.
799 * This is the most likely case: every TB must be inserted; lookups
800 * are a lot less frequent.
801 */
802 if (likely(a->size && b->size)) {
803 if (a->ptr > b->ptr) {
804 return 1;
805 } else if (a->ptr < b->ptr) {
806 return -1;
807 }
808 /* a->ptr == b->ptr should happen only on deletions */
809 g_assert(a->size == b->size);
810 return 0;
811 }
812 /*
813 * All lookups have either .size field set to 0.
814 * From the glib sources we see that @ap is always the lookup key. However
815 * the docs provide no guarantee, so we just mark this case as likely.
816 */
817 if (likely(a->size == 0)) {
818 return ptr_cmp_tb_tc(a->ptr, b);
819 }
820 return ptr_cmp_tb_tc(b->ptr, a);
821}
822
5b6dd868
BS
823static inline void code_gen_alloc(size_t tb_size)
824{
b1311c4a
EC
825 tcg_ctx->code_gen_buffer_size = size_code_gen_buffer(tb_size);
826 tcg_ctx->code_gen_buffer = alloc_code_gen_buffer();
827 if (tcg_ctx->code_gen_buffer == NULL) {
5b6dd868
BS
828 fprintf(stderr, "Could not allocate dynamic translator buffer\n");
829 exit(1);
830 }
44ded3d0
EC
831 tb_ctx.tb_tree = g_tree_new(tb_tc_cmp);
832 qemu_mutex_init(&tb_ctx.tb_lock);
5b6dd868
BS
833}
834
909eaac9
EC
835static void tb_htable_init(void)
836{
837 unsigned int mode = QHT_MODE_AUTO_RESIZE;
838
44ded3d0 839 qht_init(&tb_ctx.htable, CODE_GEN_HTABLE_SIZE, mode);
909eaac9
EC
840}
841
5b6dd868
BS
842/* Must be called before using the QEMU cpus. 'tb_size' is the size
843 (in bytes) allocated to the translation buffer. Zero means default
844 size. */
845void tcg_exec_init(unsigned long tb_size)
846{
8e2b7299 847 tcg_allowed = true;
5b6dd868 848 cpu_gen_init();
5b6dd868 849 page_init();
909eaac9 850 tb_htable_init();
f293709c 851 code_gen_alloc(tb_size);
4cbea598 852#if defined(CONFIG_SOFTMMU)
5b6dd868
BS
853 /* There's no guest base to take into account, so go ahead and
854 initialize the prologue now. */
b1311c4a 855 tcg_prologue_init(tcg_ctx);
5b6dd868
BS
856#endif
857}
858
7d7500d9
PB
859/*
860 * Allocate a new translation block. Flush the translation buffer if
861 * too many translation blocks or too much generated code.
862 *
863 * Called with tb_lock held.
864 */
5b6dd868
BS
865static TranslationBlock *tb_alloc(target_ulong pc)
866{
867 TranslationBlock *tb;
868
6ac3d7e8 869 assert_tb_locked();
e505a063 870
b1311c4a 871 tb = tcg_tb_alloc(tcg_ctx);
6e3b2bfd 872 if (unlikely(tb == NULL)) {
5b6dd868
BS
873 return NULL;
874 }
5b6dd868
BS
875 return tb;
876}
877
7d7500d9 878/* Called with tb_lock held. */
be1e0117 879void tb_remove(TranslationBlock *tb)
5b6dd868 880{
6ac3d7e8 881 assert_tb_locked();
e505a063 882
44ded3d0 883 g_tree_remove(tb_ctx.tb_tree, &tb->tc);
5b6dd868
BS
884}
885
886static inline void invalidate_page_bitmap(PageDesc *p)
887{
6fad459c 888#ifdef CONFIG_SOFTMMU
012aef07
MA
889 g_free(p->code_bitmap);
890 p->code_bitmap = NULL;
5b6dd868 891 p->code_write_count = 0;
6fad459c 892#endif
5b6dd868
BS
893}
894
895/* Set to NULL all the 'first_tb' fields in all PageDescs. */
896static void page_flush_tb_1(int level, void **lp)
897{
898 int i;
899
900 if (*lp == NULL) {
901 return;
902 }
903 if (level == 0) {
904 PageDesc *pd = *lp;
905
03f49957 906 for (i = 0; i < V_L2_SIZE; ++i) {
5b6dd868
BS
907 pd[i].first_tb = NULL;
908 invalidate_page_bitmap(pd + i);
909 }
910 } else {
911 void **pp = *lp;
912
03f49957 913 for (i = 0; i < V_L2_SIZE; ++i) {
5b6dd868
BS
914 page_flush_tb_1(level - 1, pp + i);
915 }
916 }
917}
918
919static void page_flush_tb(void)
920{
66ec9f49 921 int i, l1_sz = v_l1_size;
5b6dd868 922
66ec9f49
VK
923 for (i = 0; i < l1_sz; i++) {
924 page_flush_tb_1(v_l2_levels, l1_map + i);
5b6dd868
BS
925 }
926}
927
f19c6cc6
EC
928static gboolean tb_host_size_iter(gpointer key, gpointer value, gpointer data)
929{
930 const TranslationBlock *tb = value;
931 size_t *size = data;
932
933 *size += tb->tc.size;
934 return false;
935}
936
5b6dd868 937/* flush all the translation blocks */
14e6fe12 938static void do_tb_flush(CPUState *cpu, run_on_cpu_data tb_flush_count)
5b6dd868 939{
3359baad
SF
940 tb_lock();
941
14e6fe12 942 /* If it is already been done on request of another CPU,
3359baad
SF
943 * just retry.
944 */
44ded3d0 945 if (tb_ctx.tb_flush_count != tb_flush_count.host_int) {
3359baad 946 goto done;
135a972b 947 }
3359baad 948
424079c1 949 if (DEBUG_TB_FLUSH_GATE) {
44ded3d0 950 size_t nb_tbs = g_tree_nnodes(tb_ctx.tb_tree);
f19c6cc6 951 size_t host_size = 0;
2ac01d6d 952
44ded3d0 953 g_tree_foreach(tb_ctx.tb_tree, tb_host_size_iter, &host_size);
f19c6cc6 954 printf("qemu: flush code_size=%td nb_tbs=%zu avg_tb_size=%zu\n",
b1311c4a 955 tcg_ctx->code_gen_ptr - tcg_ctx->code_gen_buffer, nb_tbs,
f19c6cc6 956 nb_tbs > 0 ? host_size / nb_tbs : 0);
424079c1 957 }
b1311c4a
EC
958 if ((unsigned long)(tcg_ctx->code_gen_ptr - tcg_ctx->code_gen_buffer)
959 > tcg_ctx->code_gen_buffer_size) {
a47dddd7 960 cpu_abort(cpu, "Internal error: code buffer overflow\n");
5b6dd868 961 }
5b6dd868 962
bdc44640 963 CPU_FOREACH(cpu) {
f3ced3c5 964 cpu_tb_jmp_cache_clear(cpu);
5b6dd868
BS
965 }
966
2ac01d6d 967 /* Increment the refcount first so that destroy acts as a reset */
44ded3d0
EC
968 g_tree_ref(tb_ctx.tb_tree);
969 g_tree_destroy(tb_ctx.tb_tree);
2ac01d6d 970
44ded3d0 971 qht_reset_size(&tb_ctx.htable, CODE_GEN_HTABLE_SIZE);
5b6dd868
BS
972 page_flush_tb();
973
b1311c4a 974 tcg_ctx->code_gen_ptr = tcg_ctx->code_gen_buffer;
5b6dd868
BS
975 /* XXX: flush processor icache at this point if cache flush is
976 expensive */
44ded3d0 977 atomic_mb_set(&tb_ctx.tb_flush_count, tb_ctx.tb_flush_count + 1);
3359baad
SF
978
979done:
980 tb_unlock();
981}
982
983void tb_flush(CPUState *cpu)
984{
985 if (tcg_enabled()) {
44ded3d0 986 unsigned tb_flush_count = atomic_mb_read(&tb_ctx.tb_flush_count);
14e6fe12
PB
987 async_safe_run_on_cpu(cpu, do_tb_flush,
988 RUN_ON_CPU_HOST_INT(tb_flush_count));
3359baad 989 }
5b6dd868
BS
990}
991
6eb062ab
EC
992/*
993 * Formerly ifdef DEBUG_TB_CHECK. These debug functions are user-mode-only,
994 * so in order to prevent bit rot we compile them unconditionally in user-mode,
995 * and let the optimizer get rid of them by wrapping their user-only callers
996 * with if (DEBUG_TB_CHECK_GATE).
997 */
998#ifdef CONFIG_USER_ONLY
5b6dd868 999
909eaac9
EC
1000static void
1001do_tb_invalidate_check(struct qht *ht, void *p, uint32_t hash, void *userp)
5b6dd868 1002{
909eaac9
EC
1003 TranslationBlock *tb = p;
1004 target_ulong addr = *(target_ulong *)userp;
1005
1006 if (!(addr + TARGET_PAGE_SIZE <= tb->pc || addr >= tb->pc + tb->size)) {
1007 printf("ERROR invalidate: address=" TARGET_FMT_lx
1008 " PC=%08lx size=%04x\n", addr, (long)tb->pc, tb->size);
1009 }
1010}
5b6dd868 1011
7d7500d9
PB
1012/* verify that all the pages have correct rights for code
1013 *
1014 * Called with tb_lock held.
1015 */
909eaac9
EC
1016static void tb_invalidate_check(target_ulong address)
1017{
5b6dd868 1018 address &= TARGET_PAGE_MASK;
44ded3d0 1019 qht_iter(&tb_ctx.htable, do_tb_invalidate_check, &address);
909eaac9
EC
1020}
1021
1022static void
1023do_tb_page_check(struct qht *ht, void *p, uint32_t hash, void *userp)
1024{
1025 TranslationBlock *tb = p;
1026 int flags1, flags2;
1027
1028 flags1 = page_get_flags(tb->pc);
1029 flags2 = page_get_flags(tb->pc + tb->size - 1);
1030 if ((flags1 & PAGE_WRITE) || (flags2 & PAGE_WRITE)) {
1031 printf("ERROR page flags: PC=%08lx size=%04x f1=%x f2=%x\n",
1032 (long)tb->pc, tb->size, flags1, flags2);
5b6dd868
BS
1033 }
1034}
1035
1036/* verify that all the pages have correct rights for code */
1037static void tb_page_check(void)
1038{
44ded3d0 1039 qht_iter(&tb_ctx.htable, do_tb_page_check, NULL);
5b6dd868
BS
1040}
1041
6eb062ab 1042#endif /* CONFIG_USER_ONLY */
5b6dd868 1043
5b6dd868
BS
1044static inline void tb_page_remove(TranslationBlock **ptb, TranslationBlock *tb)
1045{
1046 TranslationBlock *tb1;
1047 unsigned int n1;
1048
1049 for (;;) {
1050 tb1 = *ptb;
1051 n1 = (uintptr_t)tb1 & 3;
1052 tb1 = (TranslationBlock *)((uintptr_t)tb1 & ~3);
1053 if (tb1 == tb) {
1054 *ptb = tb1->page_next[n1];
1055 break;
1056 }
1057 ptb = &tb1->page_next[n1];
1058 }
1059}
1060
13362678
SF
1061/* remove the TB from a list of TBs jumping to the n-th jump target of the TB */
1062static inline void tb_remove_from_jmp_list(TranslationBlock *tb, int n)
5b6dd868 1063{
c37e6d7e
SF
1064 TranslationBlock *tb1;
1065 uintptr_t *ptb, ntb;
5b6dd868
BS
1066 unsigned int n1;
1067
f309101c 1068 ptb = &tb->jmp_list_next[n];
c37e6d7e 1069 if (*ptb) {
5b6dd868
BS
1070 /* find tb(n) in circular list */
1071 for (;;) {
c37e6d7e
SF
1072 ntb = *ptb;
1073 n1 = ntb & 3;
1074 tb1 = (TranslationBlock *)(ntb & ~3);
5b6dd868
BS
1075 if (n1 == n && tb1 == tb) {
1076 break;
1077 }
1078 if (n1 == 2) {
f309101c 1079 ptb = &tb1->jmp_list_first;
5b6dd868 1080 } else {
f309101c 1081 ptb = &tb1->jmp_list_next[n1];
5b6dd868
BS
1082 }
1083 }
1084 /* now we can suppress tb(n) from the list */
f309101c 1085 *ptb = tb->jmp_list_next[n];
5b6dd868 1086
c37e6d7e 1087 tb->jmp_list_next[n] = (uintptr_t)NULL;
5b6dd868
BS
1088 }
1089}
1090
1091/* reset the jump entry 'n' of a TB so that it is not chained to
1092 another TB */
1093static inline void tb_reset_jump(TranslationBlock *tb, int n)
1094{
e7e168f4 1095 uintptr_t addr = (uintptr_t)(tb->tc.ptr + tb->jmp_reset_offset[n]);
f309101c 1096 tb_set_jmp_target(tb, n, addr);
5b6dd868
BS
1097}
1098
89bba496
SF
1099/* remove any jumps to the TB */
1100static inline void tb_jmp_unlink(TranslationBlock *tb)
1101{
f9c5b66f
SF
1102 TranslationBlock *tb1;
1103 uintptr_t *ptb, ntb;
89bba496
SF
1104 unsigned int n1;
1105
f9c5b66f 1106 ptb = &tb->jmp_list_first;
89bba496 1107 for (;;) {
f9c5b66f
SF
1108 ntb = *ptb;
1109 n1 = ntb & 3;
1110 tb1 = (TranslationBlock *)(ntb & ~3);
89bba496
SF
1111 if (n1 == 2) {
1112 break;
1113 }
f9c5b66f
SF
1114 tb_reset_jump(tb1, n1);
1115 *ptb = tb1->jmp_list_next[n1];
1116 tb1->jmp_list_next[n1] = (uintptr_t)NULL;
89bba496 1117 }
89bba496
SF
1118}
1119
7d7500d9
PB
1120/* invalidate one TB
1121 *
1122 * Called with tb_lock held.
1123 */
5b6dd868
BS
1124void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr)
1125{
182735ef 1126 CPUState *cpu;
5b6dd868 1127 PageDesc *p;
42bd3228 1128 uint32_t h;
5b6dd868 1129 tb_page_addr_t phys_pc;
5b6dd868 1130
6ac3d7e8 1131 assert_tb_locked();
e505a063 1132
84f1c148 1133 atomic_set(&tb->cflags, tb->cflags | CF_INVALID);
6d21e420 1134
5b6dd868
BS
1135 /* remove the TB from the hash list */
1136 phys_pc = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);
4e2ca83e
EC
1137 h = tb_hash_func(phys_pc, tb->pc, tb->flags, tb->cflags & CF_HASH_MASK,
1138 tb->trace_vcpu_dstate);
44ded3d0 1139 qht_remove(&tb_ctx.htable, tb, h);
5b6dd868
BS
1140
1141 /* remove the TB from the page list */
1142 if (tb->page_addr[0] != page_addr) {
1143 p = page_find(tb->page_addr[0] >> TARGET_PAGE_BITS);
1144 tb_page_remove(&p->first_tb, tb);
1145 invalidate_page_bitmap(p);
1146 }
1147 if (tb->page_addr[1] != -1 && tb->page_addr[1] != page_addr) {
1148 p = page_find(tb->page_addr[1] >> TARGET_PAGE_BITS);
1149 tb_page_remove(&p->first_tb, tb);
1150 invalidate_page_bitmap(p);
1151 }
1152
5b6dd868
BS
1153 /* remove the TB from the hash list */
1154 h = tb_jmp_cache_hash_func(tb->pc);
bdc44640 1155 CPU_FOREACH(cpu) {
89a16b1e
SF
1156 if (atomic_read(&cpu->tb_jmp_cache[h]) == tb) {
1157 atomic_set(&cpu->tb_jmp_cache[h], NULL);
5b6dd868
BS
1158 }
1159 }
1160
1161 /* suppress this TB from the two jump lists */
13362678
SF
1162 tb_remove_from_jmp_list(tb, 0);
1163 tb_remove_from_jmp_list(tb, 1);
5b6dd868
BS
1164
1165 /* suppress any remaining jumps to this TB */
89bba496 1166 tb_jmp_unlink(tb);
5b6dd868 1167
44ded3d0 1168 tb_ctx.tb_phys_invalidate_count++;
5b6dd868
BS
1169}
1170
6fad459c 1171#ifdef CONFIG_SOFTMMU
5b6dd868
BS
1172static void build_page_bitmap(PageDesc *p)
1173{
1174 int n, tb_start, tb_end;
1175 TranslationBlock *tb;
1176
510a647f 1177 p->code_bitmap = bitmap_new(TARGET_PAGE_SIZE);
5b6dd868
BS
1178
1179 tb = p->first_tb;
1180 while (tb != NULL) {
1181 n = (uintptr_t)tb & 3;
1182 tb = (TranslationBlock *)((uintptr_t)tb & ~3);
1183 /* NOTE: this is subtle as a TB may span two physical pages */
1184 if (n == 0) {
1185 /* NOTE: tb_end may be after the end of the page, but
1186 it is not a problem */
1187 tb_start = tb->pc & ~TARGET_PAGE_MASK;
1188 tb_end = tb_start + tb->size;
1189 if (tb_end > TARGET_PAGE_SIZE) {
1190 tb_end = TARGET_PAGE_SIZE;
e505a063 1191 }
5b6dd868
BS
1192 } else {
1193 tb_start = 0;
1194 tb_end = ((tb->pc + tb->size) & ~TARGET_PAGE_MASK);
1195 }
510a647f 1196 bitmap_set(p->code_bitmap, tb_start, tb_end - tb_start);
5b6dd868
BS
1197 tb = tb->page_next[n];
1198 }
1199}
6fad459c 1200#endif
5b6dd868 1201
e90d96b1
SF
1202/* add the tb in the target page and protect it if necessary
1203 *
1204 * Called with mmap_lock held for user-mode emulation.
1205 */
1206static inline void tb_alloc_page(TranslationBlock *tb,
1207 unsigned int n, tb_page_addr_t page_addr)
1208{
1209 PageDesc *p;
1210#ifndef CONFIG_USER_ONLY
1211 bool page_already_protected;
1212#endif
1213
e505a063
AB
1214 assert_memory_lock();
1215
e90d96b1
SF
1216 tb->page_addr[n] = page_addr;
1217 p = page_find_alloc(page_addr >> TARGET_PAGE_BITS, 1);
1218 tb->page_next[n] = p->first_tb;
1219#ifndef CONFIG_USER_ONLY
1220 page_already_protected = p->first_tb != NULL;
1221#endif
1222 p->first_tb = (TranslationBlock *)((uintptr_t)tb | n);
1223 invalidate_page_bitmap(p);
1224
1225#if defined(CONFIG_USER_ONLY)
1226 if (p->flags & PAGE_WRITE) {
1227 target_ulong addr;
1228 PageDesc *p2;
1229 int prot;
1230
1231 /* force the host page as non writable (writes will have a
1232 page fault + mprotect overhead) */
1233 page_addr &= qemu_host_page_mask;
1234 prot = 0;
1235 for (addr = page_addr; addr < page_addr + qemu_host_page_size;
1236 addr += TARGET_PAGE_SIZE) {
1237
1238 p2 = page_find(addr >> TARGET_PAGE_BITS);
1239 if (!p2) {
1240 continue;
1241 }
1242 prot |= p2->flags;
1243 p2->flags &= ~PAGE_WRITE;
1244 }
1245 mprotect(g2h(page_addr), qemu_host_page_size,
1246 (prot & PAGE_BITS) & ~PAGE_WRITE);
dae9e03a
EC
1247 if (DEBUG_TB_INVALIDATE_GATE) {
1248 printf("protecting code page: 0x" TB_PAGE_ADDR_FMT "\n", page_addr);
1249 }
e90d96b1
SF
1250 }
1251#else
1252 /* if some code is already present, then the pages are already
1253 protected. So we handle the case where only the first TB is
1254 allocated in a physical page */
1255 if (!page_already_protected) {
1256 tlb_protect_code(page_addr);
1257 }
1258#endif
1259}
1260
1261/* add a new TB and link it to the physical page tables. phys_page2 is
1262 * (-1) to indicate that only one page contains the TB.
1263 *
1264 * Called with mmap_lock held for user-mode emulation.
1265 */
1266static void tb_link_page(TranslationBlock *tb, tb_page_addr_t phys_pc,
1267 tb_page_addr_t phys_page2)
1268{
42bd3228 1269 uint32_t h;
e90d96b1 1270
e505a063
AB
1271 assert_memory_lock();
1272
e90d96b1
SF
1273 /* add in the page list */
1274 tb_alloc_page(tb, 0, phys_pc & TARGET_PAGE_MASK);
1275 if (phys_page2 != -1) {
1276 tb_alloc_page(tb, 1, phys_page2);
1277 } else {
1278 tb->page_addr[1] = -1;
1279 }
1280
2e1ae44a 1281 /* add in the hash table */
4e2ca83e
EC
1282 h = tb_hash_func(phys_pc, tb->pc, tb->flags, tb->cflags & CF_HASH_MASK,
1283 tb->trace_vcpu_dstate);
44ded3d0 1284 qht_insert(&tb_ctx.htable, tb, h);
2e1ae44a 1285
6eb062ab
EC
1286#ifdef CONFIG_USER_ONLY
1287 if (DEBUG_TB_CHECK_GATE) {
1288 tb_page_check();
1289 }
e90d96b1
SF
1290#endif
1291}
1292
75692087 1293/* Called with mmap_lock held for user mode emulation. */
648f034c 1294TranslationBlock *tb_gen_code(CPUState *cpu,
5b6dd868 1295 target_ulong pc, target_ulong cs_base,
89fee74a 1296 uint32_t flags, int cflags)
5b6dd868 1297{
648f034c 1298 CPUArchState *env = cpu->env_ptr;
5b6dd868 1299 TranslationBlock *tb;
5b6dd868
BS
1300 tb_page_addr_t phys_pc, phys_page2;
1301 target_ulong virt_page2;
fec88f64 1302 tcg_insn_unit *gen_code_buf;
fca8a500 1303 int gen_code_size, search_size;
fec88f64 1304#ifdef CONFIG_PROFILER
c3fac113 1305 TCGProfile *prof = &tcg_ctx->prof;
fec88f64
RH
1306 int64_t ti;
1307#endif
e505a063 1308 assert_memory_lock();
5b6dd868
BS
1309
1310 phys_pc = get_page_addr_code(env, pc);
b125f9dc 1311
5b6dd868 1312 tb = tb_alloc(pc);
b125f9dc
RH
1313 if (unlikely(!tb)) {
1314 buffer_overflow:
5b6dd868 1315 /* flush must be done */
bbd77c18 1316 tb_flush(cpu);
3359baad 1317 mmap_unlock();
8499c8fc
PD
1318 /* Make the execution loop process the flush as soon as possible. */
1319 cpu->exception_index = EXCP_INTERRUPT;
3359baad 1320 cpu_loop_exit(cpu);
5b6dd868 1321 }
fec88f64 1322
b1311c4a 1323 gen_code_buf = tcg_ctx->code_gen_ptr;
e7e168f4 1324 tb->tc.ptr = gen_code_buf;
2b48e10f 1325 tb->pc = pc;
5b6dd868
BS
1326 tb->cs_base = cs_base;
1327 tb->flags = flags;
1328 tb->cflags = cflags;
61a67f71 1329 tb->trace_vcpu_dstate = *cpu->trace_dstate;
b1311c4a 1330 tcg_ctx->tb_cflags = cflags;
fec88f64
RH
1331
1332#ifdef CONFIG_PROFILER
c3fac113
EC
1333 /* includes aborted translations because of exceptions */
1334 atomic_set(&prof->tb_count1, prof->tb_count1 + 1);
fec88f64
RH
1335 ti = profile_getclock();
1336#endif
1337
b1311c4a 1338 tcg_func_start(tcg_ctx);
fec88f64 1339
b1311c4a 1340 tcg_ctx->cpu = ENV_GET_CPU(env);
9c489ea6 1341 gen_intermediate_code(cpu, tb);
b1311c4a 1342 tcg_ctx->cpu = NULL;
fec88f64 1343
e7e168f4 1344 trace_translate_block(tb, tb->pc, tb->tc.ptr);
fec88f64
RH
1345
1346 /* generate machine code */
f309101c
SF
1347 tb->jmp_reset_offset[0] = TB_JMP_RESET_OFFSET_INVALID;
1348 tb->jmp_reset_offset[1] = TB_JMP_RESET_OFFSET_INVALID;
b1311c4a 1349 tcg_ctx->tb_jmp_reset_offset = tb->jmp_reset_offset;
a8583393 1350 if (TCG_TARGET_HAS_direct_jump) {
b1311c4a
EC
1351 tcg_ctx->tb_jmp_insn_offset = tb->jmp_target_arg;
1352 tcg_ctx->tb_jmp_target_addr = NULL;
a8583393 1353 } else {
b1311c4a
EC
1354 tcg_ctx->tb_jmp_insn_offset = NULL;
1355 tcg_ctx->tb_jmp_target_addr = tb->jmp_target_arg;
a8583393 1356 }
fec88f64
RH
1357
1358#ifdef CONFIG_PROFILER
c3fac113
EC
1359 atomic_set(&prof->tb_count, prof->tb_count + 1);
1360 atomic_set(&prof->interm_time, prof->interm_time + profile_getclock() - ti);
0aecede6 1361 ti = profile_getclock();
fec88f64
RH
1362#endif
1363
b125f9dc
RH
1364 /* ??? Overflow could be handled better here. In particular, we
1365 don't need to re-do gen_intermediate_code, nor should we re-do
1366 the tcg optimization currently hidden inside tcg_gen_code. All
1367 that should be required is to flush the TBs, allocate a new TB,
1368 re-initialize it per above, and re-do the actual code generation. */
b1311c4a 1369 gen_code_size = tcg_gen_code(tcg_ctx, tb);
b125f9dc
RH
1370 if (unlikely(gen_code_size < 0)) {
1371 goto buffer_overflow;
1372 }
fca8a500 1373 search_size = encode_search(tb, (void *)gen_code_buf + gen_code_size);
b125f9dc
RH
1374 if (unlikely(search_size < 0)) {
1375 goto buffer_overflow;
1376 }
2ac01d6d 1377 tb->tc.size = gen_code_size;
fec88f64
RH
1378
1379#ifdef CONFIG_PROFILER
c3fac113
EC
1380 atomic_set(&prof->code_time, prof->code_time + profile_getclock() - ti);
1381 atomic_set(&prof->code_in_len, prof->code_in_len + tb->size);
1382 atomic_set(&prof->code_out_len, prof->code_out_len + gen_code_size);
1383 atomic_set(&prof->search_out_len, prof->search_out_len + search_size);
fec88f64
RH
1384#endif
1385
1386#ifdef DEBUG_DISAS
d977e1c2
AB
1387 if (qemu_loglevel_mask(CPU_LOG_TB_OUT_ASM) &&
1388 qemu_log_in_addr_range(tb->pc)) {
1ee73216 1389 qemu_log_lock();
fec88f64 1390 qemu_log("OUT: [size=%d]\n", gen_code_size);
b1311c4a
EC
1391 if (tcg_ctx->data_gen_ptr) {
1392 size_t code_size = tcg_ctx->data_gen_ptr - tb->tc.ptr;
57a26946
RH
1393 size_t data_size = gen_code_size - code_size;
1394 size_t i;
1395
e7e168f4 1396 log_disas(tb->tc.ptr, code_size);
57a26946
RH
1397
1398 for (i = 0; i < data_size; i += sizeof(tcg_target_ulong)) {
1399 if (sizeof(tcg_target_ulong) == 8) {
1400 qemu_log("0x%08" PRIxPTR ": .quad 0x%016" PRIx64 "\n",
b1311c4a
EC
1401 (uintptr_t)tcg_ctx->data_gen_ptr + i,
1402 *(uint64_t *)(tcg_ctx->data_gen_ptr + i));
57a26946
RH
1403 } else {
1404 qemu_log("0x%08" PRIxPTR ": .long 0x%08x\n",
b1311c4a
EC
1405 (uintptr_t)tcg_ctx->data_gen_ptr + i,
1406 *(uint32_t *)(tcg_ctx->data_gen_ptr + i));
57a26946
RH
1407 }
1408 }
1409 } else {
e7e168f4 1410 log_disas(tb->tc.ptr, gen_code_size);
57a26946 1411 }
fec88f64
RH
1412 qemu_log("\n");
1413 qemu_log_flush();
1ee73216 1414 qemu_log_unlock();
fec88f64
RH
1415 }
1416#endif
1417
b1311c4a 1418 tcg_ctx->code_gen_ptr = (void *)
fca8a500
RH
1419 ROUND_UP((uintptr_t)gen_code_buf + gen_code_size + search_size,
1420 CODE_GEN_ALIGN);
5b6dd868 1421
901bc3de
SF
1422 /* init jump list */
1423 assert(((uintptr_t)tb & 3) == 0);
1424 tb->jmp_list_first = (uintptr_t)tb | 2;
1425 tb->jmp_list_next[0] = (uintptr_t)NULL;
1426 tb->jmp_list_next[1] = (uintptr_t)NULL;
1427
1428 /* init original jump addresses wich has been set during tcg_gen_code() */
1429 if (tb->jmp_reset_offset[0] != TB_JMP_RESET_OFFSET_INVALID) {
1430 tb_reset_jump(tb, 0);
1431 }
1432 if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) {
1433 tb_reset_jump(tb, 1);
1434 }
1435
5b6dd868
BS
1436 /* check next page if needed */
1437 virt_page2 = (pc + tb->size - 1) & TARGET_PAGE_MASK;
1438 phys_page2 = -1;
1439 if ((pc & TARGET_PAGE_MASK) != virt_page2) {
1440 phys_page2 = get_page_addr_code(env, virt_page2);
1441 }
901bc3de
SF
1442 /* As long as consistency of the TB stuff is provided by tb_lock in user
1443 * mode and is implicit in single-threaded softmmu emulation, no explicit
1444 * memory barrier is required before tb_link_page() makes the TB visible
1445 * through the physical hash table and physical page list.
1446 */
5b6dd868 1447 tb_link_page(tb, phys_pc, phys_page2);
44ded3d0 1448 g_tree_insert(tb_ctx.tb_tree, &tb->tc, tb);
5b6dd868
BS
1449 return tb;
1450}
1451
1452/*
1453 * Invalidate all TBs which intersect with the target physical address range
1454 * [start;end[. NOTE: start and end may refer to *different* physical pages.
1455 * 'is_cpu_write_access' should be true if called from a real cpu write
1456 * access: the virtual CPU will exit the current TB if code is modified inside
1457 * this TB.
75692087 1458 *
ba051fb5
AB
1459 * Called with mmap_lock held for user-mode emulation, grabs tb_lock
1460 * Called with tb_lock held for system-mode emulation
5b6dd868 1461 */
ba051fb5 1462static void tb_invalidate_phys_range_1(tb_page_addr_t start, tb_page_addr_t end)
5b6dd868
BS
1463{
1464 while (start < end) {
35865339 1465 tb_invalidate_phys_page_range(start, end, 0);
5b6dd868
BS
1466 start &= TARGET_PAGE_MASK;
1467 start += TARGET_PAGE_SIZE;
1468 }
1469}
1470
ba051fb5
AB
1471#ifdef CONFIG_SOFTMMU
1472void tb_invalidate_phys_range(tb_page_addr_t start, tb_page_addr_t end)
1473{
6ac3d7e8 1474 assert_tb_locked();
ba051fb5
AB
1475 tb_invalidate_phys_range_1(start, end);
1476}
1477#else
1478void tb_invalidate_phys_range(tb_page_addr_t start, tb_page_addr_t end)
1479{
1480 assert_memory_lock();
1481 tb_lock();
1482 tb_invalidate_phys_range_1(start, end);
1483 tb_unlock();
1484}
1485#endif
5b6dd868
BS
1486/*
1487 * Invalidate all TBs which intersect with the target physical address range
1488 * [start;end[. NOTE: start and end must refer to the *same* physical page.
1489 * 'is_cpu_write_access' should be true if called from a real cpu write
1490 * access: the virtual CPU will exit the current TB if code is modified inside
1491 * this TB.
75692087 1492 *
ba051fb5
AB
1493 * Called with tb_lock/mmap_lock held for user-mode emulation
1494 * Called with tb_lock held for system-mode emulation
5b6dd868
BS
1495 */
1496void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end,
1497 int is_cpu_write_access)
1498{
3213525f 1499 TranslationBlock *tb, *tb_next;
5b6dd868
BS
1500 tb_page_addr_t tb_start, tb_end;
1501 PageDesc *p;
1502 int n;
1503#ifdef TARGET_HAS_PRECISE_SMC
9b990ee5
RH
1504 CPUState *cpu = current_cpu;
1505 CPUArchState *env = NULL;
5b6dd868
BS
1506 int current_tb_not_found = is_cpu_write_access;
1507 TranslationBlock *current_tb = NULL;
1508 int current_tb_modified = 0;
1509 target_ulong current_pc = 0;
1510 target_ulong current_cs_base = 0;
89fee74a 1511 uint32_t current_flags = 0;
5b6dd868
BS
1512#endif /* TARGET_HAS_PRECISE_SMC */
1513
e505a063 1514 assert_memory_lock();
6ac3d7e8 1515 assert_tb_locked();
e505a063 1516
5b6dd868
BS
1517 p = page_find(start >> TARGET_PAGE_BITS);
1518 if (!p) {
1519 return;
1520 }
baea4fae 1521#if defined(TARGET_HAS_PRECISE_SMC)
4917cf44
AF
1522 if (cpu != NULL) {
1523 env = cpu->env_ptr;
d77953b9 1524 }
4917cf44 1525#endif
5b6dd868
BS
1526
1527 /* we remove all the TBs in the range [start, end[ */
1528 /* XXX: see if in some cases it could be faster to invalidate all
1529 the code */
1530 tb = p->first_tb;
1531 while (tb != NULL) {
1532 n = (uintptr_t)tb & 3;
1533 tb = (TranslationBlock *)((uintptr_t)tb & ~3);
1534 tb_next = tb->page_next[n];
1535 /* NOTE: this is subtle as a TB may span two physical pages */
1536 if (n == 0) {
1537 /* NOTE: tb_end may be after the end of the page, but
1538 it is not a problem */
1539 tb_start = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);
1540 tb_end = tb_start + tb->size;
1541 } else {
1542 tb_start = tb->page_addr[1];
1543 tb_end = tb_start + ((tb->pc + tb->size) & ~TARGET_PAGE_MASK);
1544 }
1545 if (!(tb_end <= start || tb_start >= end)) {
1546#ifdef TARGET_HAS_PRECISE_SMC
1547 if (current_tb_not_found) {
1548 current_tb_not_found = 0;
1549 current_tb = NULL;
93afeade 1550 if (cpu->mem_io_pc) {
5b6dd868 1551 /* now we have a real cpu fault */
93afeade 1552 current_tb = tb_find_pc(cpu->mem_io_pc);
5b6dd868
BS
1553 }
1554 }
1555 if (current_tb == tb &&
1556 (current_tb->cflags & CF_COUNT_MASK) != 1) {
1557 /* If we are modifying the current TB, we must stop
1558 its execution. We could be more precise by checking
1559 that the modification is after the current PC, but it
1560 would require a specialized function to partially
1561 restore the CPU state */
1562
1563 current_tb_modified = 1;
74f10515 1564 cpu_restore_state_from_tb(cpu, current_tb, cpu->mem_io_pc);
5b6dd868
BS
1565 cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base,
1566 &current_flags);
1567 }
1568#endif /* TARGET_HAS_PRECISE_SMC */
5b6dd868 1569 tb_phys_invalidate(tb, -1);
5b6dd868
BS
1570 }
1571 tb = tb_next;
1572 }
1573#if !defined(CONFIG_USER_ONLY)
1574 /* if no code remaining, no need to continue to use slow writes */
1575 if (!p->first_tb) {
1576 invalidate_page_bitmap(p);
fc377bcf 1577 tlb_unprotect_code(start);
5b6dd868
BS
1578 }
1579#endif
1580#ifdef TARGET_HAS_PRECISE_SMC
1581 if (current_tb_modified) {
9b990ee5
RH
1582 /* Force execution of one insn next time. */
1583 cpu->cflags_next_tb = 1 | curr_cflags();
6886b980 1584 cpu_loop_exit_noexc(cpu);
5b6dd868
BS
1585 }
1586#endif
1587}
1588
6fad459c 1589#ifdef CONFIG_SOFTMMU
ba051fb5
AB
1590/* len must be <= 8 and start must be a multiple of len.
1591 * Called via softmmu_template.h when code areas are written to with
8d04fb55 1592 * iothread mutex not held.
ba051fb5 1593 */
5b6dd868
BS
1594void tb_invalidate_phys_page_fast(tb_page_addr_t start, int len)
1595{
1596 PageDesc *p;
5b6dd868
BS
1597
1598#if 0
1599 if (1) {
1600 qemu_log("modifying code at 0x%x size=%d EIP=%x PC=%08x\n",
1601 cpu_single_env->mem_io_vaddr, len,
1602 cpu_single_env->eip,
1603 cpu_single_env->eip +
1604 (intptr_t)cpu_single_env->segs[R_CS].base);
1605 }
1606#endif
ba051fb5
AB
1607 assert_memory_lock();
1608
5b6dd868
BS
1609 p = page_find(start >> TARGET_PAGE_BITS);
1610 if (!p) {
1611 return;
1612 }
fc377bcf
PB
1613 if (!p->code_bitmap &&
1614 ++p->code_write_count >= SMC_BITMAP_USE_THRESHOLD) {
7d7500d9
PB
1615 /* build code bitmap. FIXME: writes should be protected by
1616 * tb_lock, reads by tb_lock or RCU.
1617 */
fc377bcf
PB
1618 build_page_bitmap(p);
1619 }
5b6dd868 1620 if (p->code_bitmap) {
510a647f
EC
1621 unsigned int nr;
1622 unsigned long b;
1623
1624 nr = start & ~TARGET_PAGE_MASK;
1625 b = p->code_bitmap[BIT_WORD(nr)] >> (nr & (BITS_PER_LONG - 1));
5b6dd868
BS
1626 if (b & ((1 << len) - 1)) {
1627 goto do_invalidate;
1628 }
1629 } else {
1630 do_invalidate:
1631 tb_invalidate_phys_page_range(start, start + len, 1);
1632 }
1633}
6fad459c 1634#else
75809229
PM
1635/* Called with mmap_lock held. If pc is not 0 then it indicates the
1636 * host PC of the faulting store instruction that caused this invalidate.
1637 * Returns true if the caller needs to abort execution of the current
1638 * TB (because it was modified by this store and the guest CPU has
1639 * precise-SMC semantics).
1640 */
1641static bool tb_invalidate_phys_page(tb_page_addr_t addr, uintptr_t pc)
5b6dd868
BS
1642{
1643 TranslationBlock *tb;
1644 PageDesc *p;
1645 int n;
1646#ifdef TARGET_HAS_PRECISE_SMC
1647 TranslationBlock *current_tb = NULL;
4917cf44
AF
1648 CPUState *cpu = current_cpu;
1649 CPUArchState *env = NULL;
5b6dd868
BS
1650 int current_tb_modified = 0;
1651 target_ulong current_pc = 0;
1652 target_ulong current_cs_base = 0;
89fee74a 1653 uint32_t current_flags = 0;
5b6dd868
BS
1654#endif
1655
ba051fb5
AB
1656 assert_memory_lock();
1657
5b6dd868
BS
1658 addr &= TARGET_PAGE_MASK;
1659 p = page_find(addr >> TARGET_PAGE_BITS);
1660 if (!p) {
75809229 1661 return false;
5b6dd868 1662 }
a5e99826
FK
1663
1664 tb_lock();
5b6dd868
BS
1665 tb = p->first_tb;
1666#ifdef TARGET_HAS_PRECISE_SMC
1667 if (tb && pc != 0) {
1668 current_tb = tb_find_pc(pc);
1669 }
4917cf44
AF
1670 if (cpu != NULL) {
1671 env = cpu->env_ptr;
d77953b9 1672 }
5b6dd868
BS
1673#endif
1674 while (tb != NULL) {
1675 n = (uintptr_t)tb & 3;
1676 tb = (TranslationBlock *)((uintptr_t)tb & ~3);
1677#ifdef TARGET_HAS_PRECISE_SMC
1678 if (current_tb == tb &&
1679 (current_tb->cflags & CF_COUNT_MASK) != 1) {
1680 /* If we are modifying the current TB, we must stop
1681 its execution. We could be more precise by checking
1682 that the modification is after the current PC, but it
1683 would require a specialized function to partially
1684 restore the CPU state */
1685
1686 current_tb_modified = 1;
74f10515 1687 cpu_restore_state_from_tb(cpu, current_tb, pc);
5b6dd868
BS
1688 cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base,
1689 &current_flags);
1690 }
1691#endif /* TARGET_HAS_PRECISE_SMC */
1692 tb_phys_invalidate(tb, addr);
1693 tb = tb->page_next[n];
1694 }
1695 p->first_tb = NULL;
1696#ifdef TARGET_HAS_PRECISE_SMC
1697 if (current_tb_modified) {
9b990ee5
RH
1698 /* Force execution of one insn next time. */
1699 cpu->cflags_next_tb = 1 | curr_cflags();
a5e99826
FK
1700 /* tb_lock will be reset after cpu_loop_exit_noexc longjmps
1701 * back into the cpu_exec loop. */
75809229 1702 return true;
5b6dd868
BS
1703 }
1704#endif
a5e99826
FK
1705 tb_unlock();
1706
75809229 1707 return false;
5b6dd868
BS
1708}
1709#endif
1710
2ac01d6d
EC
1711/*
1712 * Find the TB 'tb' such that
1713 * tb->tc.ptr <= tc_ptr < tb->tc.ptr + tb->tc.size
1714 * Return NULL if not found.
1715 */
a8a826a3 1716static TranslationBlock *tb_find_pc(uintptr_t tc_ptr)
5b6dd868 1717{
2ac01d6d 1718 struct tb_tc s = { .ptr = (void *)tc_ptr };
5b6dd868 1719
44ded3d0 1720 return g_tree_lookup(tb_ctx.tb_tree, &s);
5b6dd868
BS
1721}
1722
ec53b45b 1723#if !defined(CONFIG_USER_ONLY)
29d8ec7b 1724void tb_invalidate_phys_addr(AddressSpace *as, hwaddr addr)
5b6dd868
BS
1725{
1726 ram_addr_t ram_addr;
5c8a00ce 1727 MemoryRegion *mr;
149f54b5 1728 hwaddr l = 1;
5b6dd868 1729
41063e1e 1730 rcu_read_lock();
29d8ec7b 1731 mr = address_space_translate(as, addr, &addr, &l, false);
5c8a00ce
PB
1732 if (!(memory_region_is_ram(mr)
1733 || memory_region_is_romd(mr))) {
41063e1e 1734 rcu_read_unlock();
5b6dd868
BS
1735 return;
1736 }
e4e69794 1737 ram_addr = memory_region_get_ram_addr(mr) + addr;
ba051fb5 1738 tb_lock();
5b6dd868 1739 tb_invalidate_phys_page_range(ram_addr, ram_addr + 1, 0);
ba051fb5 1740 tb_unlock();
41063e1e 1741 rcu_read_unlock();
5b6dd868 1742}
ec53b45b 1743#endif /* !defined(CONFIG_USER_ONLY) */
5b6dd868 1744
7d7500d9 1745/* Called with tb_lock held. */
239c51a5 1746void tb_check_watchpoint(CPUState *cpu)
5b6dd868
BS
1747{
1748 TranslationBlock *tb;
1749
93afeade 1750 tb = tb_find_pc(cpu->mem_io_pc);
8d302e76
AJ
1751 if (tb) {
1752 /* We can use retranslation to find the PC. */
1753 cpu_restore_state_from_tb(cpu, tb, cpu->mem_io_pc);
1754 tb_phys_invalidate(tb, -1);
1755 } else {
1756 /* The exception probably happened in a helper. The CPU state should
1757 have been saved before calling it. Fetch the PC from there. */
1758 CPUArchState *env = cpu->env_ptr;
1759 target_ulong pc, cs_base;
1760 tb_page_addr_t addr;
89fee74a 1761 uint32_t flags;
8d302e76
AJ
1762
1763 cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags);
1764 addr = get_page_addr_code(env, pc);
1765 tb_invalidate_phys_range(addr, addr + 1);
5b6dd868 1766 }
5b6dd868
BS
1767}
1768
1769#ifndef CONFIG_USER_ONLY
5b6dd868 1770/* in deterministic execution mode, instructions doing device I/Os
8d04fb55
JK
1771 * must be at the end of the TB.
1772 *
1773 * Called by softmmu_template.h, with iothread mutex not held.
1774 */
90b40a69 1775void cpu_io_recompile(CPUState *cpu, uintptr_t retaddr)
5b6dd868 1776{
a47dddd7 1777#if defined(TARGET_MIPS) || defined(TARGET_SH4)
90b40a69 1778 CPUArchState *env = cpu->env_ptr;
a47dddd7 1779#endif
5b6dd868 1780 TranslationBlock *tb;
9b990ee5 1781 uint32_t n;
5b6dd868 1782
a5e99826 1783 tb_lock();
5b6dd868
BS
1784 tb = tb_find_pc(retaddr);
1785 if (!tb) {
a47dddd7 1786 cpu_abort(cpu, "cpu_io_recompile: could not find TB for pc=%p",
5b6dd868
BS
1787 (void *)retaddr);
1788 }
28ecfd7a 1789 n = cpu->icount_decr.u16.low + tb->icount;
74f10515 1790 cpu_restore_state_from_tb(cpu, tb, retaddr);
5b6dd868
BS
1791 /* Calculate how many instructions had been executed before the fault
1792 occurred. */
28ecfd7a 1793 n = n - cpu->icount_decr.u16.low;
5b6dd868
BS
1794 /* Generate a new TB ending on the I/O insn. */
1795 n++;
1796 /* On MIPS and SH, delay slot instructions can only be restarted if
1797 they were already the first instruction in the TB. If this is not
1798 the first instruction in a TB then re-execute the preceding
1799 branch. */
1800#if defined(TARGET_MIPS)
1801 if ((env->hflags & MIPS_HFLAG_BMASK) != 0 && n > 1) {
c3577479 1802 env->active_tc.PC -= (env->hflags & MIPS_HFLAG_B16 ? 2 : 4);
28ecfd7a 1803 cpu->icount_decr.u16.low++;
5b6dd868
BS
1804 env->hflags &= ~MIPS_HFLAG_BMASK;
1805 }
1806#elif defined(TARGET_SH4)
1807 if ((env->flags & ((DELAY_SLOT | DELAY_SLOT_CONDITIONAL))) != 0
1808 && n > 1) {
1809 env->pc -= 2;
28ecfd7a 1810 cpu->icount_decr.u16.low++;
5b6dd868
BS
1811 env->flags &= ~(DELAY_SLOT | DELAY_SLOT_CONDITIONAL);
1812 }
1813#endif
1814 /* This should never happen. */
1815 if (n > CF_COUNT_MASK) {
a47dddd7 1816 cpu_abort(cpu, "TB too big during recompile");
5b6dd868
BS
1817 }
1818
9b990ee5
RH
1819 /* Adjust the execution state of the next TB. */
1820 cpu->cflags_next_tb = curr_cflags() | CF_LAST_IO | n;
1821
02d57ea1
SF
1822 if (tb->cflags & CF_NOCACHE) {
1823 if (tb->orig_tb) {
1824 /* Invalidate original TB if this TB was generated in
1825 * cpu_exec_nocache() */
1826 tb_phys_invalidate(tb->orig_tb, -1);
1827 }
be1e0117 1828 tb_remove(tb);
02d57ea1 1829 }
a5e99826 1830
5b6dd868 1831 /* TODO: If env->pc != tb->pc (i.e. the faulting instruction was not
a5e99826
FK
1832 * the first in the TB) then we end up generating a whole new TB and
1833 * repeating the fault, which is horribly inefficient.
1834 * Better would be to execute just this insn uncached, or generate a
1835 * second new TB.
1836 *
1837 * cpu_loop_exit_noexc will longjmp back to cpu_exec where the
1838 * tb_lock gets reset.
1839 */
6886b980 1840 cpu_loop_exit_noexc(cpu);
5b6dd868
BS
1841}
1842
f3ced3c5 1843static void tb_jmp_cache_clear_page(CPUState *cpu, target_ulong page_addr)
5b6dd868 1844{
f3ced3c5 1845 unsigned int i, i0 = tb_jmp_cache_hash_page(page_addr);
5b6dd868 1846
f3ced3c5
EC
1847 for (i = 0; i < TB_JMP_PAGE_SIZE; i++) {
1848 atomic_set(&cpu->tb_jmp_cache[i0 + i], NULL);
1849 }
1850}
1851
1852void tb_flush_jmp_cache(CPUState *cpu, target_ulong addr)
1853{
5b6dd868
BS
1854 /* Discard jump cache entries for any tb which might potentially
1855 overlap the flushed page. */
f3ced3c5
EC
1856 tb_jmp_cache_clear_page(cpu, addr - TARGET_PAGE_SIZE);
1857 tb_jmp_cache_clear_page(cpu, addr);
5b6dd868
BS
1858}
1859
7266ae91
EC
1860static void print_qht_statistics(FILE *f, fprintf_function cpu_fprintf,
1861 struct qht_stats hst)
1862{
1863 uint32_t hgram_opts;
1864 size_t hgram_bins;
1865 char *hgram;
1866
1867 if (!hst.head_buckets) {
1868 return;
1869 }
1870 cpu_fprintf(f, "TB hash buckets %zu/%zu (%0.2f%% head buckets used)\n",
1871 hst.used_head_buckets, hst.head_buckets,
1872 (double)hst.used_head_buckets / hst.head_buckets * 100);
1873
1874 hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
1875 hgram_opts |= QDIST_PR_100X | QDIST_PR_PERCENT;
1876 if (qdist_xmax(&hst.occupancy) - qdist_xmin(&hst.occupancy) == 1) {
1877 hgram_opts |= QDIST_PR_NODECIMAL;
1878 }
1879 hgram = qdist_pr(&hst.occupancy, 10, hgram_opts);
1880 cpu_fprintf(f, "TB hash occupancy %0.2f%% avg chain occ. Histogram: %s\n",
1881 qdist_avg(&hst.occupancy) * 100, hgram);
1882 g_free(hgram);
1883
1884 hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
1885 hgram_bins = qdist_xmax(&hst.chain) - qdist_xmin(&hst.chain);
1886 if (hgram_bins > 10) {
1887 hgram_bins = 10;
1888 } else {
1889 hgram_bins = 0;
1890 hgram_opts |= QDIST_PR_NODECIMAL | QDIST_PR_NOBINRANGE;
1891 }
1892 hgram = qdist_pr(&hst.chain, hgram_bins, hgram_opts);
1893 cpu_fprintf(f, "TB hash avg chain %0.3f buckets. Histogram: %s\n",
1894 qdist_avg(&hst.chain), hgram);
1895 g_free(hgram);
1896}
1897
2ac01d6d 1898struct tb_tree_stats {
f19c6cc6 1899 size_t host_size;
2ac01d6d
EC
1900 size_t target_size;
1901 size_t max_target_size;
1902 size_t direct_jmp_count;
1903 size_t direct_jmp2_count;
1904 size_t cross_page;
1905};
1906
1907static gboolean tb_tree_stats_iter(gpointer key, gpointer value, gpointer data)
1908{
1909 const TranslationBlock *tb = value;
1910 struct tb_tree_stats *tst = data;
1911
f19c6cc6 1912 tst->host_size += tb->tc.size;
2ac01d6d
EC
1913 tst->target_size += tb->size;
1914 if (tb->size > tst->max_target_size) {
1915 tst->max_target_size = tb->size;
1916 }
1917 if (tb->page_addr[1] != -1) {
1918 tst->cross_page++;
1919 }
1920 if (tb->jmp_reset_offset[0] != TB_JMP_RESET_OFFSET_INVALID) {
1921 tst->direct_jmp_count++;
1922 if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) {
1923 tst->direct_jmp2_count++;
1924 }
1925 }
1926 return false;
1927}
1928
5b6dd868
BS
1929void dump_exec_info(FILE *f, fprintf_function cpu_fprintf)
1930{
2ac01d6d 1931 struct tb_tree_stats tst = {};
329844d4 1932 struct qht_stats hst;
2ac01d6d 1933 size_t nb_tbs;
5b6dd868 1934
a5e99826
FK
1935 tb_lock();
1936
44ded3d0
EC
1937 nb_tbs = g_tree_nnodes(tb_ctx.tb_tree);
1938 g_tree_foreach(tb_ctx.tb_tree, tb_tree_stats_iter, &tst);
5b6dd868
BS
1939 /* XXX: avoid using doubles ? */
1940 cpu_fprintf(f, "Translation buffer state:\n");
f19c6cc6
EC
1941 /*
1942 * Report total code size including the padding and TB structs;
1943 * otherwise users might think "-tb-size" is not honoured.
1944 * For avg host size we use the precise numbers from tb_tree_stats though.
1945 */
5b6dd868 1946 cpu_fprintf(f, "gen code size %td/%zd\n",
b1311c4a
EC
1947 tcg_ctx->code_gen_ptr - tcg_ctx->code_gen_buffer,
1948 tcg_ctx->code_gen_highwater - tcg_ctx->code_gen_buffer);
2ac01d6d
EC
1949 cpu_fprintf(f, "TB count %zu\n", nb_tbs);
1950 cpu_fprintf(f, "TB avg target size %zu max=%zu bytes\n",
1951 nb_tbs ? tst.target_size / nb_tbs : 0,
1952 tst.max_target_size);
f19c6cc6
EC
1953 cpu_fprintf(f, "TB avg host size %zu bytes (expansion ratio: %0.1f)\n",
1954 nb_tbs ? tst.host_size / nb_tbs : 0,
1955 tst.target_size ? (double)tst.host_size / tst.target_size : 0);
2ac01d6d
EC
1956 cpu_fprintf(f, "cross page TB count %zu (%zu%%)\n", tst.cross_page,
1957 nb_tbs ? (tst.cross_page * 100) / nb_tbs : 0);
1958 cpu_fprintf(f, "direct jump count %zu (%zu%%) (2 jumps=%zu %zu%%)\n",
1959 tst.direct_jmp_count,
1960 nb_tbs ? (tst.direct_jmp_count * 100) / nb_tbs : 0,
1961 tst.direct_jmp2_count,
1962 nb_tbs ? (tst.direct_jmp2_count * 100) / nb_tbs : 0);
329844d4 1963
44ded3d0 1964 qht_statistics_init(&tb_ctx.htable, &hst);
7266ae91 1965 print_qht_statistics(f, cpu_fprintf, hst);
329844d4
EC
1966 qht_statistics_destroy(&hst);
1967
5b6dd868 1968 cpu_fprintf(f, "\nStatistics:\n");
3359baad 1969 cpu_fprintf(f, "TB flush count %u\n",
44ded3d0
EC
1970 atomic_read(&tb_ctx.tb_flush_count));
1971 cpu_fprintf(f, "TB invalidate count %d\n", tb_ctx.tb_phys_invalidate_count);
83974cf4 1972 cpu_fprintf(f, "TLB flush count %zu\n", tlb_flush_count());
5b6dd868 1973 tcg_dump_info(f, cpu_fprintf);
a5e99826
FK
1974
1975 tb_unlock();
5b6dd868
BS
1976}
1977
246ae24d
MF
1978void dump_opcount_info(FILE *f, fprintf_function cpu_fprintf)
1979{
1980 tcg_dump_op_count(f, cpu_fprintf);
1981}
1982
5b6dd868
BS
1983#else /* CONFIG_USER_ONLY */
1984
c3affe56 1985void cpu_interrupt(CPUState *cpu, int mask)
5b6dd868 1986{
8d04fb55 1987 g_assert(qemu_mutex_iothread_locked());
259186a7 1988 cpu->interrupt_request |= mask;
1aab16c2 1989 cpu->icount_decr.u16.high = -1;
5b6dd868
BS
1990}
1991
1992/*
1993 * Walks guest process memory "regions" one by one
1994 * and calls callback function 'fn' for each region.
1995 */
1996struct walk_memory_regions_data {
1997 walk_memory_regions_fn fn;
1998 void *priv;
1a1c4db9 1999 target_ulong start;
5b6dd868
BS
2000 int prot;
2001};
2002
2003static int walk_memory_regions_end(struct walk_memory_regions_data *data,
1a1c4db9 2004 target_ulong end, int new_prot)
5b6dd868 2005{
1a1c4db9 2006 if (data->start != -1u) {
5b6dd868
BS
2007 int rc = data->fn(data->priv, data->start, end, data->prot);
2008 if (rc != 0) {
2009 return rc;
2010 }
2011 }
2012
1a1c4db9 2013 data->start = (new_prot ? end : -1u);
5b6dd868
BS
2014 data->prot = new_prot;
2015
2016 return 0;
2017}
2018
2019static int walk_memory_regions_1(struct walk_memory_regions_data *data,
1a1c4db9 2020 target_ulong base, int level, void **lp)
5b6dd868 2021{
1a1c4db9 2022 target_ulong pa;
5b6dd868
BS
2023 int i, rc;
2024
2025 if (*lp == NULL) {
2026 return walk_memory_regions_end(data, base, 0);
2027 }
2028
2029 if (level == 0) {
2030 PageDesc *pd = *lp;
2031
03f49957 2032 for (i = 0; i < V_L2_SIZE; ++i) {
5b6dd868
BS
2033 int prot = pd[i].flags;
2034
2035 pa = base | (i << TARGET_PAGE_BITS);
2036 if (prot != data->prot) {
2037 rc = walk_memory_regions_end(data, pa, prot);
2038 if (rc != 0) {
2039 return rc;
2040 }
2041 }
2042 }
2043 } else {
2044 void **pp = *lp;
2045
03f49957 2046 for (i = 0; i < V_L2_SIZE; ++i) {
1a1c4db9 2047 pa = base | ((target_ulong)i <<
03f49957 2048 (TARGET_PAGE_BITS + V_L2_BITS * level));
5b6dd868
BS
2049 rc = walk_memory_regions_1(data, pa, level - 1, pp + i);
2050 if (rc != 0) {
2051 return rc;
2052 }
2053 }
2054 }
2055
2056 return 0;
2057}
2058
2059int walk_memory_regions(void *priv, walk_memory_regions_fn fn)
2060{
2061 struct walk_memory_regions_data data;
66ec9f49 2062 uintptr_t i, l1_sz = v_l1_size;
5b6dd868
BS
2063
2064 data.fn = fn;
2065 data.priv = priv;
1a1c4db9 2066 data.start = -1u;
5b6dd868
BS
2067 data.prot = 0;
2068
66ec9f49
VK
2069 for (i = 0; i < l1_sz; i++) {
2070 target_ulong base = i << (v_l1_shift + TARGET_PAGE_BITS);
2071 int rc = walk_memory_regions_1(&data, base, v_l2_levels, l1_map + i);
5b6dd868
BS
2072 if (rc != 0) {
2073 return rc;
2074 }
2075 }
2076
2077 return walk_memory_regions_end(&data, 0, 0);
2078}
2079
1a1c4db9
MI
2080static int dump_region(void *priv, target_ulong start,
2081 target_ulong end, unsigned long prot)
5b6dd868
BS
2082{
2083 FILE *f = (FILE *)priv;
2084
1a1c4db9
MI
2085 (void) fprintf(f, TARGET_FMT_lx"-"TARGET_FMT_lx
2086 " "TARGET_FMT_lx" %c%c%c\n",
5b6dd868
BS
2087 start, end, end - start,
2088 ((prot & PAGE_READ) ? 'r' : '-'),
2089 ((prot & PAGE_WRITE) ? 'w' : '-'),
2090 ((prot & PAGE_EXEC) ? 'x' : '-'));
2091
2092 return 0;
2093}
2094
2095/* dump memory mappings */
2096void page_dump(FILE *f)
2097{
1a1c4db9 2098 const int length = sizeof(target_ulong) * 2;
227b8175
SW
2099 (void) fprintf(f, "%-*s %-*s %-*s %s\n",
2100 length, "start", length, "end", length, "size", "prot");
5b6dd868
BS
2101 walk_memory_regions(f, dump_region);
2102}
2103
2104int page_get_flags(target_ulong address)
2105{
2106 PageDesc *p;
2107
2108 p = page_find(address >> TARGET_PAGE_BITS);
2109 if (!p) {
2110 return 0;
2111 }
2112 return p->flags;
2113}
2114
2115/* Modify the flags of a page and invalidate the code if necessary.
2116 The flag PAGE_WRITE_ORG is positioned automatically depending
2117 on PAGE_WRITE. The mmap_lock should already be held. */
2118void page_set_flags(target_ulong start, target_ulong end, int flags)
2119{
2120 target_ulong addr, len;
2121
2122 /* This function should never be called with addresses outside the
2123 guest address space. If this assert fires, it probably indicates
2124 a missing call to h2g_valid. */
2125#if TARGET_ABI_BITS > L1_MAP_ADDR_SPACE_BITS
de258eb0 2126 assert(end <= ((target_ulong)1 << L1_MAP_ADDR_SPACE_BITS));
5b6dd868
BS
2127#endif
2128 assert(start < end);
e505a063 2129 assert_memory_lock();
5b6dd868
BS
2130
2131 start = start & TARGET_PAGE_MASK;
2132 end = TARGET_PAGE_ALIGN(end);
2133
2134 if (flags & PAGE_WRITE) {
2135 flags |= PAGE_WRITE_ORG;
2136 }
2137
2138 for (addr = start, len = end - start;
2139 len != 0;
2140 len -= TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {
2141 PageDesc *p = page_find_alloc(addr >> TARGET_PAGE_BITS, 1);
2142
2143 /* If the write protection bit is set, then we invalidate
2144 the code inside. */
2145 if (!(p->flags & PAGE_WRITE) &&
2146 (flags & PAGE_WRITE) &&
2147 p->first_tb) {
75809229 2148 tb_invalidate_phys_page(addr, 0);
5b6dd868
BS
2149 }
2150 p->flags = flags;
2151 }
2152}
2153
2154int page_check_range(target_ulong start, target_ulong len, int flags)
2155{
2156 PageDesc *p;
2157 target_ulong end;
2158 target_ulong addr;
2159
2160 /* This function should never be called with addresses outside the
2161 guest address space. If this assert fires, it probably indicates
2162 a missing call to h2g_valid. */
2163#if TARGET_ABI_BITS > L1_MAP_ADDR_SPACE_BITS
1a1c4db9 2164 assert(start < ((target_ulong)1 << L1_MAP_ADDR_SPACE_BITS));
5b6dd868
BS
2165#endif
2166
2167 if (len == 0) {
2168 return 0;
2169 }
2170 if (start + len - 1 < start) {
2171 /* We've wrapped around. */
2172 return -1;
2173 }
2174
2175 /* must do before we loose bits in the next step */
2176 end = TARGET_PAGE_ALIGN(start + len);
2177 start = start & TARGET_PAGE_MASK;
2178
2179 for (addr = start, len = end - start;
2180 len != 0;
2181 len -= TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {
2182 p = page_find(addr >> TARGET_PAGE_BITS);
2183 if (!p) {
2184 return -1;
2185 }
2186 if (!(p->flags & PAGE_VALID)) {
2187 return -1;
2188 }
2189
2190 if ((flags & PAGE_READ) && !(p->flags & PAGE_READ)) {
2191 return -1;
2192 }
2193 if (flags & PAGE_WRITE) {
2194 if (!(p->flags & PAGE_WRITE_ORG)) {
2195 return -1;
2196 }
2197 /* unprotect the page if it was put read-only because it
2198 contains translated code */
2199 if (!(p->flags & PAGE_WRITE)) {
f213e72f 2200 if (!page_unprotect(addr, 0)) {
5b6dd868
BS
2201 return -1;
2202 }
2203 }
5b6dd868
BS
2204 }
2205 }
2206 return 0;
2207}
2208
2209/* called from signal handler: invalidate the code and unprotect the
f213e72f
PM
2210 * page. Return 0 if the fault was not handled, 1 if it was handled,
2211 * and 2 if it was handled but the caller must cause the TB to be
2212 * immediately exited. (We can only return 2 if the 'pc' argument is
2213 * non-zero.)
2214 */
2215int page_unprotect(target_ulong address, uintptr_t pc)
5b6dd868
BS
2216{
2217 unsigned int prot;
7399a337 2218 bool current_tb_invalidated;
5b6dd868
BS
2219 PageDesc *p;
2220 target_ulong host_start, host_end, addr;
2221
2222 /* Technically this isn't safe inside a signal handler. However we
2223 know this only ever happens in a synchronous SEGV handler, so in
2224 practice it seems to be ok. */
2225 mmap_lock();
2226
2227 p = page_find(address >> TARGET_PAGE_BITS);
2228 if (!p) {
2229 mmap_unlock();
2230 return 0;
2231 }
2232
2233 /* if the page was really writable, then we change its
2234 protection back to writable */
2235 if ((p->flags & PAGE_WRITE_ORG) && !(p->flags & PAGE_WRITE)) {
2236 host_start = address & qemu_host_page_mask;
2237 host_end = host_start + qemu_host_page_size;
2238
2239 prot = 0;
7399a337 2240 current_tb_invalidated = false;
5b6dd868
BS
2241 for (addr = host_start ; addr < host_end ; addr += TARGET_PAGE_SIZE) {
2242 p = page_find(addr >> TARGET_PAGE_BITS);
2243 p->flags |= PAGE_WRITE;
2244 prot |= p->flags;
2245
2246 /* and since the content will be modified, we must invalidate
2247 the corresponding translated code. */
7399a337 2248 current_tb_invalidated |= tb_invalidate_phys_page(addr, pc);
6eb062ab
EC
2249#ifdef CONFIG_USER_ONLY
2250 if (DEBUG_TB_CHECK_GATE) {
2251 tb_invalidate_check(addr);
2252 }
5b6dd868
BS
2253#endif
2254 }
2255 mprotect((void *)g2h(host_start), qemu_host_page_size,
2256 prot & PAGE_BITS);
2257
2258 mmap_unlock();
7399a337
SS
2259 /* If current TB was invalidated return to main loop */
2260 return current_tb_invalidated ? 2 : 1;
5b6dd868
BS
2261 }
2262 mmap_unlock();
2263 return 0;
2264}
2265#endif /* CONFIG_USER_ONLY */
2cd53943
TH
2266
2267/* This is a wrapper for common code that can not use CONFIG_SOFTMMU */
2268void tcg_flush_softmmu_tlb(CPUState *cs)
2269{
2270#ifdef CONFIG_SOFTMMU
2271 tlb_flush(cs);
2272#endif
2273}