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