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