Skip to contentSkip to conversation

livepatch: Introduce replace set support

RFC PATCH Superseded Yafang Shao 3 participants 13 messages Aug 4 – Aug 5

Subsystems (2)

v4 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

v4 cover livepatch: Introduce replace set support

We previously proposed a BPF+livepatch method to enable rapid experimentation with new kernel features without interrupting production workloads:

https://lore.kernel.org/live-patching/[email protected]/

In the resulting discussion, Song and Petr suggested adding a "replace set" to support scenarios where specific livepatches can be selectively replaced or skipped.

This patchset introduces a more flexible model using two new fields in struct klp_patch:

- provides: an unsigned int id identifying the patch replace set. By default (provides=0), any livepatch replaces any other livepatch.

- obsoletes: an optional array of unsigned int ids specifying additional provides ids to be replaced. This allows a new patch to explicitly obsolete patches from different replace sets.

A new livepatch atomically replaces any existing livepatch whose provides id matches either:
1. The new patch provides id (same replace set), or
2. Any id in the new patch obsoletes list

Additionally, this design deprecates the traditional non-atomic-replace model. Previously, setting 'replace' to 0 was the only way to keep certain livepatches persistent on the system, forcing developers to disable atomic replacement entirely. With the introduction of replace set, developers now have a selective option to keep specific livepatches persistent while maintaining atomic replacement capabilities elsewhere.

At present, KLP state, shadow variables, and callbacks are not integrated with the new replace_set mechanism in this patchset. Support for these features is deferred until Petr's klp-state-transfer infrastructure is completed and merged:

https://github.com/pmladek/linux/tree/klp-state-transfer-v1-iter12

Future Work
----------
- Allow provides and obsoletes to be configured dynamically at module load time, rather than being fixed at build time.

v3->v4 (RFC):
- Allow a livepatch to replace livepatches with different provides IDs. Replace the single replace_set field with two separate fields, provides and obsoletes, for more flexible replacement semantics. (Petr, Joe)

v3: https://lore.kernel.org/live-patching/[email protected]/

v2->v3:
- Address the feedback from Sachiko AI
- Fix the pre-existing NULL pointer dereference issue
- Move klp_find_func into core.h
- Don't deprecate stack_order completely

v2: https://lore.kernel.org/live-patching/[email protected]/

v1->v2:
- Incorporate feedback from Petr:
- Initialize replace_set to 0 by default
- Improve documentation
- Enforce that livepatches in different replace_sets cannot use the same

    state->id.

- Enforce that livepatches in different replace_sets cannot modify the same function.
- Ensure consistent capitalization and naming usage of KLP_REPLACE_SET.
- Incorporate feedback from Sachiko AI:
- Skip the klp_transition patch during klp_force_transition().

v1 (RFC): https://lore.kernel.org/live-patching/[email protected]/

Yafang Shao (4):
livepatch: Make klp_find_func() non static
livepatch: Call klp_init_patch_early() earlier
livepatch: Implement replace set for scoped atomic replace
livepatch: Deprecate stack_order

 .../ABI/removed/sysfs-kernel-livepatch        |  16 +++
 .../ABI/testing/sysfs-kernel-livepatch        |  27 ++---
 .../livepatch/cumulative-patches.rst          |  93 +++++++++++-----
 Documentation/livepatch/livepatch.rst         |  23 ++--
 include/linux/livepatch.h                     |   7 +-
 kernel/livepatch/core.c                       | 101 +++++++++++-------
 kernel/livepatch/core.h                       |   2 +
 kernel/livepatch/state.c                      |  56 ++++++++--
 kernel/livepatch/transition.c                 |  11 +-
 scripts/livepatch/init.c                      |  71 +++++++++++-
 scripts/livepatch/klp-build                   |  87 +++++++++++++--
 11 files changed, 380 insertions(+), 114 deletions(-)
 create mode 100644 Documentation/ABI/removed/sysfs-kernel-livepatch
Signature · 1 line
2.52.0
#1 lore raw

RFC PATCH v4 1/4 livepatch: Make klp_find_func() non static

Make klp_find_func() non static to allow its use in other source files by an upcoming patch.

While at it, rename the parameter @old_func to @func to better reflect its generic purpose.

---
 kernel/livepatch/core.c | 16 ++++++++--------
 kernel/livepatch/core.h |  1 +
 2 files changed, 9 insertions(+), 8 deletions(-)
kernel/livepatch/core.c +8 -8
index a240d1144e89..0ad778d1006f 100644
@@ -82,20 +82,20 @@ static bool klp_initialized(void)
 	return !!klp_root_kobj;
 }
 
-static struct klp_func *klp_find_func(struct klp_object *obj,
-				      struct klp_func *old_func)
+/* Check if @func is present in @obj. */
+struct klp_func *klp_find_func(struct klp_object *obj, struct klp_func *func)
 {
-	struct klp_func *func;
+	struct klp_func *obj_func;
 
-	klp_for_each_func(obj, func) {
+	klp_for_each_func(obj, obj_func) {
 		/*
 		 * Besides identical old_sympos, also consider old_sympos
 		 * of 0 and 1 are identical.
 		 */
-		if ((strcmp(old_func->old_name, func->old_name) == 0) &&
-		    ((old_func->old_sympos == func->old_sympos) ||
-		     (old_func->old_sympos == 0 && func->old_sympos == 1) ||
-		     (old_func->old_sympos == 1 && func->old_sympos == 0))) {
+		if ((strcmp(obj_func->old_name, func->old_name) == 0) &&
+		    ((obj_func->old_sympos == func->old_sympos) ||
+		     (obj_func->old_sympos == 0 && func->old_sympos == 1) ||
+		     (obj_func->old_sympos == 1 && func->old_sympos == 0))) {
 			return func;
 		}
 	}
kernel/livepatch/core.h +1 -0
index 38209c7361b6..361a0917a03f 100644
@@ -17,6 +17,7 @@ void klp_free_patch_async(struct klp_patch *patch);
 void klp_free_replaced_patches_async(struct klp_patch *new_patch);
 void klp_unpatch_replaced_patches(struct klp_patch *new_patch);
 void klp_discard_nops(struct klp_patch *new_patch);
+struct klp_func *klp_find_func(struct klp_object *obj, struct klp_func *func);
 
 static inline bool klp_is_object_loaded(struct klp_object *obj)
 {
Signature · 1 line
2.52.0
#2 lore raw

Re: [RFC PATCH v4 1/4] livepatch: Make klp_find_func() non static

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] klp_find_func() incorrectly returns the search parameter instead of the matched object from the…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] klp_find_func() incorrectly returns the search parameter instead of the matched object from the list. --

--- Patch [1]: [RFC PATCH v4 1/4] livepatch: Make klp_find_func() non static --- commit 59916304ff12f7685cb556f7a7c1f4a1c5a25b00
Author: Yafang Shao <[email protected]>

livepatch: Make klp_find_func() non static

This commit makes klp_find_func() non static so it can be used in other source files by an upcoming patch. It also renames the old_func parameter to func to better reflect its generic purpose.

Quoted 4 lines
kernel/livepatch/core.c +0 -0
index 28d15ba58a26d..e07c41a0f3ac8 100644

[ ... ]

Quoted 13 lines
kernel/livepatch/core.c +4 -4
-static struct klp_func *klp_find_func(struct klp_object *obj,
-				      struct klp_func *old_func)
+/* Check if @func is present in @obj. */
+struct klp_func *klp_find_func(struct klp_object *obj, struct klp_func *func)
 {
-	struct klp_func *func;
+	struct klp_func *obj_func;
 
-	klp_for_each_func(obj, func) {
+	klp_for_each_func(obj, obj_func) {
 		/*
 		 * Besides identical old_sympos, also consider old_sympos
 		 * of 0 and 1 are identical.

kernel/livepatch/core.c static bool klp_initialized(void) · line 99

Quoted 10 lines
kernel/livepatch/core.c +4 -4
 		 */
-		if ((strcmp(old_func->old_name, func->old_name) == 0) &&
-		    ((old_func->old_sympos == func->old_sympos) ||
-		     (old_func->old_sympos == 0 && func->old_sympos == 1) ||
-		     (old_func->old_sympos == 1 && func->old_sympos == 0))) {
+		if ((strcmp(obj_func->old_name, func->old_name) == 0) &&
+		    ((obj_func->old_sympos == func->old_sympos) ||
+		     (obj_func->old_sympos == 0 && func->old_sympos == 1) ||
+		     (obj_func->old_sympos == 1 && func->old_sympos == 0))) {
 			return func;

[Severity: Medium]
Will this return the correct object? It looks like this now returns the search parameter (func) instead of the newly introduced list iterator variable (obj_func).

If a caller relies on the returned pointer to access the matched object from the list, they will receive the search parameter instead. This could lead to incorrect state manipulation or memory corruption for new users of this exported function.

Should this return obj_func instead?

Quoted 2 lines
kernel/livepatch/core.c +0 -0
 		}
 	}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw

Re: [RFC PATCH v4 1/4] livepatch: Make klp_find_func() non static

Quoted 49 lines · On Tue, Aug 4, 2026 at 2:56 PM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] klp_find_func() incorrectly returns the search parameter instead of the matched object from the list. --

--- Patch [1]: [RFC PATCH v4 1/4] livepatch: Make klp_find_func() non static --- commit 59916304ff12f7685cb556f7a7c1f4a1c5a25b00
Author: Yafang Shao <[email protected]>

livepatch: Make klp_find_func() non static

This commit makes klp_find_func() non static so it can be used in other source files by an upcoming patch. It also renames the old_func parameter to func to better reflect its generic purpose.

Quoted 4 lines
kernel/livepatch/core.c +0 -0
index 28d15ba58a26d..e07c41a0f3ac8 100644

[ ... ]

Quoted 13 lines
kernel/livepatch/core.c +4 -4
-static struct klp_func *klp_find_func(struct klp_object *obj,
-                                   struct klp_func *old_func)
+/* Check if @func is present in @obj. */
+struct klp_func *klp_find_func(struct klp_object *obj, struct klp_func *func)
 {
-     struct klp_func *func;
+     struct klp_func *obj_func;
 
-     klp_for_each_func(obj, func) {
+     klp_for_each_func(obj, obj_func) {
              /*
               * Besides identical old_sympos, also consider old_sympos
               * of 0 and 1 are identical.

kernel/livepatch/core.c static bool klp_initialized(void) · line 99

Quoted 10 lines
kernel/livepatch/core.c +4 -4
               */
-             if ((strcmp(old_func->old_name, func->old_name) == 0) &&
-                 ((old_func->old_sympos == func->old_sympos) ||
-                  (old_func->old_sympos == 0 && func->old_sympos == 1) ||
-                  (old_func->old_sympos == 1 && func->old_sympos == 0))) {
+             if ((strcmp(obj_func->old_name, func->old_name) == 0) &&
+                 ((obj_func->old_sympos == func->old_sympos) ||
+                  (obj_func->old_sympos == 0 && func->old_sympos == 1) ||
+                  (obj_func->old_sympos == 1 && func->old_sympos == 0))) {
                      return func;

[Severity: Medium]
Will this return the correct object? It looks like this now returns the search parameter (func) instead of the newly introduced list iterator variable (obj_func).

Quoted 6 lines

If a caller relies on the returned pointer to access the matched object from the list, they will receive the search parameter instead. This could lead to incorrect state manipulation or memory corruption for new users of this exported function.

Should this return obj_func instead?

Good catch. It should return obj_func instead.

Signature · 2 lines
Regards
Yafang
#4 lore raw

RFC PATCH v4 2/4 livepatch: Call klp_init_patch_early() earlier

In reply to Yafang Shao

Invoke klp_init_patch_early() during early initialization to avoid mixing for_each_() and for_each_*_static() variants later in the code.

No functional change. This prepares the code for an upcoming patch.

---
 kernel/livepatch/core.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/livepatch/core.c +2 -2
index 0ad778d1006f..5ec30909d382 100644
@@ -1145,6 +1145,8 @@ int klp_enable_patch(struct klp_patch *patch)
 
 	mutex_lock(&klp_mutex);
 
+	klp_init_patch_early(patch);
+
 	if (!klp_is_patch_compatible(patch)) {
 		pr_err("Livepatch patch (%s) is not compatible with the already installed livepatches.\n",
 			patch->mod->name);
@@ -1157,8 +1159,6 @@ int klp_enable_patch(struct klp_patch *patch)
 		return -ENODEV;
 	}
 
-	klp_init_patch_early(patch);
-
 	ret = klp_init_patch(patch);
 	if (ret)
 		goto err;
Signature · 1 line
2.52.0
#5 lore raw

Re: [RFC PATCH v4 2/4] livepatch: Call klp_init_patch_early() earlier

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Moving klp_init_patch_early() before early failure checks violates the kobject API lifecycle and…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Moving klp_init_patch_early() before early failure checks violates the kobject API lifecycle and introduces missing cleanup on error paths. --

--- Patch [2]: [RFC PATCH v4 2/4] livepatch: Call klp_init_patch_early() earlier --- commit 6b8df20b82104d4c61053ebea3721f1d77891456
Author: Yafang Shao <[email protected]>

livepatch: Call klp_init_patch_early() earlier

This commit moves the invocation of klp_init_patch_early() earlier in the livepatch initialization process. This prepares the code for an upcoming patch by avoiding mixing iteration variants later in the sequence.

Quoted 14 lines
kernel/livepatch/core.c +2 -0
index e07c41a0f3ac8..c98cbcf59566d 100644
@@ -1135,6 +1135,8 @@ int klp_enable_patch(struct klp_patch *patch)
 
 	mutex_lock(&klp_mutex);
 
+	klp_init_patch_early(patch);
+
 	if (!klp_is_patch_compatible(patch)) {
 		pr_err("Livepatch patch (%s) is not compatible with the already installed livepatches.\n",
 			patch->mod->name);

kernel/livepatch/core.c int klp_enable_patch(struct klp_patch *patch) · line 1150

Quoted 2 lines
kernel/livepatch/core.c +0 -0
@@ -1147,8 +1149,6 @@ int klp_enable_patch(struct klp_patch *patch)
 		return -ENODEV;
 	}

[Severity: Medium]
Since klp_init_patch_early() initializes kobjects for the patch, does returning directly on compatibility or try_module_get() failures leak these resources?

The kobject API requires that once kobject_init() is called, kobject_put() must be used to release the object. Because klp_init_patch_early() is now called before these checks, if we hit the early return paths in klp_enable_patch(), we bypass cleaning up the initialized kobjects.

Also, would simply changing these early returns to jump to the err label cause issues with klp_free_patch_finish()?

kernel/livepatch/core.c:klp_enable_patch() {
    ...
err:
	klp_free_patch_start(patch);
	mutex_unlock(&klp_mutex);
	klp_free_patch_finish(patch);
	return ret;
}

It looks like klp_free_patch_finish() calls module_put(patch->mod) unconditionally. If try_module_get() failed, jumping to the err label might underflow the module reference count.

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#6 lore raw

Re: [RFC PATCH v4 2/4] livepatch: Call klp_init_patch_early() earlier

Quoted 54 lines · On Tue, Aug 4, 2026 at 3:03 PM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Moving klp_init_patch_early() before early failure checks violates the kobject API lifecycle and introduces missing cleanup on error paths. --

--- Patch [2]: [RFC PATCH v4 2/4] livepatch: Call klp_init_patch_early() earlier --- commit 6b8df20b82104d4c61053ebea3721f1d77891456
Author: Yafang Shao <[email protected]>

livepatch: Call klp_init_patch_early() earlier

This commit moves the invocation of klp_init_patch_early() earlier in the livepatch initialization process. This prepares the code for an upcoming patch by avoiding mixing iteration variants later in the sequence.

Quoted 14 lines
kernel/livepatch/core.c +2 -0
index e07c41a0f3ac8..c98cbcf59566d 100644
@@ -1135,6 +1135,8 @@ int klp_enable_patch(struct klp_patch *patch)
 
      mutex_lock(&klp_mutex);
 
+     klp_init_patch_early(patch);
+
      if (!klp_is_patch_compatible(patch)) {
              pr_err("Livepatch patch (%s) is not compatible with the already installed livepatches.\n",
                      patch->mod->name);

kernel/livepatch/core.c int klp_enable_patch(struct klp_patch *patch) · line 1150

Quoted 2 lines
kernel/livepatch/core.c +0 -0
@@ -1147,8 +1149,6 @@ int klp_enable_patch(struct klp_patch *patch)
              return -ENODEV;
      }

[Severity: Medium]
Since klp_init_patch_early() initializes kobjects for the patch, does returning directly on compatibility or try_module_get() failures leak these resources?

The kobject API requires that once kobject_init() is called, kobject_put() must be used to release the object. Because klp_init_patch_early() is now called before these checks, if we hit the early return paths in klp_enable_patch(), we bypass cleaning up the initialized kobjects.

Also, would simply changing these early returns to jump to the err label cause issues with klp_free_patch_finish()?

kernel/livepatch/core.c:klp_enable_patch() {
    ...
err:
        klp_free_patch_start(patch);
        mutex_unlock(&klp_mutex);
        klp_free_patch_finish(patch);
        return ret;
}
Quoted 3 lines

It looks like klp_free_patch_finish() calls module_put(patch->mod) unconditionally. If try_module_get() failed, jumping to the err label might underflow the module reference count.

Good point. It seems we need the following additional change:

kernel/livepatch/core.c +5 -0
@@ -1168,19 +1168,20 @@ int klp_enable_patch(struct klp_patch *patch)
 
        mutex_lock(&klp_mutex);
 
+       if (!try_module_get(patch->mod)) {
+               mutex_unlock(&klp_mutex);
+               return -ENODEV;
+       }
+
        klp_init_patch_early(patch);
 
        if (!klp_is_patch_compatible(patch)) {
                pr_err("Livepatch patch (%s) is not compatible with

the already installed livepatches.\n",

                        patch->mod->name);
-               mutex_unlock(&klp_mutex);
-               return -EINVAL;
+               ret = -EINVAL;
+               goto err;
        }

- if (!try_module_get(patch->mod)) {
- mutex_unlock(&klp_mutex);
- return -ENODEV;
- }

        ret = klp_init_patch(patch);
        if (ret)
Signature · 2 lines
Regards
Yafang
#7 lore raw

RFC PATCH v4 3/4 livepatch: Implement replace set for scoped atomic replace

In reply to Yafang Shao

The current bool replace flag is too coarse: it is either all or nothing. A livepatch with .replace=true replaces ALL existing livepatches, which is safe but inflexible. There is no way to have multiple independent livepatch sets coexist on the same system.

Replace it with a more flexible model using two new fields in struct klp_patch:

- provides: an unsigned int id identifying the patch replace set. By default (provides=0), any livepatch replaces any other livepatch.

- obsoletes: an optional array of unsigned int ids specifying additional provides ids to be replaced. This allows a new patch to explicitly obsolete patches from different replace sets.

A new livepatch atomically replaces any existing livepatch whose provides id matches either:
1. The new patch provides id (same replace set), or
2. Any id in the new patch obsoletes list

The klp-build script is updated with -p/--provides and -r/--obsoletes options. The obsoletes list automatically includes the provides id and deduplicates entries. Input validation rejects malformed values at build time.

Two helper functions are introduced:
- klp_patch_replaceable(): checks if an old patch should be replaced by a new patch.
- klp_has_function_conflict(): rejects loading a livepatch that would modify a function already patched by a livepatch with a different provides id.

---
 .../ABI/removed/sysfs-kernel-livepatch        |  7 ++
 .../ABI/testing/sysfs-kernel-livepatch        | 22 ++++-
 .../livepatch/cumulative-patches.rst          | 93 +++++++++++++------
 Documentation/livepatch/livepatch.rst         | 23 +++--
 include/linux/livepatch.h                     |  7 +-
 kernel/livepatch/core.c                       | 69 ++++++++++++--
 kernel/livepatch/core.h                       |  1 +
 kernel/livepatch/state.c                      | 56 +++++++++--
 kernel/livepatch/transition.c                 | 11 ++-
 scripts/livepatch/init.c                      | 71 +++++++++++++-
 scripts/livepatch/klp-build                   | 87 +++++++++++++++--
 11 files changed, 368 insertions(+), 79 deletions(-)
 create mode 100644 Documentation/ABI/removed/sysfs-kernel-livepatch
Documentation/ABI/removed/sysfs-kernel-livepatch new file +7 -0
new file mode 100644
index 000000000000..87d57ba27326
@@ -0,0 +1,7 @@
+What:		/sys/kernel/livepatch/<patch>/replace
+Date:		Jun 2024
+KernelVersion:	6.11.0
+Contact:	[email protected]
+Description:
+		An attribute which indicates whether the patch supports
+		atomic-replace.
Documentation/ABI/testing/sysfs-kernel-livepatch +17 -5
index 3c3f36b32b57..2588f676deb1 100644
@@ -47,13 +47,25 @@ Description:
 		disabled when the feature is used. See
 		Documentation/livepatch/livepatch.rst for more information.
 
-What:		/sys/kernel/livepatch/<patch>/replace
-Date:		Jun 2024
-KernelVersion:	6.11.0
+What:		/sys/kernel/livepatch/<patch>/provides
+Date:		Jun 2026
+KernelVersion:	7.4.0
 Contact:	[email protected]
 Description:
-		An attribute which indicates whether the patch supports
-		atomic-replace.
+		An attribute to show the provides id of this livepatch.
+		Only one active livepatch per provides id is allowed.
+
+What:		/sys/kernel/livepatch/<patch>/obsoletes
+Date:		Jun 2026
+KernelVersion:	7.4.0
+Contact:	[email protected]
+Description:
+		An attribute to show the obsoletes ids of this livepatch.
+		The obsoletes ids are a comma-separated list of provides
+		ids that this patch obsoletes. When this livepatch is
+		loaded, any existing livepatch whose provides id matches
+		either this patch's provides id or any id in the obsoletes
+		list will be atomically replaced.
 
 What:		/sys/kernel/livepatch/<patch>/stack_order
 Date:		Jan 2025
Documentation/livepatch/cumulative-patches.rst +65 -28

105 lines not on this page · raw message

Documentation/livepatch/livepatch.rst +14 -9
index acb90164929e..73635f9ddd91 100644
@@ -347,15 +347,20 @@ to '0'.
 5.3. Replacing
 --------------
 
-All enabled patches might get replaced by a cumulative patch that
-has the .replace flag set.
-
-Once the new patch is enabled and the 'transition' finishes then
-all the functions (struct klp_func) associated with the replaced
-patches are removed from the corresponding struct klp_ops. Also
-the ftrace handler is unregistered and the struct klp_ops is
-freed when the related function is not modified by the new patch
-and func_stack list becomes empty.
+There can be only one active livepatch for a given ``provides`` id.
+A new livepatch atomically replaces any existing livepatch whose
+``provides`` id matches either the new patch's ``provides`` id or
+any id in the new patch's ``obsoletes`` list.
+
+Once the transition is complete, all functions (``struct klp_func``)
+associated with the matching replaced patches are removed from the
+corresponding ``struct klp_ops``. If a function is no longer modified by
+the new patch and its ``func_stack`` list becomes empty, the ftrace
+handler is unregistered and the ``struct klp_ops`` is freed.
+
+Patches with a different ``provides`` id are not affected by this
+process and remain active. This allows for the independent management
+and stacking of multiple, non-conflicting livepatch sets.
 
 See Documentation/livepatch/cumulative-patches.rst for more details.
 
include/linux/livepatch.h +5 -2
index ba9e3988c07c..854ed6230b96 100644
@@ -123,7 +123,8 @@ struct klp_state {
  * @mod:	reference to the live patch module
  * @objs:	object entries for kernel objects to be patched
  * @states:	system states that can get modified
- * @replace:	replace all actively used patches
+ * @provides:	only one active livepatch per id
+ * @obsoletes:	replace given livepatch id(s)
  * @list:	list node for global list of actively used patches
  * @kobj:	kobject for sysfs resources
  * @obj_list:	dynamic list of the object entries
@@ -137,7 +138,9 @@ struct klp_patch {
 	struct module *mod;
 	struct klp_object *objs;
 	struct klp_state *states;
-	bool replace;
+	unsigned int provides;
+	unsigned int *obsoletes;
+	unsigned int nr_obsoletes;
 
 	/* internal */
 	struct list_head list;
kernel/livepatch/core.c +59 -10

127 lines not on this page · raw message

kernel/livepatch/core.h +1 -0
index 361a0917a03f..558ce7b70754 100644
@@ -18,6 +18,7 @@ void klp_free_replaced_patches_async(struct klp_patch *new_patch);
 void klp_unpatch_replaced_patches(struct klp_patch *new_patch);
 void klp_discard_nops(struct klp_patch *new_patch);
 struct klp_func *klp_find_func(struct klp_object *obj, struct klp_func *func);
+bool klp_patch_replaceable(struct klp_patch *old_patch, struct klp_patch *new_patch);
 
 static inline bool klp_is_object_loaded(struct klp_object *obj)
 {
kernel/livepatch/state.c +48 -8

81 lines not on this page · raw message

kernel/livepatch/transition.c +6 -5
index 2351a19ac2a9..15dbc13d0341 100644
@@ -89,7 +89,7 @@ static void klp_complete_transition(void)
 		 klp_transition_patch->mod->name,
 		 klp_target_state == KLP_TRANSITION_PATCHED ? "patching" : "unpatching");
 
-	if (klp_transition_patch->replace && klp_target_state == KLP_TRANSITION_PATCHED) {
+	if (klp_target_state == KLP_TRANSITION_PATCHED) {
 		klp_unpatch_replaced_patches(klp_transition_patch);
 		klp_discard_nops(klp_transition_patch);
 	}
@@ -498,7 +498,7 @@ void klp_try_complete_transition(void)
 	 */
 	if (!patch->enabled)
 		klp_free_patch_async(patch);
-	else if (patch->replace)
+	else
 		klp_free_replaced_patches_async(patch);
 }
 
@@ -720,11 +720,12 @@ void klp_force_transition(void)
 		klp_update_patch_state(idle_task(cpu));
 
 	/* Set forced flag for patches being removed. */
-	if (klp_target_state == KLP_TRANSITION_UNPATCHED)
+	if (klp_target_state == KLP_TRANSITION_UNPATCHED) {
 		klp_transition_patch->forced = true;
-	else if (klp_transition_patch->replace) {
+	} else {
 		klp_for_each_patch(patch) {
-			if (patch != klp_transition_patch)
+			if (patch != klp_transition_patch &&
+			    klp_patch_replaceable(patch, klp_transition_patch))
 				patch->forced = true;
 		}
 	}
scripts/livepatch/init.c +68 -3

90 lines not on this page · raw message

scripts/livepatch/klp-build +78 -9

129 lines not on this page · raw message

Signature · 1 line
2.52.0
#8 lore raw

Re: [RFC PATCH v4 3/4] livepatch: Implement replace set for scoped atomic replace

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Dynamically allocated `funcs` arrays are leaked on KLP_OBSOLETES parsing failure. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Dynamically allocated funcs arrays are leaked on KLP_OBSOLETES parsing failure. --

--- Patch [3]: [RFC PATCH v4 3/4] livepatch: Implement replace set for scoped atomic replace --- commit d186609c1a3dbe210857d0040f657fa918504faf
Author: Yafang Shao <[email protected]>
Subject: livepatch: Implement replace set for scoped atomic replace

This commit introduces a more flexible atomic replace model for livepatches using provides and obsoletes fields. A new patch will replace any existing patch with a matching provides ID or any ID listed in its obsoletes array. The klp-build script and init code are updated to parse and validate these new fields.

Quoted 3 lines
scripts/livepatch/init.c +0 -0

[ ... ]

Quoted 1 line
scripts/livepatch/init.c +0 -0
@@ -72,10 +73,73 @@ static int __init livepatch_mod_init(void)

[ ... ]

Quoted 35 lines
scripts/livepatch/init.c +35 -0
+#ifdef KLP_OBSOLETES
+	/*
+	 * Parse KLP_OBSOLETES string (format: "0,1,2" or "0" or empty)
+	 * and convert to unsigned int array for patch->obsoletes
+	 *
+	 * Note: KLP_OBSOLETES is always defined and includes at least the
+	 * provides ID, ensuring the patch replaces old patches with same ID.
+	 */
+	{
+		unsigned int *obs_array;
+		unsigned int count = 1;
+		char *obsoletes_str;
+		char *token, *str;
+		int i = 0;
+
+		for (str = (char *)KLP_OBSOLETES; *str; str++) {
+			if (*str == ',')
+				count++;
+		}
+
+		obsoletes_str = kstrdup(KLP_OBSOLETES, GFP_KERNEL);
+		if (!obsoletes_str) {
+			ret = -ENOMEM;
+			goto err_free_objs;
+		}
+
+		obs_array = kmalloc_array(count, sizeof(unsigned int), GFP_KERNEL);
+		if (!obs_array) {
+			kfree(obsoletes_str);
+			ret = -ENOMEM;
+			goto err_free_objs;
+		}
+
+		str = obsoletes_str;
+		while ((token = strsep(&str, ",")) != NULL) {

scripts/livepatch/init.c static int __init livepatch_mod_init(void) · line 126

Quoted 10 lines
scripts/livepatch/init.c +10 -0
+			unsigned int val;
+
+			ret = kstrtouint(token, 10, &val);
+			if (ret) {
+				kfree(obsoletes_str);
+				kfree(obs_array);
+				goto err_free_objs;
+			}
+			obs_array[i++] = val;
+		}

[Severity: Medium]
Does this code leak the funcs arrays on error?

Earlier in livepatch_mod_init(), the funcs arrays are dynamically allocated for each object in a loop:

	funcs = kzalloc(sizeof(struct klp_func) * (nr_funcs + 1), GFP_KERNEL);
	...
	obj->funcs = funcs;

If KLP_OBSOLETES parsing fails during string duplication, array allocation, or integer conversion, the error paths jump to err_free_objs. It appears that the cleanup label only frees the objs array itself but leaves the individual obj->funcs arrays allocated:

err_free_objs:

	kfree(objs);
err_free_patch:
	kfree(patch);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#9 lore raw

Re: [RFC PATCH v4 3/4] livepatch: Implement replace set for scoped atomic replace

Quoted 83 lines · On Tue, Aug 4, 2026 at 3:03 PM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Dynamically allocated funcs arrays are leaked on KLP_OBSOLETES parsing failure. --

--- Patch [3]: [RFC PATCH v4 3/4] livepatch: Implement replace set for scoped atomic replace --- commit d186609c1a3dbe210857d0040f657fa918504faf
Author: Yafang Shao <[email protected]>
Subject: livepatch: Implement replace set for scoped atomic replace

This commit introduces a more flexible atomic replace model for livepatches using provides and obsoletes fields. A new patch will replace any existing patch with a matching provides ID or any ID listed in its obsoletes array. The klp-build script and init code are updated to parse and validate these new fields.

Quoted 3 lines
scripts/livepatch/init.c +0 -0

[ ... ]

Quoted 1 line
scripts/livepatch/init.c +0 -0
@@ -72,10 +73,73 @@ static int __init livepatch_mod_init(void)

[ ... ]

Quoted 35 lines
scripts/livepatch/init.c +35 -0
+#ifdef KLP_OBSOLETES
+     /*
+      * Parse KLP_OBSOLETES string (format: "0,1,2" or "0" or empty)
+      * and convert to unsigned int array for patch->obsoletes
+      *
+      * Note: KLP_OBSOLETES is always defined and includes at least the
+      * provides ID, ensuring the patch replaces old patches with same ID.
+      */
+     {
+             unsigned int *obs_array;
+             unsigned int count = 1;
+             char *obsoletes_str;
+             char *token, *str;
+             int i = 0;
+
+             for (str = (char *)KLP_OBSOLETES; *str; str++) {
+                     if (*str == ',')
+                             count++;
+             }
+
+             obsoletes_str = kstrdup(KLP_OBSOLETES, GFP_KERNEL);
+             if (!obsoletes_str) {
+                     ret = -ENOMEM;
+                     goto err_free_objs;
+             }
+
+             obs_array = kmalloc_array(count, sizeof(unsigned int), GFP_KERNEL);
+             if (!obs_array) {
+                     kfree(obsoletes_str);
+                     ret = -ENOMEM;
+                     goto err_free_objs;
+             }
+
+             str = obsoletes_str;
+             while ((token = strsep(&str, ",")) != NULL) {

scripts/livepatch/init.c

Quoted 10 lines
scripts/livepatch/init.c +10 -0
+                     unsigned int val;
+
+                     ret = kstrtouint(token, 10, &val);
+                     if (ret) {
+                             kfree(obsoletes_str);
+                             kfree(obs_array);
+                             goto err_free_objs;
+                     }
+                     obs_array[i++] = val;
+             }

[Severity: Medium]
Does this code leak the funcs arrays on error?

Earlier in livepatch_mod_init(), the funcs arrays are dynamically allocated for each object in a loop:

        funcs = kzalloc(sizeof(struct klp_func) * (nr_funcs + 1), GFP_KERNEL);
        ...
        obj->funcs = funcs;

If KLP_OBSOLETES parsing fails during string duplication, array allocation, or integer conversion, the error paths jump to err_free_objs. It appears that the cleanup label only frees the objs array itself but leaves the individual obj->funcs arrays allocated:

Quoted 4 lines

err_free_objs:

        kfree(objs);
err_free_patch:
        kfree(patch);

You are right.
Furthermore, there is a pre-existing bug in the error path that should be fixed as well:

scripts/livepatch/init.c +1 -1
@@ -52,7 +52,7 @@ static int __init livepatch_mod_init(void)
                if (!funcs) {
                        ret = -ENOMEM;
                        for (int j = 0; j < i; j++)
-                               kfree(objs[i].funcs);
+                               kfree(objs[j].funcs);
                        goto err_free_objs;
                }
 
Signature · 2 lines
Regards
Yafang
maintainer
#10 lore raw

Re: [RFC PATCH v4 3/4] livepatch: Implement replace set for scoped atomic replace

In reply to Yafang Shao

On Mon, Aug 3, 2026 at 11:50 PM Yafang Shao <[email protected]> wrote:
[...]

Quoted 8 lines

/*
- * Check that the new livepatch will not break the existing system states.
- * Cumulative patches must handle all already modified states.
- * Non-cumulative patches can touch already modified states.
+ * Refuse loading a livepatch which would want to modify a
+ * function which is already livepatched with the livepatch
+ * with another "provides".
*/

The comment above is not really accurate. This function doesn't really check "provides" or "obsoletes". Also, as long as the old patch's "provides" is in the new patches "obsoletes" or "provides", this replace is allowed (the comment doesn't mention "obsoletes". )

Quoted 5 lines
kernel/livepatch/state.c +5 -0
+static bool klp_has_function_conflict(struct klp_patch *patch,
+                                     struct klp_patch *old_patch)
+{
+       struct klp_object *obj, *old_obj;
+       struct klp_func *func;

[...]

scripts/livepatch/klp-build process_args() { · line 257

Quoted 3 lines
scripts/livepatch/klp-build +2 -0
+       # Always add provides ID to obsoletes (even if provides=0)
+       # This ensures the new patch replaces old patches with the same provides ID

Do we really need th toolchain to enforce this? AFAICT, the kernel already guranteed "provides" means "obsoletes".

Also, it will be great if we can add some basic tests for this. We are working on some new test framework for klp-build toolchain. But we don't have to wait for that. It is always good to add some tests for a major feature change.

Thanks,
Song

Quoted 7 lines
scripts/livepatch/klp-build +7 -0
+       if [[ -n "$OBSOLETES" && "$OBSOLETES" != "[]" ]]; then
+               local obsoletes_clean="${OBSOLETES//[\[\] ]/}"
+               local IFS=','
+               local -a obs_array=()
+               local obs_id
+               local provides_added=0
+               local already_exists

[...]

#11 lore raw

Re: [RFC PATCH v4 3/4] livepatch: Implement replace set for scoped atomic replace

Quoted 12 lines · Song Liu

On Mon, Aug 3, 2026 at 11:50 PM Yafang Shao <[email protected]> wrote:
[...]

Quoted 8 lines

/*
- * Check that the new livepatch will not break the existing system states.
- * Cumulative patches must handle all already modified states.
- * Non-cumulative patches can touch already modified states.
+ * Refuse loading a livepatch which would want to modify a
+ * function which is already livepatched with the livepatch
+ * with another "provides".
*/

Quoted 4 lines

The comment above is not really accurate. This function doesn't really check "provides" or "obsoletes". Also, as long as the old patch's "provides" is in the new patches "obsoletes" or "provides", this replace is allowed (the comment doesn't mention "obsoletes". )

This is already handled by klp_patch_replaceable() in klp_is_patch_compatible(). However, it would be clearer to move the klp_patch_replaceable() check into klp_has_function_conflict() and update the comments accordingly.

Quoted 8 lines
Quoted 6 lines
kernel/livepatch/state.c +5 -0
+static bool klp_has_function_conflict(struct klp_patch *patch,
+                                     struct klp_patch *old_patch)
+{
+       struct klp_object *obj, *old_obj;
+       struct klp_func *func;

[...]

Quoted 1 line
Quoted 5 lines

scripts/livepatch/klp-build process_args() { · line 257

Quoted 2 lines
scripts/livepatch/klp-build +2 -0
+       # Always add provides ID to obsoletes (even if provides=0)
+       # This ensures the new patch replaces old patches with the same provides ID

Do we really need th toolchain to enforce this? AFAICT, the kernel already guranteed "provides" means "obsoletes".

Dropping this enforcement simplifies the code logic. I will remove it in the next version.

Quoted 5 lines

Also, it will be great if we can add some basic tests for this. We are working on some new test framework for klp-build toolchain. But we don't have to wait for that. It is always good to add some tests for a major feature change.

Sure. I will add self tests in the next version.

Signature · 2 lines
Regards
Yafang
#12 lore raw

RFC PATCH v4 4/4 livepatch: Deprecate stack_order

In reply to Yafang Shao

stack_order is no longer needed for atomic-replace livepatches, as a single function can only be modified by a unique replace_set. Since this livepatch sysfs interface is mainly intended for kernel developers, backward compatibility does not need to be maintained.

---
 .../ABI/removed/sysfs-kernel-livepatch        |  9 +++++++
 .../ABI/testing/sysfs-kernel-livepatch        |  9 -------
 kernel/livepatch/core.c                       | 24 -------------------
 3 files changed, 9 insertions(+), 33 deletions(-)
Documentation/ABI/removed/sysfs-kernel-livepatch +9 -0
index 87d57ba27326..fb6ff9c3b43e 100644
@@ -5,3 +5,12 @@ Contact:	[email protected]
 Description:
 		An attribute which indicates whether the patch supports
 		atomic-replace.
+
+What:          /sys/kernel/livepatch/<patch>/stack_order
+Date:          Jan 2025
+KernelVersion: 6.14.0
+Description:
+		This attribute specifies the sequence in which live patch modules
+		are applied to the system. If multiple live patches modify the same
+		function, the implementation with the biggest 'stack_order' number
+		is used, unless a transition is currently in progress.
Documentation/ABI/testing/sysfs-kernel-livepatch +0 -9
index 2588f676deb1..3564b3e4385f 100644
@@ -67,15 +67,6 @@ Description:
 		either this patch's provides id or any id in the obsoletes
 		list will be atomically replaced.
 
-What:		/sys/kernel/livepatch/<patch>/stack_order
-Date:		Jan 2025
-KernelVersion:	6.14.0
-Description:
-		This attribute specifies the sequence in which live patch modules
-		are applied to the system. If multiple live patches modify the same
-		function, the implementation with the biggest 'stack_order' number
-		is used, unless a transition is currently in progress.
-
 What:		/sys/kernel/livepatch/<patch>/<object>
 Date:		Nov 2014
 KernelVersion:	3.19.0
kernel/livepatch/core.c +0 -24
index bd37ed99814e..5cadced61d2d 100644
@@ -352,7 +352,6 @@ int klp_apply_section_relocs(struct module *pmod, Elf_Shdr *sechdrs,
  * /sys/kernel/livepatch/<patch>/force
  * /sys/kernel/livepatch/<patch>/provides
  * /sys/kernel/livepatch/<patch>/obsoletes
- * /sys/kernel/livepatch/<patch>/stack_order
  * /sys/kernel/livepatch/<patch>/<object>
  * /sys/kernel/livepatch/<patch>/<object>/patched
  * /sys/kernel/livepatch/<patch>/<object>/<function,sympos>
@@ -477,40 +476,17 @@ static ssize_t obsoletes_show(struct kobject *kobj,
 	return len;
 }
 
-static ssize_t stack_order_show(struct kobject *kobj,
-				struct kobj_attribute *attr, char *buf)
-{
-	struct klp_patch *patch, *this_patch;
-	int stack_order = 0;
-
-	this_patch = container_of(kobj, struct klp_patch, kobj);
-
-	mutex_lock(&klp_mutex);
-
-	klp_for_each_patch(patch) {
-		stack_order++;
-		if (patch == this_patch)
-			break;
-	}
-
-	mutex_unlock(&klp_mutex);
-
-	return sysfs_emit(buf, "%d\n", stack_order);
-}
-
 static struct kobj_attribute enabled_kobj_attr = __ATTR_RW(enabled);
 static struct kobj_attribute transition_kobj_attr = __ATTR_RO(transition);
 static struct kobj_attribute force_kobj_attr = __ATTR_WO(force);
 static struct kobj_attribute provides_kobj_attr = __ATTR_RO(provides);
 static struct kobj_attribute obsoletes_kobj_attr = __ATTR_RO(obsoletes);
-static struct kobj_attribute stack_order_kobj_attr = __ATTR_RO(stack_order);
 static struct attribute *klp_patch_attrs[] = {
 	&enabled_kobj_attr.attr,
 	&transition_kobj_attr.attr,
 	&force_kobj_attr.attr,
 	&provides_kobj_attr.attr,
 	&obsoletes_kobj_attr.attr,
-	&stack_order_kobj_attr.attr,
 	NULL
 };
 ATTRIBUTE_GROUPS(klp_patch);
Signature · 1 line
2.52.0