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