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