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