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