1 /*
2  *  GRUB  --  GRand Unified Bootloader
3  *  Copyright (C) 1999,2000,2001,2002,2003,2004  Free Software Foundation, Inc.
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19 /*
20  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
21  * Use is subject to license terms.
22  */
23 
24 /*
25  * The zfs plug-in routines for GRUB are:
26  *
27  * zfs_mount() - locates a valid uberblock of the root pool and reads
28  *		in its MOS at the memory address MOS.
29  *
30  * zfs_open() - locates a plain file object by following the MOS
31  *		and places its dnode at the memory address DNODE.
32  *
33  * zfs_read() - read in the data blocks pointed by the DNODE.
34  *
35  * ZFS_SCRATCH is used as a working area.
36  *
37  * (memory addr)   MOS      DNODE	ZFS_SCRATCH
38  *		    |         |          |
39  *	    +-------V---------V----------V---------------+
40  *   memory |       | dnode   | dnode    |  scratch      |
41  *	    |       | 512B    | 512B     |  area         |
42  *	    +--------------------------------------------+
43  */
44 
45 #ifdef	FSYS_ZFS
46 
47 #include "shared.h"
48 #include "filesys.h"
49 #include "fsys_zfs.h"
50 
51 /* cache for a file block of the currently zfs_open()-ed file */
52 static void *file_buf = NULL;
53 static uint64_t file_start = 0;
54 static uint64_t file_end = 0;
55 
56 /* cache for a dnode block */
57 static dnode_phys_t *dnode_buf = NULL;
58 static dnode_phys_t *dnode_mdn = NULL;
59 static uint64_t dnode_start = 0;
60 static uint64_t dnode_end = 0;
61 
62 static uint64_t pool_guid = 0;
63 static uberblock_t current_uberblock;
64 static char *stackbase;
65 
66 decomp_entry_t decomp_table[ZIO_COMPRESS_FUNCTIONS] =
67 {
68 	{"inherit", 0},			/* ZIO_COMPRESS_INHERIT */
69 	{"on", lzjb_decompress}, 	/* ZIO_COMPRESS_ON */
70 	{"off", 0},			/* ZIO_COMPRESS_OFF */
71 	{"lzjb", lzjb_decompress},	/* ZIO_COMPRESS_LZJB */
72 	{"empty", 0}			/* ZIO_COMPRESS_EMPTY */
73 };
74 
75 static int zio_read_data(blkptr_t *bp, void *buf, char *stack);
76 
77 /*
78  * Our own version of bcmp().
79  */
80 static int
81 zfs_bcmp(const void *s1, const void *s2, size_t n)
82 {
83 	const uchar_t *ps1 = s1;
84 	const uchar_t *ps2 = s2;
85 
86 	if (s1 != s2 && n != 0) {
87 		do {
88 			if (*ps1++ != *ps2++)
89 				return (1);
90 		} while (--n != 0);
91 	}
92 
93 	return (0);
94 }
95 
96 /*
97  * Our own version of log2().  Same thing as highbit()-1.
98  */
99 static int
100 zfs_log2(uint64_t num)
101 {
102 	int i = 0;
103 
104 	while (num > 1) {
105 		i++;
106 		num = num >> 1;
107 	}
108 
109 	return (i);
110 }
111 
112 /* Checksum Functions */
113 static void
114 zio_checksum_off(const void *buf, uint64_t size, zio_cksum_t *zcp)
115 {
116 	ZIO_SET_CHECKSUM(zcp, 0, 0, 0, 0);
117 }
118 
119 /* Checksum Table and Values */
120 zio_checksum_info_t zio_checksum_table[ZIO_CHECKSUM_FUNCTIONS] = {
121 	NULL,			NULL,			0, 0,	"inherit",
122 	NULL,			NULL,			0, 0,	"on",
123 	zio_checksum_off,	zio_checksum_off,	0, 0,	"off",
124 	zio_checksum_SHA256,	zio_checksum_SHA256,	1, 1,	"label",
125 	zio_checksum_SHA256,	zio_checksum_SHA256,	1, 1,	"gang_header",
126 	fletcher_2_native,	fletcher_2_byteswap,	0, 1,	"zilog",
127 	fletcher_2_native,	fletcher_2_byteswap,	0, 0,	"fletcher2",
128 	fletcher_4_native,	fletcher_4_byteswap,	1, 0,	"fletcher4",
129 	zio_checksum_SHA256,	zio_checksum_SHA256,	1, 0,	"SHA256",
130 };
131 
132 /*
133  * zio_checksum_verify: Provides support for checksum verification.
134  *
135  * Fletcher2, Fletcher4, and SHA256 are supported.
136  *
137  * Return:
138  * 	-1 = Failure
139  *	 0 = Success
140  */
141 static int
142 zio_checksum_verify(blkptr_t *bp, char *data, int size)
143 {
144 	zio_cksum_t zc = bp->blk_cksum;
145 	uint32_t checksum = BP_GET_CHECKSUM(bp);
146 	int byteswap = BP_SHOULD_BYTESWAP(bp);
147 	zio_block_tail_t *zbt = (zio_block_tail_t *)(data + size) - 1;
148 	zio_checksum_info_t *ci = &zio_checksum_table[checksum];
149 	zio_cksum_t actual_cksum, expected_cksum;
150 
151 	/* byteswap is not supported */
152 	if (byteswap)
153 		return (-1);
154 
155 	if (checksum >= ZIO_CHECKSUM_FUNCTIONS || ci->ci_func[0] == NULL)
156 		return (-1);
157 
158 	if (ci->ci_zbt) {
159 		expected_cksum = zbt->zbt_cksum;
160 		zbt->zbt_cksum = zc;
161 		ci->ci_func[0](data, size, &actual_cksum);
162 		zbt->zbt_cksum = expected_cksum;
163 		zc = expected_cksum;
164 
165 	} else {
166 		ci->ci_func[byteswap](data, size, &actual_cksum);
167 	}
168 
169 	if ((actual_cksum.zc_word[0] - zc.zc_word[0]) |
170 	    (actual_cksum.zc_word[1] - zc.zc_word[1]) |
171 	    (actual_cksum.zc_word[2] - zc.zc_word[2]) |
172 	    (actual_cksum.zc_word[3] - zc.zc_word[3]))
173 		return (-1);
174 
175 	return (0);
176 }
177 
178 /*
179  * vdev_label_start returns the physical disk offset (in bytes) of
180  * label "l".
181  */
182 static uint64_t
183 vdev_label_start(uint64_t psize, int l)
184 {
185 	return (l * sizeof (vdev_label_t) + (l < VDEV_LABELS / 2 ?
186 	    0 : psize - VDEV_LABELS * sizeof (vdev_label_t)));
187 }
188 
189 /*
190  * vdev_uberblock_compare takes two uberblock structures and returns an integer
191  * indicating the more recent of the two.
192  * 	Return Value = 1 if ub2 is more recent
193  * 	Return Value = -1 if ub1 is more recent
194  * The most recent uberblock is determined using its transaction number and
195  * timestamp.  The uberblock with the highest transaction number is
196  * considered "newer".  If the transaction numbers of the two blocks match, the
197  * timestamps are compared to determine the "newer" of the two.
198  */
199 static int
200 vdev_uberblock_compare(uberblock_t *ub1, uberblock_t *ub2)
201 {
202 	if (ub1->ub_txg < ub2->ub_txg)
203 		return (-1);
204 	if (ub1->ub_txg > ub2->ub_txg)
205 		return (1);
206 
207 	if (ub1->ub_timestamp < ub2->ub_timestamp)
208 		return (-1);
209 	if (ub1->ub_timestamp > ub2->ub_timestamp)
210 		return (1);
211 
212 	return (0);
213 }
214 
215 /*
216  * Three pieces of information are needed to verify an uberblock: the magic
217  * number, the version number, and the checksum.
218  *
219  * Currently Implemented: version number, magic number
220  * Need to Implement: checksum
221  *
222  * Return:
223  *     0 - Success
224  *    -1 - Failure
225  */
226 static int
227 uberblock_verify(uberblock_phys_t *ub, uint64_t offset)
228 {
229 
230 	uberblock_t *uber = &ub->ubp_uberblock;
231 	blkptr_t bp;
232 
233 	BP_ZERO(&bp);
234 	BP_SET_CHECKSUM(&bp, ZIO_CHECKSUM_LABEL);
235 	BP_SET_BYTEORDER(&bp, ZFS_HOST_BYTEORDER);
236 	ZIO_SET_CHECKSUM(&bp.blk_cksum, offset, 0, 0, 0);
237 
238 	if (zio_checksum_verify(&bp, (char *)ub, UBERBLOCK_SIZE) != 0)
239 		return (-1);
240 
241 	if (uber->ub_magic == UBERBLOCK_MAGIC &&
242 	    uber->ub_version > 0 && uber->ub_version <= SPA_VERSION)
243 		return (0);
244 
245 	return (-1);
246 }
247 
248 /*
249  * Find the best uberblock.
250  * Return:
251  *    Success - Pointer to the best uberblock.
252  *    Failure - NULL
253  */
254 static uberblock_phys_t *
255 find_bestub(uberblock_phys_t *ub_array, uint64_t sector)
256 {
257 	uberblock_phys_t *ubbest = NULL;
258 	uint64_t offset;
259 	int i;
260 
261 	for (i = 0; i < (VDEV_UBERBLOCK_RING >> VDEV_UBERBLOCK_SHIFT); i++) {
262 		offset = (sector << SPA_MINBLOCKSHIFT) +
263 		    VDEV_UBERBLOCK_OFFSET(i);
264 		if (uberblock_verify(&ub_array[i], offset) == 0) {
265 			if (ubbest == NULL) {
266 				ubbest = &ub_array[i];
267 			} else if (vdev_uberblock_compare(
268 			    &(ub_array[i].ubp_uberblock),
269 			    &(ubbest->ubp_uberblock)) > 0) {
270 				ubbest = &ub_array[i];
271 			}
272 		}
273 	}
274 
275 	return (ubbest);
276 }
277 
278 /*
279  * Read a block of data based on the gang block address dva,
280  * and put its data in buf.
281  *
282  * Return:
283  *	0 - success
284  *	1 - failure
285  */
286 static int
287 zio_read_gang(blkptr_t *bp, dva_t *dva, void *buf, char *stack)
288 {
289 	zio_gbh_phys_t *zio_gb;
290 	uint64_t offset, sector;
291 	blkptr_t tmpbp;
292 	int i;
293 
294 	zio_gb = (zio_gbh_phys_t *)stack;
295 	stack += SPA_GANGBLOCKSIZE;
296 	offset = DVA_GET_OFFSET(dva);
297 	sector =  DVA_OFFSET_TO_PHYS_SECTOR(offset);
298 
299 	/* read in the gang block header */
300 	if (devread(sector, 0, SPA_GANGBLOCKSIZE, (char *)zio_gb) == 0) {
301 		grub_printf("failed to read in a gang block header\n");
302 		return (1);
303 	}
304 
305 	/* self checksuming the gang block header */
306 	BP_ZERO(&tmpbp);
307 	BP_SET_CHECKSUM(&tmpbp, ZIO_CHECKSUM_GANG_HEADER);
308 	BP_SET_BYTEORDER(&tmpbp, ZFS_HOST_BYTEORDER);
309 	ZIO_SET_CHECKSUM(&tmpbp.blk_cksum, DVA_GET_VDEV(dva),
310 	    DVA_GET_OFFSET(dva), bp->blk_birth, 0);
311 	if (zio_checksum_verify(&tmpbp, (char *)zio_gb, SPA_GANGBLOCKSIZE)) {
312 		grub_printf("failed to checksum a gang block header\n");
313 		return (1);
314 	}
315 
316 	for (i = 0; i < SPA_GBH_NBLKPTRS; i++) {
317 		if (zio_gb->zg_blkptr[i].blk_birth == 0)
318 			continue;
319 
320 		if (zio_read_data(&zio_gb->zg_blkptr[i], buf, stack))
321 			return (1);
322 		buf += BP_GET_PSIZE(&zio_gb->zg_blkptr[i]);
323 	}
324 
325 	return (0);
326 }
327 
328 /*
329  * Read in a block of raw data to buf.
330  *
331  * Return:
332  *	0 - success
333  *	1 - failure
334  */
335 static int
336 zio_read_data(blkptr_t *bp, void *buf, char *stack)
337 {
338 	int i, psize;
339 
340 	psize = BP_GET_PSIZE(bp);
341 
342 	/* pick a good dva from the block pointer */
343 	for (i = 0; i < SPA_DVAS_PER_BP; i++) {
344 		uint64_t offset, sector;
345 
346 		if (bp->blk_dva[i].dva_word[0] == 0 &&
347 		    bp->blk_dva[i].dva_word[1] == 0)
348 			continue;
349 
350 		if (DVA_GET_GANG(&bp->blk_dva[i])) {
351 			if (zio_read_gang(bp, &bp->blk_dva[i], buf, stack) == 0)
352 				return (0);
353 		} else {
354 			/* read in a data block */
355 			offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
356 			sector =  DVA_OFFSET_TO_PHYS_SECTOR(offset);
357 			if (devread(sector, 0, psize, buf))
358 				return (0);
359 		}
360 	}
361 
362 	return (1);
363 }
364 
365 /*
366  * Read in a block of data, verify its checksum, decompress if needed,
367  * and put the uncompressed data in buf.
368  *
369  * Return:
370  *	0 - success
371  *	errnum - failure
372  */
373 static int
374 zio_read(blkptr_t *bp, void *buf, char *stack)
375 {
376 	int lsize, psize, comp;
377 	char *retbuf;
378 
379 	comp = BP_GET_COMPRESS(bp);
380 	lsize = BP_GET_LSIZE(bp);
381 	psize = BP_GET_PSIZE(bp);
382 
383 	if ((unsigned int)comp >= ZIO_COMPRESS_FUNCTIONS ||
384 	    (comp != ZIO_COMPRESS_OFF &&
385 	    decomp_table[comp].decomp_func == NULL)) {
386 		grub_printf("compression algorithm not supported\n");
387 		return (ERR_FSYS_CORRUPT);
388 	}
389 
390 	if ((char *)buf < stack && ((char *)buf) + lsize > stack) {
391 		grub_printf("not enough memory allocated\n");
392 		return (ERR_WONT_FIT);
393 	}
394 
395 	retbuf = buf;
396 	if (comp != ZIO_COMPRESS_OFF) {
397 		buf = stack;
398 		stack += psize;
399 	}
400 
401 	if (zio_read_data(bp, buf, stack)) {
402 		grub_printf("zio_read_data failed\n");
403 		return (ERR_FSYS_CORRUPT);
404 	}
405 
406 	if (zio_checksum_verify(bp, buf, psize) != 0) {
407 		grub_printf("checksum verification failed\n");
408 		return (ERR_FSYS_CORRUPT);
409 	}
410 
411 	if (comp != ZIO_COMPRESS_OFF)
412 		decomp_table[comp].decomp_func(buf, retbuf, psize, lsize);
413 
414 	return (0);
415 }
416 
417 /*
418  * Get the block from a block id.
419  * push the block onto the stack.
420  *
421  * Return:
422  * 	0 - success
423  * 	errnum - failure
424  */
425 static int
426 dmu_read(dnode_phys_t *dn, uint64_t blkid, void *buf, char *stack)
427 {
428 	int idx, level;
429 	blkptr_t *bp_array = dn->dn_blkptr;
430 	int epbs = dn->dn_indblkshift - SPA_BLKPTRSHIFT;
431 	blkptr_t *bp, *tmpbuf;
432 
433 	bp = (blkptr_t *)stack;
434 	stack += sizeof (blkptr_t);
435 
436 	tmpbuf = (blkptr_t *)stack;
437 	stack += 1<<dn->dn_indblkshift;
438 
439 	for (level = dn->dn_nlevels - 1; level >= 0; level--) {
440 		idx = (blkid >> (epbs * level)) & ((1<<epbs)-1);
441 		*bp = bp_array[idx];
442 		if (level == 0)
443 			tmpbuf = buf;
444 		if (BP_IS_HOLE(bp)) {
445 			grub_memset(buf, 0,
446 			    dn->dn_datablkszsec << SPA_MINBLOCKSHIFT);
447 			break;
448 		} else if (errnum = zio_read(bp, tmpbuf, stack)) {
449 			return (errnum);
450 		}
451 
452 		bp_array = tmpbuf;
453 	}
454 
455 	return (0);
456 }
457 
458 /*
459  * mzap_lookup: Looks up property described by "name" and returns the value
460  * in "value".
461  *
462  * Return:
463  *	0 - success
464  *	errnum - failure
465  */
466 static int
467 mzap_lookup(mzap_phys_t *zapobj, int objsize, char *name,
468 	uint64_t *value)
469 {
470 	int i, chunks;
471 	mzap_ent_phys_t *mzap_ent = zapobj->mz_chunk;
472 
473 	chunks = objsize/MZAP_ENT_LEN - 1;
474 	for (i = 0; i < chunks; i++) {
475 		if (grub_strcmp(mzap_ent[i].mze_name, name) == 0) {
476 			*value = mzap_ent[i].mze_value;
477 			return (0);
478 		}
479 	}
480 
481 	return (ERR_FSYS_CORRUPT);
482 }
483 
484 static uint64_t
485 zap_hash(uint64_t salt, const char *name)
486 {
487 	static uint64_t table[256];
488 	const uint8_t *cp;
489 	uint8_t c;
490 	uint64_t crc = salt;
491 
492 	if (table[128] == 0) {
493 		uint64_t *ct;
494 		int i, j;
495 		for (i = 0; i < 256; i++) {
496 			for (ct = table + i, *ct = i, j = 8; j > 0; j--)
497 				*ct = (*ct >> 1) ^ (-(*ct & 1) &
498 				    ZFS_CRC64_POLY);
499 		}
500 	}
501 
502 	if (crc == 0 || table[128] != ZFS_CRC64_POLY) {
503 		errnum = ERR_FSYS_CORRUPT;
504 		return (0);
505 	}
506 
507 	for (cp = (const uint8_t *)name; (c = *cp) != '\0'; cp++)
508 		crc = (crc >> 8) ^ table[(crc ^ c) & 0xFF];
509 
510 	/*
511 	 * Only use 28 bits, since we need 4 bits in the cookie for the
512 	 * collision differentiator.  We MUST use the high bits, since
513 	 * those are the onces that we first pay attention to when
514 	 * chosing the bucket.
515 	 */
516 	crc &= ~((1ULL << (64 - ZAP_HASHBITS)) - 1);
517 
518 	return (crc);
519 }
520 
521 /*
522  * Only to be used on 8-bit arrays.
523  * array_len is actual len in bytes (not encoded le_value_length).
524  * buf is null-terminated.
525  */
526 static int
527 zap_leaf_array_equal(zap_leaf_phys_t *l, int blksft, int chunk,
528     int array_len, const char *buf)
529 {
530 	int bseen = 0;
531 
532 	while (bseen < array_len) {
533 		struct zap_leaf_array *la =
534 		    &ZAP_LEAF_CHUNK(l, blksft, chunk).l_array;
535 		int toread = MIN(array_len - bseen, ZAP_LEAF_ARRAY_BYTES);
536 
537 		if (chunk >= ZAP_LEAF_NUMCHUNKS(blksft))
538 			return (0);
539 
540 		if (zfs_bcmp(la->la_array, buf + bseen, toread) != 0)
541 			break;
542 		chunk = la->la_next;
543 		bseen += toread;
544 	}
545 	return (bseen == array_len);
546 }
547 
548 /*
549  * Given a zap_leaf_phys_t, walk thru the zap leaf chunks to get the
550  * value for the property "name".
551  *
552  * Return:
553  *	0 - success
554  *	errnum - failure
555  */
556 static int
557 zap_leaf_lookup(zap_leaf_phys_t *l, int blksft, uint64_t h,
558     const char *name, uint64_t *value)
559 {
560 	uint16_t chunk;
561 	struct zap_leaf_entry *le;
562 
563 	/* Verify if this is a valid leaf block */
564 	if (l->l_hdr.lh_block_type != ZBT_LEAF)
565 		return (ERR_FSYS_CORRUPT);
566 	if (l->l_hdr.lh_magic != ZAP_LEAF_MAGIC)
567 		return (ERR_FSYS_CORRUPT);
568 
569 	for (chunk = l->l_hash[LEAF_HASH(blksft, h)];
570 	    chunk != CHAIN_END; chunk = le->le_next) {
571 
572 		if (chunk >= ZAP_LEAF_NUMCHUNKS(blksft))
573 			return (ERR_FSYS_CORRUPT);
574 
575 		le = ZAP_LEAF_ENTRY(l, blksft, chunk);
576 
577 		/* Verify the chunk entry */
578 		if (le->le_type != ZAP_CHUNK_ENTRY)
579 			return (ERR_FSYS_CORRUPT);
580 
581 		if (le->le_hash != h)
582 			continue;
583 
584 		if (zap_leaf_array_equal(l, blksft, le->le_name_chunk,
585 		    le->le_name_length, name)) {
586 
587 			struct zap_leaf_array *la;
588 			uint8_t *ip;
589 
590 			if (le->le_int_size != 8 || le->le_value_length != 1)
591 				return (ERR_FSYS_CORRUPT);
592 
593 			/* get the uint64_t property value */
594 			la = &ZAP_LEAF_CHUNK(l, blksft,
595 			    le->le_value_chunk).l_array;
596 			ip = la->la_array;
597 
598 			*value = (uint64_t)ip[0] << 56 | (uint64_t)ip[1] << 48 |
599 			    (uint64_t)ip[2] << 40 | (uint64_t)ip[3] << 32 |
600 			    (uint64_t)ip[4] << 24 | (uint64_t)ip[5] << 16 |
601 			    (uint64_t)ip[6] << 8 | (uint64_t)ip[7];
602 
603 			return (0);
604 		}
605 	}
606 
607 	return (ERR_FSYS_CORRUPT);
608 }
609 
610 /*
611  * Fat ZAP lookup
612  *
613  * Return:
614  *	0 - success
615  *	errnum - failure
616  */
617 static int
618 fzap_lookup(dnode_phys_t *zap_dnode, zap_phys_t *zap,
619     char *name, uint64_t *value, char *stack)
620 {
621 	zap_leaf_phys_t *l;
622 	uint64_t hash, idx, blkid;
623 	int blksft = zfs_log2(zap_dnode->dn_datablkszsec << DNODE_SHIFT);
624 
625 	/* Verify if this is a fat zap header block */
626 	if (zap->zap_magic != (uint64_t)ZAP_MAGIC)
627 		return (ERR_FSYS_CORRUPT);
628 
629 	hash = zap_hash(zap->zap_salt, name);
630 	if (errnum)
631 		return (errnum);
632 
633 	/* get block id from index */
634 	if (zap->zap_ptrtbl.zt_numblks != 0) {
635 		/* external pointer tables not supported */
636 		return (ERR_FSYS_CORRUPT);
637 	}
638 	idx = ZAP_HASH_IDX(hash, zap->zap_ptrtbl.zt_shift);
639 	blkid = ((uint64_t *)zap)[idx + (1<<(blksft-3-1))];
640 
641 	/* Get the leaf block */
642 	l = (zap_leaf_phys_t *)stack;
643 	stack += 1<<blksft;
644 	if ((1<<blksft) < sizeof (zap_leaf_phys_t))
645 		return (ERR_FSYS_CORRUPT);
646 	if (errnum = dmu_read(zap_dnode, blkid, l, stack))
647 		return (errnum);
648 
649 	return (zap_leaf_lookup(l, blksft, hash, name, value));
650 }
651 
652 /*
653  * Read in the data of a zap object and find the value for a matching
654  * property name.
655  *
656  * Return:
657  *	0 - success
658  *	errnum - failure
659  */
660 static int
661 zap_lookup(dnode_phys_t *zap_dnode, char *name, uint64_t *val, char *stack)
662 {
663 	uint64_t block_type;
664 	int size;
665 	void *zapbuf;
666 
667 	/* Read in the first block of the zap object data. */
668 	zapbuf = stack;
669 	size = zap_dnode->dn_datablkszsec << SPA_MINBLOCKSHIFT;
670 	stack += size;
671 	if (errnum = dmu_read(zap_dnode, 0, zapbuf, stack))
672 		return (errnum);
673 
674 	block_type = *((uint64_t *)zapbuf);
675 
676 	if (block_type == ZBT_MICRO) {
677 		return (mzap_lookup(zapbuf, size, name, val));
678 	} else if (block_type == ZBT_HEADER) {
679 		/* this is a fat zap */
680 		return (fzap_lookup(zap_dnode, zapbuf, name,
681 		    val, stack));
682 	}
683 
684 	return (ERR_FSYS_CORRUPT);
685 }
686 
687 /*
688  * Get the dnode of an object number from the metadnode of an object set.
689  *
690  * Input
691  *	mdn - metadnode to get the object dnode
692  *	objnum - object number for the object dnode
693  *	buf - data buffer that holds the returning dnode
694  *	stack - scratch area
695  *
696  * Return:
697  *	0 - success
698  *	errnum - failure
699  */
700 static int
701 dnode_get(dnode_phys_t *mdn, uint64_t objnum, uint8_t type, dnode_phys_t *buf,
702 	char *stack)
703 {
704 	uint64_t blkid, blksz; /* the block id this object dnode is in */
705 	int epbs; /* shift of number of dnodes in a block */
706 	int idx; /* index within a block */
707 	dnode_phys_t *dnbuf;
708 
709 	blksz = mdn->dn_datablkszsec << SPA_MINBLOCKSHIFT;
710 	epbs = zfs_log2(blksz) - DNODE_SHIFT;
711 	blkid = objnum >> epbs;
712 	idx = objnum & ((1<<epbs)-1);
713 
714 	if (dnode_buf != NULL && dnode_mdn == mdn &&
715 	    objnum >= dnode_start && objnum < dnode_end) {
716 		grub_memmove(buf, &dnode_buf[idx], DNODE_SIZE);
717 		VERIFY_DN_TYPE(buf, type);
718 		return (0);
719 	}
720 
721 	if (dnode_buf && blksz == 1<<DNODE_BLOCK_SHIFT) {
722 		dnbuf = dnode_buf;
723 		dnode_mdn = mdn;
724 		dnode_start = blkid << epbs;
725 		dnode_end = (blkid + 1) << epbs;
726 	} else {
727 		dnbuf = (dnode_phys_t *)stack;
728 		stack += blksz;
729 	}
730 
731 	if (errnum = dmu_read(mdn, blkid, (char *)dnbuf, stack))
732 		return (errnum);
733 
734 	grub_memmove(buf, &dnbuf[idx], DNODE_SIZE);
735 	VERIFY_DN_TYPE(buf, type);
736 
737 	return (0);
738 }
739 
740 /*
741  * Check if this is a special file that resides at the top
742  * dataset of the pool. Currently this is the GRUB menu,
743  * boot signature and boot signature backup.
744  * str starts with '/'.
745  */
746 static int
747 is_top_dataset_file(char *str)
748 {
749 	char *tptr;
750 
751 	if ((tptr = grub_strstr(str, "menu.lst")) &&
752 	    (tptr[8] == '\0' || tptr[8] == ' ') &&
753 	    *(tptr-1) == '/')
754 		return (1);
755 
756 	if (grub_strncmp(str, BOOTSIGN_DIR"/",
757 	    grub_strlen(BOOTSIGN_DIR) + 1) == 0)
758 		return (1);
759 
760 	if (grub_strcmp(str, BOOTSIGN_BACKUP) == 0)
761 		return (1);
762 
763 	return (0);
764 }
765 
766 /*
767  * Get the file dnode for a given file name where mdn is the meta dnode
768  * for this ZFS object set. When found, place the file dnode in dn.
769  * The 'path' argument will be mangled.
770  *
771  * Return:
772  *	0 - success
773  *	errnum - failure
774  */
775 static int
776 dnode_get_path(dnode_phys_t *mdn, char *path, dnode_phys_t *dn,
777     char *stack)
778 {
779 	uint64_t objnum, version;
780 	char *cname, ch;
781 
782 	if (errnum = dnode_get(mdn, MASTER_NODE_OBJ, DMU_OT_MASTER_NODE,
783 	    dn, stack))
784 		return (errnum);
785 
786 	if (errnum = zap_lookup(dn, ZPL_VERSION_STR, &version, stack))
787 		return (errnum);
788 	if (version > ZPL_VERSION)
789 		return (-1);
790 
791 	if (errnum = zap_lookup(dn, ZFS_ROOT_OBJ, &objnum, stack))
792 		return (errnum);
793 
794 	if (errnum = dnode_get(mdn, objnum, DMU_OT_DIRECTORY_CONTENTS,
795 	    dn, stack))
796 		return (errnum);
797 
798 	/* skip leading slashes */
799 	while (*path == '/')
800 		path++;
801 
802 	while (*path && !isspace(*path)) {
803 
804 		/* get the next component name */
805 		cname = path;
806 		while (*path && !isspace(*path) && *path != '/')
807 			path++;
808 		ch = *path;
809 		*path = 0;   /* ensure null termination */
810 
811 		if (errnum = zap_lookup(dn, cname, &objnum, stack))
812 			return (errnum);
813 
814 		objnum = ZFS_DIRENT_OBJ(objnum);
815 		if (errnum = dnode_get(mdn, objnum, 0, dn, stack))
816 			return (errnum);
817 
818 		*path = ch;
819 		while (*path == '/')
820 			path++;
821 	}
822 
823 	/* We found the dnode for this file. Verify if it is a plain file. */
824 	VERIFY_DN_TYPE(dn, DMU_OT_PLAIN_FILE_CONTENTS);
825 
826 	return (0);
827 }
828 
829 /*
830  * Get the default 'bootfs' property value from the rootpool.
831  *
832  * Return:
833  *	0 - success
834  *	errnum -failure
835  */
836 static int
837 get_default_bootfsobj(dnode_phys_t *mosmdn, uint64_t *obj, char *stack)
838 {
839 	uint64_t objnum = 0;
840 	dnode_phys_t *dn = (dnode_phys_t *)stack;
841 	stack += DNODE_SIZE;
842 
843 	if (errnum = dnode_get(mosmdn, DMU_POOL_DIRECTORY_OBJECT,
844 	    DMU_OT_OBJECT_DIRECTORY, dn, stack))
845 		return (errnum);
846 
847 	/*
848 	 * find the object number for 'pool_props', and get the dnode
849 	 * of the 'pool_props'.
850 	 */
851 	if (zap_lookup(dn, DMU_POOL_PROPS, &objnum, stack))
852 		return (ERR_FILESYSTEM_NOT_FOUND);
853 
854 	if (errnum = dnode_get(mosmdn, objnum, DMU_OT_POOL_PROPS, dn, stack))
855 		return (errnum);
856 
857 	if (zap_lookup(dn, ZPOOL_PROP_BOOTFS, &objnum, stack))
858 		return (ERR_FILESYSTEM_NOT_FOUND);
859 
860 	if (!objnum)
861 		return (ERR_FILESYSTEM_NOT_FOUND);
862 
863 	*obj = objnum;
864 	return (0);
865 }
866 
867 /*
868  * Given a MOS metadnode, get the metadnode of a given filesystem name (fsname),
869  * e.g. pool/rootfs, or a given object number (obj), e.g. the object number
870  * of pool/rootfs.
871  *
872  * If no fsname and no obj are given, return the DSL_DIR metadnode.
873  * If fsname is given, return its metadnode and its matching object number.
874  * If only obj is given, return the metadnode for this object number.
875  *
876  * Return:
877  *	0 - success
878  *	errnum - failure
879  */
880 static int
881 get_objset_mdn(dnode_phys_t *mosmdn, char *fsname, uint64_t *obj,
882     dnode_phys_t *mdn, char *stack)
883 {
884 	uint64_t objnum, headobj;
885 	char *cname, ch;
886 	blkptr_t *bp;
887 	objset_phys_t *osp;
888 	int issnapshot = 0;
889 	char *snapname;
890 
891 	if (fsname == NULL && obj) {
892 		headobj = *obj;
893 		goto skip;
894 	}
895 
896 	if (errnum = dnode_get(mosmdn, DMU_POOL_DIRECTORY_OBJECT,
897 	    DMU_OT_OBJECT_DIRECTORY, mdn, stack))
898 		return (errnum);
899 
900 	if (errnum = zap_lookup(mdn, DMU_POOL_ROOT_DATASET, &objnum,
901 	    stack))
902 		return (errnum);
903 
904 	if (errnum = dnode_get(mosmdn, objnum, DMU_OT_DSL_DIR, mdn, stack))
905 		return (errnum);
906 
907 	if (fsname == NULL) {
908 		headobj =
909 		    ((dsl_dir_phys_t *)DN_BONUS(mdn))->dd_head_dataset_obj;
910 		goto skip;
911 	}
912 
913 	/* take out the pool name */
914 	while (*fsname && !isspace(*fsname) && *fsname != '/')
915 		fsname++;
916 
917 	while (*fsname && !isspace(*fsname)) {
918 		uint64_t childobj;
919 
920 		while (*fsname == '/')
921 			fsname++;
922 
923 		cname = fsname;
924 		while (*fsname && !isspace(*fsname) && *fsname != '/')
925 			fsname++;
926 		ch = *fsname;
927 		*fsname = 0;
928 
929 		snapname = cname;
930 		while (*snapname && !isspace(*snapname) && *snapname != '@')
931 			snapname++;
932 		if (*snapname == '@') {
933 			issnapshot = 1;
934 			*snapname = 0;
935 		}
936 		childobj =
937 		    ((dsl_dir_phys_t *)DN_BONUS(mdn))->dd_child_dir_zapobj;
938 		if (errnum = dnode_get(mosmdn, childobj,
939 		    DMU_OT_DSL_DIR_CHILD_MAP, mdn, stack))
940 			return (errnum);
941 
942 		if (zap_lookup(mdn, cname, &objnum, stack))
943 			return (ERR_FILESYSTEM_NOT_FOUND);
944 
945 		if (errnum = dnode_get(mosmdn, objnum, DMU_OT_DSL_DIR,
946 		    mdn, stack))
947 			return (errnum);
948 
949 		*fsname = ch;
950 		if (issnapshot)
951 			*snapname = '@';
952 	}
953 	headobj = ((dsl_dir_phys_t *)DN_BONUS(mdn))->dd_head_dataset_obj;
954 	if (obj)
955 		*obj = headobj;
956 
957 skip:
958 	if (errnum = dnode_get(mosmdn, headobj, DMU_OT_DSL_DATASET, mdn, stack))
959 		return (errnum);
960 	if (issnapshot) {
961 		uint64_t snapobj;
962 
963 		snapobj = ((dsl_dataset_phys_t *)DN_BONUS(mdn))->
964 		    ds_snapnames_zapobj;
965 
966 		if (errnum = dnode_get(mosmdn, snapobj,
967 		    DMU_OT_DSL_DS_SNAP_MAP, mdn, stack))
968 			return (errnum);
969 		if (zap_lookup(mdn, snapname + 1, &headobj, stack))
970 			return (ERR_FILESYSTEM_NOT_FOUND);
971 		if (errnum = dnode_get(mosmdn, headobj,
972 		    DMU_OT_DSL_DATASET, mdn, stack))
973 			return (errnum);
974 		if (obj)
975 			*obj = headobj;
976 	}
977 
978 	bp = &((dsl_dataset_phys_t *)DN_BONUS(mdn))->ds_bp;
979 	osp = (objset_phys_t *)stack;
980 	stack += sizeof (objset_phys_t);
981 	if (errnum = zio_read(bp, osp, stack))
982 		return (errnum);
983 
984 	grub_memmove((char *)mdn, (char *)&osp->os_meta_dnode, DNODE_SIZE);
985 
986 	return (0);
987 }
988 
989 /*
990  * For a given XDR packed nvlist, verify the first 4 bytes and move on.
991  *
992  * An XDR packed nvlist is encoded as (comments from nvs_xdr_create) :
993  *
994  *      encoding method/host endian     (4 bytes)
995  *      nvl_version                     (4 bytes)
996  *      nvl_nvflag                      (4 bytes)
997  *	encoded nvpairs:
998  *		encoded size of the nvpair      (4 bytes)
999  *		decoded size of the nvpair      (4 bytes)
1000  *		name string size                (4 bytes)
1001  *		name string data                (sizeof(NV_ALIGN4(string))
1002  *		data type                       (4 bytes)
1003  *		# of elements in the nvpair     (4 bytes)
1004  *		data
1005  *      2 zero's for the last nvpair
1006  *		(end of the entire list)	(8 bytes)
1007  *
1008  * Return:
1009  *	0 - success
1010  *	1 - failure
1011  */
1012 static int
1013 nvlist_unpack(char *nvlist, char **out)
1014 {
1015 	/* Verify if the 1st and 2nd byte in the nvlist are valid. */
1016 	if (nvlist[0] != NV_ENCODE_XDR || nvlist[1] != HOST_ENDIAN)
1017 		return (1);
1018 
1019 	nvlist += 4;
1020 	*out = nvlist;
1021 	return (0);
1022 }
1023 
1024 static char *
1025 nvlist_array(char *nvlist, int index)
1026 {
1027 	int i, encode_size;
1028 
1029 	for (i = 0; i < index; i++) {
1030 		/* skip the header, nvl_version, and nvl_nvflag */
1031 		nvlist = nvlist + 4 * 2;
1032 
1033 		while (encode_size = BSWAP_32(*(uint32_t *)nvlist))
1034 			nvlist += encode_size; /* goto the next nvpair */
1035 
1036 		nvlist = nvlist + 4 * 2; /* skip the ending 2 zeros - 8 bytes */
1037 	}
1038 
1039 	return (nvlist);
1040 }
1041 
1042 static int
1043 nvlist_lookup_value(char *nvlist, char *name, void *val, int valtype,
1044     int *nelmp)
1045 {
1046 	int name_len, type, slen, encode_size;
1047 	char *nvpair, *nvp_name, *strval = val;
1048 	uint64_t *intval = val;
1049 
1050 	/* skip the header, nvl_version, and nvl_nvflag */
1051 	nvlist = nvlist + 4 * 2;
1052 
1053 	/*
1054 	 * Loop thru the nvpair list
1055 	 * The XDR representation of an integer is in big-endian byte order.
1056 	 */
1057 	while (encode_size = BSWAP_32(*(uint32_t *)nvlist))  {
1058 
1059 		nvpair = nvlist + 4 * 2; /* skip the encode/decode size */
1060 
1061 		name_len = BSWAP_32(*(uint32_t *)nvpair);
1062 		nvpair += 4;
1063 
1064 		nvp_name = nvpair;
1065 		nvpair = nvpair + ((name_len + 3) & ~3); /* align */
1066 
1067 		type = BSWAP_32(*(uint32_t *)nvpair);
1068 		nvpair += 4;
1069 
1070 		if ((grub_strncmp(nvp_name, name, name_len) == 0) &&
1071 		    type == valtype) {
1072 			int nelm;
1073 
1074 			if ((nelm = BSWAP_32(*(uint32_t *)nvpair)) < 1)
1075 				return (1);
1076 			nvpair += 4;
1077 
1078 			switch (valtype) {
1079 			case DATA_TYPE_STRING:
1080 				slen = BSWAP_32(*(uint32_t *)nvpair);
1081 				nvpair += 4;
1082 				grub_memmove(strval, nvpair, slen);
1083 				strval[slen] = '\0';
1084 				return (0);
1085 
1086 			case DATA_TYPE_UINT64:
1087 				*intval = BSWAP_64(*(uint64_t *)nvpair);
1088 				return (0);
1089 
1090 			case DATA_TYPE_NVLIST:
1091 				*(void **)val = (void *)nvpair;
1092 				return (0);
1093 
1094 			case DATA_TYPE_NVLIST_ARRAY:
1095 				*(void **)val = (void *)nvpair;
1096 				if (nelmp)
1097 					*nelmp = nelm;
1098 				return (0);
1099 			}
1100 		}
1101 
1102 		nvlist += encode_size; /* goto the next nvpair */
1103 	}
1104 
1105 	return (1);
1106 }
1107 
1108 /*
1109  * Check if this vdev is online and is in a good state.
1110  */
1111 static int
1112 vdev_validate(char *nv)
1113 {
1114 	uint64_t ival;
1115 
1116 	if (nvlist_lookup_value(nv, ZPOOL_CONFIG_OFFLINE, &ival,
1117 	    DATA_TYPE_UINT64, NULL) == 0 ||
1118 	    nvlist_lookup_value(nv, ZPOOL_CONFIG_FAULTED, &ival,
1119 	    DATA_TYPE_UINT64, NULL) == 0 ||
1120 	    nvlist_lookup_value(nv, ZPOOL_CONFIG_REMOVED, &ival,
1121 	    DATA_TYPE_UINT64, NULL) == 0)
1122 		return (ERR_DEV_VALUES);
1123 
1124 	return (0);
1125 }
1126 
1127 /*
1128  * Get a valid vdev pathname/devid from the boot device.
1129  * The caller should already allocate MAXPATHLEN memory for bootpath and devid.
1130  */
1131 static int
1132 vdev_get_bootpath(char *nv, uint64_t inguid, char *devid, char *bootpath,
1133     int is_spare)
1134 {
1135 	char type[16];
1136 
1137 	if (nvlist_lookup_value(nv, ZPOOL_CONFIG_TYPE, &type, DATA_TYPE_STRING,
1138 	    NULL))
1139 		return (ERR_FSYS_CORRUPT);
1140 
1141 	if (strcmp(type, VDEV_TYPE_DISK) == 0) {
1142 		uint64_t guid;
1143 
1144 		if (vdev_validate(nv) != 0)
1145 			return (ERR_NO_BOOTPATH);
1146 
1147 		if (nvlist_lookup_value(nv, ZPOOL_CONFIG_GUID,
1148 		    &guid, DATA_TYPE_UINT64, NULL) != 0)
1149 			return (ERR_NO_BOOTPATH);
1150 
1151 		if (guid != inguid)
1152 			return (ERR_NO_BOOTPATH);
1153 
1154 		/* for a spare vdev, pick the disk labeled with "is_spare" */
1155 		if (is_spare) {
1156 			uint64_t spare = 0;
1157 			(void) nvlist_lookup_value(nv, ZPOOL_CONFIG_IS_SPARE,
1158 			    &spare, DATA_TYPE_UINT64, NULL);
1159 			if (!spare)
1160 				return (ERR_NO_BOOTPATH);
1161 		}
1162 
1163 		if (nvlist_lookup_value(nv, ZPOOL_CONFIG_PHYS_PATH,
1164 		    bootpath, DATA_TYPE_STRING, NULL) != 0)
1165 			bootpath[0] = '\0';
1166 
1167 		if (nvlist_lookup_value(nv, ZPOOL_CONFIG_DEVID,
1168 		    devid, DATA_TYPE_STRING, NULL) != 0)
1169 			devid[0] = '\0';
1170 
1171 		if (strlen(bootpath) >= MAXPATHLEN ||
1172 		    strlen(devid) >= MAXPATHLEN)
1173 			return (ERR_WONT_FIT);
1174 
1175 		return (0);
1176 
1177 	} else if (strcmp(type, VDEV_TYPE_MIRROR) == 0 ||
1178 	    strcmp(type, VDEV_TYPE_REPLACING) == 0 ||
1179 	    (is_spare = (strcmp(type, VDEV_TYPE_SPARE) == 0))) {
1180 		int nelm, i;
1181 		char *child;
1182 
1183 		if (nvlist_lookup_value(nv, ZPOOL_CONFIG_CHILDREN, &child,
1184 		    DATA_TYPE_NVLIST_ARRAY, &nelm))
1185 			return (ERR_FSYS_CORRUPT);
1186 
1187 		for (i = 0; i < nelm; i++) {
1188 			char *child_i;
1189 
1190 			child_i = nvlist_array(child, i);
1191 			if (vdev_get_bootpath(child_i, inguid, devid,
1192 			    bootpath, is_spare) == 0)
1193 				return (0);
1194 		}
1195 	}
1196 
1197 	return (ERR_NO_BOOTPATH);
1198 }
1199 
1200 /*
1201  * Check the disk label information and retrieve needed vdev name-value pairs.
1202  *
1203  * Return:
1204  *	0 - success
1205  *	ERR_* - failure
1206  */
1207 int
1208 check_pool_label(uint64_t sector, char *stack, char *outdevid,
1209     char *outpath, uint64_t *outguid)
1210 {
1211 	vdev_phys_t *vdev;
1212 	uint64_t pool_state, txg = 0;
1213 	char *nvlist, *nv;
1214 	uint64_t diskguid;
1215 	uint64_t version;
1216 
1217 	sector += (VDEV_SKIP_SIZE >> SPA_MINBLOCKSHIFT);
1218 
1219 	/* Read in the vdev name-value pair list (112K). */
1220 	if (devread(sector, 0, VDEV_PHYS_SIZE, stack) == 0)
1221 		return (ERR_READ);
1222 
1223 	vdev = (vdev_phys_t *)stack;
1224 	stack += sizeof (vdev_phys_t);
1225 
1226 	if (nvlist_unpack(vdev->vp_nvlist, &nvlist))
1227 		return (ERR_FSYS_CORRUPT);
1228 
1229 	if (nvlist_lookup_value(nvlist, ZPOOL_CONFIG_POOL_STATE, &pool_state,
1230 	    DATA_TYPE_UINT64, NULL))
1231 		return (ERR_FSYS_CORRUPT);
1232 
1233 	if (pool_state == POOL_STATE_DESTROYED)
1234 		return (ERR_FILESYSTEM_NOT_FOUND);
1235 
1236 	if (nvlist_lookup_value(nvlist, ZPOOL_CONFIG_POOL_NAME,
1237 	    current_rootpool, DATA_TYPE_STRING, NULL))
1238 		return (ERR_FSYS_CORRUPT);
1239 
1240 	if (nvlist_lookup_value(nvlist, ZPOOL_CONFIG_POOL_TXG, &txg,
1241 	    DATA_TYPE_UINT64, NULL))
1242 		return (ERR_FSYS_CORRUPT);
1243 
1244 	/* not an active device */
1245 	if (txg == 0)
1246 		return (ERR_NO_BOOTPATH);
1247 
1248 	if (nvlist_lookup_value(nvlist, ZPOOL_CONFIG_VERSION, &version,
1249 	    DATA_TYPE_UINT64, NULL))
1250 		return (ERR_FSYS_CORRUPT);
1251 	if (version > SPA_VERSION)
1252 		return (ERR_NEWER_VERSION);
1253 	if (nvlist_lookup_value(nvlist, ZPOOL_CONFIG_VDEV_TREE, &nv,
1254 	    DATA_TYPE_NVLIST, NULL))
1255 		return (ERR_FSYS_CORRUPT);
1256 	if (nvlist_lookup_value(nvlist, ZPOOL_CONFIG_GUID, &diskguid,
1257 	    DATA_TYPE_UINT64, NULL))
1258 		return (ERR_FSYS_CORRUPT);
1259 	if (vdev_get_bootpath(nv, diskguid, outdevid, outpath, 0))
1260 		return (ERR_NO_BOOTPATH);
1261 	if (nvlist_lookup_value(nvlist, ZPOOL_CONFIG_POOL_GUID, outguid,
1262 	    DATA_TYPE_UINT64, NULL))
1263 		return (ERR_FSYS_CORRUPT);
1264 	return (0);
1265 }
1266 
1267 /*
1268  * zfs_mount() locates a valid uberblock of the root pool and read in its MOS
1269  * to the memory address MOS.
1270  *
1271  * Return:
1272  *	1 - success
1273  *	0 - failure
1274  */
1275 int
1276 zfs_mount(void)
1277 {
1278 	char *stack;
1279 	int label = 0;
1280 	uberblock_phys_t *ub_array, *ubbest;
1281 	objset_phys_t *osp;
1282 	char tmp_bootpath[MAXNAMELEN];
1283 	char tmp_devid[MAXNAMELEN];
1284 	uint64_t tmp_guid;
1285 	uint64_t adjpl = (uint64_t)part_length << SPA_MINBLOCKSHIFT;
1286 	int err = errnum; /* preserve previous errnum state */
1287 
1288 	/* if it's our first time here, zero the best uberblock out */
1289 	if (best_drive == 0 && best_part == 0 && find_best_root) {
1290 		grub_memset(&current_uberblock, 0, sizeof (uberblock_t));
1291 		pool_guid = 0;
1292 	}
1293 
1294 	stackbase = ZFS_SCRATCH;
1295 	stack = stackbase;
1296 	ub_array = (uberblock_phys_t *)stack;
1297 	stack += VDEV_UBERBLOCK_RING;
1298 
1299 	osp = (objset_phys_t *)stack;
1300 	stack += sizeof (objset_phys_t);
1301 	adjpl = P2ALIGN(adjpl, (uint64_t)sizeof (vdev_label_t));
1302 
1303 	for (label = 0; label < VDEV_LABELS; label++) {
1304 		uint64_t sector = vdev_label_start(adjpl,
1305 		    label) >> SPA_MINBLOCKSHIFT;
1306 
1307 		/* Read in the uberblock ring (128K). */
1308 		if (devread(sector  +
1309 		    ((VDEV_SKIP_SIZE + VDEV_PHYS_SIZE) >>
1310 		    SPA_MINBLOCKSHIFT), 0, VDEV_UBERBLOCK_RING,
1311 		    (char *)ub_array) == 0)
1312 			continue;
1313 
1314 		if ((ubbest = find_bestub(ub_array, sector)) != NULL &&
1315 		    zio_read(&ubbest->ubp_uberblock.ub_rootbp, osp, stack)
1316 		    == 0) {
1317 
1318 			VERIFY_OS_TYPE(osp, DMU_OST_META);
1319 
1320 			if (check_pool_label(sector, stack, tmp_devid,
1321 			    tmp_bootpath, &tmp_guid))
1322 				continue;
1323 			if (pool_guid == 0)
1324 				pool_guid = tmp_guid;
1325 
1326 			if (find_best_root && ((pool_guid != tmp_guid) ||
1327 			    vdev_uberblock_compare(&ubbest->ubp_uberblock,
1328 			    &(current_uberblock)) <= 0))
1329 				continue;
1330 
1331 			/* Got the MOS. Save it at the memory addr MOS. */
1332 			grub_memmove(MOS, &osp->os_meta_dnode, DNODE_SIZE);
1333 			grub_memmove(&current_uberblock,
1334 			    &ubbest->ubp_uberblock, sizeof (uberblock_t));
1335 			grub_memmove(current_bootpath, tmp_bootpath,
1336 			    MAXNAMELEN);
1337 			grub_memmove(current_devid, tmp_devid,
1338 			    grub_strlen(tmp_devid));
1339 			is_zfs_mount = 1;
1340 			return (1);
1341 		}
1342 	}
1343 
1344 	/*
1345 	 * While some fs impls. (tftp) rely on setting and keeping
1346 	 * global errnums set, others won't reset it and will break
1347 	 * when issuing rawreads. The goal here is to simply not
1348 	 * have zfs mount attempts impact the previous state.
1349 	 */
1350 	errnum = err;
1351 	return (0);
1352 }
1353 
1354 /*
1355  * zfs_open() locates a file in the rootpool by following the
1356  * MOS and places the dnode of the file in the memory address DNODE.
1357  *
1358  * Return:
1359  *	1 - success
1360  *	0 - failure
1361  */
1362 int
1363 zfs_open(char *filename)
1364 {
1365 	char *stack;
1366 	dnode_phys_t *mdn;
1367 
1368 	file_buf = NULL;
1369 	stackbase = ZFS_SCRATCH;
1370 	stack = stackbase;
1371 
1372 	mdn = (dnode_phys_t *)stack;
1373 	stack += sizeof (dnode_phys_t);
1374 
1375 	dnode_mdn = NULL;
1376 	dnode_buf = (dnode_phys_t *)stack;
1377 	stack += 1<<DNODE_BLOCK_SHIFT;
1378 
1379 	/*
1380 	 * menu.lst is placed at the root pool filesystem level,
1381 	 * do not goto 'current_bootfs'.
1382 	 */
1383 	if (is_top_dataset_file(filename)) {
1384 		if (errnum = get_objset_mdn(MOS, NULL, NULL, mdn, stack))
1385 			return (0);
1386 
1387 		current_bootfs_obj = 0;
1388 	} else {
1389 		if (current_bootfs[0] == '\0') {
1390 			/* Get the default root filesystem object number */
1391 			if (errnum = get_default_bootfsobj(MOS,
1392 			    &current_bootfs_obj, stack))
1393 				return (0);
1394 
1395 			if (errnum = get_objset_mdn(MOS, NULL,
1396 			    &current_bootfs_obj, mdn, stack))
1397 				return (0);
1398 		} else {
1399 			if (errnum = get_objset_mdn(MOS, current_bootfs,
1400 			    &current_bootfs_obj, mdn, stack)) {
1401 				grub_memset(current_bootfs, 0, MAXNAMELEN);
1402 				return (0);
1403 			}
1404 		}
1405 	}
1406 
1407 	if (dnode_get_path(mdn, filename, DNODE, stack)) {
1408 		errnum = ERR_FILE_NOT_FOUND;
1409 		return (0);
1410 	}
1411 
1412 	/* get the file size and set the file position to 0 */
1413 	filemax = ((znode_phys_t *)DN_BONUS(DNODE))->zp_size;
1414 	filepos = 0;
1415 
1416 	dnode_buf = NULL;
1417 	return (1);
1418 }
1419 
1420 /*
1421  * zfs_read reads in the data blocks pointed by the DNODE.
1422  *
1423  * Return:
1424  *	len - the length successfully read in to the buffer
1425  *	0   - failure
1426  */
1427 int
1428 zfs_read(char *buf, int len)
1429 {
1430 	char *stack;
1431 	char *tmpbuf;
1432 	int blksz, length, movesize;
1433 
1434 	if (file_buf == NULL) {
1435 		file_buf = stackbase;
1436 		stackbase += SPA_MAXBLOCKSIZE;
1437 		file_start = file_end = 0;
1438 	}
1439 	stack = stackbase;
1440 
1441 	/*
1442 	 * If offset is in memory, move it into the buffer provided and return.
1443 	 */
1444 	if (filepos >= file_start && filepos+len <= file_end) {
1445 		grub_memmove(buf, file_buf + filepos - file_start, len);
1446 		filepos += len;
1447 		return (len);
1448 	}
1449 
1450 	blksz = DNODE->dn_datablkszsec << SPA_MINBLOCKSHIFT;
1451 
1452 	/*
1453 	 * Entire Dnode is too big to fit into the space available.  We
1454 	 * will need to read it in chunks.  This could be optimized to
1455 	 * read in as large a chunk as there is space available, but for
1456 	 * now, this only reads in one data block at a time.
1457 	 */
1458 	length = len;
1459 	while (length) {
1460 		/*
1461 		 * Find requested blkid and the offset within that block.
1462 		 */
1463 		uint64_t blkid = filepos / blksz;
1464 
1465 		if (errnum = dmu_read(DNODE, blkid, file_buf, stack))
1466 			return (0);
1467 
1468 		file_start = blkid * blksz;
1469 		file_end = file_start + blksz;
1470 
1471 		movesize = MIN(length, file_end - filepos);
1472 
1473 		grub_memmove(buf, file_buf + filepos - file_start,
1474 		    movesize);
1475 		buf += movesize;
1476 		length -= movesize;
1477 		filepos += movesize;
1478 	}
1479 
1480 	return (len);
1481 }
1482 
1483 /*
1484  * No-Op
1485  */
1486 int
1487 zfs_embed(int *start_sector, int needed_sectors)
1488 {
1489 	return (1);
1490 }
1491 
1492 #endif /* FSYS_ZFS */
1493