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