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