]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - cddl/contrib/opensolaris/cmd/zfs/zfs_main.c
MFC r256999 (smh):
[FreeBSD/stable/9.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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright 2012 Nexenta Systems, Inc. All rights reserved.
25  * Copyright (c) 2012 by Delphix. All rights reserved.
26  * Copyright 2012 Milan Jurik. All rights reserved.
27  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
28  * Copyright (c) 2011-2012 Pawel Jakub Dawidek <pawel@dawidek.net>.
29  * All rights reserved.
30  * Copyright (c) 2012 Martin Matuska <mm@FreeBSD.org>. All rights reserved.
31  * Copyright (c) 2013 Steven Hartland.  All rights reserved.
32  */
33
34 #include <assert.h>
35 #include <ctype.h>
36 #include <errno.h>
37 #include <libgen.h>
38 #include <libintl.h>
39 #include <libuutil.h>
40 #include <libnvpair.h>
41 #include <locale.h>
42 #include <stddef.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <strings.h>
46 #include <unistd.h>
47 #include <fcntl.h>
48 #include <zone.h>
49 #include <grp.h>
50 #include <pwd.h>
51 #include <signal.h>
52 #include <sys/list.h>
53 #include <sys/mntent.h>
54 #include <sys/mnttab.h>
55 #include <sys/mount.h>
56 #include <sys/stat.h>
57 #include <sys/fs/zfs.h>
58 #include <sys/types.h>
59 #include <time.h>
60
61 #include <libzfs.h>
62 #include <libzfs_core.h>
63 #include <zfs_prop.h>
64 #include <zfs_deleg.h>
65 #include <libuutil.h>
66 #ifdef sun
67 #include <aclutils.h>
68 #include <directory.h>
69 #endif
70
71 #include "zfs_iter.h"
72 #include "zfs_util.h"
73 #include "zfs_comutil.h"
74
75 libzfs_handle_t *g_zfs;
76
77 static FILE *mnttab_file;
78 static char history_str[HIS_MAX_RECORD_LEN];
79 static boolean_t log_history = B_TRUE;
80
81 static int zfs_do_clone(int argc, char **argv);
82 static int zfs_do_create(int argc, char **argv);
83 static int zfs_do_destroy(int argc, char **argv);
84 static int zfs_do_get(int argc, char **argv);
85 static int zfs_do_inherit(int argc, char **argv);
86 static int zfs_do_list(int argc, char **argv);
87 static int zfs_do_mount(int argc, char **argv);
88 static int zfs_do_rename(int argc, char **argv);
89 static int zfs_do_rollback(int argc, char **argv);
90 static int zfs_do_set(int argc, char **argv);
91 static int zfs_do_upgrade(int argc, char **argv);
92 static int zfs_do_snapshot(int argc, char **argv);
93 static int zfs_do_unmount(int argc, char **argv);
94 static int zfs_do_share(int argc, char **argv);
95 static int zfs_do_unshare(int argc, char **argv);
96 static int zfs_do_send(int argc, char **argv);
97 static int zfs_do_receive(int argc, char **argv);
98 static int zfs_do_promote(int argc, char **argv);
99 static int zfs_do_userspace(int argc, char **argv);
100 static int zfs_do_allow(int argc, char **argv);
101 static int zfs_do_unallow(int argc, char **argv);
102 static int zfs_do_hold(int argc, char **argv);
103 static int zfs_do_holds(int argc, char **argv);
104 static int zfs_do_release(int argc, char **argv);
105 static int zfs_do_diff(int argc, char **argv);
106 static int zfs_do_jail(int argc, char **argv);
107 static int zfs_do_unjail(int argc, char **argv);
108
109 /*
110  * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
111  */
112
113 #ifdef DEBUG
114 const char *
115 _umem_debug_init(void)
116 {
117         return ("default,verbose"); /* $UMEM_DEBUG setting */
118 }
119
120 const char *
121 _umem_logging_init(void)
122 {
123         return ("fail,contents"); /* $UMEM_LOGGING setting */
124 }
125 #endif
126
127 typedef enum {
128         HELP_CLONE,
129         HELP_CREATE,
130         HELP_DESTROY,
131         HELP_GET,
132         HELP_INHERIT,
133         HELP_UPGRADE,
134         HELP_JAIL,
135         HELP_UNJAIL,
136         HELP_LIST,
137         HELP_MOUNT,
138         HELP_PROMOTE,
139         HELP_RECEIVE,
140         HELP_RENAME,
141         HELP_ROLLBACK,
142         HELP_SEND,
143         HELP_SET,
144         HELP_SHARE,
145         HELP_SNAPSHOT,
146         HELP_UNMOUNT,
147         HELP_UNSHARE,
148         HELP_ALLOW,
149         HELP_UNALLOW,
150         HELP_USERSPACE,
151         HELP_GROUPSPACE,
152         HELP_HOLD,
153         HELP_HOLDS,
154         HELP_RELEASE,
155         HELP_DIFF,
156 } zfs_help_t;
157
158 typedef struct zfs_command {
159         const char      *name;
160         int             (*func)(int argc, char **argv);
161         zfs_help_t      usage;
162 } zfs_command_t;
163
164 /*
165  * Master command table.  Each ZFS command has a name, associated function, and
166  * usage message.  The usage messages need to be internationalized, so we have
167  * to have a function to return the usage message based on a command index.
168  *
169  * These commands are organized according to how they are displayed in the usage
170  * message.  An empty command (one with a NULL name) indicates an empty line in
171  * the generic usage message.
172  */
173 static zfs_command_t command_table[] = {
174         { "create",     zfs_do_create,          HELP_CREATE             },
175         { "destroy",    zfs_do_destroy,         HELP_DESTROY            },
176         { NULL },
177         { "snapshot",   zfs_do_snapshot,        HELP_SNAPSHOT           },
178         { "rollback",   zfs_do_rollback,        HELP_ROLLBACK           },
179         { "clone",      zfs_do_clone,           HELP_CLONE              },
180         { "promote",    zfs_do_promote,         HELP_PROMOTE            },
181         { "rename",     zfs_do_rename,          HELP_RENAME             },
182         { NULL },
183         { "list",       zfs_do_list,            HELP_LIST               },
184         { NULL },
185         { "set",        zfs_do_set,             HELP_SET                },
186         { "get",        zfs_do_get,             HELP_GET                },
187         { "inherit",    zfs_do_inherit,         HELP_INHERIT            },
188         { "upgrade",    zfs_do_upgrade,         HELP_UPGRADE            },
189         { "userspace",  zfs_do_userspace,       HELP_USERSPACE          },
190         { "groupspace", zfs_do_userspace,       HELP_GROUPSPACE         },
191         { NULL },
192         { "mount",      zfs_do_mount,           HELP_MOUNT              },
193         { "unmount",    zfs_do_unmount,         HELP_UNMOUNT            },
194         { "share",      zfs_do_share,           HELP_SHARE              },
195         { "unshare",    zfs_do_unshare,         HELP_UNSHARE            },
196         { NULL },
197         { "send",       zfs_do_send,            HELP_SEND               },
198         { "receive",    zfs_do_receive,         HELP_RECEIVE            },
199         { NULL },
200         { "allow",      zfs_do_allow,           HELP_ALLOW              },
201         { NULL },
202         { "unallow",    zfs_do_unallow,         HELP_UNALLOW            },
203         { NULL },
204         { "hold",       zfs_do_hold,            HELP_HOLD               },
205         { "holds",      zfs_do_holds,           HELP_HOLDS              },
206         { "release",    zfs_do_release,         HELP_RELEASE            },
207         { "diff",       zfs_do_diff,            HELP_DIFF               },
208         { NULL },
209         { "jail",       zfs_do_jail,            HELP_JAIL               },
210         { "unjail",     zfs_do_unjail,          HELP_UNJAIL             },
211 };
212
213 #define NCOMMAND        (sizeof (command_table) / sizeof (command_table[0]))
214
215 zfs_command_t *current_command;
216
217 static const char *
218 get_usage(zfs_help_t idx)
219 {
220         switch (idx) {
221         case HELP_CLONE:
222                 return (gettext("\tclone [-p] [-o property=value] ... "
223                     "<snapshot> <filesystem|volume>\n"));
224         case HELP_CREATE:
225                 return (gettext("\tcreate [-p] [-o property=value] ... "
226                     "<filesystem>\n"
227                     "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
228                     "-V <size> <volume>\n"));
229         case HELP_DESTROY:
230                 return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
231                     "\tdestroy [-dnpRrv] "
232                     "<snapshot>[%<snapname>][,...]\n"));
233         case HELP_GET:
234                 return (gettext("\tget [-rHp] [-d max] "
235                     "[-o \"all\" | field[,...]] [-t type[,...]] "
236                     "[-s source[,...]]\n"
237                     "\t    <\"all\" | property[,...]> "
238                     "[filesystem|volume|snapshot] ...\n"));
239         case HELP_INHERIT:
240                 return (gettext("\tinherit [-rS] <property> "
241                     "<filesystem|volume|snapshot> ...\n"));
242         case HELP_UPGRADE:
243                 return (gettext("\tupgrade [-v]\n"
244                     "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
245         case HELP_JAIL:
246                 return (gettext("\tjail <jailid|jailname> <filesystem>\n"));
247         case HELP_UNJAIL:
248                 return (gettext("\tunjail <jailid|jailname> <filesystem>\n"));
249         case HELP_LIST:
250                 return (gettext("\tlist [-rH][-d max] "
251                     "[-o property[,...]] [-t type[,...]] [-s property] ...\n"
252                     "\t    [-S property] ... "
253                     "[filesystem|volume|snapshot] ...\n"));
254         case HELP_MOUNT:
255                 return (gettext("\tmount\n"
256                     "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
257         case HELP_PROMOTE:
258                 return (gettext("\tpromote <clone-filesystem>\n"));
259         case HELP_RECEIVE:
260                 return (gettext("\treceive|recv [-vnFu] <filesystem|volume|"
261                 "snapshot>\n"
262                 "\treceive|recv [-vnFu] [-d | -e] <filesystem>\n"));
263         case HELP_RENAME:
264                 return (gettext("\trename [-f] <filesystem|volume|snapshot> "
265                     "<filesystem|volume|snapshot>\n"
266                     "\trename [-f] -p <filesystem|volume> "
267                     "<filesystem|volume>\n"
268                     "\trename -r <snapshot> <snapshot>\n"
269                     "\trename -u [-p] <filesystem> <filesystem>"));
270         case HELP_ROLLBACK:
271                 return (gettext("\trollback [-rRf] <snapshot>\n"));
272         case HELP_SEND:
273                 return (gettext("\tsend [-DnPpRv] "
274                     "[-i snapshot | -I snapshot] <snapshot>\n"));
275         case HELP_SET:
276                 return (gettext("\tset <property=value> "
277                     "<filesystem|volume|snapshot> ...\n"));
278         case HELP_SHARE:
279                 return (gettext("\tshare <-a | filesystem>\n"));
280         case HELP_SNAPSHOT:
281                 return (gettext("\tsnapshot|snap [-r] [-o property=value] ... "
282                     "<filesystem@snapname|volume@snapname> ...\n"));
283         case HELP_UNMOUNT:
284                 return (gettext("\tunmount|umount [-f] "
285                     "<-a | filesystem|mountpoint>\n"));
286         case HELP_UNSHARE:
287                 return (gettext("\tunshare "
288                     "<-a | filesystem|mountpoint>\n"));
289         case HELP_ALLOW:
290                 return (gettext("\tallow <filesystem|volume>\n"
291                     "\tallow [-ldug] "
292                     "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
293                     "\t    <filesystem|volume>\n"
294                     "\tallow [-ld] -e <perm|@setname>[,...] "
295                     "<filesystem|volume>\n"
296                     "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
297                     "\tallow -s @setname <perm|@setname>[,...] "
298                     "<filesystem|volume>\n"));
299         case HELP_UNALLOW:
300                 return (gettext("\tunallow [-rldug] "
301                     "<\"everyone\"|user|group>[,...]\n"
302                     "\t    [<perm|@setname>[,...]] <filesystem|volume>\n"
303                     "\tunallow [-rld] -e [<perm|@setname>[,...]] "
304                     "<filesystem|volume>\n"
305                     "\tunallow [-r] -c [<perm|@setname>[,...]] "
306                     "<filesystem|volume>\n"
307                     "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
308                     "<filesystem|volume>\n"));
309         case HELP_USERSPACE:
310                 return (gettext("\tuserspace [-Hinp] [-o field[,...]] "
311                     "[-s field] ...\n\t[-S field] ... "
312                     "[-t type[,...]] <filesystem|snapshot>\n"));
313         case HELP_GROUPSPACE:
314                 return (gettext("\tgroupspace [-Hinp] [-o field[,...]] "
315                     "[-s field] ...\n\t[-S field] ... "
316                     "[-t type[,...]] <filesystem|snapshot>\n"));
317         case HELP_HOLD:
318                 return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
319         case HELP_HOLDS:
320                 return (gettext("\tholds [-r] <snapshot> ...\n"));
321         case HELP_RELEASE:
322                 return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
323         case HELP_DIFF:
324                 return (gettext("\tdiff [-FHt] <snapshot> "
325                     "[snapshot|filesystem]\n"));
326         }
327
328         abort();
329         /* NOTREACHED */
330 }
331
332 void
333 nomem(void)
334 {
335         (void) fprintf(stderr, gettext("internal error: out of memory\n"));
336         exit(1);
337 }
338
339 /*
340  * Utility function to guarantee malloc() success.
341  */
342
343 void *
344 safe_malloc(size_t size)
345 {
346         void *data;
347
348         if ((data = calloc(1, size)) == NULL)
349                 nomem();
350
351         return (data);
352 }
353
354 static char *
355 safe_strdup(char *str)
356 {
357         char *dupstr = strdup(str);
358
359         if (dupstr == NULL)
360                 nomem();
361
362         return (dupstr);
363 }
364
365 /*
366  * Callback routine that will print out information for each of
367  * the properties.
368  */
369 static int
370 usage_prop_cb(int prop, void *cb)
371 {
372         FILE *fp = cb;
373
374         (void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
375
376         if (zfs_prop_readonly(prop))
377                 (void) fprintf(fp, " NO    ");
378         else
379                 (void) fprintf(fp, "YES    ");
380
381         if (zfs_prop_inheritable(prop))
382                 (void) fprintf(fp, "  YES   ");
383         else
384                 (void) fprintf(fp, "   NO   ");
385
386         if (zfs_prop_values(prop) == NULL)
387                 (void) fprintf(fp, "-\n");
388         else
389                 (void) fprintf(fp, "%s\n", zfs_prop_values(prop));
390
391         return (ZPROP_CONT);
392 }
393
394 /*
395  * Display usage message.  If we're inside a command, display only the usage for
396  * that command.  Otherwise, iterate over the entire command table and display
397  * a complete usage message.
398  */
399 static void
400 usage(boolean_t requested)
401 {
402         int i;
403         boolean_t show_properties = B_FALSE;
404         FILE *fp = requested ? stdout : stderr;
405
406         if (current_command == NULL) {
407
408                 (void) fprintf(fp, gettext("usage: zfs command args ...\n"));
409                 (void) fprintf(fp,
410                     gettext("where 'command' is one of the following:\n\n"));
411
412                 for (i = 0; i < NCOMMAND; i++) {
413                         if (command_table[i].name == NULL)
414                                 (void) fprintf(fp, "\n");
415                         else
416                                 (void) fprintf(fp, "%s",
417                                     get_usage(command_table[i].usage));
418                 }
419
420                 (void) fprintf(fp, gettext("\nEach dataset is of the form: "
421                     "pool/[dataset/]*dataset[@name]\n"));
422         } else {
423                 (void) fprintf(fp, gettext("usage:\n"));
424                 (void) fprintf(fp, "%s", get_usage(current_command->usage));
425         }
426
427         if (current_command != NULL &&
428             (strcmp(current_command->name, "set") == 0 ||
429             strcmp(current_command->name, "get") == 0 ||
430             strcmp(current_command->name, "inherit") == 0 ||
431             strcmp(current_command->name, "list") == 0))
432                 show_properties = B_TRUE;
433
434         if (show_properties) {
435                 (void) fprintf(fp,
436                     gettext("\nThe following properties are supported:\n"));
437
438                 (void) fprintf(fp, "\n\t%-14s %s  %s   %s\n\n",
439                     "PROPERTY", "EDIT", "INHERIT", "VALUES");
440
441                 /* Iterate over all properties */
442                 (void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
443                     ZFS_TYPE_DATASET);
444
445                 (void) fprintf(fp, "\t%-15s ", "userused@...");
446                 (void) fprintf(fp, " NO       NO   <size>\n");
447                 (void) fprintf(fp, "\t%-15s ", "groupused@...");
448                 (void) fprintf(fp, " NO       NO   <size>\n");
449                 (void) fprintf(fp, "\t%-15s ", "userquota@...");
450                 (void) fprintf(fp, "YES       NO   <size> | none\n");
451                 (void) fprintf(fp, "\t%-15s ", "groupquota@...");
452                 (void) fprintf(fp, "YES       NO   <size> | none\n");
453                 (void) fprintf(fp, "\t%-15s ", "written@<snap>");
454                 (void) fprintf(fp, " NO       NO   <size>\n");
455
456                 (void) fprintf(fp, gettext("\nSizes are specified in bytes "
457                     "with standard units such as K, M, G, etc.\n"));
458                 (void) fprintf(fp, gettext("\nUser-defined properties can "
459                     "be specified by using a name containing a colon (:).\n"));
460                 (void) fprintf(fp, gettext("\nThe {user|group}{used|quota}@ "
461                     "properties must be appended with\n"
462                     "a user or group specifier of one of these forms:\n"
463                     "    POSIX name      (eg: \"matt\")\n"
464                     "    POSIX id        (eg: \"126829\")\n"
465                     "    SMB name@domain (eg: \"matt@sun\")\n"
466                     "    SMB SID         (eg: \"S-1-234-567-89\")\n"));
467         } else {
468                 (void) fprintf(fp,
469                     gettext("\nFor the property list, run: %s\n"),
470                     "zfs set|get");
471                 (void) fprintf(fp,
472                     gettext("\nFor the delegated permission list, run: %s\n"),
473                     "zfs allow|unallow");
474         }
475
476         /*
477          * See comments at end of main().
478          */
479         if (getenv("ZFS_ABORT") != NULL) {
480                 (void) printf("dumping core by request\n");
481                 abort();
482         }
483
484         exit(requested ? 0 : 2);
485 }
486
487 static int
488 parseprop(nvlist_t *props)
489 {
490         char *propname = optarg;
491         char *propval, *strval;
492
493         if ((propval = strchr(propname, '=')) == NULL) {
494                 (void) fprintf(stderr, gettext("missing "
495                     "'=' for -o option\n"));
496                 return (-1);
497         }
498         *propval = '\0';
499         propval++;
500         if (nvlist_lookup_string(props, propname, &strval) == 0) {
501                 (void) fprintf(stderr, gettext("property '%s' "
502                     "specified multiple times\n"), propname);
503                 return (-1);
504         }
505         if (nvlist_add_string(props, propname, propval) != 0)
506                 nomem();
507         return (0);
508 }
509
510 static int
511 parse_depth(char *opt, int *flags)
512 {
513         char *tmp;
514         int depth;
515
516         depth = (int)strtol(opt, &tmp, 0);
517         if (*tmp) {
518                 (void) fprintf(stderr,
519                     gettext("%s is not an integer\n"), optarg);
520                 usage(B_FALSE);
521         }
522         if (depth < 0) {
523                 (void) fprintf(stderr,
524                     gettext("Depth can not be negative.\n"));
525                 usage(B_FALSE);
526         }
527         *flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
528         return (depth);
529 }
530
531 #define PROGRESS_DELAY 2                /* seconds */
532
533 static char *pt_reverse = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
534 static time_t pt_begin;
535 static char *pt_header = NULL;
536 static boolean_t pt_shown;
537
538 static void
539 start_progress_timer(void)
540 {
541         pt_begin = time(NULL) + PROGRESS_DELAY;
542         pt_shown = B_FALSE;
543 }
544
545 static void
546 set_progress_header(char *header)
547 {
548         assert(pt_header == NULL);
549         pt_header = safe_strdup(header);
550         if (pt_shown) {
551                 (void) printf("%s: ", header);
552                 (void) fflush(stdout);
553         }
554 }
555
556 static void
557 update_progress(char *update)
558 {
559         if (!pt_shown && time(NULL) > pt_begin) {
560                 int len = strlen(update);
561
562                 (void) printf("%s: %s%*.*s", pt_header, update, len, len,
563                     pt_reverse);
564                 (void) fflush(stdout);
565                 pt_shown = B_TRUE;
566         } else if (pt_shown) {
567                 int len = strlen(update);
568
569                 (void) printf("%s%*.*s", update, len, len, pt_reverse);
570                 (void) fflush(stdout);
571         }
572 }
573
574 static void
575 finish_progress(char *done)
576 {
577         if (pt_shown) {
578                 (void) printf("%s\n", done);
579                 (void) fflush(stdout);
580         }
581         free(pt_header);
582         pt_header = NULL;
583 }
584 /*
585  * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
586  *
587  * Given an existing dataset, create a writable copy whose initial contents
588  * are the same as the source.  The newly created dataset maintains a
589  * dependency on the original; the original cannot be destroyed so long as
590  * the clone exists.
591  *
592  * The '-p' flag creates all the non-existing ancestors of the target first.
593  */
594 static int
595 zfs_do_clone(int argc, char **argv)
596 {
597         zfs_handle_t *zhp = NULL;
598         boolean_t parents = B_FALSE;
599         nvlist_t *props;
600         int ret = 0;
601         int c;
602
603         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
604                 nomem();
605
606         /* check options */
607         while ((c = getopt(argc, argv, "o:p")) != -1) {
608                 switch (c) {
609                 case 'o':
610                         if (parseprop(props))
611                                 return (1);
612                         break;
613                 case 'p':
614                         parents = B_TRUE;
615                         break;
616                 case '?':
617                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
618                             optopt);
619                         goto usage;
620                 }
621         }
622
623         argc -= optind;
624         argv += optind;
625
626         /* check number of arguments */
627         if (argc < 1) {
628                 (void) fprintf(stderr, gettext("missing source dataset "
629                     "argument\n"));
630                 goto usage;
631         }
632         if (argc < 2) {
633                 (void) fprintf(stderr, gettext("missing target dataset "
634                     "argument\n"));
635                 goto usage;
636         }
637         if (argc > 2) {
638                 (void) fprintf(stderr, gettext("too many arguments\n"));
639                 goto usage;
640         }
641
642         /* open the source dataset */
643         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
644                 return (1);
645
646         if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
647             ZFS_TYPE_VOLUME)) {
648                 /*
649                  * Now create the ancestors of the target dataset.  If the
650                  * target already exists and '-p' option was used we should not
651                  * complain.
652                  */
653                 if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
654                     ZFS_TYPE_VOLUME))
655                         return (0);
656                 if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
657                         return (1);
658         }
659
660         /* pass to libzfs */
661         ret = zfs_clone(zhp, argv[1], props);
662
663         /* create the mountpoint if necessary */
664         if (ret == 0) {
665                 zfs_handle_t *clone;
666
667                 clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
668                 if (clone != NULL) {
669                         if (zfs_get_type(clone) != ZFS_TYPE_VOLUME)
670                                 if ((ret = zfs_mount(clone, NULL, 0)) == 0)
671                                         ret = zfs_share(clone);
672                         zfs_close(clone);
673                 }
674         }
675
676         zfs_close(zhp);
677         nvlist_free(props);
678
679         return (!!ret);
680
681 usage:
682         if (zhp)
683                 zfs_close(zhp);
684         nvlist_free(props);
685         usage(B_FALSE);
686         return (-1);
687 }
688
689 /*
690  * zfs create [-p] [-o prop=value] ... fs
691  * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
692  *
693  * Create a new dataset.  This command can be used to create filesystems
694  * and volumes.  Snapshot creation is handled by 'zfs snapshot'.
695  * For volumes, the user must specify a size to be used.
696  *
697  * The '-s' flag applies only to volumes, and indicates that we should not try
698  * to set the reservation for this volume.  By default we set a reservation
699  * equal to the size for any volume.  For pools with SPA_VERSION >=
700  * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
701  *
702  * The '-p' flag creates all the non-existing ancestors of the target first.
703  */
704 static int
705 zfs_do_create(int argc, char **argv)
706 {
707         zfs_type_t type = ZFS_TYPE_FILESYSTEM;
708         zfs_handle_t *zhp = NULL;
709         uint64_t volsize;
710         int c;
711         boolean_t noreserve = B_FALSE;
712         boolean_t bflag = B_FALSE;
713         boolean_t parents = B_FALSE;
714         int ret = 1;
715         nvlist_t *props;
716         uint64_t intval;
717         int canmount = ZFS_CANMOUNT_OFF;
718
719         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
720                 nomem();
721
722         /* check options */
723         while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
724                 switch (c) {
725                 case 'V':
726                         type = ZFS_TYPE_VOLUME;
727                         if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
728                                 (void) fprintf(stderr, gettext("bad volume "
729                                     "size '%s': %s\n"), optarg,
730                                     libzfs_error_description(g_zfs));
731                                 goto error;
732                         }
733
734                         if (nvlist_add_uint64(props,
735                             zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
736                                 nomem();
737                         volsize = intval;
738                         break;
739                 case 'p':
740                         parents = B_TRUE;
741                         break;
742                 case 'b':
743                         bflag = B_TRUE;
744                         if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
745                                 (void) fprintf(stderr, gettext("bad volume "
746                                     "block size '%s': %s\n"), optarg,
747                                     libzfs_error_description(g_zfs));
748                                 goto error;
749                         }
750
751                         if (nvlist_add_uint64(props,
752                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
753                             intval) != 0)
754                                 nomem();
755                         break;
756                 case 'o':
757                         if (parseprop(props))
758                                 goto error;
759                         break;
760                 case 's':
761                         noreserve = B_TRUE;
762                         break;
763                 case ':':
764                         (void) fprintf(stderr, gettext("missing size "
765                             "argument\n"));
766                         goto badusage;
767                 case '?':
768                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
769                             optopt);
770                         goto badusage;
771                 }
772         }
773
774         if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
775                 (void) fprintf(stderr, gettext("'-s' and '-b' can only be "
776                     "used when creating a volume\n"));
777                 goto badusage;
778         }
779
780         argc -= optind;
781         argv += optind;
782
783         /* check number of arguments */
784         if (argc == 0) {
785                 (void) fprintf(stderr, gettext("missing %s argument\n"),
786                     zfs_type_to_name(type));
787                 goto badusage;
788         }
789         if (argc > 1) {
790                 (void) fprintf(stderr, gettext("too many arguments\n"));
791                 goto badusage;
792         }
793
794         if (type == ZFS_TYPE_VOLUME && !noreserve) {
795                 zpool_handle_t *zpool_handle;
796                 uint64_t spa_version;
797                 char *p;
798                 zfs_prop_t resv_prop;
799                 char *strval;
800
801                 if (p = strchr(argv[0], '/'))
802                         *p = '\0';
803                 zpool_handle = zpool_open(g_zfs, argv[0]);
804                 if (p != NULL)
805                         *p = '/';
806                 if (zpool_handle == NULL)
807                         goto error;
808                 spa_version = zpool_get_prop_int(zpool_handle,
809                     ZPOOL_PROP_VERSION, NULL);
810                 zpool_close(zpool_handle);
811                 if (spa_version >= SPA_VERSION_REFRESERVATION)
812                         resv_prop = ZFS_PROP_REFRESERVATION;
813                 else
814                         resv_prop = ZFS_PROP_RESERVATION;
815                 volsize = zvol_volsize_to_reservation(volsize, props);
816
817                 if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
818                     &strval) != 0) {
819                         if (nvlist_add_uint64(props,
820                             zfs_prop_to_name(resv_prop), volsize) != 0) {
821                                 nvlist_free(props);
822                                 nomem();
823                         }
824                 }
825         }
826
827         if (parents && zfs_name_valid(argv[0], type)) {
828                 /*
829                  * Now create the ancestors of target dataset.  If the target
830                  * already exists and '-p' option was used we should not
831                  * complain.
832                  */
833                 if (zfs_dataset_exists(g_zfs, argv[0], type)) {
834                         ret = 0;
835                         goto error;
836                 }
837                 if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
838                         goto error;
839         }
840
841         /* pass to libzfs */
842         if (zfs_create(g_zfs, argv[0], type, props) != 0)
843                 goto error;
844
845         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
846                 goto error;
847
848         ret = 0;
849         /*
850          * if the user doesn't want the dataset automatically mounted,
851          * then skip the mount/share step
852          */
853         if (zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, type))
854                 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
855
856         /*
857          * Mount and/or share the new filesystem as appropriate.  We provide a
858          * verbose error message to let the user know that their filesystem was
859          * in fact created, even if we failed to mount or share it.
860          */
861         if (canmount == ZFS_CANMOUNT_ON) {
862                 if (zfs_mount(zhp, NULL, 0) != 0) {
863                         (void) fprintf(stderr, gettext("filesystem "
864                             "successfully created, but not mounted\n"));
865                         ret = 1;
866                 } else if (zfs_share(zhp) != 0) {
867                         (void) fprintf(stderr, gettext("filesystem "
868                             "successfully created, but not shared\n"));
869                         ret = 1;
870                 }
871         }
872
873 error:
874         if (zhp)
875                 zfs_close(zhp);
876         nvlist_free(props);
877         return (ret);
878 badusage:
879         nvlist_free(props);
880         usage(B_FALSE);
881         return (2);
882 }
883
884 /*
885  * zfs destroy [-rRf] <fs, vol>
886  * zfs destroy [-rRd] <snap>
887  *
888  *      -r      Recursively destroy all children
889  *      -R      Recursively destroy all dependents, including clones
890  *      -f      Force unmounting of any dependents
891  *      -d      If we can't destroy now, mark for deferred destruction
892  *
893  * Destroys the given dataset.  By default, it will unmount any filesystems,
894  * and refuse to destroy a dataset that has any dependents.  A dependent can
895  * either be a child, or a clone of a child.
896  */
897 typedef struct destroy_cbdata {
898         boolean_t       cb_first;
899         boolean_t       cb_force;
900         boolean_t       cb_recurse;
901         boolean_t       cb_error;
902         boolean_t       cb_doclones;
903         zfs_handle_t    *cb_target;
904         boolean_t       cb_defer_destroy;
905         boolean_t       cb_verbose;
906         boolean_t       cb_parsable;
907         boolean_t       cb_dryrun;
908         nvlist_t        *cb_nvl;
909         nvlist_t        *cb_batchedsnaps;
910
911         /* first snap in contiguous run */
912         char            *cb_firstsnap;
913         /* previous snap in contiguous run */
914         char            *cb_prevsnap;
915         int64_t         cb_snapused;
916         char            *cb_snapspec;
917 } destroy_cbdata_t;
918
919 /*
920  * Check for any dependents based on the '-r' or '-R' flags.
921  */
922 static int
923 destroy_check_dependent(zfs_handle_t *zhp, void *data)
924 {
925         destroy_cbdata_t *cbp = data;
926         const char *tname = zfs_get_name(cbp->cb_target);
927         const char *name = zfs_get_name(zhp);
928
929         if (strncmp(tname, name, strlen(tname)) == 0 &&
930             (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
931                 /*
932                  * This is a direct descendant, not a clone somewhere else in
933                  * the hierarchy.
934                  */
935                 if (cbp->cb_recurse)
936                         goto out;
937
938                 if (cbp->cb_first) {
939                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
940                             "%s has children\n"),
941                             zfs_get_name(cbp->cb_target),
942                             zfs_type_to_name(zfs_get_type(cbp->cb_target)));
943                         (void) fprintf(stderr, gettext("use '-r' to destroy "
944                             "the following datasets:\n"));
945                         cbp->cb_first = B_FALSE;
946                         cbp->cb_error = B_TRUE;
947                 }
948
949                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
950         } else {
951                 /*
952                  * This is a clone.  We only want to report this if the '-r'
953                  * wasn't specified, or the target is a snapshot.
954                  */
955                 if (!cbp->cb_recurse &&
956                     zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
957                         goto out;
958
959                 if (cbp->cb_first) {
960                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
961                             "%s has dependent clones\n"),
962                             zfs_get_name(cbp->cb_target),
963                             zfs_type_to_name(zfs_get_type(cbp->cb_target)));
964                         (void) fprintf(stderr, gettext("use '-R' to destroy "
965                             "the following datasets:\n"));
966                         cbp->cb_first = B_FALSE;
967                         cbp->cb_error = B_TRUE;
968                         cbp->cb_dryrun = B_TRUE;
969                 }
970
971                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
972         }
973
974 out:
975         zfs_close(zhp);
976         return (0);
977 }
978
979 static int
980 destroy_callback(zfs_handle_t *zhp, void *data)
981 {
982         destroy_cbdata_t *cb = data;
983         const char *name = zfs_get_name(zhp);
984
985         if (cb->cb_verbose) {
986                 if (cb->cb_parsable) {
987                         (void) printf("destroy\t%s\n", name);
988                 } else if (cb->cb_dryrun) {
989                         (void) printf(gettext("would destroy %s\n"),
990                             name);
991                 } else {
992                         (void) printf(gettext("will destroy %s\n"),
993                             name);
994                 }
995         }
996
997         /*
998          * Ignore pools (which we've already flagged as an error before getting
999          * here).
1000          */
1001         if (strchr(zfs_get_name(zhp), '/') == NULL &&
1002             zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1003                 zfs_close(zhp);
1004                 return (0);
1005         }
1006         if (cb->cb_dryrun) {
1007                 zfs_close(zhp);
1008                 return (0);
1009         }
1010
1011         /*
1012          * We batch up all contiguous snapshots (even of different
1013          * filesystems) and destroy them with one ioctl.  We can't
1014          * simply do all snap deletions and then all fs deletions,
1015          * because we must delete a clone before its origin.
1016          */
1017         if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT) {
1018                 fnvlist_add_boolean(cb->cb_batchedsnaps, name);
1019         } else {
1020                 int error = zfs_destroy_snaps_nvl(g_zfs,
1021                     cb->cb_batchedsnaps, B_FALSE);
1022                 fnvlist_free(cb->cb_batchedsnaps);
1023                 cb->cb_batchedsnaps = fnvlist_alloc();
1024
1025                 if (error != 0 ||
1026                     zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
1027                     zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
1028                         zfs_close(zhp);
1029                         return (-1);
1030                 }
1031         }
1032
1033         zfs_close(zhp);
1034         return (0);
1035 }
1036
1037 static int
1038 destroy_print_cb(zfs_handle_t *zhp, void *arg)
1039 {
1040         destroy_cbdata_t *cb = arg;
1041         const char *name = zfs_get_name(zhp);
1042         int err = 0;
1043
1044         if (nvlist_exists(cb->cb_nvl, name)) {
1045                 if (cb->cb_firstsnap == NULL)
1046                         cb->cb_firstsnap = strdup(name);
1047                 if (cb->cb_prevsnap != NULL)
1048                         free(cb->cb_prevsnap);
1049                 /* this snap continues the current range */
1050                 cb->cb_prevsnap = strdup(name);
1051                 if (cb->cb_firstsnap == NULL || cb->cb_prevsnap == NULL)
1052                         nomem();
1053                 if (cb->cb_verbose) {
1054                         if (cb->cb_parsable) {
1055                                 (void) printf("destroy\t%s\n", name);
1056                         } else if (cb->cb_dryrun) {
1057                                 (void) printf(gettext("would destroy %s\n"),
1058                                     name);
1059                         } else {
1060                                 (void) printf(gettext("will destroy %s\n"),
1061                                     name);
1062                         }
1063                 }
1064         } else if (cb->cb_firstsnap != NULL) {
1065                 /* end of this range */
1066                 uint64_t used = 0;
1067                 err = lzc_snaprange_space(cb->cb_firstsnap,
1068                     cb->cb_prevsnap, &used);
1069                 cb->cb_snapused += used;
1070                 free(cb->cb_firstsnap);
1071                 cb->cb_firstsnap = NULL;
1072                 free(cb->cb_prevsnap);
1073                 cb->cb_prevsnap = NULL;
1074         }
1075         zfs_close(zhp);
1076         return (err);
1077 }
1078
1079 static int
1080 destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
1081 {
1082         int err = 0;
1083         assert(cb->cb_firstsnap == NULL);
1084         assert(cb->cb_prevsnap == NULL);
1085         err = zfs_iter_snapshots_sorted(fs_zhp, destroy_print_cb, cb);
1086         if (cb->cb_firstsnap != NULL) {
1087                 uint64_t used = 0;
1088                 if (err == 0) {
1089                         err = lzc_snaprange_space(cb->cb_firstsnap,
1090                             cb->cb_prevsnap, &used);
1091                 }
1092                 cb->cb_snapused += used;
1093                 free(cb->cb_firstsnap);
1094                 cb->cb_firstsnap = NULL;
1095                 free(cb->cb_prevsnap);
1096                 cb->cb_prevsnap = NULL;
1097         }
1098         return (err);
1099 }
1100
1101 static int
1102 snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
1103 {
1104         destroy_cbdata_t *cb = arg;
1105         int err = 0;
1106
1107         /* Check for clones. */
1108         if (!cb->cb_doclones && !cb->cb_defer_destroy) {
1109                 cb->cb_target = zhp;
1110                 cb->cb_first = B_TRUE;
1111                 err = zfs_iter_dependents(zhp, B_TRUE,
1112                     destroy_check_dependent, cb);
1113         }
1114
1115         if (err == 0) {
1116                 if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
1117                         nomem();
1118         }
1119         zfs_close(zhp);
1120         return (err);
1121 }
1122
1123 static int
1124 gather_snapshots(zfs_handle_t *zhp, void *arg)
1125 {
1126         destroy_cbdata_t *cb = arg;
1127         int err = 0;
1128
1129         err = zfs_iter_snapspec(zhp, cb->cb_snapspec, snapshot_to_nvl_cb, cb);
1130         if (err == ENOENT)
1131                 err = 0;
1132         if (err != 0)
1133                 goto out;
1134
1135         if (cb->cb_verbose) {
1136                 err = destroy_print_snapshots(zhp, cb);
1137                 if (err != 0)
1138                         goto out;
1139         }
1140
1141         if (cb->cb_recurse)
1142                 err = zfs_iter_filesystems(zhp, gather_snapshots, cb);
1143
1144 out:
1145         zfs_close(zhp);
1146         return (err);
1147 }
1148
1149 static int
1150 destroy_clones(destroy_cbdata_t *cb)
1151 {
1152         nvpair_t *pair;
1153         for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
1154             pair != NULL;
1155             pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
1156                 zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
1157                     ZFS_TYPE_SNAPSHOT);
1158                 if (zhp != NULL) {
1159                         boolean_t defer = cb->cb_defer_destroy;
1160                         int err = 0;
1161
1162                         /*
1163                          * We can't defer destroy non-snapshots, so set it to
1164                          * false while destroying the clones.
1165                          */
1166                         cb->cb_defer_destroy = B_FALSE;
1167                         err = zfs_iter_dependents(zhp, B_FALSE,
1168                             destroy_callback, cb);
1169                         cb->cb_defer_destroy = defer;
1170                         zfs_close(zhp);
1171                         if (err != 0)
1172                                 return (err);
1173                 }
1174         }
1175         return (0);
1176 }
1177
1178 static int
1179 zfs_do_destroy(int argc, char **argv)
1180 {
1181         destroy_cbdata_t cb = { 0 };
1182         int rv = 0;
1183         int err = 0;
1184         int c;
1185         zfs_handle_t *zhp = NULL;
1186         char *at;
1187         zfs_type_t type = ZFS_TYPE_DATASET;
1188
1189         /* check options */
1190         while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
1191                 switch (c) {
1192                 case 'v':
1193                         cb.cb_verbose = B_TRUE;
1194                         break;
1195                 case 'p':
1196                         cb.cb_verbose = B_TRUE;
1197                         cb.cb_parsable = B_TRUE;
1198                         break;
1199                 case 'n':
1200                         cb.cb_dryrun = B_TRUE;
1201                         break;
1202                 case 'd':
1203                         cb.cb_defer_destroy = B_TRUE;
1204                         type = ZFS_TYPE_SNAPSHOT;
1205                         break;
1206                 case 'f':
1207                         cb.cb_force = B_TRUE;
1208                         break;
1209                 case 'r':
1210                         cb.cb_recurse = B_TRUE;
1211                         break;
1212                 case 'R':
1213                         cb.cb_recurse = B_TRUE;
1214                         cb.cb_doclones = B_TRUE;
1215                         break;
1216                 case '?':
1217                 default:
1218                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1219                             optopt);
1220                         usage(B_FALSE);
1221                 }
1222         }
1223
1224         argc -= optind;
1225         argv += optind;
1226
1227         /* check number of arguments */
1228         if (argc == 0) {
1229                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1230                 usage(B_FALSE);
1231         }
1232         if (argc > 1) {
1233                 (void) fprintf(stderr, gettext("too many arguments\n"));
1234                 usage(B_FALSE);
1235         }
1236
1237         at = strchr(argv[0], '@');
1238         if (at != NULL) {
1239
1240                 /* Build the list of snaps to destroy in cb_nvl. */
1241                 cb.cb_nvl = fnvlist_alloc();
1242
1243                 *at = '\0';
1244                 zhp = zfs_open(g_zfs, argv[0],
1245                     ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1246                 if (zhp == NULL)
1247                         return (1);
1248
1249                 cb.cb_snapspec = at + 1;
1250                 if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
1251                     cb.cb_error) {
1252                         rv = 1;
1253                         goto out;
1254                 }
1255
1256                 if (nvlist_empty(cb.cb_nvl)) {
1257                         (void) fprintf(stderr, gettext("could not find any "
1258                             "snapshots to destroy; check snapshot names.\n"));
1259                         rv = 1;
1260                         goto out;
1261                 }
1262
1263                 if (cb.cb_verbose) {
1264                         char buf[16];
1265                         zfs_nicenum(cb.cb_snapused, buf, sizeof (buf));
1266                         if (cb.cb_parsable) {
1267                                 (void) printf("reclaim\t%llu\n",
1268                                     cb.cb_snapused);
1269                         } else if (cb.cb_dryrun) {
1270                                 (void) printf(gettext("would reclaim %s\n"),
1271                                     buf);
1272                         } else {
1273                                 (void) printf(gettext("will reclaim %s\n"),
1274                                     buf);
1275                         }
1276                 }
1277
1278                 if (!cb.cb_dryrun) {
1279                         if (cb.cb_doclones) {
1280                                 cb.cb_batchedsnaps = fnvlist_alloc();
1281                                 err = destroy_clones(&cb);
1282                                 if (err == 0) {
1283                                         err = zfs_destroy_snaps_nvl(g_zfs,
1284                                             cb.cb_batchedsnaps, B_FALSE);
1285                                 }
1286                                 if (err != 0) {
1287                                         rv = 1;
1288                                         goto out;
1289                                 }
1290                         }
1291                         if (err == 0) {
1292                                 err = zfs_destroy_snaps_nvl(g_zfs, cb.cb_nvl,
1293                                     cb.cb_defer_destroy);
1294                         }
1295                 }
1296
1297                 if (err != 0)
1298                         rv = 1;
1299         } else {
1300                 /* Open the given dataset */
1301                 if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1302                         return (1);
1303
1304                 cb.cb_target = zhp;
1305
1306                 /*
1307                  * Perform an explicit check for pools before going any further.
1308                  */
1309                 if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1310                     zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1311                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
1312                             "operation does not apply to pools\n"),
1313                             zfs_get_name(zhp));
1314                         (void) fprintf(stderr, gettext("use 'zfs destroy -r "
1315                             "%s' to destroy all datasets in the pool\n"),
1316                             zfs_get_name(zhp));
1317                         (void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1318                             "to destroy the pool itself\n"), zfs_get_name(zhp));
1319                         rv = 1;
1320                         goto out;
1321                 }
1322
1323                 /*
1324                  * Check for any dependents and/or clones.
1325                  */
1326                 cb.cb_first = B_TRUE;
1327                 if (!cb.cb_doclones &&
1328                     zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
1329                     &cb) != 0) {
1330                         rv = 1;
1331                         goto out;
1332                 }
1333
1334                 if (cb.cb_error) {
1335                         rv = 1;
1336                         goto out;
1337                 }
1338
1339                 cb.cb_batchedsnaps = fnvlist_alloc();
1340                 if (zfs_iter_dependents(zhp, B_FALSE, destroy_callback,
1341                     &cb) != 0) {
1342                         rv = 1;
1343                         goto out;
1344                 }
1345
1346                 /*
1347                  * Do the real thing.  The callback will close the
1348                  * handle regardless of whether it succeeds or not.
1349                  */
1350                 err = destroy_callback(zhp, &cb);
1351                 zhp = NULL;
1352                 if (err == 0) {
1353                         err = zfs_destroy_snaps_nvl(g_zfs,
1354                             cb.cb_batchedsnaps, cb.cb_defer_destroy);
1355                 }
1356                 if (err != 0)
1357                         rv = 1;
1358         }
1359
1360 out:
1361         fnvlist_free(cb.cb_batchedsnaps);
1362         fnvlist_free(cb.cb_nvl);
1363         if (zhp != NULL)
1364                 zfs_close(zhp);
1365         return (rv);
1366 }
1367
1368 static boolean_t
1369 is_recvd_column(zprop_get_cbdata_t *cbp)
1370 {
1371         int i;
1372         zfs_get_column_t col;
1373
1374         for (i = 0; i < ZFS_GET_NCOLS &&
1375             (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1376                 if (col == GET_COL_RECVD)
1377                         return (B_TRUE);
1378         return (B_FALSE);
1379 }
1380
1381 /*
1382  * zfs get [-rHp] [-o all | field[,field]...] [-s source[,source]...]
1383  *      < all | property[,property]... > < fs | snap | vol > ...
1384  *
1385  *      -r      recurse over any child datasets
1386  *      -H      scripted mode.  Headers are stripped, and fields are separated
1387  *              by tabs instead of spaces.
1388  *      -o      Set of fields to display.  One of "name,property,value,
1389  *              received,source". Default is "name,property,value,source".
1390  *              "all" is an alias for all five.
1391  *      -s      Set of sources to allow.  One of
1392  *              "local,default,inherited,received,temporary,none".  Default is
1393  *              all six.
1394  *      -p      Display values in parsable (literal) format.
1395  *
1396  *  Prints properties for the given datasets.  The user can control which
1397  *  columns to display as well as which property types to allow.
1398  */
1399
1400 /*
1401  * Invoked to display the properties for a single dataset.
1402  */
1403 static int
1404 get_callback(zfs_handle_t *zhp, void *data)
1405 {
1406         char buf[ZFS_MAXPROPLEN];
1407         char rbuf[ZFS_MAXPROPLEN];
1408         zprop_source_t sourcetype;
1409         char source[ZFS_MAXNAMELEN];
1410         zprop_get_cbdata_t *cbp = data;
1411         nvlist_t *user_props = zfs_get_user_props(zhp);
1412         zprop_list_t *pl = cbp->cb_proplist;
1413         nvlist_t *propval;
1414         char *strval;
1415         char *sourceval;
1416         boolean_t received = is_recvd_column(cbp);
1417
1418         for (; pl != NULL; pl = pl->pl_next) {
1419                 char *recvdval = NULL;
1420                 /*
1421                  * Skip the special fake placeholder.  This will also skip over
1422                  * the name property when 'all' is specified.
1423                  */
1424                 if (pl->pl_prop == ZFS_PROP_NAME &&
1425                     pl == cbp->cb_proplist)
1426                         continue;
1427
1428                 if (pl->pl_prop != ZPROP_INVAL) {
1429                         if (zfs_prop_get(zhp, pl->pl_prop, buf,
1430                             sizeof (buf), &sourcetype, source,
1431                             sizeof (source),
1432                             cbp->cb_literal) != 0) {
1433                                 if (pl->pl_all)
1434                                         continue;
1435                                 if (!zfs_prop_valid_for_type(pl->pl_prop,
1436                                     ZFS_TYPE_DATASET)) {
1437                                         (void) fprintf(stderr,
1438                                             gettext("No such property '%s'\n"),
1439                                             zfs_prop_to_name(pl->pl_prop));
1440                                         continue;
1441                                 }
1442                                 sourcetype = ZPROP_SRC_NONE;
1443                                 (void) strlcpy(buf, "-", sizeof (buf));
1444                         }
1445
1446                         if (received && (zfs_prop_get_recvd(zhp,
1447                             zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
1448                             cbp->cb_literal) == 0))
1449                                 recvdval = rbuf;
1450
1451                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1452                             zfs_prop_to_name(pl->pl_prop),
1453                             buf, sourcetype, source, recvdval);
1454                 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
1455                         sourcetype = ZPROP_SRC_LOCAL;
1456
1457                         if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1458                             buf, sizeof (buf), cbp->cb_literal) != 0) {
1459                                 sourcetype = ZPROP_SRC_NONE;
1460                                 (void) strlcpy(buf, "-", sizeof (buf));
1461                         }
1462
1463                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1464                             pl->pl_user_prop, buf, sourcetype, source, NULL);
1465                 } else if (zfs_prop_written(pl->pl_user_prop)) {
1466                         sourcetype = ZPROP_SRC_LOCAL;
1467
1468                         if (zfs_prop_get_written(zhp, pl->pl_user_prop,
1469                             buf, sizeof (buf), cbp->cb_literal) != 0) {
1470                                 sourcetype = ZPROP_SRC_NONE;
1471                                 (void) strlcpy(buf, "-", sizeof (buf));
1472                         }
1473
1474                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1475                             pl->pl_user_prop, buf, sourcetype, source, NULL);
1476                 } else {
1477                         if (nvlist_lookup_nvlist(user_props,
1478                             pl->pl_user_prop, &propval) != 0) {
1479                                 if (pl->pl_all)
1480                                         continue;
1481                                 sourcetype = ZPROP_SRC_NONE;
1482                                 strval = "-";
1483                         } else {
1484                                 verify(nvlist_lookup_string(propval,
1485                                     ZPROP_VALUE, &strval) == 0);
1486                                 verify(nvlist_lookup_string(propval,
1487                                     ZPROP_SOURCE, &sourceval) == 0);
1488
1489                                 if (strcmp(sourceval,
1490                                     zfs_get_name(zhp)) == 0) {
1491                                         sourcetype = ZPROP_SRC_LOCAL;
1492                                 } else if (strcmp(sourceval,
1493                                     ZPROP_SOURCE_VAL_RECVD) == 0) {
1494                                         sourcetype = ZPROP_SRC_RECEIVED;
1495                                 } else {
1496                                         sourcetype = ZPROP_SRC_INHERITED;
1497                                         (void) strlcpy(source,
1498                                             sourceval, sizeof (source));
1499                                 }
1500                         }
1501
1502                         if (received && (zfs_prop_get_recvd(zhp,
1503                             pl->pl_user_prop, rbuf, sizeof (rbuf),
1504                             cbp->cb_literal) == 0))
1505                                 recvdval = rbuf;
1506
1507                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1508                             pl->pl_user_prop, strval, sourcetype,
1509                             source, recvdval);
1510                 }
1511         }
1512
1513         return (0);
1514 }
1515
1516 static int
1517 zfs_do_get(int argc, char **argv)
1518 {
1519         zprop_get_cbdata_t cb = { 0 };
1520         int i, c, flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1521         int types = ZFS_TYPE_DATASET;
1522         char *value, *fields;
1523         int ret = 0;
1524         int limit = 0;
1525         zprop_list_t fake_name = { 0 };
1526
1527         /*
1528          * Set up default columns and sources.
1529          */
1530         cb.cb_sources = ZPROP_SRC_ALL;
1531         cb.cb_columns[0] = GET_COL_NAME;
1532         cb.cb_columns[1] = GET_COL_PROPERTY;
1533         cb.cb_columns[2] = GET_COL_VALUE;
1534         cb.cb_columns[3] = GET_COL_SOURCE;
1535         cb.cb_type = ZFS_TYPE_DATASET;
1536
1537         /* check options */
1538         while ((c = getopt(argc, argv, ":d:o:s:rt:Hp")) != -1) {
1539                 switch (c) {
1540                 case 'p':
1541                         cb.cb_literal = B_TRUE;
1542                         break;
1543                 case 'd':
1544                         limit = parse_depth(optarg, &flags);
1545                         break;
1546                 case 'r':
1547                         flags |= ZFS_ITER_RECURSE;
1548                         break;
1549                 case 'H':
1550                         cb.cb_scripted = B_TRUE;
1551                         break;
1552                 case ':':
1553                         (void) fprintf(stderr, gettext("missing argument for "
1554                             "'%c' option\n"), optopt);
1555                         usage(B_FALSE);
1556                         break;
1557                 case 'o':
1558                         /*
1559                          * Process the set of columns to display.  We zero out
1560                          * the structure to give us a blank slate.
1561                          */
1562                         bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1563                         i = 0;
1564                         while (*optarg != '\0') {
1565                                 static char *col_subopts[] =
1566                                     { "name", "property", "value", "received",
1567                                     "source", "all", NULL };
1568
1569                                 if (i == ZFS_GET_NCOLS) {
1570                                         (void) fprintf(stderr, gettext("too "
1571                                             "many fields given to -o "
1572                                             "option\n"));
1573                                         usage(B_FALSE);
1574                                 }
1575
1576                                 switch (getsubopt(&optarg, col_subopts,
1577                                     &value)) {
1578                                 case 0:
1579                                         cb.cb_columns[i++] = GET_COL_NAME;
1580                                         break;
1581                                 case 1:
1582                                         cb.cb_columns[i++] = GET_COL_PROPERTY;
1583                                         break;
1584                                 case 2:
1585                                         cb.cb_columns[i++] = GET_COL_VALUE;
1586                                         break;
1587                                 case 3:
1588                                         cb.cb_columns[i++] = GET_COL_RECVD;
1589                                         flags |= ZFS_ITER_RECVD_PROPS;
1590                                         break;
1591                                 case 4:
1592                                         cb.cb_columns[i++] = GET_COL_SOURCE;
1593                                         break;
1594                                 case 5:
1595                                         if (i > 0) {
1596                                                 (void) fprintf(stderr,
1597                                                     gettext("\"all\" conflicts "
1598                                                     "with specific fields "
1599                                                     "given to -o option\n"));
1600                                                 usage(B_FALSE);
1601                                         }
1602                                         cb.cb_columns[0] = GET_COL_NAME;
1603                                         cb.cb_columns[1] = GET_COL_PROPERTY;
1604                                         cb.cb_columns[2] = GET_COL_VALUE;
1605                                         cb.cb_columns[3] = GET_COL_RECVD;
1606                                         cb.cb_columns[4] = GET_COL_SOURCE;
1607                                         flags |= ZFS_ITER_RECVD_PROPS;
1608                                         i = ZFS_GET_NCOLS;
1609                                         break;
1610                                 default:
1611                                         (void) fprintf(stderr,
1612                                             gettext("invalid column name "
1613                                             "'%s'\n"), value);
1614                                         usage(B_FALSE);
1615                                 }
1616                         }
1617                         break;
1618
1619                 case 's':
1620                         cb.cb_sources = 0;
1621                         while (*optarg != '\0') {
1622                                 static char *source_subopts[] = {
1623                                         "local", "default", "inherited",
1624                                         "received", "temporary", "none",
1625                                         NULL };
1626
1627                                 switch (getsubopt(&optarg, source_subopts,
1628                                     &value)) {
1629                                 case 0:
1630                                         cb.cb_sources |= ZPROP_SRC_LOCAL;
1631                                         break;
1632                                 case 1:
1633                                         cb.cb_sources |= ZPROP_SRC_DEFAULT;
1634                                         break;
1635                                 case 2:
1636                                         cb.cb_sources |= ZPROP_SRC_INHERITED;
1637                                         break;
1638                                 case 3:
1639                                         cb.cb_sources |= ZPROP_SRC_RECEIVED;
1640                                         break;
1641                                 case 4:
1642                                         cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1643                                         break;
1644                                 case 5:
1645                                         cb.cb_sources |= ZPROP_SRC_NONE;
1646                                         break;
1647                                 default:
1648                                         (void) fprintf(stderr,
1649                                             gettext("invalid source "
1650                                             "'%s'\n"), value);
1651                                         usage(B_FALSE);
1652                                 }
1653                         }
1654                         break;
1655
1656                 case 't':
1657                         types = 0;
1658                         flags &= ~ZFS_ITER_PROP_LISTSNAPS;
1659                         while (*optarg != '\0') {
1660                                 static char *type_subopts[] = { "filesystem",
1661                                     "volume", "snapshot", "all", NULL };
1662
1663                                 switch (getsubopt(&optarg, type_subopts,
1664                                     &value)) {
1665                                 case 0:
1666                                         types |= ZFS_TYPE_FILESYSTEM;
1667                                         break;
1668                                 case 1:
1669                                         types |= ZFS_TYPE_VOLUME;
1670                                         break;
1671                                 case 2:
1672                                         types |= ZFS_TYPE_SNAPSHOT;
1673                                         break;
1674                                 case 3:
1675                                         types = ZFS_TYPE_DATASET;
1676                                         break;
1677
1678                                 default:
1679                                         (void) fprintf(stderr,
1680                                             gettext("invalid type '%s'\n"),
1681                                             value);
1682                                         usage(B_FALSE);
1683                                 }
1684                         }
1685                         break;
1686
1687                 case '?':
1688                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1689                             optopt);
1690                         usage(B_FALSE);
1691                 }
1692         }
1693
1694         argc -= optind;
1695         argv += optind;
1696
1697         if (argc < 1) {
1698                 (void) fprintf(stderr, gettext("missing property "
1699                     "argument\n"));
1700                 usage(B_FALSE);
1701         }
1702
1703         fields = argv[0];
1704
1705         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1706             != 0)
1707                 usage(B_FALSE);
1708
1709         argc--;
1710         argv++;
1711
1712         /*
1713          * As part of zfs_expand_proplist(), we keep track of the maximum column
1714          * width for each property.  For the 'NAME' (and 'SOURCE') columns, we
1715          * need to know the maximum name length.  However, the user likely did
1716          * not specify 'name' as one of the properties to fetch, so we need to
1717          * make sure we always include at least this property for
1718          * print_get_headers() to work properly.
1719          */
1720         if (cb.cb_proplist != NULL) {
1721                 fake_name.pl_prop = ZFS_PROP_NAME;
1722                 fake_name.pl_width = strlen(gettext("NAME"));
1723                 fake_name.pl_next = cb.cb_proplist;
1724                 cb.cb_proplist = &fake_name;
1725         }
1726
1727         cb.cb_first = B_TRUE;
1728
1729         /* run for each object */
1730         ret = zfs_for_each(argc, argv, flags, types, NULL,
1731             &cb.cb_proplist, limit, get_callback, &cb);
1732
1733         if (cb.cb_proplist == &fake_name)
1734                 zprop_free_list(fake_name.pl_next);
1735         else
1736                 zprop_free_list(cb.cb_proplist);
1737
1738         return (ret);
1739 }
1740
1741 /*
1742  * inherit [-rS] <property> <fs|vol> ...
1743  *
1744  *      -r      Recurse over all children
1745  *      -S      Revert to received value, if any
1746  *
1747  * For each dataset specified on the command line, inherit the given property
1748  * from its parent.  Inheriting a property at the pool level will cause it to
1749  * use the default value.  The '-r' flag will recurse over all children, and is
1750  * useful for setting a property on a hierarchy-wide basis, regardless of any
1751  * local modifications for each dataset.
1752  */
1753
1754 typedef struct inherit_cbdata {
1755         const char *cb_propname;
1756         boolean_t cb_received;
1757 } inherit_cbdata_t;
1758
1759 static int
1760 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
1761 {
1762         inherit_cbdata_t *cb = data;
1763         zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
1764
1765         /*
1766          * If we're doing it recursively, then ignore properties that
1767          * are not valid for this type of dataset.
1768          */
1769         if (prop != ZPROP_INVAL &&
1770             !zfs_prop_valid_for_type(prop, zfs_get_type(zhp)))
1771                 return (0);
1772
1773         return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1774 }
1775
1776 static int
1777 inherit_cb(zfs_handle_t *zhp, void *data)
1778 {
1779         inherit_cbdata_t *cb = data;
1780
1781         return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1782 }
1783
1784 static int
1785 zfs_do_inherit(int argc, char **argv)
1786 {
1787         int c;
1788         zfs_prop_t prop;
1789         inherit_cbdata_t cb = { 0 };
1790         char *propname;
1791         int ret = 0;
1792         int flags = 0;
1793         boolean_t received = B_FALSE;
1794
1795         /* check options */
1796         while ((c = getopt(argc, argv, "rS")) != -1) {
1797                 switch (c) {
1798                 case 'r':
1799                         flags |= ZFS_ITER_RECURSE;
1800                         break;
1801                 case 'S':
1802                         received = B_TRUE;
1803                         break;
1804                 case '?':
1805                 default:
1806                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1807                             optopt);
1808                         usage(B_FALSE);
1809                 }
1810         }
1811
1812         argc -= optind;
1813         argv += optind;
1814
1815         /* check number of arguments */
1816         if (argc < 1) {
1817                 (void) fprintf(stderr, gettext("missing property argument\n"));
1818                 usage(B_FALSE);
1819         }
1820         if (argc < 2) {
1821                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1822                 usage(B_FALSE);
1823         }
1824
1825         propname = argv[0];
1826         argc--;
1827         argv++;
1828
1829         if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1830                 if (zfs_prop_readonly(prop)) {
1831                         (void) fprintf(stderr, gettext(
1832                             "%s property is read-only\n"),
1833                             propname);
1834                         return (1);
1835                 }
1836                 if (!zfs_prop_inheritable(prop) && !received) {
1837                         (void) fprintf(stderr, gettext("'%s' property cannot "
1838                             "be inherited\n"), propname);
1839                         if (prop == ZFS_PROP_QUOTA ||
1840                             prop == ZFS_PROP_RESERVATION ||
1841                             prop == ZFS_PROP_REFQUOTA ||
1842                             prop == ZFS_PROP_REFRESERVATION)
1843                                 (void) fprintf(stderr, gettext("use 'zfs set "
1844                                     "%s=none' to clear\n"), propname);
1845                         return (1);
1846                 }
1847                 if (received && (prop == ZFS_PROP_VOLSIZE ||
1848                     prop == ZFS_PROP_VERSION)) {
1849                         (void) fprintf(stderr, gettext("'%s' property cannot "
1850                             "be reverted to a received value\n"), propname);
1851                         return (1);
1852                 }
1853         } else if (!zfs_prop_user(propname)) {
1854                 (void) fprintf(stderr, gettext("invalid property '%s'\n"),
1855                     propname);
1856                 usage(B_FALSE);
1857         }
1858
1859         cb.cb_propname = propname;
1860         cb.cb_received = received;
1861
1862         if (flags & ZFS_ITER_RECURSE) {
1863                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1864                     NULL, NULL, 0, inherit_recurse_cb, &cb);
1865         } else {
1866                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1867                     NULL, NULL, 0, inherit_cb, &cb);
1868         }
1869
1870         return (ret);
1871 }
1872
1873 typedef struct upgrade_cbdata {
1874         uint64_t cb_numupgraded;
1875         uint64_t cb_numsamegraded;
1876         uint64_t cb_numfailed;
1877         uint64_t cb_version;
1878         boolean_t cb_newer;
1879         boolean_t cb_foundone;
1880         char cb_lastfs[ZFS_MAXNAMELEN];
1881 } upgrade_cbdata_t;
1882
1883 static int
1884 same_pool(zfs_handle_t *zhp, const char *name)
1885 {
1886         int len1 = strcspn(name, "/@");
1887         const char *zhname = zfs_get_name(zhp);
1888         int len2 = strcspn(zhname, "/@");
1889
1890         if (len1 != len2)
1891                 return (B_FALSE);
1892         return (strncmp(name, zhname, len1) == 0);
1893 }
1894
1895 static int
1896 upgrade_list_callback(zfs_handle_t *zhp, void *data)
1897 {
1898         upgrade_cbdata_t *cb = data;
1899         int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1900
1901         /* list if it's old/new */
1902         if ((!cb->cb_newer && version < ZPL_VERSION) ||
1903             (cb->cb_newer && version > ZPL_VERSION)) {
1904                 char *str;
1905                 if (cb->cb_newer) {
1906                         str = gettext("The following filesystems are "
1907                             "formatted using a newer software version and\n"
1908                             "cannot be accessed on the current system.\n\n");
1909                 } else {
1910                         str = gettext("The following filesystems are "
1911                             "out of date, and can be upgraded.  After being\n"
1912                             "upgraded, these filesystems (and any 'zfs send' "
1913                             "streams generated from\n"
1914                             "subsequent snapshots) will no longer be "
1915                             "accessible by older software versions.\n\n");
1916                 }
1917
1918                 if (!cb->cb_foundone) {
1919                         (void) puts(str);
1920                         (void) printf(gettext("VER  FILESYSTEM\n"));
1921                         (void) printf(gettext("---  ------------\n"));
1922                         cb->cb_foundone = B_TRUE;
1923                 }
1924
1925                 (void) printf("%2u   %s\n", version, zfs_get_name(zhp));
1926         }
1927
1928         return (0);
1929 }
1930
1931 static int
1932 upgrade_set_callback(zfs_handle_t *zhp, void *data)
1933 {
1934         upgrade_cbdata_t *cb = data;
1935         int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1936         int needed_spa_version;
1937         int spa_version;
1938
1939         if (zfs_spa_version(zhp, &spa_version) < 0)
1940                 return (-1);
1941
1942         needed_spa_version = zfs_spa_version_map(cb->cb_version);
1943
1944         if (needed_spa_version < 0)
1945                 return (-1);
1946
1947         if (spa_version < needed_spa_version) {
1948                 /* can't upgrade */
1949                 (void) printf(gettext("%s: can not be "
1950                     "upgraded; the pool version needs to first "
1951                     "be upgraded\nto version %d\n\n"),
1952                     zfs_get_name(zhp), needed_spa_version);
1953                 cb->cb_numfailed++;
1954                 return (0);
1955         }
1956
1957         /* upgrade */
1958         if (version < cb->cb_version) {
1959                 char verstr[16];
1960                 (void) snprintf(verstr, sizeof (verstr),
1961                     "%llu", cb->cb_version);
1962                 if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
1963                         /*
1964                          * If they did "zfs upgrade -a", then we could
1965                          * be doing ioctls to different pools.  We need
1966                          * to log this history once to each pool, and bypass
1967                          * the normal history logging that happens in main().
1968                          */
1969                         (void) zpool_log_history(g_zfs, history_str);
1970                         log_history = B_FALSE;
1971                 }
1972                 if (zfs_prop_set(zhp, "version", verstr) == 0)
1973                         cb->cb_numupgraded++;
1974                 else
1975                         cb->cb_numfailed++;
1976                 (void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
1977         } else if (version > cb->cb_version) {
1978                 /* can't downgrade */
1979                 (void) printf(gettext("%s: can not be downgraded; "
1980                     "it is already at version %u\n"),
1981                     zfs_get_name(zhp), version);
1982                 cb->cb_numfailed++;
1983         } else {
1984                 cb->cb_numsamegraded++;
1985         }
1986         return (0);
1987 }
1988
1989 /*
1990  * zfs upgrade
1991  * zfs upgrade -v
1992  * zfs upgrade [-r] [-V <version>] <-a | filesystem>
1993  */
1994 static int
1995 zfs_do_upgrade(int argc, char **argv)
1996 {
1997         boolean_t all = B_FALSE;
1998         boolean_t showversions = B_FALSE;
1999         int ret = 0;
2000         upgrade_cbdata_t cb = { 0 };
2001         char c;
2002         int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2003
2004         /* check options */
2005         while ((c = getopt(argc, argv, "rvV:a")) != -1) {
2006                 switch (c) {
2007                 case 'r':
2008                         flags |= ZFS_ITER_RECURSE;
2009                         break;
2010                 case 'v':
2011                         showversions = B_TRUE;
2012                         break;
2013                 case 'V':
2014                         if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
2015                             optarg, &cb.cb_version) != 0) {
2016                                 (void) fprintf(stderr,
2017                                     gettext("invalid version %s\n"), optarg);
2018                                 usage(B_FALSE);
2019                         }
2020                         break;
2021                 case 'a':
2022                         all = B_TRUE;
2023                         break;
2024                 case '?':
2025                 default:
2026                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2027                             optopt);
2028                         usage(B_FALSE);
2029                 }
2030         }
2031
2032         argc -= optind;
2033         argv += optind;
2034
2035         if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
2036                 usage(B_FALSE);
2037         if (showversions && (flags & ZFS_ITER_RECURSE || all ||
2038             cb.cb_version || argc))
2039                 usage(B_FALSE);
2040         if ((all || argc) && (showversions))
2041                 usage(B_FALSE);
2042         if (all && argc)
2043                 usage(B_FALSE);
2044
2045         if (showversions) {
2046                 /* Show info on available versions. */
2047                 (void) printf(gettext("The following filesystem versions are "
2048                     "supported:\n\n"));
2049                 (void) printf(gettext("VER  DESCRIPTION\n"));
2050                 (void) printf("---  -----------------------------------------"
2051                     "---------------\n");
2052                 (void) printf(gettext(" 1   Initial ZFS filesystem version\n"));
2053                 (void) printf(gettext(" 2   Enhanced directory entries\n"));
2054                 (void) printf(gettext(" 3   Case insensitive and filesystem "
2055                     "user identifier (FUID)\n"));
2056                 (void) printf(gettext(" 4   userquota, groupquota "
2057                     "properties\n"));
2058                 (void) printf(gettext(" 5   System attributes\n"));
2059                 (void) printf(gettext("\nFor more information on a particular "
2060                     "version, including supported releases,\n"));
2061                 (void) printf("see the ZFS Administration Guide.\n\n");
2062                 ret = 0;
2063         } else if (argc || all) {
2064                 /* Upgrade filesystems */
2065                 if (cb.cb_version == 0)
2066                         cb.cb_version = ZPL_VERSION;
2067                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
2068                     NULL, NULL, 0, upgrade_set_callback, &cb);
2069                 (void) printf(gettext("%llu filesystems upgraded\n"),
2070                     cb.cb_numupgraded);
2071                 if (cb.cb_numsamegraded) {
2072                         (void) printf(gettext("%llu filesystems already at "
2073                             "this version\n"),
2074                             cb.cb_numsamegraded);
2075                 }
2076                 if (cb.cb_numfailed != 0)
2077                         ret = 1;
2078         } else {
2079                 /* List old-version filesytems */
2080                 boolean_t found;
2081                 (void) printf(gettext("This system is currently running "
2082                     "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
2083
2084                 flags |= ZFS_ITER_RECURSE;
2085                 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2086                     NULL, NULL, 0, upgrade_list_callback, &cb);
2087
2088                 found = cb.cb_foundone;
2089                 cb.cb_foundone = B_FALSE;
2090                 cb.cb_newer = B_TRUE;
2091
2092                 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2093                     NULL, NULL, 0, upgrade_list_callback, &cb);
2094
2095                 if (!cb.cb_foundone && !found) {
2096                         (void) printf(gettext("All filesystems are "
2097                             "formatted with the current version.\n"));
2098                 }
2099         }
2100
2101         return (ret);
2102 }
2103
2104 /*
2105  * zfs userspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2106  *               [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2107  * zfs groupspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2108  *                [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2109  *
2110  *      -H      Scripted mode; elide headers and separate columns by tabs.
2111  *      -i      Translate SID to POSIX ID.
2112  *      -n      Print numeric ID instead of user/group name.
2113  *      -o      Control which fields to display.
2114  *      -p      Use exact (parseable) numeric output.
2115  *      -s      Specify sort columns, descending order.
2116  *      -S      Specify sort columns, ascending order.
2117  *      -t      Control which object types to display.
2118  *
2119  *      Displays space consumed by, and quotas on, each user in the specified
2120  *      filesystem or snapshot.
2121  */
2122
2123 /* us_field_types, us_field_hdr and us_field_names should be kept in sync */
2124 enum us_field_types {
2125         USFIELD_TYPE,
2126         USFIELD_NAME,
2127         USFIELD_USED,
2128         USFIELD_QUOTA
2129 };
2130 static char *us_field_hdr[] = { "TYPE", "NAME", "USED", "QUOTA" };
2131 static char *us_field_names[] = { "type", "name", "used", "quota" };
2132 #define USFIELD_LAST    (sizeof (us_field_names) / sizeof (char *))
2133
2134 #define USTYPE_PSX_GRP  (1 << 0)
2135 #define USTYPE_PSX_USR  (1 << 1)
2136 #define USTYPE_SMB_GRP  (1 << 2)
2137 #define USTYPE_SMB_USR  (1 << 3)
2138 #define USTYPE_ALL      \
2139         (USTYPE_PSX_GRP | USTYPE_PSX_USR | USTYPE_SMB_GRP | USTYPE_SMB_USR)
2140
2141 static int us_type_bits[] = {
2142         USTYPE_PSX_GRP,
2143         USTYPE_PSX_USR,
2144         USTYPE_SMB_GRP,
2145         USTYPE_SMB_USR,
2146         USTYPE_ALL
2147 };
2148 static char *us_type_names[] = { "posixgroup", "posxiuser", "smbgroup",
2149         "smbuser", "all" };
2150
2151 typedef struct us_node {
2152         nvlist_t        *usn_nvl;
2153         uu_avl_node_t   usn_avlnode;
2154         uu_list_node_t  usn_listnode;
2155 } us_node_t;
2156
2157 typedef struct us_cbdata {
2158         nvlist_t        **cb_nvlp;
2159         uu_avl_pool_t   *cb_avl_pool;
2160         uu_avl_t        *cb_avl;
2161         boolean_t       cb_numname;
2162         boolean_t       cb_nicenum;
2163         boolean_t       cb_sid2posix;
2164         zfs_userquota_prop_t cb_prop;
2165         zfs_sort_column_t *cb_sortcol;
2166         size_t          cb_width[USFIELD_LAST];
2167 } us_cbdata_t;
2168
2169 static boolean_t us_populated = B_FALSE;
2170
2171 typedef struct {
2172         zfs_sort_column_t *si_sortcol;
2173         boolean_t       si_numname;
2174 } us_sort_info_t;
2175
2176 static int
2177 us_field_index(char *field)
2178 {
2179         int i;
2180
2181         for (i = 0; i < USFIELD_LAST; i++) {
2182                 if (strcmp(field, us_field_names[i]) == 0)
2183                         return (i);
2184         }
2185
2186         return (-1);
2187 }
2188
2189 static int
2190 us_compare(const void *larg, const void *rarg, void *unused)
2191 {
2192         const us_node_t *l = larg;
2193         const us_node_t *r = rarg;
2194         us_sort_info_t *si = (us_sort_info_t *)unused;
2195         zfs_sort_column_t *sortcol = si->si_sortcol;
2196         boolean_t numname = si->si_numname;
2197         nvlist_t *lnvl = l->usn_nvl;
2198         nvlist_t *rnvl = r->usn_nvl;
2199         int rc = 0;
2200         boolean_t lvb, rvb;
2201
2202         for (; sortcol != NULL; sortcol = sortcol->sc_next) {
2203                 char *lvstr = "";
2204                 char *rvstr = "";
2205                 uint32_t lv32 = 0;
2206                 uint32_t rv32 = 0;
2207                 uint64_t lv64 = 0;
2208                 uint64_t rv64 = 0;
2209                 zfs_prop_t prop = sortcol->sc_prop;
2210                 const char *propname = NULL;
2211                 boolean_t reverse = sortcol->sc_reverse;
2212
2213                 switch (prop) {
2214                 case ZFS_PROP_TYPE:
2215                         propname = "type";
2216                         (void) nvlist_lookup_uint32(lnvl, propname, &lv32);
2217                         (void) nvlist_lookup_uint32(rnvl, propname, &rv32);
2218                         if (rv32 != lv32)
2219                                 rc = (rv32 < lv32) ? 1 : -1;
2220                         break;
2221                 case ZFS_PROP_NAME:
2222                         propname = "name";
2223                         if (numname) {
2224                                 (void) nvlist_lookup_uint64(lnvl, propname,
2225                                     &lv64);
2226                                 (void) nvlist_lookup_uint64(rnvl, propname,
2227                                     &rv64);
2228                                 if (rv64 != lv64)
2229                                         rc = (rv64 < lv64) ? 1 : -1;
2230                         } else {
2231                                 (void) nvlist_lookup_string(lnvl, propname,
2232                                     &lvstr);
2233                                 (void) nvlist_lookup_string(rnvl, propname,
2234                                     &rvstr);
2235                                 rc = strcmp(lvstr, rvstr);
2236                         }
2237                         break;
2238                 case ZFS_PROP_USED:
2239                 case ZFS_PROP_QUOTA:
2240                         if (!us_populated)
2241                                 break;
2242                         if (prop == ZFS_PROP_USED)
2243                                 propname = "used";
2244                         else
2245                                 propname = "quota";
2246                         (void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2247                         (void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2248                         if (rv64 != lv64)
2249                                 rc = (rv64 < lv64) ? 1 : -1;
2250                         break;
2251                 }
2252
2253                 if (rc != 0) {
2254                         if (rc < 0)
2255                                 return (reverse ? 1 : -1);
2256                         else
2257                                 return (reverse ? -1 : 1);
2258                 }
2259         }
2260
2261         /*
2262          * If entries still seem to be the same, check if they are of the same
2263          * type (smbentity is added only if we are doing SID to POSIX ID
2264          * translation where we can have duplicate type/name combinations).
2265          */
2266         if (nvlist_lookup_boolean_value(lnvl, "smbentity", &lvb) == 0 &&
2267             nvlist_lookup_boolean_value(rnvl, "smbentity", &rvb) == 0 &&
2268             lvb != rvb)
2269                 return (lvb < rvb ? -1 : 1);
2270
2271         return (0);
2272 }
2273
2274 static inline const char *
2275 us_type2str(unsigned field_type)
2276 {
2277         switch (field_type) {
2278         case USTYPE_PSX_USR:
2279                 return ("POSIX User");
2280         case USTYPE_PSX_GRP:
2281                 return ("POSIX Group");
2282         case USTYPE_SMB_USR:
2283                 return ("SMB User");
2284         case USTYPE_SMB_GRP:
2285                 return ("SMB Group");
2286         default:
2287                 return ("Undefined");
2288         }
2289 }
2290
2291 static int
2292 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2293 {
2294         us_cbdata_t *cb = (us_cbdata_t *)arg;
2295         zfs_userquota_prop_t prop = cb->cb_prop;
2296         char *name = NULL;
2297         char *propname;
2298         char sizebuf[32];
2299         us_node_t *node;
2300         uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2301         uu_avl_t *avl = cb->cb_avl;
2302         uu_avl_index_t idx;
2303         nvlist_t *props;
2304         us_node_t *n;
2305         zfs_sort_column_t *sortcol = cb->cb_sortcol;
2306         unsigned type;
2307         const char *typestr;
2308         size_t namelen;
2309         size_t typelen;
2310         size_t sizelen;
2311         int typeidx, nameidx, sizeidx;
2312         us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
2313         boolean_t smbentity = B_FALSE;
2314
2315         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
2316                 nomem();
2317         node = safe_malloc(sizeof (us_node_t));
2318         uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
2319         node->usn_nvl = props;
2320
2321         if (domain != NULL && domain[0] != '\0') {
2322                 /* SMB */
2323                 char sid[ZFS_MAXNAMELEN + 32];
2324                 uid_t id;
2325                 uint64_t classes;
2326 #ifdef sun
2327                 int err;
2328                 directory_error_t e;
2329 #endif
2330
2331                 smbentity = B_TRUE;
2332
2333                 (void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
2334
2335                 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2336                         type = USTYPE_SMB_GRP;
2337 #ifdef sun
2338                         err = sid_to_id(sid, B_FALSE, &id);
2339 #endif
2340                 } else {
2341                         type = USTYPE_SMB_USR;
2342 #ifdef sun
2343                         err = sid_to_id(sid, B_TRUE, &id);
2344 #endif
2345                 }
2346
2347 #ifdef sun
2348                 if (err == 0) {
2349                         rid = id;
2350                         if (!cb->cb_sid2posix) {
2351                                 e = directory_name_from_sid(NULL, sid, &name,
2352                                     &classes);
2353                                 if (e != NULL)
2354                                         directory_error_free(e);
2355                                 if (name == NULL)
2356                                         name = sid;
2357                         }
2358                 }
2359 #endif
2360         }
2361
2362         if (cb->cb_sid2posix || domain == NULL || domain[0] == '\0') {
2363                 /* POSIX or -i */
2364                 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2365                         type = USTYPE_PSX_GRP;
2366                         if (!cb->cb_numname) {
2367                                 struct group *g;
2368
2369                                 if ((g = getgrgid(rid)) != NULL)
2370                                         name = g->gr_name;
2371                         }
2372                 } else {
2373                         type = USTYPE_PSX_USR;
2374                         if (!cb->cb_numname) {
2375                                 struct passwd *p;
2376
2377                                 if ((p = getpwuid(rid)) != NULL)
2378                                         name = p->pw_name;
2379                         }
2380                 }
2381         }
2382
2383         /*
2384          * Make sure that the type/name combination is unique when doing
2385          * SID to POSIX ID translation (hence changing the type from SMB to
2386          * POSIX).
2387          */
2388         if (cb->cb_sid2posix &&
2389             nvlist_add_boolean_value(props, "smbentity", smbentity) != 0)
2390                 nomem();
2391
2392         /* Calculate/update width of TYPE field */
2393         typestr = us_type2str(type);
2394         typelen = strlen(gettext(typestr));
2395         typeidx = us_field_index("type");
2396         if (typelen > cb->cb_width[typeidx])
2397                 cb->cb_width[typeidx] = typelen;
2398         if (nvlist_add_uint32(props, "type", type) != 0)
2399                 nomem();
2400
2401         /* Calculate/update width of NAME field */
2402         if ((cb->cb_numname && cb->cb_sid2posix) || name == NULL) {
2403                 if (nvlist_add_uint64(props, "name", rid) != 0)
2404                         nomem();
2405                 namelen = snprintf(NULL, 0, "%u", rid);
2406         } else {
2407                 if (nvlist_add_string(props, "name", name) != 0)
2408                         nomem();
2409                 namelen = strlen(name);
2410         }
2411         nameidx = us_field_index("name");
2412         if (namelen > cb->cb_width[nameidx])
2413                 cb->cb_width[nameidx] = namelen;
2414
2415         /*
2416          * Check if this type/name combination is in the list and update it;
2417          * otherwise add new node to the list.
2418          */
2419         if ((n = uu_avl_find(avl, node, &sortinfo, &idx)) == NULL) {
2420                 uu_avl_insert(avl, node, idx);
2421         } else {
2422                 nvlist_free(props);
2423                 free(node);
2424                 node = n;
2425                 props = node->usn_nvl;
2426         }
2427
2428         /* Calculate/update width of USED/QUOTA fields */
2429         if (cb->cb_nicenum)
2430                 zfs_nicenum(space, sizebuf, sizeof (sizebuf));
2431         else
2432                 (void) snprintf(sizebuf, sizeof (sizebuf), "%llu", space);
2433         sizelen = strlen(sizebuf);
2434         if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED) {
2435                 propname = "used";
2436                 if (!nvlist_exists(props, "quota"))
2437                         (void) nvlist_add_uint64(props, "quota", 0);
2438         } else {
2439                 propname = "quota";
2440                 if (!nvlist_exists(props, "used"))
2441                         (void) nvlist_add_uint64(props, "used", 0);
2442         }
2443         sizeidx = us_field_index(propname);
2444         if (sizelen > cb->cb_width[sizeidx])
2445                 cb->cb_width[sizeidx] = sizelen;
2446
2447         if (nvlist_add_uint64(props, propname, space) != 0)
2448                 nomem();
2449
2450         return (0);
2451 }
2452
2453 static void
2454 print_us_node(boolean_t scripted, boolean_t parsable, int *fields, int types,
2455     size_t *width, us_node_t *node)
2456 {
2457         nvlist_t *nvl = node->usn_nvl;
2458         char valstr[ZFS_MAXNAMELEN];
2459         boolean_t first = B_TRUE;
2460         int cfield = 0;
2461         int field;
2462         uint32_t ustype;
2463
2464         /* Check type */
2465         (void) nvlist_lookup_uint32(nvl, "type", &ustype);
2466         if (!(ustype & types))
2467                 return;
2468
2469         while ((field = fields[cfield]) != USFIELD_LAST) {
2470                 nvpair_t *nvp = NULL;
2471                 data_type_t type;
2472                 uint32_t val32;
2473                 uint64_t val64;
2474                 char *strval = NULL;
2475
2476                 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
2477                         if (strcmp(nvpair_name(nvp),
2478                             us_field_names[field]) == 0)
2479                                 break;
2480                 }
2481
2482                 type = nvpair_type(nvp);
2483                 switch (type) {
2484                 case DATA_TYPE_UINT32:
2485                         (void) nvpair_value_uint32(nvp, &val32);
2486                         break;
2487                 case DATA_TYPE_UINT64:
2488                         (void) nvpair_value_uint64(nvp, &val64);
2489                         break;
2490                 case DATA_TYPE_STRING:
2491                         (void) nvpair_value_string(nvp, &strval);
2492                         break;
2493                 default:
2494                         (void) fprintf(stderr, "invalid data type\n");
2495                 }
2496
2497                 switch (field) {
2498                 case USFIELD_TYPE:
2499                         strval = (char *)us_type2str(val32);
2500                         break;
2501                 case USFIELD_NAME:
2502                         if (type == DATA_TYPE_UINT64) {
2503                                 (void) sprintf(valstr, "%llu", val64);
2504                                 strval = valstr;
2505                         }
2506                         break;
2507                 case USFIELD_USED:
2508                 case USFIELD_QUOTA:
2509                         if (type == DATA_TYPE_UINT64) {
2510                                 if (parsable) {
2511                                         (void) sprintf(valstr, "%llu", val64);
2512                                 } else {
2513                                         zfs_nicenum(val64, valstr,
2514                                             sizeof (valstr));
2515                                 }
2516                                 if (field == USFIELD_QUOTA &&
2517                                     strcmp(valstr, "0") == 0)
2518                                         strval = "none";
2519                                 else
2520                                         strval = valstr;
2521                         }
2522                         break;
2523                 }
2524
2525                 if (!first) {
2526                         if (scripted)
2527                                 (void) printf("\t");
2528                         else
2529                                 (void) printf("  ");
2530                 }
2531                 if (scripted)
2532                         (void) printf("%s", strval);
2533                 else if (field == USFIELD_TYPE || field == USFIELD_NAME)
2534                         (void) printf("%-*s", width[field], strval);
2535                 else
2536                         (void) printf("%*s", width[field], strval);
2537
2538                 first = B_FALSE;
2539                 cfield++;
2540         }
2541
2542         (void) printf("\n");
2543 }
2544
2545 static void
2546 print_us(boolean_t scripted, boolean_t parsable, int *fields, int types,
2547     size_t *width, boolean_t rmnode, uu_avl_t *avl)
2548 {
2549         us_node_t *node;
2550         const char *col;
2551         int cfield = 0;
2552         int field;
2553
2554         if (!scripted) {
2555                 boolean_t first = B_TRUE;
2556
2557                 while ((field = fields[cfield]) != USFIELD_LAST) {
2558                         col = gettext(us_field_hdr[field]);
2559                         if (field == USFIELD_TYPE || field == USFIELD_NAME) {
2560                                 (void) printf(first ? "%-*s" : "  %-*s",
2561                                     width[field], col);
2562                         } else {
2563                                 (void) printf(first ? "%*s" : "  %*s",
2564                                     width[field], col);
2565                         }
2566                         first = B_FALSE;
2567                         cfield++;
2568                 }
2569                 (void) printf("\n");
2570         }
2571
2572         for (node = uu_avl_first(avl); node; node = uu_avl_next(avl, node)) {
2573                 print_us_node(scripted, parsable, fields, types, width, node);
2574                 if (rmnode)
2575                         nvlist_free(node->usn_nvl);
2576         }
2577 }
2578
2579 static int
2580 zfs_do_userspace(int argc, char **argv)
2581 {
2582         zfs_handle_t *zhp;
2583         zfs_userquota_prop_t p;
2584
2585         uu_avl_pool_t *avl_pool;
2586         uu_avl_t *avl_tree;
2587         uu_avl_walk_t *walk;
2588         char *delim;
2589         char deffields[] = "type,name,used,quota";
2590         char *ofield = NULL;
2591         char *tfield = NULL;
2592         int cfield = 0;
2593         int fields[256];
2594         int i;
2595         boolean_t scripted = B_FALSE;
2596         boolean_t prtnum = B_FALSE;
2597         boolean_t parsable = B_FALSE;
2598         boolean_t sid2posix = B_FALSE;
2599         int ret = 0;
2600         int c;
2601         zfs_sort_column_t *sortcol = NULL;
2602         int types = USTYPE_PSX_USR | USTYPE_SMB_USR;
2603         us_cbdata_t cb;
2604         us_node_t *node;
2605         us_node_t *rmnode;
2606         uu_list_pool_t *listpool;
2607         uu_list_t *list;
2608         uu_avl_index_t idx = 0;
2609         uu_list_index_t idx2 = 0;
2610
2611         if (argc < 2)
2612                 usage(B_FALSE);
2613
2614         if (strcmp(argv[0], "groupspace") == 0)
2615                 /* Toggle default group types */
2616                 types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
2617
2618         while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
2619                 switch (c) {
2620                 case 'n':
2621                         prtnum = B_TRUE;
2622                         break;
2623                 case 'H':
2624                         scripted = B_TRUE;
2625                         break;
2626                 case 'p':
2627                         parsable = B_TRUE;
2628                         break;
2629                 case 'o':
2630                         ofield = optarg;
2631                         break;
2632                 case 's':
2633                 case 'S':
2634                         if (zfs_add_sort_column(&sortcol, optarg,
2635                             c == 's' ? B_FALSE : B_TRUE) != 0) {
2636                                 (void) fprintf(stderr,
2637                                     gettext("invalid field '%s'\n"), optarg);
2638                                 usage(B_FALSE);
2639                         }
2640                         break;
2641                 case 't':
2642                         tfield = optarg;
2643                         break;
2644                 case 'i':
2645                         sid2posix = B_TRUE;
2646                         break;
2647                 case ':':
2648                         (void) fprintf(stderr, gettext("missing argument for "
2649                             "'%c' option\n"), optopt);
2650                         usage(B_FALSE);
2651                         break;
2652                 case '?':
2653                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2654                             optopt);
2655                         usage(B_FALSE);
2656                 }
2657         }
2658
2659         argc -= optind;
2660         argv += optind;
2661
2662         if (argc < 1) {
2663                 (void) fprintf(stderr, gettext("missing dataset name\n"));
2664                 usage(B_FALSE);
2665         }
2666         if (argc > 1) {
2667                 (void) fprintf(stderr, gettext("too many arguments\n"));
2668                 usage(B_FALSE);
2669         }
2670
2671         /* Use default output fields if not specified using -o */
2672         if (ofield == NULL)
2673                 ofield = deffields;
2674         do {
2675                 if ((delim = strchr(ofield, ',')) != NULL)
2676                         *delim = '\0';
2677                 if ((fields[cfield++] = us_field_index(ofield)) == -1) {
2678                         (void) fprintf(stderr, gettext("invalid type '%s' "
2679                             "for -o option\n"), ofield);
2680                         return (-1);
2681                 }
2682                 if (delim != NULL)
2683                         ofield = delim + 1;
2684         } while (delim != NULL);
2685         fields[cfield] = USFIELD_LAST;
2686
2687         /* Override output types (-t option) */
2688         if (tfield != NULL) {
2689                 types = 0;
2690
2691                 do {
2692                         boolean_t found = B_FALSE;
2693
2694                         if ((delim = strchr(tfield, ',')) != NULL)
2695                                 *delim = '\0';
2696                         for (i = 0; i < sizeof (us_type_bits) / sizeof (int);
2697                             i++) {
2698                                 if (strcmp(tfield, us_type_names[i]) == 0) {
2699                                         found = B_TRUE;
2700                                         types |= us_type_bits[i];
2701                                         break;
2702                                 }
2703                         }
2704                         if (!found) {
2705                                 (void) fprintf(stderr, gettext("invalid type "
2706                                     "'%s' for -t option\n"), tfield);
2707                                 return (-1);
2708                         }
2709                         if (delim != NULL)
2710                                 tfield = delim + 1;
2711                 } while (delim != NULL);
2712         }
2713
2714         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
2715                 return (1);
2716
2717         if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
2718             offsetof(us_node_t, usn_avlnode), us_compare, UU_DEFAULT)) == NULL)
2719                 nomem();
2720         if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
2721                 nomem();
2722
2723         /* Always add default sorting columns */
2724         (void) zfs_add_sort_column(&sortcol, "type", B_FALSE);
2725         (void) zfs_add_sort_column(&sortcol, "name", B_FALSE);
2726
2727         cb.cb_sortcol = sortcol;
2728         cb.cb_numname = prtnum;
2729         cb.cb_nicenum = !parsable;
2730         cb.cb_avl_pool = avl_pool;
2731         cb.cb_avl = avl_tree;
2732         cb.cb_sid2posix = sid2posix;
2733
2734         for (i = 0; i < USFIELD_LAST; i++)
2735                 cb.cb_width[i] = strlen(gettext(us_field_hdr[i]));
2736
2737         for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
2738                 if (((p == ZFS_PROP_USERUSED || p == ZFS_PROP_USERQUOTA) &&
2739                     !(types & (USTYPE_PSX_USR | USTYPE_SMB_USR))) ||
2740                     ((p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA) &&
2741                     !(types & (USTYPE_PSX_GRP | USTYPE_SMB_GRP))))
2742                         continue;
2743                 cb.cb_prop = p;
2744                 if ((ret = zfs_userspace(zhp, p, userspace_cb, &cb)) != 0)
2745                         return (ret);
2746         }
2747
2748         /* Sort the list */
2749         if ((node = uu_avl_first(avl_tree)) == NULL)
2750                 return (0);
2751
2752         us_populated = B_TRUE;
2753
2754         listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
2755             offsetof(us_node_t, usn_listnode), NULL, UU_DEFAULT);
2756         list = uu_list_create(listpool, NULL, UU_DEFAULT);
2757         uu_list_node_init(node, &node->usn_listnode, listpool);
2758
2759         while (node != NULL) {
2760                 rmnode = node;
2761                 node = uu_avl_next(avl_tree, node);
2762                 uu_avl_remove(avl_tree, rmnode);
2763                 if (uu_list_find(list, rmnode, NULL, &idx2) == NULL)
2764                         uu_list_insert(list, rmnode, idx2);
2765         }
2766
2767         for (node = uu_list_first(list); node != NULL;
2768             node = uu_list_next(list, node)) {
2769                 us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
2770
2771                 if (uu_avl_find(avl_tree, node, &sortinfo, &idx) == NULL)
2772                         uu_avl_insert(avl_tree, node, idx);
2773         }
2774
2775         uu_list_destroy(list);
2776         uu_list_pool_destroy(listpool);
2777
2778         /* Print and free node nvlist memory */
2779         print_us(scripted, parsable, fields, types, cb.cb_width, B_TRUE,
2780             cb.cb_avl);
2781
2782         zfs_free_sort_columns(sortcol);
2783
2784         /* Clean up the AVL tree */
2785         if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
2786                 nomem();
2787
2788         while ((node = uu_avl_walk_next(walk)) != NULL) {
2789                 uu_avl_remove(cb.cb_avl, node);
2790                 free(node);
2791         }
2792
2793         uu_avl_walk_end(walk);
2794         uu_avl_destroy(avl_tree);
2795         uu_avl_pool_destroy(avl_pool);
2796
2797         return (ret);
2798 }
2799
2800 /*
2801  * list [-r][-d max] [-H] [-o property[,property]...] [-t type[,type]...]
2802  *      [-s property [-s property]...] [-S property [-S property]...]
2803  *      <dataset> ...
2804  *
2805  *      -r      Recurse over all children
2806  *      -d      Limit recursion by depth.
2807  *      -H      Scripted mode; elide headers and separate columns by tabs
2808  *      -o      Control which fields to display.
2809  *      -t      Control which object types to display.
2810  *      -s      Specify sort columns, descending order.
2811  *      -S      Specify sort columns, ascending order.
2812  *
2813  * When given no arguments, lists all filesystems in the system.
2814  * Otherwise, list the specified datasets, optionally recursing down them if
2815  * '-r' is specified.
2816  */
2817 typedef struct list_cbdata {
2818         boolean_t       cb_first;
2819         boolean_t       cb_scripted;
2820         zprop_list_t    *cb_proplist;
2821 } list_cbdata_t;
2822
2823 /*
2824  * Given a list of columns to display, output appropriate headers for each one.
2825  */
2826 static void
2827 print_header(zprop_list_t *pl)
2828 {
2829         char headerbuf[ZFS_MAXPROPLEN];
2830         const char *header;
2831         int i;
2832         boolean_t first = B_TRUE;
2833         boolean_t right_justify;
2834
2835         for (; pl != NULL; pl = pl->pl_next) {
2836                 if (!first) {
2837                         (void) printf("  ");
2838                 } else {
2839                         first = B_FALSE;
2840                 }
2841
2842                 right_justify = B_FALSE;
2843                 if (pl->pl_prop != ZPROP_INVAL) {
2844                         header = zfs_prop_column_name(pl->pl_prop);
2845                         right_justify = zfs_prop_align_right(pl->pl_prop);
2846                 } else {
2847                         for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
2848                                 headerbuf[i] = toupper(pl->pl_user_prop[i]);
2849                         headerbuf[i] = '\0';
2850                         header = headerbuf;
2851                 }
2852
2853                 if (pl->pl_next == NULL && !right_justify)
2854                         (void) printf("%s", header);
2855                 else if (right_justify)
2856                         (void) printf("%*s", pl->pl_width, header);
2857                 else
2858                         (void) printf("%-*s", pl->pl_width, header);
2859         }
2860
2861         (void) printf("\n");
2862 }
2863
2864 /*
2865  * Given a dataset and a list of fields, print out all the properties according
2866  * to the described layout.
2867  */
2868 static void
2869 print_dataset(zfs_handle_t *zhp, zprop_list_t *pl, boolean_t scripted)
2870 {
2871         boolean_t first = B_TRUE;
2872         char property[ZFS_MAXPROPLEN];
2873         nvlist_t *userprops = zfs_get_user_props(zhp);
2874         nvlist_t *propval;
2875         char *propstr;
2876         boolean_t right_justify;
2877         int width;
2878
2879         for (; pl != NULL; pl = pl->pl_next) {
2880                 if (!first) {
2881                         if (scripted)
2882                                 (void) printf("\t");
2883                         else
2884                                 (void) printf("  ");
2885                 } else {
2886                         first = B_FALSE;
2887                 }
2888
2889                 if (pl->pl_prop == ZFS_PROP_NAME) {
2890                         (void) strlcpy(property, zfs_get_name(zhp),
2891                             sizeof(property));
2892                         propstr = property;
2893                         right_justify = zfs_prop_align_right(pl->pl_prop);
2894                 } else if (pl->pl_prop != ZPROP_INVAL) {
2895                         if (zfs_prop_get(zhp, pl->pl_prop, property,
2896                             sizeof (property), NULL, NULL, 0, B_FALSE) != 0)
2897                                 propstr = "-";
2898                         else
2899                                 propstr = property;
2900
2901                         right_justify = zfs_prop_align_right(pl->pl_prop);
2902                 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
2903                         if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
2904                             property, sizeof (property), B_FALSE) != 0)
2905                                 propstr = "-";
2906                         else
2907                                 propstr = property;
2908                         right_justify = B_TRUE;
2909                 } else if (zfs_prop_written(pl->pl_user_prop)) {
2910                         if (zfs_prop_get_written(zhp, pl->pl_user_prop,
2911                             property, sizeof (property), B_FALSE) != 0)
2912                                 propstr = "-";
2913                         else
2914                                 propstr = property;
2915                         right_justify = B_TRUE;
2916                 } else {
2917                         if (nvlist_lookup_nvlist(userprops,
2918                             pl->pl_user_prop, &propval) != 0)
2919                                 propstr = "-";
2920                         else
2921                                 verify(nvlist_lookup_string(propval,
2922                                     ZPROP_VALUE, &propstr) == 0);
2923                         right_justify = B_FALSE;
2924                 }
2925
2926                 width = pl->pl_width;
2927
2928                 /*
2929                  * If this is being called in scripted mode, or if this is the
2930                  * last column and it is left-justified, don't include a width
2931                  * format specifier.
2932                  */
2933                 if (scripted || (pl->pl_next == NULL && !right_justify))
2934                         (void) printf("%s", propstr);
2935                 else if (right_justify)
2936                         (void) printf("%*s", width, propstr);
2937                 else
2938                         (void) printf("%-*s", width, propstr);
2939         }
2940
2941         (void) printf("\n");
2942 }
2943
2944 /*
2945  * Generic callback function to list a dataset or snapshot.
2946  */
2947 static int
2948 list_callback(zfs_handle_t *zhp, void *data)
2949 {
2950         list_cbdata_t *cbp = data;
2951
2952         if (cbp->cb_first) {
2953                 if (!cbp->cb_scripted)
2954                         print_header(cbp->cb_proplist);
2955                 cbp->cb_first = B_FALSE;
2956         }
2957
2958         print_dataset(zhp, cbp->cb_proplist, cbp->cb_scripted);
2959
2960         return (0);
2961 }
2962
2963 static int
2964 zfs_do_list(int argc, char **argv)
2965 {
2966         int c;
2967         boolean_t scripted = B_FALSE;
2968         static char default_fields[] =
2969             "name,used,available,referenced,mountpoint";
2970         int types = ZFS_TYPE_DATASET;
2971         boolean_t types_specified = B_FALSE;
2972         char *fields = NULL;
2973         list_cbdata_t cb = { 0 };
2974         char *value;
2975         int limit = 0;
2976         int ret = 0;
2977         zfs_sort_column_t *sortcol = NULL;
2978         int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
2979
2980         /* check options */
2981         while ((c = getopt(argc, argv, ":d:o:rt:Hs:S:")) != -1) {
2982                 switch (c) {
2983                 case 'o':
2984                         fields = optarg;
2985                         break;
2986                 case 'd':
2987                         limit = parse_depth(optarg, &flags);
2988                         break;
2989                 case 'r':
2990                         flags |= ZFS_ITER_RECURSE;
2991                         break;
2992                 case 'H':
2993                         scripted = B_TRUE;
2994                         break;
2995                 case 's':
2996                         if (zfs_add_sort_column(&sortcol, optarg,
2997                             B_FALSE) != 0) {
2998                                 (void) fprintf(stderr,
2999                                     gettext("invalid property '%s'\n"), optarg);
3000                                 usage(B_FALSE);
3001                         }
3002                         break;
3003                 case 'S':
3004                         if (zfs_add_sort_column(&sortcol, optarg,
3005                             B_TRUE) != 0) {
3006                                 (void) fprintf(stderr,
3007                                     gettext("invalid property '%s'\n"), optarg);
3008                                 usage(B_FALSE);
3009                         }
3010                         break;
3011                 case 't':
3012                         types = 0;
3013                         types_specified = B_TRUE;
3014                         flags &= ~ZFS_ITER_PROP_LISTSNAPS;
3015                         while (*optarg != '\0') {
3016                                 static char *type_subopts[] = { "filesystem",
3017                                     "volume", "snapshot", "snap", "all", NULL };
3018
3019                                 switch (getsubopt(&optarg, type_subopts,
3020                                     &value)) {
3021                                 case 0:
3022                                         types |= ZFS_TYPE_FILESYSTEM;
3023                                         break;
3024                                 case 1:
3025                                         types |= ZFS_TYPE_VOLUME;
3026                                         break;
3027                                 case 2:
3028                                 case 3:
3029                                         types |= ZFS_TYPE_SNAPSHOT;
3030                                         break;
3031                                 case 4:
3032                                         types = ZFS_TYPE_DATASET;
3033                                         break;
3034
3035                                 default:
3036                                         (void) fprintf(stderr,
3037                                             gettext("invalid type '%s'\n"),
3038                                             value);
3039                                         usage(B_FALSE);
3040                                 }
3041                         }
3042                         break;
3043                 case ':':
3044                         (void) fprintf(stderr, gettext("missing argument for "
3045                             "'%c' option\n"), optopt);
3046                         usage(B_FALSE);
3047                         break;
3048                 case '?':
3049                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3050                             optopt);
3051                         usage(B_FALSE);
3052                 }
3053         }
3054
3055         argc -= optind;
3056         argv += optind;
3057
3058         if (fields == NULL)
3059                 fields = default_fields;
3060
3061         /*
3062          * If we are only going to list snapshot names and sort by name,
3063          * then we can use faster version.
3064          */
3065         if (strcmp(fields, "name") == 0 && zfs_sort_only_by_name(sortcol))
3066                 flags |= ZFS_ITER_SIMPLE;
3067
3068         /*
3069          * If "-o space" and no types were specified, don't display snapshots.
3070          */
3071         if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3072                 types &= ~ZFS_TYPE_SNAPSHOT;
3073
3074         /*
3075          * If the user specifies '-o all', the zprop_get_list() doesn't
3076          * normally include the name of the dataset.  For 'zfs list', we always
3077          * want this property to be first.
3078          */
3079         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3080             != 0)
3081                 usage(B_FALSE);
3082
3083         cb.cb_scripted = scripted;
3084         cb.cb_first = B_TRUE;
3085
3086         ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
3087             limit, list_callback, &cb);
3088
3089         zprop_free_list(cb.cb_proplist);
3090         zfs_free_sort_columns(sortcol);
3091
3092         if (ret == 0 && cb.cb_first && !cb.cb_scripted)
3093                 (void) printf(gettext("no datasets available\n"));
3094
3095         return (ret);
3096 }
3097
3098 /*
3099  * zfs rename [-f] <fs | snap | vol> <fs | snap | vol>
3100  * zfs rename [-f] -p <fs | vol> <fs | vol>
3101  * zfs rename -r <snap> <snap>
3102  * zfs rename -u [-p] <fs> <fs>
3103  *
3104  * Renames the given dataset to another of the same type.
3105  *
3106  * The '-p' flag creates all the non-existing ancestors of the target first.
3107  */
3108 /* ARGSUSED */
3109 static int
3110 zfs_do_rename(int argc, char **argv)
3111 {
3112         zfs_handle_t *zhp;
3113         renameflags_t flags = { 0 };
3114         int c;
3115         int ret = 0;
3116         int types;
3117         boolean_t parents = B_FALSE;
3118         char *snapshot = NULL;
3119
3120         /* check options */
3121         while ((c = getopt(argc, argv, "fpru")) != -1) {
3122                 switch (c) {
3123                 case 'p':
3124                         parents = B_TRUE;
3125                         break;
3126                 case 'r':
3127                         flags.recurse = B_TRUE;
3128                         break;
3129                 case 'u':
3130                         flags.nounmount = B_TRUE;
3131                         break;
3132                 case 'f':
3133                         flags.forceunmount = B_TRUE;
3134                         break;
3135                 case '?':
3136                 default:
3137                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3138                             optopt);
3139                         usage(B_FALSE);
3140                 }
3141         }
3142
3143         argc -= optind;
3144         argv += optind;
3145
3146         /* check number of arguments */
3147         if (argc < 1) {
3148                 (void) fprintf(stderr, gettext("missing source dataset "
3149                     "argument\n"));
3150                 usage(B_FALSE);
3151         }
3152         if (argc < 2) {
3153                 (void) fprintf(stderr, gettext("missing target dataset "
3154                     "argument\n"));
3155                 usage(B_FALSE);
3156         }
3157         if (argc > 2) {
3158                 (void) fprintf(stderr, gettext("too many arguments\n"));
3159                 usage(B_FALSE);
3160         }
3161
3162         if (flags.recurse && parents) {
3163                 (void) fprintf(stderr, gettext("-p and -r options are mutually "
3164                     "exclusive\n"));
3165                 usage(B_FALSE);
3166         }
3167
3168         if (flags.recurse && strchr(argv[0], '@') == 0) {
3169                 (void) fprintf(stderr, gettext("source dataset for recursive "
3170                     "rename must be a snapshot\n"));
3171                 usage(B_FALSE);
3172         }
3173
3174         if (flags.nounmount && parents) {
3175                 (void) fprintf(stderr, gettext("-u and -r options are mutually "
3176                     "exclusive\n"));
3177                 usage(B_FALSE);
3178         }
3179
3180         if (flags.nounmount)
3181                 types = ZFS_TYPE_FILESYSTEM;
3182         else if (parents)
3183                 types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
3184         else
3185                 types = ZFS_TYPE_DATASET;
3186
3187         if (flags.recurse) {
3188                 /*
3189                  * When we do recursive rename we are fine when the given
3190                  * snapshot for the given dataset doesn't exist - it can
3191                  * still exists below.
3192                  */
3193
3194                 snapshot = strchr(argv[0], '@');
3195                 assert(snapshot != NULL);
3196                 *snapshot = '\0';
3197                 snapshot++;
3198         }
3199
3200         if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL)
3201                 return (1);
3202
3203         /* If we were asked and the name looks good, try to create ancestors. */
3204         if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
3205             zfs_create_ancestors(g_zfs, argv[1]) != 0) {
3206                 zfs_close(zhp);
3207                 return (1);
3208         }
3209
3210         ret = (zfs_rename(zhp, snapshot, argv[1], flags) != 0);
3211
3212         zfs_close(zhp);
3213         return (ret);
3214 }
3215
3216 /*
3217  * zfs promote <fs>
3218  *
3219  * Promotes the given clone fs to be the parent
3220  */
3221 /* ARGSUSED */
3222 static int
3223 zfs_do_promote(int argc, char **argv)
3224 {
3225         zfs_handle_t *zhp;
3226         int ret = 0;
3227
3228         /* check options */
3229         if (argc > 1 && argv[1][0] == '-') {
3230                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3231                     argv[1][1]);
3232                 usage(B_FALSE);
3233         }
3234
3235         /* check number of arguments */
3236         if (argc < 2) {
3237                 (void) fprintf(stderr, gettext("missing clone filesystem"
3238                     " argument\n"));
3239                 usage(B_FALSE);
3240         }
3241         if (argc > 2) {
3242                 (void) fprintf(stderr, gettext("too many arguments\n"));
3243                 usage(B_FALSE);
3244         }
3245
3246         zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3247         if (zhp == NULL)
3248                 return (1);
3249
3250         ret = (zfs_promote(zhp) != 0);
3251
3252
3253         zfs_close(zhp);
3254         return (ret);
3255 }
3256
3257 /*
3258  * zfs rollback [-rRf] <snapshot>
3259  *
3260  *      -r      Delete any intervening snapshots before doing rollback
3261  *      -R      Delete any snapshots and their clones
3262  *      -f      ignored for backwards compatability
3263  *
3264  * Given a filesystem, rollback to a specific snapshot, discarding any changes
3265  * since then and making it the active dataset.  If more recent snapshots exist,
3266  * the command will complain unless the '-r' flag is given.
3267  */
3268 typedef struct rollback_cbdata {
3269         uint64_t        cb_create;
3270         boolean_t       cb_first;
3271         int             cb_doclones;
3272         char            *cb_target;
3273         int             cb_error;
3274         boolean_t       cb_recurse;
3275         boolean_t       cb_dependent;
3276 } rollback_cbdata_t;
3277
3278 /*
3279  * Report any snapshots more recent than the one specified.  Used when '-r' is
3280  * not specified.  We reuse this same callback for the snapshot dependents - if
3281  * 'cb_dependent' is set, then this is a dependent and we should report it
3282  * without checking the transaction group.
3283  */
3284 static int
3285 rollback_check(zfs_handle_t *zhp, void *data)
3286 {
3287         rollback_cbdata_t *cbp = data;
3288
3289         if (cbp->cb_doclones) {
3290                 zfs_close(zhp);
3291                 return (0);
3292         }
3293
3294         if (!cbp->cb_dependent) {
3295                 if (strcmp(zfs_get_name(zhp), cbp->cb_target) != 0 &&
3296                     zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
3297                     zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
3298                     cbp->cb_create) {
3299
3300                         if (cbp->cb_first && !cbp->cb_recurse) {
3301                                 (void) fprintf(stderr, gettext("cannot "
3302                                     "rollback to '%s': more recent snapshots "
3303                                     "exist\n"),
3304                                     cbp->cb_target);
3305                                 (void) fprintf(stderr, gettext("use '-r' to "
3306                                     "force deletion of the following "
3307                                     "snapshots:\n"));
3308                                 cbp->cb_first = 0;
3309                                 cbp->cb_error = 1;
3310                         }
3311
3312                         if (cbp->cb_recurse) {
3313                                 cbp->cb_dependent = B_TRUE;
3314                                 if (zfs_iter_dependents(zhp, B_TRUE,
3315                                     rollback_check, cbp) != 0) {
3316                                         zfs_close(zhp);
3317                                         return (-1);
3318                                 }
3319                                 cbp->cb_dependent = B_FALSE;
3320                         } else {
3321                                 (void) fprintf(stderr, "%s\n",
3322                                     zfs_get_name(zhp));
3323                         }
3324                 }
3325         } else {
3326                 if (cbp->cb_first && cbp->cb_recurse) {
3327                         (void) fprintf(stderr, gettext("cannot rollback to "
3328                             "'%s': clones of previous snapshots exist\n"),
3329                             cbp->cb_target);
3330                         (void) fprintf(stderr, gettext("use '-R' to "
3331                             "force deletion of the following clones and "
3332                             "dependents:\n"));
3333                         cbp->cb_first = 0;
3334                         cbp->cb_error = 1;
3335                 }
3336
3337                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
3338         }
3339
3340         zfs_close(zhp);
3341         return (0);
3342 }
3343
3344 static int
3345 zfs_do_rollback(int argc, char **argv)
3346 {
3347         int ret = 0;
3348         int c;
3349         boolean_t force = B_FALSE;
3350         rollback_cbdata_t cb = { 0 };
3351         zfs_handle_t *zhp, *snap;
3352         char parentname[ZFS_MAXNAMELEN];
3353         char *delim;
3354
3355         /* check options */
3356         while ((c = getopt(argc, argv, "rRf")) != -1) {
3357                 switch (c) {
3358                 case 'r':
3359                         cb.cb_recurse = 1;
3360                         break;
3361                 case 'R':
3362                         cb.cb_recurse = 1;
3363                         cb.cb_doclones = 1;
3364                         break;
3365                 case 'f':
3366                         force = B_TRUE;
3367                         break;
3368                 case '?':
3369                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3370                             optopt);
3371                         usage(B_FALSE);
3372                 }
3373         }
3374
3375         argc -= optind;
3376         argv += optind;
3377
3378         /* check number of arguments */
3379         if (argc < 1) {
3380                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
3381                 usage(B_FALSE);
3382         }
3383         if (argc > 1) {
3384                 (void) fprintf(stderr, gettext("too many arguments\n"));
3385                 usage(B_FALSE);
3386         }
3387
3388         /* open the snapshot */
3389         if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
3390                 return (1);
3391
3392         /* open the parent dataset */
3393         (void) strlcpy(parentname, argv[0], sizeof (parentname));
3394         verify((delim = strrchr(parentname, '@')) != NULL);
3395         *delim = '\0';
3396         if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
3397                 zfs_close(snap);
3398                 return (1);
3399         }
3400
3401         /*
3402          * Check for more recent snapshots and/or clones based on the presence
3403          * of '-r' and '-R'.
3404          */
3405         cb.cb_target = argv[0];
3406         cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3407         cb.cb_first = B_TRUE;
3408         cb.cb_error = 0;
3409         if ((ret = zfs_iter_children(zhp, rollback_check, &cb)) != 0)
3410                 goto out;
3411
3412         if ((ret = cb.cb_error) != 0)
3413                 goto out;
3414
3415         /*
3416          * Rollback parent to the given snapshot.
3417          */
3418         ret = zfs_rollback(zhp, snap, force);
3419
3420 out:
3421         zfs_close(snap);
3422         zfs_close(zhp);
3423
3424         if (ret == 0)
3425                 return (0);
3426         else
3427                 return (1);
3428 }
3429
3430 /*
3431  * zfs set property=value { fs | snap | vol } ...
3432  *
3433  * Sets the given property for all datasets specified on the command line.
3434  */
3435 typedef struct set_cbdata {
3436         char            *cb_propname;
3437         char            *cb_value;
3438 } set_cbdata_t;
3439
3440 static int
3441 set_callback(zfs_handle_t *zhp, void *data)
3442 {
3443         set_cbdata_t *cbp = data;
3444
3445         if (zfs_prop_set(zhp, cbp->cb_propname, cbp->cb_value) != 0) {
3446                 switch (libzfs_errno(g_zfs)) {
3447                 case EZFS_MOUNTFAILED:
3448                         (void) fprintf(stderr, gettext("property may be set "
3449                             "but unable to remount filesystem\n"));
3450                         break;
3451                 case EZFS_SHARENFSFAILED:
3452                         (void) fprintf(stderr, gettext("property may be set "
3453                             "but unable to reshare filesystem\n"));
3454                         break;
3455                 }
3456                 return (1);
3457         }
3458         return (0);
3459 }
3460
3461 static int
3462 zfs_do_set(int argc, char **argv)
3463 {
3464         set_cbdata_t cb;
3465         int ret = 0;
3466
3467         /* check for options */
3468         if (argc > 1 && argv[1][0] == '-') {
3469                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3470                     argv[1][1]);
3471                 usage(B_FALSE);
3472         }
3473
3474         /* check number of arguments */
3475         if (argc < 2) {
3476                 (void) fprintf(stderr, gettext("missing property=value "
3477                     "argument\n"));
3478                 usage(B_FALSE);
3479         }
3480         if (argc < 3) {
3481                 (void) fprintf(stderr, gettext("missing dataset name\n"));
3482                 usage(B_FALSE);
3483         }
3484
3485         /* validate property=value argument */
3486         cb.cb_propname = argv[1];
3487         if (((cb.cb_value = strchr(cb.cb_propname, '=')) == NULL) ||
3488             (cb.cb_value[1] == '\0')) {
3489                 (void) fprintf(stderr, gettext("missing value in "
3490                     "property=value argument\n"));
3491                 usage(B_FALSE);
3492         }
3493
3494         *cb.cb_value = '\0';
3495         cb.cb_value++;
3496
3497         if (*cb.cb_propname == '\0') {
3498                 (void) fprintf(stderr,
3499                     gettext("missing property in property=value argument\n"));
3500                 usage(B_FALSE);
3501         }
3502
3503         ret = zfs_for_each(argc - 2, argv + 2, 0,
3504             ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, &cb);
3505
3506         return (ret);
3507 }
3508
3509 typedef struct snap_cbdata {
3510         nvlist_t *sd_nvl;
3511         boolean_t sd_recursive;
3512         const char *sd_snapname;
3513 } snap_cbdata_t;
3514
3515 static int
3516 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
3517 {
3518         snap_cbdata_t *sd = arg;
3519         char *name;
3520         int rv = 0;
3521         int error;
3522
3523         if (sd->sd_recursive &&
3524             zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
3525                 zfs_close(zhp);
3526                 return (0);
3527         }
3528
3529         error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
3530         if (error == -1)
3531                 nomem();
3532         fnvlist_add_boolean(sd->sd_nvl, name);
3533         free(name);
3534
3535         if (sd->sd_recursive)
3536                 rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
3537         zfs_close(zhp);
3538         return (rv);
3539 }
3540
3541 /*
3542  * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
3543  *
3544  * Creates a snapshot with the given name.  While functionally equivalent to
3545  * 'zfs create', it is a separate command to differentiate intent.
3546  */
3547 static int
3548 zfs_do_snapshot(int argc, char **argv)
3549 {
3550         int ret = 0;
3551         char c;
3552         nvlist_t *props;
3553         snap_cbdata_t sd = { 0 };
3554         boolean_t multiple_snaps = B_FALSE;
3555
3556         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3557                 nomem();
3558         if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
3559                 nomem();
3560
3561         /* check options */
3562         while ((c = getopt(argc, argv, "ro:")) != -1) {
3563                 switch (c) {
3564                 case 'o':
3565                         if (parseprop(props))
3566                                 return (1);
3567                         break;
3568                 case 'r':
3569                         sd.sd_recursive = B_TRUE;
3570                         multiple_snaps = B_TRUE;
3571                         break;
3572                 case '?':
3573                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3574                             optopt);
3575                         goto usage;
3576                 }
3577         }
3578
3579         argc -= optind;
3580         argv += optind;
3581
3582         /* check number of arguments */
3583         if (argc < 1) {
3584                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3585                 goto usage;
3586         }
3587
3588         if (argc > 1)
3589                 multiple_snaps = B_TRUE;
3590         for (; argc > 0; argc--, argv++) {
3591                 char *atp;
3592                 zfs_handle_t *zhp;
3593
3594                 atp = strchr(argv[0], '@');
3595                 if (atp == NULL)
3596                         goto usage;
3597                 *atp = '\0';
3598                 sd.sd_snapname = atp + 1;
3599                 zhp = zfs_open(g_zfs, argv[0],
3600                     ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3601                 if (zhp == NULL)
3602                         goto usage;
3603                 if (zfs_snapshot_cb(zhp, &sd) != 0)
3604                         goto usage;
3605         }
3606
3607         ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
3608         nvlist_free(sd.sd_nvl);
3609         nvlist_free(props);
3610         if (ret != 0 && multiple_snaps)
3611                 (void) fprintf(stderr, gettext("no snapshots were created\n"));
3612         return (ret != 0);
3613
3614 usage:
3615         nvlist_free(sd.sd_nvl);
3616         nvlist_free(props);
3617         usage(B_FALSE);
3618         return (-1);
3619 }
3620
3621 /*
3622  * Send a backup stream to stdout.
3623  */
3624 static int
3625 zfs_do_send(int argc, char **argv)
3626 {
3627         char *fromname = NULL;
3628         char *toname = NULL;
3629         char *cp;
3630         zfs_handle_t *zhp;
3631         sendflags_t flags = { 0 };
3632         int c, err;
3633         nvlist_t *dbgnv = NULL;
3634         boolean_t extraverbose = B_FALSE;
3635
3636         /* check options */
3637         while ((c = getopt(argc, argv, ":i:I:RDpvnP")) != -1) {
3638                 switch (c) {
3639                 case 'i':
3640                         if (fromname)
3641                                 usage(B_FALSE);
3642                         fromname = optarg;
3643                         break;
3644                 case 'I':
3645                         if (fromname)
3646                                 usage(B_FALSE);
3647                         fromname = optarg;
3648                         flags.doall = B_TRUE;
3649                         break;
3650                 case 'R':
3651                         flags.replicate = B_TRUE;
3652                         break;
3653                 case 'p':
3654                         flags.props = B_TRUE;
3655                         break;
3656                 case 'P':
3657                         flags.parsable = B_TRUE;
3658                         flags.verbose = B_TRUE;
3659                         break;
3660                 case 'v':
3661                         if (flags.verbose)
3662                                 extraverbose = B_TRUE;
3663                         flags.verbose = B_TRUE;
3664                         flags.progress = B_TRUE;
3665                         break;
3666                 case 'D':
3667                         flags.dedup = B_TRUE;
3668                         break;
3669                 case 'n':
3670                         flags.dryrun = B_TRUE;
3671                         break;
3672                 case ':':
3673                         (void) fprintf(stderr, gettext("missing argument for "
3674                             "'%c' option\n"), optopt);
3675                         usage(B_FALSE);
3676                         break;
3677                 case '?':
3678                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3679                             optopt);
3680                         usage(B_FALSE);
3681                 }
3682         }
3683
3684         argc -= optind;
3685         argv += optind;
3686
3687         /* check number of arguments */
3688         if (argc < 1) {
3689                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3690                 usage(B_FALSE);
3691         }
3692         if (argc > 1) {
3693                 (void) fprintf(stderr, gettext("too many arguments\n"));
3694                 usage(B_FALSE);
3695         }
3696
3697         if (!flags.dryrun && isatty(STDOUT_FILENO)) {
3698                 (void) fprintf(stderr,
3699                     gettext("Error: Stream can not be written to a terminal.\n"
3700                     "You must redirect standard output.\n"));
3701                 return (1);
3702         }
3703
3704         cp = strchr(argv[0], '@');
3705         if (cp == NULL) {
3706                 (void) fprintf(stderr,
3707                     gettext("argument must be a snapshot\n"));
3708                 usage(B_FALSE);
3709         }
3710         *cp = '\0';
3711         toname = cp + 1;
3712         zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3713         if (zhp == NULL)
3714                 return (1);
3715
3716         /*
3717          * If they specified the full path to the snapshot, chop off
3718          * everything except the short name of the snapshot, but special
3719          * case if they specify the origin.
3720          */
3721         if (fromname && (cp = strchr(fromname, '@')) != NULL) {
3722                 char origin[ZFS_MAXNAMELEN];
3723                 zprop_source_t src;
3724
3725                 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
3726                     origin, sizeof (origin), &src, NULL, 0, B_FALSE);
3727
3728                 if (strcmp(origin, fromname) == 0) {
3729                         fromname = NULL;
3730                         flags.fromorigin = B_TRUE;
3731                 } else {
3732                         *cp = '\0';
3733                         if (cp != fromname && strcmp(argv[0], fromname)) {
3734                                 (void) fprintf(stderr,
3735                                     gettext("incremental source must be "
3736                                     "in same filesystem\n"));
3737                                 usage(B_FALSE);
3738                         }
3739                         fromname = cp + 1;
3740                         if (strchr(fromname, '@') || strchr(fromname, '/')) {
3741                                 (void) fprintf(stderr,
3742                                     gettext("invalid incremental source\n"));
3743                                 usage(B_FALSE);
3744                         }
3745                 }
3746         }
3747
3748         if (flags.replicate && fromname == NULL)
3749                 flags.doall = B_TRUE;
3750
3751         err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
3752             extraverbose ? &dbgnv : NULL);
3753
3754         if (extraverbose && dbgnv != NULL) {
3755                 /*
3756                  * dump_nvlist prints to stdout, but that's been
3757                  * redirected to a file.  Make it print to stderr
3758                  * instead.
3759                  */
3760                 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
3761                 dump_nvlist(dbgnv, 0);
3762                 nvlist_free(dbgnv);
3763         }
3764         zfs_close(zhp);
3765
3766         return (err != 0);
3767 }
3768
3769 /*
3770  * zfs receive [-vnFu] [-d | -e] <fs@snap>
3771  *
3772  * Restore a backup stream from stdin.
3773  */
3774 static int
3775 zfs_do_receive(int argc, char **argv)
3776 {
3777         int c, err;
3778         recvflags_t flags = { 0 };
3779
3780         /* check options */
3781         while ((c = getopt(argc, argv, ":denuvF")) != -1) {
3782                 switch (c) {
3783                 case 'd':
3784                         flags.isprefix = B_TRUE;
3785                         break;
3786                 case 'e':
3787                         flags.isprefix = B_TRUE;
3788                         flags.istail = B_TRUE;
3789                         break;
3790                 case 'n':
3791                         flags.dryrun = B_TRUE;
3792                         break;
3793                 case 'u':
3794                         flags.nomount = B_TRUE;
3795                         break;
3796                 case 'v':
3797                         flags.verbose = B_TRUE;
3798                         break;
3799                 case 'F':
3800                         flags.force = B_TRUE;
3801                         break;
3802                 case ':':
3803                         (void) fprintf(stderr, gettext("missing argument for "
3804                             "'%c' option\n"), optopt);
3805                         usage(B_FALSE);
3806                         break;
3807                 case '?':
3808                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3809                             optopt);
3810                         usage(B_FALSE);
3811                 }
3812         }
3813
3814         argc -= optind;
3815         argv += optind;
3816
3817         /* check number of arguments */
3818         if (argc < 1) {
3819                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3820                 usage(B_FALSE);
3821         }
3822         if (argc > 1) {
3823                 (void) fprintf(stderr, gettext("too many arguments\n"));
3824                 usage(B_FALSE);
3825         }
3826
3827         if (isatty(STDIN_FILENO)) {
3828                 (void) fprintf(stderr,
3829                     gettext("Error: Backup stream can not be read "
3830                     "from a terminal.\n"
3831                     "You must redirect standard input.\n"));
3832                 return (1);
3833         }
3834
3835         err = zfs_receive(g_zfs, argv[0], &flags, STDIN_FILENO, NULL);
3836
3837         return (err != 0);
3838 }
3839
3840 /*
3841  * allow/unallow stuff
3842  */
3843 /* copied from zfs/sys/dsl_deleg.h */
3844 #define ZFS_DELEG_PERM_CREATE           "create"
3845 #define ZFS_DELEG_PERM_DESTROY          "destroy"
3846 #define ZFS_DELEG_PERM_SNAPSHOT         "snapshot"
3847 #define ZFS_DELEG_PERM_ROLLBACK         "rollback"
3848 #define ZFS_DELEG_PERM_CLONE            "clone"
3849 #define ZFS_DELEG_PERM_PROMOTE          "promote"
3850 #define ZFS_DELEG_PERM_RENAME           "rename"
3851 #define ZFS_DELEG_PERM_MOUNT            "mount"
3852 #define ZFS_DELEG_PERM_SHARE            "share"
3853 #define ZFS_DELEG_PERM_SEND             "send"
3854 #define ZFS_DELEG_PERM_RECEIVE          "receive"
3855 #define ZFS_DELEG_PERM_ALLOW            "allow"
3856 #define ZFS_DELEG_PERM_USERPROP         "userprop"
3857 #define ZFS_DELEG_PERM_VSCAN            "vscan" /* ??? */
3858 #define ZFS_DELEG_PERM_USERQUOTA        "userquota"
3859 #define ZFS_DELEG_PERM_GROUPQUOTA       "groupquota"
3860 #define ZFS_DELEG_PERM_USERUSED         "userused"
3861 #define ZFS_DELEG_PERM_GROUPUSED        "groupused"
3862 #define ZFS_DELEG_PERM_HOLD             "hold"
3863 #define ZFS_DELEG_PERM_RELEASE          "release"
3864 #define ZFS_DELEG_PERM_DIFF             "diff"
3865
3866 #define ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
3867
3868 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
3869         { ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
3870         { ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
3871         { ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
3872         { ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
3873         { ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
3874         { ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
3875         { ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
3876         { ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
3877         { ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
3878         { ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
3879         { ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
3880         { ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
3881         { ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
3882         { ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
3883         { ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
3884
3885         { ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
3886         { ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
3887         { ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
3888         { ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
3889         { ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
3890         { NULL, ZFS_DELEG_NOTE_NONE }
3891 };
3892
3893 /* permission structure */
3894 typedef struct deleg_perm {
3895         zfs_deleg_who_type_t    dp_who_type;
3896         const char              *dp_name;
3897         boolean_t               dp_local;
3898         boolean_t               dp_descend;
3899 } deleg_perm_t;
3900
3901 /* */
3902 typedef struct deleg_perm_node {
3903         deleg_perm_t            dpn_perm;
3904
3905         uu_avl_node_t           dpn_avl_node;
3906 } deleg_perm_node_t;
3907
3908 typedef struct fs_perm fs_perm_t;
3909
3910 /* permissions set */
3911 typedef struct who_perm {
3912         zfs_deleg_who_type_t    who_type;
3913         const char              *who_name;              /* id */
3914         char                    who_ug_name[256];       /* user/group name */
3915         fs_perm_t               *who_fsperm;            /* uplink */
3916
3917         uu_avl_t                *who_deleg_perm_avl;    /* permissions */
3918 } who_perm_t;
3919
3920 /* */
3921 typedef struct who_perm_node {
3922         who_perm_t      who_perm;
3923         uu_avl_node_t   who_avl_node;
3924 } who_perm_node_t;
3925
3926 typedef struct fs_perm_set fs_perm_set_t;
3927 /* fs permissions */
3928 struct fs_perm {
3929         const char              *fsp_name;
3930
3931         uu_avl_t                *fsp_sc_avl;    /* sets,create */
3932         uu_avl_t                *fsp_uge_avl;   /* user,group,everyone */
3933
3934         fs_perm_set_t           *fsp_set;       /* uplink */
3935 };
3936
3937 /* */
3938 typedef struct fs_perm_node {
3939         fs_perm_t       fspn_fsperm;
3940         uu_avl_t        *fspn_avl;
3941
3942         uu_list_node_t  fspn_list_node;
3943 } fs_perm_node_t;
3944
3945 /* top level structure */
3946 struct fs_perm_set {
3947         uu_list_pool_t  *fsps_list_pool;
3948         uu_list_t       *fsps_list; /* list of fs_perms */
3949
3950         uu_avl_pool_t   *fsps_named_set_avl_pool;
3951         uu_avl_pool_t   *fsps_who_perm_avl_pool;
3952         uu_avl_pool_t   *fsps_deleg_perm_avl_pool;
3953 };
3954
3955 static inline const char *
3956 deleg_perm_type(zfs_deleg_note_t note)
3957 {
3958         /* subcommands */
3959         switch (note) {
3960                 /* SUBCOMMANDS */
3961                 /* OTHER */
3962         case ZFS_DELEG_NOTE_GROUPQUOTA:
3963         case ZFS_DELEG_NOTE_GROUPUSED:
3964         case ZFS_DELEG_NOTE_USERPROP:
3965         case ZFS_DELEG_NOTE_USERQUOTA:
3966         case ZFS_DELEG_NOTE_USERUSED:
3967                 /* other */
3968                 return (gettext("other"));
3969         default:
3970                 return (gettext("subcommand"));
3971         }
3972 }
3973
3974 static int inline
3975 who_type2weight(zfs_deleg_who_type_t who_type)
3976 {
3977         int res;
3978         switch (who_type) {
3979                 case ZFS_DELEG_NAMED_SET_SETS:
3980                 case ZFS_DELEG_NAMED_SET:
3981                         res = 0;
3982                         break;
3983                 case ZFS_DELEG_CREATE_SETS:
3984                 case ZFS_DELEG_CREATE:
3985                         res = 1;
3986                         break;
3987                 case ZFS_DELEG_USER_SETS:
3988                 case ZFS_DELEG_USER:
3989                         res = 2;
3990                         break;
3991                 case ZFS_DELEG_GROUP_SETS:
3992                 case ZFS_DELEG_GROUP:
3993                         res = 3;
3994                         break;
3995                 case ZFS_DELEG_EVERYONE_SETS:
3996                 case ZFS_DELEG_EVERYONE:
3997                         res = 4;
3998                         break;
3999                 default:
4000                         res = -1;
4001         }
4002
4003         return (res);
4004 }
4005
4006 /* ARGSUSED */
4007 static int
4008 who_perm_compare(const void *larg, const void *rarg, void *unused)
4009 {
4010         const who_perm_node_t *l = larg;
4011         const who_perm_node_t *r = rarg;
4012         zfs_deleg_who_type_t ltype = l->who_perm.who_type;
4013         zfs_deleg_who_type_t rtype = r->who_perm.who_type;
4014         int lweight = who_type2weight(ltype);
4015         int rweight = who_type2weight(rtype);
4016         int res = lweight - rweight;
4017         if (res == 0)
4018                 res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
4019                     ZFS_MAX_DELEG_NAME-1);
4020
4021         if (res == 0)
4022                 return (0);
4023         if (res > 0)
4024                 return (1);
4025         else
4026                 return (-1);
4027 }
4028
4029 /* ARGSUSED */
4030 static int
4031 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
4032 {
4033         const deleg_perm_node_t *l = larg;
4034         const deleg_perm_node_t *r = rarg;
4035         int res =  strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
4036             ZFS_MAX_DELEG_NAME-1);
4037
4038         if (res == 0)
4039                 return (0);
4040
4041         if (res > 0)
4042                 return (1);
4043         else
4044                 return (-1);
4045 }
4046
4047 static inline void
4048 fs_perm_set_init(fs_perm_set_t *fspset)
4049 {
4050         bzero(fspset, sizeof (fs_perm_set_t));
4051
4052         if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
4053             sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
4054             NULL, UU_DEFAULT)) == NULL)
4055                 nomem();
4056         if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
4057             UU_DEFAULT)) == NULL)
4058                 nomem();
4059
4060         if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
4061             "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
4062             who_perm_node_t, who_avl_node), who_perm_compare,
4063             UU_DEFAULT)) == NULL)
4064                 nomem();
4065
4066         if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
4067             "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
4068             who_perm_node_t, who_avl_node), who_perm_compare,
4069             UU_DEFAULT)) == NULL)
4070                 nomem();
4071
4072         if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
4073             "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
4074             deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
4075             == NULL)
4076                 nomem();
4077 }
4078
4079 static inline void fs_perm_fini(fs_perm_t *);
4080 static inline void who_perm_fini(who_perm_t *);
4081
4082 static inline void
4083 fs_perm_set_fini(fs_perm_set_t *fspset)
4084 {
4085         fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
4086
4087         while (node != NULL) {
4088                 fs_perm_node_t *next_node =
4089                     uu_list_next(fspset->fsps_list, node);
4090                 fs_perm_t *fsperm = &node->fspn_fsperm;
4091                 fs_perm_fini(fsperm);
4092                 uu_list_remove(fspset->fsps_list, node);
4093                 free(node);
4094                 node = next_node;
4095         }
4096
4097         uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
4098         uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
4099         uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
4100 }
4101
4102 static inline void
4103 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
4104     const char *name)
4105 {
4106         deleg_perm->dp_who_type = type;
4107         deleg_perm->dp_name = name;
4108 }
4109
4110 static inline void
4111 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
4112     zfs_deleg_who_type_t type, const char *name)
4113 {
4114         uu_avl_pool_t   *pool;
4115         pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
4116
4117         bzero(who_perm, sizeof (who_perm_t));
4118
4119         if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
4120             UU_DEFAULT)) == NULL)
4121                 nomem();
4122
4123         who_perm->who_type = type;
4124         who_perm->who_name = name;
4125         who_perm->who_fsperm = fsperm;
4126 }
4127
4128 static inline void
4129 who_perm_fini(who_perm_t *who_perm)
4130 {
4131         deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
4132
4133         while (node != NULL) {
4134                 deleg_perm_node_t *next_node =
4135                     uu_avl_next(who_perm->who_deleg_perm_avl, node);
4136
4137                 uu_avl_remove(who_perm->who_deleg_perm_avl, node);
4138                 free(node);
4139                 node = next_node;
4140         }
4141
4142         uu_avl_destroy(who_perm->who_deleg_perm_avl);
4143 }
4144
4145 static inline void
4146 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
4147 {
4148         uu_avl_pool_t   *nset_pool = fspset->fsps_named_set_avl_pool;
4149         uu_avl_pool_t   *who_pool = fspset->fsps_who_perm_avl_pool;
4150
4151         bzero(fsperm, sizeof (fs_perm_t));
4152
4153         if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
4154             == NULL)
4155                 nomem();
4156
4157         if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
4158             == NULL)
4159                 nomem();
4160
4161         fsperm->fsp_set = fspset;
4162         fsperm->fsp_name = fsname;
4163 }
4164
4165 static inline void
4166 fs_perm_fini(fs_perm_t *fsperm)
4167 {
4168         who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
4169         while (node != NULL) {
4170                 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
4171                     node);
4172                 who_perm_t *who_perm = &node->who_perm;
4173                 who_perm_fini(who_perm);
4174                 uu_avl_remove(fsperm->fsp_sc_avl, node);
4175                 free(node);
4176                 node = next_node;
4177         }
4178
4179         node = uu_avl_first(fsperm->fsp_uge_avl);
4180         while (node != NULL) {
4181                 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
4182                     node);
4183                 who_perm_t *who_perm = &node->who_perm;
4184                 who_perm_fini(who_perm);
4185                 uu_avl_remove(fsperm->fsp_uge_avl, node);
4186                 free(node);
4187                 node = next_node;
4188         }
4189
4190         uu_avl_destroy(fsperm->fsp_sc_avl);
4191         uu_avl_destroy(fsperm->fsp_uge_avl);
4192 }
4193
4194 static void inline
4195 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
4196     zfs_deleg_who_type_t who_type, const char *name, char locality)
4197 {
4198         uu_avl_index_t idx = 0;
4199
4200         deleg_perm_node_t *found_node = NULL;
4201         deleg_perm_t    *deleg_perm = &node->dpn_perm;
4202
4203         deleg_perm_init(deleg_perm, who_type, name);
4204
4205         if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4206             == NULL)
4207                 uu_avl_insert(avl, node, idx);
4208         else {
4209                 node = found_node;
4210                 deleg_perm = &node->dpn_perm;
4211         }
4212
4213
4214         switch (locality) {
4215         case ZFS_DELEG_LOCAL:
4216                 deleg_perm->dp_local = B_TRUE;
4217                 break;
4218         case ZFS_DELEG_DESCENDENT:
4219                 deleg_perm->dp_descend = B_TRUE;
4220                 break;
4221         case ZFS_DELEG_NA:
4222                 break;
4223         default:
4224                 assert(B_FALSE); /* invalid locality */
4225         }
4226 }
4227
4228 static inline int
4229 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
4230 {
4231         nvpair_t *nvp = NULL;
4232         fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
4233         uu_avl_t *avl = who_perm->who_deleg_perm_avl;
4234         zfs_deleg_who_type_t who_type = who_perm->who_type;
4235
4236         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4237                 const char *name = nvpair_name(nvp);
4238                 data_type_t type = nvpair_type(nvp);
4239                 uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
4240                 deleg_perm_node_t *node =
4241                     safe_malloc(sizeof (deleg_perm_node_t));
4242
4243                 assert(type == DATA_TYPE_BOOLEAN);
4244
4245                 uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
4246                 set_deleg_perm_node(avl, node, who_type, name, locality);
4247         }
4248
4249         return (0);
4250 }
4251
4252 static inline int
4253 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
4254 {
4255         nvpair_t *nvp = NULL;
4256         fs_perm_set_t *fspset = fsperm->fsp_set;
4257
4258         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4259                 nvlist_t *nvl2 = NULL;
4260                 const char *name = nvpair_name(nvp);
4261                 uu_avl_t *avl = NULL;
4262                 uu_avl_pool_t *avl_pool;
4263                 zfs_deleg_who_type_t perm_type = name[0];
4264                 char perm_locality = name[1];
4265                 const char *perm_name = name + 3;
4266                 boolean_t is_set = B_TRUE;
4267                 who_perm_t *who_perm = NULL;
4268
4269                 assert('$' == name[2]);
4270
4271                 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4272                         return (-1);
4273
4274                 switch (perm_type) {
4275                 case ZFS_DELEG_CREATE:
4276                 case ZFS_DELEG_CREATE_SETS:
4277                 case ZFS_DELEG_NAMED_SET:
4278                 case ZFS_DELEG_NAMED_SET_SETS:
4279                         avl_pool = fspset->fsps_named_set_avl_pool;
4280                         avl = fsperm->fsp_sc_avl;
4281                         break;
4282                 case ZFS_DELEG_USER:
4283                 case ZFS_DELEG_USER_SETS:
4284                 case ZFS_DELEG_GROUP:
4285                 case ZFS_DELEG_GROUP_SETS:
4286                 case ZFS_DELEG_EVERYONE:
4287                 case ZFS_DELEG_EVERYONE_SETS:
4288                         avl_pool = fspset->fsps_who_perm_avl_pool;
4289                         avl = fsperm->fsp_uge_avl;
4290                         break;
4291                 }
4292
4293                 if (is_set) {
4294                         who_perm_node_t *found_node = NULL;
4295                         who_perm_node_t *node = safe_malloc(
4296                             sizeof (who_perm_node_t));
4297                         who_perm = &node->who_perm;
4298                         uu_avl_index_t idx = 0;
4299
4300                         uu_avl_node_init(node, &node->who_avl_node, avl_pool);
4301                         who_perm_init(who_perm, fsperm, perm_type, perm_name);
4302
4303                         if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4304                             == NULL) {
4305                                 if (avl == fsperm->fsp_uge_avl) {
4306                                         uid_t rid = 0;
4307                                         struct passwd *p = NULL;
4308                                         struct group *g = NULL;
4309                                         const char *nice_name = NULL;
4310
4311                                         switch (perm_type) {
4312                                         case ZFS_DELEG_USER_SETS:
4313                                         case ZFS_DELEG_USER:
4314                                                 rid = atoi(perm_name);
4315                                                 p = getpwuid(rid);
4316                                                 if (p)
4317                                                         nice_name = p->pw_name;
4318                                                 break;
4319                                         case ZFS_DELEG_GROUP_SETS:
4320                                         case ZFS_DELEG_GROUP:
4321                                                 rid = atoi(perm_name);
4322                                                 g = getgrgid(rid);
4323                                                 if (g)
4324                                                         nice_name = g->gr_name;
4325                                                 break;
4326                                         }
4327
4328                                         if (nice_name != NULL)
4329                                                 (void) strlcpy(
4330                                                     node->who_perm.who_ug_name,
4331                                                     nice_name, 256);
4332                                 }
4333
4334                                 uu_avl_insert(avl, node, idx);
4335                         } else {
4336                                 node = found_node;
4337                                 who_perm = &node->who_perm;
4338                         }
4339                 }
4340
4341                 (void) parse_who_perm(who_perm, nvl2, perm_locality);
4342         }
4343
4344         return (0);
4345 }
4346
4347 static inline int
4348 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
4349 {
4350         nvpair_t *nvp = NULL;
4351         uu_avl_index_t idx = 0;
4352
4353         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4354                 nvlist_t *nvl2 = NULL;
4355                 const char *fsname = nvpair_name(nvp);
4356                 data_type_t type = nvpair_type(nvp);
4357                 fs_perm_t *fsperm = NULL;
4358                 fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
4359                 if (node == NULL)
4360                         nomem();
4361
4362                 fsperm = &node->fspn_fsperm;
4363
4364                 assert(DATA_TYPE_NVLIST == type);
4365
4366                 uu_list_node_init(node, &node->fspn_list_node,
4367                     fspset->fsps_list_pool);
4368
4369                 idx = uu_list_numnodes(fspset->fsps_list);
4370                 fs_perm_init(fsperm, fspset, fsname);
4371
4372                 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4373                         return (-1);
4374
4375                 (void) parse_fs_perm(fsperm, nvl2);
4376
4377                 uu_list_insert(fspset->fsps_list, node, idx);
4378         }
4379
4380         return (0);
4381 }
4382
4383 static inline const char *
4384 deleg_perm_comment(zfs_deleg_note_t note)
4385 {
4386         const char *str = "";
4387
4388         /* subcommands */
4389         switch (note) {
4390                 /* SUBCOMMANDS */
4391         case ZFS_DELEG_NOTE_ALLOW:
4392                 str = gettext("Must also have the permission that is being"
4393                     "\n\t\t\t\tallowed");
4394                 break;
4395         case ZFS_DELEG_NOTE_CLONE:
4396                 str = gettext("Must also have the 'create' ability and 'mount'"
4397                     "\n\t\t\t\tability in the origin file system");
4398                 break;
4399         case ZFS_DELEG_NOTE_CREATE:
4400                 str = gettext("Must also have the 'mount' ability");
4401                 break;
4402         case ZFS_DELEG_NOTE_DESTROY:
4403                 str = gettext("Must also have the 'mount' ability");
4404                 break;
4405         case ZFS_DELEG_NOTE_DIFF:
4406                 str = gettext("Allows lookup of paths within a dataset;"
4407                     "\n\t\t\t\tgiven an object number. Ordinary users need this"
4408                     "\n\t\t\t\tin order to use zfs diff");
4409                 break;
4410         case ZFS_DELEG_NOTE_HOLD:
4411                 str = gettext("Allows adding a user hold to a snapshot");
4412                 break;
4413         case ZFS_DELEG_NOTE_MOUNT:
4414                 str = gettext("Allows mount/umount of ZFS datasets");
4415                 break;
4416         case ZFS_DELEG_NOTE_PROMOTE:
4417                 str = gettext("Must also have the 'mount'\n\t\t\t\tand"
4418                     " 'promote' ability in the origin file system");
4419                 break;
4420         case ZFS_DELEG_NOTE_RECEIVE:
4421                 str = gettext("Must also have the 'mount' and 'create'"
4422                     " ability");
4423                 break;
4424         case ZFS_DELEG_NOTE_RELEASE:
4425                 str = gettext("Allows releasing a user hold which\n\t\t\t\t"
4426                     "might destroy the snapshot");
4427                 break;
4428         case ZFS_DELEG_NOTE_RENAME:
4429                 str = gettext("Must also have the 'mount' and 'create'"
4430                     "\n\t\t\t\tability in the new parent");
4431                 break;
4432         case ZFS_DELEG_NOTE_ROLLBACK:
4433                 str = gettext("");
4434                 break;
4435         case ZFS_DELEG_NOTE_SEND:
4436                 str = gettext("");
4437                 break;
4438         case ZFS_DELEG_NOTE_SHARE:
4439                 str = gettext("Allows sharing file systems over NFS or SMB"
4440                     "\n\t\t\t\tprotocols");
4441                 break;
4442         case ZFS_DELEG_NOTE_SNAPSHOT:
4443                 str = gettext("");
4444                 break;
4445 /*
4446  *      case ZFS_DELEG_NOTE_VSCAN:
4447  *              str = gettext("");
4448  *              break;
4449  */
4450                 /* OTHER */
4451         case ZFS_DELEG_NOTE_GROUPQUOTA:
4452                 str = gettext("Allows accessing any groupquota@... property");
4453                 break;
4454         case ZFS_DELEG_NOTE_GROUPUSED:
4455                 str = gettext("Allows reading any groupused@... property");
4456                 break;
4457         case ZFS_DELEG_NOTE_USERPROP:
4458                 str = gettext("Allows changing any user property");
4459                 break;
4460         case ZFS_DELEG_NOTE_USERQUOTA:
4461                 str = gettext("Allows accessing any userquota@... property");
4462                 break;
4463         case ZFS_DELEG_NOTE_USERUSED:
4464                 str = gettext("Allows reading any userused@... property");
4465                 break;
4466                 /* other */
4467         default:
4468                 str = "";
4469         }
4470
4471         return (str);
4472 }
4473
4474 struct allow_opts {
4475         boolean_t local;
4476         boolean_t descend;
4477         boolean_t user;
4478         boolean_t group;
4479         boolean_t everyone;
4480         boolean_t create;
4481         boolean_t set;
4482         boolean_t recursive; /* unallow only */
4483         boolean_t prt_usage;
4484
4485         boolean_t prt_perms;
4486         char *who;
4487         char *perms;
4488         const char *dataset;
4489 };
4490
4491 static inline int
4492 prop_cmp(const void *a, const void *b)
4493 {
4494         const char *str1 = *(const char **)a;
4495         const char *str2 = *(const char **)b;
4496         return (strcmp(str1, str2));
4497 }
4498
4499 static void
4500 allow_usage(boolean_t un, boolean_t requested, const char *msg)
4501 {
4502         const char *opt_desc[] = {
4503                 "-h", gettext("show this help message and exit"),
4504                 "-l", gettext("set permission locally"),
4505                 "-d", gettext("set permission for descents"),
4506                 "-u", gettext("set permission for user"),
4507                 "-g", gettext("set permission for group"),
4508                 "-e", gettext("set permission for everyone"),
4509                 "-c", gettext("set create time permission"),
4510                 "-s", gettext("define permission set"),
4511                 /* unallow only */
4512                 "-r", gettext("remove permissions recursively"),
4513         };
4514         size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
4515         size_t allow_size = unallow_size - 2;
4516         const char *props[ZFS_NUM_PROPS];
4517         int i;
4518         size_t count = 0;
4519         FILE *fp = requested ? stdout : stderr;
4520         zprop_desc_t *pdtbl = zfs_prop_get_table();
4521         const char *fmt = gettext("%-16s %-14s\t%s\n");
4522
4523         (void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
4524             HELP_ALLOW));
4525         (void) fprintf(fp, gettext("Options:\n"));
4526         for (i = 0; i < (un ? unallow_size : allow_size); i++) {
4527                 const char *opt = opt_desc[i++];
4528                 const char *optdsc = opt_desc[i];
4529                 (void) fprintf(fp, gettext("  %-10s  %s\n"), opt, optdsc);
4530         }
4531
4532         (void) fprintf(fp, gettext("\nThe following permissions are "
4533             "supported:\n\n"));
4534         (void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
4535             gettext("NOTES"));
4536         for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
4537                 const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
4538                 zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
4539                 const char *perm_type = deleg_perm_type(perm_note);
4540                 const char *perm_comment = deleg_perm_comment(perm_note);
4541                 (void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
4542         }
4543
4544         for (i = 0; i < ZFS_NUM_PROPS; i++) {
4545                 zprop_desc_t *pd = &pdtbl[i];
4546                 if (pd->pd_visible != B_TRUE)
4547                         continue;
4548
4549                 if (pd->pd_attr == PROP_READONLY)
4550                         continue;
4551
4552                 props[count++] = pd->pd_name;
4553         }
4554         props[count] = NULL;
4555
4556         qsort(props, count, sizeof (char *), prop_cmp);
4557
4558         for (i = 0; i < count; i++)
4559                 (void) fprintf(fp, fmt, props[i], gettext("property"), "");
4560
4561         if (msg != NULL)
4562                 (void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
4563
4564         exit(requested ? 0 : 2);
4565 }
4566
4567 static inline const char *
4568 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
4569     char **permsp)
4570 {
4571         if (un && argc == expected_argc - 1)
4572                 *permsp = NULL;
4573         else if (argc == expected_argc)
4574                 *permsp = argv[argc - 2];
4575         else
4576                 allow_usage(un, B_FALSE,
4577                     gettext("wrong number of parameters\n"));
4578
4579         return (argv[argc - 1]);
4580 }
4581
4582 static void
4583 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
4584 {
4585         int uge_sum = opts->user + opts->group + opts->everyone;
4586         int csuge_sum = opts->create + opts->set + uge_sum;
4587         int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
4588         int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
4589
4590         if (uge_sum > 1)
4591                 allow_usage(un, B_FALSE,
4592                     gettext("-u, -g, and -e are mutually exclusive\n"));
4593
4594         if (opts->prt_usage)
4595                 if (argc == 0 && all_sum == 0)
4596                         allow_usage(un, B_TRUE, NULL);
4597                 else
4598                         usage(B_FALSE);
4599
4600         if (opts->set) {
4601                 if (csuge_sum > 1)
4602                         allow_usage(un, B_FALSE,
4603                             gettext("invalid options combined with -s\n"));
4604
4605                 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4606                 if (argv[0][0] != '@')
4607                         allow_usage(un, B_FALSE,
4608                             gettext("invalid set name: missing '@' prefix\n"));
4609                 opts->who = argv[0];
4610         } else if (opts->create) {
4611                 if (ldcsuge_sum > 1)
4612                         allow_usage(un, B_FALSE,
4613                             gettext("invalid options combined with -c\n"));
4614                 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4615         } else if (opts->everyone) {
4616                 if (csuge_sum > 1)
4617                         allow_usage(un, B_FALSE,
4618                             gettext("invalid options combined with -e\n"));
4619                 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4620         } else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
4621             == 0) {
4622                 opts->everyone = B_TRUE;
4623                 argc--;
4624                 argv++;
4625                 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4626         } else if (argc == 1 && !un) {
4627                 opts->prt_perms = B_TRUE;
4628                 opts->dataset = argv[argc-1];
4629         } else {
4630                 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4631                 opts->who = argv[0];
4632         }
4633
4634         if (!opts->local && !opts->descend) {
4635                 opts->local = B_TRUE;
4636                 opts->descend = B_TRUE;
4637         }
4638 }
4639
4640 static void
4641 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
4642     const char *who, char *perms, nvlist_t *top_nvl)
4643 {
4644         int i;
4645         char ld[2] = { '\0', '\0' };
4646         char who_buf[ZFS_MAXNAMELEN+32];
4647         char base_type;
4648         char set_type;
4649         nvlist_t *base_nvl = NULL;
4650         nvlist_t *set_nvl = NULL;
4651         nvlist_t *nvl;
4652
4653         if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
4654                 nomem();
4655         if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) !=  0)
4656                 nomem();
4657
4658         switch (type) {
4659         case ZFS_DELEG_NAMED_SET_SETS:
4660         case ZFS_DELEG_NAMED_SET:
4661                 set_type = ZFS_DELEG_NAMED_SET_SETS;
4662                 base_type = ZFS_DELEG_NAMED_SET;
4663                 ld[0] = ZFS_DELEG_NA;
4664                 break;
4665         case ZFS_DELEG_CREATE_SETS:
4666         case ZFS_DELEG_CREATE:
4667                 set_type = ZFS_DELEG_CREATE_SETS;
4668                 base_type = ZFS_DELEG_CREATE;
4669                 ld[0] = ZFS_DELEG_NA;
4670                 break;
4671         case ZFS_DELEG_USER_SETS:
4672         case ZFS_DELEG_USER:
4673                 set_type = ZFS_DELEG_USER_SETS;
4674                 base_type = ZFS_DELEG_USER;
4675                 if (local)
4676                         ld[0] = ZFS_DELEG_LOCAL;
4677                 if (descend)
4678                         ld[1] = ZFS_DELEG_DESCENDENT;
4679                 break;
4680         case ZFS_DELEG_GROUP_SETS:
4681         case ZFS_DELEG_GROUP:
4682                 set_type = ZFS_DELEG_GROUP_SETS;
4683                 base_type = ZFS_DELEG_GROUP;
4684                 if (local)
4685                         ld[0] = ZFS_DELEG_LOCAL;
4686                 if (descend)
4687                         ld[1] = ZFS_DELEG_DESCENDENT;
4688                 break;
4689         case ZFS_DELEG_EVERYONE_SETS:
4690         case ZFS_DELEG_EVERYONE:
4691                 set_type = ZFS_DELEG_EVERYONE_SETS;
4692                 base_type = ZFS_DELEG_EVERYONE;
4693                 if (local)
4694                         ld[0] = ZFS_DELEG_LOCAL;
4695                 if (descend)
4696                         ld[1] = ZFS_DELEG_DESCENDENT;
4697         }
4698
4699         if (perms != NULL) {
4700                 char *curr = perms;
4701                 char *end = curr + strlen(perms);
4702
4703                 while (curr < end) {
4704                         char *delim = strchr(curr, ',');
4705                         if (delim == NULL)
4706                                 delim = end;
4707                         else
4708                                 *delim = '\0';
4709
4710                         if (curr[0] == '@')
4711                                 nvl = set_nvl;
4712                         else
4713                                 nvl = base_nvl;
4714
4715                         (void) nvlist_add_boolean(nvl, curr);
4716                         if (delim != end)
4717                                 *delim = ',';
4718                         curr = delim + 1;
4719                 }
4720
4721                 for (i = 0; i < 2; i++) {
4722                         char locality = ld[i];
4723                         if (locality == 0)
4724                                 continue;
4725
4726                         if (!nvlist_empty(base_nvl)) {
4727                                 if (who != NULL)
4728                                         (void) snprintf(who_buf,
4729                                             sizeof (who_buf), "%c%c$%s",
4730                                             base_type, locality, who);
4731                                 else
4732                                         (void) snprintf(who_buf,
4733                                             sizeof (who_buf), "%c%c$",
4734                                             base_type, locality);
4735
4736                                 (void) nvlist_add_nvlist(top_nvl, who_buf,
4737                                     base_nvl);
4738                         }
4739
4740
4741                         if (!nvlist_empty(set_nvl)) {
4742                                 if (who != NULL)
4743                                         (void) snprintf(who_buf,
4744                                             sizeof (who_buf), "%c%c$%s",
4745                                             set_type, locality, who);
4746                                 else
4747                                         (void) snprintf(who_buf,
4748                                             sizeof (who_buf), "%c%c$",
4749                                             set_type, locality);
4750
4751                                 (void) nvlist_add_nvlist(top_nvl, who_buf,
4752                                     set_nvl);
4753                         }
4754                 }
4755         } else {
4756                 for (i = 0; i < 2; i++) {
4757                         char locality = ld[i];
4758                         if (locality == 0)
4759                                 continue;
4760
4761                         if (who != NULL)
4762                                 (void) snprintf(who_buf, sizeof (who_buf),
4763                                     "%c%c$%s", base_type, locality, who);
4764                         else
4765                                 (void) snprintf(who_buf, sizeof (who_buf),
4766                                     "%c%c$", base_type, locality);
4767                         (void) nvlist_add_boolean(top_nvl, who_buf);
4768
4769                         if (who != NULL)
4770                                 (void) snprintf(who_buf, sizeof (who_buf),
4771                                     "%c%c$%s", set_type, locality, who);
4772                         else
4773                                 (void) snprintf(who_buf, sizeof (who_buf),
4774                                     "%c%c$", set_type, locality);
4775                         (void) nvlist_add_boolean(top_nvl, who_buf);
4776                 }
4777         }
4778 }
4779
4780 static int
4781 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
4782 {
4783         if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
4784                 nomem();
4785
4786         if (opts->set) {
4787                 store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
4788                     opts->descend, opts->who, opts->perms, *nvlp);
4789         } else if (opts->create) {
4790                 store_allow_perm(ZFS_DELEG_CREATE, opts->local,
4791                     opts->descend, NULL, opts->perms, *nvlp);
4792         } else if (opts->everyone) {
4793                 store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
4794                     opts->descend, NULL, opts->perms, *nvlp);
4795         } else {
4796                 char *curr = opts->who;
4797                 char *end = curr + strlen(curr);
4798
4799                 while (curr < end) {
4800                         const char *who;
4801                         zfs_deleg_who_type_t who_type;
4802                         char *endch;
4803                         char *delim = strchr(curr, ',');
4804                         char errbuf[256];
4805                         char id[64];
4806                         struct passwd *p = NULL;
4807                         struct group *g = NULL;
4808
4809                         uid_t rid;
4810                         if (delim == NULL)
4811                                 delim = end;
4812                         else
4813                                 *delim = '\0';
4814
4815                         rid = (uid_t)strtol(curr, &endch, 0);
4816                         if (opts->user) {
4817                                 who_type = ZFS_DELEG_USER;
4818                                 if (*endch != '\0')
4819                                         p = getpwnam(curr);
4820                                 else
4821                                         p = getpwuid(rid);
4822
4823                                 if (p != NULL)
4824                                         rid = p->pw_uid;
4825                                 else {
4826                                         (void) snprintf(errbuf, 256, gettext(
4827                                             "invalid user %s"), curr);
4828                                         allow_usage(un, B_TRUE, errbuf);
4829                                 }
4830                         } else if (opts->group) {
4831                                 who_type = ZFS_DELEG_GROUP;
4832                                 if (*endch != '\0')
4833                                         g = getgrnam(curr);
4834                                 else
4835                                         g = getgrgid(rid);
4836
4837                                 if (g != NULL)
4838                                         rid = g->gr_gid;
4839                                 else {
4840                                         (void) snprintf(errbuf, 256, gettext(
4841                                             "invalid group %s"),  curr);
4842                                         allow_usage(un, B_TRUE, errbuf);
4843                                 }
4844                         } else {
4845                                 if (*endch != '\0') {
4846                                         p = getpwnam(curr);
4847                                 } else {
4848                                         p = getpwuid(rid);
4849                                 }
4850
4851                                 if (p == NULL)
4852                                         if (*endch != '\0') {
4853                                                 g = getgrnam(curr);
4854                                         } else {
4855                                                 g = getgrgid(rid);
4856                                         }
4857
4858                                 if (p != NULL) {
4859                                         who_type = ZFS_DELEG_USER;
4860                                         rid = p->pw_uid;
4861                                 } else if (g != NULL) {
4862                                         who_type = ZFS_DELEG_GROUP;
4863                                         rid = g->gr_gid;
4864                                 } else {
4865                                         (void) snprintf(errbuf, 256, gettext(
4866                                             "invalid user/group %s"), curr);
4867                                         allow_usage(un, B_TRUE, errbuf);
4868                                 }
4869                         }
4870
4871                         (void) sprintf(id, "%u", rid);
4872                         who = id;
4873
4874                         store_allow_perm(who_type, opts->local,
4875                             opts->descend, who, opts->perms, *nvlp);
4876                         curr = delim + 1;
4877                 }
4878         }
4879
4880         return (0);
4881 }
4882
4883 static void
4884 print_set_creat_perms(uu_avl_t *who_avl)
4885 {
4886         const char *sc_title[] = {
4887                 gettext("Permission sets:\n"),
4888                 gettext("Create time permissions:\n"),
4889                 NULL
4890         };
4891         const char **title_ptr = sc_title;
4892         who_perm_node_t *who_node = NULL;
4893         int prev_weight = -1;
4894
4895         for (who_node = uu_avl_first(who_avl); who_node != NULL;
4896             who_node = uu_avl_next(who_avl, who_node)) {
4897                 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
4898                 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
4899                 const char *who_name = who_node->who_perm.who_name;
4900                 int weight = who_type2weight(who_type);
4901                 boolean_t first = B_TRUE;
4902                 deleg_perm_node_t *deleg_node;
4903
4904                 if (prev_weight != weight) {
4905                         (void) printf(*title_ptr++);
4906                         prev_weight = weight;
4907                 }
4908
4909                 if (who_name == NULL || strnlen(who_name, 1) == 0)
4910                         (void) printf("\t");
4911                 else
4912                         (void) printf("\t%s ", who_name);
4913
4914                 for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
4915                     deleg_node = uu_avl_next(avl, deleg_node)) {
4916                         if (first) {
4917                                 (void) printf("%s",
4918                                     deleg_node->dpn_perm.dp_name);
4919                                 first = B_FALSE;
4920                         } else
4921                                 (void) printf(",%s",
4922                                     deleg_node->dpn_perm.dp_name);
4923                 }
4924
4925                 (void) printf("\n");
4926         }
4927 }
4928
4929 static void inline
4930 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
4931     const char *title)
4932 {
4933         who_perm_node_t *who_node = NULL;
4934         boolean_t prt_title = B_TRUE;
4935         uu_avl_walk_t *walk;
4936
4937         if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
4938                 nomem();
4939
4940         while ((who_node = uu_avl_walk_next(walk)) != NULL) {
4941                 const char *who_name = who_node->who_perm.who_name;
4942                 const char *nice_who_name = who_node->who_perm.who_ug_name;
4943                 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
4944                 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
4945                 char delim = ' ';
4946                 deleg_perm_node_t *deleg_node;
4947                 boolean_t prt_who = B_TRUE;
4948
4949                 for (deleg_node = uu_avl_first(avl);
4950                     deleg_node != NULL;
4951                     deleg_node = uu_avl_next(avl, deleg_node)) {
4952                         if (local != deleg_node->dpn_perm.dp_local ||
4953                             descend != deleg_node->dpn_perm.dp_descend)
4954                                 continue;
4955
4956                         if (prt_who) {
4957                                 const char *who = NULL;
4958                                 if (prt_title) {
4959                                         prt_title = B_FALSE;
4960                                         (void) printf(title);
4961                                 }
4962
4963                                 switch (who_type) {
4964                                 case ZFS_DELEG_USER_SETS:
4965                                 case ZFS_DELEG_USER:
4966                                         who = gettext("user");
4967                                         if (nice_who_name)
4968                                                 who_name  = nice_who_name;
4969                                         break;
4970                                 case ZFS_DELEG_GROUP_SETS:
4971                                 case ZFS_DELEG_GROUP:
4972                                         who = gettext("group");
4973                                         if (nice_who_name)
4974                                                 who_name  = nice_who_name;
4975                                         break;
4976                                 case ZFS_DELEG_EVERYONE_SETS:
4977                                 case ZFS_DELEG_EVERYONE:
4978                                         who = gettext("everyone");
4979                                         who_name = NULL;
4980                                 }
4981
4982                                 prt_who = B_FALSE;
4983                                 if (who_name == NULL)
4984                                         (void) printf("\t%s", who);
4985                                 else
4986                                         (void) printf("\t%s %s", who, who_name);
4987                         }
4988
4989                         (void) printf("%c%s", delim,
4990                             deleg_node->dpn_perm.dp_name);
4991                         delim = ',';
4992                 }
4993
4994                 if (!prt_who)
4995                         (void) printf("\n");
4996         }
4997
4998         uu_avl_walk_end(walk);
4999 }
5000
5001 static void
5002 print_fs_perms(fs_perm_set_t *fspset)
5003 {
5004         fs_perm_node_t *node = NULL;
5005         char buf[ZFS_MAXNAMELEN+32];
5006         const char *dsname = buf;
5007
5008         for (node = uu_list_first(fspset->fsps_list); node != NULL;
5009             node = uu_list_next(fspset->fsps_list, node)) {
5010                 uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
5011                 uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
5012                 int left = 0;
5013
5014                 (void) snprintf(buf, ZFS_MAXNAMELEN+32,
5015                     gettext("---- Permissions on %s "),
5016                     node->fspn_fsperm.fsp_name);
5017                 (void) printf(dsname);
5018                 left = 70 - strlen(buf);
5019                 while (left-- > 0)
5020                         (void) printf("-");
5021                 (void) printf("\n");
5022
5023                 print_set_creat_perms(sc_avl);
5024                 print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
5025                     gettext("Local permissions:\n"));
5026                 print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
5027                     gettext("Descendent permissions:\n"));
5028                 print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
5029                     gettext("Local+Descendent permissions:\n"));
5030         }
5031 }
5032
5033 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
5034
5035 struct deleg_perms {
5036         boolean_t un;
5037         nvlist_t *nvl;
5038 };
5039
5040 static int
5041 set_deleg_perms(zfs_handle_t *zhp, void *data)
5042 {
5043         struct deleg_perms *perms = (struct deleg_perms *)data;
5044         zfs_type_t zfs_type = zfs_get_type(zhp);
5045
5046         if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
5047                 return (0);
5048
5049         return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
5050 }
5051
5052 static int
5053 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
5054 {
5055         zfs_handle_t *zhp;
5056         nvlist_t *perm_nvl = NULL;
5057         nvlist_t *update_perm_nvl = NULL;
5058         int error = 1;
5059         int c;
5060         struct allow_opts opts = { 0 };
5061
5062         const char *optstr = un ? "ldugecsrh" : "ldugecsh";
5063
5064         /* check opts */
5065         while ((c = getopt(argc, argv, optstr)) != -1) {
5066                 switch (c) {
5067                 case 'l':
5068                         opts.local = B_TRUE;
5069                         break;
5070                 case 'd':
5071                         opts.descend = B_TRUE;
5072                         break;
5073                 case 'u':
5074                         opts.user = B_TRUE;
5075                         break;
5076                 case 'g':
5077                         opts.group = B_TRUE;
5078                         break;
5079                 case 'e':
5080                         opts.everyone = B_TRUE;
5081                         break;
5082                 case 's':
5083                         opts.set = B_TRUE;
5084                         break;
5085                 case 'c':
5086                         opts.create = B_TRUE;
5087                         break;
5088                 case 'r':
5089                         opts.recursive = B_TRUE;
5090                         break;
5091                 case ':':
5092                         (void) fprintf(stderr, gettext("missing argument for "
5093                             "'%c' option\n"), optopt);
5094                         usage(B_FALSE);
5095                         break;
5096                 case 'h':
5097                         opts.prt_usage = B_TRUE;
5098                         break;
5099                 case '?':
5100                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5101                             optopt);
5102                         usage(B_FALSE);
5103                 }
5104         }
5105
5106         argc -= optind;
5107         argv += optind;
5108
5109         /* check arguments */
5110         parse_allow_args(argc, argv, un, &opts);
5111
5112         /* try to open the dataset */
5113         if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
5114             ZFS_TYPE_VOLUME)) == NULL) {
5115                 (void) fprintf(stderr, "Failed to open dataset: %s\n",
5116                     opts.dataset);
5117                 return (-1);
5118         }
5119
5120         if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
5121                 goto cleanup2;
5122
5123         fs_perm_set_init(&fs_perm_set);
5124         if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
5125                 (void) fprintf(stderr, "Failed to parse fsacl permissions\n");
5126                 goto cleanup1;
5127         }
5128
5129         if (opts.prt_perms)
5130                 print_fs_perms(&fs_perm_set);
5131         else {
5132                 (void) construct_fsacl_list(un, &opts, &update_perm_nvl);
5133                 if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
5134                         goto cleanup0;
5135
5136                 if (un && opts.recursive) {
5137                         struct deleg_perms data = { un, update_perm_nvl };
5138                         if (zfs_iter_filesystems(zhp, set_deleg_perms,
5139                             &data) != 0)
5140                                 goto cleanup0;
5141                 }
5142         }
5143
5144         error = 0;
5145
5146 cleanup0:
5147         nvlist_free(perm_nvl);
5148         if (update_perm_nvl != NULL)
5149                 nvlist_free(update_perm_nvl);
5150 cleanup1:
5151         fs_perm_set_fini(&fs_perm_set);
5152 cleanup2:
5153         zfs_close(zhp);
5154
5155         return (error);
5156 }
5157
5158 static int
5159 zfs_do_allow(int argc, char **argv)
5160 {
5161         return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
5162 }
5163
5164 static int
5165 zfs_do_unallow(int argc, char **argv)
5166 {
5167         return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
5168 }
5169
5170 static int
5171 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
5172 {
5173         int errors = 0;
5174         int i;
5175         const char *tag;
5176         boolean_t recursive = B_FALSE;
5177         const char *opts = holding ? "rt" : "r";
5178         int c;
5179
5180         /* check options */
5181         while ((c = getopt(argc, argv, opts)) != -1) {
5182                 switch (c) {
5183                 case 'r':
5184                         recursive = B_TRUE;
5185                         break;
5186                 case '?':
5187                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5188                             optopt);
5189                         usage(B_FALSE);
5190                 }
5191         }
5192
5193         argc -= optind;
5194         argv += optind;
5195
5196         /* check number of arguments */
5197         if (argc < 2)
5198                 usage(B_FALSE);
5199
5200         tag = argv[0];
5201         --argc;
5202         ++argv;
5203
5204         if (holding && tag[0] == '.') {
5205                 /* tags starting with '.' are reserved for libzfs */
5206                 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
5207                 usage(B_FALSE);
5208         }
5209
5210         for (i = 0; i < argc; ++i) {
5211                 zfs_handle_t *zhp;
5212                 char parent[ZFS_MAXNAMELEN];
5213                 const char *delim;
5214                 char *path = argv[i];
5215
5216                 delim = strchr(path, '@');
5217                 if (delim == NULL) {
5218                         (void) fprintf(stderr,
5219                             gettext("'%s' is not a snapshot\n"), path);
5220                         ++errors;
5221                         continue;
5222                 }
5223                 (void) strncpy(parent, path, delim - path);
5224                 parent[delim - path] = '\0';
5225
5226                 zhp = zfs_open(g_zfs, parent,
5227                     ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5228                 if (zhp == NULL) {
5229                         ++errors;
5230                         continue;
5231                 }
5232                 if (holding) {
5233                         if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
5234                                 ++errors;
5235                 } else {
5236                         if (zfs_release(zhp, delim+1, tag, recursive) != 0)
5237                                 ++errors;
5238                 }
5239                 zfs_close(zhp);
5240         }
5241
5242         return (errors != 0);
5243 }
5244
5245 /*
5246  * zfs hold [-r] [-t] <tag> <snap> ...
5247  *
5248  *      -r      Recursively hold
5249  *
5250  * Apply a user-hold with the given tag to the list of snapshots.
5251  */
5252 static int
5253 zfs_do_hold(int argc, char **argv)
5254 {
5255         return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
5256 }
5257
5258 /*
5259  * zfs release [-r] <tag> <snap> ...
5260  *
5261  *      -r      Recursively release
5262  *
5263  * Release a user-hold with the given tag from the list of snapshots.
5264  */
5265 static int
5266 zfs_do_release(int argc, char **argv)
5267 {
5268         return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
5269 }
5270
5271 typedef struct holds_cbdata {
5272         boolean_t       cb_recursive;
5273         const char      *cb_snapname;
5274         nvlist_t        **cb_nvlp;
5275         size_t          cb_max_namelen;
5276         size_t          cb_max_taglen;
5277 } holds_cbdata_t;
5278
5279 #define STRFTIME_FMT_STR "%a %b %e %k:%M %Y"
5280 #define DATETIME_BUF_LEN (32)
5281 /*
5282  *
5283  */
5284 static void
5285 print_holds(boolean_t scripted, size_t nwidth, size_t tagwidth, nvlist_t *nvl)
5286 {
5287         int i;
5288         nvpair_t *nvp = NULL;
5289         char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
5290         const char *col;
5291
5292         if (!scripted) {
5293                 for (i = 0; i < 3; i++) {
5294                         col = gettext(hdr_cols[i]);
5295                         if (i < 2)
5296                                 (void) printf("%-*s  ", i ? tagwidth : nwidth,
5297                                     col);
5298                         else
5299                                 (void) printf("%s\n", col);
5300                 }
5301         }
5302
5303         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5304                 char *zname = nvpair_name(nvp);
5305                 nvlist_t *nvl2;
5306                 nvpair_t *nvp2 = NULL;
5307                 (void) nvpair_value_nvlist(nvp, &nvl2);
5308                 while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
5309                         char tsbuf[DATETIME_BUF_LEN];
5310                         char *tagname = nvpair_name(nvp2);
5311                         uint64_t val = 0;
5312                         time_t time;
5313                         struct tm t;
5314                         char sep = scripted ? '\t' : ' ';
5315                         size_t sepnum = scripted ? 1 : 2;
5316
5317                         (void) nvpair_value_uint64(nvp2, &val);
5318                         time = (time_t)val;
5319                         (void) localtime_r(&time, &t);
5320                         (void) strftime(tsbuf, DATETIME_BUF_LEN,
5321                             gettext(STRFTIME_FMT_STR), &t);
5322
5323                         (void) printf("%-*s%*c%-*s%*c%s\n", nwidth, zname,
5324                             sepnum, sep, tagwidth, tagname, sepnum, sep, tsbuf);
5325                 }
5326         }
5327 }
5328
5329 /*
5330  * Generic callback function to list a dataset or snapshot.
5331  */
5332 static int
5333 holds_callback(zfs_handle_t *zhp, void *data)
5334 {
5335         holds_cbdata_t *cbp = data;
5336         nvlist_t *top_nvl = *cbp->cb_nvlp;
5337         nvlist_t *nvl = NULL;
5338         nvpair_t *nvp = NULL;
5339         const char *zname = zfs_get_name(zhp);
5340         size_t znamelen = strnlen(zname, ZFS_MAXNAMELEN);
5341
5342         if (cbp->cb_recursive) {
5343                 const char *snapname;
5344                 char *delim  = strchr(zname, '@');
5345                 if (delim == NULL)
5346                         return (0);
5347
5348                 snapname = delim + 1;
5349                 if (strcmp(cbp->cb_snapname, snapname))
5350                         return (0);
5351         }
5352
5353         if (zfs_get_holds(zhp, &nvl) != 0)
5354                 return (-1);
5355
5356         if (znamelen > cbp->cb_max_namelen)
5357                 cbp->cb_max_namelen  = znamelen;
5358
5359         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5360                 const char *tag = nvpair_name(nvp);
5361                 size_t taglen = strnlen(tag, MAXNAMELEN);
5362                 if (taglen > cbp->cb_max_taglen)
5363                         cbp->cb_max_taglen  = taglen;
5364         }
5365
5366         return (nvlist_add_nvlist(top_nvl, zname, nvl));
5367 }
5368
5369 /*
5370  * zfs holds [-r] <snap> ...
5371  *
5372  *      -r      Recursively hold
5373  */
5374 static int
5375 zfs_do_holds(int argc, char **argv)
5376 {
5377         int errors = 0;
5378         int c;
5379         int i;
5380         boolean_t scripted = B_FALSE;
5381         boolean_t recursive = B_FALSE;
5382         const char *opts = "rH";
5383         nvlist_t *nvl;
5384
5385         int types = ZFS_TYPE_SNAPSHOT;
5386         holds_cbdata_t cb = { 0 };
5387
5388         int limit = 0;
5389         int ret = 0;
5390         int flags = 0;
5391
5392         /* check options */
5393         while ((c = getopt(argc, argv, opts)) != -1) {
5394                 switch (c) {
5395                 case 'r':
5396                         recursive = B_TRUE;
5397                         break;
5398                 case 'H':
5399                         scripted = B_TRUE;
5400                         break;
5401                 case '?':
5402                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5403                             optopt);
5404                         usage(B_FALSE);
5405                 }
5406         }
5407
5408         if (recursive) {
5409                 types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
5410                 flags |= ZFS_ITER_RECURSE;
5411         }
5412
5413         argc -= optind;
5414         argv += optind;
5415
5416         /* check number of arguments */
5417         if (argc < 1)
5418                 usage(B_FALSE);
5419
5420         if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5421                 nomem();
5422
5423         for (i = 0; i < argc; ++i) {
5424                 char *snapshot = argv[i];
5425                 const char *delim;
5426                 const char *snapname;
5427
5428                 delim = strchr(snapshot, '@');
5429                 if (delim == NULL) {
5430                         (void) fprintf(stderr,
5431                             gettext("'%s' is not a snapshot\n"), snapshot);
5432                         ++errors;
5433                         continue;
5434                 }
5435                 snapname = delim + 1;
5436                 if (recursive)
5437                         snapshot[delim - snapshot] = '\0';
5438
5439                 cb.cb_recursive = recursive;
5440                 cb.cb_snapname = snapname;
5441                 cb.cb_nvlp = &nvl;
5442
5443                 /*
5444                  *  1. collect holds data, set format options
5445                  */
5446                 ret = zfs_for_each(argc, argv, flags, types, NULL, NULL, limit,
5447                     holds_callback, &cb);
5448                 if (ret != 0)
5449                         ++errors;
5450         }
5451
5452         /*
5453          *  2. print holds data
5454          */
5455         print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl);
5456
5457         if (nvlist_empty(nvl))
5458                 (void) printf(gettext("no datasets available\n"));
5459
5460         nvlist_free(nvl);
5461
5462         return (0 != errors);
5463 }
5464
5465 #define CHECK_SPINNER 30
5466 #define SPINNER_TIME 3          /* seconds */
5467 #define MOUNT_TIME 5            /* seconds */
5468
5469 static int
5470 get_one_dataset(zfs_handle_t *zhp, void *data)
5471 {
5472         static char *spin[] = { "-", "\\", "|", "/" };
5473         static int spinval = 0;
5474         static int spincheck = 0;
5475         static time_t last_spin_time = (time_t)0;
5476         get_all_cb_t *cbp = data;
5477         zfs_type_t type = zfs_get_type(zhp);
5478
5479         if (cbp->cb_verbose) {
5480                 if (--spincheck < 0) {
5481                         time_t now = time(NULL);
5482                         if (last_spin_time + SPINNER_TIME < now) {
5483                                 update_progress(spin[spinval++ % 4]);
5484                                 last_spin_time = now;
5485                         }
5486                         spincheck = CHECK_SPINNER;
5487                 }
5488         }
5489
5490         /*
5491          * Interate over any nested datasets.
5492          */
5493         if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
5494                 zfs_close(zhp);
5495                 return (1);
5496         }
5497
5498         /*
5499          * Skip any datasets whose type does not match.
5500          */
5501         if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
5502                 zfs_close(zhp);
5503                 return (0);
5504         }
5505         libzfs_add_handle(cbp, zhp);
5506         assert(cbp->cb_used <= cbp->cb_alloc);
5507
5508         return (0);
5509 }
5510
5511 static void
5512 get_all_datasets(zfs_handle_t ***dslist, size_t *count, boolean_t verbose)
5513 {
5514         get_all_cb_t cb = { 0 };
5515         cb.cb_verbose = verbose;
5516         cb.cb_getone = get_one_dataset;
5517
5518         if (verbose)
5519                 set_progress_header(gettext("Reading ZFS config"));
5520         (void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
5521
5522         *dslist = cb.cb_handles;
5523         *count = cb.cb_used;
5524
5525         if (verbose)
5526                 finish_progress(gettext("done."));
5527 }
5528
5529 /*
5530  * Generic callback for sharing or mounting filesystems.  Because the code is so
5531  * similar, we have a common function with an extra parameter to determine which
5532  * mode we are using.
5533  */
5534 #define OP_SHARE        0x1
5535 #define OP_MOUNT        0x2
5536
5537 /*
5538  * Share or mount a dataset.
5539  */
5540 static int
5541 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
5542     boolean_t explicit, const char *options)
5543 {
5544         char mountpoint[ZFS_MAXPROPLEN];
5545         char shareopts[ZFS_MAXPROPLEN];
5546         char smbshareopts[ZFS_MAXPROPLEN];
5547         const char *cmdname = op == OP_SHARE ? "share" : "mount";
5548         struct mnttab mnt;
5549         uint64_t zoned, canmount;
5550         boolean_t shared_nfs, shared_smb;
5551
5552         assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
5553
5554         /*
5555          * Check to make sure we can mount/share this dataset.  If we
5556          * are in the global zone and the filesystem is exported to a
5557          * local zone, or if we are in a local zone and the
5558          * filesystem is not exported, then it is an error.
5559          */
5560         zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
5561
5562         if (zoned && getzoneid() == GLOBAL_ZONEID) {
5563                 if (!explicit)
5564                         return (0);
5565
5566                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5567                     "dataset is exported to a local zone\n"), cmdname,
5568                     zfs_get_name(zhp));
5569                 return (1);
5570
5571         } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
5572                 if (!explicit)
5573                         return (0);
5574
5575                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5576                     "permission denied\n"), cmdname,
5577                     zfs_get_name(zhp));
5578                 return (1);
5579         }
5580
5581         /*
5582          * Ignore any filesystems which don't apply to us. This
5583          * includes those with a legacy mountpoint, or those with
5584          * legacy share options.
5585          */
5586         verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
5587             sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
5588         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
5589             sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
5590         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
5591             sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
5592
5593         if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
5594             strcmp(smbshareopts, "off") == 0) {
5595                 if (!explicit)
5596                         return (0);
5597
5598                 (void) fprintf(stderr, gettext("cannot share '%s': "
5599                     "legacy share\n"), zfs_get_name(zhp));
5600                 (void) fprintf(stderr, gettext("to "
5601                     "share this filesystem set "
5602                     "sharenfs property on\n"));
5603                 return (1);
5604         }
5605
5606         /*
5607          * We cannot share or mount legacy filesystems. If the
5608          * shareopts is non-legacy but the mountpoint is legacy, we
5609          * treat it as a legacy share.
5610          */
5611         if (strcmp(mountpoint, "legacy") == 0) {
5612                 if (!explicit)
5613                         return (0);
5614
5615                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5616                     "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
5617                 (void) fprintf(stderr, gettext("use %s(8) to "
5618                     "%s this filesystem\n"), cmdname, cmdname);
5619                 return (1);
5620         }
5621
5622         if (strcmp(mountpoint, "none") == 0) {
5623                 if (!explicit)
5624                         return (0);
5625
5626                 (void) fprintf(stderr, gettext("cannot %s '%s': no "
5627                     "mountpoint set\n"), cmdname, zfs_get_name(zhp));
5628                 return (1);
5629         }
5630
5631         /*
5632          * canmount     explicit        outcome
5633          * on           no              pass through
5634          * on           yes             pass through
5635          * off          no              return 0
5636          * off          yes             display error, return 1
5637          * noauto       no              return 0
5638          * noauto       yes             pass through
5639          */
5640         canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
5641         if (canmount == ZFS_CANMOUNT_OFF) {
5642                 if (!explicit)
5643                         return (0);
5644
5645                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5646                     "'canmount' property is set to 'off'\n"), cmdname,
5647                     zfs_get_name(zhp));
5648                 return (1);
5649         } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
5650                 return (0);
5651         }
5652
5653         /*
5654          * At this point, we have verified that the mountpoint and/or
5655          * shareopts are appropriate for auto management. If the
5656          * filesystem is already mounted or shared, return (failing
5657          * for explicit requests); otherwise mount or share the
5658          * filesystem.
5659          */
5660         switch (op) {
5661         case OP_SHARE:
5662
5663                 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
5664                 shared_smb = zfs_is_shared_smb(zhp, NULL);
5665
5666                 if (shared_nfs && shared_smb ||
5667                     (shared_nfs && strcmp(shareopts, "on") == 0 &&
5668                     strcmp(smbshareopts, "off") == 0) ||
5669                     (shared_smb && strcmp(smbshareopts, "on") == 0 &&
5670                     strcmp(shareopts, "off") == 0)) {
5671                         if (!explicit)
5672                                 return (0);
5673
5674                         (void) fprintf(stderr, gettext("cannot share "
5675                             "'%s': filesystem already shared\n"),
5676                             zfs_get_name(zhp));
5677                         return (1);
5678                 }
5679
5680                 if (!zfs_is_mounted(zhp, NULL) &&
5681                     zfs_mount(zhp, NULL, 0) != 0)
5682                         return (1);
5683
5684                 if (protocol == NULL) {
5685                         if (zfs_shareall(zhp) != 0)
5686                                 return (1);
5687                 } else if (strcmp(protocol, "nfs") == 0) {
5688                         if (zfs_share_nfs(zhp))
5689                                 return (1);
5690                 } else if (strcmp(protocol, "smb") == 0) {
5691                         if (zfs_share_smb(zhp))
5692                                 return (1);
5693                 } else {
5694                         (void) fprintf(stderr, gettext("cannot share "
5695                             "'%s': invalid share type '%s' "
5696                             "specified\n"),
5697                             zfs_get_name(zhp), protocol);
5698                         return (1);
5699                 }
5700
5701                 break;
5702
5703         case OP_MOUNT:
5704                 if (options == NULL)
5705                         mnt.mnt_mntopts = "";
5706                 else
5707                         mnt.mnt_mntopts = (char *)options;
5708
5709                 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
5710                     zfs_is_mounted(zhp, NULL)) {
5711                         if (!explicit)
5712                                 return (0);
5713
5714                         (void) fprintf(stderr, gettext("cannot mount "
5715                             "'%s': filesystem already mounted\n"),
5716                             zfs_get_name(zhp));
5717                         return (1);
5718                 }
5719
5720                 if (zfs_mount(zhp, options, flags) != 0)
5721                         return (1);
5722                 break;
5723         }
5724
5725         return (0);
5726 }
5727
5728 /*
5729  * Reports progress in the form "(current/total)".  Not thread-safe.
5730  */
5731 static void
5732 report_mount_progress(int current, int total)
5733 {
5734         static time_t last_progress_time = 0;
5735         time_t now = time(NULL);
5736         char info[32];
5737
5738         /* report 1..n instead of 0..n-1 */
5739         ++current;
5740
5741         /* display header if we're here for the first time */
5742         if (current == 1) {
5743                 set_progress_header(gettext("Mounting ZFS filesystems"));
5744         } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
5745                 /* too soon to report again */
5746                 return;
5747         }
5748
5749         last_progress_time = now;
5750
5751         (void) sprintf(info, "(%d/%d)", current, total);
5752
5753         if (current == total)
5754                 finish_progress(info);
5755         else
5756                 update_progress(info);
5757 }
5758
5759 static void
5760 append_options(char *mntopts, char *newopts)
5761 {
5762         int len = strlen(mntopts);
5763
5764         /* original length plus new string to append plus 1 for the comma */
5765         if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
5766                 (void) fprintf(stderr, gettext("the opts argument for "
5767                     "'%c' option is too long (more than %d chars)\n"),
5768                     "-o", MNT_LINE_MAX);
5769                 usage(B_FALSE);
5770         }
5771
5772         if (*mntopts)
5773                 mntopts[len++] = ',';
5774
5775         (void) strcpy(&mntopts[len], newopts);
5776 }
5777
5778 static int
5779 share_mount(int op, int argc, char **argv)
5780 {
5781         int do_all = 0;
5782         boolean_t verbose = B_FALSE;
5783         int c, ret = 0;
5784         char *options = NULL;
5785         int flags = 0;
5786
5787         /* check options */
5788         while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
5789             != -1) {
5790                 switch (c) {
5791                 case 'a':
5792                         do_all = 1;
5793                         break;
5794                 case 'v':
5795                         verbose = B_TRUE;
5796                         break;
5797                 case 'o':
5798                         if (*optarg == '\0') {
5799                                 (void) fprintf(stderr, gettext("empty mount "
5800                                     "options (-o) specified\n"));
5801                                 usage(B_FALSE);
5802                         }
5803
5804                         if (options == NULL)
5805                                 options = safe_malloc(MNT_LINE_MAX + 1);
5806
5807                         /* option validation is done later */
5808                         append_options(options, optarg);
5809                         break;
5810
5811                 case 'O':
5812                         warnx("no overlay mounts support on FreeBSD, ignoring");
5813                         break;
5814                 case ':':
5815                         (void) fprintf(stderr, gettext("missing argument for "
5816                             "'%c' option\n"), optopt);
5817                         usage(B_FALSE);
5818                         break;
5819                 case '?':
5820                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5821                             optopt);
5822                         usage(B_FALSE);
5823                 }
5824         }
5825
5826         argc -= optind;
5827         argv += optind;
5828
5829         /* check number of arguments */
5830         if (do_all) {
5831                 zfs_handle_t **dslist = NULL;
5832                 size_t i, count = 0;
5833                 char *protocol = NULL;
5834
5835                 if (op == OP_SHARE && argc > 0) {
5836                         if (strcmp(argv[0], "nfs") != 0 &&
5837                             strcmp(argv[0], "smb") != 0) {
5838                                 (void) fprintf(stderr, gettext("share type "
5839                                     "must be 'nfs' or 'smb'\n"));
5840                                 usage(B_FALSE);
5841                         }
5842                         protocol = argv[0];
5843                         argc--;
5844                         argv++;
5845                 }
5846
5847                 if (argc != 0) {
5848                         (void) fprintf(stderr, gettext("too many arguments\n"));
5849                         usage(B_FALSE);
5850                 }
5851
5852                 start_progress_timer();
5853                 get_all_datasets(&dslist, &count, verbose);
5854
5855                 if (count == 0)
5856                         return (0);
5857
5858                 qsort(dslist, count, sizeof (void *), libzfs_dataset_cmp);
5859
5860                 for (i = 0; i < count; i++) {
5861                         if (verbose)
5862                                 report_mount_progress(i, count);
5863
5864                         if (share_mount_one(dslist[i], op, flags, protocol,
5865                             B_FALSE, options) != 0)
5866                                 ret = 1;
5867                         zfs_close(dslist[i]);
5868                 }
5869
5870                 free(dslist);
5871         } else if (argc == 0) {
5872                 struct mnttab entry;
5873
5874                 if ((op == OP_SHARE) || (options != NULL)) {
5875                         (void) fprintf(stderr, gettext("missing filesystem "
5876                             "argument (specify -a for all)\n"));
5877                         usage(B_FALSE);
5878                 }
5879
5880                 /*
5881                  * When mount is given no arguments, go through /etc/mnttab and
5882                  * display any active ZFS mounts.  We hide any snapshots, since
5883                  * they are controlled automatically.
5884                  */
5885                 rewind(mnttab_file);
5886                 while (getmntent(mnttab_file, &entry) == 0) {
5887                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
5888                             strchr(entry.mnt_special, '@') != NULL)
5889                                 continue;
5890
5891                         (void) printf("%-30s  %s\n", entry.mnt_special,
5892                             entry.mnt_mountp);
5893                 }
5894
5895         } else {
5896                 zfs_handle_t *zhp;
5897
5898                 if (argc > 1) {
5899                         (void) fprintf(stderr,
5900                             gettext("too many arguments\n"));
5901                         usage(B_FALSE);
5902                 }
5903
5904                 if ((zhp = zfs_open(g_zfs, argv[0],
5905                     ZFS_TYPE_FILESYSTEM)) == NULL) {
5906                         ret = 1;
5907                 } else {
5908                         ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
5909                             options);
5910                         zfs_close(zhp);
5911                 }
5912         }
5913
5914         return (ret);
5915 }
5916
5917 /*
5918  * zfs mount -a [nfs]
5919  * zfs mount filesystem
5920  *
5921  * Mount all filesystems, or mount the given filesystem.
5922  */
5923 static int
5924 zfs_do_mount(int argc, char **argv)
5925 {
5926         return (share_mount(OP_MOUNT, argc, argv));
5927 }
5928
5929 /*
5930  * zfs share -a [nfs | smb]
5931  * zfs share filesystem
5932  *
5933  * Share all filesystems, or share the given filesystem.
5934  */
5935 static int
5936 zfs_do_share(int argc, char **argv)
5937 {
5938         return (share_mount(OP_SHARE, argc, argv));
5939 }
5940
5941 typedef struct unshare_unmount_node {
5942         zfs_handle_t    *un_zhp;
5943         char            *un_mountp;
5944         uu_avl_node_t   un_avlnode;
5945 } unshare_unmount_node_t;
5946
5947 /* ARGSUSED */
5948 static int
5949 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
5950 {
5951         const unshare_unmount_node_t *l = larg;
5952         const unshare_unmount_node_t *r = rarg;
5953
5954         return (strcmp(l->un_mountp, r->un_mountp));
5955 }
5956
5957 /*
5958  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
5959  * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
5960  * and unmount it appropriately.
5961  */
5962 static int
5963 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
5964 {
5965         zfs_handle_t *zhp;
5966         int ret = 0;
5967         struct stat64 statbuf;
5968         struct extmnttab entry;
5969         const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
5970         ino_t path_inode;
5971
5972         /*
5973          * Search for the path in /etc/mnttab.  Rather than looking for the
5974          * specific path, which can be fooled by non-standard paths (i.e. ".."
5975          * or "//"), we stat() the path and search for the corresponding
5976          * (major,minor) device pair.
5977          */
5978         if (stat64(path, &statbuf) != 0) {
5979                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
5980                     cmdname, path, strerror(errno));
5981                 return (1);
5982         }
5983         path_inode = statbuf.st_ino;
5984
5985         /*
5986          * Search for the given (major,minor) pair in the mount table.
5987          */
5988 #ifdef sun
5989         rewind(mnttab_file);
5990         while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
5991                 if (entry.mnt_major == major(statbuf.st_dev) &&
5992                     entry.mnt_minor == minor(statbuf.st_dev))
5993                         break;
5994         }
5995 #else
5996         {
5997                 struct statfs sfs;
5998
5999                 if (statfs(path, &sfs) != 0) {
6000                         (void) fprintf(stderr, "%s: %s\n", path,
6001                             strerror(errno));
6002                         ret = -1;
6003                 }
6004                 statfs2mnttab(&sfs, &entry);
6005         }
6006 #endif
6007         if (ret != 0) {
6008                 if (op == OP_SHARE) {
6009                         (void) fprintf(stderr, gettext("cannot %s '%s': not "
6010                             "currently mounted\n"), cmdname, path);
6011                         return (1);
6012                 }
6013                 (void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
6014                     path);
6015                 if ((ret = umount2(path, flags)) != 0)
6016                         (void) fprintf(stderr, gettext("%s: %s\n"), path,
6017                             strerror(errno));
6018                 return (ret != 0);
6019         }
6020
6021         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
6022                 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
6023                     "filesystem\n"), cmdname, path);
6024                 return (1);
6025         }
6026
6027         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6028             ZFS_TYPE_FILESYSTEM)) == NULL)
6029                 return (1);
6030
6031         ret = 1;
6032         if (stat64(entry.mnt_mountp, &statbuf) != 0) {
6033                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6034                     cmdname, path, strerror(errno));
6035                 goto out;
6036         } else if (statbuf.st_ino != path_inode) {
6037                 (void) fprintf(stderr, gettext("cannot "
6038                     "%s '%s': not a mountpoint\n"), cmdname, path);
6039                 goto out;
6040         }
6041
6042         if (op == OP_SHARE) {
6043                 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6044                 char smbshare_prop[ZFS_MAXPROPLEN];
6045
6046                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
6047                     sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
6048                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
6049                     sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
6050
6051                 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6052                     strcmp(smbshare_prop, "off") == 0) {
6053                         (void) fprintf(stderr, gettext("cannot unshare "
6054                             "'%s': legacy share\n"), path);
6055 #ifdef illumos
6056                         (void) fprintf(stderr, gettext("use "
6057                             "unshare(1M) to unshare this filesystem\n"));
6058 #endif
6059                 } else if (!zfs_is_shared(zhp)) {
6060                         (void) fprintf(stderr, gettext("cannot unshare '%s': "
6061                             "not currently shared\n"), path);
6062                 } else {
6063                         ret = zfs_unshareall_bypath(zhp, path);
6064                 }
6065         } else {
6066                 char mtpt_prop[ZFS_MAXPROPLEN];
6067
6068                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
6069                     sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
6070
6071                 if (is_manual) {
6072                         ret = zfs_unmount(zhp, NULL, flags);
6073                 } else if (strcmp(mtpt_prop, "legacy") == 0) {
6074                         (void) fprintf(stderr, gettext("cannot unmount "
6075                             "'%s': legacy mountpoint\n"),
6076                             zfs_get_name(zhp));
6077                         (void) fprintf(stderr, gettext("use umount(8) "
6078                             "to unmount this filesystem\n"));
6079                 } else {
6080                         ret = zfs_unmountall(zhp, flags);
6081                 }
6082         }
6083
6084 out:
6085         zfs_close(zhp);
6086
6087         return (ret != 0);
6088 }
6089
6090 /*
6091  * Generic callback for unsharing or unmounting a filesystem.
6092  */
6093 static int
6094 unshare_unmount(int op, int argc, char **argv)
6095 {
6096         int do_all = 0;
6097         int flags = 0;
6098         int ret = 0;
6099         int c;
6100         zfs_handle_t *zhp;
6101         char nfs_mnt_prop[ZFS_MAXPROPLEN];
6102         char sharesmb[ZFS_MAXPROPLEN];
6103
6104         /* check options */
6105         while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
6106                 switch (c) {
6107                 case 'a':
6108                         do_all = 1;
6109                         break;
6110                 case 'f':
6111                         flags = MS_FORCE;
6112                         break;
6113                 case '?':
6114                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6115                             optopt);
6116                         usage(B_FALSE);
6117                 }
6118         }
6119
6120         argc -= optind;
6121         argv += optind;
6122
6123         if (do_all) {
6124                 /*
6125                  * We could make use of zfs_for_each() to walk all datasets in
6126                  * the system, but this would be very inefficient, especially
6127                  * since we would have to linearly search /etc/mnttab for each
6128                  * one.  Instead, do one pass through /etc/mnttab looking for
6129                  * zfs entries and call zfs_unmount() for each one.
6130                  *
6131                  * Things get a little tricky if the administrator has created
6132                  * mountpoints beneath other ZFS filesystems.  In this case, we
6133                  * have to unmount the deepest filesystems first.  To accomplish
6134                  * this, we place all the mountpoints in an AVL tree sorted by
6135                  * the special type (dataset name), and walk the result in
6136                  * reverse to make sure to get any snapshots first.
6137                  */
6138                 struct mnttab entry;
6139                 uu_avl_pool_t *pool;
6140                 uu_avl_t *tree;
6141                 unshare_unmount_node_t *node;
6142                 uu_avl_index_t idx;
6143                 uu_avl_walk_t *walk;
6144
6145                 if (argc != 0) {
6146                         (void) fprintf(stderr, gettext("too many arguments\n"));
6147                         usage(B_FALSE);
6148                 }
6149
6150                 if (((pool = uu_avl_pool_create("unmount_pool",
6151                     sizeof (unshare_unmount_node_t),
6152                     offsetof(unshare_unmount_node_t, un_avlnode),
6153                     unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
6154                     ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
6155                         nomem();
6156
6157                 rewind(mnttab_file);
6158                 while (getmntent(mnttab_file, &entry) == 0) {
6159
6160                         /* ignore non-ZFS entries */
6161                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
6162                                 continue;
6163
6164                         /* ignore snapshots */
6165                         if (strchr(entry.mnt_special, '@') != NULL)
6166                                 continue;
6167
6168                         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6169                             ZFS_TYPE_FILESYSTEM)) == NULL) {
6170                                 ret = 1;
6171                                 continue;
6172                         }
6173
6174                         switch (op) {
6175                         case OP_SHARE:
6176                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6177                                     nfs_mnt_prop,
6178                                     sizeof (nfs_mnt_prop),
6179                                     NULL, NULL, 0, B_FALSE) == 0);
6180                                 if (strcmp(nfs_mnt_prop, "off") != 0)
6181                                         break;
6182                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6183                                     nfs_mnt_prop,
6184                                     sizeof (nfs_mnt_prop),
6185                                     NULL, NULL, 0, B_FALSE) == 0);
6186                                 if (strcmp(nfs_mnt_prop, "off") == 0)
6187                                         continue;
6188                                 break;
6189                         case OP_MOUNT:
6190                                 /* Ignore legacy mounts */
6191                                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
6192                                     nfs_mnt_prop,
6193                                     sizeof (nfs_mnt_prop),
6194                                     NULL, NULL, 0, B_FALSE) == 0);
6195                                 if (strcmp(nfs_mnt_prop, "legacy") == 0)
6196                                         continue;
6197                                 /* Ignore canmount=noauto mounts */
6198                                 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
6199                                     ZFS_CANMOUNT_NOAUTO)
6200                                         continue;
6201                         default:
6202                                 break;
6203                         }
6204
6205                         node = safe_malloc(sizeof (unshare_unmount_node_t));
6206                         node->un_zhp = zhp;
6207                         node->un_mountp = safe_strdup(entry.mnt_mountp);
6208
6209                         uu_avl_node_init(node, &node->un_avlnode, pool);
6210
6211                         if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
6212                                 uu_avl_insert(tree, node, idx);
6213                         } else {
6214                                 zfs_close(node->un_zhp);
6215                                 free(node->un_mountp);
6216                                 free(node);
6217                         }
6218                 }
6219
6220                 /*
6221                  * Walk the AVL tree in reverse, unmounting each filesystem and
6222                  * removing it from the AVL tree in the process.
6223                  */
6224                 if ((walk = uu_avl_walk_start(tree,
6225                     UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
6226                         nomem();
6227
6228                 while ((node = uu_avl_walk_next(walk)) != NULL) {
6229                         uu_avl_remove(tree, node);
6230
6231                         switch (op) {
6232                         case OP_SHARE:
6233                                 if (zfs_unshareall_bypath(node->un_zhp,
6234                                     node->un_mountp) != 0)
6235                                         ret = 1;
6236                                 break;
6237
6238                         case OP_MOUNT:
6239                                 if (zfs_unmount(node->un_zhp,
6240                                     node->un_mountp, flags) != 0)
6241                                         ret = 1;
6242                                 break;
6243                         }
6244
6245                         zfs_close(node->un_zhp);
6246                         free(node->un_mountp);
6247                         free(node);
6248                 }
6249
6250                 uu_avl_walk_end(walk);
6251                 uu_avl_destroy(tree);
6252                 uu_avl_pool_destroy(pool);
6253
6254         } else {
6255                 if (argc != 1) {
6256                         if (argc == 0)
6257                                 (void) fprintf(stderr,
6258                                     gettext("missing filesystem argument\n"));
6259                         else
6260                                 (void) fprintf(stderr,
6261                                     gettext("too many arguments\n"));
6262                         usage(B_FALSE);
6263                 }
6264
6265                 /*
6266                  * We have an argument, but it may be a full path or a ZFS
6267                  * filesystem.  Pass full paths off to unmount_path() (shared by
6268                  * manual_unmount), otherwise open the filesystem and pass to
6269                  * zfs_unmount().
6270                  */
6271                 if (argv[0][0] == '/')
6272                         return (unshare_unmount_path(op, argv[0],
6273                             flags, B_FALSE));
6274
6275                 if ((zhp = zfs_open(g_zfs, argv[0],
6276                     ZFS_TYPE_FILESYSTEM)) == NULL)
6277                         return (1);
6278
6279                 verify(zfs_prop_get(zhp, op == OP_SHARE ?
6280                     ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
6281                     nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
6282                     NULL, 0, B_FALSE) == 0);
6283
6284                 switch (op) {
6285                 case OP_SHARE:
6286                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6287                             nfs_mnt_prop,
6288                             sizeof (nfs_mnt_prop),
6289                             NULL, NULL, 0, B_FALSE) == 0);
6290                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6291                             sharesmb, sizeof (sharesmb), NULL, NULL,
6292                             0, B_FALSE) == 0);
6293
6294                         if (strcmp(nfs_mnt_prop, "off") == 0 &&
6295                             strcmp(sharesmb, "off") == 0) {
6296                                 (void) fprintf(stderr, gettext("cannot "
6297                                     "unshare '%s': legacy share\n"),
6298                                     zfs_get_name(zhp));
6299 #ifdef illumos
6300                                 (void) fprintf(stderr, gettext("use "
6301                                     "unshare(1M) to unshare this "
6302                                     "filesystem\n"));
6303 #endif
6304                                 ret = 1;
6305                         } else if (!zfs_is_shared(zhp)) {
6306                                 (void) fprintf(stderr, gettext("cannot "
6307                                     "unshare '%s': not currently "
6308                                     "shared\n"), zfs_get_name(zhp));
6309                                 ret = 1;
6310                         } else if (zfs_unshareall(zhp) != 0) {
6311                                 ret = 1;
6312                         }
6313                         break;
6314
6315                 case OP_MOUNT:
6316                         if (strcmp(nfs_mnt_prop, "legacy") == 0) {
6317                                 (void) fprintf(stderr, gettext("cannot "
6318                                     "unmount '%s': legacy "
6319                                     "mountpoint\n"), zfs_get_name(zhp));
6320                                 (void) fprintf(stderr, gettext("use "
6321                                     "umount(8) to unmount this "
6322                                     "filesystem\n"));
6323                                 ret = 1;
6324                         } else if (!zfs_is_mounted(zhp, NULL)) {
6325                                 (void) fprintf(stderr, gettext("cannot "
6326                                     "unmount '%s': not currently "
6327                                     "mounted\n"),
6328                                     zfs_get_name(zhp));
6329                                 ret = 1;
6330                         } else if (zfs_unmountall(zhp, flags) != 0) {
6331                                 ret = 1;
6332                         }
6333                         break;
6334                 }
6335
6336                 zfs_close(zhp);
6337         }
6338
6339         return (ret);
6340 }
6341
6342 /*
6343  * zfs unmount -a
6344  * zfs unmount filesystem
6345  *
6346  * Unmount all filesystems, or a specific ZFS filesystem.
6347  */
6348 static int
6349 zfs_do_unmount(int argc, char **argv)
6350 {
6351         return (unshare_unmount(OP_MOUNT, argc, argv));
6352 }
6353
6354 /*
6355  * zfs unshare -a
6356  * zfs unshare filesystem
6357  *
6358  * Unshare all filesystems, or a specific ZFS filesystem.
6359  */
6360 static int
6361 zfs_do_unshare(int argc, char **argv)
6362 {
6363         return (unshare_unmount(OP_SHARE, argc, argv));
6364 }
6365
6366 /*
6367  * Attach/detach the given dataset to/from the given jail
6368  */
6369 /* ARGSUSED */
6370 static int
6371 do_jail(int argc, char **argv, int attach)
6372 {
6373         zfs_handle_t *zhp;
6374         int jailid, ret;
6375
6376         /* check number of arguments */
6377         if (argc < 3) {
6378                 (void) fprintf(stderr, gettext("missing argument(s)\n"));
6379                 usage(B_FALSE);
6380         }
6381         if (argc > 3) {
6382                 (void) fprintf(stderr, gettext("too many arguments\n"));
6383                 usage(B_FALSE);
6384         }
6385
6386         jailid = jail_getid(argv[1]);
6387         if (jailid < 0) {
6388                 (void) fprintf(stderr, gettext("invalid jail id or name\n"));
6389                 usage(B_FALSE);
6390         }
6391
6392         zhp = zfs_open(g_zfs, argv[2], ZFS_TYPE_FILESYSTEM);
6393         if (zhp == NULL)
6394                 return (1);
6395
6396         ret = (zfs_jail(zhp, jailid, attach) != 0);
6397
6398         zfs_close(zhp);
6399         return (ret);
6400 }
6401
6402 /*
6403  * zfs jail jailid filesystem
6404  *
6405  * Attach the given dataset to the given jail
6406  */
6407 /* ARGSUSED */
6408 static int
6409 zfs_do_jail(int argc, char **argv)
6410 {
6411
6412         return (do_jail(argc, argv, 1));
6413 }
6414
6415 /*
6416  * zfs unjail jailid filesystem
6417  *
6418  * Detach the given dataset from the given jail
6419  */
6420 /* ARGSUSED */
6421 static int
6422 zfs_do_unjail(int argc, char **argv)
6423 {
6424
6425         return (do_jail(argc, argv, 0));
6426 }
6427
6428 /*
6429  * Called when invoked as /etc/fs/zfs/mount.  Do the mount if the mountpoint is
6430  * 'legacy'.  Otherwise, complain that use should be using 'zfs mount'.
6431  */
6432 static int
6433 manual_mount(int argc, char **argv)
6434 {
6435         zfs_handle_t *zhp;
6436         char mountpoint[ZFS_MAXPROPLEN];
6437         char mntopts[MNT_LINE_MAX] = { '\0' };
6438         int ret = 0;
6439         int c;
6440         int flags = 0;
6441         char *dataset, *path;
6442
6443         /* check options */
6444         while ((c = getopt(argc, argv, ":mo:O")) != -1) {
6445                 switch (c) {
6446                 case 'o':
6447                         (void) strlcpy(mntopts, optarg, sizeof (mntopts));
6448                         break;
6449                 case 'O':
6450                         flags |= MS_OVERLAY;
6451                         break;
6452                 case 'm':
6453                         flags |= MS_NOMNTTAB;
6454                         break;
6455                 case ':':
6456                         (void) fprintf(stderr, gettext("missing argument for "
6457                             "'%c' option\n"), optopt);
6458                         usage(B_FALSE);
6459                         break;
6460                 case '?':
6461                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6462                             optopt);
6463                         (void) fprintf(stderr, gettext("usage: mount [-o opts] "
6464                             "<path>\n"));
6465                         return (2);
6466                 }
6467         }
6468
6469         argc -= optind;
6470         argv += optind;
6471
6472         /* check that we only have two arguments */
6473         if (argc != 2) {
6474                 if (argc == 0)
6475                         (void) fprintf(stderr, gettext("missing dataset "
6476                             "argument\n"));
6477                 else if (argc == 1)
6478                         (void) fprintf(stderr,
6479                             gettext("missing mountpoint argument\n"));
6480                 else
6481                         (void) fprintf(stderr, gettext("too many arguments\n"));
6482                 (void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
6483                 return (2);
6484         }
6485
6486         dataset = argv[0];
6487         path = argv[1];
6488
6489         /* try to open the dataset */
6490         if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
6491                 return (1);
6492
6493         (void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
6494             sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
6495
6496         /* check for legacy mountpoint and complain appropriately */
6497         ret = 0;
6498         if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
6499                 if (zmount(dataset, path, flags, MNTTYPE_ZFS,
6500                     NULL, 0, mntopts, sizeof (mntopts)) != 0) {
6501                         (void) fprintf(stderr, gettext("mount failed: %s\n"),
6502                             strerror(errno));
6503                         ret = 1;
6504                 }
6505         } else {
6506                 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
6507                     "mounted using 'mount -t zfs'\n"), dataset);
6508                 (void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
6509                     "instead.\n"), path);
6510                 (void) fprintf(stderr, gettext("If you must use 'mount -t zfs' "
6511                     "or /etc/fstab, use 'zfs set mountpoint=legacy'.\n"));
6512                 (void) fprintf(stderr, gettext("See zfs(8) for more "
6513                     "information.\n"));
6514                 ret = 1;
6515         }
6516
6517         return (ret);
6518 }
6519
6520 /*
6521  * Called when invoked as /etc/fs/zfs/umount.  Unlike a manual mount, we allow
6522  * unmounts of non-legacy filesystems, as this is the dominant administrative
6523  * interface.
6524  */
6525 static int
6526 manual_unmount(int argc, char **argv)
6527 {
6528         int flags = 0;
6529         int c;
6530
6531         /* check options */
6532         while ((c = getopt(argc, argv, "f")) != -1) {
6533                 switch (c) {
6534                 case 'f':
6535                         flags = MS_FORCE;
6536                         break;
6537                 case '?':
6538                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6539                             optopt);
6540                         (void) fprintf(stderr, gettext("usage: unmount [-f] "
6541                             "<path>\n"));
6542                         return (2);
6543                 }
6544         }
6545
6546         argc -= optind;
6547         argv += optind;
6548
6549         /* check arguments */
6550         if (argc != 1) {
6551                 if (argc == 0)
6552                         (void) fprintf(stderr, gettext("missing path "
6553                             "argument\n"));
6554                 else
6555                         (void) fprintf(stderr, gettext("too many arguments\n"));
6556                 (void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
6557                 return (2);
6558         }
6559
6560         return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
6561 }
6562
6563 static int
6564 find_command_idx(char *command, int *idx)
6565 {
6566         int i;
6567
6568         for (i = 0; i < NCOMMAND; i++) {
6569                 if (command_table[i].name == NULL)
6570                         continue;
6571
6572                 if (strcmp(command, command_table[i].name) == 0) {
6573                         *idx = i;
6574                         return (0);
6575                 }
6576         }
6577         return (1);
6578 }
6579
6580 static int
6581 zfs_do_diff(int argc, char **argv)
6582 {
6583         zfs_handle_t *zhp;
6584         int flags = 0;
6585         char *tosnap = NULL;
6586         char *fromsnap = NULL;
6587         char *atp, *copy;
6588         int err = 0;
6589         int c;
6590
6591         while ((c = getopt(argc, argv, "FHt")) != -1) {
6592                 switch (c) {
6593                 case 'F':
6594                         flags |= ZFS_DIFF_CLASSIFY;
6595                         break;
6596                 case 'H':
6597                         flags |= ZFS_DIFF_PARSEABLE;
6598                         break;
6599                 case 't':
6600                         flags |= ZFS_DIFF_TIMESTAMP;
6601                         break;
6602                 default:
6603                         (void) fprintf(stderr,
6604                             gettext("invalid option '%c'\n"), optopt);
6605                         usage(B_FALSE);
6606                 }
6607         }
6608
6609         argc -= optind;
6610         argv += optind;
6611
6612         if (argc < 1) {
6613                 (void) fprintf(stderr,
6614                 gettext("must provide at least one snapshot name\n"));
6615                 usage(B_FALSE);
6616         }
6617
6618         if (argc > 2) {
6619                 (void) fprintf(stderr, gettext("too many arguments\n"));
6620                 usage(B_FALSE);
6621         }
6622
6623         fromsnap = argv[0];
6624         tosnap = (argc == 2) ? argv[1] : NULL;
6625
6626         copy = NULL;
6627         if (*fromsnap != '@')
6628                 copy = strdup(fromsnap);
6629         else if (tosnap)
6630                 copy = strdup(tosnap);
6631         if (copy == NULL)
6632                 usage(B_FALSE);
6633
6634         if (atp = strchr(copy, '@'))
6635                 *atp = '\0';
6636
6637         if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
6638                 return (1);
6639
6640         free(copy);
6641
6642         /*
6643          * Ignore SIGPIPE so that the library can give us
6644          * information on any failure
6645          */
6646         (void) sigignore(SIGPIPE);
6647
6648         err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
6649
6650         zfs_close(zhp);
6651
6652         return (err != 0);
6653 }
6654
6655 int
6656 main(int argc, char **argv)
6657 {
6658         int ret = 0;
6659         int i;
6660         char *progname;
6661         char *cmdname;
6662
6663         (void) setlocale(LC_ALL, "");
6664         (void) textdomain(TEXT_DOMAIN);
6665
6666         opterr = 0;
6667
6668         if ((g_zfs = libzfs_init()) == NULL) {
6669                 (void) fprintf(stderr, gettext("internal error: failed to "
6670                     "initialize ZFS library\n"));
6671                 return (1);
6672         }
6673
6674         zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
6675
6676         libzfs_print_on_error(g_zfs, B_TRUE);
6677
6678         if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
6679                 (void) fprintf(stderr, gettext("internal error: unable to "
6680                     "open %s\n"), MNTTAB);
6681                 return (1);
6682         }
6683
6684         /*
6685          * This command also doubles as the /etc/fs mount and unmount program.
6686          * Determine if we should take this behavior based on argv[0].
6687          */
6688         progname = basename(argv[0]);
6689         if (strcmp(progname, "mount") == 0) {
6690                 ret = manual_mount(argc, argv);
6691         } else if (strcmp(progname, "umount") == 0) {
6692                 ret = manual_unmount(argc, argv);
6693         } else {
6694                 /*
6695                  * Make sure the user has specified some command.
6696                  */
6697                 if (argc < 2) {
6698                         (void) fprintf(stderr, gettext("missing command\n"));
6699                         usage(B_FALSE);
6700                 }
6701
6702                 cmdname = argv[1];
6703
6704                 /*
6705                  * The 'umount' command is an alias for 'unmount'
6706                  */
6707                 if (strcmp(cmdname, "umount") == 0)
6708                         cmdname = "unmount";
6709
6710                 /*
6711                  * The 'recv' command is an alias for 'receive'
6712                  */
6713                 if (strcmp(cmdname, "recv") == 0)
6714                         cmdname = "receive";
6715
6716                 /*
6717                  * The 'snap' command is an alias for 'snapshot'
6718                  */
6719                 if (strcmp(cmdname, "snap") == 0)
6720                         cmdname = "snapshot";
6721
6722                 /*
6723                  * Special case '-?'
6724                  */
6725                 if (strcmp(cmdname, "-?") == 0)
6726                         usage(B_TRUE);
6727
6728                 /*
6729                  * Run the appropriate command.
6730                  */
6731                 libzfs_mnttab_cache(g_zfs, B_TRUE);
6732                 if (find_command_idx(cmdname, &i) == 0) {
6733                         current_command = &command_table[i];
6734                         ret = command_table[i].func(argc - 1, argv + 1);
6735                 } else if (strchr(cmdname, '=') != NULL) {
6736                         verify(find_command_idx("set", &i) == 0);
6737                         current_command = &command_table[i];
6738                         ret = command_table[i].func(argc, argv);
6739                 } else {
6740                         (void) fprintf(stderr, gettext("unrecognized "
6741                             "command '%s'\n"), cmdname);
6742                         usage(B_FALSE);
6743                 }
6744                 libzfs_mnttab_cache(g_zfs, B_FALSE);
6745         }
6746
6747         (void) fclose(mnttab_file);
6748
6749         if (ret == 0 && log_history)
6750                 (void) zpool_log_history(g_zfs, history_str);
6751
6752         libzfs_fini(g_zfs);
6753
6754         /*
6755          * The 'ZFS_ABORT' environment variable causes us to dump core on exit
6756          * for the purposes of running ::findleaks.
6757          */
6758         if (getenv("ZFS_ABORT") != NULL) {
6759                 (void) printf("dumping core by request\n");
6760                 abort();
6761         }
6762
6763         return (ret);
6764 }