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