Skip to contentSkip to conversation

livepatch: shadow variables

PATCH Superseded Joe Lawrence 5 participants 19 messages Aug 14, 2017 – Aug 31, 2017

Subsystems (2)

v4 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Joe Lawrence

author maintainer
#0 lore raw

PATCH v4 1/1 livepatch: shadow variables

v4

- klp_shadow_attach(), klp_shadow_get_or_attach(), and klp_shadow_update_or_attach()
- fix up return values depending on whether a new_shadow variable was allocated, or an existing one was used
- kfree new_shadow, not shadow_data when shadow variable is found under the lock (2nd search try)
- refactor away most of the exit labels
- move klp_shadow_set() calls outside of the klp_shadow_lock
- fix multiline comment format

- klp_shadow_attach()
- drop unnecessary variable assignment for conditional

- s/shadow_match()/klp_shadow_match()/g

- klp_shadow_match(), klp_shadow_set(), klp_shadow_add()
- add "caller should hold lock" comments

- Documentation
- remove unnecessary klp_shadow_get() call in use-case
- s/its shadow variable lifetimes/their shadow variables lifetimes/

Joe Lawrence (1):
livepatch: introduce shadow variable API

 Documentation/livepatch/shadow-vars.txt   | 215 +++++++++++++++++
 include/linux/livepatch.h                 |  10 +
 kernel/livepatch/Makefile                 |   2 +-
 kernel/livepatch/shadow.c                 | 382 ++++++++++++++++++++++++++++++
 samples/Kconfig                           |   5 +-
 samples/livepatch/Makefile                |   3 +
 samples/livepatch/livepatch-shadow-fix1.c | 174 ++++++++++++++
 samples/livepatch/livepatch-shadow-fix2.c | 167 +++++++++++++
 samples/livepatch/livepatch-shadow-mod.c  | 224 ++++++++++++++++++
 9 files changed, 1178 insertions(+), 4 deletions(-)
 create mode 100644 Documentation/livepatch/shadow-vars.txt
 create mode 100644 kernel/livepatch/shadow.c
 create mode 100644 samples/livepatch/livepatch-shadow-fix1.c
 create mode 100644 samples/livepatch/livepatch-shadow-fix2.c
 create mode 100644 samples/livepatch/livepatch-shadow-mod.c
Signature · 1 line
1.8.3.1
author maintainer
#1 lore raw

PATCH v4 1/1 livepatch: introduce shadow variable API

Add exported API for livepatch modules:

klp_shadow_get()
klp_shadow_attach()
klp_shadow_get_or_attach()
klp_shadow_update_or_attach()
klp_shadow_detach()
klp_shadow_detach_all()

that implement "shadow" variables, which allow callers to associate new shadow fields to existing data structures. This is intended to be used by livepatch modules seeking to emulate additions to data structure definitions.

See Documentation/livepatch/shadow-vars.txt for a summary of the new shadow variable API, including a few common use cases.

See samples/livepatch/livepatch-shadow-* for example modules that demonstrate shadow variables.

---
 Documentation/livepatch/shadow-vars.txt   | 215 +++++++++++++++++
 include/linux/livepatch.h                 |  10 +
 kernel/livepatch/Makefile                 |   2 +-
 kernel/livepatch/shadow.c                 | 382 ++++++++++++++++++++++++++++++
 samples/Kconfig                           |   5 +-
 samples/livepatch/Makefile                |   3 +
 samples/livepatch/livepatch-shadow-fix1.c | 174 ++++++++++++++
 samples/livepatch/livepatch-shadow-fix2.c | 167 +++++++++++++
 samples/livepatch/livepatch-shadow-mod.c  | 224 ++++++++++++++++++
 9 files changed, 1178 insertions(+), 4 deletions(-)
 create mode 100644 Documentation/livepatch/shadow-vars.txt
 create mode 100644 kernel/livepatch/shadow.c
 create mode 100644 samples/livepatch/livepatch-shadow-fix1.c
 create mode 100644 samples/livepatch/livepatch-shadow-fix2.c
 create mode 100644 samples/livepatch/livepatch-shadow-mod.c
Documentation/livepatch/shadow-vars.txt new file +215 -0
new file mode 100644
index 000000000000..b8e918a37078
@@ -0,0 +1,215 @@
+================
+Shadow Variables
+================
+
+Shadow variables are a simple way for livepatch modules to associate
+additional "shadow" data with existing data structures.  Shadow data is
+allocated separately from parent data structures, which are left
+unmodified.  The shadow variable API described in this document is used
+to allocate/attach and detach/release shadow variables to their parents.
+
+The implementation introduces a global, in-kernel hashtable that
+associates pointers to parent objects and a numeric identifier of the
+shadow data.  The numeric identifier is a simple enumeration that may be
+used to describe shadow variable version, class or type, etc.  More
+specifically, the parent pointer serves as the hashtable key while the
+numeric id subsequently filters hashtable queries.  Multiple shadow
+variables may attach to the same parent object, but their numeric
+identifier distinguishes between them.
+
+
+1. Brief API summary
+====================
+
+(See the full API usage docbook notes in livepatch/shadow.c.)
+
+A hashtable references all shadow variables.  These references are
+stored and retrieved through a <obj, id> pair.
+
+* The klp_shadow variable data structure encapsulates both tracking
+meta-data and shadow-data:
+  - meta-data
+    - obj - pointer to parent object
+    - id - data identifier
+  - data[] - storage for shadow data
+
+  It is important to note that the klp_shadow_attach(),
+  klp_shadow_get_or_attach(), and klp_shadow_update_or_attach() calls,
+  described below, store a *copy* of the data that the functions are
+  provided.
+
+* klp_shadow_get() - retrieve a shadow variable data pointer
+  - search hashtable for <obj, id> pair
+
+* klp_shadow_attach() - allocate and add a new shadow variable
+  - search hashtable for <obj, id> pair
+  - if exists
+    - WARN and return NULL
+  - if <obj, id> doesn't already exist
+    - allocate a new shadow variable
+    - copy data into the new shadow variable
+    - add <obj, id> to the global hashtable
+
+* klp_shadow_get_or_attach() - get existing or attach a new shadow variable
+  - search hashtable for <obj, id> pair
+  - if exists
+    - return existing shadow variable
+  - if <obj, id> doesn't already exist
+    - allocate a new shadow variable
+    - copy data into the new shadow variable
+    - add <obj, id> pair to the global hashtable
+
+* klp_shadow_update_or_attach() - update or attach a new shadow variable
+  - search hashtable for <obj, id> pair
+  - if exists
+    -  update and return existing shadow variable
+  - if <obj, id> doesn't already exist
+    - allocate a new shadow variable
+    - copy data into the new shadow variable
+    - add <obj, id> pair to the global hashtable
+
+* klp_shadow_detach() - detach and free a <obj, id> shadow variable
+  - find and remove a <obj, id> reference from global hashtable
+    - if found, free shadow variable
+
+* klp_shadow_detach_all() - detach and free all <*, id> shadow variables
+  - find and remove any <*, id> references from global hashtable
+    - if found, free shadow variable
+
+
+2. Use cases
+============
+
+(See the example shadow variable livepatch modules in samples/livepatch/
+for full working demonstrations.)
+
+For the following use-case examples, consider commit 1d147bfa6429
+("mac80211: fix AP powersave TX vs.  wakeup race"), which added a
+spinlock to net/mac80211/sta_info.h :: struct sta_info.  Each use-case
+example can be considered a stand-alone livepatch implementation of this
+fix.
+
+
+Matching parent's lifecycle
+---------------------------
+
+If parent data structures are frequently created and destroyed, it may
+be easiest to align their shadow variables lifetimes to the same
+allocation and release functions.  In this case, the parent data
+structure is typically allocated, initialized, then registered in some
+manner.  Shadow variable allocation and setup can then be considered
+part of the parent's initialization and should be completed before the
+parent "goes live" (ie, any shadow variable get-API requests are made
+for this <obj, id> pair.
+
+For commit 1d147bfa6429, when a parent sta_info structure is allocated,
+attach a shadow copy of the ps_lock pointer, then initialize it:
+
+#define PS_LOCK 1
+struct sta_info *sta_info_alloc(struct ieee80211_sub_if_data *sdata,
+				const u8 *addr, gfp_t gfp)
+{
+	struct sta_info *sta;
+	spinlock_t *ps_lock;
+
+	/* Parent structure is created */
+	sta = kzalloc(sizeof(*sta) + hw->sta_data_size, gfp);
+
+	/* Attach a corresponding shadow variable, then initialize it */
+	ps_lock = klp_shadow_attach(sta, PS_LOCK, NULL, sizeof(ps_lock), gfp);
+	if (!ps_lock)
+		goto shadow_fail;
+	spin_lock_init(ps_lock);
+	...
+
+When requiring a ps_lock, query the shadow variable API to retrieve one
+for a specific struct sta_info:
+
+void ieee80211_sta_ps_deliver_wakeup(struct sta_info *sta)
+{
+	spinlock_t *ps_lock;
+
+	/* sync with ieee80211_tx_h_unicast_ps_buf */
+	ps_lock = klp_shadow_get(sta, PS_LOCK);
+	if (ps_lock)
+		spin_lock(ps_lock);
+	...
+
+When the parent sta_info structure is freed, first detach the shadow
+variable:
+
+void sta_info_free(struct ieee80211_local *local, struct sta_info *sta)
+{
+	spinlock_t *ps_lock;
+
+	ps_lock = klp_shadow_get(sta, PS_LOCK);
+	if (ps_lock)
+		klp_shadow_detach(sta, PS_LOCK);
+
+	kfree(sta);
+	...
+
+
+In-flight parent objects
+------------------------
+
+Sometimes it may not be convenient or possible to allocate shadow
+variables alongside their parent objects.  Or a livepatch fix may
+require shadow varibles to only a subset of parent object instances.  In
+these cases, the klp_shadow_get_or_attach() call can be used to attach
+shadow variables to parents already in-flight.
+
+For commit 1d147bfa6429, a good spot to attach a shadow spinlock is
+inside ieee80211_sta_ps_deliver_wakeup():
+
+#define PS_LOCK 1
+void ieee80211_sta_ps_deliver_wakeup(struct sta_info *sta)
+{
+	DEFINE_SPINLOCK(ps_lock_fallback);
+	spinlock_t *ps_lock;
+
+	/* sync with ieee80211_tx_h_unicast_ps_buf */
+	ps_lock = klp_shadow_get_or_attach(sta, PS_LOCK,
+			&ps_lock_fallback, sizeof(ps_lock_fallback),
+			GFP_ATOMIC);
+	if (ps_lock)
+		spin_lock(ps_lock);
+	...
+
+This usage will create a shadow variable, only if needed, otherwise it
+will use one that was already created for this <obj, id> pair.
+
+Like the previous use-case, the shadow spinlock needs to be cleaned up.
+A shadow variable can be detached just before its parent object is
+freed, or even when the shadow variable itself is no longer required.
+
+
+Other use-cases
+---------------
+
+Like klp_shadow_get_or_attach(), klp_shadow_update_or_attach() can be
+used to attach shadow variables to already allocated parent data
+structures in-flight. Unlike the former function,
+klp_shadow_update_or_attach() will *update* an existing shadow
+variable's data area.  This behavior may be useful when shadowing data
+who's lifetime does *not* follow the parent object's.  For example, when
+adding a "jiffies" or "last task pointer" shadow variable, overwriting
+the existing shadow variable's data copy is expected.
+
+Shadow variables can also be used as a flag indicating that a data
+structure was allocated by new, livepatched code.  In this case, it
+doesn't matter what data value the shadow variable holds, its existence
+suggests how to handle the parent object.
+
+
+3. References
+=============
+
+* https://github.com/dynup/kpatch
+The livepatch implementation is based on the kpatch version of shadow
+variables.
+
+* http://files.mkgnu.net/files/dynamos/doc/papers/dynamos_eurosys_07.pdf
+Dynamic and Adaptive Updates of Non-Quiescent Subsystems in Commodity
+Operating System Kernels (Kritis Makris, Kyung Dong Ryu 2007) presented
+a datatype update technique called "shadow data structures".
include/linux/livepatch.h +10 -0
index 194991ef9347..0033aaea8572 100644
@@ -164,6 +164,16 @@ static inline bool klp_have_reliable_stack(void)
 	       IS_ENABLED(CONFIG_HAVE_RELIABLE_STACKTRACE);
 }
 
+void *klp_shadow_get(void *obj, unsigned long id);
+void *klp_shadow_attach(void *obj, unsigned long id, void *data,
+			size_t size, gfp_t gfp_flags);
+void *klp_shadow_get_or_attach(void *obj, unsigned long id, void *data,
+			       size_t size, gfp_t gfp_flags);
+void *klp_shadow_update_or_attach(void *obj, unsigned long id, void *data,
+				  size_t size, gfp_t gfp_flags);
+void klp_shadow_detach(void *obj, unsigned long id);
+void klp_shadow_detach_all(unsigned long id);
+
 #else /* !CONFIG_LIVEPATCH */
 
 static inline int klp_module_coming(struct module *mod) { return 0; }
kernel/livepatch/Makefile +1 -1
index 2b8bdb1925da..b36ceda6488e 100644
@@ -1,3 +1,3 @@
 obj-$(CONFIG_LIVEPATCH) += livepatch.o
 
-livepatch-objs := core.o patch.o transition.o
+livepatch-objs := core.o patch.o shadow.o transition.o
kernel/livepatch/shadow.c new file +382 -0

382 lines not on this page · raw message

samples/Kconfig +2 -3
index 9cb63188d3ef..c332a3b9de05 100644
@@ -71,11 +71,10 @@ config SAMPLE_RPMSG_CLIENT
 	  the rpmsg bus.
 
 config SAMPLE_LIVEPATCH
-	tristate "Build live patching sample -- loadable modules only"
+	tristate "Build live patching samples -- loadable modules only"
 	depends on LIVEPATCH && m
 	help
-	  Builds a sample live patch that replaces the procfs handler
-	  for /proc/cmdline to print "this has been live patched".
+	  Build sample live patch demonstrations.
 
 config SAMPLE_CONFIGFS
 	tristate "Build configfs patching sample -- loadable modules only"
samples/livepatch/Makefile +3 -0
index 10319d7ea0b1..539e81d433cd 100644
@@ -1 +1,4 @@
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-sample.o
+obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-mod.o
+obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-fix1.o
+obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-fix2.o
samples/livepatch/livepatch-shadow-fix1.c new file +174 -0

174 lines not on this page · raw message

samples/livepatch/livepatch-shadow-fix2.c new file +167 -0

167 lines not on this page · raw message

samples/livepatch/livepatch-shadow-mod.c new file +224 -0

224 lines not on this page · raw message

Signature · 1 line
1.8.3.1
Acked-by on v4 1/1
#2 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

Quoted 14 lines · Joe Lawrence

Add exported API for livepatch modules:

klp_shadow_get()
klp_shadow_attach()
klp_shadow_get_or_attach()
klp_shadow_update_or_attach()
klp_shadow_detach()
klp_shadow_detach_all()

that implement "shadow" variables, which allow callers to associate new shadow fields to existing data structures. This is intended to be used by livepatch modules seeking to emulate additions to data structure definitions.

Quoted 7 lines

See Documentation/livepatch/shadow-vars.txt for a summary of the new shadow variable API, including a few common use cases.

See samples/livepatch/livepatch-shadow-* for example modules that demonstrate shadow variables.

Signature · 1 line
Josh
maintainer Acked-by on v4 1/1
#3 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

In reply to Joe Lawrence
Quoted 20 lines
kernel/livepatch/shadow.c new file +19 -0
+/*
+ * klp_shadow_set() - initialize a shadow variable
+ * @shadow:	shadow variable to initialize
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ * @data:	pointer to data to attach to parent
+ * @size:	size of attached data
+ *
+ * Callers should hold the klp_shadow_lock.
+ */
+static inline void klp_shadow_set(struct klp_shadow *shadow, void *obj,
+				  unsigned long id, void *data, size_t size)
+{
+	shadow->obj = obj;
+	shadow->id = id;
+
+	if (data)
+		memcpy(shadow->data, data, size);
+}

[...]

Quoted 26 lines
kernel/livepatch/shadow.c new file +26 -0
+/**
+ * klp_shadow_attach() - allocate and add a new shadow variable
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ * @data:	pointer to data to attach to parent
+ * @size:	size of attached data
+ * @gfp_flags:	GFP mask for allocation
+ *
+ * If an existing <obj, id> shadow variable can be found, this routine
+ * will issue a WARN, exit early and return NULL.
+ *
+ * Allocates @size bytes for new shadow variable data using @gfp_flags
+ * and copies @size bytes from @data into the new shadow variable's own
+ * data space.  If @data is NULL, @size bytes are still allocated, but
+ * no copy is performed.  The new shadow variable is then added to the
+ * global hashtable.
+ *
+ * Return: the shadow variable data element, NULL on duplicate or
+ * failure.
+ */
+void *klp_shadow_attach(void *obj, unsigned long id, void *data,
+			size_t size, gfp_t gfp_flags)
+{
+	struct klp_shadow *new_shadow;
+	void *shadow_data;
+	unsigned long flags;

kernel/livepatch/shadow.c line 180

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+
+	/* Take error exit path if <obj, id> already exists */
+	if (unlikely(klp_shadow_get(obj, id)))
+		goto err_exists;
+
+	/* Allocate a new shadow variable for use inside the lock below */
+	new_shadow = kzalloc(size + sizeof(*new_shadow), gfp_flags);
+	if (!new_shadow)
+		goto err;
+	klp_shadow_set(new_shadow, obj, id, data, size);

There is a comment above about locking and we do not take the spinlock here. That could surprise someone. So I'd keep only klp_shadow_add() comment, because there it is strictly needed. It depends on the context in all other cases.

Could you also add a comment above klp_shadow_lock definition about what it aims to protect?

kernel/livepatch/shadow.c line 185

Quoted 4 lines
kernel/livepatch/shadow.c new file +4 -0
+	/* Look for <obj, id> again under the lock */
+	spin_lock_irqsave(&klp_shadow_lock, flags);
+	shadow_data = klp_shadow_get(obj, id);
+	if (unlikely(shadow_data)) {

shadow_data is not needed anywhere, so you could do the same as for the first speculative search and remove shadow_data variable all together.

Quoted 11 lines
kernel/livepatch/shadow.c new file +11 -0
+		/*
+		 * Shadow variable was found, throw away speculative
+		 * allocation and update/return the existing one.
+		 */
+		spin_unlock_irqrestore(&klp_shadow_lock, flags);
+		kfree(new_shadow);
+		goto err_exists;
+	}
+
+	/* No <obj, id> found, add the newly allocated one */
+	klp_shadow_add(new_shadow);

kernel/livepatch/shadow.c line 206

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+	spin_unlock_irqrestore(&klp_shadow_lock, flags);
+
+	return new_shadow->data;
+
+err_exists:
+	WARN(1, "Duplicate shadow variable <%p, %lx>\n", obj, id);
+err:
+	return NULL;
+}
+EXPORT_SYMBOL_GPL(klp_shadow_attach);

Otherwise it looks good. You can add my

with those nits fixed.

Thanks,
Miroslav

author maintainer
#4 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

Quoted 7 lines · Miroslav Benes
Quoted 2 lines

[ ... snip ... ]

There is a comment above about locking and we do not take the spinlock here. That could surprise someone. So I'd keep only klp_shadow_add() comment, because there it is strictly needed. It depends on the context in all other cases.

Good catch, I think this changed in this last version when I moved some of the work outside the lock.

Quoted 3 lines

Could you also add a comment above klp_shadow_lock definition about what it aims to protect?

How about "klp_shadow_lock provides exclusive access to the klp_shadow_hash and the shadow variables it references." or were thinking of something more detailed?

Quoted 7 lines

kernel/livepatch/shadow.c line 185

Quoted 4 lines
kernel/livepatch/shadow.c new file +4 -0
+	/* Look for <obj, id> again under the lock */
+	spin_lock_irqsave(&klp_shadow_lock, flags);
+	shadow_data = klp_shadow_get(obj, id);
+	if (unlikely(shadow_data)) {

shadow_data is not needed anywhere, so you could do the same as for the first speculative search and remove shadow_data variable all together.

Ok.

Quoted 7 lines
Quoted 1 line

[ ... snip ... ]

Otherwise it looks good. You can add my

with those nits fixed.

Thank you for all the suggestions and reviews!

-- Joe

maintainer
#5 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

Quoted 8 lines
Quoted 4 lines

Could you also add a comment above klp_shadow_lock definition about what it aims to protect?

How about "klp_shadow_lock provides exclusive access to the klp_shadow_hash and the shadow variables it references." or were thinking of something more detailed?

No, this is good. Thanks.

Miroslav

maintainer
#6 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

In reply to Joe Lawrence
Quoted 30 lines · Joe Lawrence

Add exported API for livepatch modules:

klp_shadow_get()
klp_shadow_attach()
klp_shadow_get_or_attach()
klp_shadow_update_or_attach()
klp_shadow_detach()
klp_shadow_detach_all()

that implement "shadow" variables, which allow callers to associate new shadow fields to existing data structures. This is intended to be used by livepatch modules seeking to emulate additions to data structure definitions.

See Documentation/livepatch/shadow-vars.txt for a summary of the new shadow variable API, including a few common use cases.

See samples/livepatch/livepatch-shadow-* for example modules that demonstrate shadow variables.

kernel/livepatch/shadow.c new file +5 -0
new file mode 100644
index 000000000000..0ebd4b635e4f
+/**
+ * klp_shadow_match() - verify a shadow variable matches given <obj, id>
+ * @shadow:	shadow variable to match
+ * @obj:	pointer to parent object
+ * @id:		data identifier

kernel/livepatch/shadow.c line 83

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+ *
+ * Return: true if the shadow variable matches.
+ *
+ * Callers should hold the klp_shadow_lock.
+ */
+static inline bool klp_shadow_match(struct klp_shadow *shadow, void *obj,
+				unsigned long id)
+{
+	return shadow->obj == obj && shadow->id == id;
+}

Do we really need this function? It is called only in situations where shadow->obj == obj is always true. Especially the use in klp_shadow_detach_all() is funny because we pass shadow->obj as the shadow parameter.

Quoted 38 lines
kernel/livepatch/shadow.c new file +38 -0
+
+/**
+ * klp_shadow_get() - retrieve a shadow variable data pointer
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ *
+ * Return: the shadow variable data element, NULL on failure.
+ */
+void *klp_shadow_get(void *obj, unsigned long id)
+{
+	struct klp_shadow *shadow;
+
+	rcu_read_lock();
+
+	hash_for_each_possible_rcu(klp_shadow_hash, shadow, node,
+				   (unsigned long)obj) {
+
+		if (klp_shadow_match(shadow, obj, id)) {
+			rcu_read_unlock();
+			return shadow->data;
+		}
+	}
+
+	rcu_read_unlock();
+
+	return NULL;
+}
+EXPORT_SYMBOL_GPL(klp_shadow_get);
+
+/*
+ * klp_shadow_set() - initialize a shadow variable
+ * @shadow:	shadow variable to initialize
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ * @data:	pointer to data to attach to parent
+ * @size:	size of attached data
+ *
+ * Callers should hold the klp_shadow_lock.

kernel/livepatch/shadow.c line 131

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+ */
+static inline void klp_shadow_set(struct klp_shadow *shadow, void *obj,
+				  unsigned long id, void *data, size_t size)
+{
+	shadow->obj = obj;
+	shadow->id = id;
+
+	if (data)
+		memcpy(shadow->data, data, size);
+}

The function name suggests that it is a counterpart of klp_shadow_get() but it is not. Which is a bit confusing.

Hmm, the purpose of this function is to reduce the size of cut&pasted code between all that klp_shadow_*attach() variants. But there is still too much cut&pasted code. In fact, the base logic of all variants is basically the same. The only small difference should be how they handle the situation when the variable is already there.

OK, there is a locking difference in the update variant but it is questionable, see below.

I would suggest to do something like this:

static enum klp_shadow_attach_existing_handling {
KLP_SHADOW_EXISTING_RETURN,
KLP_SHADOW_EXISTING_WARN,
KLP_SHADOW_EXISING_UPDATE,
};

void *__klp_shadow_get_or_attach(void *obj, unsigned long id, void *data,
size_t size, gfp_t gfp_flags,
enum klp_shadow_attach_existing_handling existing_handling)

{
	struct klp_shadow *new_shadow;
	void *shadow_data;
	unsigned long flags;

	/* Check if the shadow variable if <obj, id> already exists */
	shadow_data = klp_shadow_get(obj, id);
	if (shadow_data)
		goto exists;

	/* Allocate a new shadow variable for use inside the lock below */
	new_shadow = kzalloc(size + sizeof(*new_shadow), gfp_flags);
	if (!new_shadow) {
		pr_error("failed to allocate shadow variable <0x%p, %ul>\n",
				 obj, id);
		return NULL;
	}

	new_shadow->obj = obj;
	new_shadow->id = id;

	/* initialize the shadow variable if if data provided */
	if (data)
		memcpy(new_shadow->data, data, size);

	/* Look for <obj, id> again under the lock */
	spin_lock_irqsave(&klp_shadow_lock, flags);
	shadow_data = klp_shadow_get(obj, id);
	if (unlikely(shadow_data)) {
		/*
		 * Shadow variable was found, throw away speculative
		 * allocation and update/return the existing one.
		 */
		spin_unlock_irqrestore(&klp_shadow_lock, flags);
		kfree(new_shadow);
		goto exists;
	}

	/* No <obj, id> found, so attach the newly allocated one */
	hash_add_rcu(klp_shadow_hash, &new_shadow->node,
		     (unsigned long)new_shadow->obj);
	spin_unlock_irqrestore(&klp_shadow_lock, flags);

	return new_shadow->data;

exists:

	switch(existing_handling) {
	case KLP_SHADOW_EXISTING_RETURN:
		break;

	case KLP_SHADOW_EXISTING_WARN:
		WARN(1, "Duplicate shadow variable <%p, %lx>\n", obj, id);
		shadow_data = NULL;
		break;

	case KLP_SHADOW_EXISING_UPDATE:
		if (data)
			memcpy(shadow_data, data, size);
		break;
	}
	return shadow_data;
}

void *klp_shadow_attach(void *obj, unsigned long id, void *data,
size_t size, gfp_t gfp_flags)

{
	return __klp_shadow_get_or_attach(obj, id, data, size,
			gfp_flags, KLP_SHADOW_EXISTING_RETURN);
}

void *klp_shadow_get_or_attach(void *obj, unsigned long id, void *data,
size_t size, gfp_t gfp_flags)

{
	return __klp_shadow_get_or_attach(obj, id, data, size,
			gfp_flags, KLP_SHADOW_EXISTING_WARN);
}

void *klp_shadow_update_or_attach(void *obj, unsigned long id, void *data,
size_t size, gfp_t gfp_flags)

{
	return __klp_shadow_get_or_attach(obj, id, data, size,
			gfp_flags, KLP_SHADOW_EXISTING_UPDATE);
}

Note that the above code is not even compile tested.

It removes a lot of cut&pasted code and the difference is more clear.

It updates the data outside klp_shadow_lock. But it should be fine. The lock is there to keep the hast table consistent (avoid duplicates). Users are responsible to synchronize the data stored in the variables their own way.

Hmm, the more I think about it the more I would suggest to remove klp_shadow_update_or_attach() variant. It has very weird logic. IMHO, it is not obvious that it must be called under the locks that synchronize the shadow data. IMHO, the other two variants are much more clear and enough. Or do you have a good real life example for it?

Quoted 18 lines
kernel/livepatch/shadow.c new file +18 -0
+/**
+ * klp_shadow_add() - add a shadow variable to the hashtable
+ * @shadow:	shadow variable to add
+ *
+ * Callers should hold the klp_shadow_lock.
+ */
+static inline void klp_shadow_add(struct klp_shadow *shadow)
+{
+	hash_add_rcu(klp_shadow_hash, &shadow->node,
+		     (unsigned long)shadow->obj);
+}
+
+/**
+ * klp_shadow_attach() - allocate and add a new shadow variable
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ * @data:	pointer to data to attach to parent
+ * @size:	size of attached data

kernel/livepatch/shadow.c line 160

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+ * @gfp_flags:	GFP mask for allocation
+ *
+ * If an existing <obj, id> shadow variable can be found, this routine
+ * will issue a WARN, exit early and return NULL.
+ *
+ * Allocates @size bytes for new shadow variable data using @gfp_flags
+ * and copies @size bytes from @data into the new shadow variable's own
+ * data space.  If @data is NULL, @size bytes are still allocated, but
+ * no copy is performed.  The new shadow variable is then added to the
+ * global hashtable.

I would swap the two paragraphs. We should describe the main function first and corner cases later.

Quoted 6 lines

+ * Return: the shadow variable data element, NULL on duplicate or
+ * failure.
+ */

kernel/livepatch/shadow.c new file +3 -0
+void *klp_shadow_attach(void *obj, unsigned long id, void *data,
+			size_t size, gfp_t gfp_flags)
+{

kernel/livepatch/shadow.c line 177

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+	struct klp_shadow *new_shadow;
+	void *shadow_data;
+	unsigned long flags;
+
+	/* Take error exit path if <obj, id> already exists */
+	if (unlikely(klp_shadow_get(obj, id)))
+		goto err_exists;
+
+	/* Allocate a new shadow variable for use inside the lock below */
+	new_shadow = kzalloc(size + sizeof(*new_shadow), gfp_flags);

We should print an error message when the memory cannot be allocated. Otherwise we will return NULL without explanation. It will be especially helpful when a caller forgets to check for NULL.

Quoted 36 lines
kernel/livepatch/shadow.c new file +36 -0
+	if (!new_shadow)
+		goto err;
+	klp_shadow_set(new_shadow, obj, id, data, size);
+
+	/* Look for <obj, id> again under the lock */
+	spin_lock_irqsave(&klp_shadow_lock, flags);
+	shadow_data = klp_shadow_get(obj, id);
+	if (unlikely(shadow_data)) {
+		/*
+		 * Shadow variable was found, throw away speculative
+		 * allocation and update/return the existing one.
+		 */
+		spin_unlock_irqrestore(&klp_shadow_lock, flags);
+		kfree(new_shadow);
+		goto err_exists;
+	}
+
+	/* No <obj, id> found, add the newly allocated one */
+	klp_shadow_add(new_shadow);
+	spin_unlock_irqrestore(&klp_shadow_lock, flags);
+
+	return new_shadow->data;
+
+err_exists:
+	WARN(1, "Duplicate shadow variable <%p, %lx>\n", obj, id);
+err:
+	return NULL;
+}
+EXPORT_SYMBOL_GPL(klp_shadow_attach);
+
+/**
+ * klp_shadow_get_or_attach() - get existing or attach a new shadow variable
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ * @data:	pointer to data to attach to parent
+ * @size:	size of attached data

kernel/livepatch/shadow.c line 223

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+ * @gfp_flags:	GFP mask for allocation
+ *
+ * If an existing <obj, id> shadow variable can be found, it will be
+ * used (but *not* updated) in the return value of this function.
+ *
+ * Allocates @size bytes for new shadow variable data using @gfp_flags
+ * and copies @size bytes from @data into the new shadow variable's own
+ * data space.  If @data is NULL, @size bytes are still allocated, but
+ * no copy is performed.  The new shadow variable is then added to the
+ * global hashtable.

There is a lot of duplicated text here. Also you need to read the first paragraph very carefully. Otherwise, you miss that the 2nd paragraph is true only in special situation.

I would make it more clear, something like:

It returns pointer to the shadow data when they already exist. Otherwise, it attaches and new shadow variable like klp_shadow_attach().

It guarantees that only one shadow variable will exists with the given @id for the given @obj. Also it guarantees that the variable will be initialized by the given @data only when it did not exist before.

Quoted 9 lines
samples/livepatch/livepatch-shadow-fix1.c new file +4 -0
new file mode 100644
index 000000000000..5acc838463d1
+void livepatch_fix1_dummy_free(struct dummy *d)
+{
+	void **shadow_leak;
+

samples/livepatch/livepatch-shadow-fix1.c line 100

Quoted 10 lines
samples/livepatch/livepatch-shadow-fix1.c new file +10 -0
+	/*
+	 * Patch: fetch the saved SV_LEAK shadow variable, detach and
+	 * free it.  Note: handle cases where this shadow variable does
+	 * not exist (ie, dummy structures allocated before this livepatch
+	 * was loaded.)
+	 */
+	shadow_leak = klp_shadow_get(d, SV_LEAK);
+	if (shadow_leak) {
+		klp_shadow_detach(d, SV_LEAK);
+		kfree(*shadow_leak);

This should get removed. The buffer used for the shadow variable is freed by kfree_rcu() called from klp_shadow_detach().

Same problem is also in the other livepatch.

samples/livepatch/livepatch-shadow-fix1.c

Quoted 2 lines
samples/livepatch/livepatch-shadow-fix1.c new file +2 -0
+		pr_info("%s: dummy @ %p, prevented leak @ %p\n",
+			 __func__, d, *shadow_leak);

This might access shadow_leak after it was (double) freed.

samples/livepatch/livepatch-shadow-fix1.c line 108

Quoted 6 lines
samples/livepatch/livepatch-shadow-fix1.c new file +6 -0
+	} else {
+		pr_info("%s: dummy @ %p leaked!\n", __func__, d);
+	}
+
+	kfree(d);
+}

I am sorry for the late review. I had vacation.

I know that this patch already got some acks. Most of my comments are about code clean up and tiny bugs that might be fixed later.

But I would still suggests to re-evaluate the usefulness and logic of klp_shadow_update_or_attach(). I think that it was the primary reason for the many cut&pasted code. The locking logic is weird there. It does too many things at once because it also manipulates the existing data. All other functions just get pointer to the data and eventually initialize them when they did not exist before.

Best Regards,
Petr

author maintainer
#7 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

Quoted 38 lines · Petr Mladek
Quoted 37 lines · Joe Lawrence

Add exported API for livepatch modules:

klp_shadow_get()
klp_shadow_attach()
klp_shadow_get_or_attach()
klp_shadow_update_or_attach()
klp_shadow_detach()
klp_shadow_detach_all()

that implement "shadow" variables, which allow callers to associate new shadow fields to existing data structures. This is intended to be used by livepatch modules seeking to emulate additions to data structure definitions.

See Documentation/livepatch/shadow-vars.txt for a summary of the new shadow variable API, including a few common use cases.

See samples/livepatch/livepatch-shadow-* for example modules that demonstrate shadow variables.

kernel/livepatch/shadow.c new file +12 -0
new file mode 100644
index 000000000000..0ebd4b635e4f
+/**
+ * klp_shadow_match() - verify a shadow variable matches given <obj, id>
+ * @shadow:	shadow variable to match
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ *
+ * Return: true if the shadow variable matches.
+ *
+ * Callers should hold the klp_shadow_lock.
+ */
+static inline bool klp_shadow_match(struct klp_shadow *shadow, void *obj,
+				unsigned long id)
Quoted 8 lines

kernel/livepatch/shadow.c line 83

Quoted 3 lines
kernel/livepatch/shadow.c new file +3 -0
+{
+	return shadow->obj == obj && shadow->id == id;
+}

Do we really need this function? It is called only in situations where shadow->obj == obj is always true. Especially the use in klp_shadow_detach_all() is funny because we pass shadow->obj as the shadow parameter.

Personal preference. Abstracting out all of the routines that operated on the shadow variables (setting up, comparison) did save some code lines and centralized these common bits.

Quoted 43 lines
Quoted 43 lines
kernel/livepatch/shadow.c new file +43 -0
+
+/**
+ * klp_shadow_get() - retrieve a shadow variable data pointer
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ *
+ * Return: the shadow variable data element, NULL on failure.
+ */
+void *klp_shadow_get(void *obj, unsigned long id)
+{
+	struct klp_shadow *shadow;
+
+	rcu_read_lock();
+
+	hash_for_each_possible_rcu(klp_shadow_hash, shadow, node,
+				   (unsigned long)obj) {
+
+		if (klp_shadow_match(shadow, obj, id)) {
+			rcu_read_unlock();
+			return shadow->data;
+		}
+	}
+
+	rcu_read_unlock();
+
+	return NULL;
+}
+EXPORT_SYMBOL_GPL(klp_shadow_get);
+
+/*
+ * klp_shadow_set() - initialize a shadow variable
+ * @shadow:	shadow variable to initialize
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ * @data:	pointer to data to attach to parent
+ * @size:	size of attached data
+ *
+ * Callers should hold the klp_shadow_lock.
+ */
+static inline void klp_shadow_set(struct klp_shadow *shadow, void *obj,
+				  unsigned long id, void *data, size_t size)
+{
+	shadow->obj = obj;
Quoted 8 lines

kernel/livepatch/shadow.c line 131

Quoted 5 lines
kernel/livepatch/shadow.c new file +5 -0
+	shadow->id = id;
+
+	if (data)
+		memcpy(shadow->data, data, size);
+}

The function name suggests that it is a counterpart of klp_shadow_get() but it is not. Which is a bit confusing.

I should have called it "setup" or "init", but perhaps that's moot ...

Quoted 5 lines

Hmm, the purpose of this function is to reduce the size of cut&pasted code between all that klp_shadow_*attach() variants. But there is still too much cut&pasted code. In fact, the base logic of all variants is basically the same. The only small difference should be how they handle the situation when the variable is already there.

... this is true. An earlier draft revision that I had discarded attempted combining all cases. I had used two extra function arguments, "update" and "duplicates", to key off for each behavior... it turned into a complicated, full-screen page of conditional logic, so I threw it out.

However, I like the way you pulled it off using a jump-to-switch statement at the bottom of the function...

Quoted 103 lines

OK, there is a locking difference in the update variant but it is questionable, see below.

I would suggest to do something like this:

static enum klp_shadow_attach_existing_handling {
KLP_SHADOW_EXISTING_RETURN,
KLP_SHADOW_EXISTING_WARN,
KLP_SHADOW_EXISING_UPDATE,
};

void *__klp_shadow_get_or_attach(void *obj, unsigned long id, void *data,
size_t size, gfp_t gfp_flags,
enum klp_shadow_attach_existing_handling existing_handling)

{
	struct klp_shadow *new_shadow;
	void *shadow_data;
	unsigned long flags;

	/* Check if the shadow variable if <obj, id> already exists */
	shadow_data = klp_shadow_get(obj, id);
	if (shadow_data)
		goto exists;

	/* Allocate a new shadow variable for use inside the lock below */
	new_shadow = kzalloc(size + sizeof(*new_shadow), gfp_flags);
	if (!new_shadow) {
		pr_error("failed to allocate shadow variable <0x%p, %ul>\n",
				 obj, id);
		return NULL;
	}

	new_shadow->obj = obj;
	new_shadow->id = id;

	/* initialize the shadow variable if if data provided */
	if (data)
		memcpy(new_shadow->data, data, size);

	/* Look for <obj, id> again under the lock */
	spin_lock_irqsave(&klp_shadow_lock, flags);
	shadow_data = klp_shadow_get(obj, id);
	if (unlikely(shadow_data)) {
		/*
		 * Shadow variable was found, throw away speculative
		 * allocation and update/return the existing one.
		 */
		spin_unlock_irqrestore(&klp_shadow_lock, flags);
		kfree(new_shadow);
		goto exists;
	}

	/* No <obj, id> found, so attach the newly allocated one */
	hash_add_rcu(klp_shadow_hash, &new_shadow->node,
		     (unsigned long)new_shadow->obj);
	spin_unlock_irqrestore(&klp_shadow_lock, flags);

	return new_shadow->data;

exists:

	switch(existing_handling) {
	case KLP_SHADOW_EXISTING_RETURN:
		break;

	case KLP_SHADOW_EXISTING_WARN:
		WARN(1, "Duplicate shadow variable <%p, %lx>\n", obj, id);
		shadow_data = NULL;
		break;

	case KLP_SHADOW_EXISING_UPDATE:
		if (data)
			memcpy(shadow_data, data, size);
		break;
	}
	return shadow_data;
}

void *klp_shadow_attach(void *obj, unsigned long id, void *data,
size_t size, gfp_t gfp_flags)

{
	return __klp_shadow_get_or_attach(obj, id, data, size,
			gfp_flags, KLP_SHADOW_EXISTING_RETURN);
}

void *klp_shadow_get_or_attach(void *obj, unsigned long id, void *data,
size_t size, gfp_t gfp_flags)

{
	return __klp_shadow_get_or_attach(obj, id, data, size,
			gfp_flags, KLP_SHADOW_EXISTING_WARN);
}

void *klp_shadow_update_or_attach(void *obj, unsigned long id, void *data,
size_t size, gfp_t gfp_flags)

{
	return __klp_shadow_get_or_attach(obj, id, data, size,
			gfp_flags, KLP_SHADOW_EXISTING_UPDATE);
}

Note that the above code is not even compile tested.

It removes a lot of cut&pasted code and the difference is more clear.

Quoted 6 lines

It updates the data outside klp_shadow_lock. But it should be fine. The lock is there to keep the hast table consistent (avoid duplicates).

Users are responsible to synchronize the data
stored in the variables their own way.

^^^ this is probably the best argument to ditch
klp_shadow_update_or_attach().

Quoted 9 lines

Hmm, the more I think about it the more I would suggest to remove klp_shadow_update_or_attach() variant. It has very weird logic. IMHO, it is not obvious that it must be called under the locks that synchronize the shadow data. IMHO, the other two variants are much more clear and enough. Or do you have a good real life example for it?

From the API caller's point of view, the intent was: "I want a shadow

variable and it needs to have this current value."

klp_shadow_get_or_attach() doesn't pass back information about the underlying shadow variable, ie, was an existing one found, or did it allocate a new one. In the former case, the data will be stale.

I don't have a real-world example for such use-case, so I'm willing to drop the routine if it simplifies the code. I'd be curious to see how you might solve this situation using klp_shadow_get() and/or klp_shadow_get_or_attach().

Quoted 23 lines
Quoted 23 lines
kernel/livepatch/shadow.c new file +23 -0
+/**
+ * klp_shadow_add() - add a shadow variable to the hashtable
+ * @shadow:	shadow variable to add
+ *
+ * Callers should hold the klp_shadow_lock.
+ */
+static inline void klp_shadow_add(struct klp_shadow *shadow)
+{
+	hash_add_rcu(klp_shadow_hash, &shadow->node,
+		     (unsigned long)shadow->obj);
+}
+
+/**
+ * klp_shadow_attach() - allocate and add a new shadow variable
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ * @data:	pointer to data to attach to parent
+ * @size:	size of attached data
+ * @gfp_flags:	GFP mask for allocation
+ *
+ * If an existing <obj, id> shadow variable can be found, this routine
+ * will issue a WARN, exit early and return NULL.
+ *
Quoted 8 lines
Quoted 5 lines

+ * Allocates @size bytes for new shadow variable data using @gfp_flags
+ * and copies @size bytes from @data into the new shadow variable's own
+ * data space. If @data is NULL, @size bytes are still allocated, but
+ * no copy is performed. The new shadow variable is then added to the
+ * global hashtable.

I would swap the two paragraphs. We should describe the main function first and corner cases later.

Okay, that makes sense.

Quoted 12 lines
Quoted 12 lines

+ * Return: the shadow variable data element, NULL on duplicate or
+ * failure.
+ */

kernel/livepatch/shadow.c new file +9 -0
+void *klp_shadow_attach(void *obj, unsigned long id, void *data,
+			size_t size, gfp_t gfp_flags)
+{
+	struct klp_shadow *new_shadow;
+	void *shadow_data;
+	unsigned long flags;
+
+	/* Take error exit path if <obj, id> already exists */
+	if (unlikely(klp_shadow_get(obj, id)))
Quoted 8 lines

kernel/livepatch/shadow.c line 177

Quoted 4 lines
kernel/livepatch/shadow.c new file +4 -0
+		goto err_exists;
+
+	/* Allocate a new shadow variable for use inside the lock below */
+	new_shadow = kzalloc(size + sizeof(*new_shadow), gfp_flags);

We should print an error message when the memory cannot be allocated. Otherwise we will return NULL without explanation. It will be especially helpful when a caller forgets to check for NULL.

That's a good idea. Silent failure could be confusing.

Quoted 40 lines
Quoted 40 lines
kernel/livepatch/shadow.c new file +40 -0
+	if (!new_shadow)
+		goto err;
+	klp_shadow_set(new_shadow, obj, id, data, size);
+
+	/* Look for <obj, id> again under the lock */
+	spin_lock_irqsave(&klp_shadow_lock, flags);
+	shadow_data = klp_shadow_get(obj, id);
+	if (unlikely(shadow_data)) {
+		/*
+		 * Shadow variable was found, throw away speculative
+		 * allocation and update/return the existing one.
+		 */
+		spin_unlock_irqrestore(&klp_shadow_lock, flags);
+		kfree(new_shadow);
+		goto err_exists;
+	}
+
+	/* No <obj, id> found, add the newly allocated one */
+	klp_shadow_add(new_shadow);
+	spin_unlock_irqrestore(&klp_shadow_lock, flags);
+
+	return new_shadow->data;
+
+err_exists:
+	WARN(1, "Duplicate shadow variable <%p, %lx>\n", obj, id);
+err:
+	return NULL;
+}
+EXPORT_SYMBOL_GPL(klp_shadow_attach);
+
+/**
+ * klp_shadow_get_or_attach() - get existing or attach a new shadow variable
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ * @data:	pointer to data to attach to parent
+ * @size:	size of attached data
+ * @gfp_flags:	GFP mask for allocation
+ *
+ * If an existing <obj, id> shadow variable can be found, it will be
+ * used (but *not* updated) in the return value of this function.
Quoted 8 lines
Quoted 6 lines

+ *
+ * Allocates @size bytes for new shadow variable data using @gfp_flags
+ * and copies @size bytes from @data into the new shadow variable's own
+ * data space. If @data is NULL, @size bytes are still allocated, but
+ * no copy is performed. The new shadow variable is then added to the
+ * global hashtable.

There is a lot of duplicated text here.

Copy/pasting -- it was a lot easier to keep the comments in sync with the code as it was evolving through the revisions, especially with three variants of the nearly same routine :)

Quoted 6 lines

Also you need to read the first
paragraph very carefully. Otherwise, you miss that the 2nd paragraph is true only in special situation.

I would make it more clear, something like:

Quoted 8 lines

It returns pointer to the shadow data when they already exist. Otherwise, it attaches and new shadow variable like klp_shadow_attach().

It guarantees that only one shadow variable will exists with the given @id for the given @obj. Also it guarantees that the variable will be initialized by the given @data only when it did not exist before.

Good feedback, I'll incorporate something like this for the next version.

Quoted 30 lines
Quoted 9 lines
samples/livepatch/livepatch-shadow-fix1.c new file +4 -0
new file mode 100644
index 000000000000..5acc838463d1
+void livepatch_fix1_dummy_free(struct dummy *d)
+{
+	void **shadow_leak;
+

samples/livepatch/livepatch-shadow-fix1.c line 100

Quoted 10 lines
samples/livepatch/livepatch-shadow-fix1.c new file +10 -0
+	/*
+	 * Patch: fetch the saved SV_LEAK shadow variable, detach and
+	 * free it.  Note: handle cases where this shadow variable does
+	 * not exist (ie, dummy structures allocated before this livepatch
+	 * was loaded.)
+	 */
+	shadow_leak = klp_shadow_get(d, SV_LEAK);
+	if (shadow_leak) {
+		klp_shadow_detach(d, SV_LEAK);
+		kfree(*shadow_leak);

This should get removed. The buffer used for the shadow variable is freed by kfree_rcu() called from klp_shadow_detach().

Same problem is also in the other livepatch.

samples/livepatch/livepatch-shadow-fix1.c

Quoted 2 lines
samples/livepatch/livepatch-shadow-fix1.c new file +2 -0
+		pr_info("%s: dummy @ %p, prevented leak @ %p\n",
+			 __func__, d, *shadow_leak);

This might access shadow_leak after it was (double) freed.

Quoted 6 lines

samples/livepatch/livepatch-shadow-fix1.c line 108

Quoted 6 lines
samples/livepatch/livepatch-shadow-fix1.c new file +6 -0
+	} else {
+		pr_info("%s: dummy @ %p leaked!\n", __func__, d);
+	}
+
+	kfree(d);
+}

Let me double check these double frees (though I have been running the tests w/slub_debug poisoning turned on). At first glance, they look like another holdover from the shadow-data-is-just-a pointer versions.

Quoted 2 lines

I am sorry for the late review. I had vacation.

No worries, this is a good review!

Quoted 10 lines

I know that this patch already got some acks. Most of my comments are about code clean up and tiny bugs that might be fixed later.

But I would still suggests to re-evaluate the usefulness and logic of klp_shadow_update_or_attach(). I think that it was the primary reason for the many cut&pasted code. The locking logic is weird there. It does too many things at once because it also manipulates the existing data. All other functions just get pointer to the data and eventually initialize them when they did not exist before.

Without a good real-world example, you've convinced me that klp_shadow_update_or_attach() could be dropped. I think this will also simplify the requirements of a shared __klp_shadow_get_or_attach() like you sketched out earlier.

If Josh and Miroslav don't mind, I'd like to continue churning this patch with the suggestions that Petr has made.

-- Joe

#8 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

Quoted 7 lines · Joe Lawrence

Without a good real-world example, you've convinced me that klp_shadow_update_or_attach() could be dropped. I think this will also simplify the requirements of a shared __klp_shadow_get_or_attach() like you sketched out earlier.

If Josh and Miroslav don't mind, I'd like to continue churning this patch with the suggestions that Petr has made.

By all means, go ahead. I rescind my Ack ;-)

Signature · 1 line
Josh
maintainer
#9 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

In reply to Joe Lawrence
Quoted 27 lines · Joe Lawrence
Quoted 17 lines · Petr Mladek
Quoted 17 lines
kernel/livepatch/shadow.c new file +12 -0
new file mode 100644
index 000000000000..0ebd4b635e4f
+/**
+ * klp_shadow_match() - verify a shadow variable matches given <obj, id>
+ * @shadow:	shadow variable to match
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ *
+ * Return: true if the shadow variable matches.
+ *
+ * Callers should hold the klp_shadow_lock.
+ */
+static inline bool klp_shadow_match(struct klp_shadow *shadow, void *obj,
+				unsigned long id)
Quoted 8 lines

kernel/livepatch/shadow.c line 83

Quoted 3 lines
kernel/livepatch/shadow.c new file +3 -0
+{
+	return shadow->obj == obj && shadow->id == id;
+}

Do we really need this function? It is called only in situations where shadow->obj == obj is always true. Especially the use in klp_shadow_detach_all() is funny because we pass shadow->obj as the shadow parameter.

Quoted 3 lines

Personal preference. Abstracting out all of the routines that operated on the shadow variables (setting up, comparison) did save some code lines and centralized these common bits.

I take this back. We actually need to check obj because different objects might have the same hash.

I think that I did the same mistake also the last time. I hope that I will be able to fix this in my mind faster than "never" vs. "newer" typo that I do for years.

Also I forgot to say that you did great work. Each version of the patch is much better than the previous one.

Best Regards,
Petr

#10 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

Quoted 32 lines · Petr Mladek
Quoted 27 lines · Joe Lawrence
Quoted 17 lines · Petr Mladek
Quoted 17 lines
kernel/livepatch/shadow.c new file +12 -0
new file mode 100644
index 000000000000..0ebd4b635e4f
+/**
+ * klp_shadow_match() - verify a shadow variable matches given <obj, id>
+ * @shadow:	shadow variable to match
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ *
+ * Return: true if the shadow variable matches.
+ *
+ * Callers should hold the klp_shadow_lock.
+ */
+static inline bool klp_shadow_match(struct klp_shadow *shadow, void *obj,
+				unsigned long id)
Quoted 8 lines

kernel/livepatch/shadow.c line 83

Quoted 3 lines
kernel/livepatch/shadow.c new file +3 -0
+{
+	return shadow->obj == obj && shadow->id == id;
+}

Do we really need this function? It is called only in situations where shadow->obj == obj is always true. Especially the use in klp_shadow_detach_all() is funny because we pass shadow->obj as the shadow parameter.

Quoted 3 lines

Personal preference. Abstracting out all of the routines that operated on the shadow variables (setting up, comparison) did save some code lines and centralized these common bits.

Quoted 6 lines

I take this back. We actually need to check obj because different objects might have the same hash.

I think that I did the same mistake also the last time. I hope that I will be able to fix this in my mind faster than "never" vs. "newer" typo that I do for years.

It's an easy mistake to make. hash_for_each_possible() is not intuitive, IMO. Maybe some brave soul should fix it.

Signature · 1 line
Josh
author maintainer
#11 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

In reply to Petr Mladek
Quoted 32 lines · Petr Mladek
Quoted 10 lines · Joe Lawrence

[ ... snip ... ]

samples/livepatch/livepatch-shadow-fix1.c new file +4 -0
new file mode 100644
index 000000000000..5acc838463d1
+void livepatch_fix1_dummy_free(struct dummy *d)
+{
+	void **shadow_leak;
+

samples/livepatch/livepatch-shadow-fix1.c line 100

Quoted 10 lines
samples/livepatch/livepatch-shadow-fix1.c new file +10 -0
+	/*
+	 * Patch: fetch the saved SV_LEAK shadow variable, detach and
+	 * free it.  Note: handle cases where this shadow variable does
+	 * not exist (ie, dummy structures allocated before this livepatch
+	 * was loaded.)
+	 */
+	shadow_leak = klp_shadow_get(d, SV_LEAK);
+	if (shadow_leak) {
+		klp_shadow_detach(d, SV_LEAK);
+		kfree(*shadow_leak);

This should get removed. The buffer used for the shadow variable is freed by kfree_rcu() called from klp_shadow_detach().

Same problem is also in the other livepatch.

samples/livepatch/livepatch-shadow-fix1.c

Quoted 2 lines
samples/livepatch/livepatch-shadow-fix1.c new file +2 -0
+		pr_info("%s: dummy @ %p, prevented leak @ %p\n",
+			 __func__, d, *shadow_leak);

This might access shadow_leak after it was (double) freed.

Quoted 6 lines

samples/livepatch/livepatch-shadow-fix1.c line 108

Quoted 6 lines
samples/livepatch/livepatch-shadow-fix1.c new file +6 -0
+	} else {
+		pr_info("%s: dummy @ %p leaked!\n", __func__, d);
+	}
+
+	kfree(d);
+}

Hi Petr,

I think you're half correct.

The kfree is the crux of the memory leak patch, so it needs to stay. However, the shadow variable is holding a copy of the pointer to the memory leak area, so you're right that it can't be safely dereferenced after the shadow variable is detached*.

The code should to be rearranged like:

void livepatch_fix1_dummy_free(struct dummy *d)

{
        void **p_shadow_leak, *shadow_leak;

        p_shadow_leak = klp_shadow_get(d, SV_LEAK);
        if (p_shadow_leak) {
                shadow_leak = *p_shadow_leak;   << deref before detach
                klp_shadow_detach(d, SV_LEAK);
                kfree(shadow_leak);
        ...

* Aside: I usually develop with slub_debug=FZPU set to catch silly use-after-frees like this. However, since the shadow variable is released via kfree_rcu(), I think there was a window before the grace period where this one worked out okay... once I added a synchronize_rcu() call in between the klp_shadow_detch() and kfree() calls, I did see the poison pattern. This is my first time using kfree_rcu(), so it was interesting to dig into.

Thanks,

-- Joe

maintainer
#12 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

Quoted 42 lines · Joe Lawrence
Quoted 32 lines · Petr Mladek
Quoted 10 lines · Joe Lawrence

[ ... snip ... ]

samples/livepatch/livepatch-shadow-fix1.c new file +4 -0
new file mode 100644
index 000000000000..5acc838463d1
+void livepatch_fix1_dummy_free(struct dummy *d)
+{
+	void **shadow_leak;
+

samples/livepatch/livepatch-shadow-fix1.c line 100

Quoted 10 lines
samples/livepatch/livepatch-shadow-fix1.c new file +10 -0
+	/*
+	 * Patch: fetch the saved SV_LEAK shadow variable, detach and
+	 * free it.  Note: handle cases where this shadow variable does
+	 * not exist (ie, dummy structures allocated before this livepatch
+	 * was loaded.)
+	 */
+	shadow_leak = klp_shadow_get(d, SV_LEAK);
+	if (shadow_leak) {
+		klp_shadow_detach(d, SV_LEAK);
+		kfree(*shadow_leak);

This should get removed. The buffer used for the shadow variable is freed by kfree_rcu() called from klp_shadow_detach().

Same problem is also in the other livepatch.

samples/livepatch/livepatch-shadow-fix1.c

Quoted 2 lines
samples/livepatch/livepatch-shadow-fix1.c new file +2 -0
+		pr_info("%s: dummy @ %p, prevented leak @ %p\n",
+			 __func__, d, *shadow_leak);

This might access shadow_leak after it was (double) freed.

Quoted 6 lines

samples/livepatch/livepatch-shadow-fix1.c line 108

Quoted 6 lines
samples/livepatch/livepatch-shadow-fix1.c new file +6 -0
+	} else {
+		pr_info("%s: dummy @ %p leaked!\n", __func__, d);
+	}
+
+	kfree(d);
+}

Hi Petr,

Quoted 6 lines

I think you're half correct.

The kfree is the crux of the memory leak patch, so it needs to stay. However, the shadow variable is holding a copy of the pointer to the memory leak area, so you're right that it can't be safely dereferenced after the shadow variable is detached*.

Ah, I see. The extra kftree does not free the shadow->data but it frees the data that the shadow variable points to.

Quoted 9 lines

The code should to be rearranged like:

void livepatch_fix1_dummy_free(struct dummy *d)

{
        void **p_shadow_leak, *shadow_leak;

        p_shadow_leak = klp_shadow_get(d, SV_LEAK);
        if (p_shadow_leak) {
                shadow_leak = *p_shadow_leak;   << deref before detach

I would rename shadow_leak -> leak. It will make it more clear that it is the original leak pointer.

Well, we could actually free the data before we detach/destroy the shadow variable. But then it might deserve a comment to avoid confusion that I had. I mean:

	shadow_leak = klp_shadow_get(d, SV_LEAK);
	if (shadow_leak) {
		pr_info("%s: dummy @ %p, prevented leak @ %p\n",
			 __func__, d, *shadow_leak);
		/* Free the previously leaked data */
		kfree(*shadow_leak);
		/* Free the shadow variable */
		klp_shadow_detach(d, SV_LEAK);
Quoted 6 lines
                klp_shadow_detach(d, SV_LEAK);
                kfree(shadow_leak);
        ...

* Aside: I usually develop with slub_debug=FZPU set to catch silly use-after-frees like this.

Sounds like a good practice.

Quoted 5 lines

released via kfree_rcu(), I think there was a window before the grace period where this one worked out okay... once I added a synchronize_rcu() call in between the klp_shadow_detch() and kfree() calls, I did see the poison pattern. This is my first time using kfree_rcu(), so it was interesting to dig into.

Yup.

Best Regards,
Petr

author maintainer
#13 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

In reply to Petr Mladek
Quoted 8 lines · Petr Mladek

Review

Quoted 3 lines · Joe Lawrence

[ ... snip ... ]

(quoted diff) +2 -0
+	/* Allocate a new shadow variable for use inside the lock below */
+	new_shadow = kzalloc(size + sizeof(*new_shadow), gfp_flags);

We should print an error message when the memory cannot be allocated. Otherwise we will return NULL without explanation. It will be especially helpful when a caller forgets to check for NULL.

Interesting, I hadn't seen this checkpatch complaint before:

WARNING: Possible unnecessary 'out of memory' message #416: FILE: kernel/livepatch/shadow.c:143:
+ if (!new_shadow) {
+ pr_err("failed to allocate shadow variable <0x%p, %lu>\n",

Discussion thread:
https://lkml.org/lkml/2014/6/10/382

Think the stack trace that the memory subsystem would emit is good enough, or would you like to see <obj, id> for debugging purposes?

-- Joe

maintainer
#14 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

Quoted 17 lines · Joe Lawrence
Quoted 8 lines · Petr Mladek

Review

Quoted 3 lines · Joe Lawrence

[ ... snip ... ]

(quoted diff) +2 -0
+	/* Allocate a new shadow variable for use inside the lock below */
+	new_shadow = kzalloc(size + sizeof(*new_shadow), gfp_flags);

We should print an error message when the memory cannot be allocated. Otherwise we will return NULL without explanation. It will be especially helpful when a caller forgets to check for NULL.

Interesting, I hadn't seen this checkpatch complaint before:

WARNING: Possible unnecessary 'out of memory' message #416: FILE: kernel/livepatch/shadow.c:143:

(quoted diff) +2 -0
+       if (!new_shadow) {
+               pr_err("failed to allocate shadow variable <0x%p, %lu>\n",
Quoted 2 lines

Discussion thread:
https://lkml.org/lkml/2014/6/10/382

Interesting, I was not aware of this.

Quoted 2 lines

Think the stack trace that the memory subsystem would emit is good enough, or would you like to see <obj, id> for debugging purposes?

I agree that the backtrace should be enough to locate the problematic call quickly. Feel free to omit it.

Now, I just need to update my patterns when looking for problematic code.

Best Regards,
Petr

#15 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

In reply to Joe Lawrence

Joe Lawrence <[email protected]> writes:

<snip>

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+
+/**
+ * klp_shadow_get() - retrieve a shadow variable data pointer
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ *
+ * Return: the shadow variable data element, NULL on failure.
+ */
+void *klp_shadow_get(void *obj, unsigned long id)
+{

kernel/livepatch/shadow.c line 103

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+	struct klp_shadow *shadow;
+
+	rcu_read_lock();
+
+	hash_for_each_possible_rcu(klp_shadow_hash, shadow, node,
+				   (unsigned long)obj) {
+
+		if (klp_shadow_match(shadow, obj, id)) {
+			rcu_read_unlock();
+			return shadow->data;

I had to think a moment about what protects shadow from getting freed by a concurrent detach after that rcu_read_unlock(). Then I noticed that if obj and the livepatch are alive, then so is shadow, because there obviously hasn't been any reason to detach it.

So maybe it would be nice to have an additional comment at klp_shadow_detach() that it's the API user's responsibility not to use a shadow instance after detaching it...

Thanks,

Nicolai

kernel/livepatch/shadow.c line 111

Quoted 8 lines
kernel/livepatch/shadow.c new file +8 -0
+		}
+	}
+
+	rcu_read_unlock();
+
+	return NULL;
+}
+EXPORT_SYMBOL_GPL(klp_shadow_get);

<snap>

Signature · 1 line
SUSE Linux GmbH, GF: Felix Imendörffer, Jane Smithard, Graham Norton, HRB 21284 (AG Nürnberg)
maintainer
#16 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

Quoted 29 lines · Nicolai Stange

Joe Lawrence <[email protected]> writes:

<snip>

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+
+/**
+ * klp_shadow_get() - retrieve a shadow variable data pointer
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ *
+ * Return: the shadow variable data element, NULL on failure.
+ */
+void *klp_shadow_get(void *obj, unsigned long id)
+{

kernel/livepatch/shadow.c line 103

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+	struct klp_shadow *shadow;
+
+	rcu_read_lock();
+
+	hash_for_each_possible_rcu(klp_shadow_hash, shadow, node,
+				   (unsigned long)obj) {
+
+		if (klp_shadow_match(shadow, obj, id)) {
+			rcu_read_unlock();
+			return shadow->data;

I had to think a moment about what protects shadow from getting freed by a concurrent detach after that rcu_read_unlock(). Then I noticed that if obj and the livepatch are alive, then so is shadow, because there obviously hasn't been any reason to detach it.

Quoted 3 lines

So maybe it would be nice to have an additional comment at klp_shadow_detach() that it's the API user's responsibility not to use a shadow instance after detaching it...

Good point. In fact, it might make sense to rename the functions:

     attach -> create
     detach -> destroy

The name detach suggests that the variable is just not connected to the parent object but that it is still accessible/usable.

Best Regards,
Petr

author maintainer
#17 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

Quoted 30 lines · Petr Mladek
Quoted 29 lines · Nicolai Stange

Joe Lawrence <[email protected]> writes:

<snip>

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+
+/**
+ * klp_shadow_get() - retrieve a shadow variable data pointer
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ *
+ * Return: the shadow variable data element, NULL on failure.
+ */
+void *klp_shadow_get(void *obj, unsigned long id)
+{

kernel/livepatch/shadow.c line 103

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+	struct klp_shadow *shadow;
+
+	rcu_read_lock();
+
+	hash_for_each_possible_rcu(klp_shadow_hash, shadow, node,
+				   (unsigned long)obj) {
+
+		if (klp_shadow_match(shadow, obj, id)) {
+			rcu_read_unlock();
+			return shadow->data;

I had to think a moment about what protects shadow from getting freed by a concurrent detach after that rcu_read_unlock(). Then I noticed that if obj and the livepatch are alive, then so is shadow, because there obviously hasn't been any reason to detach it.

Quoted 3 lines
Quoted 3 lines

So maybe it would be nice to have an additional comment at klp_shadow_detach() that it's the API user's responsibility not to use a shadow instance after detaching it...

Nicolai, I can add something like "This function releases the memory for this shadow variable instance, callers should stop referencing it accordingly." Similar text for klp_shadow_detach_all().

Quoted 7 lines

Good point. In fact, it might make sense to rename the functions:

     attach -> create
     detach -> destroy

The name detach suggests that the variable is just not connected to the parent object but that it is still accessible/usable.

FWIW, kpatch calls them "kpatch_shadow_alloc" and "kpatch_shadow_free". Now that it's clear that we're not going separate shadow variable allocation from hash table insertion, going back to alloc/create and destroy/free is fine w/me.

-- Joe

#18 lore raw

Re: [PATCH v4] livepatch: introduce shadow variable API

Quoted 31 lines · Joe Lawrence
Quoted 30 lines · Petr Mladek
Quoted 29 lines · Nicolai Stange

Joe Lawrence <[email protected]> writes:

<snip>

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+
+/**
+ * klp_shadow_get() - retrieve a shadow variable data pointer
+ * @obj:	pointer to parent object
+ * @id:		data identifier
+ *
+ * Return: the shadow variable data element, NULL on failure.
+ */
+void *klp_shadow_get(void *obj, unsigned long id)
+{

kernel/livepatch/shadow.c line 103

Quoted 10 lines
kernel/livepatch/shadow.c new file +10 -0
+	struct klp_shadow *shadow;
+
+	rcu_read_lock();
+
+	hash_for_each_possible_rcu(klp_shadow_hash, shadow, node,
+				   (unsigned long)obj) {
+
+		if (klp_shadow_match(shadow, obj, id)) {
+			rcu_read_unlock();
+			return shadow->data;

I had to think a moment about what protects shadow from getting freed by a concurrent detach after that rcu_read_unlock(). Then I noticed that if obj and the livepatch are alive, then so is shadow, because there obviously hasn't been any reason to detach it.

Quoted 7 lines
Quoted 3 lines
Quoted 3 lines

So maybe it would be nice to have an additional comment at klp_shadow_detach() that it's the API user's responsibility not to use a shadow instance after detaching it...

Nicolai, I can add something like "This function releases the memory for this shadow variable instance, callers should stop referencing it accordingly." Similar text for klp_shadow_detach_all().

Perfect, thanks!

Quoted 12 lines
Quoted 7 lines

Good point. In fact, it might make sense to rename the functions:

     attach -> create
     detach -> destroy

The name detach suggests that the variable is just not connected to the parent object but that it is still accessible/usable.

FWIW, kpatch calls them "kpatch_shadow_alloc" and "kpatch_shadow_free". Now that it's clear that we're not going separate shadow variable allocation from hash table insertion, going back to alloc/create and destroy/free is fine w/me.

Signature · 1 line
SUSE Linux GmbH, GF: Felix Imendörffer, Jane Smithard, Graham Norton, HRB 21284 (AG Nürnberg)