xref: /illumos-gate/usr/src/uts/common/fs/zfs/vdev_label.c (revision fa94a07fd0519b8abfd871ad8fe60e6bebe1e2bb)
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  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * Virtual Device Labels
30  * ---------------------
31  *
32  * The vdev label serves several distinct purposes:
33  *
34  *	1. Uniquely identify this device as part of a ZFS pool and confirm its
35  *	   identity within the pool.
36  *
37  * 	2. Verify that all the devices given in a configuration are present
38  *         within the pool.
39  *
40  * 	3. Determine the uberblock for the pool.
41  *
42  * 	4. In case of an import operation, determine the configuration of the
43  *         toplevel vdev of which it is a part.
44  *
45  * 	5. If an import operation cannot find all the devices in the pool,
46  *         provide enough information to the administrator to determine which
47  *         devices are missing.
48  *
49  * It is important to note that while the kernel is responsible for writing the
50  * label, it only consumes the information in the first three cases.  The
51  * latter information is only consumed in userland when determining the
52  * configuration to import a pool.
53  *
54  *
55  * Label Organization
56  * ------------------
57  *
58  * Before describing the contents of the label, it's important to understand how
59  * the labels are written and updated with respect to the uberblock.
60  *
61  * When the pool configuration is altered, either because it was newly created
62  * or a device was added, we want to update all the labels such that we can deal
63  * with fatal failure at any point.  To this end, each disk has two labels which
64  * are updated before and after the uberblock is synced.  Assuming we have
65  * labels and an uberblock with the following transaction groups:
66  *
67  *              L1          UB          L2
68  *           +------+    +------+    +------+
69  *           |      |    |      |    |      |
70  *           | t10  |    | t10  |    | t10  |
71  *           |      |    |      |    |      |
72  *           +------+    +------+    +------+
73  *
74  * In this stable state, the labels and the uberblock were all updated within
75  * the same transaction group (10).  Each label is mirrored and checksummed, so
76  * that we can detect when we fail partway through writing the label.
77  *
78  * In order to identify which labels are valid, the labels are written in the
79  * following manner:
80  *
81  * 	1. For each vdev, update 'L1' to the new label
82  * 	2. Update the uberblock
83  * 	3. For each vdev, update 'L2' to the new label
84  *
85  * Given arbitrary failure, we can determine the correct label to use based on
86  * the transaction group.  If we fail after updating L1 but before updating the
87  * UB, we will notice that L1's transaction group is greater than the uberblock,
88  * so L2 must be valid.  If we fail after writing the uberblock but before
89  * writing L2, we will notice that L2's transaction group is less than L1, and
90  * therefore L1 is valid.
91  *
92  * Another added complexity is that not every label is updated when the config
93  * is synced.  If we add a single device, we do not want to have to re-write
94  * every label for every device in the pool.  This means that both L1 and L2 may
95  * be older than the pool uberblock, because the necessary information is stored
96  * on another vdev.
97  *
98  *
99  * On-disk Format
100  * --------------
101  *
102  * The vdev label consists of two distinct parts, and is wrapped within the
103  * vdev_label_t structure.  The label includes 8k of padding to permit legacy
104  * VTOC disk labels, but is otherwise ignored.
105  *
106  * The first half of the label is a packed nvlist which contains pool wide
107  * properties, per-vdev properties, and configuration information.  It is
108  * described in more detail below.
109  *
110  * The latter half of the label consists of a redundant array of uberblocks.
111  * These uberblocks are updated whenever a transaction group is committed,
112  * or when the configuration is updated.  When a pool is loaded, we scan each
113  * vdev for the 'best' uberblock.
114  *
115  *
116  * Configuration Information
117  * -------------------------
118  *
119  * The nvlist describing the pool and vdev contains the following elements:
120  *
121  * 	version		ZFS on-disk version
122  * 	name		Pool name
123  * 	state		Pool state
124  * 	txg		Transaction group in which this label was written
125  * 	pool_guid	Unique identifier for this pool
126  * 	vdev_tree	An nvlist describing vdev tree.
127  *
128  * Each leaf device label also contains the following:
129  *
130  * 	top_guid	Unique ID for top-level vdev in which this is contained
131  * 	guid		Unique ID for the leaf vdev
132  *
133  * The 'vs' configuration follows the format described in 'spa_config.c'.
134  */
135 
136 #include <sys/zfs_context.h>
137 #include <sys/spa.h>
138 #include <sys/spa_impl.h>
139 #include <sys/dmu.h>
140 #include <sys/zap.h>
141 #include <sys/vdev.h>
142 #include <sys/vdev_impl.h>
143 #include <sys/uberblock_impl.h>
144 #include <sys/metaslab.h>
145 #include <sys/zio.h>
146 #include <sys/fs/zfs.h>
147 
148 /*
149  * Basic routines to read and write from a vdev label.
150  * Used throughout the rest of this file.
151  */
152 uint64_t
153 vdev_label_offset(uint64_t psize, int l, uint64_t offset)
154 {
155 	ASSERT(offset < sizeof (vdev_label_t));
156 	ASSERT(P2PHASE_TYPED(psize, sizeof (vdev_label_t), uint64_t) == 0);
157 
158 	return (offset + l * sizeof (vdev_label_t) + (l < VDEV_LABELS / 2 ?
159 	    0 : psize - VDEV_LABELS * sizeof (vdev_label_t)));
160 }
161 
162 static void
163 vdev_label_read(zio_t *zio, vdev_t *vd, int l, void *buf, uint64_t offset,
164 	uint64_t size, zio_done_func_t *done, void *private)
165 {
166 	ASSERT(vd->vdev_children == 0);
167 
168 	zio_nowait(zio_read_phys(zio, vd,
169 	    vdev_label_offset(vd->vdev_psize, l, offset),
170 	    size, buf, ZIO_CHECKSUM_LABEL, done, private,
171 	    ZIO_PRIORITY_SYNC_READ,
172 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE,
173 	    B_TRUE));
174 }
175 
176 static void
177 vdev_label_write(zio_t *zio, vdev_t *vd, int l, void *buf, uint64_t offset,
178 	uint64_t size, zio_done_func_t *done, void *private)
179 {
180 	ASSERT(vd->vdev_children == 0);
181 
182 	zio_nowait(zio_write_phys(zio, vd,
183 	    vdev_label_offset(vd->vdev_psize, l, offset),
184 	    size, buf, ZIO_CHECKSUM_LABEL, done, private,
185 	    ZIO_PRIORITY_SYNC_WRITE, ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL,
186 	    B_TRUE));
187 }
188 
189 /*
190  * Generate the nvlist representing this vdev's config.
191  */
192 nvlist_t *
193 vdev_config_generate(spa_t *spa, vdev_t *vd, boolean_t getstats,
194     boolean_t isspare, boolean_t isl2cache)
195 {
196 	nvlist_t *nv = NULL;
197 
198 	VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
199 
200 	VERIFY(nvlist_add_string(nv, ZPOOL_CONFIG_TYPE,
201 	    vd->vdev_ops->vdev_op_type) == 0);
202 	if (!isspare && !isl2cache)
203 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_ID, vd->vdev_id)
204 		    == 0);
205 	VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_GUID, vd->vdev_guid) == 0);
206 
207 	if (vd->vdev_path != NULL)
208 		VERIFY(nvlist_add_string(nv, ZPOOL_CONFIG_PATH,
209 		    vd->vdev_path) == 0);
210 
211 	if (vd->vdev_devid != NULL)
212 		VERIFY(nvlist_add_string(nv, ZPOOL_CONFIG_DEVID,
213 		    vd->vdev_devid) == 0);
214 
215 	if (vd->vdev_physpath != NULL)
216 		VERIFY(nvlist_add_string(nv, ZPOOL_CONFIG_PHYS_PATH,
217 		    vd->vdev_physpath) == 0);
218 
219 	if (vd->vdev_nparity != 0) {
220 		ASSERT(strcmp(vd->vdev_ops->vdev_op_type,
221 		    VDEV_TYPE_RAIDZ) == 0);
222 
223 		/*
224 		 * Make sure someone hasn't managed to sneak a fancy new vdev
225 		 * into a crufty old storage pool.
226 		 */
227 		ASSERT(vd->vdev_nparity == 1 ||
228 		    (vd->vdev_nparity == 2 &&
229 		    spa_version(spa) >= SPA_VERSION_RAID6));
230 
231 		/*
232 		 * Note that we'll add the nparity tag even on storage pools
233 		 * that only support a single parity device -- older software
234 		 * will just ignore it.
235 		 */
236 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_NPARITY,
237 		    vd->vdev_nparity) == 0);
238 	}
239 
240 	if (vd->vdev_wholedisk != -1ULL)
241 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
242 		    vd->vdev_wholedisk) == 0);
243 
244 	if (vd->vdev_not_present)
245 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT, 1) == 0);
246 
247 	if (vd->vdev_isspare)
248 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_IS_SPARE, 1) == 0);
249 
250 	if (!isspare && !isl2cache && vd == vd->vdev_top) {
251 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
252 		    vd->vdev_ms_array) == 0);
253 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
254 		    vd->vdev_ms_shift) == 0);
255 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_ASHIFT,
256 		    vd->vdev_ashift) == 0);
257 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_ASIZE,
258 		    vd->vdev_asize) == 0);
259 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_IS_LOG,
260 		    vd->vdev_islog) == 0);
261 	}
262 
263 	if (vd->vdev_dtl.smo_object != 0)
264 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_DTL,
265 		    vd->vdev_dtl.smo_object) == 0);
266 
267 	if (getstats) {
268 		vdev_stat_t vs;
269 		vdev_get_stats(vd, &vs);
270 		VERIFY(nvlist_add_uint64_array(nv, ZPOOL_CONFIG_STATS,
271 		    (uint64_t *)&vs, sizeof (vs) / sizeof (uint64_t)) == 0);
272 	}
273 
274 	if (!vd->vdev_ops->vdev_op_leaf) {
275 		nvlist_t **child;
276 		int c;
277 
278 		child = kmem_alloc(vd->vdev_children * sizeof (nvlist_t *),
279 		    KM_SLEEP);
280 
281 		for (c = 0; c < vd->vdev_children; c++)
282 			child[c] = vdev_config_generate(spa, vd->vdev_child[c],
283 			    getstats, isspare, isl2cache);
284 
285 		VERIFY(nvlist_add_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
286 		    child, vd->vdev_children) == 0);
287 
288 		for (c = 0; c < vd->vdev_children; c++)
289 			nvlist_free(child[c]);
290 
291 		kmem_free(child, vd->vdev_children * sizeof (nvlist_t *));
292 
293 	} else {
294 		if (vd->vdev_offline && !vd->vdev_tmpoffline)
295 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_OFFLINE,
296 			    B_TRUE) == 0);
297 		if (vd->vdev_faulted)
298 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_FAULTED,
299 			    B_TRUE) == 0);
300 		if (vd->vdev_degraded)
301 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_DEGRADED,
302 			    B_TRUE) == 0);
303 		if (vd->vdev_removed)
304 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_REMOVED,
305 			    B_TRUE) == 0);
306 		if (vd->vdev_unspare)
307 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_UNSPARE,
308 			    B_TRUE) == 0);
309 	}
310 
311 	return (nv);
312 }
313 
314 nvlist_t *
315 vdev_label_read_config(vdev_t *vd)
316 {
317 	spa_t *spa = vd->vdev_spa;
318 	nvlist_t *config = NULL;
319 	vdev_phys_t *vp;
320 	zio_t *zio;
321 	int l;
322 
323 	ASSERT(spa_config_held(spa, RW_READER) ||
324 	    spa_config_held(spa, RW_WRITER));
325 
326 	if (!vdev_readable(vd))
327 		return (NULL);
328 
329 	vp = zio_buf_alloc(sizeof (vdev_phys_t));
330 
331 	for (l = 0; l < VDEV_LABELS; l++) {
332 
333 		zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL |
334 		    ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CONFIG_HELD);
335 
336 		vdev_label_read(zio, vd, l, vp,
337 		    offsetof(vdev_label_t, vl_vdev_phys),
338 		    sizeof (vdev_phys_t), NULL, NULL);
339 
340 		if (zio_wait(zio) == 0 &&
341 		    nvlist_unpack(vp->vp_nvlist, sizeof (vp->vp_nvlist),
342 		    &config, 0) == 0)
343 			break;
344 
345 		if (config != NULL) {
346 			nvlist_free(config);
347 			config = NULL;
348 		}
349 	}
350 
351 	zio_buf_free(vp, sizeof (vdev_phys_t));
352 
353 	return (config);
354 }
355 
356 /*
357  * Determine if a device is in use.  The 'spare_guid' parameter will be filled
358  * in with the device guid if this spare is active elsewhere on the system.
359  */
360 static boolean_t
361 vdev_inuse(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason,
362     uint64_t *spare_guid, uint64_t *l2cache_guid)
363 {
364 	spa_t *spa = vd->vdev_spa;
365 	uint64_t state, pool_guid, device_guid, txg, spare_pool;
366 	uint64_t vdtxg = 0;
367 	nvlist_t *label;
368 
369 	if (spare_guid)
370 		*spare_guid = 0ULL;
371 	if (l2cache_guid)
372 		*l2cache_guid = 0ULL;
373 
374 	/*
375 	 * Read the label, if any, and perform some basic sanity checks.
376 	 */
377 	if ((label = vdev_label_read_config(vd)) == NULL)
378 		return (B_FALSE);
379 
380 	(void) nvlist_lookup_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
381 	    &vdtxg);
382 
383 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
384 	    &state) != 0 ||
385 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
386 	    &device_guid) != 0) {
387 		nvlist_free(label);
388 		return (B_FALSE);
389 	}
390 
391 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
392 	    (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID,
393 	    &pool_guid) != 0 ||
394 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
395 	    &txg) != 0)) {
396 		nvlist_free(label);
397 		return (B_FALSE);
398 	}
399 
400 	nvlist_free(label);
401 
402 	/*
403 	 * Check to see if this device indeed belongs to the pool it claims to
404 	 * be a part of.  The only way this is allowed is if the device is a hot
405 	 * spare (which we check for later on).
406 	 */
407 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
408 	    !spa_guid_exists(pool_guid, device_guid) &&
409 	    !spa_spare_exists(device_guid, NULL) &&
410 	    !spa_l2cache_exists(device_guid, NULL))
411 		return (B_FALSE);
412 
413 	/*
414 	 * If the transaction group is zero, then this an initialized (but
415 	 * unused) label.  This is only an error if the create transaction
416 	 * on-disk is the same as the one we're using now, in which case the
417 	 * user has attempted to add the same vdev multiple times in the same
418 	 * transaction.
419 	 */
420 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
421 	    txg == 0 && vdtxg == crtxg)
422 		return (B_TRUE);
423 
424 	/*
425 	 * Check to see if this is a spare device.  We do an explicit check for
426 	 * spa_has_spare() here because it may be on our pending list of spares
427 	 * to add.  We also check if it is an l2cache device.
428 	 */
429 	if (spa_spare_exists(device_guid, &spare_pool) ||
430 	    spa_has_spare(spa, device_guid)) {
431 		if (spare_guid)
432 			*spare_guid = device_guid;
433 
434 		switch (reason) {
435 		case VDEV_LABEL_CREATE:
436 		case VDEV_LABEL_L2CACHE:
437 			return (B_TRUE);
438 
439 		case VDEV_LABEL_REPLACE:
440 			return (!spa_has_spare(spa, device_guid) ||
441 			    spare_pool != 0ULL);
442 
443 		case VDEV_LABEL_SPARE:
444 			return (spa_has_spare(spa, device_guid));
445 		}
446 	}
447 
448 	/*
449 	 * Check to see if this is an l2cache device.
450 	 */
451 	if (spa_l2cache_exists(device_guid, NULL))
452 		return (B_TRUE);
453 
454 	/*
455 	 * If the device is marked ACTIVE, then this device is in use by another
456 	 * pool on the system.
457 	 */
458 	return (state == POOL_STATE_ACTIVE);
459 }
460 
461 /*
462  * Initialize a vdev label.  We check to make sure each leaf device is not in
463  * use, and writable.  We put down an initial label which we will later
464  * overwrite with a complete label.  Note that it's important to do this
465  * sequentially, not in parallel, so that we catch cases of multiple use of the
466  * same leaf vdev in the vdev we're creating -- e.g. mirroring a disk with
467  * itself.
468  */
469 int
470 vdev_label_init(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason)
471 {
472 	spa_t *spa = vd->vdev_spa;
473 	nvlist_t *label;
474 	vdev_phys_t *vp;
475 	vdev_boot_header_t *vb;
476 	uberblock_t *ub;
477 	zio_t *zio;
478 	int l, c, n;
479 	char *buf;
480 	size_t buflen;
481 	int error;
482 	uint64_t spare_guid, l2cache_guid;
483 
484 	ASSERT(spa_config_held(spa, RW_WRITER));
485 
486 	for (c = 0; c < vd->vdev_children; c++)
487 		if ((error = vdev_label_init(vd->vdev_child[c],
488 		    crtxg, reason)) != 0)
489 			return (error);
490 
491 	if (!vd->vdev_ops->vdev_op_leaf)
492 		return (0);
493 
494 	/*
495 	 * Dead vdevs cannot be initialized.
496 	 */
497 	if (vdev_is_dead(vd))
498 		return (EIO);
499 
500 	/*
501 	 * Determine if the vdev is in use.
502 	 */
503 	if (reason != VDEV_LABEL_REMOVE &&
504 	    vdev_inuse(vd, crtxg, reason, &spare_guid, &l2cache_guid))
505 		return (EBUSY);
506 
507 	ASSERT(reason != VDEV_LABEL_REMOVE ||
508 	    vdev_inuse(vd, crtxg, reason, NULL, NULL));
509 
510 	/*
511 	 * If this is a request to add or replace a spare or l2cache device
512 	 * that is in use elsewhere on the system, then we must update the
513 	 * guid (which was initialized to a random value) to reflect the
514 	 * actual GUID (which is shared between multiple pools).
515 	 */
516 	if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_L2CACHE &&
517 	    spare_guid != 0ULL) {
518 		vdev_t *pvd = vd->vdev_parent;
519 
520 		for (; pvd != NULL; pvd = pvd->vdev_parent) {
521 			pvd->vdev_guid_sum -= vd->vdev_guid;
522 			pvd->vdev_guid_sum += spare_guid;
523 		}
524 
525 		vd->vdev_guid = vd->vdev_guid_sum = spare_guid;
526 
527 		/*
528 		 * If this is a replacement, then we want to fallthrough to the
529 		 * rest of the code.  If we're adding a spare, then it's already
530 		 * labeled appropriately and we can just return.
531 		 */
532 		if (reason == VDEV_LABEL_SPARE)
533 			return (0);
534 		ASSERT(reason == VDEV_LABEL_REPLACE);
535 	}
536 
537 	if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_SPARE &&
538 	    l2cache_guid != 0ULL) {
539 		vdev_t *pvd = vd->vdev_parent;
540 
541 		for (; pvd != NULL; pvd = pvd->vdev_parent) {
542 			pvd->vdev_guid_sum -= vd->vdev_guid;
543 			pvd->vdev_guid_sum += l2cache_guid;
544 		}
545 
546 		vd->vdev_guid = vd->vdev_guid_sum = l2cache_guid;
547 
548 		/*
549 		 * If this is a replacement, then we want to fallthrough to the
550 		 * rest of the code.  If we're adding an l2cache, then it's
551 		 * already labeled appropriately and we can just return.
552 		 */
553 		if (reason == VDEV_LABEL_L2CACHE)
554 			return (0);
555 		ASSERT(reason == VDEV_LABEL_REPLACE);
556 	}
557 
558 	/*
559 	 * Initialize its label.
560 	 */
561 	vp = zio_buf_alloc(sizeof (vdev_phys_t));
562 	bzero(vp, sizeof (vdev_phys_t));
563 
564 	/*
565 	 * Generate a label describing the pool and our top-level vdev.
566 	 * We mark it as being from txg 0 to indicate that it's not
567 	 * really part of an active pool just yet.  The labels will
568 	 * be written again with a meaningful txg by spa_sync().
569 	 */
570 	if (reason == VDEV_LABEL_SPARE ||
571 	    (reason == VDEV_LABEL_REMOVE && vd->vdev_isspare)) {
572 		/*
573 		 * For inactive hot spares, we generate a special label that
574 		 * identifies as a mutually shared hot spare.  We write the
575 		 * label if we are adding a hot spare, or if we are removing an
576 		 * active hot spare (in which case we want to revert the
577 		 * labels).
578 		 */
579 		VERIFY(nvlist_alloc(&label, NV_UNIQUE_NAME, KM_SLEEP) == 0);
580 
581 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_VERSION,
582 		    spa_version(spa)) == 0);
583 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_POOL_STATE,
584 		    POOL_STATE_SPARE) == 0);
585 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_GUID,
586 		    vd->vdev_guid) == 0);
587 	} else if (reason == VDEV_LABEL_L2CACHE ||
588 	    (reason == VDEV_LABEL_REMOVE && vd->vdev_isl2cache)) {
589 		/*
590 		 * For level 2 ARC devices, add a special label.
591 		 */
592 		VERIFY(nvlist_alloc(&label, NV_UNIQUE_NAME, KM_SLEEP) == 0);
593 
594 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_VERSION,
595 		    spa_version(spa)) == 0);
596 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_POOL_STATE,
597 		    POOL_STATE_L2CACHE) == 0);
598 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_GUID,
599 		    vd->vdev_guid) == 0);
600 	} else {
601 		label = spa_config_generate(spa, vd, 0ULL, B_FALSE);
602 
603 		/*
604 		 * Add our creation time.  This allows us to detect multiple
605 		 * vdev uses as described above, and automatically expires if we
606 		 * fail.
607 		 */
608 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
609 		    crtxg) == 0);
610 	}
611 
612 	buf = vp->vp_nvlist;
613 	buflen = sizeof (vp->vp_nvlist);
614 
615 	error = nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP);
616 	if (error != 0) {
617 		nvlist_free(label);
618 		zio_buf_free(vp, sizeof (vdev_phys_t));
619 		/* EFAULT means nvlist_pack ran out of room */
620 		return (error == EFAULT ? ENAMETOOLONG : EINVAL);
621 	}
622 
623 	/*
624 	 * Initialize boot block header.
625 	 */
626 	vb = zio_buf_alloc(sizeof (vdev_boot_header_t));
627 	bzero(vb, sizeof (vdev_boot_header_t));
628 	vb->vb_magic = VDEV_BOOT_MAGIC;
629 	vb->vb_version = VDEV_BOOT_VERSION;
630 	vb->vb_offset = VDEV_BOOT_OFFSET;
631 	vb->vb_size = VDEV_BOOT_SIZE;
632 
633 	/*
634 	 * Initialize uberblock template.
635 	 */
636 	ub = zio_buf_alloc(VDEV_UBERBLOCK_SIZE(vd));
637 	bzero(ub, VDEV_UBERBLOCK_SIZE(vd));
638 	*ub = spa->spa_uberblock;
639 	ub->ub_txg = 0;
640 
641 	/*
642 	 * Write everything in parallel.
643 	 */
644 	zio = zio_root(spa, NULL, NULL,
645 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL);
646 
647 	for (l = 0; l < VDEV_LABELS; l++) {
648 
649 		vdev_label_write(zio, vd, l, vp,
650 		    offsetof(vdev_label_t, vl_vdev_phys),
651 		    sizeof (vdev_phys_t), NULL, NULL);
652 
653 		vdev_label_write(zio, vd, l, vb,
654 		    offsetof(vdev_label_t, vl_boot_header),
655 		    sizeof (vdev_boot_header_t), NULL, NULL);
656 
657 		for (n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
658 			vdev_label_write(zio, vd, l, ub,
659 			    VDEV_UBERBLOCK_OFFSET(vd, n),
660 			    VDEV_UBERBLOCK_SIZE(vd), NULL, NULL);
661 		}
662 	}
663 
664 	error = zio_wait(zio);
665 
666 	nvlist_free(label);
667 	zio_buf_free(ub, VDEV_UBERBLOCK_SIZE(vd));
668 	zio_buf_free(vb, sizeof (vdev_boot_header_t));
669 	zio_buf_free(vp, sizeof (vdev_phys_t));
670 
671 	/*
672 	 * If this vdev hasn't been previously identified as a spare, then we
673 	 * mark it as such only if a) we are labeling it as a spare, or b) it
674 	 * exists as a spare elsewhere in the system.  Do the same for
675 	 * level 2 ARC devices.
676 	 */
677 	if (error == 0 && !vd->vdev_isspare &&
678 	    (reason == VDEV_LABEL_SPARE ||
679 	    spa_spare_exists(vd->vdev_guid, NULL)))
680 		spa_spare_add(vd);
681 
682 	if (error == 0 && !vd->vdev_isl2cache &&
683 	    (reason == VDEV_LABEL_L2CACHE ||
684 	    spa_l2cache_exists(vd->vdev_guid, NULL)))
685 		spa_l2cache_add(vd);
686 
687 	return (error);
688 }
689 
690 /*
691  * ==========================================================================
692  * uberblock load/sync
693  * ==========================================================================
694  */
695 
696 /*
697  * Consider the following situation: txg is safely synced to disk.  We've
698  * written the first uberblock for txg + 1, and then we lose power.  When we
699  * come back up, we fail to see the uberblock for txg + 1 because, say,
700  * it was on a mirrored device and the replica to which we wrote txg + 1
701  * is now offline.  If we then make some changes and sync txg + 1, and then
702  * the missing replica comes back, then for a new seconds we'll have two
703  * conflicting uberblocks on disk with the same txg.  The solution is simple:
704  * among uberblocks with equal txg, choose the one with the latest timestamp.
705  */
706 static int
707 vdev_uberblock_compare(uberblock_t *ub1, uberblock_t *ub2)
708 {
709 	if (ub1->ub_txg < ub2->ub_txg)
710 		return (-1);
711 	if (ub1->ub_txg > ub2->ub_txg)
712 		return (1);
713 
714 	if (ub1->ub_timestamp < ub2->ub_timestamp)
715 		return (-1);
716 	if (ub1->ub_timestamp > ub2->ub_timestamp)
717 		return (1);
718 
719 	return (0);
720 }
721 
722 static void
723 vdev_uberblock_load_done(zio_t *zio)
724 {
725 	uberblock_t *ub = zio->io_data;
726 	uberblock_t *ubbest = zio->io_private;
727 	spa_t *spa = zio->io_spa;
728 
729 	ASSERT3U(zio->io_size, ==, VDEV_UBERBLOCK_SIZE(zio->io_vd));
730 
731 	if (zio->io_error == 0 && uberblock_verify(ub) == 0) {
732 		mutex_enter(&spa->spa_uberblock_lock);
733 		if (vdev_uberblock_compare(ub, ubbest) > 0)
734 			*ubbest = *ub;
735 		mutex_exit(&spa->spa_uberblock_lock);
736 	}
737 
738 	zio_buf_free(zio->io_data, zio->io_size);
739 }
740 
741 void
742 vdev_uberblock_load(zio_t *zio, vdev_t *vd, uberblock_t *ubbest)
743 {
744 	int l, c, n;
745 
746 	for (c = 0; c < vd->vdev_children; c++)
747 		vdev_uberblock_load(zio, vd->vdev_child[c], ubbest);
748 
749 	if (!vd->vdev_ops->vdev_op_leaf)
750 		return;
751 
752 	if (vdev_is_dead(vd))
753 		return;
754 
755 	for (l = 0; l < VDEV_LABELS; l++) {
756 		for (n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
757 			vdev_label_read(zio, vd, l,
758 			    zio_buf_alloc(VDEV_UBERBLOCK_SIZE(vd)),
759 			    VDEV_UBERBLOCK_OFFSET(vd, n),
760 			    VDEV_UBERBLOCK_SIZE(vd),
761 			    vdev_uberblock_load_done, ubbest);
762 		}
763 	}
764 }
765 
766 /*
767  * Write the uberblock to both labels of all leaves of the specified vdev.
768  * We only get credit for writes to known-visible vdevs; see spa_vdev_add().
769  */
770 static void
771 vdev_uberblock_sync_done(zio_t *zio)
772 {
773 	uint64_t *good_writes = zio->io_root->io_private;
774 
775 	if (zio->io_error == 0 && zio->io_vd->vdev_top->vdev_ms_array != 0)
776 		atomic_add_64(good_writes, 1);
777 }
778 
779 static void
780 vdev_uberblock_sync(zio_t *zio, uberblock_t *ub, vdev_t *vd, uint64_t txg)
781 {
782 	int l, c, n;
783 
784 	for (c = 0; c < vd->vdev_children; c++)
785 		vdev_uberblock_sync(zio, ub, vd->vdev_child[c], txg);
786 
787 	if (!vd->vdev_ops->vdev_op_leaf)
788 		return;
789 
790 	if (vdev_is_dead(vd))
791 		return;
792 
793 	n = txg & (VDEV_UBERBLOCK_COUNT(vd) - 1);
794 
795 	ASSERT(ub->ub_txg == txg);
796 
797 	for (l = 0; l < VDEV_LABELS; l++)
798 		vdev_label_write(zio, vd, l, ub,
799 		    VDEV_UBERBLOCK_OFFSET(vd, n),
800 		    VDEV_UBERBLOCK_SIZE(vd),
801 		    vdev_uberblock_sync_done, NULL);
802 
803 	dprintf("vdev %s in txg %llu\n", vdev_description(vd), txg);
804 }
805 
806 static int
807 vdev_uberblock_sync_tree(spa_t *spa, uberblock_t *ub, vdev_t *vd, uint64_t txg)
808 {
809 	uberblock_t *ubbuf;
810 	size_t size = vd->vdev_top ? VDEV_UBERBLOCK_SIZE(vd) : SPA_MAXBLOCKSIZE;
811 	uint64_t *good_writes;
812 	zio_t *zio;
813 	int error;
814 
815 	ubbuf = zio_buf_alloc(size);
816 	bzero(ubbuf, size);
817 	*ubbuf = *ub;
818 
819 	good_writes = kmem_zalloc(sizeof (uint64_t), KM_SLEEP);
820 
821 	zio = zio_root(spa, NULL, good_writes,
822 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL);
823 
824 	vdev_uberblock_sync(zio, ubbuf, vd, txg);
825 
826 	error = zio_wait(zio);
827 
828 	if (error && *good_writes != 0) {
829 		dprintf("partial success: good_writes = %llu\n", *good_writes);
830 		error = 0;
831 	}
832 
833 	/*
834 	 * It's possible to have no good writes and no error if every vdev is in
835 	 * the CANT_OPEN state.
836 	 */
837 	if (*good_writes == 0 && error == 0)
838 		error = EIO;
839 
840 	kmem_free(good_writes, sizeof (uint64_t));
841 	zio_buf_free(ubbuf, size);
842 
843 	return (error);
844 }
845 
846 /*
847  * Sync out an individual vdev.
848  */
849 static void
850 vdev_sync_label_done(zio_t *zio)
851 {
852 	uint64_t *good_writes = zio->io_root->io_private;
853 
854 	if (zio->io_error == 0)
855 		atomic_add_64(good_writes, 1);
856 }
857 
858 static void
859 vdev_sync_label(zio_t *zio, vdev_t *vd, int l, uint64_t txg)
860 {
861 	nvlist_t *label;
862 	vdev_phys_t *vp;
863 	char *buf;
864 	size_t buflen;
865 	int c;
866 
867 	for (c = 0; c < vd->vdev_children; c++)
868 		vdev_sync_label(zio, vd->vdev_child[c], l, txg);
869 
870 	if (!vd->vdev_ops->vdev_op_leaf)
871 		return;
872 
873 	if (vdev_is_dead(vd))
874 		return;
875 
876 	/*
877 	 * Generate a label describing the top-level config to which we belong.
878 	 */
879 	label = spa_config_generate(vd->vdev_spa, vd, txg, B_FALSE);
880 
881 	vp = zio_buf_alloc(sizeof (vdev_phys_t));
882 	bzero(vp, sizeof (vdev_phys_t));
883 
884 	buf = vp->vp_nvlist;
885 	buflen = sizeof (vp->vp_nvlist);
886 
887 	if (nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP) == 0)
888 		vdev_label_write(zio, vd, l, vp,
889 		    offsetof(vdev_label_t, vl_vdev_phys), sizeof (vdev_phys_t),
890 		    vdev_sync_label_done, NULL);
891 
892 	zio_buf_free(vp, sizeof (vdev_phys_t));
893 	nvlist_free(label);
894 
895 	dprintf("%s label %d txg %llu\n", vdev_description(vd), l, txg);
896 }
897 
898 static int
899 vdev_sync_labels(vdev_t *vd, int l, uint64_t txg)
900 {
901 	uint64_t *good_writes;
902 	zio_t *zio;
903 	int error;
904 
905 	ASSERT(vd == vd->vdev_top);
906 
907 	good_writes = kmem_zalloc(sizeof (uint64_t), KM_SLEEP);
908 
909 	zio = zio_root(vd->vdev_spa, NULL, good_writes,
910 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL);
911 
912 	/*
913 	 * Recursively kick off writes to all labels.
914 	 */
915 	vdev_sync_label(zio, vd, l, txg);
916 
917 	error = zio_wait(zio);
918 
919 	if (error && *good_writes != 0) {
920 		dprintf("partial success: good_writes = %llu\n", *good_writes);
921 		error = 0;
922 	}
923 
924 	if (*good_writes == 0 && error == 0)
925 		error = ENODEV;
926 
927 	/*
928 	 * Failure to write a label can be fatal for a
929 	 * top level vdev. We don't want this for slogs
930 	 * as we use the main pool if they go away.
931 	 */
932 	if (vd->vdev_islog)
933 		error = 0;
934 
935 	kmem_free(good_writes, sizeof (uint64_t));
936 
937 	return (error);
938 }
939 
940 /*
941  * Sync the entire vdev configuration.
942  *
943  * The order of operations is carefully crafted to ensure that
944  * if the system panics or loses power at any time, the state on disk
945  * is still transactionally consistent.  The in-line comments below
946  * describe the failure semantics at each stage.
947  *
948  * Moreover, it is designed to be idempotent: if spa_sync_labels() fails
949  * at any time, you can just call it again, and it will resume its work.
950  */
951 int
952 vdev_config_sync(vdev_t *uvd, uint64_t txg)
953 {
954 	spa_t *spa = uvd->vdev_spa;
955 	uberblock_t *ub = &spa->spa_uberblock;
956 	vdev_t *rvd = spa->spa_root_vdev;
957 	vdev_t *vd;
958 	zio_t *zio;
959 	int l, last_error = 0, error = 0;
960 	uint64_t good_writes = 0;
961 	boolean_t retry_avail = B_TRUE;
962 
963 	ASSERT(ub->ub_txg <= txg);
964 
965 	/*
966 	 * If this isn't a resync due to I/O errors, and nothing changed
967 	 * in this transaction group, and the vdev configuration hasn't changed,
968 	 * then there's nothing to do.
969 	 */
970 	if (ub->ub_txg < txg && uberblock_update(ub, rvd, txg) == B_FALSE &&
971 	    list_is_empty(&spa->spa_dirty_list)) {
972 		dprintf("nothing to sync in %s in txg %llu\n",
973 		    spa_name(spa), txg);
974 		return (0);
975 	}
976 
977 	if (txg > spa_freeze_txg(spa))
978 		return (0);
979 
980 	ASSERT(txg <= spa->spa_final_txg);
981 
982 	dprintf("syncing %s txg %llu\n", spa_name(spa), txg);
983 
984 	/*
985 	 * Flush the write cache of every disk that's been written to
986 	 * in this transaction group.  This ensures that all blocks
987 	 * written in this txg will be committed to stable storage
988 	 * before any uberblock that references them.
989 	 */
990 	zio = zio_root(spa, NULL, NULL,
991 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL);
992 	for (vd = txg_list_head(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)); vd;
993 	    vd = txg_list_next(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg))) {
994 		zio_nowait(zio_ioctl(zio, spa, vd, DKIOCFLUSHWRITECACHE,
995 		    NULL, NULL, ZIO_PRIORITY_NOW,
996 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY));
997 	}
998 	(void) zio_wait(zio);
999 
1000 retry:
1001 	/*
1002 	 * Sync out the even labels (L0, L2) for every dirty vdev.  If the
1003 	 * system dies in the middle of this process, that's OK: all of the
1004 	 * even labels that made it to disk will be newer than any uberblock,
1005 	 * and will therefore be considered invalid.  The odd labels (L1, L3),
1006 	 * which have not yet been touched, will still be valid.
1007 	 */
1008 	for (vd = list_head(&spa->spa_dirty_list); vd != NULL;
1009 	    vd = list_next(&spa->spa_dirty_list, vd)) {
1010 		for (l = 0; l < VDEV_LABELS; l++) {
1011 			if (l & 1)
1012 				continue;
1013 			if ((error = vdev_sync_labels(vd, l, txg)) != 0)
1014 				last_error = error;
1015 			else
1016 				good_writes++;
1017 		}
1018 	}
1019 
1020 	/*
1021 	 * If all the vdevs that are currently dirty have failed or the
1022 	 * spa_dirty_list is empty then we dirty all the vdevs and try again.
1023 	 * This is a last ditch effort to ensure that we get at least one
1024 	 * update before proceeding to the uberblock.
1025 	 */
1026 	if (good_writes == 0 && retry_avail) {
1027 		vdev_config_dirty(rvd);
1028 		retry_avail = B_FALSE;
1029 		last_error = 0;
1030 		goto retry;
1031 	}
1032 
1033 	if (good_writes == 0)
1034 		return (last_error);
1035 
1036 	/*
1037 	 * Flush the new labels to disk.  This ensures that all even-label
1038 	 * updates are committed to stable storage before the uberblock update.
1039 	 */
1040 	zio = zio_root(spa, NULL, NULL,
1041 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL);
1042 	for (vd = list_head(&spa->spa_dirty_list); vd != NULL;
1043 	    vd = list_next(&spa->spa_dirty_list, vd)) {
1044 		zio_nowait(zio_ioctl(zio, spa, vd, DKIOCFLUSHWRITECACHE,
1045 		    NULL, NULL, ZIO_PRIORITY_NOW,
1046 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY));
1047 	}
1048 	(void) zio_wait(zio);
1049 
1050 	/*
1051 	 * Sync the uberblocks to all vdevs in the tree specified by uvd.
1052 	 * If the system dies in the middle of this step, there are two cases
1053 	 * to consider, and the on-disk state is consistent either way:
1054 	 *
1055 	 * (1)	If none of the new uberblocks made it to disk, then the
1056 	 *	previous uberblock will be the newest, and the odd labels
1057 	 *	(which had not yet been touched) will be valid with respect
1058 	 *	to that uberblock.
1059 	 *
1060 	 * (2)	If one or more new uberblocks made it to disk, then they
1061 	 *	will be the newest, and the even labels (which had all
1062 	 *	been successfully committed) will be valid with respect
1063 	 *	to the new uberblocks.
1064 	 *
1065 	 * NOTE: We retry to an uberblock update on the root if we were
1066 	 * failed our initial update attempt.
1067 	 */
1068 	error = vdev_uberblock_sync_tree(spa, ub, uvd, txg);
1069 	if (error && uvd != rvd)
1070 		error = vdev_uberblock_sync_tree(spa, ub, rvd, txg);
1071 
1072 	if (error)
1073 		return (error);
1074 
1075 	/*
1076 	 * Flush the uberblocks to disk.  This ensures that the odd labels
1077 	 * are no longer needed (because the new uberblocks and the even
1078 	 * labels are safely on disk), so it is safe to overwrite them.
1079 	 */
1080 	(void) zio_wait(zio_ioctl(NULL, spa, uvd, DKIOCFLUSHWRITECACHE,
1081 	    NULL, NULL, ZIO_PRIORITY_NOW,
1082 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY));
1083 
1084 	last_error = 0;
1085 	/*
1086 	 * Sync out odd labels for every dirty vdev.  If the system dies
1087 	 * in the middle of this process, the even labels and the new
1088 	 * uberblocks will suffice to open the pool.  The next time
1089 	 * the pool is opened, the first thing we'll do -- before any
1090 	 * user data is modified -- is mark every vdev dirty so that
1091 	 * all labels will be brought up to date.
1092 	 */
1093 	for (vd = list_head(&spa->spa_dirty_list); vd != NULL;
1094 	    vd = list_next(&spa->spa_dirty_list, vd)) {
1095 		for (l = 0; l < VDEV_LABELS; l++) {
1096 			if ((l & 1) == 0)
1097 				continue;
1098 			if ((error = vdev_sync_labels(vd, l, txg)) != 0)
1099 				last_error = error;
1100 			else
1101 				good_writes++;
1102 		}
1103 	}
1104 
1105 	if (good_writes == 0)
1106 		return (last_error);
1107 
1108 	/*
1109 	 * Flush the new labels to disk.  This ensures that all odd-label
1110 	 * updates are committed to stable storage before the next
1111 	 * transaction group begins.
1112 	 */
1113 	zio = zio_root(spa, NULL, NULL,
1114 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL);
1115 	for (vd = list_head(&spa->spa_dirty_list); vd != NULL;
1116 	    vd = list_next(&spa->spa_dirty_list, vd)) {
1117 		zio_nowait(zio_ioctl(zio, spa, vd, DKIOCFLUSHWRITECACHE,
1118 		    NULL, NULL, ZIO_PRIORITY_NOW,
1119 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY));
1120 	}
1121 	(void) zio_wait(zio);
1122 
1123 	return (0);
1124 }
1125