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