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