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