1 // SPDX-License-Identifier: GPL-2.0
3 * This file contains KASAN runtime code that manages shadow memory for
4 * generic and software tag-based KASAN modes.
6 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
7 * Author: Andrey Ryabinin <ryabinin.a.a@gmail.com>
9 * Some code borrowed from https://github.com/xairy/kasan-prototype by
10 * Andrey Konovalov <andreyknvl@gmail.com>
13 #include <linux/init.h>
14 #include <linux/kasan.h>
15 #include <linux/kernel.h>
16 #include <linux/kfence.h>
17 #include <linux/kmemleak.h>
18 #include <linux/memory.h>
20 #include <linux/string.h>
21 #include <linux/types.h>
22 #include <linux/vmalloc.h>
24 #include <asm/cacheflush.h>
25 #include <asm/tlbflush.h>
29 bool __kasan_check_read(const volatile void *p, unsigned int size)
31 return kasan_check_range((unsigned long)p, size, false, _RET_IP_);
33 EXPORT_SYMBOL(__kasan_check_read);
35 bool __kasan_check_write(const volatile void *p, unsigned int size)
37 return kasan_check_range((unsigned long)p, size, true, _RET_IP_);
39 EXPORT_SYMBOL(__kasan_check_write);
42 void *memset(void *addr, int c, size_t len)
44 if (!kasan_check_range((unsigned long)addr, len, true, _RET_IP_))
47 return __memset(addr, c, len);
50 #ifdef __HAVE_ARCH_MEMMOVE
52 void *memmove(void *dest, const void *src, size_t len)
54 if (!kasan_check_range((unsigned long)src, len, false, _RET_IP_) ||
55 !kasan_check_range((unsigned long)dest, len, true, _RET_IP_))
58 return __memmove(dest, src, len);
63 void *memcpy(void *dest, const void *src, size_t len)
65 if (!kasan_check_range((unsigned long)src, len, false, _RET_IP_) ||
66 !kasan_check_range((unsigned long)dest, len, true, _RET_IP_))
69 return __memcpy(dest, src, len);
72 void kasan_poison(const void *addr, size_t size, u8 value, bool init)
74 void *shadow_start, *shadow_end;
76 if (!kasan_arch_is_ready())
80 * Perform shadow offset calculation based on untagged address, as
81 * some of the callers (e.g. kasan_poison_object_data) pass tagged
82 * addresses to this function.
84 addr = kasan_reset_tag(addr);
86 /* Skip KFENCE memory if called explicitly outside of sl*b. */
87 if (is_kfence_address(addr))
90 if (WARN_ON((unsigned long)addr & KASAN_GRANULE_MASK))
92 if (WARN_ON(size & KASAN_GRANULE_MASK))
95 shadow_start = kasan_mem_to_shadow(addr);
96 shadow_end = kasan_mem_to_shadow(addr + size);
98 __memset(shadow_start, value, shadow_end - shadow_start);
100 EXPORT_SYMBOL(kasan_poison);
102 #ifdef CONFIG_KASAN_GENERIC
103 void kasan_poison_last_granule(const void *addr, size_t size)
105 if (!kasan_arch_is_ready())
108 if (size & KASAN_GRANULE_MASK) {
109 u8 *shadow = (u8 *)kasan_mem_to_shadow(addr + size);
110 *shadow = size & KASAN_GRANULE_MASK;
115 void kasan_unpoison(const void *addr, size_t size, bool init)
117 u8 tag = get_tag(addr);
120 * Perform shadow offset calculation based on untagged address, as
121 * some of the callers (e.g. kasan_unpoison_object_data) pass tagged
122 * addresses to this function.
124 addr = kasan_reset_tag(addr);
127 * Skip KFENCE memory if called explicitly outside of sl*b. Also note
128 * that calls to ksize(), where size is not a multiple of machine-word
129 * size, would otherwise poison the invalid portion of the word.
131 if (is_kfence_address(addr))
134 if (WARN_ON((unsigned long)addr & KASAN_GRANULE_MASK))
137 /* Unpoison all granules that cover the object. */
138 kasan_poison(addr, round_up(size, KASAN_GRANULE_SIZE), tag, false);
140 /* Partially poison the last granule for the generic mode. */
141 if (IS_ENABLED(CONFIG_KASAN_GENERIC))
142 kasan_poison_last_granule(addr, size);
145 #ifdef CONFIG_MEMORY_HOTPLUG
146 static bool shadow_mapped(unsigned long addr)
148 pgd_t *pgd = pgd_offset_k(addr);
156 p4d = p4d_offset(pgd, addr);
159 pud = pud_offset(p4d, addr);
164 * We can't use pud_large() or pud_huge(), the first one is
165 * arch-specific, the last one depends on HUGETLB_PAGE. So let's abuse
166 * pud_bad(), if pud is bad then it's bad because it's huge.
170 pmd = pmd_offset(pud, addr);
176 pte = pte_offset_kernel(pmd, addr);
177 return !pte_none(*pte);
180 static int __meminit kasan_mem_notifier(struct notifier_block *nb,
181 unsigned long action, void *data)
183 struct memory_notify *mem_data = data;
184 unsigned long nr_shadow_pages, start_kaddr, shadow_start;
185 unsigned long shadow_end, shadow_size;
187 nr_shadow_pages = mem_data->nr_pages >> KASAN_SHADOW_SCALE_SHIFT;
188 start_kaddr = (unsigned long)pfn_to_kaddr(mem_data->start_pfn);
189 shadow_start = (unsigned long)kasan_mem_to_shadow((void *)start_kaddr);
190 shadow_size = nr_shadow_pages << PAGE_SHIFT;
191 shadow_end = shadow_start + shadow_size;
193 if (WARN_ON(mem_data->nr_pages % KASAN_GRANULE_SIZE) ||
194 WARN_ON(start_kaddr % KASAN_MEMORY_PER_SHADOW_PAGE))
198 case MEM_GOING_ONLINE: {
202 * If shadow is mapped already than it must have been mapped
203 * during the boot. This could happen if we onlining previously
206 if (shadow_mapped(shadow_start))
209 ret = __vmalloc_node_range(shadow_size, PAGE_SIZE, shadow_start,
210 shadow_end, GFP_KERNEL,
211 PAGE_KERNEL, VM_NO_GUARD,
212 pfn_to_nid(mem_data->start_pfn),
213 __builtin_return_address(0));
217 kmemleak_ignore(ret);
220 case MEM_CANCEL_ONLINE:
222 struct vm_struct *vm;
225 * shadow_start was either mapped during boot by kasan_init()
226 * or during memory online by __vmalloc_node_range().
227 * In the latter case we can use vfree() to free shadow.
228 * Non-NULL result of the find_vm_area() will tell us if
229 * that was the second case.
231 * Currently it's not possible to free shadow mapped
232 * during boot by kasan_init(). It's because the code
233 * to do that hasn't been written yet. So we'll just
236 vm = find_vm_area((void *)shadow_start);
238 vfree((void *)shadow_start);
245 static int __init kasan_memhotplug_init(void)
247 hotplug_memory_notifier(kasan_mem_notifier, 0);
252 core_initcall(kasan_memhotplug_init);
255 #ifdef CONFIG_KASAN_VMALLOC
257 void __init __weak kasan_populate_early_vm_area_shadow(void *start,
262 static int kasan_populate_vmalloc_pte(pte_t *ptep, unsigned long addr,
268 if (likely(!pte_none(*ptep)))
271 page = __get_free_page(GFP_KERNEL);
275 memset((void *)page, KASAN_VMALLOC_INVALID, PAGE_SIZE);
276 pte = pfn_pte(PFN_DOWN(__pa(page)), PAGE_KERNEL);
278 spin_lock(&init_mm.page_table_lock);
279 if (likely(pte_none(*ptep))) {
280 set_pte_at(&init_mm, addr, ptep, pte);
283 spin_unlock(&init_mm.page_table_lock);
289 int kasan_populate_vmalloc(unsigned long addr, unsigned long size)
291 unsigned long shadow_start, shadow_end;
294 if (!is_vmalloc_or_module_addr((void *)addr))
297 shadow_start = (unsigned long)kasan_mem_to_shadow((void *)addr);
298 shadow_end = (unsigned long)kasan_mem_to_shadow((void *)addr + size);
301 * User Mode Linux maps enough shadow memory for all of virtual memory
302 * at boot, so doesn't need to allocate more on vmalloc, just clear it.
304 * The remaining CONFIG_UML checks in this file exist for the same
307 if (IS_ENABLED(CONFIG_UML)) {
308 __memset((void *)shadow_start, KASAN_VMALLOC_INVALID, shadow_end - shadow_start);
312 shadow_start = PAGE_ALIGN_DOWN(shadow_start);
313 shadow_end = PAGE_ALIGN(shadow_end);
315 ret = apply_to_page_range(&init_mm, shadow_start,
316 shadow_end - shadow_start,
317 kasan_populate_vmalloc_pte, NULL);
321 flush_cache_vmap(shadow_start, shadow_end);
324 * We need to be careful about inter-cpu effects here. Consider:
327 * WRITE_ONCE(p, vmalloc(100)); while (x = READ_ONCE(p)) ;
330 * With compiler instrumentation, that ends up looking like this:
333 * // vmalloc() allocates memory
334 * // let a = area->addr
335 * // we reach kasan_populate_vmalloc
336 * // and call kasan_unpoison:
337 * STORE shadow(a), unpoison_val
339 * STORE shadow(a+99), unpoison_val x = LOAD p
340 * // rest of vmalloc process <data dependency>
341 * STORE p, a LOAD shadow(x+99)
343 * If there is no barrier between the end of unpoisoning the shadow
344 * and the store of the result to p, the stores could be committed
345 * in a different order by CPU#0, and CPU#1 could erroneously observe
346 * poison in the shadow.
348 * We need some sort of barrier between the stores.
350 * In the vmalloc() case, this is provided by a smp_wmb() in
351 * clear_vm_uninitialized_flag(). In the per-cpu allocator and in
352 * get_vm_area() and friends, the caller gets shadow allocated but
353 * doesn't have any pages mapped into the virtual address space that
354 * has been reserved. Mapping those pages in will involve taking and
355 * releasing a page-table lock, which will provide the barrier.
361 static int kasan_depopulate_vmalloc_pte(pte_t *ptep, unsigned long addr,
366 page = (unsigned long)__va(pte_pfn(*ptep) << PAGE_SHIFT);
368 spin_lock(&init_mm.page_table_lock);
370 if (likely(!pte_none(*ptep))) {
371 pte_clear(&init_mm, addr, ptep);
374 spin_unlock(&init_mm.page_table_lock);
380 * Release the backing for the vmalloc region [start, end), which
381 * lies within the free region [free_region_start, free_region_end).
383 * This can be run lazily, long after the region was freed. It runs
384 * under vmap_area_lock, so it's not safe to interact with the vmalloc/vmap
387 * How does this work?
388 * -------------------
390 * We have a region that is page aligned, labeled as A.
391 * That might not map onto the shadow in a way that is page-aligned:
395 * |????????|????????|AAAAAAAA|AA....AA|AAAAAAAA|????????| < vmalloc
396 * -------- -------- -------- -------- --------
399 * \-------\|/------/ |/---------------/
401 * |??AAAAAA|AAAAAAAA|AA??????| < shadow
404 * First we align the start upwards and the end downwards, so that the
405 * shadow of the region aligns with shadow page boundaries. In the
406 * example, this gives us the shadow page (2). This is the shadow entirely
407 * covered by this allocation.
409 * Then we have the tricky bits. We want to know if we can free the
410 * partially covered shadow pages - (1) and (3) in the example. For this,
411 * we are given the start and end of the free region that contains this
412 * allocation. Extending our previous example, we could have:
414 * free_region_start free_region_end
417 * |FFFFFFFF|FFFFFFFF|AAAAAAAA|AA....AA|AAAAAAAA|FFFFFFFF| < vmalloc
418 * -------- -------- -------- -------- --------
421 * \-------\|/------/ |/---------------/
423 * |FFAAAAAA|AAAAAAAA|AAF?????| < shadow
426 * Once again, we align the start of the free region up, and the end of
427 * the free region down so that the shadow is page aligned. So we can free
428 * page (1) - we know no allocation currently uses anything in that page,
429 * because all of it is in the vmalloc free region. But we cannot free
430 * page (3), because we can't be sure that the rest of it is unused.
432 * We only consider pages that contain part of the original region for
433 * freeing: we don't try to free other pages from the free region or we'd
434 * end up trying to free huge chunks of virtual address space.
439 * How do we know that we're not freeing a page that is simultaneously
440 * being used for a fresh allocation in kasan_populate_vmalloc(_pte)?
442 * We _can_ have kasan_release_vmalloc and kasan_populate_vmalloc running
443 * at the same time. While we run under free_vmap_area_lock, the population
446 * free_vmap_area_lock instead operates to ensure that the larger range
447 * [free_region_start, free_region_end) is safe: because __alloc_vmap_area and
448 * the per-cpu region-finding algorithm both run under free_vmap_area_lock,
449 * no space identified as free will become used while we are running. This
450 * means that so long as we are careful with alignment and only free shadow
451 * pages entirely covered by the free region, we will not run in to any
452 * trouble - any simultaneous allocations will be for disjoint regions.
454 void kasan_release_vmalloc(unsigned long start, unsigned long end,
455 unsigned long free_region_start,
456 unsigned long free_region_end)
458 void *shadow_start, *shadow_end;
459 unsigned long region_start, region_end;
462 region_start = ALIGN(start, KASAN_MEMORY_PER_SHADOW_PAGE);
463 region_end = ALIGN_DOWN(end, KASAN_MEMORY_PER_SHADOW_PAGE);
465 free_region_start = ALIGN(free_region_start, KASAN_MEMORY_PER_SHADOW_PAGE);
467 if (start != region_start &&
468 free_region_start < region_start)
469 region_start -= KASAN_MEMORY_PER_SHADOW_PAGE;
471 free_region_end = ALIGN_DOWN(free_region_end, KASAN_MEMORY_PER_SHADOW_PAGE);
473 if (end != region_end &&
474 free_region_end > region_end)
475 region_end += KASAN_MEMORY_PER_SHADOW_PAGE;
477 shadow_start = kasan_mem_to_shadow((void *)region_start);
478 shadow_end = kasan_mem_to_shadow((void *)region_end);
480 if (shadow_end > shadow_start) {
481 size = shadow_end - shadow_start;
482 if (IS_ENABLED(CONFIG_UML)) {
483 __memset(shadow_start, KASAN_SHADOW_INIT, shadow_end - shadow_start);
486 apply_to_existing_page_range(&init_mm,
487 (unsigned long)shadow_start,
488 size, kasan_depopulate_vmalloc_pte,
490 flush_tlb_kernel_range((unsigned long)shadow_start,
491 (unsigned long)shadow_end);
495 void *__kasan_unpoison_vmalloc(const void *start, unsigned long size,
496 kasan_vmalloc_flags_t flags)
499 * Software KASAN modes unpoison both VM_ALLOC and non-VM_ALLOC
500 * mappings, so the KASAN_VMALLOC_VM_ALLOC flag is ignored.
501 * Software KASAN modes can't optimize zeroing memory by combining it
502 * with setting memory tags, so the KASAN_VMALLOC_INIT flag is ignored.
505 if (!is_vmalloc_or_module_addr(start))
506 return (void *)start;
509 * Don't tag executable memory with the tag-based mode.
510 * The kernel doesn't tolerate having the PC register tagged.
512 if (IS_ENABLED(CONFIG_KASAN_SW_TAGS) &&
513 !(flags & KASAN_VMALLOC_PROT_NORMAL))
514 return (void *)start;
516 start = set_tag(start, kasan_random_tag());
517 kasan_unpoison(start, size, false);
518 return (void *)start;
522 * Poison the shadow for a vmalloc region. Called as part of the
523 * freeing process at the time the region is freed.
525 void __kasan_poison_vmalloc(const void *start, unsigned long size)
527 if (!is_vmalloc_or_module_addr(start))
530 size = round_up(size, KASAN_GRANULE_SIZE);
531 kasan_poison(start, size, KASAN_VMALLOC_INVALID, false);
534 #else /* CONFIG_KASAN_VMALLOC */
536 int kasan_alloc_module_shadow(void *addr, size_t size, gfp_t gfp_mask)
541 unsigned long shadow_start;
543 shadow_start = (unsigned long)kasan_mem_to_shadow(addr);
544 scaled_size = (size + KASAN_GRANULE_SIZE - 1) >>
545 KASAN_SHADOW_SCALE_SHIFT;
546 shadow_size = round_up(scaled_size, PAGE_SIZE);
548 if (WARN_ON(!PAGE_ALIGNED(shadow_start)))
551 if (IS_ENABLED(CONFIG_UML)) {
552 __memset((void *)shadow_start, KASAN_SHADOW_INIT, shadow_size);
556 ret = __vmalloc_node_range(shadow_size, 1, shadow_start,
557 shadow_start + shadow_size,
559 PAGE_KERNEL, VM_NO_GUARD, NUMA_NO_NODE,
560 __builtin_return_address(0));
563 struct vm_struct *vm = find_vm_area(addr);
564 __memset(ret, KASAN_SHADOW_INIT, shadow_size);
565 vm->flags |= VM_KASAN;
566 kmemleak_ignore(ret);
568 if (vm->flags & VM_DEFER_KMEMLEAK)
569 kmemleak_vmalloc(vm, size, gfp_mask);
577 void kasan_free_module_shadow(const struct vm_struct *vm)
579 if (IS_ENABLED(CONFIG_UML))
582 if (vm->flags & VM_KASAN)
583 vfree(kasan_mem_to_shadow(vm->addr));