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