xref: /netbsd-src/sys/external/bsd/compiler_rt/dist/lib/builtins/clear_cache.c (revision 48fb7bfab72acd4281a53bbee5ccf3f809019e75)
1 /* ===-- clear_cache.c - Implement __clear_cache ---------------------------===
2  *
3  *                     The LLVM Compiler Infrastructure
4  *
5  * This file is dual licensed under the MIT and the University of Illinois Open
6  * Source Licenses. See LICENSE.TXT for details.
7  *
8  * ===----------------------------------------------------------------------===
9  */
10 
11 #include "int_lib.h"
12 
13 #if __APPLE__
14   #include <libkern/OSCacheControl.h>
15 #endif
16 #if defined(__NetBSD__) && defined(__arm__)
17   #include <machine/sysarch.h>
18 #endif
19 
20 /*
21  * The compiler generates calls to __clear_cache() when creating
22  * trampoline functions on the stack for use with nested functions.
23  * It is expected to invalidate the instruction cache for the
24  * specified range.
25  */
26 
27 void __clear_cache(void* start, void* end)
28 {
29 #if __i386__ || __x86_64__
30 /*
31  * Intel processors have a unified instruction and data cache
32  * so there is nothing to do
33  */
34 #elif defined(__NetBSD__) && defined(__arm__)
35   struct arm_sync_icache_args arg;
36 
37   arg.addr = (uintptr_t)start;
38   arg.len = (uintptr_t)end - (uintptr_t)start;
39 
40   sysarch(ARM_SYNC_ICACHE, &arg);
41 #elif defined(__aarch64__) && !defined(__APPLE__)
42   uint64_t xstart = (uint64_t)(uintptr_t) start;
43   uint64_t xend = (uint64_t)(uintptr_t) end;
44 
45   // Get Cache Type Info
46   uint64_t ctr_el0;
47   __asm __volatile("mrs %0, ctr_el0" : "=r"(ctr_el0));
48 
49   /*
50    * dc & ic instructions must use 64bit registers so we don't use
51    * uintptr_t in case this runs in an IPL32 environment.
52    */
53   const size_t dcache_line_size = 4 << ((ctr_el0 >> 16) & 15);
54   for (uint64_t addr = xstart; addr < xend; addr += dcache_line_size)
55     __asm __volatile("dc cvau, %0" :: "r"(addr));
56   __asm __volatile("dsb ish");
57 
58   const size_t icache_line_size = 4 << ((ctr_el0 >> 0) & 15);
59   for (uint64_t addr = xstart; addr < xend; addr += icache_line_size)
60     __asm __volatile("ic ivau, %0" :: "r"(addr));
61   __asm __volatile("isb sy");
62 #else
63     #if __APPLE__
64         /* On Darwin, sys_icache_invalidate() provides this functionality */
65         sys_icache_invalidate(start, end-start);
66     #else
67         compilerrt_abort();
68     #endif
69 #endif
70 }
71 
72