Fix hangs with processes stuck sleeping on btalloc on i386.
[freebsd.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / vdev_label.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2012, 2020 by Delphix. All rights reserved.
25  * Copyright (c) 2017, Intel Corporation.
26  * Copyright 2019 Joyent, Inc.
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/uberblock_impl.h>
147 #include <sys/metaslab.h>
148 #include <sys/metaslab_impl.h>
149 #include <sys/zio.h>
150 #include <sys/dsl_scan.h>
151 #include <sys/abd.h>
152 #include <sys/fs/zfs.h>
153 #include <sys/trim_map.h>
154
155 static boolean_t vdev_trim_on_init = B_TRUE;
156 SYSCTL_DECL(_vfs_zfs_vdev);
157 SYSCTL_INT(_vfs_zfs_vdev, OID_AUTO, trim_on_init, CTLFLAG_RWTUN,
158     &vdev_trim_on_init, 0, "Enable/disable full vdev trim on initialisation");
159
160 /*
161  * Basic routines to read and write from a vdev label.
162  * Used throughout the rest of this file.
163  */
164 uint64_t
165 vdev_label_offset(uint64_t psize, int l, uint64_t offset)
166 {
167         ASSERT(offset < sizeof (vdev_label_t));
168         ASSERT(P2PHASE_TYPED(psize, sizeof (vdev_label_t), uint64_t) == 0);
169
170         return (offset + l * sizeof (vdev_label_t) + (l < VDEV_LABELS / 2 ?
171             0 : psize - VDEV_LABELS * sizeof (vdev_label_t)));
172 }
173
174 /*
175  * Returns back the vdev label associated with the passed in offset.
176  */
177 int
178 vdev_label_number(uint64_t psize, uint64_t offset)
179 {
180         int l;
181
182         if (offset >= psize - VDEV_LABEL_END_SIZE) {
183                 offset -= psize - VDEV_LABEL_END_SIZE;
184                 offset += (VDEV_LABELS / 2) * sizeof (vdev_label_t);
185         }
186         l = offset / sizeof (vdev_label_t);
187         return (l < VDEV_LABELS ? l : -1);
188 }
189
190 static void
191 vdev_label_read(zio_t *zio, vdev_t *vd, int l, abd_t *buf, uint64_t offset,
192     uint64_t size, zio_done_func_t *done, void *private, int flags)
193 {
194         ASSERT(
195             spa_config_held(zio->io_spa, SCL_STATE, RW_READER) == SCL_STATE ||
196             spa_config_held(zio->io_spa, SCL_STATE, RW_WRITER) == SCL_STATE);
197         ASSERT(flags & ZIO_FLAG_CONFIG_WRITER);
198
199         zio_nowait(zio_read_phys(zio, vd,
200             vdev_label_offset(vd->vdev_psize, l, offset),
201             size, buf, ZIO_CHECKSUM_LABEL, done, private,
202             ZIO_PRIORITY_SYNC_READ, flags, B_TRUE));
203 }
204
205 void
206 vdev_label_write(zio_t *zio, vdev_t *vd, int l, abd_t *buf, uint64_t offset,
207     uint64_t size, zio_done_func_t *done, void *private, int flags)
208 {
209         ASSERT(
210             spa_config_held(zio->io_spa, SCL_STATE, RW_READER) == SCL_STATE ||
211             spa_config_held(zio->io_spa, SCL_STATE, RW_WRITER) == SCL_STATE);
212         ASSERT(flags & ZIO_FLAG_CONFIG_WRITER);
213
214         zio_nowait(zio_write_phys(zio, vd,
215             vdev_label_offset(vd->vdev_psize, l, offset),
216             size, buf, ZIO_CHECKSUM_LABEL, done, private,
217             ZIO_PRIORITY_SYNC_WRITE, flags, B_TRUE));
218 }
219
220 static void
221 root_vdev_actions_getprogress(vdev_t *vd, nvlist_t *nvl)
222 {
223         spa_t *spa = vd->vdev_spa;
224
225         if (vd != spa->spa_root_vdev)
226                 return;
227
228         /* provide either current or previous scan information */
229         pool_scan_stat_t ps;
230         if (spa_scan_get_stats(spa, &ps) == 0) {
231                 fnvlist_add_uint64_array(nvl,
232                     ZPOOL_CONFIG_SCAN_STATS, (uint64_t *)&ps,
233                     sizeof (pool_scan_stat_t) / sizeof (uint64_t));
234         }
235
236         pool_removal_stat_t prs;
237         if (spa_removal_get_stats(spa, &prs) == 0) {
238                 fnvlist_add_uint64_array(nvl,
239                     ZPOOL_CONFIG_REMOVAL_STATS, (uint64_t *)&prs,
240                     sizeof (prs) / sizeof (uint64_t));
241         }
242
243         pool_checkpoint_stat_t pcs;
244         if (spa_checkpoint_get_stats(spa, &pcs) == 0) {
245                 fnvlist_add_uint64_array(nvl,
246                     ZPOOL_CONFIG_CHECKPOINT_STATS, (uint64_t *)&pcs,
247                     sizeof (pcs) / sizeof (uint64_t));
248         }
249 }
250
251 /*
252  * Generate the nvlist representing this vdev's config.
253  */
254 nvlist_t *
255 vdev_config_generate(spa_t *spa, vdev_t *vd, boolean_t getstats,
256     vdev_config_flag_t flags)
257 {
258         nvlist_t *nv = NULL;
259         vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
260
261         nv = fnvlist_alloc();
262
263         fnvlist_add_string(nv, ZPOOL_CONFIG_TYPE, vd->vdev_ops->vdev_op_type);
264         if (!(flags & (VDEV_CONFIG_SPARE | VDEV_CONFIG_L2CACHE)))
265                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_ID, vd->vdev_id);
266         fnvlist_add_uint64(nv, ZPOOL_CONFIG_GUID, vd->vdev_guid);
267
268         if (vd->vdev_path != NULL)
269                 fnvlist_add_string(nv, ZPOOL_CONFIG_PATH, vd->vdev_path);
270
271         if (vd->vdev_devid != NULL)
272                 fnvlist_add_string(nv, ZPOOL_CONFIG_DEVID, vd->vdev_devid);
273
274         if (vd->vdev_physpath != NULL)
275                 fnvlist_add_string(nv, ZPOOL_CONFIG_PHYS_PATH,
276                     vd->vdev_physpath);
277
278         if (vd->vdev_fru != NULL)
279                 fnvlist_add_string(nv, ZPOOL_CONFIG_FRU, vd->vdev_fru);
280
281         if (vd->vdev_nparity != 0) {
282                 ASSERT(strcmp(vd->vdev_ops->vdev_op_type,
283                     VDEV_TYPE_RAIDZ) == 0);
284
285                 /*
286                  * Make sure someone hasn't managed to sneak a fancy new vdev
287                  * into a crufty old storage pool.
288                  */
289                 ASSERT(vd->vdev_nparity == 1 ||
290                     (vd->vdev_nparity <= 2 &&
291                     spa_version(spa) >= SPA_VERSION_RAIDZ2) ||
292                     (vd->vdev_nparity <= 3 &&
293                     spa_version(spa) >= SPA_VERSION_RAIDZ3));
294
295                 /*
296                  * Note that we'll add the nparity tag even on storage pools
297                  * that only support a single parity device -- older software
298                  * will just ignore it.
299                  */
300                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_NPARITY, vd->vdev_nparity);
301         }
302
303         if (vd->vdev_wholedisk != -1ULL)
304                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
305                     vd->vdev_wholedisk);
306
307         if (vd->vdev_not_present && !(flags & VDEV_CONFIG_MISSING))
308                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT, 1);
309
310         if (vd->vdev_isspare)
311                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_IS_SPARE, 1);
312
313         if (!(flags & (VDEV_CONFIG_SPARE | VDEV_CONFIG_L2CACHE)) &&
314             vd == vd->vdev_top) {
315                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
316                     vd->vdev_ms_array);
317                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
318                     vd->vdev_ms_shift);
319                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_ASHIFT, vd->vdev_ashift);
320                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_ASIZE,
321                     vd->vdev_asize);
322                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_IS_LOG, vd->vdev_islog);
323                 if (vd->vdev_removing) {
324                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_REMOVING,
325                             vd->vdev_removing);
326                 }
327
328                 /* zpool command expects alloc class data */
329                 if (getstats && vd->vdev_alloc_bias != VDEV_BIAS_NONE) {
330                         const char *bias = NULL;
331
332                         switch (vd->vdev_alloc_bias) {
333                         case VDEV_BIAS_LOG:
334                                 bias = VDEV_ALLOC_BIAS_LOG;
335                                 break;
336                         case VDEV_BIAS_SPECIAL:
337                                 bias = VDEV_ALLOC_BIAS_SPECIAL;
338                                 break;
339                         case VDEV_BIAS_DEDUP:
340                                 bias = VDEV_ALLOC_BIAS_DEDUP;
341                                 break;
342                         default:
343                                 ASSERT3U(vd->vdev_alloc_bias, ==,
344                                     VDEV_BIAS_NONE);
345                         }
346                         fnvlist_add_string(nv, ZPOOL_CONFIG_ALLOCATION_BIAS,
347                             bias);
348                 }
349         }
350
351         if (vd->vdev_dtl_sm != NULL) {
352                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_DTL,
353                     space_map_object(vd->vdev_dtl_sm));
354         }
355
356         if (vic->vic_mapping_object != 0) {
357                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_INDIRECT_OBJECT,
358                     vic->vic_mapping_object);
359         }
360
361         if (vic->vic_births_object != 0) {
362                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_INDIRECT_BIRTHS,
363                     vic->vic_births_object);
364         }
365
366         if (vic->vic_prev_indirect_vdev != UINT64_MAX) {
367                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_PREV_INDIRECT_VDEV,
368                     vic->vic_prev_indirect_vdev);
369         }
370
371         if (vd->vdev_crtxg)
372                 fnvlist_add_uint64(nv, ZPOOL_CONFIG_CREATE_TXG, vd->vdev_crtxg);
373
374         if (flags & VDEV_CONFIG_MOS) {
375                 if (vd->vdev_leaf_zap != 0) {
376                         ASSERT(vd->vdev_ops->vdev_op_leaf);
377                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_VDEV_LEAF_ZAP,
378                             vd->vdev_leaf_zap);
379                 }
380
381                 if (vd->vdev_top_zap != 0) {
382                         ASSERT(vd == vd->vdev_top);
383                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_VDEV_TOP_ZAP,
384                             vd->vdev_top_zap);
385                 }
386         }
387
388         if (getstats) {
389                 vdev_stat_t vs;
390
391                 vdev_get_stats(vd, &vs);
392                 fnvlist_add_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
393                     (uint64_t *)&vs, sizeof (vs) / sizeof (uint64_t));
394
395                 root_vdev_actions_getprogress(vd, nv);
396
397                 /*
398                  * Note: this can be called from open context
399                  * (spa_get_stats()), so we need the rwlock to prevent
400                  * the mapping from being changed by condensing.
401                  */
402                 rw_enter(&vd->vdev_indirect_rwlock, RW_READER);
403                 if (vd->vdev_indirect_mapping != NULL) {
404                         ASSERT(vd->vdev_indirect_births != NULL);
405                         vdev_indirect_mapping_t *vim =
406                             vd->vdev_indirect_mapping;
407                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_INDIRECT_SIZE,
408                             vdev_indirect_mapping_size(vim));
409                 }
410                 rw_exit(&vd->vdev_indirect_rwlock);
411                 if (vd->vdev_mg != NULL &&
412                     vd->vdev_mg->mg_fragmentation != ZFS_FRAG_INVALID) {
413                         /*
414                          * Compute approximately how much memory would be used
415                          * for the indirect mapping if this device were to
416                          * be removed.
417                          *
418                          * Note: If the frag metric is invalid, then not
419                          * enough metaslabs have been converted to have
420                          * histograms.
421                          */
422                         uint64_t seg_count = 0;
423                         uint64_t to_alloc = vd->vdev_stat.vs_alloc;
424
425                         /*
426                          * There are the same number of allocated segments
427                          * as free segments, so we will have at least one
428                          * entry per free segment.  However, small free
429                          * segments (smaller than vdev_removal_max_span)
430                          * will be combined with adjacent allocated segments
431                          * as a single mapping.
432                          */
433                         for (int i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++) {
434                                 if (1ULL << (i + 1) < vdev_removal_max_span) {
435                                         to_alloc +=
436                                             vd->vdev_mg->mg_histogram[i] <<
437                                             i + 1;
438                                 } else {
439                                         seg_count +=
440                                             vd->vdev_mg->mg_histogram[i];
441                                 }
442                         }
443
444                         /*
445                          * The maximum length of a mapping is
446                          * zfs_remove_max_segment, so we need at least one entry
447                          * per zfs_remove_max_segment of allocated data.
448                          */
449                         seg_count += to_alloc / zfs_remove_max_segment;
450
451                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_INDIRECT_SIZE,
452                             seg_count *
453                             sizeof (vdev_indirect_mapping_entry_phys_t));
454                 }
455         }
456
457         if (!vd->vdev_ops->vdev_op_leaf) {
458                 nvlist_t **child;
459                 int c, idx;
460
461                 ASSERT(!vd->vdev_ishole);
462
463                 child = kmem_alloc(vd->vdev_children * sizeof (nvlist_t *),
464                     KM_SLEEP);
465
466                 for (c = 0, idx = 0; c < vd->vdev_children; c++) {
467                         vdev_t *cvd = vd->vdev_child[c];
468
469                         /*
470                          * If we're generating an nvlist of removing
471                          * vdevs then skip over any device which is
472                          * not being removed.
473                          */
474                         if ((flags & VDEV_CONFIG_REMOVING) &&
475                             !cvd->vdev_removing)
476                                 continue;
477
478                         child[idx++] = vdev_config_generate(spa, cvd,
479                             getstats, flags);
480                 }
481
482                 if (idx) {
483                         fnvlist_add_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
484                             child, idx);
485                 }
486
487                 for (c = 0; c < idx; c++)
488                         nvlist_free(child[c]);
489
490                 kmem_free(child, vd->vdev_children * sizeof (nvlist_t *));
491
492         } else {
493                 const char *aux = NULL;
494
495                 if (vd->vdev_offline && !vd->vdev_tmpoffline)
496                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_OFFLINE, B_TRUE);
497                 if (vd->vdev_resilver_txg != 0)
498                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_RESILVER_TXG,
499                             vd->vdev_resilver_txg);
500                 if (vd->vdev_faulted)
501                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_FAULTED, B_TRUE);
502                 if (vd->vdev_degraded)
503                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_DEGRADED, B_TRUE);
504                 if (vd->vdev_removed)
505                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_REMOVED, B_TRUE);
506                 if (vd->vdev_unspare)
507                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_UNSPARE, B_TRUE);
508                 if (vd->vdev_ishole)
509                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_IS_HOLE, B_TRUE);
510
511                 switch (vd->vdev_stat.vs_aux) {
512                 case VDEV_AUX_ERR_EXCEEDED:
513                         aux = "err_exceeded";
514                         break;
515
516                 case VDEV_AUX_EXTERNAL:
517                         aux = "external";
518                         break;
519                 }
520
521                 if (aux != NULL)
522                         fnvlist_add_string(nv, ZPOOL_CONFIG_AUX_STATE, aux);
523
524                 if (vd->vdev_splitting && vd->vdev_orig_guid != 0LL) {
525                         fnvlist_add_uint64(nv, ZPOOL_CONFIG_ORIG_GUID,
526                             vd->vdev_orig_guid);
527                 }
528         }
529
530         return (nv);
531 }
532
533 /*
534  * Generate a view of the top-level vdevs.  If we currently have holes
535  * in the namespace, then generate an array which contains a list of holey
536  * vdevs.  Additionally, add the number of top-level children that currently
537  * exist.
538  */
539 void
540 vdev_top_config_generate(spa_t *spa, nvlist_t *config)
541 {
542         vdev_t *rvd = spa->spa_root_vdev;
543         uint64_t *array;
544         uint_t c, idx;
545
546         array = kmem_alloc(rvd->vdev_children * sizeof (uint64_t), KM_SLEEP);
547
548         for (c = 0, idx = 0; c < rvd->vdev_children; c++) {
549                 vdev_t *tvd = rvd->vdev_child[c];
550
551                 if (tvd->vdev_ishole) {
552                         array[idx++] = c;
553                 }
554         }
555
556         if (idx) {
557                 VERIFY(nvlist_add_uint64_array(config, ZPOOL_CONFIG_HOLE_ARRAY,
558                     array, idx) == 0);
559         }
560
561         VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VDEV_CHILDREN,
562             rvd->vdev_children) == 0);
563
564         kmem_free(array, rvd->vdev_children * sizeof (uint64_t));
565 }
566
567 /*
568  * Returns the configuration from the label of the given vdev. For vdevs
569  * which don't have a txg value stored on their label (i.e. spares/cache)
570  * or have not been completely initialized (txg = 0) just return
571  * the configuration from the first valid label we find. Otherwise,
572  * find the most up-to-date label that does not exceed the specified
573  * 'txg' value.
574  */
575 nvlist_t *
576 vdev_label_read_config(vdev_t *vd, uint64_t txg)
577 {
578         spa_t *spa = vd->vdev_spa;
579         nvlist_t *config = NULL;
580         vdev_phys_t *vp;
581         abd_t *vp_abd;
582         zio_t *zio;
583         uint64_t best_txg = 0;
584         uint64_t label_txg = 0;
585         int error = 0;
586         int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
587             ZIO_FLAG_SPECULATIVE;
588
589         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
590
591         if (!vdev_readable(vd))
592                 return (NULL);
593
594         vp_abd = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
595         vp = abd_to_buf(vp_abd);
596
597 retry:
598         for (int l = 0; l < VDEV_LABELS; l++) {
599                 nvlist_t *label = NULL;
600
601                 zio = zio_root(spa, NULL, NULL, flags);
602
603                 vdev_label_read(zio, vd, l, vp_abd,
604                     offsetof(vdev_label_t, vl_vdev_phys),
605                     sizeof (vdev_phys_t), NULL, NULL, flags);
606
607                 if (zio_wait(zio) == 0 &&
608                     nvlist_unpack(vp->vp_nvlist, sizeof (vp->vp_nvlist),
609                     &label, 0) == 0) {
610                         /*
611                          * Auxiliary vdevs won't have txg values in their
612                          * labels and newly added vdevs may not have been
613                          * completely initialized so just return the
614                          * configuration from the first valid label we
615                          * encounter.
616                          */
617                         error = nvlist_lookup_uint64(label,
618                             ZPOOL_CONFIG_POOL_TXG, &label_txg);
619                         if ((error || label_txg == 0) && !config) {
620                                 config = label;
621                                 break;
622                         } else if (label_txg <= txg && label_txg > best_txg) {
623                                 best_txg = label_txg;
624                                 nvlist_free(config);
625                                 config = fnvlist_dup(label);
626                         }
627                 }
628
629                 if (label != NULL) {
630                         nvlist_free(label);
631                         label = NULL;
632                 }
633         }
634
635         if (config == NULL && !(flags & ZIO_FLAG_TRYHARD)) {
636                 flags |= ZIO_FLAG_TRYHARD;
637                 goto retry;
638         }
639
640         /*
641          * We found a valid label but it didn't pass txg restrictions.
642          */
643         if (config == NULL && label_txg != 0) {
644                 vdev_dbgmsg(vd, "label discarded as txg is too large "
645                     "(%llu > %llu)", (u_longlong_t)label_txg,
646                     (u_longlong_t)txg);
647         }
648
649         abd_free(vp_abd);
650
651         return (config);
652 }
653
654 /*
655  * Determine if a device is in use.  The 'spare_guid' parameter will be filled
656  * in with the device guid if this spare is active elsewhere on the system.
657  */
658 static boolean_t
659 vdev_inuse(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason,
660     uint64_t *spare_guid, uint64_t *l2cache_guid)
661 {
662         spa_t *spa = vd->vdev_spa;
663         uint64_t state, pool_guid, device_guid, txg, spare_pool;
664         uint64_t vdtxg = 0;
665         nvlist_t *label;
666
667         if (spare_guid)
668                 *spare_guid = 0ULL;
669         if (l2cache_guid)
670                 *l2cache_guid = 0ULL;
671
672         /*
673          * Read the label, if any, and perform some basic sanity checks.
674          */
675         if ((label = vdev_label_read_config(vd, -1ULL)) == NULL)
676                 return (B_FALSE);
677
678         (void) nvlist_lookup_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
679             &vdtxg);
680
681         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
682             &state) != 0 ||
683             nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
684             &device_guid) != 0) {
685                 nvlist_free(label);
686                 return (B_FALSE);
687         }
688
689         if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
690             (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID,
691             &pool_guid) != 0 ||
692             nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
693             &txg) != 0)) {
694                 nvlist_free(label);
695                 return (B_FALSE);
696         }
697
698         nvlist_free(label);
699
700         /*
701          * Check to see if this device indeed belongs to the pool it claims to
702          * be a part of.  The only way this is allowed is if the device is a hot
703          * spare (which we check for later on).
704          */
705         if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
706             !spa_guid_exists(pool_guid, device_guid) &&
707             !spa_spare_exists(device_guid, NULL, NULL) &&
708             !spa_l2cache_exists(device_guid, NULL))
709                 return (B_FALSE);
710
711         /*
712          * If the transaction group is zero, then this an initialized (but
713          * unused) label.  This is only an error if the create transaction
714          * on-disk is the same as the one we're using now, in which case the
715          * user has attempted to add the same vdev multiple times in the same
716          * transaction.
717          */
718         if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
719             txg == 0 && vdtxg == crtxg)
720                 return (B_TRUE);
721
722         /*
723          * Check to see if this is a spare device.  We do an explicit check for
724          * spa_has_spare() here because it may be on our pending list of spares
725          * to add.  We also check if it is an l2cache device.
726          */
727         if (spa_spare_exists(device_guid, &spare_pool, NULL) ||
728             spa_has_spare(spa, device_guid)) {
729                 if (spare_guid)
730                         *spare_guid = device_guid;
731
732                 switch (reason) {
733                 case VDEV_LABEL_CREATE:
734                 case VDEV_LABEL_L2CACHE:
735                         return (B_TRUE);
736
737                 case VDEV_LABEL_REPLACE:
738                         return (!spa_has_spare(spa, device_guid) ||
739                             spare_pool != 0ULL);
740
741                 case VDEV_LABEL_SPARE:
742                         return (spa_has_spare(spa, device_guid));
743                 }
744         }
745
746         /*
747          * Check to see if this is an l2cache device.
748          */
749         if (spa_l2cache_exists(device_guid, NULL))
750                 return (B_TRUE);
751
752         /*
753          * We can't rely on a pool's state if it's been imported
754          * read-only.  Instead we look to see if the pools is marked
755          * read-only in the namespace and set the state to active.
756          */
757         if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
758             (spa = spa_by_guid(pool_guid, device_guid)) != NULL &&
759             spa_mode(spa) == FREAD)
760                 state = POOL_STATE_ACTIVE;
761
762         /*
763          * If the device is marked ACTIVE, then this device is in use by another
764          * pool on the system.
765          */
766         return (state == POOL_STATE_ACTIVE);
767 }
768
769 /*
770  * Initialize a vdev label.  We check to make sure each leaf device is not in
771  * use, and writable.  We put down an initial label which we will later
772  * overwrite with a complete label.  Note that it's important to do this
773  * sequentially, not in parallel, so that we catch cases of multiple use of the
774  * same leaf vdev in the vdev we're creating -- e.g. mirroring a disk with
775  * itself.
776  */
777 int
778 vdev_label_init(vdev_t *vd, uint64_t crtxg, vdev_labeltype_t reason)
779 {
780         spa_t *spa = vd->vdev_spa;
781         nvlist_t *label;
782         vdev_phys_t *vp;
783         abd_t *vp_abd;
784         abd_t *bootenv;
785         uberblock_t *ub;
786         abd_t *ub_abd;
787         zio_t *zio;
788         char *buf;
789         size_t buflen;
790         int error;
791         uint64_t spare_guid, l2cache_guid;
792         int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL;
793
794         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
795
796         for (int c = 0; c < vd->vdev_children; c++)
797                 if ((error = vdev_label_init(vd->vdev_child[c],
798                     crtxg, reason)) != 0)
799                         return (error);
800
801         /* Track the creation time for this vdev */
802         vd->vdev_crtxg = crtxg;
803
804         if (!vd->vdev_ops->vdev_op_leaf || !spa_writeable(spa))
805                 return (0);
806
807         /*
808          * Dead vdevs cannot be initialized.
809          */
810         if (vdev_is_dead(vd))
811                 return (SET_ERROR(EIO));
812
813         /*
814          * Determine if the vdev is in use.
815          */
816         if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_SPLIT &&
817             vdev_inuse(vd, crtxg, reason, &spare_guid, &l2cache_guid))
818                 return (SET_ERROR(EBUSY));
819
820         /*
821          * If this is a request to add or replace a spare or l2cache device
822          * that is in use elsewhere on the system, then we must update the
823          * guid (which was initialized to a random value) to reflect the
824          * actual GUID (which is shared between multiple pools).
825          */
826         if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_L2CACHE &&
827             spare_guid != 0ULL) {
828                 uint64_t guid_delta = spare_guid - vd->vdev_guid;
829
830                 vd->vdev_guid += guid_delta;
831
832                 for (vdev_t *pvd = vd; pvd != NULL; pvd = pvd->vdev_parent)
833                         pvd->vdev_guid_sum += guid_delta;
834
835                 /*
836                  * If this is a replacement, then we want to fallthrough to the
837                  * rest of the code.  If we're adding a spare, then it's already
838                  * labeled appropriately and we can just return.
839                  */
840                 if (reason == VDEV_LABEL_SPARE)
841                         return (0);
842                 ASSERT(reason == VDEV_LABEL_REPLACE ||
843                     reason == VDEV_LABEL_SPLIT);
844         }
845
846         if (reason != VDEV_LABEL_REMOVE && reason != VDEV_LABEL_SPARE &&
847             l2cache_guid != 0ULL) {
848                 uint64_t guid_delta = l2cache_guid - vd->vdev_guid;
849
850                 vd->vdev_guid += guid_delta;
851
852                 for (vdev_t *pvd = vd; pvd != NULL; pvd = pvd->vdev_parent)
853                         pvd->vdev_guid_sum += guid_delta;
854
855                 /*
856                  * If this is a replacement, then we want to fallthrough to the
857                  * rest of the code.  If we're adding an l2cache, then it's
858                  * already labeled appropriately and we can just return.
859                  */
860                 if (reason == VDEV_LABEL_L2CACHE)
861                         return (0);
862                 ASSERT(reason == VDEV_LABEL_REPLACE);
863         }
864
865         /*
866          * TRIM the whole thing, excluding the blank space and boot header
867          * as specified by ZFS On-Disk Specification (section 1.3), so that
868          * we start with a clean slate.
869          * It's just an optimization, so we don't care if it fails.
870          * Don't TRIM if removing so that we don't interfere with zpool
871          * disaster recovery.
872          */
873         if (zfs_trim_enabled && vdev_trim_on_init && !vd->vdev_notrim && 
874             (reason == VDEV_LABEL_CREATE || reason == VDEV_LABEL_SPARE ||
875             reason == VDEV_LABEL_L2CACHE))
876                 zio_wait(zio_trim(NULL, spa, vd, VDEV_SKIP_SIZE,
877                     vd->vdev_psize - VDEV_SKIP_SIZE));
878
879         /*
880          * Initialize its label.
881          */
882         vp_abd = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
883         abd_zero(vp_abd, sizeof (vdev_phys_t));
884         vp = abd_to_buf(vp_abd);
885
886         /*
887          * Generate a label describing the pool and our top-level vdev.
888          * We mark it as being from txg 0 to indicate that it's not
889          * really part of an active pool just yet.  The labels will
890          * be written again with a meaningful txg by spa_sync().
891          */
892         if (reason == VDEV_LABEL_SPARE ||
893             (reason == VDEV_LABEL_REMOVE && vd->vdev_isspare)) {
894                 /*
895                  * For inactive hot spares, we generate a special label that
896                  * identifies as a mutually shared hot spare.  We write the
897                  * label if we are adding a hot spare, or if we are removing an
898                  * active hot spare (in which case we want to revert the
899                  * labels).
900                  */
901                 VERIFY(nvlist_alloc(&label, NV_UNIQUE_NAME, KM_SLEEP) == 0);
902
903                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_VERSION,
904                     spa_version(spa)) == 0);
905                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_POOL_STATE,
906                     POOL_STATE_SPARE) == 0);
907                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_GUID,
908                     vd->vdev_guid) == 0);
909         } else if (reason == VDEV_LABEL_L2CACHE ||
910             (reason == VDEV_LABEL_REMOVE && vd->vdev_isl2cache)) {
911                 /*
912                  * For level 2 ARC devices, add a special label.
913                  */
914                 VERIFY(nvlist_alloc(&label, NV_UNIQUE_NAME, KM_SLEEP) == 0);
915
916                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_VERSION,
917                     spa_version(spa)) == 0);
918                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_POOL_STATE,
919                     POOL_STATE_L2CACHE) == 0);
920                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_GUID,
921                     vd->vdev_guid) == 0);
922         } else {
923                 uint64_t txg = 0ULL;
924
925                 if (reason == VDEV_LABEL_SPLIT)
926                         txg = spa->spa_uberblock.ub_txg;
927                 label = spa_config_generate(spa, vd, txg, B_FALSE);
928
929                 /*
930                  * Add our creation time.  This allows us to detect multiple
931                  * vdev uses as described above, and automatically expires if we
932                  * fail.
933                  */
934                 VERIFY(nvlist_add_uint64(label, ZPOOL_CONFIG_CREATE_TXG,
935                     crtxg) == 0);
936         }
937
938         buf = vp->vp_nvlist;
939         buflen = sizeof (vp->vp_nvlist);
940
941         error = nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP);
942         if (error != 0) {
943                 nvlist_free(label);
944                 abd_free(vp_abd);
945                 /* EFAULT means nvlist_pack ran out of room */
946                 return (error == EFAULT ? ENAMETOOLONG : EINVAL);
947         }
948
949         /*
950          * Initialize uberblock template.
951          */
952         ub_abd = abd_alloc_linear(VDEV_UBERBLOCK_RING, B_TRUE);
953         abd_zero(ub_abd, VDEV_UBERBLOCK_RING);
954         abd_copy_from_buf(ub_abd, &spa->spa_uberblock, sizeof (uberblock_t));
955         ub = abd_to_buf(ub_abd);
956         ub->ub_txg = 0;
957
958         /* Initialize the 2nd padding area. */
959         bootenv = abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE);
960         abd_zero(bootenv, VDEV_PAD_SIZE);
961
962         /*
963          * Write everything in parallel.
964          */
965 retry:
966         zio = zio_root(spa, NULL, NULL, flags);
967
968         for (int l = 0; l < VDEV_LABELS; l++) {
969
970                 vdev_label_write(zio, vd, l, vp_abd,
971                     offsetof(vdev_label_t, vl_vdev_phys),
972                     sizeof (vdev_phys_t), NULL, NULL, flags);
973
974                 /*
975                  * Skip the 1st padding area.
976                  * Zero out the 2nd padding area where it might have
977                  * left over data from previous filesystem format.
978                  */
979                 vdev_label_write(zio, vd, l, bootenv,
980                     offsetof(vdev_label_t, vl_be),
981                     VDEV_PAD_SIZE, NULL, NULL, flags);
982
983                 vdev_label_write(zio, vd, l, ub_abd,
984                     offsetof(vdev_label_t, vl_uberblock),
985                     VDEV_UBERBLOCK_RING, NULL, NULL, flags);
986         }
987
988         error = zio_wait(zio);
989
990         if (error != 0 && !(flags & ZIO_FLAG_TRYHARD)) {
991                 flags |= ZIO_FLAG_TRYHARD;
992                 goto retry;
993         }
994
995         nvlist_free(label);
996         abd_free(bootenv);
997         abd_free(ub_abd);
998         abd_free(vp_abd);
999
1000         /*
1001          * If this vdev hasn't been previously identified as a spare, then we
1002          * mark it as such only if a) we are labeling it as a spare, or b) it
1003          * exists as a spare elsewhere in the system.  Do the same for
1004          * level 2 ARC devices.
1005          */
1006         if (error == 0 && !vd->vdev_isspare &&
1007             (reason == VDEV_LABEL_SPARE ||
1008             spa_spare_exists(vd->vdev_guid, NULL, NULL)))
1009                 spa_spare_add(vd);
1010
1011         if (error == 0 && !vd->vdev_isl2cache &&
1012             (reason == VDEV_LABEL_L2CACHE ||
1013             spa_l2cache_exists(vd->vdev_guid, NULL)))
1014                 spa_l2cache_add(vd);
1015
1016         return (error);
1017 }
1018
1019 /*
1020  * Done callback for vdev_label_read_bootenv_impl. If this is the first
1021  * callback to finish, store our abd in the callback pointer. Otherwise, we
1022  * just free our abd and return.
1023  */
1024 static void
1025 vdev_label_read_bootenv_done(zio_t *zio)
1026 {
1027         zio_t *rio = zio->io_private;
1028         abd_t **cbp = rio->io_private;
1029
1030         ASSERT3U(zio->io_size, ==, VDEV_PAD_SIZE);
1031
1032         if (zio->io_error == 0) {
1033                 mutex_enter(&rio->io_lock);
1034                 if (*cbp == NULL) {
1035                         /* Will free this buffer in vdev_label_read_bootenv. */
1036                         *cbp = zio->io_abd;
1037                 } else {
1038                         abd_free(zio->io_abd);
1039                 }
1040                 mutex_exit(&rio->io_lock);
1041         } else {
1042                 abd_free(zio->io_abd);
1043         }
1044 }
1045
1046 static void
1047 vdev_label_read_bootenv_impl(zio_t *zio, vdev_t *vd, int flags)
1048 {
1049         for (int c = 0; c < vd->vdev_children; c++)
1050                 vdev_label_read_bootenv_impl(zio, vd->vdev_child[c], flags);
1051
1052         /*
1053          * We just use the first label that has a correct checksum; the
1054          * bootloader should have rewritten them all to be the same on boot,
1055          * and any changes we made since boot have been the same across all
1056          * labels.
1057          *
1058          * While grub supports writing to all four labels, other bootloaders
1059          * don't, so we only use the first two labels to store boot
1060          * information.
1061          */
1062         if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd)) {
1063                 for (int l = 0; l < VDEV_LABELS / 2; l++) {
1064                         vdev_label_read(zio, vd, l,
1065                             abd_alloc_linear(VDEV_PAD_SIZE, B_FALSE),
1066                             offsetof(vdev_label_t, vl_be), VDEV_PAD_SIZE,
1067                             vdev_label_read_bootenv_done, zio, flags);
1068                 }
1069         }
1070 }
1071
1072 int
1073 vdev_label_read_bootenv(vdev_t *rvd, nvlist_t *command)
1074 {
1075         spa_t *spa = rvd->vdev_spa;
1076         abd_t *abd = NULL;
1077         int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
1078             ZIO_FLAG_SPECULATIVE | ZIO_FLAG_TRYHARD;
1079
1080         ASSERT(command);
1081         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1082
1083         zio_t *zio = zio_root(spa, NULL, &abd, flags);
1084         vdev_label_read_bootenv_impl(zio, rvd, flags);
1085         int err = zio_wait(zio);
1086
1087         if (abd != NULL) {
1088                 vdev_boot_envblock_t *vbe = abd_to_buf(abd);
1089                 if (vbe->vbe_version != VB_RAW) {
1090                         abd_free(abd);
1091                         return (SET_ERROR(ENOTSUP));
1092                 }
1093                 vbe->vbe_bootenv[sizeof (vbe->vbe_bootenv) - 1] = '\0';
1094                 fnvlist_add_string(command, "envmap", vbe->vbe_bootenv);
1095                 /* abd was allocated in vdev_label_read_bootenv_impl() */
1096                 abd_free(abd);
1097                 /* If we managed to read any successfully, return success. */
1098                 return (0);
1099         }
1100         return (err);
1101 }
1102
1103 int
1104 vdev_label_write_bootenv(vdev_t *vd, char *envmap)
1105 {
1106         zio_t *zio;
1107         spa_t *spa = vd->vdev_spa;
1108         vdev_boot_envblock_t *bootenv;
1109         int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL;
1110         int error = ENXIO;
1111
1112         if (strlen(envmap) >= sizeof (bootenv->vbe_bootenv)) {
1113                 return (SET_ERROR(E2BIG));
1114         }
1115
1116         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1117
1118         for (int c = 0; c < vd->vdev_children; c++) {
1119                 int child_err = vdev_label_write_bootenv(vd->vdev_child[c],
1120                     envmap);
1121                 /*
1122                  * As long as any of the disks managed to write all of their
1123                  * labels successfully, return success.
1124                  */
1125                 if (child_err == 0)
1126                         error = child_err;
1127         }
1128
1129         if (!vd->vdev_ops->vdev_op_leaf || vdev_is_dead(vd) ||
1130             !vdev_writeable(vd)) {
1131                 return (error);
1132         }
1133         ASSERT3U(sizeof (*bootenv), ==, VDEV_PAD_SIZE);
1134         abd_t *abd = abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE);
1135         abd_zero(abd, VDEV_PAD_SIZE);
1136         bootenv = abd_borrow_buf_copy(abd, VDEV_PAD_SIZE);
1137
1138         char *buf = bootenv->vbe_bootenv;
1139         (void) strlcpy(buf, envmap, sizeof (bootenv->vbe_bootenv));
1140         bootenv->vbe_version = VB_RAW;
1141         abd_return_buf_copy(abd, bootenv, VDEV_PAD_SIZE);
1142
1143 retry:
1144         zio = zio_root(spa, NULL, NULL, flags);
1145         for (int l = 0; l < VDEV_LABELS / 2; l++) {
1146                 vdev_label_write(zio, vd, l, abd,
1147                     offsetof(vdev_label_t, vl_be),
1148                     VDEV_PAD_SIZE, NULL, NULL, flags);
1149         }
1150
1151         error = zio_wait(zio);
1152         if (error != 0 && !(flags & ZIO_FLAG_TRYHARD)) {
1153                 flags |= ZIO_FLAG_TRYHARD;
1154                 goto retry;
1155         }
1156
1157         abd_free(abd);
1158         return (error);
1159 }
1160
1161 int
1162 vdev_label_write_pad2(vdev_t *vd, const char *buf, size_t size)
1163 {
1164         spa_t *spa = vd->vdev_spa;
1165         zio_t *zio;
1166         abd_t *pad2;
1167         int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL;
1168         int error;
1169
1170         if (size > VDEV_PAD_SIZE)
1171                 return (EINVAL);
1172
1173         if (!vd->vdev_ops->vdev_op_leaf)
1174                 return (ENODEV);
1175         if (vdev_is_dead(vd))
1176                 return (ENXIO);
1177
1178         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1179
1180         pad2 = abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE);
1181         abd_zero(pad2, VDEV_PAD_SIZE);
1182         abd_copy_from_buf(pad2, buf, size);
1183
1184 retry:
1185         zio = zio_root(spa, NULL, NULL, flags);
1186         vdev_label_write(zio, vd, 0, pad2,
1187             offsetof(vdev_label_t, vl_be),
1188             VDEV_PAD_SIZE, NULL, NULL, flags);
1189         error = zio_wait(zio);
1190         if (error != 0 && !(flags & ZIO_FLAG_TRYHARD)) {
1191                 flags |= ZIO_FLAG_TRYHARD;
1192                 goto retry;
1193         }
1194
1195         abd_free(pad2);
1196         return (error);
1197 }
1198
1199 /*
1200  * ==========================================================================
1201  * uberblock load/sync
1202  * ==========================================================================
1203  */
1204
1205 /*
1206  * Consider the following situation: txg is safely synced to disk.  We've
1207  * written the first uberblock for txg + 1, and then we lose power.  When we
1208  * come back up, we fail to see the uberblock for txg + 1 because, say,
1209  * it was on a mirrored device and the replica to which we wrote txg + 1
1210  * is now offline.  If we then make some changes and sync txg + 1, and then
1211  * the missing replica comes back, then for a few seconds we'll have two
1212  * conflicting uberblocks on disk with the same txg.  The solution is simple:
1213  * among uberblocks with equal txg, choose the one with the latest timestamp.
1214  */
1215 static int
1216 vdev_uberblock_compare(const uberblock_t *ub1, const uberblock_t *ub2)
1217 {
1218         int cmp = AVL_CMP(ub1->ub_txg, ub2->ub_txg);
1219
1220         if (likely(cmp))
1221                 return (cmp);
1222
1223         cmp = AVL_CMP(ub1->ub_timestamp, ub2->ub_timestamp);
1224         if (likely(cmp))
1225                 return (cmp);
1226
1227         /*
1228          * If MMP_VALID(ub) && MMP_SEQ_VALID(ub) then the host has an MMP-aware
1229          * ZFS, e.g. zfsonlinux >= 0.7.
1230          *
1231          * If one ub has MMP and the other does not, they were written by
1232          * different hosts, which matters for MMP.  So we treat no MMP/no SEQ as
1233          * a 0 value.
1234          *
1235          * Since timestamp and txg are the same if we get this far, either is
1236          * acceptable for importing the pool.
1237          */
1238         unsigned int seq1 = 0;
1239         unsigned int seq2 = 0;
1240
1241         if (MMP_VALID(ub1) && MMP_SEQ_VALID(ub1))
1242                 seq1 = MMP_SEQ(ub1);
1243
1244         if (MMP_VALID(ub2) && MMP_SEQ_VALID(ub2))
1245                 seq2 = MMP_SEQ(ub2);
1246
1247         return (AVL_CMP(seq1, seq2));
1248 }
1249
1250 struct ubl_cbdata {
1251         uberblock_t     *ubl_ubbest;    /* Best uberblock */
1252         vdev_t          *ubl_vd;        /* vdev associated with the above */
1253 };
1254
1255 static void
1256 vdev_uberblock_load_done(zio_t *zio)
1257 {
1258         vdev_t *vd = zio->io_vd;
1259         spa_t *spa = zio->io_spa;
1260         zio_t *rio = zio->io_private;
1261         uberblock_t *ub = abd_to_buf(zio->io_abd);
1262         struct ubl_cbdata *cbp = rio->io_private;
1263
1264         ASSERT3U(zio->io_size, ==, VDEV_UBERBLOCK_SIZE(vd));
1265
1266         if (zio->io_error == 0 && uberblock_verify(ub) == 0) {
1267                 mutex_enter(&rio->io_lock);
1268                 if (ub->ub_txg <= spa->spa_load_max_txg &&
1269                     vdev_uberblock_compare(ub, cbp->ubl_ubbest) > 0) {
1270                         /*
1271                          * Keep track of the vdev in which this uberblock
1272                          * was found. We will use this information later
1273                          * to obtain the config nvlist associated with
1274                          * this uberblock.
1275                          */
1276                         *cbp->ubl_ubbest = *ub;
1277                         cbp->ubl_vd = vd;
1278                 }
1279                 mutex_exit(&rio->io_lock);
1280         }
1281
1282         abd_free(zio->io_abd);
1283 }
1284
1285 static void
1286 vdev_uberblock_load_impl(zio_t *zio, vdev_t *vd, int flags,
1287     struct ubl_cbdata *cbp)
1288 {
1289         for (int c = 0; c < vd->vdev_children; c++)
1290                 vdev_uberblock_load_impl(zio, vd->vdev_child[c], flags, cbp);
1291
1292         if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd)) {
1293                 for (int l = 0; l < VDEV_LABELS; l++) {
1294                         for (int n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
1295                                 vdev_label_read(zio, vd, l,
1296                                     abd_alloc_linear(VDEV_UBERBLOCK_SIZE(vd),
1297                                     B_TRUE), VDEV_UBERBLOCK_OFFSET(vd, n),
1298                                     VDEV_UBERBLOCK_SIZE(vd),
1299                                     vdev_uberblock_load_done, zio, flags);
1300                         }
1301                 }
1302         }
1303 }
1304
1305 /*
1306  * Reads the 'best' uberblock from disk along with its associated
1307  * configuration. First, we read the uberblock array of each label of each
1308  * vdev, keeping track of the uberblock with the highest txg in each array.
1309  * Then, we read the configuration from the same vdev as the best uberblock.
1310  */
1311 void
1312 vdev_uberblock_load(vdev_t *rvd, uberblock_t *ub, nvlist_t **config)
1313 {
1314         zio_t *zio;
1315         spa_t *spa = rvd->vdev_spa;
1316         struct ubl_cbdata cb;
1317         int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL |
1318             ZIO_FLAG_SPECULATIVE | ZIO_FLAG_TRYHARD;
1319
1320         ASSERT(ub);
1321         ASSERT(config);
1322
1323         bzero(ub, sizeof (uberblock_t));
1324         *config = NULL;
1325
1326         cb.ubl_ubbest = ub;
1327         cb.ubl_vd = NULL;
1328
1329         spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1330         zio = zio_root(spa, NULL, &cb, flags);
1331         vdev_uberblock_load_impl(zio, rvd, flags, &cb);
1332         (void) zio_wait(zio);
1333
1334         /*
1335          * It's possible that the best uberblock was discovered on a label
1336          * that has a configuration which was written in a future txg.
1337          * Search all labels on this vdev to find the configuration that
1338          * matches the txg for our uberblock.
1339          */
1340         if (cb.ubl_vd != NULL) {
1341                 vdev_dbgmsg(cb.ubl_vd, "best uberblock found for spa %s. "
1342                     "txg %llu", spa->spa_name, (u_longlong_t)ub->ub_txg);
1343
1344                 *config = vdev_label_read_config(cb.ubl_vd, ub->ub_txg);
1345                 if (*config == NULL && spa->spa_extreme_rewind) {
1346                         vdev_dbgmsg(cb.ubl_vd, "failed to read label config. "
1347                             "Trying again without txg restrictions.");
1348                         *config = vdev_label_read_config(cb.ubl_vd, UINT64_MAX);
1349                 }
1350                 if (*config == NULL) {
1351                         vdev_dbgmsg(cb.ubl_vd, "failed to read label config");
1352                 }
1353         }
1354         spa_config_exit(spa, SCL_ALL, FTAG);
1355 }
1356
1357 /*
1358  * On success, increment root zio's count of good writes.
1359  * We only get credit for writes to known-visible vdevs; see spa_vdev_add().
1360  */
1361 static void
1362 vdev_uberblock_sync_done(zio_t *zio)
1363 {
1364         uint64_t *good_writes = zio->io_private;
1365
1366         if (zio->io_error == 0 && zio->io_vd->vdev_top->vdev_ms_array != 0)
1367                 atomic_inc_64(good_writes);
1368 }
1369
1370 /*
1371  * Write the uberblock to all labels of all leaves of the specified vdev.
1372  */
1373 static void
1374 vdev_uberblock_sync(zio_t *zio, uint64_t *good_writes,
1375     uberblock_t *ub, vdev_t *vd, int flags)
1376 {
1377         for (uint64_t c = 0; c < vd->vdev_children; c++) {
1378                 vdev_uberblock_sync(zio, good_writes,
1379                     ub, vd->vdev_child[c], flags);
1380         }
1381
1382         if (!vd->vdev_ops->vdev_op_leaf)
1383                 return;
1384
1385         if (!vdev_writeable(vd))
1386                 return;
1387
1388         int m = spa_multihost(vd->vdev_spa) ? MMP_BLOCKS_PER_LABEL : 0;
1389         int n = ub->ub_txg % (VDEV_UBERBLOCK_COUNT(vd) - m);
1390
1391         /* Copy the uberblock_t into the ABD */
1392         abd_t *ub_abd = abd_alloc_for_io(VDEV_UBERBLOCK_SIZE(vd), B_TRUE);
1393         abd_zero(ub_abd, VDEV_UBERBLOCK_SIZE(vd));
1394         abd_copy_from_buf(ub_abd, ub, sizeof (uberblock_t));
1395
1396         for (int l = 0; l < VDEV_LABELS; l++)
1397                 vdev_label_write(zio, vd, l, ub_abd,
1398                     VDEV_UBERBLOCK_OFFSET(vd, n), VDEV_UBERBLOCK_SIZE(vd),
1399                     vdev_uberblock_sync_done, good_writes,
1400                     flags | ZIO_FLAG_DONT_PROPAGATE);
1401
1402         abd_free(ub_abd);
1403 }
1404
1405 /* Sync the uberblocks to all vdevs in svd[] */
1406 int
1407 vdev_uberblock_sync_list(vdev_t **svd, int svdcount, uberblock_t *ub, int flags)
1408 {
1409         spa_t *spa = svd[0]->vdev_spa;
1410         zio_t *zio;
1411         uint64_t good_writes = 0;
1412
1413         zio = zio_root(spa, NULL, NULL, flags);
1414
1415         for (int v = 0; v < svdcount; v++)
1416                 vdev_uberblock_sync(zio, &good_writes, ub, svd[v], flags);
1417
1418         (void) zio_wait(zio);
1419
1420         /*
1421          * Flush the uberblocks to disk.  This ensures that the odd labels
1422          * are no longer needed (because the new uberblocks and the even
1423          * labels are safely on disk), so it is safe to overwrite them.
1424          */
1425         zio = zio_root(spa, NULL, NULL, flags);
1426
1427         for (int v = 0; v < svdcount; v++) {
1428                 if (vdev_writeable(svd[v])) {
1429                         zio_flush(zio, svd[v]);
1430                 }
1431         }
1432
1433         (void) zio_wait(zio);
1434
1435         return (good_writes >= 1 ? 0 : EIO);
1436 }
1437
1438 /*
1439  * On success, increment the count of good writes for our top-level vdev.
1440  */
1441 static void
1442 vdev_label_sync_done(zio_t *zio)
1443 {
1444         uint64_t *good_writes = zio->io_private;
1445
1446         if (zio->io_error == 0)
1447                 atomic_inc_64(good_writes);
1448 }
1449
1450 /*
1451  * If there weren't enough good writes, indicate failure to the parent.
1452  */
1453 static void
1454 vdev_label_sync_top_done(zio_t *zio)
1455 {
1456         uint64_t *good_writes = zio->io_private;
1457
1458         if (*good_writes == 0)
1459                 zio->io_error = SET_ERROR(EIO);
1460
1461         kmem_free(good_writes, sizeof (uint64_t));
1462 }
1463
1464 /*
1465  * We ignore errors for log and cache devices, simply free the private data.
1466  */
1467 static void
1468 vdev_label_sync_ignore_done(zio_t *zio)
1469 {
1470         kmem_free(zio->io_private, sizeof (uint64_t));
1471 }
1472
1473 /*
1474  * Write all even or odd labels to all leaves of the specified vdev.
1475  */
1476 static void
1477 vdev_label_sync(zio_t *zio, uint64_t *good_writes,
1478     vdev_t *vd, int l, uint64_t txg, int flags)
1479 {
1480         nvlist_t *label;
1481         vdev_phys_t *vp;
1482         abd_t *vp_abd;
1483         char *buf;
1484         size_t buflen;
1485
1486         for (int c = 0; c < vd->vdev_children; c++) {
1487                 vdev_label_sync(zio, good_writes,
1488                     vd->vdev_child[c], l, txg, flags);
1489         }
1490
1491         if (!vd->vdev_ops->vdev_op_leaf)
1492                 return;
1493
1494         if (!vdev_writeable(vd))
1495                 return;
1496
1497         /*
1498          * Generate a label describing the top-level config to which we belong.
1499          */
1500         label = spa_config_generate(vd->vdev_spa, vd, txg, B_FALSE);
1501
1502         vp_abd = abd_alloc_linear(sizeof (vdev_phys_t), B_TRUE);
1503         abd_zero(vp_abd, sizeof (vdev_phys_t));
1504         vp = abd_to_buf(vp_abd);
1505
1506         buf = vp->vp_nvlist;
1507         buflen = sizeof (vp->vp_nvlist);
1508
1509         if (nvlist_pack(label, &buf, &buflen, NV_ENCODE_XDR, KM_SLEEP) == 0) {
1510                 for (; l < VDEV_LABELS; l += 2) {
1511                         vdev_label_write(zio, vd, l, vp_abd,
1512                             offsetof(vdev_label_t, vl_vdev_phys),
1513                             sizeof (vdev_phys_t),
1514                             vdev_label_sync_done, good_writes,
1515                             flags | ZIO_FLAG_DONT_PROPAGATE);
1516                 }
1517         }
1518
1519         abd_free(vp_abd);
1520         nvlist_free(label);
1521 }
1522
1523 int
1524 vdev_label_sync_list(spa_t *spa, int l, uint64_t txg, int flags)
1525 {
1526         list_t *dl = &spa->spa_config_dirty_list;
1527         vdev_t *vd;
1528         zio_t *zio;
1529         int error;
1530
1531         /*
1532          * Write the new labels to disk.
1533          */
1534         zio = zio_root(spa, NULL, NULL, flags);
1535
1536         for (vd = list_head(dl); vd != NULL; vd = list_next(dl, vd)) {
1537                 uint64_t *good_writes = kmem_zalloc(sizeof (uint64_t),
1538                     KM_SLEEP);
1539
1540                 ASSERT(!vd->vdev_ishole);
1541
1542                 zio_t *vio = zio_null(zio, spa, NULL,
1543                     (vd->vdev_islog || vd->vdev_aux != NULL) ?
1544                     vdev_label_sync_ignore_done : vdev_label_sync_top_done,
1545                     good_writes, flags);
1546                 vdev_label_sync(vio, good_writes, vd, l, txg, flags);
1547                 zio_nowait(vio);
1548         }
1549
1550         error = zio_wait(zio);
1551
1552         /*
1553          * Flush the new labels to disk.
1554          */
1555         zio = zio_root(spa, NULL, NULL, flags);
1556
1557         for (vd = list_head(dl); vd != NULL; vd = list_next(dl, vd))
1558                 zio_flush(zio, vd);
1559
1560         (void) zio_wait(zio);
1561
1562         return (error);
1563 }
1564
1565 /*
1566  * Sync the uberblock and any changes to the vdev configuration.
1567  *
1568  * The order of operations is carefully crafted to ensure that
1569  * if the system panics or loses power at any time, the state on disk
1570  * is still transactionally consistent.  The in-line comments below
1571  * describe the failure semantics at each stage.
1572  *
1573  * Moreover, vdev_config_sync() is designed to be idempotent: if it fails
1574  * at any time, you can just call it again, and it will resume its work.
1575  */
1576 int
1577 vdev_config_sync(vdev_t **svd, int svdcount, uint64_t txg)
1578 {
1579         spa_t *spa = svd[0]->vdev_spa;
1580         uberblock_t *ub = &spa->spa_uberblock;
1581         int error = 0;
1582         int flags = ZIO_FLAG_CONFIG_WRITER | ZIO_FLAG_CANFAIL;
1583
1584         ASSERT(svdcount != 0);
1585 retry:
1586         /*
1587          * Normally, we don't want to try too hard to write every label and
1588          * uberblock.  If there is a flaky disk, we don't want the rest of the
1589          * sync process to block while we retry.  But if we can't write a
1590          * single label out, we should retry with ZIO_FLAG_TRYHARD before
1591          * bailing out and declaring the pool faulted.
1592          */
1593         if (error != 0) {
1594                 if ((flags & ZIO_FLAG_TRYHARD) != 0)
1595                         return (error);
1596                 flags |= ZIO_FLAG_TRYHARD;
1597         }
1598
1599         ASSERT(ub->ub_txg <= txg);
1600
1601         /*
1602          * If this isn't a resync due to I/O errors,
1603          * and nothing changed in this transaction group,
1604          * and the vdev configuration hasn't changed,
1605          * then there's nothing to do.
1606          */
1607         if (ub->ub_txg < txg) {
1608                 boolean_t changed = uberblock_update(ub, spa->spa_root_vdev,
1609                     txg, spa->spa_mmp.mmp_delay);
1610
1611                 if (!changed && list_is_empty(&spa->spa_config_dirty_list))
1612                         return (0);
1613         }
1614
1615         if (txg > spa_freeze_txg(spa))
1616                 return (0);
1617
1618         ASSERT(txg <= spa->spa_final_txg);
1619
1620         /*
1621          * Flush the write cache of every disk that's been written to
1622          * in this transaction group.  This ensures that all blocks
1623          * written in this txg will be committed to stable storage
1624          * before any uberblock that references them.
1625          */
1626         zio_t *zio = zio_root(spa, NULL, NULL, flags);
1627
1628         for (vdev_t *vd =
1629             txg_list_head(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)); vd != NULL;
1630             vd = txg_list_next(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg)))
1631                 zio_flush(zio, vd);
1632
1633         (void) zio_wait(zio);
1634
1635         /*
1636          * Sync out the even labels (L0, L2) for every dirty vdev.  If the
1637          * system dies in the middle of this process, that's OK: all of the
1638          * even labels that made it to disk will be newer than any uberblock,
1639          * and will therefore be considered invalid.  The odd labels (L1, L3),
1640          * which have not yet been touched, will still be valid.  We flush
1641          * the new labels to disk to ensure that all even-label updates
1642          * are committed to stable storage before the uberblock update.
1643          */
1644         if ((error = vdev_label_sync_list(spa, 0, txg, flags)) != 0) {
1645                 if ((flags & ZIO_FLAG_TRYHARD) != 0) {
1646                         zfs_dbgmsg("vdev_label_sync_list() returned error %d "
1647                             "for pool '%s' when syncing out the even labels "
1648                             "of dirty vdevs", error, spa_name(spa));
1649                 }
1650                 goto retry;
1651         }
1652
1653         /*
1654          * Sync the uberblocks to all vdevs in svd[].
1655          * If the system dies in the middle of this step, there are two cases
1656          * to consider, and the on-disk state is consistent either way:
1657          *
1658          * (1)  If none of the new uberblocks made it to disk, then the
1659          *      previous uberblock will be the newest, and the odd labels
1660          *      (which had not yet been touched) will be valid with respect
1661          *      to that uberblock.
1662          *
1663          * (2)  If one or more new uberblocks made it to disk, then they
1664          *      will be the newest, and the even labels (which had all
1665          *      been successfully committed) will be valid with respect
1666          *      to the new uberblocks.
1667          */
1668         if ((error = vdev_uberblock_sync_list(svd, svdcount, ub, flags)) != 0) {
1669                 if ((flags & ZIO_FLAG_TRYHARD) != 0) {
1670                         zfs_dbgmsg("vdev_uberblock_sync_list() returned error "
1671                             "%d for pool '%s'", error, spa_name(spa));
1672                 }
1673                 goto retry;
1674         }
1675
1676         if (spa_multihost(spa))
1677                 mmp_update_uberblock(spa, ub);
1678
1679         /*
1680          * Sync out odd labels for every dirty vdev.  If the system dies
1681          * in the middle of this process, the even labels and the new
1682          * uberblocks will suffice to open the pool.  The next time
1683          * the pool is opened, the first thing we'll do -- before any
1684          * user data is modified -- is mark every vdev dirty so that
1685          * all labels will be brought up to date.  We flush the new labels
1686          * to disk to ensure that all odd-label updates are committed to
1687          * stable storage before the next transaction group begins.
1688          */
1689         if ((error = vdev_label_sync_list(spa, 1, txg, flags)) != 0) {
1690                 if ((flags & ZIO_FLAG_TRYHARD) != 0) {
1691                         zfs_dbgmsg("vdev_label_sync_list() returned error %d "
1692                             "for pool '%s' when syncing out the odd labels of "
1693                             "dirty vdevs", error, spa_name(spa));
1694                 }
1695                 goto retry;;
1696         }
1697
1698         trim_thread_wakeup(spa);
1699
1700         return (0);
1701 }