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