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