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