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