xref: /openbmc/qemu/accel/tcg/cputlb.c (revision a1264259)
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-common.h"
33 #include "qemu/atomic.h"
34 #include "qemu/atomic128.h"
35 #include "exec/translate-all.h"
36 #include "trace.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 #include "tcg/oversized-guest.h"
44 
45 /* DEBUG defines, enable DEBUG_TLB_LOG to log to the CPU_LOG_MMU target */
46 /* #define DEBUG_TLB */
47 /* #define DEBUG_TLB_LOG */
48 
49 #ifdef DEBUG_TLB
50 # define DEBUG_TLB_GATE 1
51 # ifdef DEBUG_TLB_LOG
52 #  define DEBUG_TLB_LOG_GATE 1
53 # else
54 #  define DEBUG_TLB_LOG_GATE 0
55 # endif
56 #else
57 # define DEBUG_TLB_GATE 0
58 # define DEBUG_TLB_LOG_GATE 0
59 #endif
60 
61 #define tlb_debug(fmt, ...) do { \
62     if (DEBUG_TLB_LOG_GATE) { \
63         qemu_log_mask(CPU_LOG_MMU, "%s: " fmt, __func__, \
64                       ## __VA_ARGS__); \
65     } else if (DEBUG_TLB_GATE) { \
66         fprintf(stderr, "%s: " fmt, __func__, ## __VA_ARGS__); \
67     } \
68 } while (0)
69 
70 #define assert_cpu_is_self(cpu) do {                              \
71         if (DEBUG_TLB_GATE) {                                     \
72             g_assert(!(cpu)->created || qemu_cpu_is_self(cpu));   \
73         }                                                         \
74     } while (0)
75 
76 /* run_on_cpu_data.target_ptr should always be big enough for a
77  * vaddr even on 32 bit builds
78  */
79 QEMU_BUILD_BUG_ON(sizeof(vaddr) > sizeof(run_on_cpu_data));
80 
81 /* We currently can't handle more than 16 bits in the MMUIDX bitmask.
82  */
83 QEMU_BUILD_BUG_ON(NB_MMU_MODES > 16);
84 #define ALL_MMUIDX_BITS ((1 << NB_MMU_MODES) - 1)
85 
86 static inline size_t tlb_n_entries(CPUTLBDescFast *fast)
87 {
88     return (fast->mask >> CPU_TLB_ENTRY_BITS) + 1;
89 }
90 
91 static inline size_t sizeof_tlb(CPUTLBDescFast *fast)
92 {
93     return fast->mask + (1 << CPU_TLB_ENTRY_BITS);
94 }
95 
96 static void tlb_window_reset(CPUTLBDesc *desc, int64_t ns,
97                              size_t max_entries)
98 {
99     desc->window_begin_ns = ns;
100     desc->window_max_entries = max_entries;
101 }
102 
103 static void tb_jmp_cache_clear_page(CPUState *cpu, vaddr page_addr)
104 {
105     CPUJumpCache *jc = cpu->tb_jmp_cache;
106     int i, i0;
107 
108     if (unlikely(!jc)) {
109         return;
110     }
111 
112     i0 = tb_jmp_cache_hash_page(page_addr);
113     for (i = 0; i < TB_JMP_PAGE_SIZE; i++) {
114         qatomic_set(&jc->array[i0 + i].tb, NULL);
115     }
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     tcg_flush_jmp_cache(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                                       vaddr page, vaddr 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, vaddr page)
442 {
443     return tlb_hit_page_mask_anyprot(tlb_entry, page, -1);
444 }
445 
446 /**
447  * tlb_entry_is_empty - return true if the entry is not in use
448  * @te: pointer to CPUTLBEntry
449  */
450 static inline bool tlb_entry_is_empty(const CPUTLBEntry *te)
451 {
452     return te->addr_read == -1 && te->addr_write == -1 && te->addr_code == -1;
453 }
454 
455 /* Called with tlb_c.lock held */
456 static bool tlb_flush_entry_mask_locked(CPUTLBEntry *tlb_entry,
457                                         vaddr page,
458                                         vaddr mask)
459 {
460     if (tlb_hit_page_mask_anyprot(tlb_entry, page, mask)) {
461         memset(tlb_entry, -1, sizeof(*tlb_entry));
462         return true;
463     }
464     return false;
465 }
466 
467 static inline bool tlb_flush_entry_locked(CPUTLBEntry *tlb_entry, vaddr page)
468 {
469     return tlb_flush_entry_mask_locked(tlb_entry, page, -1);
470 }
471 
472 /* Called with tlb_c.lock held */
473 static void tlb_flush_vtlb_page_mask_locked(CPUArchState *env, int mmu_idx,
474                                             vaddr page,
475                                             vaddr mask)
476 {
477     CPUTLBDesc *d = &env_tlb(env)->d[mmu_idx];
478     int k;
479 
480     assert_cpu_is_self(env_cpu(env));
481     for (k = 0; k < CPU_VTLB_SIZE; k++) {
482         if (tlb_flush_entry_mask_locked(&d->vtable[k], page, mask)) {
483             tlb_n_used_entries_dec(env, mmu_idx);
484         }
485     }
486 }
487 
488 static inline void tlb_flush_vtlb_page_locked(CPUArchState *env, int mmu_idx,
489                                               vaddr page)
490 {
491     tlb_flush_vtlb_page_mask_locked(env, mmu_idx, page, -1);
492 }
493 
494 static void tlb_flush_page_locked(CPUArchState *env, int midx, vaddr page)
495 {
496     vaddr lp_addr = env_tlb(env)->d[midx].large_page_addr;
497     vaddr lp_mask = env_tlb(env)->d[midx].large_page_mask;
498 
499     /* Check if we need to flush due to large pages.  */
500     if ((page & lp_mask) == lp_addr) {
501         tlb_debug("forcing full flush midx %d (%016"
502                   VADDR_PRIx "/%016" VADDR_PRIx ")\n",
503                   midx, lp_addr, lp_mask);
504         tlb_flush_one_mmuidx_locked(env, midx, get_clock_realtime());
505     } else {
506         if (tlb_flush_entry_locked(tlb_entry(env, midx, page), page)) {
507             tlb_n_used_entries_dec(env, midx);
508         }
509         tlb_flush_vtlb_page_locked(env, midx, page);
510     }
511 }
512 
513 /**
514  * tlb_flush_page_by_mmuidx_async_0:
515  * @cpu: cpu on which to flush
516  * @addr: page of virtual address to flush
517  * @idxmap: set of mmu_idx to flush
518  *
519  * Helper for tlb_flush_page_by_mmuidx and friends, flush one page
520  * at @addr from the tlbs indicated by @idxmap from @cpu.
521  */
522 static void tlb_flush_page_by_mmuidx_async_0(CPUState *cpu,
523                                              vaddr addr,
524                                              uint16_t idxmap)
525 {
526     CPUArchState *env = cpu->env_ptr;
527     int mmu_idx;
528 
529     assert_cpu_is_self(cpu);
530 
531     tlb_debug("page addr: %016" VADDR_PRIx " mmu_map:0x%x\n", addr, idxmap);
532 
533     qemu_spin_lock(&env_tlb(env)->c.lock);
534     for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
535         if ((idxmap >> mmu_idx) & 1) {
536             tlb_flush_page_locked(env, mmu_idx, addr);
537         }
538     }
539     qemu_spin_unlock(&env_tlb(env)->c.lock);
540 
541     /*
542      * Discard jump cache entries for any tb which might potentially
543      * overlap the flushed page, which includes the previous.
544      */
545     tb_jmp_cache_clear_page(cpu, addr - TARGET_PAGE_SIZE);
546     tb_jmp_cache_clear_page(cpu, addr);
547 }
548 
549 /**
550  * tlb_flush_page_by_mmuidx_async_1:
551  * @cpu: cpu on which to flush
552  * @data: encoded addr + idxmap
553  *
554  * Helper for tlb_flush_page_by_mmuidx and friends, called through
555  * async_run_on_cpu.  The idxmap parameter is encoded in the page
556  * offset of the target_ptr field.  This limits the set of mmu_idx
557  * that can be passed via this method.
558  */
559 static void tlb_flush_page_by_mmuidx_async_1(CPUState *cpu,
560                                              run_on_cpu_data data)
561 {
562     vaddr addr_and_idxmap = data.target_ptr;
563     vaddr addr = addr_and_idxmap & TARGET_PAGE_MASK;
564     uint16_t idxmap = addr_and_idxmap & ~TARGET_PAGE_MASK;
565 
566     tlb_flush_page_by_mmuidx_async_0(cpu, addr, idxmap);
567 }
568 
569 typedef struct {
570     vaddr addr;
571     uint16_t idxmap;
572 } TLBFlushPageByMMUIdxData;
573 
574 /**
575  * tlb_flush_page_by_mmuidx_async_2:
576  * @cpu: cpu on which to flush
577  * @data: allocated addr + idxmap
578  *
579  * Helper for tlb_flush_page_by_mmuidx and friends, called through
580  * async_run_on_cpu.  The addr+idxmap parameters are stored in a
581  * TLBFlushPageByMMUIdxData structure that has been allocated
582  * specifically for this helper.  Free the structure when done.
583  */
584 static void tlb_flush_page_by_mmuidx_async_2(CPUState *cpu,
585                                              run_on_cpu_data data)
586 {
587     TLBFlushPageByMMUIdxData *d = data.host_ptr;
588 
589     tlb_flush_page_by_mmuidx_async_0(cpu, d->addr, d->idxmap);
590     g_free(d);
591 }
592 
593 void tlb_flush_page_by_mmuidx(CPUState *cpu, vaddr addr, uint16_t idxmap)
594 {
595     tlb_debug("addr: %016" VADDR_PRIx " mmu_idx:%" PRIx16 "\n", addr, idxmap);
596 
597     /* This should already be page aligned */
598     addr &= TARGET_PAGE_MASK;
599 
600     if (qemu_cpu_is_self(cpu)) {
601         tlb_flush_page_by_mmuidx_async_0(cpu, addr, idxmap);
602     } else if (idxmap < TARGET_PAGE_SIZE) {
603         /*
604          * Most targets have only a few mmu_idx.  In the case where
605          * we can stuff idxmap into the low TARGET_PAGE_BITS, avoid
606          * allocating memory for this operation.
607          */
608         async_run_on_cpu(cpu, tlb_flush_page_by_mmuidx_async_1,
609                          RUN_ON_CPU_TARGET_PTR(addr | idxmap));
610     } else {
611         TLBFlushPageByMMUIdxData *d = g_new(TLBFlushPageByMMUIdxData, 1);
612 
613         /* Otherwise allocate a structure, freed by the worker.  */
614         d->addr = addr;
615         d->idxmap = idxmap;
616         async_run_on_cpu(cpu, tlb_flush_page_by_mmuidx_async_2,
617                          RUN_ON_CPU_HOST_PTR(d));
618     }
619 }
620 
621 void tlb_flush_page(CPUState *cpu, vaddr addr)
622 {
623     tlb_flush_page_by_mmuidx(cpu, addr, ALL_MMUIDX_BITS);
624 }
625 
626 void tlb_flush_page_by_mmuidx_all_cpus(CPUState *src_cpu, vaddr addr,
627                                        uint16_t idxmap)
628 {
629     tlb_debug("addr: %016" VADDR_PRIx " mmu_idx:%"PRIx16"\n", addr, idxmap);
630 
631     /* This should already be page aligned */
632     addr &= TARGET_PAGE_MASK;
633 
634     /*
635      * Allocate memory to hold addr+idxmap only when needed.
636      * See tlb_flush_page_by_mmuidx for details.
637      */
638     if (idxmap < TARGET_PAGE_SIZE) {
639         flush_all_helper(src_cpu, tlb_flush_page_by_mmuidx_async_1,
640                          RUN_ON_CPU_TARGET_PTR(addr | idxmap));
641     } else {
642         CPUState *dst_cpu;
643 
644         /* Allocate a separate data block for each destination cpu.  */
645         CPU_FOREACH(dst_cpu) {
646             if (dst_cpu != src_cpu) {
647                 TLBFlushPageByMMUIdxData *d
648                     = g_new(TLBFlushPageByMMUIdxData, 1);
649 
650                 d->addr = addr;
651                 d->idxmap = idxmap;
652                 async_run_on_cpu(dst_cpu, tlb_flush_page_by_mmuidx_async_2,
653                                  RUN_ON_CPU_HOST_PTR(d));
654             }
655         }
656     }
657 
658     tlb_flush_page_by_mmuidx_async_0(src_cpu, addr, idxmap);
659 }
660 
661 void tlb_flush_page_all_cpus(CPUState *src, vaddr addr)
662 {
663     tlb_flush_page_by_mmuidx_all_cpus(src, addr, ALL_MMUIDX_BITS);
664 }
665 
666 void tlb_flush_page_by_mmuidx_all_cpus_synced(CPUState *src_cpu,
667                                               vaddr addr,
668                                               uint16_t idxmap)
669 {
670     tlb_debug("addr: %016" VADDR_PRIx " mmu_idx:%"PRIx16"\n", addr, idxmap);
671 
672     /* This should already be page aligned */
673     addr &= TARGET_PAGE_MASK;
674 
675     /*
676      * Allocate memory to hold addr+idxmap only when needed.
677      * See tlb_flush_page_by_mmuidx for details.
678      */
679     if (idxmap < TARGET_PAGE_SIZE) {
680         flush_all_helper(src_cpu, tlb_flush_page_by_mmuidx_async_1,
681                          RUN_ON_CPU_TARGET_PTR(addr | idxmap));
682         async_safe_run_on_cpu(src_cpu, tlb_flush_page_by_mmuidx_async_1,
683                               RUN_ON_CPU_TARGET_PTR(addr | idxmap));
684     } else {
685         CPUState *dst_cpu;
686         TLBFlushPageByMMUIdxData *d;
687 
688         /* Allocate a separate data block for each destination cpu.  */
689         CPU_FOREACH(dst_cpu) {
690             if (dst_cpu != src_cpu) {
691                 d = g_new(TLBFlushPageByMMUIdxData, 1);
692                 d->addr = addr;
693                 d->idxmap = idxmap;
694                 async_run_on_cpu(dst_cpu, tlb_flush_page_by_mmuidx_async_2,
695                                  RUN_ON_CPU_HOST_PTR(d));
696             }
697         }
698 
699         d = g_new(TLBFlushPageByMMUIdxData, 1);
700         d->addr = addr;
701         d->idxmap = idxmap;
702         async_safe_run_on_cpu(src_cpu, tlb_flush_page_by_mmuidx_async_2,
703                               RUN_ON_CPU_HOST_PTR(d));
704     }
705 }
706 
707 void tlb_flush_page_all_cpus_synced(CPUState *src, vaddr addr)
708 {
709     tlb_flush_page_by_mmuidx_all_cpus_synced(src, addr, ALL_MMUIDX_BITS);
710 }
711 
712 static void tlb_flush_range_locked(CPUArchState *env, int midx,
713                                    vaddr addr, vaddr len,
714                                    unsigned bits)
715 {
716     CPUTLBDesc *d = &env_tlb(env)->d[midx];
717     CPUTLBDescFast *f = &env_tlb(env)->f[midx];
718     vaddr mask = MAKE_64BIT_MASK(0, bits);
719 
720     /*
721      * If @bits is smaller than the tlb size, there may be multiple entries
722      * within the TLB; otherwise all addresses that match under @mask hit
723      * the same TLB entry.
724      * TODO: Perhaps allow bits to be a few bits less than the size.
725      * For now, just flush the entire TLB.
726      *
727      * If @len is larger than the tlb size, then it will take longer to
728      * test all of the entries in the TLB than it will to flush it all.
729      */
730     if (mask < f->mask || len > f->mask) {
731         tlb_debug("forcing full flush midx %d ("
732                   "%016" VADDR_PRIx "/%016" VADDR_PRIx "+%016" VADDR_PRIx ")\n",
733                   midx, addr, mask, len);
734         tlb_flush_one_mmuidx_locked(env, midx, get_clock_realtime());
735         return;
736     }
737 
738     /*
739      * Check if we need to flush due to large pages.
740      * Because large_page_mask contains all 1's from the msb,
741      * we only need to test the end of the range.
742      */
743     if (((addr + len - 1) & d->large_page_mask) == d->large_page_addr) {
744         tlb_debug("forcing full flush midx %d ("
745                   "%016" VADDR_PRIx "/%016" VADDR_PRIx ")\n",
746                   midx, d->large_page_addr, d->large_page_mask);
747         tlb_flush_one_mmuidx_locked(env, midx, get_clock_realtime());
748         return;
749     }
750 
751     for (vaddr i = 0; i < len; i += TARGET_PAGE_SIZE) {
752         vaddr page = addr + i;
753         CPUTLBEntry *entry = tlb_entry(env, midx, page);
754 
755         if (tlb_flush_entry_mask_locked(entry, page, mask)) {
756             tlb_n_used_entries_dec(env, midx);
757         }
758         tlb_flush_vtlb_page_mask_locked(env, midx, page, mask);
759     }
760 }
761 
762 typedef struct {
763     vaddr addr;
764     vaddr len;
765     uint16_t idxmap;
766     uint16_t bits;
767 } TLBFlushRangeData;
768 
769 static void tlb_flush_range_by_mmuidx_async_0(CPUState *cpu,
770                                               TLBFlushRangeData d)
771 {
772     CPUArchState *env = cpu->env_ptr;
773     int mmu_idx;
774 
775     assert_cpu_is_self(cpu);
776 
777     tlb_debug("range: %016" VADDR_PRIx "/%u+%016" VADDR_PRIx " mmu_map:0x%x\n",
778               d.addr, d.bits, d.len, d.idxmap);
779 
780     qemu_spin_lock(&env_tlb(env)->c.lock);
781     for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
782         if ((d.idxmap >> mmu_idx) & 1) {
783             tlb_flush_range_locked(env, mmu_idx, d.addr, d.len, d.bits);
784         }
785     }
786     qemu_spin_unlock(&env_tlb(env)->c.lock);
787 
788     /*
789      * If the length is larger than the jump cache size, then it will take
790      * longer to clear each entry individually than it will to clear it all.
791      */
792     if (d.len >= (TARGET_PAGE_SIZE * TB_JMP_CACHE_SIZE)) {
793         tcg_flush_jmp_cache(cpu);
794         return;
795     }
796 
797     /*
798      * Discard jump cache entries for any tb which might potentially
799      * overlap the flushed pages, which includes the previous.
800      */
801     d.addr -= TARGET_PAGE_SIZE;
802     for (vaddr i = 0, n = d.len / TARGET_PAGE_SIZE + 1; i < n; i++) {
803         tb_jmp_cache_clear_page(cpu, d.addr);
804         d.addr += TARGET_PAGE_SIZE;
805     }
806 }
807 
808 static void tlb_flush_range_by_mmuidx_async_1(CPUState *cpu,
809                                               run_on_cpu_data data)
810 {
811     TLBFlushRangeData *d = data.host_ptr;
812     tlb_flush_range_by_mmuidx_async_0(cpu, *d);
813     g_free(d);
814 }
815 
816 void tlb_flush_range_by_mmuidx(CPUState *cpu, vaddr addr,
817                                vaddr len, uint16_t idxmap,
818                                unsigned bits)
819 {
820     TLBFlushRangeData d;
821 
822     /*
823      * If all bits are significant, and len is small,
824      * this devolves to tlb_flush_page.
825      */
826     if (bits >= TARGET_LONG_BITS && len <= TARGET_PAGE_SIZE) {
827         tlb_flush_page_by_mmuidx(cpu, addr, idxmap);
828         return;
829     }
830     /* If no page bits are significant, this devolves to tlb_flush. */
831     if (bits < TARGET_PAGE_BITS) {
832         tlb_flush_by_mmuidx(cpu, idxmap);
833         return;
834     }
835 
836     /* This should already be page aligned */
837     d.addr = addr & TARGET_PAGE_MASK;
838     d.len = len;
839     d.idxmap = idxmap;
840     d.bits = bits;
841 
842     if (qemu_cpu_is_self(cpu)) {
843         tlb_flush_range_by_mmuidx_async_0(cpu, d);
844     } else {
845         /* Otherwise allocate a structure, freed by the worker.  */
846         TLBFlushRangeData *p = g_memdup(&d, sizeof(d));
847         async_run_on_cpu(cpu, tlb_flush_range_by_mmuidx_async_1,
848                          RUN_ON_CPU_HOST_PTR(p));
849     }
850 }
851 
852 void tlb_flush_page_bits_by_mmuidx(CPUState *cpu, vaddr addr,
853                                    uint16_t idxmap, unsigned bits)
854 {
855     tlb_flush_range_by_mmuidx(cpu, addr, TARGET_PAGE_SIZE, idxmap, bits);
856 }
857 
858 void tlb_flush_range_by_mmuidx_all_cpus(CPUState *src_cpu,
859                                         vaddr addr, vaddr len,
860                                         uint16_t idxmap, unsigned bits)
861 {
862     TLBFlushRangeData d;
863     CPUState *dst_cpu;
864 
865     /*
866      * If all bits are significant, and len is small,
867      * this devolves to tlb_flush_page.
868      */
869     if (bits >= TARGET_LONG_BITS && len <= TARGET_PAGE_SIZE) {
870         tlb_flush_page_by_mmuidx_all_cpus(src_cpu, addr, idxmap);
871         return;
872     }
873     /* If no page bits are significant, this devolves to tlb_flush. */
874     if (bits < TARGET_PAGE_BITS) {
875         tlb_flush_by_mmuidx_all_cpus(src_cpu, idxmap);
876         return;
877     }
878 
879     /* This should already be page aligned */
880     d.addr = addr & TARGET_PAGE_MASK;
881     d.len = len;
882     d.idxmap = idxmap;
883     d.bits = bits;
884 
885     /* Allocate a separate data block for each destination cpu.  */
886     CPU_FOREACH(dst_cpu) {
887         if (dst_cpu != src_cpu) {
888             TLBFlushRangeData *p = g_memdup(&d, sizeof(d));
889             async_run_on_cpu(dst_cpu,
890                              tlb_flush_range_by_mmuidx_async_1,
891                              RUN_ON_CPU_HOST_PTR(p));
892         }
893     }
894 
895     tlb_flush_range_by_mmuidx_async_0(src_cpu, d);
896 }
897 
898 void tlb_flush_page_bits_by_mmuidx_all_cpus(CPUState *src_cpu,
899                                             vaddr addr, uint16_t idxmap,
900                                             unsigned bits)
901 {
902     tlb_flush_range_by_mmuidx_all_cpus(src_cpu, addr, TARGET_PAGE_SIZE,
903                                        idxmap, bits);
904 }
905 
906 void tlb_flush_range_by_mmuidx_all_cpus_synced(CPUState *src_cpu,
907                                                vaddr addr,
908                                                vaddr len,
909                                                uint16_t idxmap,
910                                                unsigned bits)
911 {
912     TLBFlushRangeData d, *p;
913     CPUState *dst_cpu;
914 
915     /*
916      * If all bits are significant, and len is small,
917      * this devolves to tlb_flush_page.
918      */
919     if (bits >= TARGET_LONG_BITS && len <= TARGET_PAGE_SIZE) {
920         tlb_flush_page_by_mmuidx_all_cpus_synced(src_cpu, addr, idxmap);
921         return;
922     }
923     /* If no page bits are significant, this devolves to tlb_flush. */
924     if (bits < TARGET_PAGE_BITS) {
925         tlb_flush_by_mmuidx_all_cpus_synced(src_cpu, idxmap);
926         return;
927     }
928 
929     /* This should already be page aligned */
930     d.addr = addr & TARGET_PAGE_MASK;
931     d.len = len;
932     d.idxmap = idxmap;
933     d.bits = bits;
934 
935     /* Allocate a separate data block for each destination cpu.  */
936     CPU_FOREACH(dst_cpu) {
937         if (dst_cpu != src_cpu) {
938             p = g_memdup(&d, sizeof(d));
939             async_run_on_cpu(dst_cpu, tlb_flush_range_by_mmuidx_async_1,
940                              RUN_ON_CPU_HOST_PTR(p));
941         }
942     }
943 
944     p = g_memdup(&d, sizeof(d));
945     async_safe_run_on_cpu(src_cpu, tlb_flush_range_by_mmuidx_async_1,
946                           RUN_ON_CPU_HOST_PTR(p));
947 }
948 
949 void tlb_flush_page_bits_by_mmuidx_all_cpus_synced(CPUState *src_cpu,
950                                                    vaddr addr,
951                                                    uint16_t idxmap,
952                                                    unsigned bits)
953 {
954     tlb_flush_range_by_mmuidx_all_cpus_synced(src_cpu, addr, TARGET_PAGE_SIZE,
955                                               idxmap, bits);
956 }
957 
958 /* update the TLBs so that writes to code in the virtual page 'addr'
959    can be detected */
960 void tlb_protect_code(ram_addr_t ram_addr)
961 {
962     cpu_physical_memory_test_and_clear_dirty(ram_addr & TARGET_PAGE_MASK,
963                                              TARGET_PAGE_SIZE,
964                                              DIRTY_MEMORY_CODE);
965 }
966 
967 /* update the TLB so that writes in physical page 'phys_addr' are no longer
968    tested for self modifying code */
969 void tlb_unprotect_code(ram_addr_t ram_addr)
970 {
971     cpu_physical_memory_set_dirty_flag(ram_addr, DIRTY_MEMORY_CODE);
972 }
973 
974 
975 /*
976  * Dirty write flag handling
977  *
978  * When the TCG code writes to a location it looks up the address in
979  * the TLB and uses that data to compute the final address. If any of
980  * the lower bits of the address are set then the slow path is forced.
981  * There are a number of reasons to do this but for normal RAM the
982  * most usual is detecting writes to code regions which may invalidate
983  * generated code.
984  *
985  * Other vCPUs might be reading their TLBs during guest execution, so we update
986  * te->addr_write with qatomic_set. We don't need to worry about this for
987  * oversized guests as MTTCG is disabled for them.
988  *
989  * Called with tlb_c.lock held.
990  */
991 static void tlb_reset_dirty_range_locked(CPUTLBEntry *tlb_entry,
992                                          uintptr_t start, uintptr_t length)
993 {
994     uintptr_t addr = tlb_entry->addr_write;
995 
996     if ((addr & (TLB_INVALID_MASK | TLB_MMIO |
997                  TLB_DISCARD_WRITE | TLB_NOTDIRTY)) == 0) {
998         addr &= TARGET_PAGE_MASK;
999         addr += tlb_entry->addend;
1000         if ((addr - start) < length) {
1001 #if TARGET_LONG_BITS == 32
1002             uint32_t *ptr_write = (uint32_t *)&tlb_entry->addr_write;
1003             ptr_write += HOST_BIG_ENDIAN;
1004             qatomic_set(ptr_write, *ptr_write | TLB_NOTDIRTY);
1005 #elif TCG_OVERSIZED_GUEST
1006             tlb_entry->addr_write |= TLB_NOTDIRTY;
1007 #else
1008             qatomic_set(&tlb_entry->addr_write,
1009                         tlb_entry->addr_write | TLB_NOTDIRTY);
1010 #endif
1011         }
1012     }
1013 }
1014 
1015 /*
1016  * Called with tlb_c.lock held.
1017  * Called only from the vCPU context, i.e. the TLB's owner thread.
1018  */
1019 static inline void copy_tlb_helper_locked(CPUTLBEntry *d, const CPUTLBEntry *s)
1020 {
1021     *d = *s;
1022 }
1023 
1024 /* This is a cross vCPU call (i.e. another vCPU resetting the flags of
1025  * the target vCPU).
1026  * We must take tlb_c.lock to avoid racing with another vCPU update. The only
1027  * thing actually updated is the target TLB entry ->addr_write flags.
1028  */
1029 void tlb_reset_dirty(CPUState *cpu, ram_addr_t start1, ram_addr_t length)
1030 {
1031     CPUArchState *env;
1032 
1033     int mmu_idx;
1034 
1035     env = cpu->env_ptr;
1036     qemu_spin_lock(&env_tlb(env)->c.lock);
1037     for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
1038         unsigned int i;
1039         unsigned int n = tlb_n_entries(&env_tlb(env)->f[mmu_idx]);
1040 
1041         for (i = 0; i < n; i++) {
1042             tlb_reset_dirty_range_locked(&env_tlb(env)->f[mmu_idx].table[i],
1043                                          start1, length);
1044         }
1045 
1046         for (i = 0; i < CPU_VTLB_SIZE; i++) {
1047             tlb_reset_dirty_range_locked(&env_tlb(env)->d[mmu_idx].vtable[i],
1048                                          start1, length);
1049         }
1050     }
1051     qemu_spin_unlock(&env_tlb(env)->c.lock);
1052 }
1053 
1054 /* Called with tlb_c.lock held */
1055 static inline void tlb_set_dirty1_locked(CPUTLBEntry *tlb_entry,
1056                                          vaddr addr)
1057 {
1058     if (tlb_entry->addr_write == (addr | TLB_NOTDIRTY)) {
1059         tlb_entry->addr_write = addr;
1060     }
1061 }
1062 
1063 /* update the TLB corresponding to virtual page vaddr
1064    so that it is no longer dirty */
1065 void tlb_set_dirty(CPUState *cpu, vaddr addr)
1066 {
1067     CPUArchState *env = cpu->env_ptr;
1068     int mmu_idx;
1069 
1070     assert_cpu_is_self(cpu);
1071 
1072     addr &= TARGET_PAGE_MASK;
1073     qemu_spin_lock(&env_tlb(env)->c.lock);
1074     for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
1075         tlb_set_dirty1_locked(tlb_entry(env, mmu_idx, addr), addr);
1076     }
1077 
1078     for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {
1079         int k;
1080         for (k = 0; k < CPU_VTLB_SIZE; k++) {
1081             tlb_set_dirty1_locked(&env_tlb(env)->d[mmu_idx].vtable[k], addr);
1082         }
1083     }
1084     qemu_spin_unlock(&env_tlb(env)->c.lock);
1085 }
1086 
1087 /* Our TLB does not support large pages, so remember the area covered by
1088    large pages and trigger a full TLB flush if these are invalidated.  */
1089 static void tlb_add_large_page(CPUArchState *env, int mmu_idx,
1090                                vaddr addr, uint64_t size)
1091 {
1092     vaddr lp_addr = env_tlb(env)->d[mmu_idx].large_page_addr;
1093     vaddr lp_mask = ~(size - 1);
1094 
1095     if (lp_addr == (vaddr)-1) {
1096         /* No previous large page.  */
1097         lp_addr = addr;
1098     } else {
1099         /* Extend the existing region to include the new page.
1100            This is a compromise between unnecessary flushes and
1101            the cost of maintaining a full variable size TLB.  */
1102         lp_mask &= env_tlb(env)->d[mmu_idx].large_page_mask;
1103         while (((lp_addr ^ addr) & lp_mask) != 0) {
1104             lp_mask <<= 1;
1105         }
1106     }
1107     env_tlb(env)->d[mmu_idx].large_page_addr = lp_addr & lp_mask;
1108     env_tlb(env)->d[mmu_idx].large_page_mask = lp_mask;
1109 }
1110 
1111 static inline void tlb_set_compare(CPUTLBEntryFull *full, CPUTLBEntry *ent,
1112                                    vaddr address, int flags,
1113                                    MMUAccessType access_type, bool enable)
1114 {
1115     if (enable) {
1116         address |= flags & TLB_FLAGS_MASK;
1117         flags &= TLB_SLOW_FLAGS_MASK;
1118         if (flags) {
1119             address |= TLB_FORCE_SLOW;
1120         }
1121     } else {
1122         address = -1;
1123         flags = 0;
1124     }
1125     ent->addr_idx[access_type] = address;
1126     full->slow_flags[access_type] = flags;
1127 }
1128 
1129 /*
1130  * Add a new TLB entry. At most one entry for a given virtual address
1131  * is permitted. Only a single TARGET_PAGE_SIZE region is mapped, the
1132  * supplied size is only used by tlb_flush_page.
1133  *
1134  * Called from TCG-generated code, which is under an RCU read-side
1135  * critical section.
1136  */
1137 void tlb_set_page_full(CPUState *cpu, int mmu_idx,
1138                        vaddr addr, CPUTLBEntryFull *full)
1139 {
1140     CPUArchState *env = cpu->env_ptr;
1141     CPUTLB *tlb = env_tlb(env);
1142     CPUTLBDesc *desc = &tlb->d[mmu_idx];
1143     MemoryRegionSection *section;
1144     unsigned int index, read_flags, write_flags;
1145     uintptr_t addend;
1146     CPUTLBEntry *te, tn;
1147     hwaddr iotlb, xlat, sz, paddr_page;
1148     vaddr addr_page;
1149     int asidx, wp_flags, prot;
1150     bool is_ram, is_romd;
1151 
1152     assert_cpu_is_self(cpu);
1153 
1154     if (full->lg_page_size <= TARGET_PAGE_BITS) {
1155         sz = TARGET_PAGE_SIZE;
1156     } else {
1157         sz = (hwaddr)1 << full->lg_page_size;
1158         tlb_add_large_page(env, mmu_idx, addr, sz);
1159     }
1160     addr_page = addr & TARGET_PAGE_MASK;
1161     paddr_page = full->phys_addr & TARGET_PAGE_MASK;
1162 
1163     prot = full->prot;
1164     asidx = cpu_asidx_from_attrs(cpu, full->attrs);
1165     section = address_space_translate_for_iotlb(cpu, asidx, paddr_page,
1166                                                 &xlat, &sz, full->attrs, &prot);
1167     assert(sz >= TARGET_PAGE_SIZE);
1168 
1169     tlb_debug("vaddr=%016" VADDR_PRIx " paddr=0x" HWADDR_FMT_plx
1170               " prot=%x idx=%d\n",
1171               addr, full->phys_addr, prot, mmu_idx);
1172 
1173     read_flags = 0;
1174     if (full->lg_page_size < TARGET_PAGE_BITS) {
1175         /* Repeat the MMU check and TLB fill on every access.  */
1176         read_flags |= TLB_INVALID_MASK;
1177     }
1178     if (full->attrs.byte_swap) {
1179         read_flags |= TLB_BSWAP;
1180     }
1181 
1182     is_ram = memory_region_is_ram(section->mr);
1183     is_romd = memory_region_is_romd(section->mr);
1184 
1185     if (is_ram || is_romd) {
1186         /* RAM and ROMD both have associated host memory. */
1187         addend = (uintptr_t)memory_region_get_ram_ptr(section->mr) + xlat;
1188     } else {
1189         /* I/O does not; force the host address to NULL. */
1190         addend = 0;
1191     }
1192 
1193     write_flags = read_flags;
1194     if (is_ram) {
1195         iotlb = memory_region_get_ram_addr(section->mr) + xlat;
1196         /*
1197          * Computing is_clean is expensive; avoid all that unless
1198          * the page is actually writable.
1199          */
1200         if (prot & PAGE_WRITE) {
1201             if (section->readonly) {
1202                 write_flags |= TLB_DISCARD_WRITE;
1203             } else if (cpu_physical_memory_is_clean(iotlb)) {
1204                 write_flags |= TLB_NOTDIRTY;
1205             }
1206         }
1207     } else {
1208         /* I/O or ROMD */
1209         iotlb = memory_region_section_get_iotlb(cpu, section) + xlat;
1210         /*
1211          * Writes to romd devices must go through MMIO to enable write.
1212          * Reads to romd devices go through the ram_ptr found above,
1213          * but of course reads to I/O must go through MMIO.
1214          */
1215         write_flags |= TLB_MMIO;
1216         if (!is_romd) {
1217             read_flags = write_flags;
1218         }
1219     }
1220 
1221     wp_flags = cpu_watchpoint_address_matches(cpu, addr_page,
1222                                               TARGET_PAGE_SIZE);
1223 
1224     index = tlb_index(env, mmu_idx, addr_page);
1225     te = tlb_entry(env, mmu_idx, addr_page);
1226 
1227     /*
1228      * Hold the TLB lock for the rest of the function. We could acquire/release
1229      * the lock several times in the function, but it is faster to amortize the
1230      * acquisition cost by acquiring it just once. Note that this leads to
1231      * a longer critical section, but this is not a concern since the TLB lock
1232      * is unlikely to be contended.
1233      */
1234     qemu_spin_lock(&tlb->c.lock);
1235 
1236     /* Note that the tlb is no longer clean.  */
1237     tlb->c.dirty |= 1 << mmu_idx;
1238 
1239     /* Make sure there's no cached translation for the new page.  */
1240     tlb_flush_vtlb_page_locked(env, mmu_idx, addr_page);
1241 
1242     /*
1243      * Only evict the old entry to the victim tlb if it's for a
1244      * different page; otherwise just overwrite the stale data.
1245      */
1246     if (!tlb_hit_page_anyprot(te, addr_page) && !tlb_entry_is_empty(te)) {
1247         unsigned vidx = desc->vindex++ % CPU_VTLB_SIZE;
1248         CPUTLBEntry *tv = &desc->vtable[vidx];
1249 
1250         /* Evict the old entry into the victim tlb.  */
1251         copy_tlb_helper_locked(tv, te);
1252         desc->vfulltlb[vidx] = desc->fulltlb[index];
1253         tlb_n_used_entries_dec(env, mmu_idx);
1254     }
1255 
1256     /* refill the tlb */
1257     /*
1258      * At this point iotlb contains a physical section number in the lower
1259      * TARGET_PAGE_BITS, and either
1260      *  + the ram_addr_t of the page base of the target RAM (RAM)
1261      *  + the offset within section->mr of the page base (I/O, ROMD)
1262      * We subtract addr_page (which is page aligned and thus won't
1263      * disturb the low bits) to give an offset which can be added to the
1264      * (non-page-aligned) vaddr of the eventual memory access to get
1265      * the MemoryRegion offset for the access. Note that the vaddr we
1266      * subtract here is that of the page base, and not the same as the
1267      * vaddr we add back in io_readx()/io_writex()/get_page_addr_code().
1268      */
1269     desc->fulltlb[index] = *full;
1270     full = &desc->fulltlb[index];
1271     full->xlat_section = iotlb - addr_page;
1272     full->phys_addr = paddr_page;
1273 
1274     /* Now calculate the new entry */
1275     tn.addend = addend - addr_page;
1276 
1277     tlb_set_compare(full, &tn, addr_page, read_flags,
1278                     MMU_INST_FETCH, prot & PAGE_EXEC);
1279 
1280     if (wp_flags & BP_MEM_READ) {
1281         read_flags |= TLB_WATCHPOINT;
1282     }
1283     tlb_set_compare(full, &tn, addr_page, read_flags,
1284                     MMU_DATA_LOAD, prot & PAGE_READ);
1285 
1286     if (prot & PAGE_WRITE_INV) {
1287         write_flags |= TLB_INVALID_MASK;
1288     }
1289     if (wp_flags & BP_MEM_WRITE) {
1290         write_flags |= TLB_WATCHPOINT;
1291     }
1292     tlb_set_compare(full, &tn, addr_page, write_flags,
1293                     MMU_DATA_STORE, prot & PAGE_WRITE);
1294 
1295     copy_tlb_helper_locked(te, &tn);
1296     tlb_n_used_entries_inc(env, mmu_idx);
1297     qemu_spin_unlock(&tlb->c.lock);
1298 }
1299 
1300 void tlb_set_page_with_attrs(CPUState *cpu, vaddr addr,
1301                              hwaddr paddr, MemTxAttrs attrs, int prot,
1302                              int mmu_idx, uint64_t size)
1303 {
1304     CPUTLBEntryFull full = {
1305         .phys_addr = paddr,
1306         .attrs = attrs,
1307         .prot = prot,
1308         .lg_page_size = ctz64(size)
1309     };
1310 
1311     assert(is_power_of_2(size));
1312     tlb_set_page_full(cpu, mmu_idx, addr, &full);
1313 }
1314 
1315 void tlb_set_page(CPUState *cpu, vaddr addr,
1316                   hwaddr paddr, int prot,
1317                   int mmu_idx, uint64_t size)
1318 {
1319     tlb_set_page_with_attrs(cpu, addr, paddr, MEMTXATTRS_UNSPECIFIED,
1320                             prot, mmu_idx, size);
1321 }
1322 
1323 /*
1324  * Note: tlb_fill() can trigger a resize of the TLB. This means that all of the
1325  * caller's prior references to the TLB table (e.g. CPUTLBEntry pointers) must
1326  * be discarded and looked up again (e.g. via tlb_entry()).
1327  */
1328 static void tlb_fill(CPUState *cpu, vaddr addr, int size,
1329                      MMUAccessType access_type, int mmu_idx, uintptr_t retaddr)
1330 {
1331     bool ok;
1332 
1333     /*
1334      * This is not a probe, so only valid return is success; failure
1335      * should result in exception + longjmp to the cpu loop.
1336      */
1337     ok = cpu->cc->tcg_ops->tlb_fill(cpu, addr, size,
1338                                     access_type, mmu_idx, false, retaddr);
1339     assert(ok);
1340 }
1341 
1342 static inline void cpu_unaligned_access(CPUState *cpu, vaddr addr,
1343                                         MMUAccessType access_type,
1344                                         int mmu_idx, uintptr_t retaddr)
1345 {
1346     cpu->cc->tcg_ops->do_unaligned_access(cpu, addr, access_type,
1347                                           mmu_idx, retaddr);
1348 }
1349 
1350 static inline void cpu_transaction_failed(CPUState *cpu, hwaddr physaddr,
1351                                           vaddr addr, unsigned size,
1352                                           MMUAccessType access_type,
1353                                           int mmu_idx, MemTxAttrs attrs,
1354                                           MemTxResult response,
1355                                           uintptr_t retaddr)
1356 {
1357     CPUClass *cc = CPU_GET_CLASS(cpu);
1358 
1359     if (!cpu->ignore_memory_transaction_failures &&
1360         cc->tcg_ops->do_transaction_failed) {
1361         cc->tcg_ops->do_transaction_failed(cpu, physaddr, addr, size,
1362                                            access_type, mmu_idx, attrs,
1363                                            response, retaddr);
1364     }
1365 }
1366 
1367 /*
1368  * Save a potentially trashed CPUTLBEntryFull for later lookup by plugin.
1369  * This is read by tlb_plugin_lookup if the fulltlb entry doesn't match
1370  * because of the side effect of io_writex changing memory layout.
1371  */
1372 static void save_iotlb_data(CPUState *cs, MemoryRegionSection *section,
1373                             hwaddr mr_offset)
1374 {
1375 #ifdef CONFIG_PLUGIN
1376     SavedIOTLB *saved = &cs->saved_iotlb;
1377     saved->section = section;
1378     saved->mr_offset = mr_offset;
1379 #endif
1380 }
1381 
1382 static uint64_t io_readx(CPUArchState *env, CPUTLBEntryFull *full,
1383                          int mmu_idx, vaddr addr, uintptr_t retaddr,
1384                          MMUAccessType access_type, MemOp op)
1385 {
1386     CPUState *cpu = env_cpu(env);
1387     hwaddr mr_offset;
1388     MemoryRegionSection *section;
1389     MemoryRegion *mr;
1390     uint64_t val;
1391     MemTxResult r;
1392 
1393     section = iotlb_to_section(cpu, full->xlat_section, full->attrs);
1394     mr = section->mr;
1395     mr_offset = (full->xlat_section & TARGET_PAGE_MASK) + addr;
1396     cpu->mem_io_pc = retaddr;
1397     if (!cpu->can_do_io) {
1398         cpu_io_recompile(cpu, retaddr);
1399     }
1400 
1401     /*
1402      * The memory_region_dispatch may trigger a flush/resize
1403      * so for plugins we save the iotlb_data just in case.
1404      */
1405     save_iotlb_data(cpu, section, mr_offset);
1406 
1407     {
1408         QEMU_IOTHREAD_LOCK_GUARD();
1409         r = memory_region_dispatch_read(mr, mr_offset, &val, op, full->attrs);
1410     }
1411 
1412     if (r != MEMTX_OK) {
1413         hwaddr physaddr = mr_offset +
1414             section->offset_within_address_space -
1415             section->offset_within_region;
1416 
1417         cpu_transaction_failed(cpu, physaddr, addr, memop_size(op), access_type,
1418                                mmu_idx, full->attrs, r, retaddr);
1419     }
1420     return val;
1421 }
1422 
1423 static void io_writex(CPUArchState *env, CPUTLBEntryFull *full,
1424                       int mmu_idx, uint64_t val, vaddr addr,
1425                       uintptr_t retaddr, MemOp op)
1426 {
1427     CPUState *cpu = env_cpu(env);
1428     hwaddr mr_offset;
1429     MemoryRegionSection *section;
1430     MemoryRegion *mr;
1431     MemTxResult r;
1432 
1433     section = iotlb_to_section(cpu, full->xlat_section, full->attrs);
1434     mr = section->mr;
1435     mr_offset = (full->xlat_section & TARGET_PAGE_MASK) + addr;
1436     if (!cpu->can_do_io) {
1437         cpu_io_recompile(cpu, retaddr);
1438     }
1439     cpu->mem_io_pc = retaddr;
1440 
1441     /*
1442      * The memory_region_dispatch may trigger a flush/resize
1443      * so for plugins we save the iotlb_data just in case.
1444      */
1445     save_iotlb_data(cpu, section, mr_offset);
1446 
1447     {
1448         QEMU_IOTHREAD_LOCK_GUARD();
1449         r = memory_region_dispatch_write(mr, mr_offset, val, op, full->attrs);
1450     }
1451 
1452     if (r != MEMTX_OK) {
1453         hwaddr physaddr = mr_offset +
1454             section->offset_within_address_space -
1455             section->offset_within_region;
1456 
1457         cpu_transaction_failed(cpu, physaddr, addr, memop_size(op),
1458                                MMU_DATA_STORE, mmu_idx, full->attrs, r,
1459                                retaddr);
1460     }
1461 }
1462 
1463 /* Return true if ADDR is present in the victim tlb, and has been copied
1464    back to the main tlb.  */
1465 static bool victim_tlb_hit(CPUArchState *env, size_t mmu_idx, size_t index,
1466                            MMUAccessType access_type, vaddr page)
1467 {
1468     size_t vidx;
1469 
1470     assert_cpu_is_self(env_cpu(env));
1471     for (vidx = 0; vidx < CPU_VTLB_SIZE; ++vidx) {
1472         CPUTLBEntry *vtlb = &env_tlb(env)->d[mmu_idx].vtable[vidx];
1473         uint64_t cmp = tlb_read_idx(vtlb, access_type);
1474 
1475         if (cmp == page) {
1476             /* Found entry in victim tlb, swap tlb and iotlb.  */
1477             CPUTLBEntry tmptlb, *tlb = &env_tlb(env)->f[mmu_idx].table[index];
1478 
1479             qemu_spin_lock(&env_tlb(env)->c.lock);
1480             copy_tlb_helper_locked(&tmptlb, tlb);
1481             copy_tlb_helper_locked(tlb, vtlb);
1482             copy_tlb_helper_locked(vtlb, &tmptlb);
1483             qemu_spin_unlock(&env_tlb(env)->c.lock);
1484 
1485             CPUTLBEntryFull *f1 = &env_tlb(env)->d[mmu_idx].fulltlb[index];
1486             CPUTLBEntryFull *f2 = &env_tlb(env)->d[mmu_idx].vfulltlb[vidx];
1487             CPUTLBEntryFull tmpf;
1488             tmpf = *f1; *f1 = *f2; *f2 = tmpf;
1489             return true;
1490         }
1491     }
1492     return false;
1493 }
1494 
1495 static void notdirty_write(CPUState *cpu, vaddr mem_vaddr, unsigned size,
1496                            CPUTLBEntryFull *full, uintptr_t retaddr)
1497 {
1498     ram_addr_t ram_addr = mem_vaddr + full->xlat_section;
1499 
1500     trace_memory_notdirty_write_access(mem_vaddr, ram_addr, size);
1501 
1502     if (!cpu_physical_memory_get_dirty_flag(ram_addr, DIRTY_MEMORY_CODE)) {
1503         tb_invalidate_phys_range_fast(ram_addr, size, retaddr);
1504     }
1505 
1506     /*
1507      * Set both VGA and migration bits for simplicity and to remove
1508      * the notdirty callback faster.
1509      */
1510     cpu_physical_memory_set_dirty_range(ram_addr, size, DIRTY_CLIENTS_NOCODE);
1511 
1512     /* We remove the notdirty callback only if the code has been flushed. */
1513     if (!cpu_physical_memory_is_clean(ram_addr)) {
1514         trace_memory_notdirty_set_dirty(mem_vaddr);
1515         tlb_set_dirty(cpu, mem_vaddr);
1516     }
1517 }
1518 
1519 static int probe_access_internal(CPUArchState *env, vaddr addr,
1520                                  int fault_size, MMUAccessType access_type,
1521                                  int mmu_idx, bool nonfault,
1522                                  void **phost, CPUTLBEntryFull **pfull,
1523                                  uintptr_t retaddr, bool check_mem_cbs)
1524 {
1525     uintptr_t index = tlb_index(env, mmu_idx, addr);
1526     CPUTLBEntry *entry = tlb_entry(env, mmu_idx, addr);
1527     uint64_t tlb_addr = tlb_read_idx(entry, access_type);
1528     vaddr page_addr = addr & TARGET_PAGE_MASK;
1529     int flags = TLB_FLAGS_MASK & ~TLB_FORCE_SLOW;
1530     bool force_mmio = check_mem_cbs && cpu_plugin_mem_cbs_enabled(env_cpu(env));
1531     CPUTLBEntryFull *full;
1532 
1533     if (!tlb_hit_page(tlb_addr, page_addr)) {
1534         if (!victim_tlb_hit(env, mmu_idx, index, access_type, page_addr)) {
1535             CPUState *cs = env_cpu(env);
1536 
1537             if (!cs->cc->tcg_ops->tlb_fill(cs, addr, fault_size, access_type,
1538                                            mmu_idx, nonfault, retaddr)) {
1539                 /* Non-faulting page table read failed.  */
1540                 *phost = NULL;
1541                 *pfull = NULL;
1542                 return TLB_INVALID_MASK;
1543             }
1544 
1545             /* TLB resize via tlb_fill may have moved the entry.  */
1546             index = tlb_index(env, mmu_idx, addr);
1547             entry = tlb_entry(env, mmu_idx, addr);
1548 
1549             /*
1550              * With PAGE_WRITE_INV, we set TLB_INVALID_MASK immediately,
1551              * to force the next access through tlb_fill.  We've just
1552              * called tlb_fill, so we know that this entry *is* valid.
1553              */
1554             flags &= ~TLB_INVALID_MASK;
1555         }
1556         tlb_addr = tlb_read_idx(entry, access_type);
1557     }
1558     flags &= tlb_addr;
1559 
1560     *pfull = full = &env_tlb(env)->d[mmu_idx].fulltlb[index];
1561     flags |= full->slow_flags[access_type];
1562 
1563     /* Fold all "mmio-like" bits into TLB_MMIO.  This is not RAM.  */
1564     if (unlikely(flags & ~(TLB_WATCHPOINT | TLB_NOTDIRTY))
1565         ||
1566         (access_type != MMU_INST_FETCH && force_mmio)) {
1567         *phost = NULL;
1568         return TLB_MMIO;
1569     }
1570 
1571     /* Everything else is RAM. */
1572     *phost = (void *)((uintptr_t)addr + entry->addend);
1573     return flags;
1574 }
1575 
1576 int probe_access_full(CPUArchState *env, vaddr addr, int size,
1577                       MMUAccessType access_type, int mmu_idx,
1578                       bool nonfault, void **phost, CPUTLBEntryFull **pfull,
1579                       uintptr_t retaddr)
1580 {
1581     int flags = probe_access_internal(env, addr, size, access_type, mmu_idx,
1582                                       nonfault, phost, pfull, retaddr, true);
1583 
1584     /* Handle clean RAM pages.  */
1585     if (unlikely(flags & TLB_NOTDIRTY)) {
1586         notdirty_write(env_cpu(env), addr, 1, *pfull, retaddr);
1587         flags &= ~TLB_NOTDIRTY;
1588     }
1589 
1590     return flags;
1591 }
1592 
1593 int probe_access_full_mmu(CPUArchState *env, vaddr addr, int size,
1594                           MMUAccessType access_type, int mmu_idx,
1595                           void **phost, CPUTLBEntryFull **pfull)
1596 {
1597     void *discard_phost;
1598     CPUTLBEntryFull *discard_tlb;
1599 
1600     /* privately handle users that don't need full results */
1601     phost = phost ? phost : &discard_phost;
1602     pfull = pfull ? pfull : &discard_tlb;
1603 
1604     int flags = probe_access_internal(env, addr, size, access_type, mmu_idx,
1605                                       true, phost, pfull, 0, false);
1606 
1607     /* Handle clean RAM pages.  */
1608     if (unlikely(flags & TLB_NOTDIRTY)) {
1609         notdirty_write(env_cpu(env), addr, 1, *pfull, 0);
1610         flags &= ~TLB_NOTDIRTY;
1611     }
1612 
1613     return flags;
1614 }
1615 
1616 int probe_access_flags(CPUArchState *env, vaddr addr, int size,
1617                        MMUAccessType access_type, int mmu_idx,
1618                        bool nonfault, void **phost, uintptr_t retaddr)
1619 {
1620     CPUTLBEntryFull *full;
1621     int flags;
1622 
1623     g_assert(-(addr | TARGET_PAGE_MASK) >= size);
1624 
1625     flags = probe_access_internal(env, addr, size, access_type, mmu_idx,
1626                                   nonfault, phost, &full, retaddr, true);
1627 
1628     /* Handle clean RAM pages. */
1629     if (unlikely(flags & TLB_NOTDIRTY)) {
1630         notdirty_write(env_cpu(env), addr, 1, full, retaddr);
1631         flags &= ~TLB_NOTDIRTY;
1632     }
1633 
1634     return flags;
1635 }
1636 
1637 void *probe_access(CPUArchState *env, vaddr addr, int size,
1638                    MMUAccessType access_type, int mmu_idx, uintptr_t retaddr)
1639 {
1640     CPUTLBEntryFull *full;
1641     void *host;
1642     int flags;
1643 
1644     g_assert(-(addr | TARGET_PAGE_MASK) >= size);
1645 
1646     flags = probe_access_internal(env, addr, size, access_type, mmu_idx,
1647                                   false, &host, &full, retaddr, true);
1648 
1649     /* Per the interface, size == 0 merely faults the access. */
1650     if (size == 0) {
1651         return NULL;
1652     }
1653 
1654     if (unlikely(flags & (TLB_NOTDIRTY | TLB_WATCHPOINT))) {
1655         /* Handle watchpoints.  */
1656         if (flags & TLB_WATCHPOINT) {
1657             int wp_access = (access_type == MMU_DATA_STORE
1658                              ? BP_MEM_WRITE : BP_MEM_READ);
1659             cpu_check_watchpoint(env_cpu(env), addr, size,
1660                                  full->attrs, wp_access, retaddr);
1661         }
1662 
1663         /* Handle clean RAM pages.  */
1664         if (flags & TLB_NOTDIRTY) {
1665             notdirty_write(env_cpu(env), addr, 1, full, retaddr);
1666         }
1667     }
1668 
1669     return host;
1670 }
1671 
1672 void *tlb_vaddr_to_host(CPUArchState *env, abi_ptr addr,
1673                         MMUAccessType access_type, int mmu_idx)
1674 {
1675     CPUTLBEntryFull *full;
1676     void *host;
1677     int flags;
1678 
1679     flags = probe_access_internal(env, addr, 0, access_type,
1680                                   mmu_idx, true, &host, &full, 0, false);
1681 
1682     /* No combination of flags are expected by the caller. */
1683     return flags ? NULL : host;
1684 }
1685 
1686 /*
1687  * Return a ram_addr_t for the virtual address for execution.
1688  *
1689  * Return -1 if we can't translate and execute from an entire page
1690  * of RAM.  This will force us to execute by loading and translating
1691  * one insn at a time, without caching.
1692  *
1693  * NOTE: This function will trigger an exception if the page is
1694  * not executable.
1695  */
1696 tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr,
1697                                         void **hostp)
1698 {
1699     CPUTLBEntryFull *full;
1700     void *p;
1701 
1702     (void)probe_access_internal(env, addr, 1, MMU_INST_FETCH,
1703                                 cpu_mmu_index(env, true), false,
1704                                 &p, &full, 0, false);
1705     if (p == NULL) {
1706         return -1;
1707     }
1708 
1709     if (full->lg_page_size < TARGET_PAGE_BITS) {
1710         return -1;
1711     }
1712 
1713     if (hostp) {
1714         *hostp = p;
1715     }
1716     return qemu_ram_addr_from_host_nofail(p);
1717 }
1718 
1719 /* Load/store with atomicity primitives. */
1720 #include "ldst_atomicity.c.inc"
1721 
1722 #ifdef CONFIG_PLUGIN
1723 /*
1724  * Perform a TLB lookup and populate the qemu_plugin_hwaddr structure.
1725  * This should be a hot path as we will have just looked this path up
1726  * in the softmmu lookup code (or helper). We don't handle re-fills or
1727  * checking the victim table. This is purely informational.
1728  *
1729  * This almost never fails as the memory access being instrumented
1730  * should have just filled the TLB. The one corner case is io_writex
1731  * which can cause TLB flushes and potential resizing of the TLBs
1732  * losing the information we need. In those cases we need to recover
1733  * data from a copy of the CPUTLBEntryFull. As long as this always occurs
1734  * from the same thread (which a mem callback will be) this is safe.
1735  */
1736 
1737 bool tlb_plugin_lookup(CPUState *cpu, vaddr addr, int mmu_idx,
1738                        bool is_store, struct qemu_plugin_hwaddr *data)
1739 {
1740     CPUArchState *env = cpu->env_ptr;
1741     CPUTLBEntry *tlbe = tlb_entry(env, mmu_idx, addr);
1742     uintptr_t index = tlb_index(env, mmu_idx, addr);
1743     uint64_t tlb_addr = is_store ? tlb_addr_write(tlbe) : tlbe->addr_read;
1744 
1745     if (likely(tlb_hit(tlb_addr, addr))) {
1746         /* We must have an iotlb entry for MMIO */
1747         if (tlb_addr & TLB_MMIO) {
1748             CPUTLBEntryFull *full;
1749             full = &env_tlb(env)->d[mmu_idx].fulltlb[index];
1750             data->is_io = true;
1751             data->v.io.section =
1752                 iotlb_to_section(cpu, full->xlat_section, full->attrs);
1753             data->v.io.offset = (full->xlat_section & TARGET_PAGE_MASK) + addr;
1754         } else {
1755             data->is_io = false;
1756             data->v.ram.hostaddr = (void *)((uintptr_t)addr + tlbe->addend);
1757         }
1758         return true;
1759     } else {
1760         SavedIOTLB *saved = &cpu->saved_iotlb;
1761         data->is_io = true;
1762         data->v.io.section = saved->section;
1763         data->v.io.offset = saved->mr_offset;
1764         return true;
1765     }
1766 }
1767 
1768 #endif
1769 
1770 /*
1771  * Probe for a load/store operation.
1772  * Return the host address and into @flags.
1773  */
1774 
1775 typedef struct MMULookupPageData {
1776     CPUTLBEntryFull *full;
1777     void *haddr;
1778     vaddr addr;
1779     int flags;
1780     int size;
1781 } MMULookupPageData;
1782 
1783 typedef struct MMULookupLocals {
1784     MMULookupPageData page[2];
1785     MemOp memop;
1786     int mmu_idx;
1787 } MMULookupLocals;
1788 
1789 /**
1790  * mmu_lookup1: translate one page
1791  * @env: cpu context
1792  * @data: lookup parameters
1793  * @mmu_idx: virtual address context
1794  * @access_type: load/store/code
1795  * @ra: return address into tcg generated code, or 0
1796  *
1797  * Resolve the translation for the one page at @data.addr, filling in
1798  * the rest of @data with the results.  If the translation fails,
1799  * tlb_fill will longjmp out.  Return true if the softmmu tlb for
1800  * @mmu_idx may have resized.
1801  */
1802 static bool mmu_lookup1(CPUArchState *env, MMULookupPageData *data,
1803                         int mmu_idx, MMUAccessType access_type, uintptr_t ra)
1804 {
1805     vaddr addr = data->addr;
1806     uintptr_t index = tlb_index(env, mmu_idx, addr);
1807     CPUTLBEntry *entry = tlb_entry(env, mmu_idx, addr);
1808     uint64_t tlb_addr = tlb_read_idx(entry, access_type);
1809     bool maybe_resized = false;
1810     CPUTLBEntryFull *full;
1811     int flags;
1812 
1813     /* If the TLB entry is for a different page, reload and try again.  */
1814     if (!tlb_hit(tlb_addr, addr)) {
1815         if (!victim_tlb_hit(env, mmu_idx, index, access_type,
1816                             addr & TARGET_PAGE_MASK)) {
1817             tlb_fill(env_cpu(env), addr, data->size, access_type, mmu_idx, ra);
1818             maybe_resized = true;
1819             index = tlb_index(env, mmu_idx, addr);
1820             entry = tlb_entry(env, mmu_idx, addr);
1821         }
1822         tlb_addr = tlb_read_idx(entry, access_type) & ~TLB_INVALID_MASK;
1823     }
1824 
1825     full = &env_tlb(env)->d[mmu_idx].fulltlb[index];
1826     flags = tlb_addr & (TLB_FLAGS_MASK & ~TLB_FORCE_SLOW);
1827     flags |= full->slow_flags[access_type];
1828 
1829     data->full = full;
1830     data->flags = flags;
1831     /* Compute haddr speculatively; depending on flags it might be invalid. */
1832     data->haddr = (void *)((uintptr_t)addr + entry->addend);
1833 
1834     return maybe_resized;
1835 }
1836 
1837 /**
1838  * mmu_watch_or_dirty
1839  * @env: cpu context
1840  * @data: lookup parameters
1841  * @access_type: load/store/code
1842  * @ra: return address into tcg generated code, or 0
1843  *
1844  * Trigger watchpoints for @data.addr:@data.size;
1845  * record writes to protected clean pages.
1846  */
1847 static void mmu_watch_or_dirty(CPUArchState *env, MMULookupPageData *data,
1848                                MMUAccessType access_type, uintptr_t ra)
1849 {
1850     CPUTLBEntryFull *full = data->full;
1851     vaddr addr = data->addr;
1852     int flags = data->flags;
1853     int size = data->size;
1854 
1855     /* On watchpoint hit, this will longjmp out.  */
1856     if (flags & TLB_WATCHPOINT) {
1857         int wp = access_type == MMU_DATA_STORE ? BP_MEM_WRITE : BP_MEM_READ;
1858         cpu_check_watchpoint(env_cpu(env), addr, size, full->attrs, wp, ra);
1859         flags &= ~TLB_WATCHPOINT;
1860     }
1861 
1862     /* Note that notdirty is only set for writes. */
1863     if (flags & TLB_NOTDIRTY) {
1864         notdirty_write(env_cpu(env), addr, size, full, ra);
1865         flags &= ~TLB_NOTDIRTY;
1866     }
1867     data->flags = flags;
1868 }
1869 
1870 /**
1871  * mmu_lookup: translate page(s)
1872  * @env: cpu context
1873  * @addr: virtual address
1874  * @oi: combined mmu_idx and MemOp
1875  * @ra: return address into tcg generated code, or 0
1876  * @access_type: load/store/code
1877  * @l: output result
1878  *
1879  * Resolve the translation for the page(s) beginning at @addr, for MemOp.size
1880  * bytes.  Return true if the lookup crosses a page boundary.
1881  */
1882 static bool mmu_lookup(CPUArchState *env, vaddr addr, MemOpIdx oi,
1883                        uintptr_t ra, MMUAccessType type, MMULookupLocals *l)
1884 {
1885     unsigned a_bits;
1886     bool crosspage;
1887     int flags;
1888 
1889     l->memop = get_memop(oi);
1890     l->mmu_idx = get_mmuidx(oi);
1891 
1892     tcg_debug_assert(l->mmu_idx < NB_MMU_MODES);
1893 
1894     /* Handle CPU specific unaligned behaviour */
1895     a_bits = get_alignment_bits(l->memop);
1896     if (addr & ((1 << a_bits) - 1)) {
1897         cpu_unaligned_access(env_cpu(env), addr, type, l->mmu_idx, ra);
1898     }
1899 
1900     l->page[0].addr = addr;
1901     l->page[0].size = memop_size(l->memop);
1902     l->page[1].addr = (addr + l->page[0].size - 1) & TARGET_PAGE_MASK;
1903     l->page[1].size = 0;
1904     crosspage = (addr ^ l->page[1].addr) & TARGET_PAGE_MASK;
1905 
1906     if (likely(!crosspage)) {
1907         mmu_lookup1(env, &l->page[0], l->mmu_idx, type, ra);
1908 
1909         flags = l->page[0].flags;
1910         if (unlikely(flags & (TLB_WATCHPOINT | TLB_NOTDIRTY))) {
1911             mmu_watch_or_dirty(env, &l->page[0], type, ra);
1912         }
1913         if (unlikely(flags & TLB_BSWAP)) {
1914             l->memop ^= MO_BSWAP;
1915         }
1916     } else {
1917         /* Finish compute of page crossing. */
1918         int size0 = l->page[1].addr - addr;
1919         l->page[1].size = l->page[0].size - size0;
1920         l->page[0].size = size0;
1921 
1922         /*
1923          * Lookup both pages, recognizing exceptions from either.  If the
1924          * second lookup potentially resized, refresh first CPUTLBEntryFull.
1925          */
1926         mmu_lookup1(env, &l->page[0], l->mmu_idx, type, ra);
1927         if (mmu_lookup1(env, &l->page[1], l->mmu_idx, type, ra)) {
1928             uintptr_t index = tlb_index(env, l->mmu_idx, addr);
1929             l->page[0].full = &env_tlb(env)->d[l->mmu_idx].fulltlb[index];
1930         }
1931 
1932         flags = l->page[0].flags | l->page[1].flags;
1933         if (unlikely(flags & (TLB_WATCHPOINT | TLB_NOTDIRTY))) {
1934             mmu_watch_or_dirty(env, &l->page[0], type, ra);
1935             mmu_watch_or_dirty(env, &l->page[1], type, ra);
1936         }
1937 
1938         /*
1939          * Since target/sparc is the only user of TLB_BSWAP, and all
1940          * Sparc accesses are aligned, any treatment across two pages
1941          * would be arbitrary.  Refuse it until there's a use.
1942          */
1943         tcg_debug_assert((flags & TLB_BSWAP) == 0);
1944     }
1945 
1946     return crosspage;
1947 }
1948 
1949 /*
1950  * Probe for an atomic operation.  Do not allow unaligned operations,
1951  * or io operations to proceed.  Return the host address.
1952  */
1953 static void *atomic_mmu_lookup(CPUArchState *env, vaddr addr, MemOpIdx oi,
1954                                int size, uintptr_t retaddr)
1955 {
1956     uintptr_t mmu_idx = get_mmuidx(oi);
1957     MemOp mop = get_memop(oi);
1958     int a_bits = get_alignment_bits(mop);
1959     uintptr_t index;
1960     CPUTLBEntry *tlbe;
1961     vaddr tlb_addr;
1962     void *hostaddr;
1963     CPUTLBEntryFull *full;
1964 
1965     tcg_debug_assert(mmu_idx < NB_MMU_MODES);
1966 
1967     /* Adjust the given return address.  */
1968     retaddr -= GETPC_ADJ;
1969 
1970     /* Enforce guest required alignment.  */
1971     if (unlikely(a_bits > 0 && (addr & ((1 << a_bits) - 1)))) {
1972         /* ??? Maybe indicate atomic op to cpu_unaligned_access */
1973         cpu_unaligned_access(env_cpu(env), addr, MMU_DATA_STORE,
1974                              mmu_idx, retaddr);
1975     }
1976 
1977     /* Enforce qemu required alignment.  */
1978     if (unlikely(addr & (size - 1))) {
1979         /* We get here if guest alignment was not requested,
1980            or was not enforced by cpu_unaligned_access above.
1981            We might widen the access and emulate, but for now
1982            mark an exception and exit the cpu loop.  */
1983         goto stop_the_world;
1984     }
1985 
1986     index = tlb_index(env, mmu_idx, addr);
1987     tlbe = tlb_entry(env, mmu_idx, addr);
1988 
1989     /* Check TLB entry and enforce page permissions.  */
1990     tlb_addr = tlb_addr_write(tlbe);
1991     if (!tlb_hit(tlb_addr, addr)) {
1992         if (!victim_tlb_hit(env, mmu_idx, index, MMU_DATA_STORE,
1993                             addr & TARGET_PAGE_MASK)) {
1994             tlb_fill(env_cpu(env), addr, size,
1995                      MMU_DATA_STORE, mmu_idx, retaddr);
1996             index = tlb_index(env, mmu_idx, addr);
1997             tlbe = tlb_entry(env, mmu_idx, addr);
1998         }
1999         tlb_addr = tlb_addr_write(tlbe) & ~TLB_INVALID_MASK;
2000     }
2001 
2002     /*
2003      * Let the guest notice RMW on a write-only page.
2004      * We have just verified that the page is writable.
2005      * Subpage lookups may have left TLB_INVALID_MASK set,
2006      * but addr_read will only be -1 if PAGE_READ was unset.
2007      */
2008     if (unlikely(tlbe->addr_read == -1)) {
2009         tlb_fill(env_cpu(env), addr, size, MMU_DATA_LOAD, mmu_idx, retaddr);
2010         /*
2011          * Since we don't support reads and writes to different
2012          * addresses, and we do have the proper page loaded for
2013          * write, this shouldn't ever return.  But just in case,
2014          * handle via stop-the-world.
2015          */
2016         goto stop_the_world;
2017     }
2018     /* Collect tlb flags for read. */
2019     tlb_addr |= tlbe->addr_read;
2020 
2021     /* Notice an IO access or a needs-MMU-lookup access */
2022     if (unlikely(tlb_addr & (TLB_MMIO | TLB_DISCARD_WRITE))) {
2023         /* There's really nothing that can be done to
2024            support this apart from stop-the-world.  */
2025         goto stop_the_world;
2026     }
2027 
2028     hostaddr = (void *)((uintptr_t)addr + tlbe->addend);
2029     full = &env_tlb(env)->d[mmu_idx].fulltlb[index];
2030 
2031     if (unlikely(tlb_addr & TLB_NOTDIRTY)) {
2032         notdirty_write(env_cpu(env), addr, size, full, retaddr);
2033     }
2034 
2035     if (unlikely(tlb_addr & TLB_FORCE_SLOW)) {
2036         int wp_flags = 0;
2037 
2038         if (full->slow_flags[MMU_DATA_STORE] & TLB_WATCHPOINT) {
2039             wp_flags |= BP_MEM_WRITE;
2040         }
2041         if (full->slow_flags[MMU_DATA_LOAD] & TLB_WATCHPOINT) {
2042             wp_flags |= BP_MEM_READ;
2043         }
2044         if (wp_flags) {
2045             cpu_check_watchpoint(env_cpu(env), addr, size,
2046                                  full->attrs, wp_flags, retaddr);
2047         }
2048     }
2049 
2050     return hostaddr;
2051 
2052  stop_the_world:
2053     cpu_loop_exit_atomic(env_cpu(env), retaddr);
2054 }
2055 
2056 /*
2057  * Load Helpers
2058  *
2059  * We support two different access types. SOFTMMU_CODE_ACCESS is
2060  * specifically for reading instructions from system memory. It is
2061  * called by the translation loop and in some helpers where the code
2062  * is disassembled. It shouldn't be called directly by guest code.
2063  *
2064  * For the benefit of TCG generated code, we want to avoid the
2065  * complication of ABI-specific return type promotion and always
2066  * return a value extended to the register size of the host. This is
2067  * tcg_target_long, except in the case of a 32-bit host and 64-bit
2068  * data, and for that we always have uint64_t.
2069  *
2070  * We don't bother with this widened value for SOFTMMU_CODE_ACCESS.
2071  */
2072 
2073 /**
2074  * do_ld_mmio_beN:
2075  * @env: cpu context
2076  * @full: page parameters
2077  * @ret_be: accumulated data
2078  * @addr: virtual address
2079  * @size: number of bytes
2080  * @mmu_idx: virtual address context
2081  * @ra: return address into tcg generated code, or 0
2082  * Context: iothread lock held
2083  *
2084  * Load @size bytes from @addr, which is memory-mapped i/o.
2085  * The bytes are concatenated in big-endian order with @ret_be.
2086  */
2087 static uint64_t do_ld_mmio_beN(CPUArchState *env, CPUTLBEntryFull *full,
2088                                uint64_t ret_be, vaddr addr, int size,
2089                                int mmu_idx, MMUAccessType type, uintptr_t ra)
2090 {
2091     uint64_t t;
2092 
2093     tcg_debug_assert(size > 0 && size <= 8);
2094     do {
2095         /* Read aligned pieces up to 8 bytes. */
2096         switch ((size | (int)addr) & 7) {
2097         case 1:
2098         case 3:
2099         case 5:
2100         case 7:
2101             t = io_readx(env, full, mmu_idx, addr, ra, type, MO_UB);
2102             ret_be = (ret_be << 8) | t;
2103             size -= 1;
2104             addr += 1;
2105             break;
2106         case 2:
2107         case 6:
2108             t = io_readx(env, full, mmu_idx, addr, ra, type, MO_BEUW);
2109             ret_be = (ret_be << 16) | t;
2110             size -= 2;
2111             addr += 2;
2112             break;
2113         case 4:
2114             t = io_readx(env, full, mmu_idx, addr, ra, type, MO_BEUL);
2115             ret_be = (ret_be << 32) | t;
2116             size -= 4;
2117             addr += 4;
2118             break;
2119         case 0:
2120             return io_readx(env, full, mmu_idx, addr, ra, type, MO_BEUQ);
2121         default:
2122             qemu_build_not_reached();
2123         }
2124     } while (size);
2125     return ret_be;
2126 }
2127 
2128 /**
2129  * do_ld_bytes_beN
2130  * @p: translation parameters
2131  * @ret_be: accumulated data
2132  *
2133  * Load @p->size bytes from @p->haddr, which is RAM.
2134  * The bytes to concatenated in big-endian order with @ret_be.
2135  */
2136 static uint64_t do_ld_bytes_beN(MMULookupPageData *p, uint64_t ret_be)
2137 {
2138     uint8_t *haddr = p->haddr;
2139     int i, size = p->size;
2140 
2141     for (i = 0; i < size; i++) {
2142         ret_be = (ret_be << 8) | haddr[i];
2143     }
2144     return ret_be;
2145 }
2146 
2147 /**
2148  * do_ld_parts_beN
2149  * @p: translation parameters
2150  * @ret_be: accumulated data
2151  *
2152  * As do_ld_bytes_beN, but atomically on each aligned part.
2153  */
2154 static uint64_t do_ld_parts_beN(MMULookupPageData *p, uint64_t ret_be)
2155 {
2156     void *haddr = p->haddr;
2157     int size = p->size;
2158 
2159     do {
2160         uint64_t x;
2161         int n;
2162 
2163         /*
2164          * Find minimum of alignment and size.
2165          * This is slightly stronger than required by MO_ATOM_SUBALIGN, which
2166          * would have only checked the low bits of addr|size once at the start,
2167          * but is just as easy.
2168          */
2169         switch (((uintptr_t)haddr | size) & 7) {
2170         case 4:
2171             x = cpu_to_be32(load_atomic4(haddr));
2172             ret_be = (ret_be << 32) | x;
2173             n = 4;
2174             break;
2175         case 2:
2176         case 6:
2177             x = cpu_to_be16(load_atomic2(haddr));
2178             ret_be = (ret_be << 16) | x;
2179             n = 2;
2180             break;
2181         default:
2182             x = *(uint8_t *)haddr;
2183             ret_be = (ret_be << 8) | x;
2184             n = 1;
2185             break;
2186         case 0:
2187             g_assert_not_reached();
2188         }
2189         haddr += n;
2190         size -= n;
2191     } while (size != 0);
2192     return ret_be;
2193 }
2194 
2195 /**
2196  * do_ld_parts_be4
2197  * @p: translation parameters
2198  * @ret_be: accumulated data
2199  *
2200  * As do_ld_bytes_beN, but with one atomic load.
2201  * Four aligned bytes are guaranteed to cover the load.
2202  */
2203 static uint64_t do_ld_whole_be4(MMULookupPageData *p, uint64_t ret_be)
2204 {
2205     int o = p->addr & 3;
2206     uint32_t x = load_atomic4(p->haddr - o);
2207 
2208     x = cpu_to_be32(x);
2209     x <<= o * 8;
2210     x >>= (4 - p->size) * 8;
2211     return (ret_be << (p->size * 8)) | x;
2212 }
2213 
2214 /**
2215  * do_ld_parts_be8
2216  * @p: translation parameters
2217  * @ret_be: accumulated data
2218  *
2219  * As do_ld_bytes_beN, but with one atomic load.
2220  * Eight aligned bytes are guaranteed to cover the load.
2221  */
2222 static uint64_t do_ld_whole_be8(CPUArchState *env, uintptr_t ra,
2223                                 MMULookupPageData *p, uint64_t ret_be)
2224 {
2225     int o = p->addr & 7;
2226     uint64_t x = load_atomic8_or_exit(env, ra, p->haddr - o);
2227 
2228     x = cpu_to_be64(x);
2229     x <<= o * 8;
2230     x >>= (8 - p->size) * 8;
2231     return (ret_be << (p->size * 8)) | x;
2232 }
2233 
2234 /**
2235  * do_ld_parts_be16
2236  * @p: translation parameters
2237  * @ret_be: accumulated data
2238  *
2239  * As do_ld_bytes_beN, but with one atomic load.
2240  * 16 aligned bytes are guaranteed to cover the load.
2241  */
2242 static Int128 do_ld_whole_be16(CPUArchState *env, uintptr_t ra,
2243                                MMULookupPageData *p, uint64_t ret_be)
2244 {
2245     int o = p->addr & 15;
2246     Int128 x, y = load_atomic16_or_exit(env, ra, p->haddr - o);
2247     int size = p->size;
2248 
2249     if (!HOST_BIG_ENDIAN) {
2250         y = bswap128(y);
2251     }
2252     y = int128_lshift(y, o * 8);
2253     y = int128_urshift(y, (16 - size) * 8);
2254     x = int128_make64(ret_be);
2255     x = int128_lshift(x, size * 8);
2256     return int128_or(x, y);
2257 }
2258 
2259 /*
2260  * Wrapper for the above.
2261  */
2262 static uint64_t do_ld_beN(CPUArchState *env, MMULookupPageData *p,
2263                           uint64_t ret_be, int mmu_idx, MMUAccessType type,
2264                           MemOp mop, uintptr_t ra)
2265 {
2266     MemOp atom;
2267     unsigned tmp, half_size;
2268 
2269     if (unlikely(p->flags & TLB_MMIO)) {
2270         QEMU_IOTHREAD_LOCK_GUARD();
2271         return do_ld_mmio_beN(env, p->full, ret_be, p->addr, p->size,
2272                               mmu_idx, type, ra);
2273     }
2274 
2275     /*
2276      * It is a given that we cross a page and therefore there is no
2277      * atomicity for the load as a whole, but subobjects may need attention.
2278      */
2279     atom = mop & MO_ATOM_MASK;
2280     switch (atom) {
2281     case MO_ATOM_SUBALIGN:
2282         return do_ld_parts_beN(p, ret_be);
2283 
2284     case MO_ATOM_IFALIGN_PAIR:
2285     case MO_ATOM_WITHIN16_PAIR:
2286         tmp = mop & MO_SIZE;
2287         tmp = tmp ? tmp - 1 : 0;
2288         half_size = 1 << tmp;
2289         if (atom == MO_ATOM_IFALIGN_PAIR
2290             ? p->size == half_size
2291             : p->size >= half_size) {
2292             if (!HAVE_al8_fast && p->size < 4) {
2293                 return do_ld_whole_be4(p, ret_be);
2294             } else {
2295                 return do_ld_whole_be8(env, ra, p, ret_be);
2296             }
2297         }
2298         /* fall through */
2299 
2300     case MO_ATOM_IFALIGN:
2301     case MO_ATOM_WITHIN16:
2302     case MO_ATOM_NONE:
2303         return do_ld_bytes_beN(p, ret_be);
2304 
2305     default:
2306         g_assert_not_reached();
2307     }
2308 }
2309 
2310 /*
2311  * Wrapper for the above, for 8 < size < 16.
2312  */
2313 static Int128 do_ld16_beN(CPUArchState *env, MMULookupPageData *p,
2314                           uint64_t a, int mmu_idx, MemOp mop, uintptr_t ra)
2315 {
2316     int size = p->size;
2317     uint64_t b;
2318     MemOp atom;
2319 
2320     if (unlikely(p->flags & TLB_MMIO)) {
2321         QEMU_IOTHREAD_LOCK_GUARD();
2322         a = do_ld_mmio_beN(env, p->full, a, p->addr, size - 8,
2323                            mmu_idx, MMU_DATA_LOAD, ra);
2324         b = do_ld_mmio_beN(env, p->full, 0, p->addr + 8, 8,
2325                            mmu_idx, MMU_DATA_LOAD, ra);
2326         return int128_make128(b, a);
2327     }
2328 
2329     /*
2330      * It is a given that we cross a page and therefore there is no
2331      * atomicity for the load as a whole, but subobjects may need attention.
2332      */
2333     atom = mop & MO_ATOM_MASK;
2334     switch (atom) {
2335     case MO_ATOM_SUBALIGN:
2336         p->size = size - 8;
2337         a = do_ld_parts_beN(p, a);
2338         p->haddr += size - 8;
2339         p->size = 8;
2340         b = do_ld_parts_beN(p, 0);
2341         break;
2342 
2343     case MO_ATOM_WITHIN16_PAIR:
2344         /* Since size > 8, this is the half that must be atomic. */
2345         return do_ld_whole_be16(env, ra, p, a);
2346 
2347     case MO_ATOM_IFALIGN_PAIR:
2348         /*
2349          * Since size > 8, both halves are misaligned,
2350          * and so neither is atomic.
2351          */
2352     case MO_ATOM_IFALIGN:
2353     case MO_ATOM_WITHIN16:
2354     case MO_ATOM_NONE:
2355         p->size = size - 8;
2356         a = do_ld_bytes_beN(p, a);
2357         b = ldq_be_p(p->haddr + size - 8);
2358         break;
2359 
2360     default:
2361         g_assert_not_reached();
2362     }
2363 
2364     return int128_make128(b, a);
2365 }
2366 
2367 static uint8_t do_ld_1(CPUArchState *env, MMULookupPageData *p, int mmu_idx,
2368                        MMUAccessType type, uintptr_t ra)
2369 {
2370     if (unlikely(p->flags & TLB_MMIO)) {
2371         return io_readx(env, p->full, mmu_idx, p->addr, ra, type, MO_UB);
2372     } else {
2373         return *(uint8_t *)p->haddr;
2374     }
2375 }
2376 
2377 static uint16_t do_ld_2(CPUArchState *env, MMULookupPageData *p, int mmu_idx,
2378                         MMUAccessType type, MemOp memop, uintptr_t ra)
2379 {
2380     uint16_t ret;
2381 
2382     if (unlikely(p->flags & TLB_MMIO)) {
2383         QEMU_IOTHREAD_LOCK_GUARD();
2384         ret = do_ld_mmio_beN(env, p->full, 0, p->addr, 2, mmu_idx, type, ra);
2385         if ((memop & MO_BSWAP) == MO_LE) {
2386             ret = bswap16(ret);
2387         }
2388     } else {
2389         /* Perform the load host endian, then swap if necessary. */
2390         ret = load_atom_2(env, ra, p->haddr, memop);
2391         if (memop & MO_BSWAP) {
2392             ret = bswap16(ret);
2393         }
2394     }
2395     return ret;
2396 }
2397 
2398 static uint32_t do_ld_4(CPUArchState *env, MMULookupPageData *p, int mmu_idx,
2399                         MMUAccessType type, MemOp memop, uintptr_t ra)
2400 {
2401     uint32_t ret;
2402 
2403     if (unlikely(p->flags & TLB_MMIO)) {
2404         QEMU_IOTHREAD_LOCK_GUARD();
2405         ret = do_ld_mmio_beN(env, p->full, 0, p->addr, 4, mmu_idx, type, ra);
2406         if ((memop & MO_BSWAP) == MO_LE) {
2407             ret = bswap32(ret);
2408         }
2409     } else {
2410         /* Perform the load host endian. */
2411         ret = load_atom_4(env, ra, p->haddr, memop);
2412         if (memop & MO_BSWAP) {
2413             ret = bswap32(ret);
2414         }
2415     }
2416     return ret;
2417 }
2418 
2419 static uint64_t do_ld_8(CPUArchState *env, MMULookupPageData *p, int mmu_idx,
2420                         MMUAccessType type, MemOp memop, uintptr_t ra)
2421 {
2422     uint64_t ret;
2423 
2424     if (unlikely(p->flags & TLB_MMIO)) {
2425         QEMU_IOTHREAD_LOCK_GUARD();
2426         ret = do_ld_mmio_beN(env, p->full, 0, p->addr, 8, mmu_idx, type, ra);
2427         if ((memop & MO_BSWAP) == MO_LE) {
2428             ret = bswap64(ret);
2429         }
2430     } else {
2431         /* Perform the load host endian. */
2432         ret = load_atom_8(env, ra, p->haddr, memop);
2433         if (memop & MO_BSWAP) {
2434             ret = bswap64(ret);
2435         }
2436     }
2437     return ret;
2438 }
2439 
2440 static uint8_t do_ld1_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi,
2441                           uintptr_t ra, MMUAccessType access_type)
2442 {
2443     MMULookupLocals l;
2444     bool crosspage;
2445 
2446     cpu_req_mo(TCG_MO_LD_LD | TCG_MO_ST_LD);
2447     crosspage = mmu_lookup(env, addr, oi, ra, access_type, &l);
2448     tcg_debug_assert(!crosspage);
2449 
2450     return do_ld_1(env, &l.page[0], l.mmu_idx, access_type, ra);
2451 }
2452 
2453 tcg_target_ulong helper_ldub_mmu(CPUArchState *env, uint64_t addr,
2454                                  MemOpIdx oi, uintptr_t retaddr)
2455 {
2456     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_8);
2457     return do_ld1_mmu(env, addr, oi, retaddr, MMU_DATA_LOAD);
2458 }
2459 
2460 static uint16_t do_ld2_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi,
2461                            uintptr_t ra, MMUAccessType access_type)
2462 {
2463     MMULookupLocals l;
2464     bool crosspage;
2465     uint16_t ret;
2466     uint8_t a, b;
2467 
2468     cpu_req_mo(TCG_MO_LD_LD | TCG_MO_ST_LD);
2469     crosspage = mmu_lookup(env, addr, oi, ra, access_type, &l);
2470     if (likely(!crosspage)) {
2471         return do_ld_2(env, &l.page[0], l.mmu_idx, access_type, l.memop, ra);
2472     }
2473 
2474     a = do_ld_1(env, &l.page[0], l.mmu_idx, access_type, ra);
2475     b = do_ld_1(env, &l.page[1], l.mmu_idx, access_type, ra);
2476 
2477     if ((l.memop & MO_BSWAP) == MO_LE) {
2478         ret = a | (b << 8);
2479     } else {
2480         ret = b | (a << 8);
2481     }
2482     return ret;
2483 }
2484 
2485 tcg_target_ulong helper_lduw_mmu(CPUArchState *env, uint64_t addr,
2486                                  MemOpIdx oi, uintptr_t retaddr)
2487 {
2488     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_16);
2489     return do_ld2_mmu(env, addr, oi, retaddr, MMU_DATA_LOAD);
2490 }
2491 
2492 static uint32_t do_ld4_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi,
2493                            uintptr_t ra, MMUAccessType access_type)
2494 {
2495     MMULookupLocals l;
2496     bool crosspage;
2497     uint32_t ret;
2498 
2499     cpu_req_mo(TCG_MO_LD_LD | TCG_MO_ST_LD);
2500     crosspage = mmu_lookup(env, addr, oi, ra, access_type, &l);
2501     if (likely(!crosspage)) {
2502         return do_ld_4(env, &l.page[0], l.mmu_idx, access_type, l.memop, ra);
2503     }
2504 
2505     ret = do_ld_beN(env, &l.page[0], 0, l.mmu_idx, access_type, l.memop, ra);
2506     ret = do_ld_beN(env, &l.page[1], ret, l.mmu_idx, access_type, l.memop, ra);
2507     if ((l.memop & MO_BSWAP) == MO_LE) {
2508         ret = bswap32(ret);
2509     }
2510     return ret;
2511 }
2512 
2513 tcg_target_ulong helper_ldul_mmu(CPUArchState *env, uint64_t addr,
2514                                  MemOpIdx oi, uintptr_t retaddr)
2515 {
2516     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_32);
2517     return do_ld4_mmu(env, addr, oi, retaddr, MMU_DATA_LOAD);
2518 }
2519 
2520 static uint64_t do_ld8_mmu(CPUArchState *env, vaddr addr, MemOpIdx oi,
2521                            uintptr_t ra, MMUAccessType access_type)
2522 {
2523     MMULookupLocals l;
2524     bool crosspage;
2525     uint64_t ret;
2526 
2527     cpu_req_mo(TCG_MO_LD_LD | TCG_MO_ST_LD);
2528     crosspage = mmu_lookup(env, addr, oi, ra, access_type, &l);
2529     if (likely(!crosspage)) {
2530         return do_ld_8(env, &l.page[0], l.mmu_idx, access_type, l.memop, ra);
2531     }
2532 
2533     ret = do_ld_beN(env, &l.page[0], 0, l.mmu_idx, access_type, l.memop, ra);
2534     ret = do_ld_beN(env, &l.page[1], ret, l.mmu_idx, access_type, l.memop, ra);
2535     if ((l.memop & MO_BSWAP) == MO_LE) {
2536         ret = bswap64(ret);
2537     }
2538     return ret;
2539 }
2540 
2541 uint64_t helper_ldq_mmu(CPUArchState *env, uint64_t addr,
2542                         MemOpIdx oi, uintptr_t retaddr)
2543 {
2544     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_64);
2545     return do_ld8_mmu(env, addr, oi, retaddr, MMU_DATA_LOAD);
2546 }
2547 
2548 /*
2549  * Provide signed versions of the load routines as well.  We can of course
2550  * avoid this for 64-bit data, or for 32-bit data on 32-bit host.
2551  */
2552 
2553 tcg_target_ulong helper_ldsb_mmu(CPUArchState *env, uint64_t addr,
2554                                  MemOpIdx oi, uintptr_t retaddr)
2555 {
2556     return (int8_t)helper_ldub_mmu(env, addr, oi, retaddr);
2557 }
2558 
2559 tcg_target_ulong helper_ldsw_mmu(CPUArchState *env, uint64_t addr,
2560                                  MemOpIdx oi, uintptr_t retaddr)
2561 {
2562     return (int16_t)helper_lduw_mmu(env, addr, oi, retaddr);
2563 }
2564 
2565 tcg_target_ulong helper_ldsl_mmu(CPUArchState *env, uint64_t addr,
2566                                  MemOpIdx oi, uintptr_t retaddr)
2567 {
2568     return (int32_t)helper_ldul_mmu(env, addr, oi, retaddr);
2569 }
2570 
2571 static Int128 do_ld16_mmu(CPUArchState *env, vaddr addr,
2572                           MemOpIdx oi, uintptr_t ra)
2573 {
2574     MMULookupLocals l;
2575     bool crosspage;
2576     uint64_t a, b;
2577     Int128 ret;
2578     int first;
2579 
2580     cpu_req_mo(TCG_MO_LD_LD | TCG_MO_ST_LD);
2581     crosspage = mmu_lookup(env, addr, oi, ra, MMU_DATA_LOAD, &l);
2582     if (likely(!crosspage)) {
2583         if (unlikely(l.page[0].flags & TLB_MMIO)) {
2584             QEMU_IOTHREAD_LOCK_GUARD();
2585             a = do_ld_mmio_beN(env, l.page[0].full, 0, addr, 8,
2586                                l.mmu_idx, MMU_DATA_LOAD, ra);
2587             b = do_ld_mmio_beN(env, l.page[0].full, 0, addr + 8, 8,
2588                                l.mmu_idx, MMU_DATA_LOAD, ra);
2589             ret = int128_make128(b, a);
2590             if ((l.memop & MO_BSWAP) == MO_LE) {
2591                 ret = bswap128(ret);
2592             }
2593         } else {
2594             /* Perform the load host endian. */
2595             ret = load_atom_16(env, ra, l.page[0].haddr, l.memop);
2596             if (l.memop & MO_BSWAP) {
2597                 ret = bswap128(ret);
2598             }
2599         }
2600         return ret;
2601     }
2602 
2603     first = l.page[0].size;
2604     if (first == 8) {
2605         MemOp mop8 = (l.memop & ~MO_SIZE) | MO_64;
2606 
2607         a = do_ld_8(env, &l.page[0], l.mmu_idx, MMU_DATA_LOAD, mop8, ra);
2608         b = do_ld_8(env, &l.page[1], l.mmu_idx, MMU_DATA_LOAD, mop8, ra);
2609         if ((mop8 & MO_BSWAP) == MO_LE) {
2610             ret = int128_make128(a, b);
2611         } else {
2612             ret = int128_make128(b, a);
2613         }
2614         return ret;
2615     }
2616 
2617     if (first < 8) {
2618         a = do_ld_beN(env, &l.page[0], 0, l.mmu_idx,
2619                       MMU_DATA_LOAD, l.memop, ra);
2620         ret = do_ld16_beN(env, &l.page[1], a, l.mmu_idx, l.memop, ra);
2621     } else {
2622         ret = do_ld16_beN(env, &l.page[0], 0, l.mmu_idx, l.memop, ra);
2623         b = int128_getlo(ret);
2624         ret = int128_lshift(ret, l.page[1].size * 8);
2625         a = int128_gethi(ret);
2626         b = do_ld_beN(env, &l.page[1], b, l.mmu_idx,
2627                       MMU_DATA_LOAD, l.memop, ra);
2628         ret = int128_make128(b, a);
2629     }
2630     if ((l.memop & MO_BSWAP) == MO_LE) {
2631         ret = bswap128(ret);
2632     }
2633     return ret;
2634 }
2635 
2636 Int128 helper_ld16_mmu(CPUArchState *env, uint64_t addr,
2637                        uint32_t oi, uintptr_t retaddr)
2638 {
2639     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_128);
2640     return do_ld16_mmu(env, addr, oi, retaddr);
2641 }
2642 
2643 Int128 helper_ld_i128(CPUArchState *env, uint64_t addr, uint32_t oi)
2644 {
2645     return helper_ld16_mmu(env, addr, oi, GETPC());
2646 }
2647 
2648 /*
2649  * Load helpers for cpu_ldst.h.
2650  */
2651 
2652 static void plugin_load_cb(CPUArchState *env, abi_ptr addr, MemOpIdx oi)
2653 {
2654     qemu_plugin_vcpu_mem_cb(env_cpu(env), addr, oi, QEMU_PLUGIN_MEM_R);
2655 }
2656 
2657 uint8_t cpu_ldb_mmu(CPUArchState *env, abi_ptr addr, MemOpIdx oi, uintptr_t ra)
2658 {
2659     uint8_t ret;
2660 
2661     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_UB);
2662     ret = do_ld1_mmu(env, addr, oi, ra, MMU_DATA_LOAD);
2663     plugin_load_cb(env, addr, oi);
2664     return ret;
2665 }
2666 
2667 uint16_t cpu_ldw_mmu(CPUArchState *env, abi_ptr addr,
2668                      MemOpIdx oi, uintptr_t ra)
2669 {
2670     uint16_t ret;
2671 
2672     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_16);
2673     ret = do_ld2_mmu(env, addr, oi, ra, MMU_DATA_LOAD);
2674     plugin_load_cb(env, addr, oi);
2675     return ret;
2676 }
2677 
2678 uint32_t cpu_ldl_mmu(CPUArchState *env, abi_ptr addr,
2679                      MemOpIdx oi, uintptr_t ra)
2680 {
2681     uint32_t ret;
2682 
2683     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_32);
2684     ret = do_ld4_mmu(env, addr, oi, ra, MMU_DATA_LOAD);
2685     plugin_load_cb(env, addr, oi);
2686     return ret;
2687 }
2688 
2689 uint64_t cpu_ldq_mmu(CPUArchState *env, abi_ptr addr,
2690                      MemOpIdx oi, uintptr_t ra)
2691 {
2692     uint64_t ret;
2693 
2694     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_64);
2695     ret = do_ld8_mmu(env, addr, oi, ra, MMU_DATA_LOAD);
2696     plugin_load_cb(env, addr, oi);
2697     return ret;
2698 }
2699 
2700 Int128 cpu_ld16_mmu(CPUArchState *env, abi_ptr addr,
2701                     MemOpIdx oi, uintptr_t ra)
2702 {
2703     Int128 ret;
2704 
2705     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_128);
2706     ret = do_ld16_mmu(env, addr, oi, ra);
2707     plugin_load_cb(env, addr, oi);
2708     return ret;
2709 }
2710 
2711 /*
2712  * Store Helpers
2713  */
2714 
2715 /**
2716  * do_st_mmio_leN:
2717  * @env: cpu context
2718  * @full: page parameters
2719  * @val_le: data to store
2720  * @addr: virtual address
2721  * @size: number of bytes
2722  * @mmu_idx: virtual address context
2723  * @ra: return address into tcg generated code, or 0
2724  * Context: iothread lock held
2725  *
2726  * Store @size bytes at @addr, which is memory-mapped i/o.
2727  * The bytes to store are extracted in little-endian order from @val_le;
2728  * return the bytes of @val_le beyond @p->size that have not been stored.
2729  */
2730 static uint64_t do_st_mmio_leN(CPUArchState *env, CPUTLBEntryFull *full,
2731                                uint64_t val_le, vaddr addr, int size,
2732                                int mmu_idx, uintptr_t ra)
2733 {
2734     tcg_debug_assert(size > 0 && size <= 8);
2735 
2736     do {
2737         /* Store aligned pieces up to 8 bytes. */
2738         switch ((size | (int)addr) & 7) {
2739         case 1:
2740         case 3:
2741         case 5:
2742         case 7:
2743             io_writex(env, full, mmu_idx, val_le, addr, ra, MO_UB);
2744             val_le >>= 8;
2745             size -= 1;
2746             addr += 1;
2747             break;
2748         case 2:
2749         case 6:
2750             io_writex(env, full, mmu_idx, val_le, addr, ra, MO_LEUW);
2751             val_le >>= 16;
2752             size -= 2;
2753             addr += 2;
2754             break;
2755         case 4:
2756             io_writex(env, full, mmu_idx, val_le, addr, ra, MO_LEUL);
2757             val_le >>= 32;
2758             size -= 4;
2759             addr += 4;
2760             break;
2761         case 0:
2762             io_writex(env, full, mmu_idx, val_le, addr, ra, MO_LEUQ);
2763             return 0;
2764         default:
2765             qemu_build_not_reached();
2766         }
2767     } while (size);
2768 
2769     return val_le;
2770 }
2771 
2772 /*
2773  * Wrapper for the above.
2774  */
2775 static uint64_t do_st_leN(CPUArchState *env, MMULookupPageData *p,
2776                           uint64_t val_le, int mmu_idx,
2777                           MemOp mop, uintptr_t ra)
2778 {
2779     MemOp atom;
2780     unsigned tmp, half_size;
2781 
2782     if (unlikely(p->flags & TLB_MMIO)) {
2783         QEMU_IOTHREAD_LOCK_GUARD();
2784         return do_st_mmio_leN(env, p->full, val_le, p->addr,
2785                               p->size, mmu_idx, ra);
2786     } else if (unlikely(p->flags & TLB_DISCARD_WRITE)) {
2787         return val_le >> (p->size * 8);
2788     }
2789 
2790     /*
2791      * It is a given that we cross a page and therefore there is no atomicity
2792      * for the store as a whole, but subobjects may need attention.
2793      */
2794     atom = mop & MO_ATOM_MASK;
2795     switch (atom) {
2796     case MO_ATOM_SUBALIGN:
2797         return store_parts_leN(p->haddr, p->size, val_le);
2798 
2799     case MO_ATOM_IFALIGN_PAIR:
2800     case MO_ATOM_WITHIN16_PAIR:
2801         tmp = mop & MO_SIZE;
2802         tmp = tmp ? tmp - 1 : 0;
2803         half_size = 1 << tmp;
2804         if (atom == MO_ATOM_IFALIGN_PAIR
2805             ? p->size == half_size
2806             : p->size >= half_size) {
2807             if (!HAVE_al8_fast && p->size <= 4) {
2808                 return store_whole_le4(p->haddr, p->size, val_le);
2809             } else if (HAVE_al8) {
2810                 return store_whole_le8(p->haddr, p->size, val_le);
2811             } else {
2812                 cpu_loop_exit_atomic(env_cpu(env), ra);
2813             }
2814         }
2815         /* fall through */
2816 
2817     case MO_ATOM_IFALIGN:
2818     case MO_ATOM_WITHIN16:
2819     case MO_ATOM_NONE:
2820         return store_bytes_leN(p->haddr, p->size, val_le);
2821 
2822     default:
2823         g_assert_not_reached();
2824     }
2825 }
2826 
2827 /*
2828  * Wrapper for the above, for 8 < size < 16.
2829  */
2830 static uint64_t do_st16_leN(CPUArchState *env, MMULookupPageData *p,
2831                             Int128 val_le, int mmu_idx,
2832                             MemOp mop, uintptr_t ra)
2833 {
2834     int size = p->size;
2835     MemOp atom;
2836 
2837     if (unlikely(p->flags & TLB_MMIO)) {
2838         QEMU_IOTHREAD_LOCK_GUARD();
2839         do_st_mmio_leN(env, p->full, int128_getlo(val_le),
2840                        p->addr, 8, mmu_idx, ra);
2841         return do_st_mmio_leN(env, p->full, int128_gethi(val_le),
2842                               p->addr + 8, size - 8, mmu_idx, ra);
2843     } else if (unlikely(p->flags & TLB_DISCARD_WRITE)) {
2844         return int128_gethi(val_le) >> ((size - 8) * 8);
2845     }
2846 
2847     /*
2848      * It is a given that we cross a page and therefore there is no atomicity
2849      * for the store as a whole, but subobjects may need attention.
2850      */
2851     atom = mop & MO_ATOM_MASK;
2852     switch (atom) {
2853     case MO_ATOM_SUBALIGN:
2854         store_parts_leN(p->haddr, 8, int128_getlo(val_le));
2855         return store_parts_leN(p->haddr + 8, p->size - 8,
2856                                int128_gethi(val_le));
2857 
2858     case MO_ATOM_WITHIN16_PAIR:
2859         /* Since size > 8, this is the half that must be atomic. */
2860         if (!HAVE_ATOMIC128_RW) {
2861             cpu_loop_exit_atomic(env_cpu(env), ra);
2862         }
2863         return store_whole_le16(p->haddr, p->size, val_le);
2864 
2865     case MO_ATOM_IFALIGN_PAIR:
2866         /*
2867          * Since size > 8, both halves are misaligned,
2868          * and so neither is atomic.
2869          */
2870     case MO_ATOM_IFALIGN:
2871     case MO_ATOM_WITHIN16:
2872     case MO_ATOM_NONE:
2873         stq_le_p(p->haddr, int128_getlo(val_le));
2874         return store_bytes_leN(p->haddr + 8, p->size - 8,
2875                                int128_gethi(val_le));
2876 
2877     default:
2878         g_assert_not_reached();
2879     }
2880 }
2881 
2882 static void do_st_1(CPUArchState *env, MMULookupPageData *p, uint8_t val,
2883                     int mmu_idx, uintptr_t ra)
2884 {
2885     if (unlikely(p->flags & TLB_MMIO)) {
2886         io_writex(env, p->full, mmu_idx, val, p->addr, ra, MO_UB);
2887     } else if (unlikely(p->flags & TLB_DISCARD_WRITE)) {
2888         /* nothing */
2889     } else {
2890         *(uint8_t *)p->haddr = val;
2891     }
2892 }
2893 
2894 static void do_st_2(CPUArchState *env, MMULookupPageData *p, uint16_t val,
2895                     int mmu_idx, MemOp memop, uintptr_t ra)
2896 {
2897     if (unlikely(p->flags & TLB_MMIO)) {
2898         if ((memop & MO_BSWAP) != MO_LE) {
2899             val = bswap16(val);
2900         }
2901         QEMU_IOTHREAD_LOCK_GUARD();
2902         do_st_mmio_leN(env, p->full, val, p->addr, 2, mmu_idx, ra);
2903     } else if (unlikely(p->flags & TLB_DISCARD_WRITE)) {
2904         /* nothing */
2905     } else {
2906         /* Swap to host endian if necessary, then store. */
2907         if (memop & MO_BSWAP) {
2908             val = bswap16(val);
2909         }
2910         store_atom_2(env, ra, p->haddr, memop, val);
2911     }
2912 }
2913 
2914 static void do_st_4(CPUArchState *env, MMULookupPageData *p, uint32_t val,
2915                     int mmu_idx, MemOp memop, uintptr_t ra)
2916 {
2917     if (unlikely(p->flags & TLB_MMIO)) {
2918         if ((memop & MO_BSWAP) != MO_LE) {
2919             val = bswap32(val);
2920         }
2921         QEMU_IOTHREAD_LOCK_GUARD();
2922         do_st_mmio_leN(env, p->full, val, p->addr, 4, mmu_idx, ra);
2923     } else if (unlikely(p->flags & TLB_DISCARD_WRITE)) {
2924         /* nothing */
2925     } else {
2926         /* Swap to host endian if necessary, then store. */
2927         if (memop & MO_BSWAP) {
2928             val = bswap32(val);
2929         }
2930         store_atom_4(env, ra, p->haddr, memop, val);
2931     }
2932 }
2933 
2934 static void do_st_8(CPUArchState *env, MMULookupPageData *p, uint64_t val,
2935                     int mmu_idx, MemOp memop, uintptr_t ra)
2936 {
2937     if (unlikely(p->flags & TLB_MMIO)) {
2938         if ((memop & MO_BSWAP) != MO_LE) {
2939             val = bswap64(val);
2940         }
2941         QEMU_IOTHREAD_LOCK_GUARD();
2942         do_st_mmio_leN(env, p->full, val, p->addr, 8, mmu_idx, ra);
2943     } else if (unlikely(p->flags & TLB_DISCARD_WRITE)) {
2944         /* nothing */
2945     } else {
2946         /* Swap to host endian if necessary, then store. */
2947         if (memop & MO_BSWAP) {
2948             val = bswap64(val);
2949         }
2950         store_atom_8(env, ra, p->haddr, memop, val);
2951     }
2952 }
2953 
2954 void helper_stb_mmu(CPUArchState *env, uint64_t addr, uint32_t val,
2955                     MemOpIdx oi, uintptr_t ra)
2956 {
2957     MMULookupLocals l;
2958     bool crosspage;
2959 
2960     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_8);
2961     cpu_req_mo(TCG_MO_LD_ST | TCG_MO_ST_ST);
2962     crosspage = mmu_lookup(env, addr, oi, ra, MMU_DATA_STORE, &l);
2963     tcg_debug_assert(!crosspage);
2964 
2965     do_st_1(env, &l.page[0], val, l.mmu_idx, ra);
2966 }
2967 
2968 static void do_st2_mmu(CPUArchState *env, vaddr addr, uint16_t val,
2969                        MemOpIdx oi, uintptr_t ra)
2970 {
2971     MMULookupLocals l;
2972     bool crosspage;
2973     uint8_t a, b;
2974 
2975     cpu_req_mo(TCG_MO_LD_ST | TCG_MO_ST_ST);
2976     crosspage = mmu_lookup(env, addr, oi, ra, MMU_DATA_STORE, &l);
2977     if (likely(!crosspage)) {
2978         do_st_2(env, &l.page[0], val, l.mmu_idx, l.memop, ra);
2979         return;
2980     }
2981 
2982     if ((l.memop & MO_BSWAP) == MO_LE) {
2983         a = val, b = val >> 8;
2984     } else {
2985         b = val, a = val >> 8;
2986     }
2987     do_st_1(env, &l.page[0], a, l.mmu_idx, ra);
2988     do_st_1(env, &l.page[1], b, l.mmu_idx, ra);
2989 }
2990 
2991 void helper_stw_mmu(CPUArchState *env, uint64_t addr, uint32_t val,
2992                     MemOpIdx oi, uintptr_t retaddr)
2993 {
2994     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_16);
2995     do_st2_mmu(env, addr, val, oi, retaddr);
2996 }
2997 
2998 static void do_st4_mmu(CPUArchState *env, vaddr addr, uint32_t val,
2999                        MemOpIdx oi, uintptr_t ra)
3000 {
3001     MMULookupLocals l;
3002     bool crosspage;
3003 
3004     cpu_req_mo(TCG_MO_LD_ST | TCG_MO_ST_ST);
3005     crosspage = mmu_lookup(env, addr, oi, ra, MMU_DATA_STORE, &l);
3006     if (likely(!crosspage)) {
3007         do_st_4(env, &l.page[0], val, l.mmu_idx, l.memop, ra);
3008         return;
3009     }
3010 
3011     /* Swap to little endian for simplicity, then store by bytes. */
3012     if ((l.memop & MO_BSWAP) != MO_LE) {
3013         val = bswap32(val);
3014     }
3015     val = do_st_leN(env, &l.page[0], val, l.mmu_idx, l.memop, ra);
3016     (void) do_st_leN(env, &l.page[1], val, l.mmu_idx, l.memop, ra);
3017 }
3018 
3019 void helper_stl_mmu(CPUArchState *env, uint64_t addr, uint32_t val,
3020                     MemOpIdx oi, uintptr_t retaddr)
3021 {
3022     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_32);
3023     do_st4_mmu(env, addr, val, oi, retaddr);
3024 }
3025 
3026 static void do_st8_mmu(CPUArchState *env, vaddr addr, uint64_t val,
3027                        MemOpIdx oi, uintptr_t ra)
3028 {
3029     MMULookupLocals l;
3030     bool crosspage;
3031 
3032     cpu_req_mo(TCG_MO_LD_ST | TCG_MO_ST_ST);
3033     crosspage = mmu_lookup(env, addr, oi, ra, MMU_DATA_STORE, &l);
3034     if (likely(!crosspage)) {
3035         do_st_8(env, &l.page[0], val, l.mmu_idx, l.memop, ra);
3036         return;
3037     }
3038 
3039     /* Swap to little endian for simplicity, then store by bytes. */
3040     if ((l.memop & MO_BSWAP) != MO_LE) {
3041         val = bswap64(val);
3042     }
3043     val = do_st_leN(env, &l.page[0], val, l.mmu_idx, l.memop, ra);
3044     (void) do_st_leN(env, &l.page[1], val, l.mmu_idx, l.memop, ra);
3045 }
3046 
3047 void helper_stq_mmu(CPUArchState *env, uint64_t addr, uint64_t val,
3048                     MemOpIdx oi, uintptr_t retaddr)
3049 {
3050     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_64);
3051     do_st8_mmu(env, addr, val, oi, retaddr);
3052 }
3053 
3054 static void do_st16_mmu(CPUArchState *env, vaddr addr, Int128 val,
3055                         MemOpIdx oi, uintptr_t ra)
3056 {
3057     MMULookupLocals l;
3058     bool crosspage;
3059     uint64_t a, b;
3060     int first;
3061 
3062     cpu_req_mo(TCG_MO_LD_ST | TCG_MO_ST_ST);
3063     crosspage = mmu_lookup(env, addr, oi, ra, MMU_DATA_STORE, &l);
3064     if (likely(!crosspage)) {
3065         if (unlikely(l.page[0].flags & TLB_MMIO)) {
3066             if ((l.memop & MO_BSWAP) != MO_LE) {
3067                 val = bswap128(val);
3068             }
3069             a = int128_getlo(val);
3070             b = int128_gethi(val);
3071             QEMU_IOTHREAD_LOCK_GUARD();
3072             do_st_mmio_leN(env, l.page[0].full, a, addr, 8, l.mmu_idx, ra);
3073             do_st_mmio_leN(env, l.page[0].full, b, addr + 8, 8, l.mmu_idx, ra);
3074         } else if (unlikely(l.page[0].flags & TLB_DISCARD_WRITE)) {
3075             /* nothing */
3076         } else {
3077             /* Swap to host endian if necessary, then store. */
3078             if (l.memop & MO_BSWAP) {
3079                 val = bswap128(val);
3080             }
3081             store_atom_16(env, ra, l.page[0].haddr, l.memop, val);
3082         }
3083         return;
3084     }
3085 
3086     first = l.page[0].size;
3087     if (first == 8) {
3088         MemOp mop8 = (l.memop & ~(MO_SIZE | MO_BSWAP)) | MO_64;
3089 
3090         if (l.memop & MO_BSWAP) {
3091             val = bswap128(val);
3092         }
3093         if (HOST_BIG_ENDIAN) {
3094             b = int128_getlo(val), a = int128_gethi(val);
3095         } else {
3096             a = int128_getlo(val), b = int128_gethi(val);
3097         }
3098         do_st_8(env, &l.page[0], a, l.mmu_idx, mop8, ra);
3099         do_st_8(env, &l.page[1], b, l.mmu_idx, mop8, ra);
3100         return;
3101     }
3102 
3103     if ((l.memop & MO_BSWAP) != MO_LE) {
3104         val = bswap128(val);
3105     }
3106     if (first < 8) {
3107         do_st_leN(env, &l.page[0], int128_getlo(val), l.mmu_idx, l.memop, ra);
3108         val = int128_urshift(val, first * 8);
3109         do_st16_leN(env, &l.page[1], val, l.mmu_idx, l.memop, ra);
3110     } else {
3111         b = do_st16_leN(env, &l.page[0], val, l.mmu_idx, l.memop, ra);
3112         do_st_leN(env, &l.page[1], b, l.mmu_idx, l.memop, ra);
3113     }
3114 }
3115 
3116 void helper_st16_mmu(CPUArchState *env, uint64_t addr, Int128 val,
3117                      MemOpIdx oi, uintptr_t retaddr)
3118 {
3119     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_128);
3120     do_st16_mmu(env, addr, val, oi, retaddr);
3121 }
3122 
3123 void helper_st_i128(CPUArchState *env, uint64_t addr, Int128 val, MemOpIdx oi)
3124 {
3125     helper_st16_mmu(env, addr, val, oi, GETPC());
3126 }
3127 
3128 /*
3129  * Store Helpers for cpu_ldst.h
3130  */
3131 
3132 static void plugin_store_cb(CPUArchState *env, abi_ptr addr, MemOpIdx oi)
3133 {
3134     qemu_plugin_vcpu_mem_cb(env_cpu(env), addr, oi, QEMU_PLUGIN_MEM_W);
3135 }
3136 
3137 void cpu_stb_mmu(CPUArchState *env, abi_ptr addr, uint8_t val,
3138                  MemOpIdx oi, uintptr_t retaddr)
3139 {
3140     helper_stb_mmu(env, addr, val, oi, retaddr);
3141     plugin_store_cb(env, addr, oi);
3142 }
3143 
3144 void cpu_stw_mmu(CPUArchState *env, abi_ptr addr, uint16_t val,
3145                  MemOpIdx oi, uintptr_t retaddr)
3146 {
3147     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_16);
3148     do_st2_mmu(env, addr, val, oi, retaddr);
3149     plugin_store_cb(env, addr, oi);
3150 }
3151 
3152 void cpu_stl_mmu(CPUArchState *env, abi_ptr addr, uint32_t val,
3153                     MemOpIdx oi, uintptr_t retaddr)
3154 {
3155     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_32);
3156     do_st4_mmu(env, addr, val, oi, retaddr);
3157     plugin_store_cb(env, addr, oi);
3158 }
3159 
3160 void cpu_stq_mmu(CPUArchState *env, abi_ptr addr, uint64_t val,
3161                  MemOpIdx oi, uintptr_t retaddr)
3162 {
3163     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_64);
3164     do_st8_mmu(env, addr, val, oi, retaddr);
3165     plugin_store_cb(env, addr, oi);
3166 }
3167 
3168 void cpu_st16_mmu(CPUArchState *env, abi_ptr addr, Int128 val,
3169                   MemOpIdx oi, uintptr_t retaddr)
3170 {
3171     tcg_debug_assert((get_memop(oi) & MO_SIZE) == MO_128);
3172     do_st16_mmu(env, addr, val, oi, retaddr);
3173     plugin_store_cb(env, addr, oi);
3174 }
3175 
3176 #include "ldst_common.c.inc"
3177 
3178 /*
3179  * First set of functions passes in OI and RETADDR.
3180  * This makes them callable from other helpers.
3181  */
3182 
3183 #define ATOMIC_NAME(X) \
3184     glue(glue(glue(cpu_atomic_ ## X, SUFFIX), END), _mmu)
3185 
3186 #define ATOMIC_MMU_CLEANUP
3187 
3188 #include "atomic_common.c.inc"
3189 
3190 #define DATA_SIZE 1
3191 #include "atomic_template.h"
3192 
3193 #define DATA_SIZE 2
3194 #include "atomic_template.h"
3195 
3196 #define DATA_SIZE 4
3197 #include "atomic_template.h"
3198 
3199 #ifdef CONFIG_ATOMIC64
3200 #define DATA_SIZE 8
3201 #include "atomic_template.h"
3202 #endif
3203 
3204 #if defined(CONFIG_ATOMIC128) || HAVE_CMPXCHG128
3205 #define DATA_SIZE 16
3206 #include "atomic_template.h"
3207 #endif
3208 
3209 /* Code access functions.  */
3210 
3211 uint32_t cpu_ldub_code(CPUArchState *env, abi_ptr addr)
3212 {
3213     MemOpIdx oi = make_memop_idx(MO_UB, cpu_mmu_index(env, true));
3214     return do_ld1_mmu(env, addr, oi, 0, MMU_INST_FETCH);
3215 }
3216 
3217 uint32_t cpu_lduw_code(CPUArchState *env, abi_ptr addr)
3218 {
3219     MemOpIdx oi = make_memop_idx(MO_TEUW, cpu_mmu_index(env, true));
3220     return do_ld2_mmu(env, addr, oi, 0, MMU_INST_FETCH);
3221 }
3222 
3223 uint32_t cpu_ldl_code(CPUArchState *env, abi_ptr addr)
3224 {
3225     MemOpIdx oi = make_memop_idx(MO_TEUL, cpu_mmu_index(env, true));
3226     return do_ld4_mmu(env, addr, oi, 0, MMU_INST_FETCH);
3227 }
3228 
3229 uint64_t cpu_ldq_code(CPUArchState *env, abi_ptr addr)
3230 {
3231     MemOpIdx oi = make_memop_idx(MO_TEUQ, cpu_mmu_index(env, true));
3232     return do_ld8_mmu(env, addr, oi, 0, MMU_INST_FETCH);
3233 }
3234 
3235 uint8_t cpu_ldb_code_mmu(CPUArchState *env, abi_ptr addr,
3236                          MemOpIdx oi, uintptr_t retaddr)
3237 {
3238     return do_ld1_mmu(env, addr, oi, retaddr, MMU_INST_FETCH);
3239 }
3240 
3241 uint16_t cpu_ldw_code_mmu(CPUArchState *env, abi_ptr addr,
3242                           MemOpIdx oi, uintptr_t retaddr)
3243 {
3244     return do_ld2_mmu(env, addr, oi, retaddr, MMU_INST_FETCH);
3245 }
3246 
3247 uint32_t cpu_ldl_code_mmu(CPUArchState *env, abi_ptr addr,
3248                           MemOpIdx oi, uintptr_t retaddr)
3249 {
3250     return do_ld4_mmu(env, addr, oi, retaddr, MMU_INST_FETCH);
3251 }
3252 
3253 uint64_t cpu_ldq_code_mmu(CPUArchState *env, abi_ptr addr,
3254                           MemOpIdx oi, uintptr_t retaddr)
3255 {
3256     return do_ld8_mmu(env, addr, oi, retaddr, MMU_INST_FETCH);
3257 }
3258