Skip to contentSkip to conversation

dm-bufio per-client retain and dm-verity cache control

PATCH New Yongpeng Yang 1 participant 6 messages Nov 21

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

v5 cover dm-bufio per-client retain and dm-verity cache control

From: Yongpeng Yang <[email protected]>

Device-mapper's verity targets read their hash trees, and FEC parity when FEC is enabled, through dm-bufio. dm-bufio has a single module-wide retain_bytes value shared by every client, no way to see or change one client's memory use, and no way to warm the cache ahead of the reads that need it.

That fits poorly systems with many verified devices of very different sizes, such as Android, which mounts a dozen verity partitions plus per-app verified images. The hash areas we see range from a few MB to tens of MB: with the 256 KiB default, a large partition's hash blocks are evicted under memory pressure and re-read later, while a uniform large value makes every cold, idle device hold memory it does not need -- and most verity devices are cold most of the time. What is wanted is a lifecycle: prefetch when the device is about to be used, drop when it goes cold again.

This series adds per-client granularity to dm-bufio and gives dm-verity message-based control over its caches:

1. Fix an asymmetry in dm core: __dm_destroy() runs ->postsuspend without waiting for in-flight target messages, unlike __dm_suspend() which drains them with a final synchronize_srcu(). A message that passed dm_suspended() could still race the target's reset while the device is being removed. Every target with messages currently masks this with a private lock (multipath's work_mutex); verity's new messages have none, which is why the drain is needed.

2. Move the retain target into struct dm_bufio_client, initialized from the module parameter at creation, and export set/get plus a cached-buffer count. The parameter keeps its meaning as the default for new clients.

3. dm-verity: size the hash client's retain target as hash_retain_percent (default 10) of the hash area, so a small device keeps little and a large one keeps enough.

4. dm-verity: add the retain_bytes message to report or set a client's retain target; the reply also reports current_bytes and buffers, so memory use can be watched through the message.

5. dm-verity: add prefetch_hash and drop_hash messages to warm the cache ahead of use and release it afterwards. Both are rejected with -EBUSY while the device is suspended.

Nothing changes for existing users: every client starts with the value the module parameter holds.

Changes since v4:
- New patch 1 fixes the dm core hole that the message check leans
on: __dm_destroy() ran ->postsuspend without draining in-flight target messages, so a message that had passed dm_suspended() could race the target's reset during device removal (sashiko). The destroy path now mirrors __dm_suspend()'s final synchronize_srcu(). Reproduced with a debug-delayed prefetch racing dmsetup remove (WARN_ON in warn_leak); clean with the fix.

Tested on a VM running v7.4-rc1: message write paths and the memory reporting in the reply, the shrinker retain floor under memory pressure, prefetch/drop lifecycles, suspend/resume cycles, a prefetch-vs-remove race with a widened window, and error-path injection. No kernel warnings.

[1] v1: https://lore.kernel.org/all/[email protected]/
[2] v2: https://lore.kernel.org/all/[email protected]/
[3] v3: https://lore.kernel.org/all/[email protected]/
[4] v4: https://lore.kernel.org/all/[email protected]/

Comments welcome.

Assisted-by LLM

Yongpeng Yang (5):
dm: wait for in-flight messages before postsuspend on destroy
dm-bufio: make the retain target per client
dm-verity: size the hash retain target from the hash area
dm-verity: add retain_bytes message to inspect and tune the cache
floor
dm-verity: add messages to prefetch and drop the hash cache

 .../admin-guide/device-mapper/verity.rst      |  40 ++++
 .../admin-guide/kernel-parameters.txt         |   6 +
 drivers/md/dm-bufio.c                         |  41 +++-
 drivers/md/dm-verity-target.c                 | 209 +++++++++++++++++-
 drivers/md/dm.c                               |  26 ++-
 include/linux/dm-bufio.h                      |   8 +
 6 files changed, 324 insertions(+), 6 deletions(-)
Signature · 1 line
2.43.0
#1 lore raw

PATCH v5 1/5 dm: wait for in-flight messages before postsuspend on destroy

From: Yongpeng Yang <[email protected]>

__dm_suspend() ends with set_bit(DMF_SUSPENDED) followed by synchronize_srcu() before its caller runs the ->postsuspend methods, so a target message that passed dm_suspended() has finished by then. __dm_destroy() lacks that final synchronize_srcu(): a target that implements ->message and relies on dm_suspended() for serialization has its handler race its own ->postsuspend when an active device is removed. With the verity messages added later in this series:

CPU0 CPU1
target_message() dev_remove()
dm_get_live_table() __dm_destroy()
verity_message() dm_table_presuspend_targets()

    dm_suspended() -> false                set_bit(DMF_SUSPENDED)
    dm_bufio_prefetch()                   dm_table_postsuspend_targets()
      __bufio_new()                         verity_postsuspend()
        /* b->hold_count == 1 */              dm_bufio_client_reset()
      dm_bufio_unlock(c)                       drop_buffers()
                                                 /* b is held: WARN_ON */
      submit_io(b, ...)
      dm_bufio_release(b)

No in-tree target is exposed today: every one with messages serializes them against its own ->postsuspend with a private lock (multipath's work_mutex). But the hole is in the core, and any new message-bearing target that trusts dm_suspended() falls into it.

Mirror the suspend path: set the flag, drop the SRCU read lock (the table stays pinned by md->map, which cannot change under the suspend lock on a device being destroyed), wait for the grace period, then run postsuspend.

Fixes 3f77316de0ec0 ("dm: separate device deletion from dm_put")
Assisted-by LLM
---
 drivers/md/dm.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
drivers/md/dm.c +10 -2
index 38eaae8ac9b4..921b8c85f10d 100644
@@ -2736,6 +2736,7 @@ static void __dm_destroy(struct mapped_device *md, bool wait)
 {
 	struct dm_table *map;
 	int srcu_idx;
+	bool suspend_targets;
 
 	might_sleep();
 
@@ -2752,14 +2753,21 @@ static void __dm_destroy(struct mapped_device *md, bool wait)
 	 */
 	mutex_lock(&md->suspend_lock);
 	map = dm_get_live_table(md, &srcu_idx);
-	if (!dm_suspended_md(md)) {
+	suspend_targets = !dm_suspended_md(md);
+	if (suspend_targets) {
 		dm_table_presuspend_targets(map);
 		set_bit(DMF_SUSPENDED, &md->flags);
 		set_bit(DMF_POST_SUSPENDING, &md->flags);
-		dm_table_postsuspend_targets(map);
 	}
 	/* dm_put_live_table must be before fsleep, otherwise deadlock is possible */
 	dm_put_live_table(md, srcu_idx);
+
+	/* Wait for in-flight target messages, like __dm_suspend() does. */
+	if (suspend_targets)
+		synchronize_srcu(&md->io_barrier);
+
+	if (suspend_targets)
+		dm_table_postsuspend_targets(map);
 	mutex_unlock(&md->suspend_lock);
 
 	/*
Signature · 1 line
2.43.0
#2 lore raw

PATCH v5 2/5 dm-bufio: make the retain target per client

In reply to Yongpeng Yang

From: Yongpeng Yang <[email protected]>

dm_bufio_retain_bytes is a module-wide value shared by every dm-bufio user, so raising it to keep one device's metadata cached also makes every small, idle device hold on to memory it does not need.

Give each client its own target, initialized from the module parameter at creation. The parameter keeps its meaning as the default for new clients; clients that already exist are not affected. Also export a way to query the retain target and the cached buffer count, so a target can report its memory use.

Assisted-by LLM

---
v3:
- Round a non-zero target up to a block boundary instead of down, so it keeps at least as many bytes as requested (Benjamin Marzinski).

---
 drivers/md/dm-bufio.c    | 41 +++++++++++++++++++++++++++++++++++++++-
 include/linux/dm-bufio.h |  8 ++++++++
 2 files changed, 48 insertions(+), 1 deletion(-)
drivers/md/dm-bufio.c +40 -1
index 3b66cf1cb931..f3abf90793c9 100644
@@ -994,6 +994,8 @@ struct dm_bufio_client {
 
 	unsigned int minimum_buffers;
 
+	unsigned long retain_bytes;	/* READ_ONCE/WRITE_ONCE, no lock needed */
+
 	sector_t start;
 
 	struct shrinker *shrinker;
@@ -2284,6 +2286,42 @@ void dm_bufio_set_minimum_buffers(struct dm_bufio_client *c, unsigned int n)
 }
 EXPORT_SYMBOL_GPL(dm_bufio_set_minimum_buffers);
 
+/*
+ * Set the number of bytes this client tries to keep cached; 0 resets it
+ * to the module default.  Non-zero values are rounded up to a block
+ * boundary, so the target keeps at least as many bytes as requested.
+ */
+void dm_bufio_set_retain_bytes(struct dm_bufio_client *c, unsigned long bytes)
+{
+	if (!bytes) {
+		WRITE_ONCE(c->retain_bytes, READ_ONCE(dm_bufio_retain_bytes));
+		return;
+	}
+
+	/* clamp so the round-up below cannot overflow */
+	if (bytes > ULONG_MAX - c->block_size + 1)
+		bytes = ULONG_MAX - c->block_size + 1;
+
+	WRITE_ONCE(c->retain_bytes,
+		   DIV_ROUND_UP(bytes, c->block_size) * c->block_size);
+}
+EXPORT_SYMBOL_GPL(dm_bufio_set_retain_bytes);
+
+unsigned long dm_bufio_get_retain_bytes(struct dm_bufio_client *c)
+{
+	return READ_ONCE(c->retain_bytes);
+}
+EXPORT_SYMBOL_GPL(dm_bufio_get_retain_bytes);
+
+/*
+ * The number of buffers currently cached by this client.
+ */
+unsigned long dm_bufio_get_cached_buffers(struct dm_bufio_client *c)
+{
+	return cache_total(&c->cache);
+}
+EXPORT_SYMBOL_GPL(dm_bufio_get_cached_buffers);
+
 unsigned int dm_bufio_get_block_size(struct dm_bufio_client *c)
 {
 	return c->block_size;
@@ -2389,7 +2427,7 @@ static void drop_buffers(struct dm_bufio_client *c)
 
 static unsigned long get_retain_buffers(struct dm_bufio_client *c)
 {
-	unsigned long retain_bytes = READ_ONCE(dm_bufio_retain_bytes);
+	unsigned long retain_bytes = READ_ONCE(c->retain_bytes);
 
 	if (likely(c->sectors_per_block_bits >= 0))
 		retain_bytes >>= c->sectors_per_block_bits + SECTOR_SHIFT;
@@ -2522,6 +2560,7 @@ struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsign
 
 	mutex_init(&c->lock);
 	spin_lock_init(&c->spinlock);
+	c->retain_bytes = READ_ONCE(dm_bufio_retain_bytes);
 	INIT_LIST_HEAD(&c->reserved_buffers);
 	c->need_reserved_buffers = reserved_buffers;
 
include/linux/dm-bufio.h +8 -0
index d1503b815a78..f4d86b4b7e0f 100644
@@ -158,6 +158,14 @@ void dm_bufio_forget_buffers(struct dm_bufio_client *c, sector_t block, sector_t
  */
 void dm_bufio_set_minimum_buffers(struct dm_bufio_client *c, unsigned int n);
 
+/*
+ * Configure and query the per-client retain target; 0 resets the
+ * module default.
+ */
+void dm_bufio_set_retain_bytes(struct dm_bufio_client *c, unsigned long bytes);
+unsigned long dm_bufio_get_retain_bytes(struct dm_bufio_client *c);
+unsigned long dm_bufio_get_cached_buffers(struct dm_bufio_client *c);
+
 unsigned int dm_bufio_get_block_size(struct dm_bufio_client *c);
 sector_t dm_bufio_get_device_size(struct dm_bufio_client *c);
 struct dm_io_client *dm_bufio_get_dm_io_client(struct dm_bufio_client *c);
Signature · 1 line
2.43.0
#3 lore raw

PATCH v5 3/5 dm-verity: size the hash retain target from the hash area

In reply to Yongpeng Yang

From: Yongpeng Yang <[email protected]>

With the dm-bufio default of 256 KiB a large device re-reads hash blocks evicted under memory pressure, while a small device holds far more than it needs.

Set the hash client's target to hash_retain_percent (default 10) of the hash area, computed with mul_u64_u32_div() and clamped at ULONG_MAX so a large area cannot truncate to near-zero on 32-bit. A percentage above 100 is ignored, leaving the dm-bufio default.

The parameter only affects devices created afterwards.

Assisted-by LLM

---
v3:
- Compute the percentage with mul_u64_u32_div() and clamp it at ULONG_MAX, so a large area cannot truncate to near-zero on 32-bit.
- The leftover sysfs-era bufio_kobj field is removed.

---
 .../admin-guide/device-mapper/verity.rst      | 15 +++++++++++
 .../admin-guide/kernel-parameters.txt         |  6 +++++
 drivers/md/dm-verity-target.c                 | 26 +++++++++++++++++--
 3 files changed, 45 insertions(+), 2 deletions(-)
Documentation/admin-guide/device-mapper/verity.rst +15 -0
index 9e9d4b8157c0..7d6e567cef33 100644
@@ -328,6 +328,21 @@ Status
 2. Number of corrected blocks by Forward Error Correction.
    '-' if Forward Error Correction is not enabled.
 
+Metadata caching
+================
+
+The hash blocks, and the FEC parity blocks when FEC is enabled, are cached in
+memory by dm-bufio.  How much of the hash tree is kept cached is controlled by
+the ``hash_retain_percent`` module parameter (default 10), settable at boot
+time with ``dm_verity.hash_retain_percent=<0-100>`` or at run time through
+``/sys/module/dm_verity/parameters/hash_retain_percent``.  A value of 0 or
+above 100 leaves the dm-bufio default (256 KiB), which is also what the FEC
+clients keep.  Only devices created afterwards are affected.
+
+The retain target is a floor applied by the memory shrinker, not a cap: when
+there is no memory pressure a fully warmed cache may grow past it, and when
+memory is short dm-bufio evicts buffers until the target is met again.
+
 Example
 =======
 Set up a device::
Documentation/admin-guide/kernel-parameters.txt +6 -0
index 0b3c140babd9..914da403c5de 100644
@@ -1351,6 +1351,12 @@ Kernel parameters
 			For details see:
 			Documentation/admin-guide/hw-vuln/reg-file-data-sampling.rst
 
+	dm_verity.hash_retain_percent=
+			[DM] Percentage of the hash area that dm-verity
+			asks dm-bufio to keep cached for a new device.
+			Defaults to 10; 0 or a value above 100 leaves the
+			dm-bufio default.
+
 	dm_verity.keyring_unsealed=
 			[KNL] When set to 1, leave the dm-verity keyring
 			unsealed after initialization so userspace can
drivers/md/dm-verity-target.c +24 -2
index 451c75e30a8f..0e8af1a57d75 100644
@@ -32,6 +32,8 @@
 #define DM_VERITY_DEFAULT_PREFETCH_SIZE	262144
 #define DM_VERITY_USE_BH_DEFAULT_BYTES	8192
 
+#define DM_VERITY_DEFAULT_HASH_RETAIN_PERCENT	10
+
 #define DM_VERITY_MAX_CORRUPTED_ERRS	100
 
 #define DM_VERITY_OPT_LOGGING		"ignore_corruption"
@@ -50,6 +52,13 @@ static unsigned int dm_verity_prefetch_cluster = DM_VERITY_DEFAULT_PREFETCH_SIZE
 
 module_param_named(prefetch_cluster, dm_verity_prefetch_cluster, uint, 0644);
 
+/* Default fraction of the hash tree that dm-bufio is asked to keep cached. */
+static unsigned int dm_verity_hash_retain_percent = DM_VERITY_DEFAULT_HASH_RETAIN_PERCENT;
+
+module_param_named(hash_retain_percent, dm_verity_hash_retain_percent, uint, 0644);
+MODULE_PARM_DESC(hash_retain_percent,
+	"Percentage of the hash area to keep cached by default");
+
 static unsigned int dm_verity_use_bh_bytes[4] = {
 	DM_VERITY_USE_BH_DEFAULT_BYTES,	// IOPRIO_CLASS_NONE
 	DM_VERITY_USE_BH_DEFAULT_BYTES,	// IOPRIO_CLASS_RT
@@ -1084,14 +1093,14 @@ static void verity_dtr(struct dm_target *ti)
 
 	kfree(v->alg_name);
 
+	verity_fec_dtr(v);
+
 	if (v->hash_dev)
 		dm_put_device(ti, v->hash_dev);
 
 	if (v->data_dev)
 		dm_put_device(ti, v->data_dev);
 
-	verity_fec_dtr(v);
-
 	kfree(v->signature_key_desc);
 
 	if (v->use_bh_wq)
@@ -1421,6 +1430,7 @@ static int verity_ctr(struct dm_target *ti, unsigned int argc, char **argv)
 	struct dm_verity_sig_opts verify_args = {0};
 	struct dm_arg_set as;
 	unsigned int num;
+	unsigned int hash_retain_percent;
 	unsigned long long num_ll;
 	int r;
 	int i;
@@ -1638,6 +1648,18 @@ static int verity_ctr(struct dm_target *ti, unsigned int argc, char **argv)
 		goto bad;
 	}
 
+	/* Keep a configurable fraction of the hash tree cached by default. */
+	hash_retain_percent = READ_ONCE(dm_verity_hash_retain_percent);
+	if (hash_retain_percent <= 100) {
+		u64 retain = mul_u64_u32_div((u64)(v->hash_end - v->hash_start) <<
+					     v->hash_dev_block_bits,
+					     hash_retain_percent, 100);
+
+		if (retain > ULONG_MAX)
+			retain = ULONG_MAX;
+		dm_bufio_set_retain_bytes(v->bufio, retain);
+	}
+
 	/*
 	 * Using WQ_HIGHPRI improves throughput and completion latency by
 	 * reducing wait times when reading from a dm-verity device.
Signature · 1 line
2.43.0
#4 lore raw

PATCH v5 4/5 dm-verity: add retain_bytes message to inspect and tune the cache floor

In reply to Yongpeng Yang

From: Yongpeng Yang <[email protected]>

Nothing lets a user see how much memory a verity device keeps cached, or tune it for one device without touching every future client.

Add the retain_bytes <hash|fec> [<bytes>] message. It reports the selected client's retain target, or sets it when <bytes> is given (0 resets to the dm-bufio default); the reply also reports the bytes and buffers currently cached, so memory use can be watched through the message itself.

Assisted-by LLM

---
v3:
- The reply now also reports current_bytes and buffers, replacing the v1/v2 sysfs interface, which is dropped entirely.

---
 .../admin-guide/device-mapper/verity.rst      | 10 +++
 drivers/md/dm-verity-target.c                 | 63 +++++++++++++++++++
 2 files changed, 73 insertions(+)
Documentation/admin-guide/device-mapper/verity.rst +10 -0
index 7d6e567cef33..1e532c4251ae 100644
@@ -343,6 +343,16 @@ The retain target is a floor applied by the memory shrinker, not a cap: when
 there is no memory pressure a fully warmed cache may grow past it, and when
 memory is short dm-bufio evicts buffers until the target is met again.
 
+Messages
+========
+
+``retain_bytes <hash|fec> [<bytes>]``
+    Report the retain target of the hash or FEC parity client, or set it
+    (0 resets to the dm-bufio default).  ``fec`` requires FEC to be
+    enabled.  The reply is
+    ``retain_bytes=<bytes> current_bytes=<bytes> buffers=<n>``, so the
+    client's actual memory use can be watched through the message.
+
 Example
 =======
 Set up a device::
drivers/md/dm-verity-target.c +63 -0

75 lines not on this page · raw message

Signature · 1 line
2.43.0
#5 lore raw

PATCH v5 5/5 dm-verity: add messages to prefetch and drop the hash cache

In reply to Yongpeng Yang

From: Yongpeng Yang <[email protected]>

Nothing lets a user warm a verity device's cache ahead of the reads that will need it, or release the memory a device no longer needs.

Add two messages. prefetch_hash [<start> <count>] starts reading hash blocks asynchronously; it is not limited by the retain target, which only applies to eviction. drop_hash [<start> <count>] drops hash blocks, keeping those that are in use or dirty. Together they let userspace warm the cache when a device is about to be used and release the memory when it goes cold, instead of occupying it continuously.

Both are rejected with -EBUSY while the device is suspended, since their I/O bypasses the suspended dm queue, and with -EOPNOTSUPP on try_verify_in_tasklet devices, whose bufio client cannot evict or wait for a buffer that is still being read.

The suspended check needs no further serialization: __dm_suspend() sets the suspended flag before the final synchronize_srcu() that precedes ->postsuspend, so a message that passed the check is drained by that barrier before the bufio reset (the whole prefetch execution, including the window where a buffer sits with hold_count == 1 outside dm_bufio_lock, happens inside the SRCU read section), and a message that arrives after the barrier sees the flag. The reads a completed prefetch left in flight are waited out by the reset itself:
drop_buffers() evicts the buffer and __make_buffer_clean() waits on B_READING.

Assisted-by LLM

---
v4:
- prefetch_hash and drop_hash now return -EBUSY while the device is
suspended: their I/O bypasses the suspended dm queue, and the check is safe without further serialization because __dm_suspend() sets the suspended flag before the final synchronize_srcu() that precedes ->postsuspend, so a message that passed the check is drained before the bufio reset (sashiko).
v3:
- Split out of the previous message patch; contains only the cache lifecycle commands.
- Reject prefetch_hash on try_verify_in_tasklet devices (-EOPNOTSUPP), same as drop_hash.
- Accept prefetch_hash/drop_hash with an empty hash area (levels == 0) as a no-op instead of failing.

---
 .../admin-guide/device-mapper/verity.rst      |  15 +++
 drivers/md/dm-verity-target.c                 | 124 +++++++++++++++++-
 2 files changed, 137 insertions(+), 2 deletions(-)
Documentation/admin-guide/device-mapper/verity.rst +15 -0
index 1e532c4251ae..17e98e85e416 100644
@@ -353,6 +353,21 @@ Messages
     ``retain_bytes=<bytes> current_bytes=<bytes> buffers=<n>``, so the
     client's actual memory use can be watched through the message.
 
+``prefetch_hash [<start> <count>]``
+    Start reading hash blocks into the cache; without arguments, the whole
+    hash area.  The read is asynchronous and is not limited by the retain
+    target, which only applies to eviction.  Not supported on devices
+    created with ``try_verify_in_tasklet`` (``-EOPNOTSUPP``), whose bufio
+    client cannot evict or wait for a buffer that is still being read.
+
+``drop_hash [<start> <count>]``
+    Drop hash blocks from the cache, keeping blocks that are in use or
+    dirty.  Not supported on devices created with ``try_verify_in_tasklet``
+    (``-EOPNOTSUPP``), whose bufio client cannot drop buffers.
+
+``prefetch_hash`` and ``drop_hash`` return ``-EBUSY`` while the device is
+suspended, since their I/O bypasses the suspended dm queue.
+
 Example
 =======
 Set up a device::
drivers/md/dm-verity-target.c +122 -2

140 lines not on this page · raw message

Signature · 1 line
2.43.0