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