Skip to contentSkip to conversation

btrfs: scrub: support low bwlimits

PATCH In review Boris Burkov 2 participants 10 messages Nov 25 – Nov 26 Btrfs file system

lore
Share & tools
lore
#0 lore raw

cover btrfs: scrub: support low bwlimits

Scrub currently bottoms out at 512KiB/s bwlimit, and below that the logic doesn't make much sense. But if we support it naively, we ruin high speed scrubbing and add unacceptably long uninterruptible sleeps.

Therefore, to support arbitrarily slow scrubs, we must also spruce up some of the sleeping / pausing / cancelling logic.

Boris Burkov (4):
btrfs: scrub: release the commit root paths before pausing
btrfs: scrub: cancellable pause during throttle sleep
btrfs: scrub: handle bwlimit below 512KiB
btrfs: scrub: size read bios to the bwlimit 10ms burst

 fs/btrfs/scrub.c | 192 +++++++++++++++++++++++++++++------------------
 fs/btrfs/sysfs.c |   2 +
 2 files changed, 121 insertions(+), 73 deletions(-)
Signature · 1 line
2.56.0
#1 lore raw

PATCH 1/4 btrfs: scrub: release the commit root paths before pausing

Since commit 1dc4888e725d ("btrfs: scrub: avoid unnecessary extent tree search preparing stripes") scrub keeps sctx->extent_path and sctx->csum_path across the stripes of a block group, so the paths are also held across the implementation of scrub pause in scrub_simple_mirror() and scrub_raid56_parity_stripe().

Both use searches that set search_commit_root and skip_locking to true. Meanwhile, the transaction critical section is exactly what issues a pause. So if we populate sctx->extent_path/csum_path with nodes from a commit root, then pause, then complete a commit critical section, those nodes refer to the previous commit root, by construction.

These nodes could have been cowed and thus unpinned by the conclusion of the transaction. It is generally not safe to refer to nodes from old commit roots.

Therefore, we must drop these paths across pauses to ensure that after a pause we do a new search in the current commit root. Otherwise we would need to block the commit on the scrub which is obviously unacceptable.

This issue becomes particularly nasty with dev-replace scrubs which can then try to use an invalid reallocated eb to populate the new device.

Fixes 1dc4888e725d ("btrfs: scrub: avoid unnecessary extent tree search preparing stripes")
---
 fs/btrfs/scrub.c | 24 ++++++++++++++++--------
 1 file changed, 16 insertions(+), 8 deletions(-)
fs/btrfs/scrub.c +16 -8
index c8da03e14094..1a721623813f 100644
@@ -418,8 +418,16 @@ static void __scrub_blocked_if_needed(struct btrfs_fs_info *fs_info)
 	}
 }
 
-static void scrub_pause_on(struct btrfs_fs_info *fs_info)
+static void scrub_pause_on(struct scrub_ctx *sctx)
 {
+	struct btrfs_fs_info *fs_info = sctx->fs_info;
+
+	/*
+	 * These paths are populated from the commit root without using
+	 * commit_root_sem so they are not valid across pauses.
+	 */
+	btrfs_release_path(&sctx->extent_path);
+	btrfs_release_path(&sctx->csum_path);
 	atomic_inc(&fs_info->scrubs_paused);
 	wake_up(&fs_info->scrub_pause_wait);
 }
@@ -434,10 +442,10 @@ static void scrub_pause_off(struct btrfs_fs_info *fs_info)
 	wake_up(&fs_info->scrub_pause_wait);
 }
 
-static void scrub_blocked_if_needed(struct btrfs_fs_info *fs_info)
+static void scrub_blocked_if_needed(struct scrub_ctx *sctx)
 {
-	scrub_pause_on(fs_info);
-	scrub_pause_off(fs_info);
+	scrub_pause_on(sctx);
+	scrub_pause_off(sctx->fs_info);
 }
 
 static noinline_for_stack void scrub_free_ctx(struct scrub_ctx *sctx)
@@ -2204,7 +2212,7 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
 		return ret;
 
 	if (atomic_read(&fs_info->scrub_pause_req))
-		scrub_blocked_if_needed(fs_info);
+		scrub_blocked_if_needed(sctx);
 
 	spin_lock(&bg->lock);
 	if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &bg->runtime_flags)) {
@@ -2350,7 +2358,7 @@ static int scrub_simple_mirror(struct scrub_ctx *sctx,
 			break;
 
 		if (atomic_read(&fs_info->scrub_pause_req))
-			scrub_blocked_if_needed(fs_info);
+			scrub_blocked_if_needed(sctx);
 
 		spin_lock(&bg->lock);
 		if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &bg->runtime_flags)) {
@@ -2492,7 +2500,7 @@ static noinline_for_stack int scrub_stripe(struct scrub_ctx *sctx,
 	/* Extent_path should be released by now. */
 	ASSERT(sctx->extent_path.nodes[0] == NULL);
 
-	scrub_blocked_if_needed(fs_info);
+	scrub_blocked_if_needed(sctx);
 
 	if (sctx->is_dev_replace &&
 	    btrfs_dev_is_sequential(sctx->wr_tgtdev, physical)) {
@@ -2837,7 +2845,7 @@ int scrub_enumerate_chunks(struct scrub_ctx *sctx,
 		 * -> btrfs_commit_transaction()
 		 * -> btrfs_scrub_pause()
 		 */
-		scrub_pause_on(fs_info);
+		scrub_pause_on(sctx);
 
 		/*
 		 * Don't do chunk preallocation for scrub.
Signature · 1 line
2.56.0
Reviewed-by on v1 1/4
#2 lore raw

Re: [PATCH 1/4] btrfs: scrub: release the commit root paths before pausing

Quoted 20 lines · Boris Burkov

Since commit 1dc4888e725d ("btrfs: scrub: avoid unnecessary extent tree search preparing stripes") scrub keeps sctx->extent_path and sctx->csum_path across the stripes of a block group, so the paths are also held across the implementation of scrub pause in scrub_simple_mirror() and scrub_raid56_parity_stripe().

Both use searches that set search_commit_root and skip_locking to true. Meanwhile, the transaction critical section is exactly what issues a pause. So if we populate sctx->extent_path/csum_path with nodes from a commit root, then pause, then complete a commit critical section, those nodes refer to the previous commit root, by construction.

These nodes could have been cowed and thus unpinned by the conclusion of the transaction. It is generally not safe to refer to nodes from old commit roots.

Therefore, we must drop these paths across pauses to ensure that after a pause we do a new search in the current commit root. Otherwise we would need to block the commit on the scrub which is obviously unacceptable.

Quoted 5 lines

This issue becomes particularly nasty with dev-replace scrubs which can then try to use an invalid reallocated eb to populate the new device.

Fixes 1dc4888e725d ("btrfs: scrub: avoid unnecessary extent tree search preparing stripes")

Thanks,
Qu

Quoted 76 lines
---
  fs/btrfs/scrub.c | 24 ++++++++++++++++--------
  1 file changed, 16 insertions(+), 8 deletions(-)
fs/btrfs/scrub.c +16 -8
index c8da03e14094..1a721623813f 100644
@@ -418,8 +418,16 @@ static void __scrub_blocked_if_needed(struct btrfs_fs_info *fs_info)
  	}
  }
 
-static void scrub_pause_on(struct btrfs_fs_info *fs_info)
+static void scrub_pause_on(struct scrub_ctx *sctx)
  {
+	struct btrfs_fs_info *fs_info = sctx->fs_info;
+
+	/*
+	 * These paths are populated from the commit root without using
+	 * commit_root_sem so they are not valid across pauses.
+	 */
+	btrfs_release_path(&sctx->extent_path);
+	btrfs_release_path(&sctx->csum_path);
  	atomic_inc(&fs_info->scrubs_paused);
  	wake_up(&fs_info->scrub_pause_wait);
  }
@@ -434,10 +442,10 @@ static void scrub_pause_off(struct btrfs_fs_info *fs_info)
  	wake_up(&fs_info->scrub_pause_wait);
  }
 
-static void scrub_blocked_if_needed(struct btrfs_fs_info *fs_info)
+static void scrub_blocked_if_needed(struct scrub_ctx *sctx)
  {
-	scrub_pause_on(fs_info);
-	scrub_pause_off(fs_info);
+	scrub_pause_on(sctx);
+	scrub_pause_off(sctx->fs_info);
  }
 
  static noinline_for_stack void scrub_free_ctx(struct scrub_ctx *sctx)
@@ -2204,7 +2212,7 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
  		return ret;
 
  	if (atomic_read(&fs_info->scrub_pause_req))
-		scrub_blocked_if_needed(fs_info);
+		scrub_blocked_if_needed(sctx);
 
  	spin_lock(&bg->lock);
  	if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &bg->runtime_flags)) {
@@ -2350,7 +2358,7 @@ static int scrub_simple_mirror(struct scrub_ctx *sctx,
  			break;
 
  		if (atomic_read(&fs_info->scrub_pause_req))
-			scrub_blocked_if_needed(fs_info);
+			scrub_blocked_if_needed(sctx);
 
  		spin_lock(&bg->lock);
  		if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &bg->runtime_flags)) {
@@ -2492,7 +2500,7 @@ static noinline_for_stack int scrub_stripe(struct scrub_ctx *sctx,
  	/* Extent_path should be released by now. */
  	ASSERT(sctx->extent_path.nodes[0] == NULL);
 
-	scrub_blocked_if_needed(fs_info);
+	scrub_blocked_if_needed(sctx);
 
  	if (sctx->is_dev_replace &&
  	    btrfs_dev_is_sequential(sctx->wr_tgtdev, physical)) {
@@ -2837,7 +2845,7 @@ int scrub_enumerate_chunks(struct scrub_ctx *sctx,
  		 * -> btrfs_commit_transaction()
  		 * -> btrfs_scrub_pause()
  		 */
-		scrub_pause_on(fs_info);
+		scrub_pause_on(sctx);
 
  		/*
  		 * Don't do chunk preallocation for scrub.
#3 lore raw

PATCH 2/4 btrfs: scrub: cancellable pause during throttle sleep

In reply to Boris Burkov

scrub_throttle_dev_io() sleeps with schedule_timeout_interruptible() without pausing the scrub, while a transaction cannot enter a critical section without pausing scrub. Thus, a transaction commit gets blocked on a scrub throttle, which is completely backwards.

Furthermore, this sleep ignores attempts to cancel the scrub.

Improve the scrub throttling semantics by implementing it as a cancel aware sleep wrapped in a pause.

---
 fs/btrfs/scrub.c | 27 +++++++++++++++++++++------
 1 file changed, 21 insertions(+), 6 deletions(-)
fs/btrfs/scrub.c +21 -6
index 1a721623813f..a976897cea8d 100644
@@ -448,6 +448,23 @@ static void scrub_blocked_if_needed(struct scrub_ctx *sctx)
 	scrub_pause_off(sctx->fs_info);
 }
 
+/*
+ * Pause the scrub, and sleep for the throttle duration. Pausing allows the
+ * commit to proceed unblocked.
+ * Scrub cancel interrupts the sleep.
+ */
+static void scrub_throttle_sleep(struct scrub_ctx *sctx, ktime_t timeout)
+{
+	struct btrfs_fs_info *fs_info = sctx->fs_info;
+
+	scrub_pause_on(sctx);
+	wait_event_interruptible_hrtimeout(fs_info->scrub_pause_wait,
+					   atomic_read(&fs_info->scrub_cancel_req) ||
+					   atomic_read(&sctx->cancel_req),
+					   timeout);
+	scrub_pause_off(fs_info);
+}
+
 static noinline_for_stack void scrub_free_ctx(struct scrub_ctx *sctx)
 {
 	int i;
@@ -1435,12 +1452,8 @@ static void scrub_throttle_dev_io(struct scrub_ctx *sctx, struct btrfs_device *d
 		delta = 0;
 	}
 
-	if (delta) {
-		long timeout;
-
-		timeout = div_u64(delta * HZ, 1000);
-		schedule_timeout_interruptible(timeout);
-	}
+	if (delta)
+		scrub_throttle_sleep(sctx, ms_to_ktime(delta));
 
 	/* Next call will start the deadline period */
 	sctx->throttle_deadline = 0;
@@ -3334,6 +3347,7 @@ int btrfs_scrub_cancel(struct btrfs_fs_info *fs_info)
 	}
 
 	atomic_inc(&fs_info->scrub_cancel_req);
+	wake_up(&fs_info->scrub_pause_wait);
 	while (atomic_read(&fs_info->scrubs_running)) {
 		mutex_unlock(&fs_info->scrub_lock);
 		wait_event(fs_info->scrub_pause_wait,
@@ -3358,6 +3372,7 @@ int btrfs_scrub_cancel_dev(struct btrfs_device *dev)
 		return -ENOTCONN;
 	}
 	atomic_inc(&sctx->cancel_req);
+	wake_up(&fs_info->scrub_pause_wait);
 	while (dev->scrub_ctx) {
 		mutex_unlock(&fs_info->scrub_lock);
 		wait_event(fs_info->scrub_pause_wait,
Signature · 1 line
2.56.0
Reviewed-by on v1 2/4
#4 lore raw

Re: [PATCH 2/4] btrfs: scrub: cancellable pause during throttle sleep

Quoted 11 lines · Boris Burkov

scrub_throttle_dev_io() sleeps with schedule_timeout_interruptible() without pausing the scrub, while a transaction cannot enter a critical section without pausing scrub. Thus, a transaction commit gets blocked on a scrub throttle, which is completely backwards.

Furthermore, this sleep ignores attempts to cancel the scrub.

Improve the scrub throttling semantics by implementing it as a cancel aware sleep wrapped in a pause.

Thanks,
Qu

Quoted 63 lines
---
  fs/btrfs/scrub.c | 27 +++++++++++++++++++++------
  1 file changed, 21 insertions(+), 6 deletions(-)
fs/btrfs/scrub.c +21 -6
index 1a721623813f..a976897cea8d 100644
@@ -448,6 +448,23 @@ static void scrub_blocked_if_needed(struct scrub_ctx *sctx)
  	scrub_pause_off(sctx->fs_info);
  }
 
+/*
+ * Pause the scrub, and sleep for the throttle duration. Pausing allows the
+ * commit to proceed unblocked.
+ * Scrub cancel interrupts the sleep.
+ */
+static void scrub_throttle_sleep(struct scrub_ctx *sctx, ktime_t timeout)
+{
+	struct btrfs_fs_info *fs_info = sctx->fs_info;
+
+	scrub_pause_on(sctx);
+	wait_event_interruptible_hrtimeout(fs_info->scrub_pause_wait,
+					   atomic_read(&fs_info->scrub_cancel_req) ||
+					   atomic_read(&sctx->cancel_req),
+					   timeout);
+	scrub_pause_off(fs_info);
+}
+
  static noinline_for_stack void scrub_free_ctx(struct scrub_ctx *sctx)
  {
  	int i;
@@ -1435,12 +1452,8 @@ static void scrub_throttle_dev_io(struct scrub_ctx *sctx, struct btrfs_device *d
  		delta = 0;
  	}
 
-	if (delta) {
-		long timeout;
-
-		timeout = div_u64(delta * HZ, 1000);
-		schedule_timeout_interruptible(timeout);
-	}
+	if (delta)
+		scrub_throttle_sleep(sctx, ms_to_ktime(delta));
 
  	/* Next call will start the deadline period */
  	sctx->throttle_deadline = 0;
@@ -3334,6 +3347,7 @@ int btrfs_scrub_cancel(struct btrfs_fs_info *fs_info)
  	}
 
  	atomic_inc(&fs_info->scrub_cancel_req);
+	wake_up(&fs_info->scrub_pause_wait);
  	while (atomic_read(&fs_info->scrubs_running)) {
  		mutex_unlock(&fs_info->scrub_lock);
  		wait_event(fs_info->scrub_pause_wait,
@@ -3358,6 +3372,7 @@ int btrfs_scrub_cancel_dev(struct btrfs_device *dev)
  		return -ENOTCONN;
  	}
  	atomic_inc(&sctx->cancel_req);
+	wake_up(&fs_info->scrub_pause_wait);
  	while (dev->scrub_ctx) {
  		mutex_unlock(&fs_info->scrub_lock);
  		wait_event(fs_info->scrub_pause_wait,
#5 lore raw

PATCH 3/4 btrfs: scrub: handle bwlimit below 512KiB

In reply to Boris Burkov

scrub_throttle_dev_io() divides a time slice into up to 64 intervals with the computation
div = clamp(bwlimit / (16 * 1024 * 1024), 1, 64);
So at bwlimit below 16MiB/s, the time slice is unitary and above 1GiB/s the slice is split into 64 intervals.

Each interval represents an opportunity to schedule IO and we set a throttle deadline to now + time_slice / div. time_slice is 1000ms or 1s.

At each interval we count bio_size against bwlimit / div, or the portion of the per second bwlimit for that interval. If it is under, we send the bio with no throttling. Otherwise, we throttle till the end of the interval then send the bio.

This ensures that we have a hard cap of 64 sleeps in a second which ensures good throughput for typical unbounded or high limit scrubs.

But because bio_size is always 512KiB and we send at each interval, the practical minimum limit is 512KiB/s, as we will send at least 512KiB every second (the longest possible interval when div = 1).

To support lower limits without ruining throughput at higher limits, change to a model which can sleep for an arbitrary duration to properly amortize the data sent and acheive an average IO demand below bwlimit for bwlimit < 512KiB/s.

However, at higher limits, because the unit of sending is still 512KiB, sleeping between every IO for a naively calculated limit would be far too many sleeps and adds unacceptable sleeping overhead, ruining our ability to even submit at those limits. Therefore, we need to allow a "burst duration" as a floor for the sleeping duration. 10ms is a reasonable value: it is a similar number of sleeps at high limits (100 vs 64 per second) and is a responsive duration relatively commensurate in scale with disk latencies and intuitively seems like it would not be "too bursty" at any speed.

Now that we might sleep for a rather long time rather than at most 1s, although the sleeps are cancellable, also add a wakeup/cancel path from changing the limit again. If the user tunes the limit higher, they should just start running rather than needing to cancel.

---
 fs/btrfs/scrub.c | 71 +++++++++++++++++++-----------------------------
 fs/btrfs/sysfs.c |  2 ++
 2 files changed, 30 insertions(+), 43 deletions(-)
fs/btrfs/scrub.c +28 -43
index a976897cea8d..d68e8d2f766f 100644
@@ -57,6 +57,9 @@ struct scrub_ctx;
 
 #define SCRUB_TOTAL_STRIPES		(SCRUB_GROUPS_PER_SCTX * SCRUB_STRIPES_PER_GROUP)
 
+/* Length of a burst of throttled scrub IO, see scrub_throttle_dev_io(). */
+#define SCRUB_THROTTLE_BURST_MS		10
+
 /* Represent one sector and its needed info to verify the content. */
 struct scrub_sector_verification {
 	union {
@@ -195,9 +198,8 @@ struct scrub_ctx {
 	atomic_t		cancel_req;
 	int			readonly;
 
-	/* State of IO submission throttling affecting the associated device */
-	ktime_t			throttle_deadline;
-	u64			throttle_sent;
+	/* Earliest time the next read may be submitted under scrub_speed_max. */
+	ktime_t			throttle_next;
 
 	bool			is_dev_replace;
 	u64			write_pointer;
@@ -451,16 +453,19 @@ static void scrub_blocked_if_needed(struct scrub_ctx *sctx)
 /*
  * Pause the scrub, and sleep for the throttle duration. Pausing allows the
  * commit to proceed unblocked.
- * Scrub cancel interrupts the sleep.
+ * Scrub cancel or a change of the limit the sleep was computed under
+ * interrupts the sleep.
  */
-static void scrub_throttle_sleep(struct scrub_ctx *sctx, ktime_t timeout)
+static void scrub_throttle_sleep(struct scrub_ctx *sctx, struct btrfs_device *device,
+				 u64 bwlimit, ktime_t timeout)
 {
 	struct btrfs_fs_info *fs_info = sctx->fs_info;
 
 	scrub_pause_on(sctx);
 	wait_event_interruptible_hrtimeout(fs_info->scrub_pause_wait,
 					   atomic_read(&fs_info->scrub_cancel_req) ||
-					   atomic_read(&sctx->cancel_req),
+					   atomic_read(&sctx->cancel_req) ||
+					   READ_ONCE(device->scrub_speed_max) != bwlimit,
 					   timeout);
 	scrub_pause_off(fs_info);
 }
@@ -514,7 +519,7 @@ static noinline_for_stack struct scrub_ctx *scrub_setup_ctx(
 	atomic_set(&sctx->cancel_req, 0);
 
 	spin_lock_init(&sctx->stat_lock);
-	sctx->throttle_deadline = 0;
+	sctx->throttle_next = 0;
 
 	mutex_init(&sctx->wr_lock);
 	if (is_dev_replace) {
@@ -1409,54 +1414,34 @@ static void scrub_write_sectors(struct scrub_ctx *sctx, struct scrub_stripe *str
 }
 
 /*
- * Throttling of IO submission, bandwidth-limit based, the timeslice is 1
- * second.  Limit can be set via /sys/fs/UUID/devinfo/devid/scrub_speed_max.
+ * Throttling of IO submission, bandwidth-limit based. Limit can be set via
+ * /sys/fs/UUID/devinfo/devid/scrub_speed_max.
  */
 static void scrub_throttle_dev_io(struct scrub_ctx *sctx, struct btrfs_device *device,
 				  unsigned int bio_size)
 {
-	const int time_slice = 1000;
-	s64 delta;
+	const u64 bwlimit = READ_ONCE(device->scrub_speed_max);
 	ktime_t now;
-	u32 div;
-	u64 bwlimit;
+	ktime_t ahead;
 
-	bwlimit = READ_ONCE(device->scrub_speed_max);
 	if (bwlimit == 0)
 		return;
 
-	/*
-	 * Slice is divided into intervals when the IO is submitted, adjust by
-	 * bwlimit and maximum of 64 intervals.
-	 */
-	div = clamp(bwlimit / (16 * 1024 * 1024), 1, 64);
-
-	/* Start new epoch, set deadline */
 	now = ktime_get();
-	if (sctx->throttle_deadline == 0) {
-		sctx->throttle_deadline = ktime_add_ms(now, time_slice / div);
-		sctx->throttle_sent = 0;
-	}
-
-	/* Still in the time to send? */
-	if (ktime_before(now, sctx->throttle_deadline)) {
-		/* If current bio is within the limit, send it */
-		sctx->throttle_sent += bio_size;
-		if (sctx->throttle_sent <= div_u64(bwlimit, div))
+	ahead = ktime_sub(sctx->throttle_next, now);
+	if (ahead < 0) {
+		sctx->throttle_next = now;
+	} else if (ahead > SCRUB_THROTTLE_BURST_MS * NSEC_PER_MSEC) {
+		scrub_throttle_sleep(sctx, device, bwlimit, ahead);
+		/* Woken by a limit change: the debt was accrued at the old limit. */
+		if (READ_ONCE(device->scrub_speed_max) != bwlimit) {
+			sctx->throttle_next = ktime_get();
 			return;
-
-		/* We're over the limit, sleep until the rest of the slice */
-		delta = ktime_ms_delta(sctx->throttle_deadline, now);
-	} else {
-		/* New request after deadline, start new epoch */
-		delta = 0;
+		}
 	}
-
-	if (delta)
-		scrub_throttle_sleep(sctx, ms_to_ktime(delta));
-
-	/* Next call will start the deadline period */
-	sctx->throttle_deadline = 0;
+	/* (bytes * (nsec / sec)) / (bytes / sec) ==> nsec */
+	sctx->throttle_next = ktime_add_ns(sctx->throttle_next,
+				div64_u64((u64)bio_size * NSEC_PER_SEC, bwlimit));
 }
 
 /*
fs/btrfs/sysfs.c +2 -0
index 89b0a4ef4063..4c7f486c2924 100644
@@ -1928,6 +1928,8 @@ static ssize_t btrfs_devinfo_scrub_speed_max_store(struct kobject *kobj,
 	if (*endptr != 0)
 		return -EINVAL;
 	WRITE_ONCE(device->scrub_speed_max, limit);
+	/* A throttled scrub sleeps on this under the old limit. */
+	wake_up(&device->fs_info->scrub_pause_wait);
 	return len;
 }
 BTRFS_ATTR_RW(devid, scrub_speed_max, btrfs_devinfo_scrub_speed_max_show,
Signature · 1 line
2.56.0
#6 lore raw

Re: [PATCH 3/4] btrfs: scrub: handle bwlimit below 512KiB

Quoted 17 lines · Boris Burkov

scrub_throttle_dev_io() divides a time slice into up to 64 intervals with the computation
div = clamp(bwlimit / (16 * 1024 * 1024), 1, 64);
So at bwlimit below 16MiB/s, the time slice is unitary and above 1GiB/s the slice is split into 64 intervals.

Each interval represents an opportunity to schedule IO and we set a throttle deadline to now + time_slice / div. time_slice is 1000ms or 1s.

At each interval we count bio_size against bwlimit / div, or the portion of the per second bwlimit for that interval. If it is under, we send the bio with no throttling. Otherwise, we throttle till the end of the interval then send the bio.

This ensures that we have a hard cap of 64 sleeps in a second which ensures good throughput for typical unbounded or high limit scrubs.

Quoted 8 lines

But because bio_size is always 512KiB and we send at each interval, the practical minimum limit is 512KiB/s, as we will send at least 512KiB every second (the longest possible interval when div = 1).

To support lower limits without ruining throughput at higher limits, change to a model which can sleep for an arbitrary duration to properly amortize the data sent and acheive an average IO demand below bwlimit for bwlimit < 512KiB/s.

For the bandwidth limit, I doubt if it's really practical to set it so low. One 1GiB bg will take over 30min to scrub, which doesn't sound that sane.

Quoted 10 lines

However, at higher limits, because the unit of sending is still 512KiB, sleeping between every IO for a naively calculated limit would be far too many sleeps and adds unacceptable sleeping overhead, ruining our ability to even submit at those limits. Therefore, we need to allow a "burst duration" as a floor for the sleeping duration. 10ms is a reasonable value: it is a similar number of sleeps at high limits (100 vs 64 per second) and is a responsive duration relatively commensurate in scale with disk latencies and intuitively seems like it would not be "too bursty" at any speed.

I agree the old sleep behavior is not that good for high limits, especially considering how fast modern storage can be.

Quoted 48 lines

Now that we might sleep for a rather long time rather than at most 1s, although the sleeps are cancellable, also add a wakeup/cancel path from changing the limit again. If the user tunes the limit higher, they should just start running rather than needing to cancel.

---
  fs/btrfs/scrub.c | 71 +++++++++++++++++++-----------------------------
  fs/btrfs/sysfs.c |  2 ++
  2 files changed, 30 insertions(+), 43 deletions(-)
fs/btrfs/scrub.c +8 -5
index a976897cea8d..d68e8d2f766f 100644
@@ -57,6 +57,9 @@ struct scrub_ctx;
 
  #define SCRUB_TOTAL_STRIPES		(SCRUB_GROUPS_PER_SCTX * SCRUB_STRIPES_PER_GROUP)
 
+/* Length of a burst of throttled scrub IO, see scrub_throttle_dev_io(). */
+#define SCRUB_THROTTLE_BURST_MS		10
+
  /* Represent one sector and its needed info to verify the content. */
  struct scrub_sector_verification {
  	union {
@@ -195,9 +198,8 @@ struct scrub_ctx {
  	atomic_t		cancel_req;
  	int			readonly;
 
-	/* State of IO submission throttling affecting the associated device */
-	ktime_t			throttle_deadline;
-	u64			throttle_sent;
+	/* Earliest time the next read may be submitted under scrub_speed_max. */
+	ktime_t			throttle_next;
 
  	bool			is_dev_replace;
  	u64			write_pointer;
@@ -451,16 +453,19 @@ static void scrub_blocked_if_needed(struct scrub_ctx *sctx)
  /*
   * Pause the scrub, and sleep for the throttle duration. Pausing allows the
   * commit to proceed unblocked.
- * Scrub cancel interrupts the sleep.
+ * Scrub cancel or a change of the limit the sleep was computed under
+ * interrupts the sleep.
   */
-static void scrub_throttle_sleep(struct scrub_ctx *sctx, ktime_t timeout)
+static void scrub_throttle_sleep(struct scrub_ctx *sctx, struct btrfs_device *device,

fs/btrfs/scrub.c static void scrub_blocked_if_needed(struct scrub_ctx *sctx) · line 468

Quoted 10 lines
fs/btrfs/scrub.c +3 -1
+				 u64 bwlimit, ktime_t timeout)
  {
  	struct btrfs_fs_info *fs_info = sctx->fs_info;
 
  	scrub_pause_on(sctx);
  	wait_event_interruptible_hrtimeout(fs_info->scrub_pause_wait,
  					   atomic_read(&fs_info->scrub_cancel_req) ||
-					   atomic_read(&sctx->cancel_req),
+					   atomic_read(&sctx->cancel_req) ||
+					   READ_ONCE(device->scrub_speed_max) != bwlimit,

One question, do we really need to bother the scrub_speed_max change?

I think this is a little overengineered, and Sashiko is already report low priority problem related to this part.

Thanks,
Qu

Quoted 96 lines
fs/btrfs/scrub.c +17 -37
  					   timeout);
  	scrub_pause_off(fs_info);
  }
@@ -514,7 +519,7 @@ static noinline_for_stack struct scrub_ctx *scrub_setup_ctx(
  	atomic_set(&sctx->cancel_req, 0);
 
  	spin_lock_init(&sctx->stat_lock);
-	sctx->throttle_deadline = 0;
+	sctx->throttle_next = 0;
 
  	mutex_init(&sctx->wr_lock);
  	if (is_dev_replace) {
@@ -1409,54 +1414,34 @@ static void scrub_write_sectors(struct scrub_ctx *sctx, struct scrub_stripe *str
  }
 
  /*
- * Throttling of IO submission, bandwidth-limit based, the timeslice is 1
- * second.  Limit can be set via /sys/fs/UUID/devinfo/devid/scrub_speed_max.
+ * Throttling of IO submission, bandwidth-limit based. Limit can be set via
+ * /sys/fs/UUID/devinfo/devid/scrub_speed_max.
   */
  static void scrub_throttle_dev_io(struct scrub_ctx *sctx, struct btrfs_device *device,
  				  unsigned int bio_size)
  {
-	const int time_slice = 1000;
-	s64 delta;
+	const u64 bwlimit = READ_ONCE(device->scrub_speed_max);
  	ktime_t now;
-	u32 div;
-	u64 bwlimit;
+	ktime_t ahead;
 
-	bwlimit = READ_ONCE(device->scrub_speed_max);
  	if (bwlimit == 0)
  		return;
 
-	/*
-	 * Slice is divided into intervals when the IO is submitted, adjust by
-	 * bwlimit and maximum of 64 intervals.
-	 */
-	div = clamp(bwlimit / (16 * 1024 * 1024), 1, 64);
-
-	/* Start new epoch, set deadline */
  	now = ktime_get();
-	if (sctx->throttle_deadline == 0) {
-		sctx->throttle_deadline = ktime_add_ms(now, time_slice / div);
-		sctx->throttle_sent = 0;
-	}
-
-	/* Still in the time to send? */
-	if (ktime_before(now, sctx->throttle_deadline)) {
-		/* If current bio is within the limit, send it */
-		sctx->throttle_sent += bio_size;
-		if (sctx->throttle_sent <= div_u64(bwlimit, div))
+	ahead = ktime_sub(sctx->throttle_next, now);
+	if (ahead < 0) {
+		sctx->throttle_next = now;
+	} else if (ahead > SCRUB_THROTTLE_BURST_MS * NSEC_PER_MSEC) {
+		scrub_throttle_sleep(sctx, device, bwlimit, ahead);
+		/* Woken by a limit change: the debt was accrued at the old limit. */
+		if (READ_ONCE(device->scrub_speed_max) != bwlimit) {
+			sctx->throttle_next = ktime_get();
  			return;
-
-		/* We're over the limit, sleep until the rest of the slice */
-		delta = ktime_ms_delta(sctx->throttle_deadline, now);
-	} else {
-		/* New request after deadline, start new epoch */
-		delta = 0;
+		}
  	}
-
-	if (delta)
-		scrub_throttle_sleep(sctx, ms_to_ktime(delta));
-
-	/* Next call will start the deadline period */
-	sctx->throttle_deadline = 0;
+	/* (bytes * (nsec / sec)) / (bytes / sec) ==> nsec */
+	sctx->throttle_next = ktime_add_ns(sctx->throttle_next,
+				div64_u64((u64)bio_size * NSEC_PER_SEC, bwlimit));
  }
 
  /*
fs/btrfs/sysfs.c +2 -0
index 89b0a4ef4063..4c7f486c2924 100644
@@ -1928,6 +1928,8 @@ static ssize_t btrfs_devinfo_scrub_speed_max_store(struct kobject *kobj,
  	if (*endptr != 0)
  		return -EINVAL;
  	WRITE_ONCE(device->scrub_speed_max, limit);
+	/* A throttled scrub sleeps on this under the old limit. */
+	wake_up(&device->fs_info->scrub_pause_wait);
  	return len;
  }
  BTRFS_ATTR_RW(devid, scrub_speed_max, btrfs_devinfo_scrub_speed_max_show,
#7 lore raw

Re: [PATCH 3/4] btrfs: scrub: handle bwlimit below 512KiB

Quoted 24 lines · Qu Wenruo
Quoted 21 lines · Boris Burkov

scrub_throttle_dev_io() divides a time slice into up to 64 intervals with the computation
div = clamp(bwlimit / (16 * 1024 * 1024), 1, 64);
So at bwlimit below 16MiB/s, the time slice is unitary and above 1GiB/s the slice is split into 64 intervals.

Each interval represents an opportunity to schedule IO and we set a throttle deadline to now + time_slice / div. time_slice is 1000ms or 1s.

At each interval we count bio_size against bwlimit / div, or the portion of the per second bwlimit for that interval. If it is under, we send the bio with no throttling. Otherwise, we throttle till the end of the interval then send the bio.

This ensures that we have a hard cap of 64 sleeps in a second which ensures good throughput for typical unbounded or high limit scrubs.

But because bio_size is always 512KiB and we send at each interval, the practical minimum limit is 512KiB/s, as we will send at least 512KiB every second (the longest possible interval when div = 1).

Quoted 8 lines
Quoted 4 lines

To support lower limits without ruining throughput at higher limits, change to a model which can sleep for an arbitrary duration to properly amortize the data sent and acheive an average IO demand below bwlimit for bwlimit < 512KiB/s.

For the bandwidth limit, I doubt if it's really practical to set it so low. One 1GiB bg will take over 30min to scrub, which doesn't sound that sane.

I agree in general.

We have a use-case with a remote disk and a bw budget for bg checking where we would like to set a low limit. If you have a small amount of metadata and scrub the metadata bg it can be feasible to do quite slow scrubs and get some good utility.

Would it make more sense if I also sent a patch to extend the scrub ioctl to have it respect narrower ranges of the disk than the whole chunk?

Quoted 11 lines
Quoted 10 lines

However, at higher limits, because the unit of sending is still 512KiB, sleeping between every IO for a naively calculated limit would be far too many sleeps and adds unacceptable sleeping overhead, ruining our ability to even submit at those limits. Therefore, we need to allow a "burst duration" as a floor for the sleeping duration. 10ms is a reasonable value: it is a similar number of sleeps at high limits (100 vs 64 per second) and is a responsive duration relatively commensurate in scale with disk latencies and intuitively seems like it would not be "too bursty" at any speed.

Quoted 3 lines

I agree the old sleep behavior is not that good for high limits, especially considering how fast modern storage can be.

Sorry if I was unclear but the old behavior should be fast on high limits, at least as I understand it. My motivation here was:

1. slow scrub needs to sleep for required (possibly long) duration between IOs.
2. sleep for required duration between IOs done naively makes fast scrub sleep thousands of times for nanoseconds, now we are harassing the scheduler for all the sleeping/waking.
3. bring back the upper bound on how often we sleep by always allowing the burst worth of IO.

So the point is to enable slow scrubs without regressing fast scrubs, I don't think this patch should help fast scrubs at all. Besides making the code a little simpler, at least IMO.

Quoted 56 lines
Quoted 43 lines

Now that we might sleep for a rather long time rather than at most 1s, although the sleeps are cancellable, also add a wakeup/cancel path from changing the limit again. If the user tunes the limit higher, they should just start running rather than needing to cancel.

---
  fs/btrfs/scrub.c | 71 +++++++++++++++++++-----------------------------
  fs/btrfs/sysfs.c |  2 ++
  2 files changed, 30 insertions(+), 43 deletions(-)
fs/btrfs/scrub.c +7 -5
index a976897cea8d..d68e8d2f766f 100644
@@ -57,6 +57,9 @@ struct scrub_ctx;
  #define SCRUB_TOTAL_STRIPES		(SCRUB_GROUPS_PER_SCTX * SCRUB_STRIPES_PER_GROUP)
+/* Length of a burst of throttled scrub IO, see scrub_throttle_dev_io(). */
+#define SCRUB_THROTTLE_BURST_MS		10
+
  /* Represent one sector and its needed info to verify the content. */
  struct scrub_sector_verification {
  	union {
@@ -195,9 +198,8 @@ struct scrub_ctx {
  	atomic_t		cancel_req;
  	int			readonly;
-	/* State of IO submission throttling affecting the associated device */
-	ktime_t			throttle_deadline;
-	u64			throttle_sent;
+	/* Earliest time the next read may be submitted under scrub_speed_max. */
+	ktime_t			throttle_next;
  	bool			is_dev_replace;
  	u64			write_pointer;
@@ -451,16 +453,19 @@ static void scrub_blocked_if_needed(struct scrub_ctx *sctx)
  /*
   * Pause the scrub, and sleep for the throttle duration. Pausing allows the
   * commit to proceed unblocked.
- * Scrub cancel interrupts the sleep.
+ * Scrub cancel or a change of the limit the sleep was computed under
+ * interrupts the sleep.
   */
-static void scrub_throttle_sleep(struct scrub_ctx *sctx, ktime_t timeout)

fs/btrfs/scrub.c static void scrub_blocked_if_needed(struct scrub_ctx *sctx) · line 467

Quoted 10 lines
fs/btrfs/scrub.c +4 -1
+static void scrub_throttle_sleep(struct scrub_ctx *sctx, struct btrfs_device *device,
+				 u64 bwlimit, ktime_t timeout)
  {
  	struct btrfs_fs_info *fs_info = sctx->fs_info;
  	scrub_pause_on(sctx);
  	wait_event_interruptible_hrtimeout(fs_info->scrub_pause_wait,
  					   atomic_read(&fs_info->scrub_cancel_req) ||
-					   atomic_read(&sctx->cancel_req),
+					   atomic_read(&sctx->cancel_req) ||
+					   READ_ONCE(device->scrub_speed_max) != bwlimit,

One question, do we really need to bother the scrub_speed_max change?

Quoted 2 lines

I think this is a little overengineered, and Sashiko is already report low priority problem related to this part.

Yeah we can drop it, I think this was a nice-to-have UX addon. The user can always cancel if necessary.

Quoted 4 lines

Thanks,
Qu

Thanks for the review!

Quoted 91 lines
Quoted 90 lines
fs/btrfs/scrub.c +17 -37
  					   timeout);
  	scrub_pause_off(fs_info);
  }
@@ -514,7 +519,7 @@ static noinline_for_stack struct scrub_ctx *scrub_setup_ctx(
  	atomic_set(&sctx->cancel_req, 0);
  	spin_lock_init(&sctx->stat_lock);
-	sctx->throttle_deadline = 0;
+	sctx->throttle_next = 0;
  	mutex_init(&sctx->wr_lock);
  	if (is_dev_replace) {
@@ -1409,54 +1414,34 @@ static void scrub_write_sectors(struct scrub_ctx *sctx, struct scrub_stripe *str
  }
  /*
- * Throttling of IO submission, bandwidth-limit based, the timeslice is 1
- * second.  Limit can be set via /sys/fs/UUID/devinfo/devid/scrub_speed_max.
+ * Throttling of IO submission, bandwidth-limit based. Limit can be set via
+ * /sys/fs/UUID/devinfo/devid/scrub_speed_max.
   */
  static void scrub_throttle_dev_io(struct scrub_ctx *sctx, struct btrfs_device *device,
  				  unsigned int bio_size)
  {
-	const int time_slice = 1000;
-	s64 delta;
+	const u64 bwlimit = READ_ONCE(device->scrub_speed_max);
  	ktime_t now;
-	u32 div;
-	u64 bwlimit;
+	ktime_t ahead;
-	bwlimit = READ_ONCE(device->scrub_speed_max);
  	if (bwlimit == 0)
  		return;
-	/*
-	 * Slice is divided into intervals when the IO is submitted, adjust by
-	 * bwlimit and maximum of 64 intervals.
-	 */
-	div = clamp(bwlimit / (16 * 1024 * 1024), 1, 64);
-
-	/* Start new epoch, set deadline */
  	now = ktime_get();
-	if (sctx->throttle_deadline == 0) {
-		sctx->throttle_deadline = ktime_add_ms(now, time_slice / div);
-		sctx->throttle_sent = 0;
-	}
-
-	/* Still in the time to send? */
-	if (ktime_before(now, sctx->throttle_deadline)) {
-		/* If current bio is within the limit, send it */
-		sctx->throttle_sent += bio_size;
-		if (sctx->throttle_sent <= div_u64(bwlimit, div))
+	ahead = ktime_sub(sctx->throttle_next, now);
+	if (ahead < 0) {
+		sctx->throttle_next = now;
+	} else if (ahead > SCRUB_THROTTLE_BURST_MS * NSEC_PER_MSEC) {
+		scrub_throttle_sleep(sctx, device, bwlimit, ahead);
+		/* Woken by a limit change: the debt was accrued at the old limit. */
+		if (READ_ONCE(device->scrub_speed_max) != bwlimit) {
+			sctx->throttle_next = ktime_get();
  			return;
-
-		/* We're over the limit, sleep until the rest of the slice */
-		delta = ktime_ms_delta(sctx->throttle_deadline, now);
-	} else {
-		/* New request after deadline, start new epoch */
-		delta = 0;
+		}
  	}
-
-	if (delta)
-		scrub_throttle_sleep(sctx, ms_to_ktime(delta));
-
-	/* Next call will start the deadline period */
-	sctx->throttle_deadline = 0;
+	/* (bytes * (nsec / sec)) / (bytes / sec) ==> nsec */
+	sctx->throttle_next = ktime_add_ns(sctx->throttle_next,
+				div64_u64((u64)bio_size * NSEC_PER_SEC, bwlimit));
  }
  /*
fs/btrfs/sysfs.c +2 -0
index 89b0a4ef4063..4c7f486c2924 100644
@@ -1928,6 +1928,8 @@ static ssize_t btrfs_devinfo_scrub_speed_max_store(struct kobject *kobj,
  	if (*endptr != 0)
  		return -EINVAL;
  	WRITE_ONCE(device->scrub_speed_max, limit);
+	/* A throttled scrub sleeps on this under the old limit. */
+	wake_up(&device->fs_info->scrub_pause_wait);
  	return len;
  }
  BTRFS_ATTR_RW(devid, scrub_speed_max, btrfs_devinfo_scrub_speed_max_show,
#8 lore raw

Re: [PATCH 3/4] btrfs: scrub: handle bwlimit below 512KiB

Quoted 1 line · Boris Burkov

On Thu, Nov 26, 2026 at 10:15:45AM +1030, Qu Wenruo wrote:

[...]

Quoted 10 lines
Quoted 3 lines

For the bandwidth limit, I doubt if it's really practical to set it so low. One 1GiB bg will take over 30min to scrub, which doesn't sound that sane.

I agree in general.

We have a use-case with a remote disk and a bw budget for bg checking where we would like to set a low limit. If you have a small amount of metadata and scrub the metadata bg it can be feasible to do quite slow scrubs and get some good utility.

In that case, I'd argue the read-only metadata bg can be a larger problem, as it means the metadata bg can not be utilized for over 30min if using that low bwlimit.

But overall I agree for such bw limited storage, a lower and better bwlimit behavior can be beneficial, just don't set the limit too low.

Quoted 4 lines

Would it make more sense if I also sent a patch to extend the scrub ioctl to have it respect narrower ranges of the disk than the whole chunk?

Sorry but I didn't get what you mean by "respect narrower ranges of the disk than the whole chunk".

Quoted 27 lines
Quoted 12 lines
Quoted 11 lines

However, at higher limits, because the unit of sending is still 512KiB, sleeping between every IO for a naively calculated limit would be far too many sleeps and adds unacceptable sleeping overhead, ruining our ability to even submit at those limits. Therefore, we need to allow a "burst duration" as a floor for the sleeping duration. 10ms is a reasonable value: it is a similar number of sleeps at high limits (100 vs 64 per second) and is a responsive duration relatively commensurate in scale with disk latencies and intuitively seems like it would not be "too bursty" at any speed.

Quoted 3 lines

I agree the old sleep behavior is not that good for high limits, especially considering how fast modern storage can be.

Sorry if I was unclear but the old behavior should be fast on high limits, at least as I understand it. My motivation here was:

1. slow scrub needs to sleep for required (possibly long) duration between IOs.
2. sleep for required duration between IOs done naively makes fast scrub sleep thousands of times for nanoseconds, now we are harassing the scheduler for all the sleeping/waking.
3. bring back the upper bound on how often we sleep by always allowing the burst worth of IO.

Quoted 3 lines

So the point is to enable slow scrubs without regressing fast scrubs, I don't think this patch should help fast scrubs at all. Besides making the code a little simpler, at least IMO.

Oh, thanks a lot for correcting my misunderstanding.

Despite the changing bwlimit halfway part, now it looks overall good to me.

Thanks,
Qu

Quoted 70 lines
Quoted 57 lines
Quoted 44 lines

Now that we might sleep for a rather long time rather than at most 1s, although the sleeps are cancellable, also add a wakeup/cancel path from changing the limit again. If the user tunes the limit higher, they should just start running rather than needing to cancel.

---
   fs/btrfs/scrub.c | 71 +++++++++++++++++++-----------------------------
   fs/btrfs/sysfs.c |  2 ++
   2 files changed, 30 insertions(+), 43 deletions(-)
fs/btrfs/scrub.c +7 -5
index a976897cea8d..d68e8d2f766f 100644
@@ -57,6 +57,9 @@ struct scrub_ctx;
   #define SCRUB_TOTAL_STRIPES		(SCRUB_GROUPS_PER_SCTX * SCRUB_STRIPES_PER_GROUP)
+/* Length of a burst of throttled scrub IO, see scrub_throttle_dev_io(). */
+#define SCRUB_THROTTLE_BURST_MS		10
+
   /* Represent one sector and its needed info to verify the content. */
   struct scrub_sector_verification {
   	union {
@@ -195,9 +198,8 @@ struct scrub_ctx {
   	atomic_t		cancel_req;
   	int			readonly;
-	/* State of IO submission throttling affecting the associated device */
-	ktime_t			throttle_deadline;
-	u64			throttle_sent;
+	/* Earliest time the next read may be submitted under scrub_speed_max. */
+	ktime_t			throttle_next;
   	bool			is_dev_replace;
   	u64			write_pointer;
@@ -451,16 +453,19 @@ static void scrub_blocked_if_needed(struct scrub_ctx *sctx)
   /*
    * Pause the scrub, and sleep for the throttle duration. Pausing allows the
    * commit to proceed unblocked.
- * Scrub cancel interrupts the sleep.
+ * Scrub cancel or a change of the limit the sleep was computed under
+ * interrupts the sleep.
    */
-static void scrub_throttle_sleep(struct scrub_ctx *sctx, ktime_t timeout)

fs/btrfs/scrub.c static void scrub_blocked_if_needed(struct scrub_ctx *sctx) · line 467

Quoted 10 lines
fs/btrfs/scrub.c +4 -1
+static void scrub_throttle_sleep(struct scrub_ctx *sctx, struct btrfs_device *device,
+				 u64 bwlimit, ktime_t timeout)
   {
   	struct btrfs_fs_info *fs_info = sctx->fs_info;
   	scrub_pause_on(sctx);
   	wait_event_interruptible_hrtimeout(fs_info->scrub_pause_wait,
   					   atomic_read(&fs_info->scrub_cancel_req) ||
-					   atomic_read(&sctx->cancel_req),
+					   atomic_read(&sctx->cancel_req) ||
+					   READ_ONCE(device->scrub_speed_max) != bwlimit,

One question, do we really need to bother the scrub_speed_max change?

Quoted 2 lines

I think this is a little overengineered, and Sashiko is already report low priority problem related to this part.

Yeah we can drop it, I think this was a nice-to-have UX addon. The user can always cancel if necessary.

Quoted 4 lines

Thanks,
Qu

Thanks for the review!

#9 lore raw

PATCH 4/4 btrfs: scrub: size read bios to the bwlimit 10ms burst

In reply to Boris Burkov

Now that scrub will sleep for long enough to pace to an arbitrary bandwidth limit, it is also helpful to size the bios in a way that is more burst aware. For limits below 512 KiB/s it is more logical to submit more bios with shorter sleeps than to dump a 512KiB bio then sleep for tens of seconds. Compute a burst size from the burst duration and the bwlimit, then clamp that between a single sector and the normal stripe_len to determine the bio size.

Now if we throttle at each bio, the pacing scales naturally with the behavior essentially unchanged at higher limits but not crazy bursty at lower bwlimits.

The stripe takes an extra pending_io reference across the submissions, as scrub_submit_extent_sector_read() does, so the repair worker is not queued before the last bio is submitted.

To continue to avoid throttling parity reads on scrubs, we must add a throttle variable to skip throttling / bio shrinking on those bio submissions.

---
 fs/btrfs/scrub.c | 82 +++++++++++++++++++++++++++++++++++-------------
 1 file changed, 60 insertions(+), 22 deletions(-)
fs/btrfs/scrub.c +60 -22
index d68e8d2f766f..d7d986300793 100644
@@ -1823,12 +1823,37 @@ static u32 stripe_length(const struct scrub_stripe *stripe)
 		   stripe->bg->start + stripe->bg->length - stripe->logical);
 }
 
-static void scrub_submit_extent_sector_read(struct scrub_stripe *stripe)
+static u32 scrub_read_burst(const struct scrub_stripe *stripe)
+{
+	const u64 bwlimit = READ_ONCE(stripe->dev->scrub_speed_max);
+	const u32 sectorsize = stripe->bg->fs_info->sectorsize;
+	u64 burst;
+
+	if (bwlimit == 0)
+		return stripe->stripe_len;
+	/* units: (bytes / sec) * msec / (msec / sec) ==> bytes */
+	burst = mul_u64_u32_div(bwlimit, SCRUB_THROTTLE_BURST_MS, MSEC_PER_SEC);
+	burst = round_down(burst, sectorsize);
+	return clamp_t(u64, burst, sectorsize, stripe->stripe_len);
+}
+
+static void scrub_submit_read_bio(struct scrub_ctx *sctx, struct scrub_stripe *stripe,
+				  struct btrfs_bio *bbio, int mirror, bool throttle)
+{
+	if (throttle)
+		scrub_throttle_dev_io(sctx, stripe->dev, bbio->bio.bi_iter.bi_size);
+	scrub_stripe_get_io(stripe);
+	btrfs_submit_bbio(bbio, mirror);
+}
+
+static void scrub_submit_extent_sector_read(struct scrub_ctx *sctx,
+					    struct scrub_stripe *stripe, bool throttle)
 {
 	struct btrfs_fs_info *fs_info = stripe->bg->fs_info;
 	struct btrfs_bio *bbio = NULL;
 	unsigned int nr_sectors = stripe_length(stripe) >> fs_info->sectorsize_bits;
 	const unsigned long has_extent = scrub_bitmap_read_has_extent(stripe);
+	const u32 burst = throttle ? scrub_read_burst(stripe) : stripe->stripe_len;
 	u64 stripe_len = stripe->stripe_len;
 	int mirror = stripe->mirror_num;
 	int i;
@@ -1844,10 +1869,10 @@ static void scrub_submit_extent_sector_read(struct scrub_stripe *stripe)
 		/* The current sector cannot be merged, submit the bio. */
 		if (bbio &&
 		    ((i > 0 && !test_bit(i - 1, &has_extent)) ||
-		     bbio->bio.bi_iter.bi_size >= stripe_len)) {
+		     bbio->bio.bi_iter.bi_size >= stripe_len ||
+		     bbio->bio.bi_iter.bi_size >= burst)) {
 			ASSERT(bbio->bio.bi_iter.bi_size);
-			scrub_stripe_get_io(stripe);
-			btrfs_submit_bbio(bbio, mirror);
+			scrub_submit_read_bio(sctx, stripe, bbio, mirror, throttle);
 			bbio = NULL;
 		}
 
@@ -1892,8 +1917,7 @@ static void scrub_submit_extent_sector_read(struct scrub_stripe *stripe)
 
 	if (bbio) {
 		ASSERT(bbio->bio.bi_iter.bi_size);
-		scrub_stripe_get_io(stripe);
-		btrfs_submit_bbio(bbio, mirror);
+		scrub_submit_read_bio(sctx, stripe, bbio, mirror, throttle);
 	}
 
 	if (scrub_stripe_put_io(stripe)) {
@@ -1903,11 +1927,12 @@ static void scrub_submit_extent_sector_read(struct scrub_stripe *stripe)
 }
 
 static void scrub_submit_initial_read(struct scrub_ctx *sctx,
-				      struct scrub_stripe *stripe)
+				      struct scrub_stripe *stripe, bool throttle)
 {
 	struct btrfs_fs_info *fs_info = sctx->fs_info;
-	struct btrfs_bio *bbio;
+	struct btrfs_bio *bbio = NULL;
 	unsigned int nr_sectors = stripe_length(stripe) >> fs_info->sectorsize_bits;
+	const u32 burst = throttle ? scrub_read_burst(stripe) : stripe->stripe_len;
 	int mirror = stripe->mirror_num;
 
 	ASSERT(stripe->bg);
@@ -1915,17 +1940,10 @@ static void scrub_submit_initial_read(struct scrub_ctx *sctx,
 	ASSERT(test_bit(SCRUB_STRIPE_FLAG_INITIALIZED, &stripe->state));
 
 	if (btrfs_need_stripe_tree_update(fs_info, stripe->bg->flags)) {
-		scrub_submit_extent_sector_read(stripe);
+		scrub_submit_extent_sector_read(sctx, stripe, throttle);
 		return;
 	}
 
-	bbio = alloc_scrub_bbio(fs_info, REQ_OP_READ,
-				stripe->logical, scrub_read_endio, stripe);
-	/* Read the whole range inside the chunk boundary. */
-	for (unsigned int cur = 0; cur < nr_sectors; cur++)
-		scrub_bio_add_sector(bbio, stripe, cur);
-	scrub_stripe_get_io(stripe);
-
 	/*
 	 * For dev-replace, either user asks to avoid the source dev, or
 	 * the device is missing, we try the next mirror instead.
@@ -1939,7 +1957,29 @@ static void scrub_submit_initial_read(struct scrub_ctx *sctx,
 
 		mirror = calc_next_mirror(mirror, num_copies);
 	}
-	btrfs_submit_bbio(bbio, mirror);
+
+	/* The extra ref is dropped after all bios are submitted. */
+	scrub_stripe_get_io(stripe);
+
+	/* Read the whole range inside the chunk boundary, @burst bytes per bio. */
+	for (unsigned int cur = 0; cur < nr_sectors; cur++) {
+		if (bbio && bbio->bio.bi_iter.bi_size >= burst) {
+			scrub_submit_read_bio(sctx, stripe, bbio, mirror, throttle);
+			bbio = NULL;
+		}
+		if (!bbio)
+			bbio = alloc_scrub_bbio(fs_info, REQ_OP_READ,
+					stripe->logical + (cur << fs_info->sectorsize_bits),
+					scrub_read_endio, stripe);
+		scrub_bio_add_sector(bbio, stripe, cur);
+	}
+	if (bbio)
+		scrub_submit_read_bio(sctx, stripe, bbio, mirror, throttle);
+
+	if (scrub_stripe_put_io(stripe)) {
+		INIT_WORK(&stripe->work, scrub_stripe_read_repair_worker);
+		queue_work(stripe->bg->fs_info->scrub_workers, &stripe->work);
+	}
 }
 
 static bool stripe_has_metadata_error(struct scrub_stripe *stripe)
@@ -1970,16 +2010,13 @@ static void submit_initial_group_read(struct scrub_ctx *sctx,
 	ASSERT(first_slot < SCRUB_TOTAL_STRIPES);
 	ASSERT(first_slot + nr_stripes <= SCRUB_TOTAL_STRIPES);
 
-	scrub_throttle_dev_io(sctx, sctx->stripes[0].dev,
-			      btrfs_stripe_nr_to_offset(nr_stripes,
-						sctx->stripes[0].stripe_len));
 	blk_start_plug(&plug);
 	for (int i = 0; i < nr_stripes; i++) {
 		struct scrub_stripe *stripe = &sctx->stripes[first_slot + i];
 
 		/* Those stripes should be initialized. */
 		ASSERT(test_bit(SCRUB_STRIPE_FLAG_INITIALIZED, &stripe->state));
-		scrub_submit_initial_read(sctx, stripe);
+		scrub_submit_initial_read(sctx, stripe, true);
 	}
 	blk_finish_plug(&plug);
 }
@@ -2276,7 +2313,8 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
 
 	for (int i = 0; i < data_stripes; i++) {
 		stripe = &sctx->raid56_data_stripes[i];
-		scrub_submit_initial_read(sctx, stripe);
+		/* Do not throttle parity verification reads of other stripes. */
+		scrub_submit_initial_read(sctx, stripe, false);
 	}
 	for (int i = 0; i < data_stripes; i++) {
 		stripe = &sctx->raid56_data_stripes[i];
Signature · 1 line
2.56.0