]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - stand/libsa/zfs/zfs.c
loader: revert r342161 and r342151
[FreeBSD/FreeBSD.git] / stand / libsa / 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 <stand.h>
37 #include <sys/disk.h>
38 #include <sys/param.h>
39 #include <sys/time.h>
40 #include <sys/queue.h>
41 #include <part.h>
42 #include <stddef.h>
43 #include <stdarg.h>
44 #include <string.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_close(struct open_file *f);
57 static int      zfs_read(struct open_file *f, void *buf, size_t size, size_t *resid);
58 static off_t    zfs_seek(struct open_file *f, off_t offset, int where);
59 static int      zfs_stat(struct open_file *f, struct stat *sb);
60 static int      zfs_readdir(struct open_file *f, struct dirent *d);
61
62 static void     zfs_bootenv_initial(const char *);
63
64 struct devsw zfs_dev;
65
66 struct fs_ops zfs_fsops = {
67         "zfs",
68         zfs_open,
69         zfs_close,
70         zfs_read,
71         null_write,
72         zfs_seek,
73         zfs_stat,
74         zfs_readdir
75 };
76
77 /*
78  * In-core open file.
79  */
80 struct file {
81         off_t           f_seekp;        /* seek pointer */
82         dnode_phys_t    f_dnode;
83         uint64_t        f_zap_type;     /* zap type for readdir */
84         uint64_t        f_num_leafs;    /* number of fzap leaf blocks */
85         zap_leaf_phys_t *f_zap_leaf;    /* zap leaf buffer */
86 };
87
88 static int      zfs_env_index;
89 static int      zfs_env_count;
90
91 SLIST_HEAD(zfs_be_list, zfs_be_entry) zfs_be_head = SLIST_HEAD_INITIALIZER(zfs_be_head);
92 struct zfs_be_list *zfs_be_headp;
93 struct zfs_be_entry {
94         char *name;
95         SLIST_ENTRY(zfs_be_entry) entries;
96 } *zfs_be, *zfs_be_tmp;
97
98 /*
99  * Open a file.
100  */
101 static int
102 zfs_open(const char *upath, struct open_file *f)
103 {
104         struct zfsmount *mount = (struct zfsmount *)f->f_devdata;
105         struct file *fp;
106         int rc;
107
108         if (f->f_dev != &zfs_dev)
109                 return (EINVAL);
110
111         /* allocate file system specific data structure */
112         fp = calloc(1, sizeof(struct file));
113         if (fp == NULL)
114                 return (ENOMEM);
115         f->f_fsdata = 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 = NULL;
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 static off_t
175 zfs_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
206 static int
207 zfs_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
215 static int
216 zfs_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 = malloc(bsize);
252                         if (fp->f_zap_leaf == NULL)
253                                 return (ENOMEM);
254                         rc = dnode_read(spa, &fp->f_dnode,
255                                         fp->f_seekp,
256                                         fp->f_zap_leaf,
257                                         bsize);
258                         if (rc)
259                                 return (rc);
260                 }
261         }
262
263         if (fp->f_zap_type == ZBT_MICRO) {
264         mzap_next:
265                 if (fp->f_seekp >= bsize)
266                         return (ENOENT);
267
268                 rc = dnode_read(spa, &fp->f_dnode,
269                                 fp->f_seekp, &mze, sizeof(mze));
270                 if (rc)
271                         return (rc);
272                 fp->f_seekp += sizeof(mze);
273
274                 if (!mze.mze_name[0])
275                         goto mzap_next;
276
277                 d->d_fileno = ZFS_DIRENT_OBJ(mze.mze_value);
278                 d->d_type = ZFS_DIRENT_TYPE(mze.mze_value);
279                 strcpy(d->d_name, mze.mze_name);
280                 d->d_namlen = strlen(d->d_name);
281                 return (0);
282         } else {
283                 zap_leaf_t zl;
284                 zap_leaf_chunk_t *zc, *nc;
285                 int chunk;
286                 size_t namelen;
287                 char *p;
288                 uint64_t value;
289
290                 /*
291                  * Initialise this so we can use the ZAP size
292                  * calculating macros.
293                  */
294                 zl.l_bs = ilog2(bsize);
295                 zl.l_phys = fp->f_zap_leaf;
296
297                 /*
298                  * Figure out which chunk we are currently looking at
299                  * and consider seeking to the next leaf. We use the
300                  * low bits of f_seekp as a simple chunk index.
301                  */
302         fzap_next:
303                 chunk = fp->f_seekp & (bsize - 1);
304                 if (chunk == ZAP_LEAF_NUMCHUNKS(&zl)) {
305                         fp->f_seekp = rounddown2(fp->f_seekp, bsize) + bsize;
306                         chunk = 0;
307
308                         /*
309                          * Check for EOF and read the new leaf.
310                          */
311                         if (fp->f_seekp >= bsize * fp->f_num_leafs)
312                                 return (ENOENT);
313
314                         rc = dnode_read(spa, &fp->f_dnode,
315                                         fp->f_seekp,
316                                         fp->f_zap_leaf,
317                                         bsize);
318                         if (rc)
319                                 return (rc);
320                 }
321
322                 zc = &ZAP_LEAF_CHUNK(&zl, chunk);
323                 fp->f_seekp++;
324                 if (zc->l_entry.le_type != ZAP_CHUNK_ENTRY)
325                         goto fzap_next;
326
327                 namelen = zc->l_entry.le_name_numints;
328                 if (namelen > sizeof(d->d_name))
329                         namelen = sizeof(d->d_name);
330
331                 /*
332                  * Paste the name back together.
333                  */
334                 nc = &ZAP_LEAF_CHUNK(&zl, zc->l_entry.le_name_chunk);
335                 p = d->d_name;
336                 while (namelen > 0) {
337                         int len;
338                         len = namelen;
339                         if (len > ZAP_LEAF_ARRAY_BYTES)
340                                 len = ZAP_LEAF_ARRAY_BYTES;
341                         memcpy(p, nc->l_array.la_array, len);
342                         p += len;
343                         namelen -= len;
344                         nc = &ZAP_LEAF_CHUNK(&zl, nc->l_array.la_next);
345                 }
346                 d->d_name[sizeof(d->d_name) - 1] = 0;
347
348                 /*
349                  * Assume the first eight bytes of the value are
350                  * a uint64_t.
351                  */
352                 value = fzap_leaf_value(&zl, zc);
353
354                 d->d_fileno = ZFS_DIRENT_OBJ(value);
355                 d->d_type = ZFS_DIRENT_TYPE(value);
356                 d->d_namlen = strlen(d->d_name);
357
358                 return (0);
359         }
360 }
361
362 static int
363 vdev_read(vdev_t *vdev, void *priv, off_t offset, void *buf, size_t bytes)
364 {
365         int fd, ret;
366         size_t res, head, tail, total_size, full_sec_size;
367         unsigned secsz, do_tail_read;
368         off_t start_sec;
369         char *outbuf, *bouncebuf;
370
371         fd = (uintptr_t) priv;
372         outbuf = (char *) buf;
373         bouncebuf = NULL;
374
375         ret = ioctl(fd, DIOCGSECTORSIZE, &secsz);
376         if (ret != 0)
377                 return (ret);
378
379         /*
380          * Handling reads of arbitrary offset and size - multi-sector case
381          * and single-sector case.
382          *
383          *                        Multi-sector Case
384          *                (do_tail_read = true if tail > 0)
385          *
386          *   |<----------------------total_size--------------------->|
387          *   |                                                       |
388          *   |<--head-->|<--------------bytes------------>|<--tail-->|
389          *   |          |                                 |          |
390          *   |          |       |<~full_sec_size~>|       |          |
391          *   +------------------+                 +------------------+
392          *   |          |0101010|     .  .  .     |0101011|          |
393          *   +------------------+                 +------------------+
394          *         start_sec                         start_sec + n
395          *
396          *
397          *                      Single-sector Case
398          *                    (do_tail_read = false)
399          *
400          *              |<------total_size = secsz----->|
401          *              |                               |
402          *              |<-head->|<---bytes--->|<-tail->|
403          *              +-------------------------------+
404          *              |        |0101010101010|        |
405          *              +-------------------------------+
406          *                          start_sec
407          */
408         start_sec = offset / secsz;
409         head = offset % secsz;
410         total_size = roundup2(head + bytes, secsz);
411         tail = total_size - (head + bytes);
412         do_tail_read = ((tail > 0) && (head + bytes > secsz));
413         full_sec_size = total_size;
414         if (head > 0)
415                 full_sec_size -= secsz;
416         if (do_tail_read)
417                 full_sec_size -= secsz;
418
419         /* Return of partial sector data requires a bounce buffer. */
420         if ((head > 0) || do_tail_read || bytes < secsz) {
421                 bouncebuf = malloc(secsz);
422                 if (bouncebuf == NULL) {
423                         printf("vdev_read: out of memory\n");
424                         return (ENOMEM);
425                 }
426         }
427
428         if (lseek(fd, start_sec * secsz, SEEK_SET) == -1) {
429                 ret = errno;
430                 goto error;
431         }
432
433         /* Partial data return from first sector */
434         if (head > 0) {
435                 res = read(fd, bouncebuf, secsz);
436                 if (res != secsz) {
437                         ret = EIO;
438                         goto error;
439                 }
440                 memcpy(outbuf, bouncebuf + head, min(secsz - head, bytes));
441                 outbuf += min(secsz - head, bytes);
442         }
443
444         /*
445          * Full data return from read sectors.
446          * Note, there is still corner case where we read
447          * from sector boundary, but less than sector size, e.g. reading 512B
448          * from 4k sector.
449          */
450         if (full_sec_size > 0) {
451                 if (bytes < full_sec_size) {
452                         res = read(fd, bouncebuf, secsz);
453                         if (res != secsz) {
454                                 ret = EIO;
455                                 goto error;
456                         }
457                         memcpy(outbuf, bouncebuf, bytes);
458                 } else {
459                         res = read(fd, outbuf, full_sec_size);
460                         if (res != full_sec_size) {
461                                 ret = EIO;
462                                 goto error;
463                         }
464                         outbuf += full_sec_size;
465                 }
466         }
467
468         /* Partial data return from last sector */
469         if (do_tail_read) {
470                 res = read(fd, bouncebuf, secsz);
471                 if (res != secsz) {
472                         ret = EIO;
473                         goto error;
474                 }
475                 memcpy(outbuf, bouncebuf, secsz - tail);
476         }
477
478         ret = 0;
479 error:
480         free(bouncebuf);
481         return (ret);
482 }
483
484 static int
485 vdev_write(vdev_t *vdev __unused, void *priv, off_t offset, void *buf,
486     size_t bytes)
487 {
488         int fd, ret;
489         size_t head, tail, total_size, full_sec_size;
490         unsigned secsz, do_tail_write;
491         off_t start_sec;
492         ssize_t res;
493         char *outbuf, *bouncebuf;
494
495         fd = (uintptr_t)priv;
496         outbuf = (char *) buf;
497         bouncebuf = NULL;
498
499         ret = ioctl(fd, DIOCGSECTORSIZE, &secsz);
500         if (ret != 0)
501                 return (ret);
502
503         start_sec = offset / secsz;
504         head = offset % secsz;
505         total_size = roundup2(head + bytes, secsz);
506         tail = total_size - (head + bytes);
507         do_tail_write = ((tail > 0) && (head + bytes > secsz));
508         full_sec_size = total_size;
509         if (head > 0)
510                 full_sec_size -= secsz;
511         if (do_tail_write)
512                 full_sec_size -= secsz;
513
514         /* Partial sector write requires a bounce buffer. */
515         if ((head > 0) || do_tail_write || bytes < secsz) {
516                 bouncebuf = malloc(secsz);
517                 if (bouncebuf == NULL) {
518                         printf("vdev_write: out of memory\n");
519                         return (ENOMEM);
520                 }
521         }
522
523         if (lseek(fd, start_sec * secsz, SEEK_SET) == -1) {
524                 ret = errno;
525                 goto error;
526         }
527
528         /* Partial data for first sector */
529         if (head > 0) {
530                 res = read(fd, bouncebuf, secsz);
531                 if (res != secsz) {
532                         ret = EIO;
533                         goto error;
534                 }
535                 memcpy(bouncebuf + head, outbuf, min(secsz - head, bytes));
536                 (void) lseek(fd, -secsz, SEEK_CUR);
537                 res = write(fd, bouncebuf, secsz);
538                 if (res != secsz) {
539                         ret = EIO;
540                         goto error;
541                 }
542                 outbuf += min(secsz - head, bytes);
543         }
544
545         /*
546          * Full data write to sectors.
547          * Note, there is still corner case where we write
548          * to sector boundary, but less than sector size, e.g. write 512B
549          * to 4k sector.
550          */
551         if (full_sec_size > 0) {
552                 if (bytes < full_sec_size) {
553                         res = read(fd, bouncebuf, secsz);
554                         if (res != secsz) {
555                                 ret = EIO;
556                                 goto error;
557                         }
558                         memcpy(bouncebuf, outbuf, bytes);
559                         (void) lseek(fd, -secsz, SEEK_CUR);
560                         res = write(fd, bouncebuf, secsz);
561                         if (res != secsz) {
562                                 ret = EIO;
563                                 goto error;
564                         }
565                 } else {
566                         res = write(fd, outbuf, full_sec_size);
567                         if (res != full_sec_size) {
568                                 ret = EIO;
569                                 goto error;
570                         }
571                         outbuf += full_sec_size;
572                 }
573         }
574
575         /* Partial data write to last sector */
576         if (do_tail_write) {
577                 res = read(fd, bouncebuf, secsz);
578                 if (res != secsz) {
579                         ret = EIO;
580                         goto error;
581                 }
582                 memcpy(bouncebuf, outbuf, secsz - tail);
583                 (void) lseek(fd, -secsz, SEEK_CUR);
584                 res = write(fd, bouncebuf, secsz);
585                 if (res != secsz) {
586                         ret = EIO;
587                         goto error;
588                 }
589         }
590
591         ret = 0;
592 error:
593         free(bouncebuf);
594         return (ret);
595 }
596
597 static void
598 vdev_clear_pad2(vdev_t *vdev)
599 {
600         vdev_t *kid;
601         vdev_boot_envblock_t *be;
602         off_t off = offsetof(vdev_label_t, vl_be);
603         zio_checksum_info_t *ci;
604         zio_cksum_t cksum;
605
606         STAILQ_FOREACH(kid, &vdev->v_children, v_childlink) {
607                 if (kid->v_state != VDEV_STATE_HEALTHY)
608                         continue;
609                 vdev_clear_pad2(kid);
610         }
611
612         if (!STAILQ_EMPTY(&vdev->v_children))
613                 return;
614
615         be = calloc(1, sizeof (*be));
616         if (be == NULL) {
617                 printf("failed to clear be area: out of memory\n");
618                 return;
619         }
620
621         ci = &zio_checksum_table[ZIO_CHECKSUM_LABEL];
622         be->vbe_zbt.zec_magic = ZEC_MAGIC;
623         zio_checksum_label_verifier(&be->vbe_zbt.zec_cksum, off);
624         ci->ci_func[0](be, sizeof (*be), NULL, &cksum);
625         be->vbe_zbt.zec_cksum = cksum;
626
627         if (vdev_write(vdev, vdev->v_read_priv, off, be, VDEV_PAD_SIZE)) {
628                 printf("failed to clear be area of primary vdev: %d\n",
629                     errno);
630         }
631         free(be);
632 }
633
634 /*
635  * Read the next boot command from pad2.
636  * If any instance of pad2 is set to empty string, or the returned string
637  * values are not the same, we consider next boot not to be set.
638  */
639 static char *
640 vdev_read_pad2(vdev_t *vdev)
641 {
642         vdev_t *kid;
643         char *tmp, *result = NULL;
644         vdev_boot_envblock_t *be;
645         off_t off = offsetof(vdev_label_t, vl_be);
646
647         STAILQ_FOREACH(kid, &vdev->v_children, v_childlink) {
648                 if (kid->v_state != VDEV_STATE_HEALTHY)
649                         continue;
650                 tmp = vdev_read_pad2(kid);
651                 if (tmp == NULL)
652                         continue;
653
654                 /* The next boot is not set, we are done. */
655                 if (*tmp == '\0') {
656                         free(result);
657                         return (tmp);
658                 }
659                 if (result == NULL) {
660                         result = tmp;
661                         continue;
662                 }
663                 /* Are the next boot strings different? */
664                 if (strcmp(result, tmp) != 0) {
665                         free(tmp);
666                         *result = '\0';
667                         break;
668                 }
669                 free(tmp);
670         }
671         if (result != NULL)
672                 return (result);
673
674         be = malloc(sizeof (*be));
675         if (be == NULL)
676                 return (NULL);
677
678         if (vdev_read(vdev, vdev->v_read_priv, off, be, sizeof (*be))) {
679                 return (NULL);
680         }
681
682         switch (be->vbe_version) {
683         case VB_RAW:
684         case VB_NVLIST:
685                 result = strdup(be->vbe_bootenv);
686         default:
687                 /* Backward compatibility with initial nextboot feaure. */
688                 result = strdup((char *)be);
689         }
690         return (result);
691 }
692
693 static int
694 zfs_dev_init(void)
695 {
696         spa_t *spa;
697         spa_t *next;
698         spa_t *prev;
699
700         zfs_init();
701         if (archsw.arch_zfs_probe == NULL)
702                 return (ENXIO);
703         archsw.arch_zfs_probe();
704
705         prev = NULL;
706         spa = STAILQ_FIRST(&zfs_pools);
707         while (spa != NULL) {
708                 next = STAILQ_NEXT(spa, spa_link);
709                 if (zfs_spa_init(spa)) {
710                         if (prev == NULL)
711                                 STAILQ_REMOVE_HEAD(&zfs_pools, spa_link);
712                         else
713                                 STAILQ_REMOVE_AFTER(&zfs_pools, prev, spa_link);
714                 } else
715                         prev = spa;
716                 spa = next;
717         }
718         return (0);
719 }
720
721 struct zfs_probe_args {
722         int             fd;
723         const char      *devname;
724         uint64_t        *pool_guid;
725         u_int           secsz;
726 };
727
728 static int
729 zfs_diskread(void *arg, void *buf, size_t blocks, uint64_t offset)
730 {
731         struct zfs_probe_args *ppa;
732
733         ppa = (struct zfs_probe_args *)arg;
734         return (vdev_read(NULL, (void *)(uintptr_t)ppa->fd,
735             offset * ppa->secsz, buf, blocks * ppa->secsz));
736 }
737
738 static int
739 zfs_probe(int fd, uint64_t *pool_guid)
740 {
741         spa_t *spa;
742         int ret;
743
744         spa = NULL;
745         ret = vdev_probe(vdev_read, (void *)(uintptr_t)fd, &spa);
746         if (ret == 0 && pool_guid != NULL)
747                 if (*pool_guid == 0)
748                         *pool_guid = spa->spa_guid;
749         return (ret);
750 }
751
752 static int
753 zfs_probe_partition(void *arg, const char *partname,
754     const struct ptable_entry *part)
755 {
756         struct zfs_probe_args *ppa, pa;
757         struct ptable *table;
758         char devname[32];
759         int ret;
760
761         /* Probe only freebsd-zfs and freebsd partitions */
762         if (part->type != PART_FREEBSD &&
763             part->type != PART_FREEBSD_ZFS)
764                 return (0);
765
766         ppa = (struct zfs_probe_args *)arg;
767         strncpy(devname, ppa->devname, strlen(ppa->devname) - 1);
768         devname[strlen(ppa->devname) - 1] = '\0';
769         sprintf(devname, "%s%s:", devname, partname);
770         pa.fd = open(devname, O_RDWR);
771         if (pa.fd == -1)
772                 return (0);
773         ret = zfs_probe(pa.fd, ppa->pool_guid);
774         if (ret == 0)
775                 return (0);
776         /* Do we have BSD label here? */
777         if (part->type == PART_FREEBSD) {
778                 pa.devname = devname;
779                 pa.pool_guid = ppa->pool_guid;
780                 pa.secsz = ppa->secsz;
781                 table = ptable_open(&pa, part->end - part->start + 1,
782                     ppa->secsz, zfs_diskread);
783                 if (table != NULL) {
784                         ptable_iterate(table, &pa, zfs_probe_partition);
785                         ptable_close(table);
786                 }
787         }
788         close(pa.fd);
789         return (0);
790 }
791
792 int
793 zfs_nextboot(void *vdev, char *buf, size_t size)
794 {
795         struct zfs_devdesc *dev = (struct zfs_devdesc *)vdev;
796         spa_t *spa;
797         vdev_t *vd;
798         char *result = NULL;
799
800         if (dev->dd.d_dev->dv_type != DEVT_ZFS)
801                 return (1);
802
803         if (dev->pool_guid == 0)
804                 spa = STAILQ_FIRST(&zfs_pools);
805         else
806                 spa = spa_find_by_guid(dev->pool_guid);
807
808         if (spa == NULL) {
809                 printf("ZFS: can't find pool by guid\n");
810         return (1);
811         }
812
813         STAILQ_FOREACH(vd, &spa->spa_root_vdev->v_children, v_childlink) {
814                 char *tmp = vdev_read_pad2(vd);
815
816                 /* Continue on error. */
817                 if (tmp == NULL)
818                         continue;
819                 /* Nextboot is not set. */
820                 if (*tmp == '\0') {
821                         free(result);
822                         free(tmp);
823                         return (1);
824                 }
825                 if (result == NULL) {
826                         result = tmp;
827                         continue;
828                 }
829                 free(tmp);
830         }
831         if (result == NULL)
832                 return (1);
833
834         STAILQ_FOREACH(vd, &spa->spa_root_vdev->v_children, v_childlink) {
835                 vdev_clear_pad2(vd);
836         }
837
838         strlcpy(buf, result, size);
839         free(result);
840         return (0);
841 }
842
843 int
844 zfs_probe_dev(const char *devname, uint64_t *pool_guid)
845 {
846         struct ptable *table;
847         struct zfs_probe_args pa;
848         uint64_t mediasz;
849         int ret;
850
851         if (pool_guid)
852                 *pool_guid = 0;
853         pa.fd = open(devname, O_RDWR);
854         if (pa.fd == -1)
855                 return (ENXIO);
856         /* Probe the whole disk */
857         ret = zfs_probe(pa.fd, pool_guid);
858         if (ret == 0)
859                 return (0);
860
861         /* Probe each partition */
862         ret = ioctl(pa.fd, DIOCGMEDIASIZE, &mediasz);
863         if (ret == 0)
864                 ret = ioctl(pa.fd, DIOCGSECTORSIZE, &pa.secsz);
865         if (ret == 0) {
866                 pa.devname = devname;
867                 pa.pool_guid = pool_guid;
868                 table = ptable_open(&pa, mediasz / pa.secsz, pa.secsz,
869                     zfs_diskread);
870                 if (table != NULL) {
871                         ptable_iterate(table, &pa, zfs_probe_partition);
872                         ptable_close(table);
873                 }
874         }
875         close(pa.fd);
876         if (pool_guid && *pool_guid == 0)
877                 ret = ENXIO;
878         return (ret);
879 }
880
881 /*
882  * Print information about ZFS pools
883  */
884 static int
885 zfs_dev_print(int verbose)
886 {
887         spa_t *spa;
888         char line[80];
889         int ret = 0;
890
891         if (STAILQ_EMPTY(&zfs_pools))
892                 return (0);
893
894         printf("%s devices:", zfs_dev.dv_name);
895         if ((ret = pager_output("\n")) != 0)
896                 return (ret);
897
898         if (verbose) {
899                 return (spa_all_status());
900         }
901         STAILQ_FOREACH(spa, &zfs_pools, spa_link) {
902                 snprintf(line, sizeof(line), "    zfs:%s\n", spa->spa_name);
903                 ret = pager_output(line);
904                 if (ret != 0)
905                         break;
906         }
907         return (ret);
908 }
909
910 /*
911  * Attempt to open the pool described by (dev) for use by (f).
912  */
913 static int
914 zfs_dev_open(struct open_file *f, ...)
915 {
916         va_list         args;
917         struct zfs_devdesc      *dev;
918         struct zfsmount *mount;
919         spa_t           *spa;
920         int             rv;
921
922         va_start(args, f);
923         dev = va_arg(args, struct zfs_devdesc *);
924         va_end(args);
925
926         if (dev->pool_guid == 0)
927                 spa = STAILQ_FIRST(&zfs_pools);
928         else
929                 spa = spa_find_by_guid(dev->pool_guid);
930         if (!spa)
931                 return (ENXIO);
932         mount = malloc(sizeof(*mount));
933         if (mount == NULL)
934                 rv = ENOMEM;
935         else
936                 rv = zfs_mount(spa, dev->root_guid, mount);
937         if (rv != 0) {
938                 free(mount);
939                 return (rv);
940         }
941         if (mount->objset.os_type != DMU_OST_ZFS) {
942                 printf("Unexpected object set type %ju\n",
943                     (uintmax_t)mount->objset.os_type);
944                 free(mount);
945                 return (EIO);
946         }
947         f->f_devdata = mount;
948         free(dev);
949         return (0);
950 }
951
952 static int
953 zfs_dev_close(struct open_file *f)
954 {
955
956         free(f->f_devdata);
957         f->f_devdata = NULL;
958         return (0);
959 }
960
961 static int
962 zfs_dev_strategy(void *devdata, int rw, daddr_t dblk, size_t size, char *buf, size_t *rsize)
963 {
964
965         return (ENOSYS);
966 }
967
968 struct devsw zfs_dev = {
969         .dv_name = "zfs",
970         .dv_type = DEVT_ZFS,
971         .dv_init = zfs_dev_init,
972         .dv_strategy = zfs_dev_strategy,
973         .dv_open = zfs_dev_open,
974         .dv_close = zfs_dev_close,
975         .dv_ioctl = noioctl,
976         .dv_print = zfs_dev_print,
977         .dv_cleanup = NULL
978 };
979
980 int
981 zfs_parsedev(struct zfs_devdesc *dev, const char *devspec, const char **path)
982 {
983         static char     rootname[ZFS_MAXNAMELEN];
984         static char     poolname[ZFS_MAXNAMELEN];
985         spa_t           *spa;
986         const char      *end;
987         const char      *np;
988         const char      *sep;
989         int             rv;
990
991         np = devspec;
992         if (*np != ':')
993                 return (EINVAL);
994         np++;
995         end = strrchr(np, ':');
996         if (end == NULL)
997                 return (EINVAL);
998         sep = strchr(np, '/');
999         if (sep == NULL || sep >= end)
1000                 sep = end;
1001         memcpy(poolname, np, sep - np);
1002         poolname[sep - np] = '\0';
1003         if (sep < end) {
1004                 sep++;
1005                 memcpy(rootname, sep, end - sep);
1006                 rootname[end - sep] = '\0';
1007         }
1008         else
1009                 rootname[0] = '\0';
1010
1011         spa = spa_find_by_name(poolname);
1012         if (!spa)
1013                 return (ENXIO);
1014         dev->pool_guid = spa->spa_guid;
1015         rv = zfs_lookup_dataset(spa, rootname, &dev->root_guid);
1016         if (rv != 0)
1017                 return (rv);
1018         if (path != NULL)
1019                 *path = (*end == '\0') ? end : end + 1;
1020         dev->dd.d_dev = &zfs_dev;
1021         return (0);
1022 }
1023
1024 char *
1025 zfs_fmtdev(void *vdev)
1026 {
1027         static char             rootname[ZFS_MAXNAMELEN];
1028         static char             buf[2 * ZFS_MAXNAMELEN + 8];
1029         struct zfs_devdesc      *dev = (struct zfs_devdesc *)vdev;
1030         spa_t                   *spa;
1031
1032         buf[0] = '\0';
1033         if (dev->dd.d_dev->dv_type != DEVT_ZFS)
1034                 return (buf);
1035
1036         /* Do we have any pools? */
1037         spa = STAILQ_FIRST(&zfs_pools);
1038         if (spa == NULL)
1039                 return (buf);
1040
1041         if (dev->pool_guid == 0)
1042                 dev->pool_guid = spa->spa_guid;
1043         else
1044                 spa = spa_find_by_guid(dev->pool_guid);
1045
1046         if (spa == NULL) {
1047                 printf("ZFS: can't find pool by guid\n");
1048                 return (buf);
1049         }
1050         if (dev->root_guid == 0 && zfs_get_root(spa, &dev->root_guid)) {
1051                 printf("ZFS: can't find root filesystem\n");
1052                 return (buf);
1053         }
1054         if (zfs_rlookup(spa, dev->root_guid, rootname)) {
1055                 printf("ZFS: can't find filesystem by guid\n");
1056                 return (buf);
1057         }
1058
1059         if (rootname[0] == '\0')
1060                 sprintf(buf, "%s:%s:", dev->dd.d_dev->dv_name, spa->spa_name);
1061         else
1062                 sprintf(buf, "%s:%s/%s:", dev->dd.d_dev->dv_name, spa->spa_name,
1063                     rootname);
1064         return (buf);
1065 }
1066
1067 int
1068 zfs_list(const char *name)
1069 {
1070         static char     poolname[ZFS_MAXNAMELEN];
1071         uint64_t        objid;
1072         spa_t           *spa;
1073         const char      *dsname;
1074         int             len;
1075         int             rv;
1076
1077         len = strlen(name);
1078         dsname = strchr(name, '/');
1079         if (dsname != NULL) {
1080                 len = dsname - name;
1081                 dsname++;
1082         } else
1083                 dsname = "";
1084         memcpy(poolname, name, len);
1085         poolname[len] = '\0';
1086
1087         spa = spa_find_by_name(poolname);
1088         if (!spa)
1089                 return (ENXIO);
1090         rv = zfs_lookup_dataset(spa, dsname, &objid);
1091         if (rv != 0)
1092                 return (rv);
1093
1094         return (zfs_list_dataset(spa, objid));
1095 }
1096
1097 void
1098 init_zfs_bootenv(const char *currdev_in)
1099 {
1100         char *beroot, *currdev;
1101         int currdev_len;
1102
1103         currdev = NULL;
1104         currdev_len = strlen(currdev_in);
1105         if (currdev_len == 0)
1106                 return;
1107         if (strncmp(currdev_in, "zfs:", 4) != 0)
1108                 return;
1109         currdev = strdup(currdev_in);
1110         if (currdev == NULL)
1111                 return;
1112         /* Remove the trailing : */
1113         currdev[currdev_len - 1] = '\0';
1114         setenv("zfs_be_active", currdev, 1);
1115         setenv("zfs_be_currpage", "1", 1);
1116         /* Remove the last element (current bootenv) */
1117         beroot = strrchr(currdev, '/');
1118         if (beroot != NULL)
1119                 beroot[0] = '\0';
1120         beroot = strchr(currdev, ':') + 1;
1121         setenv("zfs_be_root", beroot, 1);
1122         zfs_bootenv_initial(beroot);
1123         free(currdev);
1124 }
1125
1126 static void
1127 zfs_bootenv_initial(const char *name)
1128 {
1129         char            poolname[ZFS_MAXNAMELEN], *dsname;
1130         char envname[32], envval[256];
1131         uint64_t        objid;
1132         spa_t           *spa;
1133         int             bootenvs_idx, len, rv;
1134
1135         SLIST_INIT(&zfs_be_head);
1136         zfs_env_count = 0;
1137         len = strlen(name);
1138         dsname = strchr(name, '/');
1139         if (dsname != NULL) {
1140                 len = dsname - name;
1141                 dsname++;
1142         } else
1143                 dsname = "";
1144         strlcpy(poolname, name, len + 1);
1145         spa = spa_find_by_name(poolname);
1146         if (spa == NULL)
1147                 return;
1148         rv = zfs_lookup_dataset(spa, dsname, &objid);
1149         if (rv != 0)
1150                 return;
1151         rv = zfs_callback_dataset(spa, objid, zfs_belist_add);
1152         bootenvs_idx = 0;
1153         /* Populate the initial environment variables */
1154         SLIST_FOREACH_SAFE(zfs_be, &zfs_be_head, entries, zfs_be_tmp) {
1155                 /* Enumerate all bootenvs for general usage */
1156                 snprintf(envname, sizeof(envname), "bootenvs[%d]", bootenvs_idx);
1157                 snprintf(envval, sizeof(envval), "zfs:%s/%s", name, zfs_be->name);
1158                 rv = setenv(envname, envval, 1);
1159                 if (rv != 0)
1160                         break;
1161                 bootenvs_idx++;
1162         }
1163         snprintf(envval, sizeof(envval), "%d", bootenvs_idx);
1164         setenv("bootenvs_count", envval, 1);
1165
1166         /* Clean up the SLIST of ZFS BEs */
1167         while (!SLIST_EMPTY(&zfs_be_head)) {
1168                 zfs_be = SLIST_FIRST(&zfs_be_head);
1169                 SLIST_REMOVE_HEAD(&zfs_be_head, entries);
1170                 free(zfs_be->name);
1171                 free(zfs_be);
1172         }
1173
1174         return;
1175
1176 }
1177
1178 int
1179 zfs_bootenv(const char *name)
1180 {
1181         static char     poolname[ZFS_MAXNAMELEN], *dsname, *root;
1182         char            becount[4];
1183         uint64_t        objid;
1184         spa_t           *spa;
1185         int             len, rv, pages, perpage, currpage;
1186
1187         if (name == NULL)
1188                 return (EINVAL);
1189         if ((root = getenv("zfs_be_root")) == NULL)
1190                 return (EINVAL);
1191
1192         if (strcmp(name, root) != 0) {
1193                 if (setenv("zfs_be_root", name, 1) != 0)
1194                         return (ENOMEM);
1195         }
1196
1197         SLIST_INIT(&zfs_be_head);
1198         zfs_env_count = 0;
1199         len = strlen(name);
1200         dsname = strchr(name, '/');
1201         if (dsname != NULL) {
1202                 len = dsname - name;
1203                 dsname++;
1204         } else
1205                 dsname = "";
1206         memcpy(poolname, name, len);
1207         poolname[len] = '\0';
1208
1209         spa = spa_find_by_name(poolname);
1210         if (!spa)
1211                 return (ENXIO);
1212         rv = zfs_lookup_dataset(spa, dsname, &objid);
1213         if (rv != 0)
1214                 return (rv);
1215         rv = zfs_callback_dataset(spa, objid, zfs_belist_add);
1216
1217         /* Calculate and store the number of pages of BEs */
1218         perpage = (ZFS_BE_LAST - ZFS_BE_FIRST + 1);
1219         pages = (zfs_env_count / perpage) + ((zfs_env_count % perpage) > 0 ? 1 : 0);
1220         snprintf(becount, 4, "%d", pages);
1221         if (setenv("zfs_be_pages", becount, 1) != 0)
1222                 return (ENOMEM);
1223
1224         /* Roll over the page counter if it has exceeded the maximum */
1225         currpage = strtol(getenv("zfs_be_currpage"), NULL, 10);
1226         if (currpage > pages) {
1227                 if (setenv("zfs_be_currpage", "1", 1) != 0)
1228                         return (ENOMEM);
1229         }
1230
1231         /* Populate the menu environment variables */
1232         zfs_set_env();
1233
1234         /* Clean up the SLIST of ZFS BEs */
1235         while (!SLIST_EMPTY(&zfs_be_head)) {
1236                 zfs_be = SLIST_FIRST(&zfs_be_head);
1237                 SLIST_REMOVE_HEAD(&zfs_be_head, entries);
1238                 free(zfs_be->name);
1239                 free(zfs_be);
1240         }
1241
1242         return (rv);
1243 }
1244
1245 int
1246 zfs_belist_add(const char *name, uint64_t value __unused)
1247 {
1248
1249         /* Skip special datasets that start with a $ character */
1250         if (strncmp(name, "$", 1) == 0) {
1251                 return (0);
1252         }
1253         /* Add the boot environment to the head of the SLIST */
1254         zfs_be = malloc(sizeof(struct zfs_be_entry));
1255         if (zfs_be == NULL) {
1256                 return (ENOMEM);
1257         }
1258         zfs_be->name = strdup(name);
1259         if (zfs_be->name == NULL) {
1260                 free(zfs_be);
1261                 return (ENOMEM);
1262         }
1263         SLIST_INSERT_HEAD(&zfs_be_head, zfs_be, entries);
1264         zfs_env_count++;
1265
1266         return (0);
1267 }
1268
1269 int
1270 zfs_set_env(void)
1271 {
1272         char envname[32], envval[256];
1273         char *beroot, *pagenum;
1274         int rv, page, ctr;
1275
1276         beroot = getenv("zfs_be_root");
1277         if (beroot == NULL) {
1278                 return (1);
1279         }
1280
1281         pagenum = getenv("zfs_be_currpage");
1282         if (pagenum != NULL) {
1283                 page = strtol(pagenum, NULL, 10);
1284         } else {
1285                 page = 1;
1286         }
1287
1288         ctr = 1;
1289         rv = 0;
1290         zfs_env_index = ZFS_BE_FIRST;
1291         SLIST_FOREACH_SAFE(zfs_be, &zfs_be_head, entries, zfs_be_tmp) {
1292                 /* Skip to the requested page number */
1293                 if (ctr <= ((ZFS_BE_LAST - ZFS_BE_FIRST + 1) * (page - 1))) {
1294                         ctr++;
1295                         continue;
1296                 }
1297                 
1298                 snprintf(envname, sizeof(envname), "bootenvmenu_caption[%d]", zfs_env_index);
1299                 snprintf(envval, sizeof(envval), "%s", zfs_be->name);
1300                 rv = setenv(envname, envval, 1);
1301                 if (rv != 0) {
1302                         break;
1303                 }
1304
1305                 snprintf(envname, sizeof(envname), "bootenvansi_caption[%d]", zfs_env_index);
1306                 rv = setenv(envname, envval, 1);
1307                 if (rv != 0){
1308                         break;
1309                 }
1310
1311                 snprintf(envname, sizeof(envname), "bootenvmenu_command[%d]", zfs_env_index);
1312                 rv = setenv(envname, "set_bootenv", 1);
1313                 if (rv != 0){
1314                         break;
1315                 }
1316
1317                 snprintf(envname, sizeof(envname), "bootenv_root[%d]", zfs_env_index);
1318                 snprintf(envval, sizeof(envval), "zfs:%s/%s", beroot, zfs_be->name);
1319                 rv = setenv(envname, envval, 1);
1320                 if (rv != 0){
1321                         break;
1322                 }
1323
1324                 zfs_env_index++;
1325                 if (zfs_env_index > ZFS_BE_LAST) {
1326                         break;
1327                 }
1328
1329         }
1330         
1331         for (; zfs_env_index <= ZFS_BE_LAST; zfs_env_index++) {
1332                 snprintf(envname, sizeof(envname), "bootenvmenu_caption[%d]", zfs_env_index);
1333                 (void)unsetenv(envname);
1334                 snprintf(envname, sizeof(envname), "bootenvansi_caption[%d]", zfs_env_index);
1335                 (void)unsetenv(envname);
1336                 snprintf(envname, sizeof(envname), "bootenvmenu_command[%d]", zfs_env_index);
1337                 (void)unsetenv(envname);
1338                 snprintf(envname, sizeof(envname), "bootenv_root[%d]", zfs_env_index);
1339                 (void)unsetenv(envname);
1340         }
1341
1342         return (rv);
1343 }