xref: /freebsd/stand/libsa/zfs/zfsimpl.c (revision 8bcb0991864975618c09697b1aca10683346d9f0)
1 /*-
2  * Copyright (c) 2007 Doug Rabson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 /*
31  *	Stand-alone ZFS file reader.
32  */
33 
34 #include <sys/endian.h>
35 #include <sys/stat.h>
36 #include <sys/stdint.h>
37 #include <sys/list.h>
38 #include <machine/_inttypes.h>
39 
40 #include "zfsimpl.h"
41 #include "zfssubr.c"
42 
43 
44 struct zfsmount {
45 	const spa_t	*spa;
46 	objset_phys_t	objset;
47 	uint64_t	rootobj;
48 };
49 static struct zfsmount zfsmount __unused;
50 
51 /*
52  * The indirect_child_t represents the vdev that we will read from, when we
53  * need to read all copies of the data (e.g. for scrub or reconstruction).
54  * For plain (non-mirror) top-level vdevs (i.e. is_vdev is not a mirror),
55  * ic_vdev is the same as is_vdev.  However, for mirror top-level vdevs,
56  * ic_vdev is a child of the mirror.
57  */
58 typedef struct indirect_child {
59 	void *ic_data;
60 	vdev_t *ic_vdev;
61 } indirect_child_t;
62 
63 /*
64  * The indirect_split_t represents one mapped segment of an i/o to the
65  * indirect vdev. For non-split (contiguously-mapped) blocks, there will be
66  * only one indirect_split_t, with is_split_offset==0 and is_size==io_size.
67  * For split blocks, there will be several of these.
68  */
69 typedef struct indirect_split {
70 	list_node_t is_node; /* link on iv_splits */
71 
72 	/*
73 	 * is_split_offset is the offset into the i/o.
74 	 * This is the sum of the previous splits' is_size's.
75 	 */
76 	uint64_t is_split_offset;
77 
78 	vdev_t *is_vdev; /* top-level vdev */
79 	uint64_t is_target_offset; /* offset on is_vdev */
80 	uint64_t is_size;
81 	int is_children; /* number of entries in is_child[] */
82 
83 	/*
84 	 * is_good_child is the child that we are currently using to
85 	 * attempt reconstruction.
86 	 */
87 	int is_good_child;
88 
89 	indirect_child_t is_child[1]; /* variable-length */
90 } indirect_split_t;
91 
92 /*
93  * The indirect_vsd_t is associated with each i/o to the indirect vdev.
94  * It is the "Vdev-Specific Data" in the zio_t's io_vsd.
95  */
96 typedef struct indirect_vsd {
97 	boolean_t iv_split_block;
98 	boolean_t iv_reconstruct;
99 
100 	list_t iv_splits; /* list of indirect_split_t's */
101 } indirect_vsd_t;
102 
103 /*
104  * List of all vdevs, chained through v_alllink.
105  */
106 static vdev_list_t zfs_vdevs;
107 
108 /*
109  * List of ZFS features supported for read
110  */
111 static const char *features_for_read[] = {
112 	"org.illumos:lz4_compress",
113 	"com.delphix:hole_birth",
114 	"com.delphix:extensible_dataset",
115 	"com.delphix:embedded_data",
116 	"org.open-zfs:large_blocks",
117 	"org.illumos:sha512",
118 	"org.illumos:skein",
119 	"org.zfsonlinux:large_dnode",
120 	"com.joyent:multi_vdev_crash_dump",
121 	"com.delphix:spacemap_histogram",
122 	"com.delphix:zpool_checkpoint",
123 	"com.delphix:spacemap_v2",
124 	"com.datto:encryption",
125 	"org.zfsonlinux:allocation_classes",
126 	"com.datto:resilver_defer",
127 	"com.delphix:device_removal",
128 	"com.delphix:obsolete_counts",
129 	"com.intel:allocation_classes",
130 	NULL
131 };
132 
133 /*
134  * List of all pools, chained through spa_link.
135  */
136 static spa_list_t zfs_pools;
137 
138 static const dnode_phys_t *dnode_cache_obj;
139 static uint64_t dnode_cache_bn;
140 static char *dnode_cache_buf;
141 static char *zap_scratch;
142 static char *zfs_temp_buf, *zfs_temp_end, *zfs_temp_ptr;
143 
144 #define	TEMP_SIZE	(1024 * 1024)
145 
146 static int zio_read(const spa_t *spa, const blkptr_t *bp, void *buf);
147 static int zfs_get_root(const spa_t *spa, uint64_t *objid);
148 static int zfs_rlookup(const spa_t *spa, uint64_t objnum, char *result);
149 static int zap_lookup(const spa_t *spa, const dnode_phys_t *dnode,
150     const char *name, uint64_t integer_size, uint64_t num_integers,
151     void *value);
152 static int objset_get_dnode(const spa_t *, const objset_phys_t *, uint64_t,
153     dnode_phys_t *);
154 static int dnode_read(const spa_t *, const dnode_phys_t *, off_t, void *,
155     size_t);
156 static int vdev_indirect_read(vdev_t *, const blkptr_t *, void *, off_t,
157     size_t);
158 static int vdev_mirror_read(vdev_t *, const blkptr_t *, void *, off_t, size_t);
159 vdev_indirect_mapping_t *vdev_indirect_mapping_open(spa_t *, objset_phys_t *,
160     uint64_t);
161 vdev_indirect_mapping_entry_phys_t *
162     vdev_indirect_mapping_duplicate_adjacent_entries(vdev_t *, uint64_t,
163     uint64_t, uint64_t *);
164 
165 static void
166 zfs_init(void)
167 {
168 	STAILQ_INIT(&zfs_vdevs);
169 	STAILQ_INIT(&zfs_pools);
170 
171 	zfs_temp_buf = malloc(TEMP_SIZE);
172 	zfs_temp_end = zfs_temp_buf + TEMP_SIZE;
173 	zfs_temp_ptr = zfs_temp_buf;
174 	dnode_cache_buf = malloc(SPA_MAXBLOCKSIZE);
175 	zap_scratch = malloc(SPA_MAXBLOCKSIZE);
176 
177 	zfs_init_crc();
178 }
179 
180 static void *
181 zfs_alloc(size_t size)
182 {
183 	char *ptr;
184 
185 	if (zfs_temp_ptr + size > zfs_temp_end) {
186 		panic("ZFS: out of temporary buffer space");
187 	}
188 	ptr = zfs_temp_ptr;
189 	zfs_temp_ptr += size;
190 
191 	return (ptr);
192 }
193 
194 static void
195 zfs_free(void *ptr, size_t size)
196 {
197 
198 	zfs_temp_ptr -= size;
199 	if (zfs_temp_ptr != ptr) {
200 		panic("ZFS: zfs_alloc()/zfs_free() mismatch");
201 	}
202 }
203 
204 static int
205 xdr_int(const unsigned char **xdr, int *ip)
206 {
207 	*ip = be32dec(*xdr);
208 	(*xdr) += 4;
209 	return (0);
210 }
211 
212 static int
213 xdr_u_int(const unsigned char **xdr, u_int *ip)
214 {
215 	*ip = be32dec(*xdr);
216 	(*xdr) += 4;
217 	return (0);
218 }
219 
220 static int
221 xdr_uint64_t(const unsigned char **xdr, uint64_t *lp)
222 {
223 	u_int hi, lo;
224 
225 	xdr_u_int(xdr, &hi);
226 	xdr_u_int(xdr, &lo);
227 	*lp = (((uint64_t)hi) << 32) | lo;
228 	return (0);
229 }
230 
231 static int
232 nvlist_find(const unsigned char *nvlist, const char *name, int type,
233     int *elementsp, void *valuep)
234 {
235 	const unsigned char *p, *pair;
236 	int junk;
237 	int encoded_size, decoded_size;
238 
239 	p = nvlist;
240 	xdr_int(&p, &junk);
241 	xdr_int(&p, &junk);
242 
243 	pair = p;
244 	xdr_int(&p, &encoded_size);
245 	xdr_int(&p, &decoded_size);
246 	while (encoded_size && decoded_size) {
247 		int namelen, pairtype, elements;
248 		const char *pairname;
249 
250 		xdr_int(&p, &namelen);
251 		pairname = (const char *)p;
252 		p += roundup(namelen, 4);
253 		xdr_int(&p, &pairtype);
254 
255 		if (memcmp(name, pairname, namelen) == 0 && type == pairtype) {
256 			xdr_int(&p, &elements);
257 			if (elementsp)
258 				*elementsp = elements;
259 			if (type == DATA_TYPE_UINT64) {
260 				xdr_uint64_t(&p, (uint64_t *)valuep);
261 				return (0);
262 			} else if (type == DATA_TYPE_STRING) {
263 				int len;
264 				xdr_int(&p, &len);
265 				(*(const char **)valuep) = (const char *)p;
266 				return (0);
267 			} else if (type == DATA_TYPE_NVLIST ||
268 			    type == DATA_TYPE_NVLIST_ARRAY) {
269 				(*(const unsigned char **)valuep) =
270 				    (const unsigned char *)p;
271 				return (0);
272 			} else {
273 				return (EIO);
274 			}
275 		} else {
276 			/*
277 			 * Not the pair we are looking for, skip to the
278 			 * next one.
279 			 */
280 			p = pair + encoded_size;
281 		}
282 
283 		pair = p;
284 		xdr_int(&p, &encoded_size);
285 		xdr_int(&p, &decoded_size);
286 	}
287 
288 	return (EIO);
289 }
290 
291 static int
292 nvlist_check_features_for_read(const unsigned char *nvlist)
293 {
294 	const unsigned char *p, *pair;
295 	int junk;
296 	int encoded_size, decoded_size;
297 	int rc;
298 
299 	rc = 0;
300 
301 	p = nvlist;
302 	xdr_int(&p, &junk);
303 	xdr_int(&p, &junk);
304 
305 	pair = p;
306 	xdr_int(&p, &encoded_size);
307 	xdr_int(&p, &decoded_size);
308 	while (encoded_size && decoded_size) {
309 		int namelen, pairtype;
310 		const char *pairname;
311 		int i, found;
312 
313 		found = 0;
314 
315 		xdr_int(&p, &namelen);
316 		pairname = (const char *)p;
317 		p += roundup(namelen, 4);
318 		xdr_int(&p, &pairtype);
319 
320 		for (i = 0; features_for_read[i] != NULL; i++) {
321 			if (memcmp(pairname, features_for_read[i],
322 			    namelen) == 0) {
323 				found = 1;
324 				break;
325 			}
326 		}
327 
328 		if (!found) {
329 			printf("ZFS: unsupported feature: %s\n", pairname);
330 			rc = EIO;
331 		}
332 
333 		p = pair + encoded_size;
334 
335 		pair = p;
336 		xdr_int(&p, &encoded_size);
337 		xdr_int(&p, &decoded_size);
338 	}
339 
340 	return (rc);
341 }
342 
343 /*
344  * Return the next nvlist in an nvlist array.
345  */
346 static const unsigned char *
347 nvlist_next(const unsigned char *nvlist)
348 {
349 	const unsigned char *p, *pair;
350 	int junk;
351 	int encoded_size, decoded_size;
352 
353 	p = nvlist;
354 	xdr_int(&p, &junk);
355 	xdr_int(&p, &junk);
356 
357 	pair = p;
358 	xdr_int(&p, &encoded_size);
359 	xdr_int(&p, &decoded_size);
360 	while (encoded_size && decoded_size) {
361 		p = pair + encoded_size;
362 
363 		pair = p;
364 		xdr_int(&p, &encoded_size);
365 		xdr_int(&p, &decoded_size);
366 	}
367 
368 	return (p);
369 }
370 
371 #ifdef TEST
372 
373 static const unsigned char *
374 nvlist_print(const unsigned char *nvlist, unsigned int indent)
375 {
376 	static const char *typenames[] = {
377 		"DATA_TYPE_UNKNOWN",
378 		"DATA_TYPE_BOOLEAN",
379 		"DATA_TYPE_BYTE",
380 		"DATA_TYPE_INT16",
381 		"DATA_TYPE_UINT16",
382 		"DATA_TYPE_INT32",
383 		"DATA_TYPE_UINT32",
384 		"DATA_TYPE_INT64",
385 		"DATA_TYPE_UINT64",
386 		"DATA_TYPE_STRING",
387 		"DATA_TYPE_BYTE_ARRAY",
388 		"DATA_TYPE_INT16_ARRAY",
389 		"DATA_TYPE_UINT16_ARRAY",
390 		"DATA_TYPE_INT32_ARRAY",
391 		"DATA_TYPE_UINT32_ARRAY",
392 		"DATA_TYPE_INT64_ARRAY",
393 		"DATA_TYPE_UINT64_ARRAY",
394 		"DATA_TYPE_STRING_ARRAY",
395 		"DATA_TYPE_HRTIME",
396 		"DATA_TYPE_NVLIST",
397 		"DATA_TYPE_NVLIST_ARRAY",
398 		"DATA_TYPE_BOOLEAN_VALUE",
399 		"DATA_TYPE_INT8",
400 		"DATA_TYPE_UINT8",
401 		"DATA_TYPE_BOOLEAN_ARRAY",
402 		"DATA_TYPE_INT8_ARRAY",
403 		"DATA_TYPE_UINT8_ARRAY"
404 	};
405 
406 	unsigned int i, j;
407 	const unsigned char *p, *pair;
408 	int junk;
409 	int encoded_size, decoded_size;
410 
411 	p = nvlist;
412 	xdr_int(&p, &junk);
413 	xdr_int(&p, &junk);
414 
415 	pair = p;
416 	xdr_int(&p, &encoded_size);
417 	xdr_int(&p, &decoded_size);
418 	while (encoded_size && decoded_size) {
419 		int namelen, pairtype, elements;
420 		const char *pairname;
421 
422 		xdr_int(&p, &namelen);
423 		pairname = (const char *)p;
424 		p += roundup(namelen, 4);
425 		xdr_int(&p, &pairtype);
426 
427 		for (i = 0; i < indent; i++)
428 			printf(" ");
429 		printf("%s %s", typenames[pairtype], pairname);
430 
431 		xdr_int(&p, &elements);
432 		switch (pairtype) {
433 		case DATA_TYPE_UINT64: {
434 			uint64_t val;
435 			xdr_uint64_t(&p, &val);
436 			printf(" = 0x%jx\n", (uintmax_t)val);
437 			break;
438 		}
439 
440 		case DATA_TYPE_STRING: {
441 			int len;
442 			xdr_int(&p, &len);
443 			printf(" = \"%s\"\n", p);
444 			break;
445 		}
446 
447 		case DATA_TYPE_NVLIST:
448 			printf("\n");
449 			nvlist_print(p, indent + 1);
450 			break;
451 
452 		case DATA_TYPE_NVLIST_ARRAY:
453 			for (j = 0; j < elements; j++) {
454 				printf("[%d]\n", j);
455 				p = nvlist_print(p, indent + 1);
456 				if (j != elements - 1) {
457 					for (i = 0; i < indent; i++)
458 						printf(" ");
459 					printf("%s %s", typenames[pairtype],
460 					    pairname);
461 				}
462 			}
463 			break;
464 
465 		default:
466 			printf("\n");
467 		}
468 
469 		p = pair + encoded_size;
470 
471 		pair = p;
472 		xdr_int(&p, &encoded_size);
473 		xdr_int(&p, &decoded_size);
474 	}
475 
476 	return (p);
477 }
478 
479 #endif
480 
481 static int
482 vdev_read_phys(vdev_t *vdev, const blkptr_t *bp, void *buf,
483     off_t offset, size_t size)
484 {
485 	size_t psize;
486 	int rc;
487 
488 	if (!vdev->v_phys_read)
489 		return (EIO);
490 
491 	if (bp) {
492 		psize = BP_GET_PSIZE(bp);
493 	} else {
494 		psize = size;
495 	}
496 
497 	rc = vdev->v_phys_read(vdev, vdev->v_read_priv, offset, buf, psize);
498 	if (rc == 0) {
499 		if (bp != NULL)
500 			rc = zio_checksum_verify(vdev->v_spa, bp, buf);
501 	}
502 
503 	return (rc);
504 }
505 
506 typedef struct remap_segment {
507 	vdev_t *rs_vd;
508 	uint64_t rs_offset;
509 	uint64_t rs_asize;
510 	uint64_t rs_split_offset;
511 	list_node_t rs_node;
512 } remap_segment_t;
513 
514 static remap_segment_t *
515 rs_alloc(vdev_t *vd, uint64_t offset, uint64_t asize, uint64_t split_offset)
516 {
517 	remap_segment_t *rs = malloc(sizeof (remap_segment_t));
518 
519 	if (rs != NULL) {
520 		rs->rs_vd = vd;
521 		rs->rs_offset = offset;
522 		rs->rs_asize = asize;
523 		rs->rs_split_offset = split_offset;
524 	}
525 
526 	return (rs);
527 }
528 
529 vdev_indirect_mapping_t *
530 vdev_indirect_mapping_open(spa_t *spa, objset_phys_t *os,
531     uint64_t mapping_object)
532 {
533 	vdev_indirect_mapping_t *vim;
534 	vdev_indirect_mapping_phys_t *vim_phys;
535 	int rc;
536 
537 	vim = calloc(1, sizeof (*vim));
538 	if (vim == NULL)
539 		return (NULL);
540 
541 	vim->vim_dn = calloc(1, sizeof (*vim->vim_dn));
542 	if (vim->vim_dn == NULL) {
543 		free(vim);
544 		return (NULL);
545 	}
546 
547 	rc = objset_get_dnode(spa, os, mapping_object, vim->vim_dn);
548 	if (rc != 0) {
549 		free(vim->vim_dn);
550 		free(vim);
551 		return (NULL);
552 	}
553 
554 	vim->vim_spa = spa;
555 	vim->vim_phys = malloc(sizeof (*vim->vim_phys));
556 	if (vim->vim_phys == NULL) {
557 		free(vim->vim_dn);
558 		free(vim);
559 		return (NULL);
560 	}
561 
562 	vim_phys = (vdev_indirect_mapping_phys_t *)DN_BONUS(vim->vim_dn);
563 	*vim->vim_phys = *vim_phys;
564 
565 	vim->vim_objset = os;
566 	vim->vim_object = mapping_object;
567 	vim->vim_entries = NULL;
568 
569 	vim->vim_havecounts =
570 	    (vim->vim_dn->dn_bonuslen > VDEV_INDIRECT_MAPPING_SIZE_V0);
571 
572 	return (vim);
573 }
574 
575 /*
576  * Compare an offset with an indirect mapping entry; there are three
577  * possible scenarios:
578  *
579  *     1. The offset is "less than" the mapping entry; meaning the
580  *        offset is less than the source offset of the mapping entry. In
581  *        this case, there is no overlap between the offset and the
582  *        mapping entry and -1 will be returned.
583  *
584  *     2. The offset is "greater than" the mapping entry; meaning the
585  *        offset is greater than the mapping entry's source offset plus
586  *        the entry's size. In this case, there is no overlap between
587  *        the offset and the mapping entry and 1 will be returned.
588  *
589  *        NOTE: If the offset is actually equal to the entry's offset
590  *        plus size, this is considered to be "greater" than the entry,
591  *        and this case applies (i.e. 1 will be returned). Thus, the
592  *        entry's "range" can be considered to be inclusive at its
593  *        start, but exclusive at its end: e.g. [src, src + size).
594  *
595  *     3. The last case to consider is if the offset actually falls
596  *        within the mapping entry's range. If this is the case, the
597  *        offset is considered to be "equal to" the mapping entry and
598  *        0 will be returned.
599  *
600  *        NOTE: If the offset is equal to the entry's source offset,
601  *        this case applies and 0 will be returned. If the offset is
602  *        equal to the entry's source plus its size, this case does
603  *        *not* apply (see "NOTE" above for scenario 2), and 1 will be
604  *        returned.
605  */
606 static int
607 dva_mapping_overlap_compare(const void *v_key, const void *v_array_elem)
608 {
609 	const uint64_t *key = v_key;
610 	const vdev_indirect_mapping_entry_phys_t *array_elem =
611 	    v_array_elem;
612 	uint64_t src_offset = DVA_MAPPING_GET_SRC_OFFSET(array_elem);
613 
614 	if (*key < src_offset) {
615 		return (-1);
616 	} else if (*key < src_offset + DVA_GET_ASIZE(&array_elem->vimep_dst)) {
617 		return (0);
618 	} else {
619 		return (1);
620 	}
621 }
622 
623 /*
624  * Return array entry.
625  */
626 static vdev_indirect_mapping_entry_phys_t *
627 vdev_indirect_mapping_entry(vdev_indirect_mapping_t *vim, uint64_t index)
628 {
629 	uint64_t size;
630 	off_t offset = 0;
631 	int rc;
632 
633 	if (vim->vim_phys->vimp_num_entries == 0)
634 		return (NULL);
635 
636 	if (vim->vim_entries == NULL) {
637 		uint64_t bsize;
638 
639 		bsize = vim->vim_dn->dn_datablkszsec << SPA_MINBLOCKSHIFT;
640 		size = vim->vim_phys->vimp_num_entries *
641 		    sizeof (*vim->vim_entries);
642 		if (size > bsize) {
643 			size = bsize / sizeof (*vim->vim_entries);
644 			size *= sizeof (*vim->vim_entries);
645 		}
646 		vim->vim_entries = malloc(size);
647 		if (vim->vim_entries == NULL)
648 			return (NULL);
649 		vim->vim_num_entries = size / sizeof (*vim->vim_entries);
650 		offset = index * sizeof (*vim->vim_entries);
651 	}
652 
653 	/* We have data in vim_entries */
654 	if (offset == 0) {
655 		if (index >= vim->vim_entry_offset &&
656 		    index <= vim->vim_entry_offset + vim->vim_num_entries) {
657 			index -= vim->vim_entry_offset;
658 			return (&vim->vim_entries[index]);
659 		}
660 		offset = index * sizeof (*vim->vim_entries);
661 	}
662 
663 	vim->vim_entry_offset = index;
664 	size = vim->vim_num_entries * sizeof (*vim->vim_entries);
665 	rc = dnode_read(vim->vim_spa, vim->vim_dn, offset, vim->vim_entries,
666 	    size);
667 	if (rc != 0) {
668 		/* Read error, invalidate vim_entries. */
669 		free(vim->vim_entries);
670 		vim->vim_entries = NULL;
671 		return (NULL);
672 	}
673 	index -= vim->vim_entry_offset;
674 	return (&vim->vim_entries[index]);
675 }
676 
677 /*
678  * Returns the mapping entry for the given offset.
679  *
680  * It's possible that the given offset will not be in the mapping table
681  * (i.e. no mapping entries contain this offset), in which case, the
682  * return value value depends on the "next_if_missing" parameter.
683  *
684  * If the offset is not found in the table and "next_if_missing" is
685  * B_FALSE, then NULL will always be returned. The behavior is intended
686  * to allow consumers to get the entry corresponding to the offset
687  * parameter, iff the offset overlaps with an entry in the table.
688  *
689  * If the offset is not found in the table and "next_if_missing" is
690  * B_TRUE, then the entry nearest to the given offset will be returned,
691  * such that the entry's source offset is greater than the offset
692  * passed in (i.e. the "next" mapping entry in the table is returned, if
693  * the offset is missing from the table). If there are no entries whose
694  * source offset is greater than the passed in offset, NULL is returned.
695  */
696 static vdev_indirect_mapping_entry_phys_t *
697 vdev_indirect_mapping_entry_for_offset(vdev_indirect_mapping_t *vim,
698     uint64_t offset)
699 {
700 	ASSERT(vim->vim_phys->vimp_num_entries > 0);
701 
702 	vdev_indirect_mapping_entry_phys_t *entry;
703 
704 	uint64_t last = vim->vim_phys->vimp_num_entries - 1;
705 	uint64_t base = 0;
706 
707 	/*
708 	 * We don't define these inside of the while loop because we use
709 	 * their value in the case that offset isn't in the mapping.
710 	 */
711 	uint64_t mid;
712 	int result;
713 
714 	while (last >= base) {
715 		mid = base + ((last - base) >> 1);
716 
717 		entry = vdev_indirect_mapping_entry(vim, mid);
718 		if (entry == NULL)
719 			break;
720 		result = dva_mapping_overlap_compare(&offset, entry);
721 
722 		if (result == 0) {
723 			break;
724 		} else if (result < 0) {
725 			last = mid - 1;
726 		} else {
727 			base = mid + 1;
728 		}
729 	}
730 	return (entry);
731 }
732 
733 /*
734  * Given an indirect vdev and an extent on that vdev, it duplicates the
735  * physical entries of the indirect mapping that correspond to the extent
736  * to a new array and returns a pointer to it. In addition, copied_entries
737  * is populated with the number of mapping entries that were duplicated.
738  *
739  * Finally, since we are doing an allocation, it is up to the caller to
740  * free the array allocated in this function.
741  */
742 vdev_indirect_mapping_entry_phys_t *
743 vdev_indirect_mapping_duplicate_adjacent_entries(vdev_t *vd, uint64_t offset,
744     uint64_t asize, uint64_t *copied_entries)
745 {
746 	vdev_indirect_mapping_entry_phys_t *duplicate_mappings = NULL;
747 	vdev_indirect_mapping_t *vim = vd->v_mapping;
748 	uint64_t entries = 0;
749 
750 	vdev_indirect_mapping_entry_phys_t *first_mapping =
751 	    vdev_indirect_mapping_entry_for_offset(vim, offset);
752 	ASSERT3P(first_mapping, !=, NULL);
753 
754 	vdev_indirect_mapping_entry_phys_t *m = first_mapping;
755 	while (asize > 0) {
756 		uint64_t size = DVA_GET_ASIZE(&m->vimep_dst);
757 		uint64_t inner_offset = offset - DVA_MAPPING_GET_SRC_OFFSET(m);
758 		uint64_t inner_size = MIN(asize, size - inner_offset);
759 
760 		offset += inner_size;
761 		asize -= inner_size;
762 		entries++;
763 		m++;
764 	}
765 
766 	size_t copy_length = entries * sizeof (*first_mapping);
767 	duplicate_mappings = malloc(copy_length);
768 	if (duplicate_mappings != NULL)
769 		bcopy(first_mapping, duplicate_mappings, copy_length);
770 	else
771 		entries = 0;
772 
773 	*copied_entries = entries;
774 
775 	return (duplicate_mappings);
776 }
777 
778 static vdev_t *
779 vdev_lookup_top(spa_t *spa, uint64_t vdev)
780 {
781 	vdev_t *rvd;
782 	vdev_list_t *vlist;
783 
784 	vlist = &spa->spa_root_vdev->v_children;
785 	STAILQ_FOREACH(rvd, vlist, v_childlink)
786 		if (rvd->v_id == vdev)
787 			break;
788 
789 	return (rvd);
790 }
791 
792 /*
793  * This is a callback for vdev_indirect_remap() which allocates an
794  * indirect_split_t for each split segment and adds it to iv_splits.
795  */
796 static void
797 vdev_indirect_gather_splits(uint64_t split_offset, vdev_t *vd, uint64_t offset,
798     uint64_t size, void *arg)
799 {
800 	int n = 1;
801 	zio_t *zio = arg;
802 	indirect_vsd_t *iv = zio->io_vsd;
803 
804 	if (vd->v_read == vdev_indirect_read)
805 		return;
806 
807 	if (vd->v_read == vdev_mirror_read)
808 		n = vd->v_nchildren;
809 
810 	indirect_split_t *is =
811 	    malloc(offsetof(indirect_split_t, is_child[n]));
812 	if (is == NULL) {
813 		zio->io_error = ENOMEM;
814 		return;
815 	}
816 	bzero(is, offsetof(indirect_split_t, is_child[n]));
817 
818 	is->is_children = n;
819 	is->is_size = size;
820 	is->is_split_offset = split_offset;
821 	is->is_target_offset = offset;
822 	is->is_vdev = vd;
823 
824 	/*
825 	 * Note that we only consider multiple copies of the data for
826 	 * *mirror* vdevs.  We don't for "replacing" or "spare" vdevs, even
827 	 * though they use the same ops as mirror, because there's only one
828 	 * "good" copy under the replacing/spare.
829 	 */
830 	if (vd->v_read == vdev_mirror_read) {
831 		int i = 0;
832 		vdev_t *kid;
833 
834 		STAILQ_FOREACH(kid, &vd->v_children, v_childlink) {
835 			is->is_child[i++].ic_vdev = kid;
836 		}
837 	} else {
838 		is->is_child[0].ic_vdev = vd;
839 	}
840 
841 	list_insert_tail(&iv->iv_splits, is);
842 }
843 
844 static void
845 vdev_indirect_remap(vdev_t *vd, uint64_t offset, uint64_t asize, void *arg)
846 {
847 	list_t stack;
848 	spa_t *spa = vd->v_spa;
849 	zio_t *zio = arg;
850 	remap_segment_t *rs;
851 
852 	list_create(&stack, sizeof (remap_segment_t),
853 	    offsetof(remap_segment_t, rs_node));
854 
855 	rs = rs_alloc(vd, offset, asize, 0);
856 	if (rs == NULL) {
857 		printf("vdev_indirect_remap: out of memory.\n");
858 		zio->io_error = ENOMEM;
859 	}
860 	for (; rs != NULL; rs = list_remove_head(&stack)) {
861 		vdev_t *v = rs->rs_vd;
862 		uint64_t num_entries = 0;
863 		/* vdev_indirect_mapping_t *vim = v->v_mapping; */
864 		vdev_indirect_mapping_entry_phys_t *mapping =
865 		    vdev_indirect_mapping_duplicate_adjacent_entries(v,
866 		    rs->rs_offset, rs->rs_asize, &num_entries);
867 
868 		if (num_entries == 0)
869 			zio->io_error = ENOMEM;
870 
871 		for (uint64_t i = 0; i < num_entries; i++) {
872 			vdev_indirect_mapping_entry_phys_t *m = &mapping[i];
873 			uint64_t size = DVA_GET_ASIZE(&m->vimep_dst);
874 			uint64_t dst_offset = DVA_GET_OFFSET(&m->vimep_dst);
875 			uint64_t dst_vdev = DVA_GET_VDEV(&m->vimep_dst);
876 			uint64_t inner_offset = rs->rs_offset -
877 			    DVA_MAPPING_GET_SRC_OFFSET(m);
878 			uint64_t inner_size =
879 			    MIN(rs->rs_asize, size - inner_offset);
880 			vdev_t *dst_v = vdev_lookup_top(spa, dst_vdev);
881 
882 			if (dst_v->v_read == vdev_indirect_read) {
883 				remap_segment_t *o;
884 
885 				o = rs_alloc(dst_v, dst_offset + inner_offset,
886 				    inner_size, rs->rs_split_offset);
887 				if (o == NULL) {
888 					printf("vdev_indirect_remap: "
889 					    "out of memory.\n");
890 					zio->io_error = ENOMEM;
891 					break;
892 				}
893 
894 				list_insert_head(&stack, o);
895 			}
896 			vdev_indirect_gather_splits(rs->rs_split_offset, dst_v,
897 			    dst_offset + inner_offset,
898 			    inner_size, arg);
899 
900 			/*
901 			 * vdev_indirect_gather_splits can have memory
902 			 * allocation error, we can not recover from it.
903 			 */
904 			if (zio->io_error != 0)
905 				break;
906 			rs->rs_offset += inner_size;
907 			rs->rs_asize -= inner_size;
908 			rs->rs_split_offset += inner_size;
909 		}
910 
911 		free(mapping);
912 		free(rs);
913 		if (zio->io_error != 0)
914 			break;
915 	}
916 
917 	list_destroy(&stack);
918 }
919 
920 static void
921 vdev_indirect_map_free(zio_t *zio)
922 {
923 	indirect_vsd_t *iv = zio->io_vsd;
924 	indirect_split_t *is;
925 
926 	while ((is = list_head(&iv->iv_splits)) != NULL) {
927 		for (int c = 0; c < is->is_children; c++) {
928 			indirect_child_t *ic = &is->is_child[c];
929 			free(ic->ic_data);
930 		}
931 		list_remove(&iv->iv_splits, is);
932 		free(is);
933 	}
934 	free(iv);
935 }
936 
937 static int
938 vdev_indirect_read(vdev_t *vdev, const blkptr_t *bp, void *buf,
939     off_t offset, size_t bytes)
940 {
941 	zio_t zio;
942 	spa_t *spa = vdev->v_spa;
943 	indirect_vsd_t *iv;
944 	indirect_split_t *first;
945 	int rc = EIO;
946 
947 	iv = calloc(1, sizeof(*iv));
948 	if (iv == NULL)
949 		return (ENOMEM);
950 
951 	list_create(&iv->iv_splits,
952 	    sizeof (indirect_split_t), offsetof(indirect_split_t, is_node));
953 
954 	bzero(&zio, sizeof(zio));
955 	zio.io_spa = spa;
956 	zio.io_bp = (blkptr_t *)bp;
957 	zio.io_data = buf;
958 	zio.io_size = bytes;
959 	zio.io_offset = offset;
960 	zio.io_vd = vdev;
961 	zio.io_vsd = iv;
962 
963 	if (vdev->v_mapping == NULL) {
964 		vdev_indirect_config_t *vic;
965 
966 		vic = &vdev->vdev_indirect_config;
967 		vdev->v_mapping = vdev_indirect_mapping_open(spa,
968 		    &spa->spa_mos, vic->vic_mapping_object);
969 	}
970 
971 	vdev_indirect_remap(vdev, offset, bytes, &zio);
972 	if (zio.io_error != 0)
973 		return (zio.io_error);
974 
975 	first = list_head(&iv->iv_splits);
976 	if (first->is_size == zio.io_size) {
977 		/*
978 		 * This is not a split block; we are pointing to the entire
979 		 * data, which will checksum the same as the original data.
980 		 * Pass the BP down so that the child i/o can verify the
981 		 * checksum, and try a different location if available
982 		 * (e.g. on a mirror).
983 		 *
984 		 * While this special case could be handled the same as the
985 		 * general (split block) case, doing it this way ensures
986 		 * that the vast majority of blocks on indirect vdevs
987 		 * (which are not split) are handled identically to blocks
988 		 * on non-indirect vdevs.  This allows us to be less strict
989 		 * about performance in the general (but rare) case.
990 		 */
991 		rc = first->is_vdev->v_read(first->is_vdev, zio.io_bp,
992 		    zio.io_data, first->is_target_offset, bytes);
993 	} else {
994 		iv->iv_split_block = B_TRUE;
995 		/*
996 		 * Read one copy of each split segment, from the
997 		 * top-level vdev.  Since we don't know the
998 		 * checksum of each split individually, the child
999 		 * zio can't ensure that we get the right data.
1000 		 * E.g. if it's a mirror, it will just read from a
1001 		 * random (healthy) leaf vdev.  We have to verify
1002 		 * the checksum in vdev_indirect_io_done().
1003 		 */
1004 		for (indirect_split_t *is = list_head(&iv->iv_splits);
1005 		    is != NULL; is = list_next(&iv->iv_splits, is)) {
1006 			char *ptr = zio.io_data;
1007 
1008 			rc = is->is_vdev->v_read(is->is_vdev, zio.io_bp,
1009 			    ptr + is->is_split_offset, is->is_target_offset,
1010 			    is->is_size);
1011 		}
1012 		if (zio_checksum_verify(spa, zio.io_bp, zio.io_data))
1013 			rc = ECKSUM;
1014 		else
1015 			rc = 0;
1016 	}
1017 
1018 	vdev_indirect_map_free(&zio);
1019 	if (rc == 0)
1020 		rc = zio.io_error;
1021 
1022 	return (rc);
1023 }
1024 
1025 static int
1026 vdev_disk_read(vdev_t *vdev, const blkptr_t *bp, void *buf,
1027     off_t offset, size_t bytes)
1028 {
1029 
1030 	return (vdev_read_phys(vdev, bp, buf,
1031 	    offset + VDEV_LABEL_START_SIZE, bytes));
1032 }
1033 
1034 
1035 static int
1036 vdev_mirror_read(vdev_t *vdev, const blkptr_t *bp, void *buf,
1037     off_t offset, size_t bytes)
1038 {
1039 	vdev_t *kid;
1040 	int rc;
1041 
1042 	rc = EIO;
1043 	STAILQ_FOREACH(kid, &vdev->v_children, v_childlink) {
1044 		if (kid->v_state != VDEV_STATE_HEALTHY)
1045 			continue;
1046 		rc = kid->v_read(kid, bp, buf, offset, bytes);
1047 		if (!rc)
1048 			return (0);
1049 	}
1050 
1051 	return (rc);
1052 }
1053 
1054 static int
1055 vdev_replacing_read(vdev_t *vdev, const blkptr_t *bp, void *buf,
1056     off_t offset, size_t bytes)
1057 {
1058 	vdev_t *kid;
1059 
1060 	/*
1061 	 * Here we should have two kids:
1062 	 * First one which is the one we are replacing and we can trust
1063 	 * only this one to have valid data, but it might not be present.
1064 	 * Second one is that one we are replacing with. It is most likely
1065 	 * healthy, but we can't trust it has needed data, so we won't use it.
1066 	 */
1067 	kid = STAILQ_FIRST(&vdev->v_children);
1068 	if (kid == NULL)
1069 		return (EIO);
1070 	if (kid->v_state != VDEV_STATE_HEALTHY)
1071 		return (EIO);
1072 	return (kid->v_read(kid, bp, buf, offset, bytes));
1073 }
1074 
1075 static vdev_t *
1076 vdev_find(uint64_t guid)
1077 {
1078 	vdev_t *vdev;
1079 
1080 	STAILQ_FOREACH(vdev, &zfs_vdevs, v_alllink)
1081 		if (vdev->v_guid == guid)
1082 			return (vdev);
1083 
1084 	return (0);
1085 }
1086 
1087 static vdev_t *
1088 vdev_create(uint64_t guid, vdev_read_t *_read)
1089 {
1090 	vdev_t *vdev;
1091 	vdev_indirect_config_t *vic;
1092 
1093 	vdev = calloc(1, sizeof(vdev_t));
1094 	if (vdev != NULL) {
1095 		STAILQ_INIT(&vdev->v_children);
1096 		vdev->v_guid = guid;
1097 		vdev->v_read = _read;
1098 
1099 		/*
1100 		 * root vdev has no read function, we use this fact to
1101 		 * skip setting up data we do not need for root vdev.
1102 		 * We only point root vdev from spa.
1103 		 */
1104 		if (_read != NULL) {
1105 			vic = &vdev->vdev_indirect_config;
1106 			vic->vic_prev_indirect_vdev = UINT64_MAX;
1107 			STAILQ_INSERT_TAIL(&zfs_vdevs, vdev, v_alllink);
1108 		}
1109 	}
1110 
1111 	return (vdev);
1112 }
1113 
1114 static void
1115 vdev_set_initial_state(vdev_t *vdev, const unsigned char *nvlist)
1116 {
1117 	uint64_t is_offline, is_faulted, is_degraded, is_removed, isnt_present;
1118 	uint64_t is_log;
1119 
1120 	is_offline = is_removed = is_faulted = is_degraded = isnt_present = 0;
1121 	is_log = 0;
1122 	(void) nvlist_find(nvlist, ZPOOL_CONFIG_OFFLINE, DATA_TYPE_UINT64, NULL,
1123 	    &is_offline);
1124 	(void) nvlist_find(nvlist, ZPOOL_CONFIG_REMOVED, DATA_TYPE_UINT64, NULL,
1125 	    &is_removed);
1126 	(void) nvlist_find(nvlist, ZPOOL_CONFIG_FAULTED, DATA_TYPE_UINT64, NULL,
1127 	    &is_faulted);
1128 	(void) nvlist_find(nvlist, ZPOOL_CONFIG_DEGRADED, DATA_TYPE_UINT64,
1129 	    NULL, &is_degraded);
1130 	(void) nvlist_find(nvlist, ZPOOL_CONFIG_NOT_PRESENT, DATA_TYPE_UINT64,
1131 	    NULL, &isnt_present);
1132 	(void) nvlist_find(nvlist, ZPOOL_CONFIG_IS_LOG, DATA_TYPE_UINT64, NULL,
1133 	    &is_log);
1134 
1135 	if (is_offline != 0)
1136 		vdev->v_state = VDEV_STATE_OFFLINE;
1137 	else if (is_removed != 0)
1138 		vdev->v_state = VDEV_STATE_REMOVED;
1139 	else if (is_faulted != 0)
1140 		vdev->v_state = VDEV_STATE_FAULTED;
1141 	else if (is_degraded != 0)
1142 		vdev->v_state = VDEV_STATE_DEGRADED;
1143 	else if (isnt_present != 0)
1144 		vdev->v_state = VDEV_STATE_CANT_OPEN;
1145 
1146 	vdev->v_islog = is_log != 0;
1147 }
1148 
1149 static int
1150 vdev_init(uint64_t guid, const unsigned char *nvlist, vdev_t **vdevp)
1151 {
1152 	uint64_t id, ashift, asize, nparity;
1153 	const char *path;
1154 	const char *type;
1155 	vdev_t *vdev;
1156 
1157 	if (nvlist_find(nvlist, ZPOOL_CONFIG_ID, DATA_TYPE_UINT64, NULL, &id) ||
1158 	    nvlist_find(nvlist, ZPOOL_CONFIG_TYPE, DATA_TYPE_STRING,
1159 	    NULL, &type)) {
1160 		return (ENOENT);
1161 	}
1162 
1163 	if (strcmp(type, VDEV_TYPE_MIRROR) != 0 &&
1164 	    strcmp(type, VDEV_TYPE_DISK) != 0 &&
1165 #ifdef ZFS_TEST
1166 	    strcmp(type, VDEV_TYPE_FILE) != 0 &&
1167 #endif
1168 	    strcmp(type, VDEV_TYPE_RAIDZ) != 0 &&
1169 	    strcmp(type, VDEV_TYPE_INDIRECT) != 0 &&
1170 	    strcmp(type, VDEV_TYPE_REPLACING) != 0) {
1171 		printf("ZFS: can only boot from disk, mirror, raidz1, "
1172 		    "raidz2 and raidz3 vdevs\n");
1173 		return (EIO);
1174 	}
1175 
1176 	if (strcmp(type, VDEV_TYPE_MIRROR) == 0)
1177 		vdev = vdev_create(guid, vdev_mirror_read);
1178 	else if (strcmp(type, VDEV_TYPE_RAIDZ) == 0)
1179 		vdev = vdev_create(guid, vdev_raidz_read);
1180 	else if (strcmp(type, VDEV_TYPE_REPLACING) == 0)
1181 		vdev = vdev_create(guid, vdev_replacing_read);
1182 	else if (strcmp(type, VDEV_TYPE_INDIRECT) == 0) {
1183 		vdev_indirect_config_t *vic;
1184 
1185 		vdev = vdev_create(guid, vdev_indirect_read);
1186 		if (vdev != NULL) {
1187 			vdev->v_state = VDEV_STATE_HEALTHY;
1188 			vic = &vdev->vdev_indirect_config;
1189 
1190 			nvlist_find(nvlist,
1191 			    ZPOOL_CONFIG_INDIRECT_OBJECT,
1192 			    DATA_TYPE_UINT64,
1193 			    NULL, &vic->vic_mapping_object);
1194 			nvlist_find(nvlist,
1195 			    ZPOOL_CONFIG_INDIRECT_BIRTHS,
1196 			    DATA_TYPE_UINT64,
1197 			    NULL, &vic->vic_births_object);
1198 			nvlist_find(nvlist,
1199 			    ZPOOL_CONFIG_PREV_INDIRECT_VDEV,
1200 			    DATA_TYPE_UINT64,
1201 			    NULL, &vic->vic_prev_indirect_vdev);
1202 		}
1203 	} else {
1204 		vdev = vdev_create(guid, vdev_disk_read);
1205 	}
1206 
1207 	if (vdev == NULL)
1208 		return (ENOMEM);
1209 
1210 	vdev_set_initial_state(vdev, nvlist);
1211 	vdev->v_id = id;
1212 	if (nvlist_find(nvlist, ZPOOL_CONFIG_ASHIFT,
1213 	    DATA_TYPE_UINT64, NULL, &ashift) == 0)
1214 		vdev->v_ashift = ashift;
1215 
1216 	if (nvlist_find(nvlist, ZPOOL_CONFIG_ASIZE,
1217 	    DATA_TYPE_UINT64, NULL, &asize) == 0) {
1218 		vdev->v_psize = asize +
1219 		    VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE;
1220 	}
1221 
1222 	if (nvlist_find(nvlist, ZPOOL_CONFIG_NPARITY,
1223 	    DATA_TYPE_UINT64, NULL, &nparity) == 0)
1224 		vdev->v_nparity = nparity;
1225 
1226 	if (nvlist_find(nvlist, ZPOOL_CONFIG_PATH,
1227 	    DATA_TYPE_STRING, NULL, &path) == 0) {
1228 		if (strncmp(path, "/dev/", 5) == 0)
1229 			path += 5;
1230 		vdev->v_name = strdup(path);
1231 	} else {
1232 		char *name;
1233 
1234 		name = NULL;
1235 		if (strcmp(type, "raidz") == 0) {
1236 			if (vdev->v_nparity < 1 ||
1237 			    vdev->v_nparity > 3) {
1238 				printf("ZFS: invalid raidz parity: %d\n",
1239 				    vdev->v_nparity);
1240 				return (EIO);
1241 			}
1242 			(void) asprintf(&name, "%s%d-%" PRIu64, type,
1243 			    vdev->v_nparity, id);
1244 		} else {
1245 			(void) asprintf(&name, "%s-%" PRIu64, type, id);
1246 		}
1247 		vdev->v_name = name;
1248 	}
1249 	*vdevp = vdev;
1250 	return (0);
1251 }
1252 
1253 /*
1254  * Find slot for vdev. We return either NULL to signal to use
1255  * STAILQ_INSERT_HEAD, or we return link element to be used with
1256  * STAILQ_INSERT_AFTER.
1257  */
1258 static vdev_t *
1259 vdev_find_previous(vdev_t *top_vdev, vdev_t *vdev)
1260 {
1261 	vdev_t *v, *previous;
1262 
1263 	if (STAILQ_EMPTY(&top_vdev->v_children))
1264 		return (NULL);
1265 
1266 	previous = NULL;
1267 	STAILQ_FOREACH(v, &top_vdev->v_children, v_childlink) {
1268 		if (v->v_id > vdev->v_id)
1269 			return (previous);
1270 
1271 		if (v->v_id == vdev->v_id)
1272 			return (v);
1273 
1274 		if (v->v_id < vdev->v_id)
1275 			previous = v;
1276 	}
1277 	return (previous);
1278 }
1279 
1280 static size_t
1281 vdev_child_count(vdev_t *vdev)
1282 {
1283 	vdev_t *v;
1284 	size_t count;
1285 
1286 	count = 0;
1287 	STAILQ_FOREACH(v, &vdev->v_children, v_childlink) {
1288 		count++;
1289 	}
1290 	return (count);
1291 }
1292 
1293 /*
1294  * Insert vdev into top_vdev children list. List is ordered by v_id.
1295  */
1296 static void
1297 vdev_insert(vdev_t *top_vdev, vdev_t *vdev)
1298 {
1299 	vdev_t *previous;
1300 	size_t count;
1301 
1302 	/*
1303 	 * The top level vdev can appear in random order, depending how
1304 	 * the firmware is presenting the disk devices.
1305 	 * However, we will insert vdev to create list ordered by v_id,
1306 	 * so we can use either STAILQ_INSERT_HEAD or STAILQ_INSERT_AFTER
1307 	 * as STAILQ does not have insert before.
1308 	 */
1309 	previous = vdev_find_previous(top_vdev, vdev);
1310 
1311 	if (previous == NULL) {
1312 		STAILQ_INSERT_HEAD(&top_vdev->v_children, vdev, v_childlink);
1313 	} else if (previous->v_id == vdev->v_id) {
1314 		/*
1315 		 * This vdev was configured from label config,
1316 		 * do not insert duplicate.
1317 		 */
1318 		return;
1319 	} else {
1320 		STAILQ_INSERT_AFTER(&top_vdev->v_children, previous, vdev,
1321 		    v_childlink);
1322 	}
1323 
1324 	count = vdev_child_count(top_vdev);
1325 	if (top_vdev->v_nchildren < count)
1326 		top_vdev->v_nchildren = count;
1327 }
1328 
1329 static int
1330 vdev_from_nvlist(spa_t *spa, uint64_t top_guid, const unsigned char *nvlist)
1331 {
1332 	vdev_t *top_vdev, *vdev;
1333 	const unsigned char *kids;
1334 	int rc, nkids;
1335 
1336 	/* Get top vdev. */
1337 	top_vdev = vdev_find(top_guid);
1338 	if (top_vdev == NULL) {
1339 		rc = vdev_init(top_guid, nvlist, &top_vdev);
1340 		if (rc != 0)
1341 			return (rc);
1342 		top_vdev->v_spa = spa;
1343 		top_vdev->v_top = top_vdev;
1344 		vdev_insert(spa->spa_root_vdev, top_vdev);
1345 	}
1346 
1347 	/* Add children if there are any. */
1348 	rc = nvlist_find(nvlist, ZPOOL_CONFIG_CHILDREN, DATA_TYPE_NVLIST_ARRAY,
1349 	    &nkids, &kids);
1350 	if (rc == 0) {
1351 		for (int i = 0; i < nkids; i++) {
1352 			uint64_t guid;
1353 
1354 			rc = nvlist_find(kids, ZPOOL_CONFIG_GUID,
1355 			    DATA_TYPE_UINT64, NULL, &guid);
1356 			if (rc != 0)
1357 				return (rc);
1358 			rc = vdev_init(guid, kids, &vdev);
1359 			if (rc != 0)
1360 				return (rc);
1361 
1362 			vdev->v_spa = spa;
1363 			vdev->v_top = top_vdev;
1364 			vdev_insert(top_vdev, vdev);
1365 
1366 			kids = nvlist_next(kids);
1367 		}
1368 	} else {
1369 		/*
1370 		 * When there are no children, nvlist_find() does return
1371 		 * error, reset it because leaf devices have no children.
1372 		 */
1373 		rc = 0;
1374 	}
1375 
1376 	return (rc);
1377 }
1378 
1379 static int
1380 vdev_init_from_label(spa_t *spa, const unsigned char *nvlist)
1381 {
1382 	uint64_t pool_guid, top_guid;
1383 	const unsigned char *vdevs;
1384 
1385 	if (nvlist_find(nvlist, ZPOOL_CONFIG_POOL_GUID, DATA_TYPE_UINT64,
1386 	    NULL, &pool_guid) ||
1387 	    nvlist_find(nvlist, ZPOOL_CONFIG_TOP_GUID, DATA_TYPE_UINT64,
1388 	    NULL, &top_guid) ||
1389 	    nvlist_find(nvlist, ZPOOL_CONFIG_VDEV_TREE, DATA_TYPE_NVLIST,
1390 	    NULL, &vdevs)) {
1391 		printf("ZFS: can't find vdev details\n");
1392 		return (ENOENT);
1393 	}
1394 
1395 	return (vdev_from_nvlist(spa, top_guid, vdevs));
1396 }
1397 
1398 static void
1399 vdev_set_state(vdev_t *vdev)
1400 {
1401 	vdev_t *kid;
1402 	int good_kids;
1403 	int bad_kids;
1404 
1405 	STAILQ_FOREACH(kid, &vdev->v_children, v_childlink) {
1406 		vdev_set_state(kid);
1407 	}
1408 
1409 	/*
1410 	 * A mirror or raidz is healthy if all its kids are healthy. A
1411 	 * mirror is degraded if any of its kids is healthy; a raidz
1412 	 * is degraded if at most nparity kids are offline.
1413 	 */
1414 	if (STAILQ_FIRST(&vdev->v_children)) {
1415 		good_kids = 0;
1416 		bad_kids = 0;
1417 		STAILQ_FOREACH(kid, &vdev->v_children, v_childlink) {
1418 			if (kid->v_state == VDEV_STATE_HEALTHY)
1419 				good_kids++;
1420 			else
1421 				bad_kids++;
1422 		}
1423 		if (bad_kids == 0) {
1424 			vdev->v_state = VDEV_STATE_HEALTHY;
1425 		} else {
1426 			if (vdev->v_read == vdev_mirror_read) {
1427 				if (good_kids) {
1428 					vdev->v_state = VDEV_STATE_DEGRADED;
1429 				} else {
1430 					vdev->v_state = VDEV_STATE_OFFLINE;
1431 				}
1432 			} else if (vdev->v_read == vdev_raidz_read) {
1433 				if (bad_kids > vdev->v_nparity) {
1434 					vdev->v_state = VDEV_STATE_OFFLINE;
1435 				} else {
1436 					vdev->v_state = VDEV_STATE_DEGRADED;
1437 				}
1438 			}
1439 		}
1440 	}
1441 }
1442 
1443 static int
1444 vdev_update_from_nvlist(uint64_t top_guid, const unsigned char *nvlist)
1445 {
1446 	vdev_t *vdev;
1447 	const unsigned char *kids;
1448 	int rc, nkids;
1449 
1450 	/* Update top vdev. */
1451 	vdev = vdev_find(top_guid);
1452 	if (vdev != NULL)
1453 		vdev_set_initial_state(vdev, nvlist);
1454 
1455 	/* Update children if there are any. */
1456 	rc = nvlist_find(nvlist, ZPOOL_CONFIG_CHILDREN, DATA_TYPE_NVLIST_ARRAY,
1457 	    &nkids, &kids);
1458 	if (rc == 0) {
1459 		for (int i = 0; i < nkids; i++) {
1460 			uint64_t guid;
1461 
1462 			rc = nvlist_find(kids, ZPOOL_CONFIG_GUID,
1463 			    DATA_TYPE_UINT64, NULL, &guid);
1464 			if (rc != 0)
1465 				break;
1466 
1467 			vdev = vdev_find(guid);
1468 			if (vdev != NULL)
1469 				vdev_set_initial_state(vdev, kids);
1470 
1471 			kids = nvlist_next(kids);
1472 		}
1473 	} else {
1474 		rc = 0;
1475 	}
1476 
1477 	return (rc);
1478 }
1479 
1480 static int
1481 vdev_init_from_nvlist(spa_t *spa, const unsigned char *nvlist)
1482 {
1483 	uint64_t pool_guid, vdev_children;
1484 	const unsigned char *vdevs, *kids;
1485 	int rc, nkids;
1486 
1487 	if (nvlist_find(nvlist, ZPOOL_CONFIG_POOL_GUID, DATA_TYPE_UINT64,
1488 	    NULL, &pool_guid) ||
1489 	    nvlist_find(nvlist, ZPOOL_CONFIG_VDEV_CHILDREN, DATA_TYPE_UINT64,
1490 	    NULL, &vdev_children) ||
1491 	    nvlist_find(nvlist, ZPOOL_CONFIG_VDEV_TREE, DATA_TYPE_NVLIST,
1492 	    NULL, &vdevs)) {
1493 		printf("ZFS: can't find vdev details\n");
1494 		return (ENOENT);
1495 	}
1496 
1497 	/* Wrong guid?! */
1498 	if (spa->spa_guid != pool_guid)
1499 		return (EINVAL);
1500 
1501 	spa->spa_root_vdev->v_nchildren = vdev_children;
1502 
1503 	rc = nvlist_find(vdevs, ZPOOL_CONFIG_CHILDREN, DATA_TYPE_NVLIST_ARRAY,
1504 	    &nkids, &kids);
1505 
1506 	/*
1507 	 * MOS config has at least one child for root vdev.
1508 	 */
1509 	if (rc != 0)
1510 		return (rc);
1511 
1512 	for (int i = 0; i < nkids; i++) {
1513 		uint64_t guid;
1514 		vdev_t *vdev;
1515 
1516 		rc = nvlist_find(kids, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64,
1517 		    NULL, &guid);
1518 		if (rc != 0)
1519 			break;
1520 		vdev = vdev_find(guid);
1521 		/*
1522 		 * Top level vdev is missing, create it.
1523 		 */
1524 		if (vdev == NULL)
1525 			rc = vdev_from_nvlist(spa, guid, kids);
1526 		else
1527 			rc = vdev_update_from_nvlist(guid, kids);
1528 		if (rc != 0)
1529 			break;
1530 		kids = nvlist_next(kids);
1531 	}
1532 
1533 	/*
1534 	 * Re-evaluate top-level vdev state.
1535 	 */
1536 	vdev_set_state(spa->spa_root_vdev);
1537 
1538 	return (rc);
1539 }
1540 
1541 static spa_t *
1542 spa_find_by_guid(uint64_t guid)
1543 {
1544 	spa_t *spa;
1545 
1546 	STAILQ_FOREACH(spa, &zfs_pools, spa_link)
1547 		if (spa->spa_guid == guid)
1548 			return (spa);
1549 
1550 	return (NULL);
1551 }
1552 
1553 static spa_t *
1554 spa_find_by_name(const char *name)
1555 {
1556 	spa_t *spa;
1557 
1558 	STAILQ_FOREACH(spa, &zfs_pools, spa_link)
1559 		if (strcmp(spa->spa_name, name) == 0)
1560 			return (spa);
1561 
1562 	return (NULL);
1563 }
1564 
1565 #ifdef BOOT2
1566 static spa_t *
1567 spa_get_primary(void)
1568 {
1569 
1570 	return (STAILQ_FIRST(&zfs_pools));
1571 }
1572 
1573 static vdev_t *
1574 spa_get_primary_vdev(const spa_t *spa)
1575 {
1576 	vdev_t *vdev;
1577 	vdev_t *kid;
1578 
1579 	if (spa == NULL)
1580 		spa = spa_get_primary();
1581 	if (spa == NULL)
1582 		return (NULL);
1583 	vdev = spa->spa_root_vdev;
1584 	if (vdev == NULL)
1585 		return (NULL);
1586 	for (kid = STAILQ_FIRST(&vdev->v_children); kid != NULL;
1587 	    kid = STAILQ_FIRST(&vdev->v_children))
1588 		vdev = kid;
1589 	return (vdev);
1590 }
1591 #endif
1592 
1593 static spa_t *
1594 spa_create(uint64_t guid, const char *name)
1595 {
1596 	spa_t *spa;
1597 
1598 	if ((spa = calloc(1, sizeof(spa_t))) == NULL)
1599 		return (NULL);
1600 	if ((spa->spa_name = strdup(name)) == NULL) {
1601 		free(spa);
1602 		return (NULL);
1603 	}
1604 	spa->spa_guid = guid;
1605 	spa->spa_root_vdev = vdev_create(guid, NULL);
1606 	if (spa->spa_root_vdev == NULL) {
1607 		free(spa->spa_name);
1608 		free(spa);
1609 		return (NULL);
1610 	}
1611 	spa->spa_root_vdev->v_name = strdup("root");
1612 	STAILQ_INSERT_TAIL(&zfs_pools, spa, spa_link);
1613 
1614 	return (spa);
1615 }
1616 
1617 static const char *
1618 state_name(vdev_state_t state)
1619 {
1620 	static const char *names[] = {
1621 		"UNKNOWN",
1622 		"CLOSED",
1623 		"OFFLINE",
1624 		"REMOVED",
1625 		"CANT_OPEN",
1626 		"FAULTED",
1627 		"DEGRADED",
1628 		"ONLINE"
1629 	};
1630 	return (names[state]);
1631 }
1632 
1633 #ifdef BOOT2
1634 
1635 #define pager_printf printf
1636 
1637 #else
1638 
1639 static int
1640 pager_printf(const char *fmt, ...)
1641 {
1642 	char line[80];
1643 	va_list args;
1644 
1645 	va_start(args, fmt);
1646 	vsnprintf(line, sizeof(line), fmt, args);
1647 	va_end(args);
1648 	return (pager_output(line));
1649 }
1650 
1651 #endif
1652 
1653 #define	STATUS_FORMAT	"        %s %s\n"
1654 
1655 static int
1656 print_state(int indent, const char *name, vdev_state_t state)
1657 {
1658 	int i;
1659 	char buf[512];
1660 
1661 	buf[0] = 0;
1662 	for (i = 0; i < indent; i++)
1663 		strcat(buf, "  ");
1664 	strcat(buf, name);
1665 	return (pager_printf(STATUS_FORMAT, buf, state_name(state)));
1666 }
1667 
1668 static int
1669 vdev_status(vdev_t *vdev, int indent)
1670 {
1671 	vdev_t *kid;
1672 	int ret;
1673 
1674 	if (vdev->v_islog) {
1675 		(void) pager_output("        logs\n");
1676 		indent++;
1677 	}
1678 
1679 	ret = print_state(indent, vdev->v_name, vdev->v_state);
1680 	if (ret != 0)
1681 		return (ret);
1682 
1683 	STAILQ_FOREACH(kid, &vdev->v_children, v_childlink) {
1684 		ret = vdev_status(kid, indent + 1);
1685 		if (ret != 0)
1686 			return (ret);
1687 	}
1688 	return (ret);
1689 }
1690 
1691 static int
1692 spa_status(spa_t *spa)
1693 {
1694 	static char bootfs[ZFS_MAXNAMELEN];
1695 	uint64_t rootid;
1696 	vdev_list_t *vlist;
1697 	vdev_t *vdev;
1698 	int good_kids, bad_kids, degraded_kids, ret;
1699 	vdev_state_t state;
1700 
1701 	ret = pager_printf("  pool: %s\n", spa->spa_name);
1702 	if (ret != 0)
1703 		return (ret);
1704 
1705 	if (zfs_get_root(spa, &rootid) == 0 &&
1706 	    zfs_rlookup(spa, rootid, bootfs) == 0) {
1707 		if (bootfs[0] == '\0')
1708 			ret = pager_printf("bootfs: %s\n", spa->spa_name);
1709 		else
1710 			ret = pager_printf("bootfs: %s/%s\n", spa->spa_name,
1711 			    bootfs);
1712 		if (ret != 0)
1713 			return (ret);
1714 	}
1715 	ret = pager_printf("config:\n\n");
1716 	if (ret != 0)
1717 		return (ret);
1718 	ret = pager_printf(STATUS_FORMAT, "NAME", "STATE");
1719 	if (ret != 0)
1720 		return (ret);
1721 
1722 	good_kids = 0;
1723 	degraded_kids = 0;
1724 	bad_kids = 0;
1725 	vlist = &spa->spa_root_vdev->v_children;
1726 	STAILQ_FOREACH(vdev, vlist, v_childlink) {
1727 		if (vdev->v_state == VDEV_STATE_HEALTHY)
1728 			good_kids++;
1729 		else if (vdev->v_state == VDEV_STATE_DEGRADED)
1730 			degraded_kids++;
1731 		else
1732 			bad_kids++;
1733 	}
1734 
1735 	state = VDEV_STATE_CLOSED;
1736 	if (good_kids > 0 && (degraded_kids + bad_kids) == 0)
1737 		state = VDEV_STATE_HEALTHY;
1738 	else if ((good_kids + degraded_kids) > 0)
1739 		state = VDEV_STATE_DEGRADED;
1740 
1741 	ret = print_state(0, spa->spa_name, state);
1742 	if (ret != 0)
1743 		return (ret);
1744 
1745 	STAILQ_FOREACH(vdev, vlist, v_childlink) {
1746 		ret = vdev_status(vdev, 1);
1747 		if (ret != 0)
1748 			return (ret);
1749 	}
1750 	return (ret);
1751 }
1752 
1753 static int
1754 spa_all_status(void)
1755 {
1756 	spa_t *spa;
1757 	int first = 1, ret = 0;
1758 
1759 	STAILQ_FOREACH(spa, &zfs_pools, spa_link) {
1760 		if (!first) {
1761 			ret = pager_printf("\n");
1762 			if (ret != 0)
1763 				return (ret);
1764 		}
1765 		first = 0;
1766 		ret = spa_status(spa);
1767 		if (ret != 0)
1768 			return (ret);
1769 	}
1770 	return (ret);
1771 }
1772 
1773 static uint64_t
1774 vdev_label_offset(uint64_t psize, int l, uint64_t offset)
1775 {
1776 	uint64_t label_offset;
1777 
1778 	if (l < VDEV_LABELS / 2)
1779 		label_offset = 0;
1780 	else
1781 		label_offset = psize - VDEV_LABELS * sizeof (vdev_label_t);
1782 
1783 	return (offset + l * sizeof (vdev_label_t) + label_offset);
1784 }
1785 
1786 static int
1787 vdev_uberblock_compare(const uberblock_t *ub1, const uberblock_t *ub2)
1788 {
1789 	unsigned int seq1 = 0;
1790 	unsigned int seq2 = 0;
1791 	int cmp = AVL_CMP(ub1->ub_txg, ub2->ub_txg);
1792 
1793 	if (cmp != 0)
1794 		return (cmp);
1795 
1796 	cmp = AVL_CMP(ub1->ub_timestamp, ub2->ub_timestamp);
1797 	if (cmp != 0)
1798 		return (cmp);
1799 
1800 	if (MMP_VALID(ub1) && MMP_SEQ_VALID(ub1))
1801 		seq1 = MMP_SEQ(ub1);
1802 
1803 	if (MMP_VALID(ub2) && MMP_SEQ_VALID(ub2))
1804 		seq2 = MMP_SEQ(ub2);
1805 
1806 	return (AVL_CMP(seq1, seq2));
1807 }
1808 
1809 static int
1810 uberblock_verify(uberblock_t *ub)
1811 {
1812 	if (ub->ub_magic == BSWAP_64((uint64_t)UBERBLOCK_MAGIC)) {
1813 		byteswap_uint64_array(ub, sizeof (uberblock_t));
1814 	}
1815 
1816 	if (ub->ub_magic != UBERBLOCK_MAGIC ||
1817 	    !SPA_VERSION_IS_SUPPORTED(ub->ub_version))
1818 		return (EINVAL);
1819 
1820 	return (0);
1821 }
1822 
1823 static int
1824 vdev_label_read(vdev_t *vd, int l, void *buf, uint64_t offset,
1825     size_t size)
1826 {
1827 	blkptr_t bp;
1828 	off_t off;
1829 
1830 	off = vdev_label_offset(vd->v_psize, l, offset);
1831 
1832 	BP_ZERO(&bp);
1833 	BP_SET_LSIZE(&bp, size);
1834 	BP_SET_PSIZE(&bp, size);
1835 	BP_SET_CHECKSUM(&bp, ZIO_CHECKSUM_LABEL);
1836 	BP_SET_COMPRESS(&bp, ZIO_COMPRESS_OFF);
1837 	DVA_SET_OFFSET(BP_IDENTITY(&bp), off);
1838 	ZIO_SET_CHECKSUM(&bp.blk_cksum, off, 0, 0, 0);
1839 
1840 	return (vdev_read_phys(vd, &bp, buf, off, size));
1841 }
1842 
1843 static unsigned char *
1844 vdev_label_read_config(vdev_t *vd, uint64_t txg)
1845 {
1846 	vdev_phys_t *label;
1847 	uint64_t best_txg = 0;
1848 	uint64_t label_txg = 0;
1849 	uint64_t asize;
1850 	unsigned char *nvl;
1851 	size_t nvl_size;
1852 	int error;
1853 
1854 	label = malloc(sizeof (vdev_phys_t));
1855 	if (label == NULL)
1856 		return (NULL);
1857 
1858 	nvl_size = VDEV_PHYS_SIZE - sizeof (zio_eck_t) - 4;
1859 	nvl = malloc(nvl_size);
1860 	if (nvl == NULL)
1861 		goto done;
1862 
1863 	for (int l = 0; l < VDEV_LABELS; l++) {
1864 		const unsigned char *nvlist;
1865 
1866 		if (vdev_label_read(vd, l, label,
1867 		    offsetof(vdev_label_t, vl_vdev_phys),
1868 		    sizeof (vdev_phys_t)))
1869 			continue;
1870 
1871 		if (label->vp_nvlist[0] != NV_ENCODE_XDR)
1872 			continue;
1873 
1874 		nvlist = (const unsigned char *) label->vp_nvlist + 4;
1875 		error = nvlist_find(nvlist, ZPOOL_CONFIG_POOL_TXG,
1876 		    DATA_TYPE_UINT64, NULL, &label_txg);
1877 		if (error != 0 || label_txg == 0) {
1878 			memcpy(nvl, nvlist, nvl_size);
1879 			goto done;
1880 		}
1881 
1882 		if (label_txg <= txg && label_txg > best_txg) {
1883 			best_txg = label_txg;
1884 			memcpy(nvl, nvlist, nvl_size);
1885 
1886 			/*
1887 			 * Use asize from pool config. We need this
1888 			 * because we can get bad value from BIOS.
1889 			 */
1890 			if (nvlist_find(nvlist, ZPOOL_CONFIG_ASIZE,
1891 			    DATA_TYPE_UINT64, NULL, &asize) == 0) {
1892 				vd->v_psize = asize +
1893 				    VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE;
1894 			}
1895 		}
1896 	}
1897 
1898 	if (best_txg == 0) {
1899 		free(nvl);
1900 		nvl = NULL;
1901 	}
1902 done:
1903 	free(label);
1904 	return (nvl);
1905 }
1906 
1907 static void
1908 vdev_uberblock_load(vdev_t *vd, uberblock_t *ub)
1909 {
1910 	uberblock_t *buf;
1911 
1912 	buf = malloc(VDEV_UBERBLOCK_SIZE(vd));
1913 	if (buf == NULL)
1914 		return;
1915 
1916 	for (int l = 0; l < VDEV_LABELS; l++) {
1917 		for (int n = 0; n < VDEV_UBERBLOCK_COUNT(vd); n++) {
1918 			if (vdev_label_read(vd, l, buf,
1919 			    VDEV_UBERBLOCK_OFFSET(vd, n),
1920 			    VDEV_UBERBLOCK_SIZE(vd)))
1921 				continue;
1922 			if (uberblock_verify(buf) != 0)
1923 				continue;
1924 
1925 			if (vdev_uberblock_compare(buf, ub) > 0)
1926 				*ub = *buf;
1927 		}
1928 	}
1929 	free(buf);
1930 }
1931 
1932 static int
1933 vdev_probe(vdev_phys_read_t *_read, void *read_priv, spa_t **spap)
1934 {
1935 	vdev_t vtmp;
1936 	spa_t *spa;
1937 	vdev_t *vdev;
1938 	unsigned char *nvlist;
1939 	uint64_t val;
1940 	uint64_t guid, vdev_children;
1941 	uint64_t pool_txg, pool_guid;
1942 	const char *pool_name;
1943 	const unsigned char *features;
1944 	int rc;
1945 
1946 	/*
1947 	 * Load the vdev label and figure out which
1948 	 * uberblock is most current.
1949 	 */
1950 	memset(&vtmp, 0, sizeof(vtmp));
1951 	vtmp.v_phys_read = _read;
1952 	vtmp.v_read_priv = read_priv;
1953 	vtmp.v_psize = P2ALIGN(ldi_get_size(read_priv),
1954 	    (uint64_t)sizeof (vdev_label_t));
1955 
1956 	/* Test for minimum device size. */
1957 	if (vtmp.v_psize < SPA_MINDEVSIZE)
1958 		return (EIO);
1959 
1960 	nvlist = vdev_label_read_config(&vtmp, UINT64_MAX);
1961 	if (nvlist == NULL)
1962 		return (EIO);
1963 
1964 	if (nvlist_find(nvlist, ZPOOL_CONFIG_VERSION, DATA_TYPE_UINT64,
1965 	    NULL, &val) != 0) {
1966 		free(nvlist);
1967 		return (EIO);
1968 	}
1969 
1970 	if (!SPA_VERSION_IS_SUPPORTED(val)) {
1971 		printf("ZFS: unsupported ZFS version %u (should be %u)\n",
1972 		    (unsigned)val, (unsigned)SPA_VERSION);
1973 		free(nvlist);
1974 		return (EIO);
1975 	}
1976 
1977 	/* Check ZFS features for read */
1978 	if (nvlist_find(nvlist, ZPOOL_CONFIG_FEATURES_FOR_READ,
1979 	    DATA_TYPE_NVLIST, NULL, &features) == 0 &&
1980 	    nvlist_check_features_for_read(features) != 0) {
1981 		free(nvlist);
1982 		return (EIO);
1983 	}
1984 
1985 	if (nvlist_find(nvlist, ZPOOL_CONFIG_POOL_STATE, DATA_TYPE_UINT64,
1986 	    NULL, &val) != 0) {
1987 		free(nvlist);
1988 		return (EIO);
1989 	}
1990 
1991 	if (val == POOL_STATE_DESTROYED) {
1992 		/* We don't boot only from destroyed pools. */
1993 		free(nvlist);
1994 		return (EIO);
1995 	}
1996 
1997 	if (nvlist_find(nvlist, ZPOOL_CONFIG_POOL_TXG, DATA_TYPE_UINT64,
1998 	    NULL, &pool_txg) != 0 ||
1999 	    nvlist_find(nvlist, ZPOOL_CONFIG_POOL_GUID, DATA_TYPE_UINT64,
2000 	    NULL, &pool_guid) != 0 ||
2001 	    nvlist_find(nvlist, ZPOOL_CONFIG_POOL_NAME, DATA_TYPE_STRING,
2002 	    NULL, &pool_name) != 0) {
2003 		/*
2004 		 * Cache and spare devices end up here - just ignore
2005 		 * them.
2006 		 */
2007 		free(nvlist);
2008 		return (EIO);
2009 	}
2010 
2011 	/*
2012 	 * Create the pool if this is the first time we've seen it.
2013 	 */
2014 	spa = spa_find_by_guid(pool_guid);
2015 	if (spa == NULL) {
2016 		nvlist_find(nvlist, ZPOOL_CONFIG_VDEV_CHILDREN,
2017 		    DATA_TYPE_UINT64, NULL, &vdev_children);
2018 		spa = spa_create(pool_guid, pool_name);
2019 		if (spa == NULL) {
2020 			free(nvlist);
2021 			return (ENOMEM);
2022 		}
2023 		spa->spa_root_vdev->v_nchildren = vdev_children;
2024 	}
2025 	if (pool_txg > spa->spa_txg)
2026 		spa->spa_txg = pool_txg;
2027 
2028 	/*
2029 	 * Get the vdev tree and create our in-core copy of it.
2030 	 * If we already have a vdev with this guid, this must
2031 	 * be some kind of alias (overlapping slices, dangerously dedicated
2032 	 * disks etc).
2033 	 */
2034 	if (nvlist_find(nvlist, ZPOOL_CONFIG_GUID, DATA_TYPE_UINT64,
2035 	    NULL, &guid) != 0) {
2036 		free(nvlist);
2037 		return (EIO);
2038 	}
2039 	vdev = vdev_find(guid);
2040 	/* Has this vdev already been inited? */
2041 	if (vdev && vdev->v_phys_read) {
2042 		free(nvlist);
2043 		return (EIO);
2044 	}
2045 
2046 	rc = vdev_init_from_label(spa, nvlist);
2047 	free(nvlist);
2048 	if (rc != 0)
2049 		return (rc);
2050 
2051 	/*
2052 	 * We should already have created an incomplete vdev for this
2053 	 * vdev. Find it and initialise it with our read proc.
2054 	 */
2055 	vdev = vdev_find(guid);
2056 	if (vdev != NULL) {
2057 		vdev->v_phys_read = _read;
2058 		vdev->v_read_priv = read_priv;
2059 		vdev->v_psize = vtmp.v_psize;
2060 		/*
2061 		 * If no other state is set, mark vdev healthy.
2062 		 */
2063 		if (vdev->v_state == VDEV_STATE_UNKNOWN)
2064 			vdev->v_state = VDEV_STATE_HEALTHY;
2065 	} else {
2066 		printf("ZFS: inconsistent nvlist contents\n");
2067 		return (EIO);
2068 	}
2069 
2070 	if (vdev->v_islog)
2071 		spa->spa_with_log = vdev->v_islog;
2072 
2073 	/*
2074 	 * Re-evaluate top-level vdev state.
2075 	 */
2076 	vdev_set_state(vdev->v_top);
2077 
2078 	/*
2079 	 * Ok, we are happy with the pool so far. Lets find
2080 	 * the best uberblock and then we can actually access
2081 	 * the contents of the pool.
2082 	 */
2083 	vdev_uberblock_load(vdev, &spa->spa_uberblock);
2084 
2085 	if (spap != NULL)
2086 		*spap = spa;
2087 	return (0);
2088 }
2089 
2090 static int
2091 ilog2(int n)
2092 {
2093 	int v;
2094 
2095 	for (v = 0; v < 32; v++)
2096 		if (n == (1 << v))
2097 			return (v);
2098 	return (-1);
2099 }
2100 
2101 static int
2102 zio_read_gang(const spa_t *spa, const blkptr_t *bp, void *buf)
2103 {
2104 	blkptr_t gbh_bp;
2105 	zio_gbh_phys_t zio_gb;
2106 	char *pbuf;
2107 	int i;
2108 
2109 	/* Artificial BP for gang block header. */
2110 	gbh_bp = *bp;
2111 	BP_SET_PSIZE(&gbh_bp, SPA_GANGBLOCKSIZE);
2112 	BP_SET_LSIZE(&gbh_bp, SPA_GANGBLOCKSIZE);
2113 	BP_SET_CHECKSUM(&gbh_bp, ZIO_CHECKSUM_GANG_HEADER);
2114 	BP_SET_COMPRESS(&gbh_bp, ZIO_COMPRESS_OFF);
2115 	for (i = 0; i < SPA_DVAS_PER_BP; i++)
2116 		DVA_SET_GANG(&gbh_bp.blk_dva[i], 0);
2117 
2118 	/* Read gang header block using the artificial BP. */
2119 	if (zio_read(spa, &gbh_bp, &zio_gb))
2120 		return (EIO);
2121 
2122 	pbuf = buf;
2123 	for (i = 0; i < SPA_GBH_NBLKPTRS; i++) {
2124 		blkptr_t *gbp = &zio_gb.zg_blkptr[i];
2125 
2126 		if (BP_IS_HOLE(gbp))
2127 			continue;
2128 		if (zio_read(spa, gbp, pbuf))
2129 			return (EIO);
2130 		pbuf += BP_GET_PSIZE(gbp);
2131 	}
2132 
2133 	if (zio_checksum_verify(spa, bp, buf))
2134 		return (EIO);
2135 	return (0);
2136 }
2137 
2138 static int
2139 zio_read(const spa_t *spa, const blkptr_t *bp, void *buf)
2140 {
2141 	int cpfunc = BP_GET_COMPRESS(bp);
2142 	uint64_t align, size;
2143 	void *pbuf;
2144 	int i, error;
2145 
2146 	/*
2147 	 * Process data embedded in block pointer
2148 	 */
2149 	if (BP_IS_EMBEDDED(bp)) {
2150 		ASSERT(BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
2151 
2152 		size = BPE_GET_PSIZE(bp);
2153 		ASSERT(size <= BPE_PAYLOAD_SIZE);
2154 
2155 		if (cpfunc != ZIO_COMPRESS_OFF)
2156 			pbuf = zfs_alloc(size);
2157 		else
2158 			pbuf = buf;
2159 
2160 		decode_embedded_bp_compressed(bp, pbuf);
2161 		error = 0;
2162 
2163 		if (cpfunc != ZIO_COMPRESS_OFF) {
2164 			error = zio_decompress_data(cpfunc, pbuf,
2165 			    size, buf, BP_GET_LSIZE(bp));
2166 			zfs_free(pbuf, size);
2167 		}
2168 		if (error != 0)
2169 			printf("ZFS: i/o error - unable to decompress "
2170 			    "block pointer data, error %d\n", error);
2171 		return (error);
2172 	}
2173 
2174 	error = EIO;
2175 
2176 	for (i = 0; i < SPA_DVAS_PER_BP; i++) {
2177 		const dva_t *dva = &bp->blk_dva[i];
2178 		vdev_t *vdev;
2179 		vdev_list_t *vlist;
2180 		uint64_t vdevid;
2181 		off_t offset;
2182 
2183 		if (!dva->dva_word[0] && !dva->dva_word[1])
2184 			continue;
2185 
2186 		vdevid = DVA_GET_VDEV(dva);
2187 		offset = DVA_GET_OFFSET(dva);
2188 		vlist = &spa->spa_root_vdev->v_children;
2189 		STAILQ_FOREACH(vdev, vlist, v_childlink) {
2190 			if (vdev->v_id == vdevid)
2191 				break;
2192 		}
2193 		if (!vdev || !vdev->v_read)
2194 			continue;
2195 
2196 		size = BP_GET_PSIZE(bp);
2197 		if (vdev->v_read == vdev_raidz_read) {
2198 			align = 1ULL << vdev->v_ashift;
2199 			if (P2PHASE(size, align) != 0)
2200 				size = P2ROUNDUP(size, align);
2201 		}
2202 		if (size != BP_GET_PSIZE(bp) || cpfunc != ZIO_COMPRESS_OFF)
2203 			pbuf = zfs_alloc(size);
2204 		else
2205 			pbuf = buf;
2206 
2207 		if (DVA_GET_GANG(dva))
2208 			error = zio_read_gang(spa, bp, pbuf);
2209 		else
2210 			error = vdev->v_read(vdev, bp, pbuf, offset, size);
2211 		if (error == 0) {
2212 			if (cpfunc != ZIO_COMPRESS_OFF)
2213 				error = zio_decompress_data(cpfunc, pbuf,
2214 				    BP_GET_PSIZE(bp), buf, BP_GET_LSIZE(bp));
2215 			else if (size != BP_GET_PSIZE(bp))
2216 				bcopy(pbuf, buf, BP_GET_PSIZE(bp));
2217 		}
2218 		if (buf != pbuf)
2219 			zfs_free(pbuf, size);
2220 		if (error == 0)
2221 			break;
2222 	}
2223 	if (error != 0)
2224 		printf("ZFS: i/o error - all block copies unavailable\n");
2225 	return (error);
2226 }
2227 
2228 static int
2229 dnode_read(const spa_t *spa, const dnode_phys_t *dnode, off_t offset,
2230     void *buf, size_t buflen)
2231 {
2232 	int ibshift = dnode->dn_indblkshift - SPA_BLKPTRSHIFT;
2233 	int bsize = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
2234 	int nlevels = dnode->dn_nlevels;
2235 	int i, rc;
2236 
2237 	if (bsize > SPA_MAXBLOCKSIZE) {
2238 		printf("ZFS: I/O error - blocks larger than %llu are not "
2239 		    "supported\n", SPA_MAXBLOCKSIZE);
2240 		return (EIO);
2241 	}
2242 
2243 	/*
2244 	 * Note: bsize may not be a power of two here so we need to do an
2245 	 * actual divide rather than a bitshift.
2246 	 */
2247 	while (buflen > 0) {
2248 		uint64_t bn = offset / bsize;
2249 		int boff = offset % bsize;
2250 		int ibn;
2251 		const blkptr_t *indbp;
2252 		blkptr_t bp;
2253 
2254 		if (bn > dnode->dn_maxblkid)
2255 			return (EIO);
2256 
2257 		if (dnode == dnode_cache_obj && bn == dnode_cache_bn)
2258 			goto cached;
2259 
2260 		indbp = dnode->dn_blkptr;
2261 		for (i = 0; i < nlevels; i++) {
2262 			/*
2263 			 * Copy the bp from the indirect array so that
2264 			 * we can re-use the scratch buffer for multi-level
2265 			 * objects.
2266 			 */
2267 			ibn = bn >> ((nlevels - i - 1) * ibshift);
2268 			ibn &= ((1 << ibshift) - 1);
2269 			bp = indbp[ibn];
2270 			if (BP_IS_HOLE(&bp)) {
2271 				memset(dnode_cache_buf, 0, bsize);
2272 				break;
2273 			}
2274 			rc = zio_read(spa, &bp, dnode_cache_buf);
2275 			if (rc)
2276 				return (rc);
2277 			indbp = (const blkptr_t *) dnode_cache_buf;
2278 		}
2279 		dnode_cache_obj = dnode;
2280 		dnode_cache_bn = bn;
2281 	cached:
2282 
2283 		/*
2284 		 * The buffer contains our data block. Copy what we
2285 		 * need from it and loop.
2286 		 */
2287 		i = bsize - boff;
2288 		if (i > buflen) i = buflen;
2289 		memcpy(buf, &dnode_cache_buf[boff], i);
2290 		buf = ((char *)buf) + i;
2291 		offset += i;
2292 		buflen -= i;
2293 	}
2294 
2295 	return (0);
2296 }
2297 
2298 /*
2299  * Lookup a value in a microzap directory. Assumes that the zap
2300  * scratch buffer contains the directory contents.
2301  */
2302 static int
2303 mzap_lookup(const dnode_phys_t *dnode, const char *name, uint64_t *value)
2304 {
2305 	const mzap_phys_t *mz;
2306 	const mzap_ent_phys_t *mze;
2307 	size_t size;
2308 	int chunks, i;
2309 
2310 	/*
2311 	 * Microzap objects use exactly one block. Read the whole
2312 	 * thing.
2313 	 */
2314 	size = dnode->dn_datablkszsec * 512;
2315 
2316 	mz = (const mzap_phys_t *) zap_scratch;
2317 	chunks = size / MZAP_ENT_LEN - 1;
2318 
2319 	for (i = 0; i < chunks; i++) {
2320 		mze = &mz->mz_chunk[i];
2321 		if (strcmp(mze->mze_name, name) == 0) {
2322 			*value = mze->mze_value;
2323 			return (0);
2324 		}
2325 	}
2326 
2327 	return (ENOENT);
2328 }
2329 
2330 /*
2331  * Compare a name with a zap leaf entry. Return non-zero if the name
2332  * matches.
2333  */
2334 static int
2335 fzap_name_equal(const zap_leaf_t *zl, const zap_leaf_chunk_t *zc,
2336     const char *name)
2337 {
2338 	size_t namelen;
2339 	const zap_leaf_chunk_t *nc;
2340 	const char *p;
2341 
2342 	namelen = zc->l_entry.le_name_numints;
2343 
2344 	nc = &ZAP_LEAF_CHUNK(zl, zc->l_entry.le_name_chunk);
2345 	p = name;
2346 	while (namelen > 0) {
2347 		size_t len;
2348 
2349 		len = namelen;
2350 		if (len > ZAP_LEAF_ARRAY_BYTES)
2351 			len = ZAP_LEAF_ARRAY_BYTES;
2352 		if (memcmp(p, nc->l_array.la_array, len))
2353 			return (0);
2354 		p += len;
2355 		namelen -= len;
2356 		nc = &ZAP_LEAF_CHUNK(zl, nc->l_array.la_next);
2357 	}
2358 
2359 	return (1);
2360 }
2361 
2362 /*
2363  * Extract a uint64_t value from a zap leaf entry.
2364  */
2365 static uint64_t
2366 fzap_leaf_value(const zap_leaf_t *zl, const zap_leaf_chunk_t *zc)
2367 {
2368 	const zap_leaf_chunk_t *vc;
2369 	int i;
2370 	uint64_t value;
2371 	const uint8_t *p;
2372 
2373 	vc = &ZAP_LEAF_CHUNK(zl, zc->l_entry.le_value_chunk);
2374 	for (i = 0, value = 0, p = vc->l_array.la_array; i < 8; i++) {
2375 		value = (value << 8) | p[i];
2376 	}
2377 
2378 	return (value);
2379 }
2380 
2381 static void
2382 stv(int len, void *addr, uint64_t value)
2383 {
2384 	switch (len) {
2385 	case 1:
2386 		*(uint8_t *)addr = value;
2387 		return;
2388 	case 2:
2389 		*(uint16_t *)addr = value;
2390 		return;
2391 	case 4:
2392 		*(uint32_t *)addr = value;
2393 		return;
2394 	case 8:
2395 		*(uint64_t *)addr = value;
2396 		return;
2397 	}
2398 }
2399 
2400 /*
2401  * Extract a array from a zap leaf entry.
2402  */
2403 static void
2404 fzap_leaf_array(const zap_leaf_t *zl, const zap_leaf_chunk_t *zc,
2405     uint64_t integer_size, uint64_t num_integers, void *buf)
2406 {
2407 	uint64_t array_int_len = zc->l_entry.le_value_intlen;
2408 	uint64_t value = 0;
2409 	uint64_t *u64 = buf;
2410 	char *p = buf;
2411 	int len = MIN(zc->l_entry.le_value_numints, num_integers);
2412 	int chunk = zc->l_entry.le_value_chunk;
2413 	int byten = 0;
2414 
2415 	if (integer_size == 8 && len == 1) {
2416 		*u64 = fzap_leaf_value(zl, zc);
2417 		return;
2418 	}
2419 
2420 	while (len > 0) {
2421 		struct zap_leaf_array *la = &ZAP_LEAF_CHUNK(zl, chunk).l_array;
2422 		int i;
2423 
2424 		ASSERT3U(chunk, <, ZAP_LEAF_NUMCHUNKS(zl));
2425 		for (i = 0; i < ZAP_LEAF_ARRAY_BYTES && len > 0; i++) {
2426 			value = (value << 8) | la->la_array[i];
2427 			byten++;
2428 			if (byten == array_int_len) {
2429 				stv(integer_size, p, value);
2430 				byten = 0;
2431 				len--;
2432 				if (len == 0)
2433 					return;
2434 				p += integer_size;
2435 			}
2436 		}
2437 		chunk = la->la_next;
2438 	}
2439 }
2440 
2441 static int
2442 fzap_check_size(uint64_t integer_size, uint64_t num_integers)
2443 {
2444 
2445 	switch (integer_size) {
2446 	case 1:
2447 	case 2:
2448 	case 4:
2449 	case 8:
2450 		break;
2451 	default:
2452 		return (EINVAL);
2453 	}
2454 
2455 	if (integer_size * num_integers > ZAP_MAXVALUELEN)
2456 		return (E2BIG);
2457 
2458 	return (0);
2459 }
2460 
2461 /*
2462  * Lookup a value in a fatzap directory. Assumes that the zap scratch
2463  * buffer contains the directory header.
2464  */
2465 static int
2466 fzap_lookup(const spa_t *spa, const dnode_phys_t *dnode, const char *name,
2467     uint64_t integer_size, uint64_t num_integers, void *value)
2468 {
2469 	int bsize = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
2470 	zap_phys_t zh = *(zap_phys_t *)zap_scratch;
2471 	fat_zap_t z;
2472 	uint64_t *ptrtbl;
2473 	uint64_t hash;
2474 	int rc;
2475 
2476 	if (zh.zap_magic != ZAP_MAGIC)
2477 		return (EIO);
2478 
2479 	if ((rc = fzap_check_size(integer_size, num_integers)) != 0)
2480 		return (rc);
2481 
2482 	z.zap_block_shift = ilog2(bsize);
2483 	z.zap_phys = (zap_phys_t *)zap_scratch;
2484 
2485 	/*
2486 	 * Figure out where the pointer table is and read it in if necessary.
2487 	 */
2488 	if (zh.zap_ptrtbl.zt_blk) {
2489 		rc = dnode_read(spa, dnode, zh.zap_ptrtbl.zt_blk * bsize,
2490 		    zap_scratch, bsize);
2491 		if (rc)
2492 			return (rc);
2493 		ptrtbl = (uint64_t *)zap_scratch;
2494 	} else {
2495 		ptrtbl = &ZAP_EMBEDDED_PTRTBL_ENT(&z, 0);
2496 	}
2497 
2498 	hash = zap_hash(zh.zap_salt, name);
2499 
2500 	zap_leaf_t zl;
2501 	zl.l_bs = z.zap_block_shift;
2502 
2503 	off_t off = ptrtbl[hash >> (64 - zh.zap_ptrtbl.zt_shift)] << zl.l_bs;
2504 	zap_leaf_chunk_t *zc;
2505 
2506 	rc = dnode_read(spa, dnode, off, zap_scratch, bsize);
2507 	if (rc)
2508 		return (rc);
2509 
2510 	zl.l_phys = (zap_leaf_phys_t *)zap_scratch;
2511 
2512 	/*
2513 	 * Make sure this chunk matches our hash.
2514 	 */
2515 	if (zl.l_phys->l_hdr.lh_prefix_len > 0 &&
2516 	    zl.l_phys->l_hdr.lh_prefix !=
2517 	    hash >> (64 - zl.l_phys->l_hdr.lh_prefix_len))
2518 		return (ENOENT);
2519 
2520 	/*
2521 	 * Hash within the chunk to find our entry.
2522 	 */
2523 	int shift = (64 - ZAP_LEAF_HASH_SHIFT(&zl) -
2524 	    zl.l_phys->l_hdr.lh_prefix_len);
2525 	int h = (hash >> shift) & ((1 << ZAP_LEAF_HASH_SHIFT(&zl)) - 1);
2526 	h = zl.l_phys->l_hash[h];
2527 	if (h == 0xffff)
2528 		return (ENOENT);
2529 	zc = &ZAP_LEAF_CHUNK(&zl, h);
2530 	while (zc->l_entry.le_hash != hash) {
2531 		if (zc->l_entry.le_next == 0xffff)
2532 			return (ENOENT);
2533 		zc = &ZAP_LEAF_CHUNK(&zl, zc->l_entry.le_next);
2534 	}
2535 	if (fzap_name_equal(&zl, zc, name)) {
2536 		if (zc->l_entry.le_value_intlen * zc->l_entry.le_value_numints >
2537 		    integer_size * num_integers)
2538 			return (E2BIG);
2539 		fzap_leaf_array(&zl, zc, integer_size, num_integers, value);
2540 		return (0);
2541 	}
2542 
2543 	return (ENOENT);
2544 }
2545 
2546 /*
2547  * Lookup a name in a zap object and return its value as a uint64_t.
2548  */
2549 static int
2550 zap_lookup(const spa_t *spa, const dnode_phys_t *dnode, const char *name,
2551     uint64_t integer_size, uint64_t num_integers, void *value)
2552 {
2553 	int rc;
2554 	uint64_t zap_type;
2555 	size_t size = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
2556 
2557 	rc = dnode_read(spa, dnode, 0, zap_scratch, size);
2558 	if (rc)
2559 		return (rc);
2560 
2561 	zap_type = *(uint64_t *)zap_scratch;
2562 	if (zap_type == ZBT_MICRO)
2563 		return (mzap_lookup(dnode, name, value));
2564 	else if (zap_type == ZBT_HEADER) {
2565 		return (fzap_lookup(spa, dnode, name, integer_size,
2566 		    num_integers, value));
2567 	}
2568 	printf("ZFS: invalid zap_type=%d\n", (int)zap_type);
2569 	return (EIO);
2570 }
2571 
2572 /*
2573  * List a microzap directory. Assumes that the zap scratch buffer contains
2574  * the directory contents.
2575  */
2576 static int
2577 mzap_list(const dnode_phys_t *dnode, int (*callback)(const char *, uint64_t))
2578 {
2579 	const mzap_phys_t *mz;
2580 	const mzap_ent_phys_t *mze;
2581 	size_t size;
2582 	int chunks, i, rc;
2583 
2584 	/*
2585 	 * Microzap objects use exactly one block. Read the whole
2586 	 * thing.
2587 	 */
2588 	size = dnode->dn_datablkszsec * 512;
2589 	mz = (const mzap_phys_t *) zap_scratch;
2590 	chunks = size / MZAP_ENT_LEN - 1;
2591 
2592 	for (i = 0; i < chunks; i++) {
2593 		mze = &mz->mz_chunk[i];
2594 		if (mze->mze_name[0]) {
2595 			rc = callback(mze->mze_name, mze->mze_value);
2596 			if (rc != 0)
2597 				return (rc);
2598 		}
2599 	}
2600 
2601 	return (0);
2602 }
2603 
2604 /*
2605  * List a fatzap directory. Assumes that the zap scratch buffer contains
2606  * the directory header.
2607  */
2608 static int
2609 fzap_list(const spa_t *spa, const dnode_phys_t *dnode,
2610     int (*callback)(const char *, uint64_t))
2611 {
2612 	int bsize = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
2613 	zap_phys_t zh = *(zap_phys_t *)zap_scratch;
2614 	fat_zap_t z;
2615 	int i, j, rc;
2616 
2617 	if (zh.zap_magic != ZAP_MAGIC)
2618 		return (EIO);
2619 
2620 	z.zap_block_shift = ilog2(bsize);
2621 	z.zap_phys = (zap_phys_t *)zap_scratch;
2622 
2623 	/*
2624 	 * This assumes that the leaf blocks start at block 1. The
2625 	 * documentation isn't exactly clear on this.
2626 	 */
2627 	zap_leaf_t zl;
2628 	zl.l_bs = z.zap_block_shift;
2629 	for (i = 0; i < zh.zap_num_leafs; i++) {
2630 		off_t off = ((off_t)(i + 1)) << zl.l_bs;
2631 		char name[256], *p;
2632 		uint64_t value;
2633 
2634 		if (dnode_read(spa, dnode, off, zap_scratch, bsize))
2635 			return (EIO);
2636 
2637 		zl.l_phys = (zap_leaf_phys_t *)zap_scratch;
2638 
2639 		for (j = 0; j < ZAP_LEAF_NUMCHUNKS(&zl); j++) {
2640 			zap_leaf_chunk_t *zc, *nc;
2641 			int namelen;
2642 
2643 			zc = &ZAP_LEAF_CHUNK(&zl, j);
2644 			if (zc->l_entry.le_type != ZAP_CHUNK_ENTRY)
2645 				continue;
2646 			namelen = zc->l_entry.le_name_numints;
2647 			if (namelen > sizeof(name))
2648 				namelen = sizeof(name);
2649 
2650 			/*
2651 			 * Paste the name back together.
2652 			 */
2653 			nc = &ZAP_LEAF_CHUNK(&zl, zc->l_entry.le_name_chunk);
2654 			p = name;
2655 			while (namelen > 0) {
2656 				int len;
2657 				len = namelen;
2658 				if (len > ZAP_LEAF_ARRAY_BYTES)
2659 					len = ZAP_LEAF_ARRAY_BYTES;
2660 				memcpy(p, nc->l_array.la_array, len);
2661 				p += len;
2662 				namelen -= len;
2663 				nc = &ZAP_LEAF_CHUNK(&zl, nc->l_array.la_next);
2664 			}
2665 
2666 			/*
2667 			 * Assume the first eight bytes of the value are
2668 			 * a uint64_t.
2669 			 */
2670 			value = fzap_leaf_value(&zl, zc);
2671 
2672 			/* printf("%s 0x%jx\n", name, (uintmax_t)value); */
2673 			rc = callback((const char *)name, value);
2674 			if (rc != 0)
2675 				return (rc);
2676 		}
2677 	}
2678 
2679 	return (0);
2680 }
2681 
2682 static int zfs_printf(const char *name, uint64_t value __unused)
2683 {
2684 
2685 	printf("%s\n", name);
2686 
2687 	return (0);
2688 }
2689 
2690 /*
2691  * List a zap directory.
2692  */
2693 static int
2694 zap_list(const spa_t *spa, const dnode_phys_t *dnode)
2695 {
2696 	uint64_t zap_type;
2697 	size_t size = dnode->dn_datablkszsec * 512;
2698 
2699 	if (dnode_read(spa, dnode, 0, zap_scratch, size))
2700 		return (EIO);
2701 
2702 	zap_type = *(uint64_t *)zap_scratch;
2703 	if (zap_type == ZBT_MICRO)
2704 		return (mzap_list(dnode, zfs_printf));
2705 	else
2706 		return (fzap_list(spa, dnode, zfs_printf));
2707 }
2708 
2709 static int
2710 objset_get_dnode(const spa_t *spa, const objset_phys_t *os, uint64_t objnum,
2711     dnode_phys_t *dnode)
2712 {
2713 	off_t offset;
2714 
2715 	offset = objnum * sizeof(dnode_phys_t);
2716 	return dnode_read(spa, &os->os_meta_dnode, offset,
2717 		dnode, sizeof(dnode_phys_t));
2718 }
2719 
2720 static int
2721 mzap_rlookup(const spa_t *spa, const dnode_phys_t *dnode, char *name,
2722     uint64_t value)
2723 {
2724 	const mzap_phys_t *mz;
2725 	const mzap_ent_phys_t *mze;
2726 	size_t size;
2727 	int chunks, i;
2728 
2729 	/*
2730 	 * Microzap objects use exactly one block. Read the whole
2731 	 * thing.
2732 	 */
2733 	size = dnode->dn_datablkszsec * 512;
2734 
2735 	mz = (const mzap_phys_t *)zap_scratch;
2736 	chunks = size / MZAP_ENT_LEN - 1;
2737 
2738 	for (i = 0; i < chunks; i++) {
2739 		mze = &mz->mz_chunk[i];
2740 		if (value == mze->mze_value) {
2741 			strcpy(name, mze->mze_name);
2742 			return (0);
2743 		}
2744 	}
2745 
2746 	return (ENOENT);
2747 }
2748 
2749 static void
2750 fzap_name_copy(const zap_leaf_t *zl, const zap_leaf_chunk_t *zc, char *name)
2751 {
2752 	size_t namelen;
2753 	const zap_leaf_chunk_t *nc;
2754 	char *p;
2755 
2756 	namelen = zc->l_entry.le_name_numints;
2757 
2758 	nc = &ZAP_LEAF_CHUNK(zl, zc->l_entry.le_name_chunk);
2759 	p = name;
2760 	while (namelen > 0) {
2761 		size_t len;
2762 		len = namelen;
2763 		if (len > ZAP_LEAF_ARRAY_BYTES)
2764 			len = ZAP_LEAF_ARRAY_BYTES;
2765 		memcpy(p, nc->l_array.la_array, len);
2766 		p += len;
2767 		namelen -= len;
2768 		nc = &ZAP_LEAF_CHUNK(zl, nc->l_array.la_next);
2769 	}
2770 
2771 	*p = '\0';
2772 }
2773 
2774 static int
2775 fzap_rlookup(const spa_t *spa, const dnode_phys_t *dnode, char *name,
2776     uint64_t value)
2777 {
2778 	int bsize = dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
2779 	zap_phys_t zh = *(zap_phys_t *)zap_scratch;
2780 	fat_zap_t z;
2781 	int i, j;
2782 
2783 	if (zh.zap_magic != ZAP_MAGIC)
2784 		return (EIO);
2785 
2786 	z.zap_block_shift = ilog2(bsize);
2787 	z.zap_phys = (zap_phys_t *)zap_scratch;
2788 
2789 	/*
2790 	 * This assumes that the leaf blocks start at block 1. The
2791 	 * documentation isn't exactly clear on this.
2792 	 */
2793 	zap_leaf_t zl;
2794 	zl.l_bs = z.zap_block_shift;
2795 	for (i = 0; i < zh.zap_num_leafs; i++) {
2796 		off_t off = ((off_t)(i + 1)) << zl.l_bs;
2797 
2798 		if (dnode_read(spa, dnode, off, zap_scratch, bsize))
2799 			return (EIO);
2800 
2801 		zl.l_phys = (zap_leaf_phys_t *)zap_scratch;
2802 
2803 		for (j = 0; j < ZAP_LEAF_NUMCHUNKS(&zl); j++) {
2804 			zap_leaf_chunk_t *zc;
2805 
2806 			zc = &ZAP_LEAF_CHUNK(&zl, j);
2807 			if (zc->l_entry.le_type != ZAP_CHUNK_ENTRY)
2808 				continue;
2809 			if (zc->l_entry.le_value_intlen != 8 ||
2810 			    zc->l_entry.le_value_numints != 1)
2811 				continue;
2812 
2813 			if (fzap_leaf_value(&zl, zc) == value) {
2814 				fzap_name_copy(&zl, zc, name);
2815 				return (0);
2816 			}
2817 		}
2818 	}
2819 
2820 	return (ENOENT);
2821 }
2822 
2823 static int
2824 zap_rlookup(const spa_t *spa, const dnode_phys_t *dnode, char *name,
2825     uint64_t value)
2826 {
2827 	int rc;
2828 	uint64_t zap_type;
2829 	size_t size = dnode->dn_datablkszsec * 512;
2830 
2831 	rc = dnode_read(spa, dnode, 0, zap_scratch, size);
2832 	if (rc)
2833 		return (rc);
2834 
2835 	zap_type = *(uint64_t *)zap_scratch;
2836 	if (zap_type == ZBT_MICRO)
2837 		return (mzap_rlookup(spa, dnode, name, value));
2838 	else
2839 		return (fzap_rlookup(spa, dnode, name, value));
2840 }
2841 
2842 static int
2843 zfs_rlookup(const spa_t *spa, uint64_t objnum, char *result)
2844 {
2845 	char name[256];
2846 	char component[256];
2847 	uint64_t dir_obj, parent_obj, child_dir_zapobj;
2848 	dnode_phys_t child_dir_zap, dataset, dir, parent;
2849 	dsl_dir_phys_t *dd;
2850 	dsl_dataset_phys_t *ds;
2851 	char *p;
2852 	int len;
2853 
2854 	p = &name[sizeof(name) - 1];
2855 	*p = '\0';
2856 
2857 	if (objset_get_dnode(spa, &spa->spa_mos, objnum, &dataset)) {
2858 		printf("ZFS: can't find dataset %ju\n", (uintmax_t)objnum);
2859 		return (EIO);
2860 	}
2861 	ds = (dsl_dataset_phys_t *)&dataset.dn_bonus;
2862 	dir_obj = ds->ds_dir_obj;
2863 
2864 	for (;;) {
2865 		if (objset_get_dnode(spa, &spa->spa_mos, dir_obj, &dir) != 0)
2866 			return (EIO);
2867 		dd = (dsl_dir_phys_t *)&dir.dn_bonus;
2868 
2869 		/* Actual loop condition. */
2870 		parent_obj = dd->dd_parent_obj;
2871 		if (parent_obj == 0)
2872 			break;
2873 
2874 		if (objset_get_dnode(spa, &spa->spa_mos, parent_obj,
2875 		    &parent) != 0)
2876 			return (EIO);
2877 		dd = (dsl_dir_phys_t *)&parent.dn_bonus;
2878 		child_dir_zapobj = dd->dd_child_dir_zapobj;
2879 		if (objset_get_dnode(spa, &spa->spa_mos, child_dir_zapobj,
2880 		    &child_dir_zap) != 0)
2881 			return (EIO);
2882 		if (zap_rlookup(spa, &child_dir_zap, component, dir_obj) != 0)
2883 			return (EIO);
2884 
2885 		len = strlen(component);
2886 		p -= len;
2887 		memcpy(p, component, len);
2888 		--p;
2889 		*p = '/';
2890 
2891 		/* Actual loop iteration. */
2892 		dir_obj = parent_obj;
2893 	}
2894 
2895 	if (*p != '\0')
2896 		++p;
2897 	strcpy(result, p);
2898 
2899 	return (0);
2900 }
2901 
2902 static int
2903 zfs_lookup_dataset(const spa_t *spa, const char *name, uint64_t *objnum)
2904 {
2905 	char element[256];
2906 	uint64_t dir_obj, child_dir_zapobj;
2907 	dnode_phys_t child_dir_zap, dir;
2908 	dsl_dir_phys_t *dd;
2909 	const char *p, *q;
2910 
2911 	if (objset_get_dnode(spa, &spa->spa_mos,
2912 	    DMU_POOL_DIRECTORY_OBJECT, &dir))
2913 		return (EIO);
2914 	if (zap_lookup(spa, &dir, DMU_POOL_ROOT_DATASET, sizeof (dir_obj),
2915 	    1, &dir_obj))
2916 		return (EIO);
2917 
2918 	p = name;
2919 	for (;;) {
2920 		if (objset_get_dnode(spa, &spa->spa_mos, dir_obj, &dir))
2921 			return (EIO);
2922 		dd = (dsl_dir_phys_t *)&dir.dn_bonus;
2923 
2924 		while (*p == '/')
2925 			p++;
2926 		/* Actual loop condition #1. */
2927 		if (*p == '\0')
2928 			break;
2929 
2930 		q = strchr(p, '/');
2931 		if (q) {
2932 			memcpy(element, p, q - p);
2933 			element[q - p] = '\0';
2934 			p = q + 1;
2935 		} else {
2936 			strcpy(element, p);
2937 			p += strlen(p);
2938 		}
2939 
2940 		child_dir_zapobj = dd->dd_child_dir_zapobj;
2941 		if (objset_get_dnode(spa, &spa->spa_mos, child_dir_zapobj,
2942 		    &child_dir_zap) != 0)
2943 			return (EIO);
2944 
2945 		/* Actual loop condition #2. */
2946 		if (zap_lookup(spa, &child_dir_zap, element, sizeof (dir_obj),
2947 		    1, &dir_obj) != 0)
2948 			return (ENOENT);
2949 	}
2950 
2951 	*objnum = dd->dd_head_dataset_obj;
2952 	return (0);
2953 }
2954 
2955 #ifndef BOOT2
2956 static int
2957 zfs_list_dataset(const spa_t *spa, uint64_t objnum/*, int pos, char *entry*/)
2958 {
2959 	uint64_t dir_obj, child_dir_zapobj;
2960 	dnode_phys_t child_dir_zap, dir, dataset;
2961 	dsl_dataset_phys_t *ds;
2962 	dsl_dir_phys_t *dd;
2963 
2964 	if (objset_get_dnode(spa, &spa->spa_mos, objnum, &dataset)) {
2965 		printf("ZFS: can't find dataset %ju\n", (uintmax_t)objnum);
2966 		return (EIO);
2967 	}
2968 	ds = (dsl_dataset_phys_t *)&dataset.dn_bonus;
2969 	dir_obj = ds->ds_dir_obj;
2970 
2971 	if (objset_get_dnode(spa, &spa->spa_mos, dir_obj, &dir)) {
2972 		printf("ZFS: can't find dirobj %ju\n", (uintmax_t)dir_obj);
2973 		return (EIO);
2974 	}
2975 	dd = (dsl_dir_phys_t *)&dir.dn_bonus;
2976 
2977 	child_dir_zapobj = dd->dd_child_dir_zapobj;
2978 	if (objset_get_dnode(spa, &spa->spa_mos, child_dir_zapobj,
2979 	    &child_dir_zap) != 0) {
2980 		printf("ZFS: can't find child zap %ju\n", (uintmax_t)dir_obj);
2981 		return (EIO);
2982 	}
2983 
2984 	return (zap_list(spa, &child_dir_zap) != 0);
2985 }
2986 
2987 int
2988 zfs_callback_dataset(const spa_t *spa, uint64_t objnum,
2989     int (*callback)(const char *, uint64_t))
2990 {
2991 	uint64_t dir_obj, child_dir_zapobj, zap_type;
2992 	dnode_phys_t child_dir_zap, dir, dataset;
2993 	dsl_dataset_phys_t *ds;
2994 	dsl_dir_phys_t *dd;
2995 	int err;
2996 
2997 	err = objset_get_dnode(spa, &spa->spa_mos, objnum, &dataset);
2998 	if (err != 0) {
2999 		printf("ZFS: can't find dataset %ju\n", (uintmax_t)objnum);
3000 		return (err);
3001 	}
3002 	ds = (dsl_dataset_phys_t *)&dataset.dn_bonus;
3003 	dir_obj = ds->ds_dir_obj;
3004 
3005 	err = objset_get_dnode(spa, &spa->spa_mos, dir_obj, &dir);
3006 	if (err != 0) {
3007 		printf("ZFS: can't find dirobj %ju\n", (uintmax_t)dir_obj);
3008 		return (err);
3009 	}
3010 	dd = (dsl_dir_phys_t *)&dir.dn_bonus;
3011 
3012 	child_dir_zapobj = dd->dd_child_dir_zapobj;
3013 	err = objset_get_dnode(spa, &spa->spa_mos, child_dir_zapobj,
3014 	    &child_dir_zap);
3015 	if (err != 0) {
3016 		printf("ZFS: can't find child zap %ju\n", (uintmax_t)dir_obj);
3017 		return (err);
3018 	}
3019 
3020 	err = dnode_read(spa, &child_dir_zap, 0, zap_scratch,
3021 	    child_dir_zap.dn_datablkszsec * 512);
3022 	if (err != 0)
3023 		return (err);
3024 
3025 	zap_type = *(uint64_t *)zap_scratch;
3026 	if (zap_type == ZBT_MICRO)
3027 		return (mzap_list(&child_dir_zap, callback));
3028 	else
3029 		return (fzap_list(spa, &child_dir_zap, callback));
3030 }
3031 #endif
3032 
3033 /*
3034  * Find the object set given the object number of its dataset object
3035  * and return its details in *objset
3036  */
3037 static int
3038 zfs_mount_dataset(const spa_t *spa, uint64_t objnum, objset_phys_t *objset)
3039 {
3040 	dnode_phys_t dataset;
3041 	dsl_dataset_phys_t *ds;
3042 
3043 	if (objset_get_dnode(spa, &spa->spa_mos, objnum, &dataset)) {
3044 		printf("ZFS: can't find dataset %ju\n", (uintmax_t)objnum);
3045 		return (EIO);
3046 	}
3047 
3048 	ds = (dsl_dataset_phys_t *)&dataset.dn_bonus;
3049 	if (zio_read(spa, &ds->ds_bp, objset)) {
3050 		printf("ZFS: can't read object set for dataset %ju\n",
3051 		    (uintmax_t)objnum);
3052 		return (EIO);
3053 	}
3054 
3055 	return (0);
3056 }
3057 
3058 /*
3059  * Find the object set pointed to by the BOOTFS property or the root
3060  * dataset if there is none and return its details in *objset
3061  */
3062 static int
3063 zfs_get_root(const spa_t *spa, uint64_t *objid)
3064 {
3065 	dnode_phys_t dir, propdir;
3066 	uint64_t props, bootfs, root;
3067 
3068 	*objid = 0;
3069 
3070 	/*
3071 	 * Start with the MOS directory object.
3072 	 */
3073 	if (objset_get_dnode(spa, &spa->spa_mos,
3074 	    DMU_POOL_DIRECTORY_OBJECT, &dir)) {
3075 		printf("ZFS: can't read MOS object directory\n");
3076 		return (EIO);
3077 	}
3078 
3079 	/*
3080 	 * Lookup the pool_props and see if we can find a bootfs.
3081 	 */
3082 	if (zap_lookup(spa, &dir, DMU_POOL_PROPS,
3083 	    sizeof(props), 1, &props) == 0 &&
3084 	    objset_get_dnode(spa, &spa->spa_mos, props, &propdir) == 0 &&
3085 	    zap_lookup(spa, &propdir, "bootfs",
3086 	    sizeof(bootfs), 1, &bootfs) == 0 && bootfs != 0) {
3087 		*objid = bootfs;
3088 		return (0);
3089 	}
3090 	/*
3091 	 * Lookup the root dataset directory
3092 	 */
3093 	if (zap_lookup(spa, &dir, DMU_POOL_ROOT_DATASET,
3094 	    sizeof(root), 1, &root) ||
3095 	    objset_get_dnode(spa, &spa->spa_mos, root, &dir)) {
3096 		printf("ZFS: can't find root dsl_dir\n");
3097 		return (EIO);
3098 	}
3099 
3100 	/*
3101 	 * Use the information from the dataset directory's bonus buffer
3102 	 * to find the dataset object and from that the object set itself.
3103 	 */
3104 	dsl_dir_phys_t *dd = (dsl_dir_phys_t *)&dir.dn_bonus;
3105 	*objid = dd->dd_head_dataset_obj;
3106 	return (0);
3107 }
3108 
3109 static int
3110 zfs_mount(const spa_t *spa, uint64_t rootobj, struct zfsmount *mount)
3111 {
3112 
3113 	mount->spa = spa;
3114 
3115 	/*
3116 	 * Find the root object set if not explicitly provided
3117 	 */
3118 	if (rootobj == 0 && zfs_get_root(spa, &rootobj)) {
3119 		printf("ZFS: can't find root filesystem\n");
3120 		return (EIO);
3121 	}
3122 
3123 	if (zfs_mount_dataset(spa, rootobj, &mount->objset)) {
3124 		printf("ZFS: can't open root filesystem\n");
3125 		return (EIO);
3126 	}
3127 
3128 	mount->rootobj = rootobj;
3129 
3130 	return (0);
3131 }
3132 
3133 /*
3134  * callback function for feature name checks.
3135  */
3136 static int
3137 check_feature(const char *name, uint64_t value)
3138 {
3139 	int i;
3140 
3141 	if (value == 0)
3142 		return (0);
3143 	if (name[0] == '\0')
3144 		return (0);
3145 
3146 	for (i = 0; features_for_read[i] != NULL; i++) {
3147 		if (strcmp(name, features_for_read[i]) == 0)
3148 			return (0);
3149 	}
3150 	printf("ZFS: unsupported feature: %s\n", name);
3151 	return (EIO);
3152 }
3153 
3154 /*
3155  * Checks whether the MOS features that are active are supported.
3156  */
3157 static int
3158 check_mos_features(const spa_t *spa)
3159 {
3160 	dnode_phys_t dir;
3161 	uint64_t objnum, zap_type;
3162 	size_t size;
3163 	int rc;
3164 
3165 	if ((rc = objset_get_dnode(spa, &spa->spa_mos, DMU_OT_OBJECT_DIRECTORY,
3166 	    &dir)) != 0)
3167 		return (rc);
3168 	if ((rc = zap_lookup(spa, &dir, DMU_POOL_FEATURES_FOR_READ,
3169 	    sizeof (objnum), 1, &objnum)) != 0) {
3170 		/*
3171 		 * It is older pool without features. As we have already
3172 		 * tested the label, just return without raising the error.
3173 		 */
3174 		return (0);
3175 	}
3176 
3177 	if ((rc = objset_get_dnode(spa, &spa->spa_mos, objnum, &dir)) != 0)
3178 		return (rc);
3179 
3180 	if (dir.dn_type != DMU_OTN_ZAP_METADATA)
3181 		return (EIO);
3182 
3183 	size = dir.dn_datablkszsec * 512;
3184 	if (dnode_read(spa, &dir, 0, zap_scratch, size))
3185 		return (EIO);
3186 
3187 	zap_type = *(uint64_t *)zap_scratch;
3188 	if (zap_type == ZBT_MICRO)
3189 		rc = mzap_list(&dir, check_feature);
3190 	else
3191 		rc = fzap_list(spa, &dir, check_feature);
3192 
3193 	return (rc);
3194 }
3195 
3196 static int
3197 load_nvlist(spa_t *spa, uint64_t obj, unsigned char **value)
3198 {
3199 	dnode_phys_t dir;
3200 	size_t size;
3201 	int rc;
3202 	unsigned char *nv;
3203 
3204 	*value = NULL;
3205 	if ((rc = objset_get_dnode(spa, &spa->spa_mos, obj, &dir)) != 0)
3206 		return (rc);
3207 	if (dir.dn_type != DMU_OT_PACKED_NVLIST &&
3208 	    dir.dn_bonustype != DMU_OT_PACKED_NVLIST_SIZE) {
3209 		return (EIO);
3210 	}
3211 
3212 	if (dir.dn_bonuslen != sizeof (uint64_t))
3213 		return (EIO);
3214 
3215 	size = *(uint64_t *)DN_BONUS(&dir);
3216 	nv = malloc(size);
3217 	if (nv == NULL)
3218 		return (ENOMEM);
3219 
3220 	rc = dnode_read(spa, &dir, 0, nv, size);
3221 	if (rc != 0) {
3222 		free(nv);
3223 		nv = NULL;
3224 		return (rc);
3225 	}
3226 	*value = nv;
3227 	return (rc);
3228 }
3229 
3230 static int
3231 zfs_spa_init(spa_t *spa)
3232 {
3233 	dnode_phys_t dir;
3234 	uint64_t config_object;
3235 	unsigned char *nvlist;
3236 	int rc;
3237 
3238 	if (zio_read(spa, &spa->spa_uberblock.ub_rootbp, &spa->spa_mos)) {
3239 		printf("ZFS: can't read MOS of pool %s\n", spa->spa_name);
3240 		return (EIO);
3241 	}
3242 	if (spa->spa_mos.os_type != DMU_OST_META) {
3243 		printf("ZFS: corrupted MOS of pool %s\n", spa->spa_name);
3244 		return (EIO);
3245 	}
3246 
3247 	if (objset_get_dnode(spa, &spa->spa_mos, DMU_POOL_DIRECTORY_OBJECT,
3248 	    &dir)) {
3249 		printf("ZFS: failed to read pool %s directory object\n",
3250 		    spa->spa_name);
3251 		return (EIO);
3252 	}
3253 	/* this is allowed to fail, older pools do not have salt */
3254 	rc = zap_lookup(spa, &dir, DMU_POOL_CHECKSUM_SALT, 1,
3255 	    sizeof (spa->spa_cksum_salt.zcs_bytes),
3256 	    spa->spa_cksum_salt.zcs_bytes);
3257 
3258 	rc = check_mos_features(spa);
3259 	if (rc != 0) {
3260 		printf("ZFS: pool %s is not supported\n", spa->spa_name);
3261 		return (rc);
3262 	}
3263 
3264 	rc = zap_lookup(spa, &dir, DMU_POOL_CONFIG,
3265 	    sizeof (config_object), 1, &config_object);
3266 	if (rc != 0) {
3267 		printf("ZFS: can not read MOS %s\n", DMU_POOL_CONFIG);
3268 		return (EIO);
3269 	}
3270 	rc = load_nvlist(spa, config_object, &nvlist);
3271 	if (rc != 0)
3272 		return (rc);
3273 
3274 	/*
3275 	 * Update vdevs from MOS config. Note, we do skip encoding bytes
3276 	 * here. See also vdev_label_read_config().
3277 	 */
3278 	rc = vdev_init_from_nvlist(spa, nvlist + 4);
3279 	free(nvlist);
3280 	return (rc);
3281 }
3282 
3283 static int
3284 zfs_dnode_stat(const spa_t *spa, dnode_phys_t *dn, struct stat *sb)
3285 {
3286 
3287 	if (dn->dn_bonustype != DMU_OT_SA) {
3288 		znode_phys_t *zp = (znode_phys_t *)dn->dn_bonus;
3289 
3290 		sb->st_mode = zp->zp_mode;
3291 		sb->st_uid = zp->zp_uid;
3292 		sb->st_gid = zp->zp_gid;
3293 		sb->st_size = zp->zp_size;
3294 	} else {
3295 		sa_hdr_phys_t *sahdrp;
3296 		int hdrsize;
3297 		size_t size = 0;
3298 		void *buf = NULL;
3299 
3300 		if (dn->dn_bonuslen != 0)
3301 			sahdrp = (sa_hdr_phys_t *)DN_BONUS(dn);
3302 		else {
3303 			if ((dn->dn_flags & DNODE_FLAG_SPILL_BLKPTR) != 0) {
3304 				blkptr_t *bp = DN_SPILL_BLKPTR(dn);
3305 				int error;
3306 
3307 				size = BP_GET_LSIZE(bp);
3308 				buf = zfs_alloc(size);
3309 				error = zio_read(spa, bp, buf);
3310 				if (error != 0) {
3311 					zfs_free(buf, size);
3312 					return (error);
3313 				}
3314 				sahdrp = buf;
3315 			} else {
3316 				return (EIO);
3317 			}
3318 		}
3319 		hdrsize = SA_HDR_SIZE(sahdrp);
3320 		sb->st_mode = *(uint64_t *)((char *)sahdrp + hdrsize +
3321 		    SA_MODE_OFFSET);
3322 		sb->st_uid = *(uint64_t *)((char *)sahdrp + hdrsize +
3323 		    SA_UID_OFFSET);
3324 		sb->st_gid = *(uint64_t *)((char *)sahdrp + hdrsize +
3325 		    SA_GID_OFFSET);
3326 		sb->st_size = *(uint64_t *)((char *)sahdrp + hdrsize +
3327 		    SA_SIZE_OFFSET);
3328 		if (buf != NULL)
3329 			zfs_free(buf, size);
3330 	}
3331 
3332 	return (0);
3333 }
3334 
3335 static int
3336 zfs_dnode_readlink(const spa_t *spa, dnode_phys_t *dn, char *path, size_t psize)
3337 {
3338 	int rc = 0;
3339 
3340 	if (dn->dn_bonustype == DMU_OT_SA) {
3341 		sa_hdr_phys_t *sahdrp = NULL;
3342 		size_t size = 0;
3343 		void *buf = NULL;
3344 		int hdrsize;
3345 		char *p;
3346 
3347 		if (dn->dn_bonuslen != 0)
3348 			sahdrp = (sa_hdr_phys_t *)DN_BONUS(dn);
3349 		else {
3350 			blkptr_t *bp;
3351 
3352 			if ((dn->dn_flags & DNODE_FLAG_SPILL_BLKPTR) == 0)
3353 				return (EIO);
3354 			bp = DN_SPILL_BLKPTR(dn);
3355 
3356 			size = BP_GET_LSIZE(bp);
3357 			buf = zfs_alloc(size);
3358 			rc = zio_read(spa, bp, buf);
3359 			if (rc != 0) {
3360 				zfs_free(buf, size);
3361 				return (rc);
3362 			}
3363 			sahdrp = buf;
3364 		}
3365 		hdrsize = SA_HDR_SIZE(sahdrp);
3366 		p = (char *)((uintptr_t)sahdrp + hdrsize + SA_SYMLINK_OFFSET);
3367 		memcpy(path, p, psize);
3368 		if (buf != NULL)
3369 			zfs_free(buf, size);
3370 		return (0);
3371 	}
3372 	/*
3373 	 * Second test is purely to silence bogus compiler
3374 	 * warning about accessing past the end of dn_bonus.
3375 	 */
3376 	if (psize + sizeof(znode_phys_t) <= dn->dn_bonuslen &&
3377 	    sizeof(znode_phys_t) <= sizeof(dn->dn_bonus)) {
3378 		memcpy(path, &dn->dn_bonus[sizeof(znode_phys_t)], psize);
3379 	} else {
3380 		rc = dnode_read(spa, dn, 0, path, psize);
3381 	}
3382 	return (rc);
3383 }
3384 
3385 struct obj_list {
3386 	uint64_t		objnum;
3387 	STAILQ_ENTRY(obj_list)	entry;
3388 };
3389 
3390 /*
3391  * Lookup a file and return its dnode.
3392  */
3393 static int
3394 zfs_lookup(const struct zfsmount *mount, const char *upath, dnode_phys_t *dnode)
3395 {
3396 	int rc;
3397 	uint64_t objnum;
3398 	const spa_t *spa;
3399 	dnode_phys_t dn;
3400 	const char *p, *q;
3401 	char element[256];
3402 	char path[1024];
3403 	int symlinks_followed = 0;
3404 	struct stat sb;
3405 	struct obj_list *entry, *tentry;
3406 	STAILQ_HEAD(, obj_list) on_cache = STAILQ_HEAD_INITIALIZER(on_cache);
3407 
3408 	spa = mount->spa;
3409 	if (mount->objset.os_type != DMU_OST_ZFS) {
3410 		printf("ZFS: unexpected object set type %ju\n",
3411 		    (uintmax_t)mount->objset.os_type);
3412 		return (EIO);
3413 	}
3414 
3415 	if ((entry = malloc(sizeof(struct obj_list))) == NULL)
3416 		return (ENOMEM);
3417 
3418 	/*
3419 	 * Get the root directory dnode.
3420 	 */
3421 	rc = objset_get_dnode(spa, &mount->objset, MASTER_NODE_OBJ, &dn);
3422 	if (rc) {
3423 		free(entry);
3424 		return (rc);
3425 	}
3426 
3427 	rc = zap_lookup(spa, &dn, ZFS_ROOT_OBJ, sizeof(objnum), 1, &objnum);
3428 	if (rc) {
3429 		free(entry);
3430 		return (rc);
3431 	}
3432 	entry->objnum = objnum;
3433 	STAILQ_INSERT_HEAD(&on_cache, entry, entry);
3434 
3435 	rc = objset_get_dnode(spa, &mount->objset, objnum, &dn);
3436 	if (rc != 0)
3437 		goto done;
3438 
3439 	p = upath;
3440 	while (p && *p) {
3441 		rc = objset_get_dnode(spa, &mount->objset, objnum, &dn);
3442 		if (rc != 0)
3443 			goto done;
3444 
3445 		while (*p == '/')
3446 			p++;
3447 		if (*p == '\0')
3448 			break;
3449 		q = p;
3450 		while (*q != '\0' && *q != '/')
3451 			q++;
3452 
3453 		/* skip dot */
3454 		if (p + 1 == q && p[0] == '.') {
3455 			p++;
3456 			continue;
3457 		}
3458 		/* double dot */
3459 		if (p + 2 == q && p[0] == '.' && p[1] == '.') {
3460 			p += 2;
3461 			if (STAILQ_FIRST(&on_cache) ==
3462 			    STAILQ_LAST(&on_cache, obj_list, entry)) {
3463 				rc = ENOENT;
3464 				goto done;
3465 			}
3466 			entry = STAILQ_FIRST(&on_cache);
3467 			STAILQ_REMOVE_HEAD(&on_cache, entry);
3468 			free(entry);
3469 			objnum = (STAILQ_FIRST(&on_cache))->objnum;
3470 			continue;
3471 		}
3472 		if (q - p + 1 > sizeof(element)) {
3473 			rc = ENAMETOOLONG;
3474 			goto done;
3475 		}
3476 		memcpy(element, p, q - p);
3477 		element[q - p] = 0;
3478 		p = q;
3479 
3480 		if ((rc = zfs_dnode_stat(spa, &dn, &sb)) != 0)
3481 			goto done;
3482 		if (!S_ISDIR(sb.st_mode)) {
3483 			rc = ENOTDIR;
3484 			goto done;
3485 		}
3486 
3487 		rc = zap_lookup(spa, &dn, element, sizeof (objnum), 1, &objnum);
3488 		if (rc)
3489 			goto done;
3490 		objnum = ZFS_DIRENT_OBJ(objnum);
3491 
3492 		if ((entry = malloc(sizeof(struct obj_list))) == NULL) {
3493 			rc = ENOMEM;
3494 			goto done;
3495 		}
3496 		entry->objnum = objnum;
3497 		STAILQ_INSERT_HEAD(&on_cache, entry, entry);
3498 		rc = objset_get_dnode(spa, &mount->objset, objnum, &dn);
3499 		if (rc)
3500 			goto done;
3501 
3502 		/*
3503 		 * Check for symlink.
3504 		 */
3505 		rc = zfs_dnode_stat(spa, &dn, &sb);
3506 		if (rc)
3507 			goto done;
3508 		if (S_ISLNK(sb.st_mode)) {
3509 			if (symlinks_followed > 10) {
3510 				rc = EMLINK;
3511 				goto done;
3512 			}
3513 			symlinks_followed++;
3514 
3515 			/*
3516 			 * Read the link value and copy the tail of our
3517 			 * current path onto the end.
3518 			 */
3519 			if (sb.st_size + strlen(p) + 1 > sizeof(path)) {
3520 				rc = ENAMETOOLONG;
3521 				goto done;
3522 			}
3523 			strcpy(&path[sb.st_size], p);
3524 
3525 			rc = zfs_dnode_readlink(spa, &dn, path, sb.st_size);
3526 			if (rc != 0)
3527 				goto done;
3528 
3529 			/*
3530 			 * Restart with the new path, starting either at
3531 			 * the root or at the parent depending whether or
3532 			 * not the link is relative.
3533 			 */
3534 			p = path;
3535 			if (*p == '/') {
3536 				while (STAILQ_FIRST(&on_cache) !=
3537 				    STAILQ_LAST(&on_cache, obj_list, entry)) {
3538 					entry = STAILQ_FIRST(&on_cache);
3539 					STAILQ_REMOVE_HEAD(&on_cache, entry);
3540 					free(entry);
3541 				}
3542 			} else {
3543 				entry = STAILQ_FIRST(&on_cache);
3544 				STAILQ_REMOVE_HEAD(&on_cache, entry);
3545 				free(entry);
3546 			}
3547 			objnum = (STAILQ_FIRST(&on_cache))->objnum;
3548 		}
3549 	}
3550 
3551 	*dnode = dn;
3552 done:
3553 	STAILQ_FOREACH_SAFE(entry, &on_cache, entry, tentry)
3554 		free(entry);
3555 	return (rc);
3556 }
3557