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