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