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