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