xref: /freebsd/sys/contrib/openzfs/module/zfs/vdev_label.c (revision d8fbbd371ca11d9ad4b29b9d3a316885a5da0b15)
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_IO_RETRY)) {
866 		flags |= ZIO_FLAG_IO_RETRY;
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 	    ZIO_FLAG_TRYHARD;
1084 	boolean_t reason_spare = (reason == VDEV_LABEL_SPARE || (reason ==
1085 	    VDEV_LABEL_REMOVE && vd->vdev_isspare));
1086 	boolean_t reason_l2cache = (reason == VDEV_LABEL_L2CACHE || (reason ==
1087 	    VDEV_LABEL_REMOVE && vd->vdev_isl2cache));
1088 
1089 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1090 
1091 	for (int c = 0; c < vd->vdev_children; c++)
1092 		if ((error = vdev_label_init(vd->vdev_child[c],
1093 		    crtxg, reason)) != 0)
1094 			return (error);
1095 
1096 	/* Track the creation time for this vdev */
1097 	vd->vdev_crtxg = crtxg;
1098 
1099 	if (!vd->vdev_ops->vdev_op_leaf || !spa_writeable(spa))
1100 		return (0);
1101 
1102 	/*
1103 	 * Dead vdevs cannot be initialized.
1104 	 */
1105 	if (vdev_is_dead(vd))
1106 		return (SET_ERROR(EIO));
1107 
1108 	/*
1109 	 * Determine if the vdev is in use.
1110 	 */
1111 	if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_SPLIT &&
1112 	    vdev_inuse(vd, crtxg, reason, &spare_guid, &l2cache_guid)) {
1113 		if (spa->spa_create_info == NULL) {
1114 			nvlist_t *nv = fnvlist_alloc();
1115 			nvlist_t *cfg;
1116 
1117 			if (vd->vdev_path != NULL)
1118 				fnvlist_add_string(nv,
1119 				    ZPOOL_CREATE_INFO_VDEV, vd->vdev_path);
1120 
1121 			cfg = vdev_label_read_config(vd, -1ULL);
1122 			if (cfg != NULL) {
1123 				const char *pname;
1124 				if (nvlist_lookup_string(cfg,
1125 				    ZPOOL_CONFIG_POOL_NAME, &pname) == 0)
1126 					fnvlist_add_string(nv,
1127 					    ZPOOL_CREATE_INFO_POOL, pname);
1128 				nvlist_free(cfg);
1129 			}
1130 
1131 			spa->spa_create_info = nv;
1132 		}
1133 		return (SET_ERROR(EBUSY));
1134 	}
1135 
1136 	/*
1137 	 * If this is a request to add or replace a spare or l2cache device
1138 	 * that is in use elsewhere on the system, then we must update the
1139 	 * guid (which was initialized to a random value) to reflect the
1140 	 * actual GUID (which is shared between multiple pools).
1141 	 */
1142 	if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_L2CACHE &&
1143 	    spare_guid != 0ULL) {
1144 		uint64_t guid_delta = spare_guid - vd->vdev_guid;
1145 
1146 		vd->vdev_guid += guid_delta;
1147 
1148 		for (vdev_t *pvd = vd; pvd != NULL; pvd = pvd->vdev_parent)
1149 			pvd->vdev_guid_sum += guid_delta;
1150 
1151 		/*
1152 		 * If this is a replacement, then we want to fallthrough to the
1153 		 * rest of the code.  If we're adding a spare, then it's already
1154 		 * labeled appropriately and we can just return.
1155 		 */
1156 		if (reason == VDEV_LABEL_SPARE)
1157 			return (0);
1158 		ASSERT(reason == VDEV_LABEL_REPLACE ||
1159 		    reason == VDEV_LABEL_SPLIT);
1160 	}
1161 
1162 	if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_SPARE &&
1163 	    l2cache_guid != 0ULL) {
1164 		uint64_t guid_delta = l2cache_guid - vd->vdev_guid;
1165 
1166 		vd->vdev_guid += guid_delta;
1167 
1168 		for (vdev_t *pvd = vd; pvd != NULL; pvd = pvd->vdev_parent)
1169 			pvd->vdev_guid_sum += guid_delta;
1170 
1171 		/*
1172 		 * If this is a replacement, then we want to fallthrough to the
1173 		 * rest of the code.  If we're adding an l2cache, then it's
1174 		 * already labeled appropriately and we can just return.
1175 		 */
1176 		if (reason == VDEV_LABEL_L2CACHE)
1177 			return (0);
1178 		ASSERT(reason == VDEV_LABEL_REPLACE);
1179 	}
1180 
1181 	/*
1182 	 * Initialize its label.
1183 	 */
1184 	vp_abd = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
1185 	abd_zero(vp_abd, sizeof (vdev_phys_t));
1186 	vp = abd_to_buf(vp_abd);
1187 
1188 	/*
1189 	 * Generate a label describing the pool and our top-level vdev.
1190 	 * We mark it as being from txg 0 to indicate that it's not
1191 	 * really part of an active pool just yet.  The labels will
1192 	 * be written again with a meaningful txg by spa_sync().
1193 	 */
1194 	if (reason_spare || reason_l2cache) {
1195 		label = vdev_aux_label_generate(vd, reason_spare);
1196 
1197 		/*
1198 		 * When spare or l2cache (aux) vdev is added during pool
1199 		 * creation, spa->spa_uberblock is not written until this
1200 		 * point. Write it on next config sync.
1201 		 */
1202 		if (uberblock_verify(&spa->spa_uberblock))
1203 			spa->spa_aux_sync_uber = B_TRUE;
1204 	} else {
1205 		uint64_t txg = 0ULL;
1206 
1207 		if (reason == VDEV_LABEL_SPLIT)
1208 			txg = spa->spa_uberblock.ub_txg;
1209 		label = spa_config_generate(spa, vd, txg, B_FALSE);
1210 
1211 		/*
1212 		 * Add our creation time.  This allows us to detect multiple
1213 		 * vdev uses as described above, and automatically expires if we
1214 		 * fail.
1215 		 */
1216 		VERIFY0(nvlist_add_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
1217 		    crtxg));
1218 	}
1219 
1220 	buf = vp->vp_nvlist;
1221 	buflen = sizeof (vp->vp_nvlist);
1222 
1223 	error = nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP);
1224 	if (error != 0) {
1225 		nvlist_free(label);
1226 		abd_free(vp_abd);
1227 		/* EFAULT means nvlist_pack ran out of room */
1228 		return (SET_ERROR(error == EFAULT ? ENAMETOOLONG : EINVAL));
1229 	}
1230 
1231 	/*
1232 	 * Initialize uberblock template.
1233 	 */
1234 	ub_abd = abd_alloc_linear(VDEV_UBERBLOCK_RING, B_TRUE);
1235 	abd_copy_from_buf(ub_abd, &spa->spa_uberblock, sizeof (uberblock_t));
1236 	abd_zero_off(ub_abd, sizeof (uberblock_t),
1237 	    VDEV_UBERBLOCK_RING - sizeof (uberblock_t));
1238 	ub = abd_to_buf(ub_abd);
1239 	ub->ub_txg = 0;
1240 
1241 	/* Initialize the 2nd padding area. */
1242 	bootenv = abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE);
1243 	abd_zero(bootenv, VDEV_PAD_SIZE);
1244 
1245 	/*
1246 	 * Write everything in parallel.
1247 	 */
1248 	zio = zio_root(spa, NULL, NULL, flags);
1249 
1250 	for (int l = 0; l < VDEV_LABELS; l++) {
1251 
1252 		vdev_label_write(zio, vd, l, vp_abd,
1253 		    offsetof(vdev_label_t, vl_vdev_phys),
1254 		    sizeof (vdev_phys_t), NULL, NULL, flags);
1255 
1256 		/*
1257 		 * Skip the 1st padding area.
1258 		 * Zero out the 2nd padding area where it might have
1259 		 * left over data from previous filesystem format.
1260 		 */
1261 		vdev_label_write(zio, vd, l, bootenv,
1262 		    offsetof(vdev_label_t, vl_be),
1263 		    VDEV_PAD_SIZE, NULL, NULL, flags);
1264 
1265 		vdev_label_write(zio, vd, l, ub_abd,
1266 		    offsetof(vdev_label_t, vl_uberblock),
1267 		    VDEV_UBERBLOCK_RING, NULL, NULL, flags);
1268 	}
1269 
1270 	error = zio_wait(zio);
1271 
1272 	nvlist_free(label);
1273 	abd_free(bootenv);
1274 	abd_free(ub_abd);
1275 	abd_free(vp_abd);
1276 
1277 	/*
1278 	 * If this vdev hasn't been previously identified as a spare, then we
1279 	 * mark it as such only if a) we are labeling it as a spare, or b) it
1280 	 * exists as a spare elsewhere in the system.  Do the same for
1281 	 * level 2 ARC devices.
1282 	 */
1283 	if (error == 0 && !vd->vdev_isspare &&
1284 	    (reason == VDEV_LABEL_SPARE ||
1285 	    spa_spare_exists(vd->vdev_guid, NULL, NULL)))
1286 		spa_spare_add(vd);
1287 
1288 	if (error == 0 && !vd->vdev_isl2cache &&
1289 	    (reason == VDEV_LABEL_L2CACHE ||
1290 	    spa_l2cache_exists(vd->vdev_guid, NULL)))
1291 		spa_l2cache_add(vd);
1292 
1293 	return (error);
1294 }
1295 
1296 /*
1297  * Done callback for vdev_label_read_bootenv_impl. If this is the first
1298  * callback to finish, store our abd in the callback pointer. Otherwise, we
1299  * just free our abd and return.
1300  */
1301 static void
vdev_label_read_bootenv_done(zio_t * zio)1302 vdev_label_read_bootenv_done(zio_t *zio)
1303 {
1304 	zio_t *rio = zio->io_private;
1305 	abd_t **cbp = rio->io_private;
1306 
1307 	ASSERT3U(zio->io_size, ==, VDEV_PAD_SIZE);
1308 
1309 	if (zio->io_error == 0) {
1310 		mutex_enter(&rio->io_lock);
1311 		if (*cbp == NULL) {
1312 			/* Will free this buffer in vdev_label_read_bootenv. */
1313 			*cbp = zio->io_abd;
1314 		} else {
1315 			abd_free(zio->io_abd);
1316 		}
1317 		mutex_exit(&rio->io_lock);
1318 	} else {
1319 		abd_free(zio->io_abd);
1320 	}
1321 }
1322 
1323 static void
vdev_label_read_bootenv_impl(zio_t * zio,vdev_t * vd,int flags)1324 vdev_label_read_bootenv_impl(zio_t *zio, vdev_t *vd, int flags)
1325 {
1326 	for (int c = 0; c < vd->vdev_children; c++)
1327 		vdev_label_read_bootenv_impl(zio, vd->vdev_child[c], flags);
1328 
1329 	/*
1330 	 * We just use the first label that has a correct checksum; the
1331 	 * bootloader should have rewritten them all to be the same on boot,
1332 	 * and any changes we made since boot have been the same across all
1333 	 * labels.
1334 	 */
1335 	if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd)) {
1336 		for (int l = 0; l < VDEV_LABELS; l++) {
1337 			vdev_label_read(zio, vd, l,
1338 			    abd_alloc_linear(VDEV_PAD_SIZE, B_FALSE),
1339 			    offsetof(vdev_label_t, vl_be), VDEV_PAD_SIZE,
1340 			    vdev_label_read_bootenv_done, zio, flags);
1341 		}
1342 	}
1343 }
1344 
1345 int
vdev_label_read_bootenv(vdev_t * rvd,nvlist_t * bootenv)1346 vdev_label_read_bootenv(vdev_t *rvd, nvlist_t *bootenv)
1347 {
1348 	nvlist_t *config;
1349 	spa_t *spa = rvd->vdev_spa;
1350 	abd_t *abd = NULL;
1351 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
1352 	    ZIO_FLAG_SPECULATIVE | ZIO_FLAG_TRYHARD;
1353 
1354 	ASSERT(bootenv);
1355 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1356 
1357 	zio_t *zio = zio_root(spa, NULL, &abd, flags);
1358 	vdev_label_read_bootenv_impl(zio, rvd, flags);
1359 	int err = zio_wait(zio);
1360 
1361 	if (abd != NULL) {
1362 		char *buf;
1363 		vdev_boot_envblock_t *vbe = abd_to_buf(abd);
1364 
1365 		vbe->vbe_version = ntohll(vbe->vbe_version);
1366 		switch (vbe->vbe_version) {
1367 		case VB_RAW:
1368 			/*
1369 			 * if we have textual data in vbe_bootenv, create nvlist
1370 			 * with key "envmap".
1371 			 */
1372 			fnvlist_add_uint64(bootenv, BOOTENV_VERSION, VB_RAW);
1373 			vbe->vbe_bootenv[sizeof (vbe->vbe_bootenv) - 1] = '\0';
1374 			fnvlist_add_string(bootenv, GRUB_ENVMAP,
1375 			    vbe->vbe_bootenv);
1376 			break;
1377 
1378 		case VB_NVLIST:
1379 			err = nvlist_unpack(vbe->vbe_bootenv,
1380 			    sizeof (vbe->vbe_bootenv), &config, 0);
1381 			if (err == 0) {
1382 				fnvlist_merge(bootenv, config);
1383 				nvlist_free(config);
1384 				break;
1385 			}
1386 			zfs_fallthrough;
1387 		default:
1388 			/* Check for FreeBSD zfs bootonce command string */
1389 			buf = abd_to_buf(abd);
1390 			if (*buf == '\0') {
1391 				fnvlist_add_uint64(bootenv, BOOTENV_VERSION,
1392 				    VB_NVLIST);
1393 				break;
1394 			}
1395 			fnvlist_add_string(bootenv, FREEBSD_BOOTONCE, buf);
1396 		}
1397 
1398 		/*
1399 		 * abd was allocated in vdev_label_read_bootenv_impl()
1400 		 */
1401 		abd_free(abd);
1402 		/*
1403 		 * If we managed to read any successfully,
1404 		 * return success.
1405 		 */
1406 		return (0);
1407 	}
1408 	return (err);
1409 }
1410 
1411 int
vdev_label_write_bootenv(vdev_t * vd,nvlist_t * env)1412 vdev_label_write_bootenv(vdev_t *vd, nvlist_t *env)
1413 {
1414 	zio_t *zio;
1415 	spa_t *spa = vd->vdev_spa;
1416 	vdev_boot_envblock_t *bootenv;
1417 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
1418 	    ZIO_FLAG_TRYHARD;
1419 	int error;
1420 	size_t nvsize;
1421 	char *nvbuf;
1422 	const char *tmp;
1423 
1424 	error = nvlist_size(env, &nvsize, NV_ENCODE_XDR);
1425 	if (error != 0)
1426 		return (SET_ERROR(error));
1427 
1428 	if (nvsize >= sizeof (bootenv->vbe_bootenv)) {
1429 		return (SET_ERROR(E2BIG));
1430 	}
1431 
1432 	ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1433 
1434 	error = ENXIO;
1435 	for (int c = 0; c < vd->vdev_children; c++) {
1436 		int child_err;
1437 
1438 		child_err = vdev_label_write_bootenv(vd->vdev_child[c], env);
1439 		/*
1440 		 * As long as any of the disks managed to write all of their
1441 		 * labels successfully, return success.
1442 		 */
1443 		if (child_err == 0)
1444 			error = child_err;
1445 	}
1446 
1447 	if (!vd->vdev_ops->vdev_op_leaf || vdev_is_dead(vd) ||
1448 	    !vdev_writeable(vd)) {
1449 		return (error);
1450 	}
1451 	ASSERT3U(sizeof (*bootenv), ==, VDEV_PAD_SIZE);
1452 	abd_t *abd = abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE);
1453 	abd_zero(abd, VDEV_PAD_SIZE);
1454 
1455 	bootenv = abd_borrow_buf_copy(abd, VDEV_PAD_SIZE);
1456 	nvbuf = bootenv->vbe_bootenv;
1457 	nvsize = sizeof (bootenv->vbe_bootenv);
1458 
1459 	bootenv->vbe_version = fnvlist_lookup_uint64(env, BOOTENV_VERSION);
1460 	switch (bootenv->vbe_version) {
1461 	case VB_RAW:
1462 		if (nvlist_lookup_string(env, GRUB_ENVMAP, &tmp) == 0) {
1463 			(void) strlcpy(bootenv->vbe_bootenv, tmp, nvsize);
1464 		}
1465 		error = 0;
1466 		break;
1467 
1468 	case VB_NVLIST:
1469 		error = nvlist_pack(env, &nvbuf, &nvsize, NV_ENCODE_XDR,
1470 		    KM_SLEEP);
1471 		break;
1472 
1473 	default:
1474 		error = EINVAL;
1475 		break;
1476 	}
1477 
1478 	if (error == 0) {
1479 		bootenv->vbe_version = htonll(bootenv->vbe_version);
1480 		abd_return_buf_copy(abd, bootenv, VDEV_PAD_SIZE);
1481 	} else {
1482 		abd_free(abd);
1483 		return (SET_ERROR(error));
1484 	}
1485 
1486 	zio = zio_root(spa, NULL, NULL, flags);
1487 	for (int l = 0; l < VDEV_LABELS; l++) {
1488 		vdev_label_write(zio, vd, l, abd,
1489 		    offsetof(vdev_label_t, vl_be),
1490 		    VDEV_PAD_SIZE, NULL, NULL, flags);
1491 	}
1492 
1493 	error = zio_wait(zio);
1494 
1495 	abd_free(abd);
1496 	return (error);
1497 }
1498 
1499 /*
1500  * ==========================================================================
1501  * uberblock load/sync
1502  * ==========================================================================
1503  */
1504 
1505 /*
1506  * Consider the following situation: txg is safely synced to disk.  We've
1507  * written the first uberblock for txg + 1, and then we lose power.  When we
1508  * come back up, we fail to see the uberblock for txg + 1 because, say,
1509  * it was on a mirrored device and the replica to which we wrote txg + 1
1510  * is now offline.  If we then make some changes and sync txg + 1, and then
1511  * the missing replica comes back, then for a few seconds we'll have two
1512  * conflicting uberblocks on disk with the same txg.  The solution is simple:
1513  * among uberblocks with equal txg, choose the one with the latest timestamp.
1514  */
1515 int
vdev_uberblock_compare(const uberblock_t * ub1,const uberblock_t * ub2)1516 vdev_uberblock_compare(const uberblock_t *ub1, const uberblock_t *ub2)
1517 {
1518 	int cmp = TREE_CMP(ub1->ub_txg, ub2->ub_txg);
1519 
1520 	if (likely(cmp))
1521 		return (cmp);
1522 
1523 	cmp = TREE_CMP(ub1->ub_timestamp, ub2->ub_timestamp);
1524 	if (likely(cmp))
1525 		return (cmp);
1526 
1527 	/*
1528 	 * If MMP_VALID(ub) && MMP_SEQ_VALID(ub) then the host has an MMP-aware
1529 	 * ZFS, e.g. OpenZFS >= 0.7.
1530 	 *
1531 	 * If one ub has MMP and the other does not, they were written by
1532 	 * different hosts, which matters for MMP.  So we treat no MMP/no SEQ as
1533 	 * a 0 value.
1534 	 *
1535 	 * Since timestamp and txg are the same if we get this far, either is
1536 	 * acceptable for importing the pool.
1537 	 */
1538 	unsigned int seq1 = 0;
1539 	unsigned int seq2 = 0;
1540 
1541 	if (MMP_VALID(ub1) && MMP_SEQ_VALID(ub1))
1542 		seq1 = MMP_SEQ(ub1);
1543 
1544 	if (MMP_VALID(ub2) && MMP_SEQ_VALID(ub2))
1545 		seq2 = MMP_SEQ(ub2);
1546 
1547 	return (TREE_CMP(seq1, seq2));
1548 }
1549 
1550 struct ubl_cbdata {
1551 	uberblock_t	ubl_latest;	/* Most recent uberblock */
1552 	uberblock_t	*ubl_ubbest;	/* Best uberblock (w/r/t max_txg) */
1553 	vdev_t		*ubl_vd;	/* vdev associated with the above */
1554 };
1555 
1556 static void
vdev_uberblock_load_done(zio_t * zio)1557 vdev_uberblock_load_done(zio_t *zio)
1558 {
1559 	vdev_t *vd = zio->io_vd;
1560 	spa_t *spa = zio->io_spa;
1561 	zio_t *rio = zio->io_private;
1562 	uberblock_t *ub = abd_to_buf(zio->io_abd);
1563 	struct ubl_cbdata *cbp = rio->io_private;
1564 
1565 	ASSERT3U(zio->io_size, ==, VDEV_UBERBLOCK_SIZE(vd));
1566 
1567 	if (zio->io_error == 0 && uberblock_verify(ub) == 0) {
1568 		mutex_enter(&rio->io_lock);
1569 		if (vdev_uberblock_compare(ub, &cbp->ubl_latest) > 0) {
1570 			cbp->ubl_latest = *ub;
1571 		}
1572 		if (ub->ub_txg <= spa->spa_load_max_txg &&
1573 		    vdev_uberblock_compare(ub, cbp->ubl_ubbest) > 0) {
1574 			/*
1575 			 * Keep track of the vdev in which this uberblock
1576 			 * was found. We will use this information later
1577 			 * to obtain the config nvlist associated with
1578 			 * this uberblock.
1579 			 */
1580 			*cbp->ubl_ubbest = *ub;
1581 			cbp->ubl_vd = vd;
1582 		}
1583 		mutex_exit(&rio->io_lock);
1584 	}
1585 
1586 	abd_free(zio->io_abd);
1587 }
1588 
1589 static void
vdev_uberblock_load_impl(zio_t * zio,vdev_t * vd,int flags,struct ubl_cbdata * cbp)1590 vdev_uberblock_load_impl(zio_t *zio, vdev_t *vd, int flags,
1591     struct ubl_cbdata *cbp)
1592 {
1593 	for (int c = 0; c < vd->vdev_children; c++)
1594 		vdev_uberblock_load_impl(zio, vd->vdev_child[c], flags, cbp);
1595 
1596 	if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd) &&
1597 	    vd->vdev_ops != &vdev_draid_spare_ops) {
1598 		for (int l = 0; l < VDEV_LABELS; l++) {
1599 			for (int n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
1600 				vdev_label_read(zio, vd, l,
1601 				    abd_alloc_linear(VDEV_UBERBLOCK_SIZE(vd),
1602 				    B_TRUE), VDEV_UBERBLOCK_OFFSET(vd, n),
1603 				    VDEV_UBERBLOCK_SIZE(vd),
1604 				    vdev_uberblock_load_done, zio, flags);
1605 			}
1606 		}
1607 	}
1608 }
1609 
1610 /*
1611  * Reads the 'best' uberblock from disk along with its associated
1612  * configuration. First, we read the uberblock array of each label of each
1613  * vdev, keeping track of the uberblock with the highest txg in each array.
1614  * Then, we read the configuration from the same vdev as the best uberblock.
1615  */
1616 void
vdev_uberblock_load(vdev_t * rvd,uberblock_t * ub,nvlist_t ** config)1617 vdev_uberblock_load(vdev_t *rvd, uberblock_t *ub, nvlist_t **config)
1618 {
1619 	zio_t *zio;
1620 	spa_t *spa = rvd->vdev_spa;
1621 	struct ubl_cbdata cb;
1622 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
1623 	    ZIO_FLAG_SPECULATIVE | ZIO_FLAG_TRYHARD;
1624 
1625 	ASSERT(ub);
1626 	ASSERT(config);
1627 
1628 	memset(ub, 0, sizeof (uberblock_t));
1629 	memset(&cb, 0, sizeof (cb));
1630 	*config = NULL;
1631 
1632 	cb.ubl_ubbest = ub;
1633 
1634 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1635 	zio = zio_root(spa, NULL, &cb, flags);
1636 	vdev_uberblock_load_impl(zio, rvd, flags, &cb);
1637 	(void) zio_wait(zio);
1638 
1639 	/*
1640 	 * It's possible that the best uberblock was discovered on a label
1641 	 * that has a configuration which was written in a future txg.
1642 	 * Search all labels on this vdev to find the configuration that
1643 	 * matches the txg for our uberblock.
1644 	 */
1645 	if (cb.ubl_vd != NULL) {
1646 		vdev_dbgmsg(cb.ubl_vd, "best uberblock found for spa %s, "
1647 		    "txg=%llu seq=%llu", spa_load_name(spa),
1648 		    (u_longlong_t)ub->ub_txg,
1649 		    (u_longlong_t)(MMP_SEQ_VALID(ub) ? MMP_SEQ(ub) : 0));
1650 
1651 		if (ub->ub_raidz_reflow_info !=
1652 		    cb.ubl_latest.ub_raidz_reflow_info) {
1653 			vdev_dbgmsg(cb.ubl_vd,
1654 			    "spa=%s best uberblock (txg=%llu info=0x%llx) "
1655 			    "has different raidz_reflow_info than latest "
1656 			    "uberblock (txg=%llu info=0x%llx)",
1657 			    spa_load_name(spa),
1658 			    (u_longlong_t)ub->ub_txg,
1659 			    (u_longlong_t)ub->ub_raidz_reflow_info,
1660 			    (u_longlong_t)cb.ubl_latest.ub_txg,
1661 			    (u_longlong_t)cb.ubl_latest.ub_raidz_reflow_info);
1662 			memset(ub, 0, sizeof (uberblock_t));
1663 			spa_config_exit(spa, SCL_ALL, FTAG);
1664 			return;
1665 		}
1666 
1667 		*config = vdev_label_read_config(cb.ubl_vd, ub->ub_txg);
1668 		if (*config == NULL && spa->spa_extreme_rewind) {
1669 			vdev_dbgmsg(cb.ubl_vd, "failed to read label config. "
1670 			    "Trying again without txg restrictions.");
1671 			*config = vdev_label_read_config(cb.ubl_vd, UINT64_MAX);
1672 		}
1673 		if (*config == NULL) {
1674 			vdev_dbgmsg(cb.ubl_vd, "failed to read label config");
1675 		}
1676 	}
1677 	spa_config_exit(spa, SCL_ALL, FTAG);
1678 }
1679 
1680 /*
1681  * For use when a leaf vdev is expanded.
1682  * The location of labels 2 and 3 changed, and at the new location the
1683  * uberblock rings are either empty or contain garbage.  The sync will write
1684  * new configs there because the vdev is dirty, but expansion also needs the
1685  * uberblock rings copied.  Read them from label 0 which did not move.
1686  *
1687  * Since the point is to populate labels {2,3} with valid uberblocks,
1688  * we zero uberblocks we fail to read or which are not valid.
1689  */
1690 
1691 static void
vdev_copy_uberblocks(vdev_t * vd)1692 vdev_copy_uberblocks(vdev_t *vd)
1693 {
1694 	abd_t *ub_abd;
1695 	zio_t *write_zio;
1696 	int locks = (SCL_L2ARC | SCL_ZIO);
1697 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
1698 	    ZIO_FLAG_SPECULATIVE;
1699 
1700 	ASSERT(spa_config_held(vd->vdev_spa, SCL_STATE, RW_READER) ==
1701 	    SCL_STATE);
1702 	ASSERT(vd->vdev_ops->vdev_op_leaf);
1703 
1704 	/*
1705 	 * No uberblocks are stored on distributed spares, they may be
1706 	 * safely skipped when expanding a leaf vdev.
1707 	 */
1708 	if (vd->vdev_ops == &vdev_draid_spare_ops)
1709 		return;
1710 
1711 	spa_config_enter(vd->vdev_spa, locks, FTAG, RW_READER);
1712 
1713 	ub_abd = abd_alloc_linear(VDEV_UBERBLOCK_SIZE(vd), B_TRUE);
1714 
1715 	write_zio = zio_root(vd->vdev_spa, NULL, NULL, flags);
1716 	for (int n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
1717 		const int src_label = 0;
1718 		zio_t *zio;
1719 
1720 		zio = zio_root(vd->vdev_spa, NULL, NULL, flags);
1721 		vdev_label_read(zio, vd, src_label, ub_abd,
1722 		    VDEV_UBERBLOCK_OFFSET(vd, n), VDEV_UBERBLOCK_SIZE(vd),
1723 		    NULL, NULL, flags);
1724 
1725 		if (zio_wait(zio) || uberblock_verify(abd_to_buf(ub_abd)))
1726 			abd_zero(ub_abd, VDEV_UBERBLOCK_SIZE(vd));
1727 
1728 		for (int l = 2; l < VDEV_LABELS; l++)
1729 			vdev_label_write(write_zio, vd, l, ub_abd,
1730 			    VDEV_UBERBLOCK_OFFSET(vd, n),
1731 			    VDEV_UBERBLOCK_SIZE(vd), NULL, NULL,
1732 			    flags | ZIO_FLAG_DONT_PROPAGATE);
1733 	}
1734 	(void) zio_wait(write_zio);
1735 
1736 	spa_config_exit(vd->vdev_spa, locks, FTAG);
1737 
1738 	abd_free(ub_abd);
1739 }
1740 
1741 /*
1742  * On success, increment root zio's count of good writes.
1743  * We only get credit for writes to known-visible vdevs; see spa_vdev_add().
1744  */
1745 static void
vdev_uberblock_sync_done(zio_t * zio)1746 vdev_uberblock_sync_done(zio_t *zio)
1747 {
1748 	uint64_t *good_writes = zio->io_private;
1749 
1750 	if (zio->io_error == 0 && zio->io_vd->vdev_top->vdev_ms_array != 0)
1751 		atomic_inc_64(good_writes);
1752 }
1753 
1754 /*
1755  * Write the uberblock to all labels of all leaves of the specified vdev.
1756  */
1757 static void
vdev_uberblock_sync(zio_t * zio,uint64_t * good_writes,uberblock_t * ub,vdev_t * vd,int flags)1758 vdev_uberblock_sync(zio_t *zio, uint64_t *good_writes,
1759     uberblock_t *ub, vdev_t *vd, int flags)
1760 {
1761 	for (uint64_t c = 0; c < vd->vdev_children; c++) {
1762 		vdev_uberblock_sync(zio, good_writes,
1763 		    ub, vd->vdev_child[c], flags);
1764 	}
1765 
1766 	if (!vd->vdev_ops->vdev_op_leaf)
1767 		return;
1768 
1769 	if (!vdev_writeable(vd))
1770 		return;
1771 
1772 	/*
1773 	 * There's no need to write uberblocks to a distributed spare, they
1774 	 * are already stored on all the leaves of the parent dRAID.  For
1775 	 * this same reason vdev_uberblock_load_impl() skips distributed
1776 	 * spares when reading uberblocks.
1777 	 */
1778 	if (vd->vdev_ops == &vdev_draid_spare_ops)
1779 		return;
1780 
1781 	/* If the vdev was expanded, need to copy uberblock rings. */
1782 	if (vd->vdev_state == VDEV_STATE_HEALTHY &&
1783 	    vd->vdev_copy_uberblocks == B_TRUE) {
1784 		vdev_copy_uberblocks(vd);
1785 		vd->vdev_copy_uberblocks = B_FALSE;
1786 	}
1787 
1788 	/*
1789 	 * We chose a slot based on the txg.  If this uberblock has a special
1790 	 * RAIDZ expansion state, then it is essentially an update of the
1791 	 * current uberblock (it has the same txg).  However, the current
1792 	 * state is committed, so we want to write it to a different slot. If
1793 	 * we overwrote the same slot, and we lose power during the uberblock
1794 	 * write, and the disk does not do single-sector overwrites
1795 	 * atomically (even though it is required to - i.e. we should see
1796 	 * either the old or the new uberblock), then we could lose this
1797 	 * txg's uberblock. Rewinding to the previous txg's uberblock may not
1798 	 * be possible because RAIDZ expansion may have already overwritten
1799 	 * some of the data, so we need the progress indicator in the
1800 	 * uberblock.
1801 	 */
1802 	int m = spa_multihost(vd->vdev_spa) ? MMP_BLOCKS_PER_LABEL : 0;
1803 	int n = (ub->ub_txg - (RRSS_GET_STATE(ub) == RRSS_SCRATCH_VALID)) %
1804 	    (VDEV_UBERBLOCK_COUNT(vd) - m);
1805 
1806 	/* Copy the uberblock_t into the ABD */
1807 	abd_t *ub_abd = abd_alloc_for_io(VDEV_UBERBLOCK_SIZE(vd), B_TRUE);
1808 	abd_copy_from_buf(ub_abd, ub, sizeof (uberblock_t));
1809 	abd_zero_off(ub_abd, sizeof (uberblock_t),
1810 	    VDEV_UBERBLOCK_SIZE(vd) - sizeof (uberblock_t));
1811 
1812 	for (int l = 0; l < VDEV_LABELS; l++)
1813 		vdev_label_write(zio, vd, l, ub_abd,
1814 		    VDEV_UBERBLOCK_OFFSET(vd, n), VDEV_UBERBLOCK_SIZE(vd),
1815 		    vdev_uberblock_sync_done, good_writes,
1816 		    flags | ZIO_FLAG_DONT_PROPAGATE);
1817 
1818 	abd_free(ub_abd);
1819 }
1820 
1821 /* Sync the uberblocks to all vdevs in svd[] */
1822 int
vdev_uberblock_sync_list(vdev_t ** svd,int svdcount,uberblock_t * ub,int flags)1823 vdev_uberblock_sync_list(vdev_t **svd, int svdcount, uberblock_t *ub, int flags)
1824 {
1825 	spa_t *spa = svd[0]->vdev_spa;
1826 	zio_t *zio;
1827 	uint64_t good_writes = 0;
1828 
1829 	zio = zio_root(spa, NULL, NULL, flags);
1830 
1831 	for (int v = 0; v < svdcount; v++)
1832 		vdev_uberblock_sync(zio, &good_writes, ub, svd[v], flags);
1833 
1834 	if (spa->spa_aux_sync_uber) {
1835 		for (int v = 0; v < spa->spa_spares.sav_count; v++) {
1836 			vdev_uberblock_sync(zio, &good_writes, ub,
1837 			    spa->spa_spares.sav_vdevs[v], flags);
1838 		}
1839 		for (int v = 0; v < spa->spa_l2cache.sav_count; v++) {
1840 			vdev_uberblock_sync(zio, &good_writes, ub,
1841 			    spa->spa_l2cache.sav_vdevs[v], flags);
1842 		}
1843 	}
1844 	(void) zio_wait(zio);
1845 
1846 	/*
1847 	 * Flush the uberblocks to disk.  This ensures that the odd labels
1848 	 * are no longer needed (because the new uberblocks and the even
1849 	 * labels are safely on disk), so it is safe to overwrite them.
1850 	 */
1851 	zio = zio_root(spa, NULL, NULL, flags);
1852 
1853 	for (int v = 0; v < svdcount; v++) {
1854 		if (vdev_writeable(svd[v])) {
1855 			zio_flush(zio, svd[v]);
1856 		}
1857 	}
1858 	if (spa->spa_aux_sync_uber) {
1859 		spa->spa_aux_sync_uber = B_FALSE;
1860 		for (int v = 0; v < spa->spa_spares.sav_count; v++) {
1861 			if (vdev_writeable(spa->spa_spares.sav_vdevs[v])) {
1862 				zio_flush(zio, spa->spa_spares.sav_vdevs[v]);
1863 			}
1864 		}
1865 		for (int v = 0; v < spa->spa_l2cache.sav_count; v++) {
1866 			if (vdev_writeable(spa->spa_l2cache.sav_vdevs[v])) {
1867 				zio_flush(zio, spa->spa_l2cache.sav_vdevs[v]);
1868 			}
1869 		}
1870 	}
1871 
1872 	(void) zio_wait(zio);
1873 
1874 	return (good_writes >= 1 ? 0 : EIO);
1875 }
1876 
1877 /*
1878  * On success, increment the count of good writes for our top-level vdev.
1879  */
1880 static void
vdev_label_sync_done(zio_t * zio)1881 vdev_label_sync_done(zio_t *zio)
1882 {
1883 	uint64_t *good_writes = zio->io_private;
1884 
1885 	if (zio->io_error == 0)
1886 		atomic_inc_64(good_writes);
1887 }
1888 
1889 /*
1890  * If there weren't enough good writes, indicate failure to the parent.
1891  */
1892 static void
vdev_label_sync_top_done(zio_t * zio)1893 vdev_label_sync_top_done(zio_t *zio)
1894 {
1895 	uint64_t *good_writes = zio->io_private;
1896 
1897 	if (*good_writes == 0)
1898 		zio->io_error = SET_ERROR(EIO);
1899 
1900 	kmem_free(good_writes, sizeof (uint64_t));
1901 }
1902 
1903 /*
1904  * We ignore errors for log and cache devices, simply free the private data.
1905  */
1906 static void
vdev_label_sync_ignore_done(zio_t * zio)1907 vdev_label_sync_ignore_done(zio_t *zio)
1908 {
1909 	kmem_free(zio->io_private, sizeof (uint64_t));
1910 }
1911 
1912 /*
1913  * Write all even or odd labels to all leaves of the specified vdev.
1914  */
1915 static void
vdev_label_sync(zio_t * zio,uint64_t * good_writes,vdev_t * vd,int l,uint64_t txg,int flags)1916 vdev_label_sync(zio_t *zio, uint64_t *good_writes,
1917     vdev_t *vd, int l, uint64_t txg, int flags)
1918 {
1919 	nvlist_t *label;
1920 	vdev_phys_t *vp;
1921 	abd_t *vp_abd;
1922 	char *buf;
1923 	size_t buflen;
1924 	vdev_t *pvd = vd->vdev_parent;
1925 	boolean_t spare_in_use = B_FALSE;
1926 
1927 	for (int c = 0; c < vd->vdev_children; c++) {
1928 		vdev_label_sync(zio, good_writes,
1929 		    vd->vdev_child[c], l, txg, flags);
1930 	}
1931 
1932 	if (!vd->vdev_ops->vdev_op_leaf)
1933 		return;
1934 
1935 	if (!vdev_writeable(vd))
1936 		return;
1937 
1938 	/*
1939 	 * The top-level config never needs to be written to a distributed
1940 	 * spare.  When read vdev_dspare_label_read_config() will generate
1941 	 * the config for the vdev_label_read_config().
1942 	 */
1943 	if (vd->vdev_ops == &vdev_draid_spare_ops)
1944 		return;
1945 
1946 	if (pvd && pvd->vdev_ops == &vdev_spare_ops)
1947 		spare_in_use = B_TRUE;
1948 
1949 	/*
1950 	 * Generate a label describing the top-level config to which we belong.
1951 	 */
1952 	if ((vd->vdev_isspare && !spare_in_use) || vd->vdev_isl2cache) {
1953 		label = vdev_aux_label_generate(vd, vd->vdev_isspare);
1954 	} else {
1955 		label = spa_config_generate(vd->vdev_spa, vd, txg, B_FALSE);
1956 	}
1957 
1958 	vp_abd = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
1959 	abd_zero(vp_abd, sizeof (vdev_phys_t));
1960 	vp = abd_to_buf(vp_abd);
1961 
1962 	buf = vp->vp_nvlist;
1963 	buflen = sizeof (vp->vp_nvlist);
1964 
1965 	if (!nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP)) {
1966 		for (; l < VDEV_LABELS; l += 2) {
1967 			vdev_label_write(zio, vd, l, vp_abd,
1968 			    offsetof(vdev_label_t, vl_vdev_phys),
1969 			    sizeof (vdev_phys_t),
1970 			    vdev_label_sync_done, good_writes,
1971 			    flags | ZIO_FLAG_DONT_PROPAGATE);
1972 		}
1973 	}
1974 
1975 	abd_free(vp_abd);
1976 	nvlist_free(label);
1977 }
1978 
1979 static int
vdev_label_sync_list(spa_t * spa,int l,uint64_t txg,int flags)1980 vdev_label_sync_list(spa_t *spa, int l, uint64_t txg, int flags)
1981 {
1982 	list_t *dl = &spa->spa_config_dirty_list;
1983 	vdev_t *vd;
1984 	zio_t *zio;
1985 	int error;
1986 
1987 	/*
1988 	 * Write the new labels to disk.
1989 	 */
1990 	zio = zio_root(spa, NULL, NULL, flags);
1991 
1992 	for (vd = list_head(dl); vd != NULL; vd = list_next(dl, vd)) {
1993 		uint64_t *good_writes;
1994 
1995 		ASSERT(!vd->vdev_ishole);
1996 
1997 		good_writes = kmem_zalloc(sizeof (uint64_t), KM_SLEEP);
1998 		zio_t *vio = zio_null(zio, spa, NULL,
1999 		    (vd->vdev_islog || vd->vdev_aux != NULL) ?
2000 		    vdev_label_sync_ignore_done : vdev_label_sync_top_done,
2001 		    good_writes, flags);
2002 		vdev_label_sync(vio, good_writes, vd, l, txg, flags);
2003 		zio_nowait(vio);
2004 	}
2005 
2006 	/*
2007 	 * AUX path may have changed during import
2008 	 */
2009 	spa_aux_vdev_t *sav[2] = {&spa->spa_spares, &spa->spa_l2cache};
2010 	for (int i = 0; i < 2; i++) {
2011 		for (int v = 0; v < sav[i]->sav_count; v++) {
2012 			uint64_t *good_writes;
2013 			if (!sav[i]->sav_label_sync)
2014 				continue;
2015 			good_writes = kmem_zalloc(sizeof (uint64_t), KM_SLEEP);
2016 			zio_t *vio = zio_null(zio, spa, NULL,
2017 			    vdev_label_sync_ignore_done, good_writes, flags);
2018 			vdev_label_sync(vio, good_writes, sav[i]->sav_vdevs[v],
2019 			    l, txg, flags);
2020 			zio_nowait(vio);
2021 		}
2022 	}
2023 
2024 	error = zio_wait(zio);
2025 
2026 	/*
2027 	 * Flush the new labels to disk.
2028 	 */
2029 	zio = zio_root(spa, NULL, NULL, flags);
2030 
2031 	for (vd = list_head(dl); vd != NULL; vd = list_next(dl, vd))
2032 		zio_flush(zio, vd);
2033 
2034 	for (int i = 0; i < 2; i++) {
2035 		if (!sav[i]->sav_label_sync)
2036 			continue;
2037 		for (int v = 0; v < sav[i]->sav_count; v++)
2038 			zio_flush(zio, sav[i]->sav_vdevs[v]);
2039 		if (l == 1)
2040 			sav[i]->sav_label_sync = B_FALSE;
2041 	}
2042 
2043 	(void) zio_wait(zio);
2044 
2045 	return (error);
2046 }
2047 
2048 /*
2049  * Sync the uberblock and any changes to the vdev configuration.
2050  *
2051  * The order of operations is carefully crafted to ensure that
2052  * if the system panics or loses power at any time, the state on disk
2053  * is still transactionally consistent.  The in-line comments below
2054  * describe the failure semantics at each stage.
2055  *
2056  * Moreover, vdev_config_sync() is designed to be idempotent: if it fails
2057  * at any time, you can just call it again, and it will resume its work.
2058  */
2059 int
vdev_config_sync(vdev_t ** svd,int svdcount,uint64_t txg)2060 vdev_config_sync(vdev_t **svd, int svdcount, uint64_t txg)
2061 {
2062 	spa_t *spa = svd[0]->vdev_spa;
2063 	uberblock_t *ub = &spa->spa_uberblock;
2064 	int error = 0;
2065 	int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL;
2066 
2067 	ASSERT(svdcount != 0);
2068 retry:
2069 	/*
2070 	 * Normally, we don't want to try too hard to write every label and
2071 	 * uberblock.  If there is a flaky disk, we don't want the rest of the
2072 	 * sync process to block while we retry.  But if we can't write a
2073 	 * single label out, we should retry with ZIO_FLAG_IO_RETRY before
2074 	 * bailing out and declaring the pool faulted.
2075 	 */
2076 	if (error != 0) {
2077 		if ((flags & ZIO_FLAG_IO_RETRY) != 0)
2078 			return (error);
2079 		flags |= ZIO_FLAG_IO_RETRY;
2080 	}
2081 
2082 	ASSERT(ub->ub_txg <= txg);
2083 
2084 	/*
2085 	 * If this isn't a resync due to I/O errors,
2086 	 * and nothing changed in this transaction group,
2087 	 * and multihost protection isn't enabled,
2088 	 * and the vdev configuration hasn't changed,
2089 	 * then there's nothing to do.
2090 	 */
2091 	if (ub->ub_txg < txg) {
2092 		boolean_t changed = uberblock_update(ub, spa->spa_root_vdev,
2093 		    txg, spa->spa_mmp.mmp_delay);
2094 
2095 		if (!changed && list_is_empty(&spa->spa_config_dirty_list) &&
2096 		    !spa_multihost(spa))
2097 			return (0);
2098 	}
2099 
2100 	if (txg > spa_freeze_txg(spa))
2101 		return (0);
2102 
2103 	ASSERT(txg <= spa->spa_final_txg);
2104 
2105 	/*
2106 	 * Flush the write cache of every disk that's been written to
2107 	 * in this transaction group.  This ensures that all blocks
2108 	 * written in this txg will be committed to stable storage
2109 	 * before any uberblock that references them.
2110 	 */
2111 	zio_t *zio = zio_root(spa, NULL, NULL, flags);
2112 
2113 	for (vdev_t *vd =
2114 	    txg_list_head(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)); vd != NULL;
2115 	    vd = txg_list_next(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg)))
2116 		zio_flush(zio, vd);
2117 
2118 	(void) zio_wait(zio);
2119 
2120 	/*
2121 	 * Sync out the even labels (L0, L2) for every dirty vdev.  If the
2122 	 * system dies in the middle of this process, that's OK: all of the
2123 	 * even labels that made it to disk will be newer than any uberblock,
2124 	 * and will therefore be considered invalid.  The odd labels (L1, L3),
2125 	 * which have not yet been touched, will still be valid.  We flush
2126 	 * the new labels to disk to ensure that all even-label updates
2127 	 * are committed to stable storage before the uberblock update.
2128 	 */
2129 	if ((error = vdev_label_sync_list(spa, 0, txg, flags)) != 0) {
2130 		if ((flags & ZIO_FLAG_IO_RETRY) != 0) {
2131 			zfs_dbgmsg("vdev_label_sync_list() returned error %d "
2132 			    "for pool '%s' when syncing out the even labels "
2133 			    "of dirty vdevs", error, spa_name(spa));
2134 		}
2135 		goto retry;
2136 	}
2137 
2138 	/*
2139 	 * Sync the uberblocks to all vdevs in svd[].
2140 	 * If the system dies in the middle of this step, there are two cases
2141 	 * to consider, and the on-disk state is consistent either way:
2142 	 *
2143 	 * (1)	If none of the new uberblocks made it to disk, then the
2144 	 *	previous uberblock will be the newest, and the odd labels
2145 	 *	(which had not yet been touched) will be valid with respect
2146 	 *	to that uberblock.
2147 	 *
2148 	 * (2)	If one or more new uberblocks made it to disk, then they
2149 	 *	will be the newest, and the even labels (which had all
2150 	 *	been successfully committed) will be valid with respect
2151 	 *	to the new uberblocks.
2152 	 */
2153 	if ((error = vdev_uberblock_sync_list(svd, svdcount, ub, flags)) != 0) {
2154 		if ((flags & ZIO_FLAG_IO_RETRY) != 0) {
2155 			zfs_dbgmsg("vdev_uberblock_sync_list() returned error "
2156 			    "%d for pool '%s'", error, spa_name(spa));
2157 		}
2158 		goto retry;
2159 	}
2160 
2161 	if (spa_multihost(spa))
2162 		mmp_update_uberblock(spa, ub);
2163 
2164 	/*
2165 	 * Sync out odd labels for every dirty vdev.  If the system dies
2166 	 * in the middle of this process, the even labels and the new
2167 	 * uberblocks will suffice to open the pool.  The next time
2168 	 * the pool is opened, the first thing we'll do -- before any
2169 	 * user data is modified -- is mark every vdev dirty so that
2170 	 * all labels will be brought up to date.  We flush the new labels
2171 	 * to disk to ensure that all odd-label updates are committed to
2172 	 * stable storage before the next transaction group begins.
2173 	 */
2174 	if ((error = vdev_label_sync_list(spa, 1, txg, flags)) != 0) {
2175 		if ((flags & ZIO_FLAG_IO_RETRY) != 0) {
2176 			zfs_dbgmsg("vdev_label_sync_list() returned error %d "
2177 			    "for pool '%s' when syncing out the odd labels of "
2178 			    "dirty vdevs", error, spa_name(spa));
2179 		}
2180 		goto retry;
2181 	}
2182 
2183 	return (0);
2184 }
2185