Disable umount.zfs helper
[zfs.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  */
25
26 #include <assert.h>
27 #include <ctype.h>
28 #include <errno.h>
29 #include <libgen.h>
30 #include <libintl.h>
31 #include <libuutil.h>
32 #include <libnvpair.h>
33 #include <locale.h>
34 #include <stddef.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <strings.h>
38 #include <unistd.h>
39 #include <fcntl.h>
40 #include <zone.h>
41 #include <grp.h>
42 #include <pwd.h>
43 #include <signal.h>
44 #include <sys/mkdev.h>
45 #include <sys/mntent.h>
46 #include <sys/mnttab.h>
47 #include <sys/mount.h>
48 #include <sys/stat.h>
49 #include <sys/fs/zfs.h>
50 #include <sys/types.h>
51 #include <time.h>
52
53 #include <libzfs.h>
54 #include <libuutil.h>
55
56 #include "zfs_iter.h"
57 #include "zfs_util.h"
58 #include "zfs_comutil.h"
59
60 libzfs_handle_t *g_zfs;
61
62 static FILE *mnttab_file;
63 static char history_str[HIS_MAX_RECORD_LEN];
64 const char *pypath = "/usr/lib/zfs/pyzfs.py";
65
66 static int zfs_do_clone(int argc, char **argv);
67 static int zfs_do_create(int argc, char **argv);
68 static int zfs_do_destroy(int argc, char **argv);
69 static int zfs_do_get(int argc, char **argv);
70 static int zfs_do_inherit(int argc, char **argv);
71 static int zfs_do_list(int argc, char **argv);
72 static int zfs_do_mount(int argc, char **argv);
73 static int zfs_do_rename(int argc, char **argv);
74 static int zfs_do_rollback(int argc, char **argv);
75 static int zfs_do_set(int argc, char **argv);
76 static int zfs_do_upgrade(int argc, char **argv);
77 static int zfs_do_snapshot(int argc, char **argv);
78 static int zfs_do_unmount(int argc, char **argv);
79 static int zfs_do_share(int argc, char **argv);
80 static int zfs_do_unshare(int argc, char **argv);
81 static int zfs_do_send(int argc, char **argv);
82 static int zfs_do_receive(int argc, char **argv);
83 static int zfs_do_promote(int argc, char **argv);
84 static int zfs_do_userspace(int argc, char **argv);
85 static int zfs_do_python(int argc, char **argv);
86 static int zfs_do_hold(int argc, char **argv);
87 static int zfs_do_release(int argc, char **argv);
88 static int zfs_do_diff(int argc, char **argv);
89
90 /*
91  * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
92  */
93
94 #ifdef DEBUG
95 const char *
96 _umem_debug_init(void)
97 {
98         return ("default,verbose"); /* $UMEM_DEBUG setting */
99 }
100
101 const char *
102 _umem_logging_init(void)
103 {
104         return ("fail,contents"); /* $UMEM_LOGGING setting */
105 }
106 #endif
107
108 typedef enum {
109         HELP_CLONE,
110         HELP_CREATE,
111         HELP_DESTROY,
112         HELP_GET,
113         HELP_INHERIT,
114         HELP_UPGRADE,
115         HELP_LIST,
116         HELP_MOUNT,
117         HELP_PROMOTE,
118         HELP_RECEIVE,
119         HELP_RENAME,
120         HELP_ROLLBACK,
121         HELP_SEND,
122         HELP_SET,
123         HELP_SHARE,
124         HELP_SNAPSHOT,
125         HELP_UNMOUNT,
126         HELP_UNSHARE,
127         HELP_ALLOW,
128         HELP_UNALLOW,
129         HELP_USERSPACE,
130         HELP_GROUPSPACE,
131         HELP_HOLD,
132         HELP_HOLDS,
133         HELP_RELEASE,
134         HELP_DIFF
135 } zfs_help_t;
136
137 typedef struct zfs_command {
138         const char      *name;
139         int             (*func)(int argc, char **argv);
140         zfs_help_t      usage;
141 } zfs_command_t;
142
143 /*
144  * Master command table.  Each ZFS command has a name, associated function, and
145  * usage message.  The usage messages need to be internationalized, so we have
146  * to have a function to return the usage message based on a command index.
147  *
148  * These commands are organized according to how they are displayed in the usage
149  * message.  An empty command (one with a NULL name) indicates an empty line in
150  * the generic usage message.
151  */
152 static zfs_command_t command_table[] = {
153         { "create",     zfs_do_create,          HELP_CREATE             },
154         { "destroy",    zfs_do_destroy,         HELP_DESTROY            },
155         { NULL },
156         { "snapshot",   zfs_do_snapshot,        HELP_SNAPSHOT           },
157         { "rollback",   zfs_do_rollback,        HELP_ROLLBACK           },
158         { "clone",      zfs_do_clone,           HELP_CLONE              },
159         { "promote",    zfs_do_promote,         HELP_PROMOTE            },
160         { "rename",     zfs_do_rename,          HELP_RENAME             },
161         { NULL },
162         { "list",       zfs_do_list,            HELP_LIST               },
163         { NULL },
164         { "set",        zfs_do_set,             HELP_SET                },
165         { "get",        zfs_do_get,             HELP_GET                },
166         { "inherit",    zfs_do_inherit,         HELP_INHERIT            },
167         { "upgrade",    zfs_do_upgrade,         HELP_UPGRADE            },
168         { "userspace",  zfs_do_userspace,       HELP_USERSPACE          },
169         { "groupspace", zfs_do_userspace,       HELP_GROUPSPACE         },
170         { NULL },
171         { "mount",      zfs_do_mount,           HELP_MOUNT              },
172         { "unmount",    zfs_do_unmount,         HELP_UNMOUNT            },
173         { "share",      zfs_do_share,           HELP_SHARE              },
174         { "unshare",    zfs_do_unshare,         HELP_UNSHARE            },
175         { NULL },
176         { "send",       zfs_do_send,            HELP_SEND               },
177         { "receive",    zfs_do_receive,         HELP_RECEIVE            },
178         { NULL },
179         { "allow",      zfs_do_python,          HELP_ALLOW              },
180         { NULL },
181         { "unallow",    zfs_do_python,          HELP_UNALLOW            },
182         { NULL },
183         { "hold",       zfs_do_hold,            HELP_HOLD               },
184         { "holds",      zfs_do_python,          HELP_HOLDS              },
185         { "release",    zfs_do_release,         HELP_RELEASE            },
186         { "diff",       zfs_do_diff,            HELP_DIFF               },
187 };
188
189 #define NCOMMAND        (sizeof (command_table) / sizeof (command_table[0]))
190
191 zfs_command_t *current_command;
192
193 static const char *
194 get_usage(zfs_help_t idx)
195 {
196         switch (idx) {
197         case HELP_CLONE:
198                 return (gettext("\tclone [-p] [-o property=value] ... "
199                     "<snapshot> <filesystem|volume>\n"));
200         case HELP_CREATE:
201                 return (gettext("\tcreate [-p] [-o property=value] ... "
202                     "<filesystem>\n"
203                     "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
204                     "-V <size> <volume>\n"));
205         case HELP_DESTROY:
206                 return (gettext("\tdestroy [-rRf] <filesystem|volume>\n"
207                     "\tdestroy [-rRd] <snapshot>\n"));
208         case HELP_GET:
209                 return (gettext("\tget [-rHp] [-d max] "
210                     "[-o \"all\" | field[,...]] [-s source[,...]]\n"
211                     "\t    <\"all\" | property[,...]> "
212                     "[filesystem|volume|snapshot] ...\n"));
213         case HELP_INHERIT:
214                 return (gettext("\tinherit [-rS] <property> "
215                     "<filesystem|volume|snapshot> ...\n"));
216         case HELP_UPGRADE:
217                 return (gettext("\tupgrade [-v]\n"
218                     "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
219         case HELP_LIST:
220                 return (gettext("\tlist [-rH][-d max] "
221                     "[-o property[,...]] [-t type[,...]] [-s property] ...\n"
222                     "\t    [-S property] ... "
223                     "[filesystem|volume|snapshot] ...\n"));
224         case HELP_MOUNT:
225                 return (gettext("\tmount\n"
226                     "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
227         case HELP_PROMOTE:
228                 return (gettext("\tpromote <clone-filesystem>\n"));
229         case HELP_RECEIVE:
230                 return (gettext("\treceive [-vnFu] <filesystem|volume|"
231                 "snapshot>\n"
232                 "\treceive [-vnFu] [-d | -e] <filesystem>\n"));
233         case HELP_RENAME:
234                 return (gettext("\trename <filesystem|volume|snapshot> "
235                     "<filesystem|volume|snapshot>\n"
236                     "\trename -p <filesystem|volume> <filesystem|volume>\n"
237                     "\trename -r <snapshot> <snapshot>"));
238         case HELP_ROLLBACK:
239                 return (gettext("\trollback [-rRf] <snapshot>\n"));
240         case HELP_SEND:
241                 return (gettext("\tsend [-RDp] [-[iI] snapshot] <snapshot>\n"));
242         case HELP_SET:
243                 return (gettext("\tset <property=value> "
244                     "<filesystem|volume|snapshot> ...\n"));
245         case HELP_SHARE:
246                 return (gettext("\tshare <-a | filesystem>\n"));
247         case HELP_SNAPSHOT:
248                 return (gettext("\tsnapshot [-r] [-o property=value] ... "
249                     "<filesystem@snapname|volume@snapname>\n"));
250         case HELP_UNMOUNT:
251                 return (gettext("\tunmount [-f] "
252                     "<-a | filesystem|mountpoint>\n"));
253         case HELP_UNSHARE:
254                 return (gettext("\tunshare "
255                     "<-a | filesystem|mountpoint>\n"));
256         case HELP_ALLOW:
257                 return (gettext("\tallow <filesystem|volume>\n"
258                     "\tallow [-ldug] "
259                     "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
260                     "\t    <filesystem|volume>\n"
261                     "\tallow [-ld] -e <perm|@setname>[,...] "
262                     "<filesystem|volume>\n"
263                     "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
264                     "\tallow -s @setname <perm|@setname>[,...] "
265                     "<filesystem|volume>\n"));
266         case HELP_UNALLOW:
267                 return (gettext("\tunallow [-rldug] "
268                     "<\"everyone\"|user|group>[,...]\n"
269                     "\t    [<perm|@setname>[,...]] <filesystem|volume>\n"
270                     "\tunallow [-rld] -e [<perm|@setname>[,...]] "
271                     "<filesystem|volume>\n"
272                     "\tunallow [-r] -c [<perm|@setname>[,...]] "
273                     "<filesystem|volume>\n"
274                     "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
275                     "<filesystem|volume>\n"));
276         case HELP_USERSPACE:
277                 return (gettext("\tuserspace [-hniHp] [-o field[,...]] "
278                     "[-sS field] ... [-t type[,...]]\n"
279                     "\t    <filesystem|snapshot>\n"));
280         case HELP_GROUPSPACE:
281                 return (gettext("\tgroupspace [-hniHpU] [-o field[,...]] "
282                     "[-sS field] ... [-t type[,...]]\n"
283                     "\t    <filesystem|snapshot>\n"));
284         case HELP_HOLD:
285                 return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
286         case HELP_HOLDS:
287                 return (gettext("\tholds [-r] <snapshot> ...\n"));
288         case HELP_RELEASE:
289                 return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
290         case HELP_DIFF:
291                 return (gettext("\tdiff [-FHt] <snapshot> "
292                     "[snapshot|filesystem]\n"));
293         }
294
295         abort();
296         /* NOTREACHED */
297 }
298
299 void
300 nomem(void)
301 {
302         (void) fprintf(stderr, gettext("internal error: out of memory\n"));
303         exit(1);
304 }
305
306 /*
307  * Utility function to guarantee malloc() success.
308  */
309
310 void *
311 safe_malloc(size_t size)
312 {
313         void *data;
314
315         if ((data = calloc(1, size)) == NULL)
316                 nomem();
317
318         return (data);
319 }
320
321 #ifdef HAVE_ZPL
322 static char *
323 safe_strdup(char *str)
324 {
325         char *dupstr = strdup(str);
326
327         if (dupstr == NULL)
328                 nomem();
329
330         return (dupstr);
331 }
332 #endif /* HAVE_ZPL */
333
334 /*
335  * Callback routine that will print out information for each of
336  * the properties.
337  */
338 static int
339 usage_prop_cb(int prop, void *cb)
340 {
341         FILE *fp = cb;
342
343         (void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
344
345         if (zfs_prop_readonly(prop))
346                 (void) fprintf(fp, " NO    ");
347         else
348                 (void) fprintf(fp, "YES    ");
349
350         if (zfs_prop_inheritable(prop))
351                 (void) fprintf(fp, "  YES   ");
352         else
353                 (void) fprintf(fp, "   NO   ");
354
355         if (zfs_prop_values(prop) == NULL)
356                 (void) fprintf(fp, "-\n");
357         else
358                 (void) fprintf(fp, "%s\n", zfs_prop_values(prop));
359
360         return (ZPROP_CONT);
361 }
362
363 /*
364  * Display usage message.  If we're inside a command, display only the usage for
365  * that command.  Otherwise, iterate over the entire command table and display
366  * a complete usage message.
367  */
368 static void
369 usage(boolean_t requested)
370 {
371         int i;
372         boolean_t show_properties = B_FALSE;
373         FILE *fp = requested ? stdout : stderr;
374
375         if (current_command == NULL) {
376
377                 (void) fprintf(fp, gettext("usage: zfs command args ...\n"));
378                 (void) fprintf(fp,
379                     gettext("where 'command' is one of the following:\n\n"));
380
381                 for (i = 0; i < NCOMMAND; i++) {
382                         if (command_table[i].name == NULL)
383                                 (void) fprintf(fp, "\n");
384                         else
385                                 (void) fprintf(fp, "%s",
386                                     get_usage(command_table[i].usage));
387                 }
388
389                 (void) fprintf(fp, gettext("\nEach dataset is of the form: "
390                     "pool/[dataset/]*dataset[@name]\n"));
391         } else {
392                 (void) fprintf(fp, gettext("usage:\n"));
393                 (void) fprintf(fp, "%s", get_usage(current_command->usage));
394         }
395
396         if (current_command != NULL &&
397             (strcmp(current_command->name, "set") == 0 ||
398             strcmp(current_command->name, "get") == 0 ||
399             strcmp(current_command->name, "inherit") == 0 ||
400             strcmp(current_command->name, "list") == 0))
401                 show_properties = B_TRUE;
402
403         if (show_properties) {
404                 (void) fprintf(fp,
405                     gettext("\nThe following properties are supported:\n"));
406
407                 (void) fprintf(fp, "\n\t%-14s %s  %s   %s\n\n",
408                     "PROPERTY", "EDIT", "INHERIT", "VALUES");
409
410                 /* Iterate over all properties */
411                 (void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
412                     ZFS_TYPE_DATASET);
413
414                 (void) fprintf(fp, "\t%-15s ", "userused@...");
415                 (void) fprintf(fp, " NO       NO   <size>\n");
416                 (void) fprintf(fp, "\t%-15s ", "groupused@...");
417                 (void) fprintf(fp, " NO       NO   <size>\n");
418                 (void) fprintf(fp, "\t%-15s ", "userquota@...");
419                 (void) fprintf(fp, "YES       NO   <size> | none\n");
420                 (void) fprintf(fp, "\t%-15s ", "groupquota@...");
421                 (void) fprintf(fp, "YES       NO   <size> | none\n");
422
423                 (void) fprintf(fp, gettext("\nSizes are specified in bytes "
424                     "with standard units such as K, M, G, etc.\n"));
425                 (void) fprintf(fp, gettext("\nUser-defined properties can "
426                     "be specified by using a name containing a colon (:).\n"));
427                 (void) fprintf(fp, gettext("\nThe {user|group}{used|quota}@ "
428                     "properties must be appended with\n"
429                     "a user or group specifier of one of these forms:\n"
430                     "    POSIX name      (eg: \"matt\")\n"
431                     "    POSIX id        (eg: \"126829\")\n"
432                     "    SMB name@domain (eg: \"matt@sun\")\n"
433                     "    SMB SID         (eg: \"S-1-234-567-89\")\n"));
434         } else {
435                 (void) fprintf(fp,
436                     gettext("\nFor the property list, run: %s\n"),
437                     "zfs set|get");
438                 (void) fprintf(fp,
439                     gettext("\nFor the delegated permission list, run: %s\n"),
440                     "zfs allow|unallow");
441         }
442
443         /*
444          * See comments at end of main().
445          */
446         if (getenv("ZFS_ABORT") != NULL) {
447                 (void) printf("dumping core by request\n");
448                 abort();
449         }
450
451         exit(requested ? 0 : 2);
452 }
453
454 static int
455 parseprop(nvlist_t *props)
456 {
457         char *propname = optarg;
458         char *propval, *strval;
459
460         if ((propval = strchr(propname, '=')) == NULL) {
461                 (void) fprintf(stderr, gettext("missing "
462                     "'=' for -o option\n"));
463                 return (-1);
464         }
465         *propval = '\0';
466         propval++;
467         if (nvlist_lookup_string(props, propname, &strval) == 0) {
468                 (void) fprintf(stderr, gettext("property '%s' "
469                     "specified multiple times\n"), propname);
470                 return (-1);
471         }
472         if (nvlist_add_string(props, propname, propval) != 0)
473                 nomem();
474         return (0);
475 }
476
477 static int
478 parse_depth(char *opt, int *flags)
479 {
480         char *tmp;
481         int depth;
482
483         depth = (int)strtol(opt, &tmp, 0);
484         if (*tmp) {
485                 (void) fprintf(stderr,
486                     gettext("%s is not an integer\n"), optarg);
487                 usage(B_FALSE);
488         }
489         if (depth < 0) {
490                 (void) fprintf(stderr,
491                     gettext("Depth can not be negative.\n"));
492                 usage(B_FALSE);
493         }
494         *flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
495         return (depth);
496 }
497
498 #define PROGRESS_DELAY 2                /* seconds */
499
500 #ifdef HAVE_ZPL
501 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";
502 static time_t pt_begin;
503 static char *pt_header = NULL;
504 static boolean_t pt_shown;
505
506 static void
507 start_progress_timer(void)
508 {
509         pt_begin = time(NULL) + PROGRESS_DELAY;
510         pt_shown = B_FALSE;
511 }
512
513 static void
514 set_progress_header(char *header)
515 {
516         assert(pt_header == NULL);
517         pt_header = safe_strdup(header);
518         if (pt_shown) {
519                 (void) printf("%s: ", header);
520                 (void) fflush(stdout);
521         }
522 }
523
524 static void
525 update_progress(char *update)
526 {
527         if (!pt_shown && time(NULL) > pt_begin) {
528                 int len = strlen(update);
529
530                 (void) printf("%s: %s%*.*s", pt_header, update, len, len,
531                     pt_reverse);
532                 (void) fflush(stdout);
533                 pt_shown = B_TRUE;
534         } else if (pt_shown) {
535                 int len = strlen(update);
536
537                 (void) printf("%s%*.*s", update, len, len, pt_reverse);
538                 (void) fflush(stdout);
539         }
540 }
541
542 static void
543 finish_progress(char *done)
544 {
545         if (pt_shown) {
546                 (void) printf("%s\n", done);
547                 (void) fflush(stdout);
548         }
549         free(pt_header);
550         pt_header = NULL;
551 }
552 #endif /* HAVE_ZPL */
553
554 /*
555  * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
556  *
557  * Given an existing dataset, create a writable copy whose initial contents
558  * are the same as the source.  The newly created dataset maintains a
559  * dependency on the original; the original cannot be destroyed so long as
560  * the clone exists.
561  *
562  * The '-p' flag creates all the non-existing ancestors of the target first.
563  */
564 static int
565 zfs_do_clone(int argc, char **argv)
566 {
567         zfs_handle_t *zhp = NULL;
568         boolean_t parents = B_FALSE;
569         nvlist_t *props;
570         int ret;
571         int c;
572
573         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
574                 nomem();
575
576         /* check options */
577         while ((c = getopt(argc, argv, "o:p")) != -1) {
578                 switch (c) {
579                 case 'o':
580                         if (parseprop(props))
581                                 return (1);
582                         break;
583                 case 'p':
584                         parents = B_TRUE;
585                         break;
586                 case '?':
587                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
588                             optopt);
589                         goto usage;
590                 }
591         }
592
593         argc -= optind;
594         argv += optind;
595
596         /* check number of arguments */
597         if (argc < 1) {
598                 (void) fprintf(stderr, gettext("missing source dataset "
599                     "argument\n"));
600                 goto usage;
601         }
602         if (argc < 2) {
603                 (void) fprintf(stderr, gettext("missing target dataset "
604                     "argument\n"));
605                 goto usage;
606         }
607         if (argc > 2) {
608                 (void) fprintf(stderr, gettext("too many arguments\n"));
609                 goto usage;
610         }
611
612         /* open the source dataset */
613         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
614                 return (1);
615
616         if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
617             ZFS_TYPE_VOLUME)) {
618                 /*
619                  * Now create the ancestors of the target dataset.  If the
620                  * target already exists and '-p' option was used we should not
621                  * complain.
622                  */
623                 if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
624                     ZFS_TYPE_VOLUME))
625                         return (0);
626                 if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
627                         return (1);
628         }
629
630         /* pass to libzfs */
631         ret = zfs_clone(zhp, argv[1], props);
632
633         /* create the mountpoint if necessary */
634 #ifdef HAVE_ZPL
635         if (ret == 0) {
636                 zfs_handle_t *clone;
637
638                 clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
639                 if (clone != NULL) {
640                         if (zfs_get_type(clone) != ZFS_TYPE_VOLUME)
641                                 if ((ret = zfs_mount(clone, NULL, 0)) == 0)
642                                         ret = zfs_share(clone);
643                         zfs_close(clone);
644                 }
645         }
646 #endif /* HAVE_ZPL */
647
648         zfs_close(zhp);
649         nvlist_free(props);
650
651         return (!!ret);
652
653 usage:
654         if (zhp)
655                 zfs_close(zhp);
656         nvlist_free(props);
657         usage(B_FALSE);
658         return (-1);
659 }
660
661 /*
662  * zfs create [-p] [-o prop=value] ... fs
663  * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
664  *
665  * Create a new dataset.  This command can be used to create filesystems
666  * and volumes.  Snapshot creation is handled by 'zfs snapshot'.
667  * For volumes, the user must specify a size to be used.
668  *
669  * The '-s' flag applies only to volumes, and indicates that we should not try
670  * to set the reservation for this volume.  By default we set a reservation
671  * equal to the size for any volume.  For pools with SPA_VERSION >=
672  * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
673  *
674  * The '-p' flag creates all the non-existing ancestors of the target first.
675  */
676 static int
677 zfs_do_create(int argc, char **argv)
678 {
679         zfs_type_t type = ZFS_TYPE_FILESYSTEM;
680         zfs_handle_t *zhp = NULL;
681         uint64_t volsize = 0;
682         int c;
683         boolean_t noreserve = B_FALSE;
684         boolean_t bflag = B_FALSE;
685         boolean_t parents = B_FALSE;
686         int ret = 1;
687         nvlist_t *props;
688         uint64_t intval;
689         int canmount = ZFS_CANMOUNT_OFF;
690
691         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
692                 nomem();
693
694         /* check options */
695         while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
696                 switch (c) {
697                 case 'V':
698                         type = ZFS_TYPE_VOLUME;
699                         if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
700                                 (void) fprintf(stderr, gettext("bad volume "
701                                     "size '%s': %s\n"), optarg,
702                                     libzfs_error_description(g_zfs));
703                                 goto error;
704                         }
705
706                         if (nvlist_add_uint64(props,
707                             zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
708                                 nomem();
709                         volsize = intval;
710                         break;
711                 case 'p':
712                         parents = B_TRUE;
713                         break;
714                 case 'b':
715                         bflag = B_TRUE;
716                         if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
717                                 (void) fprintf(stderr, gettext("bad volume "
718                                     "block size '%s': %s\n"), optarg,
719                                     libzfs_error_description(g_zfs));
720                                 goto error;
721                         }
722
723                         if (nvlist_add_uint64(props,
724                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
725                             intval) != 0)
726                                 nomem();
727                         break;
728                 case 'o':
729                         if (parseprop(props))
730                                 goto error;
731                         break;
732                 case 's':
733                         noreserve = B_TRUE;
734                         break;
735                 case ':':
736                         (void) fprintf(stderr, gettext("missing size "
737                             "argument\n"));
738                         goto badusage;
739                         break;
740                 case '?':
741                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
742                             optopt);
743                         goto badusage;
744                 }
745         }
746
747         if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
748                 (void) fprintf(stderr, gettext("'-s' and '-b' can only be "
749                     "used when creating a volume\n"));
750                 goto badusage;
751         }
752
753         argc -= optind;
754         argv += optind;
755
756         /* check number of arguments */
757         if (argc == 0) {
758                 (void) fprintf(stderr, gettext("missing %s argument\n"),
759                     zfs_type_to_name(type));
760                 goto badusage;
761         }
762         if (argc > 1) {
763                 (void) fprintf(stderr, gettext("too many arguments\n"));
764                 goto badusage;
765         }
766
767         if (type == ZFS_TYPE_VOLUME && !noreserve) {
768                 zpool_handle_t *zpool_handle;
769                 uint64_t spa_version;
770                 char *p;
771                 zfs_prop_t resv_prop;
772                 char *strval;
773
774                 if ((p = strchr(argv[0], '/')))
775                         *p = '\0';
776                 zpool_handle = zpool_open(g_zfs, argv[0]);
777                 if (p != NULL)
778                         *p = '/';
779                 if (zpool_handle == NULL)
780                         goto error;
781                 spa_version = zpool_get_prop_int(zpool_handle,
782                     ZPOOL_PROP_VERSION, NULL);
783                 zpool_close(zpool_handle);
784                 if (spa_version >= SPA_VERSION_REFRESERVATION)
785                         resv_prop = ZFS_PROP_REFRESERVATION;
786                 else
787                         resv_prop = ZFS_PROP_RESERVATION;
788                 volsize = zvol_volsize_to_reservation(volsize, props);
789
790                 if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
791                     &strval) != 0) {
792                         if (nvlist_add_uint64(props,
793                             zfs_prop_to_name(resv_prop), volsize) != 0) {
794                                 nvlist_free(props);
795                                 nomem();
796                         }
797                 }
798         }
799
800         if (parents && zfs_name_valid(argv[0], type)) {
801                 /*
802                  * Now create the ancestors of target dataset.  If the target
803                  * already exists and '-p' option was used we should not
804                  * complain.
805                  */
806                 if (zfs_dataset_exists(g_zfs, argv[0], type)) {
807                         ret = 0;
808                         goto error;
809                 }
810                 if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
811                         goto error;
812         }
813
814         /* pass to libzfs */
815         if (zfs_create(g_zfs, argv[0], type, props) != 0)
816                 goto error;
817
818         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
819                 goto error;
820
821         ret = 0;
822         /*
823          * if the user doesn't want the dataset automatically mounted,
824          * then skip the mount/share step
825          */
826         if (zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, type))
827                 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
828
829         /*
830          * Mount and/or share the new filesystem as appropriate.  We provide a
831          * verbose error message to let the user know that their filesystem was
832          * in fact created, even if we failed to mount or share it.
833          */
834 #ifdef HAVE_ZPL
835         if (canmount == ZFS_CANMOUNT_ON) {
836                 if (zfs_mount(zhp, NULL, 0) != 0) {
837                         (void) fprintf(stderr, gettext("filesystem "
838                             "successfully created, but not mounted\n"));
839                         ret = 1;
840                 } else if (zfs_share(zhp) != 0) {
841                         (void) fprintf(stderr, gettext("filesystem "
842                             "successfully created, but not shared\n"));
843                         ret = 1;
844                 }
845         }
846 #endif /* HAVE_ZPL */
847
848 error:
849         if (zhp)
850                 zfs_close(zhp);
851         nvlist_free(props);
852         return (ret);
853 badusage:
854         nvlist_free(props);
855         usage(B_FALSE);
856         return (2);
857 }
858
859 /*
860  * zfs destroy [-rRf] <fs, vol>
861  * zfs destroy [-rRd] <snap>
862  *
863  *      -r      Recursively destroy all children
864  *      -R      Recursively destroy all dependents, including clones
865  *      -f      Force unmounting of any dependents
866  *      -d      If we can't destroy now, mark for deferred destruction
867  *
868  * Destroys the given dataset.  By default, it will unmount any filesystems,
869  * and refuse to destroy a dataset that has any dependents.  A dependent can
870  * either be a child, or a clone of a child.
871  */
872 typedef struct destroy_cbdata {
873         boolean_t       cb_first;
874         int             cb_force;
875         int             cb_recurse;
876         int             cb_error;
877         int             cb_needforce;
878         int             cb_doclones;
879         boolean_t       cb_closezhp;
880         zfs_handle_t    *cb_target;
881         char            *cb_snapname;
882         boolean_t       cb_defer_destroy;
883 } destroy_cbdata_t;
884
885 /*
886  * Check for any dependents based on the '-r' or '-R' flags.
887  */
888 static int
889 destroy_check_dependent(zfs_handle_t *zhp, void *data)
890 {
891         destroy_cbdata_t *cbp = data;
892         const char *tname = zfs_get_name(cbp->cb_target);
893         const char *name = zfs_get_name(zhp);
894
895         if (strncmp(tname, name, strlen(tname)) == 0 &&
896             (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
897                 /*
898                  * This is a direct descendant, not a clone somewhere else in
899                  * the hierarchy.
900                  */
901                 if (cbp->cb_recurse)
902                         goto out;
903
904                 if (cbp->cb_first) {
905                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
906                             "%s has children\n"),
907                             zfs_get_name(cbp->cb_target),
908                             zfs_type_to_name(zfs_get_type(cbp->cb_target)));
909                         (void) fprintf(stderr, gettext("use '-r' to destroy "
910                             "the following datasets:\n"));
911                         cbp->cb_first = B_FALSE;
912                         cbp->cb_error = 1;
913                 }
914
915                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
916         } else {
917                 /*
918                  * This is a clone.  We only want to report this if the '-r'
919                  * wasn't specified, or the target is a snapshot.
920                  */
921                 if (!cbp->cb_recurse &&
922                     zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
923                         goto out;
924
925                 if (cbp->cb_first) {
926                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
927                             "%s has dependent clones\n"),
928                             zfs_get_name(cbp->cb_target),
929                             zfs_type_to_name(zfs_get_type(cbp->cb_target)));
930                         (void) fprintf(stderr, gettext("use '-R' to destroy "
931                             "the following datasets:\n"));
932                         cbp->cb_first = B_FALSE;
933                         cbp->cb_error = 1;
934                 }
935
936                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
937         }
938
939 out:
940         zfs_close(zhp);
941         return (0);
942 }
943
944 static int
945 destroy_callback(zfs_handle_t *zhp, void *data)
946 {
947         destroy_cbdata_t *cbp = data;
948
949         /*
950          * Ignore pools (which we've already flagged as an error before getting
951          * here).
952          */
953         if (strchr(zfs_get_name(zhp), '/') == NULL &&
954             zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
955                 zfs_close(zhp);
956                 return (0);
957         }
958
959         /*
960          * Bail out on the first error.
961          */
962         if (zfs_unmount(zhp, NULL, cbp->cb_force ? MS_FORCE : 0) != 0 ||
963             zfs_destroy(zhp, cbp->cb_defer_destroy) != 0) {
964                 zfs_close(zhp);
965                 return (-1);
966         }
967
968         zfs_close(zhp);
969         return (0);
970 }
971
972 static int
973 destroy_snap_clones(zfs_handle_t *zhp, void *arg)
974 {
975         destroy_cbdata_t *cbp = arg;
976         char thissnap[MAXPATHLEN];
977         zfs_handle_t *szhp;
978         boolean_t closezhp = cbp->cb_closezhp;
979         int rv;
980
981         (void) snprintf(thissnap, sizeof (thissnap),
982             "%s@%s", zfs_get_name(zhp), cbp->cb_snapname);
983
984         libzfs_print_on_error(g_zfs, B_FALSE);
985         szhp = zfs_open(g_zfs, thissnap, ZFS_TYPE_SNAPSHOT);
986         libzfs_print_on_error(g_zfs, B_TRUE);
987         if (szhp) {
988                 /*
989                  * Destroy any clones of this snapshot
990                  */
991                 if (zfs_iter_dependents(szhp, B_FALSE, destroy_callback,
992                     cbp) != 0) {
993                         zfs_close(szhp);
994                         if (closezhp)
995                                 zfs_close(zhp);
996                         return (-1);
997                 }
998                 zfs_close(szhp);
999         }
1000
1001         cbp->cb_closezhp = B_TRUE;
1002         rv = zfs_iter_filesystems(zhp, destroy_snap_clones, arg);
1003         if (closezhp)
1004                 zfs_close(zhp);
1005         return (rv);
1006 }
1007
1008 static int
1009 zfs_do_destroy(int argc, char **argv)
1010 {
1011         destroy_cbdata_t cb = { 0 };
1012         int c;
1013         zfs_handle_t *zhp;
1014         char *cp;
1015         zfs_type_t type = ZFS_TYPE_DATASET;
1016
1017         /* check options */
1018         while ((c = getopt(argc, argv, "dfrR")) != -1) {
1019                 switch (c) {
1020                 case 'd':
1021                         cb.cb_defer_destroy = B_TRUE;
1022                         type = ZFS_TYPE_SNAPSHOT;
1023                         break;
1024                 case 'f':
1025                         cb.cb_force = 1;
1026                         break;
1027                 case 'r':
1028                         cb.cb_recurse = 1;
1029                         break;
1030                 case 'R':
1031                         cb.cb_recurse = 1;
1032                         cb.cb_doclones = 1;
1033                         break;
1034                 case '?':
1035                 default:
1036                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1037                             optopt);
1038                         usage(B_FALSE);
1039                 }
1040         }
1041
1042         argc -= optind;
1043         argv += optind;
1044
1045         /* check number of arguments */
1046         if (argc == 0) {
1047                 (void) fprintf(stderr, gettext("missing path argument\n"));
1048                 usage(B_FALSE);
1049         }
1050         if (argc > 1) {
1051                 (void) fprintf(stderr, gettext("too many arguments\n"));
1052                 usage(B_FALSE);
1053         }
1054
1055         /*
1056          * If we are doing recursive destroy of a snapshot, then the
1057          * named snapshot may not exist.  Go straight to libzfs.
1058          */
1059         if (cb.cb_recurse && (cp = strchr(argv[0], '@'))) {
1060                 int ret;
1061
1062                 *cp = '\0';
1063                 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
1064                         return (1);
1065                 *cp = '@';
1066                 cp++;
1067
1068                 if (cb.cb_doclones) {
1069                         boolean_t defer = cb.cb_defer_destroy;
1070
1071                         /*
1072                          * Temporarily ignore the defer_destroy setting since
1073                          * it's not supported for clones.
1074                          */
1075                         cb.cb_defer_destroy = B_FALSE;
1076                         cb.cb_snapname = cp;
1077                         if (destroy_snap_clones(zhp, &cb) != 0) {
1078                                 zfs_close(zhp);
1079                                 return (1);
1080                         }
1081                         cb.cb_defer_destroy = defer;
1082                 }
1083
1084                 ret = zfs_destroy_snaps(zhp, cp, cb.cb_defer_destroy);
1085                 zfs_close(zhp);
1086                 if (ret) {
1087                         (void) fprintf(stderr,
1088                             gettext("no snapshots destroyed\n"));
1089                 }
1090                 return (ret != 0);
1091         }
1092
1093         /* Open the given dataset */
1094         if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1095                 return (1);
1096
1097         cb.cb_target = zhp;
1098
1099         /*
1100          * Perform an explicit check for pools before going any further.
1101          */
1102         if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1103             zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1104                 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1105                     "operation does not apply to pools\n"),
1106                     zfs_get_name(zhp));
1107                 (void) fprintf(stderr, gettext("use 'zfs destroy -r "
1108                     "%s' to destroy all datasets in the pool\n"),
1109                     zfs_get_name(zhp));
1110                 (void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1111                     "to destroy the pool itself\n"), zfs_get_name(zhp));
1112                 zfs_close(zhp);
1113                 return (1);
1114         }
1115
1116         /*
1117          * Check for any dependents and/or clones.
1118          */
1119         cb.cb_first = B_TRUE;
1120         if (!cb.cb_doclones && !cb.cb_defer_destroy &&
1121             zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
1122             &cb) != 0) {
1123                 zfs_close(zhp);
1124                 return (1);
1125         }
1126
1127         if (cb.cb_error || (!cb.cb_defer_destroy &&
1128             (zfs_iter_dependents(zhp, B_FALSE, destroy_callback, &cb) != 0))) {
1129                 zfs_close(zhp);
1130                 return (1);
1131         }
1132
1133         /*
1134          * Do the real thing.  The callback will close the handle regardless of
1135          * whether it succeeds or not.
1136          */
1137
1138         if (destroy_callback(zhp, &cb) != 0)
1139                 return (1);
1140
1141         return (0);
1142 }
1143
1144 static boolean_t
1145 is_recvd_column(zprop_get_cbdata_t *cbp)
1146 {
1147         int i;
1148         zfs_get_column_t col;
1149
1150         for (i = 0; i < ZFS_GET_NCOLS &&
1151             (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1152                 if (col == GET_COL_RECVD)
1153                         return (B_TRUE);
1154         return (B_FALSE);
1155 }
1156
1157 /*
1158  * zfs get [-rHp] [-o all | field[,field]...] [-s source[,source]...]
1159  *      < all | property[,property]... > < fs | snap | vol > ...
1160  *
1161  *      -r      recurse over any child datasets
1162  *      -H      scripted mode.  Headers are stripped, and fields are separated
1163  *              by tabs instead of spaces.
1164  *      -o      Set of fields to display.  One of "name,property,value,
1165  *              received,source". Default is "name,property,value,source".
1166  *              "all" is an alias for all five.
1167  *      -s      Set of sources to allow.  One of
1168  *              "local,default,inherited,received,temporary,none".  Default is
1169  *              all six.
1170  *      -p      Display values in parsable (literal) format.
1171  *
1172  *  Prints properties for the given datasets.  The user can control which
1173  *  columns to display as well as which property types to allow.
1174  */
1175
1176 /*
1177  * Invoked to display the properties for a single dataset.
1178  */
1179 static int
1180 get_callback(zfs_handle_t *zhp, void *data)
1181 {
1182         char buf[ZFS_MAXPROPLEN];
1183         char rbuf[ZFS_MAXPROPLEN];
1184         zprop_source_t sourcetype;
1185         char source[ZFS_MAXNAMELEN];
1186         zprop_get_cbdata_t *cbp = data;
1187         nvlist_t *user_props = zfs_get_user_props(zhp);
1188         zprop_list_t *pl = cbp->cb_proplist;
1189         nvlist_t *propval;
1190         char *strval;
1191         char *sourceval;
1192         boolean_t received = is_recvd_column(cbp);
1193
1194         for (; pl != NULL; pl = pl->pl_next) {
1195                 char *recvdval = NULL;
1196                 /*
1197                  * Skip the special fake placeholder.  This will also skip over
1198                  * the name property when 'all' is specified.
1199                  */
1200                 if (pl->pl_prop == ZFS_PROP_NAME &&
1201                     pl == cbp->cb_proplist)
1202                         continue;
1203
1204                 if (pl->pl_prop != ZPROP_INVAL) {
1205                         if (zfs_prop_get(zhp, pl->pl_prop, buf,
1206                             sizeof (buf), &sourcetype, source,
1207                             sizeof (source),
1208                             cbp->cb_literal) != 0) {
1209                                 if (pl->pl_all)
1210                                         continue;
1211                                 if (!zfs_prop_valid_for_type(pl->pl_prop,
1212                                     ZFS_TYPE_DATASET)) {
1213                                         (void) fprintf(stderr,
1214                                             gettext("No such property '%s'\n"),
1215                                             zfs_prop_to_name(pl->pl_prop));
1216                                         continue;
1217                                 }
1218                                 sourcetype = ZPROP_SRC_NONE;
1219                                 (void) strlcpy(buf, "-", sizeof (buf));
1220                         }
1221
1222                         if (received && (zfs_prop_get_recvd(zhp,
1223                             zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
1224                             cbp->cb_literal) == 0))
1225                                 recvdval = rbuf;
1226
1227                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1228                             zfs_prop_to_name(pl->pl_prop),
1229                             buf, sourcetype, source, recvdval);
1230                 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
1231                         sourcetype = ZPROP_SRC_LOCAL;
1232
1233                         if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1234                             buf, sizeof (buf), cbp->cb_literal) != 0) {
1235                                 sourcetype = ZPROP_SRC_NONE;
1236                                 (void) strlcpy(buf, "-", sizeof (buf));
1237                         }
1238
1239                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1240                             pl->pl_user_prop, buf, sourcetype, source, NULL);
1241                 } else {
1242                         if (nvlist_lookup_nvlist(user_props,
1243                             pl->pl_user_prop, &propval) != 0) {
1244                                 if (pl->pl_all)
1245                                         continue;
1246                                 sourcetype = ZPROP_SRC_NONE;
1247                                 strval = "-";
1248                         } else {
1249                                 verify(nvlist_lookup_string(propval,
1250                                     ZPROP_VALUE, &strval) == 0);
1251                                 verify(nvlist_lookup_string(propval,
1252                                     ZPROP_SOURCE, &sourceval) == 0);
1253
1254                                 if (strcmp(sourceval,
1255                                     zfs_get_name(zhp)) == 0) {
1256                                         sourcetype = ZPROP_SRC_LOCAL;
1257                                 } else if (strcmp(sourceval,
1258                                     ZPROP_SOURCE_VAL_RECVD) == 0) {
1259                                         sourcetype = ZPROP_SRC_RECEIVED;
1260                                 } else {
1261                                         sourcetype = ZPROP_SRC_INHERITED;
1262                                         (void) strlcpy(source,
1263                                             sourceval, sizeof (source));
1264                                 }
1265                         }
1266
1267                         if (received && (zfs_prop_get_recvd(zhp,
1268                             pl->pl_user_prop, rbuf, sizeof (rbuf),
1269                             cbp->cb_literal) == 0))
1270                                 recvdval = rbuf;
1271
1272                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1273                             pl->pl_user_prop, strval, sourcetype,
1274                             source, recvdval);
1275                 }
1276         }
1277
1278         return (0);
1279 }
1280
1281 static int
1282 zfs_do_get(int argc, char **argv)
1283 {
1284         zprop_get_cbdata_t cb = { 0 };
1285         int i, c, flags = 0;
1286         char *value, *fields;
1287         int ret;
1288         int limit = 0;
1289         zprop_list_t fake_name = { 0 };
1290
1291         /*
1292          * Set up default columns and sources.
1293          */
1294         cb.cb_sources = ZPROP_SRC_ALL;
1295         cb.cb_columns[0] = GET_COL_NAME;
1296         cb.cb_columns[1] = GET_COL_PROPERTY;
1297         cb.cb_columns[2] = GET_COL_VALUE;
1298         cb.cb_columns[3] = GET_COL_SOURCE;
1299         cb.cb_type = ZFS_TYPE_DATASET;
1300
1301         /* check options */
1302         while ((c = getopt(argc, argv, ":d:o:s:rHp")) != -1) {
1303                 switch (c) {
1304                 case 'p':
1305                         cb.cb_literal = B_TRUE;
1306                         break;
1307                 case 'd':
1308                         limit = parse_depth(optarg, &flags);
1309                         break;
1310                 case 'r':
1311                         flags |= ZFS_ITER_RECURSE;
1312                         break;
1313                 case 'H':
1314                         cb.cb_scripted = B_TRUE;
1315                         break;
1316                 case ':':
1317                         (void) fprintf(stderr, gettext("missing argument for "
1318                             "'%c' option\n"), optopt);
1319                         usage(B_FALSE);
1320                         break;
1321                 case 'o':
1322                         /*
1323                          * Process the set of columns to display.  We zero out
1324                          * the structure to give us a blank slate.
1325                          */
1326                         bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1327                         i = 0;
1328                         while (*optarg != '\0') {
1329                                 static char *col_subopts[] =
1330                                     { "name", "property", "value", "received",
1331                                     "source", "all", NULL };
1332
1333                                 if (i == ZFS_GET_NCOLS) {
1334                                         (void) fprintf(stderr, gettext("too "
1335                                             "many fields given to -o "
1336                                             "option\n"));
1337                                         usage(B_FALSE);
1338                                 }
1339
1340                                 switch (getsubopt(&optarg, col_subopts,
1341                                     &value)) {
1342                                 case 0:
1343                                         cb.cb_columns[i++] = GET_COL_NAME;
1344                                         break;
1345                                 case 1:
1346                                         cb.cb_columns[i++] = GET_COL_PROPERTY;
1347                                         break;
1348                                 case 2:
1349                                         cb.cb_columns[i++] = GET_COL_VALUE;
1350                                         break;
1351                                 case 3:
1352                                         cb.cb_columns[i++] = GET_COL_RECVD;
1353                                         flags |= ZFS_ITER_RECVD_PROPS;
1354                                         break;
1355                                 case 4:
1356                                         cb.cb_columns[i++] = GET_COL_SOURCE;
1357                                         break;
1358                                 case 5:
1359                                         if (i > 0) {
1360                                                 (void) fprintf(stderr,
1361                                                     gettext("\"all\" conflicts "
1362                                                     "with specific fields "
1363                                                     "given to -o option\n"));
1364                                                 usage(B_FALSE);
1365                                         }
1366                                         cb.cb_columns[0] = GET_COL_NAME;
1367                                         cb.cb_columns[1] = GET_COL_PROPERTY;
1368                                         cb.cb_columns[2] = GET_COL_VALUE;
1369                                         cb.cb_columns[3] = GET_COL_RECVD;
1370                                         cb.cb_columns[4] = GET_COL_SOURCE;
1371                                         flags |= ZFS_ITER_RECVD_PROPS;
1372                                         i = ZFS_GET_NCOLS;
1373                                         break;
1374                                 default:
1375                                         (void) fprintf(stderr,
1376                                             gettext("invalid column name "
1377                                             "'%s'\n"), value);
1378                                         usage(B_FALSE);
1379                                 }
1380                         }
1381                         break;
1382
1383                 case 's':
1384                         cb.cb_sources = 0;
1385                         while (*optarg != '\0') {
1386                                 static char *source_subopts[] = {
1387                                         "local", "default", "inherited",
1388                                         "received", "temporary", "none",
1389                                         NULL };
1390
1391                                 switch (getsubopt(&optarg, source_subopts,
1392                                     &value)) {
1393                                 case 0:
1394                                         cb.cb_sources |= ZPROP_SRC_LOCAL;
1395                                         break;
1396                                 case 1:
1397                                         cb.cb_sources |= ZPROP_SRC_DEFAULT;
1398                                         break;
1399                                 case 2:
1400                                         cb.cb_sources |= ZPROP_SRC_INHERITED;
1401                                         break;
1402                                 case 3:
1403                                         cb.cb_sources |= ZPROP_SRC_RECEIVED;
1404                                         break;
1405                                 case 4:
1406                                         cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1407                                         break;
1408                                 case 5:
1409                                         cb.cb_sources |= ZPROP_SRC_NONE;
1410                                         break;
1411                                 default:
1412                                         (void) fprintf(stderr,
1413                                             gettext("invalid source "
1414                                             "'%s'\n"), value);
1415                                         usage(B_FALSE);
1416                                 }
1417                         }
1418                         break;
1419
1420                 case '?':
1421                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1422                             optopt);
1423                         usage(B_FALSE);
1424                 }
1425         }
1426
1427         argc -= optind;
1428         argv += optind;
1429
1430         if (argc < 1) {
1431                 (void) fprintf(stderr, gettext("missing property "
1432                     "argument\n"));
1433                 usage(B_FALSE);
1434         }
1435
1436         fields = argv[0];
1437
1438         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1439             != 0)
1440                 usage(B_FALSE);
1441
1442         argc--;
1443         argv++;
1444
1445         /*
1446          * As part of zfs_expand_proplist(), we keep track of the maximum column
1447          * width for each property.  For the 'NAME' (and 'SOURCE') columns, we
1448          * need to know the maximum name length.  However, the user likely did
1449          * not specify 'name' as one of the properties to fetch, so we need to
1450          * make sure we always include at least this property for
1451          * print_get_headers() to work properly.
1452          */
1453         if (cb.cb_proplist != NULL) {
1454                 fake_name.pl_prop = ZFS_PROP_NAME;
1455                 fake_name.pl_width = strlen(gettext("NAME"));
1456                 fake_name.pl_next = cb.cb_proplist;
1457                 cb.cb_proplist = &fake_name;
1458         }
1459
1460         cb.cb_first = B_TRUE;
1461
1462         /* run for each object */
1463         ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET, NULL,
1464             &cb.cb_proplist, limit, get_callback, &cb);
1465
1466         if (cb.cb_proplist == &fake_name)
1467                 zprop_free_list(fake_name.pl_next);
1468         else
1469                 zprop_free_list(cb.cb_proplist);
1470
1471         return (ret);
1472 }
1473
1474 /*
1475  * inherit [-rS] <property> <fs|vol> ...
1476  *
1477  *      -r      Recurse over all children
1478  *      -S      Revert to received value, if any
1479  *
1480  * For each dataset specified on the command line, inherit the given property
1481  * from its parent.  Inheriting a property at the pool level will cause it to
1482  * use the default value.  The '-r' flag will recurse over all children, and is
1483  * useful for setting a property on a hierarchy-wide basis, regardless of any
1484  * local modifications for each dataset.
1485  */
1486
1487 typedef struct inherit_cbdata {
1488         const char *cb_propname;
1489         boolean_t cb_received;
1490 } inherit_cbdata_t;
1491
1492 static int
1493 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
1494 {
1495         inherit_cbdata_t *cb = data;
1496         zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
1497
1498         /*
1499          * If we're doing it recursively, then ignore properties that
1500          * are not valid for this type of dataset.
1501          */
1502         if (prop != ZPROP_INVAL &&
1503             !zfs_prop_valid_for_type(prop, zfs_get_type(zhp)))
1504                 return (0);
1505
1506         return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1507 }
1508
1509 static int
1510 inherit_cb(zfs_handle_t *zhp, void *data)
1511 {
1512         inherit_cbdata_t *cb = data;
1513
1514         return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1515 }
1516
1517 static int
1518 zfs_do_inherit(int argc, char **argv)
1519 {
1520         int c;
1521         zfs_prop_t prop;
1522         inherit_cbdata_t cb = { 0 };
1523         char *propname;
1524         int ret;
1525         int flags = 0;
1526         boolean_t received = B_FALSE;
1527
1528         /* check options */
1529         while ((c = getopt(argc, argv, "rS")) != -1) {
1530                 switch (c) {
1531                 case 'r':
1532                         flags |= ZFS_ITER_RECURSE;
1533                         break;
1534                 case 'S':
1535                         received = B_TRUE;
1536                         break;
1537                 case '?':
1538                 default:
1539                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1540                             optopt);
1541                         usage(B_FALSE);
1542                 }
1543         }
1544
1545         argc -= optind;
1546         argv += optind;
1547
1548         /* check number of arguments */
1549         if (argc < 1) {
1550                 (void) fprintf(stderr, gettext("missing property argument\n"));
1551                 usage(B_FALSE);
1552         }
1553         if (argc < 2) {
1554                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1555                 usage(B_FALSE);
1556         }
1557
1558         propname = argv[0];
1559         argc--;
1560         argv++;
1561
1562         if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1563                 if (zfs_prop_readonly(prop)) {
1564                         (void) fprintf(stderr, gettext(
1565                             "%s property is read-only\n"),
1566                             propname);
1567                         return (1);
1568                 }
1569                 if (!zfs_prop_inheritable(prop) && !received) {
1570                         (void) fprintf(stderr, gettext("'%s' property cannot "
1571                             "be inherited\n"), propname);
1572                         if (prop == ZFS_PROP_QUOTA ||
1573                             prop == ZFS_PROP_RESERVATION ||
1574                             prop == ZFS_PROP_REFQUOTA ||
1575                             prop == ZFS_PROP_REFRESERVATION)
1576                                 (void) fprintf(stderr, gettext("use 'zfs set "
1577                                     "%s=none' to clear\n"), propname);
1578                         return (1);
1579                 }
1580                 if (received && (prop == ZFS_PROP_VOLSIZE ||
1581                     prop == ZFS_PROP_VERSION)) {
1582                         (void) fprintf(stderr, gettext("'%s' property cannot "
1583                             "be reverted to a received value\n"), propname);
1584                         return (1);
1585                 }
1586         } else if (!zfs_prop_user(propname)) {
1587                 (void) fprintf(stderr, gettext("invalid property '%s'\n"),
1588                     propname);
1589                 usage(B_FALSE);
1590         }
1591
1592         cb.cb_propname = propname;
1593         cb.cb_received = received;
1594
1595         if (flags & ZFS_ITER_RECURSE) {
1596                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1597                     NULL, NULL, 0, inherit_recurse_cb, &cb);
1598         } else {
1599                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1600                     NULL, NULL, 0, inherit_cb, &cb);
1601         }
1602
1603         return (ret);
1604 }
1605
1606 typedef struct upgrade_cbdata {
1607         uint64_t cb_numupgraded;
1608         uint64_t cb_numsamegraded;
1609         uint64_t cb_numfailed;
1610         uint64_t cb_version;
1611         boolean_t cb_newer;
1612         boolean_t cb_foundone;
1613         char cb_lastfs[ZFS_MAXNAMELEN];
1614 } upgrade_cbdata_t;
1615
1616 static int
1617 same_pool(zfs_handle_t *zhp, const char *name)
1618 {
1619         int len1 = strcspn(name, "/@");
1620         const char *zhname = zfs_get_name(zhp);
1621         int len2 = strcspn(zhname, "/@");
1622
1623         if (len1 != len2)
1624                 return (B_FALSE);
1625         return (strncmp(name, zhname, len1) == 0);
1626 }
1627
1628 static int
1629 upgrade_list_callback(zfs_handle_t *zhp, void *data)
1630 {
1631         upgrade_cbdata_t *cb = data;
1632         int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1633
1634         /* list if it's old/new */
1635         if ((!cb->cb_newer && version < ZPL_VERSION) ||
1636             (cb->cb_newer && version > ZPL_VERSION)) {
1637                 char *str;
1638                 if (cb->cb_newer) {
1639                         str = gettext("The following filesystems are "
1640                             "formatted using a newer software version and\n"
1641                             "cannot be accessed on the current system.\n\n");
1642                 } else {
1643                         str = gettext("The following filesystems are "
1644                             "out of date, and can be upgraded.  After being\n"
1645                             "upgraded, these filesystems (and any 'zfs send' "
1646                             "streams generated from\n"
1647                             "subsequent snapshots) will no longer be "
1648                             "accessible by older software versions.\n\n");
1649                 }
1650
1651                 if (!cb->cb_foundone) {
1652                         (void) puts(str);
1653                         (void) printf(gettext("VER  FILESYSTEM\n"));
1654                         (void) printf(gettext("---  ------------\n"));
1655                         cb->cb_foundone = B_TRUE;
1656                 }
1657
1658                 (void) printf("%2u   %s\n", version, zfs_get_name(zhp));
1659         }
1660
1661         return (0);
1662 }
1663
1664 static int
1665 upgrade_set_callback(zfs_handle_t *zhp, void *data)
1666 {
1667         upgrade_cbdata_t *cb = data;
1668         int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1669         int needed_spa_version;
1670         int spa_version;
1671
1672         if (zfs_spa_version(zhp, &spa_version) < 0)
1673                 return (-1);
1674
1675         needed_spa_version = zfs_spa_version_map(cb->cb_version);
1676
1677         if (needed_spa_version < 0)
1678                 return (-1);
1679
1680         if (spa_version < needed_spa_version) {
1681                 /* can't upgrade */
1682                 (void) printf(gettext("%s: can not be "
1683                     "upgraded; the pool version needs to first "
1684                     "be upgraded\nto version %d\n\n"),
1685                     zfs_get_name(zhp), needed_spa_version);
1686                 cb->cb_numfailed++;
1687                 return (0);
1688         }
1689
1690         /* upgrade */
1691         if (version < cb->cb_version) {
1692                 char verstr[16];
1693                 (void) snprintf(verstr, sizeof (verstr),
1694                     "%llu", (u_longlong_t)cb->cb_version);
1695                 if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
1696                         /*
1697                          * If they did "zfs upgrade -a", then we could
1698                          * be doing ioctls to different pools.  We need
1699                          * to log this history once to each pool.
1700                          */
1701                         verify(zpool_stage_history(g_zfs, history_str) == 0);
1702                 }
1703                 if (zfs_prop_set(zhp, "version", verstr) == 0)
1704                         cb->cb_numupgraded++;
1705                 else
1706                         cb->cb_numfailed++;
1707                 (void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
1708         } else if (version > cb->cb_version) {
1709                 /* can't downgrade */
1710                 (void) printf(gettext("%s: can not be downgraded; "
1711                     "it is already at version %u\n"),
1712                     zfs_get_name(zhp), version);
1713                 cb->cb_numfailed++;
1714         } else {
1715                 cb->cb_numsamegraded++;
1716         }
1717         return (0);
1718 }
1719
1720 /*
1721  * zfs upgrade
1722  * zfs upgrade -v
1723  * zfs upgrade [-r] [-V <version>] <-a | filesystem>
1724  */
1725 static int
1726 zfs_do_upgrade(int argc, char **argv)
1727 {
1728         boolean_t all = B_FALSE;
1729         boolean_t showversions = B_FALSE;
1730         int ret;
1731         upgrade_cbdata_t cb = { 0 };
1732         signed char c;
1733         int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1734
1735         /* check options */
1736         while ((c = getopt(argc, argv, "rvV:a")) != -1) {
1737                 switch (c) {
1738                 case 'r':
1739                         flags |= ZFS_ITER_RECURSE;
1740                         break;
1741                 case 'v':
1742                         showversions = B_TRUE;
1743                         break;
1744                 case 'V':
1745                         if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
1746                             optarg, &cb.cb_version) != 0) {
1747                                 (void) fprintf(stderr,
1748                                     gettext("invalid version %s\n"), optarg);
1749                                 usage(B_FALSE);
1750                         }
1751                         break;
1752                 case 'a':
1753                         all = B_TRUE;
1754                         break;
1755                 case '?':
1756                 default:
1757                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1758                             optopt);
1759                         usage(B_FALSE);
1760                 }
1761         }
1762
1763         argc -= optind;
1764         argv += optind;
1765
1766         if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
1767                 usage(B_FALSE);
1768         if (showversions && (flags & ZFS_ITER_RECURSE || all ||
1769             cb.cb_version || argc))
1770                 usage(B_FALSE);
1771         if ((all || argc) && (showversions))
1772                 usage(B_FALSE);
1773         if (all && argc)
1774                 usage(B_FALSE);
1775
1776         if (showversions) {
1777                 /* Show info on available versions. */
1778                 (void) printf(gettext("The following filesystem versions are "
1779                     "supported:\n\n"));
1780                 (void) printf(gettext("VER  DESCRIPTION\n"));
1781                 (void) printf("---  -----------------------------------------"
1782                     "---------------\n");
1783                 (void) printf(gettext(" 1   Initial ZFS filesystem version\n"));
1784                 (void) printf(gettext(" 2   Enhanced directory entries\n"));
1785                 (void) printf(gettext(" 3   Case insensitive and File system "
1786                     "unique identifier (FUID)\n"));
1787                 (void) printf(gettext(" 4   userquota, groupquota "
1788                     "properties\n"));
1789                 (void) printf(gettext(" 5   System attributes\n"));
1790                 (void) printf(gettext("\nFor more information on a particular "
1791                     "version, including supported releases,\n"));
1792                 (void) printf("see the ZFS Administration Guide.\n\n");
1793                 ret = 0;
1794         } else if (argc || all) {
1795                 /* Upgrade filesystems */
1796                 if (cb.cb_version == 0)
1797                         cb.cb_version = ZPL_VERSION;
1798                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
1799                     NULL, NULL, 0, upgrade_set_callback, &cb);
1800                 (void) printf(gettext("%llu filesystems upgraded\n"),
1801                     (u_longlong_t)cb.cb_numupgraded);
1802                 if (cb.cb_numsamegraded) {
1803                         (void) printf(gettext("%llu filesystems already at "
1804                             "this version\n"),
1805                             (u_longlong_t)cb.cb_numsamegraded);
1806                 }
1807                 if (cb.cb_numfailed != 0)
1808                         ret = 1;
1809         } else {
1810                 /* List old-version filesytems */
1811                 boolean_t found;
1812                 (void) printf(gettext("This system is currently running "
1813                     "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
1814
1815                 flags |= ZFS_ITER_RECURSE;
1816                 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
1817                     NULL, NULL, 0, upgrade_list_callback, &cb);
1818
1819                 found = cb.cb_foundone;
1820                 cb.cb_foundone = B_FALSE;
1821                 cb.cb_newer = B_TRUE;
1822
1823                 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
1824                     NULL, NULL, 0, upgrade_list_callback, &cb);
1825
1826                 if (!cb.cb_foundone && !found) {
1827                         (void) printf(gettext("All filesystems are "
1828                             "formatted with the current version.\n"));
1829                 }
1830         }
1831
1832         return (ret);
1833 }
1834
1835 /*
1836  * zfs userspace
1837  */
1838 static int
1839 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
1840 {
1841         zfs_userquota_prop_t *typep = arg;
1842         zfs_userquota_prop_t p = *typep;
1843         char *name = NULL;
1844         char *ug, *propname;
1845         char namebuf[32];
1846         char sizebuf[32];
1847
1848         if (domain == NULL || domain[0] == '\0') {
1849                 if (p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA) {
1850                         struct group *g = getgrgid(rid);
1851                         if (g)
1852                                 name = g->gr_name;
1853                 } else {
1854                         struct passwd *p = getpwuid(rid);
1855                         if (p)
1856                                 name = p->pw_name;
1857                 }
1858         }
1859
1860         if (p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA)
1861                 ug = "group";
1862         else
1863                 ug = "user";
1864
1865         if (p == ZFS_PROP_USERUSED || p == ZFS_PROP_GROUPUSED)
1866                 propname = "used";
1867         else
1868                 propname = "quota";
1869
1870         if (name == NULL) {
1871                 (void) snprintf(namebuf, sizeof (namebuf),
1872                     "%llu", (longlong_t)rid);
1873                 name = namebuf;
1874         }
1875         zfs_nicenum(space, sizebuf, sizeof (sizebuf));
1876
1877         (void) printf("%s %s %s%c%s %s\n", propname, ug, domain,
1878             domain[0] ? '-' : ' ', name, sizebuf);
1879
1880         return (0);
1881 }
1882
1883 static int
1884 zfs_do_userspace(int argc, char **argv)
1885 {
1886         zfs_handle_t *zhp;
1887         zfs_userquota_prop_t p;
1888         int error;
1889
1890         /*
1891          * Try the python version.  If the execv fails, we'll continue
1892          * and do a simplistic implementation.
1893          */
1894         (void) execv(pypath, argv-1);
1895
1896         (void) printf("internal error: %s not found\n"
1897             "falling back on built-in implementation, "
1898             "some features will not work\n", pypath);
1899
1900         if ((zhp = zfs_open(g_zfs, argv[argc-1], ZFS_TYPE_DATASET)) == NULL)
1901                 return (1);
1902
1903         (void) printf("PROP TYPE NAME VALUE\n");
1904
1905         for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
1906                 error = zfs_userspace(zhp, p, userspace_cb, &p);
1907                 if (error)
1908                         break;
1909         }
1910         return (error);
1911 }
1912
1913 /*
1914  * list [-r][-d max] [-H] [-o property[,property]...] [-t type[,type]...]
1915  *      [-s property [-s property]...] [-S property [-S property]...]
1916  *      <dataset> ...
1917  *
1918  *      -r      Recurse over all children
1919  *      -d      Limit recursion by depth.
1920  *      -H      Scripted mode; elide headers and separate columns by tabs
1921  *      -o      Control which fields to display.
1922  *      -t      Control which object types to display.
1923  *      -s      Specify sort columns, descending order.
1924  *      -S      Specify sort columns, ascending order.
1925  *
1926  * When given no arguments, lists all filesystems in the system.
1927  * Otherwise, list the specified datasets, optionally recursing down them if
1928  * '-r' is specified.
1929  */
1930 typedef struct list_cbdata {
1931         boolean_t       cb_first;
1932         boolean_t       cb_scripted;
1933         zprop_list_t    *cb_proplist;
1934 } list_cbdata_t;
1935
1936 /*
1937  * Given a list of columns to display, output appropriate headers for each one.
1938  */
1939 static void
1940 print_header(zprop_list_t *pl)
1941 {
1942         char headerbuf[ZFS_MAXPROPLEN];
1943         const char *header;
1944         int i;
1945         boolean_t first = B_TRUE;
1946         boolean_t right_justify;
1947
1948         for (; pl != NULL; pl = pl->pl_next) {
1949                 if (!first) {
1950                         (void) printf("  ");
1951                 } else {
1952                         first = B_FALSE;
1953                 }
1954
1955                 right_justify = B_FALSE;
1956                 if (pl->pl_prop != ZPROP_INVAL) {
1957                         header = zfs_prop_column_name(pl->pl_prop);
1958                         right_justify = zfs_prop_align_right(pl->pl_prop);
1959                 } else {
1960                         for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
1961                                 headerbuf[i] = toupper(pl->pl_user_prop[i]);
1962                         headerbuf[i] = '\0';
1963                         header = headerbuf;
1964                 }
1965
1966                 if (pl->pl_next == NULL && !right_justify)
1967                         (void) printf("%s", header);
1968                 else if (right_justify)
1969                         (void) printf("%*s", (int)pl->pl_width, header);
1970                 else
1971                         (void) printf("%-*s", (int)pl->pl_width, header);
1972         }
1973
1974         (void) printf("\n");
1975 }
1976
1977 /*
1978  * Given a dataset and a list of fields, print out all the properties according
1979  * to the described layout.
1980  */
1981 static void
1982 print_dataset(zfs_handle_t *zhp, zprop_list_t *pl, boolean_t scripted)
1983 {
1984         boolean_t first = B_TRUE;
1985         char property[ZFS_MAXPROPLEN];
1986         nvlist_t *userprops = zfs_get_user_props(zhp);
1987         nvlist_t *propval;
1988         char *propstr;
1989         boolean_t right_justify;
1990         int width;
1991
1992         for (; pl != NULL; pl = pl->pl_next) {
1993                 if (!first) {
1994                         if (scripted)
1995                                 (void) printf("\t");
1996                         else
1997                                 (void) printf("  ");
1998                 } else {
1999                         first = B_FALSE;
2000                 }
2001
2002                 if (pl->pl_prop != ZPROP_INVAL) {
2003                         if (zfs_prop_get(zhp, pl->pl_prop, property,
2004                             sizeof (property), NULL, NULL, 0, B_FALSE) != 0)
2005                                 propstr = "-";
2006                         else
2007                                 propstr = property;
2008
2009                         right_justify = zfs_prop_align_right(pl->pl_prop);
2010                 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
2011                         if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
2012                             property, sizeof (property), B_FALSE) != 0)
2013                                 propstr = "-";
2014                         else
2015                                 propstr = property;
2016                         right_justify = B_TRUE;
2017                 } else {
2018                         if (nvlist_lookup_nvlist(userprops,
2019                             pl->pl_user_prop, &propval) != 0)
2020                                 propstr = "-";
2021                         else
2022                                 verify(nvlist_lookup_string(propval,
2023                                     ZPROP_VALUE, &propstr) == 0);
2024                         right_justify = B_FALSE;
2025                 }
2026
2027                 width = pl->pl_width;
2028
2029                 /*
2030                  * If this is being called in scripted mode, or if this is the
2031                  * last column and it is left-justified, don't include a width
2032                  * format specifier.
2033                  */
2034                 if (scripted || (pl->pl_next == NULL && !right_justify))
2035                         (void) printf("%s", propstr);
2036                 else if (right_justify)
2037                         (void) printf("%*s", width, propstr);
2038                 else
2039                         (void) printf("%-*s", width, propstr);
2040         }
2041
2042         (void) printf("\n");
2043 }
2044
2045 /*
2046  * Generic callback function to list a dataset or snapshot.
2047  */
2048 static int
2049 list_callback(zfs_handle_t *zhp, void *data)
2050 {
2051         list_cbdata_t *cbp = data;
2052
2053         if (cbp->cb_first) {
2054                 if (!cbp->cb_scripted)
2055                         print_header(cbp->cb_proplist);
2056                 cbp->cb_first = B_FALSE;
2057         }
2058
2059         print_dataset(zhp, cbp->cb_proplist, cbp->cb_scripted);
2060
2061         return (0);
2062 }
2063
2064 static int
2065 zfs_do_list(int argc, char **argv)
2066 {
2067         int c;
2068         boolean_t scripted = B_FALSE;
2069         static char default_fields[] =
2070             "name,used,available,referenced,mountpoint";
2071         int types = ZFS_TYPE_DATASET;
2072         boolean_t types_specified = B_FALSE;
2073         char *fields = NULL;
2074         list_cbdata_t cb = { 0 };
2075         char *value;
2076         int limit = 0;
2077         int ret;
2078         zfs_sort_column_t *sortcol = NULL;
2079         int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
2080
2081         /* check options */
2082         while ((c = getopt(argc, argv, ":d:o:rt:Hs:S:")) != -1) {
2083                 switch (c) {
2084                 case 'o':
2085                         fields = optarg;
2086                         break;
2087                 case 'd':
2088                         limit = parse_depth(optarg, &flags);
2089                         break;
2090                 case 'r':
2091                         flags |= ZFS_ITER_RECURSE;
2092                         break;
2093                 case 'H':
2094                         scripted = B_TRUE;
2095                         break;
2096                 case 's':
2097                         if (zfs_add_sort_column(&sortcol, optarg,
2098                             B_FALSE) != 0) {
2099                                 (void) fprintf(stderr,
2100                                     gettext("invalid property '%s'\n"), optarg);
2101                                 usage(B_FALSE);
2102                         }
2103                         break;
2104                 case 'S':
2105                         if (zfs_add_sort_column(&sortcol, optarg,
2106                             B_TRUE) != 0) {
2107                                 (void) fprintf(stderr,
2108                                     gettext("invalid property '%s'\n"), optarg);
2109                                 usage(B_FALSE);
2110                         }
2111                         break;
2112                 case 't':
2113                         types = 0;
2114                         types_specified = B_TRUE;
2115                         flags &= ~ZFS_ITER_PROP_LISTSNAPS;
2116                         while (*optarg != '\0') {
2117                                 static char *type_subopts[] = { "filesystem",
2118                                     "volume", "snapshot", "all", NULL };
2119
2120                                 switch (getsubopt(&optarg, type_subopts,
2121                                     &value)) {
2122                                 case 0:
2123                                         types |= ZFS_TYPE_FILESYSTEM;
2124                                         break;
2125                                 case 1:
2126                                         types |= ZFS_TYPE_VOLUME;
2127                                         break;
2128                                 case 2:
2129                                         types |= ZFS_TYPE_SNAPSHOT;
2130                                         break;
2131                                 case 3:
2132                                         types = ZFS_TYPE_DATASET;
2133                                         break;
2134
2135                                 default:
2136                                         (void) fprintf(stderr,
2137                                             gettext("invalid type '%s'\n"),
2138                                             value);
2139                                         usage(B_FALSE);
2140                                 }
2141                         }
2142                         break;
2143                 case ':':
2144                         (void) fprintf(stderr, gettext("missing argument for "
2145                             "'%c' option\n"), optopt);
2146                         usage(B_FALSE);
2147                         break;
2148                 case '?':
2149                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2150                             optopt);
2151                         usage(B_FALSE);
2152                 }
2153         }
2154
2155         argc -= optind;
2156         argv += optind;
2157
2158         if (fields == NULL)
2159                 fields = default_fields;
2160
2161         /*
2162          * If "-o space" and no types were specified, don't display snapshots.
2163          */
2164         if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
2165                 types &= ~ZFS_TYPE_SNAPSHOT;
2166
2167         /*
2168          * If the user specifies '-o all', the zprop_get_list() doesn't
2169          * normally include the name of the dataset.  For 'zfs list', we always
2170          * want this property to be first.
2171          */
2172         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
2173             != 0)
2174                 usage(B_FALSE);
2175
2176         cb.cb_scripted = scripted;
2177         cb.cb_first = B_TRUE;
2178
2179         ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
2180             limit, list_callback, &cb);
2181
2182         zprop_free_list(cb.cb_proplist);
2183         zfs_free_sort_columns(sortcol);
2184
2185         if (ret == 0 && cb.cb_first && !cb.cb_scripted)
2186                 (void) printf(gettext("no datasets available\n"));
2187
2188         return (ret);
2189 }
2190
2191 /*
2192  * zfs rename <fs | snap | vol> <fs | snap | vol>
2193  * zfs rename -p <fs | vol> <fs | vol>
2194  * zfs rename -r <snap> <snap>
2195  *
2196  * Renames the given dataset to another of the same type.
2197  *
2198  * The '-p' flag creates all the non-existing ancestors of the target first.
2199  */
2200 /* ARGSUSED */
2201 static int
2202 zfs_do_rename(int argc, char **argv)
2203 {
2204         zfs_handle_t *zhp;
2205         int c;
2206         int ret;
2207         boolean_t recurse = B_FALSE;
2208         boolean_t parents = B_FALSE;
2209
2210         /* check options */
2211         while ((c = getopt(argc, argv, "pr")) != -1) {
2212                 switch (c) {
2213                 case 'p':
2214                         parents = B_TRUE;
2215                         break;
2216                 case 'r':
2217                         recurse = B_TRUE;
2218                         break;
2219                 case '?':
2220                 default:
2221                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2222                             optopt);
2223                         usage(B_FALSE);
2224                 }
2225         }
2226
2227         argc -= optind;
2228         argv += optind;
2229
2230         /* check number of arguments */
2231         if (argc < 1) {
2232                 (void) fprintf(stderr, gettext("missing source dataset "
2233                     "argument\n"));
2234                 usage(B_FALSE);
2235         }
2236         if (argc < 2) {
2237                 (void) fprintf(stderr, gettext("missing target dataset "
2238                     "argument\n"));
2239                 usage(B_FALSE);
2240         }
2241         if (argc > 2) {
2242                 (void) fprintf(stderr, gettext("too many arguments\n"));
2243                 usage(B_FALSE);
2244         }
2245
2246         if (recurse && parents) {
2247                 (void) fprintf(stderr, gettext("-p and -r options are mutually "
2248                     "exclusive\n"));
2249                 usage(B_FALSE);
2250         }
2251
2252         if (recurse && strchr(argv[0], '@') == 0) {
2253                 (void) fprintf(stderr, gettext("source dataset for recursive "
2254                     "rename must be a snapshot\n"));
2255                 usage(B_FALSE);
2256         }
2257
2258         if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
2259             ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
2260                 return (1);
2261
2262         /* If we were asked and the name looks good, try to create ancestors. */
2263         if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
2264             zfs_create_ancestors(g_zfs, argv[1]) != 0) {
2265                 zfs_close(zhp);
2266                 return (1);
2267         }
2268
2269         ret = (zfs_rename(zhp, argv[1], recurse) != 0);
2270
2271         zfs_close(zhp);
2272         return (ret);
2273 }
2274
2275 /*
2276  * zfs promote <fs>
2277  *
2278  * Promotes the given clone fs to be the parent
2279  */
2280 /* ARGSUSED */
2281 static int
2282 zfs_do_promote(int argc, char **argv)
2283 {
2284         zfs_handle_t *zhp;
2285         int ret;
2286
2287         /* check options */
2288         if (argc > 1 && argv[1][0] == '-') {
2289                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2290                     argv[1][1]);
2291                 usage(B_FALSE);
2292         }
2293
2294         /* check number of arguments */
2295         if (argc < 2) {
2296                 (void) fprintf(stderr, gettext("missing clone filesystem"
2297                     " argument\n"));
2298                 usage(B_FALSE);
2299         }
2300         if (argc > 2) {
2301                 (void) fprintf(stderr, gettext("too many arguments\n"));
2302                 usage(B_FALSE);
2303         }
2304
2305         zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2306         if (zhp == NULL)
2307                 return (1);
2308
2309         ret = (zfs_promote(zhp) != 0);
2310
2311
2312         zfs_close(zhp);
2313         return (ret);
2314 }
2315
2316 /*
2317  * zfs rollback [-rRf] <snapshot>
2318  *
2319  *      -r      Delete any intervening snapshots before doing rollback
2320  *      -R      Delete any snapshots and their clones
2321  *      -f      ignored for backwards compatability
2322  *
2323  * Given a filesystem, rollback to a specific snapshot, discarding any changes
2324  * since then and making it the active dataset.  If more recent snapshots exist,
2325  * the command will complain unless the '-r' flag is given.
2326  */
2327 typedef struct rollback_cbdata {
2328         uint64_t        cb_create;
2329         boolean_t       cb_first;
2330         int             cb_doclones;
2331         char            *cb_target;
2332         int             cb_error;
2333         boolean_t       cb_recurse;
2334         boolean_t       cb_dependent;
2335 } rollback_cbdata_t;
2336
2337 /*
2338  * Report any snapshots more recent than the one specified.  Used when '-r' is
2339  * not specified.  We reuse this same callback for the snapshot dependents - if
2340  * 'cb_dependent' is set, then this is a dependent and we should report it
2341  * without checking the transaction group.
2342  */
2343 #ifdef HAVE_ZPL
2344 static int
2345 rollback_check(zfs_handle_t *zhp, void *data)
2346 {
2347         rollback_cbdata_t *cbp = data;
2348
2349         if (cbp->cb_doclones) {
2350                 zfs_close(zhp);
2351                 return (0);
2352         }
2353
2354         if (!cbp->cb_dependent) {
2355                 if (strcmp(zfs_get_name(zhp), cbp->cb_target) != 0 &&
2356                     zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
2357                     zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
2358                     cbp->cb_create) {
2359
2360                         if (cbp->cb_first && !cbp->cb_recurse) {
2361                                 (void) fprintf(stderr, gettext("cannot "
2362                                     "rollback to '%s': more recent snapshots "
2363                                     "exist\n"),
2364                                     cbp->cb_target);
2365                                 (void) fprintf(stderr, gettext("use '-r' to "
2366                                     "force deletion of the following "
2367                                     "snapshots:\n"));
2368                                 cbp->cb_first = 0;
2369                                 cbp->cb_error = 1;
2370                         }
2371
2372                         if (cbp->cb_recurse) {
2373                                 cbp->cb_dependent = B_TRUE;
2374                                 if (zfs_iter_dependents(zhp, B_TRUE,
2375                                     rollback_check, cbp) != 0) {
2376                                         zfs_close(zhp);
2377                                         return (-1);
2378                                 }
2379                                 cbp->cb_dependent = B_FALSE;
2380                         } else {
2381                                 (void) fprintf(stderr, "%s\n",
2382                                     zfs_get_name(zhp));
2383                         }
2384                 }
2385         } else {
2386                 if (cbp->cb_first && cbp->cb_recurse) {
2387                         (void) fprintf(stderr, gettext("cannot rollback to "
2388                             "'%s': clones of previous snapshots exist\n"),
2389                             cbp->cb_target);
2390                         (void) fprintf(stderr, gettext("use '-R' to "
2391                             "force deletion of the following clones and "
2392                             "dependents:\n"));
2393                         cbp->cb_first = 0;
2394                         cbp->cb_error = 1;
2395                 }
2396
2397                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
2398         }
2399
2400         zfs_close(zhp);
2401         return (0);
2402 }
2403 #endif /* HAVE_ZPL */
2404
2405 static int
2406 zfs_do_rollback(int argc, char **argv)
2407 {
2408 #ifdef HAVE_ZPL
2409         int ret;
2410         int c;
2411         boolean_t force = B_FALSE;
2412         rollback_cbdata_t cb = { 0 };
2413         zfs_handle_t *zhp, *snap;
2414         char parentname[ZFS_MAXNAMELEN];
2415         char *delim;
2416
2417         /* check options */
2418         while ((c = getopt(argc, argv, "rRf")) != -1) {
2419                 switch (c) {
2420                 case 'r':
2421                         cb.cb_recurse = 1;
2422                         break;
2423                 case 'R':
2424                         cb.cb_recurse = 1;
2425                         cb.cb_doclones = 1;
2426                         break;
2427                 case 'f':
2428                         force = B_TRUE;
2429                         break;
2430                 case '?':
2431                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2432                             optopt);
2433                         usage(B_FALSE);
2434                 }
2435         }
2436
2437         argc -= optind;
2438         argv += optind;
2439
2440         /* check number of arguments */
2441         if (argc < 1) {
2442                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
2443                 usage(B_FALSE);
2444         }
2445         if (argc > 1) {
2446                 (void) fprintf(stderr, gettext("too many arguments\n"));
2447                 usage(B_FALSE);
2448         }
2449
2450         /* open the snapshot */
2451         if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
2452                 return (1);
2453
2454         /* open the parent dataset */
2455         (void) strlcpy(parentname, argv[0], sizeof (parentname));
2456         verify((delim = strrchr(parentname, '@')) != NULL);
2457         *delim = '\0';
2458         if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
2459                 zfs_close(snap);
2460                 return (1);
2461         }
2462
2463         /*
2464          * Check for more recent snapshots and/or clones based on the presence
2465          * of '-r' and '-R'.
2466          */
2467         cb.cb_target = argv[0];
2468         cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
2469         cb.cb_first = B_TRUE;
2470         cb.cb_error = 0;
2471         if ((ret = zfs_iter_children(zhp, rollback_check, &cb)) != 0)
2472                 goto out;
2473
2474         if ((ret = cb.cb_error) != 0)
2475                 goto out;
2476
2477         /*
2478          * Rollback parent to the given snapshot.
2479          */
2480         ret = zfs_rollback(zhp, snap, force);
2481
2482 out:
2483         zfs_close(snap);
2484         zfs_close(zhp);
2485
2486         if (ret == 0)
2487                 return (0);
2488         else
2489                 return (1);
2490 #else
2491         return ENOSYS;
2492 #endif /*HAVE_ZPL*/
2493 }
2494
2495 /*
2496  * zfs set property=value { fs | snap | vol } ...
2497  *
2498  * Sets the given property for all datasets specified on the command line.
2499  */
2500 typedef struct set_cbdata {
2501         char            *cb_propname;
2502         char            *cb_value;
2503 } set_cbdata_t;
2504
2505 static int
2506 set_callback(zfs_handle_t *zhp, void *data)
2507 {
2508         set_cbdata_t *cbp = data;
2509
2510         if (zfs_prop_set(zhp, cbp->cb_propname, cbp->cb_value) != 0) {
2511                 switch (libzfs_errno(g_zfs)) {
2512                 case EZFS_MOUNTFAILED:
2513                         (void) fprintf(stderr, gettext("property may be set "
2514                             "but unable to remount filesystem\n"));
2515                         break;
2516                 case EZFS_SHARENFSFAILED:
2517                         (void) fprintf(stderr, gettext("property may be set "
2518                             "but unable to reshare filesystem\n"));
2519                         break;
2520                 }
2521                 return (1);
2522         }
2523         return (0);
2524 }
2525
2526 static int
2527 zfs_do_set(int argc, char **argv)
2528 {
2529         set_cbdata_t cb;
2530         int ret;
2531
2532         /* check for options */
2533         if (argc > 1 && argv[1][0] == '-') {
2534                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2535                     argv[1][1]);
2536                 usage(B_FALSE);
2537         }
2538
2539         /* check number of arguments */
2540         if (argc < 2) {
2541                 (void) fprintf(stderr, gettext("missing property=value "
2542                     "argument\n"));
2543                 usage(B_FALSE);
2544         }
2545         if (argc < 3) {
2546                 (void) fprintf(stderr, gettext("missing dataset name\n"));
2547                 usage(B_FALSE);
2548         }
2549
2550         /* validate property=value argument */
2551         cb.cb_propname = argv[1];
2552         if (((cb.cb_value = strchr(cb.cb_propname, '=')) == NULL) ||
2553             (cb.cb_value[1] == '\0')) {
2554                 (void) fprintf(stderr, gettext("missing value in "
2555                     "property=value argument\n"));
2556                 usage(B_FALSE);
2557         }
2558
2559         *cb.cb_value = '\0';
2560         cb.cb_value++;
2561
2562         if (*cb.cb_propname == '\0') {
2563                 (void) fprintf(stderr,
2564                     gettext("missing property in property=value argument\n"));
2565                 usage(B_FALSE);
2566         }
2567
2568         ret = zfs_for_each(argc - 2, argv + 2, 0,
2569             ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, &cb);
2570
2571         return (ret);
2572 }
2573
2574 /*
2575  * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
2576  *
2577  * Creates a snapshot with the given name.  While functionally equivalent to
2578  * 'zfs create', it is a separate command to differentiate intent.
2579  */
2580 static int
2581 zfs_do_snapshot(int argc, char **argv)
2582 {
2583         boolean_t recursive = B_FALSE;
2584         int ret;
2585         signed char c;
2586         nvlist_t *props;
2587
2588         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
2589                 nomem();
2590
2591         /* check options */
2592         while ((c = getopt(argc, argv, "ro:")) != -1) {
2593                 switch (c) {
2594                 case 'o':
2595                         if (parseprop(props))
2596                                 return (1);
2597                         break;
2598                 case 'r':
2599                         recursive = B_TRUE;
2600                         break;
2601                 case '?':
2602                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2603                             optopt);
2604                         goto usage;
2605                 }
2606         }
2607
2608         argc -= optind;
2609         argv += optind;
2610
2611         /* check number of arguments */
2612         if (argc < 1) {
2613                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2614                 goto usage;
2615         }
2616         if (argc > 1) {
2617                 (void) fprintf(stderr, gettext("too many arguments\n"));
2618                 goto usage;
2619         }
2620
2621         ret = zfs_snapshot(g_zfs, argv[0], recursive, props);
2622         nvlist_free(props);
2623         if (ret && recursive)
2624                 (void) fprintf(stderr, gettext("no snapshots were created\n"));
2625         return (ret != 0);
2626
2627 usage:
2628         nvlist_free(props);
2629         usage(B_FALSE);
2630         return (-1);
2631 }
2632
2633 /*
2634  * zfs send [-vDp] -R [-i|-I <@snap>] <fs@snap>
2635  * zfs send [-vDp] [-i|-I <@snap>] <fs@snap>
2636  *
2637  * Send a backup stream to stdout.
2638  */
2639 static int
2640 zfs_do_send(int argc, char **argv)
2641 {
2642         char *fromname = NULL;
2643         char *toname = NULL;
2644         char *cp;
2645         zfs_handle_t *zhp;
2646         sendflags_t flags = { 0 };
2647         int c, err;
2648         nvlist_t *dbgnv;
2649         boolean_t extraverbose = B_FALSE;
2650
2651         /* check options */
2652         while ((c = getopt(argc, argv, ":i:I:RDpv")) != -1) {
2653                 switch (c) {
2654                 case 'i':
2655                         if (fromname)
2656                                 usage(B_FALSE);
2657                         fromname = optarg;
2658                         break;
2659                 case 'I':
2660                         if (fromname)
2661                                 usage(B_FALSE);
2662                         fromname = optarg;
2663                         flags.doall = B_TRUE;
2664                         break;
2665                 case 'R':
2666                         flags.replicate = B_TRUE;
2667                         break;
2668                 case 'p':
2669                         flags.props = B_TRUE;
2670                         break;
2671                 case 'v':
2672                         if (flags.verbose)
2673                                 extraverbose = B_TRUE;
2674                         flags.verbose = B_TRUE;
2675                         break;
2676                 case 'D':
2677                         flags.dedup = B_TRUE;
2678                         break;
2679                 case ':':
2680                         (void) fprintf(stderr, gettext("missing argument for "
2681                             "'%c' option\n"), optopt);
2682                         usage(B_FALSE);
2683                         break;
2684                 case '?':
2685                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2686                             optopt);
2687                         usage(B_FALSE);
2688                 }
2689         }
2690
2691         argc -= optind;
2692         argv += optind;
2693
2694         /* check number of arguments */
2695         if (argc < 1) {
2696                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2697                 usage(B_FALSE);
2698         }
2699         if (argc > 1) {
2700                 (void) fprintf(stderr, gettext("too many arguments\n"));
2701                 usage(B_FALSE);
2702         }
2703
2704         if (isatty(STDOUT_FILENO)) {
2705                 (void) fprintf(stderr,
2706                     gettext("Error: Stream can not be written to a terminal.\n"
2707                     "You must redirect standard output.\n"));
2708                 return (1);
2709         }
2710
2711         cp = strchr(argv[0], '@');
2712         if (cp == NULL) {
2713                 (void) fprintf(stderr,
2714                     gettext("argument must be a snapshot\n"));
2715                 usage(B_FALSE);
2716         }
2717         *cp = '\0';
2718         toname = cp + 1;
2719         zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2720         if (zhp == NULL)
2721                 return (1);
2722
2723         /*
2724          * If they specified the full path to the snapshot, chop off
2725          * everything except the short name of the snapshot, but special
2726          * case if they specify the origin.
2727          */
2728         if (fromname && (cp = strchr(fromname, '@')) != NULL) {
2729                 char origin[ZFS_MAXNAMELEN];
2730                 zprop_source_t src;
2731
2732                 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
2733                     origin, sizeof (origin), &src, NULL, 0, B_FALSE);
2734
2735                 if (strcmp(origin, fromname) == 0) {
2736                         fromname = NULL;
2737                         flags.fromorigin = B_TRUE;
2738                 } else {
2739                         *cp = '\0';
2740                         if (cp != fromname && strcmp(argv[0], fromname)) {
2741                                 (void) fprintf(stderr,
2742                                     gettext("incremental source must be "
2743                                     "in same filesystem\n"));
2744                                 usage(B_FALSE);
2745                         }
2746                         fromname = cp + 1;
2747                         if (strchr(fromname, '@') || strchr(fromname, '/')) {
2748                                 (void) fprintf(stderr,
2749                                     gettext("invalid incremental source\n"));
2750                                 usage(B_FALSE);
2751                         }
2752                 }
2753         }
2754
2755         if (flags.replicate && fromname == NULL)
2756                 flags.doall = B_TRUE;
2757
2758         err = zfs_send(zhp, fromname, toname, flags, STDOUT_FILENO, NULL, 0,
2759             extraverbose ? &dbgnv : NULL);
2760
2761         if (extraverbose) {
2762                 /*
2763                  * dump_nvlist prints to stdout, but that's been
2764                  * redirected to a file.  Make it print to stderr
2765                  * instead.
2766                  */
2767                 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
2768                 dump_nvlist(dbgnv, 0);
2769                 nvlist_free(dbgnv);
2770         }
2771         zfs_close(zhp);
2772
2773         return (err != 0);
2774 }
2775
2776 /*
2777  * zfs receive [-vnFu] [-d | -e] <fs@snap>
2778  *
2779  * Restore a backup stream from stdin.
2780  */
2781 static int
2782 zfs_do_receive(int argc, char **argv)
2783 {
2784         int c, err;
2785         recvflags_t flags = { 0 };
2786
2787         /* check options */
2788         while ((c = getopt(argc, argv, ":denuvF")) != -1) {
2789                 switch (c) {
2790                 case 'd':
2791                         flags.isprefix = B_TRUE;
2792                         break;
2793                 case 'e':
2794                         flags.isprefix = B_TRUE;
2795                         flags.istail = B_TRUE;
2796                         break;
2797                 case 'n':
2798                         flags.dryrun = B_TRUE;
2799                         break;
2800                 case 'u':
2801                         flags.nomount = B_TRUE;
2802                         break;
2803                 case 'v':
2804                         flags.verbose = B_TRUE;
2805                         break;
2806                 case 'F':
2807                         flags.force = B_TRUE;
2808                         break;
2809                 case ':':
2810                         (void) fprintf(stderr, gettext("missing argument for "
2811                             "'%c' option\n"), optopt);
2812                         usage(B_FALSE);
2813                         break;
2814                 case '?':
2815                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2816                             optopt);
2817                         usage(B_FALSE);
2818                 }
2819         }
2820
2821         argc -= optind;
2822         argv += optind;
2823
2824         /* check number of arguments */
2825         if (argc < 1) {
2826                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2827                 usage(B_FALSE);
2828         }
2829         if (argc > 1) {
2830                 (void) fprintf(stderr, gettext("too many arguments\n"));
2831                 usage(B_FALSE);
2832         }
2833
2834         if (isatty(STDIN_FILENO)) {
2835                 (void) fprintf(stderr,
2836                     gettext("Error: Backup stream can not be read "
2837                     "from a terminal.\n"
2838                     "You must redirect standard input.\n"));
2839                 return (1);
2840         }
2841
2842         err = zfs_receive(g_zfs, argv[0], flags, STDIN_FILENO, NULL);
2843
2844         return (err != 0);
2845 }
2846
2847 static int
2848 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
2849 {
2850         int errors = 0;
2851         int i;
2852         const char *tag;
2853         boolean_t recursive = B_FALSE;
2854         boolean_t temphold = B_FALSE;
2855         const char *opts = holding ? "rt" : "r";
2856         int c;
2857
2858         /* check options */
2859         while ((c = getopt(argc, argv, opts)) != -1) {
2860                 switch (c) {
2861                 case 'r':
2862                         recursive = B_TRUE;
2863                         break;
2864                 case 't':
2865                         temphold = B_TRUE;
2866                         break;
2867                 case '?':
2868                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2869                             optopt);
2870                         usage(B_FALSE);
2871                 }
2872         }
2873
2874         argc -= optind;
2875         argv += optind;
2876
2877         /* check number of arguments */
2878         if (argc < 2)
2879                 usage(B_FALSE);
2880
2881         tag = argv[0];
2882         --argc;
2883         ++argv;
2884
2885         if (holding && tag[0] == '.') {
2886                 /* tags starting with '.' are reserved for libzfs */
2887                 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
2888                 usage(B_FALSE);
2889         }
2890
2891         for (i = 0; i < argc; ++i) {
2892                 zfs_handle_t *zhp;
2893                 char parent[ZFS_MAXNAMELEN];
2894                 const char *delim;
2895                 char *path = argv[i];
2896
2897                 delim = strchr(path, '@');
2898                 if (delim == NULL) {
2899                         (void) fprintf(stderr,
2900                             gettext("'%s' is not a snapshot\n"), path);
2901                         ++errors;
2902                         continue;
2903                 }
2904                 (void) strncpy(parent, path, delim - path);
2905                 parent[delim - path] = '\0';
2906
2907                 zhp = zfs_open(g_zfs, parent,
2908                     ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2909                 if (zhp == NULL) {
2910                         ++errors;
2911                         continue;
2912                 }
2913                 if (holding) {
2914                         if (zfs_hold(zhp, delim+1, tag, recursive,
2915                             temphold, B_FALSE, -1, 0, 0) != 0)
2916                                 ++errors;
2917                 } else {
2918                         if (zfs_release(zhp, delim+1, tag, recursive) != 0)
2919                                 ++errors;
2920                 }
2921                 zfs_close(zhp);
2922         }
2923
2924         return (errors != 0);
2925 }
2926
2927 /*
2928  * zfs hold [-r] [-t] <tag> <snap> ...
2929  *
2930  *      -r      Recursively hold
2931  *      -t      Temporary hold (hidden option)
2932  *
2933  * Apply a user-hold with the given tag to the list of snapshots.
2934  */
2935 static int
2936 zfs_do_hold(int argc, char **argv)
2937 {
2938         return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
2939 }
2940
2941 /*
2942  * zfs release [-r] <tag> <snap> ...
2943  *
2944  *      -r      Recursively release
2945  *
2946  * Release a user-hold with the given tag from the list of snapshots.
2947  */
2948 static int
2949 zfs_do_release(int argc, char **argv)
2950 {
2951         return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
2952 }
2953
2954 #define CHECK_SPINNER 30
2955 #define SPINNER_TIME 3          /* seconds */
2956 #define MOUNT_TIME 5            /* seconds */
2957
2958 #ifdef HAVE_ZPL
2959 static int
2960 get_one_dataset(zfs_handle_t *zhp, void *data)
2961 {
2962         static char *spin[] = { "-", "\\", "|", "/" };
2963         static int spinval = 0;
2964         static int spincheck = 0;
2965         static time_t last_spin_time = (time_t)0;
2966         get_all_cb_t *cbp = data;
2967         zfs_type_t type = zfs_get_type(zhp);
2968
2969         if (cbp->cb_verbose) {
2970                 if (--spincheck < 0) {
2971                         time_t now = time(NULL);
2972                         if (last_spin_time + SPINNER_TIME < now) {
2973                                 update_progress(spin[spinval++ % 4]);
2974                                 last_spin_time = now;
2975                         }
2976                         spincheck = CHECK_SPINNER;
2977                 }
2978         }
2979
2980         /*
2981          * Interate over any nested datasets.
2982          */
2983         if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
2984                 zfs_close(zhp);
2985                 return (1);
2986         }
2987
2988         /*
2989          * Skip any datasets whose type does not match.
2990          */
2991         if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
2992                 zfs_close(zhp);
2993                 return (0);
2994         }
2995         libzfs_add_handle(cbp, zhp);
2996         assert(cbp->cb_used <= cbp->cb_alloc);
2997
2998         return (0);
2999 }
3000
3001 static void
3002 get_all_datasets(zfs_handle_t ***dslist, size_t *count, boolean_t verbose)
3003 {
3004         get_all_cb_t cb = { 0 };
3005         cb.cb_verbose = verbose;
3006         cb.cb_getone = get_one_dataset;
3007
3008         if (verbose)
3009                 set_progress_header(gettext("Reading ZFS config"));
3010         (void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
3011
3012         *dslist = cb.cb_handles;
3013         *count = cb.cb_used;
3014
3015         if (verbose)
3016                 finish_progress(gettext("done."));
3017 }
3018
3019 /*
3020  * Generic callback for sharing or mounting filesystems.  Because the code is so
3021  * similar, we have a common function with an extra parameter to determine which
3022  * mode we are using.
3023  */
3024 #define OP_SHARE        0x1
3025 #define OP_MOUNT        0x2
3026
3027 /*
3028  * Share or mount a dataset.
3029  */
3030 static int
3031 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
3032     boolean_t explicit, const char *options)
3033 {
3034         char mountpoint[ZFS_MAXPROPLEN];
3035         char shareopts[ZFS_MAXPROPLEN];
3036         char smbshareopts[ZFS_MAXPROPLEN];
3037         const char *cmdname = op == OP_SHARE ? "share" : "mount";
3038         struct mnttab mnt;
3039         uint64_t zoned, canmount;
3040         boolean_t shared_nfs, shared_smb;
3041
3042         assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
3043
3044         /*
3045          * Check to make sure we can mount/share this dataset.  If we
3046          * are in the global zone and the filesystem is exported to a
3047          * local zone, or if we are in a local zone and the
3048          * filesystem is not exported, then it is an error.
3049          */
3050         zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
3051
3052         if (zoned && getzoneid() == GLOBAL_ZONEID) {
3053                 if (!explicit)
3054                         return (0);
3055
3056                 (void) fprintf(stderr, gettext("cannot %s '%s': "
3057                     "dataset is exported to a local zone\n"), cmdname,
3058                     zfs_get_name(zhp));
3059                 return (1);
3060
3061         } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
3062                 if (!explicit)
3063                         return (0);
3064
3065                 (void) fprintf(stderr, gettext("cannot %s '%s': "
3066                     "permission denied\n"), cmdname,
3067                     zfs_get_name(zhp));
3068                 return (1);
3069         }
3070
3071         /*
3072          * Ignore any filesystems which don't apply to us. This
3073          * includes those with a legacy mountpoint, or those with
3074          * legacy share options.
3075          */
3076         verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
3077             sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
3078         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
3079             sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
3080         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
3081             sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
3082
3083         if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
3084             strcmp(smbshareopts, "off") == 0) {
3085                 if (!explicit)
3086                         return (0);
3087
3088                 (void) fprintf(stderr, gettext("cannot share '%s': "
3089                     "legacy share\n"), zfs_get_name(zhp));
3090                 (void) fprintf(stderr, gettext("use share(1M) to "
3091                     "share this filesystem, or set "
3092                     "sharenfs property on\n"));
3093                 return (1);
3094         }
3095
3096         /*
3097          * We cannot share or mount legacy filesystems. If the
3098          * shareopts is non-legacy but the mountpoint is legacy, we
3099          * treat it as a legacy share.
3100          */
3101         if (strcmp(mountpoint, "legacy") == 0) {
3102                 if (!explicit)
3103                         return (0);
3104
3105                 (void) fprintf(stderr, gettext("cannot %s '%s': "
3106                     "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
3107                 (void) fprintf(stderr, gettext("use %s(1M) to "
3108                     "%s this filesystem\n"), cmdname, cmdname);
3109                 return (1);
3110         }
3111
3112         if (strcmp(mountpoint, "none") == 0) {
3113                 if (!explicit)
3114                         return (0);
3115
3116                 (void) fprintf(stderr, gettext("cannot %s '%s': no "
3117                     "mountpoint set\n"), cmdname, zfs_get_name(zhp));
3118                 return (1);
3119         }
3120
3121         /*
3122          * canmount     explicit        outcome
3123          * on           no              pass through
3124          * on           yes             pass through
3125          * off          no              return 0
3126          * off          yes             display error, return 1
3127          * noauto       no              return 0
3128          * noauto       yes             pass through
3129          */
3130         canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
3131         if (canmount == ZFS_CANMOUNT_OFF) {
3132                 if (!explicit)
3133                         return (0);
3134
3135                 (void) fprintf(stderr, gettext("cannot %s '%s': "
3136                     "'canmount' property is set to 'off'\n"), cmdname,
3137                     zfs_get_name(zhp));
3138                 return (1);
3139         } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
3140                 return (0);
3141         }
3142
3143         /*
3144          * At this point, we have verified that the mountpoint and/or
3145          * shareopts are appropriate for auto management. If the
3146          * filesystem is already mounted or shared, return (failing
3147          * for explicit requests); otherwise mount or share the
3148          * filesystem.
3149          */
3150         switch (op) {
3151         case OP_SHARE:
3152
3153                 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
3154                 shared_smb = zfs_is_shared_smb(zhp, NULL);
3155
3156                 if ((shared_nfs && shared_smb) ||
3157                     ((shared_nfs && strcmp(shareopts, "on") == 0) &&
3158                     (strcmp(smbshareopts, "off") == 0)) ||
3159                     ((shared_smb && strcmp(smbshareopts, "on") == 0) &&
3160                     (strcmp(shareopts, "off") == 0))) {
3161                         if (!explicit)
3162                                 return (0);
3163
3164                         (void) fprintf(stderr, gettext("cannot share "
3165                             "'%s': filesystem already shared\n"),
3166                             zfs_get_name(zhp));
3167                         return (1);
3168                 }
3169
3170                 if (!zfs_is_mounted(zhp, NULL) &&
3171                     zfs_mount(zhp, NULL, 0) != 0)
3172                         return (1);
3173
3174                 if (protocol == NULL) {
3175                         if (zfs_shareall(zhp) != 0)
3176                                 return (1);
3177                 } else if (strcmp(protocol, "nfs") == 0) {
3178                         if (zfs_share_nfs(zhp))
3179                                 return (1);
3180                 } else if (strcmp(protocol, "smb") == 0) {
3181                         if (zfs_share_smb(zhp))
3182                                 return (1);
3183                 } else {
3184                         (void) fprintf(stderr, gettext("cannot share "
3185                             "'%s': invalid share type '%s' "
3186                             "specified\n"),
3187                             zfs_get_name(zhp), protocol);
3188                         return (1);
3189                 }
3190
3191                 break;
3192
3193         case OP_MOUNT:
3194                 if (options == NULL)
3195                         mnt.mnt_mntopts = "";
3196                 else
3197                         mnt.mnt_mntopts = (char *)options;
3198
3199                 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
3200                     zfs_is_mounted(zhp, NULL)) {
3201                         if (!explicit)
3202                                 return (0);
3203
3204                         (void) fprintf(stderr, gettext("cannot mount "
3205                             "'%s': filesystem already mounted\n"),
3206                             zfs_get_name(zhp));
3207                         return (1);
3208                 }
3209
3210                 if (zfs_mount(zhp, options, flags) != 0)
3211                         return (1);
3212                 break;
3213         }
3214
3215         return (0);
3216 }
3217
3218 /*
3219  * Reports progress in the form "(current/total)".  Not thread-safe.
3220  */
3221 static void
3222 report_mount_progress(int current, int total)
3223 {
3224         static time_t last_progress_time = 0;
3225         time_t now = time(NULL);
3226         char info[32];
3227
3228         /* report 1..n instead of 0..n-1 */
3229         ++current;
3230
3231         /* display header if we're here for the first time */
3232         if (current == 1) {
3233                 set_progress_header(gettext("Mounting ZFS filesystems"));
3234         } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
3235                 /* too soon to report again */
3236                 return;
3237         }
3238
3239         last_progress_time = now;
3240
3241         (void) sprintf(info, "(%d/%d)", current, total);
3242
3243         if (current == total)
3244                 finish_progress(info);
3245         else
3246                 update_progress(info);
3247 }
3248
3249 static void
3250 append_options(char *mntopts, char *newopts)
3251 {
3252         int len = strlen(mntopts);
3253
3254         /* original length plus new string to append plus 1 for the comma */
3255         if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
3256                 (void) fprintf(stderr, gettext("the opts argument for "
3257                     "'%s' option is too long (more than %d chars)\n"),
3258                     "-o", MNT_LINE_MAX);
3259                 usage(B_FALSE);
3260         }
3261
3262         if (*mntopts)
3263                 mntopts[len++] = ',';
3264
3265         (void) strcpy(&mntopts[len], newopts);
3266 }
3267
3268 static int
3269 share_mount(int op, int argc, char **argv)
3270 {
3271         int do_all = 0;
3272         boolean_t verbose = B_FALSE;
3273         int c, ret = 0;
3274         char *options = NULL;
3275         int flags = 0;
3276
3277         /* check options */
3278         while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
3279             != -1) {
3280                 switch (c) {
3281                 case 'a':
3282                         do_all = 1;
3283                         break;
3284                 case 'v':
3285                         verbose = B_TRUE;
3286                         break;
3287                 case 'o':
3288                         if (*optarg == '\0') {
3289                                 (void) fprintf(stderr, gettext("empty mount "
3290                                     "options (-o) specified\n"));
3291                                 usage(B_FALSE);
3292                         }
3293
3294                         if (options == NULL)
3295                                 options = safe_malloc(MNT_LINE_MAX + 1);
3296
3297                         /* option validation is done later */
3298                         append_options(options, optarg);
3299                         break;
3300
3301                 case 'O':
3302                         flags |= MS_OVERLAY;
3303                         break;
3304                 case ':':
3305                         (void) fprintf(stderr, gettext("missing argument for "
3306                             "'%c' option\n"), optopt);
3307                         usage(B_FALSE);
3308                         break;
3309                 case '?':
3310                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3311                             optopt);
3312                         usage(B_FALSE);
3313                 }
3314         }
3315
3316         argc -= optind;
3317         argv += optind;
3318
3319         /* check number of arguments */
3320         if (do_all) {
3321                 zfs_handle_t **dslist = NULL;
3322                 size_t i, count = 0;
3323                 char *protocol = NULL;
3324
3325                 if (op == OP_SHARE && argc > 0) {
3326                         if (strcmp(argv[0], "nfs") != 0 &&
3327                             strcmp(argv[0], "smb") != 0) {
3328                                 (void) fprintf(stderr, gettext("share type "
3329                                     "must be 'nfs' or 'smb'\n"));
3330                                 usage(B_FALSE);
3331                         }
3332                         protocol = argv[0];
3333                         argc--;
3334                         argv++;
3335                 }
3336
3337                 if (argc != 0) {
3338                         (void) fprintf(stderr, gettext("too many arguments\n"));
3339                         usage(B_FALSE);
3340                 }
3341
3342                 start_progress_timer();
3343                 get_all_datasets(&dslist, &count, verbose);
3344
3345                 if (count == 0)
3346                         return (0);
3347
3348                 qsort(dslist, count, sizeof (void *), libzfs_dataset_cmp);
3349
3350                 for (i = 0; i < count; i++) {
3351                         if (verbose)
3352                                 report_mount_progress(i, count);
3353
3354                         if (share_mount_one(dslist[i], op, flags, protocol,
3355                             B_FALSE, options) != 0)
3356                                 ret = 1;
3357                         zfs_close(dslist[i]);
3358                 }
3359
3360                 free(dslist);
3361         } else if (argc == 0) {
3362                 struct mnttab entry;
3363
3364                 if ((op == OP_SHARE) || (options != NULL)) {
3365                         (void) fprintf(stderr, gettext("missing filesystem "
3366                             "argument (specify -a for all)\n"));
3367                         usage(B_FALSE);
3368                 }
3369
3370                 /*
3371                  * When mount is given no arguments, go through /etc/mnttab and
3372                  * display any active ZFS mounts.  We hide any snapshots, since
3373                  * they are controlled automatically.
3374                  */
3375                 rewind(mnttab_file);
3376                 while (getmntent(mnttab_file, &entry) == 0) {
3377                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
3378                             strchr(entry.mnt_special, '@') != NULL)
3379                                 continue;
3380
3381                         (void) printf("%-30s  %s\n", entry.mnt_special,
3382                             entry.mnt_mountp);
3383                 }
3384
3385         } else {
3386                 zfs_handle_t *zhp;
3387
3388                 if (argc > 1) {
3389                         (void) fprintf(stderr,
3390                             gettext("too many arguments\n"));
3391                         usage(B_FALSE);
3392                 }
3393
3394                 if ((zhp = zfs_open(g_zfs, argv[0],
3395                     ZFS_TYPE_FILESYSTEM)) == NULL) {
3396                         ret = 1;
3397                 } else {
3398                         ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
3399                             options);
3400                         zfs_close(zhp);
3401                 }
3402         }
3403
3404         return (ret);
3405 }
3406 #endif  /* HAVE_ZPL */
3407
3408 /*
3409  * zfs mount -a [nfs]
3410  * zfs mount filesystem
3411  *
3412  * Mount all filesystems, or mount the given filesystem.
3413  */
3414 static int
3415 zfs_do_mount(int argc, char **argv)
3416 {
3417 #ifdef HAVE_ZPL
3418         return (share_mount(OP_MOUNT, argc, argv));
3419 #else
3420         return ENOSYS;
3421 #endif  /* HAVE_ZPL */
3422 }
3423
3424 /*
3425  * zfs share -a [nfs | smb]
3426  * zfs share filesystem
3427  *
3428  * Share all filesystems, or share the given filesystem.
3429  */
3430 static int
3431 zfs_do_share(int argc, char **argv)
3432 {
3433 #ifdef HAVE_ZPL
3434         return (share_mount(OP_SHARE, argc, argv));
3435 #else
3436         return ENOSYS;
3437 #endif  /* HAVE_ZPL */
3438 }
3439
3440 #ifdef HAVE_ZPL
3441 typedef struct unshare_unmount_node {
3442         zfs_handle_t    *un_zhp;
3443         char            *un_mountp;
3444         uu_avl_node_t   un_avlnode;
3445 } unshare_unmount_node_t;
3446
3447 /* ARGSUSED */
3448 static int
3449 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
3450 {
3451         const unshare_unmount_node_t *l = larg;
3452         const unshare_unmount_node_t *r = rarg;
3453
3454         return (strcmp(l->un_mountp, r->un_mountp));
3455 }
3456
3457 /*
3458  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
3459  * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
3460  * and unmount it appropriately.
3461  */
3462 static int
3463 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
3464 {
3465         zfs_handle_t *zhp;
3466         int ret;
3467         struct stat64 statbuf;
3468         struct extmnttab entry;
3469         const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
3470         ino_t path_inode;
3471
3472         /*
3473          * Search for the path in /etc/mnttab.  Rather than looking for the
3474          * specific path, which can be fooled by non-standard paths (i.e. ".."
3475          * or "//"), we stat() the path and search for the corresponding
3476          * (major,minor) device pair.
3477          */
3478         if (stat64(path, &statbuf) != 0) {
3479                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3480                     cmdname, path, strerror(errno));
3481                 return (1);
3482         }
3483         path_inode = statbuf.st_ino;
3484
3485         /*
3486          * Search for the given (major,minor) pair in the mount table.
3487          */
3488         rewind(mnttab_file);
3489         while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
3490                 if (entry.mnt_major == major(statbuf.st_dev) &&
3491                     entry.mnt_minor == minor(statbuf.st_dev))
3492                         break;
3493         }
3494         if (ret != 0) {
3495                 if (op == OP_SHARE) {
3496                         (void) fprintf(stderr, gettext("cannot %s '%s': not "
3497                             "currently mounted\n"), cmdname, path);
3498                         return (1);
3499                 }
3500                 (void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
3501                     path);
3502                 if ((ret = umount2(path, flags)) != 0)
3503                         (void) fprintf(stderr, gettext("%s: %s\n"), path,
3504                             strerror(errno));
3505                 return (ret != 0);
3506         }
3507
3508         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
3509                 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
3510                     "filesystem\n"), cmdname, path);
3511                 return (1);
3512         }
3513
3514         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3515             ZFS_TYPE_FILESYSTEM)) == NULL)
3516                 return (1);
3517
3518         ret = 1;
3519         if (stat64(entry.mnt_mountp, &statbuf) != 0) {
3520                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3521                     cmdname, path, strerror(errno));
3522                 goto out;
3523         } else if (statbuf.st_ino != path_inode) {
3524                 (void) fprintf(stderr, gettext("cannot "
3525                     "%s '%s': not a mountpoint\n"), cmdname, path);
3526                 goto out;
3527         }
3528
3529         if (op == OP_SHARE) {
3530                 char nfs_mnt_prop[ZFS_MAXPROPLEN];
3531                 char smbshare_prop[ZFS_MAXPROPLEN];
3532
3533                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
3534                     sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
3535                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
3536                     sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
3537
3538                 if (strcmp(nfs_mnt_prop, "off") == 0 &&
3539                     strcmp(smbshare_prop, "off") == 0) {
3540                         (void) fprintf(stderr, gettext("cannot unshare "
3541                             "'%s': legacy share\n"), path);
3542                         (void) fprintf(stderr, gettext("use "
3543                             "unshare(1M) to unshare this filesystem\n"));
3544                 } else if (!zfs_is_shared(zhp)) {
3545                         (void) fprintf(stderr, gettext("cannot unshare '%s': "
3546                             "not currently shared\n"), path);
3547                 } else {
3548                         ret = zfs_unshareall_bypath(zhp, path);
3549                 }
3550         } else {
3551                 char mtpt_prop[ZFS_MAXPROPLEN];
3552
3553                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
3554                     sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
3555
3556                 if (is_manual) {
3557                         ret = zfs_unmount(zhp, NULL, flags);
3558                 } else if (strcmp(mtpt_prop, "legacy") == 0) {
3559                         (void) fprintf(stderr, gettext("cannot unmount "
3560                             "'%s': legacy mountpoint\n"),
3561                             zfs_get_name(zhp));
3562                         (void) fprintf(stderr, gettext("use umount(1M) "
3563                             "to unmount this filesystem\n"));
3564                 } else {
3565                         ret = zfs_unmountall(zhp, flags);
3566                 }
3567         }
3568
3569 out:
3570         zfs_close(zhp);
3571
3572         return (ret != 0);
3573 }
3574
3575 /*
3576  * Generic callback for unsharing or unmounting a filesystem.
3577  */
3578 static int
3579 unshare_unmount(int op, int argc, char **argv)
3580 {
3581         int do_all = 0;
3582         int flags = 0;
3583         int ret = 0;
3584         int c;
3585         zfs_handle_t *zhp;
3586         char nfs_mnt_prop[ZFS_MAXPROPLEN];
3587         char sharesmb[ZFS_MAXPROPLEN];
3588
3589         /* check options */
3590         while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
3591                 switch (c) {
3592                 case 'a':
3593                         do_all = 1;
3594                         break;
3595                 case 'f':
3596                         flags = MS_FORCE;
3597                         break;
3598                 case '?':
3599                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3600                             optopt);
3601                         usage(B_FALSE);
3602                 }
3603         }
3604
3605         argc -= optind;
3606         argv += optind;
3607
3608         if (do_all) {
3609                 /*
3610                  * We could make use of zfs_for_each() to walk all datasets in
3611                  * the system, but this would be very inefficient, especially
3612                  * since we would have to linearly search /etc/mnttab for each
3613                  * one.  Instead, do one pass through /etc/mnttab looking for
3614                  * zfs entries and call zfs_unmount() for each one.
3615                  *
3616                  * Things get a little tricky if the administrator has created
3617                  * mountpoints beneath other ZFS filesystems.  In this case, we
3618                  * have to unmount the deepest filesystems first.  To accomplish
3619                  * this, we place all the mountpoints in an AVL tree sorted by
3620                  * the special type (dataset name), and walk the result in
3621                  * reverse to make sure to get any snapshots first.
3622                  */
3623                 struct mnttab entry;
3624                 uu_avl_pool_t *pool;
3625                 uu_avl_t *tree = NULL;
3626                 unshare_unmount_node_t *node;
3627                 uu_avl_index_t idx;
3628                 uu_avl_walk_t *walk;
3629
3630                 if (argc != 0) {
3631                         (void) fprintf(stderr, gettext("too many arguments\n"));
3632                         usage(B_FALSE);
3633                 }
3634
3635                 if (((pool = uu_avl_pool_create("unmount_pool",
3636                     sizeof (unshare_unmount_node_t),
3637                     offsetof(unshare_unmount_node_t, un_avlnode),
3638                     unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
3639                     ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
3640                         nomem();
3641
3642                 rewind(mnttab_file);
3643                 while (getmntent(mnttab_file, &entry) == 0) {
3644
3645                         /* ignore non-ZFS entries */
3646                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
3647                                 continue;
3648
3649                         /* ignore snapshots */
3650                         if (strchr(entry.mnt_special, '@') != NULL)
3651                                 continue;
3652
3653                         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3654                             ZFS_TYPE_FILESYSTEM)) == NULL) {
3655                                 ret = 1;
3656                                 continue;
3657                         }
3658
3659                         switch (op) {
3660                         case OP_SHARE:
3661                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3662                                     nfs_mnt_prop,
3663                                     sizeof (nfs_mnt_prop),
3664                                     NULL, NULL, 0, B_FALSE) == 0);
3665                                 if (strcmp(nfs_mnt_prop, "off") != 0)
3666                                         break;
3667                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3668                                     nfs_mnt_prop,
3669                                     sizeof (nfs_mnt_prop),
3670                                     NULL, NULL, 0, B_FALSE) == 0);
3671                                 if (strcmp(nfs_mnt_prop, "off") == 0)
3672                                         continue;
3673                                 break;
3674                         case OP_MOUNT:
3675                                 /* Ignore legacy mounts */
3676                                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
3677                                     nfs_mnt_prop,
3678                                     sizeof (nfs_mnt_prop),
3679                                     NULL, NULL, 0, B_FALSE) == 0);
3680                                 if (strcmp(nfs_mnt_prop, "legacy") == 0)
3681                                         continue;
3682                                 /* Ignore canmount=noauto mounts */
3683                                 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
3684                                     ZFS_CANMOUNT_NOAUTO)
3685                                         continue;
3686                         default:
3687                                 break;
3688                         }
3689
3690                         node = safe_malloc(sizeof (unshare_unmount_node_t));
3691                         node->un_zhp = zhp;
3692                         node->un_mountp = safe_strdup(entry.mnt_mountp);
3693
3694                         uu_avl_node_init(node, &node->un_avlnode, pool);
3695
3696                         if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
3697                                 uu_avl_insert(tree, node, idx);
3698                         } else {
3699                                 zfs_close(node->un_zhp);
3700                                 free(node->un_mountp);
3701                                 free(node);
3702                         }
3703                 }
3704
3705                 /*
3706                  * Walk the AVL tree in reverse, unmounting each filesystem and
3707                  * removing it from the AVL tree in the process.
3708                  */
3709                 if ((walk = uu_avl_walk_start(tree,
3710                     UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
3711                         nomem();
3712
3713                 while ((node = uu_avl_walk_next(walk)) != NULL) {
3714                         uu_avl_remove(tree, node);
3715
3716                         switch (op) {
3717                         case OP_SHARE:
3718                                 if (zfs_unshareall_bypath(node->un_zhp,
3719                                     node->un_mountp) != 0)
3720                                         ret = 1;
3721                                 break;
3722
3723                         case OP_MOUNT:
3724                                 if (zfs_unmount(node->un_zhp,
3725                                     node->un_mountp, flags) != 0)
3726                                         ret = 1;
3727                                 break;
3728                         }
3729
3730                         zfs_close(node->un_zhp);
3731                         free(node->un_mountp);
3732                         free(node);
3733                 }
3734
3735                 uu_avl_walk_end(walk);
3736                 uu_avl_destroy(tree);
3737                 uu_avl_pool_destroy(pool);
3738
3739         } else {
3740                 if (argc != 1) {
3741                         if (argc == 0)
3742                                 (void) fprintf(stderr,
3743                                     gettext("missing filesystem argument\n"));
3744                         else
3745                                 (void) fprintf(stderr,
3746                                     gettext("too many arguments\n"));
3747                         usage(B_FALSE);
3748                 }
3749
3750                 /*
3751                  * We have an argument, but it may be a full path or a ZFS
3752                  * filesystem.  Pass full paths off to unmount_path() (shared by
3753                  * manual_unmount), otherwise open the filesystem and pass to
3754                  * zfs_unmount().
3755                  */
3756                 if (argv[0][0] == '/')
3757                         return (unshare_unmount_path(op, argv[0],
3758                             flags, B_FALSE));
3759
3760                 if ((zhp = zfs_open(g_zfs, argv[0],
3761                     ZFS_TYPE_FILESYSTEM)) == NULL)
3762                         return (1);
3763
3764                 verify(zfs_prop_get(zhp, op == OP_SHARE ?
3765                     ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
3766                     nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
3767                     NULL, 0, B_FALSE) == 0);
3768
3769                 switch (op) {
3770                 case OP_SHARE:
3771                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3772                             nfs_mnt_prop,
3773                             sizeof (nfs_mnt_prop),
3774                             NULL, NULL, 0, B_FALSE) == 0);
3775                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3776                             sharesmb, sizeof (sharesmb), NULL, NULL,
3777                             0, B_FALSE) == 0);
3778
3779                         if (strcmp(nfs_mnt_prop, "off") == 0 &&
3780                             strcmp(sharesmb, "off") == 0) {
3781                                 (void) fprintf(stderr, gettext("cannot "
3782                                     "unshare '%s': legacy share\n"),
3783                                     zfs_get_name(zhp));
3784                                 (void) fprintf(stderr, gettext("use "
3785                                     "unshare(1M) to unshare this "
3786                                     "filesystem\n"));
3787                                 ret = 1;
3788                         } else if (!zfs_is_shared(zhp)) {
3789                                 (void) fprintf(stderr, gettext("cannot "
3790                                     "unshare '%s': not currently "
3791                                     "shared\n"), zfs_get_name(zhp));
3792                                 ret = 1;
3793                         } else if (zfs_unshareall(zhp) != 0) {
3794                                 ret = 1;
3795                         }
3796                         break;
3797
3798                 case OP_MOUNT:
3799                         if (strcmp(nfs_mnt_prop, "legacy") == 0) {
3800                                 (void) fprintf(stderr, gettext("cannot "
3801                                     "unmount '%s': legacy "
3802                                     "mountpoint\n"), zfs_get_name(zhp));
3803                                 (void) fprintf(stderr, gettext("use "
3804                                     "umount(1M) to unmount this "
3805                                     "filesystem\n"));
3806                                 ret = 1;
3807                         } else if (!zfs_is_mounted(zhp, NULL)) {
3808                                 (void) fprintf(stderr, gettext("cannot "
3809                                     "unmount '%s': not currently "
3810                                     "mounted\n"),
3811                                     zfs_get_name(zhp));
3812                                 ret = 1;
3813                         } else if (zfs_unmountall(zhp, flags) != 0) {
3814                                 ret = 1;
3815                         }
3816                         break;
3817                 }
3818
3819                 zfs_close(zhp);
3820         }
3821
3822         return (ret);
3823 }
3824 #endif  /* HAVE_ZPL */
3825
3826 /*
3827  * zfs unmount -a
3828  * zfs unmount filesystem
3829  *
3830  * Unmount all filesystems, or a specific ZFS filesystem.
3831  */
3832 static int
3833 zfs_do_unmount(int argc, char **argv)
3834 {
3835 #ifdef HAVE_ZPL
3836         return (unshare_unmount(OP_MOUNT, argc, argv));
3837 #else
3838         return ENOSYS;
3839 #endif  /* HAVE_ZPL */
3840 }
3841
3842 /*
3843  * zfs unshare -a
3844  * zfs unshare filesystem
3845  *
3846  * Unshare all filesystems, or a specific ZFS filesystem.
3847  */
3848 static int
3849 zfs_do_unshare(int argc, char **argv)
3850 {
3851 #ifdef HAVE_ZPL
3852         return (unshare_unmount(OP_SHARE, argc, argv));
3853 #else
3854         return ENOSYS;
3855 #endif  /* HAVE_ZPL */
3856 }
3857
3858 /* ARGSUSED */
3859 static int
3860 zfs_do_python(int argc, char **argv)
3861 {
3862         (void) execv(pypath, argv-1);
3863         (void) printf("internal error: %s not found\n", pypath);
3864         return (-1);
3865 }
3866
3867 typedef struct option_map {
3868         const char *name;
3869         int mask;
3870 } option_map_t;
3871
3872 static const option_map_t option_map[] = {
3873         /* Canonicalized filesystem independent options from mount(8) */
3874         { MNTOPT_NOAUTO,        MS_COMMENT      },
3875         { MNTOPT_DEFAULTS,      MS_COMMENT      },
3876         { MNTOPT_NODEVICES,     MS_NODEV        },
3877         { MNTOPT_DIRSYNC,       MS_DIRSYNC      },
3878         { MNTOPT_NOEXEC,        MS_NOEXEC       },
3879         { MNTOPT_GROUP,         MS_GROUP        },
3880         { MNTOPT_NETDEV,        MS_COMMENT      },
3881         { MNTOPT_NOFAIL,        MS_COMMENT      },
3882         { MNTOPT_NOSUID,        MS_NOSUID       },
3883         { MNTOPT_OWNER,         MS_OWNER        },
3884         { MNTOPT_REMOUNT,       MS_REMOUNT      },
3885         { MNTOPT_RO,            MS_RDONLY       },
3886         { MNTOPT_SYNC,          MS_SYNCHRONOUS  },
3887         { MNTOPT_USER,          MS_USERS        },
3888         { MNTOPT_USERS,         MS_USERS        },
3889 #ifdef MS_NOATIME
3890         { MNTOPT_NOATIME,       MS_NOATIME      },
3891 #endif
3892 #ifdef MS_NODIRATIME
3893         { MNTOPT_NODIRATIME,    MS_NODIRATIME   },
3894 #endif
3895 #ifdef MS_RELATIME
3896         { MNTOPT_RELATIME,      MS_RELATIME     },
3897 #endif
3898 #ifdef MS_STRICTATIME
3899         { MNTOPT_DFRATIME,      MS_STRICTATIME  },
3900 #endif
3901 #ifdef HAVE_SELINUX
3902         { MNTOPT_CONTEXT,       MS_COMMENT      },
3903         { MNTOPT_FSCONTEXT,     MS_COMMENT      },
3904         { MNTOPT_DEFCONTEXT,    MS_COMMENT      },
3905         { MNTOPT_ROOTCONTEXT,   MS_COMMENT      },
3906 #endif
3907 #ifdef MS_I_VERSION
3908         { MNTOPT_IVERSION,      MS_I_VERSION    },
3909 #endif
3910 #ifdef MS_MANDLOCK
3911         { MNTOPT_NBMAND,        MS_MANDLOCK     },
3912 #endif
3913         /* Valid options not found in mount(8) */
3914         { MNTOPT_BIND,          MS_BIND         },
3915         { MNTOPT_RBIND,         MS_BIND|MS_REC  },
3916         { MNTOPT_COMMENT,       MS_COMMENT      },
3917         { MNTOPT_BOOTWAIT,      MS_COMMENT      },
3918         { MNTOPT_NOBOOTWAIT,    MS_COMMENT      },
3919         { MNTOPT_OPTIONAL,      MS_COMMENT      },
3920         { MNTOPT_SHOWTHROUGH,   MS_COMMENT      },
3921 #ifdef MS_NOSUB
3922         { MNTOPT_NOSUB,         MS_NOSUB        },
3923 #endif
3924 #ifdef MS_SILENT
3925         { MNTOPT_QUIET,         MS_SILENT       },
3926 #endif
3927         /* Custom zfs options */
3928         { MNTOPT_NOXATTR,       MS_COMMENT      },
3929         { NULL,                 0               } };
3930
3931 /*
3932  * Break the mount option in to a name/value pair.  The name is
3933  * validated against the option map and mount flags set accordingly.
3934  */
3935 static int
3936 parse_option(char *mntopt, unsigned long *mntflags, int sloppy)
3937 {
3938         const option_map_t *opt;
3939         char *ptr, *name, *value = NULL;
3940         int rc;
3941
3942         name = strdup(mntopt);
3943         if (name == NULL)
3944                 return (ENOMEM);
3945
3946         for (ptr = name; ptr && *ptr; ptr++) {
3947                 if (*ptr == '=') {
3948                         *ptr = '\0';
3949                         value = ptr+1;
3950                         break;
3951                 }
3952         }
3953
3954         for (opt = option_map; opt->name != NULL; opt++) {
3955                 if (strncmp(name, opt->name, strlen(name)) == 0) {
3956                         *mntflags |= opt->mask;
3957
3958                         /* MS_USERS implies default user options */
3959                         if (opt->mask & (MS_USERS))
3960                                 *mntflags |= (MS_NOEXEC|MS_NOSUID|MS_NODEV);
3961
3962                         /* MS_OWNER|MS_GROUP imply default owner options */
3963                         if (opt->mask & (MS_OWNER | MS_GROUP))
3964                                 *mntflags |= (MS_NOSUID|MS_NODEV);
3965
3966                         rc = 0;
3967                         goto out;
3968                 }
3969         }
3970
3971         if (!sloppy)
3972                 rc = ENOENT;
3973 out:
3974         /* If required further process on the value may be done here */
3975         free(name);
3976         return (rc);
3977 }
3978
3979 /*
3980  * Translate the mount option string in to MS_* mount flags for the
3981  * kernel vfs.  When sloppy is non-zero unknown options will be ignored
3982  * otherwise they are considered fatal are copied in to badopt.
3983  */
3984 static int
3985 parse_options(char *mntopts, unsigned long *mntflags, int sloppy, char *badopt)
3986 {
3987         int rc = 0, quote = 0;
3988         char *ptr, *opt, *opts;
3989
3990         opts = strdup(mntopts);
3991         if (opts == NULL)
3992                 return (ENOMEM);
3993
3994         *mntflags = 0;
3995         opt = NULL;
3996
3997         /*
3998          * Scan through all mount options which must be comma delimited.
3999          * We must be careful to notice regions which are double quoted
4000          * and skip commas in these regions.  Each option is then checked
4001          * to determine if it is a known option.
4002          */
4003         for (ptr = opts; ptr && *ptr; ptr++) {
4004                 if (opt == NULL)
4005                         opt = ptr;
4006
4007                 if (*ptr == '"')
4008                         quote = !quote;
4009
4010                 if (quote)
4011                         continue;
4012
4013                 if ((*ptr == ',') || (*ptr == '\0')) {
4014                         *ptr = '\0';
4015                         rc = parse_option(opt, mntflags, sloppy);
4016                         if (rc) {
4017                                 strcpy(badopt, opt);
4018                                 goto out;
4019                         }
4020
4021                         opt = NULL;
4022                 }
4023         }
4024 out:
4025         free(opts);
4026         return (rc);
4027 }
4028
4029 /*
4030  * Called when invoked as /sbin/mount.zfs, mount helper for mount(8).
4031  */
4032 static int
4033 manual_mount(int argc, char **argv)
4034 {
4035         zfs_handle_t *zhp;
4036         char legacy[ZFS_MAXPROPLEN];
4037         char mntopts[MNT_LINE_MAX] = { '\0' };
4038         char badopt[MNT_LINE_MAX] = { '\0' };
4039         char *dataset, *mntpoint;
4040         unsigned long mntflags;
4041         int sloppy = 0, fake = 0, verbose = 0;
4042         int rc, c;
4043
4044         /* check options */
4045         while ((c = getopt(argc, argv, "sfnvo:h?")) != -1) {
4046                 switch (c) {
4047                 case 's':
4048                         sloppy = 1;
4049                         break;
4050                 case 'f':
4051                         fake = 1;
4052                         break;
4053                 case 'n':
4054                         /* Ignored, handled by mount(8) */
4055                         break;
4056                 case 'v':
4057                         verbose++;
4058                         break;
4059                 case 'o':
4060                         (void) strlcpy(mntopts, optarg, sizeof (mntopts));
4061                         break;
4062                 case 'h':
4063                 case '?':
4064                         (void) fprintf(stderr, gettext("Invalid option '%c'\n"),
4065                             optopt);
4066                         (void) fprintf(stderr, gettext("Usage: mount.zfs "
4067                             "[-sfnv] [-o options] <dataset> <mountpoint>\n"));
4068                         return (MOUNT_USAGE);
4069                 }
4070         }
4071
4072         argc -= optind;
4073         argv += optind;
4074
4075         /* check that we only have two arguments */
4076         if (argc != 2) {
4077                 if (argc == 0)
4078                         (void) fprintf(stderr, gettext("missing dataset "
4079                             "argument\n"));
4080                 else if (argc == 1)
4081                         (void) fprintf(stderr,
4082                             gettext("missing mountpoint argument\n"));
4083                 else
4084                         (void) fprintf(stderr, gettext("too many arguments\n"));
4085                 (void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
4086                 return (MOUNT_USAGE);
4087         }
4088
4089         dataset = argv[0];
4090         mntpoint = argv[1];
4091
4092         /* try to open the dataset to access the mount point */
4093         if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL) {
4094                 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
4095                     "mounted, unable to open the dataset\n"), dataset);
4096                 return (MOUNT_USAGE);
4097         }
4098
4099         (void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, legacy,
4100             sizeof (legacy), NULL, NULL, 0, B_FALSE);
4101
4102         zfs_close(zhp);
4103
4104         /* check for legacy mountpoint or util mount option */
4105         if ((!strcmp(legacy, ZFS_MOUNTPOINT_LEGACY) == 0) &&
4106             (strstr(mntopts, MNTOPT_ZFSUTIL) == NULL)) {
4107                 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
4108                     "mounted using 'mount -a -t zfs'\n"), dataset);
4109                 (void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
4110                     "instead.\n"), mntpoint);
4111                 (void) fprintf(stderr, gettext("If you must use 'mount -a -t "
4112                     "zfs' or /etc/fstab, use 'zfs set mountpoint=legacy'.\n"));
4113                 (void) fprintf(stderr, gettext("See zfs(8) for more "
4114                     "information.\n"));
4115                 return (MOUNT_USAGE);
4116         }
4117
4118         /* validate mount options and set mntflags */
4119         rc = parse_options(mntopts, &mntflags, sloppy, badopt);
4120         if (rc) {
4121                 switch (rc) {
4122                 case ENOMEM:
4123                         (void) fprintf(stderr, gettext("filesystem '%s' "
4124                             "cannot be mounted due to a memory allocation "
4125                             "failure\n"), dataset);
4126                         return (MOUNT_SYSERR);
4127                 case EINVAL:
4128                         (void) fprintf(stderr, gettext("filesystem '%s' "
4129                             "cannot be mounted of due to the invalid option "
4130                             "'%s'\n"), dataset, badopt);
4131                         (void) fprintf(stderr, gettext("Use the '-s' option "
4132                             "to ignore the bad mount option.\n"));
4133                         return (MOUNT_USAGE);
4134                 default:
4135                         (void) fprintf(stderr, gettext("filesystem '%s' "
4136                             "cannot be mounted due to internal error %d\n"),
4137                             dataset, rc);
4138                         return (MOUNT_SOFTWARE);
4139                 }
4140         }
4141
4142         if (verbose > 2)
4143                 printf("mount.zfs: dataset: \"%s\", mountpoint: \"%s\" "
4144                     "mountflags: 0x%lx, mountopts: \"%s\"\n", dataset,
4145                     mntpoint, mntflags, mntopts);
4146
4147         /* load the zfs posix layer module (zpl) */
4148         if (libzfs_load_module("zpl")) {
4149                 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
4150                     "mounted without the zpl kernel module\n"), dataset);
4151                 (void) fprintf(stderr, gettext("Use 'dmesg' to determine why "
4152                     "the module could not be loaded.\n"));
4153                 return (MOUNT_SYSERR);
4154         }
4155
4156         if (!fake) {
4157                 rc = mount(dataset, mntpoint, MNTTYPE_ZFS, mntflags, mntopts);
4158                 if (rc) {
4159                         (void) fprintf(stderr, gettext("filesystem '%s' can"
4160                             "not be mounted due to error %d\n"), dataset, rc);
4161                         return (MOUNT_USAGE);
4162                 }
4163         }
4164
4165         return (MOUNT_SUCCESS);
4166 }
4167
4168 #ifdef HAVE_UNMOUNT_HELPER
4169 /*
4170  * Called when invoked as /sbin/umount.zfs, mount helper for mount(8).
4171  * Unlike a manual mount, we allow unmounts of non-legacy filesystems,
4172  * as this is the dominant administrative interface.
4173  */
4174 static int
4175 manual_unmount(int argc, char **argv)
4176 {
4177         int verbose = 0, flags = 0;
4178         int c;
4179
4180         /* check options */
4181         while ((c = getopt(argc, argv, "nlfvrh?")) != -1) {
4182                 switch (c) {
4183                 case 'n':
4184                         /* Ignored, handled by mount(8) */
4185                         break;
4186                 case 'l':
4187                         flags = MS_DETACH;
4188                         break;
4189                 case 'f':
4190                         flags = MS_FORCE;
4191                         break;
4192                 case 'v':
4193                         verbose++;
4194                         break;
4195                 case 'r':
4196                         /* Remount read-only on umount failure, unsupported */
4197                         (void) fprintf(stderr, gettext("Unsupported option "
4198                             "'%c'\n"), optopt);
4199                         return (MOUNT_USAGE);
4200                 case 'h':
4201                 case '?':
4202                         (void) fprintf(stderr, gettext("Invalid option '%c'\n"),
4203                             optopt);
4204                         (void) fprintf(stderr, gettext("Usage: umount.zfs "
4205                             "[-nlfvr] <mountpoint>\n"));
4206                         return (MOUNT_USAGE);
4207                 }
4208         }
4209
4210         argc -= optind;
4211         argv += optind;
4212
4213         /* check that we only have one argument */
4214         if (argc != 1) {
4215                 if (argc == 0)
4216                         (void) fprintf(stderr, gettext("missing mountpoint "
4217                             "argument\n"));
4218                 else
4219                         (void) fprintf(stderr, gettext("too many arguments\n"));
4220
4221                 (void) fprintf(stderr, gettext("Usage: umount.zfs [-nlfvr] "
4222                     "<mountpoint>\n"));
4223                 return (MOUNT_USAGE);
4224         }
4225
4226         return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
4227 }
4228 #endif /* HAVE_UNMOUNT_HELPER */
4229
4230 static int
4231 find_command_idx(char *command, int *idx)
4232 {
4233         int i;
4234
4235         for (i = 0; i < NCOMMAND; i++) {
4236                 if (command_table[i].name == NULL)
4237                         continue;
4238
4239                 if (strcmp(command, command_table[i].name) == 0) {
4240                         *idx = i;
4241                         return (0);
4242                 }
4243         }
4244         return (1);
4245 }
4246
4247 static int
4248 zfs_do_diff(int argc, char **argv)
4249 {
4250         zfs_handle_t *zhp;
4251         int flags = 0;
4252         char *tosnap = NULL;
4253         char *fromsnap = NULL;
4254         char *atp, *copy;
4255         int err;
4256         int c;
4257
4258         while ((c = getopt(argc, argv, "FHt")) != -1) {
4259                 switch (c) {
4260                 case 'F':
4261                         flags |= ZFS_DIFF_CLASSIFY;
4262                         break;
4263                 case 'H':
4264                         flags |= ZFS_DIFF_PARSEABLE;
4265                         break;
4266                 case 't':
4267                         flags |= ZFS_DIFF_TIMESTAMP;
4268                         break;
4269                 default:
4270                         (void) fprintf(stderr,
4271                             gettext("invalid option '%c'\n"), optopt);
4272                         usage(B_FALSE);
4273                 }
4274         }
4275
4276         argc -= optind;
4277         argv += optind;
4278
4279         if (argc < 1) {
4280                 (void) fprintf(stderr,
4281                 gettext("must provide at least one snapshot name\n"));
4282                 usage(B_FALSE);
4283         }
4284
4285         if (argc > 2) {
4286                 (void) fprintf(stderr, gettext("too many arguments\n"));
4287                 usage(B_FALSE);
4288         }
4289
4290         fromsnap = argv[0];
4291         tosnap = (argc == 2) ? argv[1] : NULL;
4292
4293         copy = NULL;
4294         if (*fromsnap != '@')
4295                 copy = strdup(fromsnap);
4296         else if (tosnap)
4297                 copy = strdup(tosnap);
4298         if (copy == NULL)
4299                 usage(B_FALSE);
4300
4301         if ((atp = strchr(copy, '@')))
4302                 *atp = '\0';
4303
4304         if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
4305                 return (1);
4306
4307         free(copy);
4308
4309         /*
4310          * Ignore SIGPIPE so that the library can give us
4311          * information on any failure
4312          */
4313         (void) sigignore(SIGPIPE);
4314
4315         err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
4316
4317         zfs_close(zhp);
4318
4319         return (err != 0);
4320 }
4321
4322 int
4323 main(int argc, char **argv)
4324 {
4325         int ret;
4326         int i = 0;
4327         char *progname;
4328         char *cmdname;
4329
4330         (void) setlocale(LC_ALL, "");
4331         (void) textdomain(TEXT_DOMAIN);
4332
4333         opterr = 0;
4334
4335         if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
4336                 (void) fprintf(stderr, gettext("internal error: unable to "
4337                     "open %s\n"), MNTTAB);
4338                 return (1);
4339         }
4340
4341         /*
4342          * This command also doubles as the /etc/fs mount and unmount program.
4343          * Determine if we should take this behavior based on argv[0].
4344          */
4345         progname = basename(argv[0]);
4346         if (strcmp(progname, "mount.zfs") == 0) {
4347                 ret = manual_mount(argc, argv);
4348 #ifdef HAVE_UNMOUNT_HELPER
4349         } else if (strcmp(progname, "umount.zfs") == 0) {
4350                 ret = manual_unmount(argc, argv);
4351 #endif /* HAVE_UNMOUNT_HELPER */
4352         } else {
4353                 /*
4354                  * Make sure the user has specified some command.
4355                  */
4356                 if (argc < 2) {
4357                         (void) fprintf(stderr, gettext("missing command\n"));
4358                         usage(B_FALSE);
4359                 }
4360
4361                 cmdname = argv[1];
4362
4363                 /*
4364                  * The 'umount' command is an alias for 'unmount'
4365                  */
4366                 if (strcmp(cmdname, "umount") == 0)
4367                         cmdname = "unmount";
4368
4369                 /*
4370                  * The 'recv' command is an alias for 'receive'
4371                  */
4372                 if (strcmp(cmdname, "recv") == 0)
4373                         cmdname = "receive";
4374
4375                 /*
4376                  * Special case '-?'
4377                  */
4378                 if ((strcmp(cmdname, "-?") == 0) ||
4379                     (strcmp(cmdname, "--help") == 0))
4380                         usage(B_TRUE);
4381
4382                 if ((g_zfs = libzfs_init()) == NULL)
4383                         return (1);
4384
4385                 zpool_set_history_str("zfs", argc, argv, history_str);
4386                 verify(zpool_stage_history(g_zfs, history_str) == 0);
4387
4388                 libzfs_print_on_error(g_zfs, B_TRUE);
4389
4390                 /*
4391                  * Run the appropriate command.
4392                  */
4393                 libzfs_mnttab_cache(g_zfs, B_TRUE);
4394                 if (find_command_idx(cmdname, &i) == 0) {
4395                         current_command = &command_table[i];
4396                         ret = command_table[i].func(argc - 1, argv + 1);
4397                 } else if (strchr(cmdname, '=') != NULL) {
4398                         verify(find_command_idx("set", &i) == 0);
4399                         current_command = &command_table[i];
4400                         ret = command_table[i].func(argc, argv);
4401                 } else {
4402                         (void) fprintf(stderr, gettext("unrecognized "
4403                             "command '%s'\n"), cmdname);
4404                         usage(B_FALSE);
4405                         ret = 1;
4406                 }
4407                 libzfs_mnttab_cache(g_zfs, B_FALSE);
4408         }
4409
4410         (void) fclose(mnttab_file);
4411
4412         libzfs_fini(g_zfs);
4413
4414         /*
4415          * The 'ZFS_ABORT' environment variable causes us to dump core on exit
4416          * for the purposes of running ::findleaks.
4417          */
4418         if (getenv("ZFS_ABORT") != NULL) {
4419                 (void) printf("dumping core by request\n");
4420                 abort();
4421         }
4422
4423         return (ret);
4424 }