]> granicus.if.org Git - zfs/blob - module/zfs/vdev.c
Remove unused vdev_t fields
[zfs] / 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 /* target number of metaslabs per top-level vdev */
58 int vdev_max_ms_count = 200;
59
60 /* minimum number of metaslabs per top-level vdev */
61 int vdev_min_ms_count = 16;
62
63 /* practical upper limit of total metaslabs per top-level vdev */
64 int vdev_ms_count_limit = 1ULL << 17;
65
66 /* lower limit for metaslab size (512M) */
67 int vdev_default_ms_shift = 29;
68
69 /* upper limit for metaslab size (256G) */
70 int vdev_max_ms_shift = 38;
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                 uint64_t count = vd->vdev_ms_count;
1350
1351                 metaslab_group_passivate(vd->vdev_mg);
1352                 for (uint64_t m = 0; m < count; m++) {
1353                         metaslab_t *msp = vd->vdev_ms[m];
1354
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         ASSERT0(vd->vdev_ms_count);
1364         ASSERT3U(vd->vdev_pending_fastwrite, ==, 0);
1365 }
1366
1367 typedef struct vdev_probe_stats {
1368         boolean_t       vps_readable;
1369         boolean_t       vps_writeable;
1370         int             vps_flags;
1371 } vdev_probe_stats_t;
1372
1373 static void
1374 vdev_probe_done(zio_t *zio)
1375 {
1376         spa_t *spa = zio->io_spa;
1377         vdev_t *vd = zio->io_vd;
1378         vdev_probe_stats_t *vps = zio->io_private;
1379
1380         ASSERT(vd->vdev_probe_zio != NULL);
1381
1382         if (zio->io_type == ZIO_TYPE_READ) {
1383                 if (zio->io_error == 0)
1384                         vps->vps_readable = 1;
1385                 if (zio->io_error == 0 && spa_writeable(spa)) {
1386                         zio_nowait(zio_write_phys(vd->vdev_probe_zio, vd,
1387                             zio->io_offset, zio->io_size, zio->io_abd,
1388                             ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1389                             ZIO_PRIORITY_SYNC_WRITE, vps->vps_flags, B_TRUE));
1390                 } else {
1391                         abd_free(zio->io_abd);
1392                 }
1393         } else if (zio->io_type == ZIO_TYPE_WRITE) {
1394                 if (zio->io_error == 0)
1395                         vps->vps_writeable = 1;
1396                 abd_free(zio->io_abd);
1397         } else if (zio->io_type == ZIO_TYPE_NULL) {
1398                 zio_t *pio;
1399                 zio_link_t *zl;
1400
1401                 vd->vdev_cant_read |= !vps->vps_readable;
1402                 vd->vdev_cant_write |= !vps->vps_writeable;
1403
1404                 if (vdev_readable(vd) &&
1405                     (vdev_writeable(vd) || !spa_writeable(spa))) {
1406                         zio->io_error = 0;
1407                 } else {
1408                         ASSERT(zio->io_error != 0);
1409                         vdev_dbgmsg(vd, "failed probe");
1410                         zfs_ereport_post(FM_EREPORT_ZFS_PROBE_FAILURE,
1411                             spa, vd, NULL, NULL, 0, 0);
1412                         zio->io_error = SET_ERROR(ENXIO);
1413                 }
1414
1415                 mutex_enter(&vd->vdev_probe_lock);
1416                 ASSERT(vd->vdev_probe_zio == zio);
1417                 vd->vdev_probe_zio = NULL;
1418                 mutex_exit(&vd->vdev_probe_lock);
1419
1420                 zl = NULL;
1421                 while ((pio = zio_walk_parents(zio, &zl)) != NULL)
1422                         if (!vdev_accessible(vd, pio))
1423                                 pio->io_error = SET_ERROR(ENXIO);
1424
1425                 kmem_free(vps, sizeof (*vps));
1426         }
1427 }
1428
1429 /*
1430  * Determine whether this device is accessible.
1431  *
1432  * Read and write to several known locations: the pad regions of each
1433  * vdev label but the first, which we leave alone in case it contains
1434  * a VTOC.
1435  */
1436 zio_t *
1437 vdev_probe(vdev_t *vd, zio_t *zio)
1438 {
1439         spa_t *spa = vd->vdev_spa;
1440         vdev_probe_stats_t *vps = NULL;
1441         zio_t *pio;
1442
1443         ASSERT(vd->vdev_ops->vdev_op_leaf);
1444
1445         /*
1446          * Don't probe the probe.
1447          */
1448         if (zio && (zio->io_flags & ZIO_FLAG_PROBE))
1449                 return (NULL);
1450
1451         /*
1452          * To prevent 'probe storms' when a device fails, we create
1453          * just one probe i/o at a time.  All zios that want to probe
1454          * this vdev will become parents of the probe io.
1455          */
1456         mutex_enter(&vd->vdev_probe_lock);
1457
1458         if ((pio = vd->vdev_probe_zio) == NULL) {
1459                 vps = kmem_zalloc(sizeof (*vps), KM_SLEEP);
1460
1461                 vps->vps_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_PROBE |
1462                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE |
1463                     ZIO_FLAG_TRYHARD;
1464
1465                 if (spa_config_held(spa, SCL_ZIO, RW_WRITER)) {
1466                         /*
1467                          * vdev_cant_read and vdev_cant_write can only
1468                          * transition from TRUE to FALSE when we have the
1469                          * SCL_ZIO lock as writer; otherwise they can only
1470                          * transition from FALSE to TRUE.  This ensures that
1471                          * any zio looking at these values can assume that
1472                          * failures persist for the life of the I/O.  That's
1473                          * important because when a device has intermittent
1474                          * connectivity problems, we want to ensure that
1475                          * they're ascribed to the device (ENXIO) and not
1476                          * the zio (EIO).
1477                          *
1478                          * Since we hold SCL_ZIO as writer here, clear both
1479                          * values so the probe can reevaluate from first
1480                          * principles.
1481                          */
1482                         vps->vps_flags |= ZIO_FLAG_CONFIG_WRITER;
1483                         vd->vdev_cant_read = B_FALSE;
1484                         vd->vdev_cant_write = B_FALSE;
1485                 }
1486
1487                 vd->vdev_probe_zio = pio = zio_null(NULL, spa, vd,
1488                     vdev_probe_done, vps,
1489                     vps->vps_flags | ZIO_FLAG_DONT_PROPAGATE);
1490
1491                 /*
1492                  * We can't change the vdev state in this context, so we
1493                  * kick off an async task to do it on our behalf.
1494                  */
1495                 if (zio != NULL) {
1496                         vd->vdev_probe_wanted = B_TRUE;
1497                         spa_async_request(spa, SPA_ASYNC_PROBE);
1498                 }
1499         }
1500
1501         if (zio != NULL)
1502                 zio_add_child(zio, pio);
1503
1504         mutex_exit(&vd->vdev_probe_lock);
1505
1506         if (vps == NULL) {
1507                 ASSERT(zio != NULL);
1508                 return (NULL);
1509         }
1510
1511         for (int l = 1; l < VDEV_LABELS; l++) {
1512                 zio_nowait(zio_read_phys(pio, vd,
1513                     vdev_label_offset(vd->vdev_psize, l,
1514                     offsetof(vdev_label_t, vl_pad2)), VDEV_PAD_SIZE,
1515                     abd_alloc_for_io(VDEV_PAD_SIZE, B_TRUE),
1516                     ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
1517                     ZIO_PRIORITY_SYNC_READ, vps->vps_flags, B_TRUE));
1518         }
1519
1520         if (zio == NULL)
1521                 return (pio);
1522
1523         zio_nowait(pio);
1524         return (NULL);
1525 }
1526
1527 static void
1528 vdev_open_child(void *arg)
1529 {
1530         vdev_t *vd = arg;
1531
1532         vd->vdev_open_thread = curthread;
1533         vd->vdev_open_error = vdev_open(vd);
1534         vd->vdev_open_thread = NULL;
1535 }
1536
1537 static boolean_t
1538 vdev_uses_zvols(vdev_t *vd)
1539 {
1540 #ifdef _KERNEL
1541         if (zvol_is_zvol(vd->vdev_path))
1542                 return (B_TRUE);
1543 #endif
1544
1545         for (int c = 0; c < vd->vdev_children; c++)
1546                 if (vdev_uses_zvols(vd->vdev_child[c]))
1547                         return (B_TRUE);
1548
1549         return (B_FALSE);
1550 }
1551
1552 void
1553 vdev_open_children(vdev_t *vd)
1554 {
1555         taskq_t *tq;
1556         int children = vd->vdev_children;
1557
1558         /*
1559          * in order to handle pools on top of zvols, do the opens
1560          * in a single thread so that the same thread holds the
1561          * spa_namespace_lock
1562          */
1563         if (vdev_uses_zvols(vd)) {
1564 retry_sync:
1565                 for (int c = 0; c < children; c++)
1566                         vd->vdev_child[c]->vdev_open_error =
1567                             vdev_open(vd->vdev_child[c]);
1568         } else {
1569                 tq = taskq_create("vdev_open", children, minclsyspri,
1570                     children, children, TASKQ_PREPOPULATE);
1571                 if (tq == NULL)
1572                         goto retry_sync;
1573
1574                 for (int c = 0; c < children; c++)
1575                         VERIFY(taskq_dispatch(tq, vdev_open_child,
1576                             vd->vdev_child[c], TQ_SLEEP) != TASKQID_INVALID);
1577
1578                 taskq_destroy(tq);
1579         }
1580
1581         vd->vdev_nonrot = B_TRUE;
1582
1583         for (int c = 0; c < children; c++)
1584                 vd->vdev_nonrot &= vd->vdev_child[c]->vdev_nonrot;
1585 }
1586
1587 /*
1588  * Compute the raidz-deflation ratio.  Note, we hard-code
1589  * in 128k (1 << 17) because it is the "typical" blocksize.
1590  * Even though SPA_MAXBLOCKSIZE changed, this algorithm can not change,
1591  * otherwise it would inconsistently account for existing bp's.
1592  */
1593 static void
1594 vdev_set_deflate_ratio(vdev_t *vd)
1595 {
1596         if (vd == vd->vdev_top && !vd->vdev_ishole && vd->vdev_ashift != 0) {
1597                 vd->vdev_deflate_ratio = (1 << 17) /
1598                     (vdev_psize_to_asize(vd, 1 << 17) >> SPA_MINBLOCKSHIFT);
1599         }
1600 }
1601
1602 /*
1603  * Prepare a virtual device for access.
1604  */
1605 int
1606 vdev_open(vdev_t *vd)
1607 {
1608         spa_t *spa = vd->vdev_spa;
1609         int error;
1610         uint64_t osize = 0;
1611         uint64_t max_osize = 0;
1612         uint64_t asize, max_asize, psize;
1613         uint64_t ashift = 0;
1614
1615         ASSERT(vd->vdev_open_thread == curthread ||
1616             spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1617         ASSERT(vd->vdev_state == VDEV_STATE_CLOSED ||
1618             vd->vdev_state == VDEV_STATE_CANT_OPEN ||
1619             vd->vdev_state == VDEV_STATE_OFFLINE);
1620
1621         vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
1622         vd->vdev_cant_read = B_FALSE;
1623         vd->vdev_cant_write = B_FALSE;
1624         vd->vdev_min_asize = vdev_get_min_asize(vd);
1625
1626         /*
1627          * If this vdev is not removed, check its fault status.  If it's
1628          * faulted, bail out of the open.
1629          */
1630         if (!vd->vdev_removed && vd->vdev_faulted) {
1631                 ASSERT(vd->vdev_children == 0);
1632                 ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
1633                     vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
1634                 vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1635                     vd->vdev_label_aux);
1636                 return (SET_ERROR(ENXIO));
1637         } else if (vd->vdev_offline) {
1638                 ASSERT(vd->vdev_children == 0);
1639                 vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE, VDEV_AUX_NONE);
1640                 return (SET_ERROR(ENXIO));
1641         }
1642
1643         error = vd->vdev_ops->vdev_op_open(vd, &osize, &max_osize, &ashift);
1644
1645         /*
1646          * Reset the vdev_reopening flag so that we actually close
1647          * the vdev on error.
1648          */
1649         vd->vdev_reopening = B_FALSE;
1650         if (zio_injection_enabled && error == 0)
1651                 error = zio_handle_device_injection(vd, NULL, ENXIO);
1652
1653         if (error) {
1654                 if (vd->vdev_removed &&
1655                     vd->vdev_stat.vs_aux != VDEV_AUX_OPEN_FAILED)
1656                         vd->vdev_removed = B_FALSE;
1657
1658                 if (vd->vdev_stat.vs_aux == VDEV_AUX_CHILDREN_OFFLINE) {
1659                         vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE,
1660                             vd->vdev_stat.vs_aux);
1661                 } else {
1662                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1663                             vd->vdev_stat.vs_aux);
1664                 }
1665                 return (error);
1666         }
1667
1668         vd->vdev_removed = B_FALSE;
1669
1670         /*
1671          * Recheck the faulted flag now that we have confirmed that
1672          * the vdev is accessible.  If we're faulted, bail.
1673          */
1674         if (vd->vdev_faulted) {
1675                 ASSERT(vd->vdev_children == 0);
1676                 ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
1677                     vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
1678                 vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1679                     vd->vdev_label_aux);
1680                 return (SET_ERROR(ENXIO));
1681         }
1682
1683         if (vd->vdev_degraded) {
1684                 ASSERT(vd->vdev_children == 0);
1685                 vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
1686                     VDEV_AUX_ERR_EXCEEDED);
1687         } else {
1688                 vdev_set_state(vd, B_TRUE, VDEV_STATE_HEALTHY, 0);
1689         }
1690
1691         /*
1692          * For hole or missing vdevs we just return success.
1693          */
1694         if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops)
1695                 return (0);
1696
1697         for (int c = 0; c < vd->vdev_children; c++) {
1698                 if (vd->vdev_child[c]->vdev_state != VDEV_STATE_HEALTHY) {
1699                         vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
1700                             VDEV_AUX_NONE);
1701                         break;
1702                 }
1703         }
1704
1705         osize = P2ALIGN(osize, (uint64_t)sizeof (vdev_label_t));
1706         max_osize = P2ALIGN(max_osize, (uint64_t)sizeof (vdev_label_t));
1707
1708         if (vd->vdev_children == 0) {
1709                 if (osize < SPA_MINDEVSIZE) {
1710                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1711                             VDEV_AUX_TOO_SMALL);
1712                         return (SET_ERROR(EOVERFLOW));
1713                 }
1714                 psize = osize;
1715                 asize = osize - (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE);
1716                 max_asize = max_osize - (VDEV_LABEL_START_SIZE +
1717                     VDEV_LABEL_END_SIZE);
1718         } else {
1719                 if (vd->vdev_parent != NULL && osize < SPA_MINDEVSIZE -
1720                     (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE)) {
1721                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1722                             VDEV_AUX_TOO_SMALL);
1723                         return (SET_ERROR(EOVERFLOW));
1724                 }
1725                 psize = 0;
1726                 asize = osize;
1727                 max_asize = max_osize;
1728         }
1729
1730         /*
1731          * If the vdev was expanded, record this so that we can re-create the
1732          * uberblock rings in labels {2,3}, during the next sync.
1733          */
1734         if ((psize > vd->vdev_psize) && (vd->vdev_psize != 0))
1735                 vd->vdev_copy_uberblocks = B_TRUE;
1736
1737         vd->vdev_psize = psize;
1738
1739         /*
1740          * Make sure the allocatable size hasn't shrunk too much.
1741          */
1742         if (asize < vd->vdev_min_asize) {
1743                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1744                     VDEV_AUX_BAD_LABEL);
1745                 return (SET_ERROR(EINVAL));
1746         }
1747
1748         if (vd->vdev_asize == 0) {
1749                 /*
1750                  * This is the first-ever open, so use the computed values.
1751                  * For compatibility, a different ashift can be requested.
1752                  */
1753                 vd->vdev_asize = asize;
1754                 vd->vdev_max_asize = max_asize;
1755                 if (vd->vdev_ashift == 0) {
1756                         vd->vdev_ashift = ashift; /* use detected value */
1757                 }
1758                 if (vd->vdev_ashift != 0 && (vd->vdev_ashift < ASHIFT_MIN ||
1759                     vd->vdev_ashift > ASHIFT_MAX)) {
1760                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1761                             VDEV_AUX_BAD_ASHIFT);
1762                         return (SET_ERROR(EDOM));
1763                 }
1764         } else {
1765                 /*
1766                  * Detect if the alignment requirement has increased.
1767                  * We don't want to make the pool unavailable, just
1768                  * post an event instead.
1769                  */
1770                 if (ashift > vd->vdev_top->vdev_ashift &&
1771                     vd->vdev_ops->vdev_op_leaf) {
1772                         zfs_ereport_post(FM_EREPORT_ZFS_DEVICE_BAD_ASHIFT,
1773                             spa, vd, NULL, NULL, 0, 0);
1774                 }
1775
1776                 vd->vdev_max_asize = max_asize;
1777         }
1778
1779         /*
1780          * If all children are healthy we update asize if either:
1781          * The asize has increased, due to a device expansion caused by dynamic
1782          * LUN growth or vdev replacement, and automatic expansion is enabled;
1783          * making the additional space available.
1784          *
1785          * The asize has decreased, due to a device shrink usually caused by a
1786          * vdev replace with a smaller device. This ensures that calculations
1787          * based of max_asize and asize e.g. esize are always valid. It's safe
1788          * to do this as we've already validated that asize is greater than
1789          * vdev_min_asize.
1790          */
1791         if (vd->vdev_state == VDEV_STATE_HEALTHY &&
1792             ((asize > vd->vdev_asize &&
1793             (vd->vdev_expanding || spa->spa_autoexpand)) ||
1794             (asize < vd->vdev_asize)))
1795                 vd->vdev_asize = asize;
1796
1797         vdev_set_min_asize(vd);
1798
1799         /*
1800          * Ensure we can issue some IO before declaring the
1801          * vdev open for business.
1802          */
1803         if (vd->vdev_ops->vdev_op_leaf &&
1804             (error = zio_wait(vdev_probe(vd, NULL))) != 0) {
1805                 vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
1806                     VDEV_AUX_ERR_EXCEEDED);
1807                 return (error);
1808         }
1809
1810         /*
1811          * Track the min and max ashift values for normal data devices.
1812          *
1813          * DJB - TBD these should perhaps be tracked per allocation class
1814          * (e.g. spa_min_ashift is used to round up post compression buffers)
1815          */
1816         if (vd->vdev_top == vd && vd->vdev_ashift != 0 &&
1817             vd->vdev_alloc_bias == VDEV_BIAS_NONE &&
1818             vd->vdev_aux == NULL) {
1819                 if (vd->vdev_ashift > spa->spa_max_ashift)
1820                         spa->spa_max_ashift = vd->vdev_ashift;
1821                 if (vd->vdev_ashift < spa->spa_min_ashift)
1822                         spa->spa_min_ashift = vd->vdev_ashift;
1823         }
1824
1825         /*
1826          * If a leaf vdev has a DTL, and seems healthy, then kick off a
1827          * resilver.  But don't do this if we are doing a reopen for a scrub,
1828          * since this would just restart the scrub we are already doing.
1829          */
1830         if (vd->vdev_ops->vdev_op_leaf && !spa->spa_scrub_reopen &&
1831             vdev_resilver_needed(vd, NULL, NULL)) {
1832                 if (dsl_scan_resilvering(spa->spa_dsl_pool) &&
1833                     spa_feature_is_enabled(spa, SPA_FEATURE_RESILVER_DEFER))
1834                         vdev_set_deferred_resilver(spa, vd);
1835                 else
1836                         spa_async_request(spa, SPA_ASYNC_RESILVER);
1837         }
1838
1839         return (0);
1840 }
1841
1842 /*
1843  * Called once the vdevs are all opened, this routine validates the label
1844  * contents. This needs to be done before vdev_load() so that we don't
1845  * inadvertently do repair I/Os to the wrong device.
1846  *
1847  * This function will only return failure if one of the vdevs indicates that it
1848  * has since been destroyed or exported.  This is only possible if
1849  * /etc/zfs/zpool.cache was readonly at the time.  Otherwise, the vdev state
1850  * will be updated but the function will return 0.
1851  */
1852 int
1853 vdev_validate(vdev_t *vd)
1854 {
1855         spa_t *spa = vd->vdev_spa;
1856         nvlist_t *label;
1857         uint64_t guid = 0, aux_guid = 0, top_guid;
1858         uint64_t state;
1859         nvlist_t *nvl;
1860         uint64_t txg;
1861
1862         if (vdev_validate_skip)
1863                 return (0);
1864
1865         for (uint64_t c = 0; c < vd->vdev_children; c++)
1866                 if (vdev_validate(vd->vdev_child[c]) != 0)
1867                         return (SET_ERROR(EBADF));
1868
1869         /*
1870          * If the device has already failed, or was marked offline, don't do
1871          * any further validation.  Otherwise, label I/O will fail and we will
1872          * overwrite the previous state.
1873          */
1874         if (!vd->vdev_ops->vdev_op_leaf || !vdev_readable(vd))
1875                 return (0);
1876
1877         /*
1878          * If we are performing an extreme rewind, we allow for a label that
1879          * was modified at a point after the current txg.
1880          * If config lock is not held do not check for the txg. spa_sync could
1881          * be updating the vdev's label before updating spa_last_synced_txg.
1882          */
1883         if (spa->spa_extreme_rewind || spa_last_synced_txg(spa) == 0 ||
1884             spa_config_held(spa, SCL_CONFIG, RW_WRITER) != SCL_CONFIG)
1885                 txg = UINT64_MAX;
1886         else
1887                 txg = spa_last_synced_txg(spa);
1888
1889         if ((label = vdev_label_read_config(vd, txg)) == NULL) {
1890                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1891                     VDEV_AUX_BAD_LABEL);
1892                 vdev_dbgmsg(vd, "vdev_validate: failed reading config for "
1893                     "txg %llu", (u_longlong_t)txg);
1894                 return (0);
1895         }
1896
1897         /*
1898          * Determine if this vdev has been split off into another
1899          * pool.  If so, then refuse to open it.
1900          */
1901         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_SPLIT_GUID,
1902             &aux_guid) == 0 && aux_guid == spa_guid(spa)) {
1903                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1904                     VDEV_AUX_SPLIT_POOL);
1905                 nvlist_free(label);
1906                 vdev_dbgmsg(vd, "vdev_validate: vdev split into other pool");
1907                 return (0);
1908         }
1909
1910         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID, &guid) != 0) {
1911                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1912                     VDEV_AUX_CORRUPT_DATA);
1913                 nvlist_free(label);
1914                 vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
1915                     ZPOOL_CONFIG_POOL_GUID);
1916                 return (0);
1917         }
1918
1919         /*
1920          * If config is not trusted then ignore the spa guid check. This is
1921          * necessary because if the machine crashed during a re-guid the new
1922          * guid might have been written to all of the vdev labels, but not the
1923          * cached config. The check will be performed again once we have the
1924          * trusted config from the MOS.
1925          */
1926         if (spa->spa_trust_config && guid != spa_guid(spa)) {
1927                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1928                     VDEV_AUX_CORRUPT_DATA);
1929                 nvlist_free(label);
1930                 vdev_dbgmsg(vd, "vdev_validate: vdev label pool_guid doesn't "
1931                     "match config (%llu != %llu)", (u_longlong_t)guid,
1932                     (u_longlong_t)spa_guid(spa));
1933                 return (0);
1934         }
1935
1936         if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_VDEV_TREE, &nvl)
1937             != 0 || nvlist_lookup_uint64(nvl, ZPOOL_CONFIG_ORIG_GUID,
1938             &aux_guid) != 0)
1939                 aux_guid = 0;
1940
1941         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0) {
1942                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1943                     VDEV_AUX_CORRUPT_DATA);
1944                 nvlist_free(label);
1945                 vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
1946                     ZPOOL_CONFIG_GUID);
1947                 return (0);
1948         }
1949
1950         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_TOP_GUID, &top_guid)
1951             != 0) {
1952                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1953                     VDEV_AUX_CORRUPT_DATA);
1954                 nvlist_free(label);
1955                 vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
1956                     ZPOOL_CONFIG_TOP_GUID);
1957                 return (0);
1958         }
1959
1960         /*
1961          * If this vdev just became a top-level vdev because its sibling was
1962          * detached, it will have adopted the parent's vdev guid -- but the
1963          * label may or may not be on disk yet. Fortunately, either version
1964          * of the label will have the same top guid, so if we're a top-level
1965          * vdev, we can safely compare to that instead.
1966          * However, if the config comes from a cachefile that failed to update
1967          * after the detach, a top-level vdev will appear as a non top-level
1968          * vdev in the config. Also relax the constraints if we perform an
1969          * extreme rewind.
1970          *
1971          * If we split this vdev off instead, then we also check the
1972          * original pool's guid. We don't want to consider the vdev
1973          * corrupt if it is partway through a split operation.
1974          */
1975         if (vd->vdev_guid != guid && vd->vdev_guid != aux_guid) {
1976                 boolean_t mismatch = B_FALSE;
1977                 if (spa->spa_trust_config && !spa->spa_extreme_rewind) {
1978                         if (vd != vd->vdev_top || vd->vdev_guid != top_guid)
1979                                 mismatch = B_TRUE;
1980                 } else {
1981                         if (vd->vdev_guid != top_guid &&
1982                             vd->vdev_top->vdev_guid != guid)
1983                                 mismatch = B_TRUE;
1984                 }
1985
1986                 if (mismatch) {
1987                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1988                             VDEV_AUX_CORRUPT_DATA);
1989                         nvlist_free(label);
1990                         vdev_dbgmsg(vd, "vdev_validate: config guid "
1991                             "doesn't match label guid");
1992                         vdev_dbgmsg(vd, "CONFIG: guid %llu, top_guid %llu",
1993                             (u_longlong_t)vd->vdev_guid,
1994                             (u_longlong_t)vd->vdev_top->vdev_guid);
1995                         vdev_dbgmsg(vd, "LABEL: guid %llu, top_guid %llu, "
1996                             "aux_guid %llu", (u_longlong_t)guid,
1997                             (u_longlong_t)top_guid, (u_longlong_t)aux_guid);
1998                         return (0);
1999                 }
2000         }
2001
2002         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
2003             &state) != 0) {
2004                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
2005                     VDEV_AUX_CORRUPT_DATA);
2006                 nvlist_free(label);
2007                 vdev_dbgmsg(vd, "vdev_validate: '%s' missing from label",
2008                     ZPOOL_CONFIG_POOL_STATE);
2009                 return (0);
2010         }
2011
2012         nvlist_free(label);
2013
2014         /*
2015          * If this is a verbatim import, no need to check the
2016          * state of the pool.
2017          */
2018         if (!(spa->spa_import_flags & ZFS_IMPORT_VERBATIM) &&
2019             spa_load_state(spa) == SPA_LOAD_OPEN &&
2020             state != POOL_STATE_ACTIVE) {
2021                 vdev_dbgmsg(vd, "vdev_validate: invalid pool state (%llu) "
2022                     "for spa %s", (u_longlong_t)state, spa->spa_name);
2023                 return (SET_ERROR(EBADF));
2024         }
2025
2026         /*
2027          * If we were able to open and validate a vdev that was
2028          * previously marked permanently unavailable, clear that state
2029          * now.
2030          */
2031         if (vd->vdev_not_present)
2032                 vd->vdev_not_present = 0;
2033
2034         return (0);
2035 }
2036
2037 static void
2038 vdev_copy_path_impl(vdev_t *svd, vdev_t *dvd)
2039 {
2040         if (svd->vdev_path != NULL && dvd->vdev_path != NULL) {
2041                 if (strcmp(svd->vdev_path, dvd->vdev_path) != 0) {
2042                         zfs_dbgmsg("vdev_copy_path: vdev %llu: path changed "
2043                             "from '%s' to '%s'", (u_longlong_t)dvd->vdev_guid,
2044                             dvd->vdev_path, svd->vdev_path);
2045                         spa_strfree(dvd->vdev_path);
2046                         dvd->vdev_path = spa_strdup(svd->vdev_path);
2047                 }
2048         } else if (svd->vdev_path != NULL) {
2049                 dvd->vdev_path = spa_strdup(svd->vdev_path);
2050                 zfs_dbgmsg("vdev_copy_path: vdev %llu: path set to '%s'",
2051                     (u_longlong_t)dvd->vdev_guid, dvd->vdev_path);
2052         }
2053 }
2054
2055 /*
2056  * Recursively copy vdev paths from one vdev to another. Source and destination
2057  * vdev trees must have same geometry otherwise return error. Intended to copy
2058  * paths from userland config into MOS config.
2059  */
2060 int
2061 vdev_copy_path_strict(vdev_t *svd, vdev_t *dvd)
2062 {
2063         if ((svd->vdev_ops == &vdev_missing_ops) ||
2064             (svd->vdev_ishole && dvd->vdev_ishole) ||
2065             (dvd->vdev_ops == &vdev_indirect_ops))
2066                 return (0);
2067
2068         if (svd->vdev_ops != dvd->vdev_ops) {
2069                 vdev_dbgmsg(svd, "vdev_copy_path: vdev type mismatch: %s != %s",
2070                     svd->vdev_ops->vdev_op_type, dvd->vdev_ops->vdev_op_type);
2071                 return (SET_ERROR(EINVAL));
2072         }
2073
2074         if (svd->vdev_guid != dvd->vdev_guid) {
2075                 vdev_dbgmsg(svd, "vdev_copy_path: guids mismatch (%llu != "
2076                     "%llu)", (u_longlong_t)svd->vdev_guid,
2077                     (u_longlong_t)dvd->vdev_guid);
2078                 return (SET_ERROR(EINVAL));
2079         }
2080
2081         if (svd->vdev_children != dvd->vdev_children) {
2082                 vdev_dbgmsg(svd, "vdev_copy_path: children count mismatch: "
2083                     "%llu != %llu", (u_longlong_t)svd->vdev_children,
2084                     (u_longlong_t)dvd->vdev_children);
2085                 return (SET_ERROR(EINVAL));
2086         }
2087
2088         for (uint64_t i = 0; i < svd->vdev_children; i++) {
2089                 int error = vdev_copy_path_strict(svd->vdev_child[i],
2090                     dvd->vdev_child[i]);
2091                 if (error != 0)
2092                         return (error);
2093         }
2094
2095         if (svd->vdev_ops->vdev_op_leaf)
2096                 vdev_copy_path_impl(svd, dvd);
2097
2098         return (0);
2099 }
2100
2101 static void
2102 vdev_copy_path_search(vdev_t *stvd, vdev_t *dvd)
2103 {
2104         ASSERT(stvd->vdev_top == stvd);
2105         ASSERT3U(stvd->vdev_id, ==, dvd->vdev_top->vdev_id);
2106
2107         for (uint64_t i = 0; i < dvd->vdev_children; i++) {
2108                 vdev_copy_path_search(stvd, dvd->vdev_child[i]);
2109         }
2110
2111         if (!dvd->vdev_ops->vdev_op_leaf || !vdev_is_concrete(dvd))
2112                 return;
2113
2114         /*
2115          * The idea here is that while a vdev can shift positions within
2116          * a top vdev (when replacing, attaching mirror, etc.) it cannot
2117          * step outside of it.
2118          */
2119         vdev_t *vd = vdev_lookup_by_guid(stvd, dvd->vdev_guid);
2120
2121         if (vd == NULL || vd->vdev_ops != dvd->vdev_ops)
2122                 return;
2123
2124         ASSERT(vd->vdev_ops->vdev_op_leaf);
2125
2126         vdev_copy_path_impl(vd, dvd);
2127 }
2128
2129 /*
2130  * Recursively copy vdev paths from one root vdev to another. Source and
2131  * destination vdev trees may differ in geometry. For each destination leaf
2132  * vdev, search a vdev with the same guid and top vdev id in the source.
2133  * Intended to copy paths from userland config into MOS config.
2134  */
2135 void
2136 vdev_copy_path_relaxed(vdev_t *srvd, vdev_t *drvd)
2137 {
2138         uint64_t children = MIN(srvd->vdev_children, drvd->vdev_children);
2139         ASSERT(srvd->vdev_ops == &vdev_root_ops);
2140         ASSERT(drvd->vdev_ops == &vdev_root_ops);
2141
2142         for (uint64_t i = 0; i < children; i++) {
2143                 vdev_copy_path_search(srvd->vdev_child[i],
2144                     drvd->vdev_child[i]);
2145         }
2146 }
2147
2148 /*
2149  * Close a virtual device.
2150  */
2151 void
2152 vdev_close(vdev_t *vd)
2153 {
2154         vdev_t *pvd = vd->vdev_parent;
2155         ASSERTV(spa_t *spa = vd->vdev_spa);
2156
2157         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2158
2159         /*
2160          * If our parent is reopening, then we are as well, unless we are
2161          * going offline.
2162          */
2163         if (pvd != NULL && pvd->vdev_reopening)
2164                 vd->vdev_reopening = (pvd->vdev_reopening && !vd->vdev_offline);
2165
2166         vd->vdev_ops->vdev_op_close(vd);
2167
2168         vdev_cache_purge(vd);
2169
2170         /*
2171          * We record the previous state before we close it, so that if we are
2172          * doing a reopen(), we don't generate FMA ereports if we notice that
2173          * it's still faulted.
2174          */
2175         vd->vdev_prevstate = vd->vdev_state;
2176
2177         if (vd->vdev_offline)
2178                 vd->vdev_state = VDEV_STATE_OFFLINE;
2179         else
2180                 vd->vdev_state = VDEV_STATE_CLOSED;
2181         vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
2182 }
2183
2184 void
2185 vdev_hold(vdev_t *vd)
2186 {
2187         spa_t *spa = vd->vdev_spa;
2188
2189         ASSERT(spa_is_root(spa));
2190         if (spa->spa_state == POOL_STATE_UNINITIALIZED)
2191                 return;
2192
2193         for (int c = 0; c < vd->vdev_children; c++)
2194                 vdev_hold(vd->vdev_child[c]);
2195
2196         if (vd->vdev_ops->vdev_op_leaf)
2197                 vd->vdev_ops->vdev_op_hold(vd);
2198 }
2199
2200 void
2201 vdev_rele(vdev_t *vd)
2202 {
2203         ASSERT(spa_is_root(vd->vdev_spa));
2204         for (int c = 0; c < vd->vdev_children; c++)
2205                 vdev_rele(vd->vdev_child[c]);
2206
2207         if (vd->vdev_ops->vdev_op_leaf)
2208                 vd->vdev_ops->vdev_op_rele(vd);
2209 }
2210
2211 /*
2212  * Reopen all interior vdevs and any unopened leaves.  We don't actually
2213  * reopen leaf vdevs which had previously been opened as they might deadlock
2214  * on the spa_config_lock.  Instead we only obtain the leaf's physical size.
2215  * If the leaf has never been opened then open it, as usual.
2216  */
2217 void
2218 vdev_reopen(vdev_t *vd)
2219 {
2220         spa_t *spa = vd->vdev_spa;
2221
2222         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2223
2224         /* set the reopening flag unless we're taking the vdev offline */
2225         vd->vdev_reopening = !vd->vdev_offline;
2226         vdev_close(vd);
2227         (void) vdev_open(vd);
2228
2229         /*
2230          * Call vdev_validate() here to make sure we have the same device.
2231          * Otherwise, a device with an invalid label could be successfully
2232          * opened in response to vdev_reopen().
2233          */
2234         if (vd->vdev_aux) {
2235                 (void) vdev_validate_aux(vd);
2236                 if (vdev_readable(vd) && vdev_writeable(vd) &&
2237                     vd->vdev_aux == &spa->spa_l2cache &&
2238                     !l2arc_vdev_present(vd))
2239                         l2arc_add_vdev(spa, vd);
2240         } else {
2241                 (void) vdev_validate(vd);
2242         }
2243
2244         /*
2245          * Reassess parent vdev's health.
2246          */
2247         vdev_propagate_state(vd);
2248 }
2249
2250 int
2251 vdev_create(vdev_t *vd, uint64_t txg, boolean_t isreplacing)
2252 {
2253         int error;
2254
2255         /*
2256          * Normally, partial opens (e.g. of a mirror) are allowed.
2257          * For a create, however, we want to fail the request if
2258          * there are any components we can't open.
2259          */
2260         error = vdev_open(vd);
2261
2262         if (error || vd->vdev_state != VDEV_STATE_HEALTHY) {
2263                 vdev_close(vd);
2264                 return (error ? error : ENXIO);
2265         }
2266
2267         /*
2268          * Recursively load DTLs and initialize all labels.
2269          */
2270         if ((error = vdev_dtl_load(vd)) != 0 ||
2271             (error = vdev_label_init(vd, txg, isreplacing ?
2272             VDEV_LABEL_REPLACE : VDEV_LABEL_CREATE)) != 0) {
2273                 vdev_close(vd);
2274                 return (error);
2275         }
2276
2277         return (0);
2278 }
2279
2280 void
2281 vdev_metaslab_set_size(vdev_t *vd)
2282 {
2283         uint64_t asize = vd->vdev_asize;
2284         uint64_t ms_count = asize >> vdev_default_ms_shift;
2285         uint64_t ms_shift;
2286
2287         /*
2288          * There are two dimensions to the metaslab sizing calculation:
2289          * the size of the metaslab and the count of metaslabs per vdev.
2290          * In general, we aim for vdev_max_ms_count (200) metaslabs. The
2291          * range of the dimensions are as follows:
2292          *
2293          *      2^29 <= ms_size  <= 2^38
2294          *        16 <= ms_count <= 131,072
2295          *
2296          * On the lower end of vdev sizes, we aim for metaslabs sizes of
2297          * at least 512MB (2^29) to minimize fragmentation effects when
2298          * testing with smaller devices.  However, the count constraint
2299          * of at least 16 metaslabs will override this minimum size goal.
2300          *
2301          * On the upper end of vdev sizes, we aim for a maximum metaslab
2302          * size of 256GB.  However, we will cap the total count to 2^17
2303          * metaslabs to keep our memory footprint in check.
2304          *
2305          * The net effect of applying above constrains is summarized below.
2306          *
2307          *      vdev size       metaslab count
2308          *      -------------|-----------------
2309          *      < 8GB           ~16
2310          *      8GB - 100GB     one per 512MB
2311          *      100GB - 50TB    ~200
2312          *      50TB - 32PB     one per 256GB
2313          *      > 32PB          ~131,072
2314          *      -------------------------------
2315          */
2316
2317         if (ms_count < vdev_min_ms_count)
2318                 ms_shift = highbit64(asize / vdev_min_ms_count);
2319         else if (ms_count > vdev_max_ms_count)
2320                 ms_shift = highbit64(asize / vdev_max_ms_count);
2321         else
2322                 ms_shift = vdev_default_ms_shift;
2323
2324         if (ms_shift < SPA_MAXBLOCKSHIFT) {
2325                 ms_shift = SPA_MAXBLOCKSHIFT;
2326         } else if (ms_shift > vdev_max_ms_shift) {
2327                 ms_shift = vdev_max_ms_shift;
2328                 /* cap the total count to constrain memory footprint */
2329                 if ((asize >> ms_shift) > vdev_ms_count_limit)
2330                         ms_shift = highbit64(asize / vdev_ms_count_limit);
2331         }
2332
2333         vd->vdev_ms_shift = ms_shift;
2334         ASSERT3U(vd->vdev_ms_shift, >=, SPA_MAXBLOCKSHIFT);
2335 }
2336
2337 void
2338 vdev_dirty(vdev_t *vd, int flags, void *arg, uint64_t txg)
2339 {
2340         ASSERT(vd == vd->vdev_top);
2341         /* indirect vdevs don't have metaslabs or dtls */
2342         ASSERT(vdev_is_concrete(vd) || flags == 0);
2343         ASSERT(ISP2(flags));
2344         ASSERT(spa_writeable(vd->vdev_spa));
2345
2346         if (flags & VDD_METASLAB)
2347                 (void) txg_list_add(&vd->vdev_ms_list, arg, txg);
2348
2349         if (flags & VDD_DTL)
2350                 (void) txg_list_add(&vd->vdev_dtl_list, arg, txg);
2351
2352         (void) txg_list_add(&vd->vdev_spa->spa_vdev_txg_list, vd, txg);
2353 }
2354
2355 void
2356 vdev_dirty_leaves(vdev_t *vd, int flags, uint64_t txg)
2357 {
2358         for (int c = 0; c < vd->vdev_children; c++)
2359                 vdev_dirty_leaves(vd->vdev_child[c], flags, txg);
2360
2361         if (vd->vdev_ops->vdev_op_leaf)
2362                 vdev_dirty(vd->vdev_top, flags, vd, txg);
2363 }
2364
2365 /*
2366  * DTLs.
2367  *
2368  * A vdev's DTL (dirty time log) is the set of transaction groups for which
2369  * the vdev has less than perfect replication.  There are four kinds of DTL:
2370  *
2371  * DTL_MISSING: txgs for which the vdev has no valid copies of the data
2372  *
2373  * DTL_PARTIAL: txgs for which data is available, but not fully replicated
2374  *
2375  * DTL_SCRUB: the txgs that could not be repaired by the last scrub; upon
2376  *      scrub completion, DTL_SCRUB replaces DTL_MISSING in the range of
2377  *      txgs that was scrubbed.
2378  *
2379  * DTL_OUTAGE: txgs which cannot currently be read, whether due to
2380  *      persistent errors or just some device being offline.
2381  *      Unlike the other three, the DTL_OUTAGE map is not generally
2382  *      maintained; it's only computed when needed, typically to
2383  *      determine whether a device can be detached.
2384  *
2385  * For leaf vdevs, DTL_MISSING and DTL_PARTIAL are identical: the device
2386  * either has the data or it doesn't.
2387  *
2388  * For interior vdevs such as mirror and RAID-Z the picture is more complex.
2389  * A vdev's DTL_PARTIAL is the union of its children's DTL_PARTIALs, because
2390  * if any child is less than fully replicated, then so is its parent.
2391  * A vdev's DTL_MISSING is a modified union of its children's DTL_MISSINGs,
2392  * comprising only those txgs which appear in 'maxfaults' or more children;
2393  * those are the txgs we don't have enough replication to read.  For example,
2394  * double-parity RAID-Z can tolerate up to two missing devices (maxfaults == 2);
2395  * thus, its DTL_MISSING consists of the set of txgs that appear in more than
2396  * two child DTL_MISSING maps.
2397  *
2398  * It should be clear from the above that to compute the DTLs and outage maps
2399  * for all vdevs, it suffices to know just the leaf vdevs' DTL_MISSING maps.
2400  * Therefore, that is all we keep on disk.  When loading the pool, or after
2401  * a configuration change, we generate all other DTLs from first principles.
2402  */
2403 void
2404 vdev_dtl_dirty(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
2405 {
2406         range_tree_t *rt = vd->vdev_dtl[t];
2407
2408         ASSERT(t < DTL_TYPES);
2409         ASSERT(vd != vd->vdev_spa->spa_root_vdev);
2410         ASSERT(spa_writeable(vd->vdev_spa));
2411
2412         mutex_enter(&vd->vdev_dtl_lock);
2413         if (!range_tree_contains(rt, txg, size))
2414                 range_tree_add(rt, txg, size);
2415         mutex_exit(&vd->vdev_dtl_lock);
2416 }
2417
2418 boolean_t
2419 vdev_dtl_contains(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
2420 {
2421         range_tree_t *rt = vd->vdev_dtl[t];
2422         boolean_t dirty = B_FALSE;
2423
2424         ASSERT(t < DTL_TYPES);
2425         ASSERT(vd != vd->vdev_spa->spa_root_vdev);
2426
2427         /*
2428          * While we are loading the pool, the DTLs have not been loaded yet.
2429          * Ignore the DTLs and try all devices.  This avoids a recursive
2430          * mutex enter on the vdev_dtl_lock, and also makes us try hard
2431          * when loading the pool (relying on the checksum to ensure that
2432          * we get the right data -- note that we while loading, we are
2433          * only reading the MOS, which is always checksummed).
2434          */
2435         if (vd->vdev_spa->spa_load_state != SPA_LOAD_NONE)
2436                 return (B_FALSE);
2437
2438         mutex_enter(&vd->vdev_dtl_lock);
2439         if (!range_tree_is_empty(rt))
2440                 dirty = range_tree_contains(rt, txg, size);
2441         mutex_exit(&vd->vdev_dtl_lock);
2442
2443         return (dirty);
2444 }
2445
2446 boolean_t
2447 vdev_dtl_empty(vdev_t *vd, vdev_dtl_type_t t)
2448 {
2449         range_tree_t *rt = vd->vdev_dtl[t];
2450         boolean_t empty;
2451
2452         mutex_enter(&vd->vdev_dtl_lock);
2453         empty = range_tree_is_empty(rt);
2454         mutex_exit(&vd->vdev_dtl_lock);
2455
2456         return (empty);
2457 }
2458
2459 /*
2460  * Returns B_TRUE if vdev determines offset needs to be resilvered.
2461  */
2462 boolean_t
2463 vdev_dtl_need_resilver(vdev_t *vd, uint64_t offset, size_t psize)
2464 {
2465         ASSERT(vd != vd->vdev_spa->spa_root_vdev);
2466
2467         if (vd->vdev_ops->vdev_op_need_resilver == NULL ||
2468             vd->vdev_ops->vdev_op_leaf)
2469                 return (B_TRUE);
2470
2471         return (vd->vdev_ops->vdev_op_need_resilver(vd, offset, psize));
2472 }
2473
2474 /*
2475  * Returns the lowest txg in the DTL range.
2476  */
2477 static uint64_t
2478 vdev_dtl_min(vdev_t *vd)
2479 {
2480         range_seg_t *rs;
2481
2482         ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
2483         ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
2484         ASSERT0(vd->vdev_children);
2485
2486         rs = avl_first(&vd->vdev_dtl[DTL_MISSING]->rt_root);
2487         return (rs->rs_start - 1);
2488 }
2489
2490 /*
2491  * Returns the highest txg in the DTL.
2492  */
2493 static uint64_t
2494 vdev_dtl_max(vdev_t *vd)
2495 {
2496         range_seg_t *rs;
2497
2498         ASSERT(MUTEX_HELD(&vd->vdev_dtl_lock));
2499         ASSERT3U(range_tree_space(vd->vdev_dtl[DTL_MISSING]), !=, 0);
2500         ASSERT0(vd->vdev_children);
2501
2502         rs = avl_last(&vd->vdev_dtl[DTL_MISSING]->rt_root);
2503         return (rs->rs_end);
2504 }
2505
2506 /*
2507  * Determine if a resilvering vdev should remove any DTL entries from
2508  * its range. If the vdev was resilvering for the entire duration of the
2509  * scan then it should excise that range from its DTLs. Otherwise, this
2510  * vdev is considered partially resilvered and should leave its DTL
2511  * entries intact. The comment in vdev_dtl_reassess() describes how we
2512  * excise the DTLs.
2513  */
2514 static boolean_t
2515 vdev_dtl_should_excise(vdev_t *vd)
2516 {
2517         spa_t *spa = vd->vdev_spa;
2518         dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
2519
2520         ASSERT0(scn->scn_phys.scn_errors);
2521         ASSERT0(vd->vdev_children);
2522
2523         if (vd->vdev_state < VDEV_STATE_DEGRADED)
2524                 return (B_FALSE);
2525
2526         if (vd->vdev_resilver_deferred)
2527                 return (B_FALSE);
2528
2529         if (vd->vdev_resilver_txg == 0 ||
2530             range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]))
2531                 return (B_TRUE);
2532
2533         /*
2534          * When a resilver is initiated the scan will assign the scn_max_txg
2535          * value to the highest txg value that exists in all DTLs. If this
2536          * device's max DTL is not part of this scan (i.e. it is not in
2537          * the range (scn_min_txg, scn_max_txg] then it is not eligible
2538          * for excision.
2539          */
2540         if (vdev_dtl_max(vd) <= scn->scn_phys.scn_max_txg) {
2541                 ASSERT3U(scn->scn_phys.scn_min_txg, <=, vdev_dtl_min(vd));
2542                 ASSERT3U(scn->scn_phys.scn_min_txg, <, vd->vdev_resilver_txg);
2543                 ASSERT3U(vd->vdev_resilver_txg, <=, scn->scn_phys.scn_max_txg);
2544                 return (B_TRUE);
2545         }
2546         return (B_FALSE);
2547 }
2548
2549 /*
2550  * Reassess DTLs after a config change or scrub completion. If txg == 0 no
2551  * write operations will be issued to the pool.
2552  */
2553 void
2554 vdev_dtl_reassess(vdev_t *vd, uint64_t txg, uint64_t scrub_txg, int scrub_done)
2555 {
2556         spa_t *spa = vd->vdev_spa;
2557         avl_tree_t reftree;
2558         int minref;
2559
2560         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
2561
2562         for (int c = 0; c < vd->vdev_children; c++)
2563                 vdev_dtl_reassess(vd->vdev_child[c], txg,
2564                     scrub_txg, scrub_done);
2565
2566         if (vd == spa->spa_root_vdev || !vdev_is_concrete(vd) || vd->vdev_aux)
2567                 return;
2568
2569         if (vd->vdev_ops->vdev_op_leaf) {
2570                 dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
2571
2572                 mutex_enter(&vd->vdev_dtl_lock);
2573
2574                 /*
2575                  * If requested, pretend the scan completed cleanly.
2576                  */
2577                 if (zfs_scan_ignore_errors && scn)
2578                         scn->scn_phys.scn_errors = 0;
2579
2580                 /*
2581                  * If we've completed a scan cleanly then determine
2582                  * if this vdev should remove any DTLs. We only want to
2583                  * excise regions on vdevs that were available during
2584                  * the entire duration of this scan.
2585                  */
2586                 if (scrub_txg != 0 &&
2587                     (spa->spa_scrub_started ||
2588                     (scn != NULL && scn->scn_phys.scn_errors == 0)) &&
2589                     vdev_dtl_should_excise(vd)) {
2590                         /*
2591                          * We completed a scrub up to scrub_txg.  If we
2592                          * did it without rebooting, then the scrub dtl
2593                          * will be valid, so excise the old region and
2594                          * fold in the scrub dtl.  Otherwise, leave the
2595                          * dtl as-is if there was an error.
2596                          *
2597                          * There's little trick here: to excise the beginning
2598                          * of the DTL_MISSING map, we put it into a reference
2599                          * tree and then add a segment with refcnt -1 that
2600                          * covers the range [0, scrub_txg).  This means
2601                          * that each txg in that range has refcnt -1 or 0.
2602                          * We then add DTL_SCRUB with a refcnt of 2, so that
2603                          * entries in the range [0, scrub_txg) will have a
2604                          * positive refcnt -- either 1 or 2.  We then convert
2605                          * the reference tree into the new DTL_MISSING map.
2606                          */
2607                         space_reftree_create(&reftree);
2608                         space_reftree_add_map(&reftree,
2609                             vd->vdev_dtl[DTL_MISSING], 1);
2610                         space_reftree_add_seg(&reftree, 0, scrub_txg, -1);
2611                         space_reftree_add_map(&reftree,
2612                             vd->vdev_dtl[DTL_SCRUB], 2);
2613                         space_reftree_generate_map(&reftree,
2614                             vd->vdev_dtl[DTL_MISSING], 1);
2615                         space_reftree_destroy(&reftree);
2616                 }
2617                 range_tree_vacate(vd->vdev_dtl[DTL_PARTIAL], NULL, NULL);
2618                 range_tree_walk(vd->vdev_dtl[DTL_MISSING],
2619                     range_tree_add, vd->vdev_dtl[DTL_PARTIAL]);
2620                 if (scrub_done)
2621                         range_tree_vacate(vd->vdev_dtl[DTL_SCRUB], NULL, NULL);
2622                 range_tree_vacate(vd->vdev_dtl[DTL_OUTAGE], NULL, NULL);
2623                 if (!vdev_readable(vd))
2624                         range_tree_add(vd->vdev_dtl[DTL_OUTAGE], 0, -1ULL);
2625                 else
2626                         range_tree_walk(vd->vdev_dtl[DTL_MISSING],
2627                             range_tree_add, vd->vdev_dtl[DTL_OUTAGE]);
2628
2629                 /*
2630                  * If the vdev was resilvering and no longer has any
2631                  * DTLs then reset its resilvering flag and dirty
2632                  * the top level so that we persist the change.
2633                  */
2634                 if (txg != 0 && vd->vdev_resilver_txg != 0 &&
2635                     range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]) &&
2636                     range_tree_is_empty(vd->vdev_dtl[DTL_OUTAGE])) {
2637                         vd->vdev_resilver_txg = 0;
2638                         vdev_config_dirty(vd->vdev_top);
2639                 }
2640
2641                 mutex_exit(&vd->vdev_dtl_lock);
2642
2643                 if (txg != 0)
2644                         vdev_dirty(vd->vdev_top, VDD_DTL, vd, txg);
2645                 return;
2646         }
2647
2648         mutex_enter(&vd->vdev_dtl_lock);
2649         for (int t = 0; t < DTL_TYPES; t++) {
2650                 /* account for child's outage in parent's missing map */
2651                 int s = (t == DTL_MISSING) ? DTL_OUTAGE: t;
2652                 if (t == DTL_SCRUB)
2653                         continue;                       /* leaf vdevs only */
2654                 if (t == DTL_PARTIAL)
2655                         minref = 1;                     /* i.e. non-zero */
2656                 else if (vd->vdev_nparity != 0)
2657                         minref = vd->vdev_nparity + 1;  /* RAID-Z */
2658                 else
2659                         minref = vd->vdev_children;     /* any kind of mirror */
2660                 space_reftree_create(&reftree);
2661                 for (int c = 0; c < vd->vdev_children; c++) {
2662                         vdev_t *cvd = vd->vdev_child[c];
2663                         mutex_enter(&cvd->vdev_dtl_lock);
2664                         space_reftree_add_map(&reftree, cvd->vdev_dtl[s], 1);
2665                         mutex_exit(&cvd->vdev_dtl_lock);
2666                 }
2667                 space_reftree_generate_map(&reftree, vd->vdev_dtl[t], minref);
2668                 space_reftree_destroy(&reftree);
2669         }
2670         mutex_exit(&vd->vdev_dtl_lock);
2671 }
2672
2673 int
2674 vdev_dtl_load(vdev_t *vd)
2675 {
2676         spa_t *spa = vd->vdev_spa;
2677         objset_t *mos = spa->spa_meta_objset;
2678         int error = 0;
2679
2680         if (vd->vdev_ops->vdev_op_leaf && vd->vdev_dtl_object != 0) {
2681                 ASSERT(vdev_is_concrete(vd));
2682
2683                 error = space_map_open(&vd->vdev_dtl_sm, mos,
2684                     vd->vdev_dtl_object, 0, -1ULL, 0);
2685                 if (error)
2686                         return (error);
2687                 ASSERT(vd->vdev_dtl_sm != NULL);
2688
2689                 mutex_enter(&vd->vdev_dtl_lock);
2690
2691                 /*
2692                  * Now that we've opened the space_map we need to update
2693                  * the in-core DTL.
2694                  */
2695                 space_map_update(vd->vdev_dtl_sm);
2696
2697                 error = space_map_load(vd->vdev_dtl_sm,
2698                     vd->vdev_dtl[DTL_MISSING], SM_ALLOC);
2699                 mutex_exit(&vd->vdev_dtl_lock);
2700
2701                 return (error);
2702         }
2703
2704         for (int c = 0; c < vd->vdev_children; c++) {
2705                 error = vdev_dtl_load(vd->vdev_child[c]);
2706                 if (error != 0)
2707                         break;
2708         }
2709
2710         return (error);
2711 }
2712
2713 static void
2714 vdev_zap_allocation_data(vdev_t *vd, dmu_tx_t *tx)
2715 {
2716         spa_t *spa = vd->vdev_spa;
2717         objset_t *mos = spa->spa_meta_objset;
2718         vdev_alloc_bias_t alloc_bias = vd->vdev_alloc_bias;
2719         const char *string;
2720
2721         ASSERT(alloc_bias != VDEV_BIAS_NONE);
2722
2723         string =
2724             (alloc_bias == VDEV_BIAS_LOG) ? VDEV_ALLOC_BIAS_LOG :
2725             (alloc_bias == VDEV_BIAS_SPECIAL) ? VDEV_ALLOC_BIAS_SPECIAL :
2726             (alloc_bias == VDEV_BIAS_DEDUP) ? VDEV_ALLOC_BIAS_DEDUP : NULL;
2727
2728         ASSERT(string != NULL);
2729         VERIFY0(zap_add(mos, vd->vdev_top_zap, VDEV_TOP_ZAP_ALLOCATION_BIAS,
2730             1, strlen(string) + 1, string, tx));
2731
2732         if (alloc_bias == VDEV_BIAS_SPECIAL || alloc_bias == VDEV_BIAS_DEDUP) {
2733                 spa_activate_allocation_classes(spa, tx);
2734         }
2735 }
2736
2737 void
2738 vdev_destroy_unlink_zap(vdev_t *vd, uint64_t zapobj, dmu_tx_t *tx)
2739 {
2740         spa_t *spa = vd->vdev_spa;
2741
2742         VERIFY0(zap_destroy(spa->spa_meta_objset, zapobj, tx));
2743         VERIFY0(zap_remove_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
2744             zapobj, tx));
2745 }
2746
2747 uint64_t
2748 vdev_create_link_zap(vdev_t *vd, dmu_tx_t *tx)
2749 {
2750         spa_t *spa = vd->vdev_spa;
2751         uint64_t zap = zap_create(spa->spa_meta_objset, DMU_OTN_ZAP_METADATA,
2752             DMU_OT_NONE, 0, tx);
2753
2754         ASSERT(zap != 0);
2755         VERIFY0(zap_add_int(spa->spa_meta_objset, spa->spa_all_vdev_zaps,
2756             zap, tx));
2757
2758         return (zap);
2759 }
2760
2761 void
2762 vdev_construct_zaps(vdev_t *vd, dmu_tx_t *tx)
2763 {
2764         if (vd->vdev_ops != &vdev_hole_ops &&
2765             vd->vdev_ops != &vdev_missing_ops &&
2766             vd->vdev_ops != &vdev_root_ops &&
2767             !vd->vdev_top->vdev_removing) {
2768                 if (vd->vdev_ops->vdev_op_leaf && vd->vdev_leaf_zap == 0) {
2769                         vd->vdev_leaf_zap = vdev_create_link_zap(vd, tx);
2770                 }
2771                 if (vd == vd->vdev_top && vd->vdev_top_zap == 0) {
2772                         vd->vdev_top_zap = vdev_create_link_zap(vd, tx);
2773                         if (vd->vdev_alloc_bias != VDEV_BIAS_NONE)
2774                                 vdev_zap_allocation_data(vd, tx);
2775                 }
2776         }
2777
2778         for (uint64_t i = 0; i < vd->vdev_children; i++) {
2779                 vdev_construct_zaps(vd->vdev_child[i], tx);
2780         }
2781 }
2782
2783 void
2784 vdev_dtl_sync(vdev_t *vd, uint64_t txg)
2785 {
2786         spa_t *spa = vd->vdev_spa;
2787         range_tree_t *rt = vd->vdev_dtl[DTL_MISSING];
2788         objset_t *mos = spa->spa_meta_objset;
2789         range_tree_t *rtsync;
2790         dmu_tx_t *tx;
2791         uint64_t object = space_map_object(vd->vdev_dtl_sm);
2792
2793         ASSERT(vdev_is_concrete(vd));
2794         ASSERT(vd->vdev_ops->vdev_op_leaf);
2795
2796         tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
2797
2798         if (vd->vdev_detached || vd->vdev_top->vdev_removing) {
2799                 mutex_enter(&vd->vdev_dtl_lock);
2800                 space_map_free(vd->vdev_dtl_sm, tx);
2801                 space_map_close(vd->vdev_dtl_sm);
2802                 vd->vdev_dtl_sm = NULL;
2803                 mutex_exit(&vd->vdev_dtl_lock);
2804
2805                 /*
2806                  * We only destroy the leaf ZAP for detached leaves or for
2807                  * removed log devices. Removed data devices handle leaf ZAP
2808                  * cleanup later, once cancellation is no longer possible.
2809                  */
2810                 if (vd->vdev_leaf_zap != 0 && (vd->vdev_detached ||
2811                     vd->vdev_top->vdev_islog)) {
2812                         vdev_destroy_unlink_zap(vd, vd->vdev_leaf_zap, tx);
2813                         vd->vdev_leaf_zap = 0;
2814                 }
2815
2816                 dmu_tx_commit(tx);
2817                 return;
2818         }
2819
2820         if (vd->vdev_dtl_sm == NULL) {
2821                 uint64_t new_object;
2822
2823                 new_object = space_map_alloc(mos, vdev_dtl_sm_blksz, tx);
2824                 VERIFY3U(new_object, !=, 0);
2825
2826                 VERIFY0(space_map_open(&vd->vdev_dtl_sm, mos, new_object,
2827                     0, -1ULL, 0));
2828                 ASSERT(vd->vdev_dtl_sm != NULL);
2829         }
2830
2831         rtsync = range_tree_create(NULL, NULL);
2832
2833         mutex_enter(&vd->vdev_dtl_lock);
2834         range_tree_walk(rt, range_tree_add, rtsync);
2835         mutex_exit(&vd->vdev_dtl_lock);
2836
2837         space_map_truncate(vd->vdev_dtl_sm, vdev_dtl_sm_blksz, tx);
2838         space_map_write(vd->vdev_dtl_sm, rtsync, SM_ALLOC, SM_NO_VDEVID, tx);
2839         range_tree_vacate(rtsync, NULL, NULL);
2840
2841         range_tree_destroy(rtsync);
2842
2843         /*
2844          * If the object for the space map has changed then dirty
2845          * the top level so that we update the config.
2846          */
2847         if (object != space_map_object(vd->vdev_dtl_sm)) {
2848                 vdev_dbgmsg(vd, "txg %llu, spa %s, DTL old object %llu, "
2849                     "new object %llu", (u_longlong_t)txg, spa_name(spa),
2850                     (u_longlong_t)object,
2851                     (u_longlong_t)space_map_object(vd->vdev_dtl_sm));
2852                 vdev_config_dirty(vd->vdev_top);
2853         }
2854
2855         dmu_tx_commit(tx);
2856
2857         mutex_enter(&vd->vdev_dtl_lock);
2858         space_map_update(vd->vdev_dtl_sm);
2859         mutex_exit(&vd->vdev_dtl_lock);
2860 }
2861
2862 /*
2863  * Determine whether the specified vdev can be offlined/detached/removed
2864  * without losing data.
2865  */
2866 boolean_t
2867 vdev_dtl_required(vdev_t *vd)
2868 {
2869         spa_t *spa = vd->vdev_spa;
2870         vdev_t *tvd = vd->vdev_top;
2871         uint8_t cant_read = vd->vdev_cant_read;
2872         boolean_t required;
2873
2874         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
2875
2876         if (vd == spa->spa_root_vdev || vd == tvd)
2877                 return (B_TRUE);
2878
2879         /*
2880          * Temporarily mark the device as unreadable, and then determine
2881          * whether this results in any DTL outages in the top-level vdev.
2882          * If not, we can safely offline/detach/remove the device.
2883          */
2884         vd->vdev_cant_read = B_TRUE;
2885         vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
2886         required = !vdev_dtl_empty(tvd, DTL_OUTAGE);
2887         vd->vdev_cant_read = cant_read;
2888         vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
2889
2890         if (!required && zio_injection_enabled)
2891                 required = !!zio_handle_device_injection(vd, NULL, ECHILD);
2892
2893         return (required);
2894 }
2895
2896 /*
2897  * Determine if resilver is needed, and if so the txg range.
2898  */
2899 boolean_t
2900 vdev_resilver_needed(vdev_t *vd, uint64_t *minp, uint64_t *maxp)
2901 {
2902         boolean_t needed = B_FALSE;
2903         uint64_t thismin = UINT64_MAX;
2904         uint64_t thismax = 0;
2905
2906         if (vd->vdev_children == 0) {
2907                 mutex_enter(&vd->vdev_dtl_lock);
2908                 if (!range_tree_is_empty(vd->vdev_dtl[DTL_MISSING]) &&
2909                     vdev_writeable(vd)) {
2910
2911                         thismin = vdev_dtl_min(vd);
2912                         thismax = vdev_dtl_max(vd);
2913                         needed = B_TRUE;
2914                 }
2915                 mutex_exit(&vd->vdev_dtl_lock);
2916         } else {
2917                 for (int c = 0; c < vd->vdev_children; c++) {
2918                         vdev_t *cvd = vd->vdev_child[c];
2919                         uint64_t cmin, cmax;
2920
2921                         if (vdev_resilver_needed(cvd, &cmin, &cmax)) {
2922                                 thismin = MIN(thismin, cmin);
2923                                 thismax = MAX(thismax, cmax);
2924                                 needed = B_TRUE;
2925                         }
2926                 }
2927         }
2928
2929         if (needed && minp) {
2930                 *minp = thismin;
2931                 *maxp = thismax;
2932         }
2933         return (needed);
2934 }
2935
2936 /*
2937  * Gets the checkpoint space map object from the vdev's ZAP.  On success sm_obj
2938  * will contain either the checkpoint spacemap object or zero if none exists.
2939  * All other errors are returned to the caller.
2940  */
2941 int
2942 vdev_checkpoint_sm_object(vdev_t *vd, uint64_t *sm_obj)
2943 {
2944         ASSERT0(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER));
2945
2946         if (vd->vdev_top_zap == 0) {
2947                 *sm_obj = 0;
2948                 return (0);
2949         }
2950
2951         int error = zap_lookup(spa_meta_objset(vd->vdev_spa), vd->vdev_top_zap,
2952             VDEV_TOP_ZAP_POOL_CHECKPOINT_SM, sizeof (uint64_t), 1, sm_obj);
2953         if (error == ENOENT) {
2954                 *sm_obj = 0;
2955                 error = 0;
2956         }
2957
2958         return (error);
2959 }
2960
2961 int
2962 vdev_load(vdev_t *vd)
2963 {
2964         int error = 0;
2965
2966         /*
2967          * Recursively load all children.
2968          */
2969         for (int c = 0; c < vd->vdev_children; c++) {
2970                 error = vdev_load(vd->vdev_child[c]);
2971                 if (error != 0) {
2972                         return (error);
2973                 }
2974         }
2975
2976         vdev_set_deflate_ratio(vd);
2977
2978         /*
2979          * On spa_load path, grab the allocation bias from our zap
2980          */
2981         if (vd == vd->vdev_top && vd->vdev_top_zap != 0) {
2982                 spa_t *spa = vd->vdev_spa;
2983                 char bias_str[64];
2984
2985                 if (zap_lookup(spa->spa_meta_objset, vd->vdev_top_zap,
2986                     VDEV_TOP_ZAP_ALLOCATION_BIAS, 1, sizeof (bias_str),
2987                     bias_str) == 0) {
2988                         ASSERT(vd->vdev_alloc_bias == VDEV_BIAS_NONE);
2989                         vd->vdev_alloc_bias = vdev_derive_alloc_bias(bias_str);
2990                 }
2991         }
2992
2993         /*
2994          * If this is a top-level vdev, initialize its metaslabs.
2995          */
2996         if (vd == vd->vdev_top && vdev_is_concrete(vd)) {
2997                 vdev_metaslab_group_create(vd);
2998
2999                 if (vd->vdev_ashift == 0 || vd->vdev_asize == 0) {
3000                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3001                             VDEV_AUX_CORRUPT_DATA);
3002                         vdev_dbgmsg(vd, "vdev_load: invalid size. ashift=%llu, "
3003                             "asize=%llu", (u_longlong_t)vd->vdev_ashift,
3004                             (u_longlong_t)vd->vdev_asize);
3005                         return (SET_ERROR(ENXIO));
3006                 } else if ((error = vdev_metaslab_init(vd, 0)) != 0) {
3007                         vdev_dbgmsg(vd, "vdev_load: metaslab_init failed "
3008                             "[error=%d]", error);
3009                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3010                             VDEV_AUX_CORRUPT_DATA);
3011                         return (error);
3012                 }
3013
3014                 uint64_t checkpoint_sm_obj;
3015                 error = vdev_checkpoint_sm_object(vd, &checkpoint_sm_obj);
3016                 if (error == 0 && checkpoint_sm_obj != 0) {
3017                         objset_t *mos = spa_meta_objset(vd->vdev_spa);
3018                         ASSERT(vd->vdev_asize != 0);
3019                         ASSERT3P(vd->vdev_checkpoint_sm, ==, NULL);
3020
3021                         if ((error = space_map_open(&vd->vdev_checkpoint_sm,
3022                             mos, checkpoint_sm_obj, 0, vd->vdev_asize,
3023                             vd->vdev_ashift))) {
3024                                 vdev_dbgmsg(vd, "vdev_load: space_map_open "
3025                                     "failed for checkpoint spacemap (obj %llu) "
3026                                     "[error=%d]",
3027                                     (u_longlong_t)checkpoint_sm_obj, error);
3028                                 return (error);
3029                         }
3030                         ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
3031                         space_map_update(vd->vdev_checkpoint_sm);
3032
3033                         /*
3034                          * Since the checkpoint_sm contains free entries
3035                          * exclusively we can use sm_alloc to indicate the
3036                          * cumulative checkpointed space that has been freed.
3037                          */
3038                         vd->vdev_stat.vs_checkpoint_space =
3039                             -vd->vdev_checkpoint_sm->sm_alloc;
3040                         vd->vdev_spa->spa_checkpoint_info.sci_dspace +=
3041                             vd->vdev_stat.vs_checkpoint_space;
3042                 } else if (error != 0) {
3043                         vdev_dbgmsg(vd, "vdev_load: failed to retrieve "
3044                             "checkpoint space map object from vdev ZAP "
3045                             "[error=%d]", error);
3046                         return (error);
3047                 }
3048         }
3049
3050         /*
3051          * If this is a leaf vdev, load its DTL.
3052          */
3053         if (vd->vdev_ops->vdev_op_leaf && (error = vdev_dtl_load(vd)) != 0) {
3054                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3055                     VDEV_AUX_CORRUPT_DATA);
3056                 vdev_dbgmsg(vd, "vdev_load: vdev_dtl_load failed "
3057                     "[error=%d]", error);
3058                 return (error);
3059         }
3060
3061         uint64_t obsolete_sm_object;
3062         error = vdev_obsolete_sm_object(vd, &obsolete_sm_object);
3063         if (error == 0 && obsolete_sm_object != 0) {
3064                 objset_t *mos = vd->vdev_spa->spa_meta_objset;
3065                 ASSERT(vd->vdev_asize != 0);
3066                 ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
3067
3068                 if ((error = space_map_open(&vd->vdev_obsolete_sm, mos,
3069                     obsolete_sm_object, 0, vd->vdev_asize, 0))) {
3070                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
3071                             VDEV_AUX_CORRUPT_DATA);
3072                         vdev_dbgmsg(vd, "vdev_load: space_map_open failed for "
3073                             "obsolete spacemap (obj %llu) [error=%d]",
3074                             (u_longlong_t)obsolete_sm_object, error);
3075                         return (error);
3076                 }
3077                 space_map_update(vd->vdev_obsolete_sm);
3078         } else if (error != 0) {
3079                 vdev_dbgmsg(vd, "vdev_load: failed to retrieve obsolete "
3080                     "space map object from vdev ZAP [error=%d]", error);
3081                 return (error);
3082         }
3083
3084         return (0);
3085 }
3086
3087 /*
3088  * The special vdev case is used for hot spares and l2cache devices.  Its
3089  * sole purpose it to set the vdev state for the associated vdev.  To do this,
3090  * we make sure that we can open the underlying device, then try to read the
3091  * label, and make sure that the label is sane and that it hasn't been
3092  * repurposed to another pool.
3093  */
3094 int
3095 vdev_validate_aux(vdev_t *vd)
3096 {
3097         nvlist_t *label;
3098         uint64_t guid, version;
3099         uint64_t state;
3100
3101         if (!vdev_readable(vd))
3102                 return (0);
3103
3104         if ((label = vdev_label_read_config(vd, -1ULL)) == NULL) {
3105                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
3106                     VDEV_AUX_CORRUPT_DATA);
3107                 return (-1);
3108         }
3109
3110         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_VERSION, &version) != 0 ||
3111             !SPA_VERSION_IS_SUPPORTED(version) ||
3112             nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0 ||
3113             guid != vd->vdev_guid ||
3114             nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE, &state) != 0) {
3115                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
3116                     VDEV_AUX_CORRUPT_DATA);
3117                 nvlist_free(label);
3118                 return (-1);
3119         }
3120
3121         /*
3122          * We don't actually check the pool state here.  If it's in fact in
3123          * use by another pool, we update this fact on the fly when requested.
3124          */
3125         nvlist_free(label);
3126         return (0);
3127 }
3128
3129 /*
3130  * Free the objects used to store this vdev's spacemaps, and the array
3131  * that points to them.
3132  */
3133 void
3134 vdev_destroy_spacemaps(vdev_t *vd, dmu_tx_t *tx)
3135 {
3136         if (vd->vdev_ms_array == 0)
3137                 return;
3138
3139         objset_t *mos = vd->vdev_spa->spa_meta_objset;
3140         uint64_t array_count = vd->vdev_asize >> vd->vdev_ms_shift;
3141         size_t array_bytes = array_count * sizeof (uint64_t);
3142         uint64_t *smobj_array = kmem_alloc(array_bytes, KM_SLEEP);
3143         VERIFY0(dmu_read(mos, vd->vdev_ms_array, 0,
3144             array_bytes, smobj_array, 0));
3145
3146         for (uint64_t i = 0; i < array_count; i++) {
3147                 uint64_t smobj = smobj_array[i];
3148                 if (smobj == 0)
3149                         continue;
3150
3151                 space_map_free_obj(mos, smobj, tx);
3152         }
3153
3154         kmem_free(smobj_array, array_bytes);
3155         VERIFY0(dmu_object_free(mos, vd->vdev_ms_array, tx));
3156         vd->vdev_ms_array = 0;
3157 }
3158
3159 static void
3160 vdev_remove_empty_log(vdev_t *vd, uint64_t txg)
3161 {
3162         spa_t *spa = vd->vdev_spa;
3163
3164         ASSERT(vd->vdev_islog);
3165         ASSERT(vd == vd->vdev_top);
3166         ASSERT3U(txg, ==, spa_syncing_txg(spa));
3167
3168         if (vd->vdev_ms != NULL) {
3169                 metaslab_group_t *mg = vd->vdev_mg;
3170
3171                 metaslab_group_histogram_verify(mg);
3172                 metaslab_class_histogram_verify(mg->mg_class);
3173
3174                 for (int m = 0; m < vd->vdev_ms_count; m++) {
3175                         metaslab_t *msp = vd->vdev_ms[m];
3176
3177                         if (msp == NULL || msp->ms_sm == NULL)
3178                                 continue;
3179
3180                         mutex_enter(&msp->ms_lock);
3181                         /*
3182                          * If the metaslab was not loaded when the vdev
3183                          * was removed then the histogram accounting may
3184                          * not be accurate. Update the histogram information
3185                          * here so that we ensure that the metaslab group
3186                          * and metaslab class are up-to-date.
3187                          */
3188                         metaslab_group_histogram_remove(mg, msp);
3189
3190                         VERIFY0(space_map_allocated(msp->ms_sm));
3191                         space_map_close(msp->ms_sm);
3192                         msp->ms_sm = NULL;
3193                         mutex_exit(&msp->ms_lock);
3194                 }
3195
3196                 if (vd->vdev_checkpoint_sm != NULL) {
3197                         ASSERT(spa_has_checkpoint(spa));
3198                         space_map_close(vd->vdev_checkpoint_sm);
3199                         vd->vdev_checkpoint_sm = NULL;
3200                 }
3201
3202                 metaslab_group_histogram_verify(mg);
3203                 metaslab_class_histogram_verify(mg->mg_class);
3204
3205                 for (int i = 0; i < RANGE_TREE_HISTOGRAM_SIZE; i++)
3206                         ASSERT0(mg->mg_histogram[i]);
3207         }
3208
3209         dmu_tx_t *tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
3210
3211         vdev_destroy_spacemaps(vd, tx);
3212         if (vd->vdev_top_zap != 0) {
3213                 vdev_destroy_unlink_zap(vd, vd->vdev_top_zap, tx);
3214                 vd->vdev_top_zap = 0;
3215         }
3216
3217         dmu_tx_commit(tx);
3218 }
3219
3220 void
3221 vdev_sync_done(vdev_t *vd, uint64_t txg)
3222 {
3223         metaslab_t *msp;
3224         boolean_t reassess = !txg_list_empty(&vd->vdev_ms_list, TXG_CLEAN(txg));
3225
3226         ASSERT(vdev_is_concrete(vd));
3227
3228         while ((msp = txg_list_remove(&vd->vdev_ms_list, TXG_CLEAN(txg)))
3229             != NULL)
3230                 metaslab_sync_done(msp, txg);
3231
3232         if (reassess)
3233                 metaslab_sync_reassess(vd->vdev_mg);
3234 }
3235
3236 void
3237 vdev_sync(vdev_t *vd, uint64_t txg)
3238 {
3239         spa_t *spa = vd->vdev_spa;
3240         vdev_t *lvd;
3241         metaslab_t *msp;
3242         dmu_tx_t *tx;
3243
3244         if (range_tree_space(vd->vdev_obsolete_segments) > 0) {
3245                 dmu_tx_t *tx;
3246
3247                 ASSERT(vd->vdev_removing ||
3248                     vd->vdev_ops == &vdev_indirect_ops);
3249
3250                 tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
3251                 vdev_indirect_sync_obsolete(vd, tx);
3252                 dmu_tx_commit(tx);
3253
3254                 /*
3255                  * If the vdev is indirect, it can't have dirty
3256                  * metaslabs or DTLs.
3257                  */
3258                 if (vd->vdev_ops == &vdev_indirect_ops) {
3259                         ASSERT(txg_list_empty(&vd->vdev_ms_list, txg));
3260                         ASSERT(txg_list_empty(&vd->vdev_dtl_list, txg));
3261                         return;
3262                 }
3263         }
3264
3265         ASSERT(vdev_is_concrete(vd));
3266
3267         if (vd->vdev_ms_array == 0 && vd->vdev_ms_shift != 0 &&
3268             !vd->vdev_removing) {
3269                 ASSERT(vd == vd->vdev_top);
3270                 ASSERT0(vd->vdev_indirect_config.vic_mapping_object);
3271                 tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
3272                 vd->vdev_ms_array = dmu_object_alloc(spa->spa_meta_objset,
3273                     DMU_OT_OBJECT_ARRAY, 0, DMU_OT_NONE, 0, tx);
3274                 ASSERT(vd->vdev_ms_array != 0);
3275                 vdev_config_dirty(vd);
3276                 dmu_tx_commit(tx);
3277         }
3278
3279         while ((msp = txg_list_remove(&vd->vdev_ms_list, txg)) != NULL) {
3280                 metaslab_sync(msp, txg);
3281                 (void) txg_list_add(&vd->vdev_ms_list, msp, TXG_CLEAN(txg));
3282         }
3283
3284         while ((lvd = txg_list_remove(&vd->vdev_dtl_list, txg)) != NULL)
3285                 vdev_dtl_sync(lvd, txg);
3286
3287         /*
3288          * If this is an empty log device being removed, destroy the
3289          * metadata associated with it.
3290          */
3291         if (vd->vdev_islog && vd->vdev_stat.vs_alloc == 0 && vd->vdev_removing)
3292                 vdev_remove_empty_log(vd, txg);
3293
3294         (void) txg_list_add(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg));
3295 }
3296
3297 uint64_t
3298 vdev_psize_to_asize(vdev_t *vd, uint64_t psize)
3299 {
3300         return (vd->vdev_ops->vdev_op_asize(vd, psize));
3301 }
3302
3303 /*
3304  * Mark the given vdev faulted.  A faulted vdev behaves as if the device could
3305  * not be opened, and no I/O is attempted.
3306  */
3307 int
3308 vdev_fault(spa_t *spa, uint64_t guid, vdev_aux_t aux)
3309 {
3310         vdev_t *vd, *tvd;
3311
3312         spa_vdev_state_enter(spa, SCL_NONE);
3313
3314         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3315                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
3316
3317         if (!vd->vdev_ops->vdev_op_leaf)
3318                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
3319
3320         tvd = vd->vdev_top;
3321
3322         /*
3323          * If user did a 'zpool offline -f' then make the fault persist across
3324          * reboots.
3325          */
3326         if (aux == VDEV_AUX_EXTERNAL_PERSIST) {
3327                 /*
3328                  * There are two kinds of forced faults: temporary and
3329                  * persistent.  Temporary faults go away at pool import, while
3330                  * persistent faults stay set.  Both types of faults can be
3331                  * cleared with a zpool clear.
3332                  *
3333                  * We tell if a vdev is persistently faulted by looking at the
3334                  * ZPOOL_CONFIG_AUX_STATE nvpair.  If it's set to "external" at
3335                  * import then it's a persistent fault.  Otherwise, it's
3336                  * temporary.  We get ZPOOL_CONFIG_AUX_STATE set to "external"
3337                  * by setting vd.vdev_stat.vs_aux to VDEV_AUX_EXTERNAL.  This
3338                  * tells vdev_config_generate() (which gets run later) to set
3339                  * ZPOOL_CONFIG_AUX_STATE to "external" in the nvlist.
3340                  */
3341                 vd->vdev_stat.vs_aux = VDEV_AUX_EXTERNAL;
3342                 vd->vdev_tmpoffline = B_FALSE;
3343                 aux = VDEV_AUX_EXTERNAL;
3344         } else {
3345                 vd->vdev_tmpoffline = B_TRUE;
3346         }
3347
3348         /*
3349          * We don't directly use the aux state here, but if we do a
3350          * vdev_reopen(), we need this value to be present to remember why we
3351          * were faulted.
3352          */
3353         vd->vdev_label_aux = aux;
3354
3355         /*
3356          * Faulted state takes precedence over degraded.
3357          */
3358         vd->vdev_delayed_close = B_FALSE;
3359         vd->vdev_faulted = 1ULL;
3360         vd->vdev_degraded = 0ULL;
3361         vdev_set_state(vd, B_FALSE, VDEV_STATE_FAULTED, aux);
3362
3363         /*
3364          * If this device has the only valid copy of the data, then
3365          * back off and simply mark the vdev as degraded instead.
3366          */
3367         if (!tvd->vdev_islog && vd->vdev_aux == NULL && vdev_dtl_required(vd)) {
3368                 vd->vdev_degraded = 1ULL;
3369                 vd->vdev_faulted = 0ULL;
3370
3371                 /*
3372                  * If we reopen the device and it's not dead, only then do we
3373                  * mark it degraded.
3374                  */
3375                 vdev_reopen(tvd);
3376
3377                 if (vdev_readable(vd))
3378                         vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED, aux);
3379         }
3380
3381         return (spa_vdev_state_exit(spa, vd, 0));
3382 }
3383
3384 /*
3385  * Mark the given vdev degraded.  A degraded vdev is purely an indication to the
3386  * user that something is wrong.  The vdev continues to operate as normal as far
3387  * as I/O is concerned.
3388  */
3389 int
3390 vdev_degrade(spa_t *spa, uint64_t guid, vdev_aux_t aux)
3391 {
3392         vdev_t *vd;
3393
3394         spa_vdev_state_enter(spa, SCL_NONE);
3395
3396         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3397                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
3398
3399         if (!vd->vdev_ops->vdev_op_leaf)
3400                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
3401
3402         /*
3403          * If the vdev is already faulted, then don't do anything.
3404          */
3405         if (vd->vdev_faulted || vd->vdev_degraded)
3406                 return (spa_vdev_state_exit(spa, NULL, 0));
3407
3408         vd->vdev_degraded = 1ULL;
3409         if (!vdev_is_dead(vd))
3410                 vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED,
3411                     aux);
3412
3413         return (spa_vdev_state_exit(spa, vd, 0));
3414 }
3415
3416 /*
3417  * Online the given vdev.
3418  *
3419  * If 'ZFS_ONLINE_UNSPARE' is set, it implies two things.  First, any attached
3420  * spare device should be detached when the device finishes resilvering.
3421  * Second, the online should be treated like a 'test' online case, so no FMA
3422  * events are generated if the device fails to open.
3423  */
3424 int
3425 vdev_online(spa_t *spa, uint64_t guid, uint64_t flags, vdev_state_t *newstate)
3426 {
3427         vdev_t *vd, *tvd, *pvd, *rvd = spa->spa_root_vdev;
3428         boolean_t wasoffline;
3429         vdev_state_t oldstate;
3430
3431         spa_vdev_state_enter(spa, SCL_NONE);
3432
3433         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3434                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
3435
3436         if (!vd->vdev_ops->vdev_op_leaf)
3437                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
3438
3439         wasoffline = (vd->vdev_offline || vd->vdev_tmpoffline);
3440         oldstate = vd->vdev_state;
3441
3442         tvd = vd->vdev_top;
3443         vd->vdev_offline = B_FALSE;
3444         vd->vdev_tmpoffline = B_FALSE;
3445         vd->vdev_checkremove = !!(flags & ZFS_ONLINE_CHECKREMOVE);
3446         vd->vdev_forcefault = !!(flags & ZFS_ONLINE_FORCEFAULT);
3447
3448         /* XXX - L2ARC 1.0 does not support expansion */
3449         if (!vd->vdev_aux) {
3450                 for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
3451                         pvd->vdev_expanding = !!((flags & ZFS_ONLINE_EXPAND) ||
3452                             spa->spa_autoexpand);
3453                 vd->vdev_expansion_time = gethrestime_sec();
3454         }
3455
3456         vdev_reopen(tvd);
3457         vd->vdev_checkremove = vd->vdev_forcefault = B_FALSE;
3458
3459         if (!vd->vdev_aux) {
3460                 for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
3461                         pvd->vdev_expanding = B_FALSE;
3462         }
3463
3464         if (newstate)
3465                 *newstate = vd->vdev_state;
3466         if ((flags & ZFS_ONLINE_UNSPARE) &&
3467             !vdev_is_dead(vd) && vd->vdev_parent &&
3468             vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
3469             vd->vdev_parent->vdev_child[0] == vd)
3470                 vd->vdev_unspare = B_TRUE;
3471
3472         if ((flags & ZFS_ONLINE_EXPAND) || spa->spa_autoexpand) {
3473
3474                 /* XXX - L2ARC 1.0 does not support expansion */
3475                 if (vd->vdev_aux)
3476                         return (spa_vdev_state_exit(spa, vd, ENOTSUP));
3477                 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3478         }
3479
3480         /* Restart initializing if necessary */
3481         mutex_enter(&vd->vdev_initialize_lock);
3482         if (vdev_writeable(vd) &&
3483             vd->vdev_initialize_thread == NULL &&
3484             vd->vdev_initialize_state == VDEV_INITIALIZE_ACTIVE) {
3485                 (void) vdev_initialize(vd);
3486         }
3487         mutex_exit(&vd->vdev_initialize_lock);
3488
3489         if (wasoffline ||
3490             (oldstate < VDEV_STATE_DEGRADED &&
3491             vd->vdev_state >= VDEV_STATE_DEGRADED))
3492                 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_ONLINE);
3493
3494         return (spa_vdev_state_exit(spa, vd, 0));
3495 }
3496
3497 static int
3498 vdev_offline_locked(spa_t *spa, uint64_t guid, uint64_t flags)
3499 {
3500         vdev_t *vd, *tvd;
3501         int error = 0;
3502         uint64_t generation;
3503         metaslab_group_t *mg;
3504
3505 top:
3506         spa_vdev_state_enter(spa, SCL_ALLOC);
3507
3508         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
3509                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
3510
3511         if (!vd->vdev_ops->vdev_op_leaf)
3512                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
3513
3514         tvd = vd->vdev_top;
3515         mg = tvd->vdev_mg;
3516         generation = spa->spa_config_generation + 1;
3517
3518         /*
3519          * If the device isn't already offline, try to offline it.
3520          */
3521         if (!vd->vdev_offline) {
3522                 /*
3523                  * If this device has the only valid copy of some data,
3524                  * don't allow it to be offlined. Log devices are always
3525                  * expendable.
3526                  */
3527                 if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
3528                     vdev_dtl_required(vd))
3529                         return (spa_vdev_state_exit(spa, NULL, EBUSY));
3530
3531                 /*
3532                  * If the top-level is a slog and it has had allocations
3533                  * then proceed.  We check that the vdev's metaslab group
3534                  * is not NULL since it's possible that we may have just
3535                  * added this vdev but not yet initialized its metaslabs.
3536                  */
3537                 if (tvd->vdev_islog && mg != NULL) {
3538                         /*
3539                          * Prevent any future allocations.
3540                          */
3541                         metaslab_group_passivate(mg);
3542                         (void) spa_vdev_state_exit(spa, vd, 0);
3543
3544                         error = spa_reset_logs(spa);
3545
3546                         /*
3547                          * If the log device was successfully reset but has
3548                          * checkpointed data, do not offline it.
3549                          */
3550                         if (error == 0 &&
3551                             tvd->vdev_checkpoint_sm != NULL) {
3552                                 ASSERT3U(tvd->vdev_checkpoint_sm->sm_alloc,
3553                                     !=, 0);
3554                                 error = ZFS_ERR_CHECKPOINT_EXISTS;
3555                         }
3556
3557                         spa_vdev_state_enter(spa, SCL_ALLOC);
3558
3559                         /*
3560                          * Check to see if the config has changed.
3561                          */
3562                         if (error || generation != spa->spa_config_generation) {
3563                                 metaslab_group_activate(mg);
3564                                 if (error)
3565                                         return (spa_vdev_state_exit(spa,
3566                                             vd, error));
3567                                 (void) spa_vdev_state_exit(spa, vd, 0);
3568                                 goto top;
3569                         }
3570                         ASSERT0(tvd->vdev_stat.vs_alloc);
3571                 }
3572
3573                 /*
3574                  * Offline this device and reopen its top-level vdev.
3575                  * If the top-level vdev is a log device then just offline
3576                  * it. Otherwise, if this action results in the top-level
3577                  * vdev becoming unusable, undo it and fail the request.
3578                  */
3579                 vd->vdev_offline = B_TRUE;
3580                 vdev_reopen(tvd);
3581
3582                 if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
3583                     vdev_is_dead(tvd)) {
3584                         vd->vdev_offline = B_FALSE;
3585                         vdev_reopen(tvd);
3586                         return (spa_vdev_state_exit(spa, NULL, EBUSY));
3587                 }
3588
3589                 /*
3590                  * Add the device back into the metaslab rotor so that
3591                  * once we online the device it's open for business.
3592                  */
3593                 if (tvd->vdev_islog && mg != NULL)
3594                         metaslab_group_activate(mg);
3595         }
3596
3597         vd->vdev_tmpoffline = !!(flags & ZFS_OFFLINE_TEMPORARY);
3598
3599         return (spa_vdev_state_exit(spa, vd, 0));
3600 }
3601
3602 int
3603 vdev_offline(spa_t *spa, uint64_t guid, uint64_t flags)
3604 {
3605         int error;
3606
3607         mutex_enter(&spa->spa_vdev_top_lock);
3608         error = vdev_offline_locked(spa, guid, flags);
3609         mutex_exit(&spa->spa_vdev_top_lock);
3610
3611         return (error);
3612 }
3613
3614 /*
3615  * Clear the error counts associated with this vdev.  Unlike vdev_online() and
3616  * vdev_offline(), we assume the spa config is locked.  We also clear all
3617  * children.  If 'vd' is NULL, then the user wants to clear all vdevs.
3618  */
3619 void
3620 vdev_clear(spa_t *spa, vdev_t *vd)
3621 {
3622         vdev_t *rvd = spa->spa_root_vdev;
3623
3624         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
3625
3626         if (vd == NULL)
3627                 vd = rvd;
3628
3629         vd->vdev_stat.vs_read_errors = 0;
3630         vd->vdev_stat.vs_write_errors = 0;
3631         vd->vdev_stat.vs_checksum_errors = 0;
3632         vd->vdev_stat.vs_slow_ios = 0;
3633
3634         for (int c = 0; c < vd->vdev_children; c++)
3635                 vdev_clear(spa, vd->vdev_child[c]);
3636
3637         /*
3638          * It makes no sense to "clear" an indirect vdev.
3639          */
3640         if (!vdev_is_concrete(vd))
3641                 return;
3642
3643         /*
3644          * If we're in the FAULTED state or have experienced failed I/O, then
3645          * clear the persistent state and attempt to reopen the device.  We
3646          * also mark the vdev config dirty, so that the new faulted state is
3647          * written out to disk.
3648          */
3649         if (vd->vdev_faulted || vd->vdev_degraded ||
3650             !vdev_readable(vd) || !vdev_writeable(vd)) {
3651                 /*
3652                  * When reopening in response to a clear event, it may be due to
3653                  * a fmadm repair request.  In this case, if the device is
3654                  * still broken, we want to still post the ereport again.
3655                  */
3656                 vd->vdev_forcefault = B_TRUE;
3657
3658                 vd->vdev_faulted = vd->vdev_degraded = 0ULL;
3659                 vd->vdev_cant_read = B_FALSE;
3660                 vd->vdev_cant_write = B_FALSE;
3661                 vd->vdev_stat.vs_aux = 0;
3662
3663                 vdev_reopen(vd == rvd ? rvd : vd->vdev_top);
3664
3665                 vd->vdev_forcefault = B_FALSE;
3666
3667                 if (vd != rvd && vdev_writeable(vd->vdev_top))
3668                         vdev_state_dirty(vd->vdev_top);
3669
3670                 if (vd->vdev_aux == NULL && !vdev_is_dead(vd)) {
3671                         if (dsl_scan_resilvering(spa->spa_dsl_pool) &&
3672                             spa_feature_is_enabled(spa,
3673                             SPA_FEATURE_RESILVER_DEFER))
3674                                 vdev_set_deferred_resilver(spa, vd);
3675                         else
3676                                 spa_async_request(spa, SPA_ASYNC_RESILVER);
3677                 }
3678
3679                 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_CLEAR);
3680         }
3681
3682         /*
3683          * When clearing a FMA-diagnosed fault, we always want to
3684          * unspare the device, as we assume that the original spare was
3685          * done in response to the FMA fault.
3686          */
3687         if (!vdev_is_dead(vd) && vd->vdev_parent != NULL &&
3688             vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
3689             vd->vdev_parent->vdev_child[0] == vd)
3690                 vd->vdev_unspare = B_TRUE;
3691 }
3692
3693 boolean_t
3694 vdev_is_dead(vdev_t *vd)
3695 {
3696         /*
3697          * Holes and missing devices are always considered "dead".
3698          * This simplifies the code since we don't have to check for
3699          * these types of devices in the various code paths.
3700          * Instead we rely on the fact that we skip over dead devices
3701          * before issuing I/O to them.
3702          */
3703         return (vd->vdev_state < VDEV_STATE_DEGRADED ||
3704             vd->vdev_ops == &vdev_hole_ops ||
3705             vd->vdev_ops == &vdev_missing_ops);
3706 }
3707
3708 boolean_t
3709 vdev_readable(vdev_t *vd)
3710 {
3711         return (!vdev_is_dead(vd) && !vd->vdev_cant_read);
3712 }
3713
3714 boolean_t
3715 vdev_writeable(vdev_t *vd)
3716 {
3717         return (!vdev_is_dead(vd) && !vd->vdev_cant_write &&
3718             vdev_is_concrete(vd));
3719 }
3720
3721 boolean_t
3722 vdev_allocatable(vdev_t *vd)
3723 {
3724         uint64_t state = vd->vdev_state;
3725
3726         /*
3727          * We currently allow allocations from vdevs which may be in the
3728          * process of reopening (i.e. VDEV_STATE_CLOSED). If the device
3729          * fails to reopen then we'll catch it later when we're holding
3730          * the proper locks.  Note that we have to get the vdev state
3731          * in a local variable because although it changes atomically,
3732          * we're asking two separate questions about it.
3733          */
3734         return (!(state < VDEV_STATE_DEGRADED && state != VDEV_STATE_CLOSED) &&
3735             !vd->vdev_cant_write && vdev_is_concrete(vd) &&
3736             vd->vdev_mg->mg_initialized);
3737 }
3738
3739 boolean_t
3740 vdev_accessible(vdev_t *vd, zio_t *zio)
3741 {
3742         ASSERT(zio->io_vd == vd);
3743
3744         if (vdev_is_dead(vd) || vd->vdev_remove_wanted)
3745                 return (B_FALSE);
3746
3747         if (zio->io_type == ZIO_TYPE_READ)
3748                 return (!vd->vdev_cant_read);
3749
3750         if (zio->io_type == ZIO_TYPE_WRITE)
3751                 return (!vd->vdev_cant_write);
3752
3753         return (B_TRUE);
3754 }
3755
3756 static void
3757 vdev_get_child_stat(vdev_t *cvd, vdev_stat_t *vs, vdev_stat_t *cvs)
3758 {
3759         int t;
3760         for (t = 0; t < ZIO_TYPES; t++) {
3761                 vs->vs_ops[t] += cvs->vs_ops[t];
3762                 vs->vs_bytes[t] += cvs->vs_bytes[t];
3763         }
3764
3765         cvs->vs_scan_removing = cvd->vdev_removing;
3766 }
3767
3768 /*
3769  * Get extended stats
3770  */
3771 static void
3772 vdev_get_child_stat_ex(vdev_t *cvd, vdev_stat_ex_t *vsx, vdev_stat_ex_t *cvsx)
3773 {
3774         int t, b;
3775         for (t = 0; t < ZIO_TYPES; t++) {
3776                 for (b = 0; b < ARRAY_SIZE(vsx->vsx_disk_histo[0]); b++)
3777                         vsx->vsx_disk_histo[t][b] += cvsx->vsx_disk_histo[t][b];
3778
3779                 for (b = 0; b < ARRAY_SIZE(vsx->vsx_total_histo[0]); b++) {
3780                         vsx->vsx_total_histo[t][b] +=
3781                             cvsx->vsx_total_histo[t][b];
3782                 }
3783         }
3784
3785         for (t = 0; t < ZIO_PRIORITY_NUM_QUEUEABLE; t++) {
3786                 for (b = 0; b < ARRAY_SIZE(vsx->vsx_queue_histo[0]); b++) {
3787                         vsx->vsx_queue_histo[t][b] +=
3788                             cvsx->vsx_queue_histo[t][b];
3789                 }
3790                 vsx->vsx_active_queue[t] += cvsx->vsx_active_queue[t];
3791                 vsx->vsx_pend_queue[t] += cvsx->vsx_pend_queue[t];
3792
3793                 for (b = 0; b < ARRAY_SIZE(vsx->vsx_ind_histo[0]); b++)
3794                         vsx->vsx_ind_histo[t][b] += cvsx->vsx_ind_histo[t][b];
3795
3796                 for (b = 0; b < ARRAY_SIZE(vsx->vsx_agg_histo[0]); b++)
3797                         vsx->vsx_agg_histo[t][b] += cvsx->vsx_agg_histo[t][b];
3798         }
3799
3800 }
3801
3802 boolean_t
3803 vdev_is_spacemap_addressable(vdev_t *vd)
3804 {
3805         if (spa_feature_is_active(vd->vdev_spa, SPA_FEATURE_SPACEMAP_V2))
3806                 return (B_TRUE);
3807
3808         /*
3809          * If double-word space map entries are not enabled we assume
3810          * 47 bits of the space map entry are dedicated to the entry's
3811          * offset (see SM_OFFSET_BITS in space_map.h). We then use that
3812          * to calculate the maximum address that can be described by a
3813          * space map entry for the given device.
3814          */
3815         uint64_t shift = vd->vdev_ashift + SM_OFFSET_BITS;
3816
3817         if (shift >= 63) /* detect potential overflow */
3818                 return (B_TRUE);
3819
3820         return (vd->vdev_asize < (1ULL << shift));
3821 }
3822
3823 /*
3824  * Get statistics for the given vdev.
3825  */
3826 static void
3827 vdev_get_stats_ex_impl(vdev_t *vd, vdev_stat_t *vs, vdev_stat_ex_t *vsx)
3828 {
3829         int t;
3830         /*
3831          * If we're getting stats on the root vdev, aggregate the I/O counts
3832          * over all top-level vdevs (i.e. the direct children of the root).
3833          */
3834         if (!vd->vdev_ops->vdev_op_leaf) {
3835                 if (vs) {
3836                         memset(vs->vs_ops, 0, sizeof (vs->vs_ops));
3837                         memset(vs->vs_bytes, 0, sizeof (vs->vs_bytes));
3838                 }
3839                 if (vsx)
3840                         memset(vsx, 0, sizeof (*vsx));
3841
3842                 for (int c = 0; c < vd->vdev_children; c++) {
3843                         vdev_t *cvd = vd->vdev_child[c];
3844                         vdev_stat_t *cvs = &cvd->vdev_stat;
3845                         vdev_stat_ex_t *cvsx = &cvd->vdev_stat_ex;
3846
3847                         vdev_get_stats_ex_impl(cvd, cvs, cvsx);
3848                         if (vs)
3849                                 vdev_get_child_stat(cvd, vs, cvs);
3850                         if (vsx)
3851                                 vdev_get_child_stat_ex(cvd, vsx, cvsx);
3852
3853                 }
3854         } else {
3855                 /*
3856                  * We're a leaf.  Just copy our ZIO active queue stats in.  The
3857                  * other leaf stats are updated in vdev_stat_update().
3858                  */
3859                 if (!vsx)
3860                         return;
3861
3862                 memcpy(vsx, &vd->vdev_stat_ex, sizeof (vd->vdev_stat_ex));
3863
3864                 for (t = 0; t < ARRAY_SIZE(vd->vdev_queue.vq_class); t++) {
3865                         vsx->vsx_active_queue[t] =
3866                             vd->vdev_queue.vq_class[t].vqc_active;
3867                         vsx->vsx_pend_queue[t] = avl_numnodes(
3868                             &vd->vdev_queue.vq_class[t].vqc_queued_tree);
3869                 }
3870         }
3871 }
3872
3873 void
3874 vdev_get_stats_ex(vdev_t *vd, vdev_stat_t *vs, vdev_stat_ex_t *vsx)
3875 {
3876         vdev_t *tvd = vd->vdev_top;
3877         mutex_enter(&vd->vdev_stat_lock);
3878         if (vs) {
3879                 bcopy(&vd->vdev_stat, vs, sizeof (*vs));
3880                 vs->vs_timestamp = gethrtime() - vs->vs_timestamp;
3881                 vs->vs_state = vd->vdev_state;
3882                 vs->vs_rsize = vdev_get_min_asize(vd);
3883                 if (vd->vdev_ops->vdev_op_leaf) {
3884                         vs->vs_rsize += VDEV_LABEL_START_SIZE +
3885                             VDEV_LABEL_END_SIZE;
3886                         /*
3887                          * Report intializing progress. Since we don't
3888                          * have the initializing locks held, this is only
3889                          * an estimate (although a fairly accurate one).
3890                          */
3891                         vs->vs_initialize_bytes_done =
3892                             vd->vdev_initialize_bytes_done;
3893                         vs->vs_initialize_bytes_est =
3894                             vd->vdev_initialize_bytes_est;
3895                         vs->vs_initialize_state = vd->vdev_initialize_state;
3896                         vs->vs_initialize_action_time =
3897                             vd->vdev_initialize_action_time;
3898                 }
3899                 /*
3900                  * Report expandable space on top-level, non-auxillary devices
3901                  * only. The expandable space is reported in terms of metaslab
3902                  * sized units since that determines how much space the pool
3903                  * can expand.
3904                  */
3905                 if (vd->vdev_aux == NULL && tvd != NULL) {
3906                         vs->vs_esize = P2ALIGN(
3907                             vd->vdev_max_asize - vd->vdev_asize,
3908                             1ULL << tvd->vdev_ms_shift);
3909                 }
3910                 if (vd->vdev_aux == NULL && vd == vd->vdev_top &&
3911                     vdev_is_concrete(vd)) {
3912                         vs->vs_fragmentation = (vd->vdev_mg != NULL) ?
3913                             vd->vdev_mg->mg_fragmentation : 0;
3914                 }
3915                 if (vd->vdev_ops->vdev_op_leaf)
3916                         vs->vs_resilver_deferred = vd->vdev_resilver_deferred;
3917         }
3918
3919         ASSERT(spa_config_held(vd->vdev_spa, SCL_ALL, RW_READER) != 0);
3920         vdev_get_stats_ex_impl(vd, vs, vsx);
3921         mutex_exit(&vd->vdev_stat_lock);
3922 }
3923
3924 void
3925 vdev_get_stats(vdev_t *vd, vdev_stat_t *vs)
3926 {
3927         return (vdev_get_stats_ex(vd, vs, NULL));
3928 }
3929
3930 void
3931 vdev_clear_stats(vdev_t *vd)
3932 {
3933         mutex_enter(&vd->vdev_stat_lock);
3934         vd->vdev_stat.vs_space = 0;
3935         vd->vdev_stat.vs_dspace = 0;
3936         vd->vdev_stat.vs_alloc = 0;
3937         mutex_exit(&vd->vdev_stat_lock);
3938 }
3939
3940 void
3941 vdev_scan_stat_init(vdev_t *vd)
3942 {
3943         vdev_stat_t *vs = &vd->vdev_stat;
3944
3945         for (int c = 0; c < vd->vdev_children; c++)
3946                 vdev_scan_stat_init(vd->vdev_child[c]);
3947
3948         mutex_enter(&vd->vdev_stat_lock);
3949         vs->vs_scan_processed = 0;
3950         mutex_exit(&vd->vdev_stat_lock);
3951 }
3952
3953 void
3954 vdev_stat_update(zio_t *zio, uint64_t psize)
3955 {
3956         spa_t *spa = zio->io_spa;
3957         vdev_t *rvd = spa->spa_root_vdev;
3958         vdev_t *vd = zio->io_vd ? zio->io_vd : rvd;
3959         vdev_t *pvd;
3960         uint64_t txg = zio->io_txg;
3961         vdev_stat_t *vs = &vd->vdev_stat;
3962         vdev_stat_ex_t *vsx = &vd->vdev_stat_ex;
3963         zio_type_t type = zio->io_type;
3964         int flags = zio->io_flags;
3965
3966         /*
3967          * If this i/o is a gang leader, it didn't do any actual work.
3968          */
3969         if (zio->io_gang_tree)
3970                 return;
3971
3972         if (zio->io_error == 0) {
3973                 /*
3974                  * If this is a root i/o, don't count it -- we've already
3975                  * counted the top-level vdevs, and vdev_get_stats() will
3976                  * aggregate them when asked.  This reduces contention on
3977                  * the root vdev_stat_lock and implicitly handles blocks
3978                  * that compress away to holes, for which there is no i/o.
3979                  * (Holes never create vdev children, so all the counters
3980                  * remain zero, which is what we want.)
3981                  *
3982                  * Note: this only applies to successful i/o (io_error == 0)
3983                  * because unlike i/o counts, errors are not additive.
3984                  * When reading a ditto block, for example, failure of
3985                  * one top-level vdev does not imply a root-level error.
3986                  */
3987                 if (vd == rvd)
3988                         return;
3989
3990                 ASSERT(vd == zio->io_vd);
3991
3992                 if (flags & ZIO_FLAG_IO_BYPASS)
3993                         return;
3994
3995                 mutex_enter(&vd->vdev_stat_lock);
3996
3997                 if (flags & ZIO_FLAG_IO_REPAIR) {
3998                         if (flags & ZIO_FLAG_SCAN_THREAD) {
3999                                 dsl_scan_phys_t *scn_phys =
4000                                     &spa->spa_dsl_pool->dp_scan->scn_phys;
4001                                 uint64_t *processed = &scn_phys->scn_processed;
4002
4003                                 /* XXX cleanup? */
4004                                 if (vd->vdev_ops->vdev_op_leaf)
4005                                         atomic_add_64(processed, psize);
4006                                 vs->vs_scan_processed += psize;
4007                         }
4008
4009                         if (flags & ZIO_FLAG_SELF_HEAL)
4010                                 vs->vs_self_healed += psize;
4011                 }
4012
4013                 /*
4014                  * The bytes/ops/histograms are recorded at the leaf level and
4015                  * aggregated into the higher level vdevs in vdev_get_stats().
4016                  */
4017                 if (vd->vdev_ops->vdev_op_leaf &&
4018                     (zio->io_priority < ZIO_PRIORITY_NUM_QUEUEABLE)) {
4019
4020                         vs->vs_ops[type]++;
4021                         vs->vs_bytes[type] += psize;
4022
4023                         if (flags & ZIO_FLAG_DELEGATED) {
4024                                 vsx->vsx_agg_histo[zio->io_priority]
4025                                     [RQ_HISTO(zio->io_size)]++;
4026                         } else {
4027                                 vsx->vsx_ind_histo[zio->io_priority]
4028                                     [RQ_HISTO(zio->io_size)]++;
4029                         }
4030
4031                         if (zio->io_delta && zio->io_delay) {
4032                                 vsx->vsx_queue_histo[zio->io_priority]
4033                                     [L_HISTO(zio->io_delta - zio->io_delay)]++;
4034                                 vsx->vsx_disk_histo[type]
4035                                     [L_HISTO(zio->io_delay)]++;
4036                                 vsx->vsx_total_histo[type]
4037                                     [L_HISTO(zio->io_delta)]++;
4038                         }
4039                 }
4040
4041                 mutex_exit(&vd->vdev_stat_lock);
4042                 return;
4043         }
4044
4045         if (flags & ZIO_FLAG_SPECULATIVE)
4046                 return;
4047
4048         /*
4049          * If this is an I/O error that is going to be retried, then ignore the
4050          * error.  Otherwise, the user may interpret B_FAILFAST I/O errors as
4051          * hard errors, when in reality they can happen for any number of
4052          * innocuous reasons (bus resets, MPxIO link failure, etc).
4053          */
4054         if (zio->io_error == EIO &&
4055             !(zio->io_flags & ZIO_FLAG_IO_RETRY))
4056                 return;
4057
4058         /*
4059          * Intent logs writes won't propagate their error to the root
4060          * I/O so don't mark these types of failures as pool-level
4061          * errors.
4062          */
4063         if (zio->io_vd == NULL && (zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
4064                 return;
4065
4066         mutex_enter(&vd->vdev_stat_lock);
4067         if (type == ZIO_TYPE_READ && !vdev_is_dead(vd)) {
4068                 if (zio->io_error == ECKSUM)
4069                         vs->vs_checksum_errors++;
4070                 else
4071                         vs->vs_read_errors++;
4072         }
4073         if (type == ZIO_TYPE_WRITE && !vdev_is_dead(vd))
4074                 vs->vs_write_errors++;
4075         mutex_exit(&vd->vdev_stat_lock);
4076
4077         if (spa->spa_load_state == SPA_LOAD_NONE &&
4078             type == ZIO_TYPE_WRITE && txg != 0 &&
4079             (!(flags & ZIO_FLAG_IO_REPAIR) ||
4080             (flags & ZIO_FLAG_SCAN_THREAD) ||
4081             spa->spa_claiming)) {
4082                 /*
4083                  * This is either a normal write (not a repair), or it's
4084                  * a repair induced by the scrub thread, or it's a repair
4085                  * made by zil_claim() during spa_load() in the first txg.
4086                  * In the normal case, we commit the DTL change in the same
4087                  * txg as the block was born.  In the scrub-induced repair
4088                  * case, we know that scrubs run in first-pass syncing context,
4089                  * so we commit the DTL change in spa_syncing_txg(spa).
4090                  * In the zil_claim() case, we commit in spa_first_txg(spa).
4091                  *
4092                  * We currently do not make DTL entries for failed spontaneous
4093                  * self-healing writes triggered by normal (non-scrubbing)
4094                  * reads, because we have no transactional context in which to
4095                  * do so -- and it's not clear that it'd be desirable anyway.
4096                  */
4097                 if (vd->vdev_ops->vdev_op_leaf) {
4098                         uint64_t commit_txg = txg;
4099                         if (flags & ZIO_FLAG_SCAN_THREAD) {
4100                                 ASSERT(flags & ZIO_FLAG_IO_REPAIR);
4101                                 ASSERT(spa_sync_pass(spa) == 1);
4102                                 vdev_dtl_dirty(vd, DTL_SCRUB, txg, 1);
4103                                 commit_txg = spa_syncing_txg(spa);
4104                         } else if (spa->spa_claiming) {
4105                                 ASSERT(flags & ZIO_FLAG_IO_REPAIR);
4106                                 commit_txg = spa_first_txg(spa);
4107                         }
4108                         ASSERT(commit_txg >= spa_syncing_txg(spa));
4109                         if (vdev_dtl_contains(vd, DTL_MISSING, txg, 1))
4110                                 return;
4111                         for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
4112                                 vdev_dtl_dirty(pvd, DTL_PARTIAL, txg, 1);
4113                         vdev_dirty(vd->vdev_top, VDD_DTL, vd, commit_txg);
4114                 }
4115                 if (vd != rvd)
4116                         vdev_dtl_dirty(vd, DTL_MISSING, txg, 1);
4117         }
4118 }
4119
4120 int64_t
4121 vdev_deflated_space(vdev_t *vd, int64_t space)
4122 {
4123         ASSERT((space & (SPA_MINBLOCKSIZE-1)) == 0);
4124         ASSERT(vd->vdev_deflate_ratio != 0 || vd->vdev_isl2cache);
4125
4126         return ((space >> SPA_MINBLOCKSHIFT) * vd->vdev_deflate_ratio);
4127 }
4128
4129 /*
4130  * Update the in-core space usage stats for this vdev and the root vdev.
4131  */
4132 void
4133 vdev_space_update(vdev_t *vd, int64_t alloc_delta, int64_t defer_delta,
4134     int64_t space_delta)
4135 {
4136         int64_t dspace_delta;
4137         spa_t *spa = vd->vdev_spa;
4138         vdev_t *rvd = spa->spa_root_vdev;
4139
4140         ASSERT(vd == vd->vdev_top);
4141
4142         /*
4143          * Apply the inverse of the psize-to-asize (ie. RAID-Z) space-expansion
4144          * factor.  We must calculate this here and not at the root vdev
4145          * because the root vdev's psize-to-asize is simply the max of its
4146          * childrens', thus not accurate enough for us.
4147          */
4148         dspace_delta = vdev_deflated_space(vd, space_delta);
4149
4150         mutex_enter(&vd->vdev_stat_lock);
4151         vd->vdev_stat.vs_alloc += alloc_delta;
4152         vd->vdev_stat.vs_space += space_delta;
4153         vd->vdev_stat.vs_dspace += dspace_delta;
4154         mutex_exit(&vd->vdev_stat_lock);
4155
4156         /* every class but log contributes to root space stats */
4157         if (vd->vdev_mg != NULL && !vd->vdev_islog) {
4158                 mutex_enter(&rvd->vdev_stat_lock);
4159                 rvd->vdev_stat.vs_alloc += alloc_delta;
4160                 rvd->vdev_stat.vs_space += space_delta;
4161                 rvd->vdev_stat.vs_dspace += dspace_delta;
4162                 mutex_exit(&rvd->vdev_stat_lock);
4163         }
4164         /* Note: metaslab_class_space_update moved to metaslab_space_update */
4165 }
4166
4167 /*
4168  * Mark a top-level vdev's config as dirty, placing it on the dirty list
4169  * so that it will be written out next time the vdev configuration is synced.
4170  * If the root vdev is specified (vdev_top == NULL), dirty all top-level vdevs.
4171  */
4172 void
4173 vdev_config_dirty(vdev_t *vd)
4174 {
4175         spa_t *spa = vd->vdev_spa;
4176         vdev_t *rvd = spa->spa_root_vdev;
4177         int c;
4178
4179         ASSERT(spa_writeable(spa));
4180
4181         /*
4182          * If this is an aux vdev (as with l2cache and spare devices), then we
4183          * update the vdev config manually and set the sync flag.
4184          */
4185         if (vd->vdev_aux != NULL) {
4186                 spa_aux_vdev_t *sav = vd->vdev_aux;
4187                 nvlist_t **aux;
4188                 uint_t naux;
4189
4190                 for (c = 0; c < sav->sav_count; c++) {
4191                         if (sav->sav_vdevs[c] == vd)
4192                                 break;
4193                 }
4194
4195                 if (c == sav->sav_count) {
4196                         /*
4197                          * We're being removed.  There's nothing more to do.
4198                          */
4199                         ASSERT(sav->sav_sync == B_TRUE);
4200                         return;
4201                 }
4202
4203                 sav->sav_sync = B_TRUE;
4204
4205                 if (nvlist_lookup_nvlist_array(sav->sav_config,
4206                     ZPOOL_CONFIG_L2CACHE, &aux, &naux) != 0) {
4207                         VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
4208                             ZPOOL_CONFIG_SPARES, &aux, &naux) == 0);
4209                 }
4210
4211                 ASSERT(c < naux);
4212
4213                 /*
4214                  * Setting the nvlist in the middle if the array is a little
4215                  * sketchy, but it will work.
4216                  */
4217                 nvlist_free(aux[c]);
4218                 aux[c] = vdev_config_generate(spa, vd, B_TRUE, 0);
4219
4220                 return;
4221         }
4222
4223         /*
4224          * The dirty list is protected by the SCL_CONFIG lock.  The caller
4225          * must either hold SCL_CONFIG as writer, or must be the sync thread
4226          * (which holds SCL_CONFIG as reader).  There's only one sync thread,
4227          * so this is sufficient to ensure mutual exclusion.
4228          */
4229         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
4230             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
4231             spa_config_held(spa, SCL_CONFIG, RW_READER)));
4232
4233         if (vd == rvd) {
4234                 for (c = 0; c < rvd->vdev_children; c++)
4235                         vdev_config_dirty(rvd->vdev_child[c]);
4236         } else {
4237                 ASSERT(vd == vd->vdev_top);
4238
4239                 if (!list_link_active(&vd->vdev_config_dirty_node) &&
4240                     vdev_is_concrete(vd)) {
4241                         list_insert_head(&spa->spa_config_dirty_list, vd);
4242                 }
4243         }
4244 }
4245
4246 void
4247 vdev_config_clean(vdev_t *vd)
4248 {
4249         spa_t *spa = vd->vdev_spa;
4250
4251         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
4252             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
4253             spa_config_held(spa, SCL_CONFIG, RW_READER)));
4254
4255         ASSERT(list_link_active(&vd->vdev_config_dirty_node));
4256         list_remove(&spa->spa_config_dirty_list, vd);
4257 }
4258
4259 /*
4260  * Mark a top-level vdev's state as dirty, so that the next pass of
4261  * spa_sync() can convert this into vdev_config_dirty().  We distinguish
4262  * the state changes from larger config changes because they require
4263  * much less locking, and are often needed for administrative actions.
4264  */
4265 void
4266 vdev_state_dirty(vdev_t *vd)
4267 {
4268         spa_t *spa = vd->vdev_spa;
4269
4270         ASSERT(spa_writeable(spa));
4271         ASSERT(vd == vd->vdev_top);
4272
4273         /*
4274          * The state list is protected by the SCL_STATE lock.  The caller
4275          * must either hold SCL_STATE as writer, or must be the sync thread
4276          * (which holds SCL_STATE as reader).  There's only one sync thread,
4277          * so this is sufficient to ensure mutual exclusion.
4278          */
4279         ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
4280             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
4281             spa_config_held(spa, SCL_STATE, RW_READER)));
4282
4283         if (!list_link_active(&vd->vdev_state_dirty_node) &&
4284             vdev_is_concrete(vd))
4285                 list_insert_head(&spa->spa_state_dirty_list, vd);
4286 }
4287
4288 void
4289 vdev_state_clean(vdev_t *vd)
4290 {
4291         spa_t *spa = vd->vdev_spa;
4292
4293         ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
4294             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
4295             spa_config_held(spa, SCL_STATE, RW_READER)));
4296
4297         ASSERT(list_link_active(&vd->vdev_state_dirty_node));
4298         list_remove(&spa->spa_state_dirty_list, vd);
4299 }
4300
4301 /*
4302  * Propagate vdev state up from children to parent.
4303  */
4304 void
4305 vdev_propagate_state(vdev_t *vd)
4306 {
4307         spa_t *spa = vd->vdev_spa;
4308         vdev_t *rvd = spa->spa_root_vdev;
4309         int degraded = 0, faulted = 0;
4310         int corrupted = 0;
4311         vdev_t *child;
4312
4313         if (vd->vdev_children > 0) {
4314                 for (int c = 0; c < vd->vdev_children; c++) {
4315                         child = vd->vdev_child[c];
4316
4317                         /*
4318                          * Don't factor holes or indirect vdevs into the
4319                          * decision.
4320                          */
4321                         if (!vdev_is_concrete(child))
4322                                 continue;
4323
4324                         if (!vdev_readable(child) ||
4325                             (!vdev_writeable(child) && spa_writeable(spa))) {
4326                                 /*
4327                                  * Root special: if there is a top-level log
4328                                  * device, treat the root vdev as if it were
4329                                  * degraded.
4330                                  */
4331                                 if (child->vdev_islog && vd == rvd)
4332                                         degraded++;
4333                                 else
4334                                         faulted++;
4335                         } else if (child->vdev_state <= VDEV_STATE_DEGRADED) {
4336                                 degraded++;
4337                         }
4338
4339                         if (child->vdev_stat.vs_aux == VDEV_AUX_CORRUPT_DATA)
4340                                 corrupted++;
4341                 }
4342
4343                 vd->vdev_ops->vdev_op_state_change(vd, faulted, degraded);
4344
4345                 /*
4346                  * Root special: if there is a top-level vdev that cannot be
4347                  * opened due to corrupted metadata, then propagate the root
4348                  * vdev's aux state as 'corrupt' rather than 'insufficient
4349                  * replicas'.
4350                  */
4351                 if (corrupted && vd == rvd &&
4352                     rvd->vdev_state == VDEV_STATE_CANT_OPEN)
4353                         vdev_set_state(rvd, B_FALSE, VDEV_STATE_CANT_OPEN,
4354                             VDEV_AUX_CORRUPT_DATA);
4355         }
4356
4357         if (vd->vdev_parent)
4358                 vdev_propagate_state(vd->vdev_parent);
4359 }
4360
4361 /*
4362  * Set a vdev's state.  If this is during an open, we don't update the parent
4363  * state, because we're in the process of opening children depth-first.
4364  * Otherwise, we propagate the change to the parent.
4365  *
4366  * If this routine places a device in a faulted state, an appropriate ereport is
4367  * generated.
4368  */
4369 void
4370 vdev_set_state(vdev_t *vd, boolean_t isopen, vdev_state_t state, vdev_aux_t aux)
4371 {
4372         uint64_t save_state;
4373         spa_t *spa = vd->vdev_spa;
4374
4375         if (state == vd->vdev_state) {
4376                 /*
4377                  * Since vdev_offline() code path is already in an offline
4378                  * state we can miss a statechange event to OFFLINE. Check
4379                  * the previous state to catch this condition.
4380                  */
4381                 if (vd->vdev_ops->vdev_op_leaf &&
4382                     (state == VDEV_STATE_OFFLINE) &&
4383                     (vd->vdev_prevstate >= VDEV_STATE_FAULTED)) {
4384                         /* post an offline state change */
4385                         zfs_post_state_change(spa, vd, vd->vdev_prevstate);
4386                 }
4387                 vd->vdev_stat.vs_aux = aux;
4388                 return;
4389         }
4390
4391         save_state = vd->vdev_state;
4392
4393         vd->vdev_state = state;
4394         vd->vdev_stat.vs_aux = aux;
4395
4396         /*
4397          * If we are setting the vdev state to anything but an open state, then
4398          * always close the underlying device unless the device has requested
4399          * a delayed close (i.e. we're about to remove or fault the device).
4400          * Otherwise, we keep accessible but invalid devices open forever.
4401          * We don't call vdev_close() itself, because that implies some extra
4402          * checks (offline, etc) that we don't want here.  This is limited to
4403          * leaf devices, because otherwise closing the device will affect other
4404          * children.
4405          */
4406         if (!vd->vdev_delayed_close && vdev_is_dead(vd) &&
4407             vd->vdev_ops->vdev_op_leaf)
4408                 vd->vdev_ops->vdev_op_close(vd);
4409
4410         if (vd->vdev_removed &&
4411             state == VDEV_STATE_CANT_OPEN &&
4412             (aux == VDEV_AUX_OPEN_FAILED || vd->vdev_checkremove)) {
4413                 /*
4414                  * If the previous state is set to VDEV_STATE_REMOVED, then this
4415                  * device was previously marked removed and someone attempted to
4416                  * reopen it.  If this failed due to a nonexistent device, then
4417                  * keep the device in the REMOVED state.  We also let this be if
4418                  * it is one of our special test online cases, which is only
4419                  * attempting to online the device and shouldn't generate an FMA
4420                  * fault.
4421                  */
4422                 vd->vdev_state = VDEV_STATE_REMOVED;
4423                 vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
4424         } else if (state == VDEV_STATE_REMOVED) {
4425                 vd->vdev_removed = B_TRUE;
4426         } else if (state == VDEV_STATE_CANT_OPEN) {
4427                 /*
4428                  * If we fail to open a vdev during an import or recovery, we
4429                  * mark it as "not available", which signifies that it was
4430                  * never there to begin with.  Failure to open such a device
4431                  * is not considered an error.
4432                  */
4433                 if ((spa_load_state(spa) == SPA_LOAD_IMPORT ||
4434                     spa_load_state(spa) == SPA_LOAD_RECOVER) &&
4435                     vd->vdev_ops->vdev_op_leaf)
4436                         vd->vdev_not_present = 1;
4437
4438                 /*
4439                  * Post the appropriate ereport.  If the 'prevstate' field is
4440                  * set to something other than VDEV_STATE_UNKNOWN, it indicates
4441                  * that this is part of a vdev_reopen().  In this case, we don't
4442                  * want to post the ereport if the device was already in the
4443                  * CANT_OPEN state beforehand.
4444                  *
4445                  * If the 'checkremove' flag is set, then this is an attempt to
4446                  * online the device in response to an insertion event.  If we
4447                  * hit this case, then we have detected an insertion event for a
4448                  * faulted or offline device that wasn't in the removed state.
4449                  * In this scenario, we don't post an ereport because we are
4450                  * about to replace the device, or attempt an online with
4451                  * vdev_forcefault, which will generate the fault for us.
4452                  */
4453                 if ((vd->vdev_prevstate != state || vd->vdev_forcefault) &&
4454                     !vd->vdev_not_present && !vd->vdev_checkremove &&
4455                     vd != spa->spa_root_vdev) {
4456                         const char *class;
4457
4458                         switch (aux) {
4459                         case VDEV_AUX_OPEN_FAILED:
4460                                 class = FM_EREPORT_ZFS_DEVICE_OPEN_FAILED;
4461                                 break;
4462                         case VDEV_AUX_CORRUPT_DATA:
4463                                 class = FM_EREPORT_ZFS_DEVICE_CORRUPT_DATA;
4464                                 break;
4465                         case VDEV_AUX_NO_REPLICAS:
4466                                 class = FM_EREPORT_ZFS_DEVICE_NO_REPLICAS;
4467                                 break;
4468                         case VDEV_AUX_BAD_GUID_SUM:
4469                                 class = FM_EREPORT_ZFS_DEVICE_BAD_GUID_SUM;
4470                                 break;
4471                         case VDEV_AUX_TOO_SMALL:
4472                                 class = FM_EREPORT_ZFS_DEVICE_TOO_SMALL;
4473                                 break;
4474                         case VDEV_AUX_BAD_LABEL:
4475                                 class = FM_EREPORT_ZFS_DEVICE_BAD_LABEL;
4476                                 break;
4477                         case VDEV_AUX_BAD_ASHIFT:
4478                                 class = FM_EREPORT_ZFS_DEVICE_BAD_ASHIFT;
4479                                 break;
4480                         default:
4481                                 class = FM_EREPORT_ZFS_DEVICE_UNKNOWN;
4482                         }
4483
4484                         zfs_ereport_post(class, spa, vd, NULL, NULL,
4485                             save_state, 0);
4486                 }
4487
4488                 /* Erase any notion of persistent removed state */
4489                 vd->vdev_removed = B_FALSE;
4490         } else {
4491                 vd->vdev_removed = B_FALSE;
4492         }
4493
4494         /*
4495          * Notify ZED of any significant state-change on a leaf vdev.
4496          *
4497          */
4498         if (vd->vdev_ops->vdev_op_leaf) {
4499                 /* preserve original state from a vdev_reopen() */
4500                 if ((vd->vdev_prevstate != VDEV_STATE_UNKNOWN) &&
4501                     (vd->vdev_prevstate != vd->vdev_state) &&
4502                     (save_state <= VDEV_STATE_CLOSED))
4503                         save_state = vd->vdev_prevstate;
4504
4505                 /* filter out state change due to initial vdev_open */
4506                 if (save_state > VDEV_STATE_CLOSED)
4507                         zfs_post_state_change(spa, vd, save_state);
4508         }
4509
4510         if (!isopen && vd->vdev_parent)
4511                 vdev_propagate_state(vd->vdev_parent);
4512 }
4513
4514 boolean_t
4515 vdev_children_are_offline(vdev_t *vd)
4516 {
4517         ASSERT(!vd->vdev_ops->vdev_op_leaf);
4518
4519         for (uint64_t i = 0; i < vd->vdev_children; i++) {
4520                 if (vd->vdev_child[i]->vdev_state != VDEV_STATE_OFFLINE)
4521                         return (B_FALSE);
4522         }
4523
4524         return (B_TRUE);
4525 }
4526
4527 /*
4528  * Check the vdev configuration to ensure that it's capable of supporting
4529  * a root pool. We do not support partial configuration.
4530  */
4531 boolean_t
4532 vdev_is_bootable(vdev_t *vd)
4533 {
4534         if (!vd->vdev_ops->vdev_op_leaf) {
4535                 const char *vdev_type = vd->vdev_ops->vdev_op_type;
4536
4537                 if (strcmp(vdev_type, VDEV_TYPE_MISSING) == 0 ||
4538                     strcmp(vdev_type, VDEV_TYPE_INDIRECT) == 0) {
4539                         return (B_FALSE);
4540                 }
4541         }
4542
4543         for (int c = 0; c < vd->vdev_children; c++) {
4544                 if (!vdev_is_bootable(vd->vdev_child[c]))
4545                         return (B_FALSE);
4546         }
4547         return (B_TRUE);
4548 }
4549
4550 boolean_t
4551 vdev_is_concrete(vdev_t *vd)
4552 {
4553         vdev_ops_t *ops = vd->vdev_ops;
4554         if (ops == &vdev_indirect_ops || ops == &vdev_hole_ops ||
4555             ops == &vdev_missing_ops || ops == &vdev_root_ops) {
4556                 return (B_FALSE);
4557         } else {
4558                 return (B_TRUE);
4559         }
4560 }
4561
4562 /*
4563  * Determine if a log device has valid content.  If the vdev was
4564  * removed or faulted in the MOS config then we know that
4565  * the content on the log device has already been written to the pool.
4566  */
4567 boolean_t
4568 vdev_log_state_valid(vdev_t *vd)
4569 {
4570         if (vd->vdev_ops->vdev_op_leaf && !vd->vdev_faulted &&
4571             !vd->vdev_removed)
4572                 return (B_TRUE);
4573
4574         for (int c = 0; c < vd->vdev_children; c++)
4575                 if (vdev_log_state_valid(vd->vdev_child[c]))
4576                         return (B_TRUE);
4577
4578         return (B_FALSE);
4579 }
4580
4581 /*
4582  * Expand a vdev if possible.
4583  */
4584 void
4585 vdev_expand(vdev_t *vd, uint64_t txg)
4586 {
4587         ASSERT(vd->vdev_top == vd);
4588         ASSERT(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
4589         ASSERT(vdev_is_concrete(vd));
4590
4591         vdev_set_deflate_ratio(vd);
4592
4593         if ((vd->vdev_asize >> vd->vdev_ms_shift) > vd->vdev_ms_count &&
4594             vdev_is_concrete(vd)) {
4595                 vdev_metaslab_group_create(vd);
4596                 VERIFY(vdev_metaslab_init(vd, txg) == 0);
4597                 vdev_config_dirty(vd);
4598         }
4599 }
4600
4601 /*
4602  * Split a vdev.
4603  */
4604 void
4605 vdev_split(vdev_t *vd)
4606 {
4607         vdev_t *cvd, *pvd = vd->vdev_parent;
4608
4609         vdev_remove_child(pvd, vd);
4610         vdev_compact_children(pvd);
4611
4612         cvd = pvd->vdev_child[0];
4613         if (pvd->vdev_children == 1) {
4614                 vdev_remove_parent(cvd);
4615                 cvd->vdev_splitting = B_TRUE;
4616         }
4617         vdev_propagate_state(cvd);
4618 }
4619
4620 void
4621 vdev_deadman(vdev_t *vd, char *tag)
4622 {
4623         for (int c = 0; c < vd->vdev_children; c++) {
4624                 vdev_t *cvd = vd->vdev_child[c];
4625
4626                 vdev_deadman(cvd, tag);
4627         }
4628
4629         if (vd->vdev_ops->vdev_op_leaf) {
4630                 vdev_queue_t *vq = &vd->vdev_queue;
4631
4632                 mutex_enter(&vq->vq_lock);
4633                 if (avl_numnodes(&vq->vq_active_tree) > 0) {
4634                         spa_t *spa = vd->vdev_spa;
4635                         zio_t *fio;
4636                         uint64_t delta;
4637
4638                         zfs_dbgmsg("slow vdev: %s has %d active IOs",
4639                             vd->vdev_path, avl_numnodes(&vq->vq_active_tree));
4640
4641                         /*
4642                          * Look at the head of all the pending queues,
4643                          * if any I/O has been outstanding for longer than
4644                          * the spa_deadman_synctime invoke the deadman logic.
4645                          */
4646                         fio = avl_first(&vq->vq_active_tree);
4647                         delta = gethrtime() - fio->io_timestamp;
4648                         if (delta > spa_deadman_synctime(spa))
4649                                 zio_deadman(fio, tag);
4650                 }
4651                 mutex_exit(&vq->vq_lock);
4652         }
4653 }
4654
4655 void
4656 vdev_set_deferred_resilver(spa_t *spa, vdev_t *vd)
4657 {
4658         for (uint64_t i = 0; i < vd->vdev_children; i++)
4659                 vdev_set_deferred_resilver(spa, vd->vdev_child[i]);
4660
4661         if (!vd->vdev_ops->vdev_op_leaf || !vdev_writeable(vd) ||
4662             range_tree_is_empty(vd->vdev_dtl[DTL_MISSING])) {
4663                 return;
4664         }
4665
4666         vd->vdev_resilver_deferred = B_TRUE;
4667         spa->spa_resilver_deferred = B_TRUE;
4668 }
4669
4670 #if defined(_KERNEL)
4671 EXPORT_SYMBOL(vdev_fault);
4672 EXPORT_SYMBOL(vdev_degrade);
4673 EXPORT_SYMBOL(vdev_online);
4674 EXPORT_SYMBOL(vdev_offline);
4675 EXPORT_SYMBOL(vdev_clear);
4676 /* BEGIN CSTYLED */
4677 module_param(vdev_max_ms_count, int, 0644);
4678 MODULE_PARM_DESC(vdev_max_ms_count,
4679         "Target number of metaslabs per top-level vdev");
4680
4681 module_param(vdev_min_ms_count, int, 0644);
4682 MODULE_PARM_DESC(vdev_min_ms_count,
4683         "Minimum number of metaslabs per top-level vdev");
4684
4685 module_param(vdev_ms_count_limit, int, 0644);
4686 MODULE_PARM_DESC(vdev_ms_count_limit,
4687         "Practical upper limit of total metaslabs per top-level vdev");
4688
4689 module_param(zfs_slow_io_events_per_second, uint, 0644);
4690 MODULE_PARM_DESC(zfs_slow_io_events_per_second,
4691         "Rate limit slow IO (delay) events to this many per second");
4692
4693 module_param(zfs_checksum_events_per_second, uint, 0644);
4694 MODULE_PARM_DESC(zfs_checksum_events_per_second, "Rate limit checksum events "
4695         "to this many checksum errors per second (do not set below zed"
4696         "threshold).");
4697
4698 module_param(zfs_scan_ignore_errors, int, 0644);
4699 MODULE_PARM_DESC(zfs_scan_ignore_errors,
4700         "Ignore errors during resilver/scrub");
4701
4702 module_param(vdev_validate_skip, int, 0644);
4703 MODULE_PARM_DESC(vdev_validate_skip,
4704         "Bypass vdev_validate()");
4705
4706 module_param(zfs_nocacheflush, int, 0644);
4707 MODULE_PARM_DESC(zfs_nocacheflush, "Disable cache flushes");
4708 /* END CSTYLED */
4709 #endif