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