Linux RAID subsystem development
 help / color / mirror / Atom feed
* Re: [GIT PULL] md-7.2-20260623
From: Jens Axboe @ 2026-06-24 12:33 UTC (permalink / raw)
  To: Yu Kuai; +Cc: linux-raid, linux-block, Abd-Alrhman Masalkhi, Chen Cheng
In-Reply-To: <20260623090327.1097428-1-yukuai@kernel.org>

On 6/23/26 3:03 AM, Yu Kuai wrote:
> Hi Jens,
> 
> Please consider pulling the following changes into your block-7.2
> branch.
> 
> This pull request contains:
> 
> Bug Fixes:
> - Fix raid1 writes_pending and barrier reference leaks on write failures.
>   (Abd-Alrhman Masalkhi)
> - Fix raid10 writes_pending leak on write request failures.
>   (Abd-Alrhman Masalkhi)
> - Fix raid10 writes_pending and barrier reference leaks on discard failures.
>   (Abd-Alrhman Masalkhi)
> - Fix raid1 REQ_NOWAIT handling while waiting for behind writes.
>   (Abd-Alrhman Masalkhi)
> - Fix raid1 r1_bio leak when a REQ_NOWAIT retry would block.
>   (Abd-Alrhman Masalkhi)
> - Fix raid1 read-balance head_position data race. (Chen Cheng)
> - Fix raid5 stripe batch bm_seq wraparound comparison. (Chen Cheng)
> - Fix raid5 stripe batch state snapshot KCSAN noise. (Chen Cheng)
> - Fix raid5 R5_Overlap races while breaking stripe batches. (Chen Cheng)
> 
> Improvements:
> - Add raid5 discard IO accounting. (Yu Kuai)
> - Always convert raid5 llbitmap bits for discard. (Yu Kuai)
> 
> Cleanups:
> - Simplify raid1_write_request() error handling. (Abd-Alrhman Masalkhi)

Pulled, thanks.

-- 
Jens Axboe


^ permalink raw reply

* [RFC PATCH] md,dm: caller-owned memalloc_noio token in mddev_suspend()/resume()
From: Chen Cheng @ 2026-06-24 10:13 UTC (permalink / raw)
  To: linux-raid, yukuai, dm-devel; +Cc: chencheng, linux-kernel

From: Chen Cheng <chencheng@fnnas.com>

Save token as mddev-scoped in mddev->noio_flags cause PF_MEMALLOC_NOIO
leak into task A, while task B restores a token that it never saved.

scenario:

task A                          mddev                         task B
======                          =======                       ============
write suspend_lo
mddev_suspend()
                                suspended == 0
                                drain active_io
                                suspended = 1
A: noio_A = memalloc_noio_save()
A returns with PF_MEMALLOC_NOIO set

                                                              write suspend_hi
                                                              mddev_suspend()
                                suspended == 1
                                suspended = 2
                                                              B returns
                                                              (no save)

mddev_resume()
                                suspended = 1
                                not last resume
A returns
A still has PF_MEMALLOC_NOIO   <-- leaked

                                                              mddev_resume()
                                suspended = 0
                                                              memalloc_noio_restore(noio_A)
                                                              (restores A's token in B)

Fixed by:
  - return each caller's noio_flags from mddev_suspend()
  - pass that token back into mddev_resume()
  - update the suspend-and-lock helpers to carry the token
  - store the token in struct raid_set for dm-raid paths where suspend
    and resume are paired across callbacks

Validation:
repeatedly updates the array's suspend_lo and suspend_hi sysfs from many
concurrent userspace workers. That makes multiple tasks to call
mddev_suspend()/mddev_resume() concurrently.

Each worker:
  - reads its initial /proc/self/stat flags and verifies that PF_MEMALLOC_NOIO is not already
    set
  - writes 0 to either suspend_lo or suspend_hi
  - immediately reads its own task flags again
  - reports success if flags & PF_MEMALLOC_NOIO is true after the write returns

Link: https://github.com/chencheng-fnnas/reproducer/blob/main/repro-md-noio-token-leak.sh

Fixes: 78f57ef9d50a ("md: use memalloc scope APIs in mddev_suspend()/mddev_resume()")

Signed-off-by: Chen Cheng <chencheng@fnnas.com>
---
 drivers/md/dm-raid.c       |  7 ++--
 drivers/md/md-autodetect.c |  5 ++-
 drivers/md/md-bitmap.c     | 12 +++---
 drivers/md/md.c            | 85 ++++++++++++++++++++++----------------
 drivers/md/md.h            | 23 ++++++-----
 drivers/md/raid5-cache.c   | 11 +++--
 drivers/md/raid5.c         | 25 ++++++-----
 7 files changed, 97 insertions(+), 71 deletions(-)

diff --git a/drivers/md/dm-raid.c b/drivers/md/dm-raid.c
index 8f5a5e1342a9..d89207e3722a 100644
--- a/drivers/md/dm-raid.c
+++ b/drivers/md/dm-raid.c
@@ -239,10 +239,11 @@ struct raid_set {
 	int raid_disks;
 	int delta_disks;
 	int data_offset;
 	int raid10_copies;
 	int requested_bitmap_chunk_sectors;
+	unsigned int suspend_noio_flags;
 
 	struct mddev md;
 	struct raid_type *raid_type;
 
 	sector_t array_sectors;
@@ -3251,11 +3252,11 @@ static int raid_ctr(struct dm_target *ti, unsigned int argc, char **argv)
 	/* Start raid set read-only and assumed clean to change in raid_resume() */
 	rs->md.ro = MD_RDONLY;
 	rs->md.in_sync = 1;
 
 	/* Has to be held on running the array */
-	mddev_suspend_and_lock_nointr(&rs->md);
+	mddev_suspend_and_lock_nointr(&rs->md, &rs->suspend_noio_flags);
 
 	/* Keep array frozen until resume. */
 	md_frozen_sync_thread(&rs->md);
 
 	r = md_run(&rs->md);
@@ -3863,11 +3864,11 @@ static void raid_postsuspend(struct dm_target *ti)
 		/*
 		 * sync_thread must be stopped during suspend, and writes have
 		 * to be stopped before suspending to avoid deadlocks.
 		 */
 		md_stop_writes(&rs->md);
-		mddev_suspend(&rs->md, false);
+		mddev_suspend(&rs->md, false, &rs->suspend_noio_flags);
 		rs->md.ro = MD_RDONLY;
 	}
 	clear_bit(MD_DM_SUSPENDING, &mddev->flags);
 
 }
@@ -4141,11 +4142,11 @@ static void raid_resume(struct dm_target *ti)
 						       lockdep_is_held(&mddev->reconfig_mutex)));
 		clear_bit(RT_FLAG_RS_FROZEN, &rs->runtime_flags);
 		mddev->ro = MD_RDWR;
 		mddev->in_sync = 0;
 		md_unfrozen_sync_thread(mddev);
-		mddev_unlock_and_resume(mddev);
+		mddev_unlock_and_resume(mddev, rs->suspend_noio_flags);
 	}
 }
 
 static struct target_type raid_target = {
 	.name = "raid",
diff --git a/drivers/md/md-autodetect.c b/drivers/md/md-autodetect.c
index 4b80165afd23..58e062cd0580 100644
--- a/drivers/md/md-autodetect.c
+++ b/drivers/md/md-autodetect.c
@@ -126,10 +126,11 @@ 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;
 	int err = 0, i;
 	char name[16];
+	unsigned int noio_flags;
 
 	if (args->partitioned) {
 		mdev = MKDEV(mdp_major, args->minor << MdpMinorShift);
 		sprintf(name, "md_d%d", args->minor);
 	} else {
@@ -173,11 +174,11 @@ static void __init md_setup_drive(struct md_setup_args *args)
 	if (IS_ERR(mddev)) {
 		pr_err("md: md_alloc failed - cannot start array %s\n", name);
 		return;
 	}
 
-	err = mddev_suspend_and_lock(mddev);
+	err = mddev_suspend_and_lock(mddev, &noio_flags);
 	if (err) {
 		pr_err("md: failed to lock array %s\n", name);
 		goto out_mddev_put;
 	}
 
@@ -219,11 +220,11 @@ static void __init md_setup_drive(struct md_setup_args *args)
 	if (!err)
 		err = do_md_run(mddev);
 	if (err)
 		pr_warn("md: starting %s failed\n", name);
 out_unlock:
-	mddev_unlock_and_resume(mddev);
+	mddev_unlock_and_resume(mddev, noio_flags);
 out_mddev_put:
 	mddev_put(mddev);
 }
 
 static int __init raid_setup(char *str)
diff --git a/drivers/md/md-bitmap.c b/drivers/md/md-bitmap.c
index 028b9ca8ce52..74b7f569a3f4 100644
--- a/drivers/md/md-bitmap.c
+++ b/drivers/md/md-bitmap.c
@@ -2620,13 +2620,14 @@ location_show(struct mddev *mddev, char *page)
 }
 
 static ssize_t
 location_store(struct mddev *mddev, const char *buf, size_t len)
 {
+	unsigned int noio_flags;
 	int rv;
 
-	rv = mddev_suspend_and_lock(mddev);
+	rv = mddev_suspend_and_lock(mddev, &noio_flags);
 	if (rv)
 		return rv;
 
 	if (mddev->pers) {
 		if (mddev->recovery || mddev->sync_thread) {
@@ -2711,11 +2712,11 @@ location_store(struct mddev *mddev, const char *buf, size_t len)
 		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
 		md_wakeup_thread(mddev->thread);
 	}
 	rv = 0;
 out:
-	mddev_unlock_and_resume(mddev);
+	mddev_unlock_and_resume(mddev, noio_flags);
 	if (rv)
 		return rv;
 	return len;
 
 merge_err:
@@ -2831,17 +2832,18 @@ backlog_store(struct mddev *mddev, const char *buf, size_t len)
 {
 	unsigned long backlog;
 	unsigned long old_mwb = mddev->bitmap_info.max_write_behind;
 	struct md_rdev *rdev;
 	bool has_write_mostly = false;
+	unsigned int noio_flags;
 	int rv = kstrtoul(buf, 10, &backlog);
 	if (rv)
 		return rv;
 	if (backlog > COUNTER_MAX)
 		return -EINVAL;
 
-	rv = mddev_suspend_and_lock(mddev);
+	rv = mddev_suspend_and_lock(mddev, &noio_flags);
 	if (rv)
 		return rv;
 
 	/*
 	 * Without write mostly device, it doesn't make sense to set
@@ -2854,11 +2856,11 @@ backlog_store(struct mddev *mddev, const char *buf, size_t len)
 		}
 	}
 	if (!has_write_mostly) {
 		pr_warn_ratelimited("%s: can't set backlog, no write mostly device available\n",
 				    mdname(mddev));
-		mddev_unlock(mddev);
+		mddev_unlock_and_resume(mddev, noio_flags);
 		return -EINVAL;
 	}
 
 	mddev->bitmap_info.max_write_behind = backlog;
 	if (!backlog && mddev->serial_info_pool) {
@@ -2871,11 +2873,11 @@ backlog_store(struct mddev *mddev, const char *buf, size_t len)
 			mddev_create_serial_pool(mddev, rdev);
 	}
 	if (old_mwb != backlog)
 		bitmap_update_sb(mddev->bitmap);
 
-	mddev_unlock_and_resume(mddev);
+	mddev_unlock_and_resume(mddev, noio_flags);
 	return len;
 }
 
 static struct md_sysfs_entry bitmap_backlog =
 __ATTR(backlog, S_IRUGO|S_IWUSR, backlog_show, backlog_store);
diff --git a/drivers/md/md.c b/drivers/md/md.c
index 1377c407614c..86d938dee50a 100644
--- a/drivers/md/md.c
+++ b/drivers/md/md.c
@@ -459,11 +459,12 @@ static void md_submit_bio(struct bio *bio)
 
 /*
  * Make sure no new requests are submitted to the device, and any requests that
  * have been submitted are completely handled.
  */
-int mddev_suspend(struct mddev *mddev, bool interruptible)
+int mddev_suspend(struct mddev *mddev, bool interruptible,
+		  unsigned int *noio_flags)
 {
 	int err = 0;
 
 	/*
 	 * hold reconfig_mutex to wait for normal io will deadlock, because
@@ -478,10 +479,11 @@ int mddev_suspend(struct mddev *mddev, bool interruptible)
 		mutex_lock(&mddev->suspend_mutex);
 	if (err)
 		return err;
 
 	if (mddev->suspended) {
+		*noio_flags = memalloc_noio_save();
 		WRITE_ONCE(mddev->suspended, mddev->suspended + 1);
 		mutex_unlock(&mddev->suspend_mutex);
 		return 0;
 	}
 
@@ -515,31 +517,30 @@ int mddev_suspend(struct mddev *mddev, bool interruptible)
 	 * prevent deadlock.
 	 */
 	WRITE_ONCE(mddev->suspended, mddev->suspended + 1);
 
 	/* restrict memory reclaim I/O during raid array is suspend */
-	mddev->noio_flag = memalloc_noio_save();
+	*noio_flags = memalloc_noio_save();
 
 	mutex_unlock(&mddev->suspend_mutex);
 	return 0;
 }
 EXPORT_SYMBOL_GPL(mddev_suspend);
 
-static void __mddev_resume(struct mddev *mddev, bool recovery_needed)
+static void __mddev_resume(struct mddev *mddev, bool recovery_needed,
+			   unsigned int noio_flags)
 {
 	lockdep_assert_not_held(&mddev->reconfig_mutex);
 
 	mutex_lock(&mddev->suspend_mutex);
+	memalloc_noio_restore(noio_flags);
 	WRITE_ONCE(mddev->suspended, mddev->suspended - 1);
 	if (mddev->suspended) {
 		mutex_unlock(&mddev->suspend_mutex);
 		return;
 	}
 
-	/* entred the memalloc scope from mddev_suspend() */
-	memalloc_noio_restore(mddev->noio_flag);
-
 	percpu_ref_resurrect(&mddev->active_io);
 	wake_up(&mddev->sb_wait);
 
 	if (recovery_needed)
 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
@@ -547,13 +548,13 @@ static void __mddev_resume(struct mddev *mddev, bool recovery_needed)
 	md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
 
 	mutex_unlock(&mddev->suspend_mutex);
 }
 
-void mddev_resume(struct mddev *mddev)
+void mddev_resume(struct mddev *mddev, unsigned int noio_flags)
 {
-	return __mddev_resume(mddev, true);
+	return __mddev_resume(mddev, true, noio_flags);
 }
 EXPORT_SYMBOL_GPL(mddev_resume);
 
 /* sync bdev before setting device to readonly or stopping raid*/
 static int mddev_set_closing_and_sync_blockdev(struct mddev *mddev, int opener_num)
@@ -3737,10 +3738,11 @@ rdev_attr_store(struct kobject *kobj, struct attribute *attr,
 {
 	struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
 	struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
 	struct kernfs_node *kn = NULL;
 	bool suspend = false;
+	unsigned int noio_flags = 0;
 	ssize_t rv;
 	struct mddev *mddev = READ_ONCE(rdev->mddev);
 
 	if (!entry->store)
 		return -EIO;
@@ -3756,17 +3758,17 @@ rdev_attr_store(struct kobject *kobj, struct attribute *attr,
 		    cmd_match(page, "writemostly") ||
 		    cmd_match(page, "-writemostly"))
 			suspend = true;
 	}
 
-	rv = suspend ? mddev_suspend_and_lock(mddev) : mddev_lock(mddev);
+	rv = suspend ? mddev_suspend_and_lock(mddev, &noio_flags) : mddev_lock(mddev);
 	if (!rv) {
 		if (rdev->mddev == NULL)
 			rv = -ENODEV;
 		else
 			rv = entry->store(rdev, page, length);
-		suspend ? mddev_unlock_and_resume(mddev) : mddev_unlock(mddev);
+		suspend ? mddev_unlock_and_resume(mddev, noio_flags) : mddev_unlock(mddev);
 	}
 
 	if (kn)
 		sysfs_unbreak_active_protection(kn);
 
@@ -4049,15 +4051,16 @@ level_store(struct mddev *mddev, const char *buf, size_t len)
 	size_t slen = len;
 	struct md_personality *pers, *oldpers;
 	long level;
 	void *priv, *oldpriv;
 	struct md_rdev *rdev;
+	unsigned int noio_flags;
 
 	if (slen == 0 || slen >= sizeof(clevel))
 		return -EINVAL;
 
-	rv = mddev_suspend_and_lock(mddev);
+	rv = mddev_suspend_and_lock(mddev, &noio_flags);
 	if (rv)
 		return rv;
 
 	if (mddev->pers == NULL) {
 		memcpy(mddev->clevel, buf, slen);
@@ -4231,11 +4234,11 @@ level_store(struct mddev *mddev, const char *buf, size_t len)
 		md_update_sb(mddev, 1);
 	sysfs_notify_dirent_safe(mddev->sysfs_level);
 	md_new_event();
 	rv = len;
 out_unlock:
-	mddev_unlock_and_resume(mddev);
+	mddev_unlock_and_resume(mddev, noio_flags);
 	return rv;
 }
 
 static struct md_sysfs_entry md_level =
 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
@@ -4410,17 +4413,18 @@ static int update_raid_disks(struct mddev *mddev, int raid_disks);
 
 static ssize_t
 raid_disks_store(struct mddev *mddev, const char *buf, size_t len)
 {
 	unsigned int n;
+	unsigned int noio_flags;
 	int err;
 
 	err = kstrtouint(buf, 10, &n);
 	if (err < 0)
 		return err;
 
-	err = mddev_suspend_and_lock(mddev);
+	err = mddev_suspend_and_lock(mddev, &noio_flags);
 	if (err)
 		return err;
 	if (mddev->pers) {
 		if (n != mddev->raid_disks)
 			err = update_raid_disks(mddev, n);
@@ -4442,11 +4446,11 @@ raid_disks_store(struct mddev *mddev, const char *buf, size_t len)
 		mddev->raid_disks = n;
 		mddev->reshape_backwards = (mddev->delta_disks < 0);
 	} else
 		mddev->raid_disks = n;
 out_unlock:
-	mddev_unlock_and_resume(mddev);
+	mddev_unlock_and_resume(mddev, noio_flags);
 	return err ? err : len;
 }
 static struct md_sysfs_entry md_raid_disks =
 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
 
@@ -4822,10 +4826,11 @@ new_dev_store(struct mddev *mddev, const char *buf, size_t len)
 	char *e;
 	int major = simple_strtoul(buf, &e, 10);
 	int minor;
 	dev_t dev;
 	struct md_rdev *rdev;
+	unsigned int noio_flags;
 	int err;
 
 	if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
 		return -EINVAL;
 	minor = simple_strtoul(e+1, &e, 10);
@@ -4834,11 +4839,11 @@ new_dev_store(struct mddev *mddev, const char *buf, size_t len)
 	dev = MKDEV(major, minor);
 	if (major != MAJOR(dev) ||
 	    minor != MINOR(dev))
 		return -EOVERFLOW;
 
-	err = mddev_suspend_and_lock(mddev);
+	err = mddev_suspend_and_lock(mddev, &noio_flags);
 	if (err)
 		return err;
 	if (mddev->persistent) {
 		rdev = md_import_device(dev, mddev->major_version,
 					mddev->minor_version);
@@ -4855,18 +4860,18 @@ new_dev_store(struct mddev *mddev, const char *buf, size_t len)
 		rdev = md_import_device(dev, -2, -1);
 	else
 		rdev = md_import_device(dev, -1, -1);
 
 	if (IS_ERR(rdev)) {
-		mddev_unlock_and_resume(mddev);
+		mddev_unlock_and_resume(mddev, noio_flags);
 		return PTR_ERR(rdev);
 	}
 	err = bind_rdev_to_array(rdev, mddev);
  out:
 	if (err)
 		export_rdev(rdev);
-	mddev_unlock_and_resume(mddev);
+	mddev_unlock_and_resume(mddev, noio_flags);
 	if (!err)
 		md_new_event();
 	return err ? err : len;
 }
 
@@ -5257,28 +5262,29 @@ static int mddev_start_reshape(struct mddev *mddev)
 static ssize_t
 action_store(struct mddev *mddev, const char *page, size_t len)
 {
 	int ret;
 	enum sync_action action;
+	unsigned int noio_flags = 0;
 
 	if (!mddev->pers || !mddev->pers->sync_request)
 		return -EINVAL;
 
 	action = md_sync_action_by_name(page);
 retry:
 	if (work_busy(&mddev->sync_work))
 		flush_work(&mddev->sync_work);
 
 	ret = (action == ACTION_RESHAPE) ?
-		mddev_suspend_and_lock(mddev) :
+		mddev_suspend_and_lock(mddev, &noio_flags) :
 		mddev_lock(mddev);
 	if (ret)
 		return ret;
 
 	if (work_busy(&mddev->sync_work)) {
 		if (action == ACTION_RESHAPE)
-			mddev_unlock_and_resume(mddev);
+			mddev_unlock_and_resume(mddev, noio_flags);
 		else
 			mddev_unlock(mddev);
 		goto retry;
 	}
 
@@ -5349,11 +5355,11 @@ action_store(struct mddev *mddev, const char *page, size_t len)
 	sysfs_notify_dirent_safe(mddev->sysfs_action);
 	ret = len;
 
 out:
 	if (action == ACTION_RESHAPE)
-		mddev_unlock_and_resume(mddev);
+		mddev_unlock_and_resume(mddev, noio_flags);
 	else
 		mddev_unlock(mddev);
 	return ret;
 }
 
@@ -5640,24 +5646,25 @@ suspend_lo_show(struct mddev *mddev, char *page)
 
 static ssize_t
 suspend_lo_store(struct mddev *mddev, const char *buf, size_t len)
 {
 	unsigned long long new;
+	unsigned int noio_flags;
 	int err;
 
 	err = kstrtoull(buf, 10, &new);
 	if (err < 0)
 		return err;
 	if (new != (sector_t)new)
 		return -EINVAL;
 
-	err = mddev_suspend(mddev, true);
+	err = mddev_suspend(mddev, true, &noio_flags);
 	if (err)
 		return err;
 
 	WRITE_ONCE(mddev->suspend_lo, new);
-	mddev_resume(mddev);
+	mddev_resume(mddev, noio_flags);
 
 	return len;
 }
 static struct md_sysfs_entry md_suspend_lo =
 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
@@ -5671,24 +5678,25 @@ suspend_hi_show(struct mddev *mddev, char *page)
 
 static ssize_t
 suspend_hi_store(struct mddev *mddev, const char *buf, size_t len)
 {
 	unsigned long long new;
+	unsigned int noio_flags;
 	int err;
 
 	err = kstrtoull(buf, 10, &new);
 	if (err < 0)
 		return err;
 	if (new != (sector_t)new)
 		return -EINVAL;
 
-	err = mddev_suspend(mddev, true);
+	err = mddev_suspend(mddev, true, &noio_flags);
 	if (err)
 		return err;
 
 	WRITE_ONCE(mddev->suspend_hi, new);
-	mddev_resume(mddev);
+	mddev_resume(mddev, noio_flags);
 
 	return len;
 }
 static struct md_sysfs_entry md_suspend_hi =
 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
@@ -5928,19 +5936,20 @@ static ssize_t serialize_policy_show(struct mddev *mddev, char *page)
 static ssize_t
 serialize_policy_store(struct mddev *mddev, const char *buf, size_t len)
 {
 	int err;
 	bool value;
+	unsigned int noio_flags;
 
 	err = kstrtobool(buf, &value);
 	if (err)
 		return err;
 
 	if (value == test_bit(MD_SERIALIZE_POLICY, &mddev->flags))
 		return len;
 
-	err = mddev_suspend_and_lock(mddev);
+	err = mddev_suspend_and_lock(mddev, &noio_flags);
 	if (err)
 		return err;
 	if (mddev->pers == NULL || (mddev->pers->head.id != ID_RAID1)) {
 		pr_err("md: serialize_policy is only effective for raid1\n");
 		err = -EINVAL;
@@ -5953,11 +5962,11 @@ serialize_policy_store(struct mddev *mddev, const char *buf, size_t len)
 	} else {
 		mddev_destroy_serial_pool(mddev, NULL);
 		clear_bit(MD_SERIALIZE_POLICY, &mddev->flags);
 	}
 unlock:
-	mddev_unlock_and_resume(mddev);
+	mddev_unlock_and_resume(mddev, noio_flags);
 	return err ?: len;
 }
 
 static struct md_sysfs_entry md_serialize_policy =
 __ATTR(serialize_policy, S_IRUGO | S_IWUSR, serialize_policy_show,
@@ -6263,21 +6272,22 @@ EXPORT_SYMBOL_GPL(mddev_stack_new_rdev);
 
 /* update the optimal I/O size after a reshape */
 void mddev_update_io_opt(struct mddev *mddev, unsigned int nr_stripes)
 {
 	struct queue_limits lim;
+	unsigned int noio_flags;
 
 	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)
+	if (mddev_suspend(mddev, false, &noio_flags) < 0)
 		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);
+	mddev_resume(mddev, noio_flags);
 }
 EXPORT_SYMBOL_GPL(mddev_update_io_opt);
 
 static void mddev_delayed_delete(struct work_struct *ws)
 {
@@ -7255,10 +7265,11 @@ static void autorun_array(struct mddev *mddev)
  */
 static void autorun_devices(int part)
 {
 	struct md_rdev *rdev0, *rdev, *tmp;
 	struct mddev *mddev;
+	unsigned int noio_flags;
 
 	pr_info("md: autorun ...\n");
 	while (!list_empty(&pending_raid_disks)) {
 		int unit;
 		dev_t dev;
@@ -7295,27 +7306,27 @@ static void autorun_devices(int part)
 
 		mddev = md_alloc(dev, NULL);
 		if (IS_ERR(mddev))
 			break;
 
-		if (mddev_suspend_and_lock(mddev))
+		if (mddev_suspend_and_lock(mddev, &noio_flags))
 			pr_warn("md: %s locked, cannot run\n", mdname(mddev));
 		else if (mddev->raid_disks || mddev->major_version
 			 || !list_empty(&mddev->disks)) {
 			pr_warn("md: %s already running, cannot run %pg\n",
 				mdname(mddev), rdev0->bdev);
-			mddev_unlock_and_resume(mddev);
+			mddev_unlock_and_resume(mddev, noio_flags);
 		} else {
 			pr_debug("md: created %s\n", mdname(mddev));
 			mddev->persistent = 1;
 			rdev_for_each_list(rdev, tmp, &candidates) {
 				list_del_init(&rdev->same_set);
 				if (bind_rdev_to_array(rdev, mddev))
 					export_rdev(rdev);
 			}
 			autorun_array(mddev);
-			mddev_unlock_and_resume(mddev);
+			mddev_unlock_and_resume(mddev, noio_flags);
 		}
 		/* on success, candidates will be empty, on error
 		 * it won't...
 		 */
 		rdev_for_each_list(rdev, tmp, &candidates) {
@@ -8329,10 +8340,11 @@ static int __md_set_array_info(struct mddev *mddev, void __user *argp)
 
 static int md_ioctl(struct block_device *bdev, blk_mode_t mode,
 			unsigned int cmd, unsigned long arg)
 {
 	int err = 0;
+	unsigned int noio_flags = 0;
 	void __user *argp = (void __user *)arg;
 	struct mddev *mddev = NULL;
 
 	err = md_ioctl_valid(cmd);
 	if (err)
@@ -8380,11 +8392,11 @@ static int md_ioctl(struct block_device *bdev, blk_mode_t mode,
 	}
 
 	if (!md_is_rdwr(mddev))
 		flush_work(&mddev->sync_work);
 
-	err = md_ioctl_need_suspend(cmd) ? mddev_suspend_and_lock(mddev) :
+	err = md_ioctl_need_suspend(cmd) ? mddev_suspend_and_lock(mddev, &noio_flags) :
 					   mddev_lock(mddev);
 	if (err) {
 		pr_debug("md: ioctl lock interrupted, reason %d, cmd %d\n",
 			 err, cmd);
 		goto out;
@@ -8511,11 +8523,11 @@ static int md_ioctl(struct block_device *bdev, blk_mode_t mode,
 unlock:
 	if (mddev->hold_active == UNTIL_IOCTL &&
 	    err != -EINVAL)
 		mddev->hold_active = 0;
 
-	md_ioctl_need_suspend(cmd) ? mddev_unlock_and_resume(mddev) :
+	md_ioctl_need_suspend(cmd) ? mddev_unlock_and_resume(mddev, noio_flags) :
 				     mddev_unlock(mddev);
 
 out:
 	if (cmd == STOP_ARRAY_RO || (err && cmd == STOP_ARRAY))
 		clear_bit(MD_CLOSING, &mddev->flags);
@@ -10180,20 +10192,21 @@ static bool md_choose_sync_action(struct mddev *mddev, int *spares)
 static void md_start_sync(struct work_struct *ws)
 {
 	struct mddev *mddev = container_of(ws, struct mddev, sync_work);
 	int spares = 0;
 	bool suspend = false;
+	unsigned int noio_flags = 0;
 	char *name;
 
 	/*
 	 * If reshape is still in progress, spares won't be added or removed
 	 * from conf until reshape is done.
 	 */
 	if (mddev->reshape_position == MaxSector &&
 	    md_spares_need_change(mddev)) {
 		suspend = true;
-		mddev_suspend(mddev, false);
+		mddev_suspend(mddev, false, &noio_flags);
 	}
 
 	mddev_lock_nointr(mddev);
 	if (!md_is_rdwr(mddev)) {
 		/*
@@ -10237,11 +10250,11 @@ static void md_start_sync(struct work_struct *ws)
 	 * not set it again. Otherwise, we may cause issue like this one:
 	 *     https://bugzilla.kernel.org/show_bug.cgi?id=218200
 	 * Therefore, use __mddev_resume(mddev, false).
 	 */
 	if (suspend)
-		__mddev_resume(mddev, false);
+		__mddev_resume(mddev, false, noio_flags);
 	md_wakeup_thread(mddev->sync_thread);
 	sysfs_notify_dirent_safe(mddev->sysfs_action);
 	md_new_event();
 	return;
 
@@ -10257,11 +10270,11 @@ static void md_start_sync(struct work_struct *ws)
 	 * not set it again. Otherwise, we may cause issue like this one:
 	 *     https://bugzilla.kernel.org/show_bug.cgi?id=218200
 	 * Therefore, use __mddev_resume(mddev, false).
 	 */
 	if (suspend)
-		__mddev_resume(mddev, false);
+		__mddev_resume(mddev, false, noio_flags);
 
 	wake_up(&resync_wait);
 	if (test_and_clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery) &&
 	    mddev->sysfs_action)
 		sysfs_notify_dirent_safe(mddev->sysfs_action);
diff --git a/drivers/md/md.h b/drivers/md/md.h
index d8daf0f75cbb..3337cd21eb30 100644
--- a/drivers/md/md.h
+++ b/drivers/md/md.h
@@ -619,11 +619,10 @@ struct mddev {
 	mempool_t *serial_info_pool;
 	void (*sync_super)(struct mddev *mddev, struct md_rdev *rdev);
 	struct md_cluster_info		*cluster_info;
 	struct md_cluster_operations *cluster_ops;
 	unsigned int			good_device_nr;	/* good device num within cluster raid */
-	unsigned int			noio_flag; /* for memalloc scope API */
 
 	/*
 	 * Temporarily store rdev that will be finally removed when
 	 * reconfig_mutex is unlocked, protected by reconfig_mutex.
 	 */
@@ -953,12 +952,13 @@ extern void md_stop(struct mddev *mddev);
 extern void md_stop_writes(struct mddev *mddev);
 extern int md_rdev_init(struct md_rdev *rdev);
 extern void md_rdev_clear(struct md_rdev *rdev);
 
 extern bool md_handle_request(struct mddev *mddev, struct bio *bio);
-extern int mddev_suspend(struct mddev *mddev, bool interruptible);
-extern void mddev_resume(struct mddev *mddev);
+extern int mddev_suspend(struct mddev *mddev, bool interruptible,
+			 unsigned int *noio_flags);
+extern void mddev_resume(struct mddev *mddev, unsigned int noio_flags);
 extern void md_idle_sync_thread(struct mddev *mddev);
 extern void md_frozen_sync_thread(struct mddev *mddev);
 extern void md_unfrozen_sync_thread(struct mddev *mddev);
 
 extern void md_update_sb(struct mddev *mddev, int force);
@@ -999,35 +999,38 @@ static inline void mddev_check_write_zeroes(struct mddev *mddev, struct bio *bio
 	if (bio_op(bio) == REQ_OP_WRITE_ZEROES &&
 	    !bio->bi_bdev->bd_disk->queue->limits.max_write_zeroes_sectors)
 		mddev->gendisk->queue->limits.max_write_zeroes_sectors = 0;
 }
 
-static inline int mddev_suspend_and_lock(struct mddev *mddev)
+static inline int mddev_suspend_and_lock(struct mddev *mddev,
+					 unsigned int *noio_flags)
 {
 	int ret;
 
-	ret = mddev_suspend(mddev, true);
+	ret = mddev_suspend(mddev, true, noio_flags);
 	if (ret)
 		return ret;
 
 	ret = mddev_lock(mddev);
 	if (ret)
-		mddev_resume(mddev);
+		mddev_resume(mddev, *noio_flags);
 
 	return ret;
 }
 
-static inline void mddev_suspend_and_lock_nointr(struct mddev *mddev)
+static inline void mddev_suspend_and_lock_nointr(struct mddev *mddev,
+						 unsigned int *noio_flags)
 {
-	mddev_suspend(mddev, false);
+	mddev_suspend(mddev, false, noio_flags);
 	mddev_lock_nointr(mddev);
 }
 
-static inline void mddev_unlock_and_resume(struct mddev *mddev)
+static inline void mddev_unlock_and_resume(struct mddev *mddev,
+					   unsigned int noio_flags)
 {
 	mddev_unlock(mddev);
-	mddev_resume(mddev);
+	mddev_resume(mddev, noio_flags);
 }
 
 struct mdu_array_info_s;
 struct mdu_disk_info_s;
 
diff --git a/drivers/md/raid5-cache.c b/drivers/md/raid5-cache.c
index 7b7546bfa21f..6f8e3a624456 100644
--- a/drivers/md/raid5-cache.c
+++ b/drivers/md/raid5-cache.c
@@ -693,13 +693,15 @@ static void r5c_disable_writeback_async(struct work_struct *work)
 		   !READ_ONCE(conf->log) ||
 		   !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
 
 	log = READ_ONCE(conf->log);
 	if (log) {
-		mddev_suspend(mddev, false);
+		unsigned int noio_flags;
+
+		mddev_suspend(mddev, false, &noio_flags);
 		log->r5c_journal_mode = R5C_JOURNAL_MODE_WRITE_THROUGH;
-		mddev_resume(mddev);
+		mddev_resume(mddev, noio_flags);
 	}
 }
 
 static void r5l_submit_current_io(struct r5l_log *log)
 {
@@ -2603,10 +2605,11 @@ EXPORT_SYMBOL(r5c_journal_mode_set);
 static ssize_t r5c_journal_mode_store(struct mddev *mddev,
 				      const char *page, size_t length)
 {
 	int mode = ARRAY_SIZE(r5c_journal_mode_str);
 	size_t len = length;
+	unsigned int noio_flags;
 	int ret;
 
 	if (len < 2)
 		return -EINVAL;
 
@@ -2615,15 +2618,15 @@ static ssize_t r5c_journal_mode_store(struct mddev *mddev,
 
 	while (mode--)
 		if (strlen(r5c_journal_mode_str[mode]) == len &&
 		    !strncmp(page, r5c_journal_mode_str[mode], len))
 			break;
-	ret = mddev_suspend_and_lock(mddev);
+	ret = mddev_suspend_and_lock(mddev, &noio_flags);
 	if (ret)
 		return ret;
 	ret = r5c_journal_mode_set(mddev, mode);
-	mddev_unlock_and_resume(mddev);
+	mddev_unlock_and_resume(mddev, noio_flags);
 	return ret ?: length;
 }
 
 struct md_sysfs_entry
 r5c_journal_mode = __ATTR(journal_mode, 0644,
diff --git a/drivers/md/raid5.c b/drivers/md/raid5.c
index 65ae7d8930fc..6062c4b62cc8 100644
--- a/drivers/md/raid5.c
+++ b/drivers/md/raid5.c
@@ -6992,11 +6992,11 @@ raid5_show_stripe_size(struct mddev  *mddev, char *page)
 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
 static ssize_t
 raid5_store_stripe_size(struct mddev  *mddev, const char *page, size_t len)
 {
 	struct r5conf *conf;
-	unsigned long new;
+	unsigned long new, noio_flags;
 	int err;
 	int size;
 
 	if (len >= PAGE_SIZE)
 		return -EINVAL;
@@ -7011,11 +7011,11 @@ raid5_store_stripe_size(struct mddev  *mddev, const char *page, size_t len)
 	if (new % DEFAULT_STRIPE_SIZE != 0 ||
 			new > PAGE_SIZE || new == 0 ||
 			new != roundup_pow_of_two(new))
 		return -EINVAL;
 
-	err = mddev_suspend_and_lock(mddev);
+	err = mddev_suspend_and_lock(mddev, &noio_flags);
 	if (err)
 		return err;
 
 	conf = mddev->private;
 	if (!conf) {
@@ -7049,11 +7049,11 @@ raid5_store_stripe_size(struct mddev  *mddev, const char *page, size_t len)
 		err = -ENOMEM;
 	}
 	mutex_unlock(&conf->cache_size_mutex);
 
 out_unlock:
-	mddev_unlock_and_resume(mddev);
+	mddev_unlock_and_resume(mddev, noio_flags);
 	return err ?: len;
 }
 
 static struct md_sysfs_entry
 raid5_stripe_size = __ATTR(stripe_size, 0644,
@@ -7127,19 +7127,20 @@ raid5_show_skip_copy(struct mddev *mddev, char *page)
 static ssize_t
 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
 {
 	struct r5conf *conf;
 	unsigned long new;
+	unsigned int noio_flags;
 	int err;
 
 	if (len >= PAGE_SIZE)
 		return -EINVAL;
 	if (kstrtoul(page, 10, &new))
 		return -EINVAL;
 	new = !!new;
 
-	err = mddev_suspend_and_lock(mddev);
+	err = mddev_suspend_and_lock(mddev, &noio_flags);
 	if (err)
 		return err;
 	conf = mddev->private;
 	if (!conf)
 		err = -ENODEV;
@@ -7152,11 +7153,11 @@ raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
 			lim.features |= BLK_FEAT_STABLE_WRITES;
 		else
 			lim.features &= ~BLK_FEAT_STABLE_WRITES;
 		err = queue_limits_commit_update(q, &lim);
 	}
-	mddev_unlock_and_resume(mddev);
+	mddev_unlock_and_resume(mddev, noio_flags);
 	return err ?: len;
 }
 
 static struct md_sysfs_entry
 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
@@ -7195,10 +7196,11 @@ static int alloc_thread_groups(struct r5conf *conf, int cnt,
 static ssize_t
 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
 {
 	struct r5conf *conf;
 	unsigned int new;
+	unsigned int noio_flags;
 	int err;
 	struct r5worker_group *new_groups, *old_groups;
 	int group_cnt;
 
 	if (len >= PAGE_SIZE)
@@ -7207,16 +7209,16 @@ raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
 		return -EINVAL;
 	/* 8192 should be big enough */
 	if (new > 8192)
 		return -EINVAL;
 
-	err = mddev_suspend_and_lock(mddev);
+	err = mddev_suspend_and_lock(mddev, &noio_flags);
 	if (err)
 		return err;
 	conf = mddev->private;
 	if (!conf) {
-		mddev_unlock_and_resume(mddev);
+		mddev_unlock_and_resume(mddev, noio_flags);
 		return -ENODEV;
 	}
 	raid5_quiesce(mddev, true);
 
 	if (new != conf->worker_cnt_per_group) {
@@ -7237,11 +7239,11 @@ raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
 			kfree(old_groups);
 		}
 	}
 
 	raid5_quiesce(mddev, false);
-	mddev_unlock_and_resume(mddev);
+	mddev_unlock_and_resume(mddev, noio_flags);
 
 	return err ?: len;
 }
 
 static struct md_sysfs_entry
@@ -8940,18 +8942,19 @@ static void *raid6_takeover(struct mddev *mddev)
 }
 
 static int raid5_change_consistency_policy(struct mddev *mddev, const char *buf)
 {
 	struct r5conf *conf;
+	unsigned int noio_flags;
 	int err;
 
-	err = mddev_suspend_and_lock(mddev);
+	err = mddev_suspend_and_lock(mddev, &noio_flags);
 	if (err)
 		return err;
 	conf = mddev->private;
 	if (!conf) {
-		mddev_unlock_and_resume(mddev);
+		mddev_unlock_and_resume(mddev, noio_flags);
 		return -ENODEV;
 	}
 
 	if (strncmp(buf, "ppl", 3) == 0) {
 		/* ppl only works with RAID 5 */
@@ -8990,11 +8993,11 @@ static int raid5_change_consistency_policy(struct mddev *mddev, const char *buf)
 	}
 
 	if (!err)
 		md_update_sb(mddev, 1);
 
-	mddev_unlock_and_resume(mddev);
+	mddev_unlock_and_resume(mddev, noio_flags);
 
 	return err;
 }
 
 static int raid5_start(struct mddev *mddev)
-- 
2.54.0

^ permalink raw reply related

* Re: [PATCH v2 08/20] md/md-llbitmap: finish reshape geometry
From: sashiko-bot @ 2026-06-24  9:06 UTC (permalink / raw)
  To: Yu Kuai; +Cc: linux-raid, yukuai
In-Reply-To: <73a8a0409b741c57bbc9927abc7a9981cbafbf27.1782282042.git.yukuai@kernel.org>

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The entire bitmap is unnecessarily flushed to disk twice during reshape finish.
--

commit ae4a6d71e5ee77405793f20d5d615e089187608f
Author: Yu Kuai <yukuai@fygo.io>
md/md-llbitmap: finish reshape geometry

This commit introduces the final step for reshaping llbitmap arrays by
committing the staged geometry. It handles quiescing the device, updating
internal state, writing the superblock, and flushing the bitmap.

> diff --git a/drivers/md/md-llbitmap.c b/drivers/md/md-llbitmap.c
> index cdced2126e975..ae2e87fd58874 100644
> --- a/drivers/md/md-llbitmap.c
> +++ b/drivers/md/md-llbitmap.c

[ ... ]

> @@ -1680,6 +1680,30 @@ static void llbitmap_dirty_bits(struct mddev *mddev, unsigned long s,
>  	llbitmap_state_machine(mddev->bitmap, s, e, BitmapActionStartwrite);
>  }
>  
> +static void llbitmap_reshape_finish(struct mddev *mddev)
> +{
> +	struct llbitmap *llbitmap = mddev->bitmap;
> +
> +	if (mddev->pers->quiesce)
> +		mddev->pers->quiesce(mddev, 1);
> +
> +	mutex_lock(&mddev->bitmap_info.mutex);
> +	llbitmap_flush(mddev);
> +
> +	llbitmap->chunksize = llbitmap->reshape_chunksize;
> +	llbitmap->chunkshift = ffz(~llbitmap->chunksize);
> +	llbitmap->chunks = llbitmap->reshape_chunks;
> +	llbitmap->sync_size = llbitmap->reshape_sync_size;
> +	llbitmap_refresh_reshape(llbitmap);
> +	mddev->bitmap_info.chunksize = llbitmap->chunksize;
> +	llbitmap_update_sb(llbitmap);
> +	__llbitmap_flush(mddev);

[Severity: Low]
Is this second flush of the entire bitmap redundant?

The code calls llbitmap_flush() at the beginning of the lock section.
After updating the geometry and writing out the superblock via
llbitmap_update_sb(), __llbitmap_flush() is called again. Since no bitmap
data bits are modified in the interim, does this cause an unnecessary
synchronous I/O spike that could be avoided?

> +	mutex_unlock(&mddev->bitmap_info.mutex);
> +
> +	if (mddev->pers->quiesce)
> +		mddev->pers->quiesce(mddev, 0);
> +}

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=8

^ permalink raw reply

* Re: [PATCH 4/7] md/raid10: raid10_write_request() drops the barrier before calling
From: Abd-Alrhman Masalkhi @ 2026-06-24  8:12 UTC (permalink / raw)
  To: yu kuai, song, magiclinan, xiao, axboe, john.g.garry,
	martin.petersen, yukuai
  Cc: linux-raid, linux-kernel
In-Reply-To: <7239c50c-b257-4179-827a-9facd48e75e1@fygo.io>


Hi Kaui,

On Wed, Jun 24, 2026 at 15:23 +0800, yu kuai wrote:
> Hi,
>
> 在 2026/6/23 15:24, Abd-Alrhman Masalkhi 写道:
>> bio_submit_split_bioset() and reacquires it afterwards. This is
>> unnecessary because bio_submit_split_bioset() does not require
>> releasing the barrier protection.
>
> Why is this safe?
>
> It's possible plug is not enabled in this context, and the allocated new
> aplit bio will be submitted and enter wait_barrier() again. wait_barrier()
> is not supposed to be called recursively. Otherwise deadlock can happend:
>
> t1: sync_thread grab barrier and waiting for nr_pending to be 0 from raise_barrier()
> t2: wait_barrier() first inc nr_pending, then recursive wait_barrier() waiting
> for barrier to be released.
>

raid10_write_request() is only called from the bio submission path and
not from raid10d thread, so we do not re-enter it while already holding
barrier. Therefore, the split bio submitted by bio_submit_split_bioset()
cannot recurse back into wait_barrier() from the same execution path.

The situation is different for reads, where raid10_read_request() will
be called both from the submission path and from raid10d. There,
dropping and reacquiring the barrier protection remains necessary.

>>
>> Remove the redundant allow_barrier()/wait_barrier() pair around
>> bio_submit_split_bioset().
>>
>> Signed-off-by: Abd-Alrhman Masalkhi <abd.masalkhi@gmail.com>
>> ---
>>   drivers/md/raid10.c | 2 --
>>   1 file changed, 2 deletions(-)
>>
>> diff --git a/drivers/md/raid10.c b/drivers/md/raid10.c
>> index 840f0446c231..4bc1d5553ec7 100644
>> --- a/drivers/md/raid10.c
>> +++ b/drivers/md/raid10.c
>> @@ -1493,10 +1493,8 @@ static bool raid10_write_request(struct mddev *mddev, struct bio *bio,
>>   		if (atomic)
>>   			goto err_handle;
>>   
>> -		allow_barrier(conf);
>>   		bio = bio_submit_split_bioset(bio, r10_bio->sectors,
>>   					      &conf->bio_split);
>> -		wait_barrier(conf, false);
>>   		if (!bio) {
>>   			set_bit(R10BIO_Returned, &r10_bio->state);
>>   			goto err_handle;
>
> -- 
> Thanks,
> Kuai

-- 
Best Regards,
Abd-Alrhman

^ permalink raw reply

* Re: [PATCH] md/raid1: honor REQ_NOWAIT when waiting for behind writes
From: Abd-Alrhman Masalkhi @ 2026-06-24  8:08 UTC (permalink / raw)
  To: yu kuai, song, magiclinan, xiao, vverma, axboe
  Cc: linux-raid, linux-kernel, yukuai
In-Reply-To: <868207d0-d20f-42e8-8257-f57816987bf5@fygo.io>

On Wed, Jun 24, 2026 at 14:39 +0800, yu kuai wrote:
> Hi,
>
> 在 2026/6/22 2:08, Abd-Alrhman Masalkhi 写道:
>> What if on a partial nowait failure we just end the master bio as
>> success, but set NEEDED on that chunk's bitmap counter and start_sync()
>> picks it up for resync? That way we don't have to decide why rdev2
>> failed at all, resync just copies from rdev1 to rdev2 without nowait,
>> so if it's a real bad block, end_sync_write() records it then.
>>
>> We kinda have the idea of ending the bio before the write lands on all
>> mirrors in write-behind already, though it's not quite the same, there
>> the deferred write still lands, here we ACK after it already failed and
>> lean on resync to redo it.
>>
>> My worry is the loaded case: AGAIN under queue pressure isn't that rare,
>> so we might end up triggering resync frequently. Do you think that's
>> acceptable, or is dropping nowait better? Happy to prototype either way.
>
> Yes, AGAIN under queue pressure isn't rare, and I don't think trigger resync
> for a nowait IO failure is acceptable. This can cause lots of offline IO
> pressure which will affect disk service life. Meanwhile, resync will cause
> performance degradation for user.
>
> I still feel dropping nowait is better.
>

That makes sense. I'll drop nowait for md and post a patch.

> -- 
> Thanks,
> Kuai

-- 
Best Regards,
Abd-Alrhman

^ permalink raw reply

* Re: [PATCH v2] md/raid5-ppl: fix use-after-free in ppl_do_flush()
From: Dan Carpenter @ 2026-06-24  8:07 UTC (permalink / raw)
  To: Brigham Campbell
  Cc: Sajal Gupta, linux-raid, song, yukuai3, tomasz.majchrzak,
	linux-kernel, skhan, linux-kernel-mentees
In-Reply-To: <DJH0687PNY2P.1WOW0ATJ2KZA9@brighamcampbell.com>

On Tue, Jun 23, 2026 at 10:42:47PM -0600, Brigham Campbell wrote:
> On Mon Jun 22, 2026 at 8:06 AM MDT, Sajal Gupta wrote:
> > Compile tested only.
> 
> It looks like you're on the right track, but this could use some
> testing. My analysis here may be incorrect, but it looks like it should
> be pretty easy to test this patch by compiling and running on a system
> with a RAID5 array, PPL enabled, and no RAID journal. I expect the call
> stack would look something like the following (feel free to correct me,
> anyone...):

Heh...  That doesn't sound easy at all.  (0_0)

I just left this one because it's not really a big deal.  It probably
isn't even a real bug.  We call increment the refcount in a loop and
then decrement it in another loop.  It's not the right way.  Sajal's
first approach is the right direction this should go but *that* patch
would require testing.

Adding a break here doesn't require testing because it can't possibly
break anything which is not already broken.

regards,
dan carpenter

^ permalink raw reply

* [PATCH v3] md/raid5: fix reshape deadlock while failed devices more than max degraded
From: Chen Cheng @ 2026-06-24  7:58 UTC (permalink / raw)
  To: linux-raid, yukuai, yukuai; +Cc: chencheng, linux-kernel

From: Chen Cheng <chencheng@fnnas.com>

reshape stripe lifetime:
- start reshape ==> reshape_request():
	* get destination stripe,
	  - if need to copy source data chunks, set STRIPE_EXPANDING;
	  - or, if new regions past the old end of the array, zero-filled,
	    no need source data, set STRIPE_EXPANDING | STRIPE_READY
	* get source stripe,
	  - set STRIPE_EXPAND_SOURCE

- handle expand stripe ==> handle_stripe():
	reshape use reconstruct-write to construct stripe,
	four stages:
	1. prepare source data chunks for old geometry stripe
		- fill source stripe data by read or compute
	2. move data from old geometry source stripe to new geometry
	   destination stripe
		- source stripe clear STRIPE_EXPAND_SOURCE
		- drain data from source to destination stripe
		- mark stripe chunk as R5_Expanded|R5_UPTODATE when the
		  drain from source chunk to destionation chunk is completed
		- all stripe chunks drain are completed, then mark
		  STRIPE_EXPAND_READY
	3. calculate p/q chunks for destination stripe
		- if destination stripe does't depends on source dstripe,
		  then we can clear STRIPE_EXPANDING
	4. write-out to disks and release
		- set R5_Wantwrite|R5_Locked, writeout to disk
		- if write-out successed, clear STRIPE_EXPAND_READY, and
		  decrement reshape_stripe, call md_done_sync() to report
		  reshape progress.

1. cleanup the following kinds of **destination stripe**
	when failed device more than max degraded:
  - new regions past the old end of the array, zero-filled in place,
    requires no source data.
	(STRIPE_EXPANDING | STRIPE_EXPAND_READY)
  - prepare source data chunks already done, and writeout failed
	(STRIPE_EXPAND_READY)

2. destination stripes that need source data
	(STRIPE_EXPANDING, no STRIPE_HANDLE)
  - these kind of stripes sit idle in the stripe cache and are never seen
    by handle_stripe(). So clean up indirectly when thier source stripe
    (type 3) is processed.

3. source stripes (STRIPE_EXPAND_SOURCE)
  - hit handle_stripe() after thier member disks are markded Faulty.
  - clear STRIPE_EXPAND_SOURCE, finds and cleanup all dependent destination
    stripes that were waiting for data.
  - walks the source's data disks, compute the corresponding destination
    sector, looks up the destination stripe, and do cleanup(clear flags,
    dec counters, call md_done_sync())

Reproducer:
  - Create a 4-disk RAID5 with mdadm on top of 5 disposable test disks
    wrapped by dm targets.
  - Add the 5th device as a spare and start a 4 -> 5 reshape.
  - Wait until /sys/block/mdX/md/sync_action reports "reshape".
  - Inject failures on two members so reshape exceeds max_degraded.
  - After a few seconds, write "frozen" to /sys/block/mdX/md/sync_action.
    Before this fix, the write blocks indefinitely.

Read-error variant:
  - Use dm-dust on /dev/sd[b-f].
  - Preload bad blocks on two source members, e.g. dust0 and dust1:
      dmsetup message dust0 0 addbadblock <range>
      dmsetup message dust1 0 addbadblock <range>
  - Start reshape:
      mdadm -C /dev/mdX -e 1.2 -l 5 -n 4 -c 64 --assume-clean /dev/mapper/dust{0..3}
      mdadm --manage /dev/mdX --add /dev/mapper/dust4
      mdadm --grow /dev/mdX -n 5 --backup-file=/tmp/grow.backup &
  - Once reshape starts, enable the injected read failures:
      dmsetup message dust0 0 enable
      dmsetup message dust1 0 enable
  - Then:
      echo frozen > /sys/block/mdX/md/sync_action
    hangs forever before the fix.

Write-error variant:
  - Use dm-flakey on /dev/sd[b-f].
  - Start the same 4 -> 5 reshape on flakey0..flakey4.
  - Once reshape starts, switch two members, e.g. flakey3 and flakey4,
    to error_writes.
  - Then:
      echo frozen > /sys/block/mdX/md/sync_action
    hangs forever before the fix.

md_do_sync() exits its main loop on MD_RECOVERY_INTR but then blocks
forever at:

  wait_event(mddev->recovery_wait,
		!atomic_read(&mddev->recovery_active));

After the fix recovery_active drains to zero, md_do_sync() prints

    md/raid:md0: Cannot continue operation (2/5 failed).
    md: md0: reshape interrupted.

v2 -> v3:
- just kick sashiko-bot to review my patch..

changes v1 -> v2:
- handle reshape write deadlock while failed devices more than max degraded

Signed-off-by: Chen Cheng <chencheng@fnnas.com>
---
 drivers/md/raid5.c | 74 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 74 insertions(+)

diff --git a/drivers/md/raid5.c b/drivers/md/raid5.c
index 65ae7d8930fc..a320b71d7117 100644
--- a/drivers/md/raid5.c
+++ b/drivers/md/raid5.c
@@ -3728,10 +3728,82 @@ handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
 
 	if (abort)
 		md_sync_error(conf->mddev);
 }
 
+/*
+ * handle_failed_reshape - handl failed stripes when reshape failed and
+ *			   degraded devices >= max_degraded
+ *
+ * handle following kinds of stripe:
+ * 1. cleanup the following kinds of destination stripe:
+ *	- new regions past the old end of the array, zero-filled in place,
+ *	  requires no source data.
+ *		(STRIPE_EXPANDING | STRIPE_EXPAND_READY)
+ *	- prepare source data chunks already done, and writeout failed
+ *		(STRIPE_EXPAND_READY)
+ * 2. dest stripes that need source data (STRIPE_EXPANDING, no STRIPE_HANDLE)
+ *   - these kind of stripes sit idle in the stripe cache and are never seen
+ *     by handle_stripe(). So clean up indirectly when thier source stripe
+ *     (type 3) is processed.
+ * 3. src stripes (STRIPE_EXPAND_SOURCE)
+ *   - hit handle_stripe() after thier member disks are markded Faulty.
+ *   - clear STRIPE_EXPAND_SOURCE, finds and cleanup all dependent destination
+ *     stripes that were waiting for data.
+ *   - walks the source's data disks, compute the corresponding destination
+ *     sector, looks up the destination stripe, and do cleanup(clear flags,
+ *     dec counters, call md_done_sync())
+ */
+static void handle_failed_reshape(struct r5conf *conf, struct stripe_head *sh,
+				  struct stripe_head_state *s)
+{
+	int i;
+	bool was_expanding = test_and_clear_bit(STRIPE_EXPANDING, &sh->state);
+	bool was_ready = test_and_clear_bit(STRIPE_EXPAND_READY, &sh->state);
+
+	if (was_expanding || was_ready) {
+		atomic_dec(&conf->reshape_stripes);
+		wake_up(&conf->wait_for_reshape);
+		md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf));
+	}
+
+	s->expanded = 0;
+	s->expanding = 0;
+
+	/* release the destination stripes that are waiting to be filled */
+	if (test_and_clear_bit(STRIPE_EXPAND_SOURCE, &sh->state)) {
+		for (i = 0; i < sh->disks; i++) {
+			int dd_idx;
+			struct stripe_head *sh2;
+			sector_t bn, sec;
+
+			if (i == sh->pd_idx)
+				continue;
+			if (conf->level == 6 && i == sh->qd_idx)
+				continue;
+
+			bn = raid5_compute_blocknr(sh, i, 1);
+			sec = raid5_compute_sector(conf, bn, 0, &dd_idx, NULL);
+			sh2 = raid5_get_active_stripe(conf, NULL, sec,
+					R5_GAS_NOBLOCK | R5_GAS_NOQUIESCE);
+			if (!sh2)
+				continue;
+
+			if (test_and_clear_bit(STRIPE_EXPANDING, &sh2->state)) {
+				atomic_dec(&conf->reshape_stripes);
+				wake_up(&conf->wait_for_reshape);
+				md_done_sync(conf->mddev,
+					     RAID5_STRIPE_SECTORS(conf));
+			}
+
+			clear_bit(STRIPE_EXPAND_READY, &sh2->state);
+
+			raid5_release_stripe(sh2);
+		}
+	}
+}
+
 static int want_replace(struct stripe_head *sh, int disk_idx)
 {
 	struct md_rdev *rdev;
 	int rv = 0;
 
@@ -5001,10 +5073,12 @@ static void handle_stripe(struct stripe_head *sh)
 		break_stripe_batch_list(sh, 0);
 		if (s.to_read+s.to_write+s.written)
 			handle_failed_stripe(conf, sh, &s, disks);
 		if (s.syncing + s.replacing)
 			handle_failed_sync(conf, sh, &s);
+		if (s.expanding + s.expanded)
+			handle_failed_reshape(conf, sh, &s);
 	}
 
 	/* Now we check to see if any write operations have recently
 	 * completed
 	 */
-- 
2.54.0

^ permalink raw reply related

* Re: [PATCH v2 20/20] md/raid5: split reshape bios before bitmap accounting
From: sashiko-bot @ 2026-06-24  7:29 UTC (permalink / raw)
  To: Yu Kuai; +Cc: linux-raid, yukuai
In-Reply-To: <f4bcf3a6cdb16689c42f2f5b5bb6b5dca0c84768.1782282042.git.yukuai@kernel.org>

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

New issues:
- [Critical] Splitting a bio in `raid5_make_request()` breaks the `STRIPE_WAIT_RESHAPE` retry logic, causing a double-submission of the remainder and a permanent leak of the split front.

Pre-existing issues:
- [High] `make_discard_request()` leaks the `REQ_OP_DISCARD` bio without completion if an array is reshaping or `REQ_NOWAIT` is set.
--

commit fd0cb884709b54fc9c1fe1f70aa2016108b2a998
Author: Yu Kuai <yukuai@fygo.io>

md/raid5: split reshape bios before bitmap accounting

The commit uses mddev_bio_split_at_reshape_offset() in
raid5_make_request() to split bios at the reshape offset. This ensures
that RAID5 submits only one-side bios to llbitmap during reshape.

> diff --git a/drivers/md/raid5.c b/drivers/md/raid5.c
> index ac7ea483502fd..fb346a3c4aa3b 100644
> --- a/drivers/md/raid5.c
> +++ b/drivers/md/raid5.c
> @@ -6181,6 +6181,14 @@ static bool raid5_make_request(struct mddev *mddev, struct bio * bi)

[ ... ]

>  		return true;
>  	}
>  

[Severity: High]
This is a pre-existing issue, but is it possible for the discard bio to be
leaked if the array is reshaping or REQ_NOWAIT is set?

In make_discard_request() which is called just above this context, it returns
early without completing the bio:

    if (WARN_ON_ONCE(bi->bi_opf & REQ_NOWAIT))
        return;

    if (mddev->reshape_position != MaxSector)
        return;

Since raid5_make_request() calls make_discard_request() and then unconditionally
returns true, does this strand the bio and cause indefinite hangs?

> +	bi = mddev_bio_split_at_reshape_offset(mddev, bi, NULL,
> +					       &conf->bio_split);

[Severity: Critical]
Does splitting the bio here break the STRIPE_WAIT_RESHAPE retry logic and cause
a double-submission and memory leak?

When mddev_bio_split_at_reshape_offset() splits the bio, it submits the
remainder via bio_submit_split_bioset() and returns the front half as the
new bi.

Later in raid5_make_request(), if make_stripe_request() hits the reshape window
and returns STRIPE_WAIT_RESHAPE, it handles the retry:

    if (res == STRIPE_WAIT_RESHAPE) {
        DECLARE_COMPLETION_ONSTACK(done);
        WRITE_ONCE(bi->bi_private, &done);
        bio_endio(bi);
        wait_for_completion(&done);
        return false;
    }

When false is returned, md_handle_request() loops and retries the original
bio pointer.

However, the original bio was already submitted as the remainder by the split
operation. Will this result in concurrently submitting the remainder twice?

Additionally, when completing the cloned front half (bi) with the completion
flag, md_end_clone_io() does not complete the original split bio, which
permanently leaks the front half.

> +	if (!bi) {
> +		if (rw == WRITE)
> +			md_write_end(mddev);
> +		return true;
> +	}
> +
>  	logical_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
>  	bi->bi_next = NULL;
>

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=20

^ permalink raw reply

* Re: [PATCH v2 18/20] md/raid5: reject llbitmap reshape when md chunk shrinks
From: sashiko-bot @ 2026-06-24  7:24 UTC (permalink / raw)
  To: Yu Kuai; +Cc: linux-raid, yukuai
In-Reply-To: <9b06d3a655f709b35ab10995a872b30d2026f7c3.1782282042.git.yukuai@kernel.org>

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

New issues:
- [High] The validation in `check_reshape` fails to reject reshapes that decrease the number of data disks (`mddev->delta_disks < 0`) for llbitmap, leaving an identical bitmap coverage truncation vulnerability to the one the patch attempts to fix.

Pre-existing issues:
- [High] Writing 0 or a very small/overflowing value to the `chunk_size` sysfs attribute bypasses chunk size validation, leading to a divide-by-zero kernel panic during reshape.
- [High] Pre-existing memory leak of `stripe_head` pages in `resize_stripes()` if array reshape initialization fails.
--

commit cd96767f06f730181f5e43d1d52815ff0535ad82
Author: Yu Kuai <yukuai@fygo.io>

md/raid5: reject llbitmap reshape when md chunk shrinks
    
llbitmap reshape keeps one live bitmap and cannot safely make an
existing bitmap bit cover a smaller data range.

The llbitmap chunksize itself will not shrink when mddev->chunk_sectors
stays the same or grows. However, shrinking mddev->chunk_sectors shrinks
sectors_per_chunk used by raid5_bitmap_sector_map(). That can shrink the
effective data range covered by each bit across the old and new RAID5
geometry. Reject that reshape while llbitmap is active.

> diff --git a/drivers/md/raid5.c b/drivers/md/raid5.c
> index 1613a42cc25dc..9de648f75dd04 100644
> --- a/drivers/md/raid5.c
> +++ b/drivers/md/raid5.c
> @@ -8506,6 +8506,9 @@ static int check_reshape(struct mddev *mddev)
>  	if (!check_stripe_cache(mddev))
>  		return -ENOSPC;
>  
> +	if (mddev->bitmap_id == ID_LLBITMAP &&
> +	    mddev->new_chunk_sectors < mddev->chunk_sectors)
> +		return -EOPNOTSUPP;

[Severity: High]
Does this validation fully address the logical coverage truncation?

The commit message correctly notes that shrinking mddev->chunk_sectors shrinks
sectors_per_chunk, which is unsafe for llbitmap because it shrinks the
effective data range covered by each bit.

However, sectors_per_chunk is also reduced if mddev->delta_disks < 0:

sectors_per_chunk = chunk_sectors * (raid_disks - max_degraded);

Since the validation here only checks if the new chunk sectors are smaller,
a reshape that reduces the number of data disks could bypass this check,
resulting in the exact same logical coverage truncation vulnerability.

Could this be updated to also check mddev->delta_disks < 0, or compute the
product to verify sectors_per_chunk does not shrink?

>  	if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
>  	    mddev->delta_disks > 0)

[Severity: High]
This is a pre-existing issue, but writing 0 or a very small value to the
chunk_size sysfs attribute appears to bypass chunk size validation entirely,
leading to a divide-by-zero panic during reshape.

In drivers/md/md.c:chunk_size_store(), user input is right-shifted by 9
to compute mddev->new_chunk_sectors. If the user writes 0, it becomes 0.

When raid5_check_reshape() is called:

drivers/md/raid5.c:raid5_check_reshape() {
    ...
	if (new_chunk > 0) {
		if (!is_power_of_2(new_chunk))
			return -EINVAL;
    ...
}

Because the checks are inside if (new_chunk > 0), a value of 0 skips the
sanity bounds. check_reshape() then accepts it.

Later, in raid5_compute_sector(), this chunk size causes a kernel panic:

drivers/md/raid5.c:raid5_compute_sector() {
    ...
	chunk_offset = sector_div(r_sector, sectors_per_chunk);
    ...
}

Should chunk_size_store() or raid5_check_reshape() explicitly prevent a
chunk size of 0?

>  		if (resize_chunks(conf,
>  				  conf->previous_raid_disks
>  				  + max(0, mddev->delta_disks),
>  				  max(mddev->new_chunk_sectors,
>  				      mddev->chunk_sectors)
>  			    ) < 0)
>  			return -ENOMEM;
> 
>  	if (conf->previous_raid_disks + mddev->delta_disks <= conf->pool_size)
>  		return 0; /* never bother to shrink */
>  	return resize_stripes(conf, (conf->previous_raid_disks
>  				     + mddev->delta_disks));
>  }

[Severity: High]
This isn't a bug introduced by this patch, but is it possible for
resize_stripes() to leak the stripe_head pages if the array reshape
initialization fails?

If the array reshape fails under memory pressure during step 3 of
resize_stripes() (for example, the ndisks allocation fails), the function
structurally proceeds to step 4 without aborting:

drivers/md/raid5.c:resize_stripes() {
    ...
		for (i=conf->raid_disks; i < newsize; i++)
			if (nsh->dev[i].page == NULL) {
				struct page *p = alloc_page(GFP_NOIO);
				nsh->dev[i].page = p;
    ...
}

It loops up to newsize and allocates physical pages for the expanded stripe
slots. At the end of the function, because err is set, it skips updating
conf->pool_size:

drivers/md/raid5.c:resize_stripes() {
    ...
	if (!err)
		conf->pool_size = newsize;
    ...
}

Since conf->pool_size is unchanged, any future teardown via shrink_buffers()
will intentionally ignore the newly allocated pages at indices >= pool_size.
When free_stripe() subsequently destroys the slab object without freeing these
pages, they appear to be permanently leaked.

Is there a mechanism that cleans up these orphaned pages if conf->pool_size
is not updated?

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=18

^ permalink raw reply

* Re: [PATCH 4/7] md/raid10: raid10_write_request() drops the barrier before calling
From: yu kuai @ 2026-06-24  7:23 UTC (permalink / raw)
  To: Abd-Alrhman Masalkhi, song, magiclinan, xiao, axboe, john.g.garry,
	martin.petersen, yukuai
  Cc: linux-raid, linux-kernel
In-Reply-To: <20260623072456.333437-5-abd.masalkhi@gmail.com>

Hi,

在 2026/6/23 15:24, Abd-Alrhman Masalkhi 写道:
> bio_submit_split_bioset() and reacquires it afterwards. This is
> unnecessary because bio_submit_split_bioset() does not require
> releasing the barrier protection.

Why is this safe?

It's possible plug is not enabled in this context, and the allocated new
aplit bio will be submitted and enter wait_barrier() again. wait_barrier()
is not supposed to be called recursively. Otherwise deadlock can happend:

t1: sync_thread grab barrier and waiting for nr_pending to be 0 from raise_barrier()
t2: wait_barrier() first inc nr_pending, then recursive wait_barrier() waiting
for barrier to be released.

>
> Remove the redundant allow_barrier()/wait_barrier() pair around
> bio_submit_split_bioset().
>
> Signed-off-by: Abd-Alrhman Masalkhi <abd.masalkhi@gmail.com>
> ---
>   drivers/md/raid10.c | 2 --
>   1 file changed, 2 deletions(-)
>
> diff --git a/drivers/md/raid10.c b/drivers/md/raid10.c
> index 840f0446c231..4bc1d5553ec7 100644
> --- a/drivers/md/raid10.c
> +++ b/drivers/md/raid10.c
> @@ -1493,10 +1493,8 @@ static bool raid10_write_request(struct mddev *mddev, struct bio *bio,
>   		if (atomic)
>   			goto err_handle;
>   
> -		allow_barrier(conf);
>   		bio = bio_submit_split_bioset(bio, r10_bio->sectors,
>   					      &conf->bio_split);
> -		wait_barrier(conf, false);
>   		if (!bio) {
>   			set_bit(R10BIO_Returned, &r10_bio->state);
>   			goto err_handle;

-- 
Thanks,
Kuai

^ permalink raw reply

* Re: [PATCH v2 15/20] md/raid10: wire llbitmap reshape lifecycle
From: sashiko-bot @ 2026-06-24  7:22 UTC (permalink / raw)
  To: Yu Kuai; +Cc: yukuai, linux-raid
In-Reply-To: <54625332edcdb5f009fb0920220ea12aa696f408.1782282042.git.yukuai@kernel.org>

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] raid10_start_reshape skips initializing llbitmap's reshape geometry, causing bitmap corruption during and after reshape.
- [Low] Hardcoded check for `ID_LLBITMAP` in `raid10_finish_reshape` breaks the polymorphism of `mddev->bitmap_ops`.
--

commit 84732a3d166ed5b144ce82fb596703bb8b35f73c
Author: Yu Kuai <yukuai@fygo.io>

md/raid10: wire llbitmap reshape lifecycle

Prepare llbitmap before RAID10 starts growing, checkpoint the bitmap
before advancing reshape_position, finish the llbitmap geometry update
when reshape completes, and export the old and new tracked sizes.

> diff --git a/drivers/md/raid10.c b/drivers/md/raid10.c
> index 1242b8d3bb6bd..e50e4adee389f 100644
> --- a/drivers/md/raid10.c
> +++ b/drivers/md/raid10.c
> @@ -4394,6 +4394,12 @@ static int raid10_start_reshape(struct mddev *mddev)
>  
>  	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
>  		return -EBUSY;
> +	if (md_bitmap_enabled(mddev, false) &&
> +	    mddev->bitmap_ops->reshape_can_start) {
> +		ret = mddev->bitmap_ops->reshape_can_start(mddev);
> +		if (ret)
> +			return ret;
> +	}

[Severity: High]
Does this fully wire up the llbitmap reshape lifecycle?

Further down in raid10_start_reshape(), the call to mddev->bitmap_ops->resize()
is gated by `if (mddev->delta_disks && mddev->bitmap)`.

If a reshape is started that only grows the chunk size (where
mddev->delta_disks == 0), won't this skip initializing the llbitmap's reshape
geometry?

If resize() is bypassed, llbitmap->reshape_chunksize would remain at the old
chunk size, causing llbitmap_encode_range() for the new layout to map IOs
using the old chunk size. Could this set bits for incorrect regions, leading
to dirty data not being tracked properly and silent data corruption upon
array recovery?

[ ... ]

> @@ -5039,10 +5062,15 @@ static void end_reshape_request(struct r10bio *r10_bio)
>  static void raid10_finish_reshape(struct mddev *mddev)
>  {
>  	struct r10conf *conf = mddev->private;
> +	bool llbitmap = mddev->bitmap_id == ID_LLBITMAP &&
> +		md_bitmap_enabled(mddev, false);
>  
>  	if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
>  		return;
>  
> +	if (llbitmap && mddev->bitmap_ops->reshape_finish)
> +		mddev->bitmap_ops->reshape_finish(mddev);

[Severity: Low]
Is this hardcoded check for ID_LLBITMAP necessary?

By explicitly checking mddev->bitmap_id, this seems to defeat the polymorphism
of mddev->bitmap_ops. If another bitmap implementation introduces
reshape_finish(), wouldn't it be silently ignored?

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=15

^ permalink raw reply

* Re: [PATCH v2 16/20] md/raid10: split reshape bios before bitmap accounting
From: sashiko-bot @ 2026-06-24  7:20 UTC (permalink / raw)
  To: Yu Kuai; +Cc: yukuai, linux-raid
In-Reply-To: <afeb48e05a8925b52e9def6bab1b0ca1e87c4aa0.1782282042.git.yukuai@kernel.org>

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Missing `md_write_end()` on `mddev_bio_split_at_reshape_offset()` failure path causes `writes_pending` leak.
- [Medium] Lockless read of `mddev->reshape_position` can result in a torn read on 32-bit architectures, leading to incorrect bio splitting.
--

commit 2a6f82a757276f6bbae0c22cb819c9c6d6b3e4b0
Author: Yu Kuai <yukuai@fygo.io>

md/raid10: split reshape bios before bitmap accounting

Use the shared mddev_bio_split_at_reshape_offset() helper so RAID10
submits only one-side bios to llbitmap during reshape.

> diff --git a/drivers/md/raid10.c b/drivers/md/raid10.c
> --- a/drivers/md/raid10.c
> +++ b/drivers/md/raid10.c
> @@ -1911,6 +1911,12 @@ static bool raid10_make_request(struct mddev *mddev, struct bio *bio)
>  		sectors = chunk_sects -
>  			(bio->bi_iter.bi_sector &
>  			 (chunk_sects - 1));
> +
> +	bio = mddev_bio_split_at_reshape_offset(mddev, bio, &sectors,
> +						&conf->bio_split);

[Severity: Medium]
Can the lockless read of mddev->reshape_position inside this helper
result in a torn read on 32-bit architectures?

In mddev_bio_split_at_reshape_offset(), mddev->reshape_position (a 64-bit
sector_t) is read without READ_ONCE() or a seqcount:

drivers/md/md.c:mddev_bio_split_at_reshape_offset() {
    ...
    boundary = mddev->reshape_position;
    ...
}

On 32-bit systems, could racing with the reshape thread's update (for
example, at the 2TB boundary) tear the 64-bit load and yield a garbage
sector value?

If so, this might cause bio_split to slice the bio at an unaligned offset,
leading to IO errors when the underlying block device rejects it.

> +	if (!bio)
> +		return true;

[Severity: High]
Does this early return bypass the md_write_end() cleanup required to
balance the earlier md_write_start() for write requests?

If mddev_bio_split_at_reshape_offset() fails and returns NULL, it appears
the writes_pending percpu reference is leaked.

Will this prevent the array from reaching the clean safemode state, causing
it to perpetually appear dirty and trigger a full resync on the next
assembly?

> +
>  	if (!__make_request(mddev, bio, sectors))
>  		md_write_end(mddev);
>

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=16

^ permalink raw reply

* Re: [PATCH v2 19/20] md/raid5: wire llbitmap reshape lifecycle
From: sashiko-bot @ 2026-06-24  7:20 UTC (permalink / raw)
  To: Yu Kuai; +Cc: linux-raid, yukuai
In-Reply-To: <55686793056df8053d1797d22c18fce8df7eebe8.1782282042.git.yukuai@kernel.org>

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Critical] Checkpointing the translated llbitmap to disk before the MD superblock is updated creates a crash window that leads to silent data corruption on restart.
- [Critical] The llbitmap page control array (`llbitmap->pctl`) can be accessed after being freed during RAID5 reshape initialization because the bitmap resize happens before the array is quiesced.
--

commit 18675e43f792016c6cde2f177af7a007c667120d
Author: Yu Kuai <yukuai@fygo.io>

md/raid5: wire llbitmap reshape lifecycle

Prepare llbitmap before RAID5 reshape starts, checkpoint the bitmap
before advancing reshape_position, and finish the llbitmap geometry
update when reshape completes.

> diff --git a/drivers/md/raid5.c b/drivers/md/raid5.c
> index 9de648f75dd04..ac7ea483502fd 100644
> --- a/drivers/md/raid5.c
> +++ b/drivers/md/raid5.c

[ ... ]

> @@ -6430,6 +6430,13 @@ static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *sk
>  			   || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
>  		if (atomic_read(&conf->reshape_stripes) != 0)
>  			return 0;
> +		if (md_bitmap_enabled(mddev, false) &&
> +		    mddev->bitmap_ops->reshape_mark &&
> +		    conf->reshape_safe != conf->reshape_progress) {
> +			mddev->bitmap_ops->reshape_mark(mddev, conf->reshape_safe,
> +						       conf->reshape_progress);
> +			mddev->bitmap_ops->unplug(mddev, true);
> +		}

[Severity: Critical]
Does checkpointing the translated llbitmap to disk before the MD superblock
is updated create a crash window that leads to silent data corruption on
restart?

During RAID5 reshape, the code translates the bitmap to the new layout via
reshape_mark() and flushes it to disk before asynchronously waking the MD
thread to update the superblock.

If the system crashes after the bitmap flush but before the superblock write
completes, the on-disk metadata will still point to the old reshape position
(reshape_safe), while the on-disk bitmap for the region 
[reshape_safe, reshape_progress] will be stored in the new layout.

On reboot, the array will resume the reshape from reshape_safe and
misinterpret the newly mapped bitmap bits as if they were in the old layout.
If the array is degraded during this restart, it might incorrectly assume the
parity for these sectors is in-sync and reconstruct missing data using
corrupted parity.

>  		mddev->reshape_position = conf->reshape_progress;
>  		mddev->curr_resync_completed = sector_nr;
>  		if (!mddev->reshape_backwards)

[ ... ]

> @@ -8571,6 +8585,12 @@ static int raid5_start_reshape(struct mddev *mddev)
>  			mdname(mddev));
>  		return -EINVAL;
>  	}
> +	if (md_bitmap_enabled(mddev, false) &&
> +	    mddev->bitmap_id == ID_LLBITMAP) {
> +		i = mddev->bitmap_ops->resize(mddev, mddev->dev_sectors, 0);
> +		if (i)
> +			return i;
> +	}

[Severity: Critical]
Can this resize operation trigger a use-after-free regression since it
occurs before raid5_quiesce() stops concurrent I/O?

In raid5_start_reshape(), mddev->bitmap_ops->resize() is called to prepare
the bitmap for the new geometry before raid5_quiesce() is invoked. This means
the array is not suspended, and concurrent I/O is actively being handled.

If the resize operation calls llbitmap_expand_pages() and frees the old
pctl array via kfree() without RCU synchronization, concurrent fast-path I/O
threads executing llbitmap_start_write() could locklessly dereference the
freed pointer array in llbitmap_raise_barrier().

>  
>  	atomic_set(&conf->reshape_stripes, 0);
>  	spin_lock_irq(&conf->device_lock);

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=19

^ permalink raw reply

* Re: [PATCH v2 17/20] md/raid5: add exact old and new llbitmap mapping helpers
From: sashiko-bot @ 2026-06-24  7:16 UTC (permalink / raw)
  To: Yu Kuai; +Cc: linux-raid, yukuai
In-Reply-To: <7f4f61a0c06d01b38b0a175ce5df9afe6450d09e.1782282042.git.yukuai@kernel.org>

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

New issues:
- [High] raid5_bitmap_array_sectors() incorrectly returns the new, smaller array size for the previous layout during a shrink reshape, leading to truncated bitmap tracking.

Pre-existing issues:
- [High] Invalid use of round_down() and round_up() with a non-power-of-2 sectors_per_chunk multiplier, causing corrupt bitmap mappings.
- [High] Bounding box calculation for mapping ranges between old and new layouts can overflow `unsigned long` on 32-bit systems, truncating dirty regions.
- [High] raid5_bitmap_sector_map() accesses reshape geometry parameters without holding the required sequence lock.
--

commit 7f0559d3994c9371245bbc6a23cf3ce1e8d48872
Author: Yu Kuai <yukuai@fygo.io>

md/raid5: add exact old and new llbitmap mapping helpers

Teach RAID5 to export exact old and new llbitmap mappings and the
corresponding sync and array sizes for reshape-aware bitmap users.

> diff --git a/drivers/md/raid5.c b/drivers/md/raid5.c
> index 0c5c9fb0606ee..1613a42cc25dc 100644
> --- a/drivers/md/raid5.c
> +++ b/drivers/md/raid5.c
[ ... ]
> @@ -5942,25 +5942,43 @@ static enum reshape_loc get_reshape_loc(struct mddev *mddev,
[ ... ]
> -static void raid5_bitmap_sector(struct mddev *mddev, sector_t *offset,
> -				unsigned long *sectors)
> +static void raid5_bitmap_sector_map(struct mddev *mddev, sector_t *offset,
> +				    unsigned long *sectors,
> +				    bool previous)
>  {
>  	struct r5conf *conf = mddev->private;
>  	sector_t start = *offset;
>  	sector_t end = start + *sectors;
> -	sector_t prev_start = start;
> -	sector_t prev_end = end;
>  	int sectors_per_chunk;
> -	enum reshape_loc loc;
>  	int dd_idx;
>  
> -	sectors_per_chunk = conf->chunk_sectors *
> -		(conf->raid_disks - conf->max_degraded);
> +	if (previous)
> +		sectors_per_chunk = conf->prev_chunk_sectors *
> +			(conf->previous_raid_disks - conf->max_degraded);
> +	else
> +		sectors_per_chunk = conf->chunk_sectors *
> +			(conf->raid_disks - conf->max_degraded);

[Severity: High]
This is a pre-existing issue, but does raid5_bitmap_sector_map() access
these reshape geometry parameters safely?

During a concurrent reshape operation (e.g., raid5_start_reshape()), these
configuration fields can be updated in-place. Without being protected by
read_seqcount_begin(&conf->gen_lock), could a concurrent I/O observe torn
state or a mismatch between chunk size and raid disks, leading to an
incorrect bitmap mapping?

>  	start = round_down(start, sectors_per_chunk);
>  	end = round_up(end, sectors_per_chunk);

[Severity: High]
This is a pre-existing issue, but do round_down() and round_up() work correctly
here when sectors_per_chunk is not a power of 2?

The round_down() and round_up() macros perform a bitwise masking operation
which strictly requires the multiplier to be a power of 2. Because the
number of data disks (raid_disks - max_degraded) is often not a power of 2
(for example, 3 data disks in a 4-disk RAID5), sectors_per_chunk is frequently
not a power of 2.

Will this bitwise mask silently corrupt the logical offsets instead of rounding
to stripe boundaries, leading to incorrect physical regions being tracked in
the bitmap?

> -	start = raid5_compute_sector(conf, start, 0, &dd_idx, NULL);
> -	end = raid5_compute_sector(conf, end, 0, &dd_idx, NULL);
> +	start = raid5_compute_sector(conf, start, previous, &dd_idx, NULL);
> +	end = raid5_compute_sector(conf, end, previous, &dd_idx, NULL);
> +	*offset = start;
> +	*sectors = end - start;
> +}
> +
> +static void raid5_bitmap_sector(struct mddev *mddev, sector_t *offset,
> +				unsigned long *sectors)
> +{
> +	struct r5conf *conf = mddev->private;
> +	sector_t start = *offset;
> +	sector_t end = start + *sectors;
> +	sector_t prev_start = start;
> +	unsigned long prev_sectors = end - start;
> +	enum reshape_loc loc;
> +
> +	raid5_bitmap_sector_map(mddev, &start, sectors, false);
> +	end = start + *sectors;
[ ... ]
> @@ -5987,7 +5998,7 @@ static void raid5_bitmap_sector(struct mddev *mddev, sector_t *offset,
>  	 * we set bits for both.
>  	 */
>  	*offset = min(start, prev_start);
> -	*sectors = max(end, prev_end) - *offset;
> +	*sectors = max(end, prev_start + prev_sectors) - *offset;

[Severity: High]
This isn't a bug introduced by this patch, but can this bounding box
calculation overflow on 32-bit systems?

When calculating the bounding box spanning the old and new physical layout
mappings for an I/O ahead of a reshape, the physical sector offsets diverge
linearly due to differing data disk counts.

For large arrays (e.g., >40TB), the gap between the mapped sectors can
exceed 2TB (4,294,967,295 sectors). Because *sectors is a pointer to
unsigned long (which is 32-bit on 32-bit architectures), could this
subtraction silently overflow, truncating the dirty region and potentially
missing necessary bits?

>  }
>  
>  static enum stripe_result make_stripe_request(struct mddev *mddev,
[ ... ]
> @@ -9049,6 +9060,20 @@ static void raid5_prepare_suspend(struct mddev *mddev)
>  	wake_up(&conf->wait_for_reshape);
>  }
>  
> +static sector_t raid5_bitmap_sync_size(struct mddev *mddev, bool previous)
> +{
> +	return mddev->dev_sectors;
> +}
> +
> +static sector_t raid5_bitmap_array_sectors(struct mddev *mddev, bool previous)
> +{
> +	struct r5conf *conf = mddev->private;
> +
> +	if (previous)
> +		return raid5_size(mddev, 0, 0);

[Severity: High]
Does passing 0 for raid_disks in raid5_size() incorrectly truncate the array
size for the previous layout?

During an array shrink reshape (e.g., from 5 disks to 4), passing 0 forces
raid5_size() to use the minimum disk count between the old and new layouts.
This would return the new, smaller array size instead of the exact previous
layout's size.

Since reshape-aware bitmap users rely on this limit to clip logical I/O
offsets, could I/Os mapping to the old unreshaped region beyond the new
limit be erroneously discarded, leading to dropped dirty bits?

> +	return raid5_size(mddev, mddev->dev_sectors, conf->raid_disks);
> +}

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=17

^ permalink raw reply

* Re: [PATCH v2 10/20] md/md-llbitmap: add reshape range mapping helpers
From: sashiko-bot @ 2026-06-24  7:08 UTC (permalink / raw)
  To: Yu Kuai; +Cc: linux-raid, yukuai
In-Reply-To: <8a47becf3100a3998e003afcdabce6c17c149194.1782282042.git.yukuai@kernel.org>

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] TOCTOU race on mddev->reshape_position causes bios to be mapped to the wrong geometry.
- [High] The resync threads use raw array sectors and blindly compute the bitmap bit index using the old geometry's chunkshift, completely ignoring reshape_chunksize for sectors residing in the new geometry.
--

commit a481d24ff8d12695efeabb7f320e930174126333
Author: Yu Kuai <yukuai@fygo.io>

md/md-llbitmap: add reshape range mapping helpers
    
Teach llbitmap to choose old versus new geometry during reshape and to
encode exact bitmap ranges for the active geometry.

This is the mapping groundwork for checkpoint remapping.

> diff --git a/drivers/md/md-llbitmap.c b/drivers/md/md-llbitmap.c
> index 11fede1fc79fd..d27993cfb13da 100644
> --- a/drivers/md/md-llbitmap.c
> +++ b/drivers/md/md-llbitmap.c

[ ... ]

> @@ -1376,11 +1433,32 @@ static void llbitmap_destroy(struct mddev *mddev)
>  	mutex_unlock(&mddev->bitmap_info.mutex);
>  }
>  
> +static bool llbitmap_map_previous(struct llbitmap *llbitmap, sector_t offset,
> +				  unsigned long sectors)
> +{
> +	struct mddev *mddev = llbitmap->mddev;
> +	sector_t boundary = mddev->reshape_position;
> +
> +	if (!llbitmap_reshaping(llbitmap))
> +		return false;

[Severity: High]
Can a concurrent reshape thread update mddev->reshape_position from MaxSector to
0 between reading it into boundary and the call to llbitmap_reshaping()?

If that happens, boundary holds MaxSector but llbitmap_reshaping() evaluates to
true. This would cause offset < MaxSector to evaluate to true, mapping the IO
to the new geometry before the array has actually reshaped the sector. Could
this race lead to data corruption?

> +
> +	WARN_ON_ONCE(sectors && offset < boundary && offset + sectors > boundary);
> +
> +	return mddev->reshape_backwards ? offset < boundary : offset >= boundary;
> +}

[ ... ]

> @@ -1549,7 +1627,11 @@ static bool llbitmap_blocks_synced(struct mddev *mddev, sector_t offset)
>  {
>  	struct llbitmap *llbitmap = mddev->bitmap;
>  	unsigned long p = offset >> llbitmap->chunkshift;

[Severity: High]
Does this unconditionally use the old chunkshift to compute the bit index from
the raw sync offset?

During an interrupted reshape recovery, active IO computes the correct bit index
using llbitmap_encode_range() for the new geometry. However, functions like
llbitmap_blocks_synced(), llbitmap_skip_sync_blocks(), and llbitmap_start_sync()
receive raw physical sectors from md_do_sync() and completely bypass
llbitmap_prepare_range().

If reshape_chunksize differs from chunksize, will the sync thread calculate the
wrong bit index, read a clean bit instead of the dirty bit marked by active IO,
and silently skip synchronizing the dirty sectors?

> -	enum llbitmap_state c = llbitmap_read(llbitmap, p);
> +	enum llbitmap_state c;
> +
> +	if (p >= llbitmap->chunks)
> +		return false;
> +	c = llbitmap_read(llbitmap, p);
>  
>  	return c == BitClean || c == BitDirty || c == BitCleanUnwritten;
>  }

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=10

^ permalink raw reply

* Re: [PATCH v2 07/20] md/md-llbitmap: track target reshape geometry fields
From: sashiko-bot @ 2026-06-24  7:07 UTC (permalink / raw)
  To: Yu Kuai; +Cc: yukuai, linux-raid
In-Reply-To: <5440f676d6637f4c0262862252191c2244363087.1782282042.git.yukuai@kernel.org>

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

Pre-existing issues:
- [High] Incomplete teardown of the `pending_timer` and `daemon_work` cycle in `llbitmap_destroy` leads to a Use-After-Free.
- [High] Concurrent array resize causes Use-After-Free on the `llbitmap->pctl` array due to lack of I/O suspension.
--

commit 2a89e33f120722b7687d6b24f4bf95273fa7a498
Author: Yu Kuai <yukuai@fygo.io>

md/md-llbitmap: track target reshape geometry fields

Track llbitmap bookkeeping for the target reshape geometry while keeping
a single live bitmap instance.

Add the reshape geometry fields, refresh helper, and update the load and
resize paths to keep the target geometry in sync.

> diff --git a/drivers/md/md-llbitmap.c b/drivers/md/md-llbitmap.c
> index 98e7824c7362e..cdced2126e975 100644
> --- a/drivers/md/md-llbitmap.c
> +++ b/drivers/md/md-llbitmap.c
> @@ -289,6 +289,9 @@ struct llbitmap {
>  	unsigned long chunks;
>  	/* total number of sectors tracked by current bitmap geometry */
>  	sector_t sync_size;
> +	unsigned long reshape_chunksize;
> +	unsigned long reshape_chunks;
> +	sector_t reshape_sync_size;
>  	unsigned long last_end_sync;
>  	/*
>  	 * time in seconds that dirty bits will be cleared if the page is not

[Severity: High]
This isn't a bug introduced by this patch, but is there a use-after-free risk
during llbitmap teardown?

If a user removes the bitmap via the location sysfs node,
llbitmap_destroy() deletes the pending_timer and flushes the I/O workqueue:

drivers/md/md-llbitmap.c:llbitmap_destroy() {
    ...
    timer_delete_sync(&llbitmap->pending_timer);
    flush_workqueue(md_llbitmap_io_wq);
    ...
}

However, it doesn't seem to set a shutdown flag to prevent re-arming.
If the daemon work is executing and finds unexpired dirty pages, it will set
restart = true and unconditionally re-arm the timer:

drivers/md/md-llbitmap.c:md_llbitmap_daemon_fn() {
    ...
    if (restart)
        mod_timer(&llbitmap->pending_timer,
                  jiffies + llbitmap->mddev->bitmap_info.daemon_sleep * HZ);
}

Once the work finishes, the flush_workqueue() call in llbitmap_destroy()
returns and the llbitmap structure is freed. Can the re-armed timer then
fire on the freed llbitmap structure?

[Severity: High]
This is a pre-existing issue, but can concurrent array resizing cause a
use-after-free on the llbitmap->pctl array?

When expanding the array size via sysfs, update_size() invokes the
personality resize hook without suspending the array:

drivers/md/md.c:update_size() {
    ...
    rv = mddev->pers->resize(mddev, num_sectors);
    ...
}

This eventually calls llbitmap_expand_pages(), which allocates a new
pointer array and immediately frees the old one:

drivers/md/md-llbitmap.c:llbitmap_expand_pages() {
    ...
    kfree(llbitmap->pctl);
    llbitmap->pctl = pctl;
    ...
}

Since update_size() only holds the mddev_lock and does not drain in-flight
I/O, new I/O can still be issued.

Could a concurrent I/O path calling llbitmap_raise_barrier() fetch the old
llbitmap->pctl array pointer just before it is freed:

drivers/md/md-llbitmap.c:llbitmap_raise_barrier() {
    struct llbitmap_page_ctl *pctl = llbitmap->pctl[page_idx];
    ...
}

and then dereference it, accessing freed memory?

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=7

^ permalink raw reply

* Re: [PATCH v2 13/20] md/md-llbitmap: clamp state-machine walks to tracked bits
From: sashiko-bot @ 2026-06-24  7:06 UTC (permalink / raw)
  To: Yu Kuai; +Cc: yukuai, linux-raid
In-Reply-To: <2f58279987b8b8b3f5b2ed8e563512524c530297.1782282042.git.yukuai@kernel.org>

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

Pre-existing issues:
- [Critical] llbitmap_cond_end_sync prematurely marks partially synced chunks as completed, risking data corruption and skipped resyncs.
--

commit e55ca490604a05215923d84a1b1272a73343ea48
Author: Yu Kuai <yukuai@fygo.io>

md/md-llbitmap: clamp state-machine walks to tracked bits

This commit adds bounds checking to llbitmap_state_machine() to prevent
walking past the tracked bitmap chunks. It ensures the state machine range
is clamped when the requested end bit exceeds the tracked boundary.

> diff --git a/drivers/md/md-llbitmap.c b/drivers/md/md-llbitmap.c
> index 00b77ecd600be..581ee9e4a3467 100644
> --- a/drivers/md/md-llbitmap.c
> +++ b/drivers/md/md-llbitmap.c
> @@ -983,7 +983,10 @@ static enum llbitmap_state llbitmap_state_machine(struct llbitmap *llbitmap,
>  		llbitmap_init_state(llbitmap);
>  		return BitNone;
>  	}
> -
> +	if (start >= llbitmap->chunks)
> +		return BitNone;
> +	if (end >= llbitmap->chunks)
> +		end = llbitmap->chunks - 1;
>  	while (start <= end) {

[Severity: Critical]
This is a pre-existing issue, but does the inclusive bound here cause
prematurely completed resyncs?

Looking at llbitmap_cond_end_sync(), it passes the current sector's chunk
index as the end bit:

drivers/md/md-llbitmap.c:llbitmap_cond_end_sync() {
    ...
    llbitmap_state_machine(llbitmap, 0, sector >> llbitmap->chunkshift,
                           BitmapActionEndsync);
    ...
}

Because the while loop condition is start <= end, the chunk currently
undergoing resync will be included in BitmapActionEndsync and transition to
BitDirty prematurely.

If start_sync() is subsequently called for the remainder of this chunk,
won't it see BitDirty and return false? This would cause the resync loop
to interpret it as no resync needed, skipping the rest of the chunk's
sectors and leaving them out of sync.

Should the end parameter be treated as exclusive instead, or does
llbitmap_cond_end_sync() need to subtract one from the end chunk when
sector is not aligned to the chunk size?

>  		enum llbitmap_state c = llbitmap_read(llbitmap, start);

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=13

^ permalink raw reply

* Re: [PATCH v2 12/20] md/md-llbitmap: remap checkpointed bits as reshape progresses
From: sashiko-bot @ 2026-06-24  7:04 UTC (permalink / raw)
  To: Yu Kuai; +Cc: linux-raid, yukuai
In-Reply-To: <8700112d660a7f9fa48d174ee9b395fbe309e7c9.1782282042.git.yukuai@kernel.org>

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Critical] In-place array modification during reshape overwrites un-reshaped source data before it can be read.
- [High] Non-atomic read-modify-write cycle in `llbitmap_reshape_merge` races with concurrent normal I/O, dropping `BitDirty` flags.
- [High] Missing handling for `BitNeedSyncUnwritten` and `BitCleanUnwritten` in `llbitmap_rmerge_state` silently demotes them.
- [High] The `level_456` condition in `llbitmap_rmerge_state` is completely ineffective and subsumed by the subsequent fallback.
--

commit a1307817c41ef916bb59f41a3af5b2d7a709caa2
Author: Yu Kuai <yukuai@fygo.io>

md/md-llbitmap: remap checkpointed bits as reshape progresses

Merge checkpointed old llbitmap state forward as reshape_position
advances and record the checkpoint remap through reshape_mark().

> diff --git a/drivers/md/md-llbitmap.c b/drivers/md/md-llbitmap.c
> index c62397743d9a0..00b77ecd600be 100644
> --- a/drivers/md/md-llbitmap.c
> +++ b/drivers/md/md-llbitmap.c

[ ... ]

> @@ -906,6 +914,33 @@ static int llbitmap_prepare_resize(struct llbitmap *llbitmap,
>  	return 0;
>  }
>  
> +static enum llbitmap_state
> +llbitmap_rmerge_state(struct llbitmap *llbitmap,
> +		      enum llbitmap_state dst,
> +		      enum llbitmap_state src)
> +{
> +	bool level_456 = raid_is_456(llbitmap->mddev);
> +
> +	if (dst == BitNeedSync || dst == BitSyncing ||
> +	    src == BitNeedSync || src == BitSyncing)
> +		return BitNeedSync;

[Severity: High]
Are BitNeedSyncUnwritten and BitCleanUnwritten states meant to be handled
here?

Because they do not match BitNeedSync, BitSyncing, BitDirty, or BitClean,
they fall through these conditions. If paired with BitClean, they
incorrectly evaluate to BitClean; otherwise, they fall through to
BitUnwritten. Both outcomes silently drop the sync requirement.

> +
> +	if (dst == BitDirty || src == BitDirty)
> +		return BitDirty;
> +
> +	/*
> +	 * Reshape generates valid target parity/data for both already-written
> +	 * and not-yet-written regions in the checkpointed range, so a mix of
> +	 * clean and unwritten still results in a clean destination bit.
> +	 */
> +	if (level_456 && ((dst == BitClean && src == BitUnwritten) ||
> +			  (src == BitClean && dst == BitUnwritten)))
> +		return BitClean;
> +	if (dst == BitClean || src == BitClean)
> +		return BitClean;

[Severity: High]
Does the fallback condition "dst == BitClean || src == BitClean" render the
preceding level_456 check dead code?

The fallback unconditionally forces any BitClean mix to BitClean, which
entirely overrides the level_456 restriction. Could this lead to RAID10
incorrectly resolving mixed BitClean and BitUnwritten states to BitClean,
causing skipped resync operations?

> +	return BitUnwritten;
> +}

[ ... ]

> +static void llbitmap_reshape_merge(struct llbitmap *llbitmap,
> +				   const struct llbitmap_reshape_range *old,
> +				   const struct llbitmap_reshape_range *new)
> +{
> +	unsigned long dst_start;
> +	unsigned long dst_end;
> +	unsigned long dst;
> +
> +	if (!new->sectors)
> +		return;
> +
> +	dst_start = div64_u64(new->offset, llbitmap->reshape_chunksize);
> +	dst_end = div64_u64(new->end - 1, llbitmap->reshape_chunksize);
> +
> +	for (dst = dst_start; dst <= dst_end; dst++) {
> +		struct llbitmap_reshape_range dst_range;
> +		struct llbitmap_reshape_range src;
> +		enum llbitmap_state state;
> +
> +		llbitmap_reshape_dst_range(llbitmap, dst, new, &dst_range);
> +		state = llbitmap_reshape_init_dst(llbitmap, dst, new);

[Severity: High]
Does this non-atomic read-modify-write cycle race with concurrent normal I/O?

llbitmap_reshape_init_dst() reads the chunk state, computes the merged state
through llbitmap_rmerge_src(), and writes it back via llbitmap_write() below
without being protected by locks.

Concurrent normal I/O operating on stripes outside the reshape window but
within the same bitmap chunk can set BitDirty. The llbitmap_reshape_merge()
thread will blindly overwrite this BitDirty flag with its locally computed
state, potentially causing silent data corruption due to lost BitDirty
flags.

> +		if (llbitmap_reshape_src_range(old, new, &dst_range, &src))
> +			state = llbitmap_rmerge_src(llbitmap, state, &src);
> +		else
> +			state = llbitmap_rmerge_state(llbitmap, state, BitUnwritten);
> +		llbitmap_write(llbitmap, state, dst);

[Severity: Critical]
Does writing directly to the shared pctl array overwrite un-reshaped source
data before it can be read?

When adding disks to a RAID5 array, new->sectors > old->sectors. This causes
the forward iteration of dst to outpace bit in llbitmap_rmerge_src()
(e.g., dst = 10, bit = 5).

Because llbitmap_write() updates the array in place, the state at index 5
is overwritten before it is read for dst = 10, destroying the original chunk
state.

> +	}
> +}

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=12

^ permalink raw reply

* Re: [PATCH v2 09/20] md/md-llbitmap: refuse reshape while llbitmap still needs sync
From: sashiko-bot @ 2026-06-24  7:04 UTC (permalink / raw)
  To: Yu Kuai; +Cc: linux-raid, yukuai
In-Reply-To: <fde37bced9be5e6b4d0f71cdd7d33d9387c022f6.1782282042.git.yukuai@kernel.org>

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] llbitmap_reshape_can_start() fails to reject reshape when chunks are in BitNeedSyncUnwritten or BitSyncingUnwritten states.
- [High] The newly introduced reshape_can_start callback is never invoked by the RAID5 subsystem, rendering the reshape refusal logic non-functional for RAID5/6.
--

commit fc17ecb84d03fe66b3e1048dc17b6b8022da7f9b
Author: Yu Kuai <yukuai@fygo.io>

md/md-llbitmap: refuse reshape while llbitmap still needs sync

Reject reshape when llbitmap still contains NeedSync or Syncing bits.

This keeps reshape from starting until the current llbitmap state has
been reconciled.

> diff --git a/drivers/md/md-llbitmap.c b/drivers/md/md-llbitmap.c
> index ae2e87fd58874..11fede1fc79fd 100644
> --- a/drivers/md/md-llbitmap.c
> +++ b/drivers/md/md-llbitmap.c
> @@ -1680,6 +1680,29 @@ static void llbitmap_dirty_bits(struct mddev *mddev, unsigned long s,
>  	llbitmap_state_machine(mddev->bitmap, s, e, BitmapActionStartwrite);
>  }
>  
> +static int llbitmap_reshape_can_start(struct mddev *mddev)
> +{
> +	struct llbitmap *llbitmap = mddev->bitmap;
> +	unsigned long chunk;
> +	int ret = 0;
> +
> +	if (!llbitmap)
> +		return 0;
> +
> +	mutex_lock(&mddev->bitmap_info.mutex);
> +	for (chunk = 0; chunk < llbitmap->chunks; chunk++) {
> +		enum llbitmap_state state = llbitmap_read(llbitmap, chunk);
> +
> +		if (state == BitNeedSync || state == BitSyncing) {

[Severity: High]
Should this check also include BitNeedSyncUnwritten and BitSyncingUnwritten
states?

Reshaping an array while it has regions pending or undergoing proactive parity
synchronization could change the array layout while the background sync process
is running, potentially leading to corrupt parity.

> +			ret = -EBUSY;
> +			break;
> +		}
> +	}
> +	mutex_unlock(&mddev->bitmap_info.mutex);
> +
> +	return ret;
> +}
> +

[ ... ]

> @@ -2002,6 +2025,7 @@ static struct bitmap_operations llbitmap_ops = {
>  	.dirty_bits		= llbitmap_dirty_bits,
>  	.prepare_range		= llbitmap_prepare_range,
>  	.reshape_finish		= llbitmap_reshape_finish,
> +	.reshape_can_start	= llbitmap_reshape_can_start,

[Severity: High]
Is the reshape_can_start callback invoked by the RAID5 subsystem when starting
a reshape?

Looking at raid5_start_reshape() in drivers/md/raid5.c:

    if (md_bitmap_enabled(mddev, false) &&
        mddev->bitmap_id == ID_LLBITMAP) {
        i = mddev->bitmap_ops->resize(mddev, mddev->dev_sectors, 0);

It doesn't appear to call mddev->bitmap_ops->reshape_can_start. This could
allow RAID5/6 arrays to start a reshape while the bitmap still contains
pending sync bits, causing the array layout to change before parity is
reconciled.

>  	.write_all		= llbitmap_write_all,
>  
>  	.groups			= md_llbitmap_groups,

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=9

^ permalink raw reply

* Re: [PATCH v2 02/20] md: skip bitmap accounting for empty write ranges
From: sashiko-bot @ 2026-06-24  7:04 UTC (permalink / raw)
  To: Yu Kuai; +Cc: yukuai, linux-raid
In-Reply-To: <d978c0c72c874d7033b0806a2dba255d6ff9e359.1782282042.git.yukuai@kernel.org>

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

Pre-existing issues:
- [High] Using `md_io_clone->start_time == 0` to check whether IO accounting was started is unsafe because `jiffies` can legitimately be exactly 0, permanently leaking the device's `in_flight` counter.
--

commit ff695222c639e0740f645b5e4a15298c468511f4
Author: Yu Kuai <yukuai@fygo.io>

md: skip bitmap accounting for empty write ranges

This commit updates md bitmap accounting to handle zero-sector flush/FUA bios.
It treats both naturally empty bios and ranges trimmed by the prepare_range
hook as not started, preventing the completion path from calling end_write()
on an empty range.

> diff --git a/drivers/md/md.c b/drivers/md/md.c
> index 3b20a57b8c7ed..0b59c676f7c03 100644
> --- a/drivers/md/md.c
> +++ b/drivers/md/md.c

[ ... ]

> @@ -9423,10 +9426,12 @@ static void md_clone_bio(struct mddev *mddev, struct bio **bio)
>  	md_io_clone = container_of(clone, struct md_io_clone, bio_clone);
>  	md_io_clone->orig_bio = *bio;
>  	md_io_clone->mddev = mddev;
> +	md_io_clone->sectors = 0;
>  	if (blk_queue_io_stat(bdev->bd_disk->queue))
>  		md_io_clone->start_time = bio_start_io_acct(*bio);

[Severity: High]
This isn't a bug introduced by this patch, but is it safe to use
md_io_clone->start_time as a boolean flag to track if IO accounting was
started?

Looking at bio_start_io_acct(), it returns the current jiffies value. If an
IO request is submitted exactly when the jiffies counter wraps to 0,
start_time will be set to 0.

When the IO completes, md_end_clone_io() evaluates the following condition:

    if (md_io_clone->start_time)
        bio_end_io_acct(orig_bio, md_io_clone->start_time);

If start_time happens to be 0, it skips bio_end_io_acct() and the block 
device's in_flight counter is permanently leaked. This prevents
is_mddev_idle() from ever returning true, which could permanently throttle
background sync operations until the system is rebooted.

> -	if (bio_data_dir(*bio) == WRITE && md_bitmap_enabled(mddev, false)) {
> +	if (bio_data_dir(*bio) == WRITE && bio_sectors(*bio) &&
> +	    md_bitmap_enabled(mddev, false)) {
>  		md_io_clone->offset = (*bio)->bi_iter.bi_sector;
>  		md_io_clone->sectors = bio_sectors(*bio);

[ ... ]

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=2

^ permalink raw reply

* Re: [PATCH v2 06/20] md/md-llbitmap: grow the page cache in place for reshape
From: sashiko-bot @ 2026-06-24  7:03 UTC (permalink / raw)
  To: Yu Kuai; +Cc: linux-raid, yukuai
In-Reply-To: <27639f9aceb3cb6d6d021df79f9f6839d916bb58.1782282042.git.yukuai@kernel.org>

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

New issues:
- [High] The `LLPageFlush` bit on existing cached pages is set during `llbitmap_flush()` but never cleared, permanently bypassing the barrier idle expiration timer and causing severe metadata write amplification.
- [High] Reallocating `llbitmap->pctl` locklessly in place causes a Use-After-Free for concurrent I/O paths and the background daemon.

Pre-existing issues:
- [High] An integer overflow in chunk size calculation on 32-bit systems causes a fatal divide-by-zero for extremely large arrays.
--

commit 06efa66cdd24523c6bea3b2de073842d179f3506
Author: Yu Kuai <yukuai@fygo.io>

md/md-llbitmap: grow the page cache in place for reshape

Use the page-control helpers to grow llbitmap's cached pages in place
for resize and later reshape preparation, instead of rebuilding the
whole cache.

> diff --git a/drivers/md/md-llbitmap.c b/drivers/md/md-llbitmap.c
> index 4c3fc4b35aff0..98e7824c7362e 100644
> --- a/drivers/md/md-llbitmap.c
> +++ b/drivers/md/md-llbitmap.c
> @@ -416,6 +416,19 @@ static char state_machine[BitStateCount][BitmapActionCount] = {
>  };
>  
>  static void __llbitmap_flush(struct mddev *mddev);
> +static void llbitmap_flush(struct mddev *mddev);
> +static void llbitmap_update_sb(void *data);
> +
> +static void llbitmap_calculate_chunks(struct mddev *mddev, sector_t blocks,
> +				      unsigned long *chunksize,
> +				      unsigned long *chunks)
> +{
> +	*chunks = DIV_ROUND_UP_SECTOR_T(blocks, *chunksize);
> +	while (*chunks > mddev->bitmap_info.space << SECTOR_SHIFT) {
> +		*chunksize = *chunksize << 1;
> +		*chunks = DIV_ROUND_UP_SECTOR_T(blocks, *chunksize);

[Severity: High]
This isn't a bug introduced by this patch, but since `chunksize` is an
`unsigned long` (32 bits on 32-bit architectures) and `blocks` is a 64-bit
`sector_t`, could the left shift push `*chunksize` past 31 bits and overflow
it to 0 for extremely large arrays?

If `*chunksize` becomes 0, does this cause a divide-by-zero panic in the
`DIV_ROUND_UP_SECTOR_T()` macro?

> +	}
> +}

[ ... ]

> +static int llbitmap_expand_pages(struct llbitmap *llbitmap,
> +				 unsigned long chunks)
> +{
> +	struct llbitmap_page_ctl **pctl;
> +	unsigned int old_nr_pages = llbitmap->nr_pages;
> +	unsigned int nr_pages = llbitmap_used_pages(llbitmap, chunks);
> +	unsigned int i;
> +	int ret;
> +
> +	if (nr_pages <= old_nr_pages)
> +		return 0;
> +
> +	pctl = kcalloc(nr_pages, sizeof(*pctl), GFP_KERNEL);
> +	if (!pctl)
> +		return -ENOMEM;
> +
> +	if (llbitmap->pctl)
> +		memcpy(pctl, llbitmap->pctl,
> +		       array_size(old_nr_pages, sizeof(*pctl)));
> +
> +	for (i = old_nr_pages; i < nr_pages; i++) {
> +		pctl[i] = llbitmap_alloc_page_ctl(llbitmap, i);
> +		if (IS_ERR(pctl[i]))
> +			goto err_alloc_ptr;
> +	}
> +
> +	kfree(llbitmap->pctl);
> +	llbitmap->pctl = pctl;
> +	llbitmap->nr_pages = nr_pages;

[Severity: High]
Is it safe to reallocate and update `llbitmap->pctl` and `nr_pages` locklessly
in place like this while the array is processing I/O?

`llbitmap_resize()` holds only `mddev->bitmap_info.mutex`, but concurrent
lockless readers like `md_llbitmap_daemon_fn()` and the I/O fastpath
`llbitmap_start_write()` dereference `llbitmap->pctl[idx]`.

Could this lead to a Use-After-Free if a concurrent reader accesses the old
`llbitmap->pctl` array just as it gets freed?

> +	return 0;
> +
> +err_alloc_ptr:
> +	ret = PTR_ERR(pctl[i]);

[ ... ]

> +static int llbitmap_prepare_resize(struct llbitmap *llbitmap,
> +				   unsigned long old_chunks,
> +				   unsigned long new_chunks,
> +				   unsigned long cache_chunks)
> +{
> +	int ret;
> +
> +	llbitmap_flush(llbitmap->mddev);
> +	ret = llbitmap_expand_pages(llbitmap, cache_chunks);

[Severity: High]
Does this sequence cause the daemon thread to bypass the barrier idle timer and
create severe metadata write amplification?

`llbitmap_flush()` sets the `LLPageFlush` bit on all existing pages. Since
`llbitmap_expand_pages()` reuses the existing `pctl` structures, the active
pages are retained with the `LLPageFlush` bit still set.

Since this bit is never cleared, the check in `md_llbitmap_daemon_fn()`:

	if (!test_bit(LLPageFlush, &pctl->flags) &&
	    time_before(jiffies, pctl->expire)) {
		restart = true;
		continue;
	}

will permanently fail for these pages, forcing the daemon to immediately flush
them and skip re-arming the pending timer.

> +	if (ret)
> +		return ret;
> +	if (new_chunks > old_chunks)
> +		llbitmap_mark_range(llbitmap, old_chunks, new_chunks - 1,
> +				    BitUnwritten);
> +	return 0;
> +}

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=6

^ permalink raw reply

* Re: [PATCH v2 04/20] md/md-llbitmap: track bitmap sync_size explicitly
From: sashiko-bot @ 2026-06-24  7:02 UTC (permalink / raw)
  To: Yu Kuai; +Cc: linux-raid, yukuai
In-Reply-To: <2fd017b2cb7bbeb49f0a1b8e0d413c0822f80885.1782282042.git.yukuai@kernel.org>

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

New issues:
- [High] Data race on `llbitmap->sync_size` between `llbitmap_resize` and `llbitmap_update_sb` can result in a corrupted superblock.

Pre-existing issues:
- [Critical] Improper teardown order in `llbitmap_destroy()` allows the asynchronous workqueue to unsafely re-arm the timer, leading to a Use-After-Free.
--

commit 4f14b77c13988c93db9a3db0e4720c69a8ac613c
Author: Yu Kuai <yukuai@fygo.io>

md/md-llbitmap: track bitmap sync_size explicitly

Track llbitmap's own sync_size instead of always using
mddev->resync_max_sectors directly. This is the minimal bookkeeping
needed before llbitmap can track old and new reshape geometry
independently.

> diff --git a/drivers/md/md-llbitmap.c b/drivers/md/md-llbitmap.c
> index f0c20afa354eb..e3500a1a52c07 100644
> --- a/drivers/md/md-llbitmap.c
> +++ b/drivers/md/md-llbitmap.c

[ ... ]

> @@ -1153,6 +1161,7 @@ static int llbitmap_resize(struct mddev *mddev, sector_t blocks, int chunksize)
>  	llbitmap->chunkshift = ffz(~chunksize);
>  	llbitmap->chunksize = chunksize;
>  	llbitmap->chunks = chunks;
> +	llbitmap->sync_size = blocks;
>  
>  	return 0;
>  }

[ ... ]

> @@ -1526,7 +1535,7 @@ static void llbitmap_update_sb(void *data)
>  	sb->events = cpu_to_le64(mddev->events);
>  	sb->state = cpu_to_le32(llbitmap->flags);
>  	sb->chunksize = cpu_to_le32(llbitmap->chunksize);
> -	sb->sync_size = cpu_to_le64(mddev->resync_max_sectors);
> +	sb->sync_size = cpu_to_le64(llbitmap->sync_size);

[Severity: High]
Can this read of llbitmap->sync_size cause a torn read on 32-bit systems?

While llbitmap_resize() updates this 64-bit value while holding
mddev->bitmap_info.mutex and reconfig_mutex, md_update_sb() calls
llbitmap_update_sb() without holding bitmap_info.mutex.

If a torn read occurs during concurrent array resize operations, could the
superblock be written with a corrupted sync_size? This might lead to array
assembly failures or out-of-bounds accesses during subsequent operations.

[ ... ]

[Severity: Critical]
This is a pre-existing issue, but does the teardown sequence in
llbitmap_destroy() have a use-after-free risk for the timer?

Looking at the current teardown order in llbitmap_destroy():

llbitmap_destroy() {
        ...
        timer_delete_sync(&llbitmap->pending_timer);
        flush_workqueue(md_llbitmap_io_wq);
        ...
}

If md_llbitmap_daemon_fn() is running during the flush_workqueue() call,
it might attempt to re-arm the timer:

md_llbitmap_daemon_fn() {
        ...
        if (restart)
                mod_timer(&llbitmap->pending_timer, jiffies + ...);
}

Could the asynchronous workqueue unsafely re-arm the timer here, allowing
it to resurrect after timer_delete_sync() and execute after the llbitmap
structure has been freed?

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=4

^ permalink raw reply

* Re: [PATCH v2 05/20] md/md-llbitmap: allocate page controls independently
From: sashiko-bot @ 2026-06-24  7:02 UTC (permalink / raw)
  To: Yu Kuai; +Cc: linux-raid, yukuai
In-Reply-To: <6e1ca7ea2cb90ae58c47230a90f3f08d51658829.1782282042.git.yukuai@kernel.org>

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

New issues:
- [High] Eager allocation of physical memory and disk I/O for the entire unused reserved bitmap space causes severe memory consumption and I/O stall regressions.

Pre-existing issues:
- [Critical] The bitmap space validation omits BITMAP_DATA_OFFSET, potentially allowing the bitmap to overflow its physical bounds and corrupt user data.
--

commit 880054f58bccd2442566ac1e584d6d9c8fc01e7e
Author: Yu Kuai <yukuai@fygo.io>

md/md-llbitmap: allocate page controls independently

Allocate one llbitmap page-control object at a time and free each
object through the same model.

> diff --git a/drivers/md/md-llbitmap.c b/drivers/md/md-llbitmap.c
> index e3500a1a52c07..4c3fc4b35aff0 100644
> --- a/drivers/md/md-llbitmap.c
> +++ b/drivers/md/md-llbitmap.c

[ ... ]

> +static int llbitmap_alloc_pages(struct llbitmap *llbitmap)
> +{
> +	unsigned int used_pages = llbitmap_used_pages(llbitmap, llbitmap->chunks);
> +	unsigned int nr_pages = max(used_pages, llbitmap_reserved_pages(llbitmap));
> +	int i;

[Severity: High]
Does this unconditionally eager-allocate memory and write out the entire 
reserved space?

By setting nr_pages to the maximum reserved space:
nr_pages = max(used_pages, llbitmap_reserved_pages(llbitmap));

and unconditionally allocating a physical 4KB page for every index up to 
this limit in llbitmap_read_page(), this seems to allocate RAM for all 
reserved, unused pages.

Furthermore, will functions like __llbitmap_flush() now iterate over all 
these allocated nr_pages, marking them dirty and synchronously writing them 
to disk, potentially causing severe I/O stalls for arrays with large 
reserved bitmap spaces?

> +
> +	llbitmap->pctl = kcalloc(nr_pages, sizeof(*llbitmap->pctl), GFP_KERNEL);
> +	if (!llbitmap->pctl)
> +		return -ENOMEM;

[ ... ]

> @@ -923,7 +948,7 @@ static int llbitmap_init(struct llbitmap *llbitmap)
>  	llbitmap->sync_size = blocks;
>  	mddev->bitmap_info.daemon_sleep = DEFAULT_DAEMON_SLEEP;
>  
> -	ret = llbitmap_cache_pages(llbitmap);
> +	ret = llbitmap_alloc_pages(llbitmap);

[Severity: Critical]
This is a pre-existing issue, but does the bitmap space validation here
omit BITMAP_DATA_OFFSET?

In llbitmap_init() and llbitmap_read_sb(), the validation checks ensure
the total bitmap size (chunks) doesn't exceed the reserved byte length
(space). However, they don't seem to account for the 1024-byte
BITMAP_DATA_OFFSET that is prepended to the bitmap data on disk.

If chunks is close to or exactly equal to space, the total byte size
required (chunks + BITMAP_DATA_OFFSET) could exceed the physical bounds
of the reserved space. During flushes, could llbitmap_write_page() write
across the reserved bitmap boundary and overwrite adjacent user data?

>  	if (ret)
>  		return ret;

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=5

^ permalink raw reply

* Re: [PATCH v2 03/20] md: add helper to split bios at reshape offset
From: sashiko-bot @ 2026-06-24  7:01 UTC (permalink / raw)
  To: Yu Kuai; +Cc: linux-raid, yukuai
In-Reply-To: <20e701b8355e1efd0d7cff3265189abf2424400b.1782282042.git.yukuai@kernel.org>

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] Lockless read of 64-bit `mddev->reshape_position` risks torn reads on 32-bit architectures and TOCTOU races between bio splitting and bitmap accounting, leading to silent data corruption.
--

commit 4912480eb23a69a6634d083e53f12568752eafb0
Author: Yu Kuai <yukuai@fygo.io>

md: add helper to split bios at reshape offset

This commit adds the mddev_bio_split_at_reshape_offset() helper function.
It allows MD personalities to share the reshape-offset bio splitting logic
instead of open-coding it in multiple places.

> diff --git a/drivers/md/md.c b/drivers/md/md.c
> index 0b59c676f7c03..c18a7f3c27e65 100644
> --- a/drivers/md/md.c
> +++ b/drivers/md/md.c
[ ... ]
> @@ -9361,6 +9361,45 @@ void md_submit_discard_bio(struct mddev *mddev, struct md_rdev *rdev,
>  }
>  EXPORT_SYMBOL_GPL(md_submit_discard_bio);
>  
> +struct bio *mddev_bio_split_at_reshape_offset(struct mddev *mddev,
> +					      struct bio *bio,
> +					      unsigned int *max_sectors,
> +					      struct bio_set *bs)
> +{
> +	sector_t boundary;
> +	sector_t start;
> +	sector_t end;
> +	unsigned int split_sectors;
> +
> +	split_sectors = bio_sectors(bio);
> +	if (max_sectors && *max_sectors && *max_sectors < split_sectors)
> +		split_sectors = *max_sectors;
> +
> +	if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
> +		goto split;
> +
> +	boundary = mddev->reshape_position;

[Severity: Critical]
Can this lockless read of mddev->reshape_position cause a torn read on
32-bit architectures since it is a 64-bit value?

Additionally, does reading this without locking introduce a time-of-check to
time-of-use race with bitmap accounting? If mddev->reshape_position
is updated by the reshape thread after this split check, but before bitmap
accounting in llbitmap_map_previous(), an unsplit bio could end up crossing
the new boundary.

This could trigger the WARN_ON_ONCE in llbitmap_map_previous():

    sector_t boundary = mddev->reshape_position;

    if (!llbitmap_reshaping(llbitmap))
        return false;

    WARN_ON_ONCE(sectors && offset < boundary && offset + sectors > boundary);

Could this race result in a bio being mis-accounted to the wrong array
geometry, potentially causing data corruption if a crash occurs during a
reshape?

> +	start = bio->bi_iter.bi_sector;
> +	end = bio_end_sector(bio);
> +	if (start >= boundary || end <= boundary)
> +		goto split;
> +
> +	if (boundary - start < split_sectors)
> +		split_sectors = boundary - start;
> +
> +split:
> +	if (max_sectors)
> +		*max_sectors = split_sectors;
> +	if (split_sectors < bio_sectors(bio)) {
> +		bio = bio_submit_split_bioset(bio, split_sectors, bs);
> +		if (bio)
> +			bio->bi_opf |= REQ_NOMERGE;
> +	}
> +
> +	return bio;
> +}
> +EXPORT_SYMBOL_GPL(mddev_bio_split_at_reshape_offset);

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=3

^ permalink raw reply

* Re: [PATCH v2 11/20] md/md-llbitmap: don't skip reshape ranges from bitmap state
From: sashiko-bot @ 2026-06-24  6:58 UTC (permalink / raw)
  To: Yu Kuai; +Cc: yukuai, linux-raid
In-Reply-To: <11d028037df1acf02db6d67a362ab02e96a7dd57.1782282042.git.yukuai@kernel.org>

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

Pre-existing issues:
- [Critical] Use-After-Free (UAF) of `llbitmap` memory during dynamic bitmap unregistration.
- [High] Signed integer overflow in `llbitmap_skip_sync_blocks` can cause premature resync termination.
--

commit 008d5398fa7aa1473594e503af861f03ef4f2548
Author: Yu Kuai <yukuai@fygo.io>

md/md-llbitmap: don't skip reshape ranges from bitmap state

Reshape progress is tracked by array metadata rather than llbitmap.
Do not let llbitmap skip_sync_blocks() suppress reshape ranges based on
stale bitmap state before the corresponding checkpoint is persisted.

> diff --git a/drivers/md/md-llbitmap.c b/drivers/md/md-llbitmap.c
> index d27993cfb13da..c62397743d9a0 100644
> --- a/drivers/md/md-llbitmap.c
> +++ b/drivers/md/md-llbitmap.c
> @@ -1647,6 +1647,14 @@ static sector_t llbitmap_skip_sync_blocks(struct mddev *mddev, sector_t offset)
>  		return 0;
>  	c = llbitmap_read(llbitmap, p);
>  
> +	/*
> +	 * Reshape progress is tracked by array metadata rather than llbitmap.
> +	 * Skipping reshape ranges from stale bitmap state can lose data after a
> +	 * restart before the corresponding bits are checkpointed to disk.
> +	 */
> +	if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
> +		return 0;
> +
>  	/* always skip unwritten blocks */
>  	if (c == BitUnwritten)
>  		return blocks;

[Severity: High]
This is a pre-existing issue, but since we are modifying this function, is
there a risk of signed integer overflow when returning blocks here?

If the array is extremely large and reserved bitmap space is small,
llbitmap->chunksize can be doubled during initialization until it exceeds
INT_MAX.

Because blocks is calculated earlier in this function as an int:

    int blocks = llbitmap->chunksize - (offset & (llbitmap->chunksize - 1));

If chunksize exceeds INT_MAX, blocks could become negative.

When this negative value is implicitly cast to the sector_t (unsigned 64-bit)
return type, it becomes a massive positive number.

Could this cause md_do_sync() to jump to the end of the array and
prematurely abort the synchronization?

Would it be safer to change the type of blocks to unsigned long or sector_t?


[Severity: Critical]
This isn't a bug introduced by this patch, but looking at the teardown
sequence elsewhere in this file for dynamic bitmap unregistration, does
llbitmap_destroy() have a use-after-free vulnerability?

When clearing the bitmap at runtime, llbitmap_destroy() deletes the timer
and flushes the workqueues without setting the LLPageFlush flag:

    timer_delete_sync(&llbitmap->pending_timer);
    flush_workqueue(md_llbitmap_io_wq);
    flush_workqueue(md_llbitmap_unplug_wq);
    
    mddev->bitmap = NULL;
    llbitmap_free_pages(llbitmap);
    kfree(llbitmap);

If the daemon worker (md_llbitmap_daemon_fn) is running on the workqueue,
timer_delete_sync() might do nothing if the timer already fired. The
flush_workqueue() call then waits for the worker to finish.

Inside the worker, because LLPageFlush is not set and idle pages have an
expire of LONG_MAX, it sets restart = true and re-arms the timer:

    if (!test_bit(LLPageFlush, &pctl->flags) &&
        time_before(jiffies, pctl->expire)) {
        restart = true;
        continue;
    }
    ...
    if (restart)
        mod_timer(&llbitmap->pending_timer, ...);

Once the worker finishes, flush_workqueue() returns and llbitmap is freed.
Does this leave the timer armed on freed memory, potentially causing memory
corruption when it fires?

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1782282042.git.yukuai@kernel.org?part=11

^ permalink raw reply


This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox