lib: remove sparc-only libdscp
[unleashed.git] / usr / src / cmd / zfs / zfs_main.c
blobea4f6148ffb67d085350f61af3b7aaf84380c2b0
1 /*
2 * CDDL HEADER START
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.
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.
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]
19 * CDDL HEADER END
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2016 by Delphix. All rights reserved.
25 * Copyright 2012 Milan Jurik. All rights reserved.
26 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
27 * Copyright (c) 2011-2012 Pawel Jakub Dawidek. All rights reserved.
28 * Copyright (c) 2013 Steven Hartland. All rights reserved.
29 * Copyright (c) 2014 Integros [integros.com]
30 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
31 * Copyright 2016 Nexenta Systems, Inc.
34 #include <assert.h>
35 #include <ctype.h>
36 #include <errno.h>
37 #include <getopt.h>
38 #include <libgen.h>
39 #include <libintl.h>
40 #include <libuutil.h>
41 #include <libnvpair.h>
42 #include <locale.h>
43 #include <stddef.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <strings.h>
47 #include <unistd.h>
48 #include <fcntl.h>
49 #include <zone.h>
50 #include <grp.h>
51 #include <pwd.h>
52 #include <signal.h>
53 #include <sys/debug.h>
54 #include <sys/list.h>
55 #include <sys/mkdev.h>
56 #include <sys/mntent.h>
57 #include <sys/mnttab.h>
58 #include <sys/mount.h>
59 #include <sys/stat.h>
60 #include <sys/fs/zfs.h>
61 #include <sys/types.h>
62 #include <time.h>
63 #include <synch.h>
65 #include <libzfs.h>
66 #include <libzfs_core.h>
67 #include <zfs_prop.h>
68 #include <zfs_deleg.h>
69 #include <libuutil.h>
70 #include <aclutils.h>
71 #include <directory.h>
72 #include <idmap.h>
73 #include <libshare.h>
75 #include "zfs_iter.h"
76 #include "zfs_util.h"
77 #include "zfs_comutil.h"
79 libzfs_handle_t *g_zfs;
81 static FILE *mnttab_file;
82 static char history_str[HIS_MAX_RECORD_LEN];
83 static boolean_t log_history = B_TRUE;
85 static int zfs_do_clone(int argc, char **argv);
86 static int zfs_do_create(int argc, char **argv);
87 static int zfs_do_destroy(int argc, char **argv);
88 static int zfs_do_get(int argc, char **argv);
89 static int zfs_do_inherit(int argc, char **argv);
90 static int zfs_do_list(int argc, char **argv);
91 static int zfs_do_mount(int argc, char **argv);
92 static int zfs_do_rename(int argc, char **argv);
93 static int zfs_do_rollback(int argc, char **argv);
94 static int zfs_do_set(int argc, char **argv);
95 static int zfs_do_upgrade(int argc, char **argv);
96 static int zfs_do_snapshot(int argc, char **argv);
97 static int zfs_do_unmount(int argc, char **argv);
98 static int zfs_do_share(int argc, char **argv);
99 static int zfs_do_unshare(int argc, char **argv);
100 static int zfs_do_send(int argc, char **argv);
101 static int zfs_do_receive(int argc, char **argv);
102 static int zfs_do_promote(int argc, char **argv);
103 static int zfs_do_userspace(int argc, char **argv);
104 static int zfs_do_allow(int argc, char **argv);
105 static int zfs_do_unallow(int argc, char **argv);
106 static int zfs_do_hold(int argc, char **argv);
107 static int zfs_do_holds(int argc, char **argv);
108 static int zfs_do_release(int argc, char **argv);
109 static int zfs_do_diff(int argc, char **argv);
110 static int zfs_do_bookmark(int argc, char **argv);
111 static int zfs_do_remap(int argc, char **argv);
112 static int zfs_do_channel_program(int argc, char **argv);
115 * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
118 #ifdef DEBUG
119 const char *
120 _umem_debug_init(void)
122 return ("default,verbose"); /* $UMEM_DEBUG setting */
125 const char *
126 _umem_logging_init(void)
128 return ("fail,contents"); /* $UMEM_LOGGING setting */
130 #endif
132 typedef enum {
133 HELP_CLONE,
134 HELP_CREATE,
135 HELP_DESTROY,
136 HELP_GET,
137 HELP_INHERIT,
138 HELP_UPGRADE,
139 HELP_LIST,
140 HELP_MOUNT,
141 HELP_PROMOTE,
142 HELP_RECEIVE,
143 HELP_RENAME,
144 HELP_ROLLBACK,
145 HELP_SEND,
146 HELP_SET,
147 HELP_SHARE,
148 HELP_SNAPSHOT,
149 HELP_UNMOUNT,
150 HELP_UNSHARE,
151 HELP_ALLOW,
152 HELP_UNALLOW,
153 HELP_USERSPACE,
154 HELP_GROUPSPACE,
155 HELP_HOLD,
156 HELP_HOLDS,
157 HELP_RELEASE,
158 HELP_DIFF,
159 HELP_REMAP,
160 HELP_BOOKMARK,
161 HELP_CHANNEL_PROGRAM,
162 } zfs_help_t;
164 typedef struct zfs_command {
165 const char *name;
166 int (*func)(int argc, char **argv);
167 zfs_help_t usage;
168 } zfs_command_t;
171 * Master command table. Each ZFS command has a name, associated function, and
172 * usage message. The usage messages need to be internationalized, so we have
173 * to have a function to return the usage message based on a command index.
175 * These commands are organized according to how they are displayed in the usage
176 * message. An empty command (one with a NULL name) indicates an empty line in
177 * the generic usage message.
179 static zfs_command_t command_table[] = {
180 { "create", zfs_do_create, HELP_CREATE },
181 { "destroy", zfs_do_destroy, HELP_DESTROY },
182 { NULL },
183 { "snapshot", zfs_do_snapshot, HELP_SNAPSHOT },
184 { "rollback", zfs_do_rollback, HELP_ROLLBACK },
185 { "clone", zfs_do_clone, HELP_CLONE },
186 { "promote", zfs_do_promote, HELP_PROMOTE },
187 { "rename", zfs_do_rename, HELP_RENAME },
188 { "bookmark", zfs_do_bookmark, HELP_BOOKMARK },
189 { "program", zfs_do_channel_program, HELP_CHANNEL_PROGRAM },
190 { NULL },
191 { "list", zfs_do_list, HELP_LIST },
192 { NULL },
193 { "set", zfs_do_set, HELP_SET },
194 { "get", zfs_do_get, HELP_GET },
195 { "inherit", zfs_do_inherit, HELP_INHERIT },
196 { "upgrade", zfs_do_upgrade, HELP_UPGRADE },
197 { "userspace", zfs_do_userspace, HELP_USERSPACE },
198 { "groupspace", zfs_do_userspace, HELP_GROUPSPACE },
199 { NULL },
200 { "mount", zfs_do_mount, HELP_MOUNT },
201 { "unmount", zfs_do_unmount, HELP_UNMOUNT },
202 { "share", zfs_do_share, HELP_SHARE },
203 { "unshare", zfs_do_unshare, HELP_UNSHARE },
204 { NULL },
205 { "send", zfs_do_send, HELP_SEND },
206 { "receive", zfs_do_receive, HELP_RECEIVE },
207 { NULL },
208 { "allow", zfs_do_allow, HELP_ALLOW },
209 { NULL },
210 { "unallow", zfs_do_unallow, HELP_UNALLOW },
211 { NULL },
212 { "hold", zfs_do_hold, HELP_HOLD },
213 { "holds", zfs_do_holds, HELP_HOLDS },
214 { "release", zfs_do_release, HELP_RELEASE },
215 { "diff", zfs_do_diff, HELP_DIFF },
216 { "remap", zfs_do_remap, HELP_REMAP },
219 #define NCOMMAND (sizeof (command_table) / sizeof (command_table[0]))
221 zfs_command_t *current_command;
223 static const char *
224 get_usage(zfs_help_t idx)
226 switch (idx) {
227 case HELP_CLONE:
228 return (gettext("\tclone [-p] [-o property=value] ... "
229 "<snapshot> <filesystem|volume>\n"));
230 case HELP_CREATE:
231 return (gettext("\tcreate [-p] [-o property=value] ... "
232 "<filesystem>\n"
233 "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
234 "-V <size> <volume>\n"));
235 case HELP_DESTROY:
236 return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
237 "\tdestroy [-dnpRrv] "
238 "<filesystem|volume>@<snap>[%<snap>][,...]\n"
239 "\tdestroy <filesystem|volume>#<bookmark>\n"));
240 case HELP_GET:
241 return (gettext("\tget [-rHp] [-d max] "
242 "[-o \"all\" | field[,...]]\n"
243 "\t [-t type[,...]] [-s source[,...]]\n"
244 "\t <\"all\" | property[,...]> "
245 "[filesystem|volume|snapshot|bookmark] ...\n"));
246 case HELP_INHERIT:
247 return (gettext("\tinherit [-rS] <property> "
248 "<filesystem|volume|snapshot> ...\n"));
249 case HELP_UPGRADE:
250 return (gettext("\tupgrade [-v]\n"
251 "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
252 case HELP_LIST:
253 return (gettext("\tlist [-Hp] [-r|-d max] [-o property[,...]] "
254 "[-s property]...\n\t [-S property]... [-t type[,...]] "
255 "[filesystem|volume|snapshot] ...\n"));
256 case HELP_MOUNT:
257 return (gettext("\tmount\n"
258 "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
259 case HELP_PROMOTE:
260 return (gettext("\tpromote <clone-filesystem>\n"));
261 case HELP_RECEIVE:
262 return (gettext("\treceive [-vnsFu] <filesystem|volume|"
263 "snapshot>\n"
264 "\treceive [-vnsFu] [-o origin=<snapshot>] [-d | -e] "
265 "<filesystem>\n"
266 "\treceive -A <filesystem|volume>\n"));
267 case HELP_RENAME:
268 return (gettext("\trename [-f] <filesystem|volume|snapshot> "
269 "<filesystem|volume|snapshot>\n"
270 "\trename [-f] -p <filesystem|volume> <filesystem|volume>\n"
271 "\trename -r <snapshot> <snapshot>\n"));
272 case HELP_ROLLBACK:
273 return (gettext("\trollback [-rRf] <snapshot>\n"));
274 case HELP_SEND:
275 return (gettext("\tsend [-DnPpRvLec] [-[iI] snapshot] "
276 "<snapshot>\n"
277 "\tsend [-Le] [-i snapshot|bookmark] "
278 "<filesystem|volume|snapshot>\n"
279 "\tsend [-nvPe] -t <receive_resume_token>\n"));
280 case HELP_SET:
281 return (gettext("\tset <property=value> ... "
282 "<filesystem|volume|snapshot> ...\n"));
283 case HELP_SHARE:
284 return (gettext("\tshare <-a | filesystem>\n"));
285 case HELP_SNAPSHOT:
286 return (gettext("\tsnapshot [-r] [-o property=value] ... "
287 "<filesystem|volume>@<snap> ...\n"));
288 case HELP_UNMOUNT:
289 return (gettext("\tunmount [-f] "
290 "<-a | filesystem|mountpoint>\n"));
291 case HELP_UNSHARE:
292 return (gettext("\tunshare "
293 "<-a | filesystem|mountpoint>\n"));
294 case HELP_ALLOW:
295 return (gettext("\tallow <filesystem|volume>\n"
296 "\tallow [-ldug] "
297 "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
298 "\t <filesystem|volume>\n"
299 "\tallow [-ld] -e <perm|@setname>[,...] "
300 "<filesystem|volume>\n"
301 "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
302 "\tallow -s @setname <perm|@setname>[,...] "
303 "<filesystem|volume>\n"));
304 case HELP_UNALLOW:
305 return (gettext("\tunallow [-rldug] "
306 "<\"everyone\"|user|group>[,...]\n"
307 "\t [<perm|@setname>[,...]] <filesystem|volume>\n"
308 "\tunallow [-rld] -e [<perm|@setname>[,...]] "
309 "<filesystem|volume>\n"
310 "\tunallow [-r] -c [<perm|@setname>[,...]] "
311 "<filesystem|volume>\n"
312 "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
313 "<filesystem|volume>\n"));
314 case HELP_USERSPACE:
315 return (gettext("\tuserspace [-Hinp] [-o field[,...]] "
316 "[-s field] ...\n"
317 "\t [-S field] ... [-t type[,...]] "
318 "<filesystem|snapshot>\n"));
319 case HELP_GROUPSPACE:
320 return (gettext("\tgroupspace [-Hinp] [-o field[,...]] "
321 "[-s field] ...\n"
322 "\t [-S field] ... [-t type[,...]] "
323 "<filesystem|snapshot>\n"));
324 case HELP_HOLD:
325 return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
326 case HELP_HOLDS:
327 return (gettext("\tholds [-r] <snapshot> ...\n"));
328 case HELP_RELEASE:
329 return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
330 case HELP_DIFF:
331 return (gettext("\tdiff [-FHt] <snapshot> "
332 "[snapshot|filesystem]\n"));
333 case HELP_REMAP:
334 return (gettext("\tremap <filesystem | volume>\n"));
335 case HELP_BOOKMARK:
336 return (gettext("\tbookmark <snapshot> <bookmark>\n"));
337 case HELP_CHANNEL_PROGRAM:
338 return (gettext("\tprogram [-n] [-t <instruction limit>] "
339 "[-m <memory limit (b)>] <pool> <program file> "
340 "[lua args...]\n"));
343 abort();
344 /* NOTREACHED */
347 void
348 nomem(void)
350 (void) fprintf(stderr, gettext("internal error: out of memory\n"));
351 exit(1);
355 * Utility function to guarantee malloc() success.
358 void *
359 safe_malloc(size_t size)
361 void *data;
363 if ((data = calloc(1, size)) == NULL)
364 nomem();
366 return (data);
369 void *
370 safe_realloc(void *data, size_t size)
372 void *newp;
373 if ((newp = realloc(data, size)) == NULL) {
374 free(data);
375 nomem();
378 return (newp);
381 static char *
382 safe_strdup(char *str)
384 char *dupstr = strdup(str);
386 if (dupstr == NULL)
387 nomem();
389 return (dupstr);
393 * Callback routine that will print out information for each of
394 * the properties.
396 static int
397 usage_prop_cb(int prop, void *cb)
399 FILE *fp = cb;
401 (void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
403 if (zfs_prop_readonly(prop))
404 (void) fprintf(fp, " NO ");
405 else
406 (void) fprintf(fp, "YES ");
408 if (zfs_prop_inheritable(prop))
409 (void) fprintf(fp, " YES ");
410 else
411 (void) fprintf(fp, " NO ");
413 if (zfs_prop_values(prop) == NULL)
414 (void) fprintf(fp, "-\n");
415 else
416 (void) fprintf(fp, "%s\n", zfs_prop_values(prop));
418 return (ZPROP_CONT);
422 * Display usage message. If we're inside a command, display only the usage for
423 * that command. Otherwise, iterate over the entire command table and display
424 * a complete usage message.
426 static void
427 usage(boolean_t requested)
429 int i;
430 boolean_t show_properties = B_FALSE;
431 FILE *fp = requested ? stdout : stderr;
433 if (current_command == NULL) {
435 (void) fprintf(fp, gettext("usage: zfs command args ...\n"));
436 (void) fprintf(fp,
437 gettext("where 'command' is one of the following:\n\n"));
439 for (i = 0; i < NCOMMAND; i++) {
440 if (command_table[i].name == NULL)
441 (void) fprintf(fp, "\n");
442 else
443 (void) fprintf(fp, "%s",
444 get_usage(command_table[i].usage));
447 (void) fprintf(fp, gettext("\nEach dataset is of the form: "
448 "pool/[dataset/]*dataset[@name]\n"));
449 } else {
450 (void) fprintf(fp, gettext("usage:\n"));
451 (void) fprintf(fp, "%s", get_usage(current_command->usage));
454 if (current_command != NULL &&
455 (strcmp(current_command->name, "set") == 0 ||
456 strcmp(current_command->name, "get") == 0 ||
457 strcmp(current_command->name, "inherit") == 0 ||
458 strcmp(current_command->name, "list") == 0))
459 show_properties = B_TRUE;
461 if (show_properties) {
462 (void) fprintf(fp,
463 gettext("\nThe following properties are supported:\n"));
465 (void) fprintf(fp, "\n\t%-14s %s %s %s\n\n",
466 "PROPERTY", "EDIT", "INHERIT", "VALUES");
468 /* Iterate over all properties */
469 (void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
470 ZFS_TYPE_DATASET);
472 (void) fprintf(fp, "\t%-15s ", "userused@...");
473 (void) fprintf(fp, " NO NO <size>\n");
474 (void) fprintf(fp, "\t%-15s ", "groupused@...");
475 (void) fprintf(fp, " NO NO <size>\n");
476 (void) fprintf(fp, "\t%-15s ", "userquota@...");
477 (void) fprintf(fp, "YES NO <size> | none\n");
478 (void) fprintf(fp, "\t%-15s ", "groupquota@...");
479 (void) fprintf(fp, "YES NO <size> | none\n");
480 (void) fprintf(fp, "\t%-15s ", "written@<snap>");
481 (void) fprintf(fp, " NO NO <size>\n");
483 (void) fprintf(fp, gettext("\nSizes are specified in bytes "
484 "with standard units such as K, M, G, etc.\n"));
485 (void) fprintf(fp, gettext("\nUser-defined properties can "
486 "be specified by using a name containing a colon (:).\n"));
487 (void) fprintf(fp, gettext("\nThe {user|group}{used|quota}@ "
488 "properties must be appended with\n"
489 "a user or group specifier of one of these forms:\n"
490 " POSIX name (eg: \"matt\")\n"
491 " POSIX id (eg: \"126829\")\n"
492 " SMB name@domain (eg: \"matt@sun\")\n"
493 " SMB SID (eg: \"S-1-234-567-89\")\n"));
494 } else {
495 (void) fprintf(fp,
496 gettext("\nFor the property list, run: %s\n"),
497 "zfs set|get");
498 (void) fprintf(fp,
499 gettext("\nFor the delegated permission list, run: %s\n"),
500 "zfs allow|unallow");
504 * See comments at end of main().
506 if (getenv("ZFS_ABORT") != NULL) {
507 (void) printf("dumping core by request\n");
508 abort();
511 exit(requested ? 0 : 2);
515 * Take a property=value argument string and add it to the given nvlist.
516 * Modifies the argument inplace.
518 static int
519 parseprop(nvlist_t *props, char *propname)
521 char *propval, *strval;
523 if ((propval = strchr(propname, '=')) == NULL) {
524 (void) fprintf(stderr, gettext("missing "
525 "'=' for property=value argument\n"));
526 return (-1);
528 *propval = '\0';
529 propval++;
530 if (nvlist_lookup_string(props, propname, &strval) == 0) {
531 (void) fprintf(stderr, gettext("property '%s' "
532 "specified multiple times\n"), propname);
533 return (-1);
535 if (nvlist_add_string(props, propname, propval) != 0)
536 nomem();
537 return (0);
540 static int
541 parse_depth(char *opt, int *flags)
543 char *tmp;
544 int depth;
546 depth = (int)strtol(opt, &tmp, 0);
547 if (*tmp) {
548 (void) fprintf(stderr,
549 gettext("%s is not an integer\n"), optarg);
550 usage(B_FALSE);
552 if (depth < 0) {
553 (void) fprintf(stderr,
554 gettext("Depth can not be negative.\n"));
555 usage(B_FALSE);
557 *flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
558 return (depth);
561 #define PROGRESS_DELAY 2 /* seconds */
563 static char *pt_reverse = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
564 static time_t pt_begin;
565 static char *pt_header = NULL;
566 static boolean_t pt_shown;
568 static void
569 start_progress_timer(void)
571 pt_begin = time(NULL) + PROGRESS_DELAY;
572 pt_shown = B_FALSE;
575 static void
576 set_progress_header(char *header)
578 assert(pt_header == NULL);
579 pt_header = safe_strdup(header);
580 if (pt_shown) {
581 (void) printf("%s: ", header);
582 (void) fflush(stdout);
586 static void
587 update_progress(char *update)
589 if (!pt_shown && time(NULL) > pt_begin) {
590 int len = strlen(update);
592 (void) printf("%s: %s%*.*s", pt_header, update, len, len,
593 pt_reverse);
594 (void) fflush(stdout);
595 pt_shown = B_TRUE;
596 } else if (pt_shown) {
597 int len = strlen(update);
599 (void) printf("%s%*.*s", update, len, len, pt_reverse);
600 (void) fflush(stdout);
604 static void
605 finish_progress(char *done)
607 if (pt_shown) {
608 (void) printf("%s\n", done);
609 (void) fflush(stdout);
611 free(pt_header);
612 pt_header = NULL;
616 * Check if the dataset is mountable and should be automatically mounted.
618 static boolean_t
619 should_auto_mount(zfs_handle_t *zhp)
621 if (!zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, zfs_get_type(zhp)))
622 return (B_FALSE);
623 return (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_ON);
627 * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
629 * Given an existing dataset, create a writable copy whose initial contents
630 * are the same as the source. The newly created dataset maintains a
631 * dependency on the original; the original cannot be destroyed so long as
632 * the clone exists.
634 * The '-p' flag creates all the non-existing ancestors of the target first.
636 static int
637 zfs_do_clone(int argc, char **argv)
639 zfs_handle_t *zhp = NULL;
640 boolean_t parents = B_FALSE;
641 nvlist_t *props;
642 int ret = 0;
643 int c;
645 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
646 nomem();
648 /* check options */
649 while ((c = getopt(argc, argv, "o:p")) != -1) {
650 switch (c) {
651 case 'o':
652 if (parseprop(props, optarg) != 0)
653 return (1);
654 break;
655 case 'p':
656 parents = B_TRUE;
657 break;
658 case '?':
659 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
660 optopt);
661 goto usage;
665 argc -= optind;
666 argv += optind;
668 /* check number of arguments */
669 if (argc < 1) {
670 (void) fprintf(stderr, gettext("missing source dataset "
671 "argument\n"));
672 goto usage;
674 if (argc < 2) {
675 (void) fprintf(stderr, gettext("missing target dataset "
676 "argument\n"));
677 goto usage;
679 if (argc > 2) {
680 (void) fprintf(stderr, gettext("too many arguments\n"));
681 goto usage;
684 /* open the source dataset */
685 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
686 return (1);
688 if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
689 ZFS_TYPE_VOLUME)) {
691 * Now create the ancestors of the target dataset. If the
692 * target already exists and '-p' option was used we should not
693 * complain.
695 if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
696 ZFS_TYPE_VOLUME))
697 return (0);
698 if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
699 return (1);
702 /* pass to libzfs */
703 ret = zfs_clone(zhp, argv[1], props);
705 /* create the mountpoint if necessary */
706 if (ret == 0) {
707 zfs_handle_t *clone;
709 clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
710 if (clone != NULL) {
712 * If the user doesn't want the dataset
713 * automatically mounted, then skip the mount/share
714 * step.
716 if (should_auto_mount(clone)) {
717 if ((ret = zfs_mount(clone, NULL, 0)) != 0) {
718 (void) fprintf(stderr, gettext("clone "
719 "successfully created, "
720 "but not mounted\n"));
721 } else if ((ret = zfs_share(clone)) != 0) {
722 (void) fprintf(stderr, gettext("clone "
723 "successfully created, "
724 "but not shared\n"));
727 zfs_close(clone);
731 zfs_close(zhp);
732 nvlist_free(props);
734 return (!!ret);
736 usage:
737 if (zhp)
738 zfs_close(zhp);
739 nvlist_free(props);
740 usage(B_FALSE);
741 return (-1);
745 * zfs create [-p] [-o prop=value] ... fs
746 * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
748 * Create a new dataset. This command can be used to create filesystems
749 * and volumes. Snapshot creation is handled by 'zfs snapshot'.
750 * For volumes, the user must specify a size to be used.
752 * The '-s' flag applies only to volumes, and indicates that we should not try
753 * to set the reservation for this volume. By default we set a reservation
754 * equal to the size for any volume. For pools with SPA_VERSION >=
755 * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
757 * The '-p' flag creates all the non-existing ancestors of the target first.
759 static int
760 zfs_do_create(int argc, char **argv)
762 zfs_type_t type = ZFS_TYPE_FILESYSTEM;
763 zfs_handle_t *zhp = NULL;
764 uint64_t volsize = 0;
765 int c;
766 boolean_t noreserve = B_FALSE;
767 boolean_t bflag = B_FALSE;
768 boolean_t parents = B_FALSE;
769 int ret = 1;
770 nvlist_t *props;
771 uint64_t intval;
773 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
774 nomem();
776 /* check options */
777 while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
778 switch (c) {
779 case 'V':
780 type = ZFS_TYPE_VOLUME;
781 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
782 (void) fprintf(stderr, gettext("bad volume "
783 "size '%s': %s\n"), optarg,
784 libzfs_error_description(g_zfs));
785 goto error;
788 if (nvlist_add_uint64(props,
789 zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
790 nomem();
791 volsize = intval;
792 break;
793 case 'p':
794 parents = B_TRUE;
795 break;
796 case 'b':
797 bflag = B_TRUE;
798 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
799 (void) fprintf(stderr, gettext("bad volume "
800 "block size '%s': %s\n"), optarg,
801 libzfs_error_description(g_zfs));
802 goto error;
805 if (nvlist_add_uint64(props,
806 zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
807 intval) != 0)
808 nomem();
809 break;
810 case 'o':
811 if (parseprop(props, optarg) != 0)
812 goto error;
813 break;
814 case 's':
815 noreserve = B_TRUE;
816 break;
817 case ':':
818 (void) fprintf(stderr, gettext("missing size "
819 "argument\n"));
820 goto badusage;
821 case '?':
822 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
823 optopt);
824 goto badusage;
828 if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
829 (void) fprintf(stderr, gettext("'-s' and '-b' can only be "
830 "used when creating a volume\n"));
831 goto badusage;
834 argc -= optind;
835 argv += optind;
837 /* check number of arguments */
838 if (argc == 0) {
839 (void) fprintf(stderr, gettext("missing %s argument\n"),
840 zfs_type_to_name(type));
841 goto badusage;
843 if (argc > 1) {
844 (void) fprintf(stderr, gettext("too many arguments\n"));
845 goto badusage;
848 if (type == ZFS_TYPE_VOLUME && !noreserve) {
849 zpool_handle_t *zpool_handle;
850 nvlist_t *real_props = NULL;
851 uint64_t spa_version;
852 char *p;
853 zfs_prop_t resv_prop;
854 char *strval;
855 char msg[1024];
857 if ((p = strchr(argv[0], '/')) != NULL)
858 *p = '\0';
859 zpool_handle = zpool_open(g_zfs, argv[0]);
860 if (p != NULL)
861 *p = '/';
862 if (zpool_handle == NULL)
863 goto error;
864 spa_version = zpool_get_prop_int(zpool_handle,
865 ZPOOL_PROP_VERSION, NULL);
866 if (spa_version >= SPA_VERSION_REFRESERVATION)
867 resv_prop = ZFS_PROP_REFRESERVATION;
868 else
869 resv_prop = ZFS_PROP_RESERVATION;
871 (void) snprintf(msg, sizeof (msg),
872 gettext("cannot create '%s'"), argv[0]);
873 if (props && (real_props = zfs_valid_proplist(g_zfs, type,
874 props, 0, NULL, zpool_handle, msg)) == NULL) {
875 zpool_close(zpool_handle);
876 goto error;
878 zpool_close(zpool_handle);
880 volsize = zvol_volsize_to_reservation(volsize, real_props);
881 nvlist_free(real_props);
883 if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
884 &strval) != 0) {
885 if (nvlist_add_uint64(props,
886 zfs_prop_to_name(resv_prop), volsize) != 0) {
887 nvlist_free(props);
888 nomem();
893 if (parents && zfs_name_valid(argv[0], type)) {
895 * Now create the ancestors of target dataset. If the target
896 * already exists and '-p' option was used we should not
897 * complain.
899 if (zfs_dataset_exists(g_zfs, argv[0], type)) {
900 ret = 0;
901 goto error;
903 if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
904 goto error;
907 /* pass to libzfs */
908 if (zfs_create(g_zfs, argv[0], type, props) != 0)
909 goto error;
911 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
912 goto error;
914 ret = 0;
917 * Mount and/or share the new filesystem as appropriate. We provide a
918 * verbose error message to let the user know that their filesystem was
919 * in fact created, even if we failed to mount or share it.
920 * If the user doesn't want the dataset automatically mounted,
921 * then skip the mount/share step altogether.
923 if (should_auto_mount(zhp)) {
924 if (zfs_mount(zhp, NULL, 0) != 0) {
925 (void) fprintf(stderr, gettext("filesystem "
926 "successfully created, but not mounted\n"));
927 ret = 1;
928 } else if (zfs_share(zhp) != 0) {
929 (void) fprintf(stderr, gettext("filesystem "
930 "successfully created, but not shared\n"));
931 ret = 1;
935 error:
936 if (zhp)
937 zfs_close(zhp);
938 nvlist_free(props);
939 return (ret);
940 badusage:
941 nvlist_free(props);
942 usage(B_FALSE);
943 return (2);
947 * zfs destroy [-rRf] <fs, vol>
948 * zfs destroy [-rRd] <snap>
950 * -r Recursively destroy all children
951 * -R Recursively destroy all dependents, including clones
952 * -f Force unmounting of any dependents
953 * -d If we can't destroy now, mark for deferred destruction
955 * Destroys the given dataset. By default, it will unmount any filesystems,
956 * and refuse to destroy a dataset that has any dependents. A dependent can
957 * either be a child, or a clone of a child.
959 typedef struct destroy_cbdata {
960 boolean_t cb_first;
961 boolean_t cb_force;
962 boolean_t cb_recurse;
963 boolean_t cb_error;
964 boolean_t cb_doclones;
965 zfs_handle_t *cb_target;
966 boolean_t cb_defer_destroy;
967 boolean_t cb_verbose;
968 boolean_t cb_parsable;
969 boolean_t cb_dryrun;
970 nvlist_t *cb_nvl;
971 nvlist_t *cb_batchedsnaps;
973 /* first snap in contiguous run */
974 char *cb_firstsnap;
975 /* previous snap in contiguous run */
976 char *cb_prevsnap;
977 int64_t cb_snapused;
978 char *cb_snapspec;
979 char *cb_bookmark;
980 } destroy_cbdata_t;
983 * Check for any dependents based on the '-r' or '-R' flags.
985 static int
986 destroy_check_dependent(zfs_handle_t *zhp, void *data)
988 destroy_cbdata_t *cbp = data;
989 const char *tname = zfs_get_name(cbp->cb_target);
990 const char *name = zfs_get_name(zhp);
992 if (strncmp(tname, name, strlen(tname)) == 0 &&
993 (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
995 * This is a direct descendant, not a clone somewhere else in
996 * the hierarchy.
998 if (cbp->cb_recurse)
999 goto out;
1001 if (cbp->cb_first) {
1002 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1003 "%s has children\n"),
1004 zfs_get_name(cbp->cb_target),
1005 zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1006 (void) fprintf(stderr, gettext("use '-r' to destroy "
1007 "the following datasets:\n"));
1008 cbp->cb_first = B_FALSE;
1009 cbp->cb_error = B_TRUE;
1012 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1013 } else {
1015 * This is a clone. We only want to report this if the '-r'
1016 * wasn't specified, or the target is a snapshot.
1018 if (!cbp->cb_recurse &&
1019 zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
1020 goto out;
1022 if (cbp->cb_first) {
1023 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1024 "%s has dependent clones\n"),
1025 zfs_get_name(cbp->cb_target),
1026 zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1027 (void) fprintf(stderr, gettext("use '-R' to destroy "
1028 "the following datasets:\n"));
1029 cbp->cb_first = B_FALSE;
1030 cbp->cb_error = B_TRUE;
1031 cbp->cb_dryrun = B_TRUE;
1034 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1037 out:
1038 zfs_close(zhp);
1039 return (0);
1042 static int
1043 destroy_callback(zfs_handle_t *zhp, void *data)
1045 destroy_cbdata_t *cb = data;
1046 const char *name = zfs_get_name(zhp);
1048 if (cb->cb_verbose) {
1049 if (cb->cb_parsable) {
1050 (void) printf("destroy\t%s\n", name);
1051 } else if (cb->cb_dryrun) {
1052 (void) printf(gettext("would destroy %s\n"),
1053 name);
1054 } else {
1055 (void) printf(gettext("will destroy %s\n"),
1056 name);
1061 * Ignore pools (which we've already flagged as an error before getting
1062 * here).
1064 if (strchr(zfs_get_name(zhp), '/') == NULL &&
1065 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1066 zfs_close(zhp);
1067 return (0);
1069 if (cb->cb_dryrun) {
1070 zfs_close(zhp);
1071 return (0);
1075 * We batch up all contiguous snapshots (even of different
1076 * filesystems) and destroy them with one ioctl. We can't
1077 * simply do all snap deletions and then all fs deletions,
1078 * because we must delete a clone before its origin.
1080 if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT) {
1081 fnvlist_add_boolean(cb->cb_batchedsnaps, name);
1082 } else {
1083 int error = zfs_destroy_snaps_nvl(g_zfs,
1084 cb->cb_batchedsnaps, B_FALSE);
1085 fnvlist_free(cb->cb_batchedsnaps);
1086 cb->cb_batchedsnaps = fnvlist_alloc();
1088 if (error != 0 ||
1089 zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
1090 zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
1091 zfs_close(zhp);
1092 return (-1);
1096 zfs_close(zhp);
1097 return (0);
1100 static int
1101 destroy_print_cb(zfs_handle_t *zhp, void *arg)
1103 destroy_cbdata_t *cb = arg;
1104 const char *name = zfs_get_name(zhp);
1105 int err = 0;
1107 if (nvlist_exists(cb->cb_nvl, name)) {
1108 if (cb->cb_firstsnap == NULL)
1109 cb->cb_firstsnap = strdup(name);
1110 free(cb->cb_prevsnap);
1111 /* this snap continues the current range */
1112 cb->cb_prevsnap = strdup(name);
1113 if (cb->cb_firstsnap == NULL || cb->cb_prevsnap == NULL)
1114 nomem();
1115 if (cb->cb_verbose) {
1116 if (cb->cb_parsable) {
1117 (void) printf("destroy\t%s\n", name);
1118 } else if (cb->cb_dryrun) {
1119 (void) printf(gettext("would destroy %s\n"),
1120 name);
1121 } else {
1122 (void) printf(gettext("will destroy %s\n"),
1123 name);
1126 } else if (cb->cb_firstsnap != NULL) {
1127 /* end of this range */
1128 uint64_t used = 0;
1129 err = lzc_snaprange_space(cb->cb_firstsnap,
1130 cb->cb_prevsnap, &used);
1131 cb->cb_snapused += used;
1132 free(cb->cb_firstsnap);
1133 cb->cb_firstsnap = NULL;
1134 free(cb->cb_prevsnap);
1135 cb->cb_prevsnap = NULL;
1137 zfs_close(zhp);
1138 return (err);
1141 static int
1142 destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
1144 int err = 0;
1145 assert(cb->cb_firstsnap == NULL);
1146 assert(cb->cb_prevsnap == NULL);
1147 err = zfs_iter_snapshots_sorted(fs_zhp, destroy_print_cb, cb);
1148 if (cb->cb_firstsnap != NULL) {
1149 uint64_t used = 0;
1150 if (err == 0) {
1151 err = lzc_snaprange_space(cb->cb_firstsnap,
1152 cb->cb_prevsnap, &used);
1154 cb->cb_snapused += used;
1155 free(cb->cb_firstsnap);
1156 cb->cb_firstsnap = NULL;
1157 free(cb->cb_prevsnap);
1158 cb->cb_prevsnap = NULL;
1160 return (err);
1163 static int
1164 snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
1166 destroy_cbdata_t *cb = arg;
1167 int err = 0;
1169 /* Check for clones. */
1170 if (!cb->cb_doclones && !cb->cb_defer_destroy) {
1171 cb->cb_target = zhp;
1172 cb->cb_first = B_TRUE;
1173 err = zfs_iter_dependents(zhp, B_TRUE,
1174 destroy_check_dependent, cb);
1177 if (err == 0) {
1178 if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
1179 nomem();
1181 zfs_close(zhp);
1182 return (err);
1185 static int
1186 gather_snapshots(zfs_handle_t *zhp, void *arg)
1188 destroy_cbdata_t *cb = arg;
1189 int err = 0;
1191 err = zfs_iter_snapspec(zhp, cb->cb_snapspec, snapshot_to_nvl_cb, cb);
1192 if (err == ENOENT)
1193 err = 0;
1194 if (err != 0)
1195 goto out;
1197 if (cb->cb_verbose) {
1198 err = destroy_print_snapshots(zhp, cb);
1199 if (err != 0)
1200 goto out;
1203 if (cb->cb_recurse)
1204 err = zfs_iter_filesystems(zhp, gather_snapshots, cb);
1206 out:
1207 zfs_close(zhp);
1208 return (err);
1211 static int
1212 destroy_clones(destroy_cbdata_t *cb)
1214 nvpair_t *pair;
1215 for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
1216 pair != NULL;
1217 pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
1218 zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
1219 ZFS_TYPE_SNAPSHOT);
1220 if (zhp != NULL) {
1221 boolean_t defer = cb->cb_defer_destroy;
1222 int err = 0;
1225 * We can't defer destroy non-snapshots, so set it to
1226 * false while destroying the clones.
1228 cb->cb_defer_destroy = B_FALSE;
1229 err = zfs_iter_dependents(zhp, B_FALSE,
1230 destroy_callback, cb);
1231 cb->cb_defer_destroy = defer;
1232 zfs_close(zhp);
1233 if (err != 0)
1234 return (err);
1237 return (0);
1240 static int
1241 zfs_do_destroy(int argc, char **argv)
1243 destroy_cbdata_t cb = { 0 };
1244 int rv = 0;
1245 int err = 0;
1246 int c;
1247 zfs_handle_t *zhp = NULL;
1248 char *at, *pound;
1249 zfs_type_t type = ZFS_TYPE_DATASET;
1251 /* check options */
1252 while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
1253 switch (c) {
1254 case 'v':
1255 cb.cb_verbose = B_TRUE;
1256 break;
1257 case 'p':
1258 cb.cb_verbose = B_TRUE;
1259 cb.cb_parsable = B_TRUE;
1260 break;
1261 case 'n':
1262 cb.cb_dryrun = B_TRUE;
1263 break;
1264 case 'd':
1265 cb.cb_defer_destroy = B_TRUE;
1266 type = ZFS_TYPE_SNAPSHOT;
1267 break;
1268 case 'f':
1269 cb.cb_force = B_TRUE;
1270 break;
1271 case 'r':
1272 cb.cb_recurse = B_TRUE;
1273 break;
1274 case 'R':
1275 cb.cb_recurse = B_TRUE;
1276 cb.cb_doclones = B_TRUE;
1277 break;
1278 case '?':
1279 default:
1280 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1281 optopt);
1282 usage(B_FALSE);
1286 argc -= optind;
1287 argv += optind;
1289 /* check number of arguments */
1290 if (argc == 0) {
1291 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1292 usage(B_FALSE);
1294 if (argc > 1) {
1295 (void) fprintf(stderr, gettext("too many arguments\n"));
1296 usage(B_FALSE);
1299 at = strchr(argv[0], '@');
1300 pound = strchr(argv[0], '#');
1301 if (at != NULL) {
1303 /* Build the list of snaps to destroy in cb_nvl. */
1304 cb.cb_nvl = fnvlist_alloc();
1306 *at = '\0';
1307 zhp = zfs_open(g_zfs, argv[0],
1308 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1309 if (zhp == NULL)
1310 return (1);
1312 cb.cb_snapspec = at + 1;
1313 if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
1314 cb.cb_error) {
1315 rv = 1;
1316 goto out;
1319 if (nvlist_empty(cb.cb_nvl)) {
1320 (void) fprintf(stderr, gettext("could not find any "
1321 "snapshots to destroy; check snapshot names.\n"));
1322 rv = 1;
1323 goto out;
1326 if (cb.cb_verbose) {
1327 char buf[16];
1328 zfs_nicenum(cb.cb_snapused, buf, sizeof (buf));
1329 if (cb.cb_parsable) {
1330 (void) printf("reclaim\t%llu\n",
1331 cb.cb_snapused);
1332 } else if (cb.cb_dryrun) {
1333 (void) printf(gettext("would reclaim %s\n"),
1334 buf);
1335 } else {
1336 (void) printf(gettext("will reclaim %s\n"),
1337 buf);
1341 if (!cb.cb_dryrun) {
1342 if (cb.cb_doclones) {
1343 cb.cb_batchedsnaps = fnvlist_alloc();
1344 err = destroy_clones(&cb);
1345 if (err == 0) {
1346 err = zfs_destroy_snaps_nvl(g_zfs,
1347 cb.cb_batchedsnaps, B_FALSE);
1349 if (err != 0) {
1350 rv = 1;
1351 goto out;
1354 if (err == 0) {
1355 err = zfs_destroy_snaps_nvl(g_zfs, cb.cb_nvl,
1356 cb.cb_defer_destroy);
1360 if (err != 0)
1361 rv = 1;
1362 } else if (pound != NULL) {
1363 int err;
1364 nvlist_t *nvl;
1366 if (cb.cb_dryrun) {
1367 (void) fprintf(stderr,
1368 "dryrun is not supported with bookmark\n");
1369 return (-1);
1372 if (cb.cb_defer_destroy) {
1373 (void) fprintf(stderr,
1374 "defer destroy is not supported with bookmark\n");
1375 return (-1);
1378 if (cb.cb_recurse) {
1379 (void) fprintf(stderr,
1380 "recursive is not supported with bookmark\n");
1381 return (-1);
1384 if (!zfs_bookmark_exists(argv[0])) {
1385 (void) fprintf(stderr, gettext("bookmark '%s' "
1386 "does not exist.\n"), argv[0]);
1387 return (1);
1390 nvl = fnvlist_alloc();
1391 fnvlist_add_boolean(nvl, argv[0]);
1393 err = lzc_destroy_bookmarks(nvl, NULL);
1394 if (err != 0) {
1395 (void) zfs_standard_error(g_zfs, err,
1396 "cannot destroy bookmark");
1399 nvlist_free(cb.cb_nvl);
1401 return (err);
1402 } else {
1403 /* Open the given dataset */
1404 if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1405 return (1);
1407 cb.cb_target = zhp;
1410 * Perform an explicit check for pools before going any further.
1412 if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1413 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1414 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1415 "operation does not apply to pools\n"),
1416 zfs_get_name(zhp));
1417 (void) fprintf(stderr, gettext("use 'zfs destroy -r "
1418 "%s' to destroy all datasets in the pool\n"),
1419 zfs_get_name(zhp));
1420 (void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1421 "to destroy the pool itself\n"), zfs_get_name(zhp));
1422 rv = 1;
1423 goto out;
1427 * Check for any dependents and/or clones.
1429 cb.cb_first = B_TRUE;
1430 if (!cb.cb_doclones &&
1431 zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
1432 &cb) != 0) {
1433 rv = 1;
1434 goto out;
1437 if (cb.cb_error) {
1438 rv = 1;
1439 goto out;
1442 cb.cb_batchedsnaps = fnvlist_alloc();
1443 if (zfs_iter_dependents(zhp, B_FALSE, destroy_callback,
1444 &cb) != 0) {
1445 rv = 1;
1446 goto out;
1450 * Do the real thing. The callback will close the
1451 * handle regardless of whether it succeeds or not.
1453 err = destroy_callback(zhp, &cb);
1454 zhp = NULL;
1455 if (err == 0) {
1456 err = zfs_destroy_snaps_nvl(g_zfs,
1457 cb.cb_batchedsnaps, cb.cb_defer_destroy);
1459 if (err != 0)
1460 rv = 1;
1463 out:
1464 fnvlist_free(cb.cb_batchedsnaps);
1465 fnvlist_free(cb.cb_nvl);
1466 if (zhp != NULL)
1467 zfs_close(zhp);
1468 return (rv);
1471 static boolean_t
1472 is_recvd_column(zprop_get_cbdata_t *cbp)
1474 int i;
1475 zfs_get_column_t col;
1477 for (i = 0; i < ZFS_GET_NCOLS &&
1478 (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1479 if (col == GET_COL_RECVD)
1480 return (B_TRUE);
1481 return (B_FALSE);
1485 * zfs get [-rHp] [-o all | field[,field]...] [-s source[,source]...]
1486 * < all | property[,property]... > < fs | snap | vol > ...
1488 * -r recurse over any child datasets
1489 * -H scripted mode. Headers are stripped, and fields are separated
1490 * by tabs instead of spaces.
1491 * -o Set of fields to display. One of "name,property,value,
1492 * received,source". Default is "name,property,value,source".
1493 * "all" is an alias for all five.
1494 * -s Set of sources to allow. One of
1495 * "local,default,inherited,received,temporary,none". Default is
1496 * all six.
1497 * -p Display values in parsable (literal) format.
1499 * Prints properties for the given datasets. The user can control which
1500 * columns to display as well as which property types to allow.
1504 * Invoked to display the properties for a single dataset.
1506 static int
1507 get_callback(zfs_handle_t *zhp, void *data)
1509 char buf[ZFS_MAXPROPLEN];
1510 char rbuf[ZFS_MAXPROPLEN];
1511 zprop_source_t sourcetype;
1512 char source[ZFS_MAX_DATASET_NAME_LEN];
1513 zprop_get_cbdata_t *cbp = data;
1514 nvlist_t *user_props = zfs_get_user_props(zhp);
1515 zprop_list_t *pl = cbp->cb_proplist;
1516 nvlist_t *propval;
1517 char *strval;
1518 char *sourceval;
1519 boolean_t received = is_recvd_column(cbp);
1521 for (; pl != NULL; pl = pl->pl_next) {
1522 char *recvdval = NULL;
1524 * Skip the special fake placeholder. This will also skip over
1525 * the name property when 'all' is specified.
1527 if (pl->pl_prop == ZFS_PROP_NAME &&
1528 pl == cbp->cb_proplist)
1529 continue;
1531 if (pl->pl_prop != ZPROP_INVAL) {
1532 if (zfs_prop_get(zhp, pl->pl_prop, buf,
1533 sizeof (buf), &sourcetype, source,
1534 sizeof (source),
1535 cbp->cb_literal) != 0) {
1536 if (pl->pl_all)
1537 continue;
1538 if (!zfs_prop_valid_for_type(pl->pl_prop,
1539 ZFS_TYPE_DATASET)) {
1540 (void) fprintf(stderr,
1541 gettext("No such property '%s'\n"),
1542 zfs_prop_to_name(pl->pl_prop));
1543 continue;
1545 sourcetype = ZPROP_SRC_NONE;
1546 (void) strlcpy(buf, "-", sizeof (buf));
1549 if (received && (zfs_prop_get_recvd(zhp,
1550 zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
1551 cbp->cb_literal) == 0))
1552 recvdval = rbuf;
1554 zprop_print_one_property(zfs_get_name(zhp), cbp,
1555 zfs_prop_to_name(pl->pl_prop),
1556 buf, sourcetype, source, recvdval);
1557 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
1558 sourcetype = ZPROP_SRC_LOCAL;
1560 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1561 buf, sizeof (buf), cbp->cb_literal) != 0) {
1562 sourcetype = ZPROP_SRC_NONE;
1563 (void) strlcpy(buf, "-", sizeof (buf));
1566 zprop_print_one_property(zfs_get_name(zhp), cbp,
1567 pl->pl_user_prop, buf, sourcetype, source, NULL);
1568 } else if (zfs_prop_written(pl->pl_user_prop)) {
1569 sourcetype = ZPROP_SRC_LOCAL;
1571 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
1572 buf, sizeof (buf), cbp->cb_literal) != 0) {
1573 sourcetype = ZPROP_SRC_NONE;
1574 (void) strlcpy(buf, "-", sizeof (buf));
1577 zprop_print_one_property(zfs_get_name(zhp), cbp,
1578 pl->pl_user_prop, buf, sourcetype, source, NULL);
1579 } else {
1580 if (nvlist_lookup_nvlist(user_props,
1581 pl->pl_user_prop, &propval) != 0) {
1582 if (pl->pl_all)
1583 continue;
1584 sourcetype = ZPROP_SRC_NONE;
1585 strval = "-";
1586 } else {
1587 verify(nvlist_lookup_string(propval,
1588 ZPROP_VALUE, &strval) == 0);
1589 verify(nvlist_lookup_string(propval,
1590 ZPROP_SOURCE, &sourceval) == 0);
1592 if (strcmp(sourceval,
1593 zfs_get_name(zhp)) == 0) {
1594 sourcetype = ZPROP_SRC_LOCAL;
1595 } else if (strcmp(sourceval,
1596 ZPROP_SOURCE_VAL_RECVD) == 0) {
1597 sourcetype = ZPROP_SRC_RECEIVED;
1598 } else {
1599 sourcetype = ZPROP_SRC_INHERITED;
1600 (void) strlcpy(source,
1601 sourceval, sizeof (source));
1605 if (received && (zfs_prop_get_recvd(zhp,
1606 pl->pl_user_prop, rbuf, sizeof (rbuf),
1607 cbp->cb_literal) == 0))
1608 recvdval = rbuf;
1610 zprop_print_one_property(zfs_get_name(zhp), cbp,
1611 pl->pl_user_prop, strval, sourcetype,
1612 source, recvdval);
1616 return (0);
1619 static int
1620 zfs_do_get(int argc, char **argv)
1622 zprop_get_cbdata_t cb = { 0 };
1623 int i, c, flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1624 int types = ZFS_TYPE_DATASET | ZFS_TYPE_BOOKMARK;
1625 char *value, *fields;
1626 int ret = 0;
1627 int limit = 0;
1628 zprop_list_t fake_name = { 0 };
1631 * Set up default columns and sources.
1633 cb.cb_sources = ZPROP_SRC_ALL;
1634 cb.cb_columns[0] = GET_COL_NAME;
1635 cb.cb_columns[1] = GET_COL_PROPERTY;
1636 cb.cb_columns[2] = GET_COL_VALUE;
1637 cb.cb_columns[3] = GET_COL_SOURCE;
1638 cb.cb_type = ZFS_TYPE_DATASET;
1640 /* check options */
1641 while ((c = getopt(argc, argv, ":d:o:s:rt:Hp")) != -1) {
1642 switch (c) {
1643 case 'p':
1644 cb.cb_literal = B_TRUE;
1645 break;
1646 case 'd':
1647 limit = parse_depth(optarg, &flags);
1648 break;
1649 case 'r':
1650 flags |= ZFS_ITER_RECURSE;
1651 break;
1652 case 'H':
1653 cb.cb_scripted = B_TRUE;
1654 break;
1655 case ':':
1656 (void) fprintf(stderr, gettext("missing argument for "
1657 "'%c' option\n"), optopt);
1658 usage(B_FALSE);
1659 break;
1660 case 'o':
1662 * Process the set of columns to display. We zero out
1663 * the structure to give us a blank slate.
1665 bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1666 i = 0;
1667 while (*optarg != '\0') {
1668 static char *col_subopts[] =
1669 { "name", "property", "value", "received",
1670 "source", "all", NULL };
1672 if (i == ZFS_GET_NCOLS) {
1673 (void) fprintf(stderr, gettext("too "
1674 "many fields given to -o "
1675 "option\n"));
1676 usage(B_FALSE);
1679 switch (getsubopt(&optarg, col_subopts,
1680 &value)) {
1681 case 0:
1682 cb.cb_columns[i++] = GET_COL_NAME;
1683 break;
1684 case 1:
1685 cb.cb_columns[i++] = GET_COL_PROPERTY;
1686 break;
1687 case 2:
1688 cb.cb_columns[i++] = GET_COL_VALUE;
1689 break;
1690 case 3:
1691 cb.cb_columns[i++] = GET_COL_RECVD;
1692 flags |= ZFS_ITER_RECVD_PROPS;
1693 break;
1694 case 4:
1695 cb.cb_columns[i++] = GET_COL_SOURCE;
1696 break;
1697 case 5:
1698 if (i > 0) {
1699 (void) fprintf(stderr,
1700 gettext("\"all\" conflicts "
1701 "with specific fields "
1702 "given to -o option\n"));
1703 usage(B_FALSE);
1705 cb.cb_columns[0] = GET_COL_NAME;
1706 cb.cb_columns[1] = GET_COL_PROPERTY;
1707 cb.cb_columns[2] = GET_COL_VALUE;
1708 cb.cb_columns[3] = GET_COL_RECVD;
1709 cb.cb_columns[4] = GET_COL_SOURCE;
1710 flags |= ZFS_ITER_RECVD_PROPS;
1711 i = ZFS_GET_NCOLS;
1712 break;
1713 default:
1714 (void) fprintf(stderr,
1715 gettext("invalid column name "
1716 "'%s'\n"), value);
1717 usage(B_FALSE);
1720 break;
1722 case 's':
1723 cb.cb_sources = 0;
1724 while (*optarg != '\0') {
1725 static char *source_subopts[] = {
1726 "local", "default", "inherited",
1727 "received", "temporary", "none",
1728 NULL };
1730 switch (getsubopt(&optarg, source_subopts,
1731 &value)) {
1732 case 0:
1733 cb.cb_sources |= ZPROP_SRC_LOCAL;
1734 break;
1735 case 1:
1736 cb.cb_sources |= ZPROP_SRC_DEFAULT;
1737 break;
1738 case 2:
1739 cb.cb_sources |= ZPROP_SRC_INHERITED;
1740 break;
1741 case 3:
1742 cb.cb_sources |= ZPROP_SRC_RECEIVED;
1743 break;
1744 case 4:
1745 cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1746 break;
1747 case 5:
1748 cb.cb_sources |= ZPROP_SRC_NONE;
1749 break;
1750 default:
1751 (void) fprintf(stderr,
1752 gettext("invalid source "
1753 "'%s'\n"), value);
1754 usage(B_FALSE);
1757 break;
1759 case 't':
1760 types = 0;
1761 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
1762 while (*optarg != '\0') {
1763 static char *type_subopts[] = { "filesystem",
1764 "volume", "snapshot", "bookmark",
1765 "all", NULL };
1767 switch (getsubopt(&optarg, type_subopts,
1768 &value)) {
1769 case 0:
1770 types |= ZFS_TYPE_FILESYSTEM;
1771 break;
1772 case 1:
1773 types |= ZFS_TYPE_VOLUME;
1774 break;
1775 case 2:
1776 types |= ZFS_TYPE_SNAPSHOT;
1777 break;
1778 case 3:
1779 types |= ZFS_TYPE_BOOKMARK;
1780 break;
1781 case 4:
1782 types = ZFS_TYPE_DATASET |
1783 ZFS_TYPE_BOOKMARK;
1784 break;
1786 default:
1787 (void) fprintf(stderr,
1788 gettext("invalid type '%s'\n"),
1789 value);
1790 usage(B_FALSE);
1793 break;
1795 case '?':
1796 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1797 optopt);
1798 usage(B_FALSE);
1802 argc -= optind;
1803 argv += optind;
1805 if (argc < 1) {
1806 (void) fprintf(stderr, gettext("missing property "
1807 "argument\n"));
1808 usage(B_FALSE);
1811 fields = argv[0];
1813 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1814 != 0)
1815 usage(B_FALSE);
1817 argc--;
1818 argv++;
1821 * As part of zfs_expand_proplist(), we keep track of the maximum column
1822 * width for each property. For the 'NAME' (and 'SOURCE') columns, we
1823 * need to know the maximum name length. However, the user likely did
1824 * not specify 'name' as one of the properties to fetch, so we need to
1825 * make sure we always include at least this property for
1826 * print_get_headers() to work properly.
1828 if (cb.cb_proplist != NULL) {
1829 fake_name.pl_prop = ZFS_PROP_NAME;
1830 fake_name.pl_width = strlen(gettext("NAME"));
1831 fake_name.pl_next = cb.cb_proplist;
1832 cb.cb_proplist = &fake_name;
1835 cb.cb_first = B_TRUE;
1837 /* run for each object */
1838 ret = zfs_for_each(argc, argv, flags, types, NULL,
1839 &cb.cb_proplist, limit, get_callback, &cb);
1841 if (cb.cb_proplist == &fake_name)
1842 zprop_free_list(fake_name.pl_next);
1843 else
1844 zprop_free_list(cb.cb_proplist);
1846 return (ret);
1850 * inherit [-rS] <property> <fs|vol> ...
1852 * -r Recurse over all children
1853 * -S Revert to received value, if any
1855 * For each dataset specified on the command line, inherit the given property
1856 * from its parent. Inheriting a property at the pool level will cause it to
1857 * use the default value. The '-r' flag will recurse over all children, and is
1858 * useful for setting a property on a hierarchy-wide basis, regardless of any
1859 * local modifications for each dataset.
1862 typedef struct inherit_cbdata {
1863 const char *cb_propname;
1864 boolean_t cb_received;
1865 } inherit_cbdata_t;
1867 static int
1868 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
1870 inherit_cbdata_t *cb = data;
1871 zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
1874 * If we're doing it recursively, then ignore properties that
1875 * are not valid for this type of dataset.
1877 if (prop != ZPROP_INVAL &&
1878 !zfs_prop_valid_for_type(prop, zfs_get_type(zhp)))
1879 return (0);
1881 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1884 static int
1885 inherit_cb(zfs_handle_t *zhp, void *data)
1887 inherit_cbdata_t *cb = data;
1889 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1892 static int
1893 zfs_do_inherit(int argc, char **argv)
1895 int c;
1896 zfs_prop_t prop;
1897 inherit_cbdata_t cb = { 0 };
1898 char *propname;
1899 int ret = 0;
1900 int flags = 0;
1901 boolean_t received = B_FALSE;
1903 /* check options */
1904 while ((c = getopt(argc, argv, "rS")) != -1) {
1905 switch (c) {
1906 case 'r':
1907 flags |= ZFS_ITER_RECURSE;
1908 break;
1909 case 'S':
1910 received = B_TRUE;
1911 break;
1912 case '?':
1913 default:
1914 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1915 optopt);
1916 usage(B_FALSE);
1920 argc -= optind;
1921 argv += optind;
1923 /* check number of arguments */
1924 if (argc < 1) {
1925 (void) fprintf(stderr, gettext("missing property argument\n"));
1926 usage(B_FALSE);
1928 if (argc < 2) {
1929 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1930 usage(B_FALSE);
1933 propname = argv[0];
1934 argc--;
1935 argv++;
1937 if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1938 if (zfs_prop_readonly(prop)) {
1939 (void) fprintf(stderr, gettext(
1940 "%s property is read-only\n"),
1941 propname);
1942 return (1);
1944 if (!zfs_prop_inheritable(prop) && !received) {
1945 (void) fprintf(stderr, gettext("'%s' property cannot "
1946 "be inherited\n"), propname);
1947 if (prop == ZFS_PROP_QUOTA ||
1948 prop == ZFS_PROP_RESERVATION ||
1949 prop == ZFS_PROP_REFQUOTA ||
1950 prop == ZFS_PROP_REFRESERVATION) {
1951 (void) fprintf(stderr, gettext("use 'zfs set "
1952 "%s=none' to clear\n"), propname);
1953 (void) fprintf(stderr, gettext("use 'zfs "
1954 "inherit -S %s' to revert to received "
1955 "value\n"), propname);
1957 return (1);
1959 if (received && (prop == ZFS_PROP_VOLSIZE ||
1960 prop == ZFS_PROP_VERSION)) {
1961 (void) fprintf(stderr, gettext("'%s' property cannot "
1962 "be reverted to a received value\n"), propname);
1963 return (1);
1965 } else if (!zfs_prop_user(propname)) {
1966 (void) fprintf(stderr, gettext("invalid property '%s'\n"),
1967 propname);
1968 usage(B_FALSE);
1971 cb.cb_propname = propname;
1972 cb.cb_received = received;
1974 if (flags & ZFS_ITER_RECURSE) {
1975 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1976 NULL, NULL, 0, inherit_recurse_cb, &cb);
1977 } else {
1978 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1979 NULL, NULL, 0, inherit_cb, &cb);
1982 return (ret);
1985 typedef struct upgrade_cbdata {
1986 uint64_t cb_numupgraded;
1987 uint64_t cb_numsamegraded;
1988 uint64_t cb_numfailed;
1989 uint64_t cb_version;
1990 boolean_t cb_newer;
1991 boolean_t cb_foundone;
1992 char cb_lastfs[ZFS_MAX_DATASET_NAME_LEN];
1993 } upgrade_cbdata_t;
1995 static int
1996 same_pool(zfs_handle_t *zhp, const char *name)
1998 int len1 = strcspn(name, "/@");
1999 const char *zhname = zfs_get_name(zhp);
2000 int len2 = strcspn(zhname, "/@");
2002 if (len1 != len2)
2003 return (B_FALSE);
2004 return (strncmp(name, zhname, len1) == 0);
2007 static int
2008 upgrade_list_callback(zfs_handle_t *zhp, void *data)
2010 upgrade_cbdata_t *cb = data;
2011 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2013 /* list if it's old/new */
2014 if ((!cb->cb_newer && version < ZPL_VERSION) ||
2015 (cb->cb_newer && version > ZPL_VERSION)) {
2016 char *str;
2017 if (cb->cb_newer) {
2018 str = gettext("The following filesystems are "
2019 "formatted using a newer software version and\n"
2020 "cannot be accessed on the current system.\n\n");
2021 } else {
2022 str = gettext("The following filesystems are "
2023 "out of date, and can be upgraded. After being\n"
2024 "upgraded, these filesystems (and any 'zfs send' "
2025 "streams generated from\n"
2026 "subsequent snapshots) will no longer be "
2027 "accessible by older software versions.\n\n");
2030 if (!cb->cb_foundone) {
2031 (void) puts(str);
2032 (void) printf(gettext("VER FILESYSTEM\n"));
2033 (void) printf(gettext("--- ------------\n"));
2034 cb->cb_foundone = B_TRUE;
2037 (void) printf("%2u %s\n", version, zfs_get_name(zhp));
2040 return (0);
2043 static int
2044 upgrade_set_callback(zfs_handle_t *zhp, void *data)
2046 upgrade_cbdata_t *cb = data;
2047 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2048 int needed_spa_version;
2049 int spa_version;
2051 if (zfs_spa_version(zhp, &spa_version) < 0)
2052 return (-1);
2054 needed_spa_version = zfs_spa_version_map(cb->cb_version);
2056 if (needed_spa_version < 0)
2057 return (-1);
2059 if (spa_version < needed_spa_version) {
2060 /* can't upgrade */
2061 (void) printf(gettext("%s: can not be "
2062 "upgraded; the pool version needs to first "
2063 "be upgraded\nto version %d\n\n"),
2064 zfs_get_name(zhp), needed_spa_version);
2065 cb->cb_numfailed++;
2066 return (0);
2069 /* upgrade */
2070 if (version < cb->cb_version) {
2071 char verstr[16];
2072 (void) snprintf(verstr, sizeof (verstr),
2073 "%llu", cb->cb_version);
2074 if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
2076 * If they did "zfs upgrade -a", then we could
2077 * be doing ioctls to different pools. We need
2078 * to log this history once to each pool, and bypass
2079 * the normal history logging that happens in main().
2081 (void) zpool_log_history(g_zfs, history_str);
2082 log_history = B_FALSE;
2084 if (zfs_prop_set(zhp, "version", verstr) == 0)
2085 cb->cb_numupgraded++;
2086 else
2087 cb->cb_numfailed++;
2088 (void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
2089 } else if (version > cb->cb_version) {
2090 /* can't downgrade */
2091 (void) printf(gettext("%s: can not be downgraded; "
2092 "it is already at version %u\n"),
2093 zfs_get_name(zhp), version);
2094 cb->cb_numfailed++;
2095 } else {
2096 cb->cb_numsamegraded++;
2098 return (0);
2102 * zfs upgrade
2103 * zfs upgrade -v
2104 * zfs upgrade [-r] [-V <version>] <-a | filesystem>
2106 static int
2107 zfs_do_upgrade(int argc, char **argv)
2109 boolean_t all = B_FALSE;
2110 boolean_t showversions = B_FALSE;
2111 int ret = 0;
2112 upgrade_cbdata_t cb = { 0 };
2113 char c;
2114 int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2116 /* check options */
2117 while ((c = getopt(argc, argv, "rvV:a")) != -1) {
2118 switch (c) {
2119 case 'r':
2120 flags |= ZFS_ITER_RECURSE;
2121 break;
2122 case 'v':
2123 showversions = B_TRUE;
2124 break;
2125 case 'V':
2126 if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
2127 optarg, &cb.cb_version) != 0) {
2128 (void) fprintf(stderr,
2129 gettext("invalid version %s\n"), optarg);
2130 usage(B_FALSE);
2132 break;
2133 case 'a':
2134 all = B_TRUE;
2135 break;
2136 case '?':
2137 default:
2138 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2139 optopt);
2140 usage(B_FALSE);
2144 argc -= optind;
2145 argv += optind;
2147 if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
2148 usage(B_FALSE);
2149 if (showversions && (flags & ZFS_ITER_RECURSE || all ||
2150 cb.cb_version || argc))
2151 usage(B_FALSE);
2152 if ((all || argc) && (showversions))
2153 usage(B_FALSE);
2154 if (all && argc)
2155 usage(B_FALSE);
2157 if (showversions) {
2158 /* Show info on available versions. */
2159 (void) printf(gettext("The following filesystem versions are "
2160 "supported:\n\n"));
2161 (void) printf(gettext("VER DESCRIPTION\n"));
2162 (void) printf("--- -----------------------------------------"
2163 "---------------\n");
2164 (void) printf(gettext(" 1 Initial ZFS filesystem version\n"));
2165 (void) printf(gettext(" 2 Enhanced directory entries\n"));
2166 (void) printf(gettext(" 3 Case insensitive and filesystem "
2167 "user identifier (FUID)\n"));
2168 (void) printf(gettext(" 4 userquota, groupquota "
2169 "properties\n"));
2170 (void) printf(gettext(" 5 System attributes\n"));
2171 (void) printf(gettext("\nFor more information on a particular "
2172 "version, including supported releases,\n"));
2173 (void) printf("see the ZFS Administration Guide.\n\n");
2174 ret = 0;
2175 } else if (argc || all) {
2176 /* Upgrade filesystems */
2177 if (cb.cb_version == 0)
2178 cb.cb_version = ZPL_VERSION;
2179 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
2180 NULL, NULL, 0, upgrade_set_callback, &cb);
2181 (void) printf(gettext("%llu filesystems upgraded\n"),
2182 cb.cb_numupgraded);
2183 if (cb.cb_numsamegraded) {
2184 (void) printf(gettext("%llu filesystems already at "
2185 "this version\n"),
2186 cb.cb_numsamegraded);
2188 if (cb.cb_numfailed != 0)
2189 ret = 1;
2190 } else {
2191 /* List old-version filesystems */
2192 boolean_t found;
2193 (void) printf(gettext("This system is currently running "
2194 "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
2196 flags |= ZFS_ITER_RECURSE;
2197 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2198 NULL, NULL, 0, upgrade_list_callback, &cb);
2200 found = cb.cb_foundone;
2201 cb.cb_foundone = B_FALSE;
2202 cb.cb_newer = B_TRUE;
2204 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2205 NULL, NULL, 0, upgrade_list_callback, &cb);
2207 if (!cb.cb_foundone && !found) {
2208 (void) printf(gettext("All filesystems are "
2209 "formatted with the current version.\n"));
2213 return (ret);
2217 * zfs userspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2218 * [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2219 * zfs groupspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2220 * [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2222 * -H Scripted mode; elide headers and separate columns by tabs.
2223 * -i Translate SID to POSIX ID.
2224 * -n Print numeric ID instead of user/group name.
2225 * -o Control which fields to display.
2226 * -p Use exact (parsable) numeric output.
2227 * -s Specify sort columns, descending order.
2228 * -S Specify sort columns, ascending order.
2229 * -t Control which object types to display.
2231 * Displays space consumed by, and quotas on, each user in the specified
2232 * filesystem or snapshot.
2235 /* us_field_types, us_field_hdr and us_field_names should be kept in sync */
2236 enum us_field_types {
2237 USFIELD_TYPE,
2238 USFIELD_NAME,
2239 USFIELD_USED,
2240 USFIELD_QUOTA
2242 static char *us_field_hdr[] = { "TYPE", "NAME", "USED", "QUOTA" };
2243 static char *us_field_names[] = { "type", "name", "used", "quota" };
2244 #define USFIELD_LAST (sizeof (us_field_names) / sizeof (char *))
2246 #define USTYPE_PSX_GRP (1 << 0)
2247 #define USTYPE_PSX_USR (1 << 1)
2248 #define USTYPE_SMB_GRP (1 << 2)
2249 #define USTYPE_SMB_USR (1 << 3)
2250 #define USTYPE_ALL \
2251 (USTYPE_PSX_GRP | USTYPE_PSX_USR | USTYPE_SMB_GRP | USTYPE_SMB_USR)
2253 static int us_type_bits[] = {
2254 USTYPE_PSX_GRP,
2255 USTYPE_PSX_USR,
2256 USTYPE_SMB_GRP,
2257 USTYPE_SMB_USR,
2258 USTYPE_ALL
2260 static char *us_type_names[] = { "posixgroup", "posixuser", "smbgroup",
2261 "smbuser", "all" };
2263 typedef struct us_node {
2264 nvlist_t *usn_nvl;
2265 uu_avl_node_t usn_avlnode;
2266 uu_list_node_t usn_listnode;
2267 } us_node_t;
2269 typedef struct us_cbdata {
2270 nvlist_t **cb_nvlp;
2271 uu_avl_pool_t *cb_avl_pool;
2272 uu_avl_t *cb_avl;
2273 boolean_t cb_numname;
2274 boolean_t cb_nicenum;
2275 boolean_t cb_sid2posix;
2276 zfs_userquota_prop_t cb_prop;
2277 zfs_sort_column_t *cb_sortcol;
2278 size_t cb_width[USFIELD_LAST];
2279 } us_cbdata_t;
2281 static boolean_t us_populated = B_FALSE;
2283 typedef struct {
2284 zfs_sort_column_t *si_sortcol;
2285 boolean_t si_numname;
2286 } us_sort_info_t;
2288 static int
2289 us_field_index(char *field)
2291 int i;
2293 for (i = 0; i < USFIELD_LAST; i++) {
2294 if (strcmp(field, us_field_names[i]) == 0)
2295 return (i);
2298 return (-1);
2301 static int
2302 us_compare(const void *larg, const void *rarg, void *unused)
2304 const us_node_t *l = larg;
2305 const us_node_t *r = rarg;
2306 us_sort_info_t *si = (us_sort_info_t *)unused;
2307 zfs_sort_column_t *sortcol = si->si_sortcol;
2308 boolean_t numname = si->si_numname;
2309 nvlist_t *lnvl = l->usn_nvl;
2310 nvlist_t *rnvl = r->usn_nvl;
2311 int rc = 0;
2312 boolean_t lvb, rvb;
2314 for (; sortcol != NULL; sortcol = sortcol->sc_next) {
2315 char *lvstr = "";
2316 char *rvstr = "";
2317 uint32_t lv32 = 0;
2318 uint32_t rv32 = 0;
2319 uint64_t lv64 = 0;
2320 uint64_t rv64 = 0;
2321 zfs_prop_t prop = sortcol->sc_prop;
2322 const char *propname = NULL;
2323 boolean_t reverse = sortcol->sc_reverse;
2325 switch (prop) {
2326 case ZFS_PROP_TYPE:
2327 propname = "type";
2328 (void) nvlist_lookup_uint32(lnvl, propname, &lv32);
2329 (void) nvlist_lookup_uint32(rnvl, propname, &rv32);
2330 if (rv32 != lv32)
2331 rc = (rv32 < lv32) ? 1 : -1;
2332 break;
2333 case ZFS_PROP_NAME:
2334 propname = "name";
2335 if (numname) {
2336 (void) nvlist_lookup_uint64(lnvl, propname,
2337 &lv64);
2338 (void) nvlist_lookup_uint64(rnvl, propname,
2339 &rv64);
2340 if (rv64 != lv64)
2341 rc = (rv64 < lv64) ? 1 : -1;
2342 } else {
2343 (void) nvlist_lookup_string(lnvl, propname,
2344 &lvstr);
2345 (void) nvlist_lookup_string(rnvl, propname,
2346 &rvstr);
2347 rc = strcmp(lvstr, rvstr);
2349 break;
2350 case ZFS_PROP_USED:
2351 case ZFS_PROP_QUOTA:
2352 if (!us_populated)
2353 break;
2354 if (prop == ZFS_PROP_USED)
2355 propname = "used";
2356 else
2357 propname = "quota";
2358 (void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2359 (void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2360 if (rv64 != lv64)
2361 rc = (rv64 < lv64) ? 1 : -1;
2362 break;
2364 default:
2365 break;
2368 if (rc != 0) {
2369 if (rc < 0)
2370 return (reverse ? 1 : -1);
2371 else
2372 return (reverse ? -1 : 1);
2377 * If entries still seem to be the same, check if they are of the same
2378 * type (smbentity is added only if we are doing SID to POSIX ID
2379 * translation where we can have duplicate type/name combinations).
2381 if (nvlist_lookup_boolean_value(lnvl, "smbentity", &lvb) == 0 &&
2382 nvlist_lookup_boolean_value(rnvl, "smbentity", &rvb) == 0 &&
2383 lvb != rvb)
2384 return (lvb < rvb ? -1 : 1);
2386 return (0);
2389 static inline const char *
2390 us_type2str(unsigned field_type)
2392 switch (field_type) {
2393 case USTYPE_PSX_USR:
2394 return ("POSIX User");
2395 case USTYPE_PSX_GRP:
2396 return ("POSIX Group");
2397 case USTYPE_SMB_USR:
2398 return ("SMB User");
2399 case USTYPE_SMB_GRP:
2400 return ("SMB Group");
2401 default:
2402 return ("Undefined");
2406 static int
2407 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2409 us_cbdata_t *cb = (us_cbdata_t *)arg;
2410 zfs_userquota_prop_t prop = cb->cb_prop;
2411 char *name = NULL;
2412 char *propname;
2413 char sizebuf[32];
2414 us_node_t *node;
2415 uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2416 uu_avl_t *avl = cb->cb_avl;
2417 uu_avl_index_t idx;
2418 nvlist_t *props;
2419 us_node_t *n;
2420 zfs_sort_column_t *sortcol = cb->cb_sortcol;
2421 unsigned type = 0;
2422 const char *typestr;
2423 size_t namelen;
2424 size_t typelen;
2425 size_t sizelen;
2426 int typeidx, nameidx, sizeidx;
2427 us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
2428 boolean_t smbentity = B_FALSE;
2430 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
2431 nomem();
2432 node = safe_malloc(sizeof (us_node_t));
2433 uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
2434 node->usn_nvl = props;
2436 if (domain != NULL && domain[0] != '\0') {
2437 /* SMB */
2438 char sid[MAXNAMELEN + 32];
2439 uid_t id;
2440 int err;
2441 int flag = IDMAP_REQ_FLG_USE_CACHE;
2443 smbentity = B_TRUE;
2445 (void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
2447 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2448 type = USTYPE_SMB_GRP;
2449 err = sid_to_id(sid, B_FALSE, &id);
2450 } else {
2451 type = USTYPE_SMB_USR;
2452 err = sid_to_id(sid, B_TRUE, &id);
2455 if (err == 0) {
2456 rid = id;
2457 if (!cb->cb_sid2posix) {
2458 if (type == USTYPE_SMB_USR) {
2459 (void) idmap_getwinnamebyuid(rid, flag,
2460 &name, NULL);
2461 } else {
2462 (void) idmap_getwinnamebygid(rid, flag,
2463 &name, NULL);
2465 if (name == NULL)
2466 name = sid;
2471 if (cb->cb_sid2posix || domain == NULL || domain[0] == '\0') {
2472 /* POSIX or -i */
2473 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2474 type = USTYPE_PSX_GRP;
2475 if (!cb->cb_numname) {
2476 struct group *g;
2478 if ((g = getgrgid(rid)) != NULL)
2479 name = g->gr_name;
2481 } else {
2482 type = USTYPE_PSX_USR;
2483 if (!cb->cb_numname) {
2484 struct passwd *p;
2486 if ((p = getpwuid(rid)) != NULL)
2487 name = p->pw_name;
2493 * Make sure that the type/name combination is unique when doing
2494 * SID to POSIX ID translation (hence changing the type from SMB to
2495 * POSIX).
2497 if (cb->cb_sid2posix &&
2498 nvlist_add_boolean_value(props, "smbentity", smbentity) != 0)
2499 nomem();
2501 /* Calculate/update width of TYPE field */
2502 typestr = us_type2str(type);
2503 typelen = strlen(gettext(typestr));
2504 typeidx = us_field_index("type");
2505 if (typelen > cb->cb_width[typeidx])
2506 cb->cb_width[typeidx] = typelen;
2507 if (nvlist_add_uint32(props, "type", type) != 0)
2508 nomem();
2510 /* Calculate/update width of NAME field */
2511 if ((cb->cb_numname && cb->cb_sid2posix) || name == NULL) {
2512 if (nvlist_add_uint64(props, "name", rid) != 0)
2513 nomem();
2514 namelen = snprintf(NULL, 0, "%u", rid);
2515 } else {
2516 if (nvlist_add_string(props, "name", name) != 0)
2517 nomem();
2518 namelen = strlen(name);
2520 nameidx = us_field_index("name");
2521 if (namelen > cb->cb_width[nameidx])
2522 cb->cb_width[nameidx] = namelen;
2525 * Check if this type/name combination is in the list and update it;
2526 * otherwise add new node to the list.
2528 if ((n = uu_avl_find(avl, node, &sortinfo, &idx)) == NULL) {
2529 uu_avl_insert(avl, node, idx);
2530 } else {
2531 nvlist_free(props);
2532 free(node);
2533 node = n;
2534 props = node->usn_nvl;
2537 /* Calculate/update width of USED/QUOTA fields */
2538 if (cb->cb_nicenum)
2539 zfs_nicenum(space, sizebuf, sizeof (sizebuf));
2540 else
2541 (void) snprintf(sizebuf, sizeof (sizebuf), "%llu", space);
2542 sizelen = strlen(sizebuf);
2543 if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED) {
2544 propname = "used";
2545 if (!nvlist_exists(props, "quota"))
2546 (void) nvlist_add_uint64(props, "quota", 0);
2547 } else {
2548 propname = "quota";
2549 if (!nvlist_exists(props, "used"))
2550 (void) nvlist_add_uint64(props, "used", 0);
2552 sizeidx = us_field_index(propname);
2553 if (sizelen > cb->cb_width[sizeidx])
2554 cb->cb_width[sizeidx] = sizelen;
2556 if (nvlist_add_uint64(props, propname, space) != 0)
2557 nomem();
2559 return (0);
2562 static void
2563 print_us_node(boolean_t scripted, boolean_t parsable, int *fields, int types,
2564 size_t *width, us_node_t *node)
2566 nvlist_t *nvl = node->usn_nvl;
2567 char valstr[MAXNAMELEN];
2568 boolean_t first = B_TRUE;
2569 int cfield = 0;
2570 int field;
2571 uint32_t ustype;
2573 /* Check type */
2574 (void) nvlist_lookup_uint32(nvl, "type", &ustype);
2575 if (!(ustype & types))
2576 return;
2578 while ((field = fields[cfield]) != USFIELD_LAST) {
2579 nvpair_t *nvp = NULL;
2580 data_type_t type;
2581 uint32_t val32;
2582 uint64_t val64;
2583 char *strval = NULL;
2585 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
2586 if (strcmp(nvpair_name(nvp),
2587 us_field_names[field]) == 0)
2588 break;
2591 type = nvpair_type(nvp);
2592 switch (type) {
2593 case DATA_TYPE_UINT32:
2594 (void) nvpair_value_uint32(nvp, &val32);
2595 break;
2596 case DATA_TYPE_UINT64:
2597 (void) nvpair_value_uint64(nvp, &val64);
2598 break;
2599 case DATA_TYPE_STRING:
2600 (void) nvpair_value_string(nvp, &strval);
2601 break;
2602 default:
2603 (void) fprintf(stderr, "invalid data type\n");
2606 switch (field) {
2607 case USFIELD_TYPE:
2608 strval = (char *)us_type2str(val32);
2609 break;
2610 case USFIELD_NAME:
2611 if (type == DATA_TYPE_UINT64) {
2612 (void) sprintf(valstr, "%llu", val64);
2613 strval = valstr;
2615 break;
2616 case USFIELD_USED:
2617 case USFIELD_QUOTA:
2618 if (type == DATA_TYPE_UINT64) {
2619 if (parsable) {
2620 (void) sprintf(valstr, "%llu", val64);
2621 } else {
2622 zfs_nicenum(val64, valstr,
2623 sizeof (valstr));
2625 if (field == USFIELD_QUOTA &&
2626 strcmp(valstr, "0") == 0)
2627 strval = "none";
2628 else
2629 strval = valstr;
2631 break;
2634 if (!first) {
2635 if (scripted)
2636 (void) printf("\t");
2637 else
2638 (void) printf(" ");
2640 if (scripted)
2641 (void) printf("%s", strval);
2642 else if (field == USFIELD_TYPE || field == USFIELD_NAME)
2643 (void) printf("%-*s", width[field], strval);
2644 else
2645 (void) printf("%*s", width[field], strval);
2647 first = B_FALSE;
2648 cfield++;
2651 (void) printf("\n");
2654 static void
2655 print_us(boolean_t scripted, boolean_t parsable, int *fields, int types,
2656 size_t *width, boolean_t rmnode, uu_avl_t *avl)
2658 us_node_t *node;
2659 const char *col;
2660 int cfield = 0;
2661 int field;
2663 if (!scripted) {
2664 boolean_t first = B_TRUE;
2666 while ((field = fields[cfield]) != USFIELD_LAST) {
2667 col = gettext(us_field_hdr[field]);
2668 if (field == USFIELD_TYPE || field == USFIELD_NAME) {
2669 (void) printf(first ? "%-*s" : " %-*s",
2670 width[field], col);
2671 } else {
2672 (void) printf(first ? "%*s" : " %*s",
2673 width[field], col);
2675 first = B_FALSE;
2676 cfield++;
2678 (void) printf("\n");
2681 for (node = uu_avl_first(avl); node; node = uu_avl_next(avl, node)) {
2682 print_us_node(scripted, parsable, fields, types, width, node);
2683 if (rmnode)
2684 nvlist_free(node->usn_nvl);
2688 static int
2689 zfs_do_userspace(int argc, char **argv)
2691 zfs_handle_t *zhp;
2692 zfs_userquota_prop_t p;
2693 uu_avl_pool_t *avl_pool;
2694 uu_avl_t *avl_tree;
2695 uu_avl_walk_t *walk;
2696 char *delim;
2697 char deffields[] = "type,name,used,quota";
2698 char *ofield = NULL;
2699 char *tfield = NULL;
2700 int cfield = 0;
2701 int fields[256];
2702 int i;
2703 boolean_t scripted = B_FALSE;
2704 boolean_t prtnum = B_FALSE;
2705 boolean_t parsable = B_FALSE;
2706 boolean_t sid2posix = B_FALSE;
2707 int ret = 0;
2708 int c;
2709 zfs_sort_column_t *sortcol = NULL;
2710 int types = USTYPE_PSX_USR | USTYPE_SMB_USR;
2711 us_cbdata_t cb;
2712 us_node_t *node;
2713 us_node_t *rmnode;
2714 uu_list_pool_t *listpool;
2715 uu_list_t *list;
2716 uu_avl_index_t idx = 0;
2717 uu_list_index_t idx2 = 0;
2719 if (argc < 2)
2720 usage(B_FALSE);
2722 if (strcmp(argv[0], "groupspace") == 0)
2723 /* Toggle default group types */
2724 types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
2726 while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
2727 switch (c) {
2728 case 'n':
2729 prtnum = B_TRUE;
2730 break;
2731 case 'H':
2732 scripted = B_TRUE;
2733 break;
2734 case 'p':
2735 parsable = B_TRUE;
2736 break;
2737 case 'o':
2738 ofield = optarg;
2739 break;
2740 case 's':
2741 case 'S':
2742 if (zfs_add_sort_column(&sortcol, optarg,
2743 c == 's' ? B_FALSE : B_TRUE) != 0) {
2744 (void) fprintf(stderr,
2745 gettext("invalid field '%s'\n"), optarg);
2746 usage(B_FALSE);
2748 break;
2749 case 't':
2750 tfield = optarg;
2751 break;
2752 case 'i':
2753 sid2posix = B_TRUE;
2754 break;
2755 case ':':
2756 (void) fprintf(stderr, gettext("missing argument for "
2757 "'%c' option\n"), optopt);
2758 usage(B_FALSE);
2759 break;
2760 case '?':
2761 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2762 optopt);
2763 usage(B_FALSE);
2767 argc -= optind;
2768 argv += optind;
2770 if (argc < 1) {
2771 (void) fprintf(stderr, gettext("missing dataset name\n"));
2772 usage(B_FALSE);
2774 if (argc > 1) {
2775 (void) fprintf(stderr, gettext("too many arguments\n"));
2776 usage(B_FALSE);
2779 /* Use default output fields if not specified using -o */
2780 if (ofield == NULL)
2781 ofield = deffields;
2782 do {
2783 if ((delim = strchr(ofield, ',')) != NULL)
2784 *delim = '\0';
2785 if ((fields[cfield++] = us_field_index(ofield)) == -1) {
2786 (void) fprintf(stderr, gettext("invalid type '%s' "
2787 "for -o option\n"), ofield);
2788 return (-1);
2790 if (delim != NULL)
2791 ofield = delim + 1;
2792 } while (delim != NULL);
2793 fields[cfield] = USFIELD_LAST;
2795 /* Override output types (-t option) */
2796 if (tfield != NULL) {
2797 types = 0;
2799 do {
2800 boolean_t found = B_FALSE;
2802 if ((delim = strchr(tfield, ',')) != NULL)
2803 *delim = '\0';
2804 for (i = 0; i < sizeof (us_type_bits) / sizeof (int);
2805 i++) {
2806 if (strcmp(tfield, us_type_names[i]) == 0) {
2807 found = B_TRUE;
2808 types |= us_type_bits[i];
2809 break;
2812 if (!found) {
2813 (void) fprintf(stderr, gettext("invalid type "
2814 "'%s' for -t option\n"), tfield);
2815 return (-1);
2817 if (delim != NULL)
2818 tfield = delim + 1;
2819 } while (delim != NULL);
2822 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
2823 return (1);
2825 if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
2826 offsetof(us_node_t, usn_avlnode), us_compare, UU_DEFAULT)) == NULL)
2827 nomem();
2828 if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
2829 nomem();
2831 /* Always add default sorting columns */
2832 (void) zfs_add_sort_column(&sortcol, "type", B_FALSE);
2833 (void) zfs_add_sort_column(&sortcol, "name", B_FALSE);
2835 cb.cb_sortcol = sortcol;
2836 cb.cb_numname = prtnum;
2837 cb.cb_nicenum = !parsable;
2838 cb.cb_avl_pool = avl_pool;
2839 cb.cb_avl = avl_tree;
2840 cb.cb_sid2posix = sid2posix;
2842 for (i = 0; i < USFIELD_LAST; i++)
2843 cb.cb_width[i] = strlen(gettext(us_field_hdr[i]));
2845 for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
2846 if (((p == ZFS_PROP_USERUSED || p == ZFS_PROP_USERQUOTA) &&
2847 !(types & (USTYPE_PSX_USR | USTYPE_SMB_USR))) ||
2848 ((p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA) &&
2849 !(types & (USTYPE_PSX_GRP | USTYPE_SMB_GRP))))
2850 continue;
2851 cb.cb_prop = p;
2852 if ((ret = zfs_userspace(zhp, p, userspace_cb, &cb)) != 0)
2853 return (ret);
2856 /* Sort the list */
2857 if ((node = uu_avl_first(avl_tree)) == NULL)
2858 return (0);
2860 us_populated = B_TRUE;
2862 listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
2863 offsetof(us_node_t, usn_listnode), NULL, UU_DEFAULT);
2864 list = uu_list_create(listpool, NULL, UU_DEFAULT);
2865 uu_list_node_init(node, &node->usn_listnode, listpool);
2867 while (node != NULL) {
2868 rmnode = node;
2869 node = uu_avl_next(avl_tree, node);
2870 uu_avl_remove(avl_tree, rmnode);
2871 if (uu_list_find(list, rmnode, NULL, &idx2) == NULL)
2872 uu_list_insert(list, rmnode, idx2);
2875 for (node = uu_list_first(list); node != NULL;
2876 node = uu_list_next(list, node)) {
2877 us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
2879 if (uu_avl_find(avl_tree, node, &sortinfo, &idx) == NULL)
2880 uu_avl_insert(avl_tree, node, idx);
2883 uu_list_destroy(list);
2884 uu_list_pool_destroy(listpool);
2886 /* Print and free node nvlist memory */
2887 print_us(scripted, parsable, fields, types, cb.cb_width, B_TRUE,
2888 cb.cb_avl);
2890 zfs_free_sort_columns(sortcol);
2892 /* Clean up the AVL tree */
2893 if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
2894 nomem();
2896 while ((node = uu_avl_walk_next(walk)) != NULL) {
2897 uu_avl_remove(cb.cb_avl, node);
2898 free(node);
2901 uu_avl_walk_end(walk);
2902 uu_avl_destroy(avl_tree);
2903 uu_avl_pool_destroy(avl_pool);
2905 return (ret);
2909 * list [-Hp][-r|-d max] [-o property[,...]] [-s property] ... [-S property] ...
2910 * [-t type[,...]] [filesystem|volume|snapshot] ...
2912 * -H Scripted mode; elide headers and separate columns by tabs.
2913 * -p Display values in parsable (literal) format.
2914 * -r Recurse over all children.
2915 * -d Limit recursion by depth.
2916 * -o Control which fields to display.
2917 * -s Specify sort columns, descending order.
2918 * -S Specify sort columns, ascending order.
2919 * -t Control which object types to display.
2921 * When given no arguments, list all filesystems in the system.
2922 * Otherwise, list the specified datasets, optionally recursing down them if
2923 * '-r' is specified.
2925 typedef struct list_cbdata {
2926 boolean_t cb_first;
2927 boolean_t cb_literal;
2928 boolean_t cb_scripted;
2929 zprop_list_t *cb_proplist;
2930 } list_cbdata_t;
2933 * Given a list of columns to display, output appropriate headers for each one.
2935 static void
2936 print_header(list_cbdata_t *cb)
2938 zprop_list_t *pl = cb->cb_proplist;
2939 char headerbuf[ZFS_MAXPROPLEN];
2940 const char *header;
2941 int i;
2942 boolean_t first = B_TRUE;
2943 boolean_t right_justify;
2945 for (; pl != NULL; pl = pl->pl_next) {
2946 if (!first) {
2947 (void) printf(" ");
2948 } else {
2949 first = B_FALSE;
2952 right_justify = B_FALSE;
2953 if (pl->pl_prop != ZPROP_INVAL) {
2954 header = zfs_prop_column_name(pl->pl_prop);
2955 right_justify = zfs_prop_align_right(pl->pl_prop);
2956 } else {
2957 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
2958 headerbuf[i] = toupper(pl->pl_user_prop[i]);
2959 headerbuf[i] = '\0';
2960 header = headerbuf;
2963 if (pl->pl_next == NULL && !right_justify)
2964 (void) printf("%s", header);
2965 else if (right_justify)
2966 (void) printf("%*s", pl->pl_width, header);
2967 else
2968 (void) printf("%-*s", pl->pl_width, header);
2971 (void) printf("\n");
2975 * Given a dataset and a list of fields, print out all the properties according
2976 * to the described layout.
2978 static void
2979 print_dataset(zfs_handle_t *zhp, list_cbdata_t *cb)
2981 zprop_list_t *pl = cb->cb_proplist;
2982 boolean_t first = B_TRUE;
2983 char property[ZFS_MAXPROPLEN];
2984 nvlist_t *userprops = zfs_get_user_props(zhp);
2985 nvlist_t *propval;
2986 char *propstr;
2987 boolean_t right_justify;
2989 for (; pl != NULL; pl = pl->pl_next) {
2990 if (!first) {
2991 if (cb->cb_scripted)
2992 (void) printf("\t");
2993 else
2994 (void) printf(" ");
2995 } else {
2996 first = B_FALSE;
2999 if (pl->pl_prop == ZFS_PROP_NAME) {
3000 (void) strlcpy(property, zfs_get_name(zhp),
3001 sizeof (property));
3002 propstr = property;
3003 right_justify = zfs_prop_align_right(pl->pl_prop);
3004 } else if (pl->pl_prop != ZPROP_INVAL) {
3005 if (zfs_prop_get(zhp, pl->pl_prop, property,
3006 sizeof (property), NULL, NULL, 0,
3007 cb->cb_literal) != 0)
3008 propstr = "-";
3009 else
3010 propstr = property;
3011 right_justify = zfs_prop_align_right(pl->pl_prop);
3012 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
3013 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
3014 property, sizeof (property), cb->cb_literal) != 0)
3015 propstr = "-";
3016 else
3017 propstr = property;
3018 right_justify = B_TRUE;
3019 } else if (zfs_prop_written(pl->pl_user_prop)) {
3020 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
3021 property, sizeof (property), cb->cb_literal) != 0)
3022 propstr = "-";
3023 else
3024 propstr = property;
3025 right_justify = B_TRUE;
3026 } else {
3027 if (nvlist_lookup_nvlist(userprops,
3028 pl->pl_user_prop, &propval) != 0)
3029 propstr = "-";
3030 else
3031 verify(nvlist_lookup_string(propval,
3032 ZPROP_VALUE, &propstr) == 0);
3033 right_justify = B_FALSE;
3037 * If this is being called in scripted mode, or if this is the
3038 * last column and it is left-justified, don't include a width
3039 * format specifier.
3041 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
3042 (void) printf("%s", propstr);
3043 else if (right_justify)
3044 (void) printf("%*s", pl->pl_width, propstr);
3045 else
3046 (void) printf("%-*s", pl->pl_width, propstr);
3049 (void) printf("\n");
3053 * Generic callback function to list a dataset or snapshot.
3055 static int
3056 list_callback(zfs_handle_t *zhp, void *data)
3058 list_cbdata_t *cbp = data;
3060 if (cbp->cb_first) {
3061 if (!cbp->cb_scripted)
3062 print_header(cbp);
3063 cbp->cb_first = B_FALSE;
3066 print_dataset(zhp, cbp);
3068 return (0);
3071 static int
3072 zfs_do_list(int argc, char **argv)
3074 int c;
3075 static char default_fields[] =
3076 "name,used,available,referenced,mountpoint";
3077 int types = ZFS_TYPE_DATASET;
3078 boolean_t types_specified = B_FALSE;
3079 char *fields = NULL;
3080 list_cbdata_t cb = { 0 };
3081 char *value;
3082 int limit = 0;
3083 int ret = 0;
3084 zfs_sort_column_t *sortcol = NULL;
3085 int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
3087 /* check options */
3088 while ((c = getopt(argc, argv, "HS:d:o:prs:t:")) != -1) {
3089 switch (c) {
3090 case 'o':
3091 fields = optarg;
3092 break;
3093 case 'p':
3094 cb.cb_literal = B_TRUE;
3095 flags |= ZFS_ITER_LITERAL_PROPS;
3096 break;
3097 case 'd':
3098 limit = parse_depth(optarg, &flags);
3099 break;
3100 case 'r':
3101 flags |= ZFS_ITER_RECURSE;
3102 break;
3103 case 'H':
3104 cb.cb_scripted = B_TRUE;
3105 break;
3106 case 's':
3107 if (zfs_add_sort_column(&sortcol, optarg,
3108 B_FALSE) != 0) {
3109 (void) fprintf(stderr,
3110 gettext("invalid property '%s'\n"), optarg);
3111 usage(B_FALSE);
3113 break;
3114 case 'S':
3115 if (zfs_add_sort_column(&sortcol, optarg,
3116 B_TRUE) != 0) {
3117 (void) fprintf(stderr,
3118 gettext("invalid property '%s'\n"), optarg);
3119 usage(B_FALSE);
3121 break;
3122 case 't':
3123 types = 0;
3124 types_specified = B_TRUE;
3125 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
3126 while (*optarg != '\0') {
3127 static char *type_subopts[] = { "filesystem",
3128 "volume", "snapshot", "snap", "bookmark",
3129 "all", NULL };
3131 switch (getsubopt(&optarg, type_subopts,
3132 &value)) {
3133 case 0:
3134 types |= ZFS_TYPE_FILESYSTEM;
3135 break;
3136 case 1:
3137 types |= ZFS_TYPE_VOLUME;
3138 break;
3139 case 2:
3140 case 3:
3141 types |= ZFS_TYPE_SNAPSHOT;
3142 break;
3143 case 4:
3144 types |= ZFS_TYPE_BOOKMARK;
3145 break;
3146 case 5:
3147 types = ZFS_TYPE_DATASET |
3148 ZFS_TYPE_BOOKMARK;
3149 break;
3150 default:
3151 (void) fprintf(stderr,
3152 gettext("invalid type '%s'\n"),
3153 value);
3154 usage(B_FALSE);
3157 break;
3158 case ':':
3159 (void) fprintf(stderr, gettext("missing argument for "
3160 "'%c' option\n"), optopt);
3161 usage(B_FALSE);
3162 break;
3163 case '?':
3164 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3165 optopt);
3166 usage(B_FALSE);
3170 argc -= optind;
3171 argv += optind;
3173 if (fields == NULL)
3174 fields = default_fields;
3177 * If we are only going to list snapshot names and sort by name,
3178 * then we can use faster version.
3180 if (strcmp(fields, "name") == 0 && zfs_sort_only_by_name(sortcol))
3181 flags |= ZFS_ITER_SIMPLE;
3184 * If "-o space" and no types were specified, don't display snapshots.
3186 if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3187 types &= ~ZFS_TYPE_SNAPSHOT;
3190 * If the user specifies '-o all', the zprop_get_list() doesn't
3191 * normally include the name of the dataset. For 'zfs list', we always
3192 * want this property to be first.
3194 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3195 != 0)
3196 usage(B_FALSE);
3198 cb.cb_first = B_TRUE;
3200 ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
3201 limit, list_callback, &cb);
3203 zprop_free_list(cb.cb_proplist);
3204 zfs_free_sort_columns(sortcol);
3206 if (ret == 0 && cb.cb_first && !cb.cb_scripted)
3207 (void) printf(gettext("no datasets available\n"));
3209 return (ret);
3213 * zfs rename [-f] <fs | snap | vol> <fs | snap | vol>
3214 * zfs rename [-f] -p <fs | vol> <fs | vol>
3215 * zfs rename -r <snap> <snap>
3217 * Renames the given dataset to another of the same type.
3219 * The '-p' flag creates all the non-existing ancestors of the target first.
3221 /* ARGSUSED */
3222 static int
3223 zfs_do_rename(int argc, char **argv)
3225 zfs_handle_t *zhp;
3226 int c;
3227 int ret = 0;
3228 boolean_t recurse = B_FALSE;
3229 boolean_t parents = B_FALSE;
3230 boolean_t force_unmount = B_FALSE;
3232 /* check options */
3233 while ((c = getopt(argc, argv, "prf")) != -1) {
3234 switch (c) {
3235 case 'p':
3236 parents = B_TRUE;
3237 break;
3238 case 'r':
3239 recurse = B_TRUE;
3240 break;
3241 case 'f':
3242 force_unmount = B_TRUE;
3243 break;
3244 case '?':
3245 default:
3246 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3247 optopt);
3248 usage(B_FALSE);
3252 argc -= optind;
3253 argv += optind;
3255 /* check number of arguments */
3256 if (argc < 1) {
3257 (void) fprintf(stderr, gettext("missing source dataset "
3258 "argument\n"));
3259 usage(B_FALSE);
3261 if (argc < 2) {
3262 (void) fprintf(stderr, gettext("missing target dataset "
3263 "argument\n"));
3264 usage(B_FALSE);
3266 if (argc > 2) {
3267 (void) fprintf(stderr, gettext("too many arguments\n"));
3268 usage(B_FALSE);
3271 if (recurse && parents) {
3272 (void) fprintf(stderr, gettext("-p and -r options are mutually "
3273 "exclusive\n"));
3274 usage(B_FALSE);
3277 if (recurse && strchr(argv[0], '@') == 0) {
3278 (void) fprintf(stderr, gettext("source dataset for recursive "
3279 "rename must be a snapshot\n"));
3280 usage(B_FALSE);
3283 if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
3284 ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
3285 return (1);
3287 /* If we were asked and the name looks good, try to create ancestors. */
3288 if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
3289 zfs_create_ancestors(g_zfs, argv[1]) != 0) {
3290 zfs_close(zhp);
3291 return (1);
3294 ret = (zfs_rename(zhp, argv[1], recurse, force_unmount) != 0);
3296 zfs_close(zhp);
3297 return (ret);
3301 * zfs promote <fs>
3303 * Promotes the given clone fs to be the parent
3305 /* ARGSUSED */
3306 static int
3307 zfs_do_promote(int argc, char **argv)
3309 zfs_handle_t *zhp;
3310 int ret = 0;
3312 /* check options */
3313 if (argc > 1 && argv[1][0] == '-') {
3314 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3315 argv[1][1]);
3316 usage(B_FALSE);
3319 /* check number of arguments */
3320 if (argc < 2) {
3321 (void) fprintf(stderr, gettext("missing clone filesystem"
3322 " argument\n"));
3323 usage(B_FALSE);
3325 if (argc > 2) {
3326 (void) fprintf(stderr, gettext("too many arguments\n"));
3327 usage(B_FALSE);
3330 zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3331 if (zhp == NULL)
3332 return (1);
3334 ret = (zfs_promote(zhp) != 0);
3337 zfs_close(zhp);
3338 return (ret);
3342 * zfs rollback [-rRf] <snapshot>
3344 * -r Delete any intervening snapshots before doing rollback
3345 * -R Delete any snapshots and their clones
3346 * -f ignored for backwards compatability
3348 * Given a filesystem, rollback to a specific snapshot, discarding any changes
3349 * since then and making it the active dataset. If more recent snapshots exist,
3350 * the command will complain unless the '-r' flag is given.
3352 typedef struct rollback_cbdata {
3353 uint64_t cb_create;
3354 boolean_t cb_first;
3355 int cb_doclones;
3356 char *cb_target;
3357 int cb_error;
3358 boolean_t cb_recurse;
3359 } rollback_cbdata_t;
3361 static int
3362 rollback_check_dependent(zfs_handle_t *zhp, void *data)
3364 rollback_cbdata_t *cbp = data;
3366 if (cbp->cb_first && cbp->cb_recurse) {
3367 (void) fprintf(stderr, gettext("cannot rollback to "
3368 "'%s': clones of previous snapshots exist\n"),
3369 cbp->cb_target);
3370 (void) fprintf(stderr, gettext("use '-R' to "
3371 "force deletion of the following clones and "
3372 "dependents:\n"));
3373 cbp->cb_first = 0;
3374 cbp->cb_error = 1;
3377 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
3379 zfs_close(zhp);
3380 return (0);
3384 * Report any snapshots more recent than the one specified. Used when '-r' is
3385 * not specified. We reuse this same callback for the snapshot dependents - if
3386 * 'cb_dependent' is set, then this is a dependent and we should report it
3387 * without checking the transaction group.
3389 static int
3390 rollback_check(zfs_handle_t *zhp, void *data)
3392 rollback_cbdata_t *cbp = data;
3394 if (cbp->cb_doclones) {
3395 zfs_close(zhp);
3396 return (0);
3399 if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
3400 if (cbp->cb_first && !cbp->cb_recurse) {
3401 (void) fprintf(stderr, gettext("cannot "
3402 "rollback to '%s': more recent snapshots "
3403 "or bookmarks exist\n"),
3404 cbp->cb_target);
3405 (void) fprintf(stderr, gettext("use '-r' to "
3406 "force deletion of the following "
3407 "snapshots and bookmarks:\n"));
3408 cbp->cb_first = 0;
3409 cbp->cb_error = 1;
3412 if (cbp->cb_recurse) {
3413 if (zfs_iter_dependents(zhp, B_TRUE,
3414 rollback_check_dependent, cbp) != 0) {
3415 zfs_close(zhp);
3416 return (-1);
3418 } else {
3419 (void) fprintf(stderr, "%s\n",
3420 zfs_get_name(zhp));
3423 zfs_close(zhp);
3424 return (0);
3427 static int
3428 zfs_do_rollback(int argc, char **argv)
3430 int ret = 0;
3431 int c;
3432 boolean_t force = B_FALSE;
3433 rollback_cbdata_t cb = { 0 };
3434 zfs_handle_t *zhp, *snap;
3435 char parentname[ZFS_MAX_DATASET_NAME_LEN];
3436 char *delim;
3438 /* check options */
3439 while ((c = getopt(argc, argv, "rRf")) != -1) {
3440 switch (c) {
3441 case 'r':
3442 cb.cb_recurse = 1;
3443 break;
3444 case 'R':
3445 cb.cb_recurse = 1;
3446 cb.cb_doclones = 1;
3447 break;
3448 case 'f':
3449 force = B_TRUE;
3450 break;
3451 case '?':
3452 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3453 optopt);
3454 usage(B_FALSE);
3458 argc -= optind;
3459 argv += optind;
3461 /* check number of arguments */
3462 if (argc < 1) {
3463 (void) fprintf(stderr, gettext("missing dataset argument\n"));
3464 usage(B_FALSE);
3466 if (argc > 1) {
3467 (void) fprintf(stderr, gettext("too many arguments\n"));
3468 usage(B_FALSE);
3471 /* open the snapshot */
3472 if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
3473 return (1);
3475 /* open the parent dataset */
3476 (void) strlcpy(parentname, argv[0], sizeof (parentname));
3477 verify((delim = strrchr(parentname, '@')) != NULL);
3478 *delim = '\0';
3479 if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
3480 zfs_close(snap);
3481 return (1);
3485 * Check for more recent snapshots and/or clones based on the presence
3486 * of '-r' and '-R'.
3488 cb.cb_target = argv[0];
3489 cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3490 cb.cb_first = B_TRUE;
3491 cb.cb_error = 0;
3492 if ((ret = zfs_iter_snapshots(zhp, B_FALSE, rollback_check, &cb)) != 0)
3493 goto out;
3494 if ((ret = zfs_iter_bookmarks(zhp, rollback_check, &cb)) != 0)
3495 goto out;
3497 if ((ret = cb.cb_error) != 0)
3498 goto out;
3501 * Rollback parent to the given snapshot.
3503 ret = zfs_rollback(zhp, snap, force);
3505 out:
3506 zfs_close(snap);
3507 zfs_close(zhp);
3509 if (ret == 0)
3510 return (0);
3511 else
3512 return (1);
3516 * zfs set property=value ... { fs | snap | vol } ...
3518 * Sets the given properties for all datasets specified on the command line.
3521 static int
3522 set_callback(zfs_handle_t *zhp, void *data)
3524 nvlist_t *props = data;
3526 if (zfs_prop_set_list(zhp, props) != 0) {
3527 switch (libzfs_errno(g_zfs)) {
3528 case EZFS_MOUNTFAILED:
3529 (void) fprintf(stderr, gettext("property may be set "
3530 "but unable to remount filesystem\n"));
3531 break;
3532 case EZFS_SHARENFSFAILED:
3533 (void) fprintf(stderr, gettext("property may be set "
3534 "but unable to reshare filesystem\n"));
3535 break;
3537 return (1);
3539 return (0);
3542 static int
3543 zfs_do_set(int argc, char **argv)
3545 nvlist_t *props = NULL;
3546 int ds_start = -1; /* argv idx of first dataset arg */
3547 int ret = 0;
3549 /* check for options */
3550 if (argc > 1 && argv[1][0] == '-') {
3551 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3552 argv[1][1]);
3553 usage(B_FALSE);
3556 /* check number of arguments */
3557 if (argc < 2) {
3558 (void) fprintf(stderr, gettext("missing arguments\n"));
3559 usage(B_FALSE);
3561 if (argc < 3) {
3562 if (strchr(argv[1], '=') == NULL) {
3563 (void) fprintf(stderr, gettext("missing property=value "
3564 "argument(s)\n"));
3565 } else {
3566 (void) fprintf(stderr, gettext("missing dataset "
3567 "name(s)\n"));
3569 usage(B_FALSE);
3572 /* validate argument order: prop=val args followed by dataset args */
3573 for (int i = 1; i < argc; i++) {
3574 if (strchr(argv[i], '=') != NULL) {
3575 if (ds_start > 0) {
3576 /* out-of-order prop=val argument */
3577 (void) fprintf(stderr, gettext("invalid "
3578 "argument order\n"), i);
3579 usage(B_FALSE);
3581 } else if (ds_start < 0) {
3582 ds_start = i;
3585 if (ds_start < 0) {
3586 (void) fprintf(stderr, gettext("missing dataset name(s)\n"));
3587 usage(B_FALSE);
3590 /* Populate a list of property settings */
3591 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3592 nomem();
3593 for (int i = 1; i < ds_start; i++) {
3594 if ((ret = parseprop(props, argv[i])) != 0)
3595 goto error;
3598 ret = zfs_for_each(argc - ds_start, argv + ds_start, 0,
3599 ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, props);
3601 error:
3602 nvlist_free(props);
3603 return (ret);
3606 typedef struct snap_cbdata {
3607 nvlist_t *sd_nvl;
3608 boolean_t sd_recursive;
3609 const char *sd_snapname;
3610 } snap_cbdata_t;
3612 static int
3613 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
3615 snap_cbdata_t *sd = arg;
3616 char *name;
3617 int rv = 0;
3618 int error;
3620 if (sd->sd_recursive &&
3621 zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
3622 zfs_close(zhp);
3623 return (0);
3626 error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
3627 if (error == -1)
3628 nomem();
3629 fnvlist_add_boolean(sd->sd_nvl, name);
3630 free(name);
3632 if (sd->sd_recursive)
3633 rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
3634 zfs_close(zhp);
3635 return (rv);
3639 * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
3641 * Creates a snapshot with the given name. While functionally equivalent to
3642 * 'zfs create', it is a separate command to differentiate intent.
3644 static int
3645 zfs_do_snapshot(int argc, char **argv)
3647 int ret = 0;
3648 char c;
3649 nvlist_t *props;
3650 snap_cbdata_t sd = { 0 };
3651 boolean_t multiple_snaps = B_FALSE;
3653 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3654 nomem();
3655 if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
3656 nomem();
3658 /* check options */
3659 while ((c = getopt(argc, argv, "ro:")) != -1) {
3660 switch (c) {
3661 case 'o':
3662 if (parseprop(props, optarg) != 0)
3663 return (1);
3664 break;
3665 case 'r':
3666 sd.sd_recursive = B_TRUE;
3667 multiple_snaps = B_TRUE;
3668 break;
3669 case '?':
3670 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3671 optopt);
3672 goto usage;
3676 argc -= optind;
3677 argv += optind;
3679 /* check number of arguments */
3680 if (argc < 1) {
3681 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3682 goto usage;
3685 if (argc > 1)
3686 multiple_snaps = B_TRUE;
3687 for (; argc > 0; argc--, argv++) {
3688 char *atp;
3689 zfs_handle_t *zhp;
3691 atp = strchr(argv[0], '@');
3692 if (atp == NULL)
3693 goto usage;
3694 *atp = '\0';
3695 sd.sd_snapname = atp + 1;
3696 zhp = zfs_open(g_zfs, argv[0],
3697 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3698 if (zhp == NULL)
3699 goto usage;
3700 if (zfs_snapshot_cb(zhp, &sd) != 0)
3701 goto usage;
3704 ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
3705 nvlist_free(sd.sd_nvl);
3706 nvlist_free(props);
3707 if (ret != 0 && multiple_snaps)
3708 (void) fprintf(stderr, gettext("no snapshots were created\n"));
3709 return (ret != 0);
3711 usage:
3712 nvlist_free(sd.sd_nvl);
3713 nvlist_free(props);
3714 usage(B_FALSE);
3715 return (-1);
3719 * Send a backup stream to stdout.
3721 static int
3722 zfs_do_send(int argc, char **argv)
3724 char *fromname = NULL;
3725 char *toname = NULL;
3726 char *resume_token = NULL;
3727 char *cp;
3728 zfs_handle_t *zhp;
3729 sendflags_t flags = { 0 };
3730 int c, err;
3731 nvlist_t *dbgnv = NULL;
3732 boolean_t extraverbose = B_FALSE;
3734 struct option long_options[] = {
3735 {"replicate", no_argument, NULL, 'R'},
3736 {"props", no_argument, NULL, 'p'},
3737 {"parsable", no_argument, NULL, 'P'},
3738 {"dedup", no_argument, NULL, 'D'},
3739 {"verbose", no_argument, NULL, 'v'},
3740 {"dryrun", no_argument, NULL, 'n'},
3741 {"large-block", no_argument, NULL, 'L'},
3742 {"embed", no_argument, NULL, 'e'},
3743 {"resume", required_argument, NULL, 't'},
3744 {"compressed", no_argument, NULL, 'c'},
3745 {0, 0, 0, 0}
3748 /* check options */
3749 while ((c = getopt_long(argc, argv, ":i:I:RbDpvnPLet:c", long_options,
3750 NULL)) != -1) {
3751 switch (c) {
3752 case 'i':
3753 if (fromname)
3754 usage(B_FALSE);
3755 fromname = optarg;
3756 break;
3757 case 'I':
3758 if (fromname)
3759 usage(B_FALSE);
3760 fromname = optarg;
3761 flags.doall = B_TRUE;
3762 break;
3763 case 'R':
3764 flags.replicate = B_TRUE;
3765 break;
3766 case 'p':
3767 flags.props = B_TRUE;
3768 break;
3769 case 'P':
3770 flags.parsable = B_TRUE;
3771 flags.verbose = B_TRUE;
3772 break;
3773 case 'v':
3774 if (flags.verbose)
3775 extraverbose = B_TRUE;
3776 flags.verbose = B_TRUE;
3777 flags.progress = B_TRUE;
3778 break;
3779 case 'D':
3780 flags.dedup = B_TRUE;
3781 break;
3782 case 'n':
3783 flags.dryrun = B_TRUE;
3784 break;
3785 case 'L':
3786 flags.largeblock = B_TRUE;
3787 break;
3788 case 'e':
3789 flags.embed_data = B_TRUE;
3790 break;
3791 case 't':
3792 resume_token = optarg;
3793 break;
3794 case 'c':
3795 flags.compress = B_TRUE;
3796 break;
3797 case ':':
3799 * If a parameter was not passed, optopt contains the
3800 * value that would normally lead us into the
3801 * appropriate case statement. If it's > 256, then this
3802 * must be a longopt and we should look at argv to get
3803 * the string. Otherwise it's just the character, so we
3804 * should use it directly.
3806 if (optopt <= UINT8_MAX) {
3807 (void) fprintf(stderr,
3808 gettext("missing argument for '%c' "
3809 "option\n"), optopt);
3810 } else {
3811 (void) fprintf(stderr,
3812 gettext("missing argument for '%s' "
3813 "option\n"), argv[optind - 1]);
3815 usage(B_FALSE);
3816 break;
3817 case '?':
3818 /*FALLTHROUGH*/
3819 default:
3821 * If an invalid flag was passed, optopt contains the
3822 * character if it was a short flag, or 0 if it was a
3823 * longopt.
3825 if (optopt != 0) {
3826 (void) fprintf(stderr,
3827 gettext("invalid option '%c'\n"), optopt);
3828 } else {
3829 (void) fprintf(stderr,
3830 gettext("invalid option '%s'\n"),
3831 argv[optind - 1]);
3834 usage(B_FALSE);
3838 argc -= optind;
3839 argv += optind;
3841 if (resume_token != NULL) {
3842 if (fromname != NULL || flags.replicate || flags.props ||
3843 flags.dedup) {
3844 (void) fprintf(stderr,
3845 gettext("invalid flags combined with -t\n"));
3846 usage(B_FALSE);
3848 if (argc != 0) {
3849 (void) fprintf(stderr, gettext("no additional "
3850 "arguments are permitted with -t\n"));
3851 usage(B_FALSE);
3853 } else {
3854 if (argc < 1) {
3855 (void) fprintf(stderr,
3856 gettext("missing snapshot argument\n"));
3857 usage(B_FALSE);
3859 if (argc > 1) {
3860 (void) fprintf(stderr, gettext("too many arguments\n"));
3861 usage(B_FALSE);
3865 if (!flags.dryrun && isatty(STDOUT_FILENO)) {
3866 (void) fprintf(stderr,
3867 gettext("Error: Stream can not be written to a terminal.\n"
3868 "You must redirect standard output.\n"));
3869 return (1);
3872 if (resume_token != NULL) {
3873 return (zfs_send_resume(g_zfs, &flags, STDOUT_FILENO,
3874 resume_token));
3878 * Special case sending a filesystem, or from a bookmark.
3880 if (strchr(argv[0], '@') == NULL ||
3881 (fromname && strchr(fromname, '#') != NULL)) {
3882 char frombuf[ZFS_MAX_DATASET_NAME_LEN];
3883 enum lzc_send_flags lzc_flags = 0;
3885 if (flags.replicate || flags.doall || flags.props ||
3886 flags.dedup || flags.dryrun || flags.verbose ||
3887 flags.progress) {
3888 (void) fprintf(stderr,
3889 gettext("Error: "
3890 "Unsupported flag with filesystem or bookmark.\n"));
3891 return (1);
3894 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
3895 if (zhp == NULL)
3896 return (1);
3898 if (flags.largeblock)
3899 lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
3900 if (flags.embed_data)
3901 lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
3902 if (flags.compress)
3903 lzc_flags |= LZC_SEND_FLAG_COMPRESS;
3905 if (fromname != NULL &&
3906 (fromname[0] == '#' || fromname[0] == '@')) {
3908 * Incremental source name begins with # or @.
3909 * Default to same fs as target.
3911 (void) strncpy(frombuf, argv[0], sizeof (frombuf));
3912 cp = strchr(frombuf, '@');
3913 if (cp != NULL)
3914 *cp = '\0';
3915 (void) strlcat(frombuf, fromname, sizeof (frombuf));
3916 fromname = frombuf;
3918 err = zfs_send_one(zhp, fromname, STDOUT_FILENO, lzc_flags);
3919 zfs_close(zhp);
3920 return (err != 0);
3923 cp = strchr(argv[0], '@');
3924 *cp = '\0';
3925 toname = cp + 1;
3926 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3927 if (zhp == NULL)
3928 return (1);
3931 * If they specified the full path to the snapshot, chop off
3932 * everything except the short name of the snapshot, but special
3933 * case if they specify the origin.
3935 if (fromname && (cp = strchr(fromname, '@')) != NULL) {
3936 char origin[ZFS_MAX_DATASET_NAME_LEN];
3937 zprop_source_t src;
3939 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
3940 origin, sizeof (origin), &src, NULL, 0, B_FALSE);
3942 if (strcmp(origin, fromname) == 0) {
3943 fromname = NULL;
3944 flags.fromorigin = B_TRUE;
3945 } else {
3946 *cp = '\0';
3947 if (cp != fromname && strcmp(argv[0], fromname)) {
3948 (void) fprintf(stderr,
3949 gettext("incremental source must be "
3950 "in same filesystem\n"));
3951 usage(B_FALSE);
3953 fromname = cp + 1;
3954 if (strchr(fromname, '@') || strchr(fromname, '/')) {
3955 (void) fprintf(stderr,
3956 gettext("invalid incremental source\n"));
3957 usage(B_FALSE);
3962 if (flags.replicate && fromname == NULL)
3963 flags.doall = B_TRUE;
3965 err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
3966 extraverbose ? &dbgnv : NULL);
3968 if (extraverbose && dbgnv != NULL) {
3970 * dump_nvlist prints to stdout, but that's been
3971 * redirected to a file. Make it print to stderr
3972 * instead.
3974 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
3975 dump_nvlist(dbgnv, 0);
3976 nvlist_free(dbgnv);
3978 zfs_close(zhp);
3980 return (err != 0);
3984 * Restore a backup stream from stdin.
3986 static int
3987 zfs_do_receive(int argc, char **argv)
3989 int c, err = 0;
3990 recvflags_t flags = { 0 };
3991 boolean_t abort_resumable = B_FALSE;
3993 nvlist_t *props;
3994 nvpair_t *nvp = NULL;
3996 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3997 nomem();
3999 /* check options */
4000 while ((c = getopt(argc, argv, ":o:denuvFsA")) != -1) {
4001 switch (c) {
4002 case 'o':
4003 if (parseprop(props, optarg) != 0)
4004 return (1);
4005 break;
4006 case 'd':
4007 flags.isprefix = B_TRUE;
4008 break;
4009 case 'e':
4010 flags.isprefix = B_TRUE;
4011 flags.istail = B_TRUE;
4012 break;
4013 case 'n':
4014 flags.dryrun = B_TRUE;
4015 break;
4016 case 'u':
4017 flags.nomount = B_TRUE;
4018 break;
4019 case 'v':
4020 flags.verbose = B_TRUE;
4021 break;
4022 case 's':
4023 flags.resumable = B_TRUE;
4024 break;
4025 case 'F':
4026 flags.force = B_TRUE;
4027 break;
4028 case 'A':
4029 abort_resumable = B_TRUE;
4030 break;
4031 case ':':
4032 (void) fprintf(stderr, gettext("missing argument for "
4033 "'%c' option\n"), optopt);
4034 usage(B_FALSE);
4035 break;
4036 case '?':
4037 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4038 optopt);
4039 usage(B_FALSE);
4043 argc -= optind;
4044 argv += optind;
4046 /* check number of arguments */
4047 if (argc < 1) {
4048 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
4049 usage(B_FALSE);
4051 if (argc > 1) {
4052 (void) fprintf(stderr, gettext("too many arguments\n"));
4053 usage(B_FALSE);
4056 while ((nvp = nvlist_next_nvpair(props, nvp))) {
4057 if (strcmp(nvpair_name(nvp), "origin") != 0) {
4058 (void) fprintf(stderr, gettext("invalid option"));
4059 usage(B_FALSE);
4063 if (abort_resumable) {
4064 if (flags.isprefix || flags.istail || flags.dryrun ||
4065 flags.resumable || flags.nomount) {
4066 (void) fprintf(stderr, gettext("invalid option"));
4067 usage(B_FALSE);
4070 char namebuf[ZFS_MAX_DATASET_NAME_LEN];
4071 (void) snprintf(namebuf, sizeof (namebuf),
4072 "%s/%%recv", argv[0]);
4074 if (zfs_dataset_exists(g_zfs, namebuf,
4075 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) {
4076 zfs_handle_t *zhp = zfs_open(g_zfs,
4077 namebuf, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4078 if (zhp == NULL)
4079 return (1);
4080 err = zfs_destroy(zhp, B_FALSE);
4081 } else {
4082 zfs_handle_t *zhp = zfs_open(g_zfs,
4083 argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4084 if (zhp == NULL)
4085 usage(B_FALSE);
4086 if (!zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) ||
4087 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
4088 NULL, 0, NULL, NULL, 0, B_TRUE) == -1) {
4089 (void) fprintf(stderr,
4090 gettext("'%s' does not have any "
4091 "resumable receive state to abort\n"),
4092 argv[0]);
4093 return (1);
4095 err = zfs_destroy(zhp, B_FALSE);
4098 return (err != 0);
4101 if (isatty(STDIN_FILENO)) {
4102 (void) fprintf(stderr,
4103 gettext("Error: Backup stream can not be read "
4104 "from a terminal.\n"
4105 "You must redirect standard input.\n"));
4106 return (1);
4108 err = zfs_receive(g_zfs, argv[0], props, &flags, STDIN_FILENO, NULL);
4110 return (err != 0);
4114 * allow/unallow stuff
4116 /* copied from zfs/sys/dsl_deleg.h */
4117 #define ZFS_DELEG_PERM_CREATE "create"
4118 #define ZFS_DELEG_PERM_DESTROY "destroy"
4119 #define ZFS_DELEG_PERM_SNAPSHOT "snapshot"
4120 #define ZFS_DELEG_PERM_ROLLBACK "rollback"
4121 #define ZFS_DELEG_PERM_CLONE "clone"
4122 #define ZFS_DELEG_PERM_PROMOTE "promote"
4123 #define ZFS_DELEG_PERM_RENAME "rename"
4124 #define ZFS_DELEG_PERM_MOUNT "mount"
4125 #define ZFS_DELEG_PERM_SHARE "share"
4126 #define ZFS_DELEG_PERM_SEND "send"
4127 #define ZFS_DELEG_PERM_RECEIVE "receive"
4128 #define ZFS_DELEG_PERM_ALLOW "allow"
4129 #define ZFS_DELEG_PERM_USERPROP "userprop"
4130 #define ZFS_DELEG_PERM_VSCAN "vscan" /* ??? */
4131 #define ZFS_DELEG_PERM_USERQUOTA "userquota"
4132 #define ZFS_DELEG_PERM_GROUPQUOTA "groupquota"
4133 #define ZFS_DELEG_PERM_USERUSED "userused"
4134 #define ZFS_DELEG_PERM_GROUPUSED "groupused"
4135 #define ZFS_DELEG_PERM_HOLD "hold"
4136 #define ZFS_DELEG_PERM_RELEASE "release"
4137 #define ZFS_DELEG_PERM_DIFF "diff"
4138 #define ZFS_DELEG_PERM_BOOKMARK "bookmark"
4139 #define ZFS_DELEG_PERM_REMAP "remap"
4141 #define ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
4143 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
4144 { ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
4145 { ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
4146 { ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
4147 { ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
4148 { ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
4149 { ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
4150 { ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
4151 { ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
4152 { ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
4153 { ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
4154 { ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
4155 { ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
4156 { ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
4157 { ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
4158 { ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
4159 { ZFS_DELEG_PERM_BOOKMARK, ZFS_DELEG_NOTE_BOOKMARK },
4160 { ZFS_DELEG_PERM_REMAP, ZFS_DELEG_NOTE_REMAP },
4162 { ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
4163 { ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
4164 { ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
4165 { ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
4166 { ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
4167 { NULL, ZFS_DELEG_NOTE_NONE }
4170 /* permission structure */
4171 typedef struct deleg_perm {
4172 zfs_deleg_who_type_t dp_who_type;
4173 const char *dp_name;
4174 boolean_t dp_local;
4175 boolean_t dp_descend;
4176 } deleg_perm_t;
4178 /* */
4179 typedef struct deleg_perm_node {
4180 deleg_perm_t dpn_perm;
4182 uu_avl_node_t dpn_avl_node;
4183 } deleg_perm_node_t;
4185 typedef struct fs_perm fs_perm_t;
4187 /* permissions set */
4188 typedef struct who_perm {
4189 zfs_deleg_who_type_t who_type;
4190 const char *who_name; /* id */
4191 char who_ug_name[256]; /* user/group name */
4192 fs_perm_t *who_fsperm; /* uplink */
4194 uu_avl_t *who_deleg_perm_avl; /* permissions */
4195 } who_perm_t;
4197 /* */
4198 typedef struct who_perm_node {
4199 who_perm_t who_perm;
4200 uu_avl_node_t who_avl_node;
4201 } who_perm_node_t;
4203 typedef struct fs_perm_set fs_perm_set_t;
4204 /* fs permissions */
4205 struct fs_perm {
4206 const char *fsp_name;
4208 uu_avl_t *fsp_sc_avl; /* sets,create */
4209 uu_avl_t *fsp_uge_avl; /* user,group,everyone */
4211 fs_perm_set_t *fsp_set; /* uplink */
4214 /* */
4215 typedef struct fs_perm_node {
4216 fs_perm_t fspn_fsperm;
4217 uu_avl_t *fspn_avl;
4219 uu_list_node_t fspn_list_node;
4220 } fs_perm_node_t;
4222 /* top level structure */
4223 struct fs_perm_set {
4224 uu_list_pool_t *fsps_list_pool;
4225 uu_list_t *fsps_list; /* list of fs_perms */
4227 uu_avl_pool_t *fsps_named_set_avl_pool;
4228 uu_avl_pool_t *fsps_who_perm_avl_pool;
4229 uu_avl_pool_t *fsps_deleg_perm_avl_pool;
4232 static inline const char *
4233 deleg_perm_type(zfs_deleg_note_t note)
4235 /* subcommands */
4236 switch (note) {
4237 /* SUBCOMMANDS */
4238 /* OTHER */
4239 case ZFS_DELEG_NOTE_GROUPQUOTA:
4240 case ZFS_DELEG_NOTE_GROUPUSED:
4241 case ZFS_DELEG_NOTE_USERPROP:
4242 case ZFS_DELEG_NOTE_USERQUOTA:
4243 case ZFS_DELEG_NOTE_USERUSED:
4244 /* other */
4245 return (gettext("other"));
4246 default:
4247 return (gettext("subcommand"));
4251 static int
4252 who_type2weight(zfs_deleg_who_type_t who_type)
4254 int res;
4255 switch (who_type) {
4256 case ZFS_DELEG_NAMED_SET_SETS:
4257 case ZFS_DELEG_NAMED_SET:
4258 res = 0;
4259 break;
4260 case ZFS_DELEG_CREATE_SETS:
4261 case ZFS_DELEG_CREATE:
4262 res = 1;
4263 break;
4264 case ZFS_DELEG_USER_SETS:
4265 case ZFS_DELEG_USER:
4266 res = 2;
4267 break;
4268 case ZFS_DELEG_GROUP_SETS:
4269 case ZFS_DELEG_GROUP:
4270 res = 3;
4271 break;
4272 case ZFS_DELEG_EVERYONE_SETS:
4273 case ZFS_DELEG_EVERYONE:
4274 res = 4;
4275 break;
4276 default:
4277 res = -1;
4280 return (res);
4283 /* ARGSUSED */
4284 static int
4285 who_perm_compare(const void *larg, const void *rarg, void *unused)
4287 const who_perm_node_t *l = larg;
4288 const who_perm_node_t *r = rarg;
4289 zfs_deleg_who_type_t ltype = l->who_perm.who_type;
4290 zfs_deleg_who_type_t rtype = r->who_perm.who_type;
4291 int lweight = who_type2weight(ltype);
4292 int rweight = who_type2weight(rtype);
4293 int res = lweight - rweight;
4294 if (res == 0)
4295 res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
4296 ZFS_MAX_DELEG_NAME-1);
4298 if (res == 0)
4299 return (0);
4300 if (res > 0)
4301 return (1);
4302 else
4303 return (-1);
4306 /* ARGSUSED */
4307 static int
4308 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
4310 const deleg_perm_node_t *l = larg;
4311 const deleg_perm_node_t *r = rarg;
4312 int res = strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
4313 ZFS_MAX_DELEG_NAME-1);
4315 if (res == 0)
4316 return (0);
4318 if (res > 0)
4319 return (1);
4320 else
4321 return (-1);
4324 static inline void
4325 fs_perm_set_init(fs_perm_set_t *fspset)
4327 bzero(fspset, sizeof (fs_perm_set_t));
4329 if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
4330 sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
4331 NULL, UU_DEFAULT)) == NULL)
4332 nomem();
4333 if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
4334 UU_DEFAULT)) == NULL)
4335 nomem();
4337 if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
4338 "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
4339 who_perm_node_t, who_avl_node), who_perm_compare,
4340 UU_DEFAULT)) == NULL)
4341 nomem();
4343 if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
4344 "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
4345 who_perm_node_t, who_avl_node), who_perm_compare,
4346 UU_DEFAULT)) == NULL)
4347 nomem();
4349 if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
4350 "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
4351 deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
4352 == NULL)
4353 nomem();
4356 static inline void fs_perm_fini(fs_perm_t *);
4357 static inline void who_perm_fini(who_perm_t *);
4359 static inline void
4360 fs_perm_set_fini(fs_perm_set_t *fspset)
4362 fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
4364 while (node != NULL) {
4365 fs_perm_node_t *next_node =
4366 uu_list_next(fspset->fsps_list, node);
4367 fs_perm_t *fsperm = &node->fspn_fsperm;
4368 fs_perm_fini(fsperm);
4369 uu_list_remove(fspset->fsps_list, node);
4370 free(node);
4371 node = next_node;
4374 uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
4375 uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
4376 uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
4379 static inline void
4380 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
4381 const char *name)
4383 deleg_perm->dp_who_type = type;
4384 deleg_perm->dp_name = name;
4387 static inline void
4388 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
4389 zfs_deleg_who_type_t type, const char *name)
4391 uu_avl_pool_t *pool;
4392 pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
4394 bzero(who_perm, sizeof (who_perm_t));
4396 if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
4397 UU_DEFAULT)) == NULL)
4398 nomem();
4400 who_perm->who_type = type;
4401 who_perm->who_name = name;
4402 who_perm->who_fsperm = fsperm;
4405 static inline void
4406 who_perm_fini(who_perm_t *who_perm)
4408 deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
4410 while (node != NULL) {
4411 deleg_perm_node_t *next_node =
4412 uu_avl_next(who_perm->who_deleg_perm_avl, node);
4414 uu_avl_remove(who_perm->who_deleg_perm_avl, node);
4415 free(node);
4416 node = next_node;
4419 uu_avl_destroy(who_perm->who_deleg_perm_avl);
4422 static inline void
4423 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
4425 uu_avl_pool_t *nset_pool = fspset->fsps_named_set_avl_pool;
4426 uu_avl_pool_t *who_pool = fspset->fsps_who_perm_avl_pool;
4428 bzero(fsperm, sizeof (fs_perm_t));
4430 if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
4431 == NULL)
4432 nomem();
4434 if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
4435 == NULL)
4436 nomem();
4438 fsperm->fsp_set = fspset;
4439 fsperm->fsp_name = fsname;
4442 static inline void
4443 fs_perm_fini(fs_perm_t *fsperm)
4445 who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
4446 while (node != NULL) {
4447 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
4448 node);
4449 who_perm_t *who_perm = &node->who_perm;
4450 who_perm_fini(who_perm);
4451 uu_avl_remove(fsperm->fsp_sc_avl, node);
4452 free(node);
4453 node = next_node;
4456 node = uu_avl_first(fsperm->fsp_uge_avl);
4457 while (node != NULL) {
4458 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
4459 node);
4460 who_perm_t *who_perm = &node->who_perm;
4461 who_perm_fini(who_perm);
4462 uu_avl_remove(fsperm->fsp_uge_avl, node);
4463 free(node);
4464 node = next_node;
4467 uu_avl_destroy(fsperm->fsp_sc_avl);
4468 uu_avl_destroy(fsperm->fsp_uge_avl);
4471 static void
4472 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
4473 zfs_deleg_who_type_t who_type, const char *name, char locality)
4475 uu_avl_index_t idx = 0;
4477 deleg_perm_node_t *found_node = NULL;
4478 deleg_perm_t *deleg_perm = &node->dpn_perm;
4480 deleg_perm_init(deleg_perm, who_type, name);
4482 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4483 == NULL)
4484 uu_avl_insert(avl, node, idx);
4485 else {
4486 node = found_node;
4487 deleg_perm = &node->dpn_perm;
4491 switch (locality) {
4492 case ZFS_DELEG_LOCAL:
4493 deleg_perm->dp_local = B_TRUE;
4494 break;
4495 case ZFS_DELEG_DESCENDENT:
4496 deleg_perm->dp_descend = B_TRUE;
4497 break;
4498 case ZFS_DELEG_NA:
4499 break;
4500 default:
4501 assert(B_FALSE); /* invalid locality */
4505 static inline int
4506 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
4508 nvpair_t *nvp = NULL;
4509 fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
4510 uu_avl_t *avl = who_perm->who_deleg_perm_avl;
4511 zfs_deleg_who_type_t who_type = who_perm->who_type;
4513 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4514 const char *name = nvpair_name(nvp);
4515 data_type_t type = nvpair_type(nvp);
4516 uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
4517 deleg_perm_node_t *node =
4518 safe_malloc(sizeof (deleg_perm_node_t));
4520 assert(type == DATA_TYPE_BOOLEAN);
4522 uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
4523 set_deleg_perm_node(avl, node, who_type, name, locality);
4526 return (0);
4529 static inline int
4530 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
4532 nvpair_t *nvp = NULL;
4533 fs_perm_set_t *fspset = fsperm->fsp_set;
4535 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4536 nvlist_t *nvl2 = NULL;
4537 const char *name = nvpair_name(nvp);
4538 uu_avl_t *avl = NULL;
4539 uu_avl_pool_t *avl_pool = NULL;
4540 zfs_deleg_who_type_t perm_type = name[0];
4541 char perm_locality = name[1];
4542 const char *perm_name = name + 3;
4543 boolean_t is_set = B_TRUE;
4544 who_perm_t *who_perm = NULL;
4546 assert('$' == name[2]);
4548 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4549 return (-1);
4551 switch (perm_type) {
4552 case ZFS_DELEG_CREATE:
4553 case ZFS_DELEG_CREATE_SETS:
4554 case ZFS_DELEG_NAMED_SET:
4555 case ZFS_DELEG_NAMED_SET_SETS:
4556 avl_pool = fspset->fsps_named_set_avl_pool;
4557 avl = fsperm->fsp_sc_avl;
4558 break;
4559 case ZFS_DELEG_USER:
4560 case ZFS_DELEG_USER_SETS:
4561 case ZFS_DELEG_GROUP:
4562 case ZFS_DELEG_GROUP_SETS:
4563 case ZFS_DELEG_EVERYONE:
4564 case ZFS_DELEG_EVERYONE_SETS:
4565 avl_pool = fspset->fsps_who_perm_avl_pool;
4566 avl = fsperm->fsp_uge_avl;
4567 break;
4569 default:
4570 assert(!"unhandled zfs_deleg_who_type_t");
4573 if (is_set) {
4574 who_perm_node_t *found_node = NULL;
4575 who_perm_node_t *node = safe_malloc(
4576 sizeof (who_perm_node_t));
4577 who_perm = &node->who_perm;
4578 uu_avl_index_t idx = 0;
4580 uu_avl_node_init(node, &node->who_avl_node, avl_pool);
4581 who_perm_init(who_perm, fsperm, perm_type, perm_name);
4583 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4584 == NULL) {
4585 if (avl == fsperm->fsp_uge_avl) {
4586 uid_t rid = 0;
4587 struct passwd *p = NULL;
4588 struct group *g = NULL;
4589 const char *nice_name = NULL;
4591 switch (perm_type) {
4592 case ZFS_DELEG_USER_SETS:
4593 case ZFS_DELEG_USER:
4594 rid = atoi(perm_name);
4595 p = getpwuid(rid);
4596 if (p)
4597 nice_name = p->pw_name;
4598 break;
4599 case ZFS_DELEG_GROUP_SETS:
4600 case ZFS_DELEG_GROUP:
4601 rid = atoi(perm_name);
4602 g = getgrgid(rid);
4603 if (g)
4604 nice_name = g->gr_name;
4605 break;
4607 default:
4608 break;
4611 if (nice_name != NULL)
4612 (void) strlcpy(
4613 node->who_perm.who_ug_name,
4614 nice_name, 256);
4617 uu_avl_insert(avl, node, idx);
4618 } else {
4619 node = found_node;
4620 who_perm = &node->who_perm;
4624 (void) parse_who_perm(who_perm, nvl2, perm_locality);
4627 return (0);
4630 static inline int
4631 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
4633 nvpair_t *nvp = NULL;
4634 uu_avl_index_t idx = 0;
4636 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4637 nvlist_t *nvl2 = NULL;
4638 const char *fsname = nvpair_name(nvp);
4639 data_type_t type = nvpair_type(nvp);
4640 fs_perm_t *fsperm = NULL;
4641 fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
4642 if (node == NULL)
4643 nomem();
4645 fsperm = &node->fspn_fsperm;
4647 assert(DATA_TYPE_NVLIST == type);
4649 uu_list_node_init(node, &node->fspn_list_node,
4650 fspset->fsps_list_pool);
4652 idx = uu_list_numnodes(fspset->fsps_list);
4653 fs_perm_init(fsperm, fspset, fsname);
4655 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4656 return (-1);
4658 (void) parse_fs_perm(fsperm, nvl2);
4660 uu_list_insert(fspset->fsps_list, node, idx);
4663 return (0);
4666 static inline const char *
4667 deleg_perm_comment(zfs_deleg_note_t note)
4669 const char *str = "";
4671 /* subcommands */
4672 switch (note) {
4673 /* SUBCOMMANDS */
4674 case ZFS_DELEG_NOTE_ALLOW:
4675 str = gettext("Must also have the permission that is being"
4676 "\n\t\t\t\tallowed");
4677 break;
4678 case ZFS_DELEG_NOTE_CLONE:
4679 str = gettext("Must also have the 'create' ability and 'mount'"
4680 "\n\t\t\t\tability in the origin file system");
4681 break;
4682 case ZFS_DELEG_NOTE_CREATE:
4683 str = gettext("Must also have the 'mount' ability");
4684 break;
4685 case ZFS_DELEG_NOTE_DESTROY:
4686 str = gettext("Must also have the 'mount' ability");
4687 break;
4688 case ZFS_DELEG_NOTE_DIFF:
4689 str = gettext("Allows lookup of paths within a dataset;"
4690 "\n\t\t\t\tgiven an object number. Ordinary users need this"
4691 "\n\t\t\t\tin order to use zfs diff");
4692 break;
4693 case ZFS_DELEG_NOTE_HOLD:
4694 str = gettext("Allows adding a user hold to a snapshot");
4695 break;
4696 case ZFS_DELEG_NOTE_MOUNT:
4697 str = gettext("Allows mount/umount of ZFS datasets");
4698 break;
4699 case ZFS_DELEG_NOTE_PROMOTE:
4700 str = gettext("Must also have the 'mount'\n\t\t\t\tand"
4701 " 'promote' ability in the origin file system");
4702 break;
4703 case ZFS_DELEG_NOTE_RECEIVE:
4704 str = gettext("Must also have the 'mount' and 'create'"
4705 " ability");
4706 break;
4707 case ZFS_DELEG_NOTE_RELEASE:
4708 str = gettext("Allows releasing a user hold which\n\t\t\t\t"
4709 "might destroy the snapshot");
4710 break;
4711 case ZFS_DELEG_NOTE_RENAME:
4712 str = gettext("Must also have the 'mount' and 'create'"
4713 "\n\t\t\t\tability in the new parent");
4714 break;
4715 case ZFS_DELEG_NOTE_ROLLBACK:
4716 str = gettext("");
4717 break;
4718 case ZFS_DELEG_NOTE_SEND:
4719 str = gettext("");
4720 break;
4721 case ZFS_DELEG_NOTE_SHARE:
4722 str = gettext("Allows sharing file systems over NFS or SMB"
4723 "\n\t\t\t\tprotocols");
4724 break;
4725 case ZFS_DELEG_NOTE_SNAPSHOT:
4726 str = gettext("");
4727 break;
4729 * case ZFS_DELEG_NOTE_VSCAN:
4730 * str = gettext("");
4731 * break;
4733 /* OTHER */
4734 case ZFS_DELEG_NOTE_GROUPQUOTA:
4735 str = gettext("Allows accessing any groupquota@... property");
4736 break;
4737 case ZFS_DELEG_NOTE_GROUPUSED:
4738 str = gettext("Allows reading any groupused@... property");
4739 break;
4740 case ZFS_DELEG_NOTE_USERPROP:
4741 str = gettext("Allows changing any user property");
4742 break;
4743 case ZFS_DELEG_NOTE_USERQUOTA:
4744 str = gettext("Allows accessing any userquota@... property");
4745 break;
4746 case ZFS_DELEG_NOTE_USERUSED:
4747 str = gettext("Allows reading any userused@... property");
4748 break;
4749 /* other */
4750 default:
4751 str = "";
4754 return (str);
4757 struct allow_opts {
4758 boolean_t local;
4759 boolean_t descend;
4760 boolean_t user;
4761 boolean_t group;
4762 boolean_t everyone;
4763 boolean_t create;
4764 boolean_t set;
4765 boolean_t recursive; /* unallow only */
4766 boolean_t prt_usage;
4768 boolean_t prt_perms;
4769 char *who;
4770 char *perms;
4771 const char *dataset;
4774 static inline int
4775 prop_cmp(const void *a, const void *b)
4777 const char *str1 = *(const char **)a;
4778 const char *str2 = *(const char **)b;
4779 return (strcmp(str1, str2));
4782 static void
4783 allow_usage(boolean_t un, boolean_t requested, const char *msg)
4785 const char *opt_desc[] = {
4786 "-h", gettext("show this help message and exit"),
4787 "-l", gettext("set permission locally"),
4788 "-d", gettext("set permission for descents"),
4789 "-u", gettext("set permission for user"),
4790 "-g", gettext("set permission for group"),
4791 "-e", gettext("set permission for everyone"),
4792 "-c", gettext("set create time permission"),
4793 "-s", gettext("define permission set"),
4794 /* unallow only */
4795 "-r", gettext("remove permissions recursively"),
4797 size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
4798 size_t allow_size = unallow_size - 2;
4799 const char *props[ZFS_NUM_PROPS];
4800 int i;
4801 size_t count = 0;
4802 FILE *fp = requested ? stdout : stderr;
4803 zprop_desc_t *pdtbl = zfs_prop_get_table();
4804 const char *fmt = gettext("%-16s %-14s\t%s\n");
4806 (void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
4807 HELP_ALLOW));
4808 (void) fprintf(fp, gettext("Options:\n"));
4809 for (int i = 0; i < (un ? unallow_size : allow_size); i++) {
4810 const char *opt = opt_desc[i++];
4811 const char *optdsc = opt_desc[i];
4812 (void) fprintf(fp, gettext(" %-10s %s\n"), opt, optdsc);
4815 (void) fprintf(fp, gettext("\nThe following permissions are "
4816 "supported:\n\n"));
4817 (void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
4818 gettext("NOTES"));
4819 for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
4820 const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
4821 zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
4822 const char *perm_type = deleg_perm_type(perm_note);
4823 const char *perm_comment = deleg_perm_comment(perm_note);
4824 (void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
4827 for (i = 0; i < ZFS_NUM_PROPS; i++) {
4828 zprop_desc_t *pd = &pdtbl[i];
4829 if (pd->pd_visible != B_TRUE)
4830 continue;
4832 if (pd->pd_attr == PROP_READONLY)
4833 continue;
4835 props[count++] = pd->pd_name;
4837 props[count] = NULL;
4839 qsort(props, count, sizeof (char *), prop_cmp);
4841 for (i = 0; i < count; i++)
4842 (void) fprintf(fp, fmt, props[i], gettext("property"), "");
4844 if (msg != NULL)
4845 (void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
4847 exit(requested ? 0 : 2);
4850 static inline const char *
4851 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
4852 char **permsp)
4854 if (un && argc == expected_argc - 1)
4855 *permsp = NULL;
4856 else if (argc == expected_argc)
4857 *permsp = argv[argc - 2];
4858 else
4859 allow_usage(un, B_FALSE,
4860 gettext("wrong number of parameters\n"));
4862 return (argv[argc - 1]);
4865 static void
4866 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
4868 int uge_sum = opts->user + opts->group + opts->everyone;
4869 int csuge_sum = opts->create + opts->set + uge_sum;
4870 int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
4871 int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
4873 if (uge_sum > 1)
4874 allow_usage(un, B_FALSE,
4875 gettext("-u, -g, and -e are mutually exclusive\n"));
4877 if (opts->prt_usage) {
4878 if (argc == 0 && all_sum == 0)
4879 allow_usage(un, B_TRUE, NULL);
4880 else
4881 usage(B_FALSE);
4884 if (opts->set) {
4885 if (csuge_sum > 1)
4886 allow_usage(un, B_FALSE,
4887 gettext("invalid options combined with -s\n"));
4889 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4890 if (argv[0][0] != '@')
4891 allow_usage(un, B_FALSE,
4892 gettext("invalid set name: missing '@' prefix\n"));
4893 opts->who = argv[0];
4894 } else if (opts->create) {
4895 if (ldcsuge_sum > 1)
4896 allow_usage(un, B_FALSE,
4897 gettext("invalid options combined with -c\n"));
4898 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4899 } else if (opts->everyone) {
4900 if (csuge_sum > 1)
4901 allow_usage(un, B_FALSE,
4902 gettext("invalid options combined with -e\n"));
4903 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4904 } else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
4905 == 0) {
4906 opts->everyone = B_TRUE;
4907 argc--;
4908 argv++;
4909 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4910 } else if (argc == 1 && !un) {
4911 opts->prt_perms = B_TRUE;
4912 opts->dataset = argv[argc-1];
4913 } else {
4914 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4915 opts->who = argv[0];
4918 if (!opts->local && !opts->descend) {
4919 opts->local = B_TRUE;
4920 opts->descend = B_TRUE;
4924 static void
4925 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
4926 const char *who, char *perms, nvlist_t *top_nvl)
4928 int i;
4929 char ld[2] = { '\0', '\0' };
4930 char who_buf[MAXNAMELEN + 32];
4931 char base_type = '\0';
4932 char set_type = '\0';
4933 nvlist_t *base_nvl = NULL;
4934 nvlist_t *set_nvl = NULL;
4935 nvlist_t *nvl;
4937 if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
4938 nomem();
4939 if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) != 0)
4940 nomem();
4942 switch (type) {
4943 case ZFS_DELEG_NAMED_SET_SETS:
4944 case ZFS_DELEG_NAMED_SET:
4945 set_type = ZFS_DELEG_NAMED_SET_SETS;
4946 base_type = ZFS_DELEG_NAMED_SET;
4947 ld[0] = ZFS_DELEG_NA;
4948 break;
4949 case ZFS_DELEG_CREATE_SETS:
4950 case ZFS_DELEG_CREATE:
4951 set_type = ZFS_DELEG_CREATE_SETS;
4952 base_type = ZFS_DELEG_CREATE;
4953 ld[0] = ZFS_DELEG_NA;
4954 break;
4955 case ZFS_DELEG_USER_SETS:
4956 case ZFS_DELEG_USER:
4957 set_type = ZFS_DELEG_USER_SETS;
4958 base_type = ZFS_DELEG_USER;
4959 if (local)
4960 ld[0] = ZFS_DELEG_LOCAL;
4961 if (descend)
4962 ld[1] = ZFS_DELEG_DESCENDENT;
4963 break;
4964 case ZFS_DELEG_GROUP_SETS:
4965 case ZFS_DELEG_GROUP:
4966 set_type = ZFS_DELEG_GROUP_SETS;
4967 base_type = ZFS_DELEG_GROUP;
4968 if (local)
4969 ld[0] = ZFS_DELEG_LOCAL;
4970 if (descend)
4971 ld[1] = ZFS_DELEG_DESCENDENT;
4972 break;
4973 case ZFS_DELEG_EVERYONE_SETS:
4974 case ZFS_DELEG_EVERYONE:
4975 set_type = ZFS_DELEG_EVERYONE_SETS;
4976 base_type = ZFS_DELEG_EVERYONE;
4977 if (local)
4978 ld[0] = ZFS_DELEG_LOCAL;
4979 if (descend)
4980 ld[1] = ZFS_DELEG_DESCENDENT;
4981 break;
4983 default:
4984 assert(set_type != '\0' && base_type != '\0');
4987 if (perms != NULL) {
4988 char *curr = perms;
4989 char *end = curr + strlen(perms);
4991 while (curr < end) {
4992 char *delim = strchr(curr, ',');
4993 if (delim == NULL)
4994 delim = end;
4995 else
4996 *delim = '\0';
4998 if (curr[0] == '@')
4999 nvl = set_nvl;
5000 else
5001 nvl = base_nvl;
5003 (void) nvlist_add_boolean(nvl, curr);
5004 if (delim != end)
5005 *delim = ',';
5006 curr = delim + 1;
5009 for (i = 0; i < 2; i++) {
5010 char locality = ld[i];
5011 if (locality == 0)
5012 continue;
5014 if (!nvlist_empty(base_nvl)) {
5015 if (who != NULL)
5016 (void) snprintf(who_buf,
5017 sizeof (who_buf), "%c%c$%s",
5018 base_type, locality, who);
5019 else
5020 (void) snprintf(who_buf,
5021 sizeof (who_buf), "%c%c$",
5022 base_type, locality);
5024 (void) nvlist_add_nvlist(top_nvl, who_buf,
5025 base_nvl);
5029 if (!nvlist_empty(set_nvl)) {
5030 if (who != NULL)
5031 (void) snprintf(who_buf,
5032 sizeof (who_buf), "%c%c$%s",
5033 set_type, locality, who);
5034 else
5035 (void) snprintf(who_buf,
5036 sizeof (who_buf), "%c%c$",
5037 set_type, locality);
5039 (void) nvlist_add_nvlist(top_nvl, who_buf,
5040 set_nvl);
5043 } else {
5044 for (i = 0; i < 2; i++) {
5045 char locality = ld[i];
5046 if (locality == 0)
5047 continue;
5049 if (who != NULL)
5050 (void) snprintf(who_buf, sizeof (who_buf),
5051 "%c%c$%s", base_type, locality, who);
5052 else
5053 (void) snprintf(who_buf, sizeof (who_buf),
5054 "%c%c$", base_type, locality);
5055 (void) nvlist_add_boolean(top_nvl, who_buf);
5057 if (who != NULL)
5058 (void) snprintf(who_buf, sizeof (who_buf),
5059 "%c%c$%s", set_type, locality, who);
5060 else
5061 (void) snprintf(who_buf, sizeof (who_buf),
5062 "%c%c$", set_type, locality);
5063 (void) nvlist_add_boolean(top_nvl, who_buf);
5068 static int
5069 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
5071 if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
5072 nomem();
5074 if (opts->set) {
5075 store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
5076 opts->descend, opts->who, opts->perms, *nvlp);
5077 } else if (opts->create) {
5078 store_allow_perm(ZFS_DELEG_CREATE, opts->local,
5079 opts->descend, NULL, opts->perms, *nvlp);
5080 } else if (opts->everyone) {
5081 store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
5082 opts->descend, NULL, opts->perms, *nvlp);
5083 } else {
5084 char *curr = opts->who;
5085 char *end = curr + strlen(curr);
5087 while (curr < end) {
5088 const char *who;
5089 zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
5090 char *endch;
5091 char *delim = strchr(curr, ',');
5092 char errbuf[256];
5093 char id[64];
5094 struct passwd *p = NULL;
5095 struct group *g = NULL;
5097 uid_t rid;
5098 if (delim == NULL)
5099 delim = end;
5100 else
5101 *delim = '\0';
5103 rid = (uid_t)strtol(curr, &endch, 0);
5104 if (opts->user) {
5105 who_type = ZFS_DELEG_USER;
5106 if (*endch != '\0')
5107 p = getpwnam(curr);
5108 else
5109 p = getpwuid(rid);
5111 if (p != NULL)
5112 rid = p->pw_uid;
5113 else {
5114 (void) snprintf(errbuf, 256, gettext(
5115 "invalid user %s"), curr);
5116 allow_usage(un, B_TRUE, errbuf);
5118 } else if (opts->group) {
5119 who_type = ZFS_DELEG_GROUP;
5120 if (*endch != '\0')
5121 g = getgrnam(curr);
5122 else
5123 g = getgrgid(rid);
5125 if (g != NULL)
5126 rid = g->gr_gid;
5127 else {
5128 (void) snprintf(errbuf, 256, gettext(
5129 "invalid group %s"), curr);
5130 allow_usage(un, B_TRUE, errbuf);
5132 } else {
5133 if (*endch != '\0') {
5134 p = getpwnam(curr);
5135 } else {
5136 p = getpwuid(rid);
5139 if (p == NULL) {
5140 if (*endch != '\0') {
5141 g = getgrnam(curr);
5142 } else {
5143 g = getgrgid(rid);
5147 if (p != NULL) {
5148 who_type = ZFS_DELEG_USER;
5149 rid = p->pw_uid;
5150 } else if (g != NULL) {
5151 who_type = ZFS_DELEG_GROUP;
5152 rid = g->gr_gid;
5153 } else {
5154 (void) snprintf(errbuf, 256, gettext(
5155 "invalid user/group %s"), curr);
5156 allow_usage(un, B_TRUE, errbuf);
5160 (void) sprintf(id, "%u", rid);
5161 who = id;
5163 store_allow_perm(who_type, opts->local,
5164 opts->descend, who, opts->perms, *nvlp);
5165 curr = delim + 1;
5169 return (0);
5172 static void
5173 print_set_creat_perms(uu_avl_t *who_avl)
5175 const char *sc_title[] = {
5176 gettext("Permission sets:\n"),
5177 gettext("Create time permissions:\n"),
5178 NULL
5180 const char **title_ptr = sc_title;
5181 who_perm_node_t *who_node = NULL;
5182 int prev_weight = -1;
5184 for (who_node = uu_avl_first(who_avl); who_node != NULL;
5185 who_node = uu_avl_next(who_avl, who_node)) {
5186 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5187 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5188 const char *who_name = who_node->who_perm.who_name;
5189 int weight = who_type2weight(who_type);
5190 boolean_t first = B_TRUE;
5191 deleg_perm_node_t *deleg_node;
5193 if (prev_weight != weight) {
5194 (void) printf(*title_ptr++);
5195 prev_weight = weight;
5198 if (who_name == NULL || strnlen(who_name, 1) == 0)
5199 (void) printf("\t");
5200 else
5201 (void) printf("\t%s ", who_name);
5203 for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
5204 deleg_node = uu_avl_next(avl, deleg_node)) {
5205 if (first) {
5206 (void) printf("%s",
5207 deleg_node->dpn_perm.dp_name);
5208 first = B_FALSE;
5209 } else
5210 (void) printf(",%s",
5211 deleg_node->dpn_perm.dp_name);
5214 (void) printf("\n");
5218 static void
5219 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
5220 const char *title)
5222 who_perm_node_t *who_node = NULL;
5223 boolean_t prt_title = B_TRUE;
5224 uu_avl_walk_t *walk;
5226 if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
5227 nomem();
5229 while ((who_node = uu_avl_walk_next(walk)) != NULL) {
5230 const char *who_name = who_node->who_perm.who_name;
5231 const char *nice_who_name = who_node->who_perm.who_ug_name;
5232 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5233 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5234 char delim = ' ';
5235 deleg_perm_node_t *deleg_node;
5236 boolean_t prt_who = B_TRUE;
5238 for (deleg_node = uu_avl_first(avl);
5239 deleg_node != NULL;
5240 deleg_node = uu_avl_next(avl, deleg_node)) {
5241 if (local != deleg_node->dpn_perm.dp_local ||
5242 descend != deleg_node->dpn_perm.dp_descend)
5243 continue;
5245 if (prt_who) {
5246 const char *who = NULL;
5247 if (prt_title) {
5248 prt_title = B_FALSE;
5249 (void) printf(title);
5252 switch (who_type) {
5253 case ZFS_DELEG_USER_SETS:
5254 case ZFS_DELEG_USER:
5255 who = gettext("user");
5256 if (nice_who_name)
5257 who_name = nice_who_name;
5258 break;
5259 case ZFS_DELEG_GROUP_SETS:
5260 case ZFS_DELEG_GROUP:
5261 who = gettext("group");
5262 if (nice_who_name)
5263 who_name = nice_who_name;
5264 break;
5265 case ZFS_DELEG_EVERYONE_SETS:
5266 case ZFS_DELEG_EVERYONE:
5267 who = gettext("everyone");
5268 who_name = NULL;
5269 break;
5271 default:
5272 assert(who != NULL);
5275 prt_who = B_FALSE;
5276 if (who_name == NULL)
5277 (void) printf("\t%s", who);
5278 else
5279 (void) printf("\t%s %s", who, who_name);
5282 (void) printf("%c%s", delim,
5283 deleg_node->dpn_perm.dp_name);
5284 delim = ',';
5287 if (!prt_who)
5288 (void) printf("\n");
5291 uu_avl_walk_end(walk);
5294 static void
5295 print_fs_perms(fs_perm_set_t *fspset)
5297 fs_perm_node_t *node = NULL;
5298 char buf[MAXNAMELEN + 32];
5299 const char *dsname = buf;
5301 for (node = uu_list_first(fspset->fsps_list); node != NULL;
5302 node = uu_list_next(fspset->fsps_list, node)) {
5303 uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
5304 uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
5305 int left = 0;
5307 (void) snprintf(buf, sizeof (buf),
5308 gettext("---- Permissions on %s "),
5309 node->fspn_fsperm.fsp_name);
5310 (void) printf(dsname);
5311 left = 70 - strlen(buf);
5312 while (left-- > 0)
5313 (void) printf("-");
5314 (void) printf("\n");
5316 print_set_creat_perms(sc_avl);
5317 print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
5318 gettext("Local permissions:\n"));
5319 print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
5320 gettext("Descendent permissions:\n"));
5321 print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
5322 gettext("Local+Descendent permissions:\n"));
5326 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
5328 struct deleg_perms {
5329 boolean_t un;
5330 nvlist_t *nvl;
5333 static int
5334 set_deleg_perms(zfs_handle_t *zhp, void *data)
5336 struct deleg_perms *perms = (struct deleg_perms *)data;
5337 zfs_type_t zfs_type = zfs_get_type(zhp);
5339 if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
5340 return (0);
5342 return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
5345 static int
5346 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
5348 zfs_handle_t *zhp;
5349 nvlist_t *perm_nvl = NULL;
5350 nvlist_t *update_perm_nvl = NULL;
5351 int error = 1;
5352 int c;
5353 struct allow_opts opts = { 0 };
5355 const char *optstr = un ? "ldugecsrh" : "ldugecsh";
5357 /* check opts */
5358 while ((c = getopt(argc, argv, optstr)) != -1) {
5359 switch (c) {
5360 case 'l':
5361 opts.local = B_TRUE;
5362 break;
5363 case 'd':
5364 opts.descend = B_TRUE;
5365 break;
5366 case 'u':
5367 opts.user = B_TRUE;
5368 break;
5369 case 'g':
5370 opts.group = B_TRUE;
5371 break;
5372 case 'e':
5373 opts.everyone = B_TRUE;
5374 break;
5375 case 's':
5376 opts.set = B_TRUE;
5377 break;
5378 case 'c':
5379 opts.create = B_TRUE;
5380 break;
5381 case 'r':
5382 opts.recursive = B_TRUE;
5383 break;
5384 case ':':
5385 (void) fprintf(stderr, gettext("missing argument for "
5386 "'%c' option\n"), optopt);
5387 usage(B_FALSE);
5388 break;
5389 case 'h':
5390 opts.prt_usage = B_TRUE;
5391 break;
5392 case '?':
5393 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5394 optopt);
5395 usage(B_FALSE);
5399 argc -= optind;
5400 argv += optind;
5402 /* check arguments */
5403 parse_allow_args(argc, argv, un, &opts);
5405 /* try to open the dataset */
5406 if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
5407 ZFS_TYPE_VOLUME)) == NULL) {
5408 (void) fprintf(stderr, "Failed to open dataset: %s\n",
5409 opts.dataset);
5410 return (-1);
5413 if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
5414 goto cleanup2;
5416 fs_perm_set_init(&fs_perm_set);
5417 if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
5418 (void) fprintf(stderr, "Failed to parse fsacl permissions\n");
5419 goto cleanup1;
5422 if (opts.prt_perms)
5423 print_fs_perms(&fs_perm_set);
5424 else {
5425 (void) construct_fsacl_list(un, &opts, &update_perm_nvl);
5426 if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
5427 goto cleanup0;
5429 if (un && opts.recursive) {
5430 struct deleg_perms data = { un, update_perm_nvl };
5431 if (zfs_iter_filesystems(zhp, set_deleg_perms,
5432 &data) != 0)
5433 goto cleanup0;
5437 error = 0;
5439 cleanup0:
5440 nvlist_free(perm_nvl);
5441 nvlist_free(update_perm_nvl);
5442 cleanup1:
5443 fs_perm_set_fini(&fs_perm_set);
5444 cleanup2:
5445 zfs_close(zhp);
5447 return (error);
5450 static int
5451 zfs_do_allow(int argc, char **argv)
5453 return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
5456 static int
5457 zfs_do_unallow(int argc, char **argv)
5459 return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
5462 static int
5463 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
5465 int errors = 0;
5466 int i;
5467 const char *tag;
5468 boolean_t recursive = B_FALSE;
5469 const char *opts = holding ? "rt" : "r";
5470 int c;
5472 /* check options */
5473 while ((c = getopt(argc, argv, opts)) != -1) {
5474 switch (c) {
5475 case 'r':
5476 recursive = B_TRUE;
5477 break;
5478 case '?':
5479 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5480 optopt);
5481 usage(B_FALSE);
5485 argc -= optind;
5486 argv += optind;
5488 /* check number of arguments */
5489 if (argc < 2)
5490 usage(B_FALSE);
5492 tag = argv[0];
5493 --argc;
5494 ++argv;
5496 if (holding && tag[0] == '.') {
5497 /* tags starting with '.' are reserved for libzfs */
5498 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
5499 usage(B_FALSE);
5502 for (i = 0; i < argc; ++i) {
5503 zfs_handle_t *zhp;
5504 char parent[ZFS_MAX_DATASET_NAME_LEN];
5505 const char *delim;
5506 char *path = argv[i];
5508 delim = strchr(path, '@');
5509 if (delim == NULL) {
5510 (void) fprintf(stderr,
5511 gettext("'%s' is not a snapshot\n"), path);
5512 ++errors;
5513 continue;
5515 (void) strncpy(parent, path, delim - path);
5516 parent[delim - path] = '\0';
5518 zhp = zfs_open(g_zfs, parent,
5519 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5520 if (zhp == NULL) {
5521 ++errors;
5522 continue;
5524 if (holding) {
5525 if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
5526 ++errors;
5527 } else {
5528 if (zfs_release(zhp, delim+1, tag, recursive) != 0)
5529 ++errors;
5531 zfs_close(zhp);
5534 return (errors != 0);
5538 * zfs hold [-r] [-t] <tag> <snap> ...
5540 * -r Recursively hold
5542 * Apply a user-hold with the given tag to the list of snapshots.
5544 static int
5545 zfs_do_hold(int argc, char **argv)
5547 return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
5551 * zfs release [-r] <tag> <snap> ...
5553 * -r Recursively release
5555 * Release a user-hold with the given tag from the list of snapshots.
5557 static int
5558 zfs_do_release(int argc, char **argv)
5560 return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
5563 typedef struct holds_cbdata {
5564 boolean_t cb_recursive;
5565 const char *cb_snapname;
5566 nvlist_t **cb_nvlp;
5567 size_t cb_max_namelen;
5568 size_t cb_max_taglen;
5569 } holds_cbdata_t;
5571 #define STRFTIME_FMT_STR "%a %b %e %k:%M %Y"
5572 #define DATETIME_BUF_LEN (32)
5576 static void
5577 print_holds(boolean_t scripted, size_t nwidth, size_t tagwidth, nvlist_t *nvl)
5579 int i;
5580 nvpair_t *nvp = NULL;
5581 char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
5582 const char *col;
5584 if (!scripted) {
5585 for (i = 0; i < 3; i++) {
5586 col = gettext(hdr_cols[i]);
5587 if (i < 2)
5588 (void) printf("%-*s ", i ? tagwidth : nwidth,
5589 col);
5590 else
5591 (void) printf("%s\n", col);
5595 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5596 char *zname = nvpair_name(nvp);
5597 nvlist_t *nvl2;
5598 nvpair_t *nvp2 = NULL;
5599 (void) nvpair_value_nvlist(nvp, &nvl2);
5600 while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
5601 char tsbuf[DATETIME_BUF_LEN];
5602 char *tagname = nvpair_name(nvp2);
5603 uint64_t val = 0;
5604 time_t time;
5605 struct tm t;
5607 (void) nvpair_value_uint64(nvp2, &val);
5608 time = (time_t)val;
5609 (void) localtime_r(&time, &t);
5610 (void) strftime(tsbuf, DATETIME_BUF_LEN,
5611 gettext(STRFTIME_FMT_STR), &t);
5613 if (scripted) {
5614 (void) printf("%s\t%s\t%s\n", zname,
5615 tagname, tsbuf);
5616 } else {
5617 (void) printf("%-*s %-*s %s\n", nwidth,
5618 zname, tagwidth, tagname, tsbuf);
5625 * Generic callback function to list a dataset or snapshot.
5627 static int
5628 holds_callback(zfs_handle_t *zhp, void *data)
5630 holds_cbdata_t *cbp = data;
5631 nvlist_t *top_nvl = *cbp->cb_nvlp;
5632 nvlist_t *nvl = NULL;
5633 nvpair_t *nvp = NULL;
5634 const char *zname = zfs_get_name(zhp);
5635 size_t znamelen = strlen(zname);
5637 if (cbp->cb_recursive) {
5638 const char *snapname;
5639 char *delim = strchr(zname, '@');
5640 if (delim == NULL)
5641 return (0);
5643 snapname = delim + 1;
5644 if (strcmp(cbp->cb_snapname, snapname))
5645 return (0);
5648 if (zfs_get_holds(zhp, &nvl) != 0)
5649 return (-1);
5651 if (znamelen > cbp->cb_max_namelen)
5652 cbp->cb_max_namelen = znamelen;
5654 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5655 const char *tag = nvpair_name(nvp);
5656 size_t taglen = strlen(tag);
5657 if (taglen > cbp->cb_max_taglen)
5658 cbp->cb_max_taglen = taglen;
5661 return (nvlist_add_nvlist(top_nvl, zname, nvl));
5665 * zfs holds [-r] <snap> ...
5667 * -r Recursively hold
5669 static int
5670 zfs_do_holds(int argc, char **argv)
5672 int errors = 0;
5673 int c;
5674 int i;
5675 boolean_t scripted = B_FALSE;
5676 boolean_t recursive = B_FALSE;
5677 const char *opts = "rH";
5678 nvlist_t *nvl;
5680 int types = ZFS_TYPE_SNAPSHOT;
5681 holds_cbdata_t cb = { 0 };
5683 int limit = 0;
5684 int ret = 0;
5685 int flags = 0;
5687 /* check options */
5688 while ((c = getopt(argc, argv, opts)) != -1) {
5689 switch (c) {
5690 case 'r':
5691 recursive = B_TRUE;
5692 break;
5693 case 'H':
5694 scripted = B_TRUE;
5695 break;
5696 case '?':
5697 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5698 optopt);
5699 usage(B_FALSE);
5703 if (recursive) {
5704 types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
5705 flags |= ZFS_ITER_RECURSE;
5708 argc -= optind;
5709 argv += optind;
5711 /* check number of arguments */
5712 if (argc < 1)
5713 usage(B_FALSE);
5715 if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5716 nomem();
5718 for (i = 0; i < argc; ++i) {
5719 char *snapshot = argv[i];
5720 const char *delim;
5721 const char *snapname;
5723 delim = strchr(snapshot, '@');
5724 if (delim == NULL) {
5725 (void) fprintf(stderr,
5726 gettext("'%s' is not a snapshot\n"), snapshot);
5727 ++errors;
5728 continue;
5730 snapname = delim + 1;
5731 if (recursive)
5732 snapshot[delim - snapshot] = '\0';
5734 cb.cb_recursive = recursive;
5735 cb.cb_snapname = snapname;
5736 cb.cb_nvlp = &nvl;
5739 * 1. collect holds data, set format options
5741 ret = zfs_for_each(argc, argv, flags, types, NULL, NULL, limit,
5742 holds_callback, &cb);
5743 if (ret != 0)
5744 ++errors;
5748 * 2. print holds data
5750 print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl);
5752 if (nvlist_empty(nvl))
5753 (void) printf(gettext("no datasets available\n"));
5755 nvlist_free(nvl);
5757 return (0 != errors);
5760 #define CHECK_SPINNER 30
5761 #define SPINNER_TIME 3 /* seconds */
5762 #define MOUNT_TIME 1 /* seconds */
5764 typedef struct get_all_state {
5765 boolean_t ga_verbose;
5766 get_all_cb_t *ga_cbp;
5767 } get_all_state_t;
5769 static int
5770 get_one_dataset(zfs_handle_t *zhp, void *data)
5772 static char *spin[] = { "-", "\\", "|", "/" };
5773 static int spinval = 0;
5774 static int spincheck = 0;
5775 static time_t last_spin_time = (time_t)0;
5776 get_all_state_t *state = data;
5777 zfs_type_t type = zfs_get_type(zhp);
5779 if (state->ga_verbose) {
5780 if (--spincheck < 0) {
5781 time_t now = time(NULL);
5782 if (last_spin_time + SPINNER_TIME < now) {
5783 update_progress(spin[spinval++ % 4]);
5784 last_spin_time = now;
5786 spincheck = CHECK_SPINNER;
5791 * Interate over any nested datasets.
5793 if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
5794 zfs_close(zhp);
5795 return (1);
5799 * Skip any datasets whose type does not match.
5801 if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
5802 zfs_close(zhp);
5803 return (0);
5805 libzfs_add_handle(state->ga_cbp, zhp);
5806 assert(state->ga_cbp->cb_used <= state->ga_cbp->cb_alloc);
5808 return (0);
5811 static void
5812 get_all_datasets(get_all_cb_t *cbp, boolean_t verbose)
5814 get_all_state_t state = {
5815 .ga_verbose = verbose,
5816 .ga_cbp = cbp
5819 if (verbose)
5820 set_progress_header(gettext("Reading ZFS config"));
5821 (void) zfs_iter_root(g_zfs, get_one_dataset, &state);
5823 if (verbose)
5824 finish_progress(gettext("done."));
5828 * Generic callback for sharing or mounting filesystems. Because the code is so
5829 * similar, we have a common function with an extra parameter to determine which
5830 * mode we are using.
5832 typedef enum { OP_SHARE, OP_MOUNT } share_mount_op_t;
5834 typedef struct share_mount_state {
5835 share_mount_op_t sm_op;
5836 boolean_t sm_verbose;
5837 int sm_flags;
5838 char *sm_options;
5839 char *sm_proto; /* only valid for OP_SHARE */
5840 mutex_t sm_lock; /* protects the remaining fields */
5841 uint_t sm_total; /* number of filesystems to process */
5842 uint_t sm_done; /* number of filesystems processed */
5843 int sm_status; /* -1 if any of the share/mount operations failed */
5844 } share_mount_state_t;
5847 * Share or mount a dataset.
5849 static int
5850 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
5851 boolean_t explicit, const char *options)
5853 char mountpoint[ZFS_MAXPROPLEN];
5854 char shareopts[ZFS_MAXPROPLEN];
5855 char smbshareopts[ZFS_MAXPROPLEN];
5856 const char *cmdname = op == OP_SHARE ? "share" : "mount";
5857 struct mnttab mnt;
5858 uint64_t zoned, canmount;
5859 boolean_t shared_nfs, shared_smb;
5861 assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
5864 * Check to make sure we can mount/share this dataset. If we
5865 * are in the global zone and the filesystem is exported to a
5866 * local zone, or if we are in a local zone and the
5867 * filesystem is not exported, then it is an error.
5869 zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
5871 if (zoned && getzoneid() == GLOBAL_ZONEID) {
5872 if (!explicit)
5873 return (0);
5875 (void) fprintf(stderr, gettext("cannot %s '%s': "
5876 "dataset is exported to a local zone\n"), cmdname,
5877 zfs_get_name(zhp));
5878 return (1);
5880 } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
5881 if (!explicit)
5882 return (0);
5884 (void) fprintf(stderr, gettext("cannot %s '%s': "
5885 "permission denied\n"), cmdname,
5886 zfs_get_name(zhp));
5887 return (1);
5891 * Ignore any filesystems which don't apply to us. This
5892 * includes those with a legacy mountpoint, or those with
5893 * legacy share options.
5895 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
5896 sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
5897 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
5898 sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
5899 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
5900 sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
5902 if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
5903 strcmp(smbshareopts, "off") == 0) {
5904 if (!explicit)
5905 return (0);
5907 (void) fprintf(stderr, gettext("cannot share '%s': "
5908 "legacy share\n"), zfs_get_name(zhp));
5909 (void) fprintf(stderr, gettext("use share(8) to "
5910 "share this filesystem, or set "
5911 "sharenfs property on\n"));
5912 return (1);
5916 * We cannot share or mount legacy filesystems. If the
5917 * shareopts is non-legacy but the mountpoint is legacy, we
5918 * treat it as a legacy share.
5920 if (strcmp(mountpoint, "legacy") == 0) {
5921 if (!explicit)
5922 return (0);
5924 (void) fprintf(stderr, gettext("cannot %s '%s': "
5925 "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
5926 (void) fprintf(stderr, gettext("use %s(8) to "
5927 "%s this filesystem\n"), cmdname, cmdname);
5928 return (1);
5931 if (strcmp(mountpoint, "none") == 0) {
5932 if (!explicit)
5933 return (0);
5935 (void) fprintf(stderr, gettext("cannot %s '%s': no "
5936 "mountpoint set\n"), cmdname, zfs_get_name(zhp));
5937 return (1);
5941 * canmount explicit outcome
5942 * on no pass through
5943 * on yes pass through
5944 * off no return 0
5945 * off yes display error, return 1
5946 * noauto no return 0
5947 * noauto yes pass through
5949 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
5950 if (canmount == ZFS_CANMOUNT_OFF) {
5951 if (!explicit)
5952 return (0);
5954 (void) fprintf(stderr, gettext("cannot %s '%s': "
5955 "'canmount' property is set to 'off'\n"), cmdname,
5956 zfs_get_name(zhp));
5957 return (1);
5958 } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
5959 return (0);
5963 * If this filesystem is inconsistent and has a receive resume
5964 * token, we can not mount it.
5966 if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) &&
5967 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
5968 NULL, 0, NULL, NULL, 0, B_TRUE) == 0) {
5969 if (!explicit)
5970 return (0);
5972 (void) fprintf(stderr, gettext("cannot %s '%s': "
5973 "Contains partially-completed state from "
5974 "\"zfs receive -r\", which can be resumed with "
5975 "\"zfs send -t\"\n"),
5976 cmdname, zfs_get_name(zhp));
5977 return (1);
5981 * At this point, we have verified that the mountpoint and/or
5982 * shareopts are appropriate for auto management. If the
5983 * filesystem is already mounted or shared, return (failing
5984 * for explicit requests); otherwise mount or share the
5985 * filesystem.
5987 switch (op) {
5988 case OP_SHARE:
5990 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
5991 shared_smb = zfs_is_shared_smb(zhp, NULL);
5993 if ((shared_nfs && shared_smb) ||
5994 (shared_nfs && strcmp(shareopts, "on") == 0 &&
5995 strcmp(smbshareopts, "off") == 0) ||
5996 (shared_smb && strcmp(smbshareopts, "on") == 0 &&
5997 strcmp(shareopts, "off") == 0)) {
5998 if (!explicit)
5999 return (0);
6001 (void) fprintf(stderr, gettext("cannot share "
6002 "'%s': filesystem already shared\n"),
6003 zfs_get_name(zhp));
6004 return (1);
6007 if (!zfs_is_mounted(zhp, NULL) &&
6008 zfs_mount(zhp, NULL, 0) != 0)
6009 return (1);
6011 if (protocol == NULL) {
6012 if (zfs_shareall(zhp) != 0)
6013 return (1);
6014 } else if (strcmp(protocol, "nfs") == 0) {
6015 if (zfs_share_nfs(zhp))
6016 return (1);
6017 } else if (strcmp(protocol, "smb") == 0) {
6018 if (zfs_share_smb(zhp))
6019 return (1);
6020 } else {
6021 (void) fprintf(stderr, gettext("cannot share "
6022 "'%s': invalid share type '%s' "
6023 "specified\n"),
6024 zfs_get_name(zhp), protocol);
6025 return (1);
6028 break;
6030 case OP_MOUNT:
6031 if (options == NULL)
6032 mnt.mnt_mntopts = "";
6033 else
6034 mnt.mnt_mntopts = (char *)options;
6036 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
6037 zfs_is_mounted(zhp, NULL)) {
6038 if (!explicit)
6039 return (0);
6041 (void) fprintf(stderr, gettext("cannot mount "
6042 "'%s': filesystem already mounted\n"),
6043 zfs_get_name(zhp));
6044 return (1);
6047 if (zfs_mount(zhp, options, flags) != 0)
6048 return (1);
6049 break;
6052 return (0);
6056 * Reports progress in the form "(current/total)". Not thread-safe.
6058 static void
6059 report_mount_progress(int current, int total)
6061 static time_t last_progress_time = 0;
6062 time_t now = time(NULL);
6063 char info[32];
6065 /* report 1..n instead of 0..n-1 */
6066 ++current;
6068 /* display header if we're here for the first time */
6069 if (current == 1) {
6070 set_progress_header(gettext("Mounting ZFS filesystems"));
6071 } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
6072 /* too soon to report again */
6073 return;
6076 last_progress_time = now;
6078 (void) sprintf(info, "(%d/%d)", current, total);
6080 if (current == total)
6081 finish_progress(info);
6082 else
6083 update_progress(info);
6087 * zfs_foreach_mountpoint() callback that mounts or shares one filesystem and
6088 * updates the progress meter.
6090 static int
6091 share_mount_one_cb(zfs_handle_t *zhp, void *arg)
6093 share_mount_state_t *sms = arg;
6094 int ret;
6096 ret = share_mount_one(zhp, sms->sm_op, sms->sm_flags, sms->sm_proto,
6097 B_FALSE, sms->sm_options);
6099 mutex_enter(&sms->sm_lock);
6100 if (ret != 0)
6101 sms->sm_status = ret;
6102 sms->sm_done++;
6103 if (sms->sm_verbose)
6104 report_mount_progress(sms->sm_done, sms->sm_total);
6105 mutex_exit(&sms->sm_lock);
6106 return (ret);
6109 static void
6110 append_options(char *mntopts, char *newopts)
6112 int len = strlen(mntopts);
6114 /* original length plus new string to append plus 1 for the comma */
6115 if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
6116 (void) fprintf(stderr, gettext("the opts argument for "
6117 "'%c' option is too long (more than %d chars)\n"),
6118 "-o", MNT_LINE_MAX);
6119 usage(B_FALSE);
6122 if (*mntopts)
6123 mntopts[len++] = ',';
6125 (void) strcpy(&mntopts[len], newopts);
6128 static int
6129 share_mount(int op, int argc, char **argv)
6131 int do_all = 0;
6132 boolean_t verbose = B_FALSE;
6133 int c, ret = 0;
6134 char *options = NULL;
6135 int flags = 0;
6137 /* check options */
6138 while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
6139 != -1) {
6140 switch (c) {
6141 case 'a':
6142 do_all = 1;
6143 break;
6144 case 'v':
6145 verbose = B_TRUE;
6146 break;
6147 case 'o':
6148 if (*optarg == '\0') {
6149 (void) fprintf(stderr, gettext("empty mount "
6150 "options (-o) specified\n"));
6151 usage(B_FALSE);
6154 if (options == NULL)
6155 options = safe_malloc(MNT_LINE_MAX + 1);
6157 /* option validation is done later */
6158 append_options(options, optarg);
6159 break;
6161 case 'O':
6162 flags |= MS_OVERLAY;
6163 break;
6164 case ':':
6165 (void) fprintf(stderr, gettext("missing argument for "
6166 "'%c' option\n"), optopt);
6167 usage(B_FALSE);
6168 break;
6169 case '?':
6170 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6171 optopt);
6172 usage(B_FALSE);
6176 argc -= optind;
6177 argv += optind;
6179 /* check number of arguments */
6180 if (do_all) {
6181 char *protocol = NULL;
6183 if (op == OP_SHARE && argc > 0) {
6184 if (strcmp(argv[0], "nfs") != 0 &&
6185 strcmp(argv[0], "smb") != 0) {
6186 (void) fprintf(stderr, gettext("share type "
6187 "must be 'nfs' or 'smb'\n"));
6188 usage(B_FALSE);
6190 protocol = argv[0];
6191 argc--;
6192 argv++;
6195 if (argc != 0) {
6196 (void) fprintf(stderr, gettext("too many arguments\n"));
6197 usage(B_FALSE);
6200 start_progress_timer();
6201 get_all_cb_t cb = { 0 };
6202 get_all_datasets(&cb, verbose);
6204 if (cb.cb_used == 0)
6205 return (0);
6207 if (op == OP_SHARE) {
6208 sa_init_selective_arg_t sharearg;
6209 sharearg.zhandle_arr = cb.cb_handles;
6210 sharearg.zhandle_len = cb.cb_used;
6211 if ((ret = zfs_init_libshare_arg(g_zfs,
6212 SA_INIT_SHARE_API_SELECTIVE, &sharearg)) != SA_OK) {
6213 (void) fprintf(stderr, gettext(
6214 "Could not initialize libshare, %d"), ret);
6215 return (ret);
6219 share_mount_state_t share_mount_state = { 0 };
6220 share_mount_state.sm_op = op;
6221 share_mount_state.sm_verbose = verbose;
6222 share_mount_state.sm_flags = flags;
6223 share_mount_state.sm_options = options;
6224 share_mount_state.sm_proto = protocol;
6225 share_mount_state.sm_total = cb.cb_used;
6226 (void) mutex_init(&share_mount_state.sm_lock,
6227 LOCK_NORMAL | LOCK_ERRORCHECK, NULL);
6229 * libshare isn't mt-safe, so only do the operation in parallel
6230 * if we're mounting.
6232 zfs_foreach_mountpoint(g_zfs, cb.cb_handles, cb.cb_used,
6233 share_mount_one_cb, &share_mount_state, op == OP_MOUNT);
6234 ret = share_mount_state.sm_status;
6236 for (int i = 0; i < cb.cb_used; i++)
6237 zfs_close(cb.cb_handles[i]);
6238 free(cb.cb_handles);
6239 } else if (argc == 0) {
6240 struct mnttab entry;
6242 if ((op == OP_SHARE) || (options != NULL)) {
6243 (void) fprintf(stderr, gettext("missing filesystem "
6244 "argument (specify -a for all)\n"));
6245 usage(B_FALSE);
6249 * When mount is given no arguments, go through /etc/mnttab and
6250 * display any active ZFS mounts. We hide any snapshots, since
6251 * they are controlled automatically.
6253 rewind(mnttab_file);
6254 while (getmntent(mnttab_file, &entry) == 0) {
6255 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
6256 strchr(entry.mnt_special, '@') != NULL)
6257 continue;
6259 (void) printf("%-30s %s\n", entry.mnt_special,
6260 entry.mnt_mountp);
6263 } else {
6264 zfs_handle_t *zhp;
6266 if (argc > 1) {
6267 (void) fprintf(stderr,
6268 gettext("too many arguments\n"));
6269 usage(B_FALSE);
6272 if ((zhp = zfs_open(g_zfs, argv[0],
6273 ZFS_TYPE_FILESYSTEM)) == NULL) {
6274 ret = 1;
6275 } else {
6276 ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
6277 options);
6278 zfs_close(zhp);
6282 return (ret);
6286 * zfs mount -a [nfs]
6287 * zfs mount filesystem
6289 * Mount all filesystems, or mount the given filesystem.
6291 static int
6292 zfs_do_mount(int argc, char **argv)
6294 return (share_mount(OP_MOUNT, argc, argv));
6298 * zfs share -a [nfs | smb]
6299 * zfs share filesystem
6301 * Share all filesystems, or share the given filesystem.
6303 static int
6304 zfs_do_share(int argc, char **argv)
6306 return (share_mount(OP_SHARE, argc, argv));
6309 typedef struct unshare_unmount_node {
6310 zfs_handle_t *un_zhp;
6311 char *un_mountp;
6312 uu_avl_node_t un_avlnode;
6313 } unshare_unmount_node_t;
6315 /* ARGSUSED */
6316 static int
6317 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
6319 const unshare_unmount_node_t *l = larg;
6320 const unshare_unmount_node_t *r = rarg;
6322 return (strcmp(l->un_mountp, r->un_mountp));
6326 * Convenience routine used by zfs_do_umount() and manual_unmount(). Given an
6327 * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
6328 * and unmount it appropriately.
6330 static int
6331 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
6333 zfs_handle_t *zhp;
6334 int ret = 0;
6335 struct stat64 statbuf;
6336 struct extmnttab entry;
6337 const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
6338 ino_t path_inode;
6341 * Search for the path in /etc/mnttab. Rather than looking for the
6342 * specific path, which can be fooled by non-standard paths (i.e. ".."
6343 * or "//"), we stat() the path and search for the corresponding
6344 * (major,minor) device pair.
6346 if (stat64(path, &statbuf) != 0) {
6347 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6348 cmdname, path, strerror(errno));
6349 return (1);
6351 path_inode = statbuf.st_ino;
6354 * Search for the given (major,minor) pair in the mount table.
6356 rewind(mnttab_file);
6357 while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
6358 if (entry.mnt_major == major(statbuf.st_dev) &&
6359 entry.mnt_minor == minor(statbuf.st_dev))
6360 break;
6362 if (ret != 0) {
6363 if (op == OP_SHARE) {
6364 (void) fprintf(stderr, gettext("cannot %s '%s': not "
6365 "currently mounted\n"), cmdname, path);
6366 return (1);
6368 (void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
6369 path);
6370 if ((ret = umount2(path, flags)) != 0)
6371 (void) fprintf(stderr, gettext("%s: %s\n"), path,
6372 strerror(errno));
6373 return (ret != 0);
6376 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
6377 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
6378 "filesystem\n"), cmdname, path);
6379 return (1);
6382 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6383 ZFS_TYPE_FILESYSTEM)) == NULL)
6384 return (1);
6386 ret = 1;
6387 if (stat64(entry.mnt_mountp, &statbuf) != 0) {
6388 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6389 cmdname, path, strerror(errno));
6390 goto out;
6391 } else if (statbuf.st_ino != path_inode) {
6392 (void) fprintf(stderr, gettext("cannot "
6393 "%s '%s': not a mountpoint\n"), cmdname, path);
6394 goto out;
6397 if (op == OP_SHARE) {
6398 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6399 char smbshare_prop[ZFS_MAXPROPLEN];
6401 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
6402 sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
6403 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
6404 sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
6406 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6407 strcmp(smbshare_prop, "off") == 0) {
6408 (void) fprintf(stderr, gettext("cannot unshare "
6409 "'%s': legacy share\n"), path);
6410 (void) fprintf(stderr, gettext("use "
6411 "unshare(8) to unshare this filesystem\n"));
6412 } else if (!zfs_is_shared(zhp)) {
6413 (void) fprintf(stderr, gettext("cannot unshare '%s': "
6414 "not currently shared\n"), path);
6415 } else {
6416 ret = zfs_unshareall_bypath(zhp, path);
6418 } else {
6419 char mtpt_prop[ZFS_MAXPROPLEN];
6421 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
6422 sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
6424 if (is_manual) {
6425 ret = zfs_unmount(zhp, NULL, flags);
6426 } else if (strcmp(mtpt_prop, "legacy") == 0) {
6427 (void) fprintf(stderr, gettext("cannot unmount "
6428 "'%s': legacy mountpoint\n"),
6429 zfs_get_name(zhp));
6430 (void) fprintf(stderr, gettext("use umount(8) "
6431 "to unmount this filesystem\n"));
6432 } else {
6433 ret = zfs_unmountall(zhp, flags);
6437 out:
6438 zfs_close(zhp);
6440 return (ret != 0);
6444 * Generic callback for unsharing or unmounting a filesystem.
6446 static int
6447 unshare_unmount(int op, int argc, char **argv)
6449 int do_all = 0;
6450 int flags = 0;
6451 int ret = 0;
6452 int c;
6453 zfs_handle_t *zhp;
6454 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6455 char sharesmb[ZFS_MAXPROPLEN];
6457 /* check options */
6458 while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
6459 switch (c) {
6460 case 'a':
6461 do_all = 1;
6462 break;
6463 case 'f':
6464 flags = MS_FORCE;
6465 break;
6466 case '?':
6467 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6468 optopt);
6469 usage(B_FALSE);
6473 argc -= optind;
6474 argv += optind;
6476 if (do_all) {
6478 * We could make use of zfs_for_each() to walk all datasets in
6479 * the system, but this would be very inefficient, especially
6480 * since we would have to linearly search /etc/mnttab for each
6481 * one. Instead, do one pass through /etc/mnttab looking for
6482 * zfs entries and call zfs_unmount() for each one.
6484 * Things get a little tricky if the administrator has created
6485 * mountpoints beneath other ZFS filesystems. In this case, we
6486 * have to unmount the deepest filesystems first. To accomplish
6487 * this, we place all the mountpoints in an AVL tree sorted by
6488 * the special type (dataset name), and walk the result in
6489 * reverse to make sure to get any snapshots first.
6491 struct mnttab entry;
6492 uu_avl_pool_t *pool;
6493 uu_avl_t *tree = NULL;
6494 unshare_unmount_node_t *node;
6495 uu_avl_index_t idx;
6496 uu_avl_walk_t *walk;
6498 if (argc != 0) {
6499 (void) fprintf(stderr, gettext("too many arguments\n"));
6500 usage(B_FALSE);
6503 if (((pool = uu_avl_pool_create("unmount_pool",
6504 sizeof (unshare_unmount_node_t),
6505 offsetof(unshare_unmount_node_t, un_avlnode),
6506 unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
6507 ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
6508 nomem();
6510 rewind(mnttab_file);
6511 while (getmntent(mnttab_file, &entry) == 0) {
6513 /* ignore non-ZFS entries */
6514 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
6515 continue;
6517 /* ignore snapshots */
6518 if (strchr(entry.mnt_special, '@') != NULL)
6519 continue;
6521 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6522 ZFS_TYPE_FILESYSTEM)) == NULL) {
6523 ret = 1;
6524 continue;
6528 * Ignore datasets that are excluded/restricted by
6529 * parent pool name.
6531 if (zpool_skip_pool(zfs_get_pool_name(zhp))) {
6532 zfs_close(zhp);
6533 continue;
6536 switch (op) {
6537 case OP_SHARE:
6538 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6539 nfs_mnt_prop,
6540 sizeof (nfs_mnt_prop),
6541 NULL, NULL, 0, B_FALSE) == 0);
6542 if (strcmp(nfs_mnt_prop, "off") != 0)
6543 break;
6544 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6545 nfs_mnt_prop,
6546 sizeof (nfs_mnt_prop),
6547 NULL, NULL, 0, B_FALSE) == 0);
6548 if (strcmp(nfs_mnt_prop, "off") == 0)
6549 continue;
6550 break;
6551 case OP_MOUNT:
6552 /* Ignore legacy mounts */
6553 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
6554 nfs_mnt_prop,
6555 sizeof (nfs_mnt_prop),
6556 NULL, NULL, 0, B_FALSE) == 0);
6557 if (strcmp(nfs_mnt_prop, "legacy") == 0)
6558 continue;
6559 /* Ignore canmount=noauto mounts */
6560 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
6561 ZFS_CANMOUNT_NOAUTO)
6562 continue;
6563 default:
6564 break;
6567 node = safe_malloc(sizeof (unshare_unmount_node_t));
6568 node->un_zhp = zhp;
6569 node->un_mountp = safe_strdup(entry.mnt_mountp);
6571 uu_avl_node_init(node, &node->un_avlnode, pool);
6573 if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
6574 uu_avl_insert(tree, node, idx);
6575 } else {
6576 zfs_close(node->un_zhp);
6577 free(node->un_mountp);
6578 free(node);
6583 * Walk the AVL tree in reverse, unmounting each filesystem and
6584 * removing it from the AVL tree in the process.
6586 if ((walk = uu_avl_walk_start(tree,
6587 UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
6588 nomem();
6590 while ((node = uu_avl_walk_next(walk)) != NULL) {
6591 uu_avl_remove(tree, node);
6593 switch (op) {
6594 case OP_SHARE:
6595 if (zfs_unshareall_bypath(node->un_zhp,
6596 node->un_mountp) != 0)
6597 ret = 1;
6598 break;
6600 case OP_MOUNT:
6601 if (zfs_unmount(node->un_zhp,
6602 node->un_mountp, flags) != 0)
6603 ret = 1;
6604 break;
6607 zfs_close(node->un_zhp);
6608 free(node->un_mountp);
6609 free(node);
6612 uu_avl_walk_end(walk);
6613 uu_avl_destroy(tree);
6614 uu_avl_pool_destroy(pool);
6616 } else {
6617 if (argc != 1) {
6618 if (argc == 0)
6619 (void) fprintf(stderr,
6620 gettext("missing filesystem argument\n"));
6621 else
6622 (void) fprintf(stderr,
6623 gettext("too many arguments\n"));
6624 usage(B_FALSE);
6628 * We have an argument, but it may be a full path or a ZFS
6629 * filesystem. Pass full paths off to unmount_path() (shared by
6630 * manual_unmount), otherwise open the filesystem and pass to
6631 * zfs_unmount().
6633 if (argv[0][0] == '/')
6634 return (unshare_unmount_path(op, argv[0],
6635 flags, B_FALSE));
6637 if ((zhp = zfs_open(g_zfs, argv[0],
6638 ZFS_TYPE_FILESYSTEM)) == NULL)
6639 return (1);
6641 verify(zfs_prop_get(zhp, op == OP_SHARE ?
6642 ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
6643 nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
6644 NULL, 0, B_FALSE) == 0);
6646 switch (op) {
6647 case OP_SHARE:
6648 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6649 nfs_mnt_prop,
6650 sizeof (nfs_mnt_prop),
6651 NULL, NULL, 0, B_FALSE) == 0);
6652 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6653 sharesmb, sizeof (sharesmb), NULL, NULL,
6654 0, B_FALSE) == 0);
6656 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6657 strcmp(sharesmb, "off") == 0) {
6658 (void) fprintf(stderr, gettext("cannot "
6659 "unshare '%s': legacy share\n"),
6660 zfs_get_name(zhp));
6661 (void) fprintf(stderr, gettext("use "
6662 "unshare(8) to unshare this "
6663 "filesystem\n"));
6664 ret = 1;
6665 } else if (!zfs_is_shared(zhp)) {
6666 (void) fprintf(stderr, gettext("cannot "
6667 "unshare '%s': not currently "
6668 "shared\n"), zfs_get_name(zhp));
6669 ret = 1;
6670 } else if (zfs_unshareall(zhp) != 0) {
6671 ret = 1;
6673 break;
6675 case OP_MOUNT:
6676 if (strcmp(nfs_mnt_prop, "legacy") == 0) {
6677 (void) fprintf(stderr, gettext("cannot "
6678 "unmount '%s': legacy "
6679 "mountpoint\n"), zfs_get_name(zhp));
6680 (void) fprintf(stderr, gettext("use "
6681 "umount(8) to unmount this "
6682 "filesystem\n"));
6683 ret = 1;
6684 } else if (!zfs_is_mounted(zhp, NULL)) {
6685 (void) fprintf(stderr, gettext("cannot "
6686 "unmount '%s': not currently "
6687 "mounted\n"),
6688 zfs_get_name(zhp));
6689 ret = 1;
6690 } else if (zfs_unmountall(zhp, flags) != 0) {
6691 ret = 1;
6693 break;
6696 zfs_close(zhp);
6699 return (ret);
6703 * zfs unmount -a
6704 * zfs unmount filesystem
6706 * Unmount all filesystems, or a specific ZFS filesystem.
6708 static int
6709 zfs_do_unmount(int argc, char **argv)
6711 return (unshare_unmount(OP_MOUNT, argc, argv));
6715 * zfs unshare -a
6716 * zfs unshare filesystem
6718 * Unshare all filesystems, or a specific ZFS filesystem.
6720 static int
6721 zfs_do_unshare(int argc, char **argv)
6723 return (unshare_unmount(OP_SHARE, argc, argv));
6727 * Called when invoked as /etc/fs/zfs/mount. Do the mount if the mountpoint is
6728 * 'legacy'. Otherwise, complain that use should be using 'zfs mount'.
6730 static int
6731 manual_mount(int argc, char **argv)
6733 zfs_handle_t *zhp;
6734 char mountpoint[ZFS_MAXPROPLEN];
6735 char mntopts[MNT_LINE_MAX] = { '\0' };
6736 int ret = 0;
6737 int c;
6738 int flags = 0;
6739 char *dataset, *path;
6741 /* check options */
6742 while ((c = getopt(argc, argv, ":mo:O")) != -1) {
6743 switch (c) {
6744 case 'o':
6745 (void) strlcpy(mntopts, optarg, sizeof (mntopts));
6746 break;
6747 case 'O':
6748 flags |= MS_OVERLAY;
6749 break;
6750 case 'm':
6751 flags |= MS_NOMNTTAB;
6752 break;
6753 case ':':
6754 (void) fprintf(stderr, gettext("missing argument for "
6755 "'%c' option\n"), optopt);
6756 usage(B_FALSE);
6757 break;
6758 case '?':
6759 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6760 optopt);
6761 (void) fprintf(stderr, gettext("usage: mount [-o opts] "
6762 "<path>\n"));
6763 return (2);
6767 argc -= optind;
6768 argv += optind;
6770 /* check that we only have two arguments */
6771 if (argc != 2) {
6772 if (argc == 0)
6773 (void) fprintf(stderr, gettext("missing dataset "
6774 "argument\n"));
6775 else if (argc == 1)
6776 (void) fprintf(stderr,
6777 gettext("missing mountpoint argument\n"));
6778 else
6779 (void) fprintf(stderr, gettext("too many arguments\n"));
6780 (void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
6781 return (2);
6784 dataset = argv[0];
6785 path = argv[1];
6787 /* try to open the dataset */
6788 if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
6789 return (1);
6791 (void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
6792 sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
6794 /* check for legacy mountpoint and complain appropriately */
6795 ret = 0;
6796 if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
6797 if (mount(dataset, path, MS_OPTIONSTR | flags, MNTTYPE_ZFS,
6798 NULL, 0, mntopts, sizeof (mntopts)) != 0) {
6799 (void) fprintf(stderr, gettext("mount failed: %s\n"),
6800 strerror(errno));
6801 ret = 1;
6803 } else {
6804 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
6805 "mounted using 'mount -F zfs'\n"), dataset);
6806 (void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
6807 "instead.\n"), path);
6808 (void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
6809 "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
6810 (void) fprintf(stderr, gettext("See zfs(8) for more "
6811 "information.\n"));
6812 ret = 1;
6815 return (ret);
6819 * Called when invoked as /etc/fs/zfs/umount. Unlike a manual mount, we allow
6820 * unmounts of non-legacy filesystems, as this is the dominant administrative
6821 * interface.
6823 static int
6824 manual_unmount(int argc, char **argv)
6826 int flags = 0;
6827 int c;
6829 /* check options */
6830 while ((c = getopt(argc, argv, "f")) != -1) {
6831 switch (c) {
6832 case 'f':
6833 flags = MS_FORCE;
6834 break;
6835 case '?':
6836 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6837 optopt);
6838 (void) fprintf(stderr, gettext("usage: unmount [-f] "
6839 "<path>\n"));
6840 return (2);
6844 argc -= optind;
6845 argv += optind;
6847 /* check arguments */
6848 if (argc != 1) {
6849 if (argc == 0)
6850 (void) fprintf(stderr, gettext("missing path "
6851 "argument\n"));
6852 else
6853 (void) fprintf(stderr, gettext("too many arguments\n"));
6854 (void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
6855 return (2);
6858 return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
6861 static int
6862 find_command_idx(char *command, int *idx)
6864 int i;
6866 for (i = 0; i < NCOMMAND; i++) {
6867 if (command_table[i].name == NULL)
6868 continue;
6870 if (strcmp(command, command_table[i].name) == 0) {
6871 *idx = i;
6872 return (0);
6875 return (1);
6878 static int
6879 zfs_do_diff(int argc, char **argv)
6881 zfs_handle_t *zhp;
6882 int flags = 0;
6883 char *tosnap = NULL;
6884 char *fromsnap = NULL;
6885 char *atp, *copy;
6886 int err = 0;
6887 int c;
6889 while ((c = getopt(argc, argv, "FHt")) != -1) {
6890 switch (c) {
6891 case 'F':
6892 flags |= ZFS_DIFF_CLASSIFY;
6893 break;
6894 case 'H':
6895 flags |= ZFS_DIFF_PARSEABLE;
6896 break;
6897 case 't':
6898 flags |= ZFS_DIFF_TIMESTAMP;
6899 break;
6900 default:
6901 (void) fprintf(stderr,
6902 gettext("invalid option '%c'\n"), optopt);
6903 usage(B_FALSE);
6907 argc -= optind;
6908 argv += optind;
6910 if (argc < 1) {
6911 (void) fprintf(stderr,
6912 gettext("must provide at least one snapshot name\n"));
6913 usage(B_FALSE);
6916 if (argc > 2) {
6917 (void) fprintf(stderr, gettext("too many arguments\n"));
6918 usage(B_FALSE);
6921 fromsnap = argv[0];
6922 tosnap = (argc == 2) ? argv[1] : NULL;
6924 copy = NULL;
6925 if (*fromsnap != '@')
6926 copy = strdup(fromsnap);
6927 else if (tosnap)
6928 copy = strdup(tosnap);
6929 if (copy == NULL)
6930 usage(B_FALSE);
6932 if ((atp = strchr(copy, '@')) != NULL)
6933 *atp = '\0';
6935 if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
6936 return (1);
6938 free(copy);
6941 * Ignore SIGPIPE so that the library can give us
6942 * information on any failure
6944 (void) sigignore(SIGPIPE);
6946 err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
6948 zfs_close(zhp);
6950 return (err != 0);
6954 * zfs remap <filesystem | volume>
6956 * Remap the indirect blocks in the given fileystem or volume.
6958 static int
6959 zfs_do_remap(int argc, char **argv)
6961 const char *fsname;
6962 int err = 0;
6963 int c;
6965 /* check options */
6966 while ((c = getopt(argc, argv, "")) != -1) {
6967 switch (c) {
6968 case '?':
6969 (void) fprintf(stderr,
6970 gettext("invalid option '%c'\n"), optopt);
6971 usage(B_FALSE);
6975 if (argc != 2) {
6976 (void) fprintf(stderr, gettext("wrong number of arguments\n"));
6977 usage(B_FALSE);
6980 fsname = argv[1];
6981 err = zfs_remap_indirects(g_zfs, fsname);
6983 return (err);
6987 * zfs bookmark <fs@snap> <fs#bmark>
6989 * Creates a bookmark with the given name from the given snapshot.
6991 static int
6992 zfs_do_bookmark(int argc, char **argv)
6994 char snapname[ZFS_MAX_DATASET_NAME_LEN];
6995 zfs_handle_t *zhp;
6996 nvlist_t *nvl;
6997 int ret = 0;
6998 int c;
7000 /* check options */
7001 while ((c = getopt(argc, argv, "")) != -1) {
7002 switch (c) {
7003 case '?':
7004 (void) fprintf(stderr,
7005 gettext("invalid option '%c'\n"), optopt);
7006 goto usage;
7010 argc -= optind;
7011 argv += optind;
7013 /* check number of arguments */
7014 if (argc < 1) {
7015 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
7016 goto usage;
7018 if (argc < 2) {
7019 (void) fprintf(stderr, gettext("missing bookmark argument\n"));
7020 goto usage;
7023 if (strchr(argv[1], '#') == NULL) {
7024 (void) fprintf(stderr,
7025 gettext("invalid bookmark name '%s' -- "
7026 "must contain a '#'\n"), argv[1]);
7027 goto usage;
7030 if (argv[0][0] == '@') {
7032 * Snapshot name begins with @.
7033 * Default to same fs as bookmark.
7035 (void) strncpy(snapname, argv[1], sizeof (snapname));
7036 *strchr(snapname, '#') = '\0';
7037 (void) strlcat(snapname, argv[0], sizeof (snapname));
7038 } else {
7039 (void) strncpy(snapname, argv[0], sizeof (snapname));
7041 zhp = zfs_open(g_zfs, snapname, ZFS_TYPE_SNAPSHOT);
7042 if (zhp == NULL)
7043 goto usage;
7044 zfs_close(zhp);
7047 nvl = fnvlist_alloc();
7048 fnvlist_add_string(nvl, argv[1], snapname);
7049 ret = lzc_bookmark(nvl, NULL);
7050 fnvlist_free(nvl);
7052 if (ret != 0) {
7053 const char *err_msg;
7054 char errbuf[1024];
7056 (void) snprintf(errbuf, sizeof (errbuf),
7057 dgettext(TEXT_DOMAIN,
7058 "cannot create bookmark '%s'"), argv[1]);
7060 switch (ret) {
7061 case EXDEV:
7062 err_msg = "bookmark is in a different pool";
7063 break;
7064 case EEXIST:
7065 err_msg = "bookmark exists";
7066 break;
7067 case EINVAL:
7068 err_msg = "invalid argument";
7069 break;
7070 case ENOTSUP:
7071 err_msg = "bookmark feature not enabled";
7072 break;
7073 case ENOSPC:
7074 err_msg = "out of space";
7075 break;
7076 default:
7077 err_msg = "unknown error";
7078 break;
7080 (void) fprintf(stderr, "%s: %s\n", errbuf,
7081 dgettext(TEXT_DOMAIN, err_msg));
7084 return (ret != 0);
7086 usage:
7087 usage(B_FALSE);
7088 return (-1);
7091 static int
7092 zfs_do_channel_program(int argc, char **argv)
7094 int ret, fd;
7095 char c;
7096 char *progbuf, *filename, *poolname;
7097 size_t progsize, progread;
7098 nvlist_t *outnvl;
7099 uint64_t instrlimit = ZCP_DEFAULT_INSTRLIMIT;
7100 uint64_t memlimit = ZCP_DEFAULT_MEMLIMIT;
7101 boolean_t sync_flag = B_TRUE;
7102 zpool_handle_t *zhp;
7104 /* check options */
7105 while (-1 !=
7106 (c = getopt(argc, argv, "nt:(instr-limit)m:(memory-limit)"))) {
7107 switch (c) {
7108 case 't':
7109 case 'm': {
7110 uint64_t arg;
7111 char *endp;
7113 errno = 0;
7114 arg = strtoull(optarg, &endp, 0);
7115 if (errno != 0 || *endp != '\0') {
7116 (void) fprintf(stderr, gettext(
7117 "invalid argument "
7118 "'%s': expected integer\n"), optarg);
7119 goto usage;
7122 if (c == 't') {
7123 if (arg > ZCP_MAX_INSTRLIMIT || arg == 0) {
7124 (void) fprintf(stderr, gettext(
7125 "Invalid instruction limit: "
7126 "%s\n"), optarg);
7127 return (1);
7128 } else {
7129 instrlimit = arg;
7131 } else {
7132 ASSERT3U(c, ==, 'm');
7133 if (arg > ZCP_MAX_MEMLIMIT || arg == 0) {
7134 (void) fprintf(stderr, gettext(
7135 "Invalid memory limit: "
7136 "%s\n"), optarg);
7137 return (1);
7138 } else {
7139 memlimit = arg;
7142 break;
7144 case 'n': {
7145 sync_flag = B_FALSE;
7146 break;
7148 case '?':
7149 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7150 optopt);
7151 goto usage;
7155 argc -= optind;
7156 argv += optind;
7158 if (argc < 2) {
7159 (void) fprintf(stderr,
7160 gettext("invalid number of arguments\n"));
7161 goto usage;
7164 poolname = argv[0];
7165 filename = argv[1];
7166 if (strcmp(filename, "-") == 0) {
7167 fd = 0;
7168 filename = "standard input";
7169 } else if ((fd = open(filename, O_RDONLY)) < 0) {
7170 (void) fprintf(stderr, gettext("cannot open '%s': %s\n"),
7171 filename, strerror(errno));
7172 return (1);
7175 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
7176 (void) fprintf(stderr, gettext("cannot open pool '%s'"),
7177 poolname);
7178 return (1);
7180 zpool_close(zhp);
7183 * Read in the channel program, expanding the program buffer as
7184 * necessary.
7186 progread = 0;
7187 progsize = 1024;
7188 progbuf = safe_malloc(progsize);
7189 do {
7190 ret = read(fd, progbuf + progread, progsize - progread);
7191 progread += ret;
7192 if (progread == progsize && ret > 0) {
7193 progsize *= 2;
7194 progbuf = safe_realloc(progbuf, progsize);
7196 } while (ret > 0);
7198 if (fd != 0)
7199 (void) close(fd);
7200 if (ret < 0) {
7201 free(progbuf);
7202 (void) fprintf(stderr,
7203 gettext("cannot read '%s': %s\n"),
7204 filename, strerror(errno));
7205 return (1);
7207 progbuf[progread] = '\0';
7210 * Any remaining arguments are passed as arguments to the lua script as
7211 * a string array:
7213 * "argv" -> [ "arg 1", ... "arg n" ],
7216 nvlist_t *argnvl = fnvlist_alloc();
7217 fnvlist_add_string_array(argnvl, ZCP_ARG_CLIARGV, argv + 2, argc - 2);
7219 if (sync_flag) {
7220 ret = lzc_channel_program(poolname, progbuf,
7221 instrlimit, memlimit, argnvl, &outnvl);
7222 } else {
7223 ret = lzc_channel_program_nosync(poolname, progbuf,
7224 instrlimit, memlimit, argnvl, &outnvl);
7227 if (ret != 0) {
7229 * On error, report the error message handed back by lua if one
7230 * exists. Otherwise, generate an appropriate error message,
7231 * falling back on strerror() for an unexpected return code.
7233 char *errstring = NULL;
7234 if (nvlist_exists(outnvl, ZCP_RET_ERROR)) {
7235 (void) nvlist_lookup_string(outnvl,
7236 ZCP_RET_ERROR, &errstring);
7237 if (errstring == NULL)
7238 errstring = strerror(ret);
7239 } else {
7240 switch (ret) {
7241 case EINVAL:
7242 errstring =
7243 "Invalid instruction or memory limit.";
7244 break;
7245 case ENOMEM:
7246 errstring = "Return value too large.";
7247 break;
7248 case ENOSPC:
7249 errstring = "Memory limit exhausted.";
7250 break;
7251 case ETIME:
7252 errstring = "Timed out.";
7253 break;
7254 case EPERM:
7255 errstring = "Permission denied. Channel "
7256 "programs must be run as root.";
7257 break;
7258 default:
7259 errstring = strerror(ret);
7262 (void) fprintf(stderr,
7263 gettext("Channel program execution failed:\n%s\n"),
7264 errstring);
7265 } else {
7266 (void) printf("Channel program fully executed ");
7267 if (nvlist_empty(outnvl)) {
7268 (void) printf("with no return value.\n");
7269 } else {
7270 (void) printf("with return value:\n");
7271 dump_nvlist(outnvl, 4);
7275 free(progbuf);
7276 fnvlist_free(outnvl);
7277 fnvlist_free(argnvl);
7278 return (ret != 0);
7280 usage:
7281 usage(B_FALSE);
7282 return (-1);
7286 main(int argc, char **argv)
7288 int ret = 0;
7289 int i;
7290 char *progname;
7291 char *cmdname;
7293 (void) setlocale(LC_ALL, "");
7294 (void) textdomain(TEXT_DOMAIN);
7296 opterr = 0;
7298 if ((g_zfs = libzfs_init()) == NULL) {
7299 (void) fprintf(stderr, gettext("internal error: failed to "
7300 "initialize ZFS library\n"));
7301 return (1);
7304 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
7306 libzfs_print_on_error(g_zfs, B_TRUE);
7308 if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
7309 (void) fprintf(stderr, gettext("internal error: unable to "
7310 "open %s\n"), MNTTAB);
7311 return (1);
7315 * This command also doubles as the /etc/fs mount and unmount program.
7316 * Determine if we should take this behavior based on argv[0].
7318 progname = basename(argv[0]);
7319 if (strcmp(progname, "mount") == 0) {
7320 ret = manual_mount(argc, argv);
7321 } else if (strcmp(progname, "umount") == 0) {
7322 ret = manual_unmount(argc, argv);
7323 } else {
7325 * Make sure the user has specified some command.
7327 if (argc < 2) {
7328 (void) fprintf(stderr, gettext("missing command\n"));
7329 usage(B_FALSE);
7332 cmdname = argv[1];
7335 * The 'umount' command is an alias for 'unmount'
7337 if (strcmp(cmdname, "umount") == 0)
7338 cmdname = "unmount";
7341 * The 'recv' command is an alias for 'receive'
7343 if (strcmp(cmdname, "recv") == 0)
7344 cmdname = "receive";
7347 * The 'snap' command is an alias for 'snapshot'
7349 if (strcmp(cmdname, "snap") == 0)
7350 cmdname = "snapshot";
7353 * Special case '-?'
7355 if (strcmp(cmdname, "-?") == 0)
7356 usage(B_TRUE);
7359 * Run the appropriate command.
7361 libzfs_mnttab_cache(g_zfs, B_TRUE);
7362 if (find_command_idx(cmdname, &i) == 0) {
7363 current_command = &command_table[i];
7364 ret = command_table[i].func(argc - 1, argv + 1);
7365 } else if (strchr(cmdname, '=') != NULL) {
7366 verify(find_command_idx("set", &i) == 0);
7367 current_command = &command_table[i];
7368 ret = command_table[i].func(argc, argv);
7369 } else {
7370 (void) fprintf(stderr, gettext("unrecognized "
7371 "command '%s'\n"), cmdname);
7372 usage(B_FALSE);
7374 libzfs_mnttab_cache(g_zfs, B_FALSE);
7377 (void) fclose(mnttab_file);
7379 if (ret == 0 && log_history)
7380 (void) zpool_log_history(g_zfs, history_str);
7382 libzfs_fini(g_zfs);
7385 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
7386 * for the purposes of running ::findleaks.
7388 if (getenv("ZFS_ABORT") != NULL) {
7389 (void) printf("dumping core by request\n");
7390 abort();
7393 return (ret);