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