xref: /qemu/target/arm/tcg/mte_helper.c (revision 0b5ad31d2a997c9b80e7e24aafce7f079fc67bbd)
1 /*
2  * ARM v8.5-MemTag Operations
3  *
4  * Copyright (c) 2020 Linaro, Ltd.
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/log.h"
22 #include "cpu.h"
23 #include "internals.h"
24 #include "exec/exec-all.h"
25 #include "exec/ram_addr.h"
26 #include "exec/cpu_ldst.h"
27 #include "exec/helper-proto.h"
28 #include "hw/core/tcg-cpu-ops.h"
29 #include "qapi/error.h"
30 #include "qemu/guest-random.h"
31 
32 
33 static int choose_nonexcluded_tag(int tag, int offset, uint16_t exclude)
34 {
35     if (exclude == 0xffff) {
36         return 0;
37     }
38     if (offset == 0) {
39         while (exclude & (1 << tag)) {
40             tag = (tag + 1) & 15;
41         }
42     } else {
43         do {
44             do {
45                 tag = (tag + 1) & 15;
46             } while (exclude & (1 << tag));
47         } while (--offset > 0);
48     }
49     return tag;
50 }
51 
52 /**
53  * allocation_tag_mem:
54  * @env: the cpu environment
55  * @ptr_mmu_idx: the addressing regime to use for the virtual address
56  * @ptr: the virtual address for which to look up tag memory
57  * @ptr_access: the access to use for the virtual address
58  * @ptr_size: the number of bytes in the normal memory access
59  * @tag_access: the access to use for the tag memory
60  * @ra: the return address for exception handling
61  *
62  * Our tag memory is formatted as a sequence of little-endian nibbles.
63  * That is, the byte at (addr >> (LOG2_TAG_GRANULE + 1)) contains two
64  * tags, with the tag at [3:0] for the lower addr and the tag at [7:4]
65  * for the higher addr.
66  *
67  * Here, resolve the physical address from the virtual address, and return
68  * a pointer to the corresponding tag byte.  Exit with exception if the
69  * virtual address is not accessible for @ptr_access.
70  *
71  * If there is no tag storage corresponding to @ptr, return NULL.
72  */
73 static uint8_t *allocation_tag_mem(CPUARMState *env, int ptr_mmu_idx,
74                                    uint64_t ptr, MMUAccessType ptr_access,
75                                    int ptr_size, MMUAccessType tag_access,
76                                    uintptr_t ra)
77 {
78 #ifdef CONFIG_USER_ONLY
79     uint64_t clean_ptr = useronly_clean_ptr(ptr);
80     int flags = page_get_flags(clean_ptr);
81     uint8_t *tags;
82     uintptr_t index;
83 
84     if (!(flags & (ptr_access == MMU_DATA_STORE ? PAGE_WRITE_ORG : PAGE_READ))) {
85         cpu_loop_exit_sigsegv(env_cpu(env), ptr, ptr_access,
86                               !(flags & PAGE_VALID), ra);
87     }
88 
89     /* Require both MAP_ANON and PROT_MTE for the page. */
90     if (!(flags & PAGE_ANON) || !(flags & PAGE_MTE)) {
91         return NULL;
92     }
93 
94     tags = page_get_target_data(clean_ptr);
95 
96     index = extract32(ptr, LOG2_TAG_GRANULE + 1,
97                       TARGET_PAGE_BITS - LOG2_TAG_GRANULE - 1);
98     return tags + index;
99 #else
100     CPUTLBEntryFull *full;
101     MemTxAttrs attrs;
102     int in_page, flags;
103     hwaddr ptr_paddr, tag_paddr, xlat;
104     MemoryRegion *mr;
105     ARMASIdx tag_asi;
106     AddressSpace *tag_as;
107     void *host;
108 
109     /*
110      * Probe the first byte of the virtual address.  This raises an
111      * exception for inaccessible pages, and resolves the virtual address
112      * into the softmmu tlb.
113      *
114      * When RA == 0, this is for mte_probe.  The page is expected to be
115      * valid.  Indicate to probe_access_flags no-fault, then assert that
116      * we received a valid page.
117      */
118     flags = probe_access_full(env, ptr, 0, ptr_access, ptr_mmu_idx,
119                               ra == 0, &host, &full, ra);
120     assert(!(flags & TLB_INVALID_MASK));
121 
122     /* If the virtual page MemAttr != Tagged, access unchecked. */
123     if (full->pte_attrs != 0xf0) {
124         return NULL;
125     }
126 
127     /*
128      * If not backed by host ram, there is no tag storage: access unchecked.
129      * This is probably a guest os bug though, so log it.
130      */
131     if (unlikely(flags & TLB_MMIO)) {
132         qemu_log_mask(LOG_GUEST_ERROR,
133                       "Page @ 0x%" PRIx64 " indicates Tagged Normal memory "
134                       "but is not backed by host ram\n", ptr);
135         return NULL;
136     }
137 
138     /*
139      * Remember these values across the second lookup below,
140      * which may invalidate this pointer via tlb resize.
141      */
142     ptr_paddr = full->phys_addr | (ptr & ~TARGET_PAGE_MASK);
143     attrs = full->attrs;
144     full = NULL;
145 
146     /*
147      * The Normal memory access can extend to the next page.  E.g. a single
148      * 8-byte access to the last byte of a page will check only the last
149      * tag on the first page.
150      * Any page access exception has priority over tag check exception.
151      */
152     in_page = -(ptr | TARGET_PAGE_MASK);
153     if (unlikely(ptr_size > in_page)) {
154         flags |= probe_access_full(env, ptr + in_page, 0, ptr_access,
155                                    ptr_mmu_idx, ra == 0, &host, &full, ra);
156         assert(!(flags & TLB_INVALID_MASK));
157     }
158 
159     /* Any debug exception has priority over a tag check exception. */
160     if (unlikely(flags & TLB_WATCHPOINT)) {
161         int wp = ptr_access == MMU_DATA_LOAD ? BP_MEM_READ : BP_MEM_WRITE;
162         assert(ra != 0);
163         cpu_check_watchpoint(env_cpu(env), ptr, ptr_size, attrs, wp, ra);
164     }
165 
166     /* Convert to the physical address in tag space.  */
167     tag_paddr = ptr_paddr >> (LOG2_TAG_GRANULE + 1);
168 
169     /* Look up the address in tag space. */
170     tag_asi = attrs.secure ? ARMASIdx_TagS : ARMASIdx_TagNS;
171     tag_as = cpu_get_address_space(env_cpu(env), tag_asi);
172     mr = address_space_translate(tag_as, tag_paddr, &xlat, NULL,
173                                  tag_access == MMU_DATA_STORE, attrs);
174 
175     /*
176      * Note that @mr will never be NULL.  If there is nothing in the address
177      * space at @tag_paddr, the translation will return the unallocated memory
178      * region.  For our purposes, the result must be ram.
179      */
180     if (unlikely(!memory_region_is_ram(mr))) {
181         /* ??? Failure is a board configuration error. */
182         qemu_log_mask(LOG_UNIMP,
183                       "Tag Memory @ 0x%" HWADDR_PRIx " not found for "
184                       "Normal Memory @ 0x%" HWADDR_PRIx "\n",
185                       tag_paddr, ptr_paddr);
186         return NULL;
187     }
188 
189     /*
190      * Ensure the tag memory is dirty on write, for migration.
191      * Tag memory can never contain code or display memory (vga).
192      */
193     if (tag_access == MMU_DATA_STORE) {
194         ram_addr_t tag_ra = memory_region_get_ram_addr(mr) + xlat;
195         cpu_physical_memory_set_dirty_flag(tag_ra, DIRTY_MEMORY_MIGRATION);
196     }
197 
198     return memory_region_get_ram_ptr(mr) + xlat;
199 #endif
200 }
201 
202 uint64_t HELPER(irg)(CPUARMState *env, uint64_t rn, uint64_t rm)
203 {
204     uint16_t exclude = extract32(rm | env->cp15.gcr_el1, 0, 16);
205     int rrnd = extract32(env->cp15.gcr_el1, 16, 1);
206     int start = extract32(env->cp15.rgsr_el1, 0, 4);
207     int seed = extract32(env->cp15.rgsr_el1, 8, 16);
208     int offset, i, rtag;
209 
210     /*
211      * Our IMPDEF choice for GCR_EL1.RRND==1 is to continue to use the
212      * deterministic algorithm.  Except that with RRND==1 the kernel is
213      * not required to have set RGSR_EL1.SEED != 0, which is required for
214      * the deterministic algorithm to function.  So we force a non-zero
215      * SEED for that case.
216      */
217     if (unlikely(seed == 0) && rrnd) {
218         do {
219             Error *err = NULL;
220             uint16_t two;
221 
222             if (qemu_guest_getrandom(&two, sizeof(two), &err) < 0) {
223                 /*
224                  * Failed, for unknown reasons in the crypto subsystem.
225                  * Best we can do is log the reason and use a constant seed.
226                  */
227                 qemu_log_mask(LOG_UNIMP, "IRG: Crypto failure: %s\n",
228                               error_get_pretty(err));
229                 error_free(err);
230                 two = 1;
231             }
232             seed = two;
233         } while (seed == 0);
234     }
235 
236     /* RandomTag */
237     for (i = offset = 0; i < 4; ++i) {
238         /* NextRandomTagBit */
239         int top = (extract32(seed, 5, 1) ^ extract32(seed, 3, 1) ^
240                    extract32(seed, 2, 1) ^ extract32(seed, 0, 1));
241         seed = (top << 15) | (seed >> 1);
242         offset |= top << i;
243     }
244     rtag = choose_nonexcluded_tag(start, offset, exclude);
245     env->cp15.rgsr_el1 = rtag | (seed << 8);
246 
247     return address_with_allocation_tag(rn, rtag);
248 }
249 
250 uint64_t HELPER(addsubg)(CPUARMState *env, uint64_t ptr,
251                          int32_t offset, uint32_t tag_offset)
252 {
253     int start_tag = allocation_tag_from_addr(ptr);
254     uint16_t exclude = extract32(env->cp15.gcr_el1, 0, 16);
255     int rtag = choose_nonexcluded_tag(start_tag, tag_offset, exclude);
256 
257     return address_with_allocation_tag(ptr + offset, rtag);
258 }
259 
260 static int load_tag1(uint64_t ptr, uint8_t *mem)
261 {
262     int ofs = extract32(ptr, LOG2_TAG_GRANULE, 1) * 4;
263     return extract32(*mem, ofs, 4);
264 }
265 
266 uint64_t HELPER(ldg)(CPUARMState *env, uint64_t ptr, uint64_t xt)
267 {
268     int mmu_idx = cpu_mmu_index(env, false);
269     uint8_t *mem;
270     int rtag = 0;
271 
272     /* Trap if accessing an invalid page.  */
273     mem = allocation_tag_mem(env, mmu_idx, ptr, MMU_DATA_LOAD, 1,
274                              MMU_DATA_LOAD, GETPC());
275 
276     /* Load if page supports tags. */
277     if (mem) {
278         rtag = load_tag1(ptr, mem);
279     }
280 
281     return address_with_allocation_tag(xt, rtag);
282 }
283 
284 static void check_tag_aligned(CPUARMState *env, uint64_t ptr, uintptr_t ra)
285 {
286     if (unlikely(!QEMU_IS_ALIGNED(ptr, TAG_GRANULE))) {
287         arm_cpu_do_unaligned_access(env_cpu(env), ptr, MMU_DATA_STORE,
288                                     cpu_mmu_index(env, false), ra);
289         g_assert_not_reached();
290     }
291 }
292 
293 /* For use in a non-parallel context, store to the given nibble.  */
294 static void store_tag1(uint64_t ptr, uint8_t *mem, int tag)
295 {
296     int ofs = extract32(ptr, LOG2_TAG_GRANULE, 1) * 4;
297     *mem = deposit32(*mem, ofs, 4, tag);
298 }
299 
300 /* For use in a parallel context, atomically store to the given nibble.  */
301 static void store_tag1_parallel(uint64_t ptr, uint8_t *mem, int tag)
302 {
303     int ofs = extract32(ptr, LOG2_TAG_GRANULE, 1) * 4;
304     uint8_t old = qatomic_read(mem);
305 
306     while (1) {
307         uint8_t new = deposit32(old, ofs, 4, tag);
308         uint8_t cmp = qatomic_cmpxchg(mem, old, new);
309         if (likely(cmp == old)) {
310             return;
311         }
312         old = cmp;
313     }
314 }
315 
316 typedef void stg_store1(uint64_t, uint8_t *, int);
317 
318 static inline void do_stg(CPUARMState *env, uint64_t ptr, uint64_t xt,
319                           uintptr_t ra, stg_store1 store1)
320 {
321     int mmu_idx = cpu_mmu_index(env, false);
322     uint8_t *mem;
323 
324     check_tag_aligned(env, ptr, ra);
325 
326     /* Trap if accessing an invalid page.  */
327     mem = allocation_tag_mem(env, mmu_idx, ptr, MMU_DATA_STORE, TAG_GRANULE,
328                              MMU_DATA_STORE, ra);
329 
330     /* Store if page supports tags. */
331     if (mem) {
332         store1(ptr, mem, allocation_tag_from_addr(xt));
333     }
334 }
335 
336 void HELPER(stg)(CPUARMState *env, uint64_t ptr, uint64_t xt)
337 {
338     do_stg(env, ptr, xt, GETPC(), store_tag1);
339 }
340 
341 void HELPER(stg_parallel)(CPUARMState *env, uint64_t ptr, uint64_t xt)
342 {
343     do_stg(env, ptr, xt, GETPC(), store_tag1_parallel);
344 }
345 
346 void HELPER(stg_stub)(CPUARMState *env, uint64_t ptr)
347 {
348     int mmu_idx = cpu_mmu_index(env, false);
349     uintptr_t ra = GETPC();
350 
351     check_tag_aligned(env, ptr, ra);
352     probe_write(env, ptr, TAG_GRANULE, mmu_idx, ra);
353 }
354 
355 static inline void do_st2g(CPUARMState *env, uint64_t ptr, uint64_t xt,
356                            uintptr_t ra, stg_store1 store1)
357 {
358     int mmu_idx = cpu_mmu_index(env, false);
359     int tag = allocation_tag_from_addr(xt);
360     uint8_t *mem1, *mem2;
361 
362     check_tag_aligned(env, ptr, ra);
363 
364     /*
365      * Trap if accessing an invalid page(s).
366      * This takes priority over !allocation_tag_access_enabled.
367      */
368     if (ptr & TAG_GRANULE) {
369         /* Two stores unaligned mod TAG_GRANULE*2 -- modify two bytes. */
370         mem1 = allocation_tag_mem(env, mmu_idx, ptr, MMU_DATA_STORE,
371                                   TAG_GRANULE, MMU_DATA_STORE, ra);
372         mem2 = allocation_tag_mem(env, mmu_idx, ptr + TAG_GRANULE,
373                                   MMU_DATA_STORE, TAG_GRANULE,
374                                   MMU_DATA_STORE, ra);
375 
376         /* Store if page(s) support tags. */
377         if (mem1) {
378             store1(TAG_GRANULE, mem1, tag);
379         }
380         if (mem2) {
381             store1(0, mem2, tag);
382         }
383     } else {
384         /* Two stores aligned mod TAG_GRANULE*2 -- modify one byte. */
385         mem1 = allocation_tag_mem(env, mmu_idx, ptr, MMU_DATA_STORE,
386                                   2 * TAG_GRANULE, MMU_DATA_STORE, ra);
387         if (mem1) {
388             tag |= tag << 4;
389             qatomic_set(mem1, tag);
390         }
391     }
392 }
393 
394 void HELPER(st2g)(CPUARMState *env, uint64_t ptr, uint64_t xt)
395 {
396     do_st2g(env, ptr, xt, GETPC(), store_tag1);
397 }
398 
399 void HELPER(st2g_parallel)(CPUARMState *env, uint64_t ptr, uint64_t xt)
400 {
401     do_st2g(env, ptr, xt, GETPC(), store_tag1_parallel);
402 }
403 
404 void HELPER(st2g_stub)(CPUARMState *env, uint64_t ptr)
405 {
406     int mmu_idx = cpu_mmu_index(env, false);
407     uintptr_t ra = GETPC();
408     int in_page = -(ptr | TARGET_PAGE_MASK);
409 
410     check_tag_aligned(env, ptr, ra);
411 
412     if (likely(in_page >= 2 * TAG_GRANULE)) {
413         probe_write(env, ptr, 2 * TAG_GRANULE, mmu_idx, ra);
414     } else {
415         probe_write(env, ptr, TAG_GRANULE, mmu_idx, ra);
416         probe_write(env, ptr + TAG_GRANULE, TAG_GRANULE, mmu_idx, ra);
417     }
418 }
419 
420 uint64_t HELPER(ldgm)(CPUARMState *env, uint64_t ptr)
421 {
422     int mmu_idx = cpu_mmu_index(env, false);
423     uintptr_t ra = GETPC();
424     int gm_bs = env_archcpu(env)->gm_blocksize;
425     int gm_bs_bytes = 4 << gm_bs;
426     void *tag_mem;
427     uint64_t ret;
428     int shift;
429 
430     ptr = QEMU_ALIGN_DOWN(ptr, gm_bs_bytes);
431 
432     /* Trap if accessing an invalid page.  */
433     tag_mem = allocation_tag_mem(env, mmu_idx, ptr, MMU_DATA_LOAD,
434                                  gm_bs_bytes, MMU_DATA_LOAD, ra);
435 
436     /* The tag is squashed to zero if the page does not support tags.  */
437     if (!tag_mem) {
438         return 0;
439     }
440 
441     /*
442      * The ordering of elements within the word corresponds to
443      * a little-endian operation.  Computation of shift comes from
444      *
445      *     index = address<LOG2_TAG_GRANULE+3:LOG2_TAG_GRANULE>
446      *     data<index*4+3:index*4> = tag
447      *
448      * Because of the alignment of ptr above, BS=6 has shift=0.
449      * All memory operations are aligned.  Defer support for BS=2,
450      * requiring insertion or extraction of a nibble, until we
451      * support a cpu that requires it.
452      */
453     switch (gm_bs) {
454     case 3:
455         /* 32 bytes -> 2 tags -> 8 result bits */
456         ret = *(uint8_t *)tag_mem;
457         break;
458     case 4:
459         /* 64 bytes -> 4 tags -> 16 result bits */
460         ret = cpu_to_le16(*(uint16_t *)tag_mem);
461         break;
462     case 5:
463         /* 128 bytes -> 8 tags -> 32 result bits */
464         ret = cpu_to_le32(*(uint32_t *)tag_mem);
465         break;
466     case 6:
467         /* 256 bytes -> 16 tags -> 64 result bits */
468         return cpu_to_le64(*(uint64_t *)tag_mem);
469     default:
470         /*
471          * CPU configured with unsupported/invalid gm blocksize.
472          * This is detected early in arm_cpu_realizefn.
473          */
474         g_assert_not_reached();
475     }
476     shift = extract64(ptr, LOG2_TAG_GRANULE, 4) * 4;
477     return ret << shift;
478 }
479 
480 void HELPER(stgm)(CPUARMState *env, uint64_t ptr, uint64_t val)
481 {
482     int mmu_idx = cpu_mmu_index(env, false);
483     uintptr_t ra = GETPC();
484     int gm_bs = env_archcpu(env)->gm_blocksize;
485     int gm_bs_bytes = 4 << gm_bs;
486     void *tag_mem;
487     int shift;
488 
489     ptr = QEMU_ALIGN_DOWN(ptr, gm_bs_bytes);
490 
491     /* Trap if accessing an invalid page.  */
492     tag_mem = allocation_tag_mem(env, mmu_idx, ptr, MMU_DATA_STORE,
493                                  gm_bs_bytes, MMU_DATA_LOAD, ra);
494 
495     /*
496      * Tag store only happens if the page support tags,
497      * and if the OS has enabled access to the tags.
498      */
499     if (!tag_mem) {
500         return;
501     }
502 
503     /* See LDGM for comments on BS and on shift.  */
504     shift = extract64(ptr, LOG2_TAG_GRANULE, 4) * 4;
505     val >>= shift;
506     switch (gm_bs) {
507     case 3:
508         /* 32 bytes -> 2 tags -> 8 result bits */
509         *(uint8_t *)tag_mem = val;
510         break;
511     case 4:
512         /* 64 bytes -> 4 tags -> 16 result bits */
513         *(uint16_t *)tag_mem = cpu_to_le16(val);
514         break;
515     case 5:
516         /* 128 bytes -> 8 tags -> 32 result bits */
517         *(uint32_t *)tag_mem = cpu_to_le32(val);
518         break;
519     case 6:
520         /* 256 bytes -> 16 tags -> 64 result bits */
521         *(uint64_t *)tag_mem = cpu_to_le64(val);
522         break;
523     default:
524         /* cpu configured with unsupported gm blocksize. */
525         g_assert_not_reached();
526     }
527 }
528 
529 void HELPER(stzgm_tags)(CPUARMState *env, uint64_t ptr, uint64_t val)
530 {
531     uintptr_t ra = GETPC();
532     int mmu_idx = cpu_mmu_index(env, false);
533     int log2_dcz_bytes, log2_tag_bytes;
534     intptr_t dcz_bytes, tag_bytes;
535     uint8_t *mem;
536 
537     /*
538      * In arm_cpu_realizefn, we assert that dcz > LOG2_TAG_GRANULE+1,
539      * i.e. 32 bytes, which is an unreasonably small dcz anyway,
540      * to make sure that we can access one complete tag byte here.
541      */
542     log2_dcz_bytes = env_archcpu(env)->dcz_blocksize + 2;
543     log2_tag_bytes = log2_dcz_bytes - (LOG2_TAG_GRANULE + 1);
544     dcz_bytes = (intptr_t)1 << log2_dcz_bytes;
545     tag_bytes = (intptr_t)1 << log2_tag_bytes;
546     ptr &= -dcz_bytes;
547 
548     mem = allocation_tag_mem(env, mmu_idx, ptr, MMU_DATA_STORE, dcz_bytes,
549                              MMU_DATA_STORE, ra);
550     if (mem) {
551         int tag_pair = (val & 0xf) * 0x11;
552         memset(mem, tag_pair, tag_bytes);
553     }
554 }
555 
556 static void mte_sync_check_fail(CPUARMState *env, uint32_t desc,
557                                 uint64_t dirty_ptr, uintptr_t ra)
558 {
559     int is_write, syn;
560 
561     env->exception.vaddress = dirty_ptr;
562 
563     is_write = FIELD_EX32(desc, MTEDESC, WRITE);
564     syn = syn_data_abort_no_iss(arm_current_el(env) != 0, 0, 0, 0, 0, is_write,
565                                 0x11);
566     raise_exception_ra(env, EXCP_DATA_ABORT, syn, exception_target_el(env), ra);
567     g_assert_not_reached();
568 }
569 
570 static void mte_async_check_fail(CPUARMState *env, uint64_t dirty_ptr,
571                                  uintptr_t ra, ARMMMUIdx arm_mmu_idx, int el)
572 {
573     int select;
574 
575     if (regime_has_2_ranges(arm_mmu_idx)) {
576         select = extract64(dirty_ptr, 55, 1);
577     } else {
578         select = 0;
579     }
580     env->cp15.tfsr_el[el] |= 1 << select;
581 #ifdef CONFIG_USER_ONLY
582     /*
583      * Stand in for a timer irq, setting _TIF_MTE_ASYNC_FAULT,
584      * which then sends a SIGSEGV when the thread is next scheduled.
585      * This cpu will return to the main loop at the end of the TB,
586      * which is rather sooner than "normal".  But the alternative
587      * is waiting until the next syscall.
588      */
589     qemu_cpu_kick(env_cpu(env));
590 #endif
591 }
592 
593 /* Record a tag check failure.  */
594 static void mte_check_fail(CPUARMState *env, uint32_t desc,
595                            uint64_t dirty_ptr, uintptr_t ra)
596 {
597     int mmu_idx = FIELD_EX32(desc, MTEDESC, MIDX);
598     ARMMMUIdx arm_mmu_idx = core_to_aa64_mmu_idx(mmu_idx);
599     int el, reg_el, tcf;
600     uint64_t sctlr;
601 
602     reg_el = regime_el(env, arm_mmu_idx);
603     sctlr = env->cp15.sctlr_el[reg_el];
604 
605     switch (arm_mmu_idx) {
606     case ARMMMUIdx_E10_0:
607     case ARMMMUIdx_E20_0:
608         el = 0;
609         tcf = extract64(sctlr, 38, 2);
610         break;
611     default:
612         el = reg_el;
613         tcf = extract64(sctlr, 40, 2);
614     }
615 
616     switch (tcf) {
617     case 1:
618         /* Tag check fail causes a synchronous exception. */
619         mte_sync_check_fail(env, desc, dirty_ptr, ra);
620         break;
621 
622     case 0:
623         /*
624          * Tag check fail does not affect the PE.
625          * We eliminate this case by not setting MTE_ACTIVE
626          * in tb_flags, so that we never make this runtime call.
627          */
628         g_assert_not_reached();
629 
630     case 2:
631         /* Tag check fail causes asynchronous flag set.  */
632         mte_async_check_fail(env, dirty_ptr, ra, arm_mmu_idx, el);
633         break;
634 
635     case 3:
636         /*
637          * Tag check fail causes asynchronous flag set for stores, or
638          * a synchronous exception for loads.
639          */
640         if (FIELD_EX32(desc, MTEDESC, WRITE)) {
641             mte_async_check_fail(env, dirty_ptr, ra, arm_mmu_idx, el);
642         } else {
643             mte_sync_check_fail(env, desc, dirty_ptr, ra);
644         }
645         break;
646     }
647 }
648 
649 /**
650  * checkN:
651  * @tag: tag memory to test
652  * @odd: true to begin testing at tags at odd nibble
653  * @cmp: the tag to compare against
654  * @count: number of tags to test
655  *
656  * Return the number of successful tests.
657  * Thus a return value < @count indicates a failure.
658  *
659  * A note about sizes: count is expected to be small.
660  *
661  * The most common use will be LDP/STP of two integer registers,
662  * which means 16 bytes of memory touching at most 2 tags, but
663  * often the access is aligned and thus just 1 tag.
664  *
665  * Using AdvSIMD LD/ST (multiple), one can access 64 bytes of memory,
666  * touching at most 5 tags.  SVE LDR/STR (vector) with the default
667  * vector length is also 64 bytes; the maximum architectural length
668  * is 256 bytes touching at most 9 tags.
669  *
670  * The loop below uses 7 logical operations and 1 memory operation
671  * per tag pair.  An implementation that loads an aligned word and
672  * uses masking to ignore adjacent tags requires 18 logical operations
673  * and thus does not begin to pay off until 6 tags.
674  * Which, according to the survey above, is unlikely to be common.
675  */
676 static int checkN(uint8_t *mem, int odd, int cmp, int count)
677 {
678     int n = 0, diff;
679 
680     /* Replicate the test tag and compare.  */
681     cmp *= 0x11;
682     diff = *mem++ ^ cmp;
683 
684     if (odd) {
685         goto start_odd;
686     }
687 
688     while (1) {
689         /* Test even tag. */
690         if (unlikely((diff) & 0x0f)) {
691             break;
692         }
693         if (++n == count) {
694             break;
695         }
696 
697     start_odd:
698         /* Test odd tag. */
699         if (unlikely((diff) & 0xf0)) {
700             break;
701         }
702         if (++n == count) {
703             break;
704         }
705 
706         diff = *mem++ ^ cmp;
707     }
708     return n;
709 }
710 
711 /**
712  * mte_probe_int() - helper for mte_probe and mte_check
713  * @env: CPU environment
714  * @desc: MTEDESC descriptor
715  * @ptr: virtual address of the base of the access
716  * @fault: return virtual address of the first check failure
717  *
718  * Internal routine for both mte_probe and mte_check.
719  * Return zero on failure, filling in *fault.
720  * Return negative on trivial success for tbi disabled.
721  * Return positive on success with tbi enabled.
722  */
723 static int mte_probe_int(CPUARMState *env, uint32_t desc, uint64_t ptr,
724                          uintptr_t ra, uint64_t *fault)
725 {
726     int mmu_idx, ptr_tag, bit55;
727     uint64_t ptr_last, prev_page, next_page;
728     uint64_t tag_first, tag_last;
729     uint32_t sizem1, tag_count, n, c;
730     uint8_t *mem1, *mem2;
731     MMUAccessType type;
732 
733     bit55 = extract64(ptr, 55, 1);
734     *fault = ptr;
735 
736     /* If TBI is disabled, the access is unchecked, and ptr is not dirty. */
737     if (unlikely(!tbi_check(desc, bit55))) {
738         return -1;
739     }
740 
741     ptr_tag = allocation_tag_from_addr(ptr);
742 
743     if (tcma_check(desc, bit55, ptr_tag)) {
744         return 1;
745     }
746 
747     mmu_idx = FIELD_EX32(desc, MTEDESC, MIDX);
748     type = FIELD_EX32(desc, MTEDESC, WRITE) ? MMU_DATA_STORE : MMU_DATA_LOAD;
749     sizem1 = FIELD_EX32(desc, MTEDESC, SIZEM1);
750 
751     /* Find the addr of the end of the access */
752     ptr_last = ptr + sizem1;
753 
754     /* Round the bounds to the tag granule, and compute the number of tags. */
755     tag_first = QEMU_ALIGN_DOWN(ptr, TAG_GRANULE);
756     tag_last = QEMU_ALIGN_DOWN(ptr_last, TAG_GRANULE);
757     tag_count = ((tag_last - tag_first) / TAG_GRANULE) + 1;
758 
759     /* Locate the page boundaries. */
760     prev_page = ptr & TARGET_PAGE_MASK;
761     next_page = prev_page + TARGET_PAGE_SIZE;
762 
763     if (likely(tag_last - prev_page < TARGET_PAGE_SIZE)) {
764         /* Memory access stays on one page. */
765         mem1 = allocation_tag_mem(env, mmu_idx, ptr, type, sizem1 + 1,
766                                   MMU_DATA_LOAD, ra);
767         if (!mem1) {
768             return 1;
769         }
770         /* Perform all of the comparisons. */
771         n = checkN(mem1, ptr & TAG_GRANULE, ptr_tag, tag_count);
772     } else {
773         /* Memory access crosses to next page. */
774         mem1 = allocation_tag_mem(env, mmu_idx, ptr, type, next_page - ptr,
775                                   MMU_DATA_LOAD, ra);
776 
777         mem2 = allocation_tag_mem(env, mmu_idx, next_page, type,
778                                   ptr_last - next_page + 1,
779                                   MMU_DATA_LOAD, ra);
780 
781         /*
782          * Perform all of the comparisons.
783          * Note the possible but unlikely case of the operation spanning
784          * two pages that do not both have tagging enabled.
785          */
786         n = c = (next_page - tag_first) / TAG_GRANULE;
787         if (mem1) {
788             n = checkN(mem1, ptr & TAG_GRANULE, ptr_tag, c);
789         }
790         if (n == c) {
791             if (!mem2) {
792                 return 1;
793             }
794             n += checkN(mem2, 0, ptr_tag, tag_count - c);
795         }
796     }
797 
798     if (likely(n == tag_count)) {
799         return 1;
800     }
801 
802     /*
803      * If we failed, we know which granule.  For the first granule, the
804      * failure address is @ptr, the first byte accessed.  Otherwise the
805      * failure address is the first byte of the nth granule.
806      */
807     if (n > 0) {
808         *fault = tag_first + n * TAG_GRANULE;
809     }
810     return 0;
811 }
812 
813 uint64_t mte_check(CPUARMState *env, uint32_t desc, uint64_t ptr, uintptr_t ra)
814 {
815     uint64_t fault;
816     int ret = mte_probe_int(env, desc, ptr, ra, &fault);
817 
818     if (unlikely(ret == 0)) {
819         mte_check_fail(env, desc, fault, ra);
820     } else if (ret < 0) {
821         return ptr;
822     }
823     return useronly_clean_ptr(ptr);
824 }
825 
826 uint64_t HELPER(mte_check)(CPUARMState *env, uint32_t desc, uint64_t ptr)
827 {
828     /*
829      * R_XCHFJ: Alignment check not caused by memory type is priority 1,
830      * higher than any translation fault.  When MTE is disabled, tcg
831      * performs the alignment check during the code generated for the
832      * memory access.  With MTE enabled, we must check this here before
833      * raising any translation fault in allocation_tag_mem.
834      */
835     unsigned align = FIELD_EX32(desc, MTEDESC, ALIGN);
836     if (unlikely(align)) {
837         align = (1u << align) - 1;
838         if (unlikely(ptr & align)) {
839             int idx = FIELD_EX32(desc, MTEDESC, MIDX);
840             bool w = FIELD_EX32(desc, MTEDESC, WRITE);
841             MMUAccessType type = w ? MMU_DATA_STORE : MMU_DATA_LOAD;
842             arm_cpu_do_unaligned_access(env_cpu(env), ptr, type, idx, GETPC());
843         }
844     }
845 
846     return mte_check(env, desc, ptr, GETPC());
847 }
848 
849 /*
850  * No-fault version of mte_check, to be used by SVE for MemSingleNF.
851  * Returns false if the access is Checked and the check failed.  This
852  * is only intended to probe the tag -- the validity of the page must
853  * be checked beforehand.
854  */
855 bool mte_probe(CPUARMState *env, uint32_t desc, uint64_t ptr)
856 {
857     uint64_t fault;
858     int ret = mte_probe_int(env, desc, ptr, 0, &fault);
859 
860     return ret != 0;
861 }
862 
863 /*
864  * Perform an MTE checked access for DC_ZVA.
865  */
866 uint64_t HELPER(mte_check_zva)(CPUARMState *env, uint32_t desc, uint64_t ptr)
867 {
868     uintptr_t ra = GETPC();
869     int log2_dcz_bytes, log2_tag_bytes;
870     int mmu_idx, bit55;
871     intptr_t dcz_bytes, tag_bytes, i;
872     void *mem;
873     uint64_t ptr_tag, mem_tag, align_ptr;
874 
875     bit55 = extract64(ptr, 55, 1);
876 
877     /* If TBI is disabled, the access is unchecked, and ptr is not dirty. */
878     if (unlikely(!tbi_check(desc, bit55))) {
879         return ptr;
880     }
881 
882     ptr_tag = allocation_tag_from_addr(ptr);
883 
884     if (tcma_check(desc, bit55, ptr_tag)) {
885         goto done;
886     }
887 
888     /*
889      * In arm_cpu_realizefn, we asserted that dcz > LOG2_TAG_GRANULE+1,
890      * i.e. 32 bytes, which is an unreasonably small dcz anyway, to make
891      * sure that we can access one complete tag byte here.
892      */
893     log2_dcz_bytes = env_archcpu(env)->dcz_blocksize + 2;
894     log2_tag_bytes = log2_dcz_bytes - (LOG2_TAG_GRANULE + 1);
895     dcz_bytes = (intptr_t)1 << log2_dcz_bytes;
896     tag_bytes = (intptr_t)1 << log2_tag_bytes;
897     align_ptr = ptr & -dcz_bytes;
898 
899     /*
900      * Trap if accessing an invalid page.  DC_ZVA requires that we supply
901      * the original pointer for an invalid page.  But watchpoints require
902      * that we probe the actual space.  So do both.
903      */
904     mmu_idx = FIELD_EX32(desc, MTEDESC, MIDX);
905     (void) probe_write(env, ptr, 1, mmu_idx, ra);
906     mem = allocation_tag_mem(env, mmu_idx, align_ptr, MMU_DATA_STORE,
907                              dcz_bytes, MMU_DATA_LOAD, ra);
908     if (!mem) {
909         goto done;
910     }
911 
912     /*
913      * Unlike the reasoning for checkN, DC_ZVA is always aligned, and thus
914      * it is quite easy to perform all of the comparisons at once without
915      * any extra masking.
916      *
917      * The most common zva block size is 64; some of the thunderx cpus use
918      * a block size of 128.  For user-only, aarch64_max_initfn will set the
919      * block size to 512.  Fill out the other cases for future-proofing.
920      *
921      * In order to be able to find the first miscompare later, we want the
922      * tag bytes to be in little-endian order.
923      */
924     switch (log2_tag_bytes) {
925     case 0: /* zva_blocksize 32 */
926         mem_tag = *(uint8_t *)mem;
927         ptr_tag *= 0x11u;
928         break;
929     case 1: /* zva_blocksize 64 */
930         mem_tag = cpu_to_le16(*(uint16_t *)mem);
931         ptr_tag *= 0x1111u;
932         break;
933     case 2: /* zva_blocksize 128 */
934         mem_tag = cpu_to_le32(*(uint32_t *)mem);
935         ptr_tag *= 0x11111111u;
936         break;
937     case 3: /* zva_blocksize 256 */
938         mem_tag = cpu_to_le64(*(uint64_t *)mem);
939         ptr_tag *= 0x1111111111111111ull;
940         break;
941 
942     default: /* zva_blocksize 512, 1024, 2048 */
943         ptr_tag *= 0x1111111111111111ull;
944         i = 0;
945         do {
946             mem_tag = cpu_to_le64(*(uint64_t *)(mem + i));
947             if (unlikely(mem_tag != ptr_tag)) {
948                 goto fail;
949             }
950             i += 8;
951             align_ptr += 16 * TAG_GRANULE;
952         } while (i < tag_bytes);
953         goto done;
954     }
955 
956     if (likely(mem_tag == ptr_tag)) {
957         goto done;
958     }
959 
960  fail:
961     /* Locate the first nibble that differs. */
962     i = ctz64(mem_tag ^ ptr_tag) >> 4;
963     mte_check_fail(env, desc, align_ptr + i * TAG_GRANULE, ra);
964 
965  done:
966     return useronly_clean_ptr(ptr);
967 }
968