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