]> CyberLeo.Net >> Repos - FreeBSD/releng/8.0.git/blob - cddl/contrib/opensolaris/cmd/zfs/zfs_main.c
Adjust to reflect 8.0-RELEASE.
[FreeBSD/releng/8.0.git] / cddl / contrib / opensolaris / cmd / zfs / zfs_main.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26
27 #include <assert.h>
28 #include <ctype.h>
29 #include <errno.h>
30 #include <libgen.h>
31 #include <libintl.h>
32 #include <libuutil.h>
33 #include <libnvpair.h>
34 #include <locale.h>
35 #include <stddef.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <strings.h>
39 #include <unistd.h>
40 #include <fcntl.h>
41 #include <zone.h>
42 #include <sys/mntent.h>
43 #include <sys/mnttab.h>
44 #include <sys/mount.h>
45 #include <sys/stat.h>
46 #include <sys/avl.h>
47
48 #include <libzfs.h>
49 #include <libuutil.h>
50
51 #include "zfs_iter.h"
52 #include "zfs_util.h"
53
54 libzfs_handle_t *g_zfs;
55
56 static FILE *mnttab_file;
57 static char history_str[HIS_MAX_RECORD_LEN];
58
59 static int zfs_do_clone(int argc, char **argv);
60 static int zfs_do_create(int argc, char **argv);
61 static int zfs_do_destroy(int argc, char **argv);
62 static int zfs_do_get(int argc, char **argv);
63 static int zfs_do_inherit(int argc, char **argv);
64 static int zfs_do_list(int argc, char **argv);
65 static int zfs_do_mount(int argc, char **argv);
66 static int zfs_do_rename(int argc, char **argv);
67 static int zfs_do_rollback(int argc, char **argv);
68 static int zfs_do_set(int argc, char **argv);
69 static int zfs_do_upgrade(int argc, char **argv);
70 static int zfs_do_snapshot(int argc, char **argv);
71 static int zfs_do_unmount(int argc, char **argv);
72 static int zfs_do_share(int argc, char **argv);
73 static int zfs_do_unshare(int argc, char **argv);
74 static int zfs_do_send(int argc, char **argv);
75 static int zfs_do_receive(int argc, char **argv);
76 static int zfs_do_promote(int argc, char **argv);
77 static int zfs_do_allow(int argc, char **argv);
78 static int zfs_do_unallow(int argc, char **argv);
79 static int zfs_do_jail(int argc, char **argv);
80 static int zfs_do_unjail(int argc, char **argv);
81
82 /*
83  * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
84  */
85
86 #ifdef DEBUG
87 const char *
88 _umem_debug_init(void)
89 {
90         return ("default,verbose"); /* $UMEM_DEBUG setting */
91 }
92
93 const char *
94 _umem_logging_init(void)
95 {
96         return ("fail,contents"); /* $UMEM_LOGGING setting */
97 }
98 #endif
99
100 typedef enum {
101         HELP_CLONE,
102         HELP_CREATE,
103         HELP_DESTROY,
104         HELP_GET,
105         HELP_INHERIT,
106         HELP_UPGRADE,
107         HELP_JAIL,
108         HELP_UNJAIL,
109         HELP_LIST,
110         HELP_MOUNT,
111         HELP_PROMOTE,
112         HELP_RECEIVE,
113         HELP_RENAME,
114         HELP_ROLLBACK,
115         HELP_SEND,
116         HELP_SET,
117         HELP_SHARE,
118         HELP_SNAPSHOT,
119         HELP_UNMOUNT,
120         HELP_UNSHARE,
121         HELP_ALLOW,
122         HELP_UNALLOW
123 } zfs_help_t;
124
125 typedef struct zfs_command {
126         const char      *name;
127         int             (*func)(int argc, char **argv);
128         zfs_help_t      usage;
129 } zfs_command_t;
130
131 /*
132  * Master command table.  Each ZFS command has a name, associated function, and
133  * usage message.  The usage messages need to be internationalized, so we have
134  * to have a function to return the usage message based on a command index.
135  *
136  * These commands are organized according to how they are displayed in the usage
137  * message.  An empty command (one with a NULL name) indicates an empty line in
138  * the generic usage message.
139  */
140 static zfs_command_t command_table[] = {
141         { "create",     zfs_do_create,          HELP_CREATE             },
142         { "destroy",    zfs_do_destroy,         HELP_DESTROY            },
143         { NULL },
144         { "snapshot",   zfs_do_snapshot,        HELP_SNAPSHOT           },
145         { "rollback",   zfs_do_rollback,        HELP_ROLLBACK           },
146         { "clone",      zfs_do_clone,           HELP_CLONE              },
147         { "promote",    zfs_do_promote,         HELP_PROMOTE            },
148         { "rename",     zfs_do_rename,          HELP_RENAME             },
149         { NULL },
150         { "list",       zfs_do_list,            HELP_LIST               },
151         { NULL },
152         { "set",        zfs_do_set,             HELP_SET                },
153         { "get",        zfs_do_get,             HELP_GET                },
154         { "inherit",    zfs_do_inherit,         HELP_INHERIT            },
155         { "upgrade",    zfs_do_upgrade,         HELP_UPGRADE            },
156         { NULL },
157         { "mount",      zfs_do_mount,           HELP_MOUNT              },
158         { "unmount",    zfs_do_unmount,         HELP_UNMOUNT            },
159         { "share",      zfs_do_share,           HELP_SHARE              },
160         { "unshare",    zfs_do_unshare,         HELP_UNSHARE            },
161         { NULL },
162         { "send",       zfs_do_send,            HELP_SEND               },
163         { "receive",    zfs_do_receive,         HELP_RECEIVE            },
164         { NULL },
165         { "allow",      zfs_do_allow,           HELP_ALLOW              },
166         { NULL },
167         { "unallow",    zfs_do_unallow,         HELP_UNALLOW            },
168         { NULL },
169         { "jail",       zfs_do_jail,            HELP_JAIL               },
170         { "unjail",     zfs_do_unjail,          HELP_UNJAIL             },
171 };
172
173 #define NCOMMAND        (sizeof (command_table) / sizeof (command_table[0]))
174
175 zfs_command_t *current_command;
176
177 static const char *
178 get_usage(zfs_help_t idx)
179 {
180         switch (idx) {
181         case HELP_CLONE:
182                 return (gettext("\tclone [-p] [-o property=value] ... "
183                     "<snapshot> <filesystem|volume>\n"));
184         case HELP_CREATE:
185                 return (gettext("\tcreate [-p] [-o property=value] ... "
186                     "<filesystem>\n"
187                     "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
188                     "-V <size> <volume>\n"));
189         case HELP_DESTROY:
190                 return (gettext("\tdestroy [-rRf] "
191                     "<filesystem|volume|snapshot>\n"));
192         case HELP_GET:
193                 return (gettext("\tget [-rHp] [-o field[,...]] "
194                     "[-s source[,...]]\n"
195                     "\t    <\"all\" | property[,...]> "
196                     "[filesystem|volume|snapshot] ...\n"));
197         case HELP_INHERIT:
198                 return (gettext("\tinherit [-r] <property> "
199                     "<filesystem|volume|snapshot> ...\n"));
200         case HELP_UPGRADE:
201                 return (gettext("\tupgrade [-v]\n"
202                     "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
203         case HELP_JAIL:
204                 return (gettext("\tjail <jailid> <filesystem>\n"));
205         case HELP_UNJAIL:
206                 return (gettext("\tunjail <jailid> <filesystem>\n"));
207         case HELP_LIST:
208                 return (gettext("\tlist [-rH] [-o property[,...]] "
209                     "[-t type[,...]] [-s property] ...\n"
210                     "\t    [-S property] ... "
211                     "[filesystem|volume|snapshot] ...\n"));
212         case HELP_MOUNT:
213                 return (gettext("\tmount\n"
214                     "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
215         case HELP_PROMOTE:
216                 return (gettext("\tpromote <clone-filesystem>\n"));
217         case HELP_RECEIVE:
218                 return (gettext("\treceive [-vnF] <filesystem|volume|"
219                 "snapshot>\n"
220                 "\treceive [-vnF] -d <filesystem>\n"));
221         case HELP_RENAME:
222                 return (gettext("\trename <filesystem|volume|snapshot> "
223                     "<filesystem|volume|snapshot>\n"
224                     "\trename -p <filesystem|volume> <filesystem|volume>\n"
225                     "\trename -r <snapshot> <snapshot>"));
226         case HELP_ROLLBACK:
227                 return (gettext("\trollback [-rRf] <snapshot>\n"));
228         case HELP_SEND:
229                 return (gettext("\tsend [-R] [-[iI] snapshot] <snapshot>\n"));
230         case HELP_SET:
231                 return (gettext("\tset <property=value> "
232                     "<filesystem|volume|snapshot> ...\n"));
233         case HELP_SHARE:
234                 return (gettext("\tshare <-a | filesystem>\n"));
235         case HELP_SNAPSHOT:
236                 return (gettext("\tsnapshot [-r] [-o property=value] ... "
237                     "<filesystem@snapname|volume@snapname>\n"));
238         case HELP_UNMOUNT:
239                 return (gettext("\tunmount [-f] "
240                     "<-a | filesystem|mountpoint>\n"));
241         case HELP_UNSHARE:
242                 return (gettext("\tunshare [-f] "
243                     "<-a | filesystem|mountpoint>\n"));
244         case HELP_ALLOW:
245                 return (gettext("\tallow [-ldug] "
246                     "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
247                     "\t    <filesystem|volume>\n"
248                     "\tallow [-ld] -e <perm|@setname>[,...] "
249                     "<filesystem|volume>\n"
250                     "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
251                     "\tallow -s @setname <perm|@setname>[,...] "
252                     "<filesystem|volume>\n"));
253         case HELP_UNALLOW:
254                 return (gettext("\tunallow [-rldug] "
255                     "<\"everyone\"|user|group>[,...]\n"
256                     "\t    [<perm|@setname>[,...]] <filesystem|volume>\n"
257                     "\tunallow [-rld] -e [<perm|@setname>[,...]] "
258                     "<filesystem|volume>\n"
259                     "\tunallow [-r] -c [<perm|@setname>[,...]] "
260                     "<filesystem|volume>\n"
261                     "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
262                     "<filesystem|volume>\n"));
263         }
264
265         abort();
266         /* NOTREACHED */
267 }
268
269 /*
270  * Utility function to guarantee malloc() success.
271  */
272 void *
273 safe_malloc(size_t size)
274 {
275         void *data;
276
277         if ((data = calloc(1, size)) == NULL) {
278                 (void) fprintf(stderr, "internal error: out of memory\n");
279                 exit(1);
280         }
281
282         return (data);
283 }
284
285 /*
286  * Callback routine that will print out information for each of
287  * the properties.
288  */
289 static int
290 usage_prop_cb(int prop, void *cb)
291 {
292         FILE *fp = cb;
293
294         (void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
295
296         if (zfs_prop_readonly(prop))
297                 (void) fprintf(fp, " NO    ");
298         else
299                 (void) fprintf(fp, "YES    ");
300
301         if (zfs_prop_inheritable(prop))
302                 (void) fprintf(fp, "  YES   ");
303         else
304                 (void) fprintf(fp, "   NO   ");
305
306         if (zfs_prop_values(prop) == NULL)
307                 (void) fprintf(fp, "-\n");
308         else
309                 (void) fprintf(fp, "%s\n", zfs_prop_values(prop));
310
311         return (ZPROP_CONT);
312 }
313
314 /*
315  * Display usage message.  If we're inside a command, display only the usage for
316  * that command.  Otherwise, iterate over the entire command table and display
317  * a complete usage message.
318  */
319 static void
320 usage(boolean_t requested)
321 {
322         int i;
323         boolean_t show_properties = B_FALSE;
324         boolean_t show_permissions = B_FALSE;
325         FILE *fp = requested ? stdout : stderr;
326
327         if (current_command == NULL) {
328
329                 (void) fprintf(fp, gettext("usage: zfs command args ...\n"));
330                 (void) fprintf(fp,
331                     gettext("where 'command' is one of the following:\n\n"));
332
333                 for (i = 0; i < NCOMMAND; i++) {
334                         if (command_table[i].name == NULL)
335                                 (void) fprintf(fp, "\n");
336                         else
337                                 (void) fprintf(fp, "%s",
338                                     get_usage(command_table[i].usage));
339                 }
340
341                 (void) fprintf(fp, gettext("\nEach dataset is of the form: "
342                     "pool/[dataset/]*dataset[@name]\n"));
343         } else {
344                 (void) fprintf(fp, gettext("usage:\n"));
345                 (void) fprintf(fp, "%s", get_usage(current_command->usage));
346         }
347
348         if (current_command != NULL &&
349             (strcmp(current_command->name, "set") == 0 ||
350             strcmp(current_command->name, "get") == 0 ||
351             strcmp(current_command->name, "inherit") == 0 ||
352             strcmp(current_command->name, "list") == 0))
353                 show_properties = B_TRUE;
354
355         if (current_command != NULL &&
356             (strcmp(current_command->name, "allow") == 0 ||
357             strcmp(current_command->name, "unallow") == 0))
358                 show_permissions = B_TRUE;
359
360         if (show_properties) {
361
362                 (void) fprintf(fp,
363                     gettext("\nThe following properties are supported:\n"));
364
365                 (void) fprintf(fp, "\n\t%-14s %s  %s   %s\n\n",
366                     "PROPERTY", "EDIT", "INHERIT", "VALUES");
367
368                 /* Iterate over all properties */
369                 (void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
370                     ZFS_TYPE_DATASET);
371
372                 (void) fprintf(fp, gettext("\nSizes are specified in bytes "
373                     "with standard units such as K, M, G, etc.\n"));
374                 (void) fprintf(fp, gettext("\nUser-defined properties can "
375                     "be specified by using a name containing a colon (:).\n"));
376
377         } else if (show_permissions) {
378                 (void) fprintf(fp,
379                     gettext("\nThe following permissions are supported:\n"));
380
381                 zfs_deleg_permissions();
382         } else {
383                 /*
384                  * TRANSLATION NOTE:
385                  * "zfs set|get" must not be localised this is the
386                  * command name and arguments.
387                  */
388
389                 (void) fprintf(fp,
390                     gettext("\nFor the property list, run: zfs set|get\n"));
391
392                 (void) fprintf(fp,
393                     gettext("\nFor the delegated permission list, run:"
394                     " zfs allow|unallow\n"));
395         }
396
397         /*
398          * See comments at end of main().
399          */
400         if (getenv("ZFS_ABORT") != NULL) {
401                 (void) printf("dumping core by request\n");
402                 abort();
403         }
404
405         exit(requested ? 0 : 2);
406 }
407
408 static int
409 parseprop(nvlist_t *props)
410 {
411         char *propname = optarg;
412         char *propval, *strval;
413
414         if ((propval = strchr(propname, '=')) == NULL) {
415                 (void) fprintf(stderr, gettext("missing "
416                     "'=' for -o option\n"));
417                 return (-1);
418         }
419         *propval = '\0';
420         propval++;
421         if (nvlist_lookup_string(props, propname, &strval) == 0) {
422                 (void) fprintf(stderr, gettext("property '%s' "
423                     "specified multiple times\n"), propname);
424                 return (-1);
425         }
426         if (nvlist_add_string(props, propname, propval) != 0) {
427                 (void) fprintf(stderr, gettext("internal "
428                     "error: out of memory\n"));
429                 return (-1);
430         }
431         return (0);
432
433 }
434
435 /*
436  * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
437  *
438  * Given an existing dataset, create a writable copy whose initial contents
439  * are the same as the source.  The newly created dataset maintains a
440  * dependency on the original; the original cannot be destroyed so long as
441  * the clone exists.
442  *
443  * The '-p' flag creates all the non-existing ancestors of the target first.
444  */
445 static int
446 zfs_do_clone(int argc, char **argv)
447 {
448         zfs_handle_t *zhp = NULL;
449         boolean_t parents = B_FALSE;
450         nvlist_t *props;
451         int ret;
452         int c;
453
454         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
455                 (void) fprintf(stderr, gettext("internal error: "
456                     "out of memory\n"));
457                 return (1);
458         }
459
460         /* check options */
461         while ((c = getopt(argc, argv, "o:p")) != -1) {
462                 switch (c) {
463                 case 'o':
464                         if (parseprop(props))
465                                 return (1);
466                         break;
467                 case 'p':
468                         parents = B_TRUE;
469                         break;
470                 case '?':
471                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
472                             optopt);
473                         goto usage;
474                 }
475         }
476
477         argc -= optind;
478         argv += optind;
479
480         /* check number of arguments */
481         if (argc < 1) {
482                 (void) fprintf(stderr, gettext("missing source dataset "
483                     "argument\n"));
484                 goto usage;
485         }
486         if (argc < 2) {
487                 (void) fprintf(stderr, gettext("missing target dataset "
488                     "argument\n"));
489                 goto usage;
490         }
491         if (argc > 2) {
492                 (void) fprintf(stderr, gettext("too many arguments\n"));
493                 goto usage;
494         }
495
496         /* open the source dataset */
497         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
498                 return (1);
499
500         if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
501             ZFS_TYPE_VOLUME)) {
502                 /*
503                  * Now create the ancestors of the target dataset.  If the
504                  * target already exists and '-p' option was used we should not
505                  * complain.
506                  */
507                 if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
508                     ZFS_TYPE_VOLUME))
509                         return (0);
510                 if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
511                         return (1);
512         }
513
514         /* pass to libzfs */
515         ret = zfs_clone(zhp, argv[1], props);
516
517         /* create the mountpoint if necessary */
518         if (ret == 0) {
519                 zfs_handle_t *clone;
520
521                 clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
522                 if (clone != NULL) {
523                         if ((ret = zfs_mount(clone, NULL, 0)) == 0)
524                                 ret = zfs_share(clone);
525                         zfs_close(clone);
526                 }
527         }
528
529         zfs_close(zhp);
530         nvlist_free(props);
531
532         return (!!ret);
533
534 usage:
535         if (zhp)
536                 zfs_close(zhp);
537         nvlist_free(props);
538         usage(B_FALSE);
539         return (-1);
540 }
541
542 /*
543  * zfs create [-p] [-o prop=value] ... fs
544  * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
545  *
546  * Create a new dataset.  This command can be used to create filesystems
547  * and volumes.  Snapshot creation is handled by 'zfs snapshot'.
548  * For volumes, the user must specify a size to be used.
549  *
550  * The '-s' flag applies only to volumes, and indicates that we should not try
551  * to set the reservation for this volume.  By default we set a reservation
552  * equal to the size for any volume.  For pools with SPA_VERSION >=
553  * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
554  *
555  * The '-p' flag creates all the non-existing ancestors of the target first.
556  */
557 static int
558 zfs_do_create(int argc, char **argv)
559 {
560         zfs_type_t type = ZFS_TYPE_FILESYSTEM;
561         zfs_handle_t *zhp = NULL;
562         uint64_t volsize;
563         int c;
564         boolean_t noreserve = B_FALSE;
565         boolean_t bflag = B_FALSE;
566         boolean_t parents = B_FALSE;
567         int ret = 1;
568         nvlist_t *props;
569         uint64_t intval;
570         int canmount;
571
572         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
573                 (void) fprintf(stderr, gettext("internal error: "
574                     "out of memory\n"));
575                 return (1);
576         }
577
578         /* check options */
579         while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
580                 switch (c) {
581                 case 'V':
582                         type = ZFS_TYPE_VOLUME;
583                         if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
584                                 (void) fprintf(stderr, gettext("bad volume "
585                                     "size '%s': %s\n"), optarg,
586                                     libzfs_error_description(g_zfs));
587                                 goto error;
588                         }
589
590                         if (nvlist_add_uint64(props,
591                             zfs_prop_to_name(ZFS_PROP_VOLSIZE),
592                             intval) != 0) {
593                                 (void) fprintf(stderr, gettext("internal "
594                                     "error: out of memory\n"));
595                                 goto error;
596                         }
597                         volsize = intval;
598                         break;
599                 case 'p':
600                         parents = B_TRUE;
601                         break;
602                 case 'b':
603                         bflag = B_TRUE;
604                         if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
605                                 (void) fprintf(stderr, gettext("bad volume "
606                                     "block size '%s': %s\n"), optarg,
607                                     libzfs_error_description(g_zfs));
608                                 goto error;
609                         }
610
611                         if (nvlist_add_uint64(props,
612                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
613                             intval) != 0) {
614                                 (void) fprintf(stderr, gettext("internal "
615                                     "error: out of memory\n"));
616                                 goto error;
617                         }
618                         break;
619                 case 'o':
620                         if (parseprop(props))
621                                 goto error;
622                         break;
623                 case 's':
624                         noreserve = B_TRUE;
625                         break;
626                 case ':':
627                         (void) fprintf(stderr, gettext("missing size "
628                             "argument\n"));
629                         goto badusage;
630                         break;
631                 case '?':
632                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
633                             optopt);
634                         goto badusage;
635                 }
636         }
637
638         if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
639                 (void) fprintf(stderr, gettext("'-s' and '-b' can only be "
640                     "used when creating a volume\n"));
641                 goto badusage;
642         }
643
644         argc -= optind;
645         argv += optind;
646
647         /* check number of arguments */
648         if (argc == 0) {
649                 (void) fprintf(stderr, gettext("missing %s argument\n"),
650                     zfs_type_to_name(type));
651                 goto badusage;
652         }
653         if (argc > 1) {
654                 (void) fprintf(stderr, gettext("too many arguments\n"));
655                 goto badusage;
656         }
657
658         if (type == ZFS_TYPE_VOLUME && !noreserve) {
659                 zpool_handle_t *zpool_handle;
660                 uint64_t spa_version;
661                 char *p;
662                 zfs_prop_t resv_prop;
663                 char *strval;
664
665                 if (p = strchr(argv[0], '/'))
666                         *p = '\0';
667                 zpool_handle = zpool_open(g_zfs, argv[0]);
668                 if (p != NULL)
669                         *p = '/';
670                 if (zpool_handle == NULL)
671                         goto error;
672                 spa_version = zpool_get_prop_int(zpool_handle,
673                     ZPOOL_PROP_VERSION, NULL);
674                 zpool_close(zpool_handle);
675                 if (spa_version >= SPA_VERSION_REFRESERVATION)
676                         resv_prop = ZFS_PROP_REFRESERVATION;
677                 else
678                         resv_prop = ZFS_PROP_RESERVATION;
679
680                 if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
681                     &strval) != 0) {
682                         if (nvlist_add_uint64(props,
683                             zfs_prop_to_name(resv_prop), volsize) != 0) {
684                                 (void) fprintf(stderr, gettext("internal "
685                                     "error: out of memory\n"));
686                                 nvlist_free(props);
687                                 return (1);
688                         }
689                 }
690         }
691
692         if (parents && zfs_name_valid(argv[0], type)) {
693                 /*
694                  * Now create the ancestors of target dataset.  If the target
695                  * already exists and '-p' option was used we should not
696                  * complain.
697                  */
698                 if (zfs_dataset_exists(g_zfs, argv[0], type)) {
699                         ret = 0;
700                         goto error;
701                 }
702                 if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
703                         goto error;
704         }
705
706         /* pass to libzfs */
707         if (zfs_create(g_zfs, argv[0], type, props) != 0)
708                 goto error;
709
710         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
711                 goto error;
712         /*
713          * if the user doesn't want the dataset automatically mounted,
714          * then skip the mount/share step
715          */
716
717         canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
718
719         /*
720          * Mount and/or share the new filesystem as appropriate.  We provide a
721          * verbose error message to let the user know that their filesystem was
722          * in fact created, even if we failed to mount or share it.
723          */
724         ret = 0;
725         if (canmount == ZFS_CANMOUNT_ON) {
726                 if (zfs_mount(zhp, NULL, 0) != 0) {
727                         (void) fprintf(stderr, gettext("filesystem "
728                             "successfully created, but not mounted\n"));
729                         ret = 1;
730                 } else if (zfs_share(zhp) != 0) {
731                         (void) fprintf(stderr, gettext("filesystem "
732                             "successfully created, but not shared\n"));
733                         ret = 1;
734                 }
735         }
736
737 error:
738         if (zhp)
739                 zfs_close(zhp);
740         nvlist_free(props);
741         return (ret);
742 badusage:
743         nvlist_free(props);
744         usage(B_FALSE);
745         return (2);
746 }
747
748 /*
749  * zfs destroy [-rf] <fs, snap, vol>
750  *
751  *      -r      Recursively destroy all children
752  *      -R      Recursively destroy all dependents, including clones
753  *      -f      Force unmounting of any dependents
754  *
755  * Destroys the given dataset.  By default, it will unmount any filesystems,
756  * and refuse to destroy a dataset that has any dependents.  A dependent can
757  * either be a child, or a clone of a child.
758  */
759 typedef struct destroy_cbdata {
760         boolean_t       cb_first;
761         int             cb_force;
762         int             cb_recurse;
763         int             cb_error;
764         int             cb_needforce;
765         int             cb_doclones;
766         boolean_t       cb_closezhp;
767         zfs_handle_t    *cb_target;
768         char            *cb_snapname;
769 } destroy_cbdata_t;
770
771 /*
772  * Check for any dependents based on the '-r' or '-R' flags.
773  */
774 static int
775 destroy_check_dependent(zfs_handle_t *zhp, void *data)
776 {
777         destroy_cbdata_t *cbp = data;
778         const char *tname = zfs_get_name(cbp->cb_target);
779         const char *name = zfs_get_name(zhp);
780
781         if (strncmp(tname, name, strlen(tname)) == 0 &&
782             (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
783                 /*
784                  * This is a direct descendant, not a clone somewhere else in
785                  * the hierarchy.
786                  */
787                 if (cbp->cb_recurse)
788                         goto out;
789
790                 if (cbp->cb_first) {
791                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
792                             "%s has children\n"),
793                             zfs_get_name(cbp->cb_target),
794                             zfs_type_to_name(zfs_get_type(cbp->cb_target)));
795                         (void) fprintf(stderr, gettext("use '-r' to destroy "
796                             "the following datasets:\n"));
797                         cbp->cb_first = B_FALSE;
798                         cbp->cb_error = 1;
799                 }
800
801                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
802         } else {
803                 /*
804                  * This is a clone.  We only want to report this if the '-r'
805                  * wasn't specified, or the target is a snapshot.
806                  */
807                 if (!cbp->cb_recurse &&
808                     zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
809                         goto out;
810
811                 if (cbp->cb_first) {
812                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
813                             "%s has dependent clones\n"),
814                             zfs_get_name(cbp->cb_target),
815                             zfs_type_to_name(zfs_get_type(cbp->cb_target)));
816                         (void) fprintf(stderr, gettext("use '-R' to destroy "
817                             "the following datasets:\n"));
818                         cbp->cb_first = B_FALSE;
819                         cbp->cb_error = 1;
820                 }
821
822                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
823         }
824
825 out:
826         zfs_close(zhp);
827         return (0);
828 }
829
830 static int
831 destroy_callback(zfs_handle_t *zhp, void *data)
832 {
833         destroy_cbdata_t *cbp = data;
834
835         /*
836          * Ignore pools (which we've already flagged as an error before getting
837          * here.
838          */
839         if (strchr(zfs_get_name(zhp), '/') == NULL &&
840             zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
841                 zfs_close(zhp);
842                 return (0);
843         }
844
845         /*
846          * Bail out on the first error.
847          */
848         if (zfs_unmount(zhp, NULL, cbp->cb_force ? MS_FORCE : 0) != 0 ||
849             zfs_destroy(zhp) != 0) {
850                 zfs_close(zhp);
851                 return (-1);
852         }
853
854         zfs_close(zhp);
855         return (0);
856 }
857
858 static int
859 destroy_snap_clones(zfs_handle_t *zhp, void *arg)
860 {
861         destroy_cbdata_t *cbp = arg;
862         char thissnap[MAXPATHLEN];
863         zfs_handle_t *szhp;
864         boolean_t closezhp = cbp->cb_closezhp;
865         int rv;
866
867         (void) snprintf(thissnap, sizeof (thissnap),
868             "%s@%s", zfs_get_name(zhp), cbp->cb_snapname);
869
870         libzfs_print_on_error(g_zfs, B_FALSE);
871         szhp = zfs_open(g_zfs, thissnap, ZFS_TYPE_SNAPSHOT);
872         libzfs_print_on_error(g_zfs, B_TRUE);
873         if (szhp) {
874                 /*
875                  * Destroy any clones of this snapshot
876                  */
877                 if (zfs_iter_dependents(szhp, B_FALSE, destroy_callback,
878                     cbp) != 0) {
879                         zfs_close(szhp);
880                         if (closezhp)
881                                 zfs_close(zhp);
882                         return (-1);
883                 }
884                 zfs_close(szhp);
885         }
886
887         cbp->cb_closezhp = B_TRUE;
888         rv = zfs_iter_filesystems(zhp, destroy_snap_clones, arg);
889         if (closezhp)
890                 zfs_close(zhp);
891         return (rv);
892 }
893
894 static int
895 zfs_do_destroy(int argc, char **argv)
896 {
897         destroy_cbdata_t cb = { 0 };
898         int c;
899         zfs_handle_t *zhp;
900         char *cp;
901
902         /* check options */
903         while ((c = getopt(argc, argv, "frR")) != -1) {
904                 switch (c) {
905                 case 'f':
906                         cb.cb_force = 1;
907                         break;
908                 case 'r':
909                         cb.cb_recurse = 1;
910                         break;
911                 case 'R':
912                         cb.cb_recurse = 1;
913                         cb.cb_doclones = 1;
914                         break;
915                 case '?':
916                 default:
917                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
918                             optopt);
919                         usage(B_FALSE);
920                 }
921         }
922
923         argc -= optind;
924         argv += optind;
925
926         /* check number of arguments */
927         if (argc == 0) {
928                 (void) fprintf(stderr, gettext("missing path argument\n"));
929                 usage(B_FALSE);
930         }
931         if (argc > 1) {
932                 (void) fprintf(stderr, gettext("too many arguments\n"));
933                 usage(B_FALSE);
934         }
935
936         /*
937          * If we are doing recursive destroy of a snapshot, then the
938          * named snapshot may not exist.  Go straight to libzfs.
939          */
940         if (cb.cb_recurse && (cp = strchr(argv[0], '@'))) {
941                 int ret;
942
943                 *cp = '\0';
944                 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
945                         return (1);
946                 *cp = '@';
947                 cp++;
948
949                 if (cb.cb_doclones) {
950                         cb.cb_snapname = cp;
951                         if (destroy_snap_clones(zhp, &cb) != 0) {
952                                 zfs_close(zhp);
953                                 return (1);
954                         }
955                 }
956
957                 ret = zfs_destroy_snaps(zhp, cp);
958                 zfs_close(zhp);
959                 if (ret) {
960                         (void) fprintf(stderr,
961                             gettext("no snapshots destroyed\n"));
962                 }
963                 return (ret != 0);
964         }
965
966
967         /* Open the given dataset */
968         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
969                 return (1);
970
971         cb.cb_target = zhp;
972
973         /*
974          * Perform an explicit check for pools before going any further.
975          */
976         if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
977             zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
978                 (void) fprintf(stderr, gettext("cannot destroy '%s': "
979                     "operation does not apply to pools\n"),
980                     zfs_get_name(zhp));
981                 (void) fprintf(stderr, gettext("use 'zfs destroy -r "
982                     "%s' to destroy all datasets in the pool\n"),
983                     zfs_get_name(zhp));
984                 (void) fprintf(stderr, gettext("use 'zpool destroy %s' "
985                     "to destroy the pool itself\n"), zfs_get_name(zhp));
986                 zfs_close(zhp);
987                 return (1);
988         }
989
990         /*
991          * Check for any dependents and/or clones.
992          */
993         cb.cb_first = B_TRUE;
994         if (!cb.cb_doclones &&
995             zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
996             &cb) != 0) {
997                 zfs_close(zhp);
998                 return (1);
999         }
1000
1001         if (cb.cb_error ||
1002             zfs_iter_dependents(zhp, B_FALSE, destroy_callback, &cb) != 0) {
1003                 zfs_close(zhp);
1004                 return (1);
1005         }
1006
1007         /*
1008          * Do the real thing.  The callback will close the handle regardless of
1009          * whether it succeeds or not.
1010          */
1011
1012         if (destroy_callback(zhp, &cb) != 0)
1013                 return (1);
1014
1015
1016         return (0);
1017 }
1018
1019 /*
1020  * zfs get [-rHp] [-o field[,field]...] [-s source[,source]...]
1021  *      < all | property[,property]... > < fs | snap | vol > ...
1022  *
1023  *      -r      recurse over any child datasets
1024  *      -H      scripted mode.  Headers are stripped, and fields are separated
1025  *              by tabs instead of spaces.
1026  *      -o      Set of fields to display.  One of "name,property,value,source".
1027  *              Default is all four.
1028  *      -s      Set of sources to allow.  One of
1029  *              "local,default,inherited,temporary,none".  Default is all
1030  *              five.
1031  *      -p      Display values in parsable (literal) format.
1032  *
1033  *  Prints properties for the given datasets.  The user can control which
1034  *  columns to display as well as which property types to allow.
1035  */
1036
1037 /*
1038  * Invoked to display the properties for a single dataset.
1039  */
1040 static int
1041 get_callback(zfs_handle_t *zhp, void *data)
1042 {
1043         char buf[ZFS_MAXPROPLEN];
1044         zprop_source_t sourcetype;
1045         char source[ZFS_MAXNAMELEN];
1046         zprop_get_cbdata_t *cbp = data;
1047         nvlist_t *userprop = zfs_get_user_props(zhp);
1048         zprop_list_t *pl = cbp->cb_proplist;
1049         nvlist_t *propval;
1050         char *strval;
1051         char *sourceval;
1052
1053         for (; pl != NULL; pl = pl->pl_next) {
1054                 /*
1055                  * Skip the special fake placeholder.  This will also skip over
1056                  * the name property when 'all' is specified.
1057                  */
1058                 if (pl->pl_prop == ZFS_PROP_NAME &&
1059                     pl == cbp->cb_proplist)
1060                         continue;
1061
1062                 if (pl->pl_prop != ZPROP_INVAL) {
1063                         if (zfs_prop_get(zhp, pl->pl_prop, buf,
1064                             sizeof (buf), &sourcetype, source,
1065                             sizeof (source),
1066                             cbp->cb_literal) != 0) {
1067                                 if (pl->pl_all)
1068                                         continue;
1069                                 if (!zfs_prop_valid_for_type(pl->pl_prop,
1070                                     ZFS_TYPE_DATASET)) {
1071                                         (void) fprintf(stderr,
1072                                             gettext("No such property '%s'\n"),
1073                                             zfs_prop_to_name(pl->pl_prop));
1074                                         continue;
1075                                 }
1076                                 sourcetype = ZPROP_SRC_NONE;
1077                                 (void) strlcpy(buf, "-", sizeof (buf));
1078                         }
1079
1080                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1081                             zfs_prop_to_name(pl->pl_prop),
1082                             buf, sourcetype, source);
1083                 } else {
1084                         if (nvlist_lookup_nvlist(userprop,
1085                             pl->pl_user_prop, &propval) != 0) {
1086                                 if (pl->pl_all)
1087                                         continue;
1088                                 sourcetype = ZPROP_SRC_NONE;
1089                                 strval = "-";
1090                         } else {
1091                                 verify(nvlist_lookup_string(propval,
1092                                     ZPROP_VALUE, &strval) == 0);
1093                                 verify(nvlist_lookup_string(propval,
1094                                     ZPROP_SOURCE, &sourceval) == 0);
1095
1096                                 if (strcmp(sourceval,
1097                                     zfs_get_name(zhp)) == 0) {
1098                                         sourcetype = ZPROP_SRC_LOCAL;
1099                                 } else {
1100                                         sourcetype = ZPROP_SRC_INHERITED;
1101                                         (void) strlcpy(source,
1102                                             sourceval, sizeof (source));
1103                                 }
1104                         }
1105
1106                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1107                             pl->pl_user_prop, strval, sourcetype,
1108                             source);
1109                 }
1110         }
1111
1112         return (0);
1113 }
1114
1115 static int
1116 zfs_do_get(int argc, char **argv)
1117 {
1118         zprop_get_cbdata_t cb = { 0 };
1119         int i, c, flags = 0;
1120         char *value, *fields;
1121         int ret;
1122         zprop_list_t fake_name = { 0 };
1123
1124         /*
1125          * Set up default columns and sources.
1126          */
1127         cb.cb_sources = ZPROP_SRC_ALL;
1128         cb.cb_columns[0] = GET_COL_NAME;
1129         cb.cb_columns[1] = GET_COL_PROPERTY;
1130         cb.cb_columns[2] = GET_COL_VALUE;
1131         cb.cb_columns[3] = GET_COL_SOURCE;
1132         cb.cb_type = ZFS_TYPE_DATASET;
1133
1134         /* check options */
1135         while ((c = getopt(argc, argv, ":o:s:rHp")) != -1) {
1136                 switch (c) {
1137                 case 'p':
1138                         cb.cb_literal = B_TRUE;
1139                         break;
1140                 case 'r':
1141                         flags |= ZFS_ITER_RECURSE;
1142                         break;
1143                 case 'H':
1144                         cb.cb_scripted = B_TRUE;
1145                         break;
1146                 case ':':
1147                         (void) fprintf(stderr, gettext("missing argument for "
1148                             "'%c' option\n"), optopt);
1149                         usage(B_FALSE);
1150                         break;
1151                 case 'o':
1152                         /*
1153                          * Process the set of columns to display.  We zero out
1154                          * the structure to give us a blank slate.
1155                          */
1156                         bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1157                         i = 0;
1158                         while (*optarg != '\0') {
1159                                 static char *col_subopts[] =
1160                                     { "name", "property", "value", "source",
1161                                     NULL };
1162
1163                                 if (i == 4) {
1164                                         (void) fprintf(stderr, gettext("too "
1165                                             "many fields given to -o "
1166                                             "option\n"));
1167                                         usage(B_FALSE);
1168                                 }
1169
1170                                 switch (getsubopt(&optarg, col_subopts,
1171                                     &value)) {
1172                                 case 0:
1173                                         cb.cb_columns[i++] = GET_COL_NAME;
1174                                         break;
1175                                 case 1:
1176                                         cb.cb_columns[i++] = GET_COL_PROPERTY;
1177                                         break;
1178                                 case 2:
1179                                         cb.cb_columns[i++] = GET_COL_VALUE;
1180                                         break;
1181                                 case 3:
1182                                         cb.cb_columns[i++] = GET_COL_SOURCE;
1183                                         break;
1184                                 default:
1185                                         (void) fprintf(stderr,
1186                                             gettext("invalid column name "
1187                                             "'%s'\n"), value);
1188                                         usage(B_FALSE);
1189                                 }
1190                         }
1191                         break;
1192
1193                 case 's':
1194                         cb.cb_sources = 0;
1195                         while (*optarg != '\0') {
1196                                 static char *source_subopts[] = {
1197                                         "local", "default", "inherited",
1198                                         "temporary", "none", NULL };
1199
1200                                 switch (getsubopt(&optarg, source_subopts,
1201                                     &value)) {
1202                                 case 0:
1203                                         cb.cb_sources |= ZPROP_SRC_LOCAL;
1204                                         break;
1205                                 case 1:
1206                                         cb.cb_sources |= ZPROP_SRC_DEFAULT;
1207                                         break;
1208                                 case 2:
1209                                         cb.cb_sources |= ZPROP_SRC_INHERITED;
1210                                         break;
1211                                 case 3:
1212                                         cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1213                                         break;
1214                                 case 4:
1215                                         cb.cb_sources |= ZPROP_SRC_NONE;
1216                                         break;
1217                                 default:
1218                                         (void) fprintf(stderr,
1219                                             gettext("invalid source "
1220                                             "'%s'\n"), value);
1221                                         usage(B_FALSE);
1222                                 }
1223                         }
1224                         break;
1225
1226                 case '?':
1227                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1228                             optopt);
1229                         usage(B_FALSE);
1230                 }
1231         }
1232
1233         argc -= optind;
1234         argv += optind;
1235
1236         if (argc < 1) {
1237                 (void) fprintf(stderr, gettext("missing property "
1238                     "argument\n"));
1239                 usage(B_FALSE);
1240         }
1241
1242         fields = argv[0];
1243
1244         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1245             != 0)
1246                 usage(B_FALSE);
1247
1248         argc--;
1249         argv++;
1250
1251         /*
1252          * As part of zfs_expand_proplist(), we keep track of the maximum column
1253          * width for each property.  For the 'NAME' (and 'SOURCE') columns, we
1254          * need to know the maximum name length.  However, the user likely did
1255          * not specify 'name' as one of the properties to fetch, so we need to
1256          * make sure we always include at least this property for
1257          * print_get_headers() to work properly.
1258          */
1259         if (cb.cb_proplist != NULL) {
1260                 fake_name.pl_prop = ZFS_PROP_NAME;
1261                 fake_name.pl_width = strlen(gettext("NAME"));
1262                 fake_name.pl_next = cb.cb_proplist;
1263                 cb.cb_proplist = &fake_name;
1264         }
1265
1266         cb.cb_first = B_TRUE;
1267
1268         /* run for each object */
1269         ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET, NULL,
1270             &cb.cb_proplist, get_callback, &cb);
1271
1272         if (cb.cb_proplist == &fake_name)
1273                 zprop_free_list(fake_name.pl_next);
1274         else
1275                 zprop_free_list(cb.cb_proplist);
1276
1277         return (ret);
1278 }
1279
1280 /*
1281  * inherit [-r] <property> <fs|vol> ...
1282  *
1283  *      -r      Recurse over all children
1284  *
1285  * For each dataset specified on the command line, inherit the given property
1286  * from its parent.  Inheriting a property at the pool level will cause it to
1287  * use the default value.  The '-r' flag will recurse over all children, and is
1288  * useful for setting a property on a hierarchy-wide basis, regardless of any
1289  * local modifications for each dataset.
1290  */
1291
1292 static int
1293 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
1294 {
1295         char *propname = data;
1296         zfs_prop_t prop = zfs_name_to_prop(propname);
1297
1298         /*
1299          * If we're doing it recursively, then ignore properties that
1300          * are not valid for this type of dataset.
1301          */
1302         if (prop != ZPROP_INVAL &&
1303             !zfs_prop_valid_for_type(prop, zfs_get_type(zhp)))
1304                 return (0);
1305
1306         return (zfs_prop_inherit(zhp, propname) != 0);
1307 }
1308
1309 static int
1310 inherit_cb(zfs_handle_t *zhp, void *data)
1311 {
1312         char *propname = data;
1313
1314         return (zfs_prop_inherit(zhp, propname) != 0);
1315 }
1316
1317 static int
1318 zfs_do_inherit(int argc, char **argv)
1319 {
1320         int c;
1321         zfs_prop_t prop;
1322         char *propname;
1323         int ret;
1324         int flags = 0;
1325
1326         /* check options */
1327         while ((c = getopt(argc, argv, "r")) != -1) {
1328                 switch (c) {
1329                 case 'r':
1330                         flags |= ZFS_ITER_RECURSE;
1331                         break;
1332                 case '?':
1333                 default:
1334                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1335                             optopt);
1336                         usage(B_FALSE);
1337                 }
1338         }
1339
1340         argc -= optind;
1341         argv += optind;
1342
1343         /* check number of arguments */
1344         if (argc < 1) {
1345                 (void) fprintf(stderr, gettext("missing property argument\n"));
1346                 usage(B_FALSE);
1347         }
1348         if (argc < 2) {
1349                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1350                 usage(B_FALSE);
1351         }
1352
1353         propname = argv[0];
1354         argc--;
1355         argv++;
1356
1357         if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1358                 if (zfs_prop_readonly(prop)) {
1359                         (void) fprintf(stderr, gettext(
1360                             "%s property is read-only\n"),
1361                             propname);
1362                         return (1);
1363                 }
1364                 if (!zfs_prop_inheritable(prop)) {
1365                         (void) fprintf(stderr, gettext("'%s' property cannot "
1366                             "be inherited\n"), propname);
1367                         if (prop == ZFS_PROP_QUOTA ||
1368                             prop == ZFS_PROP_RESERVATION ||
1369                             prop == ZFS_PROP_REFQUOTA ||
1370                             prop == ZFS_PROP_REFRESERVATION)
1371                                 (void) fprintf(stderr, gettext("use 'zfs set "
1372                                     "%s=none' to clear\n"), propname);
1373                         return (1);
1374                 }
1375         } else if (!zfs_prop_user(propname)) {
1376                 (void) fprintf(stderr, gettext("invalid property '%s'\n"),
1377                     propname);
1378                 usage(B_FALSE);
1379         }
1380
1381         if (flags & ZFS_ITER_RECURSE) {
1382                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1383                     NULL, NULL, inherit_recurse_cb, propname);
1384         } else {
1385                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1386                     NULL, NULL, inherit_cb, propname);
1387         }
1388
1389         return (ret);
1390 }
1391
1392 typedef struct upgrade_cbdata {
1393         uint64_t cb_numupgraded;
1394         uint64_t cb_numsamegraded;
1395         uint64_t cb_numfailed;
1396         uint64_t cb_version;
1397         boolean_t cb_newer;
1398         boolean_t cb_foundone;
1399         char cb_lastfs[ZFS_MAXNAMELEN];
1400 } upgrade_cbdata_t;
1401
1402 static int
1403 same_pool(zfs_handle_t *zhp, const char *name)
1404 {
1405         int len1 = strcspn(name, "/@");
1406         const char *zhname = zfs_get_name(zhp);
1407         int len2 = strcspn(zhname, "/@");
1408
1409         if (len1 != len2)
1410                 return (B_FALSE);
1411         return (strncmp(name, zhname, len1) == 0);
1412 }
1413
1414 static int
1415 upgrade_list_callback(zfs_handle_t *zhp, void *data)
1416 {
1417         upgrade_cbdata_t *cb = data;
1418         int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1419
1420         /* list if it's old/new */
1421         if ((!cb->cb_newer && version < ZPL_VERSION) ||
1422             (cb->cb_newer && version > ZPL_VERSION)) {
1423                 char *str;
1424                 if (cb->cb_newer) {
1425                         str = gettext("The following filesystems are "
1426                             "formatted using a newer software version and\n"
1427                             "cannot be accessed on the current system.\n\n");
1428                 } else {
1429                         str = gettext("The following filesystems are "
1430                             "out of date, and can be upgraded.  After being\n"
1431                             "upgraded, these filesystems (and any 'zfs send' "
1432                             "streams generated from\n"
1433                             "subsequent snapshots) will no longer be "
1434                             "accessible by older software versions.\n\n");
1435                 }
1436
1437                 if (!cb->cb_foundone) {
1438                         (void) puts(str);
1439                         (void) printf(gettext("VER  FILESYSTEM\n"));
1440                         (void) printf(gettext("---  ------------\n"));
1441                         cb->cb_foundone = B_TRUE;
1442                 }
1443
1444                 (void) printf("%2u   %s\n", version, zfs_get_name(zhp));
1445         }
1446
1447         return (0);
1448 }
1449
1450 static int
1451 upgrade_set_callback(zfs_handle_t *zhp, void *data)
1452 {
1453         upgrade_cbdata_t *cb = data;
1454         int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1455
1456         if (cb->cb_version >= ZPL_VERSION_FUID) {
1457                 int spa_version;
1458
1459                 if (zfs_spa_version(zhp, &spa_version) < 0)
1460                         return (-1);
1461
1462                 if (spa_version < SPA_VERSION_FUID) {
1463                         /* can't upgrade */
1464                         (void) printf(gettext("%s: can not be upgraded; "
1465                             "the pool version needs to first be upgraded\nto "
1466                             "version %d\n\n"),
1467                             zfs_get_name(zhp), SPA_VERSION_FUID);
1468                         cb->cb_numfailed++;
1469                         return (0);
1470                 }
1471         }
1472
1473         /* upgrade */
1474         if (version < cb->cb_version) {
1475                 char verstr[16];
1476                 (void) snprintf(verstr, sizeof (verstr),
1477                     "%llu", cb->cb_version);
1478                 if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
1479                         /*
1480                          * If they did "zfs upgrade -a", then we could
1481                          * be doing ioctls to different pools.  We need
1482                          * to log this history once to each pool.
1483                          */
1484                         verify(zpool_stage_history(g_zfs, history_str) == 0);
1485                 }
1486                 if (zfs_prop_set(zhp, "version", verstr) == 0)
1487                         cb->cb_numupgraded++;
1488                 else
1489                         cb->cb_numfailed++;
1490                 (void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
1491         } else if (version > cb->cb_version) {
1492                 /* can't downgrade */
1493                 (void) printf(gettext("%s: can not be downgraded; "
1494                     "it is already at version %u\n"),
1495                     zfs_get_name(zhp), version);
1496                 cb->cb_numfailed++;
1497         } else {
1498                 cb->cb_numsamegraded++;
1499         }
1500         return (0);
1501 }
1502
1503 /*
1504  * zfs upgrade
1505  * zfs upgrade -v
1506  * zfs upgrade [-r] [-V <version>] <-a | filesystem>
1507  */
1508 static int
1509 zfs_do_upgrade(int argc, char **argv)
1510 {
1511         boolean_t all = B_FALSE;
1512         boolean_t showversions = B_FALSE;
1513         int ret;
1514         upgrade_cbdata_t cb = { 0 };
1515         char c;
1516         int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1517
1518         /* check options */
1519         while ((c = getopt(argc, argv, "rvV:a")) != -1) {
1520                 switch (c) {
1521                 case 'r':
1522                         flags |= ZFS_ITER_RECURSE;
1523                         break;
1524                 case 'v':
1525                         showversions = B_TRUE;
1526                         break;
1527                 case 'V':
1528                         if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
1529                             optarg, &cb.cb_version) != 0) {
1530                                 (void) fprintf(stderr,
1531                                     gettext("invalid version %s\n"), optarg);
1532                                 usage(B_FALSE);
1533                         }
1534                         break;
1535                 case 'a':
1536                         all = B_TRUE;
1537                         break;
1538                 case '?':
1539                 default:
1540                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1541                             optopt);
1542                         usage(B_FALSE);
1543                 }
1544         }
1545
1546         argc -= optind;
1547         argv += optind;
1548
1549         if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
1550                 usage(B_FALSE);
1551         if (showversions && (flags & ZFS_ITER_RECURSE || all ||
1552             cb.cb_version || argc))
1553                 usage(B_FALSE);
1554         if ((all || argc) && (showversions))
1555                 usage(B_FALSE);
1556         if (all && argc)
1557                 usage(B_FALSE);
1558
1559         if (showversions) {
1560                 /* Show info on available versions. */
1561                 (void) printf(gettext("The following filesystem versions are "
1562                     "supported:\n\n"));
1563                 (void) printf(gettext("VER  DESCRIPTION\n"));
1564                 (void) printf("---  -----------------------------------------"
1565                     "---------------\n");
1566                 (void) printf(gettext(" 1   Initial ZFS filesystem version\n"));
1567                 (void) printf(gettext(" 2   Enhanced directory entries\n"));
1568                 (void) printf(gettext(" 3   Case insensitive and File system "
1569                     "unique identifer (FUID)\n"));
1570                 (void) printf(gettext("\nFor more information on a particular "
1571                     "version, including supported releases, see:\n\n"));
1572                 (void) printf("http://www.opensolaris.org/os/community/zfs/"
1573                     "version/zpl/N\n\n");
1574                 (void) printf(gettext("Where 'N' is the version number.\n"));
1575                 ret = 0;
1576         } else if (argc || all) {
1577                 /* Upgrade filesystems */
1578                 if (cb.cb_version == 0)
1579                         cb.cb_version = ZPL_VERSION;
1580                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
1581                     NULL, NULL, upgrade_set_callback, &cb);
1582                 (void) printf(gettext("%llu filesystems upgraded\n"),
1583                     cb.cb_numupgraded);
1584                 if (cb.cb_numsamegraded) {
1585                         (void) printf(gettext("%llu filesystems already at "
1586                             "this version\n"),
1587                             cb.cb_numsamegraded);
1588                 }
1589                 if (cb.cb_numfailed != 0)
1590                         ret = 1;
1591         } else {
1592                 /* List old-version filesytems */
1593                 boolean_t found;
1594                 (void) printf(gettext("This system is currently running "
1595                     "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
1596
1597                 flags |= ZFS_ITER_RECURSE;
1598                 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
1599                     NULL, NULL, upgrade_list_callback, &cb);
1600
1601                 found = cb.cb_foundone;
1602                 cb.cb_foundone = B_FALSE;
1603                 cb.cb_newer = B_TRUE;
1604
1605                 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
1606                     NULL, NULL, upgrade_list_callback, &cb);
1607
1608                 if (!cb.cb_foundone && !found) {
1609                         (void) printf(gettext("All filesystems are "
1610                             "formatted with the current version.\n"));
1611                 }
1612         }
1613
1614         return (ret);
1615 }
1616
1617 /*
1618  * list [-rH] [-o property[,property]...] [-t type[,type]...]
1619  *      [-s property [-s property]...] [-S property [-S property]...]
1620  *      <dataset> ...
1621  *
1622  *      -r      Recurse over all children
1623  *      -H      Scripted mode; elide headers and separate columns by tabs
1624  *      -o      Control which fields to display.
1625  *      -t      Control which object types to display.
1626  *      -s      Specify sort columns, descending order.
1627  *      -S      Specify sort columns, ascending order.
1628  *
1629  * When given no arguments, lists all filesystems in the system.
1630  * Otherwise, list the specified datasets, optionally recursing down them if
1631  * '-r' is specified.
1632  */
1633 typedef struct list_cbdata {
1634         boolean_t       cb_first;
1635         boolean_t       cb_scripted;
1636         zprop_list_t    *cb_proplist;
1637 } list_cbdata_t;
1638
1639 /*
1640  * Given a list of columns to display, output appropriate headers for each one.
1641  */
1642 static void
1643 print_header(zprop_list_t *pl)
1644 {
1645         char headerbuf[ZFS_MAXPROPLEN];
1646         const char *header;
1647         int i;
1648         boolean_t first = B_TRUE;
1649         boolean_t right_justify;
1650
1651         for (; pl != NULL; pl = pl->pl_next) {
1652                 if (!first) {
1653                         (void) printf("  ");
1654                 } else {
1655                         first = B_FALSE;
1656                 }
1657
1658                 right_justify = B_FALSE;
1659                 if (pl->pl_prop != ZPROP_INVAL) {
1660                         header = zfs_prop_column_name(pl->pl_prop);
1661                         right_justify = zfs_prop_align_right(pl->pl_prop);
1662                 } else {
1663                         for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
1664                                 headerbuf[i] = toupper(pl->pl_user_prop[i]);
1665                         headerbuf[i] = '\0';
1666                         header = headerbuf;
1667                 }
1668
1669                 if (pl->pl_next == NULL && !right_justify)
1670                         (void) printf("%s", header);
1671                 else if (right_justify)
1672                         (void) printf("%*s", pl->pl_width, header);
1673                 else
1674                         (void) printf("%-*s", pl->pl_width, header);
1675         }
1676
1677         (void) printf("\n");
1678 }
1679
1680 /*
1681  * Given a dataset and a list of fields, print out all the properties according
1682  * to the described layout.
1683  */
1684 static void
1685 print_dataset(zfs_handle_t *zhp, zprop_list_t *pl, boolean_t scripted)
1686 {
1687         boolean_t first = B_TRUE;
1688         char property[ZFS_MAXPROPLEN];
1689         nvlist_t *userprops = zfs_get_user_props(zhp);
1690         nvlist_t *propval;
1691         char *propstr;
1692         boolean_t right_justify;
1693         int width;
1694
1695         for (; pl != NULL; pl = pl->pl_next) {
1696                 if (!first) {
1697                         if (scripted)
1698                                 (void) printf("\t");
1699                         else
1700                                 (void) printf("  ");
1701                 } else {
1702                         first = B_FALSE;
1703                 }
1704
1705                 right_justify = B_FALSE;
1706                 if (pl->pl_prop != ZPROP_INVAL) {
1707                         if (zfs_prop_get(zhp, pl->pl_prop, property,
1708                             sizeof (property), NULL, NULL, 0, B_FALSE) != 0)
1709                                 propstr = "-";
1710                         else
1711                                 propstr = property;
1712
1713                         right_justify = zfs_prop_align_right(pl->pl_prop);
1714                 } else {
1715                         if (nvlist_lookup_nvlist(userprops,
1716                             pl->pl_user_prop, &propval) != 0)
1717                                 propstr = "-";
1718                         else
1719                                 verify(nvlist_lookup_string(propval,
1720                                     ZPROP_VALUE, &propstr) == 0);
1721                 }
1722
1723                 width = pl->pl_width;
1724
1725                 /*
1726                  * If this is being called in scripted mode, or if this is the
1727                  * last column and it is left-justified, don't include a width
1728                  * format specifier.
1729                  */
1730                 if (scripted || (pl->pl_next == NULL && !right_justify))
1731                         (void) printf("%s", propstr);
1732                 else if (right_justify)
1733                         (void) printf("%*s", width, propstr);
1734                 else
1735                         (void) printf("%-*s", width, propstr);
1736         }
1737
1738         (void) printf("\n");
1739 }
1740
1741 /*
1742  * Generic callback function to list a dataset or snapshot.
1743  */
1744 static int
1745 list_callback(zfs_handle_t *zhp, void *data)
1746 {
1747         list_cbdata_t *cbp = data;
1748
1749         if (cbp->cb_first) {
1750                 if (!cbp->cb_scripted)
1751                         print_header(cbp->cb_proplist);
1752                 cbp->cb_first = B_FALSE;
1753         }
1754
1755         print_dataset(zhp, cbp->cb_proplist, cbp->cb_scripted);
1756
1757         return (0);
1758 }
1759
1760 static int
1761 zfs_do_list(int argc, char **argv)
1762 {
1763         int c;
1764         boolean_t scripted = B_FALSE;
1765         static char default_fields[] =
1766             "name,used,available,referenced,mountpoint";
1767         int types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
1768         boolean_t types_specified = B_FALSE;
1769         char *fields = NULL;
1770         list_cbdata_t cb = { 0 };
1771         char *value;
1772         int ret;
1773         zfs_sort_column_t *sortcol = NULL;
1774         int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
1775
1776         /* check options */
1777         while ((c = getopt(argc, argv, ":o:rt:Hs:S:")) != -1) {
1778                 switch (c) {
1779                 case 'o':
1780                         fields = optarg;
1781                         break;
1782                 case 'r':
1783                         flags |= ZFS_ITER_RECURSE;
1784                         break;
1785                 case 'H':
1786                         scripted = B_TRUE;
1787                         break;
1788                 case 's':
1789                         if (zfs_add_sort_column(&sortcol, optarg,
1790                             B_FALSE) != 0) {
1791                                 (void) fprintf(stderr,
1792                                     gettext("invalid property '%s'\n"), optarg);
1793                                 usage(B_FALSE);
1794                         }
1795                         break;
1796                 case 'S':
1797                         if (zfs_add_sort_column(&sortcol, optarg,
1798                             B_TRUE) != 0) {
1799                                 (void) fprintf(stderr,
1800                                     gettext("invalid property '%s'\n"), optarg);
1801                                 usage(B_FALSE);
1802                         }
1803                         break;
1804                 case 't':
1805                         types = 0;
1806                         types_specified = B_TRUE;
1807                         flags &= ~ZFS_ITER_PROP_LISTSNAPS;
1808                         while (*optarg != '\0') {
1809                                 static char *type_subopts[] = { "filesystem",
1810                                     "volume", "snapshot", "all", NULL };
1811
1812                                 switch (getsubopt(&optarg, type_subopts,
1813                                     &value)) {
1814                                 case 0:
1815                                         types |= ZFS_TYPE_FILESYSTEM;
1816                                         break;
1817                                 case 1:
1818                                         types |= ZFS_TYPE_VOLUME;
1819                                         break;
1820                                 case 2:
1821                                         types |= ZFS_TYPE_SNAPSHOT;
1822                                         break;
1823                                 case 3:
1824                                         types = ZFS_TYPE_DATASET;
1825                                         break;
1826
1827                                 default:
1828                                         (void) fprintf(stderr,
1829                                             gettext("invalid type '%s'\n"),
1830                                             value);
1831                                         usage(B_FALSE);
1832                                 }
1833                         }
1834                         break;
1835                 case ':':
1836                         (void) fprintf(stderr, gettext("missing argument for "
1837                             "'%c' option\n"), optopt);
1838                         usage(B_FALSE);
1839                         break;
1840                 case '?':
1841                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1842                             optopt);
1843                         usage(B_FALSE);
1844                 }
1845         }
1846
1847         argc -= optind;
1848         argv += optind;
1849
1850         if (fields == NULL)
1851                 fields = default_fields;
1852
1853         /*
1854          * If "-o space" and no types were specified, don't display snapshots.
1855          */
1856         if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
1857                 types &= ~ZFS_TYPE_SNAPSHOT;
1858
1859         /*
1860          * If the user specifies '-o all', the zprop_get_list() doesn't
1861          * normally include the name of the dataset.  For 'zfs list', we always
1862          * want this property to be first.
1863          */
1864         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1865             != 0)
1866                 usage(B_FALSE);
1867
1868         cb.cb_scripted = scripted;
1869         cb.cb_first = B_TRUE;
1870
1871         ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
1872             list_callback, &cb);
1873
1874         zprop_free_list(cb.cb_proplist);
1875         zfs_free_sort_columns(sortcol);
1876
1877         if (ret == 0 && cb.cb_first && !cb.cb_scripted)
1878                 (void) printf(gettext("no datasets available\n"));
1879
1880         return (ret);
1881 }
1882
1883 /*
1884  * zfs rename <fs | snap | vol> <fs | snap | vol>
1885  * zfs rename -p <fs | vol> <fs | vol>
1886  * zfs rename -r <snap> <snap>
1887  *
1888  * Renames the given dataset to another of the same type.
1889  *
1890  * The '-p' flag creates all the non-existing ancestors of the target first.
1891  */
1892 /* ARGSUSED */
1893 static int
1894 zfs_do_rename(int argc, char **argv)
1895 {
1896         zfs_handle_t *zhp;
1897         int c;
1898         int ret;
1899         boolean_t recurse = B_FALSE;
1900         boolean_t parents = B_FALSE;
1901
1902         /* check options */
1903         while ((c = getopt(argc, argv, "pr")) != -1) {
1904                 switch (c) {
1905                 case 'p':
1906                         parents = B_TRUE;
1907                         break;
1908                 case 'r':
1909                         recurse = B_TRUE;
1910                         break;
1911                 case '?':
1912                 default:
1913                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1914                             optopt);
1915                         usage(B_FALSE);
1916                 }
1917         }
1918
1919         argc -= optind;
1920         argv += optind;
1921
1922         /* check number of arguments */
1923         if (argc < 1) {
1924                 (void) fprintf(stderr, gettext("missing source dataset "
1925                     "argument\n"));
1926                 usage(B_FALSE);
1927         }
1928         if (argc < 2) {
1929                 (void) fprintf(stderr, gettext("missing target dataset "
1930                     "argument\n"));
1931                 usage(B_FALSE);
1932         }
1933         if (argc > 2) {
1934                 (void) fprintf(stderr, gettext("too many arguments\n"));
1935                 usage(B_FALSE);
1936         }
1937
1938         if (recurse && parents) {
1939                 (void) fprintf(stderr, gettext("-p and -r options are mutually "
1940                     "exclusive\n"));
1941                 usage(B_FALSE);
1942         }
1943
1944         if (recurse && strchr(argv[0], '@') == 0) {
1945                 (void) fprintf(stderr, gettext("source dataset for recursive "
1946                     "rename must be a snapshot\n"));
1947                 usage(B_FALSE);
1948         }
1949
1950         if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
1951             ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
1952                 return (1);
1953
1954         /* If we were asked and the name looks good, try to create ancestors. */
1955         if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
1956             zfs_create_ancestors(g_zfs, argv[1]) != 0) {
1957                 zfs_close(zhp);
1958                 return (1);
1959         }
1960
1961         ret = (zfs_rename(zhp, argv[1], recurse) != 0);
1962
1963         zfs_close(zhp);
1964         return (ret);
1965 }
1966
1967 /*
1968  * zfs promote <fs>
1969  *
1970  * Promotes the given clone fs to be the parent
1971  */
1972 /* ARGSUSED */
1973 static int
1974 zfs_do_promote(int argc, char **argv)
1975 {
1976         zfs_handle_t *zhp;
1977         int ret;
1978
1979         /* check options */
1980         if (argc > 1 && argv[1][0] == '-') {
1981                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1982                     argv[1][1]);
1983                 usage(B_FALSE);
1984         }
1985
1986         /* check number of arguments */
1987         if (argc < 2) {
1988                 (void) fprintf(stderr, gettext("missing clone filesystem"
1989                     " argument\n"));
1990                 usage(B_FALSE);
1991         }
1992         if (argc > 2) {
1993                 (void) fprintf(stderr, gettext("too many arguments\n"));
1994                 usage(B_FALSE);
1995         }
1996
1997         zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1998         if (zhp == NULL)
1999                 return (1);
2000
2001         ret = (zfs_promote(zhp) != 0);
2002
2003
2004         zfs_close(zhp);
2005         return (ret);
2006 }
2007
2008 /*
2009  * zfs rollback [-rRf] <snapshot>
2010  *
2011  *      -r      Delete any intervening snapshots before doing rollback
2012  *      -R      Delete any snapshots and their clones
2013  *      -f      ignored for backwards compatability
2014  *
2015  * Given a filesystem, rollback to a specific snapshot, discarding any changes
2016  * since then and making it the active dataset.  If more recent snapshots exist,
2017  * the command will complain unless the '-r' flag is given.
2018  */
2019 typedef struct rollback_cbdata {
2020         uint64_t        cb_create;
2021         boolean_t       cb_first;
2022         int             cb_doclones;
2023         char            *cb_target;
2024         int             cb_error;
2025         boolean_t       cb_recurse;
2026         boolean_t       cb_dependent;
2027 } rollback_cbdata_t;
2028
2029 /*
2030  * Report any snapshots more recent than the one specified.  Used when '-r' is
2031  * not specified.  We reuse this same callback for the snapshot dependents - if
2032  * 'cb_dependent' is set, then this is a dependent and we should report it
2033  * without checking the transaction group.
2034  */
2035 static int
2036 rollback_check(zfs_handle_t *zhp, void *data)
2037 {
2038         rollback_cbdata_t *cbp = data;
2039
2040         if (cbp->cb_doclones) {
2041                 zfs_close(zhp);
2042                 return (0);
2043         }
2044
2045         if (!cbp->cb_dependent) {
2046                 if (strcmp(zfs_get_name(zhp), cbp->cb_target) != 0 &&
2047                     zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
2048                     zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
2049                     cbp->cb_create) {
2050
2051                         if (cbp->cb_first && !cbp->cb_recurse) {
2052                                 (void) fprintf(stderr, gettext("cannot "
2053                                     "rollback to '%s': more recent snapshots "
2054                                     "exist\n"),
2055                                     cbp->cb_target);
2056                                 (void) fprintf(stderr, gettext("use '-r' to "
2057                                     "force deletion of the following "
2058                                     "snapshots:\n"));
2059                                 cbp->cb_first = 0;
2060                                 cbp->cb_error = 1;
2061                         }
2062
2063                         if (cbp->cb_recurse) {
2064                                 cbp->cb_dependent = B_TRUE;
2065                                 if (zfs_iter_dependents(zhp, B_TRUE,
2066                                     rollback_check, cbp) != 0) {
2067                                         zfs_close(zhp);
2068                                         return (-1);
2069                                 }
2070                                 cbp->cb_dependent = B_FALSE;
2071                         } else {
2072                                 (void) fprintf(stderr, "%s\n",
2073                                     zfs_get_name(zhp));
2074                         }
2075                 }
2076         } else {
2077                 if (cbp->cb_first && cbp->cb_recurse) {
2078                         (void) fprintf(stderr, gettext("cannot rollback to "
2079                             "'%s': clones of previous snapshots exist\n"),
2080                             cbp->cb_target);
2081                         (void) fprintf(stderr, gettext("use '-R' to "
2082                             "force deletion of the following clones and "
2083                             "dependents:\n"));
2084                         cbp->cb_first = 0;
2085                         cbp->cb_error = 1;
2086                 }
2087
2088                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
2089         }
2090
2091         zfs_close(zhp);
2092         return (0);
2093 }
2094
2095 static int
2096 zfs_do_rollback(int argc, char **argv)
2097 {
2098         int ret;
2099         int c;
2100         boolean_t force = B_FALSE;
2101         rollback_cbdata_t cb = { 0 };
2102         zfs_handle_t *zhp, *snap;
2103         char parentname[ZFS_MAXNAMELEN];
2104         char *delim;
2105
2106         /* check options */
2107         while ((c = getopt(argc, argv, "rRf")) != -1) {
2108                 switch (c) {
2109                 case 'r':
2110                         cb.cb_recurse = 1;
2111                         break;
2112                 case 'R':
2113                         cb.cb_recurse = 1;
2114                         cb.cb_doclones = 1;
2115                         break;
2116                 case 'f':
2117                         force = B_TRUE;
2118                         break;
2119                 case '?':
2120                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2121                             optopt);
2122                         usage(B_FALSE);
2123                 }
2124         }
2125
2126         argc -= optind;
2127         argv += optind;
2128
2129         /* check number of arguments */
2130         if (argc < 1) {
2131                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
2132                 usage(B_FALSE);
2133         }
2134         if (argc > 1) {
2135                 (void) fprintf(stderr, gettext("too many arguments\n"));
2136                 usage(B_FALSE);
2137         }
2138
2139         /* open the snapshot */
2140         if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
2141                 return (1);
2142
2143         /* open the parent dataset */
2144         (void) strlcpy(parentname, argv[0], sizeof (parentname));
2145         verify((delim = strrchr(parentname, '@')) != NULL);
2146         *delim = '\0';
2147         if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
2148                 zfs_close(snap);
2149                 return (1);
2150         }
2151
2152         /*
2153          * Check for more recent snapshots and/or clones based on the presence
2154          * of '-r' and '-R'.
2155          */
2156         cb.cb_target = argv[0];
2157         cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
2158         cb.cb_first = B_TRUE;
2159         cb.cb_error = 0;
2160         if ((ret = zfs_iter_children(zhp, rollback_check, &cb)) != 0)
2161                 goto out;
2162
2163         if ((ret = cb.cb_error) != 0)
2164                 goto out;
2165
2166         /*
2167          * Rollback parent to the given snapshot.
2168          */
2169         ret = zfs_rollback(zhp, snap, force);
2170
2171 out:
2172         zfs_close(snap);
2173         zfs_close(zhp);
2174
2175         if (ret == 0)
2176                 return (0);
2177         else
2178                 return (1);
2179 }
2180
2181 /*
2182  * zfs set property=value { fs | snap | vol } ...
2183  *
2184  * Sets the given property for all datasets specified on the command line.
2185  */
2186 typedef struct set_cbdata {
2187         char            *cb_propname;
2188         char            *cb_value;
2189 } set_cbdata_t;
2190
2191 static int
2192 set_callback(zfs_handle_t *zhp, void *data)
2193 {
2194         set_cbdata_t *cbp = data;
2195
2196         if (zfs_prop_set(zhp, cbp->cb_propname, cbp->cb_value) != 0) {
2197                 switch (libzfs_errno(g_zfs)) {
2198                 case EZFS_MOUNTFAILED:
2199                         (void) fprintf(stderr, gettext("property may be set "
2200                             "but unable to remount filesystem\n"));
2201                         break;
2202                 case EZFS_SHARENFSFAILED:
2203                         (void) fprintf(stderr, gettext("property may be set "
2204                             "but unable to reshare filesystem\n"));
2205                         break;
2206                 }
2207                 return (1);
2208         }
2209         return (0);
2210 }
2211
2212 static int
2213 zfs_do_set(int argc, char **argv)
2214 {
2215         set_cbdata_t cb;
2216         int ret;
2217
2218         /* check for options */
2219         if (argc > 1 && argv[1][0] == '-') {
2220                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2221                     argv[1][1]);
2222                 usage(B_FALSE);
2223         }
2224
2225         /* check number of arguments */
2226         if (argc < 2) {
2227                 (void) fprintf(stderr, gettext("missing property=value "
2228                     "argument\n"));
2229                 usage(B_FALSE);
2230         }
2231         if (argc < 3) {
2232                 (void) fprintf(stderr, gettext("missing dataset name\n"));
2233                 usage(B_FALSE);
2234         }
2235
2236         /* validate property=value argument */
2237         cb.cb_propname = argv[1];
2238         if (((cb.cb_value = strchr(cb.cb_propname, '=')) == NULL) ||
2239             (cb.cb_value[1] == '\0')) {
2240                 (void) fprintf(stderr, gettext("missing value in "
2241                     "property=value argument\n"));
2242                 usage(B_FALSE);
2243         }
2244
2245         *cb.cb_value = '\0';
2246         cb.cb_value++;
2247
2248         if (*cb.cb_propname == '\0') {
2249                 (void) fprintf(stderr,
2250                     gettext("missing property in property=value argument\n"));
2251                 usage(B_FALSE);
2252         }
2253
2254         ret = zfs_for_each(argc - 2, argv + 2, NULL,
2255             ZFS_TYPE_DATASET, NULL, NULL, set_callback, &cb);
2256
2257         return (ret);
2258 }
2259
2260 /*
2261  * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
2262  *
2263  * Creates a snapshot with the given name.  While functionally equivalent to
2264  * 'zfs create', it is a separate command to differentiate intent.
2265  */
2266 static int
2267 zfs_do_snapshot(int argc, char **argv)
2268 {
2269         boolean_t recursive = B_FALSE;
2270         int ret;
2271         char c;
2272         nvlist_t *props;
2273
2274         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
2275                 (void) fprintf(stderr, gettext("internal error: "
2276                     "out of memory\n"));
2277                 return (1);
2278         }
2279
2280         /* check options */
2281         while ((c = getopt(argc, argv, "ro:")) != -1) {
2282                 switch (c) {
2283                 case 'o':
2284                         if (parseprop(props))
2285                                 return (1);
2286                         break;
2287                 case 'r':
2288                         recursive = B_TRUE;
2289                         break;
2290                 case '?':
2291                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2292                             optopt);
2293                         goto usage;
2294                 }
2295         }
2296
2297         argc -= optind;
2298         argv += optind;
2299
2300         /* check number of arguments */
2301         if (argc < 1) {
2302                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2303                 goto usage;
2304         }
2305         if (argc > 1) {
2306                 (void) fprintf(stderr, gettext("too many arguments\n"));
2307                 goto usage;
2308         }
2309
2310         ret = zfs_snapshot(g_zfs, argv[0], recursive, props);
2311         nvlist_free(props);
2312         if (ret && recursive)
2313                 (void) fprintf(stderr, gettext("no snapshots were created\n"));
2314         return (ret != 0);
2315
2316 usage:
2317         nvlist_free(props);
2318         usage(B_FALSE);
2319         return (-1);
2320 }
2321
2322 /*
2323  * zfs send [-v] -R [-i|-I <@snap>] <fs@snap>
2324  * zfs send [-v] [-i|-I <@snap>] <fs@snap>
2325  *
2326  * Send a backup stream to stdout.
2327  */
2328 static int
2329 zfs_do_send(int argc, char **argv)
2330 {
2331         char *fromname = NULL;
2332         char *toname = NULL;
2333         char *cp;
2334         zfs_handle_t *zhp;
2335         boolean_t doall = B_FALSE;
2336         boolean_t replicate = B_FALSE;
2337         boolean_t fromorigin = B_FALSE;
2338         boolean_t verbose = B_FALSE;
2339         int c, err;
2340
2341         /* check options */
2342         while ((c = getopt(argc, argv, ":i:I:Rv")) != -1) {
2343                 switch (c) {
2344                 case 'i':
2345                         if (fromname)
2346                                 usage(B_FALSE);
2347                         fromname = optarg;
2348                         break;
2349                 case 'I':
2350                         if (fromname)
2351                                 usage(B_FALSE);
2352                         fromname = optarg;
2353                         doall = B_TRUE;
2354                         break;
2355                 case 'R':
2356                         replicate = B_TRUE;
2357                         break;
2358                 case 'v':
2359                         verbose = B_TRUE;
2360                         break;
2361                 case ':':
2362                         (void) fprintf(stderr, gettext("missing argument for "
2363                             "'%c' option\n"), optopt);
2364                         usage(B_FALSE);
2365                         break;
2366                 case '?':
2367                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2368                             optopt);
2369                         usage(B_FALSE);
2370                 }
2371         }
2372
2373         argc -= optind;
2374         argv += optind;
2375
2376         /* check number of arguments */
2377         if (argc < 1) {
2378                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2379                 usage(B_FALSE);
2380         }
2381         if (argc > 1) {
2382                 (void) fprintf(stderr, gettext("too many arguments\n"));
2383                 usage(B_FALSE);
2384         }
2385
2386         if (isatty(STDOUT_FILENO)) {
2387                 (void) fprintf(stderr,
2388                     gettext("Error: Stream can not be written to a terminal.\n"
2389                     "You must redirect standard output.\n"));
2390                 return (1);
2391         }
2392
2393         cp = strchr(argv[0], '@');
2394         if (cp == NULL) {
2395                 (void) fprintf(stderr,
2396                     gettext("argument must be a snapshot\n"));
2397                 usage(B_FALSE);
2398         }
2399         *cp = '\0';
2400         toname = cp + 1;
2401         zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2402         if (zhp == NULL)
2403                 return (1);
2404
2405         /*
2406          * If they specified the full path to the snapshot, chop off
2407          * everything except the short name of the snapshot, but special
2408          * case if they specify the origin.
2409          */
2410         if (fromname && (cp = strchr(fromname, '@')) != NULL) {
2411                 char origin[ZFS_MAXNAMELEN];
2412                 zprop_source_t src;
2413
2414                 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
2415                     origin, sizeof (origin), &src, NULL, 0, B_FALSE);
2416
2417                 if (strcmp(origin, fromname) == 0) {
2418                         fromname = NULL;
2419                         fromorigin = B_TRUE;
2420                 } else {
2421                         *cp = '\0';
2422                         if (cp != fromname && strcmp(argv[0], fromname)) {
2423                                 (void) fprintf(stderr,
2424                                     gettext("incremental source must be "
2425                                     "in same filesystem\n"));
2426                                 usage(B_FALSE);
2427                         }
2428                         fromname = cp + 1;
2429                         if (strchr(fromname, '@') || strchr(fromname, '/')) {
2430                                 (void) fprintf(stderr,
2431                                     gettext("invalid incremental source\n"));
2432                                 usage(B_FALSE);
2433                         }
2434                 }
2435         }
2436
2437         if (replicate && fromname == NULL)
2438                 doall = B_TRUE;
2439
2440         err = zfs_send(zhp, fromname, toname, replicate, doall, fromorigin,
2441             verbose, STDOUT_FILENO);
2442         zfs_close(zhp);
2443
2444         return (err != 0);
2445 }
2446
2447 /*
2448  * zfs receive [-dnvF] <fs@snap>
2449  *
2450  * Restore a backup stream from stdin.
2451  */
2452 static int
2453 zfs_do_receive(int argc, char **argv)
2454 {
2455         int c, err;
2456         recvflags_t flags;
2457
2458         bzero(&flags, sizeof (recvflags_t));
2459         /* check options */
2460         while ((c = getopt(argc, argv, ":dnvF")) != -1) {
2461                 switch (c) {
2462                 case 'd':
2463                         flags.isprefix = B_TRUE;
2464                         break;
2465                 case 'n':
2466                         flags.dryrun = B_TRUE;
2467                         break;
2468                 case 'v':
2469                         flags.verbose = B_TRUE;
2470                         break;
2471                 case 'F':
2472                         flags.force = B_TRUE;
2473                         break;
2474                 case ':':
2475                         (void) fprintf(stderr, gettext("missing argument for "
2476                             "'%c' option\n"), optopt);
2477                         usage(B_FALSE);
2478                         break;
2479                 case '?':
2480                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2481                             optopt);
2482                         usage(B_FALSE);
2483                 }
2484         }
2485
2486         argc -= optind;
2487         argv += optind;
2488
2489         /* check number of arguments */
2490         if (argc < 1) {
2491                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2492                 usage(B_FALSE);
2493         }
2494         if (argc > 1) {
2495                 (void) fprintf(stderr, gettext("too many arguments\n"));
2496                 usage(B_FALSE);
2497         }
2498
2499         if (isatty(STDIN_FILENO)) {
2500                 (void) fprintf(stderr,
2501                     gettext("Error: Backup stream can not be read "
2502                     "from a terminal.\n"
2503                     "You must redirect standard input.\n"));
2504                 return (1);
2505         }
2506
2507         err = zfs_receive(g_zfs, argv[0], flags, STDIN_FILENO, NULL);
2508
2509         return (err != 0);
2510 }
2511
2512 typedef struct allow_cb {
2513         int  a_permcnt;
2514         size_t a_treeoffset;
2515 } allow_cb_t;
2516
2517 static void
2518 zfs_print_perms(avl_tree_t *tree)
2519 {
2520         zfs_perm_node_t *permnode;
2521
2522         permnode = avl_first(tree);
2523         while (permnode != NULL) {
2524                 (void) printf("%s", permnode->z_pname);
2525                 permnode = AVL_NEXT(tree, permnode);
2526                 if (permnode)
2527                         (void) printf(",");
2528                 else
2529                         (void) printf("\n");
2530         }
2531 }
2532
2533 /*
2534  * Iterate over user/groups/everyone/... and the call perm_iter
2535  * function to print actual permission when tree has >0 nodes.
2536  */
2537 static void
2538 zfs_iter_perms(avl_tree_t *tree, const char *banner, allow_cb_t *cb)
2539 {
2540         zfs_allow_node_t *item;
2541         avl_tree_t *ptree;
2542
2543         item = avl_first(tree);
2544         while (item) {
2545                 ptree = (void *)((char *)item + cb->a_treeoffset);
2546                 if (avl_numnodes(ptree)) {
2547                         if (cb->a_permcnt++ == 0)
2548                                 (void) printf("%s\n", banner);
2549                         (void) printf("\t%s", item->z_key);
2550                         /*
2551                          * Avoid an extra space being printed
2552                          * for "everyone" which is keyed with a null
2553                          * string
2554                          */
2555                         if (item->z_key[0] != '\0')
2556                                 (void) printf(" ");
2557                         zfs_print_perms(ptree);
2558                 }
2559                 item = AVL_NEXT(tree, item);
2560         }
2561 }
2562
2563 #define LINES "-------------------------------------------------------------\n"
2564 static int
2565 zfs_print_allows(char *ds)
2566 {
2567         zfs_allow_t *curperms, *perms;
2568         zfs_handle_t *zhp;
2569         allow_cb_t allowcb = { 0 };
2570         char banner[MAXPATHLEN];
2571
2572         if (ds[0] == '-')
2573                 usage(B_FALSE);
2574
2575         if (strrchr(ds, '@')) {
2576                 (void) fprintf(stderr, gettext("Snapshots don't have 'allow'"
2577                     " permissions\n"));
2578                 return (1);
2579         }
2580         if ((zhp = zfs_open(g_zfs, ds, ZFS_TYPE_DATASET)) == NULL)
2581                 return (1);
2582
2583         if (zfs_perm_get(zhp, &perms)) {
2584                 (void) fprintf(stderr,
2585                     gettext("Failed to retrieve 'allows' on %s\n"), ds);
2586                 zfs_close(zhp);
2587                 return (1);
2588         }
2589
2590         zfs_close(zhp);
2591
2592         if (perms != NULL)
2593                 (void) printf("%s", LINES);
2594         for (curperms = perms; curperms; curperms = curperms->z_next) {
2595
2596                 (void) snprintf(banner, sizeof (banner),
2597                     "Permission sets on (%s)", curperms->z_setpoint);
2598                 allowcb.a_treeoffset =
2599                     offsetof(zfs_allow_node_t, z_localdescend);
2600                 allowcb.a_permcnt = 0;
2601                 zfs_iter_perms(&curperms->z_sets, banner, &allowcb);
2602
2603                 (void) snprintf(banner, sizeof (banner),
2604                     "Create time permissions on (%s)", curperms->z_setpoint);
2605                 allowcb.a_treeoffset =
2606                     offsetof(zfs_allow_node_t, z_localdescend);
2607                 allowcb.a_permcnt = 0;
2608                 zfs_iter_perms(&curperms->z_crperms, banner, &allowcb);
2609
2610
2611                 (void) snprintf(banner, sizeof (banner),
2612                     "Local permissions on (%s)", curperms->z_setpoint);
2613                 allowcb.a_treeoffset = offsetof(zfs_allow_node_t, z_local);
2614                 allowcb.a_permcnt = 0;
2615                 zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2616                 zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2617                 zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2618
2619                 (void) snprintf(banner, sizeof (banner),
2620                     "Descendent permissions on (%s)", curperms->z_setpoint);
2621                 allowcb.a_treeoffset = offsetof(zfs_allow_node_t, z_descend);
2622                 allowcb.a_permcnt = 0;
2623                 zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2624                 zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2625                 zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2626
2627                 (void) snprintf(banner, sizeof (banner),
2628                     "Local+Descendent permissions on (%s)",
2629                     curperms->z_setpoint);
2630                 allowcb.a_treeoffset =
2631                     offsetof(zfs_allow_node_t, z_localdescend);
2632                 allowcb.a_permcnt = 0;
2633                 zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2634                 zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2635                 zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2636
2637                 (void) printf("%s", LINES);
2638         }
2639         zfs_free_allows(perms);
2640         return (0);
2641 }
2642
2643 #define ALLOWOPTIONS "ldcsu:g:e"
2644 #define UNALLOWOPTIONS "ldcsu:g:er"
2645
2646 /*
2647  * Validate options, and build necessary datastructure to display/remove/add
2648  * permissions.
2649  * Returns 0 - If permissions should be added/removed
2650  * Returns 1 - If permissions should be displayed.
2651  * Returns -1 - on failure
2652  */
2653 int
2654 parse_allow_args(int *argc, char **argv[], boolean_t unallow,
2655     char **ds, int *recurse, nvlist_t **zperms)
2656 {
2657         int c;
2658         char *options = unallow ? UNALLOWOPTIONS : ALLOWOPTIONS;
2659         zfs_deleg_inherit_t deleg_type = ZFS_DELEG_NONE;
2660         zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
2661         char *who = NULL;
2662         char *perms = NULL;
2663         zfs_handle_t *zhp;
2664
2665         while ((c = getopt(*argc, *argv, options)) != -1) {
2666                 switch (c) {
2667                 case 'l':
2668                         if (who_type == ZFS_DELEG_CREATE ||
2669                             who_type == ZFS_DELEG_NAMED_SET)
2670                                 usage(B_FALSE);
2671
2672                         deleg_type |= ZFS_DELEG_PERM_LOCAL;
2673                         break;
2674                 case 'd':
2675                         if (who_type == ZFS_DELEG_CREATE ||
2676                             who_type == ZFS_DELEG_NAMED_SET)
2677                                 usage(B_FALSE);
2678
2679                         deleg_type |= ZFS_DELEG_PERM_DESCENDENT;
2680                         break;
2681                 case 'r':
2682                         *recurse = B_TRUE;
2683                         break;
2684                 case 'c':
2685                         if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2686                                 usage(B_FALSE);
2687                         if (deleg_type)
2688                                 usage(B_FALSE);
2689                         who_type = ZFS_DELEG_CREATE;
2690                         break;
2691                 case 's':
2692                         if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2693                                 usage(B_FALSE);
2694                         if (deleg_type)
2695                                 usage(B_FALSE);
2696                         who_type = ZFS_DELEG_NAMED_SET;
2697                         break;
2698                 case 'u':
2699                         if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2700                                 usage(B_FALSE);
2701                         who_type = ZFS_DELEG_USER;
2702                         who = optarg;
2703                         break;
2704                 case 'g':
2705                         if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2706                                 usage(B_FALSE);
2707                         who_type = ZFS_DELEG_GROUP;
2708                         who = optarg;
2709                         break;
2710                 case 'e':
2711                         if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2712                                 usage(B_FALSE);
2713                         who_type = ZFS_DELEG_EVERYONE;
2714                         break;
2715                 default:
2716                         usage(B_FALSE);
2717                         break;
2718                 }
2719         }
2720
2721         if (deleg_type == 0)
2722                 deleg_type = ZFS_DELEG_PERM_LOCALDESCENDENT;
2723
2724         *argc -= optind;
2725         *argv += optind;
2726
2727         if (unallow == B_FALSE && *argc == 1) {
2728                 /*
2729                  * Only print permissions if no options were processed
2730                  */
2731                 if (optind == 1)
2732                         return (1);
2733                 else
2734                         usage(B_FALSE);
2735         }
2736
2737         /*
2738          * initialize variables for zfs_build_perms based on number
2739          * of arguments.
2740          * 3 arguments ==>      zfs [un]allow joe perm,perm,perm <dataset> or
2741          *                      zfs [un]allow -s @set1 perm,perm <dataset>
2742          * 2 arguments ==>      zfs [un]allow -c perm,perm <dataset> or
2743          *                      zfs [un]allow -u|-g <name> perm <dataset> or
2744          *                      zfs [un]allow -e perm,perm <dataset>
2745          *                      zfs unallow joe <dataset>
2746          *                      zfs unallow -s @set1 <dataset>
2747          * 1 argument  ==>      zfs [un]allow -e <dataset> or
2748          *                      zfs [un]allow -c <dataset>
2749          */
2750
2751         switch (*argc) {
2752         case 3:
2753                 perms = (*argv)[1];
2754                 who = (*argv)[0];
2755                 *ds = (*argv)[2];
2756
2757                 /*
2758                  * advance argc/argv for do_allow cases.
2759                  * for do_allow case make sure who have a know who type
2760                  * and its not a permission set.
2761                  */
2762                 if (unallow == B_TRUE) {
2763                         *argc -= 2;
2764                         *argv += 2;
2765                 } else if (who_type != ZFS_DELEG_WHO_UNKNOWN &&
2766                     who_type != ZFS_DELEG_NAMED_SET)
2767                         usage(B_FALSE);
2768                 break;
2769
2770         case 2:
2771                 if (unallow == B_TRUE && (who_type == ZFS_DELEG_EVERYONE ||
2772                     who_type == ZFS_DELEG_CREATE || who != NULL)) {
2773                         perms = (*argv)[0];
2774                         *ds = (*argv)[1];
2775                 } else {
2776                         if (unallow == B_FALSE &&
2777                             (who_type == ZFS_DELEG_WHO_UNKNOWN ||
2778                             who_type == ZFS_DELEG_NAMED_SET))
2779                                 usage(B_FALSE);
2780                         else if (who_type == ZFS_DELEG_WHO_UNKNOWN ||
2781                             who_type == ZFS_DELEG_NAMED_SET)
2782                                 who = (*argv)[0];
2783                         else if (who_type != ZFS_DELEG_NAMED_SET)
2784                                 perms = (*argv)[0];
2785                         *ds = (*argv)[1];
2786                 }
2787                 if (unallow == B_TRUE) {
2788                         (*argc)--;
2789                         (*argv)++;
2790                 }
2791                 break;
2792
2793         case 1:
2794                 if (unallow == B_FALSE)
2795                         usage(B_FALSE);
2796                 if (who == NULL && who_type != ZFS_DELEG_CREATE &&
2797                     who_type != ZFS_DELEG_EVERYONE)
2798                         usage(B_FALSE);
2799                 *ds = (*argv)[0];
2800                 break;
2801
2802         default:
2803                 usage(B_FALSE);
2804         }
2805
2806         if (strrchr(*ds, '@')) {
2807                 (void) fprintf(stderr,
2808                     gettext("Can't set or remove 'allow' permissions "
2809                     "on snapshots.\n"));
2810                         return (-1);
2811         }
2812
2813         if ((zhp = zfs_open(g_zfs, *ds, ZFS_TYPE_DATASET)) == NULL)
2814                 return (-1);
2815
2816         if ((zfs_build_perms(zhp, who, perms,
2817             who_type, deleg_type, zperms)) != 0) {
2818                 zfs_close(zhp);
2819                 return (-1);
2820         }
2821         zfs_close(zhp);
2822         return (0);
2823 }
2824
2825 static int
2826 zfs_do_allow(int argc, char **argv)
2827 {
2828         char *ds;
2829         nvlist_t *zperms = NULL;
2830         zfs_handle_t *zhp;
2831         int unused;
2832         int ret;
2833
2834         if ((ret = parse_allow_args(&argc, &argv, B_FALSE, &ds,
2835             &unused, &zperms)) == -1)
2836                 return (1);
2837
2838         if (ret == 1)
2839                 return (zfs_print_allows(argv[0]));
2840
2841         if ((zhp = zfs_open(g_zfs, ds, ZFS_TYPE_DATASET)) == NULL)
2842                 return (1);
2843
2844         if (zfs_perm_set(zhp, zperms)) {
2845                 zfs_close(zhp);
2846                 nvlist_free(zperms);
2847                 return (1);
2848         }
2849         nvlist_free(zperms);
2850         zfs_close(zhp);
2851
2852         return (0);
2853 }
2854
2855 static int
2856 unallow_callback(zfs_handle_t *zhp, void *data)
2857 {
2858         nvlist_t *nvp = (nvlist_t *)data;
2859         int error;
2860
2861         error = zfs_perm_remove(zhp, nvp);
2862         if (error) {
2863                 (void) fprintf(stderr, gettext("Failed to remove permissions "
2864                     "on %s\n"), zfs_get_name(zhp));
2865         }
2866         return (error);
2867 }
2868
2869 static int
2870 zfs_do_unallow(int argc, char **argv)
2871 {
2872         int recurse = B_FALSE;
2873         char *ds;
2874         int error;
2875         nvlist_t *zperms = NULL;
2876         int flags = 0;
2877
2878         if (parse_allow_args(&argc, &argv, B_TRUE,
2879             &ds, &recurse, &zperms) == -1)
2880                 return (1);
2881
2882         if (recurse)
2883                 flags |= ZFS_ITER_RECURSE;
2884         error = zfs_for_each(argc, argv, flags,
2885             ZFS_TYPE_FILESYSTEM|ZFS_TYPE_VOLUME, NULL,
2886             NULL, unallow_callback, (void *)zperms);
2887
2888         if (zperms)
2889                 nvlist_free(zperms);
2890
2891         return (error);
2892 }
2893
2894 typedef struct get_all_cbdata {
2895         zfs_handle_t    **cb_handles;
2896         size_t          cb_alloc;
2897         size_t          cb_used;
2898         uint_t          cb_types;
2899         boolean_t       cb_verbose;
2900 } get_all_cbdata_t;
2901
2902 #define CHECK_SPINNER 30
2903 #define SPINNER_TIME 3          /* seconds */
2904 #define MOUNT_TIME 5            /* seconds */
2905
2906 static int
2907 get_one_dataset(zfs_handle_t *zhp, void *data)
2908 {
2909         static char spin[] = { '-', '\\', '|', '/' };
2910         static int spinval = 0;
2911         static int spincheck = 0;
2912         static time_t last_spin_time = (time_t)0;
2913         get_all_cbdata_t *cbp = data;
2914         zfs_type_t type = zfs_get_type(zhp);
2915
2916         if (cbp->cb_verbose) {
2917                 if (--spincheck < 0) {
2918                         time_t now = time(NULL);
2919                         if (last_spin_time + SPINNER_TIME < now) {
2920                                 (void) printf("\b%c", spin[spinval++ % 4]);
2921                                 (void) fflush(stdout);
2922                                 last_spin_time = now;
2923                         }
2924                         spincheck = CHECK_SPINNER;
2925                 }
2926         }
2927
2928         /*
2929          * Interate over any nested datasets.
2930          */
2931         if (type == ZFS_TYPE_FILESYSTEM &&
2932             zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
2933                 zfs_close(zhp);
2934                 return (1);
2935         }
2936
2937         /*
2938          * Skip any datasets whose type does not match.
2939          */
2940         if ((type & cbp->cb_types) == 0) {
2941                 zfs_close(zhp);
2942                 return (0);
2943         }
2944
2945         if (cbp->cb_alloc == cbp->cb_used) {
2946                 zfs_handle_t **handles;
2947
2948                 if (cbp->cb_alloc == 0)
2949                         cbp->cb_alloc = 64;
2950                 else
2951                         cbp->cb_alloc *= 2;
2952
2953                 handles = safe_malloc(cbp->cb_alloc * sizeof (void *));
2954
2955                 if (cbp->cb_handles) {
2956                         bcopy(cbp->cb_handles, handles,
2957                             cbp->cb_used * sizeof (void *));
2958                         free(cbp->cb_handles);
2959                 }
2960
2961                 cbp->cb_handles = handles;
2962         }
2963
2964         cbp->cb_handles[cbp->cb_used++] = zhp;
2965
2966         return (0);
2967 }
2968
2969 static void
2970 get_all_datasets(uint_t types, zfs_handle_t ***dslist, size_t *count,
2971     boolean_t verbose)
2972 {
2973         get_all_cbdata_t cb = { 0 };
2974         cb.cb_types = types;
2975         cb.cb_verbose = verbose;
2976
2977         if (verbose) {
2978                 (void) printf("%s: *", gettext("Reading ZFS config"));
2979                 (void) fflush(stdout);
2980         }
2981
2982         (void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
2983
2984         *dslist = cb.cb_handles;
2985         *count = cb.cb_used;
2986
2987         if (verbose) {
2988                 (void) printf("\b%s\n", gettext("done."));
2989         }
2990 }
2991
2992 static int
2993 dataset_cmp(const void *a, const void *b)
2994 {
2995         zfs_handle_t **za = (zfs_handle_t **)a;
2996         zfs_handle_t **zb = (zfs_handle_t **)b;
2997         char mounta[MAXPATHLEN];
2998         char mountb[MAXPATHLEN];
2999         boolean_t gota, gotb;
3000
3001         if ((gota = (zfs_get_type(*za) == ZFS_TYPE_FILESYSTEM)) != 0)
3002                 verify(zfs_prop_get(*za, ZFS_PROP_MOUNTPOINT, mounta,
3003                     sizeof (mounta), NULL, NULL, 0, B_FALSE) == 0);
3004         if ((gotb = (zfs_get_type(*zb) == ZFS_TYPE_FILESYSTEM)) != 0)
3005                 verify(zfs_prop_get(*zb, ZFS_PROP_MOUNTPOINT, mountb,
3006                     sizeof (mountb), NULL, NULL, 0, B_FALSE) == 0);
3007
3008         if (gota && gotb)
3009                 return (strcmp(mounta, mountb));
3010
3011         if (gota)
3012                 return (-1);
3013         if (gotb)
3014                 return (1);
3015
3016         return (strcmp(zfs_get_name(a), zfs_get_name(b)));
3017 }
3018
3019 /*
3020  * Generic callback for sharing or mounting filesystems.  Because the code is so
3021  * similar, we have a common function with an extra parameter to determine which
3022  * mode we are using.
3023  */
3024 #define OP_SHARE        0x1
3025 #define OP_MOUNT        0x2
3026
3027 /*
3028  * Share or mount a dataset.
3029  */
3030 static int
3031 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
3032     boolean_t explicit, const char *options)
3033 {
3034         char mountpoint[ZFS_MAXPROPLEN];
3035         char shareopts[ZFS_MAXPROPLEN];
3036         char smbshareopts[ZFS_MAXPROPLEN];
3037         const char *cmdname = op == OP_SHARE ? "share" : "mount";
3038         struct mnttab mnt;
3039         uint64_t zoned, canmount;
3040         zfs_type_t type = zfs_get_type(zhp);
3041         boolean_t shared_nfs, shared_smb;
3042
3043         assert(type & (ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME));
3044
3045         if (type == ZFS_TYPE_FILESYSTEM) {
3046                 /*
3047                  * Check to make sure we can mount/share this dataset.  If we
3048                  * are in the global zone and the filesystem is exported to a
3049                  * local zone, or if we are in a local zone and the
3050                  * filesystem is not exported, then it is an error.
3051                  */
3052                 zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
3053
3054                 if (zoned && getzoneid() == GLOBAL_ZONEID) {
3055                         if (!explicit)
3056                                 return (0);
3057
3058                         (void) fprintf(stderr, gettext("cannot %s '%s': "
3059                             "dataset is exported to a local zone\n"), cmdname,
3060                             zfs_get_name(zhp));
3061                         return (1);
3062
3063                 } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
3064                         if (!explicit)
3065                                 return (0);
3066
3067                         (void) fprintf(stderr, gettext("cannot %s '%s': "
3068                             "permission denied\n"), cmdname,
3069                             zfs_get_name(zhp));
3070                         return (1);
3071                 }
3072
3073                 /*
3074                  * Ignore any filesystems which don't apply to us. This
3075                  * includes those with a legacy mountpoint, or those with
3076                  * legacy share options.
3077                  */
3078                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
3079                     sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
3080                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
3081                     sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
3082                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
3083                     sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
3084                 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
3085
3086                 if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
3087                     strcmp(smbshareopts, "off") == 0) {
3088                         if (!explicit)
3089                                 return (0);
3090
3091                         (void) fprintf(stderr, gettext("cannot share '%s': "
3092                             "legacy share\n"), zfs_get_name(zhp));
3093                         (void) fprintf(stderr, gettext("use share(1M) to "
3094                             "share this filesystem\n"));
3095                         return (1);
3096                 }
3097
3098                 /*
3099                  * We cannot share or mount legacy filesystems. If the
3100                  * shareopts is non-legacy but the mountpoint is legacy, we
3101                  * treat it as a legacy share.
3102                  */
3103                 if (strcmp(mountpoint, "legacy") == 0) {
3104                         if (!explicit)
3105                                 return (0);
3106
3107                         (void) fprintf(stderr, gettext("cannot %s '%s': "
3108                             "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
3109                         (void) fprintf(stderr, gettext("use %s(1M) to "
3110                             "%s this filesystem\n"), cmdname, cmdname);
3111                         return (1);
3112                 }
3113
3114                 if (strcmp(mountpoint, "none") == 0) {
3115                         if (!explicit)
3116                                 return (0);
3117
3118                         (void) fprintf(stderr, gettext("cannot %s '%s': no "
3119                             "mountpoint set\n"), cmdname, zfs_get_name(zhp));
3120                         return (1);
3121                 }
3122
3123                 /*
3124                  * canmount     explicit        outcome
3125                  * on           no              pass through
3126                  * on           yes             pass through
3127                  * off          no              return 0
3128                  * off          yes             display error, return 1
3129                  * noauto       no              return 0
3130                  * noauto       yes             pass through
3131                  */
3132                 if (canmount == ZFS_CANMOUNT_OFF) {
3133                         if (!explicit)
3134                                 return (0);
3135
3136                         (void) fprintf(stderr, gettext("cannot %s '%s': "
3137                             "'canmount' property is set to 'off'\n"), cmdname,
3138                             zfs_get_name(zhp));
3139                         return (1);
3140                 } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
3141                         return (0);
3142                 }
3143
3144                 /*
3145                  * At this point, we have verified that the mountpoint and/or
3146                  * shareopts are appropriate for auto management. If the
3147                  * filesystem is already mounted or shared, return (failing
3148                  * for explicit requests); otherwise mount or share the
3149                  * filesystem.
3150                  */
3151                 switch (op) {
3152                 case OP_SHARE:
3153
3154                         shared_nfs = zfs_is_shared_nfs(zhp, NULL);
3155                         shared_smb = zfs_is_shared_smb(zhp, NULL);
3156
3157                         if (shared_nfs && shared_smb ||
3158                             (shared_nfs && strcmp(shareopts, "on") == 0 &&
3159                             strcmp(smbshareopts, "off") == 0) ||
3160                             (shared_smb && strcmp(smbshareopts, "on") == 0 &&
3161                             strcmp(shareopts, "off") == 0)) {
3162                                 if (!explicit)
3163                                         return (0);
3164
3165                                 (void) fprintf(stderr, gettext("cannot share "
3166                                     "'%s': filesystem already shared\n"),
3167                                     zfs_get_name(zhp));
3168                                 return (1);
3169                         }
3170
3171                         if (!zfs_is_mounted(zhp, NULL) &&
3172                             zfs_mount(zhp, NULL, 0) != 0)
3173                                 return (1);
3174
3175                         if (protocol == NULL) {
3176                                 if (zfs_shareall(zhp) != 0)
3177                                         return (1);
3178                         } else if (strcmp(protocol, "nfs") == 0) {
3179                                 if (zfs_share_nfs(zhp))
3180                                         return (1);
3181                         } else if (strcmp(protocol, "smb") == 0) {
3182                                 if (zfs_share_smb(zhp))
3183                                         return (1);
3184                         } else {
3185                                 (void) fprintf(stderr, gettext("cannot share "
3186                                     "'%s': invalid share type '%s' "
3187                                     "specified\n"),
3188                                     zfs_get_name(zhp), protocol);
3189                                 return (1);
3190                         }
3191
3192                         break;
3193
3194                 case OP_MOUNT:
3195                         if (options == NULL)
3196                                 mnt.mnt_mntopts = "";
3197                         else
3198                                 mnt.mnt_mntopts = (char *)options;
3199
3200                         if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
3201                             zfs_is_mounted(zhp, NULL)) {
3202                                 if (!explicit)
3203                                         return (0);
3204
3205                                 (void) fprintf(stderr, gettext("cannot mount "
3206                                     "'%s': filesystem already mounted\n"),
3207                                     zfs_get_name(zhp));
3208                                 return (1);
3209                         }
3210
3211                         if (zfs_mount(zhp, options, flags) != 0)
3212                                 return (1);
3213                         break;
3214                 }
3215         } else {
3216                 assert(op == OP_SHARE);
3217
3218                 /*
3219                  * Ignore any volumes that aren't shared.
3220                  */
3221                 verify(zfs_prop_get(zhp, ZFS_PROP_SHAREISCSI, shareopts,
3222                     sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
3223
3224                 if (strcmp(shareopts, "off") == 0) {
3225                         if (!explicit)
3226                                 return (0);
3227
3228                         (void) fprintf(stderr, gettext("cannot share '%s': "
3229                             "'shareiscsi' property not set\n"),
3230                             zfs_get_name(zhp));
3231                         (void) fprintf(stderr, gettext("set 'shareiscsi' "
3232                             "property or use iscsitadm(1M) to share this "
3233                             "volume\n"));
3234                         return (1);
3235                 }
3236
3237                 if (zfs_is_shared_iscsi(zhp)) {
3238                         if (!explicit)
3239                                 return (0);
3240
3241                         (void) fprintf(stderr, gettext("cannot share "
3242                             "'%s': volume already shared\n"),
3243                             zfs_get_name(zhp));
3244                         return (1);
3245                 }
3246
3247                 if (zfs_share_iscsi(zhp) != 0)
3248                         return (1);
3249         }
3250
3251         return (0);
3252 }
3253
3254 /*
3255  * Reports progress in the form "(current/total)".  Not thread-safe.
3256  */
3257 static void
3258 report_mount_progress(int current, int total)
3259 {
3260         static int len;
3261         static char *reverse = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"
3262             "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
3263         static time_t last_progress_time;
3264         time_t now = time(NULL);
3265
3266         /* report 1..n instead of 0..n-1 */
3267         ++current;
3268
3269         /* display header if we're here for the first time */
3270         if (current == 1) {
3271                 (void) printf(gettext("Mounting ZFS filesystems: "));
3272                 len = 0;
3273         } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
3274                 /* too soon to report again */
3275                 return;
3276         }
3277
3278         last_progress_time = now;
3279
3280         /* back up to prepare for overwriting */
3281         if (len)
3282                 (void) printf("%*.*s", len, len, reverse);
3283
3284         /* We put a newline at the end if this is the last one.  */
3285         len = printf("(%d/%d)%s", current, total, current == total ? "\n" : "");
3286         (void) fflush(stdout);
3287 }
3288
3289 static void
3290 append_options(char *mntopts, char *newopts)
3291 {
3292         int len = strlen(mntopts);
3293
3294         /* original length plus new string to append plus 1 for the comma */
3295         if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
3296                 (void) fprintf(stderr, gettext("the opts argument for "
3297                     "'%c' option is too long (more than %d chars)\n"),
3298                     "-o", MNT_LINE_MAX);
3299                 usage(B_FALSE);
3300         }
3301
3302         if (*mntopts)
3303                 mntopts[len++] = ',';
3304
3305         (void) strcpy(&mntopts[len], newopts);
3306 }
3307
3308 static int
3309 share_mount(int op, int argc, char **argv)
3310 {
3311         int do_all = 0;
3312         boolean_t verbose = B_FALSE;
3313         int c, ret = 0;
3314         char *options = NULL;
3315         int types, flags = 0;
3316
3317         /* check options */
3318         while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
3319             != -1) {
3320                 switch (c) {
3321                 case 'a':
3322                         do_all = 1;
3323                         break;
3324                 case 'v':
3325                         verbose = B_TRUE;
3326                         break;
3327                 case 'o':
3328                         if (*optarg == '\0') {
3329                                 (void) fprintf(stderr, gettext("empty mount "
3330                                     "options (-o) specified\n"));
3331                                 usage(B_FALSE);
3332                         }
3333
3334                         if (options == NULL)
3335                                 options = safe_malloc(MNT_LINE_MAX + 1);
3336
3337                         /* option validation is done later */
3338                         append_options(options, optarg);
3339                         break;
3340
3341                 case 'O':
3342                         warnx("no overlay mounts support on FreeBSD, ignoring");
3343                         break;
3344                 case ':':
3345                         (void) fprintf(stderr, gettext("missing argument for "
3346                             "'%c' option\n"), optopt);
3347                         usage(B_FALSE);
3348                         break;
3349                 case '?':
3350                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3351                             optopt);
3352                         usage(B_FALSE);
3353                 }
3354         }
3355
3356         argc -= optind;
3357         argv += optind;
3358
3359         /* check number of arguments */
3360         if (do_all) {
3361                 zfs_handle_t **dslist = NULL;
3362                 size_t i, count = 0;
3363                 char *protocol = NULL;
3364
3365                 if (op == OP_MOUNT) {
3366                         types = ZFS_TYPE_FILESYSTEM;
3367                 } else if (argc > 0) {
3368                         if (strcmp(argv[0], "nfs") == 0 ||
3369                             strcmp(argv[0], "smb") == 0) {
3370                                 types = ZFS_TYPE_FILESYSTEM;
3371                         } else if (strcmp(argv[0], "iscsi") == 0) {
3372                                 types = ZFS_TYPE_VOLUME;
3373                         } else {
3374                                 (void) fprintf(stderr, gettext("share type "
3375                                     "must be 'nfs', 'smb' or 'iscsi'\n"));
3376                                 usage(B_FALSE);
3377                         }
3378                         protocol = argv[0];
3379                         argc--;
3380                         argv++;
3381                 } else {
3382                         types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
3383                 }
3384
3385                 if (argc != 0) {
3386                         (void) fprintf(stderr, gettext("too many arguments\n"));
3387                         usage(B_FALSE);
3388                 }
3389
3390                 get_all_datasets(types, &dslist, &count, verbose);
3391
3392                 if (count == 0)
3393                         return (0);
3394
3395                 qsort(dslist, count, sizeof (void *), dataset_cmp);
3396
3397                 for (i = 0; i < count; i++) {
3398                         if (verbose)
3399                                 report_mount_progress(i, count);
3400
3401                         if (share_mount_one(dslist[i], op, flags, protocol,
3402                             B_FALSE, options) != 0)
3403                                 ret = 1;
3404                         zfs_close(dslist[i]);
3405                 }
3406
3407                 free(dslist);
3408         } else if (argc == 0) {
3409                 struct statfs *sfs;
3410                 int i, n;
3411
3412                 if ((op == OP_SHARE) || (options != NULL)) {
3413                         (void) fprintf(stderr, gettext("missing filesystem "
3414                             "argument (specify -a for all)\n"));
3415                         usage(B_FALSE);
3416                 }
3417
3418                 /*
3419                  * When mount is given no arguments, go through /etc/mnttab and
3420                  * display any active ZFS mounts.  We hide any snapshots, since
3421                  * they are controlled automatically.
3422                  */
3423                 if ((n = getmntinfo(&sfs, MNT_WAIT)) == 0) {
3424                         fprintf(stderr, "getmntinfo(): %s\n", strerror(errno));
3425                         return (0);
3426                 }
3427                 for (i = 0; i < n; i++) {
3428                         if (strcmp(sfs[i].f_fstypename, MNTTYPE_ZFS) != 0 ||
3429                             strchr(sfs[i].f_mntfromname, '@') != NULL)
3430                                 continue;
3431
3432                         (void) printf("%-30s  %s\n", sfs[i].f_mntfromname,
3433                             sfs[i].f_mntonname);
3434                 }
3435
3436         } else {
3437                 zfs_handle_t *zhp;
3438
3439                 types = ZFS_TYPE_FILESYSTEM;
3440                 if (op == OP_SHARE)
3441                         types |= ZFS_TYPE_VOLUME;
3442
3443                 if (argc > 1) {
3444                         (void) fprintf(stderr,
3445                             gettext("too many arguments\n"));
3446                         usage(B_FALSE);
3447                 }
3448
3449                 if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL) {
3450                         ret = 1;
3451                 } else {
3452                         ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
3453                             options);
3454                         zfs_close(zhp);
3455                 }
3456         }
3457
3458         return (ret);
3459 }
3460
3461 /*
3462  * zfs mount -a [nfs | iscsi]
3463  * zfs mount filesystem
3464  *
3465  * Mount all filesystems, or mount the given filesystem.
3466  */
3467 static int
3468 zfs_do_mount(int argc, char **argv)
3469 {
3470         return (share_mount(OP_MOUNT, argc, argv));
3471 }
3472
3473 /*
3474  * zfs share -a [nfs | iscsi | smb]
3475  * zfs share filesystem
3476  *
3477  * Share all filesystems, or share the given filesystem.
3478  */
3479 static int
3480 zfs_do_share(int argc, char **argv)
3481 {
3482         return (share_mount(OP_SHARE, argc, argv));
3483 }
3484
3485 typedef struct unshare_unmount_node {
3486         zfs_handle_t    *un_zhp;
3487         char            *un_mountp;
3488         uu_avl_node_t   un_avlnode;
3489 } unshare_unmount_node_t;
3490
3491 /* ARGSUSED */
3492 static int
3493 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
3494 {
3495         const unshare_unmount_node_t *l = larg;
3496         const unshare_unmount_node_t *r = rarg;
3497
3498         return (strcmp(l->un_mountp, r->un_mountp));
3499 }
3500
3501 /*
3502  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
3503  * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
3504  * and unmount it appropriately.
3505  */
3506 static int
3507 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
3508 {
3509         zfs_handle_t *zhp;
3510         int ret;
3511         struct stat64 statbuf;
3512         struct mnttab search = { 0 }, entry;
3513         const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
3514         ino_t path_inode;
3515
3516         /*
3517          * Search for the path in /etc/mnttab.  Rather than looking for the
3518          * specific path, which can be fooled by non-standard paths (i.e. ".."
3519          * or "//"), we stat() the path and search for the corresponding
3520          * (major,minor) device pair.
3521          */
3522         if (stat64(path, &statbuf) != 0) {
3523                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3524                     cmdname, path, strerror(errno));
3525                 return (1);
3526         }
3527         path_inode = statbuf.st_ino;
3528
3529         /*
3530          * Search for the given (major,minor) pair in the mount table.
3531          */
3532         search.mnt_mountp = path;
3533         rewind(mnttab_file);
3534         if (getmntany(mnttab_file, &entry, &search) != 0) {
3535                 if (op == OP_SHARE) {
3536                         (void) fprintf(stderr, gettext("cannot %s '%s': not "
3537                             "currently mounted\n"), cmdname, path);
3538                         return (1);
3539                 }
3540                 (void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
3541                     path);
3542                 if ((ret = umount2(path, flags)) != 0)
3543                         (void) fprintf(stderr, gettext("%s: %s\n"), path,
3544                             strerror(errno));
3545                 return (ret != 0);
3546         }
3547
3548         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
3549                 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
3550                     "filesystem\n"), cmdname, path);
3551                 return (1);
3552         }
3553
3554         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3555             ZFS_TYPE_FILESYSTEM)) == NULL)
3556                 return (1);
3557
3558         ret = 1;
3559         if (stat64(entry.mnt_mountp, &statbuf) != 0) {
3560                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3561                     cmdname, path, strerror(errno));
3562                 goto out;
3563         } else if (statbuf.st_ino != path_inode) {
3564                 (void) fprintf(stderr, gettext("cannot "
3565                     "%s '%s': not a mountpoint\n"), cmdname, path);
3566                 goto out;
3567         }
3568
3569         if (op == OP_SHARE) {
3570                 char nfs_mnt_prop[ZFS_MAXPROPLEN];
3571                 char smbshare_prop[ZFS_MAXPROPLEN];
3572
3573                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
3574                     sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
3575                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
3576                     sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
3577
3578                 if (strcmp(nfs_mnt_prop, "off") == 0 &&
3579                     strcmp(smbshare_prop, "off") == 0) {
3580                         (void) fprintf(stderr, gettext("cannot unshare "
3581                             "'%s': legacy share\n"), path);
3582                         (void) fprintf(stderr, gettext("use "
3583                             "unshare(1M) to unshare this filesystem\n"));
3584                 } else if (!zfs_is_shared(zhp)) {
3585                         (void) fprintf(stderr, gettext("cannot unshare '%s': "
3586                             "not currently shared\n"), path);
3587                 } else {
3588                         ret = zfs_unshareall_bypath(zhp, path);
3589                 }
3590         } else {
3591                 char mtpt_prop[ZFS_MAXPROPLEN];
3592
3593                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
3594                     sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
3595
3596                 if (is_manual) {
3597                         ret = zfs_unmount(zhp, NULL, flags);
3598                 } else if (strcmp(mtpt_prop, "legacy") == 0) {
3599                         (void) fprintf(stderr, gettext("cannot unmount "
3600                             "'%s': legacy mountpoint\n"),
3601                             zfs_get_name(zhp));
3602                         (void) fprintf(stderr, gettext("use umount(1M) "
3603                             "to unmount this filesystem\n"));
3604                 } else {
3605                         ret = zfs_unmountall(zhp, flags);
3606                 }
3607         }
3608
3609 out:
3610         zfs_close(zhp);
3611
3612         return (ret != 0);
3613 }
3614
3615 /*
3616  * Generic callback for unsharing or unmounting a filesystem.
3617  */
3618 static int
3619 unshare_unmount(int op, int argc, char **argv)
3620 {
3621         int do_all = 0;
3622         int flags = 0;
3623         int ret = 0;
3624         int types, c;
3625         zfs_handle_t *zhp;
3626         char nfsiscsi_mnt_prop[ZFS_MAXPROPLEN];
3627         char sharesmb[ZFS_MAXPROPLEN];
3628
3629         /* check options */
3630         while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
3631                 switch (c) {
3632                 case 'a':
3633                         do_all = 1;
3634                         break;
3635                 case 'f':
3636                         flags = MS_FORCE;
3637                         break;
3638                 case '?':
3639                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3640                             optopt);
3641                         usage(B_FALSE);
3642                 }
3643         }
3644
3645         argc -= optind;
3646         argv += optind;
3647
3648         if (do_all) {
3649                 /*
3650                  * We could make use of zfs_for_each() to walk all datasets in
3651                  * the system, but this would be very inefficient, especially
3652                  * since we would have to linearly search /etc/mnttab for each
3653                  * one.  Instead, do one pass through /etc/mnttab looking for
3654                  * zfs entries and call zfs_unmount() for each one.
3655                  *
3656                  * Things get a little tricky if the administrator has created
3657                  * mountpoints beneath other ZFS filesystems.  In this case, we
3658                  * have to unmount the deepest filesystems first.  To accomplish
3659                  * this, we place all the mountpoints in an AVL tree sorted by
3660                  * the special type (dataset name), and walk the result in
3661                  * reverse to make sure to get any snapshots first.
3662                  */
3663                 uu_avl_pool_t *pool;
3664                 uu_avl_t *tree;
3665                 unshare_unmount_node_t *node;
3666                 uu_avl_index_t idx;
3667                 uu_avl_walk_t *walk;
3668                 struct statfs *sfs;
3669                 int i, n;
3670
3671                 if (argc != 0) {
3672                         (void) fprintf(stderr, gettext("too many arguments\n"));
3673                         usage(B_FALSE);
3674                 }
3675
3676                 if ((pool = uu_avl_pool_create("unmount_pool",
3677                     sizeof (unshare_unmount_node_t),
3678                     offsetof(unshare_unmount_node_t, un_avlnode),
3679                     unshare_unmount_compare,
3680                     UU_DEFAULT)) == NULL) {
3681                         (void) fprintf(stderr, gettext("internal error: "
3682                             "out of memory\n"));
3683                         exit(1);
3684                 }
3685
3686                 if ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL) {
3687                         (void) fprintf(stderr, gettext("internal error: "
3688                             "out of memory\n"));
3689                         exit(1);
3690                 }
3691
3692                 if ((n = getmntinfo(&sfs, MNT_WAIT)) == 0) {
3693                         (void) fprintf(stderr, gettext("internal error: "
3694                             "getmntinfo() failed\n"));
3695                         exit(1);
3696                 }
3697                 for (i = 0; i < n; i++) {
3698
3699                         /* ignore non-ZFS entries */
3700                         if (strcmp(sfs[i].f_fstypename, MNTTYPE_ZFS) != 0)
3701                                 continue;
3702
3703                         /* ignore snapshots */
3704                         if (strchr(sfs[i].f_mntfromname, '@') != NULL)
3705                                 continue;
3706
3707                         if ((zhp = zfs_open(g_zfs, sfs[i].f_mntfromname,
3708                             ZFS_TYPE_FILESYSTEM)) == NULL) {
3709                                 ret = 1;
3710                                 continue;
3711                         }
3712
3713                         switch (op) {
3714                         case OP_SHARE:
3715                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3716                                     nfsiscsi_mnt_prop,
3717                                     sizeof (nfsiscsi_mnt_prop),
3718                                     NULL, NULL, 0, B_FALSE) == 0);
3719                                 if (strcmp(nfsiscsi_mnt_prop, "off") != 0)
3720                                         break;
3721                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3722                                     nfsiscsi_mnt_prop,
3723                                     sizeof (nfsiscsi_mnt_prop),
3724                                     NULL, NULL, 0, B_FALSE) == 0);
3725                                 if (strcmp(nfsiscsi_mnt_prop, "off") == 0)
3726                                         continue;
3727                                 break;
3728                         case OP_MOUNT:
3729                                 /* Ignore legacy mounts */
3730                                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
3731                                     nfsiscsi_mnt_prop,
3732                                     sizeof (nfsiscsi_mnt_prop),
3733                                     NULL, NULL, 0, B_FALSE) == 0);
3734                                 if (strcmp(nfsiscsi_mnt_prop, "legacy") == 0)
3735                                         continue;
3736                                 /* Ignore canmount=noauto mounts */
3737                                 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
3738                                     ZFS_CANMOUNT_NOAUTO)
3739                                         continue;
3740                         default:
3741                                 break;
3742                         }
3743
3744                         node = safe_malloc(sizeof (unshare_unmount_node_t));
3745                         node->un_zhp = zhp;
3746
3747                         if ((node->un_mountp = strdup(sfs[i].f_mntonname)) ==
3748                             NULL) {
3749                                 (void) fprintf(stderr, gettext("internal error:"
3750                                     " out of memory\n"));
3751                                 exit(1);
3752                         }
3753
3754                         uu_avl_node_init(node, &node->un_avlnode, pool);
3755
3756                         if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
3757                                 uu_avl_insert(tree, node, idx);
3758                         } else {
3759                                 zfs_close(node->un_zhp);
3760                                 free(node->un_mountp);
3761                                 free(node);
3762                         }
3763                 }
3764
3765                 /*
3766                  * Walk the AVL tree in reverse, unmounting each filesystem and
3767                  * removing it from the AVL tree in the process.
3768                  */
3769                 if ((walk = uu_avl_walk_start(tree,
3770                     UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL) {
3771                         (void) fprintf(stderr,
3772                             gettext("internal error: out of memory"));
3773                         exit(1);
3774                 }
3775
3776                 while ((node = uu_avl_walk_next(walk)) != NULL) {
3777                         uu_avl_remove(tree, node);
3778
3779                         switch (op) {
3780                         case OP_SHARE:
3781                                 if (zfs_unshareall_bypath(node->un_zhp,
3782                                     node->un_mountp) != 0)
3783                                         ret = 1;
3784                                 break;
3785
3786                         case OP_MOUNT:
3787                                 if (zfs_unmount(node->un_zhp,
3788                                     node->un_mountp, flags) != 0)
3789                                         ret = 1;
3790                                 break;
3791                         }
3792
3793                         zfs_close(node->un_zhp);
3794                         free(node->un_mountp);
3795                         free(node);
3796                 }
3797
3798                 uu_avl_walk_end(walk);
3799                 uu_avl_destroy(tree);
3800                 uu_avl_pool_destroy(pool);
3801
3802                 if (op == OP_SHARE) {
3803                         /*
3804                          * Finally, unshare any volumes shared via iSCSI.
3805                          */
3806                         zfs_handle_t **dslist = NULL;
3807                         size_t i, count = 0;
3808
3809                         get_all_datasets(ZFS_TYPE_VOLUME, &dslist, &count,
3810                             B_FALSE);
3811
3812                         if (count != 0) {
3813                                 qsort(dslist, count, sizeof (void *),
3814                                     dataset_cmp);
3815
3816                                 for (i = 0; i < count; i++) {
3817                                         if (zfs_unshare_iscsi(dslist[i]) != 0)
3818                                                 ret = 1;
3819                                         zfs_close(dslist[i]);
3820                                 }
3821
3822                                 free(dslist);
3823                         }
3824                 }
3825         } else {
3826                 if (argc != 1) {
3827                         if (argc == 0)
3828                                 (void) fprintf(stderr,
3829                                     gettext("missing filesystem argument\n"));
3830                         else
3831                                 (void) fprintf(stderr,
3832                                     gettext("too many arguments\n"));
3833                         usage(B_FALSE);
3834                 }
3835
3836                 /*
3837                  * We have an argument, but it may be a full path or a ZFS
3838                  * filesystem.  Pass full paths off to unmount_path() (shared by
3839                  * manual_unmount), otherwise open the filesystem and pass to
3840                  * zfs_unmount().
3841                  */
3842                 if (argv[0][0] == '/')
3843                         return (unshare_unmount_path(op, argv[0],
3844                             flags, B_FALSE));
3845
3846                 types = ZFS_TYPE_FILESYSTEM;
3847                 if (op == OP_SHARE)
3848                         types |= ZFS_TYPE_VOLUME;
3849
3850                 if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL)
3851                         return (1);
3852
3853                 if (zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
3854                         verify(zfs_prop_get(zhp, op == OP_SHARE ?
3855                             ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
3856                             nfsiscsi_mnt_prop, sizeof (nfsiscsi_mnt_prop), NULL,
3857                             NULL, 0, B_FALSE) == 0);
3858
3859                         switch (op) {
3860                         case OP_SHARE:
3861                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3862                                     nfsiscsi_mnt_prop,
3863                                     sizeof (nfsiscsi_mnt_prop),
3864                                     NULL, NULL, 0, B_FALSE) == 0);
3865                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3866                                     sharesmb, sizeof (sharesmb), NULL, NULL,
3867                                     0, B_FALSE) == 0);
3868
3869                                 if (strcmp(nfsiscsi_mnt_prop, "off") == 0 &&
3870                                     strcmp(sharesmb, "off") == 0) {
3871                                         (void) fprintf(stderr, gettext("cannot "
3872                                             "unshare '%s': legacy share\n"),
3873                                             zfs_get_name(zhp));
3874                                         (void) fprintf(stderr, gettext("use "
3875                                             "unshare(1M) to unshare this "
3876                                             "filesystem\n"));
3877                                         ret = 1;
3878                                 } else if (!zfs_is_shared(zhp)) {
3879                                         (void) fprintf(stderr, gettext("cannot "
3880                                             "unshare '%s': not currently "
3881                                             "shared\n"), zfs_get_name(zhp));
3882                                         ret = 1;
3883                                 } else if (zfs_unshareall(zhp) != 0) {
3884                                         ret = 1;
3885                                 }
3886                                 break;
3887
3888                         case OP_MOUNT:
3889                                 if (strcmp(nfsiscsi_mnt_prop, "legacy") == 0) {
3890                                         (void) fprintf(stderr, gettext("cannot "
3891                                             "unmount '%s': legacy "
3892                                             "mountpoint\n"), zfs_get_name(zhp));
3893                                         (void) fprintf(stderr, gettext("use "
3894                                             "umount(1M) to unmount this "
3895                                             "filesystem\n"));
3896                                         ret = 1;
3897                                 } else if (!zfs_is_mounted(zhp, NULL)) {
3898                                         (void) fprintf(stderr, gettext("cannot "
3899                                             "unmount '%s': not currently "
3900                                             "mounted\n"),
3901                                             zfs_get_name(zhp));
3902                                         ret = 1;
3903                                 } else if (zfs_unmountall(zhp, flags) != 0) {
3904                                         ret = 1;
3905                                 }
3906                                 break;
3907                         }
3908                 } else {
3909                         assert(op == OP_SHARE);
3910
3911                         verify(zfs_prop_get(zhp, ZFS_PROP_SHAREISCSI,
3912                             nfsiscsi_mnt_prop, sizeof (nfsiscsi_mnt_prop),
3913                             NULL, NULL, 0, B_FALSE) == 0);
3914
3915                         if (strcmp(nfsiscsi_mnt_prop, "off") == 0) {
3916                                 (void) fprintf(stderr, gettext("cannot unshare "
3917                                     "'%s': 'shareiscsi' property not set\n"),
3918                                     zfs_get_name(zhp));
3919                                 (void) fprintf(stderr, gettext("set "
3920                                     "'shareiscsi' property or use "
3921                                     "iscsitadm(1M) to share this volume\n"));
3922                                 ret = 1;
3923                         } else if (!zfs_is_shared_iscsi(zhp)) {
3924                                 (void) fprintf(stderr, gettext("cannot "
3925                                     "unshare '%s': not currently shared\n"),
3926                                     zfs_get_name(zhp));
3927                                 ret = 1;
3928                         } else if (zfs_unshare_iscsi(zhp) != 0) {
3929                                 ret = 1;
3930                         }
3931                 }
3932
3933                 zfs_close(zhp);
3934         }
3935
3936         return (ret);
3937 }
3938
3939 /*
3940  * zfs unmount -a
3941  * zfs unmount filesystem
3942  *
3943  * Unmount all filesystems, or a specific ZFS filesystem.
3944  */
3945 static int
3946 zfs_do_unmount(int argc, char **argv)
3947 {
3948         return (unshare_unmount(OP_MOUNT, argc, argv));
3949 }
3950
3951 /*
3952  * zfs unshare -a
3953  * zfs unshare filesystem
3954  *
3955  * Unshare all filesystems, or a specific ZFS filesystem.
3956  */
3957 static int
3958 zfs_do_unshare(int argc, char **argv)
3959 {
3960         return (unshare_unmount(OP_SHARE, argc, argv));
3961 }
3962
3963 /*
3964  * Attach/detach the given dataset to/from the given jail
3965  */
3966 /* ARGSUSED */
3967 static int
3968 do_jail(int argc, char **argv, int attach)
3969 {
3970         zfs_handle_t *zhp;
3971         int jailid, ret;
3972
3973         /* check number of arguments */
3974         if (argc < 3) {
3975                 (void) fprintf(stderr, gettext("missing argument(s)\n"));
3976                 usage(B_FALSE);
3977         }
3978         if (argc > 3) {
3979                 (void) fprintf(stderr, gettext("too many arguments\n"));
3980                 usage(B_FALSE);
3981         }
3982
3983         jailid = atoi(argv[1]);
3984         if (jailid == 0) {
3985                 (void) fprintf(stderr, gettext("invalid jailid\n"));
3986                 usage(B_FALSE);
3987         }
3988
3989         zhp = zfs_open(g_zfs, argv[2], ZFS_TYPE_FILESYSTEM);
3990         if (zhp == NULL)
3991                 return (1);
3992
3993         ret = (zfs_jail(zhp, jailid, attach) != 0);
3994
3995         zfs_close(zhp);
3996         return (ret);
3997 }
3998
3999 /*
4000  * zfs jail jailid filesystem
4001  *
4002  * Attach the given dataset to the given jail
4003  */
4004 /* ARGSUSED */
4005 static int
4006 zfs_do_jail(int argc, char **argv)
4007 {
4008
4009         return (do_jail(argc, argv, 1));
4010 }
4011
4012 /*
4013  * zfs unjail jailid filesystem
4014  *
4015  * Detach the given dataset from the given jail
4016  */
4017 /* ARGSUSED */
4018 static int
4019 zfs_do_unjail(int argc, char **argv)
4020 {
4021
4022         return (do_jail(argc, argv, 0));
4023 }
4024
4025 /*
4026  * Called when invoked as /etc/fs/zfs/mount.  Do the mount if the mountpoint is
4027  * 'legacy'.  Otherwise, complain that use should be using 'zfs mount'.
4028  */
4029 static int
4030 manual_mount(int argc, char **argv)
4031 {
4032         zfs_handle_t *zhp;
4033         char mountpoint[ZFS_MAXPROPLEN];
4034         char mntopts[MNT_LINE_MAX] = { '\0' };
4035         int ret;
4036         int c;
4037         int flags = 0;
4038         char *dataset, *path;
4039
4040         /* check options */
4041         while ((c = getopt(argc, argv, ":mo:O")) != -1) {
4042                 switch (c) {
4043                 case 'o':
4044                         (void) strlcpy(mntopts, optarg, sizeof (mntopts));
4045                         break;
4046                 case 'O':
4047 #if 0   /* FreeBSD: No support for MS_OVERLAY. */
4048                         flags |= MS_OVERLAY;
4049 #endif
4050                         break;
4051                 case 'm':
4052 #if 0   /* FreeBSD: No support for MS_NOMNTTAB. */
4053                         flags |= MS_NOMNTTAB;
4054 #endif
4055                         break;
4056                 case ':':
4057                         (void) fprintf(stderr, gettext("missing argument for "
4058                             "'%c' option\n"), optopt);
4059                         usage(B_FALSE);
4060                         break;
4061                 case '?':
4062                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4063                             optopt);
4064                         (void) fprintf(stderr, gettext("usage: mount [-o opts] "
4065                             "<path>\n"));
4066                         return (2);
4067                 }
4068         }
4069
4070         argc -= optind;
4071         argv += optind;
4072
4073         /* check that we only have two arguments */
4074         if (argc != 2) {
4075                 if (argc == 0)
4076                         (void) fprintf(stderr, gettext("missing dataset "
4077                             "argument\n"));
4078                 else if (argc == 1)
4079                         (void) fprintf(stderr,
4080                             gettext("missing mountpoint argument\n"));
4081                 else
4082                         (void) fprintf(stderr, gettext("too many arguments\n"));
4083                 (void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
4084                 return (2);
4085         }
4086
4087         dataset = argv[0];
4088         path = argv[1];
4089
4090         /* try to open the dataset */
4091         if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
4092                 return (1);
4093
4094         (void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
4095             sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
4096
4097         /* check for legacy mountpoint and complain appropriately */
4098         ret = 0;
4099         if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
4100                 if (zmount(dataset, path, flags, MNTTYPE_ZFS,
4101                     NULL, 0, mntopts, sizeof (mntopts)) != 0) {
4102                         (void) fprintf(stderr, gettext("mount failed: %s\n"),
4103                             strerror(errno));
4104                         ret = 1;
4105                 }
4106         } else {
4107                 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
4108                     "mounted using 'mount -F zfs'\n"), dataset);
4109                 (void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
4110                     "instead.\n"), path);
4111                 (void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
4112                     "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
4113                 (void) fprintf(stderr, gettext("See zfs(1M) for more "
4114                     "information.\n"));
4115                 ret = 1;
4116         }
4117
4118         return (ret);
4119 }
4120
4121 /*
4122  * Called when invoked as /etc/fs/zfs/umount.  Unlike a manual mount, we allow
4123  * unmounts of non-legacy filesystems, as this is the dominant administrative
4124  * interface.
4125  */
4126 static int
4127 manual_unmount(int argc, char **argv)
4128 {
4129         int flags = 0;
4130         int c;
4131
4132         /* check options */
4133         while ((c = getopt(argc, argv, "f")) != -1) {
4134                 switch (c) {
4135                 case 'f':
4136                         flags = MS_FORCE;
4137                         break;
4138                 case '?':
4139                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4140                             optopt);
4141                         (void) fprintf(stderr, gettext("usage: unmount [-f] "
4142                             "<path>\n"));
4143                         return (2);
4144                 }
4145         }
4146
4147         argc -= optind;
4148         argv += optind;
4149
4150         /* check arguments */
4151         if (argc != 1) {
4152                 if (argc == 0)
4153                         (void) fprintf(stderr, gettext("missing path "
4154                             "argument\n"));
4155                 else
4156                         (void) fprintf(stderr, gettext("too many arguments\n"));
4157                 (void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
4158                 return (2);
4159         }
4160
4161         return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
4162 }
4163
4164 static int
4165 volcheck(zpool_handle_t *zhp, void *data)
4166 {
4167         boolean_t isinit = *((boolean_t *)data);
4168
4169         if (isinit)
4170                 return (zpool_create_zvol_links(zhp));
4171         else
4172                 return (zpool_remove_zvol_links(zhp));
4173 }
4174
4175 /*
4176  * Iterate over all pools in the system and either create or destroy /dev/zvol
4177  * links, depending on the value of 'isinit'.
4178  */
4179 static int
4180 do_volcheck(boolean_t isinit)
4181 {
4182         return (zpool_iter(g_zfs, volcheck, &isinit) ? 1 : 0);
4183 }
4184
4185 static int
4186 find_command_idx(char *command, int *idx)
4187 {
4188         int i;
4189
4190         for (i = 0; i < NCOMMAND; i++) {
4191                 if (command_table[i].name == NULL)
4192                         continue;
4193
4194                 if (strcmp(command, command_table[i].name) == 0) {
4195                         *idx = i;
4196                         return (0);
4197                 }
4198         }
4199         return (1);
4200 }
4201
4202 int
4203 main(int argc, char **argv)
4204 {
4205         int ret;
4206         int i;
4207         char *progname;
4208         char *cmdname;
4209
4210         (void) setlocale(LC_ALL, "");
4211         (void) textdomain(TEXT_DOMAIN);
4212
4213         opterr = 0;
4214
4215         if ((g_zfs = libzfs_init()) == NULL) {
4216                 (void) fprintf(stderr, gettext("internal error: failed to "
4217                     "initialize ZFS library\n"));
4218                 return (1);
4219         }
4220
4221         zpool_set_history_str("zfs", argc, argv, history_str);
4222         verify(zpool_stage_history(g_zfs, history_str) == 0);
4223
4224         libzfs_print_on_error(g_zfs, B_TRUE);
4225
4226         if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
4227                 (void) fprintf(stderr, gettext("internal error: unable to "
4228                     "open %s\n"), MNTTAB);
4229                 return (1);
4230         }
4231
4232         /*
4233          * This command also doubles as the /etc/fs mount and unmount program.
4234          * Determine if we should take this behavior based on argv[0].
4235          */
4236         progname = basename(argv[0]);
4237         if (strcmp(progname, "mount") == 0) {
4238                 ret = manual_mount(argc, argv);
4239         } else if (strcmp(progname, "umount") == 0) {
4240                 ret = manual_unmount(argc, argv);
4241         } else {
4242                 /*
4243                  * Make sure the user has specified some command.
4244                  */
4245                 if (argc < 2) {
4246                         (void) fprintf(stderr, gettext("missing command\n"));
4247                         usage(B_FALSE);
4248                 }
4249
4250                 cmdname = argv[1];
4251
4252                 /*
4253                  * The 'umount' command is an alias for 'unmount'
4254                  */
4255                 if (strcmp(cmdname, "umount") == 0)
4256                         cmdname = "unmount";
4257
4258                 /*
4259                  * The 'recv' command is an alias for 'receive'
4260                  */
4261                 if (strcmp(cmdname, "recv") == 0)
4262                         cmdname = "receive";
4263
4264                 /*
4265                  * Special case '-?'
4266                  */
4267                 if (strcmp(cmdname, "-?") == 0)
4268                         usage(B_TRUE);
4269
4270                 /*
4271                  * 'volinit' and 'volfini' do not appear in the usage message,
4272                  * so we have to special case them here.
4273                  */
4274                 if (strcmp(cmdname, "volinit") == 0)
4275                         return (do_volcheck(B_TRUE));
4276                 else if (strcmp(cmdname, "volfini") == 0)
4277                         return (do_volcheck(B_FALSE));
4278
4279                 /*
4280                  * Run the appropriate command.
4281                  */
4282                 if (find_command_idx(cmdname, &i) == 0) {
4283                         current_command = &command_table[i];
4284                         ret = command_table[i].func(argc - 1, argv + 1);
4285                 } else if (strchr(cmdname, '=') != NULL) {
4286                         verify(find_command_idx("set", &i) == 0);
4287                         current_command = &command_table[i];
4288                         ret = command_table[i].func(argc, argv);
4289                 } else {
4290                         (void) fprintf(stderr, gettext("unrecognized "
4291                             "command '%s'\n"), cmdname);
4292                         usage(B_FALSE);
4293                 }
4294         }
4295
4296         (void) fclose(mnttab_file);
4297
4298         libzfs_fini(g_zfs);
4299
4300         /*
4301          * The 'ZFS_ABORT' environment variable causes us to dump core on exit
4302          * for the purposes of running ::findleaks.
4303          */
4304         if (getenv("ZFS_ABORT") != NULL) {
4305                 (void) printf("dumping core by request\n");
4306                 abort();
4307         }
4308
4309         return (ret);
4310 }