Skip to contentSkip to conversation

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

PATCH Superseded Marco Elver 6 participants 18 messages Apr 24 – May 12

Subsystems (28)

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Marco Elver

author maintainer
#0 lore raw

PATCH v3 1/2 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:
* 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 54e1ae602000..afe663bdb9c0 100644
@@ -989,6 +989,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.545.g6539524ca2-goog
author maintainer
#1 lore raw

PATCH v3 2/2 slab: fix kernel-docs for mm-api

The mm-api kernel-doc comments have been broken for a while, as many documented symbols shifted from being direct function definitions to macros wrapping _noprof implementations during the introduction of allocation tagging (starting with commit 7bd230a26648 "mm/slab: enable slab allocation tagging for kmalloc and friends").

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 and generates warnings and fails to emit the documentation.

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. Converting the variadic macros for the documented APIs to use explicit arguments.

No functional change intended.

---
 include/linux/slab.h | 192 ++++++++++++++++++++++++++++++++-----------
 mm/slub.c            |  98 ----------------------
 2 files changed, 144 insertions(+), 146 deletions(-)
include/linux/slab.h +144 -48
index c232f8a10af6..dcff0da1c01c 100644
@@ -530,7 +530,46 @@ 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))
+/**
+ * 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
+ */
+#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 +952,22 @@ 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__))
 /**
  * kmalloc - allocate kernel memory
  * @size: how many bytes of memory are required.
@@ -968,27 +1023,22 @@ 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__))
+#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__))
+/**
+ * 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.
+ */
+#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 +1165,36 @@ 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__))
 /**
  * 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)
+#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__))
 /**
  * krealloc_array - reallocate memory for an array.
  * @p: pointer to the memory chunk to reallocate
@@ -1149,20 +1212,7 @@ 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__))
+#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 +1264,17 @@ 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__))
+/**
+ * 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).
+ */
+#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 +1283,26 @@ 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)
+/**
+ * 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
+ */
+#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 +1335,35 @@ _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))
+/**
+ * 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
+ */
+#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.545.g6539524ca2-goog
#2 lore raw

Re: [PATCH v3 2/2] slab: fix kernel-docs for mm-api

Quoted 16 lines · Marco Elver

The mm-api kernel-doc comments have been broken for a while, as many documented symbols shifted from being direct function definitions to macros wrapping _noprof implementations during the introduction of allocation tagging (starting with commit 7bd230a26648 "mm/slab: enable slab allocation tagging for kmalloc and friends").

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 and generates warnings and fails to emit the documentation.

Fix this by:

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

Quoted 6 lines

2. Converting the variadic macros for the documented APIs to use explicit arguments.

No functional change intended.

+Cc Jon

I thought it was supposed to work because the kernel-doc scripts were at the time taught by commit 51a7bf0238c2 ("scripts/kernel-doc: drop "_noprof" on function prototypes") to handle _noprof. In the current form git grep finds:

tools/lib/python/kdoc/kdoc_parser.py: suffixes = [ '_noprof' ]
tools/lib/python/kdoc/xforms_lists.py: (KernRe("_noprof"), ""),

Doesn't it work for you then?

author maintainer
#3 lore raw

Re: [PATCH v3 2/2] slab: fix kernel-docs for mm-api

Quoted 27 lines · Vlastimil Babka (SUSE)
Quoted 16 lines · Marco Elver

The mm-api kernel-doc comments have been broken for a while, as many documented symbols shifted from being direct function definitions to macros wrapping _noprof implementations during the introduction of allocation tagging (starting with commit 7bd230a26648 "mm/slab: enable slab allocation tagging for kmalloc and friends").

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 and generates warnings and fails to emit the documentation.

Fix this by:

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

Quoted 6 lines

2. Converting the variadic macros for the documented APIs to use explicit arguments.

No functional change intended.

+Cc Jon

Quoted 8 lines

I thought it was supposed to work because the kernel-doc scripts were at the time taught by commit 51a7bf0238c2 ("scripts/kernel-doc: drop "_noprof" on function prototypes") to handle _noprof. In the current form git grep finds:

tools/lib/python/kdoc/kdoc_parser.py: suffixes = [ '_noprof' ]
tools/lib/python/kdoc/xforms_lists.py: (KernRe("_noprof"), ""),

Doesn't it work for you then?

Ah, I see. So it doesn't work anymore because we add the '_' prefix, too.

I guess the question is if we want to proliferate more kdoc parser special cases, or just move the docs to the macros. The downside of macros is that they lose the types in the displayed function signature.

Preferences?

author maintainer
#4 lore raw

Re: [PATCH v3 2/2] slab: fix kernel-docs for mm-api

Quoted 37 lines · Marco Elver
Quoted 27 lines · Vlastimil Babka (SUSE)
Quoted 16 lines · Marco Elver

The mm-api kernel-doc comments have been broken for a while, as many documented symbols shifted from being direct function definitions to macros wrapping _noprof implementations during the introduction of allocation tagging (starting with commit 7bd230a26648 "mm/slab: enable slab allocation tagging for kmalloc and friends").

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 and generates warnings and fails to emit the documentation.

Fix this by:

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

Quoted 6 lines

2. Converting the variadic macros for the documented APIs to use explicit arguments.

No functional change intended.

+Cc Jon

Quoted 8 lines

I thought it was supposed to work because the kernel-doc scripts were at the time taught by commit 51a7bf0238c2 ("scripts/kernel-doc: drop "_noprof" on function prototypes") to handle _noprof. In the current form git grep finds:

tools/lib/python/kdoc/kdoc_parser.py: suffixes = [ '_noprof' ]
tools/lib/python/kdoc/xforms_lists.py: (KernRe("_noprof"), ""),

Doesn't it work for you then?

Quoted 8 lines

Ah, I see. So it doesn't work anymore because we add the '_' prefix, too.

I guess the question is if we want to proliferate more kdoc parser special cases, or just move the docs to the macros. The downside of macros is that they lose the types in the displayed function signature.

Preferences?

How about the below, i.e. adding type decls that only the kernel-doc parser sees? One complication is also DECL_KMALLOC_PARAMS, and adding kernel-doc parser hacks for that looks pretty awful, so this is a lot cleaner.

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

From: Marco Elver <[email protected]>
Date: Tue, 21 Apr 2026 13:48:21 +0200
Subject: [PATCH] slab: fix kernel-docs for mm-api

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 c232f8a10af6..5e1249e36b0d 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.545.g6539524ca2-goog
#5 lore raw

Re: [PATCH v3 2/2] slab: fix kernel-docs for mm-api

Quoted 45 lines · Marco Elver
Quoted 44 lines · Marco Elver
Quoted 27 lines · Vlastimil Babka (SUSE)
Quoted 16 lines · Marco Elver

The mm-api kernel-doc comments have been broken for a while, as many documented symbols shifted from being direct function definitions to macros wrapping _noprof implementations during the introduction of allocation tagging (starting with commit 7bd230a26648 "mm/slab: enable slab allocation tagging for kmalloc and friends").

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 and generates warnings and fails to emit the documentation.

Fix this by:

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

Quoted 6 lines

2. Converting the variadic macros for the documented APIs to use explicit arguments.

No functional change intended.

+Cc Jon

Quoted 8 lines

I thought it was supposed to work because the kernel-doc scripts were at the time taught by commit 51a7bf0238c2 ("scripts/kernel-doc: drop "_noprof" on function prototypes") to handle _noprof. In the current form git grep finds:

tools/lib/python/kdoc/kdoc_parser.py: suffixes = [ '_noprof' ]
tools/lib/python/kdoc/xforms_lists.py: (KernRe("_noprof"), ""),

Doesn't it work for you then?

Ah, I see. So it doesn't work anymore because we add the '_' prefix, too.

I guess the question is if we want to proliferate more kdoc parser special cases, or just move the docs to the macros. The downside of macros is that they lose the types in the displayed function signature.

Quoted 6 lines
Quoted 1 line

Preferences?

How about the below, i.e. adding type decls that only the kernel-doc parser sees? One complication is also DECL_KMALLOC_PARAMS, and adding kernel-doc parser hacks for that looks pretty awful, so this is a lot cleaner.

Looks like a good workaround to me, unless something gets confused by seeing both the declaration and the define.

maintainer
#6 lore raw

Re: [PATCH v3 2/2] slab: fix kernel-docs for mm-api

In reply to Marco Elver
Quoted 4 lines · Marco Elver

How about the below, i.e. adding type decls that only the kernel-doc parser sees? One complication is also DECL_KMALLOC_PARAMS, and adding kernel-doc parser hacks for that looks pretty awful, so this is a lot cleaner.

I'm going to be a while catching up with things, so this is just a first take. I strongly suspect that the people who object so strongly to documentation markup in general would be less than fully thrilled by the addition of this kind of workaround. I'd like to ponder a bit and see if I can some up with something better...but again, it won't happen right away.

Thanks,

jon

author maintainer
#7 lore raw

Re: [PATCH v3 2/2] slab: fix kernel-docs for mm-api

Quoted 8 lines · Jonathan Corbet
Quoted 4 lines · Marco Elver

How about the below, i.e. adding type decls that only the kernel-doc parser sees? One complication is also DECL_KMALLOC_PARAMS, and adding kernel-doc parser hacks for that looks pretty awful, so this is a lot cleaner.

Quoted 6 lines

I'm going to be a while catching up with things, so this is just a first take. I strongly suspect that the people who object so strongly to documentation markup in general would be less than fully thrilled by the addition of this kind of workaround. I'd like to ponder a bit and see if I can some up with something better...but again, it won't happen right away.

Thanks, Jon.

The technical debt (hacks) that would accumulate in the kernel-doc parser just for accommodating slab.h might be quite high; slab.h is rather special, so the "#if 0" solution might be justified. Then again, if there's a reasonable kernel-doc parser solution, that also helps in other places, I won't object.

I tested the "#if 0" version and it works as expected. So to move forward, we could consider it in the short term, and in the longer term, see what new powers the kernel-doc parser can provide.

#8 lore raw
In reply to Marco Elver
Quoted 10 lines · Marco Elver
include/linux/slab.h +1 -1
@@ -938,7 +968,7 @@ 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)
+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;

include/linux/slab.h static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 981

Quoted 5 lines
include/linux/slab.h +1 -1
@@ -948,14 +978,16 @@ static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f
 
 		index = kmalloc_index(size);
 		return __kmalloc_cache_noprof(
-				kmalloc_caches[kmalloc_type(flags, _RET_IP_)][index],
+				kmalloc_caches[kmalloc_type(flags, token)][index],

While reviewing this, it occured to me we might have been using _RET_IP_ here in a suboptimal way ever since this was introduced. Since this is all inlined, shouldn't have we been using _THIS_IP_ to really randomize using the kmalloc() callsite, and not its parent?

And after this patch, we get the token passed to _kmalloc_noprof()...

include/linux/slab.h static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 984

Quoted 4 lines
include/linux/slab.h +1 -1
 				flags, size);
 	}
-	return __kmalloc_noprof(size, flags);
+	return __kmalloc_noprof(PASS_KMALLOC_PARAMS(size, NULL, token), flags);

... and used also here for the non-constant-size, where previously __kmalloc_noprof() (not inline function) would correctly use _RET_IP_ on its own ...

include/linux/slab.h static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 986

Quoted 2 lines
include/linux/slab.h +1 -0
 }
+#define kmalloc_noprof(...)			_kmalloc_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))

... and the token comes from here. With random partitioning that's #define __kmalloc_token(...) ((kmalloc_token_t){ .v = _RET_IP_ })

so that AFAIK makes the situation worse as now the cases without constant size also start randomizing by the parent callsite and not the kmalloc callsite.

But there are many users of __kmalloc_token() and maybe some are corrent in using _RET_IP_, I haven't checked, maybe we'll need two variants, or further change things around.

Quoted 8 lines
include/linux/slab.h +2 -1
 #define kmalloc(...)				alloc_hooks(kmalloc_noprof(__VA_ARGS__))
 
-void *kmalloc_nolock_noprof(size_t size, gfp_t gfp_flags, int node);
+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__))
 
 /**

<snip>

Quoted 32 lines
mm/slab_common.c +11 -20
-#ifdef CONFIG_RANDOM_KMALLOC_CACHES
-#define __KMALLOC_RANDOM_CONCAT(a, b) a ## b
-#define KMALLOC_RANDOM_NAME(N, sz) __KMALLOC_RANDOM_CONCAT(KMA_RAND_, N)(sz)
-#define KMA_RAND_1(sz)                  .name[KMALLOC_RANDOM_START +  1] = "kmalloc-rnd-01-" #sz,
-#define KMA_RAND_2(sz)  KMA_RAND_1(sz)  .name[KMALLOC_RANDOM_START +  2] = "kmalloc-rnd-02-" #sz,
-#define KMA_RAND_3(sz)  KMA_RAND_2(sz)  .name[KMALLOC_RANDOM_START +  3] = "kmalloc-rnd-03-" #sz,
-#define KMA_RAND_4(sz)  KMA_RAND_3(sz)  .name[KMALLOC_RANDOM_START +  4] = "kmalloc-rnd-04-" #sz,
-#define KMA_RAND_5(sz)  KMA_RAND_4(sz)  .name[KMALLOC_RANDOM_START +  5] = "kmalloc-rnd-05-" #sz,
-#define KMA_RAND_6(sz)  KMA_RAND_5(sz)  .name[KMALLOC_RANDOM_START +  6] = "kmalloc-rnd-06-" #sz,
-#define KMA_RAND_7(sz)  KMA_RAND_6(sz)  .name[KMALLOC_RANDOM_START +  7] = "kmalloc-rnd-07-" #sz,
-#define KMA_RAND_8(sz)  KMA_RAND_7(sz)  .name[KMALLOC_RANDOM_START +  8] = "kmalloc-rnd-08-" #sz,
-#define KMA_RAND_9(sz)  KMA_RAND_8(sz)  .name[KMALLOC_RANDOM_START +  9] = "kmalloc-rnd-09-" #sz,
-#define KMA_RAND_10(sz) KMA_RAND_9(sz)  .name[KMALLOC_RANDOM_START + 10] = "kmalloc-rnd-10-" #sz,
-#define KMA_RAND_11(sz) KMA_RAND_10(sz) .name[KMALLOC_RANDOM_START + 11] = "kmalloc-rnd-11-" #sz,
-#define KMA_RAND_12(sz) KMA_RAND_11(sz) .name[KMALLOC_RANDOM_START + 12] = "kmalloc-rnd-12-" #sz,
-#define KMA_RAND_13(sz) KMA_RAND_12(sz) .name[KMALLOC_RANDOM_START + 13] = "kmalloc-rnd-13-" #sz,
-#define KMA_RAND_14(sz) KMA_RAND_13(sz) .name[KMALLOC_RANDOM_START + 14] = "kmalloc-rnd-14-" #sz,
-#define KMA_RAND_15(sz) KMA_RAND_14(sz) .name[KMALLOC_RANDOM_START + 15] = "kmalloc-rnd-15-" #sz,
-#else // CONFIG_RANDOM_KMALLOC_CACHES
-#define KMALLOC_RANDOM_NAME(N, sz)
+#ifdef CONFIG_KMALLOC_PARTITION_CACHES
+#define __KMALLOC_PARTITION_CONCAT(a, b) a ## b
+#define KMALLOC_PARTITION_NAME(N, sz) __KMALLOC_PARTITION_CONCAT(KMA_PART_, N)(sz)
+#define KMA_PART_1(sz)                  .name[KMALLOC_PARTITION_START +  1] = "kmalloc-part-01-" #sz,
+#define KMA_PART_2(sz)  KMA_PART_1(sz)  .name[KMALLOC_PARTITION_START +  2] = "kmalloc-part-02-" #sz,
+#define KMA_PART_3(sz)  KMA_PART_2(sz)  .name[KMALLOC_PARTITION_START +  3] = "kmalloc-part-03-" #sz,
+#define KMA_PART_4(sz)  KMA_PART_3(sz)  .name[KMALLOC_PARTITION_START +  4] = "kmalloc-part-04-" #sz,
+#define KMA_PART_5(sz)  KMA_PART_4(sz)  .name[KMALLOC_PARTITION_START +  5] = "kmalloc-part-05-" #sz,
+#define KMA_PART_6(sz)  KMA_PART_5(sz)  .name[KMALLOC_PARTITION_START +  6] = "kmalloc-part-06-" #sz,
+#define KMA_PART_7(sz)  KMA_PART_6(sz)  .name[KMALLOC_PARTITION_START +  7] = "kmalloc-part-07-" #sz,
+#define KMA_PART_8(sz)  KMA_PART_7(sz)  .name[KMALLOC_PARTITION_START +  8] = "kmalloc-part-08-" #sz,

mm/slab_common.c EXPORT_SYMBOL(kmalloc_size_roundup); · line 844

Quoted 10 lines
mm/slab_common.c +9 -0
+#define KMA_PART_9(sz)  KMA_PART_8(sz)  .name[KMALLOC_PARTITION_START +  9] = "kmalloc-part-09-" #sz,
+#define KMA_PART_10(sz) KMA_PART_9(sz)  .name[KMALLOC_PARTITION_START + 10] = "kmalloc-part-10-" #sz,
+#define KMA_PART_11(sz) KMA_PART_10(sz) .name[KMALLOC_PARTITION_START + 11] = "kmalloc-part-11-" #sz,
+#define KMA_PART_12(sz) KMA_PART_11(sz) .name[KMALLOC_PARTITION_START + 12] = "kmalloc-part-12-" #sz,
+#define KMA_PART_13(sz) KMA_PART_12(sz) .name[KMALLOC_PARTITION_START + 13] = "kmalloc-part-13-" #sz,
+#define KMA_PART_14(sz) KMA_PART_13(sz) .name[KMALLOC_PARTITION_START + 14] = "kmalloc-part-14-" #sz,
+#define KMA_PART_15(sz) KMA_PART_14(sz) .name[KMALLOC_PARTITION_START + 15] = "kmalloc-part-15-" #sz,
+#else // CONFIG_KMALLOC_PARTITION_CACHES
+#define KMALLOC_PARTITION_NAME(N, sz)
 #endif

We're renaming the caches visible in /proc/slabinfo. Maybe it's fine as people who care will just adapt their tools without complaining. Not the first time we've changes something here.

author maintainer
#9 lore raw
Quoted 40 lines · Vlastimil Babka (SUSE)
Quoted 10 lines · Marco Elver
(quoted diff) +1 -1
@@ -938,7 +968,7 @@ 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)
+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;

Review static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 981

Quoted 5 lines
(quoted diff) +1 -1
@@ -948,14 +978,16 @@ static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f
 
 		index = kmalloc_index(size);
 		return __kmalloc_cache_noprof(
-				kmalloc_caches[kmalloc_type(flags, _RET_IP_)][index],
+				kmalloc_caches[kmalloc_type(flags, token)][index],

While reviewing this, it occured to me we might have been using _RET_IP_ here in a suboptimal way ever since this was introduced. Since this is all inlined, shouldn't have we been using _THIS_IP_ to really randomize using the kmalloc() callsite, and not its parent?

And after this patch, we get the token passed to _kmalloc_noprof()...

Review static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 984

Quoted 4 lines
(quoted diff) +1 -1
 				flags, size);
 	}
-	return __kmalloc_noprof(size, flags);
+	return __kmalloc_noprof(PASS_KMALLOC_PARAMS(size, NULL, token), flags);

... and used also here for the non-constant-size, where previously __kmalloc_noprof() (not inline function) would correctly use _RET_IP_ on its own ...

Review static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 986

Quoted 2 lines
(quoted diff) +1 -0
 }
+#define kmalloc_noprof(...)			_kmalloc_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))

... and the token comes from here. With random partitioning that's #define __kmalloc_token(...) ((kmalloc_token_t){ .v = _RET_IP_ })

Quoted 6 lines

so that AFAIK makes the situation worse as now the cases without constant size also start randomizing by the parent callsite and not the kmalloc callsite.

But there are many users of __kmalloc_token() and maybe some are corrent in using _RET_IP_, I haven't checked, maybe we'll need two variants, or further change things around.

Good catch. I don't think we need multiple variants (otherwise the TYPED variant would be broken) - we're moving token generation to the callers (not even inlined anymore) with all this macro magic.

I think this is all we need:

include/linux/slab.h +1 -1
@@ -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 = _THIS_IP_ })
 #elif defined(CONFIG_KMALLOC_PARTITION_TYPED)
 #define __kmalloc_token(...) ((kmalloc_token_t){ .v = __builtin_infer_alloc_token(__VA_ARGS__) })
 #endif

Plus a paragraph in the commit message. Let me add that.

author maintainer
#10 lore raw
Quoted 67 lines · Marco Elver
Quoted 40 lines · Vlastimil Babka (SUSE)
Quoted 10 lines · Marco Elver
(quoted diff) +1 -1
@@ -938,7 +968,7 @@ 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)
+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;

Review static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 981

Quoted 5 lines
(quoted diff) +1 -1
@@ -948,14 +978,16 @@ static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f
 
            index = kmalloc_index(size);
            return __kmalloc_cache_noprof(
-                           kmalloc_caches[kmalloc_type(flags, _RET_IP_)][index],
+                           kmalloc_caches[kmalloc_type(flags, token)][index],

While reviewing this, it occured to me we might have been using _RET_IP_ here in a suboptimal way ever since this was introduced. Since this is all inlined, shouldn't have we been using _THIS_IP_ to really randomize using the kmalloc() callsite, and not its parent?

And after this patch, we get the token passed to _kmalloc_noprof()...

Review static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 984

Quoted 4 lines
(quoted diff) +1 -1
                            flags, size);
    }
-   return __kmalloc_noprof(size, flags);
+   return __kmalloc_noprof(PASS_KMALLOC_PARAMS(size, NULL, token), flags);

... and used also here for the non-constant-size, where previously __kmalloc_noprof() (not inline function) would correctly use _RET_IP_ on its own ...

Review static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 986

Quoted 2 lines
(quoted diff) +1 -0
 }
+#define kmalloc_noprof(...)                        _kmalloc_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))

... and the token comes from here. With random partitioning that's #define __kmalloc_token(...) ((kmalloc_token_t){ .v = _RET_IP_ })

Quoted 6 lines

so that AFAIK makes the situation worse as now the cases without constant size also start randomizing by the parent callsite and not the kmalloc callsite.

But there are many users of __kmalloc_token() and maybe some are corrent in using _RET_IP_, I haven't checked, maybe we'll need two variants, or further change things around.

Good catch. I don't think we need multiple variants (otherwise the TYPED variant would be broken) - we're moving token generation to the callers (not even inlined anymore) with all this macro magic.

I think this is all we need:

include/linux/slab.h +1 -1
@@ -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 = _THIS_IP_ })
 #elif defined(CONFIG_KMALLOC_PARTITION_TYPED)
 #define __kmalloc_token(...) ((kmalloc_token_t){ .v = __builtin_infer_alloc_token(__VA_ARGS__) })
 #endif
Quoted 1 line

Plus a paragraph in the commit message. Let me add that.

Bah, this is why it doesn't work:

Quoted 1 line
Quoted 1 line

drivers/gpu/drm/msm/msm_gpu.c:272:4: error: cannot jump from this indirect goto statement to one of its possible targets

     272 |                         drm_exec_retry_on_contention(&exec);
         |                         ^
   include/drm/drm_exec.h:123:4: note: expanded from macro
'drm_exec_retry_on_contention'
     123 |                         goto *__drm_exec_retry_ptr;             \
         |                         ^
   drivers/gpu/drm/msm/msm_gpu.c:304:16: note: possible target of
indirect goto statement
     304 |                 state->bos = kcalloc(submit->nr_bos,
         |                              ^

include/linux/slab.h:1173:34: note: expanded from macro 'kcalloc'
1173 | #define kcalloc(n, size, flags) kmalloc_array(n,
size, (flags) | __GFP_ZERO)
| ^
include/linux/slab.h:1133:42: note: expanded from macro 'kmalloc_array'

    1133 | #define kmalloc_array(...)

alloc_hooks(kmalloc_array_noprof(__VA_ARGS__))
| ^
include/linux/slab.h:1132:71: note: expanded from macro
'kmalloc_array_noprof'

    1132 | #define kmalloc_array_noprof(...)
_kmalloc_array_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
         |
                       ^
   include/linux/slab.h:506:55: note: expanded from macro '__kmalloc_token'
     506 | #define __kmalloc_token(...) ((kmalloc_token_t){ .v = _THIS_IP_ })
         |                                                       ^
   include/linux/instruction_pointer.h:10:41: note: expanded from
macro '_THIS_IP_'
      10 | #define _THIS_IP_  ({ __label__ __here; __here: (unsigned

long)&&__here; })
| ^
drivers/gpu/drm/msm/msm_gpu.c:304:16: note: jump enters a statement
expression

Apparently using _THIS_IP_ creates a possible indirect jump target, but because it's in a statement expression, it's invalid, so the compiler complains. This is obviously nonsense, because the actual indirect jump in this gpu driver code would never jump to the _THIS_IP_ __here label, but that's what it is.

Given this pre-existing issue, we probably need to continue using _RET_IP_, as before. I tried to fix _THIS_IP_, but it's incredibly brittle (e.g. __always_inline function returning address of label doesn't work on Clang, but would on GCC).

#11 lore raw
Quoted 45 lines · Marco Elver

Bah, this is why it doesn't work:

Quoted 1 line
Quoted 1 line

drivers/gpu/drm/msm/msm_gpu.c:272:4: error: cannot jump from this indirect goto statement to one of its possible targets

     272 |                         drm_exec_retry_on_contention(&exec);
         |                         ^
   include/drm/drm_exec.h:123:4: note: expanded from macro
'drm_exec_retry_on_contention'
     123 |                         goto *__drm_exec_retry_ptr;             \
         |                         ^
   drivers/gpu/drm/msm/msm_gpu.c:304:16: note: possible target of
indirect goto statement
     304 |                 state->bos = kcalloc(submit->nr_bos,
         |                              ^

include/linux/slab.h:1173:34: note: expanded from macro 'kcalloc'
1173 | #define kcalloc(n, size, flags) kmalloc_array(n,
size, (flags) | __GFP_ZERO)
| ^
include/linux/slab.h:1133:42: note: expanded from macro 'kmalloc_array'

    1133 | #define kmalloc_array(...)

alloc_hooks(kmalloc_array_noprof(__VA_ARGS__))
| ^
include/linux/slab.h:1132:71: note: expanded from macro
'kmalloc_array_noprof'

    1132 | #define kmalloc_array_noprof(...)
_kmalloc_array_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
         |
                       ^
   include/linux/slab.h:506:55: note: expanded from macro '__kmalloc_token'
     506 | #define __kmalloc_token(...) ((kmalloc_token_t){ .v = _THIS_IP_ })
         |                                                       ^
   include/linux/instruction_pointer.h:10:41: note: expanded from
macro '_THIS_IP_'
      10 | #define _THIS_IP_  ({ __label__ __here; __here: (unsigned

long)&&__here; })
| ^
drivers/gpu/drm/msm/msm_gpu.c:304:16: note: jump enters a statement
expression

Apparently using _THIS_IP_ creates a possible indirect jump target, but because it's in a statement expression, it's invalid, so the compiler complains. This is obviously nonsense, because the actual indirect jump in this gpu driver code would never jump to the _THIS_IP_ __here label, but that's what it is.

Quoted 4 lines

Given this pre-existing issue, we probably need to continue using _RET_IP_, as before. I tried to fix _THIS_IP_, but it's incredibly brittle (e.g. __always_inline function returning address of label doesn't work on Clang, but would on GCC).

For what it's worth, both LLVM and GCC consider the generic version of _THIS_IP_ to be broken (even if it works currently), as the address of a label is only expected to be used with a computed goto (hence the clang error above, it just looks for possible computed goto targets):

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=44298
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120071
https://github.com/llvm/llvm-project/issues/138272

Signature · 2 lines
Cheers,
Nathan
#12 lore raw
In reply to Marco Elver
Quoted 57 lines · Marco Elver
Quoted 56 lines · Marco Elver
Quoted 30 lines · Vlastimil Babka (SUSE)

Review static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 981

Quoted 6 lines · Marco Elver
(quoted diff) +1 -1
@@ -948,14 +978,16 @@ static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f
 
            index = kmalloc_index(size);
            return __kmalloc_cache_noprof(
-                           kmalloc_caches[kmalloc_type(flags, _RET_IP_)][index],
+                           kmalloc_caches[kmalloc_type(flags, token)][index],

While reviewing this, it occured to me we might have been using _RET_IP_ here in a suboptimal way ever since this was introduced. Since this is all inlined, shouldn't have we been using _THIS_IP_ to really randomize using the kmalloc() callsite, and not its parent?

And after this patch, we get the token passed to _kmalloc_noprof()...

Review static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 984

Quoted 4 lines
(quoted diff) +1 -1
                            flags, size);
    }
-   return __kmalloc_noprof(size, flags);
+   return __kmalloc_noprof(PASS_KMALLOC_PARAMS(size, NULL, token), flags);

... and used also here for the non-constant-size, where previously __kmalloc_noprof() (not inline function) would correctly use _RET_IP_ on its own ...

Review static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 986

Quoted 2 lines
(quoted diff) +1 -0
 }
+#define kmalloc_noprof(...)                        _kmalloc_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))

... and the token comes from here. With random partitioning that's #define __kmalloc_token(...) ((kmalloc_token_t){ .v = _RET_IP_ })

Quoted 6 lines

so that AFAIK makes the situation worse as now the cases without constant size also start randomizing by the parent callsite and not the kmalloc callsite.

But there are many users of __kmalloc_token() and maybe some are corrent in using _RET_IP_, I haven't checked, maybe we'll need two variants, or further change things around.

Good catch. I don't think we need multiple variants (otherwise the TYPED variant would be broken) - we're moving token generation to the callers (not even inlined anymore) with all this macro magic.

I think this is all we need:

include/linux/slab.h +1 -1
@@ -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 = _THIS_IP_ })
 #elif defined(CONFIG_KMALLOC_PARTITION_TYPED)
 #define __kmalloc_token(...) ((kmalloc_token_t){ .v = __builtin_infer_alloc_token(__VA_ARGS__) })
 #endif
Quoted 1 line
Quoted 1 line

Plus a paragraph in the commit message. Let me add that.

Err, I was like "yes, this is the way to go!"

and then...

Quoted 33 lines

Bah, this is why it doesn't work:

Quoted 1 line
Quoted 1 line

drivers/gpu/drm/msm/msm_gpu.c:272:4: error: cannot jump from this indirect goto statement to one of its possible targets

     272 |                         drm_exec_retry_on_contention(&exec);
         |                         ^
   include/drm/drm_exec.h:123:4: note: expanded from macro
'drm_exec_retry_on_contention'
     123 |                         goto *__drm_exec_retry_ptr;             \
         |                         ^
   drivers/gpu/drm/msm/msm_gpu.c:304:16: note: possible target of
indirect goto statement
     304 |                 state->bos = kcalloc(submit->nr_bos,
         |                              ^

include/linux/slab.h:1173:34: note: expanded from macro 'kcalloc'
1173 | #define kcalloc(n, size, flags) kmalloc_array(n,
size, (flags) | __GFP_ZERO)
| ^
include/linux/slab.h:1133:42: note: expanded from macro 'kmalloc_array'

    1133 | #define kmalloc_array(...)

alloc_hooks(kmalloc_array_noprof(__VA_ARGS__))
| ^
include/linux/slab.h:1132:71: note: expanded from macro
'kmalloc_array_noprof'

    1132 | #define kmalloc_array_noprof(...)
_kmalloc_array_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
         |
                       ^
   include/linux/slab.h:506:55: note: expanded from macro '__kmalloc_token'
     506 | #define __kmalloc_token(...) ((kmalloc_token_t){ .v = _THIS_IP_ })
         |                                                       ^
   include/linux/instruction_pointer.h:10:41: note: expanded from
macro '_THIS_IP_'
      10 | #define _THIS_IP_  ({ __label__ __here; __here: (unsigned
Quoted 6 lines

long)&&__here; })
| ^
drivers/gpu/drm/msm/msm_gpu.c:304:16: note: jump enters a statement
expression

Apparently using _THIS_IP_ creates a possible indirect jump target,

Didn't even realize people use indirect gotos, heh :)

Quoted 4 lines

but because it's in a statement expression, it's invalid, so the compiler complains. This is obviously nonsense, because the actual indirect jump in this gpu driver code would never jump to the _THIS_IP_ __here label, but that's what it is.

Yeah, I guess it's quite tricky to handle when you don't know where it'd jump to as it's an indirect one, and there's an invalid jump label...

Quoted 2 lines

Given this pre-existing issue, we probably need to continue using _RET_IP_, as before.

Agreed!

Signature · 2 lines
Cheers,
Harry / Hyeonggon
author maintainer
#13 lore raw
Quoted 106 lines · Harry Yoo (Oracle)' via kasan-dev
Quoted 57 lines · Marco Elver
Quoted 56 lines · Marco Elver
Quoted 30 lines · Vlastimil Babka (SUSE)

Review static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 981

Quoted 6 lines · Marco Elver
(quoted diff) +1 -1
@@ -948,14 +978,16 @@ static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f
 
            index = kmalloc_index(size);
            return __kmalloc_cache_noprof(
-                           kmalloc_caches[kmalloc_type(flags, _RET_IP_)][index],
+                           kmalloc_caches[kmalloc_type(flags, token)][index],

While reviewing this, it occured to me we might have been using _RET_IP_ here in a suboptimal way ever since this was introduced. Since this is all inlined, shouldn't have we been using _THIS_IP_ to really randomize using the kmalloc() callsite, and not its parent?

And after this patch, we get the token passed to _kmalloc_noprof()...

Review static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 984

Quoted 4 lines
(quoted diff) +1 -1
                            flags, size);
    }
-   return __kmalloc_noprof(size, flags);
+   return __kmalloc_noprof(PASS_KMALLOC_PARAMS(size, NULL, token), flags);

... and used also here for the non-constant-size, where previously __kmalloc_noprof() (not inline function) would correctly use _RET_IP_ on its own ...

Review static __always_inline __alloc_size(1) void *kmalloc_noprof(size_t size, gfp_t f · line 986

Quoted 2 lines
(quoted diff) +1 -0
 }
+#define kmalloc_noprof(...)                        _kmalloc_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))

... and the token comes from here. With random partitioning that's #define __kmalloc_token(...) ((kmalloc_token_t){ .v = _RET_IP_ })

Quoted 6 lines

so that AFAIK makes the situation worse as now the cases without constant size also start randomizing by the parent callsite and not the kmalloc callsite.

But there are many users of __kmalloc_token() and maybe some are corrent in using _RET_IP_, I haven't checked, maybe we'll need two variants, or further change things around.

Good catch. I don't think we need multiple variants (otherwise the TYPED variant would be broken) - we're moving token generation to the callers (not even inlined anymore) with all this macro magic.

I think this is all we need:

include/linux/slab.h +1 -1
@@ -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 = _THIS_IP_ })
 #elif defined(CONFIG_KMALLOC_PARTITION_TYPED)
 #define __kmalloc_token(...) ((kmalloc_token_t){ .v = __builtin_infer_alloc_token(__VA_ARGS__) })
 #endif
Quoted 1 line
Quoted 1 line

Plus a paragraph in the commit message. Let me add that.

Err, I was like "yes, this is the way to go!"

and then...

Quoted 33 lines

Bah, this is why it doesn't work:

Quoted 1 line
Quoted 1 line

drivers/gpu/drm/msm/msm_gpu.c:272:4: error: cannot jump from this indirect goto statement to one of its possible targets

     272 |                         drm_exec_retry_on_contention(&exec);
         |                         ^
   include/drm/drm_exec.h:123:4: note: expanded from macro
'drm_exec_retry_on_contention'
     123 |                         goto *__drm_exec_retry_ptr;             \
         |                         ^
   drivers/gpu/drm/msm/msm_gpu.c:304:16: note: possible target of
indirect goto statement
     304 |                 state->bos = kcalloc(submit->nr_bos,
         |                              ^

include/linux/slab.h:1173:34: note: expanded from macro 'kcalloc'
1173 | #define kcalloc(n, size, flags) kmalloc_array(n,
size, (flags) | __GFP_ZERO)
| ^
include/linux/slab.h:1133:42: note: expanded from macro 'kmalloc_array'

    1133 | #define kmalloc_array(...)

alloc_hooks(kmalloc_array_noprof(__VA_ARGS__))
| ^
include/linux/slab.h:1132:71: note: expanded from macro
'kmalloc_array_noprof'

    1132 | #define kmalloc_array_noprof(...)
_kmalloc_array_noprof(__VA_ARGS__, __kmalloc_token(__VA_ARGS__))
         |
                       ^
   include/linux/slab.h:506:55: note: expanded from macro '__kmalloc_token'
     506 | #define __kmalloc_token(...) ((kmalloc_token_t){ .v = _THIS_IP_ })
         |                                                       ^
   include/linux/instruction_pointer.h:10:41: note: expanded from
macro '_THIS_IP_'
      10 | #define _THIS_IP_  ({ __label__ __here; __here: (unsigned
Quoted 6 lines

long)&&__here; })
| ^
drivers/gpu/drm/msm/msm_gpu.c:304:16: note: jump enters a statement
expression

Apparently using _THIS_IP_ creates a possible indirect jump target,

Didn't even realize people use indirect gotos, heh :)

Quoted 11 lines
Quoted 4 lines

but because it's in a statement expression, it's invalid, so the compiler complains. This is obviously nonsense, because the actual indirect jump in this gpu driver code would never jump to the _THIS_IP_ __here label, but that's what it is.

Yeah, I guess it's quite tricky to handle when you don't know where it'd jump to as it's an indirect one, and there's an invalid jump label...

Quoted 2 lines

Given this pre-existing issue, we probably need to continue using _RET_IP_, as before.

I think I have a solution for this mess, see below.

I would not send it as 1 series, but only include the slab changes (+ instruction_pointer.h change to introduce _CODE_LOCATION_) as one series, to go through the slab tree. The rest of the patches would go to respective arch maintainers.

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

arch/alpha/include/asm/linkage.h +2 -0
index aa8661fa60dc..88617cfaa0f7 100644
@@ -6,4 +6,6 @@
 #define SYSCALL_ALIAS(alias, name)					\
 	asm ( #alias " = " #name "\n\t.globl " #alias)
 
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("br %0, 1f\n1:" : "=r" (__ip)); __ip; })
+
 #endif
arch/arc/include/asm/linkage.h +2 -0
index ba3cb65b5eaa..3fb91d1672ba 100644
@@ -75,6 +75,8 @@
 #define __arcfp_data __section(".data")
 #endif
 
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("mov %0, pcl" : "=r" (__ip)); __ip; })
+
 #endif /* __ASSEMBLER__ */
 
 #endif
arch/arm/include/asm/linkage.h +2 -0
index c4670694ada7..416e6a242dc4 100644
@@ -9,4 +9,6 @@
   .type name, %function; \
   END(name)
 
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("1: adr %0, 1b" : "=r" (__ip)); __ip; })
+
 #endif
arch/arm64/include/asm/linkage.h +2 -0
index 40bd17add539..73eabc82a6bb 100644
@@ -43,4 +43,6 @@
 	SYM_TYPED_START(name, SYM_L_GLOBAL, SYM_A_ALIGN)	\
 	bti c ;
 
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("adr %0, ." : "=r" (__ip)); __ip; })
+
 #endif
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 */
arch/hexagon/include/asm/linkage.h +2 -0
index ebdb581939e8..b3808f093e62 100644
@@ -9,4 +9,6 @@
 #define __ALIGN		.align 4
 #define __ALIGN_STR	".align 4"
 
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("call 1f\n1: %0 = r31" : "=r" (__ip) : : "r31"); __ip; })
+
 #endif
arch/loongarch/include/asm/linkage.h +2 -0
index a1bd6a3ee03a..f175b25068d7 100644
@@ -77,4 +77,6 @@
 
 #define SYM_SIGFUNC_END(name) SYM_FUNC_END(name)
 
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("pcaddi %0, 0" : "=r" (__ip)); __ip; })
+
 #endif
arch/m68k/include/asm/linkage.h +2 -0
index c8b84282764c..9ed2f36830d0 100644
@@ -35,4 +35,6 @@
 	__asmlinkage_protect_n(ret, "m" (arg1), "m" (arg2), "m" (arg3), \
 			      "m" (arg4), "m" (arg5), "m" (arg6))
 
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("lea %%pc@(.), %0" : "=a" (__ip)); __ip; })
+
 #endif
arch/microblaze/include/asm/linkage.h new file +7 -0
new file mode 100644
index 000000000000..fc3873e0e9b6
@@ -0,0 +1,7 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _ASM_MICROBLAZE_LINKAGE_H
+#define _ASM_MICROBLAZE_LINKAGE_H
+
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("mfs %0, rpc" : "=r" (__ip)); __ip; })
+
+#endif /* _ASM_MICROBLAZE_LINKAGE_H */
arch/mips/include/asm/linkage.h +10 -0
index fd44ba754f1a..0579eac57def 100644
@@ -10,4 +10,14 @@
 #define SYSCALL_ALIAS(alias, name)					\
 	asm ( #alias " = " #name "\n\t.globl " #alias)
 
+#define _THIS_IP_ ({				\
+	unsigned long __ip;			\
+	asm volatile("bal 1f\n\t"		\
+		     " nop\n\t"			\
+		     "1: move %0, $ra"		\
+		     : "=r" (__ip) : : "$ra"	\
+	);					\
+	__ip;					\
+})
+
 #endif
arch/nios2/include/asm/linkage.h +2 -0
index 211302301a8a..c4073235852b 100644
@@ -12,4 +12,6 @@
 #define __ALIGN .align 4
 #define __ALIGN_STR ".align 4"
 
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("nextpc %0" : "=r" (__ip)); __ip; })
+
 #endif
arch/openrisc/include/asm/linkage.h +10 -0
index 25aa449ac30e..a96e808b5d1a 100644
@@ -18,4 +18,14 @@
 #define __ALIGN      .align 0
 #define __ALIGN_STR ".align 0"
 
+#define _THIS_IP_ ({				\
+	unsigned long __ip;			\
+	asm volatile("l.jal 1f\n\t"		\
+		     " l.nop\n\t"		\
+		     "1: l.ori %0, r9, 0"	\
+		     : "=r" (__ip) : : "r9"	\
+	);					\
+	__ip;					\
+})
+
 #endif /* __ASM_OPENRISC_LINKAGE_H */
arch/parisc/include/asm/linkage.h +8 -0
index d4cad492b971..d4d8ff7735c7 100644
@@ -37,4 +37,12 @@ name:		ASM_NL\
 
 #endif /* __ASSEMBLER__ */
 
+#define _THIS_IP_ ({                           \
+	unsigned long __ip;                     \
+	asm volatile("b,l 1f, %0\n\t"           \
+		     " nop\n\t"                 \
+		     "1:" : "=r" (__ip));       \
+	__ip;                                   \
+})
+
 #endif  /* __ASM_PARISC_LINKAGE_H */
arch/powerpc/include/asm/linkage.h +9 -0
index b71b9582e754..aa469e7bef0b 100644
@@ -13,4 +13,13 @@
 	     "\t.globl ." #alias "\n\t.set ." #alias ", ." #name)
 #endif
 
+#define _THIS_IP_ ({				\
+	unsigned long __ip;			\
+	asm volatile("bcl 20,31,1f\n\t"		\
+		     "1: mflr %0"		\
+		     : "=r" (__ip) : : "lr"	\
+	);					\
+	__ip;					\
+})
+
 #endif	/* _ASM_POWERPC_LINKAGE_H */
arch/riscv/include/asm/linkage.h +2 -0
index 9e88ba23cd2b..7e0210ef4eb4 100644
@@ -9,4 +9,6 @@
 #define __ALIGN		.balign 4
 #define __ALIGN_STR	".balign 4"
 
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("auipc %0, 0" : "=r" (__ip)); __ip; })
+
 #endif /* _ASM_RISCV_LINKAGE_H */
arch/s390/include/asm/linkage.h +2 -0
index df3fb7d8227b..1b3ac553a642 100644
@@ -7,4 +7,6 @@
 #define __ALIGN .balign CONFIG_FUNCTION_ALIGNMENT, 0x07
 #define __ALIGN_STR __stringify(__ALIGN)
 
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("larl %0, ." : "=d" (__ip)); __ip; })
+
 #endif
arch/sh/include/asm/linkage.h +2 -0
index 7c2fa27a43f8..af56b38b6001 100644
@@ -5,4 +5,6 @@
 #define __ALIGN .balign 4
 #define __ALIGN_STR ".balign 4"
 
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("mova 1f, %0\n1:" : "=z" (__ip)); __ip; })
+
 #endif
arch/sparc/include/asm/linkage.h new file +19 -0
new file mode 100644
index 000000000000..3f24e2da88be
@@ -0,0 +1,19 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _ASM_SPARC_LINKAGE_H
+#define _ASM_SPARC_LINKAGE_H
+
+#ifdef CONFIG_SPARC64
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("rd %%pc, %0" : "=r" (__ip)); __ip; })
+#else
+#define _THIS_IP_ ({				\
+	unsigned long __ip;			\
+	asm volatile("call 1f\n\t"		\
+		     " nop\n\t"			\
+		     "1: mov %%o7, %0"		\
+		     : "=r" (__ip) : : "o7"	\
+	);					\
+	__ip;					\
+})
+#endif
+
+#endif /* _ASM_SPARC_LINKAGE_H */
arch/x86/include/asm/linkage.h +2 -1
index a7294656ad90..bce3c6f4b94f 100644
@@ -13,11 +13,12 @@
  * The generic version tends to create spurious ENDBR instructions under
  * certain conditions.
  */
-#define _THIS_IP_ ({ unsigned long __here; asm ("lea 0(%%rip), %0" : "=r" (__here)); __here; })
+#define _THIS_IP_ ({ unsigned long __here; asm volatile("lea 0(%%rip), %0" : "=r" (__here)); __here; })
 #endif
 
 #ifdef CONFIG_X86_32
 #define asmlinkage CPP_ASMLINKAGE __attribute__((regparm(0)))
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("call 1f\n1: pop %0" : "=r" (__ip)); __ip; })
 #endif /* CONFIG_X86_32 */
 
 #define __ALIGN		.balign CONFIG_FUNCTION_ALIGNMENT, 0x90;
arch/xtensa/include/asm/linkage.h +2 -0
index 0ba9973235d9..9e6f5cc81964 100644
@@ -6,4 +6,6 @@
 #define __ALIGN		.align 4
 #define __ALIGN_STR	".align 4"
 
+#define _THIS_IP_ ({ unsigned long __ip; asm volatile("call0 1f\n1: mov %0, a0" : "=r" (__ip) : : "a0"); __ip; })
+
 #endif
include/linux/instruction_pointer.h +24 -0
index aa0b3ffea935..dfe73aafddb8 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 won _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 5e1249e36b0d..a4bf1585411f 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
#14 lore raw
Quoted 6 lines · Marco Elver

I think I have a solution for this mess, see below.

I would not send it as 1 series, but only include the slab changes (+ instruction_pointer.h change to introduce _CODE_LOCATION_) as one series, to go through the slab tree. The rest of the patches would go to respective arch maintainers.

I'm assuming this will be a follow-up and reviewing patch 1 (and waiting for Jon's thuoghts on patch 2)

Quoted 11 lines
include/linux/instruction_pointer.h +3 -0
index aa0b3ffea935..dfe73aafddb8 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

include/linux/instruction_pointer.h line 23

Quoted 10 lines
include/linux/instruction_pointer.h +10 -0
+ * 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 won _THIS_IP_.
+ */
+#define HAS_BROKEN_THIS_IP
+#endif

As long as _THIS_IP_ is broken on some arches, it cannot be used anyway when in a general API that can be used by arbitrary users?

Is it something that can be fixed in all arches over time?

include/linux/instruction_pointer.h line 32

Quoted 8 lines
include/linux/instruction_pointer.h +8 -0
+/*
+ * _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; })

Nice!

Yes, we don't really need the exact code location
for partitioning kmalloc caches.

IIRC lockdep does a similar thing to define lock classes (unique for each lock init location)

include/linux/instruction_pointer.h line 35

Quoted 3 lines
include/linux/instruction_pointer.h +2 -0
+#else
+#define _CODE_LOCATION_ _THIS_IP_
 #endif

Probably we don't need this fallback?

Quoted 14 lines
include/linux/instruction_pointer.h +0 -0
 #endif /* _LINUX_INSTRUCTION_POINTER_H */
include/linux/slab.h +1 -1
index 5e1249e36b0d..a4bf1585411f 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 · 2 lines
Cheers,
Harry / Hyeonggon
author maintainer
#15 lore raw
Quoted 11 lines · Harry Yoo (Oracle)' via kasan-dev
Quoted 6 lines · Marco Elver

I think I have a solution for this mess, see below.

I would not send it as 1 series, but only include the slab changes (+ instruction_pointer.h change to introduce _CODE_LOCATION_) as one series, to go through the slab tree. The rest of the patches would go to respective arch maintainers.

I'm assuming this will be a follow-up and reviewing patch 1 (and waiting for Jon's thuoghts on patch 2)

I'll be sending v4 shortly.

Quoted 16 lines
Quoted 16 lines
include/linux/instruction_pointer.h +8 -0
index aa0b3ffea935..dfe73aafddb8 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
+ *
Quoted 8 lines

include/linux/instruction_pointer.h line 23

Quoted 5 lines
include/linux/instruction_pointer.h +5 -0
+ * Mark it as broken, so that appropriate fallback options can be implemented
+ * for architectures that do not define their won _THIS_IP_.
+ */
+#define HAS_BROKEN_THIS_IP
+#endif

As long as _THIS_IP_ is broken on some arches, it cannot be used anyway when in a general API that can be used by arbitrary users?

It more or less works today, and for debugging or tracing it's "good enough" in most cases.

The plan would be to phase out the generic _THIS_IP_ once all architectures have a correct _THIS_IP_ implementation.

Quoted 1 line

Is it something that can be fixed in all arches over time?

Yes, I have patches for that.

Quoted 14 lines

include/linux/instruction_pointer.h line 32

Quoted 8 lines
include/linux/instruction_pointer.h +8 -0
+/*
+ * _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; })

Nice!

Yes, we don't really need the exact code location
for partitioning kmalloc caches.

Quoted 8 lines

IIRC lockdep does a similar thing to define lock classes (unique for each lock init location)

include/linux/instruction_pointer.h line 35

Quoted 3 lines
include/linux/instruction_pointer.h +2 -0
+#else
+#define _CODE_LOCATION_ _THIS_IP_
 #endif

Probably we don't need this fallback?

x86-64 is the only arch that has working fast _THIS_IP_, and adding static __here markers to bss is rather wasteful.

More architectures will be supporting _THIS_IP_ properly once I get to send the patches. The mainstream architectures all have a reasonable and fast way to get the current IP, so we don't need to waste bss space there.

maintainer
#16 lore raw
Quoted 22 lines · Marco Elver
Quoted 11 lines · Harry Yoo (Oracle)' via kasan-dev
Quoted 6 lines · Marco Elver

I think I have a solution for this mess, see below.

I would not send it as 1 series, but only include the slab changes (+ instruction_pointer.h change to introduce _CODE_LOCATION_) as one series, to go through the slab tree. The rest of the patches would go to respective arch maintainers.

I'm assuming this will be a follow-up and reviewing patch 1 (and waiting for Jon's thuoghts on patch 2)

I'll be sending v4 shortly.

Quoted 6 lines
Quoted 6 lines
include/linux/instruction_pointer.h +0 -0
index aa0b3ffea935..dfe73aafddb8 100644
@@ -8,6 +8,30 @@
 
Quoted 12 lines
Quoted 4 lines
Quoted 4 lines
include/linux/instruction_pointer.h +2 -0
 #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]
Quoted 8 lines

include/linux/instruction_pointer.h line 20

Quoted 8 lines
include/linux/instruction_pointer.h +8 -0
+ * 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 won _THIS_IP_.

Teeny typo above: "won" -> "own".

Quoted 40 lines
Quoted 6 lines

include/linux/instruction_pointer.h line 23

Quoted 3 lines
include/linux/instruction_pointer.h +3 -0
+ */
+#define HAS_BROKEN_THIS_IP
+#endif

As long as _THIS_IP_ is broken on some arches, it cannot be used anyway when in a general API that can be used by arbitrary users?

It more or less works today, and for debugging or tracing it's "good enough" in most cases.

The plan would be to phase out the generic _THIS_IP_ once all architectures have a correct _THIS_IP_ implementation.

Quoted 1 line

Is it something that can be fixed in all arches over time?

Yes, I have patches for that.

Quoted 14 lines

include/linux/instruction_pointer.h line 32

Quoted 8 lines
include/linux/instruction_pointer.h +8 -0
+/*
+ * _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; })

Nice!

Yes, we don't really need the exact code location
for partitioning kmalloc caches.

Quoted 8 lines

IIRC lockdep does a similar thing to define lock classes (unique for each lock init location)

include/linux/instruction_pointer.h line 35

Quoted 3 lines
include/linux/instruction_pointer.h +2 -0
+#else
+#define _CODE_LOCATION_ _THIS_IP_
 #endif

Probably we don't need this fallback?

Quoted 7 lines

x86-64 is the only arch that has working fast _THIS_IP_, and adding static __here markers to bss is rather wasteful.

More architectures will be supporting _THIS_IP_ properly once I get to send the patches. The mainstream architectures all have a reasonable and fast way to get the current IP, so we don't need to waste bss space there.

Thanks for finding a solution for this!

Signature · 1 line
Kees Cook
#17 lore raw
In reply to Marco Elver
Quoted 11 lines · Marco Elver
Quoted 9 lines · Harry Yoo (Oracle)' via kasan-dev
Quoted 6 lines · Marco Elver

I think I have a solution for this mess, see below.

I would not send it as 1 series, but only include the slab changes (+ instruction_pointer.h change to introduce _CODE_LOCATION_) as one series, to go through the slab tree. The rest of the patches would go to respective arch maintainers.

Quoted 4 lines
Quoted 2 lines

I'm assuming this will be a follow-up and reviewing patch 1 (and waiting for Jon's thuoghts on patch 2)

I'll be sending v4 shortly.

Thanks!

Quoted 25 lines
Quoted 16 lines
Quoted 16 lines
include/linux/instruction_pointer.h +8 -0
index aa0b3ffea935..dfe73aafddb8 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
+ *
Quoted 8 lines

include/linux/instruction_pointer.h line 23

Quoted 5 lines
include/linux/instruction_pointer.h +5 -0
+ * Mark it as broken, so that appropriate fallback options can be implemented
+ * for architectures that do not define their won _THIS_IP_.
+ */
+#define HAS_BROKEN_THIS_IP
+#endif

As long as _THIS_IP_ is broken on some arches, it cannot be used anyway when in a general API that can be used by arbitrary users?

Quoted 5 lines

It more or less works today, and for debugging or tracing it's "good enough" in most cases.

The plan would be to phase out the generic _THIS_IP_ once all architectures have a correct _THIS_IP_ implementation.

Ack.

Quoted 21 lines
Quoted 1 line

Is it something that can be fixed in all arches over time?

Yes, I have patches for that.

Quoted 17 lines

include/linux/instruction_pointer.h line 32

Quoted 8 lines
include/linux/instruction_pointer.h +8 -0
+/*
+ * _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; })

Nice!

Yes, we don't really need the exact code location
for partitioning kmalloc caches.

IIRC lockdep does a similar thing to define lock classes (unique for each lock init location)

Quoted 8 lines
Quoted 5 lines

include/linux/instruction_pointer.h line 35

Quoted 3 lines
include/linux/instruction_pointer.h +2 -0
+#else
+#define _CODE_LOCATION_ _THIS_IP_
 #endif

Probably we don't need this fallback?

x86-64 is the only arch that has working fast _THIS_IP_, and adding static __here markers to bss is rather wasteful.

Ouch, I see.

Quoted 4 lines

More architectures will be supporting _THIS_IP_ properly once I get to send the patches. The mainstream architectures all have a reasonable and fast way to get the current IP, so we don't need to waste bss space there.

Ack.

Signature · 2 lines
Cheers,
Harry / Hyeonggon