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