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