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]
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
25 * Copyright 2012 Milan Jurik. All rights reserved.
26 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
27 * Copyright (c) 2013 Steven Hartland. All rights reserved.
28 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
29 * Copyright 2016 Nexenta Systems, Inc.
30 * Copyright (c) 2019 Datto Inc.
31 * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>
32 * Copyright 2019 Joyent, Inc.
33 * Copyright (c) 2019, 2020 by Christian Schwarz. All rights reserved.
38 #include <sys/debug.h>
44 #include <libnvpair.h>
56 #include <sys/debug.h>
58 #include <sys/mkdev.h>
59 #include <sys/mntent.h>
60 #include <sys/mnttab.h>
61 #include <sys/mount.h>
63 #include <sys/fs/zfs.h>
64 #include <sys/systeminfo.h>
65 #include <sys/types.h>
67 #include <sys/zfs_project.h>
70 #include <libzfs_core.h>
72 #include <zfs_deleg.h>
77 #include <directory.h>
78 #endif /* HAVE_IDMAP */
82 #include "zfs_comutil.h"
83 #include "libzfs_impl.h"
84 #include "zfs_projectutil.h"
86 libzfs_handle_t *g_zfs;
88 static FILE *mnttab_file;
89 static char history_str[HIS_MAX_RECORD_LEN];
90 static boolean_t log_history = B_TRUE;
92 static int zfs_do_clone(int argc, char **argv);
93 static int zfs_do_create(int argc, char **argv);
94 static int zfs_do_destroy(int argc, char **argv);
95 static int zfs_do_get(int argc, char **argv);
96 static int zfs_do_inherit(int argc, char **argv);
97 static int zfs_do_list(int argc, char **argv);
98 static int zfs_do_mount(int argc, char **argv);
99 static int zfs_do_rename(int argc, char **argv);
100 static int zfs_do_rollback(int argc, char **argv);
101 static int zfs_do_set(int argc, char **argv);
102 static int zfs_do_upgrade(int argc, char **argv);
103 static int zfs_do_snapshot(int argc, char **argv);
104 static int zfs_do_unmount(int argc, char **argv);
105 static int zfs_do_share(int argc, char **argv);
106 static int zfs_do_unshare(int argc, char **argv);
107 static int zfs_do_send(int argc, char **argv);
108 static int zfs_do_receive(int argc, char **argv);
109 static int zfs_do_promote(int argc, char **argv);
110 static int zfs_do_userspace(int argc, char **argv);
111 static int zfs_do_allow(int argc, char **argv);
112 static int zfs_do_unallow(int argc, char **argv);
113 static int zfs_do_hold(int argc, char **argv);
114 static int zfs_do_holds(int argc, char **argv);
115 static int zfs_do_release(int argc, char **argv);
116 static int zfs_do_diff(int argc, char **argv);
117 static int zfs_do_bookmark(int argc, char **argv);
118 static int zfs_do_channel_program(int argc, char **argv);
119 static int zfs_do_load_key(int argc, char **argv);
120 static int zfs_do_unload_key(int argc, char **argv);
121 static int zfs_do_change_key(int argc, char **argv);
122 static int zfs_do_project(int argc, char **argv);
123 static int zfs_do_version(int argc, char **argv);
124 static int zfs_do_redact(int argc, char **argv);
125 static int zfs_do_wait(int argc, char **argv);
128 static int zfs_do_jail(int argc, char **argv);
129 static int zfs_do_unjail(int argc, char **argv);
133 * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
138 _umem_debug_init(void)
140 return ("default,verbose"); /* $UMEM_DEBUG setting */
144 _umem_logging_init(void)
146 return ("fail,contents"); /* $UMEM_LOGGING setting */
180 HELP_CHANNEL_PROGRAM,
191 typedef struct zfs_command {
193 int (*func)(int argc, char **argv);
198 * Master command table. Each ZFS command has a name, associated function, and
199 * usage message. The usage messages need to be internationalized, so we have
200 * to have a function to return the usage message based on a command index.
202 * These commands are organized according to how they are displayed in the usage
203 * message. An empty command (one with a NULL name) indicates an empty line in
204 * the generic usage message.
206 static zfs_command_t command_table[] = {
207 { "version", zfs_do_version, HELP_VERSION },
209 { "create", zfs_do_create, HELP_CREATE },
210 { "destroy", zfs_do_destroy, HELP_DESTROY },
212 { "snapshot", zfs_do_snapshot, HELP_SNAPSHOT },
213 { "rollback", zfs_do_rollback, HELP_ROLLBACK },
214 { "clone", zfs_do_clone, HELP_CLONE },
215 { "promote", zfs_do_promote, HELP_PROMOTE },
216 { "rename", zfs_do_rename, HELP_RENAME },
217 { "bookmark", zfs_do_bookmark, HELP_BOOKMARK },
218 { "program", zfs_do_channel_program, HELP_CHANNEL_PROGRAM },
220 { "list", zfs_do_list, HELP_LIST },
222 { "set", zfs_do_set, HELP_SET },
223 { "get", zfs_do_get, HELP_GET },
224 { "inherit", zfs_do_inherit, HELP_INHERIT },
225 { "upgrade", zfs_do_upgrade, HELP_UPGRADE },
227 { "userspace", zfs_do_userspace, HELP_USERSPACE },
228 { "groupspace", zfs_do_userspace, HELP_GROUPSPACE },
229 { "projectspace", zfs_do_userspace, HELP_PROJECTSPACE },
231 { "project", zfs_do_project, HELP_PROJECT },
233 { "mount", zfs_do_mount, HELP_MOUNT },
234 { "unmount", zfs_do_unmount, HELP_UNMOUNT },
235 { "share", zfs_do_share, HELP_SHARE },
236 { "unshare", zfs_do_unshare, HELP_UNSHARE },
238 { "send", zfs_do_send, HELP_SEND },
239 { "receive", zfs_do_receive, HELP_RECEIVE },
241 { "allow", zfs_do_allow, HELP_ALLOW },
243 { "unallow", zfs_do_unallow, HELP_UNALLOW },
245 { "hold", zfs_do_hold, HELP_HOLD },
246 { "holds", zfs_do_holds, HELP_HOLDS },
247 { "release", zfs_do_release, HELP_RELEASE },
248 { "diff", zfs_do_diff, HELP_DIFF },
249 { "load-key", zfs_do_load_key, HELP_LOAD_KEY },
250 { "unload-key", zfs_do_unload_key, HELP_UNLOAD_KEY },
251 { "change-key", zfs_do_change_key, HELP_CHANGE_KEY },
252 { "redact", zfs_do_redact, HELP_REDACT },
253 { "wait", zfs_do_wait, HELP_WAIT },
256 { "jail", zfs_do_jail, HELP_JAIL },
257 { "unjail", zfs_do_unjail, HELP_UNJAIL },
261 #define NCOMMAND (sizeof (command_table) / sizeof (command_table[0]))
263 zfs_command_t *current_command;
266 get_usage(zfs_help_t idx)
270 return (gettext("\tclone [-p] [-o property=value] ... "
271 "<snapshot> <filesystem|volume>\n"));
273 return (gettext("\tcreate [-Pnpuv] [-o property=value] ... "
275 "\tcreate [-Pnpsv] [-b blocksize] [-o property=value] ... "
276 "-V <size> <volume>\n"));
278 return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
279 "\tdestroy [-dnpRrv] "
280 "<filesystem|volume>@<snap>[%<snap>][,...]\n"
281 "\tdestroy <filesystem|volume>#<bookmark>\n"));
283 return (gettext("\tget [-rHp] [-d max] "
284 "[-o \"all\" | field[,...]]\n"
285 "\t [-t type[,...]] [-s source[,...]]\n"
286 "\t <\"all\" | property[,...]> "
287 "[filesystem|volume|snapshot|bookmark] ...\n"));
289 return (gettext("\tinherit [-rS] <property> "
290 "<filesystem|volume|snapshot> ...\n"));
292 return (gettext("\tupgrade [-v]\n"
293 "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
295 return (gettext("\tlist [-Hp] [-r|-d max] [-o property[,...]] "
296 "[-s property]...\n\t [-S property]... [-t type[,...]] "
297 "[filesystem|volume|snapshot] ...\n"));
299 return (gettext("\tmount\n"
300 "\tmount [-flvO] [-o opts] <-a | filesystem>\n"));
302 return (gettext("\tpromote <clone-filesystem>\n"));
304 return (gettext("\treceive [-vMnsFhu] "
305 "[-o <property>=<value>] ... [-x <property>] ...\n"
306 "\t <filesystem|volume|snapshot>\n"
307 "\treceive [-vMnsFhu] [-o <property>=<value>] ... "
308 "[-x <property>] ... \n"
309 "\t [-d | -e] <filesystem>\n"
310 "\treceive -A <filesystem|volume>\n"));
312 return (gettext("\trename [-f] <filesystem|volume|snapshot> "
313 "<filesystem|volume|snapshot>\n"
314 "\trename -p [-f] <filesystem|volume> <filesystem|volume>\n"
315 "\trename -u [-f] <filesystem> <filesystem>\n"
316 "\trename -r <snapshot> <snapshot>\n"));
318 return (gettext("\trollback [-rRf] <snapshot>\n"));
320 return (gettext("\tsend [-DnPpRvLecwhb] [-[i|I] snapshot] "
322 "\tsend [-nvPLecw] [-i snapshot|bookmark] "
323 "<filesystem|volume|snapshot>\n"
324 "\tsend [-DnPpvLec] [-i bookmark|snapshot] "
325 "--redact <bookmark> <snapshot>\n"
326 "\tsend [-nvPe] -t <receive_resume_token>\n"
327 "\tsend [-Pnv] --saved filesystem\n"));
329 return (gettext("\tset <property=value> ... "
330 "<filesystem|volume|snapshot> ...\n"));
332 return (gettext("\tshare [-l] <-a [nfs|smb] | filesystem>\n"));
334 return (gettext("\tsnapshot [-r] [-o property=value] ... "
335 "<filesystem|volume>@<snap> ...\n"));
337 return (gettext("\tunmount [-fu] "
338 "<-a | filesystem|mountpoint>\n"));
340 return (gettext("\tunshare "
341 "<-a [nfs|smb] | filesystem|mountpoint>\n"));
343 return (gettext("\tallow <filesystem|volume>\n"
345 "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
346 "\t <filesystem|volume>\n"
347 "\tallow [-ld] -e <perm|@setname>[,...] "
348 "<filesystem|volume>\n"
349 "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
350 "\tallow -s @setname <perm|@setname>[,...] "
351 "<filesystem|volume>\n"));
353 return (gettext("\tunallow [-rldug] "
354 "<\"everyone\"|user|group>[,...]\n"
355 "\t [<perm|@setname>[,...]] <filesystem|volume>\n"
356 "\tunallow [-rld] -e [<perm|@setname>[,...]] "
357 "<filesystem|volume>\n"
358 "\tunallow [-r] -c [<perm|@setname>[,...]] "
359 "<filesystem|volume>\n"
360 "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
361 "<filesystem|volume>\n"));
363 return (gettext("\tuserspace [-Hinp] [-o field[,...]] "
365 "\t [-S field] ... [-t type[,...]] "
366 "<filesystem|snapshot|path>\n"));
367 case HELP_GROUPSPACE:
368 return (gettext("\tgroupspace [-Hinp] [-o field[,...]] "
370 "\t [-S field] ... [-t type[,...]] "
371 "<filesystem|snapshot|path>\n"));
372 case HELP_PROJECTSPACE:
373 return (gettext("\tprojectspace [-Hp] [-o field[,...]] "
375 "\t [-S field] ... <filesystem|snapshot|path>\n"));
377 return (gettext("\tproject [-d|-r] <directory|file ...>\n"
378 "\tproject -c [-0] [-d|-r] [-p id] <directory|file ...>\n"
379 "\tproject -C [-k] [-r] <directory ...>\n"
380 "\tproject [-p id] [-r] [-s] <directory ...>\n"));
382 return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
384 return (gettext("\tholds [-rH] <snapshot> ...\n"));
386 return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
388 return (gettext("\tdiff [-FHt] <snapshot> "
389 "[snapshot|filesystem]\n"));
391 return (gettext("\tbookmark <snapshot|bookmark> "
393 case HELP_CHANNEL_PROGRAM:
394 return (gettext("\tprogram [-jn] [-t <instruction limit>] "
395 "[-m <memory limit (b)>]\n"
396 "\t <pool> <program file> [lua args...]\n"));
398 return (gettext("\tload-key [-rn] [-L <keylocation>] "
399 "<-a | filesystem|volume>\n"));
400 case HELP_UNLOAD_KEY:
401 return (gettext("\tunload-key [-r] "
402 "<-a | filesystem|volume>\n"));
403 case HELP_CHANGE_KEY:
404 return (gettext("\tchange-key [-l] [-o keyformat=<value>]\n"
405 "\t [-o keylocation=<value>] [-o pbkdf2iters=<value>]\n"
406 "\t <filesystem|volume>\n"
407 "\tchange-key -i [-l] <filesystem|volume>\n"));
409 return (gettext("\tversion\n"));
411 return (gettext("\tredact <snapshot> <bookmark> "
412 "<redaction_snapshot> ...\n"));
414 return (gettext("\tjail <jailid|jailname> <filesystem>\n"));
416 return (gettext("\tunjail <jailid|jailname> <filesystem>\n"));
418 return (gettext("\twait [-t <activity>] <filesystem>\n"));
428 (void) fprintf(stderr, gettext("internal error: out of memory\n"));
433 * Utility function to guarantee malloc() success.
437 safe_malloc(size_t size)
441 if ((data = calloc(1, size)) == NULL)
448 safe_realloc(void *data, size_t size)
451 if ((newp = realloc(data, size)) == NULL) {
460 safe_strdup(char *str)
462 char *dupstr = strdup(str);
471 * Callback routine that will print out information for each of
475 usage_prop_cb(int prop, void *cb)
479 (void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
481 if (zfs_prop_readonly(prop))
482 (void) fprintf(fp, " NO ");
484 (void) fprintf(fp, "YES ");
486 if (zfs_prop_inheritable(prop))
487 (void) fprintf(fp, " YES ");
489 (void) fprintf(fp, " NO ");
491 if (zfs_prop_values(prop) == NULL)
492 (void) fprintf(fp, "-\n");
494 (void) fprintf(fp, "%s\n", zfs_prop_values(prop));
500 * Display usage message. If we're inside a command, display only the usage for
501 * that command. Otherwise, iterate over the entire command table and display
502 * a complete usage message.
505 usage(boolean_t requested)
508 boolean_t show_properties = B_FALSE;
509 FILE *fp = requested ? stdout : stderr;
511 if (current_command == NULL) {
513 (void) fprintf(fp, gettext("usage: zfs command args ...\n"));
515 gettext("where 'command' is one of the following:\n\n"));
517 for (i = 0; i < NCOMMAND; i++) {
518 if (command_table[i].name == NULL)
519 (void) fprintf(fp, "\n");
521 (void) fprintf(fp, "%s",
522 get_usage(command_table[i].usage));
525 (void) fprintf(fp, gettext("\nEach dataset is of the form: "
526 "pool/[dataset/]*dataset[@name]\n"));
528 (void) fprintf(fp, gettext("usage:\n"));
529 (void) fprintf(fp, "%s", get_usage(current_command->usage));
532 if (current_command != NULL &&
533 (strcmp(current_command->name, "set") == 0 ||
534 strcmp(current_command->name, "get") == 0 ||
535 strcmp(current_command->name, "inherit") == 0 ||
536 strcmp(current_command->name, "list") == 0))
537 show_properties = B_TRUE;
539 if (show_properties) {
541 gettext("\nThe following properties are supported:\n"));
543 (void) fprintf(fp, "\n\t%-14s %s %s %s\n\n",
544 "PROPERTY", "EDIT", "INHERIT", "VALUES");
546 /* Iterate over all properties */
547 (void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
550 (void) fprintf(fp, "\t%-15s ", "userused@...");
551 (void) fprintf(fp, " NO NO <size>\n");
552 (void) fprintf(fp, "\t%-15s ", "groupused@...");
553 (void) fprintf(fp, " NO NO <size>\n");
554 (void) fprintf(fp, "\t%-15s ", "projectused@...");
555 (void) fprintf(fp, " NO NO <size>\n");
556 (void) fprintf(fp, "\t%-15s ", "userobjused@...");
557 (void) fprintf(fp, " NO NO <size>\n");
558 (void) fprintf(fp, "\t%-15s ", "groupobjused@...");
559 (void) fprintf(fp, " NO NO <size>\n");
560 (void) fprintf(fp, "\t%-15s ", "projectobjused@...");
561 (void) fprintf(fp, " NO NO <size>\n");
562 (void) fprintf(fp, "\t%-15s ", "userquota@...");
563 (void) fprintf(fp, "YES NO <size> | none\n");
564 (void) fprintf(fp, "\t%-15s ", "groupquota@...");
565 (void) fprintf(fp, "YES NO <size> | none\n");
566 (void) fprintf(fp, "\t%-15s ", "projectquota@...");
567 (void) fprintf(fp, "YES NO <size> | none\n");
568 (void) fprintf(fp, "\t%-15s ", "userobjquota@...");
569 (void) fprintf(fp, "YES NO <size> | none\n");
570 (void) fprintf(fp, "\t%-15s ", "groupobjquota@...");
571 (void) fprintf(fp, "YES NO <size> | none\n");
572 (void) fprintf(fp, "\t%-15s ", "projectobjquota@...");
573 (void) fprintf(fp, "YES NO <size> | none\n");
574 (void) fprintf(fp, "\t%-15s ", "written@<snap>");
575 (void) fprintf(fp, " NO NO <size>\n");
576 (void) fprintf(fp, "\t%-15s ", "written#<bookmark>");
577 (void) fprintf(fp, " NO NO <size>\n");
579 (void) fprintf(fp, gettext("\nSizes are specified in bytes "
580 "with standard units such as K, M, G, etc.\n"));
581 (void) fprintf(fp, gettext("\nUser-defined properties can "
582 "be specified by using a name containing a colon (:).\n"));
583 (void) fprintf(fp, gettext("\nThe {user|group|project}"
584 "[obj]{used|quota}@ properties must be appended with\n"
585 "a user|group|project specifier of one of these forms:\n"
586 " POSIX name (eg: \"matt\")\n"
587 " POSIX id (eg: \"126829\")\n"
588 " SMB name@domain (eg: \"matt@sun\")\n"
589 " SMB SID (eg: \"S-1-234-567-89\")\n"));
592 gettext("\nFor the property list, run: %s\n"),
595 gettext("\nFor the delegated permission list, run: %s\n"),
596 "zfs allow|unallow");
600 * See comments at end of main().
602 if (getenv("ZFS_ABORT") != NULL) {
603 (void) printf("dumping core by request\n");
607 exit(requested ? 0 : 2);
611 * Take a property=value argument string and add it to the given nvlist.
612 * Modifies the argument inplace.
615 parseprop(nvlist_t *props, char *propname)
619 if ((propval = strchr(propname, '=')) == NULL) {
620 (void) fprintf(stderr, gettext("missing "
621 "'=' for property=value argument\n"));
626 if (nvlist_exists(props, propname)) {
627 (void) fprintf(stderr, gettext("property '%s' "
628 "specified multiple times\n"), propname);
631 if (nvlist_add_string(props, propname, propval) != 0)
637 * Take a property name argument and add it to the given nvlist.
638 * Modifies the argument inplace.
641 parsepropname(nvlist_t *props, char *propname)
643 if (strchr(propname, '=') != NULL) {
644 (void) fprintf(stderr, gettext("invalid character "
645 "'=' in property argument\n"));
648 if (nvlist_exists(props, propname)) {
649 (void) fprintf(stderr, gettext("property '%s' "
650 "specified multiple times\n"), propname);
653 if (nvlist_add_boolean(props, propname) != 0)
659 parse_depth(char *opt, int *flags)
664 depth = (int)strtol(opt, &tmp, 0);
666 (void) fprintf(stderr,
667 gettext("%s is not an integer\n"), optarg);
671 (void) fprintf(stderr,
672 gettext("Depth can not be negative.\n"));
675 *flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
679 #define PROGRESS_DELAY 2 /* seconds */
681 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";
682 static time_t pt_begin;
683 static char *pt_header = NULL;
684 static boolean_t pt_shown;
687 start_progress_timer(void)
689 pt_begin = time(NULL) + PROGRESS_DELAY;
694 set_progress_header(char *header)
696 assert(pt_header == NULL);
697 pt_header = safe_strdup(header);
699 (void) printf("%s: ", header);
700 (void) fflush(stdout);
705 update_progress(char *update)
707 if (!pt_shown && time(NULL) > pt_begin) {
708 int len = strlen(update);
710 (void) printf("%s: %s%*.*s", pt_header, update, len, len,
712 (void) fflush(stdout);
714 } else if (pt_shown) {
715 int len = strlen(update);
717 (void) printf("%s%*.*s", update, len, len, pt_reverse);
718 (void) fflush(stdout);
723 finish_progress(char *done)
726 (void) printf("%s\n", done);
727 (void) fflush(stdout);
734 zfs_mount_and_share(libzfs_handle_t *hdl, const char *dataset, zfs_type_t type)
736 zfs_handle_t *zhp = NULL;
739 zhp = zfs_open(hdl, dataset, type);
744 * Volumes may neither be mounted or shared. Potentially in the
745 * future filesystems detected on these volumes could be mounted.
747 if (zfs_get_type(zhp) == ZFS_TYPE_VOLUME) {
753 * Mount and/or share the new filesystem as appropriate. We provide a
754 * verbose error message to let the user know that their filesystem was
755 * in fact created, even if we failed to mount or share it.
757 * If the user doesn't want the dataset automatically mounted, then
758 * skip the mount/share step
760 if (zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, type, B_FALSE) &&
761 zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_ON) {
762 if (zfs_mount_delegation_check()) {
763 (void) fprintf(stderr, gettext("filesystem "
764 "successfully created, but it may only be "
765 "mounted by root\n"));
767 } else if (zfs_mount(zhp, NULL, 0) != 0) {
768 (void) fprintf(stderr, gettext("filesystem "
769 "successfully created, but not mounted\n"));
771 } else if (zfs_share(zhp) != 0) {
772 (void) fprintf(stderr, gettext("filesystem "
773 "successfully created, but not shared\n"));
776 zfs_commit_all_shares();
785 * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
787 * Given an existing dataset, create a writable copy whose initial contents
788 * are the same as the source. The newly created dataset maintains a
789 * dependency on the original; the original cannot be destroyed so long as
792 * The '-p' flag creates all the non-existing ancestors of the target first.
795 zfs_do_clone(int argc, char **argv)
797 zfs_handle_t *zhp = NULL;
798 boolean_t parents = B_FALSE;
803 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
807 while ((c = getopt(argc, argv, "o:p")) != -1) {
810 if (!parseprop(props, optarg)) {
819 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
828 /* check number of arguments */
830 (void) fprintf(stderr, gettext("missing source dataset "
835 (void) fprintf(stderr, gettext("missing target dataset "
840 (void) fprintf(stderr, gettext("too many arguments\n"));
844 /* open the source dataset */
845 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL) {
850 if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
853 * Now create the ancestors of the target dataset. If the
854 * target already exists and '-p' option was used we should not
857 if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
863 if (zfs_create_ancestors(g_zfs, argv[1]) != 0) {
871 ret = zfs_clone(zhp, argv[1], props);
873 /* create the mountpoint if necessary */
876 (void) zpool_log_history(g_zfs, history_str);
877 log_history = B_FALSE;
880 ret = zfs_mount_and_share(g_zfs, argv[1], ZFS_TYPE_DATASET);
889 ASSERT3P(zhp, ==, NULL);
896 * Return a default volblocksize for the pool which always uses more than
897 * half of the data sectors. This primarily applies to dRAID which always
898 * writes full stripe widths.
901 default_volblocksize(zpool_handle_t *zhp, nvlist_t *props)
903 uint64_t volblocksize, asize = SPA_MINBLOCKSIZE;
904 nvlist_t *tree, **vdevs;
907 nvlist_t *config = zpool_get_config(zhp, NULL);
909 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &tree) != 0 ||
910 nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN,
911 &vdevs, &nvdevs) != 0) {
912 return (ZVOL_DEFAULT_BLOCKSIZE);
915 for (int i = 0; i < nvdevs; i++) {
916 nvlist_t *nv = vdevs[i];
917 uint64_t ashift, ndata, nparity;
919 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASHIFT, &ashift) != 0)
922 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DRAID_NDATA,
924 /* dRAID minimum allocation width */
925 asize = MAX(asize, ndata * (1ULL << ashift));
926 } else if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
928 /* raidz minimum allocation width */
930 asize = MAX(asize, 2 * (1ULL << ashift));
932 asize = MAX(asize, 4 * (1ULL << ashift));
934 /* mirror or (non-redundant) leaf vdev */
935 asize = MAX(asize, 1ULL << ashift);
940 * Calculate the target volblocksize such that more than half
941 * of the asize is used. The following table is for 4k sectors.
943 * n asize blksz used | n asize blksz used
944 * -------------------------+---------------------------------
945 * 1 4,096 8,192 100% | 9 36,864 32,768 88%
946 * 2 8,192 8,192 100% | 10 40,960 32,768 80%
947 * 3 12,288 8,192 66% | 11 45,056 32,768 72%
948 * 4 16,384 16,384 100% | 12 49,152 32,768 66%
949 * 5 20,480 16,384 80% | 13 53,248 32,768 61%
950 * 6 24,576 16,384 66% | 14 57,344 32,768 57%
951 * 7 28,672 16,384 57% | 15 61,440 32,768 53%
952 * 8 32,768 32,768 100% | 16 65,536 65,636 100%
954 * This is primarily a concern for dRAID which always allocates
955 * a full stripe width. For dRAID the default stripe width is
956 * n=8 in which case the volblocksize is set to 32k. Ignoring
957 * compression there are no unused sectors. This same reasoning
958 * applies to raidz[2,3] so target 4 sectors to minimize waste.
960 uint64_t tgt_volblocksize = ZVOL_DEFAULT_BLOCKSIZE;
961 while (tgt_volblocksize * 2 <= asize)
962 tgt_volblocksize *= 2;
964 const char *prop = zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE);
965 if (nvlist_lookup_uint64(props, prop, &volblocksize) == 0) {
967 /* Issue a warning when a non-optimal size is requested. */
968 if (volblocksize < ZVOL_DEFAULT_BLOCKSIZE) {
969 (void) fprintf(stderr, gettext("Warning: "
970 "volblocksize (%llu) is less than the default "
971 "minimum block size (%llu).\nTo reduce wasted "
972 "space a volblocksize of %llu is recommended.\n"),
973 (u_longlong_t)volblocksize,
974 (u_longlong_t)ZVOL_DEFAULT_BLOCKSIZE,
975 (u_longlong_t)tgt_volblocksize);
976 } else if (volblocksize < tgt_volblocksize) {
977 (void) fprintf(stderr, gettext("Warning: "
978 "volblocksize (%llu) is much less than the "
979 "minimum allocation\nunit (%llu), which wastes "
980 "at least %llu%% of space. To reduce wasted "
981 "space,\nuse a larger volblocksize (%llu is "
982 "recommended), fewer dRAID data disks\n"
983 "per group, or smaller sector size (ashift).\n"),
984 (u_longlong_t)volblocksize, (u_longlong_t)asize,
985 (u_longlong_t)((100 * (asize - volblocksize)) /
986 asize), (u_longlong_t)tgt_volblocksize);
989 volblocksize = tgt_volblocksize;
990 fnvlist_add_uint64(props, prop, volblocksize);
993 return (volblocksize);
997 * zfs create [-Pnpv] [-o prop=value] ... fs
998 * zfs create [-Pnpsv] [-b blocksize] [-o prop=value] ... -V vol size
1000 * Create a new dataset. This command can be used to create filesystems
1001 * and volumes. Snapshot creation is handled by 'zfs snapshot'.
1002 * For volumes, the user must specify a size to be used.
1004 * The '-s' flag applies only to volumes, and indicates that we should not try
1005 * to set the reservation for this volume. By default we set a reservation
1006 * equal to the size for any volume. For pools with SPA_VERSION >=
1007 * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
1009 * The '-p' flag creates all the non-existing ancestors of the target first.
1011 * The '-n' flag is no-op (dry run) mode. This will perform a user-space sanity
1012 * check of arguments and properties, but does not check for permissions,
1013 * available space, etc.
1015 * The '-u' flag prevents the newly created file system from being mounted.
1017 * The '-v' flag is for verbose output.
1019 * The '-P' flag is used for parseable output. It implies '-v'.
1022 zfs_do_create(int argc, char **argv)
1024 zfs_type_t type = ZFS_TYPE_FILESYSTEM;
1025 zpool_handle_t *zpool_handle = NULL;
1026 nvlist_t *real_props = NULL;
1027 uint64_t volsize = 0;
1029 boolean_t noreserve = B_FALSE;
1030 boolean_t bflag = B_FALSE;
1031 boolean_t parents = B_FALSE;
1032 boolean_t dryrun = B_FALSE;
1033 boolean_t nomount = B_FALSE;
1034 boolean_t verbose = B_FALSE;
1035 boolean_t parseable = B_FALSE;
1041 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
1045 while ((c = getopt(argc, argv, ":PV:b:nso:puv")) != -1) {
1048 type = ZFS_TYPE_VOLUME;
1049 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
1050 (void) fprintf(stderr, gettext("bad volume "
1051 "size '%s': %s\n"), optarg,
1052 libzfs_error_description(g_zfs));
1056 if (nvlist_add_uint64(props,
1057 zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
1070 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
1071 (void) fprintf(stderr, gettext("bad volume "
1072 "block size '%s': %s\n"), optarg,
1073 libzfs_error_description(g_zfs));
1077 if (nvlist_add_uint64(props,
1078 zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
1086 if (!parseprop(props, optarg))
1099 (void) fprintf(stderr, gettext("missing size "
1103 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1109 if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
1110 (void) fprintf(stderr, gettext("'-s' and '-b' can only be "
1111 "used when creating a volume\n"));
1114 if (nomount && type != ZFS_TYPE_FILESYSTEM) {
1115 (void) fprintf(stderr, gettext("'-u' can only be "
1116 "used when creating a filesystem\n"));
1123 /* check number of arguments */
1125 (void) fprintf(stderr, gettext("missing %s argument\n"),
1126 zfs_type_to_name(type));
1130 (void) fprintf(stderr, gettext("too many arguments\n"));
1134 if (dryrun || type == ZFS_TYPE_VOLUME) {
1135 char msg[ZFS_MAX_DATASET_NAME_LEN * 2];
1138 if ((p = strchr(argv[0], '/')) != NULL)
1140 zpool_handle = zpool_open(g_zfs, argv[0]);
1143 if (zpool_handle == NULL)
1146 (void) snprintf(msg, sizeof (msg),
1147 dryrun ? gettext("cannot verify '%s'") :
1148 gettext("cannot create '%s'"), argv[0]);
1149 if (props && (real_props = zfs_valid_proplist(g_zfs, type,
1150 props, 0, NULL, zpool_handle, B_TRUE, msg)) == NULL) {
1151 zpool_close(zpool_handle);
1156 if (type == ZFS_TYPE_VOLUME) {
1157 const char *prop = zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE);
1158 uint64_t volblocksize = default_volblocksize(zpool_handle,
1161 if (volblocksize != ZVOL_DEFAULT_BLOCKSIZE &&
1162 nvlist_lookup_string(props, prop, &strval) != 0) {
1163 if (asprintf(&strval, "%llu",
1164 (u_longlong_t)volblocksize) == -1)
1166 nvlist_add_string(props, prop, strval);
1171 * If volsize is not a multiple of volblocksize, round it
1172 * up to the nearest multiple of the volblocksize.
1174 if (volsize % volblocksize) {
1175 volsize = P2ROUNDUP_TYPED(volsize, volblocksize,
1178 if (nvlist_add_uint64(props,
1179 zfs_prop_to_name(ZFS_PROP_VOLSIZE), volsize) != 0) {
1186 if (type == ZFS_TYPE_VOLUME && !noreserve) {
1187 uint64_t spa_version;
1188 zfs_prop_t resv_prop;
1190 spa_version = zpool_get_prop_int(zpool_handle,
1191 ZPOOL_PROP_VERSION, NULL);
1192 if (spa_version >= SPA_VERSION_REFRESERVATION)
1193 resv_prop = ZFS_PROP_REFRESERVATION;
1195 resv_prop = ZFS_PROP_RESERVATION;
1197 volsize = zvol_volsize_to_reservation(zpool_handle, volsize,
1200 if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
1202 if (nvlist_add_uint64(props,
1203 zfs_prop_to_name(resv_prop), volsize) != 0) {
1209 if (zpool_handle != NULL) {
1210 zpool_close(zpool_handle);
1211 nvlist_free(real_props);
1214 if (parents && zfs_name_valid(argv[0], type)) {
1216 * Now create the ancestors of target dataset. If the target
1217 * already exists and '-p' option was used we should not
1220 if (zfs_dataset_exists(g_zfs, argv[0], type)) {
1225 (void) printf(parseable ? "create_ancestors\t%s\n" :
1226 dryrun ? "would create ancestors of %s\n" :
1227 "create ancestors of %s\n", argv[0]);
1230 if (zfs_create_ancestors(g_zfs, argv[0]) != 0) {
1237 nvpair_t *nvp = NULL;
1238 (void) printf(parseable ? "create\t%s\n" :
1239 dryrun ? "would create %s\n" : "create %s\n", argv[0]);
1240 while ((nvp = nvlist_next_nvpair(props, nvp)) != NULL) {
1244 switch (nvpair_type(nvp)) {
1245 case DATA_TYPE_UINT64:
1246 VERIFY0(nvpair_value_uint64(nvp, &uval));
1247 (void) printf(parseable ?
1248 "property\t%s\t%llu\n" : "\t%s=%llu\n",
1249 nvpair_name(nvp), (u_longlong_t)uval);
1251 case DATA_TYPE_STRING:
1252 VERIFY0(nvpair_value_string(nvp, &sval));
1253 (void) printf(parseable ?
1254 "property\t%s\t%s\n" : "\t%s=%s\n",
1255 nvpair_name(nvp), sval);
1258 (void) fprintf(stderr, "property '%s' "
1259 "has illegal type %d\n",
1260 nvpair_name(nvp), nvpair_type(nvp));
1270 /* pass to libzfs */
1271 if (zfs_create(g_zfs, argv[0], type, props) != 0)
1275 (void) zpool_log_history(g_zfs, history_str);
1276 log_history = B_FALSE;
1284 ret = zfs_mount_and_share(g_zfs, argv[0], ZFS_TYPE_DATASET);
1295 * zfs destroy [-rRf] <fs, vol>
1296 * zfs destroy [-rRd] <snap>
1298 * -r Recursively destroy all children
1299 * -R Recursively destroy all dependents, including clones
1300 * -f Force unmounting of any dependents
1301 * -d If we can't destroy now, mark for deferred destruction
1303 * Destroys the given dataset. By default, it will unmount any filesystems,
1304 * and refuse to destroy a dataset that has any dependents. A dependent can
1305 * either be a child, or a clone of a child.
1307 typedef struct destroy_cbdata {
1310 boolean_t cb_recurse;
1312 boolean_t cb_doclones;
1313 zfs_handle_t *cb_target;
1314 boolean_t cb_defer_destroy;
1315 boolean_t cb_verbose;
1316 boolean_t cb_parsable;
1317 boolean_t cb_dryrun;
1319 nvlist_t *cb_batchedsnaps;
1321 /* first snap in contiguous run */
1323 /* previous snap in contiguous run */
1325 int64_t cb_snapused;
1328 uint64_t cb_snap_count;
1332 * Check for any dependents based on the '-r' or '-R' flags.
1335 destroy_check_dependent(zfs_handle_t *zhp, void *data)
1337 destroy_cbdata_t *cbp = data;
1338 const char *tname = zfs_get_name(cbp->cb_target);
1339 const char *name = zfs_get_name(zhp);
1341 if (strncmp(tname, name, strlen(tname)) == 0 &&
1342 (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
1344 * This is a direct descendant, not a clone somewhere else in
1347 if (cbp->cb_recurse)
1350 if (cbp->cb_first) {
1351 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1352 "%s has children\n"),
1353 zfs_get_name(cbp->cb_target),
1354 zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1355 (void) fprintf(stderr, gettext("use '-r' to destroy "
1356 "the following datasets:\n"));
1357 cbp->cb_first = B_FALSE;
1358 cbp->cb_error = B_TRUE;
1361 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1364 * This is a clone. We only want to report this if the '-r'
1365 * wasn't specified, or the target is a snapshot.
1367 if (!cbp->cb_recurse &&
1368 zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
1371 if (cbp->cb_first) {
1372 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1373 "%s has dependent clones\n"),
1374 zfs_get_name(cbp->cb_target),
1375 zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1376 (void) fprintf(stderr, gettext("use '-R' to destroy "
1377 "the following datasets:\n"));
1378 cbp->cb_first = B_FALSE;
1379 cbp->cb_error = B_TRUE;
1380 cbp->cb_dryrun = B_TRUE;
1383 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1392 destroy_batched(destroy_cbdata_t *cb)
1394 int error = zfs_destroy_snaps_nvl(g_zfs,
1395 cb->cb_batchedsnaps, B_FALSE);
1396 fnvlist_free(cb->cb_batchedsnaps);
1397 cb->cb_batchedsnaps = fnvlist_alloc();
1402 destroy_callback(zfs_handle_t *zhp, void *data)
1404 destroy_cbdata_t *cb = data;
1405 const char *name = zfs_get_name(zhp);
1408 if (cb->cb_verbose) {
1409 if (cb->cb_parsable) {
1410 (void) printf("destroy\t%s\n", name);
1411 } else if (cb->cb_dryrun) {
1412 (void) printf(gettext("would destroy %s\n"),
1415 (void) printf(gettext("will destroy %s\n"),
1421 * Ignore pools (which we've already flagged as an error before getting
1424 if (strchr(zfs_get_name(zhp), '/') == NULL &&
1425 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1429 if (cb->cb_dryrun) {
1435 * We batch up all contiguous snapshots (even of different
1436 * filesystems) and destroy them with one ioctl. We can't
1437 * simply do all snap deletions and then all fs deletions,
1438 * because we must delete a clone before its origin.
1440 if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT) {
1441 cb->cb_snap_count++;
1442 fnvlist_add_boolean(cb->cb_batchedsnaps, name);
1443 if (cb->cb_snap_count % 10 == 0 && cb->cb_defer_destroy)
1444 error = destroy_batched(cb);
1446 error = destroy_batched(cb);
1448 zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
1449 zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
1452 * When performing a recursive destroy we ignore errors
1453 * so that the recursive destroy could continue
1454 * destroying past problem datasets
1456 if (cb->cb_recurse) {
1457 cb->cb_error = B_TRUE;
1469 destroy_print_cb(zfs_handle_t *zhp, void *arg)
1471 destroy_cbdata_t *cb = arg;
1472 const char *name = zfs_get_name(zhp);
1475 if (nvlist_exists(cb->cb_nvl, name)) {
1476 if (cb->cb_firstsnap == NULL)
1477 cb->cb_firstsnap = strdup(name);
1478 if (cb->cb_prevsnap != NULL)
1479 free(cb->cb_prevsnap);
1480 /* this snap continues the current range */
1481 cb->cb_prevsnap = strdup(name);
1482 if (cb->cb_firstsnap == NULL || cb->cb_prevsnap == NULL)
1484 if (cb->cb_verbose) {
1485 if (cb->cb_parsable) {
1486 (void) printf("destroy\t%s\n", name);
1487 } else if (cb->cb_dryrun) {
1488 (void) printf(gettext("would destroy %s\n"),
1491 (void) printf(gettext("will destroy %s\n"),
1495 } else if (cb->cb_firstsnap != NULL) {
1496 /* end of this range */
1498 err = lzc_snaprange_space(cb->cb_firstsnap,
1499 cb->cb_prevsnap, &used);
1500 cb->cb_snapused += used;
1501 free(cb->cb_firstsnap);
1502 cb->cb_firstsnap = NULL;
1503 free(cb->cb_prevsnap);
1504 cb->cb_prevsnap = NULL;
1511 destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
1514 assert(cb->cb_firstsnap == NULL);
1515 assert(cb->cb_prevsnap == NULL);
1516 err = zfs_iter_snapshots_sorted(fs_zhp, destroy_print_cb, cb, 0, 0);
1517 if (cb->cb_firstsnap != NULL) {
1520 err = lzc_snaprange_space(cb->cb_firstsnap,
1521 cb->cb_prevsnap, &used);
1523 cb->cb_snapused += used;
1524 free(cb->cb_firstsnap);
1525 cb->cb_firstsnap = NULL;
1526 free(cb->cb_prevsnap);
1527 cb->cb_prevsnap = NULL;
1533 snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
1535 destroy_cbdata_t *cb = arg;
1538 /* Check for clones. */
1539 if (!cb->cb_doclones && !cb->cb_defer_destroy) {
1540 cb->cb_target = zhp;
1541 cb->cb_first = B_TRUE;
1542 err = zfs_iter_dependents(zhp, B_TRUE,
1543 destroy_check_dependent, cb);
1547 if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
1555 gather_snapshots(zfs_handle_t *zhp, void *arg)
1557 destroy_cbdata_t *cb = arg;
1560 err = zfs_iter_snapspec(zhp, cb->cb_snapspec, snapshot_to_nvl_cb, cb);
1566 if (cb->cb_verbose) {
1567 err = destroy_print_snapshots(zhp, cb);
1573 err = zfs_iter_filesystems(zhp, gather_snapshots, cb);
1581 destroy_clones(destroy_cbdata_t *cb)
1584 for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
1586 pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
1587 zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
1590 boolean_t defer = cb->cb_defer_destroy;
1594 * We can't defer destroy non-snapshots, so set it to
1595 * false while destroying the clones.
1597 cb->cb_defer_destroy = B_FALSE;
1598 err = zfs_iter_dependents(zhp, B_FALSE,
1599 destroy_callback, cb);
1600 cb->cb_defer_destroy = defer;
1610 zfs_do_destroy(int argc, char **argv)
1612 destroy_cbdata_t cb = { 0 };
1616 zfs_handle_t *zhp = NULL;
1618 zfs_type_t type = ZFS_TYPE_DATASET;
1621 while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
1624 cb.cb_verbose = B_TRUE;
1627 cb.cb_verbose = B_TRUE;
1628 cb.cb_parsable = B_TRUE;
1631 cb.cb_dryrun = B_TRUE;
1634 cb.cb_defer_destroy = B_TRUE;
1635 type = ZFS_TYPE_SNAPSHOT;
1638 cb.cb_force = B_TRUE;
1641 cb.cb_recurse = B_TRUE;
1644 cb.cb_recurse = B_TRUE;
1645 cb.cb_doclones = B_TRUE;
1649 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1658 /* check number of arguments */
1660 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1664 (void) fprintf(stderr, gettext("too many arguments\n"));
1668 at = strchr(argv[0], '@');
1669 pound = strchr(argv[0], '#');
1672 /* Build the list of snaps to destroy in cb_nvl. */
1673 cb.cb_nvl = fnvlist_alloc();
1676 zhp = zfs_open(g_zfs, argv[0],
1677 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1679 nvlist_free(cb.cb_nvl);
1683 cb.cb_snapspec = at + 1;
1684 if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
1690 if (nvlist_empty(cb.cb_nvl)) {
1691 (void) fprintf(stderr, gettext("could not find any "
1692 "snapshots to destroy; check snapshot names.\n"));
1697 if (cb.cb_verbose) {
1699 zfs_nicebytes(cb.cb_snapused, buf, sizeof (buf));
1700 if (cb.cb_parsable) {
1701 (void) printf("reclaim\t%llu\n",
1702 (u_longlong_t)cb.cb_snapused);
1703 } else if (cb.cb_dryrun) {
1704 (void) printf(gettext("would reclaim %s\n"),
1707 (void) printf(gettext("will reclaim %s\n"),
1712 if (!cb.cb_dryrun) {
1713 if (cb.cb_doclones) {
1714 cb.cb_batchedsnaps = fnvlist_alloc();
1715 err = destroy_clones(&cb);
1717 err = zfs_destroy_snaps_nvl(g_zfs,
1718 cb.cb_batchedsnaps, B_FALSE);
1726 err = zfs_destroy_snaps_nvl(g_zfs, cb.cb_nvl,
1727 cb.cb_defer_destroy);
1733 } else if (pound != NULL) {
1738 (void) fprintf(stderr,
1739 "dryrun is not supported with bookmark\n");
1743 if (cb.cb_defer_destroy) {
1744 (void) fprintf(stderr,
1745 "defer destroy is not supported with bookmark\n");
1749 if (cb.cb_recurse) {
1750 (void) fprintf(stderr,
1751 "recursive is not supported with bookmark\n");
1756 * Unfortunately, zfs_bookmark() doesn't honor the
1757 * casesensitivity setting. However, we can't simply
1758 * remove this check, because lzc_destroy_bookmarks()
1759 * ignores non-existent bookmarks, so this is necessary
1760 * to get a proper error message.
1762 if (!zfs_bookmark_exists(argv[0])) {
1763 (void) fprintf(stderr, gettext("bookmark '%s' "
1764 "does not exist.\n"), argv[0]);
1768 nvl = fnvlist_alloc();
1769 fnvlist_add_boolean(nvl, argv[0]);
1771 err = lzc_destroy_bookmarks(nvl, NULL);
1773 (void) zfs_standard_error(g_zfs, err,
1774 "cannot destroy bookmark");
1781 /* Open the given dataset */
1782 if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1788 * Perform an explicit check for pools before going any further.
1790 if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1791 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1792 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1793 "operation does not apply to pools\n"),
1795 (void) fprintf(stderr, gettext("use 'zfs destroy -r "
1796 "%s' to destroy all datasets in the pool\n"),
1798 (void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1799 "to destroy the pool itself\n"), zfs_get_name(zhp));
1805 * Check for any dependents and/or clones.
1807 cb.cb_first = B_TRUE;
1808 if (!cb.cb_doclones &&
1809 zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
1819 cb.cb_batchedsnaps = fnvlist_alloc();
1820 if (zfs_iter_dependents(zhp, B_FALSE, destroy_callback,
1827 * Do the real thing. The callback will close the
1828 * handle regardless of whether it succeeds or not.
1830 err = destroy_callback(zhp, &cb);
1833 err = zfs_destroy_snaps_nvl(g_zfs,
1834 cb.cb_batchedsnaps, cb.cb_defer_destroy);
1836 if (err != 0 || cb.cb_error == B_TRUE)
1841 fnvlist_free(cb.cb_batchedsnaps);
1842 fnvlist_free(cb.cb_nvl);
1849 is_recvd_column(zprop_get_cbdata_t *cbp)
1852 zfs_get_column_t col;
1854 for (i = 0; i < ZFS_GET_NCOLS &&
1855 (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1856 if (col == GET_COL_RECVD)
1862 * zfs get [-rHp] [-o all | field[,field]...] [-s source[,source]...]
1863 * < all | property[,property]... > < fs | snap | vol > ...
1865 * -r recurse over any child datasets
1866 * -H scripted mode. Headers are stripped, and fields are separated
1867 * by tabs instead of spaces.
1868 * -o Set of fields to display. One of "name,property,value,
1869 * received,source". Default is "name,property,value,source".
1870 * "all" is an alias for all five.
1871 * -s Set of sources to allow. One of
1872 * "local,default,inherited,received,temporary,none". Default is
1874 * -p Display values in parsable (literal) format.
1876 * Prints properties for the given datasets. The user can control which
1877 * columns to display as well as which property types to allow.
1881 * Invoked to display the properties for a single dataset.
1884 get_callback(zfs_handle_t *zhp, void *data)
1886 char buf[ZFS_MAXPROPLEN];
1887 char rbuf[ZFS_MAXPROPLEN];
1888 zprop_source_t sourcetype;
1889 char source[ZFS_MAX_DATASET_NAME_LEN];
1890 zprop_get_cbdata_t *cbp = data;
1891 nvlist_t *user_props = zfs_get_user_props(zhp);
1892 zprop_list_t *pl = cbp->cb_proplist;
1896 boolean_t received = is_recvd_column(cbp);
1898 for (; pl != NULL; pl = pl->pl_next) {
1899 char *recvdval = NULL;
1901 * Skip the special fake placeholder. This will also skip over
1902 * the name property when 'all' is specified.
1904 if (pl->pl_prop == ZFS_PROP_NAME &&
1905 pl == cbp->cb_proplist)
1908 if (pl->pl_prop != ZPROP_INVAL) {
1909 if (zfs_prop_get(zhp, pl->pl_prop, buf,
1910 sizeof (buf), &sourcetype, source,
1912 cbp->cb_literal) != 0) {
1915 if (!zfs_prop_valid_for_type(pl->pl_prop,
1916 ZFS_TYPE_DATASET, B_FALSE)) {
1917 (void) fprintf(stderr,
1918 gettext("No such property '%s'\n"),
1919 zfs_prop_to_name(pl->pl_prop));
1922 sourcetype = ZPROP_SRC_NONE;
1923 (void) strlcpy(buf, "-", sizeof (buf));
1926 if (received && (zfs_prop_get_recvd(zhp,
1927 zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
1928 cbp->cb_literal) == 0))
1931 zprop_print_one_property(zfs_get_name(zhp), cbp,
1932 zfs_prop_to_name(pl->pl_prop),
1933 buf, sourcetype, source, recvdval);
1934 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
1935 sourcetype = ZPROP_SRC_LOCAL;
1937 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1938 buf, sizeof (buf), cbp->cb_literal) != 0) {
1939 sourcetype = ZPROP_SRC_NONE;
1940 (void) strlcpy(buf, "-", sizeof (buf));
1943 zprop_print_one_property(zfs_get_name(zhp), cbp,
1944 pl->pl_user_prop, buf, sourcetype, source, NULL);
1945 } else if (zfs_prop_written(pl->pl_user_prop)) {
1946 sourcetype = ZPROP_SRC_LOCAL;
1948 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
1949 buf, sizeof (buf), cbp->cb_literal) != 0) {
1950 sourcetype = ZPROP_SRC_NONE;
1951 (void) strlcpy(buf, "-", sizeof (buf));
1954 zprop_print_one_property(zfs_get_name(zhp), cbp,
1955 pl->pl_user_prop, buf, sourcetype, source, NULL);
1957 if (nvlist_lookup_nvlist(user_props,
1958 pl->pl_user_prop, &propval) != 0) {
1961 sourcetype = ZPROP_SRC_NONE;
1964 verify(nvlist_lookup_string(propval,
1965 ZPROP_VALUE, &strval) == 0);
1966 verify(nvlist_lookup_string(propval,
1967 ZPROP_SOURCE, &sourceval) == 0);
1969 if (strcmp(sourceval,
1970 zfs_get_name(zhp)) == 0) {
1971 sourcetype = ZPROP_SRC_LOCAL;
1972 } else if (strcmp(sourceval,
1973 ZPROP_SOURCE_VAL_RECVD) == 0) {
1974 sourcetype = ZPROP_SRC_RECEIVED;
1976 sourcetype = ZPROP_SRC_INHERITED;
1977 (void) strlcpy(source,
1978 sourceval, sizeof (source));
1982 if (received && (zfs_prop_get_recvd(zhp,
1983 pl->pl_user_prop, rbuf, sizeof (rbuf),
1984 cbp->cb_literal) == 0))
1987 zprop_print_one_property(zfs_get_name(zhp), cbp,
1988 pl->pl_user_prop, strval, sourcetype,
1997 zfs_do_get(int argc, char **argv)
1999 zprop_get_cbdata_t cb = { 0 };
2000 int i, c, flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2001 int types = ZFS_TYPE_DATASET | ZFS_TYPE_BOOKMARK;
2002 char *value, *fields;
2005 zprop_list_t fake_name = { 0 };
2008 * Set up default columns and sources.
2010 cb.cb_sources = ZPROP_SRC_ALL;
2011 cb.cb_columns[0] = GET_COL_NAME;
2012 cb.cb_columns[1] = GET_COL_PROPERTY;
2013 cb.cb_columns[2] = GET_COL_VALUE;
2014 cb.cb_columns[3] = GET_COL_SOURCE;
2015 cb.cb_type = ZFS_TYPE_DATASET;
2018 while ((c = getopt(argc, argv, ":d:o:s:rt:Hp")) != -1) {
2021 cb.cb_literal = B_TRUE;
2024 limit = parse_depth(optarg, &flags);
2027 flags |= ZFS_ITER_RECURSE;
2030 cb.cb_scripted = B_TRUE;
2033 (void) fprintf(stderr, gettext("missing argument for "
2034 "'%c' option\n"), optopt);
2039 * Process the set of columns to display. We zero out
2040 * the structure to give us a blank slate.
2042 bzero(&cb.cb_columns, sizeof (cb.cb_columns));
2044 while (*optarg != '\0') {
2045 static char *col_subopts[] =
2046 { "name", "property", "value", "received",
2047 "source", "all", NULL };
2049 if (i == ZFS_GET_NCOLS) {
2050 (void) fprintf(stderr, gettext("too "
2051 "many fields given to -o "
2056 switch (getsubopt(&optarg, col_subopts,
2059 cb.cb_columns[i++] = GET_COL_NAME;
2062 cb.cb_columns[i++] = GET_COL_PROPERTY;
2065 cb.cb_columns[i++] = GET_COL_VALUE;
2068 cb.cb_columns[i++] = GET_COL_RECVD;
2069 flags |= ZFS_ITER_RECVD_PROPS;
2072 cb.cb_columns[i++] = GET_COL_SOURCE;
2076 (void) fprintf(stderr,
2077 gettext("\"all\" conflicts "
2078 "with specific fields "
2079 "given to -o option\n"));
2082 cb.cb_columns[0] = GET_COL_NAME;
2083 cb.cb_columns[1] = GET_COL_PROPERTY;
2084 cb.cb_columns[2] = GET_COL_VALUE;
2085 cb.cb_columns[3] = GET_COL_RECVD;
2086 cb.cb_columns[4] = GET_COL_SOURCE;
2087 flags |= ZFS_ITER_RECVD_PROPS;
2091 (void) fprintf(stderr,
2092 gettext("invalid column name "
2101 while (*optarg != '\0') {
2102 static char *source_subopts[] = {
2103 "local", "default", "inherited",
2104 "received", "temporary", "none",
2107 switch (getsubopt(&optarg, source_subopts,
2110 cb.cb_sources |= ZPROP_SRC_LOCAL;
2113 cb.cb_sources |= ZPROP_SRC_DEFAULT;
2116 cb.cb_sources |= ZPROP_SRC_INHERITED;
2119 cb.cb_sources |= ZPROP_SRC_RECEIVED;
2122 cb.cb_sources |= ZPROP_SRC_TEMPORARY;
2125 cb.cb_sources |= ZPROP_SRC_NONE;
2128 (void) fprintf(stderr,
2129 gettext("invalid source "
2138 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
2139 while (*optarg != '\0') {
2140 static char *type_subopts[] = { "filesystem",
2141 "volume", "snapshot", "snap", "bookmark",
2144 switch (getsubopt(&optarg, type_subopts,
2147 types |= ZFS_TYPE_FILESYSTEM;
2150 types |= ZFS_TYPE_VOLUME;
2154 types |= ZFS_TYPE_SNAPSHOT;
2157 types |= ZFS_TYPE_BOOKMARK;
2160 types = ZFS_TYPE_DATASET |
2165 (void) fprintf(stderr,
2166 gettext("invalid type '%s'\n"),
2174 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2184 (void) fprintf(stderr, gettext("missing property "
2192 * Handle users who want to get all snapshots or bookmarks
2193 * of a dataset (ex. 'zfs get -t snapshot refer <dataset>').
2195 if ((types == ZFS_TYPE_SNAPSHOT || types == ZFS_TYPE_BOOKMARK) &&
2196 argc > 1 && (flags & ZFS_ITER_RECURSE) == 0 && limit == 0) {
2197 flags |= (ZFS_ITER_DEPTH_LIMIT | ZFS_ITER_RECURSE);
2201 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
2209 * As part of zfs_expand_proplist(), we keep track of the maximum column
2210 * width for each property. For the 'NAME' (and 'SOURCE') columns, we
2211 * need to know the maximum name length. However, the user likely did
2212 * not specify 'name' as one of the properties to fetch, so we need to
2213 * make sure we always include at least this property for
2214 * print_get_headers() to work properly.
2216 if (cb.cb_proplist != NULL) {
2217 fake_name.pl_prop = ZFS_PROP_NAME;
2218 fake_name.pl_width = strlen(gettext("NAME"));
2219 fake_name.pl_next = cb.cb_proplist;
2220 cb.cb_proplist = &fake_name;
2223 cb.cb_first = B_TRUE;
2225 /* run for each object */
2226 ret = zfs_for_each(argc, argv, flags, types, NULL,
2227 &cb.cb_proplist, limit, get_callback, &cb);
2229 if (cb.cb_proplist == &fake_name)
2230 zprop_free_list(fake_name.pl_next);
2232 zprop_free_list(cb.cb_proplist);
2238 * inherit [-rS] <property> <fs|vol> ...
2240 * -r Recurse over all children
2241 * -S Revert to received value, if any
2243 * For each dataset specified on the command line, inherit the given property
2244 * from its parent. Inheriting a property at the pool level will cause it to
2245 * use the default value. The '-r' flag will recurse over all children, and is
2246 * useful for setting a property on a hierarchy-wide basis, regardless of any
2247 * local modifications for each dataset.
2250 typedef struct inherit_cbdata {
2251 const char *cb_propname;
2252 boolean_t cb_received;
2256 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
2258 inherit_cbdata_t *cb = data;
2259 zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
2262 * If we're doing it recursively, then ignore properties that
2263 * are not valid for this type of dataset.
2265 if (prop != ZPROP_INVAL &&
2266 !zfs_prop_valid_for_type(prop, zfs_get_type(zhp), B_FALSE))
2269 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
2273 inherit_cb(zfs_handle_t *zhp, void *data)
2275 inherit_cbdata_t *cb = data;
2277 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
2281 zfs_do_inherit(int argc, char **argv)
2285 inherit_cbdata_t cb = { 0 };
2289 boolean_t received = B_FALSE;
2292 while ((c = getopt(argc, argv, "rS")) != -1) {
2295 flags |= ZFS_ITER_RECURSE;
2302 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2311 /* check number of arguments */
2313 (void) fprintf(stderr, gettext("missing property argument\n"));
2317 (void) fprintf(stderr, gettext("missing dataset argument\n"));
2325 if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
2326 if (zfs_prop_readonly(prop)) {
2327 (void) fprintf(stderr, gettext(
2328 "%s property is read-only\n"),
2332 if (!zfs_prop_inheritable(prop) && !received) {
2333 (void) fprintf(stderr, gettext("'%s' property cannot "
2334 "be inherited\n"), propname);
2335 if (prop == ZFS_PROP_QUOTA ||
2336 prop == ZFS_PROP_RESERVATION ||
2337 prop == ZFS_PROP_REFQUOTA ||
2338 prop == ZFS_PROP_REFRESERVATION) {
2339 (void) fprintf(stderr, gettext("use 'zfs set "
2340 "%s=none' to clear\n"), propname);
2341 (void) fprintf(stderr, gettext("use 'zfs "
2342 "inherit -S %s' to revert to received "
2343 "value\n"), propname);
2347 if (received && (prop == ZFS_PROP_VOLSIZE ||
2348 prop == ZFS_PROP_VERSION)) {
2349 (void) fprintf(stderr, gettext("'%s' property cannot "
2350 "be reverted to a received value\n"), propname);
2353 } else if (!zfs_prop_user(propname)) {
2354 (void) fprintf(stderr, gettext("invalid property '%s'\n"),
2359 cb.cb_propname = propname;
2360 cb.cb_received = received;
2362 if (flags & ZFS_ITER_RECURSE) {
2363 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
2364 NULL, NULL, 0, inherit_recurse_cb, &cb);
2366 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
2367 NULL, NULL, 0, inherit_cb, &cb);
2373 typedef struct upgrade_cbdata {
2374 uint64_t cb_numupgraded;
2375 uint64_t cb_numsamegraded;
2376 uint64_t cb_numfailed;
2377 uint64_t cb_version;
2379 boolean_t cb_foundone;
2380 char cb_lastfs[ZFS_MAX_DATASET_NAME_LEN];
2384 same_pool(zfs_handle_t *zhp, const char *name)
2386 int len1 = strcspn(name, "/@");
2387 const char *zhname = zfs_get_name(zhp);
2388 int len2 = strcspn(zhname, "/@");
2392 return (strncmp(name, zhname, len1) == 0);
2396 upgrade_list_callback(zfs_handle_t *zhp, void *data)
2398 upgrade_cbdata_t *cb = data;
2399 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2401 /* list if it's old/new */
2402 if ((!cb->cb_newer && version < ZPL_VERSION) ||
2403 (cb->cb_newer && version > ZPL_VERSION)) {
2406 str = gettext("The following filesystems are "
2407 "formatted using a newer software version and\n"
2408 "cannot be accessed on the current system.\n\n");
2410 str = gettext("The following filesystems are "
2411 "out of date, and can be upgraded. After being\n"
2412 "upgraded, these filesystems (and any 'zfs send' "
2413 "streams generated from\n"
2414 "subsequent snapshots) will no longer be "
2415 "accessible by older software versions.\n\n");
2418 if (!cb->cb_foundone) {
2420 (void) printf(gettext("VER FILESYSTEM\n"));
2421 (void) printf(gettext("--- ------------\n"));
2422 cb->cb_foundone = B_TRUE;
2425 (void) printf("%2u %s\n", version, zfs_get_name(zhp));
2432 upgrade_set_callback(zfs_handle_t *zhp, void *data)
2434 upgrade_cbdata_t *cb = data;
2435 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2436 int needed_spa_version;
2439 if (zfs_spa_version(zhp, &spa_version) < 0)
2442 needed_spa_version = zfs_spa_version_map(cb->cb_version);
2444 if (needed_spa_version < 0)
2447 if (spa_version < needed_spa_version) {
2449 (void) printf(gettext("%s: can not be "
2450 "upgraded; the pool version needs to first "
2451 "be upgraded\nto version %d\n\n"),
2452 zfs_get_name(zhp), needed_spa_version);
2458 if (version < cb->cb_version) {
2460 (void) snprintf(verstr, sizeof (verstr),
2461 "%llu", (u_longlong_t)cb->cb_version);
2462 if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
2464 * If they did "zfs upgrade -a", then we could
2465 * be doing ioctls to different pools. We need
2466 * to log this history once to each pool, and bypass
2467 * the normal history logging that happens in main().
2469 (void) zpool_log_history(g_zfs, history_str);
2470 log_history = B_FALSE;
2472 if (zfs_prop_set(zhp, "version", verstr) == 0)
2473 cb->cb_numupgraded++;
2476 (void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
2477 } else if (version > cb->cb_version) {
2478 /* can't downgrade */
2479 (void) printf(gettext("%s: can not be downgraded; "
2480 "it is already at version %u\n"),
2481 zfs_get_name(zhp), version);
2484 cb->cb_numsamegraded++;
2492 * zfs upgrade [-r] [-V <version>] <-a | filesystem>
2495 zfs_do_upgrade(int argc, char **argv)
2497 boolean_t all = B_FALSE;
2498 boolean_t showversions = B_FALSE;
2500 upgrade_cbdata_t cb = { 0 };
2502 int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2505 while ((c = getopt(argc, argv, "rvV:a")) != -1) {
2508 flags |= ZFS_ITER_RECURSE;
2511 showversions = B_TRUE;
2514 if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
2515 optarg, &cb.cb_version) != 0) {
2516 (void) fprintf(stderr,
2517 gettext("invalid version %s\n"), optarg);
2526 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2535 if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
2537 if (showversions && (flags & ZFS_ITER_RECURSE || all ||
2538 cb.cb_version || argc))
2540 if ((all || argc) && (showversions))
2546 /* Show info on available versions. */
2547 (void) printf(gettext("The following filesystem versions are "
2549 (void) printf(gettext("VER DESCRIPTION\n"));
2550 (void) printf("--- -----------------------------------------"
2551 "---------------\n");
2552 (void) printf(gettext(" 1 Initial ZFS filesystem version\n"));
2553 (void) printf(gettext(" 2 Enhanced directory entries\n"));
2554 (void) printf(gettext(" 3 Case insensitive and filesystem "
2555 "user identifier (FUID)\n"));
2556 (void) printf(gettext(" 4 userquota, groupquota "
2558 (void) printf(gettext(" 5 System attributes\n"));
2559 (void) printf(gettext("\nFor more information on a particular "
2560 "version, including supported releases,\n"));
2561 (void) printf("see the ZFS Administration Guide.\n\n");
2563 } else if (argc || all) {
2564 /* Upgrade filesystems */
2565 if (cb.cb_version == 0)
2566 cb.cb_version = ZPL_VERSION;
2567 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
2568 NULL, NULL, 0, upgrade_set_callback, &cb);
2569 (void) printf(gettext("%llu filesystems upgraded\n"),
2570 (u_longlong_t)cb.cb_numupgraded);
2571 if (cb.cb_numsamegraded) {
2572 (void) printf(gettext("%llu filesystems already at "
2574 (u_longlong_t)cb.cb_numsamegraded);
2576 if (cb.cb_numfailed != 0)
2579 /* List old-version filesystems */
2581 (void) printf(gettext("This system is currently running "
2582 "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
2584 flags |= ZFS_ITER_RECURSE;
2585 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2586 NULL, NULL, 0, upgrade_list_callback, &cb);
2588 found = cb.cb_foundone;
2589 cb.cb_foundone = B_FALSE;
2590 cb.cb_newer = B_TRUE;
2592 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2593 NULL, NULL, 0, upgrade_list_callback, &cb);
2595 if (!cb.cb_foundone && !found) {
2596 (void) printf(gettext("All filesystems are "
2597 "formatted with the current version.\n"));
2605 * zfs userspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2606 * [-S field [-S field]...] [-t type[,...]]
2607 * filesystem | snapshot | path
2608 * zfs groupspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2609 * [-S field [-S field]...] [-t type[,...]]
2610 * filesystem | snapshot | path
2611 * zfs projectspace [-Hp] [-o field[,...]] [-s field [-s field]...]
2612 * [-S field [-S field]...] filesystem | snapshot | path
2614 * -H Scripted mode; elide headers and separate columns by tabs.
2615 * -i Translate SID to POSIX ID.
2616 * -n Print numeric ID instead of user/group name.
2617 * -o Control which fields to display.
2618 * -p Use exact (parsable) numeric output.
2619 * -s Specify sort columns, descending order.
2620 * -S Specify sort columns, ascending order.
2621 * -t Control which object types to display.
2623 * Displays space consumed by, and quotas on, each user in the specified
2624 * filesystem or snapshot.
2627 /* us_field_types, us_field_hdr and us_field_names should be kept in sync */
2628 enum us_field_types {
2636 static char *us_field_hdr[] = { "TYPE", "NAME", "USED", "QUOTA",
2637 "OBJUSED", "OBJQUOTA" };
2638 static char *us_field_names[] = { "type", "name", "used", "quota",
2639 "objused", "objquota" };
2640 #define USFIELD_LAST (sizeof (us_field_names) / sizeof (char *))
2642 #define USTYPE_PSX_GRP (1 << 0)
2643 #define USTYPE_PSX_USR (1 << 1)
2644 #define USTYPE_SMB_GRP (1 << 2)
2645 #define USTYPE_SMB_USR (1 << 3)
2646 #define USTYPE_PROJ (1 << 4)
2647 #define USTYPE_ALL \
2648 (USTYPE_PSX_GRP | USTYPE_PSX_USR | USTYPE_SMB_GRP | USTYPE_SMB_USR | \
2651 static int us_type_bits[] = {
2658 static char *us_type_names[] = { "posixgroup", "posixuser", "smbgroup",
2661 typedef struct us_node {
2663 uu_avl_node_t usn_avlnode;
2664 uu_list_node_t usn_listnode;
2667 typedef struct us_cbdata {
2669 uu_avl_pool_t *cb_avl_pool;
2671 boolean_t cb_numname;
2672 boolean_t cb_nicenum;
2673 boolean_t cb_sid2posix;
2674 zfs_userquota_prop_t cb_prop;
2675 zfs_sort_column_t *cb_sortcol;
2676 size_t cb_width[USFIELD_LAST];
2679 static boolean_t us_populated = B_FALSE;
2682 zfs_sort_column_t *si_sortcol;
2683 boolean_t si_numname;
2687 us_field_index(char *field)
2691 for (i = 0; i < USFIELD_LAST; i++) {
2692 if (strcmp(field, us_field_names[i]) == 0)
2700 us_compare(const void *larg, const void *rarg, void *unused)
2702 const us_node_t *l = larg;
2703 const us_node_t *r = rarg;
2704 us_sort_info_t *si = (us_sort_info_t *)unused;
2705 zfs_sort_column_t *sortcol = si->si_sortcol;
2706 boolean_t numname = si->si_numname;
2707 nvlist_t *lnvl = l->usn_nvl;
2708 nvlist_t *rnvl = r->usn_nvl;
2712 for (; sortcol != NULL; sortcol = sortcol->sc_next) {
2719 zfs_prop_t prop = sortcol->sc_prop;
2720 const char *propname = NULL;
2721 boolean_t reverse = sortcol->sc_reverse;
2726 (void) nvlist_lookup_uint32(lnvl, propname, &lv32);
2727 (void) nvlist_lookup_uint32(rnvl, propname, &rv32);
2729 rc = (rv32 < lv32) ? 1 : -1;
2735 (void) nvlist_lookup_uint64(lnvl, propname,
2737 (void) nvlist_lookup_uint64(rnvl, propname,
2740 rc = (rv64 < lv64) ? 1 : -1;
2742 if ((nvlist_lookup_string(lnvl, propname,
2743 &lvstr) == ENOENT) ||
2744 (nvlist_lookup_string(rnvl, propname,
2745 &rvstr) == ENOENT)) {
2748 rc = strcmp(lvstr, rvstr);
2752 case ZFS_PROP_QUOTA:
2755 if (prop == ZFS_PROP_USED)
2759 (void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2760 (void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2762 rc = (rv64 < lv64) ? 1 : -1;
2771 return (reverse ? 1 : -1);
2773 return (reverse ? -1 : 1);
2778 * If entries still seem to be the same, check if they are of the same
2779 * type (smbentity is added only if we are doing SID to POSIX ID
2780 * translation where we can have duplicate type/name combinations).
2782 if (nvlist_lookup_boolean_value(lnvl, "smbentity", &lvb) == 0 &&
2783 nvlist_lookup_boolean_value(rnvl, "smbentity", &rvb) == 0 &&
2785 return (lvb < rvb ? -1 : 1);
2791 zfs_prop_is_user(unsigned p)
2793 return (p == ZFS_PROP_USERUSED || p == ZFS_PROP_USERQUOTA ||
2794 p == ZFS_PROP_USEROBJUSED || p == ZFS_PROP_USEROBJQUOTA);
2798 zfs_prop_is_group(unsigned p)
2800 return (p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA ||
2801 p == ZFS_PROP_GROUPOBJUSED || p == ZFS_PROP_GROUPOBJQUOTA);
2805 zfs_prop_is_project(unsigned p)
2807 return (p == ZFS_PROP_PROJECTUSED || p == ZFS_PROP_PROJECTQUOTA ||
2808 p == ZFS_PROP_PROJECTOBJUSED || p == ZFS_PROP_PROJECTOBJQUOTA);
2811 static inline const char *
2812 us_type2str(unsigned field_type)
2814 switch (field_type) {
2815 case USTYPE_PSX_USR:
2816 return ("POSIX User");
2817 case USTYPE_PSX_GRP:
2818 return ("POSIX Group");
2819 case USTYPE_SMB_USR:
2820 return ("SMB User");
2821 case USTYPE_SMB_GRP:
2822 return ("SMB Group");
2826 return ("Undefined");
2831 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2833 us_cbdata_t *cb = (us_cbdata_t *)arg;
2834 zfs_userquota_prop_t prop = cb->cb_prop;
2839 uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2840 uu_avl_t *avl = cb->cb_avl;
2844 zfs_sort_column_t *sortcol = cb->cb_sortcol;
2846 const char *typestr;
2850 int typeidx, nameidx, sizeidx;
2851 us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
2852 boolean_t smbentity = B_FALSE;
2854 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
2856 node = safe_malloc(sizeof (us_node_t));
2857 uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
2858 node->usn_nvl = props;
2860 if (domain != NULL && domain[0] != '\0') {
2863 char sid[MAXNAMELEN + 32];
2867 directory_error_t e;
2871 (void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
2873 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2874 type = USTYPE_SMB_GRP;
2875 err = sid_to_id(sid, B_FALSE, &id);
2877 type = USTYPE_SMB_USR;
2878 err = sid_to_id(sid, B_TRUE, &id);
2883 if (!cb->cb_sid2posix) {
2884 e = directory_name_from_sid(NULL, sid, &name,
2887 directory_error_free(e);
2897 #endif /* HAVE_IDMAP */
2900 if (cb->cb_sid2posix || domain == NULL || domain[0] == '\0') {
2902 if (zfs_prop_is_group(prop)) {
2903 type = USTYPE_PSX_GRP;
2904 if (!cb->cb_numname) {
2907 if ((g = getgrgid(rid)) != NULL)
2910 } else if (zfs_prop_is_user(prop)) {
2911 type = USTYPE_PSX_USR;
2912 if (!cb->cb_numname) {
2915 if ((p = getpwuid(rid)) != NULL)
2924 * Make sure that the type/name combination is unique when doing
2925 * SID to POSIX ID translation (hence changing the type from SMB to
2928 if (cb->cb_sid2posix &&
2929 nvlist_add_boolean_value(props, "smbentity", smbentity) != 0)
2932 /* Calculate/update width of TYPE field */
2933 typestr = us_type2str(type);
2934 typelen = strlen(gettext(typestr));
2935 typeidx = us_field_index("type");
2936 if (typelen > cb->cb_width[typeidx])
2937 cb->cb_width[typeidx] = typelen;
2938 if (nvlist_add_uint32(props, "type", type) != 0)
2941 /* Calculate/update width of NAME field */
2942 if ((cb->cb_numname && cb->cb_sid2posix) || name == NULL) {
2943 if (nvlist_add_uint64(props, "name", rid) != 0)
2945 namelen = snprintf(NULL, 0, "%u", rid);
2947 if (nvlist_add_string(props, "name", name) != 0)
2949 namelen = strlen(name);
2951 nameidx = us_field_index("name");
2952 if (nameidx >= 0 && namelen > cb->cb_width[nameidx])
2953 cb->cb_width[nameidx] = namelen;
2956 * Check if this type/name combination is in the list and update it;
2957 * otherwise add new node to the list.
2959 if ((n = uu_avl_find(avl, node, &sortinfo, &idx)) == NULL) {
2960 uu_avl_insert(avl, node, idx);
2965 props = node->usn_nvl;
2968 /* Calculate/update width of USED/QUOTA fields */
2969 if (cb->cb_nicenum) {
2970 if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED ||
2971 prop == ZFS_PROP_USERQUOTA || prop == ZFS_PROP_GROUPQUOTA ||
2972 prop == ZFS_PROP_PROJECTUSED ||
2973 prop == ZFS_PROP_PROJECTQUOTA) {
2974 zfs_nicebytes(space, sizebuf, sizeof (sizebuf));
2976 zfs_nicenum(space, sizebuf, sizeof (sizebuf));
2979 (void) snprintf(sizebuf, sizeof (sizebuf), "%llu",
2980 (u_longlong_t)space);
2982 sizelen = strlen(sizebuf);
2983 if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED ||
2984 prop == ZFS_PROP_PROJECTUSED) {
2986 if (!nvlist_exists(props, "quota"))
2987 (void) nvlist_add_uint64(props, "quota", 0);
2988 } else if (prop == ZFS_PROP_USERQUOTA || prop == ZFS_PROP_GROUPQUOTA ||
2989 prop == ZFS_PROP_PROJECTQUOTA) {
2991 if (!nvlist_exists(props, "used"))
2992 (void) nvlist_add_uint64(props, "used", 0);
2993 } else if (prop == ZFS_PROP_USEROBJUSED ||
2994 prop == ZFS_PROP_GROUPOBJUSED || prop == ZFS_PROP_PROJECTOBJUSED) {
2995 propname = "objused";
2996 if (!nvlist_exists(props, "objquota"))
2997 (void) nvlist_add_uint64(props, "objquota", 0);
2998 } else if (prop == ZFS_PROP_USEROBJQUOTA ||
2999 prop == ZFS_PROP_GROUPOBJQUOTA ||
3000 prop == ZFS_PROP_PROJECTOBJQUOTA) {
3001 propname = "objquota";
3002 if (!nvlist_exists(props, "objused"))
3003 (void) nvlist_add_uint64(props, "objused", 0);
3007 sizeidx = us_field_index(propname);
3008 if (sizeidx >= 0 && sizelen > cb->cb_width[sizeidx])
3009 cb->cb_width[sizeidx] = sizelen;
3011 if (nvlist_add_uint64(props, propname, space) != 0)
3018 print_us_node(boolean_t scripted, boolean_t parsable, int *fields, int types,
3019 size_t *width, us_node_t *node)
3021 nvlist_t *nvl = node->usn_nvl;
3022 char valstr[MAXNAMELEN];
3023 boolean_t first = B_TRUE;
3029 (void) nvlist_lookup_uint32(nvl, "type", &ustype);
3030 if (!(ustype & types))
3033 while ((field = fields[cfield]) != USFIELD_LAST) {
3034 nvpair_t *nvp = NULL;
3040 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
3041 if (strcmp(nvpair_name(nvp),
3042 us_field_names[field]) == 0)
3046 type = nvp == NULL ? DATA_TYPE_UNKNOWN : nvpair_type(nvp);
3048 case DATA_TYPE_UINT32:
3049 (void) nvpair_value_uint32(nvp, &val32);
3051 case DATA_TYPE_UINT64:
3052 (void) nvpair_value_uint64(nvp, &val64);
3054 case DATA_TYPE_STRING:
3055 (void) nvpair_value_string(nvp, &strval);
3057 case DATA_TYPE_UNKNOWN:
3060 (void) fprintf(stderr, "invalid data type\n");
3065 if (type == DATA_TYPE_UINT32)
3066 strval = (char *)us_type2str(val32);
3069 if (type == DATA_TYPE_UINT64) {
3070 (void) sprintf(valstr, "%llu",
3071 (u_longlong_t)val64);
3077 if (type == DATA_TYPE_UINT64) {
3079 (void) sprintf(valstr, "%llu",
3080 (u_longlong_t)val64);
3082 } else if (field == USFIELD_QUOTA &&
3086 zfs_nicebytes(val64, valstr,
3092 case USFIELD_OBJUSED:
3093 case USFIELD_OBJQUOTA:
3094 if (type == DATA_TYPE_UINT64) {
3096 (void) sprintf(valstr, "%llu",
3097 (u_longlong_t)val64);
3099 } else if (field == USFIELD_OBJQUOTA &&
3103 zfs_nicenum(val64, valstr,
3113 (void) printf("\t");
3118 (void) printf("%s", strval);
3119 else if (field == USFIELD_TYPE || field == USFIELD_NAME)
3120 (void) printf("%-*s", (int)width[field], strval);
3122 (void) printf("%*s", (int)width[field], strval);
3128 (void) printf("\n");
3132 print_us(boolean_t scripted, boolean_t parsable, int *fields, int types,
3133 size_t *width, boolean_t rmnode, uu_avl_t *avl)
3141 boolean_t first = B_TRUE;
3143 while ((field = fields[cfield]) != USFIELD_LAST) {
3144 col = gettext(us_field_hdr[field]);
3145 if (field == USFIELD_TYPE || field == USFIELD_NAME) {
3146 (void) printf(first ? "%-*s" : " %-*s",
3147 (int)width[field], col);
3149 (void) printf(first ? "%*s" : " %*s",
3150 (int)width[field], col);
3155 (void) printf("\n");
3158 for (node = uu_avl_first(avl); node; node = uu_avl_next(avl, node)) {
3159 print_us_node(scripted, parsable, fields, types, width, node);
3161 nvlist_free(node->usn_nvl);
3166 zfs_do_userspace(int argc, char **argv)
3169 zfs_userquota_prop_t p;
3170 uu_avl_pool_t *avl_pool;
3172 uu_avl_walk_t *walk;
3174 char deffields[] = "type,name,used,quota,objused,objquota";
3175 char *ofield = NULL;
3176 char *tfield = NULL;
3180 boolean_t scripted = B_FALSE;
3181 boolean_t prtnum = B_FALSE;
3182 boolean_t parsable = B_FALSE;
3183 boolean_t sid2posix = B_FALSE;
3186 zfs_sort_column_t *sortcol = NULL;
3187 int types = USTYPE_PSX_USR | USTYPE_SMB_USR;
3191 uu_list_pool_t *listpool;
3193 uu_avl_index_t idx = 0;
3194 uu_list_index_t idx2 = 0;
3199 if (strcmp(argv[0], "groupspace") == 0) {
3200 /* Toggle default group types */
3201 types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
3202 } else if (strcmp(argv[0], "projectspace") == 0) {
3203 types = USTYPE_PROJ;
3207 while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
3210 if (types == USTYPE_PROJ) {
3211 (void) fprintf(stderr,
3212 gettext("invalid option 'n'\n"));
3228 if (zfs_add_sort_column(&sortcol, optarg,
3229 c == 's' ? B_FALSE : B_TRUE) != 0) {
3230 (void) fprintf(stderr,
3231 gettext("invalid field '%s'\n"), optarg);
3236 if (types == USTYPE_PROJ) {
3237 (void) fprintf(stderr,
3238 gettext("invalid option 't'\n"));
3244 if (types == USTYPE_PROJ) {
3245 (void) fprintf(stderr,
3246 gettext("invalid option 'i'\n"));
3252 (void) fprintf(stderr, gettext("missing argument for "
3253 "'%c' option\n"), optopt);
3257 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3267 (void) fprintf(stderr, gettext("missing dataset name\n"));
3271 (void) fprintf(stderr, gettext("too many arguments\n"));
3275 /* Use default output fields if not specified using -o */
3279 if ((delim = strchr(ofield, ',')) != NULL)
3281 if ((fields[cfield++] = us_field_index(ofield)) == -1) {
3282 (void) fprintf(stderr, gettext("invalid type '%s' "
3283 "for -o option\n"), ofield);
3288 } while (delim != NULL);
3289 fields[cfield] = USFIELD_LAST;
3291 /* Override output types (-t option) */
3292 if (tfield != NULL) {
3296 boolean_t found = B_FALSE;
3298 if ((delim = strchr(tfield, ',')) != NULL)
3300 for (i = 0; i < sizeof (us_type_bits) / sizeof (int);
3302 if (strcmp(tfield, us_type_names[i]) == 0) {
3304 types |= us_type_bits[i];
3309 (void) fprintf(stderr, gettext("invalid type "
3310 "'%s' for -t option\n"), tfield);
3315 } while (delim != NULL);
3318 if ((zhp = zfs_path_to_zhandle(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM |
3319 ZFS_TYPE_SNAPSHOT)) == NULL)
3321 if (zhp->zfs_head_type != ZFS_TYPE_FILESYSTEM) {
3322 (void) fprintf(stderr, gettext("operation is only applicable "
3323 "to filesystems and their snapshots\n"));
3328 if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
3329 offsetof(us_node_t, usn_avlnode), us_compare, UU_DEFAULT)) == NULL)
3331 if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
3334 /* Always add default sorting columns */
3335 (void) zfs_add_sort_column(&sortcol, "type", B_FALSE);
3336 (void) zfs_add_sort_column(&sortcol, "name", B_FALSE);
3338 cb.cb_sortcol = sortcol;
3339 cb.cb_numname = prtnum;
3340 cb.cb_nicenum = !parsable;
3341 cb.cb_avl_pool = avl_pool;
3342 cb.cb_avl = avl_tree;
3343 cb.cb_sid2posix = sid2posix;
3345 for (i = 0; i < USFIELD_LAST; i++)
3346 cb.cb_width[i] = strlen(gettext(us_field_hdr[i]));
3348 for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
3349 if ((zfs_prop_is_user(p) &&
3350 !(types & (USTYPE_PSX_USR | USTYPE_SMB_USR))) ||
3351 (zfs_prop_is_group(p) &&
3352 !(types & (USTYPE_PSX_GRP | USTYPE_SMB_GRP))) ||
3353 (zfs_prop_is_project(p) && types != USTYPE_PROJ))
3357 if ((ret = zfs_userspace(zhp, p, userspace_cb, &cb)) != 0) {
3365 if ((node = uu_avl_first(avl_tree)) == NULL)
3368 us_populated = B_TRUE;
3370 listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
3371 offsetof(us_node_t, usn_listnode), NULL, UU_DEFAULT);
3372 list = uu_list_create(listpool, NULL, UU_DEFAULT);
3373 uu_list_node_init(node, &node->usn_listnode, listpool);
3375 while (node != NULL) {
3377 node = uu_avl_next(avl_tree, node);
3378 uu_avl_remove(avl_tree, rmnode);
3379 if (uu_list_find(list, rmnode, NULL, &idx2) == NULL)
3380 uu_list_insert(list, rmnode, idx2);
3383 for (node = uu_list_first(list); node != NULL;
3384 node = uu_list_next(list, node)) {
3385 us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
3387 if (uu_avl_find(avl_tree, node, &sortinfo, &idx) == NULL)
3388 uu_avl_insert(avl_tree, node, idx);
3391 uu_list_destroy(list);
3392 uu_list_pool_destroy(listpool);
3394 /* Print and free node nvlist memory */
3395 print_us(scripted, parsable, fields, types, cb.cb_width, B_TRUE,
3398 zfs_free_sort_columns(sortcol);
3400 /* Clean up the AVL tree */
3401 if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
3404 while ((node = uu_avl_walk_next(walk)) != NULL) {
3405 uu_avl_remove(cb.cb_avl, node);
3409 uu_avl_walk_end(walk);
3410 uu_avl_destroy(avl_tree);
3411 uu_avl_pool_destroy(avl_pool);
3417 * list [-Hp][-r|-d max] [-o property[,...]] [-s property] ... [-S property]
3418 * [-t type[,...]] [filesystem|volume|snapshot] ...
3420 * -H Scripted mode; elide headers and separate columns by tabs
3421 * -p Display values in parsable (literal) format.
3422 * -r Recurse over all children
3423 * -d Limit recursion by depth.
3424 * -o Control which fields to display.
3425 * -s Specify sort columns, descending order.
3426 * -S Specify sort columns, ascending order.
3427 * -t Control which object types to display.
3429 * When given no arguments, list all filesystems in the system.
3430 * Otherwise, list the specified datasets, optionally recursing down them if
3431 * '-r' is specified.
3433 typedef struct list_cbdata {
3435 boolean_t cb_literal;
3436 boolean_t cb_scripted;
3437 zprop_list_t *cb_proplist;
3441 * Given a list of columns to display, output appropriate headers for each one.
3444 print_header(list_cbdata_t *cb)
3446 zprop_list_t *pl = cb->cb_proplist;
3447 char headerbuf[ZFS_MAXPROPLEN];
3450 boolean_t first = B_TRUE;
3451 boolean_t right_justify;
3453 for (; pl != NULL; pl = pl->pl_next) {
3460 right_justify = B_FALSE;
3461 if (pl->pl_prop != ZPROP_INVAL) {
3462 header = zfs_prop_column_name(pl->pl_prop);
3463 right_justify = zfs_prop_align_right(pl->pl_prop);
3465 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
3466 headerbuf[i] = toupper(pl->pl_user_prop[i]);
3467 headerbuf[i] = '\0';
3471 if (pl->pl_next == NULL && !right_justify)
3472 (void) printf("%s", header);
3473 else if (right_justify)
3474 (void) printf("%*s", (int)pl->pl_width, header);
3476 (void) printf("%-*s", (int)pl->pl_width, header);
3479 (void) printf("\n");
3483 * Given a dataset and a list of fields, print out all the properties according
3484 * to the described layout.
3487 print_dataset(zfs_handle_t *zhp, list_cbdata_t *cb)
3489 zprop_list_t *pl = cb->cb_proplist;
3490 boolean_t first = B_TRUE;
3491 char property[ZFS_MAXPROPLEN];
3492 nvlist_t *userprops = zfs_get_user_props(zhp);
3495 boolean_t right_justify;
3497 for (; pl != NULL; pl = pl->pl_next) {
3499 if (cb->cb_scripted)
3500 (void) printf("\t");
3507 if (pl->pl_prop == ZFS_PROP_NAME) {
3508 (void) strlcpy(property, zfs_get_name(zhp),
3511 right_justify = zfs_prop_align_right(pl->pl_prop);
3512 } else if (pl->pl_prop != ZPROP_INVAL) {
3513 if (zfs_prop_get(zhp, pl->pl_prop, property,
3514 sizeof (property), NULL, NULL, 0,
3515 cb->cb_literal) != 0)
3519 right_justify = zfs_prop_align_right(pl->pl_prop);
3520 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
3521 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
3522 property, sizeof (property), cb->cb_literal) != 0)
3526 right_justify = B_TRUE;
3527 } else if (zfs_prop_written(pl->pl_user_prop)) {
3528 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
3529 property, sizeof (property), cb->cb_literal) != 0)
3533 right_justify = B_TRUE;
3535 if (nvlist_lookup_nvlist(userprops,
3536 pl->pl_user_prop, &propval) != 0)
3539 verify(nvlist_lookup_string(propval,
3540 ZPROP_VALUE, &propstr) == 0);
3541 right_justify = B_FALSE;
3545 * If this is being called in scripted mode, or if this is the
3546 * last column and it is left-justified, don't include a width
3549 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
3550 (void) printf("%s", propstr);
3551 else if (right_justify)
3552 (void) printf("%*s", (int)pl->pl_width, propstr);
3554 (void) printf("%-*s", (int)pl->pl_width, propstr);
3557 (void) printf("\n");
3561 * Generic callback function to list a dataset or snapshot.
3564 list_callback(zfs_handle_t *zhp, void *data)
3566 list_cbdata_t *cbp = data;
3568 if (cbp->cb_first) {
3569 if (!cbp->cb_scripted)
3571 cbp->cb_first = B_FALSE;
3574 print_dataset(zhp, cbp);
3580 zfs_do_list(int argc, char **argv)
3583 static char default_fields[] =
3584 "name,used,available,referenced,mountpoint";
3585 int types = ZFS_TYPE_DATASET;
3586 boolean_t types_specified = B_FALSE;
3587 char *fields = NULL;
3588 list_cbdata_t cb = { 0 };
3592 zfs_sort_column_t *sortcol = NULL;
3593 int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
3596 while ((c = getopt(argc, argv, "HS:d:o:prs:t:")) != -1) {
3602 cb.cb_literal = B_TRUE;
3603 flags |= ZFS_ITER_LITERAL_PROPS;
3606 limit = parse_depth(optarg, &flags);
3609 flags |= ZFS_ITER_RECURSE;
3612 cb.cb_scripted = B_TRUE;
3615 if (zfs_add_sort_column(&sortcol, optarg,
3617 (void) fprintf(stderr,
3618 gettext("invalid property '%s'\n"), optarg);
3623 if (zfs_add_sort_column(&sortcol, optarg,
3625 (void) fprintf(stderr,
3626 gettext("invalid property '%s'\n"), optarg);
3632 types_specified = B_TRUE;
3633 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
3634 while (*optarg != '\0') {
3635 static char *type_subopts[] = { "filesystem",
3636 "volume", "snapshot", "snap", "bookmark",
3639 switch (getsubopt(&optarg, type_subopts,
3642 types |= ZFS_TYPE_FILESYSTEM;
3645 types |= ZFS_TYPE_VOLUME;
3649 types |= ZFS_TYPE_SNAPSHOT;
3652 types |= ZFS_TYPE_BOOKMARK;
3655 types = ZFS_TYPE_DATASET |
3659 (void) fprintf(stderr,
3660 gettext("invalid type '%s'\n"),
3667 (void) fprintf(stderr, gettext("missing argument for "
3668 "'%c' option\n"), optopt);
3672 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3682 fields = default_fields;
3685 * If we are only going to list snapshot names and sort by name,
3686 * then we can use faster version.
3688 if (strcmp(fields, "name") == 0 && zfs_sort_only_by_name(sortcol))
3689 flags |= ZFS_ITER_SIMPLE;
3692 * If "-o space" and no types were specified, don't display snapshots.
3694 if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3695 types &= ~ZFS_TYPE_SNAPSHOT;
3698 * Handle users who want to list all snapshots or bookmarks
3699 * of the current dataset (ex. 'zfs list -t snapshot <dataset>').
3701 if ((types == ZFS_TYPE_SNAPSHOT || types == ZFS_TYPE_BOOKMARK) &&
3702 argc > 0 && (flags & ZFS_ITER_RECURSE) == 0 && limit == 0) {
3703 flags |= (ZFS_ITER_DEPTH_LIMIT | ZFS_ITER_RECURSE);
3708 * If the user specifies '-o all', the zprop_get_list() doesn't
3709 * normally include the name of the dataset. For 'zfs list', we always
3710 * want this property to be first.
3712 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3716 cb.cb_first = B_TRUE;
3718 ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
3719 limit, list_callback, &cb);
3721 zprop_free_list(cb.cb_proplist);
3722 zfs_free_sort_columns(sortcol);
3724 if (ret == 0 && cb.cb_first && !cb.cb_scripted)
3725 (void) fprintf(stderr, gettext("no datasets available\n"));
3731 * zfs rename [-fu] <fs | snap | vol> <fs | snap | vol>
3732 * zfs rename [-f] -p <fs | vol> <fs | vol>
3733 * zfs rename [-u] -r <snap> <snap>
3735 * Renames the given dataset to another of the same type.
3737 * The '-p' flag creates all the non-existing ancestors of the target first.
3738 * The '-u' flag prevents file systems from being remounted during rename.
3742 zfs_do_rename(int argc, char **argv)
3745 renameflags_t flags = { 0 };
3749 boolean_t parents = B_FALSE;
3752 while ((c = getopt(argc, argv, "pruf")) != -1) {
3758 flags.recursive = B_TRUE;
3761 flags.nounmount = B_TRUE;
3764 flags.forceunmount = B_TRUE;
3768 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3777 /* check number of arguments */
3779 (void) fprintf(stderr, gettext("missing source dataset "
3784 (void) fprintf(stderr, gettext("missing target dataset "
3789 (void) fprintf(stderr, gettext("too many arguments\n"));
3793 if (flags.recursive && parents) {
3794 (void) fprintf(stderr, gettext("-p and -r options are mutually "
3799 if (flags.nounmount && parents) {
3800 (void) fprintf(stderr, gettext("-u and -p options are mutually "
3805 if (flags.recursive && strchr(argv[0], '@') == 0) {
3806 (void) fprintf(stderr, gettext("source dataset for recursive "
3807 "rename must be a snapshot\n"));
3811 if (flags.nounmount)
3812 types = ZFS_TYPE_FILESYSTEM;
3814 types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
3816 types = ZFS_TYPE_DATASET;
3818 if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL)
3821 /* If we were asked and the name looks good, try to create ancestors. */
3822 if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
3823 zfs_create_ancestors(g_zfs, argv[1]) != 0) {
3828 ret = (zfs_rename(zhp, argv[1], flags) != 0);
3837 * Promotes the given clone fs to be the parent
3841 zfs_do_promote(int argc, char **argv)
3847 if (argc > 1 && argv[1][0] == '-') {
3848 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3853 /* check number of arguments */
3855 (void) fprintf(stderr, gettext("missing clone filesystem"
3860 (void) fprintf(stderr, gettext("too many arguments\n"));
3864 zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3868 ret = (zfs_promote(zhp) != 0);
3876 zfs_do_redact(int argc, char **argv)
3879 char *bookname = NULL;
3880 char **rsnaps = NULL;
3885 (void) fprintf(stderr, gettext("too few arguments\n"));
3892 numrsnaps = argc - 2;
3894 nvlist_t *rsnapnv = fnvlist_alloc();
3896 for (int i = 0; i < numrsnaps; i++) {
3897 fnvlist_add_boolean(rsnapnv, rsnaps[i]);
3900 int err = lzc_redact(snap, bookname, rsnapnv);
3901 fnvlist_free(rsnapnv);
3907 (void) fprintf(stderr,
3908 gettext("provided snapshot %s does not exist\n"), snap);
3911 (void) fprintf(stderr, gettext("specified redaction bookmark "
3912 "(%s) provided already exists\n"), bookname);
3915 (void) fprintf(stderr, gettext("provided bookmark name cannot "
3916 "be used, final name would be too long\n"));
3919 (void) fprintf(stderr, gettext("too many redaction snapshots "
3923 if (strchr(bookname, '#') != NULL)
3924 (void) fprintf(stderr, gettext(
3925 "redaction bookmark name must not contain '#'\n"));
3927 (void) fprintf(stderr, gettext(
3928 "redaction snapshot must be descendent of "
3929 "snapshot being redacted\n"));
3932 (void) fprintf(stderr, gettext("attempted to redact redacted "
3933 "dataset or with respect to redacted dataset\n"));
3936 (void) fprintf(stderr, gettext("redaction bookmarks feature "
3940 (void) fprintf(stderr, gettext("potentially invalid redaction "
3941 "snapshot; full dataset names required\n"));
3944 (void) fprintf(stderr, gettext("internal error: %s\n"),
3952 * zfs rollback [-rRf] <snapshot>
3954 * -r Delete any intervening snapshots before doing rollback
3955 * -R Delete any snapshots and their clones
3956 * -f ignored for backwards compatibility
3958 * Given a filesystem, rollback to a specific snapshot, discarding any changes
3959 * since then and making it the active dataset. If more recent snapshots exist,
3960 * the command will complain unless the '-r' flag is given.
3962 typedef struct rollback_cbdata {
3964 uint8_t cb_younger_ds_printed;
3969 boolean_t cb_recurse;
3970 } rollback_cbdata_t;
3973 rollback_check_dependent(zfs_handle_t *zhp, void *data)
3975 rollback_cbdata_t *cbp = data;
3977 if (cbp->cb_first && cbp->cb_recurse) {
3978 (void) fprintf(stderr, gettext("cannot rollback to "
3979 "'%s': clones of previous snapshots exist\n"),
3981 (void) fprintf(stderr, gettext("use '-R' to "
3982 "force deletion of the following clones and "
3988 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
3996 * Report some snapshots/bookmarks more recent than the one specified.
3997 * Used when '-r' is not specified. We reuse this same callback for the
3998 * snapshot dependents - if 'cb_dependent' is set, then this is a
3999 * dependent and we should report it without checking the transaction group.
4002 rollback_check(zfs_handle_t *zhp, void *data)
4004 rollback_cbdata_t *cbp = data;
4006 * Max number of younger snapshots and/or bookmarks to display before
4007 * we stop the iteration.
4009 const uint8_t max_younger = 32;
4011 if (cbp->cb_doclones) {
4016 if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
4017 if (cbp->cb_first && !cbp->cb_recurse) {
4018 (void) fprintf(stderr, gettext("cannot "
4019 "rollback to '%s': more recent snapshots "
4020 "or bookmarks exist\n"),
4022 (void) fprintf(stderr, gettext("use '-r' to "
4023 "force deletion of the following "
4024 "snapshots and bookmarks:\n"));
4029 if (cbp->cb_recurse) {
4030 if (zfs_iter_dependents(zhp, B_TRUE,
4031 rollback_check_dependent, cbp) != 0) {
4036 (void) fprintf(stderr, "%s\n",
4038 cbp->cb_younger_ds_printed++;
4043 if (cbp->cb_younger_ds_printed == max_younger) {
4045 * This non-recursive rollback is going to fail due to the
4046 * presence of snapshots and/or bookmarks that are younger than
4047 * the rollback target.
4048 * We printed some of the offending objects, now we stop
4049 * zfs_iter_snapshot/bookmark iteration so we can fail fast and
4050 * avoid iterating over the rest of the younger objects
4052 (void) fprintf(stderr, gettext("Output limited to %d "
4053 "snapshots/bookmarks\n"), max_younger);
4060 zfs_do_rollback(int argc, char **argv)
4064 boolean_t force = B_FALSE;
4065 rollback_cbdata_t cb = { 0 };
4066 zfs_handle_t *zhp, *snap;
4067 char parentname[ZFS_MAX_DATASET_NAME_LEN];
4069 uint64_t min_txg = 0;
4072 while ((c = getopt(argc, argv, "rRf")) != -1) {
4085 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4094 /* check number of arguments */
4096 (void) fprintf(stderr, gettext("missing dataset argument\n"));
4100 (void) fprintf(stderr, gettext("too many arguments\n"));
4104 /* open the snapshot */
4105 if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
4108 /* open the parent dataset */
4109 (void) strlcpy(parentname, argv[0], sizeof (parentname));
4110 verify((delim = strrchr(parentname, '@')) != NULL);
4112 if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
4118 * Check for more recent snapshots and/or clones based on the presence
4121 cb.cb_target = argv[0];
4122 cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
4123 cb.cb_first = B_TRUE;
4126 if (cb.cb_create > 0)
4127 min_txg = cb.cb_create;
4129 if ((ret = zfs_iter_snapshots(zhp, B_FALSE, rollback_check, &cb,
4132 if ((ret = zfs_iter_bookmarks(zhp, rollback_check, &cb)) != 0)
4135 if ((ret = cb.cb_error) != 0)
4139 * Rollback parent to the given snapshot.
4141 ret = zfs_rollback(zhp, snap, force);
4154 * zfs set property=value ... { fs | snap | vol } ...
4156 * Sets the given properties for all datasets specified on the command line.
4160 set_callback(zfs_handle_t *zhp, void *data)
4162 nvlist_t *props = data;
4164 if (zfs_prop_set_list(zhp, props) != 0) {
4165 switch (libzfs_errno(g_zfs)) {
4166 case EZFS_MOUNTFAILED:
4167 (void) fprintf(stderr, gettext("property may be set "
4168 "but unable to remount filesystem\n"));
4170 case EZFS_SHARENFSFAILED:
4171 (void) fprintf(stderr, gettext("property may be set "
4172 "but unable to reshare filesystem\n"));
4181 zfs_do_set(int argc, char **argv)
4183 nvlist_t *props = NULL;
4184 int ds_start = -1; /* argv idx of first dataset arg */
4188 /* check for options */
4189 if (argc > 1 && argv[1][0] == '-') {
4190 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4195 /* check number of arguments */
4197 (void) fprintf(stderr, gettext("missing arguments\n"));
4201 if (strchr(argv[1], '=') == NULL) {
4202 (void) fprintf(stderr, gettext("missing property=value "
4205 (void) fprintf(stderr, gettext("missing dataset "
4211 /* validate argument order: prop=val args followed by dataset args */
4212 for (i = 1; i < argc; i++) {
4213 if (strchr(argv[i], '=') != NULL) {
4215 /* out-of-order prop=val argument */
4216 (void) fprintf(stderr, gettext("invalid "
4217 "argument order\n"));
4220 } else if (ds_start < 0) {
4225 (void) fprintf(stderr, gettext("missing dataset name(s)\n"));
4229 /* Populate a list of property settings */
4230 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
4232 for (i = 1; i < ds_start; i++) {
4233 if (!parseprop(props, argv[i])) {
4239 ret = zfs_for_each(argc - ds_start, argv + ds_start, 0,
4240 ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, props);
4247 typedef struct snap_cbdata {
4249 boolean_t sd_recursive;
4250 const char *sd_snapname;
4254 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
4256 snap_cbdata_t *sd = arg;
4261 if (sd->sd_recursive &&
4262 zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
4267 error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
4270 fnvlist_add_boolean(sd->sd_nvl, name);
4273 if (sd->sd_recursive)
4274 rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
4280 * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
4282 * Creates a snapshot with the given name. While functionally equivalent to
4283 * 'zfs create', it is a separate command to differentiate intent.
4286 zfs_do_snapshot(int argc, char **argv)
4291 snap_cbdata_t sd = { 0 };
4292 boolean_t multiple_snaps = B_FALSE;
4294 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
4296 if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
4300 while ((c = getopt(argc, argv, "ro:")) != -1) {
4303 if (!parseprop(props, optarg)) {
4304 nvlist_free(sd.sd_nvl);
4310 sd.sd_recursive = B_TRUE;
4311 multiple_snaps = B_TRUE;
4314 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4323 /* check number of arguments */
4325 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
4330 multiple_snaps = B_TRUE;
4331 for (; argc > 0; argc--, argv++) {
4335 atp = strchr(argv[0], '@');
4339 sd.sd_snapname = atp + 1;
4340 zhp = zfs_open(g_zfs, argv[0],
4341 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4344 if (zfs_snapshot_cb(zhp, &sd) != 0)
4348 ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
4349 nvlist_free(sd.sd_nvl);
4351 if (ret != 0 && multiple_snaps)
4352 (void) fprintf(stderr, gettext("no snapshots were created\n"));
4356 nvlist_free(sd.sd_nvl);
4364 * Send a backup stream to stdout.
4367 zfs_do_send(int argc, char **argv)
4369 char *fromname = NULL;
4370 char *toname = NULL;
4371 char *resume_token = NULL;
4374 sendflags_t flags = { 0 };
4376 nvlist_t *dbgnv = NULL;
4377 char *redactbook = NULL;
4379 struct option long_options[] = {
4380 {"replicate", no_argument, NULL, 'R'},
4381 {"redact", required_argument, NULL, 'd'},
4382 {"props", no_argument, NULL, 'p'},
4383 {"parsable", no_argument, NULL, 'P'},
4384 {"dedup", no_argument, NULL, 'D'},
4385 {"verbose", no_argument, NULL, 'v'},
4386 {"dryrun", no_argument, NULL, 'n'},
4387 {"large-block", no_argument, NULL, 'L'},
4388 {"embed", no_argument, NULL, 'e'},
4389 {"resume", required_argument, NULL, 't'},
4390 {"compressed", no_argument, NULL, 'c'},
4391 {"raw", no_argument, NULL, 'w'},
4392 {"backup", no_argument, NULL, 'b'},
4393 {"holds", no_argument, NULL, 'h'},
4394 {"saved", no_argument, NULL, 'S'},
4399 while ((c = getopt_long(argc, argv, ":i:I:RDpvnPLeht:cwbd:S",
4400 long_options, NULL)) != -1) {
4411 flags.doall = B_TRUE;
4414 flags.replicate = B_TRUE;
4417 redactbook = optarg;
4420 flags.props = B_TRUE;
4423 flags.backup = B_TRUE;
4426 flags.holds = B_TRUE;
4429 flags.parsable = B_TRUE;
4433 flags.progress = B_TRUE;
4436 (void) fprintf(stderr,
4437 gettext("WARNING: deduplicated send is no "
4438 "longer supported. A regular,\n"
4439 "non-deduplicated stream will be generated.\n\n"));
4442 flags.dryrun = B_TRUE;
4445 flags.largeblock = B_TRUE;
4448 flags.embed_data = B_TRUE;
4451 resume_token = optarg;
4454 flags.compress = B_TRUE;
4458 flags.compress = B_TRUE;
4459 flags.embed_data = B_TRUE;
4460 flags.largeblock = B_TRUE;
4463 flags.saved = B_TRUE;
4467 * If a parameter was not passed, optopt contains the
4468 * value that would normally lead us into the
4469 * appropriate case statement. If it's > 256, then this
4470 * must be a longopt and we should look at argv to get
4471 * the string. Otherwise it's just the character, so we
4472 * should use it directly.
4474 if (optopt <= UINT8_MAX) {
4475 (void) fprintf(stderr,
4476 gettext("missing argument for '%c' "
4477 "option\n"), optopt);
4479 (void) fprintf(stderr,
4480 gettext("missing argument for '%s' "
4481 "option\n"), argv[optind - 1]);
4489 * If an invalid flag was passed, optopt contains the
4490 * character if it was a short flag, or 0 if it was a
4494 (void) fprintf(stderr,
4495 gettext("invalid option '%c'\n"), optopt);
4497 (void) fprintf(stderr,
4498 gettext("invalid option '%s'\n"),
4506 if (flags.parsable && flags.verbosity == 0)
4507 flags.verbosity = 1;
4512 if (resume_token != NULL) {
4513 if (fromname != NULL || flags.replicate || flags.props ||
4514 flags.backup || flags.holds ||
4515 flags.saved || redactbook != NULL) {
4516 (void) fprintf(stderr,
4517 gettext("invalid flags combined with -t\n"));
4521 (void) fprintf(stderr, gettext("too many arguments\n"));
4526 (void) fprintf(stderr,
4527 gettext("missing snapshot argument\n"));
4531 (void) fprintf(stderr, gettext("too many arguments\n"));
4537 if (fromname != NULL || flags.replicate || flags.props ||
4538 flags.doall || flags.backup ||
4539 flags.holds || flags.largeblock || flags.embed_data ||
4540 flags.compress || flags.raw || redactbook != NULL) {
4541 (void) fprintf(stderr, gettext("incompatible flags "
4542 "combined with saved send flag\n"));
4545 if (strchr(argv[0], '@') != NULL) {
4546 (void) fprintf(stderr, gettext("saved send must "
4547 "specify the dataset with partially-received "
4553 if (flags.raw && redactbook != NULL) {
4554 (void) fprintf(stderr,
4555 gettext("Error: raw sends may not be redacted.\n"));
4559 if (!flags.dryrun && isatty(STDOUT_FILENO)) {
4560 (void) fprintf(stderr,
4561 gettext("Error: Stream can not be written to a terminal.\n"
4562 "You must redirect standard output.\n"));
4567 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
4571 err = zfs_send_saved(zhp, &flags, STDOUT_FILENO,
4575 } else if (resume_token != NULL) {
4576 return (zfs_send_resume(g_zfs, &flags, STDOUT_FILENO,
4581 * For everything except -R and -I, use the new, cleaner code path.
4583 if (!(flags.replicate || flags.doall)) {
4584 char frombuf[ZFS_MAX_DATASET_NAME_LEN];
4586 if (fromname != NULL && (strchr(fromname, '#') == NULL &&
4587 strchr(fromname, '@') == NULL)) {
4589 * Neither bookmark or snapshot was specified. Print a
4590 * warning, and assume snapshot.
4592 (void) fprintf(stderr, "Warning: incremental source "
4593 "didn't specify type, assuming snapshot. Use '@' "
4594 "or '#' prefix to avoid ambiguity.\n");
4595 (void) snprintf(frombuf, sizeof (frombuf), "@%s",
4599 if (fromname != NULL &&
4600 (fromname[0] == '#' || fromname[0] == '@')) {
4602 * Incremental source name begins with # or @.
4603 * Default to same fs as target.
4605 char tmpbuf[ZFS_MAX_DATASET_NAME_LEN];
4606 (void) strlcpy(tmpbuf, fromname, sizeof (tmpbuf));
4607 (void) strlcpy(frombuf, argv[0], sizeof (frombuf));
4608 cp = strchr(frombuf, '@');
4611 (void) strlcat(frombuf, tmpbuf, sizeof (frombuf));
4615 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
4618 err = zfs_send_one(zhp, fromname, STDOUT_FILENO, &flags,
4624 if (fromname != NULL && strchr(fromname, '#')) {
4625 (void) fprintf(stderr,
4626 gettext("Error: multiple snapshots cannot be "
4627 "sent from a bookmark.\n"));
4631 if (redactbook != NULL) {
4632 (void) fprintf(stderr, gettext("Error: multiple snapshots "
4633 "cannot be sent redacted.\n"));
4637 if ((cp = strchr(argv[0], '@')) == NULL) {
4638 (void) fprintf(stderr, gettext("Error: "
4639 "Unsupported flag with filesystem or bookmark.\n"));
4644 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4649 * If they specified the full path to the snapshot, chop off
4650 * everything except the short name of the snapshot, but special
4651 * case if they specify the origin.
4653 if (fromname && (cp = strchr(fromname, '@')) != NULL) {
4654 char origin[ZFS_MAX_DATASET_NAME_LEN];
4657 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
4658 origin, sizeof (origin), &src, NULL, 0, B_FALSE);
4660 if (strcmp(origin, fromname) == 0) {
4662 flags.fromorigin = B_TRUE;
4665 if (cp != fromname && strcmp(argv[0], fromname)) {
4666 (void) fprintf(stderr,
4667 gettext("incremental source must be "
4668 "in same filesystem\n"));
4672 if (strchr(fromname, '@') || strchr(fromname, '/')) {
4673 (void) fprintf(stderr,
4674 gettext("invalid incremental source\n"));
4680 if (flags.replicate && fromname == NULL)
4681 flags.doall = B_TRUE;
4683 err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
4684 flags.verbosity >= 3 ? &dbgnv : NULL);
4686 if (flags.verbosity >= 3 && dbgnv != NULL) {
4688 * dump_nvlist prints to stdout, but that's been
4689 * redirected to a file. Make it print to stderr
4692 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
4693 dump_nvlist(dbgnv, 0);
4702 * Restore a backup stream from stdin.
4705 zfs_do_receive(int argc, char **argv)
4708 recvflags_t flags = { 0 };
4709 boolean_t abort_resumable = B_FALSE;
4712 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
4716 while ((c = getopt(argc, argv, ":o:x:dehMnuvFsA")) != -1) {
4719 if (!parseprop(props, optarg)) {
4725 if (!parsepropname(props, optarg)) {
4732 (void) fprintf(stderr, gettext("invalid option "
4733 "combination: -d and -e are mutually "
4737 flags.isprefix = B_TRUE;
4740 if (flags.isprefix) {
4741 (void) fprintf(stderr, gettext("invalid option "
4742 "combination: -d and -e are mutually "
4746 flags.istail = B_TRUE;
4749 flags.skipholds = B_TRUE;
4752 flags.forceunmount = B_TRUE;
4755 flags.dryrun = B_TRUE;
4758 flags.nomount = B_TRUE;
4761 flags.verbose = B_TRUE;
4764 flags.resumable = B_TRUE;
4767 flags.force = B_TRUE;
4770 abort_resumable = B_TRUE;
4773 (void) fprintf(stderr, gettext("missing argument for "
4774 "'%c' option\n"), optopt);
4778 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4787 /* zfs recv -e (use "tail" name) implies -d (remove dataset "head") */
4789 flags.isprefix = B_TRUE;
4791 /* check number of arguments */
4793 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
4797 (void) fprintf(stderr, gettext("too many arguments\n"));
4801 if (abort_resumable) {
4802 if (flags.isprefix || flags.istail || flags.dryrun ||
4803 flags.resumable || flags.nomount) {
4804 (void) fprintf(stderr, gettext("invalid option\n"));
4808 char namebuf[ZFS_MAX_DATASET_NAME_LEN];
4809 (void) snprintf(namebuf, sizeof (namebuf),
4810 "%s/%%recv", argv[0]);
4812 if (zfs_dataset_exists(g_zfs, namebuf,
4813 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) {
4814 zfs_handle_t *zhp = zfs_open(g_zfs,
4815 namebuf, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4820 err = zfs_destroy(zhp, B_FALSE);
4823 zfs_handle_t *zhp = zfs_open(g_zfs,
4824 argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4827 if (!zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) ||
4828 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
4829 NULL, 0, NULL, NULL, 0, B_TRUE) == -1) {
4830 (void) fprintf(stderr,
4831 gettext("'%s' does not have any "
4832 "resumable receive state to abort\n"),
4838 err = zfs_destroy(zhp, B_FALSE);
4845 if (isatty(STDIN_FILENO)) {
4846 (void) fprintf(stderr,
4847 gettext("Error: Backup stream can not be read "
4848 "from a terminal.\n"
4849 "You must redirect standard input.\n"));
4853 err = zfs_receive(g_zfs, argv[0], props, &flags, STDIN_FILENO, NULL);
4860 * allow/unallow stuff
4862 /* copied from zfs/sys/dsl_deleg.h */
4863 #define ZFS_DELEG_PERM_CREATE "create"
4864 #define ZFS_DELEG_PERM_DESTROY "destroy"
4865 #define ZFS_DELEG_PERM_SNAPSHOT "snapshot"
4866 #define ZFS_DELEG_PERM_ROLLBACK "rollback"
4867 #define ZFS_DELEG_PERM_CLONE "clone"
4868 #define ZFS_DELEG_PERM_PROMOTE "promote"
4869 #define ZFS_DELEG_PERM_RENAME "rename"
4870 #define ZFS_DELEG_PERM_MOUNT "mount"
4871 #define ZFS_DELEG_PERM_SHARE "share"
4872 #define ZFS_DELEG_PERM_SEND "send"
4873 #define ZFS_DELEG_PERM_RECEIVE "receive"
4874 #define ZFS_DELEG_PERM_ALLOW "allow"
4875 #define ZFS_DELEG_PERM_USERPROP "userprop"
4876 #define ZFS_DELEG_PERM_VSCAN "vscan" /* ??? */
4877 #define ZFS_DELEG_PERM_USERQUOTA "userquota"
4878 #define ZFS_DELEG_PERM_GROUPQUOTA "groupquota"
4879 #define ZFS_DELEG_PERM_USERUSED "userused"
4880 #define ZFS_DELEG_PERM_GROUPUSED "groupused"
4881 #define ZFS_DELEG_PERM_USEROBJQUOTA "userobjquota"
4882 #define ZFS_DELEG_PERM_GROUPOBJQUOTA "groupobjquota"
4883 #define ZFS_DELEG_PERM_USEROBJUSED "userobjused"
4884 #define ZFS_DELEG_PERM_GROUPOBJUSED "groupobjused"
4886 #define ZFS_DELEG_PERM_HOLD "hold"
4887 #define ZFS_DELEG_PERM_RELEASE "release"
4888 #define ZFS_DELEG_PERM_DIFF "diff"
4889 #define ZFS_DELEG_PERM_BOOKMARK "bookmark"
4890 #define ZFS_DELEG_PERM_LOAD_KEY "load-key"
4891 #define ZFS_DELEG_PERM_CHANGE_KEY "change-key"
4893 #define ZFS_DELEG_PERM_PROJECTUSED "projectused"
4894 #define ZFS_DELEG_PERM_PROJECTQUOTA "projectquota"
4895 #define ZFS_DELEG_PERM_PROJECTOBJUSED "projectobjused"
4896 #define ZFS_DELEG_PERM_PROJECTOBJQUOTA "projectobjquota"
4898 #define ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
4900 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
4901 { ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
4902 { ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
4903 { ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
4904 { ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
4905 { ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
4906 { ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
4907 { ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
4908 { ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
4909 { ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
4910 { ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
4911 { ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
4912 { ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
4913 { ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
4914 { ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
4915 { ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
4916 { ZFS_DELEG_PERM_BOOKMARK, ZFS_DELEG_NOTE_BOOKMARK },
4917 { ZFS_DELEG_PERM_LOAD_KEY, ZFS_DELEG_NOTE_LOAD_KEY },
4918 { ZFS_DELEG_PERM_CHANGE_KEY, ZFS_DELEG_NOTE_CHANGE_KEY },
4920 { ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
4921 { ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
4922 { ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
4923 { ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
4924 { ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
4925 { ZFS_DELEG_PERM_USEROBJQUOTA, ZFS_DELEG_NOTE_USEROBJQUOTA },
4926 { ZFS_DELEG_PERM_USEROBJUSED, ZFS_DELEG_NOTE_USEROBJUSED },
4927 { ZFS_DELEG_PERM_GROUPOBJQUOTA, ZFS_DELEG_NOTE_GROUPOBJQUOTA },
4928 { ZFS_DELEG_PERM_GROUPOBJUSED, ZFS_DELEG_NOTE_GROUPOBJUSED },
4929 { ZFS_DELEG_PERM_PROJECTUSED, ZFS_DELEG_NOTE_PROJECTUSED },
4930 { ZFS_DELEG_PERM_PROJECTQUOTA, ZFS_DELEG_NOTE_PROJECTQUOTA },
4931 { ZFS_DELEG_PERM_PROJECTOBJUSED, ZFS_DELEG_NOTE_PROJECTOBJUSED },
4932 { ZFS_DELEG_PERM_PROJECTOBJQUOTA, ZFS_DELEG_NOTE_PROJECTOBJQUOTA },
4933 { NULL, ZFS_DELEG_NOTE_NONE }
4936 /* permission structure */
4937 typedef struct deleg_perm {
4938 zfs_deleg_who_type_t dp_who_type;
4939 const char *dp_name;
4941 boolean_t dp_descend;
4945 typedef struct deleg_perm_node {
4946 deleg_perm_t dpn_perm;
4948 uu_avl_node_t dpn_avl_node;
4949 } deleg_perm_node_t;
4951 typedef struct fs_perm fs_perm_t;
4953 /* permissions set */
4954 typedef struct who_perm {
4955 zfs_deleg_who_type_t who_type;
4956 const char *who_name; /* id */
4957 char who_ug_name[256]; /* user/group name */
4958 fs_perm_t *who_fsperm; /* uplink */
4960 uu_avl_t *who_deleg_perm_avl; /* permissions */
4964 typedef struct who_perm_node {
4965 who_perm_t who_perm;
4966 uu_avl_node_t who_avl_node;
4969 typedef struct fs_perm_set fs_perm_set_t;
4970 /* fs permissions */
4972 const char *fsp_name;
4974 uu_avl_t *fsp_sc_avl; /* sets,create */
4975 uu_avl_t *fsp_uge_avl; /* user,group,everyone */
4977 fs_perm_set_t *fsp_set; /* uplink */
4981 typedef struct fs_perm_node {
4982 fs_perm_t fspn_fsperm;
4985 uu_list_node_t fspn_list_node;
4988 /* top level structure */
4989 struct fs_perm_set {
4990 uu_list_pool_t *fsps_list_pool;
4991 uu_list_t *fsps_list; /* list of fs_perms */
4993 uu_avl_pool_t *fsps_named_set_avl_pool;
4994 uu_avl_pool_t *fsps_who_perm_avl_pool;
4995 uu_avl_pool_t *fsps_deleg_perm_avl_pool;
4998 static inline const char *
4999 deleg_perm_type(zfs_deleg_note_t note)
5005 case ZFS_DELEG_NOTE_GROUPQUOTA:
5006 case ZFS_DELEG_NOTE_GROUPUSED:
5007 case ZFS_DELEG_NOTE_USERPROP:
5008 case ZFS_DELEG_NOTE_USERQUOTA:
5009 case ZFS_DELEG_NOTE_USERUSED:
5010 case ZFS_DELEG_NOTE_USEROBJQUOTA:
5011 case ZFS_DELEG_NOTE_USEROBJUSED:
5012 case ZFS_DELEG_NOTE_GROUPOBJQUOTA:
5013 case ZFS_DELEG_NOTE_GROUPOBJUSED:
5014 case ZFS_DELEG_NOTE_PROJECTUSED:
5015 case ZFS_DELEG_NOTE_PROJECTQUOTA:
5016 case ZFS_DELEG_NOTE_PROJECTOBJUSED:
5017 case ZFS_DELEG_NOTE_PROJECTOBJQUOTA:
5019 return (gettext("other"));
5021 return (gettext("subcommand"));
5026 who_type2weight(zfs_deleg_who_type_t who_type)
5030 case ZFS_DELEG_NAMED_SET_SETS:
5031 case ZFS_DELEG_NAMED_SET:
5034 case ZFS_DELEG_CREATE_SETS:
5035 case ZFS_DELEG_CREATE:
5038 case ZFS_DELEG_USER_SETS:
5039 case ZFS_DELEG_USER:
5042 case ZFS_DELEG_GROUP_SETS:
5043 case ZFS_DELEG_GROUP:
5046 case ZFS_DELEG_EVERYONE_SETS:
5047 case ZFS_DELEG_EVERYONE:
5059 who_perm_compare(const void *larg, const void *rarg, void *unused)
5061 const who_perm_node_t *l = larg;
5062 const who_perm_node_t *r = rarg;
5063 zfs_deleg_who_type_t ltype = l->who_perm.who_type;
5064 zfs_deleg_who_type_t rtype = r->who_perm.who_type;
5065 int lweight = who_type2weight(ltype);
5066 int rweight = who_type2weight(rtype);
5067 int res = lweight - rweight;
5069 res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
5070 ZFS_MAX_DELEG_NAME-1);
5082 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
5084 const deleg_perm_node_t *l = larg;
5085 const deleg_perm_node_t *r = rarg;
5086 int res = strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
5087 ZFS_MAX_DELEG_NAME-1);
5099 fs_perm_set_init(fs_perm_set_t *fspset)
5101 bzero(fspset, sizeof (fs_perm_set_t));
5103 if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
5104 sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
5105 NULL, UU_DEFAULT)) == NULL)
5107 if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
5108 UU_DEFAULT)) == NULL)
5111 if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
5112 "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
5113 who_perm_node_t, who_avl_node), who_perm_compare,
5114 UU_DEFAULT)) == NULL)
5117 if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
5118 "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
5119 who_perm_node_t, who_avl_node), who_perm_compare,
5120 UU_DEFAULT)) == NULL)
5123 if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
5124 "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
5125 deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
5130 static inline void fs_perm_fini(fs_perm_t *);
5131 static inline void who_perm_fini(who_perm_t *);
5134 fs_perm_set_fini(fs_perm_set_t *fspset)
5136 fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
5138 while (node != NULL) {
5139 fs_perm_node_t *next_node =
5140 uu_list_next(fspset->fsps_list, node);
5141 fs_perm_t *fsperm = &node->fspn_fsperm;
5142 fs_perm_fini(fsperm);
5143 uu_list_remove(fspset->fsps_list, node);
5148 uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
5149 uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
5150 uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
5154 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
5157 deleg_perm->dp_who_type = type;
5158 deleg_perm->dp_name = name;
5162 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
5163 zfs_deleg_who_type_t type, const char *name)
5165 uu_avl_pool_t *pool;
5166 pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
5168 bzero(who_perm, sizeof (who_perm_t));
5170 if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
5171 UU_DEFAULT)) == NULL)
5174 who_perm->who_type = type;
5175 who_perm->who_name = name;
5176 who_perm->who_fsperm = fsperm;
5180 who_perm_fini(who_perm_t *who_perm)
5182 deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
5184 while (node != NULL) {
5185 deleg_perm_node_t *next_node =
5186 uu_avl_next(who_perm->who_deleg_perm_avl, node);
5188 uu_avl_remove(who_perm->who_deleg_perm_avl, node);
5193 uu_avl_destroy(who_perm->who_deleg_perm_avl);
5197 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
5199 uu_avl_pool_t *nset_pool = fspset->fsps_named_set_avl_pool;
5200 uu_avl_pool_t *who_pool = fspset->fsps_who_perm_avl_pool;
5202 bzero(fsperm, sizeof (fs_perm_t));
5204 if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
5208 if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
5212 fsperm->fsp_set = fspset;
5213 fsperm->fsp_name = fsname;
5217 fs_perm_fini(fs_perm_t *fsperm)
5219 who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
5220 while (node != NULL) {
5221 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
5223 who_perm_t *who_perm = &node->who_perm;
5224 who_perm_fini(who_perm);
5225 uu_avl_remove(fsperm->fsp_sc_avl, node);
5230 node = uu_avl_first(fsperm->fsp_uge_avl);
5231 while (node != NULL) {
5232 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
5234 who_perm_t *who_perm = &node->who_perm;
5235 who_perm_fini(who_perm);
5236 uu_avl_remove(fsperm->fsp_uge_avl, node);
5241 uu_avl_destroy(fsperm->fsp_sc_avl);
5242 uu_avl_destroy(fsperm->fsp_uge_avl);
5246 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
5247 zfs_deleg_who_type_t who_type, const char *name, char locality)
5249 uu_avl_index_t idx = 0;
5251 deleg_perm_node_t *found_node = NULL;
5252 deleg_perm_t *deleg_perm = &node->dpn_perm;
5254 deleg_perm_init(deleg_perm, who_type, name);
5256 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
5258 uu_avl_insert(avl, node, idx);
5261 deleg_perm = &node->dpn_perm;
5266 case ZFS_DELEG_LOCAL:
5267 deleg_perm->dp_local = B_TRUE;
5269 case ZFS_DELEG_DESCENDENT:
5270 deleg_perm->dp_descend = B_TRUE;
5275 assert(B_FALSE); /* invalid locality */
5280 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
5282 nvpair_t *nvp = NULL;
5283 fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
5284 uu_avl_t *avl = who_perm->who_deleg_perm_avl;
5285 zfs_deleg_who_type_t who_type = who_perm->who_type;
5287 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5288 const char *name = nvpair_name(nvp);
5289 data_type_t type = nvpair_type(nvp);
5290 uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
5291 deleg_perm_node_t *node =
5292 safe_malloc(sizeof (deleg_perm_node_t));
5294 VERIFY(type == DATA_TYPE_BOOLEAN);
5296 uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
5297 set_deleg_perm_node(avl, node, who_type, name, locality);
5304 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
5306 nvpair_t *nvp = NULL;
5307 fs_perm_set_t *fspset = fsperm->fsp_set;
5309 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5310 nvlist_t *nvl2 = NULL;
5311 const char *name = nvpair_name(nvp);
5312 uu_avl_t *avl = NULL;
5313 uu_avl_pool_t *avl_pool = NULL;
5314 zfs_deleg_who_type_t perm_type = name[0];
5315 char perm_locality = name[1];
5316 const char *perm_name = name + 3;
5317 who_perm_t *who_perm = NULL;
5319 assert('$' == name[2]);
5321 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
5324 switch (perm_type) {
5325 case ZFS_DELEG_CREATE:
5326 case ZFS_DELEG_CREATE_SETS:
5327 case ZFS_DELEG_NAMED_SET:
5328 case ZFS_DELEG_NAMED_SET_SETS:
5329 avl_pool = fspset->fsps_named_set_avl_pool;
5330 avl = fsperm->fsp_sc_avl;
5332 case ZFS_DELEG_USER:
5333 case ZFS_DELEG_USER_SETS:
5334 case ZFS_DELEG_GROUP:
5335 case ZFS_DELEG_GROUP_SETS:
5336 case ZFS_DELEG_EVERYONE:
5337 case ZFS_DELEG_EVERYONE_SETS:
5338 avl_pool = fspset->fsps_who_perm_avl_pool;
5339 avl = fsperm->fsp_uge_avl;
5343 assert(!"unhandled zfs_deleg_who_type_t");
5346 who_perm_node_t *found_node = NULL;
5347 who_perm_node_t *node = safe_malloc(
5348 sizeof (who_perm_node_t));
5349 who_perm = &node->who_perm;
5350 uu_avl_index_t idx = 0;
5352 uu_avl_node_init(node, &node->who_avl_node, avl_pool);
5353 who_perm_init(who_perm, fsperm, perm_type, perm_name);
5355 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
5357 if (avl == fsperm->fsp_uge_avl) {
5359 struct passwd *p = NULL;
5360 struct group *g = NULL;
5361 const char *nice_name = NULL;
5363 switch (perm_type) {
5364 case ZFS_DELEG_USER_SETS:
5365 case ZFS_DELEG_USER:
5366 rid = atoi(perm_name);
5369 nice_name = p->pw_name;
5371 case ZFS_DELEG_GROUP_SETS:
5372 case ZFS_DELEG_GROUP:
5373 rid = atoi(perm_name);
5376 nice_name = g->gr_name;
5383 if (nice_name != NULL) {
5385 node->who_perm.who_ug_name,
5388 /* User or group unknown */
5390 node->who_perm.who_ug_name,
5391 sizeof (node->who_perm.who_ug_name),
5392 "(unknown: %d)", rid);
5396 uu_avl_insert(avl, node, idx);
5399 who_perm = &node->who_perm;
5402 assert(who_perm != NULL);
5403 (void) parse_who_perm(who_perm, nvl2, perm_locality);
5410 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
5412 nvpair_t *nvp = NULL;
5413 uu_avl_index_t idx = 0;
5415 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5416 nvlist_t *nvl2 = NULL;
5417 const char *fsname = nvpair_name(nvp);
5418 data_type_t type = nvpair_type(nvp);
5419 fs_perm_t *fsperm = NULL;
5420 fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
5424 fsperm = &node->fspn_fsperm;
5426 VERIFY(DATA_TYPE_NVLIST == type);
5428 uu_list_node_init(node, &node->fspn_list_node,
5429 fspset->fsps_list_pool);
5431 idx = uu_list_numnodes(fspset->fsps_list);
5432 fs_perm_init(fsperm, fspset, fsname);
5434 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
5437 (void) parse_fs_perm(fsperm, nvl2);
5439 uu_list_insert(fspset->fsps_list, node, idx);
5445 static inline const char *
5446 deleg_perm_comment(zfs_deleg_note_t note)
5448 const char *str = "";
5453 case ZFS_DELEG_NOTE_ALLOW:
5454 str = gettext("Must also have the permission that is being"
5455 "\n\t\t\t\tallowed");
5457 case ZFS_DELEG_NOTE_CLONE:
5458 str = gettext("Must also have the 'create' ability and 'mount'"
5459 "\n\t\t\t\tability in the origin file system");
5461 case ZFS_DELEG_NOTE_CREATE:
5462 str = gettext("Must also have the 'mount' ability");
5464 case ZFS_DELEG_NOTE_DESTROY:
5465 str = gettext("Must also have the 'mount' ability");
5467 case ZFS_DELEG_NOTE_DIFF:
5468 str = gettext("Allows lookup of paths within a dataset;"
5469 "\n\t\t\t\tgiven an object number. Ordinary users need this"
5470 "\n\t\t\t\tin order to use zfs diff");
5472 case ZFS_DELEG_NOTE_HOLD:
5473 str = gettext("Allows adding a user hold to a snapshot");
5475 case ZFS_DELEG_NOTE_MOUNT:
5476 str = gettext("Allows mount/umount of ZFS datasets");
5478 case ZFS_DELEG_NOTE_PROMOTE:
5479 str = gettext("Must also have the 'mount'\n\t\t\t\tand"
5480 " 'promote' ability in the origin file system");
5482 case ZFS_DELEG_NOTE_RECEIVE:
5483 str = gettext("Must also have the 'mount' and 'create'"
5486 case ZFS_DELEG_NOTE_RELEASE:
5487 str = gettext("Allows releasing a user hold which\n\t\t\t\t"
5488 "might destroy the snapshot");
5490 case ZFS_DELEG_NOTE_RENAME:
5491 str = gettext("Must also have the 'mount' and 'create'"
5492 "\n\t\t\t\tability in the new parent");
5494 case ZFS_DELEG_NOTE_ROLLBACK:
5497 case ZFS_DELEG_NOTE_SEND:
5500 case ZFS_DELEG_NOTE_SHARE:
5501 str = gettext("Allows sharing file systems over NFS or SMB"
5502 "\n\t\t\t\tprotocols");
5504 case ZFS_DELEG_NOTE_SNAPSHOT:
5507 case ZFS_DELEG_NOTE_LOAD_KEY:
5508 str = gettext("Allows loading or unloading an encryption key");
5510 case ZFS_DELEG_NOTE_CHANGE_KEY:
5511 str = gettext("Allows changing or adding an encryption key");
5514 * case ZFS_DELEG_NOTE_VSCAN:
5515 * str = gettext("");
5519 case ZFS_DELEG_NOTE_GROUPQUOTA:
5520 str = gettext("Allows accessing any groupquota@... property");
5522 case ZFS_DELEG_NOTE_GROUPUSED:
5523 str = gettext("Allows reading any groupused@... property");
5525 case ZFS_DELEG_NOTE_USERPROP:
5526 str = gettext("Allows changing any user property");
5528 case ZFS_DELEG_NOTE_USERQUOTA:
5529 str = gettext("Allows accessing any userquota@... property");
5531 case ZFS_DELEG_NOTE_USERUSED:
5532 str = gettext("Allows reading any userused@... property");
5534 case ZFS_DELEG_NOTE_USEROBJQUOTA:
5535 str = gettext("Allows accessing any userobjquota@... property");
5537 case ZFS_DELEG_NOTE_GROUPOBJQUOTA:
5538 str = gettext("Allows accessing any \n\t\t\t\t"
5539 "groupobjquota@... property");
5541 case ZFS_DELEG_NOTE_GROUPOBJUSED:
5542 str = gettext("Allows reading any groupobjused@... property");
5544 case ZFS_DELEG_NOTE_USEROBJUSED:
5545 str = gettext("Allows reading any userobjused@... property");
5547 case ZFS_DELEG_NOTE_PROJECTQUOTA:
5548 str = gettext("Allows accessing any projectquota@... property");
5550 case ZFS_DELEG_NOTE_PROJECTOBJQUOTA:
5551 str = gettext("Allows accessing any \n\t\t\t\t"
5552 "projectobjquota@... property");
5554 case ZFS_DELEG_NOTE_PROJECTUSED:
5555 str = gettext("Allows reading any projectused@... property");
5557 case ZFS_DELEG_NOTE_PROJECTOBJUSED:
5558 str = gettext("Allows accessing any \n\t\t\t\t"
5559 "projectobjused@... property");
5577 boolean_t recursive; /* unallow only */
5578 boolean_t prt_usage;
5580 boolean_t prt_perms;
5583 const char *dataset;
5587 prop_cmp(const void *a, const void *b)
5589 const char *str1 = *(const char **)a;
5590 const char *str2 = *(const char **)b;
5591 return (strcmp(str1, str2));
5595 allow_usage(boolean_t un, boolean_t requested, const char *msg)
5597 const char *opt_desc[] = {
5598 "-h", gettext("show this help message and exit"),
5599 "-l", gettext("set permission locally"),
5600 "-d", gettext("set permission for descents"),
5601 "-u", gettext("set permission for user"),
5602 "-g", gettext("set permission for group"),
5603 "-e", gettext("set permission for everyone"),
5604 "-c", gettext("set create time permission"),
5605 "-s", gettext("define permission set"),
5607 "-r", gettext("remove permissions recursively"),
5609 size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
5610 size_t allow_size = unallow_size - 2;
5611 const char *props[ZFS_NUM_PROPS];
5614 FILE *fp = requested ? stdout : stderr;
5615 zprop_desc_t *pdtbl = zfs_prop_get_table();
5616 const char *fmt = gettext("%-16s %-14s\t%s\n");
5618 (void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
5620 (void) fprintf(fp, gettext("Options:\n"));
5621 for (i = 0; i < (un ? unallow_size : allow_size); i += 2) {
5622 const char *opt = opt_desc[i];
5623 const char *optdsc = opt_desc[i + 1];
5624 (void) fprintf(fp, gettext(" %-10s %s\n"), opt, optdsc);
5627 (void) fprintf(fp, gettext("\nThe following permissions are "
5629 (void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
5631 for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
5632 const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
5633 zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
5634 const char *perm_type = deleg_perm_type(perm_note);
5635 const char *perm_comment = deleg_perm_comment(perm_note);
5636 (void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
5639 for (i = 0; i < ZFS_NUM_PROPS; i++) {
5640 zprop_desc_t *pd = &pdtbl[i];
5641 if (pd->pd_visible != B_TRUE)
5644 if (pd->pd_attr == PROP_READONLY)
5647 props[count++] = pd->pd_name;
5649 props[count] = NULL;
5651 qsort(props, count, sizeof (char *), prop_cmp);
5653 for (i = 0; i < count; i++)
5654 (void) fprintf(fp, fmt, props[i], gettext("property"), "");
5657 (void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
5659 exit(requested ? 0 : 2);
5662 static inline const char *
5663 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
5666 if (un && argc == expected_argc - 1)
5668 else if (argc == expected_argc)
5669 *permsp = argv[argc - 2];
5671 allow_usage(un, B_FALSE,
5672 gettext("wrong number of parameters\n"));
5674 return (argv[argc - 1]);
5678 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
5680 int uge_sum = opts->user + opts->group + opts->everyone;
5681 int csuge_sum = opts->create + opts->set + uge_sum;
5682 int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
5683 int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
5686 allow_usage(un, B_FALSE,
5687 gettext("-u, -g, and -e are mutually exclusive\n"));
5689 if (opts->prt_usage) {
5690 if (argc == 0 && all_sum == 0)
5691 allow_usage(un, B_TRUE, NULL);
5698 allow_usage(un, B_FALSE,
5699 gettext("invalid options combined with -s\n"));
5701 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
5702 if (argv[0][0] != '@')
5703 allow_usage(un, B_FALSE,
5704 gettext("invalid set name: missing '@' prefix\n"));
5705 opts->who = argv[0];
5706 } else if (opts->create) {
5707 if (ldcsuge_sum > 1)
5708 allow_usage(un, B_FALSE,
5709 gettext("invalid options combined with -c\n"));
5710 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
5711 } else if (opts->everyone) {
5713 allow_usage(un, B_FALSE,
5714 gettext("invalid options combined with -e\n"));
5715 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
5716 } else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
5718 opts->everyone = B_TRUE;
5721 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
5722 } else if (argc == 1 && !un) {
5723 opts->prt_perms = B_TRUE;
5724 opts->dataset = argv[argc-1];
5726 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
5727 opts->who = argv[0];
5730 if (!opts->local && !opts->descend) {
5731 opts->local = B_TRUE;
5732 opts->descend = B_TRUE;
5737 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
5738 const char *who, char *perms, nvlist_t *top_nvl)
5741 char ld[2] = { '\0', '\0' };
5742 char who_buf[MAXNAMELEN + 32];
5743 char base_type = '\0';
5744 char set_type = '\0';
5745 nvlist_t *base_nvl = NULL;
5746 nvlist_t *set_nvl = NULL;
5749 if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
5751 if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) != 0)
5755 case ZFS_DELEG_NAMED_SET_SETS:
5756 case ZFS_DELEG_NAMED_SET:
5757 set_type = ZFS_DELEG_NAMED_SET_SETS;
5758 base_type = ZFS_DELEG_NAMED_SET;
5759 ld[0] = ZFS_DELEG_NA;
5761 case ZFS_DELEG_CREATE_SETS:
5762 case ZFS_DELEG_CREATE:
5763 set_type = ZFS_DELEG_CREATE_SETS;
5764 base_type = ZFS_DELEG_CREATE;
5765 ld[0] = ZFS_DELEG_NA;
5767 case ZFS_DELEG_USER_SETS:
5768 case ZFS_DELEG_USER:
5769 set_type = ZFS_DELEG_USER_SETS;
5770 base_type = ZFS_DELEG_USER;
5772 ld[0] = ZFS_DELEG_LOCAL;
5774 ld[1] = ZFS_DELEG_DESCENDENT;
5776 case ZFS_DELEG_GROUP_SETS:
5777 case ZFS_DELEG_GROUP:
5778 set_type = ZFS_DELEG_GROUP_SETS;
5779 base_type = ZFS_DELEG_GROUP;
5781 ld[0] = ZFS_DELEG_LOCAL;
5783 ld[1] = ZFS_DELEG_DESCENDENT;
5785 case ZFS_DELEG_EVERYONE_SETS:
5786 case ZFS_DELEG_EVERYONE:
5787 set_type = ZFS_DELEG_EVERYONE_SETS;
5788 base_type = ZFS_DELEG_EVERYONE;
5790 ld[0] = ZFS_DELEG_LOCAL;
5792 ld[1] = ZFS_DELEG_DESCENDENT;
5796 assert(set_type != '\0' && base_type != '\0');
5799 if (perms != NULL) {
5801 char *end = curr + strlen(perms);
5803 while (curr < end) {
5804 char *delim = strchr(curr, ',');
5815 (void) nvlist_add_boolean(nvl, curr);
5821 for (i = 0; i < 2; i++) {
5822 char locality = ld[i];
5826 if (!nvlist_empty(base_nvl)) {
5828 (void) snprintf(who_buf,
5829 sizeof (who_buf), "%c%c$%s",
5830 base_type, locality, who);
5832 (void) snprintf(who_buf,
5833 sizeof (who_buf), "%c%c$",
5834 base_type, locality);
5836 (void) nvlist_add_nvlist(top_nvl, who_buf,
5841 if (!nvlist_empty(set_nvl)) {
5843 (void) snprintf(who_buf,
5844 sizeof (who_buf), "%c%c$%s",
5845 set_type, locality, who);
5847 (void) snprintf(who_buf,
5848 sizeof (who_buf), "%c%c$",
5849 set_type, locality);
5851 (void) nvlist_add_nvlist(top_nvl, who_buf,
5856 for (i = 0; i < 2; i++) {
5857 char locality = ld[i];
5862 (void) snprintf(who_buf, sizeof (who_buf),
5863 "%c%c$%s", base_type, locality, who);
5865 (void) snprintf(who_buf, sizeof (who_buf),
5866 "%c%c$", base_type, locality);
5867 (void) nvlist_add_boolean(top_nvl, who_buf);
5870 (void) snprintf(who_buf, sizeof (who_buf),
5871 "%c%c$%s", set_type, locality, who);
5873 (void) snprintf(who_buf, sizeof (who_buf),
5874 "%c%c$", set_type, locality);
5875 (void) nvlist_add_boolean(top_nvl, who_buf);
5881 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
5883 if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
5887 store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
5888 opts->descend, opts->who, opts->perms, *nvlp);
5889 } else if (opts->create) {
5890 store_allow_perm(ZFS_DELEG_CREATE, opts->local,
5891 opts->descend, NULL, opts->perms, *nvlp);
5892 } else if (opts->everyone) {
5893 store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
5894 opts->descend, NULL, opts->perms, *nvlp);
5896 char *curr = opts->who;
5897 char *end = curr + strlen(curr);
5899 while (curr < end) {
5901 zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
5903 char *delim = strchr(curr, ',');
5906 struct passwd *p = NULL;
5907 struct group *g = NULL;
5915 rid = (uid_t)strtol(curr, &endch, 0);
5917 who_type = ZFS_DELEG_USER;
5925 else if (*endch != '\0') {
5926 (void) snprintf(errbuf, 256, gettext(
5927 "invalid user %s\n"), curr);
5928 allow_usage(un, B_TRUE, errbuf);
5930 } else if (opts->group) {
5931 who_type = ZFS_DELEG_GROUP;
5939 else if (*endch != '\0') {
5940 (void) snprintf(errbuf, 256, gettext(
5941 "invalid group %s\n"), curr);
5942 allow_usage(un, B_TRUE, errbuf);
5945 if (*endch != '\0') {
5952 if (*endch != '\0') {
5960 who_type = ZFS_DELEG_USER;
5962 } else if (g != NULL) {
5963 who_type = ZFS_DELEG_GROUP;
5966 (void) snprintf(errbuf, 256, gettext(
5967 "invalid user/group %s\n"), curr);
5968 allow_usage(un, B_TRUE, errbuf);
5972 (void) sprintf(id, "%u", rid);
5975 store_allow_perm(who_type, opts->local,
5976 opts->descend, who, opts->perms, *nvlp);
5985 print_set_creat_perms(uu_avl_t *who_avl)
5987 const char *sc_title[] = {
5988 gettext("Permission sets:\n"),
5989 gettext("Create time permissions:\n"),
5992 who_perm_node_t *who_node = NULL;
5993 int prev_weight = -1;
5995 for (who_node = uu_avl_first(who_avl); who_node != NULL;
5996 who_node = uu_avl_next(who_avl, who_node)) {
5997 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5998 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5999 const char *who_name = who_node->who_perm.who_name;
6000 int weight = who_type2weight(who_type);
6001 boolean_t first = B_TRUE;
6002 deleg_perm_node_t *deleg_node;
6004 if (prev_weight != weight) {
6005 (void) printf("%s", sc_title[weight]);
6006 prev_weight = weight;
6009 if (who_name == NULL || strnlen(who_name, 1) == 0)
6010 (void) printf("\t");
6012 (void) printf("\t%s ", who_name);
6014 for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
6015 deleg_node = uu_avl_next(avl, deleg_node)) {
6018 deleg_node->dpn_perm.dp_name);
6021 (void) printf(",%s",
6022 deleg_node->dpn_perm.dp_name);
6025 (void) printf("\n");
6030 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
6033 who_perm_node_t *who_node = NULL;
6034 boolean_t prt_title = B_TRUE;
6035 uu_avl_walk_t *walk;
6037 if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
6040 while ((who_node = uu_avl_walk_next(walk)) != NULL) {
6041 const char *who_name = who_node->who_perm.who_name;
6042 const char *nice_who_name = who_node->who_perm.who_ug_name;
6043 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
6044 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
6046 deleg_perm_node_t *deleg_node;
6047 boolean_t prt_who = B_TRUE;
6049 for (deleg_node = uu_avl_first(avl);
6051 deleg_node = uu_avl_next(avl, deleg_node)) {
6052 if (local != deleg_node->dpn_perm.dp_local ||
6053 descend != deleg_node->dpn_perm.dp_descend)
6057 const char *who = NULL;
6059 prt_title = B_FALSE;
6060 (void) printf("%s", title);
6064 case ZFS_DELEG_USER_SETS:
6065 case ZFS_DELEG_USER:
6066 who = gettext("user");
6068 who_name = nice_who_name;
6070 case ZFS_DELEG_GROUP_SETS:
6071 case ZFS_DELEG_GROUP:
6072 who = gettext("group");
6074 who_name = nice_who_name;
6076 case ZFS_DELEG_EVERYONE_SETS:
6077 case ZFS_DELEG_EVERYONE:
6078 who = gettext("everyone");
6083 assert(who != NULL);
6087 if (who_name == NULL)
6088 (void) printf("\t%s", who);
6090 (void) printf("\t%s %s", who, who_name);
6093 (void) printf("%c%s", delim,
6094 deleg_node->dpn_perm.dp_name);
6099 (void) printf("\n");
6102 uu_avl_walk_end(walk);
6106 print_fs_perms(fs_perm_set_t *fspset)
6108 fs_perm_node_t *node = NULL;
6109 char buf[MAXNAMELEN + 32];
6110 const char *dsname = buf;
6112 for (node = uu_list_first(fspset->fsps_list); node != NULL;
6113 node = uu_list_next(fspset->fsps_list, node)) {
6114 uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
6115 uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
6118 (void) snprintf(buf, sizeof (buf),
6119 gettext("---- Permissions on %s "),
6120 node->fspn_fsperm.fsp_name);
6121 (void) printf("%s", dsname);
6122 left = 70 - strlen(buf);
6125 (void) printf("\n");
6127 print_set_creat_perms(sc_avl);
6128 print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
6129 gettext("Local permissions:\n"));
6130 print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
6131 gettext("Descendent permissions:\n"));
6132 print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
6133 gettext("Local+Descendent permissions:\n"));
6137 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
6139 struct deleg_perms {
6145 set_deleg_perms(zfs_handle_t *zhp, void *data)
6147 struct deleg_perms *perms = (struct deleg_perms *)data;
6148 zfs_type_t zfs_type = zfs_get_type(zhp);
6150 if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
6153 return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
6157 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
6160 nvlist_t *perm_nvl = NULL;
6161 nvlist_t *update_perm_nvl = NULL;
6164 struct allow_opts opts = { 0 };
6166 const char *optstr = un ? "ldugecsrh" : "ldugecsh";
6169 while ((c = getopt(argc, argv, optstr)) != -1) {
6172 opts.local = B_TRUE;
6175 opts.descend = B_TRUE;
6181 opts.group = B_TRUE;
6184 opts.everyone = B_TRUE;
6190 opts.create = B_TRUE;
6193 opts.recursive = B_TRUE;
6196 (void) fprintf(stderr, gettext("missing argument for "
6197 "'%c' option\n"), optopt);
6201 opts.prt_usage = B_TRUE;
6204 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6213 /* check arguments */
6214 parse_allow_args(argc, argv, un, &opts);
6216 /* try to open the dataset */
6217 if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
6218 ZFS_TYPE_VOLUME)) == NULL) {
6219 (void) fprintf(stderr, "Failed to open dataset: %s\n",
6224 if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
6227 fs_perm_set_init(&fs_perm_set);
6228 if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
6229 (void) fprintf(stderr, "Failed to parse fsacl permissions\n");
6234 print_fs_perms(&fs_perm_set);
6236 (void) construct_fsacl_list(un, &opts, &update_perm_nvl);
6237 if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
6240 if (un && opts.recursive) {
6241 struct deleg_perms data = { un, update_perm_nvl };
6242 if (zfs_iter_filesystems(zhp, set_deleg_perms,
6251 nvlist_free(perm_nvl);
6252 nvlist_free(update_perm_nvl);
6254 fs_perm_set_fini(&fs_perm_set);
6262 zfs_do_allow(int argc, char **argv)
6264 return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
6268 zfs_do_unallow(int argc, char **argv)
6270 return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
6274 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
6279 boolean_t recursive = B_FALSE;
6280 const char *opts = holding ? "rt" : "r";
6284 while ((c = getopt(argc, argv, opts)) != -1) {
6290 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6299 /* check number of arguments */
6307 if (holding && tag[0] == '.') {
6308 /* tags starting with '.' are reserved for libzfs */
6309 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
6313 for (i = 0; i < argc; ++i) {
6315 char parent[ZFS_MAX_DATASET_NAME_LEN];
6317 char *path = argv[i];
6319 delim = strchr(path, '@');
6320 if (delim == NULL) {
6321 (void) fprintf(stderr,
6322 gettext("'%s' is not a snapshot\n"), path);
6326 (void) strncpy(parent, path, delim - path);
6327 parent[delim - path] = '\0';
6329 zhp = zfs_open(g_zfs, parent,
6330 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
6336 if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
6339 if (zfs_release(zhp, delim+1, tag, recursive) != 0)
6345 return (errors != 0);
6349 * zfs hold [-r] [-t] <tag> <snap> ...
6351 * -r Recursively hold
6353 * Apply a user-hold with the given tag to the list of snapshots.
6356 zfs_do_hold(int argc, char **argv)
6358 return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
6362 * zfs release [-r] <tag> <snap> ...
6364 * -r Recursively release
6366 * Release a user-hold with the given tag from the list of snapshots.
6369 zfs_do_release(int argc, char **argv)
6371 return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
6374 typedef struct holds_cbdata {
6375 boolean_t cb_recursive;
6376 const char *cb_snapname;
6378 size_t cb_max_namelen;
6379 size_t cb_max_taglen;
6382 #define STRFTIME_FMT_STR "%a %b %e %H:%M %Y"
6383 #define DATETIME_BUF_LEN (32)
6388 print_holds(boolean_t scripted, int nwidth, int tagwidth, nvlist_t *nvl)
6391 nvpair_t *nvp = NULL;
6392 char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
6396 for (i = 0; i < 3; i++) {
6397 col = gettext(hdr_cols[i]);
6399 (void) printf("%-*s ", i ? tagwidth : nwidth,
6402 (void) printf("%s\n", col);
6406 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
6407 char *zname = nvpair_name(nvp);
6409 nvpair_t *nvp2 = NULL;
6410 (void) nvpair_value_nvlist(nvp, &nvl2);
6411 while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
6412 char tsbuf[DATETIME_BUF_LEN];
6413 char *tagname = nvpair_name(nvp2);
6418 (void) nvpair_value_uint64(nvp2, &val);
6420 (void) localtime_r(&time, &t);
6421 (void) strftime(tsbuf, DATETIME_BUF_LEN,
6422 gettext(STRFTIME_FMT_STR), &t);
6425 (void) printf("%s\t%s\t%s\n", zname,
6428 (void) printf("%-*s %-*s %s\n", nwidth,
6429 zname, tagwidth, tagname, tsbuf);
6436 * Generic callback function to list a dataset or snapshot.
6439 holds_callback(zfs_handle_t *zhp, void *data)
6441 holds_cbdata_t *cbp = data;
6442 nvlist_t *top_nvl = *cbp->cb_nvlp;
6443 nvlist_t *nvl = NULL;
6444 nvpair_t *nvp = NULL;
6445 const char *zname = zfs_get_name(zhp);
6446 size_t znamelen = strlen(zname);
6448 if (cbp->cb_recursive) {
6449 const char *snapname;
6450 char *delim = strchr(zname, '@');
6454 snapname = delim + 1;
6455 if (strcmp(cbp->cb_snapname, snapname))
6459 if (zfs_get_holds(zhp, &nvl) != 0)
6462 if (znamelen > cbp->cb_max_namelen)
6463 cbp->cb_max_namelen = znamelen;
6465 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
6466 const char *tag = nvpair_name(nvp);
6467 size_t taglen = strlen(tag);
6468 if (taglen > cbp->cb_max_taglen)
6469 cbp->cb_max_taglen = taglen;
6472 return (nvlist_add_nvlist(top_nvl, zname, nvl));
6476 * zfs holds [-rH] <snap> ...
6478 * -r Lists holds that are set on the named snapshots recursively.
6479 * -H Scripted mode; elide headers and separate columns by tabs.
6482 zfs_do_holds(int argc, char **argv)
6487 boolean_t scripted = B_FALSE;
6488 boolean_t recursive = B_FALSE;
6489 const char *opts = "rH";
6492 int types = ZFS_TYPE_SNAPSHOT;
6493 holds_cbdata_t cb = { 0 };
6500 while ((c = getopt(argc, argv, opts)) != -1) {
6509 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6516 types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
6517 flags |= ZFS_ITER_RECURSE;
6523 /* check number of arguments */
6527 if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
6530 for (i = 0; i < argc; ++i) {
6531 char *snapshot = argv[i];
6533 const char *snapname;
6535 delim = strchr(snapshot, '@');
6536 if (delim == NULL) {
6537 (void) fprintf(stderr,
6538 gettext("'%s' is not a snapshot\n"), snapshot);
6542 snapname = delim + 1;
6544 snapshot[delim - snapshot] = '\0';
6546 cb.cb_recursive = recursive;
6547 cb.cb_snapname = snapname;
6551 * 1. collect holds data, set format options
6553 ret = zfs_for_each(argc, argv, flags, types, NULL, NULL, limit,
6554 holds_callback, &cb);
6560 * 2. print holds data
6562 print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl);
6564 if (nvlist_empty(nvl))
6565 (void) fprintf(stderr, gettext("no datasets available\n"));
6569 return (0 != errors);
6572 #define CHECK_SPINNER 30
6573 #define SPINNER_TIME 3 /* seconds */
6574 #define MOUNT_TIME 1 /* seconds */
6576 typedef struct get_all_state {
6577 boolean_t ga_verbose;
6578 get_all_cb_t *ga_cbp;
6582 get_one_dataset(zfs_handle_t *zhp, void *data)
6584 static char *spin[] = { "-", "\\", "|", "/" };
6585 static int spinval = 0;
6586 static int spincheck = 0;
6587 static time_t last_spin_time = (time_t)0;
6588 get_all_state_t *state = data;
6589 zfs_type_t type = zfs_get_type(zhp);
6591 if (state->ga_verbose) {
6592 if (--spincheck < 0) {
6593 time_t now = time(NULL);
6594 if (last_spin_time + SPINNER_TIME < now) {
6595 update_progress(spin[spinval++ % 4]);
6596 last_spin_time = now;
6598 spincheck = CHECK_SPINNER;
6603 * Iterate over any nested datasets.
6605 if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
6611 * Skip any datasets whose type does not match.
6613 if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
6617 libzfs_add_handle(state->ga_cbp, zhp);
6618 assert(state->ga_cbp->cb_used <= state->ga_cbp->cb_alloc);
6624 get_all_datasets(get_all_cb_t *cbp, boolean_t verbose)
6626 get_all_state_t state = {
6627 .ga_verbose = verbose,
6632 set_progress_header(gettext("Reading ZFS config"));
6633 (void) zfs_iter_root(g_zfs, get_one_dataset, &state);
6636 finish_progress(gettext("done."));
6640 * Generic callback for sharing or mounting filesystems. Because the code is so
6641 * similar, we have a common function with an extra parameter to determine which
6642 * mode we are using.
6644 typedef enum { OP_SHARE, OP_MOUNT } share_mount_op_t;
6646 typedef struct share_mount_state {
6647 share_mount_op_t sm_op;
6648 boolean_t sm_verbose;
6651 char *sm_proto; /* only valid for OP_SHARE */
6652 pthread_mutex_t sm_lock; /* protects the remaining fields */
6653 uint_t sm_total; /* number of filesystems to process */
6654 uint_t sm_done; /* number of filesystems processed */
6655 int sm_status; /* -1 if any of the share/mount operations failed */
6656 } share_mount_state_t;
6659 * Share or mount a dataset.
6662 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
6663 boolean_t explicit, const char *options)
6665 char mountpoint[ZFS_MAXPROPLEN];
6666 char shareopts[ZFS_MAXPROPLEN];
6667 char smbshareopts[ZFS_MAXPROPLEN];
6668 const char *cmdname = op == OP_SHARE ? "share" : "mount";
6670 uint64_t zoned, canmount;
6671 boolean_t shared_nfs, shared_smb;
6673 assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
6676 * Check to make sure we can mount/share this dataset. If we
6677 * are in the global zone and the filesystem is exported to a
6678 * local zone, or if we are in a local zone and the
6679 * filesystem is not exported, then it is an error.
6681 zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
6683 if (zoned && getzoneid() == GLOBAL_ZONEID) {
6687 (void) fprintf(stderr, gettext("cannot %s '%s': "
6688 "dataset is exported to a local zone\n"), cmdname,
6692 } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
6696 (void) fprintf(stderr, gettext("cannot %s '%s': "
6697 "permission denied\n"), cmdname,
6703 * Ignore any filesystems which don't apply to us. This
6704 * includes those with a legacy mountpoint, or those with
6705 * legacy share options.
6707 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
6708 sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
6709 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
6710 sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
6711 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
6712 sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
6714 if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
6715 strcmp(smbshareopts, "off") == 0) {
6719 (void) fprintf(stderr, gettext("cannot share '%s': "
6720 "legacy share\n"), zfs_get_name(zhp));
6721 (void) fprintf(stderr, gettext("use exports(5) or "
6722 "smb.conf(5) to share this filesystem, or set "
6723 "the sharenfs or sharesmb property\n"));
6728 * We cannot share or mount legacy filesystems. If the
6729 * shareopts is non-legacy but the mountpoint is legacy, we
6730 * treat it as a legacy share.
6732 if (strcmp(mountpoint, "legacy") == 0) {
6736 (void) fprintf(stderr, gettext("cannot %s '%s': "
6737 "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
6738 (void) fprintf(stderr, gettext("use %s(8) to "
6739 "%s this filesystem\n"), cmdname, cmdname);
6743 if (strcmp(mountpoint, "none") == 0) {
6747 (void) fprintf(stderr, gettext("cannot %s '%s': no "
6748 "mountpoint set\n"), cmdname, zfs_get_name(zhp));
6753 * canmount explicit outcome
6754 * on no pass through
6755 * on yes pass through
6757 * off yes display error, return 1
6758 * noauto no return 0
6759 * noauto yes pass through
6761 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
6762 if (canmount == ZFS_CANMOUNT_OFF) {
6766 (void) fprintf(stderr, gettext("cannot %s '%s': "
6767 "'canmount' property is set to 'off'\n"), cmdname,
6770 } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
6772 * When performing a 'zfs mount -a', we skip any mounts for
6773 * datasets that have 'noauto' set. Sharing a dataset with
6774 * 'noauto' set is only allowed if it's mounted.
6778 if (op == OP_SHARE && !zfs_is_mounted(zhp, NULL)) {
6779 /* also purge it from existing exports */
6780 zfs_unshareall_bypath(zhp, mountpoint);
6786 * If this filesystem is encrypted and does not have
6787 * a loaded key, we can not mount it.
6789 if ((flags & MS_CRYPT) == 0 &&
6790 zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) != ZIO_CRYPT_OFF &&
6791 zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS) ==
6792 ZFS_KEYSTATUS_UNAVAILABLE) {
6796 (void) fprintf(stderr, gettext("cannot %s '%s': "
6797 "encryption key not loaded\n"), cmdname, zfs_get_name(zhp));
6802 * If this filesystem is inconsistent and has a receive resume
6803 * token, we can not mount it.
6805 if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) &&
6806 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
6807 NULL, 0, NULL, NULL, 0, B_TRUE) == 0) {
6811 (void) fprintf(stderr, gettext("cannot %s '%s': "
6812 "Contains partially-completed state from "
6813 "\"zfs receive -s\", which can be resumed with "
6814 "\"zfs send -t\"\n"),
6815 cmdname, zfs_get_name(zhp));
6819 if (zfs_prop_get_int(zhp, ZFS_PROP_REDACTED) && !(flags & MS_FORCE)) {
6823 (void) fprintf(stderr, gettext("cannot %s '%s': "
6824 "Dataset is not complete, was created by receiving "
6825 "a redacted zfs send stream.\n"), cmdname,
6831 * At this point, we have verified that the mountpoint and/or
6832 * shareopts are appropriate for auto management. If the
6833 * filesystem is already mounted or shared, return (failing
6834 * for explicit requests); otherwise mount or share the
6840 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
6841 shared_smb = zfs_is_shared_smb(zhp, NULL);
6843 if ((shared_nfs && shared_smb) ||
6844 (shared_nfs && strcmp(shareopts, "on") == 0 &&
6845 strcmp(smbshareopts, "off") == 0) ||
6846 (shared_smb && strcmp(smbshareopts, "on") == 0 &&
6847 strcmp(shareopts, "off") == 0)) {
6851 (void) fprintf(stderr, gettext("cannot share "
6852 "'%s': filesystem already shared\n"),
6857 if (!zfs_is_mounted(zhp, NULL) &&
6858 zfs_mount(zhp, NULL, flags) != 0)
6861 if (protocol == NULL) {
6862 if (zfs_shareall(zhp) != 0)
6864 } else if (strcmp(protocol, "nfs") == 0) {
6865 if (zfs_share_nfs(zhp))
6867 } else if (strcmp(protocol, "smb") == 0) {
6868 if (zfs_share_smb(zhp))
6871 (void) fprintf(stderr, gettext("cannot share "
6872 "'%s': invalid share type '%s' "
6874 zfs_get_name(zhp), protocol);
6881 if (options == NULL)
6882 mnt.mnt_mntopts = "";
6884 mnt.mnt_mntopts = (char *)options;
6886 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
6887 zfs_is_mounted(zhp, NULL)) {
6891 (void) fprintf(stderr, gettext("cannot mount "
6892 "'%s': filesystem already mounted\n"),
6897 if (zfs_mount(zhp, options, flags) != 0)
6906 * Reports progress in the form "(current/total)". Not thread-safe.
6909 report_mount_progress(int current, int total)
6911 static time_t last_progress_time = 0;
6912 time_t now = time(NULL);
6915 /* display header if we're here for the first time */
6917 set_progress_header(gettext("Mounting ZFS filesystems"));
6918 } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
6919 /* too soon to report again */
6923 last_progress_time = now;
6925 (void) sprintf(info, "(%d/%d)", current, total);
6927 if (current == total)
6928 finish_progress(info);
6930 update_progress(info);
6934 * zfs_foreach_mountpoint() callback that mounts or shares one filesystem and
6935 * updates the progress meter.
6938 share_mount_one_cb(zfs_handle_t *zhp, void *arg)
6940 share_mount_state_t *sms = arg;
6943 ret = share_mount_one(zhp, sms->sm_op, sms->sm_flags, sms->sm_proto,
6944 B_FALSE, sms->sm_options);
6946 pthread_mutex_lock(&sms->sm_lock);
6948 sms->sm_status = ret;
6950 if (sms->sm_verbose)
6951 report_mount_progress(sms->sm_done, sms->sm_total);
6952 pthread_mutex_unlock(&sms->sm_lock);
6957 append_options(char *mntopts, char *newopts)
6959 int len = strlen(mntopts);
6961 /* original length plus new string to append plus 1 for the comma */
6962 if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
6963 (void) fprintf(stderr, gettext("the opts argument for "
6964 "'%s' option is too long (more than %d chars)\n"),
6965 "-o", MNT_LINE_MAX);
6970 mntopts[len++] = ',';
6972 (void) strcpy(&mntopts[len], newopts);
6976 share_mount(int op, int argc, char **argv)
6979 boolean_t verbose = B_FALSE;
6981 char *options = NULL;
6985 while ((c = getopt(argc, argv, op == OP_MOUNT ? ":alvo:Of" : "al"))
6998 if (*optarg == '\0') {
6999 (void) fprintf(stderr, gettext("empty mount "
7000 "options (-o) specified\n"));
7004 if (options == NULL)
7005 options = safe_malloc(MNT_LINE_MAX + 1);
7007 /* option validation is done later */
7008 append_options(options, optarg);
7011 flags |= MS_OVERLAY;
7017 (void) fprintf(stderr, gettext("missing argument for "
7018 "'%c' option\n"), optopt);
7022 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7031 /* check number of arguments */
7033 char *protocol = NULL;
7035 if (op == OP_SHARE && argc > 0) {
7036 if (strcmp(argv[0], "nfs") != 0 &&
7037 strcmp(argv[0], "smb") != 0) {
7038 (void) fprintf(stderr, gettext("share type "
7039 "must be 'nfs' or 'smb'\n"));
7048 (void) fprintf(stderr, gettext("too many arguments\n"));
7052 start_progress_timer();
7053 get_all_cb_t cb = { 0 };
7054 get_all_datasets(&cb, verbose);
7056 if (cb.cb_used == 0) {
7057 if (options != NULL)
7062 share_mount_state_t share_mount_state = { 0 };
7063 share_mount_state.sm_op = op;
7064 share_mount_state.sm_verbose = verbose;
7065 share_mount_state.sm_flags = flags;
7066 share_mount_state.sm_options = options;
7067 share_mount_state.sm_proto = protocol;
7068 share_mount_state.sm_total = cb.cb_used;
7069 pthread_mutex_init(&share_mount_state.sm_lock, NULL);
7072 * libshare isn't mt-safe, so only do the operation in parallel
7073 * if we're mounting. Additionally, the key-loading option must
7074 * be serialized so that we can prompt the user for their keys
7075 * in a consistent manner.
7077 zfs_foreach_mountpoint(g_zfs, cb.cb_handles, cb.cb_used,
7078 share_mount_one_cb, &share_mount_state,
7079 op == OP_MOUNT && !(flags & MS_CRYPT));
7080 zfs_commit_all_shares();
7082 ret = share_mount_state.sm_status;
7084 for (int i = 0; i < cb.cb_used; i++)
7085 zfs_close(cb.cb_handles[i]);
7086 free(cb.cb_handles);
7087 } else if (argc == 0) {
7088 struct mnttab entry;
7090 if ((op == OP_SHARE) || (options != NULL)) {
7091 (void) fprintf(stderr, gettext("missing filesystem "
7092 "argument (specify -a for all)\n"));
7097 * When mount is given no arguments, go through
7098 * /proc/self/mounts and display any active ZFS mounts.
7099 * We hide any snapshots, since they are controlled
7103 /* Reopen MNTTAB to prevent reading stale data from open file */
7104 if (freopen(MNTTAB, "r", mnttab_file) == NULL) {
7105 if (options != NULL)
7110 while (getmntent(mnttab_file, &entry) == 0) {
7111 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
7112 strchr(entry.mnt_special, '@') != NULL)
7115 (void) printf("%-30s %s\n", entry.mnt_special,
7123 (void) fprintf(stderr,
7124 gettext("too many arguments\n"));
7128 if ((zhp = zfs_open(g_zfs, argv[0],
7129 ZFS_TYPE_FILESYSTEM)) == NULL) {
7132 ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
7134 zfs_commit_all_shares();
7139 if (options != NULL)
7146 * zfs mount -a [nfs]
7147 * zfs mount filesystem
7149 * Mount all filesystems, or mount the given filesystem.
7152 zfs_do_mount(int argc, char **argv)
7154 return (share_mount(OP_MOUNT, argc, argv));
7158 * zfs share -a [nfs | smb]
7159 * zfs share filesystem
7161 * Share all filesystems, or share the given filesystem.
7164 zfs_do_share(int argc, char **argv)
7166 return (share_mount(OP_SHARE, argc, argv));
7169 typedef struct unshare_unmount_node {
7170 zfs_handle_t *un_zhp;
7172 uu_avl_node_t un_avlnode;
7173 } unshare_unmount_node_t;
7177 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
7179 const unshare_unmount_node_t *l = larg;
7180 const unshare_unmount_node_t *r = rarg;
7182 return (strcmp(l->un_mountp, r->un_mountp));
7186 * Convenience routine used by zfs_do_umount() and manual_unmount(). Given an
7187 * absolute path, find the entry /proc/self/mounts, verify that it's a
7188 * ZFS filesystem, and unmount it appropriately.
7191 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
7195 struct stat64 statbuf;
7196 struct extmnttab entry;
7197 const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
7201 * Search for the given (major,minor) pair in the mount table.
7204 /* Reopen MNTTAB to prevent reading stale data from open file */
7205 if (freopen(MNTTAB, "r", mnttab_file) == NULL)
7208 if (getextmntent(path, &entry, &statbuf) != 0) {
7209 if (op == OP_SHARE) {
7210 (void) fprintf(stderr, gettext("cannot %s '%s': not "
7211 "currently mounted\n"), cmdname, path);
7214 (void) fprintf(stderr, gettext("warning: %s not in"
7215 "/proc/self/mounts\n"), path);
7216 if ((ret = umount2(path, flags)) != 0)
7217 (void) fprintf(stderr, gettext("%s: %s\n"), path,
7221 path_inode = statbuf.st_ino;
7223 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
7224 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
7225 "filesystem\n"), cmdname, path);
7229 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
7230 ZFS_TYPE_FILESYSTEM)) == NULL)
7234 if (stat64(entry.mnt_mountp, &statbuf) != 0) {
7235 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
7236 cmdname, path, strerror(errno));
7238 } else if (statbuf.st_ino != path_inode) {
7239 (void) fprintf(stderr, gettext("cannot "
7240 "%s '%s': not a mountpoint\n"), cmdname, path);
7244 if (op == OP_SHARE) {
7245 char nfs_mnt_prop[ZFS_MAXPROPLEN];
7246 char smbshare_prop[ZFS_MAXPROPLEN];
7248 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
7249 sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
7250 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
7251 sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
7253 if (strcmp(nfs_mnt_prop, "off") == 0 &&
7254 strcmp(smbshare_prop, "off") == 0) {
7255 (void) fprintf(stderr, gettext("cannot unshare "
7256 "'%s': legacy share\n"), path);
7257 (void) fprintf(stderr, gettext("use exportfs(8) "
7258 "or smbcontrol(1) to unshare this filesystem\n"));
7259 } else if (!zfs_is_shared(zhp)) {
7260 (void) fprintf(stderr, gettext("cannot unshare '%s': "
7261 "not currently shared\n"), path);
7263 ret = zfs_unshareall_bypath(zhp, path);
7264 zfs_commit_all_shares();
7267 char mtpt_prop[ZFS_MAXPROPLEN];
7269 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
7270 sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
7273 ret = zfs_unmount(zhp, NULL, flags);
7274 } else if (strcmp(mtpt_prop, "legacy") == 0) {
7275 (void) fprintf(stderr, gettext("cannot unmount "
7276 "'%s': legacy mountpoint\n"),
7278 (void) fprintf(stderr, gettext("use umount(8) "
7279 "to unmount this filesystem\n"));
7281 ret = zfs_unmountall(zhp, flags);
7292 * Generic callback for unsharing or unmounting a filesystem.
7295 unshare_unmount(int op, int argc, char **argv)
7302 char nfs_mnt_prop[ZFS_MAXPROPLEN];
7303 char sharesmb[ZFS_MAXPROPLEN];
7306 while ((c = getopt(argc, argv, op == OP_SHARE ? ":a" : "afu")) != -1) {
7318 (void) fprintf(stderr, gettext("missing argument for "
7319 "'%c' option\n"), optopt);
7323 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7334 * We could make use of zfs_for_each() to walk all datasets in
7335 * the system, but this would be very inefficient, especially
7336 * since we would have to linearly search /proc/self/mounts for
7337 * each one. Instead, do one pass through /proc/self/mounts
7338 * looking for zfs entries and call zfs_unmount() for each one.
7340 * Things get a little tricky if the administrator has created
7341 * mountpoints beneath other ZFS filesystems. In this case, we
7342 * have to unmount the deepest filesystems first. To accomplish
7343 * this, we place all the mountpoints in an AVL tree sorted by
7344 * the special type (dataset name), and walk the result in
7345 * reverse to make sure to get any snapshots first.
7347 struct mnttab entry;
7348 uu_avl_pool_t *pool;
7349 uu_avl_t *tree = NULL;
7350 unshare_unmount_node_t *node;
7352 uu_avl_walk_t *walk;
7353 char *protocol = NULL;
7355 if (op == OP_SHARE && argc > 0) {
7356 if (strcmp(argv[0], "nfs") != 0 &&
7357 strcmp(argv[0], "smb") != 0) {
7358 (void) fprintf(stderr, gettext("share type "
7359 "must be 'nfs' or 'smb'\n"));
7368 (void) fprintf(stderr, gettext("too many arguments\n"));
7372 if (((pool = uu_avl_pool_create("unmount_pool",
7373 sizeof (unshare_unmount_node_t),
7374 offsetof(unshare_unmount_node_t, un_avlnode),
7375 unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
7376 ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
7379 /* Reopen MNTTAB to prevent reading stale data from open file */
7380 if (freopen(MNTTAB, "r", mnttab_file) == NULL)
7383 while (getmntent(mnttab_file, &entry) == 0) {
7385 /* ignore non-ZFS entries */
7386 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
7389 /* ignore snapshots */
7390 if (strchr(entry.mnt_special, '@') != NULL)
7393 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
7394 ZFS_TYPE_FILESYSTEM)) == NULL) {
7400 * Ignore datasets that are excluded/restricted by
7403 if (zpool_skip_pool(zfs_get_pool_name(zhp))) {
7410 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
7412 sizeof (nfs_mnt_prop),
7413 NULL, NULL, 0, B_FALSE) == 0);
7414 if (strcmp(nfs_mnt_prop, "off") != 0)
7416 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
7418 sizeof (nfs_mnt_prop),
7419 NULL, NULL, 0, B_FALSE) == 0);
7420 if (strcmp(nfs_mnt_prop, "off") == 0)
7424 /* Ignore legacy mounts */
7425 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
7427 sizeof (nfs_mnt_prop),
7428 NULL, NULL, 0, B_FALSE) == 0);
7429 if (strcmp(nfs_mnt_prop, "legacy") == 0)
7431 /* Ignore canmount=noauto mounts */
7432 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
7433 ZFS_CANMOUNT_NOAUTO)
7439 node = safe_malloc(sizeof (unshare_unmount_node_t));
7441 node->un_mountp = safe_strdup(entry.mnt_mountp);
7443 uu_avl_node_init(node, &node->un_avlnode, pool);
7445 if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
7446 uu_avl_insert(tree, node, idx);
7448 zfs_close(node->un_zhp);
7449 free(node->un_mountp);
7455 * Walk the AVL tree in reverse, unmounting each filesystem and
7456 * removing it from the AVL tree in the process.
7458 if ((walk = uu_avl_walk_start(tree,
7459 UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
7462 while ((node = uu_avl_walk_next(walk)) != NULL) {
7463 const char *mntarg = NULL;
7465 uu_avl_remove(tree, node);
7468 if (zfs_unshareall_bytype(node->un_zhp,
7469 node->un_mountp, protocol) != 0)
7474 if (zfs_unmount(node->un_zhp,
7475 mntarg, flags) != 0)
7480 zfs_close(node->un_zhp);
7481 free(node->un_mountp);
7486 zfs_commit_shares(protocol);
7488 uu_avl_walk_end(walk);
7489 uu_avl_destroy(tree);
7490 uu_avl_pool_destroy(pool);
7495 (void) fprintf(stderr,
7496 gettext("missing filesystem argument\n"));
7498 (void) fprintf(stderr,
7499 gettext("too many arguments\n"));
7504 * We have an argument, but it may be a full path or a ZFS
7505 * filesystem. Pass full paths off to unmount_path() (shared by
7506 * manual_unmount), otherwise open the filesystem and pass to
7509 if (argv[0][0] == '/')
7510 return (unshare_unmount_path(op, argv[0],
7513 if ((zhp = zfs_open(g_zfs, argv[0],
7514 ZFS_TYPE_FILESYSTEM)) == NULL)
7517 verify(zfs_prop_get(zhp, op == OP_SHARE ?
7518 ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
7519 nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
7520 NULL, 0, B_FALSE) == 0);
7524 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
7526 sizeof (nfs_mnt_prop),
7527 NULL, NULL, 0, B_FALSE) == 0);
7528 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
7529 sharesmb, sizeof (sharesmb), NULL, NULL,
7532 if (strcmp(nfs_mnt_prop, "off") == 0 &&
7533 strcmp(sharesmb, "off") == 0) {
7534 (void) fprintf(stderr, gettext("cannot "
7535 "unshare '%s': legacy share\n"),
7537 (void) fprintf(stderr, gettext("use "
7538 "exports(5) or smb.conf(5) to unshare "
7539 "this filesystem\n"));
7541 } else if (!zfs_is_shared(zhp)) {
7542 (void) fprintf(stderr, gettext("cannot "
7543 "unshare '%s': not currently "
7544 "shared\n"), zfs_get_name(zhp));
7546 } else if (zfs_unshareall(zhp) != 0) {
7552 if (strcmp(nfs_mnt_prop, "legacy") == 0) {
7553 (void) fprintf(stderr, gettext("cannot "
7554 "unmount '%s': legacy "
7555 "mountpoint\n"), zfs_get_name(zhp));
7556 (void) fprintf(stderr, gettext("use "
7557 "umount(8) to unmount this "
7560 } else if (!zfs_is_mounted(zhp, NULL)) {
7561 (void) fprintf(stderr, gettext("cannot "
7562 "unmount '%s': not currently "
7566 } else if (zfs_unmountall(zhp, flags) != 0) {
7579 * zfs unmount [-fu] -a
7580 * zfs unmount [-fu] filesystem
7582 * Unmount all filesystems, or a specific ZFS filesystem.
7585 zfs_do_unmount(int argc, char **argv)
7587 return (unshare_unmount(OP_MOUNT, argc, argv));
7592 * zfs unshare filesystem
7594 * Unshare all filesystems, or a specific ZFS filesystem.
7597 zfs_do_unshare(int argc, char **argv)
7599 return (unshare_unmount(OP_SHARE, argc, argv));
7603 find_command_idx(char *command, int *idx)
7607 for (i = 0; i < NCOMMAND; i++) {
7608 if (command_table[i].name == NULL)
7611 if (strcmp(command, command_table[i].name) == 0) {
7620 zfs_do_diff(int argc, char **argv)
7624 char *tosnap = NULL;
7625 char *fromsnap = NULL;
7629 struct sigaction sa;
7631 while ((c = getopt(argc, argv, "FHt")) != -1) {
7634 flags |= ZFS_DIFF_CLASSIFY;
7637 flags |= ZFS_DIFF_PARSEABLE;
7640 flags |= ZFS_DIFF_TIMESTAMP;
7643 (void) fprintf(stderr,
7644 gettext("invalid option '%c'\n"), optopt);
7653 (void) fprintf(stderr,
7654 gettext("must provide at least one snapshot name\n"));
7659 (void) fprintf(stderr, gettext("too many arguments\n"));
7664 tosnap = (argc == 2) ? argv[1] : NULL;
7667 if (*fromsnap != '@')
7668 copy = strdup(fromsnap);
7670 copy = strdup(tosnap);
7674 if ((atp = strchr(copy, '@')) != NULL)
7677 if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL) {
7684 * Ignore SIGPIPE so that the library can give us
7685 * information on any failure
7687 if (sigemptyset(&sa.sa_mask) == -1) {
7692 sa.sa_handler = SIG_IGN;
7693 if (sigaction(SIGPIPE, &sa, NULL) == -1) {
7698 err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
7706 * zfs bookmark <fs@source>|<fs#source> <fs#bookmark>
7708 * Creates a bookmark with the given name from the source snapshot
7709 * or creates a copy of an existing source bookmark.
7712 zfs_do_bookmark(int argc, char **argv)
7714 char *source, *bookname;
7715 char expbuf[ZFS_MAX_DATASET_NAME_LEN];
7722 while ((c = getopt(argc, argv, "")) != -1) {
7725 (void) fprintf(stderr,
7726 gettext("invalid option '%c'\n"), optopt);
7734 /* check number of arguments */
7736 (void) fprintf(stderr, gettext("missing source argument\n"));
7740 (void) fprintf(stderr, gettext("missing bookmark argument\n"));
7747 if (strchr(source, '@') == NULL && strchr(source, '#') == NULL) {
7748 (void) fprintf(stderr,
7749 gettext("invalid source name '%s': "
7750 "must contain a '@' or '#'\n"), source);
7753 if (strchr(bookname, '#') == NULL) {
7754 (void) fprintf(stderr,
7755 gettext("invalid bookmark name '%s': "
7756 "must contain a '#'\n"), bookname);
7761 * expand source or bookname to full path:
7762 * one of them may be specified as short name
7766 char *source_short, *bookname_short;
7767 source_short = strpbrk(source, "@#");
7768 bookname_short = strpbrk(bookname, "#");
7769 if (source_short == source &&
7770 bookname_short == bookname) {
7771 (void) fprintf(stderr, gettext(
7772 "either source or bookmark must be specified as "
7773 "full dataset paths"));
7775 } else if (source_short != source &&
7776 bookname_short != bookname) {
7778 } else if (source_short != source) {
7779 strlcpy(expbuf, source, sizeof (expbuf));
7781 } else if (bookname_short != bookname) {
7782 strlcpy(expbuf, bookname, sizeof (expbuf));
7787 if (expand != NULL) {
7788 *strpbrk(expbuf, "@#") = '\0'; /* dataset name in buf */
7789 (void) strlcat(expbuf, *expand, sizeof (expbuf));
7794 /* determine source type */
7795 switch (*strpbrk(source, "@#")) {
7796 case '@': source_type = ZFS_TYPE_SNAPSHOT; break;
7797 case '#': source_type = ZFS_TYPE_BOOKMARK; break;
7801 /* test the source exists */
7803 zhp = zfs_open(g_zfs, source, source_type);
7808 nvl = fnvlist_alloc();
7809 fnvlist_add_string(nvl, bookname, source);
7810 ret = lzc_bookmark(nvl, NULL);
7814 const char *err_msg = NULL;
7817 (void) snprintf(errbuf, sizeof (errbuf),
7818 dgettext(TEXT_DOMAIN,
7819 "cannot create bookmark '%s'"), bookname);
7823 err_msg = "bookmark is in a different pool";
7825 case ZFS_ERR_BOOKMARK_SOURCE_NOT_ANCESTOR:
7826 err_msg = "source is not an ancestor of the "
7827 "new bookmark's dataset";
7830 err_msg = "bookmark exists";
7833 err_msg = "invalid argument";
7836 err_msg = "bookmark feature not enabled";
7839 err_msg = "out of space";
7842 err_msg = "dataset does not exist";
7845 (void) zfs_standard_error(g_zfs, ret, errbuf);
7848 if (err_msg != NULL) {
7849 (void) fprintf(stderr, "%s: %s\n", errbuf,
7850 dgettext(TEXT_DOMAIN, err_msg));
7862 zfs_do_channel_program(int argc, char **argv)
7865 char *progbuf, *filename, *poolname;
7866 size_t progsize, progread;
7867 nvlist_t *outnvl = NULL;
7868 uint64_t instrlimit = ZCP_DEFAULT_INSTRLIMIT;
7869 uint64_t memlimit = ZCP_DEFAULT_MEMLIMIT;
7870 boolean_t sync_flag = B_TRUE, json_output = B_FALSE;
7871 zpool_handle_t *zhp;
7874 while ((c = getopt(argc, argv, "nt:m:j")) != -1) {
7882 arg = strtoull(optarg, &endp, 0);
7883 if (errno != 0 || *endp != '\0') {
7884 (void) fprintf(stderr, gettext(
7886 "'%s': expected integer\n"), optarg);
7893 ASSERT3U(c, ==, 'm');
7899 sync_flag = B_FALSE;
7903 json_output = B_TRUE;
7907 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7917 (void) fprintf(stderr,
7918 gettext("invalid number of arguments\n"));
7924 if (strcmp(filename, "-") == 0) {
7926 filename = "standard input";
7927 } else if ((fd = open(filename, O_RDONLY)) < 0) {
7928 (void) fprintf(stderr, gettext("cannot open '%s': %s\n"),
7929 filename, strerror(errno));
7933 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
7934 (void) fprintf(stderr, gettext("cannot open pool '%s'\n"),
7943 * Read in the channel program, expanding the program buffer as
7948 progbuf = safe_malloc(progsize);
7950 ret = read(fd, progbuf + progread, progsize - progread);
7952 if (progread == progsize && ret > 0) {
7954 progbuf = safe_realloc(progbuf, progsize);
7962 (void) fprintf(stderr,
7963 gettext("cannot read '%s': %s\n"),
7964 filename, strerror(errno));
7967 progbuf[progread] = '\0';
7970 * Any remaining arguments are passed as arguments to the lua script as
7973 * "argv" -> [ "arg 1", ... "arg n" ],
7976 nvlist_t *argnvl = fnvlist_alloc();
7977 fnvlist_add_string_array(argnvl, ZCP_ARG_CLIARGV, argv + 2, argc - 2);
7980 ret = lzc_channel_program(poolname, progbuf,
7981 instrlimit, memlimit, argnvl, &outnvl);
7983 ret = lzc_channel_program_nosync(poolname, progbuf,
7984 instrlimit, memlimit, argnvl, &outnvl);
7989 * On error, report the error message handed back by lua if one
7990 * exists. Otherwise, generate an appropriate error message,
7991 * falling back on strerror() for an unexpected return code.
7993 char *errstring = NULL;
7994 const char *msg = gettext("Channel program execution failed");
7995 uint64_t instructions = 0;
7996 if (outnvl != NULL && nvlist_exists(outnvl, ZCP_RET_ERROR)) {
7997 (void) nvlist_lookup_string(outnvl,
7998 ZCP_RET_ERROR, &errstring);
7999 if (errstring == NULL)
8000 errstring = strerror(ret);
8002 (void) nvlist_lookup_uint64(outnvl,
8003 ZCP_ARG_INSTRLIMIT, &instructions);
8009 "Invalid instruction or memory limit.";
8012 errstring = "Return value too large.";
8015 errstring = "Memory limit exhausted.";
8018 errstring = "Timed out.";
8021 errstring = "Permission denied. Channel "
8022 "programs must be run as root.";
8025 (void) zfs_standard_error(g_zfs, ret, msg);
8028 if (errstring != NULL)
8029 (void) fprintf(stderr, "%s:\n%s\n", msg, errstring);
8031 if (ret == ETIME && instructions != 0)
8032 (void) fprintf(stderr,
8033 gettext("%llu Lua instructions\n"),
8034 (u_longlong_t)instructions);
8037 (void) nvlist_print_json(stdout, outnvl);
8038 } else if (nvlist_empty(outnvl)) {
8039 (void) fprintf(stdout, gettext("Channel program fully "
8040 "executed and did not produce output.\n"));
8042 (void) fprintf(stdout, gettext("Channel program fully "
8043 "executed and produced output:\n"));
8044 dump_nvlist(outnvl, 4);
8049 fnvlist_free(outnvl);
8050 fnvlist_free(argnvl);
8059 typedef struct loadkey_cbdata {
8060 boolean_t cb_loadkey;
8061 boolean_t cb_recursive;
8063 char *cb_keylocation;
8064 uint64_t cb_numfailed;
8065 uint64_t cb_numattempted;
8069 load_key_callback(zfs_handle_t *zhp, void *data)
8072 boolean_t is_encroot;
8073 loadkey_cbdata_t *cb = data;
8074 uint64_t keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
8077 * If we are working recursively, we want to skip loading / unloading
8078 * keys for non-encryption roots and datasets whose keys are already
8079 * in the desired end-state.
8081 if (cb->cb_recursive) {
8082 ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
8088 if ((cb->cb_loadkey && keystatus == ZFS_KEYSTATUS_AVAILABLE) ||
8089 (!cb->cb_loadkey && keystatus == ZFS_KEYSTATUS_UNAVAILABLE))
8093 cb->cb_numattempted++;
8096 ret = zfs_crypto_load_key(zhp, cb->cb_noop, cb->cb_keylocation);
8098 ret = zfs_crypto_unload_key(zhp);
8109 load_unload_keys(int argc, char **argv, boolean_t loadkey)
8111 int c, ret = 0, flags = 0;
8112 boolean_t do_all = B_FALSE;
8113 loadkey_cbdata_t cb = { 0 };
8115 cb.cb_loadkey = loadkey;
8117 while ((c = getopt(argc, argv, "anrL:")) != -1) {
8118 /* noop and alternate keylocations only apply to zfs load-key */
8122 cb.cb_noop = B_TRUE;
8125 cb.cb_keylocation = optarg;
8135 cb.cb_recursive = B_TRUE;
8138 flags |= ZFS_ITER_RECURSE;
8139 cb.cb_recursive = B_TRUE;
8142 (void) fprintf(stderr,
8143 gettext("invalid option '%c'\n"), optopt);
8151 if (!do_all && argc == 0) {
8152 (void) fprintf(stderr,
8153 gettext("Missing dataset argument or -a option\n"));
8157 if (do_all && argc != 0) {
8158 (void) fprintf(stderr,
8159 gettext("Cannot specify dataset with -a option\n"));
8163 if (cb.cb_recursive && cb.cb_keylocation != NULL &&
8164 strcmp(cb.cb_keylocation, "prompt") != 0) {
8165 (void) fprintf(stderr, gettext("alternate keylocation may only "
8166 "be 'prompt' with -r or -a\n"));
8170 ret = zfs_for_each(argc, argv, flags,
8171 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME, NULL, NULL, 0,
8172 load_key_callback, &cb);
8174 if (cb.cb_noop || (cb.cb_recursive && cb.cb_numattempted != 0)) {
8175 (void) printf(gettext("%llu / %llu key(s) successfully %s\n"),
8176 (u_longlong_t)(cb.cb_numattempted - cb.cb_numfailed),
8177 (u_longlong_t)cb.cb_numattempted,
8178 loadkey ? (cb.cb_noop ? "verified" : "loaded") :
8182 if (cb.cb_numfailed != 0)
8189 zfs_do_load_key(int argc, char **argv)
8191 return (load_unload_keys(argc, argv, B_TRUE));
8196 zfs_do_unload_key(int argc, char **argv)
8198 return (load_unload_keys(argc, argv, B_FALSE));
8202 zfs_do_change_key(int argc, char **argv)
8206 boolean_t loadkey = B_FALSE, inheritkey = B_FALSE;
8207 zfs_handle_t *zhp = NULL;
8208 nvlist_t *props = fnvlist_alloc();
8210 while ((c = getopt(argc, argv, "lio:")) != -1) {
8216 inheritkey = B_TRUE;
8219 if (!parseprop(props, optarg)) {
8225 (void) fprintf(stderr,
8226 gettext("invalid option '%c'\n"), optopt);
8231 if (inheritkey && !nvlist_empty(props)) {
8232 (void) fprintf(stderr,
8233 gettext("Properties not allowed for inheriting\n"));
8241 (void) fprintf(stderr, gettext("Missing dataset argument\n"));
8246 (void) fprintf(stderr, gettext("Too many arguments\n"));
8250 zhp = zfs_open(g_zfs, argv[argc - 1],
8251 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
8256 keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
8257 if (keystatus != ZFS_KEYSTATUS_AVAILABLE) {
8258 ret = zfs_crypto_load_key(zhp, B_FALSE, NULL);
8266 /* refresh the properties so the new keystatus is visible */
8267 zfs_refresh_properties(zhp);
8270 ret = zfs_crypto_rewrap(zhp, props, inheritkey);
8283 * 1) zfs project [-d|-r] <file|directory ...>
8284 * List project ID and inherit flag of file(s) or directories.
8285 * -d: List the directory itself, not its children.
8286 * -r: List subdirectories recursively.
8288 * 2) zfs project -C [-k] [-r] <file|directory ...>
8289 * Clear project inherit flag and/or ID on the file(s) or directories.
8290 * -k: Keep the project ID unchanged. If not specified, the project ID
8291 * will be reset as zero.
8292 * -r: Clear on subdirectories recursively.
8294 * 3) zfs project -c [-0] [-d|-r] [-p id] <file|directory ...>
8295 * Check project ID and inherit flag on the file(s) or directories,
8296 * report the outliers.
8297 * -0: Print file name followed by a NUL instead of newline.
8298 * -d: Check the directory itself, not its children.
8299 * -p: Specify the referenced ID for comparing with the target file(s)
8300 * or directories' project IDs. If not specified, the target (top)
8301 * directory's project ID will be used as the referenced one.
8302 * -r: Check subdirectories recursively.
8304 * 4) zfs project [-p id] [-r] [-s] <file|directory ...>
8305 * Set project ID and/or inherit flag on the file(s) or directories.
8306 * -p: Set the project ID as the given id.
8307 * -r: Set on subdirectories recursively. If not specify "-p" option,
8308 * it will use top-level directory's project ID as the given id,
8309 * then set both project ID and inherit flag on all descendants
8310 * of the top-level directory.
8311 * -s: Set project inherit flag.
8314 zfs_do_project(int argc, char **argv)
8316 zfs_project_control_t zpc = {
8317 .zpc_expected_projid = ZFS_INVALID_PROJID,
8318 .zpc_op = ZFS_PROJECT_OP_DEFAULT,
8319 .zpc_dironly = B_FALSE,
8320 .zpc_keep_projid = B_FALSE,
8321 .zpc_newline = B_TRUE,
8322 .zpc_recursive = B_FALSE,
8323 .zpc_set_flag = B_FALSE,
8330 while ((c = getopt(argc, argv, "0Ccdkp:rs")) != -1) {
8333 zpc.zpc_newline = B_FALSE;
8336 if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8337 (void) fprintf(stderr, gettext("cannot "
8338 "specify '-C' '-c' '-s' together\n"));
8342 zpc.zpc_op = ZFS_PROJECT_OP_CLEAR;
8345 if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8346 (void) fprintf(stderr, gettext("cannot "
8347 "specify '-C' '-c' '-s' together\n"));
8351 zpc.zpc_op = ZFS_PROJECT_OP_CHECK;
8354 zpc.zpc_dironly = B_TRUE;
8355 /* overwrite "-r" option */
8356 zpc.zpc_recursive = B_FALSE;
8359 zpc.zpc_keep_projid = B_TRUE;
8365 zpc.zpc_expected_projid = strtoull(optarg, &endptr, 0);
8366 if (errno != 0 || *endptr != '\0') {
8367 (void) fprintf(stderr,
8368 gettext("project ID must be less than "
8369 "%u\n"), UINT32_MAX);
8372 if (zpc.zpc_expected_projid >= UINT32_MAX) {
8373 (void) fprintf(stderr,
8374 gettext("invalid project ID\n"));
8380 zpc.zpc_recursive = B_TRUE;
8381 /* overwrite "-d" option */
8382 zpc.zpc_dironly = B_FALSE;
8385 if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8386 (void) fprintf(stderr, gettext("cannot "
8387 "specify '-C' '-c' '-s' together\n"));
8391 zpc.zpc_set_flag = B_TRUE;
8392 zpc.zpc_op = ZFS_PROJECT_OP_SET;
8395 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8401 if (zpc.zpc_op == ZFS_PROJECT_OP_DEFAULT) {
8402 if (zpc.zpc_expected_projid != ZFS_INVALID_PROJID)
8403 zpc.zpc_op = ZFS_PROJECT_OP_SET;
8405 zpc.zpc_op = ZFS_PROJECT_OP_LIST;
8408 switch (zpc.zpc_op) {
8409 case ZFS_PROJECT_OP_LIST:
8410 if (zpc.zpc_keep_projid) {
8411 (void) fprintf(stderr,
8412 gettext("'-k' is only valid together with '-C'\n"));
8415 if (!zpc.zpc_newline) {
8416 (void) fprintf(stderr,
8417 gettext("'-0' is only valid together with '-c'\n"));
8421 case ZFS_PROJECT_OP_CHECK:
8422 if (zpc.zpc_keep_projid) {
8423 (void) fprintf(stderr,
8424 gettext("'-k' is only valid together with '-C'\n"));
8428 case ZFS_PROJECT_OP_CLEAR:
8429 if (zpc.zpc_dironly) {
8430 (void) fprintf(stderr,
8431 gettext("'-d' is useless together with '-C'\n"));
8434 if (!zpc.zpc_newline) {
8435 (void) fprintf(stderr,
8436 gettext("'-0' is only valid together with '-c'\n"));
8439 if (zpc.zpc_expected_projid != ZFS_INVALID_PROJID) {
8440 (void) fprintf(stderr,
8441 gettext("'-p' is useless together with '-C'\n"));
8445 case ZFS_PROJECT_OP_SET:
8446 if (zpc.zpc_dironly) {
8447 (void) fprintf(stderr,
8448 gettext("'-d' is useless for set project ID and/or "
8452 if (zpc.zpc_keep_projid) {
8453 (void) fprintf(stderr,
8454 gettext("'-k' is only valid together with '-C'\n"));
8457 if (!zpc.zpc_newline) {
8458 (void) fprintf(stderr,
8459 gettext("'-0' is only valid together with '-c'\n"));
8471 (void) fprintf(stderr,
8472 gettext("missing file or directory target(s)\n"));
8476 for (int i = 0; i < argc; i++) {
8479 err = zfs_project_handle(argv[i], &zpc);
8488 zfs_do_wait(int argc, char **argv)
8490 boolean_t enabled[ZFS_WAIT_NUM_ACTIVITIES];
8494 /* By default, wait for all types of activity. */
8495 for (i = 0; i < ZFS_WAIT_NUM_ACTIVITIES; i++)
8496 enabled[i] = B_TRUE;
8498 while ((c = getopt(argc, argv, "t:")) != -1) {
8502 static char *col_subopts[] = { "deleteq", NULL };
8505 /* Reset activities array */
8506 bzero(&enabled, sizeof (enabled));
8507 while (*optarg != '\0') {
8508 int activity = getsubopt(&optarg, col_subopts,
8512 (void) fprintf(stderr,
8513 gettext("invalid activity '%s'\n"),
8518 enabled[activity] = B_TRUE;
8523 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8532 (void) fprintf(stderr, gettext("missing 'filesystem' "
8537 (void) fprintf(stderr, gettext("too many arguments\n"));
8541 zfs_handle_t *zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM);
8546 boolean_t missing = B_FALSE;
8547 boolean_t any_waited = B_FALSE;
8549 for (int i = 0; i < ZFS_WAIT_NUM_ACTIVITIES; i++) {
8555 error = zfs_wait_status(zhp, i, &missing, &waited);
8556 if (error != 0 || missing)
8559 any_waited = (any_waited || waited);
8562 if (error != 0 || missing || !any_waited)
8572 * Display version message
8575 zfs_do_version(int argc, char **argv)
8577 if (zfs_version_print() == -1)
8584 main(int argc, char **argv)
8591 (void) setlocale(LC_ALL, "");
8592 (void) setlocale(LC_NUMERIC, "C");
8593 (void) textdomain(TEXT_DOMAIN);
8598 * Make sure the user has specified some command.
8601 (void) fprintf(stderr, gettext("missing command\n"));
8608 * The 'umount' command is an alias for 'unmount'
8610 if (strcmp(cmdname, "umount") == 0)
8611 cmdname = "unmount";
8614 * The 'recv' command is an alias for 'receive'
8616 if (strcmp(cmdname, "recv") == 0)
8617 cmdname = "receive";
8620 * The 'snap' command is an alias for 'snapshot'
8622 if (strcmp(cmdname, "snap") == 0)
8623 cmdname = "snapshot";
8628 if ((strcmp(cmdname, "-?") == 0) ||
8629 (strcmp(cmdname, "--help") == 0))
8633 * Special case '-V|--version'
8635 if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
8636 return (zfs_do_version(argc, argv));
8638 if ((g_zfs = libzfs_init()) == NULL) {
8639 (void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
8643 mnttab_file = g_zfs->libzfs_mnttab;
8645 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
8647 libzfs_print_on_error(g_zfs, B_TRUE);
8650 * Many commands modify input strings for string parsing reasons.
8651 * We create a copy to protect the original argv.
8653 newargv = malloc((argc + 1) * sizeof (newargv[0]));
8654 for (i = 0; i < argc; i++)
8655 newargv[i] = strdup(argv[i]);
8656 newargv[argc] = NULL;
8659 * Run the appropriate command.
8661 libzfs_mnttab_cache(g_zfs, B_TRUE);
8662 if (find_command_idx(cmdname, &i) == 0) {
8663 current_command = &command_table[i];
8664 ret = command_table[i].func(argc - 1, newargv + 1);
8665 } else if (strchr(cmdname, '=') != NULL) {
8666 verify(find_command_idx("set", &i) == 0);
8667 current_command = &command_table[i];
8668 ret = command_table[i].func(argc, newargv);
8670 (void) fprintf(stderr, gettext("unrecognized "
8671 "command '%s'\n"), cmdname);
8676 for (i = 0; i < argc; i++)
8680 if (ret == 0 && log_history)
8681 (void) zpool_log_history(g_zfs, history_str);
8686 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
8687 * for the purposes of running ::findleaks.
8689 if (getenv("ZFS_ABORT") != NULL) {
8690 (void) printf("dumping core by request\n");
8698 #include <sys/jail.h>
8701 * Attach/detach the given dataset to/from the given jail
8705 zfs_do_jail_impl(int argc, char **argv, boolean_t attach)
8710 /* check number of arguments */
8712 (void) fprintf(stderr, gettext("missing argument(s)\n"));
8716 (void) fprintf(stderr, gettext("too many arguments\n"));
8720 jailid = jail_getid(argv[1]);
8722 (void) fprintf(stderr, gettext("invalid jail id or name\n"));
8726 zhp = zfs_open(g_zfs, argv[2], ZFS_TYPE_FILESYSTEM);
8730 ret = (zfs_jail(zhp, jailid, attach) != 0);
8737 * zfs jail jailid filesystem
8739 * Attach the given dataset to the given jail
8743 zfs_do_jail(int argc, char **argv)
8745 return (zfs_do_jail_impl(argc, argv, B_TRUE));
8749 * zfs unjail jailid filesystem
8751 * Detach the given dataset from the given jail
8755 zfs_do_unjail(int argc, char **argv)
8757 return (zfs_do_jail_impl(argc, argv, B_FALSE));