kasan: x86: arm64: KASAN tag-based mode for x86
Subsystems (14)
v12 cover kasan: x86: arm64: KASAN tag-based mode for x86
======= Introduction
The patchset aims to add a KASAN tag-based mode for the x86 architecture with the help of the new CPU feature called Linear Address Masking (LAM). Main improvement introduced by the series is 2x lower memory usage compared to KASAN's generic mode, the only currently available mode on x86. The tag based mode may also find errors that the generic mode couldn't because of differences in how these modes operate.
======= How does KASAN' tag-based mode work?
When enabled, memory accesses and allocations are augmented by the compiler during kernel compilation. Instrumentation functions are added to each memory allocation and each pointer dereference.
The allocation related functions generate a random tag and save it in two places: in shadow memory that maps to the allocated memory, and in the top bits of the pointer that points to the allocated memory. Storing the tag in the top of the pointer is possible because of Top-Byte Ignore (TBI) on arm64 architecture and LAM on x86.
The access related functions are performing a comparison between the tag stored in the pointer and the one stored in shadow memory. If the tags don't match an out of bounds error must have occurred and so an error report is generated.
The general idea for the tag-based mode is very well explained in the series with the original implementation [1].
[1] https://lore.kernel.org/all/[email protected]/
======= Differences summary compared to the arm64 tag-based mode
- Tag width:
- Tag width influences the chance of a tag mismatch due to two tags from different allocations having the same value. The bigger the possible range of tag values the lower the chance of that happening.
- Shortening the tag width from 8 bits to 4, while it can help with memory usage, it also increases the chance of not reporting an error. 4 bit tags have a ~7% chance of a tag mismatch.
- Address masking mechanism
- TBI in arm64 allows for storing metadata in the top 8 bits of the virtual address.
- LAM in x86 allows storing tags in bits [62:57] of the pointer. To maximize memory savings the tag width is reduced to bits [60:57].
- Inline mode mismatch reporting
- Arm64 inserts a BRK instruction to pass metadata about a tag mismatch to the KASAN report.
- Right now on x86 the INT3 instruction is used for the same purpose. The attempt to move it over to use UD1 is already implemented and tested but relies on another series that needs merging first. Therefore this patch will be posted separately once the dependency is satisfied by being merged upstream.
======= Testing
Checked all the kunits for both software tags and generic KASAN after making changes.
In generic mode (both with these patches and without) the results were:
kasan: pass:61 fail:1 skip:14 total:76
Totals: pass:61 fail:1 skip:14 total:76
not ok 1 kasan
and for software tags:
kasan: pass:65 fail:1 skip:10 total:76
Totals: pass:65 fail:1 skip:10 total:76
not ok 1 kasan
At the time of testing the one failing case is also present on generic mode without this patchset applied. This seems to point to something else being at fault for the one case not passing. The test case in question concerns strscpy() out of bounds error not getting caught.
======= Benchmarks [1]
All tests were ran on a Sierra Forest server platform. The only differences between the tests were kernel options:
- CONFIG_KASAN
- CONFIG_KASAN_GENERIC
- CONFIG_KASAN_SW_TAGS
- CONFIG_KASAN_INLINE [1]
- CONFIG_KASAN_OUTLINE
Boot time (until login prompt):
* 02:55 for clean kernel
* 05:42 / 06:32 for generic KASAN (inline/outline)
* 05:58 for tag-based KASAN (outline) [2]
Total memory usage (512GB present on the system - MemAvailable just after boot):
* 12.56 GB for clean kernel
* 81.74 GB for generic KASAN
* 44.39 GB for tag-based KASAN
Kernel size:
* 14 MB for clean kernel
* 24.7 MB / 19.5 MB for generic KASAN (inline/outline)
* 27.1 MB / 18.1 MB for tag-based KASAN (inline/outline)
Work under load time comparison (compiling the mainline kernel) (200 cores):
* 62s for clean kernel
* 171s / 125s for generic KASAN (outline/inline)
* 145s for tag-based KASAN (outline) [2]
[1] Currently inline mode doesn't work on x86 due to things missing in the compiler. I have written a patch for clang that seems to fix the inline mode and I was able to boot and check that all patches regarding the inline mode work as expected. My hope is to post the patch to LLVM once this series is completed, and then make inline mode available in the kernel config.
[2] While I was able to boot the inline tag-based kernel with my compiler changes in a simulated environment, due to toolchain difficulties I couldn't get it to boot on the machine I had access to. Also boot time results from the simulation seem too good to be true, and they're much too worse for the generic case to be believable. Therefore I'm posting only results from the physical server platform.
======= Compilation
Clang was used to compile the series (make LLVM=1) since gcc doesn't seem to have support for KASAN tag-based compiler instrumentation on x86. Patchset does seem to compile with gcc without an issue but doesn't boot afterwards.
======= Dependencies
The series is based on mm-new.
======= Previous versions
v11: https://lore.kernel.org/all/[email protected]/ v10: https://lore.kernel.org/all/[email protected]/ v9: https://lore.kernel.org/all/[email protected]/ v8: https://lore.kernel.org/all/[email protected]/ v7: https://lore.kernel.org/all/[email protected]/ v6: https://lore.kernel.org/all/[email protected]/ v5: https://lore.kernel.org/all/[email protected]/ v4: https://lore.kernel.org/all/[email protected]/ v3: https://lore.kernel.org/all/[email protected]/ v2: https://lore.kernel.org/all/[email protected]/ v1: https://lore.kernel.org/all/[email protected]/
=== (two fixes patches were split off after v6) (merged into mm-unstable)
v1: https://lore.kernel.org/all/[email protected]/
v2: https://lore.kernel.org/all/[email protected]/
v3: https://lore.kernel.org/all/[email protected]/
v4: https://lore.kernel.org/all/[email protected]/
Changes v12:
- Put CC_IS_CLANG and ADDRESS_MASKING into one Kconfig option that controls HAVE_ARCH_KASAN_SW_TAGS. (Peter Zijlstra)
Changes v11:
- Rebase series onto mm-new.
- Split off and modify the documentation patch.
- Split the pointer arithmetic reset tag patch in two. One patch for slight rework of page_to_virt() and one for putting x - __START_KERNEL_map into a tag reset helper.
- Fix issue pointed out by Dave on copy_from_kernel_nofault_allowed().
- Remove the arch_kasan_non_canonical_hook function scheme in favor of Andrey Ryabinin's simpler arch independent implementation.
Changes v10:
- Rebase the series onto 6.19-rc8.
- Add Mike Rapoport's acked-by to patch 6.
- Modify Documentation/dev-tools/kasan.rst in patches 1 and 13.
Changes v9:
- Lock HAVE_ARCH_KASAN_SW_TAGS behind CC_IS_CLANG due to gcc not working in practice.
- Remove pr_info() from KASAN initialization.
- Add paragraph to mm.rst explaining the alternative KASAN memory ranges.
- Move out arch based code from kasan_non_canonical_hook() into arch subdirectories. arm64 and non-arch changes in patch 1, x86 changes in patch 12.
- Reset tag bits on arm64's non-canonical hook to allow inline mode to work.
- Revert modifying __is_canonical_address() since it can break KVM. Just untag address in copy_from_kernel_no_fault_allowed().
- Add a bunch of reviewed-by tags.
Changes v8:
- Detached the UD1/INT3 inline patch from the series so the whole patchset can be merged without waiting on other dependency series. For now with lack of compiler support for the inline mode that patch didn't work anyway so this delay is not an issue.
- Rebased patches onto 6.19-rc5.
- Added acked-by tag to "kasan: arm64: x86: Make special tags arch specific".
Changes v7:
- Rebased the series onto Peter Zijlstra's "WARN() hackery" v2 patchset.
- Fix flipped memset arguments in "x86/kasan: KASAN raw shadow memory PTE init".
- Reorder tag width defines on arm64 to avoid redefinition warnings.
- Split off the pcpu unpoison patches into a separate fix oriented series.
- Redid the canonicality checks so it works for KVM too (didn't change the __canonical_address() function previously).
- A lot of fixes pointed out by Alexander in his great review:
- Fixed "x86/mm: Physical address comparisons in fill_p*d/pte"
- Merged "Support tag widths less than 8 bits" and "Make special tags arch specific".
- Added comments and extended patch messages for patches "x86/kasan: Make software tag-based kasan available" and "mm/execmem: Untag addresses in EXECMEM_ROX related pointer arithmetic",
- Fixed KASAN_TAG_MASK definition order so all patches compile individually.
- Renamed kasan_inline.c to kasan_sw_tags.c.
Changes v6:
- Initialize sw-tags only when LAM is available.
- Move inline mode to use UD1 instead of INT3
- Remove inline multishot patch.
- Fix the canonical check to work for user addresses too.
- Revise patch names and messages to align to tip tree rules.
- Fix vdso compilation issue.
Changes v5:
- Fix a bunch of arm64 compilation errors I didn't catch earlier. Thank You Ada for testing the series!
- Simplify the usage of the tag handling x86 functions (virt_to_page, phys_addr etc.).
- Remove within() and within_range() from the EXECMEM_ROX patch.
Changes v4:
- Revert x86 kasan_mem_to_shadow() scheme to the same on used in generic KASAN. Keep the arithmetic shift idea for the KASAN in general since it makes more sense for arm64 and in risc-v.
- Fix inline mode but leave it unavailable until a complementary compiler patch can be merged.
- Apply Dave Hansen's comments on series formatting, patch style and code simplifications.
Changes v3:
- Remove the runtime_const patch and setup a unified offset for both 5 and 4 paging levels.
- Add a fix for inline mode on x86 tag-based KASAN. Add a handler for int3 that is generated on inline tag mismatches.
- Fix scripts/gdb/linux/kasan.py so the new signed mem_to_shadow() is reflected there.
- Fix Documentation/arch/arm64/kasan-offsets.sh to take new offsets into account.
- Made changes to the kasan_non_canonical_hook() according to upstream discussion.
- Remove patches 2 and 3 since they related to risc-v and this series adds only x86 related things.
- Reorder __tag_*() functions so they're before arch_kasan_*(). Remove CONFIG_KASAN condition from __tag_set().
Changes v2:
- Split the series into one adding KASAN tag-based mode (this one) and another one that adds the dense mode to KASAN (will post later).
- Removed exporting kasan_poison() and used a wrapper instead in kasan_init_64.c
- Prepended series with 4 patches from the risc-v series and applied review comments to the first patch as the rest already are reviewed.
Maciej Wieczor-Retman (13):
kasan: Fix inline mode for x86 tag-based mode
x86/kasan: Add arch specific kasan functions
x86/mm: Reset pointer tag in x - __START_KERNEL_map instances
kasan: arm64: x86: Make page_to_virt() KASAN aware mm/execmem: Untag addresses in EXECMEM_ROX related pointer arithmetic x86/mm: Use physical address comparisons in fill_p*d/pte x86/kasan: Initialize KASAN raw shadow memory
x86/mm: Reset tags in a canonical address helper call x86/mm: Initialize LAM_SUP
x86: Increase minimal SLAB alignment for KASAN
x86/kasan: Use a logical bit shift for kasan_mem_to_shadow x86/kasan: Make software tag-based kasan available
docs: Update KASAN and x86 memory map documentations
Samuel Holland (2):
kasan: sw_tags: Use arithmetic shift for shadow computation
kasan: arm64: x86: Make special tags arch specific
Documentation/arch/arm64/kasan-offsets.sh | 8 ++- Documentation/arch/x86/x86_64/mm.rst | 21 +++++- Documentation/dev-tools/kasan.rst | 79 ++++++++++++++++------- MAINTAINERS | 2 +- arch/arm64/Kconfig | 10 +-- arch/arm64/include/asm/kasan-tags.h | 14 ++++ arch/arm64/include/asm/kasan.h | 2 - arch/arm64/include/asm/memory.h | 19 ++++-- arch/arm64/include/asm/uaccess.h | 1 + arch/arm64/mm/kasan_init.c | 7 +- arch/x86/Kconfig | 9 +++ arch/x86/boot/compressed/misc.h | 1 + arch/x86/include/asm/cache.h | 4 ++ arch/x86/include/asm/kasan-tags.h | 9 +++ arch/x86/include/asm/kasan.h | 62 +++++++++++++++++- arch/x86/include/asm/page_64.h | 11 +++- arch/x86/kernel/head_64.S | 3 + arch/x86/mm/init.c | 3 + arch/x86/mm/init_64.c | 11 ++-- arch/x86/mm/kasan_init_64.c | 24 ++++++- arch/x86/mm/maccess.c | 1 + arch/x86/mm/physaddr.c | 4 +- include/linux/kasan-tags.h | 21 ++++-- include/linux/kasan.h | 23 +++++-- include/linux/mm.h | 11 ++-- include/linux/mmzone.h | 2 +- include/linux/page-flags-layout.h | 9 +-- lib/Kconfig.kasan | 4 +- mm/execmem.c | 9 ++- mm/kasan/report.c | 16 +++-- mm/vmalloc.c | 7 +- scripts/Makefile.kasan | 3 + scripts/gdb/linux/kasan.py | 5 +- scripts/gdb/linux/mm.py | 5 +- 34 files changed, 331 insertions(+), 89 deletions(-) create mode 100644 arch/arm64/include/asm/kasan-tags.h create mode 100644 arch/x86/include/asm/kasan-tags.h
Signature · 1 line
2.53.0
PATCH v12 1/15 kasan: sw_tags: Use arithmetic shift for shadow computation
From: Samuel Holland <[email protected]>
Currently, kasan_mem_to_shadow() uses a logical right shift, which turns canonical kernel addresses into non-canonical addresses by clearing the high KASAN_SHADOW_SCALE_SHIFT bits. The value of KASAN_SHADOW_OFFSET is then chosen so that the addition results in a canonical address for the shadow memory.
For KASAN_GENERIC, this shift/add combination is ABI with the compiler, because KASAN_SHADOW_OFFSET is used in compiler-generated inline tag checks[1], which must only attempt to dereference canonical addresses.
However, for KASAN_SW_TAGS there is some freedom to change the algorithm without breaking the ABI. Because TBI is enabled for kernel addresses, the top bits of shadow memory addresses computed during tag checks are irrelevant, and so likewise are the top bits of KASAN_SHADOW_OFFSET. This is demonstrated by the fact that LLVM uses a logical right shift in the tag check fast path[2] but a sbfx (signed bitfield extract) instruction in the slow path[3] without causing any issues.
Use an arithmetic shift in kasan_mem_to_shadow() as it provides a number of benefits:
1) The memory layout doesn't change but is easier to understand. KASAN_SHADOW_OFFSET becomes a canonical memory address, and the shifted pointer becomes a negative offset, so KASAN_SHADOW_OFFSET == KASAN_SHADOW_END regardless of the shift amount or the size of the virtual address space.
2) KASAN_SHADOW_OFFSET becomes a simpler constant, requiring only one instruction to load instead of two. Since it must be loaded in each function with a tag check, this decreases kernel text size by 0.5%.
3) This shift and the sign extension from kasan_reset_tag() can be combined into a single sbfx instruction. When this same algorithm change is applied to the compiler, it removes an instruction from each inline tag check, further reducing kernel text size by an additional 4.6%.
These benefits extend to other architectures as well. On RISC-V, where the baseline ISA does not shifted addition or have an equivalent to the sbfx instruction, loading KASAN_SHADOW_OFFSET is reduced from 3 to 2 instructions, and kasan_mem_to_shadow(kasan_reset_tag(addr)) similarly combines two consecutive right shifts.
---
Changelog v11: (Maciej)
- Remove the arch_kasan_non_canonical_hook() scheme in favor of Andrey Ryabinin's much nicer simple implementation.
Changelog v10: (Maciej)
- Update the Documentation/dev-tools/kasan.rst file with the changed kasan_mem_to_shadow().
Changelog v9: (Maciej)
- Take out the arm64 related code from mm/kasan/report.c and put it in the arch specific directory in a new file so the kasan_mem_to_shadow() function can be included.
- Reset addr tag bits in arm64's arch_kasan_non_canonical_hook() so the inline mode can also work with that function (Andrey Ryabinin).
- Fix incorrect number of zeros in a comment in mm/kasan/report.c.
- Remove Catalin's acked-by since changes were made.
Changelog v7: (Maciej)
- Change UL to ULL in report.c to fix some compilation warnings.
Changelog v6: (Maciej)
- Add Catalin's acked-by.
- Move x86 gdb snippet here from the last patch.
Changelog v5: (Maciej)
- (u64) -> (unsigned long) in report.c
Changelog v4: (Maciej)
- Revert x86 to signed mem_to_shadow mapping.
- Remove last two paragraphs since they were just poorer duplication of the comments in kasan_non_canonical_hook().
Changelog v3: (Maciej)
- Fix scripts/gdb/linux/kasan.py so the new signed mem_to_shadow() is reflected there.
- Fix Documentation/arch/arm64/kasan-offsets.sh to take new offsets into account.
- Made changes to the kasan_non_canonical_hook() according to upstream discussion. Settled on overflow on both ranges and separate checks for x86 and arm.
Changelog v2: (Maciej)
- Correct address range that's checked in kasan_non_canonical_hook(). Adjust the comment inside.
- Remove part of comment from arch/arm64/include/asm/memory.h.
- Append patch message paragraph about the overflow in kasan_non_canonical_hook().
Documentation/arch/arm64/kasan-offsets.sh | 8 ++++++-- Documentation/dev-tools/kasan.rst | 18 ++++++++++++------ arch/arm64/Kconfig | 10 +++++----- arch/arm64/include/asm/memory.h | 14 +++++++++++++- arch/arm64/mm/kasan_init.c | 7 +++++-- include/linux/kasan.h | 10 ++++++++-- mm/kasan/report.c | 16 ++++++++++++---- scripts/gdb/linux/kasan.py | 5 ++++- scripts/gdb/linux/mm.py | 5 +++-- 9 files changed, 68 insertions(+), 25 deletions(-)
Documentation/arch/arm64/kasan-offsets.sh +6 -2
@@ -5,8 +5,12 @@ print_kasan_offset () { printf "%02d\t" $1 - printf "0x%08x00000000\n" $(( (0xffffffff & (-1 << ($1 - 1 - 32))) \ - - (1 << (64 - 32 - $2)) )) + if [[ $2 -ne 4 ]] then + printf "0x%08x00000000\n" $(( (0xffffffff & (-1 << ($1 - 1 - 32))) \ + - (1 << (64 - 32 - $2)) )) + else + printf "0x%08x00000000\n" $(( (0xffffffff & (-1 << ($1 - 1 - 32))) )) + fi } echo KASAN_SHADOW_SCALE_SHIFT = 3
Documentation/dev-tools/kasan.rst +12 -6
@@ -315,13 +315,19 @@ translate a memory address to its corresponding shadow address. Here is the function which translates an address to its corresponding shadow address:: - static inline void *kasan_mem_to_shadow(const void *addr) - { - return (void *)((unsigned long)addr >> KASAN_SHADOW_SCALE_SHIFT) - + KASAN_SHADOW_OFFSET; - } + static inline void *kasan_mem_to_shadow(const void *addr) + { + void *scaled; -where ``KASAN_SHADOW_SCALE_SHIFT = 3``. + if (IS_ENABLED(CONFIG_KASAN_GENERIC)) + scaled = (void *)((unsigned long)addr >> KASAN_SHADOW_SCALE_SHIFT); + else + scaled = (void *)((long)addr >> KASAN_SHADOW_SCALE_SHIFT); + + return KASAN_SHADOW_OFFSET + scaled; + } + +where for Generic KASAN ``KASAN_SHADOW_SCALE_SHIFT = 3``. Compile-time instrumentation is used to insert memory access checks. Compiler inserts function calls (``__asan_load*(addr)``, ``__asan_store*(addr)``) before
arch/arm64/Kconfig +5 -5
@@ -434,11 +434,11 @@ config KASAN_SHADOW_OFFSET default 0xdffffe0000000000 if ARM64_VA_BITS_42 && !KASAN_SW_TAGS default 0xdfffffc000000000 if ARM64_VA_BITS_39 && !KASAN_SW_TAGS default 0xdffffff800000000 if ARM64_VA_BITS_36 && !KASAN_SW_TAGS - default 0xefff800000000000 if (ARM64_VA_BITS_48 || (ARM64_VA_BITS_52 && !ARM64_16K_PAGES)) && KASAN_SW_TAGS - default 0xefffc00000000000 if (ARM64_VA_BITS_47 || ARM64_VA_BITS_52) && ARM64_16K_PAGES && KASAN_SW_TAGS - default 0xeffffe0000000000 if ARM64_VA_BITS_42 && KASAN_SW_TAGS - default 0xefffffc000000000 if ARM64_VA_BITS_39 && KASAN_SW_TAGS - default 0xeffffff800000000 if ARM64_VA_BITS_36 && KASAN_SW_TAGS + default 0xffff800000000000 if (ARM64_VA_BITS_48 || (ARM64_VA_BITS_52 && !ARM64_16K_PAGES)) && KASAN_SW_TAGS + default 0xffffc00000000000 if (ARM64_VA_BITS_47 || ARM64_VA_BITS_52) && ARM64_16K_PAGES && KASAN_SW_TAGS + default 0xfffffe0000000000 if ARM64_VA_BITS_42 && KASAN_SW_TAGS + default 0xffffffc000000000 if ARM64_VA_BITS_39 && KASAN_SW_TAGS + default 0xfffffff800000000 if ARM64_VA_BITS_36 && KASAN_SW_TAGS default 0xffffffffffffffff config UNWIND_TABLES
arch/arm64/include/asm/memory.h +13 -1
@@ -89,7 +89,15 @@* * KASAN_SHADOW_END is defined first as the shadow address that corresponds to * the upper bound of possible virtual kernel memory addresses UL(1) << 64 -* according to the mapping formula. +* according to the mapping formula. For Generic KASAN, the address in the +* mapping formula is treated as unsigned (part of the compiler's ABI), so the +* end of the shadow memory region is at a large positive offset from +* KASAN_SHADOW_OFFSET. For Software Tag-Based KASAN, the address in the +* formula is treated as signed. Since all kernel addresses are negative, they +* map to shadow memory below KASAN_SHADOW_OFFSET, making KASAN_SHADOW_OFFSET +* itself the end of the shadow memory region. (User pointers are positive and +* would map to shadow memory above KASAN_SHADOW_OFFSET, but shadow memory is +* not allocated for them.) * * KASAN_SHADOW_START is defined second based on KASAN_SHADOW_END. The shadow * memory start must map to the lowest possible kernel virtual memory address
@@ -100,7 +108,11 @@*/ #if defined(CONFIG_KASAN_GENERIC ) || defined(CONFIG_KASAN_SW_TAGS )#define KASAN_SHADOW_OFFSET _AC(CONFIG_KASAN_SHADOW_OFFSET, UL) +#ifdef CONFIG_KASAN_GENERIC #define KASAN_SHADOW_END ((UL(1) << (64 - KASAN_SHADOW_SCALE_SHIFT)) + KASAN_SHADOW_OFFSET) +#else +#define KASAN_SHADOW_END KASAN_SHADOW_OFFSET +#endif #define _KASAN_SHADOW_START (va) (KASAN_SHADOW_END - (UL(1) << ((va) - KASAN_SHADOW_SCALE_SHIFT)))#define KASAN_SHADOW_START _KASAN_SHADOW_START(vabits_actual)#define PAGE_END KASAN_SHADOW_START
arch/arm64/mm/kasan_init.c +5 -2
@@ -198,8 +198,11 @@ static bool __init root_level_aligned(u64 addr)/* The early shadow maps everything to a single page of zeroes */ asmlinkage void __init kasan_early_init(void) { -BUILD_BUG_ON (KASAN_SHADOW_OFFSET != -KASAN_SHADOW_END - (1UL << (64 -KASAN_SHADOW_SCALE_SHIFT ))); +if (IS_ENABLED (CONFIG_KASAN_GENERIC )) +BUILD_BUG_ON (KASAN_SHADOW_OFFSET != +KASAN_SHADOW_END - (1UL << (64 -KASAN_SHADOW_SCALE_SHIFT ))); +else +BUILD_BUG_ON (KASAN_SHADOW_OFFSET !=KASAN_SHADOW_END );BUILD_BUG_ON (!IS_ALIGNED (_KASAN_SHADOW_START (VA_BITS ),SHADOW_ALIGN ));BUILD_BUG_ON (!IS_ALIGNED (_KASAN_SHADOW_START (VA_BITS_MIN ),SHADOW_ALIGN ));BUILD_BUG_ON (!IS_ALIGNED (KASAN_SHADOW_END ,SHADOW_ALIGN ));
include/linux/kasan.h +8 -2
@@ -62,8 +62,14 @@ int kasan_populate_early_shadow(const void *shadow_start,#ifndef kasan_mem_to_shadowstatic inline void *kasan_mem_to_shadow (const void *addr) { -return (void *)((unsigned long )addr >>KASAN_SHADOW_SCALE_SHIFT ) - +KASAN_SHADOW_OFFSET ; +void *scaled; + +if (IS_ENABLED (CONFIG_KASAN_GENERIC )) + scaled = (void *)((unsigned long )addr >>KASAN_SHADOW_SCALE_SHIFT ); +else + scaled = (void *)((long )addr >>KASAN_SHADOW_SCALE_SHIFT ); + +return KASAN_SHADOW_OFFSET + scaled; }#endif
mm/kasan/report.c +12 -4
@@ -640,12 +640,20 @@ void kasan_non_canonical_hook(unsigned long addr) {unsigned long orig_addr, user_orig_addr;const char *bug_type; +void *tagged_null =set_tag (NULL ,KASAN_TAG_KERNEL ); +void *tagged_addr =set_tag ((void *)addr,KASAN_TAG_KERNEL );/* -* All addresses that came as a result of the memory-to-shadow mapping -* (even for bogus pointers) must be >= KASAN_SHADOW_OFFSET. +* Filter out addresses that cannot be shadow memory accesses generated +* by the compiler. +* +* In SW_TAGS mode, when computing a shadow address, the compiler always +* sets the kernel tag (some top bits) on the pointer *before* computing +* the memory-to-shadow mapping. As a result, valid shadow addresses +* are derived from tagged kernel pointers. */ -if (addr <KASAN_SHADOW_OFFSET ) +if (tagged_addr <kasan_mem_to_shadow (tagged_null) || + tagged_addr >kasan_mem_to_shadow ((void *)(~0ULL )))return ; orig_addr = (unsigned long )kasan_shadow_to_mem ((void *)addr);
@@ -670,7 +678,7 @@ void kasan_non_canonical_hook(unsigned long addr) }else if (user_orig_addr <TASK_SIZE ) { bug_type ="probably user-memory-access" ; orig_addr = user_orig_addr; - }else if (addr_in_shadow ((void *)addr)) + }else if (addr_in_shadow (tagged_addr)) bug_type ="probably wild-memory-access" ;else bug_type ="maybe wild-memory-access" ;
scripts/gdb/linux/kasan.py +4 -1
@@ -7,7 +7,8 @@ # import gdb -from linux import constants, mm +from linux import constants, utils, mm +from ctypes import c_int64 as s64 def help(): t = """Usage: lx-kasan_mem_to_shadow [Hex memory addr]
@@ -39,6 +40,8 @@ class KasanMemToShadow(gdb.Command): else: help() def kasan_mem_to_shadow(self, addr): + if constants.CONFIG_KASAN_SW_TAGS and not utils.is_target_arch('x86'): + addr = s64(addr) return (addr >> self.p_ops.KASAN_SHADOW_SCALE_SHIFT) + self.p_ops.KASAN_SHADOW_OFFSET KasanMemToShadow()
scripts/gdb/linux/mm.py +3 -2
@@ -281,12 +281,13 @@ class aarch64_page_ops(): self.KERNEL_END = gdb.parse_and_eval("_end") if constants.LX_CONFIG_KASAN_GENERIC or constants.LX_CONFIG_KASAN_SW_TAGS: + self.KASAN_SHADOW_OFFSET = constants.LX_CONFIG_KASAN_SHADOW_OFFSET if constants.LX_CONFIG_KASAN_GENERIC: self.KASAN_SHADOW_SCALE_SHIFT = 3 + self.KASAN_SHADOW_END = (1 << (64 - self.KASAN_SHADOW_SCALE_SHIFT)) + self.KASAN_SHADOW_OFFSET else: self.KASAN_SHADOW_SCALE_SHIFT = 4 - self.KASAN_SHADOW_OFFSET = constants.LX_CONFIG_KASAN_SHADOW_OFFSET - self.KASAN_SHADOW_END = (1 << (64 - self.KASAN_SHADOW_SCALE_SHIFT)) + self.KASAN_SHADOW_OFFSET + self.KASAN_SHADOW_END = self.KASAN_SHADOW_OFFSET self.PAGE_END = self.KASAN_SHADOW_END - (1 << (self.vabits_actual - self.KASAN_SHADOW_SCALE_SHIFT)) else: self.PAGE_END = self._PAGE_END(self.VA_BITS_MIN)
Signature · 1 line
2.53.0
Re: [PATCH v12 01/15] kasan: sw_tags: Use arithmetic shift for shadow computation
Documentation/arch/arm64/kasan-offsets.sh line 8
Quoted 11 lines · Maciej Wieczor-Retman
Documentation/arch/arm64/kasan-offsets.sh +1
-2@@ -5,8 +5,12 @@ print_kasan_offset () { printf "%02d\t" $1 - printf "0x%08x00000000\n" $(( (0xffffffff & (-1 << ($1 - 1 - 32))) \ - - (1 << (64 - 32 - $2)) )) + if [[ $2 -ne 4 ]] then
Nitpick: does this need a semicolon before 'then'?
I can see Sashiko raised it here:
Quoted 8 lines
Documentation/arch/arm64/kasan-offsets.sh +5
-0+ printf "0x%08x00000000\n" $(( (0xffffffff & (-1 << ($1 - 1 - 32))) \ + - (1 << (64 - 32 - $2)) )) + else + printf "0x%08x00000000\n" $(( (0xffffffff & (-1 << ($1 - 1 - 32))) )) + fi } echo KASAN_SHADOW_SCALE_SHIFT = 3
[...]
Quoted 15 lines
scripts/gdb/linux/kasan.py +2
-1@@ -7,7 +7,8 @@ # import gdb -from linux import constants, mm +from linux import constants, utils, mm +from ctypes import c_int64 as s64 def help(): t = """Usage: lx-kasan_mem_to_shadow [Hex memory addr]
scripts/gdb/linux/kasan.py class KasanMemToShadow(gdb.Command): · line 43
Quoted 4 lines
scripts/gdb/linux/kasan.py +1
-0@@ -39,6 +40,8 @@ class KasanMemToShadow(gdb.Command): else: help() def kasan_mem_to_shadow(self, addr): + if constants.CONFIG_KASAN_SW_TAGS and not utils.is_target_arch('x86'):
Does this need to be constants.LX_CONFIG_KASAN_SW_TAGS? I don't claim I fully understand this script but the other constants.* use LX_*.
scripts/gdb/linux/kasan.py class KasanMemToShadow(gdb.Command): · line 45
Quoted 2 lines
scripts/gdb/linux/kasan.py +1
-0+ addr = s64(addr) return (addr >> self.p_ops.KASAN_SHADOW_SCALE_SHIFT) + self.p_ops.KASAN_SHADOW_OFFSET
And, again, Sashiko mentions that the bitwise right shift here will fail after the cast to c_int64. I just tried this in python:
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
from ctypes import
c_int64as s64
s64(0xffff000008eca008) >> 4
Traceback (most recent call last):
File "<python-input-1>", line 1, in <module>
s64(0xffff000008eca008) >> 4
~~~~~~~~~~~~~~~~~~~~~~~~^^~~TypeError: unsupported operand type(s) for >>: 'c_long' and 'int'
I guess it's hidden by the wrong check on
constants.CONFIG_KASAN_SW_TAGS.
Otherwise I think the changes are fine. If you fix the above, feel free to add:
PATCH v12 2/15 kasan: arm64: x86: Make special tags arch specific
In reply to Maciej Wieczor-RetmanFrom: Samuel Holland <[email protected]>
KASAN's tag-based mode defines multiple special tag values. They're reserved for:
- Native kernel value. On arm64 it's 0xFF and it causes an early return in the tag checking function.
- Invalid value. 0xFE marks an area as freed / unallocated. It's also the value that is used to initialize regions of shadow memory.
- Min and max values. 0xFD is the highest value that can be randomly generated for a new tag. 0 is the minimal value with the exception of arm64's hardware mode where it is equal to 0xF0.
Metadata macro is also defined:
- Tag width equal to 8.
Tag-based mode on x86 is going to use 4 bit wide tags so all the above values need to be changed accordingly.
Make tag width and native kernel tag arch specific for x86 and arm64.
Base the invalid tag value and the max value on the native kernel tag since they follow the same pattern on both mentioned architectures.
Also generalize KASAN_SHADOW_INIT and 0xff used in various page_kasan_tag* helpers.
Give KASAN_TAG_MIN the default value of zero, and move the special value for hw_tags arm64 to its arch specific kasan-tags.h.
---
Changelog v9:
- Add Andrey Ryabinin's Reviewed-by tag.
- Add Andrey Konovalov's Reviewed-by tag.
Changelog v8:
- Add Will's Acked-by tag.
Changelog v7:
- Reorder defines of arm64 tag width to prevent redefinition warnings.
- Remove KASAN_TAG_MASK so it's only defined in mmzone.h (Andrey Konovalov)
- Merge the 'support tag widths less than 8 bits' with this patch since they do similar things and overwrite each other. (Alexander)
Changelog v6:
- Add hardware tags KASAN_TAG_WIDTH value to the arm64 arch file.
- Keep KASAN_TAG_MASK in the mmzone.h.
- Remove ifndef from KASAN_SHADOW_INIT.
Changelog v5:
- Move KASAN_TAG_MIN to the arm64 kasan-tags.h for the hardware KASAN mode case.
Changelog v4:
- Move KASAN_TAG_MASK to kasan-tags.h.
Changelog v2:
- Remove risc-v from the patch.
MAINTAINERS | 2 +- arch/arm64/include/asm/kasan-tags.h | 14 ++++++++++++++ arch/arm64/include/asm/kasan.h | 2 -- arch/arm64/include/asm/uaccess.h | 1 + arch/x86/include/asm/kasan-tags.h | 9 +++++++++ include/linux/kasan-tags.h | 19 ++++++++++++++----- include/linux/kasan.h | 3 +-- include/linux/mm.h | 6 +++--- include/linux/page-flags-layout.h | 9 +-------- 9 files changed, 44 insertions(+), 21 deletions(-) create mode 100644 arch/arm64/include/asm/kasan-tags.h create mode 100644 arch/x86/include/asm/kasan-tags.h
MAINTAINERS +1 -1
@@ -13735,7 +13735,7 @@ L: [email protected] S: Maintained B: https://bugzilla.kernel.org/buglist.cgi?component=Sanitizers&product=Memory%20Management F: Documentation/dev-tools/kasan.rst -F: arch/*/include/asm/*kasan.h +F: arch/*/include/asm/*kasan*.h F: arch/*/mm/kasan_init* F: include/linux/kasan*.h F: lib/Kconfig.kasan
arch/arm64/include/asm/kasan-tags.h new file +14 -0
@@ -0,0 +1,14 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef __ASM_KASAN_TAGS_H +#define __ASM_KASAN_TAGS_H + +#define KASAN_TAG_KERNEL 0xFF/* native kernel pointers tag */ + +#ifdef CONFIG_KASAN_HW_TAGS +#define KASAN_TAG_MIN 0xF0/* minimum value for random tags */ +#define KASAN_TAG_WIDTH 4 +#else +#define KASAN_TAG_WIDTH 8 +#endif + +#endif /* ASM_KASAN_TAGS_H */
arch/arm64/include/asm/kasan.h +0 -2
@@ -6,8 +6,6 @@#include <linux/linkage.h> #include <asm/memory.h> -#include <asm/mte-kasan.h> -#include <asm/pgtable-types.h> #define arch_kasan_set_tag (addr, tag) __tag_set(addr, tag)#define arch_kasan_reset_tag (addr) __tag_reset(addr)
arch/arm64/include/asm/uaccess.h +1 -0
@@ -22,6 +22,7 @@#include <asm/cpufeature.h> #include <asm/mmu.h> #include <asm/mte.h> +#include <asm/mte-kasan.h> #include <asm/ptrace.h> #include <asm/memory.h> #include <asm/extable.h>
arch/x86/include/asm/kasan-tags.h new file +9 -0
@@ -0,0 +1,9 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef __ASM_KASAN_TAGS_H +#define __ASM_KASAN_TAGS_H + +#define KASAN_TAG_KERNEL 0xF/* native kernel pointers tag */ + +#define KASAN_TAG_WIDTH 4 + +#endif /* ASM_KASAN_TAGS_H */
include/linux/kasan-tags.h +14 -5
@@ -2,13 +2,22 @@#ifndef _LINUX_KASAN_TAGS_H#define _LINUX_KASAN_TAGS_H +#if defined(CONFIG_KASAN_SW_TAGS ) || defined(CONFIG_KASAN_HW_TAGS ) +#include <asm/kasan-tags.h> +#endif + +#ifndef KASAN_TAG_WIDTH +#define KASAN_TAG_WIDTH 0 +#endif + +#ifndef KASAN_TAG_KERNEL #define KASAN_TAG_KERNEL 0xFF/* native kernel pointers tag */ -#define KASAN_TAG_INVALID 0xFE/* inaccessible memory tag */ -#define KASAN_TAG_MAX 0xFD/* maximum value for random tags */ +#endif + +#define KASAN_TAG_INVALID (KASAN_TAG_KERNEL - 1)/* inaccessible memory tag */ +#define KASAN_TAG_MAX (KASAN_TAG_KERNEL - 2)/* maximum value for random tags */ -#ifdef CONFIG_KASAN_HW_TAGS -#define KASAN_TAG_MIN 0xF0/* minimum value for random tags */ -#else +#ifndef KASAN_TAG_MIN #define KASAN_TAG_MIN 0x00/* minimum value for random tags */ #endif
include/linux/kasan.h +1 -2
@@ -40,8 +40,7 @@ typedef unsigned int __bitwise kasan_vmalloc_flags_t;/* Software KASAN implementations use shadow memory. */ #ifdef CONFIG_KASAN_SW_TAGS -/* This matches KASAN_TAG_INVALID. */ -#define KASAN_SHADOW_INIT 0xFE +#define KASAN_SHADOW_INIT KASAN_TAG_INVALID#else #define KASAN_SHADOW_INIT 0#endif
include/linux/mm.h +3 -3
@@ -2440,7 +2440,7 @@ static inline u8 page_kasan_tag(const struct page *page)if (kasan_enabled ()) { tag = (page->flags.f >>KASAN_TAG_PGSHIFT ) &KASAN_TAG_MASK ; - tag ^=0xff ; + tag ^=KASAN_TAG_KERNEL ; }return tag;
@@ -2453,7 +2453,7 @@ static inline void page_kasan_tag_set(struct page *page, u8 tag)if (!kasan_enabled ())return ; - tag ^=0xff ; + tag ^=KASAN_TAG_KERNEL ; old_flags =READ_ONCE (page->flags.f); do { flags = old_flags;
@@ -2472,7 +2472,7 @@ static inline void page_kasan_tag_reset(struct page *page)static inline u8 page_kasan_tag (const struct page *page) { -return 0xff ; +return KASAN_TAG_KERNEL ; }static inline void page_kasan_tag_set (struct page *page,u8 tag) { }
include/linux/page-flags-layout.h +1 -8
@@ -3,6 +3,7 @@#define PAGE_FLAGS_LAYOUT_H #include <linux/numa.h> +#include <linux/kasan-tags.h> #include <generated/bounds.h> /*
@@ -72,14 +73,6 @@#define NODE_NOT_IN_PAGE_FLAGS 1#endif -#if defined(CONFIG_KASAN_SW_TAGS ) -#define KASAN_TAG_WIDTH 8 -#elif defined(CONFIG_KASAN_HW_TAGS ) -#define KASAN_TAG_WIDTH 4 -#else -#define KASAN_TAG_WIDTH 0 -#endif -#ifdef CONFIG_NUMA_BALANCING #define LAST__PID_SHIFT 8#define LAST__PID_MASK ((1 << LAST__PID_SHIFT)-1)
Signature · 1 line
2.53.0
Re: [PATCH v12 02/15] kasan: arm64: x86: Make special tags arch specific
Quoted 29 lines · Maciej Wieczor-Retman
From: Samuel Holland <[email protected]>
KASAN's tag-based mode defines multiple special tag values. They're reserved for:
- Native kernel value. On arm64 it's0xFFand it causes an early return in the tag checking function.
- Invalid value.0xFEmarks an area as freed / unallocated. It's also the value that is used to initialize regions of shadow memory.
- Min and max values.0xFDis the highest value that can be randomly generated for a new tag. 0 is the minimal value with the exception of arm64's hardware mode where it is equal to0xF0.Metadata macro is also defined:
- Tag width equal to 8.Tag-based mode on x86 is going to use 4 bit wide tags so all the above values need to be changed accordingly.
Make tag width and native kernel tag arch specific for x86 and arm64.
Base the invalid tag value and the max value on the native kernel tag since they follow the same pattern on both mentioned architectures.
Also generalize
KASAN_SHADOW_INITand0xffused in various page_kasan_tag* helpers.Give
KASAN_TAG_MINthe default value of zero, and move the special value forhw_tagsarm64 to its arch specifickasan-tags.h.
Quoted 6 lines
Signed-off-by Samuel Holland <[email protected]>Co-developed-by Maciej Wieczor-Retman <[email protected]>Signed-off-by Maciej Wieczor-Retman <[email protected]>Reviewed-by Andrey Konovalov <[email protected]>Reviewed-by Andrey Ryabinin <[email protected]>
PATCH v12 3/15 kasan: Fix inline mode for x86 tag-based mode
In reply to Maciej Wieczor-RetmanFrom: Maciej Wieczor-Retman <[email protected]>
The LLVM compiler uses hwasan-instrument-with-calls parameter to setup inline or outline mode in tag-based KASAN. If zeroed, it means the instrumentation implementation will be pasted into each relevant location along with KASAN related constants during compilation. If set to one all function instrumentation will be done with function calls instead.
The default hwasan-instrument-with-calls value for the x86 architecture in the compiler is "1", which is not true for other architectures. Because of this, enabling inline mode in software tag-based KASAN doesn't work on x86 as the kernel script doesn't zero out the parameter and always sets up the outline mode.
Explicitly zero out hwasan-instrument-with-calls when enabling inline mode in tag-based KASAN.
---
Changelog v9:
- Add Andrey Ryabinin's Reviewed-by tag.
Changelog v7:
- Add Alexander's Reviewed-by tag.
Changelog v6:
- Add Andrey's Reviewed-by tag.
Changelog v3:
- Add this patch to the series.
scripts/Makefile.kasan | 3 +++ 1 file changed, 3 insertions(+)
scripts/Makefile.kasan +3 -0
@@ -76,8 +76,11 @@ CFLAGS_KASAN := -fsanitize=kernel-hwaddress RUSTFLAGS_KASAN := -Zsanitizer=kernel-hwaddress \ -Zsanitizer-recover=kernel-hwaddress +# LLVM sets hwasan-instrument-with-calls to 1 on x86 by default. Set it to 0 +# when inline mode is enabled. ifdef CONFIG_KASAN_INLINE kasan_params += hwasan-mapping-offset=$(KASAN_SHADOW_OFFSET) + kasan_params += hwasan-instrument-with-calls=0 else kasan_params += hwasan-instrument-with-calls=1 endif
Signature · 1 line
2.53.0
PATCH v12 4/15 x86/kasan: Add arch specific kasan functions
In reply to Maciej Wieczor-RetmanFrom: Maciej Wieczor-Retman <[email protected]>
KASAN's software tag-based mode needs multiple macros/functions to handle tag and pointer interactions - to set, retrieve and reset tags from the top bits of a pointer.
Mimic functions currently used by arm64 but change the tag's position to bits [60:57] in the pointer.
---
Changelog v9:
- Rename KASAN_TAG_BYTE_MASK to KASAN_TAG_BITS_MASK.
- Add Andrey Ryabinin's Reviewed-by tag.
Changelog v7:
- Add KASAN_TAG_BYTE_MASK to avoid circular includes and avoid removing KASAN_TAG_MASK from mmzone.h.
- Remove Andrey's Acked-by tag.
Changelog v6:
- Remove empty line after ifdef CONFIG_KASAN_SW_TAGS
- Add ifdef 64 bit to avoid problems in vdso32.
- Add Andrey's Acked-by tag.
Changelog v4:
- Rewrite __tag_set() without pointless casts and make it more readable.
Changelog v3:
- Reorder functions so that __tag_*() etc are above the arch_kasan_*() ones.
- Remove CONFIG_KASAN condition from __tag_set()
arch/x86/include/asm/kasan.h | 42 ++++++++++++++++++++++++++++++++++-- include/linux/kasan-tags.h | 2 ++ include/linux/mmzone.h | 2 +- 3 files changed, 43 insertions(+), 3 deletions(-)
arch/x86/include/asm/kasan.h +40 -2
@@ -3,6 +3,8 @@#define _ASM_X86_KASAN_H#include <linux/const.h> +#include <linux/kasan-tags.h> +#include <linux/types.h> #define KASAN_SHADOW_OFFSET _AC(CONFIG_KASAN_SHADOW_OFFSET, UL)#define KASAN_SHADOW_SCALE_SHIFT 3
@@ -24,8 +26,43 @@ KASAN_SHADOW_SCALE_SHIFT)))#ifndef __ASSEMBLER__ +#include <linux/bitops.h> +#include <linux/bitfield.h> +#include <linux/bits.h> + +#ifdef CONFIG_KASAN_SW_TAGS +#define __tag_shifted (tag) FIELD_PREP(GENMASK_ULL(60, 57), tag) +#define __tag_reset (addr) (sign_extend64((u64)(addr), 56)) +#define __tag_get (addr) ((u8)FIELD_GET(GENMASK_ULL(60, 57), (u64)addr)) +#else +#define __tag_shifted (tag) 0UL +#define __tag_reset (addr) (addr) +#define __tag_get (addr) 0 +#endif /* CONFIG_KASAN_SW_TAGS */ + +#ifdef CONFIG_64BIT +static inline void *__tag_set (const void *__addr,u8 tag) +{ +u64 addr = (u64 )__addr; + + addr &= ~__tag_shifted (KASAN_TAG_BITS_MASK ); + addr |=__tag_shifted (tag &KASAN_TAG_BITS_MASK ); + +return (void *)addr; +} +#else +static inline void *__tag_set (void *__addr,u8 tag) +{ +return __addr; +} +#endif + +#define arch_kasan_set_tag (addr, tag) __tag_set(addr, tag) +#define arch_kasan_reset_tag (addr) __tag_reset(addr) +#define arch_kasan_get_tag (addr) __tag_get(addr)#ifdef CONFIG_KASAN +void __init kasan_early_init (void );void __init kasan_init (void );void __init kasan_populate_shadow_for_vaddr (void *va,size_t size,int nid);
@@ -34,8 +71,9 @@ static inline void kasan_early_init(void) { }static inline void kasan_init (void ) { }static inline void kasan_populate_shadow_for_vaddr (void *va,size_t size,int nid) { } -#endif -#endif +#endif /* CONFIG_KASAN */ + +#endif /* __ASSEMBLER__ */ #endif
include/linux/kasan-tags.h +2 -0
@@ -10,6 +10,8 @@#define KASAN_TAG_WIDTH 0#endif +#define KASAN_TAG_BITS_MASK ((1UL << KASAN_TAG_WIDTH) - 1) +#ifndef KASAN_TAG_KERNEL #define KASAN_TAG_KERNEL 0xFF/* native kernel pointers tag */ #endif
include/linux/mmzone.h +1 -1
@@ -1266,7 +1266,7 @@ static inline bool zone_is_empty(const struct zone *zone)#define NODES_MASK ((1UL << NODES_WIDTH) - 1)#define SECTIONS_MASK ((1UL << SECTIONS_WIDTH) - 1)#define LAST_CPUPID_MASK ((1UL << LAST_CPUPID_SHIFT) - 1) -#define KASAN_TAG_MASK ((1UL << KASAN_TAG_WIDTH) - 1) +#define KASAN_TAG_MASK KASAN_TAG_BITS_MASK#define ZONEID_MASK ((1UL << ZONEID_SHIFT) - 1)static inline enum zone_type memdesc_zonenum (memdesc_flags_t flags)
Signature · 1 line
2.53.0
PATCH v12 5/15 x86/mm: Reset pointer tag in x - __START_KERNEL_map instances
In reply to Maciej Wieczor-RetmanFrom: Maciej Wieczor-Retman <[email protected]>
With KASAN software tag-based mode arbitrary kernel pointers can be tagged, and any place where pointer arithmetic is used to convert a virtual address into a physical one can raise errors if the virtual address is tagged. To lower the amount of lines added it's beneficial to move the similar pointer arithmetic to a helper first.
Reset the tag in the __phys_addr_kernel_start() which plugs into all the relevant virtual to physical address helpers.
---
Changelog v11:
- Split off this patch from the tag reset patch. Move x - __START_KERNEL_map to a helper so less lines are added.
arch/x86/include/asm/page_64.h | 11 +++++++++-- arch/x86/mm/physaddr.c | 4 ++-- 2 files changed, 11 insertions(+), 4 deletions(-)
arch/x86/include/asm/page_64.h +9 -2
@@ -7,6 +7,7 @@#ifndef __ASSEMBLER__#include <asm/cpufeatures.h> #include <asm/alternative.h> +#include <asm/kasan.h> #include <linux/kmsan-checks.h> #include <linux/mmdebug.h>
@@ -20,9 +21,15 @@ extern unsigned long vmalloc_base;extern unsigned long vmemmap_base;extern unsigned long direct_map_physmem_end; +static __always_inline unsigned long __phys_addr_kernel_start (unsigned long x) +{ + x =__tag_reset (x); +return x - __START_KERNEL_map; +} +static __always_inline unsigned long __phys_addr_nodebug (unsigned long x) { -unsigned long y = x - __START_KERNEL_map; +unsigned long y =__phys_addr_kernel_start (x);/* use the carry flag to determine if x was < __START_KERNEL_map */ x = y + ((x > y) ? phys_base : (__START_KERNEL_map -PAGE_OFFSET ));
@@ -38,7 +45,7 @@ extern unsigned long __phys_addr(unsigned long);static inline unsigned long __phys_addr_symbol (unsigned long x) { -unsigned long y = x - __START_KERNEL_map; +unsigned long y =__phys_addr_kernel_start (x);/* only check upper bounds since lower bounds will trigger carry */ VIRTUAL_BUG_ON (y >=KERNEL_IMAGE_SIZE );
arch/x86/mm/physaddr.c +2 -2
@@ -14,7 +14,7 @@#ifdef CONFIG_DEBUG_VIRTUAL unsigned long __phys_addr (unsigned long x) { -unsigned long y = x - __START_KERNEL_map; +unsigned long y =__phys_addr_kernel_start (x);/* use the carry flag to determine if x was < __START_KERNEL_map */ if (unlikely (x > y)) {
@@ -35,7 +35,7 @@ EXPORT_SYMBOL(__phys_addr);bool __virt_addr_valid (unsigned long x) { -unsigned long y = x - __START_KERNEL_map; +unsigned long y =__phys_addr_kernel_start (x);/* use the carry flag to determine if x was < __START_KERNEL_map */ if (unlikely (x > y)) {
Signature · 1 line
2.53.0
PATCH v12 6/15 kasan: arm64: x86: Make page_to_virt() KASAN aware
In reply to Maciej Wieczor-RetmanFrom: Maciej Wieczor-Retman <[email protected]>
Special page_to_virt() implementation is needed if an architecture wants to enable KASAN software tag-based mode.
Make page_to_virt() KASAN aware in arch-independent code so architectures implementing the software tag-based mode don't have to define their own implementations anymore. When KASAN is disabled or for architectures that don't implement the software tag-based mode page_to_virt() will be optimized to it's previous form.
---
Changelog v11:
- Redo the patch to work on the page_to_virt macro. Split off changes about virt to phys conversion to an earlier patch.
- Remove Alexander's acked-by due to bigger changes.
Changelog v7:
- Add Alexander's Acked-by tag.
Changelog v5:
- Move __tag_reset() calls into __phys_addr_nodebug() and __virt_addr_valid() instead of calling it on the arguments of higher level functions.
Changelog v4:
- Simplify page_to_virt() by removing pointless casts.
- Remove change in __is_canonical_address() because it's taken care of in a later patch due to a LAM compatible definition of canonical.
arch/arm64/include/asm/memory.h | 5 ----- include/linux/kasan.h | 10 ++++++++++ include/linux/mm.h | 5 ++++- 3 files changed, 14 insertions(+), 6 deletions(-)
arch/arm64/include/asm/memory.h +0 -5
@@ -411,11 +411,6 @@ static inline unsigned long virt_to_pfn(const void *kaddr)*/ #if defined(CONFIG_DEBUG_VIRTUAL ) -#define page_to_virt (x) ({ \ - __typeof__(x) __page = x; \ - void *__addr = __va(page_to_phys(__page)); \ - (void *)__tag_set((const void *)__addr, page_kasan_tag(__page));\ -})#define virt_to_page (x) pfn_to_page(virt_to_pfn(x))#else #define page_to_virt (x) ({ \
include/linux/kasan.h +10 -0
@@ -527,6 +527,11 @@ static inline void *kasan_reset_tag(const void *addr)return (void *)arch_kasan_reset_tag (addr); } +static inline void *kasan_set_tag (const void *addr,u8 tag) +{ +return (void *)arch_kasan_set_tag (addr, tag); +} +/** * kasan_report - print a report about a bad memory access detected by KASAN * @addr: address of the bad access
@@ -544,6 +549,11 @@ static inline void *kasan_reset_tag(const void *addr) return (void *)addr; } +static inline void *kasan_set_tag (const void *addr,u8 tag) +{ +return (void *)addr; +} +#endif /* CONFIG_KASAN_SW_TAGS || CONFIG_KASAN_HW_TAGS*/ #ifdef CONFIG_KASAN_HW_TAGS
include/linux/mm.h +4 -1
@@ -117,7 +117,10 @@ extern int mmap_rnd_compat_bits __read_mostly;#endif #ifndef page_to_virt -#define page_to_virt (x) __va(PFN_PHYS(page_to_pfn(x))) +#define page_to_virt (x) ({ \ + void *__addr = __va(PFN_PHYS(page_to_pfn((struct page *)x))); \ + kasan_set_tag(__addr, page_kasan_tag(x)); \ +})#endif #ifndef lm_alias
Signature · 1 line
2.53.0
Will Deacon
maintainerRe: [PATCH v12 06/15] kasan: arm64: x86: Make page_to_virt() KASAN aware
Quoted 41 lines · Maciej Wieczor-Retman
From: Maciej Wieczor-Retman <[email protected]>
Special
page_to_virt()implementation is needed if an architecture wants to enable KASAN software tag-based mode.Make
page_to_virt()KASAN aware in arch-independent code so architectures implementing the software tag-based mode don't have to define their own implementations anymore. When KASAN is disabled or for architectures that don't implement the software tag-based modepage_to_virt()will be optimized to it's previous form.Signed-off-by Maciej Wieczor-Retman <[email protected]>---
Changelog v11:
- Redo the patch to work on thepage_to_virtmacro. Split off changes about virt to phys conversion to an earlier patch.
- Remove Alexander's acked-by due to bigger changes.Changelog v7:
- Add Alexander's Acked-by tag.Changelog v5:
- Move__tag_reset()calls into__phys_addr_nodebug()and__virt_addr_valid()instead of calling it on the arguments of higher level functions.Changelog v4:
- Simplifypage_to_virt()by removing pointless casts.
- Remove change in__is_canonical_address()because it's taken care of in a later patch due to a LAM compatible definition of canonical.arch/arm64/include/asm/memory.h | 5 ----- include/linux/kasan.h | 10 ++++++++++ include/linux/mm.h | 5 ++++- 3 files changed, 14 insertions(+), 6 deletions(-)arch/arm64/include/asm/memory.h +0
-0
arch/arm64/include/asm/memory.h static inline unsigned long virt_to_pfn(const void *kaddr) · line 418
Quoted 8 lines
arch/arm64/include/asm/memory.h +0
-5@@ -411,11 +411,6 @@ static inline unsigned long virt_to_pfn(const void *kaddr)*/ #if defined(CONFIG_DEBUG_VIRTUAL ) -#define page_to_virt (x) ({ \ - __typeof__(x) __page = x; \ - void *__addr = __va(page_to_phys(__page)); \ - (void *)__tag_set((const void *)__addr, page_kasan_tag(__page));\ -})
So here we're using '__page' to avoid multiple evaluations of 'x'...
Quoted 36 lines
arch/arm64/include/asm/memory.h +0
-0#define virt_to_page (x) pfn_to_page(virt_to_pfn(x))#else #define page_to_virt (x) ({ \include/linux/kasan.h +10
-0@@ -527,6 +527,11 @@ static inline void *kasan_reset_tag(const void *addr)return (void *)arch_kasan_reset_tag (addr); } +static inline void *kasan_set_tag (const void *addr,u8 tag) +{ +return (void *)arch_kasan_set_tag (addr, tag); +} +/** * kasan_report - print a report about a bad memory access detected by KASAN * @addr: address of the bad access @@ -544,6 +549,11 @@ static inline void *kasan_reset_tag(const void *addr) return (void *)addr; } +static inline void *kasan_set_tag (const void *addr,u8 tag) +{ +return (void *)addr; +} +#endif /* CONFIG_KASAN_SW_TAGS || CONFIG_KASAN_HW_TAGS*/ #ifdef CONFIG_KASAN_HW_TAGS include/linux/mm.h +0
-0
include/linux/mm.h extern int mmap_rnd_compat_bits __read_mostly; · line 123
Quoted 8 lines
include/linux/mm.h +4
-1@@ -117,7 +117,10 @@ extern int mmap_rnd_compat_bits __read_mostly;#endif #ifndef page_to_virt -#define page_to_virt (x) __va(PFN_PHYS(page_to_pfn(x))) +#define page_to_virt (x) ({ \ + void *__addr = __va(PFN_PHYS(page_to_pfn((struct page *)x))); \ + kasan_set_tag(__addr, page_kasan_tag(x)); \ +})
... but in the new code you're proposing, you evaluate 'x' twice.
Is there a reason not to take the arm64 code as-is?
Will
Re: [PATCH v12 06/15] kasan: arm64: x86: Make page_to_virt() KASAN aware
Quoted 18 lines · Will Deacon
Quoted 6 lines · Maciej Wieczor-Retman
From: Maciej Wieczor-Retman <[email protected]>
arch/arm64/include/asm/memory.h +0
-0arch/arm64/include/asm/memory.h static inline unsigned long virt_to_pfn(const void *kaddr) · line 418
Quoted 8 lines
arch/arm64/include/asm/memory.h +0
-5@@ -411,11 +411,6 @@ static inline unsigned long virt_to_pfn(const void *kaddr)*/ #if defined(CONFIG_DEBUG_VIRTUAL ) -#define page_to_virt (x) ({ \ - __typeof__(x) __page = x; \ - void *__addr = __va(page_to_phys(__page)); \ - (void *)__tag_set((const void *)__addr, page_kasan_tag(__page));\ -})So here we're using '
__page' to avoid multiple evaluations of 'x'...
...
Quoted 16 lines
include/linux/mm.h extern int mmap_rnd_compat_bits __read_mostly; · line 123
Quoted 13 lines
include/linux/mm.h +4
-1@@ -117,7 +117,10 @@ extern int mmap_rnd_compat_bits __read_mostly;#endif #ifndef page_to_virt -#define page_to_virt (x) __va(PFN_PHYS(page_to_pfn(x))) +#define page_to_virt (x) ({ \ + void *__addr = __va(PFN_PHYS(page_to_pfn((struct page *)x))); \ + kasan_set_tag(__addr, page_kasan_tag(x)); \ +})... but in the new code you're proposing, you evaluate 'x' twice.
Quoted 3 lines
Is there a reason not to take the arm64 code as-is?
Will
I was going for less lines in this macro when I initially wrote it. But you're right, the arm64 version is better, I'll switch to it.
Thanks!
Signature · 2 lines
Kind regards Maciej Wieczór-Retman
PATCH v12 7/15 mm/execmem: Untag addresses in EXECMEM_ROX related pointer arithmetic
In reply to Maciej Wieczor-RetmanFrom: Maciej Wieczor-Retman <[email protected]>
ARCH_HAS_EXECMEM_ROX was re-enabled in x86 at Linux 6.14 release. vm_reset_perms() calculates range's start and end addresses using min() and max() functions. To do that it compares pointers but, with KASAN software tags mode enabled, some are tagged - addr variable is, while start and end variables aren't. This can cause the wrong address to be chosen and result in various errors in different places.
Reset tags in the address used as function argument in min(), max().
execmem_cache_add() adds tagged pointers to a maple tree structure, which then are incorrectly compared when walking the tree. That results in different pointers being returned later and page permission violation errors panicking the kernel.
Reset tag of the address range inserted into the maple tree inside execmem_vmalloc() which then gets propagated to execmem_cache_add().
---
Changelog v10:
- Add Mike's acked-by tag.
Changelog v7:
- Add Alexander's acked-by tag.
- Add comments on why these tag resets are needed (Alexander)
Changelog v6:
- Move back the tag reset from execmem_cache_add() to execmem_vmalloc() (Mike Rapoport)
- Rewrite the changelogs to match the code changes from v6 and v5.
Changelog v5:
- Remove the within_range() change.
- arch_kasan_reset_tag -> kasan_reset_tag.
Changelog v4:
- Add patch to the series.
mm/execmem.c | 9 ++++++++- mm/vmalloc.c | 7 ++++++- 2 files changed, 14 insertions(+), 2 deletions(-)
mm/execmem.c +8 -1
@@ -59,7 +59,14 @@ static void *execmem_vmalloc(struct execmem_range *range, size_t size,return NULL ; } -return p; +/* +* Resetting the tag here is necessary to avoid the tagged address +* ending up in the maple tree structure. There it's linear address +* can be incorrectly compared with other addresses which can result in +* a wrong address being picked down the line and for example a page +* permission violation error panicking the kernel. +*/ +return kasan_reset_tag (p); }struct vm_struct *execmem_vmap (size_t size)
mm/vmalloc.c +6 -1
@@ -3361,7 +3361,12 @@ static void vm_reset_perms(struct vm_struct *area)* the vm_unmap_aliases() flush includes the direct map. */ for (i =0 ; i < area->nr_pages; i +=1U << page_order) { -unsigned long addr = (unsigned long )page_address (area->pages[i]); +/* +* Addresses' tag needs resetting so it can be properly used in +* the min() and max() below. Otherwise the start or end values +* might be favoured. +*/ +unsigned long addr = (unsigned long )kasan_reset_tag (page_address (area->pages[i]));if (addr) {unsigned long page_size;
Signature · 1 line
2.53.0
PATCH v12 8/15 x86/mm: Use physical address comparisons in fill_p*d/pte
In reply to Maciej Wieczor-RetmanFrom: Maciej Wieczor-Retman <[email protected]>
Calculating page offset returns a pointer without a tag. When comparing the calculated offset to a tagged page pointer an error is raised because they are not equal.
Change pointer comparisons to physical address comparisons as to avoid issues with tagged pointers that pointer arithmetic would create. Open code pte_offset_kernel(), pmd_offset(), pud_offset() and p4d_offset(). Because one parameter is always zero and the rest of the function insides are enclosed inside __va(), removing that layer lowers the complexity of final assembly.
---
Changelog v11:
- Add Dave's Acked-by.
Changelog v9:
- Rename patch title so it fits the tip standards.
Changelog v7:
- Swap ternary operator outcomes in fill_p4d since the order was incorrect.
Changelog v2:
- Open code *_offset() to avoid it's internal __va().
arch/x86/mm/init_64.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-)
arch/x86/mm/init_64.c +7 -4
@@ -269,7 +269,10 @@ static p4d_t *fill_p4d(pgd_t *pgd, unsigned long vaddr)if (pgd_none (*pgd)) {p4d_t *p4d = (p4d_t *)spp_getpage ();pgd_populate (&init_mm, pgd, p4d); -if (p4d !=p4d_offset (pgd,0 )) + +if (__pa (p4d) != (pgtable_l5_enabled () ? + (unsigned long )pgd_val (*pgd) &PTE_PFN_MASK : +__pa (pgd)))printk (KERN_ERR "PAGETABLE BUG #00! %p <-> %p\n" , p4d,p4d_offset (pgd,0 )); }
@@ -281,7 +284,7 @@ static pud_t *fill_pud(p4d_t *p4d, unsigned long vaddr)if (p4d_none (*p4d)) {pud_t *pud = (pud_t *)spp_getpage ();p4d_populate (&init_mm, p4d, pud); -if (pud !=pud_offset (p4d,0 )) +if (__pa (pud) != (p4d_val (*p4d) &p4d_pfn_mask (*p4d)))printk (KERN_ERR "PAGETABLE BUG #01! %p <-> %p\n" , pud,pud_offset (p4d,0 )); }
@@ -293,7 +296,7 @@ static pmd_t *fill_pmd(pud_t *pud, unsigned long vaddr)if (pud_none (*pud)) {pmd_t *pmd = (pmd_t *)spp_getpage ();pud_populate (&init_mm, pud, pmd); -if (pmd !=pmd_offset (pud,0 )) +if (__pa (pmd) != (pud_val (*pud) &pud_pfn_mask (*pud)))printk (KERN_ERR "PAGETABLE BUG #02! %p <-> %p\n" , pmd,pmd_offset (pud,0 )); }
@@ -305,7 +308,7 @@ static pte_t *fill_pte(pmd_t *pmd, unsigned long vaddr)if (pmd_none (*pmd)) {pte_t *pte = (pte_t *)spp_getpage ();pmd_populate_kernel (&init_mm, pmd, pte); -if (pte !=pte_offset_kernel (pmd,0 )) +if (__pa (pte) != (pmd_val (*pmd) &pmd_pfn_mask (*pmd)))printk (KERN_ERR "PAGETABLE BUG #03!\n" ); }return pte_offset_kernel (pmd, vaddr);
Signature · 1 line
2.53.0
PATCH v12 9/15 x86/kasan: Initialize KASAN raw shadow memory
In reply to Maciej Wieczor-RetmanFrom: Maciej Wieczor-Retman <[email protected]>
In KASAN's generic mode the default value in shadow memory is zero. During initialization of shadow memory pages they are allocated and zeroed.
In KASAN's tag-based mode the default tag for the arm64 architecture is 0xFE which corresponds to any memory that should not be accessed. On x86 (where tags are 4-bit wide instead of 8-bit wide) that tag is 0xE so during the initializations all the bytes in shadow memory pages should be filled with it.
Use memblock_alloc_try_nid_raw() instead of memblock_alloc_try_nid() to avoid zeroing out the memory so it can be set with the KASAN invalid tag.
---
Changelog v9:
- Rename patch title so it fits the tip standards.
- Add Andrey Ryabinin's Reviewed-by tag.
Changelog v7:
- Fix flipped arguments in memset().
- Add Alexander's reviewed-by tag.
Changelog v2:
- Remove dense mode references, use memset() instead of kasan_poison().
arch/x86/mm/kasan_init_64.c | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-)
arch/x86/mm/kasan_init_64.c +16 -3
@@ -34,6 +34,18 @@ static __init void *early_alloc(size_t size, int nid, bool should_panic)return ptr; } +static __init void *early_raw_alloc (size_t size,int nid,bool should_panic) +{ +void *ptr =memblock_alloc_try_nid_raw (size, size, +__pa (MAX_DMA_ADDRESS ),MEMBLOCK_ALLOC_ACCESSIBLE , nid); + +if (!ptr && should_panic) +panic ("%pS: Failed to allocate page, nid=%d from=%lx\n" , + (void *)_RET_IP_, nid,__pa (MAX_DMA_ADDRESS )); + +return ptr; +} +static void __init kasan_populate_pmd (pmd_t *pmd,unsigned long addr,unsigned long end,int nid) {
@@ -63,8 +75,9 @@ static void __init kasan_populate_pmd(pmd_t *pmd, unsigned long addr,if (!pte_none (*pte))continue ; - p =early_alloc (PAGE_SIZE , nid, true); - entry =pfn_pte (PFN_DOWN (__pa (p)),PAGE_KERNEL ); + p =early_raw_alloc (PAGE_SIZE , nid, true); +memset (p,KASAN_SHADOW_INIT ,PAGE_SIZE ); + entry =pfn_pte (PFN_DOWN (__pa_nodebug (p)),PAGE_KERNEL );set_pte_at (&init_mm, addr, pte, entry); }while (pte++, addr +=PAGE_SIZE , addr != end); }
@@ -436,7 +449,7 @@ void __init kasan_init(void)* it may contain some garbage. Now we can clear and write protect it, * since after the TLB flush no one should write to it. */ -memset (kasan_early_shadow_page,0 ,PAGE_SIZE ); +memset (kasan_early_shadow_page,KASAN_SHADOW_INIT ,PAGE_SIZE );for (i =0 ; i <PTRS_PER_PTE ; i++) {pte_t pte;pgprot_t prot;
Signature · 1 line
2.53.0
PATCH v12 10/15 x86/mm: Reset tags in a canonical address helper call
In reply to Maciej Wieczor-RetmanFrom: Maciej Wieczor-Retman <[email protected]>
With KASAN software tag-based mode arbitrary kernel pointers can be tagged. __is_canonical_address() helper can cause issues when met with tagged pointers that expect the loosened canonicality checks. The function itself shouldn't be made LAM-aware since for example in KVM, where it's used extensively - it's not practical to deal with differences between host and guest which might want a different LAM state. Also by the time __is_canonical_address() is invoked KVM has already done any necessary LAM unmasking.
Reset the address' tag early in copy_from_kernel_nofault_allowed() so pointer arithmetic checks before a __is_canonical_address() call can work properly.
---
Changelog v11:
- Reset tag earlier in copy_from_kernel_nofault_allowed() so the is_vsyscall_vaddr() can properly check tagged pointers.
- Redo the patch message.
Changelog v9:
- Redo the patch to not break KVM.
- Remove Alexander's acked-by tag.
Changelog v7:
- Add Alexander's acked-by tag.
- Add parentheses around vaddr_bits as suggested by checkpatch.
- Apply the bitmasks to the __canonical_address() function which is used in kvm code.
Changelog v6:
- Use bitmasks to check both kernel and userspace addresses in the __is_canonical_address() (Dave Hansen and Samuel Holland).
Changelog v4:
- Add patch to the series.
arch/x86/mm/maccess.c | 1 + 1 file changed, 1 insertion(+)
arch/x86/mm/maccess.c +1 -0
@@ -9,6 +9,7 @@bool copy_from_kernel_nofault_allowed (const void *unsafe_src,size_t size) {unsigned long vaddr = (unsigned long )unsafe_src; + vaddr =__tag_reset (vaddr);/* * Do not allow userspace addresses. This disallows
Signature · 1 line
2.53.0
PATCH v12 11/15 x86/mm: Initialize LAM_SUP
In reply to Maciej Wieczor-RetmanFrom: Maciej Wieczor-Retman <[email protected]>
To make use of KASAN's tag based mode on x86, Linear Address Masking (LAM) needs to be enabled. To do a bit in CR4 has to be set.
When launching secondary CPUs the LAM CR4 bit needs to be added to a mask in head_64.S. Bits that are not part of that mask are cleared when secondary CPUs are getting enabled by the primary one.
---
Changelog v11:
- Redo the patch message according to Dave's suggestions.
Changelog v9:
- Rename patch title so it fits the tip standards.
Changelog v7:
- Add Alexander's acked-by tag.
Changelog v6:
- boot_cpu_has() -> cpu_feature_enabled()
arch/x86/kernel/head_64.S | 3 +++ arch/x86/mm/init.c | 3 +++ 2 files changed, 6 insertions(+)
arch/x86/kernel/head_64.S +3 -0
@@ -209,6 +209,9 @@ SYM_INNER_LABEL(common_startup_64, SYM_L_LOCAL) * there will be no global TLB entries after the execution." */ movl $(X86_CR4_PAE | X86_CR4_LA57), %edx +#ifdef CONFIG_ADDRESS_MASKING + orl $X86_CR4_LAM_SUP, %edx +#endif #ifdef CONFIG_X86_MCE /* * Preserve CR4.MCE if the kernel will enable #MC support.
arch/x86/mm/init.c +3 -0
@@ -763,6 +763,9 @@ void __init init_mem_mapping(void)probe_page_size_mask ();setup_pcid (); +if (cpu_feature_enabled (X86_FEATURE_LAM ) &&IS_ENABLED (CONFIG_KASAN_SW_TAGS )) +cr4_set_bits_and_update_boot (X86_CR4_LAM_SUP ); +#ifdef CONFIG_X86_64 end = max_pfn <<PAGE_SHIFT ;#else
Signature · 1 line
2.53.0
PATCH v12 12/15 x86: Increase minimal SLAB alignment for KASAN
In reply to Maciej Wieczor-RetmanFrom: Maciej Wieczor-Retman <[email protected]>
8 byte minimal SLAB alignment interferes with KASAN's granularity of 16 bytes. It causes a lot of out-of-bounds errors for unaligned 8 byte allocations.
Compared to a kernel with KASAN disabled, the memory footprint increases because all kmalloc-8 allocations now are realized as kmalloc-16, which has twice the object size. But more meaningfully, when compared to a kernel with generic KASAN enabled, there is no difference. Because of redzones in generic KASAN, kmalloc-8' and kmalloc-16' object size is the same (48 bytes). So changing the minimal SLAB alignment of the tag-based mode doesn't have any negative impact when compared to the other software KASAN mode.
Adjust x86 minimal SLAB alignment to match KASAN granularity size.
---
Changelog v9:
- Rename patch title so it fits the tip standards.
Changelog v6:
- Add Andrey's Reviewed-by tag.
Changelog v4:
- Extend the patch message with some more context and impact information.
Changelog v3:
- Fix typo in patch message 4 -> 16.
- Change define location to arch/x86/include/asm/cache.c.
arch/x86/include/asm/cache.h | 4 ++++ 1 file changed, 4 insertions(+)
arch/x86/include/asm/cache.h +4 -0
@@ -21,4 +21,8 @@#endif #endif +#ifdef CONFIG_KASAN_SW_TAGS +#define ARCH_SLAB_MINALIGN (1ULL << KASAN_SHADOW_SCALE_SHIFT) +#endif +#endif /* _ASM_X86_CACHE_H */
Signature · 1 line
2.53.0
PATCH v12 13/15 x86/kasan: Use a logical bit shift for kasan_mem_to_shadow
In reply to Maciej Wieczor-RetmanFrom: Maciej Wieczor-Retman <[email protected]>
The tag-based KASAN adopts an arithemitc bit shift to convert a memory address to a shadow memory address. While it makes a lot of sense on arm64, it doesn't work well for all cases on x86 - either the non-canonical hook becomes quite complex for different paging levels, or the inline mode would need a lot more adjustments. Thus the best working scheme is the logical bit shift and non-canonical shadow offset that x86 uses for generic KASAN, of course adjusted for the increased granularity from 8 to 16 bytes.
Add an arch specific implementation of kasan_mem_to_shadow() that uses the logical bit shift.
---
Changelog v11:
- Remove arch_kasan_non_canonical_hook() since an arch independent version was added to the first patch in the series.
Changelog v9:
- Rename patch title so it fits the tip standards.
- Take out the x86 part from mm/kasan/report.c and put it in the arch specific function. Adjust the patch message.
Changelog v7:
- Redo the patch message and add a comment to __kasan_mem_to_shadow() to provide better explanation on why x86 doesn't work well with the arithemitc bit shift approach (Marco).
Changelog v4:
- Add this patch to the series.
arch/x86/include/asm/kasan.h | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
arch/x86/include/asm/kasan.h +15 -0
@@ -31,6 +31,21 @@#include <linux/bits.h> #ifdef CONFIG_KASAN_SW_TAGS +/* +* Using the non-arch specific implementation of __kasan_mem_to_shadow() with a +* arithmetic bit shift can cause high code complexity in KASAN's non-canonical +* hook for x86 or might not work for some paging level and KASAN mode +* combinations. The inline mode compiler support could also suffer from higher +* complexity for no specific benefit. Therefore the generic mode's logical +* shift implementation is used. +*/ +static inline void *__kasan_mem_to_shadow (const void *addr) +{ +return (void *)((unsigned long )addr >>KASAN_SHADOW_SCALE_SHIFT ) + +KASAN_SHADOW_OFFSET ; +} +#define kasan_mem_to_shadow (addr) __kasan_mem_to_shadow(addr) +#define __tag_shifted (tag) FIELD_PREP(GENMASK_ULL(60, 57), tag)#define __tag_reset (addr) (sign_extend64((u64)(addr), 56))#define __tag_get (addr) ((u8)FIELD_GET(GENMASK_ULL(60, 57), (u64)addr))
Signature · 1 line
2.53.0
PATCH v12 14/15 x86/kasan: Make software tag-based kasan available
In reply to Maciej Wieczor-RetmanFrom: Maciej Wieczor-Retman <[email protected]>
Make CONFIG_KASAN_SW_TAGS available for x86 machines if they have ADDRESS_MASKING enabled (LAM) as that works similarly to Top-Byte Ignore (TBI) that allows the software tag-based mode on arm64 platform.
The value for sw_tags KASAN_SHADOW_OFFSET was calculated by rearranging the formulas for KASAN_SHADOW_START and KASAN_SHADOW_END from arch/x86/include/asm/kasan.h - the only prerequisites being KASAN_SHADOW_SCALE_SHIFT of 4, and KASAN_SHADOW_END equal to the one from KASAN generic mode.
Set scale macro based on KASAN mode: in software tag-based mode 16 bytes of memory map to one shadow byte and 8 in generic mode.
Disable CONFIG_KASAN_INLINE and CONFIG_KASAN_STACK when CONFIG_KASAN_SW_TAGS is enabled on x86 until the appropriate compiler support is available.
Lock software tag KASAN behind CC_IS_CLANG due to lack of proper support by gcc resulting in kernel booting issues.
---
Changelog v12:
- Put CC_IS_CLANG and ADDRESS_MASKING into one Kconfig option that will control whether KASAN sw-tags is available.
Changelog v11:
- Split off the documentation changes.
- Rewrite the Kconfig.kasan entry for sw_tags.
Changelog v10:
- Update Documentation/dev-tools/kasan.rst with x86 related informations.
Changelog v9:
- Lock HAVE_ARCH_KASAN_HAS_SW_TAGS behind CC_IS_CLANG due to lack of support from gcc.
- Remove pr_info() from KASAN initialization since it's now done by the generic init helper.
- Add paragraph to the mm.rst to explain the mutual exclusive nature of the KASAN address ranges.
- Use cpu_feature_enabled() instead of boot_cpu_has() in kasan_init_64.c.
Changelog v7:
- Add a paragraph to the patch message explaining how the various addresses and the KASAN_SHADOW_OFFSET were calculated.
Changelog v6:
- Don't enable KASAN if LAM is not supported.
- Move kasan_init_tags() to kasan_init_64.c to not clutter the setup.c file.
- Move the #ifdef for the KASAN scale shift here.
- Move the gdb code to patch "Use arithmetic shift for shadow computation".
- Return "depends on KASAN" line to Kconfig.
- Add the defer kasan config option so KASAN can be disabled on hardware that doesn't have LAM.
Changelog v4:
- Add x86 specific kasan_mem_to_shadow().
- Revert x86 to the older unsigned KASAN_SHADOW_OFFSET. Do the same to KASAN_SHADOW_START/END.
- Modify scripts/gdb/linux/kasan.py to keep x86 using unsigned offset.
- Disable inline and stack support when software tags are enabled on x86.
Changelog v3:
- Remove runtime_const from previous patch and merge the rest here.
- Move scale shift definition back to header file.
- Add new kasan offset for software tag based mode.
- Fix patch message typo 32 -> 16, and 16 -> 8.
- Update lib/Kconfig.kasan with x86 now having software tag-based support.
Changelog v2:
- Remove KASAN dense code.
arch/x86/Kconfig | 9 +++++++++ arch/x86/boot/compressed/misc.h | 1 + arch/x86/include/asm/kasan.h | 5 +++++ arch/x86/mm/kasan_init_64.c | 5 +++++ lib/Kconfig.kasan | 4 +++- 5 files changed, 23 insertions(+), 1 deletion(-)
arch/x86/Kconfig +9 -0
@@ -67,6 +67,7 @@ config X86 select ARCH_CLOCKSOURCE_INIT select ARCH_CONFIGURES_CPU_MITIGATIONS select ARCH_CORRECT_STACKTRACE_ON_KRETPROBE + select ARCH_DISABLE_KASAN_INLINE if X86_64 && KASAN_SW_TAGS select ARCH_ENABLE_HUGEPAGE_MIGRATION if X86_64 && HUGETLB_PAGE && MIGRATION select ARCH_ENABLE_MEMORY_HOTPLUG if X86_64 select ARCH_ENABLE_SPLIT_PMD_PTLOCK if (PGTABLE_LEVELS > 2) && (X86_64 || X86_PAE)
@@ -195,6 +196,8 @@ config X86 select HAVE_ARCH_JUMP_LABEL_RELATIVE select HAVE_ARCH_KASAN if X86_64 select HAVE_ARCH_KASAN_VMALLOC if X86_64 + select HAVE_ARCH_KASAN_SW_TAGS if X86_KASAN_SW_TAGS + select ARCH_NEEDS_DEFER_KASAN if KASAN_SW_TAGS select HAVE_ARCH_KFENCE select HAVE_ARCH_KMSAN if X86_64 select HAVE_ARCH_KGDB
@@ -409,8 +412,14 @@ config AUDIT_ARCH config KASAN_SHADOW_OFFSET hex depends on KASAN + default 0xeffffc0000000000 if KASAN_SW_TAGS default 0xdffffc0000000000 +config X86_KASAN_SW_TAGS + def_bool y + depends on CC_IS_CLANG + depends on ADDRESS_MASKING + config HAVE_INTEL_TXT def_bool y depends on INTEL_IOMMU && ACPI
arch/x86/boot/compressed/misc.h +1 -0
@@ -14,6 +14,7 @@#undef CONFIG_ARCH_HAS_LAZY_MMU_MODE#undef CONFIG_KASAN#undef CONFIG_KASAN_GENERIC +#undef CONFIG_KASAN_SW_TAGS#define __NO_FORTIFY
arch/x86/include/asm/kasan.h +5 -0
@@ -6,7 +6,12 @@#include <linux/kasan-tags.h> #include <linux/types.h> #define KASAN_SHADOW_OFFSET _AC(CONFIG_KASAN_SHADOW_OFFSET, UL) + +#ifdef CONFIG_KASAN_SW_TAGS +#define KASAN_SHADOW_SCALE_SHIFT 4 +#else #define KASAN_SHADOW_SCALE_SHIFT 3 +#endif /* * Compiler uses shadow offset assuming that addresses start
arch/x86/mm/kasan_init_64.c +5 -0
@@ -465,4 +465,9 @@ void __init kasan_init(void) init_task.kasan_depth =0 ;kasan_init_generic (); + +if (cpu_feature_enabled (X86_FEATURE_LAM )) +kasan_init_sw_tags (); +else +pr_info ("KernelAddressSanitizer not initialized (sw-tags): hardware doesn't support LAM\n" ); }
lib/Kconfig.kasan +3 -1
@@ -112,7 +112,9 @@ config KASAN_SW_TAGS Requires GCC 11+ or Clang. - Supported only on arm64 CPUs and relies on Top Byte Ignore. + Supported on: + arm64: CPUs with Top Byte Ignore + x86: CPUs with Linear Address Masking. Consumes about 1/16th of available memory at kernel start and add an overhead of ~20% for dynamic allocations.
Signature · 1 line
2.53.0
PATCH v12 15/15 docs: Update KASAN and x86 memory map documentations
In reply to Maciej Wieczor-RetmanFrom: Maciej Wieczor-Retman <[email protected]>
Update the documentation concerning changes to x86's memory address space and new architecture addition to KASAN's software tag-based mode.
Redo paragraphs in KASAN's documentation on hardware and software implementation details to allow better extensibility.
---
Changelog v11:
- Split off the documentation portion of v10's patch 13.
- Apply Dave's suggestions to reformat the footer explaining alternate ranges for KASAN shadow memory, put arch hardware implementation in a separate paragraph and make a table to hold various implementation details.
Documentation/arch/x86/x86_64/mm.rst | 21 +++++++++- Documentation/dev-tools/kasan.rst | 61 ++++++++++++++++++++-------- 2 files changed, 62 insertions(+), 20 deletions(-)
Documentation/arch/x86/x86_64/mm.rst +19 -2
@@ -60,7 +60,7 @@ Complete virtual memory map with 4-level page tables ffffe90000000000 | -23 TB | ffffe9ffffffffff | 1 TB | ... unused hole ffffea0000000000 | -22 TB | ffffeaffffffffff | 1 TB | virtual memory map (vmemmap_base) ffffeb0000000000 | -21 TB | ffffebffffffffff | 1 TB | ... unused hole - ffffec0000000000 | -20 TB | fffffbffffffffff | 16 TB | KASAN shadow memory + ffffec0000000000 | -20 TB | fffffbffffffffff | 16 TB | KASAN shadow memory[1] __________________|____________|__________________|_________|____________________________________________________________ | | Identical layout to the 56-bit one from here on:
@@ -130,7 +130,7 @@ Complete virtual memory map with 5-level page tables ffd2000000000000 | -11.5 PB | ffd3ffffffffffff | 0.5 PB | ... unused hole ffd4000000000000 | -11 PB | ffd5ffffffffffff | 0.5 PB | virtual memory map (vmemmap_base) ffd6000000000000 | -10.5 PB | ffdeffffffffffff | 2.25 PB | ... unused hole - ffdf000000000000 | -8.25 PB | fffffbffffffffff | ~8 PB | KASAN shadow memory + ffdf000000000000 | -8.25 PB | fffffbffffffffff | ~8 PB | KASAN shadow memory[1] __________________|____________|__________________|_________|____________________________________________________________ | | Identical layout to the 47-bit one from here on:
@@ -178,3 +178,20 @@ correct as KASAN disables KASLR. For both 4- and 5-level layouts, the KSTACK_ERASE_POISON value in the last 2MB hole: ffffffffffff4111 + +1. The range is different based on what KASAN mode is used and what paging level + is used: + +:: + + ============================================================================================================ + Start addr | Offset | End addr | Size | VM area description + ============================================================================================================ + | | | | 4-level paging: + ffffec0000000000 | -20 TB | fffffbffffffffff | 16 TB | KASAN shadow memory (generic mode) + fffff40000000000 | -8 TB | fffffbffffffffff | 8 TB | KASAN shadow memory (software tag-based mode) + __________________|____________|__________________|_________|_______________________________________________ + | | | | 5-level paging: + ffdf000000000000 | -8.25 PB | fffffbffffffffff | ~8 PB | KASAN shadow memory (generic mode) + ffeffc0000000000 | -6 PB | fffffbffffffffff | 4 PB | KASAN shadow memory (software tag-based mode) + __________________|____________|__________________|_________|_______________________________________________
Documentation/dev-tools/kasan.rst +43 -18
79 lines not on this page · raw message
Signature · 1 line
2.53.0