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