6659 nvlist_free(NULL) is a no-op
[illumos-gate.git] / usr / src / cmd / zfs / zfs_main.c
blobdb46fbc72b196ed74af51df1200e8c4e1de7aa59
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
25 * Copyright 2012 Milan Jurik. All rights reserved.
26 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
27 * Copyright (c) 2013 Steven Hartland. All rights reserved.
28 * Copyright (c) 2014 Integros [integros.com]
29 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
30 * Copyright 2016 Nexenta Systems, Inc.
33 #include <assert.h>
34 #include <ctype.h>
35 #include <errno.h>
36 #include <libgen.h>
37 #include <libintl.h>
38 #include <libuutil.h>
39 #include <libnvpair.h>
40 #include <locale.h>
41 #include <stddef.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <strings.h>
45 #include <unistd.h>
46 #include <fcntl.h>
47 #include <zone.h>
48 #include <grp.h>
49 #include <pwd.h>
50 #include <signal.h>
51 #include <sys/list.h>
52 #include <sys/mkdev.h>
53 #include <sys/mntent.h>
54 #include <sys/mnttab.h>
55 #include <sys/mount.h>
56 #include <sys/stat.h>
57 #include <sys/fs/zfs.h>
58 #include <sys/types.h>
59 #include <time.h>
61 #include <libzfs.h>
62 #include <libzfs_core.h>
63 #include <zfs_prop.h>
64 #include <zfs_deleg.h>
65 #include <libuutil.h>
66 #include <aclutils.h>
67 #include <directory.h>
68 #include <idmap.h>
70 #include "zfs_iter.h"
71 #include "zfs_util.h"
72 #include "zfs_comutil.h"
74 libzfs_handle_t *g_zfs;
76 static FILE *mnttab_file;
77 static char history_str[HIS_MAX_RECORD_LEN];
78 static boolean_t log_history = B_TRUE;
80 static int zfs_do_clone(int argc, char **argv);
81 static int zfs_do_create(int argc, char **argv);
82 static int zfs_do_destroy(int argc, char **argv);
83 static int zfs_do_get(int argc, char **argv);
84 static int zfs_do_inherit(int argc, char **argv);
85 static int zfs_do_list(int argc, char **argv);
86 static int zfs_do_mount(int argc, char **argv);
87 static int zfs_do_rename(int argc, char **argv);
88 static int zfs_do_rollback(int argc, char **argv);
89 static int zfs_do_set(int argc, char **argv);
90 static int zfs_do_upgrade(int argc, char **argv);
91 static int zfs_do_snapshot(int argc, char **argv);
92 static int zfs_do_unmount(int argc, char **argv);
93 static int zfs_do_share(int argc, char **argv);
94 static int zfs_do_unshare(int argc, char **argv);
95 static int zfs_do_send(int argc, char **argv);
96 static int zfs_do_receive(int argc, char **argv);
97 static int zfs_do_promote(int argc, char **argv);
98 static int zfs_do_userspace(int argc, char **argv);
99 static int zfs_do_allow(int argc, char **argv);
100 static int zfs_do_unallow(int argc, char **argv);
101 static int zfs_do_hold(int argc, char **argv);
102 static int zfs_do_holds(int argc, char **argv);
103 static int zfs_do_release(int argc, char **argv);
104 static int zfs_do_diff(int argc, char **argv);
105 static int zfs_do_bookmark(int argc, char **argv);
108 * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
111 #ifdef DEBUG
112 const char *
113 _umem_debug_init(void)
115 return ("default,verbose"); /* $UMEM_DEBUG setting */
118 const char *
119 _umem_logging_init(void)
121 return ("fail,contents"); /* $UMEM_LOGGING setting */
123 #endif
125 typedef enum {
126 HELP_CLONE,
127 HELP_CREATE,
128 HELP_DESTROY,
129 HELP_GET,
130 HELP_INHERIT,
131 HELP_UPGRADE,
132 HELP_LIST,
133 HELP_MOUNT,
134 HELP_PROMOTE,
135 HELP_RECEIVE,
136 HELP_RENAME,
137 HELP_ROLLBACK,
138 HELP_SEND,
139 HELP_SET,
140 HELP_SHARE,
141 HELP_SNAPSHOT,
142 HELP_UNMOUNT,
143 HELP_UNSHARE,
144 HELP_ALLOW,
145 HELP_UNALLOW,
146 HELP_USERSPACE,
147 HELP_GROUPSPACE,
148 HELP_HOLD,
149 HELP_HOLDS,
150 HELP_RELEASE,
151 HELP_DIFF,
152 HELP_BOOKMARK,
153 } zfs_help_t;
155 typedef struct zfs_command {
156 const char *name;
157 int (*func)(int argc, char **argv);
158 zfs_help_t usage;
159 } zfs_command_t;
162 * Master command table. Each ZFS command has a name, associated function, and
163 * usage message. The usage messages need to be internationalized, so we have
164 * to have a function to return the usage message based on a command index.
166 * These commands are organized according to how they are displayed in the usage
167 * message. An empty command (one with a NULL name) indicates an empty line in
168 * the generic usage message.
170 static zfs_command_t command_table[] = {
171 { "create", zfs_do_create, HELP_CREATE },
172 { "destroy", zfs_do_destroy, HELP_DESTROY },
173 { NULL },
174 { "snapshot", zfs_do_snapshot, HELP_SNAPSHOT },
175 { "rollback", zfs_do_rollback, HELP_ROLLBACK },
176 { "clone", zfs_do_clone, HELP_CLONE },
177 { "promote", zfs_do_promote, HELP_PROMOTE },
178 { "rename", zfs_do_rename, HELP_RENAME },
179 { "bookmark", zfs_do_bookmark, HELP_BOOKMARK },
180 { NULL },
181 { "list", zfs_do_list, HELP_LIST },
182 { NULL },
183 { "set", zfs_do_set, HELP_SET },
184 { "get", zfs_do_get, HELP_GET },
185 { "inherit", zfs_do_inherit, HELP_INHERIT },
186 { "upgrade", zfs_do_upgrade, HELP_UPGRADE },
187 { "userspace", zfs_do_userspace, HELP_USERSPACE },
188 { "groupspace", zfs_do_userspace, HELP_GROUPSPACE },
189 { NULL },
190 { "mount", zfs_do_mount, HELP_MOUNT },
191 { "unmount", zfs_do_unmount, HELP_UNMOUNT },
192 { "share", zfs_do_share, HELP_SHARE },
193 { "unshare", zfs_do_unshare, HELP_UNSHARE },
194 { NULL },
195 { "send", zfs_do_send, HELP_SEND },
196 { "receive", zfs_do_receive, HELP_RECEIVE },
197 { NULL },
198 { "allow", zfs_do_allow, HELP_ALLOW },
199 { NULL },
200 { "unallow", zfs_do_unallow, HELP_UNALLOW },
201 { NULL },
202 { "hold", zfs_do_hold, HELP_HOLD },
203 { "holds", zfs_do_holds, HELP_HOLDS },
204 { "release", zfs_do_release, HELP_RELEASE },
205 { "diff", zfs_do_diff, HELP_DIFF },
208 #define NCOMMAND (sizeof (command_table) / sizeof (command_table[0]))
210 zfs_command_t *current_command;
212 static const char *
213 get_usage(zfs_help_t idx)
215 switch (idx) {
216 case HELP_CLONE:
217 return (gettext("\tclone [-p] [-o property=value] ... "
218 "<snapshot> <filesystem|volume>\n"));
219 case HELP_CREATE:
220 return (gettext("\tcreate [-p] [-o property=value] ... "
221 "<filesystem>\n"
222 "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
223 "-V <size> <volume>\n"));
224 case HELP_DESTROY:
225 return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
226 "\tdestroy [-dnpRrv] "
227 "<filesystem|volume>@<snap>[%<snap>][,...]\n"
228 "\tdestroy <filesystem|volume>#<bookmark>\n"));
229 case HELP_GET:
230 return (gettext("\tget [-rHp] [-d max] "
231 "[-o \"all\" | field[,...]]\n"
232 "\t [-t type[,...]] [-s source[,...]]\n"
233 "\t <\"all\" | property[,...]> "
234 "[filesystem|volume|snapshot] ...\n"));
235 case HELP_INHERIT:
236 return (gettext("\tinherit [-rS] <property> "
237 "<filesystem|volume|snapshot> ...\n"));
238 case HELP_UPGRADE:
239 return (gettext("\tupgrade [-v]\n"
240 "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
241 case HELP_LIST:
242 return (gettext("\tlist [-Hp] [-r|-d max] [-o property[,...]] "
243 "[-s property]...\n\t [-S property]... [-t type[,...]] "
244 "[filesystem|volume|snapshot] ...\n"));
245 case HELP_MOUNT:
246 return (gettext("\tmount\n"
247 "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
248 case HELP_PROMOTE:
249 return (gettext("\tpromote <clone-filesystem>\n"));
250 case HELP_RECEIVE:
251 return (gettext("\treceive [-vnsFu] <filesystem|volume|"
252 "snapshot>\n"
253 "\treceive [-vnsFu] [-o origin=<snapshot>] [-d | -e] "
254 "<filesystem>\n"
255 "\treceive -A <filesystem|volume>\n"));
256 case HELP_RENAME:
257 return (gettext("\trename [-f] <filesystem|volume|snapshot> "
258 "<filesystem|volume|snapshot>\n"
259 "\trename [-f] -p <filesystem|volume> <filesystem|volume>\n"
260 "\trename -r <snapshot> <snapshot>\n"));
261 case HELP_ROLLBACK:
262 return (gettext("\trollback [-rRf] <snapshot>\n"));
263 case HELP_SEND:
264 return (gettext("\tsend [-DnPpRvLe] [-[iI] snapshot] "
265 "<snapshot>\n"
266 "\tsend [-Le] [-i snapshot|bookmark] "
267 "<filesystem|volume|snapshot>\n"
268 "\tsend [-nvPe] -t <receive_resume_token>\n"));
269 case HELP_SET:
270 return (gettext("\tset <property=value> ... "
271 "<filesystem|volume|snapshot> ...\n"));
272 case HELP_SHARE:
273 return (gettext("\tshare <-a | filesystem>\n"));
274 case HELP_SNAPSHOT:
275 return (gettext("\tsnapshot [-r] [-o property=value] ... "
276 "<filesystem|volume>@<snap> ...\n"));
277 case HELP_UNMOUNT:
278 return (gettext("\tunmount [-f] "
279 "<-a | filesystem|mountpoint>\n"));
280 case HELP_UNSHARE:
281 return (gettext("\tunshare "
282 "<-a | filesystem|mountpoint>\n"));
283 case HELP_ALLOW:
284 return (gettext("\tallow <filesystem|volume>\n"
285 "\tallow [-ldug] "
286 "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
287 "\t <filesystem|volume>\n"
288 "\tallow [-ld] -e <perm|@setname>[,...] "
289 "<filesystem|volume>\n"
290 "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
291 "\tallow -s @setname <perm|@setname>[,...] "
292 "<filesystem|volume>\n"));
293 case HELP_UNALLOW:
294 return (gettext("\tunallow [-rldug] "
295 "<\"everyone\"|user|group>[,...]\n"
296 "\t [<perm|@setname>[,...]] <filesystem|volume>\n"
297 "\tunallow [-rld] -e [<perm|@setname>[,...]] "
298 "<filesystem|volume>\n"
299 "\tunallow [-r] -c [<perm|@setname>[,...]] "
300 "<filesystem|volume>\n"
301 "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
302 "<filesystem|volume>\n"));
303 case HELP_USERSPACE:
304 return (gettext("\tuserspace [-Hinp] [-o field[,...]] "
305 "[-s field] ...\n"
306 "\t [-S field] ... [-t type[,...]] "
307 "<filesystem|snapshot>\n"));
308 case HELP_GROUPSPACE:
309 return (gettext("\tgroupspace [-Hinp] [-o field[,...]] "
310 "[-s field] ...\n"
311 "\t [-S field] ... [-t type[,...]] "
312 "<filesystem|snapshot>\n"));
313 case HELP_HOLD:
314 return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
315 case HELP_HOLDS:
316 return (gettext("\tholds [-r] <snapshot> ...\n"));
317 case HELP_RELEASE:
318 return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
319 case HELP_DIFF:
320 return (gettext("\tdiff [-FHt] <snapshot> "
321 "[snapshot|filesystem]\n"));
322 case HELP_BOOKMARK:
323 return (gettext("\tbookmark <snapshot> <bookmark>\n"));
326 abort();
327 /* NOTREACHED */
330 void
331 nomem(void)
333 (void) fprintf(stderr, gettext("internal error: out of memory\n"));
334 exit(1);
338 * Utility function to guarantee malloc() success.
341 void *
342 safe_malloc(size_t size)
344 void *data;
346 if ((data = calloc(1, size)) == NULL)
347 nomem();
349 return (data);
352 static char *
353 safe_strdup(char *str)
355 char *dupstr = strdup(str);
357 if (dupstr == NULL)
358 nomem();
360 return (dupstr);
364 * Callback routine that will print out information for each of
365 * the properties.
367 static int
368 usage_prop_cb(int prop, void *cb)
370 FILE *fp = cb;
372 (void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
374 if (zfs_prop_readonly(prop))
375 (void) fprintf(fp, " NO ");
376 else
377 (void) fprintf(fp, "YES ");
379 if (zfs_prop_inheritable(prop))
380 (void) fprintf(fp, " YES ");
381 else
382 (void) fprintf(fp, " NO ");
384 if (zfs_prop_values(prop) == NULL)
385 (void) fprintf(fp, "-\n");
386 else
387 (void) fprintf(fp, "%s\n", zfs_prop_values(prop));
389 return (ZPROP_CONT);
393 * Display usage message. If we're inside a command, display only the usage for
394 * that command. Otherwise, iterate over the entire command table and display
395 * a complete usage message.
397 static void
398 usage(boolean_t requested)
400 int i;
401 boolean_t show_properties = B_FALSE;
402 FILE *fp = requested ? stdout : stderr;
404 if (current_command == NULL) {
406 (void) fprintf(fp, gettext("usage: zfs command args ...\n"));
407 (void) fprintf(fp,
408 gettext("where 'command' is one of the following:\n\n"));
410 for (i = 0; i < NCOMMAND; i++) {
411 if (command_table[i].name == NULL)
412 (void) fprintf(fp, "\n");
413 else
414 (void) fprintf(fp, "%s",
415 get_usage(command_table[i].usage));
418 (void) fprintf(fp, gettext("\nEach dataset is of the form: "
419 "pool/[dataset/]*dataset[@name]\n"));
420 } else {
421 (void) fprintf(fp, gettext("usage:\n"));
422 (void) fprintf(fp, "%s", get_usage(current_command->usage));
425 if (current_command != NULL &&
426 (strcmp(current_command->name, "set") == 0 ||
427 strcmp(current_command->name, "get") == 0 ||
428 strcmp(current_command->name, "inherit") == 0 ||
429 strcmp(current_command->name, "list") == 0))
430 show_properties = B_TRUE;
432 if (show_properties) {
433 (void) fprintf(fp,
434 gettext("\nThe following properties are supported:\n"));
436 (void) fprintf(fp, "\n\t%-14s %s %s %s\n\n",
437 "PROPERTY", "EDIT", "INHERIT", "VALUES");
439 /* Iterate over all properties */
440 (void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
441 ZFS_TYPE_DATASET);
443 (void) fprintf(fp, "\t%-15s ", "userused@...");
444 (void) fprintf(fp, " NO NO <size>\n");
445 (void) fprintf(fp, "\t%-15s ", "groupused@...");
446 (void) fprintf(fp, " NO NO <size>\n");
447 (void) fprintf(fp, "\t%-15s ", "userquota@...");
448 (void) fprintf(fp, "YES NO <size> | none\n");
449 (void) fprintf(fp, "\t%-15s ", "groupquota@...");
450 (void) fprintf(fp, "YES NO <size> | none\n");
451 (void) fprintf(fp, "\t%-15s ", "written@<snap>");
452 (void) fprintf(fp, " NO NO <size>\n");
454 (void) fprintf(fp, gettext("\nSizes are specified in bytes "
455 "with standard units such as K, M, G, etc.\n"));
456 (void) fprintf(fp, gettext("\nUser-defined properties can "
457 "be specified by using a name containing a colon (:).\n"));
458 (void) fprintf(fp, gettext("\nThe {user|group}{used|quota}@ "
459 "properties must be appended with\n"
460 "a user or group specifier of one of these forms:\n"
461 " POSIX name (eg: \"matt\")\n"
462 " POSIX id (eg: \"126829\")\n"
463 " SMB name@domain (eg: \"matt@sun\")\n"
464 " SMB SID (eg: \"S-1-234-567-89\")\n"));
465 } else {
466 (void) fprintf(fp,
467 gettext("\nFor the property list, run: %s\n"),
468 "zfs set|get");
469 (void) fprintf(fp,
470 gettext("\nFor the delegated permission list, run: %s\n"),
471 "zfs allow|unallow");
475 * See comments at end of main().
477 if (getenv("ZFS_ABORT") != NULL) {
478 (void) printf("dumping core by request\n");
479 abort();
482 exit(requested ? 0 : 2);
486 * Take a property=value argument string and add it to the given nvlist.
487 * Modifies the argument inplace.
489 static int
490 parseprop(nvlist_t *props, char *propname)
492 char *propval, *strval;
494 if ((propval = strchr(propname, '=')) == NULL) {
495 (void) fprintf(stderr, gettext("missing "
496 "'=' for property=value argument\n"));
497 return (-1);
499 *propval = '\0';
500 propval++;
501 if (nvlist_lookup_string(props, propname, &strval) == 0) {
502 (void) fprintf(stderr, gettext("property '%s' "
503 "specified multiple times\n"), propname);
504 return (-1);
506 if (nvlist_add_string(props, propname, propval) != 0)
507 nomem();
508 return (0);
511 static int
512 parse_depth(char *opt, int *flags)
514 char *tmp;
515 int depth;
517 depth = (int)strtol(opt, &tmp, 0);
518 if (*tmp) {
519 (void) fprintf(stderr,
520 gettext("%s is not an integer\n"), optarg);
521 usage(B_FALSE);
523 if (depth < 0) {
524 (void) fprintf(stderr,
525 gettext("Depth can not be negative.\n"));
526 usage(B_FALSE);
528 *flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
529 return (depth);
532 #define PROGRESS_DELAY 2 /* seconds */
534 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";
535 static time_t pt_begin;
536 static char *pt_header = NULL;
537 static boolean_t pt_shown;
539 static void
540 start_progress_timer(void)
542 pt_begin = time(NULL) + PROGRESS_DELAY;
543 pt_shown = B_FALSE;
546 static void
547 set_progress_header(char *header)
549 assert(pt_header == NULL);
550 pt_header = safe_strdup(header);
551 if (pt_shown) {
552 (void) printf("%s: ", header);
553 (void) fflush(stdout);
557 static void
558 update_progress(char *update)
560 if (!pt_shown && time(NULL) > pt_begin) {
561 int len = strlen(update);
563 (void) printf("%s: %s%*.*s", pt_header, update, len, len,
564 pt_reverse);
565 (void) fflush(stdout);
566 pt_shown = B_TRUE;
567 } else if (pt_shown) {
568 int len = strlen(update);
570 (void) printf("%s%*.*s", update, len, len, pt_reverse);
571 (void) fflush(stdout);
575 static void
576 finish_progress(char *done)
578 if (pt_shown) {
579 (void) printf("%s\n", done);
580 (void) fflush(stdout);
582 free(pt_header);
583 pt_header = NULL;
587 * Check if the dataset is mountable and should be automatically mounted.
589 static boolean_t
590 should_auto_mount(zfs_handle_t *zhp)
592 if (!zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, zfs_get_type(zhp)))
593 return (B_FALSE);
594 return (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_ON);
598 * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
600 * Given an existing dataset, create a writable copy whose initial contents
601 * are the same as the source. The newly created dataset maintains a
602 * dependency on the original; the original cannot be destroyed so long as
603 * the clone exists.
605 * The '-p' flag creates all the non-existing ancestors of the target first.
607 static int
608 zfs_do_clone(int argc, char **argv)
610 zfs_handle_t *zhp = NULL;
611 boolean_t parents = B_FALSE;
612 nvlist_t *props;
613 int ret = 0;
614 int c;
616 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
617 nomem();
619 /* check options */
620 while ((c = getopt(argc, argv, "o:p")) != -1) {
621 switch (c) {
622 case 'o':
623 if (parseprop(props, optarg) != 0)
624 return (1);
625 break;
626 case 'p':
627 parents = B_TRUE;
628 break;
629 case '?':
630 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
631 optopt);
632 goto usage;
636 argc -= optind;
637 argv += optind;
639 /* check number of arguments */
640 if (argc < 1) {
641 (void) fprintf(stderr, gettext("missing source dataset "
642 "argument\n"));
643 goto usage;
645 if (argc < 2) {
646 (void) fprintf(stderr, gettext("missing target dataset "
647 "argument\n"));
648 goto usage;
650 if (argc > 2) {
651 (void) fprintf(stderr, gettext("too many arguments\n"));
652 goto usage;
655 /* open the source dataset */
656 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
657 return (1);
659 if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
660 ZFS_TYPE_VOLUME)) {
662 * Now create the ancestors of the target dataset. If the
663 * target already exists and '-p' option was used we should not
664 * complain.
666 if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
667 ZFS_TYPE_VOLUME))
668 return (0);
669 if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
670 return (1);
673 /* pass to libzfs */
674 ret = zfs_clone(zhp, argv[1], props);
676 /* create the mountpoint if necessary */
677 if (ret == 0) {
678 zfs_handle_t *clone;
680 clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
681 if (clone != NULL) {
683 * If the user doesn't want the dataset
684 * automatically mounted, then skip the mount/share
685 * step.
687 if (should_auto_mount(clone)) {
688 if ((ret = zfs_mount(clone, NULL, 0)) != 0) {
689 (void) fprintf(stderr, gettext("clone "
690 "successfully created, "
691 "but not mounted\n"));
692 } else if ((ret = zfs_share(clone)) != 0) {
693 (void) fprintf(stderr, gettext("clone "
694 "successfully created, "
695 "but not shared\n"));
698 zfs_close(clone);
702 zfs_close(zhp);
703 nvlist_free(props);
705 return (!!ret);
707 usage:
708 if (zhp)
709 zfs_close(zhp);
710 nvlist_free(props);
711 usage(B_FALSE);
712 return (-1);
716 * zfs create [-p] [-o prop=value] ... fs
717 * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
719 * Create a new dataset. This command can be used to create filesystems
720 * and volumes. Snapshot creation is handled by 'zfs snapshot'.
721 * For volumes, the user must specify a size to be used.
723 * The '-s' flag applies only to volumes, and indicates that we should not try
724 * to set the reservation for this volume. By default we set a reservation
725 * equal to the size for any volume. For pools with SPA_VERSION >=
726 * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
728 * The '-p' flag creates all the non-existing ancestors of the target first.
730 static int
731 zfs_do_create(int argc, char **argv)
733 zfs_type_t type = ZFS_TYPE_FILESYSTEM;
734 zfs_handle_t *zhp = NULL;
735 uint64_t volsize = 0;
736 int c;
737 boolean_t noreserve = B_FALSE;
738 boolean_t bflag = B_FALSE;
739 boolean_t parents = B_FALSE;
740 int ret = 1;
741 nvlist_t *props;
742 uint64_t intval;
744 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
745 nomem();
747 /* check options */
748 while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
749 switch (c) {
750 case 'V':
751 type = ZFS_TYPE_VOLUME;
752 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
753 (void) fprintf(stderr, gettext("bad volume "
754 "size '%s': %s\n"), optarg,
755 libzfs_error_description(g_zfs));
756 goto error;
759 if (nvlist_add_uint64(props,
760 zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
761 nomem();
762 volsize = intval;
763 break;
764 case 'p':
765 parents = B_TRUE;
766 break;
767 case 'b':
768 bflag = B_TRUE;
769 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
770 (void) fprintf(stderr, gettext("bad volume "
771 "block size '%s': %s\n"), optarg,
772 libzfs_error_description(g_zfs));
773 goto error;
776 if (nvlist_add_uint64(props,
777 zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
778 intval) != 0)
779 nomem();
780 break;
781 case 'o':
782 if (parseprop(props, optarg) != 0)
783 goto error;
784 break;
785 case 's':
786 noreserve = B_TRUE;
787 break;
788 case ':':
789 (void) fprintf(stderr, gettext("missing size "
790 "argument\n"));
791 goto badusage;
792 case '?':
793 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
794 optopt);
795 goto badusage;
799 if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
800 (void) fprintf(stderr, gettext("'-s' and '-b' can only be "
801 "used when creating a volume\n"));
802 goto badusage;
805 argc -= optind;
806 argv += optind;
808 /* check number of arguments */
809 if (argc == 0) {
810 (void) fprintf(stderr, gettext("missing %s argument\n"),
811 zfs_type_to_name(type));
812 goto badusage;
814 if (argc > 1) {
815 (void) fprintf(stderr, gettext("too many arguments\n"));
816 goto badusage;
819 if (type == ZFS_TYPE_VOLUME && !noreserve) {
820 zpool_handle_t *zpool_handle;
821 nvlist_t *real_props = NULL;
822 uint64_t spa_version;
823 char *p;
824 zfs_prop_t resv_prop;
825 char *strval;
826 char msg[1024];
828 if ((p = strchr(argv[0], '/')) != NULL)
829 *p = '\0';
830 zpool_handle = zpool_open(g_zfs, argv[0]);
831 if (p != NULL)
832 *p = '/';
833 if (zpool_handle == NULL)
834 goto error;
835 spa_version = zpool_get_prop_int(zpool_handle,
836 ZPOOL_PROP_VERSION, NULL);
837 if (spa_version >= SPA_VERSION_REFRESERVATION)
838 resv_prop = ZFS_PROP_REFRESERVATION;
839 else
840 resv_prop = ZFS_PROP_RESERVATION;
842 (void) snprintf(msg, sizeof (msg),
843 gettext("cannot create '%s'"), argv[0]);
844 if (props && (real_props = zfs_valid_proplist(g_zfs, type,
845 props, 0, NULL, zpool_handle, msg)) == NULL) {
846 zpool_close(zpool_handle);
847 goto error;
849 zpool_close(zpool_handle);
851 volsize = zvol_volsize_to_reservation(volsize, real_props);
852 nvlist_free(real_props);
854 if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
855 &strval) != 0) {
856 if (nvlist_add_uint64(props,
857 zfs_prop_to_name(resv_prop), volsize) != 0) {
858 nvlist_free(props);
859 nomem();
864 if (parents && zfs_name_valid(argv[0], type)) {
866 * Now create the ancestors of target dataset. If the target
867 * already exists and '-p' option was used we should not
868 * complain.
870 if (zfs_dataset_exists(g_zfs, argv[0], type)) {
871 ret = 0;
872 goto error;
874 if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
875 goto error;
878 /* pass to libzfs */
879 if (zfs_create(g_zfs, argv[0], type, props) != 0)
880 goto error;
882 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
883 goto error;
885 ret = 0;
888 * Mount and/or share the new filesystem as appropriate. We provide a
889 * verbose error message to let the user know that their filesystem was
890 * in fact created, even if we failed to mount or share it.
891 * If the user doesn't want the dataset automatically mounted,
892 * then skip the mount/share step altogether.
894 if (should_auto_mount(zhp)) {
895 if (zfs_mount(zhp, NULL, 0) != 0) {
896 (void) fprintf(stderr, gettext("filesystem "
897 "successfully created, but not mounted\n"));
898 ret = 1;
899 } else if (zfs_share(zhp) != 0) {
900 (void) fprintf(stderr, gettext("filesystem "
901 "successfully created, but not shared\n"));
902 ret = 1;
906 error:
907 if (zhp)
908 zfs_close(zhp);
909 nvlist_free(props);
910 return (ret);
911 badusage:
912 nvlist_free(props);
913 usage(B_FALSE);
914 return (2);
918 * zfs destroy [-rRf] <fs, vol>
919 * zfs destroy [-rRd] <snap>
921 * -r Recursively destroy all children
922 * -R Recursively destroy all dependents, including clones
923 * -f Force unmounting of any dependents
924 * -d If we can't destroy now, mark for deferred destruction
926 * Destroys the given dataset. By default, it will unmount any filesystems,
927 * and refuse to destroy a dataset that has any dependents. A dependent can
928 * either be a child, or a clone of a child.
930 typedef struct destroy_cbdata {
931 boolean_t cb_first;
932 boolean_t cb_force;
933 boolean_t cb_recurse;
934 boolean_t cb_error;
935 boolean_t cb_doclones;
936 zfs_handle_t *cb_target;
937 boolean_t cb_defer_destroy;
938 boolean_t cb_verbose;
939 boolean_t cb_parsable;
940 boolean_t cb_dryrun;
941 nvlist_t *cb_nvl;
942 nvlist_t *cb_batchedsnaps;
944 /* first snap in contiguous run */
945 char *cb_firstsnap;
946 /* previous snap in contiguous run */
947 char *cb_prevsnap;
948 int64_t cb_snapused;
949 char *cb_snapspec;
950 char *cb_bookmark;
951 } destroy_cbdata_t;
954 * Check for any dependents based on the '-r' or '-R' flags.
956 static int
957 destroy_check_dependent(zfs_handle_t *zhp, void *data)
959 destroy_cbdata_t *cbp = data;
960 const char *tname = zfs_get_name(cbp->cb_target);
961 const char *name = zfs_get_name(zhp);
963 if (strncmp(tname, name, strlen(tname)) == 0 &&
964 (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
966 * This is a direct descendant, not a clone somewhere else in
967 * the hierarchy.
969 if (cbp->cb_recurse)
970 goto out;
972 if (cbp->cb_first) {
973 (void) fprintf(stderr, gettext("cannot destroy '%s': "
974 "%s has children\n"),
975 zfs_get_name(cbp->cb_target),
976 zfs_type_to_name(zfs_get_type(cbp->cb_target)));
977 (void) fprintf(stderr, gettext("use '-r' to destroy "
978 "the following datasets:\n"));
979 cbp->cb_first = B_FALSE;
980 cbp->cb_error = B_TRUE;
983 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
984 } else {
986 * This is a clone. We only want to report this if the '-r'
987 * wasn't specified, or the target is a snapshot.
989 if (!cbp->cb_recurse &&
990 zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
991 goto out;
993 if (cbp->cb_first) {
994 (void) fprintf(stderr, gettext("cannot destroy '%s': "
995 "%s has dependent clones\n"),
996 zfs_get_name(cbp->cb_target),
997 zfs_type_to_name(zfs_get_type(cbp->cb_target)));
998 (void) fprintf(stderr, gettext("use '-R' to destroy "
999 "the following datasets:\n"));
1000 cbp->cb_first = B_FALSE;
1001 cbp->cb_error = B_TRUE;
1002 cbp->cb_dryrun = B_TRUE;
1005 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1008 out:
1009 zfs_close(zhp);
1010 return (0);
1013 static int
1014 destroy_callback(zfs_handle_t *zhp, void *data)
1016 destroy_cbdata_t *cb = data;
1017 const char *name = zfs_get_name(zhp);
1019 if (cb->cb_verbose) {
1020 if (cb->cb_parsable) {
1021 (void) printf("destroy\t%s\n", name);
1022 } else if (cb->cb_dryrun) {
1023 (void) printf(gettext("would destroy %s\n"),
1024 name);
1025 } else {
1026 (void) printf(gettext("will destroy %s\n"),
1027 name);
1032 * Ignore pools (which we've already flagged as an error before getting
1033 * here).
1035 if (strchr(zfs_get_name(zhp), '/') == NULL &&
1036 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1037 zfs_close(zhp);
1038 return (0);
1040 if (cb->cb_dryrun) {
1041 zfs_close(zhp);
1042 return (0);
1046 * We batch up all contiguous snapshots (even of different
1047 * filesystems) and destroy them with one ioctl. We can't
1048 * simply do all snap deletions and then all fs deletions,
1049 * because we must delete a clone before its origin.
1051 if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT) {
1052 fnvlist_add_boolean(cb->cb_batchedsnaps, name);
1053 } else {
1054 int error = zfs_destroy_snaps_nvl(g_zfs,
1055 cb->cb_batchedsnaps, B_FALSE);
1056 fnvlist_free(cb->cb_batchedsnaps);
1057 cb->cb_batchedsnaps = fnvlist_alloc();
1059 if (error != 0 ||
1060 zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
1061 zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
1062 zfs_close(zhp);
1063 return (-1);
1067 zfs_close(zhp);
1068 return (0);
1071 static int
1072 destroy_print_cb(zfs_handle_t *zhp, void *arg)
1074 destroy_cbdata_t *cb = arg;
1075 const char *name = zfs_get_name(zhp);
1076 int err = 0;
1078 if (nvlist_exists(cb->cb_nvl, name)) {
1079 if (cb->cb_firstsnap == NULL)
1080 cb->cb_firstsnap = strdup(name);
1081 if (cb->cb_prevsnap != NULL)
1082 free(cb->cb_prevsnap);
1083 /* this snap continues the current range */
1084 cb->cb_prevsnap = strdup(name);
1085 if (cb->cb_firstsnap == NULL || cb->cb_prevsnap == NULL)
1086 nomem();
1087 if (cb->cb_verbose) {
1088 if (cb->cb_parsable) {
1089 (void) printf("destroy\t%s\n", name);
1090 } else if (cb->cb_dryrun) {
1091 (void) printf(gettext("would destroy %s\n"),
1092 name);
1093 } else {
1094 (void) printf(gettext("will destroy %s\n"),
1095 name);
1098 } else if (cb->cb_firstsnap != NULL) {
1099 /* end of this range */
1100 uint64_t used = 0;
1101 err = lzc_snaprange_space(cb->cb_firstsnap,
1102 cb->cb_prevsnap, &used);
1103 cb->cb_snapused += used;
1104 free(cb->cb_firstsnap);
1105 cb->cb_firstsnap = NULL;
1106 free(cb->cb_prevsnap);
1107 cb->cb_prevsnap = NULL;
1109 zfs_close(zhp);
1110 return (err);
1113 static int
1114 destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
1116 int err = 0;
1117 assert(cb->cb_firstsnap == NULL);
1118 assert(cb->cb_prevsnap == NULL);
1119 err = zfs_iter_snapshots_sorted(fs_zhp, destroy_print_cb, cb);
1120 if (cb->cb_firstsnap != NULL) {
1121 uint64_t used = 0;
1122 if (err == 0) {
1123 err = lzc_snaprange_space(cb->cb_firstsnap,
1124 cb->cb_prevsnap, &used);
1126 cb->cb_snapused += used;
1127 free(cb->cb_firstsnap);
1128 cb->cb_firstsnap = NULL;
1129 free(cb->cb_prevsnap);
1130 cb->cb_prevsnap = NULL;
1132 return (err);
1135 static int
1136 snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
1138 destroy_cbdata_t *cb = arg;
1139 int err = 0;
1141 /* Check for clones. */
1142 if (!cb->cb_doclones && !cb->cb_defer_destroy) {
1143 cb->cb_target = zhp;
1144 cb->cb_first = B_TRUE;
1145 err = zfs_iter_dependents(zhp, B_TRUE,
1146 destroy_check_dependent, cb);
1149 if (err == 0) {
1150 if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
1151 nomem();
1153 zfs_close(zhp);
1154 return (err);
1157 static int
1158 gather_snapshots(zfs_handle_t *zhp, void *arg)
1160 destroy_cbdata_t *cb = arg;
1161 int err = 0;
1163 err = zfs_iter_snapspec(zhp, cb->cb_snapspec, snapshot_to_nvl_cb, cb);
1164 if (err == ENOENT)
1165 err = 0;
1166 if (err != 0)
1167 goto out;
1169 if (cb->cb_verbose) {
1170 err = destroy_print_snapshots(zhp, cb);
1171 if (err != 0)
1172 goto out;
1175 if (cb->cb_recurse)
1176 err = zfs_iter_filesystems(zhp, gather_snapshots, cb);
1178 out:
1179 zfs_close(zhp);
1180 return (err);
1183 static int
1184 destroy_clones(destroy_cbdata_t *cb)
1186 nvpair_t *pair;
1187 for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
1188 pair != NULL;
1189 pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
1190 zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
1191 ZFS_TYPE_SNAPSHOT);
1192 if (zhp != NULL) {
1193 boolean_t defer = cb->cb_defer_destroy;
1194 int err = 0;
1197 * We can't defer destroy non-snapshots, so set it to
1198 * false while destroying the clones.
1200 cb->cb_defer_destroy = B_FALSE;
1201 err = zfs_iter_dependents(zhp, B_FALSE,
1202 destroy_callback, cb);
1203 cb->cb_defer_destroy = defer;
1204 zfs_close(zhp);
1205 if (err != 0)
1206 return (err);
1209 return (0);
1212 static int
1213 zfs_do_destroy(int argc, char **argv)
1215 destroy_cbdata_t cb = { 0 };
1216 int rv = 0;
1217 int err = 0;
1218 int c;
1219 zfs_handle_t *zhp = NULL;
1220 char *at, *pound;
1221 zfs_type_t type = ZFS_TYPE_DATASET;
1223 /* check options */
1224 while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
1225 switch (c) {
1226 case 'v':
1227 cb.cb_verbose = B_TRUE;
1228 break;
1229 case 'p':
1230 cb.cb_verbose = B_TRUE;
1231 cb.cb_parsable = B_TRUE;
1232 break;
1233 case 'n':
1234 cb.cb_dryrun = B_TRUE;
1235 break;
1236 case 'd':
1237 cb.cb_defer_destroy = B_TRUE;
1238 type = ZFS_TYPE_SNAPSHOT;
1239 break;
1240 case 'f':
1241 cb.cb_force = B_TRUE;
1242 break;
1243 case 'r':
1244 cb.cb_recurse = B_TRUE;
1245 break;
1246 case 'R':
1247 cb.cb_recurse = B_TRUE;
1248 cb.cb_doclones = B_TRUE;
1249 break;
1250 case '?':
1251 default:
1252 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1253 optopt);
1254 usage(B_FALSE);
1258 argc -= optind;
1259 argv += optind;
1261 /* check number of arguments */
1262 if (argc == 0) {
1263 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1264 usage(B_FALSE);
1266 if (argc > 1) {
1267 (void) fprintf(stderr, gettext("too many arguments\n"));
1268 usage(B_FALSE);
1271 at = strchr(argv[0], '@');
1272 pound = strchr(argv[0], '#');
1273 if (at != NULL) {
1275 /* Build the list of snaps to destroy in cb_nvl. */
1276 cb.cb_nvl = fnvlist_alloc();
1278 *at = '\0';
1279 zhp = zfs_open(g_zfs, argv[0],
1280 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1281 if (zhp == NULL)
1282 return (1);
1284 cb.cb_snapspec = at + 1;
1285 if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
1286 cb.cb_error) {
1287 rv = 1;
1288 goto out;
1291 if (nvlist_empty(cb.cb_nvl)) {
1292 (void) fprintf(stderr, gettext("could not find any "
1293 "snapshots to destroy; check snapshot names.\n"));
1294 rv = 1;
1295 goto out;
1298 if (cb.cb_verbose) {
1299 char buf[16];
1300 zfs_nicenum(cb.cb_snapused, buf, sizeof (buf));
1301 if (cb.cb_parsable) {
1302 (void) printf("reclaim\t%llu\n",
1303 cb.cb_snapused);
1304 } else if (cb.cb_dryrun) {
1305 (void) printf(gettext("would reclaim %s\n"),
1306 buf);
1307 } else {
1308 (void) printf(gettext("will reclaim %s\n"),
1309 buf);
1313 if (!cb.cb_dryrun) {
1314 if (cb.cb_doclones) {
1315 cb.cb_batchedsnaps = fnvlist_alloc();
1316 err = destroy_clones(&cb);
1317 if (err == 0) {
1318 err = zfs_destroy_snaps_nvl(g_zfs,
1319 cb.cb_batchedsnaps, B_FALSE);
1321 if (err != 0) {
1322 rv = 1;
1323 goto out;
1326 if (err == 0) {
1327 err = zfs_destroy_snaps_nvl(g_zfs, cb.cb_nvl,
1328 cb.cb_defer_destroy);
1332 if (err != 0)
1333 rv = 1;
1334 } else if (pound != NULL) {
1335 int err;
1336 nvlist_t *nvl;
1338 if (cb.cb_dryrun) {
1339 (void) fprintf(stderr,
1340 "dryrun is not supported with bookmark\n");
1341 return (-1);
1344 if (cb.cb_defer_destroy) {
1345 (void) fprintf(stderr,
1346 "defer destroy is not supported with bookmark\n");
1347 return (-1);
1350 if (cb.cb_recurse) {
1351 (void) fprintf(stderr,
1352 "recursive is not supported with bookmark\n");
1353 return (-1);
1356 if (!zfs_bookmark_exists(argv[0])) {
1357 (void) fprintf(stderr, gettext("bookmark '%s' "
1358 "does not exist.\n"), argv[0]);
1359 return (1);
1362 nvl = fnvlist_alloc();
1363 fnvlist_add_boolean(nvl, argv[0]);
1365 err = lzc_destroy_bookmarks(nvl, NULL);
1366 if (err != 0) {
1367 (void) zfs_standard_error(g_zfs, err,
1368 "cannot destroy bookmark");
1371 nvlist_free(cb.cb_nvl);
1373 return (err);
1374 } else {
1375 /* Open the given dataset */
1376 if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1377 return (1);
1379 cb.cb_target = zhp;
1382 * Perform an explicit check for pools before going any further.
1384 if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1385 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1386 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1387 "operation does not apply to pools\n"),
1388 zfs_get_name(zhp));
1389 (void) fprintf(stderr, gettext("use 'zfs destroy -r "
1390 "%s' to destroy all datasets in the pool\n"),
1391 zfs_get_name(zhp));
1392 (void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1393 "to destroy the pool itself\n"), zfs_get_name(zhp));
1394 rv = 1;
1395 goto out;
1399 * Check for any dependents and/or clones.
1401 cb.cb_first = B_TRUE;
1402 if (!cb.cb_doclones &&
1403 zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
1404 &cb) != 0) {
1405 rv = 1;
1406 goto out;
1409 if (cb.cb_error) {
1410 rv = 1;
1411 goto out;
1414 cb.cb_batchedsnaps = fnvlist_alloc();
1415 if (zfs_iter_dependents(zhp, B_FALSE, destroy_callback,
1416 &cb) != 0) {
1417 rv = 1;
1418 goto out;
1422 * Do the real thing. The callback will close the
1423 * handle regardless of whether it succeeds or not.
1425 err = destroy_callback(zhp, &cb);
1426 zhp = NULL;
1427 if (err == 0) {
1428 err = zfs_destroy_snaps_nvl(g_zfs,
1429 cb.cb_batchedsnaps, cb.cb_defer_destroy);
1431 if (err != 0)
1432 rv = 1;
1435 out:
1436 fnvlist_free(cb.cb_batchedsnaps);
1437 fnvlist_free(cb.cb_nvl);
1438 if (zhp != NULL)
1439 zfs_close(zhp);
1440 return (rv);
1443 static boolean_t
1444 is_recvd_column(zprop_get_cbdata_t *cbp)
1446 int i;
1447 zfs_get_column_t col;
1449 for (i = 0; i < ZFS_GET_NCOLS &&
1450 (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1451 if (col == GET_COL_RECVD)
1452 return (B_TRUE);
1453 return (B_FALSE);
1457 * zfs get [-rHp] [-o all | field[,field]...] [-s source[,source]...]
1458 * < all | property[,property]... > < fs | snap | vol > ...
1460 * -r recurse over any child datasets
1461 * -H scripted mode. Headers are stripped, and fields are separated
1462 * by tabs instead of spaces.
1463 * -o Set of fields to display. One of "name,property,value,
1464 * received,source". Default is "name,property,value,source".
1465 * "all" is an alias for all five.
1466 * -s Set of sources to allow. One of
1467 * "local,default,inherited,received,temporary,none". Default is
1468 * all six.
1469 * -p Display values in parsable (literal) format.
1471 * Prints properties for the given datasets. The user can control which
1472 * columns to display as well as which property types to allow.
1476 * Invoked to display the properties for a single dataset.
1478 static int
1479 get_callback(zfs_handle_t *zhp, void *data)
1481 char buf[ZFS_MAXPROPLEN];
1482 char rbuf[ZFS_MAXPROPLEN];
1483 zprop_source_t sourcetype;
1484 char source[ZFS_MAXNAMELEN];
1485 zprop_get_cbdata_t *cbp = data;
1486 nvlist_t *user_props = zfs_get_user_props(zhp);
1487 zprop_list_t *pl = cbp->cb_proplist;
1488 nvlist_t *propval;
1489 char *strval;
1490 char *sourceval;
1491 boolean_t received = is_recvd_column(cbp);
1493 for (; pl != NULL; pl = pl->pl_next) {
1494 char *recvdval = NULL;
1496 * Skip the special fake placeholder. This will also skip over
1497 * the name property when 'all' is specified.
1499 if (pl->pl_prop == ZFS_PROP_NAME &&
1500 pl == cbp->cb_proplist)
1501 continue;
1503 if (pl->pl_prop != ZPROP_INVAL) {
1504 if (zfs_prop_get(zhp, pl->pl_prop, buf,
1505 sizeof (buf), &sourcetype, source,
1506 sizeof (source),
1507 cbp->cb_literal) != 0) {
1508 if (pl->pl_all)
1509 continue;
1510 if (!zfs_prop_valid_for_type(pl->pl_prop,
1511 ZFS_TYPE_DATASET)) {
1512 (void) fprintf(stderr,
1513 gettext("No such property '%s'\n"),
1514 zfs_prop_to_name(pl->pl_prop));
1515 continue;
1517 sourcetype = ZPROP_SRC_NONE;
1518 (void) strlcpy(buf, "-", sizeof (buf));
1521 if (received && (zfs_prop_get_recvd(zhp,
1522 zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
1523 cbp->cb_literal) == 0))
1524 recvdval = rbuf;
1526 zprop_print_one_property(zfs_get_name(zhp), cbp,
1527 zfs_prop_to_name(pl->pl_prop),
1528 buf, sourcetype, source, recvdval);
1529 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
1530 sourcetype = ZPROP_SRC_LOCAL;
1532 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1533 buf, sizeof (buf), cbp->cb_literal) != 0) {
1534 sourcetype = ZPROP_SRC_NONE;
1535 (void) strlcpy(buf, "-", sizeof (buf));
1538 zprop_print_one_property(zfs_get_name(zhp), cbp,
1539 pl->pl_user_prop, buf, sourcetype, source, NULL);
1540 } else if (zfs_prop_written(pl->pl_user_prop)) {
1541 sourcetype = ZPROP_SRC_LOCAL;
1543 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
1544 buf, sizeof (buf), cbp->cb_literal) != 0) {
1545 sourcetype = ZPROP_SRC_NONE;
1546 (void) strlcpy(buf, "-", sizeof (buf));
1549 zprop_print_one_property(zfs_get_name(zhp), cbp,
1550 pl->pl_user_prop, buf, sourcetype, source, NULL);
1551 } else {
1552 if (nvlist_lookup_nvlist(user_props,
1553 pl->pl_user_prop, &propval) != 0) {
1554 if (pl->pl_all)
1555 continue;
1556 sourcetype = ZPROP_SRC_NONE;
1557 strval = "-";
1558 } else {
1559 verify(nvlist_lookup_string(propval,
1560 ZPROP_VALUE, &strval) == 0);
1561 verify(nvlist_lookup_string(propval,
1562 ZPROP_SOURCE, &sourceval) == 0);
1564 if (strcmp(sourceval,
1565 zfs_get_name(zhp)) == 0) {
1566 sourcetype = ZPROP_SRC_LOCAL;
1567 } else if (strcmp(sourceval,
1568 ZPROP_SOURCE_VAL_RECVD) == 0) {
1569 sourcetype = ZPROP_SRC_RECEIVED;
1570 } else {
1571 sourcetype = ZPROP_SRC_INHERITED;
1572 (void) strlcpy(source,
1573 sourceval, sizeof (source));
1577 if (received && (zfs_prop_get_recvd(zhp,
1578 pl->pl_user_prop, rbuf, sizeof (rbuf),
1579 cbp->cb_literal) == 0))
1580 recvdval = rbuf;
1582 zprop_print_one_property(zfs_get_name(zhp), cbp,
1583 pl->pl_user_prop, strval, sourcetype,
1584 source, recvdval);
1588 return (0);
1591 static int
1592 zfs_do_get(int argc, char **argv)
1594 zprop_get_cbdata_t cb = { 0 };
1595 int i, c, flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1596 int types = ZFS_TYPE_DATASET;
1597 char *value, *fields;
1598 int ret = 0;
1599 int limit = 0;
1600 zprop_list_t fake_name = { 0 };
1603 * Set up default columns and sources.
1605 cb.cb_sources = ZPROP_SRC_ALL;
1606 cb.cb_columns[0] = GET_COL_NAME;
1607 cb.cb_columns[1] = GET_COL_PROPERTY;
1608 cb.cb_columns[2] = GET_COL_VALUE;
1609 cb.cb_columns[3] = GET_COL_SOURCE;
1610 cb.cb_type = ZFS_TYPE_DATASET;
1612 /* check options */
1613 while ((c = getopt(argc, argv, ":d:o:s:rt:Hp")) != -1) {
1614 switch (c) {
1615 case 'p':
1616 cb.cb_literal = B_TRUE;
1617 break;
1618 case 'd':
1619 limit = parse_depth(optarg, &flags);
1620 break;
1621 case 'r':
1622 flags |= ZFS_ITER_RECURSE;
1623 break;
1624 case 'H':
1625 cb.cb_scripted = B_TRUE;
1626 break;
1627 case ':':
1628 (void) fprintf(stderr, gettext("missing argument for "
1629 "'%c' option\n"), optopt);
1630 usage(B_FALSE);
1631 break;
1632 case 'o':
1634 * Process the set of columns to display. We zero out
1635 * the structure to give us a blank slate.
1637 bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1638 i = 0;
1639 while (*optarg != '\0') {
1640 static char *col_subopts[] =
1641 { "name", "property", "value", "received",
1642 "source", "all", NULL };
1644 if (i == ZFS_GET_NCOLS) {
1645 (void) fprintf(stderr, gettext("too "
1646 "many fields given to -o "
1647 "option\n"));
1648 usage(B_FALSE);
1651 switch (getsubopt(&optarg, col_subopts,
1652 &value)) {
1653 case 0:
1654 cb.cb_columns[i++] = GET_COL_NAME;
1655 break;
1656 case 1:
1657 cb.cb_columns[i++] = GET_COL_PROPERTY;
1658 break;
1659 case 2:
1660 cb.cb_columns[i++] = GET_COL_VALUE;
1661 break;
1662 case 3:
1663 cb.cb_columns[i++] = GET_COL_RECVD;
1664 flags |= ZFS_ITER_RECVD_PROPS;
1665 break;
1666 case 4:
1667 cb.cb_columns[i++] = GET_COL_SOURCE;
1668 break;
1669 case 5:
1670 if (i > 0) {
1671 (void) fprintf(stderr,
1672 gettext("\"all\" conflicts "
1673 "with specific fields "
1674 "given to -o option\n"));
1675 usage(B_FALSE);
1677 cb.cb_columns[0] = GET_COL_NAME;
1678 cb.cb_columns[1] = GET_COL_PROPERTY;
1679 cb.cb_columns[2] = GET_COL_VALUE;
1680 cb.cb_columns[3] = GET_COL_RECVD;
1681 cb.cb_columns[4] = GET_COL_SOURCE;
1682 flags |= ZFS_ITER_RECVD_PROPS;
1683 i = ZFS_GET_NCOLS;
1684 break;
1685 default:
1686 (void) fprintf(stderr,
1687 gettext("invalid column name "
1688 "'%s'\n"), value);
1689 usage(B_FALSE);
1692 break;
1694 case 's':
1695 cb.cb_sources = 0;
1696 while (*optarg != '\0') {
1697 static char *source_subopts[] = {
1698 "local", "default", "inherited",
1699 "received", "temporary", "none",
1700 NULL };
1702 switch (getsubopt(&optarg, source_subopts,
1703 &value)) {
1704 case 0:
1705 cb.cb_sources |= ZPROP_SRC_LOCAL;
1706 break;
1707 case 1:
1708 cb.cb_sources |= ZPROP_SRC_DEFAULT;
1709 break;
1710 case 2:
1711 cb.cb_sources |= ZPROP_SRC_INHERITED;
1712 break;
1713 case 3:
1714 cb.cb_sources |= ZPROP_SRC_RECEIVED;
1715 break;
1716 case 4:
1717 cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1718 break;
1719 case 5:
1720 cb.cb_sources |= ZPROP_SRC_NONE;
1721 break;
1722 default:
1723 (void) fprintf(stderr,
1724 gettext("invalid source "
1725 "'%s'\n"), value);
1726 usage(B_FALSE);
1729 break;
1731 case 't':
1732 types = 0;
1733 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
1734 while (*optarg != '\0') {
1735 static char *type_subopts[] = { "filesystem",
1736 "volume", "snapshot", "bookmark",
1737 "all", NULL };
1739 switch (getsubopt(&optarg, type_subopts,
1740 &value)) {
1741 case 0:
1742 types |= ZFS_TYPE_FILESYSTEM;
1743 break;
1744 case 1:
1745 types |= ZFS_TYPE_VOLUME;
1746 break;
1747 case 2:
1748 types |= ZFS_TYPE_SNAPSHOT;
1749 break;
1750 case 3:
1751 types |= ZFS_TYPE_BOOKMARK;
1752 break;
1753 case 4:
1754 types = ZFS_TYPE_DATASET |
1755 ZFS_TYPE_BOOKMARK;
1756 break;
1758 default:
1759 (void) fprintf(stderr,
1760 gettext("invalid type '%s'\n"),
1761 value);
1762 usage(B_FALSE);
1765 break;
1767 case '?':
1768 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1769 optopt);
1770 usage(B_FALSE);
1774 argc -= optind;
1775 argv += optind;
1777 if (argc < 1) {
1778 (void) fprintf(stderr, gettext("missing property "
1779 "argument\n"));
1780 usage(B_FALSE);
1783 fields = argv[0];
1785 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1786 != 0)
1787 usage(B_FALSE);
1789 argc--;
1790 argv++;
1793 * As part of zfs_expand_proplist(), we keep track of the maximum column
1794 * width for each property. For the 'NAME' (and 'SOURCE') columns, we
1795 * need to know the maximum name length. However, the user likely did
1796 * not specify 'name' as one of the properties to fetch, so we need to
1797 * make sure we always include at least this property for
1798 * print_get_headers() to work properly.
1800 if (cb.cb_proplist != NULL) {
1801 fake_name.pl_prop = ZFS_PROP_NAME;
1802 fake_name.pl_width = strlen(gettext("NAME"));
1803 fake_name.pl_next = cb.cb_proplist;
1804 cb.cb_proplist = &fake_name;
1807 cb.cb_first = B_TRUE;
1809 /* run for each object */
1810 ret = zfs_for_each(argc, argv, flags, types, NULL,
1811 &cb.cb_proplist, limit, get_callback, &cb);
1813 if (cb.cb_proplist == &fake_name)
1814 zprop_free_list(fake_name.pl_next);
1815 else
1816 zprop_free_list(cb.cb_proplist);
1818 return (ret);
1822 * inherit [-rS] <property> <fs|vol> ...
1824 * -r Recurse over all children
1825 * -S Revert to received value, if any
1827 * For each dataset specified on the command line, inherit the given property
1828 * from its parent. Inheriting a property at the pool level will cause it to
1829 * use the default value. The '-r' flag will recurse over all children, and is
1830 * useful for setting a property on a hierarchy-wide basis, regardless of any
1831 * local modifications for each dataset.
1834 typedef struct inherit_cbdata {
1835 const char *cb_propname;
1836 boolean_t cb_received;
1837 } inherit_cbdata_t;
1839 static int
1840 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
1842 inherit_cbdata_t *cb = data;
1843 zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
1846 * If we're doing it recursively, then ignore properties that
1847 * are not valid for this type of dataset.
1849 if (prop != ZPROP_INVAL &&
1850 !zfs_prop_valid_for_type(prop, zfs_get_type(zhp)))
1851 return (0);
1853 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1856 static int
1857 inherit_cb(zfs_handle_t *zhp, void *data)
1859 inherit_cbdata_t *cb = data;
1861 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1864 static int
1865 zfs_do_inherit(int argc, char **argv)
1867 int c;
1868 zfs_prop_t prop;
1869 inherit_cbdata_t cb = { 0 };
1870 char *propname;
1871 int ret = 0;
1872 int flags = 0;
1873 boolean_t received = B_FALSE;
1875 /* check options */
1876 while ((c = getopt(argc, argv, "rS")) != -1) {
1877 switch (c) {
1878 case 'r':
1879 flags |= ZFS_ITER_RECURSE;
1880 break;
1881 case 'S':
1882 received = B_TRUE;
1883 break;
1884 case '?':
1885 default:
1886 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1887 optopt);
1888 usage(B_FALSE);
1892 argc -= optind;
1893 argv += optind;
1895 /* check number of arguments */
1896 if (argc < 1) {
1897 (void) fprintf(stderr, gettext("missing property argument\n"));
1898 usage(B_FALSE);
1900 if (argc < 2) {
1901 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1902 usage(B_FALSE);
1905 propname = argv[0];
1906 argc--;
1907 argv++;
1909 if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1910 if (zfs_prop_readonly(prop)) {
1911 (void) fprintf(stderr, gettext(
1912 "%s property is read-only\n"),
1913 propname);
1914 return (1);
1916 if (!zfs_prop_inheritable(prop) && !received) {
1917 (void) fprintf(stderr, gettext("'%s' property cannot "
1918 "be inherited\n"), propname);
1919 if (prop == ZFS_PROP_QUOTA ||
1920 prop == ZFS_PROP_RESERVATION ||
1921 prop == ZFS_PROP_REFQUOTA ||
1922 prop == ZFS_PROP_REFRESERVATION) {
1923 (void) fprintf(stderr, gettext("use 'zfs set "
1924 "%s=none' to clear\n"), propname);
1925 (void) fprintf(stderr, gettext("use 'zfs "
1926 "inherit -S %s' to revert to received "
1927 "value\n"), propname);
1929 return (1);
1931 if (received && (prop == ZFS_PROP_VOLSIZE ||
1932 prop == ZFS_PROP_VERSION)) {
1933 (void) fprintf(stderr, gettext("'%s' property cannot "
1934 "be reverted to a received value\n"), propname);
1935 return (1);
1937 } else if (!zfs_prop_user(propname)) {
1938 (void) fprintf(stderr, gettext("invalid property '%s'\n"),
1939 propname);
1940 usage(B_FALSE);
1943 cb.cb_propname = propname;
1944 cb.cb_received = received;
1946 if (flags & ZFS_ITER_RECURSE) {
1947 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1948 NULL, NULL, 0, inherit_recurse_cb, &cb);
1949 } else {
1950 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1951 NULL, NULL, 0, inherit_cb, &cb);
1954 return (ret);
1957 typedef struct upgrade_cbdata {
1958 uint64_t cb_numupgraded;
1959 uint64_t cb_numsamegraded;
1960 uint64_t cb_numfailed;
1961 uint64_t cb_version;
1962 boolean_t cb_newer;
1963 boolean_t cb_foundone;
1964 char cb_lastfs[ZFS_MAXNAMELEN];
1965 } upgrade_cbdata_t;
1967 static int
1968 same_pool(zfs_handle_t *zhp, const char *name)
1970 int len1 = strcspn(name, "/@");
1971 const char *zhname = zfs_get_name(zhp);
1972 int len2 = strcspn(zhname, "/@");
1974 if (len1 != len2)
1975 return (B_FALSE);
1976 return (strncmp(name, zhname, len1) == 0);
1979 static int
1980 upgrade_list_callback(zfs_handle_t *zhp, void *data)
1982 upgrade_cbdata_t *cb = data;
1983 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1985 /* list if it's old/new */
1986 if ((!cb->cb_newer && version < ZPL_VERSION) ||
1987 (cb->cb_newer && version > ZPL_VERSION)) {
1988 char *str;
1989 if (cb->cb_newer) {
1990 str = gettext("The following filesystems are "
1991 "formatted using a newer software version and\n"
1992 "cannot be accessed on the current system.\n\n");
1993 } else {
1994 str = gettext("The following filesystems are "
1995 "out of date, and can be upgraded. After being\n"
1996 "upgraded, these filesystems (and any 'zfs send' "
1997 "streams generated from\n"
1998 "subsequent snapshots) will no longer be "
1999 "accessible by older software versions.\n\n");
2002 if (!cb->cb_foundone) {
2003 (void) puts(str);
2004 (void) printf(gettext("VER FILESYSTEM\n"));
2005 (void) printf(gettext("--- ------------\n"));
2006 cb->cb_foundone = B_TRUE;
2009 (void) printf("%2u %s\n", version, zfs_get_name(zhp));
2012 return (0);
2015 static int
2016 upgrade_set_callback(zfs_handle_t *zhp, void *data)
2018 upgrade_cbdata_t *cb = data;
2019 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2020 int needed_spa_version;
2021 int spa_version;
2023 if (zfs_spa_version(zhp, &spa_version) < 0)
2024 return (-1);
2026 needed_spa_version = zfs_spa_version_map(cb->cb_version);
2028 if (needed_spa_version < 0)
2029 return (-1);
2031 if (spa_version < needed_spa_version) {
2032 /* can't upgrade */
2033 (void) printf(gettext("%s: can not be "
2034 "upgraded; the pool version needs to first "
2035 "be upgraded\nto version %d\n\n"),
2036 zfs_get_name(zhp), needed_spa_version);
2037 cb->cb_numfailed++;
2038 return (0);
2041 /* upgrade */
2042 if (version < cb->cb_version) {
2043 char verstr[16];
2044 (void) snprintf(verstr, sizeof (verstr),
2045 "%llu", cb->cb_version);
2046 if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
2048 * If they did "zfs upgrade -a", then we could
2049 * be doing ioctls to different pools. We need
2050 * to log this history once to each pool, and bypass
2051 * the normal history logging that happens in main().
2053 (void) zpool_log_history(g_zfs, history_str);
2054 log_history = B_FALSE;
2056 if (zfs_prop_set(zhp, "version", verstr) == 0)
2057 cb->cb_numupgraded++;
2058 else
2059 cb->cb_numfailed++;
2060 (void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
2061 } else if (version > cb->cb_version) {
2062 /* can't downgrade */
2063 (void) printf(gettext("%s: can not be downgraded; "
2064 "it is already at version %u\n"),
2065 zfs_get_name(zhp), version);
2066 cb->cb_numfailed++;
2067 } else {
2068 cb->cb_numsamegraded++;
2070 return (0);
2074 * zfs upgrade
2075 * zfs upgrade -v
2076 * zfs upgrade [-r] [-V <version>] <-a | filesystem>
2078 static int
2079 zfs_do_upgrade(int argc, char **argv)
2081 boolean_t all = B_FALSE;
2082 boolean_t showversions = B_FALSE;
2083 int ret = 0;
2084 upgrade_cbdata_t cb = { 0 };
2085 char c;
2086 int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2088 /* check options */
2089 while ((c = getopt(argc, argv, "rvV:a")) != -1) {
2090 switch (c) {
2091 case 'r':
2092 flags |= ZFS_ITER_RECURSE;
2093 break;
2094 case 'v':
2095 showversions = B_TRUE;
2096 break;
2097 case 'V':
2098 if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
2099 optarg, &cb.cb_version) != 0) {
2100 (void) fprintf(stderr,
2101 gettext("invalid version %s\n"), optarg);
2102 usage(B_FALSE);
2104 break;
2105 case 'a':
2106 all = B_TRUE;
2107 break;
2108 case '?':
2109 default:
2110 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2111 optopt);
2112 usage(B_FALSE);
2116 argc -= optind;
2117 argv += optind;
2119 if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
2120 usage(B_FALSE);
2121 if (showversions && (flags & ZFS_ITER_RECURSE || all ||
2122 cb.cb_version || argc))
2123 usage(B_FALSE);
2124 if ((all || argc) && (showversions))
2125 usage(B_FALSE);
2126 if (all && argc)
2127 usage(B_FALSE);
2129 if (showversions) {
2130 /* Show info on available versions. */
2131 (void) printf(gettext("The following filesystem versions are "
2132 "supported:\n\n"));
2133 (void) printf(gettext("VER DESCRIPTION\n"));
2134 (void) printf("--- -----------------------------------------"
2135 "---------------\n");
2136 (void) printf(gettext(" 1 Initial ZFS filesystem version\n"));
2137 (void) printf(gettext(" 2 Enhanced directory entries\n"));
2138 (void) printf(gettext(" 3 Case insensitive and filesystem "
2139 "user identifier (FUID)\n"));
2140 (void) printf(gettext(" 4 userquota, groupquota "
2141 "properties\n"));
2142 (void) printf(gettext(" 5 System attributes\n"));
2143 (void) printf(gettext("\nFor more information on a particular "
2144 "version, including supported releases,\n"));
2145 (void) printf("see the ZFS Administration Guide.\n\n");
2146 ret = 0;
2147 } else if (argc || all) {
2148 /* Upgrade filesystems */
2149 if (cb.cb_version == 0)
2150 cb.cb_version = ZPL_VERSION;
2151 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
2152 NULL, NULL, 0, upgrade_set_callback, &cb);
2153 (void) printf(gettext("%llu filesystems upgraded\n"),
2154 cb.cb_numupgraded);
2155 if (cb.cb_numsamegraded) {
2156 (void) printf(gettext("%llu filesystems already at "
2157 "this version\n"),
2158 cb.cb_numsamegraded);
2160 if (cb.cb_numfailed != 0)
2161 ret = 1;
2162 } else {
2163 /* List old-version filesytems */
2164 boolean_t found;
2165 (void) printf(gettext("This system is currently running "
2166 "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
2168 flags |= ZFS_ITER_RECURSE;
2169 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2170 NULL, NULL, 0, upgrade_list_callback, &cb);
2172 found = cb.cb_foundone;
2173 cb.cb_foundone = B_FALSE;
2174 cb.cb_newer = B_TRUE;
2176 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2177 NULL, NULL, 0, upgrade_list_callback, &cb);
2179 if (!cb.cb_foundone && !found) {
2180 (void) printf(gettext("All filesystems are "
2181 "formatted with the current version.\n"));
2185 return (ret);
2189 * zfs userspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2190 * [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2191 * zfs groupspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2192 * [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2194 * -H Scripted mode; elide headers and separate columns by tabs.
2195 * -i Translate SID to POSIX ID.
2196 * -n Print numeric ID instead of user/group name.
2197 * -o Control which fields to display.
2198 * -p Use exact (parsable) numeric output.
2199 * -s Specify sort columns, descending order.
2200 * -S Specify sort columns, ascending order.
2201 * -t Control which object types to display.
2203 * Displays space consumed by, and quotas on, each user in the specified
2204 * filesystem or snapshot.
2207 /* us_field_types, us_field_hdr and us_field_names should be kept in sync */
2208 enum us_field_types {
2209 USFIELD_TYPE,
2210 USFIELD_NAME,
2211 USFIELD_USED,
2212 USFIELD_QUOTA
2214 static char *us_field_hdr[] = { "TYPE", "NAME", "USED", "QUOTA" };
2215 static char *us_field_names[] = { "type", "name", "used", "quota" };
2216 #define USFIELD_LAST (sizeof (us_field_names) / sizeof (char *))
2218 #define USTYPE_PSX_GRP (1 << 0)
2219 #define USTYPE_PSX_USR (1 << 1)
2220 #define USTYPE_SMB_GRP (1 << 2)
2221 #define USTYPE_SMB_USR (1 << 3)
2222 #define USTYPE_ALL \
2223 (USTYPE_PSX_GRP | USTYPE_PSX_USR | USTYPE_SMB_GRP | USTYPE_SMB_USR)
2225 static int us_type_bits[] = {
2226 USTYPE_PSX_GRP,
2227 USTYPE_PSX_USR,
2228 USTYPE_SMB_GRP,
2229 USTYPE_SMB_USR,
2230 USTYPE_ALL
2232 static char *us_type_names[] = { "posixgroup", "posixuser", "smbgroup",
2233 "smbuser", "all" };
2235 typedef struct us_node {
2236 nvlist_t *usn_nvl;
2237 uu_avl_node_t usn_avlnode;
2238 uu_list_node_t usn_listnode;
2239 } us_node_t;
2241 typedef struct us_cbdata {
2242 nvlist_t **cb_nvlp;
2243 uu_avl_pool_t *cb_avl_pool;
2244 uu_avl_t *cb_avl;
2245 boolean_t cb_numname;
2246 boolean_t cb_nicenum;
2247 boolean_t cb_sid2posix;
2248 zfs_userquota_prop_t cb_prop;
2249 zfs_sort_column_t *cb_sortcol;
2250 size_t cb_width[USFIELD_LAST];
2251 } us_cbdata_t;
2253 static boolean_t us_populated = B_FALSE;
2255 typedef struct {
2256 zfs_sort_column_t *si_sortcol;
2257 boolean_t si_numname;
2258 } us_sort_info_t;
2260 static int
2261 us_field_index(char *field)
2263 int i;
2265 for (i = 0; i < USFIELD_LAST; i++) {
2266 if (strcmp(field, us_field_names[i]) == 0)
2267 return (i);
2270 return (-1);
2273 static int
2274 us_compare(const void *larg, const void *rarg, void *unused)
2276 const us_node_t *l = larg;
2277 const us_node_t *r = rarg;
2278 us_sort_info_t *si = (us_sort_info_t *)unused;
2279 zfs_sort_column_t *sortcol = si->si_sortcol;
2280 boolean_t numname = si->si_numname;
2281 nvlist_t *lnvl = l->usn_nvl;
2282 nvlist_t *rnvl = r->usn_nvl;
2283 int rc = 0;
2284 boolean_t lvb, rvb;
2286 for (; sortcol != NULL; sortcol = sortcol->sc_next) {
2287 char *lvstr = "";
2288 char *rvstr = "";
2289 uint32_t lv32 = 0;
2290 uint32_t rv32 = 0;
2291 uint64_t lv64 = 0;
2292 uint64_t rv64 = 0;
2293 zfs_prop_t prop = sortcol->sc_prop;
2294 const char *propname = NULL;
2295 boolean_t reverse = sortcol->sc_reverse;
2297 switch (prop) {
2298 case ZFS_PROP_TYPE:
2299 propname = "type";
2300 (void) nvlist_lookup_uint32(lnvl, propname, &lv32);
2301 (void) nvlist_lookup_uint32(rnvl, propname, &rv32);
2302 if (rv32 != lv32)
2303 rc = (rv32 < lv32) ? 1 : -1;
2304 break;
2305 case ZFS_PROP_NAME:
2306 propname = "name";
2307 if (numname) {
2308 (void) nvlist_lookup_uint64(lnvl, propname,
2309 &lv64);
2310 (void) nvlist_lookup_uint64(rnvl, propname,
2311 &rv64);
2312 if (rv64 != lv64)
2313 rc = (rv64 < lv64) ? 1 : -1;
2314 } else {
2315 (void) nvlist_lookup_string(lnvl, propname,
2316 &lvstr);
2317 (void) nvlist_lookup_string(rnvl, propname,
2318 &rvstr);
2319 rc = strcmp(lvstr, rvstr);
2321 break;
2322 case ZFS_PROP_USED:
2323 case ZFS_PROP_QUOTA:
2324 if (!us_populated)
2325 break;
2326 if (prop == ZFS_PROP_USED)
2327 propname = "used";
2328 else
2329 propname = "quota";
2330 (void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2331 (void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2332 if (rv64 != lv64)
2333 rc = (rv64 < lv64) ? 1 : -1;
2334 break;
2336 default:
2337 break;
2340 if (rc != 0) {
2341 if (rc < 0)
2342 return (reverse ? 1 : -1);
2343 else
2344 return (reverse ? -1 : 1);
2349 * If entries still seem to be the same, check if they are of the same
2350 * type (smbentity is added only if we are doing SID to POSIX ID
2351 * translation where we can have duplicate type/name combinations).
2353 if (nvlist_lookup_boolean_value(lnvl, "smbentity", &lvb) == 0 &&
2354 nvlist_lookup_boolean_value(rnvl, "smbentity", &rvb) == 0 &&
2355 lvb != rvb)
2356 return (lvb < rvb ? -1 : 1);
2358 return (0);
2361 static inline const char *
2362 us_type2str(unsigned field_type)
2364 switch (field_type) {
2365 case USTYPE_PSX_USR:
2366 return ("POSIX User");
2367 case USTYPE_PSX_GRP:
2368 return ("POSIX Group");
2369 case USTYPE_SMB_USR:
2370 return ("SMB User");
2371 case USTYPE_SMB_GRP:
2372 return ("SMB Group");
2373 default:
2374 return ("Undefined");
2378 static int
2379 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2381 us_cbdata_t *cb = (us_cbdata_t *)arg;
2382 zfs_userquota_prop_t prop = cb->cb_prop;
2383 char *name = NULL;
2384 char *propname;
2385 char sizebuf[32];
2386 us_node_t *node;
2387 uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2388 uu_avl_t *avl = cb->cb_avl;
2389 uu_avl_index_t idx;
2390 nvlist_t *props;
2391 us_node_t *n;
2392 zfs_sort_column_t *sortcol = cb->cb_sortcol;
2393 unsigned type = 0;
2394 const char *typestr;
2395 size_t namelen;
2396 size_t typelen;
2397 size_t sizelen;
2398 int typeidx, nameidx, sizeidx;
2399 us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
2400 boolean_t smbentity = B_FALSE;
2402 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
2403 nomem();
2404 node = safe_malloc(sizeof (us_node_t));
2405 uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
2406 node->usn_nvl = props;
2408 if (domain != NULL && domain[0] != '\0') {
2409 /* SMB */
2410 char sid[ZFS_MAXNAMELEN + 32];
2411 uid_t id;
2412 int err;
2413 int flag = IDMAP_REQ_FLG_USE_CACHE;
2415 smbentity = B_TRUE;
2417 (void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
2419 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2420 type = USTYPE_SMB_GRP;
2421 err = sid_to_id(sid, B_FALSE, &id);
2422 } else {
2423 type = USTYPE_SMB_USR;
2424 err = sid_to_id(sid, B_TRUE, &id);
2427 if (err == 0) {
2428 rid = id;
2429 if (!cb->cb_sid2posix) {
2430 if (type == USTYPE_SMB_USR) {
2431 (void) idmap_getwinnamebyuid(rid, flag,
2432 &name, NULL);
2433 } else {
2434 (void) idmap_getwinnamebygid(rid, flag,
2435 &name, NULL);
2437 if (name == NULL)
2438 name = sid;
2443 if (cb->cb_sid2posix || domain == NULL || domain[0] == '\0') {
2444 /* POSIX or -i */
2445 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2446 type = USTYPE_PSX_GRP;
2447 if (!cb->cb_numname) {
2448 struct group *g;
2450 if ((g = getgrgid(rid)) != NULL)
2451 name = g->gr_name;
2453 } else {
2454 type = USTYPE_PSX_USR;
2455 if (!cb->cb_numname) {
2456 struct passwd *p;
2458 if ((p = getpwuid(rid)) != NULL)
2459 name = p->pw_name;
2465 * Make sure that the type/name combination is unique when doing
2466 * SID to POSIX ID translation (hence changing the type from SMB to
2467 * POSIX).
2469 if (cb->cb_sid2posix &&
2470 nvlist_add_boolean_value(props, "smbentity", smbentity) != 0)
2471 nomem();
2473 /* Calculate/update width of TYPE field */
2474 typestr = us_type2str(type);
2475 typelen = strlen(gettext(typestr));
2476 typeidx = us_field_index("type");
2477 if (typelen > cb->cb_width[typeidx])
2478 cb->cb_width[typeidx] = typelen;
2479 if (nvlist_add_uint32(props, "type", type) != 0)
2480 nomem();
2482 /* Calculate/update width of NAME field */
2483 if ((cb->cb_numname && cb->cb_sid2posix) || name == NULL) {
2484 if (nvlist_add_uint64(props, "name", rid) != 0)
2485 nomem();
2486 namelen = snprintf(NULL, 0, "%u", rid);
2487 } else {
2488 if (nvlist_add_string(props, "name", name) != 0)
2489 nomem();
2490 namelen = strlen(name);
2492 nameidx = us_field_index("name");
2493 if (namelen > cb->cb_width[nameidx])
2494 cb->cb_width[nameidx] = namelen;
2497 * Check if this type/name combination is in the list and update it;
2498 * otherwise add new node to the list.
2500 if ((n = uu_avl_find(avl, node, &sortinfo, &idx)) == NULL) {
2501 uu_avl_insert(avl, node, idx);
2502 } else {
2503 nvlist_free(props);
2504 free(node);
2505 node = n;
2506 props = node->usn_nvl;
2509 /* Calculate/update width of USED/QUOTA fields */
2510 if (cb->cb_nicenum)
2511 zfs_nicenum(space, sizebuf, sizeof (sizebuf));
2512 else
2513 (void) snprintf(sizebuf, sizeof (sizebuf), "%llu", space);
2514 sizelen = strlen(sizebuf);
2515 if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED) {
2516 propname = "used";
2517 if (!nvlist_exists(props, "quota"))
2518 (void) nvlist_add_uint64(props, "quota", 0);
2519 } else {
2520 propname = "quota";
2521 if (!nvlist_exists(props, "used"))
2522 (void) nvlist_add_uint64(props, "used", 0);
2524 sizeidx = us_field_index(propname);
2525 if (sizelen > cb->cb_width[sizeidx])
2526 cb->cb_width[sizeidx] = sizelen;
2528 if (nvlist_add_uint64(props, propname, space) != 0)
2529 nomem();
2531 return (0);
2534 static void
2535 print_us_node(boolean_t scripted, boolean_t parsable, int *fields, int types,
2536 size_t *width, us_node_t *node)
2538 nvlist_t *nvl = node->usn_nvl;
2539 char valstr[ZFS_MAXNAMELEN];
2540 boolean_t first = B_TRUE;
2541 int cfield = 0;
2542 int field;
2543 uint32_t ustype;
2545 /* Check type */
2546 (void) nvlist_lookup_uint32(nvl, "type", &ustype);
2547 if (!(ustype & types))
2548 return;
2550 while ((field = fields[cfield]) != USFIELD_LAST) {
2551 nvpair_t *nvp = NULL;
2552 data_type_t type;
2553 uint32_t val32;
2554 uint64_t val64;
2555 char *strval = NULL;
2557 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
2558 if (strcmp(nvpair_name(nvp),
2559 us_field_names[field]) == 0)
2560 break;
2563 type = nvpair_type(nvp);
2564 switch (type) {
2565 case DATA_TYPE_UINT32:
2566 (void) nvpair_value_uint32(nvp, &val32);
2567 break;
2568 case DATA_TYPE_UINT64:
2569 (void) nvpair_value_uint64(nvp, &val64);
2570 break;
2571 case DATA_TYPE_STRING:
2572 (void) nvpair_value_string(nvp, &strval);
2573 break;
2574 default:
2575 (void) fprintf(stderr, "invalid data type\n");
2578 switch (field) {
2579 case USFIELD_TYPE:
2580 strval = (char *)us_type2str(val32);
2581 break;
2582 case USFIELD_NAME:
2583 if (type == DATA_TYPE_UINT64) {
2584 (void) sprintf(valstr, "%llu", val64);
2585 strval = valstr;
2587 break;
2588 case USFIELD_USED:
2589 case USFIELD_QUOTA:
2590 if (type == DATA_TYPE_UINT64) {
2591 if (parsable) {
2592 (void) sprintf(valstr, "%llu", val64);
2593 } else {
2594 zfs_nicenum(val64, valstr,
2595 sizeof (valstr));
2597 if (field == USFIELD_QUOTA &&
2598 strcmp(valstr, "0") == 0)
2599 strval = "none";
2600 else
2601 strval = valstr;
2603 break;
2606 if (!first) {
2607 if (scripted)
2608 (void) printf("\t");
2609 else
2610 (void) printf(" ");
2612 if (scripted)
2613 (void) printf("%s", strval);
2614 else if (field == USFIELD_TYPE || field == USFIELD_NAME)
2615 (void) printf("%-*s", width[field], strval);
2616 else
2617 (void) printf("%*s", width[field], strval);
2619 first = B_FALSE;
2620 cfield++;
2623 (void) printf("\n");
2626 static void
2627 print_us(boolean_t scripted, boolean_t parsable, int *fields, int types,
2628 size_t *width, boolean_t rmnode, uu_avl_t *avl)
2630 us_node_t *node;
2631 const char *col;
2632 int cfield = 0;
2633 int field;
2635 if (!scripted) {
2636 boolean_t first = B_TRUE;
2638 while ((field = fields[cfield]) != USFIELD_LAST) {
2639 col = gettext(us_field_hdr[field]);
2640 if (field == USFIELD_TYPE || field == USFIELD_NAME) {
2641 (void) printf(first ? "%-*s" : " %-*s",
2642 width[field], col);
2643 } else {
2644 (void) printf(first ? "%*s" : " %*s",
2645 width[field], col);
2647 first = B_FALSE;
2648 cfield++;
2650 (void) printf("\n");
2653 for (node = uu_avl_first(avl); node; node = uu_avl_next(avl, node)) {
2654 print_us_node(scripted, parsable, fields, types, width, node);
2655 if (rmnode)
2656 nvlist_free(node->usn_nvl);
2660 static int
2661 zfs_do_userspace(int argc, char **argv)
2663 zfs_handle_t *zhp;
2664 zfs_userquota_prop_t p;
2665 uu_avl_pool_t *avl_pool;
2666 uu_avl_t *avl_tree;
2667 uu_avl_walk_t *walk;
2668 char *delim;
2669 char deffields[] = "type,name,used,quota";
2670 char *ofield = NULL;
2671 char *tfield = NULL;
2672 int cfield = 0;
2673 int fields[256];
2674 int i;
2675 boolean_t scripted = B_FALSE;
2676 boolean_t prtnum = B_FALSE;
2677 boolean_t parsable = B_FALSE;
2678 boolean_t sid2posix = B_FALSE;
2679 int ret = 0;
2680 int c;
2681 zfs_sort_column_t *sortcol = NULL;
2682 int types = USTYPE_PSX_USR | USTYPE_SMB_USR;
2683 us_cbdata_t cb;
2684 us_node_t *node;
2685 us_node_t *rmnode;
2686 uu_list_pool_t *listpool;
2687 uu_list_t *list;
2688 uu_avl_index_t idx = 0;
2689 uu_list_index_t idx2 = 0;
2691 if (argc < 2)
2692 usage(B_FALSE);
2694 if (strcmp(argv[0], "groupspace") == 0)
2695 /* Toggle default group types */
2696 types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
2698 while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
2699 switch (c) {
2700 case 'n':
2701 prtnum = B_TRUE;
2702 break;
2703 case 'H':
2704 scripted = B_TRUE;
2705 break;
2706 case 'p':
2707 parsable = B_TRUE;
2708 break;
2709 case 'o':
2710 ofield = optarg;
2711 break;
2712 case 's':
2713 case 'S':
2714 if (zfs_add_sort_column(&sortcol, optarg,
2715 c == 's' ? B_FALSE : B_TRUE) != 0) {
2716 (void) fprintf(stderr,
2717 gettext("invalid field '%s'\n"), optarg);
2718 usage(B_FALSE);
2720 break;
2721 case 't':
2722 tfield = optarg;
2723 break;
2724 case 'i':
2725 sid2posix = B_TRUE;
2726 break;
2727 case ':':
2728 (void) fprintf(stderr, gettext("missing argument for "
2729 "'%c' option\n"), optopt);
2730 usage(B_FALSE);
2731 break;
2732 case '?':
2733 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2734 optopt);
2735 usage(B_FALSE);
2739 argc -= optind;
2740 argv += optind;
2742 if (argc < 1) {
2743 (void) fprintf(stderr, gettext("missing dataset name\n"));
2744 usage(B_FALSE);
2746 if (argc > 1) {
2747 (void) fprintf(stderr, gettext("too many arguments\n"));
2748 usage(B_FALSE);
2751 /* Use default output fields if not specified using -o */
2752 if (ofield == NULL)
2753 ofield = deffields;
2754 do {
2755 if ((delim = strchr(ofield, ',')) != NULL)
2756 *delim = '\0';
2757 if ((fields[cfield++] = us_field_index(ofield)) == -1) {
2758 (void) fprintf(stderr, gettext("invalid type '%s' "
2759 "for -o option\n"), ofield);
2760 return (-1);
2762 if (delim != NULL)
2763 ofield = delim + 1;
2764 } while (delim != NULL);
2765 fields[cfield] = USFIELD_LAST;
2767 /* Override output types (-t option) */
2768 if (tfield != NULL) {
2769 types = 0;
2771 do {
2772 boolean_t found = B_FALSE;
2774 if ((delim = strchr(tfield, ',')) != NULL)
2775 *delim = '\0';
2776 for (i = 0; i < sizeof (us_type_bits) / sizeof (int);
2777 i++) {
2778 if (strcmp(tfield, us_type_names[i]) == 0) {
2779 found = B_TRUE;
2780 types |= us_type_bits[i];
2781 break;
2784 if (!found) {
2785 (void) fprintf(stderr, gettext("invalid type "
2786 "'%s' for -t option\n"), tfield);
2787 return (-1);
2789 if (delim != NULL)
2790 tfield = delim + 1;
2791 } while (delim != NULL);
2794 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
2795 return (1);
2797 if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
2798 offsetof(us_node_t, usn_avlnode), us_compare, UU_DEFAULT)) == NULL)
2799 nomem();
2800 if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
2801 nomem();
2803 /* Always add default sorting columns */
2804 (void) zfs_add_sort_column(&sortcol, "type", B_FALSE);
2805 (void) zfs_add_sort_column(&sortcol, "name", B_FALSE);
2807 cb.cb_sortcol = sortcol;
2808 cb.cb_numname = prtnum;
2809 cb.cb_nicenum = !parsable;
2810 cb.cb_avl_pool = avl_pool;
2811 cb.cb_avl = avl_tree;
2812 cb.cb_sid2posix = sid2posix;
2814 for (i = 0; i < USFIELD_LAST; i++)
2815 cb.cb_width[i] = strlen(gettext(us_field_hdr[i]));
2817 for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
2818 if (((p == ZFS_PROP_USERUSED || p == ZFS_PROP_USERQUOTA) &&
2819 !(types & (USTYPE_PSX_USR | USTYPE_SMB_USR))) ||
2820 ((p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA) &&
2821 !(types & (USTYPE_PSX_GRP | USTYPE_SMB_GRP))))
2822 continue;
2823 cb.cb_prop = p;
2824 if ((ret = zfs_userspace(zhp, p, userspace_cb, &cb)) != 0)
2825 return (ret);
2828 /* Sort the list */
2829 if ((node = uu_avl_first(avl_tree)) == NULL)
2830 return (0);
2832 us_populated = B_TRUE;
2834 listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
2835 offsetof(us_node_t, usn_listnode), NULL, UU_DEFAULT);
2836 list = uu_list_create(listpool, NULL, UU_DEFAULT);
2837 uu_list_node_init(node, &node->usn_listnode, listpool);
2839 while (node != NULL) {
2840 rmnode = node;
2841 node = uu_avl_next(avl_tree, node);
2842 uu_avl_remove(avl_tree, rmnode);
2843 if (uu_list_find(list, rmnode, NULL, &idx2) == NULL)
2844 uu_list_insert(list, rmnode, idx2);
2847 for (node = uu_list_first(list); node != NULL;
2848 node = uu_list_next(list, node)) {
2849 us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
2851 if (uu_avl_find(avl_tree, node, &sortinfo, &idx) == NULL)
2852 uu_avl_insert(avl_tree, node, idx);
2855 uu_list_destroy(list);
2856 uu_list_pool_destroy(listpool);
2858 /* Print and free node nvlist memory */
2859 print_us(scripted, parsable, fields, types, cb.cb_width, B_TRUE,
2860 cb.cb_avl);
2862 zfs_free_sort_columns(sortcol);
2864 /* Clean up the AVL tree */
2865 if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
2866 nomem();
2868 while ((node = uu_avl_walk_next(walk)) != NULL) {
2869 uu_avl_remove(cb.cb_avl, node);
2870 free(node);
2873 uu_avl_walk_end(walk);
2874 uu_avl_destroy(avl_tree);
2875 uu_avl_pool_destroy(avl_pool);
2877 return (ret);
2881 * list [-Hp][-r|-d max] [-o property[,...]] [-s property] ... [-S property] ...
2882 * [-t type[,...]] [filesystem|volume|snapshot] ...
2884 * -H Scripted mode; elide headers and separate columns by tabs.
2885 * -p Display values in parsable (literal) format.
2886 * -r Recurse over all children.
2887 * -d Limit recursion by depth.
2888 * -o Control which fields to display.
2889 * -s Specify sort columns, descending order.
2890 * -S Specify sort columns, ascending order.
2891 * -t Control which object types to display.
2893 * When given no arguments, list all filesystems in the system.
2894 * Otherwise, list the specified datasets, optionally recursing down them if
2895 * '-r' is specified.
2897 typedef struct list_cbdata {
2898 boolean_t cb_first;
2899 boolean_t cb_literal;
2900 boolean_t cb_scripted;
2901 zprop_list_t *cb_proplist;
2902 } list_cbdata_t;
2905 * Given a list of columns to display, output appropriate headers for each one.
2907 static void
2908 print_header(list_cbdata_t *cb)
2910 zprop_list_t *pl = cb->cb_proplist;
2911 char headerbuf[ZFS_MAXPROPLEN];
2912 const char *header;
2913 int i;
2914 boolean_t first = B_TRUE;
2915 boolean_t right_justify;
2917 for (; pl != NULL; pl = pl->pl_next) {
2918 if (!first) {
2919 (void) printf(" ");
2920 } else {
2921 first = B_FALSE;
2924 right_justify = B_FALSE;
2925 if (pl->pl_prop != ZPROP_INVAL) {
2926 header = zfs_prop_column_name(pl->pl_prop);
2927 right_justify = zfs_prop_align_right(pl->pl_prop);
2928 } else {
2929 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
2930 headerbuf[i] = toupper(pl->pl_user_prop[i]);
2931 headerbuf[i] = '\0';
2932 header = headerbuf;
2935 if (pl->pl_next == NULL && !right_justify)
2936 (void) printf("%s", header);
2937 else if (right_justify)
2938 (void) printf("%*s", pl->pl_width, header);
2939 else
2940 (void) printf("%-*s", pl->pl_width, header);
2943 (void) printf("\n");
2947 * Given a dataset and a list of fields, print out all the properties according
2948 * to the described layout.
2950 static void
2951 print_dataset(zfs_handle_t *zhp, list_cbdata_t *cb)
2953 zprop_list_t *pl = cb->cb_proplist;
2954 boolean_t first = B_TRUE;
2955 char property[ZFS_MAXPROPLEN];
2956 nvlist_t *userprops = zfs_get_user_props(zhp);
2957 nvlist_t *propval;
2958 char *propstr;
2959 boolean_t right_justify;
2961 for (; pl != NULL; pl = pl->pl_next) {
2962 if (!first) {
2963 if (cb->cb_scripted)
2964 (void) printf("\t");
2965 else
2966 (void) printf(" ");
2967 } else {
2968 first = B_FALSE;
2971 if (pl->pl_prop != ZPROP_INVAL) {
2972 if (zfs_prop_get(zhp, pl->pl_prop, property,
2973 sizeof (property), NULL, NULL, 0,
2974 cb->cb_literal) != 0)
2975 propstr = "-";
2976 else
2977 propstr = property;
2978 right_justify = zfs_prop_align_right(pl->pl_prop);
2979 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
2980 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
2981 property, sizeof (property), cb->cb_literal) != 0)
2982 propstr = "-";
2983 else
2984 propstr = property;
2985 right_justify = B_TRUE;
2986 } else if (zfs_prop_written(pl->pl_user_prop)) {
2987 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
2988 property, sizeof (property), cb->cb_literal) != 0)
2989 propstr = "-";
2990 else
2991 propstr = property;
2992 right_justify = B_TRUE;
2993 } else {
2994 if (nvlist_lookup_nvlist(userprops,
2995 pl->pl_user_prop, &propval) != 0)
2996 propstr = "-";
2997 else
2998 verify(nvlist_lookup_string(propval,
2999 ZPROP_VALUE, &propstr) == 0);
3000 right_justify = B_FALSE;
3004 * If this is being called in scripted mode, or if this is the
3005 * last column and it is left-justified, don't include a width
3006 * format specifier.
3008 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
3009 (void) printf("%s", propstr);
3010 else if (right_justify)
3011 (void) printf("%*s", pl->pl_width, propstr);
3012 else
3013 (void) printf("%-*s", pl->pl_width, propstr);
3016 (void) printf("\n");
3020 * Generic callback function to list a dataset or snapshot.
3022 static int
3023 list_callback(zfs_handle_t *zhp, void *data)
3025 list_cbdata_t *cbp = data;
3027 if (cbp->cb_first) {
3028 if (!cbp->cb_scripted)
3029 print_header(cbp);
3030 cbp->cb_first = B_FALSE;
3033 print_dataset(zhp, cbp);
3035 return (0);
3038 static int
3039 zfs_do_list(int argc, char **argv)
3041 int c;
3042 static char default_fields[] =
3043 "name,used,available,referenced,mountpoint";
3044 int types = ZFS_TYPE_DATASET;
3045 boolean_t types_specified = B_FALSE;
3046 char *fields = NULL;
3047 list_cbdata_t cb = { 0 };
3048 char *value;
3049 int limit = 0;
3050 int ret = 0;
3051 zfs_sort_column_t *sortcol = NULL;
3052 int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
3054 /* check options */
3055 while ((c = getopt(argc, argv, "HS:d:o:prs:t:")) != -1) {
3056 switch (c) {
3057 case 'o':
3058 fields = optarg;
3059 break;
3060 case 'p':
3061 cb.cb_literal = B_TRUE;
3062 flags |= ZFS_ITER_LITERAL_PROPS;
3063 break;
3064 case 'd':
3065 limit = parse_depth(optarg, &flags);
3066 break;
3067 case 'r':
3068 flags |= ZFS_ITER_RECURSE;
3069 break;
3070 case 'H':
3071 cb.cb_scripted = B_TRUE;
3072 break;
3073 case 's':
3074 if (zfs_add_sort_column(&sortcol, optarg,
3075 B_FALSE) != 0) {
3076 (void) fprintf(stderr,
3077 gettext("invalid property '%s'\n"), optarg);
3078 usage(B_FALSE);
3080 break;
3081 case 'S':
3082 if (zfs_add_sort_column(&sortcol, optarg,
3083 B_TRUE) != 0) {
3084 (void) fprintf(stderr,
3085 gettext("invalid property '%s'\n"), optarg);
3086 usage(B_FALSE);
3088 break;
3089 case 't':
3090 types = 0;
3091 types_specified = B_TRUE;
3092 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
3093 while (*optarg != '\0') {
3094 static char *type_subopts[] = { "filesystem",
3095 "volume", "snapshot", "snap", "bookmark",
3096 "all", NULL };
3098 switch (getsubopt(&optarg, type_subopts,
3099 &value)) {
3100 case 0:
3101 types |= ZFS_TYPE_FILESYSTEM;
3102 break;
3103 case 1:
3104 types |= ZFS_TYPE_VOLUME;
3105 break;
3106 case 2:
3107 case 3:
3108 types |= ZFS_TYPE_SNAPSHOT;
3109 break;
3110 case 4:
3111 types |= ZFS_TYPE_BOOKMARK;
3112 break;
3113 case 5:
3114 types = ZFS_TYPE_DATASET |
3115 ZFS_TYPE_BOOKMARK;
3116 break;
3117 default:
3118 (void) fprintf(stderr,
3119 gettext("invalid type '%s'\n"),
3120 value);
3121 usage(B_FALSE);
3124 break;
3125 case ':':
3126 (void) fprintf(stderr, gettext("missing argument for "
3127 "'%c' option\n"), optopt);
3128 usage(B_FALSE);
3129 break;
3130 case '?':
3131 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3132 optopt);
3133 usage(B_FALSE);
3137 argc -= optind;
3138 argv += optind;
3140 if (fields == NULL)
3141 fields = default_fields;
3144 * If "-o space" and no types were specified, don't display snapshots.
3146 if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3147 types &= ~ZFS_TYPE_SNAPSHOT;
3150 * If the user specifies '-o all', the zprop_get_list() doesn't
3151 * normally include the name of the dataset. For 'zfs list', we always
3152 * want this property to be first.
3154 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3155 != 0)
3156 usage(B_FALSE);
3158 cb.cb_first = B_TRUE;
3160 ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
3161 limit, list_callback, &cb);
3163 zprop_free_list(cb.cb_proplist);
3164 zfs_free_sort_columns(sortcol);
3166 if (ret == 0 && cb.cb_first && !cb.cb_scripted)
3167 (void) printf(gettext("no datasets available\n"));
3169 return (ret);
3173 * zfs rename [-f] <fs | snap | vol> <fs | snap | vol>
3174 * zfs rename [-f] -p <fs | vol> <fs | vol>
3175 * zfs rename -r <snap> <snap>
3177 * Renames the given dataset to another of the same type.
3179 * The '-p' flag creates all the non-existing ancestors of the target first.
3181 /* ARGSUSED */
3182 static int
3183 zfs_do_rename(int argc, char **argv)
3185 zfs_handle_t *zhp;
3186 int c;
3187 int ret = 0;
3188 boolean_t recurse = B_FALSE;
3189 boolean_t parents = B_FALSE;
3190 boolean_t force_unmount = B_FALSE;
3192 /* check options */
3193 while ((c = getopt(argc, argv, "prf")) != -1) {
3194 switch (c) {
3195 case 'p':
3196 parents = B_TRUE;
3197 break;
3198 case 'r':
3199 recurse = B_TRUE;
3200 break;
3201 case 'f':
3202 force_unmount = B_TRUE;
3203 break;
3204 case '?':
3205 default:
3206 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3207 optopt);
3208 usage(B_FALSE);
3212 argc -= optind;
3213 argv += optind;
3215 /* check number of arguments */
3216 if (argc < 1) {
3217 (void) fprintf(stderr, gettext("missing source dataset "
3218 "argument\n"));
3219 usage(B_FALSE);
3221 if (argc < 2) {
3222 (void) fprintf(stderr, gettext("missing target dataset "
3223 "argument\n"));
3224 usage(B_FALSE);
3226 if (argc > 2) {
3227 (void) fprintf(stderr, gettext("too many arguments\n"));
3228 usage(B_FALSE);
3231 if (recurse && parents) {
3232 (void) fprintf(stderr, gettext("-p and -r options are mutually "
3233 "exclusive\n"));
3234 usage(B_FALSE);
3237 if (recurse && strchr(argv[0], '@') == 0) {
3238 (void) fprintf(stderr, gettext("source dataset for recursive "
3239 "rename must be a snapshot\n"));
3240 usage(B_FALSE);
3243 if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
3244 ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
3245 return (1);
3247 /* If we were asked and the name looks good, try to create ancestors. */
3248 if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
3249 zfs_create_ancestors(g_zfs, argv[1]) != 0) {
3250 zfs_close(zhp);
3251 return (1);
3254 ret = (zfs_rename(zhp, argv[1], recurse, force_unmount) != 0);
3256 zfs_close(zhp);
3257 return (ret);
3261 * zfs promote <fs>
3263 * Promotes the given clone fs to be the parent
3265 /* ARGSUSED */
3266 static int
3267 zfs_do_promote(int argc, char **argv)
3269 zfs_handle_t *zhp;
3270 int ret = 0;
3272 /* check options */
3273 if (argc > 1 && argv[1][0] == '-') {
3274 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3275 argv[1][1]);
3276 usage(B_FALSE);
3279 /* check number of arguments */
3280 if (argc < 2) {
3281 (void) fprintf(stderr, gettext("missing clone filesystem"
3282 " argument\n"));
3283 usage(B_FALSE);
3285 if (argc > 2) {
3286 (void) fprintf(stderr, gettext("too many arguments\n"));
3287 usage(B_FALSE);
3290 zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3291 if (zhp == NULL)
3292 return (1);
3294 ret = (zfs_promote(zhp) != 0);
3297 zfs_close(zhp);
3298 return (ret);
3302 * zfs rollback [-rRf] <snapshot>
3304 * -r Delete any intervening snapshots before doing rollback
3305 * -R Delete any snapshots and their clones
3306 * -f ignored for backwards compatability
3308 * Given a filesystem, rollback to a specific snapshot, discarding any changes
3309 * since then and making it the active dataset. If more recent snapshots exist,
3310 * the command will complain unless the '-r' flag is given.
3312 typedef struct rollback_cbdata {
3313 uint64_t cb_create;
3314 boolean_t cb_first;
3315 int cb_doclones;
3316 char *cb_target;
3317 int cb_error;
3318 boolean_t cb_recurse;
3319 } rollback_cbdata_t;
3321 static int
3322 rollback_check_dependent(zfs_handle_t *zhp, void *data)
3324 rollback_cbdata_t *cbp = data;
3326 if (cbp->cb_first && cbp->cb_recurse) {
3327 (void) fprintf(stderr, gettext("cannot rollback to "
3328 "'%s': clones of previous snapshots exist\n"),
3329 cbp->cb_target);
3330 (void) fprintf(stderr, gettext("use '-R' to "
3331 "force deletion of the following clones and "
3332 "dependents:\n"));
3333 cbp->cb_first = 0;
3334 cbp->cb_error = 1;
3337 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
3339 zfs_close(zhp);
3340 return (0);
3344 * Report any snapshots more recent than the one specified. Used when '-r' is
3345 * not specified. We reuse this same callback for the snapshot dependents - if
3346 * 'cb_dependent' is set, then this is a dependent and we should report it
3347 * without checking the transaction group.
3349 static int
3350 rollback_check(zfs_handle_t *zhp, void *data)
3352 rollback_cbdata_t *cbp = data;
3354 if (cbp->cb_doclones) {
3355 zfs_close(zhp);
3356 return (0);
3359 if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
3360 if (cbp->cb_first && !cbp->cb_recurse) {
3361 (void) fprintf(stderr, gettext("cannot "
3362 "rollback to '%s': more recent snapshots "
3363 "or bookmarks exist\n"),
3364 cbp->cb_target);
3365 (void) fprintf(stderr, gettext("use '-r' to "
3366 "force deletion of the following "
3367 "snapshots and bookmarks:\n"));
3368 cbp->cb_first = 0;
3369 cbp->cb_error = 1;
3372 if (cbp->cb_recurse) {
3373 if (zfs_iter_dependents(zhp, B_TRUE,
3374 rollback_check_dependent, cbp) != 0) {
3375 zfs_close(zhp);
3376 return (-1);
3378 } else {
3379 (void) fprintf(stderr, "%s\n",
3380 zfs_get_name(zhp));
3383 zfs_close(zhp);
3384 return (0);
3387 static int
3388 zfs_do_rollback(int argc, char **argv)
3390 int ret = 0;
3391 int c;
3392 boolean_t force = B_FALSE;
3393 rollback_cbdata_t cb = { 0 };
3394 zfs_handle_t *zhp, *snap;
3395 char parentname[ZFS_MAXNAMELEN];
3396 char *delim;
3398 /* check options */
3399 while ((c = getopt(argc, argv, "rRf")) != -1) {
3400 switch (c) {
3401 case 'r':
3402 cb.cb_recurse = 1;
3403 break;
3404 case 'R':
3405 cb.cb_recurse = 1;
3406 cb.cb_doclones = 1;
3407 break;
3408 case 'f':
3409 force = B_TRUE;
3410 break;
3411 case '?':
3412 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3413 optopt);
3414 usage(B_FALSE);
3418 argc -= optind;
3419 argv += optind;
3421 /* check number of arguments */
3422 if (argc < 1) {
3423 (void) fprintf(stderr, gettext("missing dataset argument\n"));
3424 usage(B_FALSE);
3426 if (argc > 1) {
3427 (void) fprintf(stderr, gettext("too many arguments\n"));
3428 usage(B_FALSE);
3431 /* open the snapshot */
3432 if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
3433 return (1);
3435 /* open the parent dataset */
3436 (void) strlcpy(parentname, argv[0], sizeof (parentname));
3437 verify((delim = strrchr(parentname, '@')) != NULL);
3438 *delim = '\0';
3439 if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
3440 zfs_close(snap);
3441 return (1);
3445 * Check for more recent snapshots and/or clones based on the presence
3446 * of '-r' and '-R'.
3448 cb.cb_target = argv[0];
3449 cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3450 cb.cb_first = B_TRUE;
3451 cb.cb_error = 0;
3452 if ((ret = zfs_iter_snapshots(zhp, rollback_check, &cb)) != 0)
3453 goto out;
3454 if ((ret = zfs_iter_bookmarks(zhp, rollback_check, &cb)) != 0)
3455 goto out;
3457 if ((ret = cb.cb_error) != 0)
3458 goto out;
3461 * Rollback parent to the given snapshot.
3463 ret = zfs_rollback(zhp, snap, force);
3465 out:
3466 zfs_close(snap);
3467 zfs_close(zhp);
3469 if (ret == 0)
3470 return (0);
3471 else
3472 return (1);
3476 * zfs set property=value ... { fs | snap | vol } ...
3478 * Sets the given properties for all datasets specified on the command line.
3481 static int
3482 set_callback(zfs_handle_t *zhp, void *data)
3484 nvlist_t *props = data;
3486 if (zfs_prop_set_list(zhp, props) != 0) {
3487 switch (libzfs_errno(g_zfs)) {
3488 case EZFS_MOUNTFAILED:
3489 (void) fprintf(stderr, gettext("property may be set "
3490 "but unable to remount filesystem\n"));
3491 break;
3492 case EZFS_SHARENFSFAILED:
3493 (void) fprintf(stderr, gettext("property may be set "
3494 "but unable to reshare filesystem\n"));
3495 break;
3497 return (1);
3499 return (0);
3502 static int
3503 zfs_do_set(int argc, char **argv)
3505 nvlist_t *props = NULL;
3506 int ds_start = -1; /* argv idx of first dataset arg */
3507 int ret = 0;
3509 /* check for options */
3510 if (argc > 1 && argv[1][0] == '-') {
3511 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3512 argv[1][1]);
3513 usage(B_FALSE);
3516 /* check number of arguments */
3517 if (argc < 2) {
3518 (void) fprintf(stderr, gettext("missing arguments\n"));
3519 usage(B_FALSE);
3521 if (argc < 3) {
3522 if (strchr(argv[1], '=') == NULL) {
3523 (void) fprintf(stderr, gettext("missing property=value "
3524 "argument(s)\n"));
3525 } else {
3526 (void) fprintf(stderr, gettext("missing dataset "
3527 "name(s)\n"));
3529 usage(B_FALSE);
3532 /* validate argument order: prop=val args followed by dataset args */
3533 for (int i = 1; i < argc; i++) {
3534 if (strchr(argv[i], '=') != NULL) {
3535 if (ds_start > 0) {
3536 /* out-of-order prop=val argument */
3537 (void) fprintf(stderr, gettext("invalid "
3538 "argument order\n"), i);
3539 usage(B_FALSE);
3541 } else if (ds_start < 0) {
3542 ds_start = i;
3545 if (ds_start < 0) {
3546 (void) fprintf(stderr, gettext("missing dataset name(s)\n"));
3547 usage(B_FALSE);
3550 /* Populate a list of property settings */
3551 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3552 nomem();
3553 for (int i = 1; i < ds_start; i++) {
3554 if ((ret = parseprop(props, argv[i])) != 0)
3555 goto error;
3558 ret = zfs_for_each(argc - ds_start, argv + ds_start, 0,
3559 ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, props);
3561 error:
3562 nvlist_free(props);
3563 return (ret);
3566 typedef struct snap_cbdata {
3567 nvlist_t *sd_nvl;
3568 boolean_t sd_recursive;
3569 const char *sd_snapname;
3570 } snap_cbdata_t;
3572 static int
3573 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
3575 snap_cbdata_t *sd = arg;
3576 char *name;
3577 int rv = 0;
3578 int error;
3580 if (sd->sd_recursive &&
3581 zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
3582 zfs_close(zhp);
3583 return (0);
3586 error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
3587 if (error == -1)
3588 nomem();
3589 fnvlist_add_boolean(sd->sd_nvl, name);
3590 free(name);
3592 if (sd->sd_recursive)
3593 rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
3594 zfs_close(zhp);
3595 return (rv);
3599 * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
3601 * Creates a snapshot with the given name. While functionally equivalent to
3602 * 'zfs create', it is a separate command to differentiate intent.
3604 static int
3605 zfs_do_snapshot(int argc, char **argv)
3607 int ret = 0;
3608 char c;
3609 nvlist_t *props;
3610 snap_cbdata_t sd = { 0 };
3611 boolean_t multiple_snaps = B_FALSE;
3613 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3614 nomem();
3615 if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
3616 nomem();
3618 /* check options */
3619 while ((c = getopt(argc, argv, "ro:")) != -1) {
3620 switch (c) {
3621 case 'o':
3622 if (parseprop(props, optarg) != 0)
3623 return (1);
3624 break;
3625 case 'r':
3626 sd.sd_recursive = B_TRUE;
3627 multiple_snaps = B_TRUE;
3628 break;
3629 case '?':
3630 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3631 optopt);
3632 goto usage;
3636 argc -= optind;
3637 argv += optind;
3639 /* check number of arguments */
3640 if (argc < 1) {
3641 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3642 goto usage;
3645 if (argc > 1)
3646 multiple_snaps = B_TRUE;
3647 for (; argc > 0; argc--, argv++) {
3648 char *atp;
3649 zfs_handle_t *zhp;
3651 atp = strchr(argv[0], '@');
3652 if (atp == NULL)
3653 goto usage;
3654 *atp = '\0';
3655 sd.sd_snapname = atp + 1;
3656 zhp = zfs_open(g_zfs, argv[0],
3657 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3658 if (zhp == NULL)
3659 goto usage;
3660 if (zfs_snapshot_cb(zhp, &sd) != 0)
3661 goto usage;
3664 ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
3665 nvlist_free(sd.sd_nvl);
3666 nvlist_free(props);
3667 if (ret != 0 && multiple_snaps)
3668 (void) fprintf(stderr, gettext("no snapshots were created\n"));
3669 return (ret != 0);
3671 usage:
3672 nvlist_free(sd.sd_nvl);
3673 nvlist_free(props);
3674 usage(B_FALSE);
3675 return (-1);
3679 * Send a backup stream to stdout.
3681 static int
3682 zfs_do_send(int argc, char **argv)
3684 char *fromname = NULL;
3685 char *toname = NULL;
3686 char *resume_token = NULL;
3687 char *cp;
3688 zfs_handle_t *zhp;
3689 sendflags_t flags = { 0 };
3690 int c, err;
3691 nvlist_t *dbgnv = NULL;
3692 boolean_t extraverbose = B_FALSE;
3694 /* check options */
3695 while ((c = getopt(argc, argv, ":i:I:RDpvnPLet:")) != -1) {
3696 switch (c) {
3697 case 'i':
3698 if (fromname)
3699 usage(B_FALSE);
3700 fromname = optarg;
3701 break;
3702 case 'I':
3703 if (fromname)
3704 usage(B_FALSE);
3705 fromname = optarg;
3706 flags.doall = B_TRUE;
3707 break;
3708 case 'R':
3709 flags.replicate = B_TRUE;
3710 break;
3711 case 'p':
3712 flags.props = B_TRUE;
3713 break;
3714 case 'P':
3715 flags.parsable = B_TRUE;
3716 flags.verbose = B_TRUE;
3717 break;
3718 case 'v':
3719 if (flags.verbose)
3720 extraverbose = B_TRUE;
3721 flags.verbose = B_TRUE;
3722 flags.progress = B_TRUE;
3723 break;
3724 case 'D':
3725 flags.dedup = B_TRUE;
3726 break;
3727 case 'n':
3728 flags.dryrun = B_TRUE;
3729 break;
3730 case 'L':
3731 flags.largeblock = B_TRUE;
3732 break;
3733 case 'e':
3734 flags.embed_data = B_TRUE;
3735 break;
3736 case 't':
3737 resume_token = optarg;
3738 break;
3739 case ':':
3740 (void) fprintf(stderr, gettext("missing argument for "
3741 "'%c' option\n"), optopt);
3742 usage(B_FALSE);
3743 break;
3744 case '?':
3745 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3746 optopt);
3747 usage(B_FALSE);
3751 argc -= optind;
3752 argv += optind;
3754 if (resume_token != NULL) {
3755 if (fromname != NULL || flags.replicate || flags.props ||
3756 flags.dedup) {
3757 (void) fprintf(stderr,
3758 gettext("invalid flags combined with -t\n"));
3759 usage(B_FALSE);
3761 if (argc != 0) {
3762 (void) fprintf(stderr, gettext("no additional "
3763 "arguments are permitted with -t\n"));
3764 usage(B_FALSE);
3766 } else {
3767 if (argc < 1) {
3768 (void) fprintf(stderr,
3769 gettext("missing snapshot argument\n"));
3770 usage(B_FALSE);
3772 if (argc > 1) {
3773 (void) fprintf(stderr, gettext("too many arguments\n"));
3774 usage(B_FALSE);
3778 if (!flags.dryrun && isatty(STDOUT_FILENO)) {
3779 (void) fprintf(stderr,
3780 gettext("Error: Stream can not be written to a terminal.\n"
3781 "You must redirect standard output.\n"));
3782 return (1);
3785 if (resume_token != NULL) {
3786 return (zfs_send_resume(g_zfs, &flags, STDOUT_FILENO,
3787 resume_token));
3791 * Special case sending a filesystem, or from a bookmark.
3793 if (strchr(argv[0], '@') == NULL ||
3794 (fromname && strchr(fromname, '#') != NULL)) {
3795 char frombuf[ZFS_MAXNAMELEN];
3796 enum lzc_send_flags lzc_flags = 0;
3798 if (flags.replicate || flags.doall || flags.props ||
3799 flags.dedup || flags.dryrun || flags.verbose ||
3800 flags.progress) {
3801 (void) fprintf(stderr,
3802 gettext("Error: "
3803 "Unsupported flag with filesystem or bookmark.\n"));
3804 return (1);
3807 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
3808 if (zhp == NULL)
3809 return (1);
3811 if (flags.largeblock)
3812 lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
3813 if (flags.embed_data)
3814 lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
3816 if (fromname != NULL &&
3817 (fromname[0] == '#' || fromname[0] == '@')) {
3819 * Incremental source name begins with # or @.
3820 * Default to same fs as target.
3822 (void) strncpy(frombuf, argv[0], sizeof (frombuf));
3823 cp = strchr(frombuf, '@');
3824 if (cp != NULL)
3825 *cp = '\0';
3826 (void) strlcat(frombuf, fromname, sizeof (frombuf));
3827 fromname = frombuf;
3829 err = zfs_send_one(zhp, fromname, STDOUT_FILENO, lzc_flags);
3830 zfs_close(zhp);
3831 return (err != 0);
3834 cp = strchr(argv[0], '@');
3835 *cp = '\0';
3836 toname = cp + 1;
3837 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3838 if (zhp == NULL)
3839 return (1);
3842 * If they specified the full path to the snapshot, chop off
3843 * everything except the short name of the snapshot, but special
3844 * case if they specify the origin.
3846 if (fromname && (cp = strchr(fromname, '@')) != NULL) {
3847 char origin[ZFS_MAXNAMELEN];
3848 zprop_source_t src;
3850 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
3851 origin, sizeof (origin), &src, NULL, 0, B_FALSE);
3853 if (strcmp(origin, fromname) == 0) {
3854 fromname = NULL;
3855 flags.fromorigin = B_TRUE;
3856 } else {
3857 *cp = '\0';
3858 if (cp != fromname && strcmp(argv[0], fromname)) {
3859 (void) fprintf(stderr,
3860 gettext("incremental source must be "
3861 "in same filesystem\n"));
3862 usage(B_FALSE);
3864 fromname = cp + 1;
3865 if (strchr(fromname, '@') || strchr(fromname, '/')) {
3866 (void) fprintf(stderr,
3867 gettext("invalid incremental source\n"));
3868 usage(B_FALSE);
3873 if (flags.replicate && fromname == NULL)
3874 flags.doall = B_TRUE;
3876 err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
3877 extraverbose ? &dbgnv : NULL);
3879 if (extraverbose && dbgnv != NULL) {
3881 * dump_nvlist prints to stdout, but that's been
3882 * redirected to a file. Make it print to stderr
3883 * instead.
3885 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
3886 dump_nvlist(dbgnv, 0);
3887 nvlist_free(dbgnv);
3889 zfs_close(zhp);
3891 return (err != 0);
3895 * Restore a backup stream from stdin.
3897 static int
3898 zfs_do_receive(int argc, char **argv)
3900 int c, err = 0;
3901 recvflags_t flags = { 0 };
3902 boolean_t abort_resumable = B_FALSE;
3904 nvlist_t *props;
3905 nvpair_t *nvp = NULL;
3907 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3908 nomem();
3910 /* check options */
3911 while ((c = getopt(argc, argv, ":o:denuvFsA")) != -1) {
3912 switch (c) {
3913 case 'o':
3914 if (parseprop(props, optarg) != 0)
3915 return (1);
3916 break;
3917 case 'd':
3918 flags.isprefix = B_TRUE;
3919 break;
3920 case 'e':
3921 flags.isprefix = B_TRUE;
3922 flags.istail = B_TRUE;
3923 break;
3924 case 'n':
3925 flags.dryrun = B_TRUE;
3926 break;
3927 case 'u':
3928 flags.nomount = B_TRUE;
3929 break;
3930 case 'v':
3931 flags.verbose = B_TRUE;
3932 break;
3933 case 's':
3934 flags.resumable = B_TRUE;
3935 break;
3936 case 'F':
3937 flags.force = B_TRUE;
3938 break;
3939 case 'A':
3940 abort_resumable = B_TRUE;
3941 break;
3942 case ':':
3943 (void) fprintf(stderr, gettext("missing argument for "
3944 "'%c' option\n"), optopt);
3945 usage(B_FALSE);
3946 break;
3947 case '?':
3948 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3949 optopt);
3950 usage(B_FALSE);
3954 argc -= optind;
3955 argv += optind;
3957 /* check number of arguments */
3958 if (argc < 1) {
3959 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3960 usage(B_FALSE);
3962 if (argc > 1) {
3963 (void) fprintf(stderr, gettext("too many arguments\n"));
3964 usage(B_FALSE);
3967 while ((nvp = nvlist_next_nvpair(props, nvp))) {
3968 if (strcmp(nvpair_name(nvp), "origin") != 0) {
3969 (void) fprintf(stderr, gettext("invalid option"));
3970 usage(B_FALSE);
3974 if (abort_resumable) {
3975 if (flags.isprefix || flags.istail || flags.dryrun ||
3976 flags.resumable || flags.nomount) {
3977 (void) fprintf(stderr, gettext("invalid option"));
3978 usage(B_FALSE);
3981 char namebuf[ZFS_MAXNAMELEN];
3982 (void) snprintf(namebuf, sizeof (namebuf),
3983 "%s/%%recv", argv[0]);
3985 if (zfs_dataset_exists(g_zfs, namebuf,
3986 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) {
3987 zfs_handle_t *zhp = zfs_open(g_zfs,
3988 namebuf, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3989 if (zhp == NULL)
3990 return (1);
3991 err = zfs_destroy(zhp, B_FALSE);
3992 } else {
3993 zfs_handle_t *zhp = zfs_open(g_zfs,
3994 argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3995 if (zhp == NULL)
3996 usage(B_FALSE);
3997 if (!zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) ||
3998 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
3999 NULL, 0, NULL, NULL, 0, B_TRUE) == -1) {
4000 (void) fprintf(stderr,
4001 gettext("'%s' does not have any "
4002 "resumable receive state to abort\n"),
4003 argv[0]);
4004 return (1);
4006 err = zfs_destroy(zhp, B_FALSE);
4009 return (err != 0);
4012 if (isatty(STDIN_FILENO)) {
4013 (void) fprintf(stderr,
4014 gettext("Error: Backup stream can not be read "
4015 "from a terminal.\n"
4016 "You must redirect standard input.\n"));
4017 return (1);
4019 err = zfs_receive(g_zfs, argv[0], props, &flags, STDIN_FILENO, NULL);
4021 return (err != 0);
4025 * allow/unallow stuff
4027 /* copied from zfs/sys/dsl_deleg.h */
4028 #define ZFS_DELEG_PERM_CREATE "create"
4029 #define ZFS_DELEG_PERM_DESTROY "destroy"
4030 #define ZFS_DELEG_PERM_SNAPSHOT "snapshot"
4031 #define ZFS_DELEG_PERM_ROLLBACK "rollback"
4032 #define ZFS_DELEG_PERM_CLONE "clone"
4033 #define ZFS_DELEG_PERM_PROMOTE "promote"
4034 #define ZFS_DELEG_PERM_RENAME "rename"
4035 #define ZFS_DELEG_PERM_MOUNT "mount"
4036 #define ZFS_DELEG_PERM_SHARE "share"
4037 #define ZFS_DELEG_PERM_SEND "send"
4038 #define ZFS_DELEG_PERM_RECEIVE "receive"
4039 #define ZFS_DELEG_PERM_ALLOW "allow"
4040 #define ZFS_DELEG_PERM_USERPROP "userprop"
4041 #define ZFS_DELEG_PERM_VSCAN "vscan" /* ??? */
4042 #define ZFS_DELEG_PERM_USERQUOTA "userquota"
4043 #define ZFS_DELEG_PERM_GROUPQUOTA "groupquota"
4044 #define ZFS_DELEG_PERM_USERUSED "userused"
4045 #define ZFS_DELEG_PERM_GROUPUSED "groupused"
4046 #define ZFS_DELEG_PERM_HOLD "hold"
4047 #define ZFS_DELEG_PERM_RELEASE "release"
4048 #define ZFS_DELEG_PERM_DIFF "diff"
4049 #define ZFS_DELEG_PERM_BOOKMARK "bookmark"
4051 #define ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
4053 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
4054 { ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
4055 { ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
4056 { ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
4057 { ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
4058 { ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
4059 { ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
4060 { ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
4061 { ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
4062 { ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
4063 { ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
4064 { ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
4065 { ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
4066 { ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
4067 { ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
4068 { ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
4069 { ZFS_DELEG_PERM_BOOKMARK, ZFS_DELEG_NOTE_BOOKMARK },
4071 { ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
4072 { ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
4073 { ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
4074 { ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
4075 { ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
4076 { NULL, ZFS_DELEG_NOTE_NONE }
4079 /* permission structure */
4080 typedef struct deleg_perm {
4081 zfs_deleg_who_type_t dp_who_type;
4082 const char *dp_name;
4083 boolean_t dp_local;
4084 boolean_t dp_descend;
4085 } deleg_perm_t;
4087 /* */
4088 typedef struct deleg_perm_node {
4089 deleg_perm_t dpn_perm;
4091 uu_avl_node_t dpn_avl_node;
4092 } deleg_perm_node_t;
4094 typedef struct fs_perm fs_perm_t;
4096 /* permissions set */
4097 typedef struct who_perm {
4098 zfs_deleg_who_type_t who_type;
4099 const char *who_name; /* id */
4100 char who_ug_name[256]; /* user/group name */
4101 fs_perm_t *who_fsperm; /* uplink */
4103 uu_avl_t *who_deleg_perm_avl; /* permissions */
4104 } who_perm_t;
4106 /* */
4107 typedef struct who_perm_node {
4108 who_perm_t who_perm;
4109 uu_avl_node_t who_avl_node;
4110 } who_perm_node_t;
4112 typedef struct fs_perm_set fs_perm_set_t;
4113 /* fs permissions */
4114 struct fs_perm {
4115 const char *fsp_name;
4117 uu_avl_t *fsp_sc_avl; /* sets,create */
4118 uu_avl_t *fsp_uge_avl; /* user,group,everyone */
4120 fs_perm_set_t *fsp_set; /* uplink */
4123 /* */
4124 typedef struct fs_perm_node {
4125 fs_perm_t fspn_fsperm;
4126 uu_avl_t *fspn_avl;
4128 uu_list_node_t fspn_list_node;
4129 } fs_perm_node_t;
4131 /* top level structure */
4132 struct fs_perm_set {
4133 uu_list_pool_t *fsps_list_pool;
4134 uu_list_t *fsps_list; /* list of fs_perms */
4136 uu_avl_pool_t *fsps_named_set_avl_pool;
4137 uu_avl_pool_t *fsps_who_perm_avl_pool;
4138 uu_avl_pool_t *fsps_deleg_perm_avl_pool;
4141 static inline const char *
4142 deleg_perm_type(zfs_deleg_note_t note)
4144 /* subcommands */
4145 switch (note) {
4146 /* SUBCOMMANDS */
4147 /* OTHER */
4148 case ZFS_DELEG_NOTE_GROUPQUOTA:
4149 case ZFS_DELEG_NOTE_GROUPUSED:
4150 case ZFS_DELEG_NOTE_USERPROP:
4151 case ZFS_DELEG_NOTE_USERQUOTA:
4152 case ZFS_DELEG_NOTE_USERUSED:
4153 /* other */
4154 return (gettext("other"));
4155 default:
4156 return (gettext("subcommand"));
4160 static int
4161 who_type2weight(zfs_deleg_who_type_t who_type)
4163 int res;
4164 switch (who_type) {
4165 case ZFS_DELEG_NAMED_SET_SETS:
4166 case ZFS_DELEG_NAMED_SET:
4167 res = 0;
4168 break;
4169 case ZFS_DELEG_CREATE_SETS:
4170 case ZFS_DELEG_CREATE:
4171 res = 1;
4172 break;
4173 case ZFS_DELEG_USER_SETS:
4174 case ZFS_DELEG_USER:
4175 res = 2;
4176 break;
4177 case ZFS_DELEG_GROUP_SETS:
4178 case ZFS_DELEG_GROUP:
4179 res = 3;
4180 break;
4181 case ZFS_DELEG_EVERYONE_SETS:
4182 case ZFS_DELEG_EVERYONE:
4183 res = 4;
4184 break;
4185 default:
4186 res = -1;
4189 return (res);
4192 /* ARGSUSED */
4193 static int
4194 who_perm_compare(const void *larg, const void *rarg, void *unused)
4196 const who_perm_node_t *l = larg;
4197 const who_perm_node_t *r = rarg;
4198 zfs_deleg_who_type_t ltype = l->who_perm.who_type;
4199 zfs_deleg_who_type_t rtype = r->who_perm.who_type;
4200 int lweight = who_type2weight(ltype);
4201 int rweight = who_type2weight(rtype);
4202 int res = lweight - rweight;
4203 if (res == 0)
4204 res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
4205 ZFS_MAX_DELEG_NAME-1);
4207 if (res == 0)
4208 return (0);
4209 if (res > 0)
4210 return (1);
4211 else
4212 return (-1);
4215 /* ARGSUSED */
4216 static int
4217 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
4219 const deleg_perm_node_t *l = larg;
4220 const deleg_perm_node_t *r = rarg;
4221 int res = strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
4222 ZFS_MAX_DELEG_NAME-1);
4224 if (res == 0)
4225 return (0);
4227 if (res > 0)
4228 return (1);
4229 else
4230 return (-1);
4233 static inline void
4234 fs_perm_set_init(fs_perm_set_t *fspset)
4236 bzero(fspset, sizeof (fs_perm_set_t));
4238 if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
4239 sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
4240 NULL, UU_DEFAULT)) == NULL)
4241 nomem();
4242 if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
4243 UU_DEFAULT)) == NULL)
4244 nomem();
4246 if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
4247 "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
4248 who_perm_node_t, who_avl_node), who_perm_compare,
4249 UU_DEFAULT)) == NULL)
4250 nomem();
4252 if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
4253 "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
4254 who_perm_node_t, who_avl_node), who_perm_compare,
4255 UU_DEFAULT)) == NULL)
4256 nomem();
4258 if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
4259 "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
4260 deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
4261 == NULL)
4262 nomem();
4265 static inline void fs_perm_fini(fs_perm_t *);
4266 static inline void who_perm_fini(who_perm_t *);
4268 static inline void
4269 fs_perm_set_fini(fs_perm_set_t *fspset)
4271 fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
4273 while (node != NULL) {
4274 fs_perm_node_t *next_node =
4275 uu_list_next(fspset->fsps_list, node);
4276 fs_perm_t *fsperm = &node->fspn_fsperm;
4277 fs_perm_fini(fsperm);
4278 uu_list_remove(fspset->fsps_list, node);
4279 free(node);
4280 node = next_node;
4283 uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
4284 uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
4285 uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
4288 static inline void
4289 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
4290 const char *name)
4292 deleg_perm->dp_who_type = type;
4293 deleg_perm->dp_name = name;
4296 static inline void
4297 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
4298 zfs_deleg_who_type_t type, const char *name)
4300 uu_avl_pool_t *pool;
4301 pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
4303 bzero(who_perm, sizeof (who_perm_t));
4305 if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
4306 UU_DEFAULT)) == NULL)
4307 nomem();
4309 who_perm->who_type = type;
4310 who_perm->who_name = name;
4311 who_perm->who_fsperm = fsperm;
4314 static inline void
4315 who_perm_fini(who_perm_t *who_perm)
4317 deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
4319 while (node != NULL) {
4320 deleg_perm_node_t *next_node =
4321 uu_avl_next(who_perm->who_deleg_perm_avl, node);
4323 uu_avl_remove(who_perm->who_deleg_perm_avl, node);
4324 free(node);
4325 node = next_node;
4328 uu_avl_destroy(who_perm->who_deleg_perm_avl);
4331 static inline void
4332 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
4334 uu_avl_pool_t *nset_pool = fspset->fsps_named_set_avl_pool;
4335 uu_avl_pool_t *who_pool = fspset->fsps_who_perm_avl_pool;
4337 bzero(fsperm, sizeof (fs_perm_t));
4339 if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
4340 == NULL)
4341 nomem();
4343 if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
4344 == NULL)
4345 nomem();
4347 fsperm->fsp_set = fspset;
4348 fsperm->fsp_name = fsname;
4351 static inline void
4352 fs_perm_fini(fs_perm_t *fsperm)
4354 who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
4355 while (node != NULL) {
4356 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
4357 node);
4358 who_perm_t *who_perm = &node->who_perm;
4359 who_perm_fini(who_perm);
4360 uu_avl_remove(fsperm->fsp_sc_avl, node);
4361 free(node);
4362 node = next_node;
4365 node = uu_avl_first(fsperm->fsp_uge_avl);
4366 while (node != NULL) {
4367 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
4368 node);
4369 who_perm_t *who_perm = &node->who_perm;
4370 who_perm_fini(who_perm);
4371 uu_avl_remove(fsperm->fsp_uge_avl, node);
4372 free(node);
4373 node = next_node;
4376 uu_avl_destroy(fsperm->fsp_sc_avl);
4377 uu_avl_destroy(fsperm->fsp_uge_avl);
4380 static void
4381 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
4382 zfs_deleg_who_type_t who_type, const char *name, char locality)
4384 uu_avl_index_t idx = 0;
4386 deleg_perm_node_t *found_node = NULL;
4387 deleg_perm_t *deleg_perm = &node->dpn_perm;
4389 deleg_perm_init(deleg_perm, who_type, name);
4391 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4392 == NULL)
4393 uu_avl_insert(avl, node, idx);
4394 else {
4395 node = found_node;
4396 deleg_perm = &node->dpn_perm;
4400 switch (locality) {
4401 case ZFS_DELEG_LOCAL:
4402 deleg_perm->dp_local = B_TRUE;
4403 break;
4404 case ZFS_DELEG_DESCENDENT:
4405 deleg_perm->dp_descend = B_TRUE;
4406 break;
4407 case ZFS_DELEG_NA:
4408 break;
4409 default:
4410 assert(B_FALSE); /* invalid locality */
4414 static inline int
4415 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
4417 nvpair_t *nvp = NULL;
4418 fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
4419 uu_avl_t *avl = who_perm->who_deleg_perm_avl;
4420 zfs_deleg_who_type_t who_type = who_perm->who_type;
4422 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4423 const char *name = nvpair_name(nvp);
4424 data_type_t type = nvpair_type(nvp);
4425 uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
4426 deleg_perm_node_t *node =
4427 safe_malloc(sizeof (deleg_perm_node_t));
4429 assert(type == DATA_TYPE_BOOLEAN);
4431 uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
4432 set_deleg_perm_node(avl, node, who_type, name, locality);
4435 return (0);
4438 static inline int
4439 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
4441 nvpair_t *nvp = NULL;
4442 fs_perm_set_t *fspset = fsperm->fsp_set;
4444 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4445 nvlist_t *nvl2 = NULL;
4446 const char *name = nvpair_name(nvp);
4447 uu_avl_t *avl = NULL;
4448 uu_avl_pool_t *avl_pool = NULL;
4449 zfs_deleg_who_type_t perm_type = name[0];
4450 char perm_locality = name[1];
4451 const char *perm_name = name + 3;
4452 boolean_t is_set = B_TRUE;
4453 who_perm_t *who_perm = NULL;
4455 assert('$' == name[2]);
4457 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4458 return (-1);
4460 switch (perm_type) {
4461 case ZFS_DELEG_CREATE:
4462 case ZFS_DELEG_CREATE_SETS:
4463 case ZFS_DELEG_NAMED_SET:
4464 case ZFS_DELEG_NAMED_SET_SETS:
4465 avl_pool = fspset->fsps_named_set_avl_pool;
4466 avl = fsperm->fsp_sc_avl;
4467 break;
4468 case ZFS_DELEG_USER:
4469 case ZFS_DELEG_USER_SETS:
4470 case ZFS_DELEG_GROUP:
4471 case ZFS_DELEG_GROUP_SETS:
4472 case ZFS_DELEG_EVERYONE:
4473 case ZFS_DELEG_EVERYONE_SETS:
4474 avl_pool = fspset->fsps_who_perm_avl_pool;
4475 avl = fsperm->fsp_uge_avl;
4476 break;
4478 default:
4479 assert(!"unhandled zfs_deleg_who_type_t");
4482 if (is_set) {
4483 who_perm_node_t *found_node = NULL;
4484 who_perm_node_t *node = safe_malloc(
4485 sizeof (who_perm_node_t));
4486 who_perm = &node->who_perm;
4487 uu_avl_index_t idx = 0;
4489 uu_avl_node_init(node, &node->who_avl_node, avl_pool);
4490 who_perm_init(who_perm, fsperm, perm_type, perm_name);
4492 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4493 == NULL) {
4494 if (avl == fsperm->fsp_uge_avl) {
4495 uid_t rid = 0;
4496 struct passwd *p = NULL;
4497 struct group *g = NULL;
4498 const char *nice_name = NULL;
4500 switch (perm_type) {
4501 case ZFS_DELEG_USER_SETS:
4502 case ZFS_DELEG_USER:
4503 rid = atoi(perm_name);
4504 p = getpwuid(rid);
4505 if (p)
4506 nice_name = p->pw_name;
4507 break;
4508 case ZFS_DELEG_GROUP_SETS:
4509 case ZFS_DELEG_GROUP:
4510 rid = atoi(perm_name);
4511 g = getgrgid(rid);
4512 if (g)
4513 nice_name = g->gr_name;
4514 break;
4516 default:
4517 break;
4520 if (nice_name != NULL)
4521 (void) strlcpy(
4522 node->who_perm.who_ug_name,
4523 nice_name, 256);
4526 uu_avl_insert(avl, node, idx);
4527 } else {
4528 node = found_node;
4529 who_perm = &node->who_perm;
4533 (void) parse_who_perm(who_perm, nvl2, perm_locality);
4536 return (0);
4539 static inline int
4540 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
4542 nvpair_t *nvp = NULL;
4543 uu_avl_index_t idx = 0;
4545 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4546 nvlist_t *nvl2 = NULL;
4547 const char *fsname = nvpair_name(nvp);
4548 data_type_t type = nvpair_type(nvp);
4549 fs_perm_t *fsperm = NULL;
4550 fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
4551 if (node == NULL)
4552 nomem();
4554 fsperm = &node->fspn_fsperm;
4556 assert(DATA_TYPE_NVLIST == type);
4558 uu_list_node_init(node, &node->fspn_list_node,
4559 fspset->fsps_list_pool);
4561 idx = uu_list_numnodes(fspset->fsps_list);
4562 fs_perm_init(fsperm, fspset, fsname);
4564 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4565 return (-1);
4567 (void) parse_fs_perm(fsperm, nvl2);
4569 uu_list_insert(fspset->fsps_list, node, idx);
4572 return (0);
4575 static inline const char *
4576 deleg_perm_comment(zfs_deleg_note_t note)
4578 const char *str = "";
4580 /* subcommands */
4581 switch (note) {
4582 /* SUBCOMMANDS */
4583 case ZFS_DELEG_NOTE_ALLOW:
4584 str = gettext("Must also have the permission that is being"
4585 "\n\t\t\t\tallowed");
4586 break;
4587 case ZFS_DELEG_NOTE_CLONE:
4588 str = gettext("Must also have the 'create' ability and 'mount'"
4589 "\n\t\t\t\tability in the origin file system");
4590 break;
4591 case ZFS_DELEG_NOTE_CREATE:
4592 str = gettext("Must also have the 'mount' ability");
4593 break;
4594 case ZFS_DELEG_NOTE_DESTROY:
4595 str = gettext("Must also have the 'mount' ability");
4596 break;
4597 case ZFS_DELEG_NOTE_DIFF:
4598 str = gettext("Allows lookup of paths within a dataset;"
4599 "\n\t\t\t\tgiven an object number. Ordinary users need this"
4600 "\n\t\t\t\tin order to use zfs diff");
4601 break;
4602 case ZFS_DELEG_NOTE_HOLD:
4603 str = gettext("Allows adding a user hold to a snapshot");
4604 break;
4605 case ZFS_DELEG_NOTE_MOUNT:
4606 str = gettext("Allows mount/umount of ZFS datasets");
4607 break;
4608 case ZFS_DELEG_NOTE_PROMOTE:
4609 str = gettext("Must also have the 'mount'\n\t\t\t\tand"
4610 " 'promote' ability in the origin file system");
4611 break;
4612 case ZFS_DELEG_NOTE_RECEIVE:
4613 str = gettext("Must also have the 'mount' and 'create'"
4614 " ability");
4615 break;
4616 case ZFS_DELEG_NOTE_RELEASE:
4617 str = gettext("Allows releasing a user hold which\n\t\t\t\t"
4618 "might destroy the snapshot");
4619 break;
4620 case ZFS_DELEG_NOTE_RENAME:
4621 str = gettext("Must also have the 'mount' and 'create'"
4622 "\n\t\t\t\tability in the new parent");
4623 break;
4624 case ZFS_DELEG_NOTE_ROLLBACK:
4625 str = gettext("");
4626 break;
4627 case ZFS_DELEG_NOTE_SEND:
4628 str = gettext("");
4629 break;
4630 case ZFS_DELEG_NOTE_SHARE:
4631 str = gettext("Allows sharing file systems over NFS or SMB"
4632 "\n\t\t\t\tprotocols");
4633 break;
4634 case ZFS_DELEG_NOTE_SNAPSHOT:
4635 str = gettext("");
4636 break;
4638 * case ZFS_DELEG_NOTE_VSCAN:
4639 * str = gettext("");
4640 * break;
4642 /* OTHER */
4643 case ZFS_DELEG_NOTE_GROUPQUOTA:
4644 str = gettext("Allows accessing any groupquota@... property");
4645 break;
4646 case ZFS_DELEG_NOTE_GROUPUSED:
4647 str = gettext("Allows reading any groupused@... property");
4648 break;
4649 case ZFS_DELEG_NOTE_USERPROP:
4650 str = gettext("Allows changing any user property");
4651 break;
4652 case ZFS_DELEG_NOTE_USERQUOTA:
4653 str = gettext("Allows accessing any userquota@... property");
4654 break;
4655 case ZFS_DELEG_NOTE_USERUSED:
4656 str = gettext("Allows reading any userused@... property");
4657 break;
4658 /* other */
4659 default:
4660 str = "";
4663 return (str);
4666 struct allow_opts {
4667 boolean_t local;
4668 boolean_t descend;
4669 boolean_t user;
4670 boolean_t group;
4671 boolean_t everyone;
4672 boolean_t create;
4673 boolean_t set;
4674 boolean_t recursive; /* unallow only */
4675 boolean_t prt_usage;
4677 boolean_t prt_perms;
4678 char *who;
4679 char *perms;
4680 const char *dataset;
4683 static inline int
4684 prop_cmp(const void *a, const void *b)
4686 const char *str1 = *(const char **)a;
4687 const char *str2 = *(const char **)b;
4688 return (strcmp(str1, str2));
4691 static void
4692 allow_usage(boolean_t un, boolean_t requested, const char *msg)
4694 const char *opt_desc[] = {
4695 "-h", gettext("show this help message and exit"),
4696 "-l", gettext("set permission locally"),
4697 "-d", gettext("set permission for descents"),
4698 "-u", gettext("set permission for user"),
4699 "-g", gettext("set permission for group"),
4700 "-e", gettext("set permission for everyone"),
4701 "-c", gettext("set create time permission"),
4702 "-s", gettext("define permission set"),
4703 /* unallow only */
4704 "-r", gettext("remove permissions recursively"),
4706 size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
4707 size_t allow_size = unallow_size - 2;
4708 const char *props[ZFS_NUM_PROPS];
4709 int i;
4710 size_t count = 0;
4711 FILE *fp = requested ? stdout : stderr;
4712 zprop_desc_t *pdtbl = zfs_prop_get_table();
4713 const char *fmt = gettext("%-16s %-14s\t%s\n");
4715 (void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
4716 HELP_ALLOW));
4717 (void) fprintf(fp, gettext("Options:\n"));
4718 for (int i = 0; i < (un ? unallow_size : allow_size); i++) {
4719 const char *opt = opt_desc[i++];
4720 const char *optdsc = opt_desc[i];
4721 (void) fprintf(fp, gettext(" %-10s %s\n"), opt, optdsc);
4724 (void) fprintf(fp, gettext("\nThe following permissions are "
4725 "supported:\n\n"));
4726 (void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
4727 gettext("NOTES"));
4728 for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
4729 const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
4730 zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
4731 const char *perm_type = deleg_perm_type(perm_note);
4732 const char *perm_comment = deleg_perm_comment(perm_note);
4733 (void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
4736 for (i = 0; i < ZFS_NUM_PROPS; i++) {
4737 zprop_desc_t *pd = &pdtbl[i];
4738 if (pd->pd_visible != B_TRUE)
4739 continue;
4741 if (pd->pd_attr == PROP_READONLY)
4742 continue;
4744 props[count++] = pd->pd_name;
4746 props[count] = NULL;
4748 qsort(props, count, sizeof (char *), prop_cmp);
4750 for (i = 0; i < count; i++)
4751 (void) fprintf(fp, fmt, props[i], gettext("property"), "");
4753 if (msg != NULL)
4754 (void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
4756 exit(requested ? 0 : 2);
4759 static inline const char *
4760 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
4761 char **permsp)
4763 if (un && argc == expected_argc - 1)
4764 *permsp = NULL;
4765 else if (argc == expected_argc)
4766 *permsp = argv[argc - 2];
4767 else
4768 allow_usage(un, B_FALSE,
4769 gettext("wrong number of parameters\n"));
4771 return (argv[argc - 1]);
4774 static void
4775 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
4777 int uge_sum = opts->user + opts->group + opts->everyone;
4778 int csuge_sum = opts->create + opts->set + uge_sum;
4779 int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
4780 int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
4782 if (uge_sum > 1)
4783 allow_usage(un, B_FALSE,
4784 gettext("-u, -g, and -e are mutually exclusive\n"));
4786 if (opts->prt_usage) {
4787 if (argc == 0 && all_sum == 0)
4788 allow_usage(un, B_TRUE, NULL);
4789 else
4790 usage(B_FALSE);
4793 if (opts->set) {
4794 if (csuge_sum > 1)
4795 allow_usage(un, B_FALSE,
4796 gettext("invalid options combined with -s\n"));
4798 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4799 if (argv[0][0] != '@')
4800 allow_usage(un, B_FALSE,
4801 gettext("invalid set name: missing '@' prefix\n"));
4802 opts->who = argv[0];
4803 } else if (opts->create) {
4804 if (ldcsuge_sum > 1)
4805 allow_usage(un, B_FALSE,
4806 gettext("invalid options combined with -c\n"));
4807 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4808 } else if (opts->everyone) {
4809 if (csuge_sum > 1)
4810 allow_usage(un, B_FALSE,
4811 gettext("invalid options combined with -e\n"));
4812 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4813 } else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
4814 == 0) {
4815 opts->everyone = B_TRUE;
4816 argc--;
4817 argv++;
4818 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4819 } else if (argc == 1 && !un) {
4820 opts->prt_perms = B_TRUE;
4821 opts->dataset = argv[argc-1];
4822 } else {
4823 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4824 opts->who = argv[0];
4827 if (!opts->local && !opts->descend) {
4828 opts->local = B_TRUE;
4829 opts->descend = B_TRUE;
4833 static void
4834 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
4835 const char *who, char *perms, nvlist_t *top_nvl)
4837 int i;
4838 char ld[2] = { '\0', '\0' };
4839 char who_buf[ZFS_MAXNAMELEN+32];
4840 char base_type = '\0';
4841 char set_type = '\0';
4842 nvlist_t *base_nvl = NULL;
4843 nvlist_t *set_nvl = NULL;
4844 nvlist_t *nvl;
4846 if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
4847 nomem();
4848 if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) != 0)
4849 nomem();
4851 switch (type) {
4852 case ZFS_DELEG_NAMED_SET_SETS:
4853 case ZFS_DELEG_NAMED_SET:
4854 set_type = ZFS_DELEG_NAMED_SET_SETS;
4855 base_type = ZFS_DELEG_NAMED_SET;
4856 ld[0] = ZFS_DELEG_NA;
4857 break;
4858 case ZFS_DELEG_CREATE_SETS:
4859 case ZFS_DELEG_CREATE:
4860 set_type = ZFS_DELEG_CREATE_SETS;
4861 base_type = ZFS_DELEG_CREATE;
4862 ld[0] = ZFS_DELEG_NA;
4863 break;
4864 case ZFS_DELEG_USER_SETS:
4865 case ZFS_DELEG_USER:
4866 set_type = ZFS_DELEG_USER_SETS;
4867 base_type = ZFS_DELEG_USER;
4868 if (local)
4869 ld[0] = ZFS_DELEG_LOCAL;
4870 if (descend)
4871 ld[1] = ZFS_DELEG_DESCENDENT;
4872 break;
4873 case ZFS_DELEG_GROUP_SETS:
4874 case ZFS_DELEG_GROUP:
4875 set_type = ZFS_DELEG_GROUP_SETS;
4876 base_type = ZFS_DELEG_GROUP;
4877 if (local)
4878 ld[0] = ZFS_DELEG_LOCAL;
4879 if (descend)
4880 ld[1] = ZFS_DELEG_DESCENDENT;
4881 break;
4882 case ZFS_DELEG_EVERYONE_SETS:
4883 case ZFS_DELEG_EVERYONE:
4884 set_type = ZFS_DELEG_EVERYONE_SETS;
4885 base_type = ZFS_DELEG_EVERYONE;
4886 if (local)
4887 ld[0] = ZFS_DELEG_LOCAL;
4888 if (descend)
4889 ld[1] = ZFS_DELEG_DESCENDENT;
4890 break;
4892 default:
4893 assert(set_type != '\0' && base_type != '\0');
4896 if (perms != NULL) {
4897 char *curr = perms;
4898 char *end = curr + strlen(perms);
4900 while (curr < end) {
4901 char *delim = strchr(curr, ',');
4902 if (delim == NULL)
4903 delim = end;
4904 else
4905 *delim = '\0';
4907 if (curr[0] == '@')
4908 nvl = set_nvl;
4909 else
4910 nvl = base_nvl;
4912 (void) nvlist_add_boolean(nvl, curr);
4913 if (delim != end)
4914 *delim = ',';
4915 curr = delim + 1;
4918 for (i = 0; i < 2; i++) {
4919 char locality = ld[i];
4920 if (locality == 0)
4921 continue;
4923 if (!nvlist_empty(base_nvl)) {
4924 if (who != NULL)
4925 (void) snprintf(who_buf,
4926 sizeof (who_buf), "%c%c$%s",
4927 base_type, locality, who);
4928 else
4929 (void) snprintf(who_buf,
4930 sizeof (who_buf), "%c%c$",
4931 base_type, locality);
4933 (void) nvlist_add_nvlist(top_nvl, who_buf,
4934 base_nvl);
4938 if (!nvlist_empty(set_nvl)) {
4939 if (who != NULL)
4940 (void) snprintf(who_buf,
4941 sizeof (who_buf), "%c%c$%s",
4942 set_type, locality, who);
4943 else
4944 (void) snprintf(who_buf,
4945 sizeof (who_buf), "%c%c$",
4946 set_type, locality);
4948 (void) nvlist_add_nvlist(top_nvl, who_buf,
4949 set_nvl);
4952 } else {
4953 for (i = 0; i < 2; i++) {
4954 char locality = ld[i];
4955 if (locality == 0)
4956 continue;
4958 if (who != NULL)
4959 (void) snprintf(who_buf, sizeof (who_buf),
4960 "%c%c$%s", base_type, locality, who);
4961 else
4962 (void) snprintf(who_buf, sizeof (who_buf),
4963 "%c%c$", base_type, locality);
4964 (void) nvlist_add_boolean(top_nvl, who_buf);
4966 if (who != NULL)
4967 (void) snprintf(who_buf, sizeof (who_buf),
4968 "%c%c$%s", set_type, locality, who);
4969 else
4970 (void) snprintf(who_buf, sizeof (who_buf),
4971 "%c%c$", set_type, locality);
4972 (void) nvlist_add_boolean(top_nvl, who_buf);
4977 static int
4978 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
4980 if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
4981 nomem();
4983 if (opts->set) {
4984 store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
4985 opts->descend, opts->who, opts->perms, *nvlp);
4986 } else if (opts->create) {
4987 store_allow_perm(ZFS_DELEG_CREATE, opts->local,
4988 opts->descend, NULL, opts->perms, *nvlp);
4989 } else if (opts->everyone) {
4990 store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
4991 opts->descend, NULL, opts->perms, *nvlp);
4992 } else {
4993 char *curr = opts->who;
4994 char *end = curr + strlen(curr);
4996 while (curr < end) {
4997 const char *who;
4998 zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
4999 char *endch;
5000 char *delim = strchr(curr, ',');
5001 char errbuf[256];
5002 char id[64];
5003 struct passwd *p = NULL;
5004 struct group *g = NULL;
5006 uid_t rid;
5007 if (delim == NULL)
5008 delim = end;
5009 else
5010 *delim = '\0';
5012 rid = (uid_t)strtol(curr, &endch, 0);
5013 if (opts->user) {
5014 who_type = ZFS_DELEG_USER;
5015 if (*endch != '\0')
5016 p = getpwnam(curr);
5017 else
5018 p = getpwuid(rid);
5020 if (p != NULL)
5021 rid = p->pw_uid;
5022 else {
5023 (void) snprintf(errbuf, 256, gettext(
5024 "invalid user %s"), curr);
5025 allow_usage(un, B_TRUE, errbuf);
5027 } else if (opts->group) {
5028 who_type = ZFS_DELEG_GROUP;
5029 if (*endch != '\0')
5030 g = getgrnam(curr);
5031 else
5032 g = getgrgid(rid);
5034 if (g != NULL)
5035 rid = g->gr_gid;
5036 else {
5037 (void) snprintf(errbuf, 256, gettext(
5038 "invalid group %s"), curr);
5039 allow_usage(un, B_TRUE, errbuf);
5041 } else {
5042 if (*endch != '\0') {
5043 p = getpwnam(curr);
5044 } else {
5045 p = getpwuid(rid);
5048 if (p == NULL) {
5049 if (*endch != '\0') {
5050 g = getgrnam(curr);
5051 } else {
5052 g = getgrgid(rid);
5056 if (p != NULL) {
5057 who_type = ZFS_DELEG_USER;
5058 rid = p->pw_uid;
5059 } else if (g != NULL) {
5060 who_type = ZFS_DELEG_GROUP;
5061 rid = g->gr_gid;
5062 } else {
5063 (void) snprintf(errbuf, 256, gettext(
5064 "invalid user/group %s"), curr);
5065 allow_usage(un, B_TRUE, errbuf);
5069 (void) sprintf(id, "%u", rid);
5070 who = id;
5072 store_allow_perm(who_type, opts->local,
5073 opts->descend, who, opts->perms, *nvlp);
5074 curr = delim + 1;
5078 return (0);
5081 static void
5082 print_set_creat_perms(uu_avl_t *who_avl)
5084 const char *sc_title[] = {
5085 gettext("Permission sets:\n"),
5086 gettext("Create time permissions:\n"),
5087 NULL
5089 const char **title_ptr = sc_title;
5090 who_perm_node_t *who_node = NULL;
5091 int prev_weight = -1;
5093 for (who_node = uu_avl_first(who_avl); who_node != NULL;
5094 who_node = uu_avl_next(who_avl, who_node)) {
5095 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5096 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5097 const char *who_name = who_node->who_perm.who_name;
5098 int weight = who_type2weight(who_type);
5099 boolean_t first = B_TRUE;
5100 deleg_perm_node_t *deleg_node;
5102 if (prev_weight != weight) {
5103 (void) printf(*title_ptr++);
5104 prev_weight = weight;
5107 if (who_name == NULL || strnlen(who_name, 1) == 0)
5108 (void) printf("\t");
5109 else
5110 (void) printf("\t%s ", who_name);
5112 for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
5113 deleg_node = uu_avl_next(avl, deleg_node)) {
5114 if (first) {
5115 (void) printf("%s",
5116 deleg_node->dpn_perm.dp_name);
5117 first = B_FALSE;
5118 } else
5119 (void) printf(",%s",
5120 deleg_node->dpn_perm.dp_name);
5123 (void) printf("\n");
5127 static void
5128 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
5129 const char *title)
5131 who_perm_node_t *who_node = NULL;
5132 boolean_t prt_title = B_TRUE;
5133 uu_avl_walk_t *walk;
5135 if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
5136 nomem();
5138 while ((who_node = uu_avl_walk_next(walk)) != NULL) {
5139 const char *who_name = who_node->who_perm.who_name;
5140 const char *nice_who_name = who_node->who_perm.who_ug_name;
5141 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5142 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5143 char delim = ' ';
5144 deleg_perm_node_t *deleg_node;
5145 boolean_t prt_who = B_TRUE;
5147 for (deleg_node = uu_avl_first(avl);
5148 deleg_node != NULL;
5149 deleg_node = uu_avl_next(avl, deleg_node)) {
5150 if (local != deleg_node->dpn_perm.dp_local ||
5151 descend != deleg_node->dpn_perm.dp_descend)
5152 continue;
5154 if (prt_who) {
5155 const char *who = NULL;
5156 if (prt_title) {
5157 prt_title = B_FALSE;
5158 (void) printf(title);
5161 switch (who_type) {
5162 case ZFS_DELEG_USER_SETS:
5163 case ZFS_DELEG_USER:
5164 who = gettext("user");
5165 if (nice_who_name)
5166 who_name = nice_who_name;
5167 break;
5168 case ZFS_DELEG_GROUP_SETS:
5169 case ZFS_DELEG_GROUP:
5170 who = gettext("group");
5171 if (nice_who_name)
5172 who_name = nice_who_name;
5173 break;
5174 case ZFS_DELEG_EVERYONE_SETS:
5175 case ZFS_DELEG_EVERYONE:
5176 who = gettext("everyone");
5177 who_name = NULL;
5178 break;
5180 default:
5181 assert(who != NULL);
5184 prt_who = B_FALSE;
5185 if (who_name == NULL)
5186 (void) printf("\t%s", who);
5187 else
5188 (void) printf("\t%s %s", who, who_name);
5191 (void) printf("%c%s", delim,
5192 deleg_node->dpn_perm.dp_name);
5193 delim = ',';
5196 if (!prt_who)
5197 (void) printf("\n");
5200 uu_avl_walk_end(walk);
5203 static void
5204 print_fs_perms(fs_perm_set_t *fspset)
5206 fs_perm_node_t *node = NULL;
5207 char buf[ZFS_MAXNAMELEN+32];
5208 const char *dsname = buf;
5210 for (node = uu_list_first(fspset->fsps_list); node != NULL;
5211 node = uu_list_next(fspset->fsps_list, node)) {
5212 uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
5213 uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
5214 int left = 0;
5216 (void) snprintf(buf, ZFS_MAXNAMELEN+32,
5217 gettext("---- Permissions on %s "),
5218 node->fspn_fsperm.fsp_name);
5219 (void) printf(dsname);
5220 left = 70 - strlen(buf);
5221 while (left-- > 0)
5222 (void) printf("-");
5223 (void) printf("\n");
5225 print_set_creat_perms(sc_avl);
5226 print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
5227 gettext("Local permissions:\n"));
5228 print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
5229 gettext("Descendent permissions:\n"));
5230 print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
5231 gettext("Local+Descendent permissions:\n"));
5235 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
5237 struct deleg_perms {
5238 boolean_t un;
5239 nvlist_t *nvl;
5242 static int
5243 set_deleg_perms(zfs_handle_t *zhp, void *data)
5245 struct deleg_perms *perms = (struct deleg_perms *)data;
5246 zfs_type_t zfs_type = zfs_get_type(zhp);
5248 if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
5249 return (0);
5251 return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
5254 static int
5255 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
5257 zfs_handle_t *zhp;
5258 nvlist_t *perm_nvl = NULL;
5259 nvlist_t *update_perm_nvl = NULL;
5260 int error = 1;
5261 int c;
5262 struct allow_opts opts = { 0 };
5264 const char *optstr = un ? "ldugecsrh" : "ldugecsh";
5266 /* check opts */
5267 while ((c = getopt(argc, argv, optstr)) != -1) {
5268 switch (c) {
5269 case 'l':
5270 opts.local = B_TRUE;
5271 break;
5272 case 'd':
5273 opts.descend = B_TRUE;
5274 break;
5275 case 'u':
5276 opts.user = B_TRUE;
5277 break;
5278 case 'g':
5279 opts.group = B_TRUE;
5280 break;
5281 case 'e':
5282 opts.everyone = B_TRUE;
5283 break;
5284 case 's':
5285 opts.set = B_TRUE;
5286 break;
5287 case 'c':
5288 opts.create = B_TRUE;
5289 break;
5290 case 'r':
5291 opts.recursive = B_TRUE;
5292 break;
5293 case ':':
5294 (void) fprintf(stderr, gettext("missing argument for "
5295 "'%c' option\n"), optopt);
5296 usage(B_FALSE);
5297 break;
5298 case 'h':
5299 opts.prt_usage = B_TRUE;
5300 break;
5301 case '?':
5302 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5303 optopt);
5304 usage(B_FALSE);
5308 argc -= optind;
5309 argv += optind;
5311 /* check arguments */
5312 parse_allow_args(argc, argv, un, &opts);
5314 /* try to open the dataset */
5315 if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
5316 ZFS_TYPE_VOLUME)) == NULL) {
5317 (void) fprintf(stderr, "Failed to open dataset: %s\n",
5318 opts.dataset);
5319 return (-1);
5322 if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
5323 goto cleanup2;
5325 fs_perm_set_init(&fs_perm_set);
5326 if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
5327 (void) fprintf(stderr, "Failed to parse fsacl permissions\n");
5328 goto cleanup1;
5331 if (opts.prt_perms)
5332 print_fs_perms(&fs_perm_set);
5333 else {
5334 (void) construct_fsacl_list(un, &opts, &update_perm_nvl);
5335 if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
5336 goto cleanup0;
5338 if (un && opts.recursive) {
5339 struct deleg_perms data = { un, update_perm_nvl };
5340 if (zfs_iter_filesystems(zhp, set_deleg_perms,
5341 &data) != 0)
5342 goto cleanup0;
5346 error = 0;
5348 cleanup0:
5349 nvlist_free(perm_nvl);
5350 nvlist_free(update_perm_nvl);
5351 cleanup1:
5352 fs_perm_set_fini(&fs_perm_set);
5353 cleanup2:
5354 zfs_close(zhp);
5356 return (error);
5359 static int
5360 zfs_do_allow(int argc, char **argv)
5362 return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
5365 static int
5366 zfs_do_unallow(int argc, char **argv)
5368 return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
5371 static int
5372 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
5374 int errors = 0;
5375 int i;
5376 const char *tag;
5377 boolean_t recursive = B_FALSE;
5378 const char *opts = holding ? "rt" : "r";
5379 int c;
5381 /* check options */
5382 while ((c = getopt(argc, argv, opts)) != -1) {
5383 switch (c) {
5384 case 'r':
5385 recursive = B_TRUE;
5386 break;
5387 case '?':
5388 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5389 optopt);
5390 usage(B_FALSE);
5394 argc -= optind;
5395 argv += optind;
5397 /* check number of arguments */
5398 if (argc < 2)
5399 usage(B_FALSE);
5401 tag = argv[0];
5402 --argc;
5403 ++argv;
5405 if (holding && tag[0] == '.') {
5406 /* tags starting with '.' are reserved for libzfs */
5407 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
5408 usage(B_FALSE);
5411 for (i = 0; i < argc; ++i) {
5412 zfs_handle_t *zhp;
5413 char parent[ZFS_MAXNAMELEN];
5414 const char *delim;
5415 char *path = argv[i];
5417 delim = strchr(path, '@');
5418 if (delim == NULL) {
5419 (void) fprintf(stderr,
5420 gettext("'%s' is not a snapshot\n"), path);
5421 ++errors;
5422 continue;
5424 (void) strncpy(parent, path, delim - path);
5425 parent[delim - path] = '\0';
5427 zhp = zfs_open(g_zfs, parent,
5428 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5429 if (zhp == NULL) {
5430 ++errors;
5431 continue;
5433 if (holding) {
5434 if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
5435 ++errors;
5436 } else {
5437 if (zfs_release(zhp, delim+1, tag, recursive) != 0)
5438 ++errors;
5440 zfs_close(zhp);
5443 return (errors != 0);
5447 * zfs hold [-r] [-t] <tag> <snap> ...
5449 * -r Recursively hold
5451 * Apply a user-hold with the given tag to the list of snapshots.
5453 static int
5454 zfs_do_hold(int argc, char **argv)
5456 return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
5460 * zfs release [-r] <tag> <snap> ...
5462 * -r Recursively release
5464 * Release a user-hold with the given tag from the list of snapshots.
5466 static int
5467 zfs_do_release(int argc, char **argv)
5469 return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
5472 typedef struct holds_cbdata {
5473 boolean_t cb_recursive;
5474 const char *cb_snapname;
5475 nvlist_t **cb_nvlp;
5476 size_t cb_max_namelen;
5477 size_t cb_max_taglen;
5478 } holds_cbdata_t;
5480 #define STRFTIME_FMT_STR "%a %b %e %k:%M %Y"
5481 #define DATETIME_BUF_LEN (32)
5485 static void
5486 print_holds(boolean_t scripted, size_t nwidth, size_t tagwidth, nvlist_t *nvl)
5488 int i;
5489 nvpair_t *nvp = NULL;
5490 char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
5491 const char *col;
5493 if (!scripted) {
5494 for (i = 0; i < 3; i++) {
5495 col = gettext(hdr_cols[i]);
5496 if (i < 2)
5497 (void) printf("%-*s ", i ? tagwidth : nwidth,
5498 col);
5499 else
5500 (void) printf("%s\n", col);
5504 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5505 char *zname = nvpair_name(nvp);
5506 nvlist_t *nvl2;
5507 nvpair_t *nvp2 = NULL;
5508 (void) nvpair_value_nvlist(nvp, &nvl2);
5509 while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
5510 char tsbuf[DATETIME_BUF_LEN];
5511 char *tagname = nvpair_name(nvp2);
5512 uint64_t val = 0;
5513 time_t time;
5514 struct tm t;
5515 char sep = scripted ? '\t' : ' ';
5516 size_t sepnum = scripted ? 1 : 2;
5518 (void) nvpair_value_uint64(nvp2, &val);
5519 time = (time_t)val;
5520 (void) localtime_r(&time, &t);
5521 (void) strftime(tsbuf, DATETIME_BUF_LEN,
5522 gettext(STRFTIME_FMT_STR), &t);
5524 (void) printf("%-*s%*c%-*s%*c%s\n", nwidth, zname,
5525 sepnum, sep, tagwidth, tagname, sepnum, sep, tsbuf);
5531 * Generic callback function to list a dataset or snapshot.
5533 static int
5534 holds_callback(zfs_handle_t *zhp, void *data)
5536 holds_cbdata_t *cbp = data;
5537 nvlist_t *top_nvl = *cbp->cb_nvlp;
5538 nvlist_t *nvl = NULL;
5539 nvpair_t *nvp = NULL;
5540 const char *zname = zfs_get_name(zhp);
5541 size_t znamelen = strnlen(zname, ZFS_MAXNAMELEN);
5543 if (cbp->cb_recursive) {
5544 const char *snapname;
5545 char *delim = strchr(zname, '@');
5546 if (delim == NULL)
5547 return (0);
5549 snapname = delim + 1;
5550 if (strcmp(cbp->cb_snapname, snapname))
5551 return (0);
5554 if (zfs_get_holds(zhp, &nvl) != 0)
5555 return (-1);
5557 if (znamelen > cbp->cb_max_namelen)
5558 cbp->cb_max_namelen = znamelen;
5560 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5561 const char *tag = nvpair_name(nvp);
5562 size_t taglen = strnlen(tag, MAXNAMELEN);
5563 if (taglen > cbp->cb_max_taglen)
5564 cbp->cb_max_taglen = taglen;
5567 return (nvlist_add_nvlist(top_nvl, zname, nvl));
5571 * zfs holds [-r] <snap> ...
5573 * -r Recursively hold
5575 static int
5576 zfs_do_holds(int argc, char **argv)
5578 int errors = 0;
5579 int c;
5580 int i;
5581 boolean_t scripted = B_FALSE;
5582 boolean_t recursive = B_FALSE;
5583 const char *opts = "rH";
5584 nvlist_t *nvl;
5586 int types = ZFS_TYPE_SNAPSHOT;
5587 holds_cbdata_t cb = { 0 };
5589 int limit = 0;
5590 int ret = 0;
5591 int flags = 0;
5593 /* check options */
5594 while ((c = getopt(argc, argv, opts)) != -1) {
5595 switch (c) {
5596 case 'r':
5597 recursive = B_TRUE;
5598 break;
5599 case 'H':
5600 scripted = B_TRUE;
5601 break;
5602 case '?':
5603 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5604 optopt);
5605 usage(B_FALSE);
5609 if (recursive) {
5610 types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
5611 flags |= ZFS_ITER_RECURSE;
5614 argc -= optind;
5615 argv += optind;
5617 /* check number of arguments */
5618 if (argc < 1)
5619 usage(B_FALSE);
5621 if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5622 nomem();
5624 for (i = 0; i < argc; ++i) {
5625 char *snapshot = argv[i];
5626 const char *delim;
5627 const char *snapname;
5629 delim = strchr(snapshot, '@');
5630 if (delim == NULL) {
5631 (void) fprintf(stderr,
5632 gettext("'%s' is not a snapshot\n"), snapshot);
5633 ++errors;
5634 continue;
5636 snapname = delim + 1;
5637 if (recursive)
5638 snapshot[delim - snapshot] = '\0';
5640 cb.cb_recursive = recursive;
5641 cb.cb_snapname = snapname;
5642 cb.cb_nvlp = &nvl;
5645 * 1. collect holds data, set format options
5647 ret = zfs_for_each(argc, argv, flags, types, NULL, NULL, limit,
5648 holds_callback, &cb);
5649 if (ret != 0)
5650 ++errors;
5654 * 2. print holds data
5656 print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl);
5658 if (nvlist_empty(nvl))
5659 (void) printf(gettext("no datasets available\n"));
5661 nvlist_free(nvl);
5663 return (0 != errors);
5666 #define CHECK_SPINNER 30
5667 #define SPINNER_TIME 3 /* seconds */
5668 #define MOUNT_TIME 5 /* seconds */
5670 static int
5671 get_one_dataset(zfs_handle_t *zhp, void *data)
5673 static char *spin[] = { "-", "\\", "|", "/" };
5674 static int spinval = 0;
5675 static int spincheck = 0;
5676 static time_t last_spin_time = (time_t)0;
5677 get_all_cb_t *cbp = data;
5678 zfs_type_t type = zfs_get_type(zhp);
5680 if (cbp->cb_verbose) {
5681 if (--spincheck < 0) {
5682 time_t now = time(NULL);
5683 if (last_spin_time + SPINNER_TIME < now) {
5684 update_progress(spin[spinval++ % 4]);
5685 last_spin_time = now;
5687 spincheck = CHECK_SPINNER;
5692 * Interate over any nested datasets.
5694 if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
5695 zfs_close(zhp);
5696 return (1);
5700 * Skip any datasets whose type does not match.
5702 if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
5703 zfs_close(zhp);
5704 return (0);
5706 libzfs_add_handle(cbp, zhp);
5707 assert(cbp->cb_used <= cbp->cb_alloc);
5709 return (0);
5712 static void
5713 get_all_datasets(zfs_handle_t ***dslist, size_t *count, boolean_t verbose)
5715 get_all_cb_t cb = { 0 };
5716 cb.cb_verbose = verbose;
5717 cb.cb_getone = get_one_dataset;
5719 if (verbose)
5720 set_progress_header(gettext("Reading ZFS config"));
5721 (void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
5723 *dslist = cb.cb_handles;
5724 *count = cb.cb_used;
5726 if (verbose)
5727 finish_progress(gettext("done."));
5731 * Generic callback for sharing or mounting filesystems. Because the code is so
5732 * similar, we have a common function with an extra parameter to determine which
5733 * mode we are using.
5735 #define OP_SHARE 0x1
5736 #define OP_MOUNT 0x2
5739 * Share or mount a dataset.
5741 static int
5742 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
5743 boolean_t explicit, const char *options)
5745 char mountpoint[ZFS_MAXPROPLEN];
5746 char shareopts[ZFS_MAXPROPLEN];
5747 char smbshareopts[ZFS_MAXPROPLEN];
5748 const char *cmdname = op == OP_SHARE ? "share" : "mount";
5749 struct mnttab mnt;
5750 uint64_t zoned, canmount;
5751 boolean_t shared_nfs, shared_smb;
5753 assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
5756 * Check to make sure we can mount/share this dataset. If we
5757 * are in the global zone and the filesystem is exported to a
5758 * local zone, or if we are in a local zone and the
5759 * filesystem is not exported, then it is an error.
5761 zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
5763 if (zoned && getzoneid() == GLOBAL_ZONEID) {
5764 if (!explicit)
5765 return (0);
5767 (void) fprintf(stderr, gettext("cannot %s '%s': "
5768 "dataset is exported to a local zone\n"), cmdname,
5769 zfs_get_name(zhp));
5770 return (1);
5772 } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
5773 if (!explicit)
5774 return (0);
5776 (void) fprintf(stderr, gettext("cannot %s '%s': "
5777 "permission denied\n"), cmdname,
5778 zfs_get_name(zhp));
5779 return (1);
5783 * Ignore any filesystems which don't apply to us. This
5784 * includes those with a legacy mountpoint, or those with
5785 * legacy share options.
5787 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
5788 sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
5789 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
5790 sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
5791 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
5792 sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
5794 if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
5795 strcmp(smbshareopts, "off") == 0) {
5796 if (!explicit)
5797 return (0);
5799 (void) fprintf(stderr, gettext("cannot share '%s': "
5800 "legacy share\n"), zfs_get_name(zhp));
5801 (void) fprintf(stderr, gettext("use share(1M) to "
5802 "share this filesystem, or set "
5803 "sharenfs property on\n"));
5804 return (1);
5808 * We cannot share or mount legacy filesystems. If the
5809 * shareopts is non-legacy but the mountpoint is legacy, we
5810 * treat it as a legacy share.
5812 if (strcmp(mountpoint, "legacy") == 0) {
5813 if (!explicit)
5814 return (0);
5816 (void) fprintf(stderr, gettext("cannot %s '%s': "
5817 "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
5818 (void) fprintf(stderr, gettext("use %s(1M) to "
5819 "%s this filesystem\n"), cmdname, cmdname);
5820 return (1);
5823 if (strcmp(mountpoint, "none") == 0) {
5824 if (!explicit)
5825 return (0);
5827 (void) fprintf(stderr, gettext("cannot %s '%s': no "
5828 "mountpoint set\n"), cmdname, zfs_get_name(zhp));
5829 return (1);
5833 * canmount explicit outcome
5834 * on no pass through
5835 * on yes pass through
5836 * off no return 0
5837 * off yes display error, return 1
5838 * noauto no return 0
5839 * noauto yes pass through
5841 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
5842 if (canmount == ZFS_CANMOUNT_OFF) {
5843 if (!explicit)
5844 return (0);
5846 (void) fprintf(stderr, gettext("cannot %s '%s': "
5847 "'canmount' property is set to 'off'\n"), cmdname,
5848 zfs_get_name(zhp));
5849 return (1);
5850 } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
5851 return (0);
5855 * If this filesystem is inconsistent and has a receive resume
5856 * token, we can not mount it.
5858 if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) &&
5859 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
5860 NULL, 0, NULL, NULL, 0, B_TRUE) == 0) {
5861 if (!explicit)
5862 return (0);
5864 (void) fprintf(stderr, gettext("cannot %s '%s': "
5865 "Contains partially-completed state from "
5866 "\"zfs receive -r\", which can be resumed with "
5867 "\"zfs send -t\"\n"),
5868 cmdname, zfs_get_name(zhp));
5869 return (1);
5873 * At this point, we have verified that the mountpoint and/or
5874 * shareopts are appropriate for auto management. If the
5875 * filesystem is already mounted or shared, return (failing
5876 * for explicit requests); otherwise mount or share the
5877 * filesystem.
5879 switch (op) {
5880 case OP_SHARE:
5882 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
5883 shared_smb = zfs_is_shared_smb(zhp, NULL);
5885 if ((shared_nfs && shared_smb) ||
5886 (shared_nfs && strcmp(shareopts, "on") == 0 &&
5887 strcmp(smbshareopts, "off") == 0) ||
5888 (shared_smb && strcmp(smbshareopts, "on") == 0 &&
5889 strcmp(shareopts, "off") == 0)) {
5890 if (!explicit)
5891 return (0);
5893 (void) fprintf(stderr, gettext("cannot share "
5894 "'%s': filesystem already shared\n"),
5895 zfs_get_name(zhp));
5896 return (1);
5899 if (!zfs_is_mounted(zhp, NULL) &&
5900 zfs_mount(zhp, NULL, 0) != 0)
5901 return (1);
5903 if (protocol == NULL) {
5904 if (zfs_shareall(zhp) != 0)
5905 return (1);
5906 } else if (strcmp(protocol, "nfs") == 0) {
5907 if (zfs_share_nfs(zhp))
5908 return (1);
5909 } else if (strcmp(protocol, "smb") == 0) {
5910 if (zfs_share_smb(zhp))
5911 return (1);
5912 } else {
5913 (void) fprintf(stderr, gettext("cannot share "
5914 "'%s': invalid share type '%s' "
5915 "specified\n"),
5916 zfs_get_name(zhp), protocol);
5917 return (1);
5920 break;
5922 case OP_MOUNT:
5923 if (options == NULL)
5924 mnt.mnt_mntopts = "";
5925 else
5926 mnt.mnt_mntopts = (char *)options;
5928 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
5929 zfs_is_mounted(zhp, NULL)) {
5930 if (!explicit)
5931 return (0);
5933 (void) fprintf(stderr, gettext("cannot mount "
5934 "'%s': filesystem already mounted\n"),
5935 zfs_get_name(zhp));
5936 return (1);
5939 if (zfs_mount(zhp, options, flags) != 0)
5940 return (1);
5941 break;
5944 return (0);
5948 * Reports progress in the form "(current/total)". Not thread-safe.
5950 static void
5951 report_mount_progress(int current, int total)
5953 static time_t last_progress_time = 0;
5954 time_t now = time(NULL);
5955 char info[32];
5957 /* report 1..n instead of 0..n-1 */
5958 ++current;
5960 /* display header if we're here for the first time */
5961 if (current == 1) {
5962 set_progress_header(gettext("Mounting ZFS filesystems"));
5963 } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
5964 /* too soon to report again */
5965 return;
5968 last_progress_time = now;
5970 (void) sprintf(info, "(%d/%d)", current, total);
5972 if (current == total)
5973 finish_progress(info);
5974 else
5975 update_progress(info);
5978 static void
5979 append_options(char *mntopts, char *newopts)
5981 int len = strlen(mntopts);
5983 /* original length plus new string to append plus 1 for the comma */
5984 if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
5985 (void) fprintf(stderr, gettext("the opts argument for "
5986 "'%c' option is too long (more than %d chars)\n"),
5987 "-o", MNT_LINE_MAX);
5988 usage(B_FALSE);
5991 if (*mntopts)
5992 mntopts[len++] = ',';
5994 (void) strcpy(&mntopts[len], newopts);
5997 static int
5998 share_mount(int op, int argc, char **argv)
6000 int do_all = 0;
6001 boolean_t verbose = B_FALSE;
6002 int c, ret = 0;
6003 char *options = NULL;
6004 int flags = 0;
6006 /* check options */
6007 while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
6008 != -1) {
6009 switch (c) {
6010 case 'a':
6011 do_all = 1;
6012 break;
6013 case 'v':
6014 verbose = B_TRUE;
6015 break;
6016 case 'o':
6017 if (*optarg == '\0') {
6018 (void) fprintf(stderr, gettext("empty mount "
6019 "options (-o) specified\n"));
6020 usage(B_FALSE);
6023 if (options == NULL)
6024 options = safe_malloc(MNT_LINE_MAX + 1);
6026 /* option validation is done later */
6027 append_options(options, optarg);
6028 break;
6030 case 'O':
6031 flags |= MS_OVERLAY;
6032 break;
6033 case ':':
6034 (void) fprintf(stderr, gettext("missing argument for "
6035 "'%c' option\n"), optopt);
6036 usage(B_FALSE);
6037 break;
6038 case '?':
6039 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6040 optopt);
6041 usage(B_FALSE);
6045 argc -= optind;
6046 argv += optind;
6048 /* check number of arguments */
6049 if (do_all) {
6050 zfs_handle_t **dslist = NULL;
6051 size_t i, count = 0;
6052 char *protocol = NULL;
6054 if (op == OP_SHARE && argc > 0) {
6055 if (strcmp(argv[0], "nfs") != 0 &&
6056 strcmp(argv[0], "smb") != 0) {
6057 (void) fprintf(stderr, gettext("share type "
6058 "must be 'nfs' or 'smb'\n"));
6059 usage(B_FALSE);
6061 protocol = argv[0];
6062 argc--;
6063 argv++;
6066 if (argc != 0) {
6067 (void) fprintf(stderr, gettext("too many arguments\n"));
6068 usage(B_FALSE);
6071 start_progress_timer();
6072 get_all_datasets(&dslist, &count, verbose);
6074 if (count == 0)
6075 return (0);
6077 qsort(dslist, count, sizeof (void *), libzfs_dataset_cmp);
6079 for (i = 0; i < count; i++) {
6080 if (verbose)
6081 report_mount_progress(i, count);
6083 if (share_mount_one(dslist[i], op, flags, protocol,
6084 B_FALSE, options) != 0)
6085 ret = 1;
6086 zfs_close(dslist[i]);
6089 free(dslist);
6090 } else if (argc == 0) {
6091 struct mnttab entry;
6093 if ((op == OP_SHARE) || (options != NULL)) {
6094 (void) fprintf(stderr, gettext("missing filesystem "
6095 "argument (specify -a for all)\n"));
6096 usage(B_FALSE);
6100 * When mount is given no arguments, go through /etc/mnttab and
6101 * display any active ZFS mounts. We hide any snapshots, since
6102 * they are controlled automatically.
6104 rewind(mnttab_file);
6105 while (getmntent(mnttab_file, &entry) == 0) {
6106 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
6107 strchr(entry.mnt_special, '@') != NULL)
6108 continue;
6110 (void) printf("%-30s %s\n", entry.mnt_special,
6111 entry.mnt_mountp);
6114 } else {
6115 zfs_handle_t *zhp;
6117 if (argc > 1) {
6118 (void) fprintf(stderr,
6119 gettext("too many arguments\n"));
6120 usage(B_FALSE);
6123 if ((zhp = zfs_open(g_zfs, argv[0],
6124 ZFS_TYPE_FILESYSTEM)) == NULL) {
6125 ret = 1;
6126 } else {
6127 ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
6128 options);
6129 zfs_close(zhp);
6133 return (ret);
6137 * zfs mount -a [nfs]
6138 * zfs mount filesystem
6140 * Mount all filesystems, or mount the given filesystem.
6142 static int
6143 zfs_do_mount(int argc, char **argv)
6145 return (share_mount(OP_MOUNT, argc, argv));
6149 * zfs share -a [nfs | smb]
6150 * zfs share filesystem
6152 * Share all filesystems, or share the given filesystem.
6154 static int
6155 zfs_do_share(int argc, char **argv)
6157 return (share_mount(OP_SHARE, argc, argv));
6160 typedef struct unshare_unmount_node {
6161 zfs_handle_t *un_zhp;
6162 char *un_mountp;
6163 uu_avl_node_t un_avlnode;
6164 } unshare_unmount_node_t;
6166 /* ARGSUSED */
6167 static int
6168 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
6170 const unshare_unmount_node_t *l = larg;
6171 const unshare_unmount_node_t *r = rarg;
6173 return (strcmp(l->un_mountp, r->un_mountp));
6177 * Convenience routine used by zfs_do_umount() and manual_unmount(). Given an
6178 * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
6179 * and unmount it appropriately.
6181 static int
6182 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
6184 zfs_handle_t *zhp;
6185 int ret = 0;
6186 struct stat64 statbuf;
6187 struct extmnttab entry;
6188 const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
6189 ino_t path_inode;
6192 * Search for the path in /etc/mnttab. Rather than looking for the
6193 * specific path, which can be fooled by non-standard paths (i.e. ".."
6194 * or "//"), we stat() the path and search for the corresponding
6195 * (major,minor) device pair.
6197 if (stat64(path, &statbuf) != 0) {
6198 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6199 cmdname, path, strerror(errno));
6200 return (1);
6202 path_inode = statbuf.st_ino;
6205 * Search for the given (major,minor) pair in the mount table.
6207 rewind(mnttab_file);
6208 while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
6209 if (entry.mnt_major == major(statbuf.st_dev) &&
6210 entry.mnt_minor == minor(statbuf.st_dev))
6211 break;
6213 if (ret != 0) {
6214 if (op == OP_SHARE) {
6215 (void) fprintf(stderr, gettext("cannot %s '%s': not "
6216 "currently mounted\n"), cmdname, path);
6217 return (1);
6219 (void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
6220 path);
6221 if ((ret = umount2(path, flags)) != 0)
6222 (void) fprintf(stderr, gettext("%s: %s\n"), path,
6223 strerror(errno));
6224 return (ret != 0);
6227 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
6228 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
6229 "filesystem\n"), cmdname, path);
6230 return (1);
6233 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6234 ZFS_TYPE_FILESYSTEM)) == NULL)
6235 return (1);
6237 ret = 1;
6238 if (stat64(entry.mnt_mountp, &statbuf) != 0) {
6239 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6240 cmdname, path, strerror(errno));
6241 goto out;
6242 } else if (statbuf.st_ino != path_inode) {
6243 (void) fprintf(stderr, gettext("cannot "
6244 "%s '%s': not a mountpoint\n"), cmdname, path);
6245 goto out;
6248 if (op == OP_SHARE) {
6249 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6250 char smbshare_prop[ZFS_MAXPROPLEN];
6252 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
6253 sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
6254 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
6255 sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
6257 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6258 strcmp(smbshare_prop, "off") == 0) {
6259 (void) fprintf(stderr, gettext("cannot unshare "
6260 "'%s': legacy share\n"), path);
6261 (void) fprintf(stderr, gettext("use "
6262 "unshare(1M) to unshare this filesystem\n"));
6263 } else if (!zfs_is_shared(zhp)) {
6264 (void) fprintf(stderr, gettext("cannot unshare '%s': "
6265 "not currently shared\n"), path);
6266 } else {
6267 ret = zfs_unshareall_bypath(zhp, path);
6269 } else {
6270 char mtpt_prop[ZFS_MAXPROPLEN];
6272 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
6273 sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
6275 if (is_manual) {
6276 ret = zfs_unmount(zhp, NULL, flags);
6277 } else if (strcmp(mtpt_prop, "legacy") == 0) {
6278 (void) fprintf(stderr, gettext("cannot unmount "
6279 "'%s': legacy mountpoint\n"),
6280 zfs_get_name(zhp));
6281 (void) fprintf(stderr, gettext("use umount(1M) "
6282 "to unmount this filesystem\n"));
6283 } else {
6284 ret = zfs_unmountall(zhp, flags);
6288 out:
6289 zfs_close(zhp);
6291 return (ret != 0);
6295 * Generic callback for unsharing or unmounting a filesystem.
6297 static int
6298 unshare_unmount(int op, int argc, char **argv)
6300 int do_all = 0;
6301 int flags = 0;
6302 int ret = 0;
6303 int c;
6304 zfs_handle_t *zhp;
6305 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6306 char sharesmb[ZFS_MAXPROPLEN];
6308 /* check options */
6309 while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
6310 switch (c) {
6311 case 'a':
6312 do_all = 1;
6313 break;
6314 case 'f':
6315 flags = MS_FORCE;
6316 break;
6317 case '?':
6318 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6319 optopt);
6320 usage(B_FALSE);
6324 argc -= optind;
6325 argv += optind;
6327 if (do_all) {
6329 * We could make use of zfs_for_each() to walk all datasets in
6330 * the system, but this would be very inefficient, especially
6331 * since we would have to linearly search /etc/mnttab for each
6332 * one. Instead, do one pass through /etc/mnttab looking for
6333 * zfs entries and call zfs_unmount() for each one.
6335 * Things get a little tricky if the administrator has created
6336 * mountpoints beneath other ZFS filesystems. In this case, we
6337 * have to unmount the deepest filesystems first. To accomplish
6338 * this, we place all the mountpoints in an AVL tree sorted by
6339 * the special type (dataset name), and walk the result in
6340 * reverse to make sure to get any snapshots first.
6342 struct mnttab entry;
6343 uu_avl_pool_t *pool;
6344 uu_avl_t *tree = NULL;
6345 unshare_unmount_node_t *node;
6346 uu_avl_index_t idx;
6347 uu_avl_walk_t *walk;
6349 if (argc != 0) {
6350 (void) fprintf(stderr, gettext("too many arguments\n"));
6351 usage(B_FALSE);
6354 if (((pool = uu_avl_pool_create("unmount_pool",
6355 sizeof (unshare_unmount_node_t),
6356 offsetof(unshare_unmount_node_t, un_avlnode),
6357 unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
6358 ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
6359 nomem();
6361 rewind(mnttab_file);
6362 while (getmntent(mnttab_file, &entry) == 0) {
6364 /* ignore non-ZFS entries */
6365 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
6366 continue;
6368 /* ignore snapshots */
6369 if (strchr(entry.mnt_special, '@') != NULL)
6370 continue;
6372 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6373 ZFS_TYPE_FILESYSTEM)) == NULL) {
6374 ret = 1;
6375 continue;
6379 * Ignore datasets that are excluded/restricted by
6380 * parent pool name.
6382 if (zpool_skip_pool(zfs_get_pool_name(zhp))) {
6383 zfs_close(zhp);
6384 continue;
6387 switch (op) {
6388 case OP_SHARE:
6389 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6390 nfs_mnt_prop,
6391 sizeof (nfs_mnt_prop),
6392 NULL, NULL, 0, B_FALSE) == 0);
6393 if (strcmp(nfs_mnt_prop, "off") != 0)
6394 break;
6395 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6396 nfs_mnt_prop,
6397 sizeof (nfs_mnt_prop),
6398 NULL, NULL, 0, B_FALSE) == 0);
6399 if (strcmp(nfs_mnt_prop, "off") == 0)
6400 continue;
6401 break;
6402 case OP_MOUNT:
6403 /* Ignore legacy mounts */
6404 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
6405 nfs_mnt_prop,
6406 sizeof (nfs_mnt_prop),
6407 NULL, NULL, 0, B_FALSE) == 0);
6408 if (strcmp(nfs_mnt_prop, "legacy") == 0)
6409 continue;
6410 /* Ignore canmount=noauto mounts */
6411 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
6412 ZFS_CANMOUNT_NOAUTO)
6413 continue;
6414 default:
6415 break;
6418 node = safe_malloc(sizeof (unshare_unmount_node_t));
6419 node->un_zhp = zhp;
6420 node->un_mountp = safe_strdup(entry.mnt_mountp);
6422 uu_avl_node_init(node, &node->un_avlnode, pool);
6424 if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
6425 uu_avl_insert(tree, node, idx);
6426 } else {
6427 zfs_close(node->un_zhp);
6428 free(node->un_mountp);
6429 free(node);
6434 * Walk the AVL tree in reverse, unmounting each filesystem and
6435 * removing it from the AVL tree in the process.
6437 if ((walk = uu_avl_walk_start(tree,
6438 UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
6439 nomem();
6441 while ((node = uu_avl_walk_next(walk)) != NULL) {
6442 uu_avl_remove(tree, node);
6444 switch (op) {
6445 case OP_SHARE:
6446 if (zfs_unshareall_bypath(node->un_zhp,
6447 node->un_mountp) != 0)
6448 ret = 1;
6449 break;
6451 case OP_MOUNT:
6452 if (zfs_unmount(node->un_zhp,
6453 node->un_mountp, flags) != 0)
6454 ret = 1;
6455 break;
6458 zfs_close(node->un_zhp);
6459 free(node->un_mountp);
6460 free(node);
6463 uu_avl_walk_end(walk);
6464 uu_avl_destroy(tree);
6465 uu_avl_pool_destroy(pool);
6467 } else {
6468 if (argc != 1) {
6469 if (argc == 0)
6470 (void) fprintf(stderr,
6471 gettext("missing filesystem argument\n"));
6472 else
6473 (void) fprintf(stderr,
6474 gettext("too many arguments\n"));
6475 usage(B_FALSE);
6479 * We have an argument, but it may be a full path or a ZFS
6480 * filesystem. Pass full paths off to unmount_path() (shared by
6481 * manual_unmount), otherwise open the filesystem and pass to
6482 * zfs_unmount().
6484 if (argv[0][0] == '/')
6485 return (unshare_unmount_path(op, argv[0],
6486 flags, B_FALSE));
6488 if ((zhp = zfs_open(g_zfs, argv[0],
6489 ZFS_TYPE_FILESYSTEM)) == NULL)
6490 return (1);
6492 verify(zfs_prop_get(zhp, op == OP_SHARE ?
6493 ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
6494 nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
6495 NULL, 0, B_FALSE) == 0);
6497 switch (op) {
6498 case OP_SHARE:
6499 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6500 nfs_mnt_prop,
6501 sizeof (nfs_mnt_prop),
6502 NULL, NULL, 0, B_FALSE) == 0);
6503 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6504 sharesmb, sizeof (sharesmb), NULL, NULL,
6505 0, B_FALSE) == 0);
6507 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6508 strcmp(sharesmb, "off") == 0) {
6509 (void) fprintf(stderr, gettext("cannot "
6510 "unshare '%s': legacy share\n"),
6511 zfs_get_name(zhp));
6512 (void) fprintf(stderr, gettext("use "
6513 "unshare(1M) to unshare this "
6514 "filesystem\n"));
6515 ret = 1;
6516 } else if (!zfs_is_shared(zhp)) {
6517 (void) fprintf(stderr, gettext("cannot "
6518 "unshare '%s': not currently "
6519 "shared\n"), zfs_get_name(zhp));
6520 ret = 1;
6521 } else if (zfs_unshareall(zhp) != 0) {
6522 ret = 1;
6524 break;
6526 case OP_MOUNT:
6527 if (strcmp(nfs_mnt_prop, "legacy") == 0) {
6528 (void) fprintf(stderr, gettext("cannot "
6529 "unmount '%s': legacy "
6530 "mountpoint\n"), zfs_get_name(zhp));
6531 (void) fprintf(stderr, gettext("use "
6532 "umount(1M) to unmount this "
6533 "filesystem\n"));
6534 ret = 1;
6535 } else if (!zfs_is_mounted(zhp, NULL)) {
6536 (void) fprintf(stderr, gettext("cannot "
6537 "unmount '%s': not currently "
6538 "mounted\n"),
6539 zfs_get_name(zhp));
6540 ret = 1;
6541 } else if (zfs_unmountall(zhp, flags) != 0) {
6542 ret = 1;
6544 break;
6547 zfs_close(zhp);
6550 return (ret);
6554 * zfs unmount -a
6555 * zfs unmount filesystem
6557 * Unmount all filesystems, or a specific ZFS filesystem.
6559 static int
6560 zfs_do_unmount(int argc, char **argv)
6562 return (unshare_unmount(OP_MOUNT, argc, argv));
6566 * zfs unshare -a
6567 * zfs unshare filesystem
6569 * Unshare all filesystems, or a specific ZFS filesystem.
6571 static int
6572 zfs_do_unshare(int argc, char **argv)
6574 return (unshare_unmount(OP_SHARE, argc, argv));
6578 * Called when invoked as /etc/fs/zfs/mount. Do the mount if the mountpoint is
6579 * 'legacy'. Otherwise, complain that use should be using 'zfs mount'.
6581 static int
6582 manual_mount(int argc, char **argv)
6584 zfs_handle_t *zhp;
6585 char mountpoint[ZFS_MAXPROPLEN];
6586 char mntopts[MNT_LINE_MAX] = { '\0' };
6587 int ret = 0;
6588 int c;
6589 int flags = 0;
6590 char *dataset, *path;
6592 /* check options */
6593 while ((c = getopt(argc, argv, ":mo:O")) != -1) {
6594 switch (c) {
6595 case 'o':
6596 (void) strlcpy(mntopts, optarg, sizeof (mntopts));
6597 break;
6598 case 'O':
6599 flags |= MS_OVERLAY;
6600 break;
6601 case 'm':
6602 flags |= MS_NOMNTTAB;
6603 break;
6604 case ':':
6605 (void) fprintf(stderr, gettext("missing argument for "
6606 "'%c' option\n"), optopt);
6607 usage(B_FALSE);
6608 break;
6609 case '?':
6610 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6611 optopt);
6612 (void) fprintf(stderr, gettext("usage: mount [-o opts] "
6613 "<path>\n"));
6614 return (2);
6618 argc -= optind;
6619 argv += optind;
6621 /* check that we only have two arguments */
6622 if (argc != 2) {
6623 if (argc == 0)
6624 (void) fprintf(stderr, gettext("missing dataset "
6625 "argument\n"));
6626 else if (argc == 1)
6627 (void) fprintf(stderr,
6628 gettext("missing mountpoint argument\n"));
6629 else
6630 (void) fprintf(stderr, gettext("too many arguments\n"));
6631 (void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
6632 return (2);
6635 dataset = argv[0];
6636 path = argv[1];
6638 /* try to open the dataset */
6639 if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
6640 return (1);
6642 (void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
6643 sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
6645 /* check for legacy mountpoint and complain appropriately */
6646 ret = 0;
6647 if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
6648 if (mount(dataset, path, MS_OPTIONSTR | flags, MNTTYPE_ZFS,
6649 NULL, 0, mntopts, sizeof (mntopts)) != 0) {
6650 (void) fprintf(stderr, gettext("mount failed: %s\n"),
6651 strerror(errno));
6652 ret = 1;
6654 } else {
6655 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
6656 "mounted using 'mount -F zfs'\n"), dataset);
6657 (void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
6658 "instead.\n"), path);
6659 (void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
6660 "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
6661 (void) fprintf(stderr, gettext("See zfs(1M) for more "
6662 "information.\n"));
6663 ret = 1;
6666 return (ret);
6670 * Called when invoked as /etc/fs/zfs/umount. Unlike a manual mount, we allow
6671 * unmounts of non-legacy filesystems, as this is the dominant administrative
6672 * interface.
6674 static int
6675 manual_unmount(int argc, char **argv)
6677 int flags = 0;
6678 int c;
6680 /* check options */
6681 while ((c = getopt(argc, argv, "f")) != -1) {
6682 switch (c) {
6683 case 'f':
6684 flags = MS_FORCE;
6685 break;
6686 case '?':
6687 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6688 optopt);
6689 (void) fprintf(stderr, gettext("usage: unmount [-f] "
6690 "<path>\n"));
6691 return (2);
6695 argc -= optind;
6696 argv += optind;
6698 /* check arguments */
6699 if (argc != 1) {
6700 if (argc == 0)
6701 (void) fprintf(stderr, gettext("missing path "
6702 "argument\n"));
6703 else
6704 (void) fprintf(stderr, gettext("too many arguments\n"));
6705 (void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
6706 return (2);
6709 return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
6712 static int
6713 find_command_idx(char *command, int *idx)
6715 int i;
6717 for (i = 0; i < NCOMMAND; i++) {
6718 if (command_table[i].name == NULL)
6719 continue;
6721 if (strcmp(command, command_table[i].name) == 0) {
6722 *idx = i;
6723 return (0);
6726 return (1);
6729 static int
6730 zfs_do_diff(int argc, char **argv)
6732 zfs_handle_t *zhp;
6733 int flags = 0;
6734 char *tosnap = NULL;
6735 char *fromsnap = NULL;
6736 char *atp, *copy;
6737 int err = 0;
6738 int c;
6740 while ((c = getopt(argc, argv, "FHt")) != -1) {
6741 switch (c) {
6742 case 'F':
6743 flags |= ZFS_DIFF_CLASSIFY;
6744 break;
6745 case 'H':
6746 flags |= ZFS_DIFF_PARSEABLE;
6747 break;
6748 case 't':
6749 flags |= ZFS_DIFF_TIMESTAMP;
6750 break;
6751 default:
6752 (void) fprintf(stderr,
6753 gettext("invalid option '%c'\n"), optopt);
6754 usage(B_FALSE);
6758 argc -= optind;
6759 argv += optind;
6761 if (argc < 1) {
6762 (void) fprintf(stderr,
6763 gettext("must provide at least one snapshot name\n"));
6764 usage(B_FALSE);
6767 if (argc > 2) {
6768 (void) fprintf(stderr, gettext("too many arguments\n"));
6769 usage(B_FALSE);
6772 fromsnap = argv[0];
6773 tosnap = (argc == 2) ? argv[1] : NULL;
6775 copy = NULL;
6776 if (*fromsnap != '@')
6777 copy = strdup(fromsnap);
6778 else if (tosnap)
6779 copy = strdup(tosnap);
6780 if (copy == NULL)
6781 usage(B_FALSE);
6783 if ((atp = strchr(copy, '@')) != NULL)
6784 *atp = '\0';
6786 if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
6787 return (1);
6789 free(copy);
6792 * Ignore SIGPIPE so that the library can give us
6793 * information on any failure
6795 (void) sigignore(SIGPIPE);
6797 err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
6799 zfs_close(zhp);
6801 return (err != 0);
6805 * zfs bookmark <fs@snap> <fs#bmark>
6807 * Creates a bookmark with the given name from the given snapshot.
6809 static int
6810 zfs_do_bookmark(int argc, char **argv)
6812 char snapname[ZFS_MAXNAMELEN];
6813 zfs_handle_t *zhp;
6814 nvlist_t *nvl;
6815 int ret = 0;
6816 int c;
6818 /* check options */
6819 while ((c = getopt(argc, argv, "")) != -1) {
6820 switch (c) {
6821 case '?':
6822 (void) fprintf(stderr,
6823 gettext("invalid option '%c'\n"), optopt);
6824 goto usage;
6828 argc -= optind;
6829 argv += optind;
6831 /* check number of arguments */
6832 if (argc < 1) {
6833 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
6834 goto usage;
6836 if (argc < 2) {
6837 (void) fprintf(stderr, gettext("missing bookmark argument\n"));
6838 goto usage;
6841 if (strchr(argv[1], '#') == NULL) {
6842 (void) fprintf(stderr,
6843 gettext("invalid bookmark name '%s' -- "
6844 "must contain a '#'\n"), argv[1]);
6845 goto usage;
6848 if (argv[0][0] == '@') {
6850 * Snapshot name begins with @.
6851 * Default to same fs as bookmark.
6853 (void) strncpy(snapname, argv[1], sizeof (snapname));
6854 *strchr(snapname, '#') = '\0';
6855 (void) strlcat(snapname, argv[0], sizeof (snapname));
6856 } else {
6857 (void) strncpy(snapname, argv[0], sizeof (snapname));
6859 zhp = zfs_open(g_zfs, snapname, ZFS_TYPE_SNAPSHOT);
6860 if (zhp == NULL)
6861 goto usage;
6862 zfs_close(zhp);
6865 nvl = fnvlist_alloc();
6866 fnvlist_add_string(nvl, argv[1], snapname);
6867 ret = lzc_bookmark(nvl, NULL);
6868 fnvlist_free(nvl);
6870 if (ret != 0) {
6871 const char *err_msg;
6872 char errbuf[1024];
6874 (void) snprintf(errbuf, sizeof (errbuf),
6875 dgettext(TEXT_DOMAIN,
6876 "cannot create bookmark '%s'"), argv[1]);
6878 switch (ret) {
6879 case EXDEV:
6880 err_msg = "bookmark is in a different pool";
6881 break;
6882 case EEXIST:
6883 err_msg = "bookmark exists";
6884 break;
6885 case EINVAL:
6886 err_msg = "invalid argument";
6887 break;
6888 case ENOTSUP:
6889 err_msg = "bookmark feature not enabled";
6890 break;
6891 case ENOSPC:
6892 err_msg = "out of space";
6893 break;
6894 default:
6895 err_msg = "unknown error";
6896 break;
6898 (void) fprintf(stderr, "%s: %s\n", errbuf,
6899 dgettext(TEXT_DOMAIN, err_msg));
6902 return (ret != 0);
6904 usage:
6905 usage(B_FALSE);
6906 return (-1);
6910 main(int argc, char **argv)
6912 int ret = 0;
6913 int i;
6914 char *progname;
6915 char *cmdname;
6917 (void) setlocale(LC_ALL, "");
6918 (void) textdomain(TEXT_DOMAIN);
6920 opterr = 0;
6922 if ((g_zfs = libzfs_init()) == NULL) {
6923 (void) fprintf(stderr, gettext("internal error: failed to "
6924 "initialize ZFS library\n"));
6925 return (1);
6928 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
6930 libzfs_print_on_error(g_zfs, B_TRUE);
6932 if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
6933 (void) fprintf(stderr, gettext("internal error: unable to "
6934 "open %s\n"), MNTTAB);
6935 return (1);
6939 * This command also doubles as the /etc/fs mount and unmount program.
6940 * Determine if we should take this behavior based on argv[0].
6942 progname = basename(argv[0]);
6943 if (strcmp(progname, "mount") == 0) {
6944 ret = manual_mount(argc, argv);
6945 } else if (strcmp(progname, "umount") == 0) {
6946 ret = manual_unmount(argc, argv);
6947 } else {
6949 * Make sure the user has specified some command.
6951 if (argc < 2) {
6952 (void) fprintf(stderr, gettext("missing command\n"));
6953 usage(B_FALSE);
6956 cmdname = argv[1];
6959 * The 'umount' command is an alias for 'unmount'
6961 if (strcmp(cmdname, "umount") == 0)
6962 cmdname = "unmount";
6965 * The 'recv' command is an alias for 'receive'
6967 if (strcmp(cmdname, "recv") == 0)
6968 cmdname = "receive";
6971 * The 'snap' command is an alias for 'snapshot'
6973 if (strcmp(cmdname, "snap") == 0)
6974 cmdname = "snapshot";
6977 * Special case '-?'
6979 if (strcmp(cmdname, "-?") == 0)
6980 usage(B_TRUE);
6983 * Run the appropriate command.
6985 libzfs_mnttab_cache(g_zfs, B_TRUE);
6986 if (find_command_idx(cmdname, &i) == 0) {
6987 current_command = &command_table[i];
6988 ret = command_table[i].func(argc - 1, argv + 1);
6989 } else if (strchr(cmdname, '=') != NULL) {
6990 verify(find_command_idx("set", &i) == 0);
6991 current_command = &command_table[i];
6992 ret = command_table[i].func(argc, argv);
6993 } else {
6994 (void) fprintf(stderr, gettext("unrecognized "
6995 "command '%s'\n"), cmdname);
6996 usage(B_FALSE);
6998 libzfs_mnttab_cache(g_zfs, B_FALSE);
7001 (void) fclose(mnttab_file);
7003 if (ret == 0 && log_history)
7004 (void) zpool_log_history(g_zfs, history_str);
7006 libzfs_fini(g_zfs);
7009 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
7010 * for the purposes of running ::findleaks.
7012 if (getenv("ZFS_ABORT") != NULL) {
7013 (void) printf("dumping core by request\n");
7014 abort();
7017 return (ret);