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