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