6298 zfs_create_008_neg and zpool_create_023_neg need to be updated for large block...
[unleashed.git] / usr / src / cmd / zfs / zfs_main.c
blobc7de0013eff5f5f68fb5a0a5c79c73407a78ff0b
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 2013 Nexenta Systems, Inc. All rights reserved.
31 #include <assert.h>
32 #include <ctype.h>
33 #include <errno.h>
34 #include <libgen.h>
35 #include <libintl.h>
36 #include <libuutil.h>
37 #include <libnvpair.h>
38 #include <locale.h>
39 #include <stddef.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <strings.h>
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <zone.h>
46 #include <grp.h>
47 #include <pwd.h>
48 #include <signal.h>
49 #include <sys/list.h>
50 #include <sys/mkdev.h>
51 #include <sys/mntent.h>
52 #include <sys/mnttab.h>
53 #include <sys/mount.h>
54 #include <sys/stat.h>
55 #include <sys/fs/zfs.h>
56 #include <sys/types.h>
57 #include <time.h>
59 #include <libzfs.h>
60 #include <libzfs_core.h>
61 #include <zfs_prop.h>
62 #include <zfs_deleg.h>
63 #include <libuutil.h>
64 #include <aclutils.h>
65 #include <directory.h>
66 #include <idmap.h>
68 #include "zfs_iter.h"
69 #include "zfs_util.h"
70 #include "zfs_comutil.h"
72 libzfs_handle_t *g_zfs;
74 static FILE *mnttab_file;
75 static char history_str[HIS_MAX_RECORD_LEN];
76 static boolean_t log_history = B_TRUE;
78 static int zfs_do_clone(int argc, char **argv);
79 static int zfs_do_create(int argc, char **argv);
80 static int zfs_do_destroy(int argc, char **argv);
81 static int zfs_do_get(int argc, char **argv);
82 static int zfs_do_inherit(int argc, char **argv);
83 static int zfs_do_list(int argc, char **argv);
84 static int zfs_do_mount(int argc, char **argv);
85 static int zfs_do_rename(int argc, char **argv);
86 static int zfs_do_rollback(int argc, char **argv);
87 static int zfs_do_set(int argc, char **argv);
88 static int zfs_do_upgrade(int argc, char **argv);
89 static int zfs_do_snapshot(int argc, char **argv);
90 static int zfs_do_unmount(int argc, char **argv);
91 static int zfs_do_share(int argc, char **argv);
92 static int zfs_do_unshare(int argc, char **argv);
93 static int zfs_do_send(int argc, char **argv);
94 static int zfs_do_receive(int argc, char **argv);
95 static int zfs_do_promote(int argc, char **argv);
96 static int zfs_do_userspace(int argc, char **argv);
97 static int zfs_do_allow(int argc, char **argv);
98 static int zfs_do_unallow(int argc, char **argv);
99 static int zfs_do_hold(int argc, char **argv);
100 static int zfs_do_holds(int argc, char **argv);
101 static int zfs_do_release(int argc, char **argv);
102 static int zfs_do_diff(int argc, char **argv);
103 static int zfs_do_bookmark(int argc, char **argv);
106 * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
109 #ifdef DEBUG
110 const char *
111 _umem_debug_init(void)
113 return ("default,verbose"); /* $UMEM_DEBUG setting */
116 const char *
117 _umem_logging_init(void)
119 return ("fail,contents"); /* $UMEM_LOGGING setting */
121 #endif
123 typedef enum {
124 HELP_CLONE,
125 HELP_CREATE,
126 HELP_DESTROY,
127 HELP_GET,
128 HELP_INHERIT,
129 HELP_UPGRADE,
130 HELP_LIST,
131 HELP_MOUNT,
132 HELP_PROMOTE,
133 HELP_RECEIVE,
134 HELP_RENAME,
135 HELP_ROLLBACK,
136 HELP_SEND,
137 HELP_SET,
138 HELP_SHARE,
139 HELP_SNAPSHOT,
140 HELP_UNMOUNT,
141 HELP_UNSHARE,
142 HELP_ALLOW,
143 HELP_UNALLOW,
144 HELP_USERSPACE,
145 HELP_GROUPSPACE,
146 HELP_HOLD,
147 HELP_HOLDS,
148 HELP_RELEASE,
149 HELP_DIFF,
150 HELP_BOOKMARK,
151 } zfs_help_t;
153 typedef struct zfs_command {
154 const char *name;
155 int (*func)(int argc, char **argv);
156 zfs_help_t usage;
157 } zfs_command_t;
160 * Master command table. Each ZFS command has a name, associated function, and
161 * usage message. The usage messages need to be internationalized, so we have
162 * to have a function to return the usage message based on a command index.
164 * These commands are organized according to how they are displayed in the usage
165 * message. An empty command (one with a NULL name) indicates an empty line in
166 * the generic usage message.
168 static zfs_command_t command_table[] = {
169 { "create", zfs_do_create, HELP_CREATE },
170 { "destroy", zfs_do_destroy, HELP_DESTROY },
171 { NULL },
172 { "snapshot", zfs_do_snapshot, HELP_SNAPSHOT },
173 { "rollback", zfs_do_rollback, HELP_ROLLBACK },
174 { "clone", zfs_do_clone, HELP_CLONE },
175 { "promote", zfs_do_promote, HELP_PROMOTE },
176 { "rename", zfs_do_rename, HELP_RENAME },
177 { "bookmark", zfs_do_bookmark, HELP_BOOKMARK },
178 { NULL },
179 { "list", zfs_do_list, HELP_LIST },
180 { NULL },
181 { "set", zfs_do_set, HELP_SET },
182 { "get", zfs_do_get, HELP_GET },
183 { "inherit", zfs_do_inherit, HELP_INHERIT },
184 { "upgrade", zfs_do_upgrade, HELP_UPGRADE },
185 { "userspace", zfs_do_userspace, HELP_USERSPACE },
186 { "groupspace", zfs_do_userspace, HELP_GROUPSPACE },
187 { NULL },
188 { "mount", zfs_do_mount, HELP_MOUNT },
189 { "unmount", zfs_do_unmount, HELP_UNMOUNT },
190 { "share", zfs_do_share, HELP_SHARE },
191 { "unshare", zfs_do_unshare, HELP_UNSHARE },
192 { NULL },
193 { "send", zfs_do_send, HELP_SEND },
194 { "receive", zfs_do_receive, HELP_RECEIVE },
195 { NULL },
196 { "allow", zfs_do_allow, HELP_ALLOW },
197 { NULL },
198 { "unallow", zfs_do_unallow, HELP_UNALLOW },
199 { NULL },
200 { "hold", zfs_do_hold, HELP_HOLD },
201 { "holds", zfs_do_holds, HELP_HOLDS },
202 { "release", zfs_do_release, HELP_RELEASE },
203 { "diff", zfs_do_diff, HELP_DIFF },
206 #define NCOMMAND (sizeof (command_table) / sizeof (command_table[0]))
208 zfs_command_t *current_command;
210 static const char *
211 get_usage(zfs_help_t idx)
213 switch (idx) {
214 case HELP_CLONE:
215 return (gettext("\tclone [-p] [-o property=value] ... "
216 "<snapshot> <filesystem|volume>\n"));
217 case HELP_CREATE:
218 return (gettext("\tcreate [-p] [-o property=value] ... "
219 "<filesystem>\n"
220 "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
221 "-V <size> <volume>\n"));
222 case HELP_DESTROY:
223 return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
224 "\tdestroy [-dnpRrv] "
225 "<filesystem|volume>@<snap>[%<snap>][,...]\n"
226 "\tdestroy <filesystem|volume>#<bookmark>\n"));
227 case HELP_GET:
228 return (gettext("\tget [-rHp] [-d max] "
229 "[-o \"all\" | field[,...]]\n"
230 "\t [-t type[,...]] [-s source[,...]]\n"
231 "\t <\"all\" | property[,...]> "
232 "[filesystem|volume|snapshot] ...\n"));
233 case HELP_INHERIT:
234 return (gettext("\tinherit [-rS] <property> "
235 "<filesystem|volume|snapshot> ...\n"));
236 case HELP_UPGRADE:
237 return (gettext("\tupgrade [-v]\n"
238 "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
239 case HELP_LIST:
240 return (gettext("\tlist [-Hp] [-r|-d max] [-o property[,...]] "
241 "[-s property]...\n\t [-S property]... [-t type[,...]] "
242 "[filesystem|volume|snapshot] ...\n"));
243 case HELP_MOUNT:
244 return (gettext("\tmount\n"
245 "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
246 case HELP_PROMOTE:
247 return (gettext("\tpromote <clone-filesystem>\n"));
248 case HELP_RECEIVE:
249 return (gettext("\treceive [-vnsFu] <filesystem|volume|"
250 "snapshot>\n"
251 "\treceive [-vnsFu] [-o origin=<snapshot>] [-d | -e] "
252 "<filesystem>\n"
253 "\treceive -A <filesystem|volume>\n"));
254 case HELP_RENAME:
255 return (gettext("\trename [-f] <filesystem|volume|snapshot> "
256 "<filesystem|volume|snapshot>\n"
257 "\trename [-f] -p <filesystem|volume> <filesystem|volume>\n"
258 "\trename -r <snapshot> <snapshot>\n"));
259 case HELP_ROLLBACK:
260 return (gettext("\trollback [-rRf] <snapshot>\n"));
261 case HELP_SEND:
262 return (gettext("\tsend [-DnPpRvLe] [-[iI] snapshot] "
263 "<snapshot>\n"
264 "\tsend [-Le] [-i snapshot|bookmark] "
265 "<filesystem|volume|snapshot>\n"
266 "\tsend [-nvPe] -t <receive_resume_token>\n"));
267 case HELP_SET:
268 return (gettext("\tset <property=value> ... "
269 "<filesystem|volume|snapshot> ...\n"));
270 case HELP_SHARE:
271 return (gettext("\tshare <-a | filesystem>\n"));
272 case HELP_SNAPSHOT:
273 return (gettext("\tsnapshot [-r] [-o property=value] ... "
274 "<filesystem|volume>@<snap> ...\n"));
275 case HELP_UNMOUNT:
276 return (gettext("\tunmount [-f] "
277 "<-a | filesystem|mountpoint>\n"));
278 case HELP_UNSHARE:
279 return (gettext("\tunshare "
280 "<-a | filesystem|mountpoint>\n"));
281 case HELP_ALLOW:
282 return (gettext("\tallow <filesystem|volume>\n"
283 "\tallow [-ldug] "
284 "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
285 "\t <filesystem|volume>\n"
286 "\tallow [-ld] -e <perm|@setname>[,...] "
287 "<filesystem|volume>\n"
288 "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
289 "\tallow -s @setname <perm|@setname>[,...] "
290 "<filesystem|volume>\n"));
291 case HELP_UNALLOW:
292 return (gettext("\tunallow [-rldug] "
293 "<\"everyone\"|user|group>[,...]\n"
294 "\t [<perm|@setname>[,...]] <filesystem|volume>\n"
295 "\tunallow [-rld] -e [<perm|@setname>[,...]] "
296 "<filesystem|volume>\n"
297 "\tunallow [-r] -c [<perm|@setname>[,...]] "
298 "<filesystem|volume>\n"
299 "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
300 "<filesystem|volume>\n"));
301 case HELP_USERSPACE:
302 return (gettext("\tuserspace [-Hinp] [-o field[,...]] "
303 "[-s field] ...\n"
304 "\t [-S field] ... [-t type[,...]] "
305 "<filesystem|snapshot>\n"));
306 case HELP_GROUPSPACE:
307 return (gettext("\tgroupspace [-Hinp] [-o field[,...]] "
308 "[-s field] ...\n"
309 "\t [-S field] ... [-t type[,...]] "
310 "<filesystem|snapshot>\n"));
311 case HELP_HOLD:
312 return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
313 case HELP_HOLDS:
314 return (gettext("\tholds [-r] <snapshot> ...\n"));
315 case HELP_RELEASE:
316 return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
317 case HELP_DIFF:
318 return (gettext("\tdiff [-FHt] <snapshot> "
319 "[snapshot|filesystem]\n"));
320 case HELP_BOOKMARK:
321 return (gettext("\tbookmark <snapshot> <bookmark>\n"));
324 abort();
325 /* NOTREACHED */
328 void
329 nomem(void)
331 (void) fprintf(stderr, gettext("internal error: out of memory\n"));
332 exit(1);
336 * Utility function to guarantee malloc() success.
339 void *
340 safe_malloc(size_t size)
342 void *data;
344 if ((data = calloc(1, size)) == NULL)
345 nomem();
347 return (data);
350 static char *
351 safe_strdup(char *str)
353 char *dupstr = strdup(str);
355 if (dupstr == NULL)
356 nomem();
358 return (dupstr);
362 * Callback routine that will print out information for each of
363 * the properties.
365 static int
366 usage_prop_cb(int prop, void *cb)
368 FILE *fp = cb;
370 (void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
372 if (zfs_prop_readonly(prop))
373 (void) fprintf(fp, " NO ");
374 else
375 (void) fprintf(fp, "YES ");
377 if (zfs_prop_inheritable(prop))
378 (void) fprintf(fp, " YES ");
379 else
380 (void) fprintf(fp, " NO ");
382 if (zfs_prop_values(prop) == NULL)
383 (void) fprintf(fp, "-\n");
384 else
385 (void) fprintf(fp, "%s\n", zfs_prop_values(prop));
387 return (ZPROP_CONT);
391 * Display usage message. If we're inside a command, display only the usage for
392 * that command. Otherwise, iterate over the entire command table and display
393 * a complete usage message.
395 static void
396 usage(boolean_t requested)
398 int i;
399 boolean_t show_properties = B_FALSE;
400 FILE *fp = requested ? stdout : stderr;
402 if (current_command == NULL) {
404 (void) fprintf(fp, gettext("usage: zfs command args ...\n"));
405 (void) fprintf(fp,
406 gettext("where 'command' is one of the following:\n\n"));
408 for (i = 0; i < NCOMMAND; i++) {
409 if (command_table[i].name == NULL)
410 (void) fprintf(fp, "\n");
411 else
412 (void) fprintf(fp, "%s",
413 get_usage(command_table[i].usage));
416 (void) fprintf(fp, gettext("\nEach dataset is of the form: "
417 "pool/[dataset/]*dataset[@name]\n"));
418 } else {
419 (void) fprintf(fp, gettext("usage:\n"));
420 (void) fprintf(fp, "%s", get_usage(current_command->usage));
423 if (current_command != NULL &&
424 (strcmp(current_command->name, "set") == 0 ||
425 strcmp(current_command->name, "get") == 0 ||
426 strcmp(current_command->name, "inherit") == 0 ||
427 strcmp(current_command->name, "list") == 0))
428 show_properties = B_TRUE;
430 if (show_properties) {
431 (void) fprintf(fp,
432 gettext("\nThe following properties are supported:\n"));
434 (void) fprintf(fp, "\n\t%-14s %s %s %s\n\n",
435 "PROPERTY", "EDIT", "INHERIT", "VALUES");
437 /* Iterate over all properties */
438 (void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
439 ZFS_TYPE_DATASET);
441 (void) fprintf(fp, "\t%-15s ", "userused@...");
442 (void) fprintf(fp, " NO NO <size>\n");
443 (void) fprintf(fp, "\t%-15s ", "groupused@...");
444 (void) fprintf(fp, " NO NO <size>\n");
445 (void) fprintf(fp, "\t%-15s ", "userquota@...");
446 (void) fprintf(fp, "YES NO <size> | none\n");
447 (void) fprintf(fp, "\t%-15s ", "groupquota@...");
448 (void) fprintf(fp, "YES NO <size> | none\n");
449 (void) fprintf(fp, "\t%-15s ", "written@<snap>");
450 (void) fprintf(fp, " NO NO <size>\n");
452 (void) fprintf(fp, gettext("\nSizes are specified in bytes "
453 "with standard units such as K, M, G, etc.\n"));
454 (void) fprintf(fp, gettext("\nUser-defined properties can "
455 "be specified by using a name containing a colon (:).\n"));
456 (void) fprintf(fp, gettext("\nThe {user|group}{used|quota}@ "
457 "properties must be appended with\n"
458 "a user or group specifier of one of these forms:\n"
459 " POSIX name (eg: \"matt\")\n"
460 " POSIX id (eg: \"126829\")\n"
461 " SMB name@domain (eg: \"matt@sun\")\n"
462 " SMB SID (eg: \"S-1-234-567-89\")\n"));
463 } else {
464 (void) fprintf(fp,
465 gettext("\nFor the property list, run: %s\n"),
466 "zfs set|get");
467 (void) fprintf(fp,
468 gettext("\nFor the delegated permission list, run: %s\n"),
469 "zfs allow|unallow");
473 * See comments at end of main().
475 if (getenv("ZFS_ABORT") != NULL) {
476 (void) printf("dumping core by request\n");
477 abort();
480 exit(requested ? 0 : 2);
484 * Take a property=value argument string and add it to the given nvlist.
485 * Modifies the argument inplace.
487 static int
488 parseprop(nvlist_t *props, char *propname)
490 char *propval, *strval;
492 if ((propval = strchr(propname, '=')) == NULL) {
493 (void) fprintf(stderr, gettext("missing "
494 "'=' for property=value argument\n"));
495 return (-1);
497 *propval = '\0';
498 propval++;
499 if (nvlist_lookup_string(props, propname, &strval) == 0) {
500 (void) fprintf(stderr, gettext("property '%s' "
501 "specified multiple times\n"), propname);
502 return (-1);
504 if (nvlist_add_string(props, propname, propval) != 0)
505 nomem();
506 return (0);
509 static int
510 parse_depth(char *opt, int *flags)
512 char *tmp;
513 int depth;
515 depth = (int)strtol(opt, &tmp, 0);
516 if (*tmp) {
517 (void) fprintf(stderr,
518 gettext("%s is not an integer\n"), optarg);
519 usage(B_FALSE);
521 if (depth < 0) {
522 (void) fprintf(stderr,
523 gettext("Depth can not be negative.\n"));
524 usage(B_FALSE);
526 *flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
527 return (depth);
530 #define PROGRESS_DELAY 2 /* seconds */
532 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";
533 static time_t pt_begin;
534 static char *pt_header = NULL;
535 static boolean_t pt_shown;
537 static void
538 start_progress_timer(void)
540 pt_begin = time(NULL) + PROGRESS_DELAY;
541 pt_shown = B_FALSE;
544 static void
545 set_progress_header(char *header)
547 assert(pt_header == NULL);
548 pt_header = safe_strdup(header);
549 if (pt_shown) {
550 (void) printf("%s: ", header);
551 (void) fflush(stdout);
555 static void
556 update_progress(char *update)
558 if (!pt_shown && time(NULL) > pt_begin) {
559 int len = strlen(update);
561 (void) printf("%s: %s%*.*s", pt_header, update, len, len,
562 pt_reverse);
563 (void) fflush(stdout);
564 pt_shown = B_TRUE;
565 } else if (pt_shown) {
566 int len = strlen(update);
568 (void) printf("%s%*.*s", update, len, len, pt_reverse);
569 (void) fflush(stdout);
573 static void
574 finish_progress(char *done)
576 if (pt_shown) {
577 (void) printf("%s\n", done);
578 (void) fflush(stdout);
580 free(pt_header);
581 pt_header = NULL;
585 * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
587 * Given an existing dataset, create a writable copy whose initial contents
588 * are the same as the source. The newly created dataset maintains a
589 * dependency on the original; the original cannot be destroyed so long as
590 * the clone exists.
592 * The '-p' flag creates all the non-existing ancestors of the target first.
594 static int
595 zfs_do_clone(int argc, char **argv)
597 zfs_handle_t *zhp = NULL;
598 boolean_t parents = B_FALSE;
599 nvlist_t *props;
600 int ret = 0;
601 int c;
603 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
604 nomem();
606 /* check options */
607 while ((c = getopt(argc, argv, "o:p")) != -1) {
608 switch (c) {
609 case 'o':
610 if (parseprop(props, optarg) != 0)
611 return (1);
612 break;
613 case 'p':
614 parents = B_TRUE;
615 break;
616 case '?':
617 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
618 optopt);
619 goto usage;
623 argc -= optind;
624 argv += optind;
626 /* check number of arguments */
627 if (argc < 1) {
628 (void) fprintf(stderr, gettext("missing source dataset "
629 "argument\n"));
630 goto usage;
632 if (argc < 2) {
633 (void) fprintf(stderr, gettext("missing target dataset "
634 "argument\n"));
635 goto usage;
637 if (argc > 2) {
638 (void) fprintf(stderr, gettext("too many arguments\n"));
639 goto usage;
642 /* open the source dataset */
643 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
644 return (1);
646 if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
647 ZFS_TYPE_VOLUME)) {
649 * Now create the ancestors of the target dataset. If the
650 * target already exists and '-p' option was used we should not
651 * complain.
653 if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
654 ZFS_TYPE_VOLUME))
655 return (0);
656 if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
657 return (1);
660 /* pass to libzfs */
661 ret = zfs_clone(zhp, argv[1], props);
663 /* create the mountpoint if necessary */
664 if (ret == 0) {
665 zfs_handle_t *clone;
667 clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
668 if (clone != NULL) {
669 if (zfs_get_type(clone) != ZFS_TYPE_VOLUME)
670 if ((ret = zfs_mount(clone, NULL, 0)) == 0)
671 ret = zfs_share(clone);
672 zfs_close(clone);
676 zfs_close(zhp);
677 nvlist_free(props);
679 return (!!ret);
681 usage:
682 if (zhp)
683 zfs_close(zhp);
684 nvlist_free(props);
685 usage(B_FALSE);
686 return (-1);
690 * zfs create [-p] [-o prop=value] ... fs
691 * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
693 * Create a new dataset. This command can be used to create filesystems
694 * and volumes. Snapshot creation is handled by 'zfs snapshot'.
695 * For volumes, the user must specify a size to be used.
697 * The '-s' flag applies only to volumes, and indicates that we should not try
698 * to set the reservation for this volume. By default we set a reservation
699 * equal to the size for any volume. For pools with SPA_VERSION >=
700 * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
702 * The '-p' flag creates all the non-existing ancestors of the target first.
704 static int
705 zfs_do_create(int argc, char **argv)
707 zfs_type_t type = ZFS_TYPE_FILESYSTEM;
708 zfs_handle_t *zhp = NULL;
709 uint64_t volsize;
710 int c;
711 boolean_t noreserve = B_FALSE;
712 boolean_t bflag = B_FALSE;
713 boolean_t parents = B_FALSE;
714 int ret = 1;
715 nvlist_t *props;
716 uint64_t intval;
717 int canmount = ZFS_CANMOUNT_OFF;
719 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
720 nomem();
722 /* check options */
723 while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
724 switch (c) {
725 case 'V':
726 type = ZFS_TYPE_VOLUME;
727 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
728 (void) fprintf(stderr, gettext("bad volume "
729 "size '%s': %s\n"), optarg,
730 libzfs_error_description(g_zfs));
731 goto error;
734 if (nvlist_add_uint64(props,
735 zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
736 nomem();
737 volsize = intval;
738 break;
739 case 'p':
740 parents = B_TRUE;
741 break;
742 case 'b':
743 bflag = B_TRUE;
744 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
745 (void) fprintf(stderr, gettext("bad volume "
746 "block size '%s': %s\n"), optarg,
747 libzfs_error_description(g_zfs));
748 goto error;
751 if (nvlist_add_uint64(props,
752 zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
753 intval) != 0)
754 nomem();
755 break;
756 case 'o':
757 if (parseprop(props, optarg) != 0)
758 goto error;
759 break;
760 case 's':
761 noreserve = B_TRUE;
762 break;
763 case ':':
764 (void) fprintf(stderr, gettext("missing size "
765 "argument\n"));
766 goto badusage;
767 case '?':
768 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
769 optopt);
770 goto badusage;
774 if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
775 (void) fprintf(stderr, gettext("'-s' and '-b' can only be "
776 "used when creating a volume\n"));
777 goto badusage;
780 argc -= optind;
781 argv += optind;
783 /* check number of arguments */
784 if (argc == 0) {
785 (void) fprintf(stderr, gettext("missing %s argument\n"),
786 zfs_type_to_name(type));
787 goto badusage;
789 if (argc > 1) {
790 (void) fprintf(stderr, gettext("too many arguments\n"));
791 goto badusage;
794 if (type == ZFS_TYPE_VOLUME && !noreserve) {
795 zpool_handle_t *zpool_handle;
796 nvlist_t *real_props;
797 uint64_t spa_version;
798 char *p;
799 zfs_prop_t resv_prop;
800 char *strval;
801 char msg[1024];
803 if (p = strchr(argv[0], '/'))
804 *p = '\0';
805 zpool_handle = zpool_open(g_zfs, argv[0]);
806 if (p != NULL)
807 *p = '/';
808 if (zpool_handle == NULL)
809 goto error;
810 spa_version = zpool_get_prop_int(zpool_handle,
811 ZPOOL_PROP_VERSION, NULL);
812 if (spa_version >= SPA_VERSION_REFRESERVATION)
813 resv_prop = ZFS_PROP_REFRESERVATION;
814 else
815 resv_prop = ZFS_PROP_RESERVATION;
817 (void) snprintf(msg, sizeof (msg),
818 gettext("cannot create '%s'"), argv[0]);
819 if (props && (real_props = zfs_valid_proplist(g_zfs, type,
820 props, 0, NULL, zpool_handle, msg)) == NULL) {
821 zpool_close(zpool_handle);
822 goto error;
824 zpool_close(zpool_handle);
826 volsize = zvol_volsize_to_reservation(volsize, real_props);
827 nvlist_free(real_props);
829 if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
830 &strval) != 0) {
831 if (nvlist_add_uint64(props,
832 zfs_prop_to_name(resv_prop), volsize) != 0) {
833 nvlist_free(props);
834 nomem();
839 if (parents && zfs_name_valid(argv[0], type)) {
841 * Now create the ancestors of target dataset. If the target
842 * already exists and '-p' option was used we should not
843 * complain.
845 if (zfs_dataset_exists(g_zfs, argv[0], type)) {
846 ret = 0;
847 goto error;
849 if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
850 goto error;
853 /* pass to libzfs */
854 if (zfs_create(g_zfs, argv[0], type, props) != 0)
855 goto error;
857 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
858 goto error;
860 ret = 0;
862 * if the user doesn't want the dataset automatically mounted,
863 * then skip the mount/share step
865 if (zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, type))
866 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
869 * Mount and/or share the new filesystem as appropriate. We provide a
870 * verbose error message to let the user know that their filesystem was
871 * in fact created, even if we failed to mount or share it.
873 if (canmount == ZFS_CANMOUNT_ON) {
874 if (zfs_mount(zhp, NULL, 0) != 0) {
875 (void) fprintf(stderr, gettext("filesystem "
876 "successfully created, but not mounted\n"));
877 ret = 1;
878 } else if (zfs_share(zhp) != 0) {
879 (void) fprintf(stderr, gettext("filesystem "
880 "successfully created, but not shared\n"));
881 ret = 1;
885 error:
886 if (zhp)
887 zfs_close(zhp);
888 nvlist_free(props);
889 return (ret);
890 badusage:
891 nvlist_free(props);
892 usage(B_FALSE);
893 return (2);
897 * zfs destroy [-rRf] <fs, vol>
898 * zfs destroy [-rRd] <snap>
900 * -r Recursively destroy all children
901 * -R Recursively destroy all dependents, including clones
902 * -f Force unmounting of any dependents
903 * -d If we can't destroy now, mark for deferred destruction
905 * Destroys the given dataset. By default, it will unmount any filesystems,
906 * and refuse to destroy a dataset that has any dependents. A dependent can
907 * either be a child, or a clone of a child.
909 typedef struct destroy_cbdata {
910 boolean_t cb_first;
911 boolean_t cb_force;
912 boolean_t cb_recurse;
913 boolean_t cb_error;
914 boolean_t cb_doclones;
915 zfs_handle_t *cb_target;
916 boolean_t cb_defer_destroy;
917 boolean_t cb_verbose;
918 boolean_t cb_parsable;
919 boolean_t cb_dryrun;
920 nvlist_t *cb_nvl;
921 nvlist_t *cb_batchedsnaps;
923 /* first snap in contiguous run */
924 char *cb_firstsnap;
925 /* previous snap in contiguous run */
926 char *cb_prevsnap;
927 int64_t cb_snapused;
928 char *cb_snapspec;
929 char *cb_bookmark;
930 } destroy_cbdata_t;
933 * Check for any dependents based on the '-r' or '-R' flags.
935 static int
936 destroy_check_dependent(zfs_handle_t *zhp, void *data)
938 destroy_cbdata_t *cbp = data;
939 const char *tname = zfs_get_name(cbp->cb_target);
940 const char *name = zfs_get_name(zhp);
942 if (strncmp(tname, name, strlen(tname)) == 0 &&
943 (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
945 * This is a direct descendant, not a clone somewhere else in
946 * the hierarchy.
948 if (cbp->cb_recurse)
949 goto out;
951 if (cbp->cb_first) {
952 (void) fprintf(stderr, gettext("cannot destroy '%s': "
953 "%s has children\n"),
954 zfs_get_name(cbp->cb_target),
955 zfs_type_to_name(zfs_get_type(cbp->cb_target)));
956 (void) fprintf(stderr, gettext("use '-r' to destroy "
957 "the following datasets:\n"));
958 cbp->cb_first = B_FALSE;
959 cbp->cb_error = B_TRUE;
962 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
963 } else {
965 * This is a clone. We only want to report this if the '-r'
966 * wasn't specified, or the target is a snapshot.
968 if (!cbp->cb_recurse &&
969 zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
970 goto out;
972 if (cbp->cb_first) {
973 (void) fprintf(stderr, gettext("cannot destroy '%s': "
974 "%s has dependent clones\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;
981 cbp->cb_dryrun = B_TRUE;
984 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
987 out:
988 zfs_close(zhp);
989 return (0);
992 static int
993 destroy_callback(zfs_handle_t *zhp, void *data)
995 destroy_cbdata_t *cb = data;
996 const char *name = zfs_get_name(zhp);
998 if (cb->cb_verbose) {
999 if (cb->cb_parsable) {
1000 (void) printf("destroy\t%s\n", name);
1001 } else if (cb->cb_dryrun) {
1002 (void) printf(gettext("would destroy %s\n"),
1003 name);
1004 } else {
1005 (void) printf(gettext("will destroy %s\n"),
1006 name);
1011 * Ignore pools (which we've already flagged as an error before getting
1012 * here).
1014 if (strchr(zfs_get_name(zhp), '/') == NULL &&
1015 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1016 zfs_close(zhp);
1017 return (0);
1019 if (cb->cb_dryrun) {
1020 zfs_close(zhp);
1021 return (0);
1025 * We batch up all contiguous snapshots (even of different
1026 * filesystems) and destroy them with one ioctl. We can't
1027 * simply do all snap deletions and then all fs deletions,
1028 * because we must delete a clone before its origin.
1030 if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT) {
1031 fnvlist_add_boolean(cb->cb_batchedsnaps, name);
1032 } else {
1033 int error = zfs_destroy_snaps_nvl(g_zfs,
1034 cb->cb_batchedsnaps, B_FALSE);
1035 fnvlist_free(cb->cb_batchedsnaps);
1036 cb->cb_batchedsnaps = fnvlist_alloc();
1038 if (error != 0 ||
1039 zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
1040 zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
1041 zfs_close(zhp);
1042 return (-1);
1046 zfs_close(zhp);
1047 return (0);
1050 static int
1051 destroy_print_cb(zfs_handle_t *zhp, void *arg)
1053 destroy_cbdata_t *cb = arg;
1054 const char *name = zfs_get_name(zhp);
1055 int err = 0;
1057 if (nvlist_exists(cb->cb_nvl, name)) {
1058 if (cb->cb_firstsnap == NULL)
1059 cb->cb_firstsnap = strdup(name);
1060 if (cb->cb_prevsnap != NULL)
1061 free(cb->cb_prevsnap);
1062 /* this snap continues the current range */
1063 cb->cb_prevsnap = strdup(name);
1064 if (cb->cb_firstsnap == NULL || cb->cb_prevsnap == NULL)
1065 nomem();
1066 if (cb->cb_verbose) {
1067 if (cb->cb_parsable) {
1068 (void) printf("destroy\t%s\n", name);
1069 } else if (cb->cb_dryrun) {
1070 (void) printf(gettext("would destroy %s\n"),
1071 name);
1072 } else {
1073 (void) printf(gettext("will destroy %s\n"),
1074 name);
1077 } else if (cb->cb_firstsnap != NULL) {
1078 /* end of this range */
1079 uint64_t used = 0;
1080 err = lzc_snaprange_space(cb->cb_firstsnap,
1081 cb->cb_prevsnap, &used);
1082 cb->cb_snapused += used;
1083 free(cb->cb_firstsnap);
1084 cb->cb_firstsnap = NULL;
1085 free(cb->cb_prevsnap);
1086 cb->cb_prevsnap = NULL;
1088 zfs_close(zhp);
1089 return (err);
1092 static int
1093 destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
1095 int err = 0;
1096 assert(cb->cb_firstsnap == NULL);
1097 assert(cb->cb_prevsnap == NULL);
1098 err = zfs_iter_snapshots_sorted(fs_zhp, destroy_print_cb, cb);
1099 if (cb->cb_firstsnap != NULL) {
1100 uint64_t used = 0;
1101 if (err == 0) {
1102 err = lzc_snaprange_space(cb->cb_firstsnap,
1103 cb->cb_prevsnap, &used);
1105 cb->cb_snapused += used;
1106 free(cb->cb_firstsnap);
1107 cb->cb_firstsnap = NULL;
1108 free(cb->cb_prevsnap);
1109 cb->cb_prevsnap = NULL;
1111 return (err);
1114 static int
1115 snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
1117 destroy_cbdata_t *cb = arg;
1118 int err = 0;
1120 /* Check for clones. */
1121 if (!cb->cb_doclones && !cb->cb_defer_destroy) {
1122 cb->cb_target = zhp;
1123 cb->cb_first = B_TRUE;
1124 err = zfs_iter_dependents(zhp, B_TRUE,
1125 destroy_check_dependent, cb);
1128 if (err == 0) {
1129 if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
1130 nomem();
1132 zfs_close(zhp);
1133 return (err);
1136 static int
1137 gather_snapshots(zfs_handle_t *zhp, void *arg)
1139 destroy_cbdata_t *cb = arg;
1140 int err = 0;
1142 err = zfs_iter_snapspec(zhp, cb->cb_snapspec, snapshot_to_nvl_cb, cb);
1143 if (err == ENOENT)
1144 err = 0;
1145 if (err != 0)
1146 goto out;
1148 if (cb->cb_verbose) {
1149 err = destroy_print_snapshots(zhp, cb);
1150 if (err != 0)
1151 goto out;
1154 if (cb->cb_recurse)
1155 err = zfs_iter_filesystems(zhp, gather_snapshots, cb);
1157 out:
1158 zfs_close(zhp);
1159 return (err);
1162 static int
1163 destroy_clones(destroy_cbdata_t *cb)
1165 nvpair_t *pair;
1166 for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
1167 pair != NULL;
1168 pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
1169 zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
1170 ZFS_TYPE_SNAPSHOT);
1171 if (zhp != NULL) {
1172 boolean_t defer = cb->cb_defer_destroy;
1173 int err = 0;
1176 * We can't defer destroy non-snapshots, so set it to
1177 * false while destroying the clones.
1179 cb->cb_defer_destroy = B_FALSE;
1180 err = zfs_iter_dependents(zhp, B_FALSE,
1181 destroy_callback, cb);
1182 cb->cb_defer_destroy = defer;
1183 zfs_close(zhp);
1184 if (err != 0)
1185 return (err);
1188 return (0);
1191 static int
1192 zfs_do_destroy(int argc, char **argv)
1194 destroy_cbdata_t cb = { 0 };
1195 int rv = 0;
1196 int err = 0;
1197 int c;
1198 zfs_handle_t *zhp = NULL;
1199 char *at, *pound;
1200 zfs_type_t type = ZFS_TYPE_DATASET;
1202 /* check options */
1203 while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
1204 switch (c) {
1205 case 'v':
1206 cb.cb_verbose = B_TRUE;
1207 break;
1208 case 'p':
1209 cb.cb_verbose = B_TRUE;
1210 cb.cb_parsable = B_TRUE;
1211 break;
1212 case 'n':
1213 cb.cb_dryrun = B_TRUE;
1214 break;
1215 case 'd':
1216 cb.cb_defer_destroy = B_TRUE;
1217 type = ZFS_TYPE_SNAPSHOT;
1218 break;
1219 case 'f':
1220 cb.cb_force = B_TRUE;
1221 break;
1222 case 'r':
1223 cb.cb_recurse = B_TRUE;
1224 break;
1225 case 'R':
1226 cb.cb_recurse = B_TRUE;
1227 cb.cb_doclones = B_TRUE;
1228 break;
1229 case '?':
1230 default:
1231 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1232 optopt);
1233 usage(B_FALSE);
1237 argc -= optind;
1238 argv += optind;
1240 /* check number of arguments */
1241 if (argc == 0) {
1242 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1243 usage(B_FALSE);
1245 if (argc > 1) {
1246 (void) fprintf(stderr, gettext("too many arguments\n"));
1247 usage(B_FALSE);
1250 at = strchr(argv[0], '@');
1251 pound = strchr(argv[0], '#');
1252 if (at != NULL) {
1254 /* Build the list of snaps to destroy in cb_nvl. */
1255 cb.cb_nvl = fnvlist_alloc();
1257 *at = '\0';
1258 zhp = zfs_open(g_zfs, argv[0],
1259 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1260 if (zhp == NULL)
1261 return (1);
1263 cb.cb_snapspec = at + 1;
1264 if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
1265 cb.cb_error) {
1266 rv = 1;
1267 goto out;
1270 if (nvlist_empty(cb.cb_nvl)) {
1271 (void) fprintf(stderr, gettext("could not find any "
1272 "snapshots to destroy; check snapshot names.\n"));
1273 rv = 1;
1274 goto out;
1277 if (cb.cb_verbose) {
1278 char buf[16];
1279 zfs_nicenum(cb.cb_snapused, buf, sizeof (buf));
1280 if (cb.cb_parsable) {
1281 (void) printf("reclaim\t%llu\n",
1282 cb.cb_snapused);
1283 } else if (cb.cb_dryrun) {
1284 (void) printf(gettext("would reclaim %s\n"),
1285 buf);
1286 } else {
1287 (void) printf(gettext("will reclaim %s\n"),
1288 buf);
1292 if (!cb.cb_dryrun) {
1293 if (cb.cb_doclones) {
1294 cb.cb_batchedsnaps = fnvlist_alloc();
1295 err = destroy_clones(&cb);
1296 if (err == 0) {
1297 err = zfs_destroy_snaps_nvl(g_zfs,
1298 cb.cb_batchedsnaps, B_FALSE);
1300 if (err != 0) {
1301 rv = 1;
1302 goto out;
1305 if (err == 0) {
1306 err = zfs_destroy_snaps_nvl(g_zfs, cb.cb_nvl,
1307 cb.cb_defer_destroy);
1311 if (err != 0)
1312 rv = 1;
1313 } else if (pound != NULL) {
1314 int err;
1315 nvlist_t *nvl;
1317 if (cb.cb_dryrun) {
1318 (void) fprintf(stderr,
1319 "dryrun is not supported with bookmark\n");
1320 return (-1);
1323 if (cb.cb_defer_destroy) {
1324 (void) fprintf(stderr,
1325 "defer destroy is not supported with bookmark\n");
1326 return (-1);
1329 if (cb.cb_recurse) {
1330 (void) fprintf(stderr,
1331 "recursive is not supported with bookmark\n");
1332 return (-1);
1335 if (!zfs_bookmark_exists(argv[0])) {
1336 (void) fprintf(stderr, gettext("bookmark '%s' "
1337 "does not exist.\n"), argv[0]);
1338 return (1);
1341 nvl = fnvlist_alloc();
1342 fnvlist_add_boolean(nvl, argv[0]);
1344 err = lzc_destroy_bookmarks(nvl, NULL);
1345 if (err != 0) {
1346 (void) zfs_standard_error(g_zfs, err,
1347 "cannot destroy bookmark");
1350 nvlist_free(cb.cb_nvl);
1352 return (err);
1353 } else {
1354 /* Open the given dataset */
1355 if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1356 return (1);
1358 cb.cb_target = zhp;
1361 * Perform an explicit check for pools before going any further.
1363 if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1364 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1365 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1366 "operation does not apply to pools\n"),
1367 zfs_get_name(zhp));
1368 (void) fprintf(stderr, gettext("use 'zfs destroy -r "
1369 "%s' to destroy all datasets in the pool\n"),
1370 zfs_get_name(zhp));
1371 (void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1372 "to destroy the pool itself\n"), zfs_get_name(zhp));
1373 rv = 1;
1374 goto out;
1378 * Check for any dependents and/or clones.
1380 cb.cb_first = B_TRUE;
1381 if (!cb.cb_doclones &&
1382 zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
1383 &cb) != 0) {
1384 rv = 1;
1385 goto out;
1388 if (cb.cb_error) {
1389 rv = 1;
1390 goto out;
1393 cb.cb_batchedsnaps = fnvlist_alloc();
1394 if (zfs_iter_dependents(zhp, B_FALSE, destroy_callback,
1395 &cb) != 0) {
1396 rv = 1;
1397 goto out;
1401 * Do the real thing. The callback will close the
1402 * handle regardless of whether it succeeds or not.
1404 err = destroy_callback(zhp, &cb);
1405 zhp = NULL;
1406 if (err == 0) {
1407 err = zfs_destroy_snaps_nvl(g_zfs,
1408 cb.cb_batchedsnaps, cb.cb_defer_destroy);
1410 if (err != 0)
1411 rv = 1;
1414 out:
1415 fnvlist_free(cb.cb_batchedsnaps);
1416 fnvlist_free(cb.cb_nvl);
1417 if (zhp != NULL)
1418 zfs_close(zhp);
1419 return (rv);
1422 static boolean_t
1423 is_recvd_column(zprop_get_cbdata_t *cbp)
1425 int i;
1426 zfs_get_column_t col;
1428 for (i = 0; i < ZFS_GET_NCOLS &&
1429 (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1430 if (col == GET_COL_RECVD)
1431 return (B_TRUE);
1432 return (B_FALSE);
1436 * zfs get [-rHp] [-o all | field[,field]...] [-s source[,source]...]
1437 * < all | property[,property]... > < fs | snap | vol > ...
1439 * -r recurse over any child datasets
1440 * -H scripted mode. Headers are stripped, and fields are separated
1441 * by tabs instead of spaces.
1442 * -o Set of fields to display. One of "name,property,value,
1443 * received,source". Default is "name,property,value,source".
1444 * "all" is an alias for all five.
1445 * -s Set of sources to allow. One of
1446 * "local,default,inherited,received,temporary,none". Default is
1447 * all six.
1448 * -p Display values in parsable (literal) format.
1450 * Prints properties for the given datasets. The user can control which
1451 * columns to display as well as which property types to allow.
1455 * Invoked to display the properties for a single dataset.
1457 static int
1458 get_callback(zfs_handle_t *zhp, void *data)
1460 char buf[ZFS_MAXPROPLEN];
1461 char rbuf[ZFS_MAXPROPLEN];
1462 zprop_source_t sourcetype;
1463 char source[ZFS_MAXNAMELEN];
1464 zprop_get_cbdata_t *cbp = data;
1465 nvlist_t *user_props = zfs_get_user_props(zhp);
1466 zprop_list_t *pl = cbp->cb_proplist;
1467 nvlist_t *propval;
1468 char *strval;
1469 char *sourceval;
1470 boolean_t received = is_recvd_column(cbp);
1472 for (; pl != NULL; pl = pl->pl_next) {
1473 char *recvdval = NULL;
1475 * Skip the special fake placeholder. This will also skip over
1476 * the name property when 'all' is specified.
1478 if (pl->pl_prop == ZFS_PROP_NAME &&
1479 pl == cbp->cb_proplist)
1480 continue;
1482 if (pl->pl_prop != ZPROP_INVAL) {
1483 if (zfs_prop_get(zhp, pl->pl_prop, buf,
1484 sizeof (buf), &sourcetype, source,
1485 sizeof (source),
1486 cbp->cb_literal) != 0) {
1487 if (pl->pl_all)
1488 continue;
1489 if (!zfs_prop_valid_for_type(pl->pl_prop,
1490 ZFS_TYPE_DATASET)) {
1491 (void) fprintf(stderr,
1492 gettext("No such property '%s'\n"),
1493 zfs_prop_to_name(pl->pl_prop));
1494 continue;
1496 sourcetype = ZPROP_SRC_NONE;
1497 (void) strlcpy(buf, "-", sizeof (buf));
1500 if (received && (zfs_prop_get_recvd(zhp,
1501 zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
1502 cbp->cb_literal) == 0))
1503 recvdval = rbuf;
1505 zprop_print_one_property(zfs_get_name(zhp), cbp,
1506 zfs_prop_to_name(pl->pl_prop),
1507 buf, sourcetype, source, recvdval);
1508 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
1509 sourcetype = ZPROP_SRC_LOCAL;
1511 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1512 buf, sizeof (buf), cbp->cb_literal) != 0) {
1513 sourcetype = ZPROP_SRC_NONE;
1514 (void) strlcpy(buf, "-", sizeof (buf));
1517 zprop_print_one_property(zfs_get_name(zhp), cbp,
1518 pl->pl_user_prop, buf, sourcetype, source, NULL);
1519 } else if (zfs_prop_written(pl->pl_user_prop)) {
1520 sourcetype = ZPROP_SRC_LOCAL;
1522 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
1523 buf, sizeof (buf), cbp->cb_literal) != 0) {
1524 sourcetype = ZPROP_SRC_NONE;
1525 (void) strlcpy(buf, "-", sizeof (buf));
1528 zprop_print_one_property(zfs_get_name(zhp), cbp,
1529 pl->pl_user_prop, buf, sourcetype, source, NULL);
1530 } else {
1531 if (nvlist_lookup_nvlist(user_props,
1532 pl->pl_user_prop, &propval) != 0) {
1533 if (pl->pl_all)
1534 continue;
1535 sourcetype = ZPROP_SRC_NONE;
1536 strval = "-";
1537 } else {
1538 verify(nvlist_lookup_string(propval,
1539 ZPROP_VALUE, &strval) == 0);
1540 verify(nvlist_lookup_string(propval,
1541 ZPROP_SOURCE, &sourceval) == 0);
1543 if (strcmp(sourceval,
1544 zfs_get_name(zhp)) == 0) {
1545 sourcetype = ZPROP_SRC_LOCAL;
1546 } else if (strcmp(sourceval,
1547 ZPROP_SOURCE_VAL_RECVD) == 0) {
1548 sourcetype = ZPROP_SRC_RECEIVED;
1549 } else {
1550 sourcetype = ZPROP_SRC_INHERITED;
1551 (void) strlcpy(source,
1552 sourceval, sizeof (source));
1556 if (received && (zfs_prop_get_recvd(zhp,
1557 pl->pl_user_prop, rbuf, sizeof (rbuf),
1558 cbp->cb_literal) == 0))
1559 recvdval = rbuf;
1561 zprop_print_one_property(zfs_get_name(zhp), cbp,
1562 pl->pl_user_prop, strval, sourcetype,
1563 source, recvdval);
1567 return (0);
1570 static int
1571 zfs_do_get(int argc, char **argv)
1573 zprop_get_cbdata_t cb = { 0 };
1574 int i, c, flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1575 int types = ZFS_TYPE_DATASET;
1576 char *value, *fields;
1577 int ret = 0;
1578 int limit = 0;
1579 zprop_list_t fake_name = { 0 };
1582 * Set up default columns and sources.
1584 cb.cb_sources = ZPROP_SRC_ALL;
1585 cb.cb_columns[0] = GET_COL_NAME;
1586 cb.cb_columns[1] = GET_COL_PROPERTY;
1587 cb.cb_columns[2] = GET_COL_VALUE;
1588 cb.cb_columns[3] = GET_COL_SOURCE;
1589 cb.cb_type = ZFS_TYPE_DATASET;
1591 /* check options */
1592 while ((c = getopt(argc, argv, ":d:o:s:rt:Hp")) != -1) {
1593 switch (c) {
1594 case 'p':
1595 cb.cb_literal = B_TRUE;
1596 break;
1597 case 'd':
1598 limit = parse_depth(optarg, &flags);
1599 break;
1600 case 'r':
1601 flags |= ZFS_ITER_RECURSE;
1602 break;
1603 case 'H':
1604 cb.cb_scripted = B_TRUE;
1605 break;
1606 case ':':
1607 (void) fprintf(stderr, gettext("missing argument for "
1608 "'%c' option\n"), optopt);
1609 usage(B_FALSE);
1610 break;
1611 case 'o':
1613 * Process the set of columns to display. We zero out
1614 * the structure to give us a blank slate.
1616 bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1617 i = 0;
1618 while (*optarg != '\0') {
1619 static char *col_subopts[] =
1620 { "name", "property", "value", "received",
1621 "source", "all", NULL };
1623 if (i == ZFS_GET_NCOLS) {
1624 (void) fprintf(stderr, gettext("too "
1625 "many fields given to -o "
1626 "option\n"));
1627 usage(B_FALSE);
1630 switch (getsubopt(&optarg, col_subopts,
1631 &value)) {
1632 case 0:
1633 cb.cb_columns[i++] = GET_COL_NAME;
1634 break;
1635 case 1:
1636 cb.cb_columns[i++] = GET_COL_PROPERTY;
1637 break;
1638 case 2:
1639 cb.cb_columns[i++] = GET_COL_VALUE;
1640 break;
1641 case 3:
1642 cb.cb_columns[i++] = GET_COL_RECVD;
1643 flags |= ZFS_ITER_RECVD_PROPS;
1644 break;
1645 case 4:
1646 cb.cb_columns[i++] = GET_COL_SOURCE;
1647 break;
1648 case 5:
1649 if (i > 0) {
1650 (void) fprintf(stderr,
1651 gettext("\"all\" conflicts "
1652 "with specific fields "
1653 "given to -o option\n"));
1654 usage(B_FALSE);
1656 cb.cb_columns[0] = GET_COL_NAME;
1657 cb.cb_columns[1] = GET_COL_PROPERTY;
1658 cb.cb_columns[2] = GET_COL_VALUE;
1659 cb.cb_columns[3] = GET_COL_RECVD;
1660 cb.cb_columns[4] = GET_COL_SOURCE;
1661 flags |= ZFS_ITER_RECVD_PROPS;
1662 i = ZFS_GET_NCOLS;
1663 break;
1664 default:
1665 (void) fprintf(stderr,
1666 gettext("invalid column name "
1667 "'%s'\n"), value);
1668 usage(B_FALSE);
1671 break;
1673 case 's':
1674 cb.cb_sources = 0;
1675 while (*optarg != '\0') {
1676 static char *source_subopts[] = {
1677 "local", "default", "inherited",
1678 "received", "temporary", "none",
1679 NULL };
1681 switch (getsubopt(&optarg, source_subopts,
1682 &value)) {
1683 case 0:
1684 cb.cb_sources |= ZPROP_SRC_LOCAL;
1685 break;
1686 case 1:
1687 cb.cb_sources |= ZPROP_SRC_DEFAULT;
1688 break;
1689 case 2:
1690 cb.cb_sources |= ZPROP_SRC_INHERITED;
1691 break;
1692 case 3:
1693 cb.cb_sources |= ZPROP_SRC_RECEIVED;
1694 break;
1695 case 4:
1696 cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1697 break;
1698 case 5:
1699 cb.cb_sources |= ZPROP_SRC_NONE;
1700 break;
1701 default:
1702 (void) fprintf(stderr,
1703 gettext("invalid source "
1704 "'%s'\n"), value);
1705 usage(B_FALSE);
1708 break;
1710 case 't':
1711 types = 0;
1712 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
1713 while (*optarg != '\0') {
1714 static char *type_subopts[] = { "filesystem",
1715 "volume", "snapshot", "bookmark",
1716 "all", NULL };
1718 switch (getsubopt(&optarg, type_subopts,
1719 &value)) {
1720 case 0:
1721 types |= ZFS_TYPE_FILESYSTEM;
1722 break;
1723 case 1:
1724 types |= ZFS_TYPE_VOLUME;
1725 break;
1726 case 2:
1727 types |= ZFS_TYPE_SNAPSHOT;
1728 break;
1729 case 3:
1730 types |= ZFS_TYPE_BOOKMARK;
1731 break;
1732 case 4:
1733 types = ZFS_TYPE_DATASET |
1734 ZFS_TYPE_BOOKMARK;
1735 break;
1737 default:
1738 (void) fprintf(stderr,
1739 gettext("invalid type '%s'\n"),
1740 value);
1741 usage(B_FALSE);
1744 break;
1746 case '?':
1747 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1748 optopt);
1749 usage(B_FALSE);
1753 argc -= optind;
1754 argv += optind;
1756 if (argc < 1) {
1757 (void) fprintf(stderr, gettext("missing property "
1758 "argument\n"));
1759 usage(B_FALSE);
1762 fields = argv[0];
1764 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1765 != 0)
1766 usage(B_FALSE);
1768 argc--;
1769 argv++;
1772 * As part of zfs_expand_proplist(), we keep track of the maximum column
1773 * width for each property. For the 'NAME' (and 'SOURCE') columns, we
1774 * need to know the maximum name length. However, the user likely did
1775 * not specify 'name' as one of the properties to fetch, so we need to
1776 * make sure we always include at least this property for
1777 * print_get_headers() to work properly.
1779 if (cb.cb_proplist != NULL) {
1780 fake_name.pl_prop = ZFS_PROP_NAME;
1781 fake_name.pl_width = strlen(gettext("NAME"));
1782 fake_name.pl_next = cb.cb_proplist;
1783 cb.cb_proplist = &fake_name;
1786 cb.cb_first = B_TRUE;
1788 /* run for each object */
1789 ret = zfs_for_each(argc, argv, flags, types, NULL,
1790 &cb.cb_proplist, limit, get_callback, &cb);
1792 if (cb.cb_proplist == &fake_name)
1793 zprop_free_list(fake_name.pl_next);
1794 else
1795 zprop_free_list(cb.cb_proplist);
1797 return (ret);
1801 * inherit [-rS] <property> <fs|vol> ...
1803 * -r Recurse over all children
1804 * -S Revert to received value, if any
1806 * For each dataset specified on the command line, inherit the given property
1807 * from its parent. Inheriting a property at the pool level will cause it to
1808 * use the default value. The '-r' flag will recurse over all children, and is
1809 * useful for setting a property on a hierarchy-wide basis, regardless of any
1810 * local modifications for each dataset.
1813 typedef struct inherit_cbdata {
1814 const char *cb_propname;
1815 boolean_t cb_received;
1816 } inherit_cbdata_t;
1818 static int
1819 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
1821 inherit_cbdata_t *cb = data;
1822 zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
1825 * If we're doing it recursively, then ignore properties that
1826 * are not valid for this type of dataset.
1828 if (prop != ZPROP_INVAL &&
1829 !zfs_prop_valid_for_type(prop, zfs_get_type(zhp)))
1830 return (0);
1832 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1835 static int
1836 inherit_cb(zfs_handle_t *zhp, void *data)
1838 inherit_cbdata_t *cb = data;
1840 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1843 static int
1844 zfs_do_inherit(int argc, char **argv)
1846 int c;
1847 zfs_prop_t prop;
1848 inherit_cbdata_t cb = { 0 };
1849 char *propname;
1850 int ret = 0;
1851 int flags = 0;
1852 boolean_t received = B_FALSE;
1854 /* check options */
1855 while ((c = getopt(argc, argv, "rS")) != -1) {
1856 switch (c) {
1857 case 'r':
1858 flags |= ZFS_ITER_RECURSE;
1859 break;
1860 case 'S':
1861 received = B_TRUE;
1862 break;
1863 case '?':
1864 default:
1865 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1866 optopt);
1867 usage(B_FALSE);
1871 argc -= optind;
1872 argv += optind;
1874 /* check number of arguments */
1875 if (argc < 1) {
1876 (void) fprintf(stderr, gettext("missing property argument\n"));
1877 usage(B_FALSE);
1879 if (argc < 2) {
1880 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1881 usage(B_FALSE);
1884 propname = argv[0];
1885 argc--;
1886 argv++;
1888 if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1889 if (zfs_prop_readonly(prop)) {
1890 (void) fprintf(stderr, gettext(
1891 "%s property is read-only\n"),
1892 propname);
1893 return (1);
1895 if (!zfs_prop_inheritable(prop) && !received) {
1896 (void) fprintf(stderr, gettext("'%s' property cannot "
1897 "be inherited\n"), propname);
1898 if (prop == ZFS_PROP_QUOTA ||
1899 prop == ZFS_PROP_RESERVATION ||
1900 prop == ZFS_PROP_REFQUOTA ||
1901 prop == ZFS_PROP_REFRESERVATION) {
1902 (void) fprintf(stderr, gettext("use 'zfs set "
1903 "%s=none' to clear\n"), propname);
1904 (void) fprintf(stderr, gettext("use 'zfs "
1905 "inherit -S %s' to revert to received "
1906 "value\n"), propname);
1908 return (1);
1910 if (received && (prop == ZFS_PROP_VOLSIZE ||
1911 prop == ZFS_PROP_VERSION)) {
1912 (void) fprintf(stderr, gettext("'%s' property cannot "
1913 "be reverted to a received value\n"), propname);
1914 return (1);
1916 } else if (!zfs_prop_user(propname)) {
1917 (void) fprintf(stderr, gettext("invalid property '%s'\n"),
1918 propname);
1919 usage(B_FALSE);
1922 cb.cb_propname = propname;
1923 cb.cb_received = received;
1925 if (flags & ZFS_ITER_RECURSE) {
1926 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1927 NULL, NULL, 0, inherit_recurse_cb, &cb);
1928 } else {
1929 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1930 NULL, NULL, 0, inherit_cb, &cb);
1933 return (ret);
1936 typedef struct upgrade_cbdata {
1937 uint64_t cb_numupgraded;
1938 uint64_t cb_numsamegraded;
1939 uint64_t cb_numfailed;
1940 uint64_t cb_version;
1941 boolean_t cb_newer;
1942 boolean_t cb_foundone;
1943 char cb_lastfs[ZFS_MAXNAMELEN];
1944 } upgrade_cbdata_t;
1946 static int
1947 same_pool(zfs_handle_t *zhp, const char *name)
1949 int len1 = strcspn(name, "/@");
1950 const char *zhname = zfs_get_name(zhp);
1951 int len2 = strcspn(zhname, "/@");
1953 if (len1 != len2)
1954 return (B_FALSE);
1955 return (strncmp(name, zhname, len1) == 0);
1958 static int
1959 upgrade_list_callback(zfs_handle_t *zhp, void *data)
1961 upgrade_cbdata_t *cb = data;
1962 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1964 /* list if it's old/new */
1965 if ((!cb->cb_newer && version < ZPL_VERSION) ||
1966 (cb->cb_newer && version > ZPL_VERSION)) {
1967 char *str;
1968 if (cb->cb_newer) {
1969 str = gettext("The following filesystems are "
1970 "formatted using a newer software version and\n"
1971 "cannot be accessed on the current system.\n\n");
1972 } else {
1973 str = gettext("The following filesystems are "
1974 "out of date, and can be upgraded. After being\n"
1975 "upgraded, these filesystems (and any 'zfs send' "
1976 "streams generated from\n"
1977 "subsequent snapshots) will no longer be "
1978 "accessible by older software versions.\n\n");
1981 if (!cb->cb_foundone) {
1982 (void) puts(str);
1983 (void) printf(gettext("VER FILESYSTEM\n"));
1984 (void) printf(gettext("--- ------------\n"));
1985 cb->cb_foundone = B_TRUE;
1988 (void) printf("%2u %s\n", version, zfs_get_name(zhp));
1991 return (0);
1994 static int
1995 upgrade_set_callback(zfs_handle_t *zhp, void *data)
1997 upgrade_cbdata_t *cb = data;
1998 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1999 int needed_spa_version;
2000 int spa_version;
2002 if (zfs_spa_version(zhp, &spa_version) < 0)
2003 return (-1);
2005 needed_spa_version = zfs_spa_version_map(cb->cb_version);
2007 if (needed_spa_version < 0)
2008 return (-1);
2010 if (spa_version < needed_spa_version) {
2011 /* can't upgrade */
2012 (void) printf(gettext("%s: can not be "
2013 "upgraded; the pool version needs to first "
2014 "be upgraded\nto version %d\n\n"),
2015 zfs_get_name(zhp), needed_spa_version);
2016 cb->cb_numfailed++;
2017 return (0);
2020 /* upgrade */
2021 if (version < cb->cb_version) {
2022 char verstr[16];
2023 (void) snprintf(verstr, sizeof (verstr),
2024 "%llu", cb->cb_version);
2025 if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
2027 * If they did "zfs upgrade -a", then we could
2028 * be doing ioctls to different pools. We need
2029 * to log this history once to each pool, and bypass
2030 * the normal history logging that happens in main().
2032 (void) zpool_log_history(g_zfs, history_str);
2033 log_history = B_FALSE;
2035 if (zfs_prop_set(zhp, "version", verstr) == 0)
2036 cb->cb_numupgraded++;
2037 else
2038 cb->cb_numfailed++;
2039 (void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
2040 } else if (version > cb->cb_version) {
2041 /* can't downgrade */
2042 (void) printf(gettext("%s: can not be downgraded; "
2043 "it is already at version %u\n"),
2044 zfs_get_name(zhp), version);
2045 cb->cb_numfailed++;
2046 } else {
2047 cb->cb_numsamegraded++;
2049 return (0);
2053 * zfs upgrade
2054 * zfs upgrade -v
2055 * zfs upgrade [-r] [-V <version>] <-a | filesystem>
2057 static int
2058 zfs_do_upgrade(int argc, char **argv)
2060 boolean_t all = B_FALSE;
2061 boolean_t showversions = B_FALSE;
2062 int ret = 0;
2063 upgrade_cbdata_t cb = { 0 };
2064 char c;
2065 int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2067 /* check options */
2068 while ((c = getopt(argc, argv, "rvV:a")) != -1) {
2069 switch (c) {
2070 case 'r':
2071 flags |= ZFS_ITER_RECURSE;
2072 break;
2073 case 'v':
2074 showversions = B_TRUE;
2075 break;
2076 case 'V':
2077 if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
2078 optarg, &cb.cb_version) != 0) {
2079 (void) fprintf(stderr,
2080 gettext("invalid version %s\n"), optarg);
2081 usage(B_FALSE);
2083 break;
2084 case 'a':
2085 all = B_TRUE;
2086 break;
2087 case '?':
2088 default:
2089 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2090 optopt);
2091 usage(B_FALSE);
2095 argc -= optind;
2096 argv += optind;
2098 if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
2099 usage(B_FALSE);
2100 if (showversions && (flags & ZFS_ITER_RECURSE || all ||
2101 cb.cb_version || argc))
2102 usage(B_FALSE);
2103 if ((all || argc) && (showversions))
2104 usage(B_FALSE);
2105 if (all && argc)
2106 usage(B_FALSE);
2108 if (showversions) {
2109 /* Show info on available versions. */
2110 (void) printf(gettext("The following filesystem versions are "
2111 "supported:\n\n"));
2112 (void) printf(gettext("VER DESCRIPTION\n"));
2113 (void) printf("--- -----------------------------------------"
2114 "---------------\n");
2115 (void) printf(gettext(" 1 Initial ZFS filesystem version\n"));
2116 (void) printf(gettext(" 2 Enhanced directory entries\n"));
2117 (void) printf(gettext(" 3 Case insensitive and filesystem "
2118 "user identifier (FUID)\n"));
2119 (void) printf(gettext(" 4 userquota, groupquota "
2120 "properties\n"));
2121 (void) printf(gettext(" 5 System attributes\n"));
2122 (void) printf(gettext("\nFor more information on a particular "
2123 "version, including supported releases,\n"));
2124 (void) printf("see the ZFS Administration Guide.\n\n");
2125 ret = 0;
2126 } else if (argc || all) {
2127 /* Upgrade filesystems */
2128 if (cb.cb_version == 0)
2129 cb.cb_version = ZPL_VERSION;
2130 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
2131 NULL, NULL, 0, upgrade_set_callback, &cb);
2132 (void) printf(gettext("%llu filesystems upgraded\n"),
2133 cb.cb_numupgraded);
2134 if (cb.cb_numsamegraded) {
2135 (void) printf(gettext("%llu filesystems already at "
2136 "this version\n"),
2137 cb.cb_numsamegraded);
2139 if (cb.cb_numfailed != 0)
2140 ret = 1;
2141 } else {
2142 /* List old-version filesytems */
2143 boolean_t found;
2144 (void) printf(gettext("This system is currently running "
2145 "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
2147 flags |= ZFS_ITER_RECURSE;
2148 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2149 NULL, NULL, 0, upgrade_list_callback, &cb);
2151 found = cb.cb_foundone;
2152 cb.cb_foundone = B_FALSE;
2153 cb.cb_newer = B_TRUE;
2155 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2156 NULL, NULL, 0, upgrade_list_callback, &cb);
2158 if (!cb.cb_foundone && !found) {
2159 (void) printf(gettext("All filesystems are "
2160 "formatted with the current version.\n"));
2164 return (ret);
2168 * zfs userspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2169 * [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2170 * zfs groupspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2171 * [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2173 * -H Scripted mode; elide headers and separate columns by tabs.
2174 * -i Translate SID to POSIX ID.
2175 * -n Print numeric ID instead of user/group name.
2176 * -o Control which fields to display.
2177 * -p Use exact (parsable) numeric output.
2178 * -s Specify sort columns, descending order.
2179 * -S Specify sort columns, ascending order.
2180 * -t Control which object types to display.
2182 * Displays space consumed by, and quotas on, each user in the specified
2183 * filesystem or snapshot.
2186 /* us_field_types, us_field_hdr and us_field_names should be kept in sync */
2187 enum us_field_types {
2188 USFIELD_TYPE,
2189 USFIELD_NAME,
2190 USFIELD_USED,
2191 USFIELD_QUOTA
2193 static char *us_field_hdr[] = { "TYPE", "NAME", "USED", "QUOTA" };
2194 static char *us_field_names[] = { "type", "name", "used", "quota" };
2195 #define USFIELD_LAST (sizeof (us_field_names) / sizeof (char *))
2197 #define USTYPE_PSX_GRP (1 << 0)
2198 #define USTYPE_PSX_USR (1 << 1)
2199 #define USTYPE_SMB_GRP (1 << 2)
2200 #define USTYPE_SMB_USR (1 << 3)
2201 #define USTYPE_ALL \
2202 (USTYPE_PSX_GRP | USTYPE_PSX_USR | USTYPE_SMB_GRP | USTYPE_SMB_USR)
2204 static int us_type_bits[] = {
2205 USTYPE_PSX_GRP,
2206 USTYPE_PSX_USR,
2207 USTYPE_SMB_GRP,
2208 USTYPE_SMB_USR,
2209 USTYPE_ALL
2211 static char *us_type_names[] = { "posixgroup", "posixuser", "smbgroup",
2212 "smbuser", "all" };
2214 typedef struct us_node {
2215 nvlist_t *usn_nvl;
2216 uu_avl_node_t usn_avlnode;
2217 uu_list_node_t usn_listnode;
2218 } us_node_t;
2220 typedef struct us_cbdata {
2221 nvlist_t **cb_nvlp;
2222 uu_avl_pool_t *cb_avl_pool;
2223 uu_avl_t *cb_avl;
2224 boolean_t cb_numname;
2225 boolean_t cb_nicenum;
2226 boolean_t cb_sid2posix;
2227 zfs_userquota_prop_t cb_prop;
2228 zfs_sort_column_t *cb_sortcol;
2229 size_t cb_width[USFIELD_LAST];
2230 } us_cbdata_t;
2232 static boolean_t us_populated = B_FALSE;
2234 typedef struct {
2235 zfs_sort_column_t *si_sortcol;
2236 boolean_t si_numname;
2237 } us_sort_info_t;
2239 static int
2240 us_field_index(char *field)
2242 int i;
2244 for (i = 0; i < USFIELD_LAST; i++) {
2245 if (strcmp(field, us_field_names[i]) == 0)
2246 return (i);
2249 return (-1);
2252 static int
2253 us_compare(const void *larg, const void *rarg, void *unused)
2255 const us_node_t *l = larg;
2256 const us_node_t *r = rarg;
2257 us_sort_info_t *si = (us_sort_info_t *)unused;
2258 zfs_sort_column_t *sortcol = si->si_sortcol;
2259 boolean_t numname = si->si_numname;
2260 nvlist_t *lnvl = l->usn_nvl;
2261 nvlist_t *rnvl = r->usn_nvl;
2262 int rc = 0;
2263 boolean_t lvb, rvb;
2265 for (; sortcol != NULL; sortcol = sortcol->sc_next) {
2266 char *lvstr = "";
2267 char *rvstr = "";
2268 uint32_t lv32 = 0;
2269 uint32_t rv32 = 0;
2270 uint64_t lv64 = 0;
2271 uint64_t rv64 = 0;
2272 zfs_prop_t prop = sortcol->sc_prop;
2273 const char *propname = NULL;
2274 boolean_t reverse = sortcol->sc_reverse;
2276 switch (prop) {
2277 case ZFS_PROP_TYPE:
2278 propname = "type";
2279 (void) nvlist_lookup_uint32(lnvl, propname, &lv32);
2280 (void) nvlist_lookup_uint32(rnvl, propname, &rv32);
2281 if (rv32 != lv32)
2282 rc = (rv32 < lv32) ? 1 : -1;
2283 break;
2284 case ZFS_PROP_NAME:
2285 propname = "name";
2286 if (numname) {
2287 (void) nvlist_lookup_uint64(lnvl, propname,
2288 &lv64);
2289 (void) nvlist_lookup_uint64(rnvl, propname,
2290 &rv64);
2291 if (rv64 != lv64)
2292 rc = (rv64 < lv64) ? 1 : -1;
2293 } else {
2294 (void) nvlist_lookup_string(lnvl, propname,
2295 &lvstr);
2296 (void) nvlist_lookup_string(rnvl, propname,
2297 &rvstr);
2298 rc = strcmp(lvstr, rvstr);
2300 break;
2301 case ZFS_PROP_USED:
2302 case ZFS_PROP_QUOTA:
2303 if (!us_populated)
2304 break;
2305 if (prop == ZFS_PROP_USED)
2306 propname = "used";
2307 else
2308 propname = "quota";
2309 (void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2310 (void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2311 if (rv64 != lv64)
2312 rc = (rv64 < lv64) ? 1 : -1;
2313 break;
2316 if (rc != 0) {
2317 if (rc < 0)
2318 return (reverse ? 1 : -1);
2319 else
2320 return (reverse ? -1 : 1);
2325 * If entries still seem to be the same, check if they are of the same
2326 * type (smbentity is added only if we are doing SID to POSIX ID
2327 * translation where we can have duplicate type/name combinations).
2329 if (nvlist_lookup_boolean_value(lnvl, "smbentity", &lvb) == 0 &&
2330 nvlist_lookup_boolean_value(rnvl, "smbentity", &rvb) == 0 &&
2331 lvb != rvb)
2332 return (lvb < rvb ? -1 : 1);
2334 return (0);
2337 static inline const char *
2338 us_type2str(unsigned field_type)
2340 switch (field_type) {
2341 case USTYPE_PSX_USR:
2342 return ("POSIX User");
2343 case USTYPE_PSX_GRP:
2344 return ("POSIX Group");
2345 case USTYPE_SMB_USR:
2346 return ("SMB User");
2347 case USTYPE_SMB_GRP:
2348 return ("SMB Group");
2349 default:
2350 return ("Undefined");
2354 static int
2355 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2357 us_cbdata_t *cb = (us_cbdata_t *)arg;
2358 zfs_userquota_prop_t prop = cb->cb_prop;
2359 char *name = NULL;
2360 char *propname;
2361 char sizebuf[32];
2362 us_node_t *node;
2363 uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2364 uu_avl_t *avl = cb->cb_avl;
2365 uu_avl_index_t idx;
2366 nvlist_t *props;
2367 us_node_t *n;
2368 zfs_sort_column_t *sortcol = cb->cb_sortcol;
2369 unsigned type;
2370 const char *typestr;
2371 size_t namelen;
2372 size_t typelen;
2373 size_t sizelen;
2374 int typeidx, nameidx, sizeidx;
2375 us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
2376 boolean_t smbentity = B_FALSE;
2378 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
2379 nomem();
2380 node = safe_malloc(sizeof (us_node_t));
2381 uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
2382 node->usn_nvl = props;
2384 if (domain != NULL && domain[0] != '\0') {
2385 /* SMB */
2386 char sid[ZFS_MAXNAMELEN + 32];
2387 uid_t id;
2388 int err;
2389 int flag = IDMAP_REQ_FLG_USE_CACHE;
2391 smbentity = B_TRUE;
2393 (void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
2395 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2396 type = USTYPE_SMB_GRP;
2397 err = sid_to_id(sid, B_FALSE, &id);
2398 } else {
2399 type = USTYPE_SMB_USR;
2400 err = sid_to_id(sid, B_TRUE, &id);
2403 if (err == 0) {
2404 rid = id;
2405 if (!cb->cb_sid2posix) {
2406 if (type == USTYPE_SMB_USR) {
2407 (void) idmap_getwinnamebyuid(rid, flag,
2408 &name, NULL);
2409 } else {
2410 (void) idmap_getwinnamebygid(rid, flag,
2411 &name, NULL);
2413 if (name == NULL)
2414 name = sid;
2419 if (cb->cb_sid2posix || domain == NULL || domain[0] == '\0') {
2420 /* POSIX or -i */
2421 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2422 type = USTYPE_PSX_GRP;
2423 if (!cb->cb_numname) {
2424 struct group *g;
2426 if ((g = getgrgid(rid)) != NULL)
2427 name = g->gr_name;
2429 } else {
2430 type = USTYPE_PSX_USR;
2431 if (!cb->cb_numname) {
2432 struct passwd *p;
2434 if ((p = getpwuid(rid)) != NULL)
2435 name = p->pw_name;
2441 * Make sure that the type/name combination is unique when doing
2442 * SID to POSIX ID translation (hence changing the type from SMB to
2443 * POSIX).
2445 if (cb->cb_sid2posix &&
2446 nvlist_add_boolean_value(props, "smbentity", smbentity) != 0)
2447 nomem();
2449 /* Calculate/update width of TYPE field */
2450 typestr = us_type2str(type);
2451 typelen = strlen(gettext(typestr));
2452 typeidx = us_field_index("type");
2453 if (typelen > cb->cb_width[typeidx])
2454 cb->cb_width[typeidx] = typelen;
2455 if (nvlist_add_uint32(props, "type", type) != 0)
2456 nomem();
2458 /* Calculate/update width of NAME field */
2459 if ((cb->cb_numname && cb->cb_sid2posix) || name == NULL) {
2460 if (nvlist_add_uint64(props, "name", rid) != 0)
2461 nomem();
2462 namelen = snprintf(NULL, 0, "%u", rid);
2463 } else {
2464 if (nvlist_add_string(props, "name", name) != 0)
2465 nomem();
2466 namelen = strlen(name);
2468 nameidx = us_field_index("name");
2469 if (namelen > cb->cb_width[nameidx])
2470 cb->cb_width[nameidx] = namelen;
2473 * Check if this type/name combination is in the list and update it;
2474 * otherwise add new node to the list.
2476 if ((n = uu_avl_find(avl, node, &sortinfo, &idx)) == NULL) {
2477 uu_avl_insert(avl, node, idx);
2478 } else {
2479 nvlist_free(props);
2480 free(node);
2481 node = n;
2482 props = node->usn_nvl;
2485 /* Calculate/update width of USED/QUOTA fields */
2486 if (cb->cb_nicenum)
2487 zfs_nicenum(space, sizebuf, sizeof (sizebuf));
2488 else
2489 (void) snprintf(sizebuf, sizeof (sizebuf), "%llu", space);
2490 sizelen = strlen(sizebuf);
2491 if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED) {
2492 propname = "used";
2493 if (!nvlist_exists(props, "quota"))
2494 (void) nvlist_add_uint64(props, "quota", 0);
2495 } else {
2496 propname = "quota";
2497 if (!nvlist_exists(props, "used"))
2498 (void) nvlist_add_uint64(props, "used", 0);
2500 sizeidx = us_field_index(propname);
2501 if (sizelen > cb->cb_width[sizeidx])
2502 cb->cb_width[sizeidx] = sizelen;
2504 if (nvlist_add_uint64(props, propname, space) != 0)
2505 nomem();
2507 return (0);
2510 static void
2511 print_us_node(boolean_t scripted, boolean_t parsable, int *fields, int types,
2512 size_t *width, us_node_t *node)
2514 nvlist_t *nvl = node->usn_nvl;
2515 char valstr[ZFS_MAXNAMELEN];
2516 boolean_t first = B_TRUE;
2517 int cfield = 0;
2518 int field;
2519 uint32_t ustype;
2521 /* Check type */
2522 (void) nvlist_lookup_uint32(nvl, "type", &ustype);
2523 if (!(ustype & types))
2524 return;
2526 while ((field = fields[cfield]) != USFIELD_LAST) {
2527 nvpair_t *nvp = NULL;
2528 data_type_t type;
2529 uint32_t val32;
2530 uint64_t val64;
2531 char *strval = NULL;
2533 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
2534 if (strcmp(nvpair_name(nvp),
2535 us_field_names[field]) == 0)
2536 break;
2539 type = nvpair_type(nvp);
2540 switch (type) {
2541 case DATA_TYPE_UINT32:
2542 (void) nvpair_value_uint32(nvp, &val32);
2543 break;
2544 case DATA_TYPE_UINT64:
2545 (void) nvpair_value_uint64(nvp, &val64);
2546 break;
2547 case DATA_TYPE_STRING:
2548 (void) nvpair_value_string(nvp, &strval);
2549 break;
2550 default:
2551 (void) fprintf(stderr, "invalid data type\n");
2554 switch (field) {
2555 case USFIELD_TYPE:
2556 strval = (char *)us_type2str(val32);
2557 break;
2558 case USFIELD_NAME:
2559 if (type == DATA_TYPE_UINT64) {
2560 (void) sprintf(valstr, "%llu", val64);
2561 strval = valstr;
2563 break;
2564 case USFIELD_USED:
2565 case USFIELD_QUOTA:
2566 if (type == DATA_TYPE_UINT64) {
2567 if (parsable) {
2568 (void) sprintf(valstr, "%llu", val64);
2569 } else {
2570 zfs_nicenum(val64, valstr,
2571 sizeof (valstr));
2573 if (field == USFIELD_QUOTA &&
2574 strcmp(valstr, "0") == 0)
2575 strval = "none";
2576 else
2577 strval = valstr;
2579 break;
2582 if (!first) {
2583 if (scripted)
2584 (void) printf("\t");
2585 else
2586 (void) printf(" ");
2588 if (scripted)
2589 (void) printf("%s", strval);
2590 else if (field == USFIELD_TYPE || field == USFIELD_NAME)
2591 (void) printf("%-*s", width[field], strval);
2592 else
2593 (void) printf("%*s", width[field], strval);
2595 first = B_FALSE;
2596 cfield++;
2599 (void) printf("\n");
2602 static void
2603 print_us(boolean_t scripted, boolean_t parsable, int *fields, int types,
2604 size_t *width, boolean_t rmnode, uu_avl_t *avl)
2606 us_node_t *node;
2607 const char *col;
2608 int cfield = 0;
2609 int field;
2611 if (!scripted) {
2612 boolean_t first = B_TRUE;
2614 while ((field = fields[cfield]) != USFIELD_LAST) {
2615 col = gettext(us_field_hdr[field]);
2616 if (field == USFIELD_TYPE || field == USFIELD_NAME) {
2617 (void) printf(first ? "%-*s" : " %-*s",
2618 width[field], col);
2619 } else {
2620 (void) printf(first ? "%*s" : " %*s",
2621 width[field], col);
2623 first = B_FALSE;
2624 cfield++;
2626 (void) printf("\n");
2629 for (node = uu_avl_first(avl); node; node = uu_avl_next(avl, node)) {
2630 print_us_node(scripted, parsable, fields, types, width, node);
2631 if (rmnode)
2632 nvlist_free(node->usn_nvl);
2636 static int
2637 zfs_do_userspace(int argc, char **argv)
2639 zfs_handle_t *zhp;
2640 zfs_userquota_prop_t p;
2641 uu_avl_pool_t *avl_pool;
2642 uu_avl_t *avl_tree;
2643 uu_avl_walk_t *walk;
2644 char *delim;
2645 char deffields[] = "type,name,used,quota";
2646 char *ofield = NULL;
2647 char *tfield = NULL;
2648 int cfield = 0;
2649 int fields[256];
2650 int i;
2651 boolean_t scripted = B_FALSE;
2652 boolean_t prtnum = B_FALSE;
2653 boolean_t parsable = B_FALSE;
2654 boolean_t sid2posix = B_FALSE;
2655 int ret = 0;
2656 int c;
2657 zfs_sort_column_t *sortcol = NULL;
2658 int types = USTYPE_PSX_USR | USTYPE_SMB_USR;
2659 us_cbdata_t cb;
2660 us_node_t *node;
2661 us_node_t *rmnode;
2662 uu_list_pool_t *listpool;
2663 uu_list_t *list;
2664 uu_avl_index_t idx = 0;
2665 uu_list_index_t idx2 = 0;
2667 if (argc < 2)
2668 usage(B_FALSE);
2670 if (strcmp(argv[0], "groupspace") == 0)
2671 /* Toggle default group types */
2672 types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
2674 while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
2675 switch (c) {
2676 case 'n':
2677 prtnum = B_TRUE;
2678 break;
2679 case 'H':
2680 scripted = B_TRUE;
2681 break;
2682 case 'p':
2683 parsable = B_TRUE;
2684 break;
2685 case 'o':
2686 ofield = optarg;
2687 break;
2688 case 's':
2689 case 'S':
2690 if (zfs_add_sort_column(&sortcol, optarg,
2691 c == 's' ? B_FALSE : B_TRUE) != 0) {
2692 (void) fprintf(stderr,
2693 gettext("invalid field '%s'\n"), optarg);
2694 usage(B_FALSE);
2696 break;
2697 case 't':
2698 tfield = optarg;
2699 break;
2700 case 'i':
2701 sid2posix = B_TRUE;
2702 break;
2703 case ':':
2704 (void) fprintf(stderr, gettext("missing argument for "
2705 "'%c' option\n"), optopt);
2706 usage(B_FALSE);
2707 break;
2708 case '?':
2709 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2710 optopt);
2711 usage(B_FALSE);
2715 argc -= optind;
2716 argv += optind;
2718 if (argc < 1) {
2719 (void) fprintf(stderr, gettext("missing dataset name\n"));
2720 usage(B_FALSE);
2722 if (argc > 1) {
2723 (void) fprintf(stderr, gettext("too many arguments\n"));
2724 usage(B_FALSE);
2727 /* Use default output fields if not specified using -o */
2728 if (ofield == NULL)
2729 ofield = deffields;
2730 do {
2731 if ((delim = strchr(ofield, ',')) != NULL)
2732 *delim = '\0';
2733 if ((fields[cfield++] = us_field_index(ofield)) == -1) {
2734 (void) fprintf(stderr, gettext("invalid type '%s' "
2735 "for -o option\n"), ofield);
2736 return (-1);
2738 if (delim != NULL)
2739 ofield = delim + 1;
2740 } while (delim != NULL);
2741 fields[cfield] = USFIELD_LAST;
2743 /* Override output types (-t option) */
2744 if (tfield != NULL) {
2745 types = 0;
2747 do {
2748 boolean_t found = B_FALSE;
2750 if ((delim = strchr(tfield, ',')) != NULL)
2751 *delim = '\0';
2752 for (i = 0; i < sizeof (us_type_bits) / sizeof (int);
2753 i++) {
2754 if (strcmp(tfield, us_type_names[i]) == 0) {
2755 found = B_TRUE;
2756 types |= us_type_bits[i];
2757 break;
2760 if (!found) {
2761 (void) fprintf(stderr, gettext("invalid type "
2762 "'%s' for -t option\n"), tfield);
2763 return (-1);
2765 if (delim != NULL)
2766 tfield = delim + 1;
2767 } while (delim != NULL);
2770 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
2771 return (1);
2773 if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
2774 offsetof(us_node_t, usn_avlnode), us_compare, UU_DEFAULT)) == NULL)
2775 nomem();
2776 if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
2777 nomem();
2779 /* Always add default sorting columns */
2780 (void) zfs_add_sort_column(&sortcol, "type", B_FALSE);
2781 (void) zfs_add_sort_column(&sortcol, "name", B_FALSE);
2783 cb.cb_sortcol = sortcol;
2784 cb.cb_numname = prtnum;
2785 cb.cb_nicenum = !parsable;
2786 cb.cb_avl_pool = avl_pool;
2787 cb.cb_avl = avl_tree;
2788 cb.cb_sid2posix = sid2posix;
2790 for (i = 0; i < USFIELD_LAST; i++)
2791 cb.cb_width[i] = strlen(gettext(us_field_hdr[i]));
2793 for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
2794 if (((p == ZFS_PROP_USERUSED || p == ZFS_PROP_USERQUOTA) &&
2795 !(types & (USTYPE_PSX_USR | USTYPE_SMB_USR))) ||
2796 ((p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA) &&
2797 !(types & (USTYPE_PSX_GRP | USTYPE_SMB_GRP))))
2798 continue;
2799 cb.cb_prop = p;
2800 if ((ret = zfs_userspace(zhp, p, userspace_cb, &cb)) != 0)
2801 return (ret);
2804 /* Sort the list */
2805 if ((node = uu_avl_first(avl_tree)) == NULL)
2806 return (0);
2808 us_populated = B_TRUE;
2810 listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
2811 offsetof(us_node_t, usn_listnode), NULL, UU_DEFAULT);
2812 list = uu_list_create(listpool, NULL, UU_DEFAULT);
2813 uu_list_node_init(node, &node->usn_listnode, listpool);
2815 while (node != NULL) {
2816 rmnode = node;
2817 node = uu_avl_next(avl_tree, node);
2818 uu_avl_remove(avl_tree, rmnode);
2819 if (uu_list_find(list, rmnode, NULL, &idx2) == NULL)
2820 uu_list_insert(list, rmnode, idx2);
2823 for (node = uu_list_first(list); node != NULL;
2824 node = uu_list_next(list, node)) {
2825 us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
2827 if (uu_avl_find(avl_tree, node, &sortinfo, &idx) == NULL)
2828 uu_avl_insert(avl_tree, node, idx);
2831 uu_list_destroy(list);
2832 uu_list_pool_destroy(listpool);
2834 /* Print and free node nvlist memory */
2835 print_us(scripted, parsable, fields, types, cb.cb_width, B_TRUE,
2836 cb.cb_avl);
2838 zfs_free_sort_columns(sortcol);
2840 /* Clean up the AVL tree */
2841 if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
2842 nomem();
2844 while ((node = uu_avl_walk_next(walk)) != NULL) {
2845 uu_avl_remove(cb.cb_avl, node);
2846 free(node);
2849 uu_avl_walk_end(walk);
2850 uu_avl_destroy(avl_tree);
2851 uu_avl_pool_destroy(avl_pool);
2853 return (ret);
2857 * list [-Hp][-r|-d max] [-o property[,...]] [-s property] ... [-S property] ...
2858 * [-t type[,...]] [filesystem|volume|snapshot] ...
2860 * -H Scripted mode; elide headers and separate columns by tabs.
2861 * -p Display values in parsable (literal) format.
2862 * -r Recurse over all children.
2863 * -d Limit recursion by depth.
2864 * -o Control which fields to display.
2865 * -s Specify sort columns, descending order.
2866 * -S Specify sort columns, ascending order.
2867 * -t Control which object types to display.
2869 * When given no arguments, list all filesystems in the system.
2870 * Otherwise, list the specified datasets, optionally recursing down them if
2871 * '-r' is specified.
2873 typedef struct list_cbdata {
2874 boolean_t cb_first;
2875 boolean_t cb_literal;
2876 boolean_t cb_scripted;
2877 zprop_list_t *cb_proplist;
2878 } list_cbdata_t;
2881 * Given a list of columns to display, output appropriate headers for each one.
2883 static void
2884 print_header(list_cbdata_t *cb)
2886 zprop_list_t *pl = cb->cb_proplist;
2887 char headerbuf[ZFS_MAXPROPLEN];
2888 const char *header;
2889 int i;
2890 boolean_t first = B_TRUE;
2891 boolean_t right_justify;
2893 for (; pl != NULL; pl = pl->pl_next) {
2894 if (!first) {
2895 (void) printf(" ");
2896 } else {
2897 first = B_FALSE;
2900 right_justify = B_FALSE;
2901 if (pl->pl_prop != ZPROP_INVAL) {
2902 header = zfs_prop_column_name(pl->pl_prop);
2903 right_justify = zfs_prop_align_right(pl->pl_prop);
2904 } else {
2905 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
2906 headerbuf[i] = toupper(pl->pl_user_prop[i]);
2907 headerbuf[i] = '\0';
2908 header = headerbuf;
2911 if (pl->pl_next == NULL && !right_justify)
2912 (void) printf("%s", header);
2913 else if (right_justify)
2914 (void) printf("%*s", pl->pl_width, header);
2915 else
2916 (void) printf("%-*s", pl->pl_width, header);
2919 (void) printf("\n");
2923 * Given a dataset and a list of fields, print out all the properties according
2924 * to the described layout.
2926 static void
2927 print_dataset(zfs_handle_t *zhp, list_cbdata_t *cb)
2929 zprop_list_t *pl = cb->cb_proplist;
2930 boolean_t first = B_TRUE;
2931 char property[ZFS_MAXPROPLEN];
2932 nvlist_t *userprops = zfs_get_user_props(zhp);
2933 nvlist_t *propval;
2934 char *propstr;
2935 boolean_t right_justify;
2937 for (; pl != NULL; pl = pl->pl_next) {
2938 if (!first) {
2939 if (cb->cb_scripted)
2940 (void) printf("\t");
2941 else
2942 (void) printf(" ");
2943 } else {
2944 first = B_FALSE;
2947 if (pl->pl_prop != ZPROP_INVAL) {
2948 if (zfs_prop_get(zhp, pl->pl_prop, property,
2949 sizeof (property), NULL, NULL, 0,
2950 cb->cb_literal) != 0)
2951 propstr = "-";
2952 else
2953 propstr = property;
2954 right_justify = zfs_prop_align_right(pl->pl_prop);
2955 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
2956 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
2957 property, sizeof (property), cb->cb_literal) != 0)
2958 propstr = "-";
2959 else
2960 propstr = property;
2961 right_justify = B_TRUE;
2962 } else if (zfs_prop_written(pl->pl_user_prop)) {
2963 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
2964 property, sizeof (property), cb->cb_literal) != 0)
2965 propstr = "-";
2966 else
2967 propstr = property;
2968 right_justify = B_TRUE;
2969 } else {
2970 if (nvlist_lookup_nvlist(userprops,
2971 pl->pl_user_prop, &propval) != 0)
2972 propstr = "-";
2973 else
2974 verify(nvlist_lookup_string(propval,
2975 ZPROP_VALUE, &propstr) == 0);
2976 right_justify = B_FALSE;
2980 * If this is being called in scripted mode, or if this is the
2981 * last column and it is left-justified, don't include a width
2982 * format specifier.
2984 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
2985 (void) printf("%s", propstr);
2986 else if (right_justify)
2987 (void) printf("%*s", pl->pl_width, propstr);
2988 else
2989 (void) printf("%-*s", pl->pl_width, propstr);
2992 (void) printf("\n");
2996 * Generic callback function to list a dataset or snapshot.
2998 static int
2999 list_callback(zfs_handle_t *zhp, void *data)
3001 list_cbdata_t *cbp = data;
3003 if (cbp->cb_first) {
3004 if (!cbp->cb_scripted)
3005 print_header(cbp);
3006 cbp->cb_first = B_FALSE;
3009 print_dataset(zhp, cbp);
3011 return (0);
3014 static int
3015 zfs_do_list(int argc, char **argv)
3017 int c;
3018 static char default_fields[] =
3019 "name,used,available,referenced,mountpoint";
3020 int types = ZFS_TYPE_DATASET;
3021 boolean_t types_specified = B_FALSE;
3022 char *fields = NULL;
3023 list_cbdata_t cb = { 0 };
3024 char *value;
3025 int limit = 0;
3026 int ret = 0;
3027 zfs_sort_column_t *sortcol = NULL;
3028 int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
3030 /* check options */
3031 while ((c = getopt(argc, argv, "HS:d:o:prs:t:")) != -1) {
3032 switch (c) {
3033 case 'o':
3034 fields = optarg;
3035 break;
3036 case 'p':
3037 cb.cb_literal = B_TRUE;
3038 flags |= ZFS_ITER_LITERAL_PROPS;
3039 break;
3040 case 'd':
3041 limit = parse_depth(optarg, &flags);
3042 break;
3043 case 'r':
3044 flags |= ZFS_ITER_RECURSE;
3045 break;
3046 case 'H':
3047 cb.cb_scripted = B_TRUE;
3048 break;
3049 case 's':
3050 if (zfs_add_sort_column(&sortcol, optarg,
3051 B_FALSE) != 0) {
3052 (void) fprintf(stderr,
3053 gettext("invalid property '%s'\n"), optarg);
3054 usage(B_FALSE);
3056 break;
3057 case 'S':
3058 if (zfs_add_sort_column(&sortcol, optarg,
3059 B_TRUE) != 0) {
3060 (void) fprintf(stderr,
3061 gettext("invalid property '%s'\n"), optarg);
3062 usage(B_FALSE);
3064 break;
3065 case 't':
3066 types = 0;
3067 types_specified = B_TRUE;
3068 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
3069 while (*optarg != '\0') {
3070 static char *type_subopts[] = { "filesystem",
3071 "volume", "snapshot", "snap", "bookmark",
3072 "all", NULL };
3074 switch (getsubopt(&optarg, type_subopts,
3075 &value)) {
3076 case 0:
3077 types |= ZFS_TYPE_FILESYSTEM;
3078 break;
3079 case 1:
3080 types |= ZFS_TYPE_VOLUME;
3081 break;
3082 case 2:
3083 case 3:
3084 types |= ZFS_TYPE_SNAPSHOT;
3085 break;
3086 case 4:
3087 types |= ZFS_TYPE_BOOKMARK;
3088 break;
3089 case 5:
3090 types = ZFS_TYPE_DATASET |
3091 ZFS_TYPE_BOOKMARK;
3092 break;
3093 default:
3094 (void) fprintf(stderr,
3095 gettext("invalid type '%s'\n"),
3096 value);
3097 usage(B_FALSE);
3100 break;
3101 case ':':
3102 (void) fprintf(stderr, gettext("missing argument for "
3103 "'%c' option\n"), optopt);
3104 usage(B_FALSE);
3105 break;
3106 case '?':
3107 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3108 optopt);
3109 usage(B_FALSE);
3113 argc -= optind;
3114 argv += optind;
3116 if (fields == NULL)
3117 fields = default_fields;
3120 * If "-o space" and no types were specified, don't display snapshots.
3122 if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3123 types &= ~ZFS_TYPE_SNAPSHOT;
3126 * If the user specifies '-o all', the zprop_get_list() doesn't
3127 * normally include the name of the dataset. For 'zfs list', we always
3128 * want this property to be first.
3130 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3131 != 0)
3132 usage(B_FALSE);
3134 cb.cb_first = B_TRUE;
3136 ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
3137 limit, list_callback, &cb);
3139 zprop_free_list(cb.cb_proplist);
3140 zfs_free_sort_columns(sortcol);
3142 if (ret == 0 && cb.cb_first && !cb.cb_scripted)
3143 (void) printf(gettext("no datasets available\n"));
3145 return (ret);
3149 * zfs rename [-f] <fs | snap | vol> <fs | snap | vol>
3150 * zfs rename [-f] -p <fs | vol> <fs | vol>
3151 * zfs rename -r <snap> <snap>
3153 * Renames the given dataset to another of the same type.
3155 * The '-p' flag creates all the non-existing ancestors of the target first.
3157 /* ARGSUSED */
3158 static int
3159 zfs_do_rename(int argc, char **argv)
3161 zfs_handle_t *zhp;
3162 int c;
3163 int ret = 0;
3164 boolean_t recurse = B_FALSE;
3165 boolean_t parents = B_FALSE;
3166 boolean_t force_unmount = B_FALSE;
3168 /* check options */
3169 while ((c = getopt(argc, argv, "prf")) != -1) {
3170 switch (c) {
3171 case 'p':
3172 parents = B_TRUE;
3173 break;
3174 case 'r':
3175 recurse = B_TRUE;
3176 break;
3177 case 'f':
3178 force_unmount = B_TRUE;
3179 break;
3180 case '?':
3181 default:
3182 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3183 optopt);
3184 usage(B_FALSE);
3188 argc -= optind;
3189 argv += optind;
3191 /* check number of arguments */
3192 if (argc < 1) {
3193 (void) fprintf(stderr, gettext("missing source dataset "
3194 "argument\n"));
3195 usage(B_FALSE);
3197 if (argc < 2) {
3198 (void) fprintf(stderr, gettext("missing target dataset "
3199 "argument\n"));
3200 usage(B_FALSE);
3202 if (argc > 2) {
3203 (void) fprintf(stderr, gettext("too many arguments\n"));
3204 usage(B_FALSE);
3207 if (recurse && parents) {
3208 (void) fprintf(stderr, gettext("-p and -r options are mutually "
3209 "exclusive\n"));
3210 usage(B_FALSE);
3213 if (recurse && strchr(argv[0], '@') == 0) {
3214 (void) fprintf(stderr, gettext("source dataset for recursive "
3215 "rename must be a snapshot\n"));
3216 usage(B_FALSE);
3219 if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
3220 ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
3221 return (1);
3223 /* If we were asked and the name looks good, try to create ancestors. */
3224 if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
3225 zfs_create_ancestors(g_zfs, argv[1]) != 0) {
3226 zfs_close(zhp);
3227 return (1);
3230 ret = (zfs_rename(zhp, argv[1], recurse, force_unmount) != 0);
3232 zfs_close(zhp);
3233 return (ret);
3237 * zfs promote <fs>
3239 * Promotes the given clone fs to be the parent
3241 /* ARGSUSED */
3242 static int
3243 zfs_do_promote(int argc, char **argv)
3245 zfs_handle_t *zhp;
3246 int ret = 0;
3248 /* check options */
3249 if (argc > 1 && argv[1][0] == '-') {
3250 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3251 argv[1][1]);
3252 usage(B_FALSE);
3255 /* check number of arguments */
3256 if (argc < 2) {
3257 (void) fprintf(stderr, gettext("missing clone filesystem"
3258 " argument\n"));
3259 usage(B_FALSE);
3261 if (argc > 2) {
3262 (void) fprintf(stderr, gettext("too many arguments\n"));
3263 usage(B_FALSE);
3266 zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3267 if (zhp == NULL)
3268 return (1);
3270 ret = (zfs_promote(zhp) != 0);
3273 zfs_close(zhp);
3274 return (ret);
3278 * zfs rollback [-rRf] <snapshot>
3280 * -r Delete any intervening snapshots before doing rollback
3281 * -R Delete any snapshots and their clones
3282 * -f ignored for backwards compatability
3284 * Given a filesystem, rollback to a specific snapshot, discarding any changes
3285 * since then and making it the active dataset. If more recent snapshots exist,
3286 * the command will complain unless the '-r' flag is given.
3288 typedef struct rollback_cbdata {
3289 uint64_t cb_create;
3290 boolean_t cb_first;
3291 int cb_doclones;
3292 char *cb_target;
3293 int cb_error;
3294 boolean_t cb_recurse;
3295 } rollback_cbdata_t;
3297 static int
3298 rollback_check_dependent(zfs_handle_t *zhp, void *data)
3300 rollback_cbdata_t *cbp = data;
3302 if (cbp->cb_first && cbp->cb_recurse) {
3303 (void) fprintf(stderr, gettext("cannot rollback to "
3304 "'%s': clones of previous snapshots exist\n"),
3305 cbp->cb_target);
3306 (void) fprintf(stderr, gettext("use '-R' to "
3307 "force deletion of the following clones and "
3308 "dependents:\n"));
3309 cbp->cb_first = 0;
3310 cbp->cb_error = 1;
3313 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
3315 zfs_close(zhp);
3316 return (0);
3320 * Report any snapshots more recent than the one specified. Used when '-r' is
3321 * not specified. We reuse this same callback for the snapshot dependents - if
3322 * 'cb_dependent' is set, then this is a dependent and we should report it
3323 * without checking the transaction group.
3325 static int
3326 rollback_check(zfs_handle_t *zhp, void *data)
3328 rollback_cbdata_t *cbp = data;
3330 if (cbp->cb_doclones) {
3331 zfs_close(zhp);
3332 return (0);
3335 if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
3336 if (cbp->cb_first && !cbp->cb_recurse) {
3337 (void) fprintf(stderr, gettext("cannot "
3338 "rollback to '%s': more recent snapshots "
3339 "or bookmarks exist\n"),
3340 cbp->cb_target);
3341 (void) fprintf(stderr, gettext("use '-r' to "
3342 "force deletion of the following "
3343 "snapshots and bookmarks:\n"));
3344 cbp->cb_first = 0;
3345 cbp->cb_error = 1;
3348 if (cbp->cb_recurse) {
3349 if (zfs_iter_dependents(zhp, B_TRUE,
3350 rollback_check_dependent, cbp) != 0) {
3351 zfs_close(zhp);
3352 return (-1);
3354 } else {
3355 (void) fprintf(stderr, "%s\n",
3356 zfs_get_name(zhp));
3359 zfs_close(zhp);
3360 return (0);
3363 static int
3364 zfs_do_rollback(int argc, char **argv)
3366 int ret = 0;
3367 int c;
3368 boolean_t force = B_FALSE;
3369 rollback_cbdata_t cb = { 0 };
3370 zfs_handle_t *zhp, *snap;
3371 char parentname[ZFS_MAXNAMELEN];
3372 char *delim;
3374 /* check options */
3375 while ((c = getopt(argc, argv, "rRf")) != -1) {
3376 switch (c) {
3377 case 'r':
3378 cb.cb_recurse = 1;
3379 break;
3380 case 'R':
3381 cb.cb_recurse = 1;
3382 cb.cb_doclones = 1;
3383 break;
3384 case 'f':
3385 force = B_TRUE;
3386 break;
3387 case '?':
3388 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3389 optopt);
3390 usage(B_FALSE);
3394 argc -= optind;
3395 argv += optind;
3397 /* check number of arguments */
3398 if (argc < 1) {
3399 (void) fprintf(stderr, gettext("missing dataset argument\n"));
3400 usage(B_FALSE);
3402 if (argc > 1) {
3403 (void) fprintf(stderr, gettext("too many arguments\n"));
3404 usage(B_FALSE);
3407 /* open the snapshot */
3408 if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
3409 return (1);
3411 /* open the parent dataset */
3412 (void) strlcpy(parentname, argv[0], sizeof (parentname));
3413 verify((delim = strrchr(parentname, '@')) != NULL);
3414 *delim = '\0';
3415 if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
3416 zfs_close(snap);
3417 return (1);
3421 * Check for more recent snapshots and/or clones based on the presence
3422 * of '-r' and '-R'.
3424 cb.cb_target = argv[0];
3425 cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3426 cb.cb_first = B_TRUE;
3427 cb.cb_error = 0;
3428 if ((ret = zfs_iter_snapshots(zhp, rollback_check, &cb)) != 0)
3429 goto out;
3430 if ((ret = zfs_iter_bookmarks(zhp, rollback_check, &cb)) != 0)
3431 goto out;
3433 if ((ret = cb.cb_error) != 0)
3434 goto out;
3437 * Rollback parent to the given snapshot.
3439 ret = zfs_rollback(zhp, snap, force);
3441 out:
3442 zfs_close(snap);
3443 zfs_close(zhp);
3445 if (ret == 0)
3446 return (0);
3447 else
3448 return (1);
3452 * zfs set property=value ... { fs | snap | vol } ...
3454 * Sets the given properties for all datasets specified on the command line.
3457 static int
3458 set_callback(zfs_handle_t *zhp, void *data)
3460 nvlist_t *props = data;
3462 if (zfs_prop_set_list(zhp, props) != 0) {
3463 switch (libzfs_errno(g_zfs)) {
3464 case EZFS_MOUNTFAILED:
3465 (void) fprintf(stderr, gettext("property may be set "
3466 "but unable to remount filesystem\n"));
3467 break;
3468 case EZFS_SHARENFSFAILED:
3469 (void) fprintf(stderr, gettext("property may be set "
3470 "but unable to reshare filesystem\n"));
3471 break;
3473 return (1);
3475 return (0);
3478 static int
3479 zfs_do_set(int argc, char **argv)
3481 nvlist_t *props = NULL;
3482 int ds_start = -1; /* argv idx of first dataset arg */
3483 int ret = 0;
3485 /* check for options */
3486 if (argc > 1 && argv[1][0] == '-') {
3487 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3488 argv[1][1]);
3489 usage(B_FALSE);
3492 /* check number of arguments */
3493 if (argc < 2) {
3494 (void) fprintf(stderr, gettext("missing arguments\n"));
3495 usage(B_FALSE);
3497 if (argc < 3) {
3498 if (strchr(argv[1], '=') == NULL) {
3499 (void) fprintf(stderr, gettext("missing property=value "
3500 "argument(s)\n"));
3501 } else {
3502 (void) fprintf(stderr, gettext("missing dataset "
3503 "name(s)\n"));
3505 usage(B_FALSE);
3508 /* validate argument order: prop=val args followed by dataset args */
3509 for (int i = 1; i < argc; i++) {
3510 if (strchr(argv[i], '=') != NULL) {
3511 if (ds_start > 0) {
3512 /* out-of-order prop=val argument */
3513 (void) fprintf(stderr, gettext("invalid "
3514 "argument order\n"), i);
3515 usage(B_FALSE);
3517 } else if (ds_start < 0) {
3518 ds_start = i;
3521 if (ds_start < 0) {
3522 (void) fprintf(stderr, gettext("missing dataset name(s)\n"));
3523 usage(B_FALSE);
3526 /* Populate a list of property settings */
3527 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3528 nomem();
3529 for (int i = 1; i < ds_start; i++) {
3530 if ((ret = parseprop(props, argv[i])) != 0)
3531 goto error;
3534 ret = zfs_for_each(argc - ds_start, argv + ds_start, 0,
3535 ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, props);
3537 error:
3538 nvlist_free(props);
3539 return (ret);
3542 typedef struct snap_cbdata {
3543 nvlist_t *sd_nvl;
3544 boolean_t sd_recursive;
3545 const char *sd_snapname;
3546 } snap_cbdata_t;
3548 static int
3549 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
3551 snap_cbdata_t *sd = arg;
3552 char *name;
3553 int rv = 0;
3554 int error;
3556 if (sd->sd_recursive &&
3557 zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
3558 zfs_close(zhp);
3559 return (0);
3562 error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
3563 if (error == -1)
3564 nomem();
3565 fnvlist_add_boolean(sd->sd_nvl, name);
3566 free(name);
3568 if (sd->sd_recursive)
3569 rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
3570 zfs_close(zhp);
3571 return (rv);
3575 * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
3577 * Creates a snapshot with the given name. While functionally equivalent to
3578 * 'zfs create', it is a separate command to differentiate intent.
3580 static int
3581 zfs_do_snapshot(int argc, char **argv)
3583 int ret = 0;
3584 char c;
3585 nvlist_t *props;
3586 snap_cbdata_t sd = { 0 };
3587 boolean_t multiple_snaps = B_FALSE;
3589 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3590 nomem();
3591 if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
3592 nomem();
3594 /* check options */
3595 while ((c = getopt(argc, argv, "ro:")) != -1) {
3596 switch (c) {
3597 case 'o':
3598 if (parseprop(props, optarg) != 0)
3599 return (1);
3600 break;
3601 case 'r':
3602 sd.sd_recursive = B_TRUE;
3603 multiple_snaps = B_TRUE;
3604 break;
3605 case '?':
3606 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3607 optopt);
3608 goto usage;
3612 argc -= optind;
3613 argv += optind;
3615 /* check number of arguments */
3616 if (argc < 1) {
3617 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3618 goto usage;
3621 if (argc > 1)
3622 multiple_snaps = B_TRUE;
3623 for (; argc > 0; argc--, argv++) {
3624 char *atp;
3625 zfs_handle_t *zhp;
3627 atp = strchr(argv[0], '@');
3628 if (atp == NULL)
3629 goto usage;
3630 *atp = '\0';
3631 sd.sd_snapname = atp + 1;
3632 zhp = zfs_open(g_zfs, argv[0],
3633 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3634 if (zhp == NULL)
3635 goto usage;
3636 if (zfs_snapshot_cb(zhp, &sd) != 0)
3637 goto usage;
3640 ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
3641 nvlist_free(sd.sd_nvl);
3642 nvlist_free(props);
3643 if (ret != 0 && multiple_snaps)
3644 (void) fprintf(stderr, gettext("no snapshots were created\n"));
3645 return (ret != 0);
3647 usage:
3648 nvlist_free(sd.sd_nvl);
3649 nvlist_free(props);
3650 usage(B_FALSE);
3651 return (-1);
3655 * Send a backup stream to stdout.
3657 static int
3658 zfs_do_send(int argc, char **argv)
3660 char *fromname = NULL;
3661 char *toname = NULL;
3662 char *resume_token = NULL;
3663 char *cp;
3664 zfs_handle_t *zhp;
3665 sendflags_t flags = { 0 };
3666 int c, err;
3667 nvlist_t *dbgnv = NULL;
3668 boolean_t extraverbose = B_FALSE;
3670 /* check options */
3671 while ((c = getopt(argc, argv, ":i:I:RDpvnPLet:")) != -1) {
3672 switch (c) {
3673 case 'i':
3674 if (fromname)
3675 usage(B_FALSE);
3676 fromname = optarg;
3677 break;
3678 case 'I':
3679 if (fromname)
3680 usage(B_FALSE);
3681 fromname = optarg;
3682 flags.doall = B_TRUE;
3683 break;
3684 case 'R':
3685 flags.replicate = B_TRUE;
3686 break;
3687 case 'p':
3688 flags.props = B_TRUE;
3689 break;
3690 case 'P':
3691 flags.parsable = B_TRUE;
3692 flags.verbose = B_TRUE;
3693 break;
3694 case 'v':
3695 if (flags.verbose)
3696 extraverbose = B_TRUE;
3697 flags.verbose = B_TRUE;
3698 flags.progress = B_TRUE;
3699 break;
3700 case 'D':
3701 flags.dedup = B_TRUE;
3702 break;
3703 case 'n':
3704 flags.dryrun = B_TRUE;
3705 break;
3706 case 'L':
3707 flags.largeblock = B_TRUE;
3708 break;
3709 case 'e':
3710 flags.embed_data = B_TRUE;
3711 break;
3712 case 't':
3713 resume_token = optarg;
3714 break;
3715 case ':':
3716 (void) fprintf(stderr, gettext("missing argument for "
3717 "'%c' option\n"), optopt);
3718 usage(B_FALSE);
3719 break;
3720 case '?':
3721 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3722 optopt);
3723 usage(B_FALSE);
3727 argc -= optind;
3728 argv += optind;
3730 if (resume_token != NULL) {
3731 if (fromname != NULL || flags.replicate || flags.props ||
3732 flags.dedup) {
3733 (void) fprintf(stderr,
3734 gettext("invalid flags combined with -t\n"));
3735 usage(B_FALSE);
3737 if (argc != 0) {
3738 (void) fprintf(stderr, gettext("no additional "
3739 "arguments are permitted with -t\n"));
3740 usage(B_FALSE);
3742 } else {
3743 if (argc < 1) {
3744 (void) fprintf(stderr,
3745 gettext("missing snapshot argument\n"));
3746 usage(B_FALSE);
3748 if (argc > 1) {
3749 (void) fprintf(stderr, gettext("too many arguments\n"));
3750 usage(B_FALSE);
3754 if (!flags.dryrun && isatty(STDOUT_FILENO)) {
3755 (void) fprintf(stderr,
3756 gettext("Error: Stream can not be written to a terminal.\n"
3757 "You must redirect standard output.\n"));
3758 return (1);
3761 if (resume_token != NULL) {
3762 return (zfs_send_resume(g_zfs, &flags, STDOUT_FILENO,
3763 resume_token));
3767 * Special case sending a filesystem, or from a bookmark.
3769 if (strchr(argv[0], '@') == NULL ||
3770 (fromname && strchr(fromname, '#') != NULL)) {
3771 char frombuf[ZFS_MAXNAMELEN];
3772 enum lzc_send_flags lzc_flags = 0;
3774 if (flags.replicate || flags.doall || flags.props ||
3775 flags.dedup || flags.dryrun || flags.verbose ||
3776 flags.progress) {
3777 (void) fprintf(stderr,
3778 gettext("Error: "
3779 "Unsupported flag with filesystem or bookmark.\n"));
3780 return (1);
3783 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
3784 if (zhp == NULL)
3785 return (1);
3787 if (flags.largeblock)
3788 lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
3789 if (flags.embed_data)
3790 lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
3792 if (fromname != NULL &&
3793 (fromname[0] == '#' || fromname[0] == '@')) {
3795 * Incremental source name begins with # or @.
3796 * Default to same fs as target.
3798 (void) strncpy(frombuf, argv[0], sizeof (frombuf));
3799 cp = strchr(frombuf, '@');
3800 if (cp != NULL)
3801 *cp = '\0';
3802 (void) strlcat(frombuf, fromname, sizeof (frombuf));
3803 fromname = frombuf;
3805 err = zfs_send_one(zhp, fromname, STDOUT_FILENO, lzc_flags);
3806 zfs_close(zhp);
3807 return (err != 0);
3810 cp = strchr(argv[0], '@');
3811 *cp = '\0';
3812 toname = cp + 1;
3813 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3814 if (zhp == NULL)
3815 return (1);
3818 * If they specified the full path to the snapshot, chop off
3819 * everything except the short name of the snapshot, but special
3820 * case if they specify the origin.
3822 if (fromname && (cp = strchr(fromname, '@')) != NULL) {
3823 char origin[ZFS_MAXNAMELEN];
3824 zprop_source_t src;
3826 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
3827 origin, sizeof (origin), &src, NULL, 0, B_FALSE);
3829 if (strcmp(origin, fromname) == 0) {
3830 fromname = NULL;
3831 flags.fromorigin = B_TRUE;
3832 } else {
3833 *cp = '\0';
3834 if (cp != fromname && strcmp(argv[0], fromname)) {
3835 (void) fprintf(stderr,
3836 gettext("incremental source must be "
3837 "in same filesystem\n"));
3838 usage(B_FALSE);
3840 fromname = cp + 1;
3841 if (strchr(fromname, '@') || strchr(fromname, '/')) {
3842 (void) fprintf(stderr,
3843 gettext("invalid incremental source\n"));
3844 usage(B_FALSE);
3849 if (flags.replicate && fromname == NULL)
3850 flags.doall = B_TRUE;
3852 err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
3853 extraverbose ? &dbgnv : NULL);
3855 if (extraverbose && dbgnv != NULL) {
3857 * dump_nvlist prints to stdout, but that's been
3858 * redirected to a file. Make it print to stderr
3859 * instead.
3861 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
3862 dump_nvlist(dbgnv, 0);
3863 nvlist_free(dbgnv);
3865 zfs_close(zhp);
3867 return (err != 0);
3871 * Restore a backup stream from stdin.
3873 static int
3874 zfs_do_receive(int argc, char **argv)
3876 int c, err;
3877 recvflags_t flags = { 0 };
3878 boolean_t abort_resumable = B_FALSE;
3880 nvlist_t *props;
3881 nvpair_t *nvp = NULL;
3883 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3884 nomem();
3886 /* check options */
3887 while ((c = getopt(argc, argv, ":o:denuvFsA")) != -1) {
3888 switch (c) {
3889 case 'o':
3890 if (parseprop(props, optarg) != 0)
3891 return (1);
3892 break;
3893 case 'd':
3894 flags.isprefix = B_TRUE;
3895 break;
3896 case 'e':
3897 flags.isprefix = B_TRUE;
3898 flags.istail = B_TRUE;
3899 break;
3900 case 'n':
3901 flags.dryrun = B_TRUE;
3902 break;
3903 case 'u':
3904 flags.nomount = B_TRUE;
3905 break;
3906 case 'v':
3907 flags.verbose = B_TRUE;
3908 break;
3909 case 's':
3910 flags.resumable = B_TRUE;
3911 break;
3912 case 'F':
3913 flags.force = B_TRUE;
3914 break;
3915 case 'A':
3916 abort_resumable = B_TRUE;
3917 break;
3918 case ':':
3919 (void) fprintf(stderr, gettext("missing argument for "
3920 "'%c' option\n"), optopt);
3921 usage(B_FALSE);
3922 break;
3923 case '?':
3924 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3925 optopt);
3926 usage(B_FALSE);
3930 argc -= optind;
3931 argv += optind;
3933 /* check number of arguments */
3934 if (argc < 1) {
3935 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3936 usage(B_FALSE);
3938 if (argc > 1) {
3939 (void) fprintf(stderr, gettext("too many arguments\n"));
3940 usage(B_FALSE);
3943 while ((nvp = nvlist_next_nvpair(props, nvp))) {
3944 if (strcmp(nvpair_name(nvp), "origin") != 0) {
3945 (void) fprintf(stderr, gettext("invalid option"));
3946 usage(B_FALSE);
3950 if (abort_resumable) {
3951 if (flags.isprefix || flags.istail || flags.dryrun ||
3952 flags.resumable || flags.nomount) {
3953 (void) fprintf(stderr, gettext("invalid option"));
3954 usage(B_FALSE);
3957 char namebuf[ZFS_MAXNAMELEN];
3958 (void) snprintf(namebuf, sizeof (namebuf),
3959 "%s/%%recv", argv[0]);
3961 if (zfs_dataset_exists(g_zfs, namebuf,
3962 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) {
3963 zfs_handle_t *zhp = zfs_open(g_zfs,
3964 namebuf, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3965 if (zhp == NULL)
3966 return (1);
3967 err = zfs_destroy(zhp, B_FALSE);
3968 } else {
3969 zfs_handle_t *zhp = zfs_open(g_zfs,
3970 argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3971 if (zhp == NULL)
3972 usage(B_FALSE);
3973 if (!zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) ||
3974 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
3975 NULL, 0, NULL, NULL, 0, B_TRUE) == -1) {
3976 (void) fprintf(stderr,
3977 gettext("'%s' does not have any "
3978 "resumable receive state to abort\n"),
3979 argv[0]);
3980 return (1);
3982 err = zfs_destroy(zhp, B_FALSE);
3985 return (err != 0);
3988 if (isatty(STDIN_FILENO)) {
3989 (void) fprintf(stderr,
3990 gettext("Error: Backup stream can not be read "
3991 "from a terminal.\n"
3992 "You must redirect standard input.\n"));
3993 return (1);
3995 err = zfs_receive(g_zfs, argv[0], props, &flags, STDIN_FILENO, NULL);
3997 return (err != 0);
4001 * allow/unallow stuff
4003 /* copied from zfs/sys/dsl_deleg.h */
4004 #define ZFS_DELEG_PERM_CREATE "create"
4005 #define ZFS_DELEG_PERM_DESTROY "destroy"
4006 #define ZFS_DELEG_PERM_SNAPSHOT "snapshot"
4007 #define ZFS_DELEG_PERM_ROLLBACK "rollback"
4008 #define ZFS_DELEG_PERM_CLONE "clone"
4009 #define ZFS_DELEG_PERM_PROMOTE "promote"
4010 #define ZFS_DELEG_PERM_RENAME "rename"
4011 #define ZFS_DELEG_PERM_MOUNT "mount"
4012 #define ZFS_DELEG_PERM_SHARE "share"
4013 #define ZFS_DELEG_PERM_SEND "send"
4014 #define ZFS_DELEG_PERM_RECEIVE "receive"
4015 #define ZFS_DELEG_PERM_ALLOW "allow"
4016 #define ZFS_DELEG_PERM_USERPROP "userprop"
4017 #define ZFS_DELEG_PERM_VSCAN "vscan" /* ??? */
4018 #define ZFS_DELEG_PERM_USERQUOTA "userquota"
4019 #define ZFS_DELEG_PERM_GROUPQUOTA "groupquota"
4020 #define ZFS_DELEG_PERM_USERUSED "userused"
4021 #define ZFS_DELEG_PERM_GROUPUSED "groupused"
4022 #define ZFS_DELEG_PERM_HOLD "hold"
4023 #define ZFS_DELEG_PERM_RELEASE "release"
4024 #define ZFS_DELEG_PERM_DIFF "diff"
4025 #define ZFS_DELEG_PERM_BOOKMARK "bookmark"
4027 #define ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
4029 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
4030 { ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
4031 { ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
4032 { ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
4033 { ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
4034 { ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
4035 { ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
4036 { ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
4037 { ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
4038 { ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
4039 { ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
4040 { ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
4041 { ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
4042 { ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
4043 { ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
4044 { ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
4045 { ZFS_DELEG_PERM_BOOKMARK, ZFS_DELEG_NOTE_BOOKMARK },
4047 { ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
4048 { ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
4049 { ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
4050 { ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
4051 { ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
4052 { NULL, ZFS_DELEG_NOTE_NONE }
4055 /* permission structure */
4056 typedef struct deleg_perm {
4057 zfs_deleg_who_type_t dp_who_type;
4058 const char *dp_name;
4059 boolean_t dp_local;
4060 boolean_t dp_descend;
4061 } deleg_perm_t;
4063 /* */
4064 typedef struct deleg_perm_node {
4065 deleg_perm_t dpn_perm;
4067 uu_avl_node_t dpn_avl_node;
4068 } deleg_perm_node_t;
4070 typedef struct fs_perm fs_perm_t;
4072 /* permissions set */
4073 typedef struct who_perm {
4074 zfs_deleg_who_type_t who_type;
4075 const char *who_name; /* id */
4076 char who_ug_name[256]; /* user/group name */
4077 fs_perm_t *who_fsperm; /* uplink */
4079 uu_avl_t *who_deleg_perm_avl; /* permissions */
4080 } who_perm_t;
4082 /* */
4083 typedef struct who_perm_node {
4084 who_perm_t who_perm;
4085 uu_avl_node_t who_avl_node;
4086 } who_perm_node_t;
4088 typedef struct fs_perm_set fs_perm_set_t;
4089 /* fs permissions */
4090 struct fs_perm {
4091 const char *fsp_name;
4093 uu_avl_t *fsp_sc_avl; /* sets,create */
4094 uu_avl_t *fsp_uge_avl; /* user,group,everyone */
4096 fs_perm_set_t *fsp_set; /* uplink */
4099 /* */
4100 typedef struct fs_perm_node {
4101 fs_perm_t fspn_fsperm;
4102 uu_avl_t *fspn_avl;
4104 uu_list_node_t fspn_list_node;
4105 } fs_perm_node_t;
4107 /* top level structure */
4108 struct fs_perm_set {
4109 uu_list_pool_t *fsps_list_pool;
4110 uu_list_t *fsps_list; /* list of fs_perms */
4112 uu_avl_pool_t *fsps_named_set_avl_pool;
4113 uu_avl_pool_t *fsps_who_perm_avl_pool;
4114 uu_avl_pool_t *fsps_deleg_perm_avl_pool;
4117 static inline const char *
4118 deleg_perm_type(zfs_deleg_note_t note)
4120 /* subcommands */
4121 switch (note) {
4122 /* SUBCOMMANDS */
4123 /* OTHER */
4124 case ZFS_DELEG_NOTE_GROUPQUOTA:
4125 case ZFS_DELEG_NOTE_GROUPUSED:
4126 case ZFS_DELEG_NOTE_USERPROP:
4127 case ZFS_DELEG_NOTE_USERQUOTA:
4128 case ZFS_DELEG_NOTE_USERUSED:
4129 /* other */
4130 return (gettext("other"));
4131 default:
4132 return (gettext("subcommand"));
4136 static int inline
4137 who_type2weight(zfs_deleg_who_type_t who_type)
4139 int res;
4140 switch (who_type) {
4141 case ZFS_DELEG_NAMED_SET_SETS:
4142 case ZFS_DELEG_NAMED_SET:
4143 res = 0;
4144 break;
4145 case ZFS_DELEG_CREATE_SETS:
4146 case ZFS_DELEG_CREATE:
4147 res = 1;
4148 break;
4149 case ZFS_DELEG_USER_SETS:
4150 case ZFS_DELEG_USER:
4151 res = 2;
4152 break;
4153 case ZFS_DELEG_GROUP_SETS:
4154 case ZFS_DELEG_GROUP:
4155 res = 3;
4156 break;
4157 case ZFS_DELEG_EVERYONE_SETS:
4158 case ZFS_DELEG_EVERYONE:
4159 res = 4;
4160 break;
4161 default:
4162 res = -1;
4165 return (res);
4168 /* ARGSUSED */
4169 static int
4170 who_perm_compare(const void *larg, const void *rarg, void *unused)
4172 const who_perm_node_t *l = larg;
4173 const who_perm_node_t *r = rarg;
4174 zfs_deleg_who_type_t ltype = l->who_perm.who_type;
4175 zfs_deleg_who_type_t rtype = r->who_perm.who_type;
4176 int lweight = who_type2weight(ltype);
4177 int rweight = who_type2weight(rtype);
4178 int res = lweight - rweight;
4179 if (res == 0)
4180 res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
4181 ZFS_MAX_DELEG_NAME-1);
4183 if (res == 0)
4184 return (0);
4185 if (res > 0)
4186 return (1);
4187 else
4188 return (-1);
4191 /* ARGSUSED */
4192 static int
4193 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
4195 const deleg_perm_node_t *l = larg;
4196 const deleg_perm_node_t *r = rarg;
4197 int res = strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
4198 ZFS_MAX_DELEG_NAME-1);
4200 if (res == 0)
4201 return (0);
4203 if (res > 0)
4204 return (1);
4205 else
4206 return (-1);
4209 static inline void
4210 fs_perm_set_init(fs_perm_set_t *fspset)
4212 bzero(fspset, sizeof (fs_perm_set_t));
4214 if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
4215 sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
4216 NULL, UU_DEFAULT)) == NULL)
4217 nomem();
4218 if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
4219 UU_DEFAULT)) == NULL)
4220 nomem();
4222 if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
4223 "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
4224 who_perm_node_t, who_avl_node), who_perm_compare,
4225 UU_DEFAULT)) == NULL)
4226 nomem();
4228 if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
4229 "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
4230 who_perm_node_t, who_avl_node), who_perm_compare,
4231 UU_DEFAULT)) == NULL)
4232 nomem();
4234 if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
4235 "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
4236 deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
4237 == NULL)
4238 nomem();
4241 static inline void fs_perm_fini(fs_perm_t *);
4242 static inline void who_perm_fini(who_perm_t *);
4244 static inline void
4245 fs_perm_set_fini(fs_perm_set_t *fspset)
4247 fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
4249 while (node != NULL) {
4250 fs_perm_node_t *next_node =
4251 uu_list_next(fspset->fsps_list, node);
4252 fs_perm_t *fsperm = &node->fspn_fsperm;
4253 fs_perm_fini(fsperm);
4254 uu_list_remove(fspset->fsps_list, node);
4255 free(node);
4256 node = next_node;
4259 uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
4260 uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
4261 uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
4264 static inline void
4265 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
4266 const char *name)
4268 deleg_perm->dp_who_type = type;
4269 deleg_perm->dp_name = name;
4272 static inline void
4273 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
4274 zfs_deleg_who_type_t type, const char *name)
4276 uu_avl_pool_t *pool;
4277 pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
4279 bzero(who_perm, sizeof (who_perm_t));
4281 if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
4282 UU_DEFAULT)) == NULL)
4283 nomem();
4285 who_perm->who_type = type;
4286 who_perm->who_name = name;
4287 who_perm->who_fsperm = fsperm;
4290 static inline void
4291 who_perm_fini(who_perm_t *who_perm)
4293 deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
4295 while (node != NULL) {
4296 deleg_perm_node_t *next_node =
4297 uu_avl_next(who_perm->who_deleg_perm_avl, node);
4299 uu_avl_remove(who_perm->who_deleg_perm_avl, node);
4300 free(node);
4301 node = next_node;
4304 uu_avl_destroy(who_perm->who_deleg_perm_avl);
4307 static inline void
4308 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
4310 uu_avl_pool_t *nset_pool = fspset->fsps_named_set_avl_pool;
4311 uu_avl_pool_t *who_pool = fspset->fsps_who_perm_avl_pool;
4313 bzero(fsperm, sizeof (fs_perm_t));
4315 if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
4316 == NULL)
4317 nomem();
4319 if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
4320 == NULL)
4321 nomem();
4323 fsperm->fsp_set = fspset;
4324 fsperm->fsp_name = fsname;
4327 static inline void
4328 fs_perm_fini(fs_perm_t *fsperm)
4330 who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
4331 while (node != NULL) {
4332 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
4333 node);
4334 who_perm_t *who_perm = &node->who_perm;
4335 who_perm_fini(who_perm);
4336 uu_avl_remove(fsperm->fsp_sc_avl, node);
4337 free(node);
4338 node = next_node;
4341 node = uu_avl_first(fsperm->fsp_uge_avl);
4342 while (node != NULL) {
4343 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
4344 node);
4345 who_perm_t *who_perm = &node->who_perm;
4346 who_perm_fini(who_perm);
4347 uu_avl_remove(fsperm->fsp_uge_avl, node);
4348 free(node);
4349 node = next_node;
4352 uu_avl_destroy(fsperm->fsp_sc_avl);
4353 uu_avl_destroy(fsperm->fsp_uge_avl);
4356 static void inline
4357 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
4358 zfs_deleg_who_type_t who_type, const char *name, char locality)
4360 uu_avl_index_t idx = 0;
4362 deleg_perm_node_t *found_node = NULL;
4363 deleg_perm_t *deleg_perm = &node->dpn_perm;
4365 deleg_perm_init(deleg_perm, who_type, name);
4367 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4368 == NULL)
4369 uu_avl_insert(avl, node, idx);
4370 else {
4371 node = found_node;
4372 deleg_perm = &node->dpn_perm;
4376 switch (locality) {
4377 case ZFS_DELEG_LOCAL:
4378 deleg_perm->dp_local = B_TRUE;
4379 break;
4380 case ZFS_DELEG_DESCENDENT:
4381 deleg_perm->dp_descend = B_TRUE;
4382 break;
4383 case ZFS_DELEG_NA:
4384 break;
4385 default:
4386 assert(B_FALSE); /* invalid locality */
4390 static inline int
4391 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
4393 nvpair_t *nvp = NULL;
4394 fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
4395 uu_avl_t *avl = who_perm->who_deleg_perm_avl;
4396 zfs_deleg_who_type_t who_type = who_perm->who_type;
4398 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4399 const char *name = nvpair_name(nvp);
4400 data_type_t type = nvpair_type(nvp);
4401 uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
4402 deleg_perm_node_t *node =
4403 safe_malloc(sizeof (deleg_perm_node_t));
4405 assert(type == DATA_TYPE_BOOLEAN);
4407 uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
4408 set_deleg_perm_node(avl, node, who_type, name, locality);
4411 return (0);
4414 static inline int
4415 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
4417 nvpair_t *nvp = NULL;
4418 fs_perm_set_t *fspset = fsperm->fsp_set;
4420 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4421 nvlist_t *nvl2 = NULL;
4422 const char *name = nvpair_name(nvp);
4423 uu_avl_t *avl = NULL;
4424 uu_avl_pool_t *avl_pool;
4425 zfs_deleg_who_type_t perm_type = name[0];
4426 char perm_locality = name[1];
4427 const char *perm_name = name + 3;
4428 boolean_t is_set = B_TRUE;
4429 who_perm_t *who_perm = NULL;
4431 assert('$' == name[2]);
4433 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4434 return (-1);
4436 switch (perm_type) {
4437 case ZFS_DELEG_CREATE:
4438 case ZFS_DELEG_CREATE_SETS:
4439 case ZFS_DELEG_NAMED_SET:
4440 case ZFS_DELEG_NAMED_SET_SETS:
4441 avl_pool = fspset->fsps_named_set_avl_pool;
4442 avl = fsperm->fsp_sc_avl;
4443 break;
4444 case ZFS_DELEG_USER:
4445 case ZFS_DELEG_USER_SETS:
4446 case ZFS_DELEG_GROUP:
4447 case ZFS_DELEG_GROUP_SETS:
4448 case ZFS_DELEG_EVERYONE:
4449 case ZFS_DELEG_EVERYONE_SETS:
4450 avl_pool = fspset->fsps_who_perm_avl_pool;
4451 avl = fsperm->fsp_uge_avl;
4452 break;
4455 if (is_set) {
4456 who_perm_node_t *found_node = NULL;
4457 who_perm_node_t *node = safe_malloc(
4458 sizeof (who_perm_node_t));
4459 who_perm = &node->who_perm;
4460 uu_avl_index_t idx = 0;
4462 uu_avl_node_init(node, &node->who_avl_node, avl_pool);
4463 who_perm_init(who_perm, fsperm, perm_type, perm_name);
4465 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4466 == NULL) {
4467 if (avl == fsperm->fsp_uge_avl) {
4468 uid_t rid = 0;
4469 struct passwd *p = NULL;
4470 struct group *g = NULL;
4471 const char *nice_name = NULL;
4473 switch (perm_type) {
4474 case ZFS_DELEG_USER_SETS:
4475 case ZFS_DELEG_USER:
4476 rid = atoi(perm_name);
4477 p = getpwuid(rid);
4478 if (p)
4479 nice_name = p->pw_name;
4480 break;
4481 case ZFS_DELEG_GROUP_SETS:
4482 case ZFS_DELEG_GROUP:
4483 rid = atoi(perm_name);
4484 g = getgrgid(rid);
4485 if (g)
4486 nice_name = g->gr_name;
4487 break;
4490 if (nice_name != NULL)
4491 (void) strlcpy(
4492 node->who_perm.who_ug_name,
4493 nice_name, 256);
4496 uu_avl_insert(avl, node, idx);
4497 } else {
4498 node = found_node;
4499 who_perm = &node->who_perm;
4503 (void) parse_who_perm(who_perm, nvl2, perm_locality);
4506 return (0);
4509 static inline int
4510 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
4512 nvpair_t *nvp = NULL;
4513 uu_avl_index_t idx = 0;
4515 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4516 nvlist_t *nvl2 = NULL;
4517 const char *fsname = nvpair_name(nvp);
4518 data_type_t type = nvpair_type(nvp);
4519 fs_perm_t *fsperm = NULL;
4520 fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
4521 if (node == NULL)
4522 nomem();
4524 fsperm = &node->fspn_fsperm;
4526 assert(DATA_TYPE_NVLIST == type);
4528 uu_list_node_init(node, &node->fspn_list_node,
4529 fspset->fsps_list_pool);
4531 idx = uu_list_numnodes(fspset->fsps_list);
4532 fs_perm_init(fsperm, fspset, fsname);
4534 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4535 return (-1);
4537 (void) parse_fs_perm(fsperm, nvl2);
4539 uu_list_insert(fspset->fsps_list, node, idx);
4542 return (0);
4545 static inline const char *
4546 deleg_perm_comment(zfs_deleg_note_t note)
4548 const char *str = "";
4550 /* subcommands */
4551 switch (note) {
4552 /* SUBCOMMANDS */
4553 case ZFS_DELEG_NOTE_ALLOW:
4554 str = gettext("Must also have the permission that is being"
4555 "\n\t\t\t\tallowed");
4556 break;
4557 case ZFS_DELEG_NOTE_CLONE:
4558 str = gettext("Must also have the 'create' ability and 'mount'"
4559 "\n\t\t\t\tability in the origin file system");
4560 break;
4561 case ZFS_DELEG_NOTE_CREATE:
4562 str = gettext("Must also have the 'mount' ability");
4563 break;
4564 case ZFS_DELEG_NOTE_DESTROY:
4565 str = gettext("Must also have the 'mount' ability");
4566 break;
4567 case ZFS_DELEG_NOTE_DIFF:
4568 str = gettext("Allows lookup of paths within a dataset;"
4569 "\n\t\t\t\tgiven an object number. Ordinary users need this"
4570 "\n\t\t\t\tin order to use zfs diff");
4571 break;
4572 case ZFS_DELEG_NOTE_HOLD:
4573 str = gettext("Allows adding a user hold to a snapshot");
4574 break;
4575 case ZFS_DELEG_NOTE_MOUNT:
4576 str = gettext("Allows mount/umount of ZFS datasets");
4577 break;
4578 case ZFS_DELEG_NOTE_PROMOTE:
4579 str = gettext("Must also have the 'mount'\n\t\t\t\tand"
4580 " 'promote' ability in the origin file system");
4581 break;
4582 case ZFS_DELEG_NOTE_RECEIVE:
4583 str = gettext("Must also have the 'mount' and 'create'"
4584 " ability");
4585 break;
4586 case ZFS_DELEG_NOTE_RELEASE:
4587 str = gettext("Allows releasing a user hold which\n\t\t\t\t"
4588 "might destroy the snapshot");
4589 break;
4590 case ZFS_DELEG_NOTE_RENAME:
4591 str = gettext("Must also have the 'mount' and 'create'"
4592 "\n\t\t\t\tability in the new parent");
4593 break;
4594 case ZFS_DELEG_NOTE_ROLLBACK:
4595 str = gettext("");
4596 break;
4597 case ZFS_DELEG_NOTE_SEND:
4598 str = gettext("");
4599 break;
4600 case ZFS_DELEG_NOTE_SHARE:
4601 str = gettext("Allows sharing file systems over NFS or SMB"
4602 "\n\t\t\t\tprotocols");
4603 break;
4604 case ZFS_DELEG_NOTE_SNAPSHOT:
4605 str = gettext("");
4606 break;
4608 * case ZFS_DELEG_NOTE_VSCAN:
4609 * str = gettext("");
4610 * break;
4612 /* OTHER */
4613 case ZFS_DELEG_NOTE_GROUPQUOTA:
4614 str = gettext("Allows accessing any groupquota@... property");
4615 break;
4616 case ZFS_DELEG_NOTE_GROUPUSED:
4617 str = gettext("Allows reading any groupused@... property");
4618 break;
4619 case ZFS_DELEG_NOTE_USERPROP:
4620 str = gettext("Allows changing any user property");
4621 break;
4622 case ZFS_DELEG_NOTE_USERQUOTA:
4623 str = gettext("Allows accessing any userquota@... property");
4624 break;
4625 case ZFS_DELEG_NOTE_USERUSED:
4626 str = gettext("Allows reading any userused@... property");
4627 break;
4628 /* other */
4629 default:
4630 str = "";
4633 return (str);
4636 struct allow_opts {
4637 boolean_t local;
4638 boolean_t descend;
4639 boolean_t user;
4640 boolean_t group;
4641 boolean_t everyone;
4642 boolean_t create;
4643 boolean_t set;
4644 boolean_t recursive; /* unallow only */
4645 boolean_t prt_usage;
4647 boolean_t prt_perms;
4648 char *who;
4649 char *perms;
4650 const char *dataset;
4653 static inline int
4654 prop_cmp(const void *a, const void *b)
4656 const char *str1 = *(const char **)a;
4657 const char *str2 = *(const char **)b;
4658 return (strcmp(str1, str2));
4661 static void
4662 allow_usage(boolean_t un, boolean_t requested, const char *msg)
4664 const char *opt_desc[] = {
4665 "-h", gettext("show this help message and exit"),
4666 "-l", gettext("set permission locally"),
4667 "-d", gettext("set permission for descents"),
4668 "-u", gettext("set permission for user"),
4669 "-g", gettext("set permission for group"),
4670 "-e", gettext("set permission for everyone"),
4671 "-c", gettext("set create time permission"),
4672 "-s", gettext("define permission set"),
4673 /* unallow only */
4674 "-r", gettext("remove permissions recursively"),
4676 size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
4677 size_t allow_size = unallow_size - 2;
4678 const char *props[ZFS_NUM_PROPS];
4679 int i;
4680 size_t count = 0;
4681 FILE *fp = requested ? stdout : stderr;
4682 zprop_desc_t *pdtbl = zfs_prop_get_table();
4683 const char *fmt = gettext("%-16s %-14s\t%s\n");
4685 (void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
4686 HELP_ALLOW));
4687 (void) fprintf(fp, gettext("Options:\n"));
4688 for (int i = 0; i < (un ? unallow_size : allow_size); i++) {
4689 const char *opt = opt_desc[i++];
4690 const char *optdsc = opt_desc[i];
4691 (void) fprintf(fp, gettext(" %-10s %s\n"), opt, optdsc);
4694 (void) fprintf(fp, gettext("\nThe following permissions are "
4695 "supported:\n\n"));
4696 (void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
4697 gettext("NOTES"));
4698 for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
4699 const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
4700 zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
4701 const char *perm_type = deleg_perm_type(perm_note);
4702 const char *perm_comment = deleg_perm_comment(perm_note);
4703 (void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
4706 for (i = 0; i < ZFS_NUM_PROPS; i++) {
4707 zprop_desc_t *pd = &pdtbl[i];
4708 if (pd->pd_visible != B_TRUE)
4709 continue;
4711 if (pd->pd_attr == PROP_READONLY)
4712 continue;
4714 props[count++] = pd->pd_name;
4716 props[count] = NULL;
4718 qsort(props, count, sizeof (char *), prop_cmp);
4720 for (i = 0; i < count; i++)
4721 (void) fprintf(fp, fmt, props[i], gettext("property"), "");
4723 if (msg != NULL)
4724 (void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
4726 exit(requested ? 0 : 2);
4729 static inline const char *
4730 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
4731 char **permsp)
4733 if (un && argc == expected_argc - 1)
4734 *permsp = NULL;
4735 else if (argc == expected_argc)
4736 *permsp = argv[argc - 2];
4737 else
4738 allow_usage(un, B_FALSE,
4739 gettext("wrong number of parameters\n"));
4741 return (argv[argc - 1]);
4744 static void
4745 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
4747 int uge_sum = opts->user + opts->group + opts->everyone;
4748 int csuge_sum = opts->create + opts->set + uge_sum;
4749 int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
4750 int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
4752 if (uge_sum > 1)
4753 allow_usage(un, B_FALSE,
4754 gettext("-u, -g, and -e are mutually exclusive\n"));
4756 if (opts->prt_usage)
4757 if (argc == 0 && all_sum == 0)
4758 allow_usage(un, B_TRUE, NULL);
4759 else
4760 usage(B_FALSE);
4762 if (opts->set) {
4763 if (csuge_sum > 1)
4764 allow_usage(un, B_FALSE,
4765 gettext("invalid options combined with -s\n"));
4767 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4768 if (argv[0][0] != '@')
4769 allow_usage(un, B_FALSE,
4770 gettext("invalid set name: missing '@' prefix\n"));
4771 opts->who = argv[0];
4772 } else if (opts->create) {
4773 if (ldcsuge_sum > 1)
4774 allow_usage(un, B_FALSE,
4775 gettext("invalid options combined with -c\n"));
4776 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4777 } else if (opts->everyone) {
4778 if (csuge_sum > 1)
4779 allow_usage(un, B_FALSE,
4780 gettext("invalid options combined with -e\n"));
4781 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4782 } else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
4783 == 0) {
4784 opts->everyone = B_TRUE;
4785 argc--;
4786 argv++;
4787 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4788 } else if (argc == 1 && !un) {
4789 opts->prt_perms = B_TRUE;
4790 opts->dataset = argv[argc-1];
4791 } else {
4792 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4793 opts->who = argv[0];
4796 if (!opts->local && !opts->descend) {
4797 opts->local = B_TRUE;
4798 opts->descend = B_TRUE;
4802 static void
4803 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
4804 const char *who, char *perms, nvlist_t *top_nvl)
4806 int i;
4807 char ld[2] = { '\0', '\0' };
4808 char who_buf[ZFS_MAXNAMELEN+32];
4809 char base_type;
4810 char set_type;
4811 nvlist_t *base_nvl = NULL;
4812 nvlist_t *set_nvl = NULL;
4813 nvlist_t *nvl;
4815 if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
4816 nomem();
4817 if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) != 0)
4818 nomem();
4820 switch (type) {
4821 case ZFS_DELEG_NAMED_SET_SETS:
4822 case ZFS_DELEG_NAMED_SET:
4823 set_type = ZFS_DELEG_NAMED_SET_SETS;
4824 base_type = ZFS_DELEG_NAMED_SET;
4825 ld[0] = ZFS_DELEG_NA;
4826 break;
4827 case ZFS_DELEG_CREATE_SETS:
4828 case ZFS_DELEG_CREATE:
4829 set_type = ZFS_DELEG_CREATE_SETS;
4830 base_type = ZFS_DELEG_CREATE;
4831 ld[0] = ZFS_DELEG_NA;
4832 break;
4833 case ZFS_DELEG_USER_SETS:
4834 case ZFS_DELEG_USER:
4835 set_type = ZFS_DELEG_USER_SETS;
4836 base_type = ZFS_DELEG_USER;
4837 if (local)
4838 ld[0] = ZFS_DELEG_LOCAL;
4839 if (descend)
4840 ld[1] = ZFS_DELEG_DESCENDENT;
4841 break;
4842 case ZFS_DELEG_GROUP_SETS:
4843 case ZFS_DELEG_GROUP:
4844 set_type = ZFS_DELEG_GROUP_SETS;
4845 base_type = ZFS_DELEG_GROUP;
4846 if (local)
4847 ld[0] = ZFS_DELEG_LOCAL;
4848 if (descend)
4849 ld[1] = ZFS_DELEG_DESCENDENT;
4850 break;
4851 case ZFS_DELEG_EVERYONE_SETS:
4852 case ZFS_DELEG_EVERYONE:
4853 set_type = ZFS_DELEG_EVERYONE_SETS;
4854 base_type = ZFS_DELEG_EVERYONE;
4855 if (local)
4856 ld[0] = ZFS_DELEG_LOCAL;
4857 if (descend)
4858 ld[1] = ZFS_DELEG_DESCENDENT;
4861 if (perms != NULL) {
4862 char *curr = perms;
4863 char *end = curr + strlen(perms);
4865 while (curr < end) {
4866 char *delim = strchr(curr, ',');
4867 if (delim == NULL)
4868 delim = end;
4869 else
4870 *delim = '\0';
4872 if (curr[0] == '@')
4873 nvl = set_nvl;
4874 else
4875 nvl = base_nvl;
4877 (void) nvlist_add_boolean(nvl, curr);
4878 if (delim != end)
4879 *delim = ',';
4880 curr = delim + 1;
4883 for (i = 0; i < 2; i++) {
4884 char locality = ld[i];
4885 if (locality == 0)
4886 continue;
4888 if (!nvlist_empty(base_nvl)) {
4889 if (who != NULL)
4890 (void) snprintf(who_buf,
4891 sizeof (who_buf), "%c%c$%s",
4892 base_type, locality, who);
4893 else
4894 (void) snprintf(who_buf,
4895 sizeof (who_buf), "%c%c$",
4896 base_type, locality);
4898 (void) nvlist_add_nvlist(top_nvl, who_buf,
4899 base_nvl);
4903 if (!nvlist_empty(set_nvl)) {
4904 if (who != NULL)
4905 (void) snprintf(who_buf,
4906 sizeof (who_buf), "%c%c$%s",
4907 set_type, locality, who);
4908 else
4909 (void) snprintf(who_buf,
4910 sizeof (who_buf), "%c%c$",
4911 set_type, locality);
4913 (void) nvlist_add_nvlist(top_nvl, who_buf,
4914 set_nvl);
4917 } else {
4918 for (i = 0; i < 2; i++) {
4919 char locality = ld[i];
4920 if (locality == 0)
4921 continue;
4923 if (who != NULL)
4924 (void) snprintf(who_buf, sizeof (who_buf),
4925 "%c%c$%s", base_type, locality, who);
4926 else
4927 (void) snprintf(who_buf, sizeof (who_buf),
4928 "%c%c$", base_type, locality);
4929 (void) nvlist_add_boolean(top_nvl, who_buf);
4931 if (who != NULL)
4932 (void) snprintf(who_buf, sizeof (who_buf),
4933 "%c%c$%s", set_type, locality, who);
4934 else
4935 (void) snprintf(who_buf, sizeof (who_buf),
4936 "%c%c$", set_type, locality);
4937 (void) nvlist_add_boolean(top_nvl, who_buf);
4942 static int
4943 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
4945 if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
4946 nomem();
4948 if (opts->set) {
4949 store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
4950 opts->descend, opts->who, opts->perms, *nvlp);
4951 } else if (opts->create) {
4952 store_allow_perm(ZFS_DELEG_CREATE, opts->local,
4953 opts->descend, NULL, opts->perms, *nvlp);
4954 } else if (opts->everyone) {
4955 store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
4956 opts->descend, NULL, opts->perms, *nvlp);
4957 } else {
4958 char *curr = opts->who;
4959 char *end = curr + strlen(curr);
4961 while (curr < end) {
4962 const char *who;
4963 zfs_deleg_who_type_t who_type;
4964 char *endch;
4965 char *delim = strchr(curr, ',');
4966 char errbuf[256];
4967 char id[64];
4968 struct passwd *p = NULL;
4969 struct group *g = NULL;
4971 uid_t rid;
4972 if (delim == NULL)
4973 delim = end;
4974 else
4975 *delim = '\0';
4977 rid = (uid_t)strtol(curr, &endch, 0);
4978 if (opts->user) {
4979 who_type = ZFS_DELEG_USER;
4980 if (*endch != '\0')
4981 p = getpwnam(curr);
4982 else
4983 p = getpwuid(rid);
4985 if (p != NULL)
4986 rid = p->pw_uid;
4987 else {
4988 (void) snprintf(errbuf, 256, gettext(
4989 "invalid user %s"), curr);
4990 allow_usage(un, B_TRUE, errbuf);
4992 } else if (opts->group) {
4993 who_type = ZFS_DELEG_GROUP;
4994 if (*endch != '\0')
4995 g = getgrnam(curr);
4996 else
4997 g = getgrgid(rid);
4999 if (g != NULL)
5000 rid = g->gr_gid;
5001 else {
5002 (void) snprintf(errbuf, 256, gettext(
5003 "invalid group %s"), curr);
5004 allow_usage(un, B_TRUE, errbuf);
5006 } else {
5007 if (*endch != '\0') {
5008 p = getpwnam(curr);
5009 } else {
5010 p = getpwuid(rid);
5013 if (p == NULL)
5014 if (*endch != '\0') {
5015 g = getgrnam(curr);
5016 } else {
5017 g = getgrgid(rid);
5020 if (p != NULL) {
5021 who_type = ZFS_DELEG_USER;
5022 rid = p->pw_uid;
5023 } else if (g != NULL) {
5024 who_type = ZFS_DELEG_GROUP;
5025 rid = g->gr_gid;
5026 } else {
5027 (void) snprintf(errbuf, 256, gettext(
5028 "invalid user/group %s"), curr);
5029 allow_usage(un, B_TRUE, errbuf);
5033 (void) sprintf(id, "%u", rid);
5034 who = id;
5036 store_allow_perm(who_type, opts->local,
5037 opts->descend, who, opts->perms, *nvlp);
5038 curr = delim + 1;
5042 return (0);
5045 static void
5046 print_set_creat_perms(uu_avl_t *who_avl)
5048 const char *sc_title[] = {
5049 gettext("Permission sets:\n"),
5050 gettext("Create time permissions:\n"),
5051 NULL
5053 const char **title_ptr = sc_title;
5054 who_perm_node_t *who_node = NULL;
5055 int prev_weight = -1;
5057 for (who_node = uu_avl_first(who_avl); who_node != NULL;
5058 who_node = uu_avl_next(who_avl, who_node)) {
5059 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5060 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5061 const char *who_name = who_node->who_perm.who_name;
5062 int weight = who_type2weight(who_type);
5063 boolean_t first = B_TRUE;
5064 deleg_perm_node_t *deleg_node;
5066 if (prev_weight != weight) {
5067 (void) printf(*title_ptr++);
5068 prev_weight = weight;
5071 if (who_name == NULL || strnlen(who_name, 1) == 0)
5072 (void) printf("\t");
5073 else
5074 (void) printf("\t%s ", who_name);
5076 for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
5077 deleg_node = uu_avl_next(avl, deleg_node)) {
5078 if (first) {
5079 (void) printf("%s",
5080 deleg_node->dpn_perm.dp_name);
5081 first = B_FALSE;
5082 } else
5083 (void) printf(",%s",
5084 deleg_node->dpn_perm.dp_name);
5087 (void) printf("\n");
5091 static void inline
5092 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
5093 const char *title)
5095 who_perm_node_t *who_node = NULL;
5096 boolean_t prt_title = B_TRUE;
5097 uu_avl_walk_t *walk;
5099 if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
5100 nomem();
5102 while ((who_node = uu_avl_walk_next(walk)) != NULL) {
5103 const char *who_name = who_node->who_perm.who_name;
5104 const char *nice_who_name = who_node->who_perm.who_ug_name;
5105 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5106 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5107 char delim = ' ';
5108 deleg_perm_node_t *deleg_node;
5109 boolean_t prt_who = B_TRUE;
5111 for (deleg_node = uu_avl_first(avl);
5112 deleg_node != NULL;
5113 deleg_node = uu_avl_next(avl, deleg_node)) {
5114 if (local != deleg_node->dpn_perm.dp_local ||
5115 descend != deleg_node->dpn_perm.dp_descend)
5116 continue;
5118 if (prt_who) {
5119 const char *who = NULL;
5120 if (prt_title) {
5121 prt_title = B_FALSE;
5122 (void) printf(title);
5125 switch (who_type) {
5126 case ZFS_DELEG_USER_SETS:
5127 case ZFS_DELEG_USER:
5128 who = gettext("user");
5129 if (nice_who_name)
5130 who_name = nice_who_name;
5131 break;
5132 case ZFS_DELEG_GROUP_SETS:
5133 case ZFS_DELEG_GROUP:
5134 who = gettext("group");
5135 if (nice_who_name)
5136 who_name = nice_who_name;
5137 break;
5138 case ZFS_DELEG_EVERYONE_SETS:
5139 case ZFS_DELEG_EVERYONE:
5140 who = gettext("everyone");
5141 who_name = NULL;
5144 prt_who = B_FALSE;
5145 if (who_name == NULL)
5146 (void) printf("\t%s", who);
5147 else
5148 (void) printf("\t%s %s", who, who_name);
5151 (void) printf("%c%s", delim,
5152 deleg_node->dpn_perm.dp_name);
5153 delim = ',';
5156 if (!prt_who)
5157 (void) printf("\n");
5160 uu_avl_walk_end(walk);
5163 static void
5164 print_fs_perms(fs_perm_set_t *fspset)
5166 fs_perm_node_t *node = NULL;
5167 char buf[ZFS_MAXNAMELEN+32];
5168 const char *dsname = buf;
5170 for (node = uu_list_first(fspset->fsps_list); node != NULL;
5171 node = uu_list_next(fspset->fsps_list, node)) {
5172 uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
5173 uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
5174 int left = 0;
5176 (void) snprintf(buf, ZFS_MAXNAMELEN+32,
5177 gettext("---- Permissions on %s "),
5178 node->fspn_fsperm.fsp_name);
5179 (void) printf(dsname);
5180 left = 70 - strlen(buf);
5181 while (left-- > 0)
5182 (void) printf("-");
5183 (void) printf("\n");
5185 print_set_creat_perms(sc_avl);
5186 print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
5187 gettext("Local permissions:\n"));
5188 print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
5189 gettext("Descendent permissions:\n"));
5190 print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
5191 gettext("Local+Descendent permissions:\n"));
5195 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
5197 struct deleg_perms {
5198 boolean_t un;
5199 nvlist_t *nvl;
5202 static int
5203 set_deleg_perms(zfs_handle_t *zhp, void *data)
5205 struct deleg_perms *perms = (struct deleg_perms *)data;
5206 zfs_type_t zfs_type = zfs_get_type(zhp);
5208 if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
5209 return (0);
5211 return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
5214 static int
5215 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
5217 zfs_handle_t *zhp;
5218 nvlist_t *perm_nvl = NULL;
5219 nvlist_t *update_perm_nvl = NULL;
5220 int error = 1;
5221 int c;
5222 struct allow_opts opts = { 0 };
5224 const char *optstr = un ? "ldugecsrh" : "ldugecsh";
5226 /* check opts */
5227 while ((c = getopt(argc, argv, optstr)) != -1) {
5228 switch (c) {
5229 case 'l':
5230 opts.local = B_TRUE;
5231 break;
5232 case 'd':
5233 opts.descend = B_TRUE;
5234 break;
5235 case 'u':
5236 opts.user = B_TRUE;
5237 break;
5238 case 'g':
5239 opts.group = B_TRUE;
5240 break;
5241 case 'e':
5242 opts.everyone = B_TRUE;
5243 break;
5244 case 's':
5245 opts.set = B_TRUE;
5246 break;
5247 case 'c':
5248 opts.create = B_TRUE;
5249 break;
5250 case 'r':
5251 opts.recursive = B_TRUE;
5252 break;
5253 case ':':
5254 (void) fprintf(stderr, gettext("missing argument for "
5255 "'%c' option\n"), optopt);
5256 usage(B_FALSE);
5257 break;
5258 case 'h':
5259 opts.prt_usage = B_TRUE;
5260 break;
5261 case '?':
5262 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5263 optopt);
5264 usage(B_FALSE);
5268 argc -= optind;
5269 argv += optind;
5271 /* check arguments */
5272 parse_allow_args(argc, argv, un, &opts);
5274 /* try to open the dataset */
5275 if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
5276 ZFS_TYPE_VOLUME)) == NULL) {
5277 (void) fprintf(stderr, "Failed to open dataset: %s\n",
5278 opts.dataset);
5279 return (-1);
5282 if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
5283 goto cleanup2;
5285 fs_perm_set_init(&fs_perm_set);
5286 if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
5287 (void) fprintf(stderr, "Failed to parse fsacl permissions\n");
5288 goto cleanup1;
5291 if (opts.prt_perms)
5292 print_fs_perms(&fs_perm_set);
5293 else {
5294 (void) construct_fsacl_list(un, &opts, &update_perm_nvl);
5295 if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
5296 goto cleanup0;
5298 if (un && opts.recursive) {
5299 struct deleg_perms data = { un, update_perm_nvl };
5300 if (zfs_iter_filesystems(zhp, set_deleg_perms,
5301 &data) != 0)
5302 goto cleanup0;
5306 error = 0;
5308 cleanup0:
5309 nvlist_free(perm_nvl);
5310 if (update_perm_nvl != NULL)
5311 nvlist_free(update_perm_nvl);
5312 cleanup1:
5313 fs_perm_set_fini(&fs_perm_set);
5314 cleanup2:
5315 zfs_close(zhp);
5317 return (error);
5320 static int
5321 zfs_do_allow(int argc, char **argv)
5323 return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
5326 static int
5327 zfs_do_unallow(int argc, char **argv)
5329 return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
5332 static int
5333 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
5335 int errors = 0;
5336 int i;
5337 const char *tag;
5338 boolean_t recursive = B_FALSE;
5339 const char *opts = holding ? "rt" : "r";
5340 int c;
5342 /* check options */
5343 while ((c = getopt(argc, argv, opts)) != -1) {
5344 switch (c) {
5345 case 'r':
5346 recursive = B_TRUE;
5347 break;
5348 case '?':
5349 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5350 optopt);
5351 usage(B_FALSE);
5355 argc -= optind;
5356 argv += optind;
5358 /* check number of arguments */
5359 if (argc < 2)
5360 usage(B_FALSE);
5362 tag = argv[0];
5363 --argc;
5364 ++argv;
5366 if (holding && tag[0] == '.') {
5367 /* tags starting with '.' are reserved for libzfs */
5368 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
5369 usage(B_FALSE);
5372 for (i = 0; i < argc; ++i) {
5373 zfs_handle_t *zhp;
5374 char parent[ZFS_MAXNAMELEN];
5375 const char *delim;
5376 char *path = argv[i];
5378 delim = strchr(path, '@');
5379 if (delim == NULL) {
5380 (void) fprintf(stderr,
5381 gettext("'%s' is not a snapshot\n"), path);
5382 ++errors;
5383 continue;
5385 (void) strncpy(parent, path, delim - path);
5386 parent[delim - path] = '\0';
5388 zhp = zfs_open(g_zfs, parent,
5389 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5390 if (zhp == NULL) {
5391 ++errors;
5392 continue;
5394 if (holding) {
5395 if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
5396 ++errors;
5397 } else {
5398 if (zfs_release(zhp, delim+1, tag, recursive) != 0)
5399 ++errors;
5401 zfs_close(zhp);
5404 return (errors != 0);
5408 * zfs hold [-r] [-t] <tag> <snap> ...
5410 * -r Recursively hold
5412 * Apply a user-hold with the given tag to the list of snapshots.
5414 static int
5415 zfs_do_hold(int argc, char **argv)
5417 return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
5421 * zfs release [-r] <tag> <snap> ...
5423 * -r Recursively release
5425 * Release a user-hold with the given tag from the list of snapshots.
5427 static int
5428 zfs_do_release(int argc, char **argv)
5430 return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
5433 typedef struct holds_cbdata {
5434 boolean_t cb_recursive;
5435 const char *cb_snapname;
5436 nvlist_t **cb_nvlp;
5437 size_t cb_max_namelen;
5438 size_t cb_max_taglen;
5439 } holds_cbdata_t;
5441 #define STRFTIME_FMT_STR "%a %b %e %k:%M %Y"
5442 #define DATETIME_BUF_LEN (32)
5446 static void
5447 print_holds(boolean_t scripted, size_t nwidth, size_t tagwidth, nvlist_t *nvl)
5449 int i;
5450 nvpair_t *nvp = NULL;
5451 char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
5452 const char *col;
5454 if (!scripted) {
5455 for (i = 0; i < 3; i++) {
5456 col = gettext(hdr_cols[i]);
5457 if (i < 2)
5458 (void) printf("%-*s ", i ? tagwidth : nwidth,
5459 col);
5460 else
5461 (void) printf("%s\n", col);
5465 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5466 char *zname = nvpair_name(nvp);
5467 nvlist_t *nvl2;
5468 nvpair_t *nvp2 = NULL;
5469 (void) nvpair_value_nvlist(nvp, &nvl2);
5470 while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
5471 char tsbuf[DATETIME_BUF_LEN];
5472 char *tagname = nvpair_name(nvp2);
5473 uint64_t val = 0;
5474 time_t time;
5475 struct tm t;
5476 char sep = scripted ? '\t' : ' ';
5477 size_t sepnum = scripted ? 1 : 2;
5479 (void) nvpair_value_uint64(nvp2, &val);
5480 time = (time_t)val;
5481 (void) localtime_r(&time, &t);
5482 (void) strftime(tsbuf, DATETIME_BUF_LEN,
5483 gettext(STRFTIME_FMT_STR), &t);
5485 (void) printf("%-*s%*c%-*s%*c%s\n", nwidth, zname,
5486 sepnum, sep, tagwidth, tagname, sepnum, sep, tsbuf);
5492 * Generic callback function to list a dataset or snapshot.
5494 static int
5495 holds_callback(zfs_handle_t *zhp, void *data)
5497 holds_cbdata_t *cbp = data;
5498 nvlist_t *top_nvl = *cbp->cb_nvlp;
5499 nvlist_t *nvl = NULL;
5500 nvpair_t *nvp = NULL;
5501 const char *zname = zfs_get_name(zhp);
5502 size_t znamelen = strnlen(zname, ZFS_MAXNAMELEN);
5504 if (cbp->cb_recursive) {
5505 const char *snapname;
5506 char *delim = strchr(zname, '@');
5507 if (delim == NULL)
5508 return (0);
5510 snapname = delim + 1;
5511 if (strcmp(cbp->cb_snapname, snapname))
5512 return (0);
5515 if (zfs_get_holds(zhp, &nvl) != 0)
5516 return (-1);
5518 if (znamelen > cbp->cb_max_namelen)
5519 cbp->cb_max_namelen = znamelen;
5521 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5522 const char *tag = nvpair_name(nvp);
5523 size_t taglen = strnlen(tag, MAXNAMELEN);
5524 if (taglen > cbp->cb_max_taglen)
5525 cbp->cb_max_taglen = taglen;
5528 return (nvlist_add_nvlist(top_nvl, zname, nvl));
5532 * zfs holds [-r] <snap> ...
5534 * -r Recursively hold
5536 static int
5537 zfs_do_holds(int argc, char **argv)
5539 int errors = 0;
5540 int c;
5541 int i;
5542 boolean_t scripted = B_FALSE;
5543 boolean_t recursive = B_FALSE;
5544 const char *opts = "rH";
5545 nvlist_t *nvl;
5547 int types = ZFS_TYPE_SNAPSHOT;
5548 holds_cbdata_t cb = { 0 };
5550 int limit = 0;
5551 int ret = 0;
5552 int flags = 0;
5554 /* check options */
5555 while ((c = getopt(argc, argv, opts)) != -1) {
5556 switch (c) {
5557 case 'r':
5558 recursive = B_TRUE;
5559 break;
5560 case 'H':
5561 scripted = B_TRUE;
5562 break;
5563 case '?':
5564 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5565 optopt);
5566 usage(B_FALSE);
5570 if (recursive) {
5571 types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
5572 flags |= ZFS_ITER_RECURSE;
5575 argc -= optind;
5576 argv += optind;
5578 /* check number of arguments */
5579 if (argc < 1)
5580 usage(B_FALSE);
5582 if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5583 nomem();
5585 for (i = 0; i < argc; ++i) {
5586 char *snapshot = argv[i];
5587 const char *delim;
5588 const char *snapname;
5590 delim = strchr(snapshot, '@');
5591 if (delim == NULL) {
5592 (void) fprintf(stderr,
5593 gettext("'%s' is not a snapshot\n"), snapshot);
5594 ++errors;
5595 continue;
5597 snapname = delim + 1;
5598 if (recursive)
5599 snapshot[delim - snapshot] = '\0';
5601 cb.cb_recursive = recursive;
5602 cb.cb_snapname = snapname;
5603 cb.cb_nvlp = &nvl;
5606 * 1. collect holds data, set format options
5608 ret = zfs_for_each(argc, argv, flags, types, NULL, NULL, limit,
5609 holds_callback, &cb);
5610 if (ret != 0)
5611 ++errors;
5615 * 2. print holds data
5617 print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl);
5619 if (nvlist_empty(nvl))
5620 (void) printf(gettext("no datasets available\n"));
5622 nvlist_free(nvl);
5624 return (0 != errors);
5627 #define CHECK_SPINNER 30
5628 #define SPINNER_TIME 3 /* seconds */
5629 #define MOUNT_TIME 5 /* seconds */
5631 static int
5632 get_one_dataset(zfs_handle_t *zhp, void *data)
5634 static char *spin[] = { "-", "\\", "|", "/" };
5635 static int spinval = 0;
5636 static int spincheck = 0;
5637 static time_t last_spin_time = (time_t)0;
5638 get_all_cb_t *cbp = data;
5639 zfs_type_t type = zfs_get_type(zhp);
5641 if (cbp->cb_verbose) {
5642 if (--spincheck < 0) {
5643 time_t now = time(NULL);
5644 if (last_spin_time + SPINNER_TIME < now) {
5645 update_progress(spin[spinval++ % 4]);
5646 last_spin_time = now;
5648 spincheck = CHECK_SPINNER;
5653 * Interate over any nested datasets.
5655 if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
5656 zfs_close(zhp);
5657 return (1);
5661 * Skip any datasets whose type does not match.
5663 if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
5664 zfs_close(zhp);
5665 return (0);
5667 libzfs_add_handle(cbp, zhp);
5668 assert(cbp->cb_used <= cbp->cb_alloc);
5670 return (0);
5673 static void
5674 get_all_datasets(zfs_handle_t ***dslist, size_t *count, boolean_t verbose)
5676 get_all_cb_t cb = { 0 };
5677 cb.cb_verbose = verbose;
5678 cb.cb_getone = get_one_dataset;
5680 if (verbose)
5681 set_progress_header(gettext("Reading ZFS config"));
5682 (void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
5684 *dslist = cb.cb_handles;
5685 *count = cb.cb_used;
5687 if (verbose)
5688 finish_progress(gettext("done."));
5692 * Generic callback for sharing or mounting filesystems. Because the code is so
5693 * similar, we have a common function with an extra parameter to determine which
5694 * mode we are using.
5696 #define OP_SHARE 0x1
5697 #define OP_MOUNT 0x2
5700 * Share or mount a dataset.
5702 static int
5703 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
5704 boolean_t explicit, const char *options)
5706 char mountpoint[ZFS_MAXPROPLEN];
5707 char shareopts[ZFS_MAXPROPLEN];
5708 char smbshareopts[ZFS_MAXPROPLEN];
5709 const char *cmdname = op == OP_SHARE ? "share" : "mount";
5710 struct mnttab mnt;
5711 uint64_t zoned, canmount;
5712 boolean_t shared_nfs, shared_smb;
5714 assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
5717 * Check to make sure we can mount/share this dataset. If we
5718 * are in the global zone and the filesystem is exported to a
5719 * local zone, or if we are in a local zone and the
5720 * filesystem is not exported, then it is an error.
5722 zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
5724 if (zoned && getzoneid() == GLOBAL_ZONEID) {
5725 if (!explicit)
5726 return (0);
5728 (void) fprintf(stderr, gettext("cannot %s '%s': "
5729 "dataset is exported to a local zone\n"), cmdname,
5730 zfs_get_name(zhp));
5731 return (1);
5733 } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
5734 if (!explicit)
5735 return (0);
5737 (void) fprintf(stderr, gettext("cannot %s '%s': "
5738 "permission denied\n"), cmdname,
5739 zfs_get_name(zhp));
5740 return (1);
5744 * Ignore any filesystems which don't apply to us. This
5745 * includes those with a legacy mountpoint, or those with
5746 * legacy share options.
5748 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
5749 sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
5750 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
5751 sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
5752 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
5753 sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
5755 if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
5756 strcmp(smbshareopts, "off") == 0) {
5757 if (!explicit)
5758 return (0);
5760 (void) fprintf(stderr, gettext("cannot share '%s': "
5761 "legacy share\n"), zfs_get_name(zhp));
5762 (void) fprintf(stderr, gettext("use share(1M) to "
5763 "share this filesystem, or set "
5764 "sharenfs property on\n"));
5765 return (1);
5769 * We cannot share or mount legacy filesystems. If the
5770 * shareopts is non-legacy but the mountpoint is legacy, we
5771 * treat it as a legacy share.
5773 if (strcmp(mountpoint, "legacy") == 0) {
5774 if (!explicit)
5775 return (0);
5777 (void) fprintf(stderr, gettext("cannot %s '%s': "
5778 "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
5779 (void) fprintf(stderr, gettext("use %s(1M) to "
5780 "%s this filesystem\n"), cmdname, cmdname);
5781 return (1);
5784 if (strcmp(mountpoint, "none") == 0) {
5785 if (!explicit)
5786 return (0);
5788 (void) fprintf(stderr, gettext("cannot %s '%s': no "
5789 "mountpoint set\n"), cmdname, zfs_get_name(zhp));
5790 return (1);
5794 * canmount explicit outcome
5795 * on no pass through
5796 * on yes pass through
5797 * off no return 0
5798 * off yes display error, return 1
5799 * noauto no return 0
5800 * noauto yes pass through
5802 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
5803 if (canmount == ZFS_CANMOUNT_OFF) {
5804 if (!explicit)
5805 return (0);
5807 (void) fprintf(stderr, gettext("cannot %s '%s': "
5808 "'canmount' property is set to 'off'\n"), cmdname,
5809 zfs_get_name(zhp));
5810 return (1);
5811 } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
5812 return (0);
5816 * If this filesystem is inconsistent and has a receive resume
5817 * token, we can not mount it.
5819 if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) &&
5820 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
5821 NULL, 0, NULL, NULL, 0, B_TRUE) == 0) {
5822 if (!explicit)
5823 return (0);
5825 (void) fprintf(stderr, gettext("cannot %s '%s': "
5826 "Contains partially-completed state from "
5827 "\"zfs receive -r\", which can be resumed with "
5828 "\"zfs send -t\"\n"),
5829 cmdname, zfs_get_name(zhp));
5830 return (1);
5834 * At this point, we have verified that the mountpoint and/or
5835 * shareopts are appropriate for auto management. If the
5836 * filesystem is already mounted or shared, return (failing
5837 * for explicit requests); otherwise mount or share the
5838 * filesystem.
5840 switch (op) {
5841 case OP_SHARE:
5843 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
5844 shared_smb = zfs_is_shared_smb(zhp, NULL);
5846 if (shared_nfs && shared_smb ||
5847 (shared_nfs && strcmp(shareopts, "on") == 0 &&
5848 strcmp(smbshareopts, "off") == 0) ||
5849 (shared_smb && strcmp(smbshareopts, "on") == 0 &&
5850 strcmp(shareopts, "off") == 0)) {
5851 if (!explicit)
5852 return (0);
5854 (void) fprintf(stderr, gettext("cannot share "
5855 "'%s': filesystem already shared\n"),
5856 zfs_get_name(zhp));
5857 return (1);
5860 if (!zfs_is_mounted(zhp, NULL) &&
5861 zfs_mount(zhp, NULL, 0) != 0)
5862 return (1);
5864 if (protocol == NULL) {
5865 if (zfs_shareall(zhp) != 0)
5866 return (1);
5867 } else if (strcmp(protocol, "nfs") == 0) {
5868 if (zfs_share_nfs(zhp))
5869 return (1);
5870 } else if (strcmp(protocol, "smb") == 0) {
5871 if (zfs_share_smb(zhp))
5872 return (1);
5873 } else {
5874 (void) fprintf(stderr, gettext("cannot share "
5875 "'%s': invalid share type '%s' "
5876 "specified\n"),
5877 zfs_get_name(zhp), protocol);
5878 return (1);
5881 break;
5883 case OP_MOUNT:
5884 if (options == NULL)
5885 mnt.mnt_mntopts = "";
5886 else
5887 mnt.mnt_mntopts = (char *)options;
5889 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
5890 zfs_is_mounted(zhp, NULL)) {
5891 if (!explicit)
5892 return (0);
5894 (void) fprintf(stderr, gettext("cannot mount "
5895 "'%s': filesystem already mounted\n"),
5896 zfs_get_name(zhp));
5897 return (1);
5900 if (zfs_mount(zhp, options, flags) != 0)
5901 return (1);
5902 break;
5905 return (0);
5909 * Reports progress in the form "(current/total)". Not thread-safe.
5911 static void
5912 report_mount_progress(int current, int total)
5914 static time_t last_progress_time = 0;
5915 time_t now = time(NULL);
5916 char info[32];
5918 /* report 1..n instead of 0..n-1 */
5919 ++current;
5921 /* display header if we're here for the first time */
5922 if (current == 1) {
5923 set_progress_header(gettext("Mounting ZFS filesystems"));
5924 } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
5925 /* too soon to report again */
5926 return;
5929 last_progress_time = now;
5931 (void) sprintf(info, "(%d/%d)", current, total);
5933 if (current == total)
5934 finish_progress(info);
5935 else
5936 update_progress(info);
5939 static void
5940 append_options(char *mntopts, char *newopts)
5942 int len = strlen(mntopts);
5944 /* original length plus new string to append plus 1 for the comma */
5945 if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
5946 (void) fprintf(stderr, gettext("the opts argument for "
5947 "'%c' option is too long (more than %d chars)\n"),
5948 "-o", MNT_LINE_MAX);
5949 usage(B_FALSE);
5952 if (*mntopts)
5953 mntopts[len++] = ',';
5955 (void) strcpy(&mntopts[len], newopts);
5958 static int
5959 share_mount(int op, int argc, char **argv)
5961 int do_all = 0;
5962 boolean_t verbose = B_FALSE;
5963 int c, ret = 0;
5964 char *options = NULL;
5965 int flags = 0;
5967 /* check options */
5968 while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
5969 != -1) {
5970 switch (c) {
5971 case 'a':
5972 do_all = 1;
5973 break;
5974 case 'v':
5975 verbose = B_TRUE;
5976 break;
5977 case 'o':
5978 if (*optarg == '\0') {
5979 (void) fprintf(stderr, gettext("empty mount "
5980 "options (-o) specified\n"));
5981 usage(B_FALSE);
5984 if (options == NULL)
5985 options = safe_malloc(MNT_LINE_MAX + 1);
5987 /* option validation is done later */
5988 append_options(options, optarg);
5989 break;
5991 case 'O':
5992 flags |= MS_OVERLAY;
5993 break;
5994 case ':':
5995 (void) fprintf(stderr, gettext("missing argument for "
5996 "'%c' option\n"), optopt);
5997 usage(B_FALSE);
5998 break;
5999 case '?':
6000 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6001 optopt);
6002 usage(B_FALSE);
6006 argc -= optind;
6007 argv += optind;
6009 /* check number of arguments */
6010 if (do_all) {
6011 zfs_handle_t **dslist = NULL;
6012 size_t i, count = 0;
6013 char *protocol = NULL;
6015 if (op == OP_SHARE && argc > 0) {
6016 if (strcmp(argv[0], "nfs") != 0 &&
6017 strcmp(argv[0], "smb") != 0) {
6018 (void) fprintf(stderr, gettext("share type "
6019 "must be 'nfs' or 'smb'\n"));
6020 usage(B_FALSE);
6022 protocol = argv[0];
6023 argc--;
6024 argv++;
6027 if (argc != 0) {
6028 (void) fprintf(stderr, gettext("too many arguments\n"));
6029 usage(B_FALSE);
6032 start_progress_timer();
6033 get_all_datasets(&dslist, &count, verbose);
6035 if (count == 0)
6036 return (0);
6038 qsort(dslist, count, sizeof (void *), libzfs_dataset_cmp);
6040 for (i = 0; i < count; i++) {
6041 if (verbose)
6042 report_mount_progress(i, count);
6044 if (share_mount_one(dslist[i], op, flags, protocol,
6045 B_FALSE, options) != 0)
6046 ret = 1;
6047 zfs_close(dslist[i]);
6050 free(dslist);
6051 } else if (argc == 0) {
6052 struct mnttab entry;
6054 if ((op == OP_SHARE) || (options != NULL)) {
6055 (void) fprintf(stderr, gettext("missing filesystem "
6056 "argument (specify -a for all)\n"));
6057 usage(B_FALSE);
6061 * When mount is given no arguments, go through /etc/mnttab and
6062 * display any active ZFS mounts. We hide any snapshots, since
6063 * they are controlled automatically.
6065 rewind(mnttab_file);
6066 while (getmntent(mnttab_file, &entry) == 0) {
6067 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
6068 strchr(entry.mnt_special, '@') != NULL)
6069 continue;
6071 (void) printf("%-30s %s\n", entry.mnt_special,
6072 entry.mnt_mountp);
6075 } else {
6076 zfs_handle_t *zhp;
6078 if (argc > 1) {
6079 (void) fprintf(stderr,
6080 gettext("too many arguments\n"));
6081 usage(B_FALSE);
6084 if ((zhp = zfs_open(g_zfs, argv[0],
6085 ZFS_TYPE_FILESYSTEM)) == NULL) {
6086 ret = 1;
6087 } else {
6088 ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
6089 options);
6090 zfs_close(zhp);
6094 return (ret);
6098 * zfs mount -a [nfs]
6099 * zfs mount filesystem
6101 * Mount all filesystems, or mount the given filesystem.
6103 static int
6104 zfs_do_mount(int argc, char **argv)
6106 return (share_mount(OP_MOUNT, argc, argv));
6110 * zfs share -a [nfs | smb]
6111 * zfs share filesystem
6113 * Share all filesystems, or share the given filesystem.
6115 static int
6116 zfs_do_share(int argc, char **argv)
6118 return (share_mount(OP_SHARE, argc, argv));
6121 typedef struct unshare_unmount_node {
6122 zfs_handle_t *un_zhp;
6123 char *un_mountp;
6124 uu_avl_node_t un_avlnode;
6125 } unshare_unmount_node_t;
6127 /* ARGSUSED */
6128 static int
6129 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
6131 const unshare_unmount_node_t *l = larg;
6132 const unshare_unmount_node_t *r = rarg;
6134 return (strcmp(l->un_mountp, r->un_mountp));
6138 * Convenience routine used by zfs_do_umount() and manual_unmount(). Given an
6139 * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
6140 * and unmount it appropriately.
6142 static int
6143 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
6145 zfs_handle_t *zhp;
6146 int ret = 0;
6147 struct stat64 statbuf;
6148 struct extmnttab entry;
6149 const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
6150 ino_t path_inode;
6153 * Search for the path in /etc/mnttab. Rather than looking for the
6154 * specific path, which can be fooled by non-standard paths (i.e. ".."
6155 * or "//"), we stat() the path and search for the corresponding
6156 * (major,minor) device pair.
6158 if (stat64(path, &statbuf) != 0) {
6159 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6160 cmdname, path, strerror(errno));
6161 return (1);
6163 path_inode = statbuf.st_ino;
6166 * Search for the given (major,minor) pair in the mount table.
6168 rewind(mnttab_file);
6169 while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
6170 if (entry.mnt_major == major(statbuf.st_dev) &&
6171 entry.mnt_minor == minor(statbuf.st_dev))
6172 break;
6174 if (ret != 0) {
6175 if (op == OP_SHARE) {
6176 (void) fprintf(stderr, gettext("cannot %s '%s': not "
6177 "currently mounted\n"), cmdname, path);
6178 return (1);
6180 (void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
6181 path);
6182 if ((ret = umount2(path, flags)) != 0)
6183 (void) fprintf(stderr, gettext("%s: %s\n"), path,
6184 strerror(errno));
6185 return (ret != 0);
6188 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
6189 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
6190 "filesystem\n"), cmdname, path);
6191 return (1);
6194 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6195 ZFS_TYPE_FILESYSTEM)) == NULL)
6196 return (1);
6198 ret = 1;
6199 if (stat64(entry.mnt_mountp, &statbuf) != 0) {
6200 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6201 cmdname, path, strerror(errno));
6202 goto out;
6203 } else if (statbuf.st_ino != path_inode) {
6204 (void) fprintf(stderr, gettext("cannot "
6205 "%s '%s': not a mountpoint\n"), cmdname, path);
6206 goto out;
6209 if (op == OP_SHARE) {
6210 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6211 char smbshare_prop[ZFS_MAXPROPLEN];
6213 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
6214 sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
6215 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
6216 sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
6218 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6219 strcmp(smbshare_prop, "off") == 0) {
6220 (void) fprintf(stderr, gettext("cannot unshare "
6221 "'%s': legacy share\n"), path);
6222 (void) fprintf(stderr, gettext("use "
6223 "unshare(1M) to unshare this filesystem\n"));
6224 } else if (!zfs_is_shared(zhp)) {
6225 (void) fprintf(stderr, gettext("cannot unshare '%s': "
6226 "not currently shared\n"), path);
6227 } else {
6228 ret = zfs_unshareall_bypath(zhp, path);
6230 } else {
6231 char mtpt_prop[ZFS_MAXPROPLEN];
6233 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
6234 sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
6236 if (is_manual) {
6237 ret = zfs_unmount(zhp, NULL, flags);
6238 } else if (strcmp(mtpt_prop, "legacy") == 0) {
6239 (void) fprintf(stderr, gettext("cannot unmount "
6240 "'%s': legacy mountpoint\n"),
6241 zfs_get_name(zhp));
6242 (void) fprintf(stderr, gettext("use umount(1M) "
6243 "to unmount this filesystem\n"));
6244 } else {
6245 ret = zfs_unmountall(zhp, flags);
6249 out:
6250 zfs_close(zhp);
6252 return (ret != 0);
6256 * Generic callback for unsharing or unmounting a filesystem.
6258 static int
6259 unshare_unmount(int op, int argc, char **argv)
6261 int do_all = 0;
6262 int flags = 0;
6263 int ret = 0;
6264 int c;
6265 zfs_handle_t *zhp;
6266 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6267 char sharesmb[ZFS_MAXPROPLEN];
6269 /* check options */
6270 while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
6271 switch (c) {
6272 case 'a':
6273 do_all = 1;
6274 break;
6275 case 'f':
6276 flags = MS_FORCE;
6277 break;
6278 case '?':
6279 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6280 optopt);
6281 usage(B_FALSE);
6285 argc -= optind;
6286 argv += optind;
6288 if (do_all) {
6290 * We could make use of zfs_for_each() to walk all datasets in
6291 * the system, but this would be very inefficient, especially
6292 * since we would have to linearly search /etc/mnttab for each
6293 * one. Instead, do one pass through /etc/mnttab looking for
6294 * zfs entries and call zfs_unmount() for each one.
6296 * Things get a little tricky if the administrator has created
6297 * mountpoints beneath other ZFS filesystems. In this case, we
6298 * have to unmount the deepest filesystems first. To accomplish
6299 * this, we place all the mountpoints in an AVL tree sorted by
6300 * the special type (dataset name), and walk the result in
6301 * reverse to make sure to get any snapshots first.
6303 struct mnttab entry;
6304 uu_avl_pool_t *pool;
6305 uu_avl_t *tree;
6306 unshare_unmount_node_t *node;
6307 uu_avl_index_t idx;
6308 uu_avl_walk_t *walk;
6310 if (argc != 0) {
6311 (void) fprintf(stderr, gettext("too many arguments\n"));
6312 usage(B_FALSE);
6315 if (((pool = uu_avl_pool_create("unmount_pool",
6316 sizeof (unshare_unmount_node_t),
6317 offsetof(unshare_unmount_node_t, un_avlnode),
6318 unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
6319 ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
6320 nomem();
6322 rewind(mnttab_file);
6323 while (getmntent(mnttab_file, &entry) == 0) {
6325 /* ignore non-ZFS entries */
6326 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
6327 continue;
6329 /* ignore snapshots */
6330 if (strchr(entry.mnt_special, '@') != NULL)
6331 continue;
6333 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6334 ZFS_TYPE_FILESYSTEM)) == NULL) {
6335 ret = 1;
6336 continue;
6339 switch (op) {
6340 case OP_SHARE:
6341 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6342 nfs_mnt_prop,
6343 sizeof (nfs_mnt_prop),
6344 NULL, NULL, 0, B_FALSE) == 0);
6345 if (strcmp(nfs_mnt_prop, "off") != 0)
6346 break;
6347 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6348 nfs_mnt_prop,
6349 sizeof (nfs_mnt_prop),
6350 NULL, NULL, 0, B_FALSE) == 0);
6351 if (strcmp(nfs_mnt_prop, "off") == 0)
6352 continue;
6353 break;
6354 case OP_MOUNT:
6355 /* Ignore legacy mounts */
6356 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
6357 nfs_mnt_prop,
6358 sizeof (nfs_mnt_prop),
6359 NULL, NULL, 0, B_FALSE) == 0);
6360 if (strcmp(nfs_mnt_prop, "legacy") == 0)
6361 continue;
6362 /* Ignore canmount=noauto mounts */
6363 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
6364 ZFS_CANMOUNT_NOAUTO)
6365 continue;
6366 default:
6367 break;
6370 node = safe_malloc(sizeof (unshare_unmount_node_t));
6371 node->un_zhp = zhp;
6372 node->un_mountp = safe_strdup(entry.mnt_mountp);
6374 uu_avl_node_init(node, &node->un_avlnode, pool);
6376 if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
6377 uu_avl_insert(tree, node, idx);
6378 } else {
6379 zfs_close(node->un_zhp);
6380 free(node->un_mountp);
6381 free(node);
6386 * Walk the AVL tree in reverse, unmounting each filesystem and
6387 * removing it from the AVL tree in the process.
6389 if ((walk = uu_avl_walk_start(tree,
6390 UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
6391 nomem();
6393 while ((node = uu_avl_walk_next(walk)) != NULL) {
6394 uu_avl_remove(tree, node);
6396 switch (op) {
6397 case OP_SHARE:
6398 if (zfs_unshareall_bypath(node->un_zhp,
6399 node->un_mountp) != 0)
6400 ret = 1;
6401 break;
6403 case OP_MOUNT:
6404 if (zfs_unmount(node->un_zhp,
6405 node->un_mountp, flags) != 0)
6406 ret = 1;
6407 break;
6410 zfs_close(node->un_zhp);
6411 free(node->un_mountp);
6412 free(node);
6415 uu_avl_walk_end(walk);
6416 uu_avl_destroy(tree);
6417 uu_avl_pool_destroy(pool);
6419 } else {
6420 if (argc != 1) {
6421 if (argc == 0)
6422 (void) fprintf(stderr,
6423 gettext("missing filesystem argument\n"));
6424 else
6425 (void) fprintf(stderr,
6426 gettext("too many arguments\n"));
6427 usage(B_FALSE);
6431 * We have an argument, but it may be a full path or a ZFS
6432 * filesystem. Pass full paths off to unmount_path() (shared by
6433 * manual_unmount), otherwise open the filesystem and pass to
6434 * zfs_unmount().
6436 if (argv[0][0] == '/')
6437 return (unshare_unmount_path(op, argv[0],
6438 flags, B_FALSE));
6440 if ((zhp = zfs_open(g_zfs, argv[0],
6441 ZFS_TYPE_FILESYSTEM)) == NULL)
6442 return (1);
6444 verify(zfs_prop_get(zhp, op == OP_SHARE ?
6445 ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
6446 nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
6447 NULL, 0, B_FALSE) == 0);
6449 switch (op) {
6450 case OP_SHARE:
6451 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6452 nfs_mnt_prop,
6453 sizeof (nfs_mnt_prop),
6454 NULL, NULL, 0, B_FALSE) == 0);
6455 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6456 sharesmb, sizeof (sharesmb), NULL, NULL,
6457 0, B_FALSE) == 0);
6459 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6460 strcmp(sharesmb, "off") == 0) {
6461 (void) fprintf(stderr, gettext("cannot "
6462 "unshare '%s': legacy share\n"),
6463 zfs_get_name(zhp));
6464 (void) fprintf(stderr, gettext("use "
6465 "unshare(1M) to unshare this "
6466 "filesystem\n"));
6467 ret = 1;
6468 } else if (!zfs_is_shared(zhp)) {
6469 (void) fprintf(stderr, gettext("cannot "
6470 "unshare '%s': not currently "
6471 "shared\n"), zfs_get_name(zhp));
6472 ret = 1;
6473 } else if (zfs_unshareall(zhp) != 0) {
6474 ret = 1;
6476 break;
6478 case OP_MOUNT:
6479 if (strcmp(nfs_mnt_prop, "legacy") == 0) {
6480 (void) fprintf(stderr, gettext("cannot "
6481 "unmount '%s': legacy "
6482 "mountpoint\n"), zfs_get_name(zhp));
6483 (void) fprintf(stderr, gettext("use "
6484 "umount(1M) to unmount this "
6485 "filesystem\n"));
6486 ret = 1;
6487 } else if (!zfs_is_mounted(zhp, NULL)) {
6488 (void) fprintf(stderr, gettext("cannot "
6489 "unmount '%s': not currently "
6490 "mounted\n"),
6491 zfs_get_name(zhp));
6492 ret = 1;
6493 } else if (zfs_unmountall(zhp, flags) != 0) {
6494 ret = 1;
6496 break;
6499 zfs_close(zhp);
6502 return (ret);
6506 * zfs unmount -a
6507 * zfs unmount filesystem
6509 * Unmount all filesystems, or a specific ZFS filesystem.
6511 static int
6512 zfs_do_unmount(int argc, char **argv)
6514 return (unshare_unmount(OP_MOUNT, argc, argv));
6518 * zfs unshare -a
6519 * zfs unshare filesystem
6521 * Unshare all filesystems, or a specific ZFS filesystem.
6523 static int
6524 zfs_do_unshare(int argc, char **argv)
6526 return (unshare_unmount(OP_SHARE, argc, argv));
6530 * Called when invoked as /etc/fs/zfs/mount. Do the mount if the mountpoint is
6531 * 'legacy'. Otherwise, complain that use should be using 'zfs mount'.
6533 static int
6534 manual_mount(int argc, char **argv)
6536 zfs_handle_t *zhp;
6537 char mountpoint[ZFS_MAXPROPLEN];
6538 char mntopts[MNT_LINE_MAX] = { '\0' };
6539 int ret = 0;
6540 int c;
6541 int flags = 0;
6542 char *dataset, *path;
6544 /* check options */
6545 while ((c = getopt(argc, argv, ":mo:O")) != -1) {
6546 switch (c) {
6547 case 'o':
6548 (void) strlcpy(mntopts, optarg, sizeof (mntopts));
6549 break;
6550 case 'O':
6551 flags |= MS_OVERLAY;
6552 break;
6553 case 'm':
6554 flags |= MS_NOMNTTAB;
6555 break;
6556 case ':':
6557 (void) fprintf(stderr, gettext("missing argument for "
6558 "'%c' option\n"), optopt);
6559 usage(B_FALSE);
6560 break;
6561 case '?':
6562 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6563 optopt);
6564 (void) fprintf(stderr, gettext("usage: mount [-o opts] "
6565 "<path>\n"));
6566 return (2);
6570 argc -= optind;
6571 argv += optind;
6573 /* check that we only have two arguments */
6574 if (argc != 2) {
6575 if (argc == 0)
6576 (void) fprintf(stderr, gettext("missing dataset "
6577 "argument\n"));
6578 else if (argc == 1)
6579 (void) fprintf(stderr,
6580 gettext("missing mountpoint argument\n"));
6581 else
6582 (void) fprintf(stderr, gettext("too many arguments\n"));
6583 (void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
6584 return (2);
6587 dataset = argv[0];
6588 path = argv[1];
6590 /* try to open the dataset */
6591 if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
6592 return (1);
6594 (void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
6595 sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
6597 /* check for legacy mountpoint and complain appropriately */
6598 ret = 0;
6599 if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
6600 if (mount(dataset, path, MS_OPTIONSTR | flags, MNTTYPE_ZFS,
6601 NULL, 0, mntopts, sizeof (mntopts)) != 0) {
6602 (void) fprintf(stderr, gettext("mount failed: %s\n"),
6603 strerror(errno));
6604 ret = 1;
6606 } else {
6607 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
6608 "mounted using 'mount -F zfs'\n"), dataset);
6609 (void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
6610 "instead.\n"), path);
6611 (void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
6612 "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
6613 (void) fprintf(stderr, gettext("See zfs(1M) for more "
6614 "information.\n"));
6615 ret = 1;
6618 return (ret);
6622 * Called when invoked as /etc/fs/zfs/umount. Unlike a manual mount, we allow
6623 * unmounts of non-legacy filesystems, as this is the dominant administrative
6624 * interface.
6626 static int
6627 manual_unmount(int argc, char **argv)
6629 int flags = 0;
6630 int c;
6632 /* check options */
6633 while ((c = getopt(argc, argv, "f")) != -1) {
6634 switch (c) {
6635 case 'f':
6636 flags = MS_FORCE;
6637 break;
6638 case '?':
6639 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6640 optopt);
6641 (void) fprintf(stderr, gettext("usage: unmount [-f] "
6642 "<path>\n"));
6643 return (2);
6647 argc -= optind;
6648 argv += optind;
6650 /* check arguments */
6651 if (argc != 1) {
6652 if (argc == 0)
6653 (void) fprintf(stderr, gettext("missing path "
6654 "argument\n"));
6655 else
6656 (void) fprintf(stderr, gettext("too many arguments\n"));
6657 (void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
6658 return (2);
6661 return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
6664 static int
6665 find_command_idx(char *command, int *idx)
6667 int i;
6669 for (i = 0; i < NCOMMAND; i++) {
6670 if (command_table[i].name == NULL)
6671 continue;
6673 if (strcmp(command, command_table[i].name) == 0) {
6674 *idx = i;
6675 return (0);
6678 return (1);
6681 static int
6682 zfs_do_diff(int argc, char **argv)
6684 zfs_handle_t *zhp;
6685 int flags = 0;
6686 char *tosnap = NULL;
6687 char *fromsnap = NULL;
6688 char *atp, *copy;
6689 int err = 0;
6690 int c;
6692 while ((c = getopt(argc, argv, "FHt")) != -1) {
6693 switch (c) {
6694 case 'F':
6695 flags |= ZFS_DIFF_CLASSIFY;
6696 break;
6697 case 'H':
6698 flags |= ZFS_DIFF_PARSEABLE;
6699 break;
6700 case 't':
6701 flags |= ZFS_DIFF_TIMESTAMP;
6702 break;
6703 default:
6704 (void) fprintf(stderr,
6705 gettext("invalid option '%c'\n"), optopt);
6706 usage(B_FALSE);
6710 argc -= optind;
6711 argv += optind;
6713 if (argc < 1) {
6714 (void) fprintf(stderr,
6715 gettext("must provide at least one snapshot name\n"));
6716 usage(B_FALSE);
6719 if (argc > 2) {
6720 (void) fprintf(stderr, gettext("too many arguments\n"));
6721 usage(B_FALSE);
6724 fromsnap = argv[0];
6725 tosnap = (argc == 2) ? argv[1] : NULL;
6727 copy = NULL;
6728 if (*fromsnap != '@')
6729 copy = strdup(fromsnap);
6730 else if (tosnap)
6731 copy = strdup(tosnap);
6732 if (copy == NULL)
6733 usage(B_FALSE);
6735 if (atp = strchr(copy, '@'))
6736 *atp = '\0';
6738 if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
6739 return (1);
6741 free(copy);
6744 * Ignore SIGPIPE so that the library can give us
6745 * information on any failure
6747 (void) sigignore(SIGPIPE);
6749 err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
6751 zfs_close(zhp);
6753 return (err != 0);
6757 * zfs bookmark <fs@snap> <fs#bmark>
6759 * Creates a bookmark with the given name from the given snapshot.
6761 static int
6762 zfs_do_bookmark(int argc, char **argv)
6764 char snapname[ZFS_MAXNAMELEN];
6765 zfs_handle_t *zhp;
6766 nvlist_t *nvl;
6767 int ret = 0;
6768 int c;
6770 /* check options */
6771 while ((c = getopt(argc, argv, "")) != -1) {
6772 switch (c) {
6773 case '?':
6774 (void) fprintf(stderr,
6775 gettext("invalid option '%c'\n"), optopt);
6776 goto usage;
6780 argc -= optind;
6781 argv += optind;
6783 /* check number of arguments */
6784 if (argc < 1) {
6785 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
6786 goto usage;
6788 if (argc < 2) {
6789 (void) fprintf(stderr, gettext("missing bookmark argument\n"));
6790 goto usage;
6793 if (strchr(argv[1], '#') == NULL) {
6794 (void) fprintf(stderr,
6795 gettext("invalid bookmark name '%s' -- "
6796 "must contain a '#'\n"), argv[1]);
6797 goto usage;
6800 if (argv[0][0] == '@') {
6802 * Snapshot name begins with @.
6803 * Default to same fs as bookmark.
6805 (void) strncpy(snapname, argv[1], sizeof (snapname));
6806 *strchr(snapname, '#') = '\0';
6807 (void) strlcat(snapname, argv[0], sizeof (snapname));
6808 } else {
6809 (void) strncpy(snapname, argv[0], sizeof (snapname));
6811 zhp = zfs_open(g_zfs, snapname, ZFS_TYPE_SNAPSHOT);
6812 if (zhp == NULL)
6813 goto usage;
6814 zfs_close(zhp);
6817 nvl = fnvlist_alloc();
6818 fnvlist_add_string(nvl, argv[1], snapname);
6819 ret = lzc_bookmark(nvl, NULL);
6820 fnvlist_free(nvl);
6822 if (ret != 0) {
6823 const char *err_msg;
6824 char errbuf[1024];
6826 (void) snprintf(errbuf, sizeof (errbuf),
6827 dgettext(TEXT_DOMAIN,
6828 "cannot create bookmark '%s'"), argv[1]);
6830 switch (ret) {
6831 case EXDEV:
6832 err_msg = "bookmark is in a different pool";
6833 break;
6834 case EEXIST:
6835 err_msg = "bookmark exists";
6836 break;
6837 case EINVAL:
6838 err_msg = "invalid argument";
6839 break;
6840 case ENOTSUP:
6841 err_msg = "bookmark feature not enabled";
6842 break;
6843 case ENOSPC:
6844 err_msg = "out of space";
6845 break;
6846 default:
6847 err_msg = "unknown error";
6848 break;
6850 (void) fprintf(stderr, "%s: %s\n", errbuf,
6851 dgettext(TEXT_DOMAIN, err_msg));
6854 return (ret != 0);
6856 usage:
6857 usage(B_FALSE);
6858 return (-1);
6862 main(int argc, char **argv)
6864 int ret = 0;
6865 int i;
6866 char *progname;
6867 char *cmdname;
6869 (void) setlocale(LC_ALL, "");
6870 (void) textdomain(TEXT_DOMAIN);
6872 opterr = 0;
6874 if ((g_zfs = libzfs_init()) == NULL) {
6875 (void) fprintf(stderr, gettext("internal error: failed to "
6876 "initialize ZFS library\n"));
6877 return (1);
6880 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
6882 libzfs_print_on_error(g_zfs, B_TRUE);
6884 if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
6885 (void) fprintf(stderr, gettext("internal error: unable to "
6886 "open %s\n"), MNTTAB);
6887 return (1);
6891 * This command also doubles as the /etc/fs mount and unmount program.
6892 * Determine if we should take this behavior based on argv[0].
6894 progname = basename(argv[0]);
6895 if (strcmp(progname, "mount") == 0) {
6896 ret = manual_mount(argc, argv);
6897 } else if (strcmp(progname, "umount") == 0) {
6898 ret = manual_unmount(argc, argv);
6899 } else {
6901 * Make sure the user has specified some command.
6903 if (argc < 2) {
6904 (void) fprintf(stderr, gettext("missing command\n"));
6905 usage(B_FALSE);
6908 cmdname = argv[1];
6911 * The 'umount' command is an alias for 'unmount'
6913 if (strcmp(cmdname, "umount") == 0)
6914 cmdname = "unmount";
6917 * The 'recv' command is an alias for 'receive'
6919 if (strcmp(cmdname, "recv") == 0)
6920 cmdname = "receive";
6923 * The 'snap' command is an alias for 'snapshot'
6925 if (strcmp(cmdname, "snap") == 0)
6926 cmdname = "snapshot";
6929 * Special case '-?'
6931 if (strcmp(cmdname, "-?") == 0)
6932 usage(B_TRUE);
6935 * Run the appropriate command.
6937 libzfs_mnttab_cache(g_zfs, B_TRUE);
6938 if (find_command_idx(cmdname, &i) == 0) {
6939 current_command = &command_table[i];
6940 ret = command_table[i].func(argc - 1, argv + 1);
6941 } else if (strchr(cmdname, '=') != NULL) {
6942 verify(find_command_idx("set", &i) == 0);
6943 current_command = &command_table[i];
6944 ret = command_table[i].func(argc, argv);
6945 } else {
6946 (void) fprintf(stderr, gettext("unrecognized "
6947 "command '%s'\n"), cmdname);
6948 usage(B_FALSE);
6950 libzfs_mnttab_cache(g_zfs, B_FALSE);
6953 (void) fclose(mnttab_file);
6955 if (ret == 0 && log_history)
6956 (void) zpool_log_history(g_zfs, history_str);
6958 libzfs_fini(g_zfs);
6961 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
6962 * for the purposes of running ::findleaks.
6964 if (getenv("ZFS_ABORT") != NULL) {
6965 (void) printf("dumping core by request\n");
6966 abort();
6969 return (ret);