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