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