1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
25  */
26 
27 #include <sys/zfs_context.h>
28 #include <sys/spa_impl.h>
29 #include <sys/dmu.h>
30 #include <sys/dmu_tx.h>
31 #include <sys/zap.h>
32 #include <sys/vdev_impl.h>
33 #include <sys/metaslab.h>
34 #include <sys/metaslab_impl.h>
35 #include <sys/uberblock_impl.h>
36 #include <sys/txg.h>
37 #include <sys/avl.h>
38 #include <sys/bpobj.h>
39 #include <sys/dsl_pool.h>
40 #include <sys/dsl_synctask.h>
41 #include <sys/dsl_dir.h>
42 #include <sys/arc.h>
43 #include <sys/zfeature.h>
44 #include <sys/vdev_indirect_births.h>
45 #include <sys/vdev_indirect_mapping.h>
46 #include <sys/abd.h>
47 
48 /*
49  * This file contains the necessary logic to remove vdevs from a
50  * storage pool.  Currently, the only devices that can be removed
51  * are log, cache, and spare devices; and top level vdevs from a pool
52  * w/o raidz.  (Note that members of a mirror can also be removed
53  * by the detach operation.)
54  *
55  * Log vdevs are removed by evacuating them and then turning the vdev
56  * into a hole vdev while holding spa config locks.
57  *
58  * Top level vdevs are removed and converted into an indirect vdev via
59  * a multi-step process:
60  *
61  *  - Disable allocations from this device (spa_vdev_remove_top).
62  *
63  *  - From a new thread (spa_vdev_remove_thread), copy data from
64  *    the removing vdev to a different vdev.  The copy happens in open
65  *    context (spa_vdev_copy_impl) and issues a sync task
66  *    (vdev_mapping_sync) so the sync thread can update the partial
67  *    indirect mappings in core and on disk.
68  *
69  *  - If a free happens during a removal, it is freed from the
70  *    removing vdev, and if it has already been copied, from the new
71  *    location as well (free_from_removing_vdev).
72  *
73  *  - After the removal is completed, the copy thread converts the vdev
74  *    into an indirect vdev (vdev_remove_complete) before instructing
75  *    the sync thread to destroy the space maps and finish the removal
76  *    (spa_finish_removal).
77  */
78 
79 typedef struct vdev_copy_arg {
80 	metaslab_t	*vca_msp;
81 	uint64_t	vca_outstanding_bytes;
82 	kcondvar_t	vca_cv;
83 	kmutex_t	vca_lock;
84 } vdev_copy_arg_t;
85 
86 /*
87  * The maximum amount of memory we can use for outstanding i/o while
88  * doing a device removal.  This determines how much i/o we can have
89  * in flight concurrently.
90  */
91 int zfs_remove_max_copy_bytes = 64 * 1024 * 1024;
92 
93 /*
94  * The largest contiguous segment that we will attempt to allocate when
95  * removing a device.  This can be no larger than SPA_MAXBLOCKSIZE.  If
96  * there is a performance problem with attempting to allocate large blocks,
97  * consider decreasing this.
98  *
99  * Note: we will issue I/Os of up to this size.  The mpt driver does not
100  * respond well to I/Os larger than 1MB, so we set this to 1MB.  (When
101  * mpt processes an I/O larger than 1MB, it needs to do an allocation of
102  * 2 physically contiguous pages; if this allocation fails, mpt will drop
103  * the I/O and hang the device.)
104  */
105 int zfs_remove_max_segment = 1024 * 1024;
106 
107 /*
108  * This is used by the test suite so that it can ensure that certain
109  * actions happen while in the middle of a removal.
110  */
111 uint64_t zfs_remove_max_bytes_pause = UINT64_MAX;
112 
113 #define	VDEV_REMOVAL_ZAP_OBJS	"lzap"
114 
115 static void spa_vdev_remove_thread(void *arg);
116 
117 static void
118 spa_sync_removing_state(spa_t *spa, dmu_tx_t *tx)
119 {
120 	VERIFY0(zap_update(spa->spa_dsl_pool->dp_meta_objset,
121 	    DMU_POOL_DIRECTORY_OBJECT,
122 	    DMU_POOL_REMOVING, sizeof (uint64_t),
123 	    sizeof (spa->spa_removing_phys) / sizeof (uint64_t),
124 	    &spa->spa_removing_phys, tx));
125 }
126 
127 static nvlist_t *
128 spa_nvlist_lookup_by_guid(nvlist_t **nvpp, int count, uint64_t target_guid)
129 {
130 	for (int i = 0; i < count; i++) {
131 		uint64_t guid =
132 		    fnvlist_lookup_uint64(nvpp[i], ZPOOL_CONFIG_GUID);
133 
134 		if (guid == target_guid)
135 			return (nvpp[i]);
136 	}
137 
138 	return (NULL);
139 }
140 
141 static void
142 spa_vdev_remove_aux(nvlist_t *config, char *name, nvlist_t **dev, int count,
143     nvlist_t *dev_to_remove)
144 {
145 	nvlist_t **newdev = NULL;
146 
147 	if (count > 1)
148 		newdev = kmem_alloc((count - 1) * sizeof (void *), KM_SLEEP);
149 
150 	for (int i = 0, j = 0; i < count; i++) {
151 		if (dev[i] == dev_to_remove)
152 			continue;
153 		VERIFY(nvlist_dup(dev[i], &newdev[j++], KM_SLEEP) == 0);
154 	}
155 
156 	VERIFY(nvlist_remove(config, name, DATA_TYPE_NVLIST_ARRAY) == 0);
157 	VERIFY(nvlist_add_nvlist_array(config, name, newdev, count - 1) == 0);
158 
159 	for (int i = 0; i < count - 1; i++)
160 		nvlist_free(newdev[i]);
161 
162 	if (count > 1)
163 		kmem_free(newdev, (count - 1) * sizeof (void *));
164 }
165 
166 static spa_vdev_removal_t *
167 spa_vdev_removal_create(vdev_t *vd)
168 {
169 	spa_vdev_removal_t *svr = kmem_zalloc(sizeof (*svr), KM_SLEEP);
170 	mutex_init(&svr->svr_lock, NULL, MUTEX_DEFAULT, NULL);
171 	cv_init(&svr->svr_cv, NULL, CV_DEFAULT, NULL);
172 	svr->svr_allocd_segs = range_tree_create(NULL, NULL);
173 	svr->svr_vdev_id = vd->vdev_id;
174 
175 	for (int i = 0; i < TXG_SIZE; i++) {
176 		svr->svr_frees[i] = range_tree_create(NULL, NULL);
177 		list_create(&svr->svr_new_segments[i],
178 		    sizeof (vdev_indirect_mapping_entry_t),
179 		    offsetof(vdev_indirect_mapping_entry_t, vime_node));
180 	}
181 
182 	return (svr);
183 }
184 
185 void
186 spa_vdev_removal_destroy(spa_vdev_removal_t *svr)
187 {
188 	for (int i = 0; i < TXG_SIZE; i++) {
189 		ASSERT0(svr->svr_bytes_done[i]);
190 		ASSERT0(svr->svr_max_offset_to_sync[i]);
191 		range_tree_destroy(svr->svr_frees[i]);
192 		list_destroy(&svr->svr_new_segments[i]);
193 	}
194 
195 	range_tree_destroy(svr->svr_allocd_segs);
196 	mutex_destroy(&svr->svr_lock);
197 	cv_destroy(&svr->svr_cv);
198 	kmem_free(svr, sizeof (*svr));
199 }
200 
201 /*
202  * This is called as a synctask in the txg in which we will mark this vdev
203  * as removing (in the config stored in the MOS).
204  *
205  * It begins the evacuation of a toplevel vdev by:
206  * - initializing the spa_removing_phys which tracks this removal
207  * - computing the amount of space to remove for accounting purposes
208  * - dirtying all dbufs in the spa_config_object
209  * - creating the spa_vdev_removal
210  * - starting the spa_vdev_remove_thread
211  */
212 static void
213 vdev_remove_initiate_sync(void *arg, dmu_tx_t *tx)
214 {
215 	int vdev_id = (uintptr_t)arg;
216 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
217 	vdev_t *vd = vdev_lookup_top(spa, vdev_id);
218 	vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
219 	objset_t *mos = spa->spa_dsl_pool->dp_meta_objset;
220 	spa_vdev_removal_t *svr = NULL;
221 	uint64_t txg = dmu_tx_get_txg(tx);
222 
223 	ASSERT3P(vd->vdev_ops, !=, &vdev_raidz_ops);
224 	svr = spa_vdev_removal_create(vd);
225 
226 	ASSERT(vd->vdev_removing);
227 	ASSERT3P(vd->vdev_indirect_mapping, ==, NULL);
228 
229 	spa_feature_incr(spa, SPA_FEATURE_DEVICE_REMOVAL, tx);
230 	if (spa_feature_is_enabled(spa, SPA_FEATURE_OBSOLETE_COUNTS)) {
231 		/*
232 		 * By activating the OBSOLETE_COUNTS feature, we prevent
233 		 * the pool from being downgraded and ensure that the
234 		 * refcounts are precise.
235 		 */
236 		spa_feature_incr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
237 		uint64_t one = 1;
238 		VERIFY0(zap_add(spa->spa_meta_objset, vd->vdev_top_zap,
239 		    VDEV_TOP_ZAP_OBSOLETE_COUNTS_ARE_PRECISE, sizeof (one), 1,
240 		    &one, tx));
241 		ASSERT3U(vdev_obsolete_counts_are_precise(vd), !=, 0);
242 	}
243 
244 	vic->vic_mapping_object = vdev_indirect_mapping_alloc(mos, tx);
245 	vd->vdev_indirect_mapping =
246 	    vdev_indirect_mapping_open(mos, vic->vic_mapping_object);
247 	vic->vic_births_object = vdev_indirect_births_alloc(mos, tx);
248 	vd->vdev_indirect_births =
249 	    vdev_indirect_births_open(mos, vic->vic_births_object);
250 	spa->spa_removing_phys.sr_removing_vdev = vd->vdev_id;
251 	spa->spa_removing_phys.sr_start_time = gethrestime_sec();
252 	spa->spa_removing_phys.sr_end_time = 0;
253 	spa->spa_removing_phys.sr_state = DSS_SCANNING;
254 	spa->spa_removing_phys.sr_to_copy = 0;
255 	spa->spa_removing_phys.sr_copied = 0;
256 
257 	/*
258 	 * Note: We can't use vdev_stat's vs_alloc for sr_to_copy, because
259 	 * there may be space in the defer tree, which is free, but still
260 	 * counted in vs_alloc.
261 	 */
262 	for (uint64_t i = 0; i < vd->vdev_ms_count; i++) {
263 		metaslab_t *ms = vd->vdev_ms[i];
264 		if (ms->ms_sm == NULL)
265 			continue;
266 
267 		/*
268 		 * Sync tasks happen before metaslab_sync(), therefore
269 		 * smp_alloc and sm_alloc must be the same.
270 		 */
271 		ASSERT3U(space_map_allocated(ms->ms_sm), ==,
272 		    ms->ms_sm->sm_phys->smp_alloc);
273 
274 		spa->spa_removing_phys.sr_to_copy +=
275 		    space_map_allocated(ms->ms_sm);
276 
277 		/*
278 		 * Space which we are freeing this txg does not need to
279 		 * be copied.
280 		 */
281 		spa->spa_removing_phys.sr_to_copy -=
282 		    range_tree_space(ms->ms_freeing);
283 
284 		ASSERT0(range_tree_space(ms->ms_freed));
285 		for (int t = 0; t < TXG_SIZE; t++)
286 			ASSERT0(range_tree_space(ms->ms_allocating[t]));
287 	}
288 
289 	/*
290 	 * Sync tasks are called before metaslab_sync(), so there should
291 	 * be no already-synced metaslabs in the TXG_CLEAN list.
292 	 */
293 	ASSERT3P(txg_list_head(&vd->vdev_ms_list, TXG_CLEAN(txg)), ==, NULL);
294 
295 	spa_sync_removing_state(spa, tx);
296 
297 	/*
298 	 * All blocks that we need to read the most recent mapping must be
299 	 * stored on concrete vdevs.  Therefore, we must dirty anything that
300 	 * is read before spa_remove_init().  Specifically, the
301 	 * spa_config_object.  (Note that although we already modified the
302 	 * spa_config_object in spa_sync_removing_state, that may not have
303 	 * modified all blocks of the object.)
304 	 */
305 	dmu_object_info_t doi;
306 	VERIFY0(dmu_object_info(mos, DMU_POOL_DIRECTORY_OBJECT, &doi));
307 	for (uint64_t offset = 0; offset < doi.doi_max_offset; ) {
308 		dmu_buf_t *dbuf;
309 		VERIFY0(dmu_buf_hold(mos, DMU_POOL_DIRECTORY_OBJECT,
310 		    offset, FTAG, &dbuf, 0));
311 		dmu_buf_will_dirty(dbuf, tx);
312 		offset += dbuf->db_size;
313 		dmu_buf_rele(dbuf, FTAG);
314 	}
315 
316 	/*
317 	 * Now that we've allocated the im_object, dirty the vdev to ensure
318 	 * that the object gets written to the config on disk.
319 	 */
320 	vdev_config_dirty(vd);
321 
322 	zfs_dbgmsg("starting removal thread for vdev %llu (%p) in txg %llu "
323 	    "im_obj=%llu", vd->vdev_id, vd, dmu_tx_get_txg(tx),
324 	    vic->vic_mapping_object);
325 
326 	spa_history_log_internal(spa, "vdev remove started", tx,
327 	    "%s vdev %llu %s", spa_name(spa), vd->vdev_id,
328 	    (vd->vdev_path != NULL) ? vd->vdev_path : "-");
329 	/*
330 	 * Setting spa_vdev_removal causes subsequent frees to call
331 	 * free_from_removing_vdev().  Note that we don't need any locking
332 	 * because we are the sync thread, and metaslab_free_impl() is only
333 	 * called from syncing context (potentially from a zio taskq thread,
334 	 * but in any case only when there are outstanding free i/os, which
335 	 * there are not).
336 	 */
337 	ASSERT3P(spa->spa_vdev_removal, ==, NULL);
338 	spa->spa_vdev_removal = svr;
339 	svr->svr_thread = thread_create(NULL, 0,
340 	    spa_vdev_remove_thread, spa, 0, &p0, TS_RUN, minclsyspri);
341 }
342 
343 /*
344  * When we are opening a pool, we must read the mapping for each
345  * indirect vdev in order from most recently removed to least
346  * recently removed.  We do this because the blocks for the mapping
347  * of older indirect vdevs may be stored on more recently removed vdevs.
348  * In order to read each indirect mapping object, we must have
349  * initialized all more recently removed vdevs.
350  */
351 int
352 spa_remove_init(spa_t *spa)
353 {
354 	int error;
355 
356 	error = zap_lookup(spa->spa_dsl_pool->dp_meta_objset,
357 	    DMU_POOL_DIRECTORY_OBJECT,
358 	    DMU_POOL_REMOVING, sizeof (uint64_t),
359 	    sizeof (spa->spa_removing_phys) / sizeof (uint64_t),
360 	    &spa->spa_removing_phys);
361 
362 	if (error == ENOENT) {
363 		spa->spa_removing_phys.sr_state = DSS_NONE;
364 		spa->spa_removing_phys.sr_removing_vdev = -1;
365 		spa->spa_removing_phys.sr_prev_indirect_vdev = -1;
366 		return (0);
367 	} else if (error != 0) {
368 		return (error);
369 	}
370 
371 	if (spa->spa_removing_phys.sr_state == DSS_SCANNING) {
372 		/*
373 		 * We are currently removing a vdev.  Create and
374 		 * initialize a spa_vdev_removal_t from the bonus
375 		 * buffer of the removing vdevs vdev_im_object, and
376 		 * initialize its partial mapping.
377 		 */
378 		spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
379 		vdev_t *vd = vdev_lookup_top(spa,
380 		    spa->spa_removing_phys.sr_removing_vdev);
381 
382 		if (vd == NULL) {
383 			spa_config_exit(spa, SCL_STATE, FTAG);
384 			return (EINVAL);
385 		}
386 
387 		vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
388 
389 		ASSERT(vdev_is_concrete(vd));
390 		spa_vdev_removal_t *svr = spa_vdev_removal_create(vd);
391 		ASSERT3U(svr->svr_vdev_id, ==, vd->vdev_id);
392 		ASSERT(vd->vdev_removing);
393 
394 		vd->vdev_indirect_mapping = vdev_indirect_mapping_open(
395 		    spa->spa_meta_objset, vic->vic_mapping_object);
396 		vd->vdev_indirect_births = vdev_indirect_births_open(
397 		    spa->spa_meta_objset, vic->vic_births_object);
398 		spa_config_exit(spa, SCL_STATE, FTAG);
399 
400 		spa->spa_vdev_removal = svr;
401 	}
402 
403 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
404 	uint64_t indirect_vdev_id =
405 	    spa->spa_removing_phys.sr_prev_indirect_vdev;
406 	while (indirect_vdev_id != UINT64_MAX) {
407 		vdev_t *vd = vdev_lookup_top(spa, indirect_vdev_id);
408 		vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
409 
410 		ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
411 		vd->vdev_indirect_mapping = vdev_indirect_mapping_open(
412 		    spa->spa_meta_objset, vic->vic_mapping_object);
413 		vd->vdev_indirect_births = vdev_indirect_births_open(
414 		    spa->spa_meta_objset, vic->vic_births_object);
415 
416 		indirect_vdev_id = vic->vic_prev_indirect_vdev;
417 	}
418 	spa_config_exit(spa, SCL_STATE, FTAG);
419 
420 	/*
421 	 * Now that we've loaded all the indirect mappings, we can allow
422 	 * reads from other blocks (e.g. via predictive prefetch).
423 	 */
424 	spa->spa_indirect_vdevs_loaded = B_TRUE;
425 	return (0);
426 }
427 
428 void
429 spa_restart_removal(spa_t *spa)
430 {
431 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
432 
433 	if (svr == NULL)
434 		return;
435 
436 	/*
437 	 * In general when this function is called there is no
438 	 * removal thread running. The only scenario where this
439 	 * is not true is during spa_import() where this function
440 	 * is called twice [once from spa_import_impl() and
441 	 * spa_async_resume()]. Thus, in the scenario where we
442 	 * import a pool that has an ongoing removal we don't
443 	 * want to spawn a second thread.
444 	 */
445 	if (svr->svr_thread != NULL)
446 		return;
447 
448 	if (!spa_writeable(spa))
449 		return;
450 
451 	zfs_dbgmsg("restarting removal of %llu", svr->svr_vdev_id);
452 	svr->svr_thread = thread_create(NULL, 0, spa_vdev_remove_thread, spa,
453 	    0, &p0, TS_RUN, minclsyspri);
454 }
455 
456 /*
457  * Process freeing from a device which is in the middle of being removed.
458  * We must handle this carefully so that we attempt to copy freed data,
459  * and we correctly free already-copied data.
460  */
461 void
462 free_from_removing_vdev(vdev_t *vd, uint64_t offset, uint64_t size)
463 {
464 	spa_t *spa = vd->vdev_spa;
465 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
466 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
467 	uint64_t txg = spa_syncing_txg(spa);
468 	uint64_t max_offset_yet = 0;
469 
470 	ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
471 	ASSERT3U(vd->vdev_indirect_config.vic_mapping_object, ==,
472 	    vdev_indirect_mapping_object(vim));
473 	ASSERT3U(vd->vdev_id, ==, svr->svr_vdev_id);
474 
475 	mutex_enter(&svr->svr_lock);
476 
477 	/*
478 	 * Remove the segment from the removing vdev's spacemap.  This
479 	 * ensures that we will not attempt to copy this space (if the
480 	 * removal thread has not yet visited it), and also ensures
481 	 * that we know what is actually allocated on the new vdevs
482 	 * (needed if we cancel the removal).
483 	 *
484 	 * Note: we must do the metaslab_free_concrete() with the svr_lock
485 	 * held, so that the remove_thread can not load this metaslab and then
486 	 * visit this offset between the time that we metaslab_free_concrete()
487 	 * and when we check to see if it has been visited.
488 	 *
489 	 * Note: The checkpoint flag is set to false as having/taking
490 	 * a checkpoint and removing a device can't happen at the same
491 	 * time.
492 	 */
493 	ASSERT(!spa_has_checkpoint(spa));
494 	metaslab_free_concrete(vd, offset, size, B_FALSE);
495 
496 	uint64_t synced_size = 0;
497 	uint64_t synced_offset = 0;
498 	uint64_t max_offset_synced = vdev_indirect_mapping_max_offset(vim);
499 	if (offset < max_offset_synced) {
500 		/*
501 		 * The mapping for this offset is already on disk.
502 		 * Free from the new location.
503 		 *
504 		 * Note that we use svr_max_synced_offset because it is
505 		 * updated atomically with respect to the in-core mapping.
506 		 * By contrast, vim_max_offset is not.
507 		 *
508 		 * This block may be split between a synced entry and an
509 		 * in-flight or unvisited entry.  Only process the synced
510 		 * portion of it here.
511 		 */
512 		synced_size = MIN(size, max_offset_synced - offset);
513 		synced_offset = offset;
514 
515 		ASSERT3U(max_offset_yet, <=, max_offset_synced);
516 		max_offset_yet = max_offset_synced;
517 
518 		DTRACE_PROBE3(remove__free__synced,
519 		    spa_t *, spa,
520 		    uint64_t, offset,
521 		    uint64_t, synced_size);
522 
523 		size -= synced_size;
524 		offset += synced_size;
525 	}
526 
527 	/*
528 	 * Look at all in-flight txgs starting from the currently syncing one
529 	 * and see if a section of this free is being copied. By starting from
530 	 * this txg and iterating forward, we might find that this region
531 	 * was copied in two different txgs and handle it appropriately.
532 	 */
533 	for (int i = 0; i < TXG_CONCURRENT_STATES; i++) {
534 		int txgoff = (txg + i) & TXG_MASK;
535 		if (size > 0 && offset < svr->svr_max_offset_to_sync[txgoff]) {
536 			/*
537 			 * The mapping for this offset is in flight, and
538 			 * will be synced in txg+i.
539 			 */
540 			uint64_t inflight_size = MIN(size,
541 			    svr->svr_max_offset_to_sync[txgoff] - offset);
542 
543 			DTRACE_PROBE4(remove__free__inflight,
544 			    spa_t *, spa,
545 			    uint64_t, offset,
546 			    uint64_t, inflight_size,
547 			    uint64_t, txg + i);
548 
549 			/*
550 			 * We copy data in order of increasing offset.
551 			 * Therefore the max_offset_to_sync[] must increase
552 			 * (or be zero, indicating that nothing is being
553 			 * copied in that txg).
554 			 */
555 			if (svr->svr_max_offset_to_sync[txgoff] != 0) {
556 				ASSERT3U(svr->svr_max_offset_to_sync[txgoff],
557 				    >=, max_offset_yet);
558 				max_offset_yet =
559 				    svr->svr_max_offset_to_sync[txgoff];
560 			}
561 
562 			/*
563 			 * We've already committed to copying this segment:
564 			 * we have allocated space elsewhere in the pool for
565 			 * it and have an IO outstanding to copy the data. We
566 			 * cannot free the space before the copy has
567 			 * completed, or else the copy IO might overwrite any
568 			 * new data. To free that space, we record the
569 			 * segment in the appropriate svr_frees tree and free
570 			 * the mapped space later, in the txg where we have
571 			 * completed the copy and synced the mapping (see
572 			 * vdev_mapping_sync).
573 			 */
574 			range_tree_add(svr->svr_frees[txgoff],
575 			    offset, inflight_size);
576 			size -= inflight_size;
577 			offset += inflight_size;
578 
579 			/*
580 			 * This space is already accounted for as being
581 			 * done, because it is being copied in txg+i.
582 			 * However, if i!=0, then it is being copied in
583 			 * a future txg.  If we crash after this txg
584 			 * syncs but before txg+i syncs, then the space
585 			 * will be free.  Therefore we must account
586 			 * for the space being done in *this* txg
587 			 * (when it is freed) rather than the future txg
588 			 * (when it will be copied).
589 			 */
590 			ASSERT3U(svr->svr_bytes_done[txgoff], >=,
591 			    inflight_size);
592 			svr->svr_bytes_done[txgoff] -= inflight_size;
593 			svr->svr_bytes_done[txg & TXG_MASK] += inflight_size;
594 		}
595 	}
596 	ASSERT0(svr->svr_max_offset_to_sync[TXG_CLEAN(txg) & TXG_MASK]);
597 
598 	if (size > 0) {
599 		/*
600 		 * The copy thread has not yet visited this offset.  Ensure
601 		 * that it doesn't.
602 		 */
603 
604 		DTRACE_PROBE3(remove__free__unvisited,
605 		    spa_t *, spa,
606 		    uint64_t, offset,
607 		    uint64_t, size);
608 
609 		if (svr->svr_allocd_segs != NULL)
610 			range_tree_clear(svr->svr_allocd_segs, offset, size);
611 
612 		/*
613 		 * Since we now do not need to copy this data, for
614 		 * accounting purposes we have done our job and can count
615 		 * it as completed.
616 		 */
617 		svr->svr_bytes_done[txg & TXG_MASK] += size;
618 	}
619 	mutex_exit(&svr->svr_lock);
620 
621 	/*
622 	 * Now that we have dropped svr_lock, process the synced portion
623 	 * of this free.
624 	 */
625 	if (synced_size > 0) {
626 		vdev_indirect_mark_obsolete(vd, synced_offset, synced_size);
627 
628 		/*
629 		 * Note: this can only be called from syncing context,
630 		 * and the vdev_indirect_mapping is only changed from the
631 		 * sync thread, so we don't need svr_lock while doing
632 		 * metaslab_free_impl_cb.
633 		 */
634 		boolean_t checkpoint = B_FALSE;
635 		vdev_indirect_ops.vdev_op_remap(vd, synced_offset, synced_size,
636 		    metaslab_free_impl_cb, &checkpoint);
637 	}
638 }
639 
640 /*
641  * Stop an active removal and update the spa_removing phys.
642  */
643 static void
644 spa_finish_removal(spa_t *spa, dsl_scan_state_t state, dmu_tx_t *tx)
645 {
646 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
647 	ASSERT3U(dmu_tx_get_txg(tx), ==, spa_syncing_txg(spa));
648 
649 	/* Ensure the removal thread has completed before we free the svr. */
650 	spa_vdev_remove_suspend(spa);
651 
652 	ASSERT(state == DSS_FINISHED || state == DSS_CANCELED);
653 
654 	if (state == DSS_FINISHED) {
655 		spa_removing_phys_t *srp = &spa->spa_removing_phys;
656 		vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
657 		vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
658 
659 		if (srp->sr_prev_indirect_vdev != UINT64_MAX) {
660 			vdev_t *pvd = vdev_lookup_top(spa,
661 			    srp->sr_prev_indirect_vdev);
662 			ASSERT3P(pvd->vdev_ops, ==, &vdev_indirect_ops);
663 		}
664 
665 		vic->vic_prev_indirect_vdev = srp->sr_prev_indirect_vdev;
666 		srp->sr_prev_indirect_vdev = vd->vdev_id;
667 	}
668 	spa->spa_removing_phys.sr_state = state;
669 	spa->spa_removing_phys.sr_end_time = gethrestime_sec();
670 
671 	spa->spa_vdev_removal = NULL;
672 	spa_vdev_removal_destroy(svr);
673 
674 	spa_sync_removing_state(spa, tx);
675 
676 	vdev_config_dirty(spa->spa_root_vdev);
677 }
678 
679 static void
680 free_mapped_segment_cb(void *arg, uint64_t offset, uint64_t size)
681 {
682 	vdev_t *vd = arg;
683 	vdev_indirect_mark_obsolete(vd, offset, size);
684 	boolean_t checkpoint = B_FALSE;
685 	vdev_indirect_ops.vdev_op_remap(vd, offset, size,
686 	    metaslab_free_impl_cb, &checkpoint);
687 }
688 
689 /*
690  * On behalf of the removal thread, syncs an incremental bit more of
691  * the indirect mapping to disk and updates the in-memory mapping.
692  * Called as a sync task in every txg that the removal thread makes progress.
693  */
694 static void
695 vdev_mapping_sync(void *arg, dmu_tx_t *tx)
696 {
697 	spa_vdev_removal_t *svr = arg;
698 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
699 	vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
700 	vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
701 	uint64_t txg = dmu_tx_get_txg(tx);
702 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
703 
704 	ASSERT(vic->vic_mapping_object != 0);
705 	ASSERT3U(txg, ==, spa_syncing_txg(spa));
706 
707 	vdev_indirect_mapping_add_entries(vim,
708 	    &svr->svr_new_segments[txg & TXG_MASK], tx);
709 	vdev_indirect_births_add_entry(vd->vdev_indirect_births,
710 	    vdev_indirect_mapping_max_offset(vim), dmu_tx_get_txg(tx), tx);
711 
712 	/*
713 	 * Free the copied data for anything that was freed while the
714 	 * mapping entries were in flight.
715 	 */
716 	mutex_enter(&svr->svr_lock);
717 	range_tree_vacate(svr->svr_frees[txg & TXG_MASK],
718 	    free_mapped_segment_cb, vd);
719 	ASSERT3U(svr->svr_max_offset_to_sync[txg & TXG_MASK], >=,
720 	    vdev_indirect_mapping_max_offset(vim));
721 	svr->svr_max_offset_to_sync[txg & TXG_MASK] = 0;
722 	mutex_exit(&svr->svr_lock);
723 
724 	spa_sync_removing_state(spa, tx);
725 }
726 
727 /*
728  * All reads and writes associated with a call to spa_vdev_copy_segment()
729  * are done.
730  */
731 static void
732 spa_vdev_copy_nullzio_done(zio_t *zio)
733 {
734 	spa_config_exit(zio->io_spa, SCL_STATE, zio->io_spa);
735 }
736 
737 /*
738  * The write of the new location is done.
739  */
740 static void
741 spa_vdev_copy_segment_write_done(zio_t *zio)
742 {
743 	vdev_copy_arg_t *vca = zio->io_private;
744 
745 	abd_free(zio->io_abd);
746 
747 	mutex_enter(&vca->vca_lock);
748 	vca->vca_outstanding_bytes -= zio->io_size;
749 	cv_signal(&vca->vca_cv);
750 	mutex_exit(&vca->vca_lock);
751 }
752 
753 /*
754  * The read of the old location is done.  The parent zio is the write to
755  * the new location.  Allow it to start.
756  */
757 static void
758 spa_vdev_copy_segment_read_done(zio_t *zio)
759 {
760 	zio_nowait(zio_unique_parent(zio));
761 }
762 
763 /*
764  * If the old and new vdevs are mirrors, we will read both sides of the old
765  * mirror, and write each copy to the corresponding side of the new mirror.
766  * If the old and new vdevs have a different number of children, we will do
767  * this as best as possible.  Since we aren't verifying checksums, this
768  * ensures that as long as there's a good copy of the data, we'll have a
769  * good copy after the removal, even if there's silent damage to one side
770  * of the mirror. If we're removing a mirror that has some silent damage,
771  * we'll have exactly the same damage in the new location (assuming that
772  * the new location is also a mirror).
773  *
774  * We accomplish this by creating a tree of zio_t's, with as many writes as
775  * there are "children" of the new vdev (a non-redundant vdev counts as one
776  * child, a 2-way mirror has 2 children, etc). Each write has an associated
777  * read from a child of the old vdev. Typically there will be the same
778  * number of children of the old and new vdevs.  However, if there are more
779  * children of the new vdev, some child(ren) of the old vdev will be issued
780  * multiple reads.  If there are more children of the old vdev, some copies
781  * will be dropped.
782  *
783  * For example, the tree of zio_t's for a 2-way mirror is:
784  *
785  *                            null
786  *                           /    \
787  *    write(new vdev, child 0)      write(new vdev, child 1)
788  *      |                             |
789  *    read(old vdev, child 0)       read(old vdev, child 1)
790  *
791  * Child zio's complete before their parents complete.  However, zio's
792  * created with zio_vdev_child_io() may be issued before their children
793  * complete.  In this case we need to make sure that the children (reads)
794  * complete before the parents (writes) are *issued*.  We do this by not
795  * calling zio_nowait() on each write until its corresponding read has
796  * completed.
797  *
798  * The spa_config_lock must be held while zio's created by
799  * zio_vdev_child_io() are in progress, to ensure that the vdev tree does
800  * not change (e.g. due to a concurrent "zpool attach/detach"). The "null"
801  * zio is needed to release the spa_config_lock after all the reads and
802  * writes complete. (Note that we can't grab the config lock for each read,
803  * because it is not reentrant - we could deadlock with a thread waiting
804  * for a write lock.)
805  */
806 static void
807 spa_vdev_copy_one_child(vdev_copy_arg_t *vca, zio_t *nzio,
808     vdev_t *source_vd, uint64_t source_offset,
809     vdev_t *dest_child_vd, uint64_t dest_offset, int dest_id, uint64_t size)
810 {
811 	ASSERT3U(spa_config_held(nzio->io_spa, SCL_ALL, RW_READER), !=, 0);
812 
813 	mutex_enter(&vca->vca_lock);
814 	vca->vca_outstanding_bytes += size;
815 	mutex_exit(&vca->vca_lock);
816 
817 	abd_t *abd = abd_alloc_for_io(size, B_FALSE);
818 
819 	vdev_t *source_child_vd;
820 	if (source_vd->vdev_ops == &vdev_mirror_ops && dest_id != -1) {
821 		/*
822 		 * Source and dest are both mirrors.  Copy from the same
823 		 * child id as we are copying to (wrapping around if there
824 		 * are more dest children than source children).
825 		 */
826 		source_child_vd =
827 		    source_vd->vdev_child[dest_id % source_vd->vdev_children];
828 	} else {
829 		source_child_vd = source_vd;
830 	}
831 
832 	zio_t *write_zio = zio_vdev_child_io(nzio, NULL,
833 	    dest_child_vd, dest_offset, abd, size,
834 	    ZIO_TYPE_WRITE, ZIO_PRIORITY_REMOVAL,
835 	    ZIO_FLAG_CANFAIL,
836 	    spa_vdev_copy_segment_write_done, vca);
837 
838 	zio_nowait(zio_vdev_child_io(write_zio, NULL,
839 	    source_child_vd, source_offset, abd, size,
840 	    ZIO_TYPE_READ, ZIO_PRIORITY_REMOVAL,
841 	    ZIO_FLAG_CANFAIL,
842 	    spa_vdev_copy_segment_read_done, vca));
843 }
844 
845 /*
846  * Allocate a new location for this segment, and create the zio_t's to
847  * read from the old location and write to the new location.
848  */
849 static int
850 spa_vdev_copy_segment(vdev_t *vd, uint64_t start, uint64_t size, uint64_t txg,
851     vdev_copy_arg_t *vca, zio_alloc_list_t *zal)
852 {
853 	metaslab_group_t *mg = vd->vdev_mg;
854 	spa_t *spa = vd->vdev_spa;
855 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
856 	vdev_indirect_mapping_entry_t *entry;
857 	dva_t dst = { 0 };
858 
859 	ASSERT3U(size, <=, SPA_MAXBLOCKSIZE);
860 
861 	/*
862 	 * We use allocator 0 for this I/O because we don't expect device remap
863 	 * to be the steady state of the system, so parallelizing is not as
864 	 * critical as it is for other allocation types. We also want to ensure
865 	 * that the IOs are allocated together as much as possible, to reduce
866 	 * mapping sizes.
867 	 */
868 	int error = metaslab_alloc_dva(spa, mg->mg_class, size,
869 	    &dst, 0, NULL, txg, 0, zal, 0);
870 	if (error != 0)
871 		return (error);
872 
873 	/*
874 	 * We can't have any padding of the allocated size, otherwise we will
875 	 * misunderstand what's allocated, and the size of the mapping.
876 	 * The caller ensures this will be true by passing in a size that is
877 	 * aligned to the worst (highest) ashift in the pool.
878 	 */
879 	ASSERT3U(DVA_GET_ASIZE(&dst), ==, size);
880 
881 	entry = kmem_zalloc(sizeof (vdev_indirect_mapping_entry_t), KM_SLEEP);
882 	DVA_MAPPING_SET_SRC_OFFSET(&entry->vime_mapping, start);
883 	entry->vime_mapping.vimep_dst = dst;
884 
885 	/*
886 	 * See comment before spa_vdev_copy_one_child().
887 	 */
888 	spa_config_enter(spa, SCL_STATE, spa, RW_READER);
889 	zio_t *nzio = zio_null(spa->spa_txg_zio[txg & TXG_MASK], spa, NULL,
890 	    spa_vdev_copy_nullzio_done, NULL, 0);
891 	vdev_t *dest_vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dst));
892 	if (dest_vd->vdev_ops == &vdev_mirror_ops) {
893 		for (int i = 0; i < dest_vd->vdev_children; i++) {
894 			vdev_t *child = dest_vd->vdev_child[i];
895 			spa_vdev_copy_one_child(vca, nzio, vd, start,
896 			    child, DVA_GET_OFFSET(&dst), i, size);
897 		}
898 	} else {
899 		spa_vdev_copy_one_child(vca, nzio, vd, start,
900 		    dest_vd, DVA_GET_OFFSET(&dst), -1, size);
901 	}
902 	zio_nowait(nzio);
903 
904 	list_insert_tail(&svr->svr_new_segments[txg & TXG_MASK], entry);
905 	ASSERT3U(start + size, <=, vd->vdev_ms_count << vd->vdev_ms_shift);
906 	vdev_dirty(vd, 0, NULL, txg);
907 
908 	return (0);
909 }
910 
911 /*
912  * Complete the removal of a toplevel vdev. This is called as a
913  * synctask in the same txg that we will sync out the new config (to the
914  * MOS object) which indicates that this vdev is indirect.
915  */
916 static void
917 vdev_remove_complete_sync(void *arg, dmu_tx_t *tx)
918 {
919 	spa_vdev_removal_t *svr = arg;
920 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
921 	vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
922 
923 	ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
924 
925 	for (int i = 0; i < TXG_SIZE; i++) {
926 		ASSERT0(svr->svr_bytes_done[i]);
927 	}
928 
929 	ASSERT3U(spa->spa_removing_phys.sr_copied, ==,
930 	    spa->spa_removing_phys.sr_to_copy);
931 
932 	vdev_destroy_spacemaps(vd, tx);
933 
934 	/* destroy leaf zaps, if any */
935 	ASSERT3P(svr->svr_zaplist, !=, NULL);
936 	for (nvpair_t *pair = nvlist_next_nvpair(svr->svr_zaplist, NULL);
937 	    pair != NULL;
938 	    pair = nvlist_next_nvpair(svr->svr_zaplist, pair)) {
939 		vdev_destroy_unlink_zap(vd, fnvpair_value_uint64(pair), tx);
940 	}
941 	fnvlist_free(svr->svr_zaplist);
942 
943 	spa_finish_removal(dmu_tx_pool(tx)->dp_spa, DSS_FINISHED, tx);
944 	/* vd->vdev_path is not available here */
945 	spa_history_log_internal(spa, "vdev remove completed",  tx,
946 	    "%s vdev %llu", spa_name(spa), vd->vdev_id);
947 }
948 
949 static void
950 vdev_remove_enlist_zaps(vdev_t *vd, nvlist_t *zlist)
951 {
952 	ASSERT3P(zlist, !=, NULL);
953 	ASSERT3P(vd->vdev_ops, !=, &vdev_raidz_ops);
954 
955 	if (vd->vdev_leaf_zap != 0) {
956 		char zkey[32];
957 		(void) snprintf(zkey, sizeof (zkey), "%s-%"PRIu64,
958 		    VDEV_REMOVAL_ZAP_OBJS, vd->vdev_leaf_zap);
959 		fnvlist_add_uint64(zlist, zkey, vd->vdev_leaf_zap);
960 	}
961 
962 	for (uint64_t id = 0; id < vd->vdev_children; id++) {
963 		vdev_remove_enlist_zaps(vd->vdev_child[id], zlist);
964 	}
965 }
966 
967 static void
968 vdev_remove_replace_with_indirect(vdev_t *vd, uint64_t txg)
969 {
970 	vdev_t *ivd;
971 	dmu_tx_t *tx;
972 	spa_t *spa = vd->vdev_spa;
973 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
974 
975 	/*
976 	 * First, build a list of leaf zaps to be destroyed.
977 	 * This is passed to the sync context thread,
978 	 * which does the actual unlinking.
979 	 */
980 	svr->svr_zaplist = fnvlist_alloc();
981 	vdev_remove_enlist_zaps(vd, svr->svr_zaplist);
982 
983 	ivd = vdev_add_parent(vd, &vdev_indirect_ops);
984 	ivd->vdev_removing = 0;
985 
986 	vd->vdev_leaf_zap = 0;
987 
988 	vdev_remove_child(ivd, vd);
989 	vdev_compact_children(ivd);
990 
991 	ASSERT(!list_link_active(&vd->vdev_state_dirty_node));
992 
993 	tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
994 	dsl_sync_task_nowait(spa->spa_dsl_pool, vdev_remove_complete_sync, svr,
995 	    0, ZFS_SPACE_CHECK_NONE, tx);
996 	dmu_tx_commit(tx);
997 
998 	/*
999 	 * Indicate that this thread has exited.
1000 	 * After this, we can not use svr.
1001 	 */
1002 	mutex_enter(&svr->svr_lock);
1003 	svr->svr_thread = NULL;
1004 	cv_broadcast(&svr->svr_cv);
1005 	mutex_exit(&svr->svr_lock);
1006 }
1007 
1008 /*
1009  * Complete the removal of a toplevel vdev. This is called in open
1010  * context by the removal thread after we have copied all vdev's data.
1011  */
1012 static void
1013 vdev_remove_complete(spa_t *spa)
1014 {
1015 	uint64_t txg;
1016 
1017 	/*
1018 	 * Wait for any deferred frees to be synced before we call
1019 	 * vdev_metaslab_fini()
1020 	 */
1021 	txg_wait_synced(spa->spa_dsl_pool, 0);
1022 	txg = spa_vdev_enter(spa);
1023 	vdev_t *vd = vdev_lookup_top(spa, spa->spa_vdev_removal->svr_vdev_id);
1024 
1025 	sysevent_t *ev = spa_event_create(spa, vd, NULL,
1026 	    ESC_ZFS_VDEV_REMOVE_DEV);
1027 
1028 	zfs_dbgmsg("finishing device removal for vdev %llu in txg %llu",
1029 	    vd->vdev_id, txg);
1030 
1031 	/*
1032 	 * Discard allocation state.
1033 	 */
1034 	if (vd->vdev_mg != NULL) {
1035 		vdev_metaslab_fini(vd);
1036 		metaslab_group_destroy(vd->vdev_mg);
1037 		vd->vdev_mg = NULL;
1038 	}
1039 	ASSERT0(vd->vdev_stat.vs_space);
1040 	ASSERT0(vd->vdev_stat.vs_dspace);
1041 
1042 	vdev_remove_replace_with_indirect(vd, txg);
1043 
1044 	/*
1045 	 * We now release the locks, allowing spa_sync to run and finish the
1046 	 * removal via vdev_remove_complete_sync in syncing context.
1047 	 *
1048 	 * Note that we hold on to the vdev_t that has been replaced.  Since
1049 	 * it isn't part of the vdev tree any longer, it can't be concurrently
1050 	 * manipulated, even while we don't have the config lock.
1051 	 */
1052 	(void) spa_vdev_exit(spa, NULL, txg, 0);
1053 
1054 	/*
1055 	 * Top ZAP should have been transferred to the indirect vdev in
1056 	 * vdev_remove_replace_with_indirect.
1057 	 */
1058 	ASSERT0(vd->vdev_top_zap);
1059 
1060 	/*
1061 	 * Leaf ZAP should have been moved in vdev_remove_replace_with_indirect.
1062 	 */
1063 	ASSERT0(vd->vdev_leaf_zap);
1064 
1065 	txg = spa_vdev_enter(spa);
1066 	(void) vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
1067 	/*
1068 	 * Request to update the config and the config cachefile.
1069 	 */
1070 	vdev_config_dirty(spa->spa_root_vdev);
1071 	(void) spa_vdev_exit(spa, vd, txg, 0);
1072 
1073 	spa_event_post(ev);
1074 }
1075 
1076 /*
1077  * Evacuates a segment of size at most max_alloc from the vdev
1078  * via repeated calls to spa_vdev_copy_segment. If an allocation
1079  * fails, the pool is probably too fragmented to handle such a
1080  * large size, so decrease max_alloc so that the caller will not try
1081  * this size again this txg.
1082  */
1083 static void
1084 spa_vdev_copy_impl(vdev_t *vd, spa_vdev_removal_t *svr, vdev_copy_arg_t *vca,
1085     uint64_t *max_alloc, dmu_tx_t *tx)
1086 {
1087 	uint64_t txg = dmu_tx_get_txg(tx);
1088 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1089 
1090 	mutex_enter(&svr->svr_lock);
1091 
1092 	range_seg_t *rs = avl_first(&svr->svr_allocd_segs->rt_root);
1093 	if (rs == NULL) {
1094 		mutex_exit(&svr->svr_lock);
1095 		return;
1096 	}
1097 	uint64_t offset = rs->rs_start;
1098 	uint64_t length = MIN(rs->rs_end - rs->rs_start, *max_alloc);
1099 
1100 	range_tree_remove(svr->svr_allocd_segs, offset, length);
1101 
1102 	if (svr->svr_max_offset_to_sync[txg & TXG_MASK] == 0) {
1103 		dsl_sync_task_nowait(dmu_tx_pool(tx), vdev_mapping_sync,
1104 		    svr, 0, ZFS_SPACE_CHECK_NONE, tx);
1105 	}
1106 
1107 	svr->svr_max_offset_to_sync[txg & TXG_MASK] = offset + length;
1108 
1109 	/*
1110 	 * Note: this is the amount of *allocated* space
1111 	 * that we are taking care of each txg.
1112 	 */
1113 	svr->svr_bytes_done[txg & TXG_MASK] += length;
1114 
1115 	mutex_exit(&svr->svr_lock);
1116 
1117 	zio_alloc_list_t zal;
1118 	metaslab_trace_init(&zal);
1119 	uint64_t thismax = *max_alloc;
1120 	while (length > 0) {
1121 		uint64_t mylen = MIN(length, thismax);
1122 
1123 		int error = spa_vdev_copy_segment(vd,
1124 		    offset, mylen, txg, vca, &zal);
1125 
1126 		if (error == ENOSPC) {
1127 			/*
1128 			 * Cut our segment in half, and don't try this
1129 			 * segment size again this txg.  Note that the
1130 			 * allocation size must be aligned to the highest
1131 			 * ashift in the pool, so that the allocation will
1132 			 * not be padded out to a multiple of the ashift,
1133 			 * which could cause us to think that this mapping
1134 			 * is larger than we intended.
1135 			 */
1136 			ASSERT3U(spa->spa_max_ashift, >=, SPA_MINBLOCKSHIFT);
1137 			ASSERT3U(spa->spa_max_ashift, ==, spa->spa_min_ashift);
1138 			thismax = P2ROUNDUP(mylen / 2,
1139 			    1 << spa->spa_max_ashift);
1140 			ASSERT3U(thismax, <, mylen);
1141 			/*
1142 			 * The minimum-size allocation can not fail.
1143 			 */
1144 			ASSERT3U(mylen, >, 1 << spa->spa_max_ashift);
1145 			*max_alloc = mylen - (1 << spa->spa_max_ashift);
1146 		} else {
1147 			ASSERT0(error);
1148 			length -= mylen;
1149 			offset += mylen;
1150 
1151 			/*
1152 			 * We've performed an allocation, so reset the
1153 			 * alloc trace list.
1154 			 */
1155 			metaslab_trace_fini(&zal);
1156 			metaslab_trace_init(&zal);
1157 		}
1158 	}
1159 	metaslab_trace_fini(&zal);
1160 }
1161 
1162 /*
1163  * The removal thread operates in open context.  It iterates over all
1164  * allocated space in the vdev, by loading each metaslab's spacemap.
1165  * For each contiguous segment of allocated space (capping the segment
1166  * size at SPA_MAXBLOCKSIZE), we:
1167  *    - Allocate space for it on another vdev.
1168  *    - Create a new mapping from the old location to the new location
1169  *      (as a record in svr_new_segments).
1170  *    - Initiate a logical read zio to get the data off the removing disk.
1171  *    - In the read zio's done callback, initiate a logical write zio to
1172  *      write it to the new vdev.
1173  * Note that all of this will take effect when a particular TXG syncs.
1174  * The sync thread ensures that all the phys reads and writes for the syncing
1175  * TXG have completed (see spa_txg_zio) and writes the new mappings to disk
1176  * (see vdev_mapping_sync()).
1177  */
1178 static void
1179 spa_vdev_remove_thread(void *arg)
1180 {
1181 	spa_t *spa = arg;
1182 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
1183 	vdev_copy_arg_t vca;
1184 	uint64_t max_alloc = zfs_remove_max_segment;
1185 	uint64_t last_txg = 0;
1186 
1187 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
1188 	vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
1189 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1190 	uint64_t start_offset = vdev_indirect_mapping_max_offset(vim);
1191 
1192 	ASSERT3P(vd->vdev_ops, !=, &vdev_indirect_ops);
1193 	ASSERT(vdev_is_concrete(vd));
1194 	ASSERT(vd->vdev_removing);
1195 	ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
1196 	ASSERT(vim != NULL);
1197 
1198 	mutex_init(&vca.vca_lock, NULL, MUTEX_DEFAULT, NULL);
1199 	cv_init(&vca.vca_cv, NULL, CV_DEFAULT, NULL);
1200 	vca.vca_outstanding_bytes = 0;
1201 
1202 	mutex_enter(&svr->svr_lock);
1203 
1204 	/*
1205 	 * Start from vim_max_offset so we pick up where we left off
1206 	 * if we are restarting the removal after opening the pool.
1207 	 */
1208 	uint64_t msi;
1209 	for (msi = start_offset >> vd->vdev_ms_shift;
1210 	    msi < vd->vdev_ms_count && !svr->svr_thread_exit; msi++) {
1211 		metaslab_t *msp = vd->vdev_ms[msi];
1212 		ASSERT3U(msi, <=, vd->vdev_ms_count);
1213 
1214 		ASSERT0(range_tree_space(svr->svr_allocd_segs));
1215 
1216 		mutex_enter(&msp->ms_sync_lock);
1217 		mutex_enter(&msp->ms_lock);
1218 
1219 		/*
1220 		 * Assert nothing in flight -- ms_*tree is empty.
1221 		 */
1222 		for (int i = 0; i < TXG_SIZE; i++) {
1223 			ASSERT0(range_tree_space(msp->ms_allocating[i]));
1224 		}
1225 
1226 		/*
1227 		 * If the metaslab has ever been allocated from (ms_sm!=NULL),
1228 		 * read the allocated segments from the space map object
1229 		 * into svr_allocd_segs. Since we do this while holding
1230 		 * svr_lock and ms_sync_lock, concurrent frees (which
1231 		 * would have modified the space map) will wait for us
1232 		 * to finish loading the spacemap, and then take the
1233 		 * appropriate action (see free_from_removing_vdev()).
1234 		 */
1235 		if (msp->ms_sm != NULL) {
1236 			space_map_t *sm = NULL;
1237 
1238 			/*
1239 			 * We have to open a new space map here, because
1240 			 * ms_sm's sm_length and sm_alloc may not reflect
1241 			 * what's in the object contents, if we are in between
1242 			 * metaslab_sync() and metaslab_sync_done().
1243 			 */
1244 			VERIFY0(space_map_open(&sm,
1245 			    spa->spa_dsl_pool->dp_meta_objset,
1246 			    msp->ms_sm->sm_object, msp->ms_sm->sm_start,
1247 			    msp->ms_sm->sm_size, msp->ms_sm->sm_shift));
1248 			space_map_update(sm);
1249 			VERIFY0(space_map_load(sm, svr->svr_allocd_segs,
1250 			    SM_ALLOC));
1251 			space_map_close(sm);
1252 
1253 			range_tree_walk(msp->ms_freeing,
1254 			    range_tree_remove, svr->svr_allocd_segs);
1255 
1256 			/*
1257 			 * When we are resuming from a paused removal (i.e.
1258 			 * when importing a pool with a removal in progress),
1259 			 * discard any state that we have already processed.
1260 			 */
1261 			range_tree_clear(svr->svr_allocd_segs, 0, start_offset);
1262 		}
1263 		mutex_exit(&msp->ms_lock);
1264 		mutex_exit(&msp->ms_sync_lock);
1265 
1266 		vca.vca_msp = msp;
1267 		zfs_dbgmsg("copying %llu segments for metaslab %llu",
1268 		    avl_numnodes(&svr->svr_allocd_segs->rt_root),
1269 		    msp->ms_id);
1270 
1271 		while (!svr->svr_thread_exit &&
1272 		    !range_tree_is_empty(svr->svr_allocd_segs)) {
1273 
1274 			mutex_exit(&svr->svr_lock);
1275 
1276 			/*
1277 			 * We need to periodically drop the config lock so that
1278 			 * writers can get in.  Additionally, we can't wait
1279 			 * for a txg to sync while holding a config lock
1280 			 * (since a waiting writer could cause a 3-way deadlock
1281 			 * with the sync thread, which also gets a config
1282 			 * lock for reader).  So we can't hold the config lock
1283 			 * while calling dmu_tx_assign().
1284 			 */
1285 			spa_config_exit(spa, SCL_CONFIG, FTAG);
1286 
1287 			/*
1288 			 * This delay will pause the removal around the point
1289 			 * specified by zfs_remove_max_bytes_pause. We do this
1290 			 * solely from the test suite or during debugging.
1291 			 */
1292 			uint64_t bytes_copied =
1293 			    spa->spa_removing_phys.sr_copied;
1294 			for (int i = 0; i < TXG_SIZE; i++)
1295 				bytes_copied += svr->svr_bytes_done[i];
1296 			while (zfs_remove_max_bytes_pause <= bytes_copied &&
1297 			    !svr->svr_thread_exit)
1298 				delay(hz);
1299 
1300 			mutex_enter(&vca.vca_lock);
1301 			while (vca.vca_outstanding_bytes >
1302 			    zfs_remove_max_copy_bytes) {
1303 				cv_wait(&vca.vca_cv, &vca.vca_lock);
1304 			}
1305 			mutex_exit(&vca.vca_lock);
1306 
1307 			dmu_tx_t *tx =
1308 			    dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
1309 
1310 			VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
1311 			uint64_t txg = dmu_tx_get_txg(tx);
1312 
1313 			/*
1314 			 * Reacquire the vdev_config lock.  The vdev_t
1315 			 * that we're removing may have changed, e.g. due
1316 			 * to a vdev_attach or vdev_detach.
1317 			 */
1318 			spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
1319 			vd = vdev_lookup_top(spa, svr->svr_vdev_id);
1320 
1321 			if (txg != last_txg)
1322 				max_alloc = zfs_remove_max_segment;
1323 			last_txg = txg;
1324 
1325 			spa_vdev_copy_impl(vd, svr, &vca, &max_alloc, tx);
1326 
1327 			dmu_tx_commit(tx);
1328 			mutex_enter(&svr->svr_lock);
1329 		}
1330 	}
1331 
1332 	mutex_exit(&svr->svr_lock);
1333 
1334 	spa_config_exit(spa, SCL_CONFIG, FTAG);
1335 
1336 	/*
1337 	 * Wait for all copies to finish before cleaning up the vca.
1338 	 */
1339 	txg_wait_synced(spa->spa_dsl_pool, 0);
1340 	ASSERT0(vca.vca_outstanding_bytes);
1341 
1342 	mutex_destroy(&vca.vca_lock);
1343 	cv_destroy(&vca.vca_cv);
1344 
1345 	if (svr->svr_thread_exit) {
1346 		mutex_enter(&svr->svr_lock);
1347 		range_tree_vacate(svr->svr_allocd_segs, NULL, NULL);
1348 		svr->svr_thread = NULL;
1349 		cv_broadcast(&svr->svr_cv);
1350 		mutex_exit(&svr->svr_lock);
1351 	} else {
1352 		ASSERT0(range_tree_space(svr->svr_allocd_segs));
1353 		vdev_remove_complete(spa);
1354 	}
1355 }
1356 
1357 void
1358 spa_vdev_remove_suspend(spa_t *spa)
1359 {
1360 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
1361 
1362 	if (svr == NULL)
1363 		return;
1364 
1365 	mutex_enter(&svr->svr_lock);
1366 	svr->svr_thread_exit = B_TRUE;
1367 	while (svr->svr_thread != NULL)
1368 		cv_wait(&svr->svr_cv, &svr->svr_lock);
1369 	svr->svr_thread_exit = B_FALSE;
1370 	mutex_exit(&svr->svr_lock);
1371 }
1372 
1373 /* ARGSUSED */
1374 static int
1375 spa_vdev_remove_cancel_check(void *arg, dmu_tx_t *tx)
1376 {
1377 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1378 
1379 	if (spa->spa_vdev_removal == NULL)
1380 		return (ENOTACTIVE);
1381 	return (0);
1382 }
1383 
1384 /*
1385  * Cancel a removal by freeing all entries from the partial mapping
1386  * and marking the vdev as no longer being removing.
1387  */
1388 /* ARGSUSED */
1389 static void
1390 spa_vdev_remove_cancel_sync(void *arg, dmu_tx_t *tx)
1391 {
1392 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1393 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
1394 	vdev_t *vd = vdev_lookup_top(spa, svr->svr_vdev_id);
1395 	vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
1396 	vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1397 	objset_t *mos = spa->spa_meta_objset;
1398 
1399 	ASSERT3P(svr->svr_thread, ==, NULL);
1400 
1401 	spa_feature_decr(spa, SPA_FEATURE_DEVICE_REMOVAL, tx);
1402 	if (vdev_obsolete_counts_are_precise(vd)) {
1403 		spa_feature_decr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
1404 		VERIFY0(zap_remove(spa->spa_meta_objset, vd->vdev_top_zap,
1405 		    VDEV_TOP_ZAP_OBSOLETE_COUNTS_ARE_PRECISE, tx));
1406 	}
1407 
1408 	if (vdev_obsolete_sm_object(vd) != 0) {
1409 		ASSERT(vd->vdev_obsolete_sm != NULL);
1410 		ASSERT3U(vdev_obsolete_sm_object(vd), ==,
1411 		    space_map_object(vd->vdev_obsolete_sm));
1412 
1413 		space_map_free(vd->vdev_obsolete_sm, tx);
1414 		VERIFY0(zap_remove(spa->spa_meta_objset, vd->vdev_top_zap,
1415 		    VDEV_TOP_ZAP_INDIRECT_OBSOLETE_SM, tx));
1416 		space_map_close(vd->vdev_obsolete_sm);
1417 		vd->vdev_obsolete_sm = NULL;
1418 		spa_feature_decr(spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
1419 	}
1420 	for (int i = 0; i < TXG_SIZE; i++) {
1421 		ASSERT(list_is_empty(&svr->svr_new_segments[i]));
1422 		ASSERT3U(svr->svr_max_offset_to_sync[i], <=,
1423 		    vdev_indirect_mapping_max_offset(vim));
1424 	}
1425 
1426 	for (uint64_t msi = 0; msi < vd->vdev_ms_count; msi++) {
1427 		metaslab_t *msp = vd->vdev_ms[msi];
1428 
1429 		if (msp->ms_start >= vdev_indirect_mapping_max_offset(vim))
1430 			break;
1431 
1432 		ASSERT0(range_tree_space(svr->svr_allocd_segs));
1433 
1434 		mutex_enter(&msp->ms_lock);
1435 
1436 		/*
1437 		 * Assert nothing in flight -- ms_*tree is empty.
1438 		 */
1439 		for (int i = 0; i < TXG_SIZE; i++)
1440 			ASSERT0(range_tree_space(msp->ms_allocating[i]));
1441 		for (int i = 0; i < TXG_DEFER_SIZE; i++)
1442 			ASSERT0(range_tree_space(msp->ms_defer[i]));
1443 		ASSERT0(range_tree_space(msp->ms_freed));
1444 
1445 		if (msp->ms_sm != NULL) {
1446 			/*
1447 			 * Assert that the in-core spacemap has the same
1448 			 * length as the on-disk one, so we can use the
1449 			 * existing in-core spacemap to load it from disk.
1450 			 */
1451 			ASSERT3U(msp->ms_sm->sm_alloc, ==,
1452 			    msp->ms_sm->sm_phys->smp_alloc);
1453 			ASSERT3U(msp->ms_sm->sm_length, ==,
1454 			    msp->ms_sm->sm_phys->smp_objsize);
1455 
1456 			mutex_enter(&svr->svr_lock);
1457 			VERIFY0(space_map_load(msp->ms_sm,
1458 			    svr->svr_allocd_segs, SM_ALLOC));
1459 			range_tree_walk(msp->ms_freeing,
1460 			    range_tree_remove, svr->svr_allocd_segs);
1461 
1462 			/*
1463 			 * Clear everything past what has been synced,
1464 			 * because we have not allocated mappings for it yet.
1465 			 */
1466 			uint64_t syncd = vdev_indirect_mapping_max_offset(vim);
1467 			uint64_t sm_end = msp->ms_sm->sm_start +
1468 			    msp->ms_sm->sm_size;
1469 			if (sm_end > syncd)
1470 				range_tree_clear(svr->svr_allocd_segs,
1471 				    syncd, sm_end - syncd);
1472 
1473 			mutex_exit(&svr->svr_lock);
1474 		}
1475 		mutex_exit(&msp->ms_lock);
1476 
1477 		mutex_enter(&svr->svr_lock);
1478 		range_tree_vacate(svr->svr_allocd_segs,
1479 		    free_mapped_segment_cb, vd);
1480 		mutex_exit(&svr->svr_lock);
1481 	}
1482 
1483 	/*
1484 	 * Note: this must happen after we invoke free_mapped_segment_cb,
1485 	 * because it adds to the obsolete_segments.
1486 	 */
1487 	range_tree_vacate(vd->vdev_obsolete_segments, NULL, NULL);
1488 
1489 	ASSERT3U(vic->vic_mapping_object, ==,
1490 	    vdev_indirect_mapping_object(vd->vdev_indirect_mapping));
1491 	vdev_indirect_mapping_close(vd->vdev_indirect_mapping);
1492 	vd->vdev_indirect_mapping = NULL;
1493 	vdev_indirect_mapping_free(mos, vic->vic_mapping_object, tx);
1494 	vic->vic_mapping_object = 0;
1495 
1496 	ASSERT3U(vic->vic_births_object, ==,
1497 	    vdev_indirect_births_object(vd->vdev_indirect_births));
1498 	vdev_indirect_births_close(vd->vdev_indirect_births);
1499 	vd->vdev_indirect_births = NULL;
1500 	vdev_indirect_births_free(mos, vic->vic_births_object, tx);
1501 	vic->vic_births_object = 0;
1502 
1503 	/*
1504 	 * We may have processed some frees from the removing vdev in this
1505 	 * txg, thus increasing svr_bytes_done; discard that here to
1506 	 * satisfy the assertions in spa_vdev_removal_destroy().
1507 	 * Note that future txg's can not have any bytes_done, because
1508 	 * future TXG's are only modified from open context, and we have
1509 	 * already shut down the copying thread.
1510 	 */
1511 	svr->svr_bytes_done[dmu_tx_get_txg(tx) & TXG_MASK] = 0;
1512 	spa_finish_removal(spa, DSS_CANCELED, tx);
1513 
1514 	vd->vdev_removing = B_FALSE;
1515 	vdev_config_dirty(vd);
1516 
1517 	zfs_dbgmsg("canceled device removal for vdev %llu in %llu",
1518 	    vd->vdev_id, dmu_tx_get_txg(tx));
1519 	spa_history_log_internal(spa, "vdev remove canceled", tx,
1520 	    "%s vdev %llu %s", spa_name(spa),
1521 	    vd->vdev_id, (vd->vdev_path != NULL) ? vd->vdev_path : "-");
1522 }
1523 
1524 int
1525 spa_vdev_remove_cancel(spa_t *spa)
1526 {
1527 	spa_vdev_remove_suspend(spa);
1528 
1529 	if (spa->spa_vdev_removal == NULL)
1530 		return (ENOTACTIVE);
1531 
1532 	uint64_t vdid = spa->spa_vdev_removal->svr_vdev_id;
1533 
1534 	int error = dsl_sync_task(spa->spa_name, spa_vdev_remove_cancel_check,
1535 	    spa_vdev_remove_cancel_sync, NULL, 0,
1536 	    ZFS_SPACE_CHECK_EXTRA_RESERVED);
1537 
1538 	if (error == 0) {
1539 		spa_config_enter(spa, SCL_ALLOC | SCL_VDEV, FTAG, RW_WRITER);
1540 		vdev_t *vd = vdev_lookup_top(spa, vdid);
1541 		metaslab_group_activate(vd->vdev_mg);
1542 		spa_config_exit(spa, SCL_ALLOC | SCL_VDEV, FTAG);
1543 	}
1544 
1545 	return (error);
1546 }
1547 
1548 /*
1549  * Called every sync pass of every txg if there's a svr.
1550  */
1551 void
1552 svr_sync(spa_t *spa, dmu_tx_t *tx)
1553 {
1554 	spa_vdev_removal_t *svr = spa->spa_vdev_removal;
1555 	int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
1556 
1557 	/*
1558 	 * This check is necessary so that we do not dirty the
1559 	 * DIRECTORY_OBJECT via spa_sync_removing_state() when there
1560 	 * is nothing to do.  Dirtying it every time would prevent us
1561 	 * from syncing-to-convergence.
1562 	 */
1563 	if (svr->svr_bytes_done[txgoff] == 0)
1564 		return;
1565 
1566 	/*
1567 	 * Update progress accounting.
1568 	 */
1569 	spa->spa_removing_phys.sr_copied += svr->svr_bytes_done[txgoff];
1570 	svr->svr_bytes_done[txgoff] = 0;
1571 
1572 	spa_sync_removing_state(spa, tx);
1573 }
1574 
1575 static void
1576 vdev_remove_make_hole_and_free(vdev_t *vd)
1577 {
1578 	uint64_t id = vd->vdev_id;
1579 	spa_t *spa = vd->vdev_spa;
1580 	vdev_t *rvd = spa->spa_root_vdev;
1581 	boolean_t last_vdev = (id == (rvd->vdev_children - 1));
1582 
1583 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1584 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1585 
1586 	vdev_free(vd);
1587 
1588 	if (last_vdev) {
1589 		vdev_compact_children(rvd);
1590 	} else {
1591 		vd = vdev_alloc_common(spa, id, 0, &vdev_hole_ops);
1592 		vdev_add_child(rvd, vd);
1593 	}
1594 	vdev_config_dirty(rvd);
1595 
1596 	/*
1597 	 * Reassess the health of our root vdev.
1598 	 */
1599 	vdev_reopen(rvd);
1600 }
1601 
1602 /*
1603  * Remove a log device.  The config lock is held for the specified TXG.
1604  */
1605 static int
1606 spa_vdev_remove_log(vdev_t *vd, uint64_t *txg)
1607 {
1608 	metaslab_group_t *mg = vd->vdev_mg;
1609 	spa_t *spa = vd->vdev_spa;
1610 	int error = 0;
1611 
1612 	ASSERT(vd->vdev_islog);
1613 	ASSERT(vd == vd->vdev_top);
1614 
1615 	/*
1616 	 * Stop allocating from this vdev.
1617 	 */
1618 	metaslab_group_passivate(mg);
1619 
1620 	/*
1621 	 * Wait for the youngest allocations and frees to sync,
1622 	 * and then wait for the deferral of those frees to finish.
1623 	 */
1624 	spa_vdev_config_exit(spa, NULL,
1625 	    *txg + TXG_CONCURRENT_STATES + TXG_DEFER_SIZE, 0, FTAG);
1626 
1627 	/*
1628 	 * Evacuate the device.  We don't hold the config lock as writer
1629 	 * since we need to do I/O but we do keep the
1630 	 * spa_namespace_lock held.  Once this completes the device
1631 	 * should no longer have any blocks allocated on it.
1632 	 */
1633 	if (vd->vdev_islog) {
1634 		if (vd->vdev_stat.vs_alloc != 0)
1635 			error = spa_reset_logs(spa);
1636 	}
1637 
1638 	*txg = spa_vdev_config_enter(spa);
1639 
1640 	if (error != 0) {
1641 		metaslab_group_activate(mg);
1642 		return (error);
1643 	}
1644 	ASSERT0(vd->vdev_stat.vs_alloc);
1645 
1646 	/*
1647 	 * The evacuation succeeded.  Remove any remaining MOS metadata
1648 	 * associated with this vdev, and wait for these changes to sync.
1649 	 */
1650 	vd->vdev_removing = B_TRUE;
1651 
1652 	vdev_dirty_leaves(vd, VDD_DTL, *txg);
1653 	vdev_config_dirty(vd);
1654 
1655 	spa_history_log_internal(spa, "vdev remove", NULL,
1656 	    "%s vdev %llu (log) %s", spa_name(spa), vd->vdev_id,
1657 	    (vd->vdev_path != NULL) ? vd->vdev_path : "-");
1658 
1659 	/* Make sure these changes are sync'ed */
1660 	spa_vdev_config_exit(spa, NULL, *txg, 0, FTAG);
1661 
1662 	*txg = spa_vdev_config_enter(spa);
1663 
1664 	sysevent_t *ev = spa_event_create(spa, vd, NULL,
1665 	    ESC_ZFS_VDEV_REMOVE_DEV);
1666 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1667 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1668 
1669 	/* The top ZAP should have been destroyed by vdev_remove_empty. */
1670 	ASSERT0(vd->vdev_top_zap);
1671 	/* The leaf ZAP should have been destroyed by vdev_dtl_sync. */
1672 	ASSERT0(vd->vdev_leaf_zap);
1673 
1674 	(void) vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
1675 
1676 	if (list_link_active(&vd->vdev_state_dirty_node))
1677 		vdev_state_clean(vd);
1678 	if (list_link_active(&vd->vdev_config_dirty_node))
1679 		vdev_config_clean(vd);
1680 
1681 	/*
1682 	 * Clean up the vdev namespace.
1683 	 */
1684 	vdev_remove_make_hole_and_free(vd);
1685 
1686 	if (ev != NULL)
1687 		spa_event_post(ev);
1688 
1689 	return (0);
1690 }
1691 
1692 static int
1693 spa_vdev_remove_top_check(vdev_t *vd)
1694 {
1695 	spa_t *spa = vd->vdev_spa;
1696 
1697 	if (vd != vd->vdev_top)
1698 		return (SET_ERROR(ENOTSUP));
1699 
1700 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_DEVICE_REMOVAL))
1701 		return (SET_ERROR(ENOTSUP));
1702 
1703 	/*
1704 	 * There has to be enough free space to remove the
1705 	 * device and leave double the "slop" space (i.e. we
1706 	 * must leave at least 3% of the pool free, in addition to
1707 	 * the normal slop space).
1708 	 */
1709 	if (dsl_dir_space_available(spa->spa_dsl_pool->dp_root_dir,
1710 	    NULL, 0, B_TRUE) <
1711 	    vd->vdev_stat.vs_dspace + spa_get_slop_space(spa)) {
1712 		return (SET_ERROR(ENOSPC));
1713 	}
1714 
1715 	/*
1716 	 * There can not be a removal in progress.
1717 	 */
1718 	if (spa->spa_removing_phys.sr_state == DSS_SCANNING)
1719 		return (SET_ERROR(EBUSY));
1720 
1721 	/*
1722 	 * The device must have all its data.
1723 	 */
1724 	if (!vdev_dtl_empty(vd, DTL_MISSING) ||
1725 	    !vdev_dtl_empty(vd, DTL_OUTAGE))
1726 		return (SET_ERROR(EBUSY));
1727 
1728 	/*
1729 	 * The device must be healthy.
1730 	 */
1731 	if (!vdev_readable(vd))
1732 		return (SET_ERROR(EIO));
1733 
1734 	/*
1735 	 * All vdevs in normal class must have the same ashift.
1736 	 */
1737 	if (spa->spa_max_ashift != spa->spa_min_ashift) {
1738 		return (SET_ERROR(EINVAL));
1739 	}
1740 
1741 	/*
1742 	 * All vdevs in normal class must have the same ashift
1743 	 * and not be raidz.
1744 	 */
1745 	vdev_t *rvd = spa->spa_root_vdev;
1746 	int num_indirect = 0;
1747 	for (uint64_t id = 0; id < rvd->vdev_children; id++) {
1748 		vdev_t *cvd = rvd->vdev_child[id];
1749 		if (cvd->vdev_ashift != 0 && !cvd->vdev_islog)
1750 			ASSERT3U(cvd->vdev_ashift, ==, spa->spa_max_ashift);
1751 		if (cvd->vdev_ops == &vdev_indirect_ops)
1752 			num_indirect++;
1753 		if (!vdev_is_concrete(cvd))
1754 			continue;
1755 		if (cvd->vdev_ops == &vdev_raidz_ops)
1756 			return (SET_ERROR(EINVAL));
1757 		/*
1758 		 * Need the mirror to be mirror of leaf vdevs only
1759 		 */
1760 		if (cvd->vdev_ops == &vdev_mirror_ops) {
1761 			for (uint64_t cid = 0;
1762 			    cid < cvd->vdev_children; cid++) {
1763 				vdev_t *tmp = cvd->vdev_child[cid];
1764 				if (!tmp->vdev_ops->vdev_op_leaf)
1765 					return (SET_ERROR(EINVAL));
1766 			}
1767 		}
1768 	}
1769 
1770 	return (0);
1771 }
1772 
1773 /*
1774  * Initiate removal of a top-level vdev, reducing the total space in the pool.
1775  * The config lock is held for the specified TXG.  Once initiated,
1776  * evacuation of all allocated space (copying it to other vdevs) happens
1777  * in the background (see spa_vdev_remove_thread()), and can be canceled
1778  * (see spa_vdev_remove_cancel()).  If successful, the vdev will
1779  * be transformed to an indirect vdev (see spa_vdev_remove_complete()).
1780  */
1781 static int
1782 spa_vdev_remove_top(vdev_t *vd, uint64_t *txg)
1783 {
1784 	spa_t *spa = vd->vdev_spa;
1785 	int error;
1786 
1787 	/*
1788 	 * Check for errors up-front, so that we don't waste time
1789 	 * passivating the metaslab group and clearing the ZIL if there
1790 	 * are errors.
1791 	 */
1792 	error = spa_vdev_remove_top_check(vd);
1793 	if (error != 0)
1794 		return (error);
1795 
1796 	/*
1797 	 * Stop allocating from this vdev.  Note that we must check
1798 	 * that this is not the only device in the pool before
1799 	 * passivating, otherwise we will not be able to make
1800 	 * progress because we can't allocate from any vdevs.
1801 	 * The above check for sufficient free space serves this
1802 	 * purpose.
1803 	 */
1804 	metaslab_group_t *mg = vd->vdev_mg;
1805 	metaslab_group_passivate(mg);
1806 
1807 	/*
1808 	 * Wait for the youngest allocations and frees to sync,
1809 	 * and then wait for the deferral of those frees to finish.
1810 	 */
1811 	spa_vdev_config_exit(spa, NULL,
1812 	    *txg + TXG_CONCURRENT_STATES + TXG_DEFER_SIZE, 0, FTAG);
1813 
1814 	/*
1815 	 * We must ensure that no "stubby" log blocks are allocated
1816 	 * on the device to be removed.  These blocks could be
1817 	 * written at any time, including while we are in the middle
1818 	 * of copying them.
1819 	 */
1820 	error = spa_reset_logs(spa);
1821 
1822 	*txg = spa_vdev_config_enter(spa);
1823 
1824 	/*
1825 	 * Things might have changed while the config lock was dropped
1826 	 * (e.g. space usage).  Check for errors again.
1827 	 */
1828 	if (error == 0)
1829 		error = spa_vdev_remove_top_check(vd);
1830 
1831 	if (error != 0) {
1832 		metaslab_group_activate(mg);
1833 		return (error);
1834 	}
1835 
1836 	vd->vdev_removing = B_TRUE;
1837 
1838 	vdev_dirty_leaves(vd, VDD_DTL, *txg);
1839 	vdev_config_dirty(vd);
1840 	dmu_tx_t *tx = dmu_tx_create_assigned(spa->spa_dsl_pool, *txg);
1841 	dsl_sync_task_nowait(spa->spa_dsl_pool,
1842 	    vdev_remove_initiate_sync,
1843 	    (void *)(uintptr_t)vd->vdev_id, 0, ZFS_SPACE_CHECK_NONE, tx);
1844 	dmu_tx_commit(tx);
1845 
1846 	return (0);
1847 }
1848 
1849 /*
1850  * Remove a device from the pool.
1851  *
1852  * Removing a device from the vdev namespace requires several steps
1853  * and can take a significant amount of time.  As a result we use
1854  * the spa_vdev_config_[enter/exit] functions which allow us to
1855  * grab and release the spa_config_lock while still holding the namespace
1856  * lock.  During each step the configuration is synced out.
1857  */
1858 int
1859 spa_vdev_remove(spa_t *spa, uint64_t guid, boolean_t unspare)
1860 {
1861 	vdev_t *vd;
1862 	nvlist_t **spares, **l2cache, *nv;
1863 	uint64_t txg = 0;
1864 	uint_t nspares, nl2cache;
1865 	int error = 0;
1866 	boolean_t locked = MUTEX_HELD(&spa_namespace_lock);
1867 	sysevent_t *ev = NULL;
1868 
1869 	ASSERT(spa_writeable(spa));
1870 
1871 	if (!locked)
1872 		txg = spa_vdev_enter(spa);
1873 
1874 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
1875 	if (spa_feature_is_active(spa, SPA_FEATURE_POOL_CHECKPOINT)) {
1876 		error = (spa_has_checkpoint(spa)) ?
1877 		    ZFS_ERR_CHECKPOINT_EXISTS : ZFS_ERR_DISCARDING_CHECKPOINT;
1878 
1879 		if (!locked)
1880 			return (spa_vdev_exit(spa, NULL, txg, error));
1881 
1882 		return (error);
1883 	}
1884 
1885 	vd = spa_lookup_by_guid(spa, guid, B_FALSE);
1886 
1887 	if (spa->spa_spares.sav_vdevs != NULL &&
1888 	    nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1889 	    ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0 &&
1890 	    (nv = spa_nvlist_lookup_by_guid(spares, nspares, guid)) != NULL) {
1891 		/*
1892 		 * Only remove the hot spare if it's not currently in use
1893 		 * in this pool.
1894 		 */
1895 		if (vd == NULL || unspare) {
1896 			char *nvstr = fnvlist_lookup_string(nv,
1897 			    ZPOOL_CONFIG_PATH);
1898 			spa_history_log_internal(spa, "vdev remove", NULL,
1899 			    "%s vdev (%s) %s", spa_name(spa),
1900 			    VDEV_TYPE_SPARE, nvstr);
1901 			if (vd == NULL)
1902 				vd = spa_lookup_by_guid(spa, guid, B_TRUE);
1903 			ev = spa_event_create(spa, vd, NULL,
1904 			    ESC_ZFS_VDEV_REMOVE_AUX);
1905 			spa_vdev_remove_aux(spa->spa_spares.sav_config,
1906 			    ZPOOL_CONFIG_SPARES, spares, nspares, nv);
1907 			spa_load_spares(spa);
1908 			spa->spa_spares.sav_sync = B_TRUE;
1909 		} else {
1910 			error = SET_ERROR(EBUSY);
1911 		}
1912 	} else if (spa->spa_l2cache.sav_vdevs != NULL &&
1913 	    nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
1914 	    ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0 &&
1915 	    (nv = spa_nvlist_lookup_by_guid(l2cache, nl2cache, guid)) != NULL) {
1916 		char *nvstr = fnvlist_lookup_string(nv, ZPOOL_CONFIG_PATH);
1917 		spa_history_log_internal(spa, "vdev remove", NULL,
1918 		    "%s vdev (%s) %s", spa_name(spa), VDEV_TYPE_L2CACHE, nvstr);
1919 		/*
1920 		 * Cache devices can always be removed.
1921 		 */
1922 		vd = spa_lookup_by_guid(spa, guid, B_TRUE);
1923 		ev = spa_event_create(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE_AUX);
1924 		spa_vdev_remove_aux(spa->spa_l2cache.sav_config,
1925 		    ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache, nv);
1926 		spa_load_l2cache(spa);
1927 		spa->spa_l2cache.sav_sync = B_TRUE;
1928 	} else if (vd != NULL && vd->vdev_islog) {
1929 		ASSERT(!locked);
1930 		error = spa_vdev_remove_log(vd, &txg);
1931 	} else if (vd != NULL) {
1932 		ASSERT(!locked);
1933 		error = spa_vdev_remove_top(vd, &txg);
1934 	} else {
1935 		/*
1936 		 * There is no vdev of any kind with the specified guid.
1937 		 */
1938 		error = SET_ERROR(ENOENT);
1939 	}
1940 
1941 	if (!locked)
1942 		error = spa_vdev_exit(spa, NULL, txg, error);
1943 
1944 	if (ev != NULL) {
1945 		if (error != 0) {
1946 			spa_event_discard(ev);
1947 		} else {
1948 			spa_event_post(ev);
1949 		}
1950 	}
1951 
1952 	return (error);
1953 }
1954 
1955 int
1956 spa_removal_get_stats(spa_t *spa, pool_removal_stat_t *prs)
1957 {
1958 	prs->prs_state = spa->spa_removing_phys.sr_state;
1959 
1960 	if (prs->prs_state == DSS_NONE)
1961 		return (SET_ERROR(ENOENT));
1962 
1963 	prs->prs_removing_vdev = spa->spa_removing_phys.sr_removing_vdev;
1964 	prs->prs_start_time = spa->spa_removing_phys.sr_start_time;
1965 	prs->prs_end_time = spa->spa_removing_phys.sr_end_time;
1966 	prs->prs_to_copy = spa->spa_removing_phys.sr_to_copy;
1967 	prs->prs_copied = spa->spa_removing_phys.sr_copied;
1968 
1969 	if (spa->spa_vdev_removal != NULL) {
1970 		for (int i = 0; i < TXG_SIZE; i++) {
1971 			prs->prs_copied +=
1972 			    spa->spa_vdev_removal->svr_bytes_done[i];
1973 		}
1974 	}
1975 
1976 	prs->prs_mapping_memory = 0;
1977 	uint64_t indirect_vdev_id =
1978 	    spa->spa_removing_phys.sr_prev_indirect_vdev;
1979 	while (indirect_vdev_id != -1) {
1980 		vdev_t *vd = spa->spa_root_vdev->vdev_child[indirect_vdev_id];
1981 		vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
1982 		vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
1983 
1984 		ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
1985 		prs->prs_mapping_memory += vdev_indirect_mapping_size(vim);
1986 		indirect_vdev_id = vic->vic_prev_indirect_vdev;
1987 	}
1988 
1989 	return (0);
1990 }
1991