Merge commit 'b1e7e97d3b60469b243b3b2e22c7d8cbd11c7c90'
[unleashed.git] / usr / src / cmd / zfs / zfs_main.c
blob9438c68555ddaa0f863291d28eb33f0f81c937e4
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.
32 * Copyright (c) 2018 Datto Inc.
35 #include <assert.h>
36 #include <ctype.h>
37 #include <errno.h>
38 #include <getopt.h>
39 #include <libgen.h>
40 #include <libintl.h>
41 #include <libuutil.h>
42 #include <libnvpair.h>
43 #include <locale.h>
44 #include <stddef.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <strings.h>
48 #include <unistd.h>
49 #include <fcntl.h>
50 #include <zone.h>
51 #include <grp.h>
52 #include <pwd.h>
53 #include <signal.h>
54 #include <sys/debug.h>
55 #include <sys/list.h>
56 #include <sys/mkdev.h>
57 #include <sys/mntent.h>
58 #include <sys/mnttab.h>
59 #include <sys/mount.h>
60 #include <sys/stat.h>
61 #include <sys/fs/zfs.h>
62 #include <sys/types.h>
63 #include <time.h>
64 #include <synch.h>
66 #include <libzfs.h>
67 #include <libzfs_core.h>
68 #include <zfs_prop.h>
69 #include <zfs_deleg.h>
70 #include <libuutil.h>
71 #include <aclutils.h>
72 #include <directory.h>
73 #include <idmap.h>
74 #include <libshare.h>
76 #include "zfs_iter.h"
77 #include "zfs_util.h"
78 #include "zfs_comutil.h"
80 libzfs_handle_t *g_zfs;
82 static FILE *mnttab_file;
83 static char history_str[HIS_MAX_RECORD_LEN];
84 static boolean_t log_history = B_TRUE;
86 static int zfs_do_clone(int argc, char **argv);
87 static int zfs_do_create(int argc, char **argv);
88 static int zfs_do_destroy(int argc, char **argv);
89 static int zfs_do_get(int argc, char **argv);
90 static int zfs_do_inherit(int argc, char **argv);
91 static int zfs_do_list(int argc, char **argv);
92 static int zfs_do_mount(int argc, char **argv);
93 static int zfs_do_rename(int argc, char **argv);
94 static int zfs_do_rollback(int argc, char **argv);
95 static int zfs_do_set(int argc, char **argv);
96 static int zfs_do_upgrade(int argc, char **argv);
97 static int zfs_do_snapshot(int argc, char **argv);
98 static int zfs_do_unmount(int argc, char **argv);
99 static int zfs_do_share(int argc, char **argv);
100 static int zfs_do_unshare(int argc, char **argv);
101 static int zfs_do_send(int argc, char **argv);
102 static int zfs_do_receive(int argc, char **argv);
103 static int zfs_do_promote(int argc, char **argv);
104 static int zfs_do_userspace(int argc, char **argv);
105 static int zfs_do_allow(int argc, char **argv);
106 static int zfs_do_unallow(int argc, char **argv);
107 static int zfs_do_hold(int argc, char **argv);
108 static int zfs_do_holds(int argc, char **argv);
109 static int zfs_do_release(int argc, char **argv);
110 static int zfs_do_diff(int argc, char **argv);
111 static int zfs_do_bookmark(int argc, char **argv);
112 static int zfs_do_remap(int argc, char **argv);
113 static int zfs_do_channel_program(int argc, char **argv);
116 * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
119 #ifdef DEBUG
120 const char *
121 _umem_debug_init(void)
123 return ("default,verbose"); /* $UMEM_DEBUG setting */
126 const char *
127 _umem_logging_init(void)
129 return ("fail,contents"); /* $UMEM_LOGGING setting */
131 #endif
133 typedef enum {
134 HELP_CLONE,
135 HELP_CREATE,
136 HELP_DESTROY,
137 HELP_GET,
138 HELP_INHERIT,
139 HELP_UPGRADE,
140 HELP_LIST,
141 HELP_MOUNT,
142 HELP_PROMOTE,
143 HELP_RECEIVE,
144 HELP_RENAME,
145 HELP_ROLLBACK,
146 HELP_SEND,
147 HELP_SET,
148 HELP_SHARE,
149 HELP_SNAPSHOT,
150 HELP_UNMOUNT,
151 HELP_UNSHARE,
152 HELP_ALLOW,
153 HELP_UNALLOW,
154 HELP_USERSPACE,
155 HELP_GROUPSPACE,
156 HELP_HOLD,
157 HELP_HOLDS,
158 HELP_RELEASE,
159 HELP_DIFF,
160 HELP_REMAP,
161 HELP_BOOKMARK,
162 HELP_CHANNEL_PROGRAM,
163 } zfs_help_t;
165 typedef struct zfs_command {
166 const char *name;
167 int (*func)(int argc, char **argv);
168 zfs_help_t usage;
169 } zfs_command_t;
172 * Master command table. Each ZFS command has a name, associated function, and
173 * usage message. The usage messages need to be internationalized, so we have
174 * to have a function to return the usage message based on a command index.
176 * These commands are organized according to how they are displayed in the usage
177 * message. An empty command (one with a NULL name) indicates an empty line in
178 * the generic usage message.
180 static zfs_command_t command_table[] = {
181 { "create", zfs_do_create, HELP_CREATE },
182 { "destroy", zfs_do_destroy, HELP_DESTROY },
183 { NULL },
184 { "snapshot", zfs_do_snapshot, HELP_SNAPSHOT },
185 { "rollback", zfs_do_rollback, HELP_ROLLBACK },
186 { "clone", zfs_do_clone, HELP_CLONE },
187 { "promote", zfs_do_promote, HELP_PROMOTE },
188 { "rename", zfs_do_rename, HELP_RENAME },
189 { "bookmark", zfs_do_bookmark, HELP_BOOKMARK },
190 { "program", zfs_do_channel_program, HELP_CHANNEL_PROGRAM },
191 { NULL },
192 { "list", zfs_do_list, HELP_LIST },
193 { NULL },
194 { "set", zfs_do_set, HELP_SET },
195 { "get", zfs_do_get, HELP_GET },
196 { "inherit", zfs_do_inherit, HELP_INHERIT },
197 { "upgrade", zfs_do_upgrade, HELP_UPGRADE },
198 { "userspace", zfs_do_userspace, HELP_USERSPACE },
199 { "groupspace", zfs_do_userspace, HELP_GROUPSPACE },
200 { NULL },
201 { "mount", zfs_do_mount, HELP_MOUNT },
202 { "unmount", zfs_do_unmount, HELP_UNMOUNT },
203 { "share", zfs_do_share, HELP_SHARE },
204 { "unshare", zfs_do_unshare, HELP_UNSHARE },
205 { NULL },
206 { "send", zfs_do_send, HELP_SEND },
207 { "receive", zfs_do_receive, HELP_RECEIVE },
208 { NULL },
209 { "allow", zfs_do_allow, HELP_ALLOW },
210 { NULL },
211 { "unallow", zfs_do_unallow, HELP_UNALLOW },
212 { NULL },
213 { "hold", zfs_do_hold, HELP_HOLD },
214 { "holds", zfs_do_holds, HELP_HOLDS },
215 { "release", zfs_do_release, HELP_RELEASE },
216 { "diff", zfs_do_diff, HELP_DIFF },
217 { "remap", zfs_do_remap, HELP_REMAP },
220 #define NCOMMAND (sizeof (command_table) / sizeof (command_table[0]))
222 zfs_command_t *current_command;
224 static const char *
225 get_usage(zfs_help_t idx)
227 switch (idx) {
228 case HELP_CLONE:
229 return (gettext("\tclone [-p] [-o property=value] ... "
230 "<snapshot> <filesystem|volume>\n"));
231 case HELP_CREATE:
232 return (gettext("\tcreate [-p] [-o property=value] ... "
233 "<filesystem>\n"
234 "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
235 "-V <size> <volume>\n"));
236 case HELP_DESTROY:
237 return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
238 "\tdestroy [-dnpRrv] "
239 "<filesystem|volume>@<snap>[%<snap>][,...]\n"
240 "\tdestroy <filesystem|volume>#<bookmark>\n"));
241 case HELP_GET:
242 return (gettext("\tget [-rHp] [-d max] "
243 "[-o \"all\" | field[,...]]\n"
244 "\t [-t type[,...]] [-s source[,...]]\n"
245 "\t <\"all\" | property[,...]> "
246 "[filesystem|volume|snapshot|bookmark] ...\n"));
247 case HELP_INHERIT:
248 return (gettext("\tinherit [-rS] <property> "
249 "<filesystem|volume|snapshot> ...\n"));
250 case HELP_UPGRADE:
251 return (gettext("\tupgrade [-v]\n"
252 "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
253 case HELP_LIST:
254 return (gettext("\tlist [-Hp] [-r|-d max] [-o property[,...]] "
255 "[-s property]...\n\t [-S property]... [-t type[,...]] "
256 "[filesystem|volume|snapshot] ...\n"));
257 case HELP_MOUNT:
258 return (gettext("\tmount\n"
259 "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
260 case HELP_PROMOTE:
261 return (gettext("\tpromote <clone-filesystem>\n"));
262 case HELP_RECEIVE:
263 return (gettext("\treceive [-vnsFu] <filesystem|volume|"
264 "snapshot>\n"
265 "\treceive [-vnsFu] [-o origin=<snapshot>] [-d | -e] "
266 "<filesystem>\n"
267 "\treceive -A <filesystem|volume>\n"));
268 case HELP_RENAME:
269 return (gettext("\trename [-f] <filesystem|volume|snapshot> "
270 "<filesystem|volume|snapshot>\n"
271 "\trename [-f] -p <filesystem|volume> <filesystem|volume>\n"
272 "\trename -r <snapshot> <snapshot>\n"));
273 case HELP_ROLLBACK:
274 return (gettext("\trollback [-rRf] <snapshot>\n"));
275 case HELP_SEND:
276 return (gettext("\tsend [-DnPpRvLec] [-[iI] snapshot] "
277 "<snapshot>\n"
278 "\tsend [-Le] [-i snapshot|bookmark] "
279 "<filesystem|volume|snapshot>\n"
280 "\tsend [-nvPe] -t <receive_resume_token>\n"));
281 case HELP_SET:
282 return (gettext("\tset <property=value> ... "
283 "<filesystem|volume|snapshot> ...\n"));
284 case HELP_SHARE:
285 return (gettext("\tshare <-a | filesystem>\n"));
286 case HELP_SNAPSHOT:
287 return (gettext("\tsnapshot [-r] [-o property=value] ... "
288 "<filesystem|volume>@<snap> ...\n"));
289 case HELP_UNMOUNT:
290 return (gettext("\tunmount [-f] "
291 "<-a | filesystem|mountpoint>\n"));
292 case HELP_UNSHARE:
293 return (gettext("\tunshare "
294 "<-a | filesystem|mountpoint>\n"));
295 case HELP_ALLOW:
296 return (gettext("\tallow <filesystem|volume>\n"
297 "\tallow [-ldug] "
298 "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
299 "\t <filesystem|volume>\n"
300 "\tallow [-ld] -e <perm|@setname>[,...] "
301 "<filesystem|volume>\n"
302 "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
303 "\tallow -s @setname <perm|@setname>[,...] "
304 "<filesystem|volume>\n"));
305 case HELP_UNALLOW:
306 return (gettext("\tunallow [-rldug] "
307 "<\"everyone\"|user|group>[,...]\n"
308 "\t [<perm|@setname>[,...]] <filesystem|volume>\n"
309 "\tunallow [-rld] -e [<perm|@setname>[,...]] "
310 "<filesystem|volume>\n"
311 "\tunallow [-r] -c [<perm|@setname>[,...]] "
312 "<filesystem|volume>\n"
313 "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
314 "<filesystem|volume>\n"));
315 case HELP_USERSPACE:
316 return (gettext("\tuserspace [-Hinp] [-o field[,...]] "
317 "[-s field] ...\n"
318 "\t [-S field] ... [-t type[,...]] "
319 "<filesystem|snapshot>\n"));
320 case HELP_GROUPSPACE:
321 return (gettext("\tgroupspace [-Hinp] [-o field[,...]] "
322 "[-s field] ...\n"
323 "\t [-S field] ... [-t type[,...]] "
324 "<filesystem|snapshot>\n"));
325 case HELP_HOLD:
326 return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
327 case HELP_HOLDS:
328 return (gettext("\tholds [-r] <snapshot> ...\n"));
329 case HELP_RELEASE:
330 return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
331 case HELP_DIFF:
332 return (gettext("\tdiff [-FHt] <snapshot> "
333 "[snapshot|filesystem]\n"));
334 case HELP_REMAP:
335 return (gettext("\tremap <filesystem | volume>\n"));
336 case HELP_BOOKMARK:
337 return (gettext("\tbookmark <snapshot> <bookmark>\n"));
338 case HELP_CHANNEL_PROGRAM:
339 return (gettext("\tprogram [-jn] [-t <instruction limit>] "
340 "[-m <memory limit (b)>] <pool> <program file> "
341 "[lua args...]\n"));
344 abort();
345 /* NOTREACHED */
348 void
349 nomem(void)
351 (void) fprintf(stderr, gettext("internal error: out of memory\n"));
352 exit(1);
356 * Utility function to guarantee malloc() success.
359 void *
360 safe_malloc(size_t size)
362 void *data;
364 if ((data = calloc(1, size)) == NULL)
365 nomem();
367 return (data);
370 void *
371 safe_realloc(void *data, size_t size)
373 void *newp;
374 if ((newp = realloc(data, size)) == NULL) {
375 free(data);
376 nomem();
379 return (newp);
382 static char *
383 safe_strdup(char *str)
385 char *dupstr = strdup(str);
387 if (dupstr == NULL)
388 nomem();
390 return (dupstr);
394 * Callback routine that will print out information for each of
395 * the properties.
397 static int
398 usage_prop_cb(int prop, void *cb)
400 FILE *fp = cb;
402 (void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
404 if (zfs_prop_readonly(prop))
405 (void) fprintf(fp, " NO ");
406 else
407 (void) fprintf(fp, "YES ");
409 if (zfs_prop_inheritable(prop))
410 (void) fprintf(fp, " YES ");
411 else
412 (void) fprintf(fp, " NO ");
414 if (zfs_prop_values(prop) == NULL)
415 (void) fprintf(fp, "-\n");
416 else
417 (void) fprintf(fp, "%s\n", zfs_prop_values(prop));
419 return (ZPROP_CONT);
423 * Display usage message. If we're inside a command, display only the usage for
424 * that command. Otherwise, iterate over the entire command table and display
425 * a complete usage message.
427 static void
428 usage(boolean_t requested)
430 int i;
431 boolean_t show_properties = B_FALSE;
432 FILE *fp = requested ? stdout : stderr;
434 if (current_command == NULL) {
436 (void) fprintf(fp, gettext("usage: zfs command args ...\n"));
437 (void) fprintf(fp,
438 gettext("where 'command' is one of the following:\n\n"));
440 for (i = 0; i < NCOMMAND; i++) {
441 if (command_table[i].name == NULL)
442 (void) fprintf(fp, "\n");
443 else
444 (void) fprintf(fp, "%s",
445 get_usage(command_table[i].usage));
448 (void) fprintf(fp, gettext("\nEach dataset is of the form: "
449 "pool/[dataset/]*dataset[@name]\n"));
450 } else {
451 (void) fprintf(fp, gettext("usage:\n"));
452 (void) fprintf(fp, "%s", get_usage(current_command->usage));
455 if (current_command != NULL &&
456 (strcmp(current_command->name, "set") == 0 ||
457 strcmp(current_command->name, "get") == 0 ||
458 strcmp(current_command->name, "inherit") == 0 ||
459 strcmp(current_command->name, "list") == 0))
460 show_properties = B_TRUE;
462 if (show_properties) {
463 (void) fprintf(fp,
464 gettext("\nThe following properties are supported:\n"));
466 (void) fprintf(fp, "\n\t%-14s %s %s %s\n\n",
467 "PROPERTY", "EDIT", "INHERIT", "VALUES");
469 /* Iterate over all properties */
470 (void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
471 ZFS_TYPE_DATASET);
473 (void) fprintf(fp, "\t%-15s ", "userused@...");
474 (void) fprintf(fp, " NO NO <size>\n");
475 (void) fprintf(fp, "\t%-15s ", "groupused@...");
476 (void) fprintf(fp, " NO NO <size>\n");
477 (void) fprintf(fp, "\t%-15s ", "userquota@...");
478 (void) fprintf(fp, "YES NO <size> | none\n");
479 (void) fprintf(fp, "\t%-15s ", "groupquota@...");
480 (void) fprintf(fp, "YES NO <size> | none\n");
481 (void) fprintf(fp, "\t%-15s ", "written@<snap>");
482 (void) fprintf(fp, " NO NO <size>\n");
484 (void) fprintf(fp, gettext("\nSizes are specified in bytes "
485 "with standard units such as K, M, G, etc.\n"));
486 (void) fprintf(fp, gettext("\nUser-defined properties can "
487 "be specified by using a name containing a colon (:).\n"));
488 (void) fprintf(fp, gettext("\nThe {user|group}{used|quota}@ "
489 "properties must be appended with\n"
490 "a user or group specifier of one of these forms:\n"
491 " POSIX name (eg: \"matt\")\n"
492 " POSIX id (eg: \"126829\")\n"
493 " SMB name@domain (eg: \"matt@sun\")\n"
494 " SMB SID (eg: \"S-1-234-567-89\")\n"));
495 } else {
496 (void) fprintf(fp,
497 gettext("\nFor the property list, run: %s\n"),
498 "zfs set|get");
499 (void) fprintf(fp,
500 gettext("\nFor the delegated permission list, run: %s\n"),
501 "zfs allow|unallow");
505 * See comments at end of main().
507 if (getenv("ZFS_ABORT") != NULL) {
508 (void) printf("dumping core by request\n");
509 abort();
512 exit(requested ? 0 : 2);
516 * Take a property=value argument string and add it to the given nvlist.
517 * Modifies the argument inplace.
519 static int
520 parseprop(nvlist_t *props, char *propname)
522 char *propval, *strval;
524 if ((propval = strchr(propname, '=')) == NULL) {
525 (void) fprintf(stderr, gettext("missing "
526 "'=' for property=value argument\n"));
527 return (-1);
529 *propval = '\0';
530 propval++;
531 if (nvlist_lookup_string(props, propname, &strval) == 0) {
532 (void) fprintf(stderr, gettext("property '%s' "
533 "specified multiple times\n"), propname);
534 return (-1);
536 if (nvlist_add_string(props, propname, propval) != 0)
537 nomem();
538 return (0);
541 static int
542 parse_depth(char *opt, int *flags)
544 char *tmp;
545 int depth;
547 depth = (int)strtol(opt, &tmp, 0);
548 if (*tmp) {
549 (void) fprintf(stderr,
550 gettext("%s is not an integer\n"), optarg);
551 usage(B_FALSE);
553 if (depth < 0) {
554 (void) fprintf(stderr,
555 gettext("Depth can not be negative.\n"));
556 usage(B_FALSE);
558 *flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
559 return (depth);
562 #define PROGRESS_DELAY 2 /* seconds */
564 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";
565 static time_t pt_begin;
566 static char *pt_header = NULL;
567 static boolean_t pt_shown;
569 static void
570 start_progress_timer(void)
572 pt_begin = time(NULL) + PROGRESS_DELAY;
573 pt_shown = B_FALSE;
576 static void
577 set_progress_header(char *header)
579 assert(pt_header == NULL);
580 pt_header = safe_strdup(header);
581 if (pt_shown) {
582 (void) printf("%s: ", header);
583 (void) fflush(stdout);
587 static void
588 update_progress(char *update)
590 if (!pt_shown && time(NULL) > pt_begin) {
591 int len = strlen(update);
593 (void) printf("%s: %s%*.*s", pt_header, update, len, len,
594 pt_reverse);
595 (void) fflush(stdout);
596 pt_shown = B_TRUE;
597 } else if (pt_shown) {
598 int len = strlen(update);
600 (void) printf("%s%*.*s", update, len, len, pt_reverse);
601 (void) fflush(stdout);
605 static void
606 finish_progress(char *done)
608 if (pt_shown) {
609 (void) printf("%s\n", done);
610 (void) fflush(stdout);
612 free(pt_header);
613 pt_header = NULL;
617 * Check if the dataset is mountable and should be automatically mounted.
619 static boolean_t
620 should_auto_mount(zfs_handle_t *zhp)
622 if (!zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, zfs_get_type(zhp)))
623 return (B_FALSE);
624 return (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_ON);
628 * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
630 * Given an existing dataset, create a writable copy whose initial contents
631 * are the same as the source. The newly created dataset maintains a
632 * dependency on the original; the original cannot be destroyed so long as
633 * the clone exists.
635 * The '-p' flag creates all the non-existing ancestors of the target first.
637 static int
638 zfs_do_clone(int argc, char **argv)
640 zfs_handle_t *zhp = NULL;
641 boolean_t parents = B_FALSE;
642 nvlist_t *props;
643 int ret = 0;
644 int c;
646 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
647 nomem();
649 /* check options */
650 while ((c = getopt(argc, argv, "o:p")) != -1) {
651 switch (c) {
652 case 'o':
653 if (parseprop(props, optarg) != 0)
654 return (1);
655 break;
656 case 'p':
657 parents = B_TRUE;
658 break;
659 case '?':
660 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
661 optopt);
662 goto usage;
666 argc -= optind;
667 argv += optind;
669 /* check number of arguments */
670 if (argc < 1) {
671 (void) fprintf(stderr, gettext("missing source dataset "
672 "argument\n"));
673 goto usage;
675 if (argc < 2) {
676 (void) fprintf(stderr, gettext("missing target dataset "
677 "argument\n"));
678 goto usage;
680 if (argc > 2) {
681 (void) fprintf(stderr, gettext("too many arguments\n"));
682 goto usage;
685 /* open the source dataset */
686 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
687 return (1);
689 if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
690 ZFS_TYPE_VOLUME)) {
692 * Now create the ancestors of the target dataset. If the
693 * target already exists and '-p' option was used we should not
694 * complain.
696 if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
697 ZFS_TYPE_VOLUME))
698 return (0);
699 if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
700 return (1);
703 /* pass to libzfs */
704 ret = zfs_clone(zhp, argv[1], props);
706 /* create the mountpoint if necessary */
707 if (ret == 0) {
708 zfs_handle_t *clone;
710 clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
711 if (clone != NULL) {
713 * If the user doesn't want the dataset
714 * automatically mounted, then skip the mount/share
715 * step.
717 if (should_auto_mount(clone)) {
718 if ((ret = zfs_mount(clone, NULL, 0)) != 0) {
719 (void) fprintf(stderr, gettext("clone "
720 "successfully created, "
721 "but not mounted\n"));
722 } else if ((ret = zfs_share(clone)) != 0) {
723 (void) fprintf(stderr, gettext("clone "
724 "successfully created, "
725 "but not shared\n"));
728 zfs_close(clone);
732 zfs_close(zhp);
733 nvlist_free(props);
735 return (!!ret);
737 usage:
738 if (zhp)
739 zfs_close(zhp);
740 nvlist_free(props);
741 usage(B_FALSE);
742 return (-1);
746 * zfs create [-p] [-o prop=value] ... fs
747 * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
749 * Create a new dataset. This command can be used to create filesystems
750 * and volumes. Snapshot creation is handled by 'zfs snapshot'.
751 * For volumes, the user must specify a size to be used.
753 * The '-s' flag applies only to volumes, and indicates that we should not try
754 * to set the reservation for this volume. By default we set a reservation
755 * equal to the size for any volume. For pools with SPA_VERSION >=
756 * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
758 * The '-p' flag creates all the non-existing ancestors of the target first.
760 static int
761 zfs_do_create(int argc, char **argv)
763 zfs_type_t type = ZFS_TYPE_FILESYSTEM;
764 zfs_handle_t *zhp = NULL;
765 uint64_t volsize = 0;
766 int c;
767 boolean_t noreserve = B_FALSE;
768 boolean_t bflag = B_FALSE;
769 boolean_t parents = B_FALSE;
770 int ret = 1;
771 nvlist_t *props;
772 uint64_t intval;
774 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
775 nomem();
777 /* check options */
778 while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
779 switch (c) {
780 case 'V':
781 type = ZFS_TYPE_VOLUME;
782 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
783 (void) fprintf(stderr, gettext("bad volume "
784 "size '%s': %s\n"), optarg,
785 libzfs_error_description(g_zfs));
786 goto error;
789 if (nvlist_add_uint64(props,
790 zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
791 nomem();
792 volsize = intval;
793 break;
794 case 'p':
795 parents = B_TRUE;
796 break;
797 case 'b':
798 bflag = B_TRUE;
799 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
800 (void) fprintf(stderr, gettext("bad volume "
801 "block size '%s': %s\n"), optarg,
802 libzfs_error_description(g_zfs));
803 goto error;
806 if (nvlist_add_uint64(props,
807 zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
808 intval) != 0)
809 nomem();
810 break;
811 case 'o':
812 if (parseprop(props, optarg) != 0)
813 goto error;
814 break;
815 case 's':
816 noreserve = B_TRUE;
817 break;
818 case ':':
819 (void) fprintf(stderr, gettext("missing size "
820 "argument\n"));
821 goto badusage;
822 case '?':
823 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
824 optopt);
825 goto badusage;
829 if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
830 (void) fprintf(stderr, gettext("'-s' and '-b' can only be "
831 "used when creating a volume\n"));
832 goto badusage;
835 argc -= optind;
836 argv += optind;
838 /* check number of arguments */
839 if (argc == 0) {
840 (void) fprintf(stderr, gettext("missing %s argument\n"),
841 zfs_type_to_name(type));
842 goto badusage;
844 if (argc > 1) {
845 (void) fprintf(stderr, gettext("too many arguments\n"));
846 goto badusage;
849 if (type == ZFS_TYPE_VOLUME && !noreserve) {
850 zpool_handle_t *zpool_handle;
851 nvlist_t *real_props = NULL;
852 uint64_t spa_version;
853 char *p;
854 zfs_prop_t resv_prop;
855 char *strval;
856 char msg[1024];
858 if ((p = strchr(argv[0], '/')) != NULL)
859 *p = '\0';
860 zpool_handle = zpool_open(g_zfs, argv[0]);
861 if (p != NULL)
862 *p = '/';
863 if (zpool_handle == NULL)
864 goto error;
865 spa_version = zpool_get_prop_int(zpool_handle,
866 ZPOOL_PROP_VERSION, NULL);
867 if (spa_version >= SPA_VERSION_REFRESERVATION)
868 resv_prop = ZFS_PROP_REFRESERVATION;
869 else
870 resv_prop = ZFS_PROP_RESERVATION;
872 (void) snprintf(msg, sizeof (msg),
873 gettext("cannot create '%s'"), argv[0]);
874 if (props && (real_props = zfs_valid_proplist(g_zfs, type,
875 props, 0, NULL, zpool_handle, msg)) == NULL) {
876 zpool_close(zpool_handle);
877 goto error;
879 zpool_close(zpool_handle);
881 volsize = zvol_volsize_to_reservation(volsize, real_props);
882 nvlist_free(real_props);
884 if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
885 &strval) != 0) {
886 if (nvlist_add_uint64(props,
887 zfs_prop_to_name(resv_prop), volsize) != 0) {
888 nvlist_free(props);
889 nomem();
894 if (parents && zfs_name_valid(argv[0], type)) {
896 * Now create the ancestors of target dataset. If the target
897 * already exists and '-p' option was used we should not
898 * complain.
900 if (zfs_dataset_exists(g_zfs, argv[0], type)) {
901 ret = 0;
902 goto error;
904 if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
905 goto error;
908 /* pass to libzfs */
909 if (zfs_create(g_zfs, argv[0], type, props) != 0)
910 goto error;
912 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
913 goto error;
915 ret = 0;
918 * Mount and/or share the new filesystem as appropriate. We provide a
919 * verbose error message to let the user know that their filesystem was
920 * in fact created, even if we failed to mount or share it.
921 * If the user doesn't want the dataset automatically mounted,
922 * then skip the mount/share step altogether.
924 if (should_auto_mount(zhp)) {
925 if (zfs_mount(zhp, NULL, 0) != 0) {
926 (void) fprintf(stderr, gettext("filesystem "
927 "successfully created, but not mounted\n"));
928 ret = 1;
929 } else if (zfs_share(zhp) != 0) {
930 (void) fprintf(stderr, gettext("filesystem "
931 "successfully created, but not shared\n"));
932 ret = 1;
936 error:
937 if (zhp)
938 zfs_close(zhp);
939 nvlist_free(props);
940 return (ret);
941 badusage:
942 nvlist_free(props);
943 usage(B_FALSE);
944 return (2);
948 * zfs destroy [-rRf] <fs, vol>
949 * zfs destroy [-rRd] <snap>
951 * -r Recursively destroy all children
952 * -R Recursively destroy all dependents, including clones
953 * -f Force unmounting of any dependents
954 * -d If we can't destroy now, mark for deferred destruction
956 * Destroys the given dataset. By default, it will unmount any filesystems,
957 * and refuse to destroy a dataset that has any dependents. A dependent can
958 * either be a child, or a clone of a child.
960 typedef struct destroy_cbdata {
961 boolean_t cb_first;
962 boolean_t cb_force;
963 boolean_t cb_recurse;
964 boolean_t cb_error;
965 boolean_t cb_doclones;
966 zfs_handle_t *cb_target;
967 boolean_t cb_defer_destroy;
968 boolean_t cb_verbose;
969 boolean_t cb_parsable;
970 boolean_t cb_dryrun;
971 nvlist_t *cb_nvl;
972 nvlist_t *cb_batchedsnaps;
974 /* first snap in contiguous run */
975 char *cb_firstsnap;
976 /* previous snap in contiguous run */
977 char *cb_prevsnap;
978 int64_t cb_snapused;
979 char *cb_snapspec;
980 char *cb_bookmark;
981 } destroy_cbdata_t;
984 * Check for any dependents based on the '-r' or '-R' flags.
986 static int
987 destroy_check_dependent(zfs_handle_t *zhp, void *data)
989 destroy_cbdata_t *cbp = data;
990 const char *tname = zfs_get_name(cbp->cb_target);
991 const char *name = zfs_get_name(zhp);
993 if (strncmp(tname, name, strlen(tname)) == 0 &&
994 (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
996 * This is a direct descendant, not a clone somewhere else in
997 * the hierarchy.
999 if (cbp->cb_recurse)
1000 goto out;
1002 if (cbp->cb_first) {
1003 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1004 "%s has children\n"),
1005 zfs_get_name(cbp->cb_target),
1006 zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1007 (void) fprintf(stderr, gettext("use '-r' to destroy "
1008 "the following datasets:\n"));
1009 cbp->cb_first = B_FALSE;
1010 cbp->cb_error = B_TRUE;
1013 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1014 } else {
1016 * This is a clone. We only want to report this if the '-r'
1017 * wasn't specified, or the target is a snapshot.
1019 if (!cbp->cb_recurse &&
1020 zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
1021 goto out;
1023 if (cbp->cb_first) {
1024 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1025 "%s has dependent clones\n"),
1026 zfs_get_name(cbp->cb_target),
1027 zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1028 (void) fprintf(stderr, gettext("use '-R' to destroy "
1029 "the following datasets:\n"));
1030 cbp->cb_first = B_FALSE;
1031 cbp->cb_error = B_TRUE;
1032 cbp->cb_dryrun = B_TRUE;
1035 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1038 out:
1039 zfs_close(zhp);
1040 return (0);
1043 static int
1044 destroy_callback(zfs_handle_t *zhp, void *data)
1046 destroy_cbdata_t *cb = data;
1047 const char *name = zfs_get_name(zhp);
1049 if (cb->cb_verbose) {
1050 if (cb->cb_parsable) {
1051 (void) printf("destroy\t%s\n", name);
1052 } else if (cb->cb_dryrun) {
1053 (void) printf(gettext("would destroy %s\n"),
1054 name);
1055 } else {
1056 (void) printf(gettext("will destroy %s\n"),
1057 name);
1062 * Ignore pools (which we've already flagged as an error before getting
1063 * here).
1065 if (strchr(zfs_get_name(zhp), '/') == NULL &&
1066 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1067 zfs_close(zhp);
1068 return (0);
1070 if (cb->cb_dryrun) {
1071 zfs_close(zhp);
1072 return (0);
1076 * We batch up all contiguous snapshots (even of different
1077 * filesystems) and destroy them with one ioctl. We can't
1078 * simply do all snap deletions and then all fs deletions,
1079 * because we must delete a clone before its origin.
1081 if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT) {
1082 fnvlist_add_boolean(cb->cb_batchedsnaps, name);
1083 } else {
1084 int error = zfs_destroy_snaps_nvl(g_zfs,
1085 cb->cb_batchedsnaps, B_FALSE);
1086 fnvlist_free(cb->cb_batchedsnaps);
1087 cb->cb_batchedsnaps = fnvlist_alloc();
1089 if (error != 0 ||
1090 zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
1091 zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
1092 zfs_close(zhp);
1093 return (-1);
1097 zfs_close(zhp);
1098 return (0);
1101 static int
1102 destroy_print_cb(zfs_handle_t *zhp, void *arg)
1104 destroy_cbdata_t *cb = arg;
1105 const char *name = zfs_get_name(zhp);
1106 int err = 0;
1108 if (nvlist_exists(cb->cb_nvl, name)) {
1109 if (cb->cb_firstsnap == NULL)
1110 cb->cb_firstsnap = strdup(name);
1111 free(cb->cb_prevsnap);
1112 /* this snap continues the current range */
1113 cb->cb_prevsnap = strdup(name);
1114 if (cb->cb_firstsnap == NULL || cb->cb_prevsnap == NULL)
1115 nomem();
1116 if (cb->cb_verbose) {
1117 if (cb->cb_parsable) {
1118 (void) printf("destroy\t%s\n", name);
1119 } else if (cb->cb_dryrun) {
1120 (void) printf(gettext("would destroy %s\n"),
1121 name);
1122 } else {
1123 (void) printf(gettext("will destroy %s\n"),
1124 name);
1127 } else if (cb->cb_firstsnap != NULL) {
1128 /* end of this range */
1129 uint64_t used = 0;
1130 err = lzc_snaprange_space(cb->cb_firstsnap,
1131 cb->cb_prevsnap, &used);
1132 cb->cb_snapused += used;
1133 free(cb->cb_firstsnap);
1134 cb->cb_firstsnap = NULL;
1135 free(cb->cb_prevsnap);
1136 cb->cb_prevsnap = NULL;
1138 zfs_close(zhp);
1139 return (err);
1142 static int
1143 destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
1145 int err = 0;
1146 assert(cb->cb_firstsnap == NULL);
1147 assert(cb->cb_prevsnap == NULL);
1148 err = zfs_iter_snapshots_sorted(fs_zhp, destroy_print_cb, cb);
1149 if (cb->cb_firstsnap != NULL) {
1150 uint64_t used = 0;
1151 if (err == 0) {
1152 err = lzc_snaprange_space(cb->cb_firstsnap,
1153 cb->cb_prevsnap, &used);
1155 cb->cb_snapused += used;
1156 free(cb->cb_firstsnap);
1157 cb->cb_firstsnap = NULL;
1158 free(cb->cb_prevsnap);
1159 cb->cb_prevsnap = NULL;
1161 return (err);
1164 static int
1165 snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
1167 destroy_cbdata_t *cb = arg;
1168 int err = 0;
1170 /* Check for clones. */
1171 if (!cb->cb_doclones && !cb->cb_defer_destroy) {
1172 cb->cb_target = zhp;
1173 cb->cb_first = B_TRUE;
1174 err = zfs_iter_dependents(zhp, B_TRUE,
1175 destroy_check_dependent, cb);
1178 if (err == 0) {
1179 if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
1180 nomem();
1182 zfs_close(zhp);
1183 return (err);
1186 static int
1187 gather_snapshots(zfs_handle_t *zhp, void *arg)
1189 destroy_cbdata_t *cb = arg;
1190 int err = 0;
1192 err = zfs_iter_snapspec(zhp, cb->cb_snapspec, snapshot_to_nvl_cb, cb);
1193 if (err == ENOENT)
1194 err = 0;
1195 if (err != 0)
1196 goto out;
1198 if (cb->cb_verbose) {
1199 err = destroy_print_snapshots(zhp, cb);
1200 if (err != 0)
1201 goto out;
1204 if (cb->cb_recurse)
1205 err = zfs_iter_filesystems(zhp, gather_snapshots, cb);
1207 out:
1208 zfs_close(zhp);
1209 return (err);
1212 static int
1213 destroy_clones(destroy_cbdata_t *cb)
1215 nvpair_t *pair;
1216 for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
1217 pair != NULL;
1218 pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
1219 zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
1220 ZFS_TYPE_SNAPSHOT);
1221 if (zhp != NULL) {
1222 boolean_t defer = cb->cb_defer_destroy;
1223 int err = 0;
1226 * We can't defer destroy non-snapshots, so set it to
1227 * false while destroying the clones.
1229 cb->cb_defer_destroy = B_FALSE;
1230 err = zfs_iter_dependents(zhp, B_FALSE,
1231 destroy_callback, cb);
1232 cb->cb_defer_destroy = defer;
1233 zfs_close(zhp);
1234 if (err != 0)
1235 return (err);
1238 return (0);
1241 static int
1242 zfs_do_destroy(int argc, char **argv)
1244 destroy_cbdata_t cb = { 0 };
1245 int rv = 0;
1246 int err = 0;
1247 int c;
1248 zfs_handle_t *zhp = NULL;
1249 char *at, *pound;
1250 zfs_type_t type = ZFS_TYPE_DATASET;
1252 /* check options */
1253 while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
1254 switch (c) {
1255 case 'v':
1256 cb.cb_verbose = B_TRUE;
1257 break;
1258 case 'p':
1259 cb.cb_verbose = B_TRUE;
1260 cb.cb_parsable = B_TRUE;
1261 break;
1262 case 'n':
1263 cb.cb_dryrun = B_TRUE;
1264 break;
1265 case 'd':
1266 cb.cb_defer_destroy = B_TRUE;
1267 type = ZFS_TYPE_SNAPSHOT;
1268 break;
1269 case 'f':
1270 cb.cb_force = B_TRUE;
1271 break;
1272 case 'r':
1273 cb.cb_recurse = B_TRUE;
1274 break;
1275 case 'R':
1276 cb.cb_recurse = B_TRUE;
1277 cb.cb_doclones = B_TRUE;
1278 break;
1279 case '?':
1280 default:
1281 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1282 optopt);
1283 usage(B_FALSE);
1287 argc -= optind;
1288 argv += optind;
1290 /* check number of arguments */
1291 if (argc == 0) {
1292 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1293 usage(B_FALSE);
1295 if (argc > 1) {
1296 (void) fprintf(stderr, gettext("too many arguments\n"));
1297 usage(B_FALSE);
1300 at = strchr(argv[0], '@');
1301 pound = strchr(argv[0], '#');
1302 if (at != NULL) {
1304 /* Build the list of snaps to destroy in cb_nvl. */
1305 cb.cb_nvl = fnvlist_alloc();
1307 *at = '\0';
1308 zhp = zfs_open(g_zfs, argv[0],
1309 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1310 if (zhp == NULL)
1311 return (1);
1313 cb.cb_snapspec = at + 1;
1314 if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
1315 cb.cb_error) {
1316 rv = 1;
1317 goto out;
1320 if (nvlist_empty(cb.cb_nvl)) {
1321 (void) fprintf(stderr, gettext("could not find any "
1322 "snapshots to destroy; check snapshot names.\n"));
1323 rv = 1;
1324 goto out;
1327 if (cb.cb_verbose) {
1328 char buf[16];
1329 zfs_nicenum(cb.cb_snapused, buf, sizeof (buf));
1330 if (cb.cb_parsable) {
1331 (void) printf("reclaim\t%llu\n",
1332 cb.cb_snapused);
1333 } else if (cb.cb_dryrun) {
1334 (void) printf(gettext("would reclaim %s\n"),
1335 buf);
1336 } else {
1337 (void) printf(gettext("will reclaim %s\n"),
1338 buf);
1342 if (!cb.cb_dryrun) {
1343 if (cb.cb_doclones) {
1344 cb.cb_batchedsnaps = fnvlist_alloc();
1345 err = destroy_clones(&cb);
1346 if (err == 0) {
1347 err = zfs_destroy_snaps_nvl(g_zfs,
1348 cb.cb_batchedsnaps, B_FALSE);
1350 if (err != 0) {
1351 rv = 1;
1352 goto out;
1355 if (err == 0) {
1356 err = zfs_destroy_snaps_nvl(g_zfs, cb.cb_nvl,
1357 cb.cb_defer_destroy);
1361 if (err != 0)
1362 rv = 1;
1363 } else if (pound != NULL) {
1364 int err;
1365 nvlist_t *nvl;
1367 if (cb.cb_dryrun) {
1368 (void) fprintf(stderr,
1369 "dryrun is not supported with bookmark\n");
1370 return (-1);
1373 if (cb.cb_defer_destroy) {
1374 (void) fprintf(stderr,
1375 "defer destroy is not supported with bookmark\n");
1376 return (-1);
1379 if (cb.cb_recurse) {
1380 (void) fprintf(stderr,
1381 "recursive is not supported with bookmark\n");
1382 return (-1);
1385 if (!zfs_bookmark_exists(argv[0])) {
1386 (void) fprintf(stderr, gettext("bookmark '%s' "
1387 "does not exist.\n"), argv[0]);
1388 return (1);
1391 nvl = fnvlist_alloc();
1392 fnvlist_add_boolean(nvl, argv[0]);
1394 err = lzc_destroy_bookmarks(nvl, NULL);
1395 if (err != 0) {
1396 (void) zfs_standard_error(g_zfs, err,
1397 "cannot destroy bookmark");
1400 nvlist_free(cb.cb_nvl);
1402 return (err);
1403 } else {
1404 /* Open the given dataset */
1405 if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1406 return (1);
1408 cb.cb_target = zhp;
1411 * Perform an explicit check for pools before going any further.
1413 if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1414 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1415 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1416 "operation does not apply to pools\n"),
1417 zfs_get_name(zhp));
1418 (void) fprintf(stderr, gettext("use 'zfs destroy -r "
1419 "%s' to destroy all datasets in the pool\n"),
1420 zfs_get_name(zhp));
1421 (void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1422 "to destroy the pool itself\n"), zfs_get_name(zhp));
1423 rv = 1;
1424 goto out;
1428 * Check for any dependents and/or clones.
1430 cb.cb_first = B_TRUE;
1431 if (!cb.cb_doclones &&
1432 zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
1433 &cb) != 0) {
1434 rv = 1;
1435 goto out;
1438 if (cb.cb_error) {
1439 rv = 1;
1440 goto out;
1443 cb.cb_batchedsnaps = fnvlist_alloc();
1444 if (zfs_iter_dependents(zhp, B_FALSE, destroy_callback,
1445 &cb) != 0) {
1446 rv = 1;
1447 goto out;
1451 * Do the real thing. The callback will close the
1452 * handle regardless of whether it succeeds or not.
1454 err = destroy_callback(zhp, &cb);
1455 zhp = NULL;
1456 if (err == 0) {
1457 err = zfs_destroy_snaps_nvl(g_zfs,
1458 cb.cb_batchedsnaps, cb.cb_defer_destroy);
1460 if (err != 0)
1461 rv = 1;
1464 out:
1465 fnvlist_free(cb.cb_batchedsnaps);
1466 fnvlist_free(cb.cb_nvl);
1467 if (zhp != NULL)
1468 zfs_close(zhp);
1469 return (rv);
1472 static boolean_t
1473 is_recvd_column(zprop_get_cbdata_t *cbp)
1475 int i;
1476 zfs_get_column_t col;
1478 for (i = 0; i < ZFS_GET_NCOLS &&
1479 (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1480 if (col == GET_COL_RECVD)
1481 return (B_TRUE);
1482 return (B_FALSE);
1486 * zfs get [-rHp] [-o all | field[,field]...] [-s source[,source]...]
1487 * < all | property[,property]... > < fs | snap | vol > ...
1489 * -r recurse over any child datasets
1490 * -H scripted mode. Headers are stripped, and fields are separated
1491 * by tabs instead of spaces.
1492 * -o Set of fields to display. One of "name,property,value,
1493 * received,source". Default is "name,property,value,source".
1494 * "all" is an alias for all five.
1495 * -s Set of sources to allow. One of
1496 * "local,default,inherited,received,temporary,none". Default is
1497 * all six.
1498 * -p Display values in parsable (literal) format.
1500 * Prints properties for the given datasets. The user can control which
1501 * columns to display as well as which property types to allow.
1505 * Invoked to display the properties for a single dataset.
1507 static int
1508 get_callback(zfs_handle_t *zhp, void *data)
1510 char buf[ZFS_MAXPROPLEN];
1511 char rbuf[ZFS_MAXPROPLEN];
1512 zprop_source_t sourcetype;
1513 char source[ZFS_MAX_DATASET_NAME_LEN];
1514 zprop_get_cbdata_t *cbp = data;
1515 nvlist_t *user_props = zfs_get_user_props(zhp);
1516 zprop_list_t *pl = cbp->cb_proplist;
1517 nvlist_t *propval;
1518 char *strval;
1519 char *sourceval;
1520 boolean_t received = is_recvd_column(cbp);
1522 for (; pl != NULL; pl = pl->pl_next) {
1523 char *recvdval = NULL;
1525 * Skip the special fake placeholder. This will also skip over
1526 * the name property when 'all' is specified.
1528 if (pl->pl_prop == ZFS_PROP_NAME &&
1529 pl == cbp->cb_proplist)
1530 continue;
1532 if (pl->pl_prop != ZPROP_INVAL) {
1533 if (zfs_prop_get(zhp, pl->pl_prop, buf,
1534 sizeof (buf), &sourcetype, source,
1535 sizeof (source),
1536 cbp->cb_literal) != 0) {
1537 if (pl->pl_all)
1538 continue;
1539 if (!zfs_prop_valid_for_type(pl->pl_prop,
1540 ZFS_TYPE_DATASET)) {
1541 (void) fprintf(stderr,
1542 gettext("No such property '%s'\n"),
1543 zfs_prop_to_name(pl->pl_prop));
1544 continue;
1546 sourcetype = ZPROP_SRC_NONE;
1547 (void) strlcpy(buf, "-", sizeof (buf));
1550 if (received && (zfs_prop_get_recvd(zhp,
1551 zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
1552 cbp->cb_literal) == 0))
1553 recvdval = rbuf;
1555 zprop_print_one_property(zfs_get_name(zhp), cbp,
1556 zfs_prop_to_name(pl->pl_prop),
1557 buf, sourcetype, source, recvdval);
1558 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
1559 sourcetype = ZPROP_SRC_LOCAL;
1561 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1562 buf, sizeof (buf), cbp->cb_literal) != 0) {
1563 sourcetype = ZPROP_SRC_NONE;
1564 (void) strlcpy(buf, "-", sizeof (buf));
1567 zprop_print_one_property(zfs_get_name(zhp), cbp,
1568 pl->pl_user_prop, buf, sourcetype, source, NULL);
1569 } else if (zfs_prop_written(pl->pl_user_prop)) {
1570 sourcetype = ZPROP_SRC_LOCAL;
1572 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
1573 buf, sizeof (buf), cbp->cb_literal) != 0) {
1574 sourcetype = ZPROP_SRC_NONE;
1575 (void) strlcpy(buf, "-", sizeof (buf));
1578 zprop_print_one_property(zfs_get_name(zhp), cbp,
1579 pl->pl_user_prop, buf, sourcetype, source, NULL);
1580 } else {
1581 if (nvlist_lookup_nvlist(user_props,
1582 pl->pl_user_prop, &propval) != 0) {
1583 if (pl->pl_all)
1584 continue;
1585 sourcetype = ZPROP_SRC_NONE;
1586 strval = "-";
1587 } else {
1588 verify(nvlist_lookup_string(propval,
1589 ZPROP_VALUE, &strval) == 0);
1590 verify(nvlist_lookup_string(propval,
1591 ZPROP_SOURCE, &sourceval) == 0);
1593 if (strcmp(sourceval,
1594 zfs_get_name(zhp)) == 0) {
1595 sourcetype = ZPROP_SRC_LOCAL;
1596 } else if (strcmp(sourceval,
1597 ZPROP_SOURCE_VAL_RECVD) == 0) {
1598 sourcetype = ZPROP_SRC_RECEIVED;
1599 } else {
1600 sourcetype = ZPROP_SRC_INHERITED;
1601 (void) strlcpy(source,
1602 sourceval, sizeof (source));
1606 if (received && (zfs_prop_get_recvd(zhp,
1607 pl->pl_user_prop, rbuf, sizeof (rbuf),
1608 cbp->cb_literal) == 0))
1609 recvdval = rbuf;
1611 zprop_print_one_property(zfs_get_name(zhp), cbp,
1612 pl->pl_user_prop, strval, sourcetype,
1613 source, recvdval);
1617 return (0);
1620 static int
1621 zfs_do_get(int argc, char **argv)
1623 zprop_get_cbdata_t cb = { 0 };
1624 int i, c, flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1625 int types = ZFS_TYPE_DATASET | ZFS_TYPE_BOOKMARK;
1626 char *value, *fields;
1627 int ret = 0;
1628 int limit = 0;
1629 zprop_list_t fake_name = { 0 };
1632 * Set up default columns and sources.
1634 cb.cb_sources = ZPROP_SRC_ALL;
1635 cb.cb_columns[0] = GET_COL_NAME;
1636 cb.cb_columns[1] = GET_COL_PROPERTY;
1637 cb.cb_columns[2] = GET_COL_VALUE;
1638 cb.cb_columns[3] = GET_COL_SOURCE;
1639 cb.cb_type = ZFS_TYPE_DATASET;
1641 /* check options */
1642 while ((c = getopt(argc, argv, ":d:o:s:rt:Hp")) != -1) {
1643 switch (c) {
1644 case 'p':
1645 cb.cb_literal = B_TRUE;
1646 break;
1647 case 'd':
1648 limit = parse_depth(optarg, &flags);
1649 break;
1650 case 'r':
1651 flags |= ZFS_ITER_RECURSE;
1652 break;
1653 case 'H':
1654 cb.cb_scripted = B_TRUE;
1655 break;
1656 case ':':
1657 (void) fprintf(stderr, gettext("missing argument for "
1658 "'%c' option\n"), optopt);
1659 usage(B_FALSE);
1660 break;
1661 case 'o':
1663 * Process the set of columns to display. We zero out
1664 * the structure to give us a blank slate.
1666 bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1667 i = 0;
1668 while (*optarg != '\0') {
1669 static char *col_subopts[] =
1670 { "name", "property", "value", "received",
1671 "source", "all", NULL };
1673 if (i == ZFS_GET_NCOLS) {
1674 (void) fprintf(stderr, gettext("too "
1675 "many fields given to -o "
1676 "option\n"));
1677 usage(B_FALSE);
1680 switch (getsubopt(&optarg, col_subopts,
1681 &value)) {
1682 case 0:
1683 cb.cb_columns[i++] = GET_COL_NAME;
1684 break;
1685 case 1:
1686 cb.cb_columns[i++] = GET_COL_PROPERTY;
1687 break;
1688 case 2:
1689 cb.cb_columns[i++] = GET_COL_VALUE;
1690 break;
1691 case 3:
1692 cb.cb_columns[i++] = GET_COL_RECVD;
1693 flags |= ZFS_ITER_RECVD_PROPS;
1694 break;
1695 case 4:
1696 cb.cb_columns[i++] = GET_COL_SOURCE;
1697 break;
1698 case 5:
1699 if (i > 0) {
1700 (void) fprintf(stderr,
1701 gettext("\"all\" conflicts "
1702 "with specific fields "
1703 "given to -o option\n"));
1704 usage(B_FALSE);
1706 cb.cb_columns[0] = GET_COL_NAME;
1707 cb.cb_columns[1] = GET_COL_PROPERTY;
1708 cb.cb_columns[2] = GET_COL_VALUE;
1709 cb.cb_columns[3] = GET_COL_RECVD;
1710 cb.cb_columns[4] = GET_COL_SOURCE;
1711 flags |= ZFS_ITER_RECVD_PROPS;
1712 i = ZFS_GET_NCOLS;
1713 break;
1714 default:
1715 (void) fprintf(stderr,
1716 gettext("invalid column name "
1717 "'%s'\n"), value);
1718 usage(B_FALSE);
1721 break;
1723 case 's':
1724 cb.cb_sources = 0;
1725 while (*optarg != '\0') {
1726 static char *source_subopts[] = {
1727 "local", "default", "inherited",
1728 "received", "temporary", "none",
1729 NULL };
1731 switch (getsubopt(&optarg, source_subopts,
1732 &value)) {
1733 case 0:
1734 cb.cb_sources |= ZPROP_SRC_LOCAL;
1735 break;
1736 case 1:
1737 cb.cb_sources |= ZPROP_SRC_DEFAULT;
1738 break;
1739 case 2:
1740 cb.cb_sources |= ZPROP_SRC_INHERITED;
1741 break;
1742 case 3:
1743 cb.cb_sources |= ZPROP_SRC_RECEIVED;
1744 break;
1745 case 4:
1746 cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1747 break;
1748 case 5:
1749 cb.cb_sources |= ZPROP_SRC_NONE;
1750 break;
1751 default:
1752 (void) fprintf(stderr,
1753 gettext("invalid source "
1754 "'%s'\n"), value);
1755 usage(B_FALSE);
1758 break;
1760 case 't':
1761 types = 0;
1762 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
1763 while (*optarg != '\0') {
1764 static char *type_subopts[] = { "filesystem",
1765 "volume", "snapshot", "bookmark",
1766 "all", NULL };
1768 switch (getsubopt(&optarg, type_subopts,
1769 &value)) {
1770 case 0:
1771 types |= ZFS_TYPE_FILESYSTEM;
1772 break;
1773 case 1:
1774 types |= ZFS_TYPE_VOLUME;
1775 break;
1776 case 2:
1777 types |= ZFS_TYPE_SNAPSHOT;
1778 break;
1779 case 3:
1780 types |= ZFS_TYPE_BOOKMARK;
1781 break;
1782 case 4:
1783 types = ZFS_TYPE_DATASET |
1784 ZFS_TYPE_BOOKMARK;
1785 break;
1787 default:
1788 (void) fprintf(stderr,
1789 gettext("invalid type '%s'\n"),
1790 value);
1791 usage(B_FALSE);
1794 break;
1796 case '?':
1797 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1798 optopt);
1799 usage(B_FALSE);
1803 argc -= optind;
1804 argv += optind;
1806 if (argc < 1) {
1807 (void) fprintf(stderr, gettext("missing property "
1808 "argument\n"));
1809 usage(B_FALSE);
1812 fields = argv[0];
1814 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1815 != 0)
1816 usage(B_FALSE);
1818 argc--;
1819 argv++;
1822 * As part of zfs_expand_proplist(), we keep track of the maximum column
1823 * width for each property. For the 'NAME' (and 'SOURCE') columns, we
1824 * need to know the maximum name length. However, the user likely did
1825 * not specify 'name' as one of the properties to fetch, so we need to
1826 * make sure we always include at least this property for
1827 * print_get_headers() to work properly.
1829 if (cb.cb_proplist != NULL) {
1830 fake_name.pl_prop = ZFS_PROP_NAME;
1831 fake_name.pl_width = strlen(gettext("NAME"));
1832 fake_name.pl_next = cb.cb_proplist;
1833 cb.cb_proplist = &fake_name;
1836 cb.cb_first = B_TRUE;
1838 /* run for each object */
1839 ret = zfs_for_each(argc, argv, flags, types, NULL,
1840 &cb.cb_proplist, limit, get_callback, &cb);
1842 if (cb.cb_proplist == &fake_name)
1843 zprop_free_list(fake_name.pl_next);
1844 else
1845 zprop_free_list(cb.cb_proplist);
1847 return (ret);
1851 * inherit [-rS] <property> <fs|vol> ...
1853 * -r Recurse over all children
1854 * -S Revert to received value, if any
1856 * For each dataset specified on the command line, inherit the given property
1857 * from its parent. Inheriting a property at the pool level will cause it to
1858 * use the default value. The '-r' flag will recurse over all children, and is
1859 * useful for setting a property on a hierarchy-wide basis, regardless of any
1860 * local modifications for each dataset.
1863 typedef struct inherit_cbdata {
1864 const char *cb_propname;
1865 boolean_t cb_received;
1866 } inherit_cbdata_t;
1868 static int
1869 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
1871 inherit_cbdata_t *cb = data;
1872 zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
1875 * If we're doing it recursively, then ignore properties that
1876 * are not valid for this type of dataset.
1878 if (prop != ZPROP_INVAL &&
1879 !zfs_prop_valid_for_type(prop, zfs_get_type(zhp)))
1880 return (0);
1882 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1885 static int
1886 inherit_cb(zfs_handle_t *zhp, void *data)
1888 inherit_cbdata_t *cb = data;
1890 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1893 static int
1894 zfs_do_inherit(int argc, char **argv)
1896 int c;
1897 zfs_prop_t prop;
1898 inherit_cbdata_t cb = { 0 };
1899 char *propname;
1900 int ret = 0;
1901 int flags = 0;
1902 boolean_t received = B_FALSE;
1904 /* check options */
1905 while ((c = getopt(argc, argv, "rS")) != -1) {
1906 switch (c) {
1907 case 'r':
1908 flags |= ZFS_ITER_RECURSE;
1909 break;
1910 case 'S':
1911 received = B_TRUE;
1912 break;
1913 case '?':
1914 default:
1915 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1916 optopt);
1917 usage(B_FALSE);
1921 argc -= optind;
1922 argv += optind;
1924 /* check number of arguments */
1925 if (argc < 1) {
1926 (void) fprintf(stderr, gettext("missing property argument\n"));
1927 usage(B_FALSE);
1929 if (argc < 2) {
1930 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1931 usage(B_FALSE);
1934 propname = argv[0];
1935 argc--;
1936 argv++;
1938 if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1939 if (zfs_prop_readonly(prop)) {
1940 (void) fprintf(stderr, gettext(
1941 "%s property is read-only\n"),
1942 propname);
1943 return (1);
1945 if (!zfs_prop_inheritable(prop) && !received) {
1946 (void) fprintf(stderr, gettext("'%s' property cannot "
1947 "be inherited\n"), propname);
1948 if (prop == ZFS_PROP_QUOTA ||
1949 prop == ZFS_PROP_RESERVATION ||
1950 prop == ZFS_PROP_REFQUOTA ||
1951 prop == ZFS_PROP_REFRESERVATION) {
1952 (void) fprintf(stderr, gettext("use 'zfs set "
1953 "%s=none' to clear\n"), propname);
1954 (void) fprintf(stderr, gettext("use 'zfs "
1955 "inherit -S %s' to revert to received "
1956 "value\n"), propname);
1958 return (1);
1960 if (received && (prop == ZFS_PROP_VOLSIZE ||
1961 prop == ZFS_PROP_VERSION)) {
1962 (void) fprintf(stderr, gettext("'%s' property cannot "
1963 "be reverted to a received value\n"), propname);
1964 return (1);
1966 } else if (!zfs_prop_user(propname)) {
1967 (void) fprintf(stderr, gettext("invalid property '%s'\n"),
1968 propname);
1969 usage(B_FALSE);
1972 cb.cb_propname = propname;
1973 cb.cb_received = received;
1975 if (flags & ZFS_ITER_RECURSE) {
1976 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1977 NULL, NULL, 0, inherit_recurse_cb, &cb);
1978 } else {
1979 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1980 NULL, NULL, 0, inherit_cb, &cb);
1983 return (ret);
1986 typedef struct upgrade_cbdata {
1987 uint64_t cb_numupgraded;
1988 uint64_t cb_numsamegraded;
1989 uint64_t cb_numfailed;
1990 uint64_t cb_version;
1991 boolean_t cb_newer;
1992 boolean_t cb_foundone;
1993 char cb_lastfs[ZFS_MAX_DATASET_NAME_LEN];
1994 } upgrade_cbdata_t;
1996 static int
1997 same_pool(zfs_handle_t *zhp, const char *name)
1999 int len1 = strcspn(name, "/@");
2000 const char *zhname = zfs_get_name(zhp);
2001 int len2 = strcspn(zhname, "/@");
2003 if (len1 != len2)
2004 return (B_FALSE);
2005 return (strncmp(name, zhname, len1) == 0);
2008 static int
2009 upgrade_list_callback(zfs_handle_t *zhp, void *data)
2011 upgrade_cbdata_t *cb = data;
2012 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2014 /* list if it's old/new */
2015 if ((!cb->cb_newer && version < ZPL_VERSION) ||
2016 (cb->cb_newer && version > ZPL_VERSION)) {
2017 char *str;
2018 if (cb->cb_newer) {
2019 str = gettext("The following filesystems are "
2020 "formatted using a newer software version and\n"
2021 "cannot be accessed on the current system.\n\n");
2022 } else {
2023 str = gettext("The following filesystems are "
2024 "out of date, and can be upgraded. After being\n"
2025 "upgraded, these filesystems (and any 'zfs send' "
2026 "streams generated from\n"
2027 "subsequent snapshots) will no longer be "
2028 "accessible by older software versions.\n\n");
2031 if (!cb->cb_foundone) {
2032 (void) puts(str);
2033 (void) printf(gettext("VER FILESYSTEM\n"));
2034 (void) printf(gettext("--- ------------\n"));
2035 cb->cb_foundone = B_TRUE;
2038 (void) printf("%2u %s\n", version, zfs_get_name(zhp));
2041 return (0);
2044 static int
2045 upgrade_set_callback(zfs_handle_t *zhp, void *data)
2047 upgrade_cbdata_t *cb = data;
2048 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2049 int needed_spa_version;
2050 int spa_version;
2052 if (zfs_spa_version(zhp, &spa_version) < 0)
2053 return (-1);
2055 needed_spa_version = zfs_spa_version_map(cb->cb_version);
2057 if (needed_spa_version < 0)
2058 return (-1);
2060 if (spa_version < needed_spa_version) {
2061 /* can't upgrade */
2062 (void) printf(gettext("%s: can not be "
2063 "upgraded; the pool version needs to first "
2064 "be upgraded\nto version %d\n\n"),
2065 zfs_get_name(zhp), needed_spa_version);
2066 cb->cb_numfailed++;
2067 return (0);
2070 /* upgrade */
2071 if (version < cb->cb_version) {
2072 char verstr[16];
2073 (void) snprintf(verstr, sizeof (verstr),
2074 "%llu", cb->cb_version);
2075 if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
2077 * If they did "zfs upgrade -a", then we could
2078 * be doing ioctls to different pools. We need
2079 * to log this history once to each pool, and bypass
2080 * the normal history logging that happens in main().
2082 (void) zpool_log_history(g_zfs, history_str);
2083 log_history = B_FALSE;
2085 if (zfs_prop_set(zhp, "version", verstr) == 0)
2086 cb->cb_numupgraded++;
2087 else
2088 cb->cb_numfailed++;
2089 (void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
2090 } else if (version > cb->cb_version) {
2091 /* can't downgrade */
2092 (void) printf(gettext("%s: can not be downgraded; "
2093 "it is already at version %u\n"),
2094 zfs_get_name(zhp), version);
2095 cb->cb_numfailed++;
2096 } else {
2097 cb->cb_numsamegraded++;
2099 return (0);
2103 * zfs upgrade
2104 * zfs upgrade -v
2105 * zfs upgrade [-r] [-V <version>] <-a | filesystem>
2107 static int
2108 zfs_do_upgrade(int argc, char **argv)
2110 boolean_t all = B_FALSE;
2111 boolean_t showversions = B_FALSE;
2112 int ret = 0;
2113 upgrade_cbdata_t cb = { 0 };
2114 char c;
2115 int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2117 /* check options */
2118 while ((c = getopt(argc, argv, "rvV:a")) != -1) {
2119 switch (c) {
2120 case 'r':
2121 flags |= ZFS_ITER_RECURSE;
2122 break;
2123 case 'v':
2124 showversions = B_TRUE;
2125 break;
2126 case 'V':
2127 if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
2128 optarg, &cb.cb_version) != 0) {
2129 (void) fprintf(stderr,
2130 gettext("invalid version %s\n"), optarg);
2131 usage(B_FALSE);
2133 break;
2134 case 'a':
2135 all = B_TRUE;
2136 break;
2137 case '?':
2138 default:
2139 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2140 optopt);
2141 usage(B_FALSE);
2145 argc -= optind;
2146 argv += optind;
2148 if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
2149 usage(B_FALSE);
2150 if (showversions && (flags & ZFS_ITER_RECURSE || all ||
2151 cb.cb_version || argc))
2152 usage(B_FALSE);
2153 if ((all || argc) && (showversions))
2154 usage(B_FALSE);
2155 if (all && argc)
2156 usage(B_FALSE);
2158 if (showversions) {
2159 /* Show info on available versions. */
2160 (void) printf(gettext("The following filesystem versions are "
2161 "supported:\n\n"));
2162 (void) printf(gettext("VER DESCRIPTION\n"));
2163 (void) printf("--- -----------------------------------------"
2164 "---------------\n");
2165 (void) printf(gettext(" 1 Initial ZFS filesystem version\n"));
2166 (void) printf(gettext(" 2 Enhanced directory entries\n"));
2167 (void) printf(gettext(" 3 Case insensitive and filesystem "
2168 "user identifier (FUID)\n"));
2169 (void) printf(gettext(" 4 userquota, groupquota "
2170 "properties\n"));
2171 (void) printf(gettext(" 5 System attributes\n"));
2172 (void) printf(gettext("\nFor more information on a particular "
2173 "version, including supported releases,\n"));
2174 (void) printf("see the ZFS Administration Guide.\n\n");
2175 ret = 0;
2176 } else if (argc || all) {
2177 /* Upgrade filesystems */
2178 if (cb.cb_version == 0)
2179 cb.cb_version = ZPL_VERSION;
2180 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
2181 NULL, NULL, 0, upgrade_set_callback, &cb);
2182 (void) printf(gettext("%llu filesystems upgraded\n"),
2183 cb.cb_numupgraded);
2184 if (cb.cb_numsamegraded) {
2185 (void) printf(gettext("%llu filesystems already at "
2186 "this version\n"),
2187 cb.cb_numsamegraded);
2189 if (cb.cb_numfailed != 0)
2190 ret = 1;
2191 } else {
2192 /* List old-version filesystems */
2193 boolean_t found;
2194 (void) printf(gettext("This system is currently running "
2195 "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
2197 flags |= ZFS_ITER_RECURSE;
2198 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2199 NULL, NULL, 0, upgrade_list_callback, &cb);
2201 found = cb.cb_foundone;
2202 cb.cb_foundone = B_FALSE;
2203 cb.cb_newer = B_TRUE;
2205 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2206 NULL, NULL, 0, upgrade_list_callback, &cb);
2208 if (!cb.cb_foundone && !found) {
2209 (void) printf(gettext("All filesystems are "
2210 "formatted with the current version.\n"));
2214 return (ret);
2218 * zfs userspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2219 * [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2220 * zfs groupspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2221 * [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2223 * -H Scripted mode; elide headers and separate columns by tabs.
2224 * -i Translate SID to POSIX ID.
2225 * -n Print numeric ID instead of user/group name.
2226 * -o Control which fields to display.
2227 * -p Use exact (parsable) numeric output.
2228 * -s Specify sort columns, descending order.
2229 * -S Specify sort columns, ascending order.
2230 * -t Control which object types to display.
2232 * Displays space consumed by, and quotas on, each user in the specified
2233 * filesystem or snapshot.
2236 /* us_field_types, us_field_hdr and us_field_names should be kept in sync */
2237 enum us_field_types {
2238 USFIELD_TYPE,
2239 USFIELD_NAME,
2240 USFIELD_USED,
2241 USFIELD_QUOTA
2243 static char *us_field_hdr[] = { "TYPE", "NAME", "USED", "QUOTA" };
2244 static char *us_field_names[] = { "type", "name", "used", "quota" };
2245 #define USFIELD_LAST (sizeof (us_field_names) / sizeof (char *))
2247 #define USTYPE_PSX_GRP (1 << 0)
2248 #define USTYPE_PSX_USR (1 << 1)
2249 #define USTYPE_SMB_GRP (1 << 2)
2250 #define USTYPE_SMB_USR (1 << 3)
2251 #define USTYPE_ALL \
2252 (USTYPE_PSX_GRP | USTYPE_PSX_USR | USTYPE_SMB_GRP | USTYPE_SMB_USR)
2254 static int us_type_bits[] = {
2255 USTYPE_PSX_GRP,
2256 USTYPE_PSX_USR,
2257 USTYPE_SMB_GRP,
2258 USTYPE_SMB_USR,
2259 USTYPE_ALL
2261 static char *us_type_names[] = { "posixgroup", "posixuser", "smbgroup",
2262 "smbuser", "all" };
2264 typedef struct us_node {
2265 nvlist_t *usn_nvl;
2266 uu_avl_node_t usn_avlnode;
2267 uu_list_node_t usn_listnode;
2268 } us_node_t;
2270 typedef struct us_cbdata {
2271 nvlist_t **cb_nvlp;
2272 uu_avl_pool_t *cb_avl_pool;
2273 uu_avl_t *cb_avl;
2274 boolean_t cb_numname;
2275 boolean_t cb_nicenum;
2276 boolean_t cb_sid2posix;
2277 zfs_userquota_prop_t cb_prop;
2278 zfs_sort_column_t *cb_sortcol;
2279 size_t cb_width[USFIELD_LAST];
2280 } us_cbdata_t;
2282 static boolean_t us_populated = B_FALSE;
2284 typedef struct {
2285 zfs_sort_column_t *si_sortcol;
2286 boolean_t si_numname;
2287 } us_sort_info_t;
2289 static int
2290 us_field_index(char *field)
2292 int i;
2294 for (i = 0; i < USFIELD_LAST; i++) {
2295 if (strcmp(field, us_field_names[i]) == 0)
2296 return (i);
2299 return (-1);
2302 static int
2303 us_compare(const void *larg, const void *rarg, void *unused)
2305 const us_node_t *l = larg;
2306 const us_node_t *r = rarg;
2307 us_sort_info_t *si = (us_sort_info_t *)unused;
2308 zfs_sort_column_t *sortcol = si->si_sortcol;
2309 boolean_t numname = si->si_numname;
2310 nvlist_t *lnvl = l->usn_nvl;
2311 nvlist_t *rnvl = r->usn_nvl;
2312 int rc = 0;
2313 boolean_t lvb, rvb;
2315 for (; sortcol != NULL; sortcol = sortcol->sc_next) {
2316 char *lvstr = "";
2317 char *rvstr = "";
2318 uint32_t lv32 = 0;
2319 uint32_t rv32 = 0;
2320 uint64_t lv64 = 0;
2321 uint64_t rv64 = 0;
2322 zfs_prop_t prop = sortcol->sc_prop;
2323 const char *propname = NULL;
2324 boolean_t reverse = sortcol->sc_reverse;
2326 switch (prop) {
2327 case ZFS_PROP_TYPE:
2328 propname = "type";
2329 (void) nvlist_lookup_uint32(lnvl, propname, &lv32);
2330 (void) nvlist_lookup_uint32(rnvl, propname, &rv32);
2331 if (rv32 != lv32)
2332 rc = (rv32 < lv32) ? 1 : -1;
2333 break;
2334 case ZFS_PROP_NAME:
2335 propname = "name";
2336 if (numname) {
2337 (void) nvlist_lookup_uint64(lnvl, propname,
2338 &lv64);
2339 (void) nvlist_lookup_uint64(rnvl, propname,
2340 &rv64);
2341 if (rv64 != lv64)
2342 rc = (rv64 < lv64) ? 1 : -1;
2343 } else {
2344 (void) nvlist_lookup_string(lnvl, propname,
2345 &lvstr);
2346 (void) nvlist_lookup_string(rnvl, propname,
2347 &rvstr);
2348 rc = strcmp(lvstr, rvstr);
2350 break;
2351 case ZFS_PROP_USED:
2352 case ZFS_PROP_QUOTA:
2353 if (!us_populated)
2354 break;
2355 if (prop == ZFS_PROP_USED)
2356 propname = "used";
2357 else
2358 propname = "quota";
2359 (void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2360 (void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2361 if (rv64 != lv64)
2362 rc = (rv64 < lv64) ? 1 : -1;
2363 break;
2365 default:
2366 break;
2369 if (rc != 0) {
2370 if (rc < 0)
2371 return (reverse ? 1 : -1);
2372 else
2373 return (reverse ? -1 : 1);
2378 * If entries still seem to be the same, check if they are of the same
2379 * type (smbentity is added only if we are doing SID to POSIX ID
2380 * translation where we can have duplicate type/name combinations).
2382 if (nvlist_lookup_boolean_value(lnvl, "smbentity", &lvb) == 0 &&
2383 nvlist_lookup_boolean_value(rnvl, "smbentity", &rvb) == 0 &&
2384 lvb != rvb)
2385 return (lvb < rvb ? -1 : 1);
2387 return (0);
2390 static inline const char *
2391 us_type2str(unsigned field_type)
2393 switch (field_type) {
2394 case USTYPE_PSX_USR:
2395 return ("POSIX User");
2396 case USTYPE_PSX_GRP:
2397 return ("POSIX Group");
2398 case USTYPE_SMB_USR:
2399 return ("SMB User");
2400 case USTYPE_SMB_GRP:
2401 return ("SMB Group");
2402 default:
2403 return ("Undefined");
2407 static int
2408 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2410 us_cbdata_t *cb = (us_cbdata_t *)arg;
2411 zfs_userquota_prop_t prop = cb->cb_prop;
2412 char *name = NULL;
2413 char *propname;
2414 char sizebuf[32];
2415 us_node_t *node;
2416 uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2417 uu_avl_t *avl = cb->cb_avl;
2418 uu_avl_index_t idx;
2419 nvlist_t *props;
2420 us_node_t *n;
2421 zfs_sort_column_t *sortcol = cb->cb_sortcol;
2422 unsigned type = 0;
2423 const char *typestr;
2424 size_t namelen;
2425 size_t typelen;
2426 size_t sizelen;
2427 int typeidx, nameidx, sizeidx;
2428 us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
2429 boolean_t smbentity = B_FALSE;
2431 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
2432 nomem();
2433 node = safe_malloc(sizeof (us_node_t));
2434 uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
2435 node->usn_nvl = props;
2437 if (domain != NULL && domain[0] != '\0') {
2438 /* SMB */
2439 char sid[MAXNAMELEN + 32];
2440 uid_t id;
2441 int err;
2442 int flag = IDMAP_REQ_FLG_USE_CACHE;
2444 smbentity = B_TRUE;
2446 (void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
2448 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2449 type = USTYPE_SMB_GRP;
2450 err = sid_to_id(sid, B_FALSE, &id);
2451 } else {
2452 type = USTYPE_SMB_USR;
2453 err = sid_to_id(sid, B_TRUE, &id);
2456 if (err == 0) {
2457 rid = id;
2458 if (!cb->cb_sid2posix) {
2459 if (type == USTYPE_SMB_USR) {
2460 (void) idmap_getwinnamebyuid(rid, flag,
2461 &name, NULL);
2462 } else {
2463 (void) idmap_getwinnamebygid(rid, flag,
2464 &name, NULL);
2466 if (name == NULL)
2467 name = sid;
2472 if (cb->cb_sid2posix || domain == NULL || domain[0] == '\0') {
2473 /* POSIX or -i */
2474 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2475 type = USTYPE_PSX_GRP;
2476 if (!cb->cb_numname) {
2477 struct group *g;
2479 if ((g = getgrgid(rid)) != NULL)
2480 name = g->gr_name;
2482 } else {
2483 type = USTYPE_PSX_USR;
2484 if (!cb->cb_numname) {
2485 struct passwd *p;
2487 if ((p = getpwuid(rid)) != NULL)
2488 name = p->pw_name;
2494 * Make sure that the type/name combination is unique when doing
2495 * SID to POSIX ID translation (hence changing the type from SMB to
2496 * POSIX).
2498 if (cb->cb_sid2posix &&
2499 nvlist_add_boolean_value(props, "smbentity", smbentity) != 0)
2500 nomem();
2502 /* Calculate/update width of TYPE field */
2503 typestr = us_type2str(type);
2504 typelen = strlen(gettext(typestr));
2505 typeidx = us_field_index("type");
2506 if (typelen > cb->cb_width[typeidx])
2507 cb->cb_width[typeidx] = typelen;
2508 if (nvlist_add_uint32(props, "type", type) != 0)
2509 nomem();
2511 /* Calculate/update width of NAME field */
2512 if ((cb->cb_numname && cb->cb_sid2posix) || name == NULL) {
2513 if (nvlist_add_uint64(props, "name", rid) != 0)
2514 nomem();
2515 namelen = snprintf(NULL, 0, "%u", rid);
2516 } else {
2517 if (nvlist_add_string(props, "name", name) != 0)
2518 nomem();
2519 namelen = strlen(name);
2521 nameidx = us_field_index("name");
2522 if (namelen > cb->cb_width[nameidx])
2523 cb->cb_width[nameidx] = namelen;
2526 * Check if this type/name combination is in the list and update it;
2527 * otherwise add new node to the list.
2529 if ((n = uu_avl_find(avl, node, &sortinfo, &idx)) == NULL) {
2530 uu_avl_insert(avl, node, idx);
2531 } else {
2532 nvlist_free(props);
2533 free(node);
2534 node = n;
2535 props = node->usn_nvl;
2538 /* Calculate/update width of USED/QUOTA fields */
2539 if (cb->cb_nicenum)
2540 zfs_nicenum(space, sizebuf, sizeof (sizebuf));
2541 else
2542 (void) snprintf(sizebuf, sizeof (sizebuf), "%llu", space);
2543 sizelen = strlen(sizebuf);
2544 if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED) {
2545 propname = "used";
2546 if (!nvlist_exists(props, "quota"))
2547 (void) nvlist_add_uint64(props, "quota", 0);
2548 } else {
2549 propname = "quota";
2550 if (!nvlist_exists(props, "used"))
2551 (void) nvlist_add_uint64(props, "used", 0);
2553 sizeidx = us_field_index(propname);
2554 if (sizelen > cb->cb_width[sizeidx])
2555 cb->cb_width[sizeidx] = sizelen;
2557 if (nvlist_add_uint64(props, propname, space) != 0)
2558 nomem();
2560 return (0);
2563 static void
2564 print_us_node(boolean_t scripted, boolean_t parsable, int *fields, int types,
2565 size_t *width, us_node_t *node)
2567 nvlist_t *nvl = node->usn_nvl;
2568 char valstr[MAXNAMELEN];
2569 boolean_t first = B_TRUE;
2570 int cfield = 0;
2571 int field;
2572 uint32_t ustype;
2574 /* Check type */
2575 (void) nvlist_lookup_uint32(nvl, "type", &ustype);
2576 if (!(ustype & types))
2577 return;
2579 while ((field = fields[cfield]) != USFIELD_LAST) {
2580 nvpair_t *nvp = NULL;
2581 data_type_t type;
2582 uint32_t val32;
2583 uint64_t val64;
2584 char *strval = NULL;
2586 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
2587 if (strcmp(nvpair_name(nvp),
2588 us_field_names[field]) == 0)
2589 break;
2592 type = nvpair_type(nvp);
2593 switch (type) {
2594 case DATA_TYPE_UINT32:
2595 (void) nvpair_value_uint32(nvp, &val32);
2596 break;
2597 case DATA_TYPE_UINT64:
2598 (void) nvpair_value_uint64(nvp, &val64);
2599 break;
2600 case DATA_TYPE_STRING:
2601 (void) nvpair_value_string(nvp, &strval);
2602 break;
2603 default:
2604 (void) fprintf(stderr, "invalid data type\n");
2607 switch (field) {
2608 case USFIELD_TYPE:
2609 strval = (char *)us_type2str(val32);
2610 break;
2611 case USFIELD_NAME:
2612 if (type == DATA_TYPE_UINT64) {
2613 (void) sprintf(valstr, "%llu", val64);
2614 strval = valstr;
2616 break;
2617 case USFIELD_USED:
2618 case USFIELD_QUOTA:
2619 if (type == DATA_TYPE_UINT64) {
2620 if (parsable) {
2621 (void) sprintf(valstr, "%llu", val64);
2622 } else {
2623 zfs_nicenum(val64, valstr,
2624 sizeof (valstr));
2626 if (field == USFIELD_QUOTA &&
2627 strcmp(valstr, "0") == 0)
2628 strval = "none";
2629 else
2630 strval = valstr;
2632 break;
2635 if (!first) {
2636 if (scripted)
2637 (void) printf("\t");
2638 else
2639 (void) printf(" ");
2641 if (scripted)
2642 (void) printf("%s", strval);
2643 else if (field == USFIELD_TYPE || field == USFIELD_NAME)
2644 (void) printf("%-*s", width[field], strval);
2645 else
2646 (void) printf("%*s", width[field], strval);
2648 first = B_FALSE;
2649 cfield++;
2652 (void) printf("\n");
2655 static void
2656 print_us(boolean_t scripted, boolean_t parsable, int *fields, int types,
2657 size_t *width, boolean_t rmnode, uu_avl_t *avl)
2659 us_node_t *node;
2660 const char *col;
2661 int cfield = 0;
2662 int field;
2664 if (!scripted) {
2665 boolean_t first = B_TRUE;
2667 while ((field = fields[cfield]) != USFIELD_LAST) {
2668 col = gettext(us_field_hdr[field]);
2669 if (field == USFIELD_TYPE || field == USFIELD_NAME) {
2670 (void) printf(first ? "%-*s" : " %-*s",
2671 width[field], col);
2672 } else {
2673 (void) printf(first ? "%*s" : " %*s",
2674 width[field], col);
2676 first = B_FALSE;
2677 cfield++;
2679 (void) printf("\n");
2682 for (node = uu_avl_first(avl); node; node = uu_avl_next(avl, node)) {
2683 print_us_node(scripted, parsable, fields, types, width, node);
2684 if (rmnode)
2685 nvlist_free(node->usn_nvl);
2689 static int
2690 zfs_do_userspace(int argc, char **argv)
2692 zfs_handle_t *zhp;
2693 zfs_userquota_prop_t p;
2694 uu_avl_pool_t *avl_pool;
2695 uu_avl_t *avl_tree;
2696 uu_avl_walk_t *walk;
2697 char *delim;
2698 char deffields[] = "type,name,used,quota";
2699 char *ofield = NULL;
2700 char *tfield = NULL;
2701 int cfield = 0;
2702 int fields[256];
2703 int i;
2704 boolean_t scripted = B_FALSE;
2705 boolean_t prtnum = B_FALSE;
2706 boolean_t parsable = B_FALSE;
2707 boolean_t sid2posix = B_FALSE;
2708 int ret = 0;
2709 int c;
2710 zfs_sort_column_t *sortcol = NULL;
2711 int types = USTYPE_PSX_USR | USTYPE_SMB_USR;
2712 us_cbdata_t cb;
2713 us_node_t *node;
2714 us_node_t *rmnode;
2715 uu_list_pool_t *listpool;
2716 uu_list_t *list;
2717 uu_avl_index_t idx = 0;
2718 uu_list_index_t idx2 = 0;
2720 if (argc < 2)
2721 usage(B_FALSE);
2723 if (strcmp(argv[0], "groupspace") == 0)
2724 /* Toggle default group types */
2725 types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
2727 while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
2728 switch (c) {
2729 case 'n':
2730 prtnum = B_TRUE;
2731 break;
2732 case 'H':
2733 scripted = B_TRUE;
2734 break;
2735 case 'p':
2736 parsable = B_TRUE;
2737 break;
2738 case 'o':
2739 ofield = optarg;
2740 break;
2741 case 's':
2742 case 'S':
2743 if (zfs_add_sort_column(&sortcol, optarg,
2744 c == 's' ? B_FALSE : B_TRUE) != 0) {
2745 (void) fprintf(stderr,
2746 gettext("invalid field '%s'\n"), optarg);
2747 usage(B_FALSE);
2749 break;
2750 case 't':
2751 tfield = optarg;
2752 break;
2753 case 'i':
2754 sid2posix = B_TRUE;
2755 break;
2756 case ':':
2757 (void) fprintf(stderr, gettext("missing argument for "
2758 "'%c' option\n"), optopt);
2759 usage(B_FALSE);
2760 break;
2761 case '?':
2762 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2763 optopt);
2764 usage(B_FALSE);
2768 argc -= optind;
2769 argv += optind;
2771 if (argc < 1) {
2772 (void) fprintf(stderr, gettext("missing dataset name\n"));
2773 usage(B_FALSE);
2775 if (argc > 1) {
2776 (void) fprintf(stderr, gettext("too many arguments\n"));
2777 usage(B_FALSE);
2780 /* Use default output fields if not specified using -o */
2781 if (ofield == NULL)
2782 ofield = deffields;
2783 do {
2784 if ((delim = strchr(ofield, ',')) != NULL)
2785 *delim = '\0';
2786 if ((fields[cfield++] = us_field_index(ofield)) == -1) {
2787 (void) fprintf(stderr, gettext("invalid type '%s' "
2788 "for -o option\n"), ofield);
2789 return (-1);
2791 if (delim != NULL)
2792 ofield = delim + 1;
2793 } while (delim != NULL);
2794 fields[cfield] = USFIELD_LAST;
2796 /* Override output types (-t option) */
2797 if (tfield != NULL) {
2798 types = 0;
2800 do {
2801 boolean_t found = B_FALSE;
2803 if ((delim = strchr(tfield, ',')) != NULL)
2804 *delim = '\0';
2805 for (i = 0; i < sizeof (us_type_bits) / sizeof (int);
2806 i++) {
2807 if (strcmp(tfield, us_type_names[i]) == 0) {
2808 found = B_TRUE;
2809 types |= us_type_bits[i];
2810 break;
2813 if (!found) {
2814 (void) fprintf(stderr, gettext("invalid type "
2815 "'%s' for -t option\n"), tfield);
2816 return (-1);
2818 if (delim != NULL)
2819 tfield = delim + 1;
2820 } while (delim != NULL);
2823 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
2824 return (1);
2826 if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
2827 offsetof(us_node_t, usn_avlnode), us_compare, UU_DEFAULT)) == NULL)
2828 nomem();
2829 if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
2830 nomem();
2832 /* Always add default sorting columns */
2833 (void) zfs_add_sort_column(&sortcol, "type", B_FALSE);
2834 (void) zfs_add_sort_column(&sortcol, "name", B_FALSE);
2836 cb.cb_sortcol = sortcol;
2837 cb.cb_numname = prtnum;
2838 cb.cb_nicenum = !parsable;
2839 cb.cb_avl_pool = avl_pool;
2840 cb.cb_avl = avl_tree;
2841 cb.cb_sid2posix = sid2posix;
2843 for (i = 0; i < USFIELD_LAST; i++)
2844 cb.cb_width[i] = strlen(gettext(us_field_hdr[i]));
2846 for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
2847 if (((p == ZFS_PROP_USERUSED || p == ZFS_PROP_USERQUOTA) &&
2848 !(types & (USTYPE_PSX_USR | USTYPE_SMB_USR))) ||
2849 ((p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA) &&
2850 !(types & (USTYPE_PSX_GRP | USTYPE_SMB_GRP))))
2851 continue;
2852 cb.cb_prop = p;
2853 if ((ret = zfs_userspace(zhp, p, userspace_cb, &cb)) != 0)
2854 return (ret);
2857 /* Sort the list */
2858 if ((node = uu_avl_first(avl_tree)) == NULL)
2859 return (0);
2861 us_populated = B_TRUE;
2863 listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
2864 offsetof(us_node_t, usn_listnode), NULL, UU_DEFAULT);
2865 list = uu_list_create(listpool, NULL, UU_DEFAULT);
2866 uu_list_node_init(node, &node->usn_listnode, listpool);
2868 while (node != NULL) {
2869 rmnode = node;
2870 node = uu_avl_next(avl_tree, node);
2871 uu_avl_remove(avl_tree, rmnode);
2872 if (uu_list_find(list, rmnode, NULL, &idx2) == NULL)
2873 uu_list_insert(list, rmnode, idx2);
2876 for (node = uu_list_first(list); node != NULL;
2877 node = uu_list_next(list, node)) {
2878 us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
2880 if (uu_avl_find(avl_tree, node, &sortinfo, &idx) == NULL)
2881 uu_avl_insert(avl_tree, node, idx);
2884 uu_list_destroy(list);
2885 uu_list_pool_destroy(listpool);
2887 /* Print and free node nvlist memory */
2888 print_us(scripted, parsable, fields, types, cb.cb_width, B_TRUE,
2889 cb.cb_avl);
2891 zfs_free_sort_columns(sortcol);
2893 /* Clean up the AVL tree */
2894 if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
2895 nomem();
2897 while ((node = uu_avl_walk_next(walk)) != NULL) {
2898 uu_avl_remove(cb.cb_avl, node);
2899 free(node);
2902 uu_avl_walk_end(walk);
2903 uu_avl_destroy(avl_tree);
2904 uu_avl_pool_destroy(avl_pool);
2906 return (ret);
2910 * list [-Hp][-r|-d max] [-o property[,...]] [-s property] ... [-S property] ...
2911 * [-t type[,...]] [filesystem|volume|snapshot] ...
2913 * -H Scripted mode; elide headers and separate columns by tabs.
2914 * -p Display values in parsable (literal) format.
2915 * -r Recurse over all children.
2916 * -d Limit recursion by depth.
2917 * -o Control which fields to display.
2918 * -s Specify sort columns, descending order.
2919 * -S Specify sort columns, ascending order.
2920 * -t Control which object types to display.
2922 * When given no arguments, list all filesystems in the system.
2923 * Otherwise, list the specified datasets, optionally recursing down them if
2924 * '-r' is specified.
2926 typedef struct list_cbdata {
2927 boolean_t cb_first;
2928 boolean_t cb_literal;
2929 boolean_t cb_scripted;
2930 zprop_list_t *cb_proplist;
2931 } list_cbdata_t;
2934 * Given a list of columns to display, output appropriate headers for each one.
2936 static void
2937 print_header(list_cbdata_t *cb)
2939 zprop_list_t *pl = cb->cb_proplist;
2940 char headerbuf[ZFS_MAXPROPLEN];
2941 const char *header;
2942 int i;
2943 boolean_t first = B_TRUE;
2944 boolean_t right_justify;
2946 for (; pl != NULL; pl = pl->pl_next) {
2947 if (!first) {
2948 (void) printf(" ");
2949 } else {
2950 first = B_FALSE;
2953 right_justify = B_FALSE;
2954 if (pl->pl_prop != ZPROP_INVAL) {
2955 header = zfs_prop_column_name(pl->pl_prop);
2956 right_justify = zfs_prop_align_right(pl->pl_prop);
2957 } else {
2958 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
2959 headerbuf[i] = toupper(pl->pl_user_prop[i]);
2960 headerbuf[i] = '\0';
2961 header = headerbuf;
2964 if (pl->pl_next == NULL && !right_justify)
2965 (void) printf("%s", header);
2966 else if (right_justify)
2967 (void) printf("%*s", pl->pl_width, header);
2968 else
2969 (void) printf("%-*s", pl->pl_width, header);
2972 (void) printf("\n");
2976 * Given a dataset and a list of fields, print out all the properties according
2977 * to the described layout.
2979 static void
2980 print_dataset(zfs_handle_t *zhp, list_cbdata_t *cb)
2982 zprop_list_t *pl = cb->cb_proplist;
2983 boolean_t first = B_TRUE;
2984 char property[ZFS_MAXPROPLEN];
2985 nvlist_t *userprops = zfs_get_user_props(zhp);
2986 nvlist_t *propval;
2987 char *propstr;
2988 boolean_t right_justify;
2990 for (; pl != NULL; pl = pl->pl_next) {
2991 if (!first) {
2992 if (cb->cb_scripted)
2993 (void) printf("\t");
2994 else
2995 (void) printf(" ");
2996 } else {
2997 first = B_FALSE;
3000 if (pl->pl_prop == ZFS_PROP_NAME) {
3001 (void) strlcpy(property, zfs_get_name(zhp),
3002 sizeof (property));
3003 propstr = property;
3004 right_justify = zfs_prop_align_right(pl->pl_prop);
3005 } else if (pl->pl_prop != ZPROP_INVAL) {
3006 if (zfs_prop_get(zhp, pl->pl_prop, property,
3007 sizeof (property), NULL, NULL, 0,
3008 cb->cb_literal) != 0)
3009 propstr = "-";
3010 else
3011 propstr = property;
3012 right_justify = zfs_prop_align_right(pl->pl_prop);
3013 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
3014 if (zfs_prop_get_userquota(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 if (zfs_prop_written(pl->pl_user_prop)) {
3021 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
3022 property, sizeof (property), cb->cb_literal) != 0)
3023 propstr = "-";
3024 else
3025 propstr = property;
3026 right_justify = B_TRUE;
3027 } else {
3028 if (nvlist_lookup_nvlist(userprops,
3029 pl->pl_user_prop, &propval) != 0)
3030 propstr = "-";
3031 else
3032 verify(nvlist_lookup_string(propval,
3033 ZPROP_VALUE, &propstr) == 0);
3034 right_justify = B_FALSE;
3038 * If this is being called in scripted mode, or if this is the
3039 * last column and it is left-justified, don't include a width
3040 * format specifier.
3042 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
3043 (void) printf("%s", propstr);
3044 else if (right_justify)
3045 (void) printf("%*s", pl->pl_width, propstr);
3046 else
3047 (void) printf("%-*s", pl->pl_width, propstr);
3050 (void) printf("\n");
3054 * Generic callback function to list a dataset or snapshot.
3056 static int
3057 list_callback(zfs_handle_t *zhp, void *data)
3059 list_cbdata_t *cbp = data;
3061 if (cbp->cb_first) {
3062 if (!cbp->cb_scripted)
3063 print_header(cbp);
3064 cbp->cb_first = B_FALSE;
3067 print_dataset(zhp, cbp);
3069 return (0);
3072 static int
3073 zfs_do_list(int argc, char **argv)
3075 int c;
3076 static char default_fields[] =
3077 "name,used,available,referenced,mountpoint";
3078 int types = ZFS_TYPE_DATASET;
3079 boolean_t types_specified = B_FALSE;
3080 char *fields = NULL;
3081 list_cbdata_t cb = { 0 };
3082 char *value;
3083 int limit = 0;
3084 int ret = 0;
3085 zfs_sort_column_t *sortcol = NULL;
3086 int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
3088 /* check options */
3089 while ((c = getopt(argc, argv, "HS:d:o:prs:t:")) != -1) {
3090 switch (c) {
3091 case 'o':
3092 fields = optarg;
3093 break;
3094 case 'p':
3095 cb.cb_literal = B_TRUE;
3096 flags |= ZFS_ITER_LITERAL_PROPS;
3097 break;
3098 case 'd':
3099 limit = parse_depth(optarg, &flags);
3100 break;
3101 case 'r':
3102 flags |= ZFS_ITER_RECURSE;
3103 break;
3104 case 'H':
3105 cb.cb_scripted = B_TRUE;
3106 break;
3107 case 's':
3108 if (zfs_add_sort_column(&sortcol, optarg,
3109 B_FALSE) != 0) {
3110 (void) fprintf(stderr,
3111 gettext("invalid property '%s'\n"), optarg);
3112 usage(B_FALSE);
3114 break;
3115 case 'S':
3116 if (zfs_add_sort_column(&sortcol, optarg,
3117 B_TRUE) != 0) {
3118 (void) fprintf(stderr,
3119 gettext("invalid property '%s'\n"), optarg);
3120 usage(B_FALSE);
3122 break;
3123 case 't':
3124 types = 0;
3125 types_specified = B_TRUE;
3126 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
3127 while (*optarg != '\0') {
3128 static char *type_subopts[] = { "filesystem",
3129 "volume", "snapshot", "snap", "bookmark",
3130 "all", NULL };
3132 switch (getsubopt(&optarg, type_subopts,
3133 &value)) {
3134 case 0:
3135 types |= ZFS_TYPE_FILESYSTEM;
3136 break;
3137 case 1:
3138 types |= ZFS_TYPE_VOLUME;
3139 break;
3140 case 2:
3141 case 3:
3142 types |= ZFS_TYPE_SNAPSHOT;
3143 break;
3144 case 4:
3145 types |= ZFS_TYPE_BOOKMARK;
3146 break;
3147 case 5:
3148 types = ZFS_TYPE_DATASET |
3149 ZFS_TYPE_BOOKMARK;
3150 break;
3151 default:
3152 (void) fprintf(stderr,
3153 gettext("invalid type '%s'\n"),
3154 value);
3155 usage(B_FALSE);
3158 break;
3159 case ':':
3160 (void) fprintf(stderr, gettext("missing argument for "
3161 "'%c' option\n"), optopt);
3162 usage(B_FALSE);
3163 break;
3164 case '?':
3165 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3166 optopt);
3167 usage(B_FALSE);
3171 argc -= optind;
3172 argv += optind;
3174 if (fields == NULL)
3175 fields = default_fields;
3178 * If we are only going to list snapshot names and sort by name,
3179 * then we can use faster version.
3181 if (strcmp(fields, "name") == 0 && zfs_sort_only_by_name(sortcol))
3182 flags |= ZFS_ITER_SIMPLE;
3185 * If "-o space" and no types were specified, don't display snapshots.
3187 if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3188 types &= ~ZFS_TYPE_SNAPSHOT;
3191 * If the user specifies '-o all', the zprop_get_list() doesn't
3192 * normally include the name of the dataset. For 'zfs list', we always
3193 * want this property to be first.
3195 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3196 != 0)
3197 usage(B_FALSE);
3199 cb.cb_first = B_TRUE;
3201 ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
3202 limit, list_callback, &cb);
3204 zprop_free_list(cb.cb_proplist);
3205 zfs_free_sort_columns(sortcol);
3207 if (ret == 0 && cb.cb_first && !cb.cb_scripted)
3208 (void) printf(gettext("no datasets available\n"));
3210 return (ret);
3214 * zfs rename [-f] <fs | snap | vol> <fs | snap | vol>
3215 * zfs rename [-f] -p <fs | vol> <fs | vol>
3216 * zfs rename -r <snap> <snap>
3218 * Renames the given dataset to another of the same type.
3220 * The '-p' flag creates all the non-existing ancestors of the target first.
3222 /* ARGSUSED */
3223 static int
3224 zfs_do_rename(int argc, char **argv)
3226 zfs_handle_t *zhp;
3227 int c;
3228 int ret = 0;
3229 boolean_t recurse = B_FALSE;
3230 boolean_t parents = B_FALSE;
3231 boolean_t force_unmount = B_FALSE;
3233 /* check options */
3234 while ((c = getopt(argc, argv, "prf")) != -1) {
3235 switch (c) {
3236 case 'p':
3237 parents = B_TRUE;
3238 break;
3239 case 'r':
3240 recurse = B_TRUE;
3241 break;
3242 case 'f':
3243 force_unmount = B_TRUE;
3244 break;
3245 case '?':
3246 default:
3247 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3248 optopt);
3249 usage(B_FALSE);
3253 argc -= optind;
3254 argv += optind;
3256 /* check number of arguments */
3257 if (argc < 1) {
3258 (void) fprintf(stderr, gettext("missing source dataset "
3259 "argument\n"));
3260 usage(B_FALSE);
3262 if (argc < 2) {
3263 (void) fprintf(stderr, gettext("missing target dataset "
3264 "argument\n"));
3265 usage(B_FALSE);
3267 if (argc > 2) {
3268 (void) fprintf(stderr, gettext("too many arguments\n"));
3269 usage(B_FALSE);
3272 if (recurse && parents) {
3273 (void) fprintf(stderr, gettext("-p and -r options are mutually "
3274 "exclusive\n"));
3275 usage(B_FALSE);
3278 if (recurse && strchr(argv[0], '@') == 0) {
3279 (void) fprintf(stderr, gettext("source dataset for recursive "
3280 "rename must be a snapshot\n"));
3281 usage(B_FALSE);
3284 if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
3285 ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
3286 return (1);
3288 /* If we were asked and the name looks good, try to create ancestors. */
3289 if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
3290 zfs_create_ancestors(g_zfs, argv[1]) != 0) {
3291 zfs_close(zhp);
3292 return (1);
3295 ret = (zfs_rename(zhp, argv[1], recurse, force_unmount) != 0);
3297 zfs_close(zhp);
3298 return (ret);
3302 * zfs promote <fs>
3304 * Promotes the given clone fs to be the parent
3306 /* ARGSUSED */
3307 static int
3308 zfs_do_promote(int argc, char **argv)
3310 zfs_handle_t *zhp;
3311 int ret = 0;
3313 /* check options */
3314 if (argc > 1 && argv[1][0] == '-') {
3315 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3316 argv[1][1]);
3317 usage(B_FALSE);
3320 /* check number of arguments */
3321 if (argc < 2) {
3322 (void) fprintf(stderr, gettext("missing clone filesystem"
3323 " argument\n"));
3324 usage(B_FALSE);
3326 if (argc > 2) {
3327 (void) fprintf(stderr, gettext("too many arguments\n"));
3328 usage(B_FALSE);
3331 zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3332 if (zhp == NULL)
3333 return (1);
3335 ret = (zfs_promote(zhp) != 0);
3338 zfs_close(zhp);
3339 return (ret);
3343 * zfs rollback [-rRf] <snapshot>
3345 * -r Delete any intervening snapshots before doing rollback
3346 * -R Delete any snapshots and their clones
3347 * -f ignored for backwards compatability
3349 * Given a filesystem, rollback to a specific snapshot, discarding any changes
3350 * since then and making it the active dataset. If more recent snapshots exist,
3351 * the command will complain unless the '-r' flag is given.
3353 typedef struct rollback_cbdata {
3354 uint64_t cb_create;
3355 boolean_t cb_first;
3356 int cb_doclones;
3357 char *cb_target;
3358 int cb_error;
3359 boolean_t cb_recurse;
3360 } rollback_cbdata_t;
3362 static int
3363 rollback_check_dependent(zfs_handle_t *zhp, void *data)
3365 rollback_cbdata_t *cbp = data;
3367 if (cbp->cb_first && cbp->cb_recurse) {
3368 (void) fprintf(stderr, gettext("cannot rollback to "
3369 "'%s': clones of previous snapshots exist\n"),
3370 cbp->cb_target);
3371 (void) fprintf(stderr, gettext("use '-R' to "
3372 "force deletion of the following clones and "
3373 "dependents:\n"));
3374 cbp->cb_first = 0;
3375 cbp->cb_error = 1;
3378 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
3380 zfs_close(zhp);
3381 return (0);
3385 * Report any snapshots more recent than the one specified. Used when '-r' is
3386 * not specified. We reuse this same callback for the snapshot dependents - if
3387 * 'cb_dependent' is set, then this is a dependent and we should report it
3388 * without checking the transaction group.
3390 static int
3391 rollback_check(zfs_handle_t *zhp, void *data)
3393 rollback_cbdata_t *cbp = data;
3395 if (cbp->cb_doclones) {
3396 zfs_close(zhp);
3397 return (0);
3400 if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
3401 if (cbp->cb_first && !cbp->cb_recurse) {
3402 (void) fprintf(stderr, gettext("cannot "
3403 "rollback to '%s': more recent snapshots "
3404 "or bookmarks exist\n"),
3405 cbp->cb_target);
3406 (void) fprintf(stderr, gettext("use '-r' to "
3407 "force deletion of the following "
3408 "snapshots and bookmarks:\n"));
3409 cbp->cb_first = 0;
3410 cbp->cb_error = 1;
3413 if (cbp->cb_recurse) {
3414 if (zfs_iter_dependents(zhp, B_TRUE,
3415 rollback_check_dependent, cbp) != 0) {
3416 zfs_close(zhp);
3417 return (-1);
3419 } else {
3420 (void) fprintf(stderr, "%s\n",
3421 zfs_get_name(zhp));
3424 zfs_close(zhp);
3425 return (0);
3428 static int
3429 zfs_do_rollback(int argc, char **argv)
3431 int ret = 0;
3432 int c;
3433 boolean_t force = B_FALSE;
3434 rollback_cbdata_t cb = { 0 };
3435 zfs_handle_t *zhp, *snap;
3436 char parentname[ZFS_MAX_DATASET_NAME_LEN];
3437 char *delim;
3439 /* check options */
3440 while ((c = getopt(argc, argv, "rRf")) != -1) {
3441 switch (c) {
3442 case 'r':
3443 cb.cb_recurse = 1;
3444 break;
3445 case 'R':
3446 cb.cb_recurse = 1;
3447 cb.cb_doclones = 1;
3448 break;
3449 case 'f':
3450 force = B_TRUE;
3451 break;
3452 case '?':
3453 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3454 optopt);
3455 usage(B_FALSE);
3459 argc -= optind;
3460 argv += optind;
3462 /* check number of arguments */
3463 if (argc < 1) {
3464 (void) fprintf(stderr, gettext("missing dataset argument\n"));
3465 usage(B_FALSE);
3467 if (argc > 1) {
3468 (void) fprintf(stderr, gettext("too many arguments\n"));
3469 usage(B_FALSE);
3472 /* open the snapshot */
3473 if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
3474 return (1);
3476 /* open the parent dataset */
3477 (void) strlcpy(parentname, argv[0], sizeof (parentname));
3478 verify((delim = strrchr(parentname, '@')) != NULL);
3479 *delim = '\0';
3480 if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
3481 zfs_close(snap);
3482 return (1);
3486 * Check for more recent snapshots and/or clones based on the presence
3487 * of '-r' and '-R'.
3489 cb.cb_target = argv[0];
3490 cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3491 cb.cb_first = B_TRUE;
3492 cb.cb_error = 0;
3493 if ((ret = zfs_iter_snapshots(zhp, B_FALSE, rollback_check, &cb)) != 0)
3494 goto out;
3495 if ((ret = zfs_iter_bookmarks(zhp, rollback_check, &cb)) != 0)
3496 goto out;
3498 if ((ret = cb.cb_error) != 0)
3499 goto out;
3502 * Rollback parent to the given snapshot.
3504 ret = zfs_rollback(zhp, snap, force);
3506 out:
3507 zfs_close(snap);
3508 zfs_close(zhp);
3510 if (ret == 0)
3511 return (0);
3512 else
3513 return (1);
3517 * zfs set property=value ... { fs | snap | vol } ...
3519 * Sets the given properties for all datasets specified on the command line.
3522 static int
3523 set_callback(zfs_handle_t *zhp, void *data)
3525 nvlist_t *props = data;
3527 if (zfs_prop_set_list(zhp, props) != 0) {
3528 switch (libzfs_errno(g_zfs)) {
3529 case EZFS_MOUNTFAILED:
3530 (void) fprintf(stderr, gettext("property may be set "
3531 "but unable to remount filesystem\n"));
3532 break;
3533 case EZFS_SHARENFSFAILED:
3534 (void) fprintf(stderr, gettext("property may be set "
3535 "but unable to reshare filesystem\n"));
3536 break;
3538 return (1);
3540 return (0);
3543 static int
3544 zfs_do_set(int argc, char **argv)
3546 nvlist_t *props = NULL;
3547 int ds_start = -1; /* argv idx of first dataset arg */
3548 int ret = 0;
3550 /* check for options */
3551 if (argc > 1 && argv[1][0] == '-') {
3552 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3553 argv[1][1]);
3554 usage(B_FALSE);
3557 /* check number of arguments */
3558 if (argc < 2) {
3559 (void) fprintf(stderr, gettext("missing arguments\n"));
3560 usage(B_FALSE);
3562 if (argc < 3) {
3563 if (strchr(argv[1], '=') == NULL) {
3564 (void) fprintf(stderr, gettext("missing property=value "
3565 "argument(s)\n"));
3566 } else {
3567 (void) fprintf(stderr, gettext("missing dataset "
3568 "name(s)\n"));
3570 usage(B_FALSE);
3573 /* validate argument order: prop=val args followed by dataset args */
3574 for (int i = 1; i < argc; i++) {
3575 if (strchr(argv[i], '=') != NULL) {
3576 if (ds_start > 0) {
3577 /* out-of-order prop=val argument */
3578 (void) fprintf(stderr, gettext("invalid "
3579 "argument order\n"), i);
3580 usage(B_FALSE);
3582 } else if (ds_start < 0) {
3583 ds_start = i;
3586 if (ds_start < 0) {
3587 (void) fprintf(stderr, gettext("missing dataset name(s)\n"));
3588 usage(B_FALSE);
3591 /* Populate a list of property settings */
3592 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3593 nomem();
3594 for (int i = 1; i < ds_start; i++) {
3595 if ((ret = parseprop(props, argv[i])) != 0)
3596 goto error;
3599 ret = zfs_for_each(argc - ds_start, argv + ds_start, 0,
3600 ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, props);
3602 error:
3603 nvlist_free(props);
3604 return (ret);
3607 typedef struct snap_cbdata {
3608 nvlist_t *sd_nvl;
3609 boolean_t sd_recursive;
3610 const char *sd_snapname;
3611 } snap_cbdata_t;
3613 static int
3614 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
3616 snap_cbdata_t *sd = arg;
3617 char *name;
3618 int rv = 0;
3619 int error;
3621 if (sd->sd_recursive &&
3622 zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
3623 zfs_close(zhp);
3624 return (0);
3627 error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
3628 if (error == -1)
3629 nomem();
3630 fnvlist_add_boolean(sd->sd_nvl, name);
3631 free(name);
3633 if (sd->sd_recursive)
3634 rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
3635 zfs_close(zhp);
3636 return (rv);
3640 * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
3642 * Creates a snapshot with the given name. While functionally equivalent to
3643 * 'zfs create', it is a separate command to differentiate intent.
3645 static int
3646 zfs_do_snapshot(int argc, char **argv)
3648 int ret = 0;
3649 char c;
3650 nvlist_t *props;
3651 snap_cbdata_t sd = { 0 };
3652 boolean_t multiple_snaps = B_FALSE;
3654 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3655 nomem();
3656 if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
3657 nomem();
3659 /* check options */
3660 while ((c = getopt(argc, argv, "ro:")) != -1) {
3661 switch (c) {
3662 case 'o':
3663 if (parseprop(props, optarg) != 0)
3664 return (1);
3665 break;
3666 case 'r':
3667 sd.sd_recursive = B_TRUE;
3668 multiple_snaps = B_TRUE;
3669 break;
3670 case '?':
3671 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3672 optopt);
3673 goto usage;
3677 argc -= optind;
3678 argv += optind;
3680 /* check number of arguments */
3681 if (argc < 1) {
3682 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3683 goto usage;
3686 if (argc > 1)
3687 multiple_snaps = B_TRUE;
3688 for (; argc > 0; argc--, argv++) {
3689 char *atp;
3690 zfs_handle_t *zhp;
3692 atp = strchr(argv[0], '@');
3693 if (atp == NULL)
3694 goto usage;
3695 *atp = '\0';
3696 sd.sd_snapname = atp + 1;
3697 zhp = zfs_open(g_zfs, argv[0],
3698 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3699 if (zhp == NULL)
3700 goto usage;
3701 if (zfs_snapshot_cb(zhp, &sd) != 0)
3702 goto usage;
3705 ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
3706 nvlist_free(sd.sd_nvl);
3707 nvlist_free(props);
3708 if (ret != 0 && multiple_snaps)
3709 (void) fprintf(stderr, gettext("no snapshots were created\n"));
3710 return (ret != 0);
3712 usage:
3713 nvlist_free(sd.sd_nvl);
3714 nvlist_free(props);
3715 usage(B_FALSE);
3716 return (-1);
3720 * Send a backup stream to stdout.
3722 static int
3723 zfs_do_send(int argc, char **argv)
3725 char *fromname = NULL;
3726 char *toname = NULL;
3727 char *resume_token = NULL;
3728 char *cp;
3729 zfs_handle_t *zhp;
3730 sendflags_t flags = { 0 };
3731 int c, err;
3732 nvlist_t *dbgnv = NULL;
3733 boolean_t extraverbose = B_FALSE;
3735 struct option long_options[] = {
3736 {"replicate", no_argument, NULL, 'R'},
3737 {"props", no_argument, NULL, 'p'},
3738 {"parsable", no_argument, NULL, 'P'},
3739 {"dedup", no_argument, NULL, 'D'},
3740 {"verbose", no_argument, NULL, 'v'},
3741 {"dryrun", no_argument, NULL, 'n'},
3742 {"large-block", no_argument, NULL, 'L'},
3743 {"embed", no_argument, NULL, 'e'},
3744 {"resume", required_argument, NULL, 't'},
3745 {"compressed", no_argument, NULL, 'c'},
3746 {0, 0, 0, 0}
3749 /* check options */
3750 while ((c = getopt_long(argc, argv, ":i:I:RbDpvnPLet:c", long_options,
3751 NULL)) != -1) {
3752 switch (c) {
3753 case 'i':
3754 if (fromname)
3755 usage(B_FALSE);
3756 fromname = optarg;
3757 break;
3758 case 'I':
3759 if (fromname)
3760 usage(B_FALSE);
3761 fromname = optarg;
3762 flags.doall = B_TRUE;
3763 break;
3764 case 'R':
3765 flags.replicate = B_TRUE;
3766 break;
3767 case 'p':
3768 flags.props = B_TRUE;
3769 break;
3770 case 'P':
3771 flags.parsable = B_TRUE;
3772 flags.verbose = B_TRUE;
3773 break;
3774 case 'v':
3775 if (flags.verbose)
3776 extraverbose = B_TRUE;
3777 flags.verbose = B_TRUE;
3778 flags.progress = B_TRUE;
3779 break;
3780 case 'D':
3781 flags.dedup = B_TRUE;
3782 break;
3783 case 'n':
3784 flags.dryrun = B_TRUE;
3785 break;
3786 case 'L':
3787 flags.largeblock = B_TRUE;
3788 break;
3789 case 'e':
3790 flags.embed_data = B_TRUE;
3791 break;
3792 case 't':
3793 resume_token = optarg;
3794 break;
3795 case 'c':
3796 flags.compress = B_TRUE;
3797 break;
3798 case ':':
3800 * If a parameter was not passed, optopt contains the
3801 * value that would normally lead us into the
3802 * appropriate case statement. If it's > 256, then this
3803 * must be a longopt and we should look at argv to get
3804 * the string. Otherwise it's just the character, so we
3805 * should use it directly.
3807 if (optopt <= UINT8_MAX) {
3808 (void) fprintf(stderr,
3809 gettext("missing argument for '%c' "
3810 "option\n"), optopt);
3811 } else {
3812 (void) fprintf(stderr,
3813 gettext("missing argument for '%s' "
3814 "option\n"), argv[optind - 1]);
3816 usage(B_FALSE);
3817 break;
3818 case '?':
3819 /*FALLTHROUGH*/
3820 default:
3822 * If an invalid flag was passed, optopt contains the
3823 * character if it was a short flag, or 0 if it was a
3824 * longopt.
3826 if (optopt != 0) {
3827 (void) fprintf(stderr,
3828 gettext("invalid option '%c'\n"), optopt);
3829 } else {
3830 (void) fprintf(stderr,
3831 gettext("invalid option '%s'\n"),
3832 argv[optind - 1]);
3835 usage(B_FALSE);
3839 argc -= optind;
3840 argv += optind;
3842 if (resume_token != NULL) {
3843 if (fromname != NULL || flags.replicate || flags.props ||
3844 flags.dedup) {
3845 (void) fprintf(stderr,
3846 gettext("invalid flags combined with -t\n"));
3847 usage(B_FALSE);
3849 if (argc != 0) {
3850 (void) fprintf(stderr, gettext("no additional "
3851 "arguments are permitted with -t\n"));
3852 usage(B_FALSE);
3854 } else {
3855 if (argc < 1) {
3856 (void) fprintf(stderr,
3857 gettext("missing snapshot argument\n"));
3858 usage(B_FALSE);
3860 if (argc > 1) {
3861 (void) fprintf(stderr, gettext("too many arguments\n"));
3862 usage(B_FALSE);
3866 if (!flags.dryrun && isatty(STDOUT_FILENO)) {
3867 (void) fprintf(stderr,
3868 gettext("Error: Stream can not be written to a terminal.\n"
3869 "You must redirect standard output.\n"));
3870 return (1);
3873 if (resume_token != NULL) {
3874 return (zfs_send_resume(g_zfs, &flags, STDOUT_FILENO,
3875 resume_token));
3879 * Special case sending a filesystem, or from a bookmark.
3881 if (strchr(argv[0], '@') == NULL ||
3882 (fromname && strchr(fromname, '#') != NULL)) {
3883 char frombuf[ZFS_MAX_DATASET_NAME_LEN];
3884 enum lzc_send_flags lzc_flags = 0;
3886 if (flags.replicate || flags.doall || flags.props ||
3887 flags.dedup || flags.dryrun || flags.verbose ||
3888 flags.progress) {
3889 (void) fprintf(stderr,
3890 gettext("Error: "
3891 "Unsupported flag with filesystem or bookmark.\n"));
3892 return (1);
3895 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
3896 if (zhp == NULL)
3897 return (1);
3899 if (flags.largeblock)
3900 lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
3901 if (flags.embed_data)
3902 lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
3903 if (flags.compress)
3904 lzc_flags |= LZC_SEND_FLAG_COMPRESS;
3906 if (fromname != NULL &&
3907 (fromname[0] == '#' || fromname[0] == '@')) {
3909 * Incremental source name begins with # or @.
3910 * Default to same fs as target.
3912 (void) strncpy(frombuf, argv[0], sizeof (frombuf));
3913 cp = strchr(frombuf, '@');
3914 if (cp != NULL)
3915 *cp = '\0';
3916 (void) strlcat(frombuf, fromname, sizeof (frombuf));
3917 fromname = frombuf;
3919 err = zfs_send_one(zhp, fromname, STDOUT_FILENO, lzc_flags);
3920 zfs_close(zhp);
3921 return (err != 0);
3924 cp = strchr(argv[0], '@');
3925 *cp = '\0';
3926 toname = cp + 1;
3927 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3928 if (zhp == NULL)
3929 return (1);
3932 * If they specified the full path to the snapshot, chop off
3933 * everything except the short name of the snapshot, but special
3934 * case if they specify the origin.
3936 if (fromname && (cp = strchr(fromname, '@')) != NULL) {
3937 char origin[ZFS_MAX_DATASET_NAME_LEN];
3938 zprop_source_t src;
3940 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
3941 origin, sizeof (origin), &src, NULL, 0, B_FALSE);
3943 if (strcmp(origin, fromname) == 0) {
3944 fromname = NULL;
3945 flags.fromorigin = B_TRUE;
3946 } else {
3947 *cp = '\0';
3948 if (cp != fromname && strcmp(argv[0], fromname)) {
3949 (void) fprintf(stderr,
3950 gettext("incremental source must be "
3951 "in same filesystem\n"));
3952 usage(B_FALSE);
3954 fromname = cp + 1;
3955 if (strchr(fromname, '@') || strchr(fromname, '/')) {
3956 (void) fprintf(stderr,
3957 gettext("invalid incremental source\n"));
3958 usage(B_FALSE);
3963 if (flags.replicate && fromname == NULL)
3964 flags.doall = B_TRUE;
3966 err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
3967 extraverbose ? &dbgnv : NULL);
3969 if (extraverbose && dbgnv != NULL) {
3971 * dump_nvlist prints to stdout, but that's been
3972 * redirected to a file. Make it print to stderr
3973 * instead.
3975 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
3976 dump_nvlist(dbgnv, 0);
3977 nvlist_free(dbgnv);
3979 zfs_close(zhp);
3981 return (err != 0);
3985 * Restore a backup stream from stdin.
3987 static int
3988 zfs_do_receive(int argc, char **argv)
3990 int c, err = 0;
3991 recvflags_t flags = { 0 };
3992 boolean_t abort_resumable = B_FALSE;
3994 nvlist_t *props;
3995 nvpair_t *nvp = NULL;
3997 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3998 nomem();
4000 /* check options */
4001 while ((c = getopt(argc, argv, ":o:denuvFsA")) != -1) {
4002 switch (c) {
4003 case 'o':
4004 if (parseprop(props, optarg) != 0)
4005 return (1);
4006 break;
4007 case 'd':
4008 flags.isprefix = B_TRUE;
4009 break;
4010 case 'e':
4011 flags.isprefix = B_TRUE;
4012 flags.istail = B_TRUE;
4013 break;
4014 case 'n':
4015 flags.dryrun = B_TRUE;
4016 break;
4017 case 'u':
4018 flags.nomount = B_TRUE;
4019 break;
4020 case 'v':
4021 flags.verbose = B_TRUE;
4022 break;
4023 case 's':
4024 flags.resumable = B_TRUE;
4025 break;
4026 case 'F':
4027 flags.force = B_TRUE;
4028 break;
4029 case 'A':
4030 abort_resumable = B_TRUE;
4031 break;
4032 case ':':
4033 (void) fprintf(stderr, gettext("missing argument for "
4034 "'%c' option\n"), optopt);
4035 usage(B_FALSE);
4036 break;
4037 case '?':
4038 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4039 optopt);
4040 usage(B_FALSE);
4044 argc -= optind;
4045 argv += optind;
4047 /* check number of arguments */
4048 if (argc < 1) {
4049 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
4050 usage(B_FALSE);
4052 if (argc > 1) {
4053 (void) fprintf(stderr, gettext("too many arguments\n"));
4054 usage(B_FALSE);
4057 while ((nvp = nvlist_next_nvpair(props, nvp))) {
4058 if (strcmp(nvpair_name(nvp), "origin") != 0) {
4059 (void) fprintf(stderr, gettext("invalid option"));
4060 usage(B_FALSE);
4064 if (abort_resumable) {
4065 if (flags.isprefix || flags.istail || flags.dryrun ||
4066 flags.resumable || flags.nomount) {
4067 (void) fprintf(stderr, gettext("invalid option"));
4068 usage(B_FALSE);
4071 char namebuf[ZFS_MAX_DATASET_NAME_LEN];
4072 (void) snprintf(namebuf, sizeof (namebuf),
4073 "%s/%%recv", argv[0]);
4075 if (zfs_dataset_exists(g_zfs, namebuf,
4076 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) {
4077 zfs_handle_t *zhp = zfs_open(g_zfs,
4078 namebuf, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4079 if (zhp == NULL)
4080 return (1);
4081 err = zfs_destroy(zhp, B_FALSE);
4082 } else {
4083 zfs_handle_t *zhp = zfs_open(g_zfs,
4084 argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4085 if (zhp == NULL)
4086 usage(B_FALSE);
4087 if (!zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) ||
4088 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
4089 NULL, 0, NULL, NULL, 0, B_TRUE) == -1) {
4090 (void) fprintf(stderr,
4091 gettext("'%s' does not have any "
4092 "resumable receive state to abort\n"),
4093 argv[0]);
4094 return (1);
4096 err = zfs_destroy(zhp, B_FALSE);
4099 return (err != 0);
4102 if (isatty(STDIN_FILENO)) {
4103 (void) fprintf(stderr,
4104 gettext("Error: Backup stream can not be read "
4105 "from a terminal.\n"
4106 "You must redirect standard input.\n"));
4107 return (1);
4109 err = zfs_receive(g_zfs, argv[0], props, &flags, STDIN_FILENO, NULL);
4111 return (err != 0);
4115 * allow/unallow stuff
4117 /* copied from zfs/sys/dsl_deleg.h */
4118 #define ZFS_DELEG_PERM_CREATE "create"
4119 #define ZFS_DELEG_PERM_DESTROY "destroy"
4120 #define ZFS_DELEG_PERM_SNAPSHOT "snapshot"
4121 #define ZFS_DELEG_PERM_ROLLBACK "rollback"
4122 #define ZFS_DELEG_PERM_CLONE "clone"
4123 #define ZFS_DELEG_PERM_PROMOTE "promote"
4124 #define ZFS_DELEG_PERM_RENAME "rename"
4125 #define ZFS_DELEG_PERM_MOUNT "mount"
4126 #define ZFS_DELEG_PERM_SHARE "share"
4127 #define ZFS_DELEG_PERM_SEND "send"
4128 #define ZFS_DELEG_PERM_RECEIVE "receive"
4129 #define ZFS_DELEG_PERM_ALLOW "allow"
4130 #define ZFS_DELEG_PERM_USERPROP "userprop"
4131 #define ZFS_DELEG_PERM_VSCAN "vscan" /* ??? */
4132 #define ZFS_DELEG_PERM_USERQUOTA "userquota"
4133 #define ZFS_DELEG_PERM_GROUPQUOTA "groupquota"
4134 #define ZFS_DELEG_PERM_USERUSED "userused"
4135 #define ZFS_DELEG_PERM_GROUPUSED "groupused"
4136 #define ZFS_DELEG_PERM_HOLD "hold"
4137 #define ZFS_DELEG_PERM_RELEASE "release"
4138 #define ZFS_DELEG_PERM_DIFF "diff"
4139 #define ZFS_DELEG_PERM_BOOKMARK "bookmark"
4140 #define ZFS_DELEG_PERM_REMAP "remap"
4142 #define ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
4144 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
4145 { ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
4146 { ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
4147 { ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
4148 { ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
4149 { ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
4150 { ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
4151 { ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
4152 { ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
4153 { ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
4154 { ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
4155 { ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
4156 { ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
4157 { ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
4158 { ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
4159 { ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
4160 { ZFS_DELEG_PERM_BOOKMARK, ZFS_DELEG_NOTE_BOOKMARK },
4161 { ZFS_DELEG_PERM_REMAP, ZFS_DELEG_NOTE_REMAP },
4163 { ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
4164 { ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
4165 { ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
4166 { ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
4167 { ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
4168 { NULL, ZFS_DELEG_NOTE_NONE }
4171 /* permission structure */
4172 typedef struct deleg_perm {
4173 zfs_deleg_who_type_t dp_who_type;
4174 const char *dp_name;
4175 boolean_t dp_local;
4176 boolean_t dp_descend;
4177 } deleg_perm_t;
4179 /* */
4180 typedef struct deleg_perm_node {
4181 deleg_perm_t dpn_perm;
4183 uu_avl_node_t dpn_avl_node;
4184 } deleg_perm_node_t;
4186 typedef struct fs_perm fs_perm_t;
4188 /* permissions set */
4189 typedef struct who_perm {
4190 zfs_deleg_who_type_t who_type;
4191 const char *who_name; /* id */
4192 char who_ug_name[256]; /* user/group name */
4193 fs_perm_t *who_fsperm; /* uplink */
4195 uu_avl_t *who_deleg_perm_avl; /* permissions */
4196 } who_perm_t;
4198 /* */
4199 typedef struct who_perm_node {
4200 who_perm_t who_perm;
4201 uu_avl_node_t who_avl_node;
4202 } who_perm_node_t;
4204 typedef struct fs_perm_set fs_perm_set_t;
4205 /* fs permissions */
4206 struct fs_perm {
4207 const char *fsp_name;
4209 uu_avl_t *fsp_sc_avl; /* sets,create */
4210 uu_avl_t *fsp_uge_avl; /* user,group,everyone */
4212 fs_perm_set_t *fsp_set; /* uplink */
4215 /* */
4216 typedef struct fs_perm_node {
4217 fs_perm_t fspn_fsperm;
4218 uu_avl_t *fspn_avl;
4220 uu_list_node_t fspn_list_node;
4221 } fs_perm_node_t;
4223 /* top level structure */
4224 struct fs_perm_set {
4225 uu_list_pool_t *fsps_list_pool;
4226 uu_list_t *fsps_list; /* list of fs_perms */
4228 uu_avl_pool_t *fsps_named_set_avl_pool;
4229 uu_avl_pool_t *fsps_who_perm_avl_pool;
4230 uu_avl_pool_t *fsps_deleg_perm_avl_pool;
4233 static inline const char *
4234 deleg_perm_type(zfs_deleg_note_t note)
4236 /* subcommands */
4237 switch (note) {
4238 /* SUBCOMMANDS */
4239 /* OTHER */
4240 case ZFS_DELEG_NOTE_GROUPQUOTA:
4241 case ZFS_DELEG_NOTE_GROUPUSED:
4242 case ZFS_DELEG_NOTE_USERPROP:
4243 case ZFS_DELEG_NOTE_USERQUOTA:
4244 case ZFS_DELEG_NOTE_USERUSED:
4245 /* other */
4246 return (gettext("other"));
4247 default:
4248 return (gettext("subcommand"));
4252 static int
4253 who_type2weight(zfs_deleg_who_type_t who_type)
4255 int res;
4256 switch (who_type) {
4257 case ZFS_DELEG_NAMED_SET_SETS:
4258 case ZFS_DELEG_NAMED_SET:
4259 res = 0;
4260 break;
4261 case ZFS_DELEG_CREATE_SETS:
4262 case ZFS_DELEG_CREATE:
4263 res = 1;
4264 break;
4265 case ZFS_DELEG_USER_SETS:
4266 case ZFS_DELEG_USER:
4267 res = 2;
4268 break;
4269 case ZFS_DELEG_GROUP_SETS:
4270 case ZFS_DELEG_GROUP:
4271 res = 3;
4272 break;
4273 case ZFS_DELEG_EVERYONE_SETS:
4274 case ZFS_DELEG_EVERYONE:
4275 res = 4;
4276 break;
4277 default:
4278 res = -1;
4281 return (res);
4284 /* ARGSUSED */
4285 static int
4286 who_perm_compare(const void *larg, const void *rarg, void *unused)
4288 const who_perm_node_t *l = larg;
4289 const who_perm_node_t *r = rarg;
4290 zfs_deleg_who_type_t ltype = l->who_perm.who_type;
4291 zfs_deleg_who_type_t rtype = r->who_perm.who_type;
4292 int lweight = who_type2weight(ltype);
4293 int rweight = who_type2weight(rtype);
4294 int res = lweight - rweight;
4295 if (res == 0)
4296 res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
4297 ZFS_MAX_DELEG_NAME-1);
4299 if (res == 0)
4300 return (0);
4301 if (res > 0)
4302 return (1);
4303 else
4304 return (-1);
4307 /* ARGSUSED */
4308 static int
4309 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
4311 const deleg_perm_node_t *l = larg;
4312 const deleg_perm_node_t *r = rarg;
4313 int res = strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
4314 ZFS_MAX_DELEG_NAME-1);
4316 if (res == 0)
4317 return (0);
4319 if (res > 0)
4320 return (1);
4321 else
4322 return (-1);
4325 static inline void
4326 fs_perm_set_init(fs_perm_set_t *fspset)
4328 bzero(fspset, sizeof (fs_perm_set_t));
4330 if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
4331 sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
4332 NULL, UU_DEFAULT)) == NULL)
4333 nomem();
4334 if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
4335 UU_DEFAULT)) == NULL)
4336 nomem();
4338 if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
4339 "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
4340 who_perm_node_t, who_avl_node), who_perm_compare,
4341 UU_DEFAULT)) == NULL)
4342 nomem();
4344 if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
4345 "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
4346 who_perm_node_t, who_avl_node), who_perm_compare,
4347 UU_DEFAULT)) == NULL)
4348 nomem();
4350 if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
4351 "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
4352 deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
4353 == NULL)
4354 nomem();
4357 static inline void fs_perm_fini(fs_perm_t *);
4358 static inline void who_perm_fini(who_perm_t *);
4360 static inline void
4361 fs_perm_set_fini(fs_perm_set_t *fspset)
4363 fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
4365 while (node != NULL) {
4366 fs_perm_node_t *next_node =
4367 uu_list_next(fspset->fsps_list, node);
4368 fs_perm_t *fsperm = &node->fspn_fsperm;
4369 fs_perm_fini(fsperm);
4370 uu_list_remove(fspset->fsps_list, node);
4371 free(node);
4372 node = next_node;
4375 uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
4376 uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
4377 uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
4380 static inline void
4381 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
4382 const char *name)
4384 deleg_perm->dp_who_type = type;
4385 deleg_perm->dp_name = name;
4388 static inline void
4389 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
4390 zfs_deleg_who_type_t type, const char *name)
4392 uu_avl_pool_t *pool;
4393 pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
4395 bzero(who_perm, sizeof (who_perm_t));
4397 if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
4398 UU_DEFAULT)) == NULL)
4399 nomem();
4401 who_perm->who_type = type;
4402 who_perm->who_name = name;
4403 who_perm->who_fsperm = fsperm;
4406 static inline void
4407 who_perm_fini(who_perm_t *who_perm)
4409 deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
4411 while (node != NULL) {
4412 deleg_perm_node_t *next_node =
4413 uu_avl_next(who_perm->who_deleg_perm_avl, node);
4415 uu_avl_remove(who_perm->who_deleg_perm_avl, node);
4416 free(node);
4417 node = next_node;
4420 uu_avl_destroy(who_perm->who_deleg_perm_avl);
4423 static inline void
4424 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
4426 uu_avl_pool_t *nset_pool = fspset->fsps_named_set_avl_pool;
4427 uu_avl_pool_t *who_pool = fspset->fsps_who_perm_avl_pool;
4429 bzero(fsperm, sizeof (fs_perm_t));
4431 if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
4432 == NULL)
4433 nomem();
4435 if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
4436 == NULL)
4437 nomem();
4439 fsperm->fsp_set = fspset;
4440 fsperm->fsp_name = fsname;
4443 static inline void
4444 fs_perm_fini(fs_perm_t *fsperm)
4446 who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
4447 while (node != NULL) {
4448 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
4449 node);
4450 who_perm_t *who_perm = &node->who_perm;
4451 who_perm_fini(who_perm);
4452 uu_avl_remove(fsperm->fsp_sc_avl, node);
4453 free(node);
4454 node = next_node;
4457 node = uu_avl_first(fsperm->fsp_uge_avl);
4458 while (node != NULL) {
4459 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
4460 node);
4461 who_perm_t *who_perm = &node->who_perm;
4462 who_perm_fini(who_perm);
4463 uu_avl_remove(fsperm->fsp_uge_avl, node);
4464 free(node);
4465 node = next_node;
4468 uu_avl_destroy(fsperm->fsp_sc_avl);
4469 uu_avl_destroy(fsperm->fsp_uge_avl);
4472 static void
4473 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
4474 zfs_deleg_who_type_t who_type, const char *name, char locality)
4476 uu_avl_index_t idx = 0;
4478 deleg_perm_node_t *found_node = NULL;
4479 deleg_perm_t *deleg_perm = &node->dpn_perm;
4481 deleg_perm_init(deleg_perm, who_type, name);
4483 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4484 == NULL)
4485 uu_avl_insert(avl, node, idx);
4486 else {
4487 node = found_node;
4488 deleg_perm = &node->dpn_perm;
4492 switch (locality) {
4493 case ZFS_DELEG_LOCAL:
4494 deleg_perm->dp_local = B_TRUE;
4495 break;
4496 case ZFS_DELEG_DESCENDENT:
4497 deleg_perm->dp_descend = B_TRUE;
4498 break;
4499 case ZFS_DELEG_NA:
4500 break;
4501 default:
4502 assert(B_FALSE); /* invalid locality */
4506 static inline int
4507 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
4509 nvpair_t *nvp = NULL;
4510 fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
4511 uu_avl_t *avl = who_perm->who_deleg_perm_avl;
4512 zfs_deleg_who_type_t who_type = who_perm->who_type;
4514 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4515 const char *name = nvpair_name(nvp);
4516 data_type_t type = nvpair_type(nvp);
4517 uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
4518 deleg_perm_node_t *node =
4519 safe_malloc(sizeof (deleg_perm_node_t));
4521 assert(type == DATA_TYPE_BOOLEAN);
4523 uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
4524 set_deleg_perm_node(avl, node, who_type, name, locality);
4527 return (0);
4530 static inline int
4531 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
4533 nvpair_t *nvp = NULL;
4534 fs_perm_set_t *fspset = fsperm->fsp_set;
4536 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4537 nvlist_t *nvl2 = NULL;
4538 const char *name = nvpair_name(nvp);
4539 uu_avl_t *avl = NULL;
4540 uu_avl_pool_t *avl_pool = NULL;
4541 zfs_deleg_who_type_t perm_type = name[0];
4542 char perm_locality = name[1];
4543 const char *perm_name = name + 3;
4544 boolean_t is_set = B_TRUE;
4545 who_perm_t *who_perm = NULL;
4547 assert('$' == name[2]);
4549 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4550 return (-1);
4552 switch (perm_type) {
4553 case ZFS_DELEG_CREATE:
4554 case ZFS_DELEG_CREATE_SETS:
4555 case ZFS_DELEG_NAMED_SET:
4556 case ZFS_DELEG_NAMED_SET_SETS:
4557 avl_pool = fspset->fsps_named_set_avl_pool;
4558 avl = fsperm->fsp_sc_avl;
4559 break;
4560 case ZFS_DELEG_USER:
4561 case ZFS_DELEG_USER_SETS:
4562 case ZFS_DELEG_GROUP:
4563 case ZFS_DELEG_GROUP_SETS:
4564 case ZFS_DELEG_EVERYONE:
4565 case ZFS_DELEG_EVERYONE_SETS:
4566 avl_pool = fspset->fsps_who_perm_avl_pool;
4567 avl = fsperm->fsp_uge_avl;
4568 break;
4570 default:
4571 assert(!"unhandled zfs_deleg_who_type_t");
4574 if (is_set) {
4575 who_perm_node_t *found_node = NULL;
4576 who_perm_node_t *node = safe_malloc(
4577 sizeof (who_perm_node_t));
4578 who_perm = &node->who_perm;
4579 uu_avl_index_t idx = 0;
4581 uu_avl_node_init(node, &node->who_avl_node, avl_pool);
4582 who_perm_init(who_perm, fsperm, perm_type, perm_name);
4584 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4585 == NULL) {
4586 if (avl == fsperm->fsp_uge_avl) {
4587 uid_t rid = 0;
4588 struct passwd *p = NULL;
4589 struct group *g = NULL;
4590 const char *nice_name = NULL;
4592 switch (perm_type) {
4593 case ZFS_DELEG_USER_SETS:
4594 case ZFS_DELEG_USER:
4595 rid = atoi(perm_name);
4596 p = getpwuid(rid);
4597 if (p)
4598 nice_name = p->pw_name;
4599 break;
4600 case ZFS_DELEG_GROUP_SETS:
4601 case ZFS_DELEG_GROUP:
4602 rid = atoi(perm_name);
4603 g = getgrgid(rid);
4604 if (g)
4605 nice_name = g->gr_name;
4606 break;
4608 default:
4609 break;
4612 if (nice_name != NULL)
4613 (void) strlcpy(
4614 node->who_perm.who_ug_name,
4615 nice_name, 256);
4618 uu_avl_insert(avl, node, idx);
4619 } else {
4620 node = found_node;
4621 who_perm = &node->who_perm;
4625 (void) parse_who_perm(who_perm, nvl2, perm_locality);
4628 return (0);
4631 static inline int
4632 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
4634 nvpair_t *nvp = NULL;
4635 uu_avl_index_t idx = 0;
4637 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4638 nvlist_t *nvl2 = NULL;
4639 const char *fsname = nvpair_name(nvp);
4640 data_type_t type = nvpair_type(nvp);
4641 fs_perm_t *fsperm = NULL;
4642 fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
4643 if (node == NULL)
4644 nomem();
4646 fsperm = &node->fspn_fsperm;
4648 assert(DATA_TYPE_NVLIST == type);
4650 uu_list_node_init(node, &node->fspn_list_node,
4651 fspset->fsps_list_pool);
4653 idx = uu_list_numnodes(fspset->fsps_list);
4654 fs_perm_init(fsperm, fspset, fsname);
4656 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4657 return (-1);
4659 (void) parse_fs_perm(fsperm, nvl2);
4661 uu_list_insert(fspset->fsps_list, node, idx);
4664 return (0);
4667 static inline const char *
4668 deleg_perm_comment(zfs_deleg_note_t note)
4670 const char *str = "";
4672 /* subcommands */
4673 switch (note) {
4674 /* SUBCOMMANDS */
4675 case ZFS_DELEG_NOTE_ALLOW:
4676 str = gettext("Must also have the permission that is being"
4677 "\n\t\t\t\tallowed");
4678 break;
4679 case ZFS_DELEG_NOTE_CLONE:
4680 str = gettext("Must also have the 'create' ability and 'mount'"
4681 "\n\t\t\t\tability in the origin file system");
4682 break;
4683 case ZFS_DELEG_NOTE_CREATE:
4684 str = gettext("Must also have the 'mount' ability");
4685 break;
4686 case ZFS_DELEG_NOTE_DESTROY:
4687 str = gettext("Must also have the 'mount' ability");
4688 break;
4689 case ZFS_DELEG_NOTE_DIFF:
4690 str = gettext("Allows lookup of paths within a dataset;"
4691 "\n\t\t\t\tgiven an object number. Ordinary users need this"
4692 "\n\t\t\t\tin order to use zfs diff");
4693 break;
4694 case ZFS_DELEG_NOTE_HOLD:
4695 str = gettext("Allows adding a user hold to a snapshot");
4696 break;
4697 case ZFS_DELEG_NOTE_MOUNT:
4698 str = gettext("Allows mount/umount of ZFS datasets");
4699 break;
4700 case ZFS_DELEG_NOTE_PROMOTE:
4701 str = gettext("Must also have the 'mount'\n\t\t\t\tand"
4702 " 'promote' ability in the origin file system");
4703 break;
4704 case ZFS_DELEG_NOTE_RECEIVE:
4705 str = gettext("Must also have the 'mount' and 'create'"
4706 " ability");
4707 break;
4708 case ZFS_DELEG_NOTE_RELEASE:
4709 str = gettext("Allows releasing a user hold which\n\t\t\t\t"
4710 "might destroy the snapshot");
4711 break;
4712 case ZFS_DELEG_NOTE_RENAME:
4713 str = gettext("Must also have the 'mount' and 'create'"
4714 "\n\t\t\t\tability in the new parent");
4715 break;
4716 case ZFS_DELEG_NOTE_ROLLBACK:
4717 str = gettext("");
4718 break;
4719 case ZFS_DELEG_NOTE_SEND:
4720 str = gettext("");
4721 break;
4722 case ZFS_DELEG_NOTE_SHARE:
4723 str = gettext("Allows sharing file systems over NFS or SMB"
4724 "\n\t\t\t\tprotocols");
4725 break;
4726 case ZFS_DELEG_NOTE_SNAPSHOT:
4727 str = gettext("");
4728 break;
4730 * case ZFS_DELEG_NOTE_VSCAN:
4731 * str = gettext("");
4732 * break;
4734 /* OTHER */
4735 case ZFS_DELEG_NOTE_GROUPQUOTA:
4736 str = gettext("Allows accessing any groupquota@... property");
4737 break;
4738 case ZFS_DELEG_NOTE_GROUPUSED:
4739 str = gettext("Allows reading any groupused@... property");
4740 break;
4741 case ZFS_DELEG_NOTE_USERPROP:
4742 str = gettext("Allows changing any user property");
4743 break;
4744 case ZFS_DELEG_NOTE_USERQUOTA:
4745 str = gettext("Allows accessing any userquota@... property");
4746 break;
4747 case ZFS_DELEG_NOTE_USERUSED:
4748 str = gettext("Allows reading any userused@... property");
4749 break;
4750 /* other */
4751 default:
4752 str = "";
4755 return (str);
4758 struct allow_opts {
4759 boolean_t local;
4760 boolean_t descend;
4761 boolean_t user;
4762 boolean_t group;
4763 boolean_t everyone;
4764 boolean_t create;
4765 boolean_t set;
4766 boolean_t recursive; /* unallow only */
4767 boolean_t prt_usage;
4769 boolean_t prt_perms;
4770 char *who;
4771 char *perms;
4772 const char *dataset;
4775 static inline int
4776 prop_cmp(const void *a, const void *b)
4778 const char *str1 = *(const char **)a;
4779 const char *str2 = *(const char **)b;
4780 return (strcmp(str1, str2));
4783 static void
4784 allow_usage(boolean_t un, boolean_t requested, const char *msg)
4786 const char *opt_desc[] = {
4787 "-h", gettext("show this help message and exit"),
4788 "-l", gettext("set permission locally"),
4789 "-d", gettext("set permission for descents"),
4790 "-u", gettext("set permission for user"),
4791 "-g", gettext("set permission for group"),
4792 "-e", gettext("set permission for everyone"),
4793 "-c", gettext("set create time permission"),
4794 "-s", gettext("define permission set"),
4795 /* unallow only */
4796 "-r", gettext("remove permissions recursively"),
4798 size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
4799 size_t allow_size = unallow_size - 2;
4800 const char *props[ZFS_NUM_PROPS];
4801 int i;
4802 size_t count = 0;
4803 FILE *fp = requested ? stdout : stderr;
4804 zprop_desc_t *pdtbl = zfs_prop_get_table();
4805 const char *fmt = gettext("%-16s %-14s\t%s\n");
4807 (void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
4808 HELP_ALLOW));
4809 (void) fprintf(fp, gettext("Options:\n"));
4810 for (int i = 0; i < (un ? unallow_size : allow_size); i++) {
4811 const char *opt = opt_desc[i++];
4812 const char *optdsc = opt_desc[i];
4813 (void) fprintf(fp, gettext(" %-10s %s\n"), opt, optdsc);
4816 (void) fprintf(fp, gettext("\nThe following permissions are "
4817 "supported:\n\n"));
4818 (void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
4819 gettext("NOTES"));
4820 for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
4821 const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
4822 zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
4823 const char *perm_type = deleg_perm_type(perm_note);
4824 const char *perm_comment = deleg_perm_comment(perm_note);
4825 (void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
4828 for (i = 0; i < ZFS_NUM_PROPS; i++) {
4829 zprop_desc_t *pd = &pdtbl[i];
4830 if (pd->pd_visible != B_TRUE)
4831 continue;
4833 if (pd->pd_attr == PROP_READONLY)
4834 continue;
4836 props[count++] = pd->pd_name;
4838 props[count] = NULL;
4840 qsort(props, count, sizeof (char *), prop_cmp);
4842 for (i = 0; i < count; i++)
4843 (void) fprintf(fp, fmt, props[i], gettext("property"), "");
4845 if (msg != NULL)
4846 (void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
4848 exit(requested ? 0 : 2);
4851 static inline const char *
4852 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
4853 char **permsp)
4855 if (un && argc == expected_argc - 1)
4856 *permsp = NULL;
4857 else if (argc == expected_argc)
4858 *permsp = argv[argc - 2];
4859 else
4860 allow_usage(un, B_FALSE,
4861 gettext("wrong number of parameters\n"));
4863 return (argv[argc - 1]);
4866 static void
4867 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
4869 int uge_sum = opts->user + opts->group + opts->everyone;
4870 int csuge_sum = opts->create + opts->set + uge_sum;
4871 int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
4872 int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
4874 if (uge_sum > 1)
4875 allow_usage(un, B_FALSE,
4876 gettext("-u, -g, and -e are mutually exclusive\n"));
4878 if (opts->prt_usage) {
4879 if (argc == 0 && all_sum == 0)
4880 allow_usage(un, B_TRUE, NULL);
4881 else
4882 usage(B_FALSE);
4885 if (opts->set) {
4886 if (csuge_sum > 1)
4887 allow_usage(un, B_FALSE,
4888 gettext("invalid options combined with -s\n"));
4890 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4891 if (argv[0][0] != '@')
4892 allow_usage(un, B_FALSE,
4893 gettext("invalid set name: missing '@' prefix\n"));
4894 opts->who = argv[0];
4895 } else if (opts->create) {
4896 if (ldcsuge_sum > 1)
4897 allow_usage(un, B_FALSE,
4898 gettext("invalid options combined with -c\n"));
4899 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4900 } else if (opts->everyone) {
4901 if (csuge_sum > 1)
4902 allow_usage(un, B_FALSE,
4903 gettext("invalid options combined with -e\n"));
4904 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4905 } else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
4906 == 0) {
4907 opts->everyone = B_TRUE;
4908 argc--;
4909 argv++;
4910 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4911 } else if (argc == 1 && !un) {
4912 opts->prt_perms = B_TRUE;
4913 opts->dataset = argv[argc-1];
4914 } else {
4915 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4916 opts->who = argv[0];
4919 if (!opts->local && !opts->descend) {
4920 opts->local = B_TRUE;
4921 opts->descend = B_TRUE;
4925 static void
4926 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
4927 const char *who, char *perms, nvlist_t *top_nvl)
4929 int i;
4930 char ld[2] = { '\0', '\0' };
4931 char who_buf[MAXNAMELEN + 32];
4932 char base_type = '\0';
4933 char set_type = '\0';
4934 nvlist_t *base_nvl = NULL;
4935 nvlist_t *set_nvl = NULL;
4936 nvlist_t *nvl;
4938 if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
4939 nomem();
4940 if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) != 0)
4941 nomem();
4943 switch (type) {
4944 case ZFS_DELEG_NAMED_SET_SETS:
4945 case ZFS_DELEG_NAMED_SET:
4946 set_type = ZFS_DELEG_NAMED_SET_SETS;
4947 base_type = ZFS_DELEG_NAMED_SET;
4948 ld[0] = ZFS_DELEG_NA;
4949 break;
4950 case ZFS_DELEG_CREATE_SETS:
4951 case ZFS_DELEG_CREATE:
4952 set_type = ZFS_DELEG_CREATE_SETS;
4953 base_type = ZFS_DELEG_CREATE;
4954 ld[0] = ZFS_DELEG_NA;
4955 break;
4956 case ZFS_DELEG_USER_SETS:
4957 case ZFS_DELEG_USER:
4958 set_type = ZFS_DELEG_USER_SETS;
4959 base_type = ZFS_DELEG_USER;
4960 if (local)
4961 ld[0] = ZFS_DELEG_LOCAL;
4962 if (descend)
4963 ld[1] = ZFS_DELEG_DESCENDENT;
4964 break;
4965 case ZFS_DELEG_GROUP_SETS:
4966 case ZFS_DELEG_GROUP:
4967 set_type = ZFS_DELEG_GROUP_SETS;
4968 base_type = ZFS_DELEG_GROUP;
4969 if (local)
4970 ld[0] = ZFS_DELEG_LOCAL;
4971 if (descend)
4972 ld[1] = ZFS_DELEG_DESCENDENT;
4973 break;
4974 case ZFS_DELEG_EVERYONE_SETS:
4975 case ZFS_DELEG_EVERYONE:
4976 set_type = ZFS_DELEG_EVERYONE_SETS;
4977 base_type = ZFS_DELEG_EVERYONE;
4978 if (local)
4979 ld[0] = ZFS_DELEG_LOCAL;
4980 if (descend)
4981 ld[1] = ZFS_DELEG_DESCENDENT;
4982 break;
4984 default:
4985 assert(set_type != '\0' && base_type != '\0');
4988 if (perms != NULL) {
4989 char *curr = perms;
4990 char *end = curr + strlen(perms);
4992 while (curr < end) {
4993 char *delim = strchr(curr, ',');
4994 if (delim == NULL)
4995 delim = end;
4996 else
4997 *delim = '\0';
4999 if (curr[0] == '@')
5000 nvl = set_nvl;
5001 else
5002 nvl = base_nvl;
5004 (void) nvlist_add_boolean(nvl, curr);
5005 if (delim != end)
5006 *delim = ',';
5007 curr = delim + 1;
5010 for (i = 0; i < 2; i++) {
5011 char locality = ld[i];
5012 if (locality == 0)
5013 continue;
5015 if (!nvlist_empty(base_nvl)) {
5016 if (who != NULL)
5017 (void) snprintf(who_buf,
5018 sizeof (who_buf), "%c%c$%s",
5019 base_type, locality, who);
5020 else
5021 (void) snprintf(who_buf,
5022 sizeof (who_buf), "%c%c$",
5023 base_type, locality);
5025 (void) nvlist_add_nvlist(top_nvl, who_buf,
5026 base_nvl);
5030 if (!nvlist_empty(set_nvl)) {
5031 if (who != NULL)
5032 (void) snprintf(who_buf,
5033 sizeof (who_buf), "%c%c$%s",
5034 set_type, locality, who);
5035 else
5036 (void) snprintf(who_buf,
5037 sizeof (who_buf), "%c%c$",
5038 set_type, locality);
5040 (void) nvlist_add_nvlist(top_nvl, who_buf,
5041 set_nvl);
5044 } else {
5045 for (i = 0; i < 2; i++) {
5046 char locality = ld[i];
5047 if (locality == 0)
5048 continue;
5050 if (who != NULL)
5051 (void) snprintf(who_buf, sizeof (who_buf),
5052 "%c%c$%s", base_type, locality, who);
5053 else
5054 (void) snprintf(who_buf, sizeof (who_buf),
5055 "%c%c$", base_type, locality);
5056 (void) nvlist_add_boolean(top_nvl, who_buf);
5058 if (who != NULL)
5059 (void) snprintf(who_buf, sizeof (who_buf),
5060 "%c%c$%s", set_type, locality, who);
5061 else
5062 (void) snprintf(who_buf, sizeof (who_buf),
5063 "%c%c$", set_type, locality);
5064 (void) nvlist_add_boolean(top_nvl, who_buf);
5069 static int
5070 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
5072 if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
5073 nomem();
5075 if (opts->set) {
5076 store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
5077 opts->descend, opts->who, opts->perms, *nvlp);
5078 } else if (opts->create) {
5079 store_allow_perm(ZFS_DELEG_CREATE, opts->local,
5080 opts->descend, NULL, opts->perms, *nvlp);
5081 } else if (opts->everyone) {
5082 store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
5083 opts->descend, NULL, opts->perms, *nvlp);
5084 } else {
5085 char *curr = opts->who;
5086 char *end = curr + strlen(curr);
5088 while (curr < end) {
5089 const char *who;
5090 zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
5091 char *endch;
5092 char *delim = strchr(curr, ',');
5093 char errbuf[256];
5094 char id[64];
5095 struct passwd *p = NULL;
5096 struct group *g = NULL;
5098 uid_t rid;
5099 if (delim == NULL)
5100 delim = end;
5101 else
5102 *delim = '\0';
5104 rid = (uid_t)strtol(curr, &endch, 0);
5105 if (opts->user) {
5106 who_type = ZFS_DELEG_USER;
5107 if (*endch != '\0')
5108 p = getpwnam(curr);
5109 else
5110 p = getpwuid(rid);
5112 if (p != NULL)
5113 rid = p->pw_uid;
5114 else {
5115 (void) snprintf(errbuf, 256, gettext(
5116 "invalid user %s"), curr);
5117 allow_usage(un, B_TRUE, errbuf);
5119 } else if (opts->group) {
5120 who_type = ZFS_DELEG_GROUP;
5121 if (*endch != '\0')
5122 g = getgrnam(curr);
5123 else
5124 g = getgrgid(rid);
5126 if (g != NULL)
5127 rid = g->gr_gid;
5128 else {
5129 (void) snprintf(errbuf, 256, gettext(
5130 "invalid group %s"), curr);
5131 allow_usage(un, B_TRUE, errbuf);
5133 } else {
5134 if (*endch != '\0') {
5135 p = getpwnam(curr);
5136 } else {
5137 p = getpwuid(rid);
5140 if (p == NULL) {
5141 if (*endch != '\0') {
5142 g = getgrnam(curr);
5143 } else {
5144 g = getgrgid(rid);
5148 if (p != NULL) {
5149 who_type = ZFS_DELEG_USER;
5150 rid = p->pw_uid;
5151 } else if (g != NULL) {
5152 who_type = ZFS_DELEG_GROUP;
5153 rid = g->gr_gid;
5154 } else {
5155 (void) snprintf(errbuf, 256, gettext(
5156 "invalid user/group %s"), curr);
5157 allow_usage(un, B_TRUE, errbuf);
5161 (void) sprintf(id, "%u", rid);
5162 who = id;
5164 store_allow_perm(who_type, opts->local,
5165 opts->descend, who, opts->perms, *nvlp);
5166 curr = delim + 1;
5170 return (0);
5173 static void
5174 print_set_creat_perms(uu_avl_t *who_avl)
5176 const char *sc_title[] = {
5177 gettext("Permission sets:\n"),
5178 gettext("Create time permissions:\n"),
5179 NULL
5181 const char **title_ptr = sc_title;
5182 who_perm_node_t *who_node = NULL;
5183 int prev_weight = -1;
5185 for (who_node = uu_avl_first(who_avl); who_node != NULL;
5186 who_node = uu_avl_next(who_avl, who_node)) {
5187 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5188 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5189 const char *who_name = who_node->who_perm.who_name;
5190 int weight = who_type2weight(who_type);
5191 boolean_t first = B_TRUE;
5192 deleg_perm_node_t *deleg_node;
5194 if (prev_weight != weight) {
5195 (void) printf(*title_ptr++);
5196 prev_weight = weight;
5199 if (who_name == NULL || strnlen(who_name, 1) == 0)
5200 (void) printf("\t");
5201 else
5202 (void) printf("\t%s ", who_name);
5204 for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
5205 deleg_node = uu_avl_next(avl, deleg_node)) {
5206 if (first) {
5207 (void) printf("%s",
5208 deleg_node->dpn_perm.dp_name);
5209 first = B_FALSE;
5210 } else
5211 (void) printf(",%s",
5212 deleg_node->dpn_perm.dp_name);
5215 (void) printf("\n");
5219 static void
5220 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
5221 const char *title)
5223 who_perm_node_t *who_node = NULL;
5224 boolean_t prt_title = B_TRUE;
5225 uu_avl_walk_t *walk;
5227 if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
5228 nomem();
5230 while ((who_node = uu_avl_walk_next(walk)) != NULL) {
5231 const char *who_name = who_node->who_perm.who_name;
5232 const char *nice_who_name = who_node->who_perm.who_ug_name;
5233 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5234 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5235 char delim = ' ';
5236 deleg_perm_node_t *deleg_node;
5237 boolean_t prt_who = B_TRUE;
5239 for (deleg_node = uu_avl_first(avl);
5240 deleg_node != NULL;
5241 deleg_node = uu_avl_next(avl, deleg_node)) {
5242 if (local != deleg_node->dpn_perm.dp_local ||
5243 descend != deleg_node->dpn_perm.dp_descend)
5244 continue;
5246 if (prt_who) {
5247 const char *who = NULL;
5248 if (prt_title) {
5249 prt_title = B_FALSE;
5250 (void) printf(title);
5253 switch (who_type) {
5254 case ZFS_DELEG_USER_SETS:
5255 case ZFS_DELEG_USER:
5256 who = gettext("user");
5257 if (nice_who_name)
5258 who_name = nice_who_name;
5259 break;
5260 case ZFS_DELEG_GROUP_SETS:
5261 case ZFS_DELEG_GROUP:
5262 who = gettext("group");
5263 if (nice_who_name)
5264 who_name = nice_who_name;
5265 break;
5266 case ZFS_DELEG_EVERYONE_SETS:
5267 case ZFS_DELEG_EVERYONE:
5268 who = gettext("everyone");
5269 who_name = NULL;
5270 break;
5272 default:
5273 assert(who != NULL);
5276 prt_who = B_FALSE;
5277 if (who_name == NULL)
5278 (void) printf("\t%s", who);
5279 else
5280 (void) printf("\t%s %s", who, who_name);
5283 (void) printf("%c%s", delim,
5284 deleg_node->dpn_perm.dp_name);
5285 delim = ',';
5288 if (!prt_who)
5289 (void) printf("\n");
5292 uu_avl_walk_end(walk);
5295 static void
5296 print_fs_perms(fs_perm_set_t *fspset)
5298 fs_perm_node_t *node = NULL;
5299 char buf[MAXNAMELEN + 32];
5300 const char *dsname = buf;
5302 for (node = uu_list_first(fspset->fsps_list); node != NULL;
5303 node = uu_list_next(fspset->fsps_list, node)) {
5304 uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
5305 uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
5306 int left = 0;
5308 (void) snprintf(buf, sizeof (buf),
5309 gettext("---- Permissions on %s "),
5310 node->fspn_fsperm.fsp_name);
5311 (void) printf(dsname);
5312 left = 70 - strlen(buf);
5313 while (left-- > 0)
5314 (void) printf("-");
5315 (void) printf("\n");
5317 print_set_creat_perms(sc_avl);
5318 print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
5319 gettext("Local permissions:\n"));
5320 print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
5321 gettext("Descendent permissions:\n"));
5322 print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
5323 gettext("Local+Descendent permissions:\n"));
5327 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
5329 struct deleg_perms {
5330 boolean_t un;
5331 nvlist_t *nvl;
5334 static int
5335 set_deleg_perms(zfs_handle_t *zhp, void *data)
5337 struct deleg_perms *perms = (struct deleg_perms *)data;
5338 zfs_type_t zfs_type = zfs_get_type(zhp);
5340 if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
5341 return (0);
5343 return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
5346 static int
5347 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
5349 zfs_handle_t *zhp;
5350 nvlist_t *perm_nvl = NULL;
5351 nvlist_t *update_perm_nvl = NULL;
5352 int error = 1;
5353 int c;
5354 struct allow_opts opts = { 0 };
5356 const char *optstr = un ? "ldugecsrh" : "ldugecsh";
5358 /* check opts */
5359 while ((c = getopt(argc, argv, optstr)) != -1) {
5360 switch (c) {
5361 case 'l':
5362 opts.local = B_TRUE;
5363 break;
5364 case 'd':
5365 opts.descend = B_TRUE;
5366 break;
5367 case 'u':
5368 opts.user = B_TRUE;
5369 break;
5370 case 'g':
5371 opts.group = B_TRUE;
5372 break;
5373 case 'e':
5374 opts.everyone = B_TRUE;
5375 break;
5376 case 's':
5377 opts.set = B_TRUE;
5378 break;
5379 case 'c':
5380 opts.create = B_TRUE;
5381 break;
5382 case 'r':
5383 opts.recursive = B_TRUE;
5384 break;
5385 case ':':
5386 (void) fprintf(stderr, gettext("missing argument for "
5387 "'%c' option\n"), optopt);
5388 usage(B_FALSE);
5389 break;
5390 case 'h':
5391 opts.prt_usage = B_TRUE;
5392 break;
5393 case '?':
5394 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5395 optopt);
5396 usage(B_FALSE);
5400 argc -= optind;
5401 argv += optind;
5403 /* check arguments */
5404 parse_allow_args(argc, argv, un, &opts);
5406 /* try to open the dataset */
5407 if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
5408 ZFS_TYPE_VOLUME)) == NULL) {
5409 (void) fprintf(stderr, "Failed to open dataset: %s\n",
5410 opts.dataset);
5411 return (-1);
5414 if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
5415 goto cleanup2;
5417 fs_perm_set_init(&fs_perm_set);
5418 if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
5419 (void) fprintf(stderr, "Failed to parse fsacl permissions\n");
5420 goto cleanup1;
5423 if (opts.prt_perms)
5424 print_fs_perms(&fs_perm_set);
5425 else {
5426 (void) construct_fsacl_list(un, &opts, &update_perm_nvl);
5427 if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
5428 goto cleanup0;
5430 if (un && opts.recursive) {
5431 struct deleg_perms data = { un, update_perm_nvl };
5432 if (zfs_iter_filesystems(zhp, set_deleg_perms,
5433 &data) != 0)
5434 goto cleanup0;
5438 error = 0;
5440 cleanup0:
5441 nvlist_free(perm_nvl);
5442 nvlist_free(update_perm_nvl);
5443 cleanup1:
5444 fs_perm_set_fini(&fs_perm_set);
5445 cleanup2:
5446 zfs_close(zhp);
5448 return (error);
5451 static int
5452 zfs_do_allow(int argc, char **argv)
5454 return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
5457 static int
5458 zfs_do_unallow(int argc, char **argv)
5460 return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
5463 static int
5464 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
5466 int errors = 0;
5467 int i;
5468 const char *tag;
5469 boolean_t recursive = B_FALSE;
5470 const char *opts = holding ? "rt" : "r";
5471 int c;
5473 /* check options */
5474 while ((c = getopt(argc, argv, opts)) != -1) {
5475 switch (c) {
5476 case 'r':
5477 recursive = B_TRUE;
5478 break;
5479 case '?':
5480 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5481 optopt);
5482 usage(B_FALSE);
5486 argc -= optind;
5487 argv += optind;
5489 /* check number of arguments */
5490 if (argc < 2)
5491 usage(B_FALSE);
5493 tag = argv[0];
5494 --argc;
5495 ++argv;
5497 if (holding && tag[0] == '.') {
5498 /* tags starting with '.' are reserved for libzfs */
5499 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
5500 usage(B_FALSE);
5503 for (i = 0; i < argc; ++i) {
5504 zfs_handle_t *zhp;
5505 char parent[ZFS_MAX_DATASET_NAME_LEN];
5506 const char *delim;
5507 char *path = argv[i];
5509 delim = strchr(path, '@');
5510 if (delim == NULL) {
5511 (void) fprintf(stderr,
5512 gettext("'%s' is not a snapshot\n"), path);
5513 ++errors;
5514 continue;
5516 (void) strncpy(parent, path, delim - path);
5517 parent[delim - path] = '\0';
5519 zhp = zfs_open(g_zfs, parent,
5520 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5521 if (zhp == NULL) {
5522 ++errors;
5523 continue;
5525 if (holding) {
5526 if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
5527 ++errors;
5528 } else {
5529 if (zfs_release(zhp, delim+1, tag, recursive) != 0)
5530 ++errors;
5532 zfs_close(zhp);
5535 return (errors != 0);
5539 * zfs hold [-r] [-t] <tag> <snap> ...
5541 * -r Recursively hold
5543 * Apply a user-hold with the given tag to the list of snapshots.
5545 static int
5546 zfs_do_hold(int argc, char **argv)
5548 return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
5552 * zfs release [-r] <tag> <snap> ...
5554 * -r Recursively release
5556 * Release a user-hold with the given tag from the list of snapshots.
5558 static int
5559 zfs_do_release(int argc, char **argv)
5561 return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
5564 typedef struct holds_cbdata {
5565 boolean_t cb_recursive;
5566 const char *cb_snapname;
5567 nvlist_t **cb_nvlp;
5568 size_t cb_max_namelen;
5569 size_t cb_max_taglen;
5570 } holds_cbdata_t;
5572 #define STRFTIME_FMT_STR "%a %b %e %k:%M %Y"
5573 #define DATETIME_BUF_LEN (32)
5577 static void
5578 print_holds(boolean_t scripted, size_t nwidth, size_t tagwidth, nvlist_t *nvl)
5580 int i;
5581 nvpair_t *nvp = NULL;
5582 char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
5583 const char *col;
5585 if (!scripted) {
5586 for (i = 0; i < 3; i++) {
5587 col = gettext(hdr_cols[i]);
5588 if (i < 2)
5589 (void) printf("%-*s ", i ? tagwidth : nwidth,
5590 col);
5591 else
5592 (void) printf("%s\n", col);
5596 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5597 char *zname = nvpair_name(nvp);
5598 nvlist_t *nvl2;
5599 nvpair_t *nvp2 = NULL;
5600 (void) nvpair_value_nvlist(nvp, &nvl2);
5601 while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
5602 char tsbuf[DATETIME_BUF_LEN];
5603 char *tagname = nvpair_name(nvp2);
5604 uint64_t val = 0;
5605 time_t time;
5606 struct tm t;
5608 (void) nvpair_value_uint64(nvp2, &val);
5609 time = (time_t)val;
5610 (void) localtime_r(&time, &t);
5611 (void) strftime(tsbuf, DATETIME_BUF_LEN,
5612 gettext(STRFTIME_FMT_STR), &t);
5614 if (scripted) {
5615 (void) printf("%s\t%s\t%s\n", zname,
5616 tagname, tsbuf);
5617 } else {
5618 (void) printf("%-*s %-*s %s\n", nwidth,
5619 zname, tagwidth, tagname, tsbuf);
5626 * Generic callback function to list a dataset or snapshot.
5628 static int
5629 holds_callback(zfs_handle_t *zhp, void *data)
5631 holds_cbdata_t *cbp = data;
5632 nvlist_t *top_nvl = *cbp->cb_nvlp;
5633 nvlist_t *nvl = NULL;
5634 nvpair_t *nvp = NULL;
5635 const char *zname = zfs_get_name(zhp);
5636 size_t znamelen = strlen(zname);
5638 if (cbp->cb_recursive) {
5639 const char *snapname;
5640 char *delim = strchr(zname, '@');
5641 if (delim == NULL)
5642 return (0);
5644 snapname = delim + 1;
5645 if (strcmp(cbp->cb_snapname, snapname))
5646 return (0);
5649 if (zfs_get_holds(zhp, &nvl) != 0)
5650 return (-1);
5652 if (znamelen > cbp->cb_max_namelen)
5653 cbp->cb_max_namelen = znamelen;
5655 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5656 const char *tag = nvpair_name(nvp);
5657 size_t taglen = strlen(tag);
5658 if (taglen > cbp->cb_max_taglen)
5659 cbp->cb_max_taglen = taglen;
5662 return (nvlist_add_nvlist(top_nvl, zname, nvl));
5666 * zfs holds [-r] <snap> ...
5668 * -r Recursively hold
5670 static int
5671 zfs_do_holds(int argc, char **argv)
5673 int errors = 0;
5674 int c;
5675 int i;
5676 boolean_t scripted = B_FALSE;
5677 boolean_t recursive = B_FALSE;
5678 const char *opts = "rH";
5679 nvlist_t *nvl;
5681 int types = ZFS_TYPE_SNAPSHOT;
5682 holds_cbdata_t cb = { 0 };
5684 int limit = 0;
5685 int ret = 0;
5686 int flags = 0;
5688 /* check options */
5689 while ((c = getopt(argc, argv, opts)) != -1) {
5690 switch (c) {
5691 case 'r':
5692 recursive = B_TRUE;
5693 break;
5694 case 'H':
5695 scripted = B_TRUE;
5696 break;
5697 case '?':
5698 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5699 optopt);
5700 usage(B_FALSE);
5704 if (recursive) {
5705 types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
5706 flags |= ZFS_ITER_RECURSE;
5709 argc -= optind;
5710 argv += optind;
5712 /* check number of arguments */
5713 if (argc < 1)
5714 usage(B_FALSE);
5716 if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5717 nomem();
5719 for (i = 0; i < argc; ++i) {
5720 char *snapshot = argv[i];
5721 const char *delim;
5722 const char *snapname;
5724 delim = strchr(snapshot, '@');
5725 if (delim == NULL) {
5726 (void) fprintf(stderr,
5727 gettext("'%s' is not a snapshot\n"), snapshot);
5728 ++errors;
5729 continue;
5731 snapname = delim + 1;
5732 if (recursive)
5733 snapshot[delim - snapshot] = '\0';
5735 cb.cb_recursive = recursive;
5736 cb.cb_snapname = snapname;
5737 cb.cb_nvlp = &nvl;
5740 * 1. collect holds data, set format options
5742 ret = zfs_for_each(argc, argv, flags, types, NULL, NULL, limit,
5743 holds_callback, &cb);
5744 if (ret != 0)
5745 ++errors;
5749 * 2. print holds data
5751 print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl);
5753 if (nvlist_empty(nvl))
5754 (void) printf(gettext("no datasets available\n"));
5756 nvlist_free(nvl);
5758 return (0 != errors);
5761 #define CHECK_SPINNER 30
5762 #define SPINNER_TIME 3 /* seconds */
5763 #define MOUNT_TIME 1 /* seconds */
5765 typedef struct get_all_state {
5766 boolean_t ga_verbose;
5767 get_all_cb_t *ga_cbp;
5768 } get_all_state_t;
5770 static int
5771 get_one_dataset(zfs_handle_t *zhp, void *data)
5773 static char *spin[] = { "-", "\\", "|", "/" };
5774 static int spinval = 0;
5775 static int spincheck = 0;
5776 static time_t last_spin_time = (time_t)0;
5777 get_all_state_t *state = data;
5778 zfs_type_t type = zfs_get_type(zhp);
5780 if (state->ga_verbose) {
5781 if (--spincheck < 0) {
5782 time_t now = time(NULL);
5783 if (last_spin_time + SPINNER_TIME < now) {
5784 update_progress(spin[spinval++ % 4]);
5785 last_spin_time = now;
5787 spincheck = CHECK_SPINNER;
5792 * Interate over any nested datasets.
5794 if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
5795 zfs_close(zhp);
5796 return (1);
5800 * Skip any datasets whose type does not match.
5802 if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
5803 zfs_close(zhp);
5804 return (0);
5806 libzfs_add_handle(state->ga_cbp, zhp);
5807 assert(state->ga_cbp->cb_used <= state->ga_cbp->cb_alloc);
5809 return (0);
5812 static void
5813 get_all_datasets(get_all_cb_t *cbp, boolean_t verbose)
5815 get_all_state_t state = {
5816 .ga_verbose = verbose,
5817 .ga_cbp = cbp
5820 if (verbose)
5821 set_progress_header(gettext("Reading ZFS config"));
5822 (void) zfs_iter_root(g_zfs, get_one_dataset, &state);
5824 if (verbose)
5825 finish_progress(gettext("done."));
5829 * Generic callback for sharing or mounting filesystems. Because the code is so
5830 * similar, we have a common function with an extra parameter to determine which
5831 * mode we are using.
5833 typedef enum { OP_SHARE, OP_MOUNT } share_mount_op_t;
5835 typedef struct share_mount_state {
5836 share_mount_op_t sm_op;
5837 boolean_t sm_verbose;
5838 int sm_flags;
5839 char *sm_options;
5840 char *sm_proto; /* only valid for OP_SHARE */
5841 mutex_t sm_lock; /* protects the remaining fields */
5842 uint_t sm_total; /* number of filesystems to process */
5843 uint_t sm_done; /* number of filesystems processed */
5844 int sm_status; /* -1 if any of the share/mount operations failed */
5845 } share_mount_state_t;
5848 * Share or mount a dataset.
5850 static int
5851 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
5852 boolean_t explicit, const char *options)
5854 char mountpoint[ZFS_MAXPROPLEN];
5855 char shareopts[ZFS_MAXPROPLEN];
5856 char smbshareopts[ZFS_MAXPROPLEN];
5857 const char *cmdname = op == OP_SHARE ? "share" : "mount";
5858 struct mnttab mnt;
5859 uint64_t zoned, canmount;
5860 boolean_t shared_nfs, shared_smb;
5862 assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
5865 * Check to make sure we can mount/share this dataset. If we
5866 * are in the global zone and the filesystem is exported to a
5867 * local zone, or if we are in a local zone and the
5868 * filesystem is not exported, then it is an error.
5870 zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
5872 if (zoned && getzoneid() == GLOBAL_ZONEID) {
5873 if (!explicit)
5874 return (0);
5876 (void) fprintf(stderr, gettext("cannot %s '%s': "
5877 "dataset is exported to a local zone\n"), cmdname,
5878 zfs_get_name(zhp));
5879 return (1);
5881 } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
5882 if (!explicit)
5883 return (0);
5885 (void) fprintf(stderr, gettext("cannot %s '%s': "
5886 "permission denied\n"), cmdname,
5887 zfs_get_name(zhp));
5888 return (1);
5892 * Ignore any filesystems which don't apply to us. This
5893 * includes those with a legacy mountpoint, or those with
5894 * legacy share options.
5896 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
5897 sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
5898 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
5899 sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
5900 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
5901 sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
5903 if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
5904 strcmp(smbshareopts, "off") == 0) {
5905 if (!explicit)
5906 return (0);
5908 (void) fprintf(stderr, gettext("cannot share '%s': "
5909 "legacy share\n"), zfs_get_name(zhp));
5910 (void) fprintf(stderr, gettext("use share(8) to "
5911 "share this filesystem, or set "
5912 "sharenfs property on\n"));
5913 return (1);
5917 * We cannot share or mount legacy filesystems. If the
5918 * shareopts is non-legacy but the mountpoint is legacy, we
5919 * treat it as a legacy share.
5921 if (strcmp(mountpoint, "legacy") == 0) {
5922 if (!explicit)
5923 return (0);
5925 (void) fprintf(stderr, gettext("cannot %s '%s': "
5926 "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
5927 (void) fprintf(stderr, gettext("use %s(8) to "
5928 "%s this filesystem\n"), cmdname, cmdname);
5929 return (1);
5932 if (strcmp(mountpoint, "none") == 0) {
5933 if (!explicit)
5934 return (0);
5936 (void) fprintf(stderr, gettext("cannot %s '%s': no "
5937 "mountpoint set\n"), cmdname, zfs_get_name(zhp));
5938 return (1);
5942 * canmount explicit outcome
5943 * on no pass through
5944 * on yes pass through
5945 * off no return 0
5946 * off yes display error, return 1
5947 * noauto no return 0
5948 * noauto yes pass through
5950 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
5951 if (canmount == ZFS_CANMOUNT_OFF) {
5952 if (!explicit)
5953 return (0);
5955 (void) fprintf(stderr, gettext("cannot %s '%s': "
5956 "'canmount' property is set to 'off'\n"), cmdname,
5957 zfs_get_name(zhp));
5958 return (1);
5959 } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
5960 return (0);
5964 * If this filesystem is inconsistent and has a receive resume
5965 * token, we can not mount it.
5967 if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) &&
5968 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
5969 NULL, 0, NULL, NULL, 0, B_TRUE) == 0) {
5970 if (!explicit)
5971 return (0);
5973 (void) fprintf(stderr, gettext("cannot %s '%s': "
5974 "Contains partially-completed state from "
5975 "\"zfs receive -r\", which can be resumed with "
5976 "\"zfs send -t\"\n"),
5977 cmdname, zfs_get_name(zhp));
5978 return (1);
5982 * At this point, we have verified that the mountpoint and/or
5983 * shareopts are appropriate for auto management. If the
5984 * filesystem is already mounted or shared, return (failing
5985 * for explicit requests); otherwise mount or share the
5986 * filesystem.
5988 switch (op) {
5989 case OP_SHARE:
5991 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
5992 shared_smb = zfs_is_shared_smb(zhp, NULL);
5994 if ((shared_nfs && shared_smb) ||
5995 (shared_nfs && strcmp(shareopts, "on") == 0 &&
5996 strcmp(smbshareopts, "off") == 0) ||
5997 (shared_smb && strcmp(smbshareopts, "on") == 0 &&
5998 strcmp(shareopts, "off") == 0)) {
5999 if (!explicit)
6000 return (0);
6002 (void) fprintf(stderr, gettext("cannot share "
6003 "'%s': filesystem already shared\n"),
6004 zfs_get_name(zhp));
6005 return (1);
6008 if (!zfs_is_mounted(zhp, NULL) &&
6009 zfs_mount(zhp, NULL, 0) != 0)
6010 return (1);
6012 if (protocol == NULL) {
6013 if (zfs_shareall(zhp) != 0)
6014 return (1);
6015 } else if (strcmp(protocol, "nfs") == 0) {
6016 if (zfs_share_nfs(zhp))
6017 return (1);
6018 } else if (strcmp(protocol, "smb") == 0) {
6019 if (zfs_share_smb(zhp))
6020 return (1);
6021 } else {
6022 (void) fprintf(stderr, gettext("cannot share "
6023 "'%s': invalid share type '%s' "
6024 "specified\n"),
6025 zfs_get_name(zhp), protocol);
6026 return (1);
6029 break;
6031 case OP_MOUNT:
6032 if (options == NULL)
6033 mnt.mnt_mntopts = "";
6034 else
6035 mnt.mnt_mntopts = (char *)options;
6037 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
6038 zfs_is_mounted(zhp, NULL)) {
6039 if (!explicit)
6040 return (0);
6042 (void) fprintf(stderr, gettext("cannot mount "
6043 "'%s': filesystem already mounted\n"),
6044 zfs_get_name(zhp));
6045 return (1);
6048 if (zfs_mount(zhp, options, flags) != 0)
6049 return (1);
6050 break;
6053 return (0);
6057 * Reports progress in the form "(current/total)". Not thread-safe.
6059 static void
6060 report_mount_progress(int current, int total)
6062 static time_t last_progress_time = 0;
6063 time_t now = time(NULL);
6064 char info[32];
6066 /* report 1..n instead of 0..n-1 */
6067 ++current;
6069 /* display header if we're here for the first time */
6070 if (current == 1) {
6071 set_progress_header(gettext("Mounting ZFS filesystems"));
6072 } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
6073 /* too soon to report again */
6074 return;
6077 last_progress_time = now;
6079 (void) sprintf(info, "(%d/%d)", current, total);
6081 if (current == total)
6082 finish_progress(info);
6083 else
6084 update_progress(info);
6088 * zfs_foreach_mountpoint() callback that mounts or shares one filesystem and
6089 * updates the progress meter.
6091 static int
6092 share_mount_one_cb(zfs_handle_t *zhp, void *arg)
6094 share_mount_state_t *sms = arg;
6095 int ret;
6097 ret = share_mount_one(zhp, sms->sm_op, sms->sm_flags, sms->sm_proto,
6098 B_FALSE, sms->sm_options);
6100 mutex_enter(&sms->sm_lock);
6101 if (ret != 0)
6102 sms->sm_status = ret;
6103 sms->sm_done++;
6104 if (sms->sm_verbose)
6105 report_mount_progress(sms->sm_done, sms->sm_total);
6106 mutex_exit(&sms->sm_lock);
6107 return (ret);
6110 static void
6111 append_options(char *mntopts, char *newopts)
6113 int len = strlen(mntopts);
6115 /* original length plus new string to append plus 1 for the comma */
6116 if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
6117 (void) fprintf(stderr, gettext("the opts argument for "
6118 "'%c' option is too long (more than %d chars)\n"),
6119 "-o", MNT_LINE_MAX);
6120 usage(B_FALSE);
6123 if (*mntopts)
6124 mntopts[len++] = ',';
6126 (void) strcpy(&mntopts[len], newopts);
6129 static int
6130 share_mount(int op, int argc, char **argv)
6132 int do_all = 0;
6133 boolean_t verbose = B_FALSE;
6134 int c, ret = 0;
6135 char *options = NULL;
6136 int flags = 0;
6138 /* check options */
6139 while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
6140 != -1) {
6141 switch (c) {
6142 case 'a':
6143 do_all = 1;
6144 break;
6145 case 'v':
6146 verbose = B_TRUE;
6147 break;
6148 case 'o':
6149 if (*optarg == '\0') {
6150 (void) fprintf(stderr, gettext("empty mount "
6151 "options (-o) specified\n"));
6152 usage(B_FALSE);
6155 if (options == NULL)
6156 options = safe_malloc(MNT_LINE_MAX + 1);
6158 /* option validation is done later */
6159 append_options(options, optarg);
6160 break;
6162 case 'O':
6163 flags |= MS_OVERLAY;
6164 break;
6165 case ':':
6166 (void) fprintf(stderr, gettext("missing argument for "
6167 "'%c' option\n"), optopt);
6168 usage(B_FALSE);
6169 break;
6170 case '?':
6171 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6172 optopt);
6173 usage(B_FALSE);
6177 argc -= optind;
6178 argv += optind;
6180 /* check number of arguments */
6181 if (do_all) {
6182 char *protocol = NULL;
6184 if (op == OP_SHARE && argc > 0) {
6185 if (strcmp(argv[0], "nfs") != 0 &&
6186 strcmp(argv[0], "smb") != 0) {
6187 (void) fprintf(stderr, gettext("share type "
6188 "must be 'nfs' or 'smb'\n"));
6189 usage(B_FALSE);
6191 protocol = argv[0];
6192 argc--;
6193 argv++;
6196 if (argc != 0) {
6197 (void) fprintf(stderr, gettext("too many arguments\n"));
6198 usage(B_FALSE);
6201 start_progress_timer();
6202 get_all_cb_t cb = { 0 };
6203 get_all_datasets(&cb, verbose);
6205 if (cb.cb_used == 0)
6206 return (0);
6208 if (op == OP_SHARE) {
6209 sa_init_selective_arg_t sharearg;
6210 sharearg.zhandle_arr = cb.cb_handles;
6211 sharearg.zhandle_len = cb.cb_used;
6212 if ((ret = zfs_init_libshare_arg(g_zfs,
6213 SA_INIT_SHARE_API_SELECTIVE, &sharearg)) != SA_OK) {
6214 (void) fprintf(stderr, gettext(
6215 "Could not initialize libshare, %d"), ret);
6216 return (ret);
6220 share_mount_state_t share_mount_state = { 0 };
6221 share_mount_state.sm_op = op;
6222 share_mount_state.sm_verbose = verbose;
6223 share_mount_state.sm_flags = flags;
6224 share_mount_state.sm_options = options;
6225 share_mount_state.sm_proto = protocol;
6226 share_mount_state.sm_total = cb.cb_used;
6227 (void) mutex_init(&share_mount_state.sm_lock,
6228 LOCK_NORMAL | LOCK_ERRORCHECK, NULL);
6230 * libshare isn't mt-safe, so only do the operation in parallel
6231 * if we're mounting.
6233 zfs_foreach_mountpoint(g_zfs, cb.cb_handles, cb.cb_used,
6234 share_mount_one_cb, &share_mount_state, op == OP_MOUNT);
6235 ret = share_mount_state.sm_status;
6237 for (int i = 0; i < cb.cb_used; i++)
6238 zfs_close(cb.cb_handles[i]);
6239 free(cb.cb_handles);
6240 } else if (argc == 0) {
6241 struct mnttab entry;
6243 if ((op == OP_SHARE) || (options != NULL)) {
6244 (void) fprintf(stderr, gettext("missing filesystem "
6245 "argument (specify -a for all)\n"));
6246 usage(B_FALSE);
6250 * When mount is given no arguments, go through /etc/mnttab and
6251 * display any active ZFS mounts. We hide any snapshots, since
6252 * they are controlled automatically.
6254 rewind(mnttab_file);
6255 while (getmntent(mnttab_file, &entry) == 0) {
6256 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
6257 strchr(entry.mnt_special, '@') != NULL)
6258 continue;
6260 (void) printf("%-30s %s\n", entry.mnt_special,
6261 entry.mnt_mountp);
6264 } else {
6265 zfs_handle_t *zhp;
6267 if (argc > 1) {
6268 (void) fprintf(stderr,
6269 gettext("too many arguments\n"));
6270 usage(B_FALSE);
6273 if ((zhp = zfs_open(g_zfs, argv[0],
6274 ZFS_TYPE_FILESYSTEM)) == NULL) {
6275 ret = 1;
6276 } else {
6277 ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
6278 options);
6279 zfs_close(zhp);
6283 return (ret);
6287 * zfs mount -a [nfs]
6288 * zfs mount filesystem
6290 * Mount all filesystems, or mount the given filesystem.
6292 static int
6293 zfs_do_mount(int argc, char **argv)
6295 return (share_mount(OP_MOUNT, argc, argv));
6299 * zfs share -a [nfs | smb]
6300 * zfs share filesystem
6302 * Share all filesystems, or share the given filesystem.
6304 static int
6305 zfs_do_share(int argc, char **argv)
6307 return (share_mount(OP_SHARE, argc, argv));
6310 typedef struct unshare_unmount_node {
6311 zfs_handle_t *un_zhp;
6312 char *un_mountp;
6313 uu_avl_node_t un_avlnode;
6314 } unshare_unmount_node_t;
6316 /* ARGSUSED */
6317 static int
6318 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
6320 const unshare_unmount_node_t *l = larg;
6321 const unshare_unmount_node_t *r = rarg;
6323 return (strcmp(l->un_mountp, r->un_mountp));
6327 * Convenience routine used by zfs_do_umount() and manual_unmount(). Given an
6328 * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
6329 * and unmount it appropriately.
6331 static int
6332 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
6334 zfs_handle_t *zhp;
6335 int ret = 0;
6336 struct stat64 statbuf;
6337 struct extmnttab entry;
6338 const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
6339 ino_t path_inode;
6342 * Search for the path in /etc/mnttab. Rather than looking for the
6343 * specific path, which can be fooled by non-standard paths (i.e. ".."
6344 * or "//"), we stat() the path and search for the corresponding
6345 * (major,minor) device pair.
6347 if (stat64(path, &statbuf) != 0) {
6348 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6349 cmdname, path, strerror(errno));
6350 return (1);
6352 path_inode = statbuf.st_ino;
6355 * Search for the given (major,minor) pair in the mount table.
6357 rewind(mnttab_file);
6358 while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
6359 if (entry.mnt_major == major(statbuf.st_dev) &&
6360 entry.mnt_minor == minor(statbuf.st_dev))
6361 break;
6363 if (ret != 0) {
6364 if (op == OP_SHARE) {
6365 (void) fprintf(stderr, gettext("cannot %s '%s': not "
6366 "currently mounted\n"), cmdname, path);
6367 return (1);
6369 (void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
6370 path);
6371 if ((ret = umount2(path, flags)) != 0)
6372 (void) fprintf(stderr, gettext("%s: %s\n"), path,
6373 strerror(errno));
6374 return (ret != 0);
6377 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
6378 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
6379 "filesystem\n"), cmdname, path);
6380 return (1);
6383 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6384 ZFS_TYPE_FILESYSTEM)) == NULL)
6385 return (1);
6387 ret = 1;
6388 if (stat64(entry.mnt_mountp, &statbuf) != 0) {
6389 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6390 cmdname, path, strerror(errno));
6391 goto out;
6392 } else if (statbuf.st_ino != path_inode) {
6393 (void) fprintf(stderr, gettext("cannot "
6394 "%s '%s': not a mountpoint\n"), cmdname, path);
6395 goto out;
6398 if (op == OP_SHARE) {
6399 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6400 char smbshare_prop[ZFS_MAXPROPLEN];
6402 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
6403 sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
6404 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
6405 sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
6407 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6408 strcmp(smbshare_prop, "off") == 0) {
6409 (void) fprintf(stderr, gettext("cannot unshare "
6410 "'%s': legacy share\n"), path);
6411 (void) fprintf(stderr, gettext("use "
6412 "unshare(8) to unshare this filesystem\n"));
6413 } else if (!zfs_is_shared(zhp)) {
6414 (void) fprintf(stderr, gettext("cannot unshare '%s': "
6415 "not currently shared\n"), path);
6416 } else {
6417 ret = zfs_unshareall_bypath(zhp, path);
6419 } else {
6420 char mtpt_prop[ZFS_MAXPROPLEN];
6422 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
6423 sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
6425 if (is_manual) {
6426 ret = zfs_unmount(zhp, NULL, flags);
6427 } else if (strcmp(mtpt_prop, "legacy") == 0) {
6428 (void) fprintf(stderr, gettext("cannot unmount "
6429 "'%s': legacy mountpoint\n"),
6430 zfs_get_name(zhp));
6431 (void) fprintf(stderr, gettext("use umount(8) "
6432 "to unmount this filesystem\n"));
6433 } else {
6434 ret = zfs_unmountall(zhp, flags);
6438 out:
6439 zfs_close(zhp);
6441 return (ret != 0);
6445 * Generic callback for unsharing or unmounting a filesystem.
6447 static int
6448 unshare_unmount(int op, int argc, char **argv)
6450 int do_all = 0;
6451 int flags = 0;
6452 int ret = 0;
6453 int c;
6454 zfs_handle_t *zhp;
6455 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6456 char sharesmb[ZFS_MAXPROPLEN];
6458 /* check options */
6459 while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
6460 switch (c) {
6461 case 'a':
6462 do_all = 1;
6463 break;
6464 case 'f':
6465 flags = MS_FORCE;
6466 break;
6467 case '?':
6468 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6469 optopt);
6470 usage(B_FALSE);
6474 argc -= optind;
6475 argv += optind;
6477 if (do_all) {
6479 * We could make use of zfs_for_each() to walk all datasets in
6480 * the system, but this would be very inefficient, especially
6481 * since we would have to linearly search /etc/mnttab for each
6482 * one. Instead, do one pass through /etc/mnttab looking for
6483 * zfs entries and call zfs_unmount() for each one.
6485 * Things get a little tricky if the administrator has created
6486 * mountpoints beneath other ZFS filesystems. In this case, we
6487 * have to unmount the deepest filesystems first. To accomplish
6488 * this, we place all the mountpoints in an AVL tree sorted by
6489 * the special type (dataset name), and walk the result in
6490 * reverse to make sure to get any snapshots first.
6492 struct mnttab entry;
6493 uu_avl_pool_t *pool;
6494 uu_avl_t *tree = NULL;
6495 unshare_unmount_node_t *node;
6496 uu_avl_index_t idx;
6497 uu_avl_walk_t *walk;
6499 if (argc != 0) {
6500 (void) fprintf(stderr, gettext("too many arguments\n"));
6501 usage(B_FALSE);
6504 if (((pool = uu_avl_pool_create("unmount_pool",
6505 sizeof (unshare_unmount_node_t),
6506 offsetof(unshare_unmount_node_t, un_avlnode),
6507 unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
6508 ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
6509 nomem();
6511 rewind(mnttab_file);
6512 while (getmntent(mnttab_file, &entry) == 0) {
6514 /* ignore non-ZFS entries */
6515 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
6516 continue;
6518 /* ignore snapshots */
6519 if (strchr(entry.mnt_special, '@') != NULL)
6520 continue;
6522 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6523 ZFS_TYPE_FILESYSTEM)) == NULL) {
6524 ret = 1;
6525 continue;
6529 * Ignore datasets that are excluded/restricted by
6530 * parent pool name.
6532 if (zpool_skip_pool(zfs_get_pool_name(zhp))) {
6533 zfs_close(zhp);
6534 continue;
6537 switch (op) {
6538 case OP_SHARE:
6539 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6540 nfs_mnt_prop,
6541 sizeof (nfs_mnt_prop),
6542 NULL, NULL, 0, B_FALSE) == 0);
6543 if (strcmp(nfs_mnt_prop, "off") != 0)
6544 break;
6545 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6546 nfs_mnt_prop,
6547 sizeof (nfs_mnt_prop),
6548 NULL, NULL, 0, B_FALSE) == 0);
6549 if (strcmp(nfs_mnt_prop, "off") == 0)
6550 continue;
6551 break;
6552 case OP_MOUNT:
6553 /* Ignore legacy mounts */
6554 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
6555 nfs_mnt_prop,
6556 sizeof (nfs_mnt_prop),
6557 NULL, NULL, 0, B_FALSE) == 0);
6558 if (strcmp(nfs_mnt_prop, "legacy") == 0)
6559 continue;
6560 /* Ignore canmount=noauto mounts */
6561 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
6562 ZFS_CANMOUNT_NOAUTO)
6563 continue;
6564 default:
6565 break;
6568 node = safe_malloc(sizeof (unshare_unmount_node_t));
6569 node->un_zhp = zhp;
6570 node->un_mountp = safe_strdup(entry.mnt_mountp);
6572 uu_avl_node_init(node, &node->un_avlnode, pool);
6574 if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
6575 uu_avl_insert(tree, node, idx);
6576 } else {
6577 zfs_close(node->un_zhp);
6578 free(node->un_mountp);
6579 free(node);
6584 * Walk the AVL tree in reverse, unmounting each filesystem and
6585 * removing it from the AVL tree in the process.
6587 if ((walk = uu_avl_walk_start(tree,
6588 UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
6589 nomem();
6591 while ((node = uu_avl_walk_next(walk)) != NULL) {
6592 uu_avl_remove(tree, node);
6594 switch (op) {
6595 case OP_SHARE:
6596 if (zfs_unshareall_bypath(node->un_zhp,
6597 node->un_mountp) != 0)
6598 ret = 1;
6599 break;
6601 case OP_MOUNT:
6602 if (zfs_unmount(node->un_zhp,
6603 node->un_mountp, flags) != 0)
6604 ret = 1;
6605 break;
6608 zfs_close(node->un_zhp);
6609 free(node->un_mountp);
6610 free(node);
6613 uu_avl_walk_end(walk);
6614 uu_avl_destroy(tree);
6615 uu_avl_pool_destroy(pool);
6617 } else {
6618 if (argc != 1) {
6619 if (argc == 0)
6620 (void) fprintf(stderr,
6621 gettext("missing filesystem argument\n"));
6622 else
6623 (void) fprintf(stderr,
6624 gettext("too many arguments\n"));
6625 usage(B_FALSE);
6629 * We have an argument, but it may be a full path or a ZFS
6630 * filesystem. Pass full paths off to unmount_path() (shared by
6631 * manual_unmount), otherwise open the filesystem and pass to
6632 * zfs_unmount().
6634 if (argv[0][0] == '/')
6635 return (unshare_unmount_path(op, argv[0],
6636 flags, B_FALSE));
6638 if ((zhp = zfs_open(g_zfs, argv[0],
6639 ZFS_TYPE_FILESYSTEM)) == NULL)
6640 return (1);
6642 verify(zfs_prop_get(zhp, op == OP_SHARE ?
6643 ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
6644 nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
6645 NULL, 0, B_FALSE) == 0);
6647 switch (op) {
6648 case OP_SHARE:
6649 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6650 nfs_mnt_prop,
6651 sizeof (nfs_mnt_prop),
6652 NULL, NULL, 0, B_FALSE) == 0);
6653 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6654 sharesmb, sizeof (sharesmb), NULL, NULL,
6655 0, B_FALSE) == 0);
6657 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6658 strcmp(sharesmb, "off") == 0) {
6659 (void) fprintf(stderr, gettext("cannot "
6660 "unshare '%s': legacy share\n"),
6661 zfs_get_name(zhp));
6662 (void) fprintf(stderr, gettext("use "
6663 "unshare(8) to unshare this "
6664 "filesystem\n"));
6665 ret = 1;
6666 } else if (!zfs_is_shared(zhp)) {
6667 (void) fprintf(stderr, gettext("cannot "
6668 "unshare '%s': not currently "
6669 "shared\n"), zfs_get_name(zhp));
6670 ret = 1;
6671 } else if (zfs_unshareall(zhp) != 0) {
6672 ret = 1;
6674 break;
6676 case OP_MOUNT:
6677 if (strcmp(nfs_mnt_prop, "legacy") == 0) {
6678 (void) fprintf(stderr, gettext("cannot "
6679 "unmount '%s': legacy "
6680 "mountpoint\n"), zfs_get_name(zhp));
6681 (void) fprintf(stderr, gettext("use "
6682 "umount(8) to unmount this "
6683 "filesystem\n"));
6684 ret = 1;
6685 } else if (!zfs_is_mounted(zhp, NULL)) {
6686 (void) fprintf(stderr, gettext("cannot "
6687 "unmount '%s': not currently "
6688 "mounted\n"),
6689 zfs_get_name(zhp));
6690 ret = 1;
6691 } else if (zfs_unmountall(zhp, flags) != 0) {
6692 ret = 1;
6694 break;
6697 zfs_close(zhp);
6700 return (ret);
6704 * zfs unmount -a
6705 * zfs unmount filesystem
6707 * Unmount all filesystems, or a specific ZFS filesystem.
6709 static int
6710 zfs_do_unmount(int argc, char **argv)
6712 return (unshare_unmount(OP_MOUNT, argc, argv));
6716 * zfs unshare -a
6717 * zfs unshare filesystem
6719 * Unshare all filesystems, or a specific ZFS filesystem.
6721 static int
6722 zfs_do_unshare(int argc, char **argv)
6724 return (unshare_unmount(OP_SHARE, argc, argv));
6728 * Called when invoked as /etc/fs/zfs/mount. Do the mount if the mountpoint is
6729 * 'legacy'. Otherwise, complain that use should be using 'zfs mount'.
6731 static int
6732 manual_mount(int argc, char **argv)
6734 zfs_handle_t *zhp;
6735 char mountpoint[ZFS_MAXPROPLEN];
6736 char mntopts[MNT_LINE_MAX] = { '\0' };
6737 int ret = 0;
6738 int c;
6739 int flags = 0;
6740 char *dataset, *path;
6742 /* check options */
6743 while ((c = getopt(argc, argv, ":mo:O")) != -1) {
6744 switch (c) {
6745 case 'o':
6746 (void) strlcpy(mntopts, optarg, sizeof (mntopts));
6747 break;
6748 case 'O':
6749 flags |= MS_OVERLAY;
6750 break;
6751 case 'm':
6752 flags |= MS_NOMNTTAB;
6753 break;
6754 case ':':
6755 (void) fprintf(stderr, gettext("missing argument for "
6756 "'%c' option\n"), optopt);
6757 usage(B_FALSE);
6758 break;
6759 case '?':
6760 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6761 optopt);
6762 (void) fprintf(stderr, gettext("usage: mount [-o opts] "
6763 "<path>\n"));
6764 return (2);
6768 argc -= optind;
6769 argv += optind;
6771 /* check that we only have two arguments */
6772 if (argc != 2) {
6773 if (argc == 0)
6774 (void) fprintf(stderr, gettext("missing dataset "
6775 "argument\n"));
6776 else if (argc == 1)
6777 (void) fprintf(stderr,
6778 gettext("missing mountpoint argument\n"));
6779 else
6780 (void) fprintf(stderr, gettext("too many arguments\n"));
6781 (void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
6782 return (2);
6785 dataset = argv[0];
6786 path = argv[1];
6788 /* try to open the dataset */
6789 if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
6790 return (1);
6792 (void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
6793 sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
6795 /* check for legacy mountpoint and complain appropriately */
6796 ret = 0;
6797 if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
6798 if (mount(dataset, path, MS_OPTIONSTR | flags, MNTTYPE_ZFS,
6799 NULL, 0, mntopts, sizeof (mntopts)) != 0) {
6800 (void) fprintf(stderr, gettext("mount failed: %s\n"),
6801 strerror(errno));
6802 ret = 1;
6804 } else {
6805 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
6806 "mounted using 'mount -F zfs'\n"), dataset);
6807 (void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
6808 "instead.\n"), path);
6809 (void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
6810 "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
6811 (void) fprintf(stderr, gettext("See zfs(8) for more "
6812 "information.\n"));
6813 ret = 1;
6816 return (ret);
6820 * Called when invoked as /etc/fs/zfs/umount. Unlike a manual mount, we allow
6821 * unmounts of non-legacy filesystems, as this is the dominant administrative
6822 * interface.
6824 static int
6825 manual_unmount(int argc, char **argv)
6827 int flags = 0;
6828 int c;
6830 /* check options */
6831 while ((c = getopt(argc, argv, "f")) != -1) {
6832 switch (c) {
6833 case 'f':
6834 flags = MS_FORCE;
6835 break;
6836 case '?':
6837 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6838 optopt);
6839 (void) fprintf(stderr, gettext("usage: unmount [-f] "
6840 "<path>\n"));
6841 return (2);
6845 argc -= optind;
6846 argv += optind;
6848 /* check arguments */
6849 if (argc != 1) {
6850 if (argc == 0)
6851 (void) fprintf(stderr, gettext("missing path "
6852 "argument\n"));
6853 else
6854 (void) fprintf(stderr, gettext("too many arguments\n"));
6855 (void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
6856 return (2);
6859 return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
6862 static int
6863 find_command_idx(char *command, int *idx)
6865 int i;
6867 for (i = 0; i < NCOMMAND; i++) {
6868 if (command_table[i].name == NULL)
6869 continue;
6871 if (strcmp(command, command_table[i].name) == 0) {
6872 *idx = i;
6873 return (0);
6876 return (1);
6879 static int
6880 zfs_do_diff(int argc, char **argv)
6882 zfs_handle_t *zhp;
6883 int flags = 0;
6884 char *tosnap = NULL;
6885 char *fromsnap = NULL;
6886 char *atp, *copy;
6887 int err = 0;
6888 int c;
6890 while ((c = getopt(argc, argv, "FHt")) != -1) {
6891 switch (c) {
6892 case 'F':
6893 flags |= ZFS_DIFF_CLASSIFY;
6894 break;
6895 case 'H':
6896 flags |= ZFS_DIFF_PARSEABLE;
6897 break;
6898 case 't':
6899 flags |= ZFS_DIFF_TIMESTAMP;
6900 break;
6901 default:
6902 (void) fprintf(stderr,
6903 gettext("invalid option '%c'\n"), optopt);
6904 usage(B_FALSE);
6908 argc -= optind;
6909 argv += optind;
6911 if (argc < 1) {
6912 (void) fprintf(stderr,
6913 gettext("must provide at least one snapshot name\n"));
6914 usage(B_FALSE);
6917 if (argc > 2) {
6918 (void) fprintf(stderr, gettext("too many arguments\n"));
6919 usage(B_FALSE);
6922 fromsnap = argv[0];
6923 tosnap = (argc == 2) ? argv[1] : NULL;
6925 copy = NULL;
6926 if (*fromsnap != '@')
6927 copy = strdup(fromsnap);
6928 else if (tosnap)
6929 copy = strdup(tosnap);
6930 if (copy == NULL)
6931 usage(B_FALSE);
6933 if ((atp = strchr(copy, '@')) != NULL)
6934 *atp = '\0';
6936 if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
6937 return (1);
6939 free(copy);
6942 * Ignore SIGPIPE so that the library can give us
6943 * information on any failure
6945 (void) sigignore(SIGPIPE);
6947 err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
6949 zfs_close(zhp);
6951 return (err != 0);
6955 * zfs remap <filesystem | volume>
6957 * Remap the indirect blocks in the given fileystem or volume.
6959 static int
6960 zfs_do_remap(int argc, char **argv)
6962 const char *fsname;
6963 int err = 0;
6964 int c;
6966 /* check options */
6967 while ((c = getopt(argc, argv, "")) != -1) {
6968 switch (c) {
6969 case '?':
6970 (void) fprintf(stderr,
6971 gettext("invalid option '%c'\n"), optopt);
6972 usage(B_FALSE);
6976 if (argc != 2) {
6977 (void) fprintf(stderr, gettext("wrong number of arguments\n"));
6978 usage(B_FALSE);
6981 fsname = argv[1];
6982 err = zfs_remap_indirects(g_zfs, fsname);
6984 return (err);
6988 * zfs bookmark <fs@snap> <fs#bmark>
6990 * Creates a bookmark with the given name from the given snapshot.
6992 static int
6993 zfs_do_bookmark(int argc, char **argv)
6995 char snapname[ZFS_MAX_DATASET_NAME_LEN];
6996 zfs_handle_t *zhp;
6997 nvlist_t *nvl;
6998 int ret = 0;
6999 int c;
7001 /* check options */
7002 while ((c = getopt(argc, argv, "")) != -1) {
7003 switch (c) {
7004 case '?':
7005 (void) fprintf(stderr,
7006 gettext("invalid option '%c'\n"), optopt);
7007 goto usage;
7011 argc -= optind;
7012 argv += optind;
7014 /* check number of arguments */
7015 if (argc < 1) {
7016 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
7017 goto usage;
7019 if (argc < 2) {
7020 (void) fprintf(stderr, gettext("missing bookmark argument\n"));
7021 goto usage;
7024 if (strchr(argv[1], '#') == NULL) {
7025 (void) fprintf(stderr,
7026 gettext("invalid bookmark name '%s' -- "
7027 "must contain a '#'\n"), argv[1]);
7028 goto usage;
7031 if (argv[0][0] == '@') {
7033 * Snapshot name begins with @.
7034 * Default to same fs as bookmark.
7036 (void) strncpy(snapname, argv[1], sizeof (snapname));
7037 *strchr(snapname, '#') = '\0';
7038 (void) strlcat(snapname, argv[0], sizeof (snapname));
7039 } else {
7040 (void) strncpy(snapname, argv[0], sizeof (snapname));
7042 zhp = zfs_open(g_zfs, snapname, ZFS_TYPE_SNAPSHOT);
7043 if (zhp == NULL)
7044 goto usage;
7045 zfs_close(zhp);
7048 nvl = fnvlist_alloc();
7049 fnvlist_add_string(nvl, argv[1], snapname);
7050 ret = lzc_bookmark(nvl, NULL);
7051 fnvlist_free(nvl);
7053 if (ret != 0) {
7054 const char *err_msg;
7055 char errbuf[1024];
7057 (void) snprintf(errbuf, sizeof (errbuf),
7058 dgettext(TEXT_DOMAIN,
7059 "cannot create bookmark '%s'"), argv[1]);
7061 switch (ret) {
7062 case EXDEV:
7063 err_msg = "bookmark is in a different pool";
7064 break;
7065 case EEXIST:
7066 err_msg = "bookmark exists";
7067 break;
7068 case EINVAL:
7069 err_msg = "invalid argument";
7070 break;
7071 case ENOTSUP:
7072 err_msg = "bookmark feature not enabled";
7073 break;
7074 case ENOSPC:
7075 err_msg = "out of space";
7076 break;
7077 default:
7078 err_msg = "unknown error";
7079 break;
7081 (void) fprintf(stderr, "%s: %s\n", errbuf,
7082 dgettext(TEXT_DOMAIN, err_msg));
7085 return (ret != 0);
7087 usage:
7088 usage(B_FALSE);
7089 return (-1);
7092 static int
7093 zfs_do_channel_program(int argc, char **argv)
7095 int ret, fd;
7096 char c;
7097 char *progbuf, *filename, *poolname;
7098 size_t progsize, progread;
7099 nvlist_t *outnvl;
7100 uint64_t instrlimit = ZCP_DEFAULT_INSTRLIMIT;
7101 uint64_t memlimit = ZCP_DEFAULT_MEMLIMIT;
7102 boolean_t sync_flag = B_TRUE, json_output = B_FALSE;
7103 zpool_handle_t *zhp;
7105 /* check options */
7106 while (-1 !=
7107 (c = getopt(argc, argv, "jnt:(instr-limit)m:(memory-limit)"))) {
7108 switch (c) {
7109 case 't':
7110 case 'm': {
7111 uint64_t arg;
7112 char *endp;
7114 errno = 0;
7115 arg = strtoull(optarg, &endp, 0);
7116 if (errno != 0 || *endp != '\0') {
7117 (void) fprintf(stderr, gettext(
7118 "invalid argument "
7119 "'%s': expected integer\n"), optarg);
7120 goto usage;
7123 if (c == 't') {
7124 if (arg > ZCP_MAX_INSTRLIMIT || arg == 0) {
7125 (void) fprintf(stderr, gettext(
7126 "Invalid instruction limit: "
7127 "%s\n"), optarg);
7128 return (1);
7129 } else {
7130 instrlimit = arg;
7132 } else {
7133 ASSERT3U(c, ==, 'm');
7134 if (arg > ZCP_MAX_MEMLIMIT || arg == 0) {
7135 (void) fprintf(stderr, gettext(
7136 "Invalid memory limit: "
7137 "%s\n"), optarg);
7138 return (1);
7139 } else {
7140 memlimit = arg;
7143 break;
7145 case 'n': {
7146 sync_flag = B_FALSE;
7147 break;
7149 case 'j': {
7150 json_output = B_TRUE;
7151 break;
7153 case '?':
7154 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7155 optopt);
7156 goto usage;
7160 argc -= optind;
7161 argv += optind;
7163 if (argc < 2) {
7164 (void) fprintf(stderr,
7165 gettext("invalid number of arguments\n"));
7166 goto usage;
7169 poolname = argv[0];
7170 filename = argv[1];
7171 if (strcmp(filename, "-") == 0) {
7172 fd = 0;
7173 filename = "standard input";
7174 } else if ((fd = open(filename, O_RDONLY)) < 0) {
7175 (void) fprintf(stderr, gettext("cannot open '%s': %s\n"),
7176 filename, strerror(errno));
7177 return (1);
7180 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
7181 (void) fprintf(stderr, gettext("cannot open pool '%s'"),
7182 poolname);
7183 return (1);
7185 zpool_close(zhp);
7188 * Read in the channel program, expanding the program buffer as
7189 * necessary.
7191 progread = 0;
7192 progsize = 1024;
7193 progbuf = safe_malloc(progsize);
7194 do {
7195 ret = read(fd, progbuf + progread, progsize - progread);
7196 progread += ret;
7197 if (progread == progsize && ret > 0) {
7198 progsize *= 2;
7199 progbuf = safe_realloc(progbuf, progsize);
7201 } while (ret > 0);
7203 if (fd != 0)
7204 (void) close(fd);
7205 if (ret < 0) {
7206 free(progbuf);
7207 (void) fprintf(stderr,
7208 gettext("cannot read '%s': %s\n"),
7209 filename, strerror(errno));
7210 return (1);
7212 progbuf[progread] = '\0';
7215 * Any remaining arguments are passed as arguments to the lua script as
7216 * a string array:
7218 * "argv" -> [ "arg 1", ... "arg n" ],
7221 nvlist_t *argnvl = fnvlist_alloc();
7222 fnvlist_add_string_array(argnvl, ZCP_ARG_CLIARGV, argv + 2, argc - 2);
7224 if (sync_flag) {
7225 ret = lzc_channel_program(poolname, progbuf,
7226 instrlimit, memlimit, argnvl, &outnvl);
7227 } else {
7228 ret = lzc_channel_program_nosync(poolname, progbuf,
7229 instrlimit, memlimit, argnvl, &outnvl);
7232 if (ret != 0) {
7234 * On error, report the error message handed back by lua if one
7235 * exists. Otherwise, generate an appropriate error message,
7236 * falling back on strerror() for an unexpected return code.
7238 char *errstring = NULL;
7239 if (nvlist_exists(outnvl, ZCP_RET_ERROR)) {
7240 (void) nvlist_lookup_string(outnvl,
7241 ZCP_RET_ERROR, &errstring);
7242 if (errstring == NULL)
7243 errstring = strerror(ret);
7244 } else {
7245 switch (ret) {
7246 case EINVAL:
7247 errstring =
7248 "Invalid instruction or memory limit.";
7249 break;
7250 case ENOMEM:
7251 errstring = "Return value too large.";
7252 break;
7253 case ENOSPC:
7254 errstring = "Memory limit exhausted.";
7255 break;
7256 case ETIME:
7257 errstring = "Timed out.";
7258 break;
7259 case EPERM:
7260 errstring = "Permission denied. Channel "
7261 "programs must be run as root.";
7262 break;
7263 default:
7264 errstring = strerror(ret);
7267 (void) fprintf(stderr,
7268 gettext("Channel program execution failed:\n%s\n"),
7269 errstring);
7270 } else {
7271 if (json_output) {
7272 (void) nvlist_print_json(stdout, outnvl);
7273 } else if (nvlist_empty(outnvl)) {
7274 (void) fprintf(stdout, gettext("Channel program fully "
7275 "executed and did not produce output.\n"));
7276 } else {
7277 (void) fprintf(stdout, gettext("Channel program fully "
7278 "executed and produced output:\n"));
7279 dump_nvlist(outnvl, 4);
7283 free(progbuf);
7284 fnvlist_free(outnvl);
7285 fnvlist_free(argnvl);
7286 return (ret != 0);
7288 usage:
7289 usage(B_FALSE);
7290 return (-1);
7294 main(int argc, char **argv)
7296 int ret = 0;
7297 int i;
7298 char *progname;
7299 char *cmdname;
7301 (void) setlocale(LC_ALL, "");
7302 (void) textdomain(TEXT_DOMAIN);
7304 opterr = 0;
7306 if ((g_zfs = libzfs_init()) == NULL) {
7307 (void) fprintf(stderr, gettext("internal error: failed to "
7308 "initialize ZFS library\n"));
7309 return (1);
7312 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
7314 libzfs_print_on_error(g_zfs, B_TRUE);
7316 if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
7317 (void) fprintf(stderr, gettext("internal error: unable to "
7318 "open %s\n"), MNTTAB);
7319 return (1);
7323 * This command also doubles as the /etc/fs mount and unmount program.
7324 * Determine if we should take this behavior based on argv[0].
7326 progname = basename(argv[0]);
7327 if (strcmp(progname, "mount") == 0) {
7328 ret = manual_mount(argc, argv);
7329 } else if (strcmp(progname, "umount") == 0) {
7330 ret = manual_unmount(argc, argv);
7331 } else {
7333 * Make sure the user has specified some command.
7335 if (argc < 2) {
7336 (void) fprintf(stderr, gettext("missing command\n"));
7337 usage(B_FALSE);
7340 cmdname = argv[1];
7343 * The 'umount' command is an alias for 'unmount'
7345 if (strcmp(cmdname, "umount") == 0)
7346 cmdname = "unmount";
7349 * The 'recv' command is an alias for 'receive'
7351 if (strcmp(cmdname, "recv") == 0)
7352 cmdname = "receive";
7355 * The 'snap' command is an alias for 'snapshot'
7357 if (strcmp(cmdname, "snap") == 0)
7358 cmdname = "snapshot";
7361 * Special case '-?'
7363 if (strcmp(cmdname, "-?") == 0)
7364 usage(B_TRUE);
7367 * Run the appropriate command.
7369 libzfs_mnttab_cache(g_zfs, B_TRUE);
7370 if (find_command_idx(cmdname, &i) == 0) {
7371 current_command = &command_table[i];
7372 ret = command_table[i].func(argc - 1, argv + 1);
7373 } else if (strchr(cmdname, '=') != NULL) {
7374 verify(find_command_idx("set", &i) == 0);
7375 current_command = &command_table[i];
7376 ret = command_table[i].func(argc, argv);
7377 } else {
7378 (void) fprintf(stderr, gettext("unrecognized "
7379 "command '%s'\n"), cmdname);
7380 usage(B_FALSE);
7382 libzfs_mnttab_cache(g_zfs, B_FALSE);
7385 (void) fclose(mnttab_file);
7387 if (ret == 0 && log_history)
7388 (void) zpool_log_history(g_zfs, history_str);
7390 libzfs_fini(g_zfs);
7393 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
7394 * for the purposes of running ::findleaks.
7396 if (getenv("ZFS_ABORT") != NULL) {
7397 (void) printf("dumping core by request\n");
7398 abort();
7401 return (ret);