xref: /openbmc/qemu/accel/tcg/cputlb.c (revision 37523ff734721a699d338f918e95b1697cb0880c)
1 /*
2  *  Common CPU TLB handling
3  *
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.1 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
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "qemu/osdep.h"
21 #include "qemu/main-loop.h"
22 #include "hw/core/tcg-cpu-ops.h"
23 #include "exec/exec-all.h"
24 #include "exec/memory.h"
25 #include "exec/cpu_ldst.h"
26 #include "exec/cputlb.h"
27 #include "exec/memory-internal.h"
28 #include "exec/ram_addr.h"
29 #include "tcg/tcg.h"
30 #include "qemu/error-report.h"
31 #include "exec/log.h"
32 #include "exec/helper-proto.h"
33 #include "qemu/atomic.h"
34 #include "qemu/atomic128.h"
35 #include "exec/translate-all.h"
36 #include "trace/trace-root.h"
37 #include "tb-hash.h"
38 #include "internal.h"
39 #ifdef CONFIG_PLUGIN
40 #include "qemu/plugin-memory.h"
41 #endif
42 #include "tcg/tcg-ldst.h"
43 
44 /* DEBUG defines, enable DEBUG_TLB_LOG to log to the CPU_LOG_MMU target */
45 /* #define DEBUG_TLB */
46 /* #define DEBUG_TLB_LOG */
47 
48 #ifdef DEBUG_TLB
49 # define DEBUG_TLB_GATE 1
50 # ifdef DEBUG_TLB_LOG
51 #  define DEBUG_TLB_LOG_GATE 1
52 # else
53 #  define DEBUG_TLB_LOG_GATE 0
54 # endif
55 #else
56 # define DEBUG_TLB_GATE 0
57 # define DEBUG_TLB_LOG_GATE 0
58 #endif
59 
60 #define tlb_debug(fmt, ...) do { \
61     if (DEBUG_TLB_LOG_GATE) { \
62         qemu_log_mask(CPU_LOG_MMU, "%s: " fmt, __func__, \
63                       ## __VA_ARGS__); \
64     } else if (DEBUG_TLB_GATE) { \
65         fprintf(stderr, "%s: " fmt, __func__, ## __VA_ARGS__); \
66     } \
67 } while (0)
68 
69 #define assert_cpu_is_self(cpu) do {                              \
70         if (DEBUG_TLB_GATE) {                                     \
71             g_assert(!(cpu)->created || qemu_cpu_is_self(cpu));   \
72         }                                                         \
73     } while (0)
74 
75 /* run_on_cpu_data.target_ptr should always be big enough for a
76  * target_ulong even on 32 bit builds */
77 QEMU_BUILD_BUG_ON(sizeof(target_ulong) > sizeof(run_on_cpu_data));
78 
79 /* We currently can't handle more than 16 bits in the MMUIDX bitmask.
80  */
81 QEMU_BUILD_BUG_ON(NB_MMU_MODES > 16);
82 #define ALL_MMUIDX_BITS ((1 << NB_MMU_MODES) - 1)
83 
84 static inline size_t tlb_n_entries(CPUTLBDescFast *fast)
85 {
86     return (fast->mask >> CPU_TLB_ENTRY_BITS) + 1;
87 }
88 
89 static inline size_t sizeof_tlb(CPUTLBDescFast *fast)
90 {
91     return fast->mask + (1 << CPU_TLB_ENTRY_BITS);
92 }
93 
94 static void tlb_window_reset(CPUTLBDesc *desc, int64_t ns,
95                              size_t max_entries)
96 {
97     desc->window_begin_ns = ns;
98     desc->window_max_entries = max_entries;
99 }
100 
101 static void tb_jmp_cache_clear_page(CPUState *cpu, target_ulong page_addr)
102 {
103     unsigned int i, i0 = tb_jmp_cache_hash_page(page_addr);
104 
105     for (i = 0; i < TB_JMP_PAGE_SIZE; i++) {
106         qatomic_set(&cpu->tb_jmp_cache[i0 + i], NULL);
107     }
108 }
109 
110 static void tb_flush_jmp_cache(CPUState *cpu, target_ulong addr)
111 {
112     /* Discard jump cache entries for any tb which might potentially
113        overlap the flushed page.  */
114     tb_jmp_cache_clear_page(cpu, addr - TARGET_PAGE_SIZE);
115     tb_jmp_cache_clear_page(cpu, addr);
116 }
117 
118 /**
119  * tlb_mmu_resize_locked() - perform TLB resize bookkeeping; resize if necessary
120  * @desc: The CPUTLBDesc portion of the TLB
121  * @fast: The CPUTLBDescFast portion of the same TLB
122  *
123  * Called with tlb_lock_held.
124  *
125  * We have two main constraints when resizing a TLB: (1) we only resize it
126  * on a TLB flush (otherwise we'd have to take a perf hit by either rehashing
127  * the array or unnecessarily flushing it), which means we do not control how
128  * frequently the resizing can occur; (2) we don't have access to the guest's
129  * future scheduling decisions, and therefore have to decide the magnitude of
130  * the resize based on past observations.
131  *
132  * In general, a memory-hungry process can benefit greatly from an appropriately
133  * sized TLB, since a guest TLB miss is very expensive. This doesn't mean that
134  * we just have to make the TLB as large as possible; while an oversized TLB
135  * results in minimal TLB miss rates, it also takes longer to be flushed
136  * (flushes can be _very_ frequent), and the reduced locality can also hurt
137  * performance.
138  *
139  * To achieve near-optimal performance for all kinds of workloads, we:
140  *
141  * 1. Aggressively increase the size of the TLB when the use rate of the
142  * TLB being flushed is high, since it is likely that in the near future this
143  * memory-hungry process will execute again, and its memory hungriness will
144  * probably be similar.
145  *
146  * 2. Slowly reduce the size of the TLB as the use rate declines over a
147  * reasonably large time window. The rationale is that if in such a time window
148  * we have not observed a high TLB use rate, it is likely that we won't observe
149  * it in the near future. In that case, once a time window expires we downsize
150  * the TLB to match the maximum use rate observed in the window.
151  *
152  * 3. Try to keep the maximum use rate in a time window in the 30-70% range,
153  * since in that range performance is likely near-optimal. Recall that the TLB
154  * is direct mapped, so we want the use rate to be low (or at least not too
155  * high), since otherwise we are likely to have a significant amount of
156  * conflict misses.
157  */
158 static void tlb_mmu_resize_locked(CPUTLBDesc *desc, CPUTLBDescFast *fast,
159                                   int64_t now)
160 {
161     size_t old_size = tlb_n_entries(fast);
162     size_t rate;
163     size_t new_size = old_size;
164     int64_t window_len_ms = 100;
165     int64_t window_len_ns = window_len_ms * 1000 * 1000;
166     bool window_expired = now > desc->window_begin_ns + window_len_ns;
167 
168     if (desc->n_used_entries > desc->window_max_entries) {
169         desc->window_max_entries = desc->n_used_entries;
170     }
171     rate = desc->window_max_entries * 100 / old_size;
172 
173     if (rate > 70) {
174         new_size = MIN(old_size << 1, 1 << CPU_TLB_DYN_MAX_BITS);
175     } else if (rate < 30 && window_expired) {
176         size_t ceil = pow2ceil(desc->window_max_entries);
177         size_t expected_rate = desc->window_max_entries * 100 / ceil;
178 
179         /*
180          * Avoid undersizing when the max number of entries seen is just below
181          * a pow2. For instance, if max_entries == 1025, the expected use rate
182          * would be 1025/2048==50%. However, if max_entries == 1023, we'd get
183          * 1023/1024==99.9% use rate, so we'd likely end up doubling the size
184          * later. Thus, make sure that the expected use rate remains below 70%.
185          * (and since we double the size, that means the lowest rate we'd
186          * expect to get is 35%, which is still in the 30-70% range where
187          * we consider that the size is appropriate.)
188          */
189         if (expected_rate > 70) {
190             ceil *= 2;
191         }
192         new_size = MAX(ceil, 1 << CPU_TLB_DYN_MIN_BITS);
193     }
194 
195     if (new_size == old_size) {
196         if (window_expired) {
197             tlb_window_reset(desc, now, desc->n_used_entries);
198         }
199         return;
200     }
201 
202     g_free(fast->table);
203     g_free(desc->fulltlb);
204 
205     tlb_window_reset(desc, now, 0);
206     /* desc->n_used_entries is cleared by the caller */
207     fast->mask = (new_size - 1) << CPU_TLB_ENTRY_BITS;
208     fast->table = g_try_new(CPUTLBEntry, new_size);
209     desc->fulltlb = g_try_new(CPUTLBEntryFull, new_size);
210 
211     /*
212      * If the allocations fail, try smaller sizes. We just freed some
213      * memory, so going back to half of new_size has a good chance of working.
214      * Increased memory pressure elsewhere in the system might cause the
215      * allocations to fail though, so we progressively reduce the allocation
216      * size, aborting if we cannot even allocate the smallest TLB we support.
217      */
218     while (fast->table == NULL || desc->fulltlb == NULL) {
219         if (new_size == (1 << CPU_TLB_DYN_MIN_BITS)) {
220             error_report("%s: %s", __func__, strerror(errno));
221             abort();
222         }
223         new_size = MAX(new_size >> 1, 1 << CPU_TLB_DYN_MIN_BITS);
224         fast->mask = (new_size - 1) << CPU_TLB_ENTRY_BITS;
225 
226         g_free(fast->table);
227         g_free(desc->fulltlb);
228         fast->table = g_try_new(CPUTLBEntry, new_size);
229         desc->fulltlb = g_try_new(CPUTLBEntryFull, new_size);
230     }
231 }
232 
233 static void tlb_mmu_flush_locked(CPUTLBDesc *desc, CPUTLBDescFast *fast)
234 {
235     desc->n_used_entries = 0;
236     desc->large_page_addr = -1;
237     desc->large_page_mask = -1;
238     desc->vindex = 0;
239     memset(fast->table, -1, sizeof_tlb(fast));
240     memset(desc->vtable, -1, sizeof(desc->vtable));
241 }
242 
243 static void tlb_flush_one_mmuidx_locked(CPUArchState *env, int mmu_idx,
244                                         int64_t now)
245 {
246     CPUTLBDesc *desc = &env_tlb(env)->d[mmu_idx];
247     CPUTLBDescFast *fast = &env_tlb(env)->f[mmu_idx];
248 
249     tlb_mmu_resize_locked(desc, fast, now);
250     tlb_mmu_flush_locked(desc, fast);
251 }
252 
253 static void tlb_mmu_init(CPUTLBDesc *desc, CPUTLBDescFast *fast, int64_t now)
254 {
255     size_t n_entries = 1 << CPU_TLB_DYN_DEFAULT_BITS;
256 
257     tlb_window_reset(desc, now, 0);
258     desc->n_used_entries = 0;
259     fast->mask = (n_entries - 1) << CPU_TLB_ENTRY_BITS;
260     fast->table = g_new(CPUTLBEntry, n_entries);
261     desc->fulltlb = g_new(CPUTLBEntryFull, n_entries);
262     tlb_mmu_flush_locked(desc, fast);
263 }
264 
265 static inline void tlb_n_used_entries_inc(CPUArchState *env, uintptr_t mmu_idx)
266 {
267     env_tlb(env)->d[mmu_idx].n_used_entries++;
268 }
269 
270 static inline void tlb_n_used_entries_dec(CPUArchState *env, uintptr_t mmu_idx)
271 {
272     env_tlb(env)->d[mmu_idx].n_used_entries--;
273 }
274 
275 void tlb_init(CPUState *cpu)
276 {
277     CPUArchState *env = cpu->env_ptr;
278     int64_t now = get_clock_realtime();
279     int i;
280 
281     qemu_spin_init(&env_tlb(env)->c.lock);
282 
283     /* All tlbs are initialized flushed. */
284     env_tlb(env)->c.dirty = 0;
285 
286     for (i = 0; i < NB_MMU_MODES; i++) {
287         tlb_mmu_init(&env_tlb(env)->d[i], &env_tlb(env)->f[i], now);
288     }
289 }
290 
291 void tlb_destroy(CPUState *cpu)
292 {
293     CPUArchState *env = cpu->env_ptr;
294     int i;
295 
296     qemu_spin_destroy(&env_tlb(env)->c.lock);
297     for (i = 0; i < NB_MMU_MODES; i++) {
298         CPUTLBDesc *desc = &env_tlb(env)->d[i];
299         CPUTLBDescFast *fast = &env_tlb(env)->f[i];
300 
301         g_free(fast->table);
302         g_free(desc->fulltlb);
303     }
304 }
305 
306 /* flush_all_helper: run fn across all cpus
307  *
308  * If the wait flag is set then the src cpu's helper will be queued as
309  * "safe" work and the loop exited creating a synchronisation point
310  * where all queued work will be finished before execution starts
311  * again.
312  */
313 static void flush_all_helper(CPUState *src, run_on_cpu_func fn,
314                              run_on_cpu_data d)
315 {
316     CPUState *cpu;
317 
318     CPU_FOREACH(cpu) {
319         if (cpu != src) {
320             async_run_on_cpu(cpu, fn, d);
321         }
322     }
323 }
324 
325 void tlb_flush_counts(size_t *pfull, size_t *ppart, size_t *pelide)
326 {
327     CPUState *cpu;
328     size_t full = 0, part = 0, elide = 0;
329 
330     CPU_FOREACH(cpu) {
331         CPUArchState *env = cpu->env_ptr;
332 
333         full += qatomic_read(&env_tlb(env)->c.full_flush_count);
334         part += qatomic_read(&env_tlb(env)->c.part_flush_count);
335         elide += qatomic_read(&env_tlb(env)->c.elide_flush_count);
336     }
337     *pfull = full;
338     *ppart = part;
339     *pelide = elide;
340 }
341 
342 static void tlb_flush_by_mmuidx_async_work(CPUState *cpu, run_on_cpu_data data)
343 {
344     CPUArchState *env = cpu->env_ptr;
345     uint16_t asked = data.host_int;
346     uint16_t all_dirty, work, to_clean;
347     int64_t now = get_clock_realtime();
348 
349     assert_cpu_is_self(cpu);
350 
351     tlb_debug("mmu_idx:0x%04" PRIx16 "\n", asked);
352 
353     qemu_spin_lock(&env_tlb(env)->c.lock);
354 
355     all_dirty = env_tlb(env)->c.dirty;
356     to_clean = asked & all_dirty;
357     all_dirty &= ~to_clean;
358     env_tlb(env)->c.dirty = all_dirty;
359 
360     for (work = to_clean; work != 0; work &= work - 1) {
361         int mmu_idx = ctz32(work);
362         tlb_flush_one_mmuidx_locked(env, mmu_idx, now);
363     }
364 
365     qemu_spin_unlock(&env_tlb(env)->c.lock);
366 
367     cpu_tb_jmp_cache_clear(cpu);
368 
369     if (to_clean == ALL_MMUIDX_BITS) {
370         qatomic_set(&env_tlb(env)->c.full_flush_count,
371                    env_tlb(env)->c.full_flush_count + 1);
372     } else {
373         qatomic_set(&env_tlb(env)->c.part_flush_count,
374                    env_tlb(env)->c.part_flush_count + ctpop16(to_clean));
375         if (to_clean != asked) {
376             qatomic_set(&env_tlb(env)->c.elide_flush_count,
377                        env_tlb(env)->c.elide_flush_count +
378                        ctpop16(asked & ~to_clean));
379         }
380     }
381 }
382 
383 void tlb_flush_by_mmuidx(CPUState *cpu, uint16_t idxmap)
384 {
385     tlb_debug("mmu_idx: 0x%" PRIx16 "\n", idxmap);
386 
387     if (cpu->created && !qemu_cpu_is_self(cpu)) {
388         async_run_on_cpu(cpu, tlb_flush_by_mmuidx_async_work,
389                          RUN_ON_CPU_HOST_INT(idxmap));
390     } else {
391         tlb_flush_by_mmuidx_async_work(cpu, RUN_ON_CPU_HOST_INT(idxmap));
392     }
393 }
394 
395 void tlb_flush(CPUState *cpu)
396 {
397     tlb_flush_by_mmuidx(cpu, ALL_MMUIDX_BITS);
398 }
399 
400 void tlb_flush_by_mmuidx_all_cpus(CPUState *src_cpu, uint16_t idxmap)
401 {
402     const run_on_cpu_func fn = tlb_flush_by_mmuidx_async_work;
403 
404     tlb_debug("mmu_idx: 0x%"PRIx16"\n", idxmap);
405 
406     flush_all_helper(src_cpu, fn, RUN_ON_CPU_HOST_INT(idxmap));
407     fn(src_cpu, RUN_ON_CPU_HOST_INT(idxmap));
408 }
409 
410 void tlb_flush_all_cpus(CPUState *src_cpu)
411 {
412     tlb_flush_by_mmuidx_all_cpus(src_cpu, ALL_MMUIDX_BITS);
413 }
414 
415 void tlb_flush_by_mmuidx_all_cpus_synced(CPUState *src_cpu, uint16_t idxmap)
416 {
417     const run_on_cpu_func fn = tlb_flush_by_mmuidx_async_work;
418 
419     tlb_debug("mmu_idx: 0x%"PRIx16"\n", idxmap);
420 
421     flush_all_helper(src_cpu, fn, RUN_ON_CPU_HOST_INT(idxmap));
422     async_safe_run_on_cpu(src_cpu, fn, RUN_ON_CPU_HOST_INT(idxmap));
423 }
424 
425 void tlb_flush_all_cpus_synced(CPUState *src_cpu)
426 {
427     tlb_flush_by_mmuidx_all_cpus_synced(src_cpu, ALL_MMUIDX_BITS);
428 }
429 
430 static bool tlb_hit_page_mask_anyprot(CPUTLBEntry *tlb_entry,
431                                       target_ulong page, target_ulong mask)
432 {
433     page &= mask;
434     mask &= TARGET_PAGE_MASK | TLB_INVALID_MASK;
435 
436     return (page == (tlb_entry->addr_read & mask) ||
437             page == (tlb_addr_write(tlb_entry) & mask) ||
438             page == (tlb_entry->addr_code & mask));
439 }
440 
441 static inline bool tlb_hit_page_anyprot(CPUTLBEntry *tlb_entry,
442                                         target_ulong page)
443 {
444     return tlb_hit_page_mask_anyprot(tlb_entry, page, -1);
445 }
446 
447 /**
448  * tlb_entry_is_empty - return true if the entry is not in use
449  * @te: pointer to CPUTLBEntry
450  */
451 static inline bool tlb_entry_is_empty(const CPUTLBEntry *te)
452 {
453     return te->addr_read == -1 && te->addr_write == -1 && te->addr_code == -1;
454 }
455 
456 /* Called with tlb_c.lock held */
457 static bool tlb_flush_entry_mask_locked(CPUTLBEntry *tlb_entry,
458                                         target_ulong page,
459                                         target_ulong mask)
460 {
461     if (tlb_hit_page_mask_anyprot(tlb_entry, page, mask)) {
462         memset(tlb_entry, -1, sizeof(*tlb_entry));
463         return true;
464     }
465     return false;
466 }
467 
468 static inline bool tlb_flush_entry_locked(CPUTLBEntry *tlb_entry,
469                                           target_ulong page)
470 {
471     return tlb_flush_entry_mask_locked(tlb_entry, page, -1);
472 }
473 
474 /* Called with tlb_c.lock held */
475 static void tlb_flush_vtlb_page_mask_locked(CPUArchState *env, int mmu_idx,
476                                             target_ulong page,
477                                             target_ulong mask)
478 {
479     CPUTLBDesc *d = &env_tlb(env)->d[mmu_idx];
480     int k;
481 
482     assert_cpu_is_self(env_cpu(env));
483     for (k = 0; k < CPU_VTLB_SIZE; k++) {
484         if (tlb_flush_entry_mask_locked(&d->vtable[k], page, mask)) {
485             tlb_n_used_entries_dec(env, mmu_idx);
486         }
487     }
488 }
489 
490 static inline void tlb_flush_vtlb_page_locked(CPUArchState *env, int mmu_idx,
491                                               target_ulong page)
492 {
493     tlb_flush_vtlb_page_mask_locked(env, mmu_idx, page, -1);
494 }
495 
496 static void tlb_flush_page_locked(CPUArchState *env, int midx,
497                                   target_ulong page)
498 {
499     target_ulong lp_addr = env_tlb(env)->d[midx].large_page_addr;
500     target_ulong lp_mask = env_tlb(env)->d[midx].large_page_mask;
501 
502     /* Check if we need to flush due to large pages.  */
503     if ((page & lp_mask) == lp_addr) {
504         tlb_debug("forcing full flush midx %d ("
505                   TARGET_FMT_lx "/" TARGET_FMT_lx ")\n",
506                   midx, lp_addr, lp_mask);
507         tlb_flush_one_mmuidx_locked(env, midx, get_clock_realtime());
508     } else {
509         if (tlb_flush_entry_locked(tlb_entry(env, midx, page), page)) {
510             tlb_n_used_entries_dec(env, midx);
511         }
512         tlb_flush_vtlb_page_locked(env, midx, page);
513     }
514 }
515 
516 /**
517  * tlb_flush_page_by_mmuidx_async_0:
518  * @cpu: cpu on which to flush
519  * @addr: page of virtual address to flush
520  * @idxmap: set of mmu_idx to flush
521  *
522  * Helper for tlb_flush_page_by_mmuidx and friends, flush one page
523  * at @addr from the tlbs indicated by @idxmap from @cpu.
524  */
525 static void tlb_flush_page_by_mmuidx_async_0(CPUState *cpu,
526                                              target_ulong addr,
527                                              uint16_t idxmap)
528 {
529     CPUArchState *env = cpu->env_ptr;
530     int mmu_idx;
531 
532     assert_cpu_is_self(cpu);
533 
534     tlb_debug("page addr:" TARGET_FMT_lx " mmu_map:0x%x\n", addr, idxmap);
535 
536     qemu_spin_lock(&env_tlb(env)->c.lock);
537     for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
538         if ((idxmap >> mmu_idx) & 1) {
539             tlb_flush_page_locked(env, mmu_idx, addr);
540         }
541     }
542     qemu_spin_unlock(&env_tlb(env)->c.lock);
543 
544     tb_flush_jmp_cache(cpu, addr);
545 }
546 
547 /**
548  * tlb_flush_page_by_mmuidx_async_1:
549  * @cpu: cpu on which to flush
550  * @data: encoded addr + idxmap
551  *
552  * Helper for tlb_flush_page_by_mmuidx and friends, called through
553  * async_run_on_cpu.  The idxmap parameter is encoded in the page
554  * offset of the target_ptr field.  This limits the set of mmu_idx
555  * that can be passed via this method.
556  */
557 static void tlb_flush_page_by_mmuidx_async_1(CPUState *cpu,
558                                              run_on_cpu_data data)
559 {
560     target_ulong addr_and_idxmap = (target_ulong) data.target_ptr;
561     target_ulong addr = addr_and_idxmap & TARGET_PAGE_MASK;
562     uint16_t idxmap = addr_and_idxmap & ~TARGET_PAGE_MASK;
563 
564     tlb_flush_page_by_mmuidx_async_0(cpu, addr, idxmap);
565 }
566 
567 typedef struct {
568     target_ulong addr;
569     uint16_t idxmap;
570 } TLBFlushPageByMMUIdxData;
571 
572 /**
573  * tlb_flush_page_by_mmuidx_async_2:
574  * @cpu: cpu on which to flush
575  * @data: allocated addr + idxmap
576  *
577  * Helper for tlb_flush_page_by_mmuidx and friends, called through
578  * async_run_on_cpu.  The addr+idxmap parameters are stored in a
579  * TLBFlushPageByMMUIdxData structure that has been allocated
580  * specifically for this helper.  Free the structure when done.
581  */
582 static void tlb_flush_page_by_mmuidx_async_2(CPUState *cpu,
583                                              run_on_cpu_data data)
584 {
585     TLBFlushPageByMMUIdxData *d = data.host_ptr;
586 
587     tlb_flush_page_by_mmuidx_async_0(cpu, d->addr, d->idxmap);
588     g_free(d);
589 }
590 
591 void tlb_flush_page_by_mmuidx(CPUState *cpu, target_ulong addr, uint16_t idxmap)
592 {
593     tlb_debug("addr: "TARGET_FMT_lx" mmu_idx:%" PRIx16 "\n", addr, idxmap);
594 
595     /* This should already be page aligned */
596     addr &= TARGET_PAGE_MASK;
597 
598     if (qemu_cpu_is_self(cpu)) {
599         tlb_flush_page_by_mmuidx_async_0(cpu, addr, idxmap);
600     } else if (idxmap < TARGET_PAGE_SIZE) {
601         /*
602          * Most targets have only a few mmu_idx.  In the case where
603          * we can stuff idxmap into the low TARGET_PAGE_BITS, avoid
604          * allocating memory for this operation.
605          */
606         async_run_on_cpu(cpu, tlb_flush_page_by_mmuidx_async_1,
607                          RUN_ON_CPU_TARGET_PTR(addr | idxmap));
608     } else {
609         TLBFlushPageByMMUIdxData *d = g_new(TLBFlushPageByMMUIdxData, 1);
610 
611         /* Otherwise allocate a structure, freed by the worker.  */
612         d->addr = addr;
613         d->idxmap = idxmap;
614         async_run_on_cpu(cpu, tlb_flush_page_by_mmuidx_async_2,
615                          RUN_ON_CPU_HOST_PTR(d));
616     }
617 }
618 
619 void tlb_flush_page(CPUState *cpu, target_ulong addr)
620 {
621     tlb_flush_page_by_mmuidx(cpu, addr, ALL_MMUIDX_BITS);
622 }
623 
624 void tlb_flush_page_by_mmuidx_all_cpus(CPUState *src_cpu, target_ulong addr,
625                                        uint16_t idxmap)
626 {
627     tlb_debug("addr: "TARGET_FMT_lx" mmu_idx:%"PRIx16"\n", addr, idxmap);
628 
629     /* This should already be page aligned */
630     addr &= TARGET_PAGE_MASK;
631 
632     /*
633      * Allocate memory to hold addr+idxmap only when needed.
634      * See tlb_flush_page_by_mmuidx for details.
635      */
636     if (idxmap < TARGET_PAGE_SIZE) {
637         flush_all_helper(src_cpu, tlb_flush_page_by_mmuidx_async_1,
638                          RUN_ON_CPU_TARGET_PTR(addr | idxmap));
639     } else {
640         CPUState *dst_cpu;
641 
642         /* Allocate a separate data block for each destination cpu.  */
643         CPU_FOREACH(dst_cpu) {
644             if (dst_cpu != src_cpu) {
645                 TLBFlushPageByMMUIdxData *d
646                     = g_new(TLBFlushPageByMMUIdxData, 1);
647 
648                 d->addr = addr;
649                 d->idxmap = idxmap;
650                 async_run_on_cpu(dst_cpu, tlb_flush_page_by_mmuidx_async_2,
651                                  RUN_ON_CPU_HOST_PTR(d));
652             }
653         }
654     }
655 
656     tlb_flush_page_by_mmuidx_async_0(src_cpu, addr, idxmap);
657 }
658 
659 void tlb_flush_page_all_cpus(CPUState *src, target_ulong addr)
660 {
661     tlb_flush_page_by_mmuidx_all_cpus(src, addr, ALL_MMUIDX_BITS);
662 }
663 
664 void tlb_flush_page_by_mmuidx_all_cpus_synced(CPUState *src_cpu,
665                                               target_ulong addr,
666                                               uint16_t idxmap)
667 {
668     tlb_debug("addr: "TARGET_FMT_lx" mmu_idx:%"PRIx16"\n", addr, idxmap);
669 
670     /* This should already be page aligned */
671     addr &= TARGET_PAGE_MASK;
672 
673     /*
674      * Allocate memory to hold addr+idxmap only when needed.
675      * See tlb_flush_page_by_mmuidx for details.
676      */
677     if (idxmap < TARGET_PAGE_SIZE) {
678         flush_all_helper(src_cpu, tlb_flush_page_by_mmuidx_async_1,
679                          RUN_ON_CPU_TARGET_PTR(addr | idxmap));
680         async_safe_run_on_cpu(src_cpu, tlb_flush_page_by_mmuidx_async_1,
681                               RUN_ON_CPU_TARGET_PTR(addr | idxmap));
682     } else {
683         CPUState *dst_cpu;
684         TLBFlushPageByMMUIdxData *d;
685 
686         /* Allocate a separate data block for each destination cpu.  */
687         CPU_FOREACH(dst_cpu) {
688             if (dst_cpu != src_cpu) {
689                 d = g_new(TLBFlushPageByMMUIdxData, 1);
690                 d->addr = addr;
691                 d->idxmap = idxmap;
692                 async_run_on_cpu(dst_cpu, tlb_flush_page_by_mmuidx_async_2,
693                                  RUN_ON_CPU_HOST_PTR(d));
694             }
695         }
696 
697         d = g_new(TLBFlushPageByMMUIdxData, 1);
698         d->addr = addr;
699         d->idxmap = idxmap;
700         async_safe_run_on_cpu(src_cpu, tlb_flush_page_by_mmuidx_async_2,
701                               RUN_ON_CPU_HOST_PTR(d));
702     }
703 }
704 
705 void tlb_flush_page_all_cpus_synced(CPUState *src, target_ulong addr)
706 {
707     tlb_flush_page_by_mmuidx_all_cpus_synced(src, addr, ALL_MMUIDX_BITS);
708 }
709 
710 static void tlb_flush_range_locked(CPUArchState *env, int midx,
711                                    target_ulong addr, target_ulong len,
712                                    unsigned bits)
713 {
714     CPUTLBDesc *d = &env_tlb(env)->d[midx];
715     CPUTLBDescFast *f = &env_tlb(env)->f[midx];
716     target_ulong mask = MAKE_64BIT_MASK(0, bits);
717 
718     /*
719      * If @bits is smaller than the tlb size, there may be multiple entries
720      * within the TLB; otherwise all addresses that match under @mask hit
721      * the same TLB entry.
722      * TODO: Perhaps allow bits to be a few bits less than the size.
723      * For now, just flush the entire TLB.
724      *
725      * If @len is larger than the tlb size, then it will take longer to
726      * test all of the entries in the TLB than it will to flush it all.
727      */
728     if (mask < f->mask || len > f->mask) {
729         tlb_debug("forcing full flush midx %d ("
730                   TARGET_FMT_lx "/" TARGET_FMT_lx "+" TARGET_FMT_lx ")\n",
731                   midx, addr, mask, len);
732         tlb_flush_one_mmuidx_locked(env, midx, get_clock_realtime());
733         return;
734     }
735 
736     /*
737      * Check if we need to flush due to large pages.
738      * Because large_page_mask contains all 1's from the msb,
739      * we only need to test the end of the range.
740      */
741     if (((addr + len - 1) & d->large_page_mask) == d->large_page_addr) {
742         tlb_debug("forcing full flush midx %d ("
743                   TARGET_FMT_lx "/" TARGET_FMT_lx ")\n",
744                   midx, d->large_page_addr, d->large_page_mask);
745         tlb_flush_one_mmuidx_locked(env, midx, get_clock_realtime());
746         return;
747     }
748 
749     for (target_ulong i = 0; i < len; i += TARGET_PAGE_SIZE) {
750         target_ulong page = addr + i;
751         CPUTLBEntry *entry = tlb_entry(env, midx, page);
752 
753         if (tlb_flush_entry_mask_locked(entry, page, mask)) {
754             tlb_n_used_entries_dec(env, midx);
755         }
756         tlb_flush_vtlb_page_mask_locked(env, midx, page, mask);
757     }
758 }
759 
760 typedef struct {
761     target_ulong addr;
762     target_ulong len;
763     uint16_t idxmap;
764     uint16_t bits;
765 } TLBFlushRangeData;
766 
767 static void tlb_flush_range_by_mmuidx_async_0(CPUState *cpu,
768                                               TLBFlushRangeData d)
769 {
770     CPUArchState *env = cpu->env_ptr;
771     int mmu_idx;
772 
773     assert_cpu_is_self(cpu);
774 
775     tlb_debug("range:" TARGET_FMT_lx "/%u+" TARGET_FMT_lx " mmu_map:0x%x\n",
776               d.addr, d.bits, d.len, d.idxmap);
777 
778     qemu_spin_lock(&env_tlb(env)->c.lock);
779     for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
780         if ((d.idxmap >> mmu_idx) & 1) {
781             tlb_flush_range_locked(env, mmu_idx, d.addr, d.len, d.bits);
782         }
783     }
784     qemu_spin_unlock(&env_tlb(env)->c.lock);
785 
786     /*
787      * If the length is larger than the jump cache size, then it will take
788      * longer to clear each entry individually than it will to clear it all.
789      */
790     if (d.len >= (TARGET_PAGE_SIZE * TB_JMP_CACHE_SIZE)) {
791         cpu_tb_jmp_cache_clear(cpu);
792         return;
793     }
794 
795     for (target_ulong i = 0; i < d.len; i += TARGET_PAGE_SIZE) {
796         tb_flush_jmp_cache(cpu, d.addr + i);
797     }
798 }
799 
800 static void tlb_flush_range_by_mmuidx_async_1(CPUState *cpu,
801                                               run_on_cpu_data data)
802 {
803     TLBFlushRangeData *d = data.host_ptr;
804     tlb_flush_range_by_mmuidx_async_0(cpu, *d);
805     g_free(d);
806 }
807 
808 void tlb_flush_range_by_mmuidx(CPUState *cpu, target_ulong addr,
809                                target_ulong len, uint16_t idxmap,
810                                unsigned bits)
811 {
812     TLBFlushRangeData d;
813 
814     /*
815      * If all bits are significant, and len is small,
816      * this devolves to tlb_flush_page.
817      */
818     if (bits >= TARGET_LONG_BITS && len <= TARGET_PAGE_SIZE) {
819         tlb_flush_page_by_mmuidx(cpu, addr, idxmap);
820         return;
821     }
822     /* If no page bits are significant, this devolves to tlb_flush. */
823     if (bits < TARGET_PAGE_BITS) {
824         tlb_flush_by_mmuidx(cpu, idxmap);
825         return;
826     }
827 
828     /* This should already be page aligned */
829     d.addr = addr & TARGET_PAGE_MASK;
830     d.len = len;
831     d.idxmap = idxmap;
832     d.bits = bits;
833 
834     if (qemu_cpu_is_self(cpu)) {
835         tlb_flush_range_by_mmuidx_async_0(cpu, d);
836     } else {
837         /* Otherwise allocate a structure, freed by the worker.  */
838         TLBFlushRangeData *p = g_memdup(&d, sizeof(d));
839         async_run_on_cpu(cpu, tlb_flush_range_by_mmuidx_async_1,
840                          RUN_ON_CPU_HOST_PTR(p));
841     }
842 }
843 
844 void tlb_flush_page_bits_by_mmuidx(CPUState *cpu, target_ulong addr,
845                                    uint16_t idxmap, unsigned bits)
846 {
847     tlb_flush_range_by_mmuidx(cpu, addr, TARGET_PAGE_SIZE, idxmap, bits);
848 }
849 
850 void tlb_flush_range_by_mmuidx_all_cpus(CPUState *src_cpu,
851                                         target_ulong addr, target_ulong len,
852                                         uint16_t idxmap, unsigned bits)
853 {
854     TLBFlushRangeData d;
855     CPUState *dst_cpu;
856 
857     /*
858      * If all bits are significant, and len is small,
859      * this devolves to tlb_flush_page.
860      */
861     if (bits >= TARGET_LONG_BITS && len <= TARGET_PAGE_SIZE) {
862         tlb_flush_page_by_mmuidx_all_cpus(src_cpu, addr, idxmap);
863         return;
864     }
865     /* If no page bits are significant, this devolves to tlb_flush. */
866     if (bits < TARGET_PAGE_BITS) {
867         tlb_flush_by_mmuidx_all_cpus(src_cpu, idxmap);
868         return;
869     }
870 
871     /* This should already be page aligned */
872     d.addr = addr & TARGET_PAGE_MASK;
873     d.len = len;
874     d.idxmap = idxmap;
875     d.bits = bits;
876 
877     /* Allocate a separate data block for each destination cpu.  */
878     CPU_FOREACH(dst_cpu) {
879         if (dst_cpu != src_cpu) {
880             TLBFlushRangeData *p = g_memdup(&d, sizeof(d));
881             async_run_on_cpu(dst_cpu,
882                              tlb_flush_range_by_mmuidx_async_1,
883                              RUN_ON_CPU_HOST_PTR(p));
884         }
885     }
886 
887     tlb_flush_range_by_mmuidx_async_0(src_cpu, d);
888 }
889 
890 void tlb_flush_page_bits_by_mmuidx_all_cpus(CPUState *src_cpu,
891                                             target_ulong addr,
892                                             uint16_t idxmap, unsigned bits)
893 {
894     tlb_flush_range_by_mmuidx_all_cpus(src_cpu, addr, TARGET_PAGE_SIZE,
895                                        idxmap, bits);
896 }
897 
898 void tlb_flush_range_by_mmuidx_all_cpus_synced(CPUState *src_cpu,
899                                                target_ulong addr,
900                                                target_ulong len,
901                                                uint16_t idxmap,
902                                                unsigned bits)
903 {
904     TLBFlushRangeData d, *p;
905     CPUState *dst_cpu;
906 
907     /*
908      * If all bits are significant, and len is small,
909      * this devolves to tlb_flush_page.
910      */
911     if (bits >= TARGET_LONG_BITS && len <= TARGET_PAGE_SIZE) {
912         tlb_flush_page_by_mmuidx_all_cpus_synced(src_cpu, addr, idxmap);
913         return;
914     }
915     /* If no page bits are significant, this devolves to tlb_flush. */
916     if (bits < TARGET_PAGE_BITS) {
917         tlb_flush_by_mmuidx_all_cpus_synced(src_cpu, idxmap);
918         return;
919     }
920 
921     /* This should already be page aligned */
922     d.addr = addr & TARGET_PAGE_MASK;
923     d.len = len;
924     d.idxmap = idxmap;
925     d.bits = bits;
926 
927     /* Allocate a separate data block for each destination cpu.  */
928     CPU_FOREACH(dst_cpu) {
929         if (dst_cpu != src_cpu) {
930             p = g_memdup(&d, sizeof(d));
931             async_run_on_cpu(dst_cpu, tlb_flush_range_by_mmuidx_async_1,
932                              RUN_ON_CPU_HOST_PTR(p));
933         }
934     }
935 
936     p = g_memdup(&d, sizeof(d));
937     async_safe_run_on_cpu(src_cpu, tlb_flush_range_by_mmuidx_async_1,
938                           RUN_ON_CPU_HOST_PTR(p));
939 }
940 
941 void tlb_flush_page_bits_by_mmuidx_all_cpus_synced(CPUState *src_cpu,
942                                                    target_ulong addr,
943                                                    uint16_t idxmap,
944                                                    unsigned bits)
945 {
946     tlb_flush_range_by_mmuidx_all_cpus_synced(src_cpu, addr, TARGET_PAGE_SIZE,
947                                               idxmap, bits);
948 }
949 
950 /* update the TLBs so that writes to code in the virtual page 'addr'
951    can be detected */
952 void tlb_protect_code(ram_addr_t ram_addr)
953 {
954     cpu_physical_memory_test_and_clear_dirty(ram_addr, TARGET_PAGE_SIZE,
955                                              DIRTY_MEMORY_CODE);
956 }
957 
958 /* update the TLB so that writes in physical page 'phys_addr' are no longer
959    tested for self modifying code */
960 void tlb_unprotect_code(ram_addr_t ram_addr)
961 {
962     cpu_physical_memory_set_dirty_flag(ram_addr, DIRTY_MEMORY_CODE);
963 }
964 
965 
966 /*
967  * Dirty write flag handling
968  *
969  * When the TCG code writes to a location it looks up the address in
970  * the TLB and uses that data to compute the final address. If any of
971  * the lower bits of the address are set then the slow path is forced.
972  * There are a number of reasons to do this but for normal RAM the
973  * most usual is detecting writes to code regions which may invalidate
974  * generated code.
975  *
976  * Other vCPUs might be reading their TLBs during guest execution, so we update
977  * te->addr_write with qatomic_set. We don't need to worry about this for
978  * oversized guests as MTTCG is disabled for them.
979  *
980  * Called with tlb_c.lock held.
981  */
982 static void tlb_reset_dirty_range_locked(CPUTLBEntry *tlb_entry,
983                                          uintptr_t start, uintptr_t length)
984 {
985     uintptr_t addr = tlb_entry->addr_write;
986 
987     if ((addr & (TLB_INVALID_MASK | TLB_MMIO |
988                  TLB_DISCARD_WRITE | TLB_NOTDIRTY)) == 0) {
989         addr &= TARGET_PAGE_MASK;
990         addr += tlb_entry->addend;
991         if ((addr - start) < length) {
992 #if TCG_OVERSIZED_GUEST
993             tlb_entry->addr_write |= TLB_NOTDIRTY;
994 #else
995             qatomic_set(&tlb_entry->addr_write,
996                        tlb_entry->addr_write | TLB_NOTDIRTY);
997 #endif
998         }
999     }
1000 }
1001 
1002 /*
1003  * Called with tlb_c.lock held.
1004  * Called only from the vCPU context, i.e. the TLB's owner thread.
1005  */
1006 static inline void copy_tlb_helper_locked(CPUTLBEntry *d, const CPUTLBEntry *s)
1007 {
1008     *d = *s;
1009 }
1010 
1011 /* This is a cross vCPU call (i.e. another vCPU resetting the flags of
1012  * the target vCPU).
1013  * We must take tlb_c.lock to avoid racing with another vCPU update. The only
1014  * thing actually updated is the target TLB entry ->addr_write flags.
1015  */
1016 void tlb_reset_dirty(CPUState *cpu, ram_addr_t start1, ram_addr_t length)
1017 {
1018     CPUArchState *env;
1019 
1020     int mmu_idx;
1021 
1022     env = cpu->env_ptr;
1023     qemu_spin_lock(&env_tlb(env)->c.lock);
1024     for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
1025         unsigned int i;
1026         unsigned int n = tlb_n_entries(&env_tlb(env)->f[mmu_idx]);
1027 
1028         for (i = 0; i < n; i++) {
1029             tlb_reset_dirty_range_locked(&env_tlb(env)->f[mmu_idx].table[i],
1030                                          start1, length);
1031         }
1032 
1033         for (i = 0; i < CPU_VTLB_SIZE; i++) {
1034             tlb_reset_dirty_range_locked(&env_tlb(env)->d[mmu_idx].vtable[i],
1035                                          start1, length);
1036         }
1037     }
1038     qemu_spin_unlock(&env_tlb(env)->c.lock);
1039 }
1040 
1041 /* Called with tlb_c.lock held */
1042 static inline void tlb_set_dirty1_locked(CPUTLBEntry *tlb_entry,
1043                                          target_ulong vaddr)
1044 {
1045     if (tlb_entry->addr_write == (vaddr | TLB_NOTDIRTY)) {
1046         tlb_entry->addr_write = vaddr;
1047     }
1048 }
1049 
1050 /* update the TLB corresponding to virtual page vaddr
1051    so that it is no longer dirty */
1052 void tlb_set_dirty(CPUState *cpu, target_ulong vaddr)
1053 {
1054     CPUArchState *env = cpu->env_ptr;
1055     int mmu_idx;
1056 
1057     assert_cpu_is_self(cpu);
1058 
1059     vaddr &= TARGET_PAGE_MASK;
1060     qemu_spin_lock(&env_tlb(env)->c.lock);
1061     for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
1062         tlb_set_dirty1_locked(tlb_entry(env, mmu_idx, vaddr), vaddr);
1063     }
1064 
1065     for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
1066         int k;
1067         for (k = 0; k < CPU_VTLB_SIZE; k++) {
1068             tlb_set_dirty1_locked(&env_tlb(env)->d[mmu_idx].vtable[k], vaddr);
1069         }
1070     }
1071     qemu_spin_unlock(&env_tlb(env)->c.lock);
1072 }
1073 
1074 /* Our TLB does not support large pages, so remember the area covered by
1075    large pages and trigger a full TLB flush if these are invalidated.  */
1076 static void tlb_add_large_page(CPUArchState *env, int mmu_idx,
1077                                target_ulong vaddr, target_ulong size)
1078 {
1079     target_ulong lp_addr = env_tlb(env)->d[mmu_idx].large_page_addr;
1080     target_ulong lp_mask = ~(size - 1);
1081 
1082     if (lp_addr == (target_ulong)-1) {
1083         /* No previous large page.  */
1084         lp_addr = vaddr;
1085     } else {
1086         /* Extend the existing region to include the new page.
1087            This is a compromise between unnecessary flushes and
1088            the cost of maintaining a full variable size TLB.  */
1089         lp_mask &= env_tlb(env)->d[mmu_idx].large_page_mask;
1090         while (((lp_addr ^ vaddr) & lp_mask) != 0) {
1091             lp_mask <<= 1;
1092         }
1093     }
1094     env_tlb(env)->d[mmu_idx].large_page_addr = lp_addr & lp_mask;
1095     env_tlb(env)->d[mmu_idx].large_page_mask = lp_mask;
1096 }
1097 
1098 /* Add a new TLB entry. At most one entry for a given virtual address
1099  * is permitted. Only a single TARGET_PAGE_SIZE region is mapped, the
1100  * supplied size is only used by tlb_flush_page.
1101  *
1102  * Called from TCG-generated code, which is under an RCU read-side
1103  * critical section.
1104  */
1105 void tlb_set_page_with_attrs(CPUState *cpu, target_ulong vaddr,
1106                              hwaddr paddr, MemTxAttrs attrs, int prot,
1107                              int mmu_idx, target_ulong size)
1108 {
1109     CPUArchState *env = cpu->env_ptr;
1110     CPUTLB *tlb = env_tlb(env);
1111     CPUTLBDesc *desc = &tlb->d[mmu_idx];
1112     MemoryRegionSection *section;
1113     unsigned int index;
1114     target_ulong address;
1115     target_ulong write_address;
1116     uintptr_t addend;
1117     CPUTLBEntry *te, tn;
1118     hwaddr iotlb, xlat, sz, paddr_page;
1119     target_ulong vaddr_page;
1120     int asidx = cpu_asidx_from_attrs(cpu, attrs);
1121     int wp_flags;
1122     bool is_ram, is_romd;
1123 
1124     assert_cpu_is_self(cpu);
1125 
1126     if (size <= TARGET_PAGE_SIZE) {
1127         sz = TARGET_PAGE_SIZE;
1128     } else {
1129         tlb_add_large_page(env, mmu_idx, vaddr, size);
1130         sz = size;
1131     }
1132     vaddr_page = vaddr & TARGET_PAGE_MASK;
1133     paddr_page = paddr & TARGET_PAGE_MASK;
1134 
1135     section = address_space_translate_for_iotlb(cpu, asidx, paddr_page,
1136                                                 &xlat, &sz, attrs, &prot);
1137     assert(sz >= TARGET_PAGE_SIZE);
1138 
1139     tlb_debug("vaddr=" TARGET_FMT_lx " paddr=0x" TARGET_FMT_plx
1140               " prot=%x idx=%d\n",
1141               vaddr, paddr, prot, mmu_idx);
1142 
1143     address = vaddr_page;
1144     if (size < TARGET_PAGE_SIZE) {
1145         /* Repeat the MMU check and TLB fill on every access.  */
1146         address |= TLB_INVALID_MASK;
1147     }
1148     if (attrs.byte_swap) {
1149         address |= TLB_BSWAP;
1150     }
1151 
1152     is_ram = memory_region_is_ram(section->mr);
1153     is_romd = memory_region_is_romd(section->mr);
1154 
1155     if (is_ram || is_romd) {
1156         /* RAM and ROMD both have associated host memory. */
1157         addend = (uintptr_t)memory_region_get_ram_ptr(section->mr) + xlat;
1158     } else {
1159         /* I/O does not; force the host address to NULL. */
1160         addend = 0;
1161     }
1162 
1163     write_address = address;
1164     if (is_ram) {
1165         iotlb = memory_region_get_ram_addr(section->mr) + xlat;
1166         /*
1167          * Computing is_clean is expensive; avoid all that unless
1168          * the page is actually writable.
1169          */
1170         if (prot & PAGE_WRITE) {
1171             if (section->readonly) {
1172                 write_address |= TLB_DISCARD_WRITE;
1173             } else if (cpu_physical_memory_is_clean(iotlb)) {
1174                 write_address |= TLB_NOTDIRTY;
1175             }
1176         }
1177     } else {
1178         /* I/O or ROMD */
1179         iotlb = memory_region_section_get_iotlb(cpu, section) + xlat;
1180         /*
1181          * Writes to romd devices must go through MMIO to enable write.
1182          * Reads to romd devices go through the ram_ptr found above,
1183          * but of course reads to I/O must go through MMIO.
1184          */
1185         write_address |= TLB_MMIO;
1186         if (!is_romd) {
1187             address = write_address;
1188         }
1189     }
1190 
1191     wp_flags = cpu_watchpoint_address_matches(cpu, vaddr_page,
1192                                               TARGET_PAGE_SIZE);
1193 
1194     index = tlb_index(env, mmu_idx, vaddr_page);
1195     te = tlb_entry(env, mmu_idx, vaddr_page);
1196 
1197     /*
1198      * Hold the TLB lock for the rest of the function. We could acquire/release
1199      * the lock several times in the function, but it is faster to amortize the
1200      * acquisition cost by acquiring it just once. Note that this leads to
1201      * a longer critical section, but this is not a concern since the TLB lock
1202      * is unlikely to be contended.
1203      */
1204     qemu_spin_lock(&tlb->c.lock);
1205 
1206     /* Note that the tlb is no longer clean.  */
1207     tlb->c.dirty |= 1 << mmu_idx;
1208 
1209     /* Make sure there's no cached translation for the new page.  */
1210     tlb_flush_vtlb_page_locked(env, mmu_idx, vaddr_page);
1211 
1212     /*
1213      * Only evict the old entry to the victim tlb if it's for a
1214      * different page; otherwise just overwrite the stale data.
1215      */
1216     if (!tlb_hit_page_anyprot(te, vaddr_page) && !tlb_entry_is_empty(te)) {
1217         unsigned vidx = desc->vindex++ % CPU_VTLB_SIZE;
1218         CPUTLBEntry *tv = &desc->vtable[vidx];
1219 
1220         /* Evict the old entry into the victim tlb.  */
1221         copy_tlb_helper_locked(tv, te);
1222         desc->vfulltlb[vidx] = desc->fulltlb[index];
1223         tlb_n_used_entries_dec(env, mmu_idx);
1224     }
1225 
1226     /* refill the tlb */
1227     /*
1228      * At this point iotlb contains a physical section number in the lower
1229      * TARGET_PAGE_BITS, and either
1230      *  + the ram_addr_t of the page base of the target RAM (RAM)
1231      *  + the offset within section->mr of the page base (I/O, ROMD)
1232      * We subtract the vaddr_page (which is page aligned and thus won't
1233      * disturb the low bits) to give an offset which can be added to the
1234      * (non-page-aligned) vaddr of the eventual memory access to get
1235      * the MemoryRegion offset for the access. Note that the vaddr we
1236      * subtract here is that of the page base, and not the same as the
1237      * vaddr we add back in io_readx()/io_writex()/get_page_addr_code().
1238      */
1239     desc->fulltlb[index].xlat_section = iotlb - vaddr_page;
1240     desc->fulltlb[index].attrs = attrs;
1241 
1242     /* Now calculate the new entry */
1243     tn.addend = addend - vaddr_page;
1244     if (prot & PAGE_READ) {
1245         tn.addr_read = address;
1246         if (wp_flags & BP_MEM_READ) {
1247             tn.addr_read |= TLB_WATCHPOINT;
1248         }
1249     } else {
1250         tn.addr_read = -1;
1251     }
1252 
1253     if (prot & PAGE_EXEC) {
1254         tn.addr_code = address;
1255     } else {
1256         tn.addr_code = -1;
1257     }
1258 
1259     tn.addr_write = -1;
1260     if (prot & PAGE_WRITE) {
1261         tn.addr_write = write_address;
1262         if (prot & PAGE_WRITE_INV) {
1263             tn.addr_write |= TLB_INVALID_MASK;
1264         }
1265         if (wp_flags & BP_MEM_WRITE) {
1266             tn.addr_write |= TLB_WATCHPOINT;
1267         }
1268     }
1269 
1270     copy_tlb_helper_locked(te, &tn);
1271     tlb_n_used_entries_inc(env, mmu_idx);
1272     qemu_spin_unlock(&tlb->c.lock);
1273 }
1274 
1275 /* Add a new TLB entry, but without specifying the memory
1276  * transaction attributes to be used.
1277  */
1278 void tlb_set_page(CPUState *cpu, target_ulong vaddr,
1279                   hwaddr paddr, int prot,
1280                   int mmu_idx, target_ulong size)
1281 {
1282     tlb_set_page_with_attrs(cpu, vaddr, paddr, MEMTXATTRS_UNSPECIFIED,
1283                             prot, mmu_idx, size);
1284 }
1285 
1286 /*
1287  * Note: tlb_fill() can trigger a resize of the TLB. This means that all of the
1288  * caller's prior references to the TLB table (e.g. CPUTLBEntry pointers) must
1289  * be discarded and looked up again (e.g. via tlb_entry()).
1290  */
1291 static void tlb_fill(CPUState *cpu, target_ulong addr, int size,
1292                      MMUAccessType access_type, int mmu_idx, uintptr_t retaddr)
1293 {
1294     bool ok;
1295 
1296     /*
1297      * This is not a probe, so only valid return is success; failure
1298      * should result in exception + longjmp to the cpu loop.
1299      */
1300     ok = cpu->cc->tcg_ops->tlb_fill(cpu, addr, size,
1301                                     access_type, mmu_idx, false, retaddr);
1302     assert(ok);
1303 }
1304 
1305 static inline void cpu_unaligned_access(CPUState *cpu, vaddr addr,
1306                                         MMUAccessType access_type,
1307                                         int mmu_idx, uintptr_t retaddr)
1308 {
1309     cpu->cc->tcg_ops->do_unaligned_access(cpu, addr, access_type,
1310                                           mmu_idx, retaddr);
1311 }
1312 
1313 static inline void cpu_transaction_failed(CPUState *cpu, hwaddr physaddr,
1314                                           vaddr addr, unsigned size,
1315                                           MMUAccessType access_type,
1316                                           int mmu_idx, MemTxAttrs attrs,
1317                                           MemTxResult response,
1318                                           uintptr_t retaddr)
1319 {
1320     CPUClass *cc = CPU_GET_CLASS(cpu);
1321 
1322     if (!cpu->ignore_memory_transaction_failures &&
1323         cc->tcg_ops->do_transaction_failed) {
1324         cc->tcg_ops->do_transaction_failed(cpu, physaddr, addr, size,
1325                                            access_type, mmu_idx, attrs,
1326                                            response, retaddr);
1327     }
1328 }
1329 
1330 static uint64_t io_readx(CPUArchState *env, CPUTLBEntryFull *full,
1331                          int mmu_idx, target_ulong addr, uintptr_t retaddr,
1332                          MMUAccessType access_type, MemOp op)
1333 {
1334     CPUState *cpu = env_cpu(env);
1335     hwaddr mr_offset;
1336     MemoryRegionSection *section;
1337     MemoryRegion *mr;
1338     uint64_t val;
1339     bool locked = false;
1340     MemTxResult r;
1341 
1342     section = iotlb_to_section(cpu, full->xlat_section, full->attrs);
1343     mr = section->mr;
1344     mr_offset = (full->xlat_section & TARGET_PAGE_MASK) + addr;
1345     cpu->mem_io_pc = retaddr;
1346     if (!cpu->can_do_io) {
1347         cpu_io_recompile(cpu, retaddr);
1348     }
1349 
1350     if (!qemu_mutex_iothread_locked()) {
1351         qemu_mutex_lock_iothread();
1352         locked = true;
1353     }
1354     r = memory_region_dispatch_read(mr, mr_offset, &val, op, full->attrs);
1355     if (r != MEMTX_OK) {
1356         hwaddr physaddr = mr_offset +
1357             section->offset_within_address_space -
1358             section->offset_within_region;
1359 
1360         cpu_transaction_failed(cpu, physaddr, addr, memop_size(op), access_type,
1361                                mmu_idx, full->attrs, r, retaddr);
1362     }
1363     if (locked) {
1364         qemu_mutex_unlock_iothread();
1365     }
1366 
1367     return val;
1368 }
1369 
1370 /*
1371  * Save a potentially trashed CPUTLBEntryFull for later lookup by plugin.
1372  * This is read by tlb_plugin_lookup if the fulltlb entry doesn't match
1373  * because of the side effect of io_writex changing memory layout.
1374  */
1375 static void save_iotlb_data(CPUState *cs, MemoryRegionSection *section,
1376                             hwaddr mr_offset)
1377 {
1378 #ifdef CONFIG_PLUGIN
1379     SavedIOTLB *saved = &cs->saved_iotlb;
1380     saved->section = section;
1381     saved->mr_offset = mr_offset;
1382 #endif
1383 }
1384 
1385 static void io_writex(CPUArchState *env, CPUTLBEntryFull *full,
1386                       int mmu_idx, uint64_t val, target_ulong addr,
1387                       uintptr_t retaddr, MemOp op)
1388 {
1389     CPUState *cpu = env_cpu(env);
1390     hwaddr mr_offset;
1391     MemoryRegionSection *section;
1392     MemoryRegion *mr;
1393     bool locked = false;
1394     MemTxResult r;
1395 
1396     section = iotlb_to_section(cpu, full->xlat_section, full->attrs);
1397     mr = section->mr;
1398     mr_offset = (full->xlat_section & TARGET_PAGE_MASK) + addr;
1399     if (!cpu->can_do_io) {
1400         cpu_io_recompile(cpu, retaddr);
1401     }
1402     cpu->mem_io_pc = retaddr;
1403 
1404     /*
1405      * The memory_region_dispatch may trigger a flush/resize
1406      * so for plugins we save the iotlb_data just in case.
1407      */
1408     save_iotlb_data(cpu, section, mr_offset);
1409 
1410     if (!qemu_mutex_iothread_locked()) {
1411         qemu_mutex_lock_iothread();
1412         locked = true;
1413     }
1414     r = memory_region_dispatch_write(mr, mr_offset, val, op, full->attrs);
1415     if (r != MEMTX_OK) {
1416         hwaddr physaddr = mr_offset +
1417             section->offset_within_address_space -
1418             section->offset_within_region;
1419 
1420         cpu_transaction_failed(cpu, physaddr, addr, memop_size(op),
1421                                MMU_DATA_STORE, mmu_idx, full->attrs, r,
1422                                retaddr);
1423     }
1424     if (locked) {
1425         qemu_mutex_unlock_iothread();
1426     }
1427 }
1428 
1429 static inline target_ulong tlb_read_ofs(CPUTLBEntry *entry, size_t ofs)
1430 {
1431 #if TCG_OVERSIZED_GUEST
1432     return *(target_ulong *)((uintptr_t)entry + ofs);
1433 #else
1434     /* ofs might correspond to .addr_write, so use qatomic_read */
1435     return qatomic_read((target_ulong *)((uintptr_t)entry + ofs));
1436 #endif
1437 }
1438 
1439 /* Return true if ADDR is present in the victim tlb, and has been copied
1440    back to the main tlb.  */
1441 static bool victim_tlb_hit(CPUArchState *env, size_t mmu_idx, size_t index,
1442                            size_t elt_ofs, target_ulong page)
1443 {
1444     size_t vidx;
1445 
1446     assert_cpu_is_self(env_cpu(env));
1447     for (vidx = 0; vidx < CPU_VTLB_SIZE; ++vidx) {
1448         CPUTLBEntry *vtlb = &env_tlb(env)->d[mmu_idx].vtable[vidx];
1449         target_ulong cmp;
1450 
1451         /* elt_ofs might correspond to .addr_write, so use qatomic_read */
1452 #if TCG_OVERSIZED_GUEST
1453         cmp = *(target_ulong *)((uintptr_t)vtlb + elt_ofs);
1454 #else
1455         cmp = qatomic_read((target_ulong *)((uintptr_t)vtlb + elt_ofs));
1456 #endif
1457 
1458         if (cmp == page) {
1459             /* Found entry in victim tlb, swap tlb and iotlb.  */
1460             CPUTLBEntry tmptlb, *tlb = &env_tlb(env)->f[mmu_idx].table[index];
1461 
1462             qemu_spin_lock(&env_tlb(env)->c.lock);
1463             copy_tlb_helper_locked(&tmptlb, tlb);
1464             copy_tlb_helper_locked(tlb, vtlb);
1465             copy_tlb_helper_locked(vtlb, &tmptlb);
1466             qemu_spin_unlock(&env_tlb(env)->c.lock);
1467 
1468             CPUTLBEntryFull *f1 = &env_tlb(env)->d[mmu_idx].fulltlb[index];
1469             CPUTLBEntryFull *f2 = &env_tlb(env)->d[mmu_idx].vfulltlb[vidx];
1470             CPUTLBEntryFull tmpf;
1471             tmpf = *f1; *f1 = *f2; *f2 = tmpf;
1472             return true;
1473         }
1474     }
1475     return false;
1476 }
1477 
1478 /* Macro to call the above, with local variables from the use context.  */
1479 #define VICTIM_TLB_HIT(TY, ADDR) \
1480   victim_tlb_hit(env, mmu_idx, index, offsetof(CPUTLBEntry, TY), \
1481                  (ADDR) & TARGET_PAGE_MASK)
1482 
1483 static void notdirty_write(CPUState *cpu, vaddr mem_vaddr, unsigned size,
1484                            CPUTLBEntryFull *full, uintptr_t retaddr)
1485 {
1486     ram_addr_t ram_addr = mem_vaddr + full->xlat_section;
1487 
1488     trace_memory_notdirty_write_access(mem_vaddr, ram_addr, size);
1489 
1490     if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
1491         struct page_collection *pages
1492             = page_collection_lock(ram_addr, ram_addr + size);
1493         tb_invalidate_phys_page_fast(pages, ram_addr, size, retaddr);
1494         page_collection_unlock(pages);
1495     }
1496 
1497     /*
1498      * Set both VGA and migration bits for simplicity and to remove
1499      * the notdirty callback faster.
1500      */
1501     cpu_physical_memory_set_dirty_range(ram_addr, size, DIRTY_CLIENTS_NOCODE);
1502 
1503     /* We remove the notdirty callback only if the code has been flushed. */
1504     if (!cpu_physical_memory_is_clean(ram_addr)) {
1505         trace_memory_notdirty_set_dirty(mem_vaddr);
1506         tlb_set_dirty(cpu, mem_vaddr);
1507     }
1508 }
1509 
1510 static int probe_access_internal(CPUArchState *env, target_ulong addr,
1511                                  int fault_size, MMUAccessType access_type,
1512                                  int mmu_idx, bool nonfault,
1513                                  void **phost, uintptr_t retaddr)
1514 {
1515     uintptr_t index = tlb_index(env, mmu_idx, addr);
1516     CPUTLBEntry *entry = tlb_entry(env, mmu_idx, addr);
1517     target_ulong tlb_addr, page_addr;
1518     size_t elt_ofs;
1519     int flags;
1520 
1521     switch (access_type) {
1522     case MMU_DATA_LOAD:
1523         elt_ofs = offsetof(CPUTLBEntry, addr_read);
1524         break;
1525     case MMU_DATA_STORE:
1526         elt_ofs = offsetof(CPUTLBEntry, addr_write);
1527         break;
1528     case MMU_INST_FETCH:
1529         elt_ofs = offsetof(CPUTLBEntry, addr_code);
1530         break;
1531     default:
1532         g_assert_not_reached();
1533     }
1534     tlb_addr = tlb_read_ofs(entry, elt_ofs);
1535 
1536     page_addr = addr & TARGET_PAGE_MASK;
1537     if (!tlb_hit_page(tlb_addr, page_addr)) {
1538         if (!victim_tlb_hit(env, mmu_idx, index, elt_ofs, page_addr)) {
1539             CPUState *cs = env_cpu(env);
1540 
1541             if (!cs->cc->tcg_ops->tlb_fill(cs, addr, fault_size, access_type,
1542                                            mmu_idx, nonfault, retaddr)) {
1543                 /* Non-faulting page table read failed.  */
1544                 *phost = NULL;
1545                 return TLB_INVALID_MASK;
1546             }
1547 
1548             /* TLB resize via tlb_fill may have moved the entry.  */
1549             entry = tlb_entry(env, mmu_idx, addr);
1550         }
1551         tlb_addr = tlb_read_ofs(entry, elt_ofs);
1552     }
1553     flags = tlb_addr & TLB_FLAGS_MASK;
1554 
1555     /* Fold all "mmio-like" bits into TLB_MMIO.  This is not RAM.  */
1556     if (unlikely(flags & ~(TLB_WATCHPOINT | TLB_NOTDIRTY))) {
1557         *phost = NULL;
1558         return TLB_MMIO;
1559     }
1560 
1561     /* Everything else is RAM. */
1562     *phost = (void *)((uintptr_t)addr + entry->addend);
1563     return flags;
1564 }
1565 
1566 int probe_access_flags(CPUArchState *env, target_ulong addr,
1567                        MMUAccessType access_type, int mmu_idx,
1568                        bool nonfault, void **phost, uintptr_t retaddr)
1569 {
1570     int flags;
1571 
1572     flags = probe_access_internal(env, addr, 0, access_type, mmu_idx,
1573                                   nonfault, phost, retaddr);
1574 
1575     /* Handle clean RAM pages.  */
1576     if (unlikely(flags & TLB_NOTDIRTY)) {
1577         uintptr_t index = tlb_index(env, mmu_idx, addr);
1578         CPUTLBEntryFull *full = &env_tlb(env)->d[mmu_idx].fulltlb[index];
1579 
1580         notdirty_write(env_cpu(env), addr, 1, full, retaddr);
1581         flags &= ~TLB_NOTDIRTY;
1582     }
1583 
1584     return flags;
1585 }
1586 
1587 void *probe_access(CPUArchState *env, target_ulong addr, int size,
1588                    MMUAccessType access_type, int mmu_idx, uintptr_t retaddr)
1589 {
1590     void *host;
1591     int flags;
1592 
1593     g_assert(-(addr | TARGET_PAGE_MASK) >= size);
1594 
1595     flags = probe_access_internal(env, addr, size, access_type, mmu_idx,
1596                                   false, &host, retaddr);
1597 
1598     /* Per the interface, size == 0 merely faults the access. */
1599     if (size == 0) {
1600         return NULL;
1601     }
1602 
1603     if (unlikely(flags & (TLB_NOTDIRTY | TLB_WATCHPOINT))) {
1604         uintptr_t index = tlb_index(env, mmu_idx, addr);
1605         CPUTLBEntryFull *full = &env_tlb(env)->d[mmu_idx].fulltlb[index];
1606 
1607         /* Handle watchpoints.  */
1608         if (flags & TLB_WATCHPOINT) {
1609             int wp_access = (access_type == MMU_DATA_STORE
1610                              ? BP_MEM_WRITE : BP_MEM_READ);
1611             cpu_check_watchpoint(env_cpu(env), addr, size,
1612                                  full->attrs, wp_access, retaddr);
1613         }
1614 
1615         /* Handle clean RAM pages.  */
1616         if (flags & TLB_NOTDIRTY) {
1617             notdirty_write(env_cpu(env), addr, 1, full, retaddr);
1618         }
1619     }
1620 
1621     return host;
1622 }
1623 
1624 void *tlb_vaddr_to_host(CPUArchState *env, abi_ptr addr,
1625                         MMUAccessType access_type, int mmu_idx)
1626 {
1627     void *host;
1628     int flags;
1629 
1630     flags = probe_access_internal(env, addr, 0, access_type,
1631                                   mmu_idx, true, &host, 0);
1632 
1633     /* No combination of flags are expected by the caller. */
1634     return flags ? NULL : host;
1635 }
1636 
1637 /*
1638  * Return a ram_addr_t for the virtual address for execution.
1639  *
1640  * Return -1 if we can't translate and execute from an entire page
1641  * of RAM.  This will force us to execute by loading and translating
1642  * one insn at a time, without caching.
1643  *
1644  * NOTE: This function will trigger an exception if the page is
1645  * not executable.
1646  */
1647 tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, target_ulong addr,
1648                                         void **hostp)
1649 {
1650     void *p;
1651 
1652     (void)probe_access_internal(env, addr, 1, MMU_INST_FETCH,
1653                                 cpu_mmu_index(env, true), false, &p, 0);
1654     if (p == NULL) {
1655         return -1;
1656     }
1657     if (hostp) {
1658         *hostp = p;
1659     }
1660     return qemu_ram_addr_from_host_nofail(p);
1661 }
1662 
1663 #ifdef CONFIG_PLUGIN
1664 /*
1665  * Perform a TLB lookup and populate the qemu_plugin_hwaddr structure.
1666  * This should be a hot path as we will have just looked this path up
1667  * in the softmmu lookup code (or helper). We don't handle re-fills or
1668  * checking the victim table. This is purely informational.
1669  *
1670  * This almost never fails as the memory access being instrumented
1671  * should have just filled the TLB. The one corner case is io_writex
1672  * which can cause TLB flushes and potential resizing of the TLBs
1673  * losing the information we need. In those cases we need to recover
1674  * data from a copy of the CPUTLBEntryFull. As long as this always occurs
1675  * from the same thread (which a mem callback will be) this is safe.
1676  */
1677 
1678 bool tlb_plugin_lookup(CPUState *cpu, target_ulong addr, int mmu_idx,
1679                        bool is_store, struct qemu_plugin_hwaddr *data)
1680 {
1681     CPUArchState *env = cpu->env_ptr;
1682     CPUTLBEntry *tlbe = tlb_entry(env, mmu_idx, addr);
1683     uintptr_t index = tlb_index(env, mmu_idx, addr);
1684     target_ulong tlb_addr = is_store ? tlb_addr_write(tlbe) : tlbe->addr_read;
1685 
1686     if (likely(tlb_hit(tlb_addr, addr))) {
1687         /* We must have an iotlb entry for MMIO */
1688         if (tlb_addr & TLB_MMIO) {
1689             CPUTLBEntryFull *full;
1690             full = &env_tlb(env)->d[mmu_idx].fulltlb[index];
1691             data->is_io = true;
1692             data->v.io.section =
1693                 iotlb_to_section(cpu, full->xlat_section, full->attrs);
1694             data->v.io.offset = (full->xlat_section & TARGET_PAGE_MASK) + addr;
1695         } else {
1696             data->is_io = false;
1697             data->v.ram.hostaddr = (void *)((uintptr_t)addr + tlbe->addend);
1698         }
1699         return true;
1700     } else {
1701         SavedIOTLB *saved = &cpu->saved_iotlb;
1702         data->is_io = true;
1703         data->v.io.section = saved->section;
1704         data->v.io.offset = saved->mr_offset;
1705         return true;
1706     }
1707 }
1708 
1709 #endif
1710 
1711 /*
1712  * Probe for an atomic operation.  Do not allow unaligned operations,
1713  * or io operations to proceed.  Return the host address.
1714  *
1715  * @prot may be PAGE_READ, PAGE_WRITE, or PAGE_READ|PAGE_WRITE.
1716  */
1717 static void *atomic_mmu_lookup(CPUArchState *env, target_ulong addr,
1718                                MemOpIdx oi, int size, int prot,
1719                                uintptr_t retaddr)
1720 {
1721     uintptr_t mmu_idx = get_mmuidx(oi);
1722     MemOp mop = get_memop(oi);
1723     int a_bits = get_alignment_bits(mop);
1724     uintptr_t index;
1725     CPUTLBEntry *tlbe;
1726     target_ulong tlb_addr;
1727     void *hostaddr;
1728 
1729     tcg_debug_assert(mmu_idx < NB_MMU_MODES);
1730 
1731     /* Adjust the given return address.  */
1732     retaddr -= GETPC_ADJ;
1733 
1734     /* Enforce guest required alignment.  */
1735     if (unlikely(a_bits > 0 && (addr & ((1 << a_bits) - 1)))) {
1736         /* ??? Maybe indicate atomic op to cpu_unaligned_access */
1737         cpu_unaligned_access(env_cpu(env), addr, MMU_DATA_STORE,
1738                              mmu_idx, retaddr);
1739     }
1740 
1741     /* Enforce qemu required alignment.  */
1742     if (unlikely(addr & (size - 1))) {
1743         /* We get here if guest alignment was not requested,
1744            or was not enforced by cpu_unaligned_access above.
1745            We might widen the access and emulate, but for now
1746            mark an exception and exit the cpu loop.  */
1747         goto stop_the_world;
1748     }
1749 
1750     index = tlb_index(env, mmu_idx, addr);
1751     tlbe = tlb_entry(env, mmu_idx, addr);
1752 
1753     /* Check TLB entry and enforce page permissions.  */
1754     if (prot & PAGE_WRITE) {
1755         tlb_addr = tlb_addr_write(tlbe);
1756         if (!tlb_hit(tlb_addr, addr)) {
1757             if (!VICTIM_TLB_HIT(addr_write, addr)) {
1758                 tlb_fill(env_cpu(env), addr, size,
1759                          MMU_DATA_STORE, mmu_idx, retaddr);
1760                 index = tlb_index(env, mmu_idx, addr);
1761                 tlbe = tlb_entry(env, mmu_idx, addr);
1762             }
1763             tlb_addr = tlb_addr_write(tlbe) & ~TLB_INVALID_MASK;
1764         }
1765 
1766         /* Let the guest notice RMW on a write-only page.  */
1767         if ((prot & PAGE_READ) &&
1768             unlikely(tlbe->addr_read != (tlb_addr & ~TLB_NOTDIRTY))) {
1769             tlb_fill(env_cpu(env), addr, size,
1770                      MMU_DATA_LOAD, mmu_idx, retaddr);
1771             /*
1772              * Since we don't support reads and writes to different addresses,
1773              * and we do have the proper page loaded for write, this shouldn't
1774              * ever return.  But just in case, handle via stop-the-world.
1775              */
1776             goto stop_the_world;
1777         }
1778     } else /* if (prot & PAGE_READ) */ {
1779         tlb_addr = tlbe->addr_read;
1780         if (!tlb_hit(tlb_addr, addr)) {
1781             if (!VICTIM_TLB_HIT(addr_write, addr)) {
1782                 tlb_fill(env_cpu(env), addr, size,
1783                          MMU_DATA_LOAD, mmu_idx, retaddr);
1784                 index = tlb_index(env, mmu_idx, addr);
1785                 tlbe = tlb_entry(env, mmu_idx, addr);
1786             }
1787             tlb_addr = tlbe->addr_read & ~TLB_INVALID_MASK;
1788         }
1789     }
1790 
1791     /* Notice an IO access or a needs-MMU-lookup access */
1792     if (unlikely(tlb_addr & TLB_MMIO)) {
1793         /* There's really nothing that can be done to
1794            support this apart from stop-the-world.  */
1795         goto stop_the_world;
1796     }
1797 
1798     hostaddr = (void *)((uintptr_t)addr + tlbe->addend);
1799 
1800     if (unlikely(tlb_addr & TLB_NOTDIRTY)) {
1801         notdirty_write(env_cpu(env), addr, size,
1802                        &env_tlb(env)->d[mmu_idx].fulltlb[index], retaddr);
1803     }
1804 
1805     return hostaddr;
1806 
1807  stop_the_world:
1808     cpu_loop_exit_atomic(env_cpu(env), retaddr);
1809 }
1810 
1811 /*
1812  * Verify that we have passed the correct MemOp to the correct function.
1813  *
1814  * In the case of the helper_*_mmu functions, we will have done this by
1815  * using the MemOp to look up the helper during code generation.
1816  *
1817  * In the case of the cpu_*_mmu functions, this is up to the caller.
1818  * We could present one function to target code, and dispatch based on
1819  * the MemOp, but so far we have worked hard to avoid an indirect function
1820  * call along the memory path.
1821  */
1822 static void validate_memop(MemOpIdx oi, MemOp expected)
1823 {
1824 #ifdef CONFIG_DEBUG_TCG
1825     MemOp have = get_memop(oi) & (MO_SIZE | MO_BSWAP);
1826     assert(have == expected);
1827 #endif
1828 }
1829 
1830 /*
1831  * Load Helpers
1832  *
1833  * We support two different access types. SOFTMMU_CODE_ACCESS is
1834  * specifically for reading instructions from system memory. It is
1835  * called by the translation loop and in some helpers where the code
1836  * is disassembled. It shouldn't be called directly by guest code.
1837  */
1838 
1839 typedef uint64_t FullLoadHelper(CPUArchState *env, target_ulong addr,
1840                                 MemOpIdx oi, uintptr_t retaddr);
1841 
1842 static inline uint64_t QEMU_ALWAYS_INLINE
1843 load_memop(const void *haddr, MemOp op)
1844 {
1845     switch (op) {
1846     case MO_UB:
1847         return ldub_p(haddr);
1848     case MO_BEUW:
1849         return lduw_be_p(haddr);
1850     case MO_LEUW:
1851         return lduw_le_p(haddr);
1852     case MO_BEUL:
1853         return (uint32_t)ldl_be_p(haddr);
1854     case MO_LEUL:
1855         return (uint32_t)ldl_le_p(haddr);
1856     case MO_BEUQ:
1857         return ldq_be_p(haddr);
1858     case MO_LEUQ:
1859         return ldq_le_p(haddr);
1860     default:
1861         qemu_build_not_reached();
1862     }
1863 }
1864 
1865 static inline uint64_t QEMU_ALWAYS_INLINE
1866 load_helper(CPUArchState *env, target_ulong addr, MemOpIdx oi,
1867             uintptr_t retaddr, MemOp op, bool code_read,
1868             FullLoadHelper *full_load)
1869 {
1870     const size_t tlb_off = code_read ?
1871         offsetof(CPUTLBEntry, addr_code) : offsetof(CPUTLBEntry, addr_read);
1872     const MMUAccessType access_type =
1873         code_read ? MMU_INST_FETCH : MMU_DATA_LOAD;
1874     const unsigned a_bits = get_alignment_bits(get_memop(oi));
1875     const size_t size = memop_size(op);
1876     uintptr_t mmu_idx = get_mmuidx(oi);
1877     uintptr_t index;
1878     CPUTLBEntry *entry;
1879     target_ulong tlb_addr;
1880     void *haddr;
1881     uint64_t res;
1882 
1883     tcg_debug_assert(mmu_idx < NB_MMU_MODES);
1884 
1885     /* Handle CPU specific unaligned behaviour */
1886     if (addr & ((1 << a_bits) - 1)) {
1887         cpu_unaligned_access(env_cpu(env), addr, access_type,
1888                              mmu_idx, retaddr);
1889     }
1890 
1891     index = tlb_index(env, mmu_idx, addr);
1892     entry = tlb_entry(env, mmu_idx, addr);
1893     tlb_addr = code_read ? entry->addr_code : entry->addr_read;
1894 
1895     /* If the TLB entry is for a different page, reload and try again.  */
1896     if (!tlb_hit(tlb_addr, addr)) {
1897         if (!victim_tlb_hit(env, mmu_idx, index, tlb_off,
1898                             addr & TARGET_PAGE_MASK)) {
1899             tlb_fill(env_cpu(env), addr, size,
1900                      access_type, mmu_idx, retaddr);
1901             index = tlb_index(env, mmu_idx, addr);
1902             entry = tlb_entry(env, mmu_idx, addr);
1903         }
1904         tlb_addr = code_read ? entry->addr_code : entry->addr_read;
1905         tlb_addr &= ~TLB_INVALID_MASK;
1906     }
1907 
1908     /* Handle anything that isn't just a straight memory access.  */
1909     if (unlikely(tlb_addr & ~TARGET_PAGE_MASK)) {
1910         CPUTLBEntryFull *full;
1911         bool need_swap;
1912 
1913         /* For anything that is unaligned, recurse through full_load.  */
1914         if ((addr & (size - 1)) != 0) {
1915             goto do_unaligned_access;
1916         }
1917 
1918         full = &env_tlb(env)->d[mmu_idx].fulltlb[index];
1919 
1920         /* Handle watchpoints.  */
1921         if (unlikely(tlb_addr & TLB_WATCHPOINT)) {
1922             /* On watchpoint hit, this will longjmp out.  */
1923             cpu_check_watchpoint(env_cpu(env), addr, size,
1924                                  full->attrs, BP_MEM_READ, retaddr);
1925         }
1926 
1927         need_swap = size > 1 && (tlb_addr & TLB_BSWAP);
1928 
1929         /* Handle I/O access.  */
1930         if (likely(tlb_addr & TLB_MMIO)) {
1931             return io_readx(env, full, mmu_idx, addr, retaddr,
1932                             access_type, op ^ (need_swap * MO_BSWAP));
1933         }
1934 
1935         haddr = (void *)((uintptr_t)addr + entry->addend);
1936 
1937         /*
1938          * Keep these two load_memop separate to ensure that the compiler
1939          * is able to fold the entire function to a single instruction.
1940          * There is a build-time assert inside to remind you of this.  ;-)
1941          */
1942         if (unlikely(need_swap)) {
1943             return load_memop(haddr, op ^ MO_BSWAP);
1944         }
1945         return load_memop(haddr, op);
1946     }
1947 
1948     /* Handle slow unaligned access (it spans two pages or IO).  */
1949     if (size > 1
1950         && unlikely((addr & ~TARGET_PAGE_MASK) + size - 1
1951                     >= TARGET_PAGE_SIZE)) {
1952         target_ulong addr1, addr2;
1953         uint64_t r1, r2;
1954         unsigned shift;
1955     do_unaligned_access:
1956         addr1 = addr & ~((target_ulong)size - 1);
1957         addr2 = addr1 + size;
1958         r1 = full_load(env, addr1, oi, retaddr);
1959         r2 = full_load(env, addr2, oi, retaddr);
1960         shift = (addr & (size - 1)) * 8;
1961 
1962         if (memop_big_endian(op)) {
1963             /* Big-endian combine.  */
1964             res = (r1 << shift) | (r2 >> ((size * 8) - shift));
1965         } else {
1966             /* Little-endian combine.  */
1967             res = (r1 >> shift) | (r2 << ((size * 8) - shift));
1968         }
1969         return res & MAKE_64BIT_MASK(0, size * 8);
1970     }
1971 
1972     haddr = (void *)((uintptr_t)addr + entry->addend);
1973     return load_memop(haddr, op);
1974 }
1975 
1976 /*
1977  * For the benefit of TCG generated code, we want to avoid the
1978  * complication of ABI-specific return type promotion and always
1979  * return a value extended to the register size of the host. This is
1980  * tcg_target_long, except in the case of a 32-bit host and 64-bit
1981  * data, and for that we always have uint64_t.
1982  *
1983  * We don't bother with this widened value for SOFTMMU_CODE_ACCESS.
1984  */
1985 
1986 static uint64_t full_ldub_mmu(CPUArchState *env, target_ulong addr,
1987                               MemOpIdx oi, uintptr_t retaddr)
1988 {
1989     validate_memop(oi, MO_UB);
1990     return load_helper(env, addr, oi, retaddr, MO_UB, false, full_ldub_mmu);
1991 }
1992 
1993 tcg_target_ulong helper_ret_ldub_mmu(CPUArchState *env, target_ulong addr,
1994                                      MemOpIdx oi, uintptr_t retaddr)
1995 {
1996     return full_ldub_mmu(env, addr, oi, retaddr);
1997 }
1998 
1999 static uint64_t full_le_lduw_mmu(CPUArchState *env, target_ulong addr,
2000                                  MemOpIdx oi, uintptr_t retaddr)
2001 {
2002     validate_memop(oi, MO_LEUW);
2003     return load_helper(env, addr, oi, retaddr, MO_LEUW, false,
2004                        full_le_lduw_mmu);
2005 }
2006 
2007 tcg_target_ulong helper_le_lduw_mmu(CPUArchState *env, target_ulong addr,
2008                                     MemOpIdx oi, uintptr_t retaddr)
2009 {
2010     return full_le_lduw_mmu(env, addr, oi, retaddr);
2011 }
2012 
2013 static uint64_t full_be_lduw_mmu(CPUArchState *env, target_ulong addr,
2014                                  MemOpIdx oi, uintptr_t retaddr)
2015 {
2016     validate_memop(oi, MO_BEUW);
2017     return load_helper(env, addr, oi, retaddr, MO_BEUW, false,
2018                        full_be_lduw_mmu);
2019 }
2020 
2021 tcg_target_ulong helper_be_lduw_mmu(CPUArchState *env, target_ulong addr,
2022                                     MemOpIdx oi, uintptr_t retaddr)
2023 {
2024     return full_be_lduw_mmu(env, addr, oi, retaddr);
2025 }
2026 
2027 static uint64_t full_le_ldul_mmu(CPUArchState *env, target_ulong addr,
2028                                  MemOpIdx oi, uintptr_t retaddr)
2029 {
2030     validate_memop(oi, MO_LEUL);
2031     return load_helper(env, addr, oi, retaddr, MO_LEUL, false,
2032                        full_le_ldul_mmu);
2033 }
2034 
2035 tcg_target_ulong helper_le_ldul_mmu(CPUArchState *env, target_ulong addr,
2036                                     MemOpIdx oi, uintptr_t retaddr)
2037 {
2038     return full_le_ldul_mmu(env, addr, oi, retaddr);
2039 }
2040 
2041 static uint64_t full_be_ldul_mmu(CPUArchState *env, target_ulong addr,
2042                                  MemOpIdx oi, uintptr_t retaddr)
2043 {
2044     validate_memop(oi, MO_BEUL);
2045     return load_helper(env, addr, oi, retaddr, MO_BEUL, false,
2046                        full_be_ldul_mmu);
2047 }
2048 
2049 tcg_target_ulong helper_be_ldul_mmu(CPUArchState *env, target_ulong addr,
2050                                     MemOpIdx oi, uintptr_t retaddr)
2051 {
2052     return full_be_ldul_mmu(env, addr, oi, retaddr);
2053 }
2054 
2055 uint64_t helper_le_ldq_mmu(CPUArchState *env, target_ulong addr,
2056                            MemOpIdx oi, uintptr_t retaddr)
2057 {
2058     validate_memop(oi, MO_LEUQ);
2059     return load_helper(env, addr, oi, retaddr, MO_LEUQ, false,
2060                        helper_le_ldq_mmu);
2061 }
2062 
2063 uint64_t helper_be_ldq_mmu(CPUArchState *env, target_ulong addr,
2064                            MemOpIdx oi, uintptr_t retaddr)
2065 {
2066     validate_memop(oi, MO_BEUQ);
2067     return load_helper(env, addr, oi, retaddr, MO_BEUQ, false,
2068                        helper_be_ldq_mmu);
2069 }
2070 
2071 /*
2072  * Provide signed versions of the load routines as well.  We can of course
2073  * avoid this for 64-bit data, or for 32-bit data on 32-bit host.
2074  */
2075 
2076 
2077 tcg_target_ulong helper_ret_ldsb_mmu(CPUArchState *env, target_ulong addr,
2078                                      MemOpIdx oi, uintptr_t retaddr)
2079 {
2080     return (int8_t)helper_ret_ldub_mmu(env, addr, oi, retaddr);
2081 }
2082 
2083 tcg_target_ulong helper_le_ldsw_mmu(CPUArchState *env, target_ulong addr,
2084                                     MemOpIdx oi, uintptr_t retaddr)
2085 {
2086     return (int16_t)helper_le_lduw_mmu(env, addr, oi, retaddr);
2087 }
2088 
2089 tcg_target_ulong helper_be_ldsw_mmu(CPUArchState *env, target_ulong addr,
2090                                     MemOpIdx oi, uintptr_t retaddr)
2091 {
2092     return (int16_t)helper_be_lduw_mmu(env, addr, oi, retaddr);
2093 }
2094 
2095 tcg_target_ulong helper_le_ldsl_mmu(CPUArchState *env, target_ulong addr,
2096                                     MemOpIdx oi, uintptr_t retaddr)
2097 {
2098     return (int32_t)helper_le_ldul_mmu(env, addr, oi, retaddr);
2099 }
2100 
2101 tcg_target_ulong helper_be_ldsl_mmu(CPUArchState *env, target_ulong addr,
2102                                     MemOpIdx oi, uintptr_t retaddr)
2103 {
2104     return (int32_t)helper_be_ldul_mmu(env, addr, oi, retaddr);
2105 }
2106 
2107 /*
2108  * Load helpers for cpu_ldst.h.
2109  */
2110 
2111 static inline uint64_t cpu_load_helper(CPUArchState *env, abi_ptr addr,
2112                                        MemOpIdx oi, uintptr_t retaddr,
2113                                        FullLoadHelper *full_load)
2114 {
2115     uint64_t ret;
2116 
2117     ret = full_load(env, addr, oi, retaddr);
2118     qemu_plugin_vcpu_mem_cb(env_cpu(env), addr, oi, QEMU_PLUGIN_MEM_R);
2119     return ret;
2120 }
2121 
2122 uint8_t cpu_ldb_mmu(CPUArchState *env, abi_ptr addr, MemOpIdx oi, uintptr_t ra)
2123 {
2124     return cpu_load_helper(env, addr, oi, ra, full_ldub_mmu);
2125 }
2126 
2127 uint16_t cpu_ldw_be_mmu(CPUArchState *env, abi_ptr addr,
2128                         MemOpIdx oi, uintptr_t ra)
2129 {
2130     return cpu_load_helper(env, addr, oi, ra, full_be_lduw_mmu);
2131 }
2132 
2133 uint32_t cpu_ldl_be_mmu(CPUArchState *env, abi_ptr addr,
2134                         MemOpIdx oi, uintptr_t ra)
2135 {
2136     return cpu_load_helper(env, addr, oi, ra, full_be_ldul_mmu);
2137 }
2138 
2139 uint64_t cpu_ldq_be_mmu(CPUArchState *env, abi_ptr addr,
2140                         MemOpIdx oi, uintptr_t ra)
2141 {
2142     return cpu_load_helper(env, addr, oi, ra, helper_be_ldq_mmu);
2143 }
2144 
2145 uint16_t cpu_ldw_le_mmu(CPUArchState *env, abi_ptr addr,
2146                         MemOpIdx oi, uintptr_t ra)
2147 {
2148     return cpu_load_helper(env, addr, oi, ra, full_le_lduw_mmu);
2149 }
2150 
2151 uint32_t cpu_ldl_le_mmu(CPUArchState *env, abi_ptr addr,
2152                         MemOpIdx oi, uintptr_t ra)
2153 {
2154     return cpu_load_helper(env, addr, oi, ra, full_le_ldul_mmu);
2155 }
2156 
2157 uint64_t cpu_ldq_le_mmu(CPUArchState *env, abi_ptr addr,
2158                         MemOpIdx oi, uintptr_t ra)
2159 {
2160     return cpu_load_helper(env, addr, oi, ra, helper_le_ldq_mmu);
2161 }
2162 
2163 /*
2164  * Store Helpers
2165  */
2166 
2167 static inline void QEMU_ALWAYS_INLINE
2168 store_memop(void *haddr, uint64_t val, MemOp op)
2169 {
2170     switch (op) {
2171     case MO_UB:
2172         stb_p(haddr, val);
2173         break;
2174     case MO_BEUW:
2175         stw_be_p(haddr, val);
2176         break;
2177     case MO_LEUW:
2178         stw_le_p(haddr, val);
2179         break;
2180     case MO_BEUL:
2181         stl_be_p(haddr, val);
2182         break;
2183     case MO_LEUL:
2184         stl_le_p(haddr, val);
2185         break;
2186     case MO_BEUQ:
2187         stq_be_p(haddr, val);
2188         break;
2189     case MO_LEUQ:
2190         stq_le_p(haddr, val);
2191         break;
2192     default:
2193         qemu_build_not_reached();
2194     }
2195 }
2196 
2197 static void full_stb_mmu(CPUArchState *env, target_ulong addr, uint64_t val,
2198                          MemOpIdx oi, uintptr_t retaddr);
2199 
2200 static void __attribute__((noinline))
2201 store_helper_unaligned(CPUArchState *env, target_ulong addr, uint64_t val,
2202                        uintptr_t retaddr, size_t size, uintptr_t mmu_idx,
2203                        bool big_endian)
2204 {
2205     const size_t tlb_off = offsetof(CPUTLBEntry, addr_write);
2206     uintptr_t index, index2;
2207     CPUTLBEntry *entry, *entry2;
2208     target_ulong page1, page2, tlb_addr, tlb_addr2;
2209     MemOpIdx oi;
2210     size_t size2;
2211     int i;
2212 
2213     /*
2214      * Ensure the second page is in the TLB.  Note that the first page
2215      * is already guaranteed to be filled, and that the second page
2216      * cannot evict the first.  An exception to this rule is PAGE_WRITE_INV
2217      * handling: the first page could have evicted itself.
2218      */
2219     page1 = addr & TARGET_PAGE_MASK;
2220     page2 = (addr + size) & TARGET_PAGE_MASK;
2221     size2 = (addr + size) & ~TARGET_PAGE_MASK;
2222     index2 = tlb_index(env, mmu_idx, page2);
2223     entry2 = tlb_entry(env, mmu_idx, page2);
2224 
2225     tlb_addr2 = tlb_addr_write(entry2);
2226     if (page1 != page2 && !tlb_hit_page(tlb_addr2, page2)) {
2227         if (!victim_tlb_hit(env, mmu_idx, index2, tlb_off, page2)) {
2228             tlb_fill(env_cpu(env), page2, size2, MMU_DATA_STORE,
2229                      mmu_idx, retaddr);
2230             index2 = tlb_index(env, mmu_idx, page2);
2231             entry2 = tlb_entry(env, mmu_idx, page2);
2232         }
2233         tlb_addr2 = tlb_addr_write(entry2);
2234     }
2235 
2236     index = tlb_index(env, mmu_idx, addr);
2237     entry = tlb_entry(env, mmu_idx, addr);
2238     tlb_addr = tlb_addr_write(entry);
2239 
2240     /*
2241      * Handle watchpoints.  Since this may trap, all checks
2242      * must happen before any store.
2243      */
2244     if (unlikely(tlb_addr & TLB_WATCHPOINT)) {
2245         cpu_check_watchpoint(env_cpu(env), addr, size - size2,
2246                              env_tlb(env)->d[mmu_idx].fulltlb[index].attrs,
2247                              BP_MEM_WRITE, retaddr);
2248     }
2249     if (unlikely(tlb_addr2 & TLB_WATCHPOINT)) {
2250         cpu_check_watchpoint(env_cpu(env), page2, size2,
2251                              env_tlb(env)->d[mmu_idx].fulltlb[index2].attrs,
2252                              BP_MEM_WRITE, retaddr);
2253     }
2254 
2255     /*
2256      * XXX: not efficient, but simple.
2257      * This loop must go in the forward direction to avoid issues
2258      * with self-modifying code in Windows 64-bit.
2259      */
2260     oi = make_memop_idx(MO_UB, mmu_idx);
2261     if (big_endian) {
2262         for (i = 0; i < size; ++i) {
2263             /* Big-endian extract.  */
2264             uint8_t val8 = val >> (((size - 1) * 8) - (i * 8));
2265             full_stb_mmu(env, addr + i, val8, oi, retaddr);
2266         }
2267     } else {
2268         for (i = 0; i < size; ++i) {
2269             /* Little-endian extract.  */
2270             uint8_t val8 = val >> (i * 8);
2271             full_stb_mmu(env, addr + i, val8, oi, retaddr);
2272         }
2273     }
2274 }
2275 
2276 static inline void QEMU_ALWAYS_INLINE
2277 store_helper(CPUArchState *env, target_ulong addr, uint64_t val,
2278              MemOpIdx oi, uintptr_t retaddr, MemOp op)
2279 {
2280     const size_t tlb_off = offsetof(CPUTLBEntry, addr_write);
2281     const unsigned a_bits = get_alignment_bits(get_memop(oi));
2282     const size_t size = memop_size(op);
2283     uintptr_t mmu_idx = get_mmuidx(oi);
2284     uintptr_t index;
2285     CPUTLBEntry *entry;
2286     target_ulong tlb_addr;
2287     void *haddr;
2288 
2289     tcg_debug_assert(mmu_idx < NB_MMU_MODES);
2290 
2291     /* Handle CPU specific unaligned behaviour */
2292     if (addr & ((1 << a_bits) - 1)) {
2293         cpu_unaligned_access(env_cpu(env), addr, MMU_DATA_STORE,
2294                              mmu_idx, retaddr);
2295     }
2296 
2297     index = tlb_index(env, mmu_idx, addr);
2298     entry = tlb_entry(env, mmu_idx, addr);
2299     tlb_addr = tlb_addr_write(entry);
2300 
2301     /* If the TLB entry is for a different page, reload and try again.  */
2302     if (!tlb_hit(tlb_addr, addr)) {
2303         if (!victim_tlb_hit(env, mmu_idx, index, tlb_off,
2304             addr & TARGET_PAGE_MASK)) {
2305             tlb_fill(env_cpu(env), addr, size, MMU_DATA_STORE,
2306                      mmu_idx, retaddr);
2307             index = tlb_index(env, mmu_idx, addr);
2308             entry = tlb_entry(env, mmu_idx, addr);
2309         }
2310         tlb_addr = tlb_addr_write(entry) & ~TLB_INVALID_MASK;
2311     }
2312 
2313     /* Handle anything that isn't just a straight memory access.  */
2314     if (unlikely(tlb_addr & ~TARGET_PAGE_MASK)) {
2315         CPUTLBEntryFull *full;
2316         bool need_swap;
2317 
2318         /* For anything that is unaligned, recurse through byte stores.  */
2319         if ((addr & (size - 1)) != 0) {
2320             goto do_unaligned_access;
2321         }
2322 
2323         full = &env_tlb(env)->d[mmu_idx].fulltlb[index];
2324 
2325         /* Handle watchpoints.  */
2326         if (unlikely(tlb_addr & TLB_WATCHPOINT)) {
2327             /* On watchpoint hit, this will longjmp out.  */
2328             cpu_check_watchpoint(env_cpu(env), addr, size,
2329                                  full->attrs, BP_MEM_WRITE, retaddr);
2330         }
2331 
2332         need_swap = size > 1 && (tlb_addr & TLB_BSWAP);
2333 
2334         /* Handle I/O access.  */
2335         if (tlb_addr & TLB_MMIO) {
2336             io_writex(env, full, mmu_idx, val, addr, retaddr,
2337                       op ^ (need_swap * MO_BSWAP));
2338             return;
2339         }
2340 
2341         /* Ignore writes to ROM.  */
2342         if (unlikely(tlb_addr & TLB_DISCARD_WRITE)) {
2343             return;
2344         }
2345 
2346         /* Handle clean RAM pages.  */
2347         if (tlb_addr & TLB_NOTDIRTY) {
2348             notdirty_write(env_cpu(env), addr, size, full, retaddr);
2349         }
2350 
2351         haddr = (void *)((uintptr_t)addr + entry->addend);
2352 
2353         /*
2354          * Keep these two store_memop separate to ensure that the compiler
2355          * is able to fold the entire function to a single instruction.
2356          * There is a build-time assert inside to remind you of this.  ;-)
2357          */
2358         if (unlikely(need_swap)) {
2359             store_memop(haddr, val, op ^ MO_BSWAP);
2360         } else {
2361             store_memop(haddr, val, op);
2362         }
2363         return;
2364     }
2365 
2366     /* Handle slow unaligned access (it spans two pages or IO).  */
2367     if (size > 1
2368         && unlikely((addr & ~TARGET_PAGE_MASK) + size - 1
2369                      >= TARGET_PAGE_SIZE)) {
2370     do_unaligned_access:
2371         store_helper_unaligned(env, addr, val, retaddr, size,
2372                                mmu_idx, memop_big_endian(op));
2373         return;
2374     }
2375 
2376     haddr = (void *)((uintptr_t)addr + entry->addend);
2377     store_memop(haddr, val, op);
2378 }
2379 
2380 static void __attribute__((noinline))
2381 full_stb_mmu(CPUArchState *env, target_ulong addr, uint64_t val,
2382              MemOpIdx oi, uintptr_t retaddr)
2383 {
2384     validate_memop(oi, MO_UB);
2385     store_helper(env, addr, val, oi, retaddr, MO_UB);
2386 }
2387 
2388 void helper_ret_stb_mmu(CPUArchState *env, target_ulong addr, uint8_t val,
2389                         MemOpIdx oi, uintptr_t retaddr)
2390 {
2391     full_stb_mmu(env, addr, val, oi, retaddr);
2392 }
2393 
2394 static void full_le_stw_mmu(CPUArchState *env, target_ulong addr, uint64_t val,
2395                             MemOpIdx oi, uintptr_t retaddr)
2396 {
2397     validate_memop(oi, MO_LEUW);
2398     store_helper(env, addr, val, oi, retaddr, MO_LEUW);
2399 }
2400 
2401 void helper_le_stw_mmu(CPUArchState *env, target_ulong addr, uint16_t val,
2402                        MemOpIdx oi, uintptr_t retaddr)
2403 {
2404     full_le_stw_mmu(env, addr, val, oi, retaddr);
2405 }
2406 
2407 static void full_be_stw_mmu(CPUArchState *env, target_ulong addr, uint64_t val,
2408                             MemOpIdx oi, uintptr_t retaddr)
2409 {
2410     validate_memop(oi, MO_BEUW);
2411     store_helper(env, addr, val, oi, retaddr, MO_BEUW);
2412 }
2413 
2414 void helper_be_stw_mmu(CPUArchState *env, target_ulong addr, uint16_t val,
2415                        MemOpIdx oi, uintptr_t retaddr)
2416 {
2417     full_be_stw_mmu(env, addr, val, oi, retaddr);
2418 }
2419 
2420 static void full_le_stl_mmu(CPUArchState *env, target_ulong addr, uint64_t val,
2421                             MemOpIdx oi, uintptr_t retaddr)
2422 {
2423     validate_memop(oi, MO_LEUL);
2424     store_helper(env, addr, val, oi, retaddr, MO_LEUL);
2425 }
2426 
2427 void helper_le_stl_mmu(CPUArchState *env, target_ulong addr, uint32_t val,
2428                        MemOpIdx oi, uintptr_t retaddr)
2429 {
2430     full_le_stl_mmu(env, addr, val, oi, retaddr);
2431 }
2432 
2433 static void full_be_stl_mmu(CPUArchState *env, target_ulong addr, uint64_t val,
2434                             MemOpIdx oi, uintptr_t retaddr)
2435 {
2436     validate_memop(oi, MO_BEUL);
2437     store_helper(env, addr, val, oi, retaddr, MO_BEUL);
2438 }
2439 
2440 void helper_be_stl_mmu(CPUArchState *env, target_ulong addr, uint32_t val,
2441                        MemOpIdx oi, uintptr_t retaddr)
2442 {
2443     full_be_stl_mmu(env, addr, val, oi, retaddr);
2444 }
2445 
2446 void helper_le_stq_mmu(CPUArchState *env, target_ulong addr, uint64_t val,
2447                        MemOpIdx oi, uintptr_t retaddr)
2448 {
2449     validate_memop(oi, MO_LEUQ);
2450     store_helper(env, addr, val, oi, retaddr, MO_LEUQ);
2451 }
2452 
2453 void helper_be_stq_mmu(CPUArchState *env, target_ulong addr, uint64_t val,
2454                        MemOpIdx oi, uintptr_t retaddr)
2455 {
2456     validate_memop(oi, MO_BEUQ);
2457     store_helper(env, addr, val, oi, retaddr, MO_BEUQ);
2458 }
2459 
2460 /*
2461  * Store Helpers for cpu_ldst.h
2462  */
2463 
2464 typedef void FullStoreHelper(CPUArchState *env, target_ulong addr,
2465                              uint64_t val, MemOpIdx oi, uintptr_t retaddr);
2466 
2467 static inline void cpu_store_helper(CPUArchState *env, target_ulong addr,
2468                                     uint64_t val, MemOpIdx oi, uintptr_t ra,
2469                                     FullStoreHelper *full_store)
2470 {
2471     full_store(env, addr, val, oi, ra);
2472     qemu_plugin_vcpu_mem_cb(env_cpu(env), addr, oi, QEMU_PLUGIN_MEM_W);
2473 }
2474 
2475 void cpu_stb_mmu(CPUArchState *env, target_ulong addr, uint8_t val,
2476                  MemOpIdx oi, uintptr_t retaddr)
2477 {
2478     cpu_store_helper(env, addr, val, oi, retaddr, full_stb_mmu);
2479 }
2480 
2481 void cpu_stw_be_mmu(CPUArchState *env, target_ulong addr, uint16_t val,
2482                     MemOpIdx oi, uintptr_t retaddr)
2483 {
2484     cpu_store_helper(env, addr, val, oi, retaddr, full_be_stw_mmu);
2485 }
2486 
2487 void cpu_stl_be_mmu(CPUArchState *env, target_ulong addr, uint32_t val,
2488                     MemOpIdx oi, uintptr_t retaddr)
2489 {
2490     cpu_store_helper(env, addr, val, oi, retaddr, full_be_stl_mmu);
2491 }
2492 
2493 void cpu_stq_be_mmu(CPUArchState *env, target_ulong addr, uint64_t val,
2494                     MemOpIdx oi, uintptr_t retaddr)
2495 {
2496     cpu_store_helper(env, addr, val, oi, retaddr, helper_be_stq_mmu);
2497 }
2498 
2499 void cpu_stw_le_mmu(CPUArchState *env, target_ulong addr, uint16_t val,
2500                     MemOpIdx oi, uintptr_t retaddr)
2501 {
2502     cpu_store_helper(env, addr, val, oi, retaddr, full_le_stw_mmu);
2503 }
2504 
2505 void cpu_stl_le_mmu(CPUArchState *env, target_ulong addr, uint32_t val,
2506                     MemOpIdx oi, uintptr_t retaddr)
2507 {
2508     cpu_store_helper(env, addr, val, oi, retaddr, full_le_stl_mmu);
2509 }
2510 
2511 void cpu_stq_le_mmu(CPUArchState *env, target_ulong addr, uint64_t val,
2512                     MemOpIdx oi, uintptr_t retaddr)
2513 {
2514     cpu_store_helper(env, addr, val, oi, retaddr, helper_le_stq_mmu);
2515 }
2516 
2517 #include "ldst_common.c.inc"
2518 
2519 /*
2520  * First set of functions passes in OI and RETADDR.
2521  * This makes them callable from other helpers.
2522  */
2523 
2524 #define ATOMIC_NAME(X) \
2525     glue(glue(glue(cpu_atomic_ ## X, SUFFIX), END), _mmu)
2526 
2527 #define ATOMIC_MMU_CLEANUP
2528 
2529 #include "atomic_common.c.inc"
2530 
2531 #define DATA_SIZE 1
2532 #include "atomic_template.h"
2533 
2534 #define DATA_SIZE 2
2535 #include "atomic_template.h"
2536 
2537 #define DATA_SIZE 4
2538 #include "atomic_template.h"
2539 
2540 #ifdef CONFIG_ATOMIC64
2541 #define DATA_SIZE 8
2542 #include "atomic_template.h"
2543 #endif
2544 
2545 #if HAVE_CMPXCHG128 || HAVE_ATOMIC128
2546 #define DATA_SIZE 16
2547 #include "atomic_template.h"
2548 #endif
2549 
2550 /* Code access functions.  */
2551 
2552 static uint64_t full_ldub_code(CPUArchState *env, target_ulong addr,
2553                                MemOpIdx oi, uintptr_t retaddr)
2554 {
2555     return load_helper(env, addr, oi, retaddr, MO_8, true, full_ldub_code);
2556 }
2557 
2558 uint32_t cpu_ldub_code(CPUArchState *env, abi_ptr addr)
2559 {
2560     MemOpIdx oi = make_memop_idx(MO_UB, cpu_mmu_index(env, true));
2561     return full_ldub_code(env, addr, oi, 0);
2562 }
2563 
2564 static uint64_t full_lduw_code(CPUArchState *env, target_ulong addr,
2565                                MemOpIdx oi, uintptr_t retaddr)
2566 {
2567     return load_helper(env, addr, oi, retaddr, MO_TEUW, true, full_lduw_code);
2568 }
2569 
2570 uint32_t cpu_lduw_code(CPUArchState *env, abi_ptr addr)
2571 {
2572     MemOpIdx oi = make_memop_idx(MO_TEUW, cpu_mmu_index(env, true));
2573     return full_lduw_code(env, addr, oi, 0);
2574 }
2575 
2576 static uint64_t full_ldl_code(CPUArchState *env, target_ulong addr,
2577                               MemOpIdx oi, uintptr_t retaddr)
2578 {
2579     return load_helper(env, addr, oi, retaddr, MO_TEUL, true, full_ldl_code);
2580 }
2581 
2582 uint32_t cpu_ldl_code(CPUArchState *env, abi_ptr addr)
2583 {
2584     MemOpIdx oi = make_memop_idx(MO_TEUL, cpu_mmu_index(env, true));
2585     return full_ldl_code(env, addr, oi, 0);
2586 }
2587 
2588 static uint64_t full_ldq_code(CPUArchState *env, target_ulong addr,
2589                               MemOpIdx oi, uintptr_t retaddr)
2590 {
2591     return load_helper(env, addr, oi, retaddr, MO_TEUQ, true, full_ldq_code);
2592 }
2593 
2594 uint64_t cpu_ldq_code(CPUArchState *env, abi_ptr addr)
2595 {
2596     MemOpIdx oi = make_memop_idx(MO_TEUQ, cpu_mmu_index(env, true));
2597     return full_ldq_code(env, addr, oi, 0);
2598 }
2599