xref: /freebsd/sys/contrib/openzfs/module/zfs/vdev_removal.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 
13 /*
14  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
15  * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
16  * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
17  */
18 
19 #include <sys/zfs_context.h>
20 #include <sys/spa_impl.h>
21 #include <sys/dmu.h>
22 #include <sys/dmu_tx.h>
23 #include <sys/zap.h>
24 #include <sys/vdev_impl.h>
25 #include <sys/metaslab.h>
26 #include <sys/metaslab_impl.h>
27 #include <sys/uberblock_impl.h>
28 #include <sys/txg.h>
29 #include <sys/avl.h>
30 #include <sys/bpobj.h>
31 #include <sys/dsl_pool.h>
32 #include <sys/dsl_synctask.h>
33 #include <sys/dsl_dir.h>
34 #include <sys/arc.h>
35 #include <sys/zfeature.h>
36 #include <sys/vdev_indirect_births.h>
37 #include <sys/vdev_indirect_mapping.h>
38 #include <sys/abd.h>
39 #include <sys/vdev_initialize.h>
40 #include <sys/vdev_trim.h>
41 #include <sys/trace_zfs.h>
42 
43 /*
44  * This file contains the necessary logic to remove vdevs from a storage
45  * pool. Note that members of a mirror can be removed by the detach
46  * operation. Currently, the only devices that can be removed are:
47  *
48  * 1) Traditional hot spare and cache vdevs. Note that draid distributed
49  *    spares are fixed at creation time and cannot be removed.
50  *
51  * 2) Log vdevs are removed by evacuating them and then turning the vdev
52  *    into a hole vdev while holding spa config locks.
53  *
54  * 3) Top-level singleton and mirror vdevs, including dedup and special
55  *    vdevs, are removed and converted into an indirect vdev via a
56  *    multi-step process:
57  *
58  *    - Disable allocations from this device (spa_vdev_remove_top).
59  *
60  *    - From a new thread (spa_vdev_remove_thread), copy data from the
61  *      removing vdev to a different vdev. The copy happens in open context
62  *      (spa_vdev_copy_impl) and issues a sync task (vdev_mapping_sync) so
63  *      the sync thread can update the partial indirect mappings in core
64  *      and on disk.
65  *
66  *    - If a free happens during a removal, it is freed from the removing
67  *      vdev, and if it has already been copied, from the new location as
68  *      well (free_from_removing_vdev).
69  *
70  *    - After the removal is completed, the copy thread converts the vdev
71  *      into an indirect vdev (vdev_remove_complete) before instructing
72  *      the sync thread to destroy the space maps and finish the removal
73  *      (spa_finish_removal).
74  *
75  *   The following constraints currently apply primary device removal:
76  *
77  *     - All vdevs must be online, healthy, and not be missing any data
78  *       according to the DTLs.
79  *
80  *     - When removing a singleton or mirror vdev, regardless of it's a
81  *       special, dedup, or primary device, it must have the same ashift
82  *       as the devices in the normal allocation class. Furthermore, all
83  *       vdevs in the normal allocation class must have the same ashift to
84  *       ensure the new allocations never includes additional padding.
85  *
86  *     - The normal allocation class cannot contain any raidz or draid
87  *       top-level vdevs since segments are copied without regard for block
88  *       boundaries. This makes it impossible to calculate the required
89  *       parity columns when using these vdev types as the destination.
90  *
91  *     - The encryption keys must be loaded so the ZIL logs can be reset
92  *       in order to prevent writing to the device being removed.
93  *
94  * N.B. ashift and raidz/draid constraints for primary top-level device
95  * removal could be slightly relaxed if it were possible to request that
96  * DVAs from a mirror or singleton in the specified allocation class be
97  * used (metaslab_alloc_dva).
98  *
99  * This flexibility would be particularly useful for raidz/draid pools which
100  * often include a mirrored special device. If a mistakenly added top-level
101  * singleton were added it could then still be removed at the cost of some
102  * special device capacity. This may be a worthwhile tradeoff depending on
103  * the pool capacity and expense (cost, complexity, time) of creating a new
104  * pool and copying all of the data to correct the configuration.
105  *
106  * Furthermore, while not currently supported it should be possible to allow
107  * vdevs of any type to be removed as long as they've never been written to.
108  */
109 
110 typedef struct vdev_copy_arg {
111 	metaslab_t	*vca_msp;
112 	uint64_t	vca_outstanding_bytes;
113 	uint64_t	vca_read_error_bytes;
114 	uint64_t	vca_write_error_bytes;
115 	kcondvar_t	vca_cv;
116 	kmutex_t	vca_lock;
117 } vdev_copy_arg_t;
118 
119 /*
120  * The maximum amount of memory we can use for outstanding i/o while
121  * doing a device removal.  This determines how much i/o we can have
122  * in flight concurrently.
123  */
124 static const uint_t zfs_remove_max_copy_bytes = 64 * 1024 * 1024;
125 
126 /*
127  * The largest contiguous segment that we will attempt to allocate when
128  * removing a device.  This can be no larger than SPA_MAXBLOCKSIZE.  If
129  * there is a performance problem with attempting to allocate large blocks,
130  * consider decreasing this.
131  *
132  * See also the accessor function spa_remove_max_segment().
133  */
134 uint_t zfs_remove_max_segment = SPA_MAXBLOCKSIZE;
135 
136 /*
137  * Ignore hard IO errors during device removal.  When set if a device
138  * encounters hard IO error during the removal process the removal will
139  * not be cancelled.  This can result in a normally recoverable block
140  * becoming permanently damaged and is not recommended.
141  */
142 static int zfs_removal_ignore_errors = 0;
143 
144 /*
145  * Allow a remap segment to span free chunks of at most this size. The main
146  * impact of a larger span is that we will read and write larger, more
147  * contiguous chunks, with more "unnecessary" data -- trading off bandwidth
148  * for iops.  The value here was chosen to align with
149  * zfs_vdev_read_gap_limit, which is a similar concept when doing regular
150  * reads (but there's no reason it has to be the same).
151  *
152  * Additionally, a higher span will have the following relatively minor
153  * effects:
154  *  - the mapping will be smaller, since one entry can cover more allocated
155  *    segments
156  *  - more of the fragmentation in the removing device will be preserved
157  *  - we'll do larger allocations, which may fail and fall back on smaller
158  *    allocations
159  */
160 uint_t vdev_removal_max_span = 32 * 1024;
161 
162 /*
163  * This is used by the test suite so that it can ensure that certain
164  * actions happen while in the middle of a removal.
165  */
166 int zfs_removal_suspend_progress = 0;
167 
168 #define	VDEV_REMOVAL_ZAP_OBJS	"lzap"
169 
170 static __attribute__((noreturn)) void spa_vdev_remove_thread(void *arg);
171 static int spa_vdev_remove_cancel_impl(spa_t *spa);
172 
173 static void
spa_sync_removing_state(spa_t * spa,dmu_tx_t * tx)174 spa_sync_removing_state(spa_t *spa, dmu_tx_t *tx)
175 {
176 	VERIFY0(zap_update(spa->spa_dsl_pool->dp_meta_objset,
177 	    DMU_POOL_DIRECTORY_OBJECT,
178 	    DMU_POOL_REMOVING, sizeof (uint64_t),
179 	    sizeof (spa->spa_removing_phys) / sizeof (uint64_t),
180 	    &spa->spa_removing_phys, tx));
181 }
182 
183 static nvlist_t *
spa_nvlist_lookup_by_guid(nvlist_t ** nvpp,int count,uint64_t target_guid)184 spa_nvlist_lookup_by_guid(nvlist_t **nvpp, int count, uint64_t target_guid)
185 {
186 	for (int i = 0; i < count; i++) {
187 		uint64_t guid =
188 		    fnvlist_lookup_uint64(nvpp[i], ZPOOL_CONFIG_GUID);
189 
190 		if (guid == target_guid)
191 			return (nvpp[i]);
192 	}
193 
194 	return (NULL);
195 }
196 
197 static void
vdev_activate(vdev_t * vd)198 vdev_activate(vdev_t *vd)
199 {
200 	metaslab_group_t *mg = vd->vdev_mg;
201 
202 	ASSERT(!vd->vdev_islog);
203 	ASSERT(vd->vdev_noalloc);
204 
205 	metaslab_group_activate(mg);
206 	metaslab_group_activate(vd->vdev_log_mg);
207 
208 	vdev_update_nonallocating_space(vd, B_FALSE);
209 
210 	vd->vdev_noalloc = B_FALSE;
211 }
212 
213 static int
vdev_passivate(vdev_t * vd,uint64_t * txg)214 vdev_passivate(vdev_t *vd, uint64_t *txg)
215 {
216 	spa_t *spa = vd->vdev_spa;
217 	int error;
218 
219 	ASSERT(!vd->vdev_noalloc);
220 
221 	vdev_t *rvd = spa->spa_root_vdev;
222 	metaslab_group_t *mg = vd->vdev_mg;
223 	metaslab_class_t *normal = spa_normal_class(spa);
224 	if (mg->mg_class == normal) {
225 		/*
226 		 * We must check that this is not the only allocating device in
227 		 * the pool before passivating, otherwise we will not be able
228 		 * to make progress because we can't allocate from any vdevs.
229 		 */
230 		boolean_t last = B_TRUE;
231 		for (uint64_t id = 0; id < rvd->vdev_children; id++) {
232 			vdev_t *cvd = rvd->vdev_child[id];
233 
234 			if (cvd == vd || !vdev_is_concrete(cvd) ||
235 			    vdev_is_dead(cvd))
236 				continue;
237 
238 			metaslab_class_t *mc = cvd->vdev_mg->mg_class;
239 			if (mc != normal)
240 				continue;
241 
242 			if (!cvd->vdev_noalloc) {
243 				last = B_FALSE;
244 				break;
245 			}
246 		}
247 		if (last)
248 			return (SET_ERROR(EINVAL));
249 	}
250 
251 	metaslab_group_passivate(mg);
252 	ASSERT(!vd->vdev_islog);
253 	metaslab_group_passivate(vd->vdev_log_mg);
254 
255 	/*
256 	 * Wait for the youngest allocations and frees to sync,
257 	 * and then wait for the deferral of those frees to finish.
258 	 */
259 	spa_vdev_config_exit(spa, NULL,
260 	    *txg + TXG_CONCURRENT_STATES + TXG_DEFER_SIZE, 0, FTAG);
261 
262 	/*
263 	 * We must ensure that no "stubby" log blocks are allocated
264 	 * on the device to be removed.  These blocks could be
265 	 * written at any time, including while we are in the middle
266 	 * of copying them.
267 	 */
268 	error = spa_reset_logs(spa);
269 
270 	*txg = spa_vdev_config_enter(spa);
271 
272 	if (error != 0) {
273 		metaslab_group_activate(mg);
274 		ASSERT(!vd->vdev_islog);
275 		if (vd->vdev_log_mg != NULL)
276 			metaslab_group_activate(vd->vdev_log_mg);
277 		return (error);
278 	}
279 
280 	vdev_update_nonallocating_space(vd, B_TRUE);
281 	vd->vdev_noalloc = B_TRUE;
282 
283 	return (0);
284 }
285 
286 /*
287  * Turn off allocations for a top-level device from the pool.
288  *
289  * Turning off allocations for a top-level device can take a significant
290  * amount of time. As a result we use the spa_vdev_config_[enter/exit]
291  * functions which allow us to grab and release the spa_config_lock while
292  * still holding the namespace lock. During each step the configuration
293  * is synced out.
294  */
295 int
spa_vdev_noalloc(spa_t * spa,uint64_t guid)296 spa_vdev_noalloc(spa_t *spa, uint64_t guid)
297 {
298 	vdev_t *vd;
299 	uint64_t txg;
300 	int error = 0;
301 
302 	ASSERT(!spa_namespace_held());
303 	ASSERT(spa_writeable(spa));
304 
305 	txg = spa_vdev_enter(spa);
306 
307 	ASSERT(spa_namespace_held());
308 
309 	vd = spa_lookup_by_guid(spa, guid, B_FALSE);
310 
311 	if (vd == NULL)
312 		error = SET_ERROR(ENOENT);
313 	else if (vd->vdev_mg == NULL)
314 		error = SET_ERROR(ZFS_ERR_VDEV_NOTSUP);
315 	else if (!vd->vdev_noalloc)
316 		error = vdev_passivate(vd, &txg);
317 
318 	if (error == 0) {
319 		vdev_dirty_leaves(vd, VDD_DTL, txg);
320 		vdev_config_dirty(vd);
321 	}
322 
323 	error = spa_vdev_exit(spa, NULL, txg, error);
324 
325 	return (error);
326 }
327 
328 int
spa_vdev_alloc(spa_t * spa,uint64_t guid)329 spa_vdev_alloc(spa_t *spa, uint64_t guid)
330 {
331 	vdev_t *vd;
332 	uint64_t txg;
333 	int error = 0;
334 
335 	ASSERT(!spa_namespace_held());
336 	ASSERT(spa_writeable(spa));
337 
338 	txg = spa_vdev_enter(spa);
339 
340 	ASSERT(spa_namespace_held());
341 
342 	vd = spa_lookup_by_guid(spa, guid, B_FALSE);
343 
344 	if (vd == NULL)
345 		error = SET_ERROR(ENOENT);
346 	else if (vd->vdev_mg == NULL)
347 		error = SET_ERROR(ZFS_ERR_VDEV_NOTSUP);
348 	else if (!vd->vdev_removing)
349 		vdev_activate(vd);
350 
351 	if (error == 0) {
352 		vdev_dirty_leaves(vd, VDD_DTL, txg);
353 		vdev_config_dirty(vd);
354 	}
355 
356 	(void) spa_vdev_exit(spa, NULL, txg, error);
357 
358 	return (error);
359 }
360 
361 static void
spa_vdev_remove_aux(nvlist_t * config,const char * name,nvlist_t ** dev,int count,nvlist_t * dev_to_remove)362 spa_vdev_remove_aux(nvlist_t *config, const char *name, nvlist_t **dev,
363     int count, nvlist_t *dev_to_remove)
364 {
365 	nvlist_t **newdev = NULL;
366 
367 	if (count > 1)
368 		newdev = kmem_alloc((count - 1) * sizeof (void *), KM_SLEEP);
369 
370 	for (int i = 0, j = 0; i < count; i++) {
371 		if (dev[i] == dev_to_remove)
372 			continue;
373 		VERIFY0(nvlist_dup(dev[i], &newdev[j++], KM_SLEEP));
374 	}
375 
376 	VERIFY0(nvlist_remove(config, name, DATA_TYPE_NVLIST_ARRAY));
377 	fnvlist_add_nvlist_array(config, name, (const nvlist_t * const *)newdev,
378 	    count - 1);
379 
380 	for (int i = 0; i < count - 1; i++)
381 		nvlist_free(newdev[i]);
382 
383 	if (count > 1)
384 		kmem_free(newdev, (count - 1) * sizeof (void *));
385 }
386 
387 static spa_vdev_removal_t *
spa_vdev_removal_create(vdev_t * vd)388 spa_vdev_removal_create(vdev_t *vd)
389 {
390 	spa_vdev_removal_t *svr = kmem_zalloc(sizeof (*svr), KM_SLEEP);
391 	mutex_init(&svr->svr_lock, NULL, MUTEX_DEFAULT, NULL);
392 	cv_init(&svr->svr_cv, NULL, CV_DEFAULT, NULL);
393 	svr->svr_allocd_segs = zfs_range_tree_create_flags(
394 	    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
395 	    ZFS_RT_F_DYN_NAME, vdev_rt_name(vd, "svr_allocd_segs"));
396 	svr->svr_vdev_id = vd->vdev_id;
397 
398 	for (int i = 0; i < TXG_SIZE; i++) {
399 		svr->svr_frees[i] = zfs_range_tree_create_flags(
400 		    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
401 		    ZFS_RT_F_DYN_NAME, vdev_rt_name(vd, "svr_frees"));
402 		list_create(&svr->svr_new_segments[i],
403 		    sizeof (vdev_indirect_mapping_entry_t),
404 		    offsetof(vdev_indirect_mapping_entry_t, vime_node));
405 	}
406 
407 	return (svr);
408 }
409 
410 void
spa_vdev_removal_destroy(spa_vdev_removal_t * svr)411 spa_vdev_removal_destroy(spa_vdev_removal_t *svr)
412 {
413 	for (int i = 0; i < TXG_SIZE; i++) {
414 		ASSERT0(svr->svr_bytes_done[i]);
415 		ASSERT0(svr->svr_max_offset_to_sync[i]);
416 		zfs_range_tree_destroy(svr->svr_frees[i]);
417 		list_destroy(&svr->svr_new_segments[i]);
418 	}
419 
420 	zfs_range_tree_destroy(svr->svr_allocd_segs);
421 	mutex_destroy(&svr->svr_lock);
422 	cv_destroy(&svr->svr_cv);
423 	kmem_free(svr, sizeof (*svr));
424 }
425 
426 /*
427  * This is called as a synctask in the txg in which we will mark this vdev
428  * as removing (in the config stored in the MOS).
429  *
430  * It begins the evacuation of a toplevel vdev by:
431  * - initializing the spa_removing_phys which tracks this removal
432  * - computing the amount of space to remove for accounting purposes
433  * - dirtying all dbufs in the spa_config_object
434  * - creating the spa_vdev_removal
435  * - starting the spa_vdev_remove_thread
436  */
437 static void
vdev_remove_initiate_sync(void * arg,dmu_tx_t * tx)438 vdev_remove_initiate_sync(void *arg, dmu_tx_t *tx)
439 {
440 	int vdev_id = (uintptr_t)arg;
441 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
442 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
443 	vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
444 	objset_t *mos = spa->spa_dsl_pool->dp_meta_objset;
445 	spa_vdev_removal_t *svr = NULL;
446 	uint64_t txg __maybe_unused = dmu_tx_get_txg(tx);
447 
448 	ASSERT0(vdev_get_nparity(vd));
449 	svr = spa_vdev_removal_create(vd);
450 
451 	ASSERT(vd->vdev_removing);
452 	ASSERT0P(vd->vdev_indirect_mapping);
453 
454 	spa_feature_incr(spa, SPA_FEATURE_DEVICE_REMOVAL, tx);
455 	if (spa_feature_is_enabled(spa, SPA_FEATURE_OBSOLETE_COUNTS)) {
456 		/*
457 		 * By activating the OBSOLETE_COUNTS feature, we prevent
458 		 * the pool from being downgraded and ensure that the
459 		 * refcounts are precise.
460 		 */
461 		spa_feature_incr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
462 		uint64_t one = 1;
463 		VERIFY0(zap_add(spa->spa_meta_objset, vd->vdev_top_zap,
464 		    VDEV_TOP_ZAP_OBSOLETE_COUNTS_ARE_PRECISE, sizeof (one), 1,
465 		    &one, tx));
466 		boolean_t are_precise __maybe_unused;
467 		ASSERT0(vdev_obsolete_counts_are_precise(vd, &are_precise));
468 		ASSERT3B(are_precise, ==, B_TRUE);
469 	}
470 
471 	vic->vic_mapping_object = vdev_indirect_mapping_alloc(mos, tx);
472 	vd->vdev_indirect_mapping =
473 	    vdev_indirect_mapping_open(mos, vic->vic_mapping_object);
474 	vic->vic_births_object = vdev_indirect_births_alloc(mos, tx);
475 	vd->vdev_indirect_births =
476 	    vdev_indirect_births_open(mos, vic->vic_births_object);
477 	spa->spa_removing_phys.sr_removing_vdev = vd->vdev_id;
478 	spa->spa_removing_phys.sr_start_time = gethrestime_sec();
479 	spa->spa_removing_phys.sr_end_time = 0;
480 	spa->spa_removing_phys.sr_state = DSS_SCANNING;
481 	spa->spa_removing_phys.sr_to_copy = 0;
482 	spa->spa_removing_phys.sr_copied = 0;
483 
484 	/*
485 	 * Note: We can't use vdev_stat's vs_alloc for sr_to_copy, because
486 	 * there may be space in the defer tree, which is free, but still
487 	 * counted in vs_alloc.
488 	 */
489 	for (uint64_t i = 0; i < vd->vdev_ms_count; i++) {
490 		metaslab_t *ms = vd->vdev_ms[i];
491 		if (ms->ms_sm == NULL)
492 			continue;
493 
494 		spa->spa_removing_phys.sr_to_copy +=
495 		    metaslab_allocated_space(ms);
496 
497 		/*
498 		 * Space which we are freeing this txg does not need to
499 		 * be copied.
500 		 */
501 		spa->spa_removing_phys.sr_to_copy -=
502 		    zfs_range_tree_space(ms->ms_freeing);
503 
504 		ASSERT0(zfs_range_tree_space(ms->ms_freed));
505 		for (int t = 0; t < TXG_SIZE; t++)
506 			ASSERT0(zfs_range_tree_space(ms->ms_allocating[t]));
507 	}
508 
509 	/*
510 	 * Sync tasks are called before metaslab_sync(), so there should
511 	 * be no already-synced metaslabs in the TXG_CLEAN list.
512 	 */
513 	ASSERT3P(txg_list_head(&vd->vdev_ms_list, TXG_CLEAN(txg)), ==, NULL);
514 
515 	spa_sync_removing_state(spa, tx);
516 
517 	/*
518 	 * All blocks that we need to read the most recent mapping must be
519 	 * stored on concrete vdevs.  Therefore, we must dirty anything that
520 	 * is read before spa_remove_init().  Specifically, the
521 	 * spa_config_object.  (Note that although we already modified the
522 	 * spa_config_object in spa_sync_removing_state, that may not have
523 	 * modified all blocks of the object.)
524 	 */
525 	dmu_object_info_t doi;
526 	VERIFY0(dmu_object_info(mos, DMU_POOL_DIRECTORY_OBJECT, &doi));
527 	for (uint64_t offset = 0; offset < doi.doi_max_offset; ) {
528 		dmu_buf_t *dbuf;
529 		VERIFY0(dmu_buf_hold(mos, DMU_POOL_DIRECTORY_OBJECT,
530 		    offset, FTAG, &dbuf, 0));
531 		dmu_buf_will_dirty(dbuf, tx);
532 		offset += dbuf->db_size;
533 		dmu_buf_rele(dbuf, FTAG);
534 	}
535 
536 	/*
537 	 * Now that we've allocated the im_object, dirty the vdev to ensure
538 	 * that the object gets written to the config on disk.
539 	 */
540 	vdev_config_dirty(vd);
541 
542 	zfs_dbgmsg("starting removal thread for vdev %llu (%px) in txg %llu "
543 	    "im_obj=%llu", (u_longlong_t)vd->vdev_id, vd,
544 	    (u_longlong_t)dmu_tx_get_txg(tx),
545 	    (u_longlong_t)vic->vic_mapping_object);
546 
547 	spa_history_log_internal(spa, "vdev remove started", tx,
548 	    "%s vdev %llu %s", spa_name(spa), (u_longlong_t)vd->vdev_id,
549 	    (vd->vdev_path != NULL) ? vd->vdev_path : "-");
550 	/*
551 	 * Setting spa_vdev_removal causes subsequent frees to call
552 	 * free_from_removing_vdev().  Note that we don't need any locking
553 	 * because we are the sync thread, and metaslab_free_impl() is only
554 	 * called from syncing context (potentially from a zio taskq thread,
555 	 * but in any case only when there are outstanding free i/os, which
556 	 * there are not).
557 	 */
558 	ASSERT0P(spa->spa_vdev_removal);
559 	spa->spa_vdev_removal = svr;
560 	svr->svr_thread = thread_create(NULL, 0,
561 	    spa_vdev_remove_thread, spa, 0, &p0, TS_RUN, minclsyspri);
562 }
563 
564 /*
565  * When we are opening a pool, we must read the mapping for each
566  * indirect vdev in order from most recently removed to least
567  * recently removed.  We do this because the blocks for the mapping
568  * of older indirect vdevs may be stored on more recently removed vdevs.
569  * In order to read each indirect mapping object, we must have
570  * initialized all more recently removed vdevs.
571  */
572 int
spa_remove_init(spa_t * spa)573 spa_remove_init(spa_t *spa)
574 {
575 	int error;
576 
577 	error = zap_lookup(spa->spa_dsl_pool->dp_meta_objset,
578 	    DMU_POOL_DIRECTORY_OBJECT,
579 	    DMU_POOL_REMOVING, sizeof (uint64_t),
580 	    sizeof (spa->spa_removing_phys) / sizeof (uint64_t),
581 	    &spa->spa_removing_phys);
582 
583 	if (error == ENOENT) {
584 		spa->spa_removing_phys.sr_state = DSS_NONE;
585 		spa->spa_removing_phys.sr_removing_vdev = -1;
586 		spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
587 		spa->spa_indirect_vdevs_loaded = B_TRUE;
588 		return (0);
589 	} else if (error != 0) {
590 		return (error);
591 	}
592 
593 	if (spa->spa_removing_phys.sr_state == DSS_SCANNING) {
594 		/*
595 		 * We are currently removing a vdev.  Create and
596 		 * initialize a spa_vdev_removal_t from the bonus
597 		 * buffer of the removing vdevs vdev_im_object, and
598 		 * initialize its partial mapping.
599 		 */
600 		spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
601 		vdev_t *vd = vdev_lookup_top(spa,
602 		    spa->spa_removing_phys.sr_removing_vdev);
603 
604 		if (vd == NULL) {
605 			spa_config_exit(spa, SCL_STATE, FTAG);
606 			return (EINVAL);
607 		}
608 
609 		vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
610 
611 		ASSERT(vdev_is_concrete(vd));
612 		spa_vdev_removal_t *svr = spa_vdev_removal_create(vd);
613 		ASSERT3U(svr->svr_vdev_id, ==, vd->vdev_id);
614 		ASSERT(vd->vdev_removing);
615 
616 		vd->vdev_indirect_mapping = vdev_indirect_mapping_open(
617 		    spa->spa_meta_objset, vic->vic_mapping_object);
618 		vd->vdev_indirect_births = vdev_indirect_births_open(
619 		    spa->spa_meta_objset, vic->vic_births_object);
620 		spa_config_exit(spa, SCL_STATE, FTAG);
621 
622 		spa->spa_vdev_removal = svr;
623 	}
624 
625 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
626 	uint64_t indirect_vdev_id =
627 	    spa->spa_removing_phys.sr_prev_indirect_vdev;
628 	while (indirect_vdev_id != UINT64_MAX) {
629 		vdev_t *vd = vdev_lookup_top(spa, indirect_vdev_id);
630 		vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
631 
632 		ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
633 		vd->vdev_indirect_mapping = vdev_indirect_mapping_open(
634 		    spa->spa_meta_objset, vic->vic_mapping_object);
635 		vd->vdev_indirect_births = vdev_indirect_births_open(
636 		    spa->spa_meta_objset, vic->vic_births_object);
637 
638 		indirect_vdev_id = vic->vic_prev_indirect_vdev;
639 	}
640 	spa_config_exit(spa, SCL_STATE, FTAG);
641 
642 	/*
643 	 * Now that we've loaded all the indirect mappings, we can allow
644 	 * reads from other blocks (e.g. via predictive prefetch).
645 	 */
646 	spa->spa_indirect_vdevs_loaded = B_TRUE;
647 	return (0);
648 }
649 
650 void
spa_restart_removal(spa_t * spa)651 spa_restart_removal(spa_t *spa)
652 {
653 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
654 
655 	if (svr == NULL)
656 		return;
657 
658 	/*
659 	 * In general when this function is called there is no
660 	 * removal thread running. The only scenario where this
661 	 * is not true is during spa_import() where this function
662 	 * is called twice [once from spa_import_impl() and
663 	 * spa_async_resume()]. Thus, in the scenario where we
664 	 * import a pool that has an ongoing removal we don't
665 	 * want to spawn a second thread.
666 	 */
667 	if (svr->svr_thread != NULL)
668 		return;
669 
670 	if (!spa_writeable(spa))
671 		return;
672 
673 	zfs_dbgmsg("restarting removal of %llu",
674 	    (u_longlong_t)svr->svr_vdev_id);
675 	svr->svr_thread = thread_create(NULL, 0, spa_vdev_remove_thread, spa,
676 	    0, &p0, TS_RUN, minclsyspri);
677 }
678 
679 /*
680  * Process freeing from a device which is in the middle of being removed.
681  * We must handle this carefully so that we attempt to copy freed data,
682  * and we correctly free already-copied data.
683  */
684 void
free_from_removing_vdev(vdev_t * vd,uint64_t offset,uint64_t size)685 free_from_removing_vdev(vdev_t *vd, uint64_t offset, uint64_t size)
686 {
687 	spa_t *spa = vd->vdev_spa;
688 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
689 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
690 	uint64_t txg = spa_syncing_txg(spa);
691 	uint64_t max_offset_yet = 0;
692 
693 	ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
694 	ASSERT3U(vd->vdev_indirect_config.vic_mapping_object, ==,
695 	    vdev_indirect_mapping_object(vim));
696 	ASSERT3U(vd->vdev_id, ==, svr->svr_vdev_id);
697 
698 	mutex_enter(&svr->svr_lock);
699 
700 	/*
701 	 * Remove the segment from the removing vdev's spacemap.  This
702 	 * ensures that we will not attempt to copy this space (if the
703 	 * removal thread has not yet visited it), and also ensures
704 	 * that we know what is actually allocated on the new vdevs
705 	 * (needed if we cancel the removal).
706 	 *
707 	 * Note: we must do the metaslab_free_concrete() with the svr_lock
708 	 * held, so that the remove_thread can not load this metaslab and then
709 	 * visit this offset between the time that we metaslab_free_concrete()
710 	 * and when we check to see if it has been visited.
711 	 *
712 	 * Note: The checkpoint flag is set to false as having/taking
713 	 * a checkpoint and removing a device can't happen at the same
714 	 * time.
715 	 */
716 	ASSERT(!spa_has_checkpoint(spa));
717 	metaslab_free_concrete(vd, offset, size, B_FALSE);
718 
719 	uint64_t synced_size = 0;
720 	uint64_t synced_offset = 0;
721 	uint64_t max_offset_synced = vdev_indirect_mapping_max_offset(vim);
722 	if (offset < max_offset_synced) {
723 		/*
724 		 * The mapping for this offset is already on disk.
725 		 * Free from the new location.
726 		 *
727 		 * Note that we use svr_max_synced_offset because it is
728 		 * updated atomically with respect to the in-core mapping.
729 		 * By contrast, vim_max_offset is not.
730 		 *
731 		 * This block may be split between a synced entry and an
732 		 * in-flight or unvisited entry.  Only process the synced
733 		 * portion of it here.
734 		 */
735 		synced_size = MIN(size, max_offset_synced - offset);
736 		synced_offset = offset;
737 
738 		ASSERT3U(max_offset_yet, <=, max_offset_synced);
739 		max_offset_yet = max_offset_synced;
740 
741 		DTRACE_PROBE3(remove__free__synced,
742 		    spa_t *, spa,
743 		    uint64_t, offset,
744 		    uint64_t, synced_size);
745 
746 		size -= synced_size;
747 		offset += synced_size;
748 	}
749 
750 	/*
751 	 * Look at all in-flight txgs starting from the currently syncing one
752 	 * and see if a section of this free is being copied. By starting from
753 	 * this txg and iterating forward, we might find that this region
754 	 * was copied in two different txgs and handle it appropriately.
755 	 */
756 	for (int i = 0; i < TXG_CONCURRENT_STATES; i++) {
757 		int txgoff = (txg + i) & TXG_MASK;
758 		if (size > 0 && offset < svr->svr_max_offset_to_sync[txgoff]) {
759 			/*
760 			 * The mapping for this offset is in flight, and
761 			 * will be synced in txg+i.
762 			 */
763 			uint64_t inflight_size = MIN(size,
764 			    svr->svr_max_offset_to_sync[txgoff] - offset);
765 
766 			DTRACE_PROBE4(remove__free__inflight,
767 			    spa_t *, spa,
768 			    uint64_t, offset,
769 			    uint64_t, inflight_size,
770 			    uint64_t, txg + i);
771 
772 			/*
773 			 * We copy data in order of increasing offset.
774 			 * Therefore the max_offset_to_sync[] must increase
775 			 * (or be zero, indicating that nothing is being
776 			 * copied in that txg).
777 			 */
778 			if (svr->svr_max_offset_to_sync[txgoff] != 0) {
779 				ASSERT3U(svr->svr_max_offset_to_sync[txgoff],
780 				    >=, max_offset_yet);
781 				max_offset_yet =
782 				    svr->svr_max_offset_to_sync[txgoff];
783 			}
784 
785 			/*
786 			 * We've already committed to copying this segment:
787 			 * we have allocated space elsewhere in the pool for
788 			 * it and have an IO outstanding to copy the data. We
789 			 * cannot free the space before the copy has
790 			 * completed, or else the copy IO might overwrite any
791 			 * new data. To free that space, we record the
792 			 * segment in the appropriate svr_frees tree and free
793 			 * the mapped space later, in the txg where we have
794 			 * completed the copy and synced the mapping (see
795 			 * vdev_mapping_sync).
796 			 */
797 			zfs_range_tree_add(svr->svr_frees[txgoff],
798 			    offset, inflight_size);
799 			size -= inflight_size;
800 			offset += inflight_size;
801 
802 			/*
803 			 * This space is already accounted for as being
804 			 * done, because it is being copied in txg+i.
805 			 * However, if i!=0, then it is being copied in
806 			 * a future txg.  If we crash after this txg
807 			 * syncs but before txg+i syncs, then the space
808 			 * will be free.  Therefore we must account
809 			 * for the space being done in *this* txg
810 			 * (when it is freed) rather than the future txg
811 			 * (when it will be copied).
812 			 */
813 			ASSERT3U(svr->svr_bytes_done[txgoff], >=,
814 			    inflight_size);
815 			svr->svr_bytes_done[txgoff] -= inflight_size;
816 			svr->svr_bytes_done[txg & TXG_MASK] += inflight_size;
817 		}
818 	}
819 	ASSERT0(svr->svr_max_offset_to_sync[TXG_CLEAN(txg) & TXG_MASK]);
820 
821 	if (size > 0) {
822 		/*
823 		 * The copy thread has not yet visited this offset.  Ensure
824 		 * that it doesn't.
825 		 */
826 
827 		DTRACE_PROBE3(remove__free__unvisited,
828 		    spa_t *, spa,
829 		    uint64_t, offset,
830 		    uint64_t, size);
831 
832 		if (svr->svr_allocd_segs != NULL)
833 			zfs_range_tree_clear(svr->svr_allocd_segs, offset,
834 			    size);
835 
836 		/*
837 		 * Since we now do not need to copy this data, for
838 		 * accounting purposes we have done our job and can count
839 		 * it as completed.
840 		 */
841 		svr->svr_bytes_done[txg & TXG_MASK] += size;
842 	}
843 	mutex_exit(&svr->svr_lock);
844 
845 	/*
846 	 * Now that we have dropped svr_lock, process the synced portion
847 	 * of this free.
848 	 */
849 	if (synced_size > 0) {
850 		vdev_indirect_mark_obsolete(vd, synced_offset, synced_size);
851 
852 		/*
853 		 * Note: this can only be called from syncing context,
854 		 * and the vdev_indirect_mapping is only changed from the
855 		 * sync thread, so we don't need svr_lock while doing
856 		 * metaslab_free_impl_cb.
857 		 */
858 		boolean_t checkpoint = B_FALSE;
859 		vdev_indirect_ops.vdev_op_remap(vd, synced_offset, synced_size,
860 		    metaslab_free_impl_cb, &checkpoint);
861 	}
862 }
863 
864 /*
865  * Stop an active removal and update the spa_removing phys.
866  */
867 static void
spa_finish_removal(spa_t * spa,dsl_scan_state_t state,dmu_tx_t * tx)868 spa_finish_removal(spa_t *spa, dsl_scan_state_t state, dmu_tx_t *tx)
869 {
870 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
871 	ASSERT3U(dmu_tx_get_txg(tx), ==, spa_syncing_txg(spa));
872 
873 	/* Ensure the removal thread has completed before we free the svr. */
874 	spa_vdev_remove_suspend(spa);
875 
876 	ASSERT(state == DSS_FINISHED || state == DSS_CANCELED);
877 
878 	if (state == DSS_FINISHED) {
879 		spa_removing_phys_t *srp = &spa->spa_removing_phys;
880 		vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
881 		vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
882 
883 		if (srp->sr_prev_indirect_vdev != -1) {
884 			vdev_t *pvd;
885 			pvd = vdev_lookup_top(spa,
886 			    srp->sr_prev_indirect_vdev);
887 			ASSERT3P(pvd->vdev_ops, ==, &vdev_indirect_ops);
888 		}
889 
890 		vic->vic_prev_indirect_vdev = srp->sr_prev_indirect_vdev;
891 		srp->sr_prev_indirect_vdev = vd->vdev_id;
892 	}
893 	spa->spa_removing_phys.sr_state = state;
894 	spa->spa_removing_phys.sr_end_time = gethrestime_sec();
895 
896 	spa->spa_vdev_removal = NULL;
897 	spa_vdev_removal_destroy(svr);
898 
899 	spa_sync_removing_state(spa, tx);
900 	spa_notify_waiters(spa);
901 
902 	vdev_config_dirty(spa->spa_root_vdev);
903 }
904 
905 static void
free_mapped_segment_cb(void * arg,uint64_t offset,uint64_t size)906 free_mapped_segment_cb(void *arg, uint64_t offset, uint64_t size)
907 {
908 	vdev_t *vd = arg;
909 	vdev_indirect_mark_obsolete(vd, offset, size);
910 	boolean_t checkpoint = B_FALSE;
911 	vdev_indirect_ops.vdev_op_remap(vd, offset, size,
912 	    metaslab_free_impl_cb, &checkpoint);
913 }
914 
915 /*
916  * On behalf of the removal thread, syncs an incremental bit more of
917  * the indirect mapping to disk and updates the in-memory mapping.
918  * Called as a sync task in every txg that the removal thread makes progress.
919  */
920 static void
vdev_mapping_sync(void * arg,dmu_tx_t * tx)921 vdev_mapping_sync(void *arg, dmu_tx_t *tx)
922 {
923 	spa_vdev_removal_t *svr = arg;
924 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
925 	vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
926 	vdev_indirect_config_t *vic __maybe_unused = &vd->vdev_indirect_config;
927 	uint64_t txg = dmu_tx_get_txg(tx);
928 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
929 
930 	ASSERT(vic->vic_mapping_object != 0);
931 	ASSERT3U(txg, ==, spa_syncing_txg(spa));
932 
933 	vdev_indirect_mapping_add_entries(vim,
934 	    &svr->svr_new_segments[txg & TXG_MASK], tx);
935 	vdev_indirect_births_add_entry(vd->vdev_indirect_births,
936 	    vdev_indirect_mapping_max_offset(vim), dmu_tx_get_txg(tx), tx);
937 
938 	/*
939 	 * Free the copied data for anything that was freed while the
940 	 * mapping entries were in flight.
941 	 */
942 	mutex_enter(&svr->svr_lock);
943 	zfs_range_tree_vacate(svr->svr_frees[txg & TXG_MASK],
944 	    free_mapped_segment_cb, vd);
945 	ASSERT3U(svr->svr_max_offset_to_sync[txg & TXG_MASK], >=,
946 	    vdev_indirect_mapping_max_offset(vim));
947 	svr->svr_max_offset_to_sync[txg & TXG_MASK] = 0;
948 	mutex_exit(&svr->svr_lock);
949 
950 	spa_sync_removing_state(spa, tx);
951 }
952 
953 typedef struct vdev_copy_segment_arg {
954 	spa_t *vcsa_spa;
955 	dva_t *vcsa_dest_dva;
956 	uint64_t vcsa_txg;
957 	zfs_range_tree_t *vcsa_obsolete_segs;
958 } vdev_copy_segment_arg_t;
959 
960 static void
unalloc_seg(void * arg,uint64_t start,uint64_t size)961 unalloc_seg(void *arg, uint64_t start, uint64_t size)
962 {
963 	vdev_copy_segment_arg_t *vcsa = arg;
964 	spa_t *spa = vcsa->vcsa_spa;
965 	blkptr_t bp = { { { {0} } } };
966 
967 	BP_SET_BIRTH(&bp, TXG_INITIAL, TXG_INITIAL);
968 	BP_SET_LSIZE(&bp, size);
969 	BP_SET_PSIZE(&bp, size);
970 	BP_SET_COMPRESS(&bp, ZIO_COMPRESS_OFF);
971 	BP_SET_CHECKSUM(&bp, ZIO_CHECKSUM_OFF);
972 	BP_SET_TYPE(&bp, DMU_OT_NONE);
973 	BP_SET_LEVEL(&bp, 0);
974 	BP_SET_DEDUP(&bp, 0);
975 	BP_SET_BYTEORDER(&bp, ZFS_HOST_BYTEORDER);
976 
977 	DVA_SET_VDEV(&bp.blk_dva[0], DVA_GET_VDEV(vcsa->vcsa_dest_dva));
978 	DVA_SET_OFFSET(&bp.blk_dva[0],
979 	    DVA_GET_OFFSET(vcsa->vcsa_dest_dva) + start);
980 	DVA_SET_ASIZE(&bp.blk_dva[0], size);
981 
982 	zio_free(spa, vcsa->vcsa_txg, &bp);
983 }
984 
985 /*
986  * All reads and writes associated with a call to spa_vdev_copy_segment()
987  * are done.
988  */
989 static void
spa_vdev_copy_segment_done(zio_t * zio)990 spa_vdev_copy_segment_done(zio_t *zio)
991 {
992 	vdev_copy_segment_arg_t *vcsa = zio->io_private;
993 
994 	zfs_range_tree_vacate(vcsa->vcsa_obsolete_segs,
995 	    unalloc_seg, vcsa);
996 	zfs_range_tree_destroy(vcsa->vcsa_obsolete_segs);
997 	kmem_free(vcsa, sizeof (*vcsa));
998 
999 	spa_config_exit(zio->io_spa, SCL_STATE, zio->io_spa);
1000 }
1001 
1002 /*
1003  * The write of the new location is done.
1004  */
1005 static void
spa_vdev_copy_segment_write_done(zio_t * zio)1006 spa_vdev_copy_segment_write_done(zio_t *zio)
1007 {
1008 	vdev_copy_arg_t *vca = zio->io_private;
1009 
1010 	abd_free(zio->io_abd);
1011 
1012 	mutex_enter(&vca->vca_lock);
1013 	vca->vca_outstanding_bytes -= zio->io_size;
1014 
1015 	if (zio->io_error != 0)
1016 		vca->vca_write_error_bytes += zio->io_size;
1017 
1018 	cv_signal(&vca->vca_cv);
1019 	mutex_exit(&vca->vca_lock);
1020 }
1021 
1022 /*
1023  * The read of the old location is done.  The parent zio is the write to
1024  * the new location.  Allow it to start.
1025  */
1026 static void
spa_vdev_copy_segment_read_done(zio_t * zio)1027 spa_vdev_copy_segment_read_done(zio_t *zio)
1028 {
1029 	vdev_copy_arg_t *vca = zio->io_private;
1030 
1031 	if (zio->io_error != 0) {
1032 		mutex_enter(&vca->vca_lock);
1033 		vca->vca_read_error_bytes += zio->io_size;
1034 		mutex_exit(&vca->vca_lock);
1035 	}
1036 
1037 	zio_nowait(zio_unique_parent(zio));
1038 }
1039 
1040 /*
1041  * If the old and new vdevs are mirrors, we will read both sides of the old
1042  * mirror, and write each copy to the corresponding side of the new mirror.
1043  * If the old and new vdevs have a different number of children, we will do
1044  * this as best as possible.  Since we aren't verifying checksums, this
1045  * ensures that as long as there's a good copy of the data, we'll have a
1046  * good copy after the removal, even if there's silent damage to one side
1047  * of the mirror. If we're removing a mirror that has some silent damage,
1048  * we'll have exactly the same damage in the new location (assuming that
1049  * the new location is also a mirror).
1050  *
1051  * We accomplish this by creating a tree of zio_t's, with as many writes as
1052  * there are "children" of the new vdev (a non-redundant vdev counts as one
1053  * child, a 2-way mirror has 2 children, etc). Each write has an associated
1054  * read from a child of the old vdev. Typically there will be the same
1055  * number of children of the old and new vdevs.  However, if there are more
1056  * children of the new vdev, some child(ren) of the old vdev will be issued
1057  * multiple reads.  If there are more children of the old vdev, some copies
1058  * will be dropped.
1059  *
1060  * For example, the tree of zio_t's for a 2-way mirror is:
1061  *
1062  *                            null
1063  *                           /    \
1064  *    write(new vdev, child 0)      write(new vdev, child 1)
1065  *      |                             |
1066  *    read(old vdev, child 0)       read(old vdev, child 1)
1067  *
1068  * Child zio's complete before their parents complete.  However, zio's
1069  * created with zio_vdev_child_io() may be issued before their children
1070  * complete.  In this case we need to make sure that the children (reads)
1071  * complete before the parents (writes) are *issued*.  We do this by not
1072  * calling zio_nowait() on each write until its corresponding read has
1073  * completed.
1074  *
1075  * The spa_config_lock must be held while zio's created by
1076  * zio_vdev_child_io() are in progress, to ensure that the vdev tree does
1077  * not change (e.g. due to a concurrent "zpool attach/detach"). The "null"
1078  * zio is needed to release the spa_config_lock after all the reads and
1079  * writes complete. (Note that we can't grab the config lock for each read,
1080  * because it is not reentrant - we could deadlock with a thread waiting
1081  * for a write lock.)
1082  */
1083 static void
spa_vdev_copy_one_child(vdev_copy_arg_t * vca,zio_t * nzio,vdev_t * source_vd,uint64_t source_offset,vdev_t * dest_child_vd,uint64_t dest_offset,int dest_id,uint64_t size)1084 spa_vdev_copy_one_child(vdev_copy_arg_t *vca, zio_t *nzio,
1085     vdev_t *source_vd, uint64_t source_offset,
1086     vdev_t *dest_child_vd, uint64_t dest_offset, int dest_id, uint64_t size)
1087 {
1088 	ASSERT3U(spa_config_held(nzio->io_spa, SCL_ALL, RW_READER), !=, 0);
1089 
1090 	/*
1091 	 * If the destination child in unwritable then there is no point
1092 	 * in issuing the source reads which cannot be written.
1093 	 */
1094 	if (!vdev_writeable(dest_child_vd))
1095 		return;
1096 
1097 	mutex_enter(&vca->vca_lock);
1098 	vca->vca_outstanding_bytes += size;
1099 	mutex_exit(&vca->vca_lock);
1100 
1101 	abd_t *abd = abd_alloc_for_io(size, B_FALSE);
1102 
1103 	vdev_t *source_child_vd = NULL;
1104 	if (source_vd->vdev_ops == &vdev_mirror_ops && dest_id != -1) {
1105 		/*
1106 		 * Source and dest are both mirrors.  Copy from the same
1107 		 * child id as we are copying to (wrapping around if there
1108 		 * are more dest children than source children).  If the
1109 		 * preferred source child is unreadable select another.
1110 		 */
1111 		for (int i = 0; i < source_vd->vdev_children; i++) {
1112 			source_child_vd = source_vd->vdev_child[
1113 			    (dest_id + i) % source_vd->vdev_children];
1114 			if (vdev_readable(source_child_vd))
1115 				break;
1116 		}
1117 	} else {
1118 		source_child_vd = source_vd;
1119 	}
1120 
1121 	/*
1122 	 * There should always be at least one readable source child or
1123 	 * the pool would be in a suspended state.  Somehow selecting an
1124 	 * unreadable child would result in IO errors, the removal process
1125 	 * being cancelled, and the pool reverting to its pre-removal state.
1126 	 */
1127 	ASSERT3P(source_child_vd, !=, NULL);
1128 
1129 	zio_t *write_zio = zio_vdev_child_io(nzio, NULL,
1130 	    dest_child_vd, dest_offset, abd, size,
1131 	    ZIO_TYPE_WRITE, ZIO_PRIORITY_REMOVAL,
1132 	    ZIO_FLAG_CANFAIL,
1133 	    spa_vdev_copy_segment_write_done, vca);
1134 
1135 	zio_nowait(zio_vdev_child_io(write_zio, NULL,
1136 	    source_child_vd, source_offset, abd, size,
1137 	    ZIO_TYPE_READ, ZIO_PRIORITY_REMOVAL,
1138 	    ZIO_FLAG_CANFAIL,
1139 	    spa_vdev_copy_segment_read_done, vca));
1140 }
1141 
1142 /*
1143  * Allocate a new location for this segment, and create the zio_t's to
1144  * read from the old location and write to the new location.
1145  */
1146 static int
spa_vdev_copy_segment(vdev_t * vd,zfs_range_tree_t * segs,uint64_t maxalloc,uint64_t txg,vdev_copy_arg_t * vca,zio_alloc_list_t * zal)1147 spa_vdev_copy_segment(vdev_t *vd, zfs_range_tree_t *segs,
1148     uint64_t maxalloc, uint64_t txg,
1149     vdev_copy_arg_t *vca, zio_alloc_list_t *zal)
1150 {
1151 	metaslab_group_t *mg = vd->vdev_mg;
1152 	spa_t *spa = vd->vdev_spa;
1153 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
1154 	vdev_indirect_mapping_entry_t *entry;
1155 	dva_t dst = {{ 0 }};
1156 	uint64_t start = zfs_range_tree_min(segs);
1157 	ASSERT0(P2PHASE(start, 1 << spa->spa_min_ashift));
1158 
1159 	ASSERT3U(maxalloc, <=, SPA_MAXBLOCKSIZE);
1160 	ASSERT0(P2PHASE(maxalloc, 1 << spa->spa_min_ashift));
1161 
1162 	uint64_t size = zfs_range_tree_span(segs);
1163 	if (zfs_range_tree_span(segs) > maxalloc) {
1164 		/*
1165 		 * We can't allocate all the segments.  Prefer to end
1166 		 * the allocation at the end of a segment, thus avoiding
1167 		 * additional split blocks.
1168 		 */
1169 		zfs_range_seg_max_t search;
1170 		zfs_btree_index_t where;
1171 		zfs_rs_set_start(&search, segs, start + maxalloc);
1172 		zfs_rs_set_end(&search, segs, start + maxalloc);
1173 		(void) zfs_btree_find(&segs->rt_root, &search, &where);
1174 		zfs_range_seg_t *rs = zfs_btree_prev(&segs->rt_root, &where,
1175 		    &where);
1176 		if (rs != NULL) {
1177 			size = zfs_rs_get_end(rs, segs) - start;
1178 		} else {
1179 			/*
1180 			 * There are no segments that end before maxalloc.
1181 			 * I.e. the first segment is larger than maxalloc,
1182 			 * so we must split it.
1183 			 */
1184 			size = maxalloc;
1185 		}
1186 	}
1187 	ASSERT3U(size, <=, maxalloc);
1188 	ASSERT0(P2PHASE(size, 1 << spa->spa_min_ashift));
1189 
1190 	/*
1191 	 * An allocation class might not have any remaining vdevs or space
1192 	 */
1193 	metaslab_class_t *mc = mg->mg_class;
1194 	if (mc->mc_groups == 0)
1195 		mc = spa_normal_class(spa);
1196 	int error = metaslab_alloc_dva(spa, mc, size, &dst, 0, NULL, txg,
1197 	    0, zal, 0);
1198 	if (error == ENOSPC && mc != spa_normal_class(spa)) {
1199 		error = metaslab_alloc_dva(spa, spa_normal_class(spa), size,
1200 		    &dst, 0, NULL, txg, 0, zal, 0);
1201 	}
1202 	if (error != 0)
1203 		return (error);
1204 
1205 	/*
1206 	 * Determine the ranges that are not actually needed.  Offsets are
1207 	 * relative to the start of the range to be copied (i.e. relative to the
1208 	 * local variable "start").
1209 	 */
1210 	zfs_range_tree_t *obsolete_segs = zfs_range_tree_create_flags(
1211 	    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
1212 	    ZFS_RT_F_DYN_NAME, vdev_rt_name(vd, "obsolete_segs"));
1213 
1214 	zfs_btree_index_t where;
1215 	zfs_range_seg_t *rs = zfs_btree_first(&segs->rt_root, &where);
1216 	ASSERT3U(zfs_rs_get_start(rs, segs), ==, start);
1217 	uint64_t prev_seg_end = zfs_rs_get_end(rs, segs);
1218 	while ((rs = zfs_btree_next(&segs->rt_root, &where, &where)) != NULL) {
1219 		if (zfs_rs_get_start(rs, segs) >= start + size) {
1220 			break;
1221 		} else {
1222 			zfs_range_tree_add(obsolete_segs,
1223 			    prev_seg_end - start,
1224 			    zfs_rs_get_start(rs, segs) - prev_seg_end);
1225 		}
1226 		prev_seg_end = zfs_rs_get_end(rs, segs);
1227 	}
1228 	/* We don't end in the middle of an obsolete range */
1229 	ASSERT3U(start + size, <=, prev_seg_end);
1230 
1231 	zfs_range_tree_clear(segs, start, size);
1232 
1233 	/*
1234 	 * We can't have any padding of the allocated size, otherwise we will
1235 	 * misunderstand what's allocated, and the size of the mapping. We
1236 	 * prevent padding by ensuring that all devices in the pool have the
1237 	 * same ashift, and the allocation size is a multiple of the ashift.
1238 	 */
1239 	VERIFY3U(DVA_GET_ASIZE(&dst), ==, size);
1240 
1241 	entry = kmem_zalloc(sizeof (vdev_indirect_mapping_entry_t), KM_SLEEP);
1242 	DVA_MAPPING_SET_SRC_OFFSET(&entry->vime_mapping, start);
1243 	entry->vime_mapping.vimep_dst = dst;
1244 	if (spa_feature_is_enabled(spa, SPA_FEATURE_OBSOLETE_COUNTS)) {
1245 		entry->vime_obsolete_count =
1246 		    zfs_range_tree_space(obsolete_segs);
1247 	}
1248 
1249 	vdev_copy_segment_arg_t *vcsa = kmem_zalloc(sizeof (*vcsa), KM_SLEEP);
1250 	vcsa->vcsa_dest_dva = &entry->vime_mapping.vimep_dst;
1251 	vcsa->vcsa_obsolete_segs = obsolete_segs;
1252 	vcsa->vcsa_spa = spa;
1253 	vcsa->vcsa_txg = txg;
1254 
1255 	/*
1256 	 * See comment before spa_vdev_copy_one_child().
1257 	 */
1258 	spa_config_enter(spa, SCL_STATE, spa, RW_READER);
1259 	zio_t *nzio = zio_null(spa->spa_txg_zio[txg & TXG_MASK], spa, NULL,
1260 	    spa_vdev_copy_segment_done, vcsa, 0);
1261 	vdev_t *dest_vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dst));
1262 	if (dest_vd->vdev_ops == &vdev_mirror_ops) {
1263 		for (int i = 0; i < dest_vd->vdev_children; i++) {
1264 			vdev_t *child = dest_vd->vdev_child[i];
1265 			spa_vdev_copy_one_child(vca, nzio, vd, start,
1266 			    child, DVA_GET_OFFSET(&dst), i, size);
1267 		}
1268 	} else {
1269 		spa_vdev_copy_one_child(vca, nzio, vd, start,
1270 		    dest_vd, DVA_GET_OFFSET(&dst), -1, size);
1271 	}
1272 	zio_nowait(nzio);
1273 
1274 	list_insert_tail(&svr->svr_new_segments[txg & TXG_MASK], entry);
1275 	ASSERT3U(start + size, <=, vd->vdev_ms_count << vd->vdev_ms_shift);
1276 	vdev_dirty(vd, 0, NULL, txg);
1277 
1278 	return (0);
1279 }
1280 
1281 /*
1282  * Complete the removal of a toplevel vdev. This is called as a
1283  * synctask in the same txg that we will sync out the new config (to the
1284  * MOS object) which indicates that this vdev is indirect.
1285  */
1286 static void
vdev_remove_complete_sync(void * arg,dmu_tx_t * tx)1287 vdev_remove_complete_sync(void *arg, dmu_tx_t *tx)
1288 {
1289 	spa_vdev_removal_t *svr = arg;
1290 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1291 	vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
1292 
1293 	ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
1294 
1295 	for (int i = 0; i < TXG_SIZE; i++) {
1296 		ASSERT0(svr->svr_bytes_done[i]);
1297 	}
1298 
1299 	ASSERT3U(spa->spa_removing_phys.sr_copied, ==,
1300 	    spa->spa_removing_phys.sr_to_copy);
1301 
1302 	vdev_destroy_spacemaps(vd, tx);
1303 
1304 	/* destroy leaf zaps, if any */
1305 	ASSERT3P(svr->svr_zaplist, !=, NULL);
1306 	for (nvpair_t *pair = nvlist_next_nvpair(svr->svr_zaplist, NULL);
1307 	    pair != NULL;
1308 	    pair = nvlist_next_nvpair(svr->svr_zaplist, pair)) {
1309 		vdev_destroy_unlink_zap(vd, fnvpair_value_uint64(pair), tx);
1310 	}
1311 	fnvlist_free(svr->svr_zaplist);
1312 
1313 	spa_finish_removal(dmu_tx_pool(tx)->dp_spa, DSS_FINISHED, tx);
1314 	/* vd->vdev_path is not available here */
1315 	spa_history_log_internal(spa, "vdev remove completed",  tx,
1316 	    "%s vdev %llu", spa_name(spa), (u_longlong_t)vd->vdev_id);
1317 }
1318 
1319 static void
vdev_remove_enlist_zaps(vdev_t * vd,nvlist_t * zlist)1320 vdev_remove_enlist_zaps(vdev_t *vd, nvlist_t *zlist)
1321 {
1322 	ASSERT3P(zlist, !=, NULL);
1323 	ASSERT0(vdev_get_nparity(vd));
1324 
1325 	if (vd->vdev_leaf_zap != 0) {
1326 		char zkey[32];
1327 		(void) snprintf(zkey, sizeof (zkey), "%s-%llu",
1328 		    VDEV_REMOVAL_ZAP_OBJS, (u_longlong_t)vd->vdev_leaf_zap);
1329 		fnvlist_add_uint64(zlist, zkey, vd->vdev_leaf_zap);
1330 	}
1331 
1332 	for (uint64_t id = 0; id < vd->vdev_children; id++) {
1333 		vdev_remove_enlist_zaps(vd->vdev_child[id], zlist);
1334 	}
1335 }
1336 
1337 static void
vdev_remove_replace_with_indirect(vdev_t * vd,uint64_t txg)1338 vdev_remove_replace_with_indirect(vdev_t *vd, uint64_t txg)
1339 {
1340 	vdev_t *ivd;
1341 	dmu_tx_t *tx;
1342 	spa_t *spa = vd->vdev_spa;
1343 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
1344 
1345 	/*
1346 	 * First, build a list of leaf zaps to be destroyed.
1347 	 * This is passed to the sync context thread,
1348 	 * which does the actual unlinking.
1349 	 */
1350 	svr->svr_zaplist = fnvlist_alloc();
1351 	vdev_remove_enlist_zaps(vd, svr->svr_zaplist);
1352 
1353 	ivd = vdev_add_parent(vd, &vdev_indirect_ops);
1354 	ivd->vdev_removing = 0;
1355 
1356 	vd->vdev_leaf_zap = 0;
1357 
1358 	vdev_remove_child(ivd, vd);
1359 	vdev_compact_children(ivd);
1360 
1361 	ASSERT(!list_link_active(&vd->vdev_state_dirty_node));
1362 
1363 	mutex_enter(&svr->svr_lock);
1364 	svr->svr_thread = NULL;
1365 	cv_broadcast(&svr->svr_cv);
1366 	mutex_exit(&svr->svr_lock);
1367 
1368 	/* After this, we can not use svr. */
1369 	tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
1370 	dsl_sync_task_nowait(spa->spa_dsl_pool,
1371 	    vdev_remove_complete_sync, svr, tx);
1372 	dmu_tx_commit(tx);
1373 }
1374 
1375 /*
1376  * Complete the removal of a toplevel vdev. This is called in open
1377  * context by the removal thread after we have copied all vdev's data.
1378  */
1379 static void
vdev_remove_complete(spa_t * spa)1380 vdev_remove_complete(spa_t *spa)
1381 {
1382 	uint64_t txg;
1383 
1384 	/*
1385 	 * Wait for any deferred frees to be synced before we call
1386 	 * vdev_metaslab_fini()
1387 	 */
1388 	txg_wait_synced(spa->spa_dsl_pool, 0);
1389 	txg = spa_vdev_enter(spa);
1390 	vdev_t *vd = vdev_lookup_top(spa, spa->spa_vdev_removal->svr_vdev_id);
1391 	ASSERT0P(vd->vdev_initialize_thread);
1392 	ASSERT0P(vd->vdev_trim_thread);
1393 	ASSERT0P(vd->vdev_autotrim_thread);
1394 	vdev_rebuild_stop_wait(vd);
1395 	ASSERT0P(vd->vdev_rebuild_thread);
1396 
1397 	sysevent_t *ev = spa_event_create(spa, vd, NULL,
1398 	    ESC_ZFS_VDEV_REMOVE_DEV);
1399 
1400 	zfs_dbgmsg("finishing device removal for vdev %llu in txg %llu",
1401 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)txg);
1402 
1403 	/* the vdev is no longer part of the dspace */
1404 	vdev_update_nonallocating_space(vd, B_FALSE);
1405 
1406 	/*
1407 	 * Discard allocation state.
1408 	 */
1409 	if (vd->vdev_mg != NULL) {
1410 		vdev_metaslab_fini(vd);
1411 		metaslab_group_destroy(vd->vdev_mg);
1412 		vd->vdev_mg = NULL;
1413 	}
1414 	if (vd->vdev_log_mg != NULL) {
1415 		ASSERT0(vd->vdev_ms_count);
1416 		metaslab_group_destroy(vd->vdev_log_mg);
1417 		vd->vdev_log_mg = NULL;
1418 	}
1419 	ASSERT0(vd->vdev_stat.vs_space);
1420 	ASSERT0(vd->vdev_stat.vs_dspace);
1421 
1422 	vdev_remove_replace_with_indirect(vd, txg);
1423 
1424 	/*
1425 	 * Release the config lock and allow spa_sync to run and finish the
1426 	 * removal via vdev_remove_complete_sync in syncing context.
1427 	 *
1428 	 * Retain the namespace lock to prevent the pool from being exported
1429 	 * or destroyed before completion of the device removal.
1430 	 *
1431 	 * Note that we hold on to the vdev_t that has been replaced.  Since
1432 	 * it isn't part of the vdev tree any longer, it can't be concurrently
1433 	 * manipulated, even while we don't have the config lock.
1434 	 */
1435 	(void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
1436 
1437 	/*
1438 	 * Top ZAP should have been transferred to the indirect vdev in
1439 	 * vdev_remove_replace_with_indirect.
1440 	 */
1441 	ASSERT0(vd->vdev_top_zap);
1442 
1443 	/*
1444 	 * Leaf ZAP should have been moved in vdev_remove_replace_with_indirect.
1445 	 */
1446 	ASSERT0(vd->vdev_leaf_zap);
1447 
1448 	/* Update the vdev labels and dirty the config. */
1449 	txg = spa_vdev_config_enter(spa);
1450 	(void) vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
1451 	/*
1452 	 * Request to update the config and the config cachefile.
1453 	 */
1454 	vdev_config_dirty(spa->spa_root_vdev);
1455 	(void) spa_vdev_exit(spa, vd, txg, 0);
1456 
1457 	if (ev != NULL)
1458 		spa_event_post(ev);
1459 }
1460 
1461 /*
1462  * Evacuates a segment of size at most max_alloc from the vdev
1463  * via repeated calls to spa_vdev_copy_segment. If an allocation
1464  * fails, the pool is probably too fragmented to handle such a
1465  * large size, so decrease max_alloc so that the caller will not try
1466  * this size again this txg.
1467  */
1468 static void
spa_vdev_copy_impl(vdev_t * vd,spa_vdev_removal_t * svr,vdev_copy_arg_t * vca,uint64_t * max_alloc,dmu_tx_t * tx)1469 spa_vdev_copy_impl(vdev_t *vd, spa_vdev_removal_t *svr, vdev_copy_arg_t *vca,
1470     uint64_t *max_alloc, dmu_tx_t *tx)
1471 {
1472 	uint64_t txg = dmu_tx_get_txg(tx);
1473 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1474 
1475 	mutex_enter(&svr->svr_lock);
1476 
1477 	/*
1478 	 * Determine how big of a chunk to copy.  We can allocate up
1479 	 * to max_alloc bytes, and we can span up to vdev_removal_max_span
1480 	 * bytes of unallocated space at a time.  "segs" will track the
1481 	 * allocated segments that we are copying.  We may also be copying
1482 	 * free segments (of up to vdev_removal_max_span bytes).
1483 	 */
1484 	zfs_range_tree_t *segs = zfs_range_tree_create_flags(
1485 	    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
1486 	    ZFS_RT_F_DYN_NAME, vdev_rt_name(vd, "spa_vdev_copy_impl:segs"));
1487 	for (;;) {
1488 		zfs_range_tree_t *rt = svr->svr_allocd_segs;
1489 		zfs_range_seg_t *rs = zfs_range_tree_first(rt);
1490 
1491 		if (rs == NULL)
1492 			break;
1493 
1494 		uint64_t seg_length;
1495 
1496 		if (zfs_range_tree_is_empty(segs)) {
1497 			/* need to truncate the first seg based on max_alloc */
1498 			seg_length = MIN(zfs_rs_get_end(rs, rt) -
1499 			    zfs_rs_get_start(rs, rt), *max_alloc);
1500 		} else {
1501 			if (zfs_rs_get_start(rs, rt) - zfs_range_tree_max(segs)
1502 			    > vdev_removal_max_span) {
1503 				/*
1504 				 * Including this segment would cause us to
1505 				 * copy a larger unneeded chunk than is allowed.
1506 				 */
1507 				break;
1508 			} else if (zfs_rs_get_end(rs, rt) -
1509 			    zfs_range_tree_min(segs) > *max_alloc) {
1510 				/*
1511 				 * This additional segment would extend past
1512 				 * max_alloc. Rather than splitting this
1513 				 * segment, leave it for the next mapping.
1514 				 */
1515 				break;
1516 			} else {
1517 				seg_length = zfs_rs_get_end(rs, rt) -
1518 				    zfs_rs_get_start(rs, rt);
1519 			}
1520 		}
1521 
1522 		zfs_range_tree_add(segs, zfs_rs_get_start(rs, rt), seg_length);
1523 		zfs_range_tree_remove(svr->svr_allocd_segs,
1524 		    zfs_rs_get_start(rs, rt), seg_length);
1525 	}
1526 
1527 	if (zfs_range_tree_is_empty(segs)) {
1528 		mutex_exit(&svr->svr_lock);
1529 		zfs_range_tree_destroy(segs);
1530 		return;
1531 	}
1532 
1533 	if (svr->svr_max_offset_to_sync[txg & TXG_MASK] == 0) {
1534 		dsl_sync_task_nowait(dmu_tx_pool(tx), vdev_mapping_sync,
1535 		    svr, tx);
1536 	}
1537 
1538 	svr->svr_max_offset_to_sync[txg & TXG_MASK] = zfs_range_tree_max(segs);
1539 
1540 	/*
1541 	 * Note: this is the amount of *allocated* space
1542 	 * that we are taking care of each txg.
1543 	 */
1544 	svr->svr_bytes_done[txg & TXG_MASK] += zfs_range_tree_space(segs);
1545 
1546 	mutex_exit(&svr->svr_lock);
1547 
1548 	zio_alloc_list_t zal;
1549 	metaslab_trace_init(&zal);
1550 	uint64_t thismax = SPA_MAXBLOCKSIZE;
1551 	while (!zfs_range_tree_is_empty(segs)) {
1552 		int error = spa_vdev_copy_segment(vd,
1553 		    segs, thismax, txg, vca, &zal);
1554 
1555 		if (error == ENOSPC) {
1556 			/*
1557 			 * Cut our segment in half, and don't try this
1558 			 * segment size again this txg.  Note that the
1559 			 * allocation size must be aligned to the highest
1560 			 * ashift in the pool, so that the allocation will
1561 			 * not be padded out to a multiple of the ashift,
1562 			 * which could cause us to think that this mapping
1563 			 * is larger than we intended.
1564 			 */
1565 			ASSERT3U(spa->spa_max_ashift, >=, SPA_MINBLOCKSHIFT);
1566 			ASSERT3U(spa->spa_max_ashift, ==, spa->spa_min_ashift);
1567 			uint64_t attempted =
1568 			    MIN(zfs_range_tree_span(segs), thismax);
1569 			thismax = P2ROUNDUP(attempted / 2,
1570 			    1 << spa->spa_max_ashift);
1571 			/*
1572 			 * The minimum-size allocation can not fail.
1573 			 */
1574 			ASSERT3U(attempted, >, 1 << spa->spa_max_ashift);
1575 			*max_alloc = attempted - (1 << spa->spa_max_ashift);
1576 		} else {
1577 			ASSERT0(error);
1578 
1579 			/*
1580 			 * We've performed an allocation, so reset the
1581 			 * alloc trace list.
1582 			 */
1583 			metaslab_trace_fini(&zal);
1584 			metaslab_trace_init(&zal);
1585 		}
1586 	}
1587 	metaslab_trace_fini(&zal);
1588 	zfs_range_tree_destroy(segs);
1589 }
1590 
1591 /*
1592  * The size of each removal mapping is limited by the tunable
1593  * zfs_remove_max_segment, but we must adjust this to be a multiple of the
1594  * pool's ashift, so that we don't try to split individual sectors regardless
1595  * of the tunable value.  (Note that device removal requires that all devices
1596  * have the same ashift, so there's no difference between spa_min_ashift and
1597  * spa_max_ashift.) The raw tunable should not be used elsewhere.
1598  */
1599 uint64_t
spa_remove_max_segment(spa_t * spa)1600 spa_remove_max_segment(spa_t *spa)
1601 {
1602 	return (P2ROUNDUP(zfs_remove_max_segment, 1 << spa->spa_max_ashift));
1603 }
1604 
1605 /*
1606  * The removal thread operates in open context.  It iterates over all
1607  * allocated space in the vdev, by loading each metaslab's spacemap.
1608  * For each contiguous segment of allocated space (capping the segment
1609  * size at SPA_MAXBLOCKSIZE), we:
1610  *    - Allocate space for it on another vdev.
1611  *    - Create a new mapping from the old location to the new location
1612  *      (as a record in svr_new_segments).
1613  *    - Initiate a physical read zio to get the data off the removing disk.
1614  *    - In the read zio's done callback, initiate a physical write zio to
1615  *      write it to the new vdev.
1616  * Note that all of this will take effect when a particular TXG syncs.
1617  * The sync thread ensures that all the phys reads and writes for the syncing
1618  * TXG have completed (see spa_txg_zio) and writes the new mappings to disk
1619  * (see vdev_mapping_sync()).
1620  */
1621 static __attribute__((noreturn)) void
spa_vdev_remove_thread(void * arg)1622 spa_vdev_remove_thread(void *arg)
1623 {
1624 	spa_t *spa = arg;
1625 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
1626 	vdev_copy_arg_t vca;
1627 	uint64_t max_alloc = spa_remove_max_segment(spa);
1628 	uint64_t last_txg = 0;
1629 
1630 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
1631 	vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
1632 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1633 	uint64_t start_offset = vdev_indirect_mapping_max_offset(vim);
1634 
1635 	ASSERT3P(vd->vdev_ops, !=, &vdev_indirect_ops);
1636 	ASSERT(vdev_is_concrete(vd));
1637 	ASSERT(vd->vdev_removing);
1638 	ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
1639 	ASSERT(vim != NULL);
1640 
1641 	mutex_init(&vca.vca_lock, NULL, MUTEX_DEFAULT, NULL);
1642 	cv_init(&vca.vca_cv, NULL, CV_DEFAULT, NULL);
1643 	vca.vca_outstanding_bytes = 0;
1644 	vca.vca_read_error_bytes = 0;
1645 	vca.vca_write_error_bytes = 0;
1646 
1647 	zfs_range_tree_t *segs = zfs_range_tree_create_flags(
1648 	    NULL, ZFS_RANGE_SEG64, NULL, 0, 0,
1649 	    ZFS_RT_F_DYN_NAME, vdev_rt_name(vd, "spa_vdev_remove_thread:segs"));
1650 
1651 	mutex_enter(&svr->svr_lock);
1652 
1653 	/*
1654 	 * Start from vim_max_offset so we pick up where we left off
1655 	 * if we are restarting the removal after opening the pool.
1656 	 */
1657 	uint64_t msi;
1658 	for (msi = start_offset >> vd->vdev_ms_shift;
1659 	    msi < vd->vdev_ms_count && !svr->svr_thread_exit; msi++) {
1660 		metaslab_t *msp = vd->vdev_ms[msi];
1661 		ASSERT3U(msi, <=, vd->vdev_ms_count);
1662 
1663 again:
1664 		ASSERT0(zfs_range_tree_space(svr->svr_allocd_segs));
1665 		mutex_exit(&svr->svr_lock);
1666 
1667 		mutex_enter(&msp->ms_sync_lock);
1668 		mutex_enter(&msp->ms_lock);
1669 
1670 		/*
1671 		 * Assert nothing in flight -- ms_*tree is empty.
1672 		 */
1673 		for (int i = 0; i < TXG_SIZE; i++) {
1674 			ASSERT0(zfs_range_tree_space(msp->ms_allocating[i]));
1675 		}
1676 
1677 		/*
1678 		 * If the metaslab has ever been synced (ms_sm != NULL),
1679 		 * read the allocated segments from the space map object
1680 		 * into svr_allocd_segs. Since we do this while holding
1681 		 * ms_lock and ms_sync_lock, concurrent frees (which
1682 		 * would have modified the space map) will wait for us
1683 		 * to finish loading the spacemap, and then take the
1684 		 * appropriate action (see free_from_removing_vdev()).
1685 		 */
1686 		if (msp->ms_sm != NULL)
1687 			VERIFY0(space_map_load(msp->ms_sm, segs, SM_ALLOC));
1688 
1689 		/*
1690 		 * We could not hold svr_lock while loading space map, or we
1691 		 * could hit deadlock in a ZIO pipeline, having to wait for
1692 		 * it.  But we can not block for it here under metaslab locks,
1693 		 * or it would be a lock ordering violation.
1694 		 */
1695 		if (!mutex_tryenter(&svr->svr_lock)) {
1696 			mutex_exit(&msp->ms_lock);
1697 			mutex_exit(&msp->ms_sync_lock);
1698 			zfs_range_tree_vacate(segs, NULL, NULL);
1699 			mutex_enter(&svr->svr_lock);
1700 			goto again;
1701 		}
1702 
1703 		zfs_range_tree_swap(&segs, &svr->svr_allocd_segs);
1704 		zfs_range_tree_walk(msp->ms_unflushed_allocs,
1705 		    zfs_range_tree_add, svr->svr_allocd_segs);
1706 		zfs_range_tree_walk(msp->ms_unflushed_frees,
1707 		    zfs_range_tree_remove, svr->svr_allocd_segs);
1708 		zfs_range_tree_walk(msp->ms_freeing,
1709 		    zfs_range_tree_remove, svr->svr_allocd_segs);
1710 
1711 		mutex_exit(&msp->ms_lock);
1712 		mutex_exit(&msp->ms_sync_lock);
1713 
1714 		/*
1715 		 * When we are resuming from a paused removal (i.e.
1716 		 * when importing a pool with a removal in progress),
1717 		 * discard any state that we have already processed.
1718 		 */
1719 		zfs_range_tree_clear(svr->svr_allocd_segs, 0, start_offset);
1720 
1721 		vca.vca_msp = msp;
1722 		zfs_dbgmsg("copying %llu segments for metaslab %llu",
1723 		    (u_longlong_t)zfs_btree_numnodes(
1724 		    &svr->svr_allocd_segs->rt_root),
1725 		    (u_longlong_t)msp->ms_id);
1726 
1727 		while (!svr->svr_thread_exit &&
1728 		    !zfs_range_tree_is_empty(svr->svr_allocd_segs)) {
1729 
1730 			mutex_exit(&svr->svr_lock);
1731 
1732 			/*
1733 			 * We need to periodically drop the config lock so that
1734 			 * writers can get in.  Additionally, we can't wait
1735 			 * for a txg to sync while holding a config lock
1736 			 * (since a waiting writer could cause a 3-way deadlock
1737 			 * with the sync thread, which also gets a config
1738 			 * lock for reader).  So we can't hold the config lock
1739 			 * while calling dmu_tx_assign().
1740 			 */
1741 			spa_config_exit(spa, SCL_CONFIG, FTAG);
1742 
1743 			/*
1744 			 * This delay will pause the removal around the point
1745 			 * specified by zfs_removal_suspend_progress. We do this
1746 			 * solely from the test suite or during debugging.
1747 			 */
1748 			while (zfs_removal_suspend_progress &&
1749 			    !svr->svr_thread_exit)
1750 				delay(hz);
1751 
1752 			mutex_enter(&vca.vca_lock);
1753 			while (vca.vca_outstanding_bytes >
1754 			    zfs_remove_max_copy_bytes) {
1755 				cv_wait(&vca.vca_cv, &vca.vca_lock);
1756 			}
1757 			mutex_exit(&vca.vca_lock);
1758 
1759 			dmu_tx_t *tx =
1760 			    dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
1761 
1762 			VERIFY0(dmu_tx_assign(tx, DMU_TX_WAIT |
1763 			    DMU_TX_SUSPEND));
1764 			uint64_t txg = dmu_tx_get_txg(tx);
1765 
1766 			/*
1767 			 * Reacquire the vdev_config lock.  The vdev_t
1768 			 * that we're removing may have changed, e.g. due
1769 			 * to a vdev_attach or vdev_detach.
1770 			 */
1771 			spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
1772 			vd = vdev_lookup_top(spa, svr->svr_vdev_id);
1773 
1774 			if (txg != last_txg)
1775 				max_alloc = spa_remove_max_segment(spa);
1776 			last_txg = txg;
1777 
1778 			spa_vdev_copy_impl(vd, svr, &vca, &max_alloc, tx);
1779 
1780 			dmu_tx_commit(tx);
1781 			mutex_enter(&svr->svr_lock);
1782 		}
1783 
1784 		mutex_enter(&vca.vca_lock);
1785 		if (zfs_removal_ignore_errors == 0 &&
1786 		    (vca.vca_read_error_bytes > 0 ||
1787 		    vca.vca_write_error_bytes > 0)) {
1788 			svr->svr_thread_exit = B_TRUE;
1789 		}
1790 		mutex_exit(&vca.vca_lock);
1791 	}
1792 
1793 	mutex_exit(&svr->svr_lock);
1794 
1795 	spa_config_exit(spa, SCL_CONFIG, FTAG);
1796 
1797 	zfs_range_tree_destroy(segs);
1798 
1799 	/*
1800 	 * Wait for all copies to finish before cleaning up the vca.
1801 	 */
1802 	txg_wait_synced(spa->spa_dsl_pool, 0);
1803 	ASSERT0(vca.vca_outstanding_bytes);
1804 
1805 	mutex_destroy(&vca.vca_lock);
1806 	cv_destroy(&vca.vca_cv);
1807 
1808 	if (svr->svr_thread_exit) {
1809 		mutex_enter(&svr->svr_lock);
1810 		zfs_range_tree_vacate(svr->svr_allocd_segs, NULL, NULL);
1811 		svr->svr_thread = NULL;
1812 		cv_broadcast(&svr->svr_cv);
1813 		mutex_exit(&svr->svr_lock);
1814 
1815 		/*
1816 		 * During the removal process an unrecoverable read or write
1817 		 * error was encountered.  The removal process must be
1818 		 * cancelled or this damage may become permanent.
1819 		 */
1820 		if (zfs_removal_ignore_errors == 0 &&
1821 		    (vca.vca_read_error_bytes > 0 ||
1822 		    vca.vca_write_error_bytes > 0)) {
1823 			zfs_dbgmsg("canceling removal due to IO errors: "
1824 			    "[read_error_bytes=%llu] [write_error_bytes=%llu]",
1825 			    (u_longlong_t)vca.vca_read_error_bytes,
1826 			    (u_longlong_t)vca.vca_write_error_bytes);
1827 			spa_vdev_remove_cancel_impl(spa);
1828 		}
1829 	} else {
1830 		ASSERT0(zfs_range_tree_space(svr->svr_allocd_segs));
1831 		vdev_remove_complete(spa);
1832 	}
1833 
1834 	thread_exit();
1835 }
1836 
1837 void
spa_vdev_remove_suspend(spa_t * spa)1838 spa_vdev_remove_suspend(spa_t *spa)
1839 {
1840 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
1841 
1842 	if (svr == NULL)
1843 		return;
1844 
1845 	mutex_enter(&svr->svr_lock);
1846 	svr->svr_thread_exit = B_TRUE;
1847 	while (svr->svr_thread != NULL)
1848 		cv_wait(&svr->svr_cv, &svr->svr_lock);
1849 	svr->svr_thread_exit = B_FALSE;
1850 	mutex_exit(&svr->svr_lock);
1851 }
1852 
1853 /*
1854  * Return true if the "allocating" property has been set to "off"
1855  */
1856 static boolean_t
vdev_prop_allocating_off(vdev_t * vd)1857 vdev_prop_allocating_off(vdev_t *vd)
1858 {
1859 	uint64_t objid = vd->vdev_top_zap;
1860 	uint64_t allocating = 1;
1861 
1862 	/* no vdev property object => no props */
1863 	if (objid != 0) {
1864 		spa_t *spa = vd->vdev_spa;
1865 		objset_t *mos = spa->spa_meta_objset;
1866 
1867 		mutex_enter(&spa->spa_props_lock);
1868 		(void) zap_lookup(mos, objid, "allocating", sizeof (uint64_t),
1869 		    1, &allocating);
1870 		mutex_exit(&spa->spa_props_lock);
1871 	}
1872 	return (allocating == 0);
1873 }
1874 
1875 static int
spa_vdev_remove_cancel_check(void * arg,dmu_tx_t * tx)1876 spa_vdev_remove_cancel_check(void *arg, dmu_tx_t *tx)
1877 {
1878 	(void) arg;
1879 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1880 
1881 	if (spa->spa_vdev_removal == NULL)
1882 		return (ENOTACTIVE);
1883 	return (0);
1884 }
1885 
1886 /*
1887  * Cancel a removal by freeing all entries from the partial mapping
1888  * and marking the vdev as no longer being removing.
1889  */
1890 static void
spa_vdev_remove_cancel_sync(void * arg,dmu_tx_t * tx)1891 spa_vdev_remove_cancel_sync(void *arg, dmu_tx_t *tx)
1892 {
1893 	(void) arg;
1894 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1895 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
1896 	vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
1897 	vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
1898 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1899 	objset_t *mos = spa->spa_meta_objset;
1900 
1901 	ASSERT0P(svr->svr_thread);
1902 
1903 	spa_feature_decr(spa, SPA_FEATURE_DEVICE_REMOVAL, tx);
1904 
1905 	boolean_t are_precise;
1906 	VERIFY0(vdev_obsolete_counts_are_precise(vd, &are_precise));
1907 	if (are_precise) {
1908 		spa_feature_decr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
1909 		VERIFY0(zap_remove(spa->spa_meta_objset, vd->vdev_top_zap,
1910 		    VDEV_TOP_ZAP_OBSOLETE_COUNTS_ARE_PRECISE, tx));
1911 	}
1912 
1913 	uint64_t obsolete_sm_object;
1914 	VERIFY0(vdev_obsolete_sm_object(vd, &obsolete_sm_object));
1915 	if (obsolete_sm_object != 0) {
1916 		ASSERT(vd->vdev_obsolete_sm != NULL);
1917 		ASSERT3U(obsolete_sm_object, ==,
1918 		    space_map_object(vd->vdev_obsolete_sm));
1919 
1920 		space_map_free(vd->vdev_obsolete_sm, tx);
1921 		VERIFY0(zap_remove(spa->spa_meta_objset, vd->vdev_top_zap,
1922 		    VDEV_TOP_ZAP_INDIRECT_OBSOLETE_SM, tx));
1923 		space_map_close(vd->vdev_obsolete_sm);
1924 		vd->vdev_obsolete_sm = NULL;
1925 		spa_feature_decr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
1926 	}
1927 	for (int i = 0; i < TXG_SIZE; i++) {
1928 		ASSERT(list_is_empty(&svr->svr_new_segments[i]));
1929 		ASSERT3U(svr->svr_max_offset_to_sync[i], <=,
1930 		    vdev_indirect_mapping_max_offset(vim));
1931 	}
1932 
1933 	zfs_range_tree_t *segs = zfs_range_tree_create_flags(
1934 	    NULL, ZFS_RANGE_SEG64, NULL, 0, 0, ZFS_RT_F_DYN_NAME,
1935 	    vdev_rt_name(vd, "spa_vdev_remove_cancel_sync:segs"));
1936 	for (uint64_t msi = 0; msi < vd->vdev_ms_count; msi++) {
1937 		metaslab_t *msp = vd->vdev_ms[msi];
1938 
1939 		if (msp->ms_start >= vdev_indirect_mapping_max_offset(vim))
1940 			break;
1941 
1942 		ASSERT0(zfs_range_tree_space(svr->svr_allocd_segs));
1943 
1944 		mutex_enter(&msp->ms_lock);
1945 
1946 		/*
1947 		 * Assert nothing in flight -- ms_*tree is empty.
1948 		 */
1949 		for (int i = 0; i < TXG_SIZE; i++)
1950 			ASSERT0(zfs_range_tree_space(msp->ms_allocating[i]));
1951 		for (int i = 0; i < TXG_DEFER_SIZE; i++)
1952 			ASSERT0(zfs_range_tree_space(msp->ms_defer[i]));
1953 		ASSERT0(zfs_range_tree_space(msp->ms_freed));
1954 
1955 		if (msp->ms_sm != NULL)
1956 			VERIFY0(space_map_load(msp->ms_sm, segs, SM_ALLOC));
1957 
1958 		zfs_range_tree_walk(msp->ms_unflushed_allocs,
1959 		    zfs_range_tree_add, segs);
1960 		zfs_range_tree_walk(msp->ms_unflushed_frees,
1961 		    zfs_range_tree_remove, segs);
1962 		zfs_range_tree_walk(msp->ms_freeing,
1963 		    zfs_range_tree_remove, segs);
1964 		mutex_exit(&msp->ms_lock);
1965 
1966 		/*
1967 		 * Clear everything past what has been synced,
1968 		 * because we have not allocated mappings for it yet.
1969 		 */
1970 		uint64_t syncd = vdev_indirect_mapping_max_offset(vim);
1971 		uint64_t ms_end = msp->ms_start + msp->ms_size;
1972 		if (ms_end > syncd)
1973 			zfs_range_tree_clear(segs, syncd, ms_end - syncd);
1974 
1975 		zfs_range_tree_vacate(segs, free_mapped_segment_cb, vd);
1976 	}
1977 	zfs_range_tree_destroy(segs);
1978 
1979 	/*
1980 	 * Note: this must happen after we invoke free_mapped_segment_cb,
1981 	 * because it adds to the obsolete_segments.
1982 	 */
1983 	zfs_range_tree_vacate(vd->vdev_obsolete_segments, NULL, NULL);
1984 
1985 	ASSERT3U(vic->vic_mapping_object, ==,
1986 	    vdev_indirect_mapping_object(vd->vdev_indirect_mapping));
1987 	vdev_indirect_mapping_close(vd->vdev_indirect_mapping);
1988 	vd->vdev_indirect_mapping = NULL;
1989 	vdev_indirect_mapping_free(mos, vic->vic_mapping_object, tx);
1990 	vic->vic_mapping_object = 0;
1991 
1992 	ASSERT3U(vic->vic_births_object, ==,
1993 	    vdev_indirect_births_object(vd->vdev_indirect_births));
1994 	vdev_indirect_births_close(vd->vdev_indirect_births);
1995 	vd->vdev_indirect_births = NULL;
1996 	vdev_indirect_births_free(mos, vic->vic_births_object, tx);
1997 	vic->vic_births_object = 0;
1998 
1999 	/*
2000 	 * We may have processed some frees from the removing vdev in this
2001 	 * txg, thus increasing svr_bytes_done; discard that here to
2002 	 * satisfy the assertions in spa_vdev_removal_destroy().
2003 	 * Note that future txg's can not have any bytes_done, because
2004 	 * future TXG's are only modified from open context, and we have
2005 	 * already shut down the copying thread.
2006 	 */
2007 	svr->svr_bytes_done[dmu_tx_get_txg(tx) & TXG_MASK] = 0;
2008 	spa_finish_removal(spa, DSS_CANCELED, tx);
2009 
2010 	vd->vdev_removing = B_FALSE;
2011 
2012 	if (!vdev_prop_allocating_off(vd)) {
2013 		spa_config_enter(spa, SCL_ALLOC | SCL_VDEV, FTAG, RW_WRITER);
2014 		vdev_activate(vd);
2015 		spa_config_exit(spa, SCL_ALLOC | SCL_VDEV, FTAG);
2016 	}
2017 
2018 	vdev_config_dirty(vd);
2019 
2020 	zfs_dbgmsg("canceled device removal for vdev %llu in %llu",
2021 	    (u_longlong_t)vd->vdev_id, (u_longlong_t)dmu_tx_get_txg(tx));
2022 	spa_history_log_internal(spa, "vdev remove canceled", tx,
2023 	    "%s vdev %llu %s", spa_name(spa),
2024 	    (u_longlong_t)vd->vdev_id,
2025 	    (vd->vdev_path != NULL) ? vd->vdev_path : "-");
2026 }
2027 
2028 static int
spa_vdev_remove_cancel_impl(spa_t * spa)2029 spa_vdev_remove_cancel_impl(spa_t *spa)
2030 {
2031 	int error = dsl_sync_task(spa->spa_name, spa_vdev_remove_cancel_check,
2032 	    spa_vdev_remove_cancel_sync, NULL, 0,
2033 	    ZFS_SPACE_CHECK_EXTRA_RESERVED);
2034 	return (error);
2035 }
2036 
2037 int
spa_vdev_remove_cancel(spa_t * spa)2038 spa_vdev_remove_cancel(spa_t *spa)
2039 {
2040 	spa_vdev_remove_suspend(spa);
2041 
2042 	if (spa->spa_vdev_removal == NULL)
2043 		return (ENOTACTIVE);
2044 
2045 	return (spa_vdev_remove_cancel_impl(spa));
2046 }
2047 
2048 void
svr_sync(spa_t * spa,dmu_tx_t * tx)2049 svr_sync(spa_t *spa, dmu_tx_t *tx)
2050 {
2051 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
2052 	int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
2053 
2054 	if (svr == NULL)
2055 		return;
2056 
2057 	/*
2058 	 * This check is necessary so that we do not dirty the
2059 	 * DIRECTORY_OBJECT via spa_sync_removing_state() when there
2060 	 * is nothing to do.  Dirtying it every time would prevent us
2061 	 * from syncing-to-convergence.
2062 	 */
2063 	if (svr->svr_bytes_done[txgoff] == 0)
2064 		return;
2065 
2066 	/*
2067 	 * Update progress accounting.
2068 	 */
2069 	spa->spa_removing_phys.sr_copied += svr->svr_bytes_done[txgoff];
2070 	svr->svr_bytes_done[txgoff] = 0;
2071 
2072 	spa_sync_removing_state(spa, tx);
2073 }
2074 
2075 static void
vdev_remove_make_hole_and_free(vdev_t * vd)2076 vdev_remove_make_hole_and_free(vdev_t *vd)
2077 {
2078 	uint64_t id = vd->vdev_id;
2079 	spa_t *spa = vd->vdev_spa;
2080 	vdev_t *rvd = spa->spa_root_vdev;
2081 
2082 	ASSERT(spa_namespace_held());
2083 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
2084 
2085 	vdev_free(vd);
2086 
2087 	vd = vdev_alloc_common(spa, id, 0, &vdev_hole_ops);
2088 	vdev_add_child(rvd, vd);
2089 	vdev_config_dirty(rvd);
2090 
2091 	/*
2092 	 * Reassess the health of our root vdev.
2093 	 */
2094 	vdev_reopen(rvd);
2095 }
2096 
2097 /*
2098  * Remove a log device.  The config lock is held for the specified TXG.
2099  */
2100 static int
spa_vdev_remove_log(vdev_t * vd,uint64_t * txg)2101 spa_vdev_remove_log(vdev_t *vd, uint64_t *txg)
2102 {
2103 	metaslab_group_t *mg = vd->vdev_mg;
2104 	spa_t *spa = vd->vdev_spa;
2105 	int error = 0;
2106 
2107 	ASSERT(vd->vdev_islog);
2108 	ASSERT(vd == vd->vdev_top);
2109 	ASSERT0P(vd->vdev_log_mg);
2110 	ASSERT(spa_namespace_held());
2111 
2112 	/*
2113 	 * Stop allocating from this vdev.
2114 	 */
2115 	metaslab_group_passivate(mg);
2116 
2117 	/*
2118 	 * Wait for the youngest allocations and frees to sync,
2119 	 * and then wait for the deferral of those frees to finish.
2120 	 */
2121 	spa_vdev_config_exit(spa, NULL,
2122 	    *txg + TXG_CONCURRENT_STATES + TXG_DEFER_SIZE, 0, FTAG);
2123 
2124 	/*
2125 	 * Cancel any initialize or TRIM which was in progress.
2126 	 */
2127 	vdev_initialize_stop_all(vd, VDEV_INITIALIZE_CANCELED);
2128 	vdev_trim_stop_all(vd, VDEV_TRIM_CANCELED);
2129 	vdev_autotrim_stop_wait(vd);
2130 
2131 	/*
2132 	 * Evacuate the device.  We don't hold the config lock as
2133 	 * writer since we need to do I/O but we do keep the
2134 	 * spa_namespace_lock held.  Once this completes the device
2135 	 * should no longer have any blocks allocated on it.
2136 	 */
2137 	ASSERT(spa_namespace_held());
2138 	if (vd->vdev_stat.vs_alloc != 0)
2139 		error = spa_reset_logs(spa);
2140 
2141 	*txg = spa_vdev_config_enter(spa);
2142 
2143 	if (error != 0) {
2144 		metaslab_group_activate(mg);
2145 		ASSERT0P(vd->vdev_log_mg);
2146 		return (error);
2147 	}
2148 
2149 	/*
2150 	 * The evacuation succeeded.  Remove any remaining MOS metadata
2151 	 * associated with this vdev, and wait for these changes to sync.
2152 	 */
2153 	vd->vdev_removing = B_TRUE;
2154 
2155 	vdev_dirty_leaves(vd, VDD_DTL, *txg);
2156 	vdev_config_dirty(vd);
2157 
2158 	/*
2159 	 * When the log space map feature is enabled we look at
2160 	 * the vdev's top_zap to find the on-disk flush data of
2161 	 * the metaslab we just flushed. Thus, while removing a
2162 	 * log vdev we make sure to call vdev_metaslab_fini()
2163 	 * first, which removes all metaslabs of this vdev from
2164 	 * spa_metaslabs_by_flushed before vdev_remove_empty()
2165 	 * destroys the top_zap of this log vdev.
2166 	 *
2167 	 * This avoids the scenario where we flush a metaslab
2168 	 * from the log vdev being removed that doesn't have a
2169 	 * top_zap and end up failing to lookup its on-disk flush
2170 	 * data.
2171 	 *
2172 	 * We don't call metaslab_group_destroy() right away
2173 	 * though (it will be called in vdev_free() later) as
2174 	 * during metaslab_sync() of metaslabs from other vdevs
2175 	 * we may touch the metaslab group of this vdev through
2176 	 * metaslab_class_histogram_verify()
2177 	 */
2178 	vdev_metaslab_fini(vd);
2179 
2180 	spa_vdev_config_exit(spa, NULL, *txg, 0, FTAG);
2181 	*txg = spa_vdev_config_enter(spa);
2182 
2183 	sysevent_t *ev = spa_event_create(spa, vd, NULL,
2184 	    ESC_ZFS_VDEV_REMOVE_DEV);
2185 	ASSERT(spa_namespace_held());
2186 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
2187 
2188 	/* The top ZAP should have been destroyed by vdev_remove_empty. */
2189 	ASSERT0(vd->vdev_top_zap);
2190 	/* The leaf ZAP should have been destroyed by vdev_dtl_sync. */
2191 	ASSERT0(vd->vdev_leaf_zap);
2192 
2193 	(void) vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
2194 
2195 	if (list_link_active(&vd->vdev_state_dirty_node))
2196 		vdev_state_clean(vd);
2197 	if (list_link_active(&vd->vdev_config_dirty_node))
2198 		vdev_config_clean(vd);
2199 
2200 	ASSERT0(vd->vdev_stat.vs_alloc);
2201 
2202 	/*
2203 	 * Clean up the vdev namespace.
2204 	 */
2205 	vdev_remove_make_hole_and_free(vd);
2206 
2207 	if (ev != NULL)
2208 		spa_event_post(ev);
2209 
2210 	return (0);
2211 }
2212 
2213 static int
spa_vdev_remove_top_check(vdev_t * vd)2214 spa_vdev_remove_top_check(vdev_t *vd)
2215 {
2216 	spa_t *spa = vd->vdev_spa;
2217 
2218 	if (vd != vd->vdev_top)
2219 		return (SET_ERROR(ENOTSUP));
2220 
2221 	if (!vdev_is_concrete(vd))
2222 		return (SET_ERROR(ENOTSUP));
2223 
2224 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_DEVICE_REMOVAL))
2225 		return (SET_ERROR(ENOTSUP));
2226 
2227 	/*
2228 	 * This device is already being removed
2229 	 */
2230 	if (vd->vdev_removing)
2231 		return (SET_ERROR(EALREADY));
2232 
2233 	metaslab_class_t *mc = vd->vdev_mg->mg_class;
2234 	metaslab_class_t *normal = spa_normal_class(spa);
2235 	if (mc != normal) {
2236 		/*
2237 		 * Space allocated from the special (or dedup) class is
2238 		 * included in the DMU's space usage, but it's not included
2239 		 * in spa_dspace (or dsl_pool_adjustedsize()).  Therefore
2240 		 * there is always at least as much free space in the normal
2241 		 * class, as is allocated from the special (and dedup) class.
2242 		 * As a backup check, we will return ENOSPC if this is
2243 		 * violated. See also spa_update_dspace().
2244 		 */
2245 		uint64_t available = metaslab_class_get_space(normal) -
2246 		    metaslab_class_get_alloc(normal);
2247 		ASSERT3U(available, >=, vd->vdev_stat.vs_alloc);
2248 		if (available < vd->vdev_stat.vs_alloc)
2249 			return (SET_ERROR(ENOSPC));
2250 	} else if (!vd->vdev_noalloc) {
2251 		/* available space in the pool's normal class */
2252 		uint64_t available = dsl_dir_space_available(
2253 		    spa->spa_dsl_pool->dp_root_dir, NULL, 0, B_TRUE);
2254 		if (available < vd->vdev_stat.vs_dspace)
2255 			return (SET_ERROR(ENOSPC));
2256 	}
2257 
2258 	/*
2259 	 * There can not be a removal in progress.
2260 	 */
2261 	if (spa->spa_removing_phys.sr_state == DSS_SCANNING)
2262 		return (SET_ERROR(EBUSY));
2263 
2264 	/*
2265 	 * The device must have all its data.
2266 	 */
2267 	if (!vdev_dtl_empty(vd, DTL_MISSING) ||
2268 	    !vdev_dtl_empty(vd, DTL_OUTAGE))
2269 		return (SET_ERROR(EBUSY));
2270 
2271 	/*
2272 	 * The device must be healthy.
2273 	 */
2274 	if (!vdev_readable(vd))
2275 		return (SET_ERROR(EIO));
2276 
2277 	/*
2278 	 * All vdevs in normal class must have the same ashift.
2279 	 */
2280 	if (spa->spa_max_ashift != spa->spa_min_ashift) {
2281 		return (SET_ERROR(EINVAL));
2282 	}
2283 
2284 	/*
2285 	 * A removed special/dedup vdev must have same ashift as normal class.
2286 	 */
2287 	ASSERT(!vd->vdev_islog);
2288 	if (vd->vdev_alloc_bias != VDEV_BIAS_NONE &&
2289 	    vd->vdev_ashift != spa->spa_max_ashift) {
2290 		return (SET_ERROR(EINVAL));
2291 	}
2292 
2293 	/*
2294 	 * All vdevs in normal class must have the same ashift
2295 	 * and not be raidz or draid.
2296 	 */
2297 	vdev_t *rvd = spa->spa_root_vdev;
2298 	for (uint64_t id = 0; id < rvd->vdev_children; id++) {
2299 		vdev_t *cvd = rvd->vdev_child[id];
2300 
2301 		/*
2302 		 * A removed special/dedup vdev must have the same ashift
2303 		 * across all vdevs in its class.
2304 		 */
2305 		if (vd->vdev_alloc_bias != VDEV_BIAS_NONE &&
2306 		    cvd->vdev_alloc_bias == vd->vdev_alloc_bias &&
2307 		    cvd->vdev_ashift != vd->vdev_ashift) {
2308 			return (SET_ERROR(EINVAL));
2309 		}
2310 		if (cvd->vdev_ashift != 0 &&
2311 		    cvd->vdev_alloc_bias == VDEV_BIAS_NONE)
2312 			ASSERT3U(cvd->vdev_ashift, ==, spa->spa_max_ashift);
2313 		if (!vdev_is_concrete(cvd))
2314 			continue;
2315 		if (vdev_get_nparity(cvd) != 0)
2316 			return (SET_ERROR(EINVAL));
2317 		/*
2318 		 * Need the mirror to be mirror of leaf vdevs only
2319 		 */
2320 		if (cvd->vdev_ops == &vdev_mirror_ops) {
2321 			for (uint64_t cid = 0;
2322 			    cid < cvd->vdev_children; cid++) {
2323 				if (!cvd->vdev_child[cid]->vdev_ops->
2324 				    vdev_op_leaf)
2325 					return (SET_ERROR(EINVAL));
2326 			}
2327 		}
2328 	}
2329 
2330 	return (0);
2331 }
2332 
2333 /*
2334  * Initiate removal of a top-level vdev, reducing the total space in the pool.
2335  * The config lock is held for the specified TXG.  Once initiated,
2336  * evacuation of all allocated space (copying it to other vdevs) happens
2337  * in the background (see spa_vdev_remove_thread()), and can be canceled
2338  * (see spa_vdev_remove_cancel()).  If successful, the vdev will
2339  * be transformed to an indirect vdev (see spa_vdev_remove_complete()).
2340  */
2341 static int
spa_vdev_remove_top(vdev_t * vd,uint64_t * txg)2342 spa_vdev_remove_top(vdev_t *vd, uint64_t *txg)
2343 {
2344 	spa_t *spa = vd->vdev_spa;
2345 	boolean_t set_noalloc = B_FALSE;
2346 	int error;
2347 
2348 	/*
2349 	 * Check for errors up-front, so that we don't waste time
2350 	 * passivating the metaslab group and clearing the ZIL if there
2351 	 * are errors.
2352 	 */
2353 	error = spa_vdev_remove_top_check(vd);
2354 
2355 	/*
2356 	 * Stop allocating from this vdev.  Note that we must check
2357 	 * that this is not the only device in the pool before
2358 	 * passivating, otherwise we will not be able to make
2359 	 * progress because we can't allocate from any vdevs.
2360 	 * The above check for sufficient free space serves this
2361 	 * purpose.
2362 	 */
2363 	if (error == 0 && !vd->vdev_noalloc) {
2364 		set_noalloc = B_TRUE;
2365 		error = vdev_passivate(vd, txg);
2366 	}
2367 
2368 	if (error != 0)
2369 		return (error);
2370 
2371 	/*
2372 	 * We stop any initializing and TRIM that is currently in progress
2373 	 * but leave the state as "active". This will allow the process to
2374 	 * resume if the removal is canceled sometime later.
2375 	 */
2376 
2377 	spa_vdev_config_exit(spa, NULL, *txg, 0, FTAG);
2378 
2379 	vdev_initialize_stop_all(vd, VDEV_INITIALIZE_ACTIVE);
2380 	vdev_trim_stop_all(vd, VDEV_TRIM_ACTIVE);
2381 	vdev_autotrim_stop_wait(vd);
2382 
2383 	*txg = spa_vdev_config_enter(spa);
2384 
2385 	/*
2386 	 * Things might have changed while the config lock was dropped
2387 	 * (e.g. space usage).  Check for errors again.
2388 	 */
2389 	error = spa_vdev_remove_top_check(vd);
2390 
2391 	if (error != 0) {
2392 		if (set_noalloc)
2393 			vdev_activate(vd);
2394 		spa_async_request(spa, SPA_ASYNC_INITIALIZE_RESTART);
2395 		spa_async_request(spa, SPA_ASYNC_TRIM_RESTART);
2396 		spa_async_request(spa, SPA_ASYNC_AUTOTRIM_RESTART);
2397 		return (error);
2398 	}
2399 
2400 	vd->vdev_removing = B_TRUE;
2401 
2402 	vdev_dirty_leaves(vd, VDD_DTL, *txg);
2403 	vdev_config_dirty(vd);
2404 	dmu_tx_t *tx = dmu_tx_create_assigned(spa->spa_dsl_pool, *txg);
2405 	dsl_sync_task_nowait(spa->spa_dsl_pool,
2406 	    vdev_remove_initiate_sync, (void *)(uintptr_t)vd->vdev_id, tx);
2407 	dmu_tx_commit(tx);
2408 
2409 	return (0);
2410 }
2411 
2412 /*
2413  * Remove a device from the pool.
2414  *
2415  * Removing a device from the vdev namespace requires several steps
2416  * and can take a significant amount of time.  As a result we use
2417  * the spa_vdev_config_[enter/exit] functions which allow us to
2418  * grab and release the spa_config_lock while still holding the namespace
2419  * lock.  During each step the configuration is synced out.
2420  */
2421 int
spa_vdev_remove(spa_t * spa,uint64_t guid,boolean_t unspare)2422 spa_vdev_remove(spa_t *spa, uint64_t guid, boolean_t unspare)
2423 {
2424 	vdev_t *vd;
2425 	nvlist_t **spares, **l2cache, *nv;
2426 	uint64_t txg = 0;
2427 	uint_t nspares, nl2cache;
2428 	int error = 0, error_log;
2429 	boolean_t locked = spa_namespace_held();
2430 	sysevent_t *ev = NULL;
2431 	const char *vd_type = NULL;
2432 	char *vd_path = NULL;
2433 
2434 	ASSERT(spa_writeable(spa));
2435 
2436 	if (!locked)
2437 		txg = spa_vdev_enter(spa);
2438 
2439 	ASSERT(spa_namespace_held());
2440 	if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
2441 		error = (spa_has_checkpoint(spa)) ?
2442 		    ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
2443 
2444 		if (!locked)
2445 			return (spa_vdev_exit(spa, NULL, txg, error));
2446 
2447 		return (error);
2448 	}
2449 
2450 	vd = spa_lookup_by_guid(spa, guid, B_FALSE);
2451 
2452 	if (spa->spa_spares.sav_vdevs != NULL &&
2453 	    nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
2454 	    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0 &&
2455 	    (nv = spa_nvlist_lookup_by_guid(spares, nspares, guid)) != NULL) {
2456 		/*
2457 		 * Only remove the hot spare if it's not currently in use
2458 		 * in this pool.
2459 		 */
2460 		if (vd == NULL || unspare) {
2461 			const char *type;
2462 			boolean_t draid_spare = B_FALSE;
2463 
2464 			if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type)
2465 			    == 0 && strcmp(type, VDEV_TYPE_DRAID_SPARE) == 0)
2466 				draid_spare = B_TRUE;
2467 
2468 			if (vd == NULL && draid_spare) {
2469 				error = SET_ERROR(ENOTSUP);
2470 			} else {
2471 				if (vd == NULL)
2472 					vd = spa_lookup_by_guid(spa,
2473 					    guid, B_TRUE);
2474 				ev = spa_event_create(spa, vd, NULL,
2475 				    ESC_ZFS_VDEV_REMOVE_AUX);
2476 
2477 				vd_type = VDEV_TYPE_SPARE;
2478 				vd_path = spa_strdup(fnvlist_lookup_string(
2479 				    nv, ZPOOL_CONFIG_PATH));
2480 				spa_vdev_remove_aux(spa->spa_spares.sav_config,
2481 				    ZPOOL_CONFIG_SPARES, spares, nspares, nv);
2482 				spa_load_spares(spa);
2483 				spa->spa_spares.sav_sync = B_TRUE;
2484 			}
2485 		} else {
2486 			error = SET_ERROR(EBUSY);
2487 		}
2488 	} else if (spa->spa_l2cache.sav_vdevs != NULL &&
2489 	    nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
2490 	    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0 &&
2491 	    (nv = spa_nvlist_lookup_by_guid(l2cache, nl2cache, guid)) != NULL) {
2492 		vd_type = VDEV_TYPE_L2CACHE;
2493 		vd_path = spa_strdup(fnvlist_lookup_string(
2494 		    nv, ZPOOL_CONFIG_PATH));
2495 		/*
2496 		 * Cache devices can always be removed.
2497 		 */
2498 		vd = spa_lookup_by_guid(spa, guid, B_TRUE);
2499 
2500 		/*
2501 		 * Stop trimming the cache device. We need to release the
2502 		 * config lock to allow the syncing of TRIM transactions
2503 		 * without releasing the spa_namespace_lock. The same
2504 		 * strategy is employed in spa_vdev_remove_top().
2505 		 */
2506 		spa_vdev_config_exit(spa, NULL,
2507 		    txg + TXG_CONCURRENT_STATES + TXG_DEFER_SIZE, 0, FTAG);
2508 		mutex_enter(&vd->vdev_trim_lock);
2509 		vdev_trim_stop(vd, VDEV_TRIM_CANCELED, NULL);
2510 		mutex_exit(&vd->vdev_trim_lock);
2511 		txg = spa_vdev_config_enter(spa);
2512 
2513 		ev = spa_event_create(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE_AUX);
2514 		spa_vdev_remove_aux(spa->spa_l2cache.sav_config,
2515 		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache, nv);
2516 		spa_load_l2cache(spa);
2517 		spa->spa_l2cache.sav_sync = B_TRUE;
2518 	} else if (vd != NULL && vd->vdev_islog) {
2519 		ASSERT(!locked);
2520 		vd_type = VDEV_TYPE_LOG;
2521 		vd_path = spa_strdup((vd->vdev_path != NULL) ?
2522 		    vd->vdev_path : "-");
2523 		error = spa_vdev_remove_log(vd, &txg);
2524 	} else if (vd != NULL) {
2525 		ASSERT(!locked);
2526 		error = spa_vdev_remove_top(vd, &txg);
2527 	} else {
2528 		/*
2529 		 * There is no vdev of any kind with the specified guid.
2530 		 */
2531 		error = SET_ERROR(ENOENT);
2532 	}
2533 
2534 	error_log = error;
2535 
2536 	if (!locked)
2537 		error = spa_vdev_exit(spa, NULL, txg, error);
2538 
2539 	/*
2540 	 * Logging must be done outside the spa config lock. Otherwise,
2541 	 * this code path could end up holding the spa config lock while
2542 	 * waiting for a txg_sync so it can write to the internal log.
2543 	 * Doing that would prevent the txg sync from actually happening,
2544 	 * causing a deadlock.
2545 	 */
2546 	if (error_log == 0 && vd_type != NULL && vd_path != NULL) {
2547 		spa_history_log_internal(spa, "vdev remove", NULL,
2548 		    "%s vdev (%s) %s", spa_name(spa), vd_type, vd_path);
2549 	}
2550 	if (vd_path != NULL)
2551 		spa_strfree(vd_path);
2552 
2553 	if (ev != NULL)
2554 		spa_event_post(ev);
2555 
2556 	return (error);
2557 }
2558 
2559 int
spa_removal_get_stats(spa_t * spa,pool_removal_stat_t * prs)2560 spa_removal_get_stats(spa_t *spa, pool_removal_stat_t *prs)
2561 {
2562 	prs->prs_state = spa->spa_removing_phys.sr_state;
2563 
2564 	if (prs->prs_state == DSS_NONE)
2565 		return (SET_ERROR(ENOENT));
2566 
2567 	prs->prs_removing_vdev = spa->spa_removing_phys.sr_removing_vdev;
2568 	prs->prs_start_time = spa->spa_removing_phys.sr_start_time;
2569 	prs->prs_end_time = spa->spa_removing_phys.sr_end_time;
2570 	prs->prs_to_copy = spa->spa_removing_phys.sr_to_copy;
2571 	prs->prs_copied = spa->spa_removing_phys.sr_copied;
2572 
2573 	prs->prs_mapping_memory = 0;
2574 	uint64_t indirect_vdev_id =
2575 	    spa->spa_removing_phys.sr_prev_indirect_vdev;
2576 	while (indirect_vdev_id != -1) {
2577 		vdev_t *vd = spa->spa_root_vdev->vdev_child[indirect_vdev_id];
2578 		vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
2579 		vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
2580 
2581 		ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
2582 		prs->prs_mapping_memory += vdev_indirect_mapping_size(vim);
2583 		indirect_vdev_id = vic->vic_prev_indirect_vdev;
2584 	}
2585 
2586 	return (0);
2587 }
2588 
2589 ZFS_MODULE_PARAM(zfs_vdev, zfs_, removal_ignore_errors, INT, ZMOD_RW,
2590 	"Ignore hard IO errors when removing device");
2591 
2592 ZFS_MODULE_PARAM(zfs_vdev, zfs_, remove_max_segment, UINT, ZMOD_RW,
2593 	"Largest contiguous segment to allocate when removing device");
2594 
2595 ZFS_MODULE_PARAM(zfs_vdev, vdev_, removal_max_span, UINT, ZMOD_RW,
2596 	"Largest span of free chunks a remap segment can span");
2597 
2598 ZFS_MODULE_PARAM(zfs_vdev, zfs_, removal_suspend_progress, UINT, ZMOD_RW,
2599 	"Pause device removal after this many bytes are copied "
2600 	"(debug use only - causes removal to hang)");
2601 
2602 EXPORT_SYMBOL(free_from_removing_vdev);
2603 EXPORT_SYMBOL(spa_removal_get_stats);
2604 EXPORT_SYMBOL(spa_remove_init);
2605 EXPORT_SYMBOL(spa_restart_removal);
2606 EXPORT_SYMBOL(spa_vdev_removal_destroy);
2607 EXPORT_SYMBOL(spa_vdev_remove);
2608 EXPORT_SYMBOL(spa_vdev_remove_cancel);
2609 EXPORT_SYMBOL(spa_vdev_remove_suspend);
2610 EXPORT_SYMBOL(svr_sync);
2611