1 // SPDX-License-Identifier: GPL-2.0 2 3 #define DISABLE_BRANCH_PROFILING 4 5 #include <linux/kasan.h> 6 #include <linux/memblock.h> 7 #include <linux/hugetlb.h> 8 #include <asm/pgalloc.h> 9 10 static int __init 11 kasan_init_shadow_8M(unsigned long k_start, unsigned long k_end, void *block) 12 { 13 pmd_t *pmd = pmd_off_k(k_start); 14 unsigned long k_cur, k_next; 15 16 for (k_cur = k_start; k_cur != k_end; k_cur = k_next, pmd += 2, block += SZ_8M) { 17 pte_basic_t *new; 18 19 k_next = pgd_addr_end(k_cur, k_end); 20 k_next = pgd_addr_end(k_next, k_end); 21 if ((void *)pmd_page_vaddr(*pmd) != kasan_early_shadow_pte) 22 continue; 23 24 new = memblock_alloc(sizeof(pte_basic_t), SZ_4K); 25 if (!new) 26 return -ENOMEM; 27 28 *new = pte_val(pte_mkhuge(pfn_pte(PHYS_PFN(__pa(block)), PAGE_KERNEL))); 29 30 hugepd_populate_kernel((hugepd_t *)pmd, (pte_t *)new, PAGE_SHIFT_8M); 31 hugepd_populate_kernel((hugepd_t *)pmd + 1, (pte_t *)new, PAGE_SHIFT_8M); 32 } 33 return 0; 34 } 35 36 int __init kasan_init_region(void *start, size_t size) 37 { 38 unsigned long k_start = (unsigned long)kasan_mem_to_shadow(start); 39 unsigned long k_end = (unsigned long)kasan_mem_to_shadow(start + size); 40 unsigned long k_cur; 41 int ret; 42 void *block; 43 44 block = memblock_alloc(k_end - k_start, SZ_8M); 45 if (!block) 46 return -ENOMEM; 47 48 if (IS_ALIGNED(k_start, SZ_8M)) { 49 kasan_init_shadow_8M(k_start, ALIGN_DOWN(k_end, SZ_8M), block); 50 k_cur = ALIGN_DOWN(k_end, SZ_8M); 51 if (k_cur == k_end) 52 goto finish; 53 } else { 54 k_cur = k_start; 55 } 56 57 ret = kasan_init_shadow_page_tables(k_start, k_end); 58 if (ret) 59 return ret; 60 61 for (; k_cur < k_end; k_cur += PAGE_SIZE) { 62 pmd_t *pmd = pmd_off_k(k_cur); 63 void *va = block + k_cur - k_start; 64 pte_t pte = pfn_pte(PHYS_PFN(__pa(va)), PAGE_KERNEL); 65 66 if (k_cur < ALIGN_DOWN(k_end, SZ_512K)) 67 pte = pte_mkhuge(pte); 68 69 __set_pte_at(&init_mm, k_cur, pte_offset_kernel(pmd, k_cur), pte, 0); 70 } 71 finish: 72 flush_tlb_kernel_range(k_start, k_end); 73 return 0; 74 } 75