]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev.c
Import zstandard 1.3.1
[FreeBSD/FreeBSD.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / vdev.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) 2011, 2015 by Delphix. All rights reserved.
25  * Copyright 2017 Nexenta Systems, Inc.
26  * Copyright 2013 Martin Matuska <mm@FreeBSD.org>. All rights reserved.
27  * Copyright (c) 2014 Integros [integros.com]
28  * Copyright 2016 Toomas Soome <tsoome@me.com>
29  */
30
31 #include <sys/zfs_context.h>
32 #include <sys/fm/fs/zfs.h>
33 #include <sys/spa.h>
34 #include <sys/spa_impl.h>
35 #include <sys/dmu.h>
36 #include <sys/dmu_tx.h>
37 #include <sys/vdev_impl.h>
38 #include <sys/uberblock_impl.h>
39 #include <sys/metaslab.h>
40 #include <sys/metaslab_impl.h>
41 #include <sys/space_map.h>
42 #include <sys/space_reftree.h>
43 #include <sys/zio.h>
44 #include <sys/zap.h>
45 #include <sys/fs/zfs.h>
46 #include <sys/arc.h>
47 #include <sys/zil.h>
48 #include <sys/dsl_scan.h>
49 #include <sys/abd.h>
50 #include <sys/trim_map.h>
51
52 SYSCTL_DECL(_vfs_zfs);
53 SYSCTL_NODE(_vfs_zfs, OID_AUTO, vdev, CTLFLAG_RW, 0, "ZFS VDEV");
54
55 /*
56  * Virtual device management.
57  */
58
59 /*
60  * The limit for ZFS to automatically increase a top-level vdev's ashift
61  * from logical ashift to physical ashift.
62  *
63  * Example: one or more 512B emulation child vdevs
64  *          child->vdev_ashift = 9 (512 bytes)
65  *          child->vdev_physical_ashift = 12 (4096 bytes)
66  *          zfs_max_auto_ashift = 11 (2048 bytes)
67  *          zfs_min_auto_ashift = 9 (512 bytes)
68  *
69  * On pool creation or the addition of a new top-level vdev, ZFS will
70  * increase the ashift of the top-level vdev to 2048 as limited by
71  * zfs_max_auto_ashift.
72  *
73  * Example: one or more 512B emulation child vdevs
74  *          child->vdev_ashift = 9 (512 bytes)
75  *          child->vdev_physical_ashift = 12 (4096 bytes)
76  *          zfs_max_auto_ashift = 13 (8192 bytes)
77  *          zfs_min_auto_ashift = 9 (512 bytes)
78  *
79  * On pool creation or the addition of a new top-level vdev, ZFS will
80  * increase the ashift of the top-level vdev to 4096 to match the
81  * max vdev_physical_ashift.
82  *
83  * Example: one or more 512B emulation child vdevs
84  *          child->vdev_ashift = 9 (512 bytes)
85  *          child->vdev_physical_ashift = 9 (512 bytes)
86  *          zfs_max_auto_ashift = 13 (8192 bytes)
87  *          zfs_min_auto_ashift = 12 (4096 bytes)
88  *
89  * On pool creation or the addition of a new top-level vdev, ZFS will
90  * increase the ashift of the top-level vdev to 4096 to match the
91  * zfs_min_auto_ashift.
92  */
93 static uint64_t zfs_max_auto_ashift = SPA_MAXASHIFT;
94 static uint64_t zfs_min_auto_ashift = SPA_MINASHIFT;
95
96 static int
97 sysctl_vfs_zfs_max_auto_ashift(SYSCTL_HANDLER_ARGS)
98 {
99         uint64_t val;
100         int err;
101
102         val = zfs_max_auto_ashift;
103         err = sysctl_handle_64(oidp, &val, 0, req);
104         if (err != 0 || req->newptr == NULL)
105                 return (err);
106
107         if (val > SPA_MAXASHIFT || val < zfs_min_auto_ashift)
108                 return (EINVAL);
109
110         zfs_max_auto_ashift = val;
111
112         return (0);
113 }
114 SYSCTL_PROC(_vfs_zfs, OID_AUTO, max_auto_ashift,
115     CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
116     sysctl_vfs_zfs_max_auto_ashift, "QU",
117     "Max ashift used when optimising for logical -> physical sectors size on "
118     "new top-level vdevs.");
119
120 static int
121 sysctl_vfs_zfs_min_auto_ashift(SYSCTL_HANDLER_ARGS)
122 {
123         uint64_t val;
124         int err;
125
126         val = zfs_min_auto_ashift;
127         err = sysctl_handle_64(oidp, &val, 0, req);
128         if (err != 0 || req->newptr == NULL)
129                 return (err);
130
131         if (val < SPA_MINASHIFT || val > zfs_max_auto_ashift)
132                 return (EINVAL);
133
134         zfs_min_auto_ashift = val;
135
136         return (0);
137 }
138 SYSCTL_PROC(_vfs_zfs, OID_AUTO, min_auto_ashift,
139     CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
140     sysctl_vfs_zfs_min_auto_ashift, "QU",
141     "Min ashift used when creating new top-level vdevs.");
142
143 static vdev_ops_t *vdev_ops_table[] = {
144         &vdev_root_ops,
145         &vdev_raidz_ops,
146         &vdev_mirror_ops,
147         &vdev_replacing_ops,
148         &vdev_spare_ops,
149 #ifdef _KERNEL
150         &vdev_geom_ops,
151 #else
152         &vdev_disk_ops,
153 #endif
154         &vdev_file_ops,
155         &vdev_missing_ops,
156         &vdev_hole_ops,
157         NULL
158 };
159
160
161 /*
162  * When a vdev is added, it will be divided into approximately (but no
163  * more than) this number of metaslabs.
164  */
165 int metaslabs_per_vdev = 200;
166 SYSCTL_INT(_vfs_zfs_vdev, OID_AUTO, metaslabs_per_vdev, CTLFLAG_RDTUN,
167     &metaslabs_per_vdev, 0,
168     "When a vdev is added, how many metaslabs the vdev should be divided into");
169
170 /*
171  * Given a vdev type, return the appropriate ops vector.
172  */
173 static vdev_ops_t *
174 vdev_getops(const char *type)
175 {
176         vdev_ops_t *ops, **opspp;
177
178         for (opspp = vdev_ops_table; (ops = *opspp) != NULL; opspp++)
179                 if (strcmp(ops->vdev_op_type, type) == 0)
180                         break;
181
182         return (ops);
183 }
184
185 /*
186  * Default asize function: return the MAX of psize with the asize of
187  * all children.  This is what's used by anything other than RAID-Z.
188  */
189 uint64_t
190 vdev_default_asize(vdev_t *vd, uint64_t psize)
191 {
192         uint64_t asize = P2ROUNDUP(psize, 1ULL << vd->vdev_top->vdev_ashift);
193         uint64_t csize;
194
195         for (int c = 0; c < vd->vdev_children; c++) {
196                 csize = vdev_psize_to_asize(vd->vdev_child[c], psize);
197                 asize = MAX(asize, csize);
198         }
199
200         return (asize);
201 }
202
203 /*
204  * Get the minimum allocatable size. We define the allocatable size as
205  * the vdev's asize rounded to the nearest metaslab. This allows us to
206  * replace or attach devices which don't have the same physical size but
207  * can still satisfy the same number of allocations.
208  */
209 uint64_t
210 vdev_get_min_asize(vdev_t *vd)
211 {
212         vdev_t *pvd = vd->vdev_parent;
213
214         /*
215          * If our parent is NULL (inactive spare or cache) or is the root,
216          * just return our own asize.
217          */
218         if (pvd == NULL)
219                 return (vd->vdev_asize);
220
221         /*
222          * The top-level vdev just returns the allocatable size rounded
223          * to the nearest metaslab.
224          */
225         if (vd == vd->vdev_top)
226                 return (P2ALIGN(vd->vdev_asize, 1ULL << vd->vdev_ms_shift));
227
228         /*
229          * The allocatable space for a raidz vdev is N * sizeof(smallest child),
230          * so each child must provide at least 1/Nth of its asize.
231          */
232         if (pvd->vdev_ops == &vdev_raidz_ops)
233                 return ((pvd->vdev_min_asize + pvd->vdev_children - 1) /
234                     pvd->vdev_children);
235
236         return (pvd->vdev_min_asize);
237 }
238
239 void
240 vdev_set_min_asize(vdev_t *vd)
241 {
242         vd->vdev_min_asize = vdev_get_min_asize(vd);
243
244         for (int c = 0; c < vd->vdev_children; c++)
245                 vdev_set_min_asize(vd->vdev_child[c]);
246 }
247
248 vdev_t *
249 vdev_lookup_top(spa_t *spa, uint64_t vdev)
250 {
251         vdev_t *rvd = spa->spa_root_vdev;
252
253         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
254
255         if (vdev < rvd->vdev_children) {
256                 ASSERT(rvd->vdev_child[vdev] != NULL);
257                 return (rvd->vdev_child[vdev]);
258         }
259
260         return (NULL);
261 }
262
263 vdev_t *
264 vdev_lookup_by_guid(vdev_t *vd, uint64_t guid)
265 {
266         vdev_t *mvd;
267
268         if (vd->vdev_guid == guid)
269                 return (vd);
270
271         for (int c = 0; c < vd->vdev_children; c++)
272                 if ((mvd = vdev_lookup_by_guid(vd->vdev_child[c], guid)) !=
273                     NULL)
274                         return (mvd);
275
276         return (NULL);
277 }
278
279 static int
280 vdev_count_leaves_impl(vdev_t *vd)
281 {
282         int n = 0;
283
284         if (vd->vdev_ops->vdev_op_leaf)
285                 return (1);
286
287         for (int c = 0; c < vd->vdev_children; c++)
288                 n += vdev_count_leaves_impl(vd->vdev_child[c]);
289
290         return (n);
291 }
292
293 int
294 vdev_count_leaves(spa_t *spa)
295 {
296         return (vdev_count_leaves_impl(spa->spa_root_vdev));
297 }
298
299 void
300 vdev_add_child(vdev_t *pvd, vdev_t *cvd)
301 {
302         size_t oldsize, newsize;
303         uint64_t id = cvd->vdev_id;
304         vdev_t **newchild;
305         spa_t *spa = cvd->vdev_spa;
306
307         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
308         ASSERT(cvd->vdev_parent == NULL);
309
310         cvd->vdev_parent = pvd;
311
312         if (pvd == NULL)
313                 return;
314
315         ASSERT(id >= pvd->vdev_children || pvd->vdev_child[id] == NULL);
316
317         oldsize = pvd->vdev_children * sizeof (vdev_t *);
318         pvd->vdev_children = MAX(pvd->vdev_children, id + 1);
319         newsize = pvd->vdev_children * sizeof (vdev_t *);
320
321         newchild = kmem_zalloc(newsize, KM_SLEEP);
322         if (pvd->vdev_child != NULL) {
323                 bcopy(pvd->vdev_child, newchild, oldsize);
324                 kmem_free(pvd->vdev_child, oldsize);
325         }
326
327         pvd->vdev_child = newchild;
328         pvd->vdev_child[id] = cvd;
329
330         cvd->vdev_top = (pvd->vdev_top ? pvd->vdev_top: cvd);
331         ASSERT(cvd->vdev_top->vdev_parent->vdev_parent == NULL);
332
333         /*
334          * Walk up all ancestors to update guid sum.
335          */
336         for (; pvd != NULL; pvd = pvd->vdev_parent)
337                 pvd->vdev_guid_sum += cvd->vdev_guid_sum;
338 }
339
340 void
341 vdev_remove_child(vdev_t *pvd, vdev_t *cvd)
342 {
343         int c;
344         uint_t id = cvd->vdev_id;
345
346         ASSERT(cvd->vdev_parent == pvd);
347
348         if (pvd == NULL)
349                 return;
350
351         ASSERT(id < pvd->vdev_children);
352         ASSERT(pvd->vdev_child[id] == cvd);
353
354         pvd->vdev_child[id] = NULL;
355         cvd->vdev_parent = NULL;
356
357         for (c = 0; c < pvd->vdev_children; c++)
358                 if (pvd->vdev_child[c])
359                         break;
360
361         if (c == pvd->vdev_children) {
362                 kmem_free(pvd->vdev_child, c * sizeof (vdev_t *));
363                 pvd->vdev_child = NULL;
364                 pvd->vdev_children = 0;
365         }
366
367         /*
368          * Walk up all ancestors to update guid sum.
369          */
370         for (; pvd != NULL; pvd = pvd->vdev_parent)
371                 pvd->vdev_guid_sum -= cvd->vdev_guid_sum;
372 }
373
374 /*
375  * Remove any holes in the child array.
376  */
377 void
378 vdev_compact_children(vdev_t *pvd)
379 {
380         vdev_t **newchild, *cvd;
381         int oldc = pvd->vdev_children;
382         int newc;
383
384         ASSERT(spa_config_held(pvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
385
386         for (int c = newc = 0; c < oldc; c++)
387                 if (pvd->vdev_child[c])
388                         newc++;
389
390         newchild = kmem_alloc(newc * sizeof (vdev_t *), KM_SLEEP);
391
392         for (int c = newc = 0; c < oldc; c++) {
393                 if ((cvd = pvd->vdev_child[c]) != NULL) {
394                         newchild[newc] = cvd;
395                         cvd->vdev_id = newc++;
396                 }
397         }
398
399         kmem_free(pvd->vdev_child, oldc * sizeof (vdev_t *));
400         pvd->vdev_child = newchild;
401         pvd->vdev_children = newc;
402 }
403
404 /*
405  * Allocate and minimally initialize a vdev_t.
406  */
407 vdev_t *
408 vdev_alloc_common(spa_t *spa, uint_t id, uint64_t guid, vdev_ops_t *ops)
409 {
410         vdev_t *vd;
411
412         vd = kmem_zalloc(sizeof (vdev_t), KM_SLEEP);
413
414         if (spa->spa_root_vdev == NULL) {
415                 ASSERT(ops == &vdev_root_ops);
416                 spa->spa_root_vdev = vd;
417                 spa->spa_load_guid = spa_generate_guid(NULL);
418         }
419
420         if (guid == 0 && ops != &vdev_hole_ops) {
421                 if (spa->spa_root_vdev == vd) {
422                         /*
423                          * The root vdev's guid will also be the pool guid,
424                          * which must be unique among all pools.
425                          */
426                         guid = spa_generate_guid(NULL);
427                 } else {
428                         /*
429                          * Any other vdev's guid must be unique within the pool.
430                          */
431                         guid = spa_generate_guid(spa);
432                 }
433                 ASSERT(!spa_guid_exists(spa_guid(spa), guid));
434         }
435
436         vd->vdev_spa = spa;
437         vd->vdev_id = id;
438         vd->vdev_guid = guid;
439         vd->vdev_guid_sum = guid;
440         vd->vdev_ops = ops;
441         vd->vdev_state = VDEV_STATE_CLOSED;
442         vd->vdev_ishole = (ops == &vdev_hole_ops);
443
444         mutex_init(&vd->vdev_dtl_lock, NULL, MUTEX_DEFAULT, NULL);
445         mutex_init(&vd->vdev_stat_lock, NULL, MUTEX_DEFAULT, NULL);
446         mutex_init(&vd->vdev_probe_lock, NULL, MUTEX_DEFAULT, NULL);
447         mutex_init(&vd->vdev_queue_lock, NULL, MUTEX_DEFAULT, NULL);
448         for (int t = 0; t < DTL_TYPES; t++) {
449                 vd->vdev_dtl[t] = range_tree_create(NULL, NULL,
450                     &vd->vdev_dtl_lock);
451         }
452         txg_list_create(&vd->vdev_ms_list, spa,
453             offsetof(struct metaslab, ms_txg_node));
454         txg_list_create(&vd->vdev_dtl_list, spa,
455             offsetof(struct vdev, vdev_dtl_node));
456         vd->vdev_stat.vs_timestamp = gethrtime();
457         vdev_queue_init(vd);
458         vdev_cache_init(vd);
459
460         return (vd);
461 }
462
463 /*
464  * Allocate a new vdev.  The 'alloctype' is used to control whether we are
465  * creating a new vdev or loading an existing one - the behavior is slightly
466  * different for each case.
467  */
468 int
469 vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
470     int alloctype)
471 {
472         vdev_ops_t *ops;
473         char *type;
474         uint64_t guid = 0, islog, nparity;
475         vdev_t *vd;
476
477         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
478
479         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
480                 return (SET_ERROR(EINVAL));
481
482         if ((ops = vdev_getops(type)) == NULL)
483                 return (SET_ERROR(EINVAL));
484
485         /*
486          * If this is a load, get the vdev guid from the nvlist.
487          * Otherwise, vdev_alloc_common() will generate one for us.
488          */
489         if (alloctype == VDEV_ALLOC_LOAD) {
490                 uint64_t label_id;
491
492                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID, &label_id) ||
493                     label_id != id)
494                         return (SET_ERROR(EINVAL));
495
496                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
497                         return (SET_ERROR(EINVAL));
498         } else if (alloctype == VDEV_ALLOC_SPARE) {
499                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
500                         return (SET_ERROR(EINVAL));
501         } else if (alloctype == VDEV_ALLOC_L2CACHE) {
502                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
503                         return (SET_ERROR(EINVAL));
504         } else if (alloctype == VDEV_ALLOC_ROOTPOOL) {
505                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
506                         return (SET_ERROR(EINVAL));
507         }
508
509         /*
510          * The first allocated vdev must be of type 'root'.
511          */
512         if (ops != &vdev_root_ops && spa->spa_root_vdev == NULL)
513                 return (SET_ERROR(EINVAL));
514
515         /*
516          * Determine whether we're a log vdev.
517          */
518         islog = 0;
519         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG, &islog);
520         if (islog && spa_version(spa) < SPA_VERSION_SLOGS)
521                 return (SET_ERROR(ENOTSUP));
522
523         if (ops == &vdev_hole_ops && spa_version(spa) < SPA_VERSION_HOLES)
524                 return (SET_ERROR(ENOTSUP));
525
526         /*
527          * Set the nparity property for RAID-Z vdevs.
528          */
529         nparity = -1ULL;
530         if (ops == &vdev_raidz_ops) {
531                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
532                     &nparity) == 0) {
533                         if (nparity == 0 || nparity > VDEV_RAIDZ_MAXPARITY)
534                                 return (SET_ERROR(EINVAL));
535                         /*
536                          * Previous versions could only support 1 or 2 parity
537                          * device.
538                          */
539                         if (nparity > 1 &&
540                             spa_version(spa) < SPA_VERSION_RAIDZ2)
541                                 return (SET_ERROR(ENOTSUP));
542                         if (nparity > 2 &&
543                             spa_version(spa) < SPA_VERSION_RAIDZ3)
544                                 return (SET_ERROR(ENOTSUP));
545                 } else {
546                         /*
547                          * We require the parity to be specified for SPAs that
548                          * support multiple parity levels.
549                          */
550                         if (spa_version(spa) >= SPA_VERSION_RAIDZ2)
551                                 return (SET_ERROR(EINVAL));
552                         /*
553                          * Otherwise, we default to 1 parity device for RAID-Z.
554                          */
555                         nparity = 1;
556                 }
557         } else {
558                 nparity = 0;
559         }
560         ASSERT(nparity != -1ULL);
561
562         vd = vdev_alloc_common(spa, id, guid, ops);
563
564         vd->vdev_islog = islog;
565         vd->vdev_nparity = nparity;
566
567         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &vd->vdev_path) == 0)
568                 vd->vdev_path = spa_strdup(vd->vdev_path);
569         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &vd->vdev_devid) == 0)
570                 vd->vdev_devid = spa_strdup(vd->vdev_devid);
571         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PHYS_PATH,
572             &vd->vdev_physpath) == 0)
573                 vd->vdev_physpath = spa_strdup(vd->vdev_physpath);
574         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_FRU, &vd->vdev_fru) == 0)
575                 vd->vdev_fru = spa_strdup(vd->vdev_fru);
576
577         /*
578          * Set the whole_disk property.  If it's not specified, leave the value
579          * as -1.
580          */
581         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
582             &vd->vdev_wholedisk) != 0)
583                 vd->vdev_wholedisk = -1ULL;
584
585         /*
586          * Look for the 'not present' flag.  This will only be set if the device
587          * was not present at the time of import.
588          */
589         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
590             &vd->vdev_not_present);
591
592         /*
593          * Get the alignment requirement.
594          */
595         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASHIFT, &vd->vdev_ashift);
596
597         /*
598          * Retrieve the vdev creation time.
599          */
600         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_CREATE_TXG,
601             &vd->vdev_crtxg);
602
603         /*
604          * If we're a top-level vdev, try to load the allocation parameters.
605          */
606         if (parent && !parent->vdev_parent &&
607             (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
608                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
609                     &vd->vdev_ms_array);
610                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
611                     &vd->vdev_ms_shift);
612                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASIZE,
613                     &vd->vdev_asize);
614                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVING,
615                     &vd->vdev_removing);
616                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_VDEV_TOP_ZAP,
617                     &vd->vdev_top_zap);
618         } else {
619                 ASSERT0(vd->vdev_top_zap);
620         }
621
622         if (parent && !parent->vdev_parent && alloctype != VDEV_ALLOC_ATTACH) {
623                 ASSERT(alloctype == VDEV_ALLOC_LOAD ||
624                     alloctype == VDEV_ALLOC_ADD ||
625                     alloctype == VDEV_ALLOC_SPLIT ||
626                     alloctype == VDEV_ALLOC_ROOTPOOL);
627                 vd->vdev_mg = metaslab_group_create(islog ?
628                     spa_log_class(spa) : spa_normal_class(spa), vd);
629         }
630
631         if (vd->vdev_ops->vdev_op_leaf &&
632             (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
633                 (void) nvlist_lookup_uint64(nv,
634                     ZPOOL_CONFIG_VDEV_LEAF_ZAP, &vd->vdev_leaf_zap);
635         } else {
636                 ASSERT0(vd->vdev_leaf_zap);
637         }
638
639         /*
640          * If we're a leaf vdev, try to load the DTL object and other state.
641          */
642
643         if (vd->vdev_ops->vdev_op_leaf &&
644             (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_L2CACHE ||
645             alloctype == VDEV_ALLOC_ROOTPOOL)) {
646                 if (alloctype == VDEV_ALLOC_LOAD) {
647                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DTL,
648                             &vd->vdev_dtl_object);
649                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_UNSPARE,
650                             &vd->vdev_unspare);
651                 }
652
653                 if (alloctype == VDEV_ALLOC_ROOTPOOL) {
654                         uint64_t spare = 0;
655
656                         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE,
657                             &spare) == 0 && spare)
658                                 spa_spare_add(vd);
659                 }
660
661                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE,
662                     &vd->vdev_offline);
663
664                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_RESILVER_TXG,
665                     &vd->vdev_resilver_txg);
666
667                 /*
668                  * When importing a pool, we want to ignore the persistent fault
669                  * state, as the diagnosis made on another system may not be
670                  * valid in the current context.  Local vdevs will
671                  * remain in the faulted state.
672                  */
673                 if (spa_load_state(spa) == SPA_LOAD_OPEN) {
674                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED,
675                             &vd->vdev_faulted);
676                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DEGRADED,
677                             &vd->vdev_degraded);
678                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED,
679                             &vd->vdev_removed);
680
681                         if (vd->vdev_faulted || vd->vdev_degraded) {
682                                 char *aux;
683
684                                 vd->vdev_label_aux =
685                                     VDEV_AUX_ERR_EXCEEDED;
686                                 if (nvlist_lookup_string(nv,
687                                     ZPOOL_CONFIG_AUX_STATE, &aux) == 0 &&
688                                     strcmp(aux, "external") == 0)
689                                         vd->vdev_label_aux = VDEV_AUX_EXTERNAL;
690                         }
691                 }
692         }
693
694         /*
695          * Add ourselves to the parent's list of children.
696          */
697         vdev_add_child(parent, vd);
698
699         *vdp = vd;
700
701         return (0);
702 }
703
704 void
705 vdev_free(vdev_t *vd)
706 {
707         spa_t *spa = vd->vdev_spa;
708
709         /*
710          * vdev_free() implies closing the vdev first.  This is simpler than
711          * trying to ensure complicated semantics for all callers.
712          */
713         vdev_close(vd);
714
715         ASSERT(!list_link_active(&vd->vdev_config_dirty_node));
716         ASSERT(!list_link_active(&vd->vdev_state_dirty_node));
717
718         /*
719          * Free all children.
720          */
721         for (int c = 0; c < vd->vdev_children; c++)
722                 vdev_free(vd->vdev_child[c]);
723
724         ASSERT(vd->vdev_child == NULL);
725         ASSERT(vd->vdev_guid_sum == vd->vdev_guid);
726
727         /*
728          * Discard allocation state.
729          */
730         if (vd->vdev_mg != NULL) {
731                 vdev_metaslab_fini(vd);
732                 metaslab_group_destroy(vd->vdev_mg);
733         }
734
735         ASSERT0(vd->vdev_stat.vs_space);
736         ASSERT0(vd->vdev_stat.vs_dspace);
737         ASSERT0(vd->vdev_stat.vs_alloc);
738
739         /*
740          * Remove this vdev from its parent's child list.
741          */
742         vdev_remove_child(vd->vdev_parent, vd);
743
744         ASSERT(vd->vdev_parent == NULL);
745
746         /*
747          * Clean up vdev structure.
748          */
749         vdev_queue_fini(vd);
750         vdev_cache_fini(vd);
751
752         if (vd->vdev_path)
753                 spa_strfree(vd->vdev_path);
754         if (vd->vdev_devid)
755                 spa_strfree(vd->vdev_devid);
756         if (vd->vdev_physpath)
757                 spa_strfree(vd->vdev_physpath);
758         if (vd->vdev_fru)
759                 spa_strfree(vd->vdev_fru);
760
761         if (vd->vdev_isspare)
762                 spa_spare_remove(vd);
763         if (vd->vdev_isl2cache)
764                 spa_l2cache_remove(vd);
765
766         txg_list_destroy(&vd->vdev_ms_list);
767         txg_list_destroy(&vd->vdev_dtl_list);
768
769         mutex_enter(&vd->vdev_dtl_lock);
770         space_map_close(vd->vdev_dtl_sm);
771         for (int t = 0; t < DTL_TYPES; t++) {
772                 range_tree_vacate(vd->vdev_dtl[t], NULL, NULL);
773                 range_tree_destroy(vd->vdev_dtl[t]);
774         }
775         mutex_exit(&vd->vdev_dtl_lock);
776
777         mutex_destroy(&vd->vdev_queue_lock);
778         mutex_destroy(&vd->vdev_dtl_lock);
779         mutex_destroy(&vd->vdev_stat_lock);
780         mutex_destroy(&vd->vdev_probe_lock);
781
782         if (vd == spa->spa_root_vdev)
783                 spa->spa_root_vdev = NULL;
784
785         kmem_free(vd, sizeof (vdev_t));
786 }
787
788 /*
789  * Transfer top-level vdev state from svd to tvd.
790  */
791 static void
792 vdev_top_transfer(vdev_t *svd, vdev_t *tvd)
793 {
794         spa_t *spa = svd->vdev_spa;
795         metaslab_t *msp;
796         vdev_t *vd;
797         int t;
798
799         ASSERT(tvd == tvd->vdev_top);
800
801         tvd->vdev_ms_array = svd->vdev_ms_array;
802         tvd->vdev_ms_shift = svd->vdev_ms_shift;
803         tvd->vdev_ms_count = svd->vdev_ms_count;
804         tvd->vdev_top_zap = svd->vdev_top_zap;
805
806         svd->vdev_ms_array = 0;
807         svd->vdev_ms_shift = 0;
808         svd->vdev_ms_count = 0;
809         svd->vdev_top_zap = 0;
810
811         if (tvd->vdev_mg)
812                 ASSERT3P(tvd->vdev_mg, ==, svd->vdev_mg);
813         tvd->vdev_mg = svd->vdev_mg;
814         tvd->vdev_ms = svd->vdev_ms;
815
816         svd->vdev_mg = NULL;
817         svd->vdev_ms = NULL;
818
819         if (tvd->vdev_mg != NULL)
820                 tvd->vdev_mg->mg_vd = tvd;
821
822         tvd->vdev_stat.vs_alloc = svd->vdev_stat.vs_alloc;
823         tvd->vdev_stat.vs_space = svd->vdev_stat.vs_space;
824         tvd->vdev_stat.vs_dspace = svd->vdev_stat.vs_dspace;
825
826         svd->vdev_stat.vs_alloc = 0;
827         svd->vdev_stat.vs_space = 0;
828         svd->vdev_stat.vs_dspace = 0;
829
830         for (t = 0; t < TXG_SIZE; t++) {
831                 while ((msp = txg_list_remove(&svd->vdev_ms_list, t)) != NULL)
832                         (void) txg_list_add(&tvd->vdev_ms_list, msp, t);
833                 while ((vd = txg_list_remove(&svd->vdev_dtl_list, t)) != NULL)
834                         (void) txg_list_add(&tvd->vdev_dtl_list, vd, t);
835                 if (txg_list_remove_this(&spa->spa_vdev_txg_list, svd, t))
836                         (void) txg_list_add(&spa->spa_vdev_txg_list, tvd, t);
837         }
838
839         if (list_link_active(&svd->vdev_config_dirty_node)) {
840                 vdev_config_clean(svd);
841                 vdev_config_dirty(tvd);
842         }
843
844         if (list_link_active(&svd->vdev_state_dirty_node)) {
845                 vdev_state_clean(svd);
846                 vdev_state_dirty(tvd);
847         }
848
849         tvd->vdev_deflate_ratio = svd->vdev_deflate_ratio;
850         svd->vdev_deflate_ratio = 0;
851
852         tvd->vdev_islog = svd->vdev_islog;
853         svd->vdev_islog = 0;
854 }
855
856 static void
857 vdev_top_update(vdev_t *tvd, vdev_t *vd)
858 {
859         if (vd == NULL)
860                 return;
861
862         vd->vdev_top = tvd;
863
864         for (int c = 0; c < vd->vdev_children; c++)
865                 vdev_top_update(tvd, vd->vdev_child[c]);
866 }
867
868 /*
869  * Add a mirror/replacing vdev above an existing vdev.
870  */
871 vdev_t *
872 vdev_add_parent(vdev_t *cvd, vdev_ops_t *ops)
873 {
874         spa_t *spa = cvd->vdev_spa;
875         vdev_t *pvd = cvd->vdev_parent;
876         vdev_t *mvd;
877
878         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
879
880         mvd = vdev_alloc_common(spa, cvd->vdev_id, 0, ops);
881
882         mvd->vdev_asize = cvd->vdev_asize;
883         mvd->vdev_min_asize = cvd->vdev_min_asize;
884         mvd->vdev_max_asize = cvd->vdev_max_asize;
885         mvd->vdev_ashift = cvd->vdev_ashift;
886         mvd->vdev_logical_ashift = cvd->vdev_logical_ashift;
887         mvd->vdev_physical_ashift = cvd->vdev_physical_ashift;
888         mvd->vdev_state = cvd->vdev_state;
889         mvd->vdev_crtxg = cvd->vdev_crtxg;
890
891         vdev_remove_child(pvd, cvd);
892         vdev_add_child(pvd, mvd);
893         cvd->vdev_id = mvd->vdev_children;
894         vdev_add_child(mvd, cvd);
895         vdev_top_update(cvd->vdev_top, cvd->vdev_top);
896
897         if (mvd == mvd->vdev_top)
898                 vdev_top_transfer(cvd, mvd);
899
900         return (mvd);
901 }
902
903 /*
904  * Remove a 1-way mirror/replacing vdev from the tree.
905  */
906 void
907 vdev_remove_parent(vdev_t *cvd)
908 {
909         vdev_t *mvd = cvd->vdev_parent;
910         vdev_t *pvd = mvd->vdev_parent;
911
912         ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
913
914         ASSERT(mvd->vdev_children == 1);
915         ASSERT(mvd->vdev_ops == &vdev_mirror_ops ||
916             mvd->vdev_ops == &vdev_replacing_ops ||
917             mvd->vdev_ops == &vdev_spare_ops);
918         cvd->vdev_ashift = mvd->vdev_ashift;
919         cvd->vdev_logical_ashift = mvd->vdev_logical_ashift;
920         cvd->vdev_physical_ashift = mvd->vdev_physical_ashift;
921
922         vdev_remove_child(mvd, cvd);
923         vdev_remove_child(pvd, mvd);
924
925         /*
926          * If cvd will replace mvd as a top-level vdev, preserve mvd's guid.
927          * Otherwise, we could have detached an offline device, and when we
928          * go to import the pool we'll think we have two top-level vdevs,
929          * instead of a different version of the same top-level vdev.
930          */
931         if (mvd->vdev_top == mvd) {
932                 uint64_t guid_delta = mvd->vdev_guid - cvd->vdev_guid;
933                 cvd->vdev_orig_guid = cvd->vdev_guid;
934                 cvd->vdev_guid += guid_delta;
935                 cvd->vdev_guid_sum += guid_delta;
936         }
937         cvd->vdev_id = mvd->vdev_id;
938         vdev_add_child(pvd, cvd);
939         vdev_top_update(cvd->vdev_top, cvd->vdev_top);
940
941         if (cvd == cvd->vdev_top)
942                 vdev_top_transfer(mvd, cvd);
943
944         ASSERT(mvd->vdev_children == 0);
945         vdev_free(mvd);
946 }
947
948 int
949 vdev_metaslab_init(vdev_t *vd, uint64_t txg)
950 {
951         spa_t *spa = vd->vdev_spa;
952         objset_t *mos = spa->spa_meta_objset;
953         uint64_t m;
954         uint64_t oldc = vd->vdev_ms_count;
955         uint64_t newc = vd->vdev_asize >> vd->vdev_ms_shift;
956         metaslab_t **mspp;
957         int error;
958
959         ASSERT(txg == 0 || spa_config_held(spa, SCL_ALLOC, RW_WRITER));
960
961         /*
962          * This vdev is not being allocated from yet or is a hole.
963          */
964         if (vd->vdev_ms_shift == 0)
965                 return (0);
966
967         ASSERT(!vd->vdev_ishole);
968
969         /*
970          * Compute the raidz-deflation ratio.  Note, we hard-code
971          * in 128k (1 << 17) because it is the "typical" blocksize.
972          * Even though SPA_MAXBLOCKSIZE changed, this algorithm can not change,
973          * otherwise it would inconsistently account for existing bp's.
974          */
975         vd->vdev_deflate_ratio = (1 << 17) /
976             (vdev_psize_to_asize(vd, 1 << 17) >> SPA_MINBLOCKSHIFT);
977
978         ASSERT(oldc <= newc);
979
980         mspp = kmem_zalloc(newc * sizeof (*mspp), KM_SLEEP);
981
982         if (oldc != 0) {
983                 bcopy(vd->vdev_ms, mspp, oldc * sizeof (*mspp));
984                 kmem_free(vd->vdev_ms, oldc * sizeof (*mspp));
985         }
986
987         vd->vdev_ms = mspp;
988         vd->vdev_ms_count = newc;
989
990         for (m = oldc; m < newc; m++) {
991                 uint64_t object = 0;
992
993                 if (txg == 0) {
994                         error = dmu_read(mos, vd->vdev_ms_array,
995                             m * sizeof (uint64_t), sizeof (uint64_t), &object,
996                             DMU_READ_PREFETCH);
997                         if (error)
998                                 return (error);
999                 }
1000
1001                 error = metaslab_init(vd->vdev_mg, m, object, txg,
1002                     &(vd->vdev_ms[m]));
1003                 if (error)
1004                         return (error);
1005         }
1006
1007         if (txg == 0)
1008                 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_WRITER);
1009
1010         /*
1011          * If the vdev is being removed we don't activate
1012          * the metaslabs since we want to ensure that no new
1013          * allocations are performed on this device.
1014          */
1015         if (oldc == 0 && !vd->vdev_removing)
1016                 metaslab_group_activate(vd->vdev_mg);
1017
1018         if (txg == 0)
1019                 spa_config_exit(spa, SCL_ALLOC, FTAG);
1020
1021         return (0);
1022 }
1023
1024 void
1025 vdev_metaslab_fini(vdev_t *vd)
1026 {
1027         uint64_t m;
1028         uint64_t count = vd->vdev_ms_count;
1029
1030         if (vd->vdev_ms != NULL) {
1031                 metaslab_group_passivate(vd->vdev_mg);
1032                 for (m = 0; m < count; m++) {
1033                         metaslab_t *msp = vd->vdev_ms[m];
1034
1035                         if (msp != NULL)
1036                                 metaslab_fini(msp);
1037                 }
1038                 kmem_free(vd->vdev_ms, count * sizeof (metaslab_t *));
1039                 vd->vdev_ms = NULL;
1040         }
1041 }
1042
1043 typedef struct vdev_probe_stats {
1044         boolean_t       vps_readable;
1045         boolean_t       vps_writeable;
1046         int             vps_flags;
1047 } vdev_probe_stats_t;
1048
1049 static void
1050 vdev_probe_done(zio_t *zio)
1051 {
1052         spa_t *spa = zio->io_spa;
1053         vdev_t *vd = zio->io_vd;
1054         vdev_probe_stats_t *vps = zio->io_private;
1055
1056         ASSERT(vd->vdev_probe_zio != NULL);
1057
1058         if (zio->io_type == ZIO_TYPE_READ) {
1059                 if (zio->io_error == 0)
1060                         vps->vps_readable = 1;
1061                 if (zio->io_error == 0 && spa_writeable(spa)) {
1062                         zio_nowait(zio_write_phys(vd->vdev_probe_zio, vd,
1063                             zio->io_offset, zio->io_size, zio->io_abd,
1064                             ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1065                             ZIO_PRIORITY_SYNC_WRITE, vps->vps_flags, B_TRUE));
1066                 } else {
1067                         abd_free(zio->io_abd);
1068                 }
1069         } else if (zio->io_type == ZIO_TYPE_WRITE) {
1070                 if (zio->io_error == 0)
1071                         vps->vps_writeable = 1;
1072                 abd_free(zio->io_abd);
1073         } else if (zio->io_type == ZIO_TYPE_NULL) {
1074                 zio_t *pio;
1075
1076                 vd->vdev_cant_read |= !vps->vps_readable;
1077                 vd->vdev_cant_write |= !vps->vps_writeable;
1078
1079                 if (vdev_readable(vd) &&
1080                     (vdev_writeable(vd) || !spa_writeable(spa))) {
1081                         zio->io_error = 0;
1082                 } else {
1083                         ASSERT(zio->io_error != 0);
1084                         zfs_ereport_post(FM_EREPORT_ZFS_PROBE_FAILURE,
1085                             spa, vd, NULL, 0, 0);
1086                         zio->io_error = SET_ERROR(ENXIO);
1087                 }
1088
1089                 mutex_enter(&vd->vdev_probe_lock);
1090                 ASSERT(vd->vdev_probe_zio == zio);
1091                 vd->vdev_probe_zio = NULL;
1092                 mutex_exit(&vd->vdev_probe_lock);
1093
1094                 zio_link_t *zl = NULL;
1095                 while ((pio = zio_walk_parents(zio, &zl)) != NULL)
1096                         if (!vdev_accessible(vd, pio))
1097                                 pio->io_error = SET_ERROR(ENXIO);
1098
1099                 kmem_free(vps, sizeof (*vps));
1100         }
1101 }
1102
1103 /*
1104  * Determine whether this device is accessible.
1105  *
1106  * Read and write to several known locations: the pad regions of each
1107  * vdev label but the first, which we leave alone in case it contains
1108  * a VTOC.
1109  */
1110 zio_t *
1111 vdev_probe(vdev_t *vd, zio_t *zio)
1112 {
1113         spa_t *spa = vd->vdev_spa;
1114         vdev_probe_stats_t *vps = NULL;
1115         zio_t *pio;
1116
1117         ASSERT(vd->vdev_ops->vdev_op_leaf);
1118
1119         /*
1120          * Don't probe the probe.
1121          */
1122         if (zio && (zio->io_flags & ZIO_FLAG_PROBE))
1123                 return (NULL);
1124
1125         /*
1126          * To prevent 'probe storms' when a device fails, we create
1127          * just one probe i/o at a time.  All zios that want to probe
1128          * this vdev will become parents of the probe io.
1129          */
1130         mutex_enter(&vd->vdev_probe_lock);
1131
1132         if ((pio = vd->vdev_probe_zio) == NULL) {
1133                 vps = kmem_zalloc(sizeof (*vps), KM_SLEEP);
1134
1135                 vps->vps_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_PROBE |
1136                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE |
1137                     ZIO_FLAG_TRYHARD;
1138
1139                 if (spa_config_held(spa, SCL_ZIO, RW_WRITER)) {
1140                         /*
1141                          * vdev_cant_read and vdev_cant_write can only
1142                          * transition from TRUE to FALSE when we have the
1143                          * SCL_ZIO lock as writer; otherwise they can only
1144                          * transition from FALSE to TRUE.  This ensures that
1145                          * any zio looking at these values can assume that
1146                          * failures persist for the life of the I/O.  That's
1147                          * important because when a device has intermittent
1148                          * connectivity problems, we want to ensure that
1149                          * they're ascribed to the device (ENXIO) and not
1150                          * the zio (EIO).
1151                          *
1152                          * Since we hold SCL_ZIO as writer here, clear both
1153                          * values so the probe can reevaluate from first
1154                          * principles.
1155                          */
1156                         vps->vps_flags |= ZIO_FLAG_CONFIG_WRITER;
1157                         vd->vdev_cant_read = B_FALSE;
1158                         vd->vdev_cant_write = B_FALSE;
1159                 }
1160
1161                 vd->vdev_probe_zio = pio = zio_null(NULL, spa, vd,
1162                     vdev_probe_done, vps,
1163                     vps->vps_flags | ZIO_FLAG_DONT_PROPAGATE);
1164
1165                 /*
1166                  * We can't change the vdev state in this context, so we
1167                  * kick off an async task to do it on our behalf.
1168                  */
1169                 if (zio != NULL) {
1170                         vd->vdev_probe_wanted = B_TRUE;
1171                         spa_async_request(spa, SPA_ASYNC_PROBE);
1172                 }
1173         }
1174
1175         if (zio != NULL)
1176                 zio_add_child(zio, pio);
1177
1178         mutex_exit(&vd->vdev_probe_lock);
1179
1180         if (vps == NULL) {
1181                 ASSERT(zio != NULL);
1182                 return (NULL);
1183         }
1184
1185         for (int l = 1; l < VDEV_LABELS; l++) {
1186                 zio_nowait(zio_read_phys(pio, vd,
1187                     vdev_label_offset(vd->vdev_psize, l,
1188                     offsetof(vdev_label_t, vl_pad2)), VDEV_PAD_SIZE,
1189                     abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE),
1190                     ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1191                     ZIO_PRIORITY_SYNC_READ, vps->vps_flags, B_TRUE));
1192         }
1193
1194         if (zio == NULL)
1195                 return (pio);
1196
1197         zio_nowait(pio);
1198         return (NULL);
1199 }
1200
1201 static void
1202 vdev_open_child(void *arg)
1203 {
1204         vdev_t *vd = arg;
1205
1206         vd->vdev_open_thread = curthread;
1207         vd->vdev_open_error = vdev_open(vd);
1208         vd->vdev_open_thread = NULL;
1209 }
1210
1211 boolean_t
1212 vdev_uses_zvols(vdev_t *vd)
1213 {
1214         if (vd->vdev_path && strncmp(vd->vdev_path, ZVOL_DIR,
1215             strlen(ZVOL_DIR)) == 0)
1216                 return (B_TRUE);
1217         for (int c = 0; c < vd->vdev_children; c++)
1218                 if (vdev_uses_zvols(vd->vdev_child[c]))
1219                         return (B_TRUE);
1220         return (B_FALSE);
1221 }
1222
1223 void
1224 vdev_open_children(vdev_t *vd)
1225 {
1226         taskq_t *tq;
1227         int children = vd->vdev_children;
1228
1229         /*
1230          * in order to handle pools on top of zvols, do the opens
1231          * in a single thread so that the same thread holds the
1232          * spa_namespace_lock
1233          */
1234         if (B_TRUE || vdev_uses_zvols(vd)) {
1235                 for (int c = 0; c < children; c++)
1236                         vd->vdev_child[c]->vdev_open_error =
1237                             vdev_open(vd->vdev_child[c]);
1238                 return;
1239         }
1240         tq = taskq_create("vdev_open", children, minclsyspri,
1241             children, children, TASKQ_PREPOPULATE);
1242
1243         for (int c = 0; c < children; c++)
1244                 VERIFY(taskq_dispatch(tq, vdev_open_child, vd->vdev_child[c],
1245                     TQ_SLEEP) != 0);
1246
1247         taskq_destroy(tq);
1248 }
1249
1250 /*
1251  * Prepare a virtual device for access.
1252  */
1253 int
1254 vdev_open(vdev_t *vd)
1255 {
1256         spa_t *spa = vd->vdev_spa;
1257         int error;
1258         uint64_t osize = 0;
1259         uint64_t max_osize = 0;
1260         uint64_t asize, max_asize, psize;
1261         uint64_t logical_ashift = 0;
1262         uint64_t physical_ashift = 0;
1263
1264         ASSERT(vd->vdev_open_thread == curthread ||
1265             spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1266         ASSERT(vd->vdev_state == VDEV_STATE_CLOSED ||
1267             vd->vdev_state == VDEV_STATE_CANT_OPEN ||
1268             vd->vdev_state == VDEV_STATE_OFFLINE);
1269
1270         vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
1271         vd->vdev_cant_read = B_FALSE;
1272         vd->vdev_cant_write = B_FALSE;
1273         vd->vdev_notrim = B_FALSE;
1274         vd->vdev_min_asize = vdev_get_min_asize(vd);
1275
1276         /*
1277          * If this vdev is not removed, check its fault status.  If it's
1278          * faulted, bail out of the open.
1279          */
1280         if (!vd->vdev_removed && vd->vdev_faulted) {
1281                 ASSERT(vd->vdev_children == 0);
1282                 ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
1283                     vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
1284                 vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1285                     vd->vdev_label_aux);
1286                 return (SET_ERROR(ENXIO));
1287         } else if (vd->vdev_offline) {
1288                 ASSERT(vd->vdev_children == 0);
1289                 vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE, VDEV_AUX_NONE);
1290                 return (SET_ERROR(ENXIO));
1291         }
1292
1293         error = vd->vdev_ops->vdev_op_open(vd, &osize, &max_osize,
1294             &logical_ashift, &physical_ashift);
1295
1296         /*
1297          * Reset the vdev_reopening flag so that we actually close
1298          * the vdev on error.
1299          */
1300         vd->vdev_reopening = B_FALSE;
1301         if (zio_injection_enabled && error == 0)
1302                 error = zio_handle_device_injection(vd, NULL, ENXIO);
1303
1304         if (error) {
1305                 if (vd->vdev_removed &&
1306                     vd->vdev_stat.vs_aux != VDEV_AUX_OPEN_FAILED)
1307                         vd->vdev_removed = B_FALSE;
1308
1309                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1310                     vd->vdev_stat.vs_aux);
1311                 return (error);
1312         }
1313
1314         vd->vdev_removed = B_FALSE;
1315
1316         /*
1317          * Recheck the faulted flag now that we have confirmed that
1318          * the vdev is accessible.  If we're faulted, bail.
1319          */
1320         if (vd->vdev_faulted) {
1321                 ASSERT(vd->vdev_children == 0);
1322                 ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
1323                     vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
1324                 vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1325                     vd->vdev_label_aux);
1326                 return (SET_ERROR(ENXIO));
1327         }
1328
1329         if (vd->vdev_degraded) {
1330                 ASSERT(vd->vdev_children == 0);
1331                 vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
1332                     VDEV_AUX_ERR_EXCEEDED);
1333         } else {
1334                 vdev_set_state(vd, B_TRUE, VDEV_STATE_HEALTHY, 0);
1335         }
1336
1337         /*
1338          * For hole or missing vdevs we just return success.
1339          */
1340         if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops)
1341                 return (0);
1342
1343         if (zfs_trim_enabled && !vd->vdev_notrim && vd->vdev_ops->vdev_op_leaf)
1344                 trim_map_create(vd);
1345
1346         for (int c = 0; c < vd->vdev_children; c++) {
1347                 if (vd->vdev_child[c]->vdev_state != VDEV_STATE_HEALTHY) {
1348                         vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
1349                             VDEV_AUX_NONE);
1350                         break;
1351                 }
1352         }
1353
1354         osize = P2ALIGN(osize, (uint64_t)sizeof (vdev_label_t));
1355         max_osize = P2ALIGN(max_osize, (uint64_t)sizeof (vdev_label_t));
1356
1357         if (vd->vdev_children == 0) {
1358                 if (osize < SPA_MINDEVSIZE) {
1359                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1360                             VDEV_AUX_TOO_SMALL);
1361                         return (SET_ERROR(EOVERFLOW));
1362                 }
1363                 psize = osize;
1364                 asize = osize - (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE);
1365                 max_asize = max_osize - (VDEV_LABEL_START_SIZE +
1366                     VDEV_LABEL_END_SIZE);
1367         } else {
1368                 if (vd->vdev_parent != NULL && osize < SPA_MINDEVSIZE -
1369                     (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE)) {
1370                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1371                             VDEV_AUX_TOO_SMALL);
1372                         return (SET_ERROR(EOVERFLOW));
1373                 }
1374                 psize = 0;
1375                 asize = osize;
1376                 max_asize = max_osize;
1377         }
1378
1379         vd->vdev_psize = psize;
1380
1381         /*
1382          * Make sure the allocatable size hasn't shrunk too much.
1383          */
1384         if (asize < vd->vdev_min_asize) {
1385                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1386                     VDEV_AUX_BAD_LABEL);
1387                 return (SET_ERROR(EINVAL));
1388         }
1389
1390         vd->vdev_physical_ashift =
1391             MAX(physical_ashift, vd->vdev_physical_ashift);
1392         vd->vdev_logical_ashift = MAX(logical_ashift, vd->vdev_logical_ashift);
1393         vd->vdev_ashift = MAX(vd->vdev_logical_ashift, vd->vdev_ashift);
1394
1395         if (vd->vdev_logical_ashift > SPA_MAXASHIFT) {
1396                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1397                     VDEV_AUX_ASHIFT_TOO_BIG);
1398                 return (EINVAL);
1399         }
1400
1401         if (vd->vdev_asize == 0) {
1402                 /*
1403                  * This is the first-ever open, so use the computed values.
1404                  * For testing purposes, a higher ashift can be requested.
1405                  */
1406                 vd->vdev_asize = asize;
1407                 vd->vdev_max_asize = max_asize;
1408         } else {
1409                 /*
1410                  * Make sure the alignment requirement hasn't increased.
1411                  */
1412                 if (vd->vdev_ashift > vd->vdev_top->vdev_ashift &&
1413                     vd->vdev_ops->vdev_op_leaf) {
1414                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1415                             VDEV_AUX_BAD_LABEL);
1416                         return (EINVAL);
1417                 }
1418                 vd->vdev_max_asize = max_asize;
1419         }
1420
1421         /*
1422          * If all children are healthy we update asize if either:
1423          * The asize has increased, due to a device expansion caused by dynamic
1424          * LUN growth or vdev replacement, and automatic expansion is enabled;
1425          * making the additional space available.
1426          *
1427          * The asize has decreased, due to a device shrink usually caused by a
1428          * vdev replace with a smaller device. This ensures that calculations
1429          * based of max_asize and asize e.g. esize are always valid. It's safe
1430          * to do this as we've already validated that asize is greater than
1431          * vdev_min_asize.
1432          */
1433         if (vd->vdev_state == VDEV_STATE_HEALTHY &&
1434             ((asize > vd->vdev_asize &&
1435             (vd->vdev_expanding || spa->spa_autoexpand)) ||
1436             (asize < vd->vdev_asize)))
1437                 vd->vdev_asize = asize;
1438
1439         vdev_set_min_asize(vd);
1440
1441         /*
1442          * Ensure we can issue some IO before declaring the
1443          * vdev open for business.
1444          */
1445         if (vd->vdev_ops->vdev_op_leaf &&
1446             (error = zio_wait(vdev_probe(vd, NULL))) != 0) {
1447                 vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1448                     VDEV_AUX_ERR_EXCEEDED);
1449                 return (error);
1450         }
1451
1452         /*
1453          * Track the min and max ashift values for normal data devices.
1454          */
1455         if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
1456             !vd->vdev_islog && vd->vdev_aux == NULL) {
1457                 if (vd->vdev_ashift > spa->spa_max_ashift)
1458                         spa->spa_max_ashift = vd->vdev_ashift;
1459                 if (vd->vdev_ashift < spa->spa_min_ashift)
1460                         spa->spa_min_ashift = vd->vdev_ashift;
1461         }
1462
1463         /*
1464          * If a leaf vdev has a DTL, and seems healthy, then kick off a
1465          * resilver.  But don't do this if we are doing a reopen for a scrub,
1466          * since this would just restart the scrub we are already doing.
1467          */
1468         if (vd->vdev_ops->vdev_op_leaf && !spa->spa_scrub_reopen &&
1469             vdev_resilver_needed(vd, NULL, NULL))
1470                 spa_async_request(spa, SPA_ASYNC_RESILVER);
1471
1472         return (0);
1473 }
1474
1475 /*
1476  * Called once the vdevs are all opened, this routine validates the label
1477  * contents.  This needs to be done before vdev_load() so that we don't
1478  * inadvertently do repair I/Os to the wrong device.
1479  *
1480  * If 'strict' is false ignore the spa guid check. This is necessary because
1481  * if the machine crashed during a re-guid the new guid might have been written
1482  * to all of the vdev labels, but not the cached config. The strict check
1483  * will be performed when the pool is opened again using the mos config.
1484  *
1485  * This function will only return failure if one of the vdevs indicates that it
1486  * has since been destroyed or exported.  This is only possible if
1487  * /etc/zfs/zpool.cache was readonly at the time.  Otherwise, the vdev state
1488  * will be updated but the function will return 0.
1489  */
1490 int
1491 vdev_validate(vdev_t *vd, boolean_t strict)
1492 {
1493         spa_t *spa = vd->vdev_spa;
1494         nvlist_t *label;
1495         uint64_t guid = 0, top_guid;
1496         uint64_t state;
1497
1498         for (int c = 0; c < vd->vdev_children; c++)
1499                 if (vdev_validate(vd->vdev_child[c], strict) != 0)
1500                         return (SET_ERROR(EBADF));
1501
1502         /*
1503          * If the device has already failed, or was marked offline, don't do
1504          * any further validation.  Otherwise, label I/O will fail and we will
1505          * overwrite the previous state.
1506          */
1507         if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd)) {
1508                 uint64_t aux_guid = 0;
1509                 nvlist_t *nvl;
1510                 uint64_t txg = spa_last_synced_txg(spa) != 0 ?
1511                     spa_last_synced_txg(spa) : -1ULL;
1512
1513                 if ((label = vdev_label_read_config(vd, txg)) == NULL) {
1514                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1515                             VDEV_AUX_BAD_LABEL);
1516                         return (0);
1517                 }
1518
1519                 /*
1520                  * Determine if this vdev has been split off into another
1521                  * pool.  If so, then refuse to open it.
1522                  */
1523                 if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_SPLIT_GUID,
1524                     &aux_guid) == 0 && aux_guid == spa_guid(spa)) {
1525                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1526                             VDEV_AUX_SPLIT_POOL);
1527                         nvlist_free(label);
1528                         return (0);
1529                 }
1530
1531                 if (strict && (nvlist_lookup_uint64(label,
1532                     ZPOOL_CONFIG_POOL_GUID, &guid) != 0 ||
1533                     guid != spa_guid(spa))) {
1534                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1535                             VDEV_AUX_CORRUPT_DATA);
1536                         nvlist_free(label);
1537                         return (0);
1538                 }
1539
1540                 if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_VDEV_TREE, &nvl)
1541                     != 0 || nvlist_lookup_uint64(nvl, ZPOOL_CONFIG_ORIG_GUID,
1542                     &aux_guid) != 0)
1543                         aux_guid = 0;
1544
1545                 /*
1546                  * If this vdev just became a top-level vdev because its
1547                  * sibling was detached, it will have adopted the parent's
1548                  * vdev guid -- but the label may or may not be on disk yet.
1549                  * Fortunately, either version of the label will have the
1550                  * same top guid, so if we're a top-level vdev, we can
1551                  * safely compare to that instead.
1552                  *
1553                  * If we split this vdev off instead, then we also check the
1554                  * original pool's guid.  We don't want to consider the vdev
1555                  * corrupt if it is partway through a split operation.
1556                  */
1557                 if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
1558                     &guid) != 0 ||
1559                     nvlist_lookup_uint64(label, ZPOOL_CONFIG_TOP_GUID,
1560                     &top_guid) != 0 ||
1561                     ((vd->vdev_guid != guid && vd->vdev_guid != aux_guid) &&
1562                     (vd->vdev_guid != top_guid || vd != vd->vdev_top))) {
1563                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1564                             VDEV_AUX_CORRUPT_DATA);
1565                         nvlist_free(label);
1566                         return (0);
1567                 }
1568
1569                 if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
1570                     &state) != 0) {
1571                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1572                             VDEV_AUX_CORRUPT_DATA);
1573                         nvlist_free(label);
1574                         return (0);
1575                 }
1576
1577                 nvlist_free(label);
1578
1579                 /*
1580                  * If this is a verbatim import, no need to check the
1581                  * state of the pool.
1582                  */
1583                 if (!(spa->spa_import_flags & ZFS_IMPORT_VERBATIM) &&
1584                     spa_load_state(spa) == SPA_LOAD_OPEN &&
1585                     state != POOL_STATE_ACTIVE)
1586                         return (SET_ERROR(EBADF));
1587
1588                 /*
1589                  * If we were able to open and validate a vdev that was
1590                  * previously marked permanently unavailable, clear that state
1591                  * now.
1592                  */
1593                 if (vd->vdev_not_present)
1594                         vd->vdev_not_present = 0;
1595         }
1596
1597         return (0);
1598 }
1599
1600 /*
1601  * Close a virtual device.
1602  */
1603 void
1604 vdev_close(vdev_t *vd)
1605 {
1606         spa_t *spa = vd->vdev_spa;
1607         vdev_t *pvd = vd->vdev_parent;
1608
1609         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1610
1611         /*
1612          * If our parent is reopening, then we are as well, unless we are
1613          * going offline.
1614          */
1615         if (pvd != NULL && pvd->vdev_reopening)
1616                 vd->vdev_reopening = (pvd->vdev_reopening && !vd->vdev_offline);
1617
1618         vd->vdev_ops->vdev_op_close(vd);
1619
1620         vdev_cache_purge(vd);
1621
1622         if (vd->vdev_ops->vdev_op_leaf)
1623                 trim_map_destroy(vd);
1624
1625         /*
1626          * We record the previous state before we close it, so that if we are
1627          * doing a reopen(), we don't generate FMA ereports if we notice that
1628          * it's still faulted.
1629          */
1630         vd->vdev_prevstate = vd->vdev_state;
1631
1632         if (vd->vdev_offline)
1633                 vd->vdev_state = VDEV_STATE_OFFLINE;
1634         else
1635                 vd->vdev_state = VDEV_STATE_CLOSED;
1636         vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
1637 }
1638
1639 void
1640 vdev_hold(vdev_t *vd)
1641 {
1642         spa_t *spa = vd->vdev_spa;
1643
1644         ASSERT(spa_is_root(spa));
1645         if (spa->spa_state == POOL_STATE_UNINITIALIZED)
1646                 return;
1647
1648         for (int c = 0; c < vd->vdev_children; c++)
1649                 vdev_hold(vd->vdev_child[c]);
1650
1651         if (vd->vdev_ops->vdev_op_leaf)
1652                 vd->vdev_ops->vdev_op_hold(vd);
1653 }
1654
1655 void
1656 vdev_rele(vdev_t *vd)
1657 {
1658         spa_t *spa = vd->vdev_spa;
1659
1660         ASSERT(spa_is_root(spa));
1661         for (int c = 0; c < vd->vdev_children; c++)
1662                 vdev_rele(vd->vdev_child[c]);
1663
1664         if (vd->vdev_ops->vdev_op_leaf)
1665                 vd->vdev_ops->vdev_op_rele(vd);
1666 }
1667
1668 /*
1669  * Reopen all interior vdevs and any unopened leaves.  We don't actually
1670  * reopen leaf vdevs which had previously been opened as they might deadlock
1671  * on the spa_config_lock.  Instead we only obtain the leaf's physical size.
1672  * If the leaf has never been opened then open it, as usual.
1673  */
1674 void
1675 vdev_reopen(vdev_t *vd)
1676 {
1677         spa_t *spa = vd->vdev_spa;
1678
1679         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1680
1681         /* set the reopening flag unless we're taking the vdev offline */
1682         vd->vdev_reopening = !vd->vdev_offline;
1683         vdev_close(vd);
1684         (void) vdev_open(vd);
1685
1686         /*
1687          * Call vdev_validate() here to make sure we have the same device.
1688          * Otherwise, a device with an invalid label could be successfully
1689          * opened in response to vdev_reopen().
1690          */
1691         if (vd->vdev_aux) {
1692                 (void) vdev_validate_aux(vd);
1693                 if (vdev_readable(vd) && vdev_writeable(vd) &&
1694                     vd->vdev_aux == &spa->spa_l2cache &&
1695                     !l2arc_vdev_present(vd))
1696                         l2arc_add_vdev(spa, vd);
1697         } else {
1698                 (void) vdev_validate(vd, B_TRUE);
1699         }
1700
1701         /*
1702          * Reassess parent vdev's health.
1703          */
1704         vdev_propagate_state(vd);
1705 }
1706
1707 int
1708 vdev_create(vdev_t *vd, uint64_t txg, boolean_t isreplacing)
1709 {
1710         int error;
1711
1712         /*
1713          * Normally, partial opens (e.g. of a mirror) are allowed.
1714          * For a create, however, we want to fail the request if
1715          * there are any components we can't open.
1716          */
1717         error = vdev_open(vd);
1718
1719         if (error || vd->vdev_state != VDEV_STATE_HEALTHY) {
1720                 vdev_close(vd);
1721                 return (error ? error : ENXIO);
1722         }
1723
1724         /*
1725          * Recursively load DTLs and initialize all labels.
1726          */
1727         if ((error = vdev_dtl_load(vd)) != 0 ||
1728             (error = vdev_label_init(vd, txg, isreplacing ?
1729             VDEV_LABEL_REPLACE : VDEV_LABEL_CREATE)) != 0) {
1730                 vdev_close(vd);
1731                 return (error);
1732         }
1733
1734         return (0);
1735 }
1736
1737 void
1738 vdev_metaslab_set_size(vdev_t *vd)
1739 {
1740         /*
1741          * Aim for roughly metaslabs_per_vdev (default 200) metaslabs per vdev.
1742          */
1743         vd->vdev_ms_shift = highbit64(vd->vdev_asize / metaslabs_per_vdev);
1744         vd->vdev_ms_shift = MAX(vd->vdev_ms_shift, SPA_MAXBLOCKSHIFT);
1745 }
1746
1747 /*
1748  * Maximize performance by inflating the configured ashift for top level
1749  * vdevs to be as close to the physical ashift as possible while maintaining
1750  * administrator defined limits and ensuring it doesn't go below the
1751  * logical ashift.
1752  */
1753 void
1754 vdev_ashift_optimize(vdev_t *vd)
1755 {
1756         if (vd == vd->vdev_top) {
1757                 if (vd->vdev_ashift < vd->vdev_physical_ashift) {
1758                         vd->vdev_ashift = MIN(
1759                             MAX(zfs_max_auto_ashift, vd->vdev_ashift),
1760                             MAX(zfs_min_auto_ashift, vd->vdev_physical_ashift));
1761                 } else {
1762                         /*
1763                          * Unusual case where logical ashift > physical ashift
1764                          * so we can't cap the calculated ashift based on max
1765                          * ashift as that would cause failures.
1766                          * We still check if we need to increase it to match
1767                          * the min ashift.
1768                          */
1769                         vd->vdev_ashift = MAX(zfs_min_auto_ashift,
1770                             vd->vdev_ashift);
1771                 }
1772         }
1773 }
1774
1775 void
1776 vdev_dirty(vdev_t *vd, int flags, void *arg, uint64_t txg)
1777 {
1778         ASSERT(vd == vd->vdev_top);
1779         ASSERT(!vd->vdev_ishole);
1780         ASSERT(ISP2(flags));
1781         ASSERT(spa_writeable(vd->vdev_spa));
1782
1783         if (flags & VDD_METASLAB)
1784                 (void) txg_list_add(&vd->vdev_ms_list, arg, txg);
1785
1786         if (flags & VDD_DTL)
1787                 (void) txg_list_add(&vd->vdev_dtl_list, arg, txg);
1788
1789         (void) txg_list_add(&vd->vdev_spa->spa_vdev_txg_list, vd, txg);
1790 }
1791
1792 void
1793 vdev_dirty_leaves(vdev_t *vd, int flags, uint64_t txg)
1794 {
1795         for (int c = 0; c < vd->vdev_children; c++)
1796                 vdev_dirty_leaves(vd->vdev_child[c], flags, txg);
1797
1798         if (vd->vdev_ops->vdev_op_leaf)
1799                 vdev_dirty(vd->vdev_top, flags, vd, txg);
1800 }
1801
1802 /*
1803  * DTLs.
1804  *
1805  * A vdev's DTL (dirty time log) is the set of transaction groups for which
1806  * the vdev has less than perfect replication.  There are four kinds of DTL:
1807  *
1808  * DTL_MISSING: txgs for which the vdev has no valid copies of the data
1809  *
1810  * DTL_PARTIAL: txgs for which data is available, but not fully replicated
1811  *
1812  * DTL_SCRUB: the txgs that could not be repaired by the last scrub; upon
1813  *      scrub completion, DTL_SCRUB replaces DTL_MISSING in the range of
1814  *      txgs that was scrubbed.
1815  *
1816  * DTL_OUTAGE: txgs which cannot currently be read, whether due to
1817  *      persistent errors or just some device being offline.
1818  *      Unlike the other three, the DTL_OUTAGE map is not generally
1819  *      maintained; it's only computed when needed, typically to
1820  *      determine whether a device can be detached.
1821  *
1822  * For leaf vdevs, DTL_MISSING and DTL_PARTIAL are identical: the device
1823  * either has the data or it doesn't.
1824  *
1825  * For interior vdevs such as mirror and RAID-Z the picture is more complex.
1826  * A vdev's DTL_PARTIAL is the union of its children's DTL_PARTIALs, because
1827  * if any child is less than fully replicated, then so is its parent.
1828  * A vdev's DTL_MISSING is a modified union of its children's DTL_MISSINGs,
1829  * comprising only those txgs which appear in 'maxfaults' or more children;
1830  * those are the txgs we don't have enough replication to read.  For example,
1831  * double-parity RAID-Z can tolerate up to two missing devices (maxfaults == 2);
1832  * thus, its DTL_MISSING consists of the set of txgs that appear in more than
1833  * two child DTL_MISSING maps.
1834  *
1835  * It should be clear from the above that to compute the DTLs and outage maps
1836  * for all vdevs, it suffices to know just the leaf vdevs' DTL_MISSING maps.
1837  * Therefore, that is all we keep on disk.  When loading the pool, or after
1838  * a configuration change, we generate all other DTLs from first principles.
1839  */
1840 void
1841 vdev_dtl_dirty(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
1842 {
1843         range_tree_t *rt = vd->vdev_dtl[t];
1844
1845         ASSERT(t < DTL_TYPES);
1846         ASSERT(vd != vd->vdev_spa->spa_root_vdev);
1847         ASSERT(spa_writeable(vd->vdev_spa));
1848
1849         mutex_enter(rt->rt_lock);
1850         if (!range_tree_contains(rt, txg, size))
1851                 range_tree_add(rt, txg, size);
1852         mutex_exit(rt->rt_lock);
1853 }
1854
1855 boolean_t
1856 vdev_dtl_contains(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
1857 {
1858         range_tree_t *rt = vd->vdev_dtl[t];
1859         boolean_t dirty = B_FALSE;
1860
1861         ASSERT(t < DTL_TYPES);
1862         ASSERT(vd != vd->vdev_spa->spa_root_vdev);
1863
1864         mutex_enter(rt->rt_lock);
1865         if (range_tree_space(rt) != 0)
1866                 dirty = range_tree_contains(rt, txg, size);
1867         mutex_exit(rt->rt_lock);
1868
1869         return (dirty);
1870 }
1871
1872 boolean_t
1873 vdev_dtl_empty(vdev_t *vd, vdev_dtl_type_t t)
1874 {
1875         range_tree_t *rt = vd->vdev_dtl[t];
1876         boolean_t empty;
1877
1878         mutex_enter(rt->rt_lock);
1879         empty = (range_tree_space(rt) == 0);
1880         mutex_exit(rt->rt_lock);
1881
1882         return (empty);
1883 }
1884
1885 /*
1886  * Returns the lowest txg in the DTL range.
1887  */
1888 static uint64_t
1889 vdev_dtl_min(vdev_t *vd)
1890 {
1891         range_seg_t *rs;
1892
1893         ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
1894         ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
1895         ASSERT0(vd->vdev_children);
1896
1897         rs = avl_first(&vd->vdev_dtl[DTL_MISSING]->rt_root);
1898         return (rs->rs_start - 1);
1899 }
1900
1901 /*
1902  * Returns the highest txg in the DTL.
1903  */
1904 static uint64_t
1905 vdev_dtl_max(vdev_t *vd)
1906 {
1907         range_seg_t *rs;
1908
1909         ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
1910         ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
1911         ASSERT0(vd->vdev_children);
1912
1913         rs = avl_last(&vd->vdev_dtl[DTL_MISSING]->rt_root);
1914         return (rs->rs_end);
1915 }
1916
1917 /*
1918  * Determine if a resilvering vdev should remove any DTL entries from
1919  * its range. If the vdev was resilvering for the entire duration of the
1920  * scan then it should excise that range from its DTLs. Otherwise, this
1921  * vdev is considered partially resilvered and should leave its DTL
1922  * entries intact. The comment in vdev_dtl_reassess() describes how we
1923  * excise the DTLs.
1924  */
1925 static boolean_t
1926 vdev_dtl_should_excise(vdev_t *vd)
1927 {
1928         spa_t *spa = vd->vdev_spa;
1929         dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
1930
1931         ASSERT0(scn->scn_phys.scn_errors);
1932         ASSERT0(vd->vdev_children);
1933
1934         if (vd->vdev_state < VDEV_STATE_DEGRADED)
1935                 return (B_FALSE);
1936
1937         if (vd->vdev_resilver_txg == 0 ||
1938             range_tree_space(vd->vdev_dtl[DTL_MISSING]) == 0)
1939                 return (B_TRUE);
1940
1941         /*
1942          * When a resilver is initiated the scan will assign the scn_max_txg
1943          * value to the highest txg value that exists in all DTLs. If this
1944          * device's max DTL is not part of this scan (i.e. it is not in
1945          * the range (scn_min_txg, scn_max_txg] then it is not eligible
1946          * for excision.
1947          */
1948         if (vdev_dtl_max(vd) <= scn->scn_phys.scn_max_txg) {
1949                 ASSERT3U(scn->scn_phys.scn_min_txg, <=, vdev_dtl_min(vd));
1950                 ASSERT3U(scn->scn_phys.scn_min_txg, <, vd->vdev_resilver_txg);
1951                 ASSERT3U(vd->vdev_resilver_txg, <=, scn->scn_phys.scn_max_txg);
1952                 return (B_TRUE);
1953         }
1954         return (B_FALSE);
1955 }
1956
1957 /*
1958  * Reassess DTLs after a config change or scrub completion.
1959  */
1960 void
1961 vdev_dtl_reassess(vdev_t *vd, uint64_t txg, uint64_t scrub_txg, int scrub_done)
1962 {
1963         spa_t *spa = vd->vdev_spa;
1964         avl_tree_t reftree;
1965         int minref;
1966
1967         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1968
1969         for (int c = 0; c < vd->vdev_children; c++)
1970                 vdev_dtl_reassess(vd->vdev_child[c], txg,
1971                     scrub_txg, scrub_done);
1972
1973         if (vd == spa->spa_root_vdev || vd->vdev_ishole || vd->vdev_aux)
1974                 return;
1975
1976         if (vd->vdev_ops->vdev_op_leaf) {
1977                 dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
1978
1979                 mutex_enter(&vd->vdev_dtl_lock);
1980
1981                 /*
1982                  * If we've completed a scan cleanly then determine
1983                  * if this vdev should remove any DTLs. We only want to
1984                  * excise regions on vdevs that were available during
1985                  * the entire duration of this scan.
1986                  */
1987                 if (scrub_txg != 0 &&
1988                     (spa->spa_scrub_started ||
1989                     (scn != NULL && scn->scn_phys.scn_errors == 0)) &&
1990                     vdev_dtl_should_excise(vd)) {
1991                         /*
1992                          * We completed a scrub up to scrub_txg.  If we
1993                          * did it without rebooting, then the scrub dtl
1994                          * will be valid, so excise the old region and
1995                          * fold in the scrub dtl.  Otherwise, leave the
1996                          * dtl as-is if there was an error.
1997                          *
1998                          * There's little trick here: to excise the beginning
1999                          * of the DTL_MISSING map, we put it into a reference
2000                          * tree and then add a segment with refcnt -1 that
2001                          * covers the range [0, scrub_txg).  This means
2002                          * that each txg in that range has refcnt -1 or 0.
2003                          * We then add DTL_SCRUB with a refcnt of 2, so that
2004                          * entries in the range [0, scrub_txg) will have a
2005                          * positive refcnt -- either 1 or 2.  We then convert
2006                          * the reference tree into the new DTL_MISSING map.
2007                          */
2008                         space_reftree_create(&reftree);
2009                         space_reftree_add_map(&reftree,
2010                             vd->vdev_dtl[DTL_MISSING], 1);
2011                         space_reftree_add_seg(&reftree, 0, scrub_txg, -1);
2012                         space_reftree_add_map(&reftree,
2013                             vd->vdev_dtl[DTL_SCRUB], 2);
2014                         space_reftree_generate_map(&reftree,
2015                             vd->vdev_dtl[DTL_MISSING], 1);
2016                         space_reftree_destroy(&reftree);
2017                 }
2018                 range_tree_vacate(vd->vdev_dtl[DTL_PARTIAL], NULL, NULL);
2019                 range_tree_walk(vd->vdev_dtl[DTL_MISSING],
2020                     range_tree_add, vd->vdev_dtl[DTL_PARTIAL]);
2021                 if (scrub_done)
2022                         range_tree_vacate(vd->vdev_dtl[DTL_SCRUB], NULL, NULL);
2023                 range_tree_vacate(vd->vdev_dtl[DTL_OUTAGE], NULL, NULL);
2024                 if (!vdev_readable(vd))
2025                         range_tree_add(vd->vdev_dtl[DTL_OUTAGE], 0, -1ULL);
2026                 else
2027                         range_tree_walk(vd->vdev_dtl[DTL_MISSING],
2028                             range_tree_add, vd->vdev_dtl[DTL_OUTAGE]);
2029
2030                 /*
2031                  * If the vdev was resilvering and no longer has any
2032                  * DTLs then reset its resilvering flag and dirty
2033                  * the top level so that we persist the change.
2034                  */
2035                 if (vd->vdev_resilver_txg != 0 &&
2036                     range_tree_space(vd->vdev_dtl[DTL_MISSING]) == 0 &&
2037                     range_tree_space(vd->vdev_dtl[DTL_OUTAGE]) == 0) {
2038                         vd->vdev_resilver_txg = 0;
2039                         vdev_config_dirty(vd->vdev_top);
2040                 }
2041
2042                 mutex_exit(&vd->vdev_dtl_lock);
2043
2044                 if (txg != 0)
2045                         vdev_dirty(vd->vdev_top, VDD_DTL, vd, txg);
2046                 return;
2047         }
2048
2049         mutex_enter(&vd->vdev_dtl_lock);
2050         for (int t = 0; t < DTL_TYPES; t++) {
2051                 /* account for child's outage in parent's missing map */
2052                 int s = (t == DTL_MISSING) ? DTL_OUTAGE: t;
2053                 if (t == DTL_SCRUB)
2054                         continue;                       /* leaf vdevs only */
2055                 if (t == DTL_PARTIAL)
2056                         minref = 1;                     /* i.e. non-zero */
2057                 else if (vd->vdev_nparity != 0)
2058                         minref = vd->vdev_nparity + 1;  /* RAID-Z */
2059                 else
2060                         minref = vd->vdev_children;     /* any kind of mirror */
2061                 space_reftree_create(&reftree);
2062                 for (int c = 0; c < vd->vdev_children; c++) {
2063                         vdev_t *cvd = vd->vdev_child[c];
2064                         mutex_enter(&cvd->vdev_dtl_lock);
2065                         space_reftree_add_map(&reftree, cvd->vdev_dtl[s], 1);
2066                         mutex_exit(&cvd->vdev_dtl_lock);
2067                 }
2068                 space_reftree_generate_map(&reftree, vd->vdev_dtl[t], minref);
2069                 space_reftree_destroy(&reftree);
2070         }
2071         mutex_exit(&vd->vdev_dtl_lock);
2072 }
2073
2074 int
2075 vdev_dtl_load(vdev_t *vd)
2076 {
2077         spa_t *spa = vd->vdev_spa;
2078         objset_t *mos = spa->spa_meta_objset;
2079         int error = 0;
2080
2081         if (vd->vdev_ops->vdev_op_leaf && vd->vdev_dtl_object != 0) {
2082                 ASSERT(!vd->vdev_ishole);
2083
2084                 error = space_map_open(&vd->vdev_dtl_sm, mos,
2085                     vd->vdev_dtl_object, 0, -1ULL, 0, &vd->vdev_dtl_lock);
2086                 if (error)
2087                         return (error);
2088                 ASSERT(vd->vdev_dtl_sm != NULL);
2089
2090                 mutex_enter(&vd->vdev_dtl_lock);
2091
2092                 /*
2093                  * Now that we've opened the space_map we need to update
2094                  * the in-core DTL.
2095                  */
2096                 space_map_update(vd->vdev_dtl_sm);
2097
2098                 error = space_map_load(vd->vdev_dtl_sm,
2099                     vd->vdev_dtl[DTL_MISSING], SM_ALLOC);
2100                 mutex_exit(&vd->vdev_dtl_lock);
2101
2102                 return (error);
2103         }
2104
2105         for (int c = 0; c < vd->vdev_children; c++) {
2106                 error = vdev_dtl_load(vd->vdev_child[c]);
2107                 if (error != 0)
2108                         break;
2109         }
2110
2111         return (error);
2112 }
2113
2114 void
2115 vdev_destroy_unlink_zap(vdev_t *vd, uint64_t zapobj, dmu_tx_t *tx)
2116 {
2117         spa_t *spa = vd->vdev_spa;
2118
2119         VERIFY0(zap_destroy(spa->spa_meta_objset, zapobj, tx));
2120         VERIFY0(zap_remove_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
2121             zapobj, tx));
2122 }
2123
2124 uint64_t
2125 vdev_create_link_zap(vdev_t *vd, dmu_tx_t *tx)
2126 {
2127         spa_t *spa = vd->vdev_spa;
2128         uint64_t zap = zap_create(spa->spa_meta_objset, DMU_OTN_ZAP_METADATA,
2129             DMU_OT_NONE, 0, tx);
2130
2131         ASSERT(zap != 0);
2132         VERIFY0(zap_add_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
2133             zap, tx));
2134
2135         return (zap);
2136 }
2137
2138 void
2139 vdev_construct_zaps(vdev_t *vd, dmu_tx_t *tx)
2140 {
2141         if (vd->vdev_ops != &vdev_hole_ops &&
2142             vd->vdev_ops != &vdev_missing_ops &&
2143             vd->vdev_ops != &vdev_root_ops &&
2144             !vd->vdev_top->vdev_removing) {
2145                 if (vd->vdev_ops->vdev_op_leaf && vd->vdev_leaf_zap == 0) {
2146                         vd->vdev_leaf_zap = vdev_create_link_zap(vd, tx);
2147                 }
2148                 if (vd == vd->vdev_top && vd->vdev_top_zap == 0) {
2149                         vd->vdev_top_zap = vdev_create_link_zap(vd, tx);
2150                 }
2151         }
2152         for (uint64_t i = 0; i < vd->vdev_children; i++) {
2153                 vdev_construct_zaps(vd->vdev_child[i], tx);
2154         }
2155 }
2156
2157 void
2158 vdev_dtl_sync(vdev_t *vd, uint64_t txg)
2159 {
2160         spa_t *spa = vd->vdev_spa;
2161         range_tree_t *rt = vd->vdev_dtl[DTL_MISSING];
2162         objset_t *mos = spa->spa_meta_objset;
2163         range_tree_t *rtsync;
2164         kmutex_t rtlock;
2165         dmu_tx_t *tx;
2166         uint64_t object = space_map_object(vd->vdev_dtl_sm);
2167
2168         ASSERT(!vd->vdev_ishole);
2169         ASSERT(vd->vdev_ops->vdev_op_leaf);
2170
2171         tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
2172
2173         if (vd->vdev_detached || vd->vdev_top->vdev_removing) {
2174                 mutex_enter(&vd->vdev_dtl_lock);
2175                 space_map_free(vd->vdev_dtl_sm, tx);
2176                 space_map_close(vd->vdev_dtl_sm);
2177                 vd->vdev_dtl_sm = NULL;
2178                 mutex_exit(&vd->vdev_dtl_lock);
2179
2180                 /*
2181                  * We only destroy the leaf ZAP for detached leaves or for
2182                  * removed log devices. Removed data devices handle leaf ZAP
2183                  * cleanup later, once cancellation is no longer possible.
2184                  */
2185                 if (vd->vdev_leaf_zap != 0 && (vd->vdev_detached ||
2186                     vd->vdev_top->vdev_islog)) {
2187                         vdev_destroy_unlink_zap(vd, vd->vdev_leaf_zap, tx);
2188                         vd->vdev_leaf_zap = 0;
2189                 }
2190
2191                 dmu_tx_commit(tx);
2192                 return;
2193         }
2194
2195         if (vd->vdev_dtl_sm == NULL) {
2196                 uint64_t new_object;
2197
2198                 new_object = space_map_alloc(mos, tx);
2199                 VERIFY3U(new_object, !=, 0);
2200
2201                 VERIFY0(space_map_open(&vd->vdev_dtl_sm, mos, new_object,
2202                     0, -1ULL, 0, &vd->vdev_dtl_lock));
2203                 ASSERT(vd->vdev_dtl_sm != NULL);
2204         }
2205
2206         bzero(&rtlock, sizeof(rtlock));
2207         mutex_init(&rtlock, NULL, MUTEX_DEFAULT, NULL);
2208
2209         rtsync = range_tree_create(NULL, NULL, &rtlock);
2210
2211         mutex_enter(&rtlock);
2212
2213         mutex_enter(&vd->vdev_dtl_lock);
2214         range_tree_walk(rt, range_tree_add, rtsync);
2215         mutex_exit(&vd->vdev_dtl_lock);
2216
2217         space_map_truncate(vd->vdev_dtl_sm, tx);
2218         space_map_write(vd->vdev_dtl_sm, rtsync, SM_ALLOC, tx);
2219         range_tree_vacate(rtsync, NULL, NULL);
2220
2221         range_tree_destroy(rtsync);
2222
2223         mutex_exit(&rtlock);
2224         mutex_destroy(&rtlock);
2225
2226         /*
2227          * If the object for the space map has changed then dirty
2228          * the top level so that we update the config.
2229          */
2230         if (object != space_map_object(vd->vdev_dtl_sm)) {
2231                 zfs_dbgmsg("txg %llu, spa %s, DTL old object %llu, "
2232                     "new object %llu", txg, spa_name(spa), object,
2233                     space_map_object(vd->vdev_dtl_sm));
2234                 vdev_config_dirty(vd->vdev_top);
2235         }
2236
2237         dmu_tx_commit(tx);
2238
2239         mutex_enter(&vd->vdev_dtl_lock);
2240         space_map_update(vd->vdev_dtl_sm);
2241         mutex_exit(&vd->vdev_dtl_lock);
2242 }
2243
2244 /*
2245  * Determine whether the specified vdev can be offlined/detached/removed
2246  * without losing data.
2247  */
2248 boolean_t
2249 vdev_dtl_required(vdev_t *vd)
2250 {
2251         spa_t *spa = vd->vdev_spa;
2252         vdev_t *tvd = vd->vdev_top;
2253         uint8_t cant_read = vd->vdev_cant_read;
2254         boolean_t required;
2255
2256         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2257
2258         if (vd == spa->spa_root_vdev || vd == tvd)
2259                 return (B_TRUE);
2260
2261         /*
2262          * Temporarily mark the device as unreadable, and then determine
2263          * whether this results in any DTL outages in the top-level vdev.
2264          * If not, we can safely offline/detach/remove the device.
2265          */
2266         vd->vdev_cant_read = B_TRUE;
2267         vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
2268         required = !vdev_dtl_empty(tvd, DTL_OUTAGE);
2269         vd->vdev_cant_read = cant_read;
2270         vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
2271
2272         if (!required && zio_injection_enabled)
2273                 required = !!zio_handle_device_injection(vd, NULL, ECHILD);
2274
2275         return (required);
2276 }
2277
2278 /*
2279  * Determine if resilver is needed, and if so the txg range.
2280  */
2281 boolean_t
2282 vdev_resilver_needed(vdev_t *vd, uint64_t *minp, uint64_t *maxp)
2283 {
2284         boolean_t needed = B_FALSE;
2285         uint64_t thismin = UINT64_MAX;
2286         uint64_t thismax = 0;
2287
2288         if (vd->vdev_children == 0) {
2289                 mutex_enter(&vd->vdev_dtl_lock);
2290                 if (range_tree_space(vd->vdev_dtl[DTL_MISSING]) != 0 &&
2291                     vdev_writeable(vd)) {
2292
2293                         thismin = vdev_dtl_min(vd);
2294                         thismax = vdev_dtl_max(vd);
2295                         needed = B_TRUE;
2296                 }
2297                 mutex_exit(&vd->vdev_dtl_lock);
2298         } else {
2299                 for (int c = 0; c < vd->vdev_children; c++) {
2300                         vdev_t *cvd = vd->vdev_child[c];
2301                         uint64_t cmin, cmax;
2302
2303                         if (vdev_resilver_needed(cvd, &cmin, &cmax)) {
2304                                 thismin = MIN(thismin, cmin);
2305                                 thismax = MAX(thismax, cmax);
2306                                 needed = B_TRUE;
2307                         }
2308                 }
2309         }
2310
2311         if (needed && minp) {
2312                 *minp = thismin;
2313                 *maxp = thismax;
2314         }
2315         return (needed);
2316 }
2317
2318 void
2319 vdev_load(vdev_t *vd)
2320 {
2321         /*
2322          * Recursively load all children.
2323          */
2324         for (int c = 0; c < vd->vdev_children; c++)
2325                 vdev_load(vd->vdev_child[c]);
2326
2327         /*
2328          * If this is a top-level vdev, initialize its metaslabs.
2329          */
2330         if (vd == vd->vdev_top && !vd->vdev_ishole &&
2331             (vd->vdev_ashift == 0 || vd->vdev_asize == 0 ||
2332             vdev_metaslab_init(vd, 0) != 0))
2333                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2334                     VDEV_AUX_CORRUPT_DATA);
2335
2336         /*
2337          * If this is a leaf vdev, load its DTL.
2338          */
2339         if (vd->vdev_ops->vdev_op_leaf && vdev_dtl_load(vd) != 0)
2340                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2341                     VDEV_AUX_CORRUPT_DATA);
2342 }
2343
2344 /*
2345  * The special vdev case is used for hot spares and l2cache devices.  Its
2346  * sole purpose it to set the vdev state for the associated vdev.  To do this,
2347  * we make sure that we can open the underlying device, then try to read the
2348  * label, and make sure that the label is sane and that it hasn't been
2349  * repurposed to another pool.
2350  */
2351 int
2352 vdev_validate_aux(vdev_t *vd)
2353 {
2354         nvlist_t *label;
2355         uint64_t guid, version;
2356         uint64_t state;
2357
2358         if (!vdev_readable(vd))
2359                 return (0);
2360
2361         if ((label = vdev_label_read_config(vd, -1ULL)) == NULL) {
2362                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2363                     VDEV_AUX_CORRUPT_DATA);
2364                 return (-1);
2365         }
2366
2367         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_VERSION, &version) != 0 ||
2368             !SPA_VERSION_IS_SUPPORTED(version) ||
2369             nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0 ||
2370             guid != vd->vdev_guid ||
2371             nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE, &state) != 0) {
2372                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
2373                     VDEV_AUX_CORRUPT_DATA);
2374                 nvlist_free(label);
2375                 return (-1);
2376         }
2377
2378         /*
2379          * We don't actually check the pool state here.  If it's in fact in
2380          * use by another pool, we update this fact on the fly when requested.
2381          */
2382         nvlist_free(label);
2383         return (0);
2384 }
2385
2386 void
2387 vdev_remove(vdev_t *vd, uint64_t txg)
2388 {
2389         spa_t *spa = vd->vdev_spa;
2390         objset_t *mos = spa->spa_meta_objset;
2391         dmu_tx_t *tx;
2392
2393         tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
2394         ASSERT(vd == vd->vdev_top);
2395         ASSERT3U(txg, ==, spa_syncing_txg(spa));
2396
2397         if (vd->vdev_ms != NULL) {
2398                 metaslab_group_t *mg = vd->vdev_mg;
2399
2400                 metaslab_group_histogram_verify(mg);
2401                 metaslab_class_histogram_verify(mg->mg_class);
2402
2403                 for (int m = 0; m < vd->vdev_ms_count; m++) {
2404                         metaslab_t *msp = vd->vdev_ms[m];
2405
2406                         if (msp == NULL || msp->ms_sm == NULL)
2407                                 continue;
2408
2409                         mutex_enter(&msp->ms_lock);
2410                         /*
2411                          * If the metaslab was not loaded when the vdev
2412                          * was removed then the histogram accounting may
2413                          * not be accurate. Update the histogram information
2414                          * here so that we ensure that the metaslab group
2415                          * and metaslab class are up-to-date.
2416                          */
2417                         metaslab_group_histogram_remove(mg, msp);
2418
2419                         VERIFY0(space_map_allocated(msp->ms_sm));
2420                         space_map_free(msp->ms_sm, tx);
2421                         space_map_close(msp->ms_sm);
2422                         msp->ms_sm = NULL;
2423                         mutex_exit(&msp->ms_lock);
2424                 }
2425
2426                 metaslab_group_histogram_verify(mg);
2427                 metaslab_class_histogram_verify(mg->mg_class);
2428                 for (int i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
2429                         ASSERT0(mg->mg_histogram[i]);
2430
2431         }
2432
2433         if (vd->vdev_ms_array) {
2434                 (void) dmu_object_free(mos, vd->vdev_ms_array, tx);
2435                 vd->vdev_ms_array = 0;
2436         }
2437
2438         if (vd->vdev_islog && vd->vdev_top_zap != 0) {
2439                 vdev_destroy_unlink_zap(vd, vd->vdev_top_zap, tx);
2440                 vd->vdev_top_zap = 0;
2441         }
2442         dmu_tx_commit(tx);
2443 }
2444
2445 void
2446 vdev_sync_done(vdev_t *vd, uint64_t txg)
2447 {
2448         metaslab_t *msp;
2449         boolean_t reassess = !txg_list_empty(&vd->vdev_ms_list, TXG_CLEAN(txg));
2450
2451         ASSERT(!vd->vdev_ishole);
2452
2453         while (msp = txg_list_remove(&vd->vdev_ms_list, TXG_CLEAN(txg)))
2454                 metaslab_sync_done(msp, txg);
2455
2456         if (reassess)
2457                 metaslab_sync_reassess(vd->vdev_mg);
2458 }
2459
2460 void
2461 vdev_sync(vdev_t *vd, uint64_t txg)
2462 {
2463         spa_t *spa = vd->vdev_spa;
2464         vdev_t *lvd;
2465         metaslab_t *msp;
2466         dmu_tx_t *tx;
2467
2468         ASSERT(!vd->vdev_ishole);
2469
2470         if (vd->vdev_ms_array == 0 && vd->vdev_ms_shift != 0) {
2471                 ASSERT(vd == vd->vdev_top);
2472                 tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
2473                 vd->vdev_ms_array = dmu_object_alloc(spa->spa_meta_objset,
2474                     DMU_OT_OBJECT_ARRAY, 0, DMU_OT_NONE, 0, tx);
2475                 ASSERT(vd->vdev_ms_array != 0);
2476                 vdev_config_dirty(vd);
2477                 dmu_tx_commit(tx);
2478         }
2479
2480         /*
2481          * Remove the metadata associated with this vdev once it's empty.
2482          */
2483         if (vd->vdev_stat.vs_alloc == 0 && vd->vdev_removing)
2484                 vdev_remove(vd, txg);
2485
2486         while ((msp = txg_list_remove(&vd->vdev_ms_list, txg)) != NULL) {
2487                 metaslab_sync(msp, txg);
2488                 (void) txg_list_add(&vd->vdev_ms_list, msp, TXG_CLEAN(txg));
2489         }
2490
2491         while ((lvd = txg_list_remove(&vd->vdev_dtl_list, txg)) != NULL)
2492                 vdev_dtl_sync(lvd, txg);
2493
2494         (void) txg_list_add(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg));
2495 }
2496
2497 uint64_t
2498 vdev_psize_to_asize(vdev_t *vd, uint64_t psize)
2499 {
2500         return (vd->vdev_ops->vdev_op_asize(vd, psize));
2501 }
2502
2503 /*
2504  * Mark the given vdev faulted.  A faulted vdev behaves as if the device could
2505  * not be opened, and no I/O is attempted.
2506  */
2507 int
2508 vdev_fault(spa_t *spa, uint64_t guid, vdev_aux_t aux)
2509 {
2510         vdev_t *vd, *tvd;
2511
2512         spa_vdev_state_enter(spa, SCL_NONE);
2513
2514         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
2515                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
2516
2517         if (!vd->vdev_ops->vdev_op_leaf)
2518                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
2519
2520         tvd = vd->vdev_top;
2521
2522         /*
2523          * We don't directly use the aux state here, but if we do a
2524          * vdev_reopen(), we need this value to be present to remember why we
2525          * were faulted.
2526          */
2527         vd->vdev_label_aux = aux;
2528
2529         /*
2530          * Faulted state takes precedence over degraded.
2531          */
2532         vd->vdev_delayed_close = B_FALSE;
2533         vd->vdev_faulted = 1ULL;
2534         vd->vdev_degraded = 0ULL;
2535         vdev_set_state(vd, B_FALSE, VDEV_STATE_FAULTED, aux);
2536
2537         /*
2538          * If this device has the only valid copy of the data, then
2539          * back off and simply mark the vdev as degraded instead.
2540          */
2541         if (!tvd->vdev_islog && vd->vdev_aux == NULL && vdev_dtl_required(vd)) {
2542                 vd->vdev_degraded = 1ULL;
2543                 vd->vdev_faulted = 0ULL;
2544
2545                 /*
2546                  * If we reopen the device and it's not dead, only then do we
2547                  * mark it degraded.
2548                  */
2549                 vdev_reopen(tvd);
2550
2551                 if (vdev_readable(vd))
2552                         vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED, aux);
2553         }
2554
2555         return (spa_vdev_state_exit(spa, vd, 0));
2556 }
2557
2558 /*
2559  * Mark the given vdev degraded.  A degraded vdev is purely an indication to the
2560  * user that something is wrong.  The vdev continues to operate as normal as far
2561  * as I/O is concerned.
2562  */
2563 int
2564 vdev_degrade(spa_t *spa, uint64_t guid, vdev_aux_t aux)
2565 {
2566         vdev_t *vd;
2567
2568         spa_vdev_state_enter(spa, SCL_NONE);
2569
2570         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
2571                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
2572
2573         if (!vd->vdev_ops->vdev_op_leaf)
2574                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
2575
2576         /*
2577          * If the vdev is already faulted, then don't do anything.
2578          */
2579         if (vd->vdev_faulted || vd->vdev_degraded)
2580                 return (spa_vdev_state_exit(spa, NULL, 0));
2581
2582         vd->vdev_degraded = 1ULL;
2583         if (!vdev_is_dead(vd))
2584                 vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED,
2585                     aux);
2586
2587         return (spa_vdev_state_exit(spa, vd, 0));
2588 }
2589
2590 /*
2591  * Online the given vdev.
2592  *
2593  * If 'ZFS_ONLINE_UNSPARE' is set, it implies two things.  First, any attached
2594  * spare device should be detached when the device finishes resilvering.
2595  * Second, the online should be treated like a 'test' online case, so no FMA
2596  * events are generated if the device fails to open.
2597  */
2598 int
2599 vdev_online(spa_t *spa, uint64_t guid, uint64_t flags, vdev_state_t *newstate)
2600 {
2601         vdev_t *vd, *tvd, *pvd, *rvd = spa->spa_root_vdev;
2602         boolean_t wasoffline;
2603         vdev_state_t oldstate;
2604
2605         spa_vdev_state_enter(spa, SCL_NONE);
2606
2607         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
2608                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
2609
2610         if (!vd->vdev_ops->vdev_op_leaf)
2611                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
2612
2613         wasoffline = (vd->vdev_offline || vd->vdev_tmpoffline);
2614         oldstate = vd->vdev_state;
2615
2616         tvd = vd->vdev_top;
2617         vd->vdev_offline = B_FALSE;
2618         vd->vdev_tmpoffline = B_FALSE;
2619         vd->vdev_checkremove = !!(flags & ZFS_ONLINE_CHECKREMOVE);
2620         vd->vdev_forcefault = !!(flags & ZFS_ONLINE_FORCEFAULT);
2621
2622         /* XXX - L2ARC 1.0 does not support expansion */
2623         if (!vd->vdev_aux) {
2624                 for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
2625                         pvd->vdev_expanding = !!(flags & ZFS_ONLINE_EXPAND);
2626         }
2627
2628         vdev_reopen(tvd);
2629         vd->vdev_checkremove = vd->vdev_forcefault = B_FALSE;
2630
2631         if (!vd->vdev_aux) {
2632                 for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
2633                         pvd->vdev_expanding = B_FALSE;
2634         }
2635
2636         if (newstate)
2637                 *newstate = vd->vdev_state;
2638         if ((flags & ZFS_ONLINE_UNSPARE) &&
2639             !vdev_is_dead(vd) && vd->vdev_parent &&
2640             vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
2641             vd->vdev_parent->vdev_child[0] == vd)
2642                 vd->vdev_unspare = B_TRUE;
2643
2644         if ((flags & ZFS_ONLINE_EXPAND) || spa->spa_autoexpand) {
2645
2646                 /* XXX - L2ARC 1.0 does not support expansion */
2647                 if (vd->vdev_aux)
2648                         return (spa_vdev_state_exit(spa, vd, ENOTSUP));
2649                 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
2650         }
2651
2652         if (wasoffline ||
2653             (oldstate < VDEV_STATE_DEGRADED &&
2654             vd->vdev_state >= VDEV_STATE_DEGRADED))
2655                 spa_event_notify(spa, vd, ESC_ZFS_VDEV_ONLINE);
2656
2657         return (spa_vdev_state_exit(spa, vd, 0));
2658 }
2659
2660 static int
2661 vdev_offline_locked(spa_t *spa, uint64_t guid, uint64_t flags)
2662 {
2663         vdev_t *vd, *tvd;
2664         int error = 0;
2665         uint64_t generation;
2666         metaslab_group_t *mg;
2667
2668 top:
2669         spa_vdev_state_enter(spa, SCL_ALLOC);
2670
2671         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
2672                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
2673
2674         if (!vd->vdev_ops->vdev_op_leaf)
2675                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
2676
2677         tvd = vd->vdev_top;
2678         mg = tvd->vdev_mg;
2679         generation = spa->spa_config_generation + 1;
2680
2681         /*
2682          * If the device isn't already offline, try to offline it.
2683          */
2684         if (!vd->vdev_offline) {
2685                 /*
2686                  * If this device has the only valid copy of some data,
2687                  * don't allow it to be offlined. Log devices are always
2688                  * expendable.
2689                  */
2690                 if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
2691                     vdev_dtl_required(vd))
2692                         return (spa_vdev_state_exit(spa, NULL, EBUSY));
2693
2694                 /*
2695                  * If the top-level is a slog and it has had allocations
2696                  * then proceed.  We check that the vdev's metaslab group
2697                  * is not NULL since it's possible that we may have just
2698                  * added this vdev but not yet initialized its metaslabs.
2699                  */
2700                 if (tvd->vdev_islog && mg != NULL) {
2701                         /*
2702                          * Prevent any future allocations.
2703                          */
2704                         metaslab_group_passivate(mg);
2705                         (void) spa_vdev_state_exit(spa, vd, 0);
2706
2707                         error = spa_offline_log(spa);
2708
2709                         spa_vdev_state_enter(spa, SCL_ALLOC);
2710
2711                         /*
2712                          * Check to see if the config has changed.
2713                          */
2714                         if (error || generation != spa->spa_config_generation) {
2715                                 metaslab_group_activate(mg);
2716                                 if (error)
2717                                         return (spa_vdev_state_exit(spa,
2718                                             vd, error));
2719                                 (void) spa_vdev_state_exit(spa, vd, 0);
2720                                 goto top;
2721                         }
2722                         ASSERT0(tvd->vdev_stat.vs_alloc);
2723                 }
2724
2725                 /*
2726                  * Offline this device and reopen its top-level vdev.
2727                  * If the top-level vdev is a log device then just offline
2728                  * it. Otherwise, if this action results in the top-level
2729                  * vdev becoming unusable, undo it and fail the request.
2730                  */
2731                 vd->vdev_offline = B_TRUE;
2732                 vdev_reopen(tvd);
2733
2734                 if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
2735                     vdev_is_dead(tvd)) {
2736                         vd->vdev_offline = B_FALSE;
2737                         vdev_reopen(tvd);
2738                         return (spa_vdev_state_exit(spa, NULL, EBUSY));
2739                 }
2740
2741                 /*
2742                  * Add the device back into the metaslab rotor so that
2743                  * once we online the device it's open for business.
2744                  */
2745                 if (tvd->vdev_islog && mg != NULL)
2746                         metaslab_group_activate(mg);
2747         }
2748
2749         vd->vdev_tmpoffline = !!(flags & ZFS_OFFLINE_TEMPORARY);
2750
2751         return (spa_vdev_state_exit(spa, vd, 0));
2752 }
2753
2754 int
2755 vdev_offline(spa_t *spa, uint64_t guid, uint64_t flags)
2756 {
2757         int error;
2758
2759         mutex_enter(&spa->spa_vdev_top_lock);
2760         error = vdev_offline_locked(spa, guid, flags);
2761         mutex_exit(&spa->spa_vdev_top_lock);
2762
2763         return (error);
2764 }
2765
2766 /*
2767  * Clear the error counts associated with this vdev.  Unlike vdev_online() and
2768  * vdev_offline(), we assume the spa config is locked.  We also clear all
2769  * children.  If 'vd' is NULL, then the user wants to clear all vdevs.
2770  */
2771 void
2772 vdev_clear(spa_t *spa, vdev_t *vd)
2773 {
2774         vdev_t *rvd = spa->spa_root_vdev;
2775
2776         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2777
2778         if (vd == NULL)
2779                 vd = rvd;
2780
2781         vd->vdev_stat.vs_read_errors = 0;
2782         vd->vdev_stat.vs_write_errors = 0;
2783         vd->vdev_stat.vs_checksum_errors = 0;
2784
2785         for (int c = 0; c < vd->vdev_children; c++)
2786                 vdev_clear(spa, vd->vdev_child[c]);
2787
2788         if (vd == rvd) {
2789                 for (int c = 0; c < spa->spa_l2cache.sav_count; c++)
2790                         vdev_clear(spa, spa->spa_l2cache.sav_vdevs[c]);
2791
2792                 for (int c = 0; c < spa->spa_spares.sav_count; c++)
2793                         vdev_clear(spa, spa->spa_spares.sav_vdevs[c]);
2794         }
2795
2796         /*
2797          * If we're in the FAULTED state or have experienced failed I/O, then
2798          * clear the persistent state and attempt to reopen the device.  We
2799          * also mark the vdev config dirty, so that the new faulted state is
2800          * written out to disk.
2801          */
2802         if (vd->vdev_faulted || vd->vdev_degraded ||
2803             !vdev_readable(vd) || !vdev_writeable(vd)) {
2804
2805                 /*
2806                  * When reopening in reponse to a clear event, it may be due to
2807                  * a fmadm repair request.  In this case, if the device is
2808                  * still broken, we want to still post the ereport again.
2809                  */
2810                 vd->vdev_forcefault = B_TRUE;
2811
2812                 vd->vdev_faulted = vd->vdev_degraded = 0ULL;
2813                 vd->vdev_cant_read = B_FALSE;
2814                 vd->vdev_cant_write = B_FALSE;
2815
2816                 vdev_reopen(vd == rvd ? rvd : vd->vdev_top);
2817
2818                 vd->vdev_forcefault = B_FALSE;
2819
2820                 if (vd != rvd && vdev_writeable(vd->vdev_top))
2821                         vdev_state_dirty(vd->vdev_top);
2822
2823                 if (vd->vdev_aux == NULL && !vdev_is_dead(vd))
2824                         spa_async_request(spa, SPA_ASYNC_RESILVER);
2825
2826                 spa_event_notify(spa, vd, ESC_ZFS_VDEV_CLEAR);
2827         }
2828
2829         /*
2830          * When clearing a FMA-diagnosed fault, we always want to
2831          * unspare the device, as we assume that the original spare was
2832          * done in response to the FMA fault.
2833          */
2834         if (!vdev_is_dead(vd) && vd->vdev_parent != NULL &&
2835             vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
2836             vd->vdev_parent->vdev_child[0] == vd)
2837                 vd->vdev_unspare = B_TRUE;
2838 }
2839
2840 boolean_t
2841 vdev_is_dead(vdev_t *vd)
2842 {
2843         /*
2844          * Holes and missing devices are always considered "dead".
2845          * This simplifies the code since we don't have to check for
2846          * these types of devices in the various code paths.
2847          * Instead we rely on the fact that we skip over dead devices
2848          * before issuing I/O to them.
2849          */
2850         return (vd->vdev_state < VDEV_STATE_DEGRADED || vd->vdev_ishole ||
2851             vd->vdev_ops == &vdev_missing_ops);
2852 }
2853
2854 boolean_t
2855 vdev_readable(vdev_t *vd)
2856 {
2857         return (!vdev_is_dead(vd) && !vd->vdev_cant_read);
2858 }
2859
2860 boolean_t
2861 vdev_writeable(vdev_t *vd)
2862 {
2863         return (!vdev_is_dead(vd) && !vd->vdev_cant_write);
2864 }
2865
2866 boolean_t
2867 vdev_allocatable(vdev_t *vd)
2868 {
2869         uint64_t state = vd->vdev_state;
2870
2871         /*
2872          * We currently allow allocations from vdevs which may be in the
2873          * process of reopening (i.e. VDEV_STATE_CLOSED). If the device
2874          * fails to reopen then we'll catch it later when we're holding
2875          * the proper locks.  Note that we have to get the vdev state
2876          * in a local variable because although it changes atomically,
2877          * we're asking two separate questions about it.
2878          */
2879         return (!(state < VDEV_STATE_DEGRADED && state != VDEV_STATE_CLOSED) &&
2880             !vd->vdev_cant_write && !vd->vdev_ishole &&
2881             vd->vdev_mg->mg_initialized);
2882 }
2883
2884 boolean_t
2885 vdev_accessible(vdev_t *vd, zio_t *zio)
2886 {
2887         ASSERT(zio->io_vd == vd);
2888
2889         if (vdev_is_dead(vd) || vd->vdev_remove_wanted)
2890                 return (B_FALSE);
2891
2892         if (zio->io_type == ZIO_TYPE_READ)
2893                 return (!vd->vdev_cant_read);
2894
2895         if (zio->io_type == ZIO_TYPE_WRITE)
2896                 return (!vd->vdev_cant_write);
2897
2898         return (B_TRUE);
2899 }
2900
2901 /*
2902  * Get statistics for the given vdev.
2903  */
2904 void
2905 vdev_get_stats(vdev_t *vd, vdev_stat_t *vs)
2906 {
2907         spa_t *spa = vd->vdev_spa;
2908         vdev_t *rvd = spa->spa_root_vdev;
2909         vdev_t *tvd = vd->vdev_top;
2910
2911         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
2912
2913         mutex_enter(&vd->vdev_stat_lock);
2914         bcopy(&vd->vdev_stat, vs, sizeof (*vs));
2915         vs->vs_timestamp = gethrtime() - vs->vs_timestamp;
2916         vs->vs_state = vd->vdev_state;
2917         vs->vs_rsize = vdev_get_min_asize(vd);
2918         if (vd->vdev_ops->vdev_op_leaf)
2919                 vs->vs_rsize += VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE;
2920         /*
2921          * Report expandable space on top-level, non-auxillary devices only.
2922          * The expandable space is reported in terms of metaslab sized units
2923          * since that determines how much space the pool can expand.
2924          */
2925         if (vd->vdev_aux == NULL && tvd != NULL && vd->vdev_max_asize != 0) {
2926                 vs->vs_esize = P2ALIGN(vd->vdev_max_asize - vd->vdev_asize,
2927                     1ULL << tvd->vdev_ms_shift);
2928         }
2929         vs->vs_configured_ashift = vd->vdev_top != NULL
2930             ? vd->vdev_top->vdev_ashift : vd->vdev_ashift;
2931         vs->vs_logical_ashift = vd->vdev_logical_ashift;
2932         vs->vs_physical_ashift = vd->vdev_physical_ashift;
2933         if (vd->vdev_aux == NULL && vd == vd->vdev_top && !vd->vdev_ishole) {
2934                 vs->vs_fragmentation = vd->vdev_mg->mg_fragmentation;
2935         }
2936
2937         /*
2938          * If we're getting stats on the root vdev, aggregate the I/O counts
2939          * over all top-level vdevs (i.e. the direct children of the root).
2940          */
2941         if (vd == rvd) {
2942                 for (int c = 0; c < rvd->vdev_children; c++) {
2943                         vdev_t *cvd = rvd->vdev_child[c];
2944                         vdev_stat_t *cvs = &cvd->vdev_stat;
2945
2946                         for (int t = 0; t < ZIO_TYPES; t++) {
2947                                 vs->vs_ops[t] += cvs->vs_ops[t];
2948                                 vs->vs_bytes[t] += cvs->vs_bytes[t];
2949                         }
2950                         cvs->vs_scan_removing = cvd->vdev_removing;
2951                 }
2952         }
2953         mutex_exit(&vd->vdev_stat_lock);
2954 }
2955
2956 void
2957 vdev_clear_stats(vdev_t *vd)
2958 {
2959         mutex_enter(&vd->vdev_stat_lock);
2960         vd->vdev_stat.vs_space = 0;
2961         vd->vdev_stat.vs_dspace = 0;
2962         vd->vdev_stat.vs_alloc = 0;
2963         mutex_exit(&vd->vdev_stat_lock);
2964 }
2965
2966 void
2967 vdev_scan_stat_init(vdev_t *vd)
2968 {
2969         vdev_stat_t *vs = &vd->vdev_stat;
2970
2971         for (int c = 0; c < vd->vdev_children; c++)
2972                 vdev_scan_stat_init(vd->vdev_child[c]);
2973
2974         mutex_enter(&vd->vdev_stat_lock);
2975         vs->vs_scan_processed = 0;
2976         mutex_exit(&vd->vdev_stat_lock);
2977 }
2978
2979 void
2980 vdev_stat_update(zio_t *zio, uint64_t psize)
2981 {
2982         spa_t *spa = zio->io_spa;
2983         vdev_t *rvd = spa->spa_root_vdev;
2984         vdev_t *vd = zio->io_vd ? zio->io_vd : rvd;
2985         vdev_t *pvd;
2986         uint64_t txg = zio->io_txg;
2987         vdev_stat_t *vs = &vd->vdev_stat;
2988         zio_type_t type = zio->io_type;
2989         int flags = zio->io_flags;
2990
2991         /*
2992          * If this i/o is a gang leader, it didn't do any actual work.
2993          */
2994         if (zio->io_gang_tree)
2995                 return;
2996
2997         if (zio->io_error == 0) {
2998                 /*
2999                  * If this is a root i/o, don't count it -- we've already
3000                  * counted the top-level vdevs, and vdev_get_stats() will
3001                  * aggregate them when asked.  This reduces contention on
3002                  * the root vdev_stat_lock and implicitly handles blocks
3003                  * that compress away to holes, for which there is no i/o.
3004                  * (Holes never create vdev children, so all the counters
3005                  * remain zero, which is what we want.)
3006                  *
3007                  * Note: this only applies to successful i/o (io_error == 0)
3008                  * because unlike i/o counts, errors are not additive.
3009                  * When reading a ditto block, for example, failure of
3010                  * one top-level vdev does not imply a root-level error.
3011                  */
3012                 if (vd == rvd)
3013                         return;
3014
3015                 ASSERT(vd == zio->io_vd);
3016
3017                 if (flags & ZIO_FLAG_IO_BYPASS)
3018                         return;
3019
3020                 mutex_enter(&vd->vdev_stat_lock);
3021
3022                 if (flags & ZIO_FLAG_IO_REPAIR) {
3023                         if (flags & ZIO_FLAG_SCAN_THREAD) {
3024                                 dsl_scan_phys_t *scn_phys =
3025                                     &spa->spa_dsl_pool->dp_scan->scn_phys;
3026                                 uint64_t *processed = &scn_phys->scn_processed;
3027
3028                                 /* XXX cleanup? */
3029                                 if (vd->vdev_ops->vdev_op_leaf)
3030                                         atomic_add_64(processed, psize);
3031                                 vs->vs_scan_processed += psize;
3032                         }
3033
3034                         if (flags & ZIO_FLAG_SELF_HEAL)
3035                                 vs->vs_self_healed += psize;
3036                 }
3037
3038                 vs->vs_ops[type]++;
3039                 vs->vs_bytes[type] += psize;
3040
3041                 mutex_exit(&vd->vdev_stat_lock);
3042                 return;
3043         }
3044
3045         if (flags & ZIO_FLAG_SPECULATIVE)
3046                 return;
3047
3048         /*
3049          * If this is an I/O error that is going to be retried, then ignore the
3050          * error.  Otherwise, the user may interpret B_FAILFAST I/O errors as
3051          * hard errors, when in reality they can happen for any number of
3052          * innocuous reasons (bus resets, MPxIO link failure, etc).
3053          */
3054         if (zio->io_error == EIO &&
3055             !(zio->io_flags & ZIO_FLAG_IO_RETRY))
3056                 return;
3057
3058         /*
3059          * Intent logs writes won't propagate their error to the root
3060          * I/O so don't mark these types of failures as pool-level
3061          * errors.
3062          */
3063         if (zio->io_vd == NULL && (zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
3064                 return;
3065
3066         mutex_enter(&vd->vdev_stat_lock);
3067         if (type == ZIO_TYPE_READ && !vdev_is_dead(vd)) {
3068                 if (zio->io_error == ECKSUM)
3069                         vs->vs_checksum_errors++;
3070                 else
3071                         vs->vs_read_errors++;
3072         }
3073         if (type == ZIO_TYPE_WRITE && !vdev_is_dead(vd))
3074                 vs->vs_write_errors++;
3075         mutex_exit(&vd->vdev_stat_lock);
3076
3077         if (type == ZIO_TYPE_WRITE && txg != 0 &&
3078             (!(flags & ZIO_FLAG_IO_REPAIR) ||
3079             (flags & ZIO_FLAG_SCAN_THREAD) ||
3080             spa->spa_claiming)) {
3081                 /*
3082                  * This is either a normal write (not a repair), or it's
3083                  * a repair induced by the scrub thread, or it's a repair
3084                  * made by zil_claim() during spa_load() in the first txg.
3085                  * In the normal case, we commit the DTL change in the same
3086                  * txg as the block was born.  In the scrub-induced repair
3087                  * case, we know that scrubs run in first-pass syncing context,
3088                  * so we commit the DTL change in spa_syncing_txg(spa).
3089                  * In the zil_claim() case, we commit in spa_first_txg(spa).
3090                  *
3091                  * We currently do not make DTL entries for failed spontaneous
3092                  * self-healing writes triggered by normal (non-scrubbing)
3093                  * reads, because we have no transactional context in which to
3094                  * do so -- and it's not clear that it'd be desirable anyway.
3095                  */
3096                 if (vd->vdev_ops->vdev_op_leaf) {
3097                         uint64_t commit_txg = txg;
3098                         if (flags & ZIO_FLAG_SCAN_THREAD) {
3099                                 ASSERT(flags & ZIO_FLAG_IO_REPAIR);
3100                                 ASSERT(spa_sync_pass(spa) == 1);
3101                                 vdev_dtl_dirty(vd, DTL_SCRUB, txg, 1);
3102                                 commit_txg = spa_syncing_txg(spa);
3103                         } else if (spa->spa_claiming) {
3104                                 ASSERT(flags & ZIO_FLAG_IO_REPAIR);
3105                                 commit_txg = spa_first_txg(spa);
3106                         }
3107                         ASSERT(commit_txg >= spa_syncing_txg(spa));
3108                         if (vdev_dtl_contains(vd, DTL_MISSING, txg, 1))
3109                                 return;
3110                         for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
3111                                 vdev_dtl_dirty(pvd, DTL_PARTIAL, txg, 1);
3112                         vdev_dirty(vd->vdev_top, VDD_DTL, vd, commit_txg);
3113                 }
3114                 if (vd != rvd)
3115                         vdev_dtl_dirty(vd, DTL_MISSING, txg, 1);
3116         }
3117 }
3118
3119 /*
3120  * Update the in-core space usage stats for this vdev, its metaslab class,
3121  * and the root vdev.
3122  */
3123 void
3124 vdev_space_update(vdev_t *vd, int64_t alloc_delta, int64_t defer_delta,
3125     int64_t space_delta)
3126 {
3127         int64_t dspace_delta = space_delta;
3128         spa_t *spa = vd->vdev_spa;
3129         vdev_t *rvd = spa->spa_root_vdev;
3130         metaslab_group_t *mg = vd->vdev_mg;
3131         metaslab_class_t *mc = mg ? mg->mg_class : NULL;
3132
3133         ASSERT(vd == vd->vdev_top);
3134
3135         /*
3136          * Apply the inverse of the psize-to-asize (ie. RAID-Z) space-expansion
3137          * factor.  We must calculate this here and not at the root vdev
3138          * because the root vdev's psize-to-asize is simply the max of its
3139          * childrens', thus not accurate enough for us.
3140          */
3141         ASSERT((dspace_delta & (SPA_MINBLOCKSIZE-1)) == 0);
3142         ASSERT(vd->vdev_deflate_ratio != 0 || vd->vdev_isl2cache);
3143         dspace_delta = (dspace_delta >> SPA_MINBLOCKSHIFT) *
3144             vd->vdev_deflate_ratio;
3145
3146         mutex_enter(&vd->vdev_stat_lock);
3147         vd->vdev_stat.vs_alloc += alloc_delta;
3148         vd->vdev_stat.vs_space += space_delta;
3149         vd->vdev_stat.vs_dspace += dspace_delta;
3150         mutex_exit(&vd->vdev_stat_lock);
3151
3152         if (mc == spa_normal_class(spa)) {
3153                 mutex_enter(&rvd->vdev_stat_lock);
3154                 rvd->vdev_stat.vs_alloc += alloc_delta;
3155                 rvd->vdev_stat.vs_space += space_delta;
3156                 rvd->vdev_stat.vs_dspace += dspace_delta;
3157                 mutex_exit(&rvd->vdev_stat_lock);
3158         }
3159
3160         if (mc != NULL) {
3161                 ASSERT(rvd == vd->vdev_parent);
3162                 ASSERT(vd->vdev_ms_count != 0);
3163
3164                 metaslab_class_space_update(mc,
3165                     alloc_delta, defer_delta, space_delta, dspace_delta);
3166         }
3167 }
3168
3169 /*
3170  * Mark a top-level vdev's config as dirty, placing it on the dirty list
3171  * so that it will be written out next time the vdev configuration is synced.
3172  * If the root vdev is specified (vdev_top == NULL), dirty all top-level vdevs.
3173  */
3174 void
3175 vdev_config_dirty(vdev_t *vd)
3176 {
3177         spa_t *spa = vd->vdev_spa;
3178         vdev_t *rvd = spa->spa_root_vdev;
3179         int c;
3180
3181         ASSERT(spa_writeable(spa));
3182
3183         /*
3184          * If this is an aux vdev (as with l2cache and spare devices), then we
3185          * update the vdev config manually and set the sync flag.
3186          */
3187         if (vd->vdev_aux != NULL) {
3188                 spa_aux_vdev_t *sav = vd->vdev_aux;
3189                 nvlist_t **aux;
3190                 uint_t naux;
3191
3192                 for (c = 0; c < sav->sav_count; c++) {
3193                         if (sav->sav_vdevs[c] == vd)
3194                                 break;
3195                 }
3196
3197                 if (c == sav->sav_count) {
3198                         /*
3199                          * We're being removed.  There's nothing more to do.
3200                          */
3201                         ASSERT(sav->sav_sync == B_TRUE);
3202                         return;
3203                 }
3204
3205                 sav->sav_sync = B_TRUE;
3206
3207                 if (nvlist_lookup_nvlist_array(sav->sav_config,
3208                     ZPOOL_CONFIG_L2CACHE, &aux, &naux) != 0) {
3209                         VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
3210                             ZPOOL_CONFIG_SPARES, &aux, &naux) == 0);
3211                 }
3212
3213                 ASSERT(c < naux);
3214
3215                 /*
3216                  * Setting the nvlist in the middle if the array is a little
3217                  * sketchy, but it will work.
3218                  */
3219                 nvlist_free(aux[c]);
3220                 aux[c] = vdev_config_generate(spa, vd, B_TRUE, 0);
3221
3222                 return;
3223         }
3224
3225         /*
3226          * The dirty list is protected by the SCL_CONFIG lock.  The caller
3227          * must either hold SCL_CONFIG as writer, or must be the sync thread
3228          * (which holds SCL_CONFIG as reader).  There's only one sync thread,
3229          * so this is sufficient to ensure mutual exclusion.
3230          */
3231         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
3232             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3233             spa_config_held(spa, SCL_CONFIG, RW_READER)));
3234
3235         if (vd == rvd) {
3236                 for (c = 0; c < rvd->vdev_children; c++)
3237                         vdev_config_dirty(rvd->vdev_child[c]);
3238         } else {
3239                 ASSERT(vd == vd->vdev_top);
3240
3241                 if (!list_link_active(&vd->vdev_config_dirty_node) &&
3242                     !vd->vdev_ishole)
3243                         list_insert_head(&spa->spa_config_dirty_list, vd);
3244         }
3245 }
3246
3247 void
3248 vdev_config_clean(vdev_t *vd)
3249 {
3250         spa_t *spa = vd->vdev_spa;
3251
3252         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
3253             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3254             spa_config_held(spa, SCL_CONFIG, RW_READER)));
3255
3256         ASSERT(list_link_active(&vd->vdev_config_dirty_node));
3257         list_remove(&spa->spa_config_dirty_list, vd);
3258 }
3259
3260 /*
3261  * Mark a top-level vdev's state as dirty, so that the next pass of
3262  * spa_sync() can convert this into vdev_config_dirty().  We distinguish
3263  * the state changes from larger config changes because they require
3264  * much less locking, and are often needed for administrative actions.
3265  */
3266 void
3267 vdev_state_dirty(vdev_t *vd)
3268 {
3269         spa_t *spa = vd->vdev_spa;
3270
3271         ASSERT(spa_writeable(spa));
3272         ASSERT(vd == vd->vdev_top);
3273
3274         /*
3275          * The state list is protected by the SCL_STATE lock.  The caller
3276          * must either hold SCL_STATE as writer, or must be the sync thread
3277          * (which holds SCL_STATE as reader).  There's only one sync thread,
3278          * so this is sufficient to ensure mutual exclusion.
3279          */
3280         ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
3281             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3282             spa_config_held(spa, SCL_STATE, RW_READER)));
3283
3284         if (!list_link_active(&vd->vdev_state_dirty_node) && !vd->vdev_ishole)
3285                 list_insert_head(&spa->spa_state_dirty_list, vd);
3286 }
3287
3288 void
3289 vdev_state_clean(vdev_t *vd)
3290 {
3291         spa_t *spa = vd->vdev_spa;
3292
3293         ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
3294             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
3295             spa_config_held(spa, SCL_STATE, RW_READER)));
3296
3297         ASSERT(list_link_active(&vd->vdev_state_dirty_node));
3298         list_remove(&spa->spa_state_dirty_list, vd);
3299 }
3300
3301 /*
3302  * Propagate vdev state up from children to parent.
3303  */
3304 void
3305 vdev_propagate_state(vdev_t *vd)
3306 {
3307         spa_t *spa = vd->vdev_spa;
3308         vdev_t *rvd = spa->spa_root_vdev;
3309         int degraded = 0, faulted = 0;
3310         int corrupted = 0;
3311         vdev_t *child;
3312
3313         if (vd->vdev_children > 0) {
3314                 for (int c = 0; c < vd->vdev_children; c++) {
3315                         child = vd->vdev_child[c];
3316
3317                         /*
3318                          * Don't factor holes into the decision.
3319                          */
3320                         if (child->vdev_ishole)
3321                                 continue;
3322
3323                         if (!vdev_readable(child) ||
3324                             (!vdev_writeable(child) && spa_writeable(spa))) {
3325                                 /*
3326                                  * Root special: if there is a top-level log
3327                                  * device, treat the root vdev as if it were
3328                                  * degraded.
3329                                  */
3330                                 if (child->vdev_islog && vd == rvd)
3331                                         degraded++;
3332                                 else
3333                                         faulted++;
3334                         } else if (child->vdev_state <= VDEV_STATE_DEGRADED) {
3335                                 degraded++;
3336                         }
3337
3338                         if (child->vdev_stat.vs_aux == VDEV_AUX_CORRUPT_DATA)
3339                                 corrupted++;
3340                 }
3341
3342                 vd->vdev_ops->vdev_op_state_change(vd, faulted, degraded);
3343
3344                 /*
3345                  * Root special: if there is a top-level vdev that cannot be
3346                  * opened due to corrupted metadata, then propagate the root
3347                  * vdev's aux state as 'corrupt' rather than 'insufficient
3348                  * replicas'.
3349                  */
3350                 if (corrupted && vd == rvd &&
3351                     rvd->vdev_state == VDEV_STATE_CANT_OPEN)
3352                         vdev_set_state(rvd, B_FALSE, VDEV_STATE_CANT_OPEN,
3353                             VDEV_AUX_CORRUPT_DATA);
3354         }
3355
3356         if (vd->vdev_parent)
3357                 vdev_propagate_state(vd->vdev_parent);
3358 }
3359
3360 /*
3361  * Set a vdev's state.  If this is during an open, we don't update the parent
3362  * state, because we're in the process of opening children depth-first.
3363  * Otherwise, we propagate the change to the parent.
3364  *
3365  * If this routine places a device in a faulted state, an appropriate ereport is
3366  * generated.
3367  */
3368 void
3369 vdev_set_state(vdev_t *vd, boolean_t isopen, vdev_state_t state, vdev_aux_t aux)
3370 {
3371         uint64_t save_state;
3372         spa_t *spa = vd->vdev_spa;
3373
3374         if (state == vd->vdev_state) {
3375                 vd->vdev_stat.vs_aux = aux;
3376                 return;
3377         }
3378
3379         save_state = vd->vdev_state;
3380
3381         vd->vdev_state = state;
3382         vd->vdev_stat.vs_aux = aux;
3383
3384         /*
3385          * If we are setting the vdev state to anything but an open state, then
3386          * always close the underlying device unless the device has requested
3387          * a delayed close (i.e. we're about to remove or fault the device).
3388          * Otherwise, we keep accessible but invalid devices open forever.
3389          * We don't call vdev_close() itself, because that implies some extra
3390          * checks (offline, etc) that we don't want here.  This is limited to
3391          * leaf devices, because otherwise closing the device will affect other
3392          * children.
3393          */
3394         if (!vd->vdev_delayed_close && vdev_is_dead(vd) &&
3395             vd->vdev_ops->vdev_op_leaf)
3396                 vd->vdev_ops->vdev_op_close(vd);
3397
3398         if (vd->vdev_removed &&
3399             state == VDEV_STATE_CANT_OPEN &&
3400             (aux == VDEV_AUX_OPEN_FAILED || vd->vdev_checkremove)) {
3401                 /*
3402                  * If the previous state is set to VDEV_STATE_REMOVED, then this
3403                  * device was previously marked removed and someone attempted to
3404                  * reopen it.  If this failed due to a nonexistent device, then
3405                  * keep the device in the REMOVED state.  We also let this be if
3406                  * it is one of our special test online cases, which is only
3407                  * attempting to online the device and shouldn't generate an FMA
3408                  * fault.
3409                  */
3410                 vd->vdev_state = VDEV_STATE_REMOVED;
3411                 vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
3412         } else if (state == VDEV_STATE_REMOVED) {
3413                 vd->vdev_removed = B_TRUE;
3414         } else if (state == VDEV_STATE_CANT_OPEN) {
3415                 /*
3416                  * If we fail to open a vdev during an import or recovery, we
3417                  * mark it as "not available", which signifies that it was
3418                  * never there to begin with.  Failure to open such a device
3419                  * is not considered an error.
3420                  */
3421                 if ((spa_load_state(spa) == SPA_LOAD_IMPORT ||
3422                     spa_load_state(spa) == SPA_LOAD_RECOVER) &&
3423                     vd->vdev_ops->vdev_op_leaf)
3424                         vd->vdev_not_present = 1;
3425
3426                 /*
3427                  * Post the appropriate ereport.  If the 'prevstate' field is
3428                  * set to something other than VDEV_STATE_UNKNOWN, it indicates
3429                  * that this is part of a vdev_reopen().  In this case, we don't
3430                  * want to post the ereport if the device was already in the
3431                  * CANT_OPEN state beforehand.
3432                  *
3433                  * If the 'checkremove' flag is set, then this is an attempt to
3434                  * online the device in response to an insertion event.  If we
3435                  * hit this case, then we have detected an insertion event for a
3436                  * faulted or offline device that wasn't in the removed state.
3437                  * In this scenario, we don't post an ereport because we are
3438                  * about to replace the device, or attempt an online with
3439                  * vdev_forcefault, which will generate the fault for us.
3440                  */
3441                 if ((vd->vdev_prevstate != state || vd->vdev_forcefault) &&
3442                     !vd->vdev_not_present && !vd->vdev_checkremove &&
3443                     vd != spa->spa_root_vdev) {
3444                         const char *class;
3445
3446                         switch (aux) {
3447                         case VDEV_AUX_OPEN_FAILED:
3448                                 class = FM_EREPORT_ZFS_DEVICE_OPEN_FAILED;
3449                                 break;
3450                         case VDEV_AUX_CORRUPT_DATA:
3451                                 class = FM_EREPORT_ZFS_DEVICE_CORRUPT_DATA;
3452                                 break;
3453                         case VDEV_AUX_NO_REPLICAS:
3454                                 class = FM_EREPORT_ZFS_DEVICE_NO_REPLICAS;
3455                                 break;
3456                         case VDEV_AUX_BAD_GUID_SUM:
3457                                 class = FM_EREPORT_ZFS_DEVICE_BAD_GUID_SUM;
3458                                 break;
3459                         case VDEV_AUX_TOO_SMALL:
3460                                 class = FM_EREPORT_ZFS_DEVICE_TOO_SMALL;
3461                                 break;
3462                         case VDEV_AUX_BAD_LABEL:
3463                                 class = FM_EREPORT_ZFS_DEVICE_BAD_LABEL;
3464                                 break;
3465                         default:
3466                                 class = FM_EREPORT_ZFS_DEVICE_UNKNOWN;
3467                         }
3468
3469                         zfs_ereport_post(class, spa, vd, NULL, save_state, 0);
3470                 }
3471
3472                 /* Erase any notion of persistent removed state */
3473                 vd->vdev_removed = B_FALSE;
3474         } else {
3475                 vd->vdev_removed = B_FALSE;
3476         }
3477
3478         /*
3479         * Notify the fmd of the state change.  Be verbose and post
3480         * notifications even for stuff that's not important; the fmd agent can
3481         * sort it out.  Don't emit state change events for non-leaf vdevs since
3482         * they can't change state on their own.  The FMD can check their state
3483         * if it wants to when it sees that a leaf vdev had a state change.
3484         */
3485         if (vd->vdev_ops->vdev_op_leaf)
3486                 zfs_post_state_change(spa, vd);
3487
3488         if (!isopen && vd->vdev_parent)
3489                 vdev_propagate_state(vd->vdev_parent);
3490 }
3491
3492 /*
3493  * Check the vdev configuration to ensure that it's capable of supporting
3494  * a root pool. We do not support partial configuration.
3495  * In addition, only a single top-level vdev is allowed.
3496  *
3497  * FreeBSD does not have above limitations.
3498  */
3499 boolean_t
3500 vdev_is_bootable(vdev_t *vd)
3501 {
3502 #ifdef illumos
3503         if (!vd->vdev_ops->vdev_op_leaf) {
3504                 char *vdev_type = vd->vdev_ops->vdev_op_type;
3505
3506                 if (strcmp(vdev_type, VDEV_TYPE_ROOT) == 0 &&
3507                     vd->vdev_children > 1) {
3508                         return (B_FALSE);
3509                 } else if (strcmp(vdev_type, VDEV_TYPE_MISSING) == 0) {
3510                         return (B_FALSE);
3511                 }
3512         }
3513
3514         for (int c = 0; c < vd->vdev_children; c++) {
3515                 if (!vdev_is_bootable(vd->vdev_child[c]))
3516                         return (B_FALSE);
3517         }
3518 #endif  /* illumos */
3519         return (B_TRUE);
3520 }
3521
3522 /*
3523  * Load the state from the original vdev tree (ovd) which
3524  * we've retrieved from the MOS config object. If the original
3525  * vdev was offline or faulted then we transfer that state to the
3526  * device in the current vdev tree (nvd).
3527  */
3528 void
3529 vdev_load_log_state(vdev_t *nvd, vdev_t *ovd)
3530 {
3531         spa_t *spa = nvd->vdev_spa;
3532
3533         ASSERT(nvd->vdev_top->vdev_islog);
3534         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
3535         ASSERT3U(nvd->vdev_guid, ==, ovd->vdev_guid);
3536
3537         for (int c = 0; c < nvd->vdev_children; c++)
3538                 vdev_load_log_state(nvd->vdev_child[c], ovd->vdev_child[c]);
3539
3540         if (nvd->vdev_ops->vdev_op_leaf) {
3541                 /*
3542                  * Restore the persistent vdev state
3543                  */
3544                 nvd->vdev_offline = ovd->vdev_offline;
3545                 nvd->vdev_faulted = ovd->vdev_faulted;
3546                 nvd->vdev_degraded = ovd->vdev_degraded;
3547                 nvd->vdev_removed = ovd->vdev_removed;
3548         }
3549 }
3550
3551 /*
3552  * Determine if a log device has valid content.  If the vdev was
3553  * removed or faulted in the MOS config then we know that
3554  * the content on the log device has already been written to the pool.
3555  */
3556 boolean_t
3557 vdev_log_state_valid(vdev_t *vd)
3558 {
3559         if (vd->vdev_ops->vdev_op_leaf && !vd->vdev_faulted &&
3560             !vd->vdev_removed)
3561                 return (B_TRUE);
3562
3563         for (int c = 0; c < vd->vdev_children; c++)
3564                 if (vdev_log_state_valid(vd->vdev_child[c]))
3565                         return (B_TRUE);
3566
3567         return (B_FALSE);
3568 }
3569
3570 /*
3571  * Expand a vdev if possible.
3572  */
3573 void
3574 vdev_expand(vdev_t *vd, uint64_t txg)
3575 {
3576         ASSERT(vd->vdev_top == vd);
3577         ASSERT(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3578
3579         if ((vd->vdev_asize >> vd->vdev_ms_shift) > vd->vdev_ms_count) {
3580                 VERIFY(vdev_metaslab_init(vd, txg) == 0);
3581                 vdev_config_dirty(vd);
3582         }
3583 }
3584
3585 /*
3586  * Split a vdev.
3587  */
3588 void
3589 vdev_split(vdev_t *vd)
3590 {
3591         vdev_t *cvd, *pvd = vd->vdev_parent;
3592
3593         vdev_remove_child(pvd, vd);
3594         vdev_compact_children(pvd);
3595
3596         cvd = pvd->vdev_child[0];
3597         if (pvd->vdev_children == 1) {
3598                 vdev_remove_parent(cvd);
3599                 cvd->vdev_splitting = B_TRUE;
3600         }
3601         vdev_propagate_state(cvd);
3602 }
3603
3604 void
3605 vdev_deadman(vdev_t *vd)
3606 {
3607         for (int c = 0; c < vd->vdev_children; c++) {
3608                 vdev_t *cvd = vd->vdev_child[c];
3609
3610                 vdev_deadman(cvd);
3611         }
3612
3613         if (vd->vdev_ops->vdev_op_leaf) {
3614                 vdev_queue_t *vq = &vd->vdev_queue;
3615
3616                 mutex_enter(&vq->vq_lock);
3617                 if (avl_numnodes(&vq->vq_active_tree) > 0) {
3618                         spa_t *spa = vd->vdev_spa;
3619                         zio_t *fio;
3620                         uint64_t delta;
3621
3622                         /*
3623                          * Look at the head of all the pending queues,
3624                          * if any I/O has been outstanding for longer than
3625                          * the spa_deadman_synctime we panic the system.
3626                          */
3627                         fio = avl_first(&vq->vq_active_tree);
3628                         delta = gethrtime() - fio->io_timestamp;
3629                         if (delta > spa_deadman_synctime(spa)) {
3630                                 zfs_dbgmsg("SLOW IO: zio timestamp %lluns, "
3631                                     "delta %lluns, last io %lluns",
3632                                     fio->io_timestamp, delta,
3633                                     vq->vq_io_complete_ts);
3634                                 fm_panic("I/O to pool '%s' appears to be "
3635                                     "hung on vdev guid %llu at '%s'.",
3636                                     spa_name(spa),
3637                                     (long long unsigned int) vd->vdev_guid,
3638                                     vd->vdev_path);
3639                         }
3640                 }
3641                 mutex_exit(&vq->vq_lock);
3642         }
3643 }