xref: /titanic_51/usr/src/uts/common/fs/zfs/vdev_label.c (revision 4e9cfc9a015e8ca7d41f7d018c74dc8a692305b3)
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 }
174 
175 static void
176 vdev_label_write(zio_t *zio, vdev_t *vd, int l, void *buf, uint64_t offset,
177 	uint64_t size, zio_done_func_t *done, void *private)
178 {
179 	ASSERT(vd->vdev_children == 0);
180 
181 	zio_nowait(zio_write_phys(zio, vd,
182 	    vdev_label_offset(vd->vdev_psize, l, offset),
183 	    size, buf, ZIO_CHECKSUM_LABEL, done, private,
184 	    ZIO_PRIORITY_SYNC_WRITE, ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL));
185 }
186 
187 /*
188  * Generate the nvlist representing this vdev's config.
189  */
190 nvlist_t *
191 vdev_config_generate(spa_t *spa, vdev_t *vd, boolean_t getstats,
192     boolean_t isspare)
193 {
194 	nvlist_t *nv = NULL;
195 
196 	VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
197 
198 	VERIFY(nvlist_add_string(nv, ZPOOL_CONFIG_TYPE,
199 	    vd->vdev_ops->vdev_op_type) == 0);
200 	if (!isspare)
201 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_ID, vd->vdev_id)
202 		    == 0);
203 	VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_GUID, vd->vdev_guid) == 0);
204 
205 	if (vd->vdev_path != NULL)
206 		VERIFY(nvlist_add_string(nv, ZPOOL_CONFIG_PATH,
207 		    vd->vdev_path) == 0);
208 
209 	if (vd->vdev_devid != NULL)
210 		VERIFY(nvlist_add_string(nv, ZPOOL_CONFIG_DEVID,
211 		    vd->vdev_devid) == 0);
212 
213 	if (vd->vdev_physpath != NULL)
214 		VERIFY(nvlist_add_string(nv, ZPOOL_CONFIG_PHYS_PATH,
215 		    vd->vdev_physpath) == 0);
216 
217 	if (vd->vdev_nparity != 0) {
218 		ASSERT(strcmp(vd->vdev_ops->vdev_op_type,
219 		    VDEV_TYPE_RAIDZ) == 0);
220 
221 		/*
222 		 * Make sure someone hasn't managed to sneak a fancy new vdev
223 		 * into a crufty old storage pool.
224 		 */
225 		ASSERT(vd->vdev_nparity == 1 ||
226 		    (vd->vdev_nparity == 2 &&
227 		    spa_version(spa) >= SPA_VERSION_RAID6));
228 
229 		/*
230 		 * Note that we'll add the nparity tag even on storage pools
231 		 * that only support a single parity device -- older software
232 		 * will just ignore it.
233 		 */
234 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_NPARITY,
235 		    vd->vdev_nparity) == 0);
236 	}
237 
238 	if (vd->vdev_wholedisk != -1ULL)
239 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
240 		    vd->vdev_wholedisk) == 0);
241 
242 	if (vd->vdev_not_present)
243 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT, 1) == 0);
244 
245 	if (vd->vdev_isspare)
246 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_IS_SPARE, 1) == 0);
247 
248 	if (!isspare && vd == vd->vdev_top) {
249 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
250 		    vd->vdev_ms_array) == 0);
251 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
252 		    vd->vdev_ms_shift) == 0);
253 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_ASHIFT,
254 		    vd->vdev_ashift) == 0);
255 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_ASIZE,
256 		    vd->vdev_asize) == 0);
257 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_IS_LOG,
258 		    vd->vdev_islog) == 0);
259 	}
260 
261 	if (vd->vdev_dtl.smo_object != 0)
262 		VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_DTL,
263 		    vd->vdev_dtl.smo_object) == 0);
264 
265 	if (getstats) {
266 		vdev_stat_t vs;
267 		vdev_get_stats(vd, &vs);
268 		VERIFY(nvlist_add_uint64_array(nv, ZPOOL_CONFIG_STATS,
269 		    (uint64_t *)&vs, sizeof (vs) / sizeof (uint64_t)) == 0);
270 	}
271 
272 	if (!vd->vdev_ops->vdev_op_leaf) {
273 		nvlist_t **child;
274 		int c;
275 
276 		child = kmem_alloc(vd->vdev_children * sizeof (nvlist_t *),
277 		    KM_SLEEP);
278 
279 		for (c = 0; c < vd->vdev_children; c++)
280 			child[c] = vdev_config_generate(spa, vd->vdev_child[c],
281 			    getstats, isspare);
282 
283 		VERIFY(nvlist_add_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
284 		    child, vd->vdev_children) == 0);
285 
286 		for (c = 0; c < vd->vdev_children; c++)
287 			nvlist_free(child[c]);
288 
289 		kmem_free(child, vd->vdev_children * sizeof (nvlist_t *));
290 
291 	} else {
292 		if (vd->vdev_offline && !vd->vdev_tmpoffline)
293 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_OFFLINE,
294 			    B_TRUE) == 0);
295 		if (vd->vdev_faulted)
296 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_FAULTED,
297 			    B_TRUE) == 0);
298 		if (vd->vdev_degraded)
299 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_DEGRADED,
300 			    B_TRUE) == 0);
301 		if (vd->vdev_removed)
302 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_REMOVED,
303 			    B_TRUE) == 0);
304 		if (vd->vdev_unspare)
305 			VERIFY(nvlist_add_uint64(nv, ZPOOL_CONFIG_UNSPARE,
306 			    B_TRUE) == 0);
307 	}
308 
309 	return (nv);
310 }
311 
312 nvlist_t *
313 vdev_label_read_config(vdev_t *vd)
314 {
315 	spa_t *spa = vd->vdev_spa;
316 	nvlist_t *config = NULL;
317 	vdev_phys_t *vp;
318 	zio_t *zio;
319 	int l;
320 
321 	ASSERT(spa_config_held(spa, RW_READER) ||
322 	    spa_config_held(spa, RW_WRITER));
323 
324 	if (vdev_is_dead(vd))
325 		return (NULL);
326 
327 	vp = zio_buf_alloc(sizeof (vdev_phys_t));
328 
329 	for (l = 0; l < VDEV_LABELS; l++) {
330 
331 		zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL |
332 		    ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CONFIG_HELD);
333 
334 		vdev_label_read(zio, vd, l, vp,
335 		    offsetof(vdev_label_t, vl_vdev_phys),
336 		    sizeof (vdev_phys_t), NULL, NULL);
337 
338 		if (zio_wait(zio) == 0 &&
339 		    nvlist_unpack(vp->vp_nvlist, sizeof (vp->vp_nvlist),
340 		    &config, 0) == 0)
341 			break;
342 
343 		if (config != NULL) {
344 			nvlist_free(config);
345 			config = NULL;
346 		}
347 	}
348 
349 	zio_buf_free(vp, sizeof (vdev_phys_t));
350 
351 	return (config);
352 }
353 
354 /*
355  * Determine if a device is in use.  The 'spare_guid' parameter will be filled
356  * in with the device guid if this spare is active elsewhere on the system.
357  */
358 static boolean_t
359 vdev_inuse(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason,
360     uint64_t *spare_guid)
361 {
362 	spa_t *spa = vd->vdev_spa;
363 	uint64_t state, pool_guid, device_guid, txg, spare_pool;
364 	uint64_t vdtxg = 0;
365 	nvlist_t *label;
366 
367 	if (spare_guid)
368 		*spare_guid = 0ULL;
369 
370 	/*
371 	 * Read the label, if any, and perform some basic sanity checks.
372 	 */
373 	if ((label = vdev_label_read_config(vd)) == NULL)
374 		return (B_FALSE);
375 
376 	(void) nvlist_lookup_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
377 	    &vdtxg);
378 
379 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
380 	    &state) != 0 ||
381 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
382 	    &device_guid) != 0) {
383 		nvlist_free(label);
384 		return (B_FALSE);
385 	}
386 
387 	if (state != POOL_STATE_SPARE &&
388 	    (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID,
389 	    &pool_guid) != 0 ||
390 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
391 	    &txg) != 0)) {
392 		nvlist_free(label);
393 		return (B_FALSE);
394 	}
395 
396 	nvlist_free(label);
397 
398 	/*
399 	 * Check to see if this device indeed belongs to the pool it claims to
400 	 * be a part of.  The only way this is allowed is if the device is a hot
401 	 * spare (which we check for later on).
402 	 */
403 	if (state != POOL_STATE_SPARE &&
404 	    !spa_guid_exists(pool_guid, device_guid) &&
405 	    !spa_spare_exists(device_guid, NULL))
406 		return (B_FALSE);
407 
408 	/*
409 	 * If the transaction group is zero, then this an initialized (but
410 	 * unused) label.  This is only an error if the create transaction
411 	 * on-disk is the same as the one we're using now, in which case the
412 	 * user has attempted to add the same vdev multiple times in the same
413 	 * transaction.
414 	 */
415 	if (state != POOL_STATE_SPARE && txg == 0 && vdtxg == crtxg)
416 		return (B_TRUE);
417 
418 	/*
419 	 * Check to see if this is a spare device.  We do an explicit check for
420 	 * spa_has_spare() here because it may be on our pending list of spares
421 	 * to add.
422 	 */
423 	if (spa_spare_exists(device_guid, &spare_pool) ||
424 	    spa_has_spare(spa, device_guid)) {
425 		if (spare_guid)
426 			*spare_guid = device_guid;
427 
428 		switch (reason) {
429 		case VDEV_LABEL_CREATE:
430 			return (B_TRUE);
431 
432 		case VDEV_LABEL_REPLACE:
433 			return (!spa_has_spare(spa, device_guid) ||
434 			    spare_pool != 0ULL);
435 
436 		case VDEV_LABEL_SPARE:
437 			return (spa_has_spare(spa, device_guid));
438 		}
439 	}
440 
441 	/*
442 	 * If the device is marked ACTIVE, then this device is in use by another
443 	 * pool on the system.
444 	 */
445 	return (state == POOL_STATE_ACTIVE);
446 }
447 
448 /*
449  * Initialize a vdev label.  We check to make sure each leaf device is not in
450  * use, and writable.  We put down an initial label which we will later
451  * overwrite with a complete label.  Note that it's important to do this
452  * sequentially, not in parallel, so that we catch cases of multiple use of the
453  * same leaf vdev in the vdev we're creating -- e.g. mirroring a disk with
454  * itself.
455  */
456 int
457 vdev_label_init(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason)
458 {
459 	spa_t *spa = vd->vdev_spa;
460 	nvlist_t *label;
461 	vdev_phys_t *vp;
462 	vdev_boot_header_t *vb;
463 	uberblock_t *ub;
464 	zio_t *zio;
465 	int l, c, n;
466 	char *buf;
467 	size_t buflen;
468 	int error;
469 	uint64_t spare_guid;
470 
471 	ASSERT(spa_config_held(spa, RW_WRITER));
472 
473 	for (c = 0; c < vd->vdev_children; c++)
474 		if ((error = vdev_label_init(vd->vdev_child[c],
475 		    crtxg, reason)) != 0)
476 			return (error);
477 
478 	if (!vd->vdev_ops->vdev_op_leaf)
479 		return (0);
480 
481 	/*
482 	 * Dead vdevs cannot be initialized.
483 	 */
484 	if (vdev_is_dead(vd))
485 		return (EIO);
486 
487 	/*
488 	 * Determine if the vdev is in use.
489 	 */
490 	if (reason != VDEV_LABEL_REMOVE &&
491 	    vdev_inuse(vd, crtxg, reason, &spare_guid))
492 		return (EBUSY);
493 
494 	ASSERT(reason != VDEV_LABEL_REMOVE ||
495 	    vdev_inuse(vd, crtxg, reason, NULL));
496 
497 	/*
498 	 * If this is a request to add or replace a spare that is in use
499 	 * elsewhere on the system, then we must update the guid (which was
500 	 * initialized to a random value) to reflect the actual GUID (which is
501 	 * shared between multiple pools).
502 	 */
503 	if (reason != VDEV_LABEL_REMOVE && spare_guid != 0ULL) {
504 		vdev_t *pvd = vd->vdev_parent;
505 
506 		for (; pvd != NULL; pvd = pvd->vdev_parent) {
507 			pvd->vdev_guid_sum -= vd->vdev_guid;
508 			pvd->vdev_guid_sum += spare_guid;
509 		}
510 
511 		vd->vdev_guid = vd->vdev_guid_sum = spare_guid;
512 
513 		/*
514 		 * If this is a replacement, then we want to fallthrough to the
515 		 * rest of the code.  If we're adding a spare, then it's already
516 		 * labeled appropriately and we can just return.
517 		 */
518 		if (reason == VDEV_LABEL_SPARE)
519 			return (0);
520 		ASSERT(reason == VDEV_LABEL_REPLACE);
521 	}
522 
523 	/*
524 	 * Initialize its label.
525 	 */
526 	vp = zio_buf_alloc(sizeof (vdev_phys_t));
527 	bzero(vp, sizeof (vdev_phys_t));
528 
529 	/*
530 	 * Generate a label describing the pool and our top-level vdev.
531 	 * We mark it as being from txg 0 to indicate that it's not
532 	 * really part of an active pool just yet.  The labels will
533 	 * be written again with a meaningful txg by spa_sync().
534 	 */
535 	if (reason == VDEV_LABEL_SPARE ||
536 	    (reason == VDEV_LABEL_REMOVE && vd->vdev_isspare)) {
537 		/*
538 		 * For inactive hot spares, we generate a special label that
539 		 * identifies as a mutually shared hot spare.  We write the
540 		 * label if we are adding a hot spare, or if we are removing an
541 		 * active hot spare (in which case we want to revert the
542 		 * labels).
543 		 */
544 		VERIFY(nvlist_alloc(&label, NV_UNIQUE_NAME, KM_SLEEP) == 0);
545 
546 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_VERSION,
547 		    spa_version(spa)) == 0);
548 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_POOL_STATE,
549 		    POOL_STATE_SPARE) == 0);
550 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_GUID,
551 		    vd->vdev_guid) == 0);
552 	} else {
553 		label = spa_config_generate(spa, vd, 0ULL, B_FALSE);
554 
555 		/*
556 		 * Add our creation time.  This allows us to detect multiple
557 		 * vdev uses as described above, and automatically expires if we
558 		 * fail.
559 		 */
560 		VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
561 		    crtxg) == 0);
562 	}
563 
564 	buf = vp->vp_nvlist;
565 	buflen = sizeof (vp->vp_nvlist);
566 
567 	error = nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP);
568 	if (error != 0) {
569 		nvlist_free(label);
570 		zio_buf_free(vp, sizeof (vdev_phys_t));
571 		/* EFAULT means nvlist_pack ran out of room */
572 		return (error == EFAULT ? ENAMETOOLONG : EINVAL);
573 	}
574 
575 	/*
576 	 * Initialize boot block header.
577 	 */
578 	vb = zio_buf_alloc(sizeof (vdev_boot_header_t));
579 	bzero(vb, sizeof (vdev_boot_header_t));
580 	vb->vb_magic = VDEV_BOOT_MAGIC;
581 	vb->vb_version = VDEV_BOOT_VERSION;
582 	vb->vb_offset = VDEV_BOOT_OFFSET;
583 	vb->vb_size = VDEV_BOOT_SIZE;
584 
585 	/*
586 	 * Initialize uberblock template.
587 	 */
588 	ub = zio_buf_alloc(VDEV_UBERBLOCK_SIZE(vd));
589 	bzero(ub, VDEV_UBERBLOCK_SIZE(vd));
590 	*ub = spa->spa_uberblock;
591 	ub->ub_txg = 0;
592 
593 	/*
594 	 * Write everything in parallel.
595 	 */
596 	zio = zio_root(spa, NULL, NULL,
597 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL);
598 
599 	for (l = 0; l < VDEV_LABELS; l++) {
600 
601 		vdev_label_write(zio, vd, l, vp,
602 		    offsetof(vdev_label_t, vl_vdev_phys),
603 		    sizeof (vdev_phys_t), NULL, NULL);
604 
605 		vdev_label_write(zio, vd, l, vb,
606 		    offsetof(vdev_label_t, vl_boot_header),
607 		    sizeof (vdev_boot_header_t), NULL, NULL);
608 
609 		for (n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
610 			vdev_label_write(zio, vd, l, ub,
611 			    VDEV_UBERBLOCK_OFFSET(vd, n),
612 			    VDEV_UBERBLOCK_SIZE(vd), NULL, NULL);
613 		}
614 	}
615 
616 	error = zio_wait(zio);
617 
618 	nvlist_free(label);
619 	zio_buf_free(ub, VDEV_UBERBLOCK_SIZE(vd));
620 	zio_buf_free(vb, sizeof (vdev_boot_header_t));
621 	zio_buf_free(vp, sizeof (vdev_phys_t));
622 
623 	/*
624 	 * If this vdev hasn't been previously identified as a spare, then we
625 	 * mark it as such only if a) we are labeling it as a spare, or b) it
626 	 * exists as a spare elsewhere in the system.
627 	 */
628 	if (error == 0 && !vd->vdev_isspare &&
629 	    (reason == VDEV_LABEL_SPARE ||
630 	    spa_spare_exists(vd->vdev_guid, NULL)))
631 		spa_spare_add(vd);
632 
633 	return (error);
634 }
635 
636 /*
637  * ==========================================================================
638  * uberblock load/sync
639  * ==========================================================================
640  */
641 
642 /*
643  * Consider the following situation: txg is safely synced to disk.  We've
644  * written the first uberblock for txg + 1, and then we lose power.  When we
645  * come back up, we fail to see the uberblock for txg + 1 because, say,
646  * it was on a mirrored device and the replica to which we wrote txg + 1
647  * is now offline.  If we then make some changes and sync txg + 1, and then
648  * the missing replica comes back, then for a new seconds we'll have two
649  * conflicting uberblocks on disk with the same txg.  The solution is simple:
650  * among uberblocks with equal txg, choose the one with the latest timestamp.
651  */
652 static int
653 vdev_uberblock_compare(uberblock_t *ub1, uberblock_t *ub2)
654 {
655 	if (ub1->ub_txg < ub2->ub_txg)
656 		return (-1);
657 	if (ub1->ub_txg > ub2->ub_txg)
658 		return (1);
659 
660 	if (ub1->ub_timestamp < ub2->ub_timestamp)
661 		return (-1);
662 	if (ub1->ub_timestamp > ub2->ub_timestamp)
663 		return (1);
664 
665 	return (0);
666 }
667 
668 static void
669 vdev_uberblock_load_done(zio_t *zio)
670 {
671 	uberblock_t *ub = zio->io_data;
672 	uberblock_t *ubbest = zio->io_private;
673 	spa_t *spa = zio->io_spa;
674 
675 	ASSERT3U(zio->io_size, ==, VDEV_UBERBLOCK_SIZE(zio->io_vd));
676 
677 	if (zio->io_error == 0 && uberblock_verify(ub) == 0) {
678 		mutex_enter(&spa->spa_uberblock_lock);
679 		if (vdev_uberblock_compare(ub, ubbest) > 0)
680 			*ubbest = *ub;
681 		mutex_exit(&spa->spa_uberblock_lock);
682 	}
683 
684 	zio_buf_free(zio->io_data, zio->io_size);
685 }
686 
687 void
688 vdev_uberblock_load(zio_t *zio, vdev_t *vd, uberblock_t *ubbest)
689 {
690 	int l, c, n;
691 
692 	for (c = 0; c < vd->vdev_children; c++)
693 		vdev_uberblock_load(zio, vd->vdev_child[c], ubbest);
694 
695 	if (!vd->vdev_ops->vdev_op_leaf)
696 		return;
697 
698 	if (vdev_is_dead(vd))
699 		return;
700 
701 	for (l = 0; l < VDEV_LABELS; l++) {
702 		for (n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
703 			vdev_label_read(zio, vd, l,
704 			    zio_buf_alloc(VDEV_UBERBLOCK_SIZE(vd)),
705 			    VDEV_UBERBLOCK_OFFSET(vd, n),
706 			    VDEV_UBERBLOCK_SIZE(vd),
707 			    vdev_uberblock_load_done, ubbest);
708 		}
709 	}
710 }
711 
712 /*
713  * Write the uberblock to both labels of all leaves of the specified vdev.
714  * We only get credit for writes to known-visible vdevs; see spa_vdev_add().
715  */
716 static void
717 vdev_uberblock_sync_done(zio_t *zio)
718 {
719 	uint64_t *good_writes = zio->io_root->io_private;
720 
721 	if (zio->io_error == 0 && zio->io_vd->vdev_top->vdev_ms_array != 0)
722 		atomic_add_64(good_writes, 1);
723 }
724 
725 static void
726 vdev_uberblock_sync(zio_t *zio, uberblock_t *ub, vdev_t *vd, uint64_t txg)
727 {
728 	int l, c, n;
729 
730 	for (c = 0; c < vd->vdev_children; c++)
731 		vdev_uberblock_sync(zio, ub, vd->vdev_child[c], txg);
732 
733 	if (!vd->vdev_ops->vdev_op_leaf)
734 		return;
735 
736 	if (vdev_is_dead(vd))
737 		return;
738 
739 	n = txg & (VDEV_UBERBLOCK_COUNT(vd) - 1);
740 
741 	ASSERT(ub->ub_txg == txg);
742 
743 	for (l = 0; l < VDEV_LABELS; l++)
744 		vdev_label_write(zio, vd, l, ub,
745 		    VDEV_UBERBLOCK_OFFSET(vd, n),
746 		    VDEV_UBERBLOCK_SIZE(vd),
747 		    vdev_uberblock_sync_done, NULL);
748 
749 	dprintf("vdev %s in txg %llu\n", vdev_description(vd), txg);
750 }
751 
752 static int
753 vdev_uberblock_sync_tree(spa_t *spa, uberblock_t *ub, vdev_t *vd, uint64_t txg)
754 {
755 	uberblock_t *ubbuf;
756 	size_t size = vd->vdev_top ? VDEV_UBERBLOCK_SIZE(vd) : SPA_MAXBLOCKSIZE;
757 	uint64_t *good_writes;
758 	zio_t *zio;
759 	int error;
760 
761 	ubbuf = zio_buf_alloc(size);
762 	bzero(ubbuf, size);
763 	*ubbuf = *ub;
764 
765 	good_writes = kmem_zalloc(sizeof (uint64_t), KM_SLEEP);
766 
767 	zio = zio_root(spa, NULL, good_writes,
768 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL);
769 
770 	vdev_uberblock_sync(zio, ubbuf, vd, txg);
771 
772 	error = zio_wait(zio);
773 
774 	if (error && *good_writes != 0) {
775 		dprintf("partial success: good_writes = %llu\n", *good_writes);
776 		error = 0;
777 	}
778 
779 	/*
780 	 * It's possible to have no good writes and no error if every vdev is in
781 	 * the CANT_OPEN state.
782 	 */
783 	if (*good_writes == 0 && error == 0)
784 		error = EIO;
785 
786 	kmem_free(good_writes, sizeof (uint64_t));
787 	zio_buf_free(ubbuf, size);
788 
789 	return (error);
790 }
791 
792 /*
793  * Sync out an individual vdev.
794  */
795 static void
796 vdev_sync_label_done(zio_t *zio)
797 {
798 	uint64_t *good_writes = zio->io_root->io_private;
799 
800 	if (zio->io_error == 0)
801 		atomic_add_64(good_writes, 1);
802 }
803 
804 static void
805 vdev_sync_label(zio_t *zio, vdev_t *vd, int l, uint64_t txg)
806 {
807 	nvlist_t *label;
808 	vdev_phys_t *vp;
809 	char *buf;
810 	size_t buflen;
811 	int c;
812 
813 	for (c = 0; c < vd->vdev_children; c++)
814 		vdev_sync_label(zio, vd->vdev_child[c], l, txg);
815 
816 	if (!vd->vdev_ops->vdev_op_leaf)
817 		return;
818 
819 	if (vdev_is_dead(vd))
820 		return;
821 
822 	/*
823 	 * Generate a label describing the top-level config to which we belong.
824 	 */
825 	label = spa_config_generate(vd->vdev_spa, vd, txg, B_FALSE);
826 
827 	vp = zio_buf_alloc(sizeof (vdev_phys_t));
828 	bzero(vp, sizeof (vdev_phys_t));
829 
830 	buf = vp->vp_nvlist;
831 	buflen = sizeof (vp->vp_nvlist);
832 
833 	if (nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP) == 0)
834 		vdev_label_write(zio, vd, l, vp,
835 		    offsetof(vdev_label_t, vl_vdev_phys), sizeof (vdev_phys_t),
836 		    vdev_sync_label_done, NULL);
837 
838 	zio_buf_free(vp, sizeof (vdev_phys_t));
839 	nvlist_free(label);
840 
841 	dprintf("%s label %d txg %llu\n", vdev_description(vd), l, txg);
842 }
843 
844 static int
845 vdev_sync_labels(vdev_t *vd, int l, uint64_t txg)
846 {
847 	uint64_t *good_writes;
848 	zio_t *zio;
849 	int error;
850 
851 	ASSERT(vd == vd->vdev_top);
852 
853 	good_writes = kmem_zalloc(sizeof (uint64_t), KM_SLEEP);
854 
855 	zio = zio_root(vd->vdev_spa, NULL, good_writes,
856 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL);
857 
858 	/*
859 	 * Recursively kick off writes to all labels.
860 	 */
861 	vdev_sync_label(zio, vd, l, txg);
862 
863 	error = zio_wait(zio);
864 
865 	if (error && *good_writes != 0) {
866 		dprintf("partial success: good_writes = %llu\n", *good_writes);
867 		error = 0;
868 	}
869 
870 	if (*good_writes == 0 && error == 0)
871 		error = ENODEV;
872 
873 	/*
874 	 * Failure to write a label can be fatal for a
875 	 * top level vdev. We don't want this for slogs
876 	 * as we use the main pool if they go away.
877 	 */
878 	if (vd->vdev_islog)
879 		error = 0;
880 
881 	kmem_free(good_writes, sizeof (uint64_t));
882 
883 	return (error);
884 }
885 
886 /*
887  * Sync the entire vdev configuration.
888  *
889  * The order of operations is carefully crafted to ensure that
890  * if the system panics or loses power at any time, the state on disk
891  * is still transactionally consistent.  The in-line comments below
892  * describe the failure semantics at each stage.
893  *
894  * Moreover, it is designed to be idempotent: if spa_sync_labels() fails
895  * at any time, you can just call it again, and it will resume its work.
896  */
897 int
898 vdev_config_sync(vdev_t *uvd, uint64_t txg)
899 {
900 	spa_t *spa = uvd->vdev_spa;
901 	uberblock_t *ub = &spa->spa_uberblock;
902 	vdev_t *rvd = spa->spa_root_vdev;
903 	vdev_t *vd;
904 	zio_t *zio;
905 	int l, error;
906 
907 	ASSERT(ub->ub_txg <= txg);
908 
909 	/*
910 	 * If this isn't a resync due to I/O errors, and nothing changed
911 	 * in this transaction group, and the vdev configuration hasn't changed,
912 	 * then there's nothing to do.
913 	 */
914 	if (ub->ub_txg < txg && uberblock_update(ub, rvd, txg) == B_FALSE &&
915 	    list_is_empty(&spa->spa_dirty_list)) {
916 		dprintf("nothing to sync in %s in txg %llu\n",
917 		    spa_name(spa), txg);
918 		return (0);
919 	}
920 
921 	if (txg > spa_freeze_txg(spa))
922 		return (0);
923 
924 	ASSERT(txg <= spa->spa_final_txg);
925 
926 	dprintf("syncing %s txg %llu\n", spa_name(spa), txg);
927 
928 	/*
929 	 * Flush the write cache of every disk that's been written to
930 	 * in this transaction group.  This ensures that all blocks
931 	 * written in this txg will be committed to stable storage
932 	 * before any uberblock that references them.
933 	 */
934 	zio = zio_root(spa, NULL, NULL,
935 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL);
936 	for (vd = txg_list_head(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)); vd;
937 	    vd = txg_list_next(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg))) {
938 		zio_nowait(zio_ioctl(zio, spa, vd, DKIOCFLUSHWRITECACHE,
939 		    NULL, NULL, ZIO_PRIORITY_NOW,
940 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY));
941 	}
942 	(void) zio_wait(zio);
943 
944 	/*
945 	 * Sync out the even labels (L0, L2) for every dirty vdev.  If the
946 	 * system dies in the middle of this process, that's OK: all of the
947 	 * even labels that made it to disk will be newer than any uberblock,
948 	 * and will therefore be considered invalid.  The odd labels (L1, L3),
949 	 * which have not yet been touched, will still be valid.
950 	 */
951 	for (vd = list_head(&spa->spa_dirty_list); vd != NULL;
952 	    vd = list_next(&spa->spa_dirty_list, vd)) {
953 		for (l = 0; l < VDEV_LABELS; l++) {
954 			if (l & 1)
955 				continue;
956 			if ((error = vdev_sync_labels(vd, l, txg)) != 0)
957 				return (error);
958 		}
959 	}
960 
961 	/*
962 	 * Flush the new labels to disk.  This ensures that all even-label
963 	 * updates are committed to stable storage before the uberblock update.
964 	 */
965 	zio = zio_root(spa, NULL, NULL,
966 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL);
967 	for (vd = list_head(&spa->spa_dirty_list); vd != NULL;
968 	    vd = list_next(&spa->spa_dirty_list, vd)) {
969 		zio_nowait(zio_ioctl(zio, spa, vd, DKIOCFLUSHWRITECACHE,
970 		    NULL, NULL, ZIO_PRIORITY_NOW,
971 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY));
972 	}
973 	(void) zio_wait(zio);
974 
975 	/*
976 	 * Sync the uberblocks to all vdevs in the tree specified by uvd.
977 	 * If the system dies in the middle of this step, there are two cases
978 	 * to consider, and the on-disk state is consistent either way:
979 	 *
980 	 * (1)	If none of the new uberblocks made it to disk, then the
981 	 *	previous uberblock will be the newest, and the odd labels
982 	 *	(which had not yet been touched) will be valid with respect
983 	 *	to that uberblock.
984 	 *
985 	 * (2)	If one or more new uberblocks made it to disk, then they
986 	 *	will be the newest, and the even labels (which had all
987 	 *	been successfully committed) will be valid with respect
988 	 *	to the new uberblocks.
989 	 */
990 	if ((error = vdev_uberblock_sync_tree(spa, ub, uvd, txg)) != 0)
991 		return (error);
992 
993 	/*
994 	 * Flush the uberblocks to disk.  This ensures that the odd labels
995 	 * are no longer needed (because the new uberblocks and the even
996 	 * labels are safely on disk), so it is safe to overwrite them.
997 	 */
998 	(void) zio_wait(zio_ioctl(NULL, spa, uvd, DKIOCFLUSHWRITECACHE,
999 	    NULL, NULL, ZIO_PRIORITY_NOW,
1000 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY));
1001 
1002 	/*
1003 	 * Sync out odd labels for every dirty vdev.  If the system dies
1004 	 * in the middle of this process, the even labels and the new
1005 	 * uberblocks will suffice to open the pool.  The next time
1006 	 * the pool is opened, the first thing we'll do -- before any
1007 	 * user data is modified -- is mark every vdev dirty so that
1008 	 * all labels will be brought up to date.
1009 	 */
1010 	for (vd = list_head(&spa->spa_dirty_list); vd != NULL;
1011 	    vd = list_next(&spa->spa_dirty_list, vd)) {
1012 		for (l = 0; l < VDEV_LABELS; l++) {
1013 			if ((l & 1) == 0)
1014 				continue;
1015 			if ((error = vdev_sync_labels(vd, l, txg)) != 0)
1016 				return (error);
1017 		}
1018 	}
1019 
1020 	/*
1021 	 * Flush the new labels to disk.  This ensures that all odd-label
1022 	 * updates are committed to stable storage before the next
1023 	 * transaction group begins.
1024 	 */
1025 	zio = zio_root(spa, NULL, NULL,
1026 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL);
1027 	for (vd = list_head(&spa->spa_dirty_list); vd != NULL;
1028 	    vd = list_next(&spa->spa_dirty_list, vd)) {
1029 		zio_nowait(zio_ioctl(zio, spa, vd, DKIOCFLUSHWRITECACHE,
1030 		    NULL, NULL, ZIO_PRIORITY_NOW,
1031 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_RETRY));
1032 	}
1033 	(void) zio_wait(zio);
1034 
1035 	return (0);
1036 }
1037