xref: /freebsd/sys/contrib/openzfs/module/zfs/vdev_rebuild.c (revision efa8679e7f69c9cc225613827d9f75644cca5b3b)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  *
24  * Copyright (c) 2018, Intel Corporation.
25  * Copyright (c) 2020 by Lawrence Livermore National Security, LLC.
26  * Copyright (c) 2022, 2026 Hewlett Packard Enterprise Development LP.
27  * Copyright (c) 2024 by Delphix. All rights reserved.
28  */
29 
30 #include <sys/vdev_impl.h>
31 #include <sys/vdev_draid.h>
32 #include <sys/dsl_scan.h>
33 #include <sys/spa_impl.h>
34 #include <sys/metaslab_impl.h>
35 #include <sys/vdev_rebuild.h>
36 #include <sys/zio.h>
37 #include <sys/dmu_tx.h>
38 #include <sys/arc.h>
39 #include <sys/arc_impl.h>
40 #include <sys/zap.h>
41 
42 /*
43  * This file contains the sequential reconstruction implementation for
44  * resilvering.  This form of resilvering is internally referred to as device
45  * rebuild to avoid conflating it with the traditional healing reconstruction
46  * performed by the dsl scan code.
47  *
48  * When replacing a device, or scrubbing the pool, ZFS has historically used
49  * a process called resilvering which is a form of healing reconstruction.
50  * This approach has the advantage that as blocks are read from disk their
51  * checksums can be immediately verified and the data repaired.  Unfortunately,
52  * it also results in a random IO pattern to the disk even when extra care
53  * is taken to sequentialize the IO as much as possible.  This substantially
54  * increases the time required to resilver the pool and restore redundancy.
55  *
56  * For mirrored devices it's possible to implement an alternate sequential
57  * reconstruction strategy when resilvering.  Sequential reconstruction
58  * behaves like a traditional RAID rebuild and reconstructs a device in LBA
59  * order without verifying the checksum.  After this phase completes a second
60  * scrub phase is started to verify all of the checksums.  This two phase
61  * process will take longer than the healing reconstruction described above.
62  * However, it has that advantage that after the reconstruction first phase
63  * completes redundancy has been restored.  At this point the pool can incur
64  * another device failure without risking data loss.
65  *
66  * There are a few noteworthy limitations and other advantages of resilvering
67  * using sequential reconstruction vs healing reconstruction.
68  *
69  * Limitations:
70  *
71  *   - Sequential reconstruction is not possible on RAIDZ due to its
72  *     variable stripe width.  Note dRAID uses a fixed stripe width which
73  *     avoids this issue, but comes at the expense of some usable capacity.
74  *
75  *   - Block checksums are not verified during sequential reconstruction.
76  *     Similar to traditional RAID the parity/mirror data is reconstructed
77  *     but cannot be immediately double checked.  For this reason when the
78  *     last active resilver completes the pool is automatically scrubbed
79  *     by default.
80  *
81  *   - Deferred resilvers using sequential reconstruction are not currently
82  *     supported.  When adding another vdev to an active top-level resilver
83  *     it must be restarted.
84  *
85  * Advantages:
86  *
87  *   - Sequential reconstruction is performed in LBA order which may be faster
88  *     than healing reconstruction particularly when using HDDs (or
89  *     especially with SMR devices).  Only allocated capacity is resilvered.
90  *
91  *   - Sequential reconstruction is not constrained by ZFS block boundaries.
92  *     This allows it to issue larger IOs to disk which span multiple blocks
93  *     allowing all of these logical blocks to be repaired with a single IO.
94  *
95  *   - Unlike a healing resilver or scrub which are pool wide operations,
96  *     sequential reconstruction is handled by the top-level vdevs.  This
97  *     allows for it to be started or canceled on a top-level vdev without
98  *     impacting any other top-level vdevs in the pool.
99  *
100  *   - Data only referenced by a pool checkpoint will be repaired because
101  *     that space is reflected in the space maps.  This differs for a
102  *     healing resilver or scrub which will not repair that data.
103  */
104 
105 
106 /*
107  * Size of rebuild reads; defaults to 1MiB per data disk and is capped at
108  * SPA_MAXBLOCKSIZE.
109  */
110 static uint64_t zfs_rebuild_max_segment = 1024 * 1024;
111 
112 /*
113  * Maximum number of parallelly executed bytes per leaf vdev caused by a
114  * sequential resilver.  We attempt to strike a balance here between keeping
115  * the vdev queues full of I/Os at all times and not overflowing the queues
116  * to cause long latency, which would cause long txg sync times.
117  *
118  * A large default value can be safely used here because the default target
119  * segment size is also large (zfs_rebuild_max_segment=1M).  This helps keep
120  * the queue depth short.
121  *
122  * 64MB was observed to deliver the best performance and set as the default.
123  * Testing was performed with a 106-drive dRAID HDD pool (draid2:11d:106c)
124  * and a rebuild rate of 1.2GB/s was measured to the distribute spare.
125  * Smaller values were unable to fully saturate the available pool I/O.
126  */
127 static uint64_t zfs_rebuild_vdev_limit = 64 << 20;
128 
129 /*
130  * Automatically start a pool scrub when the last active sequential resilver
131  * completes in order to verify the checksums of all blocks which have been
132  * resilvered. This option is enabled by default and is strongly recommended.
133  */
134 static int zfs_rebuild_scrub_enabled = 1;
135 
136 /*
137  * For vdev_rebuild_initiate_sync() and vdev_rebuild_reset_sync().
138  */
139 static __attribute__((noreturn)) void vdev_rebuild_thread(void *arg);
140 static void vdev_rebuild_reset_sync(void *arg, dmu_tx_t *tx);
141 
142 /*
143  * Clear the per-vdev rebuild bytes value for a vdev tree.
144  */
145 static void
clear_rebuild_bytes(vdev_t * vd)146 clear_rebuild_bytes(vdev_t *vd)
147 {
148 	vdev_stat_t *vs = &vd->vdev_stat;
149 
150 	for (uint64_t i = 0; i < vd->vdev_children; i++)
151 		clear_rebuild_bytes(vd->vdev_child[i]);
152 
153 	mutex_enter(&vd->vdev_stat_lock);
154 	vs->vs_rebuild_processed = 0;
155 	mutex_exit(&vd->vdev_stat_lock);
156 }
157 
158 /*
159  * Determines whether a vdev_rebuild_thread() should be stopped.
160  */
161 static boolean_t
vdev_rebuild_should_stop(vdev_t * vd)162 vdev_rebuild_should_stop(vdev_t *vd)
163 {
164 	return (!vdev_writeable(vd) || vd->vdev_removing ||
165 	    vd->vdev_rebuild_exit_wanted ||
166 	    vd->vdev_rebuild_cancel_wanted ||
167 	    vd->vdev_rebuild_reset_wanted);
168 }
169 
170 /*
171  * Determine if the rebuild should be canceled.  This may happen when all
172  * vdevs with MISSING DTLs are detached.
173  */
174 static boolean_t
vdev_rebuild_should_cancel(vdev_t * vd)175 vdev_rebuild_should_cancel(vdev_t *vd)
176 {
177 	vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
178 	vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
179 
180 	if (!vdev_resilver_needed(vd, &vrp->vrp_min_txg, &vrp->vrp_max_txg))
181 		return (B_TRUE);
182 
183 	return (B_FALSE);
184 }
185 
186 /*
187  * The sync task for updating the on-disk state of a rebuild.  This is
188  * scheduled by vdev_rebuild_range().
189  */
190 static void
vdev_rebuild_update_sync(void * arg,dmu_tx_t * tx)191 vdev_rebuild_update_sync(void *arg, dmu_tx_t *tx)
192 {
193 	int vdev_id = (uintptr_t)arg;
194 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
195 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
196 	vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
197 	vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
198 	uint64_t txg = dmu_tx_get_txg(tx);
199 
200 	mutex_enter(&vd->vdev_rebuild_lock);
201 
202 	if (vr->vr_scan_offset[txg & TXG_MASK] > 0) {
203 		vrp->vrp_last_offset = vr->vr_scan_offset[txg & TXG_MASK];
204 		vr->vr_scan_offset[txg & TXG_MASK] = 0;
205 	}
206 
207 	vrp->vrp_scan_time_ms = vr->vr_prev_scan_time_ms +
208 	    NSEC2MSEC(gethrtime() - vr->vr_pass_start_time);
209 
210 	VERIFY0(zap_update(vd->vdev_spa->spa_meta_objset, vd->vdev_top_zap,
211 	    VDEV_TOP_ZAP_VDEV_REBUILD_PHYS, sizeof (uint64_t),
212 	    REBUILD_PHYS_ENTRIES, vrp, tx));
213 
214 	mutex_exit(&vd->vdev_rebuild_lock);
215 }
216 
217 /*
218  * Initialize the on-disk state for a new rebuild, start the rebuild thread.
219  */
220 static void
vdev_rebuild_initiate_sync(void * arg,dmu_tx_t * tx)221 vdev_rebuild_initiate_sync(void *arg, dmu_tx_t *tx)
222 {
223 	int vdev_id = (uintptr_t)arg;
224 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
225 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
226 	vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
227 	vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
228 
229 	ASSERT(vd->vdev_rebuilding);
230 
231 	spa_feature_incr(vd->vdev_spa, SPA_FEATURE_DEVICE_REBUILD, tx);
232 
233 	mutex_enter(&vd->vdev_rebuild_lock);
234 	memset(vrp, 0, sizeof (uint64_t) * REBUILD_PHYS_ENTRIES);
235 	vrp->vrp_rebuild_state = VDEV_REBUILD_ACTIVE;
236 	vrp->vrp_min_txg = TXG_INITIAL;
237 	vrp->vrp_max_txg = dmu_tx_get_txg(tx);
238 	vrp->vrp_start_time = gethrestime_sec();
239 	vrp->vrp_scan_time_ms = 0;
240 	vr->vr_prev_scan_time_ms = 0;
241 
242 	/*
243 	 * Rebuilds are currently only used when replacing a device, in which
244 	 * case there must be DTL_MISSING entries.  In the future, we could
245 	 * allow rebuilds to be used in a way similar to a scrub.  This would
246 	 * be useful because it would allow us to rebuild the space used by
247 	 * pool checkpoints.
248 	 */
249 	VERIFY(vdev_resilver_needed(vd, &vrp->vrp_min_txg, &vrp->vrp_max_txg));
250 
251 	VERIFY0(zap_update(vd->vdev_spa->spa_meta_objset, vd->vdev_top_zap,
252 	    VDEV_TOP_ZAP_VDEV_REBUILD_PHYS, sizeof (uint64_t),
253 	    REBUILD_PHYS_ENTRIES, vrp, tx));
254 
255 	spa_history_log_internal(spa, "rebuild", tx,
256 	    "vdev_id=%llu vdev_guid=%llu started",
257 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)vd->vdev_guid);
258 
259 	ASSERT0P(vd->vdev_rebuild_thread);
260 	vd->vdev_rebuild_thread = thread_create(NULL, 0,
261 	    vdev_rebuild_thread, vd, 0, &p0, TS_RUN, maxclsyspri);
262 
263 	mutex_exit(&vd->vdev_rebuild_lock);
264 }
265 
266 static void
vdev_rebuild_log_notify(spa_t * spa,vdev_t * vd,const char * name)267 vdev_rebuild_log_notify(spa_t *spa, vdev_t *vd, const char *name)
268 {
269 	nvlist_t *aux = fnvlist_alloc();
270 
271 	fnvlist_add_string(aux, ZFS_EV_RESILVER_TYPE, "sequential");
272 	spa_event_notify(spa, vd, aux, name);
273 	nvlist_free(aux);
274 }
275 
276 /*
277  * Called to request that a new rebuild be started.  The feature will remain
278  * active for the duration of the rebuild, then revert to the enabled state.
279  */
280 static void
vdev_rebuild_initiate(vdev_t * vd,uint64_t txg)281 vdev_rebuild_initiate(vdev_t *vd, uint64_t txg)
282 {
283 	spa_t *spa = vd->vdev_spa;
284 
285 	ASSERT(vd->vdev_top == vd);
286 	ASSERT(MUTEX_HELD(&vd->vdev_rebuild_lock));
287 	ASSERT(!vd->vdev_rebuilding);
288 
289 	dmu_tx_t *tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
290 
291 	vd->vdev_rebuilding = B_TRUE;
292 
293 	dsl_sync_task_nowait(spa_get_dsl(spa), vdev_rebuild_initiate_sync,
294 	    (void *)(uintptr_t)vd->vdev_id, tx);
295 	dmu_tx_commit(tx);
296 
297 	vdev_rebuild_log_notify(spa, vd, ESC_ZFS_RESILVER_START);
298 }
299 
300 /*
301  * Update the on-disk state to completed when a rebuild finishes.
302  */
303 static void
vdev_rebuild_complete_sync(void * arg,dmu_tx_t * tx)304 vdev_rebuild_complete_sync(void *arg, dmu_tx_t *tx)
305 {
306 	int vdev_id = (uintptr_t)arg;
307 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
308 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
309 	vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
310 	vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
311 
312 	mutex_enter(&vd->vdev_rebuild_lock);
313 
314 	/*
315 	 * Handle a second device failure if it occurs after all rebuild I/O
316 	 * has completed but before this sync task has been executed.
317 	 */
318 	if (vd->vdev_rebuild_reset_wanted) {
319 		mutex_exit(&vd->vdev_rebuild_lock);
320 		vdev_rebuild_reset_sync(arg, tx);
321 		return;
322 	}
323 
324 	vrp->vrp_rebuild_state = VDEV_REBUILD_COMPLETE;
325 	vrp->vrp_end_time = gethrestime_sec();
326 
327 	VERIFY0(zap_update(vd->vdev_spa->spa_meta_objset, vd->vdev_top_zap,
328 	    VDEV_TOP_ZAP_VDEV_REBUILD_PHYS, sizeof (uint64_t),
329 	    REBUILD_PHYS_ENTRIES, vrp, tx));
330 
331 	vdev_dtl_reassess(vd, tx->tx_txg, vrp->vrp_max_txg, B_TRUE, B_TRUE);
332 	spa_feature_decr(vd->vdev_spa, SPA_FEATURE_DEVICE_REBUILD, tx);
333 
334 	spa_history_log_internal(spa, "rebuild",  tx,
335 	    "vdev_id=%llu vdev_guid=%llu complete",
336 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)vd->vdev_guid);
337 	vdev_rebuild_log_notify(spa, vd, ESC_ZFS_RESILVER_FINISH);
338 
339 	/* Handles detaching of spares */
340 	spa_async_request(spa, SPA_ASYNC_REBUILD_DONE);
341 	vd->vdev_rebuilding = B_FALSE;
342 	mutex_exit(&vd->vdev_rebuild_lock);
343 
344 	/*
345 	 * While we're in syncing context take the opportunity to
346 	 * setup the scrub when there are no more active rebuilds.
347 	 */
348 	setup_sync_arg_t setup_sync_arg = {
349 		.func = POOL_SCAN_SCRUB,
350 		.txgstart = 0,
351 		.txgend = 0,
352 	};
353 	if (dsl_scan_setup_check(&setup_sync_arg.func, tx) == 0 &&
354 	    zfs_rebuild_scrub_enabled) {
355 		dsl_scan_setup_sync(&setup_sync_arg, tx);
356 	}
357 
358 	cv_broadcast(&vd->vdev_rebuild_cv);
359 
360 	/* Clear recent error events (i.e. duplicate events tracking) */
361 	zfs_ereport_clear(spa, NULL);
362 }
363 
364 /*
365  * Update the on-disk state to canceled when a rebuild finishes.
366  */
367 static void
vdev_rebuild_cancel_sync(void * arg,dmu_tx_t * tx)368 vdev_rebuild_cancel_sync(void *arg, dmu_tx_t *tx)
369 {
370 	int vdev_id = (uintptr_t)arg;
371 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
372 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
373 	vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
374 	vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
375 
376 	mutex_enter(&vd->vdev_rebuild_lock);
377 	vrp->vrp_rebuild_state = VDEV_REBUILD_CANCELED;
378 	vrp->vrp_end_time = gethrestime_sec();
379 
380 	VERIFY0(zap_update(vd->vdev_spa->spa_meta_objset, vd->vdev_top_zap,
381 	    VDEV_TOP_ZAP_VDEV_REBUILD_PHYS, sizeof (uint64_t),
382 	    REBUILD_PHYS_ENTRIES, vrp, tx));
383 
384 	spa_feature_decr(vd->vdev_spa, SPA_FEATURE_DEVICE_REBUILD, tx);
385 
386 	spa_history_log_internal(spa, "rebuild",  tx,
387 	    "vdev_id=%llu vdev_guid=%llu canceled",
388 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)vd->vdev_guid);
389 	vdev_rebuild_log_notify(spa, vd, ESC_ZFS_RESILVER_FINISH);
390 
391 	vd->vdev_rebuild_cancel_wanted = B_FALSE;
392 	vd->vdev_rebuilding = B_FALSE;
393 	mutex_exit(&vd->vdev_rebuild_lock);
394 
395 	spa_notify_waiters(spa);
396 	cv_broadcast(&vd->vdev_rebuild_cv);
397 }
398 
399 /*
400  * Resets the progress of a running rebuild.  This will occur when a new
401  * vdev is added to rebuild.
402  */
403 static void
vdev_rebuild_reset_sync(void * arg,dmu_tx_t * tx)404 vdev_rebuild_reset_sync(void *arg, dmu_tx_t *tx)
405 {
406 	int vdev_id = (uintptr_t)arg;
407 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
408 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
409 	vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
410 	vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
411 
412 	mutex_enter(&vd->vdev_rebuild_lock);
413 
414 	ASSERT(vrp->vrp_rebuild_state == VDEV_REBUILD_ACTIVE);
415 	ASSERT0P(vd->vdev_rebuild_thread);
416 
417 	vrp->vrp_last_offset = 0;
418 	vrp->vrp_min_txg = TXG_INITIAL;
419 	vrp->vrp_max_txg = dmu_tx_get_txg(tx);
420 	vrp->vrp_bytes_scanned = 0;
421 	vrp->vrp_bytes_issued = 0;
422 	vrp->vrp_bytes_rebuilt = 0;
423 	vrp->vrp_bytes_est = 0;
424 	vrp->vrp_scan_time_ms = 0;
425 	vr->vr_prev_scan_time_ms = 0;
426 
427 	/* See vdev_rebuild_initiate_sync comment */
428 	VERIFY(vdev_resilver_needed(vd, &vrp->vrp_min_txg, &vrp->vrp_max_txg));
429 
430 	VERIFY0(zap_update(vd->vdev_spa->spa_meta_objset, vd->vdev_top_zap,
431 	    VDEV_TOP_ZAP_VDEV_REBUILD_PHYS, sizeof (uint64_t),
432 	    REBUILD_PHYS_ENTRIES, vrp, tx));
433 
434 	spa_history_log_internal(spa, "rebuild",  tx,
435 	    "vdev_id=%llu vdev_guid=%llu reset",
436 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)vd->vdev_guid);
437 
438 	vd->vdev_rebuild_reset_wanted = B_FALSE;
439 	ASSERT(vd->vdev_rebuilding);
440 
441 	vd->vdev_rebuild_thread = thread_create(NULL, 0,
442 	    vdev_rebuild_thread, vd, 0, &p0, TS_RUN, maxclsyspri);
443 
444 	mutex_exit(&vd->vdev_rebuild_lock);
445 }
446 
447 /*
448  * Clear the last rebuild status.
449  */
450 void
vdev_rebuild_clear_sync(void * arg,dmu_tx_t * tx)451 vdev_rebuild_clear_sync(void *arg, dmu_tx_t *tx)
452 {
453 	int vdev_id = (uintptr_t)arg;
454 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
455 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
456 	vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
457 	vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
458 	objset_t *mos = spa_meta_objset(spa);
459 
460 	mutex_enter(&vd->vdev_rebuild_lock);
461 
462 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_DEVICE_REBUILD) ||
463 	    vrp->vrp_rebuild_state == VDEV_REBUILD_ACTIVE) {
464 		mutex_exit(&vd->vdev_rebuild_lock);
465 		return;
466 	}
467 
468 	clear_rebuild_bytes(vd);
469 	memset(vrp, 0, sizeof (uint64_t) * REBUILD_PHYS_ENTRIES);
470 
471 	if (vd->vdev_top_zap != 0 && zap_contains(mos, vd->vdev_top_zap,
472 	    VDEV_TOP_ZAP_VDEV_REBUILD_PHYS) == 0) {
473 		VERIFY0(zap_update(mos, vd->vdev_top_zap,
474 		    VDEV_TOP_ZAP_VDEV_REBUILD_PHYS, sizeof (uint64_t),
475 		    REBUILD_PHYS_ENTRIES, vrp, tx));
476 	}
477 
478 	mutex_exit(&vd->vdev_rebuild_lock);
479 }
480 
481 /*
482  * The zio_done_func_t callback for each rebuild I/O issued.  It's responsible
483  * for updating the rebuild stats and limiting the number of in flight I/Os.
484  */
485 static void
vdev_rebuild_cb(zio_t * zio)486 vdev_rebuild_cb(zio_t *zio)
487 {
488 	vdev_rebuild_t *vr = zio->io_private;
489 	vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
490 	vdev_t *vd = vr->vr_top_vdev;
491 
492 	mutex_enter(&vr->vr_io_lock);
493 	if (zio->io_error == ENXIO && !vdev_writeable(vd)) {
494 		/*
495 		 * The I/O failed because the top-level vdev was unavailable.
496 		 * Attempt to roll back to the last completed offset, in order
497 		 * resume from the correct location if the pool is resumed.
498 		 * (This works because spa_sync waits on spa_txg_zio before
499 		 * it runs sync tasks.)
500 		 */
501 		uint64_t *off = &vr->vr_scan_offset[zio->io_txg & TXG_MASK];
502 		*off = MIN(*off, zio->io_offset);
503 	} else if (zio->io_error) {
504 		vrp->vrp_errors++;
505 	}
506 
507 	abd_free(zio->io_abd);
508 
509 	ASSERT3U(vr->vr_bytes_inflight, >, 0);
510 	vr->vr_bytes_inflight -= zio->io_size;
511 	cv_broadcast(&vr->vr_io_cv);
512 	mutex_exit(&vr->vr_io_lock);
513 
514 	spa_config_exit(vd->vdev_spa, SCL_STATE_ALL, vd);
515 }
516 
517 /*
518  * Initialize a block pointer that can be used to read the given segment
519  * for sequential rebuild.
520  */
521 static void
vdev_rebuild_blkptr_init(blkptr_t * bp,vdev_t * vd,uint64_t start,uint64_t asize)522 vdev_rebuild_blkptr_init(blkptr_t *bp, vdev_t *vd, uint64_t start,
523     uint64_t asize)
524 {
525 	ASSERT(vd->vdev_ops == &vdev_draid_ops ||
526 	    vd->vdev_ops == &vdev_mirror_ops ||
527 	    vd->vdev_ops == &vdev_replacing_ops ||
528 	    vd->vdev_ops == &vdev_spare_ops);
529 
530 	uint64_t psize = vd->vdev_ops == &vdev_draid_ops ?
531 	    vdev_draid_asize_to_psize(vd, asize, 0) : asize;
532 
533 	BP_ZERO(bp);
534 
535 	DVA_SET_VDEV(&bp->blk_dva[0], vd->vdev_id);
536 	DVA_SET_OFFSET(&bp->blk_dva[0], start);
537 	DVA_SET_GANG(&bp->blk_dva[0], 0);
538 	DVA_SET_ASIZE(&bp->blk_dva[0], asize);
539 
540 	BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
541 	BP_SET_LSIZE(bp, psize);
542 	BP_SET_PSIZE(bp, psize);
543 	BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
544 	BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
545 	BP_SET_TYPE(bp, DMU_OT_NONE);
546 	BP_SET_LEVEL(bp, 0);
547 	BP_SET_DEDUP(bp, 0);
548 	BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
549 }
550 
551 /*
552  * Issues a rebuild I/O and takes care of rate limiting the number of queued
553  * rebuild I/Os.  The provided start and size must be properly aligned for the
554  * top-level vdev type being rebuilt.
555  */
556 static int
vdev_rebuild_range(vdev_rebuild_t * vr,uint64_t start,uint64_t size)557 vdev_rebuild_range(vdev_rebuild_t *vr, uint64_t start, uint64_t size)
558 {
559 	uint64_t ms_id __maybe_unused = vr->vr_scan_msp->ms_id;
560 	vdev_t *vd = vr->vr_top_vdev;
561 	spa_t *spa = vd->vdev_spa;
562 	blkptr_t blk;
563 
564 	ASSERT3U(ms_id, ==, start >> vd->vdev_ms_shift);
565 	ASSERT3U(ms_id, ==, (start + size - 1) >> vd->vdev_ms_shift);
566 
567 	vr->vr_pass_bytes_scanned += size;
568 	vr->vr_rebuild_phys.vrp_bytes_scanned += size;
569 
570 	/*
571 	 * Rebuild the data in this range by constructing a special block
572 	 * pointer.  It has no relation to any existing blocks in the pool.
573 	 * However, by disabling checksum verification and issuing a scrub IO
574 	 * we can reconstruct and repair any children with missing data.
575 	 */
576 	vdev_rebuild_blkptr_init(&blk, vd, start, size);
577 	uint64_t psize = BP_GET_PSIZE(&blk);
578 
579 	if (!vdev_dtl_need_resilver(vd, &blk.blk_dva[0], psize, TXG_UNKNOWN)) {
580 		vr->vr_pass_bytes_skipped += size;
581 		return (0);
582 	}
583 
584 	mutex_enter(&vr->vr_io_lock);
585 
586 	/* Limit in flight rebuild I/Os */
587 	while (vr->vr_bytes_inflight >= vr->vr_bytes_inflight_max)
588 		cv_wait(&vr->vr_io_cv, &vr->vr_io_lock);
589 
590 	vr->vr_bytes_inflight += psize;
591 	mutex_exit(&vr->vr_io_lock);
592 
593 	dmu_tx_t *tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
594 	VERIFY0(dmu_tx_assign(tx, DMU_TX_WAIT | DMU_TX_SUSPEND));
595 	uint64_t txg = dmu_tx_get_txg(tx);
596 	vr->vr_last_txg = txg;
597 
598 	spa_config_enter(spa, SCL_STATE_ALL, vd, RW_READER);
599 	mutex_enter(&vd->vdev_rebuild_lock);
600 
601 	/* This is the first I/O for this txg. */
602 	if (vr->vr_scan_offset[txg & TXG_MASK] == 0) {
603 		vr->vr_scan_offset[txg & TXG_MASK] = start;
604 		dsl_sync_task_nowait(spa_get_dsl(spa),
605 		    vdev_rebuild_update_sync,
606 		    (void *)(uintptr_t)vd->vdev_id, tx);
607 	}
608 
609 	/* When exiting write out our progress. */
610 	if (vdev_rebuild_should_stop(vd)) {
611 		mutex_enter(&vr->vr_io_lock);
612 		vr->vr_bytes_inflight -= psize;
613 		mutex_exit(&vr->vr_io_lock);
614 		spa_config_exit(vd->vdev_spa, SCL_STATE_ALL, vd);
615 		mutex_exit(&vd->vdev_rebuild_lock);
616 		dmu_tx_commit(tx);
617 		return (SET_ERROR(EINTR));
618 	}
619 	mutex_exit(&vd->vdev_rebuild_lock);
620 
621 	vr->vr_scan_offset[txg & TXG_MASK] = start + size;
622 	vr->vr_pass_bytes_issued += size;
623 	vr->vr_rebuild_phys.vrp_bytes_issued += size;
624 
625 	zio_nowait(zio_read(spa->spa_txg_zio[txg & TXG_MASK], spa, &blk,
626 	    abd_alloc(psize, B_FALSE), psize, vdev_rebuild_cb, vr,
627 	    ZIO_PRIORITY_REBUILD, ZIO_FLAG_RAW | ZIO_FLAG_CANFAIL |
628 	    ZIO_FLAG_RESILVER, NULL));
629 	/* vdev_rebuild_cb releases SCL_STATE_ALL */
630 
631 	dmu_tx_commit(tx);
632 
633 	return (0);
634 }
635 
636 /*
637  * Issues rebuild I/Os for all ranges in the provided vr->vr_tree range tree.
638  */
639 static int
vdev_rebuild_ranges(vdev_rebuild_t * vr)640 vdev_rebuild_ranges(vdev_rebuild_t *vr)
641 {
642 	vdev_t *vd = vr->vr_top_vdev;
643 	zfs_btree_t *t = &vr->vr_scan_tree->rt_root;
644 	zfs_btree_index_t idx;
645 	int error;
646 
647 	for (zfs_range_seg_t *rs = zfs_btree_first(t, &idx); rs != NULL;
648 	    rs = zfs_btree_next(t, &idx, &idx)) {
649 		uint64_t start = zfs_rs_get_start(rs, vr->vr_scan_tree);
650 		uint64_t size = zfs_rs_get_end(rs, vr->vr_scan_tree) - start;
651 
652 		/*
653 		 * zfs_scan_suspend_progress can be set to disable rebuild
654 		 * progress for testing.  See comment in dsl_scan_sync().
655 		 */
656 		while (zfs_scan_suspend_progress &&
657 		    !vdev_rebuild_should_stop(vd)) {
658 			delay(hz);
659 		}
660 
661 		while (size > 0) {
662 			uint64_t chunk_size;
663 
664 			/*
665 			 * Split range into legally-sized logical chunks
666 			 * given the constraints of the top-level vdev
667 			 * being rebuilt (dRAID or mirror).
668 			 */
669 			ASSERT3P(vd->vdev_ops, !=, NULL);
670 			chunk_size = vd->vdev_ops->vdev_op_rebuild_asize(vd,
671 			    start, size, zfs_rebuild_max_segment);
672 
673 			error = vdev_rebuild_range(vr, start, chunk_size);
674 			if (error != 0)
675 				return (error);
676 
677 			size -= chunk_size;
678 			start += chunk_size;
679 		}
680 	}
681 
682 	return (0);
683 }
684 
685 /*
686  * Calculates the estimated capacity which remains to be scanned.  Since
687  * we traverse the pool in metaslab order only allocated capacity beyond
688  * the vrp_last_offset need be considered.  All lower offsets must have
689  * already been rebuilt and are thus already included in vrp_bytes_scanned.
690  */
691 static void
vdev_rebuild_update_bytes_est(vdev_t * vd,uint64_t ms_id)692 vdev_rebuild_update_bytes_est(vdev_t *vd, uint64_t ms_id)
693 {
694 	vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
695 	vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
696 	uint64_t bytes_est = vrp->vrp_bytes_scanned;
697 
698 	if (vrp->vrp_last_offset < vd->vdev_ms[ms_id]->ms_start)
699 		return;
700 
701 	for (uint64_t i = ms_id; i < vd->vdev_ms_count; i++) {
702 		metaslab_t *msp = vd->vdev_ms[i];
703 
704 		mutex_enter(&msp->ms_lock);
705 		bytes_est += metaslab_allocated_space(msp);
706 		mutex_exit(&msp->ms_lock);
707 	}
708 
709 	vrp->vrp_bytes_est = bytes_est;
710 }
711 
712 /*
713  * Load from disk the top-level vdev's rebuild information.
714  */
715 int
vdev_rebuild_load(vdev_t * vd)716 vdev_rebuild_load(vdev_t *vd)
717 {
718 	vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
719 	vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
720 	spa_t *spa = vd->vdev_spa;
721 	int err = 0;
722 
723 	mutex_enter(&vd->vdev_rebuild_lock);
724 	vd->vdev_rebuilding = B_FALSE;
725 
726 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_DEVICE_REBUILD)) {
727 		memset(vrp, 0, sizeof (uint64_t) * REBUILD_PHYS_ENTRIES);
728 		mutex_exit(&vd->vdev_rebuild_lock);
729 		return (SET_ERROR(ENOTSUP));
730 	}
731 
732 	ASSERT(vd->vdev_top == vd);
733 
734 	err = zap_lookup(spa->spa_meta_objset, vd->vdev_top_zap,
735 	    VDEV_TOP_ZAP_VDEV_REBUILD_PHYS, sizeof (uint64_t),
736 	    REBUILD_PHYS_ENTRIES, vrp);
737 
738 	/*
739 	 * A missing or damaged VDEV_TOP_ZAP_VDEV_REBUILD_PHYS should
740 	 * not prevent a pool from being imported.  Clear the rebuild
741 	 * status allowing a new resilver/rebuild to be started.
742 	 */
743 	if (err == ENOENT || err == EOVERFLOW || err == ECKSUM) {
744 		memset(vrp, 0, sizeof (uint64_t) * REBUILD_PHYS_ENTRIES);
745 	} else if (err) {
746 		mutex_exit(&vd->vdev_rebuild_lock);
747 		return (err);
748 	}
749 
750 	vr->vr_prev_scan_time_ms = vrp->vrp_scan_time_ms;
751 	vr->vr_top_vdev = vd;
752 
753 	mutex_exit(&vd->vdev_rebuild_lock);
754 
755 	return (0);
756 }
757 
758 /*
759  * Each scan thread is responsible for rebuilding a top-level vdev.  The
760  * rebuild progress in tracked on-disk in VDEV_TOP_ZAP_VDEV_REBUILD_PHYS.
761  */
762 static __attribute__((noreturn)) void
vdev_rebuild_thread(void * arg)763 vdev_rebuild_thread(void *arg)
764 {
765 	vdev_t *vd = arg;
766 	spa_t *spa = vd->vdev_spa;
767 	vdev_t *rvd = spa->spa_root_vdev;
768 	dsl_pool_t *dp = spa_get_dsl(spa);
769 	int error = 0;
770 
771 	/*
772 	 * If there's a scrub in process request that it be stopped.  This
773 	 * is not required for a correct rebuild, but we do want rebuilds to
774 	 * emulate the resilver behavior as much as possible.
775 	 */
776 	if (dsl_scan_scrubbing(dp))
777 		dsl_scan_cancel(dp);
778 
779 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
780 	mutex_enter(&vd->vdev_rebuild_lock);
781 
782 	ASSERT3P(vd->vdev_top, ==, vd);
783 	ASSERT3P(vd->vdev_rebuild_thread, !=, NULL);
784 	ASSERT(vd->vdev_rebuilding);
785 	ASSERT(spa_feature_is_active(spa, SPA_FEATURE_DEVICE_REBUILD));
786 	ASSERT3B(vd->vdev_rebuild_cancel_wanted, ==, B_FALSE);
787 
788 	vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
789 	vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
790 	vr->vr_top_vdev = vd;
791 	vr->vr_scan_msp = NULL;
792 	vr->vr_scan_tree = zfs_range_tree_create_flags(
793 	    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
794 	    ZFS_RT_F_DYN_NAME, vdev_rt_name(vd, "vr_scan_tree"));
795 	mutex_init(&vr->vr_io_lock, NULL, MUTEX_DEFAULT, NULL);
796 	cv_init(&vr->vr_io_cv, NULL, CV_DEFAULT, NULL);
797 
798 	vr->vr_pass_start_time = gethrtime();
799 	vr->vr_pass_bytes_scanned = 0;
800 	vr->vr_pass_bytes_issued = 0;
801 	vr->vr_pass_bytes_skipped = 0;
802 
803 	uint64_t update_est_time = gethrtime();
804 	vdev_rebuild_update_bytes_est(vd, 0);
805 
806 	clear_rebuild_bytes(vr->vr_top_vdev);
807 
808 	mutex_exit(&vd->vdev_rebuild_lock);
809 
810 	/*
811 	 * Systematically walk the metaslabs and issue rebuild I/Os for
812 	 * all ranges in the allocated space map.
813 	 */
814 	for (uint64_t i = 0; i < vd->vdev_ms_count; i++) {
815 		metaslab_t *msp = vd->vdev_ms[i];
816 		vr->vr_scan_msp = msp;
817 
818 		/*
819 		 * Calculate the max number of in-flight bytes for top-level
820 		 * vdev scanning operations (minimum 1MB, maximum 1/2 of
821 		 * arc_c_max shared by all top-level vdevs).  Limits for the
822 		 * issuing phase are done per top-level vdev and are handled
823 		 * separately.
824 		 */
825 		uint64_t limit = (arc_c_max / 2) / MAX(rvd->vdev_children, 1);
826 		vr->vr_bytes_inflight_max = MIN(limit, MAX(1ULL << 20,
827 		    zfs_rebuild_vdev_limit * vd->vdev_children));
828 		vr->vr_last_txg = 0;
829 
830 		/*
831 		 * Removal of vdevs from the vdev tree may eliminate the need
832 		 * for the rebuild, in which case it should be canceled.  The
833 		 * vdev_rebuild_cancel_wanted flag is set until the sync task
834 		 * completes.  This may be after the rebuild thread exits.
835 		 */
836 		if (vdev_rebuild_should_cancel(vd)) {
837 			vd->vdev_rebuild_cancel_wanted = B_TRUE;
838 			error = EINTR;
839 			break;
840 		}
841 
842 		ASSERT0(zfs_range_tree_space(vr->vr_scan_tree));
843 
844 		/* Disable any new allocations to this metaslab */
845 		spa_config_exit(spa, SCL_CONFIG, FTAG);
846 		metaslab_disable(msp);
847 
848 		mutex_enter(&msp->ms_sync_lock);
849 		mutex_enter(&msp->ms_lock);
850 
851 		/*
852 		 * If there are outstanding allocations wait for them to be
853 		 * synced.  This is needed to ensure all allocated ranges are
854 		 * on disk and therefore will be rebuilt.
855 		 */
856 		for (int j = 0; j < TXG_SIZE; j++) {
857 			if (zfs_range_tree_space(msp->ms_allocating[j])) {
858 				mutex_exit(&msp->ms_lock);
859 				mutex_exit(&msp->ms_sync_lock);
860 				txg_wait_synced(dp, 0);
861 				mutex_enter(&msp->ms_sync_lock);
862 				mutex_enter(&msp->ms_lock);
863 				break;
864 			}
865 		}
866 
867 		/*
868 		 * When a metaslab has been allocated from read its allocated
869 		 * ranges from the space map object into the vr_scan_tree.
870 		 * Then add inflight / unflushed ranges and remove inflight /
871 		 * unflushed frees.  This is the minimum range to be rebuilt.
872 		 */
873 		if (msp->ms_sm != NULL) {
874 			VERIFY0(space_map_load(msp->ms_sm,
875 			    vr->vr_scan_tree, SM_ALLOC));
876 
877 			for (int i = 0; i < TXG_SIZE; i++) {
878 				ASSERT0(zfs_range_tree_space(
879 				    msp->ms_allocating[i]));
880 			}
881 
882 			zfs_range_tree_walk(msp->ms_unflushed_allocs,
883 			    zfs_range_tree_add, vr->vr_scan_tree);
884 			zfs_range_tree_walk(msp->ms_unflushed_frees,
885 			    zfs_range_tree_remove, vr->vr_scan_tree);
886 
887 			/*
888 			 * Remove ranges which have already been rebuilt based
889 			 * on the last offset.  This can happen when restarting
890 			 * a scan after exporting and re-importing the pool.
891 			 */
892 			zfs_range_tree_clear(vr->vr_scan_tree, 0,
893 			    vrp->vrp_last_offset);
894 		}
895 
896 		mutex_exit(&msp->ms_lock);
897 		mutex_exit(&msp->ms_sync_lock);
898 
899 		/*
900 		 * To provide an accurate estimate re-calculate the estimated
901 		 * size every 5 minutes to account for recent allocations and
902 		 * frees made to space maps which have not yet been rebuilt.
903 		 */
904 		if (gethrtime() > update_est_time + SEC2NSEC(300)) {
905 			update_est_time = gethrtime();
906 			vdev_rebuild_update_bytes_est(vd, i);
907 		}
908 
909 		/*
910 		 * Walk the allocated space map and issue the rebuild I/O.
911 		 */
912 		error = vdev_rebuild_ranges(vr);
913 		zfs_range_tree_vacate(vr->vr_scan_tree, NULL, NULL);
914 
915 		/*
916 		 * Allow rebuilt ranges to be sync-ed before enabling metaslab
917 		 * to avoid any interfering allocations. Otherwise, we might
918 		 * see checksum errors after scrub.
919 		 */
920 		if (vr->vr_last_txg != 0)
921 			txg_wait_synced(dp, vr->vr_last_txg);
922 
923 		metaslab_enable(msp, B_FALSE, B_FALSE);
924 		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
925 
926 		if (error != 0)
927 			break;
928 	}
929 
930 	zfs_range_tree_destroy(vr->vr_scan_tree);
931 	spa_config_exit(spa, SCL_CONFIG, FTAG);
932 
933 	/* Wait for any remaining rebuild I/O to complete */
934 	mutex_enter(&vr->vr_io_lock);
935 	while (vr->vr_bytes_inflight > 0)
936 		cv_wait(&vr->vr_io_cv, &vr->vr_io_lock);
937 
938 	mutex_exit(&vr->vr_io_lock);
939 
940 	mutex_destroy(&vr->vr_io_lock);
941 	cv_destroy(&vr->vr_io_cv);
942 
943 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
944 
945 	dmu_tx_t *tx = dmu_tx_create_dd(dp->dp_mos_dir);
946 	VERIFY0(dmu_tx_assign(tx, DMU_TX_WAIT | DMU_TX_SUSPEND));
947 
948 	mutex_enter(&vd->vdev_rebuild_lock);
949 	if (error == 0) {
950 		/*
951 		 * After a successful rebuild clear the DTLs of all ranges
952 		 * which were missing when the rebuild was started.  These
953 		 * ranges must have been rebuilt as a consequence of rebuilding
954 		 * all allocated space.  Note that unlike a scrub or resilver
955 		 * the rebuild operation will reconstruct data only referenced
956 		 * by a pool checkpoint.  See the dsl_scan_done() comments.
957 		 */
958 		dsl_sync_task_nowait(dp, vdev_rebuild_complete_sync,
959 		    (void *)(uintptr_t)vd->vdev_id, tx);
960 	} else if (vd->vdev_rebuild_cancel_wanted) {
961 		/*
962 		 * The rebuild operation was canceled.  This will occur when
963 		 * a device participating in the rebuild is detached.
964 		 */
965 		dsl_sync_task_nowait(dp, vdev_rebuild_cancel_sync,
966 		    (void *)(uintptr_t)vd->vdev_id, tx);
967 	} else if (vd->vdev_rebuild_reset_wanted) {
968 		/*
969 		 * Reset the running rebuild without canceling and restarting
970 		 * it.  This will occur when a new device is attached and must
971 		 * participate in the rebuild.
972 		 */
973 		dsl_sync_task_nowait(dp, vdev_rebuild_reset_sync,
974 		    (void *)(uintptr_t)vd->vdev_id, tx);
975 	} else {
976 		/*
977 		 * The rebuild operation should be suspended.  This may occur
978 		 * when detaching a child vdev or when exporting the pool.  The
979 		 * rebuild is left in the active state so it will be resumed.
980 		 */
981 		ASSERT(vrp->vrp_rebuild_state == VDEV_REBUILD_ACTIVE);
982 		vd->vdev_rebuilding = B_FALSE;
983 	}
984 
985 	dmu_tx_commit(tx);
986 
987 	vd->vdev_rebuild_thread = NULL;
988 	mutex_exit(&vd->vdev_rebuild_lock);
989 	spa_config_exit(spa, SCL_CONFIG, FTAG);
990 
991 	cv_broadcast(&vd->vdev_rebuild_cv);
992 
993 	thread_exit();
994 }
995 
996 /*
997  * Returns B_TRUE if any top-level vdev are rebuilding.
998  */
999 boolean_t
vdev_rebuild_active(vdev_t * vd)1000 vdev_rebuild_active(vdev_t *vd)
1001 {
1002 	spa_t *spa = vd->vdev_spa;
1003 	boolean_t ret = B_FALSE;
1004 
1005 	if (vd == spa->spa_root_vdev) {
1006 		for (uint64_t i = 0; i < vd->vdev_children; i++) {
1007 			ret = vdev_rebuild_active(vd->vdev_child[i]);
1008 			if (ret)
1009 				return (ret);
1010 		}
1011 	} else if (vd->vdev_top_zap != 0) {
1012 		vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
1013 		vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
1014 
1015 		mutex_enter(&vd->vdev_rebuild_lock);
1016 		ret = (vrp->vrp_rebuild_state == VDEV_REBUILD_ACTIVE);
1017 		mutex_exit(&vd->vdev_rebuild_lock);
1018 	}
1019 
1020 	return (ret);
1021 }
1022 
1023 /*
1024  * Start a rebuild operation.  The rebuild may be restarted when the
1025  * top-level vdev is currently actively rebuilding.
1026  */
1027 void
vdev_rebuild(vdev_t * vd,uint64_t txg)1028 vdev_rebuild(vdev_t *vd, uint64_t txg)
1029 {
1030 	vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
1031 	vdev_rebuild_phys_t *vrp __maybe_unused = &vr->vr_rebuild_phys;
1032 
1033 	ASSERT(vd->vdev_top == vd);
1034 	ASSERT(vdev_is_concrete(vd));
1035 	ASSERT(!vd->vdev_removing);
1036 	ASSERT(spa_feature_is_enabled(vd->vdev_spa,
1037 	    SPA_FEATURE_DEVICE_REBUILD));
1038 
1039 	mutex_enter(&vd->vdev_rebuild_lock);
1040 	if (vd->vdev_rebuilding) {
1041 		ASSERT3U(vrp->vrp_rebuild_state, ==, VDEV_REBUILD_ACTIVE);
1042 
1043 		/*
1044 		 * Signal a running rebuild operation that it should restart
1045 		 * from the beginning because a new device was attached.  The
1046 		 * vdev_rebuild_reset_wanted flag is set until the sync task
1047 		 * completes.  This may be after the rebuild thread exits.
1048 		 */
1049 		if (!vd->vdev_rebuild_reset_wanted)
1050 			vd->vdev_rebuild_reset_wanted = B_TRUE;
1051 	} else {
1052 		vdev_rebuild_initiate(vd, txg);
1053 	}
1054 	mutex_exit(&vd->vdev_rebuild_lock);
1055 }
1056 
1057 static void
vdev_rebuild_restart_impl(vdev_t * vd)1058 vdev_rebuild_restart_impl(vdev_t *vd)
1059 {
1060 	spa_t *spa = vd->vdev_spa;
1061 
1062 	if (vd == spa->spa_root_vdev) {
1063 		for (uint64_t i = 0; i < vd->vdev_children; i++)
1064 			vdev_rebuild_restart_impl(vd->vdev_child[i]);
1065 
1066 	} else if (vd->vdev_top_zap != 0) {
1067 		vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
1068 		vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
1069 
1070 		mutex_enter(&vd->vdev_rebuild_lock);
1071 		if (vrp->vrp_rebuild_state == VDEV_REBUILD_ACTIVE &&
1072 		    vdev_writeable(vd) && !vd->vdev_rebuilding) {
1073 			ASSERT(spa_feature_is_active(spa,
1074 			    SPA_FEATURE_DEVICE_REBUILD));
1075 			vd->vdev_rebuilding = B_TRUE;
1076 			vd->vdev_rebuild_thread = thread_create(NULL, 0,
1077 			    vdev_rebuild_thread, vd, 0, &p0, TS_RUN,
1078 			    maxclsyspri);
1079 		}
1080 		mutex_exit(&vd->vdev_rebuild_lock);
1081 	}
1082 }
1083 
1084 /*
1085  * Conditionally restart all of the vdev_rebuild_thread's for a pool.  The
1086  * feature flag must be active and the rebuild in the active state.   This
1087  * cannot be used to start a new rebuild.
1088  */
1089 void
vdev_rebuild_restart(spa_t * spa)1090 vdev_rebuild_restart(spa_t *spa)
1091 {
1092 	ASSERT(spa_namespace_held() ||
1093 	    spa->spa_load_thread == curthread);
1094 
1095 	vdev_rebuild_restart_impl(spa->spa_root_vdev);
1096 }
1097 
1098 /*
1099  * Stop and wait for all of the vdev_rebuild_thread's associated with the
1100  * vdev tree provide to be terminated (canceled or stopped).
1101  */
1102 void
vdev_rebuild_stop_wait(vdev_t * vd)1103 vdev_rebuild_stop_wait(vdev_t *vd)
1104 {
1105 	spa_t *spa = vd->vdev_spa;
1106 
1107 	ASSERT(spa_namespace_held() ||
1108 	    spa->spa_export_thread == curthread);
1109 
1110 	if (vd == spa->spa_root_vdev) {
1111 		for (uint64_t i = 0; i < vd->vdev_children; i++)
1112 			vdev_rebuild_stop_wait(vd->vdev_child[i]);
1113 
1114 	} else if (vd->vdev_top_zap != 0) {
1115 		ASSERT(vd == vd->vdev_top);
1116 
1117 		mutex_enter(&vd->vdev_rebuild_lock);
1118 		if (vd->vdev_rebuild_thread != NULL) {
1119 			vd->vdev_rebuild_exit_wanted = B_TRUE;
1120 			while (vd->vdev_rebuilding) {
1121 				cv_wait(&vd->vdev_rebuild_cv,
1122 				    &vd->vdev_rebuild_lock);
1123 			}
1124 			vd->vdev_rebuild_exit_wanted = B_FALSE;
1125 		}
1126 		mutex_exit(&vd->vdev_rebuild_lock);
1127 	}
1128 }
1129 
1130 /*
1131  * Stop all rebuild operations but leave them in the active state so they
1132  * will be resumed when importing the pool.
1133  */
1134 void
vdev_rebuild_stop_all(spa_t * spa)1135 vdev_rebuild_stop_all(spa_t *spa)
1136 {
1137 	vdev_rebuild_stop_wait(spa->spa_root_vdev);
1138 }
1139 
1140 /*
1141  * Return rebuild transaction groups range.  It's used to populate DTLs
1142  * of the non-writable devices during the rebuild so that they could be
1143  * healed correctly, in case they are cleared, and not miss the data
1144  * that was written to their spares during the rebuild.
1145  */
1146 void
vdev_rebuild_txgs(vdev_t * vd,uint64_t * min_txg,uint64_t * size)1147 vdev_rebuild_txgs(vdev_t *vd, uint64_t *min_txg, uint64_t *size)
1148 {
1149 	vdev_rebuild_t *vr = &vd->vdev_rebuild_config;
1150 	vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
1151 
1152 	*min_txg = vrp->vrp_min_txg;
1153 	*size = vrp->vrp_max_txg - vrp->vrp_min_txg;
1154 }
1155 
1156 /*
1157  * Rebuild statistics reported per top-level vdev.
1158  */
1159 int
vdev_rebuild_get_stats(vdev_t * tvd,vdev_rebuild_stat_t * vrs)1160 vdev_rebuild_get_stats(vdev_t *tvd, vdev_rebuild_stat_t *vrs)
1161 {
1162 	spa_t *spa = tvd->vdev_spa;
1163 
1164 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_DEVICE_REBUILD))
1165 		return (SET_ERROR(ENOTSUP));
1166 
1167 	if (tvd != tvd->vdev_top || tvd->vdev_top_zap == 0)
1168 		return (SET_ERROR(EINVAL));
1169 
1170 	int error = zap_contains(spa_meta_objset(spa),
1171 	    tvd->vdev_top_zap, VDEV_TOP_ZAP_VDEV_REBUILD_PHYS);
1172 
1173 	if (error == ENOENT) {
1174 		memset(vrs, 0, sizeof (vdev_rebuild_stat_t));
1175 		vrs->vrs_state = VDEV_REBUILD_NONE;
1176 		error = 0;
1177 	} else if (error == 0) {
1178 		vdev_rebuild_t *vr = &tvd->vdev_rebuild_config;
1179 		vdev_rebuild_phys_t *vrp = &vr->vr_rebuild_phys;
1180 
1181 		mutex_enter(&tvd->vdev_rebuild_lock);
1182 		vrs->vrs_state = vrp->vrp_rebuild_state;
1183 		vrs->vrs_start_time = vrp->vrp_start_time;
1184 		vrs->vrs_end_time = vrp->vrp_end_time;
1185 		vrs->vrs_scan_time_ms = vrp->vrp_scan_time_ms;
1186 		vrs->vrs_bytes_scanned = vrp->vrp_bytes_scanned;
1187 		vrs->vrs_bytes_issued = vrp->vrp_bytes_issued;
1188 		vrs->vrs_bytes_rebuilt = vrp->vrp_bytes_rebuilt;
1189 		vrs->vrs_bytes_est = vrp->vrp_bytes_est;
1190 		vrs->vrs_errors = vrp->vrp_errors;
1191 		vrs->vrs_pass_time_ms = NSEC2MSEC(gethrtime() -
1192 		    vr->vr_pass_start_time);
1193 		vrs->vrs_pass_bytes_scanned = vr->vr_pass_bytes_scanned;
1194 		vrs->vrs_pass_bytes_issued = vr->vr_pass_bytes_issued;
1195 		vrs->vrs_pass_bytes_skipped = vr->vr_pass_bytes_skipped;
1196 		mutex_exit(&tvd->vdev_rebuild_lock);
1197 	}
1198 
1199 	return (error);
1200 }
1201 
1202 ZFS_MODULE_PARAM(zfs, zfs_, rebuild_max_segment, U64, ZMOD_RW,
1203 	"Max segment size in bytes of rebuild reads");
1204 
1205 ZFS_MODULE_PARAM(zfs, zfs_, rebuild_vdev_limit, U64, ZMOD_RW,
1206 	"Max bytes in flight per leaf vdev for sequential resilvers");
1207 
1208 ZFS_MODULE_PARAM(zfs, zfs_, rebuild_scrub_enabled, INT, ZMOD_RW,
1209 	"Automatically scrub after sequential resilver completes");
1210