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