Skip to contentSkip to conversation

md: don't wait for q->limits_lock while md holds back I/O

PATCH In review Jack Wang 5 participants 19 messages Sep 10 – Oct 23

Subsystems (3)
lore
Share & tools
lore

Jack Wang

author
#0 lore raw

v2 cover md: don't wait for q->limits_lock while md holds back I/O

From: Jack Wang <[email protected]>

Writing to a queue limits attribute of an md array while a spare is being re-added deadlocks the array. I reported this earlier here:

https://lore.kernel.org/linux-raid/CAMGffE=heGA3y8FjQ0Sm1jj-kd-=H9Y54WozKASSEZhc9UNKjA@mail.gmail.com/

Four tasks, one array:

udev-worker queue_attr_store() holds q->limits_lock, waits in
blk_mq_freeze_queue() for q_usage_counter to drain
fio holds a q_usage_counter reference, parked in
md_handle_request()'s is_suspended() loop
mdadm suspended the array, waits for reconfig_mutex
md_start_sync holds reconfig_mutex, waits for q->limits_lock

The last leg is mddev_stack_new_rdev() from ->hot_add_disk(). Since commit c99f66e4084a ("block: fix queue freeze vs limits lock order in sysfs store methods") the sysfs store holds q->limits_lock across the freeze, so md must not block on that lock while it is holding back the I/O the freeze waits for. That is the same hazard mddev_suspend() already documents for reconfig_mutex.

v1 kept q->limits_lock outermost where it could and used a trylock everywhere else. Christoph asked for the lock ordering to be fixed instead, so v2 drops the trylock and the block patch that added it.

The rule v2 applies is that q->limits_lock nests outside reconfig_mutex and the suspend everywhere, with no exceptions to paper over. The two callers that cannot own an update do not need one: check_sb_changes() and md_check_recovery() only ever re-add a device that is already a member, so its limits are stacked and the update is a refresh, and they now take the no-stack path unconditionally. mddev_update_io_opt() is not an add and does need the update, so patch 4 defers it to a work item that takes the lock with nothing held.

Making the hoists unconditional exposed a second cycle that the trylock had been hiding, which Nilay hit with lockdep on v1:

q->limits_lock -> reconfig_mutex added by this series
reconfig_mutex -> disk->open_mutex pre-existing, md opens legs
under reconfig_mutex
disk->open_mutex -> q->limits_lock pre-existing, sd_open() ->
sd_revalidate_disk()

Only the middle edge can go, so legs are now opened before any md lock is taken. Patch 7 does the opens and patch 8 the holder links, which take disk->open_mutex too and were easy to miss because the release side only takes blk_holder_mutex. Opening without reconfig_mutex means the superblock format fields have to be snapshotted and rechecked once the array is locked.

Patches 1, 3 and 6 are plumbing with no functional change.

Two callers still take q->limits_lock inside reconfig_mutex, both with the array suspended, and patch 5 says why: ->start_reshape() from action_store(), which suspends before flushing sync_work, and raid*_run() -> queue_limits_set() from level_store(), which already hangs on its own because it freezes the queue while suspended. Both need more restructuring than belongs here.

The patches are based on v7.3-rc2.

v1: https://lore.kernel.org/linux-raid/[email protected]/T/#t

Changes since v1:
- Drop the trylock and the block patch adding queue_limits_start_update_trylock(), per Christoph.
- check_sb_changes() and md_check_recovery() take the no-stack path unconditionally instead of trying the lock first.
- Defer the io_opt update to a work item rather than skipping it on a contended pass (patch 4, was "md: don't wait for q->limits_lock in mddev_update_io_opt()").
- New patches 6-8 to close the reconfig_mutex -> disk->open_mutex edge that lockdep reported on v1: pass a queue_limits through ->run(), open new legs before locking the array, and link their holders there too.
- Rebased on v7.3-rc2.

Testing, on v7.3-rc2 with lockdep (PROVE_LOCKING, DEBUG_LOCK_ALLOC):

- the reproducer below, 20 fail/remove/add cycles with fio in flight and a loop writing queue/max_sectors_kb, where the same test wedges the array before the series
- array start at raid0, raid1, raid5, raid10 and linear, spare add, fail and remove, the rdev sysfs stores, ADD_NEW_DISK, array_state transitions, a level change and a raid5 3 -> 4 reshape to completion, which is what exercises patch 4's work item: io_opt goes from 1048576 to 1572864 once end_reshape() runs
- HOT_ADD_DISK of an undersized leg, so bind_rdev_to_array() fails and patch 8's release path runs

No lockdep reports, and debug_locks stayed 1 throughout. Every patch builds on its own.

A blktests case covering this deadlock will be sent separately.

The reproducer, for anyone who wants it:

  mdadm -C /dev/md111 --force -e 1.2 --assume-clean -l 1 \
        --bitmap=internal -n 2 /dev/ram0 /dev/ram1

  fio --direct=1 --rw=randrw --ioengine=libaio --iodepth=32 --numjobs=4 \
      --time_based=1 --runtime=180 --filename=/dev/md111 --name=repro &

while :; do

      echo 128 > /sys/block/md111/queue/max_sectors_kb 2>/dev/null

done &

  for i in $(seq 20); do
      mdadm /dev/md111 --fail /dev/ram0
      mdadm /dev/md111 --remove /dev/ram0
      mdadm /dev/md111 --add /dev/ram0
      mdadm --wait /dev/md111
  done

Jack Wang (8):
md: pass a queue_limits down to ->hot_add_disk()
md: don't wait for q->limits_lock in check_sb_changes()
md: pass a queue_limits through the rdev sysfs stores
md: defer the io_opt update out of the sync thread
md: take q->limits_lock before locking and suspending the array
md: pass a queue_limits through ->run()
md: open new legs before locking the array
md: link a new leg's holder before locking the array

 drivers/md/dm-raid.c       |   4 +-
 drivers/md/md-autodetect.c |  38 ++-
 drivers/md/md-linear.c     |  30 +-
 drivers/md/md.c            | 661 +++++++++++++++++++++++++++++--------
 drivers/md/md.h            |  56 +++-
 drivers/md/raid0.c         |  16 +-
 drivers/md/raid1.c         |  26 +-
 drivers/md/raid10.c        |  37 ++-
 drivers/md/raid5.c         |  54 ++-
 9 files changed, 741 insertions(+), 181 deletions(-)
Signature · 1 line
2.43.0
author
#1 lore raw

PATCH v2 1/8 md: pass a queue_limits down to ->hot_add_disk()

From: Jack Wang <[email protected]>

Adding a leg stacks its queue limits, which mddev_stack_new_rdev() does by taking q->limits_lock itself. Callers holding reconfig_mutex or a suspended array cannot allow that, and must own the update instead.

Give ->hot_add_disk(), remove_and_add_spares() and md_choose_sync_action() a struct queue_limits argument with three
states: an update to stack into, NULL to let the personality take the lock as before, or MDDEV_STACK_SKIP to add the leg without touching the limits, for callers that can do neither. mddev_stack_rdev_into() stacks into a caller-owned update without the lock.

Every caller still passes NULL and nothing passes the sentinel yet, so there is no functional change; the users follow.

Assisted-by LLM
---
 drivers/md/dm-raid.c   |  2 +-
 drivers/md/md-linear.c | 28 ++++++++++++++----
 drivers/md/md.c        | 66 ++++++++++++++++++++++++++++++++----------
 drivers/md/md.h        | 11 ++++++-
 drivers/md/raid1.c     | 10 +++++--
 drivers/md/raid10.c    | 19 +++++++++---
 drivers/md/raid5.c     |  5 ++--
 7 files changed, 110 insertions(+), 31 deletions(-)
drivers/md/dm-raid.c +1 -1
index 8f5a5e1342a9..21a1922bee4f 100644
@@ -3923,7 +3923,7 @@ static void attempt_restore_of_faulty_devices(struct raid_set *rs)
 			clear_bit(Faulty, &r->flags);
 			clear_bit(WriteErrorSeen, &r->flags);
 
-			if (mddev->pers->hot_add_disk(mddev, r)) {
+			if (mddev->pers->hot_add_disk(mddev, r, NULL)) {
 				/* Failed to revive this device, try next */
 				r->raid_disk = r->saved_raid_disk = -1;
 				r->flags = flags;
drivers/md/md-linear.c +22 -6
index 73b367b61b87..da82c313d459 100644
@@ -65,11 +65,16 @@ static sector_t linear_size(struct mddev *mddev, sector_t sectors, int raid_disk
 	return array_sectors;
 }
 
-static int linear_set_limits(struct mddev *mddev)
+static int linear_set_limits(struct mddev *mddev,
+			     struct queue_limits *caller_lim)
 {
 	struct queue_limits lim;
 	int err;
 
+	/* the caller can neither stack nor take q->limits_lock */
+	if (caller_lim == MDDEV_STACK_SKIP)
+		return 0;
+
 	md_init_stacking_limits(&lim);
 	lim.features |= BLK_FEAT_NOWAIT;
 	lim.max_hw_sectors = mddev->chunk_sectors;
@@ -82,10 +87,20 @@ static int linear_set_limits(struct mddev *mddev)
 	if (err)
 		return err;
 
+	/*
+	 * The caller owns an update and commits it itself; taking
+	 * q->limits_lock here would take it a second time.
+	 */
+	if (caller_lim) {
+		*caller_lim = lim;
+		return 0;
+	}
+
 	return queue_limits_set(mddev->gendisk->queue, &lim);
 }
 
-static struct linear_conf *linear_conf(struct mddev *mddev, int raid_disks)
+static struct linear_conf *linear_conf(struct mddev *mddev, int raid_disks,
+				       struct queue_limits *lim)
 {
 	struct linear_conf *conf;
 	struct md_rdev *rdev;
@@ -151,7 +166,7 @@ static struct linear_conf *linear_conf(struct mddev *mddev, int raid_disks)
 			conf->disks[i].rdev->sectors;
 
 	if (!mddev_is_dm(mddev)) {
-		ret = linear_set_limits(mddev);
+		ret = linear_set_limits(mddev, lim);
 		if (ret)
 			goto out;
 	}
@@ -171,7 +186,7 @@ static int linear_run(struct mddev *mddev)
 	if (md_check_no_bitmap(mddev))
 		return -EINVAL;
 
-	conf = linear_conf(mddev, mddev->raid_disks);
+	conf = linear_conf(mddev, mddev->raid_disks, NULL);
 	if (IS_ERR(conf))
 		return PTR_ERR(conf);
 
@@ -186,7 +201,8 @@ static int linear_run(struct mddev *mddev)
 	return ret;
 }
 
-static int linear_add(struct mddev *mddev, struct md_rdev *rdev)
+static int linear_add(struct mddev *mddev, struct md_rdev *rdev,
+		      struct queue_limits *lim)
 {
 	/* Adding a drive to a linear array allows the array to grow.
 	 * It is permitted if the new drive has a matching superblock
@@ -204,7 +220,7 @@ static int linear_add(struct mddev *mddev, struct md_rdev *rdev)
 	rdev->raid_disk = rdev->saved_raid_disk;
 	rdev->saved_raid_disk = -1;
 
-	newconf = linear_conf(mddev, mddev->raid_disks + 1);
+	newconf = linear_conf(mddev, mddev->raid_disks + 1, lim);
 	if (IS_ERR(newconf))
 		return PTR_ERR(newconf);
 
drivers/md/md.c +51 -15

147 lines not on this page · raw message

drivers/md/md.h +10 -1
index b6d2e8929a0f..ebdd57677062 100644
@@ -765,7 +765,8 @@ struct md_personality
 	 * if appropriate, and should abort recovery if needed
 	 */
 	void (*error_handler)(struct mddev *mddev, struct md_rdev *rdev);
-	int (*hot_add_disk) (struct mddev *mddev, struct md_rdev *rdev);
+	int (*hot_add_disk)(struct mddev *mddev, struct md_rdev *rdev,
+			    struct queue_limits *lim);
 	int (*hot_remove_disk) (struct mddev *mddev, struct md_rdev *rdev);
 	int (*spare_active) (struct mddev *mddev);
 	sector_t (*sync_request)(struct mddev *mddev, sector_t sector_nr,
@@ -1047,6 +1048,14 @@ int do_md_run(struct mddev *mddev);
 int mddev_stack_rdev_limits(struct mddev *mddev, struct queue_limits *lim,
 		unsigned int flags);
 int mddev_stack_new_rdev(struct mddev *mddev, struct md_rdev *rdev);
+int mddev_stack_rdev_into(struct mddev *mddev, struct md_rdev *rdev,
+			  struct queue_limits *lim);
+/*
+ * Sentinel for the queue_limits argument of ->hot_add_disk().  The caller has
+ * no update to stack into and must not take q->limits_lock itself, so the leg
+ * is added with the array's current limits.
+ */
+#define MDDEV_STACK_SKIP	((struct queue_limits *)ERR_PTR(-EAGAIN))
 void mddev_update_io_opt(struct mddev *mddev, unsigned int nr_stripes);
 
 extern const struct block_device_operations md_fops;
drivers/md/raid1.c +8 -2
index f0646fb24371..78effcac138d 100644
@@ -1898,7 +1898,8 @@ static bool raid1_remove_conf(struct r1conf *conf, int disk)
 	return true;
 }
 
-static int raid1_add_disk(struct mddev *mddev, struct md_rdev *rdev)
+static int raid1_add_disk(struct mddev *mddev, struct md_rdev *rdev,
+			  struct queue_limits *lim)
 {
 	struct r1conf *conf = mddev->private;
 	int err = -EEXIST;
@@ -1923,7 +1924,12 @@ static int raid1_add_disk(struct mddev *mddev, struct md_rdev *rdev)
 	for (mirror = first; mirror <= last; mirror++) {
 		p = conf->mirrors + mirror;
 		if (!p->rdev) {
-			err = mddev_stack_new_rdev(mddev, rdev);
+			if (lim == MDDEV_STACK_SKIP)
+				err = 0;
+			else if (lim)
+				err = mddev_stack_rdev_into(mddev, rdev, lim);
+			else
+				err = mddev_stack_new_rdev(mddev, rdev);
 			if (err)
 				return err;
 
drivers/md/raid10.c +15 -4
index 1093c798d9dd..222bd7badcff 100644
@@ -2095,7 +2095,8 @@ static int raid10_spare_active(struct mddev *mddev)
 	return count;
 }
 
-static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev)
+static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev,
+			   struct queue_limits *lim)
 {
 	struct r10conf *conf = mddev->private;
 	int err = -EEXIST;
@@ -2130,7 +2131,12 @@ static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev)
 			continue;
 		}
 
-		err = mddev_stack_new_rdev(mddev, rdev);
+		if (lim == MDDEV_STACK_SKIP)
+			err = 0;
+		else if (lim)
+			err = mddev_stack_rdev_into(mddev, rdev, lim);
+		else
+			err = mddev_stack_new_rdev(mddev, rdev);
 		if (err)
 			return err;
 		p->head_position = 0;
@@ -2147,7 +2153,12 @@ static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev)
 		clear_bit(In_sync, &rdev->flags);
 		set_bit(Replacement, &rdev->flags);
 		rdev->raid_disk = repl_slot;
-		err = mddev_stack_new_rdev(mddev, rdev);
+		if (lim == MDDEV_STACK_SKIP)
+			err = 0;
+		else if (lim)
+			err = mddev_stack_rdev_into(mddev, rdev, lim);
+		else
+			err = mddev_stack_new_rdev(mddev, rdev);
 		if (err)
 			return err;
 		conf->fullsync = 1;
@@ -4484,7 +4495,7 @@ static int raid10_start_reshape(struct mddev *mddev)
 		rdev_for_each(rdev, mddev)
 			if (rdev->raid_disk < 0 &&
 			    !test_bit(Faulty, &rdev->flags)) {
-				if (raid10_add_disk(mddev, rdev) == 0) {
+				if (raid10_add_disk(mddev, rdev, NULL) == 0) {
 					if (rdev->raid_disk >=
 					    conf->prev.raid_disks)
 						set_bit(In_sync, &rdev->flags);
drivers/md/raid5.c +3 -2
index b91545ce090d..0ec555ada64a 100644
@@ -8441,7 +8441,8 @@ static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
 	return err;
 }
 
-static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
+static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev,
+			  struct queue_limits *lim)
 {
 	struct r5conf *conf = mddev->private;
 	int ret, err = -EEXIST;
@@ -8728,7 +8729,7 @@ static int raid5_start_reshape(struct mddev *mddev)
 		rdev_for_each(rdev, mddev)
 			if (rdev->raid_disk < 0 &&
 			    !test_bit(Faulty, &rdev->flags)) {
-				if (raid5_add_disk(mddev, rdev) == 0) {
+				if (raid5_add_disk(mddev, rdev, NULL) == 0) {
 					if (rdev->raid_disk
 					    >= conf->previous_raid_disks)
 						set_bit(In_sync, &rdev->flags);
Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH v2 1/8] md: pass a queue_limits down to ->hot_add_disk()

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] raid1_add_disk fails to stack limits or validate compatibility for replacement disks. --

commit d7876b523180e9507873b141ec81e8cdf84d9929
Author: Jack Wang <[email protected]>

md: pass a queue_limits down to ->hot_add_disk()

This commit updates the md hot-add disk paths to accept a queue_limits argument. This allows callers to manage the limits lock explicitly when adding a disk, preventing potential deadlocks.

[ ... ]

Quoted 16 lines
drivers/md/raid1.c +6 -1
@@ -1923,7 +1924,12 @@ static int raid1_add_disk(struct mddev *mddev, struct md_rdev *rdev)
 	for (mirror = first; mirror <= last; mirror++) {
 		p = conf->mirrors + mirror;
 		if (!p->rdev) {
-			err = mddev_stack_new_rdev(mddev, rdev);
+			if (lim == MDDEV_STACK_SKIP)
+				err = 0;
+			else if (lim)
+				err = mddev_stack_rdev_into(mddev, rdev, lim);
+			else
+				err = mddev_stack_new_rdev(mddev, rdev);
 			if (err)
 				return err;

[ ... ]

Quoted 5 lines
		if (test_bit(WantReplacement, &p->rdev->flags) &&
		    p[conf->raid_disks].rdev == NULL && repl_slot < 0)
			repl_slot = mirror;
	}
Quoted 8 lines
	if (err && repl_slot >= 0) {
		/* Add this device as a replacement */
		clear_bit(In_sync, &rdev->flags);
		set_bit(Replacement, &rdev->flags);
		raid1_add_conf(conf, rdev, repl_slot, true);
		err = 0;
		conf->fullsync = 1;
	}

[Severity: High]
This is a pre-existing issue, but does this replacement path in raid1_add_disk() omit queue limits validation?

Unlike the primary hot-add path modified above, the fallback block for configuring replacement disks skips the queue limits stacking entirely. If a replacement disk is hot-added with incompatible features, such as a larger logical block size or an unsupported integrity profile, it appears the array will accept the disk without validation.

Could this allow the queue limits API contract to be bypassed, potentially leading to misaligned I/Os being sent to the underlying block device and resulting in I/O errors or data corruption during array reconstruction?

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

Re: [PATCH v2 1/8] md: pass a queue_limits down to ->hot_add_disk()

In reply to Jack Wang
Quoted 69 lines · Jack Wang

From: Jack Wang <[email protected]>

Adding a leg stacks its queue limits, which mddev_stack_new_rdev() does by taking q->limits_lock itself. Callers holding reconfig_mutex or a suspended array cannot allow that, and must own the update instead.

Give ->hot_add_disk(), remove_and_add_spares() and md_choose_sync_action() a struct queue_limits argument with three
states: an update to stack into, NULL to let the personality take the lock as before, or MDDEV_STACK_SKIP to add the leg without touching the limits, for callers that can do neither. mddev_stack_rdev_into() stacks into a caller-owned update without the lock.

Every caller still passes NULL and nothing passes the sentinel yet, so there is no functional change; the users follow.

Assisted-by LLM
---
  drivers/md/dm-raid.c   |  2 +-
  drivers/md/md-linear.c | 28 ++++++++++++++----
  drivers/md/md.c        | 66 ++++++++++++++++++++++++++++++++----------
  drivers/md/md.h        | 11 ++++++-
  drivers/md/raid1.c     | 10 +++++--
  drivers/md/raid10.c    | 19 +++++++++---
  drivers/md/raid5.c     |  5 ++--
  7 files changed, 110 insertions(+), 31 deletions(-)
drivers/md/dm-raid.c +1 -1
index 8f5a5e1342a9..21a1922bee4f 100644
@@ -3923,7 +3923,7 @@ static void attempt_restore_of_faulty_devices(struct raid_set *rs)
  			clear_bit(Faulty, &r->flags);
  			clear_bit(WriteErrorSeen, &r->flags);
 
-			if (mddev->pers->hot_add_disk(mddev, r)) {
+			if (mddev->pers->hot_add_disk(mddev, r, NULL)) {
  				/* Failed to revive this device, try next */
  				r->raid_disk = r->saved_raid_disk = -1;
  				r->flags = flags;
drivers/md/md-linear.c +8 -1
index 73b367b61b87..da82c313d459 100644
@@ -65,11 +65,16 @@ static sector_t linear_size(struct mddev *mddev, sector_t sectors, int raid_disk
  	return array_sectors;
  }
 
-static int linear_set_limits(struct mddev *mddev)
+static int linear_set_limits(struct mddev *mddev,
+			     struct queue_limits *caller_lim)
  {
  	struct queue_limits lim;
  	int err;
 
+	/* the caller can neither stack nor take q->limits_lock */
+	if (caller_lim == MDDEV_STACK_SKIP)
+		return 0;
+
  	md_init_stacking_limits(&lim);
  	lim.features |= BLK_FEAT_NOWAIT;
  	lim.max_hw_sectors = mddev->chunk_sectors;
@@ -82,10 +87,20 @@ static int linear_set_limits(struct mddev *mddev)
  	if (err)
  		return err;
 
+	/*
+	 * The caller owns an update and commits it itself; taking

drivers/md/md-linear.c static int linear_set_limits(struct mddev *mddev) · line 101

Quoted 10 lines
drivers/md/md-linear.c +7 -0
+	 * q->limits_lock here would take it a second time.
+	 */
+	if (caller_lim) {
+		*caller_lim = lim;
+		return 0;
+	}
+
  	return queue_limits_set(mddev->gendisk->queue, &lim);
  }
 

This looks overly complicated with three different cases where linear_set_limits() either ignores the limits update, updates the limits provided by the caller without committing them, or updates and commits the limits itself.

Why can't we instead have the callers always pass a struct queue_limits pointer, and make linear_set_limits() only update the limits provided by its caller without committing them?

The caller can then decide what to do with the resulting limits: either ignore them or commit them as appropriate. This also avoids introducing MDDEV_STACK_SKIP as a special sentinel value.

In this model, linear_set_limits() would only be responsible for preparing the limits. This also keeps the locking and limits-commit logic in one common place. The caller is then responsible for acquiring the appropriate locks and committing the limits in the correct order for its particular context.

So the core logic is: personality should describe what the limits need to become and the MD core/caller should decide when those limits become visible.

[...]

Quoted 25 lines
drivers/md/md-linear.c +24 -0
+/*
+ * Stack a new rdev into limits the caller already holds limits_lock for and
+ * will commit itself.  Used from paths that must take limits_lock before
+ * quiescing the array, see md_start_sync().
+ */
+int mddev_stack_rdev_into(struct mddev *mddev, struct md_rdev *rdev,
+			  struct queue_limits *lim)
+{
+	struct queue_limits tmp = *lim;
+
+	if (mddev_is_dm(mddev))
+		return 0;
+
+	if (queue_logical_block_size(rdev->bdev->bd_disk->queue) >
+	    queue_logical_block_size(mddev->gendisk->queue)) {
+		pr_err("%s: incompatible logical_block_size, can not add\n",
+		       mdname(mddev));
+		return -EINVAL;
+	}
+
+	queue_limits_stack_bdev(&tmp, rdev->bdev, rdev->data_offset,
+				mddev->gendisk->disk_name);
+
+	if (!queue_limits_stack_integrity_bdev(&tmp, rdev->bdev)) {

drivers/md/md-linear.c static int linear_set_limits(struct mddev *mddev)

Quoted 10 lines
drivers/md/md-linear.c +10 -0
+		pr_err("%s: incompatible integrity profile for %pg\n",
+		       mdname(mddev), rdev->bdev);
+		return -ENXIO;
+	}
+
+	*lim = tmp;
+	return 0;
+}
+EXPORT_SYMBOL_GPL(mddev_stack_rdev_into);
+

This API is correctly moving in that direction which I proposed above. But rather than adding new API, I'd update mddev_stack_new_rdev() (or rename it to mddev_stack_rdev_into()) which would stack the rdev into the caller-provided struct queue_limits without taking q->limits_lock or committing the limits.

[...]

drivers/md/md-linear.c

Quoted 6 lines
drivers/md/md-linear.c +6 -0
+/*
+ * Sentinel for the queue_limits argument of ->hot_add_disk().  The caller has
+ * no update to stack into and must not take q->limits_lock itself, so the leg
+ * is added with the array's current limits.
+ */
+#define MDDEV_STACK_SKIP	((struct queue_limits *)ERR_PTR(-EAGAIN))

If we follow the design as I suggested above then we can get away with above sentinel.

[...]

Quoted 10 lines
drivers/md/md-linear.c +2 -1
-static int raid1_add_disk(struct mddev *mddev, struct md_rdev *rdev)
+static int raid1_add_disk(struct mddev *mddev, struct md_rdev *rdev,
+			  struct queue_limits *lim)
  {
  	struct r1conf *conf = mddev->private;
  	int err = -EEXIST;
@@ -1923,7 +1924,12 @@ static int raid1_add_disk(struct mddev *mddev, struct md_rdev *rdev)
  	for (mirror = first; mirror <= last; mirror++) {
  		p = conf->mirrors + mirror;
  		if (!p->rdev) {

drivers/md/md-linear.c static int raid1_add_disk(struct mddev *mddev, struct md_rdev *rdev) · line 1935

Quoted 10 lines
drivers/md/md-linear.c +6 -1
-			err = mddev_stack_new_rdev(mddev, rdev);
+			if (lim == MDDEV_STACK_SKIP)
+				err = 0;
+			else if (lim)
+				err = mddev_stack_rdev_into(mddev, rdev, lim);
+			else
+				err = mddev_stack_new_rdev(mddev, rdev);
  			if (err)
  				return err;
 

Here as well the same comment as linear_set_limits().

Quoted 32 lines
drivers/md/raid10.c +8 -2
index 1093c798d9dd..222bd7badcff 100644
@@ -2095,7 +2095,8 @@ static int raid10_spare_active(struct mddev *mddev)
  	return count;
  }
 
-static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev)
+static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev,
+			   struct queue_limits *lim)
  {
  	struct r10conf *conf = mddev->private;
  	int err = -EEXIST;
@@ -2130,7 +2131,12 @@ static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev)
  			continue;
  		}
 
-		err = mddev_stack_new_rdev(mddev, rdev);
+		if (lim == MDDEV_STACK_SKIP)
+			err = 0;
+		else if (lim)
+			err = mddev_stack_rdev_into(mddev, rdev, lim);
+		else
+			err = mddev_stack_new_rdev(mddev, rdev);
  		if (err)
  			return err;
  		p->head_position = 0;
@@ -2147,7 +2153,12 @@ static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev)
  		clear_bit(In_sync, &rdev->flags);
  		set_bit(Replacement, &rdev->flags);
  		rdev->raid_disk = repl_slot;

drivers/md/raid10.c static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev) · line 2164

Quoted 10 lines
drivers/md/raid10.c +6 -1
-		err = mddev_stack_new_rdev(mddev, rdev);
+		if (lim == MDDEV_STACK_SKIP)
+			err = 0;
+		else if (lim)
+			err = mddev_stack_rdev_into(mddev, rdev, lim);
+		else
+			err = mddev_stack_new_rdev(mddev, rdev);
  		if (err)
  			return err;
  		conf->fullsync = 1;

Again same comment as linear_set_limits().

Thanks,
--Nilay

author
#4 lore raw

PATCH v2 2/8 md: don't wait for q->limits_lock in check_sb_changes()

In reply to Jack Wang

From: Jack Wang <[email protected]>

check_sb_changes() activates a spare another node added, reached from md_reload_sb() -> process_metadata_update() with reconfig_mutex held. Stacking the device's limits there waits for q->limits_lock under that mutex, which deadlocks: the lock's holder waits for the queue to drain, and that I/O can be waiting for a superblock update needing reconfig_mutex.

The device is already a member, so its limits are stacked. Add it with MDDEV_STACK_SKIP and leave them alone.

Assisted-by LLM
---
 drivers/md/md.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
drivers/md/md.c +8 -1
index 28fc903ffeea..e60dc2c7eb90 100644
@@ -10885,7 +10885,14 @@ static void check_sb_changes(struct mddev *mddev, struct md_rdev *rdev)
 					rdev2->saved_raid_disk = -1;
 				else
 					rdev2->saved_raid_disk = role;
-				ret = remove_and_add_spares(mddev, rdev2, NULL);
+				/*
+				 * reconfig_mutex is held, so q->limits_lock
+				 * cannot be taken here.  The device is
+				 * already a member, its limits are stacked,
+				 * so add it without touching them.
+				 */
+				ret = remove_and_add_spares(mddev, rdev2,
+							    MDDEV_STACK_SKIP);
 				pr_info("Activated spare: %pg\n",
 					rdev2->bdev);
 				/* wakeup mddev->thread here, so array could
Signature · 1 line
2.43.0
#5 lore raw

Re: [PATCH v2 2/8] md: don't wait for q->limits_lock in check_sb_changes()

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Bypassing queue limit stacking for hot-added disks on cluster peer nodes leaves the array with…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Bypassing queue limit stacking for hot-added disks on cluster peer nodes leaves the array with potentially invalid queue limits. --

commit 82a21bb72118b2177a8f4af3c99a80190f1aac3e
Author: Jack Wang <[email protected]>

md: don't wait for q->limits_lock in check_sb_changes()

This commit modifies check_sb_changes() to bypass queue limit stacking for a newly activated spare by passing MDDEV_STACK_SKIP to remove_and_add_spares(). This is intended to prevent deadlocks when reconfig_mutex is held.

Quoted 7 lines
drivers/md/md.c +0 -0
index 28fc903ffeea3..e60dc2c7eb90e 100644
@@ -10885,7 +10885,14 @@ static void check_sb_changes(struct mddev *mddev, struct md_rdev *rdev)
 					rdev2->saved_raid_disk = -1;
 				else

drivers/md/md.c static void check_sb_changes(struct mddev *mddev, struct md_rdev *rdev) · line 10895

Quoted 10 lines
drivers/md/md.c +8 -1
 					rdev2->saved_raid_disk = role;
-				ret = remove_and_add_spares(mddev, rdev2, NULL);
+				/*
+				 * reconfig_mutex is held, so q->limits_lock
+				 * cannot be taken here.  The device is
+				 * already a member, its limits are stacked,
+				 * so add it without touching them.
+				 */
+				ret = remove_and_add_spares(mddev, rdev2,
+							    MDDEV_STACK_SKIP);

[Severity: High]
Does this code permanently bypass limit stacking for disks hot-added on cluster peer nodes?

In a clustered MD array, when a remote node adds a new disk, the local peer processes the NEWDISK message via md_add_new_disk() and add_bound_rdev(). Because personalities like raid1 and raid10 implement hot_remove_disk, add_bound_rdev() intentionally skips calling hot_add_disk(), meaning the new disk's limits are not stacked at that time.

When the remote node later activates the disk and sends a METADATA_UPDATED message, this check_sb_changes() code handles it. By passing MDDEV_STACK_SKIP, the personality's hot_add_disk() detects the flag and bypasses mddev_stack_new_rdev():

drivers/md/raid1.c:raid1_add_disk() {
    ...
    if (lim == MDDEV_STACK_SKIP)
        err = 0;
    else if (lim)
        err = mddev_stack_rdev_into(mddev, rdev, lim);
    ...
}

Since the disk is marked with raid_disk >= 0, the sync thread will ignore it, so it seems its limits will never be stacked. Can this leave the array with invalid queue limits, potentially causing the local block layer to submit incompatible I/O to the newly activated disk?

Also, the commit message states "The device is already a member, so its limits are stacked", which appears to be inaccurate for Candidate disks added remotely. I noticed that none of the follow-up patches in this series correct this missing limits update.

Quoted 3 lines
drivers/md/md.c +0 -0
 				pr_info("Activated spare: %pg\n",
 					rdev2->bdev);
 				/* wakeup mddev->thread here, so array could
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author
#6 lore raw

PATCH v2 3/8 md: pass a queue_limits through the rdev sysfs stores

In reply to Jack Wang

From: Jack Wang <[email protected]>

state_store() and slot_store() can add a leg back to the array, which stacks its limits, and q->limits_lock has to be taken before the array is locked and suspended.

Give the rdev sysfs store callback a struct queue_limits argument. rdev_attr_store() passes NULL, so there is no functional change; the user follows.

Assisted-by LLM
---
 drivers/md/md.c | 45 ++++++++++++++++++++++++++++++++-------------
 1 file changed, 32 insertions(+), 13 deletions(-)
drivers/md/md.c +32 -13
index e60dc2c7eb90..3067ea05ba27 100644
@@ -3033,7 +3033,13 @@ static int cmd_match(const char *cmd, const char *str)
 struct rdev_sysfs_entry {
 	struct attribute attr;
 	ssize_t (*show)(struct md_rdev *, char *);
-	ssize_t (*store)(struct md_rdev *, const char *, size_t);
+	/*
+	 * @lim: a queue limits update the caller owns, or NULL.  Stores that
+	 * can add a leg to the array must stack into it rather than take
+	 * q->limits_lock themselves, see md_start_sync().
+	 */
+	ssize_t (*store)(struct md_rdev *rdev, const char *page, size_t len,
+			 struct queue_limits *lim);
 };
 
 static ssize_t
@@ -3079,7 +3085,8 @@ state_show(struct md_rdev *rdev, char *page)
 }
 
 static ssize_t
-state_store(struct md_rdev *rdev, const char *buf, size_t len)
+state_store(struct md_rdev *rdev, const char *buf, size_t len,
+	    struct queue_limits *lim)
 {
 	/* can write
 	 *  faulty  - simulates an error
@@ -3257,7 +3264,8 @@ errors_show(struct md_rdev *rdev, char *page)
 }
 
 static ssize_t
-errors_store(struct md_rdev *rdev, const char *buf, size_t len)
+errors_store(struct md_rdev *rdev, const char *buf, size_t len,
+	     struct queue_limits *lim)
 {
 	unsigned int n;
 	int rv;
@@ -3283,7 +3291,8 @@ slot_show(struct md_rdev *rdev, char *page)
 }
 
 static ssize_t
-slot_store(struct md_rdev *rdev, const char *buf, size_t len)
+slot_store(struct md_rdev *rdev, const char *buf, size_t len,
+	   struct queue_limits *lim)
 {
 	int slot;
 	int err;
@@ -3378,7 +3387,8 @@ offset_show(struct md_rdev *rdev, char *page)
 }
 
 static ssize_t
-offset_store(struct md_rdev *rdev, const char *buf, size_t len)
+offset_store(struct md_rdev *rdev, const char *buf, size_t len,
+	     struct queue_limits *lim)
 {
 	unsigned long long offset;
 	if (kstrtoull(buf, 10, &offset) < 0)
@@ -3404,7 +3414,8 @@ static ssize_t new_offset_show(struct md_rdev *rdev, char *page)
 }
 
 static ssize_t new_offset_store(struct md_rdev *rdev,
-				const char *buf, size_t len)
+				const char *buf, size_t len,
+				struct queue_limits *lim)
 {
 	unsigned long long new_offset;
 	struct mddev *mddev = rdev->mddev;
@@ -3511,7 +3522,8 @@ static int strict_blocks_to_sectors(const char *buf, sector_t *sectors)
 }
 
 static ssize_t
-rdev_size_store(struct md_rdev *rdev, const char *buf, size_t len)
+rdev_size_store(struct md_rdev *rdev, const char *buf, size_t len,
+		struct queue_limits *lim)
 {
 	struct mddev *my_mddev = rdev->mddev;
 	sector_t oldsectors = rdev->sectors;
@@ -3573,7 +3585,8 @@ static ssize_t recovery_start_show(struct md_rdev *rdev, char *page)
 	return sprintf(page, "%llu\n", recovery_start);
 }
 
-static ssize_t recovery_start_store(struct md_rdev *rdev, const char *buf, size_t len)
+static ssize_t recovery_start_store(struct md_rdev *rdev, const char *buf, size_t len,
+				    struct queue_limits *lim)
 {
 	unsigned long long recovery_start;
 
@@ -3612,7 +3625,9 @@ static ssize_t bb_show(struct md_rdev *rdev, char *page)
 {
 	return badblocks_show(&rdev->badblocks, page, 0);
 }
-static ssize_t bb_store(struct md_rdev *rdev, const char *page, size_t len)
+
+static ssize_t bb_store(struct md_rdev *rdev, const char *page, size_t len,
+			struct queue_limits *lim)
 {
 	int rv = badblocks_store(&rdev->badblocks, page, len, 0);
 	/* Maybe that ack was all we needed */
@@ -3627,7 +3642,9 @@ static ssize_t ubb_show(struct md_rdev *rdev, char *page)
 {
 	return badblocks_show(&rdev->badblocks, page, 1);
 }
-static ssize_t ubb_store(struct md_rdev *rdev, const char *page, size_t len)
+
+static ssize_t ubb_store(struct md_rdev *rdev, const char *page, size_t len,
+			 struct queue_limits *lim)
 {
 	return badblocks_store(&rdev->badblocks, page, len, 1);
 }
@@ -3641,7 +3658,8 @@ ppl_sector_show(struct md_rdev *rdev, char *page)
 }
 
 static ssize_t
-ppl_sector_store(struct md_rdev *rdev, const char *buf, size_t len)
+ppl_sector_store(struct md_rdev *rdev, const char *buf, size_t len,
+		 struct queue_limits *lim)
 {
 	unsigned long long sector;
 
@@ -3680,7 +3698,8 @@ ppl_size_show(struct md_rdev *rdev, char *page)
 }
 
 static ssize_t
-ppl_size_store(struct md_rdev *rdev, const char *buf, size_t len)
+ppl_size_store(struct md_rdev *rdev, const char *buf, size_t len,
+	       struct queue_limits *lim)
 {
 	unsigned int size;
 
@@ -3766,7 +3785,7 @@ rdev_attr_store(struct kobject *kobj, struct attribute *attr,
 		if (rdev->mddev == NULL)
 			rv = -ENODEV;
 		else
-			rv = entry->store(rdev, page, length);
+			rv = entry->store(rdev, page, length, NULL);
 		suspend ? mddev_unlock_and_resume(mddev) : mddev_unlock(mddev);
 	}
 
Signature · 1 line
2.43.0
author
#7 lore raw

PATCH v2 4/8 md: defer the io_opt update out of the sync thread

In reply to Jack Wang

From: Jack Wang <[email protected]>

mddev_update_io_opt() runs from end_reshape() in the sync thread, and md_reap_sync_thread() waits for that thread with reconfig_mutex held. Taking q->limits_lock there hangs a finishing reshape whenever the lock's holder waits for I/O that only md_check_recovery() can let complete, and no ordering avoids it: the sync thread is what lets that I/O finish.

Hand the update to a work item, which holds neither reconfig_mutex nor the suspend and so takes q->limits_lock in the order the rest of md uses, before suspending. __md_stop() flushes it, as it suspends the array.

Also give the function a queue_limits argument, so a caller that already owns an update has it changed in place; the users of that path follow.

Assisted-by LLM
---
 drivers/md/md.c     | 49 ++++++++++++++++++++++++++++++++++++++-------
 drivers/md/md.h     |  7 ++++++-
 drivers/md/raid10.c |  2 +-
 drivers/md/raid5.c  |  2 +-
 4 files changed, 50 insertions(+), 10 deletions(-)
drivers/md/md.c +42 -7
index 3067ea05ba27..87e17ba86d93 100644
@@ -671,6 +671,7 @@ void mddev_put(struct mddev *mddev)
 
 static void md_safemode_timeout(struct timer_list *t);
 static void md_start_sync(struct work_struct *ws);
+static void md_io_opt_work(struct work_struct *ws);
 
 static void active_io_release(struct percpu_ref *ref)
 {
@@ -794,6 +795,7 @@ int mddev_init(struct mddev *mddev)
 	mddev->level = LEVEL_NONE;
 
 	INIT_WORK(&mddev->sync_work, md_start_sync);
+	INIT_WORK(&mddev->io_opt_work, md_io_opt_work);
 	INIT_WORK(&mddev->del_work, mddev_delayed_delete);
 
 	return 0;
@@ -6330,20 +6332,51 @@ int mddev_stack_rdev_into(struct mddev *mddev, struct md_rdev *rdev,
 EXPORT_SYMBOL_GPL(mddev_stack_rdev_into);
 
 /* update the optimal I/O size after a reshape */
-void mddev_update_io_opt(struct mddev *mddev, unsigned int nr_stripes)
+static void md_io_opt_work(struct work_struct *ws)
 {
+	struct mddev *mddev = container_of(ws, struct mddev, io_opt_work);
+	struct request_queue *q = mddev->gendisk->queue;
 	struct queue_limits lim;
 
+	/*
+	 * Nothing is held here, so take q->limits_lock in the order the rest
+	 * of md uses: before the suspend, see md_start_sync().
+	 */
+	lim = queue_limits_start_update(q);
+	if (mddev_suspend(mddev, false) < 0) {
+		queue_limits_cancel_update(q);
+		return;
+	}
+	lim.io_opt = lim.io_min * READ_ONCE(mddev->io_opt_nr_stripes);
+	if (queue_limits_commit_update(q, &lim))
+		pr_err("%s: could not apply queue limits\n", mdname(mddev));
+	mddev_resume(mddev);
+}
+
+void mddev_update_io_opt(struct mddev *mddev, unsigned int nr_stripes,
+			 struct queue_limits *lim)
+{
 	if (mddev_is_dm(mddev))
 		return;
 
-	/* don't bother updating io_opt if we can't suspend the array */
-	if (mddev_suspend(mddev, false) < 0)
+	/*
+	 * With an update owned by the caller just change it in place; it is
+	 * committed, and the array resumed, by whoever started it.  Taking
+	 * q->limits_lock here would nest it inside reconfig_mutex and the
+	 * suspend, which deadlocks, see md_start_sync().
+	 */
+	if (lim) {
+		lim->io_opt = lim->io_min * nr_stripes;
 		return;
-	lim = queue_limits_start_update(mddev->gendisk->queue);
-	lim.io_opt = lim.io_min * nr_stripes;
-	queue_limits_commit_update(mddev->gendisk->queue, &lim);
-	mddev_resume(mddev);
+	}
+
+	/*
+	 * Called from the sync thread, which md_reap_sync_thread() waits for
+	 * with reconfig_mutex held, so q->limits_lock cannot be taken here
+	 * either.  Hand it to a work item that holds neither.
+	 */
+	WRITE_ONCE(mddev->io_opt_nr_stripes, nr_stripes);
+	queue_work(md_misc_wq, &mddev->io_opt_work);
 }
 EXPORT_SYMBOL_GPL(mddev_update_io_opt);
 
@@ -7139,6 +7172,8 @@ static void __md_stop(struct mddev *mddev)
 {
 	struct md_personality *pers = mddev->pers;
 
+	/* the deferred io_opt update suspends the array, so let it finish */
+	flush_work(&mddev->io_opt_work);
 	mddev_detach(mddev);
 	md_bitmap_destroy(mddev);
 	spin_lock(&mddev->lock);
drivers/md/md.h +6 -1
index ebdd57677062..1b2e8720f0d1 100644
@@ -554,6 +554,10 @@ struct mddev {
 	/* used for register new sync thread */
 	struct work_struct sync_work;
 
+	/* deferred io_opt update, see mddev_update_io_opt() */
+	struct work_struct	io_opt_work;
+	unsigned int		io_opt_nr_stripes;
+
 	/* "lock" protects:
 	 *   flush_bio transition from NULL to !NULL
 	 *   rdev superblocks, events
@@ -1056,7 +1060,8 @@ int mddev_stack_rdev_into(struct mddev *mddev, struct md_rdev *rdev,
  * is added with the array's current limits.
  */
 #define MDDEV_STACK_SKIP	((struct queue_limits *)ERR_PTR(-EAGAIN))
-void mddev_update_io_opt(struct mddev *mddev, unsigned int nr_stripes);
+void mddev_update_io_opt(struct mddev *mddev, unsigned int nr_stripes,
+			 struct queue_limits *lim);
 
 extern const struct block_device_operations md_fops;
 
drivers/md/raid10.c +1 -1
index 222bd7badcff..5580ca77ef1e 100644
@@ -4932,7 +4932,7 @@ static void end_reshape(struct r10conf *conf)
 	conf->reshape_safe = MaxSector;
 	spin_unlock_irq(&conf->device_lock);
 
-	mddev_update_io_opt(conf->mddev, raid10_nr_stripes(conf));
+	mddev_update_io_opt(conf->mddev, raid10_nr_stripes(conf), NULL);
 	conf->fullsync = 0;
 }
 
drivers/md/raid5.c +1 -1
index 0ec555ada64a..3faa2a94c03b 100644
@@ -8800,7 +8800,7 @@ static void end_reshape(struct r5conf *conf)
 		wake_up(&conf->wait_for_reshape);
 
 		mddev_update_io_opt(conf->mddev,
-			conf->raid_disks - conf->max_degraded);
+			conf->raid_disks - conf->max_degraded, NULL);
 	}
 }
 
Signature · 1 line
2.43.0
#8 lore raw

Re: [PATCH v2 4/8] md: defer the io_opt update out of the sync thread

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] ABBA/4-thread deadlock in __md_stop() when synchronously flushing io_opt_work while holding…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] ABBA/4-thread deadlock in __md_stop() when synchronously flushing io_opt_work while holding reconfig_mutex. --

commit d238224db360133630dc01a16a121d6c63417309
Author: Jack Wang <[email protected]>

md: defer the io_opt update out of the sync thread

This patch defers the mddev_update_io_opt() call from the sync thread into a work item to avoid hanging a finishing reshape when taking q->limits_lock. The __md_stop() function is updated to flush this work item during array suspension.

Quoted 4 lines
drivers/md/md.c +0 -0
index 3067ea05ba276..87e17ba86d93a 100644

[ ... ]

drivers/md/md.c static void __md_stop(struct mddev *mddev) · line 7176

Quoted 6 lines
drivers/md/md.c +2 -0
@@ -7139,6 +7172,8 @@ static void __md_stop(struct mddev *mddev)
 {
 	struct md_personality *pers = mddev->pers;
 
+	/* the deferred io_opt update suspends the array, so let it finish */
+	flush_work(&mddev->io_opt_work);

[Severity: High]
Can this flush_work() call lead to a deadlock when the array is stopped while I/O is active?

The array stop sequence holds reconfig_mutex while calling __md_stop(), which blocks here waiting for md_io_opt_work() to complete.

Meanwhile, md_io_opt_work() calls mddev_suspend(), which blocks indefinitely waiting for the active_io refcount to drop to zero:

drivers/md/md.c:md_io_opt_work() {
    ...
	lim = queue_limits_start_update(q);
	if (mddev_suspend(mddev, false) < 0) {
    ...
}

However, a concurrent write I/O can increment active_io and then block in md_write_start() waiting for the MD management thread to clear MD_SB_CHANGE_PENDING:

drivers/md/md.c:md_write_start() {
    ...
	wait_event(mddev->sb_wait,
		   !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
    ...
}

The MD management thread cannot clear this flag because it wakes up to update the superblock but fails to acquire reconfig_mutex:

drivers/md/md.c:md_check_recovery() {
    ...
	if (mddev_trylock(mddev)) {
    ...
}

Since the array stop sequence holds reconfig_mutex, this creates a 4-thread circular dependency:

1. array stop thread waits for md_io_opt_work() to complete
2. md_io_opt_work() thread waits for active_io to reach zero
3. write I/O holding active_io waits for MD thread to clear MD_SB_CHANGE_PENDING
4. MD thread waits for array stop thread to release reconfig_mutex

Does the flush_work() call need to be moved outside the section holding reconfig_mutex, or could the workqueue be drained earlier?

Quoted 3 lines
drivers/md/md.c +0 -0
 	mddev_detach(mddev);
 	md_bitmap_destroy(mddev);
 	spin_lock(&mddev->lock);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author
#9 lore raw

PATCH v2 5/8 md: take q->limits_lock before locking and suspending the array

In reply to Jack Wang

From: Jack Wang <[email protected]>

Writing a queue limits attribute while a spare is re-added deadlocks the array:

udev-worker queue_attr_store() holds q->limits_lock, waits in
blk_mq_freeze_queue() for q_usage_counter to drain
fio holds a q_usage_counter reference, parked in
md_handle_request()'s is_suspended() loop
mdadm suspended the array, waits for reconfig_mutex
md_start_sync holds reconfig_mutex, waits for q->limits_lock

Blocking on q->limits_lock while holding reconfig_mutex, or with the array suspended, is waiting for normal I/O, which mddev_suspend() already warns about with lockdep_assert_not_held(). So q->limits_lock has to nest outside both.

Take the update before the array is locked and suspended, and pass it down so the personality stacks into it:

- md_start_sync(), at both suspend points
- md_ioctl() for ADD_NEW_DISK and HOT_REMOVE_DISK
- rdev_attr_store(), for slot and for state "remove"/"re-add"
- raid5 skip_copy_store(), which took the lock while suspended

They are converted together because a mix of the two orders is an ABBA. All of them commit while the array is still quiesced.

Two callers still take the lock inside reconfig_mutex with the array
suspended: ->start_reshape() from action_store(), which suspends before flushing sync_work so the update cannot be held across it, and raid*_run() from level_store(), which a later patch converts.

Verified with a raid1 of two ram devices, fio in flight and a loop writing queue/max_sectors_kb: 20 fail/remove/add cycles complete, where the same test wedges the array before the change.

Fixes c99f66e4084a ("block: fix queue freeze vs limits lock order in sysfs store methods")
Assisted-by LLM
---
 drivers/md/md-autodetect.c |   2 +-
 drivers/md/md.c            | 120 +++++++++++++++++++++++++++++++------
 drivers/md/md.h            |   3 +-
 drivers/md/raid5.c         |  31 +++++++---
 4 files changed, 128 insertions(+), 28 deletions(-)
drivers/md/md-autodetect.c +1 -1
index 4b80165afd23..929513109657 100644
@@ -213,7 +213,7 @@ static void __init md_setup_drive(struct md_setup_args *args)
 				(1 << MD_DISK_ACTIVE) | (1 << MD_DISK_SYNC);
 		}
 
-		md_add_new_disk(mddev, &dinfo);
+		md_add_new_disk(mddev, &dinfo, NULL);
 	}
 
 	if (!err)
drivers/md/md.c +103 -17

289 lines not on this page · raw message

drivers/md/md.h +2 -1
index 1b2e8720f0d1..7f4e3ea8b826 100644
@@ -1046,7 +1046,8 @@ struct mdu_disk_info_s;
 extern int mdp_major;
 void md_autostart_arrays(int part);
 int md_set_array_info(struct mddev *mddev, struct mdu_array_info_s *info);
-int md_add_new_disk(struct mddev *mddev, struct mdu_disk_info_s *info);
+int md_add_new_disk(struct mddev *mddev, struct mdu_disk_info_s *info,
+		    struct queue_limits *lim);
 int do_md_run(struct mddev *mddev);
 #define MDDEV_STACK_INTEGRITY	(1u << 0)
 int mddev_stack_rdev_limits(struct mddev *mddev, struct queue_limits *lim,
drivers/md/raid5.c +22 -9
index 3faa2a94c03b..22759c631c4d 100644
@@ -7288,6 +7288,9 @@ static ssize_t
 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
 {
 	struct r5conf *conf;
+	struct request_queue *q = NULL;
+	struct queue_limits lim;
+	struct queue_limits *limp = NULL;
 	unsigned long new;
 	int err;
 
@@ -7297,23 +7300,33 @@ raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
 		return -EINVAL;
 	new = !!new;
 
+	/* q->limits_lock nests outside both, see md_start_sync() */
+	if (!mddev_is_dm(mddev)) {
+		q = mddev->gendisk->queue;
+		lim = queue_limits_start_update(q);
+		limp = &lim;
+	}
+
 	err = mddev_suspend_and_lock(mddev);
-	if (err)
+	if (err) {
+		if (limp)
+			queue_limits_cancel_update(q);
 		return err;
+	}
 	conf = mddev->private;
 	if (!conf)
 		err = -ENODEV;
 	else if (new != conf->skip_copy) {
-		struct request_queue *q = mddev->gendisk->queue;
-		struct queue_limits lim = queue_limits_start_update(q);
-
 		conf->skip_copy = new;
-		if (new)
-			lim.features |= BLK_FEAT_STABLE_WRITES;
-		else
-			lim.features &= ~BLK_FEAT_STABLE_WRITES;
-		err = queue_limits_commit_update(q, &lim);
+		if (limp) {
+			if (new)
+				limp->features |= BLK_FEAT_STABLE_WRITES;
+			else
+				limp->features &= ~BLK_FEAT_STABLE_WRITES;
+		}
 	}
+	if (limp)
+		err = queue_limits_commit_update(q, limp) ?: err;
 	mddev_unlock_and_resume(mddev);
 	return err ?: len;
 }
Signature · 1 line
2.43.0
#10 lore raw

Re: [PATCH v2 5/8] md: take q->limits_lock before locking and suspending the array

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

New issues:
- [High] Missing rollback when queue_limits_commit_update() fails, leaving the array mutated with rejected and potentially dangerous block limits.

Pre-existing issues:
- [High] The patch leaves an ABBA deadlock unresolved in action_store() when triggering ACTION_RESHAPE.
- [High] Writing 'remove' to a spare disk's state attribute in a degraded array incorrectly hot-adds the disk to the array instead of removing it. --

commit 7025b63183a90cd4ea9de7b41e69a4702b7c8d13
Author: Jack Wang <[email protected]>

md: take q->limits_lock before locking and suspending the array

This commit modifies block limit handling during MD array reconfigurations to acquire q->limits_lock before locking and suspending the array. This fixes an ABBA deadlock between the limits lock, reconfig_mutex, and the array suspend state.

Quoted 4 lines

Two callers still take the lock inside reconfig_mutex with the array
suspended: ->start_reshape() from action_store(), which suspends before flushing sync_work so the update cannot be held across it, and raid*_run() from level_store(), which a later patch converts.

[Severity: High]
This is a pre-existing issue, but by leaving the action_store() path unresolved here, does this leave the system vulnerable to the same ABBA deadlock if a user writes 'reshape' to sync_action? Concurrent I/O could still park in the block layer, and a sysfs write to queue limits could still wait in blk_mq_freeze_queue for q_usage_counter to drain while mddev_stack_new_rdev attempts to acquire q->limits_lock.

[ ... ]

Quoted 4 lines
drivers/md/md.c +0 -0
index 87e17ba86d93a..0668a048db716 100644

[ ... ]

drivers/md/md.c state_store(struct md_rdev *rdev, const char *buf, size_t len, · line 3125

Quoted 9 lines
drivers/md/md.c +1 -1
@@ -3119,7 +3119,7 @@ state_store(struct md_rdev *rdev, const char *buf, size_t len,
 	} else if (cmd_match(buf, "remove")) {
 		if (rdev->mddev->pers) {
 			clear_bit(Blocked, &rdev->flags);
-			remove_and_add_spares(rdev->mddev, rdev, NULL);
+			remove_and_add_spares(rdev->mddev, rdev, lim);
 		}
 		if (rdev->raid_disk >= 0)
 			err = -EBUSY;

[Severity: High]
This isn't a bug introduced by this patch, but if an admin tries to remove a spare from a degraded array by writing "remove" to the state attribute, could this unintentionally hot-add the spare instead? Looking at remove_and_add_spares(), rdev_removeable() would skip spares because they have raid_disk < 0. Then rdev_addable() might return true, causing hot_add_disk() to be called and returning -EBUSY.

[ ... ]

Quoted 1 line
drivers/md/md.c +0 -0
@@ -3782,15 +3785,41 @@ rdev_attr_store(struct kobject *kobj, struct attribute *attr,

[ ... ]

Quoted 5 lines
drivers/md/md.c +0 -0
 	rv = suspend ? mddev_suspend_and_lock(mddev) : mddev_lock(mddev);
 	if (!rv) {
 		if (rdev->mddev == NULL)
 			rv = -ENODEV;
 		else

drivers/md/md.c rdev_attr_store(struct kobject *kobj, struct attribute *attr, · line 3815

Quoted 10 lines
drivers/md/md.c +9 -1
-			rv = entry->store(rdev, page, length, NULL);
+			rv = entry->store(rdev, page, length, limp);
+		/* apply the limits before the array takes I/O again */
+		if (limp) {
+			int err = queue_limits_commit_update(q, limp);
+
+			limp = NULL;
+			if (err && rv >= 0)
+				rv = err;
+		}

[Severity: High]
If queue_limits_commit_update() fails and rejects the stacked limits, the error is bubbled up, but is it possible that the array has already been mutated by entry->store() (such as structurally binding a new disk)? This might leave the disk actively bound to the array configuration with stale/rejected block limits.

[ ... ]

drivers/md/md.c static int md_ioctl(struct block_device *bdev, blk_mode_t mode, · line 8682

Quoted 7 lines
drivers/md/md.c +3 -0
@@ -8618,6 +8677,9 @@ static int md_ioctl(struct block_device *bdev, blk_mode_t mode,
 	    err != -EINVAL)
 		mddev->hold_active = 0;
 
+	if (limp)
+		err = queue_limits_commit_update(q, limp) ?: err;
+

[Severity: High]
Similar to the rdev_attr_store() path above, if the limit commit fails here, are the array mutations (such as ADD_NEW_DISK) reverted?

[ ... ]

Quoted 1 line
drivers/md/md.c +0 -0
@@ -10419,6 +10501,8 @@ static void md_start_sync(struct work_struct *ws)

[ ... ]

drivers/md/md.c static void md_start_sync(struct work_struct *ws) · line 10505

Quoted 5 lines
drivers/md/md.c +2 -0
 	 *     https://bugzilla.kernel.org/show_bug.cgi?id=218200
 	 * Therefore, use __mddev_resume(mddev, false).
 	 */
+	if (limp && queue_limits_commit_update(q, limp))
+		pr_err("%s: could not apply queue limits\n", mdname(mddev));

[Severity: High]
If the limit commit fails, this merely logs an error. Will any spares recently added via remove_and_add_spares() remain fully active with stale limits, potentially causing data corruption or crashing lower-level drivers?

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

PATCH v2 6/8 md: pass a queue_limits through ->run()

In reply to Jack Wang

From: Jack Wang <[email protected]>

raid*_run() -> queue_limits_set() takes q->limits_lock with reconfig_mutex held, the order the previous patches inverted. With lockdep on, creating an array and then adding a leg reports it:

-> #1 (&q->limits_lock): -> #0 (&mddev->reconfig_mutex):
queue_limits_set md_ioctl <- ADD_NEW_DISK
raid1_run
do_md_run
md_ioctl <- RUN_ARRAY

The earlier patch left this for level_store() alone; RUN_ARRAY reaches it too, so every array creation records the wrong order.

Give ->run() a queue_limits argument and take the update at the entry points that start an array: md_ioctl() for RUN_ARRAY, level_store(), autorun_devices(), md_setup_drive(), and array_state_store() for readonly, read_auto and active -- but only while mddev->pers is NULL, as with the array running those states go to md_set_readonly(), which waits in stop_sync_thread() for the work that takes the same lock.

dm-raid passes NULL: with no gendisk the personalities return before touching any limits.

Assisted-by LLM
---
 drivers/md/dm-raid.c       |   2 +-
 drivers/md/md-autodetect.c |  21 ++++++-
 drivers/md/md-linear.c     |   4 +-
 drivers/md/md.c            | 116 +++++++++++++++++++++++++++++++------
 drivers/md/md.h            |  11 +++-
 drivers/md/raid0.c         |  16 ++++-
 drivers/md/raid1.c         |  16 ++++-
 drivers/md/raid10.c        |  16 ++++-
 drivers/md/raid5.c         |  16 ++++-
 9 files changed, 182 insertions(+), 36 deletions(-)
drivers/md/dm-raid.c +1 -1
index 21a1922bee4f..d043a5c49608 100644
@@ -3258,7 +3258,7 @@ static int raid_ctr(struct dm_target *ti, unsigned int argc, char **argv)
 	/* Keep array frozen until resume. */
 	md_frozen_sync_thread(&rs->md);
 
-	r = md_run(&rs->md);
+	r = md_run(&rs->md, NULL);
 	rs->md.in_sync = 0; /* Assume already marked dirty */
 	if (r) {
 		ti->error = "Failed to run raid array";
drivers/md/md-autodetect.c +20 -1
index 929513109657..e15ae2fb58a2 100644
@@ -126,6 +126,9 @@ static void __init md_setup_drive(struct md_setup_args *args)
 	dev_t devices[MD_SB_DISKS + 1], mdev;
 	struct mdu_array_info_s ainfo = { };
 	struct mddev *mddev;
+	struct request_queue *q = NULL;
+	struct queue_limits lim;
+	struct queue_limits *limp = NULL;
 	int err = 0, i;
 	char name[16];
 
@@ -216,11 +219,27 @@ static void __init md_setup_drive(struct md_setup_args *args)
 		md_add_new_disk(mddev, &dinfo, NULL);
 	}
 
+	/*
+	 * do_md_run() restacks the array's limits, and q->limits_lock must
+	 * not nest inside reconfig_mutex, so start the update with the array
+	 * unlocked.  This is __init and the array is not reachable yet.
+	 */
+	if (!err && !mddev_is_dm(mddev)) {
+		mddev_unlock(mddev);
+		q = mddev->gendisk->queue;
+		lim = queue_limits_start_update(q);
+		limp = &lim;
+		mddev_lock_nointr(mddev);
+	}
+
 	if (!err)
-		err = do_md_run(mddev);
+		err = do_md_run(mddev, limp);
 	if (err)
 		pr_warn("md: starting %s failed\n", name);
 out_unlock:
+	/* apply the limits before the array takes I/O */
+	if (limp)
+		queue_limits_commit_update(q, limp);
 	mddev_unlock_and_resume(mddev);
 out_mddev_put:
 	mddev_put(mddev);
drivers/md/md-linear.c +2 -2
index da82c313d459..5438c23a7242 100644
@@ -178,7 +178,7 @@ static struct linear_conf *linear_conf(struct mddev *mddev, int raid_disks,
 	return ERR_PTR(ret);
 }
 
-static int linear_run(struct mddev *mddev)
+static int linear_run(struct mddev *mddev, struct queue_limits *lim)
 {
 	struct linear_conf *conf;
 	int ret;
@@ -186,7 +186,7 @@ static int linear_run(struct mddev *mddev)
 	if (md_check_no_bitmap(mddev))
 		return -EINVAL;
 
-	conf = linear_conf(mddev, mddev->raid_disks, NULL);
+	conf = linear_conf(mddev, mddev->raid_disks, lim);
 	if (IS_ERR(conf))
 		return PTR_ERR(conf);
 
drivers/md/md.c +99 -17

248 lines not on this page · raw message

drivers/md/md.h +8 -3
index 7f4e3ea8b826..73f6ef20f266 100644
@@ -760,7 +760,12 @@ struct md_personality
 	 * start up works that do NOT require md_thread. tasks that
 	 * requires md_thread should go into start()
 	 */
-	int (*run)(struct mddev *mddev);
+	/*
+	 * @lim: a queue limits update the caller owns, or NULL.  Non-NULL
+	 * means stack into it rather than take q->limits_lock, which has to
+	 * nest outside reconfig_mutex, see md_start_sync().
+	 */
+	int (*run)(struct mddev *mddev, struct queue_limits *lim);
 	/* start up works that require md threads */
 	int (*start)(struct mddev *mddev);
 	void (*free)(struct mddev *mddev, void *priv);
@@ -959,7 +964,7 @@ extern void mddev_destroy(struct mddev *mddev);
 void md_init_stacking_limits(struct queue_limits *lim);
 struct mddev *md_alloc(dev_t dev, char *name);
 void mddev_put(struct mddev *mddev);
-extern int md_run(struct mddev *mddev);
+extern int md_run(struct mddev *mddev, struct queue_limits *lim);
 extern int md_start(struct mddev *mddev);
 extern void md_stop(struct mddev *mddev);
 extern void md_stop_writes(struct mddev *mddev);
@@ -1048,7 +1053,7 @@ void md_autostart_arrays(int part);
 int md_set_array_info(struct mddev *mddev, struct mdu_array_info_s *info);
 int md_add_new_disk(struct mddev *mddev, struct mdu_disk_info_s *info,
 		    struct queue_limits *lim);
-int do_md_run(struct mddev *mddev);
+int do_md_run(struct mddev *mddev, struct queue_limits *lim);
 #define MDDEV_STACK_INTEGRITY	(1u << 0)
 int mddev_stack_rdev_limits(struct mddev *mddev, struct queue_limits *lim,
 		unsigned int flags);
drivers/md/raid0.c +13 -3
index 35e103f0c2c3..59141e4299a8 100644
@@ -379,7 +379,8 @@ static void raid0_free(struct mddev *mddev, void *priv)
 	kfree(conf);
 }
 
-static int raid0_set_limits(struct mddev *mddev)
+static int raid0_set_limits(struct mddev *mddev,
+			    struct queue_limits *caller_lim)
 {
 	struct queue_limits lim;
 	int err;
@@ -398,10 +399,19 @@ static int raid0_set_limits(struct mddev *mddev)
 	err = mddev_stack_rdev_limits(mddev, &lim, MDDEV_STACK_INTEGRITY);
 	if (err)
 		return err;
+	/*
+	 * The caller owns an update and commits it itself; taking
+	 * q->limits_lock here would take it a second time.
+	 */
+	if (caller_lim) {
+		*caller_lim = lim;
+		return 0;
+	}
+
 	return queue_limits_set(mddev->gendisk->queue, &lim);
 }
 
-static int raid0_run(struct mddev *mddev)
+static int raid0_run(struct mddev *mddev, struct queue_limits *lim)
 {
 	struct r0conf *conf;
 	int ret;
@@ -414,7 +424,7 @@ static int raid0_run(struct mddev *mddev)
 		return -EINVAL;
 
 	if (!mddev_is_dm(mddev)) {
-		ret = raid0_set_limits(mddev);
+		ret = raid0_set_limits(mddev, lim);
 		if (ret)
 			return ret;
 	}
drivers/md/raid1.c +13 -3
index 78effcac138d..6713a53fd460 100644
@@ -3170,7 +3170,8 @@ static struct r1conf *setup_conf(struct mddev *mddev)
 	return ERR_PTR(err);
 }
 
-static int raid1_set_limits(struct mddev *mddev)
+static int raid1_set_limits(struct mddev *mddev,
+			    struct queue_limits *caller_lim)
 {
 	struct queue_limits lim;
 	int err;
@@ -3185,10 +3186,19 @@ static int raid1_set_limits(struct mddev *mddev)
 	err = mddev_stack_rdev_limits(mddev, &lim, MDDEV_STACK_INTEGRITY);
 	if (err)
 		return err;
+	/*
+	 * The caller owns an update and commits it itself; taking
+	 * q->limits_lock here would take it a second time.
+	 */
+	if (caller_lim) {
+		*caller_lim = lim;
+		return 0;
+	}
+
 	return queue_limits_set(mddev->gendisk->queue, &lim);
 }
 
-static int raid1_run(struct mddev *mddev)
+static int raid1_run(struct mddev *mddev, struct queue_limits *lim)
 {
 	struct r1conf *conf;
 	int i;
@@ -3219,7 +3229,7 @@ static int raid1_run(struct mddev *mddev)
 		return PTR_ERR(conf);
 
 	if (!mddev_is_dm(mddev)) {
-		ret = raid1_set_limits(mddev);
+		ret = raid1_set_limits(mddev, lim);
 		if (ret) {
 			md_unregister_thread(mddev, &conf->thread);
 			if (!mddev->private)
drivers/md/raid10.c +13 -3
index 5580ca77ef1e..16143db6085b 100644
@@ -3930,7 +3930,8 @@ static unsigned int raid10_nr_stripes(struct r10conf *conf)
 	return raid_disks / conf->geo.near_copies;
 }
 
-static int raid10_set_queue_limits(struct mddev *mddev)
+static int raid10_set_queue_limits(struct mddev *mddev,
+				   struct queue_limits *caller_lim)
 {
 	struct r10conf *conf = mddev->private;
 	struct queue_limits lim;
@@ -3948,10 +3949,19 @@ static int raid10_set_queue_limits(struct mddev *mddev)
 	err = mddev_stack_rdev_limits(mddev, &lim, MDDEV_STACK_INTEGRITY);
 	if (err)
 		return err;
+	/*
+	 * The caller owns an update and commits it itself; taking
+	 * q->limits_lock here would take it a second time.
+	 */
+	if (caller_lim) {
+		*caller_lim = lim;
+		return 0;
+	}
+
 	return queue_limits_set(mddev->gendisk->queue, &lim);
 }
 
-static int raid10_run(struct mddev *mddev)
+static int raid10_run(struct mddev *mddev, struct queue_limits *lim)
 {
 	struct r10conf *conf;
 	int i, disk_idx;
@@ -4020,7 +4030,7 @@ static int raid10_run(struct mddev *mddev)
 	}
 
 	if (!mddev_is_dm(conf->mddev)) {
-		int err = raid10_set_queue_limits(mddev);
+		int err = raid10_set_queue_limits(mddev, lim);
 
 		if (err) {
 			ret = err;
drivers/md/raid5.c +13 -3
index 22759c631c4d..28bd81de86c1 100644
@@ -7944,7 +7944,8 @@ static int raid5_create_ctx_pool(struct r5conf *conf)
 	return conf->ctx_pool ? 0 : -ENOMEM;
 }
 
-static int raid5_set_limits(struct mddev *mddev)
+static int raid5_set_limits(struct mddev *mddev,
+			    struct queue_limits *caller_lim)
 {
 	struct r5conf *conf = mddev->private;
 	struct queue_limits lim;
@@ -7996,10 +7997,19 @@ static int raid5_set_limits(struct mddev *mddev)
 	/* No restrictions on the number of segments in the request */
 	lim.max_segments = USHRT_MAX;
 
+	/*
+	 * The caller owns an update and commits it itself; taking
+	 * q->limits_lock here would take it a second time.
+	 */
+	if (caller_lim) {
+		*caller_lim = lim;
+		return 0;
+	}
+
 	return queue_limits_set(mddev->gendisk->queue, &lim);
 }
 
-static int raid5_run(struct mddev *mddev)
+static int raid5_run(struct mddev *mddev, struct queue_limits *lim)
 {
 	struct r5conf *conf;
 	int dirty_parity_disks = 0;
@@ -8259,7 +8269,7 @@ static int raid5_run(struct mddev *mddev)
 	md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
 
 	if (!mddev_is_dm(mddev)) {
-		ret = raid5_set_limits(mddev);
+		ret = raid5_set_limits(mddev, lim);
 		if (ret)
 			goto abort;
 	}
Signature · 1 line
2.43.0
#12 lore raw

Re: [PATCH v2 6/8] md: pass a queue_limits through ->run()

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Array starts successfully but fails to apply its queue limits if queue_limits_commit_update()…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Array starts successfully but fails to apply its queue limits if queue_limits_commit_update() returns an error, leaving a running array with inconsistent block limits. --

commit a296ef119cee93cfa123eae52144130e9c5df88f
Author: Jack Wang <[email protected]>

md: pass a queue_limits through ->run()

This commit delegates the application of queue limits to the top-level callers that start the array. This is done to prevent lock inversion between the reconfig_mutex and q->limits_lock. Personalities now pass the limits up to be committed by the caller.

Quoted 3 lines
drivers/md/md.c +0 -0

[ ... ]

drivers/md/md.c array_state_store(struct mddev *mddev, const char *buf, size_t len) · line 4886

Quoted 8 lines
drivers/md/md.c +3 -0
@@ -4826,6 +4880,9 @@ array_state_store(struct mddev *mddev, const char *buf, size_t len)
 			mddev->hold_active = 0;
 		sysfs_notify_dirent_safe(mddev->sysfs_state);
 	}
+	/* apply the limits before the array takes I/O */
+	if (limp)
+		err = queue_limits_commit_update(q, limp) ?: err;
 	mddev_unlock(mddev);

[Severity: High]
If queue_limits_commit_update() fails here, does it leave the array in an inconsistent state?

The limits are committed after do_md_run() has already activated the array. If the commit fails, an error is returned to userspace, but the running array isn't stopped or rolled back. Can this lead to block layer warnings, driver crashes, or data corruption if I/O requests exceed the capabilities of the underlying devices?

[ ... ]

drivers/md/md.c static int md_ioctl(struct block_device *bdev, blk_mode_t mode, · line 8746

Quoted 7 lines
drivers/md/md.c +1 -1
@@ -8660,7 +8742,7 @@ static int md_ioctl(struct block_device *bdev, blk_mode_t mode,
 		goto unlock;
 
 	case RUN_ARRAY:
-		err = do_md_run(mddev);
+		err = do_md_run(mddev, limp);
 		goto unlock;

[Severity: High]
Similarly, when do_md_run() successfully starts the array here, the limits are committed later in the function (under the unlock label). If that commit fails, the array will remain active with unvalidated or default limits.

Should there be a rollback mechanism (e.g., calling do_md_stop()) if the limits cannot be successfully applied after the array is started?

Quoted 3 lines
drivers/md/raid1.c +0 -0

[ ... ]

Quoted 5 lines
drivers/md/raid1.c +1 -0
@@ -3185,10 +3186,19 @@ static int raid1_set_limits(struct mddev *mddev)
 	err = mddev_stack_rdev_limits(mddev, &lim, MDDEV_STACK_INTEGRITY);
 	if (err)
 		return err;
+	/*

drivers/md/raid1.c static int raid1_set_limits(struct mddev *mddev) · line 3199

Quoted 10 lines
drivers/md/raid1.c +8 -0
+	 * The caller owns an update and commits it itself; taking
+	 * q->limits_lock here would take it a second time.
+	 */
+	if (caller_lim) {
+		*caller_lim = lim;
+		return 0;
+	}
+
 	return queue_limits_set(mddev->gendisk->queue, &lim);
 }

[Severity: High]
By unconditionally returning 0 when caller_lim is provided, are we deferring all limit validation until after the array is fully activated?

Because the personality's ->run() method copies the limits but does not validate them with the block layer, the first point of failure becomes queue_limits_commit_update() in the caller. Since the caller currently lacks rollback handling, this guarantees the array is left running with invalid limits if the configuration is rejected by blk_validate_limits().

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

Re: [PATCH v2 6/8] md: pass a queue_limits through ->run()

In reply to Jack Wang
Quoted 30 lines
drivers/md/raid0.c +11 -1
index 35e103f0c2c3..59141e4299a8 100644
@@ -379,7 +379,8 @@ static void raid0_free(struct mddev *mddev, void *priv)
  	kfree(conf);
  }
 
-static int raid0_set_limits(struct mddev *mddev)
+static int raid0_set_limits(struct mddev *mddev,
+			    struct queue_limits *caller_lim)
  {
  	struct queue_limits lim;
  	int err;
@@ -398,10 +399,19 @@ static int raid0_set_limits(struct mddev *mddev)
  	err = mddev_stack_rdev_limits(mddev, &lim, MDDEV_STACK_INTEGRITY);
  	if (err)
  		return err;
+	/*
+	 * The caller owns an update and commits it itself; taking
+	 * q->limits_lock here would take it a second time.
+	 */
+	if (caller_lim) {
+		*caller_lim = lim;
+		return 0;
+	}
+
  	return queue_limits_set(mddev->gendisk->queue, &lim);
  }
 

[...]

Quoted 22 lines
drivers/md/raid0.c +11 -1
-static int raid1_set_limits(struct mddev *mddev)
+static int raid1_set_limits(struct mddev *mddev,
+			    struct queue_limits *caller_lim)
  {
  	struct queue_limits lim;
  	int err;
@@ -3185,10 +3186,19 @@ static int raid1_set_limits(struct mddev *mddev)
  	err = mddev_stack_rdev_limits(mddev, &lim, MDDEV_STACK_INTEGRITY);
  	if (err)
  		return err;
+	/*
+	 * The caller owns an update and commits it itself; taking
+	 * q->limits_lock here would take it a second time.
+	 */
+	if (caller_lim) {
+		*caller_lim = lim;
+		return 0;
+	}
+
  	return queue_limits_set(mddev->gendisk->queue, &lim);
  }
 

[...]

Quoted 23 lines
drivers/md/raid0.c +11 -1
-static int raid10_set_queue_limits(struct mddev *mddev)
+static int raid10_set_queue_limits(struct mddev *mddev,
+				   struct queue_limits *caller_lim)
  {
  	struct r10conf *conf = mddev->private;
  	struct queue_limits lim;
@@ -3948,10 +3949,19 @@ static int raid10_set_queue_limits(struct mddev *mddev)
  	err = mddev_stack_rdev_limits(mddev, &lim, MDDEV_STACK_INTEGRITY);
  	if (err)
  		return err;
+	/*
+	 * The caller owns an update and commits it itself; taking
+	 * q->limits_lock here would take it a second time.
+	 */
+	if (caller_lim) {
+		*caller_lim = lim;
+		return 0;
+	}
+
  	return queue_limits_set(mddev->gendisk->queue, &lim);
  }
 

[...]

Quoted 20 lines
drivers/md/raid5.c +4 -1
index 22759c631c4d..28bd81de86c1 100644
@@ -7944,7 +7944,8 @@ static int raid5_create_ctx_pool(struct r5conf *conf)
  	return conf->ctx_pool ? 0 : -ENOMEM;
  }
 
-static int raid5_set_limits(struct mddev *mddev)
+static int raid5_set_limits(struct mddev *mddev,
+			    struct queue_limits *caller_lim)
  {
  	struct r5conf *conf = mddev->private;
  	struct queue_limits lim;
@@ -7996,10 +7997,19 @@ static int raid5_set_limits(struct mddev *mddev)
  	/* No restrictions on the number of segments in the request */
  	lim.max_segments = USHRT_MAX;
 
+	/*
+	 * The caller owns an update and commits it itself; taking

drivers/md/raid5.c static int raid5_set_limits(struct mddev *mddev) · line 8011

Quoted 10 lines
drivers/md/raid5.c +7 -0
+	 * q->limits_lock here would take it a second time.
+	 */
+	if (caller_lim) {
+		*caller_lim = lim;
+		return 0;
+	}
+
  	return queue_limits_set(mddev->gendisk->queue, &lim);
  }
 

[...]
I'd propose the same changes as I suggested in patch 1/8, for raid5_set_limits(), raid10_set_queue_limits(), raid1_set_limits() and raid0_set_limits().

In particular, I think these functions should always operate on a caller-provided struct queue_limits and only prepare/update the limits, without deciding whether to commit them. The caller should own the limits update and commit it as appropriate for its locking context.

Thanks,
--Nilay

author
#14 lore raw

PATCH v2 7/8 md: open new legs before locking the array

In reply to Jack Wang

From: Jack Wang <[email protected]>

Opening a leg takes disk->open_mutex, and the scsi disk probe path nests q->limits_lock inside it (sd_open() -> sd_revalidate_disk()). md opens legs under reconfig_mutex, which this series makes q->limits_lock nest outside, closing a cycle. Booting with lockdep on an md root reports it during assembly:

-> #2 (&q->limits_lock): sd_revalidate_disk / sd_open
-> #1 (&disk->open_mutex): md_import_device
md_add_new_disk
md_ioctl <- ADD_NEW_DISK
-> #0 (&mddev->reconfig_mutex): md_ioctl <- RUN_ARRAY

Move every open out from under the lock. md_import_new_disk() mirrors md_add_new_disk()'s branch selection so all three of its branches take a pre-opened leg, and hot_add_disk(), new_dev_store() and md_setup_drive() open before they lock as well.

The mddev fields the open depends on are read without reconfig_mutex, so each caller rechecks them once the array is locked and rejects the add with -EBUSY if the branch or the superblock format would have changed.

md_autostart_arrays() needs no change: it opens under detected_devices_mutex.

Assisted-by LLM
---
 drivers/md/md-autodetect.c |  17 ++-
 drivers/md/md.c            | 238 ++++++++++++++++++++++++++-----------
 drivers/md/md.h            |  21 +++-
 3 files changed, 203 insertions(+), 73 deletions(-)
drivers/md/md-autodetect.c +16 -1
index e15ae2fb58a2..e592577356ad 100644
@@ -208,6 +208,7 @@ static void __init md_setup_drive(struct md_setup_args *args)
 			.major	= MAJOR(devices[i]),
 			.minor	= MINOR(devices[i]),
 		};
+		struct md_new_disk nd;
 
 		if (args->level != LEVEL_NONE) {
 			dinfo.number = i;
@@ -216,7 +217,21 @@ static void __init md_setup_drive(struct md_setup_args *args)
 				(1 << MD_DISK_ACTIVE) | (1 << MD_DISK_SYNC);
 		}
 
-		md_add_new_disk(mddev, &dinfo, NULL);
+		/*
+		 * Opening a leg takes disk->open_mutex, which must not nest
+		 * inside reconfig_mutex, see md_import_new_disk().  Drop the
+		 * array lock around it; this is __init and the array is not
+		 * reachable yet, so nothing else can touch it in between.
+		 */
+		mddev_unlock(mddev);
+		if (md_import_new_disk(mddev, &dinfo, &nd)) {
+			mddev_lock_nointr(mddev);
+			continue;
+		}
+		mddev_lock_nointr(mddev);
+
+		md_add_new_disk(mddev, &dinfo, &nd, NULL);
+		md_put_new_disk(&nd);
 	}
 
 	/*
drivers/md/md.c +167 -71

346 lines not on this page · raw message

drivers/md/md.h +20 -1
index 73f6ef20f266..73a27d83d65a 100644
@@ -1051,8 +1051,27 @@ struct mdu_disk_info_s;
 extern int mdp_major;
 void md_autostart_arrays(int part);
 int md_set_array_info(struct mddev *mddev, struct mdu_array_info_s *info);
+/*
+ * A leg opened before the array was locked, with the mddev fields that
+ * selected the branch and the superblock format.  Opening takes
+ * disk->open_mutex, which must not nest inside reconfig_mutex; the fields
+ * are read unlocked and md_add_new_disk() rechecks them.
+ */
+struct md_new_disk {
+	struct md_rdev *rdev;
+	bool stacks;		/* the add can reach ->hot_add_disk() */
+	bool have_pers;
+	bool have_raid_disks;
+	int persistent;
+	int major_version;
+	int minor_version;
+};
+
+int md_import_new_disk(struct mddev *mddev, struct mdu_disk_info_s *info,
+		       struct md_new_disk *nd);
+void md_put_new_disk(struct md_new_disk *nd);
 int md_add_new_disk(struct mddev *mddev, struct mdu_disk_info_s *info,
-		    struct queue_limits *lim);
+		    struct md_new_disk *nd, struct queue_limits *lim);
 int do_md_run(struct mddev *mddev, struct queue_limits *lim);
 #define MDDEV_STACK_INTEGRITY	(1u << 0)
 int mddev_stack_rdev_limits(struct mddev *mddev, struct queue_limits *lim,
Signature · 1 line
2.43.0
#15 lore raw

Re: [PATCH v2 7/8] md: open new legs before locking the array

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] The patch leaves export_rdev() calls inside the mddev->reconfig_mutex critical section on error…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] The patch leaves export_rdev() calls inside the mddev->reconfig_mutex critical section on error paths, failing to completely break the disk->open_mutex deadlock cycle.
- [Medium] The snapshot check in md_add_new_disk() is bypassed when nd->rdev is NULL, allowing concurrent array reconfigurations to trigger a WARN_ON_ONCE. --

commit 140222a8600d2514747d88643188f131c16b6c50
Author: Jack Wang <[email protected]>

md: open new legs before locking the array

This commit aims to resolve a lockdep cycle between disk->open_mutex and mddev->reconfig_mutex by opening new devices before acquiring the array lock. It updates functions like md_import_new_disk() and new_dev_store() to snapshot configuration and validate it after locking.

Quoted 14 lines
drivers/md/md-autodetect.c +5 -1
index e15ae2fb58a2d..e592577356ad3 100644
@@ -216,7 +217,21 @@ static void __init md_setup_drive(struct md_setup_args *args)
 				(1 << MD_DISK_ACTIVE) | (1 << MD_DISK_SYNC);
 		}
 
-		md_add_new_disk(mddev, &dinfo, NULL);
+		/*
+		 * Opening a leg takes disk->open_mutex, which must not nest
+		 * inside reconfig_mutex, see md_import_new_disk().  Drop the
+		 * array lock around it; this is __init and the array is not
+		 * reachable yet, so nothing else can touch it in between.

drivers/md/md-autodetect.c static void __init md_setup_drive(struct md_setup_args *args) · line 234

Quoted 10 lines
drivers/md/md-autodetect.c +10 -0
+		 */
+		mddev_unlock(mddev);
+		if (md_import_new_disk(mddev, &dinfo, &nd)) {
+			mddev_lock_nointr(mddev);
+			continue;
+		}
+		mddev_lock_nointr(mddev);
+
+		md_add_new_disk(mddev, &dinfo, &nd, NULL);
+		md_put_new_disk(&nd);

[Severity: High]
Does md_put_new_disk() recreate the lockdep cycle we are trying to fix?

Since md_put_new_disk() calls export_rdev() internally, and export_rdev() acquires disk->open_mutex, calling it here while mddev_lock_nointr() is held appears to preserve the reconfig_mutex -> disk->open_mutex lock order.

Quoted 4 lines
drivers/md/md.c +0 -0
index 5be956e80563d..fa033d7d38318 100644

[ ... ]

Quoted 17 lines
drivers/md/md.c +7 -1
@@ -7685,12 +7706,35 @@ static int get_disk_info(struct mddev *mddev, void __user * arg)
 	return 0;
 }
 
+/*
+ * @nd carries an rdev the caller opened before locking the array, for the
+ * branch its snapshot selected.  Every caller must open first; doing it
+ * here would nest disk->open_mutex inside reconfig_mutex.
+ */
 int md_add_new_disk(struct mddev *mddev, struct mdu_disk_info_s *info,
-		    struct queue_limits *lim)
+		    struct md_new_disk *nd, struct queue_limits *lim)
 {
 	struct md_rdev *rdev;
 	dev_t dev = MKDEV(info->major,info->minor);
 
+	/*

drivers/md/md.c static int get_disk_info(struct mddev *mddev, void __user * arg) · line 7730

Quoted 10 lines
drivers/md/md.c +10 -0
+	 * The open ran unlocked, so anything that selects a different branch
+	 * below, or a different superblock format, means it was done against
+	 * an array that no longer looks like this one.
+	 */
+	if (nd && nd->rdev &&
+	    (nd->have_raid_disks != (mddev->raid_disks != 0) ||
+	     nd->have_pers != !!mddev->pers ||
+	     nd->persistent != mddev->persistent ||
+	     nd->major_version != mddev->major_version ||
+	     nd->minor_version != mddev->minor_version)) {

[Severity: Medium]
Is this validation check bypassed if nd->rdev is NULL?

If md_import_new_disk() is called on an array where ADD_NEW_DISK is unsupported (for example, raid_disks != 0 and pers == NULL), it returns 0 with nd->rdev = NULL. If a concurrent ioctl like STOP_ARRAY resets raid_disks to 0 before md_add_new_disk() acquires the lock, the condition checking nd->rdev evaluates to false, skipping the validation entirely.

This allows the function to proceed into the !mddev->raid_disks branch and hit the WARN_ON_ONCE(!nd || !nd->rdev) below, triggering a kernel splat.

drivers/md/md.c static int get_disk_info(struct mddev *mddev, void __user * arg) · line 7736

Quoted 6 lines
drivers/md/md.c +6 -0
+		pr_warn("%s: array reconfigured while opening %pg\n",
+			mdname(mddev), nd->rdev->bdev);
+		export_rdev(nd->rdev);
+		nd->rdev = NULL;
+		return -EBUSY;
+	}

[Severity: High]
This new failure path also executes with reconfig_mutex held, directly calling export_rdev() and recreating the lockdep cycle.

Could this leave the system vulnerable to the same deadlock on error paths?

This pattern also occurs in new_dev_store(), where the error path calls export_rdev() before mddev_unlock_and_resume().

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

PATCH v2 8/8 md: link a new leg's holder before locking the array

In reply to Jack Wang

From: Jack Wang <[email protected]>

bd_link_disk_holder() takes the leg's disk->open_mutex, and bind_rdev_to_array() calls it with reconfig_mutex held, so the dependency the previous patch removed from md_import_device() is still there by another route:

-> #2 (&q->limits_lock): sd_revalidate_disk / sd_open
-> #1 (&disk->open_mutex): bd_link_disk_holder
bind_rdev_to_array md_add_new_disk
md_ioctl <- ADD_NEW_DISK
-> #0 (&mddev->reconfig_mutex): md_ioctl <- RUN_ARRAY

bd_unlink_disk_holder() only takes blk_holder_mutex, which is why the release side needs no change and made the link side easy to miss.

Link the holder where the leg is opened, before the array is locked, and record it in a new HolderLinked flag so the release side knows whether there is a link to drop. A failed link is not fatal, as before. A leg that is linked but not yet bound is released through md_export_rdev(), which drops the link first.

A leg is now linked before it is known to be acceptable, so a leg the array goes on to reject shows up in its slaves directory until the error path releases it.

md then no longer takes disk->open_mutex under reconfig_mutex: of the functions that take it, md reaches bdev_open() and bd_link_disk_holder() from the paths above, bdev_release() and bdev_fput() only through fput(), which defers to task work, del_gendisk() only from mddev teardown, and never sync_bdevs().

Assisted-by LLM
---
 drivers/md/md-autodetect.c |  2 +-
 drivers/md/md.c            | 70 ++++++++++++++++++++++++++++----------
 drivers/md/md.h            |  7 +++-
 3 files changed, 59 insertions(+), 20 deletions(-)
drivers/md/md-autodetect.c +1 -1
index e592577356ad..b6f9fb36f1bb 100644
@@ -231,7 +231,7 @@ static void __init md_setup_drive(struct md_setup_args *args)
 		mddev_lock_nointr(mddev);
 
 		md_add_new_disk(mddev, &dinfo, &nd, NULL);
-		md_put_new_disk(&nd);
+		md_put_new_disk(mddev, &nd);
 	}
 
 	/*
drivers/md/md.c +52 -18

202 lines not on this page · raw message

drivers/md/md.h +6 -1
index 73a27d83d65a..1a0d57d58ad1 100644
@@ -294,6 +294,11 @@ enum flag_bits {
 				 * serial bios.
 				 */
 	Nonrot,			/* non-rotational device (SSD) */
+	HolderLinked,		/* bd_link_disk_holder() succeeded for this
+				 * leg.  The link is made before the array is
+				 * locked, as it takes disk->open_mutex,
+				 * see md_import_new_disk().
+				 */
 };
 
 static inline int is_badblock(struct md_rdev *rdev, sector_t s, sector_t sectors,
@@ -1069,7 +1074,7 @@ struct md_new_disk {
 
 int md_import_new_disk(struct mddev *mddev, struct mdu_disk_info_s *info,
 		       struct md_new_disk *nd);
-void md_put_new_disk(struct md_new_disk *nd);
+void md_put_new_disk(struct mddev *mddev, struct md_new_disk *nd);
 int md_add_new_disk(struct mddev *mddev, struct mdu_disk_info_s *info,
 		    struct md_new_disk *nd, struct queue_limits *lim);
 int do_md_run(struct mddev *mddev, struct queue_limits *lim);
Signature · 1 line
2.43.0
maintainer
#17 lore raw
In reply to Jack Wang

Hi,

Quoted 11 lines · Jack Wang

From: Jack Wang <[email protected]>

Writing to a queue limits attribute of an md array while a spare is being re-added deadlocks the array. I reported this earlier here:

https://lore.kernel.org/linux-raid/CAMGffE=heGA3y8FjQ0Sm1jj-kd-=H9Y54WozKASSEZhc9UNKjA@mail.gmail.com/

Four tasks, one array:

udev-worker queue_attr_store() holds q->limits_lock, waits in
blk_mq_freeze_queue() for q_usage_counter to drain

Sorry for the delay, usually blk_mq_freeze_queue() is useless for bio-based disks, because it can't guarantee inflight BIOs to drain. So this looks like a long term problem since queue_attr_store() can still update limits while there can still be bios inflight.

Quoted 4 lines

fio holds a q_usage_counter reference, parked in
md_handle_request()'s is_suspended() loop
mdadm suspended the array, waits for reconfig_mutex
md_start_sync holds reconfig_mutex, waits for q->limits_lock

And this deadlock looks related to blk_mq_freeze_queue() concurrent with mddev_suspend(), hence there can be bio blocked between. So I think there can be a simpler solution for this deadlock.

1) either remove the blk_mq_freeze_queue() from limits update for mdraid, or
2) also add blk_mq_freeze_queue() to mddev_suspend().

If this is a mdraid specific problem, I'll suggest 2). If there are other bio-based drivers have the same problem, we might what to replace blk_mq_freeze_queue() with driver's bio suspend to fix that limits can update with inflight bios as well.

Quoted 122 lines

The last leg is mddev_stack_new_rdev() from ->hot_add_disk(). Since commit c99f66e4084a ("block: fix queue freeze vs limits lock order in sysfs store methods") the sysfs store holds q->limits_lock across the freeze, so md must not block on that lock while it is holding back the I/O the freeze waits for. That is the same hazard mddev_suspend() already documents for reconfig_mutex.

v1 kept q->limits_lock outermost where it could and used a trylock everywhere else. Christoph asked for the lock ordering to be fixed instead, so v2 drops the trylock and the block patch that added it.

The rule v2 applies is that q->limits_lock nests outside reconfig_mutex and the suspend everywhere, with no exceptions to paper over. The two callers that cannot own an update do not need one: check_sb_changes() and md_check_recovery() only ever re-add a device that is already a member, so its limits are stacked and the update is a refresh, and they now take the no-stack path unconditionally. mddev_update_io_opt() is not an add and does need the update, so patch 4 defers it to a work item that takes the lock with nothing held.

Making the hoists unconditional exposed a second cycle that the trylock had been hiding, which Nilay hit with lockdep on v1:

   q->limits_lock -> reconfig_mutex        added by this series
   reconfig_mutex -> disk->open_mutex      pre-existing, md opens legs
                                           under reconfig_mutex
   disk->open_mutex -> q->limits_lock      pre-existing, sd_open() ->
                                           sd_revalidate_disk()

Only the middle edge can go, so legs are now opened before any md lock is taken. Patch 7 does the opens and patch 8 the holder links, which take disk->open_mutex too and were easy to miss because the release side only takes blk_holder_mutex. Opening without reconfig_mutex means the superblock format fields have to be snapshotted and rechecked once the array is locked.

Patches 1, 3 and 6 are plumbing with no functional change.

Two callers still take q->limits_lock inside reconfig_mutex, both with the array suspended, and patch 5 says why: ->start_reshape() from action_store(), which suspends before flushing sync_work, and raid*_run() -> queue_limits_set() from level_store(), which already hangs on its own because it freezes the queue while suspended. Both need more restructuring than belongs here.

The patches are based on v7.3-rc2.

v1: https://lore.kernel.org/linux-raid/[email protected]/T/#t

Changes since v1:
- Drop the trylock and the block patch adding queue_limits_start_update_trylock(), per Christoph.
- check_sb_changes() and md_check_recovery() take the no-stack path unconditionally instead of trying the lock first.
- Defer the io_opt update to a work item rather than skipping it on a

    contended pass (patch 4, was "md: don't wait for q->limits_lock in
    mddev_update_io_opt()").

- New patches 6-8 to close the reconfig_mutex -> disk->open_mutex edge that lockdep reported on v1: pass a queue_limits through ->run(), open new legs before locking the array, and link their holders there too.
- Rebased on v7.3-rc2.

Testing, on v7.3-rc2 with lockdep (PROVE_LOCKING, DEBUG_LOCK_ALLOC):

- the reproducer below, 20 fail/remove/add cycles with fio in flight and a loop writing queue/max_sectors_kb, where the same test wedges the array before the series
- array start at raid0, raid1, raid5, raid10 and linear, spare add, fail and remove, the rdev sysfs stores, ADD_NEW_DISK, array_state transitions, a level change and a raid5 3 -> 4 reshape to completion, which is what exercises patch 4's work item: io_opt goes from 1048576 to 1572864 once end_reshape() runs
- HOT_ADD_DISK of an undersized leg, so bind_rdev_to_array() fails and patch 8's release path runs

No lockdep reports, and debug_locks stayed 1 throughout. Every patch builds on its own.

A blktests case covering this deadlock will be sent separately.

The reproducer, for anyone who wants it:

   mdadm -C /dev/md111 --force -e 1.2 --assume-clean -l 1 \
         --bitmap=internal -n 2 /dev/ram0 /dev/ram1

   fio --direct=1 --rw=randrw --ioengine=libaio --iodepth=32 --numjobs=4 \
       --time_based=1 --runtime=180 --filename=/dev/md111 --name=repro &
   while :; do
       echo 128 > /sys/block/md111/queue/max_sectors_kb 2>/dev/null
   done &

   for i in $(seq 20); do
       mdadm /dev/md111 --fail /dev/ram0
       mdadm /dev/md111 --remove /dev/ram0
       mdadm /dev/md111 --add /dev/ram0
       mdadm --wait /dev/md111
   done

Jack Wang (8):
md: pass a queue_limits down to ->hot_add_disk()
md: don't wait for q->limits_lock in check_sb_changes()
md: pass a queue_limits through the rdev sysfs stores
md: defer the io_opt update out of the sync thread
md: take q->limits_lock before locking and suspending the array
md: pass a queue_limits through ->run()
md: open new legs before locking the array
md: link a new leg's holder before locking the array

  drivers/md/dm-raid.c       |   4 +-
  drivers/md/md-autodetect.c |  38 ++-
  drivers/md/md-linear.c     |  30 +-
  drivers/md/md.c            | 661 +++++++++++++++++++++++++++++--------
  drivers/md/md.h            |  56 +++-
  drivers/md/raid0.c         |  16 +-
  drivers/md/raid1.c         |  26 +-
  drivers/md/raid10.c        |  37 ++-
  drivers/md/raid5.c         |  54 ++-
  9 files changed, 741 insertions(+), 181 deletions(-)
Signature · 2 lines
Thanks,
Kuai
#18 lore raw

Hi Kuai,

Quoted 30 lines · yu kuai

Hi,

Quoted 11 lines · Jack Wang

From: Jack Wang <[email protected]>

Writing to a queue limits attribute of an md array while a spare is being re-added deadlocks the array. I reported this earlier here:

https://lore.kernel.org/linux-raid/CAMGffE=heGA3y8FjQ0Sm1jj-kd-=H9Y54WozKASSEZhc9UNKjA@mail.gmail.com/

Four tasks, one array:

udev-worker queue_attr_store() holds q->limits_lock, waits in
blk_mq_freeze_queue() for q_usage_counter to drain

Sorry for the delay, usually blk_mq_freeze_queue() is useless for bio-based disks, because it can't guarantee inflight BIOs to drain. So this looks like a long term problem since queue_attr_store() can still update limits while there can still be bios inflight.

Quoted 4 lines

fio holds a q_usage_counter reference, parked in
md_handle_request()'s is_suspended() loop
mdadm suspended the array, waits for reconfig_mutex
md_start_sync holds reconfig_mutex, waits for q->limits_lock

And this deadlock looks related to blk_mq_freeze_queue() concurrent with mddev_suspend(), hence there can be bio blocked between. So I think there can be a simpler solution for this deadlock.

Quoted 7 lines

1) either remove the blk_mq_freeze_queue() from limits update for mdraid, or
2) also add blk_mq_freeze_queue() to mddev_suspend().

If this is a mdraid specific problem, I'll suggest 2). If there are other bio-based drivers have the same problem, we might what to replace blk_mq_freeze_queue() with driver's bio suspend to fix that limits can update with inflight bios as well.

Thanks for the suggestion, will look into it back from vacation. Yes, it's a MDraid specific problem.

Quoted 126 lines
Quoted 112 lines

The last leg is mddev_stack_new_rdev() from ->hot_add_disk(). Since commit c99f66e4084a ("block: fix queue freeze vs limits lock order in sysfs store methods") the sysfs store holds q->limits_lock across the freeze, so md must not block on that lock while it is holding back the I/O the freeze waits for. That is the same hazard mddev_suspend() already documents for reconfig_mutex.

v1 kept q->limits_lock outermost where it could and used a trylock everywhere else. Christoph asked for the lock ordering to be fixed instead, so v2 drops the trylock and the block patch that added it.

The rule v2 applies is that q->limits_lock nests outside reconfig_mutex and the suspend everywhere, with no exceptions to paper over. The two callers that cannot own an update do not need one: check_sb_changes() and md_check_recovery() only ever re-add a device that is already a member, so its limits are stacked and the update is a refresh, and they now take the no-stack path unconditionally. mddev_update_io_opt() is not an add and does need the update, so patch 4 defers it to a work item that takes the lock with nothing held.

Making the hoists unconditional exposed a second cycle that the trylock had been hiding, which Nilay hit with lockdep on v1:

   q->limits_lock -> reconfig_mutex        added by this series
   reconfig_mutex -> disk->open_mutex      pre-existing, md opens legs
                                           under reconfig_mutex
   disk->open_mutex -> q->limits_lock      pre-existing, sd_open() ->
                                           sd_revalidate_disk()

Only the middle edge can go, so legs are now opened before any md lock is taken. Patch 7 does the opens and patch 8 the holder links, which take disk->open_mutex too and were easy to miss because the release side only takes blk_holder_mutex. Opening without reconfig_mutex means the superblock format fields have to be snapshotted and rechecked once the array is locked.

Patches 1, 3 and 6 are plumbing with no functional change.

Two callers still take q->limits_lock inside reconfig_mutex, both with the array suspended, and patch 5 says why: ->start_reshape() from action_store(), which suspends before flushing sync_work, and raid*_run() -> queue_limits_set() from level_store(), which already hangs on its own because it freezes the queue while suspended. Both need more restructuring than belongs here.

The patches are based on v7.3-rc2.

v1: https://lore.kernel.org/linux-raid/[email protected]/T/#t

Changes since v1:
- Drop the trylock and the block patch adding queue_limits_start_update_trylock(), per Christoph.
- check_sb_changes() and md_check_recovery() take the no-stack path unconditionally instead of trying the lock first.
- Defer the io_opt update to a work item rather than skipping it on a

    contended pass (patch 4, was "md: don't wait for q->limits_lock in
    mddev_update_io_opt()").

- New patches 6-8 to close the reconfig_mutex -> disk->open_mutex edge that lockdep reported on v1: pass a queue_limits through ->run(), open new legs before locking the array, and link their holders there too.
- Rebased on v7.3-rc2.

Testing, on v7.3-rc2 with lockdep (PROVE_LOCKING, DEBUG_LOCK_ALLOC):

- the reproducer below, 20 fail/remove/add cycles with fio in flight and a loop writing queue/max_sectors_kb, where the same test wedges the array before the series
- array start at raid0, raid1, raid5, raid10 and linear, spare add, fail and remove, the rdev sysfs stores, ADD_NEW_DISK, array_state transitions, a level change and a raid5 3 -> 4 reshape to completion, which is what exercises patch 4's work item: io_opt goes from 1048576 to 1572864 once end_reshape() runs
- HOT_ADD_DISK of an undersized leg, so bind_rdev_to_array() fails and patch 8's release path runs

No lockdep reports, and debug_locks stayed 1 throughout. Every patch builds on its own.

A blktests case covering this deadlock will be sent separately.

The reproducer, for anyone who wants it:

   mdadm -C /dev/md111 --force -e 1.2 --assume-clean -l 1 \
         --bitmap=internal -n 2 /dev/ram0 /dev/ram1

   fio --direct=1 --rw=randrw --ioengine=libaio --iodepth=32 --numjobs=4 \
       --time_based=1 --runtime=180 --filename=/dev/md111 --name=repro &
   while :; do
       echo 128 > /sys/block/md111/queue/max_sectors_kb 2>/dev/null
   done &

   for i in $(seq 20); do
       mdadm /dev/md111 --fail /dev/ram0
       mdadm /dev/md111 --remove /dev/ram0
       mdadm /dev/md111 --add /dev/ram0
       mdadm --wait /dev/md111
   done

Jack Wang (8):
md: pass a queue_limits down to ->hot_add_disk()
md: don't wait for q->limits_lock in check_sb_changes()
md: pass a queue_limits through the rdev sysfs stores
md: defer the io_opt update out of the sync thread
md: take q->limits_lock before locking and suspending the array
md: pass a queue_limits through ->run()
md: open new legs before locking the array
md: link a new leg's holder before locking the array

Quoted 11 lines
  drivers/md/dm-raid.c       |   4 +-
  drivers/md/md-autodetect.c |  38 ++-
  drivers/md/md-linear.c     |  30 +-
  drivers/md/md.c            | 661 +++++++++++++++++++++++++++++--------
  drivers/md/md.h            |  56 +++-
  drivers/md/raid0.c         |  16 +-
  drivers/md/raid1.c         |  26 +-
  drivers/md/raid10.c        |  37 ++-
  drivers/md/raid5.c         |  54 ++-
  9 files changed, 741 insertions(+), 181 deletions(-)

--
Thanks,
Kuai