xref: /illumos-gate/usr/src/uts/common/fs/zfs/vdev_label.c (revision c4ab0d3f46036e85ad0700125c5a83cc139f55a3)
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) 2012, 2018 by Delphix. All rights reserved.
25  * Copyright (c) 2017, Intel Corporation.
26  * Copyright 2019 Joyent, Inc.
27  */
28 
29 /*
30  * Virtual Device Labels
31  * ---------------------
32  *
33  * The vdev label serves several distinct purposes:
34  *
35  *	1. Uniquely identify this device as part of a ZFS pool and confirm its
36  *	   identity within the pool.
37  *
38  *	2. Verify that all the devices given in a configuration are present
39  *         within the pool.
40  *
41  *	3. Determine the uberblock for the pool.
42  *
43  *	4. In case of an import operation, determine the configuration of the
44  *         toplevel vdev of which it is a part.
45  *
46  *	5. If an import operation cannot find all the devices in the pool,
47  *         provide enough information to the administrator to determine which
48  *         devices are missing.
49  *
50  * It is important to note that while the kernel is responsible for writing the
51  * label, it only consumes the information in the first three cases.  The
52  * latter information is only consumed in userland when determining the
53  * configuration to import a pool.
54  *
55  *
56  * Label Organization
57  * ------------------
58  *
59  * Before describing the contents of the label, it's important to understand how
60  * the labels are written and updated with respect to the uberblock.
61  *
62  * When the pool configuration is altered, either because it was newly created
63  * or a device was added, we want to update all the labels such that we can deal
64  * with fatal failure at any point.  To this end, each disk has two labels which
65  * are updated before and after the uberblock is synced.  Assuming we have
66  * labels and an uberblock with the following transaction groups:
67  *
68  *              L1          UB          L2
69  *           +------+    +------+    +------+
70  *           |      |    |      |    |      |
71  *           | t10  |    | t10  |    | t10  |
72  *           |      |    |      |    |      |
73  *           +------+    +------+    +------+
74  *
75  * In this stable state, the labels and the uberblock were all updated within
76  * the same transaction group (10).  Each label is mirrored and checksummed, so
77  * that we can detect when we fail partway through writing the label.
78  *
79  * In order to identify which labels are valid, the labels are written in the
80  * following manner:
81  *
82  *	1. For each vdev, update 'L1' to the new label
83  *	2. Update the uberblock
84  *	3. For each vdev, update 'L2' to the new label
85  *
86  * Given arbitrary failure, we can determine the correct label to use based on
87  * the transaction group.  If we fail after updating L1 but before updating the
88  * UB, we will notice that L1's transaction group is greater than the uberblock,
89  * so L2 must be valid.  If we fail after writing the uberblock but before
90  * writing L2, we will notice that L2's transaction group is less than L1, and
91  * therefore L1 is valid.
92  *
93  * Another added complexity is that not every label is updated when the config
94  * is synced.  If we add a single device, we do not want to have to re-write
95  * every label for every device in the pool.  This means that both L1 and L2 may
96  * be older than the pool uberblock, because the necessary information is stored
97  * on another vdev.
98  *
99  *
100  * On-disk Format
101  * --------------
102  *
103  * The vdev label consists of two distinct parts, and is wrapped within the
104  * vdev_label_t structure.  The label includes 8k of padding to permit legacy
105  * VTOC disk labels, but is otherwise ignored.
106  *
107  * The first half of the label is a packed nvlist which contains pool wide
108  * properties, per-vdev properties, and configuration information.  It is
109  * described in more detail below.
110  *
111  * The latter half of the label consists of a redundant array of uberblocks.
112  * These uberblocks are updated whenever a transaction group is committed,
113  * or when the configuration is updated.  When a pool is loaded, we scan each
114  * vdev for the 'best' uberblock.
115  *
116  *
117  * Configuration Information
118  * -------------------------
119  *
120  * The nvlist describing the pool and vdev contains the following elements:
121  *
122  *	version		ZFS on-disk version
123  *	name		Pool name
124  *	state		Pool state
125  *	txg		Transaction group in which this label was written
126  *	pool_guid	Unique identifier for this pool
127  *	vdev_tree	An nvlist describing vdev tree.
128  *	features_for_read
129  *			An nvlist of the features necessary for reading the MOS.
130  *
131  * Each leaf device label also contains the following:
132  *
133  *	top_guid	Unique ID for top-level vdev in which this is contained
134  *	guid		Unique ID for the leaf vdev
135  *
136  * The 'vs' configuration follows the format described in 'spa_config.c'.
137  */
138 
139 #include <sys/zfs_context.h>
140 #include <sys/spa.h>
141 #include <sys/spa_impl.h>
142 #include <sys/dmu.h>
143 #include <sys/zap.h>
144 #include <sys/vdev.h>
145 #include <sys/vdev_impl.h>
146 #include <sys/uberblock_impl.h>
147 #include <sys/metaslab.h>
148 #include <sys/metaslab_impl.h>
149 #include <sys/zio.h>
150 #include <sys/dsl_scan.h>
151 #include <sys/abd.h>
152 #include <sys/fs/zfs.h>
153 
154 /*
155  * Basic routines to read and write from a vdev label.
156  * Used throughout the rest of this file.
157  */
158 uint64_t
159 vdev_label_offset(uint64_t psize, int l, uint64_t offset)
160 {
161 	ASSERT(offset < sizeof (vdev_label_t));
162 	ASSERT(P2PHASE_TYPED(psize, sizeof (vdev_label_t), uint64_t) == 0);
163 
164 	return (offset + l * sizeof (vdev_label_t) + (l < VDEV_LABELS / 2 ?
165 	    0 : psize - VDEV_LABELS * sizeof (vdev_label_t)));
166 }
167 
168 /*
169  * Returns back the vdev label associated with the passed in offset.
170  */
171 int
172 vdev_label_number(uint64_t psize, uint64_t offset)
173 {
174 	int l;
175 
176 	if (offset >= psize - VDEV_LABEL_END_SIZE) {
177 		offset -= psize - VDEV_LABEL_END_SIZE;
178 		offset += (VDEV_LABELS / 2) * sizeof (vdev_label_t);
179 	}
180 	l = offset / sizeof (vdev_label_t);
181 	return (l < VDEV_LABELS ? l : -1);
182 }
183 
184 static void
185 vdev_label_read(zio_t *zio, vdev_t *vd, int l, abd_t *buf, uint64_t offset,
186     uint64_t size, zio_done_func_t *done, void *private, int flags)
187 {
188 	ASSERT(
189 	    spa_config_held(zio->io_spa, SCL_STATE, RW_READER) == SCL_STATE ||
190 	    spa_config_held(zio->io_spa, SCL_STATE, RW_WRITER) == SCL_STATE);
191 	ASSERT(flags & ZIO_FLAG_CONFIG_WRITER);
192 
193 	zio_nowait(zio_read_phys(zio, vd,
194 	    vdev_label_offset(vd->vdev_psize, l, offset),
195 	    size, buf, ZIO_CHECKSUM_LABEL, done, private,
196 	    ZIO_PRIORITY_SYNC_READ, flags, B_TRUE));
197 }
198 
199 void
200 vdev_label_write(zio_t *zio, vdev_t *vd, int l, abd_t *buf, uint64_t offset,
201     uint64_t size, zio_done_func_t *done, void *private, int flags)
202 {
203 	ASSERT(
204 	    spa_config_held(zio->io_spa, SCL_STATE, RW_READER) == SCL_STATE ||
205 	    spa_config_held(zio->io_spa, SCL_STATE, RW_WRITER) == SCL_STATE);
206 	ASSERT(flags & ZIO_FLAG_CONFIG_WRITER);
207 
208 	zio_nowait(zio_write_phys(zio, vd,
209 	    vdev_label_offset(vd->vdev_psize, l, offset),
210 	    size, buf, ZIO_CHECKSUM_LABEL, done, private,
211 	    ZIO_PRIORITY_SYNC_WRITE, flags, B_TRUE));
212 }
213 
214 static void
215 root_vdev_actions_getprogress(vdev_t *vd, nvlist_t *nvl)
216 {
217 	spa_t *spa = vd->vdev_spa;
218 
219 	if (vd != spa->spa_root_vdev)
220 		return;
221 
222 	/* provide either current or previous scan information */
223 	pool_scan_stat_t ps;
224 	if (spa_scan_get_stats(spa, &ps) == 0) {
225 		fnvlist_add_uint64_array(nvl,
226 		    ZPOOL_CONFIG_SCAN_STATS, (uint64_t *)&ps,
227 		    sizeof (pool_scan_stat_t) / sizeof (uint64_t));
228 	}
229 
230 	pool_removal_stat_t prs;
231 	if (spa_removal_get_stats(spa, &prs) == 0) {
232 		fnvlist_add_uint64_array(nvl,
233 		    ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t *)&prs,
234 		    sizeof (prs) / sizeof (uint64_t));
235 	}
236 
237 	pool_checkpoint_stat_t pcs;
238 	if (spa_checkpoint_get_stats(spa, &pcs) == 0) {
239 		fnvlist_add_uint64_array(nvl,
240 		    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t *)&pcs,
241 		    sizeof (pcs) / sizeof (uint64_t));
242 	}
243 }
244 
245 /*
246  * Generate the nvlist representing this vdev's config.
247  */
248 nvlist_t *
249 vdev_config_generate(spa_t *spa, vdev_t *vd, boolean_t getstats,
250     vdev_config_flag_t flags)
251 {
252 	nvlist_t *nv = NULL;
253 	vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
254 
255 	nv = fnvlist_alloc();
256 
257 	fnvlist_add_string(nv, ZPOOL_CONFIG_TYPE, vd->vdev_ops->vdev_op_type);
258 	if (!(flags & (VDEV_CONFIG_SPARE | VDEV_CONFIG_L2CACHE)))
259 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_ID, vd->vdev_id);
260 	fnvlist_add_uint64(nv, ZPOOL_CONFIG_GUID, vd->vdev_guid);
261 
262 	if (vd->vdev_path != NULL)
263 		fnvlist_add_string(nv, ZPOOL_CONFIG_PATH, vd->vdev_path);
264 
265 	if (vd->vdev_devid != NULL)
266 		fnvlist_add_string(nv, ZPOOL_CONFIG_DEVID, vd->vdev_devid);
267 
268 	if (vd->vdev_physpath != NULL)
269 		fnvlist_add_string(nv, ZPOOL_CONFIG_PHYS_PATH,
270 		    vd->vdev_physpath);
271 
272 	if (vd->vdev_fru != NULL)
273 		fnvlist_add_string(nv, ZPOOL_CONFIG_FRU, vd->vdev_fru);
274 
275 	if (vd->vdev_nparity != 0) {
276 		ASSERT(strcmp(vd->vdev_ops->vdev_op_type,
277 		    VDEV_TYPE_RAIDZ) == 0);
278 
279 		/*
280 		 * Make sure someone hasn't managed to sneak a fancy new vdev
281 		 * into a crufty old storage pool.
282 		 */
283 		ASSERT(vd->vdev_nparity == 1 ||
284 		    (vd->vdev_nparity <= 2 &&
285 		    spa_version(spa) >= SPA_VERSION_RAIDZ2) ||
286 		    (vd->vdev_nparity <= 3 &&
287 		    spa_version(spa) >= SPA_VERSION_RAIDZ3));
288 
289 		/*
290 		 * Note that we'll add the nparity tag even on storage pools
291 		 * that only support a single parity device -- older software
292 		 * will just ignore it.
293 		 */
294 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_NPARITY, vd->vdev_nparity);
295 	}
296 
297 	if (vd->vdev_wholedisk != -1ULL)
298 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
299 		    vd->vdev_wholedisk);
300 
301 	if (vd->vdev_not_present && !(flags & VDEV_CONFIG_MISSING))
302 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT, 1);
303 
304 	if (vd->vdev_isspare)
305 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_IS_SPARE, 1);
306 
307 	if (!(flags & (VDEV_CONFIG_SPARE | VDEV_CONFIG_L2CACHE)) &&
308 	    vd == vd->vdev_top) {
309 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
310 		    vd->vdev_ms_array);
311 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
312 		    vd->vdev_ms_shift);
313 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_ASHIFT, vd->vdev_ashift);
314 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_ASIZE,
315 		    vd->vdev_asize);
316 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_IS_LOG, vd->vdev_islog);
317 		if (vd->vdev_removing) {
318 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_REMOVING,
319 			    vd->vdev_removing);
320 		}
321 
322 		/* zpool command expects alloc class data */
323 		if (getstats && vd->vdev_alloc_bias != VDEV_BIAS_NONE) {
324 			const char *bias = NULL;
325 
326 			switch (vd->vdev_alloc_bias) {
327 			case VDEV_BIAS_LOG:
328 				bias = VDEV_ALLOC_BIAS_LOG;
329 				break;
330 			case VDEV_BIAS_SPECIAL:
331 				bias = VDEV_ALLOC_BIAS_SPECIAL;
332 				break;
333 			case VDEV_BIAS_DEDUP:
334 				bias = VDEV_ALLOC_BIAS_DEDUP;
335 				break;
336 			default:
337 				ASSERT3U(vd->vdev_alloc_bias, ==,
338 				    VDEV_BIAS_NONE);
339 			}
340 			fnvlist_add_string(nv, ZPOOL_CONFIG_ALLOCATION_BIAS,
341 			    bias);
342 		}
343 	}
344 
345 	if (vd->vdev_dtl_sm != NULL) {
346 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_DTL,
347 		    space_map_object(vd->vdev_dtl_sm));
348 	}
349 
350 	if (vic->vic_mapping_object != 0) {
351 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_INDIRECT_OBJECT,
352 		    vic->vic_mapping_object);
353 	}
354 
355 	if (vic->vic_births_object != 0) {
356 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_INDIRECT_BIRTHS,
357 		    vic->vic_births_object);
358 	}
359 
360 	if (vic->vic_prev_indirect_vdev != UINT64_MAX) {
361 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_PREV_INDIRECT_VDEV,
362 		    vic->vic_prev_indirect_vdev);
363 	}
364 
365 	if (vd->vdev_crtxg)
366 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_CREATE_TXG, vd->vdev_crtxg);
367 
368 	if (flags & VDEV_CONFIG_MOS) {
369 		if (vd->vdev_leaf_zap != 0) {
370 			ASSERT(vd->vdev_ops->vdev_op_leaf);
371 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_VDEV_LEAF_ZAP,
372 			    vd->vdev_leaf_zap);
373 		}
374 
375 		if (vd->vdev_top_zap != 0) {
376 			ASSERT(vd == vd->vdev_top);
377 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_VDEV_TOP_ZAP,
378 			    vd->vdev_top_zap);
379 		}
380 	}
381 
382 	if (getstats) {
383 		vdev_stat_t vs;
384 
385 		vdev_get_stats(vd, &vs);
386 		fnvlist_add_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
387 		    (uint64_t *)&vs, sizeof (vs) / sizeof (uint64_t));
388 
389 		root_vdev_actions_getprogress(vd, nv);
390 
391 		/*
392 		 * Note: this can be called from open context
393 		 * (spa_get_stats()), so we need the rwlock to prevent
394 		 * the mapping from being changed by condensing.
395 		 */
396 		rw_enter(&vd->vdev_indirect_rwlock, RW_READER);
397 		if (vd->vdev_indirect_mapping != NULL) {
398 			ASSERT(vd->vdev_indirect_births != NULL);
399 			vdev_indirect_mapping_t *vim =
400 			    vd->vdev_indirect_mapping;
401 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_INDIRECT_SIZE,
402 			    vdev_indirect_mapping_size(vim));
403 		}
404 		rw_exit(&vd->vdev_indirect_rwlock);
405 		if (vd->vdev_mg != NULL &&
406 		    vd->vdev_mg->mg_fragmentation != ZFS_FRAG_INVALID) {
407 			/*
408 			 * Compute approximately how much memory would be used
409 			 * for the indirect mapping if this device were to
410 			 * be removed.
411 			 *
412 			 * Note: If the frag metric is invalid, then not
413 			 * enough metaslabs have been converted to have
414 			 * histograms.
415 			 */
416 			uint64_t seg_count = 0;
417 			uint64_t to_alloc = vd->vdev_stat.vs_alloc;
418 
419 			/*
420 			 * There are the same number of allocated segments
421 			 * as free segments, so we will have at least one
422 			 * entry per free segment.  However, small free
423 			 * segments (smaller than vdev_removal_max_span)
424 			 * will be combined with adjacent allocated segments
425 			 * as a single mapping.
426 			 */
427 			for (int i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++) {
428 				if (1ULL << (i + 1) < vdev_removal_max_span) {
429 					to_alloc +=
430 					    vd->vdev_mg->mg_histogram[i] <<
431 					    i + 1;
432 				} else {
433 					seg_count +=
434 					    vd->vdev_mg->mg_histogram[i];
435 				}
436 			}
437 
438 			/*
439 			 * The maximum length of a mapping is
440 			 * zfs_remove_max_segment, so we need at least one entry
441 			 * per zfs_remove_max_segment of allocated data.
442 			 */
443 			seg_count += to_alloc / zfs_remove_max_segment;
444 
445 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_INDIRECT_SIZE,
446 			    seg_count *
447 			    sizeof (vdev_indirect_mapping_entry_phys_t));
448 		}
449 	}
450 
451 	if (!vd->vdev_ops->vdev_op_leaf) {
452 		nvlist_t **child;
453 		int c, idx;
454 
455 		ASSERT(!vd->vdev_ishole);
456 
457 		child = kmem_alloc(vd->vdev_children * sizeof (nvlist_t *),
458 		    KM_SLEEP);
459 
460 		for (c = 0, idx = 0; c < vd->vdev_children; c++) {
461 			vdev_t *cvd = vd->vdev_child[c];
462 
463 			/*
464 			 * If we're generating an nvlist of removing
465 			 * vdevs then skip over any device which is
466 			 * not being removed.
467 			 */
468 			if ((flags & VDEV_CONFIG_REMOVING) &&
469 			    !cvd->vdev_removing)
470 				continue;
471 
472 			child[idx++] = vdev_config_generate(spa, cvd,
473 			    getstats, flags);
474 		}
475 
476 		if (idx) {
477 			fnvlist_add_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
478 			    child, idx);
479 		}
480 
481 		for (c = 0; c < idx; c++)
482 			nvlist_free(child[c]);
483 
484 		kmem_free(child, vd->vdev_children * sizeof (nvlist_t *));
485 
486 	} else {
487 		const char *aux = NULL;
488 
489 		if (vd->vdev_offline && !vd->vdev_tmpoffline)
490 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_OFFLINE, B_TRUE);
491 		if (vd->vdev_resilver_txg != 0)
492 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_RESILVER_TXG,
493 			    vd->vdev_resilver_txg);
494 		if (vd->vdev_faulted)
495 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_FAULTED, B_TRUE);
496 		if (vd->vdev_degraded)
497 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_DEGRADED, B_TRUE);
498 		if (vd->vdev_removed)
499 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_REMOVED, B_TRUE);
500 		if (vd->vdev_unspare)
501 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_UNSPARE, B_TRUE);
502 		if (vd->vdev_ishole)
503 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_IS_HOLE, B_TRUE);
504 
505 		switch (vd->vdev_stat.vs_aux) {
506 		case VDEV_AUX_ERR_EXCEEDED:
507 			aux = "err_exceeded";
508 			break;
509 
510 		case VDEV_AUX_EXTERNAL:
511 			aux = "external";
512 			break;
513 		}
514 
515 		if (aux != NULL)
516 			fnvlist_add_string(nv, ZPOOL_CONFIG_AUX_STATE, aux);
517 
518 		if (vd->vdev_splitting && vd->vdev_orig_guid != 0LL) {
519 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_ORIG_GUID,
520 			    vd->vdev_orig_guid);
521 		}
522 	}
523 
524 	return (nv);
525 }
526 
527 /*
528  * Generate a view of the top-level vdevs.  If we currently have holes
529  * in the namespace, then generate an array which contains a list of holey
530  * vdevs.  Additionally, add the number of top-level children that currently
531  * exist.
532  */
533 void
534 vdev_top_config_generate(spa_t *spa, nvlist_t *config)
535 {
536 	vdev_t *rvd = spa->spa_root_vdev;
537 	uint64_t *array;
538 	uint_t c, idx;
539 
540 	array = kmem_alloc(rvd->vdev_children * sizeof (uint64_t), KM_SLEEP);
541 
542 	for (c = 0, idx = 0; c < rvd->vdev_children; c++) {
543 		vdev_t *tvd = rvd->vdev_child[c];
544 
545 		if (tvd->vdev_ishole) {
546 			array[idx++] = c;
547 		}
548 	}
549 
550 	if (idx) {
551 		VERIFY(nvlist_add_uint64_array(config, ZPOOL_CONFIG_HOLE_ARRAY,
552 		    array, idx) == 0);
553 	}
554 
555 	VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VDEV_CHILDREN,
556 	    rvd->vdev_children) == 0);
557 
558 	kmem_free(array, rvd->vdev_children * sizeof (uint64_t));
559 }
560 
561 /*
562  * Returns the configuration from the label of the given vdev. For vdevs
563  * which don't have a txg value stored on their label (i.e. spares/cache)
564  * or have not been completely initialized (txg = 0) just return
565  * the configuration from the first valid label we find. Otherwise,
566  * find the most up-to-date label that does not exceed the specified
567  * 'txg' value.
568  */
569 nvlist_t *
570 vdev_label_read_config(vdev_t *vd, uint64_t txg)
571 {
572 	spa_t *spa = vd->vdev_spa;
573 	nvlist_t *config = NULL;
574 	vdev_phys_t *vp;
575 	abd_t *vp_abd;
576 	zio_t *zio;
577 	uint64_t best_txg = 0;
578 	uint64_t label_txg = 0;
579 	int error = 0;
580 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
581 	    ZIO_FLAG_SPECULATIVE;
582 
583 	ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
584 
585 	if (!vdev_readable(vd))
586 		return (NULL);
587 
588 	vp_abd = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
589 	vp = abd_to_buf(vp_abd);
590 
591 retry:
592 	for (int l = 0; l < VDEV_LABELS; l++) {
593 		nvlist_t *label = NULL;
594 
595 		zio = zio_root(spa, NULL, NULL, flags);
596 
597 		vdev_label_read(zio, vd, l, vp_abd,
598 		    offsetof(vdev_label_t, vl_vdev_phys),
599 		    sizeof (vdev_phys_t), NULL, NULL, flags);
600 
601 		if (zio_wait(zio) == 0 &&
602 		    nvlist_unpack(vp->vp_nvlist, sizeof (vp->vp_nvlist),
603 		    &label, 0) == 0) {
604 			/*
605 			 * Auxiliary vdevs won't have txg values in their
606 			 * labels and newly added vdevs may not have been
607 			 * completely initialized so just return the
608 			 * configuration from the first valid label we
609 			 * encounter.
610 			 */
611 			error = nvlist_lookup_uint64(label,
612 			    ZPOOL_CONFIG_POOL_TXG, &label_txg);
613 			if ((error || label_txg == 0) && !config) {
614 				config = label;
615 				break;
616 			} else if (label_txg <= txg && label_txg > best_txg) {
617 				best_txg = label_txg;
618 				nvlist_free(config);
619 				config = fnvlist_dup(label);
620 			}
621 		}
622 
623 		if (label != NULL) {
624 			nvlist_free(label);
625 			label = NULL;
626 		}
627 	}
628 
629 	if (config == NULL && !(flags & ZIO_FLAG_TRYHARD)) {
630 		flags |= ZIO_FLAG_TRYHARD;
631 		goto retry;
632 	}
633 
634 	/*
635 	 * We found a valid label but it didn't pass txg restrictions.
636 	 */
637 	if (config == NULL && label_txg != 0) {
638 		vdev_dbgmsg(vd, "label discarded as txg is too large "
639 		    "(%llu > %llu)", (u_longlong_t)label_txg,
640 		    (u_longlong_t)txg);
641 	}
642 
643 	abd_free(vp_abd);
644 
645 	return (config);
646 }
647 
648 /*
649  * Determine if a device is in use.  The 'spare_guid' parameter will be filled
650  * in with the device guid if this spare is active elsewhere on the system.
651  */
652 static boolean_t
653 vdev_inuse(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason,
654     uint64_t *spare_guid, uint64_t *l2cache_guid)
655 {
656 	spa_t *spa = vd->vdev_spa;
657 	uint64_t state, pool_guid, device_guid, txg, spare_pool;
658 	uint64_t vdtxg = 0;
659 	nvlist_t *label;
660 
661 	if (spare_guid)
662 		*spare_guid = 0ULL;
663 	if (l2cache_guid)
664 		*l2cache_guid = 0ULL;
665 
666 	/*
667 	 * Read the label, if any, and perform some basic sanity checks.
668 	 */
669 	if ((label = vdev_label_read_config(vd, -1ULL)) == NULL)
670 		return (B_FALSE);
671 
672 	(void) nvlist_lookup_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
673 	    &vdtxg);
674 
675 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
676 	    &state) != 0 ||
677 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
678 	    &device_guid) != 0) {
679 		nvlist_free(label);
680 		return (B_FALSE);
681 	}
682 
683 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
684 	    (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID,
685 	    &pool_guid) != 0 ||
686 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
687 	    &txg) != 0)) {
688 		nvlist_free(label);
689 		return (B_FALSE);
690 	}
691 
692 	nvlist_free(label);
693 
694 	/*
695 	 * Check to see if this device indeed belongs to the pool it claims to
696 	 * be a part of.  The only way this is allowed is if the device is a hot
697 	 * spare (which we check for later on).
698 	 */
699 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
700 	    !spa_guid_exists(pool_guid, device_guid) &&
701 	    !spa_spare_exists(device_guid, NULL, NULL) &&
702 	    !spa_l2cache_exists(device_guid, NULL))
703 		return (B_FALSE);
704 
705 	/*
706 	 * If the transaction group is zero, then this an initialized (but
707 	 * unused) label.  This is only an error if the create transaction
708 	 * on-disk is the same as the one we're using now, in which case the
709 	 * user has attempted to add the same vdev multiple times in the same
710 	 * transaction.
711 	 */
712 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
713 	    txg == 0 && vdtxg == crtxg)
714 		return (B_TRUE);
715 
716 	/*
717 	 * Check to see if this is a spare device.  We do an explicit check for
718 	 * spa_has_spare() here because it may be on our pending list of spares
719 	 * to add.  We also check if it is an l2cache device.
720 	 */
721 	if (spa_spare_exists(device_guid, &spare_pool, NULL) ||
722 	    spa_has_spare(spa, device_guid)) {
723 		if (spare_guid)
724 			*spare_guid = device_guid;
725 
726 		switch (reason) {
727 		case VDEV_LABEL_CREATE:
728 		case VDEV_LABEL_L2CACHE:
729 			return (B_TRUE);
730 
731 		case VDEV_LABEL_REPLACE:
732 			return (!spa_has_spare(spa, device_guid) ||
733 			    spare_pool != 0ULL);
734 
735 		case VDEV_LABEL_SPARE:
736 			return (spa_has_spare(spa, device_guid));
737 		}
738 	}
739 
740 	/*
741 	 * Check to see if this is an l2cache device.
742 	 */
743 	if (spa_l2cache_exists(device_guid, NULL))
744 		return (B_TRUE);
745 
746 	/*
747 	 * We can't rely on a pool's state if it's been imported
748 	 * read-only.  Instead we look to see if the pools is marked
749 	 * read-only in the namespace and set the state to active.
750 	 */
751 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
752 	    (spa = spa_by_guid(pool_guid, device_guid)) != NULL &&
753 	    spa_mode(spa) == FREAD)
754 		state = POOL_STATE_ACTIVE;
755 
756 	/*
757 	 * If the device is marked ACTIVE, then this device is in use by another
758 	 * pool on the system.
759 	 */
760 	return (state == POOL_STATE_ACTIVE);
761 }
762 
763 /*
764  * Initialize a vdev label.  We check to make sure each leaf device is not in
765  * use, and writable.  We put down an initial label which we will later
766  * overwrite with a complete label.  Note that it's important to do this
767  * sequentially, not in parallel, so that we catch cases of multiple use of the
768  * same leaf vdev in the vdev we're creating -- e.g. mirroring a disk with
769  * itself.
770  */
771 int
772 vdev_label_init(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason)
773 {
774 	spa_t *spa = vd->vdev_spa;
775 	nvlist_t *label;
776 	vdev_phys_t *vp;
777 	abd_t *vp_abd;
778 	abd_t *pad2;
779 	uberblock_t *ub;
780 	abd_t *ub_abd;
781 	zio_t *zio;
782 	char *buf;
783 	size_t buflen;
784 	int error;
785 	uint64_t spare_guid, l2cache_guid;
786 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL;
787 
788 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
789 
790 	for (int c = 0; c < vd->vdev_children; c++)
791 		if ((error = vdev_label_init(vd->vdev_child[c],
792 		    crtxg, reason)) != 0)
793 			return (error);
794 
795 	/* Track the creation time for this vdev */
796 	vd->vdev_crtxg = crtxg;
797 
798 	if (!vd->vdev_ops->vdev_op_leaf || !spa_writeable(spa))
799 		return (0);
800 
801 	/*
802 	 * Dead vdevs cannot be initialized.
803 	 */
804 	if (vdev_is_dead(vd))
805 		return (SET_ERROR(EIO));
806 
807 	/*
808 	 * Determine if the vdev is in use.
809 	 */
810 	if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_SPLIT &&
811 	    vdev_inuse(vd, crtxg, reason, &spare_guid, &l2cache_guid))
812 		return (SET_ERROR(EBUSY));
813 
814 	/*
815 	 * If this is a request to add or replace a spare or l2cache device
816 	 * that is in use elsewhere on the system, then we must update the
817 	 * guid (which was initialized to a random value) to reflect the
818 	 * actual GUID (which is shared between multiple pools).
819 	 */
820 	if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_L2CACHE &&
821 	    spare_guid != 0ULL) {
822 		uint64_t guid_delta = spare_guid - vd->vdev_guid;
823 
824 		vd->vdev_guid += guid_delta;
825 
826 		for (vdev_t *pvd = vd; pvd != NULL; pvd = pvd->vdev_parent)
827 			pvd->vdev_guid_sum += guid_delta;
828 
829 		/*
830 		 * If this is a replacement, then we want to fallthrough to the
831 		 * rest of the code.  If we're adding a spare, then it's already
832 		 * labeled appropriately and we can just return.
833 		 */
834 		if (reason == VDEV_LABEL_SPARE)
835 			return (0);
836 		ASSERT(reason == VDEV_LABEL_REPLACE ||
837 		    reason == VDEV_LABEL_SPLIT);
838 	}
839 
840 	if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_SPARE &&
841 	    l2cache_guid != 0ULL) {
842 		uint64_t guid_delta = l2cache_guid - vd->vdev_guid;
843 
844 		vd->vdev_guid += guid_delta;
845 
846 		for (vdev_t *pvd = vd; pvd != NULL; pvd = pvd->vdev_parent)
847 			pvd->vdev_guid_sum += guid_delta;
848 
849 		/*
850 		 * If this is a replacement, then we want to fallthrough to the
851 		 * rest of the code.  If we're adding an l2cache, then it's
852 		 * already labeled appropriately and we can just return.
853 		 */
854 		if (reason == VDEV_LABEL_L2CACHE)
855 			return (0);
856 		ASSERT(reason == VDEV_LABEL_REPLACE);
857 	}
858 
859 	/*
860 	 * Initialize its label.
861 	 */
862 	vp_abd = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
863 	abd_zero(vp_abd, sizeof (vdev_phys_t));
864 	vp = abd_to_buf(vp_abd);
865 
866 	/*
867 	 * Generate a label describing the pool and our top-level vdev.
868 	 * We mark it as being from txg 0 to indicate that it's not
869 	 * really part of an active pool just yet.  The labels will
870 	 * be written again with a meaningful txg by spa_sync().
871 	 */
872 	if (reason == VDEV_LABEL_SPARE ||
873 	    (reason == VDEV_LABEL_REMOVE && vd->vdev_isspare)) {
874 		/*
875 		 * For inactive hot spares, we generate a special label that
876 		 * identifies as a mutually shared hot spare.  We write the
877 		 * label if we are adding a hot spare, or if we are removing an
878 		 * active hot spare (in which case we want to revert the
879 		 * labels).
880 		 */
881 		VERIFY(nvlist_alloc(&label, NV_UNIQUE_NAME, KM_SLEEP) == 0);
882 
883 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_VERSION,
884 		    spa_version(spa)) == 0);
885 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_POOL_STATE,
886 		    POOL_STATE_SPARE) == 0);
887 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_GUID,
888 		    vd->vdev_guid) == 0);
889 	} else if (reason == VDEV_LABEL_L2CACHE ||
890 	    (reason == VDEV_LABEL_REMOVE && vd->vdev_isl2cache)) {
891 		/*
892 		 * For level 2 ARC devices, add a special label.
893 		 */
894 		VERIFY(nvlist_alloc(&label, NV_UNIQUE_NAME, KM_SLEEP) == 0);
895 
896 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_VERSION,
897 		    spa_version(spa)) == 0);
898 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_POOL_STATE,
899 		    POOL_STATE_L2CACHE) == 0);
900 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_GUID,
901 		    vd->vdev_guid) == 0);
902 	} else {
903 		uint64_t txg = 0ULL;
904 
905 		if (reason == VDEV_LABEL_SPLIT)
906 			txg = spa->spa_uberblock.ub_txg;
907 		label = spa_config_generate(spa, vd, txg, B_FALSE);
908 
909 		/*
910 		 * Add our creation time.  This allows us to detect multiple
911 		 * vdev uses as described above, and automatically expires if we
912 		 * fail.
913 		 */
914 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
915 		    crtxg) == 0);
916 	}
917 
918 	buf = vp->vp_nvlist;
919 	buflen = sizeof (vp->vp_nvlist);
920 
921 	error = nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP);
922 	if (error != 0) {
923 		nvlist_free(label);
924 		abd_free(vp_abd);
925 		/* EFAULT means nvlist_pack ran out of room */
926 		return (error == EFAULT ? ENAMETOOLONG : EINVAL);
927 	}
928 
929 	/*
930 	 * Initialize uberblock template.
931 	 */
932 	ub_abd = abd_alloc_linear(VDEV_UBERBLOCK_RING, B_TRUE);
933 	abd_zero(ub_abd, VDEV_UBERBLOCK_RING);
934 	abd_copy_from_buf(ub_abd, &spa->spa_uberblock, sizeof (uberblock_t));
935 	ub = abd_to_buf(ub_abd);
936 	ub->ub_txg = 0;
937 
938 	/* Initialize the 2nd padding area. */
939 	pad2 = abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE);
940 	abd_zero(pad2, VDEV_PAD_SIZE);
941 
942 	/*
943 	 * Write everything in parallel.
944 	 */
945 retry:
946 	zio = zio_root(spa, NULL, NULL, flags);
947 
948 	for (int l = 0; l < VDEV_LABELS; l++) {
949 
950 		vdev_label_write(zio, vd, l, vp_abd,
951 		    offsetof(vdev_label_t, vl_vdev_phys),
952 		    sizeof (vdev_phys_t), NULL, NULL, flags);
953 
954 		/*
955 		 * Skip the 1st padding area.
956 		 * Zero out the 2nd padding area where it might have
957 		 * left over data from previous filesystem format.
958 		 */
959 		vdev_label_write(zio, vd, l, pad2,
960 		    offsetof(vdev_label_t, vl_pad2),
961 		    VDEV_PAD_SIZE, NULL, NULL, flags);
962 
963 		vdev_label_write(zio, vd, l, ub_abd,
964 		    offsetof(vdev_label_t, vl_uberblock),
965 		    VDEV_UBERBLOCK_RING, NULL, NULL, flags);
966 	}
967 
968 	error = zio_wait(zio);
969 
970 	if (error != 0 && !(flags & ZIO_FLAG_TRYHARD)) {
971 		flags |= ZIO_FLAG_TRYHARD;
972 		goto retry;
973 	}
974 
975 	nvlist_free(label);
976 	abd_free(pad2);
977 	abd_free(ub_abd);
978 	abd_free(vp_abd);
979 
980 	/*
981 	 * If this vdev hasn't been previously identified as a spare, then we
982 	 * mark it as such only if a) we are labeling it as a spare, or b) it
983 	 * exists as a spare elsewhere in the system.  Do the same for
984 	 * level 2 ARC devices.
985 	 */
986 	if (error == 0 && !vd->vdev_isspare &&
987 	    (reason == VDEV_LABEL_SPARE ||
988 	    spa_spare_exists(vd->vdev_guid, NULL, NULL)))
989 		spa_spare_add(vd);
990 
991 	if (error == 0 && !vd->vdev_isl2cache &&
992 	    (reason == VDEV_LABEL_L2CACHE ||
993 	    spa_l2cache_exists(vd->vdev_guid, NULL)))
994 		spa_l2cache_add(vd);
995 
996 	return (error);
997 }
998 
999 /*
1000  * ==========================================================================
1001  * uberblock load/sync
1002  * ==========================================================================
1003  */
1004 
1005 /*
1006  * Consider the following situation: txg is safely synced to disk.  We've
1007  * written the first uberblock for txg + 1, and then we lose power.  When we
1008  * come back up, we fail to see the uberblock for txg + 1 because, say,
1009  * it was on a mirrored device and the replica to which we wrote txg + 1
1010  * is now offline.  If we then make some changes and sync txg + 1, and then
1011  * the missing replica comes back, then for a few seconds we'll have two
1012  * conflicting uberblocks on disk with the same txg.  The solution is simple:
1013  * among uberblocks with equal txg, choose the one with the latest timestamp.
1014  */
1015 static int
1016 vdev_uberblock_compare(const uberblock_t *ub1, const uberblock_t *ub2)
1017 {
1018 	int cmp = AVL_CMP(ub1->ub_txg, ub2->ub_txg);
1019 	if (likely(cmp))
1020 		return (cmp);
1021 
1022 	return (AVL_CMP(ub1->ub_timestamp, ub2->ub_timestamp));
1023 }
1024 
1025 struct ubl_cbdata {
1026 	uberblock_t	*ubl_ubbest;	/* Best uberblock */
1027 	vdev_t		*ubl_vd;	/* vdev associated with the above */
1028 };
1029 
1030 static void
1031 vdev_uberblock_load_done(zio_t *zio)
1032 {
1033 	vdev_t *vd = zio->io_vd;
1034 	spa_t *spa = zio->io_spa;
1035 	zio_t *rio = zio->io_private;
1036 	uberblock_t *ub = abd_to_buf(zio->io_abd);
1037 	struct ubl_cbdata *cbp = rio->io_private;
1038 
1039 	ASSERT3U(zio->io_size, ==, VDEV_UBERBLOCK_SIZE(vd));
1040 
1041 	if (zio->io_error == 0 && uberblock_verify(ub) == 0) {
1042 		mutex_enter(&rio->io_lock);
1043 		if (ub->ub_txg <= spa->spa_load_max_txg &&
1044 		    vdev_uberblock_compare(ub, cbp->ubl_ubbest) > 0) {
1045 			/*
1046 			 * Keep track of the vdev in which this uberblock
1047 			 * was found. We will use this information later
1048 			 * to obtain the config nvlist associated with
1049 			 * this uberblock.
1050 			 */
1051 			*cbp->ubl_ubbest = *ub;
1052 			cbp->ubl_vd = vd;
1053 		}
1054 		mutex_exit(&rio->io_lock);
1055 	}
1056 
1057 	abd_free(zio->io_abd);
1058 }
1059 
1060 static void
1061 vdev_uberblock_load_impl(zio_t *zio, vdev_t *vd, int flags,
1062     struct ubl_cbdata *cbp)
1063 {
1064 	for (int c = 0; c < vd->vdev_children; c++)
1065 		vdev_uberblock_load_impl(zio, vd->vdev_child[c], flags, cbp);
1066 
1067 	if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd)) {
1068 		for (int l = 0; l < VDEV_LABELS; l++) {
1069 			for (int n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
1070 				vdev_label_read(zio, vd, l,
1071 				    abd_alloc_linear(VDEV_UBERBLOCK_SIZE(vd),
1072 				    B_TRUE), VDEV_UBERBLOCK_OFFSET(vd, n),
1073 				    VDEV_UBERBLOCK_SIZE(vd),
1074 				    vdev_uberblock_load_done, zio, flags);
1075 			}
1076 		}
1077 	}
1078 }
1079 
1080 /*
1081  * Reads the 'best' uberblock from disk along with its associated
1082  * configuration. First, we read the uberblock array of each label of each
1083  * vdev, keeping track of the uberblock with the highest txg in each array.
1084  * Then, we read the configuration from the same vdev as the best uberblock.
1085  */
1086 void
1087 vdev_uberblock_load(vdev_t *rvd, uberblock_t *ub, nvlist_t **config)
1088 {
1089 	zio_t *zio;
1090 	spa_t *spa = rvd->vdev_spa;
1091 	struct ubl_cbdata cb;
1092 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
1093 	    ZIO_FLAG_SPECULATIVE | ZIO_FLAG_TRYHARD;
1094 
1095 	ASSERT(ub);
1096 	ASSERT(config);
1097 
1098 	bzero(ub, sizeof (uberblock_t));
1099 	*config = NULL;
1100 
1101 	cb.ubl_ubbest = ub;
1102 	cb.ubl_vd = NULL;
1103 
1104 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1105 	zio = zio_root(spa, NULL, &cb, flags);
1106 	vdev_uberblock_load_impl(zio, rvd, flags, &cb);
1107 	(void) zio_wait(zio);
1108 
1109 	/*
1110 	 * It's possible that the best uberblock was discovered on a label
1111 	 * that has a configuration which was written in a future txg.
1112 	 * Search all labels on this vdev to find the configuration that
1113 	 * matches the txg for our uberblock.
1114 	 */
1115 	if (cb.ubl_vd != NULL) {
1116 		vdev_dbgmsg(cb.ubl_vd, "best uberblock found for spa %s. "
1117 		    "txg %llu", spa->spa_name, (u_longlong_t)ub->ub_txg);
1118 
1119 		*config = vdev_label_read_config(cb.ubl_vd, ub->ub_txg);
1120 		if (*config == NULL && spa->spa_extreme_rewind) {
1121 			vdev_dbgmsg(cb.ubl_vd, "failed to read label config. "
1122 			    "Trying again without txg restrictions.");
1123 			*config = vdev_label_read_config(cb.ubl_vd, UINT64_MAX);
1124 		}
1125 		if (*config == NULL) {
1126 			vdev_dbgmsg(cb.ubl_vd, "failed to read label config");
1127 		}
1128 	}
1129 	spa_config_exit(spa, SCL_ALL, FTAG);
1130 }
1131 
1132 /*
1133  * On success, increment root zio's count of good writes.
1134  * We only get credit for writes to known-visible vdevs; see spa_vdev_add().
1135  */
1136 static void
1137 vdev_uberblock_sync_done(zio_t *zio)
1138 {
1139 	uint64_t *good_writes = zio->io_private;
1140 
1141 	if (zio->io_error == 0 && zio->io_vd->vdev_top->vdev_ms_array != 0)
1142 		atomic_inc_64(good_writes);
1143 }
1144 
1145 /*
1146  * Write the uberblock to all labels of all leaves of the specified vdev.
1147  */
1148 static void
1149 vdev_uberblock_sync(zio_t *zio, uint64_t *good_writes,
1150     uberblock_t *ub, vdev_t *vd, int flags)
1151 {
1152 	for (uint64_t c = 0; c < vd->vdev_children; c++) {
1153 		vdev_uberblock_sync(zio, good_writes,
1154 		    ub, vd->vdev_child[c], flags);
1155 	}
1156 
1157 	if (!vd->vdev_ops->vdev_op_leaf)
1158 		return;
1159 
1160 	if (!vdev_writeable(vd))
1161 		return;
1162 
1163 	int m = spa_multihost(vd->vdev_spa) ? MMP_BLOCKS_PER_LABEL : 0;
1164 	int n = ub->ub_txg % (VDEV_UBERBLOCK_COUNT(vd) - m);
1165 
1166 	/* Copy the uberblock_t into the ABD */
1167 	abd_t *ub_abd = abd_alloc_for_io(VDEV_UBERBLOCK_SIZE(vd), B_TRUE);
1168 	abd_zero(ub_abd, VDEV_UBERBLOCK_SIZE(vd));
1169 	abd_copy_from_buf(ub_abd, ub, sizeof (uberblock_t));
1170 
1171 	for (int l = 0; l < VDEV_LABELS; l++)
1172 		vdev_label_write(zio, vd, l, ub_abd,
1173 		    VDEV_UBERBLOCK_OFFSET(vd, n), VDEV_UBERBLOCK_SIZE(vd),
1174 		    vdev_uberblock_sync_done, good_writes,
1175 		    flags | ZIO_FLAG_DONT_PROPAGATE);
1176 
1177 	abd_free(ub_abd);
1178 }
1179 
1180 /* Sync the uberblocks to all vdevs in svd[] */
1181 int
1182 vdev_uberblock_sync_list(vdev_t **svd, int svdcount, uberblock_t *ub, int flags)
1183 {
1184 	spa_t *spa = svd[0]->vdev_spa;
1185 	zio_t *zio;
1186 	uint64_t good_writes = 0;
1187 
1188 	zio = zio_root(spa, NULL, NULL, flags);
1189 
1190 	for (int v = 0; v < svdcount; v++)
1191 		vdev_uberblock_sync(zio, &good_writes, ub, svd[v], flags);
1192 
1193 	(void) zio_wait(zio);
1194 
1195 	/*
1196 	 * Flush the uberblocks to disk.  This ensures that the odd labels
1197 	 * are no longer needed (because the new uberblocks and the even
1198 	 * labels are safely on disk), so it is safe to overwrite them.
1199 	 */
1200 	zio = zio_root(spa, NULL, NULL, flags);
1201 
1202 	for (int v = 0; v < svdcount; v++) {
1203 		if (vdev_writeable(svd[v])) {
1204 			zio_flush(zio, svd[v]);
1205 		}
1206 	}
1207 
1208 	(void) zio_wait(zio);
1209 
1210 	return (good_writes >= 1 ? 0 : EIO);
1211 }
1212 
1213 /*
1214  * On success, increment the count of good writes for our top-level vdev.
1215  */
1216 static void
1217 vdev_label_sync_done(zio_t *zio)
1218 {
1219 	uint64_t *good_writes = zio->io_private;
1220 
1221 	if (zio->io_error == 0)
1222 		atomic_inc_64(good_writes);
1223 }
1224 
1225 /*
1226  * If there weren't enough good writes, indicate failure to the parent.
1227  */
1228 static void
1229 vdev_label_sync_top_done(zio_t *zio)
1230 {
1231 	uint64_t *good_writes = zio->io_private;
1232 
1233 	if (*good_writes == 0)
1234 		zio->io_error = SET_ERROR(EIO);
1235 
1236 	kmem_free(good_writes, sizeof (uint64_t));
1237 }
1238 
1239 /*
1240  * We ignore errors for log and cache devices, simply free the private data.
1241  */
1242 static void
1243 vdev_label_sync_ignore_done(zio_t *zio)
1244 {
1245 	kmem_free(zio->io_private, sizeof (uint64_t));
1246 }
1247 
1248 /*
1249  * Write all even or odd labels to all leaves of the specified vdev.
1250  */
1251 static void
1252 vdev_label_sync(zio_t *zio, uint64_t *good_writes,
1253     vdev_t *vd, int l, uint64_t txg, int flags)
1254 {
1255 	nvlist_t *label;
1256 	vdev_phys_t *vp;
1257 	abd_t *vp_abd;
1258 	char *buf;
1259 	size_t buflen;
1260 
1261 	for (int c = 0; c < vd->vdev_children; c++) {
1262 		vdev_label_sync(zio, good_writes,
1263 		    vd->vdev_child[c], l, txg, flags);
1264 	}
1265 
1266 	if (!vd->vdev_ops->vdev_op_leaf)
1267 		return;
1268 
1269 	if (!vdev_writeable(vd))
1270 		return;
1271 
1272 	/*
1273 	 * Generate a label describing the top-level config to which we belong.
1274 	 */
1275 	label = spa_config_generate(vd->vdev_spa, vd, txg, B_FALSE);
1276 
1277 	vp_abd = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
1278 	abd_zero(vp_abd, sizeof (vdev_phys_t));
1279 	vp = abd_to_buf(vp_abd);
1280 
1281 	buf = vp->vp_nvlist;
1282 	buflen = sizeof (vp->vp_nvlist);
1283 
1284 	if (nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP) == 0) {
1285 		for (; l < VDEV_LABELS; l += 2) {
1286 			vdev_label_write(zio, vd, l, vp_abd,
1287 			    offsetof(vdev_label_t, vl_vdev_phys),
1288 			    sizeof (vdev_phys_t),
1289 			    vdev_label_sync_done, good_writes,
1290 			    flags | ZIO_FLAG_DONT_PROPAGATE);
1291 		}
1292 	}
1293 
1294 	abd_free(vp_abd);
1295 	nvlist_free(label);
1296 }
1297 
1298 int
1299 vdev_label_sync_list(spa_t *spa, int l, uint64_t txg, int flags)
1300 {
1301 	list_t *dl = &spa->spa_config_dirty_list;
1302 	vdev_t *vd;
1303 	zio_t *zio;
1304 	int error;
1305 
1306 	/*
1307 	 * Write the new labels to disk.
1308 	 */
1309 	zio = zio_root(spa, NULL, NULL, flags);
1310 
1311 	for (vd = list_head(dl); vd != NULL; vd = list_next(dl, vd)) {
1312 		uint64_t *good_writes = kmem_zalloc(sizeof (uint64_t),
1313 		    KM_SLEEP);
1314 
1315 		ASSERT(!vd->vdev_ishole);
1316 
1317 		zio_t *vio = zio_null(zio, spa, NULL,
1318 		    (vd->vdev_islog || vd->vdev_aux != NULL) ?
1319 		    vdev_label_sync_ignore_done : vdev_label_sync_top_done,
1320 		    good_writes, flags);
1321 		vdev_label_sync(vio, good_writes, vd, l, txg, flags);
1322 		zio_nowait(vio);
1323 	}
1324 
1325 	error = zio_wait(zio);
1326 
1327 	/*
1328 	 * Flush the new labels to disk.
1329 	 */
1330 	zio = zio_root(spa, NULL, NULL, flags);
1331 
1332 	for (vd = list_head(dl); vd != NULL; vd = list_next(dl, vd))
1333 		zio_flush(zio, vd);
1334 
1335 	(void) zio_wait(zio);
1336 
1337 	return (error);
1338 }
1339 
1340 /*
1341  * Sync the uberblock and any changes to the vdev configuration.
1342  *
1343  * The order of operations is carefully crafted to ensure that
1344  * if the system panics or loses power at any time, the state on disk
1345  * is still transactionally consistent.  The in-line comments below
1346  * describe the failure semantics at each stage.
1347  *
1348  * Moreover, vdev_config_sync() is designed to be idempotent: if it fails
1349  * at any time, you can just call it again, and it will resume its work.
1350  */
1351 int
1352 vdev_config_sync(vdev_t **svd, int svdcount, uint64_t txg)
1353 {
1354 	spa_t *spa = svd[0]->vdev_spa;
1355 	uberblock_t *ub = &spa->spa_uberblock;
1356 	int error = 0;
1357 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL;
1358 
1359 	ASSERT(svdcount != 0);
1360 retry:
1361 	/*
1362 	 * Normally, we don't want to try too hard to write every label and
1363 	 * uberblock.  If there is a flaky disk, we don't want the rest of the
1364 	 * sync process to block while we retry.  But if we can't write a
1365 	 * single label out, we should retry with ZIO_FLAG_TRYHARD before
1366 	 * bailing out and declaring the pool faulted.
1367 	 */
1368 	if (error != 0) {
1369 		if ((flags & ZIO_FLAG_TRYHARD) != 0)
1370 			return (error);
1371 		flags |= ZIO_FLAG_TRYHARD;
1372 	}
1373 
1374 	ASSERT(ub->ub_txg <= txg);
1375 
1376 	/*
1377 	 * If this isn't a resync due to I/O errors,
1378 	 * and nothing changed in this transaction group,
1379 	 * and the vdev configuration hasn't changed,
1380 	 * then there's nothing to do.
1381 	 */
1382 	if (ub->ub_txg < txg) {
1383 		boolean_t changed = uberblock_update(ub, spa->spa_root_vdev,
1384 		    txg, spa->spa_mmp.mmp_delay);
1385 
1386 		if (!changed && list_is_empty(&spa->spa_config_dirty_list))
1387 			return (0);
1388 	}
1389 
1390 	if (txg > spa_freeze_txg(spa))
1391 		return (0);
1392 
1393 	ASSERT(txg <= spa->spa_final_txg);
1394 
1395 	/*
1396 	 * Flush the write cache of every disk that's been written to
1397 	 * in this transaction group.  This ensures that all blocks
1398 	 * written in this txg will be committed to stable storage
1399 	 * before any uberblock that references them.
1400 	 */
1401 	zio_t *zio = zio_root(spa, NULL, NULL, flags);
1402 
1403 	for (vdev_t *vd =
1404 	    txg_list_head(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)); vd != NULL;
1405 	    vd = txg_list_next(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg)))
1406 		zio_flush(zio, vd);
1407 
1408 	(void) zio_wait(zio);
1409 
1410 	/*
1411 	 * Sync out the even labels (L0, L2) for every dirty vdev.  If the
1412 	 * system dies in the middle of this process, that's OK: all of the
1413 	 * even labels that made it to disk will be newer than any uberblock,
1414 	 * and will therefore be considered invalid.  The odd labels (L1, L3),
1415 	 * which have not yet been touched, will still be valid.  We flush
1416 	 * the new labels to disk to ensure that all even-label updates
1417 	 * are committed to stable storage before the uberblock update.
1418 	 */
1419 	if ((error = vdev_label_sync_list(spa, 0, txg, flags)) != 0) {
1420 		if ((flags & ZIO_FLAG_TRYHARD) != 0) {
1421 			zfs_dbgmsg("vdev_label_sync_list() returned error %d "
1422 			    "for pool '%s' when syncing out the even labels "
1423 			    "of dirty vdevs", error, spa_name(spa));
1424 		}
1425 		goto retry;
1426 	}
1427 
1428 	/*
1429 	 * Sync the uberblocks to all vdevs in svd[].
1430 	 * If the system dies in the middle of this step, there are two cases
1431 	 * to consider, and the on-disk state is consistent either way:
1432 	 *
1433 	 * (1)	If none of the new uberblocks made it to disk, then the
1434 	 *	previous uberblock will be the newest, and the odd labels
1435 	 *	(which had not yet been touched) will be valid with respect
1436 	 *	to that uberblock.
1437 	 *
1438 	 * (2)	If one or more new uberblocks made it to disk, then they
1439 	 *	will be the newest, and the even labels (which had all
1440 	 *	been successfully committed) will be valid with respect
1441 	 *	to the new uberblocks.
1442 	 */
1443 	if ((error = vdev_uberblock_sync_list(svd, svdcount, ub, flags)) != 0) {
1444 		if ((flags & ZIO_FLAG_TRYHARD) != 0) {
1445 			zfs_dbgmsg("vdev_uberblock_sync_list() returned error "
1446 			    "%d for pool '%s'", error, spa_name(spa));
1447 		}
1448 		goto retry;
1449 	}
1450 
1451 	if (spa_multihost(spa))
1452 		mmp_update_uberblock(spa, ub);
1453 
1454 	/*
1455 	 * Sync out odd labels for every dirty vdev.  If the system dies
1456 	 * in the middle of this process, the even labels and the new
1457 	 * uberblocks will suffice to open the pool.  The next time
1458 	 * the pool is opened, the first thing we'll do -- before any
1459 	 * user data is modified -- is mark every vdev dirty so that
1460 	 * all labels will be brought up to date.  We flush the new labels
1461 	 * to disk to ensure that all odd-label updates are committed to
1462 	 * stable storage before the next transaction group begins.
1463 	 */
1464 	if ((error = vdev_label_sync_list(spa, 1, txg, flags)) != 0) {
1465 		if ((flags & ZIO_FLAG_TRYHARD) != 0) {
1466 			zfs_dbgmsg("vdev_label_sync_list() returned error %d "
1467 			    "for pool '%s' when syncing out the odd labels of "
1468 			    "dirty vdevs", error, spa_name(spa));
1469 		}
1470 		goto retry;
1471 	}
1472 
1473 	return (0);
1474 }
1475