xref: /illumos-gate/usr/src/uts/common/fs/zfs/vdev_label.c (revision d321a33cdd896e6b211d113a33698dd76e89b861)
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, int flags)
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, flags, B_TRUE));
186 }
187 
188 /*
189  * Generate the nvlist representing this vdev's config.
190  */
191 nvlist_t *
192 vdev_config_generate(spa_t *spa, vdev_t *vd, boolean_t getstats,
193     boolean_t isspare, boolean_t isl2cache)
194 {
195 	nvlist_t *nv = NULL;
196 
197 	VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
198 
199 	VERIFY(nvlist_add_string(nv, ZPOOL_CONFIG_TYPE,
200 	    vd->vdev_ops->vdev_op_type) == 0);
201 	if (!isspare && !isl2cache)
202 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_ID, vd->vdev_id)
203 		    == 0);
204 	VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_GUID, vd->vdev_guid) == 0);
205 
206 	if (vd->vdev_path != NULL)
207 		VERIFY(nvlist_add_string(nv, ZPOOL_CONFIG_PATH,
208 		    vd->vdev_path) == 0);
209 
210 	if (vd->vdev_devid != NULL)
211 		VERIFY(nvlist_add_string(nv, ZPOOL_CONFIG_DEVID,
212 		    vd->vdev_devid) == 0);
213 
214 	if (vd->vdev_physpath != NULL)
215 		VERIFY(nvlist_add_string(nv, ZPOOL_CONFIG_PHYS_PATH,
216 		    vd->vdev_physpath) == 0);
217 
218 	if (vd->vdev_nparity != 0) {
219 		ASSERT(strcmp(vd->vdev_ops->vdev_op_type,
220 		    VDEV_TYPE_RAIDZ) == 0);
221 
222 		/*
223 		 * Make sure someone hasn't managed to sneak a fancy new vdev
224 		 * into a crufty old storage pool.
225 		 */
226 		ASSERT(vd->vdev_nparity == 1 ||
227 		    (vd->vdev_nparity == 2 &&
228 		    spa_version(spa) >= SPA_VERSION_RAID6));
229 
230 		/*
231 		 * Note that we'll add the nparity tag even on storage pools
232 		 * that only support a single parity device -- older software
233 		 * will just ignore it.
234 		 */
235 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_NPARITY,
236 		    vd->vdev_nparity) == 0);
237 	}
238 
239 	if (vd->vdev_wholedisk != -1ULL)
240 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
241 		    vd->vdev_wholedisk) == 0);
242 
243 	if (vd->vdev_not_present)
244 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT, 1) == 0);
245 
246 	if (vd->vdev_isspare)
247 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_IS_SPARE, 1) == 0);
248 
249 	if (!isspare && !isl2cache && vd == vd->vdev_top) {
250 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
251 		    vd->vdev_ms_array) == 0);
252 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
253 		    vd->vdev_ms_shift) == 0);
254 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_ASHIFT,
255 		    vd->vdev_ashift) == 0);
256 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_ASIZE,
257 		    vd->vdev_asize) == 0);
258 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_IS_LOG,
259 		    vd->vdev_islog) == 0);
260 	}
261 
262 	if (vd->vdev_dtl.smo_object != 0)
263 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_DTL,
264 		    vd->vdev_dtl.smo_object) == 0);
265 
266 	if (getstats) {
267 		vdev_stat_t vs;
268 		vdev_get_stats(vd, &vs);
269 		VERIFY(nvlist_add_uint64_array(nv, ZPOOL_CONFIG_STATS,
270 		    (uint64_t *)&vs, sizeof (vs) / sizeof (uint64_t)) == 0);
271 	}
272 
273 	if (!vd->vdev_ops->vdev_op_leaf) {
274 		nvlist_t **child;
275 		int c;
276 
277 		child = kmem_alloc(vd->vdev_children * sizeof (nvlist_t *),
278 		    KM_SLEEP);
279 
280 		for (c = 0; c < vd->vdev_children; c++)
281 			child[c] = vdev_config_generate(spa, vd->vdev_child[c],
282 			    getstats, isspare, isl2cache);
283 
284 		VERIFY(nvlist_add_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
285 		    child, vd->vdev_children) == 0);
286 
287 		for (c = 0; c < vd->vdev_children; c++)
288 			nvlist_free(child[c]);
289 
290 		kmem_free(child, vd->vdev_children * sizeof (nvlist_t *));
291 
292 	} else {
293 		if (vd->vdev_offline && !vd->vdev_tmpoffline)
294 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_OFFLINE,
295 			    B_TRUE) == 0);
296 		if (vd->vdev_faulted)
297 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_FAULTED,
298 			    B_TRUE) == 0);
299 		if (vd->vdev_degraded)
300 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_DEGRADED,
301 			    B_TRUE) == 0);
302 		if (vd->vdev_removed)
303 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_REMOVED,
304 			    B_TRUE) == 0);
305 		if (vd->vdev_unspare)
306 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_UNSPARE,
307 			    B_TRUE) == 0);
308 	}
309 
310 	return (nv);
311 }
312 
313 nvlist_t *
314 vdev_label_read_config(vdev_t *vd)
315 {
316 	spa_t *spa = vd->vdev_spa;
317 	nvlist_t *config = NULL;
318 	vdev_phys_t *vp;
319 	zio_t *zio;
320 	int l;
321 
322 	ASSERT(spa_config_held(spa, RW_READER) ||
323 	    spa_config_held(spa, RW_WRITER));
324 
325 	if (!vdev_readable(vd))
326 		return (NULL);
327 
328 	vp = zio_buf_alloc(sizeof (vdev_phys_t));
329 
330 	for (l = 0; l < VDEV_LABELS; l++) {
331 
332 		zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL |
333 		    ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CONFIG_HELD);
334 
335 		vdev_label_read(zio, vd, l, vp,
336 		    offsetof(vdev_label_t, vl_vdev_phys),
337 		    sizeof (vdev_phys_t), NULL, NULL);
338 
339 		if (zio_wait(zio) == 0 &&
340 		    nvlist_unpack(vp->vp_nvlist, sizeof (vp->vp_nvlist),
341 		    &config, 0) == 0)
342 			break;
343 
344 		if (config != NULL) {
345 			nvlist_free(config);
346 			config = NULL;
347 		}
348 	}
349 
350 	zio_buf_free(vp, sizeof (vdev_phys_t));
351 
352 	return (config);
353 }
354 
355 /*
356  * Determine if a device is in use.  The 'spare_guid' parameter will be filled
357  * in with the device guid if this spare is active elsewhere on the system.
358  */
359 static boolean_t
360 vdev_inuse(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason,
361     uint64_t *spare_guid, uint64_t *l2cache_guid)
362 {
363 	spa_t *spa = vd->vdev_spa;
364 	uint64_t state, pool_guid, device_guid, txg, spare_pool;
365 	uint64_t vdtxg = 0;
366 	nvlist_t *label;
367 
368 	if (spare_guid)
369 		*spare_guid = 0ULL;
370 	if (l2cache_guid)
371 		*l2cache_guid = 0ULL;
372 
373 	/*
374 	 * Read the label, if any, and perform some basic sanity checks.
375 	 */
376 	if ((label = vdev_label_read_config(vd)) == NULL)
377 		return (B_FALSE);
378 
379 	(void) nvlist_lookup_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
380 	    &vdtxg);
381 
382 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
383 	    &state) != 0 ||
384 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
385 	    &device_guid) != 0) {
386 		nvlist_free(label);
387 		return (B_FALSE);
388 	}
389 
390 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
391 	    (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID,
392 	    &pool_guid) != 0 ||
393 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
394 	    &txg) != 0)) {
395 		nvlist_free(label);
396 		return (B_FALSE);
397 	}
398 
399 	nvlist_free(label);
400 
401 	/*
402 	 * Check to see if this device indeed belongs to the pool it claims to
403 	 * be a part of.  The only way this is allowed is if the device is a hot
404 	 * spare (which we check for later on).
405 	 */
406 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
407 	    !spa_guid_exists(pool_guid, device_guid) &&
408 	    !spa_spare_exists(device_guid, NULL) &&
409 	    !spa_l2cache_exists(device_guid, NULL))
410 		return (B_FALSE);
411 
412 	/*
413 	 * If the transaction group is zero, then this an initialized (but
414 	 * unused) label.  This is only an error if the create transaction
415 	 * on-disk is the same as the one we're using now, in which case the
416 	 * user has attempted to add the same vdev multiple times in the same
417 	 * transaction.
418 	 */
419 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
420 	    txg == 0 && vdtxg == crtxg)
421 		return (B_TRUE);
422 
423 	/*
424 	 * Check to see if this is a spare device.  We do an explicit check for
425 	 * spa_has_spare() here because it may be on our pending list of spares
426 	 * to add.  We also check if it is an l2cache device.
427 	 */
428 	if (spa_spare_exists(device_guid, &spare_pool) ||
429 	    spa_has_spare(spa, device_guid)) {
430 		if (spare_guid)
431 			*spare_guid = device_guid;
432 
433 		switch (reason) {
434 		case VDEV_LABEL_CREATE:
435 		case VDEV_LABEL_L2CACHE:
436 			return (B_TRUE);
437 
438 		case VDEV_LABEL_REPLACE:
439 			return (!spa_has_spare(spa, device_guid) ||
440 			    spare_pool != 0ULL);
441 
442 		case VDEV_LABEL_SPARE:
443 			return (spa_has_spare(spa, device_guid));
444 		}
445 	}
446 
447 	/*
448 	 * Check to see if this is an l2cache device.
449 	 */
450 	if (spa_l2cache_exists(device_guid, NULL))
451 		return (B_TRUE);
452 
453 	/*
454 	 * If the device is marked ACTIVE, then this device is in use by another
455 	 * pool on the system.
456 	 */
457 	return (state == POOL_STATE_ACTIVE);
458 }
459 
460 /*
461  * Initialize a vdev label.  We check to make sure each leaf device is not in
462  * use, and writable.  We put down an initial label which we will later
463  * overwrite with a complete label.  Note that it's important to do this
464  * sequentially, not in parallel, so that we catch cases of multiple use of the
465  * same leaf vdev in the vdev we're creating -- e.g. mirroring a disk with
466  * itself.
467  */
468 int
469 vdev_label_init(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason)
470 {
471 	spa_t *spa = vd->vdev_spa;
472 	nvlist_t *label;
473 	vdev_phys_t *vp;
474 	vdev_boot_header_t *vb;
475 	uberblock_t *ub;
476 	zio_t *zio;
477 	int l, c, n;
478 	char *buf;
479 	size_t buflen;
480 	int error;
481 	uint64_t spare_guid, l2cache_guid;
482 	int flags = ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL;
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, flags);
645 
646 	for (l = 0; l < VDEV_LABELS; l++) {
647 
648 		vdev_label_write(zio, vd, l, vp,
649 		    offsetof(vdev_label_t, vl_vdev_phys),
650 		    sizeof (vdev_phys_t), NULL, NULL, flags);
651 
652 		vdev_label_write(zio, vd, l, vb,
653 		    offsetof(vdev_label_t, vl_boot_header),
654 		    sizeof (vdev_boot_header_t), NULL, NULL, flags);
655 
656 		for (n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
657 			vdev_label_write(zio, vd, l, ub,
658 			    VDEV_UBERBLOCK_OFFSET(vd, n),
659 			    VDEV_UBERBLOCK_SIZE(vd), NULL, NULL, flags);
660 		}
661 	}
662 
663 	error = zio_wait(zio);
664 
665 	nvlist_free(label);
666 	zio_buf_free(ub, VDEV_UBERBLOCK_SIZE(vd));
667 	zio_buf_free(vb, sizeof (vdev_boot_header_t));
668 	zio_buf_free(vp, sizeof (vdev_phys_t));
669 
670 	/*
671 	 * If this vdev hasn't been previously identified as a spare, then we
672 	 * mark it as such only if a) we are labeling it as a spare, or b) it
673 	 * exists as a spare elsewhere in the system.  Do the same for
674 	 * level 2 ARC devices.
675 	 */
676 	if (error == 0 && !vd->vdev_isspare &&
677 	    (reason == VDEV_LABEL_SPARE ||
678 	    spa_spare_exists(vd->vdev_guid, NULL)))
679 		spa_spare_add(vd);
680 
681 	if (error == 0 && !vd->vdev_isl2cache &&
682 	    (reason == VDEV_LABEL_L2CACHE ||
683 	    spa_l2cache_exists(vd->vdev_guid, NULL)))
684 		spa_l2cache_add(vd);
685 
686 	return (error);
687 }
688 
689 /*
690  * ==========================================================================
691  * uberblock load/sync
692  * ==========================================================================
693  */
694 
695 /*
696  * Consider the following situation: txg is safely synced to disk.  We've
697  * written the first uberblock for txg + 1, and then we lose power.  When we
698  * come back up, we fail to see the uberblock for txg + 1 because, say,
699  * it was on a mirrored device and the replica to which we wrote txg + 1
700  * is now offline.  If we then make some changes and sync txg + 1, and then
701  * the missing replica comes back, then for a new seconds we'll have two
702  * conflicting uberblocks on disk with the same txg.  The solution is simple:
703  * among uberblocks with equal txg, choose the one with the latest timestamp.
704  */
705 static int
706 vdev_uberblock_compare(uberblock_t *ub1, uberblock_t *ub2)
707 {
708 	if (ub1->ub_txg < ub2->ub_txg)
709 		return (-1);
710 	if (ub1->ub_txg > ub2->ub_txg)
711 		return (1);
712 
713 	if (ub1->ub_timestamp < ub2->ub_timestamp)
714 		return (-1);
715 	if (ub1->ub_timestamp > ub2->ub_timestamp)
716 		return (1);
717 
718 	return (0);
719 }
720 
721 static void
722 vdev_uberblock_load_done(zio_t *zio)
723 {
724 	uberblock_t *ub = zio->io_data;
725 	uberblock_t *ubbest = zio->io_private;
726 	spa_t *spa = zio->io_spa;
727 
728 	ASSERT3U(zio->io_size, ==, VDEV_UBERBLOCK_SIZE(zio->io_vd));
729 
730 	if (zio->io_error == 0 && uberblock_verify(ub) == 0) {
731 		mutex_enter(&spa->spa_uberblock_lock);
732 		if (vdev_uberblock_compare(ub, ubbest) > 0)
733 			*ubbest = *ub;
734 		mutex_exit(&spa->spa_uberblock_lock);
735 	}
736 
737 	zio_buf_free(zio->io_data, zio->io_size);
738 }
739 
740 void
741 vdev_uberblock_load(zio_t *zio, vdev_t *vd, uberblock_t *ubbest)
742 {
743 	int l, c, n;
744 
745 	for (c = 0; c < vd->vdev_children; c++)
746 		vdev_uberblock_load(zio, vd->vdev_child[c], ubbest);
747 
748 	if (!vd->vdev_ops->vdev_op_leaf)
749 		return;
750 
751 	if (vdev_is_dead(vd))
752 		return;
753 
754 	for (l = 0; l < VDEV_LABELS; l++) {
755 		for (n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
756 			vdev_label_read(zio, vd, l,
757 			    zio_buf_alloc(VDEV_UBERBLOCK_SIZE(vd)),
758 			    VDEV_UBERBLOCK_OFFSET(vd, n),
759 			    VDEV_UBERBLOCK_SIZE(vd),
760 			    vdev_uberblock_load_done, ubbest);
761 		}
762 	}
763 }
764 
765 /*
766  * On success, increment root zio's count of good writes.
767  * We only get credit for writes to known-visible vdevs; see spa_vdev_add().
768  */
769 static void
770 vdev_uberblock_sync_done(zio_t *zio)
771 {
772 	uint64_t *good_writes = zio->io_private;
773 
774 	if (zio->io_error == 0 && zio->io_vd->vdev_top->vdev_ms_array != 0)
775 		atomic_add_64(good_writes, 1);
776 }
777 
778 /*
779  * Write the uberblock to all labels of all leaves of the specified vdev.
780  */
781 static void
782 vdev_uberblock_sync(zio_t *zio, uberblock_t *ub, vdev_t *vd)
783 {
784 	int l, c, n;
785 	uberblock_t *ubbuf;
786 
787 	for (c = 0; c < vd->vdev_children; c++)
788 		vdev_uberblock_sync(zio, ub, vd->vdev_child[c]);
789 
790 	if (!vd->vdev_ops->vdev_op_leaf)
791 		return;
792 
793 	if (vdev_is_dead(vd))
794 		return;
795 
796 	n = ub->ub_txg & (VDEV_UBERBLOCK_COUNT(vd) - 1);
797 
798 	ubbuf = zio_buf_alloc(VDEV_UBERBLOCK_SIZE(vd));
799 	bzero(ubbuf, VDEV_UBERBLOCK_SIZE(vd));
800 	*ubbuf = *ub;
801 
802 	for (l = 0; l < VDEV_LABELS; l++)
803 		vdev_label_write(zio, vd, l, ubbuf,
804 		    VDEV_UBERBLOCK_OFFSET(vd, n),
805 		    VDEV_UBERBLOCK_SIZE(vd),
806 		    vdev_uberblock_sync_done, zio->io_private,
807 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE);
808 
809 	zio_buf_free(ubbuf, VDEV_UBERBLOCK_SIZE(vd));
810 }
811 
812 int
813 vdev_uberblock_sync_list(vdev_t **svd, int svdcount, uberblock_t *ub, int flags)
814 {
815 	spa_t *spa = svd[0]->vdev_spa;
816 	int v;
817 	zio_t *zio;
818 	uint64_t good_writes = 0;
819 
820 	zio = zio_root(spa, NULL, &good_writes, flags);
821 
822 	for (v = 0; v < svdcount; v++)
823 		vdev_uberblock_sync(zio, ub, svd[v]);
824 
825 	(void) zio_wait(zio);
826 
827 	/*
828 	 * Flush the uberblocks to disk.  This ensures that the odd labels
829 	 * are no longer needed (because the new uberblocks and the even
830 	 * labels are safely on disk), so it is safe to overwrite them.
831 	 */
832 	zio = zio_root(spa, NULL, NULL, flags);
833 
834 	for (v = 0; v < svdcount; v++)
835 		zio_flush(zio, svd[v]);
836 
837 	(void) zio_wait(zio);
838 
839 	return (good_writes >= 1 ? 0 : EIO);
840 }
841 
842 /*
843  * On success, increment the count of good writes for our top-level vdev.
844  */
845 static void
846 vdev_label_sync_done(zio_t *zio)
847 {
848 	uint64_t *good_writes = zio->io_private;
849 
850 	if (zio->io_error == 0)
851 		atomic_add_64(good_writes, 1);
852 }
853 
854 /*
855  * If there weren't enough good writes, indicate failure to the parent.
856  */
857 static void
858 vdev_label_sync_top_done(zio_t *zio)
859 {
860 	uint64_t *good_writes = zio->io_private;
861 
862 	if (*good_writes == 0)
863 		zio->io_error = EIO;
864 
865 	kmem_free(good_writes, sizeof (uint64_t));
866 }
867 
868 /*
869  * Write all even or odd labels to all leaves of the specified vdev.
870  */
871 static void
872 vdev_label_sync(zio_t *zio, vdev_t *vd, int l, uint64_t txg)
873 {
874 	nvlist_t *label;
875 	vdev_phys_t *vp;
876 	char *buf;
877 	size_t buflen;
878 	int c;
879 
880 	for (c = 0; c < vd->vdev_children; c++)
881 		vdev_label_sync(zio, vd->vdev_child[c], l, txg);
882 
883 	if (!vd->vdev_ops->vdev_op_leaf)
884 		return;
885 
886 	if (vdev_is_dead(vd))
887 		return;
888 
889 	/*
890 	 * Generate a label describing the top-level config to which we belong.
891 	 */
892 	label = spa_config_generate(vd->vdev_spa, vd, txg, B_FALSE);
893 
894 	vp = zio_buf_alloc(sizeof (vdev_phys_t));
895 	bzero(vp, sizeof (vdev_phys_t));
896 
897 	buf = vp->vp_nvlist;
898 	buflen = sizeof (vp->vp_nvlist);
899 
900 	if (nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP) == 0) {
901 		for (; l < VDEV_LABELS; l += 2) {
902 			vdev_label_write(zio, vd, l, vp,
903 			    offsetof(vdev_label_t, vl_vdev_phys),
904 			    sizeof (vdev_phys_t),
905 			    vdev_label_sync_done, zio->io_private,
906 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE);
907 		}
908 	}
909 
910 	zio_buf_free(vp, sizeof (vdev_phys_t));
911 	nvlist_free(label);
912 }
913 
914 int
915 vdev_label_sync_list(spa_t *spa, int l, int flags, uint64_t txg)
916 {
917 	list_t *dl = &spa->spa_dirty_list;
918 	vdev_t *vd;
919 	zio_t *zio;
920 	int error;
921 
922 	/*
923 	 * Write the new labels to disk.
924 	 */
925 	zio = zio_root(spa, NULL, NULL, flags);
926 
927 	for (vd = list_head(dl); vd != NULL; vd = list_next(dl, vd)) {
928 		uint64_t *good_writes = kmem_zalloc(sizeof (uint64_t),
929 		    KM_SLEEP);
930 		zio_t *vio = zio_null(zio, spa, vdev_label_sync_top_done,
931 		    good_writes, flags);
932 		vdev_label_sync(vio, vd, l, txg);
933 		zio_nowait(vio);
934 	}
935 
936 	error = zio_wait(zio);
937 
938 	/*
939 	 * Flush the new labels to disk.
940 	 */
941 	zio = zio_root(spa, NULL, NULL, flags);
942 
943 	for (vd = list_head(dl); vd != NULL; vd = list_next(dl, vd))
944 		zio_flush(zio, vd);
945 
946 	(void) zio_wait(zio);
947 
948 	return (error);
949 }
950 
951 /*
952  * Sync the uberblock and any changes to the vdev configuration.
953  *
954  * The order of operations is carefully crafted to ensure that
955  * if the system panics or loses power at any time, the state on disk
956  * is still transactionally consistent.  The in-line comments below
957  * describe the failure semantics at each stage.
958  *
959  * Moreover, vdev_config_sync() is designed to be idempotent: if it fails
960  * at any time, you can just call it again, and it will resume its work.
961  */
962 int
963 vdev_config_sync(vdev_t **svd, int svdcount, uint64_t txg)
964 {
965 	spa_t *spa = svd[0]->vdev_spa;
966 	uberblock_t *ub = &spa->spa_uberblock;
967 	vdev_t *vd;
968 	zio_t *zio;
969 	int error;
970 	int flags = ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL;
971 
972 	ASSERT(ub->ub_txg <= txg);
973 
974 	/*
975 	 * If this isn't a resync due to I/O errors,
976 	 * and nothing changed in this transaction group,
977 	 * and the vdev configuration hasn't changed,
978 	 * then there's nothing to do.
979 	 */
980 	if (ub->ub_txg < txg &&
981 	    uberblock_update(ub, spa->spa_root_vdev, txg) == B_FALSE &&
982 	    list_is_empty(&spa->spa_dirty_list))
983 		return (0);
984 
985 	if (txg > spa_freeze_txg(spa))
986 		return (0);
987 
988 	ASSERT(txg <= spa->spa_final_txg);
989 
990 	/*
991 	 * Flush the write cache of every disk that's been written to
992 	 * in this transaction group.  This ensures that all blocks
993 	 * written in this txg will be committed to stable storage
994 	 * before any uberblock that references them.
995 	 */
996 	zio = zio_root(spa, NULL, NULL, flags);
997 
998 	for (vd = txg_list_head(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)); vd;
999 	    vd = txg_list_next(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg)))
1000 		zio_flush(zio, vd);
1001 
1002 	(void) zio_wait(zio);
1003 
1004 	/*
1005 	 * Sync out the even labels (L0, L2) for every dirty vdev.  If the
1006 	 * system dies in the middle of this process, that's OK: all of the
1007 	 * even labels that made it to disk will be newer than any uberblock,
1008 	 * and will therefore be considered invalid.  The odd labels (L1, L3),
1009 	 * which have not yet been touched, will still be valid.  We flush
1010 	 * the new labels to disk to ensure that all even-label updates
1011 	 * are committed to stable storage before the uberblock update.
1012 	 */
1013 	if ((error = vdev_label_sync_list(spa, 0, flags, txg)) != 0)
1014 		return (error);
1015 
1016 	/*
1017 	 * Sync the uberblocks to all vdevs in svd[].
1018 	 * If the system dies in the middle of this step, there are two cases
1019 	 * to consider, and the on-disk state is consistent either way:
1020 	 *
1021 	 * (1)	If none of the new uberblocks made it to disk, then the
1022 	 *	previous uberblock will be the newest, and the odd labels
1023 	 *	(which had not yet been touched) will be valid with respect
1024 	 *	to that uberblock.
1025 	 *
1026 	 * (2)	If one or more new uberblocks made it to disk, then they
1027 	 *	will be the newest, and the even labels (which had all
1028 	 *	been successfully committed) will be valid with respect
1029 	 *	to the new uberblocks.
1030 	 */
1031 	if ((error = vdev_uberblock_sync_list(svd, svdcount, ub, flags)) != 0)
1032 		return (error);
1033 
1034 	/*
1035 	 * Sync out odd labels for every dirty vdev.  If the system dies
1036 	 * in the middle of this process, the even labels and the new
1037 	 * uberblocks will suffice to open the pool.  The next time
1038 	 * the pool is opened, the first thing we'll do -- before any
1039 	 * user data is modified -- is mark every vdev dirty so that
1040 	 * all labels will be brought up to date.  We flush the new labels
1041 	 * to disk to ensure that all odd-label updates are committed to
1042 	 * stable storage before the next transaction group begins.
1043 	 */
1044 	return (vdev_label_sync_list(spa, 1, flags, txg));
1045 }
1046