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