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