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