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