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