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