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