initial commit
[freebsd-arm:freebsd-arm.git] / 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 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26
27 #include <sys/zfs_context.h>
28 #include <sys/fm/fs/zfs.h>
29 #include <sys/spa.h>
30 #include <sys/spa_impl.h>
31 #include <sys/dmu.h>
32 #include <sys/dmu_tx.h>
33 #include <sys/vdev_impl.h>
34 #include <sys/uberblock_impl.h>
35 #include <sys/metaslab.h>
36 #include <sys/metaslab_impl.h>
37 #include <sys/space_map.h>
38 #include <sys/zio.h>
39 #include <sys/zap.h>
40 #include <sys/fs/zfs.h>
41 #include <sys/arc.h>
42
43 SYSCTL_DECL(_vfs_zfs);
44 SYSCTL_NODE(_vfs_zfs, OID_AUTO, vdev, CTLFLAG_RW, 0, "ZFS VDEV");
45
46 /*
47  * Virtual device management.
48  */
49
50 static vdev_ops_t *vdev_ops_table[] = {
51         &vdev_root_ops,
52         &vdev_raidz_ops,
53         &vdev_mirror_ops,
54         &vdev_replacing_ops,
55         &vdev_spare_ops,
56 #ifdef _KERNEL
57         &vdev_geom_ops,
58 #else
59         &vdev_disk_ops,
60 #endif
61         &vdev_file_ops,
62         &vdev_missing_ops,
63         NULL
64 };
65
66 /* maximum scrub/resilver I/O queue per leaf vdev */
67 int zfs_scrub_limit = 10;
68
69 TUNABLE_INT("vfs.zfs.scrub_limit", &zfs_scrub_limit);
70 SYSCTL_INT(_vfs_zfs, OID_AUTO, scrub_limit, CTLFLAG_RDTUN, &zfs_scrub_limit, 0,
71     "Maximum scrub/resilver I/O queue");
72
73 /*
74  * Given a vdev type, return the appropriate ops vector.
75  */
76 static vdev_ops_t *
77 vdev_getops(const char *type)
78 {
79         vdev_ops_t *ops, **opspp;
80
81         for (opspp = vdev_ops_table; (ops = *opspp) != NULL; opspp++)
82                 if (strcmp(ops->vdev_op_type, type) == 0)
83                         break;
84
85         return (ops);
86 }
87
88 /*
89  * Default asize function: return the MAX of psize with the asize of
90  * all children.  This is what's used by anything other than RAID-Z.
91  */
92 uint64_t
93 vdev_default_asize(vdev_t *vd, uint64_t psize)
94 {
95         uint64_t asize = P2ROUNDUP(psize, 1ULL << vd->vdev_top->vdev_ashift);
96         uint64_t csize;
97         uint64_t c;
98
99         for (c = 0; c < vd->vdev_children; c++) {
100                 csize = vdev_psize_to_asize(vd->vdev_child[c], psize);
101                 asize = MAX(asize, csize);
102         }
103
104         return (asize);
105 }
106
107 /*
108  * Get the replaceable or attachable device size.
109  * If the parent is a mirror or raidz, the replaceable size is the minimum
110  * psize of all its children. For the rest, just return our own psize.
111  *
112  * e.g.
113  *                      psize   rsize
114  * root                 -       -
115  *      mirror/raidz    -       -
116  *          disk1       20g     20g
117  *          disk2       40g     20g
118  *      disk3           80g     80g
119  */
120 uint64_t
121 vdev_get_rsize(vdev_t *vd)
122 {
123         vdev_t *pvd, *cvd;
124         uint64_t c, rsize;
125
126         pvd = vd->vdev_parent;
127
128         /*
129          * If our parent is NULL or the root, just return our own psize.
130          */
131         if (pvd == NULL || pvd->vdev_parent == NULL)
132                 return (vd->vdev_psize);
133
134         rsize = 0;
135
136         for (c = 0; c < pvd->vdev_children; c++) {
137                 cvd = pvd->vdev_child[c];
138                 rsize = MIN(rsize - 1, cvd->vdev_psize - 1) + 1;
139         }
140
141         return (rsize);
142 }
143
144 vdev_t *
145 vdev_lookup_top(spa_t *spa, uint64_t vdev)
146 {
147         vdev_t *rvd = spa->spa_root_vdev;
148
149         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
150
151         if (vdev < rvd->vdev_children) {
152                 ASSERT(rvd->vdev_child[vdev] != NULL);
153                 return (rvd->vdev_child[vdev]);
154         }
155
156         return (NULL);
157 }
158
159 vdev_t *
160 vdev_lookup_by_guid(vdev_t *vd, uint64_t guid)
161 {
162         int c;
163         vdev_t *mvd;
164
165         if (vd->vdev_guid == guid)
166                 return (vd);
167
168         for (c = 0; c < vd->vdev_children; c++)
169                 if ((mvd = vdev_lookup_by_guid(vd->vdev_child[c], guid)) !=
170                     NULL)
171                         return (mvd);
172
173         return (NULL);
174 }
175
176 void
177 vdev_add_child(vdev_t *pvd, vdev_t *cvd)
178 {
179         size_t oldsize, newsize;
180         uint64_t id = cvd->vdev_id;
181         vdev_t **newchild;
182
183         ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
184         ASSERT(cvd->vdev_parent == NULL);
185
186         cvd->vdev_parent = pvd;
187
188         if (pvd == NULL)
189                 return;
190
191         ASSERT(id >= pvd->vdev_children || pvd->vdev_child[id] == NULL);
192
193         oldsize = pvd->vdev_children * sizeof (vdev_t *);
194         pvd->vdev_children = MAX(pvd->vdev_children, id + 1);
195         newsize = pvd->vdev_children * sizeof (vdev_t *);
196
197         newchild = kmem_zalloc(newsize, KM_SLEEP);
198         if (pvd->vdev_child != NULL) {
199                 bcopy(pvd->vdev_child, newchild, oldsize);
200                 kmem_free(pvd->vdev_child, oldsize);
201         }
202
203         pvd->vdev_child = newchild;
204         pvd->vdev_child[id] = cvd;
205
206         cvd->vdev_top = (pvd->vdev_top ? pvd->vdev_top: cvd);
207         ASSERT(cvd->vdev_top->vdev_parent->vdev_parent == NULL);
208
209         /*
210          * Walk up all ancestors to update guid sum.
211          */
212         for (; pvd != NULL; pvd = pvd->vdev_parent)
213                 pvd->vdev_guid_sum += cvd->vdev_guid_sum;
214
215         if (cvd->vdev_ops->vdev_op_leaf)
216                 cvd->vdev_spa->spa_scrub_maxinflight += zfs_scrub_limit;
217 }
218
219 void
220 vdev_remove_child(vdev_t *pvd, vdev_t *cvd)
221 {
222         int c;
223         uint_t id = cvd->vdev_id;
224
225         ASSERT(cvd->vdev_parent == pvd);
226
227         if (pvd == NULL)
228                 return;
229
230         ASSERT(id < pvd->vdev_children);
231         ASSERT(pvd->vdev_child[id] == cvd);
232
233         pvd->vdev_child[id] = NULL;
234         cvd->vdev_parent = NULL;
235
236         for (c = 0; c < pvd->vdev_children; c++)
237                 if (pvd->vdev_child[c])
238                         break;
239
240         if (c == pvd->vdev_children) {
241                 kmem_free(pvd->vdev_child, c * sizeof (vdev_t *));
242                 pvd->vdev_child = NULL;
243                 pvd->vdev_children = 0;
244         }
245
246         /*
247          * Walk up all ancestors to update guid sum.
248          */
249         for (; pvd != NULL; pvd = pvd->vdev_parent)
250                 pvd->vdev_guid_sum -= cvd->vdev_guid_sum;
251
252         if (cvd->vdev_ops->vdev_op_leaf)
253                 cvd->vdev_spa->spa_scrub_maxinflight -= zfs_scrub_limit;
254 }
255
256 /*
257  * Remove any holes in the child array.
258  */
259 void
260 vdev_compact_children(vdev_t *pvd)
261 {
262         vdev_t **newchild, *cvd;
263         int oldc = pvd->vdev_children;
264         int newc, c;
265
266         ASSERT(spa_config_held(pvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
267
268         for (c = newc = 0; c < oldc; c++)
269                 if (pvd->vdev_child[c])
270                         newc++;
271
272         newchild = kmem_alloc(newc * sizeof (vdev_t *), KM_SLEEP);
273
274         for (c = newc = 0; c < oldc; c++) {
275                 if ((cvd = pvd->vdev_child[c]) != NULL) {
276                         newchild[newc] = cvd;
277                         cvd->vdev_id = newc++;
278                 }
279         }
280
281         kmem_free(pvd->vdev_child, oldc * sizeof (vdev_t *));
282         pvd->vdev_child = newchild;
283         pvd->vdev_children = newc;
284 }
285
286 /*
287  * Allocate and minimally initialize a vdev_t.
288  */
289 static vdev_t *
290 vdev_alloc_common(spa_t *spa, uint_t id, uint64_t guid, vdev_ops_t *ops)
291 {
292         vdev_t *vd;
293
294         vd = kmem_zalloc(sizeof (vdev_t), KM_SLEEP);
295
296         if (spa->spa_root_vdev == NULL) {
297                 ASSERT(ops == &vdev_root_ops);
298                 spa->spa_root_vdev = vd;
299         }
300
301         if (guid == 0) {
302                 if (spa->spa_root_vdev == vd) {
303                         /*
304                          * The root vdev's guid will also be the pool guid,
305                          * which must be unique among all pools.
306                          */
307                         while (guid == 0 || spa_guid_exists(guid, 0))
308                                 guid = spa_get_random(-1ULL);
309                 } else {
310                         /*
311                          * Any other vdev's guid must be unique within the pool.
312                          */
313                         while (guid == 0 ||
314                             spa_guid_exists(spa_guid(spa), guid))
315                                 guid = spa_get_random(-1ULL);
316                 }
317                 ASSERT(!spa_guid_exists(spa_guid(spa), guid));
318         }
319
320         vd->vdev_spa = spa;
321         vd->vdev_id = id;
322         vd->vdev_guid = guid;
323         vd->vdev_guid_sum = guid;
324         vd->vdev_ops = ops;
325         vd->vdev_state = VDEV_STATE_CLOSED;
326
327         mutex_init(&vd->vdev_dtl_lock, NULL, MUTEX_DEFAULT, NULL);
328         mutex_init(&vd->vdev_stat_lock, NULL, MUTEX_DEFAULT, NULL);
329         mutex_init(&vd->vdev_probe_lock, NULL, MUTEX_DEFAULT, NULL);
330         space_map_create(&vd->vdev_dtl_map, 0, -1ULL, 0, &vd->vdev_dtl_lock);
331         space_map_create(&vd->vdev_dtl_scrub, 0, -1ULL, 0, &vd->vdev_dtl_lock);
332         txg_list_create(&vd->vdev_ms_list,
333             offsetof(struct metaslab, ms_txg_node));
334         txg_list_create(&vd->vdev_dtl_list,
335             offsetof(struct vdev, vdev_dtl_node));
336         vd->vdev_stat.vs_timestamp = gethrtime();
337         vdev_queue_init(vd);
338         vdev_cache_init(vd);
339
340         return (vd);
341 }
342
343 /*
344  * Allocate a new vdev.  The 'alloctype' is used to control whether we are
345  * creating a new vdev or loading an existing one - the behavior is slightly
346  * different for each case.
347  */
348 int
349 vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
350     int alloctype)
351 {
352         vdev_ops_t *ops;
353         char *type;
354         uint64_t guid = 0, islog, nparity;
355         vdev_t *vd;
356
357         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
358
359         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
360                 return (EINVAL);
361
362         if ((ops = vdev_getops(type)) == NULL)
363                 return (EINVAL);
364
365         /*
366          * If this is a load, get the vdev guid from the nvlist.
367          * Otherwise, vdev_alloc_common() will generate one for us.
368          */
369         if (alloctype == VDEV_ALLOC_LOAD) {
370                 uint64_t label_id;
371
372                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID, &label_id) ||
373                     label_id != id)
374                         return (EINVAL);
375
376                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
377                         return (EINVAL);
378         } else if (alloctype == VDEV_ALLOC_SPARE) {
379                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
380                         return (EINVAL);
381         } else if (alloctype == VDEV_ALLOC_L2CACHE) {
382                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
383                         return (EINVAL);
384         }
385
386         /*
387          * The first allocated vdev must be of type 'root'.
388          */
389         if (ops != &vdev_root_ops && spa->spa_root_vdev == NULL)
390                 return (EINVAL);
391
392         /*
393          * Determine whether we're a log vdev.
394          */
395         islog = 0;
396         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG, &islog);
397         if (islog && spa_version(spa) < SPA_VERSION_SLOGS)
398                 return (ENOTSUP);
399
400         /*
401          * Set the nparity property for RAID-Z vdevs.
402          */
403         nparity = -1ULL;
404         if (ops == &vdev_raidz_ops) {
405                 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
406                     &nparity) == 0) {
407                         /*
408                          * Currently, we can only support 2 parity devices.
409                          */
410                         if (nparity == 0 || nparity > 2)
411                                 return (EINVAL);
412                         /*
413                          * Older versions can only support 1 parity device.
414                          */
415                         if (nparity == 2 &&
416                             spa_version(spa) < SPA_VERSION_RAID6)
417                                 return (ENOTSUP);
418                 } else {
419                         /*
420                          * We require the parity to be specified for SPAs that
421                          * support multiple parity levels.
422                          */
423                         if (spa_version(spa) >= SPA_VERSION_RAID6)
424                                 return (EINVAL);
425                         /*
426                          * Otherwise, we default to 1 parity device for RAID-Z.
427                          */
428                         nparity = 1;
429                 }
430         } else {
431                 nparity = 0;
432         }
433         ASSERT(nparity != -1ULL);
434
435         vd = vdev_alloc_common(spa, id, guid, ops);
436
437         vd->vdev_islog = islog;
438         vd->vdev_nparity = nparity;
439
440         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &vd->vdev_path) == 0)
441                 vd->vdev_path = spa_strdup(vd->vdev_path);
442         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &vd->vdev_devid) == 0)
443                 vd->vdev_devid = spa_strdup(vd->vdev_devid);
444         if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PHYS_PATH,
445             &vd->vdev_physpath) == 0)
446                 vd->vdev_physpath = spa_strdup(vd->vdev_physpath);
447
448         /*
449          * Set the whole_disk property.  If it's not specified, leave the value
450          * as -1.
451          */
452         if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
453             &vd->vdev_wholedisk) != 0)
454                 vd->vdev_wholedisk = -1ULL;
455
456         /*
457          * Look for the 'not present' flag.  This will only be set if the device
458          * was not present at the time of import.
459          */
460         if (!spa->spa_import_faulted)
461                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
462                     &vd->vdev_not_present);
463
464         /*
465          * Get the alignment requirement.
466          */
467         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASHIFT, &vd->vdev_ashift);
468
469         /*
470          * If we're a top-level vdev, try to load the allocation parameters.
471          */
472         if (parent && !parent->vdev_parent && alloctype == VDEV_ALLOC_LOAD) {
473                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
474                     &vd->vdev_ms_array);
475                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
476                     &vd->vdev_ms_shift);
477                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASIZE,
478                     &vd->vdev_asize);
479         }
480
481         /*
482          * If we're a leaf vdev, try to load the DTL object and other state.
483          */
484         if (vd->vdev_ops->vdev_op_leaf &&
485             (alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_L2CACHE)) {
486                 if (alloctype == VDEV_ALLOC_LOAD) {
487                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DTL,
488                             &vd->vdev_dtl.smo_object);
489                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_UNSPARE,
490                             &vd->vdev_unspare);
491                 }
492                 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE,
493                     &vd->vdev_offline);
494
495                 /*
496                  * When importing a pool, we want to ignore the persistent fault
497                  * state, as the diagnosis made on another system may not be
498                  * valid in the current context.
499                  */
500                 if (spa->spa_load_state == SPA_LOAD_OPEN) {
501                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED,
502                             &vd->vdev_faulted);
503                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DEGRADED,
504                             &vd->vdev_degraded);
505                         (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED,
506                             &vd->vdev_removed);
507                 }
508         }
509
510         /*
511          * Add ourselves to the parent's list of children.
512          */
513         vdev_add_child(parent, vd);
514
515         *vdp = vd;
516
517         return (0);
518 }
519
520 void
521 vdev_free(vdev_t *vd)
522 {
523         int c;
524         spa_t *spa = vd->vdev_spa;
525
526         /*
527          * vdev_free() implies closing the vdev first.  This is simpler than
528          * trying to ensure complicated semantics for all callers.
529          */
530         vdev_close(vd);
531
532         ASSERT(!list_link_active(&vd->vdev_config_dirty_node));
533
534         /*
535          * Free all children.
536          */
537         for (c = 0; c < vd->vdev_children; c++)
538                 vdev_free(vd->vdev_child[c]);
539
540         ASSERT(vd->vdev_child == NULL);
541         ASSERT(vd->vdev_guid_sum == vd->vdev_guid);
542
543         /*
544          * Discard allocation state.
545          */
546         if (vd == vd->vdev_top)
547                 vdev_metaslab_fini(vd);
548
549         ASSERT3U(vd->vdev_stat.vs_space, ==, 0);
550         ASSERT3U(vd->vdev_stat.vs_dspace, ==, 0);
551         ASSERT3U(vd->vdev_stat.vs_alloc, ==, 0);
552
553         /*
554          * Remove this vdev from its parent's child list.
555          */
556         vdev_remove_child(vd->vdev_parent, vd);
557
558         ASSERT(vd->vdev_parent == NULL);
559
560         /*
561          * Clean up vdev structure.
562          */
563         vdev_queue_fini(vd);
564         vdev_cache_fini(vd);
565
566         if (vd->vdev_path)
567                 spa_strfree(vd->vdev_path);
568         if (vd->vdev_devid)
569                 spa_strfree(vd->vdev_devid);
570         if (vd->vdev_physpath)
571                 spa_strfree(vd->vdev_physpath);
572
573         if (vd->vdev_isspare)
574                 spa_spare_remove(vd);
575         if (vd->vdev_isl2cache)
576                 spa_l2cache_remove(vd);
577
578         txg_list_destroy(&vd->vdev_ms_list);
579         txg_list_destroy(&vd->vdev_dtl_list);
580         mutex_enter(&vd->vdev_dtl_lock);
581         space_map_unload(&vd->vdev_dtl_map);
582         space_map_destroy(&vd->vdev_dtl_map);
583         space_map_vacate(&vd->vdev_dtl_scrub, NULL, NULL);
584         space_map_destroy(&vd->vdev_dtl_scrub);
585         mutex_exit(&vd->vdev_dtl_lock);
586         mutex_destroy(&vd->vdev_dtl_lock);
587         mutex_destroy(&vd->vdev_stat_lock);
588         mutex_destroy(&vd->vdev_probe_lock);
589
590         if (vd == spa->spa_root_vdev)
591                 spa->spa_root_vdev = NULL;
592
593         kmem_free(vd, sizeof (vdev_t));
594 }
595
596 /*
597  * Transfer top-level vdev state from svd to tvd.
598  */
599 static void
600 vdev_top_transfer(vdev_t *svd, vdev_t *tvd)
601 {
602         spa_t *spa = svd->vdev_spa;
603         metaslab_t *msp;
604         vdev_t *vd;
605         int t;
606
607         ASSERT(tvd == tvd->vdev_top);
608
609         tvd->vdev_ms_array = svd->vdev_ms_array;
610         tvd->vdev_ms_shift = svd->vdev_ms_shift;
611         tvd->vdev_ms_count = svd->vdev_ms_count;
612
613         svd->vdev_ms_array = 0;
614         svd->vdev_ms_shift = 0;
615         svd->vdev_ms_count = 0;
616
617         tvd->vdev_mg = svd->vdev_mg;
618         tvd->vdev_ms = svd->vdev_ms;
619
620         svd->vdev_mg = NULL;
621         svd->vdev_ms = NULL;
622
623         if (tvd->vdev_mg != NULL)
624                 tvd->vdev_mg->mg_vd = tvd;
625
626         tvd->vdev_stat.vs_alloc = svd->vdev_stat.vs_alloc;
627         tvd->vdev_stat.vs_space = svd->vdev_stat.vs_space;
628         tvd->vdev_stat.vs_dspace = svd->vdev_stat.vs_dspace;
629
630         svd->vdev_stat.vs_alloc = 0;
631         svd->vdev_stat.vs_space = 0;
632         svd->vdev_stat.vs_dspace = 0;
633
634         for (t = 0; t < TXG_SIZE; t++) {
635                 while ((msp = txg_list_remove(&svd->vdev_ms_list, t)) != NULL)
636                         (void) txg_list_add(&tvd->vdev_ms_list, msp, t);
637                 while ((vd = txg_list_remove(&svd->vdev_dtl_list, t)) != NULL)
638                         (void) txg_list_add(&tvd->vdev_dtl_list, vd, t);
639                 if (txg_list_remove_this(&spa->spa_vdev_txg_list, svd, t))
640                         (void) txg_list_add(&spa->spa_vdev_txg_list, tvd, t);
641         }
642
643         if (list_link_active(&svd->vdev_config_dirty_node)) {
644                 vdev_config_clean(svd);
645                 vdev_config_dirty(tvd);
646         }
647
648         if (list_link_active(&svd->vdev_state_dirty_node)) {
649                 vdev_state_clean(svd);
650                 vdev_state_dirty(tvd);
651         }
652
653         tvd->vdev_deflate_ratio = svd->vdev_deflate_ratio;
654         svd->vdev_deflate_ratio = 0;
655
656         tvd->vdev_islog = svd->vdev_islog;
657         svd->vdev_islog = 0;
658 }
659
660 static void
661 vdev_top_update(vdev_t *tvd, vdev_t *vd)
662 {
663         int c;
664
665         if (vd == NULL)
666                 return;
667
668         vd->vdev_top = tvd;
669
670         for (c = 0; c < vd->vdev_children; c++)
671                 vdev_top_update(tvd, vd->vdev_child[c]);
672 }
673
674 /*
675  * Add a mirror/replacing vdev above an existing vdev.
676  */
677 vdev_t *
678 vdev_add_parent(vdev_t *cvd, vdev_ops_t *ops)
679 {
680         spa_t *spa = cvd->vdev_spa;
681         vdev_t *pvd = cvd->vdev_parent;
682         vdev_t *mvd;
683
684         ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
685
686         mvd = vdev_alloc_common(spa, cvd->vdev_id, 0, ops);
687
688         mvd->vdev_asize = cvd->vdev_asize;
689         mvd->vdev_ashift = cvd->vdev_ashift;
690         mvd->vdev_state = cvd->vdev_state;
691
692         vdev_remove_child(pvd, cvd);
693         vdev_add_child(pvd, mvd);
694         cvd->vdev_id = mvd->vdev_children;
695         vdev_add_child(mvd, cvd);
696         vdev_top_update(cvd->vdev_top, cvd->vdev_top);
697
698         if (mvd == mvd->vdev_top)
699                 vdev_top_transfer(cvd, mvd);
700
701         return (mvd);
702 }
703
704 /*
705  * Remove a 1-way mirror/replacing vdev from the tree.
706  */
707 void
708 vdev_remove_parent(vdev_t *cvd)
709 {
710         vdev_t *mvd = cvd->vdev_parent;
711         vdev_t *pvd = mvd->vdev_parent;
712
713         ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
714
715         ASSERT(mvd->vdev_children == 1);
716         ASSERT(mvd->vdev_ops == &vdev_mirror_ops ||
717             mvd->vdev_ops == &vdev_replacing_ops ||
718             mvd->vdev_ops == &vdev_spare_ops);
719         cvd->vdev_ashift = mvd->vdev_ashift;
720
721         vdev_remove_child(mvd, cvd);
722         vdev_remove_child(pvd, mvd);
723         /*
724          * If cvd will replace mvd as a top-level vdev, preserve mvd's guid.
725          * Otherwise, we could have detached an offline device, and when we
726          * go to import the pool we'll think we have two top-level vdevs,
727          * instead of a different version of the same top-level vdev.
728          */
729         if (mvd->vdev_top == mvd)
730                 cvd->vdev_guid = cvd->vdev_guid_sum = mvd->vdev_guid;
731         cvd->vdev_id = mvd->vdev_id;
732         vdev_add_child(pvd, cvd);
733         vdev_top_update(cvd->vdev_top, cvd->vdev_top);
734
735         if (cvd == cvd->vdev_top)
736                 vdev_top_transfer(mvd, cvd);
737
738         ASSERT(mvd->vdev_children == 0);
739         vdev_free(mvd);
740 }
741
742 int
743 vdev_metaslab_init(vdev_t *vd, uint64_t txg)
744 {
745         spa_t *spa = vd->vdev_spa;
746         objset_t *mos = spa->spa_meta_objset;
747         metaslab_class_t *mc;
748         uint64_t m;
749         uint64_t oldc = vd->vdev_ms_count;
750         uint64_t newc = vd->vdev_asize >> vd->vdev_ms_shift;
751         metaslab_t **mspp;
752         int error;
753
754         if (vd->vdev_ms_shift == 0)     /* not being allocated from yet */
755                 return (0);
756
757         ASSERT(oldc <= newc);
758
759         if (vd->vdev_islog)
760                 mc = spa->spa_log_class;
761         else
762                 mc = spa->spa_normal_class;
763
764         if (vd->vdev_mg == NULL)
765                 vd->vdev_mg = metaslab_group_create(mc, vd);
766
767         mspp = kmem_zalloc(newc * sizeof (*mspp), KM_SLEEP);
768
769         if (oldc != 0) {
770                 bcopy(vd->vdev_ms, mspp, oldc * sizeof (*mspp));
771                 kmem_free(vd->vdev_ms, oldc * sizeof (*mspp));
772         }
773
774         vd->vdev_ms = mspp;
775         vd->vdev_ms_count = newc;
776
777         for (m = oldc; m < newc; m++) {
778                 space_map_obj_t smo = { 0, 0, 0 };
779                 if (txg == 0) {
780                         uint64_t object = 0;
781                         error = dmu_read(mos, vd->vdev_ms_array,
782                             m * sizeof (uint64_t), sizeof (uint64_t), &object);
783                         if (error)
784                                 return (error);
785                         if (object != 0) {
786                                 dmu_buf_t *db;
787                                 error = dmu_bonus_hold(mos, object, FTAG, &db);
788                                 if (error)
789                                         return (error);
790                                 ASSERT3U(db->db_size, >=, sizeof (smo));
791                                 bcopy(db->db_data, &smo, sizeof (smo));
792                                 ASSERT3U(smo.smo_object, ==, object);
793                                 dmu_buf_rele(db, FTAG);
794                         }
795                 }
796                 vd->vdev_ms[m] = metaslab_init(vd->vdev_mg, &smo,
797                     m << vd->vdev_ms_shift, 1ULL << vd->vdev_ms_shift, txg);
798         }
799
800         return (0);
801 }
802
803 void
804 vdev_metaslab_fini(vdev_t *vd)
805 {
806         uint64_t m;
807         uint64_t count = vd->vdev_ms_count;
808
809         if (vd->vdev_ms != NULL) {
810                 for (m = 0; m < count; m++)
811                         if (vd->vdev_ms[m] != NULL)
812                                 metaslab_fini(vd->vdev_ms[m]);
813                 kmem_free(vd->vdev_ms, count * sizeof (metaslab_t *));
814                 vd->vdev_ms = NULL;
815         }
816 }
817
818 typedef struct vdev_probe_stats {
819         boolean_t       vps_readable;
820         boolean_t       vps_writeable;
821         int             vps_flags;
822         zio_t           *vps_root;
823         vdev_t          *vps_vd;
824 } vdev_probe_stats_t;
825
826 static void
827 vdev_probe_done(zio_t *zio)
828 {
829         vdev_probe_stats_t *vps = zio->io_private;
830         vdev_t *vd = vps->vps_vd;
831
832         if (zio->io_type == ZIO_TYPE_READ) {
833                 ASSERT(zio->io_vd == vd);
834                 if (zio->io_error == 0)
835                         vps->vps_readable = 1;
836                 if (zio->io_error == 0 && (spa_mode & FWRITE)) {
837                         zio_nowait(zio_write_phys(vps->vps_root, vd,
838                             zio->io_offset, zio->io_size, zio->io_data,
839                             ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
840                             ZIO_PRIORITY_SYNC_WRITE, vps->vps_flags, B_TRUE));
841                 } else {
842                         zio_buf_free(zio->io_data, zio->io_size);
843                 }
844         } else if (zio->io_type == ZIO_TYPE_WRITE) {
845                 ASSERT(zio->io_vd == vd);
846                 if (zio->io_error == 0)
847                         vps->vps_writeable = 1;
848                 zio_buf_free(zio->io_data, zio->io_size);
849         } else if (zio->io_type == ZIO_TYPE_NULL) {
850                 ASSERT(zio->io_vd == NULL);
851                 ASSERT(zio == vps->vps_root);
852
853                 vd->vdev_cant_read |= !vps->vps_readable;
854                 vd->vdev_cant_write |= !vps->vps_writeable;
855
856                 if (vdev_readable(vd) &&
857                     (vdev_writeable(vd) || !(spa_mode & FWRITE))) {
858                         zio->io_error = 0;
859                 } else {
860                         ASSERT(zio->io_error != 0);
861                         zfs_ereport_post(FM_EREPORT_ZFS_PROBE_FAILURE,
862                             zio->io_spa, vd, NULL, 0, 0);
863                         zio->io_error = ENXIO;
864                 }
865                 kmem_free(vps, sizeof (*vps));
866         }
867 }
868
869 /*
870  * Determine whether this device is accessible by reading and writing
871  * to several known locations: the pad regions of each vdev label
872  * but the first (which we leave alone in case it contains a VTOC).
873  */
874 zio_t *
875 vdev_probe(vdev_t *vd, zio_t *pio)
876 {
877         spa_t *spa = vd->vdev_spa;
878         vdev_probe_stats_t *vps;
879         zio_t *zio;
880
881         vps = kmem_zalloc(sizeof (*vps), KM_SLEEP);
882
883         vps->vps_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_PROBE |
884             ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE | ZIO_FLAG_DONT_RETRY;
885
886         if (spa_config_held(spa, SCL_ZIO, RW_WRITER)) {
887                 /*
888                  * vdev_cant_read and vdev_cant_write can only transition
889                  * from TRUE to FALSE when we have the SCL_ZIO lock as writer;
890                  * otherwise they can only transition from FALSE to TRUE.
891                  * This ensures that any zio looking at these values can
892                  * assume that failures persist for the life of the I/O.
893                  * That's important because when a device has intermittent
894                  * connectivity problems, we want to ensure that they're
895                  * ascribed to the device (ENXIO) and not the zio (EIO).
896                  *
897                  * Since we hold SCL_ZIO as writer here, clear both values
898                  * so the probe can reevaluate from first principles.
899                  */
900                 vps->vps_flags |= ZIO_FLAG_CONFIG_WRITER;
901                 vd->vdev_cant_read = B_FALSE;
902                 vd->vdev_cant_write = B_FALSE;
903         }
904
905         ASSERT(vd->vdev_ops->vdev_op_leaf);
906
907         zio = zio_null(pio, spa, vdev_probe_done, vps, vps->vps_flags);
908
909         vps->vps_root = zio;
910         vps->vps_vd = vd;
911
912         for (int l = 1; l < VDEV_LABELS; l++) {
913                 zio_nowait(zio_read_phys(zio, vd,
914                     vdev_label_offset(vd->vdev_psize, l,
915                     offsetof(vdev_label_t, vl_pad)),
916                     VDEV_SKIP_SIZE, zio_buf_alloc(VDEV_SKIP_SIZE),
917                     ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
918                     ZIO_PRIORITY_SYNC_READ, vps->vps_flags, B_TRUE));
919         }
920
921         return (zio);
922 }
923
924 /*
925  * Prepare a virtual device for access.
926  */
927 int
928 vdev_open(vdev_t *vd)
929 {
930         int error;
931         int c;
932         uint64_t osize = 0;
933         uint64_t asize, psize;
934         uint64_t ashift = 0;
935
936         ASSERT(vd->vdev_state == VDEV_STATE_CLOSED ||
937             vd->vdev_state == VDEV_STATE_CANT_OPEN ||
938             vd->vdev_state == VDEV_STATE_OFFLINE);
939
940         vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
941
942         if (!vd->vdev_removed && vd->vdev_faulted) {
943                 ASSERT(vd->vdev_children == 0);
944                 vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
945                     VDEV_AUX_ERR_EXCEEDED);
946                 return (ENXIO);
947         } else if (vd->vdev_offline) {
948                 ASSERT(vd->vdev_children == 0);
949                 vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE, VDEV_AUX_NONE);
950                 return (ENXIO);
951         }
952
953         error = vd->vdev_ops->vdev_op_open(vd, &osize, &ashift);
954
955         if (zio_injection_enabled && error == 0)
956                 error = zio_handle_device_injection(vd, ENXIO);
957
958         if (error) {
959                 if (vd->vdev_removed &&
960                     vd->vdev_stat.vs_aux != VDEV_AUX_OPEN_FAILED)
961                         vd->vdev_removed = B_FALSE;
962
963                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
964                     vd->vdev_stat.vs_aux);
965                 return (error);
966         }
967
968         vd->vdev_removed = B_FALSE;
969
970         if (vd->vdev_degraded) {
971                 ASSERT(vd->vdev_children == 0);
972                 vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
973                     VDEV_AUX_ERR_EXCEEDED);
974         } else {
975                 vd->vdev_state = VDEV_STATE_HEALTHY;
976         }
977
978         for (c = 0; c < vd->vdev_children; c++)
979                 if (vd->vdev_child[c]->vdev_state != VDEV_STATE_HEALTHY) {
980                         vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
981                             VDEV_AUX_NONE);
982                         break;
983                 }
984
985         osize = P2ALIGN(osize, (uint64_t)sizeof (vdev_label_t));
986
987         if (vd->vdev_children == 0) {
988                 if (osize < SPA_MINDEVSIZE) {
989                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
990                             VDEV_AUX_TOO_SMALL);
991                         return (EOVERFLOW);
992                 }
993                 psize = osize;
994                 asize = osize - (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE);
995         } else {
996                 if (vd->vdev_parent != NULL && osize < SPA_MINDEVSIZE -
997                     (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE)) {
998                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
999                             VDEV_AUX_TOO_SMALL);
1000                         return (EOVERFLOW);
1001                 }
1002                 psize = 0;
1003                 asize = osize;
1004         }
1005
1006         vd->vdev_psize = psize;
1007
1008         if (vd->vdev_asize == 0) {
1009                 /*
1010                  * This is the first-ever open, so use the computed values.
1011                  * For testing purposes, a higher ashift can be requested.
1012                  */
1013                 vd->vdev_asize = asize;
1014                 vd->vdev_ashift = MAX(ashift, vd->vdev_ashift);
1015         } else {
1016                 /*
1017                  * Make sure the alignment requirement hasn't increased.
1018                  */
1019                 if (ashift > vd->vdev_top->vdev_ashift) {
1020                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1021                             VDEV_AUX_BAD_LABEL);
1022                         return (EINVAL);
1023                 }
1024
1025                 /*
1026                  * Make sure the device hasn't shrunk.
1027                  */
1028                 if (asize < vd->vdev_asize) {
1029                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1030                             VDEV_AUX_BAD_LABEL);
1031                         return (EINVAL);
1032                 }
1033
1034                 /*
1035                  * If all children are healthy and the asize has increased,
1036                  * then we've experienced dynamic LUN growth.
1037                  */
1038                 if (vd->vdev_state == VDEV_STATE_HEALTHY &&
1039                     asize > vd->vdev_asize) {
1040                         vd->vdev_asize = asize;
1041                 }
1042         }
1043
1044         /*
1045          * Ensure we can issue some IO before declaring the
1046          * vdev open for business.
1047          */
1048         if (vd->vdev_ops->vdev_op_leaf &&
1049             (error = zio_wait(vdev_probe(vd, NULL))) != 0) {
1050                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1051                     VDEV_AUX_IO_FAILURE);
1052                 return (error);
1053         }
1054
1055         /*
1056          * If this is a top-level vdev, compute the raidz-deflation
1057          * ratio.  Note, we hard-code in 128k (1<<17) because it is the
1058          * current "typical" blocksize.  Even if SPA_MAXBLOCKSIZE
1059          * changes, this algorithm must never change, or we will
1060          * inconsistently account for existing bp's.
1061          */
1062         if (vd->vdev_top == vd) {
1063                 vd->vdev_deflate_ratio = (1<<17) /
1064                     (vdev_psize_to_asize(vd, 1<<17) >> SPA_MINBLOCKSHIFT);
1065         }
1066
1067         /*
1068          * If a leaf vdev has a DTL, and seems healthy, then kick off a
1069          * resilver.  But don't do this if we are doing a reopen for a
1070          * scrub, since this would just restart the scrub we are already
1071          * doing.
1072          */
1073         if (vd->vdev_children == 0 && !vd->vdev_spa->spa_scrub_reopen) {
1074                 mutex_enter(&vd->vdev_dtl_lock);
1075                 if (vd->vdev_dtl_map.sm_space != 0 && vdev_writeable(vd))
1076                         spa_async_request(vd->vdev_spa, SPA_ASYNC_RESILVER);
1077                 mutex_exit(&vd->vdev_dtl_lock);
1078         }
1079
1080         return (0);
1081 }
1082
1083 /*
1084  * Called once the vdevs are all opened, this routine validates the label
1085  * contents.  This needs to be done before vdev_load() so that we don't
1086  * inadvertently do repair I/Os to the wrong device.
1087  *
1088  * This function will only return failure if one of the vdevs indicates that it
1089  * has since been destroyed or exported.  This is only possible if
1090  * /etc/zfs/zpool.cache was readonly at the time.  Otherwise, the vdev state
1091  * will be updated but the function will return 0.
1092  */
1093 int
1094 vdev_validate(vdev_t *vd)
1095 {
1096         spa_t *spa = vd->vdev_spa;
1097         int c;
1098         nvlist_t *label;
1099         uint64_t guid, top_guid;
1100         uint64_t state;
1101
1102         for (c = 0; c < vd->vdev_children; c++)
1103                 if (vdev_validate(vd->vdev_child[c]) != 0)
1104                         return (EBADF);
1105
1106         /*
1107          * If the device has already failed, or was marked offline, don't do
1108          * any further validation.  Otherwise, label I/O will fail and we will
1109          * overwrite the previous state.
1110          */
1111         if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd)) {
1112
1113                 if ((label = vdev_label_read_config(vd)) == NULL) {
1114                         vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1115                             VDEV_AUX_BAD_LABEL);
1116                         return (0);
1117                 }
1118
1119                 if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID,
1120                     &guid) != 0 || guid != spa_guid(spa)) {
1121                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1122                             VDEV_AUX_CORRUPT_DATA);
1123                         nvlist_free(label);
1124                         return (0);
1125                 }
1126
1127                 /*
1128                  * If this vdev just became a top-level vdev because its
1129                  * sibling was detached, it will have adopted the parent's
1130                  * vdev guid -- but the label may or may not be on disk yet.
1131                  * Fortunately, either version of the label will have the
1132                  * same top guid, so if we're a top-level vdev, we can
1133                  * safely compare to that instead.
1134                  */
1135                 if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
1136                     &guid) != 0 ||
1137                     nvlist_lookup_uint64(label, ZPOOL_CONFIG_TOP_GUID,
1138                     &top_guid) != 0 ||
1139                     (vd->vdev_guid != guid &&
1140                     (vd->vdev_guid != top_guid || vd != vd->vdev_top))) {
1141                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1142                             VDEV_AUX_CORRUPT_DATA);
1143                         nvlist_free(label);
1144                         return (0);
1145                 }
1146
1147                 if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
1148                     &state) != 0) {
1149                         vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1150                             VDEV_AUX_CORRUPT_DATA);
1151                         nvlist_free(label);
1152                         return (0);
1153                 }
1154
1155                 nvlist_free(label);
1156
1157                 if (spa->spa_load_state == SPA_LOAD_OPEN &&
1158                     state != POOL_STATE_ACTIVE)
1159                         return (EBADF);
1160
1161                 /*
1162                  * If we were able to open and validate a vdev that was
1163                  * previously marked permanently unavailable, clear that state
1164                  * now.
1165                  */
1166                 if (vd->vdev_not_present)
1167                         vd->vdev_not_present = 0;
1168         }
1169
1170         return (0);
1171 }
1172
1173 /*
1174  * Close a virtual device.
1175  */
1176 void
1177 vdev_close(vdev_t *vd)
1178 {
1179         vd->vdev_ops->vdev_op_close(vd);
1180
1181         vdev_cache_purge(vd);
1182
1183         /*
1184          * We record the previous state before we close it, so  that if we are
1185          * doing a reopen(), we don't generate FMA ereports if we notice that
1186          * it's still faulted.
1187          */
1188         vd->vdev_prevstate = vd->vdev_state;
1189
1190         if (vd->vdev_offline)
1191                 vd->vdev_state = VDEV_STATE_OFFLINE;
1192         else
1193                 vd->vdev_state = VDEV_STATE_CLOSED;
1194         vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
1195 }
1196
1197 void
1198 vdev_reopen(vdev_t *vd)
1199 {
1200         spa_t *spa = vd->vdev_spa;
1201
1202         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1203
1204         vdev_close(vd);
1205         (void) vdev_open(vd);
1206
1207         /*
1208          * Call vdev_validate() here to make sure we have the same device.
1209          * Otherwise, a device with an invalid label could be successfully
1210          * opened in response to vdev_reopen().
1211          */
1212         if (vd->vdev_aux) {
1213                 (void) vdev_validate_aux(vd);
1214                 if (vdev_readable(vd) && vdev_writeable(vd) &&
1215                     !l2arc_vdev_present(vd)) {
1216                         uint64_t size = vdev_get_rsize(vd);
1217                         l2arc_add_vdev(spa, vd,
1218                             VDEV_LABEL_START_SIZE,
1219                             size - VDEV_LABEL_START_SIZE);
1220                 }
1221         } else {
1222                 (void) vdev_validate(vd);
1223         }
1224
1225         /*
1226          * Reassess parent vdev's health.
1227          */
1228         vdev_propagate_state(vd);
1229 }
1230
1231 int
1232 vdev_create(vdev_t *vd, uint64_t txg, boolean_t isreplacing)
1233 {
1234         int error;
1235
1236         /*
1237          * Normally, partial opens (e.g. of a mirror) are allowed.
1238          * For a create, however, we want to fail the request if
1239          * there are any components we can't open.
1240          */
1241         error = vdev_open(vd);
1242
1243         if (error || vd->vdev_state != VDEV_STATE_HEALTHY) {
1244                 vdev_close(vd);
1245                 return (error ? error : ENXIO);
1246         }
1247
1248         /*
1249          * Recursively initialize all labels.
1250          */
1251         if ((error = vdev_label_init(vd, txg, isreplacing ?
1252             VDEV_LABEL_REPLACE : VDEV_LABEL_CREATE)) != 0) {
1253                 vdev_close(vd);
1254                 return (error);
1255         }
1256
1257         return (0);
1258 }
1259
1260 /*
1261  * The is the latter half of vdev_create().  It is distinct because it
1262  * involves initiating transactions in order to do metaslab creation.
1263  * For creation, we want to try to create all vdevs at once and then undo it
1264  * if anything fails; this is much harder if we have pending transactions.
1265  */
1266 void
1267 vdev_init(vdev_t *vd, uint64_t txg)
1268 {
1269         /*
1270          * Aim for roughly 200 metaslabs per vdev.
1271          */
1272         vd->vdev_ms_shift = highbit(vd->vdev_asize / 200);
1273         vd->vdev_ms_shift = MAX(vd->vdev_ms_shift, SPA_MAXBLOCKSHIFT);
1274
1275         /*
1276          * Initialize the vdev's metaslabs.  This can't fail because
1277          * there's nothing to read when creating all new metaslabs.
1278          */
1279         VERIFY(vdev_metaslab_init(vd, txg) == 0);
1280 }
1281
1282 void
1283 vdev_dirty(vdev_t *vd, int flags, void *arg, uint64_t txg)
1284 {
1285         ASSERT(vd == vd->vdev_top);
1286         ASSERT(ISP2(flags));
1287
1288         if (flags & VDD_METASLAB)
1289                 (void) txg_list_add(&vd->vdev_ms_list, arg, txg);
1290
1291         if (flags & VDD_DTL)
1292                 (void) txg_list_add(&vd->vdev_dtl_list, arg, txg);
1293
1294         (void) txg_list_add(&vd->vdev_spa->spa_vdev_txg_list, vd, txg);
1295 }
1296
1297 void
1298 vdev_dtl_dirty(space_map_t *sm, uint64_t txg, uint64_t size)
1299 {
1300         mutex_enter(sm->sm_lock);
1301         if (!space_map_contains(sm, txg, size))
1302                 space_map_add(sm, txg, size);
1303         mutex_exit(sm->sm_lock);
1304 }
1305
1306 int
1307 vdev_dtl_contains(space_map_t *sm, uint64_t txg, uint64_t size)
1308 {
1309         int dirty;
1310
1311         /*
1312          * Quick test without the lock -- covers the common case that
1313          * there are no dirty time segments.
1314          */
1315         if (sm->sm_space == 0)
1316                 return (0);
1317
1318         mutex_enter(sm->sm_lock);
1319         dirty = space_map_contains(sm, txg, size);
1320         mutex_exit(sm->sm_lock);
1321
1322         return (dirty);
1323 }
1324
1325 /*
1326  * Reassess DTLs after a config change or scrub completion.
1327  */
1328 void
1329 vdev_dtl_reassess(vdev_t *vd, uint64_t txg, uint64_t scrub_txg, int scrub_done)
1330 {
1331         spa_t *spa = vd->vdev_spa;
1332         int c;
1333
1334         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
1335
1336         if (vd->vdev_children == 0) {
1337                 mutex_enter(&vd->vdev_dtl_lock);
1338                 if (scrub_txg != 0 &&
1339                     (spa->spa_scrub_started || spa->spa_scrub_errors == 0)) {
1340                         /* XXX should check scrub_done? */
1341                         /*
1342                          * We completed a scrub up to scrub_txg.  If we
1343                          * did it without rebooting, then the scrub dtl
1344                          * will be valid, so excise the old region and
1345                          * fold in the scrub dtl.  Otherwise, leave the
1346                          * dtl as-is if there was an error.
1347                          */
1348                         space_map_excise(&vd->vdev_dtl_map, 0, scrub_txg);
1349                         space_map_union(&vd->vdev_dtl_map, &vd->vdev_dtl_scrub);
1350                 }
1351                 if (scrub_done)
1352                         space_map_vacate(&vd->vdev_dtl_scrub, NULL, NULL);
1353                 mutex_exit(&vd->vdev_dtl_lock);
1354
1355                 if (txg != 0)
1356                         vdev_dirty(vd->vdev_top, VDD_DTL, vd, txg);
1357                 return;
1358         }
1359
1360         /*
1361          * Make sure the DTLs are always correct under the scrub lock.
1362          */
1363         if (vd == spa->spa_root_vdev)
1364                 mutex_enter(&spa->spa_scrub_lock);
1365
1366         mutex_enter(&vd->vdev_dtl_lock);
1367         space_map_vacate(&vd->vdev_dtl_map, NULL, NULL);
1368         space_map_vacate(&vd->vdev_dtl_scrub, NULL, NULL);
1369         mutex_exit(&vd->vdev_dtl_lock);
1370
1371         for (c = 0; c < vd->vdev_children; c++) {
1372                 vdev_t *cvd = vd->vdev_child[c];
1373                 vdev_dtl_reassess(cvd, txg, scrub_txg, scrub_done);
1374                 mutex_enter(&vd->vdev_dtl_lock);
1375                 space_map_union(&vd->vdev_dtl_map, &cvd->vdev_dtl_map);
1376                 space_map_union(&vd->vdev_dtl_scrub, &cvd->vdev_dtl_scrub);
1377                 mutex_exit(&vd->vdev_dtl_lock);
1378         }
1379
1380         if (vd == spa->spa_root_vdev)
1381                 mutex_exit(&spa->spa_scrub_lock);
1382 }
1383
1384 static int
1385 vdev_dtl_load(vdev_t *vd)
1386 {
1387         spa_t *spa = vd->vdev_spa;
1388         space_map_obj_t *smo = &vd->vdev_dtl;
1389         objset_t *mos = spa->spa_meta_objset;
1390         dmu_buf_t *db;
1391         int error;
1392
1393         ASSERT(vd->vdev_children == 0);
1394
1395         if (smo->smo_object == 0)
1396                 return (0);
1397
1398         if ((error = dmu_bonus_hold(mos, smo->smo_object, FTAG, &db)) != 0)
1399                 return (error);
1400
1401         ASSERT3U(db->db_size, >=, sizeof (*smo));
1402         bcopy(db->db_data, smo, sizeof (*smo));
1403         dmu_buf_rele(db, FTAG);
1404
1405         mutex_enter(&vd->vdev_dtl_lock);
1406         error = space_map_load(&vd->vdev_dtl_map, NULL, SM_ALLOC, smo, mos);
1407         mutex_exit(&vd->vdev_dtl_lock);
1408
1409         return (error);
1410 }
1411
1412 void
1413 vdev_dtl_sync(vdev_t *vd, uint64_t txg)
1414 {
1415         spa_t *spa = vd->vdev_spa;
1416         space_map_obj_t *smo = &vd->vdev_dtl;
1417         space_map_t *sm = &vd->vdev_dtl_map;
1418         objset_t *mos = spa->spa_meta_objset;
1419         space_map_t smsync;
1420         kmutex_t smlock;
1421         dmu_buf_t *db;
1422         dmu_tx_t *tx;
1423
1424         tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
1425
1426         if (vd->vdev_detached) {
1427                 if (smo->smo_object != 0) {
1428                         int err = dmu_object_free(mos, smo->smo_object, tx);
1429                         ASSERT3U(err, ==, 0);
1430                         smo->smo_object = 0;
1431                 }
1432                 dmu_tx_commit(tx);
1433                 return;
1434         }
1435
1436         if (smo->smo_object == 0) {
1437                 ASSERT(smo->smo_objsize == 0);
1438                 ASSERT(smo->smo_alloc == 0);
1439                 smo->smo_object = dmu_object_alloc(mos,
1440                     DMU_OT_SPACE_MAP, 1 << SPACE_MAP_BLOCKSHIFT,
1441                     DMU_OT_SPACE_MAP_HEADER, sizeof (*smo), tx);
1442                 ASSERT(smo->smo_object != 0);
1443                 vdev_config_dirty(vd->vdev_top);
1444         }
1445
1446         mutex_init(&smlock, NULL, MUTEX_DEFAULT, NULL);
1447
1448         space_map_create(&smsync, sm->sm_start, sm->sm_size, sm->sm_shift,
1449             &smlock);
1450
1451         mutex_enter(&smlock);
1452
1453         mutex_enter(&vd->vdev_dtl_lock);
1454         space_map_walk(sm, space_map_add, &smsync);
1455         mutex_exit(&vd->vdev_dtl_lock);
1456
1457         space_map_truncate(smo, mos, tx);
1458         space_map_sync(&smsync, SM_ALLOC, smo, mos, tx);
1459
1460         space_map_destroy(&smsync);
1461
1462         mutex_exit(&smlock);
1463         mutex_destroy(&smlock);
1464
1465         VERIFY(0 == dmu_bonus_hold(mos, smo->smo_object, FTAG, &db));
1466         dmu_buf_will_dirty(db, tx);
1467         ASSERT3U(db->db_size, >=, sizeof (*smo));
1468         bcopy(smo, db->db_data, sizeof (*smo));
1469         dmu_buf_rele(db, FTAG);
1470
1471         dmu_tx_commit(tx);
1472 }
1473
1474 /*
1475  * Determine if resilver is needed, and if so the txg range.
1476  */
1477 boolean_t
1478 vdev_resilver_needed(vdev_t *vd, uint64_t *minp, uint64_t *maxp)
1479 {
1480         boolean_t needed = B_FALSE;
1481         uint64_t thismin = UINT64_MAX;
1482         uint64_t thismax = 0;
1483
1484         if (vd->vdev_children == 0) {
1485                 mutex_enter(&vd->vdev_dtl_lock);
1486                 if (vd->vdev_dtl_map.sm_space != 0 && vdev_writeable(vd)) {
1487                         space_seg_t *ss;
1488
1489                         ss = avl_first(&vd->vdev_dtl_map.sm_root);
1490                         thismin = ss->ss_start - 1;
1491                         ss = avl_last(&vd->vdev_dtl_map.sm_root);
1492                         thismax = ss->ss_end;
1493                         needed = B_TRUE;
1494                 }
1495                 mutex_exit(&vd->vdev_dtl_lock);
1496         } else {
1497                 int c;
1498                 for (c = 0; c < vd->vdev_children; c++) {
1499                         vdev_t *cvd = vd->vdev_child[c];
1500                         uint64_t cmin, cmax;
1501
1502                         if (vdev_resilver_needed(cvd, &cmin, &cmax)) {
1503                                 thismin = MIN(thismin, cmin);
1504                                 thismax = MAX(thismax, cmax);
1505                                 needed = B_TRUE;
1506                         }
1507                 }
1508         }
1509
1510         if (needed && minp) {
1511                 *minp = thismin;
1512                 *maxp = thismax;
1513         }
1514         return (needed);
1515 }
1516
1517 void
1518 vdev_load(vdev_t *vd)
1519 {
1520         int c;
1521
1522         /*
1523          * Recursively load all children.
1524          */
1525         for (c = 0; c < vd->vdev_children; c++)
1526                 vdev_load(vd->vdev_child[c]);
1527
1528         /*
1529          * If this is a top-level vdev, initialize its metaslabs.
1530          */
1531         if (vd == vd->vdev_top &&
1532             (vd->vdev_ashift == 0 || vd->vdev_asize == 0 ||
1533             vdev_metaslab_init(vd, 0) != 0))
1534                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1535                     VDEV_AUX_CORRUPT_DATA);
1536
1537         /*
1538          * If this is a leaf vdev, load its DTL.
1539          */
1540         if (vd->vdev_ops->vdev_op_leaf && vdev_dtl_load(vd) != 0)
1541                 vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
1542                     VDEV_AUX_CORRUPT_DATA);
1543 }
1544
1545 /*
1546  * The special vdev case is used for hot spares and l2cache devices.  Its
1547  * sole purpose it to set the vdev state for the associated vdev.  To do this,
1548  * we make sure that we can open the underlying device, then try to read the
1549  * label, and make sure that the label is sane and that it hasn't been
1550  * repurposed to another pool.
1551  */
1552 int
1553 vdev_validate_aux(vdev_t *vd)
1554 {
1555         nvlist_t *label;
1556         uint64_t guid, version;
1557         uint64_t state;
1558
1559         if (!vdev_readable(vd))
1560                 return (0);
1561
1562         if ((label = vdev_label_read_config(vd)) == NULL) {
1563                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1564                     VDEV_AUX_CORRUPT_DATA);
1565                 return (-1);
1566         }
1567
1568         if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_VERSION, &version) != 0 ||
1569             version > SPA_VERSION ||
1570             nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0 ||
1571             guid != vd->vdev_guid ||
1572             nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE, &state) != 0) {
1573                 vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
1574                     VDEV_AUX_CORRUPT_DATA);
1575                 nvlist_free(label);
1576                 return (-1);
1577         }
1578
1579         /*
1580          * We don't actually check the pool state here.  If it's in fact in
1581          * use by another pool, we update this fact on the fly when requested.
1582          */
1583         nvlist_free(label);
1584         return (0);
1585 }
1586
1587 void
1588 vdev_sync_done(vdev_t *vd, uint64_t txg)
1589 {
1590         metaslab_t *msp;
1591
1592         while (msp = txg_list_remove(&vd->vdev_ms_list, TXG_CLEAN(txg)))
1593                 metaslab_sync_done(msp, txg);
1594 }
1595
1596 void
1597 vdev_sync(vdev_t *vd, uint64_t txg)
1598 {
1599         spa_t *spa = vd->vdev_spa;
1600         vdev_t *lvd;
1601         metaslab_t *msp;
1602         dmu_tx_t *tx;
1603
1604         if (vd->vdev_ms_array == 0 && vd->vdev_ms_shift != 0) {
1605                 ASSERT(vd == vd->vdev_top);
1606                 tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
1607                 vd->vdev_ms_array = dmu_object_alloc(spa->spa_meta_objset,
1608                     DMU_OT_OBJECT_ARRAY, 0, DMU_OT_NONE, 0, tx);
1609                 ASSERT(vd->vdev_ms_array != 0);
1610                 vdev_config_dirty(vd);
1611                 dmu_tx_commit(tx);
1612         }
1613
1614         while ((msp = txg_list_remove(&vd->vdev_ms_list, txg)) != NULL) {
1615                 metaslab_sync(msp, txg);
1616                 (void) txg_list_add(&vd->vdev_ms_list, msp, TXG_CLEAN(txg));
1617         }
1618
1619         while ((lvd = txg_list_remove(&vd->vdev_dtl_list, txg)) != NULL)
1620                 vdev_dtl_sync(lvd, txg);
1621
1622         (void) txg_list_add(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg));
1623 }
1624
1625 uint64_t
1626 vdev_psize_to_asize(vdev_t *vd, uint64_t psize)
1627 {
1628         return (vd->vdev_ops->vdev_op_asize(vd, psize));
1629 }
1630
1631 /*
1632  * Mark the given vdev faulted.  A faulted vdev behaves as if the device could
1633  * not be opened, and no I/O is attempted.
1634  */
1635 int
1636 vdev_fault(spa_t *spa, uint64_t guid)
1637 {
1638         vdev_t *vd;
1639
1640         spa_vdev_state_enter(spa);
1641
1642         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
1643                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
1644
1645         if (!vd->vdev_ops->vdev_op_leaf)
1646                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
1647
1648         /*
1649          * Faulted state takes precedence over degraded.
1650          */
1651         vd->vdev_faulted = 1ULL;
1652         vd->vdev_degraded = 0ULL;
1653         vdev_set_state(vd, B_FALSE, VDEV_STATE_FAULTED, VDEV_AUX_ERR_EXCEEDED);
1654
1655         /*
1656          * If marking the vdev as faulted cause the top-level vdev to become
1657          * unavailable, then back off and simply mark the vdev as degraded
1658          * instead.
1659          */
1660         if (vdev_is_dead(vd->vdev_top) && vd->vdev_aux == NULL) {
1661                 vd->vdev_degraded = 1ULL;
1662                 vd->vdev_faulted = 0ULL;
1663
1664                 /*
1665                  * If we reopen the device and it's not dead, only then do we
1666                  * mark it degraded.
1667                  */
1668                 vdev_reopen(vd);
1669
1670                 if (vdev_readable(vd)) {
1671                         vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED,
1672                             VDEV_AUX_ERR_EXCEEDED);
1673                 }
1674         }
1675
1676         return (spa_vdev_state_exit(spa, vd, 0));
1677 }
1678
1679 /*
1680  * Mark the given vdev degraded.  A degraded vdev is purely an indication to the
1681  * user that something is wrong.  The vdev continues to operate as normal as far
1682  * as I/O is concerned.
1683  */
1684 int
1685 vdev_degrade(spa_t *spa, uint64_t guid)
1686 {
1687         vdev_t *vd;
1688
1689         spa_vdev_state_enter(spa);
1690
1691         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
1692                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
1693
1694         if (!vd->vdev_ops->vdev_op_leaf)
1695                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
1696
1697         /*
1698          * If the vdev is already faulted, then don't do anything.
1699          */
1700         if (vd->vdev_faulted || vd->vdev_degraded)
1701                 return (spa_vdev_state_exit(spa, NULL, 0));
1702
1703         vd->vdev_degraded = 1ULL;
1704         if (!vdev_is_dead(vd))
1705                 vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED,
1706                     VDEV_AUX_ERR_EXCEEDED);
1707
1708         return (spa_vdev_state_exit(spa, vd, 0));
1709 }
1710
1711 /*
1712  * Online the given vdev.  If 'unspare' is set, it implies two things.  First,
1713  * any attached spare device should be detached when the device finishes
1714  * resilvering.  Second, the online should be treated like a 'test' online case,
1715  * so no FMA events are generated if the device fails to open.
1716  */
1717 int
1718 vdev_online(spa_t *spa, uint64_t guid, uint64_t flags, vdev_state_t *newstate)
1719 {
1720         vdev_t *vd;
1721
1722         spa_vdev_state_enter(spa);
1723
1724         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
1725                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
1726
1727         if (!vd->vdev_ops->vdev_op_leaf)
1728                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
1729
1730         vd->vdev_offline = B_FALSE;
1731         vd->vdev_tmpoffline = B_FALSE;
1732         vd->vdev_checkremove = !!(flags & ZFS_ONLINE_CHECKREMOVE);
1733         vd->vdev_forcefault = !!(flags & ZFS_ONLINE_FORCEFAULT);
1734         vdev_reopen(vd->vdev_top);
1735         vd->vdev_checkremove = vd->vdev_forcefault = B_FALSE;
1736
1737         if (newstate)
1738                 *newstate = vd->vdev_state;
1739         if ((flags & ZFS_ONLINE_UNSPARE) &&
1740             !vdev_is_dead(vd) && vd->vdev_parent &&
1741             vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
1742             vd->vdev_parent->vdev_child[0] == vd)
1743                 vd->vdev_unspare = B_TRUE;
1744
1745         (void) spa_vdev_state_exit(spa, vd, 0);
1746
1747         VERIFY3U(spa_scrub(spa, POOL_SCRUB_RESILVER), ==, 0);
1748
1749         return (0);
1750 }
1751
1752 int
1753 vdev_offline(spa_t *spa, uint64_t guid, uint64_t flags)
1754 {
1755         vdev_t *vd;
1756
1757         spa_vdev_state_enter(spa);
1758
1759         if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
1760                 return (spa_vdev_state_exit(spa, NULL, ENODEV));
1761
1762         if (!vd->vdev_ops->vdev_op_leaf)
1763                 return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
1764
1765         /*
1766          * If the device isn't already offline, try to offline it.
1767          */
1768         if (!vd->vdev_offline) {
1769                 /*
1770                  * If this device's top-level vdev has a non-empty DTL,
1771                  * don't allow the device to be offlined.
1772                  *
1773                  * XXX -- make this more precise by allowing the offline
1774                  * as long as the remaining devices don't have any DTL holes.
1775                  */
1776                 if (vd->vdev_top->vdev_dtl_map.sm_space != 0)
1777                         return (spa_vdev_state_exit(spa, NULL, EBUSY));
1778
1779                 /*
1780                  * Offline this device and reopen its top-level vdev.
1781                  * If this action results in the top-level vdev becoming
1782                  * unusable, undo it and fail the request.
1783                  */
1784                 vd->vdev_offline = B_TRUE;
1785                 vdev_reopen(vd->vdev_top);
1786                 if (vdev_is_dead(vd->vdev_top) && vd->vdev_aux == NULL) {
1787                         vd->vdev_offline = B_FALSE;
1788                         vdev_reopen(vd->vdev_top);
1789                         return (spa_vdev_state_exit(spa, NULL, EBUSY));
1790                 }
1791         }
1792
1793         vd->vdev_tmpoffline = !!(flags & ZFS_OFFLINE_TEMPORARY);
1794
1795         return (spa_vdev_state_exit(spa, vd, 0));
1796 }
1797
1798 /*
1799  * Clear the error counts associated with this vdev.  Unlike vdev_online() and
1800  * vdev_offline(), we assume the spa config is locked.  We also clear all
1801  * children.  If 'vd' is NULL, then the user wants to clear all vdevs.
1802  */
1803 void
1804 vdev_clear(spa_t *spa, vdev_t *vd)
1805 {
1806         vdev_t *rvd = spa->spa_root_vdev;
1807
1808         ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
1809
1810         if (vd == NULL)
1811                 vd = rvd;
1812
1813         vd->vdev_stat.vs_read_errors = 0;
1814         vd->vdev_stat.vs_write_errors = 0;
1815         vd->vdev_stat.vs_checksum_errors = 0;
1816
1817         for (int c = 0; c < vd->vdev_children; c++)
1818                 vdev_clear(spa, vd->vdev_child[c]);
1819
1820         /*
1821          * If we're in the FAULTED state or have experienced failed I/O, then
1822          * clear the persistent state and attempt to reopen the device.  We
1823          * also mark the vdev config dirty, so that the new faulted state is
1824          * written out to disk.
1825          */
1826         if (vd->vdev_faulted || vd->vdev_degraded ||
1827             !vdev_readable(vd) || !vdev_writeable(vd)) {
1828
1829                 vd->vdev_faulted = vd->vdev_degraded = 0;
1830                 vd->vdev_cant_read = B_FALSE;
1831                 vd->vdev_cant_write = B_FALSE;
1832
1833                 vdev_reopen(vd);
1834
1835                 if (vd != rvd)
1836                         vdev_state_dirty(vd->vdev_top);
1837
1838                 if (vd->vdev_aux == NULL && !vdev_is_dead(vd))
1839                         spa_async_request(spa, SPA_ASYNC_RESILVER);
1840
1841                 spa_event_notify(spa, vd, ESC_ZFS_VDEV_CLEAR);
1842         }
1843 }
1844
1845 boolean_t
1846 vdev_is_dead(vdev_t *vd)
1847 {
1848         return (vd->vdev_state < VDEV_STATE_DEGRADED);
1849 }
1850
1851 boolean_t
1852 vdev_readable(vdev_t *vd)
1853 {
1854         return (!vdev_is_dead(vd) && !vd->vdev_cant_read);
1855 }
1856
1857 boolean_t
1858 vdev_writeable(vdev_t *vd)
1859 {
1860         return (!vdev_is_dead(vd) && !vd->vdev_cant_write);
1861 }
1862
1863 boolean_t
1864 vdev_accessible(vdev_t *vd, zio_t *zio)
1865 {
1866         ASSERT(zio->io_vd == vd);
1867
1868         if (vdev_is_dead(vd) || vd->vdev_remove_wanted)
1869                 return (B_FALSE);
1870
1871         if (zio->io_type == ZIO_TYPE_READ)
1872                 return (!vd->vdev_cant_read);
1873
1874         if (zio->io_type == ZIO_TYPE_WRITE)
1875                 return (!vd->vdev_cant_write);
1876
1877         return (B_TRUE);
1878 }
1879
1880 /*
1881  * Get statistics for the given vdev.
1882  */
1883 void
1884 vdev_get_stats(vdev_t *vd, vdev_stat_t *vs)
1885 {
1886         vdev_t *rvd = vd->vdev_spa->spa_root_vdev;
1887
1888         mutex_enter(&vd->vdev_stat_lock);
1889         bcopy(&vd->vdev_stat, vs, sizeof (*vs));
1890         vs->vs_scrub_errors = vd->vdev_spa->spa_scrub_errors;
1891         vs->vs_timestamp = gethrtime() - vs->vs_timestamp;
1892         vs->vs_state = vd->vdev_state;
1893         vs->vs_rsize = vdev_get_rsize(vd);
1894         mutex_exit(&vd->vdev_stat_lock);
1895
1896         /*
1897          * If we're getting stats on the root vdev, aggregate the I/O counts
1898          * over all top-level vdevs (i.e. the direct children of the root).
1899          */
1900         if (vd == rvd) {
1901                 for (int c = 0; c < rvd->vdev_children; c++) {
1902                         vdev_t *cvd = rvd->vdev_child[c];
1903                         vdev_stat_t *cvs = &cvd->vdev_stat;
1904
1905                         mutex_enter(&vd->vdev_stat_lock);
1906                         for (int t = 0; t < ZIO_TYPES; t++) {
1907                                 vs->vs_ops[t] += cvs->vs_ops[t];
1908                                 vs->vs_bytes[t] += cvs->vs_bytes[t];
1909                         }
1910                         vs->vs_scrub_examined += cvs->vs_scrub_examined;
1911                         mutex_exit(&vd->vdev_stat_lock);
1912                 }
1913         }
1914 }
1915
1916 void
1917 vdev_clear_stats(vdev_t *vd)
1918 {
1919         mutex_enter(&vd->vdev_stat_lock);
1920         vd->vdev_stat.vs_space = 0;
1921         vd->vdev_stat.vs_dspace = 0;
1922         vd->vdev_stat.vs_alloc = 0;
1923         mutex_exit(&vd->vdev_stat_lock);
1924 }
1925
1926 void
1927 vdev_stat_update(zio_t *zio, uint64_t psize)
1928 {
1929         vdev_t *rvd = zio->io_spa->spa_root_vdev;
1930         vdev_t *vd = zio->io_vd ? zio->io_vd : rvd;
1931         vdev_t *pvd;
1932         uint64_t txg = zio->io_txg;
1933         vdev_stat_t *vs = &vd->vdev_stat;
1934         zio_type_t type = zio->io_type;
1935         int flags = zio->io_flags;
1936
1937         /*
1938          * If this i/o is a gang leader, it didn't do any actual work.
1939          */
1940         if (zio->io_gang_tree)
1941                 return;
1942
1943         if (zio->io_error == 0) {
1944                 /*
1945                  * If this is a root i/o, don't count it -- we've already
1946                  * counted the top-level vdevs, and vdev_get_stats() will
1947                  * aggregate them when asked.  This reduces contention on
1948                  * the root vdev_stat_lock and implicitly handles blocks
1949                  * that compress away to holes, for which there is no i/o.
1950                  * (Holes never create vdev children, so all the counters
1951                  * remain zero, which is what we want.)
1952                  *
1953                  * Note: this only applies to successful i/o (io_error == 0)
1954                  * because unlike i/o counts, errors are not additive.
1955                  * When reading a ditto block, for example, failure of
1956                  * one top-level vdev does not imply a root-level error.
1957                  */
1958                 if (vd == rvd)
1959                         return;
1960
1961                 ASSERT(vd == zio->io_vd);
1962                 if (!(flags & ZIO_FLAG_IO_BYPASS)) {
1963                         mutex_enter(&vd->vdev_stat_lock);
1964                         vs->vs_ops[type]++;
1965                         vs->vs_bytes[type] += psize;
1966                         mutex_exit(&vd->vdev_stat_lock);
1967                 }
1968                 if (flags & ZIO_FLAG_IO_REPAIR) {
1969                         ASSERT(zio->io_delegate_list == NULL);
1970                         mutex_enter(&vd->vdev_stat_lock);
1971                         if (flags & ZIO_FLAG_SCRUB_THREAD)
1972                                 vs->vs_scrub_repaired += psize;
1973                         else
1974                                 vs->vs_self_healed += psize;
1975                         mutex_exit(&vd->vdev_stat_lock);
1976                 }
1977                 return;
1978         }
1979
1980         if (flags & ZIO_FLAG_SPECULATIVE)
1981                 return;
1982
1983         mutex_enter(&vd->vdev_stat_lock);
1984         if (type == ZIO_TYPE_READ) {
1985                 if (zio->io_error == ECKSUM)
1986                         vs->vs_checksum_errors++;
1987                 else
1988                         vs->vs_read_errors++;
1989         }
1990         if (type == ZIO_TYPE_WRITE)
1991                 vs->vs_write_errors++;
1992         mutex_exit(&vd->vdev_stat_lock);
1993
1994         if (type == ZIO_TYPE_WRITE && txg != 0 && vd->vdev_children == 0) {
1995                 if (flags & ZIO_FLAG_SCRUB_THREAD) {
1996                         ASSERT(flags & ZIO_FLAG_IO_REPAIR);
1997                         for (pvd = vd; pvd != NULL; pvd = pvd->vdev_parent)
1998                                 vdev_dtl_dirty(&pvd->vdev_dtl_scrub, txg, 1);
1999                 }
2000                 if (!(flags & ZIO_FLAG_IO_REPAIR)) {
2001                         if (vdev_dtl_contains(&vd->vdev_dtl_map, txg, 1))
2002                                 return;
2003                         vdev_dirty(vd->vdev_top, VDD_DTL, vd, txg);
2004                         for (pvd = vd; pvd != NULL; pvd = pvd->vdev_parent)
2005                                 vdev_dtl_dirty(&pvd->vdev_dtl_map, txg, 1);
2006                 }
2007         }
2008 }
2009
2010 void
2011 vdev_scrub_stat_update(vdev_t *vd, pool_scrub_type_t type, boolean_t complete)
2012 {
2013         int c;
2014         vdev_stat_t *vs = &vd->vdev_stat;
2015
2016         for (c = 0; c < vd->vdev_children; c++)
2017                 vdev_scrub_stat_update(vd->vdev_child[c], type, complete);
2018
2019         mutex_enter(&vd->vdev_stat_lock);
2020
2021         if (type == POOL_SCRUB_NONE) {
2022                 /*
2023                  * Update completion and end time.  Leave everything else alone
2024                  * so we can report what happened during the previous scrub.
2025                  */
2026                 vs->vs_scrub_complete = complete;
2027                 vs->vs_scrub_end = gethrestime_sec();
2028         } else {
2029                 vs->vs_scrub_type = type;
2030                 vs->vs_scrub_complete = 0;
2031                 vs->vs_scrub_examined = 0;
2032                 vs->vs_scrub_repaired = 0;
2033                 vs->vs_scrub_start = gethrestime_sec();
2034                 vs->vs_scrub_end = 0;
2035         }
2036
2037         mutex_exit(&vd->vdev_stat_lock);
2038 }
2039
2040 /*
2041  * Update the in-core space usage stats for this vdev and the root vdev.
2042  */
2043 void
2044 vdev_space_update(vdev_t *vd, int64_t space_delta, int64_t alloc_delta,
2045     boolean_t update_root)
2046 {
2047         int64_t dspace_delta = space_delta;
2048         spa_t *spa = vd->vdev_spa;
2049         vdev_t *rvd = spa->spa_root_vdev;
2050
2051         ASSERT(vd == vd->vdev_top);
2052
2053         /*
2054          * Apply the inverse of the psize-to-asize (ie. RAID-Z) space-expansion
2055          * factor.  We must calculate this here and not at the root vdev
2056          * because the root vdev's psize-to-asize is simply the max of its
2057          * childrens', thus not accurate enough for us.
2058          */
2059         ASSERT((dspace_delta & (SPA_MINBLOCKSIZE-1)) == 0);
2060         dspace_delta = (dspace_delta >> SPA_MINBLOCKSHIFT) *
2061             vd->vdev_deflate_ratio;
2062
2063         mutex_enter(&vd->vdev_stat_lock);
2064         vd->vdev_stat.vs_space += space_delta;
2065         vd->vdev_stat.vs_alloc += alloc_delta;
2066         vd->vdev_stat.vs_dspace += dspace_delta;
2067         mutex_exit(&vd->vdev_stat_lock);
2068
2069         if (update_root) {
2070                 ASSERT(rvd == vd->vdev_parent);
2071                 ASSERT(vd->vdev_ms_count != 0);
2072
2073                 /*
2074                  * Don't count non-normal (e.g. intent log) space as part of
2075                  * the pool's capacity.
2076                  */
2077                 if (vd->vdev_mg->mg_class != spa->spa_normal_class)
2078                         return;
2079
2080                 mutex_enter(&rvd->vdev_stat_lock);
2081                 rvd->vdev_stat.vs_space += space_delta;
2082                 rvd->vdev_stat.vs_alloc += alloc_delta;
2083                 rvd->vdev_stat.vs_dspace += dspace_delta;
2084                 mutex_exit(&rvd->vdev_stat_lock);
2085         }
2086 }
2087
2088 /*
2089  * Mark a top-level vdev's config as dirty, placing it on the dirty list
2090  * so that it will be written out next time the vdev configuration is synced.
2091  * If the root vdev is specified (vdev_top == NULL), dirty all top-level vdevs.
2092  */
2093 void
2094 vdev_config_dirty(vdev_t *vd)
2095 {
2096         spa_t *spa = vd->vdev_spa;
2097         vdev_t *rvd = spa->spa_root_vdev;
2098         int c;
2099
2100         /*
2101          * If this is an aux vdev (as with l2cache devices), then we update the
2102          * vdev config manually and set the sync flag.
2103          */
2104         if (vd->vdev_aux != NULL) {
2105                 spa_aux_vdev_t *sav = vd->vdev_aux;
2106                 nvlist_t **aux;
2107                 uint_t naux;
2108
2109                 for (c = 0; c < sav->sav_count; c++) {
2110                         if (sav->sav_vdevs[c] == vd)
2111                                 break;
2112                 }
2113
2114                 if (c == sav->sav_count) {
2115                         /*
2116                          * We're being removed.  There's nothing more to do.
2117                          */
2118                         ASSERT(sav->sav_sync == B_TRUE);
2119                         return;
2120                 }
2121
2122                 sav->sav_sync = B_TRUE;
2123
2124                 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
2125                     ZPOOL_CONFIG_L2CACHE, &aux, &naux) == 0);
2126
2127                 ASSERT(c < naux);
2128
2129                 /*
2130                  * Setting the nvlist in the middle if the array is a little
2131                  * sketchy, but it will work.
2132                  */
2133                 nvlist_free(aux[c]);
2134                 aux[c] = vdev_config_generate(spa, vd, B_TRUE, B_FALSE, B_TRUE);
2135
2136                 return;
2137         }
2138
2139         /*
2140          * The dirty list is protected by the SCL_CONFIG lock.  The caller
2141          * must either hold SCL_CONFIG as writer, or must be the sync thread
2142          * (which holds SCL_CONFIG as reader).  There's only one sync thread,
2143          * so this is sufficient to ensure mutual exclusion.
2144          */
2145         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
2146             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
2147             spa_config_held(spa, SCL_CONFIG, RW_READER)));
2148
2149         if (vd == rvd) {
2150                 for (c = 0; c < rvd->vdev_children; c++)
2151                         vdev_config_dirty(rvd->vdev_child[c]);
2152         } else {
2153                 ASSERT(vd == vd->vdev_top);
2154
2155                 if (!list_link_active(&vd->vdev_config_dirty_node))
2156                         list_insert_head(&spa->spa_config_dirty_list, vd);
2157         }
2158 }
2159
2160 void
2161 vdev_config_clean(vdev_t *vd)
2162 {
2163         spa_t *spa = vd->vdev_spa;
2164
2165         ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
2166             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
2167             spa_config_held(spa, SCL_CONFIG, RW_READER)));
2168
2169         ASSERT(list_link_active(&vd->vdev_config_dirty_node));
2170         list_remove(&spa->spa_config_dirty_list, vd);
2171 }
2172
2173 /*
2174  * Mark a top-level vdev's state as dirty, so that the next pass of
2175  * spa_sync() can convert this into vdev_config_dirty().  We distinguish
2176  * the state changes from larger config changes because they require
2177  * much less locking, and are often needed for administrative actions.
2178  */
2179 void
2180 vdev_state_dirty(vdev_t *vd)
2181 {
2182         spa_t *spa = vd->vdev_spa;
2183
2184         ASSERT(vd == vd->vdev_top);
2185
2186         /*
2187          * The state list is protected by the SCL_STATE lock.  The caller
2188          * must either hold SCL_STATE as writer, or must be the sync thread
2189          * (which holds SCL_STATE as reader).  There's only one sync thread,
2190          * so this is sufficient to ensure mutual exclusion.
2191          */
2192         ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
2193             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
2194             spa_config_held(spa, SCL_STATE, RW_READER)));
2195
2196         if (!list_link_active(&vd->vdev_state_dirty_node))
2197                 list_insert_head(&spa->spa_state_dirty_list, vd);
2198 }
2199
2200 void
2201 vdev_state_clean(vdev_t *vd)
2202 {
2203         spa_t *spa = vd->vdev_spa;
2204
2205         ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
2206             (dsl_pool_sync_context(spa_get_dsl(spa)) &&
2207             spa_config_held(spa, SCL_STATE, RW_READER)));
2208
2209         ASSERT(list_link_active(&vd->vdev_state_dirty_node));
2210         list_remove(&spa->spa_state_dirty_list, vd);
2211 }
2212
2213 /*
2214  * Propagate vdev state up from children to parent.
2215  */
2216 void
2217 vdev_propagate_state(vdev_t *vd)
2218 {
2219         vdev_t *rvd = vd->vdev_spa->spa_root_vdev;
2220         int degraded = 0, faulted = 0;
2221         int corrupted = 0;
2222         int c;
2223         vdev_t *child;
2224
2225         if (vd->vdev_children > 0) {
2226                 for (c = 0; c < vd->vdev_children; c++) {
2227                         child = vd->vdev_child[c];
2228
2229                         if (!vdev_readable(child) ||
2230                             (!vdev_writeable(child) && (spa_mode & FWRITE))) {
2231                                 /*
2232                                  * Root special: if there is a top-level log
2233                                  * device, treat the root vdev as if it were
2234                                  * degraded.
2235                                  */
2236                                 if (child->vdev_islog && vd == rvd)
2237                                         degraded++;
2238                                 else
2239                                         faulted++;
2240                         } else if (child->vdev_state <= VDEV_STATE_DEGRADED) {
2241                                 degraded++;
2242                         }
2243
2244                         if (child->vdev_stat.vs_aux == VDEV_AUX_CORRUPT_DATA)
2245                                 corrupted++;
2246                 }
2247
2248                 vd->vdev_ops->vdev_op_state_change(vd, faulted, degraded);
2249
2250                 /*
2251                  * Root special: if there is a top-level vdev that cannot be
2252                  * opened due to corrupted metadata, then propagate the root
2253                  * vdev's aux state as 'corrupt' rather than 'insufficient
2254                  * replicas'.
2255                  */
2256                 if (corrupted && vd == rvd &&
2257                     rvd->vdev_state == VDEV_STATE_CANT_OPEN)
2258                         vdev_set_state(rvd, B_FALSE, VDEV_STATE_CANT_OPEN,
2259                             VDEV_AUX_CORRUPT_DATA);
2260         }
2261
2262         if (vd->vdev_parent)
2263                 vdev_propagate_state(vd->vdev_parent);
2264 }
2265
2266 /*
2267  * Set a vdev's state.  If this is during an open, we don't update the parent
2268  * state, because we're in the process of opening children depth-first.
2269  * Otherwise, we propagate the change to the parent.
2270  *
2271  * If this routine places a device in a faulted state, an appropriate ereport is
2272  * generated.
2273  */
2274 void
2275 vdev_set_state(vdev_t *vd, boolean_t isopen, vdev_state_t state, vdev_aux_t aux)
2276 {
2277         uint64_t save_state;
2278         spa_t *spa = vd->vdev_spa;
2279
2280         if (state == vd->vdev_state) {
2281                 vd->vdev_stat.vs_aux = aux;
2282                 return;
2283         }
2284
2285         save_state = vd->vdev_state;
2286
2287         vd->vdev_state = state;
2288         vd->vdev_stat.vs_aux = aux;
2289
2290         /*
2291          * If we are setting the vdev state to anything but an open state, then
2292          * always close the underlying device.  Otherwise, we keep accessible
2293          * but invalid devices open forever.  We don't call vdev_close() itself,
2294          * because that implies some extra checks (offline, etc) that we don't
2295          * want here.  This is limited to leaf devices, because otherwise
2296          * closing the device will affect other children.
2297          */
2298         if (vdev_is_dead(vd) && vd->vdev_ops->vdev_op_leaf)
2299                 vd->vdev_ops->vdev_op_close(vd);
2300
2301         if (vd->vdev_removed &&
2302             state == VDEV_STATE_CANT_OPEN &&
2303             (aux == VDEV_AUX_OPEN_FAILED || vd->vdev_checkremove)) {
2304                 /*
2305                  * If the previous state is set to VDEV_STATE_REMOVED, then this
2306                  * device was previously marked removed and someone attempted to
2307                  * reopen it.  If this failed due to a nonexistent device, then
2308                  * keep the device in the REMOVED state.  We also let this be if
2309                  * it is one of our special test online cases, which is only
2310                  * attempting to online the device and shouldn't generate an FMA
2311                  * fault.
2312                  */
2313                 vd->vdev_state = VDEV_STATE_REMOVED;
2314                 vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
2315         } else if (state == VDEV_STATE_REMOVED) {
2316                 /*
2317                  * Indicate to the ZFS DE that this device has been removed, and
2318                  * any recent errors should be ignored.
2319                  */
2320                 zfs_post_remove(spa, vd);
2321                 vd->vdev_removed = B_TRUE;
2322         } else if (state == VDEV_STATE_CANT_OPEN) {
2323                 /*
2324                  * If we fail to open a vdev during an import, we mark it as
2325                  * "not available", which signifies that it was never there to
2326                  * begin with.  Failure to open such a device is not considered
2327                  * an error.
2328                  */
2329                 if (spa->spa_load_state == SPA_LOAD_IMPORT &&
2330                     !spa->spa_import_faulted &&
2331                     vd->vdev_ops->vdev_op_leaf)
2332                         vd->vdev_not_present = 1;
2333
2334                 /*
2335                  * Post the appropriate ereport.  If the 'prevstate' field is
2336                  * set to something other than VDEV_STATE_UNKNOWN, it indicates
2337                  * that this is part of a vdev_reopen().  In this case, we don't
2338                  * want to post the ereport if the device was already in the
2339                  * CANT_OPEN state beforehand.
2340                  *
2341                  * If the 'checkremove' flag is set, then this is an attempt to
2342                  * online the device in response to an insertion event.  If we
2343                  * hit this case, then we have detected an insertion event for a
2344                  * faulted or offline device that wasn't in the removed state.
2345                  * In this scenario, we don't post an ereport because we are
2346                  * about to replace the device, or attempt an online with
2347                  * vdev_forcefault, which will generate the fault for us.
2348                  */
2349                 if ((vd->vdev_prevstate != state || vd->vdev_forcefault) &&
2350                     !vd->vdev_not_present && !vd->vdev_checkremove &&
2351                     vd != spa->spa_root_vdev) {
2352                         const char *class;
2353
2354                         switch (aux) {
2355                         case VDEV_AUX_OPEN_FAILED:
2356                                 class = FM_EREPORT_ZFS_DEVICE_OPEN_FAILED;
2357                                 break;
2358                         case VDEV_AUX_CORRUPT_DATA:
2359                                 class = FM_EREPORT_ZFS_DEVICE_CORRUPT_DATA;
2360                                 break;
2361                         case VDEV_AUX_NO_REPLICAS:
2362                                 class = FM_EREPORT_ZFS_DEVICE_NO_REPLICAS;
2363                                 break;
2364                         case VDEV_AUX_BAD_GUID_SUM:
2365                                 class = FM_EREPORT_ZFS_DEVICE_BAD_GUID_SUM;
2366                                 break;
2367                         case VDEV_AUX_TOO_SMALL:
2368                                 class = FM_EREPORT_ZFS_DEVICE_TOO_SMALL;
2369                                 break;
2370                         case VDEV_AUX_BAD_LABEL:
2371                                 class = FM_EREPORT_ZFS_DEVICE_BAD_LABEL;
2372                                 break;
2373                         case VDEV_AUX_IO_FAILURE:
2374                                 class = FM_EREPORT_ZFS_IO_FAILURE;
2375                                 break;
2376                         default:
2377                                 class = FM_EREPORT_ZFS_DEVICE_UNKNOWN;
2378                         }
2379
2380                         zfs_ereport_post(class, spa, vd, NULL, save_state, 0);
2381                 }
2382
2383                 /* Erase any notion of persistent removed state */
2384                 vd->vdev_removed = B_FALSE;
2385         } else {
2386                 vd->vdev_removed = B_FALSE;
2387         }
2388
2389         if (!isopen)
2390                 vdev_propagate_state(vd);
2391 }
2392
2393 /*
2394  * Check the vdev configuration to ensure that it's capable of supporting
2395  * a root pool.
2396  *
2397  * On Solaris, we do not support RAID-Z or partial configuration.  In
2398  * addition, only a single top-level vdev is allowed and none of the
2399  * leaves can be wholedisks.
2400  *
2401  * For FreeBSD, we can boot from any configuration. There is a
2402  * limitation that the boot filesystem must be either uncompressed or
2403  * compresses with lzjb compression but I'm not sure how to enforce
2404  * that here.
2405  */
2406 boolean_t
2407 vdev_is_bootable(vdev_t *vd)
2408 {
2409 #ifdef __FreeBSD_version
2410         return (B_TRUE);
2411 #else
2412         int c;
2413
2414         if (!vd->vdev_ops->vdev_op_leaf) {
2415                 char *vdev_type = vd->vdev_ops->vdev_op_type;
2416
2417                 if (strcmp(vdev_type, VDEV_TYPE_ROOT) == 0 &&
2418                     vd->vdev_children > 1) {
2419                         return (B_FALSE);
2420                 } else if (strcmp(vdev_type, VDEV_TYPE_RAIDZ) == 0 ||
2421                     strcmp(vdev_type, VDEV_TYPE_MISSING) == 0) {
2422                         return (B_FALSE);
2423                 }
2424         } else if (vd->vdev_wholedisk == 1) {
2425                 return (B_FALSE);
2426         }
2427
2428         for (c = 0; c < vd->vdev_children; c++) {
2429                 if (!vdev_is_bootable(vd->vdev_child[c]))
2430                         return (B_FALSE);
2431         }
2432         return (B_TRUE);
2433 #endif
2434 }