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