]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - stand/zfs/zfs.c
MFC r325834,r325997,326502: Move sys/boot to stand/
[FreeBSD/FreeBSD.git] / stand / zfs / zfs.c
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 <sys/disk.h>
37 #include <sys/param.h>
38 #include <sys/time.h>
39 #include <sys/queue.h>
40 #include <part.h>
41 #include <stddef.h>
42 #include <stdarg.h>
43 #include <string.h>
44 #include <stand.h>
45 #include <bootstrap.h>
46
47 #include "libzfs.h"
48
49 #include "zfsimpl.c"
50
51 /* Define the range of indexes to be populated with ZFS Boot Environments */
52 #define         ZFS_BE_FIRST    4
53 #define         ZFS_BE_LAST     8
54
55 static int      zfs_open(const char *path, struct open_file *f);
56 static int      zfs_write(struct open_file *f, void *buf, size_t size, size_t *resid);
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 struct devsw zfs_dev;
64
65 struct fs_ops zfs_fsops = {
66         "zfs",
67         zfs_open,
68         zfs_close,
69         zfs_read,
70         zfs_write,
71         zfs_seek,
72         zfs_stat,
73         zfs_readdir
74 };
75
76 /*
77  * In-core open file.
78  */
79 struct file {
80         off_t           f_seekp;        /* seek pointer */
81         dnode_phys_t    f_dnode;
82         uint64_t        f_zap_type;     /* zap type for readdir */
83         uint64_t        f_num_leafs;    /* number of fzap leaf blocks */
84         zap_leaf_phys_t *f_zap_leaf;    /* zap leaf buffer */
85 };
86
87 static int      zfs_env_index;
88 static int      zfs_env_count;
89
90 SLIST_HEAD(zfs_be_list, zfs_be_entry) zfs_be_head = SLIST_HEAD_INITIALIZER(zfs_be_head);
91 struct zfs_be_list *zfs_be_headp;
92 struct 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  */
100 static int
101 zfs_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
124 static int
125 zfs_close(struct open_file *f)
126 {
127         struct file *fp = (struct file *)f->f_fsdata;
128
129         dnode_cache_obj = NULL;
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  */
142 static int
143 zfs_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
174 /*
175  * Don't be silly - the bootstrap has no business writing anything.
176  */
177 static int
178 zfs_write(struct open_file *f, void *start, size_t size, size_t *resid  /* out */)
179 {
180
181         return (EROFS);
182 }
183
184 static off_t
185 zfs_seek(struct open_file *f, off_t offset, int where)
186 {
187         struct file *fp = (struct file *)f->f_fsdata;
188
189         switch (where) {
190         case SEEK_SET:
191                 fp->f_seekp = offset;
192                 break;
193         case SEEK_CUR:
194                 fp->f_seekp += offset;
195                 break;
196         case SEEK_END:
197             {
198                 struct stat sb;
199                 int error;
200
201                 error = zfs_stat(f, &sb);
202                 if (error != 0) {
203                         errno = error;
204                         return (-1);
205                 }
206                 fp->f_seekp = sb.st_size - offset;
207                 break;
208             }
209         default:
210                 errno = EINVAL;
211                 return (-1);
212         }
213         return (fp->f_seekp);
214 }
215
216 static int
217 zfs_stat(struct open_file *f, struct stat *sb)
218 {
219         const spa_t *spa = ((struct zfsmount *)f->f_devdata)->spa;
220         struct file *fp = (struct file *)f->f_fsdata;
221
222         return (zfs_dnode_stat(spa, &fp->f_dnode, sb));
223 }
224
225 static int
226 zfs_readdir(struct open_file *f, struct dirent *d)
227 {
228         const spa_t *spa = ((struct zfsmount *)f->f_devdata)->spa;
229         struct file *fp = (struct file *)f->f_fsdata;
230         mzap_ent_phys_t mze;
231         struct stat sb;
232         size_t bsize = fp->f_dnode.dn_datablkszsec << SPA_MINBLOCKSHIFT;
233         int rc;
234
235         rc = zfs_stat(f, &sb);
236         if (rc)
237                 return (rc);
238         if (!S_ISDIR(sb.st_mode))
239                 return (ENOTDIR);
240
241         /*
242          * If this is the first read, get the zap type.
243          */
244         if (fp->f_seekp == 0) {
245                 rc = dnode_read(spa, &fp->f_dnode,
246                                 0, &fp->f_zap_type, sizeof(fp->f_zap_type));
247                 if (rc)
248                         return (rc);
249
250                 if (fp->f_zap_type == ZBT_MICRO) {
251                         fp->f_seekp = offsetof(mzap_phys_t, mz_chunk);
252                 } else {
253                         rc = dnode_read(spa, &fp->f_dnode,
254                                         offsetof(zap_phys_t, zap_num_leafs),
255                                         &fp->f_num_leafs,
256                                         sizeof(fp->f_num_leafs));
257                         if (rc)
258                                 return (rc);
259
260                         fp->f_seekp = bsize;
261                         fp->f_zap_leaf = (zap_leaf_phys_t *)malloc(bsize);
262                         rc = dnode_read(spa, &fp->f_dnode,
263                                         fp->f_seekp,
264                                         fp->f_zap_leaf,
265                                         bsize);
266                         if (rc)
267                                 return (rc);
268                 }
269         }
270
271         if (fp->f_zap_type == ZBT_MICRO) {
272         mzap_next:
273                 if (fp->f_seekp >= bsize)
274                         return (ENOENT);
275
276                 rc = dnode_read(spa, &fp->f_dnode,
277                                 fp->f_seekp, &mze, sizeof(mze));
278                 if (rc)
279                         return (rc);
280                 fp->f_seekp += sizeof(mze);
281
282                 if (!mze.mze_name[0])
283                         goto mzap_next;
284
285                 d->d_fileno = ZFS_DIRENT_OBJ(mze.mze_value);
286                 d->d_type = ZFS_DIRENT_TYPE(mze.mze_value);
287                 strcpy(d->d_name, mze.mze_name);
288                 d->d_namlen = strlen(d->d_name);
289                 return (0);
290         } else {
291                 zap_leaf_t zl;
292                 zap_leaf_chunk_t *zc, *nc;
293                 int chunk;
294                 size_t namelen;
295                 char *p;
296                 uint64_t value;
297
298                 /*
299                  * Initialise this so we can use the ZAP size
300                  * calculating macros.
301                  */
302                 zl.l_bs = ilog2(bsize);
303                 zl.l_phys = fp->f_zap_leaf;
304
305                 /*
306                  * Figure out which chunk we are currently looking at
307                  * and consider seeking to the next leaf. We use the
308                  * low bits of f_seekp as a simple chunk index.
309                  */
310         fzap_next:
311                 chunk = fp->f_seekp & (bsize - 1);
312                 if (chunk == ZAP_LEAF_NUMCHUNKS(&zl)) {
313                         fp->f_seekp = rounddown2(fp->f_seekp, bsize) + bsize;
314                         chunk = 0;
315
316                         /*
317                          * Check for EOF and read the new leaf.
318                          */
319                         if (fp->f_seekp >= bsize * fp->f_num_leafs)
320                                 return (ENOENT);
321
322                         rc = dnode_read(spa, &fp->f_dnode,
323                                         fp->f_seekp,
324                                         fp->f_zap_leaf,
325                                         bsize);
326                         if (rc)
327                                 return (rc);
328                 }
329
330                 zc = &ZAP_LEAF_CHUNK(&zl, chunk);
331                 fp->f_seekp++;
332                 if (zc->l_entry.le_type != ZAP_CHUNK_ENTRY)
333                         goto fzap_next;
334
335                 namelen = zc->l_entry.le_name_numints;
336                 if (namelen > sizeof(d->d_name))
337                         namelen = sizeof(d->d_name);
338
339                 /*
340                  * Paste the name back together.
341                  */
342                 nc = &ZAP_LEAF_CHUNK(&zl, zc->l_entry.le_name_chunk);
343                 p = d->d_name;
344                 while (namelen > 0) {
345                         int len;
346                         len = namelen;
347                         if (len > ZAP_LEAF_ARRAY_BYTES)
348                                 len = ZAP_LEAF_ARRAY_BYTES;
349                         memcpy(p, nc->l_array.la_array, len);
350                         p += len;
351                         namelen -= len;
352                         nc = &ZAP_LEAF_CHUNK(&zl, nc->l_array.la_next);
353                 }
354                 d->d_name[sizeof(d->d_name) - 1] = 0;
355
356                 /*
357                  * Assume the first eight bytes of the value are
358                  * a uint64_t.
359                  */
360                 value = fzap_leaf_value(&zl, zc);
361
362                 d->d_fileno = ZFS_DIRENT_OBJ(value);
363                 d->d_type = ZFS_DIRENT_TYPE(value);
364                 d->d_namlen = strlen(d->d_name);
365
366                 return (0);
367         }
368 }
369
370 static int
371 vdev_read(vdev_t *vdev, void *priv, off_t offset, void *buf, size_t bytes)
372 {
373         int fd, ret;
374         size_t res, size, remainder, rb_size, blksz;
375         unsigned secsz;
376         off_t off;
377         char *bouncebuf, *rb_buf;
378
379         fd = (uintptr_t) priv;
380         bouncebuf = NULL;
381
382         ret = ioctl(fd, DIOCGSECTORSIZE, &secsz);
383         if (ret != 0)
384                 return (ret);
385
386         off = offset / secsz;
387         remainder = offset % secsz;
388         if (lseek(fd, off * secsz, SEEK_SET) == -1)
389                 return (errno);
390
391         rb_buf = buf;
392         rb_size = bytes;
393         size = roundup2(bytes + remainder, secsz);
394         blksz = size;
395         if (remainder != 0 || size != bytes) {
396                 bouncebuf = zfs_alloc(secsz);
397                 if (bouncebuf == NULL) {
398                         printf("vdev_read: out of memory\n");
399                         return (ENOMEM);
400                 }
401                 rb_buf = bouncebuf;
402                 blksz = rb_size - remainder;
403         }
404
405         while (bytes > 0) {
406                 res = read(fd, rb_buf, rb_size);
407                 if (res != rb_size) {
408                         ret = EIO;
409                         goto error;
410                 }
411                 if (bytes < blksz)
412                         blksz = bytes;
413                 if (bouncebuf != NULL)
414                         memcpy(buf, rb_buf + remainder, blksz);
415                 buf = (void *)((uintptr_t)buf + blksz);
416                 bytes -= blksz;
417                 remainder = 0;
418                 blksz = rb_size;
419         }
420
421         ret = 0;
422 error:
423         if (bouncebuf != NULL)
424                 zfs_free(bouncebuf, secsz);
425         return (ret);
426 }
427
428 static int
429 zfs_dev_init(void)
430 {
431         spa_t *spa;
432         spa_t *next;
433         spa_t *prev;
434
435         zfs_init();
436         if (archsw.arch_zfs_probe == NULL)
437                 return (ENXIO);
438         archsw.arch_zfs_probe();
439
440         prev = NULL;
441         spa = STAILQ_FIRST(&zfs_pools);
442         while (spa != NULL) {
443                 next = STAILQ_NEXT(spa, spa_link);
444                 if (zfs_spa_init(spa)) {
445                         if (prev == NULL)
446                                 STAILQ_REMOVE_HEAD(&zfs_pools, spa_link);
447                         else
448                                 STAILQ_REMOVE_AFTER(&zfs_pools, prev, spa_link);
449                 } else
450                         prev = spa;
451                 spa = next;
452         }
453         return (0);
454 }
455
456 struct zfs_probe_args {
457         int             fd;
458         const char      *devname;
459         uint64_t        *pool_guid;
460         u_int           secsz;
461 };
462
463 static int
464 zfs_diskread(void *arg, void *buf, size_t blocks, uint64_t offset)
465 {
466         struct zfs_probe_args *ppa;
467
468         ppa = (struct zfs_probe_args *)arg;
469         return (vdev_read(NULL, (void *)(uintptr_t)ppa->fd,
470             offset * ppa->secsz, buf, blocks * ppa->secsz));
471 }
472
473 static int
474 zfs_probe(int fd, uint64_t *pool_guid)
475 {
476         spa_t *spa;
477         int ret;
478
479         ret = vdev_probe(vdev_read, (void *)(uintptr_t)fd, &spa);
480         if (ret == 0 && pool_guid != NULL)
481                 *pool_guid = spa->spa_guid;
482         return (ret);
483 }
484
485 static int
486 zfs_probe_partition(void *arg, const char *partname,
487     const struct ptable_entry *part)
488 {
489         struct zfs_probe_args *ppa, pa;
490         struct ptable *table;
491         char devname[32];
492         int ret;
493
494         /* Probe only freebsd-zfs and freebsd partitions */
495         if (part->type != PART_FREEBSD &&
496             part->type != PART_FREEBSD_ZFS)
497                 return (0);
498
499         ppa = (struct zfs_probe_args *)arg;
500         strncpy(devname, ppa->devname, strlen(ppa->devname) - 1);
501         devname[strlen(ppa->devname) - 1] = '\0';
502         sprintf(devname, "%s%s:", devname, partname);
503         pa.fd = open(devname, O_RDONLY);
504         if (pa.fd == -1)
505                 return (0);
506         ret = zfs_probe(pa.fd, ppa->pool_guid);
507         if (ret == 0)
508                 return (0);
509         /* Do we have BSD label here? */
510         if (part->type == PART_FREEBSD) {
511                 pa.devname = devname;
512                 pa.pool_guid = ppa->pool_guid;
513                 pa.secsz = ppa->secsz;
514                 table = ptable_open(&pa, part->end - part->start + 1,
515                     ppa->secsz, zfs_diskread);
516                 if (table != NULL) {
517                         ptable_iterate(table, &pa, zfs_probe_partition);
518                         ptable_close(table);
519                 }
520         }
521         close(pa.fd);
522         return (0);
523 }
524
525 int
526 zfs_probe_dev(const char *devname, uint64_t *pool_guid)
527 {
528         struct ptable *table;
529         struct zfs_probe_args pa;
530         uint64_t mediasz;
531         int ret;
532
533         if (pool_guid)
534                 *pool_guid = 0;
535         pa.fd = open(devname, O_RDONLY);
536         if (pa.fd == -1)
537                 return (ENXIO);
538         /* Probe the whole disk */
539         ret = zfs_probe(pa.fd, pool_guid);
540         if (ret == 0)
541                 return (0);
542
543         /* Probe each partition */
544         ret = ioctl(pa.fd, DIOCGMEDIASIZE, &mediasz);
545         if (ret == 0)
546                 ret = ioctl(pa.fd, DIOCGSECTORSIZE, &pa.secsz);
547         if (ret == 0) {
548                 pa.devname = devname;
549                 pa.pool_guid = pool_guid;
550                 table = ptable_open(&pa, mediasz / pa.secsz, pa.secsz,
551                     zfs_diskread);
552                 if (table != NULL) {
553                         ptable_iterate(table, &pa, zfs_probe_partition);
554                         ptable_close(table);
555                 }
556         }
557         close(pa.fd);
558         if (pool_guid && *pool_guid == 0)
559                 ret = ENXIO;
560         return (ret);
561 }
562
563 /*
564  * Print information about ZFS pools
565  */
566 static int
567 zfs_dev_print(int verbose)
568 {
569         spa_t *spa;
570         char line[80];
571         int ret = 0;
572
573         if (STAILQ_EMPTY(&zfs_pools))
574                 return (0);
575
576         printf("%s devices:", zfs_dev.dv_name);
577         if ((ret = pager_output("\n")) != 0)
578                 return (ret);
579
580         if (verbose) {
581                 return (spa_all_status());
582         }
583         STAILQ_FOREACH(spa, &zfs_pools, spa_link) {
584                 snprintf(line, sizeof(line), "    zfs:%s\n", spa->spa_name);
585                 ret = pager_output(line);
586                 if (ret != 0)
587                         break;
588         }
589         return (ret);
590 }
591
592 /*
593  * Attempt to open the pool described by (dev) for use by (f).
594  */
595 static int
596 zfs_dev_open(struct open_file *f, ...)
597 {
598         va_list         args;
599         struct zfs_devdesc      *dev;
600         struct zfsmount *mount;
601         spa_t           *spa;
602         int             rv;
603
604         va_start(args, f);
605         dev = va_arg(args, struct zfs_devdesc *);
606         va_end(args);
607
608         if (dev->pool_guid == 0)
609                 spa = STAILQ_FIRST(&zfs_pools);
610         else
611                 spa = spa_find_by_guid(dev->pool_guid);
612         if (!spa)
613                 return (ENXIO);
614         mount = malloc(sizeof(*mount));
615         rv = zfs_mount(spa, dev->root_guid, mount);
616         if (rv != 0) {
617                 free(mount);
618                 return (rv);
619         }
620         if (mount->objset.os_type != DMU_OST_ZFS) {
621                 printf("Unexpected object set type %ju\n",
622                     (uintmax_t)mount->objset.os_type);
623                 free(mount);
624                 return (EIO);
625         }
626         f->f_devdata = mount;
627         free(dev);
628         return (0);
629 }
630
631 static int
632 zfs_dev_close(struct open_file *f)
633 {
634
635         free(f->f_devdata);
636         f->f_devdata = NULL;
637         return (0);
638 }
639
640 static int
641 zfs_dev_strategy(void *devdata, int rw, daddr_t dblk, size_t size, char *buf, size_t *rsize)
642 {
643
644         return (ENOSYS);
645 }
646
647 struct devsw zfs_dev = {
648         .dv_name = "zfs",
649         .dv_type = DEVT_ZFS,
650         .dv_init = zfs_dev_init,
651         .dv_strategy = zfs_dev_strategy,
652         .dv_open = zfs_dev_open,
653         .dv_close = zfs_dev_close,
654         .dv_ioctl = noioctl,
655         .dv_print = zfs_dev_print,
656         .dv_cleanup = NULL
657 };
658
659 int
660 zfs_parsedev(struct zfs_devdesc *dev, const char *devspec, const char **path)
661 {
662         static char     rootname[ZFS_MAXNAMELEN];
663         static char     poolname[ZFS_MAXNAMELEN];
664         spa_t           *spa;
665         const char      *end;
666         const char      *np;
667         const char      *sep;
668         int             rv;
669
670         np = devspec;
671         if (*np != ':')
672                 return (EINVAL);
673         np++;
674         end = strchr(np, ':');
675         if (end == NULL)
676                 return (EINVAL);
677         sep = strchr(np, '/');
678         if (sep == NULL || sep >= end)
679                 sep = end;
680         memcpy(poolname, np, sep - np);
681         poolname[sep - np] = '\0';
682         if (sep < end) {
683                 sep++;
684                 memcpy(rootname, sep, end - sep);
685                 rootname[end - sep] = '\0';
686         }
687         else
688                 rootname[0] = '\0';
689
690         spa = spa_find_by_name(poolname);
691         if (!spa)
692                 return (ENXIO);
693         dev->pool_guid = spa->spa_guid;
694         rv = zfs_lookup_dataset(spa, rootname, &dev->root_guid);
695         if (rv != 0)
696                 return (rv);
697         if (path != NULL)
698                 *path = (*end == '\0') ? end : end + 1;
699         dev->d_dev = &zfs_dev;
700         dev->d_type = zfs_dev.dv_type;
701         return (0);
702 }
703
704 char *
705 zfs_fmtdev(void *vdev)
706 {
707         static char             rootname[ZFS_MAXNAMELEN];
708         static char             buf[2 * ZFS_MAXNAMELEN + 8];
709         struct zfs_devdesc      *dev = (struct zfs_devdesc *)vdev;
710         spa_t                   *spa;
711
712         buf[0] = '\0';
713         if (dev->d_type != DEVT_ZFS)
714                 return (buf);
715
716         if (dev->pool_guid == 0) {
717                 spa = STAILQ_FIRST(&zfs_pools);
718                 dev->pool_guid = spa->spa_guid;
719         } else
720                 spa = spa_find_by_guid(dev->pool_guid);
721         if (spa == NULL) {
722                 printf("ZFS: can't find pool by guid\n");
723                 return (buf);
724         }
725         if (dev->root_guid == 0 && zfs_get_root(spa, &dev->root_guid)) {
726                 printf("ZFS: can't find root filesystem\n");
727                 return (buf);
728         }
729         if (zfs_rlookup(spa, dev->root_guid, rootname)) {
730                 printf("ZFS: can't find filesystem by guid\n");
731                 return (buf);
732         }
733
734         if (rootname[0] == '\0')
735                 sprintf(buf, "%s:%s:", dev->d_dev->dv_name, spa->spa_name);
736         else
737                 sprintf(buf, "%s:%s/%s:", dev->d_dev->dv_name, spa->spa_name,
738                     rootname);
739         return (buf);
740 }
741
742 int
743 zfs_list(const char *name)
744 {
745         static char     poolname[ZFS_MAXNAMELEN];
746         uint64_t        objid;
747         spa_t           *spa;
748         const char      *dsname;
749         int             len;
750         int             rv;
751
752         len = strlen(name);
753         dsname = strchr(name, '/');
754         if (dsname != NULL) {
755                 len = dsname - name;
756                 dsname++;
757         } else
758                 dsname = "";
759         memcpy(poolname, name, len);
760         poolname[len] = '\0';
761
762         spa = spa_find_by_name(poolname);
763         if (!spa)
764                 return (ENXIO);
765         rv = zfs_lookup_dataset(spa, dsname, &objid);
766         if (rv != 0)
767                 return (rv);
768
769         return (zfs_list_dataset(spa, objid));
770 }
771
772 void
773 init_zfs_bootenv(char *currdev)
774 {
775         char *beroot;
776
777         if (strlen(currdev) == 0)
778                 return;
779         if(strncmp(currdev, "zfs:", 4) != 0)
780                 return;
781         /* Remove the trailing : */
782         currdev[strlen(currdev) - 1] = '\0';
783         setenv("zfs_be_active", currdev, 1);
784         setenv("zfs_be_currpage", "1", 1);
785         /* Forward past zfs: */
786         currdev = strchr(currdev, ':');
787         currdev++;
788         /* Remove the last element (current bootenv) */
789         beroot = strrchr(currdev, '/');
790         if (beroot != NULL)
791                 beroot[0] = '\0';
792         beroot = currdev;
793         setenv("zfs_be_root", beroot, 1);
794 }
795
796 int
797 zfs_bootenv(const char *name)
798 {
799         static char     poolname[ZFS_MAXNAMELEN], *dsname, *root;
800         char            becount[4];
801         uint64_t        objid;
802         spa_t           *spa;
803         int             len, rv, pages, perpage, currpage;
804
805         if (name == NULL)
806                 return (EINVAL);
807         if ((root = getenv("zfs_be_root")) == NULL)
808                 return (EINVAL);
809
810         if (strcmp(name, root) != 0) {
811                 if (setenv("zfs_be_root", name, 1) != 0)
812                         return (ENOMEM);
813         }
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         memcpy(poolname, name, len);
825         poolname[len] = '\0';
826
827         spa = spa_find_by_name(poolname);
828         if (!spa)
829                 return (ENXIO);
830         rv = zfs_lookup_dataset(spa, dsname, &objid);
831         if (rv != 0)
832                 return (rv);
833         rv = zfs_callback_dataset(spa, objid, zfs_belist_add);
834
835         /* Calculate and store the number of pages of BEs */
836         perpage = (ZFS_BE_LAST - ZFS_BE_FIRST + 1);
837         pages = (zfs_env_count / perpage) + ((zfs_env_count % perpage) > 0 ? 1 : 0);
838         snprintf(becount, 4, "%d", pages);
839         if (setenv("zfs_be_pages", becount, 1) != 0)
840                 return (ENOMEM);
841
842         /* Roll over the page counter if it has exceeded the maximum */
843         currpage = strtol(getenv("zfs_be_currpage"), NULL, 10);
844         if (currpage > pages) {
845                 if (setenv("zfs_be_currpage", "1", 1) != 0)
846                         return (ENOMEM);
847         }
848
849         /* Populate the menu environment variables */
850         zfs_set_env();
851
852         /* Clean up the SLIST of ZFS BEs */
853         while (!SLIST_EMPTY(&zfs_be_head)) {
854                 zfs_be = SLIST_FIRST(&zfs_be_head);
855                 SLIST_REMOVE_HEAD(&zfs_be_head, entries);
856                 free(zfs_be);
857         }
858
859         return (rv);
860 }
861
862 int
863 zfs_belist_add(const char *name, uint64_t value __unused)
864 {
865
866         /* Skip special datasets that start with a $ character */
867         if (strncmp(name, "$", 1) == 0) {
868                 return (0);
869         }
870         /* Add the boot environment to the head of the SLIST */
871         zfs_be = malloc(sizeof(struct zfs_be_entry));
872         if (zfs_be == NULL) {
873                 return (ENOMEM);
874         }
875         zfs_be->name = name;
876         SLIST_INSERT_HEAD(&zfs_be_head, zfs_be, entries);
877         zfs_env_count++;
878
879         return (0);
880 }
881
882 int
883 zfs_set_env(void)
884 {
885         char envname[32], envval[256];
886         char *beroot, *pagenum;
887         int rv, page, ctr;
888
889         beroot = getenv("zfs_be_root");
890         if (beroot == NULL) {
891                 return (1);
892         }
893
894         pagenum = getenv("zfs_be_currpage");
895         if (pagenum != NULL) {
896                 page = strtol(pagenum, NULL, 10);
897         } else {
898                 page = 1;
899         }
900
901         ctr = 1;
902         rv = 0;
903         zfs_env_index = ZFS_BE_FIRST;
904         SLIST_FOREACH_SAFE(zfs_be, &zfs_be_head, entries, zfs_be_tmp) {
905                 /* Skip to the requested page number */
906                 if (ctr <= ((ZFS_BE_LAST - ZFS_BE_FIRST + 1) * (page - 1))) {
907                         ctr++;
908                         continue;
909                 }
910                 
911                 snprintf(envname, sizeof(envname), "bootenvmenu_caption[%d]", zfs_env_index);
912                 snprintf(envval, sizeof(envval), "%s", zfs_be->name);
913                 rv = setenv(envname, envval, 1);
914                 if (rv != 0) {
915                         break;
916                 }
917
918                 snprintf(envname, sizeof(envname), "bootenvansi_caption[%d]", zfs_env_index);
919                 rv = setenv(envname, envval, 1);
920                 if (rv != 0){
921                         break;
922                 }
923
924                 snprintf(envname, sizeof(envname), "bootenvmenu_command[%d]", zfs_env_index);
925                 rv = setenv(envname, "set_bootenv", 1);
926                 if (rv != 0){
927                         break;
928                 }
929
930                 snprintf(envname, sizeof(envname), "bootenv_root[%d]", zfs_env_index);
931                 snprintf(envval, sizeof(envval), "zfs:%s/%s", beroot, zfs_be->name);
932                 rv = setenv(envname, envval, 1);
933                 if (rv != 0){
934                         break;
935                 }
936
937                 zfs_env_index++;
938                 if (zfs_env_index > ZFS_BE_LAST) {
939                         break;
940                 }
941
942         }
943         
944         for (; zfs_env_index <= ZFS_BE_LAST; zfs_env_index++) {
945                 snprintf(envname, sizeof(envname), "bootenvmenu_caption[%d]", zfs_env_index);
946                 (void)unsetenv(envname);
947                 snprintf(envname, sizeof(envname), "bootenvansi_caption[%d]", zfs_env_index);
948                 (void)unsetenv(envname);
949                 snprintf(envname, sizeof(envname), "bootenvmenu_command[%d]", zfs_env_index);
950                 (void)unsetenv(envname);
951                 snprintf(envname, sizeof(envname), "bootenv_root[%d]", zfs_env_index);
952                 (void)unsetenv(envname);
953         }
954
955         return (rv);
956 }