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