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