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