xref: /freebsd/stand/libsa/zfs/zfs.c (revision 6871d4882591c9a8fcab24d084c93f0a2972e1af)
1 /*-
2  * Copyright (c) 2007 Doug Rabson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  *	$FreeBSD$
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 /*
33  *	Stand-alone file reading package.
34  */
35 
36 #include <stand.h>
37 #include <sys/disk.h>
38 #include <sys/param.h>
39 #include <sys/time.h>
40 #include <sys/queue.h>
41 #include <disk.h>
42 #include <part.h>
43 #include <stddef.h>
44 #include <stdarg.h>
45 #include <string.h>
46 #include <bootstrap.h>
47 
48 #include "libzfs.h"
49 
50 #include "zfsimpl.c"
51 
52 /* Define the range of indexes to be populated with ZFS Boot Environments */
53 #define		ZFS_BE_FIRST	4
54 #define		ZFS_BE_LAST	8
55 
56 static int	zfs_open(const char *path, struct open_file *f);
57 static int	zfs_close(struct open_file *f);
58 static int	zfs_read(struct open_file *f, void *buf, size_t size, size_t *resid);
59 static off_t	zfs_seek(struct open_file *f, off_t offset, int where);
60 static int	zfs_stat(struct open_file *f, struct stat *sb);
61 static int	zfs_readdir(struct open_file *f, struct dirent *d);
62 
63 static void	zfs_bootenv_initial(const char *);
64 
65 struct devsw zfs_dev;
66 
67 struct fs_ops zfs_fsops = {
68 	"zfs",
69 	zfs_open,
70 	zfs_close,
71 	zfs_read,
72 	null_write,
73 	zfs_seek,
74 	zfs_stat,
75 	zfs_readdir
76 };
77 
78 /*
79  * In-core open file.
80  */
81 struct file {
82 	off_t		f_seekp;	/* seek pointer */
83 	dnode_phys_t	f_dnode;
84 	uint64_t	f_zap_type;	/* zap type for readdir */
85 	uint64_t	f_num_leafs;	/* number of fzap leaf blocks */
86 	zap_leaf_phys_t	*f_zap_leaf;	/* zap leaf buffer */
87 };
88 
89 static int	zfs_env_index;
90 static int	zfs_env_count;
91 
92 SLIST_HEAD(zfs_be_list, zfs_be_entry) zfs_be_head = SLIST_HEAD_INITIALIZER(zfs_be_head);
93 struct zfs_be_list *zfs_be_headp;
94 struct zfs_be_entry {
95 	const char *name;
96 	SLIST_ENTRY(zfs_be_entry) entries;
97 } *zfs_be, *zfs_be_tmp;
98 
99 /*
100  * Open a file.
101  */
102 static int
103 zfs_open(const char *upath, struct open_file *f)
104 {
105 	struct zfsmount *mount = (struct zfsmount *)f->f_devdata;
106 	struct file *fp;
107 	int rc;
108 
109 	if (f->f_dev != &zfs_dev)
110 		return (EINVAL);
111 
112 	/* allocate file system specific data structure */
113 	fp = malloc(sizeof(struct file));
114 	bzero(fp, sizeof(struct file));
115 	f->f_fsdata = (void *)fp;
116 
117 	rc = zfs_lookup(mount, upath, &fp->f_dnode);
118 	fp->f_seekp = 0;
119 	if (rc) {
120 		f->f_fsdata = NULL;
121 		free(fp);
122 	}
123 	return (rc);
124 }
125 
126 static int
127 zfs_close(struct open_file *f)
128 {
129 	struct file *fp = (struct file *)f->f_fsdata;
130 
131 	dnode_cache_obj = NULL;
132 	f->f_fsdata = (void *)0;
133 	if (fp == (struct file *)0)
134 		return (0);
135 
136 	free(fp);
137 	return (0);
138 }
139 
140 /*
141  * Copy a portion of a file into kernel memory.
142  * Cross block boundaries when necessary.
143  */
144 static int
145 zfs_read(struct open_file *f, void *start, size_t size, size_t *resid	/* out */)
146 {
147 	const spa_t *spa = ((struct zfsmount *)f->f_devdata)->spa;
148 	struct file *fp = (struct file *)f->f_fsdata;
149 	struct stat sb;
150 	size_t n;
151 	int rc;
152 
153 	rc = zfs_stat(f, &sb);
154 	if (rc)
155 		return (rc);
156 	n = size;
157 	if (fp->f_seekp + n > sb.st_size)
158 		n = sb.st_size - fp->f_seekp;
159 
160 	rc = dnode_read(spa, &fp->f_dnode, fp->f_seekp, start, n);
161 	if (rc)
162 		return (rc);
163 
164 	if (0) {
165 	    int i;
166 	    for (i = 0; i < n; i++)
167 		putchar(((char*) start)[i]);
168 	}
169 	fp->f_seekp += n;
170 	if (resid)
171 		*resid = size - n;
172 
173 	return (0);
174 }
175 
176 static off_t
177 zfs_seek(struct open_file *f, off_t offset, int where)
178 {
179 	struct file *fp = (struct file *)f->f_fsdata;
180 
181 	switch (where) {
182 	case SEEK_SET:
183 		fp->f_seekp = offset;
184 		break;
185 	case SEEK_CUR:
186 		fp->f_seekp += offset;
187 		break;
188 	case SEEK_END:
189 	    {
190 		struct stat sb;
191 		int error;
192 
193 		error = zfs_stat(f, &sb);
194 		if (error != 0) {
195 			errno = error;
196 			return (-1);
197 		}
198 		fp->f_seekp = sb.st_size - offset;
199 		break;
200 	    }
201 	default:
202 		errno = EINVAL;
203 		return (-1);
204 	}
205 	return (fp->f_seekp);
206 }
207 
208 static int
209 zfs_stat(struct open_file *f, struct stat *sb)
210 {
211 	const spa_t *spa = ((struct zfsmount *)f->f_devdata)->spa;
212 	struct file *fp = (struct file *)f->f_fsdata;
213 
214 	return (zfs_dnode_stat(spa, &fp->f_dnode, sb));
215 }
216 
217 static int
218 zfs_readdir(struct open_file *f, struct dirent *d)
219 {
220 	const spa_t *spa = ((struct zfsmount *)f->f_devdata)->spa;
221 	struct file *fp = (struct file *)f->f_fsdata;
222 	mzap_ent_phys_t mze;
223 	struct stat sb;
224 	size_t bsize = fp->f_dnode.dn_datablkszsec << SPA_MINBLOCKSHIFT;
225 	int rc;
226 
227 	rc = zfs_stat(f, &sb);
228 	if (rc)
229 		return (rc);
230 	if (!S_ISDIR(sb.st_mode))
231 		return (ENOTDIR);
232 
233 	/*
234 	 * If this is the first read, get the zap type.
235 	 */
236 	if (fp->f_seekp == 0) {
237 		rc = dnode_read(spa, &fp->f_dnode,
238 				0, &fp->f_zap_type, sizeof(fp->f_zap_type));
239 		if (rc)
240 			return (rc);
241 
242 		if (fp->f_zap_type == ZBT_MICRO) {
243 			fp->f_seekp = offsetof(mzap_phys_t, mz_chunk);
244 		} else {
245 			rc = dnode_read(spa, &fp->f_dnode,
246 					offsetof(zap_phys_t, zap_num_leafs),
247 					&fp->f_num_leafs,
248 					sizeof(fp->f_num_leafs));
249 			if (rc)
250 				return (rc);
251 
252 			fp->f_seekp = bsize;
253 			fp->f_zap_leaf = (zap_leaf_phys_t *)malloc(bsize);
254 			rc = dnode_read(spa, &fp->f_dnode,
255 					fp->f_seekp,
256 					fp->f_zap_leaf,
257 					bsize);
258 			if (rc)
259 				return (rc);
260 		}
261 	}
262 
263 	if (fp->f_zap_type == ZBT_MICRO) {
264 	mzap_next:
265 		if (fp->f_seekp >= bsize)
266 			return (ENOENT);
267 
268 		rc = dnode_read(spa, &fp->f_dnode,
269 				fp->f_seekp, &mze, sizeof(mze));
270 		if (rc)
271 			return (rc);
272 		fp->f_seekp += sizeof(mze);
273 
274 		if (!mze.mze_name[0])
275 			goto mzap_next;
276 
277 		d->d_fileno = ZFS_DIRENT_OBJ(mze.mze_value);
278 		d->d_type = ZFS_DIRENT_TYPE(mze.mze_value);
279 		strcpy(d->d_name, mze.mze_name);
280 		d->d_namlen = strlen(d->d_name);
281 		return (0);
282 	} else {
283 		zap_leaf_t zl;
284 		zap_leaf_chunk_t *zc, *nc;
285 		int chunk;
286 		size_t namelen;
287 		char *p;
288 		uint64_t value;
289 
290 		/*
291 		 * Initialise this so we can use the ZAP size
292 		 * calculating macros.
293 		 */
294 		zl.l_bs = ilog2(bsize);
295 		zl.l_phys = fp->f_zap_leaf;
296 
297 		/*
298 		 * Figure out which chunk we are currently looking at
299 		 * and consider seeking to the next leaf. We use the
300 		 * low bits of f_seekp as a simple chunk index.
301 		 */
302 	fzap_next:
303 		chunk = fp->f_seekp & (bsize - 1);
304 		if (chunk == ZAP_LEAF_NUMCHUNKS(&zl)) {
305 			fp->f_seekp = rounddown2(fp->f_seekp, bsize) + bsize;
306 			chunk = 0;
307 
308 			/*
309 			 * Check for EOF and read the new leaf.
310 			 */
311 			if (fp->f_seekp >= bsize * fp->f_num_leafs)
312 				return (ENOENT);
313 
314 			rc = dnode_read(spa, &fp->f_dnode,
315 					fp->f_seekp,
316 					fp->f_zap_leaf,
317 					bsize);
318 			if (rc)
319 				return (rc);
320 		}
321 
322 		zc = &ZAP_LEAF_CHUNK(&zl, chunk);
323 		fp->f_seekp++;
324 		if (zc->l_entry.le_type != ZAP_CHUNK_ENTRY)
325 			goto fzap_next;
326 
327 		namelen = zc->l_entry.le_name_numints;
328 		if (namelen > sizeof(d->d_name))
329 			namelen = sizeof(d->d_name);
330 
331 		/*
332 		 * Paste the name back together.
333 		 */
334 		nc = &ZAP_LEAF_CHUNK(&zl, zc->l_entry.le_name_chunk);
335 		p = d->d_name;
336 		while (namelen > 0) {
337 			int len;
338 			len = namelen;
339 			if (len > ZAP_LEAF_ARRAY_BYTES)
340 				len = ZAP_LEAF_ARRAY_BYTES;
341 			memcpy(p, nc->l_array.la_array, len);
342 			p += len;
343 			namelen -= len;
344 			nc = &ZAP_LEAF_CHUNK(&zl, nc->l_array.la_next);
345 		}
346 		d->d_name[sizeof(d->d_name) - 1] = 0;
347 
348 		/*
349 		 * Assume the first eight bytes of the value are
350 		 * a uint64_t.
351 		 */
352 		value = fzap_leaf_value(&zl, zc);
353 
354 		d->d_fileno = ZFS_DIRENT_OBJ(value);
355 		d->d_type = ZFS_DIRENT_TYPE(value);
356 		d->d_namlen = strlen(d->d_name);
357 
358 		return (0);
359 	}
360 }
361 
362 static int
363 vdev_read(vdev_t *vdev, void *priv, off_t offset, void *buf, size_t bytes)
364 {
365 	int fd, ret;
366 	size_t res, size, remainder, rb_size, blksz;
367 	unsigned secsz;
368 	off_t off;
369 	char *bouncebuf, *rb_buf;
370 
371 	fd = (uintptr_t) priv;
372 	bouncebuf = NULL;
373 
374 	ret = ioctl(fd, DIOCGSECTORSIZE, &secsz);
375 	if (ret != 0)
376 		return (ret);
377 
378 	off = offset / secsz;
379 	remainder = offset % secsz;
380 	if (lseek(fd, off * secsz, SEEK_SET) == -1)
381 		return (errno);
382 
383 	rb_buf = buf;
384 	rb_size = bytes;
385 	size = roundup2(bytes + remainder, secsz);
386 	blksz = size;
387 	if (remainder != 0 || size != bytes) {
388 		bouncebuf = zfs_alloc(secsz);
389 		if (bouncebuf == NULL) {
390 			printf("vdev_read: out of memory\n");
391 			return (ENOMEM);
392 		}
393 		rb_buf = bouncebuf;
394 		blksz = rb_size - remainder;
395 	}
396 
397 	while (bytes > 0) {
398 		res = read(fd, rb_buf, rb_size);
399 		if (res != rb_size) {
400 			ret = EIO;
401 			goto error;
402 		}
403 		if (bytes < blksz)
404 			blksz = bytes;
405 		if (bouncebuf != NULL)
406 			memcpy(buf, rb_buf + remainder, blksz);
407 		buf = (void *)((uintptr_t)buf + blksz);
408 		bytes -= blksz;
409 		remainder = 0;
410 		blksz = rb_size;
411 	}
412 
413 	ret = 0;
414 error:
415 	if (bouncebuf != NULL)
416 		zfs_free(bouncebuf, secsz);
417 	return (ret);
418 }
419 
420 static int
421 zfs_dev_init(void)
422 {
423 	spa_t *spa;
424 	spa_t *next;
425 	spa_t *prev;
426 
427 	zfs_init();
428 	if (archsw.arch_zfs_probe == NULL)
429 		return (ENXIO);
430 	archsw.arch_zfs_probe();
431 
432 	prev = NULL;
433 	spa = STAILQ_FIRST(&zfs_pools);
434 	while (spa != NULL) {
435 		next = STAILQ_NEXT(spa, spa_link);
436 		if (zfs_spa_init(spa)) {
437 			if (prev == NULL)
438 				STAILQ_REMOVE_HEAD(&zfs_pools, spa_link);
439 			else
440 				STAILQ_REMOVE_AFTER(&zfs_pools, prev, spa_link);
441 		} else
442 			prev = spa;
443 		spa = next;
444 	}
445 	return (0);
446 }
447 
448 struct zfs_probe_args {
449 	int		fd;
450 	const char	*devname;
451 	uint64_t	*pool_guid;
452 	u_int		secsz;
453 };
454 
455 static int
456 zfs_diskread(void *arg, void *buf, size_t blocks, uint64_t offset)
457 {
458 	struct zfs_probe_args *ppa;
459 
460 	ppa = (struct zfs_probe_args *)arg;
461 	return (vdev_read(NULL, (void *)(uintptr_t)ppa->fd,
462 	    offset * ppa->secsz, buf, blocks * ppa->secsz));
463 }
464 
465 static int
466 zfs_probe(int fd, uint64_t *pool_guid)
467 {
468 	spa_t *spa;
469 	int ret;
470 
471 	spa = NULL;
472 	ret = vdev_probe(vdev_read, (void *)(uintptr_t)fd, &spa);
473 	if (ret == 0 && pool_guid != NULL)
474 		*pool_guid = spa->spa_guid;
475 	return (ret);
476 }
477 
478 static int
479 zfs_probe_partition(void *arg, const char *partname,
480     const struct ptable_entry *part)
481 {
482 	struct zfs_probe_args *ppa, pa;
483 	struct ptable *table;
484 	char devname[32];
485 	int ret;
486 
487 	/* Probe only freebsd-zfs and freebsd partitions */
488 	if (part->type != PART_FREEBSD &&
489 	    part->type != PART_FREEBSD_ZFS)
490 		return (0);
491 
492 	ppa = (struct zfs_probe_args *)arg;
493 	strncpy(devname, ppa->devname, strlen(ppa->devname) - 1);
494 	devname[strlen(ppa->devname) - 1] = '\0';
495 	sprintf(devname, "%s%s:", devname, partname);
496 	pa.fd = open(devname, O_RDONLY);
497 	if (pa.fd == -1)
498 		return (0);
499 	ret = zfs_probe(pa.fd, ppa->pool_guid);
500 	if (ret == 0)
501 		return (0);
502 	/* Do we have BSD label here? */
503 	if (part->type == PART_FREEBSD) {
504 		pa.devname = devname;
505 		pa.pool_guid = ppa->pool_guid;
506 		pa.secsz = ppa->secsz;
507 		table = ptable_open(&pa, part->end - part->start + 1,
508 		    ppa->secsz, zfs_diskread);
509 		if (table != NULL) {
510 			ptable_iterate(table, &pa, zfs_probe_partition);
511 			ptable_close(table);
512 		}
513 	}
514 	close(pa.fd);
515 	return (0);
516 }
517 
518 int
519 zfs_probe_dev(const char *devname, uint64_t *pool_guid)
520 {
521 	struct disk_devdesc *dev;
522 	struct ptable *table;
523 	struct zfs_probe_args pa;
524 	uint64_t mediasz;
525 	int ret;
526 
527 	if (pool_guid)
528 		*pool_guid = 0;
529 	pa.fd = open(devname, O_RDONLY);
530 	if (pa.fd == -1)
531 		return (ENXIO);
532 	/*
533 	 * We will not probe the whole disk, we can not boot from such
534 	 * disks and some systems will misreport the disk sizes and will
535 	 * hang while accessing the disk.
536 	 */
537 	if (archsw.arch_getdev((void **)&dev, devname, NULL) == 0) {
538 		int partition = dev->d_partition;
539 		int slice = dev->d_slice;
540 
541 		free(dev);
542 		if (partition != -1 && slice != -1) {
543 			ret = zfs_probe(pa.fd, pool_guid);
544 			if (ret == 0)
545 				return (0);
546 		}
547 	}
548 
549 	/* Probe each partition */
550 	ret = ioctl(pa.fd, DIOCGMEDIASIZE, &mediasz);
551 	if (ret == 0)
552 		ret = ioctl(pa.fd, DIOCGSECTORSIZE, &pa.secsz);
553 	if (ret == 0) {
554 		pa.devname = devname;
555 		pa.pool_guid = pool_guid;
556 		table = ptable_open(&pa, mediasz / pa.secsz, pa.secsz,
557 		    zfs_diskread);
558 		if (table != NULL) {
559 			ptable_iterate(table, &pa, zfs_probe_partition);
560 			ptable_close(table);
561 		}
562 	}
563 	close(pa.fd);
564 	if (pool_guid && *pool_guid == 0)
565 		ret = ENXIO;
566 	return (ret);
567 }
568 
569 /*
570  * Print information about ZFS pools
571  */
572 static int
573 zfs_dev_print(int verbose)
574 {
575 	spa_t *spa;
576 	char line[80];
577 	int ret = 0;
578 
579 	if (STAILQ_EMPTY(&zfs_pools))
580 		return (0);
581 
582 	printf("%s devices:", zfs_dev.dv_name);
583 	if ((ret = pager_output("\n")) != 0)
584 		return (ret);
585 
586 	if (verbose) {
587 		return (spa_all_status());
588 	}
589 	STAILQ_FOREACH(spa, &zfs_pools, spa_link) {
590 		snprintf(line, sizeof(line), "    zfs:%s\n", spa->spa_name);
591 		ret = pager_output(line);
592 		if (ret != 0)
593 			break;
594 	}
595 	return (ret);
596 }
597 
598 /*
599  * Attempt to open the pool described by (dev) for use by (f).
600  */
601 static int
602 zfs_dev_open(struct open_file *f, ...)
603 {
604 	va_list		args;
605 	struct zfs_devdesc	*dev;
606 	struct zfsmount	*mount;
607 	spa_t		*spa;
608 	int		rv;
609 
610 	va_start(args, f);
611 	dev = va_arg(args, struct zfs_devdesc *);
612 	va_end(args);
613 
614 	if (dev->pool_guid == 0)
615 		spa = STAILQ_FIRST(&zfs_pools);
616 	else
617 		spa = spa_find_by_guid(dev->pool_guid);
618 	if (!spa)
619 		return (ENXIO);
620 	mount = malloc(sizeof(*mount));
621 	rv = zfs_mount(spa, dev->root_guid, mount);
622 	if (rv != 0) {
623 		free(mount);
624 		return (rv);
625 	}
626 	if (mount->objset.os_type != DMU_OST_ZFS) {
627 		printf("Unexpected object set type %ju\n",
628 		    (uintmax_t)mount->objset.os_type);
629 		free(mount);
630 		return (EIO);
631 	}
632 	f->f_devdata = mount;
633 	free(dev);
634 	return (0);
635 }
636 
637 static int
638 zfs_dev_close(struct open_file *f)
639 {
640 
641 	free(f->f_devdata);
642 	f->f_devdata = NULL;
643 	return (0);
644 }
645 
646 static int
647 zfs_dev_strategy(void *devdata, int rw, daddr_t dblk, size_t size, char *buf, size_t *rsize)
648 {
649 
650 	return (ENOSYS);
651 }
652 
653 struct devsw zfs_dev = {
654 	.dv_name = "zfs",
655 	.dv_type = DEVT_ZFS,
656 	.dv_init = zfs_dev_init,
657 	.dv_strategy = zfs_dev_strategy,
658 	.dv_open = zfs_dev_open,
659 	.dv_close = zfs_dev_close,
660 	.dv_ioctl = noioctl,
661 	.dv_print = zfs_dev_print,
662 	.dv_cleanup = NULL
663 };
664 
665 int
666 zfs_parsedev(struct zfs_devdesc *dev, const char *devspec, const char **path)
667 {
668 	static char	rootname[ZFS_MAXNAMELEN];
669 	static char	poolname[ZFS_MAXNAMELEN];
670 	spa_t		*spa;
671 	const char	*end;
672 	const char	*np;
673 	const char	*sep;
674 	int		rv;
675 
676 	np = devspec;
677 	if (*np != ':')
678 		return (EINVAL);
679 	np++;
680 	end = strrchr(np, ':');
681 	if (end == NULL)
682 		return (EINVAL);
683 	sep = strchr(np, '/');
684 	if (sep == NULL || sep >= end)
685 		sep = end;
686 	memcpy(poolname, np, sep - np);
687 	poolname[sep - np] = '\0';
688 	if (sep < end) {
689 		sep++;
690 		memcpy(rootname, sep, end - sep);
691 		rootname[end - sep] = '\0';
692 	}
693 	else
694 		rootname[0] = '\0';
695 
696 	spa = spa_find_by_name(poolname);
697 	if (!spa)
698 		return (ENXIO);
699 	dev->pool_guid = spa->spa_guid;
700 	rv = zfs_lookup_dataset(spa, rootname, &dev->root_guid);
701 	if (rv != 0)
702 		return (rv);
703 	if (path != NULL)
704 		*path = (*end == '\0') ? end : end + 1;
705 	dev->dd.d_dev = &zfs_dev;
706 	return (0);
707 }
708 
709 char *
710 zfs_fmtdev(void *vdev)
711 {
712 	static char		rootname[ZFS_MAXNAMELEN];
713 	static char		buf[2 * ZFS_MAXNAMELEN + 8];
714 	struct zfs_devdesc	*dev = (struct zfs_devdesc *)vdev;
715 	spa_t			*spa;
716 
717 	buf[0] = '\0';
718 	if (dev->dd.d_dev->dv_type != DEVT_ZFS)
719 		return (buf);
720 
721 	if (dev->pool_guid == 0) {
722 		spa = STAILQ_FIRST(&zfs_pools);
723 		dev->pool_guid = spa->spa_guid;
724 	} else
725 		spa = spa_find_by_guid(dev->pool_guid);
726 	if (spa == NULL) {
727 		printf("ZFS: can't find pool by guid\n");
728 		return (buf);
729 	}
730 	if (dev->root_guid == 0 && zfs_get_root(spa, &dev->root_guid)) {
731 		printf("ZFS: can't find root filesystem\n");
732 		return (buf);
733 	}
734 	if (zfs_rlookup(spa, dev->root_guid, rootname)) {
735 		printf("ZFS: can't find filesystem by guid\n");
736 		return (buf);
737 	}
738 
739 	if (rootname[0] == '\0')
740 		sprintf(buf, "%s:%s:", dev->dd.d_dev->dv_name, spa->spa_name);
741 	else
742 		sprintf(buf, "%s:%s/%s:", dev->dd.d_dev->dv_name, spa->spa_name,
743 		    rootname);
744 	return (buf);
745 }
746 
747 int
748 zfs_list(const char *name)
749 {
750 	static char	poolname[ZFS_MAXNAMELEN];
751 	uint64_t	objid;
752 	spa_t		*spa;
753 	const char	*dsname;
754 	int		len;
755 	int		rv;
756 
757 	len = strlen(name);
758 	dsname = strchr(name, '/');
759 	if (dsname != NULL) {
760 		len = dsname - name;
761 		dsname++;
762 	} else
763 		dsname = "";
764 	memcpy(poolname, name, len);
765 	poolname[len] = '\0';
766 
767 	spa = spa_find_by_name(poolname);
768 	if (!spa)
769 		return (ENXIO);
770 	rv = zfs_lookup_dataset(spa, dsname, &objid);
771 	if (rv != 0)
772 		return (rv);
773 
774 	return (zfs_list_dataset(spa, objid));
775 }
776 
777 void
778 init_zfs_bootenv(const char *currdev_in)
779 {
780 	char *beroot, *currdev;
781 	int currdev_len;
782 
783 	currdev = NULL;
784 	currdev_len = strlen(currdev_in);
785 	if (currdev_len == 0)
786 		return;
787 	if (strncmp(currdev_in, "zfs:", 4) != 0)
788 		return;
789 	currdev = strdup(currdev_in);
790 	if (currdev == NULL)
791 		return;
792 	/* Remove the trailing : */
793 	currdev[currdev_len - 1] = '\0';
794 	setenv("zfs_be_active", currdev, 1);
795 	setenv("zfs_be_currpage", "1", 1);
796 	/* Remove the last element (current bootenv) */
797 	beroot = strrchr(currdev, '/');
798 	if (beroot != NULL)
799 		beroot[0] = '\0';
800 	beroot = strchr(currdev, ':') + 1;
801 	setenv("zfs_be_root", beroot, 1);
802 	zfs_bootenv_initial(beroot);
803 	free(currdev);
804 }
805 
806 static void
807 zfs_bootenv_initial(const char *name)
808 {
809 	char		poolname[ZFS_MAXNAMELEN], *dsname;
810 	char envname[32], envval[256];
811 	uint64_t	objid;
812 	spa_t		*spa;
813 	int		bootenvs_idx, len, rv;
814 
815 	SLIST_INIT(&zfs_be_head);
816 	zfs_env_count = 0;
817 	len = strlen(name);
818 	dsname = strchr(name, '/');
819 	if (dsname != NULL) {
820 		len = dsname - name;
821 		dsname++;
822 	} else
823 		dsname = "";
824 	strlcpy(poolname, name, len + 1);
825 	spa = spa_find_by_name(poolname);
826 	if (spa == NULL)
827 		return;
828 	rv = zfs_lookup_dataset(spa, dsname, &objid);
829 	if (rv != 0)
830 		return;
831 	rv = zfs_callback_dataset(spa, objid, zfs_belist_add);
832 	bootenvs_idx = 0;
833 	/* Populate the initial environment variables */
834 	SLIST_FOREACH_SAFE(zfs_be, &zfs_be_head, entries, zfs_be_tmp) {
835 		/* Enumerate all bootenvs for general usage */
836 		snprintf(envname, sizeof(envname), "bootenvs[%d]", bootenvs_idx);
837 		snprintf(envval, sizeof(envval), "zfs:%s/%s", name, zfs_be->name);
838 		rv = setenv(envname, envval, 1);
839 		if (rv != 0)
840 			break;
841 		bootenvs_idx++;
842 	}
843 	snprintf(envval, sizeof(envval), "%d", bootenvs_idx);
844 	setenv("bootenvs_count", envval, 1);
845 
846 	/* Clean up the SLIST of ZFS BEs */
847 	while (!SLIST_EMPTY(&zfs_be_head)) {
848 		zfs_be = SLIST_FIRST(&zfs_be_head);
849 		SLIST_REMOVE_HEAD(&zfs_be_head, entries);
850 		free(zfs_be);
851 	}
852 
853 	return;
854 
855 }
856 
857 int
858 zfs_bootenv(const char *name)
859 {
860 	static char	poolname[ZFS_MAXNAMELEN], *dsname, *root;
861 	char		becount[4];
862 	uint64_t	objid;
863 	spa_t		*spa;
864 	int		len, rv, pages, perpage, currpage;
865 
866 	if (name == NULL)
867 		return (EINVAL);
868 	if ((root = getenv("zfs_be_root")) == NULL)
869 		return (EINVAL);
870 
871 	if (strcmp(name, root) != 0) {
872 		if (setenv("zfs_be_root", name, 1) != 0)
873 			return (ENOMEM);
874 	}
875 
876 	SLIST_INIT(&zfs_be_head);
877 	zfs_env_count = 0;
878 	len = strlen(name);
879 	dsname = strchr(name, '/');
880 	if (dsname != NULL) {
881 		len = dsname - name;
882 		dsname++;
883 	} else
884 		dsname = "";
885 	memcpy(poolname, name, len);
886 	poolname[len] = '\0';
887 
888 	spa = spa_find_by_name(poolname);
889 	if (!spa)
890 		return (ENXIO);
891 	rv = zfs_lookup_dataset(spa, dsname, &objid);
892 	if (rv != 0)
893 		return (rv);
894 	rv = zfs_callback_dataset(spa, objid, zfs_belist_add);
895 
896 	/* Calculate and store the number of pages of BEs */
897 	perpage = (ZFS_BE_LAST - ZFS_BE_FIRST + 1);
898 	pages = (zfs_env_count / perpage) + ((zfs_env_count % perpage) > 0 ? 1 : 0);
899 	snprintf(becount, 4, "%d", pages);
900 	if (setenv("zfs_be_pages", becount, 1) != 0)
901 		return (ENOMEM);
902 
903 	/* Roll over the page counter if it has exceeded the maximum */
904 	currpage = strtol(getenv("zfs_be_currpage"), NULL, 10);
905 	if (currpage > pages) {
906 		if (setenv("zfs_be_currpage", "1", 1) != 0)
907 			return (ENOMEM);
908 	}
909 
910 	/* Populate the menu environment variables */
911 	zfs_set_env();
912 
913 	/* Clean up the SLIST of ZFS BEs */
914 	while (!SLIST_EMPTY(&zfs_be_head)) {
915 		zfs_be = SLIST_FIRST(&zfs_be_head);
916 		SLIST_REMOVE_HEAD(&zfs_be_head, entries);
917 		free(zfs_be);
918 	}
919 
920 	return (rv);
921 }
922 
923 int
924 zfs_belist_add(const char *name, uint64_t value __unused)
925 {
926 
927 	/* Skip special datasets that start with a $ character */
928 	if (strncmp(name, "$", 1) == 0) {
929 		return (0);
930 	}
931 	/* Add the boot environment to the head of the SLIST */
932 	zfs_be = malloc(sizeof(struct zfs_be_entry));
933 	if (zfs_be == NULL) {
934 		return (ENOMEM);
935 	}
936 	zfs_be->name = name;
937 	SLIST_INSERT_HEAD(&zfs_be_head, zfs_be, entries);
938 	zfs_env_count++;
939 
940 	return (0);
941 }
942 
943 int
944 zfs_set_env(void)
945 {
946 	char envname[32], envval[256];
947 	char *beroot, *pagenum;
948 	int rv, page, ctr;
949 
950 	beroot = getenv("zfs_be_root");
951 	if (beroot == NULL) {
952 		return (1);
953 	}
954 
955 	pagenum = getenv("zfs_be_currpage");
956 	if (pagenum != NULL) {
957 		page = strtol(pagenum, NULL, 10);
958 	} else {
959 		page = 1;
960 	}
961 
962 	ctr = 1;
963 	rv = 0;
964 	zfs_env_index = ZFS_BE_FIRST;
965 	SLIST_FOREACH_SAFE(zfs_be, &zfs_be_head, entries, zfs_be_tmp) {
966 		/* Skip to the requested page number */
967 		if (ctr <= ((ZFS_BE_LAST - ZFS_BE_FIRST + 1) * (page - 1))) {
968 			ctr++;
969 			continue;
970 		}
971 
972 		snprintf(envname, sizeof(envname), "bootenvmenu_caption[%d]", zfs_env_index);
973 		snprintf(envval, sizeof(envval), "%s", zfs_be->name);
974 		rv = setenv(envname, envval, 1);
975 		if (rv != 0) {
976 			break;
977 		}
978 
979 		snprintf(envname, sizeof(envname), "bootenvansi_caption[%d]", zfs_env_index);
980 		rv = setenv(envname, envval, 1);
981 		if (rv != 0){
982 			break;
983 		}
984 
985 		snprintf(envname, sizeof(envname), "bootenvmenu_command[%d]", zfs_env_index);
986 		rv = setenv(envname, "set_bootenv", 1);
987 		if (rv != 0){
988 			break;
989 		}
990 
991 		snprintf(envname, sizeof(envname), "bootenv_root[%d]", zfs_env_index);
992 		snprintf(envval, sizeof(envval), "zfs:%s/%s", beroot, zfs_be->name);
993 		rv = setenv(envname, envval, 1);
994 		if (rv != 0){
995 			break;
996 		}
997 
998 		zfs_env_index++;
999 		if (zfs_env_index > ZFS_BE_LAST) {
1000 			break;
1001 		}
1002 
1003 	}
1004 
1005 	for (; zfs_env_index <= ZFS_BE_LAST; zfs_env_index++) {
1006 		snprintf(envname, sizeof(envname), "bootenvmenu_caption[%d]", zfs_env_index);
1007 		(void)unsetenv(envname);
1008 		snprintf(envname, sizeof(envname), "bootenvansi_caption[%d]", zfs_env_index);
1009 		(void)unsetenv(envname);
1010 		snprintf(envname, sizeof(envname), "bootenvmenu_command[%d]", zfs_env_index);
1011 		(void)unsetenv(envname);
1012 		snprintf(envname, sizeof(envname), "bootenv_root[%d]", zfs_env_index);
1013 		(void)unsetenv(envname);
1014 	}
1015 
1016 	return (rv);
1017 }
1018