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