dmake: do not set MAKEFLAGS=k
[unleashed/tickless.git] / usr / src / cmd / zfs / zfs_main.c
bloba87b5afe1847f71fb67848039bd17413285d95b7
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2016 by Delphix. All rights reserved.
25 * Copyright 2012 Milan Jurik. All rights reserved.
26 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
27 * Copyright (c) 2011-2012 Pawel Jakub Dawidek. All rights reserved.
28 * Copyright (c) 2013 Steven Hartland. All rights reserved.
29 * Copyright (c) 2014 Integros [integros.com]
30 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
31 * Copyright 2016 Nexenta Systems, Inc.
34 #include <assert.h>
35 #include <ctype.h>
36 #include <errno.h>
37 #include <getopt.h>
38 #include <libgen.h>
39 #include <libintl.h>
40 #include <libuutil.h>
41 #include <libnvpair.h>
42 #include <locale.h>
43 #include <stddef.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <strings.h>
47 #include <unistd.h>
48 #include <fcntl.h>
49 #include <zone.h>
50 #include <grp.h>
51 #include <pwd.h>
52 #include <signal.h>
53 #include <sys/debug.h>
54 #include <sys/list.h>
55 #include <sys/mkdev.h>
56 #include <sys/mntent.h>
57 #include <sys/mnttab.h>
58 #include <sys/mount.h>
59 #include <sys/stat.h>
60 #include <sys/fs/zfs.h>
61 #include <sys/types.h>
62 #include <time.h>
64 #include <libzfs.h>
65 #include <libzfs_core.h>
66 #include <zfs_prop.h>
67 #include <zfs_deleg.h>
68 #include <libuutil.h>
69 #include <aclutils.h>
70 #include <directory.h>
71 #include <idmap.h>
72 #include <libshare.h>
74 #include "zfs_iter.h"
75 #include "zfs_util.h"
76 #include "zfs_comutil.h"
78 libzfs_handle_t *g_zfs;
80 static FILE *mnttab_file;
81 static char history_str[HIS_MAX_RECORD_LEN];
82 static boolean_t log_history = B_TRUE;
84 static int zfs_do_clone(int argc, char **argv);
85 static int zfs_do_create(int argc, char **argv);
86 static int zfs_do_destroy(int argc, char **argv);
87 static int zfs_do_get(int argc, char **argv);
88 static int zfs_do_inherit(int argc, char **argv);
89 static int zfs_do_list(int argc, char **argv);
90 static int zfs_do_mount(int argc, char **argv);
91 static int zfs_do_rename(int argc, char **argv);
92 static int zfs_do_rollback(int argc, char **argv);
93 static int zfs_do_set(int argc, char **argv);
94 static int zfs_do_upgrade(int argc, char **argv);
95 static int zfs_do_snapshot(int argc, char **argv);
96 static int zfs_do_unmount(int argc, char **argv);
97 static int zfs_do_share(int argc, char **argv);
98 static int zfs_do_unshare(int argc, char **argv);
99 static int zfs_do_send(int argc, char **argv);
100 static int zfs_do_receive(int argc, char **argv);
101 static int zfs_do_promote(int argc, char **argv);
102 static int zfs_do_userspace(int argc, char **argv);
103 static int zfs_do_allow(int argc, char **argv);
104 static int zfs_do_unallow(int argc, char **argv);
105 static int zfs_do_hold(int argc, char **argv);
106 static int zfs_do_holds(int argc, char **argv);
107 static int zfs_do_release(int argc, char **argv);
108 static int zfs_do_diff(int argc, char **argv);
109 static int zfs_do_bookmark(int argc, char **argv);
110 static int zfs_do_channel_program(int argc, char **argv);
113 * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
116 #ifdef DEBUG
117 const char *
118 _umem_debug_init(void)
120 return ("default,verbose"); /* $UMEM_DEBUG setting */
123 const char *
124 _umem_logging_init(void)
126 return ("fail,contents"); /* $UMEM_LOGGING setting */
128 #endif
130 typedef enum {
131 HELP_CLONE,
132 HELP_CREATE,
133 HELP_DESTROY,
134 HELP_GET,
135 HELP_INHERIT,
136 HELP_UPGRADE,
137 HELP_LIST,
138 HELP_MOUNT,
139 HELP_PROMOTE,
140 HELP_RECEIVE,
141 HELP_RENAME,
142 HELP_ROLLBACK,
143 HELP_SEND,
144 HELP_SET,
145 HELP_SHARE,
146 HELP_SNAPSHOT,
147 HELP_UNMOUNT,
148 HELP_UNSHARE,
149 HELP_ALLOW,
150 HELP_UNALLOW,
151 HELP_USERSPACE,
152 HELP_GROUPSPACE,
153 HELP_HOLD,
154 HELP_HOLDS,
155 HELP_RELEASE,
156 HELP_DIFF,
157 HELP_BOOKMARK,
158 HELP_CHANNEL_PROGRAM,
159 } zfs_help_t;
161 typedef struct zfs_command {
162 const char *name;
163 int (*func)(int argc, char **argv);
164 zfs_help_t usage;
165 } zfs_command_t;
168 * Master command table. Each ZFS command has a name, associated function, and
169 * usage message. The usage messages need to be internationalized, so we have
170 * to have a function to return the usage message based on a command index.
172 * These commands are organized according to how they are displayed in the usage
173 * message. An empty command (one with a NULL name) indicates an empty line in
174 * the generic usage message.
176 static zfs_command_t command_table[] = {
177 { "create", zfs_do_create, HELP_CREATE },
178 { "destroy", zfs_do_destroy, HELP_DESTROY },
179 { NULL },
180 { "snapshot", zfs_do_snapshot, HELP_SNAPSHOT },
181 { "rollback", zfs_do_rollback, HELP_ROLLBACK },
182 { "clone", zfs_do_clone, HELP_CLONE },
183 { "promote", zfs_do_promote, HELP_PROMOTE },
184 { "rename", zfs_do_rename, HELP_RENAME },
185 { "bookmark", zfs_do_bookmark, HELP_BOOKMARK },
186 { "program", zfs_do_channel_program, HELP_CHANNEL_PROGRAM },
187 { NULL },
188 { "list", zfs_do_list, HELP_LIST },
189 { NULL },
190 { "set", zfs_do_set, HELP_SET },
191 { "get", zfs_do_get, HELP_GET },
192 { "inherit", zfs_do_inherit, HELP_INHERIT },
193 { "upgrade", zfs_do_upgrade, HELP_UPGRADE },
194 { "userspace", zfs_do_userspace, HELP_USERSPACE },
195 { "groupspace", zfs_do_userspace, HELP_GROUPSPACE },
196 { NULL },
197 { "mount", zfs_do_mount, HELP_MOUNT },
198 { "unmount", zfs_do_unmount, HELP_UNMOUNT },
199 { "share", zfs_do_share, HELP_SHARE },
200 { "unshare", zfs_do_unshare, HELP_UNSHARE },
201 { NULL },
202 { "send", zfs_do_send, HELP_SEND },
203 { "receive", zfs_do_receive, HELP_RECEIVE },
204 { NULL },
205 { "allow", zfs_do_allow, HELP_ALLOW },
206 { NULL },
207 { "unallow", zfs_do_unallow, HELP_UNALLOW },
208 { NULL },
209 { "hold", zfs_do_hold, HELP_HOLD },
210 { "holds", zfs_do_holds, HELP_HOLDS },
211 { "release", zfs_do_release, HELP_RELEASE },
212 { "diff", zfs_do_diff, HELP_DIFF },
215 #define NCOMMAND (sizeof (command_table) / sizeof (command_table[0]))
217 zfs_command_t *current_command;
219 static const char *
220 get_usage(zfs_help_t idx)
222 switch (idx) {
223 case HELP_CLONE:
224 return (gettext("\tclone [-p] [-o property=value] ... "
225 "<snapshot> <filesystem|volume>\n"));
226 case HELP_CREATE:
227 return (gettext("\tcreate [-p] [-o property=value] ... "
228 "<filesystem>\n"
229 "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
230 "-V <size> <volume>\n"));
231 case HELP_DESTROY:
232 return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
233 "\tdestroy [-dnpRrv] "
234 "<filesystem|volume>@<snap>[%<snap>][,...]\n"
235 "\tdestroy <filesystem|volume>#<bookmark>\n"));
236 case HELP_GET:
237 return (gettext("\tget [-rHp] [-d max] "
238 "[-o \"all\" | field[,...]]\n"
239 "\t [-t type[,...]] [-s source[,...]]\n"
240 "\t <\"all\" | property[,...]> "
241 "[filesystem|volume|snapshot|bookmark] ...\n"));
242 case HELP_INHERIT:
243 return (gettext("\tinherit [-rS] <property> "
244 "<filesystem|volume|snapshot> ...\n"));
245 case HELP_UPGRADE:
246 return (gettext("\tupgrade [-v]\n"
247 "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
248 case HELP_LIST:
249 return (gettext("\tlist [-Hp] [-r|-d max] [-o property[,...]] "
250 "[-s property]...\n\t [-S property]... [-t type[,...]] "
251 "[filesystem|volume|snapshot] ...\n"));
252 case HELP_MOUNT:
253 return (gettext("\tmount\n"
254 "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
255 case HELP_PROMOTE:
256 return (gettext("\tpromote <clone-filesystem>\n"));
257 case HELP_RECEIVE:
258 return (gettext("\treceive [-vnsFu] <filesystem|volume|"
259 "snapshot>\n"
260 "\treceive [-vnsFu] [-o origin=<snapshot>] [-d | -e] "
261 "<filesystem>\n"
262 "\treceive -A <filesystem|volume>\n"));
263 case HELP_RENAME:
264 return (gettext("\trename [-f] <filesystem|volume|snapshot> "
265 "<filesystem|volume|snapshot>\n"
266 "\trename [-f] -p <filesystem|volume> <filesystem|volume>\n"
267 "\trename -r <snapshot> <snapshot>\n"));
268 case HELP_ROLLBACK:
269 return (gettext("\trollback [-rRf] <snapshot>\n"));
270 case HELP_SEND:
271 return (gettext("\tsend [-DnPpRvLec] [-[iI] snapshot] "
272 "<snapshot>\n"
273 "\tsend [-Le] [-i snapshot|bookmark] "
274 "<filesystem|volume|snapshot>\n"
275 "\tsend [-nvPe] -t <receive_resume_token>\n"));
276 case HELP_SET:
277 return (gettext("\tset <property=value> ... "
278 "<filesystem|volume|snapshot> ...\n"));
279 case HELP_SHARE:
280 return (gettext("\tshare <-a | filesystem>\n"));
281 case HELP_SNAPSHOT:
282 return (gettext("\tsnapshot [-r] [-o property=value] ... "
283 "<filesystem|volume>@<snap> ...\n"));
284 case HELP_UNMOUNT:
285 return (gettext("\tunmount [-f] "
286 "<-a | filesystem|mountpoint>\n"));
287 case HELP_UNSHARE:
288 return (gettext("\tunshare "
289 "<-a | filesystem|mountpoint>\n"));
290 case HELP_ALLOW:
291 return (gettext("\tallow <filesystem|volume>\n"
292 "\tallow [-ldug] "
293 "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
294 "\t <filesystem|volume>\n"
295 "\tallow [-ld] -e <perm|@setname>[,...] "
296 "<filesystem|volume>\n"
297 "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
298 "\tallow -s @setname <perm|@setname>[,...] "
299 "<filesystem|volume>\n"));
300 case HELP_UNALLOW:
301 return (gettext("\tunallow [-rldug] "
302 "<\"everyone\"|user|group>[,...]\n"
303 "\t [<perm|@setname>[,...]] <filesystem|volume>\n"
304 "\tunallow [-rld] -e [<perm|@setname>[,...]] "
305 "<filesystem|volume>\n"
306 "\tunallow [-r] -c [<perm|@setname>[,...]] "
307 "<filesystem|volume>\n"
308 "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
309 "<filesystem|volume>\n"));
310 case HELP_USERSPACE:
311 return (gettext("\tuserspace [-Hinp] [-o field[,...]] "
312 "[-s field] ...\n"
313 "\t [-S field] ... [-t type[,...]] "
314 "<filesystem|snapshot>\n"));
315 case HELP_GROUPSPACE:
316 return (gettext("\tgroupspace [-Hinp] [-o field[,...]] "
317 "[-s field] ...\n"
318 "\t [-S field] ... [-t type[,...]] "
319 "<filesystem|snapshot>\n"));
320 case HELP_HOLD:
321 return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
322 case HELP_HOLDS:
323 return (gettext("\tholds [-r] <snapshot> ...\n"));
324 case HELP_RELEASE:
325 return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
326 case HELP_DIFF:
327 return (gettext("\tdiff [-FHt] <snapshot> "
328 "[snapshot|filesystem]\n"));
329 case HELP_BOOKMARK:
330 return (gettext("\tbookmark <snapshot> <bookmark>\n"));
331 case HELP_CHANNEL_PROGRAM:
332 return (gettext("\tprogram [-t <instruction limit>] "
333 "[-m <memory limit (b)>] <pool> <program file> "
334 "[lua args...]\n"));
337 abort();
338 /* NOTREACHED */
341 void
342 nomem(void)
344 (void) fprintf(stderr, gettext("internal error: out of memory\n"));
345 exit(1);
349 * Utility function to guarantee malloc() success.
352 void *
353 safe_malloc(size_t size)
355 void *data;
357 if ((data = calloc(1, size)) == NULL)
358 nomem();
360 return (data);
363 void *
364 safe_realloc(void *data, size_t size)
366 void *newp;
367 if ((newp = realloc(data, size)) == NULL) {
368 free(data);
369 nomem();
372 return (newp);
375 static char *
376 safe_strdup(char *str)
378 char *dupstr = strdup(str);
380 if (dupstr == NULL)
381 nomem();
383 return (dupstr);
387 * Callback routine that will print out information for each of
388 * the properties.
390 static int
391 usage_prop_cb(int prop, void *cb)
393 FILE *fp = cb;
395 (void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
397 if (zfs_prop_readonly(prop))
398 (void) fprintf(fp, " NO ");
399 else
400 (void) fprintf(fp, "YES ");
402 if (zfs_prop_inheritable(prop))
403 (void) fprintf(fp, " YES ");
404 else
405 (void) fprintf(fp, " NO ");
407 if (zfs_prop_values(prop) == NULL)
408 (void) fprintf(fp, "-\n");
409 else
410 (void) fprintf(fp, "%s\n", zfs_prop_values(prop));
412 return (ZPROP_CONT);
416 * Display usage message. If we're inside a command, display only the usage for
417 * that command. Otherwise, iterate over the entire command table and display
418 * a complete usage message.
420 static void
421 usage(boolean_t requested)
423 int i;
424 boolean_t show_properties = B_FALSE;
425 FILE *fp = requested ? stdout : stderr;
427 if (current_command == NULL) {
429 (void) fprintf(fp, gettext("usage: zfs command args ...\n"));
430 (void) fprintf(fp,
431 gettext("where 'command' is one of the following:\n\n"));
433 for (i = 0; i < NCOMMAND; i++) {
434 if (command_table[i].name == NULL)
435 (void) fprintf(fp, "\n");
436 else
437 (void) fprintf(fp, "%s",
438 get_usage(command_table[i].usage));
441 (void) fprintf(fp, gettext("\nEach dataset is of the form: "
442 "pool/[dataset/]*dataset[@name]\n"));
443 } else {
444 (void) fprintf(fp, gettext("usage:\n"));
445 (void) fprintf(fp, "%s", get_usage(current_command->usage));
448 if (current_command != NULL &&
449 (strcmp(current_command->name, "set") == 0 ||
450 strcmp(current_command->name, "get") == 0 ||
451 strcmp(current_command->name, "inherit") == 0 ||
452 strcmp(current_command->name, "list") == 0))
453 show_properties = B_TRUE;
455 if (show_properties) {
456 (void) fprintf(fp,
457 gettext("\nThe following properties are supported:\n"));
459 (void) fprintf(fp, "\n\t%-14s %s %s %s\n\n",
460 "PROPERTY", "EDIT", "INHERIT", "VALUES");
462 /* Iterate over all properties */
463 (void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
464 ZFS_TYPE_DATASET);
466 (void) fprintf(fp, "\t%-15s ", "userused@...");
467 (void) fprintf(fp, " NO NO <size>\n");
468 (void) fprintf(fp, "\t%-15s ", "groupused@...");
469 (void) fprintf(fp, " NO NO <size>\n");
470 (void) fprintf(fp, "\t%-15s ", "userquota@...");
471 (void) fprintf(fp, "YES NO <size> | none\n");
472 (void) fprintf(fp, "\t%-15s ", "groupquota@...");
473 (void) fprintf(fp, "YES NO <size> | none\n");
474 (void) fprintf(fp, "\t%-15s ", "written@<snap>");
475 (void) fprintf(fp, " NO NO <size>\n");
477 (void) fprintf(fp, gettext("\nSizes are specified in bytes "
478 "with standard units such as K, M, G, etc.\n"));
479 (void) fprintf(fp, gettext("\nUser-defined properties can "
480 "be specified by using a name containing a colon (:).\n"));
481 (void) fprintf(fp, gettext("\nThe {user|group}{used|quota}@ "
482 "properties must be appended with\n"
483 "a user or group specifier of one of these forms:\n"
484 " POSIX name (eg: \"matt\")\n"
485 " POSIX id (eg: \"126829\")\n"
486 " SMB name@domain (eg: \"matt@sun\")\n"
487 " SMB SID (eg: \"S-1-234-567-89\")\n"));
488 } else {
489 (void) fprintf(fp,
490 gettext("\nFor the property list, run: %s\n"),
491 "zfs set|get");
492 (void) fprintf(fp,
493 gettext("\nFor the delegated permission list, run: %s\n"),
494 "zfs allow|unallow");
498 * See comments at end of main().
500 if (getenv("ZFS_ABORT") != NULL) {
501 (void) printf("dumping core by request\n");
502 abort();
505 exit(requested ? 0 : 2);
509 * Take a property=value argument string and add it to the given nvlist.
510 * Modifies the argument inplace.
512 static int
513 parseprop(nvlist_t *props, char *propname)
515 char *propval, *strval;
517 if ((propval = strchr(propname, '=')) == NULL) {
518 (void) fprintf(stderr, gettext("missing "
519 "'=' for property=value argument\n"));
520 return (-1);
522 *propval = '\0';
523 propval++;
524 if (nvlist_lookup_string(props, propname, &strval) == 0) {
525 (void) fprintf(stderr, gettext("property '%s' "
526 "specified multiple times\n"), propname);
527 return (-1);
529 if (nvlist_add_string(props, propname, propval) != 0)
530 nomem();
531 return (0);
534 static int
535 parse_depth(char *opt, int *flags)
537 char *tmp;
538 int depth;
540 depth = (int)strtol(opt, &tmp, 0);
541 if (*tmp) {
542 (void) fprintf(stderr,
543 gettext("%s is not an integer\n"), optarg);
544 usage(B_FALSE);
546 if (depth < 0) {
547 (void) fprintf(stderr,
548 gettext("Depth can not be negative.\n"));
549 usage(B_FALSE);
551 *flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
552 return (depth);
555 #define PROGRESS_DELAY 2 /* seconds */
557 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";
558 static time_t pt_begin;
559 static char *pt_header = NULL;
560 static boolean_t pt_shown;
562 static void
563 start_progress_timer(void)
565 pt_begin = time(NULL) + PROGRESS_DELAY;
566 pt_shown = B_FALSE;
569 static void
570 set_progress_header(char *header)
572 assert(pt_header == NULL);
573 pt_header = safe_strdup(header);
574 if (pt_shown) {
575 (void) printf("%s: ", header);
576 (void) fflush(stdout);
580 static void
581 update_progress(char *update)
583 if (!pt_shown && time(NULL) > pt_begin) {
584 int len = strlen(update);
586 (void) printf("%s: %s%*.*s", pt_header, update, len, len,
587 pt_reverse);
588 (void) fflush(stdout);
589 pt_shown = B_TRUE;
590 } else if (pt_shown) {
591 int len = strlen(update);
593 (void) printf("%s%*.*s", update, len, len, pt_reverse);
594 (void) fflush(stdout);
598 static void
599 finish_progress(char *done)
601 if (pt_shown) {
602 (void) printf("%s\n", done);
603 (void) fflush(stdout);
605 free(pt_header);
606 pt_header = NULL;
610 * Check if the dataset is mountable and should be automatically mounted.
612 static boolean_t
613 should_auto_mount(zfs_handle_t *zhp)
615 if (!zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, zfs_get_type(zhp)))
616 return (B_FALSE);
617 return (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_ON);
621 * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
623 * Given an existing dataset, create a writable copy whose initial contents
624 * are the same as the source. The newly created dataset maintains a
625 * dependency on the original; the original cannot be destroyed so long as
626 * the clone exists.
628 * The '-p' flag creates all the non-existing ancestors of the target first.
630 static int
631 zfs_do_clone(int argc, char **argv)
633 zfs_handle_t *zhp = NULL;
634 boolean_t parents = B_FALSE;
635 nvlist_t *props;
636 int ret = 0;
637 int c;
639 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
640 nomem();
642 /* check options */
643 while ((c = getopt(argc, argv, "o:p")) != -1) {
644 switch (c) {
645 case 'o':
646 if (parseprop(props, optarg) != 0)
647 return (1);
648 break;
649 case 'p':
650 parents = B_TRUE;
651 break;
652 case '?':
653 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
654 optopt);
655 goto usage;
659 argc -= optind;
660 argv += optind;
662 /* check number of arguments */
663 if (argc < 1) {
664 (void) fprintf(stderr, gettext("missing source dataset "
665 "argument\n"));
666 goto usage;
668 if (argc < 2) {
669 (void) fprintf(stderr, gettext("missing target dataset "
670 "argument\n"));
671 goto usage;
673 if (argc > 2) {
674 (void) fprintf(stderr, gettext("too many arguments\n"));
675 goto usage;
678 /* open the source dataset */
679 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
680 return (1);
682 if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
683 ZFS_TYPE_VOLUME)) {
685 * Now create the ancestors of the target dataset. If the
686 * target already exists and '-p' option was used we should not
687 * complain.
689 if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
690 ZFS_TYPE_VOLUME))
691 return (0);
692 if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
693 return (1);
696 /* pass to libzfs */
697 ret = zfs_clone(zhp, argv[1], props);
699 /* create the mountpoint if necessary */
700 if (ret == 0) {
701 zfs_handle_t *clone;
703 clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
704 if (clone != NULL) {
706 * If the user doesn't want the dataset
707 * automatically mounted, then skip the mount/share
708 * step.
710 if (should_auto_mount(clone)) {
711 if ((ret = zfs_mount(clone, NULL, 0)) != 0) {
712 (void) fprintf(stderr, gettext("clone "
713 "successfully created, "
714 "but not mounted\n"));
715 } else if ((ret = zfs_share(clone)) != 0) {
716 (void) fprintf(stderr, gettext("clone "
717 "successfully created, "
718 "but not shared\n"));
721 zfs_close(clone);
725 zfs_close(zhp);
726 nvlist_free(props);
728 return (!!ret);
730 usage:
731 if (zhp)
732 zfs_close(zhp);
733 nvlist_free(props);
734 usage(B_FALSE);
735 return (-1);
739 * zfs create [-p] [-o prop=value] ... fs
740 * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
742 * Create a new dataset. This command can be used to create filesystems
743 * and volumes. Snapshot creation is handled by 'zfs snapshot'.
744 * For volumes, the user must specify a size to be used.
746 * The '-s' flag applies only to volumes, and indicates that we should not try
747 * to set the reservation for this volume. By default we set a reservation
748 * equal to the size for any volume. For pools with SPA_VERSION >=
749 * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
751 * The '-p' flag creates all the non-existing ancestors of the target first.
753 static int
754 zfs_do_create(int argc, char **argv)
756 zfs_type_t type = ZFS_TYPE_FILESYSTEM;
757 zfs_handle_t *zhp = NULL;
758 uint64_t volsize = 0;
759 int c;
760 boolean_t noreserve = B_FALSE;
761 boolean_t bflag = B_FALSE;
762 boolean_t parents = B_FALSE;
763 int ret = 1;
764 nvlist_t *props;
765 uint64_t intval;
767 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
768 nomem();
770 /* check options */
771 while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
772 switch (c) {
773 case 'V':
774 type = ZFS_TYPE_VOLUME;
775 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
776 (void) fprintf(stderr, gettext("bad volume "
777 "size '%s': %s\n"), optarg,
778 libzfs_error_description(g_zfs));
779 goto error;
782 if (nvlist_add_uint64(props,
783 zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
784 nomem();
785 volsize = intval;
786 break;
787 case 'p':
788 parents = B_TRUE;
789 break;
790 case 'b':
791 bflag = B_TRUE;
792 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
793 (void) fprintf(stderr, gettext("bad volume "
794 "block size '%s': %s\n"), optarg,
795 libzfs_error_description(g_zfs));
796 goto error;
799 if (nvlist_add_uint64(props,
800 zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
801 intval) != 0)
802 nomem();
803 break;
804 case 'o':
805 if (parseprop(props, optarg) != 0)
806 goto error;
807 break;
808 case 's':
809 noreserve = B_TRUE;
810 break;
811 case ':':
812 (void) fprintf(stderr, gettext("missing size "
813 "argument\n"));
814 goto badusage;
815 case '?':
816 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
817 optopt);
818 goto badusage;
822 if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
823 (void) fprintf(stderr, gettext("'-s' and '-b' can only be "
824 "used when creating a volume\n"));
825 goto badusage;
828 argc -= optind;
829 argv += optind;
831 /* check number of arguments */
832 if (argc == 0) {
833 (void) fprintf(stderr, gettext("missing %s argument\n"),
834 zfs_type_to_name(type));
835 goto badusage;
837 if (argc > 1) {
838 (void) fprintf(stderr, gettext("too many arguments\n"));
839 goto badusage;
842 if (type == ZFS_TYPE_VOLUME && !noreserve) {
843 zpool_handle_t *zpool_handle;
844 nvlist_t *real_props = NULL;
845 uint64_t spa_version;
846 char *p;
847 zfs_prop_t resv_prop;
848 char *strval;
849 char msg[1024];
851 if ((p = strchr(argv[0], '/')) != NULL)
852 *p = '\0';
853 zpool_handle = zpool_open(g_zfs, argv[0]);
854 if (p != NULL)
855 *p = '/';
856 if (zpool_handle == NULL)
857 goto error;
858 spa_version = zpool_get_prop_int(zpool_handle,
859 ZPOOL_PROP_VERSION, NULL);
860 if (spa_version >= SPA_VERSION_REFRESERVATION)
861 resv_prop = ZFS_PROP_REFRESERVATION;
862 else
863 resv_prop = ZFS_PROP_RESERVATION;
865 (void) snprintf(msg, sizeof (msg),
866 gettext("cannot create '%s'"), argv[0]);
867 if (props && (real_props = zfs_valid_proplist(g_zfs, type,
868 props, 0, NULL, zpool_handle, msg)) == NULL) {
869 zpool_close(zpool_handle);
870 goto error;
872 zpool_close(zpool_handle);
874 volsize = zvol_volsize_to_reservation(volsize, real_props);
875 nvlist_free(real_props);
877 if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
878 &strval) != 0) {
879 if (nvlist_add_uint64(props,
880 zfs_prop_to_name(resv_prop), volsize) != 0) {
881 nvlist_free(props);
882 nomem();
887 if (parents && zfs_name_valid(argv[0], type)) {
889 * Now create the ancestors of target dataset. If the target
890 * already exists and '-p' option was used we should not
891 * complain.
893 if (zfs_dataset_exists(g_zfs, argv[0], type)) {
894 ret = 0;
895 goto error;
897 if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
898 goto error;
901 /* pass to libzfs */
902 if (zfs_create(g_zfs, argv[0], type, props) != 0)
903 goto error;
905 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
906 goto error;
908 ret = 0;
911 * Mount and/or share the new filesystem as appropriate. We provide a
912 * verbose error message to let the user know that their filesystem was
913 * in fact created, even if we failed to mount or share it.
914 * If the user doesn't want the dataset automatically mounted,
915 * then skip the mount/share step altogether.
917 if (should_auto_mount(zhp)) {
918 if (zfs_mount(zhp, NULL, 0) != 0) {
919 (void) fprintf(stderr, gettext("filesystem "
920 "successfully created, but not mounted\n"));
921 ret = 1;
922 } else if (zfs_share(zhp) != 0) {
923 (void) fprintf(stderr, gettext("filesystem "
924 "successfully created, but not shared\n"));
925 ret = 1;
929 error:
930 if (zhp)
931 zfs_close(zhp);
932 nvlist_free(props);
933 return (ret);
934 badusage:
935 nvlist_free(props);
936 usage(B_FALSE);
937 return (2);
941 * zfs destroy [-rRf] <fs, vol>
942 * zfs destroy [-rRd] <snap>
944 * -r Recursively destroy all children
945 * -R Recursively destroy all dependents, including clones
946 * -f Force unmounting of any dependents
947 * -d If we can't destroy now, mark for deferred destruction
949 * Destroys the given dataset. By default, it will unmount any filesystems,
950 * and refuse to destroy a dataset that has any dependents. A dependent can
951 * either be a child, or a clone of a child.
953 typedef struct destroy_cbdata {
954 boolean_t cb_first;
955 boolean_t cb_force;
956 boolean_t cb_recurse;
957 boolean_t cb_error;
958 boolean_t cb_doclones;
959 zfs_handle_t *cb_target;
960 boolean_t cb_defer_destroy;
961 boolean_t cb_verbose;
962 boolean_t cb_parsable;
963 boolean_t cb_dryrun;
964 nvlist_t *cb_nvl;
965 nvlist_t *cb_batchedsnaps;
967 /* first snap in contiguous run */
968 char *cb_firstsnap;
969 /* previous snap in contiguous run */
970 char *cb_prevsnap;
971 int64_t cb_snapused;
972 char *cb_snapspec;
973 char *cb_bookmark;
974 } destroy_cbdata_t;
977 * Check for any dependents based on the '-r' or '-R' flags.
979 static int
980 destroy_check_dependent(zfs_handle_t *zhp, void *data)
982 destroy_cbdata_t *cbp = data;
983 const char *tname = zfs_get_name(cbp->cb_target);
984 const char *name = zfs_get_name(zhp);
986 if (strncmp(tname, name, strlen(tname)) == 0 &&
987 (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
989 * This is a direct descendant, not a clone somewhere else in
990 * the hierarchy.
992 if (cbp->cb_recurse)
993 goto out;
995 if (cbp->cb_first) {
996 (void) fprintf(stderr, gettext("cannot destroy '%s': "
997 "%s has children\n"),
998 zfs_get_name(cbp->cb_target),
999 zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1000 (void) fprintf(stderr, gettext("use '-r' to destroy "
1001 "the following datasets:\n"));
1002 cbp->cb_first = B_FALSE;
1003 cbp->cb_error = B_TRUE;
1006 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1007 } else {
1009 * This is a clone. We only want to report this if the '-r'
1010 * wasn't specified, or the target is a snapshot.
1012 if (!cbp->cb_recurse &&
1013 zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
1014 goto out;
1016 if (cbp->cb_first) {
1017 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1018 "%s has dependent clones\n"),
1019 zfs_get_name(cbp->cb_target),
1020 zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1021 (void) fprintf(stderr, gettext("use '-R' to destroy "
1022 "the following datasets:\n"));
1023 cbp->cb_first = B_FALSE;
1024 cbp->cb_error = B_TRUE;
1025 cbp->cb_dryrun = B_TRUE;
1028 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1031 out:
1032 zfs_close(zhp);
1033 return (0);
1036 static int
1037 destroy_callback(zfs_handle_t *zhp, void *data)
1039 destroy_cbdata_t *cb = data;
1040 const char *name = zfs_get_name(zhp);
1042 if (cb->cb_verbose) {
1043 if (cb->cb_parsable) {
1044 (void) printf("destroy\t%s\n", name);
1045 } else if (cb->cb_dryrun) {
1046 (void) printf(gettext("would destroy %s\n"),
1047 name);
1048 } else {
1049 (void) printf(gettext("will destroy %s\n"),
1050 name);
1055 * Ignore pools (which we've already flagged as an error before getting
1056 * here).
1058 if (strchr(zfs_get_name(zhp), '/') == NULL &&
1059 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1060 zfs_close(zhp);
1061 return (0);
1063 if (cb->cb_dryrun) {
1064 zfs_close(zhp);
1065 return (0);
1069 * We batch up all contiguous snapshots (even of different
1070 * filesystems) and destroy them with one ioctl. We can't
1071 * simply do all snap deletions and then all fs deletions,
1072 * because we must delete a clone before its origin.
1074 if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT) {
1075 fnvlist_add_boolean(cb->cb_batchedsnaps, name);
1076 } else {
1077 int error = zfs_destroy_snaps_nvl(g_zfs,
1078 cb->cb_batchedsnaps, B_FALSE);
1079 fnvlist_free(cb->cb_batchedsnaps);
1080 cb->cb_batchedsnaps = fnvlist_alloc();
1082 if (error != 0 ||
1083 zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
1084 zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
1085 zfs_close(zhp);
1086 return (-1);
1090 zfs_close(zhp);
1091 return (0);
1094 static int
1095 destroy_print_cb(zfs_handle_t *zhp, void *arg)
1097 destroy_cbdata_t *cb = arg;
1098 const char *name = zfs_get_name(zhp);
1099 int err = 0;
1101 if (nvlist_exists(cb->cb_nvl, name)) {
1102 if (cb->cb_firstsnap == NULL)
1103 cb->cb_firstsnap = strdup(name);
1104 free(cb->cb_prevsnap);
1105 /* this snap continues the current range */
1106 cb->cb_prevsnap = strdup(name);
1107 if (cb->cb_firstsnap == NULL || cb->cb_prevsnap == NULL)
1108 nomem();
1109 if (cb->cb_verbose) {
1110 if (cb->cb_parsable) {
1111 (void) printf("destroy\t%s\n", name);
1112 } else if (cb->cb_dryrun) {
1113 (void) printf(gettext("would destroy %s\n"),
1114 name);
1115 } else {
1116 (void) printf(gettext("will destroy %s\n"),
1117 name);
1120 } else if (cb->cb_firstsnap != NULL) {
1121 /* end of this range */
1122 uint64_t used = 0;
1123 err = lzc_snaprange_space(cb->cb_firstsnap,
1124 cb->cb_prevsnap, &used);
1125 cb->cb_snapused += used;
1126 free(cb->cb_firstsnap);
1127 cb->cb_firstsnap = NULL;
1128 free(cb->cb_prevsnap);
1129 cb->cb_prevsnap = NULL;
1131 zfs_close(zhp);
1132 return (err);
1135 static int
1136 destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
1138 int err = 0;
1139 assert(cb->cb_firstsnap == NULL);
1140 assert(cb->cb_prevsnap == NULL);
1141 err = zfs_iter_snapshots_sorted(fs_zhp, destroy_print_cb, cb);
1142 if (cb->cb_firstsnap != NULL) {
1143 uint64_t used = 0;
1144 if (err == 0) {
1145 err = lzc_snaprange_space(cb->cb_firstsnap,
1146 cb->cb_prevsnap, &used);
1148 cb->cb_snapused += used;
1149 free(cb->cb_firstsnap);
1150 cb->cb_firstsnap = NULL;
1151 free(cb->cb_prevsnap);
1152 cb->cb_prevsnap = NULL;
1154 return (err);
1157 static int
1158 snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
1160 destroy_cbdata_t *cb = arg;
1161 int err = 0;
1163 /* Check for clones. */
1164 if (!cb->cb_doclones && !cb->cb_defer_destroy) {
1165 cb->cb_target = zhp;
1166 cb->cb_first = B_TRUE;
1167 err = zfs_iter_dependents(zhp, B_TRUE,
1168 destroy_check_dependent, cb);
1171 if (err == 0) {
1172 if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
1173 nomem();
1175 zfs_close(zhp);
1176 return (err);
1179 static int
1180 gather_snapshots(zfs_handle_t *zhp, void *arg)
1182 destroy_cbdata_t *cb = arg;
1183 int err = 0;
1185 err = zfs_iter_snapspec(zhp, cb->cb_snapspec, snapshot_to_nvl_cb, cb);
1186 if (err == ENOENT)
1187 err = 0;
1188 if (err != 0)
1189 goto out;
1191 if (cb->cb_verbose) {
1192 err = destroy_print_snapshots(zhp, cb);
1193 if (err != 0)
1194 goto out;
1197 if (cb->cb_recurse)
1198 err = zfs_iter_filesystems(zhp, gather_snapshots, cb);
1200 out:
1201 zfs_close(zhp);
1202 return (err);
1205 static int
1206 destroy_clones(destroy_cbdata_t *cb)
1208 nvpair_t *pair;
1209 for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
1210 pair != NULL;
1211 pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
1212 zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
1213 ZFS_TYPE_SNAPSHOT);
1214 if (zhp != NULL) {
1215 boolean_t defer = cb->cb_defer_destroy;
1216 int err = 0;
1219 * We can't defer destroy non-snapshots, so set it to
1220 * false while destroying the clones.
1222 cb->cb_defer_destroy = B_FALSE;
1223 err = zfs_iter_dependents(zhp, B_FALSE,
1224 destroy_callback, cb);
1225 cb->cb_defer_destroy = defer;
1226 zfs_close(zhp);
1227 if (err != 0)
1228 return (err);
1231 return (0);
1234 static int
1235 zfs_do_destroy(int argc, char **argv)
1237 destroy_cbdata_t cb = { 0 };
1238 int rv = 0;
1239 int err = 0;
1240 int c;
1241 zfs_handle_t *zhp = NULL;
1242 char *at, *pound;
1243 zfs_type_t type = ZFS_TYPE_DATASET;
1245 /* check options */
1246 while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
1247 switch (c) {
1248 case 'v':
1249 cb.cb_verbose = B_TRUE;
1250 break;
1251 case 'p':
1252 cb.cb_verbose = B_TRUE;
1253 cb.cb_parsable = B_TRUE;
1254 break;
1255 case 'n':
1256 cb.cb_dryrun = B_TRUE;
1257 break;
1258 case 'd':
1259 cb.cb_defer_destroy = B_TRUE;
1260 type = ZFS_TYPE_SNAPSHOT;
1261 break;
1262 case 'f':
1263 cb.cb_force = B_TRUE;
1264 break;
1265 case 'r':
1266 cb.cb_recurse = B_TRUE;
1267 break;
1268 case 'R':
1269 cb.cb_recurse = B_TRUE;
1270 cb.cb_doclones = B_TRUE;
1271 break;
1272 case '?':
1273 default:
1274 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1275 optopt);
1276 usage(B_FALSE);
1280 argc -= optind;
1281 argv += optind;
1283 /* check number of arguments */
1284 if (argc == 0) {
1285 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1286 usage(B_FALSE);
1288 if (argc > 1) {
1289 (void) fprintf(stderr, gettext("too many arguments\n"));
1290 usage(B_FALSE);
1293 at = strchr(argv[0], '@');
1294 pound = strchr(argv[0], '#');
1295 if (at != NULL) {
1297 /* Build the list of snaps to destroy in cb_nvl. */
1298 cb.cb_nvl = fnvlist_alloc();
1300 *at = '\0';
1301 zhp = zfs_open(g_zfs, argv[0],
1302 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1303 if (zhp == NULL)
1304 return (1);
1306 cb.cb_snapspec = at + 1;
1307 if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
1308 cb.cb_error) {
1309 rv = 1;
1310 goto out;
1313 if (nvlist_empty(cb.cb_nvl)) {
1314 (void) fprintf(stderr, gettext("could not find any "
1315 "snapshots to destroy; check snapshot names.\n"));
1316 rv = 1;
1317 goto out;
1320 if (cb.cb_verbose) {
1321 char buf[16];
1322 zfs_nicenum(cb.cb_snapused, buf, sizeof (buf));
1323 if (cb.cb_parsable) {
1324 (void) printf("reclaim\t%llu\n",
1325 cb.cb_snapused);
1326 } else if (cb.cb_dryrun) {
1327 (void) printf(gettext("would reclaim %s\n"),
1328 buf);
1329 } else {
1330 (void) printf(gettext("will reclaim %s\n"),
1331 buf);
1335 if (!cb.cb_dryrun) {
1336 if (cb.cb_doclones) {
1337 cb.cb_batchedsnaps = fnvlist_alloc();
1338 err = destroy_clones(&cb);
1339 if (err == 0) {
1340 err = zfs_destroy_snaps_nvl(g_zfs,
1341 cb.cb_batchedsnaps, B_FALSE);
1343 if (err != 0) {
1344 rv = 1;
1345 goto out;
1348 if (err == 0) {
1349 err = zfs_destroy_snaps_nvl(g_zfs, cb.cb_nvl,
1350 cb.cb_defer_destroy);
1354 if (err != 0)
1355 rv = 1;
1356 } else if (pound != NULL) {
1357 int err;
1358 nvlist_t *nvl;
1360 if (cb.cb_dryrun) {
1361 (void) fprintf(stderr,
1362 "dryrun is not supported with bookmark\n");
1363 return (-1);
1366 if (cb.cb_defer_destroy) {
1367 (void) fprintf(stderr,
1368 "defer destroy is not supported with bookmark\n");
1369 return (-1);
1372 if (cb.cb_recurse) {
1373 (void) fprintf(stderr,
1374 "recursive is not supported with bookmark\n");
1375 return (-1);
1378 if (!zfs_bookmark_exists(argv[0])) {
1379 (void) fprintf(stderr, gettext("bookmark '%s' "
1380 "does not exist.\n"), argv[0]);
1381 return (1);
1384 nvl = fnvlist_alloc();
1385 fnvlist_add_boolean(nvl, argv[0]);
1387 err = lzc_destroy_bookmarks(nvl, NULL);
1388 if (err != 0) {
1389 (void) zfs_standard_error(g_zfs, err,
1390 "cannot destroy bookmark");
1393 nvlist_free(cb.cb_nvl);
1395 return (err);
1396 } else {
1397 /* Open the given dataset */
1398 if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1399 return (1);
1401 cb.cb_target = zhp;
1404 * Perform an explicit check for pools before going any further.
1406 if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1407 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1408 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1409 "operation does not apply to pools\n"),
1410 zfs_get_name(zhp));
1411 (void) fprintf(stderr, gettext("use 'zfs destroy -r "
1412 "%s' to destroy all datasets in the pool\n"),
1413 zfs_get_name(zhp));
1414 (void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1415 "to destroy the pool itself\n"), zfs_get_name(zhp));
1416 rv = 1;
1417 goto out;
1421 * Check for any dependents and/or clones.
1423 cb.cb_first = B_TRUE;
1424 if (!cb.cb_doclones &&
1425 zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
1426 &cb) != 0) {
1427 rv = 1;
1428 goto out;
1431 if (cb.cb_error) {
1432 rv = 1;
1433 goto out;
1436 cb.cb_batchedsnaps = fnvlist_alloc();
1437 if (zfs_iter_dependents(zhp, B_FALSE, destroy_callback,
1438 &cb) != 0) {
1439 rv = 1;
1440 goto out;
1444 * Do the real thing. The callback will close the
1445 * handle regardless of whether it succeeds or not.
1447 err = destroy_callback(zhp, &cb);
1448 zhp = NULL;
1449 if (err == 0) {
1450 err = zfs_destroy_snaps_nvl(g_zfs,
1451 cb.cb_batchedsnaps, cb.cb_defer_destroy);
1453 if (err != 0)
1454 rv = 1;
1457 out:
1458 fnvlist_free(cb.cb_batchedsnaps);
1459 fnvlist_free(cb.cb_nvl);
1460 if (zhp != NULL)
1461 zfs_close(zhp);
1462 return (rv);
1465 static boolean_t
1466 is_recvd_column(zprop_get_cbdata_t *cbp)
1468 int i;
1469 zfs_get_column_t col;
1471 for (i = 0; i < ZFS_GET_NCOLS &&
1472 (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1473 if (col == GET_COL_RECVD)
1474 return (B_TRUE);
1475 return (B_FALSE);
1479 * zfs get [-rHp] [-o all | field[,field]...] [-s source[,source]...]
1480 * < all | property[,property]... > < fs | snap | vol > ...
1482 * -r recurse over any child datasets
1483 * -H scripted mode. Headers are stripped, and fields are separated
1484 * by tabs instead of spaces.
1485 * -o Set of fields to display. One of "name,property,value,
1486 * received,source". Default is "name,property,value,source".
1487 * "all" is an alias for all five.
1488 * -s Set of sources to allow. One of
1489 * "local,default,inherited,received,temporary,none". Default is
1490 * all six.
1491 * -p Display values in parsable (literal) format.
1493 * Prints properties for the given datasets. The user can control which
1494 * columns to display as well as which property types to allow.
1498 * Invoked to display the properties for a single dataset.
1500 static int
1501 get_callback(zfs_handle_t *zhp, void *data)
1503 char buf[ZFS_MAXPROPLEN];
1504 char rbuf[ZFS_MAXPROPLEN];
1505 zprop_source_t sourcetype;
1506 char source[ZFS_MAX_DATASET_NAME_LEN];
1507 zprop_get_cbdata_t *cbp = data;
1508 nvlist_t *user_props = zfs_get_user_props(zhp);
1509 zprop_list_t *pl = cbp->cb_proplist;
1510 nvlist_t *propval;
1511 char *strval;
1512 char *sourceval;
1513 boolean_t received = is_recvd_column(cbp);
1515 for (; pl != NULL; pl = pl->pl_next) {
1516 char *recvdval = NULL;
1518 * Skip the special fake placeholder. This will also skip over
1519 * the name property when 'all' is specified.
1521 if (pl->pl_prop == ZFS_PROP_NAME &&
1522 pl == cbp->cb_proplist)
1523 continue;
1525 if (pl->pl_prop != ZPROP_INVAL) {
1526 if (zfs_prop_get(zhp, pl->pl_prop, buf,
1527 sizeof (buf), &sourcetype, source,
1528 sizeof (source),
1529 cbp->cb_literal) != 0) {
1530 if (pl->pl_all)
1531 continue;
1532 if (!zfs_prop_valid_for_type(pl->pl_prop,
1533 ZFS_TYPE_DATASET)) {
1534 (void) fprintf(stderr,
1535 gettext("No such property '%s'\n"),
1536 zfs_prop_to_name(pl->pl_prop));
1537 continue;
1539 sourcetype = ZPROP_SRC_NONE;
1540 (void) strlcpy(buf, "-", sizeof (buf));
1543 if (received && (zfs_prop_get_recvd(zhp,
1544 zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
1545 cbp->cb_literal) == 0))
1546 recvdval = rbuf;
1548 zprop_print_one_property(zfs_get_name(zhp), cbp,
1549 zfs_prop_to_name(pl->pl_prop),
1550 buf, sourcetype, source, recvdval);
1551 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
1552 sourcetype = ZPROP_SRC_LOCAL;
1554 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1555 buf, sizeof (buf), cbp->cb_literal) != 0) {
1556 sourcetype = ZPROP_SRC_NONE;
1557 (void) strlcpy(buf, "-", sizeof (buf));
1560 zprop_print_one_property(zfs_get_name(zhp), cbp,
1561 pl->pl_user_prop, buf, sourcetype, source, NULL);
1562 } else if (zfs_prop_written(pl->pl_user_prop)) {
1563 sourcetype = ZPROP_SRC_LOCAL;
1565 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
1566 buf, sizeof (buf), cbp->cb_literal) != 0) {
1567 sourcetype = ZPROP_SRC_NONE;
1568 (void) strlcpy(buf, "-", sizeof (buf));
1571 zprop_print_one_property(zfs_get_name(zhp), cbp,
1572 pl->pl_user_prop, buf, sourcetype, source, NULL);
1573 } else {
1574 if (nvlist_lookup_nvlist(user_props,
1575 pl->pl_user_prop, &propval) != 0) {
1576 if (pl->pl_all)
1577 continue;
1578 sourcetype = ZPROP_SRC_NONE;
1579 strval = "-";
1580 } else {
1581 verify(nvlist_lookup_string(propval,
1582 ZPROP_VALUE, &strval) == 0);
1583 verify(nvlist_lookup_string(propval,
1584 ZPROP_SOURCE, &sourceval) == 0);
1586 if (strcmp(sourceval,
1587 zfs_get_name(zhp)) == 0) {
1588 sourcetype = ZPROP_SRC_LOCAL;
1589 } else if (strcmp(sourceval,
1590 ZPROP_SOURCE_VAL_RECVD) == 0) {
1591 sourcetype = ZPROP_SRC_RECEIVED;
1592 } else {
1593 sourcetype = ZPROP_SRC_INHERITED;
1594 (void) strlcpy(source,
1595 sourceval, sizeof (source));
1599 if (received && (zfs_prop_get_recvd(zhp,
1600 pl->pl_user_prop, rbuf, sizeof (rbuf),
1601 cbp->cb_literal) == 0))
1602 recvdval = rbuf;
1604 zprop_print_one_property(zfs_get_name(zhp), cbp,
1605 pl->pl_user_prop, strval, sourcetype,
1606 source, recvdval);
1610 return (0);
1613 static int
1614 zfs_do_get(int argc, char **argv)
1616 zprop_get_cbdata_t cb = { 0 };
1617 int i, c, flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1618 int types = ZFS_TYPE_DATASET | ZFS_TYPE_BOOKMARK;
1619 char *value, *fields;
1620 int ret = 0;
1621 int limit = 0;
1622 zprop_list_t fake_name = { 0 };
1625 * Set up default columns and sources.
1627 cb.cb_sources = ZPROP_SRC_ALL;
1628 cb.cb_columns[0] = GET_COL_NAME;
1629 cb.cb_columns[1] = GET_COL_PROPERTY;
1630 cb.cb_columns[2] = GET_COL_VALUE;
1631 cb.cb_columns[3] = GET_COL_SOURCE;
1632 cb.cb_type = ZFS_TYPE_DATASET;
1634 /* check options */
1635 while ((c = getopt(argc, argv, ":d:o:s:rt:Hp")) != -1) {
1636 switch (c) {
1637 case 'p':
1638 cb.cb_literal = B_TRUE;
1639 break;
1640 case 'd':
1641 limit = parse_depth(optarg, &flags);
1642 break;
1643 case 'r':
1644 flags |= ZFS_ITER_RECURSE;
1645 break;
1646 case 'H':
1647 cb.cb_scripted = B_TRUE;
1648 break;
1649 case ':':
1650 (void) fprintf(stderr, gettext("missing argument for "
1651 "'%c' option\n"), optopt);
1652 usage(B_FALSE);
1653 break;
1654 case 'o':
1656 * Process the set of columns to display. We zero out
1657 * the structure to give us a blank slate.
1659 bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1660 i = 0;
1661 while (*optarg != '\0') {
1662 static char *col_subopts[] =
1663 { "name", "property", "value", "received",
1664 "source", "all", NULL };
1666 if (i == ZFS_GET_NCOLS) {
1667 (void) fprintf(stderr, gettext("too "
1668 "many fields given to -o "
1669 "option\n"));
1670 usage(B_FALSE);
1673 switch (getsubopt(&optarg, col_subopts,
1674 &value)) {
1675 case 0:
1676 cb.cb_columns[i++] = GET_COL_NAME;
1677 break;
1678 case 1:
1679 cb.cb_columns[i++] = GET_COL_PROPERTY;
1680 break;
1681 case 2:
1682 cb.cb_columns[i++] = GET_COL_VALUE;
1683 break;
1684 case 3:
1685 cb.cb_columns[i++] = GET_COL_RECVD;
1686 flags |= ZFS_ITER_RECVD_PROPS;
1687 break;
1688 case 4:
1689 cb.cb_columns[i++] = GET_COL_SOURCE;
1690 break;
1691 case 5:
1692 if (i > 0) {
1693 (void) fprintf(stderr,
1694 gettext("\"all\" conflicts "
1695 "with specific fields "
1696 "given to -o option\n"));
1697 usage(B_FALSE);
1699 cb.cb_columns[0] = GET_COL_NAME;
1700 cb.cb_columns[1] = GET_COL_PROPERTY;
1701 cb.cb_columns[2] = GET_COL_VALUE;
1702 cb.cb_columns[3] = GET_COL_RECVD;
1703 cb.cb_columns[4] = GET_COL_SOURCE;
1704 flags |= ZFS_ITER_RECVD_PROPS;
1705 i = ZFS_GET_NCOLS;
1706 break;
1707 default:
1708 (void) fprintf(stderr,
1709 gettext("invalid column name "
1710 "'%s'\n"), value);
1711 usage(B_FALSE);
1714 break;
1716 case 's':
1717 cb.cb_sources = 0;
1718 while (*optarg != '\0') {
1719 static char *source_subopts[] = {
1720 "local", "default", "inherited",
1721 "received", "temporary", "none",
1722 NULL };
1724 switch (getsubopt(&optarg, source_subopts,
1725 &value)) {
1726 case 0:
1727 cb.cb_sources |= ZPROP_SRC_LOCAL;
1728 break;
1729 case 1:
1730 cb.cb_sources |= ZPROP_SRC_DEFAULT;
1731 break;
1732 case 2:
1733 cb.cb_sources |= ZPROP_SRC_INHERITED;
1734 break;
1735 case 3:
1736 cb.cb_sources |= ZPROP_SRC_RECEIVED;
1737 break;
1738 case 4:
1739 cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1740 break;
1741 case 5:
1742 cb.cb_sources |= ZPROP_SRC_NONE;
1743 break;
1744 default:
1745 (void) fprintf(stderr,
1746 gettext("invalid source "
1747 "'%s'\n"), value);
1748 usage(B_FALSE);
1751 break;
1753 case 't':
1754 types = 0;
1755 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
1756 while (*optarg != '\0') {
1757 static char *type_subopts[] = { "filesystem",
1758 "volume", "snapshot", "bookmark",
1759 "all", NULL };
1761 switch (getsubopt(&optarg, type_subopts,
1762 &value)) {
1763 case 0:
1764 types |= ZFS_TYPE_FILESYSTEM;
1765 break;
1766 case 1:
1767 types |= ZFS_TYPE_VOLUME;
1768 break;
1769 case 2:
1770 types |= ZFS_TYPE_SNAPSHOT;
1771 break;
1772 case 3:
1773 types |= ZFS_TYPE_BOOKMARK;
1774 break;
1775 case 4:
1776 types = ZFS_TYPE_DATASET |
1777 ZFS_TYPE_BOOKMARK;
1778 break;
1780 default:
1781 (void) fprintf(stderr,
1782 gettext("invalid type '%s'\n"),
1783 value);
1784 usage(B_FALSE);
1787 break;
1789 case '?':
1790 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1791 optopt);
1792 usage(B_FALSE);
1796 argc -= optind;
1797 argv += optind;
1799 if (argc < 1) {
1800 (void) fprintf(stderr, gettext("missing property "
1801 "argument\n"));
1802 usage(B_FALSE);
1805 fields = argv[0];
1807 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1808 != 0)
1809 usage(B_FALSE);
1811 argc--;
1812 argv++;
1815 * As part of zfs_expand_proplist(), we keep track of the maximum column
1816 * width for each property. For the 'NAME' (and 'SOURCE') columns, we
1817 * need to know the maximum name length. However, the user likely did
1818 * not specify 'name' as one of the properties to fetch, so we need to
1819 * make sure we always include at least this property for
1820 * print_get_headers() to work properly.
1822 if (cb.cb_proplist != NULL) {
1823 fake_name.pl_prop = ZFS_PROP_NAME;
1824 fake_name.pl_width = strlen(gettext("NAME"));
1825 fake_name.pl_next = cb.cb_proplist;
1826 cb.cb_proplist = &fake_name;
1829 cb.cb_first = B_TRUE;
1831 /* run for each object */
1832 ret = zfs_for_each(argc, argv, flags, types, NULL,
1833 &cb.cb_proplist, limit, get_callback, &cb);
1835 if (cb.cb_proplist == &fake_name)
1836 zprop_free_list(fake_name.pl_next);
1837 else
1838 zprop_free_list(cb.cb_proplist);
1840 return (ret);
1844 * inherit [-rS] <property> <fs|vol> ...
1846 * -r Recurse over all children
1847 * -S Revert to received value, if any
1849 * For each dataset specified on the command line, inherit the given property
1850 * from its parent. Inheriting a property at the pool level will cause it to
1851 * use the default value. The '-r' flag will recurse over all children, and is
1852 * useful for setting a property on a hierarchy-wide basis, regardless of any
1853 * local modifications for each dataset.
1856 typedef struct inherit_cbdata {
1857 const char *cb_propname;
1858 boolean_t cb_received;
1859 } inherit_cbdata_t;
1861 static int
1862 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
1864 inherit_cbdata_t *cb = data;
1865 zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
1868 * If we're doing it recursively, then ignore properties that
1869 * are not valid for this type of dataset.
1871 if (prop != ZPROP_INVAL &&
1872 !zfs_prop_valid_for_type(prop, zfs_get_type(zhp)))
1873 return (0);
1875 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1878 static int
1879 inherit_cb(zfs_handle_t *zhp, void *data)
1881 inherit_cbdata_t *cb = data;
1883 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1886 static int
1887 zfs_do_inherit(int argc, char **argv)
1889 int c;
1890 zfs_prop_t prop;
1891 inherit_cbdata_t cb = { 0 };
1892 char *propname;
1893 int ret = 0;
1894 int flags = 0;
1895 boolean_t received = B_FALSE;
1897 /* check options */
1898 while ((c = getopt(argc, argv, "rS")) != -1) {
1899 switch (c) {
1900 case 'r':
1901 flags |= ZFS_ITER_RECURSE;
1902 break;
1903 case 'S':
1904 received = B_TRUE;
1905 break;
1906 case '?':
1907 default:
1908 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1909 optopt);
1910 usage(B_FALSE);
1914 argc -= optind;
1915 argv += optind;
1917 /* check number of arguments */
1918 if (argc < 1) {
1919 (void) fprintf(stderr, gettext("missing property argument\n"));
1920 usage(B_FALSE);
1922 if (argc < 2) {
1923 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1924 usage(B_FALSE);
1927 propname = argv[0];
1928 argc--;
1929 argv++;
1931 if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1932 if (zfs_prop_readonly(prop)) {
1933 (void) fprintf(stderr, gettext(
1934 "%s property is read-only\n"),
1935 propname);
1936 return (1);
1938 if (!zfs_prop_inheritable(prop) && !received) {
1939 (void) fprintf(stderr, gettext("'%s' property cannot "
1940 "be inherited\n"), propname);
1941 if (prop == ZFS_PROP_QUOTA ||
1942 prop == ZFS_PROP_RESERVATION ||
1943 prop == ZFS_PROP_REFQUOTA ||
1944 prop == ZFS_PROP_REFRESERVATION) {
1945 (void) fprintf(stderr, gettext("use 'zfs set "
1946 "%s=none' to clear\n"), propname);
1947 (void) fprintf(stderr, gettext("use 'zfs "
1948 "inherit -S %s' to revert to received "
1949 "value\n"), propname);
1951 return (1);
1953 if (received && (prop == ZFS_PROP_VOLSIZE ||
1954 prop == ZFS_PROP_VERSION)) {
1955 (void) fprintf(stderr, gettext("'%s' property cannot "
1956 "be reverted to a received value\n"), propname);
1957 return (1);
1959 } else if (!zfs_prop_user(propname)) {
1960 (void) fprintf(stderr, gettext("invalid property '%s'\n"),
1961 propname);
1962 usage(B_FALSE);
1965 cb.cb_propname = propname;
1966 cb.cb_received = received;
1968 if (flags & ZFS_ITER_RECURSE) {
1969 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1970 NULL, NULL, 0, inherit_recurse_cb, &cb);
1971 } else {
1972 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1973 NULL, NULL, 0, inherit_cb, &cb);
1976 return (ret);
1979 typedef struct upgrade_cbdata {
1980 uint64_t cb_numupgraded;
1981 uint64_t cb_numsamegraded;
1982 uint64_t cb_numfailed;
1983 uint64_t cb_version;
1984 boolean_t cb_newer;
1985 boolean_t cb_foundone;
1986 char cb_lastfs[ZFS_MAX_DATASET_NAME_LEN];
1987 } upgrade_cbdata_t;
1989 static int
1990 same_pool(zfs_handle_t *zhp, const char *name)
1992 int len1 = strcspn(name, "/@");
1993 const char *zhname = zfs_get_name(zhp);
1994 int len2 = strcspn(zhname, "/@");
1996 if (len1 != len2)
1997 return (B_FALSE);
1998 return (strncmp(name, zhname, len1) == 0);
2001 static int
2002 upgrade_list_callback(zfs_handle_t *zhp, void *data)
2004 upgrade_cbdata_t *cb = data;
2005 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2007 /* list if it's old/new */
2008 if ((!cb->cb_newer && version < ZPL_VERSION) ||
2009 (cb->cb_newer && version > ZPL_VERSION)) {
2010 char *str;
2011 if (cb->cb_newer) {
2012 str = gettext("The following filesystems are "
2013 "formatted using a newer software version and\n"
2014 "cannot be accessed on the current system.\n\n");
2015 } else {
2016 str = gettext("The following filesystems are "
2017 "out of date, and can be upgraded. After being\n"
2018 "upgraded, these filesystems (and any 'zfs send' "
2019 "streams generated from\n"
2020 "subsequent snapshots) will no longer be "
2021 "accessible by older software versions.\n\n");
2024 if (!cb->cb_foundone) {
2025 (void) puts(str);
2026 (void) printf(gettext("VER FILESYSTEM\n"));
2027 (void) printf(gettext("--- ------------\n"));
2028 cb->cb_foundone = B_TRUE;
2031 (void) printf("%2u %s\n", version, zfs_get_name(zhp));
2034 return (0);
2037 static int
2038 upgrade_set_callback(zfs_handle_t *zhp, void *data)
2040 upgrade_cbdata_t *cb = data;
2041 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2042 int needed_spa_version;
2043 int spa_version;
2045 if (zfs_spa_version(zhp, &spa_version) < 0)
2046 return (-1);
2048 needed_spa_version = zfs_spa_version_map(cb->cb_version);
2050 if (needed_spa_version < 0)
2051 return (-1);
2053 if (spa_version < needed_spa_version) {
2054 /* can't upgrade */
2055 (void) printf(gettext("%s: can not be "
2056 "upgraded; the pool version needs to first "
2057 "be upgraded\nto version %d\n\n"),
2058 zfs_get_name(zhp), needed_spa_version);
2059 cb->cb_numfailed++;
2060 return (0);
2063 /* upgrade */
2064 if (version < cb->cb_version) {
2065 char verstr[16];
2066 (void) snprintf(verstr, sizeof (verstr),
2067 "%llu", cb->cb_version);
2068 if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
2070 * If they did "zfs upgrade -a", then we could
2071 * be doing ioctls to different pools. We need
2072 * to log this history once to each pool, and bypass
2073 * the normal history logging that happens in main().
2075 (void) zpool_log_history(g_zfs, history_str);
2076 log_history = B_FALSE;
2078 if (zfs_prop_set(zhp, "version", verstr) == 0)
2079 cb->cb_numupgraded++;
2080 else
2081 cb->cb_numfailed++;
2082 (void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
2083 } else if (version > cb->cb_version) {
2084 /* can't downgrade */
2085 (void) printf(gettext("%s: can not be downgraded; "
2086 "it is already at version %u\n"),
2087 zfs_get_name(zhp), version);
2088 cb->cb_numfailed++;
2089 } else {
2090 cb->cb_numsamegraded++;
2092 return (0);
2096 * zfs upgrade
2097 * zfs upgrade -v
2098 * zfs upgrade [-r] [-V <version>] <-a | filesystem>
2100 static int
2101 zfs_do_upgrade(int argc, char **argv)
2103 boolean_t all = B_FALSE;
2104 boolean_t showversions = B_FALSE;
2105 int ret = 0;
2106 upgrade_cbdata_t cb = { 0 };
2107 char c;
2108 int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2110 /* check options */
2111 while ((c = getopt(argc, argv, "rvV:a")) != -1) {
2112 switch (c) {
2113 case 'r':
2114 flags |= ZFS_ITER_RECURSE;
2115 break;
2116 case 'v':
2117 showversions = B_TRUE;
2118 break;
2119 case 'V':
2120 if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
2121 optarg, &cb.cb_version) != 0) {
2122 (void) fprintf(stderr,
2123 gettext("invalid version %s\n"), optarg);
2124 usage(B_FALSE);
2126 break;
2127 case 'a':
2128 all = B_TRUE;
2129 break;
2130 case '?':
2131 default:
2132 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2133 optopt);
2134 usage(B_FALSE);
2138 argc -= optind;
2139 argv += optind;
2141 if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
2142 usage(B_FALSE);
2143 if (showversions && (flags & ZFS_ITER_RECURSE || all ||
2144 cb.cb_version || argc))
2145 usage(B_FALSE);
2146 if ((all || argc) && (showversions))
2147 usage(B_FALSE);
2148 if (all && argc)
2149 usage(B_FALSE);
2151 if (showversions) {
2152 /* Show info on available versions. */
2153 (void) printf(gettext("The following filesystem versions are "
2154 "supported:\n\n"));
2155 (void) printf(gettext("VER DESCRIPTION\n"));
2156 (void) printf("--- -----------------------------------------"
2157 "---------------\n");
2158 (void) printf(gettext(" 1 Initial ZFS filesystem version\n"));
2159 (void) printf(gettext(" 2 Enhanced directory entries\n"));
2160 (void) printf(gettext(" 3 Case insensitive and filesystem "
2161 "user identifier (FUID)\n"));
2162 (void) printf(gettext(" 4 userquota, groupquota "
2163 "properties\n"));
2164 (void) printf(gettext(" 5 System attributes\n"));
2165 (void) printf(gettext("\nFor more information on a particular "
2166 "version, including supported releases,\n"));
2167 (void) printf("see the ZFS Administration Guide.\n\n");
2168 ret = 0;
2169 } else if (argc || all) {
2170 /* Upgrade filesystems */
2171 if (cb.cb_version == 0)
2172 cb.cb_version = ZPL_VERSION;
2173 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
2174 NULL, NULL, 0, upgrade_set_callback, &cb);
2175 (void) printf(gettext("%llu filesystems upgraded\n"),
2176 cb.cb_numupgraded);
2177 if (cb.cb_numsamegraded) {
2178 (void) printf(gettext("%llu filesystems already at "
2179 "this version\n"),
2180 cb.cb_numsamegraded);
2182 if (cb.cb_numfailed != 0)
2183 ret = 1;
2184 } else {
2185 /* List old-version filesytems */
2186 boolean_t found;
2187 (void) printf(gettext("This system is currently running "
2188 "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
2190 flags |= ZFS_ITER_RECURSE;
2191 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2192 NULL, NULL, 0, upgrade_list_callback, &cb);
2194 found = cb.cb_foundone;
2195 cb.cb_foundone = B_FALSE;
2196 cb.cb_newer = B_TRUE;
2198 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2199 NULL, NULL, 0, upgrade_list_callback, &cb);
2201 if (!cb.cb_foundone && !found) {
2202 (void) printf(gettext("All filesystems are "
2203 "formatted with the current version.\n"));
2207 return (ret);
2211 * zfs userspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2212 * [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2213 * zfs groupspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2214 * [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2216 * -H Scripted mode; elide headers and separate columns by tabs.
2217 * -i Translate SID to POSIX ID.
2218 * -n Print numeric ID instead of user/group name.
2219 * -o Control which fields to display.
2220 * -p Use exact (parsable) numeric output.
2221 * -s Specify sort columns, descending order.
2222 * -S Specify sort columns, ascending order.
2223 * -t Control which object types to display.
2225 * Displays space consumed by, and quotas on, each user in the specified
2226 * filesystem or snapshot.
2229 /* us_field_types, us_field_hdr and us_field_names should be kept in sync */
2230 enum us_field_types {
2231 USFIELD_TYPE,
2232 USFIELD_NAME,
2233 USFIELD_USED,
2234 USFIELD_QUOTA
2236 static char *us_field_hdr[] = { "TYPE", "NAME", "USED", "QUOTA" };
2237 static char *us_field_names[] = { "type", "name", "used", "quota" };
2238 #define USFIELD_LAST (sizeof (us_field_names) / sizeof (char *))
2240 #define USTYPE_PSX_GRP (1 << 0)
2241 #define USTYPE_PSX_USR (1 << 1)
2242 #define USTYPE_SMB_GRP (1 << 2)
2243 #define USTYPE_SMB_USR (1 << 3)
2244 #define USTYPE_ALL \
2245 (USTYPE_PSX_GRP | USTYPE_PSX_USR | USTYPE_SMB_GRP | USTYPE_SMB_USR)
2247 static int us_type_bits[] = {
2248 USTYPE_PSX_GRP,
2249 USTYPE_PSX_USR,
2250 USTYPE_SMB_GRP,
2251 USTYPE_SMB_USR,
2252 USTYPE_ALL
2254 static char *us_type_names[] = { "posixgroup", "posixuser", "smbgroup",
2255 "smbuser", "all" };
2257 typedef struct us_node {
2258 nvlist_t *usn_nvl;
2259 uu_avl_node_t usn_avlnode;
2260 uu_list_node_t usn_listnode;
2261 } us_node_t;
2263 typedef struct us_cbdata {
2264 nvlist_t **cb_nvlp;
2265 uu_avl_pool_t *cb_avl_pool;
2266 uu_avl_t *cb_avl;
2267 boolean_t cb_numname;
2268 boolean_t cb_nicenum;
2269 boolean_t cb_sid2posix;
2270 zfs_userquota_prop_t cb_prop;
2271 zfs_sort_column_t *cb_sortcol;
2272 size_t cb_width[USFIELD_LAST];
2273 } us_cbdata_t;
2275 static boolean_t us_populated = B_FALSE;
2277 typedef struct {
2278 zfs_sort_column_t *si_sortcol;
2279 boolean_t si_numname;
2280 } us_sort_info_t;
2282 static int
2283 us_field_index(char *field)
2285 int i;
2287 for (i = 0; i < USFIELD_LAST; i++) {
2288 if (strcmp(field, us_field_names[i]) == 0)
2289 return (i);
2292 return (-1);
2295 static int
2296 us_compare(const void *larg, const void *rarg, void *unused)
2298 const us_node_t *l = larg;
2299 const us_node_t *r = rarg;
2300 us_sort_info_t *si = (us_sort_info_t *)unused;
2301 zfs_sort_column_t *sortcol = si->si_sortcol;
2302 boolean_t numname = si->si_numname;
2303 nvlist_t *lnvl = l->usn_nvl;
2304 nvlist_t *rnvl = r->usn_nvl;
2305 int rc = 0;
2306 boolean_t lvb, rvb;
2308 for (; sortcol != NULL; sortcol = sortcol->sc_next) {
2309 char *lvstr = "";
2310 char *rvstr = "";
2311 uint32_t lv32 = 0;
2312 uint32_t rv32 = 0;
2313 uint64_t lv64 = 0;
2314 uint64_t rv64 = 0;
2315 zfs_prop_t prop = sortcol->sc_prop;
2316 const char *propname = NULL;
2317 boolean_t reverse = sortcol->sc_reverse;
2319 switch (prop) {
2320 case ZFS_PROP_TYPE:
2321 propname = "type";
2322 (void) nvlist_lookup_uint32(lnvl, propname, &lv32);
2323 (void) nvlist_lookup_uint32(rnvl, propname, &rv32);
2324 if (rv32 != lv32)
2325 rc = (rv32 < lv32) ? 1 : -1;
2326 break;
2327 case ZFS_PROP_NAME:
2328 propname = "name";
2329 if (numname) {
2330 (void) nvlist_lookup_uint64(lnvl, propname,
2331 &lv64);
2332 (void) nvlist_lookup_uint64(rnvl, propname,
2333 &rv64);
2334 if (rv64 != lv64)
2335 rc = (rv64 < lv64) ? 1 : -1;
2336 } else {
2337 (void) nvlist_lookup_string(lnvl, propname,
2338 &lvstr);
2339 (void) nvlist_lookup_string(rnvl, propname,
2340 &rvstr);
2341 rc = strcmp(lvstr, rvstr);
2343 break;
2344 case ZFS_PROP_USED:
2345 case ZFS_PROP_QUOTA:
2346 if (!us_populated)
2347 break;
2348 if (prop == ZFS_PROP_USED)
2349 propname = "used";
2350 else
2351 propname = "quota";
2352 (void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2353 (void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2354 if (rv64 != lv64)
2355 rc = (rv64 < lv64) ? 1 : -1;
2356 break;
2358 default:
2359 break;
2362 if (rc != 0) {
2363 if (rc < 0)
2364 return (reverse ? 1 : -1);
2365 else
2366 return (reverse ? -1 : 1);
2371 * If entries still seem to be the same, check if they are of the same
2372 * type (smbentity is added only if we are doing SID to POSIX ID
2373 * translation where we can have duplicate type/name combinations).
2375 if (nvlist_lookup_boolean_value(lnvl, "smbentity", &lvb) == 0 &&
2376 nvlist_lookup_boolean_value(rnvl, "smbentity", &rvb) == 0 &&
2377 lvb != rvb)
2378 return (lvb < rvb ? -1 : 1);
2380 return (0);
2383 static inline const char *
2384 us_type2str(unsigned field_type)
2386 switch (field_type) {
2387 case USTYPE_PSX_USR:
2388 return ("POSIX User");
2389 case USTYPE_PSX_GRP:
2390 return ("POSIX Group");
2391 case USTYPE_SMB_USR:
2392 return ("SMB User");
2393 case USTYPE_SMB_GRP:
2394 return ("SMB Group");
2395 default:
2396 return ("Undefined");
2400 static int
2401 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2403 us_cbdata_t *cb = (us_cbdata_t *)arg;
2404 zfs_userquota_prop_t prop = cb->cb_prop;
2405 char *name = NULL;
2406 char *propname;
2407 char sizebuf[32];
2408 us_node_t *node;
2409 uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2410 uu_avl_t *avl = cb->cb_avl;
2411 uu_avl_index_t idx;
2412 nvlist_t *props;
2413 us_node_t *n;
2414 zfs_sort_column_t *sortcol = cb->cb_sortcol;
2415 unsigned type = 0;
2416 const char *typestr;
2417 size_t namelen;
2418 size_t typelen;
2419 size_t sizelen;
2420 int typeidx, nameidx, sizeidx;
2421 us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
2422 boolean_t smbentity = B_FALSE;
2424 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
2425 nomem();
2426 node = safe_malloc(sizeof (us_node_t));
2427 uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
2428 node->usn_nvl = props;
2430 if (domain != NULL && domain[0] != '\0') {
2431 /* SMB */
2432 char sid[MAXNAMELEN + 32];
2433 uid_t id;
2434 int err;
2435 int flag = IDMAP_REQ_FLG_USE_CACHE;
2437 smbentity = B_TRUE;
2439 (void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
2441 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2442 type = USTYPE_SMB_GRP;
2443 err = sid_to_id(sid, B_FALSE, &id);
2444 } else {
2445 type = USTYPE_SMB_USR;
2446 err = sid_to_id(sid, B_TRUE, &id);
2449 if (err == 0) {
2450 rid = id;
2451 if (!cb->cb_sid2posix) {
2452 if (type == USTYPE_SMB_USR) {
2453 (void) idmap_getwinnamebyuid(rid, flag,
2454 &name, NULL);
2455 } else {
2456 (void) idmap_getwinnamebygid(rid, flag,
2457 &name, NULL);
2459 if (name == NULL)
2460 name = sid;
2465 if (cb->cb_sid2posix || domain == NULL || domain[0] == '\0') {
2466 /* POSIX or -i */
2467 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2468 type = USTYPE_PSX_GRP;
2469 if (!cb->cb_numname) {
2470 struct group *g;
2472 if ((g = getgrgid(rid)) != NULL)
2473 name = g->gr_name;
2475 } else {
2476 type = USTYPE_PSX_USR;
2477 if (!cb->cb_numname) {
2478 struct passwd *p;
2480 if ((p = getpwuid(rid)) != NULL)
2481 name = p->pw_name;
2487 * Make sure that the type/name combination is unique when doing
2488 * SID to POSIX ID translation (hence changing the type from SMB to
2489 * POSIX).
2491 if (cb->cb_sid2posix &&
2492 nvlist_add_boolean_value(props, "smbentity", smbentity) != 0)
2493 nomem();
2495 /* Calculate/update width of TYPE field */
2496 typestr = us_type2str(type);
2497 typelen = strlen(gettext(typestr));
2498 typeidx = us_field_index("type");
2499 if (typelen > cb->cb_width[typeidx])
2500 cb->cb_width[typeidx] = typelen;
2501 if (nvlist_add_uint32(props, "type", type) != 0)
2502 nomem();
2504 /* Calculate/update width of NAME field */
2505 if ((cb->cb_numname && cb->cb_sid2posix) || name == NULL) {
2506 if (nvlist_add_uint64(props, "name", rid) != 0)
2507 nomem();
2508 namelen = snprintf(NULL, 0, "%u", rid);
2509 } else {
2510 if (nvlist_add_string(props, "name", name) != 0)
2511 nomem();
2512 namelen = strlen(name);
2514 nameidx = us_field_index("name");
2515 if (namelen > cb->cb_width[nameidx])
2516 cb->cb_width[nameidx] = namelen;
2519 * Check if this type/name combination is in the list and update it;
2520 * otherwise add new node to the list.
2522 if ((n = uu_avl_find(avl, node, &sortinfo, &idx)) == NULL) {
2523 uu_avl_insert(avl, node, idx);
2524 } else {
2525 nvlist_free(props);
2526 free(node);
2527 node = n;
2528 props = node->usn_nvl;
2531 /* Calculate/update width of USED/QUOTA fields */
2532 if (cb->cb_nicenum)
2533 zfs_nicenum(space, sizebuf, sizeof (sizebuf));
2534 else
2535 (void) snprintf(sizebuf, sizeof (sizebuf), "%llu", space);
2536 sizelen = strlen(sizebuf);
2537 if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED) {
2538 propname = "used";
2539 if (!nvlist_exists(props, "quota"))
2540 (void) nvlist_add_uint64(props, "quota", 0);
2541 } else {
2542 propname = "quota";
2543 if (!nvlist_exists(props, "used"))
2544 (void) nvlist_add_uint64(props, "used", 0);
2546 sizeidx = us_field_index(propname);
2547 if (sizelen > cb->cb_width[sizeidx])
2548 cb->cb_width[sizeidx] = sizelen;
2550 if (nvlist_add_uint64(props, propname, space) != 0)
2551 nomem();
2553 return (0);
2556 static void
2557 print_us_node(boolean_t scripted, boolean_t parsable, int *fields, int types,
2558 size_t *width, us_node_t *node)
2560 nvlist_t *nvl = node->usn_nvl;
2561 char valstr[MAXNAMELEN];
2562 boolean_t first = B_TRUE;
2563 int cfield = 0;
2564 int field;
2565 uint32_t ustype;
2567 /* Check type */
2568 (void) nvlist_lookup_uint32(nvl, "type", &ustype);
2569 if (!(ustype & types))
2570 return;
2572 while ((field = fields[cfield]) != USFIELD_LAST) {
2573 nvpair_t *nvp = NULL;
2574 data_type_t type;
2575 uint32_t val32;
2576 uint64_t val64;
2577 char *strval = NULL;
2579 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
2580 if (strcmp(nvpair_name(nvp),
2581 us_field_names[field]) == 0)
2582 break;
2585 type = nvpair_type(nvp);
2586 switch (type) {
2587 case DATA_TYPE_UINT32:
2588 (void) nvpair_value_uint32(nvp, &val32);
2589 break;
2590 case DATA_TYPE_UINT64:
2591 (void) nvpair_value_uint64(nvp, &val64);
2592 break;
2593 case DATA_TYPE_STRING:
2594 (void) nvpair_value_string(nvp, &strval);
2595 break;
2596 default:
2597 (void) fprintf(stderr, "invalid data type\n");
2600 switch (field) {
2601 case USFIELD_TYPE:
2602 strval = (char *)us_type2str(val32);
2603 break;
2604 case USFIELD_NAME:
2605 if (type == DATA_TYPE_UINT64) {
2606 (void) sprintf(valstr, "%llu", val64);
2607 strval = valstr;
2609 break;
2610 case USFIELD_USED:
2611 case USFIELD_QUOTA:
2612 if (type == DATA_TYPE_UINT64) {
2613 if (parsable) {
2614 (void) sprintf(valstr, "%llu", val64);
2615 } else {
2616 zfs_nicenum(val64, valstr,
2617 sizeof (valstr));
2619 if (field == USFIELD_QUOTA &&
2620 strcmp(valstr, "0") == 0)
2621 strval = "none";
2622 else
2623 strval = valstr;
2625 break;
2628 if (!first) {
2629 if (scripted)
2630 (void) printf("\t");
2631 else
2632 (void) printf(" ");
2634 if (scripted)
2635 (void) printf("%s", strval);
2636 else if (field == USFIELD_TYPE || field == USFIELD_NAME)
2637 (void) printf("%-*s", width[field], strval);
2638 else
2639 (void) printf("%*s", width[field], strval);
2641 first = B_FALSE;
2642 cfield++;
2645 (void) printf("\n");
2648 static void
2649 print_us(boolean_t scripted, boolean_t parsable, int *fields, int types,
2650 size_t *width, boolean_t rmnode, uu_avl_t *avl)
2652 us_node_t *node;
2653 const char *col;
2654 int cfield = 0;
2655 int field;
2657 if (!scripted) {
2658 boolean_t first = B_TRUE;
2660 while ((field = fields[cfield]) != USFIELD_LAST) {
2661 col = gettext(us_field_hdr[field]);
2662 if (field == USFIELD_TYPE || field == USFIELD_NAME) {
2663 (void) printf(first ? "%-*s" : " %-*s",
2664 width[field], col);
2665 } else {
2666 (void) printf(first ? "%*s" : " %*s",
2667 width[field], col);
2669 first = B_FALSE;
2670 cfield++;
2672 (void) printf("\n");
2675 for (node = uu_avl_first(avl); node; node = uu_avl_next(avl, node)) {
2676 print_us_node(scripted, parsable, fields, types, width, node);
2677 if (rmnode)
2678 nvlist_free(node->usn_nvl);
2682 static int
2683 zfs_do_userspace(int argc, char **argv)
2685 zfs_handle_t *zhp;
2686 zfs_userquota_prop_t p;
2687 uu_avl_pool_t *avl_pool;
2688 uu_avl_t *avl_tree;
2689 uu_avl_walk_t *walk;
2690 char *delim;
2691 char deffields[] = "type,name,used,quota";
2692 char *ofield = NULL;
2693 char *tfield = NULL;
2694 int cfield = 0;
2695 int fields[256];
2696 int i;
2697 boolean_t scripted = B_FALSE;
2698 boolean_t prtnum = B_FALSE;
2699 boolean_t parsable = B_FALSE;
2700 boolean_t sid2posix = B_FALSE;
2701 int ret = 0;
2702 int c;
2703 zfs_sort_column_t *sortcol = NULL;
2704 int types = USTYPE_PSX_USR | USTYPE_SMB_USR;
2705 us_cbdata_t cb;
2706 us_node_t *node;
2707 us_node_t *rmnode;
2708 uu_list_pool_t *listpool;
2709 uu_list_t *list;
2710 uu_avl_index_t idx = 0;
2711 uu_list_index_t idx2 = 0;
2713 if (argc < 2)
2714 usage(B_FALSE);
2716 if (strcmp(argv[0], "groupspace") == 0)
2717 /* Toggle default group types */
2718 types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
2720 while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
2721 switch (c) {
2722 case 'n':
2723 prtnum = B_TRUE;
2724 break;
2725 case 'H':
2726 scripted = B_TRUE;
2727 break;
2728 case 'p':
2729 parsable = B_TRUE;
2730 break;
2731 case 'o':
2732 ofield = optarg;
2733 break;
2734 case 's':
2735 case 'S':
2736 if (zfs_add_sort_column(&sortcol, optarg,
2737 c == 's' ? B_FALSE : B_TRUE) != 0) {
2738 (void) fprintf(stderr,
2739 gettext("invalid field '%s'\n"), optarg);
2740 usage(B_FALSE);
2742 break;
2743 case 't':
2744 tfield = optarg;
2745 break;
2746 case 'i':
2747 sid2posix = B_TRUE;
2748 break;
2749 case ':':
2750 (void) fprintf(stderr, gettext("missing argument for "
2751 "'%c' option\n"), optopt);
2752 usage(B_FALSE);
2753 break;
2754 case '?':
2755 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2756 optopt);
2757 usage(B_FALSE);
2761 argc -= optind;
2762 argv += optind;
2764 if (argc < 1) {
2765 (void) fprintf(stderr, gettext("missing dataset name\n"));
2766 usage(B_FALSE);
2768 if (argc > 1) {
2769 (void) fprintf(stderr, gettext("too many arguments\n"));
2770 usage(B_FALSE);
2773 /* Use default output fields if not specified using -o */
2774 if (ofield == NULL)
2775 ofield = deffields;
2776 do {
2777 if ((delim = strchr(ofield, ',')) != NULL)
2778 *delim = '\0';
2779 if ((fields[cfield++] = us_field_index(ofield)) == -1) {
2780 (void) fprintf(stderr, gettext("invalid type '%s' "
2781 "for -o option\n"), ofield);
2782 return (-1);
2784 if (delim != NULL)
2785 ofield = delim + 1;
2786 } while (delim != NULL);
2787 fields[cfield] = USFIELD_LAST;
2789 /* Override output types (-t option) */
2790 if (tfield != NULL) {
2791 types = 0;
2793 do {
2794 boolean_t found = B_FALSE;
2796 if ((delim = strchr(tfield, ',')) != NULL)
2797 *delim = '\0';
2798 for (i = 0; i < sizeof (us_type_bits) / sizeof (int);
2799 i++) {
2800 if (strcmp(tfield, us_type_names[i]) == 0) {
2801 found = B_TRUE;
2802 types |= us_type_bits[i];
2803 break;
2806 if (!found) {
2807 (void) fprintf(stderr, gettext("invalid type "
2808 "'%s' for -t option\n"), tfield);
2809 return (-1);
2811 if (delim != NULL)
2812 tfield = delim + 1;
2813 } while (delim != NULL);
2816 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
2817 return (1);
2819 if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
2820 offsetof(us_node_t, usn_avlnode), us_compare, UU_DEFAULT)) == NULL)
2821 nomem();
2822 if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
2823 nomem();
2825 /* Always add default sorting columns */
2826 (void) zfs_add_sort_column(&sortcol, "type", B_FALSE);
2827 (void) zfs_add_sort_column(&sortcol, "name", B_FALSE);
2829 cb.cb_sortcol = sortcol;
2830 cb.cb_numname = prtnum;
2831 cb.cb_nicenum = !parsable;
2832 cb.cb_avl_pool = avl_pool;
2833 cb.cb_avl = avl_tree;
2834 cb.cb_sid2posix = sid2posix;
2836 for (i = 0; i < USFIELD_LAST; i++)
2837 cb.cb_width[i] = strlen(gettext(us_field_hdr[i]));
2839 for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
2840 if (((p == ZFS_PROP_USERUSED || p == ZFS_PROP_USERQUOTA) &&
2841 !(types & (USTYPE_PSX_USR | USTYPE_SMB_USR))) ||
2842 ((p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA) &&
2843 !(types & (USTYPE_PSX_GRP | USTYPE_SMB_GRP))))
2844 continue;
2845 cb.cb_prop = p;
2846 if ((ret = zfs_userspace(zhp, p, userspace_cb, &cb)) != 0)
2847 return (ret);
2850 /* Sort the list */
2851 if ((node = uu_avl_first(avl_tree)) == NULL)
2852 return (0);
2854 us_populated = B_TRUE;
2856 listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
2857 offsetof(us_node_t, usn_listnode), NULL, UU_DEFAULT);
2858 list = uu_list_create(listpool, NULL, UU_DEFAULT);
2859 uu_list_node_init(node, &node->usn_listnode, listpool);
2861 while (node != NULL) {
2862 rmnode = node;
2863 node = uu_avl_next(avl_tree, node);
2864 uu_avl_remove(avl_tree, rmnode);
2865 if (uu_list_find(list, rmnode, NULL, &idx2) == NULL)
2866 uu_list_insert(list, rmnode, idx2);
2869 for (node = uu_list_first(list); node != NULL;
2870 node = uu_list_next(list, node)) {
2871 us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
2873 if (uu_avl_find(avl_tree, node, &sortinfo, &idx) == NULL)
2874 uu_avl_insert(avl_tree, node, idx);
2877 uu_list_destroy(list);
2878 uu_list_pool_destroy(listpool);
2880 /* Print and free node nvlist memory */
2881 print_us(scripted, parsable, fields, types, cb.cb_width, B_TRUE,
2882 cb.cb_avl);
2884 zfs_free_sort_columns(sortcol);
2886 /* Clean up the AVL tree */
2887 if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
2888 nomem();
2890 while ((node = uu_avl_walk_next(walk)) != NULL) {
2891 uu_avl_remove(cb.cb_avl, node);
2892 free(node);
2895 uu_avl_walk_end(walk);
2896 uu_avl_destroy(avl_tree);
2897 uu_avl_pool_destroy(avl_pool);
2899 return (ret);
2903 * list [-Hp][-r|-d max] [-o property[,...]] [-s property] ... [-S property] ...
2904 * [-t type[,...]] [filesystem|volume|snapshot] ...
2906 * -H Scripted mode; elide headers and separate columns by tabs.
2907 * -p Display values in parsable (literal) format.
2908 * -r Recurse over all children.
2909 * -d Limit recursion by depth.
2910 * -o Control which fields to display.
2911 * -s Specify sort columns, descending order.
2912 * -S Specify sort columns, ascending order.
2913 * -t Control which object types to display.
2915 * When given no arguments, list all filesystems in the system.
2916 * Otherwise, list the specified datasets, optionally recursing down them if
2917 * '-r' is specified.
2919 typedef struct list_cbdata {
2920 boolean_t cb_first;
2921 boolean_t cb_literal;
2922 boolean_t cb_scripted;
2923 zprop_list_t *cb_proplist;
2924 } list_cbdata_t;
2927 * Given a list of columns to display, output appropriate headers for each one.
2929 static void
2930 print_header(list_cbdata_t *cb)
2932 zprop_list_t *pl = cb->cb_proplist;
2933 char headerbuf[ZFS_MAXPROPLEN];
2934 const char *header;
2935 int i;
2936 boolean_t first = B_TRUE;
2937 boolean_t right_justify;
2939 for (; pl != NULL; pl = pl->pl_next) {
2940 if (!first) {
2941 (void) printf(" ");
2942 } else {
2943 first = B_FALSE;
2946 right_justify = B_FALSE;
2947 if (pl->pl_prop != ZPROP_INVAL) {
2948 header = zfs_prop_column_name(pl->pl_prop);
2949 right_justify = zfs_prop_align_right(pl->pl_prop);
2950 } else {
2951 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
2952 headerbuf[i] = toupper(pl->pl_user_prop[i]);
2953 headerbuf[i] = '\0';
2954 header = headerbuf;
2957 if (pl->pl_next == NULL && !right_justify)
2958 (void) printf("%s", header);
2959 else if (right_justify)
2960 (void) printf("%*s", pl->pl_width, header);
2961 else
2962 (void) printf("%-*s", pl->pl_width, header);
2965 (void) printf("\n");
2969 * Given a dataset and a list of fields, print out all the properties according
2970 * to the described layout.
2972 static void
2973 print_dataset(zfs_handle_t *zhp, list_cbdata_t *cb)
2975 zprop_list_t *pl = cb->cb_proplist;
2976 boolean_t first = B_TRUE;
2977 char property[ZFS_MAXPROPLEN];
2978 nvlist_t *userprops = zfs_get_user_props(zhp);
2979 nvlist_t *propval;
2980 char *propstr;
2981 boolean_t right_justify;
2983 for (; pl != NULL; pl = pl->pl_next) {
2984 if (!first) {
2985 if (cb->cb_scripted)
2986 (void) printf("\t");
2987 else
2988 (void) printf(" ");
2989 } else {
2990 first = B_FALSE;
2993 if (pl->pl_prop == ZFS_PROP_NAME) {
2994 (void) strlcpy(property, zfs_get_name(zhp),
2995 sizeof (property));
2996 propstr = property;
2997 right_justify = zfs_prop_align_right(pl->pl_prop);
2998 } else if (pl->pl_prop != ZPROP_INVAL) {
2999 if (zfs_prop_get(zhp, pl->pl_prop, property,
3000 sizeof (property), NULL, NULL, 0,
3001 cb->cb_literal) != 0)
3002 propstr = "-";
3003 else
3004 propstr = property;
3005 right_justify = zfs_prop_align_right(pl->pl_prop);
3006 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
3007 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
3008 property, sizeof (property), cb->cb_literal) != 0)
3009 propstr = "-";
3010 else
3011 propstr = property;
3012 right_justify = B_TRUE;
3013 } else if (zfs_prop_written(pl->pl_user_prop)) {
3014 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
3015 property, sizeof (property), cb->cb_literal) != 0)
3016 propstr = "-";
3017 else
3018 propstr = property;
3019 right_justify = B_TRUE;
3020 } else {
3021 if (nvlist_lookup_nvlist(userprops,
3022 pl->pl_user_prop, &propval) != 0)
3023 propstr = "-";
3024 else
3025 verify(nvlist_lookup_string(propval,
3026 ZPROP_VALUE, &propstr) == 0);
3027 right_justify = B_FALSE;
3031 * If this is being called in scripted mode, or if this is the
3032 * last column and it is left-justified, don't include a width
3033 * format specifier.
3035 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
3036 (void) printf("%s", propstr);
3037 else if (right_justify)
3038 (void) printf("%*s", pl->pl_width, propstr);
3039 else
3040 (void) printf("%-*s", pl->pl_width, propstr);
3043 (void) printf("\n");
3047 * Generic callback function to list a dataset or snapshot.
3049 static int
3050 list_callback(zfs_handle_t *zhp, void *data)
3052 list_cbdata_t *cbp = data;
3054 if (cbp->cb_first) {
3055 if (!cbp->cb_scripted)
3056 print_header(cbp);
3057 cbp->cb_first = B_FALSE;
3060 print_dataset(zhp, cbp);
3062 return (0);
3065 static int
3066 zfs_do_list(int argc, char **argv)
3068 int c;
3069 static char default_fields[] =
3070 "name,used,available,referenced,mountpoint";
3071 int types = ZFS_TYPE_DATASET;
3072 boolean_t types_specified = B_FALSE;
3073 char *fields = NULL;
3074 list_cbdata_t cb = { 0 };
3075 char *value;
3076 int limit = 0;
3077 int ret = 0;
3078 zfs_sort_column_t *sortcol = NULL;
3079 int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
3081 /* check options */
3082 while ((c = getopt(argc, argv, "HS:d:o:prs:t:")) != -1) {
3083 switch (c) {
3084 case 'o':
3085 fields = optarg;
3086 break;
3087 case 'p':
3088 cb.cb_literal = B_TRUE;
3089 flags |= ZFS_ITER_LITERAL_PROPS;
3090 break;
3091 case 'd':
3092 limit = parse_depth(optarg, &flags);
3093 break;
3094 case 'r':
3095 flags |= ZFS_ITER_RECURSE;
3096 break;
3097 case 'H':
3098 cb.cb_scripted = B_TRUE;
3099 break;
3100 case 's':
3101 if (zfs_add_sort_column(&sortcol, optarg,
3102 B_FALSE) != 0) {
3103 (void) fprintf(stderr,
3104 gettext("invalid property '%s'\n"), optarg);
3105 usage(B_FALSE);
3107 break;
3108 case 'S':
3109 if (zfs_add_sort_column(&sortcol, optarg,
3110 B_TRUE) != 0) {
3111 (void) fprintf(stderr,
3112 gettext("invalid property '%s'\n"), optarg);
3113 usage(B_FALSE);
3115 break;
3116 case 't':
3117 types = 0;
3118 types_specified = B_TRUE;
3119 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
3120 while (*optarg != '\0') {
3121 static char *type_subopts[] = { "filesystem",
3122 "volume", "snapshot", "snap", "bookmark",
3123 "all", NULL };
3125 switch (getsubopt(&optarg, type_subopts,
3126 &value)) {
3127 case 0:
3128 types |= ZFS_TYPE_FILESYSTEM;
3129 break;
3130 case 1:
3131 types |= ZFS_TYPE_VOLUME;
3132 break;
3133 case 2:
3134 case 3:
3135 types |= ZFS_TYPE_SNAPSHOT;
3136 break;
3137 case 4:
3138 types |= ZFS_TYPE_BOOKMARK;
3139 break;
3140 case 5:
3141 types = ZFS_TYPE_DATASET |
3142 ZFS_TYPE_BOOKMARK;
3143 break;
3144 default:
3145 (void) fprintf(stderr,
3146 gettext("invalid type '%s'\n"),
3147 value);
3148 usage(B_FALSE);
3151 break;
3152 case ':':
3153 (void) fprintf(stderr, gettext("missing argument for "
3154 "'%c' option\n"), optopt);
3155 usage(B_FALSE);
3156 break;
3157 case '?':
3158 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3159 optopt);
3160 usage(B_FALSE);
3164 argc -= optind;
3165 argv += optind;
3167 if (fields == NULL)
3168 fields = default_fields;
3171 * If we are only going to list snapshot names and sort by name,
3172 * then we can use faster version.
3174 if (strcmp(fields, "name") == 0 && zfs_sort_only_by_name(sortcol))
3175 flags |= ZFS_ITER_SIMPLE;
3178 * If "-o space" and no types were specified, don't display snapshots.
3180 if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3181 types &= ~ZFS_TYPE_SNAPSHOT;
3184 * If the user specifies '-o all', the zprop_get_list() doesn't
3185 * normally include the name of the dataset. For 'zfs list', we always
3186 * want this property to be first.
3188 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3189 != 0)
3190 usage(B_FALSE);
3192 cb.cb_first = B_TRUE;
3194 ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
3195 limit, list_callback, &cb);
3197 zprop_free_list(cb.cb_proplist);
3198 zfs_free_sort_columns(sortcol);
3200 if (ret == 0 && cb.cb_first && !cb.cb_scripted)
3201 (void) printf(gettext("no datasets available\n"));
3203 return (ret);
3207 * zfs rename [-f] <fs | snap | vol> <fs | snap | vol>
3208 * zfs rename [-f] -p <fs | vol> <fs | vol>
3209 * zfs rename -r <snap> <snap>
3211 * Renames the given dataset to another of the same type.
3213 * The '-p' flag creates all the non-existing ancestors of the target first.
3215 /* ARGSUSED */
3216 static int
3217 zfs_do_rename(int argc, char **argv)
3219 zfs_handle_t *zhp;
3220 int c;
3221 int ret = 0;
3222 boolean_t recurse = B_FALSE;
3223 boolean_t parents = B_FALSE;
3224 boolean_t force_unmount = B_FALSE;
3226 /* check options */
3227 while ((c = getopt(argc, argv, "prf")) != -1) {
3228 switch (c) {
3229 case 'p':
3230 parents = B_TRUE;
3231 break;
3232 case 'r':
3233 recurse = B_TRUE;
3234 break;
3235 case 'f':
3236 force_unmount = B_TRUE;
3237 break;
3238 case '?':
3239 default:
3240 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3241 optopt);
3242 usage(B_FALSE);
3246 argc -= optind;
3247 argv += optind;
3249 /* check number of arguments */
3250 if (argc < 1) {
3251 (void) fprintf(stderr, gettext("missing source dataset "
3252 "argument\n"));
3253 usage(B_FALSE);
3255 if (argc < 2) {
3256 (void) fprintf(stderr, gettext("missing target dataset "
3257 "argument\n"));
3258 usage(B_FALSE);
3260 if (argc > 2) {
3261 (void) fprintf(stderr, gettext("too many arguments\n"));
3262 usage(B_FALSE);
3265 if (recurse && parents) {
3266 (void) fprintf(stderr, gettext("-p and -r options are mutually "
3267 "exclusive\n"));
3268 usage(B_FALSE);
3271 if (recurse && strchr(argv[0], '@') == 0) {
3272 (void) fprintf(stderr, gettext("source dataset for recursive "
3273 "rename must be a snapshot\n"));
3274 usage(B_FALSE);
3277 if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
3278 ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
3279 return (1);
3281 /* If we were asked and the name looks good, try to create ancestors. */
3282 if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
3283 zfs_create_ancestors(g_zfs, argv[1]) != 0) {
3284 zfs_close(zhp);
3285 return (1);
3288 ret = (zfs_rename(zhp, argv[1], recurse, force_unmount) != 0);
3290 zfs_close(zhp);
3291 return (ret);
3295 * zfs promote <fs>
3297 * Promotes the given clone fs to be the parent
3299 /* ARGSUSED */
3300 static int
3301 zfs_do_promote(int argc, char **argv)
3303 zfs_handle_t *zhp;
3304 int ret = 0;
3306 /* check options */
3307 if (argc > 1 && argv[1][0] == '-') {
3308 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3309 argv[1][1]);
3310 usage(B_FALSE);
3313 /* check number of arguments */
3314 if (argc < 2) {
3315 (void) fprintf(stderr, gettext("missing clone filesystem"
3316 " argument\n"));
3317 usage(B_FALSE);
3319 if (argc > 2) {
3320 (void) fprintf(stderr, gettext("too many arguments\n"));
3321 usage(B_FALSE);
3324 zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3325 if (zhp == NULL)
3326 return (1);
3328 ret = (zfs_promote(zhp) != 0);
3331 zfs_close(zhp);
3332 return (ret);
3336 * zfs rollback [-rRf] <snapshot>
3338 * -r Delete any intervening snapshots before doing rollback
3339 * -R Delete any snapshots and their clones
3340 * -f ignored for backwards compatability
3342 * Given a filesystem, rollback to a specific snapshot, discarding any changes
3343 * since then and making it the active dataset. If more recent snapshots exist,
3344 * the command will complain unless the '-r' flag is given.
3346 typedef struct rollback_cbdata {
3347 uint64_t cb_create;
3348 boolean_t cb_first;
3349 int cb_doclones;
3350 char *cb_target;
3351 int cb_error;
3352 boolean_t cb_recurse;
3353 } rollback_cbdata_t;
3355 static int
3356 rollback_check_dependent(zfs_handle_t *zhp, void *data)
3358 rollback_cbdata_t *cbp = data;
3360 if (cbp->cb_first && cbp->cb_recurse) {
3361 (void) fprintf(stderr, gettext("cannot rollback to "
3362 "'%s': clones of previous snapshots exist\n"),
3363 cbp->cb_target);
3364 (void) fprintf(stderr, gettext("use '-R' to "
3365 "force deletion of the following clones and "
3366 "dependents:\n"));
3367 cbp->cb_first = 0;
3368 cbp->cb_error = 1;
3371 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
3373 zfs_close(zhp);
3374 return (0);
3378 * Report any snapshots more recent than the one specified. Used when '-r' is
3379 * not specified. We reuse this same callback for the snapshot dependents - if
3380 * 'cb_dependent' is set, then this is a dependent and we should report it
3381 * without checking the transaction group.
3383 static int
3384 rollback_check(zfs_handle_t *zhp, void *data)
3386 rollback_cbdata_t *cbp = data;
3388 if (cbp->cb_doclones) {
3389 zfs_close(zhp);
3390 return (0);
3393 if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
3394 if (cbp->cb_first && !cbp->cb_recurse) {
3395 (void) fprintf(stderr, gettext("cannot "
3396 "rollback to '%s': more recent snapshots "
3397 "or bookmarks exist\n"),
3398 cbp->cb_target);
3399 (void) fprintf(stderr, gettext("use '-r' to "
3400 "force deletion of the following "
3401 "snapshots and bookmarks:\n"));
3402 cbp->cb_first = 0;
3403 cbp->cb_error = 1;
3406 if (cbp->cb_recurse) {
3407 if (zfs_iter_dependents(zhp, B_TRUE,
3408 rollback_check_dependent, cbp) != 0) {
3409 zfs_close(zhp);
3410 return (-1);
3412 } else {
3413 (void) fprintf(stderr, "%s\n",
3414 zfs_get_name(zhp));
3417 zfs_close(zhp);
3418 return (0);
3421 static int
3422 zfs_do_rollback(int argc, char **argv)
3424 int ret = 0;
3425 int c;
3426 boolean_t force = B_FALSE;
3427 rollback_cbdata_t cb = { 0 };
3428 zfs_handle_t *zhp, *snap;
3429 char parentname[ZFS_MAX_DATASET_NAME_LEN];
3430 char *delim;
3432 /* check options */
3433 while ((c = getopt(argc, argv, "rRf")) != -1) {
3434 switch (c) {
3435 case 'r':
3436 cb.cb_recurse = 1;
3437 break;
3438 case 'R':
3439 cb.cb_recurse = 1;
3440 cb.cb_doclones = 1;
3441 break;
3442 case 'f':
3443 force = B_TRUE;
3444 break;
3445 case '?':
3446 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3447 optopt);
3448 usage(B_FALSE);
3452 argc -= optind;
3453 argv += optind;
3455 /* check number of arguments */
3456 if (argc < 1) {
3457 (void) fprintf(stderr, gettext("missing dataset argument\n"));
3458 usage(B_FALSE);
3460 if (argc > 1) {
3461 (void) fprintf(stderr, gettext("too many arguments\n"));
3462 usage(B_FALSE);
3465 /* open the snapshot */
3466 if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
3467 return (1);
3469 /* open the parent dataset */
3470 (void) strlcpy(parentname, argv[0], sizeof (parentname));
3471 verify((delim = strrchr(parentname, '@')) != NULL);
3472 *delim = '\0';
3473 if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
3474 zfs_close(snap);
3475 return (1);
3479 * Check for more recent snapshots and/or clones based on the presence
3480 * of '-r' and '-R'.
3482 cb.cb_target = argv[0];
3483 cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3484 cb.cb_first = B_TRUE;
3485 cb.cb_error = 0;
3486 if ((ret = zfs_iter_snapshots(zhp, B_FALSE, rollback_check, &cb)) != 0)
3487 goto out;
3488 if ((ret = zfs_iter_bookmarks(zhp, rollback_check, &cb)) != 0)
3489 goto out;
3491 if ((ret = cb.cb_error) != 0)
3492 goto out;
3495 * Rollback parent to the given snapshot.
3497 ret = zfs_rollback(zhp, snap, force);
3499 out:
3500 zfs_close(snap);
3501 zfs_close(zhp);
3503 if (ret == 0)
3504 return (0);
3505 else
3506 return (1);
3510 * zfs set property=value ... { fs | snap | vol } ...
3512 * Sets the given properties for all datasets specified on the command line.
3515 static int
3516 set_callback(zfs_handle_t *zhp, void *data)
3518 nvlist_t *props = data;
3520 if (zfs_prop_set_list(zhp, props) != 0) {
3521 switch (libzfs_errno(g_zfs)) {
3522 case EZFS_MOUNTFAILED:
3523 (void) fprintf(stderr, gettext("property may be set "
3524 "but unable to remount filesystem\n"));
3525 break;
3526 case EZFS_SHARENFSFAILED:
3527 (void) fprintf(stderr, gettext("property may be set "
3528 "but unable to reshare filesystem\n"));
3529 break;
3531 return (1);
3533 return (0);
3536 static int
3537 zfs_do_set(int argc, char **argv)
3539 nvlist_t *props = NULL;
3540 int ds_start = -1; /* argv idx of first dataset arg */
3541 int ret = 0;
3543 /* check for options */
3544 if (argc > 1 && argv[1][0] == '-') {
3545 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3546 argv[1][1]);
3547 usage(B_FALSE);
3550 /* check number of arguments */
3551 if (argc < 2) {
3552 (void) fprintf(stderr, gettext("missing arguments\n"));
3553 usage(B_FALSE);
3555 if (argc < 3) {
3556 if (strchr(argv[1], '=') == NULL) {
3557 (void) fprintf(stderr, gettext("missing property=value "
3558 "argument(s)\n"));
3559 } else {
3560 (void) fprintf(stderr, gettext("missing dataset "
3561 "name(s)\n"));
3563 usage(B_FALSE);
3566 /* validate argument order: prop=val args followed by dataset args */
3567 for (int i = 1; i < argc; i++) {
3568 if (strchr(argv[i], '=') != NULL) {
3569 if (ds_start > 0) {
3570 /* out-of-order prop=val argument */
3571 (void) fprintf(stderr, gettext("invalid "
3572 "argument order\n"), i);
3573 usage(B_FALSE);
3575 } else if (ds_start < 0) {
3576 ds_start = i;
3579 if (ds_start < 0) {
3580 (void) fprintf(stderr, gettext("missing dataset name(s)\n"));
3581 usage(B_FALSE);
3584 /* Populate a list of property settings */
3585 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3586 nomem();
3587 for (int i = 1; i < ds_start; i++) {
3588 if ((ret = parseprop(props, argv[i])) != 0)
3589 goto error;
3592 ret = zfs_for_each(argc - ds_start, argv + ds_start, 0,
3593 ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, props);
3595 error:
3596 nvlist_free(props);
3597 return (ret);
3600 typedef struct snap_cbdata {
3601 nvlist_t *sd_nvl;
3602 boolean_t sd_recursive;
3603 const char *sd_snapname;
3604 } snap_cbdata_t;
3606 static int
3607 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
3609 snap_cbdata_t *sd = arg;
3610 char *name;
3611 int rv = 0;
3612 int error;
3614 if (sd->sd_recursive &&
3615 zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
3616 zfs_close(zhp);
3617 return (0);
3620 error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
3621 if (error == -1)
3622 nomem();
3623 fnvlist_add_boolean(sd->sd_nvl, name);
3624 free(name);
3626 if (sd->sd_recursive)
3627 rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
3628 zfs_close(zhp);
3629 return (rv);
3633 * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
3635 * Creates a snapshot with the given name. While functionally equivalent to
3636 * 'zfs create', it is a separate command to differentiate intent.
3638 static int
3639 zfs_do_snapshot(int argc, char **argv)
3641 int ret = 0;
3642 char c;
3643 nvlist_t *props;
3644 snap_cbdata_t sd = { 0 };
3645 boolean_t multiple_snaps = B_FALSE;
3647 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3648 nomem();
3649 if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
3650 nomem();
3652 /* check options */
3653 while ((c = getopt(argc, argv, "ro:")) != -1) {
3654 switch (c) {
3655 case 'o':
3656 if (parseprop(props, optarg) != 0)
3657 return (1);
3658 break;
3659 case 'r':
3660 sd.sd_recursive = B_TRUE;
3661 multiple_snaps = B_TRUE;
3662 break;
3663 case '?':
3664 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3665 optopt);
3666 goto usage;
3670 argc -= optind;
3671 argv += optind;
3673 /* check number of arguments */
3674 if (argc < 1) {
3675 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3676 goto usage;
3679 if (argc > 1)
3680 multiple_snaps = B_TRUE;
3681 for (; argc > 0; argc--, argv++) {
3682 char *atp;
3683 zfs_handle_t *zhp;
3685 atp = strchr(argv[0], '@');
3686 if (atp == NULL)
3687 goto usage;
3688 *atp = '\0';
3689 sd.sd_snapname = atp + 1;
3690 zhp = zfs_open(g_zfs, argv[0],
3691 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3692 if (zhp == NULL)
3693 goto usage;
3694 if (zfs_snapshot_cb(zhp, &sd) != 0)
3695 goto usage;
3698 ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
3699 nvlist_free(sd.sd_nvl);
3700 nvlist_free(props);
3701 if (ret != 0 && multiple_snaps)
3702 (void) fprintf(stderr, gettext("no snapshots were created\n"));
3703 return (ret != 0);
3705 usage:
3706 nvlist_free(sd.sd_nvl);
3707 nvlist_free(props);
3708 usage(B_FALSE);
3709 return (-1);
3713 * Send a backup stream to stdout.
3715 static int
3716 zfs_do_send(int argc, char **argv)
3718 char *fromname = NULL;
3719 char *toname = NULL;
3720 char *resume_token = NULL;
3721 char *cp;
3722 zfs_handle_t *zhp;
3723 sendflags_t flags = { 0 };
3724 int c, err;
3725 nvlist_t *dbgnv = NULL;
3726 boolean_t extraverbose = B_FALSE;
3728 struct option long_options[] = {
3729 {"replicate", no_argument, NULL, 'R'},
3730 {"props", no_argument, NULL, 'p'},
3731 {"parsable", no_argument, NULL, 'P'},
3732 {"dedup", no_argument, NULL, 'D'},
3733 {"verbose", no_argument, NULL, 'v'},
3734 {"dryrun", no_argument, NULL, 'n'},
3735 {"large-block", no_argument, NULL, 'L'},
3736 {"embed", no_argument, NULL, 'e'},
3737 {"resume", required_argument, NULL, 't'},
3738 {"compressed", no_argument, NULL, 'c'},
3739 {0, 0, 0, 0}
3742 /* check options */
3743 while ((c = getopt_long(argc, argv, ":i:I:RbDpvnPLet:c", long_options,
3744 NULL)) != -1) {
3745 switch (c) {
3746 case 'i':
3747 if (fromname)
3748 usage(B_FALSE);
3749 fromname = optarg;
3750 break;
3751 case 'I':
3752 if (fromname)
3753 usage(B_FALSE);
3754 fromname = optarg;
3755 flags.doall = B_TRUE;
3756 break;
3757 case 'R':
3758 flags.replicate = B_TRUE;
3759 break;
3760 case 'p':
3761 flags.props = B_TRUE;
3762 break;
3763 case 'P':
3764 flags.parsable = B_TRUE;
3765 flags.verbose = B_TRUE;
3766 break;
3767 case 'v':
3768 if (flags.verbose)
3769 extraverbose = B_TRUE;
3770 flags.verbose = B_TRUE;
3771 flags.progress = B_TRUE;
3772 break;
3773 case 'D':
3774 flags.dedup = B_TRUE;
3775 break;
3776 case 'n':
3777 flags.dryrun = B_TRUE;
3778 break;
3779 case 'L':
3780 flags.largeblock = B_TRUE;
3781 break;
3782 case 'e':
3783 flags.embed_data = B_TRUE;
3784 break;
3785 case 't':
3786 resume_token = optarg;
3787 break;
3788 case 'c':
3789 flags.compress = B_TRUE;
3790 break;
3791 case ':':
3793 * If a parameter was not passed, optopt contains the
3794 * value that would normally lead us into the
3795 * appropriate case statement. If it's > 256, then this
3796 * must be a longopt and we should look at argv to get
3797 * the string. Otherwise it's just the character, so we
3798 * should use it directly.
3800 if (optopt <= UINT8_MAX) {
3801 (void) fprintf(stderr,
3802 gettext("missing argument for '%c' "
3803 "option\n"), optopt);
3804 } else {
3805 (void) fprintf(stderr,
3806 gettext("missing argument for '%s' "
3807 "option\n"), argv[optind - 1]);
3809 usage(B_FALSE);
3810 break;
3811 case '?':
3812 /*FALLTHROUGH*/
3813 default:
3815 * If an invalid flag was passed, optopt contains the
3816 * character if it was a short flag, or 0 if it was a
3817 * longopt.
3819 if (optopt != 0) {
3820 (void) fprintf(stderr,
3821 gettext("invalid option '%c'\n"), optopt);
3822 } else {
3823 (void) fprintf(stderr,
3824 gettext("invalid option '%s'\n"),
3825 argv[optind - 1]);
3828 usage(B_FALSE);
3832 argc -= optind;
3833 argv += optind;
3835 if (resume_token != NULL) {
3836 if (fromname != NULL || flags.replicate || flags.props ||
3837 flags.dedup) {
3838 (void) fprintf(stderr,
3839 gettext("invalid flags combined with -t\n"));
3840 usage(B_FALSE);
3842 if (argc != 0) {
3843 (void) fprintf(stderr, gettext("no additional "
3844 "arguments are permitted with -t\n"));
3845 usage(B_FALSE);
3847 } else {
3848 if (argc < 1) {
3849 (void) fprintf(stderr,
3850 gettext("missing snapshot argument\n"));
3851 usage(B_FALSE);
3853 if (argc > 1) {
3854 (void) fprintf(stderr, gettext("too many arguments\n"));
3855 usage(B_FALSE);
3859 if (!flags.dryrun && isatty(STDOUT_FILENO)) {
3860 (void) fprintf(stderr,
3861 gettext("Error: Stream can not be written to a terminal.\n"
3862 "You must redirect standard output.\n"));
3863 return (1);
3866 if (resume_token != NULL) {
3867 return (zfs_send_resume(g_zfs, &flags, STDOUT_FILENO,
3868 resume_token));
3872 * Special case sending a filesystem, or from a bookmark.
3874 if (strchr(argv[0], '@') == NULL ||
3875 (fromname && strchr(fromname, '#') != NULL)) {
3876 char frombuf[ZFS_MAX_DATASET_NAME_LEN];
3877 enum lzc_send_flags lzc_flags = 0;
3879 if (flags.replicate || flags.doall || flags.props ||
3880 flags.dedup || flags.dryrun || flags.verbose ||
3881 flags.progress) {
3882 (void) fprintf(stderr,
3883 gettext("Error: "
3884 "Unsupported flag with filesystem or bookmark.\n"));
3885 return (1);
3888 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
3889 if (zhp == NULL)
3890 return (1);
3892 if (flags.largeblock)
3893 lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
3894 if (flags.embed_data)
3895 lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
3896 if (flags.compress)
3897 lzc_flags |= LZC_SEND_FLAG_COMPRESS;
3899 if (fromname != NULL &&
3900 (fromname[0] == '#' || fromname[0] == '@')) {
3902 * Incremental source name begins with # or @.
3903 * Default to same fs as target.
3905 (void) strncpy(frombuf, argv[0], sizeof (frombuf));
3906 cp = strchr(frombuf, '@');
3907 if (cp != NULL)
3908 *cp = '\0';
3909 (void) strlcat(frombuf, fromname, sizeof (frombuf));
3910 fromname = frombuf;
3912 err = zfs_send_one(zhp, fromname, STDOUT_FILENO, lzc_flags);
3913 zfs_close(zhp);
3914 return (err != 0);
3917 cp = strchr(argv[0], '@');
3918 *cp = '\0';
3919 toname = cp + 1;
3920 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3921 if (zhp == NULL)
3922 return (1);
3925 * If they specified the full path to the snapshot, chop off
3926 * everything except the short name of the snapshot, but special
3927 * case if they specify the origin.
3929 if (fromname && (cp = strchr(fromname, '@')) != NULL) {
3930 char origin[ZFS_MAX_DATASET_NAME_LEN];
3931 zprop_source_t src;
3933 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
3934 origin, sizeof (origin), &src, NULL, 0, B_FALSE);
3936 if (strcmp(origin, fromname) == 0) {
3937 fromname = NULL;
3938 flags.fromorigin = B_TRUE;
3939 } else {
3940 *cp = '\0';
3941 if (cp != fromname && strcmp(argv[0], fromname)) {
3942 (void) fprintf(stderr,
3943 gettext("incremental source must be "
3944 "in same filesystem\n"));
3945 usage(B_FALSE);
3947 fromname = cp + 1;
3948 if (strchr(fromname, '@') || strchr(fromname, '/')) {
3949 (void) fprintf(stderr,
3950 gettext("invalid incremental source\n"));
3951 usage(B_FALSE);
3956 if (flags.replicate && fromname == NULL)
3957 flags.doall = B_TRUE;
3959 err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
3960 extraverbose ? &dbgnv : NULL);
3962 if (extraverbose && dbgnv != NULL) {
3964 * dump_nvlist prints to stdout, but that's been
3965 * redirected to a file. Make it print to stderr
3966 * instead.
3968 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
3969 dump_nvlist(dbgnv, 0);
3970 nvlist_free(dbgnv);
3972 zfs_close(zhp);
3974 return (err != 0);
3978 * Restore a backup stream from stdin.
3980 static int
3981 zfs_do_receive(int argc, char **argv)
3983 int c, err = 0;
3984 recvflags_t flags = { 0 };
3985 boolean_t abort_resumable = B_FALSE;
3987 nvlist_t *props;
3988 nvpair_t *nvp = NULL;
3990 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3991 nomem();
3993 /* check options */
3994 while ((c = getopt(argc, argv, ":o:denuvFsA")) != -1) {
3995 switch (c) {
3996 case 'o':
3997 if (parseprop(props, optarg) != 0)
3998 return (1);
3999 break;
4000 case 'd':
4001 flags.isprefix = B_TRUE;
4002 break;
4003 case 'e':
4004 flags.isprefix = B_TRUE;
4005 flags.istail = B_TRUE;
4006 break;
4007 case 'n':
4008 flags.dryrun = B_TRUE;
4009 break;
4010 case 'u':
4011 flags.nomount = B_TRUE;
4012 break;
4013 case 'v':
4014 flags.verbose = B_TRUE;
4015 break;
4016 case 's':
4017 flags.resumable = B_TRUE;
4018 break;
4019 case 'F':
4020 flags.force = B_TRUE;
4021 break;
4022 case 'A':
4023 abort_resumable = B_TRUE;
4024 break;
4025 case ':':
4026 (void) fprintf(stderr, gettext("missing argument for "
4027 "'%c' option\n"), optopt);
4028 usage(B_FALSE);
4029 break;
4030 case '?':
4031 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4032 optopt);
4033 usage(B_FALSE);
4037 argc -= optind;
4038 argv += optind;
4040 /* check number of arguments */
4041 if (argc < 1) {
4042 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
4043 usage(B_FALSE);
4045 if (argc > 1) {
4046 (void) fprintf(stderr, gettext("too many arguments\n"));
4047 usage(B_FALSE);
4050 while ((nvp = nvlist_next_nvpair(props, nvp))) {
4051 if (strcmp(nvpair_name(nvp), "origin") != 0) {
4052 (void) fprintf(stderr, gettext("invalid option"));
4053 usage(B_FALSE);
4057 if (abort_resumable) {
4058 if (flags.isprefix || flags.istail || flags.dryrun ||
4059 flags.resumable || flags.nomount) {
4060 (void) fprintf(stderr, gettext("invalid option"));
4061 usage(B_FALSE);
4064 char namebuf[ZFS_MAX_DATASET_NAME_LEN];
4065 (void) snprintf(namebuf, sizeof (namebuf),
4066 "%s/%%recv", argv[0]);
4068 if (zfs_dataset_exists(g_zfs, namebuf,
4069 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) {
4070 zfs_handle_t *zhp = zfs_open(g_zfs,
4071 namebuf, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4072 if (zhp == NULL)
4073 return (1);
4074 err = zfs_destroy(zhp, B_FALSE);
4075 } else {
4076 zfs_handle_t *zhp = zfs_open(g_zfs,
4077 argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4078 if (zhp == NULL)
4079 usage(B_FALSE);
4080 if (!zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) ||
4081 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
4082 NULL, 0, NULL, NULL, 0, B_TRUE) == -1) {
4083 (void) fprintf(stderr,
4084 gettext("'%s' does not have any "
4085 "resumable receive state to abort\n"),
4086 argv[0]);
4087 return (1);
4089 err = zfs_destroy(zhp, B_FALSE);
4092 return (err != 0);
4095 if (isatty(STDIN_FILENO)) {
4096 (void) fprintf(stderr,
4097 gettext("Error: Backup stream can not be read "
4098 "from a terminal.\n"
4099 "You must redirect standard input.\n"));
4100 return (1);
4102 err = zfs_receive(g_zfs, argv[0], props, &flags, STDIN_FILENO, NULL);
4104 return (err != 0);
4108 * allow/unallow stuff
4110 /* copied from zfs/sys/dsl_deleg.h */
4111 #define ZFS_DELEG_PERM_CREATE "create"
4112 #define ZFS_DELEG_PERM_DESTROY "destroy"
4113 #define ZFS_DELEG_PERM_SNAPSHOT "snapshot"
4114 #define ZFS_DELEG_PERM_ROLLBACK "rollback"
4115 #define ZFS_DELEG_PERM_CLONE "clone"
4116 #define ZFS_DELEG_PERM_PROMOTE "promote"
4117 #define ZFS_DELEG_PERM_RENAME "rename"
4118 #define ZFS_DELEG_PERM_MOUNT "mount"
4119 #define ZFS_DELEG_PERM_SHARE "share"
4120 #define ZFS_DELEG_PERM_SEND "send"
4121 #define ZFS_DELEG_PERM_RECEIVE "receive"
4122 #define ZFS_DELEG_PERM_ALLOW "allow"
4123 #define ZFS_DELEG_PERM_USERPROP "userprop"
4124 #define ZFS_DELEG_PERM_VSCAN "vscan" /* ??? */
4125 #define ZFS_DELEG_PERM_USERQUOTA "userquota"
4126 #define ZFS_DELEG_PERM_GROUPQUOTA "groupquota"
4127 #define ZFS_DELEG_PERM_USERUSED "userused"
4128 #define ZFS_DELEG_PERM_GROUPUSED "groupused"
4129 #define ZFS_DELEG_PERM_HOLD "hold"
4130 #define ZFS_DELEG_PERM_RELEASE "release"
4131 #define ZFS_DELEG_PERM_DIFF "diff"
4132 #define ZFS_DELEG_PERM_BOOKMARK "bookmark"
4134 #define ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
4136 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
4137 { ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
4138 { ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
4139 { ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
4140 { ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
4141 { ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
4142 { ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
4143 { ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
4144 { ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
4145 { ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
4146 { ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
4147 { ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
4148 { ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
4149 { ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
4150 { ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
4151 { ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
4152 { ZFS_DELEG_PERM_BOOKMARK, ZFS_DELEG_NOTE_BOOKMARK },
4154 { ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
4155 { ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
4156 { ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
4157 { ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
4158 { ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
4159 { NULL, ZFS_DELEG_NOTE_NONE }
4162 /* permission structure */
4163 typedef struct deleg_perm {
4164 zfs_deleg_who_type_t dp_who_type;
4165 const char *dp_name;
4166 boolean_t dp_local;
4167 boolean_t dp_descend;
4168 } deleg_perm_t;
4170 /* */
4171 typedef struct deleg_perm_node {
4172 deleg_perm_t dpn_perm;
4174 uu_avl_node_t dpn_avl_node;
4175 } deleg_perm_node_t;
4177 typedef struct fs_perm fs_perm_t;
4179 /* permissions set */
4180 typedef struct who_perm {
4181 zfs_deleg_who_type_t who_type;
4182 const char *who_name; /* id */
4183 char who_ug_name[256]; /* user/group name */
4184 fs_perm_t *who_fsperm; /* uplink */
4186 uu_avl_t *who_deleg_perm_avl; /* permissions */
4187 } who_perm_t;
4189 /* */
4190 typedef struct who_perm_node {
4191 who_perm_t who_perm;
4192 uu_avl_node_t who_avl_node;
4193 } who_perm_node_t;
4195 typedef struct fs_perm_set fs_perm_set_t;
4196 /* fs permissions */
4197 struct fs_perm {
4198 const char *fsp_name;
4200 uu_avl_t *fsp_sc_avl; /* sets,create */
4201 uu_avl_t *fsp_uge_avl; /* user,group,everyone */
4203 fs_perm_set_t *fsp_set; /* uplink */
4206 /* */
4207 typedef struct fs_perm_node {
4208 fs_perm_t fspn_fsperm;
4209 uu_avl_t *fspn_avl;
4211 uu_list_node_t fspn_list_node;
4212 } fs_perm_node_t;
4214 /* top level structure */
4215 struct fs_perm_set {
4216 uu_list_pool_t *fsps_list_pool;
4217 uu_list_t *fsps_list; /* list of fs_perms */
4219 uu_avl_pool_t *fsps_named_set_avl_pool;
4220 uu_avl_pool_t *fsps_who_perm_avl_pool;
4221 uu_avl_pool_t *fsps_deleg_perm_avl_pool;
4224 static inline const char *
4225 deleg_perm_type(zfs_deleg_note_t note)
4227 /* subcommands */
4228 switch (note) {
4229 /* SUBCOMMANDS */
4230 /* OTHER */
4231 case ZFS_DELEG_NOTE_GROUPQUOTA:
4232 case ZFS_DELEG_NOTE_GROUPUSED:
4233 case ZFS_DELEG_NOTE_USERPROP:
4234 case ZFS_DELEG_NOTE_USERQUOTA:
4235 case ZFS_DELEG_NOTE_USERUSED:
4236 /* other */
4237 return (gettext("other"));
4238 default:
4239 return (gettext("subcommand"));
4243 static int
4244 who_type2weight(zfs_deleg_who_type_t who_type)
4246 int res;
4247 switch (who_type) {
4248 case ZFS_DELEG_NAMED_SET_SETS:
4249 case ZFS_DELEG_NAMED_SET:
4250 res = 0;
4251 break;
4252 case ZFS_DELEG_CREATE_SETS:
4253 case ZFS_DELEG_CREATE:
4254 res = 1;
4255 break;
4256 case ZFS_DELEG_USER_SETS:
4257 case ZFS_DELEG_USER:
4258 res = 2;
4259 break;
4260 case ZFS_DELEG_GROUP_SETS:
4261 case ZFS_DELEG_GROUP:
4262 res = 3;
4263 break;
4264 case ZFS_DELEG_EVERYONE_SETS:
4265 case ZFS_DELEG_EVERYONE:
4266 res = 4;
4267 break;
4268 default:
4269 res = -1;
4272 return (res);
4275 /* ARGSUSED */
4276 static int
4277 who_perm_compare(const void *larg, const void *rarg, void *unused)
4279 const who_perm_node_t *l = larg;
4280 const who_perm_node_t *r = rarg;
4281 zfs_deleg_who_type_t ltype = l->who_perm.who_type;
4282 zfs_deleg_who_type_t rtype = r->who_perm.who_type;
4283 int lweight = who_type2weight(ltype);
4284 int rweight = who_type2weight(rtype);
4285 int res = lweight - rweight;
4286 if (res == 0)
4287 res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
4288 ZFS_MAX_DELEG_NAME-1);
4290 if (res == 0)
4291 return (0);
4292 if (res > 0)
4293 return (1);
4294 else
4295 return (-1);
4298 /* ARGSUSED */
4299 static int
4300 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
4302 const deleg_perm_node_t *l = larg;
4303 const deleg_perm_node_t *r = rarg;
4304 int res = strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
4305 ZFS_MAX_DELEG_NAME-1);
4307 if (res == 0)
4308 return (0);
4310 if (res > 0)
4311 return (1);
4312 else
4313 return (-1);
4316 static inline void
4317 fs_perm_set_init(fs_perm_set_t *fspset)
4319 bzero(fspset, sizeof (fs_perm_set_t));
4321 if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
4322 sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
4323 NULL, UU_DEFAULT)) == NULL)
4324 nomem();
4325 if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
4326 UU_DEFAULT)) == NULL)
4327 nomem();
4329 if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
4330 "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
4331 who_perm_node_t, who_avl_node), who_perm_compare,
4332 UU_DEFAULT)) == NULL)
4333 nomem();
4335 if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
4336 "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
4337 who_perm_node_t, who_avl_node), who_perm_compare,
4338 UU_DEFAULT)) == NULL)
4339 nomem();
4341 if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
4342 "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
4343 deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
4344 == NULL)
4345 nomem();
4348 static inline void fs_perm_fini(fs_perm_t *);
4349 static inline void who_perm_fini(who_perm_t *);
4351 static inline void
4352 fs_perm_set_fini(fs_perm_set_t *fspset)
4354 fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
4356 while (node != NULL) {
4357 fs_perm_node_t *next_node =
4358 uu_list_next(fspset->fsps_list, node);
4359 fs_perm_t *fsperm = &node->fspn_fsperm;
4360 fs_perm_fini(fsperm);
4361 uu_list_remove(fspset->fsps_list, node);
4362 free(node);
4363 node = next_node;
4366 uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
4367 uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
4368 uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
4371 static inline void
4372 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
4373 const char *name)
4375 deleg_perm->dp_who_type = type;
4376 deleg_perm->dp_name = name;
4379 static inline void
4380 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
4381 zfs_deleg_who_type_t type, const char *name)
4383 uu_avl_pool_t *pool;
4384 pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
4386 bzero(who_perm, sizeof (who_perm_t));
4388 if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
4389 UU_DEFAULT)) == NULL)
4390 nomem();
4392 who_perm->who_type = type;
4393 who_perm->who_name = name;
4394 who_perm->who_fsperm = fsperm;
4397 static inline void
4398 who_perm_fini(who_perm_t *who_perm)
4400 deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
4402 while (node != NULL) {
4403 deleg_perm_node_t *next_node =
4404 uu_avl_next(who_perm->who_deleg_perm_avl, node);
4406 uu_avl_remove(who_perm->who_deleg_perm_avl, node);
4407 free(node);
4408 node = next_node;
4411 uu_avl_destroy(who_perm->who_deleg_perm_avl);
4414 static inline void
4415 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
4417 uu_avl_pool_t *nset_pool = fspset->fsps_named_set_avl_pool;
4418 uu_avl_pool_t *who_pool = fspset->fsps_who_perm_avl_pool;
4420 bzero(fsperm, sizeof (fs_perm_t));
4422 if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
4423 == NULL)
4424 nomem();
4426 if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
4427 == NULL)
4428 nomem();
4430 fsperm->fsp_set = fspset;
4431 fsperm->fsp_name = fsname;
4434 static inline void
4435 fs_perm_fini(fs_perm_t *fsperm)
4437 who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
4438 while (node != NULL) {
4439 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
4440 node);
4441 who_perm_t *who_perm = &node->who_perm;
4442 who_perm_fini(who_perm);
4443 uu_avl_remove(fsperm->fsp_sc_avl, node);
4444 free(node);
4445 node = next_node;
4448 node = uu_avl_first(fsperm->fsp_uge_avl);
4449 while (node != NULL) {
4450 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
4451 node);
4452 who_perm_t *who_perm = &node->who_perm;
4453 who_perm_fini(who_perm);
4454 uu_avl_remove(fsperm->fsp_uge_avl, node);
4455 free(node);
4456 node = next_node;
4459 uu_avl_destroy(fsperm->fsp_sc_avl);
4460 uu_avl_destroy(fsperm->fsp_uge_avl);
4463 static void
4464 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
4465 zfs_deleg_who_type_t who_type, const char *name, char locality)
4467 uu_avl_index_t idx = 0;
4469 deleg_perm_node_t *found_node = NULL;
4470 deleg_perm_t *deleg_perm = &node->dpn_perm;
4472 deleg_perm_init(deleg_perm, who_type, name);
4474 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4475 == NULL)
4476 uu_avl_insert(avl, node, idx);
4477 else {
4478 node = found_node;
4479 deleg_perm = &node->dpn_perm;
4483 switch (locality) {
4484 case ZFS_DELEG_LOCAL:
4485 deleg_perm->dp_local = B_TRUE;
4486 break;
4487 case ZFS_DELEG_DESCENDENT:
4488 deleg_perm->dp_descend = B_TRUE;
4489 break;
4490 case ZFS_DELEG_NA:
4491 break;
4492 default:
4493 assert(B_FALSE); /* invalid locality */
4497 static inline int
4498 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
4500 nvpair_t *nvp = NULL;
4501 fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
4502 uu_avl_t *avl = who_perm->who_deleg_perm_avl;
4503 zfs_deleg_who_type_t who_type = who_perm->who_type;
4505 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4506 const char *name = nvpair_name(nvp);
4507 data_type_t type = nvpair_type(nvp);
4508 uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
4509 deleg_perm_node_t *node =
4510 safe_malloc(sizeof (deleg_perm_node_t));
4512 assert(type == DATA_TYPE_BOOLEAN);
4514 uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
4515 set_deleg_perm_node(avl, node, who_type, name, locality);
4518 return (0);
4521 static inline int
4522 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
4524 nvpair_t *nvp = NULL;
4525 fs_perm_set_t *fspset = fsperm->fsp_set;
4527 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4528 nvlist_t *nvl2 = NULL;
4529 const char *name = nvpair_name(nvp);
4530 uu_avl_t *avl = NULL;
4531 uu_avl_pool_t *avl_pool = NULL;
4532 zfs_deleg_who_type_t perm_type = name[0];
4533 char perm_locality = name[1];
4534 const char *perm_name = name + 3;
4535 boolean_t is_set = B_TRUE;
4536 who_perm_t *who_perm = NULL;
4538 assert('$' == name[2]);
4540 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4541 return (-1);
4543 switch (perm_type) {
4544 case ZFS_DELEG_CREATE:
4545 case ZFS_DELEG_CREATE_SETS:
4546 case ZFS_DELEG_NAMED_SET:
4547 case ZFS_DELEG_NAMED_SET_SETS:
4548 avl_pool = fspset->fsps_named_set_avl_pool;
4549 avl = fsperm->fsp_sc_avl;
4550 break;
4551 case ZFS_DELEG_USER:
4552 case ZFS_DELEG_USER_SETS:
4553 case ZFS_DELEG_GROUP:
4554 case ZFS_DELEG_GROUP_SETS:
4555 case ZFS_DELEG_EVERYONE:
4556 case ZFS_DELEG_EVERYONE_SETS:
4557 avl_pool = fspset->fsps_who_perm_avl_pool;
4558 avl = fsperm->fsp_uge_avl;
4559 break;
4561 default:
4562 assert(!"unhandled zfs_deleg_who_type_t");
4565 if (is_set) {
4566 who_perm_node_t *found_node = NULL;
4567 who_perm_node_t *node = safe_malloc(
4568 sizeof (who_perm_node_t));
4569 who_perm = &node->who_perm;
4570 uu_avl_index_t idx = 0;
4572 uu_avl_node_init(node, &node->who_avl_node, avl_pool);
4573 who_perm_init(who_perm, fsperm, perm_type, perm_name);
4575 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4576 == NULL) {
4577 if (avl == fsperm->fsp_uge_avl) {
4578 uid_t rid = 0;
4579 struct passwd *p = NULL;
4580 struct group *g = NULL;
4581 const char *nice_name = NULL;
4583 switch (perm_type) {
4584 case ZFS_DELEG_USER_SETS:
4585 case ZFS_DELEG_USER:
4586 rid = atoi(perm_name);
4587 p = getpwuid(rid);
4588 if (p)
4589 nice_name = p->pw_name;
4590 break;
4591 case ZFS_DELEG_GROUP_SETS:
4592 case ZFS_DELEG_GROUP:
4593 rid = atoi(perm_name);
4594 g = getgrgid(rid);
4595 if (g)
4596 nice_name = g->gr_name;
4597 break;
4599 default:
4600 break;
4603 if (nice_name != NULL)
4604 (void) strlcpy(
4605 node->who_perm.who_ug_name,
4606 nice_name, 256);
4609 uu_avl_insert(avl, node, idx);
4610 } else {
4611 node = found_node;
4612 who_perm = &node->who_perm;
4616 (void) parse_who_perm(who_perm, nvl2, perm_locality);
4619 return (0);
4622 static inline int
4623 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
4625 nvpair_t *nvp = NULL;
4626 uu_avl_index_t idx = 0;
4628 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4629 nvlist_t *nvl2 = NULL;
4630 const char *fsname = nvpair_name(nvp);
4631 data_type_t type = nvpair_type(nvp);
4632 fs_perm_t *fsperm = NULL;
4633 fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
4634 if (node == NULL)
4635 nomem();
4637 fsperm = &node->fspn_fsperm;
4639 assert(DATA_TYPE_NVLIST == type);
4641 uu_list_node_init(node, &node->fspn_list_node,
4642 fspset->fsps_list_pool);
4644 idx = uu_list_numnodes(fspset->fsps_list);
4645 fs_perm_init(fsperm, fspset, fsname);
4647 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4648 return (-1);
4650 (void) parse_fs_perm(fsperm, nvl2);
4652 uu_list_insert(fspset->fsps_list, node, idx);
4655 return (0);
4658 static inline const char *
4659 deleg_perm_comment(zfs_deleg_note_t note)
4661 const char *str = "";
4663 /* subcommands */
4664 switch (note) {
4665 /* SUBCOMMANDS */
4666 case ZFS_DELEG_NOTE_ALLOW:
4667 str = gettext("Must also have the permission that is being"
4668 "\n\t\t\t\tallowed");
4669 break;
4670 case ZFS_DELEG_NOTE_CLONE:
4671 str = gettext("Must also have the 'create' ability and 'mount'"
4672 "\n\t\t\t\tability in the origin file system");
4673 break;
4674 case ZFS_DELEG_NOTE_CREATE:
4675 str = gettext("Must also have the 'mount' ability");
4676 break;
4677 case ZFS_DELEG_NOTE_DESTROY:
4678 str = gettext("Must also have the 'mount' ability");
4679 break;
4680 case ZFS_DELEG_NOTE_DIFF:
4681 str = gettext("Allows lookup of paths within a dataset;"
4682 "\n\t\t\t\tgiven an object number. Ordinary users need this"
4683 "\n\t\t\t\tin order to use zfs diff");
4684 break;
4685 case ZFS_DELEG_NOTE_HOLD:
4686 str = gettext("Allows adding a user hold to a snapshot");
4687 break;
4688 case ZFS_DELEG_NOTE_MOUNT:
4689 str = gettext("Allows mount/umount of ZFS datasets");
4690 break;
4691 case ZFS_DELEG_NOTE_PROMOTE:
4692 str = gettext("Must also have the 'mount'\n\t\t\t\tand"
4693 " 'promote' ability in the origin file system");
4694 break;
4695 case ZFS_DELEG_NOTE_RECEIVE:
4696 str = gettext("Must also have the 'mount' and 'create'"
4697 " ability");
4698 break;
4699 case ZFS_DELEG_NOTE_RELEASE:
4700 str = gettext("Allows releasing a user hold which\n\t\t\t\t"
4701 "might destroy the snapshot");
4702 break;
4703 case ZFS_DELEG_NOTE_RENAME:
4704 str = gettext("Must also have the 'mount' and 'create'"
4705 "\n\t\t\t\tability in the new parent");
4706 break;
4707 case ZFS_DELEG_NOTE_ROLLBACK:
4708 str = gettext("");
4709 break;
4710 case ZFS_DELEG_NOTE_SEND:
4711 str = gettext("");
4712 break;
4713 case ZFS_DELEG_NOTE_SHARE:
4714 str = gettext("Allows sharing file systems over NFS or SMB"
4715 "\n\t\t\t\tprotocols");
4716 break;
4717 case ZFS_DELEG_NOTE_SNAPSHOT:
4718 str = gettext("");
4719 break;
4721 * case ZFS_DELEG_NOTE_VSCAN:
4722 * str = gettext("");
4723 * break;
4725 /* OTHER */
4726 case ZFS_DELEG_NOTE_GROUPQUOTA:
4727 str = gettext("Allows accessing any groupquota@... property");
4728 break;
4729 case ZFS_DELEG_NOTE_GROUPUSED:
4730 str = gettext("Allows reading any groupused@... property");
4731 break;
4732 case ZFS_DELEG_NOTE_USERPROP:
4733 str = gettext("Allows changing any user property");
4734 break;
4735 case ZFS_DELEG_NOTE_USERQUOTA:
4736 str = gettext("Allows accessing any userquota@... property");
4737 break;
4738 case ZFS_DELEG_NOTE_USERUSED:
4739 str = gettext("Allows reading any userused@... property");
4740 break;
4741 /* other */
4742 default:
4743 str = "";
4746 return (str);
4749 struct allow_opts {
4750 boolean_t local;
4751 boolean_t descend;
4752 boolean_t user;
4753 boolean_t group;
4754 boolean_t everyone;
4755 boolean_t create;
4756 boolean_t set;
4757 boolean_t recursive; /* unallow only */
4758 boolean_t prt_usage;
4760 boolean_t prt_perms;
4761 char *who;
4762 char *perms;
4763 const char *dataset;
4766 static inline int
4767 prop_cmp(const void *a, const void *b)
4769 const char *str1 = *(const char **)a;
4770 const char *str2 = *(const char **)b;
4771 return (strcmp(str1, str2));
4774 static void
4775 allow_usage(boolean_t un, boolean_t requested, const char *msg)
4777 const char *opt_desc[] = {
4778 "-h", gettext("show this help message and exit"),
4779 "-l", gettext("set permission locally"),
4780 "-d", gettext("set permission for descents"),
4781 "-u", gettext("set permission for user"),
4782 "-g", gettext("set permission for group"),
4783 "-e", gettext("set permission for everyone"),
4784 "-c", gettext("set create time permission"),
4785 "-s", gettext("define permission set"),
4786 /* unallow only */
4787 "-r", gettext("remove permissions recursively"),
4789 size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
4790 size_t allow_size = unallow_size - 2;
4791 const char *props[ZFS_NUM_PROPS];
4792 int i;
4793 size_t count = 0;
4794 FILE *fp = requested ? stdout : stderr;
4795 zprop_desc_t *pdtbl = zfs_prop_get_table();
4796 const char *fmt = gettext("%-16s %-14s\t%s\n");
4798 (void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
4799 HELP_ALLOW));
4800 (void) fprintf(fp, gettext("Options:\n"));
4801 for (int i = 0; i < (un ? unallow_size : allow_size); i++) {
4802 const char *opt = opt_desc[i++];
4803 const char *optdsc = opt_desc[i];
4804 (void) fprintf(fp, gettext(" %-10s %s\n"), opt, optdsc);
4807 (void) fprintf(fp, gettext("\nThe following permissions are "
4808 "supported:\n\n"));
4809 (void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
4810 gettext("NOTES"));
4811 for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
4812 const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
4813 zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
4814 const char *perm_type = deleg_perm_type(perm_note);
4815 const char *perm_comment = deleg_perm_comment(perm_note);
4816 (void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
4819 for (i = 0; i < ZFS_NUM_PROPS; i++) {
4820 zprop_desc_t *pd = &pdtbl[i];
4821 if (pd->pd_visible != B_TRUE)
4822 continue;
4824 if (pd->pd_attr == PROP_READONLY)
4825 continue;
4827 props[count++] = pd->pd_name;
4829 props[count] = NULL;
4831 qsort(props, count, sizeof (char *), prop_cmp);
4833 for (i = 0; i < count; i++)
4834 (void) fprintf(fp, fmt, props[i], gettext("property"), "");
4836 if (msg != NULL)
4837 (void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
4839 exit(requested ? 0 : 2);
4842 static inline const char *
4843 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
4844 char **permsp)
4846 if (un && argc == expected_argc - 1)
4847 *permsp = NULL;
4848 else if (argc == expected_argc)
4849 *permsp = argv[argc - 2];
4850 else
4851 allow_usage(un, B_FALSE,
4852 gettext("wrong number of parameters\n"));
4854 return (argv[argc - 1]);
4857 static void
4858 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
4860 int uge_sum = opts->user + opts->group + opts->everyone;
4861 int csuge_sum = opts->create + opts->set + uge_sum;
4862 int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
4863 int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
4865 if (uge_sum > 1)
4866 allow_usage(un, B_FALSE,
4867 gettext("-u, -g, and -e are mutually exclusive\n"));
4869 if (opts->prt_usage) {
4870 if (argc == 0 && all_sum == 0)
4871 allow_usage(un, B_TRUE, NULL);
4872 else
4873 usage(B_FALSE);
4876 if (opts->set) {
4877 if (csuge_sum > 1)
4878 allow_usage(un, B_FALSE,
4879 gettext("invalid options combined with -s\n"));
4881 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4882 if (argv[0][0] != '@')
4883 allow_usage(un, B_FALSE,
4884 gettext("invalid set name: missing '@' prefix\n"));
4885 opts->who = argv[0];
4886 } else if (opts->create) {
4887 if (ldcsuge_sum > 1)
4888 allow_usage(un, B_FALSE,
4889 gettext("invalid options combined with -c\n"));
4890 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4891 } else if (opts->everyone) {
4892 if (csuge_sum > 1)
4893 allow_usage(un, B_FALSE,
4894 gettext("invalid options combined with -e\n"));
4895 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4896 } else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
4897 == 0) {
4898 opts->everyone = B_TRUE;
4899 argc--;
4900 argv++;
4901 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4902 } else if (argc == 1 && !un) {
4903 opts->prt_perms = B_TRUE;
4904 opts->dataset = argv[argc-1];
4905 } else {
4906 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4907 opts->who = argv[0];
4910 if (!opts->local && !opts->descend) {
4911 opts->local = B_TRUE;
4912 opts->descend = B_TRUE;
4916 static void
4917 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
4918 const char *who, char *perms, nvlist_t *top_nvl)
4920 int i;
4921 char ld[2] = { '\0', '\0' };
4922 char who_buf[MAXNAMELEN + 32];
4923 char base_type = '\0';
4924 char set_type = '\0';
4925 nvlist_t *base_nvl = NULL;
4926 nvlist_t *set_nvl = NULL;
4927 nvlist_t *nvl;
4929 if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
4930 nomem();
4931 if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) != 0)
4932 nomem();
4934 switch (type) {
4935 case ZFS_DELEG_NAMED_SET_SETS:
4936 case ZFS_DELEG_NAMED_SET:
4937 set_type = ZFS_DELEG_NAMED_SET_SETS;
4938 base_type = ZFS_DELEG_NAMED_SET;
4939 ld[0] = ZFS_DELEG_NA;
4940 break;
4941 case ZFS_DELEG_CREATE_SETS:
4942 case ZFS_DELEG_CREATE:
4943 set_type = ZFS_DELEG_CREATE_SETS;
4944 base_type = ZFS_DELEG_CREATE;
4945 ld[0] = ZFS_DELEG_NA;
4946 break;
4947 case ZFS_DELEG_USER_SETS:
4948 case ZFS_DELEG_USER:
4949 set_type = ZFS_DELEG_USER_SETS;
4950 base_type = ZFS_DELEG_USER;
4951 if (local)
4952 ld[0] = ZFS_DELEG_LOCAL;
4953 if (descend)
4954 ld[1] = ZFS_DELEG_DESCENDENT;
4955 break;
4956 case ZFS_DELEG_GROUP_SETS:
4957 case ZFS_DELEG_GROUP:
4958 set_type = ZFS_DELEG_GROUP_SETS;
4959 base_type = ZFS_DELEG_GROUP;
4960 if (local)
4961 ld[0] = ZFS_DELEG_LOCAL;
4962 if (descend)
4963 ld[1] = ZFS_DELEG_DESCENDENT;
4964 break;
4965 case ZFS_DELEG_EVERYONE_SETS:
4966 case ZFS_DELEG_EVERYONE:
4967 set_type = ZFS_DELEG_EVERYONE_SETS;
4968 base_type = ZFS_DELEG_EVERYONE;
4969 if (local)
4970 ld[0] = ZFS_DELEG_LOCAL;
4971 if (descend)
4972 ld[1] = ZFS_DELEG_DESCENDENT;
4973 break;
4975 default:
4976 assert(set_type != '\0' && base_type != '\0');
4979 if (perms != NULL) {
4980 char *curr = perms;
4981 char *end = curr + strlen(perms);
4983 while (curr < end) {
4984 char *delim = strchr(curr, ',');
4985 if (delim == NULL)
4986 delim = end;
4987 else
4988 *delim = '\0';
4990 if (curr[0] == '@')
4991 nvl = set_nvl;
4992 else
4993 nvl = base_nvl;
4995 (void) nvlist_add_boolean(nvl, curr);
4996 if (delim != end)
4997 *delim = ',';
4998 curr = delim + 1;
5001 for (i = 0; i < 2; i++) {
5002 char locality = ld[i];
5003 if (locality == 0)
5004 continue;
5006 if (!nvlist_empty(base_nvl)) {
5007 if (who != NULL)
5008 (void) snprintf(who_buf,
5009 sizeof (who_buf), "%c%c$%s",
5010 base_type, locality, who);
5011 else
5012 (void) snprintf(who_buf,
5013 sizeof (who_buf), "%c%c$",
5014 base_type, locality);
5016 (void) nvlist_add_nvlist(top_nvl, who_buf,
5017 base_nvl);
5021 if (!nvlist_empty(set_nvl)) {
5022 if (who != NULL)
5023 (void) snprintf(who_buf,
5024 sizeof (who_buf), "%c%c$%s",
5025 set_type, locality, who);
5026 else
5027 (void) snprintf(who_buf,
5028 sizeof (who_buf), "%c%c$",
5029 set_type, locality);
5031 (void) nvlist_add_nvlist(top_nvl, who_buf,
5032 set_nvl);
5035 } else {
5036 for (i = 0; i < 2; i++) {
5037 char locality = ld[i];
5038 if (locality == 0)
5039 continue;
5041 if (who != NULL)
5042 (void) snprintf(who_buf, sizeof (who_buf),
5043 "%c%c$%s", base_type, locality, who);
5044 else
5045 (void) snprintf(who_buf, sizeof (who_buf),
5046 "%c%c$", base_type, locality);
5047 (void) nvlist_add_boolean(top_nvl, who_buf);
5049 if (who != NULL)
5050 (void) snprintf(who_buf, sizeof (who_buf),
5051 "%c%c$%s", set_type, locality, who);
5052 else
5053 (void) snprintf(who_buf, sizeof (who_buf),
5054 "%c%c$", set_type, locality);
5055 (void) nvlist_add_boolean(top_nvl, who_buf);
5060 static int
5061 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
5063 if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
5064 nomem();
5066 if (opts->set) {
5067 store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
5068 opts->descend, opts->who, opts->perms, *nvlp);
5069 } else if (opts->create) {
5070 store_allow_perm(ZFS_DELEG_CREATE, opts->local,
5071 opts->descend, NULL, opts->perms, *nvlp);
5072 } else if (opts->everyone) {
5073 store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
5074 opts->descend, NULL, opts->perms, *nvlp);
5075 } else {
5076 char *curr = opts->who;
5077 char *end = curr + strlen(curr);
5079 while (curr < end) {
5080 const char *who;
5081 zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
5082 char *endch;
5083 char *delim = strchr(curr, ',');
5084 char errbuf[256];
5085 char id[64];
5086 struct passwd *p = NULL;
5087 struct group *g = NULL;
5089 uid_t rid;
5090 if (delim == NULL)
5091 delim = end;
5092 else
5093 *delim = '\0';
5095 rid = (uid_t)strtol(curr, &endch, 0);
5096 if (opts->user) {
5097 who_type = ZFS_DELEG_USER;
5098 if (*endch != '\0')
5099 p = getpwnam(curr);
5100 else
5101 p = getpwuid(rid);
5103 if (p != NULL)
5104 rid = p->pw_uid;
5105 else {
5106 (void) snprintf(errbuf, 256, gettext(
5107 "invalid user %s"), curr);
5108 allow_usage(un, B_TRUE, errbuf);
5110 } else if (opts->group) {
5111 who_type = ZFS_DELEG_GROUP;
5112 if (*endch != '\0')
5113 g = getgrnam(curr);
5114 else
5115 g = getgrgid(rid);
5117 if (g != NULL)
5118 rid = g->gr_gid;
5119 else {
5120 (void) snprintf(errbuf, 256, gettext(
5121 "invalid group %s"), curr);
5122 allow_usage(un, B_TRUE, errbuf);
5124 } else {
5125 if (*endch != '\0') {
5126 p = getpwnam(curr);
5127 } else {
5128 p = getpwuid(rid);
5131 if (p == NULL) {
5132 if (*endch != '\0') {
5133 g = getgrnam(curr);
5134 } else {
5135 g = getgrgid(rid);
5139 if (p != NULL) {
5140 who_type = ZFS_DELEG_USER;
5141 rid = p->pw_uid;
5142 } else if (g != NULL) {
5143 who_type = ZFS_DELEG_GROUP;
5144 rid = g->gr_gid;
5145 } else {
5146 (void) snprintf(errbuf, 256, gettext(
5147 "invalid user/group %s"), curr);
5148 allow_usage(un, B_TRUE, errbuf);
5152 (void) sprintf(id, "%u", rid);
5153 who = id;
5155 store_allow_perm(who_type, opts->local,
5156 opts->descend, who, opts->perms, *nvlp);
5157 curr = delim + 1;
5161 return (0);
5164 static void
5165 print_set_creat_perms(uu_avl_t *who_avl)
5167 const char *sc_title[] = {
5168 gettext("Permission sets:\n"),
5169 gettext("Create time permissions:\n"),
5170 NULL
5172 const char **title_ptr = sc_title;
5173 who_perm_node_t *who_node = NULL;
5174 int prev_weight = -1;
5176 for (who_node = uu_avl_first(who_avl); who_node != NULL;
5177 who_node = uu_avl_next(who_avl, who_node)) {
5178 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5179 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5180 const char *who_name = who_node->who_perm.who_name;
5181 int weight = who_type2weight(who_type);
5182 boolean_t first = B_TRUE;
5183 deleg_perm_node_t *deleg_node;
5185 if (prev_weight != weight) {
5186 (void) printf(*title_ptr++);
5187 prev_weight = weight;
5190 if (who_name == NULL || strnlen(who_name, 1) == 0)
5191 (void) printf("\t");
5192 else
5193 (void) printf("\t%s ", who_name);
5195 for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
5196 deleg_node = uu_avl_next(avl, deleg_node)) {
5197 if (first) {
5198 (void) printf("%s",
5199 deleg_node->dpn_perm.dp_name);
5200 first = B_FALSE;
5201 } else
5202 (void) printf(",%s",
5203 deleg_node->dpn_perm.dp_name);
5206 (void) printf("\n");
5210 static void
5211 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
5212 const char *title)
5214 who_perm_node_t *who_node = NULL;
5215 boolean_t prt_title = B_TRUE;
5216 uu_avl_walk_t *walk;
5218 if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
5219 nomem();
5221 while ((who_node = uu_avl_walk_next(walk)) != NULL) {
5222 const char *who_name = who_node->who_perm.who_name;
5223 const char *nice_who_name = who_node->who_perm.who_ug_name;
5224 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5225 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5226 char delim = ' ';
5227 deleg_perm_node_t *deleg_node;
5228 boolean_t prt_who = B_TRUE;
5230 for (deleg_node = uu_avl_first(avl);
5231 deleg_node != NULL;
5232 deleg_node = uu_avl_next(avl, deleg_node)) {
5233 if (local != deleg_node->dpn_perm.dp_local ||
5234 descend != deleg_node->dpn_perm.dp_descend)
5235 continue;
5237 if (prt_who) {
5238 const char *who = NULL;
5239 if (prt_title) {
5240 prt_title = B_FALSE;
5241 (void) printf(title);
5244 switch (who_type) {
5245 case ZFS_DELEG_USER_SETS:
5246 case ZFS_DELEG_USER:
5247 who = gettext("user");
5248 if (nice_who_name)
5249 who_name = nice_who_name;
5250 break;
5251 case ZFS_DELEG_GROUP_SETS:
5252 case ZFS_DELEG_GROUP:
5253 who = gettext("group");
5254 if (nice_who_name)
5255 who_name = nice_who_name;
5256 break;
5257 case ZFS_DELEG_EVERYONE_SETS:
5258 case ZFS_DELEG_EVERYONE:
5259 who = gettext("everyone");
5260 who_name = NULL;
5261 break;
5263 default:
5264 assert(who != NULL);
5267 prt_who = B_FALSE;
5268 if (who_name == NULL)
5269 (void) printf("\t%s", who);
5270 else
5271 (void) printf("\t%s %s", who, who_name);
5274 (void) printf("%c%s", delim,
5275 deleg_node->dpn_perm.dp_name);
5276 delim = ',';
5279 if (!prt_who)
5280 (void) printf("\n");
5283 uu_avl_walk_end(walk);
5286 static void
5287 print_fs_perms(fs_perm_set_t *fspset)
5289 fs_perm_node_t *node = NULL;
5290 char buf[MAXNAMELEN + 32];
5291 const char *dsname = buf;
5293 for (node = uu_list_first(fspset->fsps_list); node != NULL;
5294 node = uu_list_next(fspset->fsps_list, node)) {
5295 uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
5296 uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
5297 int left = 0;
5299 (void) snprintf(buf, sizeof (buf),
5300 gettext("---- Permissions on %s "),
5301 node->fspn_fsperm.fsp_name);
5302 (void) printf(dsname);
5303 left = 70 - strlen(buf);
5304 while (left-- > 0)
5305 (void) printf("-");
5306 (void) printf("\n");
5308 print_set_creat_perms(sc_avl);
5309 print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
5310 gettext("Local permissions:\n"));
5311 print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
5312 gettext("Descendent permissions:\n"));
5313 print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
5314 gettext("Local+Descendent permissions:\n"));
5318 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
5320 struct deleg_perms {
5321 boolean_t un;
5322 nvlist_t *nvl;
5325 static int
5326 set_deleg_perms(zfs_handle_t *zhp, void *data)
5328 struct deleg_perms *perms = (struct deleg_perms *)data;
5329 zfs_type_t zfs_type = zfs_get_type(zhp);
5331 if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
5332 return (0);
5334 return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
5337 static int
5338 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
5340 zfs_handle_t *zhp;
5341 nvlist_t *perm_nvl = NULL;
5342 nvlist_t *update_perm_nvl = NULL;
5343 int error = 1;
5344 int c;
5345 struct allow_opts opts = { 0 };
5347 const char *optstr = un ? "ldugecsrh" : "ldugecsh";
5349 /* check opts */
5350 while ((c = getopt(argc, argv, optstr)) != -1) {
5351 switch (c) {
5352 case 'l':
5353 opts.local = B_TRUE;
5354 break;
5355 case 'd':
5356 opts.descend = B_TRUE;
5357 break;
5358 case 'u':
5359 opts.user = B_TRUE;
5360 break;
5361 case 'g':
5362 opts.group = B_TRUE;
5363 break;
5364 case 'e':
5365 opts.everyone = B_TRUE;
5366 break;
5367 case 's':
5368 opts.set = B_TRUE;
5369 break;
5370 case 'c':
5371 opts.create = B_TRUE;
5372 break;
5373 case 'r':
5374 opts.recursive = B_TRUE;
5375 break;
5376 case ':':
5377 (void) fprintf(stderr, gettext("missing argument for "
5378 "'%c' option\n"), optopt);
5379 usage(B_FALSE);
5380 break;
5381 case 'h':
5382 opts.prt_usage = B_TRUE;
5383 break;
5384 case '?':
5385 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5386 optopt);
5387 usage(B_FALSE);
5391 argc -= optind;
5392 argv += optind;
5394 /* check arguments */
5395 parse_allow_args(argc, argv, un, &opts);
5397 /* try to open the dataset */
5398 if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
5399 ZFS_TYPE_VOLUME)) == NULL) {
5400 (void) fprintf(stderr, "Failed to open dataset: %s\n",
5401 opts.dataset);
5402 return (-1);
5405 if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
5406 goto cleanup2;
5408 fs_perm_set_init(&fs_perm_set);
5409 if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
5410 (void) fprintf(stderr, "Failed to parse fsacl permissions\n");
5411 goto cleanup1;
5414 if (opts.prt_perms)
5415 print_fs_perms(&fs_perm_set);
5416 else {
5417 (void) construct_fsacl_list(un, &opts, &update_perm_nvl);
5418 if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
5419 goto cleanup0;
5421 if (un && opts.recursive) {
5422 struct deleg_perms data = { un, update_perm_nvl };
5423 if (zfs_iter_filesystems(zhp, set_deleg_perms,
5424 &data) != 0)
5425 goto cleanup0;
5429 error = 0;
5431 cleanup0:
5432 nvlist_free(perm_nvl);
5433 nvlist_free(update_perm_nvl);
5434 cleanup1:
5435 fs_perm_set_fini(&fs_perm_set);
5436 cleanup2:
5437 zfs_close(zhp);
5439 return (error);
5442 static int
5443 zfs_do_allow(int argc, char **argv)
5445 return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
5448 static int
5449 zfs_do_unallow(int argc, char **argv)
5451 return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
5454 static int
5455 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
5457 int errors = 0;
5458 int i;
5459 const char *tag;
5460 boolean_t recursive = B_FALSE;
5461 const char *opts = holding ? "rt" : "r";
5462 int c;
5464 /* check options */
5465 while ((c = getopt(argc, argv, opts)) != -1) {
5466 switch (c) {
5467 case 'r':
5468 recursive = B_TRUE;
5469 break;
5470 case '?':
5471 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5472 optopt);
5473 usage(B_FALSE);
5477 argc -= optind;
5478 argv += optind;
5480 /* check number of arguments */
5481 if (argc < 2)
5482 usage(B_FALSE);
5484 tag = argv[0];
5485 --argc;
5486 ++argv;
5488 if (holding && tag[0] == '.') {
5489 /* tags starting with '.' are reserved for libzfs */
5490 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
5491 usage(B_FALSE);
5494 for (i = 0; i < argc; ++i) {
5495 zfs_handle_t *zhp;
5496 char parent[ZFS_MAX_DATASET_NAME_LEN];
5497 const char *delim;
5498 char *path = argv[i];
5500 delim = strchr(path, '@');
5501 if (delim == NULL) {
5502 (void) fprintf(stderr,
5503 gettext("'%s' is not a snapshot\n"), path);
5504 ++errors;
5505 continue;
5507 (void) strncpy(parent, path, delim - path);
5508 parent[delim - path] = '\0';
5510 zhp = zfs_open(g_zfs, parent,
5511 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5512 if (zhp == NULL) {
5513 ++errors;
5514 continue;
5516 if (holding) {
5517 if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
5518 ++errors;
5519 } else {
5520 if (zfs_release(zhp, delim+1, tag, recursive) != 0)
5521 ++errors;
5523 zfs_close(zhp);
5526 return (errors != 0);
5530 * zfs hold [-r] [-t] <tag> <snap> ...
5532 * -r Recursively hold
5534 * Apply a user-hold with the given tag to the list of snapshots.
5536 static int
5537 zfs_do_hold(int argc, char **argv)
5539 return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
5543 * zfs release [-r] <tag> <snap> ...
5545 * -r Recursively release
5547 * Release a user-hold with the given tag from the list of snapshots.
5549 static int
5550 zfs_do_release(int argc, char **argv)
5552 return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
5555 typedef struct holds_cbdata {
5556 boolean_t cb_recursive;
5557 const char *cb_snapname;
5558 nvlist_t **cb_nvlp;
5559 size_t cb_max_namelen;
5560 size_t cb_max_taglen;
5561 } holds_cbdata_t;
5563 #define STRFTIME_FMT_STR "%a %b %e %k:%M %Y"
5564 #define DATETIME_BUF_LEN (32)
5568 static void
5569 print_holds(boolean_t scripted, size_t nwidth, size_t tagwidth, nvlist_t *nvl)
5571 int i;
5572 nvpair_t *nvp = NULL;
5573 char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
5574 const char *col;
5576 if (!scripted) {
5577 for (i = 0; i < 3; i++) {
5578 col = gettext(hdr_cols[i]);
5579 if (i < 2)
5580 (void) printf("%-*s ", i ? tagwidth : nwidth,
5581 col);
5582 else
5583 (void) printf("%s\n", col);
5587 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5588 char *zname = nvpair_name(nvp);
5589 nvlist_t *nvl2;
5590 nvpair_t *nvp2 = NULL;
5591 (void) nvpair_value_nvlist(nvp, &nvl2);
5592 while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
5593 char tsbuf[DATETIME_BUF_LEN];
5594 char *tagname = nvpair_name(nvp2);
5595 uint64_t val = 0;
5596 time_t time;
5597 struct tm t;
5598 char sep = scripted ? '\t' : ' ';
5599 size_t sepnum = scripted ? 1 : 2;
5601 (void) nvpair_value_uint64(nvp2, &val);
5602 time = (time_t)val;
5603 (void) localtime_r(&time, &t);
5604 (void) strftime(tsbuf, DATETIME_BUF_LEN,
5605 gettext(STRFTIME_FMT_STR), &t);
5607 (void) printf("%-*s%*c%-*s%*c%s\n", nwidth, zname,
5608 sepnum, sep, tagwidth, tagname, sepnum, sep, tsbuf);
5614 * Generic callback function to list a dataset or snapshot.
5616 static int
5617 holds_callback(zfs_handle_t *zhp, void *data)
5619 holds_cbdata_t *cbp = data;
5620 nvlist_t *top_nvl = *cbp->cb_nvlp;
5621 nvlist_t *nvl = NULL;
5622 nvpair_t *nvp = NULL;
5623 const char *zname = zfs_get_name(zhp);
5624 size_t znamelen = strlen(zname);
5626 if (cbp->cb_recursive) {
5627 const char *snapname;
5628 char *delim = strchr(zname, '@');
5629 if (delim == NULL)
5630 return (0);
5632 snapname = delim + 1;
5633 if (strcmp(cbp->cb_snapname, snapname))
5634 return (0);
5637 if (zfs_get_holds(zhp, &nvl) != 0)
5638 return (-1);
5640 if (znamelen > cbp->cb_max_namelen)
5641 cbp->cb_max_namelen = znamelen;
5643 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5644 const char *tag = nvpair_name(nvp);
5645 size_t taglen = strlen(tag);
5646 if (taglen > cbp->cb_max_taglen)
5647 cbp->cb_max_taglen = taglen;
5650 return (nvlist_add_nvlist(top_nvl, zname, nvl));
5654 * zfs holds [-r] <snap> ...
5656 * -r Recursively hold
5658 static int
5659 zfs_do_holds(int argc, char **argv)
5661 int errors = 0;
5662 int c;
5663 int i;
5664 boolean_t scripted = B_FALSE;
5665 boolean_t recursive = B_FALSE;
5666 const char *opts = "rH";
5667 nvlist_t *nvl;
5669 int types = ZFS_TYPE_SNAPSHOT;
5670 holds_cbdata_t cb = { 0 };
5672 int limit = 0;
5673 int ret = 0;
5674 int flags = 0;
5676 /* check options */
5677 while ((c = getopt(argc, argv, opts)) != -1) {
5678 switch (c) {
5679 case 'r':
5680 recursive = B_TRUE;
5681 break;
5682 case 'H':
5683 scripted = B_TRUE;
5684 break;
5685 case '?':
5686 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5687 optopt);
5688 usage(B_FALSE);
5692 if (recursive) {
5693 types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
5694 flags |= ZFS_ITER_RECURSE;
5697 argc -= optind;
5698 argv += optind;
5700 /* check number of arguments */
5701 if (argc < 1)
5702 usage(B_FALSE);
5704 if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5705 nomem();
5707 for (i = 0; i < argc; ++i) {
5708 char *snapshot = argv[i];
5709 const char *delim;
5710 const char *snapname;
5712 delim = strchr(snapshot, '@');
5713 if (delim == NULL) {
5714 (void) fprintf(stderr,
5715 gettext("'%s' is not a snapshot\n"), snapshot);
5716 ++errors;
5717 continue;
5719 snapname = delim + 1;
5720 if (recursive)
5721 snapshot[delim - snapshot] = '\0';
5723 cb.cb_recursive = recursive;
5724 cb.cb_snapname = snapname;
5725 cb.cb_nvlp = &nvl;
5728 * 1. collect holds data, set format options
5730 ret = zfs_for_each(argc, argv, flags, types, NULL, NULL, limit,
5731 holds_callback, &cb);
5732 if (ret != 0)
5733 ++errors;
5737 * 2. print holds data
5739 print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl);
5741 if (nvlist_empty(nvl))
5742 (void) printf(gettext("no datasets available\n"));
5744 nvlist_free(nvl);
5746 return (0 != errors);
5749 #define CHECK_SPINNER 30
5750 #define SPINNER_TIME 3 /* seconds */
5751 #define MOUNT_TIME 5 /* seconds */
5753 static int
5754 get_one_dataset(zfs_handle_t *zhp, void *data)
5756 static char *spin[] = { "-", "\\", "|", "/" };
5757 static int spinval = 0;
5758 static int spincheck = 0;
5759 static time_t last_spin_time = (time_t)0;
5760 get_all_cb_t *cbp = data;
5761 zfs_type_t type = zfs_get_type(zhp);
5763 if (cbp->cb_verbose) {
5764 if (--spincheck < 0) {
5765 time_t now = time(NULL);
5766 if (last_spin_time + SPINNER_TIME < now) {
5767 update_progress(spin[spinval++ % 4]);
5768 last_spin_time = now;
5770 spincheck = CHECK_SPINNER;
5775 * Interate over any nested datasets.
5777 if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
5778 zfs_close(zhp);
5779 return (1);
5783 * Skip any datasets whose type does not match.
5785 if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
5786 zfs_close(zhp);
5787 return (0);
5789 libzfs_add_handle(cbp, zhp);
5790 assert(cbp->cb_used <= cbp->cb_alloc);
5792 return (0);
5795 static void
5796 get_all_datasets(zfs_handle_t ***dslist, size_t *count, boolean_t verbose)
5798 get_all_cb_t cb = { 0 };
5799 cb.cb_verbose = verbose;
5800 cb.cb_getone = get_one_dataset;
5802 if (verbose)
5803 set_progress_header(gettext("Reading ZFS config"));
5804 (void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
5806 *dslist = cb.cb_handles;
5807 *count = cb.cb_used;
5809 if (verbose)
5810 finish_progress(gettext("done."));
5814 * Generic callback for sharing or mounting filesystems. Because the code is so
5815 * similar, we have a common function with an extra parameter to determine which
5816 * mode we are using.
5818 #define OP_SHARE 0x1
5819 #define OP_MOUNT 0x2
5822 * Share or mount a dataset.
5824 static int
5825 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
5826 boolean_t explicit, const char *options)
5828 char mountpoint[ZFS_MAXPROPLEN];
5829 char shareopts[ZFS_MAXPROPLEN];
5830 char smbshareopts[ZFS_MAXPROPLEN];
5831 const char *cmdname = op == OP_SHARE ? "share" : "mount";
5832 struct mnttab mnt;
5833 uint64_t zoned, canmount;
5834 boolean_t shared_nfs, shared_smb;
5836 assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
5839 * Check to make sure we can mount/share this dataset. If we
5840 * are in the global zone and the filesystem is exported to a
5841 * local zone, or if we are in a local zone and the
5842 * filesystem is not exported, then it is an error.
5844 zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
5846 if (zoned && getzoneid() == GLOBAL_ZONEID) {
5847 if (!explicit)
5848 return (0);
5850 (void) fprintf(stderr, gettext("cannot %s '%s': "
5851 "dataset is exported to a local zone\n"), cmdname,
5852 zfs_get_name(zhp));
5853 return (1);
5855 } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
5856 if (!explicit)
5857 return (0);
5859 (void) fprintf(stderr, gettext("cannot %s '%s': "
5860 "permission denied\n"), cmdname,
5861 zfs_get_name(zhp));
5862 return (1);
5866 * Ignore any filesystems which don't apply to us. This
5867 * includes those with a legacy mountpoint, or those with
5868 * legacy share options.
5870 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
5871 sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
5872 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
5873 sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
5874 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
5875 sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
5877 if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
5878 strcmp(smbshareopts, "off") == 0) {
5879 if (!explicit)
5880 return (0);
5882 (void) fprintf(stderr, gettext("cannot share '%s': "
5883 "legacy share\n"), zfs_get_name(zhp));
5884 (void) fprintf(stderr, gettext("use share(1M) to "
5885 "share this filesystem, or set "
5886 "sharenfs property on\n"));
5887 return (1);
5891 * We cannot share or mount legacy filesystems. If the
5892 * shareopts is non-legacy but the mountpoint is legacy, we
5893 * treat it as a legacy share.
5895 if (strcmp(mountpoint, "legacy") == 0) {
5896 if (!explicit)
5897 return (0);
5899 (void) fprintf(stderr, gettext("cannot %s '%s': "
5900 "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
5901 (void) fprintf(stderr, gettext("use %s(1M) to "
5902 "%s this filesystem\n"), cmdname, cmdname);
5903 return (1);
5906 if (strcmp(mountpoint, "none") == 0) {
5907 if (!explicit)
5908 return (0);
5910 (void) fprintf(stderr, gettext("cannot %s '%s': no "
5911 "mountpoint set\n"), cmdname, zfs_get_name(zhp));
5912 return (1);
5916 * canmount explicit outcome
5917 * on no pass through
5918 * on yes pass through
5919 * off no return 0
5920 * off yes display error, return 1
5921 * noauto no return 0
5922 * noauto yes pass through
5924 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
5925 if (canmount == ZFS_CANMOUNT_OFF) {
5926 if (!explicit)
5927 return (0);
5929 (void) fprintf(stderr, gettext("cannot %s '%s': "
5930 "'canmount' property is set to 'off'\n"), cmdname,
5931 zfs_get_name(zhp));
5932 return (1);
5933 } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
5934 return (0);
5938 * If this filesystem is inconsistent and has a receive resume
5939 * token, we can not mount it.
5941 if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) &&
5942 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
5943 NULL, 0, NULL, NULL, 0, B_TRUE) == 0) {
5944 if (!explicit)
5945 return (0);
5947 (void) fprintf(stderr, gettext("cannot %s '%s': "
5948 "Contains partially-completed state from "
5949 "\"zfs receive -r\", which can be resumed with "
5950 "\"zfs send -t\"\n"),
5951 cmdname, zfs_get_name(zhp));
5952 return (1);
5956 * At this point, we have verified that the mountpoint and/or
5957 * shareopts are appropriate for auto management. If the
5958 * filesystem is already mounted or shared, return (failing
5959 * for explicit requests); otherwise mount or share the
5960 * filesystem.
5962 switch (op) {
5963 case OP_SHARE:
5965 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
5966 shared_smb = zfs_is_shared_smb(zhp, NULL);
5968 if ((shared_nfs && shared_smb) ||
5969 (shared_nfs && strcmp(shareopts, "on") == 0 &&
5970 strcmp(smbshareopts, "off") == 0) ||
5971 (shared_smb && strcmp(smbshareopts, "on") == 0 &&
5972 strcmp(shareopts, "off") == 0)) {
5973 if (!explicit)
5974 return (0);
5976 (void) fprintf(stderr, gettext("cannot share "
5977 "'%s': filesystem already shared\n"),
5978 zfs_get_name(zhp));
5979 return (1);
5982 if (!zfs_is_mounted(zhp, NULL) &&
5983 zfs_mount(zhp, NULL, 0) != 0)
5984 return (1);
5986 if (protocol == NULL) {
5987 if (zfs_shareall(zhp) != 0)
5988 return (1);
5989 } else if (strcmp(protocol, "nfs") == 0) {
5990 if (zfs_share_nfs(zhp))
5991 return (1);
5992 } else if (strcmp(protocol, "smb") == 0) {
5993 if (zfs_share_smb(zhp))
5994 return (1);
5995 } else {
5996 (void) fprintf(stderr, gettext("cannot share "
5997 "'%s': invalid share type '%s' "
5998 "specified\n"),
5999 zfs_get_name(zhp), protocol);
6000 return (1);
6003 break;
6005 case OP_MOUNT:
6006 if (options == NULL)
6007 mnt.mnt_mntopts = "";
6008 else
6009 mnt.mnt_mntopts = (char *)options;
6011 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
6012 zfs_is_mounted(zhp, NULL)) {
6013 if (!explicit)
6014 return (0);
6016 (void) fprintf(stderr, gettext("cannot mount "
6017 "'%s': filesystem already mounted\n"),
6018 zfs_get_name(zhp));
6019 return (1);
6022 if (zfs_mount(zhp, options, flags) != 0)
6023 return (1);
6024 break;
6027 return (0);
6031 * Reports progress in the form "(current/total)". Not thread-safe.
6033 static void
6034 report_mount_progress(int current, int total)
6036 static time_t last_progress_time = 0;
6037 time_t now = time(NULL);
6038 char info[32];
6040 /* report 1..n instead of 0..n-1 */
6041 ++current;
6043 /* display header if we're here for the first time */
6044 if (current == 1) {
6045 set_progress_header(gettext("Mounting ZFS filesystems"));
6046 } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
6047 /* too soon to report again */
6048 return;
6051 last_progress_time = now;
6053 (void) sprintf(info, "(%d/%d)", current, total);
6055 if (current == total)
6056 finish_progress(info);
6057 else
6058 update_progress(info);
6061 static void
6062 append_options(char *mntopts, char *newopts)
6064 int len = strlen(mntopts);
6066 /* original length plus new string to append plus 1 for the comma */
6067 if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
6068 (void) fprintf(stderr, gettext("the opts argument for "
6069 "'%c' option is too long (more than %d chars)\n"),
6070 "-o", MNT_LINE_MAX);
6071 usage(B_FALSE);
6074 if (*mntopts)
6075 mntopts[len++] = ',';
6077 (void) strcpy(&mntopts[len], newopts);
6080 static int
6081 share_mount(int op, int argc, char **argv)
6083 int do_all = 0;
6084 boolean_t verbose = B_FALSE;
6085 int c, ret = 0;
6086 char *options = NULL;
6087 int flags = 0;
6089 /* check options */
6090 while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
6091 != -1) {
6092 switch (c) {
6093 case 'a':
6094 do_all = 1;
6095 break;
6096 case 'v':
6097 verbose = B_TRUE;
6098 break;
6099 case 'o':
6100 if (*optarg == '\0') {
6101 (void) fprintf(stderr, gettext("empty mount "
6102 "options (-o) specified\n"));
6103 usage(B_FALSE);
6106 if (options == NULL)
6107 options = safe_malloc(MNT_LINE_MAX + 1);
6109 /* option validation is done later */
6110 append_options(options, optarg);
6111 break;
6113 case 'O':
6114 flags |= MS_OVERLAY;
6115 break;
6116 case ':':
6117 (void) fprintf(stderr, gettext("missing argument for "
6118 "'%c' option\n"), optopt);
6119 usage(B_FALSE);
6120 break;
6121 case '?':
6122 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6123 optopt);
6124 usage(B_FALSE);
6128 argc -= optind;
6129 argv += optind;
6131 /* check number of arguments */
6132 if (do_all) {
6133 zfs_handle_t **dslist = NULL;
6134 size_t i, count = 0;
6135 char *protocol = NULL;
6137 if (op == OP_SHARE && argc > 0) {
6138 if (strcmp(argv[0], "nfs") != 0 &&
6139 strcmp(argv[0], "smb") != 0) {
6140 (void) fprintf(stderr, gettext("share type "
6141 "must be 'nfs' or 'smb'\n"));
6142 usage(B_FALSE);
6144 protocol = argv[0];
6145 argc--;
6146 argv++;
6149 if (argc != 0) {
6150 (void) fprintf(stderr, gettext("too many arguments\n"));
6151 usage(B_FALSE);
6154 start_progress_timer();
6155 get_all_datasets(&dslist, &count, verbose);
6157 if (count == 0)
6158 return (0);
6160 qsort(dslist, count, sizeof (void *), libzfs_dataset_cmp);
6161 sa_init_selective_arg_t sharearg;
6162 sharearg.zhandle_arr = dslist;
6163 sharearg.zhandle_len = count;
6164 if ((ret = zfs_init_libshare_arg(zfs_get_handle(dslist[0]),
6165 SA_INIT_SHARE_API_SELECTIVE, &sharearg)) != SA_OK) {
6166 (void) fprintf(stderr,
6167 gettext("Could not initialize libshare, %d"), ret);
6168 return (ret);
6171 for (i = 0; i < count; i++) {
6172 if (verbose)
6173 report_mount_progress(i, count);
6175 if (share_mount_one(dslist[i], op, flags, protocol,
6176 B_FALSE, options) != 0)
6177 ret = 1;
6178 zfs_close(dslist[i]);
6181 free(dslist);
6182 } else if (argc == 0) {
6183 struct mnttab entry;
6185 if ((op == OP_SHARE) || (options != NULL)) {
6186 (void) fprintf(stderr, gettext("missing filesystem "
6187 "argument (specify -a for all)\n"));
6188 usage(B_FALSE);
6192 * When mount is given no arguments, go through /etc/mnttab and
6193 * display any active ZFS mounts. We hide any snapshots, since
6194 * they are controlled automatically.
6196 rewind(mnttab_file);
6197 while (getmntent(mnttab_file, &entry) == 0) {
6198 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
6199 strchr(entry.mnt_special, '@') != NULL)
6200 continue;
6202 (void) printf("%-30s %s\n", entry.mnt_special,
6203 entry.mnt_mountp);
6206 } else {
6207 zfs_handle_t *zhp;
6209 if (argc > 1) {
6210 (void) fprintf(stderr,
6211 gettext("too many arguments\n"));
6212 usage(B_FALSE);
6215 if ((zhp = zfs_open(g_zfs, argv[0],
6216 ZFS_TYPE_FILESYSTEM)) == NULL) {
6217 ret = 1;
6218 } else {
6219 ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
6220 options);
6221 zfs_close(zhp);
6225 return (ret);
6229 * zfs mount -a [nfs]
6230 * zfs mount filesystem
6232 * Mount all filesystems, or mount the given filesystem.
6234 static int
6235 zfs_do_mount(int argc, char **argv)
6237 return (share_mount(OP_MOUNT, argc, argv));
6241 * zfs share -a [nfs | smb]
6242 * zfs share filesystem
6244 * Share all filesystems, or share the given filesystem.
6246 static int
6247 zfs_do_share(int argc, char **argv)
6249 return (share_mount(OP_SHARE, argc, argv));
6252 typedef struct unshare_unmount_node {
6253 zfs_handle_t *un_zhp;
6254 char *un_mountp;
6255 uu_avl_node_t un_avlnode;
6256 } unshare_unmount_node_t;
6258 /* ARGSUSED */
6259 static int
6260 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
6262 const unshare_unmount_node_t *l = larg;
6263 const unshare_unmount_node_t *r = rarg;
6265 return (strcmp(l->un_mountp, r->un_mountp));
6269 * Convenience routine used by zfs_do_umount() and manual_unmount(). Given an
6270 * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
6271 * and unmount it appropriately.
6273 static int
6274 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
6276 zfs_handle_t *zhp;
6277 int ret = 0;
6278 struct stat64 statbuf;
6279 struct extmnttab entry;
6280 const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
6281 ino_t path_inode;
6284 * Search for the path in /etc/mnttab. Rather than looking for the
6285 * specific path, which can be fooled by non-standard paths (i.e. ".."
6286 * or "//"), we stat() the path and search for the corresponding
6287 * (major,minor) device pair.
6289 if (stat64(path, &statbuf) != 0) {
6290 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6291 cmdname, path, strerror(errno));
6292 return (1);
6294 path_inode = statbuf.st_ino;
6297 * Search for the given (major,minor) pair in the mount table.
6299 rewind(mnttab_file);
6300 while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
6301 if (entry.mnt_major == major(statbuf.st_dev) &&
6302 entry.mnt_minor == minor(statbuf.st_dev))
6303 break;
6305 if (ret != 0) {
6306 if (op == OP_SHARE) {
6307 (void) fprintf(stderr, gettext("cannot %s '%s': not "
6308 "currently mounted\n"), cmdname, path);
6309 return (1);
6311 (void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
6312 path);
6313 if ((ret = umount2(path, flags)) != 0)
6314 (void) fprintf(stderr, gettext("%s: %s\n"), path,
6315 strerror(errno));
6316 return (ret != 0);
6319 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
6320 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
6321 "filesystem\n"), cmdname, path);
6322 return (1);
6325 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6326 ZFS_TYPE_FILESYSTEM)) == NULL)
6327 return (1);
6329 ret = 1;
6330 if (stat64(entry.mnt_mountp, &statbuf) != 0) {
6331 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6332 cmdname, path, strerror(errno));
6333 goto out;
6334 } else if (statbuf.st_ino != path_inode) {
6335 (void) fprintf(stderr, gettext("cannot "
6336 "%s '%s': not a mountpoint\n"), cmdname, path);
6337 goto out;
6340 if (op == OP_SHARE) {
6341 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6342 char smbshare_prop[ZFS_MAXPROPLEN];
6344 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
6345 sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
6346 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
6347 sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
6349 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6350 strcmp(smbshare_prop, "off") == 0) {
6351 (void) fprintf(stderr, gettext("cannot unshare "
6352 "'%s': legacy share\n"), path);
6353 (void) fprintf(stderr, gettext("use "
6354 "unshare(1M) to unshare this filesystem\n"));
6355 } else if (!zfs_is_shared(zhp)) {
6356 (void) fprintf(stderr, gettext("cannot unshare '%s': "
6357 "not currently shared\n"), path);
6358 } else {
6359 ret = zfs_unshareall_bypath(zhp, path);
6361 } else {
6362 char mtpt_prop[ZFS_MAXPROPLEN];
6364 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
6365 sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
6367 if (is_manual) {
6368 ret = zfs_unmount(zhp, NULL, flags);
6369 } else if (strcmp(mtpt_prop, "legacy") == 0) {
6370 (void) fprintf(stderr, gettext("cannot unmount "
6371 "'%s': legacy mountpoint\n"),
6372 zfs_get_name(zhp));
6373 (void) fprintf(stderr, gettext("use umount(1M) "
6374 "to unmount this filesystem\n"));
6375 } else {
6376 ret = zfs_unmountall(zhp, flags);
6380 out:
6381 zfs_close(zhp);
6383 return (ret != 0);
6387 * Generic callback for unsharing or unmounting a filesystem.
6389 static int
6390 unshare_unmount(int op, int argc, char **argv)
6392 int do_all = 0;
6393 int flags = 0;
6394 int ret = 0;
6395 int c;
6396 zfs_handle_t *zhp;
6397 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6398 char sharesmb[ZFS_MAXPROPLEN];
6400 /* check options */
6401 while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
6402 switch (c) {
6403 case 'a':
6404 do_all = 1;
6405 break;
6406 case 'f':
6407 flags = MS_FORCE;
6408 break;
6409 case '?':
6410 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6411 optopt);
6412 usage(B_FALSE);
6416 argc -= optind;
6417 argv += optind;
6419 if (do_all) {
6421 * We could make use of zfs_for_each() to walk all datasets in
6422 * the system, but this would be very inefficient, especially
6423 * since we would have to linearly search /etc/mnttab for each
6424 * one. Instead, do one pass through /etc/mnttab looking for
6425 * zfs entries and call zfs_unmount() for each one.
6427 * Things get a little tricky if the administrator has created
6428 * mountpoints beneath other ZFS filesystems. In this case, we
6429 * have to unmount the deepest filesystems first. To accomplish
6430 * this, we place all the mountpoints in an AVL tree sorted by
6431 * the special type (dataset name), and walk the result in
6432 * reverse to make sure to get any snapshots first.
6434 struct mnttab entry;
6435 uu_avl_pool_t *pool;
6436 uu_avl_t *tree = NULL;
6437 unshare_unmount_node_t *node;
6438 uu_avl_index_t idx;
6439 uu_avl_walk_t *walk;
6441 if (argc != 0) {
6442 (void) fprintf(stderr, gettext("too many arguments\n"));
6443 usage(B_FALSE);
6446 if (((pool = uu_avl_pool_create("unmount_pool",
6447 sizeof (unshare_unmount_node_t),
6448 offsetof(unshare_unmount_node_t, un_avlnode),
6449 unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
6450 ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
6451 nomem();
6453 rewind(mnttab_file);
6454 while (getmntent(mnttab_file, &entry) == 0) {
6456 /* ignore non-ZFS entries */
6457 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
6458 continue;
6460 /* ignore snapshots */
6461 if (strchr(entry.mnt_special, '@') != NULL)
6462 continue;
6464 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6465 ZFS_TYPE_FILESYSTEM)) == NULL) {
6466 ret = 1;
6467 continue;
6471 * Ignore datasets that are excluded/restricted by
6472 * parent pool name.
6474 if (zpool_skip_pool(zfs_get_pool_name(zhp))) {
6475 zfs_close(zhp);
6476 continue;
6479 switch (op) {
6480 case OP_SHARE:
6481 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6482 nfs_mnt_prop,
6483 sizeof (nfs_mnt_prop),
6484 NULL, NULL, 0, B_FALSE) == 0);
6485 if (strcmp(nfs_mnt_prop, "off") != 0)
6486 break;
6487 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6488 nfs_mnt_prop,
6489 sizeof (nfs_mnt_prop),
6490 NULL, NULL, 0, B_FALSE) == 0);
6491 if (strcmp(nfs_mnt_prop, "off") == 0)
6492 continue;
6493 break;
6494 case OP_MOUNT:
6495 /* Ignore legacy mounts */
6496 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
6497 nfs_mnt_prop,
6498 sizeof (nfs_mnt_prop),
6499 NULL, NULL, 0, B_FALSE) == 0);
6500 if (strcmp(nfs_mnt_prop, "legacy") == 0)
6501 continue;
6502 /* Ignore canmount=noauto mounts */
6503 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
6504 ZFS_CANMOUNT_NOAUTO)
6505 continue;
6506 default:
6507 break;
6510 node = safe_malloc(sizeof (unshare_unmount_node_t));
6511 node->un_zhp = zhp;
6512 node->un_mountp = safe_strdup(entry.mnt_mountp);
6514 uu_avl_node_init(node, &node->un_avlnode, pool);
6516 if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
6517 uu_avl_insert(tree, node, idx);
6518 } else {
6519 zfs_close(node->un_zhp);
6520 free(node->un_mountp);
6521 free(node);
6526 * Walk the AVL tree in reverse, unmounting each filesystem and
6527 * removing it from the AVL tree in the process.
6529 if ((walk = uu_avl_walk_start(tree,
6530 UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
6531 nomem();
6533 while ((node = uu_avl_walk_next(walk)) != NULL) {
6534 uu_avl_remove(tree, node);
6536 switch (op) {
6537 case OP_SHARE:
6538 if (zfs_unshareall_bypath(node->un_zhp,
6539 node->un_mountp) != 0)
6540 ret = 1;
6541 break;
6543 case OP_MOUNT:
6544 if (zfs_unmount(node->un_zhp,
6545 node->un_mountp, flags) != 0)
6546 ret = 1;
6547 break;
6550 zfs_close(node->un_zhp);
6551 free(node->un_mountp);
6552 free(node);
6555 uu_avl_walk_end(walk);
6556 uu_avl_destroy(tree);
6557 uu_avl_pool_destroy(pool);
6559 } else {
6560 if (argc != 1) {
6561 if (argc == 0)
6562 (void) fprintf(stderr,
6563 gettext("missing filesystem argument\n"));
6564 else
6565 (void) fprintf(stderr,
6566 gettext("too many arguments\n"));
6567 usage(B_FALSE);
6571 * We have an argument, but it may be a full path or a ZFS
6572 * filesystem. Pass full paths off to unmount_path() (shared by
6573 * manual_unmount), otherwise open the filesystem and pass to
6574 * zfs_unmount().
6576 if (argv[0][0] == '/')
6577 return (unshare_unmount_path(op, argv[0],
6578 flags, B_FALSE));
6580 if ((zhp = zfs_open(g_zfs, argv[0],
6581 ZFS_TYPE_FILESYSTEM)) == NULL)
6582 return (1);
6584 verify(zfs_prop_get(zhp, op == OP_SHARE ?
6585 ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
6586 nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
6587 NULL, 0, B_FALSE) == 0);
6589 switch (op) {
6590 case OP_SHARE:
6591 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6592 nfs_mnt_prop,
6593 sizeof (nfs_mnt_prop),
6594 NULL, NULL, 0, B_FALSE) == 0);
6595 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6596 sharesmb, sizeof (sharesmb), NULL, NULL,
6597 0, B_FALSE) == 0);
6599 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6600 strcmp(sharesmb, "off") == 0) {
6601 (void) fprintf(stderr, gettext("cannot "
6602 "unshare '%s': legacy share\n"),
6603 zfs_get_name(zhp));
6604 (void) fprintf(stderr, gettext("use "
6605 "unshare(1M) to unshare this "
6606 "filesystem\n"));
6607 ret = 1;
6608 } else if (!zfs_is_shared(zhp)) {
6609 (void) fprintf(stderr, gettext("cannot "
6610 "unshare '%s': not currently "
6611 "shared\n"), zfs_get_name(zhp));
6612 ret = 1;
6613 } else if (zfs_unshareall(zhp) != 0) {
6614 ret = 1;
6616 break;
6618 case OP_MOUNT:
6619 if (strcmp(nfs_mnt_prop, "legacy") == 0) {
6620 (void) fprintf(stderr, gettext("cannot "
6621 "unmount '%s': legacy "
6622 "mountpoint\n"), zfs_get_name(zhp));
6623 (void) fprintf(stderr, gettext("use "
6624 "umount(1M) to unmount this "
6625 "filesystem\n"));
6626 ret = 1;
6627 } else if (!zfs_is_mounted(zhp, NULL)) {
6628 (void) fprintf(stderr, gettext("cannot "
6629 "unmount '%s': not currently "
6630 "mounted\n"),
6631 zfs_get_name(zhp));
6632 ret = 1;
6633 } else if (zfs_unmountall(zhp, flags) != 0) {
6634 ret = 1;
6636 break;
6639 zfs_close(zhp);
6642 return (ret);
6646 * zfs unmount -a
6647 * zfs unmount filesystem
6649 * Unmount all filesystems, or a specific ZFS filesystem.
6651 static int
6652 zfs_do_unmount(int argc, char **argv)
6654 return (unshare_unmount(OP_MOUNT, argc, argv));
6658 * zfs unshare -a
6659 * zfs unshare filesystem
6661 * Unshare all filesystems, or a specific ZFS filesystem.
6663 static int
6664 zfs_do_unshare(int argc, char **argv)
6666 return (unshare_unmount(OP_SHARE, argc, argv));
6670 * Called when invoked as /etc/fs/zfs/mount. Do the mount if the mountpoint is
6671 * 'legacy'. Otherwise, complain that use should be using 'zfs mount'.
6673 static int
6674 manual_mount(int argc, char **argv)
6676 zfs_handle_t *zhp;
6677 char mountpoint[ZFS_MAXPROPLEN];
6678 char mntopts[MNT_LINE_MAX] = { '\0' };
6679 int ret = 0;
6680 int c;
6681 int flags = 0;
6682 char *dataset, *path;
6684 /* check options */
6685 while ((c = getopt(argc, argv, ":mo:O")) != -1) {
6686 switch (c) {
6687 case 'o':
6688 (void) strlcpy(mntopts, optarg, sizeof (mntopts));
6689 break;
6690 case 'O':
6691 flags |= MS_OVERLAY;
6692 break;
6693 case 'm':
6694 flags |= MS_NOMNTTAB;
6695 break;
6696 case ':':
6697 (void) fprintf(stderr, gettext("missing argument for "
6698 "'%c' option\n"), optopt);
6699 usage(B_FALSE);
6700 break;
6701 case '?':
6702 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6703 optopt);
6704 (void) fprintf(stderr, gettext("usage: mount [-o opts] "
6705 "<path>\n"));
6706 return (2);
6710 argc -= optind;
6711 argv += optind;
6713 /* check that we only have two arguments */
6714 if (argc != 2) {
6715 if (argc == 0)
6716 (void) fprintf(stderr, gettext("missing dataset "
6717 "argument\n"));
6718 else if (argc == 1)
6719 (void) fprintf(stderr,
6720 gettext("missing mountpoint argument\n"));
6721 else
6722 (void) fprintf(stderr, gettext("too many arguments\n"));
6723 (void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
6724 return (2);
6727 dataset = argv[0];
6728 path = argv[1];
6730 /* try to open the dataset */
6731 if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
6732 return (1);
6734 (void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
6735 sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
6737 /* check for legacy mountpoint and complain appropriately */
6738 ret = 0;
6739 if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
6740 if (mount(dataset, path, MS_OPTIONSTR | flags, MNTTYPE_ZFS,
6741 NULL, 0, mntopts, sizeof (mntopts)) != 0) {
6742 (void) fprintf(stderr, gettext("mount failed: %s\n"),
6743 strerror(errno));
6744 ret = 1;
6746 } else {
6747 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
6748 "mounted using 'mount -F zfs'\n"), dataset);
6749 (void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
6750 "instead.\n"), path);
6751 (void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
6752 "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
6753 (void) fprintf(stderr, gettext("See zfs(1M) for more "
6754 "information.\n"));
6755 ret = 1;
6758 return (ret);
6762 * Called when invoked as /etc/fs/zfs/umount. Unlike a manual mount, we allow
6763 * unmounts of non-legacy filesystems, as this is the dominant administrative
6764 * interface.
6766 static int
6767 manual_unmount(int argc, char **argv)
6769 int flags = 0;
6770 int c;
6772 /* check options */
6773 while ((c = getopt(argc, argv, "f")) != -1) {
6774 switch (c) {
6775 case 'f':
6776 flags = MS_FORCE;
6777 break;
6778 case '?':
6779 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6780 optopt);
6781 (void) fprintf(stderr, gettext("usage: unmount [-f] "
6782 "<path>\n"));
6783 return (2);
6787 argc -= optind;
6788 argv += optind;
6790 /* check arguments */
6791 if (argc != 1) {
6792 if (argc == 0)
6793 (void) fprintf(stderr, gettext("missing path "
6794 "argument\n"));
6795 else
6796 (void) fprintf(stderr, gettext("too many arguments\n"));
6797 (void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
6798 return (2);
6801 return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
6804 static int
6805 find_command_idx(char *command, int *idx)
6807 int i;
6809 for (i = 0; i < NCOMMAND; i++) {
6810 if (command_table[i].name == NULL)
6811 continue;
6813 if (strcmp(command, command_table[i].name) == 0) {
6814 *idx = i;
6815 return (0);
6818 return (1);
6821 static int
6822 zfs_do_diff(int argc, char **argv)
6824 zfs_handle_t *zhp;
6825 int flags = 0;
6826 char *tosnap = NULL;
6827 char *fromsnap = NULL;
6828 char *atp, *copy;
6829 int err = 0;
6830 int c;
6832 while ((c = getopt(argc, argv, "FHt")) != -1) {
6833 switch (c) {
6834 case 'F':
6835 flags |= ZFS_DIFF_CLASSIFY;
6836 break;
6837 case 'H':
6838 flags |= ZFS_DIFF_PARSEABLE;
6839 break;
6840 case 't':
6841 flags |= ZFS_DIFF_TIMESTAMP;
6842 break;
6843 default:
6844 (void) fprintf(stderr,
6845 gettext("invalid option '%c'\n"), optopt);
6846 usage(B_FALSE);
6850 argc -= optind;
6851 argv += optind;
6853 if (argc < 1) {
6854 (void) fprintf(stderr,
6855 gettext("must provide at least one snapshot name\n"));
6856 usage(B_FALSE);
6859 if (argc > 2) {
6860 (void) fprintf(stderr, gettext("too many arguments\n"));
6861 usage(B_FALSE);
6864 fromsnap = argv[0];
6865 tosnap = (argc == 2) ? argv[1] : NULL;
6867 copy = NULL;
6868 if (*fromsnap != '@')
6869 copy = strdup(fromsnap);
6870 else if (tosnap)
6871 copy = strdup(tosnap);
6872 if (copy == NULL)
6873 usage(B_FALSE);
6875 if ((atp = strchr(copy, '@')) != NULL)
6876 *atp = '\0';
6878 if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
6879 return (1);
6881 free(copy);
6884 * Ignore SIGPIPE so that the library can give us
6885 * information on any failure
6887 (void) sigignore(SIGPIPE);
6889 err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
6891 zfs_close(zhp);
6893 return (err != 0);
6897 * zfs bookmark <fs@snap> <fs#bmark>
6899 * Creates a bookmark with the given name from the given snapshot.
6901 static int
6902 zfs_do_bookmark(int argc, char **argv)
6904 char snapname[ZFS_MAX_DATASET_NAME_LEN];
6905 zfs_handle_t *zhp;
6906 nvlist_t *nvl;
6907 int ret = 0;
6908 int c;
6910 /* check options */
6911 while ((c = getopt(argc, argv, "")) != -1) {
6912 switch (c) {
6913 case '?':
6914 (void) fprintf(stderr,
6915 gettext("invalid option '%c'\n"), optopt);
6916 goto usage;
6920 argc -= optind;
6921 argv += optind;
6923 /* check number of arguments */
6924 if (argc < 1) {
6925 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
6926 goto usage;
6928 if (argc < 2) {
6929 (void) fprintf(stderr, gettext("missing bookmark argument\n"));
6930 goto usage;
6933 if (strchr(argv[1], '#') == NULL) {
6934 (void) fprintf(stderr,
6935 gettext("invalid bookmark name '%s' -- "
6936 "must contain a '#'\n"), argv[1]);
6937 goto usage;
6940 if (argv[0][0] == '@') {
6942 * Snapshot name begins with @.
6943 * Default to same fs as bookmark.
6945 (void) strncpy(snapname, argv[1], sizeof (snapname));
6946 *strchr(snapname, '#') = '\0';
6947 (void) strlcat(snapname, argv[0], sizeof (snapname));
6948 } else {
6949 (void) strncpy(snapname, argv[0], sizeof (snapname));
6951 zhp = zfs_open(g_zfs, snapname, ZFS_TYPE_SNAPSHOT);
6952 if (zhp == NULL)
6953 goto usage;
6954 zfs_close(zhp);
6957 nvl = fnvlist_alloc();
6958 fnvlist_add_string(nvl, argv[1], snapname);
6959 ret = lzc_bookmark(nvl, NULL);
6960 fnvlist_free(nvl);
6962 if (ret != 0) {
6963 const char *err_msg;
6964 char errbuf[1024];
6966 (void) snprintf(errbuf, sizeof (errbuf),
6967 dgettext(TEXT_DOMAIN,
6968 "cannot create bookmark '%s'"), argv[1]);
6970 switch (ret) {
6971 case EXDEV:
6972 err_msg = "bookmark is in a different pool";
6973 break;
6974 case EEXIST:
6975 err_msg = "bookmark exists";
6976 break;
6977 case EINVAL:
6978 err_msg = "invalid argument";
6979 break;
6980 case ENOTSUP:
6981 err_msg = "bookmark feature not enabled";
6982 break;
6983 case ENOSPC:
6984 err_msg = "out of space";
6985 break;
6986 default:
6987 err_msg = "unknown error";
6988 break;
6990 (void) fprintf(stderr, "%s: %s\n", errbuf,
6991 dgettext(TEXT_DOMAIN, err_msg));
6994 return (ret != 0);
6996 usage:
6997 usage(B_FALSE);
6998 return (-1);
7001 static int
7002 zfs_do_channel_program(int argc, char **argv)
7004 int ret, fd;
7005 char c;
7006 char *progbuf, *filename, *poolname;
7007 size_t progsize, progread;
7008 nvlist_t *outnvl;
7009 uint64_t instrlimit = ZCP_DEFAULT_INSTRLIMIT;
7010 uint64_t memlimit = ZCP_DEFAULT_MEMLIMIT;
7011 zpool_handle_t *zhp;
7013 /* check options */
7014 while (-1 !=
7015 (c = getopt(argc, argv, "t:(instr-limit)m:(memory-limit)"))) {
7016 switch (c) {
7017 case 't':
7018 case 'm': {
7019 uint64_t arg;
7020 char *endp;
7022 errno = 0;
7023 arg = strtoull(optarg, &endp, 0);
7024 if (errno != 0 || *endp != '\0') {
7025 (void) fprintf(stderr, gettext(
7026 "invalid argument "
7027 "'%s': expected integer\n"), optarg);
7028 goto usage;
7031 if (c == 't') {
7032 if (arg > ZCP_MAX_INSTRLIMIT || arg == 0) {
7033 (void) fprintf(stderr, gettext(
7034 "Invalid instruction limit: "
7035 "%s\n"), optarg);
7036 return (1);
7037 } else {
7038 instrlimit = arg;
7040 } else {
7041 ASSERT3U(c, ==, 'm');
7042 if (arg > ZCP_MAX_MEMLIMIT || arg == 0) {
7043 (void) fprintf(stderr, gettext(
7044 "Invalid memory limit: "
7045 "%s\n"), optarg);
7046 return (1);
7047 } else {
7048 memlimit = arg;
7051 break;
7053 case '?':
7054 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7055 optopt);
7056 goto usage;
7060 argc -= optind;
7061 argv += optind;
7063 if (argc < 2) {
7064 (void) fprintf(stderr,
7065 gettext("invalid number of arguments\n"));
7066 goto usage;
7069 poolname = argv[0];
7070 filename = argv[1];
7071 if (strcmp(filename, "-") == 0) {
7072 fd = 0;
7073 filename = "standard input";
7074 } else if ((fd = open(filename, O_RDONLY)) < 0) {
7075 (void) fprintf(stderr, gettext("cannot open '%s': %s\n"),
7076 filename, strerror(errno));
7077 return (1);
7080 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
7081 (void) fprintf(stderr, gettext("cannot open pool '%s'"),
7082 poolname);
7083 return (1);
7085 zpool_close(zhp);
7088 * Read in the channel program, expanding the program buffer as
7089 * necessary.
7091 progread = 0;
7092 progsize = 1024;
7093 progbuf = safe_malloc(progsize);
7094 do {
7095 ret = read(fd, progbuf + progread, progsize - progread);
7096 progread += ret;
7097 if (progread == progsize && ret > 0) {
7098 progsize *= 2;
7099 progbuf = safe_realloc(progbuf, progsize);
7101 } while (ret > 0);
7103 if (fd != 0)
7104 (void) close(fd);
7105 if (ret < 0) {
7106 free(progbuf);
7107 (void) fprintf(stderr,
7108 gettext("cannot read '%s': %s\n"),
7109 filename, strerror(errno));
7110 return (1);
7112 progbuf[progread] = '\0';
7115 * Any remaining arguments are passed as arguments to the lua script as
7116 * a string array:
7118 * "argv" -> [ "arg 1", ... "arg n" ],
7121 nvlist_t *argnvl = fnvlist_alloc();
7122 fnvlist_add_string_array(argnvl, ZCP_ARG_CLIARGV, argv + 2, argc - 2);
7124 ret = lzc_channel_program(poolname, progbuf, instrlimit, memlimit,
7125 argnvl, &outnvl);
7127 if (ret != 0) {
7129 * On error, report the error message handed back by lua if one
7130 * exists. Otherwise, generate an appropriate error message,
7131 * falling back on strerror() for an unexpected return code.
7133 char *errstring = NULL;
7134 if (nvlist_exists(outnvl, ZCP_RET_ERROR)) {
7135 (void) nvlist_lookup_string(outnvl,
7136 ZCP_RET_ERROR, &errstring);
7137 if (errstring == NULL)
7138 errstring = strerror(ret);
7139 } else {
7140 switch (ret) {
7141 case EINVAL:
7142 errstring =
7143 "Invalid instruction or memory limit.";
7144 break;
7145 case ENOMEM:
7146 errstring = "Return value too large.";
7147 break;
7148 case ENOSPC:
7149 errstring = "Memory limit exhausted.";
7150 break;
7151 case ETIME:
7152 errstring = "Timed out.";
7153 break;
7154 case EPERM:
7155 errstring = "Permission denied. Channel "
7156 "programs must be run as root.";
7157 break;
7158 default:
7159 errstring = strerror(ret);
7162 (void) fprintf(stderr,
7163 gettext("Channel program execution failed:\n%s\n"),
7164 errstring);
7165 } else {
7166 (void) printf("Channel program fully executed ");
7167 if (nvlist_empty(outnvl)) {
7168 (void) printf("with no return value.\n");
7169 } else {
7170 (void) printf("with return value:\n");
7171 dump_nvlist(outnvl, 4);
7175 free(progbuf);
7176 fnvlist_free(outnvl);
7177 fnvlist_free(argnvl);
7178 return (ret != 0);
7180 usage:
7181 usage(B_FALSE);
7182 return (-1);
7186 main(int argc, char **argv)
7188 int ret = 0;
7189 int i;
7190 char *progname;
7191 char *cmdname;
7193 (void) setlocale(LC_ALL, "");
7194 (void) textdomain(TEXT_DOMAIN);
7196 opterr = 0;
7198 if ((g_zfs = libzfs_init()) == NULL) {
7199 (void) fprintf(stderr, gettext("internal error: failed to "
7200 "initialize ZFS library\n"));
7201 return (1);
7204 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
7206 libzfs_print_on_error(g_zfs, B_TRUE);
7208 if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
7209 (void) fprintf(stderr, gettext("internal error: unable to "
7210 "open %s\n"), MNTTAB);
7211 return (1);
7215 * This command also doubles as the /etc/fs mount and unmount program.
7216 * Determine if we should take this behavior based on argv[0].
7218 progname = basename(argv[0]);
7219 if (strcmp(progname, "mount") == 0) {
7220 ret = manual_mount(argc, argv);
7221 } else if (strcmp(progname, "umount") == 0) {
7222 ret = manual_unmount(argc, argv);
7223 } else {
7225 * Make sure the user has specified some command.
7227 if (argc < 2) {
7228 (void) fprintf(stderr, gettext("missing command\n"));
7229 usage(B_FALSE);
7232 cmdname = argv[1];
7235 * The 'umount' command is an alias for 'unmount'
7237 if (strcmp(cmdname, "umount") == 0)
7238 cmdname = "unmount";
7241 * The 'recv' command is an alias for 'receive'
7243 if (strcmp(cmdname, "recv") == 0)
7244 cmdname = "receive";
7247 * The 'snap' command is an alias for 'snapshot'
7249 if (strcmp(cmdname, "snap") == 0)
7250 cmdname = "snapshot";
7253 * Special case '-?'
7255 if (strcmp(cmdname, "-?") == 0)
7256 usage(B_TRUE);
7259 * Run the appropriate command.
7261 libzfs_mnttab_cache(g_zfs, B_TRUE);
7262 if (find_command_idx(cmdname, &i) == 0) {
7263 current_command = &command_table[i];
7264 ret = command_table[i].func(argc - 1, argv + 1);
7265 } else if (strchr(cmdname, '=') != NULL) {
7266 verify(find_command_idx("set", &i) == 0);
7267 current_command = &command_table[i];
7268 ret = command_table[i].func(argc, argv);
7269 } else {
7270 (void) fprintf(stderr, gettext("unrecognized "
7271 "command '%s'\n"), cmdname);
7272 usage(B_FALSE);
7274 libzfs_mnttab_cache(g_zfs, B_FALSE);
7277 (void) fclose(mnttab_file);
7279 if (ret == 0 && log_history)
7280 (void) zpool_log_history(g_zfs, history_str);
7282 libzfs_fini(g_zfs);
7285 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
7286 * for the purposes of running ::findleaks.
7288 if (getenv("ZFS_ABORT") != NULL) {
7289 (void) printf("dumping core by request\n");
7290 abort();
7293 return (ret);