xref: /freebsd/sys/contrib/openzfs/module/zfs/vdev_label.c (revision 36c970ed985ff3dd5443db4bf2aa58799028512c)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright (c) 2012, 2020 by Delphix. All rights reserved.
26  * Copyright (c) 2017, Intel Corporation.
27  */
28 
29 /*
30  * Virtual Device Labels
31  * ---------------------
32  *
33  * The vdev label serves several distinct purposes:
34  *
35  *	1. Uniquely identify this device as part of a ZFS pool and confirm its
36  *	   identity within the pool.
37  *
38  *	2. Verify that all the devices given in a configuration are present
39  *         within the pool.
40  *
41  *	3. Determine the uberblock for the pool.
42  *
43  *	4. In case of an import operation, determine the configuration of the
44  *         toplevel vdev of which it is a part.
45  *
46  *	5. If an import operation cannot find all the devices in the pool,
47  *         provide enough information to the administrator to determine which
48  *         devices are missing.
49  *
50  * It is important to note that while the kernel is responsible for writing the
51  * label, it only consumes the information in the first three cases.  The
52  * latter information is only consumed in userland when determining the
53  * configuration to import a pool.
54  *
55  *
56  * Label Organization
57  * ------------------
58  *
59  * Before describing the contents of the label, it's important to understand how
60  * the labels are written and updated with respect to the uberblock.
61  *
62  * When the pool configuration is altered, either because it was newly created
63  * or a device was added, we want to update all the labels such that we can deal
64  * with fatal failure at any point.  To this end, each disk has two labels which
65  * are updated before and after the uberblock is synced.  Assuming we have
66  * labels and an uberblock with the following transaction groups:
67  *
68  *              L1          UB          L2
69  *           +------+    +------+    +------+
70  *           |      |    |      |    |      |
71  *           | t10  |    | t10  |    | t10  |
72  *           |      |    |      |    |      |
73  *           +------+    +------+    +------+
74  *
75  * In this stable state, the labels and the uberblock were all updated within
76  * the same transaction group (10).  Each label is mirrored and checksummed, so
77  * that we can detect when we fail partway through writing the label.
78  *
79  * In order to identify which labels are valid, the labels are written in the
80  * following manner:
81  *
82  *	1. For each vdev, update 'L1' to the new label
83  *	2. Update the uberblock
84  *	3. For each vdev, update 'L2' to the new label
85  *
86  * Given arbitrary failure, we can determine the correct label to use based on
87  * the transaction group.  If we fail after updating L1 but before updating the
88  * UB, we will notice that L1's transaction group is greater than the uberblock,
89  * so L2 must be valid.  If we fail after writing the uberblock but before
90  * writing L2, we will notice that L2's transaction group is less than L1, and
91  * therefore L1 is valid.
92  *
93  * Another added complexity is that not every label is updated when the config
94  * is synced.  If we add a single device, we do not want to have to re-write
95  * every label for every device in the pool.  This means that both L1 and L2 may
96  * be older than the pool uberblock, because the necessary information is stored
97  * on another vdev.
98  *
99  *
100  * On-disk Format
101  * --------------
102  *
103  * The vdev label consists of two distinct parts, and is wrapped within the
104  * vdev_label_t structure.  The label includes 8k of padding to permit legacy
105  * VTOC disk labels, but is otherwise ignored.
106  *
107  * The first half of the label is a packed nvlist which contains pool wide
108  * properties, per-vdev properties, and configuration information.  It is
109  * described in more detail below.
110  *
111  * The latter half of the label consists of a redundant array of uberblocks.
112  * These uberblocks are updated whenever a transaction group is committed,
113  * or when the configuration is updated.  When a pool is loaded, we scan each
114  * vdev for the 'best' uberblock.
115  *
116  *
117  * Configuration Information
118  * -------------------------
119  *
120  * The nvlist describing the pool and vdev contains the following elements:
121  *
122  *	version		ZFS on-disk version
123  *	name		Pool name
124  *	state		Pool state
125  *	txg		Transaction group in which this label was written
126  *	pool_guid	Unique identifier for this pool
127  *	vdev_tree	An nvlist describing vdev tree.
128  *	features_for_read
129  *			An nvlist of the features necessary for reading the MOS.
130  *
131  * Each leaf device label also contains the following:
132  *
133  *	top_guid	Unique ID for top-level vdev in which this is contained
134  *	guid		Unique ID for the leaf vdev
135  *
136  * The 'vs' configuration follows the format described in 'spa_config.c'.
137  */
138 
139 #include <sys/zfs_context.h>
140 #include <sys/spa.h>
141 #include <sys/spa_impl.h>
142 #include <sys/dmu.h>
143 #include <sys/zap.h>
144 #include <sys/vdev.h>
145 #include <sys/vdev_impl.h>
146 #include <sys/vdev_raidz.h>
147 #include <sys/vdev_draid.h>
148 #include <sys/uberblock_impl.h>
149 #include <sys/metaslab.h>
150 #include <sys/metaslab_impl.h>
151 #include <sys/zio.h>
152 #include <sys/dsl_scan.h>
153 #include <sys/abd.h>
154 #include <sys/fs/zfs.h>
155 #include <sys/byteorder.h>
156 #include <sys/zfs_bootenv.h>
157 
158 /*
159  * Basic routines to read and write from a vdev label.
160  * Used throughout the rest of this file.
161  */
162 uint64_t
vdev_label_offset(uint64_t psize,int l,uint64_t offset)163 vdev_label_offset(uint64_t psize, int l, uint64_t offset)
164 {
165 	ASSERT(offset < sizeof (vdev_label_t));
166 	ASSERT0(P2PHASE_TYPED(psize, sizeof (vdev_label_t), uint64_t));
167 
168 	return (offset + l * sizeof (vdev_label_t) + (l < VDEV_LABELS / 2 ?
169 	    0 : psize - VDEV_LABELS * sizeof (vdev_label_t)));
170 }
171 
172 /*
173  * Returns back the vdev label associated with the passed in offset.
174  */
175 int
vdev_label_number(uint64_t psize,uint64_t offset)176 vdev_label_number(uint64_t psize, uint64_t offset)
177 {
178 	int l;
179 
180 	if (offset >= psize - VDEV_LABEL_END_SIZE) {
181 		offset -= psize - VDEV_LABEL_END_SIZE;
182 		offset += (VDEV_LABELS / 2) * sizeof (vdev_label_t);
183 	}
184 	l = offset / sizeof (vdev_label_t);
185 	return (l < VDEV_LABELS ? l : -1);
186 }
187 
188 static void
vdev_label_read(zio_t * zio,vdev_t * vd,int l,abd_t * buf,uint64_t offset,uint64_t size,zio_done_func_t * done,void * private,int flags)189 vdev_label_read(zio_t *zio, vdev_t *vd, int l, abd_t *buf, uint64_t offset,
190     uint64_t size, zio_done_func_t *done, void *private, int flags)
191 {
192 	ASSERT(
193 	    spa_config_held(zio->io_spa, SCL_STATE, RW_READER) == SCL_STATE ||
194 	    spa_config_held(zio->io_spa, SCL_STATE, RW_WRITER) == SCL_STATE);
195 	ASSERT(flags & ZIO_FLAG_CONFIG_WRITER);
196 
197 	zio_nowait(zio_read_phys(zio, vd,
198 	    vdev_label_offset(vd->vdev_psize, l, offset),
199 	    size, buf, ZIO_CHECKSUM_LABEL, done, private,
200 	    ZIO_PRIORITY_SYNC_READ, flags, B_TRUE));
201 }
202 
203 void
vdev_label_write(zio_t * zio,vdev_t * vd,int l,abd_t * buf,uint64_t offset,uint64_t size,zio_done_func_t * done,void * private,int flags)204 vdev_label_write(zio_t *zio, vdev_t *vd, int l, abd_t *buf, uint64_t offset,
205     uint64_t size, zio_done_func_t *done, void *private, int flags)
206 {
207 	ASSERT(
208 	    spa_config_held(zio->io_spa, SCL_STATE, RW_READER) == SCL_STATE ||
209 	    spa_config_held(zio->io_spa, SCL_STATE, RW_WRITER) == SCL_STATE);
210 	ASSERT(flags & ZIO_FLAG_CONFIG_WRITER);
211 
212 	zio_nowait(zio_write_phys(zio, vd,
213 	    vdev_label_offset(vd->vdev_psize, l, offset),
214 	    size, buf, ZIO_CHECKSUM_LABEL, done, private,
215 	    ZIO_PRIORITY_SYNC_WRITE, flags, B_TRUE));
216 }
217 
218 /*
219  * Generate the nvlist representing this vdev's stats
220  */
221 void
vdev_config_generate_stats(vdev_t * vd,nvlist_t * nv)222 vdev_config_generate_stats(vdev_t *vd, nvlist_t *nv)
223 {
224 	nvlist_t *nvx;
225 	vdev_stat_t *vs;
226 	vdev_stat_ex_t *vsx;
227 
228 	vs = kmem_alloc(sizeof (*vs), KM_SLEEP);
229 	vsx = kmem_alloc(sizeof (*vsx), KM_SLEEP);
230 
231 	vdev_get_stats_ex(vd, vs, vsx);
232 	fnvlist_add_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
233 	    (uint64_t *)vs, sizeof (*vs) / sizeof (uint64_t));
234 
235 	/*
236 	 * Add extended stats into a special extended stats nvlist.  This keeps
237 	 * all the extended stats nicely grouped together.  The extended stats
238 	 * nvlist is then added to the main nvlist.
239 	 */
240 	nvx = fnvlist_alloc();
241 
242 	/* ZIOs in flight to disk */
243 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_SYNC_R_ACTIVE_QUEUE,
244 	    vsx->vsx_active_queue[ZIO_PRIORITY_SYNC_READ]);
245 
246 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_SYNC_W_ACTIVE_QUEUE,
247 	    vsx->vsx_active_queue[ZIO_PRIORITY_SYNC_WRITE]);
248 
249 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_ASYNC_R_ACTIVE_QUEUE,
250 	    vsx->vsx_active_queue[ZIO_PRIORITY_ASYNC_READ]);
251 
252 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_ASYNC_W_ACTIVE_QUEUE,
253 	    vsx->vsx_active_queue[ZIO_PRIORITY_ASYNC_WRITE]);
254 
255 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_SCRUB_ACTIVE_QUEUE,
256 	    vsx->vsx_active_queue[ZIO_PRIORITY_SCRUB]);
257 
258 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_TRIM_ACTIVE_QUEUE,
259 	    vsx->vsx_active_queue[ZIO_PRIORITY_TRIM]);
260 
261 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_REBUILD_ACTIVE_QUEUE,
262 	    vsx->vsx_active_queue[ZIO_PRIORITY_REBUILD]);
263 
264 	/* ZIOs pending */
265 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_SYNC_R_PEND_QUEUE,
266 	    vsx->vsx_pend_queue[ZIO_PRIORITY_SYNC_READ]);
267 
268 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_SYNC_W_PEND_QUEUE,
269 	    vsx->vsx_pend_queue[ZIO_PRIORITY_SYNC_WRITE]);
270 
271 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_ASYNC_R_PEND_QUEUE,
272 	    vsx->vsx_pend_queue[ZIO_PRIORITY_ASYNC_READ]);
273 
274 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_ASYNC_W_PEND_QUEUE,
275 	    vsx->vsx_pend_queue[ZIO_PRIORITY_ASYNC_WRITE]);
276 
277 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_SCRUB_PEND_QUEUE,
278 	    vsx->vsx_pend_queue[ZIO_PRIORITY_SCRUB]);
279 
280 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_TRIM_PEND_QUEUE,
281 	    vsx->vsx_pend_queue[ZIO_PRIORITY_TRIM]);
282 
283 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_REBUILD_PEND_QUEUE,
284 	    vsx->vsx_pend_queue[ZIO_PRIORITY_REBUILD]);
285 
286 	/* Histograms */
287 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_TOT_R_LAT_HISTO,
288 	    vsx->vsx_total_histo[ZIO_TYPE_READ],
289 	    ARRAY_SIZE(vsx->vsx_total_histo[ZIO_TYPE_READ]));
290 
291 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_TOT_W_LAT_HISTO,
292 	    vsx->vsx_total_histo[ZIO_TYPE_WRITE],
293 	    ARRAY_SIZE(vsx->vsx_total_histo[ZIO_TYPE_WRITE]));
294 
295 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_DISK_R_LAT_HISTO,
296 	    vsx->vsx_disk_histo[ZIO_TYPE_READ],
297 	    ARRAY_SIZE(vsx->vsx_disk_histo[ZIO_TYPE_READ]));
298 
299 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_DISK_W_LAT_HISTO,
300 	    vsx->vsx_disk_histo[ZIO_TYPE_WRITE],
301 	    ARRAY_SIZE(vsx->vsx_disk_histo[ZIO_TYPE_WRITE]));
302 
303 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_SYNC_R_LAT_HISTO,
304 	    vsx->vsx_queue_histo[ZIO_PRIORITY_SYNC_READ],
305 	    ARRAY_SIZE(vsx->vsx_queue_histo[ZIO_PRIORITY_SYNC_READ]));
306 
307 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_SYNC_W_LAT_HISTO,
308 	    vsx->vsx_queue_histo[ZIO_PRIORITY_SYNC_WRITE],
309 	    ARRAY_SIZE(vsx->vsx_queue_histo[ZIO_PRIORITY_SYNC_WRITE]));
310 
311 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_ASYNC_R_LAT_HISTO,
312 	    vsx->vsx_queue_histo[ZIO_PRIORITY_ASYNC_READ],
313 	    ARRAY_SIZE(vsx->vsx_queue_histo[ZIO_PRIORITY_ASYNC_READ]));
314 
315 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_ASYNC_W_LAT_HISTO,
316 	    vsx->vsx_queue_histo[ZIO_PRIORITY_ASYNC_WRITE],
317 	    ARRAY_SIZE(vsx->vsx_queue_histo[ZIO_PRIORITY_ASYNC_WRITE]));
318 
319 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_SCRUB_LAT_HISTO,
320 	    vsx->vsx_queue_histo[ZIO_PRIORITY_SCRUB],
321 	    ARRAY_SIZE(vsx->vsx_queue_histo[ZIO_PRIORITY_SCRUB]));
322 
323 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_TRIM_LAT_HISTO,
324 	    vsx->vsx_queue_histo[ZIO_PRIORITY_TRIM],
325 	    ARRAY_SIZE(vsx->vsx_queue_histo[ZIO_PRIORITY_TRIM]));
326 
327 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_REBUILD_LAT_HISTO,
328 	    vsx->vsx_queue_histo[ZIO_PRIORITY_REBUILD],
329 	    ARRAY_SIZE(vsx->vsx_queue_histo[ZIO_PRIORITY_REBUILD]));
330 
331 	/* Request sizes */
332 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_SYNC_IND_R_HISTO,
333 	    vsx->vsx_ind_histo[ZIO_PRIORITY_SYNC_READ],
334 	    ARRAY_SIZE(vsx->vsx_ind_histo[ZIO_PRIORITY_SYNC_READ]));
335 
336 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_SYNC_IND_W_HISTO,
337 	    vsx->vsx_ind_histo[ZIO_PRIORITY_SYNC_WRITE],
338 	    ARRAY_SIZE(vsx->vsx_ind_histo[ZIO_PRIORITY_SYNC_WRITE]));
339 
340 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_ASYNC_IND_R_HISTO,
341 	    vsx->vsx_ind_histo[ZIO_PRIORITY_ASYNC_READ],
342 	    ARRAY_SIZE(vsx->vsx_ind_histo[ZIO_PRIORITY_ASYNC_READ]));
343 
344 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_ASYNC_IND_W_HISTO,
345 	    vsx->vsx_ind_histo[ZIO_PRIORITY_ASYNC_WRITE],
346 	    ARRAY_SIZE(vsx->vsx_ind_histo[ZIO_PRIORITY_ASYNC_WRITE]));
347 
348 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_IND_SCRUB_HISTO,
349 	    vsx->vsx_ind_histo[ZIO_PRIORITY_SCRUB],
350 	    ARRAY_SIZE(vsx->vsx_ind_histo[ZIO_PRIORITY_SCRUB]));
351 
352 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_IND_TRIM_HISTO,
353 	    vsx->vsx_ind_histo[ZIO_PRIORITY_TRIM],
354 	    ARRAY_SIZE(vsx->vsx_ind_histo[ZIO_PRIORITY_TRIM]));
355 
356 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_IND_REBUILD_HISTO,
357 	    vsx->vsx_ind_histo[ZIO_PRIORITY_REBUILD],
358 	    ARRAY_SIZE(vsx->vsx_ind_histo[ZIO_PRIORITY_REBUILD]));
359 
360 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_SYNC_AGG_R_HISTO,
361 	    vsx->vsx_agg_histo[ZIO_PRIORITY_SYNC_READ],
362 	    ARRAY_SIZE(vsx->vsx_agg_histo[ZIO_PRIORITY_SYNC_READ]));
363 
364 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_SYNC_AGG_W_HISTO,
365 	    vsx->vsx_agg_histo[ZIO_PRIORITY_SYNC_WRITE],
366 	    ARRAY_SIZE(vsx->vsx_agg_histo[ZIO_PRIORITY_SYNC_WRITE]));
367 
368 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_ASYNC_AGG_R_HISTO,
369 	    vsx->vsx_agg_histo[ZIO_PRIORITY_ASYNC_READ],
370 	    ARRAY_SIZE(vsx->vsx_agg_histo[ZIO_PRIORITY_ASYNC_READ]));
371 
372 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_ASYNC_AGG_W_HISTO,
373 	    vsx->vsx_agg_histo[ZIO_PRIORITY_ASYNC_WRITE],
374 	    ARRAY_SIZE(vsx->vsx_agg_histo[ZIO_PRIORITY_ASYNC_WRITE]));
375 
376 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_AGG_SCRUB_HISTO,
377 	    vsx->vsx_agg_histo[ZIO_PRIORITY_SCRUB],
378 	    ARRAY_SIZE(vsx->vsx_agg_histo[ZIO_PRIORITY_SCRUB]));
379 
380 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_AGG_TRIM_HISTO,
381 	    vsx->vsx_agg_histo[ZIO_PRIORITY_TRIM],
382 	    ARRAY_SIZE(vsx->vsx_agg_histo[ZIO_PRIORITY_TRIM]));
383 
384 	fnvlist_add_uint64_array(nvx, ZPOOL_CONFIG_VDEV_AGG_REBUILD_HISTO,
385 	    vsx->vsx_agg_histo[ZIO_PRIORITY_REBUILD],
386 	    ARRAY_SIZE(vsx->vsx_agg_histo[ZIO_PRIORITY_REBUILD]));
387 
388 	/* IO delays */
389 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_SLOW_IOS, vs->vs_slow_ios);
390 
391 	/* Direct I/O write verify errors */
392 	fnvlist_add_uint64(nvx, ZPOOL_CONFIG_VDEV_DIO_VERIFY_ERRORS,
393 	    vs->vs_dio_verify_errors);
394 
395 	/* Add extended stats nvlist to main nvlist */
396 	fnvlist_add_nvlist(nv, ZPOOL_CONFIG_VDEV_STATS_EX, nvx);
397 
398 	fnvlist_free(nvx);
399 	kmem_free(vs, sizeof (*vs));
400 	kmem_free(vsx, sizeof (*vsx));
401 }
402 
403 static void
root_vdev_actions_getprogress(vdev_t * vd,nvlist_t * nvl)404 root_vdev_actions_getprogress(vdev_t *vd, nvlist_t *nvl)
405 {
406 	spa_t *spa = vd->vdev_spa;
407 
408 	if (vd != spa->spa_root_vdev)
409 		return;
410 
411 	/* provide either current or previous scan information */
412 	pool_scan_stat_t ps;
413 	if (spa_scan_get_stats(spa, &ps) == 0) {
414 		fnvlist_add_uint64_array(nvl,
415 		    ZPOOL_CONFIG_SCAN_STATS, (uint64_t *)&ps,
416 		    sizeof (pool_scan_stat_t) / sizeof (uint64_t));
417 	}
418 
419 	pool_removal_stat_t prs;
420 	if (spa_removal_get_stats(spa, &prs) == 0) {
421 		fnvlist_add_uint64_array(nvl,
422 		    ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t *)&prs,
423 		    sizeof (prs) / sizeof (uint64_t));
424 	}
425 
426 	pool_checkpoint_stat_t pcs;
427 	if (spa_checkpoint_get_stats(spa, &pcs) == 0) {
428 		fnvlist_add_uint64_array(nvl,
429 		    ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t *)&pcs,
430 		    sizeof (pcs) / sizeof (uint64_t));
431 	}
432 
433 	pool_raidz_expand_stat_t pres;
434 	if (spa_raidz_expand_get_stats(spa, &pres) == 0) {
435 		fnvlist_add_uint64_array(nvl,
436 		    ZPOOL_CONFIG_RAIDZ_EXPAND_STATS, (uint64_t *)&pres,
437 		    sizeof (pres) / sizeof (uint64_t));
438 	}
439 }
440 
441 static void
top_vdev_actions_getprogress(vdev_t * vd,nvlist_t * nvl)442 top_vdev_actions_getprogress(vdev_t *vd, nvlist_t *nvl)
443 {
444 	if (vd == vd->vdev_top) {
445 		vdev_rebuild_stat_t vrs;
446 		if (vdev_rebuild_get_stats(vd, &vrs) == 0) {
447 			fnvlist_add_uint64_array(nvl,
448 			    ZPOOL_CONFIG_REBUILD_STATS, (uint64_t *)&vrs,
449 			    sizeof (vrs) / sizeof (uint64_t));
450 		}
451 	}
452 }
453 
454 /*
455  * Generate the nvlist representing this vdev's config.
456  */
457 nvlist_t *
vdev_config_generate(spa_t * spa,vdev_t * vd,boolean_t getstats,vdev_config_flag_t flags)458 vdev_config_generate(spa_t *spa, vdev_t *vd, boolean_t getstats,
459     vdev_config_flag_t flags)
460 {
461 	nvlist_t *nv = NULL;
462 	vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
463 
464 	nv = fnvlist_alloc();
465 
466 	fnvlist_add_string(nv, ZPOOL_CONFIG_TYPE, vd->vdev_ops->vdev_op_type);
467 	if (!(flags & (VDEV_CONFIG_SPARE | VDEV_CONFIG_L2CACHE)))
468 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_ID, vd->vdev_id);
469 	fnvlist_add_uint64(nv, ZPOOL_CONFIG_GUID, vd->vdev_guid);
470 
471 	if (vd->vdev_path != NULL)
472 		fnvlist_add_string(nv, ZPOOL_CONFIG_PATH, vd->vdev_path);
473 
474 	if (vd->vdev_devid != NULL)
475 		fnvlist_add_string(nv, ZPOOL_CONFIG_DEVID, vd->vdev_devid);
476 
477 	if (vd->vdev_physpath != NULL)
478 		fnvlist_add_string(nv, ZPOOL_CONFIG_PHYS_PATH,
479 		    vd->vdev_physpath);
480 
481 	if (vd->vdev_enc_sysfs_path != NULL)
482 		fnvlist_add_string(nv, ZPOOL_CONFIG_VDEV_ENC_SYSFS_PATH,
483 		    vd->vdev_enc_sysfs_path);
484 
485 	if (vd->vdev_fru != NULL)
486 		fnvlist_add_string(nv, ZPOOL_CONFIG_FRU, vd->vdev_fru);
487 
488 	if (vd->vdev_ops->vdev_op_config_generate != NULL)
489 		vd->vdev_ops->vdev_op_config_generate(vd, nv);
490 
491 	if (vd->vdev_wholedisk != -1ULL) {
492 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
493 		    vd->vdev_wholedisk);
494 	}
495 
496 	if (vd->vdev_not_present && !(flags & VDEV_CONFIG_MISSING))
497 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT, 1);
498 
499 	if (vd->vdev_isspare)
500 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_IS_SPARE, 1);
501 
502 	if (flags & VDEV_CONFIG_L2CACHE)
503 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_ASHIFT, vd->vdev_ashift);
504 
505 	if (!(flags & (VDEV_CONFIG_SPARE | VDEV_CONFIG_L2CACHE)) &&
506 	    vd == vd->vdev_top) {
507 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
508 		    vd->vdev_ms_array);
509 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
510 		    vd->vdev_ms_shift);
511 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_ASHIFT, vd->vdev_ashift);
512 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_ASIZE,
513 		    vd->vdev_asize);
514 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_MIN_ALLOC,
515 		    vdev_get_min_alloc(vd));
516 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_IS_LOG, vd->vdev_islog);
517 		if (vd->vdev_noalloc) {
518 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_NONALLOCATING,
519 			    vd->vdev_noalloc);
520 		}
521 
522 		/*
523 		 * Slog devices are removed synchronously so don't
524 		 * persist the vdev_removing flag to the label.
525 		 */
526 		if (vd->vdev_removing && !vd->vdev_islog) {
527 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_REMOVING,
528 			    vd->vdev_removing);
529 		}
530 
531 		/* zpool command expects alloc class data */
532 		if (getstats && vd->vdev_alloc_bias != VDEV_BIAS_NONE) {
533 			const char *bias = NULL;
534 
535 			switch (vd->vdev_alloc_bias) {
536 			case VDEV_BIAS_LOG:
537 				bias = VDEV_ALLOC_BIAS_LOG;
538 				break;
539 			case VDEV_BIAS_SPECIAL:
540 				bias = VDEV_ALLOC_BIAS_SPECIAL;
541 				break;
542 			case VDEV_BIAS_DEDUP:
543 				bias = VDEV_ALLOC_BIAS_DEDUP;
544 				break;
545 			default:
546 				ASSERT3U(vd->vdev_alloc_bias, ==,
547 				    VDEV_BIAS_NONE);
548 			}
549 			fnvlist_add_string(nv, ZPOOL_CONFIG_ALLOCATION_BIAS,
550 			    bias);
551 		}
552 	}
553 
554 	if (vd->vdev_dtl_sm != NULL) {
555 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_DTL,
556 		    space_map_object(vd->vdev_dtl_sm));
557 	}
558 
559 	if (vic->vic_mapping_object != 0) {
560 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_INDIRECT_OBJECT,
561 		    vic->vic_mapping_object);
562 	}
563 
564 	if (vic->vic_births_object != 0) {
565 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_INDIRECT_BIRTHS,
566 		    vic->vic_births_object);
567 	}
568 
569 	if (vic->vic_prev_indirect_vdev != UINT64_MAX) {
570 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_PREV_INDIRECT_VDEV,
571 		    vic->vic_prev_indirect_vdev);
572 	}
573 
574 	if (vd->vdev_crtxg)
575 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_CREATE_TXG, vd->vdev_crtxg);
576 
577 	if (vd->vdev_expansion_time)
578 		fnvlist_add_uint64(nv, ZPOOL_CONFIG_EXPANSION_TIME,
579 		    vd->vdev_expansion_time);
580 
581 	if (flags & VDEV_CONFIG_MOS) {
582 		if (vd->vdev_leaf_zap != 0) {
583 			ASSERT(vd->vdev_ops->vdev_op_leaf);
584 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_VDEV_LEAF_ZAP,
585 			    vd->vdev_leaf_zap);
586 		}
587 
588 		if (vd->vdev_top_zap != 0) {
589 			ASSERT(vd == vd->vdev_top);
590 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_VDEV_TOP_ZAP,
591 			    vd->vdev_top_zap);
592 		}
593 
594 		if (vd->vdev_ops == &vdev_root_ops && vd->vdev_root_zap != 0 &&
595 		    spa_feature_is_active(vd->vdev_spa, SPA_FEATURE_AVZ_V2)) {
596 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_VDEV_ROOT_ZAP,
597 			    vd->vdev_root_zap);
598 		}
599 
600 		if (vd->vdev_resilver_deferred) {
601 			ASSERT(vd->vdev_ops->vdev_op_leaf);
602 			ASSERT(spa->spa_resilver_deferred);
603 			fnvlist_add_boolean(nv, ZPOOL_CONFIG_RESILVER_DEFER);
604 		}
605 	}
606 
607 	if (getstats) {
608 		vdev_config_generate_stats(vd, nv);
609 
610 		root_vdev_actions_getprogress(vd, nv);
611 		top_vdev_actions_getprogress(vd, nv);
612 
613 		/*
614 		 * Note: this can be called from open context
615 		 * (spa_get_stats()), so we need the rwlock to prevent
616 		 * the mapping from being changed by condensing.
617 		 */
618 		rw_enter(&vd->vdev_indirect_rwlock, RW_READER);
619 		if (vd->vdev_indirect_mapping != NULL) {
620 			ASSERT(vd->vdev_indirect_births != NULL);
621 			vdev_indirect_mapping_t *vim =
622 			    vd->vdev_indirect_mapping;
623 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_INDIRECT_SIZE,
624 			    vdev_indirect_mapping_size(vim));
625 		}
626 		rw_exit(&vd->vdev_indirect_rwlock);
627 		if (vd->vdev_mg != NULL &&
628 		    vd->vdev_mg->mg_fragmentation != ZFS_FRAG_INVALID) {
629 			/*
630 			 * Compute approximately how much memory would be used
631 			 * for the indirect mapping if this device were to
632 			 * be removed.
633 			 *
634 			 * Note: If the frag metric is invalid, then not
635 			 * enough metaslabs have been converted to have
636 			 * histograms.
637 			 */
638 			uint64_t seg_count = 0;
639 			uint64_t to_alloc = vd->vdev_stat.vs_alloc;
640 
641 			/*
642 			 * There are the same number of allocated segments
643 			 * as free segments, so we will have at least one
644 			 * entry per free segment.  However, small free
645 			 * segments (smaller than vdev_removal_max_span)
646 			 * will be combined with adjacent allocated segments
647 			 * as a single mapping.
648 			 */
649 			for (int i = 0; i < ZFS_RANGE_TREE_HISTOGRAM_SIZE;
650 			    i++) {
651 				if (i + 1 < highbit64(vdev_removal_max_span)
652 				    - 1) {
653 					to_alloc +=
654 					    vd->vdev_mg->mg_histogram[i] <<
655 					    (i + 1);
656 				} else {
657 					seg_count +=
658 					    vd->vdev_mg->mg_histogram[i];
659 				}
660 			}
661 
662 			/*
663 			 * The maximum length of a mapping is
664 			 * zfs_remove_max_segment, so we need at least one entry
665 			 * per zfs_remove_max_segment of allocated data.
666 			 */
667 			seg_count += to_alloc / spa_remove_max_segment(spa);
668 
669 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_INDIRECT_SIZE,
670 			    seg_count *
671 			    sizeof (vdev_indirect_mapping_entry_phys_t));
672 		}
673 	}
674 
675 	if (!vd->vdev_ops->vdev_op_leaf) {
676 		nvlist_t **child;
677 		uint64_t c;
678 
679 		ASSERT(!vd->vdev_ishole);
680 
681 		child = kmem_alloc(vd->vdev_children * sizeof (nvlist_t *),
682 		    KM_SLEEP);
683 
684 		for (c = 0; c < vd->vdev_children; c++) {
685 			child[c] = vdev_config_generate(spa, vd->vdev_child[c],
686 			    getstats, flags);
687 		}
688 
689 		fnvlist_add_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
690 		    (const nvlist_t * const *)child, vd->vdev_children);
691 
692 		for (c = 0; c < vd->vdev_children; c++)
693 			nvlist_free(child[c]);
694 
695 		kmem_free(child, vd->vdev_children * sizeof (nvlist_t *));
696 
697 	} else {
698 		const char *aux = NULL;
699 
700 		if (vd->vdev_offline && !vd->vdev_tmpoffline)
701 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_OFFLINE, B_TRUE);
702 		if (vd->vdev_resilver_txg != 0)
703 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_RESILVER_TXG,
704 			    vd->vdev_resilver_txg);
705 		if (vd->vdev_rebuild_txg != 0)
706 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_REBUILD_TXG,
707 			    vd->vdev_rebuild_txg);
708 		if (vd->vdev_faulted)
709 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_FAULTED, B_TRUE);
710 		if (vd->vdev_degraded)
711 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_DEGRADED, B_TRUE);
712 		if (vd->vdev_removed)
713 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_REMOVED, B_TRUE);
714 		if (vd->vdev_unspare)
715 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_UNSPARE, B_TRUE);
716 		if (vd->vdev_ishole)
717 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_IS_HOLE, B_TRUE);
718 
719 		/* Set the reason why we're FAULTED/DEGRADED. */
720 		switch (vd->vdev_stat.vs_aux) {
721 		case VDEV_AUX_ERR_EXCEEDED:
722 			aux = "err_exceeded";
723 			break;
724 
725 		case VDEV_AUX_EXTERNAL:
726 			aux = "external";
727 			break;
728 		}
729 
730 		if (aux != NULL && !vd->vdev_tmpoffline) {
731 			fnvlist_add_string(nv, ZPOOL_CONFIG_AUX_STATE, aux);
732 		} else {
733 			/*
734 			 * We're healthy - clear any previous AUX_STATE values.
735 			 */
736 			if (nvlist_exists(nv, ZPOOL_CONFIG_AUX_STATE))
737 				nvlist_remove_all(nv, ZPOOL_CONFIG_AUX_STATE);
738 		}
739 
740 		if (vd->vdev_splitting && vd->vdev_orig_guid != 0LL) {
741 			fnvlist_add_uint64(nv, ZPOOL_CONFIG_ORIG_GUID,
742 			    vd->vdev_orig_guid);
743 		}
744 	}
745 
746 	return (nv);
747 }
748 
749 /*
750  * Generate a view of the top-level vdevs.  If we currently have holes
751  * in the namespace, then generate an array which contains a list of holey
752  * vdevs.  Additionally, add the number of top-level children that currently
753  * exist.
754  */
755 void
vdev_top_config_generate(spa_t * spa,nvlist_t * config)756 vdev_top_config_generate(spa_t *spa, nvlist_t *config)
757 {
758 	vdev_t *rvd = spa->spa_root_vdev;
759 	uint64_t *array;
760 	uint_t c, idx;
761 
762 	array = kmem_alloc(rvd->vdev_children * sizeof (uint64_t), KM_SLEEP);
763 
764 	for (c = 0, idx = 0; c < rvd->vdev_children; c++) {
765 		vdev_t *tvd = rvd->vdev_child[c];
766 
767 		if (tvd->vdev_ishole) {
768 			array[idx++] = c;
769 		}
770 	}
771 
772 	if (idx) {
773 		VERIFY0(nvlist_add_uint64_array(config,
774 		    ZPOOL_CONFIG_HOLE_ARRAY, array, idx));
775 	}
776 
777 	VERIFY0(nvlist_add_uint64(config, ZPOOL_CONFIG_VDEV_CHILDREN,
778 	    rvd->vdev_children));
779 
780 	kmem_free(array, rvd->vdev_children * sizeof (uint64_t));
781 }
782 
783 /*
784  * Returns the configuration from the label of the given vdev. For vdevs
785  * which don't have a txg value stored on their label (i.e. spares/cache)
786  * or have not been completely initialized (txg = 0) just return
787  * the configuration from the first valid label we find. Otherwise,
788  * find the most up-to-date label that does not exceed the specified
789  * 'txg' value.
790  */
791 nvlist_t *
vdev_label_read_config(vdev_t * vd,uint64_t txg)792 vdev_label_read_config(vdev_t *vd, uint64_t txg)
793 {
794 	spa_t *spa = vd->vdev_spa;
795 	nvlist_t *config = NULL;
796 	vdev_phys_t *vp[VDEV_LABELS];
797 	abd_t *vp_abd[VDEV_LABELS];
798 	zio_t *zio[VDEV_LABELS];
799 	uint64_t best_txg = 0;
800 	uint64_t label_txg = 0;
801 	int error = 0;
802 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
803 	    ZIO_FLAG_SPECULATIVE;
804 
805 	ASSERT(vd->vdev_validate_thread == curthread ||
806 	    spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
807 
808 	if (!vdev_readable(vd))
809 		return (NULL);
810 
811 	/*
812 	 * The label for a dRAID distributed spare is not stored on disk.
813 	 * Instead it is generated when needed which allows us to bypass
814 	 * the pipeline when reading the config from the label.
815 	 */
816 	if (vd->vdev_ops == &vdev_draid_spare_ops)
817 		return (vdev_draid_read_config_spare(vd));
818 
819 	for (int l = 0; l < VDEV_LABELS; l++) {
820 		vp_abd[l] = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
821 		vp[l] = abd_to_buf(vp_abd[l]);
822 	}
823 
824 retry:
825 	for (int l = 0; l < VDEV_LABELS; l++) {
826 		zio[l] = zio_root(spa, NULL, NULL, flags);
827 
828 		vdev_label_read(zio[l], vd, l, vp_abd[l],
829 		    offsetof(vdev_label_t, vl_vdev_phys), sizeof (vdev_phys_t),
830 		    NULL, NULL, flags);
831 	}
832 	for (int l = 0; l < VDEV_LABELS; l++) {
833 		nvlist_t *label = NULL;
834 
835 		if (zio_wait(zio[l]) == 0 &&
836 		    nvlist_unpack(vp[l]->vp_nvlist, sizeof (vp[l]->vp_nvlist),
837 		    &label, 0) == 0) {
838 			/*
839 			 * Auxiliary vdevs won't have txg values in their
840 			 * labels and newly added vdevs may not have been
841 			 * completely initialized so just return the
842 			 * configuration from the first valid label we
843 			 * encounter.
844 			 */
845 			error = nvlist_lookup_uint64(label,
846 			    ZPOOL_CONFIG_POOL_TXG, &label_txg);
847 			if ((error || label_txg == 0) && !config) {
848 				config = label;
849 				for (l++; l < VDEV_LABELS; l++)
850 					zio_wait(zio[l]);
851 				break;
852 			} else if (label_txg <= txg && label_txg > best_txg) {
853 				best_txg = label_txg;
854 				nvlist_free(config);
855 				config = fnvlist_dup(label);
856 			}
857 		}
858 
859 		if (label != NULL) {
860 			nvlist_free(label);
861 			label = NULL;
862 		}
863 	}
864 
865 	if (config == NULL && !(flags & ZIO_FLAG_TRYHARD)) {
866 		flags |= ZIO_FLAG_TRYHARD;
867 		goto retry;
868 	}
869 
870 	/*
871 	 * We found a valid label but it didn't pass txg restrictions.
872 	 */
873 	if (config == NULL && label_txg != 0) {
874 		vdev_dbgmsg(vd, "label discarded as txg is too large "
875 		    "(%llu > %llu)", (u_longlong_t)label_txg,
876 		    (u_longlong_t)txg);
877 	}
878 
879 	for (int l = 0; l < VDEV_LABELS; l++) {
880 		abd_free(vp_abd[l]);
881 	}
882 
883 	return (config);
884 }
885 
886 /*
887  * Determine if a device is in use.  The 'spare_guid' parameter will be filled
888  * in with the device guid if this spare is active elsewhere on the system.
889  */
890 static boolean_t
vdev_inuse(vdev_t * vd,uint64_t crtxg,vdev_labeltype_t reason,uint64_t * spare_guid,uint64_t * l2cache_guid)891 vdev_inuse(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason,
892     uint64_t *spare_guid, uint64_t *l2cache_guid)
893 {
894 	spa_t *spa = vd->vdev_spa;
895 	uint64_t state, pool_guid, device_guid, txg, spare_pool;
896 	uint64_t vdtxg = 0;
897 	nvlist_t *label;
898 
899 	if (spare_guid)
900 		*spare_guid = 0ULL;
901 	if (l2cache_guid)
902 		*l2cache_guid = 0ULL;
903 
904 	/*
905 	 * Read the label, if any, and perform some basic sanity checks.
906 	 */
907 	if ((label = vdev_label_read_config(vd, -1ULL)) == NULL)
908 		return (B_FALSE);
909 
910 	(void) nvlist_lookup_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
911 	    &vdtxg);
912 
913 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
914 	    &state) != 0 ||
915 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
916 	    &device_guid) != 0) {
917 		nvlist_free(label);
918 		return (B_FALSE);
919 	}
920 
921 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
922 	    (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID,
923 	    &pool_guid) != 0 ||
924 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
925 	    &txg) != 0)) {
926 		nvlist_free(label);
927 		return (B_FALSE);
928 	}
929 
930 	nvlist_free(label);
931 
932 	/*
933 	 * Check to see if this device indeed belongs to the pool it claims to
934 	 * be a part of.  The only way this is allowed is if the device is a hot
935 	 * spare (which we check for later on).
936 	 */
937 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
938 	    !spa_guid_exists(pool_guid, device_guid) &&
939 	    !spa_spare_exists(device_guid, NULL, NULL) &&
940 	    !spa_l2cache_exists(device_guid, NULL))
941 		return (B_FALSE);
942 
943 	/*
944 	 * If the transaction group is zero, then this an initialized (but
945 	 * unused) label.  This is only an error if the create transaction
946 	 * on-disk is the same as the one we're using now, in which case the
947 	 * user has attempted to add the same vdev multiple times in the same
948 	 * transaction.
949 	 */
950 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
951 	    txg == 0 && vdtxg == crtxg)
952 		return (B_TRUE);
953 
954 	/*
955 	 * Check to see if this is a spare device.  We do an explicit check for
956 	 * spa_has_spare() here because it may be on our pending list of spares
957 	 * to add.
958 	 */
959 	if (spa_spare_exists(device_guid, &spare_pool, NULL) ||
960 	    spa_has_spare(spa, device_guid)) {
961 		if (spare_guid)
962 			*spare_guid = device_guid;
963 
964 		switch (reason) {
965 		case VDEV_LABEL_CREATE:
966 			return (B_TRUE);
967 
968 		case VDEV_LABEL_REPLACE:
969 			return (!spa_has_spare(spa, device_guid) ||
970 			    spare_pool != 0ULL);
971 
972 		case VDEV_LABEL_SPARE:
973 			return (spa_has_spare(spa, device_guid));
974 		default:
975 			break;
976 		}
977 	}
978 
979 	/*
980 	 * Check to see if this is an l2cache device.
981 	 */
982 	if (spa_l2cache_exists(device_guid, NULL) ||
983 	    spa_has_l2cache(spa, device_guid)) {
984 		if (l2cache_guid)
985 			*l2cache_guid = device_guid;
986 
987 		switch (reason) {
988 		case VDEV_LABEL_CREATE:
989 			return (B_TRUE);
990 
991 		case VDEV_LABEL_REPLACE:
992 			return (!spa_has_l2cache(spa, device_guid));
993 
994 		case VDEV_LABEL_L2CACHE:
995 			return (spa_has_l2cache(spa, device_guid));
996 		default:
997 			break;
998 		}
999 	}
1000 
1001 	/*
1002 	 * We can't rely on a pool's state if it's been imported
1003 	 * read-only.  Instead we look to see if the pools is marked
1004 	 * read-only in the namespace and set the state to active.
1005 	 */
1006 	if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
1007 	    (spa = spa_by_guid(pool_guid, device_guid)) != NULL &&
1008 	    spa_mode(spa) == SPA_MODE_READ)
1009 		state = POOL_STATE_ACTIVE;
1010 
1011 	/*
1012 	 * If the device is marked ACTIVE, then this device is in use by another
1013 	 * pool on the system.
1014 	 */
1015 	return (state == POOL_STATE_ACTIVE);
1016 }
1017 
1018 static nvlist_t *
vdev_aux_label_generate(vdev_t * vd,boolean_t reason_spare)1019 vdev_aux_label_generate(vdev_t *vd, boolean_t reason_spare)
1020 {
1021 	/*
1022 	 * For inactive hot spares and level 2 ARC devices, we generate
1023 	 * a special label that identifies as a mutually shared hot
1024 	 * spare or l2cache device. We write the label in case of
1025 	 * addition or removal of hot spare or l2cache vdev (in which
1026 	 * case we want to revert the labels).
1027 	 */
1028 	nvlist_t *label = fnvlist_alloc();
1029 	fnvlist_add_uint64(label, ZPOOL_CONFIG_VERSION,
1030 	    spa_version(vd->vdev_spa));
1031 	fnvlist_add_uint64(label, ZPOOL_CONFIG_POOL_STATE, reason_spare ?
1032 	    POOL_STATE_SPARE : POOL_STATE_L2CACHE);
1033 	fnvlist_add_uint64(label, ZPOOL_CONFIG_GUID, vd->vdev_guid);
1034 
1035 	/*
1036 	 * This is merely to facilitate reporting the ashift of the
1037 	 * cache device through zdb. The actual retrieval of the
1038 	 * ashift (in vdev_alloc()) uses the nvlist
1039 	 * spa->spa_l2cache->sav_config (populated in
1040 	 * spa_ld_open_aux_vdevs()).
1041 	 */
1042 	if (!reason_spare)
1043 		fnvlist_add_uint64(label, ZPOOL_CONFIG_ASHIFT, vd->vdev_ashift);
1044 
1045 	/*
1046 	 * Add path information to help find it during pool import
1047 	 */
1048 	if (vd->vdev_path != NULL)
1049 		fnvlist_add_string(label, ZPOOL_CONFIG_PATH, vd->vdev_path);
1050 	if (vd->vdev_devid != NULL)
1051 		fnvlist_add_string(label, ZPOOL_CONFIG_DEVID, vd->vdev_devid);
1052 	if (vd->vdev_physpath != NULL) {
1053 		fnvlist_add_string(label, ZPOOL_CONFIG_PHYS_PATH,
1054 		    vd->vdev_physpath);
1055 	}
1056 	return (label);
1057 }
1058 
1059 /*
1060  * Initialize a vdev label.  We check to make sure each leaf device is not in
1061  * use, and writable.  We put down an initial label which we will later
1062  * overwrite with a complete label.  Note that it's important to do this
1063  * sequentially, not in parallel, so that we catch cases of multiple use of the
1064  * same leaf vdev in the vdev we're creating -- e.g. mirroring a disk with
1065  * itself.
1066  */
1067 int
vdev_label_init(vdev_t * vd,uint64_t crtxg,vdev_labeltype_t reason)1068 vdev_label_init(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason)
1069 {
1070 	spa_t *spa = vd->vdev_spa;
1071 	nvlist_t *label;
1072 	vdev_phys_t *vp;
1073 	abd_t *vp_abd;
1074 	abd_t *bootenv;
1075 	uberblock_t *ub;
1076 	abd_t *ub_abd;
1077 	zio_t *zio;
1078 	char *buf;
1079 	size_t buflen;
1080 	int error;
1081 	uint64_t spare_guid = 0, l2cache_guid = 0;
1082 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL;
1083 	boolean_t reason_spare = (reason == VDEV_LABEL_SPARE || (reason ==
1084 	    VDEV_LABEL_REMOVE && vd->vdev_isspare));
1085 	boolean_t reason_l2cache = (reason == VDEV_LABEL_L2CACHE || (reason ==
1086 	    VDEV_LABEL_REMOVE && vd->vdev_isl2cache));
1087 
1088 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1089 
1090 	for (int c = 0; c < vd->vdev_children; c++)
1091 		if ((error = vdev_label_init(vd->vdev_child[c],
1092 		    crtxg, reason)) != 0)
1093 			return (error);
1094 
1095 	/* Track the creation time for this vdev */
1096 	vd->vdev_crtxg = crtxg;
1097 
1098 	if (!vd->vdev_ops->vdev_op_leaf || !spa_writeable(spa))
1099 		return (0);
1100 
1101 	/*
1102 	 * Dead vdevs cannot be initialized.
1103 	 */
1104 	if (vdev_is_dead(vd))
1105 		return (SET_ERROR(EIO));
1106 
1107 	/*
1108 	 * Determine if the vdev is in use.
1109 	 */
1110 	if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_SPLIT &&
1111 	    vdev_inuse(vd, crtxg, reason, &spare_guid, &l2cache_guid))
1112 		return (SET_ERROR(EBUSY));
1113 
1114 	/*
1115 	 * If this is a request to add or replace a spare or l2cache device
1116 	 * that is in use elsewhere on the system, then we must update the
1117 	 * guid (which was initialized to a random value) to reflect the
1118 	 * actual GUID (which is shared between multiple pools).
1119 	 */
1120 	if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_L2CACHE &&
1121 	    spare_guid != 0ULL) {
1122 		uint64_t guid_delta = spare_guid - vd->vdev_guid;
1123 
1124 		vd->vdev_guid += guid_delta;
1125 
1126 		for (vdev_t *pvd = vd; pvd != NULL; pvd = pvd->vdev_parent)
1127 			pvd->vdev_guid_sum += guid_delta;
1128 
1129 		/*
1130 		 * If this is a replacement, then we want to fallthrough to the
1131 		 * rest of the code.  If we're adding a spare, then it's already
1132 		 * labeled appropriately and we can just return.
1133 		 */
1134 		if (reason == VDEV_LABEL_SPARE)
1135 			return (0);
1136 		ASSERT(reason == VDEV_LABEL_REPLACE ||
1137 		    reason == VDEV_LABEL_SPLIT);
1138 	}
1139 
1140 	if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_SPARE &&
1141 	    l2cache_guid != 0ULL) {
1142 		uint64_t guid_delta = l2cache_guid - vd->vdev_guid;
1143 
1144 		vd->vdev_guid += guid_delta;
1145 
1146 		for (vdev_t *pvd = vd; pvd != NULL; pvd = pvd->vdev_parent)
1147 			pvd->vdev_guid_sum += guid_delta;
1148 
1149 		/*
1150 		 * If this is a replacement, then we want to fallthrough to the
1151 		 * rest of the code.  If we're adding an l2cache, then it's
1152 		 * already labeled appropriately and we can just return.
1153 		 */
1154 		if (reason == VDEV_LABEL_L2CACHE)
1155 			return (0);
1156 		ASSERT(reason == VDEV_LABEL_REPLACE);
1157 	}
1158 
1159 	/*
1160 	 * Initialize its label.
1161 	 */
1162 	vp_abd = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
1163 	abd_zero(vp_abd, sizeof (vdev_phys_t));
1164 	vp = abd_to_buf(vp_abd);
1165 
1166 	/*
1167 	 * Generate a label describing the pool and our top-level vdev.
1168 	 * We mark it as being from txg 0 to indicate that it's not
1169 	 * really part of an active pool just yet.  The labels will
1170 	 * be written again with a meaningful txg by spa_sync().
1171 	 */
1172 	if (reason_spare || reason_l2cache) {
1173 		label = vdev_aux_label_generate(vd, reason_spare);
1174 
1175 		/*
1176 		 * When spare or l2cache (aux) vdev is added during pool
1177 		 * creation, spa->spa_uberblock is not written until this
1178 		 * point. Write it on next config sync.
1179 		 */
1180 		if (uberblock_verify(&spa->spa_uberblock))
1181 			spa->spa_aux_sync_uber = B_TRUE;
1182 	} else {
1183 		uint64_t txg = 0ULL;
1184 
1185 		if (reason == VDEV_LABEL_SPLIT)
1186 			txg = spa->spa_uberblock.ub_txg;
1187 		label = spa_config_generate(spa, vd, txg, B_FALSE);
1188 
1189 		/*
1190 		 * Add our creation time.  This allows us to detect multiple
1191 		 * vdev uses as described above, and automatically expires if we
1192 		 * fail.
1193 		 */
1194 		VERIFY0(nvlist_add_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
1195 		    crtxg));
1196 	}
1197 
1198 	buf = vp->vp_nvlist;
1199 	buflen = sizeof (vp->vp_nvlist);
1200 
1201 	error = nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP);
1202 	if (error != 0) {
1203 		nvlist_free(label);
1204 		abd_free(vp_abd);
1205 		/* EFAULT means nvlist_pack ran out of room */
1206 		return (SET_ERROR(error == EFAULT ? ENAMETOOLONG : EINVAL));
1207 	}
1208 
1209 	/*
1210 	 * Initialize uberblock template.
1211 	 */
1212 	ub_abd = abd_alloc_linear(VDEV_UBERBLOCK_RING, B_TRUE);
1213 	abd_copy_from_buf(ub_abd, &spa->spa_uberblock, sizeof (uberblock_t));
1214 	abd_zero_off(ub_abd, sizeof (uberblock_t),
1215 	    VDEV_UBERBLOCK_RING - sizeof (uberblock_t));
1216 	ub = abd_to_buf(ub_abd);
1217 	ub->ub_txg = 0;
1218 
1219 	/* Initialize the 2nd padding area. */
1220 	bootenv = abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE);
1221 	abd_zero(bootenv, VDEV_PAD_SIZE);
1222 
1223 	/*
1224 	 * Write everything in parallel.
1225 	 */
1226 retry:
1227 	zio = zio_root(spa, NULL, NULL, flags);
1228 
1229 	for (int l = 0; l < VDEV_LABELS; l++) {
1230 
1231 		vdev_label_write(zio, vd, l, vp_abd,
1232 		    offsetof(vdev_label_t, vl_vdev_phys),
1233 		    sizeof (vdev_phys_t), NULL, NULL, flags);
1234 
1235 		/*
1236 		 * Skip the 1st padding area.
1237 		 * Zero out the 2nd padding area where it might have
1238 		 * left over data from previous filesystem format.
1239 		 */
1240 		vdev_label_write(zio, vd, l, bootenv,
1241 		    offsetof(vdev_label_t, vl_be),
1242 		    VDEV_PAD_SIZE, NULL, NULL, flags);
1243 
1244 		vdev_label_write(zio, vd, l, ub_abd,
1245 		    offsetof(vdev_label_t, vl_uberblock),
1246 		    VDEV_UBERBLOCK_RING, NULL, NULL, flags);
1247 	}
1248 
1249 	error = zio_wait(zio);
1250 
1251 	if (error != 0 && !(flags & ZIO_FLAG_TRYHARD)) {
1252 		flags |= ZIO_FLAG_TRYHARD;
1253 		goto retry;
1254 	}
1255 
1256 	nvlist_free(label);
1257 	abd_free(bootenv);
1258 	abd_free(ub_abd);
1259 	abd_free(vp_abd);
1260 
1261 	/*
1262 	 * If this vdev hasn't been previously identified as a spare, then we
1263 	 * mark it as such only if a) we are labeling it as a spare, or b) it
1264 	 * exists as a spare elsewhere in the system.  Do the same for
1265 	 * level 2 ARC devices.
1266 	 */
1267 	if (error == 0 && !vd->vdev_isspare &&
1268 	    (reason == VDEV_LABEL_SPARE ||
1269 	    spa_spare_exists(vd->vdev_guid, NULL, NULL)))
1270 		spa_spare_add(vd);
1271 
1272 	if (error == 0 && !vd->vdev_isl2cache &&
1273 	    (reason == VDEV_LABEL_L2CACHE ||
1274 	    spa_l2cache_exists(vd->vdev_guid, NULL)))
1275 		spa_l2cache_add(vd);
1276 
1277 	return (error);
1278 }
1279 
1280 /*
1281  * Done callback for vdev_label_read_bootenv_impl. If this is the first
1282  * callback to finish, store our abd in the callback pointer. Otherwise, we
1283  * just free our abd and return.
1284  */
1285 static void
vdev_label_read_bootenv_done(zio_t * zio)1286 vdev_label_read_bootenv_done(zio_t *zio)
1287 {
1288 	zio_t *rio = zio->io_private;
1289 	abd_t **cbp = rio->io_private;
1290 
1291 	ASSERT3U(zio->io_size, ==, VDEV_PAD_SIZE);
1292 
1293 	if (zio->io_error == 0) {
1294 		mutex_enter(&rio->io_lock);
1295 		if (*cbp == NULL) {
1296 			/* Will free this buffer in vdev_label_read_bootenv. */
1297 			*cbp = zio->io_abd;
1298 		} else {
1299 			abd_free(zio->io_abd);
1300 		}
1301 		mutex_exit(&rio->io_lock);
1302 	} else {
1303 		abd_free(zio->io_abd);
1304 	}
1305 }
1306 
1307 static void
vdev_label_read_bootenv_impl(zio_t * zio,vdev_t * vd,int flags)1308 vdev_label_read_bootenv_impl(zio_t *zio, vdev_t *vd, int flags)
1309 {
1310 	for (int c = 0; c < vd->vdev_children; c++)
1311 		vdev_label_read_bootenv_impl(zio, vd->vdev_child[c], flags);
1312 
1313 	/*
1314 	 * We just use the first label that has a correct checksum; the
1315 	 * bootloader should have rewritten them all to be the same on boot,
1316 	 * and any changes we made since boot have been the same across all
1317 	 * labels.
1318 	 */
1319 	if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd)) {
1320 		for (int l = 0; l < VDEV_LABELS; l++) {
1321 			vdev_label_read(zio, vd, l,
1322 			    abd_alloc_linear(VDEV_PAD_SIZE, B_FALSE),
1323 			    offsetof(vdev_label_t, vl_be), VDEV_PAD_SIZE,
1324 			    vdev_label_read_bootenv_done, zio, flags);
1325 		}
1326 	}
1327 }
1328 
1329 int
vdev_label_read_bootenv(vdev_t * rvd,nvlist_t * bootenv)1330 vdev_label_read_bootenv(vdev_t *rvd, nvlist_t *bootenv)
1331 {
1332 	nvlist_t *config;
1333 	spa_t *spa = rvd->vdev_spa;
1334 	abd_t *abd = NULL;
1335 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
1336 	    ZIO_FLAG_SPECULATIVE | ZIO_FLAG_TRYHARD;
1337 
1338 	ASSERT(bootenv);
1339 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1340 
1341 	zio_t *zio = zio_root(spa, NULL, &abd, flags);
1342 	vdev_label_read_bootenv_impl(zio, rvd, flags);
1343 	int err = zio_wait(zio);
1344 
1345 	if (abd != NULL) {
1346 		char *buf;
1347 		vdev_boot_envblock_t *vbe = abd_to_buf(abd);
1348 
1349 		vbe->vbe_version = ntohll(vbe->vbe_version);
1350 		switch (vbe->vbe_version) {
1351 		case VB_RAW:
1352 			/*
1353 			 * if we have textual data in vbe_bootenv, create nvlist
1354 			 * with key "envmap".
1355 			 */
1356 			fnvlist_add_uint64(bootenv, BOOTENV_VERSION, VB_RAW);
1357 			vbe->vbe_bootenv[sizeof (vbe->vbe_bootenv) - 1] = '\0';
1358 			fnvlist_add_string(bootenv, GRUB_ENVMAP,
1359 			    vbe->vbe_bootenv);
1360 			break;
1361 
1362 		case VB_NVLIST:
1363 			err = nvlist_unpack(vbe->vbe_bootenv,
1364 			    sizeof (vbe->vbe_bootenv), &config, 0);
1365 			if (err == 0) {
1366 				fnvlist_merge(bootenv, config);
1367 				nvlist_free(config);
1368 				break;
1369 			}
1370 			zfs_fallthrough;
1371 		default:
1372 			/* Check for FreeBSD zfs bootonce command string */
1373 			buf = abd_to_buf(abd);
1374 			if (*buf == '\0') {
1375 				fnvlist_add_uint64(bootenv, BOOTENV_VERSION,
1376 				    VB_NVLIST);
1377 				break;
1378 			}
1379 			fnvlist_add_string(bootenv, FREEBSD_BOOTONCE, buf);
1380 		}
1381 
1382 		/*
1383 		 * abd was allocated in vdev_label_read_bootenv_impl()
1384 		 */
1385 		abd_free(abd);
1386 		/*
1387 		 * If we managed to read any successfully,
1388 		 * return success.
1389 		 */
1390 		return (0);
1391 	}
1392 	return (err);
1393 }
1394 
1395 int
vdev_label_write_bootenv(vdev_t * vd,nvlist_t * env)1396 vdev_label_write_bootenv(vdev_t *vd, nvlist_t *env)
1397 {
1398 	zio_t *zio;
1399 	spa_t *spa = vd->vdev_spa;
1400 	vdev_boot_envblock_t *bootenv;
1401 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL;
1402 	int error;
1403 	size_t nvsize;
1404 	char *nvbuf;
1405 	const char *tmp;
1406 
1407 	error = nvlist_size(env, &nvsize, NV_ENCODE_XDR);
1408 	if (error != 0)
1409 		return (SET_ERROR(error));
1410 
1411 	if (nvsize >= sizeof (bootenv->vbe_bootenv)) {
1412 		return (SET_ERROR(E2BIG));
1413 	}
1414 
1415 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1416 
1417 	error = ENXIO;
1418 	for (int c = 0; c < vd->vdev_children; c++) {
1419 		int child_err;
1420 
1421 		child_err = vdev_label_write_bootenv(vd->vdev_child[c], env);
1422 		/*
1423 		 * As long as any of the disks managed to write all of their
1424 		 * labels successfully, return success.
1425 		 */
1426 		if (child_err == 0)
1427 			error = child_err;
1428 	}
1429 
1430 	if (!vd->vdev_ops->vdev_op_leaf || vdev_is_dead(vd) ||
1431 	    !vdev_writeable(vd)) {
1432 		return (error);
1433 	}
1434 	ASSERT3U(sizeof (*bootenv), ==, VDEV_PAD_SIZE);
1435 	abd_t *abd = abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE);
1436 	abd_zero(abd, VDEV_PAD_SIZE);
1437 
1438 	bootenv = abd_borrow_buf_copy(abd, VDEV_PAD_SIZE);
1439 	nvbuf = bootenv->vbe_bootenv;
1440 	nvsize = sizeof (bootenv->vbe_bootenv);
1441 
1442 	bootenv->vbe_version = fnvlist_lookup_uint64(env, BOOTENV_VERSION);
1443 	switch (bootenv->vbe_version) {
1444 	case VB_RAW:
1445 		if (nvlist_lookup_string(env, GRUB_ENVMAP, &tmp) == 0) {
1446 			(void) strlcpy(bootenv->vbe_bootenv, tmp, nvsize);
1447 		}
1448 		error = 0;
1449 		break;
1450 
1451 	case VB_NVLIST:
1452 		error = nvlist_pack(env, &nvbuf, &nvsize, NV_ENCODE_XDR,
1453 		    KM_SLEEP);
1454 		break;
1455 
1456 	default:
1457 		error = EINVAL;
1458 		break;
1459 	}
1460 
1461 	if (error == 0) {
1462 		bootenv->vbe_version = htonll(bootenv->vbe_version);
1463 		abd_return_buf_copy(abd, bootenv, VDEV_PAD_SIZE);
1464 	} else {
1465 		abd_free(abd);
1466 		return (SET_ERROR(error));
1467 	}
1468 
1469 retry:
1470 	zio = zio_root(spa, NULL, NULL, flags);
1471 	for (int l = 0; l < VDEV_LABELS; l++) {
1472 		vdev_label_write(zio, vd, l, abd,
1473 		    offsetof(vdev_label_t, vl_be),
1474 		    VDEV_PAD_SIZE, NULL, NULL, flags);
1475 	}
1476 
1477 	error = zio_wait(zio);
1478 	if (error != 0 && !(flags & ZIO_FLAG_TRYHARD)) {
1479 		flags |= ZIO_FLAG_TRYHARD;
1480 		goto retry;
1481 	}
1482 
1483 	abd_free(abd);
1484 	return (error);
1485 }
1486 
1487 /*
1488  * ==========================================================================
1489  * uberblock load/sync
1490  * ==========================================================================
1491  */
1492 
1493 /*
1494  * Consider the following situation: txg is safely synced to disk.  We've
1495  * written the first uberblock for txg + 1, and then we lose power.  When we
1496  * come back up, we fail to see the uberblock for txg + 1 because, say,
1497  * it was on a mirrored device and the replica to which we wrote txg + 1
1498  * is now offline.  If we then make some changes and sync txg + 1, and then
1499  * the missing replica comes back, then for a few seconds we'll have two
1500  * conflicting uberblocks on disk with the same txg.  The solution is simple:
1501  * among uberblocks with equal txg, choose the one with the latest timestamp.
1502  */
1503 static int
vdev_uberblock_compare(const uberblock_t * ub1,const uberblock_t * ub2)1504 vdev_uberblock_compare(const uberblock_t *ub1, const uberblock_t *ub2)
1505 {
1506 	int cmp = TREE_CMP(ub1->ub_txg, ub2->ub_txg);
1507 
1508 	if (likely(cmp))
1509 		return (cmp);
1510 
1511 	cmp = TREE_CMP(ub1->ub_timestamp, ub2->ub_timestamp);
1512 	if (likely(cmp))
1513 		return (cmp);
1514 
1515 	/*
1516 	 * If MMP_VALID(ub) && MMP_SEQ_VALID(ub) then the host has an MMP-aware
1517 	 * ZFS, e.g. OpenZFS >= 0.7.
1518 	 *
1519 	 * If one ub has MMP and the other does not, they were written by
1520 	 * different hosts, which matters for MMP.  So we treat no MMP/no SEQ as
1521 	 * a 0 value.
1522 	 *
1523 	 * Since timestamp and txg are the same if we get this far, either is
1524 	 * acceptable for importing the pool.
1525 	 */
1526 	unsigned int seq1 = 0;
1527 	unsigned int seq2 = 0;
1528 
1529 	if (MMP_VALID(ub1) && MMP_SEQ_VALID(ub1))
1530 		seq1 = MMP_SEQ(ub1);
1531 
1532 	if (MMP_VALID(ub2) && MMP_SEQ_VALID(ub2))
1533 		seq2 = MMP_SEQ(ub2);
1534 
1535 	return (TREE_CMP(seq1, seq2));
1536 }
1537 
1538 struct ubl_cbdata {
1539 	uberblock_t	ubl_latest;	/* Most recent uberblock */
1540 	uberblock_t	*ubl_ubbest;	/* Best uberblock (w/r/t max_txg) */
1541 	vdev_t		*ubl_vd;	/* vdev associated with the above */
1542 };
1543 
1544 static void
vdev_uberblock_load_done(zio_t * zio)1545 vdev_uberblock_load_done(zio_t *zio)
1546 {
1547 	vdev_t *vd = zio->io_vd;
1548 	spa_t *spa = zio->io_spa;
1549 	zio_t *rio = zio->io_private;
1550 	uberblock_t *ub = abd_to_buf(zio->io_abd);
1551 	struct ubl_cbdata *cbp = rio->io_private;
1552 
1553 	ASSERT3U(zio->io_size, ==, VDEV_UBERBLOCK_SIZE(vd));
1554 
1555 	if (zio->io_error == 0 && uberblock_verify(ub) == 0) {
1556 		mutex_enter(&rio->io_lock);
1557 		if (vdev_uberblock_compare(ub, &cbp->ubl_latest) > 0) {
1558 			cbp->ubl_latest = *ub;
1559 		}
1560 		if (ub->ub_txg <= spa->spa_load_max_txg &&
1561 		    vdev_uberblock_compare(ub, cbp->ubl_ubbest) > 0) {
1562 			/*
1563 			 * Keep track of the vdev in which this uberblock
1564 			 * was found. We will use this information later
1565 			 * to obtain the config nvlist associated with
1566 			 * this uberblock.
1567 			 */
1568 			*cbp->ubl_ubbest = *ub;
1569 			cbp->ubl_vd = vd;
1570 		}
1571 		mutex_exit(&rio->io_lock);
1572 	}
1573 
1574 	abd_free(zio->io_abd);
1575 }
1576 
1577 static void
vdev_uberblock_load_impl(zio_t * zio,vdev_t * vd,int flags,struct ubl_cbdata * cbp)1578 vdev_uberblock_load_impl(zio_t *zio, vdev_t *vd, int flags,
1579     struct ubl_cbdata *cbp)
1580 {
1581 	for (int c = 0; c < vd->vdev_children; c++)
1582 		vdev_uberblock_load_impl(zio, vd->vdev_child[c], flags, cbp);
1583 
1584 	if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd) &&
1585 	    vd->vdev_ops != &vdev_draid_spare_ops) {
1586 		for (int l = 0; l < VDEV_LABELS; l++) {
1587 			for (int n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
1588 				vdev_label_read(zio, vd, l,
1589 				    abd_alloc_linear(VDEV_UBERBLOCK_SIZE(vd),
1590 				    B_TRUE), VDEV_UBERBLOCK_OFFSET(vd, n),
1591 				    VDEV_UBERBLOCK_SIZE(vd),
1592 				    vdev_uberblock_load_done, zio, flags);
1593 			}
1594 		}
1595 	}
1596 }
1597 
1598 /*
1599  * Reads the 'best' uberblock from disk along with its associated
1600  * configuration. First, we read the uberblock array of each label of each
1601  * vdev, keeping track of the uberblock with the highest txg in each array.
1602  * Then, we read the configuration from the same vdev as the best uberblock.
1603  */
1604 void
vdev_uberblock_load(vdev_t * rvd,uberblock_t * ub,nvlist_t ** config)1605 vdev_uberblock_load(vdev_t *rvd, uberblock_t *ub, nvlist_t **config)
1606 {
1607 	zio_t *zio;
1608 	spa_t *spa = rvd->vdev_spa;
1609 	struct ubl_cbdata cb;
1610 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
1611 	    ZIO_FLAG_SPECULATIVE | ZIO_FLAG_TRYHARD;
1612 
1613 	ASSERT(ub);
1614 	ASSERT(config);
1615 
1616 	memset(ub, 0, sizeof (uberblock_t));
1617 	memset(&cb, 0, sizeof (cb));
1618 	*config = NULL;
1619 
1620 	cb.ubl_ubbest = ub;
1621 
1622 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1623 	zio = zio_root(spa, NULL, &cb, flags);
1624 	vdev_uberblock_load_impl(zio, rvd, flags, &cb);
1625 	(void) zio_wait(zio);
1626 
1627 	/*
1628 	 * It's possible that the best uberblock was discovered on a label
1629 	 * that has a configuration which was written in a future txg.
1630 	 * Search all labels on this vdev to find the configuration that
1631 	 * matches the txg for our uberblock.
1632 	 */
1633 	if (cb.ubl_vd != NULL) {
1634 		vdev_dbgmsg(cb.ubl_vd, "best uberblock found for spa %s. "
1635 		    "txg %llu", spa->spa_name, (u_longlong_t)ub->ub_txg);
1636 
1637 		if (ub->ub_raidz_reflow_info !=
1638 		    cb.ubl_latest.ub_raidz_reflow_info) {
1639 			vdev_dbgmsg(cb.ubl_vd,
1640 			    "spa=%s best uberblock (txg=%llu info=0x%llx) "
1641 			    "has different raidz_reflow_info than latest "
1642 			    "uberblock (txg=%llu info=0x%llx)",
1643 			    spa->spa_name,
1644 			    (u_longlong_t)ub->ub_txg,
1645 			    (u_longlong_t)ub->ub_raidz_reflow_info,
1646 			    (u_longlong_t)cb.ubl_latest.ub_txg,
1647 			    (u_longlong_t)cb.ubl_latest.ub_raidz_reflow_info);
1648 			memset(ub, 0, sizeof (uberblock_t));
1649 			spa_config_exit(spa, SCL_ALL, FTAG);
1650 			return;
1651 		}
1652 
1653 		*config = vdev_label_read_config(cb.ubl_vd, ub->ub_txg);
1654 		if (*config == NULL && spa->spa_extreme_rewind) {
1655 			vdev_dbgmsg(cb.ubl_vd, "failed to read label config. "
1656 			    "Trying again without txg restrictions.");
1657 			*config = vdev_label_read_config(cb.ubl_vd, UINT64_MAX);
1658 		}
1659 		if (*config == NULL) {
1660 			vdev_dbgmsg(cb.ubl_vd, "failed to read label config");
1661 		}
1662 	}
1663 	spa_config_exit(spa, SCL_ALL, FTAG);
1664 }
1665 
1666 /*
1667  * For use when a leaf vdev is expanded.
1668  * The location of labels 2 and 3 changed, and at the new location the
1669  * uberblock rings are either empty or contain garbage.  The sync will write
1670  * new configs there because the vdev is dirty, but expansion also needs the
1671  * uberblock rings copied.  Read them from label 0 which did not move.
1672  *
1673  * Since the point is to populate labels {2,3} with valid uberblocks,
1674  * we zero uberblocks we fail to read or which are not valid.
1675  */
1676 
1677 static void
vdev_copy_uberblocks(vdev_t * vd)1678 vdev_copy_uberblocks(vdev_t *vd)
1679 {
1680 	abd_t *ub_abd;
1681 	zio_t *write_zio;
1682 	int locks = (SCL_L2ARC | SCL_ZIO);
1683 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
1684 	    ZIO_FLAG_SPECULATIVE;
1685 
1686 	ASSERT(spa_config_held(vd->vdev_spa, SCL_STATE, RW_READER) ==
1687 	    SCL_STATE);
1688 	ASSERT(vd->vdev_ops->vdev_op_leaf);
1689 
1690 	/*
1691 	 * No uberblocks are stored on distributed spares, they may be
1692 	 * safely skipped when expanding a leaf vdev.
1693 	 */
1694 	if (vd->vdev_ops == &vdev_draid_spare_ops)
1695 		return;
1696 
1697 	spa_config_enter(vd->vdev_spa, locks, FTAG, RW_READER);
1698 
1699 	ub_abd = abd_alloc_linear(VDEV_UBERBLOCK_SIZE(vd), B_TRUE);
1700 
1701 	write_zio = zio_root(vd->vdev_spa, NULL, NULL, flags);
1702 	for (int n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
1703 		const int src_label = 0;
1704 		zio_t *zio;
1705 
1706 		zio = zio_root(vd->vdev_spa, NULL, NULL, flags);
1707 		vdev_label_read(zio, vd, src_label, ub_abd,
1708 		    VDEV_UBERBLOCK_OFFSET(vd, n), VDEV_UBERBLOCK_SIZE(vd),
1709 		    NULL, NULL, flags);
1710 
1711 		if (zio_wait(zio) || uberblock_verify(abd_to_buf(ub_abd)))
1712 			abd_zero(ub_abd, VDEV_UBERBLOCK_SIZE(vd));
1713 
1714 		for (int l = 2; l < VDEV_LABELS; l++)
1715 			vdev_label_write(write_zio, vd, l, ub_abd,
1716 			    VDEV_UBERBLOCK_OFFSET(vd, n),
1717 			    VDEV_UBERBLOCK_SIZE(vd), NULL, NULL,
1718 			    flags | ZIO_FLAG_DONT_PROPAGATE);
1719 	}
1720 	(void) zio_wait(write_zio);
1721 
1722 	spa_config_exit(vd->vdev_spa, locks, FTAG);
1723 
1724 	abd_free(ub_abd);
1725 }
1726 
1727 /*
1728  * On success, increment root zio's count of good writes.
1729  * We only get credit for writes to known-visible vdevs; see spa_vdev_add().
1730  */
1731 static void
vdev_uberblock_sync_done(zio_t * zio)1732 vdev_uberblock_sync_done(zio_t *zio)
1733 {
1734 	uint64_t *good_writes = zio->io_private;
1735 
1736 	if (zio->io_error == 0 && zio->io_vd->vdev_top->vdev_ms_array != 0)
1737 		atomic_inc_64(good_writes);
1738 }
1739 
1740 /*
1741  * Write the uberblock to all labels of all leaves of the specified vdev.
1742  */
1743 static void
vdev_uberblock_sync(zio_t * zio,uint64_t * good_writes,uberblock_t * ub,vdev_t * vd,int flags)1744 vdev_uberblock_sync(zio_t *zio, uint64_t *good_writes,
1745     uberblock_t *ub, vdev_t *vd, int flags)
1746 {
1747 	for (uint64_t c = 0; c < vd->vdev_children; c++) {
1748 		vdev_uberblock_sync(zio, good_writes,
1749 		    ub, vd->vdev_child[c], flags);
1750 	}
1751 
1752 	if (!vd->vdev_ops->vdev_op_leaf)
1753 		return;
1754 
1755 	if (!vdev_writeable(vd))
1756 		return;
1757 
1758 	/*
1759 	 * There's no need to write uberblocks to a distributed spare, they
1760 	 * are already stored on all the leaves of the parent dRAID.  For
1761 	 * this same reason vdev_uberblock_load_impl() skips distributed
1762 	 * spares when reading uberblocks.
1763 	 */
1764 	if (vd->vdev_ops == &vdev_draid_spare_ops)
1765 		return;
1766 
1767 	/* If the vdev was expanded, need to copy uberblock rings. */
1768 	if (vd->vdev_state == VDEV_STATE_HEALTHY &&
1769 	    vd->vdev_copy_uberblocks == B_TRUE) {
1770 		vdev_copy_uberblocks(vd);
1771 		vd->vdev_copy_uberblocks = B_FALSE;
1772 	}
1773 
1774 	/*
1775 	 * We chose a slot based on the txg.  If this uberblock has a special
1776 	 * RAIDZ expansion state, then it is essentially an update of the
1777 	 * current uberblock (it has the same txg).  However, the current
1778 	 * state is committed, so we want to write it to a different slot. If
1779 	 * we overwrote the same slot, and we lose power during the uberblock
1780 	 * write, and the disk does not do single-sector overwrites
1781 	 * atomically (even though it is required to - i.e. we should see
1782 	 * either the old or the new uberblock), then we could lose this
1783 	 * txg's uberblock. Rewinding to the previous txg's uberblock may not
1784 	 * be possible because RAIDZ expansion may have already overwritten
1785 	 * some of the data, so we need the progress indicator in the
1786 	 * uberblock.
1787 	 */
1788 	int m = spa_multihost(vd->vdev_spa) ? MMP_BLOCKS_PER_LABEL : 0;
1789 	int n = (ub->ub_txg - (RRSS_GET_STATE(ub) == RRSS_SCRATCH_VALID)) %
1790 	    (VDEV_UBERBLOCK_COUNT(vd) - m);
1791 
1792 	/* Copy the uberblock_t into the ABD */
1793 	abd_t *ub_abd = abd_alloc_for_io(VDEV_UBERBLOCK_SIZE(vd), B_TRUE);
1794 	abd_copy_from_buf(ub_abd, ub, sizeof (uberblock_t));
1795 	abd_zero_off(ub_abd, sizeof (uberblock_t),
1796 	    VDEV_UBERBLOCK_SIZE(vd) - sizeof (uberblock_t));
1797 
1798 	for (int l = 0; l < VDEV_LABELS; l++)
1799 		vdev_label_write(zio, vd, l, ub_abd,
1800 		    VDEV_UBERBLOCK_OFFSET(vd, n), VDEV_UBERBLOCK_SIZE(vd),
1801 		    vdev_uberblock_sync_done, good_writes,
1802 		    flags | ZIO_FLAG_DONT_PROPAGATE);
1803 
1804 	abd_free(ub_abd);
1805 }
1806 
1807 /* Sync the uberblocks to all vdevs in svd[] */
1808 int
vdev_uberblock_sync_list(vdev_t ** svd,int svdcount,uberblock_t * ub,int flags)1809 vdev_uberblock_sync_list(vdev_t **svd, int svdcount, uberblock_t *ub, int flags)
1810 {
1811 	spa_t *spa = svd[0]->vdev_spa;
1812 	zio_t *zio;
1813 	uint64_t good_writes = 0;
1814 
1815 	zio = zio_root(spa, NULL, NULL, flags);
1816 
1817 	for (int v = 0; v < svdcount; v++)
1818 		vdev_uberblock_sync(zio, &good_writes, ub, svd[v], flags);
1819 
1820 	if (spa->spa_aux_sync_uber) {
1821 		for (int v = 0; v < spa->spa_spares.sav_count; v++) {
1822 			vdev_uberblock_sync(zio, &good_writes, ub,
1823 			    spa->spa_spares.sav_vdevs[v], flags);
1824 		}
1825 		for (int v = 0; v < spa->spa_l2cache.sav_count; v++) {
1826 			vdev_uberblock_sync(zio, &good_writes, ub,
1827 			    spa->spa_l2cache.sav_vdevs[v], flags);
1828 		}
1829 	}
1830 	(void) zio_wait(zio);
1831 
1832 	/*
1833 	 * Flush the uberblocks to disk.  This ensures that the odd labels
1834 	 * are no longer needed (because the new uberblocks and the even
1835 	 * labels are safely on disk), so it is safe to overwrite them.
1836 	 */
1837 	zio = zio_root(spa, NULL, NULL, flags);
1838 
1839 	for (int v = 0; v < svdcount; v++) {
1840 		if (vdev_writeable(svd[v])) {
1841 			zio_flush(zio, svd[v]);
1842 		}
1843 	}
1844 	if (spa->spa_aux_sync_uber) {
1845 		spa->spa_aux_sync_uber = B_FALSE;
1846 		for (int v = 0; v < spa->spa_spares.sav_count; v++) {
1847 			if (vdev_writeable(spa->spa_spares.sav_vdevs[v])) {
1848 				zio_flush(zio, spa->spa_spares.sav_vdevs[v]);
1849 			}
1850 		}
1851 		for (int v = 0; v < spa->spa_l2cache.sav_count; v++) {
1852 			if (vdev_writeable(spa->spa_l2cache.sav_vdevs[v])) {
1853 				zio_flush(zio, spa->spa_l2cache.sav_vdevs[v]);
1854 			}
1855 		}
1856 	}
1857 
1858 	(void) zio_wait(zio);
1859 
1860 	return (good_writes >= 1 ? 0 : EIO);
1861 }
1862 
1863 /*
1864  * On success, increment the count of good writes for our top-level vdev.
1865  */
1866 static void
vdev_label_sync_done(zio_t * zio)1867 vdev_label_sync_done(zio_t *zio)
1868 {
1869 	uint64_t *good_writes = zio->io_private;
1870 
1871 	if (zio->io_error == 0)
1872 		atomic_inc_64(good_writes);
1873 }
1874 
1875 /*
1876  * If there weren't enough good writes, indicate failure to the parent.
1877  */
1878 static void
vdev_label_sync_top_done(zio_t * zio)1879 vdev_label_sync_top_done(zio_t *zio)
1880 {
1881 	uint64_t *good_writes = zio->io_private;
1882 
1883 	if (*good_writes == 0)
1884 		zio->io_error = SET_ERROR(EIO);
1885 
1886 	kmem_free(good_writes, sizeof (uint64_t));
1887 }
1888 
1889 /*
1890  * We ignore errors for log and cache devices, simply free the private data.
1891  */
1892 static void
vdev_label_sync_ignore_done(zio_t * zio)1893 vdev_label_sync_ignore_done(zio_t *zio)
1894 {
1895 	kmem_free(zio->io_private, sizeof (uint64_t));
1896 }
1897 
1898 /*
1899  * Write all even or odd labels to all leaves of the specified vdev.
1900  */
1901 static void
vdev_label_sync(zio_t * zio,uint64_t * good_writes,vdev_t * vd,int l,uint64_t txg,int flags)1902 vdev_label_sync(zio_t *zio, uint64_t *good_writes,
1903     vdev_t *vd, int l, uint64_t txg, int flags)
1904 {
1905 	nvlist_t *label;
1906 	vdev_phys_t *vp;
1907 	abd_t *vp_abd;
1908 	char *buf;
1909 	size_t buflen;
1910 	vdev_t *pvd = vd->vdev_parent;
1911 	boolean_t spare_in_use = B_FALSE;
1912 
1913 	for (int c = 0; c < vd->vdev_children; c++) {
1914 		vdev_label_sync(zio, good_writes,
1915 		    vd->vdev_child[c], l, txg, flags);
1916 	}
1917 
1918 	if (!vd->vdev_ops->vdev_op_leaf)
1919 		return;
1920 
1921 	if (!vdev_writeable(vd))
1922 		return;
1923 
1924 	/*
1925 	 * The top-level config never needs to be written to a distributed
1926 	 * spare.  When read vdev_dspare_label_read_config() will generate
1927 	 * the config for the vdev_label_read_config().
1928 	 */
1929 	if (vd->vdev_ops == &vdev_draid_spare_ops)
1930 		return;
1931 
1932 	if (pvd && pvd->vdev_ops == &vdev_spare_ops)
1933 		spare_in_use = B_TRUE;
1934 
1935 	/*
1936 	 * Generate a label describing the top-level config to which we belong.
1937 	 */
1938 	if ((vd->vdev_isspare && !spare_in_use) || vd->vdev_isl2cache) {
1939 		label = vdev_aux_label_generate(vd, vd->vdev_isspare);
1940 	} else {
1941 		label = spa_config_generate(vd->vdev_spa, vd, txg, B_FALSE);
1942 	}
1943 
1944 	vp_abd = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
1945 	abd_zero(vp_abd, sizeof (vdev_phys_t));
1946 	vp = abd_to_buf(vp_abd);
1947 
1948 	buf = vp->vp_nvlist;
1949 	buflen = sizeof (vp->vp_nvlist);
1950 
1951 	if (!nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP)) {
1952 		for (; l < VDEV_LABELS; l += 2) {
1953 			vdev_label_write(zio, vd, l, vp_abd,
1954 			    offsetof(vdev_label_t, vl_vdev_phys),
1955 			    sizeof (vdev_phys_t),
1956 			    vdev_label_sync_done, good_writes,
1957 			    flags | ZIO_FLAG_DONT_PROPAGATE);
1958 		}
1959 	}
1960 
1961 	abd_free(vp_abd);
1962 	nvlist_free(label);
1963 }
1964 
1965 static int
vdev_label_sync_list(spa_t * spa,int l,uint64_t txg,int flags)1966 vdev_label_sync_list(spa_t *spa, int l, uint64_t txg, int flags)
1967 {
1968 	list_t *dl = &spa->spa_config_dirty_list;
1969 	vdev_t *vd;
1970 	zio_t *zio;
1971 	int error;
1972 
1973 	/*
1974 	 * Write the new labels to disk.
1975 	 */
1976 	zio = zio_root(spa, NULL, NULL, flags);
1977 
1978 	for (vd = list_head(dl); vd != NULL; vd = list_next(dl, vd)) {
1979 		uint64_t *good_writes;
1980 
1981 		ASSERT(!vd->vdev_ishole);
1982 
1983 		good_writes = kmem_zalloc(sizeof (uint64_t), KM_SLEEP);
1984 		zio_t *vio = zio_null(zio, spa, NULL,
1985 		    (vd->vdev_islog || vd->vdev_aux != NULL) ?
1986 		    vdev_label_sync_ignore_done : vdev_label_sync_top_done,
1987 		    good_writes, flags);
1988 		vdev_label_sync(vio, good_writes, vd, l, txg, flags);
1989 		zio_nowait(vio);
1990 	}
1991 
1992 	/*
1993 	 * AUX path may have changed during import
1994 	 */
1995 	spa_aux_vdev_t *sav[2] = {&spa->spa_spares, &spa->spa_l2cache};
1996 	for (int i = 0; i < 2; i++) {
1997 		for (int v = 0; v < sav[i]->sav_count; v++) {
1998 			uint64_t *good_writes;
1999 			if (!sav[i]->sav_label_sync)
2000 				continue;
2001 			good_writes = kmem_zalloc(sizeof (uint64_t), KM_SLEEP);
2002 			zio_t *vio = zio_null(zio, spa, NULL,
2003 			    vdev_label_sync_ignore_done, good_writes, flags);
2004 			vdev_label_sync(vio, good_writes, sav[i]->sav_vdevs[v],
2005 			    l, txg, flags);
2006 			zio_nowait(vio);
2007 		}
2008 	}
2009 
2010 	error = zio_wait(zio);
2011 
2012 	/*
2013 	 * Flush the new labels to disk.
2014 	 */
2015 	zio = zio_root(spa, NULL, NULL, flags);
2016 
2017 	for (vd = list_head(dl); vd != NULL; vd = list_next(dl, vd))
2018 		zio_flush(zio, vd);
2019 
2020 	for (int i = 0; i < 2; i++) {
2021 		if (!sav[i]->sav_label_sync)
2022 			continue;
2023 		for (int v = 0; v < sav[i]->sav_count; v++)
2024 			zio_flush(zio, sav[i]->sav_vdevs[v]);
2025 		if (l == 1)
2026 			sav[i]->sav_label_sync = B_FALSE;
2027 	}
2028 
2029 	(void) zio_wait(zio);
2030 
2031 	return (error);
2032 }
2033 
2034 /*
2035  * Sync the uberblock and any changes to the vdev configuration.
2036  *
2037  * The order of operations is carefully crafted to ensure that
2038  * if the system panics or loses power at any time, the state on disk
2039  * is still transactionally consistent.  The in-line comments below
2040  * describe the failure semantics at each stage.
2041  *
2042  * Moreover, vdev_config_sync() is designed to be idempotent: if it fails
2043  * at any time, you can just call it again, and it will resume its work.
2044  */
2045 int
vdev_config_sync(vdev_t ** svd,int svdcount,uint64_t txg)2046 vdev_config_sync(vdev_t **svd, int svdcount, uint64_t txg)
2047 {
2048 	spa_t *spa = svd[0]->vdev_spa;
2049 	uberblock_t *ub = &spa->spa_uberblock;
2050 	int error = 0;
2051 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL;
2052 
2053 	ASSERT(svdcount != 0);
2054 retry:
2055 	/*
2056 	 * Normally, we don't want to try too hard to write every label and
2057 	 * uberblock.  If there is a flaky disk, we don't want the rest of the
2058 	 * sync process to block while we retry.  But if we can't write a
2059 	 * single label out, we should retry with ZIO_FLAG_TRYHARD before
2060 	 * bailing out and declaring the pool faulted.
2061 	 */
2062 	if (error != 0) {
2063 		if ((flags & ZIO_FLAG_TRYHARD) != 0)
2064 			return (error);
2065 		flags |= ZIO_FLAG_TRYHARD;
2066 	}
2067 
2068 	ASSERT(ub->ub_txg <= txg);
2069 
2070 	/*
2071 	 * If this isn't a resync due to I/O errors,
2072 	 * and nothing changed in this transaction group,
2073 	 * and multihost protection isn't enabled,
2074 	 * and the vdev configuration hasn't changed,
2075 	 * then there's nothing to do.
2076 	 */
2077 	if (ub->ub_txg < txg) {
2078 		boolean_t changed = uberblock_update(ub, spa->spa_root_vdev,
2079 		    txg, spa->spa_mmp.mmp_delay);
2080 
2081 		if (!changed && list_is_empty(&spa->spa_config_dirty_list) &&
2082 		    !spa_multihost(spa))
2083 			return (0);
2084 	}
2085 
2086 	if (txg > spa_freeze_txg(spa))
2087 		return (0);
2088 
2089 	ASSERT(txg <= spa->spa_final_txg);
2090 
2091 	/*
2092 	 * Flush the write cache of every disk that's been written to
2093 	 * in this transaction group.  This ensures that all blocks
2094 	 * written in this txg will be committed to stable storage
2095 	 * before any uberblock that references them.
2096 	 */
2097 	zio_t *zio = zio_root(spa, NULL, NULL, flags);
2098 
2099 	for (vdev_t *vd =
2100 	    txg_list_head(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)); vd != NULL;
2101 	    vd = txg_list_next(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg)))
2102 		zio_flush(zio, vd);
2103 
2104 	(void) zio_wait(zio);
2105 
2106 	/*
2107 	 * Sync out the even labels (L0, L2) for every dirty vdev.  If the
2108 	 * system dies in the middle of this process, that's OK: all of the
2109 	 * even labels that made it to disk will be newer than any uberblock,
2110 	 * and will therefore be considered invalid.  The odd labels (L1, L3),
2111 	 * which have not yet been touched, will still be valid.  We flush
2112 	 * the new labels to disk to ensure that all even-label updates
2113 	 * are committed to stable storage before the uberblock update.
2114 	 */
2115 	if ((error = vdev_label_sync_list(spa, 0, txg, flags)) != 0) {
2116 		if ((flags & ZIO_FLAG_TRYHARD) != 0) {
2117 			zfs_dbgmsg("vdev_label_sync_list() returned error %d "
2118 			    "for pool '%s' when syncing out the even labels "
2119 			    "of dirty vdevs", error, spa_name(spa));
2120 		}
2121 		goto retry;
2122 	}
2123 
2124 	/*
2125 	 * Sync the uberblocks to all vdevs in svd[].
2126 	 * If the system dies in the middle of this step, there are two cases
2127 	 * to consider, and the on-disk state is consistent either way:
2128 	 *
2129 	 * (1)	If none of the new uberblocks made it to disk, then the
2130 	 *	previous uberblock will be the newest, and the odd labels
2131 	 *	(which had not yet been touched) will be valid with respect
2132 	 *	to that uberblock.
2133 	 *
2134 	 * (2)	If one or more new uberblocks made it to disk, then they
2135 	 *	will be the newest, and the even labels (which had all
2136 	 *	been successfully committed) will be valid with respect
2137 	 *	to the new uberblocks.
2138 	 */
2139 	if ((error = vdev_uberblock_sync_list(svd, svdcount, ub, flags)) != 0) {
2140 		if ((flags & ZIO_FLAG_TRYHARD) != 0) {
2141 			zfs_dbgmsg("vdev_uberblock_sync_list() returned error "
2142 			    "%d for pool '%s'", error, spa_name(spa));
2143 		}
2144 		goto retry;
2145 	}
2146 
2147 	if (spa_multihost(spa))
2148 		mmp_update_uberblock(spa, ub);
2149 
2150 	/*
2151 	 * Sync out odd labels for every dirty vdev.  If the system dies
2152 	 * in the middle of this process, the even labels and the new
2153 	 * uberblocks will suffice to open the pool.  The next time
2154 	 * the pool is opened, the first thing we'll do -- before any
2155 	 * user data is modified -- is mark every vdev dirty so that
2156 	 * all labels will be brought up to date.  We flush the new labels
2157 	 * to disk to ensure that all odd-label updates are committed to
2158 	 * stable storage before the next transaction group begins.
2159 	 */
2160 	if ((error = vdev_label_sync_list(spa, 1, txg, flags)) != 0) {
2161 		if ((flags & ZIO_FLAG_TRYHARD) != 0) {
2162 			zfs_dbgmsg("vdev_label_sync_list() returned error %d "
2163 			    "for pool '%s' when syncing out the odd labels of "
2164 			    "dirty vdevs", error, spa_name(spa));
2165 		}
2166 		goto retry;
2167 	}
2168 
2169 	return (0);
2170 }
2171