Skip to contentSkip to conversation

slab: support for compiler-assisted type-based slab cache partitioning

PATCH In review Marco Elver 7 participants 21 messages May 11 – Sep 25

Subsystems (9)
lore
Share & tools
lore

Marco Elver

author maintainer
#0 lore raw

PATCH v4 1/3 slab: support for compiler-assisted type-based slab cache partitioning

Rework the general infrastructure around RANDOM_KMALLOC_CACHES into more flexible KMALLOC_PARTITION_CACHES, with the former being a partitioning mode of the latter.

Introduce a new mode, KMALLOC_PARTITION_TYPED, which leverages a feature available in Clang 22 and later, called "allocation tokens" via __builtin_infer_alloc_token() [1]. Unlike KMALLOC_PARTITION_RANDOM (formerly RANDOM_KMALLOC_CACHES), this mode deterministically assigns a slab cache to an allocation of type T, regardless of allocation site.

The builtin __builtin_infer_alloc_token(<malloc-args>, ...) instructs the compiler to infer an allocation type from arguments commonly passed to memory-allocating functions and returns a type-derived token ID. The implementation passes kmalloc-args to the builtin: the compiler performs best-effort type inference, and then recognizes common patterns such as kmalloc(sizeof(T), ...), kmalloc(sizeof(T) * n, ...), but also (T *)kmalloc(...). Where the compiler fails to infer a type the fallback token (default: 0) is chosen.

Note: kmalloc_obj(..) APIs fix the pattern how size and result type are expressed, and therefore ensures there's not much drift in which patterns the compiler needs to recognize. Specifically, kmalloc_obj() and friends expand to (TYPE *)KMALLOC(__obj_size, GFP), which the compiler recognizes via the cast to TYPE*.

Clang's default token ID calculation is described as [1]:

typehashpointersplit: This mode assigns a token ID based on the hash of the allocated type's name, where the top half ID-space is reserved for types that contain pointers and the bottom half for types that do not contain pointers.

Separating pointer-containing objects from pointerless objects and data allocations can help mitigate certain classes of memory corruption exploits [2]: attackers who gains a buffer overflow on a primitive buffer cannot use it to directly corrupt pointers or other critical metadata in an object residing in a different, isolated heap region.

It is important to note that heap isolation strategies offer a best-effort approach, and do not provide a 100% security guarantee, albeit achievable at relatively low performance cost. Note that this also does not prevent cross-cache attacks: while waiting for future features like SLAB_VIRTUAL [3] to provide physical page isolation, this feature should be deployed alongside SHUFFLE_PAGE_ALLOCATOR and init_on_free=1 to mitigate cross-cache attacks and page-reuse attacks as much as possible today.

With all that, my kernel (x86 defconfig) shows me a histogram of slab cache object distribution per /proc/slabinfo (after boot):

<slab cache> <objs> <hist>

  kmalloc-part-15    1465  ++++++++++++++
  kmalloc-part-14    2988  +++++++++++++++++++++++++++++
  kmalloc-part-13    1656  ++++++++++++++++
  kmalloc-part-12    1045  ++++++++++
  kmalloc-part-11    1697  ++++++++++++++++
  kmalloc-part-10    1489  ++++++++++++++
  kmalloc-part-09     965  +++++++++
  kmalloc-part-08     710  +++++++
  kmalloc-part-07     100  +
  kmalloc-part-06     217  ++
  kmalloc-part-05     105  +
  kmalloc-part-04    4047  ++++++++++++++++++++++++++++++++++++++++
  kmalloc-part-03     183  +
  kmalloc-part-02     283  ++
  kmalloc-part-01     316  +++
  kmalloc            1422  ++++++++++++++

The above /proc/slabinfo snapshot shows me there are 6673 allocated objects (slabs 00 - 07) that the compiler claims contain no pointers or it was unable to infer the type of, and 12015 objects that contain pointers (slabs 08 - 15). On a whole, this looks relatively sane.

Additionally, when I compile my kernel with -Rpass=alloc-token, which provides diagnostics where (after dead-code elimination) type inference failed, I see 186 allocation sites where the compiler failed to identify a type (down from 966 when I sent the RFC [4]). Some initial review confirms these are mostly variable sized buffers, but also include structs with trailing flexible length arrays.

---
v3: https://lore.kernel.org/all/[email protected]/
* Introduce DECL_TOKEN_PARAMS / PASS_TOKEN_PARAMS (suggested-by Harry).
* Rename {RANDOM,TYPED}_KMALLOC_CACHES to KMALLOC_PARTITION_{RANDOM,TYPED}, so it's more easily searchable and consistent with the top-level name with the variant at the end of the CONFIG phrase (reported-by Kees).
* Make KMALLOC_PARTITION_TYPED default if available (suggested-by Kees).
* Add RANDOM_KMALLOC_CACHES transitional option (suggested-by Kees).
* Add CC_HAS_ALLOC_TOKEN and use it (reported-by Kees).

v2: https://lore.kernel.org/all/[email protected]/
* Avoid empty function argument if !KMALLOC_PARTITION_CACHES (co-developed-by Harry). While Clang does optimize out the empty struct argument (and generated code is identical to before if KMALLOC_PARTITION_CACHES is disabled), GCC doesn't do so. So we need to fully remove the argument if not actually required.
* Cover krealloc() which was missed before, resulting in ~100 additional objects in the pointer-containing caches in above histogram.
* Unify kmalloc_token_t definition.
* Expand Kconfig help text.

v1: https://lore.kernel.org/all/[email protected]/
* Rebase and switch to builtin name that was released in Clang 22.
* Keep RANDOM_KMALLOC_CACHES the default.

RFC: https://lore.kernel.org/all/[email protected]/

---
 Makefile                        |   5 ++
 include/linux/percpu.h          |   2 +-
 include/linux/slab.h            | 136 +++++++++++++++++++++-----------
 init/Kconfig                    |   3 +
 kernel/configs/hardening.config |   2 +-
 mm/Kconfig                      |  73 ++++++++++++++---
 mm/kfence/kfence_test.c         |   4 +-
 mm/slab.h                       |   4 +-
 mm/slab_common.c                |  52 ++++++------
 mm/slub.c                       |  54 +++++++------
 10 files changed, 220 insertions(+), 115 deletions(-)
Makefile +5 -0
index 9f88dcaae382..13d804391949 100644
@@ -991,6 +991,11 @@ KBUILD_CFLAGS	+= $(CC_AUTO_VAR_INIT_ZERO_ENABLER)
 endif
 endif
 
+ifdef CONFIG_KMALLOC_PARTITION_TYPED
+# KMALLOC_PARTITION_CACHES_NR + 1
+KBUILD_CFLAGS	+= -falloc-token-max=16
+endif
+
 ifdef CONFIG_CC_IS_CLANG
 ifdef CONFIG_CC_HAS_COUNTED_BY_PTR
 KBUILD_CFLAGS	+= -fexperimental-late-parse-attributes
include/linux/percpu.h +1 -1
index 85bf8dd9f087..bdb721dac0e3 100644
@@ -36,7 +36,7 @@
 #define PCPU_BITMAP_BLOCK_BITS		(PCPU_BITMAP_BLOCK_SIZE >>	\
 					 PCPU_MIN_ALLOC_SHIFT)
 
-#ifdef CONFIG_RANDOM_KMALLOC_CACHES
+#ifdef CONFIG_KMALLOC_PARTITION_CACHES
 # if defined(CONFIG_LOCKDEP) && !defined(CONFIG_PAGE_SIZE_4KB)
 # define PERCPU_DYNAMIC_SIZE_SHIFT      13
 # else
include/linux/slab.h +88 -48

307 lines not on this page · raw message

init/Kconfig +3 -0
index 2937c4d308ae..dba97bc8e2ce 100644
@@ -170,6 +170,9 @@ config CC_HAS_BROKEN_COUNTED_BY_REF
 	# https://github.com/llvm/llvm-project/issues/182575
 	default y if CC_IS_CLANG && CLANG_VERSION < 220100
 
+config CC_HAS_ALLOC_TOKEN
+	def_bool $(cc-option,-falloc-token-max=123)
+
 config CC_HAS_MULTIDIMENSIONAL_NONSTRING
 	def_bool $(success,echo 'char tag[][4] __attribute__((__nonstring__)) = { };' | $(CC) $(CLANG_FLAGS) -x c - -c -o /dev/null -Werror)
 
kernel/configs/hardening.config +1 -1
index 7c3924614e01..26831a2a5739 100644
@@ -22,7 +22,7 @@ CONFIG_SLAB_FREELIST_RANDOM=y
 CONFIG_SLAB_FREELIST_HARDENED=y
 CONFIG_SLAB_BUCKETS=y
 CONFIG_SHUFFLE_PAGE_ALLOCATOR=y
-CONFIG_RANDOM_KMALLOC_CACHES=y
+CONFIG_KMALLOC_PARTITION_CACHES=y
 
 # Sanity check userspace page table mappings.
 CONFIG_PAGE_TABLE_CHECK=y
mm/Kconfig +63 -10

85 lines not on this page · raw message

mm/kfence/kfence_test.c +2 -2
index 5725a367246d..8807ea8ed0d3 100644
@@ -214,7 +214,7 @@ static void test_cache_destroy(void)
 static inline size_t kmalloc_cache_alignment(size_t size)
 {
 	/* just to get ->align so no need to pass in the real caller */
-	enum kmalloc_cache_type type = kmalloc_type(GFP_KERNEL, 0);
+	enum kmalloc_cache_type type = kmalloc_type(GFP_KERNEL, __kmalloc_token(0));
 	return kmalloc_caches[type][__kmalloc_index(size, false)]->align;
 }
 
@@ -285,7 +285,7 @@ static void *test_alloc(struct kunit *test, size_t size, gfp_t gfp, enum allocat
 
 		if (is_kfence_address(alloc)) {
 			struct slab *slab = virt_to_slab(alloc);
-			enum kmalloc_cache_type type = kmalloc_type(GFP_KERNEL, _RET_IP_);
+			enum kmalloc_cache_type type = kmalloc_type(GFP_KERNEL, __kmalloc_token(size));
 			struct kmem_cache *s = test_cache ?:
 					kmalloc_caches[type][__kmalloc_index(size, false)];
 
mm/slab.h +2 -2
index bf2f87acf5e3..1bf9c3021ae3 100644
@@ -362,12 +362,12 @@ static inline unsigned int size_index_elem(unsigned int bytes)
  * KMALLOC_MAX_CACHE_SIZE and the caller must check that.
  */
 static inline struct kmem_cache *
-kmalloc_slab(size_t size, kmem_buckets *b, gfp_t flags, unsigned long caller)
+kmalloc_slab(size_t size, kmem_buckets *b, gfp_t flags, kmalloc_token_t token)
 {
 	unsigned int index;
 
 	if (!b)
-		b = &kmalloc_caches[kmalloc_type(flags, caller)];
+		b = &kmalloc_caches[kmalloc_type(flags, token)];
 	if (size <= 192)
 		index = kmalloc_size_index[size_index_elem(size)];
 	else
mm/slab_common.c +26 -26

88 lines not on this page · raw message

mm/slub.c +29 -25

167 lines not on this page · raw message

Signature · 1 line
2.54.0.563.g4f69b47b94-goog
author maintainer
#1 lore raw

PATCH v4 2/3 slab: improve KMALLOC_PARTITION_RANDOM randomness

When using CONFIG_KMALLOC_PARTITION_RANDOM, _RET_IP_ was previously used to identify the allocation site. _RET_IP_, however, evaluates to the caller's parent's instruction pointer rather than the actual allocation site; this would lead to collisions where a function performs multiple allocations.

With the generalization to kmalloc_token_t, we now generate the token at the outermost macro, and using _THIS_IP_ would fix this for all cases.

Unfortunately, the generic implementation of _THIS_IP_ relies on taking the address of a local label, which is considered broken by both GCC [1] and Clang [2] because label addresses are only expected to be used with computed gotos. While the generic version more or less works today, it is known to be brittle. For example, Clang -O2 always returns 1 when this function is inlined:

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

To provide a reliable unique identifier without breaking architectures relying on the generic _THIS_IP_, introduce _CODE_LOCATION_: it resolves to _THIS_IP_ where architectures provide a safe implementation, and falls back to a zero-cost static marker where _THIS_IP_ is broken.

---
v4:
* New patch.

---
 include/linux/instruction_pointer.h | 24 ++++++++++++++++++++++++
 include/linux/slab.h                |  2 +-
 2 files changed, 25 insertions(+), 1 deletion(-)
include/linux/instruction_pointer.h +24 -0
index aa0b3ffea935..ea5bc756bd99 100644
@@ -8,6 +8,30 @@
 
 #ifndef _THIS_IP_
 #define _THIS_IP_  ({ __label__ __here; __here: (unsigned long)&&__here; })
+/*
+ * The current generic definition of _THIS_IP_ is considered broken by GCC [1]
+ * and Clang [2]. In particular, the address of a label is only expected to be
+ * used with a computed goto.
+ *
+ *   [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120071
+ *   [2] https://github.com/llvm/llvm-project/issues/138272
+ *
+ * Mark it as broken, so that appropriate fallback options can be implemented
+ * for architectures that do not define their own _THIS_IP_.
+ */
+#define HAS_BROKEN_THIS_IP
+#endif
+
+/*
+ * _CODE_LOCATION_ provides a unique identifier for the current code location.
+ * When _THIS_IP_ is broken (generic version), we fall back to a static marker
+ * which guarantees uniqueness and resolves to a constant address at link time,
+ * avoiding runtime overhead and compiler optimizations breaking it.
+ */
+#ifdef HAS_BROKEN_THIS_IP
+#define _CODE_LOCATION_ ({ static const char __here; (unsigned long)&__here; })
+#else
+#define _CODE_LOCATION_ _THIS_IP_
 #endif
 
 #endif /* _LINUX_INSTRUCTION_POINTER_H */
include/linux/slab.h +1 -1
index c232f8a10af6..efab6b2ccf21 100644
@@ -503,7 +503,7 @@ int kmem_cache_shrink(struct kmem_cache *s);
 typedef struct { unsigned long v; } kmalloc_token_t;
 #ifdef CONFIG_KMALLOC_PARTITION_RANDOM
 extern unsigned long random_kmalloc_seed;
-#define __kmalloc_token(...) ((kmalloc_token_t){ .v = _RET_IP_ })
+#define __kmalloc_token(...) ((kmalloc_token_t){ .v = _CODE_LOCATION_ })
 #elif defined(CONFIG_KMALLOC_PARTITION_TYPED)
 #define __kmalloc_token(...) ((kmalloc_token_t){ .v = __builtin_infer_alloc_token(__VA_ARGS__) })
 #endif
Signature · 1 line
2.54.0.563.g4f69b47b94-goog
maintainer Reviewed-by on v4 2/3
#2 lore raw

Re: [PATCH v4 2/3] slab: improve KMALLOC_PARTITION_RANDOM randomness

Quoted 24 lines · Marco Elver

When using CONFIG_KMALLOC_PARTITION_RANDOM, _RET_IP_ was previously used to identify the allocation site. _RET_IP_, however, evaluates to the caller's parent's instruction pointer rather than the actual allocation site; this would lead to collisions where a function performs multiple allocations.

With the generalization to kmalloc_token_t, we now generate the token at the outermost macro, and using _THIS_IP_ would fix this for all cases.

Unfortunately, the generic implementation of _THIS_IP_ relies on taking the address of a local label, which is considered broken by both GCC [1] and Clang [2] because label addresses are only expected to be used with computed gotos. While the generic version more or less works today, it is known to be brittle. For example, Clang -O2 always returns 1 when this function is inlined:

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

To provide a reliable unique identifier without breaking architectures relying on the generic _THIS_IP_, introduce _CODE_LOCATION_: it resolves to _THIS_IP_ where architectures provide a safe implementation, and falls back to a zero-cost static marker where _THIS_IP_ is broken.

Quoted 4 lines

---

Looks good to me,

with one suggestion below.

Quoted 25 lines
---
 include/linux/instruction_pointer.h | 24 ++++++++++++++++++++++++
 include/linux/slab.h                |  2 +-
 2 files changed, 25 insertions(+), 1 deletion(-)
include/linux/instruction_pointer.h +12 -0
index aa0b3ffea935..ea5bc756bd99 100644
@@ -8,6 +8,30 @@
 
 #ifndef _THIS_IP_
 #define _THIS_IP_  ({ __label__ __here; __here: (unsigned long)&&__here; })
+/*
+ * The current generic definition of _THIS_IP_ is considered broken by GCC [1]
+ * and Clang [2]. In particular, the address of a label is only expected to be
+ * used with a computed goto.
+ *
+ *   [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120071
+ *   [2] https://github.com/llvm/llvm-project/issues/138272
+ *
+ * Mark it as broken, so that appropriate fallback options can be implemented
+ * for architectures that do not define their own _THIS_IP_.
+ */
+#define HAS_BROKEN_THIS_IP

include/linux/instruction_pointer.h line 32

Quoted 10 lines
include/linux/instruction_pointer.h +10 -0
+#endif
+
+/*
+ * _CODE_LOCATION_ provides a unique identifier for the current code location.
+ * When _THIS_IP_ is broken (generic version), we fall back to a static marker
+ * which guarantees uniqueness and resolves to a constant address at link time,
+ * avoiding runtime overhead and compiler optimizations breaking it.
+ */
+#ifdef HAS_BROKEN_THIS_IP
+#define _CODE_LOCATION_ ({ static const char __here; (unsigned long)&__here; })

nit: perhaps it can be __initdata to free these after boot? ... if we want to save actual memory allocated rather than the vmlinux size.

apparently ".init.bss" is a not thing :(

Quoted 3 lines
include/linux/instruction_pointer.h +2 -0
+#else
+#define _CODE_LOCATION_ _THIS_IP_
 #endif
Signature · 2 lines
Cheers,
Harry / Hyeonggon
author maintainer
#3 lore raw

Re: [PATCH v4 2/3] slab: improve KMALLOC_PARTITION_RANDOM randomness

Quoted 26 lines · Harry Yoo (Oracle)' via kasan-dev
Quoted 24 lines · Marco Elver

When using CONFIG_KMALLOC_PARTITION_RANDOM, _RET_IP_ was previously used to identify the allocation site. _RET_IP_, however, evaluates to the caller's parent's instruction pointer rather than the actual allocation site; this would lead to collisions where a function performs multiple allocations.

With the generalization to kmalloc_token_t, we now generate the token at the outermost macro, and using _THIS_IP_ would fix this for all cases.

Unfortunately, the generic implementation of _THIS_IP_ relies on taking the address of a local label, which is considered broken by both GCC [1] and Clang [2] because label addresses are only expected to be used with computed gotos. While the generic version more or less works today, it is known to be brittle. For example, Clang -O2 always returns 1 when this function is inlined:

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

To provide a reliable unique identifier without breaking architectures relying on the generic _THIS_IP_, introduce _CODE_LOCATION_: it resolves to _THIS_IP_ where architectures provide a safe implementation, and falls back to a zero-cost static marker where _THIS_IP_ is broken.

Quoted 7 lines
Quoted 4 lines

---

Looks good to me,

Thanks!

Quoted 42 lines

with one suggestion below.

Quoted 25 lines
---
 include/linux/instruction_pointer.h | 24 ++++++++++++++++++++++++
 include/linux/slab.h                |  2 +-
 2 files changed, 25 insertions(+), 1 deletion(-)
include/linux/instruction_pointer.h +12 -0
index aa0b3ffea935..ea5bc756bd99 100644
@@ -8,6 +8,30 @@
 
 #ifndef _THIS_IP_
 #define _THIS_IP_  ({ __label__ __here; __here: (unsigned long)&&__here; })
+/*
+ * The current generic definition of _THIS_IP_ is considered broken by GCC [1]
+ * and Clang [2]. In particular, the address of a label is only expected to be
+ * used with a computed goto.
+ *
+ *   [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120071
+ *   [2] https://github.com/llvm/llvm-project/issues/138272
+ *
+ * Mark it as broken, so that appropriate fallback options can be implemented
+ * for architectures that do not define their own _THIS_IP_.
+ */
+#define HAS_BROKEN_THIS_IP

include/linux/instruction_pointer.h line 32

Quoted 10 lines
include/linux/instruction_pointer.h +10 -0
+#endif
+
+/*
+ * _CODE_LOCATION_ provides a unique identifier for the current code location.
+ * When _THIS_IP_ is broken (generic version), we fall back to a static marker
+ * which guarantees uniqueness and resolves to a constant address at link time,
+ * avoiding runtime overhead and compiler optimizations breaking it.
+ */
+#ifdef HAS_BROKEN_THIS_IP
+#define _CODE_LOCATION_ ({ static const char __here; (unsigned long)&__here; })

nit: perhaps it can be __initdata to free these after boot? ... if we want to save actual memory allocated rather than the vmlinux size.

Quoted 1 line

apparently ".init.bss" is a not thing :(

Not sure - it might cause CONFIG_DEBUG_SECTION_MISMATCH warnings. Also, if this memory is reclaimed, it may be reused for kernel modules, at which point there's a chance for collisions.

#4 lore raw

Re: [PATCH v4 2/3] slab: improve KMALLOC_PARTITION_RANDOM randomness

In reply to Marco Elver
Quoted 8 lines · Marco Elver

When using CONFIG_KMALLOC_PARTITION_RANDOM, _RET_IP_ was previously used to identify the allocation site. _RET_IP_, however, evaluates to the caller's parent's instruction pointer rather than the actual allocation site; this would lead to collisions where a function performs multiple allocations.

With the generalization to kmalloc_token_t, we now generate the token at the outermost macro, and using _THIS_IP_ would fix this for all cases.

Hm but it means in patch 1 we make things even worse and then fix them again, and also improve what was suboptimal prior to the series. Would it be instead possible to reorder patches 1 and 2 so we improve the current state first, and then introduce typed partitioning without any changes to the randomized one? (aside from changing the previously correcly used cases _RET_IP_ to _CODE_LOCATION_).

Quoted 74 lines

Unfortunately, the generic implementation of _THIS_IP_ relies on taking the address of a local label, which is considered broken by both GCC [1] and Clang [2] because label addresses are only expected to be used with computed gotos. While the generic version more or less works today, it is known to be brittle. For example, Clang -O2 always returns 1 when this function is inlined:

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

To provide a reliable unique identifier without breaking architectures relying on the generic _THIS_IP_, introduce _CODE_LOCATION_: it resolves to _THIS_IP_ where architectures provide a safe implementation, and falls back to a zero-cost static marker where _THIS_IP_ is broken.

---
v4:
* New patch.

---
 include/linux/instruction_pointer.h | 24 ++++++++++++++++++++++++
 include/linux/slab.h                |  2 +-
 2 files changed, 25 insertions(+), 1 deletion(-)
include/linux/instruction_pointer.h +24 -0
index aa0b3ffea935..ea5bc756bd99 100644
@@ -8,6 +8,30 @@
 
 #ifndef _THIS_IP_
 #define _THIS_IP_  ({ __label__ __here; __here: (unsigned long)&&__here; })
+/*
+ * The current generic definition of _THIS_IP_ is considered broken by GCC [1]
+ * and Clang [2]. In particular, the address of a label is only expected to be
+ * used with a computed goto.
+ *
+ *   [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120071
+ *   [2] https://github.com/llvm/llvm-project/issues/138272
+ *
+ * Mark it as broken, so that appropriate fallback options can be implemented
+ * for architectures that do not define their own _THIS_IP_.
+ */
+#define HAS_BROKEN_THIS_IP
+#endif
+
+/*
+ * _CODE_LOCATION_ provides a unique identifier for the current code location.
+ * When _THIS_IP_ is broken (generic version), we fall back to a static marker
+ * which guarantees uniqueness and resolves to a constant address at link time,
+ * avoiding runtime overhead and compiler optimizations breaking it.
+ */
+#ifdef HAS_BROKEN_THIS_IP
+#define _CODE_LOCATION_ ({ static const char __here; (unsigned long)&__here; })
+#else
+#define _CODE_LOCATION_ _THIS_IP_
 #endif
 
 #endif /* _LINUX_INSTRUCTION_POINTER_H */
include/linux/slab.h +1 -1
index c232f8a10af6..efab6b2ccf21 100644
@@ -503,7 +503,7 @@ int kmem_cache_shrink(struct kmem_cache *s);
 typedef struct { unsigned long v; } kmalloc_token_t;
 #ifdef CONFIG_KMALLOC_PARTITION_RANDOM
 extern unsigned long random_kmalloc_seed;
-#define __kmalloc_token(...) ((kmalloc_token_t){ .v = _RET_IP_ })
+#define __kmalloc_token(...) ((kmalloc_token_t){ .v = _CODE_LOCATION_ })
 #elif defined(CONFIG_KMALLOC_PARTITION_TYPED)
 #define __kmalloc_token(...) ((kmalloc_token_t){ .v = __builtin_infer_alloc_token(__VA_ARGS__) })
 #endif
author maintainer
#5 lore raw

Re: [PATCH v4 2/3] slab: improve KMALLOC_PARTITION_RANDOM randomness

Quoted 10 lines · Vlastimil Babka (SUSE)' via kasan-dev
Quoted 8 lines · Marco Elver

When using CONFIG_KMALLOC_PARTITION_RANDOM, _RET_IP_ was previously used to identify the allocation site. _RET_IP_, however, evaluates to the caller's parent's instruction pointer rather than the actual allocation site; this would lead to collisions where a function performs multiple allocations.

With the generalization to kmalloc_token_t, we now generate the token at the outermost macro, and using _THIS_IP_ would fix this for all cases.

Quoted 6 lines

Hm but it means in patch 1 we make things even worse and then fix them again, and also improve what was suboptimal prior to the series. Would it be instead possible to reorder patches 1 and 2 so we improve the current state first, and then introduce typed partitioning without any changes to the randomized one? (aside from changing the previously correcly used cases _RET_IP_ to _CODE_LOCATION_).

It won't work (it could be made to work if _THIS_IP_ wasn't broken). The compiler is supposed to maintain semantics of a static variable in a function, even inline functions, and refer to the same static variable -- and because kmalloc_type is an inline function, if _CODE_LOCATION_ is the non-_THIS_IP_ version, it'd break.

Even if _THIS_IP_ wasn't broken, the other complication is introducing the slab.c vs. outside use of kmalloc_type differentiation.

Both these problems go away if we make this patch 2 (using _CODE_LOCATION_ on the outer macro, not in an inline function).

While I understand that maybe we could have considered this as a stable backport, I think it's borderline; the feature isn't broken per-se, just slightly lower randomness than perhaps intended if size is a constant expression. A minimal fix prior to the macro rework currently eludes me.

#6 lore raw

Re: [PATCH v4 2/3] slab: improve KMALLOC_PARTITION_RANDOM randomness

Quoted 19 lines · Marco Elver
Quoted 10 lines · Vlastimil Babka (SUSE)' via kasan-dev
Quoted 8 lines · Marco Elver

When using CONFIG_KMALLOC_PARTITION_RANDOM, _RET_IP_ was previously used to identify the allocation site. _RET_IP_, however, evaluates to the caller's parent's instruction pointer rather than the actual allocation site; this would lead to collisions where a function performs multiple allocations.

With the generalization to kmalloc_token_t, we now generate the token at the outermost macro, and using _THIS_IP_ would fix this for all cases.

Quoted 6 lines

Hm but it means in patch 1 we make things even worse and then fix them again, and also improve what was suboptimal prior to the series. Would it be instead possible to reorder patches 1 and 2 so we improve the current state first, and then introduce typed partitioning without any changes to the randomized one? (aside from changing the previously correcly used cases _RET_IP_ to _CODE_LOCATION_).

Quoted 5 lines

It won't work (it could be made to work if _THIS_IP_ wasn't broken). The compiler is supposed to maintain semantics of a static variable in a function, even inline functions, and refer to the same static variable -- and because kmalloc_type is an inline function, if _CODE_LOCATION_ is the non-_THIS_IP_ version, it'd break.

Oh, I see.

Quoted 11 lines

Even if _THIS_IP_ wasn't broken, the other complication is introducing the slab.c vs. outside use of kmalloc_type differentiation.

Both these problems go away if we make this patch 2 (using _CODE_LOCATION_ on the outer macro, not in an inline function).

While I understand that maybe we could have considered this as a stable backport, I think it's borderline; the feature isn't broken per-se, just slightly lower randomness than perhaps intended if size is a constant expression. A minimal fix prior to the macro rework currently eludes me.

Fair enough. I wanted to avoid a bisection hazard, but since it's not feasible and it shouldn't actually break anything (compilation, run), it's acceptable. Thanks.

#7 lore raw

Re: [PATCH v4 2/3] slab: improve KMALLOC_PARTITION_RANDOM randomness

In reply to Marco Elver
Quoted 16 lines · On Mon, 11 May 2026 22:00:49 +0200 Marco Elver <[email protected]> wrote:

When using CONFIG_KMALLOC_PARTITION_RANDOM, _RET_IP_ was previously used to identify the allocation site. _RET_IP_, however, evaluates to the caller's parent's instruction pointer rather than the actual allocation site; this would lead to collisions where a function performs multiple allocations.

With the generalization to kmalloc_token_t, we now generate the token at the outermost macro, and using _THIS_IP_ would fix this for all cases.

Unfortunately, the generic implementation of _THIS_IP_ relies on taking the address of a local label, which is considered broken by both GCC [1] and Clang [2] because label addresses are only expected to be used with computed gotos. While the generic version more or less works today, it is known to be brittle. For example, Clang -O2 always returns 1 when this function is inlined:

Quoted 7 lines

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

To provide a reliable unique identifier without breaking architectures relying on the generic _THIS_IP_, introduce _CODE_LOCATION_: it resolves to _THIS_IP_ where architectures provide a safe implementation, and falls back to a zero-cost static marker where _THIS_IP_ is broken.

Doesn't that mean that all the other uses of _THIS_IP_ (which seem to mostly be tracking lock requests) are basically broken on everything except x86-64.

Would it be better to actually fit that?
It isn't as though it is hard asm, you just need to look at how gcc generates PIC references to static data.

-- David

author maintainer
#8 lore raw

Re: [PATCH v4 2/3] slab: improve KMALLOC_PARTITION_RANDOM randomness

Quoted 23 lines · David Laight
Quoted 19 lines · On Mon, 11 May 2026 22:00:49 +0200 Marco Elver <[email protected]> wrote:

When using CONFIG_KMALLOC_PARTITION_RANDOM, _RET_IP_ was previously used to identify the allocation site. _RET_IP_, however, evaluates to the caller's parent's instruction pointer rather than the actual allocation site; this would lead to collisions where a function performs multiple allocations.

With the generalization to kmalloc_token_t, we now generate the token at the outermost macro, and using _THIS_IP_ would fix this for all cases.

Unfortunately, the generic implementation of _THIS_IP_ relies on taking the address of a local label, which is considered broken by both GCC [1] and Clang [2] because label addresses are only expected to be used with computed gotos. While the generic version more or less works today, it is known to be brittle. For example, Clang -O2 always returns 1 when this function is inlined:

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

Quoted 7 lines
Quoted 4 lines

To provide a reliable unique identifier without breaking architectures relying on the generic _THIS_IP_, introduce _CODE_LOCATION_: it resolves to _THIS_IP_ where architectures provide a safe implementation, and falls back to a zero-cost static marker where _THIS_IP_ is broken.

Doesn't that mean that all the other uses of _THIS_IP_ (which seem to mostly be tracking lock requests) are basically broken on everything except x86-64.

It seems to mostly work, but yeah, it's probably broken in some places.

Quoted 3 lines

Would it be better to actually fit that?
It isn't as though it is hard asm, you just need to look at how gcc generates PIC references to static data.

Yeah, I have patches waiting to be sent - I sent one for arm64:
https://lore.kernel.org/all/[email protected]/

The rest of my patches are to-be-sent, when I get around to testing - which I didn't yet for most of them since setting up test environments for all of them is a PITA. Though I can send and let arch maintainers review them - this would be the tentative list:
https://git.kernel.org/pub/scm/linux/kernel/git/melver/linux.git/log/?h=alloc-token

#9 lore raw

csky ICe (was: Re: [PATCH v4 2/3] slab: improve KMALLOC_PARTITION_RANDOM randomness)

In reply to Marco Elver

Hi,

Quoted 19 lines · Marco Elver

When using CONFIG_KMALLOC_PARTITION_RANDOM, _RET_IP_ was previously used to identify the allocation site. _RET_IP_, however, evaluates to the caller's parent's instruction pointer rather than the actual allocation site; this would lead to collisions where a function performs multiple allocations.

With the generalization to kmalloc_token_t, we now generate the token at the outermost macro, and using _THIS_IP_ would fix this for all cases.

Unfortunately, the generic implementation of _THIS_IP_ relies on taking the address of a local label, which is considered broken by both GCC [1] and Clang [2] because label addresses are only expected to be used with computed gotos. While the generic version more or less works today, it is known to be brittle. For example, Clang -O2 always returns 1 when this function is inlined:

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

Quoted 8 lines

To provide a reliable unique identifier without breaking architectures relying on the generic _THIS_IP_, introduce _CODE_LOCATION_: it resolves to _THIS_IP_ where architectures provide a safe implementation, and falls back to a zero-cost static marker where _THIS_IP_ is broken.

With this patch in the tree, I get ICE erors when trying to build csky:allmodconfig.

Example:

Error log:
sound/core/oss/mixer_oss.c: In function 'snd_mixer_oss_proc_write':
sound/core/oss/mixer_oss.c:1202:1: error: could not split insn
1202 | }

      | ^
(insn 183 400 184 (set (reg:SI 0 a0 [orig:307 _55 ] [307])
        (xor:SI (reg:SI 3 a3 [orig:308 random_kmalloc_seed ] [308])
            (const:SI (plus:SI (symbol_ref:SI ("*.LANCHOR0") [flags 0x182])
                    (const_int 132 [0x84]))))) "include/linux/slab.h":759:52 288 {cskyv2_xorsi3}
     (expr_list:REG_DEAD (reg:SI 3 a3 [orig:308 random_kmalloc_seed ] [308])
        (nil)))
during RTL pass: final
sound/core/oss/mixer_oss.c:1202:1: internal compiler error: in final_scan_insn_1, at final.cc:2813
0x779b51e2a1c9 __libc_start_call_main
	../sysdeps/nptl/libc_start_call_main.h:58
0x779b51e2a28a __libc_start_main_impl
	../csu/libc-start.c:360

This happens with lots of files, not just this one. It is seen with all versions of gcc starting with at least v13.x. Reverting this patch fixes the problem. Bisect log is attached for reference.

Any idea what I could do to avoid the problem other than stopping to build csky:allmodconfig ?

Thanks,
Guenter

---
# bad: [93f51579e7df248780214094418f205253383cc5] Linux 7.3-rc4
# good: [7d0a66e4bb9081d75c82ec4957c50034cb0ea449] Linux 6.18
git bisect start 'HEAD' 'v6.18'
# good: [df8f6181ab57d65a99e61fcfc5be22a42df58642] Merge tag 'perf-tools-for-v7.1-2026-04-17' of git://git.kernel.org/pub/scm/linux/kernel/git/perf/perf-tools
git bisect good df8f6181ab57d65a99e61fcfc5be22a42df58642
# bad: [093239070573637ad2b4cb56abc9c4c7ee109294] Merge tag 'v7.2-rc2' into togreg
git bisect bad 093239070573637ad2b4cb56abc9c4c7ee109294
# bad: [b85966adbf5de0668a815c6e3527f87e0c387fb4] Merge tag 'net-next-7.2' of git://git.kernel.org/pub/scm/linux/kernel/git/netdev/net-next
git bisect bad b85966adbf5de0668a815c6e3527f87e0c387fb4
# good: [25447851777a53bd4b501e7f2cb418332ad584cc] Merge tag 'char-misc-7.1-rc6' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/char-misc
git bisect good 25447851777a53bd4b501e7f2cb418332ad584cc
# good: [bd77e50c9a70f844d6073499f3d1a6fd193eae73] Merge tag 'fbdev-for-7.2-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/deller/linux-fbdev
git bisect good bd77e50c9a70f844d6073499f3d1a6fd193eae73
# good: [972c4dd19cb92e03d75b66c426cfade07582a1ba] Merge tag 'wireless-next-2026-06-10' of https://git.kernel.org/pub/scm/linux/kernel/git/wireless/wireless-next
git bisect good 972c4dd19cb92e03d75b66c426cfade07582a1ba
# bad: [9b40ba14edcdf70240af8114092a76f75f070774] Merge tag 'for-7.2/io_uring-20260615' of git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux
git bisect bad 9b40ba14edcdf70240af8114092a76f75f070774
# bad: [0d8c1134936f1fb6678156ab4248ac740d274525] Merge tag 'v7.2-p1' of git://git.kernel.org/pub/scm/linux/kernel/git/herbert/crypto-2.6
git bisect bad 0d8c1134936f1fb6678156ab4248ac740d274525
# good: [42a58f08b70a7a320c168a1ce15e3fcfc8568708] crypto: atmel-sha204a - Use named initializers for struct i2c_device_id
git bisect good 42a58f08b70a7a320c168a1ce15e3fcfc8568708
# good: [2c1ccd9a1d786503086e83fe83e5c3b3c953b70e] docs: changes.rst: restore pahole 1.26 minimum (regressed by sort)
git bisect good 2c1ccd9a1d786503086e83fe83e5c3b3c953b70e
# bad: [f8115f0e8a0585ef1c03d07a68b989023097d16c] Merge tag 'slab-for-7.2' of git://git.kernel.org/pub/scm/linux/kernel/git/vbabka/slab
git bisect bad f8115f0e8a0585ef1c03d07a68b989023097d16c
# bad: [dfdfd58cce1c3f5df8733b64595448996c08e424] Merge branch 'slab/for-7.2/alloc_token' into slab/for-next
git bisect bad dfdfd58cce1c3f5df8733b64595448996c08e424
# good: [648927ceb84021a25a0fbd5673740956f318d534] mm/slab: do not limit zeroing to orig_size when only red zoning is enabled
git bisect good 648927ceb84021a25a0fbd5673740956f318d534
# good: [d196ea36a2f2118833ca648af53654553a4a1e7b] Merge branch 'slab/for-7.2/tools' into slab/for-next
git bisect good d196ea36a2f2118833ca648af53654553a4a1e7b
# bad: [e0f54249a491c62ef8196b9f13bd7d95dba47c6f] slab: fix kernel-docs for mm-api
git bisect bad e0f54249a491c62ef8196b9f13bd7d95dba47c6f
# bad: [0fc1bd38a19c108395d8338fb034f90c2d3fbe55] slab: improve KMALLOC_PARTITION_RANDOM randomness
git bisect bad 0fc1bd38a19c108395d8338fb034f90c2d3fbe55
# good: [feb662d9168b63e1d4c02671ec96005410c6f3ce] slab: support for compiler-assisted type-based slab cache partitioning
git bisect good feb662d9168b63e1d4c02671ec96005410c6f3ce

# first bad commit: [0fc1bd38a19c108395d8338fb034f90c2d3fbe55] slab: improve KMALLOC_PARTITION_RANDOM randomness
reviewer
#10 lore raw

Re: csky ICe (was: Re: [PATCH v4 2/3] slab: improve KMALLOC_PARTITION_RANDOM randomness)

Quoted 54 lines · Guenter Roeck

Hi,

Quoted 19 lines · Marco Elver

When using CONFIG_KMALLOC_PARTITION_RANDOM, _RET_IP_ was previously used to identify the allocation site. _RET_IP_, however, evaluates to the caller's parent's instruction pointer rather than the actual allocation site; this would lead to collisions where a function performs multiple allocations.

With the generalization to kmalloc_token_t, we now generate the token at the outermost macro, and using _THIS_IP_ would fix this for all cases.

Unfortunately, the generic implementation of _THIS_IP_ relies on taking the address of a local label, which is considered broken by both GCC [1] and Clang [2] because label addresses are only expected to be used with computed gotos. While the generic version more or less works today, it is known to be brittle. For example, Clang -O2 always returns 1 when this function is inlined:

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

Quoted 8 lines

To provide a reliable unique identifier without breaking architectures relying on the generic _THIS_IP_, introduce _CODE_LOCATION_: it resolves to _THIS_IP_ where architectures provide a safe implementation, and falls back to a zero-cost static marker where _THIS_IP_ is broken.

With this patch in the tree, I get ICE erors when trying to build csky:allmodconfig.

Example:

Error log:
sound/core/oss/mixer_oss.c: In function 'snd_mixer_oss_proc_write':
sound/core/oss/mixer_oss.c:1202:1: error: could not split insn
1202 | }

      | ^
(insn 183 400 184 (set (reg:SI 0 a0 [orig:307 _55 ] [307])
        (xor:SI (reg:SI 3 a3 [orig:308 random_kmalloc_seed ] [308])
            (const:SI (plus:SI (symbol_ref:SI ("*.LANCHOR0") [flags 0x182])
                    (const_int 132 [0x84]))))) "include/linux/slab.h":759:52 288 {cskyv2_xorsi3}
     (expr_list:REG_DEAD (reg:SI 3 a3 [orig:308 random_kmalloc_seed ] [308])
        (nil)))
during RTL pass: final
sound/core/oss/mixer_oss.c:1202:1: internal compiler error: in final_scan_insn_1, at final.cc:2813
0x779b51e2a1c9 __libc_start_call_main
	../sysdeps/nptl/libc_start_call_main.h:58
0x779b51e2a28a __libc_start_main_impl
	../csu/libc-start.c:360
Quoted 6 lines

This happens with lots of files, not just this one. It is seen with all versions of gcc starting with at least v13.x. Reverting this patch fixes the problem. Bisect log is attached for reference.

Any idea what I could do to avoid the problem other than stopping to build csky:allmodconfig ?

Maybe it's time to say goodbye to csky? ;-)

Quoted 2 lines

Thanks,
Guenter

Signature · 2 lines
Sincerely yours,
Mike.
author maintainer
#11 lore raw

Re: csky ICe (was: Re: [PATCH v4 2/3] slab: improve KMALLOC_PARTITION_RANDOM randomness)

In reply to Guenter Roeck
Quoted 54 lines · Guenter Roeck

Hi,

Quoted 19 lines · Marco Elver

When using CONFIG_KMALLOC_PARTITION_RANDOM, _RET_IP_ was previously used to identify the allocation site. _RET_IP_, however, evaluates to the caller's parent's instruction pointer rather than the actual allocation site; this would lead to collisions where a function performs multiple allocations.

With the generalization to kmalloc_token_t, we now generate the token at the outermost macro, and using _THIS_IP_ would fix this for all cases.

Unfortunately, the generic implementation of _THIS_IP_ relies on taking the address of a local label, which is considered broken by both GCC [1] and Clang [2] because label addresses are only expected to be used with computed gotos. While the generic version more or less works today, it is known to be brittle. For example, Clang -O2 always returns 1 when this function is inlined:

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

Quoted 8 lines

To provide a reliable unique identifier without breaking architectures relying on the generic _THIS_IP_, introduce _CODE_LOCATION_: it resolves to _THIS_IP_ where architectures provide a safe implementation, and falls back to a zero-cost static marker where _THIS_IP_ is broken.

With this patch in the tree, I get ICE erors when trying to build csky:allmodconfig.

Example:

Error log:
sound/core/oss/mixer_oss.c: In function 'snd_mixer_oss_proc_write':
sound/core/oss/mixer_oss.c:1202:1: error: could not split insn
1202 | }

      | ^
(insn 183 400 184 (set (reg:SI 0 a0 [orig:307 _55 ] [307])
        (xor:SI (reg:SI 3 a3 [orig:308 random_kmalloc_seed ] [308])
            (const:SI (plus:SI (symbol_ref:SI ("*.LANCHOR0") [flags 0x182])
                    (const_int 132 [0x84]))))) "include/linux/slab.h":759:52 288 {cskyv2_xorsi3}
     (expr_list:REG_DEAD (reg:SI 3 a3 [orig:308 random_kmalloc_seed ] [308])
        (nil)))
during RTL pass: final
sound/core/oss/mixer_oss.c:1202:1: internal compiler error: in final_scan_insn_1, at final.cc:2813
0x779b51e2a1c9 __libc_start_call_main
	../sysdeps/nptl/libc_start_call_main.h:58
0x779b51e2a28a __libc_start_main_impl
	../csu/libc-start.c:360
Quoted 6 lines

This happens with lots of files, not just this one. It is seen with all versions of gcc starting with at least v13.x. Reverting this patch fixes the problem. Bisect log is attached for reference.

Any idea what I could do to avoid the problem other than stopping to build csky:allmodconfig ?

No idea what gcc is falling over here, but the below patch could be a workaround/fix. Does that work better?

------ >8 ------

From: Marco Elver <[email protected]>
Date: Fri, 8 May 2026 14:51:45 +0200
Subject: [PATCH] csky: Implement _THIS_IP_ using inline asm

Both GCC [1] and Clang [2] consider the generic version of _THIS_IP_ to be broken:

        #define _THIS_IP_  ({ __label__ __here; __here: (unsigned long)&&__here; })

In particular, the address of a label is only expected to be used with a computed goto.

While the generic version more or less works today, it is known to be brittle and may break with current and future optimizations. For example, Clang -O2 always returns 1 when this function is inlined:

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

Fix it by overriding _THIS_IP_ in <asm/linkage.h> (which is included by <linux/instruction_pointer.h>) using an architecture-specific inline asm version. Additionally, avoiding taking the address of a label prevents compilers from emitting spurious indirect branch targets (e.g. ENDBR or BTI) under control-flow integrity schemes.

---
 arch/csky/include/asm/linkage.h | 7 +++++++
 1 file changed, 7 insertions(+)
 create mode 100644 arch/csky/include/asm/linkage.h
arch/csky/include/asm/linkage.h new file +7 -0
new file mode 100644
index 000000000000..04afd3583e25
@@ -0,0 +1,7 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __ASM_CSKY_LINKAGE_H
+#define __ASM_CSKY_LINKAGE_H
+
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("grs %0, ." : "=r" (__ip)); __ip; })
+
+#endif /* __ASM_CSKY_LINKAGE_H */
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
Tested-by
#12 lore raw

Re: csky ICe (was: Re: [PATCH v4 2/3] slab: improve KMALLOC_PARTITION_RANDOM randomness)

Quoted 59 lines · Marco Elver
Quoted 58 lines · Guenter Roeck

Hi,

Quoted 19 lines · Marco Elver

When using CONFIG_KMALLOC_PARTITION_RANDOM, _RET_IP_ was previously used to identify the allocation site. _RET_IP_, however, evaluates to the caller's parent's instruction pointer rather than the actual allocation site; this would lead to collisions where a function performs multiple allocations.

With the generalization to kmalloc_token_t, we now generate the token at the outermost macro, and using _THIS_IP_ would fix this for all cases.

Unfortunately, the generic implementation of _THIS_IP_ relies on taking the address of a local label, which is considered broken by both GCC [1] and Clang [2] because label addresses are only expected to be used with computed gotos. While the generic version more or less works today, it is known to be brittle. For example, Clang -O2 always returns 1 when this function is inlined:

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

Quoted 8 lines

To provide a reliable unique identifier without breaking architectures relying on the generic _THIS_IP_, introduce _CODE_LOCATION_: it resolves to _THIS_IP_ where architectures provide a safe implementation, and falls back to a zero-cost static marker where _THIS_IP_ is broken.

With this patch in the tree, I get ICE erors when trying to build csky:allmodconfig.

Example:

Error log:
sound/core/oss/mixer_oss.c: In function 'snd_mixer_oss_proc_write':
sound/core/oss/mixer_oss.c:1202:1: error: could not split insn
1202 | }

      | ^
(insn 183 400 184 (set (reg:SI 0 a0 [orig:307 _55 ] [307])
        (xor:SI (reg:SI 3 a3 [orig:308 random_kmalloc_seed ] [308])
            (const:SI (plus:SI (symbol_ref:SI ("*.LANCHOR0") [flags 0x182])
                    (const_int 132 [0x84]))))) "include/linux/slab.h":759:52 288 {cskyv2_xorsi3}
     (expr_list:REG_DEAD (reg:SI 3 a3 [orig:308 random_kmalloc_seed ] [308])
        (nil)))
during RTL pass: final
sound/core/oss/mixer_oss.c:1202:1: internal compiler error: in final_scan_insn_1, at final.cc:2813
0x779b51e2a1c9 __libc_start_call_main
	../sysdeps/nptl/libc_start_call_main.h:58
0x779b51e2a28a __libc_start_main_impl
	../csu/libc-start.c:360

This happens with lots of files, not just this one. It is seen with all versions of gcc starting with at least v13.x. Reverting this patch fixes the problem. Bisect log is attached for reference.

Quoted 6 lines
Quoted 2 lines

Any idea what I could do to avoid the problem other than stopping to build csky:allmodconfig ?

No idea what gcc is falling over here, but the below patch could be a workaround/fix. Does that work better?

Yes, it does.

Thanks,
Guenter

Quoted 51 lines

------ >8 ------

From: Marco Elver <[email protected]>
Date: Fri, 8 May 2026 14:51:45 +0200
Subject: [PATCH] csky: Implement _THIS_IP_ using inline asm

Both GCC [1] and Clang [2] consider the generic version of _THIS_IP_ to be broken:

        #define _THIS_IP_  ({ __label__ __here; __here: (unsigned long)&&__here; })

In particular, the address of a label is only expected to be used with a computed goto.

While the generic version more or less works today, it is known to be brittle and may break with current and future optimizations. For example, Clang -O2 always returns 1 when this function is inlined:

static inline unsigned long get_ip(void)
{ return ({ __label__ __here; __here: (unsigned long)&&__here; }); }

Fix it by overriding _THIS_IP_ in <asm/linkage.h> (which is included by <linux/instruction_pointer.h>) using an architecture-specific inline asm version. Additionally, avoiding taking the address of a label prevents compilers from emitting spurious indirect branch targets (e.g. ENDBR or BTI) under control-flow integrity schemes.

---
 arch/csky/include/asm/linkage.h | 7 +++++++
 1 file changed, 7 insertions(+)
 create mode 100644 arch/csky/include/asm/linkage.h
arch/csky/include/asm/linkage.h new file +7 -0
new file mode 100644
index 000000000000..04afd3583e25
@@ -0,0 +1,7 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __ASM_CSKY_LINKAGE_H
+#define __ASM_CSKY_LINKAGE_H
+
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("grs %0, ." : "=r" (__ip)); __ip; })
+
+#endif /* __ASM_CSKY_LINKAGE_H */
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
author maintainer
#13 lore raw

PATCH v4 3/3 slab: fix kernel-docs for mm-api

In reply to Marco Elver

The mm-api kernel-docs have been disconnected from their symbols. While the scripts were previously taught to handle the _noprof suffix added by allocation tagging (in 51a7bf0238c2 "scripts/kernel-doc: drop "_noprof" on function prototypes"), this does not handle cases where the internal implementation function has an additional leading underscore. The added optional parameters (via DECL_KMALLOC_PARAMS) further complicate parsing the internal signatures.

When the kernel-doc block remains above the internal implementation function but uses the public API name, the documentation generator fails to associate the documented symbol.

Simply moving the docs to the macros in slab.h fixes the association but causes loss of types in the generated documentation (rendering as e.g. untyped 'kmalloc(size, flags)' macro).

Fix this by:

1. Moving the kernel-doc comment blocks from slub.c to slab.h, placing them directly above the user-facing macros.

2. Providing explicit, typed C prototypes for the documented APIs inside '#if 0 /* kernel-doc */' blocks.

3. Converting the variadic macros for the documented APIs to use explicit arguments to match the documentation.

No functional change intended.

---
v4:
* Provide typed C prototypes in '#if 0' blocks to properly render API.

---
 include/linux/slab.h | 216 +++++++++++++++++++++++++++++++++----------
 mm/slub.c            |  98 --------------------
 2 files changed, 168 insertions(+), 146 deletions(-)
include/linux/slab.h +168 -48
index efab6b2ccf21..a4bf1585411f 100644
@@ -530,7 +530,49 @@ void * __must_check krealloc_node_align_noprof(const void *objp,
 					       unsigned long align,
 					       gfp_t flags, int nid) __realloc_size(2);
 #define krealloc_noprof(_o, _s, _f)	krealloc_node_align_noprof(_o, PASS_TOKEN_PARAMS(_s, __kmalloc_token(_s)), 1, _f, NUMA_NO_NODE)
-#define krealloc_node_align(_o, _s, _a, _f, _n)	alloc_hooks(krealloc_node_align_noprof(_o, PASS_TOKEN_PARAMS(_s, __kmalloc_token(_s)), _a, _f, _n))
+#if 0 /* kernel-doc */
+/**
+ * krealloc_node_align - reallocate memory. The contents will remain unchanged.
+ * @p: object to reallocate memory for.
+ * @new_size: how many bytes of memory are required.
+ * @align: desired alignment.
+ * @flags: the type of memory to allocate.
+ * @nid: NUMA node or NUMA_NO_NODE
+ *
+ * If @p is %NULL, krealloc() behaves exactly like kmalloc().  If @new_size
+ * is 0 and @p is not a %NULL pointer, the object pointed to is freed.
+ *
+ * Only alignments up to those guaranteed by kmalloc() will be honored. Please see
+ * Documentation/core-api/memory-allocation.rst for more details.
+ *
+ * If __GFP_ZERO logic is requested, callers must ensure that, starting with the
+ * initial memory allocation, every subsequent call to this API for the same
+ * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that
+ * __GFP_ZERO is not fully honored by this API.
+ *
+ * When slub_debug_orig_size() is off, krealloc() only knows about the bucket
+ * size of an allocation (but not the exact size it was allocated with) and
+ * hence implements the following semantics for shrinking and growing buffers
+ * with __GFP_ZERO::
+ *
+ *           new             bucket
+ *   0       size             size
+ *   |--------|----------------|
+ *   |  keep  |      zero      |
+ *
+ * Otherwise, the original allocation size 'orig_size' could be used to
+ * precisely clear the requested size, and the new size will also be stored
+ * as the new 'orig_size'.
+ *
+ * In any case, the contents of the object pointed to are preserved up to the
+ * lesser of the new and old sizes.
+ *
+ * Return: pointer to the allocated memory or %NULL in case of error
+ */
+void *krealloc_node_align(const void *p, size_t new_size, unsigned long align, gfp_t flags, int nid);
+#endif
+#define krealloc_node_align(p, new_size, align, flags, nid) \
+	alloc_hooks(krealloc_node_align_noprof(p, PASS_TOKEN_PARAMS(new_size, __kmalloc_token(new_size)), align, flags, nid))
 #define krealloc_node(_o, _s, _f, _n)	krealloc_node_align(_o, _s, 1, _f, _n)
 #define krealloc(...)			krealloc_node(__VA_ARGS__, NUMA_NO_NODE)
 
@@ -913,6 +955,23 @@ void *__kmalloc_large_noprof(size_t size, gfp_t flags)
 void *__kmalloc_large_node_noprof(size_t size, gfp_t flags, int node)
 				__assume_page_alignment __alloc_size(1);
 
+static __always_inline __alloc_size(1) void *_kmalloc_noprof(size_t size, gfp_t flags, kmalloc_token_t token)
+{
+	if (__builtin_constant_p(size) && size) {
+		unsigned int index;
+
+		if (size > KMALLOC_MAX_CACHE_SIZE)
+			return __kmalloc_large_noprof(size, flags);
+
+		index = kmalloc_index(size);
+		return __kmalloc_cache_noprof(
+				kmalloc_caches[kmalloc_type(flags, token)][index],
+				flags, size);
+	}
+	return __kmalloc_noprof(PASS_KMALLOC_PARAMS(size, NULL, token), flags);
+}
+#define kmalloc_noprof(...)			_kmalloc_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
+#if 0 /* kernel-doc */
 /**
  * kmalloc - allocate kernel memory
  * @size: how many bytes of memory are required.
@@ -968,27 +1027,27 @@ void *__kmalloc_large_node_noprof(size_t size, gfp_t flags, int node)
  *	Try really hard to succeed the allocation but fail
  *	eventually.
  */
-static __always_inline __alloc_size(1) void *_kmalloc_noprof(size_t size, gfp_t flags, kmalloc_token_t token)
-{
-	if (__builtin_constant_p(size) && size) {
-		unsigned int index;
-
-		if (size > KMALLOC_MAX_CACHE_SIZE)
-			return __kmalloc_large_noprof(size, flags);
-
-		index = kmalloc_index(size);
-		return __kmalloc_cache_noprof(
-				kmalloc_caches[kmalloc_type(flags, token)][index],
-				flags, size);
-	}
-	return __kmalloc_noprof(PASS_KMALLOC_PARAMS(size, NULL, token), flags);
-}
-#define kmalloc_noprof(...)			_kmalloc_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
-#define kmalloc(...)				alloc_hooks(kmalloc_noprof(__VA_ARGS__))
+void *kmalloc(size_t size, gfp_t flags);
+#endif
+#define kmalloc(size, flags)			alloc_hooks(kmalloc_noprof(size, flags))
 
 void *_kmalloc_nolock_noprof(DECL_TOKEN_PARAMS(size, token), gfp_t gfp_flags, int node);
 #define kmalloc_nolock_noprof(_s, _f, _n)	_kmalloc_nolock_noprof(PASS_TOKEN_PARAMS(_s, __kmalloc_token(_s)), _f, _n)
-#define kmalloc_nolock(...)			alloc_hooks(kmalloc_nolock_noprof(__VA_ARGS__))
+#if 0 /* kernel-doc */
+/**
+ * kmalloc_nolock - Allocate an object of given size from any context.
+ * @size: size to allocate
+ * @gfp_flags: GFP flags. Only __GFP_ACCOUNT, __GFP_ZERO, __GFP_NO_OBJ_EXT
+ * allowed.
+ * @node: node number of the target node.
+ *
+ * Return: pointer to the new object or NULL in case of error.
+ * NULL does not mean EBUSY or EAGAIN. It means ENOMEM.
+ * There is no reason to call it again and expect !NULL.
+ */
+void *kmalloc_nolock(size_t size, gfp_t gfp_flags, int node);
+#endif
+#define kmalloc_nolock(size, gfp_flags, node)	alloc_hooks(kmalloc_nolock_noprof(size, gfp_flags, node))
 
 /**
  * __alloc_objs - Allocate objects of a given type using
@@ -1115,23 +1174,40 @@ static __always_inline __alloc_size(1) void *_kmalloc_node_noprof(size_t size, g
 #define kmalloc_node_noprof(...)		_kmalloc_node_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
 #define kmalloc_node(...)			alloc_hooks(kmalloc_node_noprof(__VA_ARGS__))
 
+static inline __alloc_size(1, 2) void *_kmalloc_array_noprof(size_t n, size_t size, gfp_t flags, kmalloc_token_t token)
+{
+	size_t bytes;
+
+	if (unlikely(check_mul_overflow(n, size, &bytes)))
+		return NULL;
+	return _kmalloc_noprof(bytes, flags, token);
+}
+#define kmalloc_array_noprof(...)		_kmalloc_array_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
+#if 0 /* kernel-doc */
 /**
  * kmalloc_array - allocate memory for an array.
  * @n: number of elements.
  * @size: element size.
  * @flags: the type of memory to allocate (see kmalloc).
  */
-static inline __alloc_size(1, 2) void *_kmalloc_array_noprof(size_t n, size_t size, gfp_t flags, kmalloc_token_t token)
+void *kmalloc_array(size_t n, size_t size, gfp_t flags);
+#endif
+#define kmalloc_array(n, size, flags)		alloc_hooks(kmalloc_array_noprof(n, size, flags))
+
+static inline __realloc_size(2, 3) void * __must_check _krealloc_array_noprof(void *p,
+								       size_t new_n,
+								       size_t new_size,
+								       gfp_t flags, kmalloc_token_t token)
 {
 	size_t bytes;
 
-	if (unlikely(check_mul_overflow(n, size, &bytes)))
+	if (unlikely(check_mul_overflow(new_n, new_size, &bytes)))
 		return NULL;
-	return _kmalloc_noprof(bytes, flags, token);
-}
-#define kmalloc_array_noprof(...)		_kmalloc_array_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
-#define kmalloc_array(...)			alloc_hooks(kmalloc_array_noprof(__VA_ARGS__))
 
+	return krealloc_node_align_noprof(p, PASS_TOKEN_PARAMS(bytes, token), 1, flags, NUMA_NO_NODE);
+}
+#define krealloc_array_noprof(...)		_krealloc_array_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
+#if 0 /* kernel-doc */
 /**
  * krealloc_array - reallocate memory for an array.
  * @p: pointer to the memory chunk to reallocate
@@ -1149,20 +1225,9 @@ static inline __alloc_size(1, 2) void *_kmalloc_array_noprof(size_t n, size_t si
  * In any case, the contents of the object pointed to are preserved up to the
  * lesser of the new and old sizes.
  */
-static inline __realloc_size(2, 3) void * __must_check _krealloc_array_noprof(void *p,
-								       size_t new_n,
-								       size_t new_size,
-								       gfp_t flags, kmalloc_token_t token)
-{
-	size_t bytes;
-
-	if (unlikely(check_mul_overflow(new_n, new_size, &bytes)))
-		return NULL;
-
-	return krealloc_node_align_noprof(p, PASS_TOKEN_PARAMS(bytes, token), 1, flags, NUMA_NO_NODE);
-}
-#define krealloc_array_noprof(...)		_krealloc_array_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
-#define krealloc_array(...)			alloc_hooks(krealloc_array_noprof(__VA_ARGS__))
+void *krealloc_array(void *p, size_t new_n, size_t new_size, gfp_t flags);
+#endif
+#define krealloc_array(p, new_n, new_size, flags) alloc_hooks(krealloc_array_noprof(p, new_n, new_size, flags))
 
 /**
  * kcalloc - allocate memory for an array. The memory is set to zero.
@@ -1214,17 +1279,20 @@ static inline __alloc_size(1, 2) void *_kmalloc_array_node_noprof(size_t n, size
  */
 #define kmem_cache_zalloc(_k, _flags)		kmem_cache_alloc(_k, (_flags)|__GFP_ZERO)
 
-/**
- * kzalloc - allocate memory. The memory is set to zero.
- * @size: how many bytes of memory are required.
- * @flags: the type of memory to allocate (see kmalloc).
- */
 static inline __alloc_size(1) void *_kzalloc_noprof(size_t size, gfp_t flags, kmalloc_token_t token)
 {
 	return _kmalloc_noprof(size, flags | __GFP_ZERO, token);
 }
 #define kzalloc_noprof(...)			_kzalloc_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
-#define kzalloc(...)				alloc_hooks(kzalloc_noprof(__VA_ARGS__))
+#if 0 /* kernel-doc */
+/**
+ * kzalloc - allocate memory. The memory is set to zero.
+ * @size: how many bytes of memory are required.
+ * @flags: the type of memory to allocate (see kmalloc).
+ */
+void *kzalloc(size_t size, gfp_t flags);
+#endif
+#define kzalloc(size, flags)			alloc_hooks(kzalloc_noprof(size, flags))
 #define kzalloc_node(_size, _flags, _node)	kmalloc_node(_size, (_flags)|__GFP_ZERO, _node)
 
 void *__kvmalloc_node_noprof(DECL_KMALLOC_PARAMS(size, b, token), unsigned long align,
@@ -1233,7 +1301,29 @@ void *__kvmalloc_node_noprof(DECL_KMALLOC_PARAMS(size, b, token), unsigned long
 	__kvmalloc_node_noprof(PASS_KMALLOC_PARAMS(_size, NULL, __kmalloc_token(_size)), _align, _flags, _node)
 #define kvmalloc_node_align(...)		\
 	alloc_hooks(kvmalloc_node_align_noprof(__VA_ARGS__))
-#define kvmalloc_node(_s, _f, _n)		kvmalloc_node_align(_s, 1, _f, _n)
+#if 0 /* kernel-doc */
+/**
+ * kvmalloc_node - attempt to allocate physically contiguous memory, but upon
+ * failure, fall back to non-contiguous (vmalloc) allocation.
+ * @size: size of the request.
+ * @flags: gfp mask for the allocation - must be compatible (superset) with GFP_KERNEL.
+ * @node: numa node to allocate from
+ *
+ * Only alignments up to those guaranteed by kmalloc() will be honored. Please see
+ * Documentation/core-api/memory-allocation.rst for more details.
+ *
+ * Uses kmalloc to get the memory but if the allocation fails then falls back
+ * to the vmalloc allocator. Use kvfree for freeing the memory.
+ *
+ * GFP_NOWAIT and GFP_ATOMIC are supported, the __GFP_NORETRY modifier is not.
+ * __GFP_RETRY_MAYFAIL is supported, and it should be used only if kmalloc is
+ * preferable to the vmalloc fallback, due to visible performance drawbacks.
+ *
+ * Return: pointer to the allocated memory of %NULL in case of failure
+ */
+void *kvmalloc_node(size_t size, gfp_t flags, int node);
+#endif
+#define kvmalloc_node(size, flags, node)	kvmalloc_node_align(size, 1, flags, node)
 #define kvmalloc_node_noprof(size, flags, node)	\
 	kvmalloc_node_align_noprof(size, 1, flags, node)
 #define kvmalloc(...)				kvmalloc_node(__VA_ARGS__, NUMA_NO_NODE)
@@ -1266,8 +1356,38 @@ _kvmalloc_array_node_noprof(size_t n, size_t size, gfp_t flags, int node, kmallo
 
 void *kvrealloc_node_align_noprof(const void *p, DECL_TOKEN_PARAMS(size, token), unsigned long align,
 				  gfp_t flags, int nid) __realloc_size(2);
-#define kvrealloc_node_align(_p, _s, _a, _f, _n)	\
-	alloc_hooks(kvrealloc_node_align_noprof(_p, PASS_TOKEN_PARAMS(_s, __kmalloc_token(_s)), _a, _f, _n))
+#if 0 /* kernel-doc */
+/**
+ * kvrealloc_node_align - reallocate memory; contents remain unchanged
+ * @p: object to reallocate memory for
+ * @size: the size to reallocate
+ * @align: desired alignment
+ * @flags: the flags for the page level allocator
+ * @nid: NUMA node id
+ *
+ * If @p is %NULL, kvrealloc() behaves exactly like kvmalloc(). If @size is 0
+ * and @p is not a %NULL pointer, the object pointed to is freed.
+ *
+ * Only alignments up to those guaranteed by kmalloc() will be honored. Please see
+ * Documentation/core-api/memory-allocation.rst for more details.
+ *
+ * If __GFP_ZERO logic is requested, callers must ensure that, starting with the
+ * initial memory allocation, every subsequent call to this API for the same
+ * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that
+ * __GFP_ZERO is not fully honored by this API.
+ *
+ * In any case, the contents of the object pointed to are preserved up to the
+ * lesser of the new and old sizes.
+ *
+ * This function must not be called concurrently with itself or kvfree() for the
+ * same memory allocation.
+ *
+ * Return: pointer to the allocated memory or %NULL in case of error
+ */
+void *kvrealloc_node_align(const void *p, size_t size, unsigned long align, gfp_t flags, int nid);
+#endif
+#define kvrealloc_node_align(p, size, align, flags, nid)	\
+	alloc_hooks(kvrealloc_node_align_noprof(p, PASS_TOKEN_PARAMS(size, __kmalloc_token(size)), align, flags, nid))
 #define kvrealloc_node(_p, _s, _f, _n)		kvrealloc_node_align(_p, _s, 1, _f, _n)
 #define kvrealloc(...)				kvrealloc_node(__VA_ARGS__, NUMA_NO_NODE)
 
mm/slub.c +0 -98

122 lines not on this page · raw message

Signature · 1 line
2.54.0.563.g4f69b47b94-goog
maintainer Reviewed-by on v4 1/3
#14 lore raw
In reply to Marco Elver
Quoted 89 lines · Marco Elver

Rework the general infrastructure around RANDOM_KMALLOC_CACHES into more flexible KMALLOC_PARTITION_CACHES, with the former being a partitioning mode of the latter.

Introduce a new mode, KMALLOC_PARTITION_TYPED, which leverages a feature available in Clang 22 and later, called "allocation tokens" via __builtin_infer_alloc_token() [1]. Unlike KMALLOC_PARTITION_RANDOM (formerly RANDOM_KMALLOC_CACHES), this mode deterministically assigns a slab cache to an allocation of type T, regardless of allocation site.

The builtin __builtin_infer_alloc_token(<malloc-args>, ...) instructs the compiler to infer an allocation type from arguments commonly passed to memory-allocating functions and returns a type-derived token ID. The implementation passes kmalloc-args to the builtin: the compiler performs best-effort type inference, and then recognizes common patterns such as kmalloc(sizeof(T), ...), kmalloc(sizeof(T) * n, ...), but also (T *)kmalloc(...). Where the compiler fails to infer a type the fallback token (default: 0) is chosen.

Note: kmalloc_obj(..) APIs fix the pattern how size and result type are expressed, and therefore ensures there's not much drift in which patterns the compiler needs to recognize. Specifically, kmalloc_obj() and friends expand to (TYPE *)KMALLOC(__obj_size, GFP), which the compiler recognizes via the cast to TYPE*.

Clang's default token ID calculation is described as [1]:

typehashpointersplit: This mode assigns a token ID based on the hash of the allocated type's name, where the top half ID-space is reserved for types that contain pointers and the bottom half for types that do not contain pointers.

Separating pointer-containing objects from pointerless objects and data allocations can help mitigate certain classes of memory corruption exploits [2]: attackers who gains a buffer overflow on a primitive buffer cannot use it to directly corrupt pointers or other critical metadata in an object residing in a different, isolated heap region.

It is important to note that heap isolation strategies offer a best-effort approach, and do not provide a 100% security guarantee, albeit achievable at relatively low performance cost. Note that this also does not prevent cross-cache attacks: while waiting for future features like SLAB_VIRTUAL [3] to provide physical page isolation, this feature should be deployed alongside SHUFFLE_PAGE_ALLOCATOR and init_on_free=1 to mitigate cross-cache attacks and page-reuse attacks as much as possible today.

With all that, my kernel (x86 defconfig) shows me a histogram of slab cache object distribution per /proc/slabinfo (after boot):

<slab cache> <objs> <hist>

  kmalloc-part-15    1465  ++++++++++++++
  kmalloc-part-14    2988  +++++++++++++++++++++++++++++
  kmalloc-part-13    1656  ++++++++++++++++
  kmalloc-part-12    1045  ++++++++++
  kmalloc-part-11    1697  ++++++++++++++++
  kmalloc-part-10    1489  ++++++++++++++
  kmalloc-part-09     965  +++++++++
  kmalloc-part-08     710  +++++++
  kmalloc-part-07     100  +
  kmalloc-part-06     217  ++
  kmalloc-part-05     105  +
  kmalloc-part-04    4047  ++++++++++++++++++++++++++++++++++++++++
  kmalloc-part-03     183  +
  kmalloc-part-02     283  ++
  kmalloc-part-01     316  +++
  kmalloc            1422  ++++++++++++++

The above /proc/slabinfo snapshot shows me there are 6673 allocated objects (slabs 00 - 07) that the compiler claims contain no pointers or it was unable to infer the type of, and 12015 objects that contain pointers (slabs 08 - 15). On a whole, this looks relatively sane.

Additionally, when I compile my kernel with -Rpass=alloc-token, which provides diagnostics where (after dead-code elimination) type inference failed, I see 186 allocation sites where the compiler failed to identify a type (down from 966 when I sent the RFC [4]). Some initial review confirms these are mostly variable sized buffers, but also include structs with trailing flexible length arrays.

Quoted 1 line

---

Looks good to me,

mm/Kconfig config SLUB_STATS · line 319

Quoted 7 lines

# Sanity check userspace page table mappings.
CONFIG_PAGE_TABLE_CHECK=y

mm/Kconfig +5 -0
+config RANDOM_KMALLOC_CACHES
+	bool
+	transitional
+	help
+	  Transitional config for migration to KMALLOC_PARTITION_CACHES.

Heh, didn't realize transitional config was a thing, nice!

Signature · 2 lines
Cheers,
Harry / Hyeonggon
#15 lore raw
In reply to Marco Elver
Quoted 80 lines · Marco Elver

Rework the general infrastructure around RANDOM_KMALLOC_CACHES into more flexible KMALLOC_PARTITION_CACHES, with the former being a partitioning mode of the latter.

Introduce a new mode, KMALLOC_PARTITION_TYPED, which leverages a feature available in Clang 22 and later, called "allocation tokens" via __builtin_infer_alloc_token() [1]. Unlike KMALLOC_PARTITION_RANDOM (formerly RANDOM_KMALLOC_CACHES), this mode deterministically assigns a slab cache to an allocation of type T, regardless of allocation site.

The builtin __builtin_infer_alloc_token(<malloc-args>, ...) instructs the compiler to infer an allocation type from arguments commonly passed to memory-allocating functions and returns a type-derived token ID. The implementation passes kmalloc-args to the builtin: the compiler performs best-effort type inference, and then recognizes common patterns such as kmalloc(sizeof(T), ...), kmalloc(sizeof(T) * n, ...), but also (T *)kmalloc(...). Where the compiler fails to infer a type the fallback token (default: 0) is chosen.

Note: kmalloc_obj(..) APIs fix the pattern how size and result type are expressed, and therefore ensures there's not much drift in which patterns the compiler needs to recognize. Specifically, kmalloc_obj() and friends expand to (TYPE *)KMALLOC(__obj_size, GFP), which the compiler recognizes via the cast to TYPE*.

Clang's default token ID calculation is described as [1]:

typehashpointersplit: This mode assigns a token ID based on the hash of the allocated type's name, where the top half ID-space is reserved for types that contain pointers and the bottom half for types that do not contain pointers.

Separating pointer-containing objects from pointerless objects and data allocations can help mitigate certain classes of memory corruption exploits [2]: attackers who gains a buffer overflow on a primitive buffer cannot use it to directly corrupt pointers or other critical metadata in an object residing in a different, isolated heap region.

It is important to note that heap isolation strategies offer a best-effort approach, and do not provide a 100% security guarantee, albeit achievable at relatively low performance cost. Note that this also does not prevent cross-cache attacks: while waiting for future features like SLAB_VIRTUAL [3] to provide physical page isolation, this feature should be deployed alongside SHUFFLE_PAGE_ALLOCATOR and init_on_free=1 to mitigate cross-cache attacks and page-reuse attacks as much as possible today.

With all that, my kernel (x86 defconfig) shows me a histogram of slab cache object distribution per /proc/slabinfo (after boot):

<slab cache> <objs> <hist>

  kmalloc-part-15    1465  ++++++++++++++
  kmalloc-part-14    2988  +++++++++++++++++++++++++++++
  kmalloc-part-13    1656  ++++++++++++++++
  kmalloc-part-12    1045  ++++++++++
  kmalloc-part-11    1697  ++++++++++++++++
  kmalloc-part-10    1489  ++++++++++++++
  kmalloc-part-09     965  +++++++++
  kmalloc-part-08     710  +++++++
  kmalloc-part-07     100  +
  kmalloc-part-06     217  ++
  kmalloc-part-05     105  +
  kmalloc-part-04    4047  ++++++++++++++++++++++++++++++++++++++++
  kmalloc-part-03     183  +
  kmalloc-part-02     283  ++
  kmalloc-part-01     316  +++
  kmalloc            1422  ++++++++++++++

The above /proc/slabinfo snapshot shows me there are 6673 allocated objects (slabs 00 - 07) that the compiler claims contain no pointers or it was unable to infer the type of, and 12015 objects that contain pointers (slabs 08 - 15). On a whole, this looks relatively sane.

Additionally, when I compile my kernel with -Rpass=alloc-token, which provides diagnostics where (after dead-code elimination) type inference failed, I see 186 allocation sites where the compiler failed to identify a type (down from 966 when I sent the RFC [4]). Some initial review confirms these are mostly variable sized buffers, but also include structs with trailing flexible length arrays.

Quoted 9 lines

Applied [1] to slab/for-next, thanks. That means including the kernel-doc workarounds in patch 3. I know Jon said someone might hate it, but maybe it will motivate them for creating a proper fix :) It seems better than leaving doc generation broken or not applying this series at all.

https://git.kernel.org/pub/scm/linux/kernel/git/vbabka/slab.git/log/?h=slab/for-7.2/alloc_token

I did the following fixup to remove passing an unnecessary NULL argument for __kmalloc_nolock() with buckets enabled. Made bloat-o-meter happier a bit.

include/linux/slab.h +2 -2
index c232f8a10af6..795455256329 100644
@@ -894,7 +894,7 @@ unsigned int kmem_cache_sheaf_size(struct slab_sheaf *sheaf);
  * with the exception of kunit tests
  */
 
-void *__kmalloc_noprof(DECL_KMALLOC_PARAMS(size, b, token), gfp_t flags)
+void *__kmalloc_noprof(DECL_TOKEN_PARAMS(size, token), gfp_t flags)
 				__assume_kmalloc_alignment __alloc_size(1);
 
 void *__kmalloc_node_noprof(DECL_KMALLOC_PARAMS(size, b, token), gfp_t flags, int node)
@@ -981,7 +981,7 @@ static __always_inline __alloc_size(1) void *_kmalloc_noprof(size_t size, gfp_t
 				kmalloc_caches[kmalloc_type(flags, token)][index],
 				flags, size);
 	}
-	return __kmalloc_noprof(PASS_KMALLOC_PARAMS(size, NULL, token), flags);
+	return __kmalloc_noprof(PASS_TOKEN_PARAMS(size, token), flags);
 }
 #define kmalloc_noprof(...)			_kmalloc_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
 #define kmalloc(...)				alloc_hooks(kmalloc_noprof(__VA_ARGS__))
mm/slub.c +3 -3
index a6e9015601d6..74652bbdd591 100644
@@ -5303,10 +5303,10 @@ void *__kmalloc_node_noprof(DECL_KMALLOC_PARAMS(size, b, token), gfp_t flags, in
 }
 EXPORT_SYMBOL(__kmalloc_node_noprof);
 
-void *__kmalloc_noprof(DECL_KMALLOC_PARAMS(size, b, token), gfp_t flags)
+void *__kmalloc_noprof(DECL_TOKEN_PARAMS(size, token), gfp_t flags)
 {
-	return __do_kmalloc_node(size, PASS_BUCKET_PARAM(b), flags,
-				 NUMA_NO_NODE, _RET_IP_, PASS_TOKEN_PARAM(token));
+	return __do_kmalloc_node(size, NULL, flags,  NUMA_NO_NODE, _RET_IP_,
+				 PASS_TOKEN_PARAM(token));
 }
 EXPORT_SYMBOL(__kmalloc_noprof);
 
#16 lore raw
Quoted 9 lines · Vlastimil Babka (SUSE)

Applied [1] to slab/for-next, thanks. That means including the kernel-doc workarounds in patch 3. I know Jon said someone might hate it, but maybe it will motivate them for creating a proper fix :) It seems better than leaving doc generation broken or not applying this series at all.

https://git.kernel.org/pub/scm/linux/kernel/git/vbabka/slab.git/log/?h=slab/for-7.2/alloc_token

I did the following fixup to remove passing an unnecessary NULL argument for __kmalloc_nolock() with buckets enabled. Made bloat-o-meter happier a bit.

[...]

Looks reasonable to me, thanks!

Signature · 2 lines
Cheers,
Harry / Hyeonggon
author maintainer Reviewed-by
#17 lore raw
In reply to Vlastimil Babka (SUSE)
Quoted 92 lines · Vlastimil Babka (SUSE)
Quoted 80 lines · Marco Elver

Rework the general infrastructure around RANDOM_KMALLOC_CACHES into more flexible KMALLOC_PARTITION_CACHES, with the former being a partitioning mode of the latter.

Introduce a new mode, KMALLOC_PARTITION_TYPED, which leverages a feature available in Clang 22 and later, called "allocation tokens" via __builtin_infer_alloc_token() [1]. Unlike KMALLOC_PARTITION_RANDOM (formerly RANDOM_KMALLOC_CACHES), this mode deterministically assigns a slab cache to an allocation of type T, regardless of allocation site.

The builtin __builtin_infer_alloc_token(<malloc-args>, ...) instructs the compiler to infer an allocation type from arguments commonly passed to memory-allocating functions and returns a type-derived token ID. The implementation passes kmalloc-args to the builtin: the compiler performs best-effort type inference, and then recognizes common patterns such as kmalloc(sizeof(T), ...), kmalloc(sizeof(T) * n, ...), but also (T *)kmalloc(...). Where the compiler fails to infer a type the fallback token (default: 0) is chosen.

Note: kmalloc_obj(..) APIs fix the pattern how size and result type are expressed, and therefore ensures there's not much drift in which patterns the compiler needs to recognize. Specifically, kmalloc_obj() and friends expand to (TYPE *)KMALLOC(__obj_size, GFP), which the compiler recognizes via the cast to TYPE*.

Clang's default token ID calculation is described as [1]:

typehashpointersplit: This mode assigns a token ID based on the hash of the allocated type's name, where the top half ID-space is reserved for types that contain pointers and the bottom half for types that do not contain pointers.

Separating pointer-containing objects from pointerless objects and data allocations can help mitigate certain classes of memory corruption exploits [2]: attackers who gains a buffer overflow on a primitive buffer cannot use it to directly corrupt pointers or other critical metadata in an object residing in a different, isolated heap region.

It is important to note that heap isolation strategies offer a best-effort approach, and do not provide a 100% security guarantee, albeit achievable at relatively low performance cost. Note that this also does not prevent cross-cache attacks: while waiting for future features like SLAB_VIRTUAL [3] to provide physical page isolation, this feature should be deployed alongside SHUFFLE_PAGE_ALLOCATOR and init_on_free=1 to mitigate cross-cache attacks and page-reuse attacks as much as possible today.

With all that, my kernel (x86 defconfig) shows me a histogram of slab cache object distribution per /proc/slabinfo (after boot):

<slab cache> <objs> <hist>

  kmalloc-part-15    1465  ++++++++++++++
  kmalloc-part-14    2988  +++++++++++++++++++++++++++++
  kmalloc-part-13    1656  ++++++++++++++++
  kmalloc-part-12    1045  ++++++++++
  kmalloc-part-11    1697  ++++++++++++++++
  kmalloc-part-10    1489  ++++++++++++++
  kmalloc-part-09     965  +++++++++
  kmalloc-part-08     710  +++++++
  kmalloc-part-07     100  +
  kmalloc-part-06     217  ++
  kmalloc-part-05     105  +
  kmalloc-part-04    4047  ++++++++++++++++++++++++++++++++++++++++
  kmalloc-part-03     183  +
  kmalloc-part-02     283  ++
  kmalloc-part-01     316  +++
  kmalloc            1422  ++++++++++++++

The above /proc/slabinfo snapshot shows me there are 6673 allocated objects (slabs 00 - 07) that the compiler claims contain no pointers or it was unable to infer the type of, and 12015 objects that contain pointers (slabs 08 - 15). On a whole, this looks relatively sane.

Additionally, when I compile my kernel with -Rpass=alloc-token, which provides diagnostics where (after dead-code elimination) type inference failed, I see 186 allocation sites where the compiler failed to identify a type (down from 966 when I sent the RFC [4]). Some initial review confirms these are mostly variable sized buffers, but also include structs with trailing flexible length arrays.

Quoted 9 lines
Quoted 4 lines

Applied [1] to slab/for-next, thanks. That means including the kernel-doc workarounds in patch 3. I know Jon said someone might hate it, but maybe it will motivate them for creating a proper fix :) It seems better than leaving doc generation broken or not applying this series at all.

Thanks!

Quoted 4 lines

https://git.kernel.org/pub/scm/linux/kernel/git/vbabka/slab.git/log/?h=slab/for-7.2/alloc_token

I did the following fixup to remove passing an unnecessary NULL argument for __kmalloc_nolock() with buckets enabled. Made bloat-o-meter happier a bit.

Good.

Quoted 29 lines
include/linux/slab.h +2 -2
index c232f8a10af6..795455256329 100644
@@ -894,7 +894,7 @@ unsigned int kmem_cache_sheaf_size(struct slab_sheaf *sheaf);
  * with the exception of kunit tests
  */
 
-void *__kmalloc_noprof(DECL_KMALLOC_PARAMS(size, b, token), gfp_t flags)
+void *__kmalloc_noprof(DECL_TOKEN_PARAMS(size, token), gfp_t flags)
                                __assume_kmalloc_alignment __alloc_size(1);
 
 void *__kmalloc_node_noprof(DECL_KMALLOC_PARAMS(size, b, token), gfp_t flags, int node)
@@ -981,7 +981,7 @@ static __always_inline __alloc_size(1) void *_kmalloc_noprof(size_t size, gfp_t
                                kmalloc_caches[kmalloc_type(flags, token)][index],
                                flags, size);
        }
-       return __kmalloc_noprof(PASS_KMALLOC_PARAMS(size, NULL, token), flags);
+       return __kmalloc_noprof(PASS_TOKEN_PARAMS(size, token), flags);
 }
 #define kmalloc_noprof(...)                    _kmalloc_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
 #define kmalloc(...)                           alloc_hooks(kmalloc_noprof(__VA_ARGS__))
mm/slub.c +0 -0
index a6e9015601d6..74652bbdd591 100644
@@ -5303,10 +5303,10 @@ void *__kmalloc_node_noprof(DECL_KMALLOC_PARAMS(size, b, token), gfp_t flags, in
 }
 EXPORT_SYMBOL(__kmalloc_node_noprof);

mm/slub.c void *__kmalloc_node_noprof(DECL_KMALLOC_PARAMS(size, b, token), gfp_t flags, in · line 5311

Quoted 10 lines
mm/slub.c +3 -3
 
-void *__kmalloc_noprof(DECL_KMALLOC_PARAMS(size, b, token), gfp_t flags)
+void *__kmalloc_noprof(DECL_TOKEN_PARAMS(size, token), gfp_t flags)
 {
-       return __do_kmalloc_node(size, PASS_BUCKET_PARAM(b), flags,
-                                NUMA_NO_NODE, _RET_IP_, PASS_TOKEN_PARAM(token));
+       return __do_kmalloc_node(size, NULL, flags,  NUMA_NO_NODE, _RET_IP_,
+                                PASS_TOKEN_PARAM(token));
 }
 EXPORT_SYMBOL(__kmalloc_noprof);

Thanks!

#18 lore raw
In reply to Marco Elver
Quoted 51 lines · Marco Elver

Rework the general infrastructure around RANDOM_KMALLOC_CACHES into more flexible KMALLOC_PARTITION_CACHES, with the former being a partitioning mode of the latter.

Introduce a new mode, KMALLOC_PARTITION_TYPED, which leverages a feature available in Clang 22 and later, called "allocation tokens" via __builtin_infer_alloc_token() [1]. Unlike KMALLOC_PARTITION_RANDOM (formerly RANDOM_KMALLOC_CACHES), this mode deterministically assigns a slab cache to an allocation of type T, regardless of allocation site.

The builtin __builtin_infer_alloc_token(<malloc-args>, ...) instructs the compiler to infer an allocation type from arguments commonly passed to memory-allocating functions and returns a type-derived token ID. The implementation passes kmalloc-args to the builtin: the compiler performs best-effort type inference, and then recognizes common patterns such as kmalloc(sizeof(T), ...), kmalloc(sizeof(T) * n, ...), but also (T *)kmalloc(...). Where the compiler fails to infer a type the fallback token (default: 0) is chosen.

Note: kmalloc_obj(..) APIs fix the pattern how size and result type are expressed, and therefore ensures there's not much drift in which patterns the compiler needs to recognize. Specifically, kmalloc_obj() and friends expand to (TYPE *)KMALLOC(__obj_size, GFP), which the compiler recognizes via the cast to TYPE*.

Clang's default token ID calculation is described as [1]:

typehashpointersplit: This mode assigns a token ID based on the hash of the allocated type's name, where the top half ID-space is reserved for types that contain pointers and the bottom half for types that do not contain pointers.

Separating pointer-containing objects from pointerless objects and data allocations can help mitigate certain classes of memory corruption exploits [2]: attackers who gains a buffer overflow on a primitive buffer cannot use it to directly corrupt pointers or other critical metadata in an object residing in a different, isolated heap region.

It is important to note that heap isolation strategies offer a best-effort approach, and do not provide a 100% security guarantee, albeit achievable at relatively low performance cost. Note that this also does not prevent cross-cache attacks: while waiting for future features like SLAB_VIRTUAL [3] to provide physical page isolation, this feature should be deployed alongside SHUFFLE_PAGE_ALLOCATOR and init_on_free=1 to mitigate cross-cache attacks and page-reuse attacks as much as possible today.

With all that, my kernel (x86 defconfig) shows me a histogram of slab cache object distribution per /proc/slabinfo (after boot):

<slab cache> <objs> <hist>

Quoted 16 lines
  kmalloc-part-15    1465  ++++++++++++++
  kmalloc-part-14    2988  +++++++++++++++++++++++++++++
  kmalloc-part-13    1656  ++++++++++++++++
  kmalloc-part-12    1045  ++++++++++
  kmalloc-part-11    1697  ++++++++++++++++
  kmalloc-part-10    1489  ++++++++++++++
  kmalloc-part-09     965  +++++++++
  kmalloc-part-08     710  +++++++
  kmalloc-part-07     100  +
  kmalloc-part-06     217  ++
  kmalloc-part-05     105  +
  kmalloc-part-04    4047  ++++++++++++++++++++++++++++++++++++++++
  kmalloc-part-03     183  +
  kmalloc-part-02     283  ++
  kmalloc-part-01     316  +++
  kmalloc            1422  ++++++++++++++

Hi,

A couple of questions (I apologise if this was asked before, I wasn't involved in this thread):

1) What's the object behind kmalloc-part-04? I imagine it's a single type getting allocated a lot?

2) The bucketing looks quite skewed. Do you have plans to implement something more similar to what's in the original Apple blog post (with the smaller granularity and all)? I'm asking because most of our types have pointers in some way.

3) Obligatory "how about GCC?" :) I quite like the idea behind this feature, and it would be awesome if it could be more broadly deployed!

In any case, really cool work!

Signature · 1 line
Pedro
author maintainer
#19 lore raw
Quoted 70 lines · Pedro Falcato
Quoted 51 lines · Marco Elver

Rework the general infrastructure around RANDOM_KMALLOC_CACHES into more flexible KMALLOC_PARTITION_CACHES, with the former being a partitioning mode of the latter.

Introduce a new mode, KMALLOC_PARTITION_TYPED, which leverages a feature available in Clang 22 and later, called "allocation tokens" via __builtin_infer_alloc_token() [1]. Unlike KMALLOC_PARTITION_RANDOM (formerly RANDOM_KMALLOC_CACHES), this mode deterministically assigns a slab cache to an allocation of type T, regardless of allocation site.

The builtin __builtin_infer_alloc_token(<malloc-args>, ...) instructs the compiler to infer an allocation type from arguments commonly passed to memory-allocating functions and returns a type-derived token ID. The implementation passes kmalloc-args to the builtin: the compiler performs best-effort type inference, and then recognizes common patterns such as kmalloc(sizeof(T), ...), kmalloc(sizeof(T) * n, ...), but also (T *)kmalloc(...). Where the compiler fails to infer a type the fallback token (default: 0) is chosen.

Note: kmalloc_obj(..) APIs fix the pattern how size and result type are expressed, and therefore ensures there's not much drift in which patterns the compiler needs to recognize. Specifically, kmalloc_obj() and friends expand to (TYPE *)KMALLOC(__obj_size, GFP), which the compiler recognizes via the cast to TYPE*.

Clang's default token ID calculation is described as [1]:

typehashpointersplit: This mode assigns a token ID based on the hash of the allocated type's name, where the top half ID-space is reserved for types that contain pointers and the bottom half for types that do not contain pointers.

Separating pointer-containing objects from pointerless objects and data allocations can help mitigate certain classes of memory corruption exploits [2]: attackers who gains a buffer overflow on a primitive buffer cannot use it to directly corrupt pointers or other critical metadata in an object residing in a different, isolated heap region.

It is important to note that heap isolation strategies offer a best-effort approach, and do not provide a 100% security guarantee, albeit achievable at relatively low performance cost. Note that this also does not prevent cross-cache attacks: while waiting for future features like SLAB_VIRTUAL [3] to provide physical page isolation, this feature should be deployed alongside SHUFFLE_PAGE_ALLOCATOR and init_on_free=1 to mitigate cross-cache attacks and page-reuse attacks as much as possible today.

With all that, my kernel (x86 defconfig) shows me a histogram of slab cache object distribution per /proc/slabinfo (after boot):

<slab cache> <objs> <hist>

Quoted 16 lines
  kmalloc-part-15    1465  ++++++++++++++
  kmalloc-part-14    2988  +++++++++++++++++++++++++++++
  kmalloc-part-13    1656  ++++++++++++++++
  kmalloc-part-12    1045  ++++++++++
  kmalloc-part-11    1697  ++++++++++++++++
  kmalloc-part-10    1489  ++++++++++++++
  kmalloc-part-09     965  +++++++++
  kmalloc-part-08     710  +++++++
  kmalloc-part-07     100  +
  kmalloc-part-06     217  ++
  kmalloc-part-05     105  +
  kmalloc-part-04    4047  ++++++++++++++++++++++++++++++++++++++++
  kmalloc-part-03     183  +
  kmalloc-part-02     283  ++
  kmalloc-part-01     316  +++
  kmalloc            1422  ++++++++++++++
Quoted 7 lines

Hi,

A couple of questions (I apologise if this was asked before, I wasn't involved in this thread):

1) What's the object behind kmalloc-part-04? I imagine it's a single type getting allocated a lot?

That's from __kmemdup_nul().

Quoted 4 lines

2) The bucketing looks quite skewed. Do you have plans to implement something more similar to what's in the original Apple blog post (with the smaller granularity and all)? I'm asking because most of our types have pointers in some way.

Having a scheme more tailored towards kernel data structures would be nice.

But we first need to build experience with this, and get more data. I think I agree with you that a smaller granularty scheme that tries to bucket similarly-shaped objects (e.g. with a pointer bitmap) will work better for the kernel, but I have no evidence of that yet. We need an analysis of "this scheme would have stopped X out of Y exploit chains". There are plans to look into that. But if an improvement comes out of it, it's just a compiler-flag flip away for the kernel, once the compiler supports it.

There's also what Kees had proposed:
https://lore.kernel.org/lkml/[email protected]/
.. but that trades memory and performance for stronger partitioning. Probably should become another KMALLOC_PARTITION variant.

But if performance and memory usage are a concern (which is the case for environments where I'd like to enable this), we need a smarter token calculation scheme (if the current one is not good enough after some analysis).

Quoted 2 lines

3) Obligatory "how about GCC?" :) I quite like the idea behind this feature, and it would be awesome if it could be more broadly deployed!

+cc linux-toolchains

We'd need __builtin_infer_alloc_token + -falloc-token-max= for kernel support (-fsanitize=alloc-token is not needed if kernel support is all you'd care about):
https://clang.llvm.org/docs/AllocToken.html#querying-token-ids-with-builtin-infer-alloc-token

Thanks,
-- Marco

maintainer
#20 lore raw
Quoted 73 lines · Marco Elver
Quoted 72 lines · Pedro Falcato
Quoted 59 lines · Marco Elver

Rework the general infrastructure around RANDOM_KMALLOC_CACHES into more flexible KMALLOC_PARTITION_CACHES, with the former being a partitioning mode of the latter.

Introduce a new mode, KMALLOC_PARTITION_TYPED, which leverages a feature available in Clang 22 and later, called "allocation tokens" via __builtin_infer_alloc_token() [1]. Unlike KMALLOC_PARTITION_RANDOM (formerly RANDOM_KMALLOC_CACHES), this mode deterministically assigns a slab cache to an allocation of type T, regardless of allocation site.

The builtin __builtin_infer_alloc_token(<malloc-args>, ...) instructs the compiler to infer an allocation type from arguments commonly passed to memory-allocating functions and returns a type-derived token ID. The implementation passes kmalloc-args to the builtin: the compiler performs best-effort type inference, and then recognizes common patterns such as kmalloc(sizeof(T), ...), kmalloc(sizeof(T) * n, ...), but also (T *)kmalloc(...). Where the compiler fails to infer a type the fallback token (default: 0) is chosen.

Note: kmalloc_obj(..) APIs fix the pattern how size and result type are expressed, and therefore ensures there's not much drift in which patterns the compiler needs to recognize. Specifically, kmalloc_obj() and friends expand to (TYPE *)KMALLOC(__obj_size, GFP), which the compiler recognizes via the cast to TYPE*.

Clang's default token ID calculation is described as [1]:

typehashpointersplit: This mode assigns a token ID based on the hash of the allocated type's name, where the top half ID-space is reserved for types that contain pointers and the bottom half for types that do not contain pointers.

Separating pointer-containing objects from pointerless objects and data allocations can help mitigate certain classes of memory corruption exploits [2]: attackers who gains a buffer overflow on a primitive buffer cannot use it to directly corrupt pointers or other critical metadata in an object residing in a different, isolated heap region.

It is important to note that heap isolation strategies offer a best-effort approach, and do not provide a 100% security guarantee, albeit achievable at relatively low performance cost. Note that this also does not prevent cross-cache attacks: while waiting for future features like SLAB_VIRTUAL [3] to provide physical page isolation, this feature should be deployed alongside SHUFFLE_PAGE_ALLOCATOR and init_on_free=1 to mitigate cross-cache attacks and page-reuse attacks as much as possible today.

With all that, my kernel (x86 defconfig) shows me a histogram of slab cache object distribution per /proc/slabinfo (after boot):

   <slab cache>      <objs> <hist>
   kmalloc-part-15    1465  ++++++++++++++
   kmalloc-part-14    2988  +++++++++++++++++++++++++++++
   kmalloc-part-13    1656  ++++++++++++++++
   kmalloc-part-12    1045  ++++++++++
   kmalloc-part-11    1697  ++++++++++++++++
   kmalloc-part-10    1489  ++++++++++++++
   kmalloc-part-09     965  +++++++++
   kmalloc-part-08     710  +++++++
Quoted 8 lines
   kmalloc-part-07     100  +
   kmalloc-part-06     217  ++
   kmalloc-part-05     105  +
   kmalloc-part-04    4047  ++++++++++++++++++++++++++++++++++++++++
   kmalloc-part-03     183  +
   kmalloc-part-02     283  ++
   kmalloc-part-01     316  +++
   kmalloc            1422  ++++++++++++++

Hi,

Quoted 7 lines
Quoted 5 lines

A couple of questions (I apologise if this was asked before, I wasn't involved in this thread):

1) What's the object behind kmalloc-part-04? I imagine it's a single type getting allocated a lot?

That's from __kmemdup_nul().

__kmemdup_nul() is probably a good fit for SLAB_BUCKETS?

Signature · 2 lines
Cheers,
Harry / Hyeonggon