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