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