xref: /qemu/accel/tcg/user-exec.c (revision cc944932ecef3b7a56ae62d89dd92fb9e56c5cc8)
1 /*
2  *  User emulator execution
3  *
4  *  Copyright (c) 2003-2005 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 #include "qemu/osdep.h"
20 #include "accel/tcg/cpu-ops.h"
21 #include "disas/disas.h"
22 #include "exec/vaddr.h"
23 #include "exec/exec-all.h"
24 #include "exec/tlb-flags.h"
25 #include "tcg/tcg.h"
26 #include "qemu/bitops.h"
27 #include "qemu/rcu.h"
28 #include "exec/cpu_ldst.h"
29 #include "user/cpu_loop.h"
30 #include "qemu/main-loop.h"
31 #include "user/page-protection.h"
32 #include "exec/page-protection.h"
33 #include "exec/helper-proto.h"
34 #include "qemu/atomic128.h"
35 #include "qemu/bswap.h"
36 #include "qemu/int128.h"
37 #include "trace.h"
38 #include "tcg/tcg-ldst.h"
39 #include "internal-common.h"
40 #include "internal-target.h"
41 #include "tb-internal.h"
42 
43 __thread uintptr_t helper_retaddr;
44 
45 //#define DEBUG_SIGNAL
46 
47 void cpu_interrupt(CPUState *cpu, int mask)
48 {
49     g_assert(bql_locked());
50     cpu->interrupt_request |= mask;
51     qatomic_set(&cpu->neg.icount_decr.u16.high, -1);
52 }
53 
54 /*
55  * Adjust the pc to pass to cpu_restore_state; return the memop type.
56  */
57 MMUAccessType adjust_signal_pc(uintptr_t *pc, bool is_write)
58 {
59     switch (helper_retaddr) {
60     default:
61         /*
62          * Fault during host memory operation within a helper function.
63          * The helper's host return address, saved here, gives us a
64          * pointer into the generated code that will unwind to the
65          * correct guest pc.
66          */
67         *pc = helper_retaddr;
68         break;
69 
70     case 0:
71         /*
72          * Fault during host memory operation within generated code.
73          * (Or, a unrelated bug within qemu, but we can't tell from here).
74          *
75          * We take the host pc from the signal frame.  However, we cannot
76          * use that value directly.  Within cpu_restore_state_from_tb, we
77          * assume PC comes from GETPC(), as used by the helper functions,
78          * so we adjust the address by -GETPC_ADJ to form an address that
79          * is within the call insn, so that the address does not accidentally
80          * match the beginning of the next guest insn.  However, when the
81          * pc comes from the signal frame it points to the actual faulting
82          * host memory insn and not the return from a call insn.
83          *
84          * Therefore, adjust to compensate for what will be done later
85          * by cpu_restore_state_from_tb.
86          */
87         *pc += GETPC_ADJ;
88         break;
89 
90     case 1:
91         /*
92          * Fault during host read for translation, or loosely, "execution".
93          *
94          * The guest pc is already pointing to the start of the TB for which
95          * code is being generated.  If the guest translator manages the
96          * page crossings correctly, this is exactly the correct address
97          * (and if the translator doesn't handle page boundaries correctly
98          * there's little we can do about that here).  Therefore, do not
99          * trigger the unwinder.
100          */
101         *pc = 0;
102         return MMU_INST_FETCH;
103     }
104 
105     return is_write ? MMU_DATA_STORE : MMU_DATA_LOAD;
106 }
107 
108 /**
109  * handle_sigsegv_accerr_write:
110  * @cpu: the cpu context
111  * @old_set: the sigset_t from the signal ucontext_t
112  * @host_pc: the host pc, adjusted for the signal
113  * @guest_addr: the guest address of the fault
114  *
115  * Return true if the write fault has been handled, and should be re-tried.
116  *
117  * Note that it is important that we don't call page_unprotect() unless
118  * this is really a "write to nonwritable page" fault, because
119  * page_unprotect() assumes that if it is called for an access to
120  * a page that's writable this means we had two threads racing and
121  * another thread got there first and already made the page writable;
122  * so we will retry the access. If we were to call page_unprotect()
123  * for some other kind of fault that should really be passed to the
124  * guest, we'd end up in an infinite loop of retrying the faulting access.
125  */
126 bool handle_sigsegv_accerr_write(CPUState *cpu, sigset_t *old_set,
127                                  uintptr_t host_pc, abi_ptr guest_addr)
128 {
129     switch (page_unprotect(guest_addr, host_pc)) {
130     case 0:
131         /*
132          * Fault not caused by a page marked unwritable to protect
133          * cached translations, must be the guest binary's problem.
134          */
135         return false;
136     case 1:
137         /*
138          * Fault caused by protection of cached translation; TBs
139          * invalidated, so resume execution.
140          */
141         return true;
142     case 2:
143         /*
144          * Fault caused by protection of cached translation, and the
145          * currently executing TB was modified and must be exited immediately.
146          */
147         sigprocmask(SIG_SETMASK, old_set, NULL);
148         cpu_loop_exit_noexc(cpu);
149         /* NORETURN */
150     default:
151         g_assert_not_reached();
152     }
153 }
154 
155 typedef struct PageFlagsNode {
156     struct rcu_head rcu;
157     IntervalTreeNode itree;
158     int flags;
159 } PageFlagsNode;
160 
161 static IntervalTreeRoot pageflags_root;
162 
163 static PageFlagsNode *pageflags_find(target_ulong start, target_ulong last)
164 {
165     IntervalTreeNode *n;
166 
167     n = interval_tree_iter_first(&pageflags_root, start, last);
168     return n ? container_of(n, PageFlagsNode, itree) : NULL;
169 }
170 
171 static PageFlagsNode *pageflags_next(PageFlagsNode *p, target_ulong start,
172                                      target_ulong last)
173 {
174     IntervalTreeNode *n;
175 
176     n = interval_tree_iter_next(&p->itree, start, last);
177     return n ? container_of(n, PageFlagsNode, itree) : NULL;
178 }
179 
180 int walk_memory_regions(void *priv, walk_memory_regions_fn fn)
181 {
182     IntervalTreeNode *n;
183     int rc = 0;
184 
185     mmap_lock();
186     for (n = interval_tree_iter_first(&pageflags_root, 0, -1);
187          n != NULL;
188          n = interval_tree_iter_next(n, 0, -1)) {
189         PageFlagsNode *p = container_of(n, PageFlagsNode, itree);
190 
191         rc = fn(priv, n->start, n->last + 1, p->flags);
192         if (rc != 0) {
193             break;
194         }
195     }
196     mmap_unlock();
197 
198     return rc;
199 }
200 
201 static int dump_region(void *priv, target_ulong start,
202                        target_ulong end, unsigned long prot)
203 {
204     FILE *f = (FILE *)priv;
205 
206     fprintf(f, TARGET_FMT_lx"-"TARGET_FMT_lx" "TARGET_FMT_lx" %c%c%c\n",
207             start, end, end - start,
208             ((prot & PAGE_READ) ? 'r' : '-'),
209             ((prot & PAGE_WRITE) ? 'w' : '-'),
210             ((prot & PAGE_EXEC) ? 'x' : '-'));
211     return 0;
212 }
213 
214 /* dump memory mappings */
215 void page_dump(FILE *f)
216 {
217     const int length = sizeof(target_ulong) * 2;
218 
219     fprintf(f, "%-*s %-*s %-*s %s\n",
220             length, "start", length, "end", length, "size", "prot");
221     walk_memory_regions(f, dump_region);
222 }
223 
224 int page_get_flags(target_ulong address)
225 {
226     PageFlagsNode *p = pageflags_find(address, address);
227 
228     /*
229      * See util/interval-tree.c re lockless lookups: no false positives but
230      * there are false negatives.  If we find nothing, retry with the mmap
231      * lock acquired.
232      */
233     if (p) {
234         return p->flags;
235     }
236     if (have_mmap_lock()) {
237         return 0;
238     }
239 
240     mmap_lock();
241     p = pageflags_find(address, address);
242     mmap_unlock();
243     return p ? p->flags : 0;
244 }
245 
246 /* A subroutine of page_set_flags: insert a new node for [start,last]. */
247 static void pageflags_create(target_ulong start, target_ulong last, int flags)
248 {
249     PageFlagsNode *p = g_new(PageFlagsNode, 1);
250 
251     p->itree.start = start;
252     p->itree.last = last;
253     p->flags = flags;
254     interval_tree_insert(&p->itree, &pageflags_root);
255 }
256 
257 /* A subroutine of page_set_flags: remove everything in [start,last]. */
258 static bool pageflags_unset(target_ulong start, target_ulong last)
259 {
260     bool inval_tb = false;
261 
262     while (true) {
263         PageFlagsNode *p = pageflags_find(start, last);
264         target_ulong p_last;
265 
266         if (!p) {
267             break;
268         }
269 
270         if (p->flags & PAGE_EXEC) {
271             inval_tb = true;
272         }
273 
274         interval_tree_remove(&p->itree, &pageflags_root);
275         p_last = p->itree.last;
276 
277         if (p->itree.start < start) {
278             /* Truncate the node from the end, or split out the middle. */
279             p->itree.last = start - 1;
280             interval_tree_insert(&p->itree, &pageflags_root);
281             if (last < p_last) {
282                 pageflags_create(last + 1, p_last, p->flags);
283                 break;
284             }
285         } else if (p_last <= last) {
286             /* Range completely covers node -- remove it. */
287             g_free_rcu(p, rcu);
288         } else {
289             /* Truncate the node from the start. */
290             p->itree.start = last + 1;
291             interval_tree_insert(&p->itree, &pageflags_root);
292             break;
293         }
294     }
295 
296     return inval_tb;
297 }
298 
299 /*
300  * A subroutine of page_set_flags: nothing overlaps [start,last],
301  * but check adjacent mappings and maybe merge into a single range.
302  */
303 static void pageflags_create_merge(target_ulong start, target_ulong last,
304                                    int flags)
305 {
306     PageFlagsNode *next = NULL, *prev = NULL;
307 
308     if (start > 0) {
309         prev = pageflags_find(start - 1, start - 1);
310         if (prev) {
311             if (prev->flags == flags) {
312                 interval_tree_remove(&prev->itree, &pageflags_root);
313             } else {
314                 prev = NULL;
315             }
316         }
317     }
318     if (last + 1 != 0) {
319         next = pageflags_find(last + 1, last + 1);
320         if (next) {
321             if (next->flags == flags) {
322                 interval_tree_remove(&next->itree, &pageflags_root);
323             } else {
324                 next = NULL;
325             }
326         }
327     }
328 
329     if (prev) {
330         if (next) {
331             prev->itree.last = next->itree.last;
332             g_free_rcu(next, rcu);
333         } else {
334             prev->itree.last = last;
335         }
336         interval_tree_insert(&prev->itree, &pageflags_root);
337     } else if (next) {
338         next->itree.start = start;
339         interval_tree_insert(&next->itree, &pageflags_root);
340     } else {
341         pageflags_create(start, last, flags);
342     }
343 }
344 
345 /*
346  * Allow the target to decide if PAGE_TARGET_[12] may be reset.
347  * By default, they are not kept.
348  */
349 #ifndef PAGE_TARGET_STICKY
350 #define PAGE_TARGET_STICKY  0
351 #endif
352 #define PAGE_STICKY  (PAGE_ANON | PAGE_PASSTHROUGH | PAGE_TARGET_STICKY)
353 
354 /* A subroutine of page_set_flags: add flags to [start,last]. */
355 static bool pageflags_set_clear(target_ulong start, target_ulong last,
356                                 int set_flags, int clear_flags)
357 {
358     PageFlagsNode *p;
359     target_ulong p_start, p_last;
360     int p_flags, merge_flags;
361     bool inval_tb = false;
362 
363  restart:
364     p = pageflags_find(start, last);
365     if (!p) {
366         if (set_flags) {
367             pageflags_create_merge(start, last, set_flags);
368         }
369         goto done;
370     }
371 
372     p_start = p->itree.start;
373     p_last = p->itree.last;
374     p_flags = p->flags;
375     /* Using mprotect on a page does not change sticky bits. */
376     merge_flags = (p_flags & ~clear_flags) | set_flags;
377 
378     /*
379      * Need to flush if an overlapping executable region
380      * removes exec, or adds write.
381      */
382     if ((p_flags & PAGE_EXEC)
383         && (!(merge_flags & PAGE_EXEC)
384             || (merge_flags & ~p_flags & PAGE_WRITE))) {
385         inval_tb = true;
386     }
387 
388     /*
389      * If there is an exact range match, update and return without
390      * attempting to merge with adjacent regions.
391      */
392     if (start == p_start && last == p_last) {
393         if (merge_flags) {
394             p->flags = merge_flags;
395         } else {
396             interval_tree_remove(&p->itree, &pageflags_root);
397             g_free_rcu(p, rcu);
398         }
399         goto done;
400     }
401 
402     /*
403      * If sticky bits affect the original mapping, then we must be more
404      * careful about the existing intervals and the separate flags.
405      */
406     if (set_flags != merge_flags) {
407         if (p_start < start) {
408             interval_tree_remove(&p->itree, &pageflags_root);
409             p->itree.last = start - 1;
410             interval_tree_insert(&p->itree, &pageflags_root);
411 
412             if (last < p_last) {
413                 if (merge_flags) {
414                     pageflags_create(start, last, merge_flags);
415                 }
416                 pageflags_create(last + 1, p_last, p_flags);
417             } else {
418                 if (merge_flags) {
419                     pageflags_create(start, p_last, merge_flags);
420                 }
421                 if (p_last < last) {
422                     start = p_last + 1;
423                     goto restart;
424                 }
425             }
426         } else {
427             if (start < p_start && set_flags) {
428                 pageflags_create(start, p_start - 1, set_flags);
429             }
430             if (last < p_last) {
431                 interval_tree_remove(&p->itree, &pageflags_root);
432                 p->itree.start = last + 1;
433                 interval_tree_insert(&p->itree, &pageflags_root);
434                 if (merge_flags) {
435                     pageflags_create(start, last, merge_flags);
436                 }
437             } else {
438                 if (merge_flags) {
439                     p->flags = merge_flags;
440                 } else {
441                     interval_tree_remove(&p->itree, &pageflags_root);
442                     g_free_rcu(p, rcu);
443                 }
444                 if (p_last < last) {
445                     start = p_last + 1;
446                     goto restart;
447                 }
448             }
449         }
450         goto done;
451     }
452 
453     /* If flags are not changing for this range, incorporate it. */
454     if (set_flags == p_flags) {
455         if (start < p_start) {
456             interval_tree_remove(&p->itree, &pageflags_root);
457             p->itree.start = start;
458             interval_tree_insert(&p->itree, &pageflags_root);
459         }
460         if (p_last < last) {
461             start = p_last + 1;
462             goto restart;
463         }
464         goto done;
465     }
466 
467     /* Maybe split out head and/or tail ranges with the original flags. */
468     interval_tree_remove(&p->itree, &pageflags_root);
469     if (p_start < start) {
470         p->itree.last = start - 1;
471         interval_tree_insert(&p->itree, &pageflags_root);
472 
473         if (p_last < last) {
474             goto restart;
475         }
476         if (last < p_last) {
477             pageflags_create(last + 1, p_last, p_flags);
478         }
479     } else if (last < p_last) {
480         p->itree.start = last + 1;
481         interval_tree_insert(&p->itree, &pageflags_root);
482     } else {
483         g_free_rcu(p, rcu);
484         goto restart;
485     }
486     if (set_flags) {
487         pageflags_create(start, last, set_flags);
488     }
489 
490  done:
491     return inval_tb;
492 }
493 
494 void page_set_flags(target_ulong start, target_ulong last, int flags)
495 {
496     bool reset = false;
497     bool inval_tb = false;
498 
499     /* This function should never be called with addresses outside the
500        guest address space.  If this assert fires, it probably indicates
501        a missing call to h2g_valid.  */
502     assert(start <= last);
503     assert(last <= GUEST_ADDR_MAX);
504     /* Only set PAGE_ANON with new mappings. */
505     assert(!(flags & PAGE_ANON) || (flags & PAGE_RESET));
506     assert_memory_lock();
507 
508     start &= TARGET_PAGE_MASK;
509     last |= ~TARGET_PAGE_MASK;
510 
511     if (!(flags & PAGE_VALID)) {
512         flags = 0;
513     } else {
514         reset = flags & PAGE_RESET;
515         flags &= ~PAGE_RESET;
516         if (flags & PAGE_WRITE) {
517             flags |= PAGE_WRITE_ORG;
518         }
519     }
520 
521     if (!flags || reset) {
522         page_reset_target_data(start, last);
523         inval_tb |= pageflags_unset(start, last);
524     }
525     if (flags) {
526         inval_tb |= pageflags_set_clear(start, last, flags,
527                                         ~(reset ? 0 : PAGE_STICKY));
528     }
529     if (inval_tb) {
530         tb_invalidate_phys_range(start, last);
531     }
532 }
533 
534 bool page_check_range(target_ulong start, target_ulong len, int flags)
535 {
536     target_ulong last;
537     int locked;  /* tri-state: =0: unlocked, +1: global, -1: local */
538     bool ret;
539 
540     if (len == 0) {
541         return true;  /* trivial length */
542     }
543 
544     last = start + len - 1;
545     if (last < start) {
546         return false; /* wrap around */
547     }
548 
549     locked = have_mmap_lock();
550     while (true) {
551         PageFlagsNode *p = pageflags_find(start, last);
552         int missing;
553 
554         if (!p) {
555             if (!locked) {
556                 /*
557                  * Lockless lookups have false negatives.
558                  * Retry with the lock held.
559                  */
560                 mmap_lock();
561                 locked = -1;
562                 p = pageflags_find(start, last);
563             }
564             if (!p) {
565                 ret = false; /* entire region invalid */
566                 break;
567             }
568         }
569         if (start < p->itree.start) {
570             ret = false; /* initial bytes invalid */
571             break;
572         }
573 
574         missing = flags & ~p->flags;
575         if (missing & ~PAGE_WRITE) {
576             ret = false; /* page doesn't match */
577             break;
578         }
579         if (missing & PAGE_WRITE) {
580             if (!(p->flags & PAGE_WRITE_ORG)) {
581                 ret = false; /* page not writable */
582                 break;
583             }
584             /* Asking about writable, but has been protected: undo. */
585             if (!page_unprotect(start, 0)) {
586                 ret = false;
587                 break;
588             }
589             /* TODO: page_unprotect should take a range, not a single page. */
590             if (last - start < TARGET_PAGE_SIZE) {
591                 ret = true; /* ok */
592                 break;
593             }
594             start += TARGET_PAGE_SIZE;
595             continue;
596         }
597 
598         if (last <= p->itree.last) {
599             ret = true; /* ok */
600             break;
601         }
602         start = p->itree.last + 1;
603     }
604 
605     /* Release the lock if acquired locally. */
606     if (locked < 0) {
607         mmap_unlock();
608     }
609     return ret;
610 }
611 
612 bool page_check_range_empty(target_ulong start, target_ulong last)
613 {
614     assert(last >= start);
615     assert_memory_lock();
616     return pageflags_find(start, last) == NULL;
617 }
618 
619 target_ulong page_find_range_empty(target_ulong min, target_ulong max,
620                                    target_ulong len, target_ulong align)
621 {
622     target_ulong len_m1, align_m1;
623 
624     assert(min <= max);
625     assert(max <= GUEST_ADDR_MAX);
626     assert(len != 0);
627     assert(is_power_of_2(align));
628     assert_memory_lock();
629 
630     len_m1 = len - 1;
631     align_m1 = align - 1;
632 
633     /* Iteratively narrow the search region. */
634     while (1) {
635         PageFlagsNode *p;
636 
637         /* Align min and double-check there's enough space remaining. */
638         min = (min + align_m1) & ~align_m1;
639         if (min > max) {
640             return -1;
641         }
642         if (len_m1 > max - min) {
643             return -1;
644         }
645 
646         p = pageflags_find(min, min + len_m1);
647         if (p == NULL) {
648             /* Found! */
649             return min;
650         }
651         if (max <= p->itree.last) {
652             /* Existing allocation fills the remainder of the search region. */
653             return -1;
654         }
655         /* Skip across existing allocation. */
656         min = p->itree.last + 1;
657     }
658 }
659 
660 void tb_lock_page0(tb_page_addr_t address)
661 {
662     PageFlagsNode *p;
663     target_ulong start, last;
664     int host_page_size = qemu_real_host_page_size();
665     int prot;
666 
667     assert_memory_lock();
668 
669     if (host_page_size <= TARGET_PAGE_SIZE) {
670         start = address & TARGET_PAGE_MASK;
671         last = start + TARGET_PAGE_SIZE - 1;
672     } else {
673         start = address & -host_page_size;
674         last = start + host_page_size - 1;
675     }
676 
677     p = pageflags_find(start, last);
678     if (!p) {
679         return;
680     }
681     prot = p->flags;
682 
683     if (unlikely(p->itree.last < last)) {
684         /* More than one protection region covers the one host page. */
685         assert(TARGET_PAGE_SIZE < host_page_size);
686         while ((p = pageflags_next(p, start, last)) != NULL) {
687             prot |= p->flags;
688         }
689     }
690 
691     if (prot & PAGE_WRITE) {
692         pageflags_set_clear(start, last, 0, PAGE_WRITE);
693         mprotect(g2h_untagged(start), last - start + 1,
694                  prot & (PAGE_READ | PAGE_EXEC) ? PROT_READ : PROT_NONE);
695     }
696 }
697 
698 /*
699  * Called from signal handler: invalidate the code and unprotect the
700  * page. Return 0 if the fault was not handled, 1 if it was handled,
701  * and 2 if it was handled but the caller must cause the TB to be
702  * immediately exited. (We can only return 2 if the 'pc' argument is
703  * non-zero.)
704  */
705 int page_unprotect(tb_page_addr_t address, uintptr_t pc)
706 {
707     PageFlagsNode *p;
708     bool current_tb_invalidated;
709 
710     /*
711      * Technically this isn't safe inside a signal handler.  However we
712      * know this only ever happens in a synchronous SEGV handler, so in
713      * practice it seems to be ok.
714      */
715     mmap_lock();
716 
717     p = pageflags_find(address, address);
718 
719     /* If this address was not really writable, nothing to do. */
720     if (!p || !(p->flags & PAGE_WRITE_ORG)) {
721         mmap_unlock();
722         return 0;
723     }
724 
725     current_tb_invalidated = false;
726     if (p->flags & PAGE_WRITE) {
727         /*
728          * If the page is actually marked WRITE then assume this is because
729          * this thread raced with another one which got here first and
730          * set the page to PAGE_WRITE and did the TB invalidate for us.
731          */
732 #ifdef TARGET_HAS_PRECISE_SMC
733         TranslationBlock *current_tb = tcg_tb_lookup(pc);
734         if (current_tb) {
735             current_tb_invalidated = tb_cflags(current_tb) & CF_INVALID;
736         }
737 #endif
738     } else {
739         int host_page_size = qemu_real_host_page_size();
740         target_ulong start, len, i;
741         int prot;
742 
743         if (host_page_size <= TARGET_PAGE_SIZE) {
744             start = address & TARGET_PAGE_MASK;
745             len = TARGET_PAGE_SIZE;
746             prot = p->flags | PAGE_WRITE;
747             pageflags_set_clear(start, start + len - 1, PAGE_WRITE, 0);
748             current_tb_invalidated = tb_invalidate_phys_page_unwind(start, pc);
749         } else {
750             start = address & -host_page_size;
751             len = host_page_size;
752             prot = 0;
753 
754             for (i = 0; i < len; i += TARGET_PAGE_SIZE) {
755                 target_ulong addr = start + i;
756 
757                 p = pageflags_find(addr, addr);
758                 if (p) {
759                     prot |= p->flags;
760                     if (p->flags & PAGE_WRITE_ORG) {
761                         prot |= PAGE_WRITE;
762                         pageflags_set_clear(addr, addr + TARGET_PAGE_SIZE - 1,
763                                             PAGE_WRITE, 0);
764                     }
765                 }
766                 /*
767                  * Since the content will be modified, we must invalidate
768                  * the corresponding translated code.
769                  */
770                 current_tb_invalidated |=
771                     tb_invalidate_phys_page_unwind(addr, pc);
772             }
773         }
774         if (prot & PAGE_EXEC) {
775             prot = (prot & ~PAGE_EXEC) | PAGE_READ;
776         }
777         mprotect((void *)g2h_untagged(start), len, prot & PAGE_RWX);
778     }
779     mmap_unlock();
780 
781     /* If current TB was invalidated return to main loop */
782     return current_tb_invalidated ? 2 : 1;
783 }
784 
785 static int probe_access_internal(CPUArchState *env, vaddr addr,
786                                  int fault_size, MMUAccessType access_type,
787                                  bool nonfault, uintptr_t ra)
788 {
789     int acc_flag;
790     bool maperr;
791 
792     switch (access_type) {
793     case MMU_DATA_STORE:
794         acc_flag = PAGE_WRITE_ORG;
795         break;
796     case MMU_DATA_LOAD:
797         acc_flag = PAGE_READ;
798         break;
799     case MMU_INST_FETCH:
800         acc_flag = PAGE_EXEC;
801         break;
802     default:
803         g_assert_not_reached();
804     }
805 
806     if (guest_addr_valid_untagged(addr)) {
807         int page_flags = page_get_flags(addr);
808         if (page_flags & acc_flag) {
809             if (access_type != MMU_INST_FETCH
810                 && cpu_plugin_mem_cbs_enabled(env_cpu(env))) {
811                 return TLB_MMIO;
812             }
813             return 0; /* success */
814         }
815         maperr = !(page_flags & PAGE_VALID);
816     } else {
817         maperr = true;
818     }
819 
820     if (nonfault) {
821         return TLB_INVALID_MASK;
822     }
823 
824     cpu_loop_exit_sigsegv(env_cpu(env), addr, access_type, maperr, ra);
825 }
826 
827 int probe_access_flags(CPUArchState *env, vaddr addr, int size,
828                        MMUAccessType access_type, int mmu_idx,
829                        bool nonfault, void **phost, uintptr_t ra)
830 {
831     int flags;
832 
833     g_assert(-(addr | TARGET_PAGE_MASK) >= size);
834     flags = probe_access_internal(env, addr, size, access_type, nonfault, ra);
835     *phost = (flags & TLB_INVALID_MASK) ? NULL : g2h(env_cpu(env), addr);
836     return flags;
837 }
838 
839 void *probe_access(CPUArchState *env, vaddr addr, int size,
840                    MMUAccessType access_type, int mmu_idx, uintptr_t ra)
841 {
842     int flags;
843 
844     g_assert(-(addr | TARGET_PAGE_MASK) >= size);
845     flags = probe_access_internal(env, addr, size, access_type, false, ra);
846     g_assert((flags & ~TLB_MMIO) == 0);
847 
848     return size ? g2h(env_cpu(env), addr) : NULL;
849 }
850 
851 tb_page_addr_t get_page_addr_code_hostp(CPUArchState *env, vaddr addr,
852                                         void **hostp)
853 {
854     int flags;
855 
856     flags = probe_access_internal(env, addr, 1, MMU_INST_FETCH, false, 0);
857     g_assert(flags == 0);
858 
859     if (hostp) {
860         *hostp = g2h_untagged(addr);
861     }
862     return addr;
863 }
864 
865 #ifdef TARGET_PAGE_DATA_SIZE
866 /*
867  * Allocate chunks of target data together.  For the only current user,
868  * if we allocate one hunk per page, we have overhead of 40/128 or 40%.
869  * Therefore, allocate memory for 64 pages at a time for overhead < 1%.
870  */
871 #define TPD_PAGES  64
872 #define TBD_MASK   (TARGET_PAGE_MASK * TPD_PAGES)
873 
874 typedef struct TargetPageDataNode {
875     struct rcu_head rcu;
876     IntervalTreeNode itree;
877     char data[] __attribute__((aligned));
878 } TargetPageDataNode;
879 
880 static IntervalTreeRoot targetdata_root;
881 
882 void page_reset_target_data(target_ulong start, target_ulong last)
883 {
884     IntervalTreeNode *n, *next;
885 
886     assert_memory_lock();
887 
888     start &= TARGET_PAGE_MASK;
889     last |= ~TARGET_PAGE_MASK;
890 
891     for (n = interval_tree_iter_first(&targetdata_root, start, last),
892          next = n ? interval_tree_iter_next(n, start, last) : NULL;
893          n != NULL;
894          n = next,
895          next = next ? interval_tree_iter_next(n, start, last) : NULL) {
896         target_ulong n_start, n_last, p_ofs, p_len;
897         TargetPageDataNode *t = container_of(n, TargetPageDataNode, itree);
898 
899         if (n->start >= start && n->last <= last) {
900             interval_tree_remove(n, &targetdata_root);
901             g_free_rcu(t, rcu);
902             continue;
903         }
904 
905         if (n->start < start) {
906             n_start = start;
907             p_ofs = (start - n->start) >> TARGET_PAGE_BITS;
908         } else {
909             n_start = n->start;
910             p_ofs = 0;
911         }
912         n_last = MIN(last, n->last);
913         p_len = (n_last + 1 - n_start) >> TARGET_PAGE_BITS;
914 
915         memset(t->data + p_ofs * TARGET_PAGE_DATA_SIZE, 0,
916                p_len * TARGET_PAGE_DATA_SIZE);
917     }
918 }
919 
920 void *page_get_target_data(target_ulong address)
921 {
922     IntervalTreeNode *n;
923     TargetPageDataNode *t;
924     target_ulong page, region, p_ofs;
925 
926     page = address & TARGET_PAGE_MASK;
927     region = address & TBD_MASK;
928 
929     n = interval_tree_iter_first(&targetdata_root, page, page);
930     if (!n) {
931         /*
932          * See util/interval-tree.c re lockless lookups: no false positives
933          * but there are false negatives.  If we find nothing, retry with
934          * the mmap lock acquired.  We also need the lock for the
935          * allocation + insert.
936          */
937         mmap_lock();
938         n = interval_tree_iter_first(&targetdata_root, page, page);
939         if (!n) {
940             t = g_malloc0(sizeof(TargetPageDataNode)
941                           + TPD_PAGES * TARGET_PAGE_DATA_SIZE);
942             n = &t->itree;
943             n->start = region;
944             n->last = region | ~TBD_MASK;
945             interval_tree_insert(n, &targetdata_root);
946         }
947         mmap_unlock();
948     }
949 
950     t = container_of(n, TargetPageDataNode, itree);
951     p_ofs = (page - region) >> TARGET_PAGE_BITS;
952     return t->data + p_ofs * TARGET_PAGE_DATA_SIZE;
953 }
954 #else
955 void page_reset_target_data(target_ulong start, target_ulong last) { }
956 #endif /* TARGET_PAGE_DATA_SIZE */
957 
958 /* The system-mode versions of these helpers are in cputlb.c.  */
959 
960 static void *cpu_mmu_lookup(CPUState *cpu, vaddr addr,
961                             MemOp mop, uintptr_t ra, MMUAccessType type)
962 {
963     int a_bits = memop_alignment_bits(mop);
964     void *ret;
965 
966     /* Enforce guest required alignment.  */
967     if (unlikely(addr & ((1 << a_bits) - 1))) {
968         cpu_loop_exit_sigbus(cpu, addr, type, ra);
969     }
970 
971     ret = g2h(cpu, addr);
972     set_helper_retaddr(ra);
973     return ret;
974 }
975 
976 /* physical memory access (slow version, mainly for debug) */
977 int cpu_memory_rw_debug(CPUState *cpu, vaddr addr,
978                         void *ptr, size_t len, bool is_write)
979 {
980     int flags;
981     vaddr l, page;
982     uint8_t *buf = ptr;
983     ssize_t written;
984     int ret = -1;
985     int fd = -1;
986 
987     mmap_lock();
988 
989     while (len > 0) {
990         page = addr & TARGET_PAGE_MASK;
991         l = (page + TARGET_PAGE_SIZE) - addr;
992         if (l > len) {
993             l = len;
994         }
995         flags = page_get_flags(page);
996         if (!(flags & PAGE_VALID)) {
997             goto out_close;
998         }
999         if (is_write) {
1000             if (flags & PAGE_WRITE) {
1001                 memcpy(g2h(cpu, addr), buf, l);
1002             } else {
1003                 /* Bypass the host page protection using ptrace. */
1004                 if (fd == -1) {
1005                     fd = open("/proc/self/mem", O_WRONLY);
1006                     if (fd == -1) {
1007                         goto out;
1008                     }
1009                 }
1010                 /*
1011                  * If there is a TranslationBlock and we weren't bypassing the
1012                  * host page protection, the memcpy() above would SEGV,
1013                  * ultimately leading to page_unprotect(). So invalidate the
1014                  * translations manually. Both invalidation and pwrite() must
1015                  * be under mmap_lock() in order to prevent the creation of
1016                  * another TranslationBlock in between.
1017                  */
1018                 tb_invalidate_phys_range(addr, addr + l - 1);
1019                 written = pwrite(fd, buf, l,
1020                                  (off_t)(uintptr_t)g2h_untagged(addr));
1021                 if (written != l) {
1022                     goto out_close;
1023                 }
1024             }
1025         } else if (flags & PAGE_READ) {
1026             memcpy(buf, g2h(cpu, addr), l);
1027         } else {
1028             /* Bypass the host page protection using ptrace. */
1029             if (fd == -1) {
1030                 fd = open("/proc/self/mem", O_RDONLY);
1031                 if (fd == -1) {
1032                     goto out;
1033                 }
1034             }
1035             if (pread(fd, buf, l,
1036                       (off_t)(uintptr_t)g2h_untagged(addr)) != l) {
1037                 goto out_close;
1038             }
1039         }
1040         len -= l;
1041         buf += l;
1042         addr += l;
1043     }
1044     ret = 0;
1045 out_close:
1046     if (fd != -1) {
1047         close(fd);
1048     }
1049 out:
1050     mmap_unlock();
1051 
1052     return ret;
1053 }
1054 
1055 #include "ldst_atomicity.c.inc"
1056 
1057 static uint8_t do_ld1_mmu(CPUState *cpu, vaddr addr, MemOpIdx oi,
1058                           uintptr_t ra, MMUAccessType access_type)
1059 {
1060     void *haddr;
1061     uint8_t ret;
1062 
1063     cpu_req_mo(TCG_MO_LD_LD | TCG_MO_ST_LD);
1064     haddr = cpu_mmu_lookup(cpu, addr, get_memop(oi), ra, access_type);
1065     ret = ldub_p(haddr);
1066     clear_helper_retaddr();
1067     return ret;
1068 }
1069 
1070 static uint16_t do_ld2_mmu(CPUState *cpu, vaddr addr, MemOpIdx oi,
1071                            uintptr_t ra, MMUAccessType access_type)
1072 {
1073     void *haddr;
1074     uint16_t ret;
1075     MemOp mop = get_memop(oi);
1076 
1077     cpu_req_mo(TCG_MO_LD_LD | TCG_MO_ST_LD);
1078     haddr = cpu_mmu_lookup(cpu, addr, mop, ra, access_type);
1079     ret = load_atom_2(cpu, ra, haddr, mop);
1080     clear_helper_retaddr();
1081 
1082     if (mop & MO_BSWAP) {
1083         ret = bswap16(ret);
1084     }
1085     return ret;
1086 }
1087 
1088 static uint32_t do_ld4_mmu(CPUState *cpu, vaddr addr, MemOpIdx oi,
1089                            uintptr_t ra, MMUAccessType access_type)
1090 {
1091     void *haddr;
1092     uint32_t ret;
1093     MemOp mop = get_memop(oi);
1094 
1095     cpu_req_mo(TCG_MO_LD_LD | TCG_MO_ST_LD);
1096     haddr = cpu_mmu_lookup(cpu, addr, mop, ra, access_type);
1097     ret = load_atom_4(cpu, ra, haddr, mop);
1098     clear_helper_retaddr();
1099 
1100     if (mop & MO_BSWAP) {
1101         ret = bswap32(ret);
1102     }
1103     return ret;
1104 }
1105 
1106 static uint64_t do_ld8_mmu(CPUState *cpu, vaddr addr, MemOpIdx oi,
1107                            uintptr_t ra, MMUAccessType access_type)
1108 {
1109     void *haddr;
1110     uint64_t ret;
1111     MemOp mop = get_memop(oi);
1112 
1113     cpu_req_mo(TCG_MO_LD_LD | TCG_MO_ST_LD);
1114     haddr = cpu_mmu_lookup(cpu, addr, mop, ra, access_type);
1115     ret = load_atom_8(cpu, ra, haddr, mop);
1116     clear_helper_retaddr();
1117 
1118     if (mop & MO_BSWAP) {
1119         ret = bswap64(ret);
1120     }
1121     return ret;
1122 }
1123 
1124 static Int128 do_ld16_mmu(CPUState *cpu, abi_ptr addr,
1125                           MemOpIdx oi, uintptr_t ra)
1126 {
1127     void *haddr;
1128     Int128 ret;
1129     MemOp mop = get_memop(oi);
1130 
1131     tcg_debug_assert((mop & MO_SIZE) == MO_128);
1132     cpu_req_mo(TCG_MO_LD_LD | TCG_MO_ST_LD);
1133     haddr = cpu_mmu_lookup(cpu, addr, mop, ra, MMU_DATA_LOAD);
1134     ret = load_atom_16(cpu, ra, haddr, mop);
1135     clear_helper_retaddr();
1136 
1137     if (mop & MO_BSWAP) {
1138         ret = bswap128(ret);
1139     }
1140     return ret;
1141 }
1142 
1143 static void do_st1_mmu(CPUState *cpu, vaddr addr, uint8_t val,
1144                        MemOpIdx oi, uintptr_t ra)
1145 {
1146     void *haddr;
1147 
1148     cpu_req_mo(TCG_MO_LD_ST | TCG_MO_ST_ST);
1149     haddr = cpu_mmu_lookup(cpu, addr, get_memop(oi), ra, MMU_DATA_STORE);
1150     stb_p(haddr, val);
1151     clear_helper_retaddr();
1152 }
1153 
1154 static void do_st2_mmu(CPUState *cpu, vaddr addr, uint16_t val,
1155                        MemOpIdx oi, uintptr_t ra)
1156 {
1157     void *haddr;
1158     MemOp mop = get_memop(oi);
1159 
1160     cpu_req_mo(TCG_MO_LD_ST | TCG_MO_ST_ST);
1161     haddr = cpu_mmu_lookup(cpu, addr, mop, ra, MMU_DATA_STORE);
1162 
1163     if (mop & MO_BSWAP) {
1164         val = bswap16(val);
1165     }
1166     store_atom_2(cpu, ra, haddr, mop, val);
1167     clear_helper_retaddr();
1168 }
1169 
1170 static void do_st4_mmu(CPUState *cpu, vaddr addr, uint32_t val,
1171                        MemOpIdx oi, uintptr_t ra)
1172 {
1173     void *haddr;
1174     MemOp mop = get_memop(oi);
1175 
1176     cpu_req_mo(TCG_MO_LD_ST | TCG_MO_ST_ST);
1177     haddr = cpu_mmu_lookup(cpu, addr, mop, ra, MMU_DATA_STORE);
1178 
1179     if (mop & MO_BSWAP) {
1180         val = bswap32(val);
1181     }
1182     store_atom_4(cpu, ra, haddr, mop, val);
1183     clear_helper_retaddr();
1184 }
1185 
1186 static void do_st8_mmu(CPUState *cpu, vaddr addr, uint64_t val,
1187                        MemOpIdx oi, uintptr_t ra)
1188 {
1189     void *haddr;
1190     MemOp mop = get_memop(oi);
1191 
1192     cpu_req_mo(TCG_MO_LD_ST | TCG_MO_ST_ST);
1193     haddr = cpu_mmu_lookup(cpu, addr, mop, ra, MMU_DATA_STORE);
1194 
1195     if (mop & MO_BSWAP) {
1196         val = bswap64(val);
1197     }
1198     store_atom_8(cpu, ra, haddr, mop, val);
1199     clear_helper_retaddr();
1200 }
1201 
1202 static void do_st16_mmu(CPUState *cpu, vaddr addr, Int128 val,
1203                         MemOpIdx oi, uintptr_t ra)
1204 {
1205     void *haddr;
1206     MemOpIdx mop = get_memop(oi);
1207 
1208     cpu_req_mo(TCG_MO_LD_ST | TCG_MO_ST_ST);
1209     haddr = cpu_mmu_lookup(cpu, addr, mop, ra, MMU_DATA_STORE);
1210 
1211     if (mop & MO_BSWAP) {
1212         val = bswap128(val);
1213     }
1214     store_atom_16(cpu, ra, haddr, mop, val);
1215     clear_helper_retaddr();
1216 }
1217 
1218 uint8_t cpu_ldb_code_mmu(CPUArchState *env, vaddr addr,
1219                          MemOpIdx oi, uintptr_t ra)
1220 {
1221     return do_ld1_mmu(env_cpu(env), addr, oi, ra ? ra : 1, MMU_INST_FETCH);
1222 }
1223 
1224 uint16_t cpu_ldw_code_mmu(CPUArchState *env, vaddr addr,
1225                           MemOpIdx oi, uintptr_t ra)
1226 {
1227     return do_ld2_mmu(env_cpu(env), addr, oi, ra ? ra : 1, MMU_INST_FETCH);
1228 }
1229 
1230 uint32_t cpu_ldl_code_mmu(CPUArchState *env, vaddr addr,
1231                           MemOpIdx oi, uintptr_t ra)
1232 {
1233     return do_ld4_mmu(env_cpu(env), addr, oi, ra ? ra : 1, MMU_INST_FETCH);
1234 }
1235 
1236 uint64_t cpu_ldq_code_mmu(CPUArchState *env, vaddr addr,
1237                           MemOpIdx oi, uintptr_t ra)
1238 {
1239     return do_ld8_mmu(env_cpu(env), addr, oi, ra ? ra : 1, MMU_INST_FETCH);
1240 }
1241 
1242 #include "ldst_common.c.inc"
1243 
1244 /*
1245  * Do not allow unaligned operations to proceed.  Return the host address.
1246  */
1247 static void *atomic_mmu_lookup(CPUState *cpu, vaddr addr, MemOpIdx oi,
1248                                int size, uintptr_t retaddr)
1249 {
1250     MemOp mop = get_memop(oi);
1251     int a_bits = memop_alignment_bits(mop);
1252     void *ret;
1253 
1254     /* Enforce guest required alignment.  */
1255     if (unlikely(addr & ((1 << a_bits) - 1))) {
1256         cpu_loop_exit_sigbus(cpu, addr, MMU_DATA_STORE, retaddr);
1257     }
1258 
1259     /* Enforce qemu required alignment.  */
1260     if (unlikely(addr & (size - 1))) {
1261         cpu_loop_exit_atomic(cpu, retaddr);
1262     }
1263 
1264     ret = g2h(cpu, addr);
1265     set_helper_retaddr(retaddr);
1266     return ret;
1267 }
1268 
1269 #include "atomic_common.c.inc"
1270 
1271 /*
1272  * First set of functions passes in OI and RETADDR.
1273  * This makes them callable from other helpers.
1274  */
1275 
1276 #define ATOMIC_NAME(X) \
1277     glue(glue(glue(cpu_atomic_ ## X, SUFFIX), END), _mmu)
1278 #define ATOMIC_MMU_CLEANUP do { clear_helper_retaddr(); } while (0)
1279 
1280 #define DATA_SIZE 1
1281 #include "atomic_template.h"
1282 
1283 #define DATA_SIZE 2
1284 #include "atomic_template.h"
1285 
1286 #define DATA_SIZE 4
1287 #include "atomic_template.h"
1288 
1289 #ifdef CONFIG_ATOMIC64
1290 #define DATA_SIZE 8
1291 #include "atomic_template.h"
1292 #endif
1293 
1294 #if defined(CONFIG_ATOMIC128) || HAVE_CMPXCHG128
1295 #define DATA_SIZE 16
1296 #include "atomic_template.h"
1297 #endif
1298