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