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