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