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