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