Add missing parenthesis in VERIFYF()
[zfs.git] / cmd / zfs / zfs_main.c
blob7836f5909f4a670c73b8c31ededa0215811eca83
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 https://opensource.org/licenses/CDDL-1.0.
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, 2020 by Delphix. All rights reserved.
25 * Copyright 2012 Milan Jurik. All rights reserved.
26 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
27 * Copyright (c) 2013 Steven Hartland. All rights reserved.
28 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>.
29 * Copyright 2016 Nexenta Systems, Inc.
30 * Copyright (c) 2019 Datto Inc.
31 * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>
32 * Copyright 2019 Joyent, Inc.
33 * Copyright (c) 2019, 2020 by Christian Schwarz. All rights reserved.
36 #include <assert.h>
37 #include <ctype.h>
38 #include <sys/debug.h>
39 #include <errno.h>
40 #include <getopt.h>
41 #include <libgen.h>
42 #include <libintl.h>
43 #include <libuutil.h>
44 #include <libnvpair.h>
45 #include <locale.h>
46 #include <stddef.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 #include <fcntl.h>
52 #include <zone.h>
53 #include <grp.h>
54 #include <pwd.h>
55 #include <umem.h>
56 #include <pthread.h>
57 #include <signal.h>
58 #include <sys/list.h>
59 #include <sys/mkdev.h>
60 #include <sys/mntent.h>
61 #include <sys/mnttab.h>
62 #include <sys/mount.h>
63 #include <sys/stat.h>
64 #include <sys/fs/zfs.h>
65 #include <sys/systeminfo.h>
66 #include <sys/types.h>
67 #include <time.h>
68 #include <sys/zfs_project.h>
70 #include <libzfs.h>
71 #include <libzfs_core.h>
72 #include <zfs_prop.h>
73 #include <zfs_deleg.h>
74 #include <libzutil.h>
75 #ifdef HAVE_IDMAP
76 #include <aclutils.h>
77 #include <directory.h>
78 #endif /* HAVE_IDMAP */
80 #include "zfs_iter.h"
81 #include "zfs_util.h"
82 #include "zfs_comutil.h"
83 #include "zfs_projectutil.h"
85 libzfs_handle_t *g_zfs;
87 static char history_str[HIS_MAX_RECORD_LEN];
88 static boolean_t log_history = B_TRUE;
90 static int zfs_do_clone(int argc, char **argv);
91 static int zfs_do_create(int argc, char **argv);
92 static int zfs_do_destroy(int argc, char **argv);
93 static int zfs_do_get(int argc, char **argv);
94 static int zfs_do_inherit(int argc, char **argv);
95 static int zfs_do_list(int argc, char **argv);
96 static int zfs_do_mount(int argc, char **argv);
97 static int zfs_do_rename(int argc, char **argv);
98 static int zfs_do_rollback(int argc, char **argv);
99 static int zfs_do_set(int argc, char **argv);
100 static int zfs_do_upgrade(int argc, char **argv);
101 static int zfs_do_snapshot(int argc, char **argv);
102 static int zfs_do_unmount(int argc, char **argv);
103 static int zfs_do_share(int argc, char **argv);
104 static int zfs_do_unshare(int argc, char **argv);
105 static int zfs_do_send(int argc, char **argv);
106 static int zfs_do_receive(int argc, char **argv);
107 static int zfs_do_promote(int argc, char **argv);
108 static int zfs_do_userspace(int argc, char **argv);
109 static int zfs_do_allow(int argc, char **argv);
110 static int zfs_do_unallow(int argc, char **argv);
111 static int zfs_do_hold(int argc, char **argv);
112 static int zfs_do_holds(int argc, char **argv);
113 static int zfs_do_release(int argc, char **argv);
114 static int zfs_do_diff(int argc, char **argv);
115 static int zfs_do_bookmark(int argc, char **argv);
116 static int zfs_do_channel_program(int argc, char **argv);
117 static int zfs_do_load_key(int argc, char **argv);
118 static int zfs_do_unload_key(int argc, char **argv);
119 static int zfs_do_change_key(int argc, char **argv);
120 static int zfs_do_project(int argc, char **argv);
121 static int zfs_do_version(int argc, char **argv);
122 static int zfs_do_redact(int argc, char **argv);
123 static int zfs_do_wait(int argc, char **argv);
125 #ifdef __FreeBSD__
126 static int zfs_do_jail(int argc, char **argv);
127 static int zfs_do_unjail(int argc, char **argv);
128 #endif
130 #ifdef __linux__
131 static int zfs_do_zone(int argc, char **argv);
132 static int zfs_do_unzone(int argc, char **argv);
133 #endif
135 static int zfs_do_help(int argc, char **argv);
137 enum zfs_options {
138 ZFS_OPTION_JSON_NUMS_AS_INT = 1024
142 * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
145 #ifdef DEBUG
146 const char *
147 _umem_debug_init(void)
149 return ("default,verbose"); /* $UMEM_DEBUG setting */
152 const char *
153 _umem_logging_init(void)
155 return ("fail,contents"); /* $UMEM_LOGGING setting */
157 #endif
159 typedef enum {
160 HELP_CLONE,
161 HELP_CREATE,
162 HELP_DESTROY,
163 HELP_GET,
164 HELP_INHERIT,
165 HELP_UPGRADE,
166 HELP_LIST,
167 HELP_MOUNT,
168 HELP_PROMOTE,
169 HELP_RECEIVE,
170 HELP_RENAME,
171 HELP_ROLLBACK,
172 HELP_SEND,
173 HELP_SET,
174 HELP_SHARE,
175 HELP_SNAPSHOT,
176 HELP_UNMOUNT,
177 HELP_UNSHARE,
178 HELP_ALLOW,
179 HELP_UNALLOW,
180 HELP_USERSPACE,
181 HELP_GROUPSPACE,
182 HELP_PROJECTSPACE,
183 HELP_PROJECT,
184 HELP_HOLD,
185 HELP_HOLDS,
186 HELP_RELEASE,
187 HELP_DIFF,
188 HELP_BOOKMARK,
189 HELP_CHANNEL_PROGRAM,
190 HELP_LOAD_KEY,
191 HELP_UNLOAD_KEY,
192 HELP_CHANGE_KEY,
193 HELP_VERSION,
194 HELP_REDACT,
195 HELP_JAIL,
196 HELP_UNJAIL,
197 HELP_WAIT,
198 HELP_ZONE,
199 HELP_UNZONE,
200 } zfs_help_t;
202 typedef struct zfs_command {
203 const char *name;
204 int (*func)(int argc, char **argv);
205 zfs_help_t usage;
206 } zfs_command_t;
209 * Master command table. Each ZFS command has a name, associated function, and
210 * usage message. The usage messages need to be internationalized, so we have
211 * to have a function to return the usage message based on a command index.
213 * These commands are organized according to how they are displayed in the usage
214 * message. An empty command (one with a NULL name) indicates an empty line in
215 * the generic usage message.
217 static zfs_command_t command_table[] = {
218 { "version", zfs_do_version, HELP_VERSION },
219 { NULL },
220 { "create", zfs_do_create, HELP_CREATE },
221 { "destroy", zfs_do_destroy, HELP_DESTROY },
222 { NULL },
223 { "snapshot", zfs_do_snapshot, HELP_SNAPSHOT },
224 { "rollback", zfs_do_rollback, HELP_ROLLBACK },
225 { "clone", zfs_do_clone, HELP_CLONE },
226 { "promote", zfs_do_promote, HELP_PROMOTE },
227 { "rename", zfs_do_rename, HELP_RENAME },
228 { "bookmark", zfs_do_bookmark, HELP_BOOKMARK },
229 { "program", zfs_do_channel_program, HELP_CHANNEL_PROGRAM },
230 { NULL },
231 { "list", zfs_do_list, HELP_LIST },
232 { NULL },
233 { "set", zfs_do_set, HELP_SET },
234 { "get", zfs_do_get, HELP_GET },
235 { "inherit", zfs_do_inherit, HELP_INHERIT },
236 { "upgrade", zfs_do_upgrade, HELP_UPGRADE },
237 { NULL },
238 { "userspace", zfs_do_userspace, HELP_USERSPACE },
239 { "groupspace", zfs_do_userspace, HELP_GROUPSPACE },
240 { "projectspace", zfs_do_userspace, HELP_PROJECTSPACE },
241 { NULL },
242 { "project", zfs_do_project, HELP_PROJECT },
243 { NULL },
244 { "mount", zfs_do_mount, HELP_MOUNT },
245 { "unmount", zfs_do_unmount, HELP_UNMOUNT },
246 { "share", zfs_do_share, HELP_SHARE },
247 { "unshare", zfs_do_unshare, HELP_UNSHARE },
248 { NULL },
249 { "send", zfs_do_send, HELP_SEND },
250 { "receive", zfs_do_receive, HELP_RECEIVE },
251 { NULL },
252 { "allow", zfs_do_allow, HELP_ALLOW },
253 { NULL },
254 { "unallow", zfs_do_unallow, HELP_UNALLOW },
255 { NULL },
256 { "hold", zfs_do_hold, HELP_HOLD },
257 { "holds", zfs_do_holds, HELP_HOLDS },
258 { "release", zfs_do_release, HELP_RELEASE },
259 { "diff", zfs_do_diff, HELP_DIFF },
260 { "load-key", zfs_do_load_key, HELP_LOAD_KEY },
261 { "unload-key", zfs_do_unload_key, HELP_UNLOAD_KEY },
262 { "change-key", zfs_do_change_key, HELP_CHANGE_KEY },
263 { "redact", zfs_do_redact, HELP_REDACT },
264 { "wait", zfs_do_wait, HELP_WAIT },
266 #ifdef __FreeBSD__
267 { "jail", zfs_do_jail, HELP_JAIL },
268 { "unjail", zfs_do_unjail, HELP_UNJAIL },
269 #endif
271 #ifdef __linux__
272 { "zone", zfs_do_zone, HELP_ZONE },
273 { "unzone", zfs_do_unzone, HELP_UNZONE },
274 #endif
277 #define NCOMMAND (sizeof (command_table) / sizeof (command_table[0]))
279 #define MAX_CMD_LEN 256
281 zfs_command_t *current_command;
283 static const char *
284 get_usage(zfs_help_t idx)
286 switch (idx) {
287 case HELP_CLONE:
288 return (gettext("\tclone [-p] [-o property=value] ... "
289 "<snapshot> <filesystem|volume>\n"));
290 case HELP_CREATE:
291 return (gettext("\tcreate [-Pnpuv] [-o property=value] ... "
292 "<filesystem>\n"
293 "\tcreate [-Pnpsv] [-b blocksize] [-o property=value] ... "
294 "-V <size> <volume>\n"));
295 case HELP_DESTROY:
296 return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
297 "\tdestroy [-dnpRrv] "
298 "<filesystem|volume>@<snap>[%<snap>][,...]\n"
299 "\tdestroy <filesystem|volume>#<bookmark>\n"));
300 case HELP_GET:
301 return (gettext("\tget [-rHp] [-j [--json-int]] [-d max] "
302 "[-o \"all\" | field[,...]]\n"
303 "\t [-t type[,...]] [-s source[,...]]\n"
304 "\t <\"all\" | property[,...]> "
305 "[filesystem|volume|snapshot|bookmark] ...\n"));
306 case HELP_INHERIT:
307 return (gettext("\tinherit [-rS] <property> "
308 "<filesystem|volume|snapshot> ...\n"));
309 case HELP_UPGRADE:
310 return (gettext("\tupgrade [-v]\n"
311 "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
312 case HELP_LIST:
313 return (gettext("\tlist [-Hp] [-j [--json-int]] [-r|-d max] "
314 "[-o property[,...]] [-s property]...\n\t "
315 "[-S property]... [-t type[,...]] "
316 "[filesystem|volume|snapshot] ...\n"));
317 case HELP_MOUNT:
318 return (gettext("\tmount [-j]\n"
319 "\tmount [-flvO] [-o opts] <-a|-R filesystem|"
320 "filesystem>\n"));
321 case HELP_PROMOTE:
322 return (gettext("\tpromote <clone-filesystem>\n"));
323 case HELP_RECEIVE:
324 return (gettext("\treceive [-vMnsFhu] "
325 "[-o <property>=<value>] ... [-x <property>] ...\n"
326 "\t <filesystem|volume|snapshot>\n"
327 "\treceive [-vMnsFhu] [-o <property>=<value>] ... "
328 "[-x <property>] ... \n"
329 "\t [-d | -e] <filesystem>\n"
330 "\treceive -A <filesystem|volume>\n"));
331 case HELP_RENAME:
332 return (gettext("\trename [-f] <filesystem|volume|snapshot> "
333 "<filesystem|volume|snapshot>\n"
334 "\trename -p [-f] <filesystem|volume> <filesystem|volume>\n"
335 "\trename -u [-f] <filesystem> <filesystem>\n"
336 "\trename -r <snapshot> <snapshot>\n"));
337 case HELP_ROLLBACK:
338 return (gettext("\trollback [-rRf] <snapshot>\n"));
339 case HELP_SEND:
340 return (gettext("\tsend [-DLPbcehnpsVvw] "
341 "[-i|-I snapshot]\n"
342 "\t [-R [-X dataset[,dataset]...]] <snapshot>\n"
343 "\tsend [-DnVvPLecw] [-i snapshot|bookmark] "
344 "<filesystem|volume|snapshot>\n"
345 "\tsend [-DnPpVvLec] [-i bookmark|snapshot] "
346 "--redact <bookmark> <snapshot>\n"
347 "\tsend [-nVvPe] -t <receive_resume_token>\n"
348 "\tsend [-PnVv] --saved filesystem\n"));
349 case HELP_SET:
350 return (gettext("\tset [-u] <property=value> ... "
351 "<filesystem|volume|snapshot> ...\n"));
352 case HELP_SHARE:
353 return (gettext("\tshare [-l] <-a [nfs|smb] | filesystem>\n"));
354 case HELP_SNAPSHOT:
355 return (gettext("\tsnapshot [-r] [-o property=value] ... "
356 "<filesystem|volume>@<snap> ...\n"));
357 case HELP_UNMOUNT:
358 return (gettext("\tunmount [-fu] "
359 "<-a | filesystem|mountpoint>\n"));
360 case HELP_UNSHARE:
361 return (gettext("\tunshare "
362 "<-a [nfs|smb] | filesystem|mountpoint>\n"));
363 case HELP_ALLOW:
364 return (gettext("\tallow <filesystem|volume>\n"
365 "\tallow [-ldug] "
366 "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
367 "\t <filesystem|volume>\n"
368 "\tallow [-ld] -e <perm|@setname>[,...] "
369 "<filesystem|volume>\n"
370 "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
371 "\tallow -s @setname <perm|@setname>[,...] "
372 "<filesystem|volume>\n"));
373 case HELP_UNALLOW:
374 return (gettext("\tunallow [-rldug] "
375 "<\"everyone\"|user|group>[,...]\n"
376 "\t [<perm|@setname>[,...]] <filesystem|volume>\n"
377 "\tunallow [-rld] -e [<perm|@setname>[,...]] "
378 "<filesystem|volume>\n"
379 "\tunallow [-r] -c [<perm|@setname>[,...]] "
380 "<filesystem|volume>\n"
381 "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
382 "<filesystem|volume>\n"));
383 case HELP_USERSPACE:
384 return (gettext("\tuserspace [-Hinp] [-o field[,...]] "
385 "[-s field] ...\n"
386 "\t [-S field] ... [-t type[,...]] "
387 "<filesystem|snapshot|path>\n"));
388 case HELP_GROUPSPACE:
389 return (gettext("\tgroupspace [-Hinp] [-o field[,...]] "
390 "[-s field] ...\n"
391 "\t [-S field] ... [-t type[,...]] "
392 "<filesystem|snapshot|path>\n"));
393 case HELP_PROJECTSPACE:
394 return (gettext("\tprojectspace [-Hp] [-o field[,...]] "
395 "[-s field] ... \n"
396 "\t [-S field] ... <filesystem|snapshot|path>\n"));
397 case HELP_PROJECT:
398 return (gettext("\tproject [-d|-r] <directory|file ...>\n"
399 "\tproject -c [-0] [-d|-r] [-p id] <directory|file ...>\n"
400 "\tproject -C [-k] [-r] <directory ...>\n"
401 "\tproject [-p id] [-r] [-s] <directory ...>\n"));
402 case HELP_HOLD:
403 return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
404 case HELP_HOLDS:
405 return (gettext("\tholds [-rHp] <snapshot> ...\n"));
406 case HELP_RELEASE:
407 return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
408 case HELP_DIFF:
409 return (gettext("\tdiff [-FHth] <snapshot> "
410 "[snapshot|filesystem]\n"));
411 case HELP_BOOKMARK:
412 return (gettext("\tbookmark <snapshot|bookmark> "
413 "<newbookmark>\n"));
414 case HELP_CHANNEL_PROGRAM:
415 return (gettext("\tprogram [-jn] [-t <instruction limit>] "
416 "[-m <memory limit (b)>]\n"
417 "\t <pool> <program file> [lua args...]\n"));
418 case HELP_LOAD_KEY:
419 return (gettext("\tload-key [-rn] [-L <keylocation>] "
420 "<-a | filesystem|volume>\n"));
421 case HELP_UNLOAD_KEY:
422 return (gettext("\tunload-key [-r] "
423 "<-a | filesystem|volume>\n"));
424 case HELP_CHANGE_KEY:
425 return (gettext("\tchange-key [-l] [-o keyformat=<value>]\n"
426 "\t [-o keylocation=<value>] [-o pbkdf2iters=<value>]\n"
427 "\t <filesystem|volume>\n"
428 "\tchange-key -i [-l] <filesystem|volume>\n"));
429 case HELP_VERSION:
430 return (gettext("\tversion [-j]\n"));
431 case HELP_REDACT:
432 return (gettext("\tredact <snapshot> <bookmark> "
433 "<redaction_snapshot> ...\n"));
434 case HELP_JAIL:
435 return (gettext("\tjail <jailid|jailname> <filesystem>\n"));
436 case HELP_UNJAIL:
437 return (gettext("\tunjail <jailid|jailname> <filesystem>\n"));
438 case HELP_WAIT:
439 return (gettext("\twait [-t <activity>] <filesystem>\n"));
440 case HELP_ZONE:
441 return (gettext("\tzone <nsfile> <filesystem>\n"));
442 case HELP_UNZONE:
443 return (gettext("\tunzone <nsfile> <filesystem>\n"));
444 default:
445 __builtin_unreachable();
449 void
450 nomem(void)
452 (void) fprintf(stderr, gettext("internal error: out of memory\n"));
453 exit(1);
457 * Utility function to guarantee malloc() success.
460 void *
461 safe_malloc(size_t size)
463 void *data;
465 if ((data = calloc(1, size)) == NULL)
466 nomem();
468 return (data);
471 static void *
472 safe_realloc(void *data, size_t size)
474 void *newp;
475 if ((newp = realloc(data, size)) == NULL) {
476 free(data);
477 nomem();
480 return (newp);
483 static char *
484 safe_strdup(const char *str)
486 char *dupstr = strdup(str);
488 if (dupstr == NULL)
489 nomem();
491 return (dupstr);
495 * Callback routine that will print out information for each of
496 * the properties.
498 static int
499 usage_prop_cb(int prop, void *cb)
501 FILE *fp = cb;
503 (void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
505 if (zfs_prop_readonly(prop))
506 (void) fprintf(fp, " NO ");
507 else
508 (void) fprintf(fp, "YES ");
510 if (zfs_prop_inheritable(prop))
511 (void) fprintf(fp, " YES ");
512 else
513 (void) fprintf(fp, " NO ");
515 (void) fprintf(fp, "%s\n", zfs_prop_values(prop) ?: "-");
517 return (ZPROP_CONT);
521 * Display usage message. If we're inside a command, display only the usage for
522 * that command. Otherwise, iterate over the entire command table and display
523 * a complete usage message.
525 static __attribute__((noreturn)) void
526 usage(boolean_t requested)
528 int i;
529 boolean_t show_properties = B_FALSE;
530 FILE *fp = requested ? stdout : stderr;
532 if (current_command == NULL) {
534 (void) fprintf(fp, gettext("usage: zfs command args ...\n"));
535 (void) fprintf(fp,
536 gettext("where 'command' is one of the following:\n\n"));
538 for (i = 0; i < NCOMMAND; i++) {
539 if (command_table[i].name == NULL)
540 (void) fprintf(fp, "\n");
541 else
542 (void) fprintf(fp, "%s",
543 get_usage(command_table[i].usage));
546 (void) fprintf(fp, gettext("\nEach dataset is of the form: "
547 "pool/[dataset/]*dataset[@name]\n"));
548 } else {
549 (void) fprintf(fp, gettext("usage:\n"));
550 (void) fprintf(fp, "%s", get_usage(current_command->usage));
553 if (current_command != NULL &&
554 (strcmp(current_command->name, "set") == 0 ||
555 strcmp(current_command->name, "get") == 0 ||
556 strcmp(current_command->name, "inherit") == 0 ||
557 strcmp(current_command->name, "list") == 0))
558 show_properties = B_TRUE;
560 if (show_properties) {
561 (void) fprintf(fp, "%s",
562 gettext("\nThe following properties are supported:\n"));
564 (void) fprintf(fp, "\n\t%-14s %s %s %s\n\n",
565 "PROPERTY", "EDIT", "INHERIT", "VALUES");
567 /* Iterate over all properties */
568 (void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
569 ZFS_TYPE_DATASET);
571 (void) fprintf(fp, "\t%-15s ", "userused@...");
572 (void) fprintf(fp, " NO NO <size>\n");
573 (void) fprintf(fp, "\t%-15s ", "groupused@...");
574 (void) fprintf(fp, " NO NO <size>\n");
575 (void) fprintf(fp, "\t%-15s ", "projectused@...");
576 (void) fprintf(fp, " NO NO <size>\n");
577 (void) fprintf(fp, "\t%-15s ", "userobjused@...");
578 (void) fprintf(fp, " NO NO <size>\n");
579 (void) fprintf(fp, "\t%-15s ", "groupobjused@...");
580 (void) fprintf(fp, " NO NO <size>\n");
581 (void) fprintf(fp, "\t%-15s ", "projectobjused@...");
582 (void) fprintf(fp, " NO NO <size>\n");
583 (void) fprintf(fp, "\t%-15s ", "userquota@...");
584 (void) fprintf(fp, "YES NO <size> | none\n");
585 (void) fprintf(fp, "\t%-15s ", "groupquota@...");
586 (void) fprintf(fp, "YES NO <size> | none\n");
587 (void) fprintf(fp, "\t%-15s ", "projectquota@...");
588 (void) fprintf(fp, "YES NO <size> | none\n");
589 (void) fprintf(fp, "\t%-15s ", "userobjquota@...");
590 (void) fprintf(fp, "YES NO <size> | none\n");
591 (void) fprintf(fp, "\t%-15s ", "groupobjquota@...");
592 (void) fprintf(fp, "YES NO <size> | none\n");
593 (void) fprintf(fp, "\t%-15s ", "projectobjquota@...");
594 (void) fprintf(fp, "YES NO <size> | none\n");
595 (void) fprintf(fp, "\t%-15s ", "written@<snap>");
596 (void) fprintf(fp, " NO NO <size>\n");
597 (void) fprintf(fp, "\t%-15s ", "written#<bookmark>");
598 (void) fprintf(fp, " NO NO <size>\n");
600 (void) fprintf(fp, gettext("\nSizes are specified in bytes "
601 "with standard units such as K, M, G, etc.\n"));
602 (void) fprintf(fp, "%s", gettext("\nUser-defined properties "
603 "can be specified by using a name containing a colon "
604 "(:).\n"));
605 (void) fprintf(fp, gettext("\nThe {user|group|project}"
606 "[obj]{used|quota}@ properties must be appended with\n"
607 "a user|group|project specifier of one of these forms:\n"
608 " POSIX name (eg: \"matt\")\n"
609 " POSIX id (eg: \"126829\")\n"
610 " SMB name@domain (eg: \"matt@sun\")\n"
611 " SMB SID (eg: \"S-1-234-567-89\")\n"));
612 } else {
613 (void) fprintf(fp,
614 gettext("\nFor the property list, run: %s\n"),
615 "zfs set|get");
616 (void) fprintf(fp,
617 gettext("\nFor the delegated permission list, run: %s\n"),
618 "zfs allow|unallow");
619 (void) fprintf(fp,
620 gettext("\nFor further help on a command or topic, "
621 "run: %s\n"), "zfs help [<topic>]");
625 * See comments at end of main().
627 if (getenv("ZFS_ABORT") != NULL) {
628 (void) printf("dumping core by request\n");
629 abort();
632 exit(requested ? 0 : 2);
636 * Take a property=value argument string and add it to the given nvlist.
637 * Modifies the argument inplace.
639 static boolean_t
640 parseprop(nvlist_t *props, char *propname)
642 char *propval;
644 if ((propval = strchr(propname, '=')) == NULL) {
645 (void) fprintf(stderr, gettext("missing "
646 "'=' for property=value argument\n"));
647 return (B_FALSE);
649 *propval = '\0';
650 propval++;
651 if (nvlist_exists(props, propname)) {
652 (void) fprintf(stderr, gettext("property '%s' "
653 "specified multiple times\n"), propname);
654 return (B_FALSE);
656 if (nvlist_add_string(props, propname, propval) != 0)
657 nomem();
658 return (B_TRUE);
662 * Take a property name argument and add it to the given nvlist.
663 * Modifies the argument inplace.
665 static boolean_t
666 parsepropname(nvlist_t *props, char *propname)
668 if (strchr(propname, '=') != NULL) {
669 (void) fprintf(stderr, gettext("invalid character "
670 "'=' in property argument\n"));
671 return (B_FALSE);
673 if (nvlist_exists(props, propname)) {
674 (void) fprintf(stderr, gettext("property '%s' "
675 "specified multiple times\n"), propname);
676 return (B_FALSE);
678 if (nvlist_add_boolean(props, propname) != 0)
679 nomem();
680 return (B_TRUE);
683 static int
684 parse_depth(char *opt, int *flags)
686 char *tmp;
687 int depth;
689 depth = (int)strtol(opt, &tmp, 0);
690 if (*tmp) {
691 (void) fprintf(stderr,
692 gettext("%s is not an integer\n"), optarg);
693 usage(B_FALSE);
695 if (depth < 0) {
696 (void) fprintf(stderr,
697 gettext("Depth can not be negative.\n"));
698 usage(B_FALSE);
700 *flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
701 return (depth);
704 #define PROGRESS_DELAY 2 /* seconds */
706 static const char *pt_reverse =
707 "\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";
708 static time_t pt_begin;
709 static char *pt_header = NULL;
710 static boolean_t pt_shown;
712 static void
713 start_progress_timer(void)
715 pt_begin = time(NULL) + PROGRESS_DELAY;
716 pt_shown = B_FALSE;
719 static void
720 set_progress_header(const char *header)
722 assert(pt_header == NULL);
723 pt_header = safe_strdup(header);
724 if (pt_shown) {
725 (void) printf("%s: ", header);
726 (void) fflush(stdout);
730 static void
731 update_progress(const char *update)
733 if (!pt_shown && time(NULL) > pt_begin) {
734 int len = strlen(update);
736 (void) printf("%s: %s%*.*s", pt_header, update, len, len,
737 pt_reverse);
738 (void) fflush(stdout);
739 pt_shown = B_TRUE;
740 } else if (pt_shown) {
741 int len = strlen(update);
743 (void) printf("%s%*.*s", update, len, len, pt_reverse);
744 (void) fflush(stdout);
748 static void
749 finish_progress(const char *done)
751 if (pt_shown) {
752 (void) puts(done);
753 (void) fflush(stdout);
755 free(pt_header);
756 pt_header = NULL;
759 static int
760 zfs_mount_and_share(libzfs_handle_t *hdl, const char *dataset, zfs_type_t type)
762 zfs_handle_t *zhp = NULL;
763 int ret = 0;
765 zhp = zfs_open(hdl, dataset, type);
766 if (zhp == NULL)
767 return (1);
770 * Volumes may neither be mounted or shared. Potentially in the
771 * future filesystems detected on these volumes could be mounted.
773 if (zfs_get_type(zhp) == ZFS_TYPE_VOLUME) {
774 zfs_close(zhp);
775 return (0);
779 * Mount and/or share the new filesystem as appropriate. We provide a
780 * verbose error message to let the user know that their filesystem was
781 * in fact created, even if we failed to mount or share it.
783 * If the user doesn't want the dataset automatically mounted, then
784 * skip the mount/share step
786 if (zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, type, B_FALSE) &&
787 zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_ON) {
788 if (zfs_mount_delegation_check()) {
789 (void) fprintf(stderr, gettext("filesystem "
790 "successfully created, but it may only be "
791 "mounted by root\n"));
792 ret = 1;
793 } else if (zfs_mount(zhp, NULL, 0) != 0) {
794 (void) fprintf(stderr, gettext("filesystem "
795 "successfully created, but not mounted\n"));
796 ret = 1;
797 } else if (zfs_share(zhp, NULL) != 0) {
798 (void) fprintf(stderr, gettext("filesystem "
799 "successfully created, but not shared\n"));
800 ret = 1;
802 zfs_commit_shares(NULL);
805 zfs_close(zhp);
807 return (ret);
811 * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
813 * Given an existing dataset, create a writable copy whose initial contents
814 * are the same as the source. The newly created dataset maintains a
815 * dependency on the original; the original cannot be destroyed so long as
816 * the clone exists.
818 * The '-p' flag creates all the non-existing ancestors of the target first.
820 static int
821 zfs_do_clone(int argc, char **argv)
823 zfs_handle_t *zhp = NULL;
824 boolean_t parents = B_FALSE;
825 nvlist_t *props;
826 int ret = 0;
827 int c;
829 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
830 nomem();
832 /* check options */
833 while ((c = getopt(argc, argv, "o:p")) != -1) {
834 switch (c) {
835 case 'o':
836 if (!parseprop(props, optarg)) {
837 nvlist_free(props);
838 return (1);
840 break;
841 case 'p':
842 parents = B_TRUE;
843 break;
844 case '?':
845 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
846 optopt);
847 goto usage;
851 argc -= optind;
852 argv += optind;
854 /* check number of arguments */
855 if (argc < 1) {
856 (void) fprintf(stderr, gettext("missing source dataset "
857 "argument\n"));
858 goto usage;
860 if (argc < 2) {
861 (void) fprintf(stderr, gettext("missing target dataset "
862 "argument\n"));
863 goto usage;
865 if (argc > 2) {
866 (void) fprintf(stderr, gettext("too many arguments\n"));
867 goto usage;
870 /* open the source dataset */
871 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL) {
872 nvlist_free(props);
873 return (1);
876 if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
877 ZFS_TYPE_VOLUME)) {
879 * Now create the ancestors of the target dataset. If the
880 * target already exists and '-p' option was used we should not
881 * complain.
883 if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
884 ZFS_TYPE_VOLUME)) {
885 zfs_close(zhp);
886 nvlist_free(props);
887 return (0);
889 if (zfs_create_ancestors(g_zfs, argv[1]) != 0) {
890 zfs_close(zhp);
891 nvlist_free(props);
892 return (1);
896 /* pass to libzfs */
897 ret = zfs_clone(zhp, argv[1], props);
899 /* create the mountpoint if necessary */
900 if (ret == 0) {
901 if (log_history) {
902 (void) zpool_log_history(g_zfs, history_str);
903 log_history = B_FALSE;
906 ret = zfs_mount_and_share(g_zfs, argv[1], ZFS_TYPE_DATASET);
909 zfs_close(zhp);
910 nvlist_free(props);
912 return (!!ret);
914 usage:
915 ASSERT3P(zhp, ==, NULL);
916 nvlist_free(props);
917 usage(B_FALSE);
918 return (-1);
922 * Return a default volblocksize for the pool which always uses more than
923 * half of the data sectors. This primarily applies to dRAID which always
924 * writes full stripe widths.
926 static uint64_t
927 default_volblocksize(zpool_handle_t *zhp, nvlist_t *props)
929 uint64_t volblocksize, asize = SPA_MINBLOCKSIZE;
930 nvlist_t *tree, **vdevs;
931 uint_t nvdevs;
933 nvlist_t *config = zpool_get_config(zhp, NULL);
935 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &tree) != 0 ||
936 nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN,
937 &vdevs, &nvdevs) != 0) {
938 return (ZVOL_DEFAULT_BLOCKSIZE);
941 for (int i = 0; i < nvdevs; i++) {
942 nvlist_t *nv = vdevs[i];
943 uint64_t ashift, ndata, nparity;
945 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASHIFT, &ashift) != 0)
946 continue;
948 if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DRAID_NDATA,
949 &ndata) == 0) {
950 /* dRAID minimum allocation width */
951 asize = MAX(asize, ndata * (1ULL << ashift));
952 } else if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
953 &nparity) == 0) {
954 /* raidz minimum allocation width */
955 if (nparity == 1)
956 asize = MAX(asize, 2 * (1ULL << ashift));
957 else
958 asize = MAX(asize, 4 * (1ULL << ashift));
959 } else {
960 /* mirror or (non-redundant) leaf vdev */
961 asize = MAX(asize, 1ULL << ashift);
966 * Calculate the target volblocksize such that more than half
967 * of the asize is used. The following table is for 4k sectors.
969 * n asize blksz used | n asize blksz used
970 * -------------------------+---------------------------------
971 * 1 4,096 8,192 100% | 9 36,864 32,768 88%
972 * 2 8,192 8,192 100% | 10 40,960 32,768 80%
973 * 3 12,288 8,192 66% | 11 45,056 32,768 72%
974 * 4 16,384 16,384 100% | 12 49,152 32,768 66%
975 * 5 20,480 16,384 80% | 13 53,248 32,768 61%
976 * 6 24,576 16,384 66% | 14 57,344 32,768 57%
977 * 7 28,672 16,384 57% | 15 61,440 32,768 53%
978 * 8 32,768 32,768 100% | 16 65,536 65,636 100%
980 * This is primarily a concern for dRAID which always allocates
981 * a full stripe width. For dRAID the default stripe width is
982 * n=8 in which case the volblocksize is set to 32k. Ignoring
983 * compression there are no unused sectors. This same reasoning
984 * applies to raidz[2,3] so target 4 sectors to minimize waste.
986 uint64_t tgt_volblocksize = ZVOL_DEFAULT_BLOCKSIZE;
987 while (tgt_volblocksize * 2 <= asize)
988 tgt_volblocksize *= 2;
990 const char *prop = zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE);
991 if (nvlist_lookup_uint64(props, prop, &volblocksize) == 0) {
993 /* Issue a warning when a non-optimal size is requested. */
994 if (volblocksize < ZVOL_DEFAULT_BLOCKSIZE) {
995 (void) fprintf(stderr, gettext("Warning: "
996 "volblocksize (%llu) is less than the default "
997 "minimum block size (%llu).\nTo reduce wasted "
998 "space a volblocksize of %llu is recommended.\n"),
999 (u_longlong_t)volblocksize,
1000 (u_longlong_t)ZVOL_DEFAULT_BLOCKSIZE,
1001 (u_longlong_t)tgt_volblocksize);
1002 } else if (volblocksize < tgt_volblocksize) {
1003 (void) fprintf(stderr, gettext("Warning: "
1004 "volblocksize (%llu) is much less than the "
1005 "minimum allocation\nunit (%llu), which wastes "
1006 "at least %llu%% of space. To reduce wasted "
1007 "space,\nuse a larger volblocksize (%llu is "
1008 "recommended), fewer dRAID data disks\n"
1009 "per group, or smaller sector size (ashift).\n"),
1010 (u_longlong_t)volblocksize, (u_longlong_t)asize,
1011 (u_longlong_t)((100 * (asize - volblocksize)) /
1012 asize), (u_longlong_t)tgt_volblocksize);
1014 } else {
1015 volblocksize = tgt_volblocksize;
1016 fnvlist_add_uint64(props, prop, volblocksize);
1019 return (volblocksize);
1023 * zfs create [-Pnpv] [-o prop=value] ... fs
1024 * zfs create [-Pnpsv] [-b blocksize] [-o prop=value] ... -V vol size
1026 * Create a new dataset. This command can be used to create filesystems
1027 * and volumes. Snapshot creation is handled by 'zfs snapshot'.
1028 * For volumes, the user must specify a size to be used.
1030 * The '-s' flag applies only to volumes, and indicates that we should not try
1031 * to set the reservation for this volume. By default we set a reservation
1032 * equal to the size for any volume. For pools with SPA_VERSION >=
1033 * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
1035 * The '-p' flag creates all the non-existing ancestors of the target first.
1037 * The '-n' flag is no-op (dry run) mode. This will perform a user-space sanity
1038 * check of arguments and properties, but does not check for permissions,
1039 * available space, etc.
1041 * The '-u' flag prevents the newly created file system from being mounted.
1043 * The '-v' flag is for verbose output.
1045 * The '-P' flag is used for parseable output. It implies '-v'.
1047 static int
1048 zfs_do_create(int argc, char **argv)
1050 zfs_type_t type = ZFS_TYPE_FILESYSTEM;
1051 zpool_handle_t *zpool_handle = NULL;
1052 nvlist_t *real_props = NULL;
1053 uint64_t volsize = 0;
1054 int c;
1055 boolean_t noreserve = B_FALSE;
1056 boolean_t bflag = B_FALSE;
1057 boolean_t parents = B_FALSE;
1058 boolean_t dryrun = B_FALSE;
1059 boolean_t nomount = B_FALSE;
1060 boolean_t verbose = B_FALSE;
1061 boolean_t parseable = B_FALSE;
1062 int ret = 1;
1063 nvlist_t *props;
1064 uint64_t intval;
1065 const char *strval;
1067 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
1068 nomem();
1070 /* check options */
1071 while ((c = getopt(argc, argv, ":PV:b:nso:puv")) != -1) {
1072 switch (c) {
1073 case 'V':
1074 type = ZFS_TYPE_VOLUME;
1075 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
1076 (void) fprintf(stderr, gettext("bad volume "
1077 "size '%s': %s\n"), optarg,
1078 libzfs_error_description(g_zfs));
1079 goto error;
1082 if (nvlist_add_uint64(props,
1083 zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
1084 nomem();
1085 volsize = intval;
1086 break;
1087 case 'P':
1088 verbose = B_TRUE;
1089 parseable = B_TRUE;
1090 break;
1091 case 'p':
1092 parents = B_TRUE;
1093 break;
1094 case 'b':
1095 bflag = B_TRUE;
1096 if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
1097 (void) fprintf(stderr, gettext("bad volume "
1098 "block size '%s': %s\n"), optarg,
1099 libzfs_error_description(g_zfs));
1100 goto error;
1103 if (nvlist_add_uint64(props,
1104 zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
1105 intval) != 0)
1106 nomem();
1107 break;
1108 case 'n':
1109 dryrun = B_TRUE;
1110 break;
1111 case 'o':
1112 if (!parseprop(props, optarg))
1113 goto error;
1114 break;
1115 case 's':
1116 noreserve = B_TRUE;
1117 break;
1118 case 'u':
1119 nomount = B_TRUE;
1120 break;
1121 case 'v':
1122 verbose = B_TRUE;
1123 break;
1124 case ':':
1125 (void) fprintf(stderr, gettext("missing size "
1126 "argument\n"));
1127 goto badusage;
1128 case '?':
1129 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1130 optopt);
1131 goto badusage;
1135 if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
1136 (void) fprintf(stderr, gettext("'-s' and '-b' can only be "
1137 "used when creating a volume\n"));
1138 goto badusage;
1140 if (nomount && type != ZFS_TYPE_FILESYSTEM) {
1141 (void) fprintf(stderr, gettext("'-u' can only be "
1142 "used when creating a filesystem\n"));
1143 goto badusage;
1146 argc -= optind;
1147 argv += optind;
1149 /* check number of arguments */
1150 if (argc == 0) {
1151 (void) fprintf(stderr, gettext("missing %s argument\n"),
1152 zfs_type_to_name(type));
1153 goto badusage;
1155 if (argc > 1) {
1156 (void) fprintf(stderr, gettext("too many arguments\n"));
1157 goto badusage;
1160 if (dryrun || type == ZFS_TYPE_VOLUME) {
1161 char msg[ZFS_MAX_DATASET_NAME_LEN * 2];
1162 char *p;
1164 if ((p = strchr(argv[0], '/')) != NULL)
1165 *p = '\0';
1166 zpool_handle = zpool_open(g_zfs, argv[0]);
1167 if (p != NULL)
1168 *p = '/';
1169 if (zpool_handle == NULL)
1170 goto error;
1172 (void) snprintf(msg, sizeof (msg),
1173 dryrun ? gettext("cannot verify '%s'") :
1174 gettext("cannot create '%s'"), argv[0]);
1175 if (props && (real_props = zfs_valid_proplist(g_zfs, type,
1176 props, 0, NULL, zpool_handle, B_TRUE, msg)) == NULL) {
1177 zpool_close(zpool_handle);
1178 goto error;
1182 if (type == ZFS_TYPE_VOLUME) {
1183 const char *prop = zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE);
1184 uint64_t volblocksize = default_volblocksize(zpool_handle,
1185 real_props);
1187 if (volblocksize != ZVOL_DEFAULT_BLOCKSIZE &&
1188 nvlist_lookup_string(props, prop, &strval) != 0) {
1189 char *tmp;
1190 if (asprintf(&tmp, "%llu",
1191 (u_longlong_t)volblocksize) == -1)
1192 nomem();
1193 nvlist_add_string(props, prop, tmp);
1194 free(tmp);
1198 * If volsize is not a multiple of volblocksize, round it
1199 * up to the nearest multiple of the volblocksize.
1201 if (volsize % volblocksize) {
1202 volsize = P2ROUNDUP_TYPED(volsize, volblocksize,
1203 uint64_t);
1205 if (nvlist_add_uint64(props,
1206 zfs_prop_to_name(ZFS_PROP_VOLSIZE), volsize) != 0) {
1207 nvlist_free(props);
1208 nomem();
1213 if (type == ZFS_TYPE_VOLUME && !noreserve) {
1214 uint64_t spa_version;
1215 zfs_prop_t resv_prop;
1217 spa_version = zpool_get_prop_int(zpool_handle,
1218 ZPOOL_PROP_VERSION, NULL);
1219 if (spa_version >= SPA_VERSION_REFRESERVATION)
1220 resv_prop = ZFS_PROP_REFRESERVATION;
1221 else
1222 resv_prop = ZFS_PROP_RESERVATION;
1224 volsize = zvol_volsize_to_reservation(zpool_handle, volsize,
1225 real_props);
1227 if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
1228 &strval) != 0) {
1229 if (nvlist_add_uint64(props,
1230 zfs_prop_to_name(resv_prop), volsize) != 0) {
1231 nvlist_free(props);
1232 nomem();
1236 if (zpool_handle != NULL) {
1237 zpool_close(zpool_handle);
1238 nvlist_free(real_props);
1241 if (parents && zfs_name_valid(argv[0], type)) {
1243 * Now create the ancestors of target dataset. If the target
1244 * already exists and '-p' option was used we should not
1245 * complain.
1247 if (zfs_dataset_exists(g_zfs, argv[0], type)) {
1248 ret = 0;
1249 goto error;
1251 if (verbose) {
1252 (void) printf(parseable ? "create_ancestors\t%s\n" :
1253 dryrun ? "would create ancestors of %s\n" :
1254 "create ancestors of %s\n", argv[0]);
1256 if (!dryrun) {
1257 if (zfs_create_ancestors(g_zfs, argv[0]) != 0) {
1258 goto error;
1263 if (verbose) {
1264 nvpair_t *nvp = NULL;
1265 (void) printf(parseable ? "create\t%s\n" :
1266 dryrun ? "would create %s\n" : "create %s\n", argv[0]);
1267 while ((nvp = nvlist_next_nvpair(props, nvp)) != NULL) {
1268 uint64_t uval;
1269 const char *sval;
1271 switch (nvpair_type(nvp)) {
1272 case DATA_TYPE_UINT64:
1273 VERIFY0(nvpair_value_uint64(nvp, &uval));
1274 (void) printf(parseable ?
1275 "property\t%s\t%llu\n" : "\t%s=%llu\n",
1276 nvpair_name(nvp), (u_longlong_t)uval);
1277 break;
1278 case DATA_TYPE_STRING:
1279 VERIFY0(nvpair_value_string(nvp, &sval));
1280 (void) printf(parseable ?
1281 "property\t%s\t%s\n" : "\t%s=%s\n",
1282 nvpair_name(nvp), sval);
1283 break;
1284 default:
1285 (void) fprintf(stderr, "property '%s' "
1286 "has illegal type %d\n",
1287 nvpair_name(nvp), nvpair_type(nvp));
1288 abort();
1292 if (dryrun) {
1293 ret = 0;
1294 goto error;
1297 /* pass to libzfs */
1298 if (zfs_create(g_zfs, argv[0], type, props) != 0)
1299 goto error;
1301 if (log_history) {
1302 (void) zpool_log_history(g_zfs, history_str);
1303 log_history = B_FALSE;
1306 if (nomount) {
1307 ret = 0;
1308 goto error;
1311 ret = zfs_mount_and_share(g_zfs, argv[0], ZFS_TYPE_DATASET);
1312 error:
1313 nvlist_free(props);
1314 return (ret);
1315 badusage:
1316 nvlist_free(props);
1317 usage(B_FALSE);
1318 return (2);
1322 * zfs destroy [-rRf] <fs, vol>
1323 * zfs destroy [-rRd] <snap>
1325 * -r Recursively destroy all children
1326 * -R Recursively destroy all dependents, including clones
1327 * -f Force unmounting of any dependents
1328 * -d If we can't destroy now, mark for deferred destruction
1330 * Destroys the given dataset. By default, it will unmount any filesystems,
1331 * and refuse to destroy a dataset that has any dependents. A dependent can
1332 * either be a child, or a clone of a child.
1334 typedef struct destroy_cbdata {
1335 boolean_t cb_first;
1336 boolean_t cb_force;
1337 boolean_t cb_recurse;
1338 boolean_t cb_error;
1339 boolean_t cb_doclones;
1340 zfs_handle_t *cb_target;
1341 boolean_t cb_defer_destroy;
1342 boolean_t cb_verbose;
1343 boolean_t cb_parsable;
1344 boolean_t cb_dryrun;
1345 nvlist_t *cb_nvl;
1346 nvlist_t *cb_batchedsnaps;
1348 /* first snap in contiguous run */
1349 char *cb_firstsnap;
1350 /* previous snap in contiguous run */
1351 char *cb_prevsnap;
1352 int64_t cb_snapused;
1353 char *cb_snapspec;
1354 char *cb_bookmark;
1355 uint64_t cb_snap_count;
1356 } destroy_cbdata_t;
1359 * Check for any dependents based on the '-r' or '-R' flags.
1361 static int
1362 destroy_check_dependent(zfs_handle_t *zhp, void *data)
1364 destroy_cbdata_t *cbp = data;
1365 const char *tname = zfs_get_name(cbp->cb_target);
1366 const char *name = zfs_get_name(zhp);
1368 if (strncmp(tname, name, strlen(tname)) == 0 &&
1369 (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
1371 * This is a direct descendant, not a clone somewhere else in
1372 * the hierarchy.
1374 if (cbp->cb_recurse)
1375 goto out;
1377 if (cbp->cb_first) {
1378 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1379 "%s has children\n"),
1380 zfs_get_name(cbp->cb_target),
1381 zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1382 (void) fprintf(stderr, gettext("use '-r' to destroy "
1383 "the following datasets:\n"));
1384 cbp->cb_first = B_FALSE;
1385 cbp->cb_error = B_TRUE;
1388 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1389 } else {
1391 * This is a clone. We only want to report this if the '-r'
1392 * wasn't specified, or the target is a snapshot.
1394 if (!cbp->cb_recurse &&
1395 zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
1396 goto out;
1398 if (cbp->cb_first) {
1399 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1400 "%s has dependent clones\n"),
1401 zfs_get_name(cbp->cb_target),
1402 zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1403 (void) fprintf(stderr, gettext("use '-R' to destroy "
1404 "the following datasets:\n"));
1405 cbp->cb_first = B_FALSE;
1406 cbp->cb_error = B_TRUE;
1407 cbp->cb_dryrun = B_TRUE;
1410 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1413 out:
1414 zfs_close(zhp);
1415 return (0);
1418 static int
1419 destroy_batched(destroy_cbdata_t *cb)
1421 int error = zfs_destroy_snaps_nvl(g_zfs,
1422 cb->cb_batchedsnaps, B_FALSE);
1423 fnvlist_free(cb->cb_batchedsnaps);
1424 cb->cb_batchedsnaps = fnvlist_alloc();
1425 return (error);
1428 static int
1429 destroy_callback(zfs_handle_t *zhp, void *data)
1431 destroy_cbdata_t *cb = data;
1432 const char *name = zfs_get_name(zhp);
1433 int error;
1435 if (cb->cb_verbose) {
1436 if (cb->cb_parsable) {
1437 (void) printf("destroy\t%s\n", name);
1438 } else if (cb->cb_dryrun) {
1439 (void) printf(gettext("would destroy %s\n"),
1440 name);
1441 } else {
1442 (void) printf(gettext("will destroy %s\n"),
1443 name);
1448 * Ignore pools (which we've already flagged as an error before getting
1449 * here).
1451 if (strchr(zfs_get_name(zhp), '/') == NULL &&
1452 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1453 zfs_close(zhp);
1454 return (0);
1456 if (cb->cb_dryrun) {
1457 zfs_close(zhp);
1458 return (0);
1462 * We batch up all contiguous snapshots (even of different
1463 * filesystems) and destroy them with one ioctl. We can't
1464 * simply do all snap deletions and then all fs deletions,
1465 * because we must delete a clone before its origin.
1467 if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT) {
1468 cb->cb_snap_count++;
1469 fnvlist_add_boolean(cb->cb_batchedsnaps, name);
1470 if (cb->cb_snap_count % 10 == 0 && cb->cb_defer_destroy) {
1471 error = destroy_batched(cb);
1472 if (error != 0) {
1473 zfs_close(zhp);
1474 return (-1);
1477 } else {
1478 error = destroy_batched(cb);
1479 if (error != 0 ||
1480 zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
1481 zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
1482 zfs_close(zhp);
1484 * When performing a recursive destroy we ignore errors
1485 * so that the recursive destroy could continue
1486 * destroying past problem datasets
1488 if (cb->cb_recurse) {
1489 cb->cb_error = B_TRUE;
1490 return (0);
1492 return (-1);
1496 zfs_close(zhp);
1497 return (0);
1500 static int
1501 destroy_print_cb(zfs_handle_t *zhp, void *arg)
1503 destroy_cbdata_t *cb = arg;
1504 const char *name = zfs_get_name(zhp);
1505 int err = 0;
1507 if (nvlist_exists(cb->cb_nvl, name)) {
1508 if (cb->cb_firstsnap == NULL)
1509 cb->cb_firstsnap = strdup(name);
1510 if (cb->cb_prevsnap != NULL)
1511 free(cb->cb_prevsnap);
1512 /* this snap continues the current range */
1513 cb->cb_prevsnap = strdup(name);
1514 if (cb->cb_firstsnap == NULL || cb->cb_prevsnap == NULL)
1515 nomem();
1516 if (cb->cb_verbose) {
1517 if (cb->cb_parsable) {
1518 (void) printf("destroy\t%s\n", name);
1519 } else if (cb->cb_dryrun) {
1520 (void) printf(gettext("would destroy %s\n"),
1521 name);
1522 } else {
1523 (void) printf(gettext("will destroy %s\n"),
1524 name);
1527 } else if (cb->cb_firstsnap != NULL) {
1528 /* end of this range */
1529 uint64_t used = 0;
1530 err = lzc_snaprange_space(cb->cb_firstsnap,
1531 cb->cb_prevsnap, &used);
1532 cb->cb_snapused += used;
1533 free(cb->cb_firstsnap);
1534 cb->cb_firstsnap = NULL;
1535 free(cb->cb_prevsnap);
1536 cb->cb_prevsnap = NULL;
1538 zfs_close(zhp);
1539 return (err);
1542 static int
1543 destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
1545 int err;
1546 assert(cb->cb_firstsnap == NULL);
1547 assert(cb->cb_prevsnap == NULL);
1548 err = zfs_iter_snapshots_sorted_v2(fs_zhp, 0, destroy_print_cb, cb, 0,
1550 if (cb->cb_firstsnap != NULL) {
1551 uint64_t used = 0;
1552 if (err == 0) {
1553 err = lzc_snaprange_space(cb->cb_firstsnap,
1554 cb->cb_prevsnap, &used);
1556 cb->cb_snapused += used;
1557 free(cb->cb_firstsnap);
1558 cb->cb_firstsnap = NULL;
1559 free(cb->cb_prevsnap);
1560 cb->cb_prevsnap = NULL;
1562 return (err);
1565 static int
1566 snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
1568 destroy_cbdata_t *cb = arg;
1569 int err = 0;
1571 /* Check for clones. */
1572 if (!cb->cb_doclones && !cb->cb_defer_destroy) {
1573 cb->cb_target = zhp;
1574 cb->cb_first = B_TRUE;
1575 err = zfs_iter_dependents_v2(zhp, 0, B_TRUE,
1576 destroy_check_dependent, cb);
1579 if (err == 0) {
1580 if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
1581 nomem();
1583 zfs_close(zhp);
1584 return (err);
1587 static int
1588 gather_snapshots(zfs_handle_t *zhp, void *arg)
1590 destroy_cbdata_t *cb = arg;
1591 int err = 0;
1593 err = zfs_iter_snapspec_v2(zhp, 0, cb->cb_snapspec,
1594 snapshot_to_nvl_cb, cb);
1595 if (err == ENOENT)
1596 err = 0;
1597 if (err != 0)
1598 goto out;
1600 if (cb->cb_verbose) {
1601 err = destroy_print_snapshots(zhp, cb);
1602 if (err != 0)
1603 goto out;
1606 if (cb->cb_recurse)
1607 err = zfs_iter_filesystems_v2(zhp, 0, gather_snapshots, cb);
1609 out:
1610 zfs_close(zhp);
1611 return (err);
1614 static int
1615 destroy_clones(destroy_cbdata_t *cb)
1617 nvpair_t *pair;
1618 for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
1619 pair != NULL;
1620 pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
1621 zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
1622 ZFS_TYPE_SNAPSHOT);
1623 if (zhp != NULL) {
1624 boolean_t defer = cb->cb_defer_destroy;
1625 int err;
1628 * We can't defer destroy non-snapshots, so set it to
1629 * false while destroying the clones.
1631 cb->cb_defer_destroy = B_FALSE;
1632 err = zfs_iter_dependents_v2(zhp, 0, B_FALSE,
1633 destroy_callback, cb);
1634 cb->cb_defer_destroy = defer;
1635 zfs_close(zhp);
1636 if (err != 0)
1637 return (err);
1640 return (0);
1643 static int
1644 zfs_do_destroy(int argc, char **argv)
1646 destroy_cbdata_t cb = { 0 };
1647 int rv = 0;
1648 int err = 0;
1649 int c;
1650 zfs_handle_t *zhp = NULL;
1651 char *at, *pound;
1652 zfs_type_t type = ZFS_TYPE_DATASET;
1654 /* check options */
1655 while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
1656 switch (c) {
1657 case 'v':
1658 cb.cb_verbose = B_TRUE;
1659 break;
1660 case 'p':
1661 cb.cb_verbose = B_TRUE;
1662 cb.cb_parsable = B_TRUE;
1663 break;
1664 case 'n':
1665 cb.cb_dryrun = B_TRUE;
1666 break;
1667 case 'd':
1668 cb.cb_defer_destroy = B_TRUE;
1669 type = ZFS_TYPE_SNAPSHOT;
1670 break;
1671 case 'f':
1672 cb.cb_force = B_TRUE;
1673 break;
1674 case 'r':
1675 cb.cb_recurse = B_TRUE;
1676 break;
1677 case 'R':
1678 cb.cb_recurse = B_TRUE;
1679 cb.cb_doclones = B_TRUE;
1680 break;
1681 case '?':
1682 default:
1683 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1684 optopt);
1685 usage(B_FALSE);
1689 argc -= optind;
1690 argv += optind;
1692 /* check number of arguments */
1693 if (argc == 0) {
1694 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1695 usage(B_FALSE);
1697 if (argc > 1) {
1698 (void) fprintf(stderr, gettext("too many arguments\n"));
1699 usage(B_FALSE);
1702 at = strchr(argv[0], '@');
1703 pound = strchr(argv[0], '#');
1704 if (at != NULL) {
1706 /* Build the list of snaps to destroy in cb_nvl. */
1707 cb.cb_nvl = fnvlist_alloc();
1709 *at = '\0';
1710 zhp = zfs_open(g_zfs, argv[0],
1711 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1712 if (zhp == NULL) {
1713 nvlist_free(cb.cb_nvl);
1714 return (1);
1717 cb.cb_snapspec = at + 1;
1718 if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
1719 cb.cb_error) {
1720 rv = 1;
1721 goto out;
1724 if (nvlist_empty(cb.cb_nvl)) {
1725 (void) fprintf(stderr, gettext("could not find any "
1726 "snapshots to destroy; check snapshot names.\n"));
1727 rv = 1;
1728 goto out;
1731 if (cb.cb_verbose) {
1732 char buf[16];
1733 zfs_nicebytes(cb.cb_snapused, buf, sizeof (buf));
1734 if (cb.cb_parsable) {
1735 (void) printf("reclaim\t%llu\n",
1736 (u_longlong_t)cb.cb_snapused);
1737 } else if (cb.cb_dryrun) {
1738 (void) printf(gettext("would reclaim %s\n"),
1739 buf);
1740 } else {
1741 (void) printf(gettext("will reclaim %s\n"),
1742 buf);
1746 if (!cb.cb_dryrun) {
1747 if (cb.cb_doclones) {
1748 cb.cb_batchedsnaps = fnvlist_alloc();
1749 err = destroy_clones(&cb);
1750 if (err == 0) {
1751 err = zfs_destroy_snaps_nvl(g_zfs,
1752 cb.cb_batchedsnaps, B_FALSE);
1754 if (err != 0) {
1755 rv = 1;
1756 goto out;
1759 if (err == 0) {
1760 err = zfs_destroy_snaps_nvl(g_zfs, cb.cb_nvl,
1761 cb.cb_defer_destroy);
1765 if (err != 0)
1766 rv = 1;
1767 } else if (pound != NULL) {
1768 int err;
1769 nvlist_t *nvl;
1771 if (cb.cb_dryrun) {
1772 (void) fprintf(stderr,
1773 "dryrun is not supported with bookmark\n");
1774 return (-1);
1777 if (cb.cb_defer_destroy) {
1778 (void) fprintf(stderr,
1779 "defer destroy is not supported with bookmark\n");
1780 return (-1);
1783 if (cb.cb_recurse) {
1784 (void) fprintf(stderr,
1785 "recursive is not supported with bookmark\n");
1786 return (-1);
1790 * Unfortunately, zfs_bookmark() doesn't honor the
1791 * casesensitivity setting. However, we can't simply
1792 * remove this check, because lzc_destroy_bookmarks()
1793 * ignores non-existent bookmarks, so this is necessary
1794 * to get a proper error message.
1796 if (!zfs_bookmark_exists(argv[0])) {
1797 (void) fprintf(stderr, gettext("bookmark '%s' "
1798 "does not exist.\n"), argv[0]);
1799 return (1);
1802 nvl = fnvlist_alloc();
1803 fnvlist_add_boolean(nvl, argv[0]);
1805 err = lzc_destroy_bookmarks(nvl, NULL);
1806 if (err != 0) {
1807 (void) zfs_standard_error(g_zfs, err,
1808 "cannot destroy bookmark");
1811 nvlist_free(nvl);
1813 return (err);
1814 } else {
1815 /* Open the given dataset */
1816 if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1817 return (1);
1819 cb.cb_target = zhp;
1822 * Perform an explicit check for pools before going any further.
1824 if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1825 zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1826 (void) fprintf(stderr, gettext("cannot destroy '%s': "
1827 "operation does not apply to pools\n"),
1828 zfs_get_name(zhp));
1829 (void) fprintf(stderr, gettext("use 'zfs destroy -r "
1830 "%s' to destroy all datasets in the pool\n"),
1831 zfs_get_name(zhp));
1832 (void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1833 "to destroy the pool itself\n"), zfs_get_name(zhp));
1834 rv = 1;
1835 goto out;
1839 * Check for any dependents and/or clones.
1841 cb.cb_first = B_TRUE;
1842 if (!cb.cb_doclones && zfs_iter_dependents_v2(zhp, 0, B_TRUE,
1843 destroy_check_dependent, &cb) != 0) {
1844 rv = 1;
1845 goto out;
1848 if (cb.cb_error) {
1849 rv = 1;
1850 goto out;
1852 cb.cb_batchedsnaps = fnvlist_alloc();
1853 if (zfs_iter_dependents_v2(zhp, 0, B_FALSE, destroy_callback,
1854 &cb) != 0) {
1855 rv = 1;
1856 goto out;
1860 * Do the real thing. The callback will close the
1861 * handle regardless of whether it succeeds or not.
1863 err = destroy_callback(zhp, &cb);
1864 zhp = NULL;
1865 if (err == 0) {
1866 err = zfs_destroy_snaps_nvl(g_zfs,
1867 cb.cb_batchedsnaps, cb.cb_defer_destroy);
1869 if (err != 0 || cb.cb_error == B_TRUE)
1870 rv = 1;
1873 out:
1874 fnvlist_free(cb.cb_batchedsnaps);
1875 fnvlist_free(cb.cb_nvl);
1876 if (zhp != NULL)
1877 zfs_close(zhp);
1878 return (rv);
1881 static boolean_t
1882 is_recvd_column(zprop_get_cbdata_t *cbp)
1884 int i;
1885 zfs_get_column_t col;
1887 for (i = 0; i < ZFS_GET_NCOLS &&
1888 (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1889 if (col == GET_COL_RECVD)
1890 return (B_TRUE);
1891 return (B_FALSE);
1895 * Generates an nvlist with output version for every command based on params.
1896 * Purpose of this is to add a version of JSON output, considering the schema
1897 * format might be updated for each command in future.
1899 * Schema:
1901 * "output_version": {
1902 * "command": string,
1903 * "vers_major": integer,
1904 * "vers_minor": integer,
1907 static nvlist_t *
1908 zfs_json_schema(int maj_v, int min_v)
1910 nvlist_t *sch = NULL;
1911 nvlist_t *ov = NULL;
1912 char cmd[MAX_CMD_LEN];
1913 snprintf(cmd, MAX_CMD_LEN, "zfs %s", current_command->name);
1915 sch = fnvlist_alloc();
1916 ov = fnvlist_alloc();
1917 fnvlist_add_string(ov, "command", cmd);
1918 fnvlist_add_uint32(ov, "vers_major", maj_v);
1919 fnvlist_add_uint32(ov, "vers_minor", min_v);
1920 fnvlist_add_nvlist(sch, "output_version", ov);
1921 fnvlist_free(ov);
1922 return (sch);
1925 static void
1926 fill_dataset_info(nvlist_t *list, zfs_handle_t *zhp, boolean_t as_int)
1928 char createtxg[ZFS_MAXPROPLEN];
1929 zfs_type_t type = zfs_get_type(zhp);
1930 nvlist_add_string(list, "name", zfs_get_name(zhp));
1932 switch (type) {
1933 case ZFS_TYPE_FILESYSTEM:
1934 fnvlist_add_string(list, "type", "FILESYSTEM");
1935 break;
1936 case ZFS_TYPE_VOLUME:
1937 fnvlist_add_string(list, "type", "VOLUME");
1938 break;
1939 case ZFS_TYPE_SNAPSHOT:
1940 fnvlist_add_string(list, "type", "SNAPSHOT");
1941 break;
1942 case ZFS_TYPE_POOL:
1943 fnvlist_add_string(list, "type", "POOL");
1944 break;
1945 case ZFS_TYPE_BOOKMARK:
1946 fnvlist_add_string(list, "type", "BOOKMARK");
1947 break;
1948 default:
1949 fnvlist_add_string(list, "type", "UNKNOWN");
1950 break;
1953 if (type != ZFS_TYPE_POOL)
1954 fnvlist_add_string(list, "pool", zfs_get_pool_name(zhp));
1956 if (as_int) {
1957 fnvlist_add_uint64(list, "createtxg", zfs_prop_get_int(zhp,
1958 ZFS_PROP_CREATETXG));
1959 } else {
1960 if (zfs_prop_get(zhp, ZFS_PROP_CREATETXG, createtxg,
1961 sizeof (createtxg), NULL, NULL, 0, B_TRUE) == 0)
1962 fnvlist_add_string(list, "createtxg", createtxg);
1965 if (type == ZFS_TYPE_SNAPSHOT) {
1966 char *ds, *snap;
1967 ds = snap = strdup(zfs_get_name(zhp));
1968 ds = strsep(&snap, "@");
1969 fnvlist_add_string(list, "dataset", ds);
1970 fnvlist_add_string(list, "snapshot_name", snap);
1971 free(ds);
1976 * zfs get [-rHp] [-j [--json-int]] [-o all | field[,field]...]
1977 * [-s source[,source]...]
1978 * < all | property[,property]... > < fs | snap | vol > ...
1980 * -r recurse over any child datasets
1981 * -H scripted mode. Headers are stripped, and fields are separated
1982 * by tabs instead of spaces.
1983 * -o Set of fields to display. One of "name,property,value,
1984 * received,source". Default is "name,property,value,source".
1985 * "all" is an alias for all five.
1986 * -s Set of sources to allow. One of
1987 * "local,default,inherited,received,temporary,none". Default is
1988 * all six.
1989 * -p Display values in parsable (literal) format.
1990 * -j Display output in JSON format.
1991 * --json-int Display numbers as integers instead of strings.
1993 * Prints properties for the given datasets. The user can control which
1994 * columns to display as well as which property types to allow.
1998 * Invoked to display the properties for a single dataset.
2000 static int
2001 get_callback(zfs_handle_t *zhp, void *data)
2003 char buf[ZFS_MAXPROPLEN];
2004 char rbuf[ZFS_MAXPROPLEN];
2005 zprop_source_t sourcetype;
2006 char source[ZFS_MAX_DATASET_NAME_LEN];
2007 zprop_get_cbdata_t *cbp = data;
2008 nvlist_t *user_props = zfs_get_user_props(zhp);
2009 zprop_list_t *pl = cbp->cb_proplist;
2010 nvlist_t *propval;
2011 nvlist_t *item, *d, *props;
2012 item = d = props = NULL;
2013 const char *strval;
2014 const char *sourceval;
2015 boolean_t received = is_recvd_column(cbp);
2016 int err = 0;
2018 if (cbp->cb_json) {
2019 d = fnvlist_lookup_nvlist(cbp->cb_jsobj, "datasets");
2020 if (d == NULL) {
2021 fprintf(stderr, "datasets obj not found.\n");
2022 exit(1);
2024 props = fnvlist_alloc();
2027 for (; pl != NULL; pl = pl->pl_next) {
2028 char *recvdval = NULL;
2030 * Skip the special fake placeholder. This will also skip over
2031 * the name property when 'all' is specified.
2033 if (pl->pl_prop == ZFS_PROP_NAME &&
2034 pl == cbp->cb_proplist)
2035 continue;
2037 if (pl->pl_prop != ZPROP_USERPROP) {
2038 if (zfs_prop_get(zhp, pl->pl_prop, buf,
2039 sizeof (buf), &sourcetype, source,
2040 sizeof (source),
2041 cbp->cb_literal) != 0) {
2042 if (pl->pl_all)
2043 continue;
2044 if (!zfs_prop_valid_for_type(pl->pl_prop,
2045 ZFS_TYPE_DATASET, B_FALSE)) {
2046 (void) fprintf(stderr,
2047 gettext("No such property '%s'\n"),
2048 zfs_prop_to_name(pl->pl_prop));
2049 continue;
2051 sourcetype = ZPROP_SRC_NONE;
2052 (void) strlcpy(buf, "-", sizeof (buf));
2055 if (received && (zfs_prop_get_recvd(zhp,
2056 zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
2057 cbp->cb_literal) == 0))
2058 recvdval = rbuf;
2060 err = zprop_collect_property(zfs_get_name(zhp), cbp,
2061 zfs_prop_to_name(pl->pl_prop),
2062 buf, sourcetype, source, recvdval, props);
2063 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
2064 sourcetype = ZPROP_SRC_LOCAL;
2066 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
2067 buf, sizeof (buf), cbp->cb_literal) != 0) {
2068 sourcetype = ZPROP_SRC_NONE;
2069 (void) strlcpy(buf, "-", sizeof (buf));
2072 err = zprop_collect_property(zfs_get_name(zhp), cbp,
2073 pl->pl_user_prop, buf, sourcetype, source, NULL,
2074 props);
2075 } else if (zfs_prop_written(pl->pl_user_prop)) {
2076 sourcetype = ZPROP_SRC_LOCAL;
2078 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
2079 buf, sizeof (buf), cbp->cb_literal) != 0) {
2080 sourcetype = ZPROP_SRC_NONE;
2081 (void) strlcpy(buf, "-", sizeof (buf));
2084 err = zprop_collect_property(zfs_get_name(zhp), cbp,
2085 pl->pl_user_prop, buf, sourcetype, source, NULL,
2086 props);
2087 } else {
2088 if (nvlist_lookup_nvlist(user_props,
2089 pl->pl_user_prop, &propval) != 0) {
2090 if (pl->pl_all)
2091 continue;
2092 sourcetype = ZPROP_SRC_NONE;
2093 strval = "-";
2094 } else {
2095 strval = fnvlist_lookup_string(propval,
2096 ZPROP_VALUE);
2097 sourceval = fnvlist_lookup_string(propval,
2098 ZPROP_SOURCE);
2100 if (strcmp(sourceval,
2101 zfs_get_name(zhp)) == 0) {
2102 sourcetype = ZPROP_SRC_LOCAL;
2103 } else if (strcmp(sourceval,
2104 ZPROP_SOURCE_VAL_RECVD) == 0) {
2105 sourcetype = ZPROP_SRC_RECEIVED;
2106 } else {
2107 sourcetype = ZPROP_SRC_INHERITED;
2108 (void) strlcpy(source,
2109 sourceval, sizeof (source));
2113 if (received && (zfs_prop_get_recvd(zhp,
2114 pl->pl_user_prop, rbuf, sizeof (rbuf),
2115 cbp->cb_literal) == 0))
2116 recvdval = rbuf;
2118 err = zprop_collect_property(zfs_get_name(zhp), cbp,
2119 pl->pl_user_prop, strval, sourcetype,
2120 source, recvdval, props);
2122 if (err != 0)
2123 return (err);
2126 if (cbp->cb_json) {
2127 if (!nvlist_empty(props)) {
2128 item = fnvlist_alloc();
2129 fill_dataset_info(item, zhp, cbp->cb_json_as_int);
2130 fnvlist_add_nvlist(item, "properties", props);
2131 fnvlist_add_nvlist(d, zfs_get_name(zhp), item);
2132 fnvlist_free(props);
2133 fnvlist_free(item);
2134 } else {
2135 fnvlist_free(props);
2139 return (0);
2142 static int
2143 zfs_do_get(int argc, char **argv)
2145 zprop_get_cbdata_t cb = { 0 };
2146 int i, c, flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2147 int types = ZFS_TYPE_DATASET | ZFS_TYPE_BOOKMARK;
2148 char *fields;
2149 int ret = 0;
2150 int limit = 0;
2151 zprop_list_t fake_name = { 0 };
2152 nvlist_t *data;
2155 * Set up default columns and sources.
2157 cb.cb_sources = ZPROP_SRC_ALL;
2158 cb.cb_columns[0] = GET_COL_NAME;
2159 cb.cb_columns[1] = GET_COL_PROPERTY;
2160 cb.cb_columns[2] = GET_COL_VALUE;
2161 cb.cb_columns[3] = GET_COL_SOURCE;
2162 cb.cb_type = ZFS_TYPE_DATASET;
2164 struct option long_options[] = {
2165 {"json", no_argument, NULL, 'j'},
2166 {"json-int", no_argument, NULL, ZFS_OPTION_JSON_NUMS_AS_INT},
2167 {0, 0, 0, 0}
2170 /* check options */
2171 while ((c = getopt_long(argc, argv, ":d:o:s:jrt:Hp", long_options,
2172 NULL)) != -1) {
2173 switch (c) {
2174 case 'p':
2175 cb.cb_literal = B_TRUE;
2176 break;
2177 case 'd':
2178 limit = parse_depth(optarg, &flags);
2179 break;
2180 case 'r':
2181 flags |= ZFS_ITER_RECURSE;
2182 break;
2183 case 'H':
2184 cb.cb_scripted = B_TRUE;
2185 break;
2186 case 'j':
2187 cb.cb_json = B_TRUE;
2188 cb.cb_jsobj = zfs_json_schema(0, 1);
2189 data = fnvlist_alloc();
2190 fnvlist_add_nvlist(cb.cb_jsobj, "datasets", data);
2191 fnvlist_free(data);
2192 break;
2193 case ZFS_OPTION_JSON_NUMS_AS_INT:
2194 cb.cb_json_as_int = B_TRUE;
2195 cb.cb_literal = B_TRUE;
2196 break;
2197 case ':':
2198 (void) fprintf(stderr, gettext("missing argument for "
2199 "'%c' option\n"), optopt);
2200 usage(B_FALSE);
2201 break;
2202 case 'o':
2204 * Process the set of columns to display. We zero out
2205 * the structure to give us a blank slate.
2207 memset(&cb.cb_columns, 0, sizeof (cb.cb_columns));
2209 i = 0;
2210 for (char *tok; (tok = strsep(&optarg, ",")); ) {
2211 static const char *const col_subopts[] =
2212 { "name", "property", "value",
2213 "received", "source", "all" };
2214 static const zfs_get_column_t col_subopt_col[] =
2215 { GET_COL_NAME, GET_COL_PROPERTY, GET_COL_VALUE,
2216 GET_COL_RECVD, GET_COL_SOURCE };
2217 static const int col_subopt_flags[] =
2218 { 0, 0, 0, ZFS_ITER_RECVD_PROPS, 0 };
2220 if (i == ZFS_GET_NCOLS) {
2221 (void) fprintf(stderr, gettext("too "
2222 "many fields given to -o "
2223 "option\n"));
2224 usage(B_FALSE);
2227 for (c = 0; c < ARRAY_SIZE(col_subopts); ++c)
2228 if (strcmp(tok, col_subopts[c]) == 0)
2229 goto found;
2231 (void) fprintf(stderr,
2232 gettext("invalid column name '%s'\n"), tok);
2233 usage(B_FALSE);
2235 found:
2236 if (c >= 5) {
2237 if (i > 0) {
2238 (void) fprintf(stderr,
2239 gettext("\"all\" conflicts "
2240 "with specific fields "
2241 "given to -o option\n"));
2242 usage(B_FALSE);
2245 memcpy(cb.cb_columns, col_subopt_col,
2246 sizeof (col_subopt_col));
2247 flags |= ZFS_ITER_RECVD_PROPS;
2248 i = ZFS_GET_NCOLS;
2249 } else {
2250 cb.cb_columns[i++] = col_subopt_col[c];
2251 flags |= col_subopt_flags[c];
2254 break;
2256 case 's':
2257 cb.cb_sources = 0;
2259 for (char *tok; (tok = strsep(&optarg, ",")); ) {
2260 static const char *const source_opt[] = {
2261 "local", "default",
2262 "inherited", "received",
2263 "temporary", "none" };
2264 static const int source_flg[] = {
2265 ZPROP_SRC_LOCAL, ZPROP_SRC_DEFAULT,
2266 ZPROP_SRC_INHERITED, ZPROP_SRC_RECEIVED,
2267 ZPROP_SRC_TEMPORARY, ZPROP_SRC_NONE };
2269 for (i = 0; i < ARRAY_SIZE(source_opt); ++i)
2270 if (strcmp(tok, source_opt[i]) == 0) {
2271 cb.cb_sources |= source_flg[i];
2272 goto found2;
2275 (void) fprintf(stderr,
2276 gettext("invalid source '%s'\n"), tok);
2277 usage(B_FALSE);
2278 found2:;
2280 break;
2282 case 't':
2283 types = 0;
2284 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
2286 for (char *tok; (tok = strsep(&optarg, ",")); ) {
2287 static const char *const type_opts[] = {
2288 "filesystem",
2289 "fs",
2290 "volume",
2291 "vol",
2292 "snapshot",
2293 "snap",
2294 "bookmark",
2295 "all"
2297 static const int type_types[] = {
2298 ZFS_TYPE_FILESYSTEM,
2299 ZFS_TYPE_FILESYSTEM,
2300 ZFS_TYPE_VOLUME,
2301 ZFS_TYPE_VOLUME,
2302 ZFS_TYPE_SNAPSHOT,
2303 ZFS_TYPE_SNAPSHOT,
2304 ZFS_TYPE_BOOKMARK,
2305 ZFS_TYPE_DATASET | ZFS_TYPE_BOOKMARK
2308 for (i = 0; i < ARRAY_SIZE(type_opts); ++i)
2309 if (strcmp(tok, type_opts[i]) == 0) {
2310 types |= type_types[i];
2311 goto found3;
2314 (void) fprintf(stderr,
2315 gettext("invalid type '%s'\n"), tok);
2316 usage(B_FALSE);
2317 found3:;
2319 break;
2320 case '?':
2321 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2322 optopt);
2323 usage(B_FALSE);
2327 argc -= optind;
2328 argv += optind;
2330 if (argc < 1) {
2331 (void) fprintf(stderr, gettext("missing property "
2332 "argument\n"));
2333 usage(B_FALSE);
2336 if (!cb.cb_json && cb.cb_json_as_int) {
2337 (void) fprintf(stderr, gettext("'--json-int' only works with"
2338 " '-j' option\n"));
2339 usage(B_FALSE);
2342 fields = argv[0];
2345 * Handle users who want to get all snapshots or bookmarks
2346 * of a dataset (ex. 'zfs get -t snapshot refer <dataset>').
2348 if ((types == ZFS_TYPE_SNAPSHOT || types == ZFS_TYPE_BOOKMARK) &&
2349 argc > 1 && (flags & ZFS_ITER_RECURSE) == 0 && limit == 0) {
2350 flags |= (ZFS_ITER_DEPTH_LIMIT | ZFS_ITER_RECURSE);
2351 limit = 1;
2354 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
2355 != 0)
2356 usage(B_FALSE);
2358 argc--;
2359 argv++;
2362 * As part of zfs_expand_proplist(), we keep track of the maximum column
2363 * width for each property. For the 'NAME' (and 'SOURCE') columns, we
2364 * need to know the maximum name length. However, the user likely did
2365 * not specify 'name' as one of the properties to fetch, so we need to
2366 * make sure we always include at least this property for
2367 * print_get_headers() to work properly.
2369 if (cb.cb_proplist != NULL) {
2370 fake_name.pl_prop = ZFS_PROP_NAME;
2371 fake_name.pl_width = strlen(gettext("NAME"));
2372 fake_name.pl_next = cb.cb_proplist;
2373 cb.cb_proplist = &fake_name;
2376 cb.cb_first = B_TRUE;
2378 /* run for each object */
2379 ret = zfs_for_each(argc, argv, flags, types, NULL,
2380 &cb.cb_proplist, limit, get_callback, &cb);
2382 if (ret == 0 && cb.cb_json)
2383 zcmd_print_json(cb.cb_jsobj);
2384 else if (ret != 0 && cb.cb_json)
2385 nvlist_free(cb.cb_jsobj);
2387 if (cb.cb_proplist == &fake_name)
2388 zprop_free_list(fake_name.pl_next);
2389 else
2390 zprop_free_list(cb.cb_proplist);
2392 return (ret);
2396 * inherit [-rS] <property> <fs|vol> ...
2398 * -r Recurse over all children
2399 * -S Revert to received value, if any
2401 * For each dataset specified on the command line, inherit the given property
2402 * from its parent. Inheriting a property at the pool level will cause it to
2403 * use the default value. The '-r' flag will recurse over all children, and is
2404 * useful for setting a property on a hierarchy-wide basis, regardless of any
2405 * local modifications for each dataset.
2408 typedef struct inherit_cbdata {
2409 const char *cb_propname;
2410 boolean_t cb_received;
2411 } inherit_cbdata_t;
2413 static int
2414 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
2416 inherit_cbdata_t *cb = data;
2417 zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
2420 * If we're doing it recursively, then ignore properties that
2421 * are not valid for this type of dataset.
2423 if (prop != ZPROP_INVAL &&
2424 !zfs_prop_valid_for_type(prop, zfs_get_type(zhp), B_FALSE))
2425 return (0);
2427 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
2430 static int
2431 inherit_cb(zfs_handle_t *zhp, void *data)
2433 inherit_cbdata_t *cb = data;
2435 return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
2438 static int
2439 zfs_do_inherit(int argc, char **argv)
2441 int c;
2442 zfs_prop_t prop;
2443 inherit_cbdata_t cb = { 0 };
2444 char *propname;
2445 int ret = 0;
2446 int flags = 0;
2447 boolean_t received = B_FALSE;
2449 /* check options */
2450 while ((c = getopt(argc, argv, "rS")) != -1) {
2451 switch (c) {
2452 case 'r':
2453 flags |= ZFS_ITER_RECURSE;
2454 break;
2455 case 'S':
2456 received = B_TRUE;
2457 break;
2458 case '?':
2459 default:
2460 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2461 optopt);
2462 usage(B_FALSE);
2466 argc -= optind;
2467 argv += optind;
2469 /* check number of arguments */
2470 if (argc < 1) {
2471 (void) fprintf(stderr, gettext("missing property argument\n"));
2472 usage(B_FALSE);
2474 if (argc < 2) {
2475 (void) fprintf(stderr, gettext("missing dataset argument\n"));
2476 usage(B_FALSE);
2479 propname = argv[0];
2480 argc--;
2481 argv++;
2483 if ((prop = zfs_name_to_prop(propname)) != ZPROP_USERPROP) {
2484 if (zfs_prop_readonly(prop)) {
2485 (void) fprintf(stderr, gettext(
2486 "%s property is read-only\n"),
2487 propname);
2488 return (1);
2490 if (!zfs_prop_inheritable(prop) && !received) {
2491 (void) fprintf(stderr, gettext("'%s' property cannot "
2492 "be inherited\n"), propname);
2493 if (prop == ZFS_PROP_QUOTA ||
2494 prop == ZFS_PROP_RESERVATION ||
2495 prop == ZFS_PROP_REFQUOTA ||
2496 prop == ZFS_PROP_REFRESERVATION) {
2497 (void) fprintf(stderr, gettext("use 'zfs set "
2498 "%s=none' to clear\n"), propname);
2499 (void) fprintf(stderr, gettext("use 'zfs "
2500 "inherit -S %s' to revert to received "
2501 "value\n"), propname);
2503 return (1);
2505 if (received && (prop == ZFS_PROP_VOLSIZE ||
2506 prop == ZFS_PROP_VERSION)) {
2507 (void) fprintf(stderr, gettext("'%s' property cannot "
2508 "be reverted to a received value\n"), propname);
2509 return (1);
2511 } else if (!zfs_prop_user(propname)) {
2512 (void) fprintf(stderr, gettext("invalid property '%s'\n"),
2513 propname);
2514 usage(B_FALSE);
2517 cb.cb_propname = propname;
2518 cb.cb_received = received;
2520 if (flags & ZFS_ITER_RECURSE) {
2521 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
2522 NULL, NULL, 0, inherit_recurse_cb, &cb);
2523 } else {
2524 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
2525 NULL, NULL, 0, inherit_cb, &cb);
2528 return (ret);
2531 typedef struct upgrade_cbdata {
2532 uint64_t cb_numupgraded;
2533 uint64_t cb_numsamegraded;
2534 uint64_t cb_numfailed;
2535 uint64_t cb_version;
2536 boolean_t cb_newer;
2537 boolean_t cb_foundone;
2538 char cb_lastfs[ZFS_MAX_DATASET_NAME_LEN];
2539 } upgrade_cbdata_t;
2541 static int
2542 same_pool(zfs_handle_t *zhp, const char *name)
2544 int len1 = strcspn(name, "/@");
2545 const char *zhname = zfs_get_name(zhp);
2546 int len2 = strcspn(zhname, "/@");
2548 if (len1 != len2)
2549 return (B_FALSE);
2550 return (strncmp(name, zhname, len1) == 0);
2553 static int
2554 upgrade_list_callback(zfs_handle_t *zhp, void *data)
2556 upgrade_cbdata_t *cb = data;
2557 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2559 /* list if it's old/new */
2560 if ((!cb->cb_newer && version < ZPL_VERSION) ||
2561 (cb->cb_newer && version > ZPL_VERSION)) {
2562 char *str;
2563 if (cb->cb_newer) {
2564 str = gettext("The following filesystems are "
2565 "formatted using a newer software version and\n"
2566 "cannot be accessed on the current system.\n\n");
2567 } else {
2568 str = gettext("The following filesystems are "
2569 "out of date, and can be upgraded. After being\n"
2570 "upgraded, these filesystems (and any 'zfs send' "
2571 "streams generated from\n"
2572 "subsequent snapshots) will no longer be "
2573 "accessible by older software versions.\n\n");
2576 if (!cb->cb_foundone) {
2577 (void) puts(str);
2578 (void) printf(gettext("VER FILESYSTEM\n"));
2579 (void) printf(gettext("--- ------------\n"));
2580 cb->cb_foundone = B_TRUE;
2583 (void) printf("%2u %s\n", version, zfs_get_name(zhp));
2586 return (0);
2589 static int
2590 upgrade_set_callback(zfs_handle_t *zhp, void *data)
2592 upgrade_cbdata_t *cb = data;
2593 int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2594 int needed_spa_version;
2595 int spa_version;
2597 if (zfs_spa_version(zhp, &spa_version) < 0)
2598 return (-1);
2600 needed_spa_version = zfs_spa_version_map(cb->cb_version);
2602 if (needed_spa_version < 0)
2603 return (-1);
2605 if (spa_version < needed_spa_version) {
2606 /* can't upgrade */
2607 (void) printf(gettext("%s: can not be "
2608 "upgraded; the pool version needs to first "
2609 "be upgraded\nto version %d\n\n"),
2610 zfs_get_name(zhp), needed_spa_version);
2611 cb->cb_numfailed++;
2612 return (0);
2615 /* upgrade */
2616 if (version < cb->cb_version) {
2617 char verstr[24];
2618 (void) snprintf(verstr, sizeof (verstr),
2619 "%llu", (u_longlong_t)cb->cb_version);
2620 if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
2622 * If they did "zfs upgrade -a", then we could
2623 * be doing ioctls to different pools. We need
2624 * to log this history once to each pool, and bypass
2625 * the normal history logging that happens in main().
2627 (void) zpool_log_history(g_zfs, history_str);
2628 log_history = B_FALSE;
2630 if (zfs_prop_set(zhp, "version", verstr) == 0)
2631 cb->cb_numupgraded++;
2632 else
2633 cb->cb_numfailed++;
2634 (void) strlcpy(cb->cb_lastfs, zfs_get_name(zhp),
2635 sizeof (cb->cb_lastfs));
2636 } else if (version > cb->cb_version) {
2637 /* can't downgrade */
2638 (void) printf(gettext("%s: can not be downgraded; "
2639 "it is already at version %u\n"),
2640 zfs_get_name(zhp), version);
2641 cb->cb_numfailed++;
2642 } else {
2643 cb->cb_numsamegraded++;
2645 return (0);
2649 * zfs upgrade
2650 * zfs upgrade -v
2651 * zfs upgrade [-r] [-V <version>] <-a | filesystem>
2653 static int
2654 zfs_do_upgrade(int argc, char **argv)
2656 boolean_t all = B_FALSE;
2657 boolean_t showversions = B_FALSE;
2658 int ret = 0;
2659 upgrade_cbdata_t cb = { 0 };
2660 int c;
2661 int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2663 /* check options */
2664 while ((c = getopt(argc, argv, "rvV:a")) != -1) {
2665 switch (c) {
2666 case 'r':
2667 flags |= ZFS_ITER_RECURSE;
2668 break;
2669 case 'v':
2670 showversions = B_TRUE;
2671 break;
2672 case 'V':
2673 if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
2674 optarg, &cb.cb_version) != 0) {
2675 (void) fprintf(stderr,
2676 gettext("invalid version %s\n"), optarg);
2677 usage(B_FALSE);
2679 break;
2680 case 'a':
2681 all = B_TRUE;
2682 break;
2683 case '?':
2684 default:
2685 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2686 optopt);
2687 usage(B_FALSE);
2691 argc -= optind;
2692 argv += optind;
2694 if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
2695 usage(B_FALSE);
2696 if (showversions && (flags & ZFS_ITER_RECURSE || all ||
2697 cb.cb_version || argc))
2698 usage(B_FALSE);
2699 if ((all || argc) && (showversions))
2700 usage(B_FALSE);
2701 if (all && argc)
2702 usage(B_FALSE);
2704 if (showversions) {
2705 /* Show info on available versions. */
2706 (void) printf(gettext("The following filesystem versions are "
2707 "supported:\n\n"));
2708 (void) printf(gettext("VER DESCRIPTION\n"));
2709 (void) printf("--- -----------------------------------------"
2710 "---------------\n");
2711 (void) printf(gettext(" 1 Initial ZFS filesystem version\n"));
2712 (void) printf(gettext(" 2 Enhanced directory entries\n"));
2713 (void) printf(gettext(" 3 Case insensitive and filesystem "
2714 "user identifier (FUID)\n"));
2715 (void) printf(gettext(" 4 userquota, groupquota "
2716 "properties\n"));
2717 (void) printf(gettext(" 5 System attributes\n"));
2718 (void) printf(gettext("\nFor more information on a particular "
2719 "version, including supported releases,\n"));
2720 (void) printf("see the ZFS Administration Guide.\n\n");
2721 ret = 0;
2722 } else if (argc || all) {
2723 /* Upgrade filesystems */
2724 if (cb.cb_version == 0)
2725 cb.cb_version = ZPL_VERSION;
2726 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
2727 NULL, NULL, 0, upgrade_set_callback, &cb);
2728 (void) printf(gettext("%llu filesystems upgraded\n"),
2729 (u_longlong_t)cb.cb_numupgraded);
2730 if (cb.cb_numsamegraded) {
2731 (void) printf(gettext("%llu filesystems already at "
2732 "this version\n"),
2733 (u_longlong_t)cb.cb_numsamegraded);
2735 if (cb.cb_numfailed != 0)
2736 ret = 1;
2737 } else {
2738 /* List old-version filesystems */
2739 boolean_t found;
2740 (void) printf(gettext("This system is currently running "
2741 "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
2743 flags |= ZFS_ITER_RECURSE;
2744 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2745 NULL, NULL, 0, upgrade_list_callback, &cb);
2747 found = cb.cb_foundone;
2748 cb.cb_foundone = B_FALSE;
2749 cb.cb_newer = B_TRUE;
2751 ret |= zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2752 NULL, NULL, 0, upgrade_list_callback, &cb);
2754 if (!cb.cb_foundone && !found) {
2755 (void) printf(gettext("All filesystems are "
2756 "formatted with the current version.\n"));
2760 return (ret);
2764 * zfs userspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2765 * [-S field [-S field]...] [-t type[,...]]
2766 * filesystem | snapshot | path
2767 * zfs groupspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2768 * [-S field [-S field]...] [-t type[,...]]
2769 * filesystem | snapshot | path
2770 * zfs projectspace [-Hp] [-o field[,...]] [-s field [-s field]...]
2771 * [-S field [-S field]...] filesystem | snapshot | path
2773 * -H Scripted mode; elide headers and separate columns by tabs.
2774 * -i Translate SID to POSIX ID.
2775 * -n Print numeric ID instead of user/group name.
2776 * -o Control which fields to display.
2777 * -p Use exact (parsable) numeric output.
2778 * -s Specify sort columns, descending order.
2779 * -S Specify sort columns, ascending order.
2780 * -t Control which object types to display.
2782 * Displays space consumed by, and quotas on, each user in the specified
2783 * filesystem or snapshot.
2786 /* us_field_types, us_field_hdr and us_field_names should be kept in sync */
2787 enum us_field_types {
2788 USFIELD_TYPE,
2789 USFIELD_NAME,
2790 USFIELD_USED,
2791 USFIELD_QUOTA,
2792 USFIELD_OBJUSED,
2793 USFIELD_OBJQUOTA
2795 static const char *const us_field_hdr[] = { "TYPE", "NAME", "USED", "QUOTA",
2796 "OBJUSED", "OBJQUOTA" };
2797 static const char *const us_field_names[] = { "type", "name", "used", "quota",
2798 "objused", "objquota" };
2799 #define USFIELD_LAST (sizeof (us_field_names) / sizeof (char *))
2801 #define USTYPE_PSX_GRP (1 << 0)
2802 #define USTYPE_PSX_USR (1 << 1)
2803 #define USTYPE_SMB_GRP (1 << 2)
2804 #define USTYPE_SMB_USR (1 << 3)
2805 #define USTYPE_PROJ (1 << 4)
2806 #define USTYPE_ALL \
2807 (USTYPE_PSX_GRP | USTYPE_PSX_USR | USTYPE_SMB_GRP | USTYPE_SMB_USR | \
2808 USTYPE_PROJ)
2810 static int us_type_bits[] = {
2811 USTYPE_PSX_GRP,
2812 USTYPE_PSX_USR,
2813 USTYPE_SMB_GRP,
2814 USTYPE_SMB_USR,
2815 USTYPE_ALL
2817 static const char *const us_type_names[] = { "posixgroup", "posixuser",
2818 "smbgroup", "smbuser", "all" };
2820 typedef struct us_node {
2821 nvlist_t *usn_nvl;
2822 uu_avl_node_t usn_avlnode;
2823 uu_list_node_t usn_listnode;
2824 } us_node_t;
2826 typedef struct us_cbdata {
2827 nvlist_t **cb_nvlp;
2828 uu_avl_pool_t *cb_avl_pool;
2829 uu_avl_t *cb_avl;
2830 boolean_t cb_numname;
2831 boolean_t cb_nicenum;
2832 boolean_t cb_sid2posix;
2833 zfs_userquota_prop_t cb_prop;
2834 zfs_sort_column_t *cb_sortcol;
2835 size_t cb_width[USFIELD_LAST];
2836 } us_cbdata_t;
2838 static boolean_t us_populated = B_FALSE;
2840 typedef struct {
2841 zfs_sort_column_t *si_sortcol;
2842 boolean_t si_numname;
2843 } us_sort_info_t;
2845 static int
2846 us_field_index(const char *field)
2848 for (int i = 0; i < USFIELD_LAST; i++) {
2849 if (strcmp(field, us_field_names[i]) == 0)
2850 return (i);
2853 return (-1);
2856 static int
2857 us_compare(const void *larg, const void *rarg, void *unused)
2859 const us_node_t *l = larg;
2860 const us_node_t *r = rarg;
2861 us_sort_info_t *si = (us_sort_info_t *)unused;
2862 zfs_sort_column_t *sortcol = si->si_sortcol;
2863 boolean_t numname = si->si_numname;
2864 nvlist_t *lnvl = l->usn_nvl;
2865 nvlist_t *rnvl = r->usn_nvl;
2866 int rc = 0;
2867 boolean_t lvb, rvb;
2869 for (; sortcol != NULL; sortcol = sortcol->sc_next) {
2870 const char *lvstr = "";
2871 const char *rvstr = "";
2872 uint32_t lv32 = 0;
2873 uint32_t rv32 = 0;
2874 uint64_t lv64 = 0;
2875 uint64_t rv64 = 0;
2876 zfs_prop_t prop = sortcol->sc_prop;
2877 const char *propname = NULL;
2878 boolean_t reverse = sortcol->sc_reverse;
2880 switch (prop) {
2881 case ZFS_PROP_TYPE:
2882 propname = "type";
2883 (void) nvlist_lookup_uint32(lnvl, propname, &lv32);
2884 (void) nvlist_lookup_uint32(rnvl, propname, &rv32);
2885 if (rv32 != lv32)
2886 rc = (rv32 < lv32) ? 1 : -1;
2887 break;
2888 case ZFS_PROP_NAME:
2889 propname = "name";
2890 if (numname) {
2891 compare_nums:
2892 (void) nvlist_lookup_uint64(lnvl, propname,
2893 &lv64);
2894 (void) nvlist_lookup_uint64(rnvl, propname,
2895 &rv64);
2896 if (rv64 != lv64)
2897 rc = (rv64 < lv64) ? 1 : -1;
2898 } else {
2899 if ((nvlist_lookup_string(lnvl, propname,
2900 &lvstr) == ENOENT) ||
2901 (nvlist_lookup_string(rnvl, propname,
2902 &rvstr) == ENOENT)) {
2903 goto compare_nums;
2905 rc = strcmp(lvstr, rvstr);
2907 break;
2908 case ZFS_PROP_USED:
2909 case ZFS_PROP_QUOTA:
2910 if (!us_populated)
2911 break;
2912 if (prop == ZFS_PROP_USED)
2913 propname = "used";
2914 else
2915 propname = "quota";
2916 (void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2917 (void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2918 if (rv64 != lv64)
2919 rc = (rv64 < lv64) ? 1 : -1;
2920 break;
2922 default:
2923 break;
2926 if (rc != 0) {
2927 if (rc < 0)
2928 return (reverse ? 1 : -1);
2929 else
2930 return (reverse ? -1 : 1);
2935 * If entries still seem to be the same, check if they are of the same
2936 * type (smbentity is added only if we are doing SID to POSIX ID
2937 * translation where we can have duplicate type/name combinations).
2939 if (nvlist_lookup_boolean_value(lnvl, "smbentity", &lvb) == 0 &&
2940 nvlist_lookup_boolean_value(rnvl, "smbentity", &rvb) == 0 &&
2941 lvb != rvb)
2942 return (lvb < rvb ? -1 : 1);
2944 return (0);
2947 static boolean_t
2948 zfs_prop_is_user(unsigned p)
2950 return (p == ZFS_PROP_USERUSED || p == ZFS_PROP_USERQUOTA ||
2951 p == ZFS_PROP_USEROBJUSED || p == ZFS_PROP_USEROBJQUOTA);
2954 static boolean_t
2955 zfs_prop_is_group(unsigned p)
2957 return (p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA ||
2958 p == ZFS_PROP_GROUPOBJUSED || p == ZFS_PROP_GROUPOBJQUOTA);
2961 static boolean_t
2962 zfs_prop_is_project(unsigned p)
2964 return (p == ZFS_PROP_PROJECTUSED || p == ZFS_PROP_PROJECTQUOTA ||
2965 p == ZFS_PROP_PROJECTOBJUSED || p == ZFS_PROP_PROJECTOBJQUOTA);
2968 static inline const char *
2969 us_type2str(unsigned field_type)
2971 switch (field_type) {
2972 case USTYPE_PSX_USR:
2973 return ("POSIX User");
2974 case USTYPE_PSX_GRP:
2975 return ("POSIX Group");
2976 case USTYPE_SMB_USR:
2977 return ("SMB User");
2978 case USTYPE_SMB_GRP:
2979 return ("SMB Group");
2980 case USTYPE_PROJ:
2981 return ("Project");
2982 default:
2983 return ("Undefined");
2987 static int
2988 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2990 us_cbdata_t *cb = (us_cbdata_t *)arg;
2991 zfs_userquota_prop_t prop = cb->cb_prop;
2992 char *name = NULL;
2993 const char *propname;
2994 char sizebuf[32];
2995 us_node_t *node;
2996 uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2997 uu_avl_t *avl = cb->cb_avl;
2998 uu_avl_index_t idx;
2999 nvlist_t *props;
3000 us_node_t *n;
3001 zfs_sort_column_t *sortcol = cb->cb_sortcol;
3002 unsigned type = 0;
3003 const char *typestr;
3004 size_t namelen;
3005 size_t typelen;
3006 size_t sizelen;
3007 int typeidx, nameidx, sizeidx;
3008 us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
3009 boolean_t smbentity = B_FALSE;
3011 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3012 nomem();
3013 node = safe_malloc(sizeof (us_node_t));
3014 uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
3015 node->usn_nvl = props;
3017 if (domain != NULL && domain[0] != '\0') {
3018 #ifdef HAVE_IDMAP
3019 /* SMB */
3020 char sid[MAXNAMELEN + 32];
3021 uid_t id;
3022 uint64_t classes;
3023 int err;
3024 directory_error_t e;
3026 smbentity = B_TRUE;
3028 (void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
3030 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
3031 type = USTYPE_SMB_GRP;
3032 err = sid_to_id(sid, B_FALSE, &id);
3033 } else {
3034 type = USTYPE_SMB_USR;
3035 err = sid_to_id(sid, B_TRUE, &id);
3038 if (err == 0) {
3039 rid = id;
3040 if (!cb->cb_sid2posix) {
3041 e = directory_name_from_sid(NULL, sid, &name,
3042 &classes);
3043 if (e != NULL)
3044 directory_error_free(e);
3045 if (name == NULL)
3046 name = sid;
3049 #else
3050 nvlist_free(props);
3051 free(node);
3053 return (-1);
3054 #endif /* HAVE_IDMAP */
3057 if (cb->cb_sid2posix || domain == NULL || domain[0] == '\0') {
3058 /* POSIX or -i */
3059 if (zfs_prop_is_group(prop)) {
3060 type = USTYPE_PSX_GRP;
3061 if (!cb->cb_numname) {
3062 struct group *g;
3064 if ((g = getgrgid(rid)) != NULL)
3065 name = g->gr_name;
3067 } else if (zfs_prop_is_user(prop)) {
3068 type = USTYPE_PSX_USR;
3069 if (!cb->cb_numname) {
3070 struct passwd *p;
3072 if ((p = getpwuid(rid)) != NULL)
3073 name = p->pw_name;
3075 } else {
3076 type = USTYPE_PROJ;
3081 * Make sure that the type/name combination is unique when doing
3082 * SID to POSIX ID translation (hence changing the type from SMB to
3083 * POSIX).
3085 if (cb->cb_sid2posix &&
3086 nvlist_add_boolean_value(props, "smbentity", smbentity) != 0)
3087 nomem();
3089 /* Calculate/update width of TYPE field */
3090 typestr = us_type2str(type);
3091 typelen = strlen(gettext(typestr));
3092 typeidx = us_field_index("type");
3093 if (typelen > cb->cb_width[typeidx])
3094 cb->cb_width[typeidx] = typelen;
3095 if (nvlist_add_uint32(props, "type", type) != 0)
3096 nomem();
3098 /* Calculate/update width of NAME field */
3099 if ((cb->cb_numname && cb->cb_sid2posix) || name == NULL) {
3100 if (nvlist_add_uint64(props, "name", rid) != 0)
3101 nomem();
3102 namelen = snprintf(NULL, 0, "%u", rid);
3103 } else {
3104 if (nvlist_add_string(props, "name", name) != 0)
3105 nomem();
3106 namelen = strlen(name);
3108 nameidx = us_field_index("name");
3109 if (nameidx >= 0 && namelen > cb->cb_width[nameidx])
3110 cb->cb_width[nameidx] = namelen;
3113 * Check if this type/name combination is in the list and update it;
3114 * otherwise add new node to the list.
3116 if ((n = uu_avl_find(avl, node, &sortinfo, &idx)) == NULL) {
3117 uu_avl_insert(avl, node, idx);
3118 } else {
3119 nvlist_free(props);
3120 free(node);
3121 node = n;
3122 props = node->usn_nvl;
3125 /* Calculate/update width of USED/QUOTA fields */
3126 if (cb->cb_nicenum) {
3127 if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED ||
3128 prop == ZFS_PROP_USERQUOTA || prop == ZFS_PROP_GROUPQUOTA ||
3129 prop == ZFS_PROP_PROJECTUSED ||
3130 prop == ZFS_PROP_PROJECTQUOTA) {
3131 zfs_nicebytes(space, sizebuf, sizeof (sizebuf));
3132 } else {
3133 zfs_nicenum(space, sizebuf, sizeof (sizebuf));
3135 } else {
3136 (void) snprintf(sizebuf, sizeof (sizebuf), "%llu",
3137 (u_longlong_t)space);
3139 sizelen = strlen(sizebuf);
3140 if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED ||
3141 prop == ZFS_PROP_PROJECTUSED) {
3142 propname = "used";
3143 if (!nvlist_exists(props, "quota"))
3144 (void) nvlist_add_uint64(props, "quota", 0);
3145 } else if (prop == ZFS_PROP_USERQUOTA || prop == ZFS_PROP_GROUPQUOTA ||
3146 prop == ZFS_PROP_PROJECTQUOTA) {
3147 propname = "quota";
3148 if (!nvlist_exists(props, "used"))
3149 (void) nvlist_add_uint64(props, "used", 0);
3150 } else if (prop == ZFS_PROP_USEROBJUSED ||
3151 prop == ZFS_PROP_GROUPOBJUSED || prop == ZFS_PROP_PROJECTOBJUSED) {
3152 propname = "objused";
3153 if (!nvlist_exists(props, "objquota"))
3154 (void) nvlist_add_uint64(props, "objquota", 0);
3155 } else if (prop == ZFS_PROP_USEROBJQUOTA ||
3156 prop == ZFS_PROP_GROUPOBJQUOTA ||
3157 prop == ZFS_PROP_PROJECTOBJQUOTA) {
3158 propname = "objquota";
3159 if (!nvlist_exists(props, "objused"))
3160 (void) nvlist_add_uint64(props, "objused", 0);
3161 } else {
3162 return (-1);
3164 sizeidx = us_field_index(propname);
3165 if (sizeidx >= 0 && sizelen > cb->cb_width[sizeidx])
3166 cb->cb_width[sizeidx] = sizelen;
3168 if (nvlist_add_uint64(props, propname, space) != 0)
3169 nomem();
3171 return (0);
3174 static void
3175 print_us_node(boolean_t scripted, boolean_t parsable, int *fields, int types,
3176 size_t *width, us_node_t *node)
3178 nvlist_t *nvl = node->usn_nvl;
3179 char valstr[MAXNAMELEN];
3180 boolean_t first = B_TRUE;
3181 int cfield = 0;
3182 int field;
3183 uint32_t ustype;
3185 /* Check type */
3186 (void) nvlist_lookup_uint32(nvl, "type", &ustype);
3187 if (!(ustype & types))
3188 return;
3190 while ((field = fields[cfield]) != USFIELD_LAST) {
3191 nvpair_t *nvp = NULL;
3192 data_type_t type;
3193 uint32_t val32 = -1;
3194 uint64_t val64 = -1;
3195 const char *strval = "-";
3197 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL)
3198 if (strcmp(nvpair_name(nvp),
3199 us_field_names[field]) == 0)
3200 break;
3202 type = nvp == NULL ? DATA_TYPE_UNKNOWN : nvpair_type(nvp);
3203 switch (type) {
3204 case DATA_TYPE_UINT32:
3205 val32 = fnvpair_value_uint32(nvp);
3206 break;
3207 case DATA_TYPE_UINT64:
3208 val64 = fnvpair_value_uint64(nvp);
3209 break;
3210 case DATA_TYPE_STRING:
3211 strval = fnvpair_value_string(nvp);
3212 break;
3213 case DATA_TYPE_UNKNOWN:
3214 break;
3215 default:
3216 (void) fprintf(stderr, "invalid data type\n");
3219 switch (field) {
3220 case USFIELD_TYPE:
3221 if (type == DATA_TYPE_UINT32)
3222 strval = us_type2str(val32);
3223 break;
3224 case USFIELD_NAME:
3225 if (type == DATA_TYPE_UINT64) {
3226 (void) sprintf(valstr, "%llu",
3227 (u_longlong_t)val64);
3228 strval = valstr;
3230 break;
3231 case USFIELD_USED:
3232 case USFIELD_QUOTA:
3233 if (type == DATA_TYPE_UINT64) {
3234 if (parsable) {
3235 (void) sprintf(valstr, "%llu",
3236 (u_longlong_t)val64);
3237 strval = valstr;
3238 } else if (field == USFIELD_QUOTA &&
3239 val64 == 0) {
3240 strval = "none";
3241 } else {
3242 zfs_nicebytes(val64, valstr,
3243 sizeof (valstr));
3244 strval = valstr;
3247 break;
3248 case USFIELD_OBJUSED:
3249 case USFIELD_OBJQUOTA:
3250 if (type == DATA_TYPE_UINT64) {
3251 if (parsable) {
3252 (void) sprintf(valstr, "%llu",
3253 (u_longlong_t)val64);
3254 strval = valstr;
3255 } else if (field == USFIELD_OBJQUOTA &&
3256 val64 == 0) {
3257 strval = "none";
3258 } else {
3259 zfs_nicenum(val64, valstr,
3260 sizeof (valstr));
3261 strval = valstr;
3264 break;
3267 if (!first) {
3268 if (scripted)
3269 (void) putchar('\t');
3270 else
3271 (void) fputs(" ", stdout);
3273 if (scripted)
3274 (void) fputs(strval, stdout);
3275 else if (field == USFIELD_TYPE || field == USFIELD_NAME)
3276 (void) printf("%-*s", (int)width[field], strval);
3277 else
3278 (void) printf("%*s", (int)width[field], strval);
3280 first = B_FALSE;
3281 cfield++;
3284 (void) putchar('\n');
3287 static void
3288 print_us(boolean_t scripted, boolean_t parsable, int *fields, int types,
3289 size_t *width, boolean_t rmnode, uu_avl_t *avl)
3291 us_node_t *node;
3292 const char *col;
3293 int cfield = 0;
3294 int field;
3296 if (!scripted) {
3297 boolean_t first = B_TRUE;
3299 while ((field = fields[cfield]) != USFIELD_LAST) {
3300 col = gettext(us_field_hdr[field]);
3301 if (field == USFIELD_TYPE || field == USFIELD_NAME) {
3302 (void) printf(first ? "%-*s" : " %-*s",
3303 (int)width[field], col);
3304 } else {
3305 (void) printf(first ? "%*s" : " %*s",
3306 (int)width[field], col);
3308 first = B_FALSE;
3309 cfield++;
3311 (void) printf("\n");
3314 for (node = uu_avl_first(avl); node; node = uu_avl_next(avl, node)) {
3315 print_us_node(scripted, parsable, fields, types, width, node);
3316 if (rmnode)
3317 nvlist_free(node->usn_nvl);
3321 static int
3322 zfs_do_userspace(int argc, char **argv)
3324 zfs_handle_t *zhp;
3325 zfs_userquota_prop_t p;
3326 uu_avl_pool_t *avl_pool;
3327 uu_avl_t *avl_tree;
3328 uu_avl_walk_t *walk;
3329 char *delim;
3330 char deffields[] = "type,name,used,quota,objused,objquota";
3331 char *ofield = NULL;
3332 char *tfield = NULL;
3333 int cfield = 0;
3334 int fields[256];
3335 int i;
3336 boolean_t scripted = B_FALSE;
3337 boolean_t prtnum = B_FALSE;
3338 boolean_t parsable = B_FALSE;
3339 boolean_t sid2posix = B_FALSE;
3340 int ret = 0;
3341 int c;
3342 zfs_sort_column_t *sortcol = NULL;
3343 int types = USTYPE_PSX_USR | USTYPE_SMB_USR;
3344 us_cbdata_t cb;
3345 us_node_t *node;
3346 us_node_t *rmnode;
3347 uu_list_pool_t *listpool;
3348 uu_list_t *list;
3349 uu_avl_index_t idx = 0;
3350 uu_list_index_t idx2 = 0;
3352 if (argc < 2)
3353 usage(B_FALSE);
3355 if (strcmp(argv[0], "groupspace") == 0) {
3356 /* Toggle default group types */
3357 types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
3358 } else if (strcmp(argv[0], "projectspace") == 0) {
3359 types = USTYPE_PROJ;
3360 prtnum = B_TRUE;
3363 while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
3364 switch (c) {
3365 case 'n':
3366 if (types == USTYPE_PROJ) {
3367 (void) fprintf(stderr,
3368 gettext("invalid option 'n'\n"));
3369 usage(B_FALSE);
3371 prtnum = B_TRUE;
3372 break;
3373 case 'H':
3374 scripted = B_TRUE;
3375 break;
3376 case 'p':
3377 parsable = B_TRUE;
3378 break;
3379 case 'o':
3380 ofield = optarg;
3381 break;
3382 case 's':
3383 case 'S':
3384 if (zfs_add_sort_column(&sortcol, optarg,
3385 c == 's' ? B_FALSE : B_TRUE) != 0) {
3386 (void) fprintf(stderr,
3387 gettext("invalid field '%s'\n"), optarg);
3388 usage(B_FALSE);
3390 break;
3391 case 't':
3392 if (types == USTYPE_PROJ) {
3393 (void) fprintf(stderr,
3394 gettext("invalid option 't'\n"));
3395 usage(B_FALSE);
3397 tfield = optarg;
3398 break;
3399 case 'i':
3400 if (types == USTYPE_PROJ) {
3401 (void) fprintf(stderr,
3402 gettext("invalid option 'i'\n"));
3403 usage(B_FALSE);
3405 sid2posix = B_TRUE;
3406 break;
3407 case ':':
3408 (void) fprintf(stderr, gettext("missing argument for "
3409 "'%c' option\n"), optopt);
3410 usage(B_FALSE);
3411 break;
3412 case '?':
3413 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3414 optopt);
3415 usage(B_FALSE);
3419 argc -= optind;
3420 argv += optind;
3422 if (argc < 1) {
3423 (void) fprintf(stderr, gettext("missing dataset name\n"));
3424 usage(B_FALSE);
3426 if (argc > 1) {
3427 (void) fprintf(stderr, gettext("too many arguments\n"));
3428 usage(B_FALSE);
3431 /* Use default output fields if not specified using -o */
3432 if (ofield == NULL)
3433 ofield = deffields;
3434 do {
3435 if ((delim = strchr(ofield, ',')) != NULL)
3436 *delim = '\0';
3437 if ((fields[cfield++] = us_field_index(ofield)) == -1) {
3438 (void) fprintf(stderr, gettext("invalid type '%s' "
3439 "for -o option\n"), ofield);
3440 return (-1);
3442 if (delim != NULL)
3443 ofield = delim + 1;
3444 } while (delim != NULL);
3445 fields[cfield] = USFIELD_LAST;
3447 /* Override output types (-t option) */
3448 if (tfield != NULL) {
3449 types = 0;
3451 do {
3452 boolean_t found = B_FALSE;
3454 if ((delim = strchr(tfield, ',')) != NULL)
3455 *delim = '\0';
3456 for (i = 0; i < sizeof (us_type_bits) / sizeof (int);
3457 i++) {
3458 if (strcmp(tfield, us_type_names[i]) == 0) {
3459 found = B_TRUE;
3460 types |= us_type_bits[i];
3461 break;
3464 if (!found) {
3465 (void) fprintf(stderr, gettext("invalid type "
3466 "'%s' for -t option\n"), tfield);
3467 return (-1);
3469 if (delim != NULL)
3470 tfield = delim + 1;
3471 } while (delim != NULL);
3474 if ((zhp = zfs_path_to_zhandle(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM |
3475 ZFS_TYPE_SNAPSHOT)) == NULL)
3476 return (1);
3477 if (zfs_get_underlying_type(zhp) != ZFS_TYPE_FILESYSTEM) {
3478 (void) fprintf(stderr, gettext("operation is only applicable "
3479 "to filesystems and their snapshots\n"));
3480 zfs_close(zhp);
3481 return (1);
3484 if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
3485 offsetof(us_node_t, usn_avlnode), us_compare, UU_DEFAULT)) == NULL)
3486 nomem();
3487 if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
3488 nomem();
3490 /* Always add default sorting columns */
3491 (void) zfs_add_sort_column(&sortcol, "type", B_FALSE);
3492 (void) zfs_add_sort_column(&sortcol, "name", B_FALSE);
3494 cb.cb_sortcol = sortcol;
3495 cb.cb_numname = prtnum;
3496 cb.cb_nicenum = !parsable;
3497 cb.cb_avl_pool = avl_pool;
3498 cb.cb_avl = avl_tree;
3499 cb.cb_sid2posix = sid2posix;
3501 for (i = 0; i < USFIELD_LAST; i++)
3502 cb.cb_width[i] = strlen(gettext(us_field_hdr[i]));
3504 for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
3505 if ((zfs_prop_is_user(p) &&
3506 !(types & (USTYPE_PSX_USR | USTYPE_SMB_USR))) ||
3507 (zfs_prop_is_group(p) &&
3508 !(types & (USTYPE_PSX_GRP | USTYPE_SMB_GRP))) ||
3509 (zfs_prop_is_project(p) && types != USTYPE_PROJ))
3510 continue;
3512 cb.cb_prop = p;
3513 if ((ret = zfs_userspace(zhp, p, userspace_cb, &cb)) != 0) {
3514 zfs_close(zhp);
3515 return (ret);
3518 zfs_close(zhp);
3520 /* Sort the list */
3521 if ((node = uu_avl_first(avl_tree)) == NULL)
3522 return (0);
3524 us_populated = B_TRUE;
3526 listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
3527 offsetof(us_node_t, usn_listnode), NULL, UU_DEFAULT);
3528 list = uu_list_create(listpool, NULL, UU_DEFAULT);
3529 uu_list_node_init(node, &node->usn_listnode, listpool);
3531 while (node != NULL) {
3532 rmnode = node;
3533 node = uu_avl_next(avl_tree, node);
3534 uu_avl_remove(avl_tree, rmnode);
3535 if (uu_list_find(list, rmnode, NULL, &idx2) == NULL)
3536 uu_list_insert(list, rmnode, idx2);
3539 for (node = uu_list_first(list); node != NULL;
3540 node = uu_list_next(list, node)) {
3541 us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
3543 if (uu_avl_find(avl_tree, node, &sortinfo, &idx) == NULL)
3544 uu_avl_insert(avl_tree, node, idx);
3547 uu_list_destroy(list);
3548 uu_list_pool_destroy(listpool);
3550 /* Print and free node nvlist memory */
3551 print_us(scripted, parsable, fields, types, cb.cb_width, B_TRUE,
3552 cb.cb_avl);
3554 zfs_free_sort_columns(sortcol);
3556 /* Clean up the AVL tree */
3557 if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
3558 nomem();
3560 while ((node = uu_avl_walk_next(walk)) != NULL) {
3561 uu_avl_remove(cb.cb_avl, node);
3562 free(node);
3565 uu_avl_walk_end(walk);
3566 uu_avl_destroy(avl_tree);
3567 uu_avl_pool_destroy(avl_pool);
3569 return (ret);
3573 * list [-Hp][-r|-d max] [-o property[,...]] [-s property] ... [-S property]
3574 * [-t type[,...]] [filesystem|volume|snapshot] ...
3576 * -H Scripted mode; elide headers and separate columns by tabs
3577 * -p Display values in parsable (literal) format.
3578 * -r Recurse over all children
3579 * -d Limit recursion by depth.
3580 * -o Control which fields to display.
3581 * -s Specify sort columns, descending order.
3582 * -S Specify sort columns, ascending order.
3583 * -t Control which object types to display.
3585 * When given no arguments, list all filesystems in the system.
3586 * Otherwise, list the specified datasets, optionally recursing down them if
3587 * '-r' is specified.
3589 typedef struct list_cbdata {
3590 boolean_t cb_first;
3591 boolean_t cb_literal;
3592 boolean_t cb_scripted;
3593 zprop_list_t *cb_proplist;
3594 boolean_t cb_json;
3595 nvlist_t *cb_jsobj;
3596 boolean_t cb_json_as_int;
3597 } list_cbdata_t;
3600 * Given a list of columns to display, output appropriate headers for each one.
3602 static void
3603 print_header(list_cbdata_t *cb)
3605 zprop_list_t *pl = cb->cb_proplist;
3606 char headerbuf[ZFS_MAXPROPLEN];
3607 const char *header;
3608 int i;
3609 boolean_t first = B_TRUE;
3610 boolean_t right_justify;
3612 color_start(ANSI_BOLD);
3614 for (; pl != NULL; pl = pl->pl_next) {
3615 if (!first) {
3616 (void) printf(" ");
3617 } else {
3618 first = B_FALSE;
3621 right_justify = B_FALSE;
3622 if (pl->pl_prop != ZPROP_USERPROP) {
3623 header = zfs_prop_column_name(pl->pl_prop);
3624 right_justify = zfs_prop_align_right(pl->pl_prop);
3625 } else {
3626 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
3627 headerbuf[i] = toupper(pl->pl_user_prop[i]);
3628 headerbuf[i] = '\0';
3629 header = headerbuf;
3632 if (pl->pl_next == NULL && !right_justify)
3633 (void) printf("%s", header);
3634 else if (right_justify)
3635 (void) printf("%*s", (int)pl->pl_width, header);
3636 else
3637 (void) printf("%-*s", (int)pl->pl_width, header);
3640 color_end();
3642 (void) printf("\n");
3646 * Decides on the color that the avail value should be printed in.
3647 * > 80% used = yellow
3648 * > 90% used = red
3650 static const char *
3651 zfs_list_avail_color(zfs_handle_t *zhp)
3653 uint64_t used = zfs_prop_get_int(zhp, ZFS_PROP_USED);
3654 uint64_t avail = zfs_prop_get_int(zhp, ZFS_PROP_AVAILABLE);
3655 int percentage = (int)((double)avail / MAX(avail + used, 1) * 100);
3657 if (percentage > 20)
3658 return (NULL);
3659 else if (percentage > 10)
3660 return (ANSI_YELLOW);
3661 else
3662 return (ANSI_RED);
3666 * Given a dataset and a list of fields, print out all the properties according
3667 * to the described layout, or return an nvlist containing all the fields, later
3668 * to be printed out as JSON object.
3670 static void
3671 collect_dataset(zfs_handle_t *zhp, list_cbdata_t *cb)
3673 zprop_list_t *pl = cb->cb_proplist;
3674 boolean_t first = B_TRUE;
3675 char property[ZFS_MAXPROPLEN];
3676 nvlist_t *userprops = zfs_get_user_props(zhp);
3677 nvlist_t *propval;
3678 const char *propstr;
3679 boolean_t right_justify;
3680 nvlist_t *item, *d, *props;
3681 item = d = props = NULL;
3682 zprop_source_t sourcetype = ZPROP_SRC_NONE;
3683 char source[ZFS_MAX_DATASET_NAME_LEN];
3684 if (cb->cb_json) {
3685 d = fnvlist_lookup_nvlist(cb->cb_jsobj, "datasets");
3686 if (d == NULL) {
3687 fprintf(stderr, "datasets obj not found.\n");
3688 exit(1);
3690 item = fnvlist_alloc();
3691 props = fnvlist_alloc();
3692 fill_dataset_info(item, zhp, cb->cb_json_as_int);
3695 for (; pl != NULL; pl = pl->pl_next) {
3696 if (!cb->cb_json && !first) {
3697 if (cb->cb_scripted)
3698 (void) putchar('\t');
3699 else
3700 (void) fputs(" ", stdout);
3701 } else {
3702 first = B_FALSE;
3705 if (pl->pl_prop == ZFS_PROP_NAME) {
3706 (void) strlcpy(property, zfs_get_name(zhp),
3707 sizeof (property));
3708 propstr = property;
3709 right_justify = zfs_prop_align_right(pl->pl_prop);
3710 } else if (pl->pl_prop != ZPROP_USERPROP) {
3711 if (zfs_prop_get(zhp, pl->pl_prop, property,
3712 sizeof (property), &sourcetype, source,
3713 sizeof (source), cb->cb_literal) != 0)
3714 propstr = "-";
3715 else
3716 propstr = property;
3717 right_justify = zfs_prop_align_right(pl->pl_prop);
3718 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
3719 sourcetype = ZPROP_SRC_LOCAL;
3720 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
3721 property, sizeof (property), cb->cb_literal) != 0) {
3722 sourcetype = ZPROP_SRC_NONE;
3723 propstr = "-";
3724 } else {
3725 propstr = property;
3727 right_justify = B_TRUE;
3728 } else if (zfs_prop_written(pl->pl_user_prop)) {
3729 sourcetype = ZPROP_SRC_LOCAL;
3730 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
3731 property, sizeof (property), cb->cb_literal) != 0) {
3732 sourcetype = ZPROP_SRC_NONE;
3733 propstr = "-";
3734 } else {
3735 propstr = property;
3737 right_justify = B_TRUE;
3738 } else {
3739 if (nvlist_lookup_nvlist(userprops,
3740 pl->pl_user_prop, &propval) != 0) {
3741 propstr = "-";
3742 } else {
3743 propstr = fnvlist_lookup_string(propval,
3744 ZPROP_VALUE);
3745 strlcpy(source,
3746 fnvlist_lookup_string(propval,
3747 ZPROP_SOURCE), ZFS_MAX_DATASET_NAME_LEN);
3748 if (strcmp(source,
3749 zfs_get_name(zhp)) == 0) {
3750 sourcetype = ZPROP_SRC_LOCAL;
3751 } else if (strcmp(source,
3752 ZPROP_SOURCE_VAL_RECVD) == 0) {
3753 sourcetype = ZPROP_SRC_RECEIVED;
3754 } else {
3755 sourcetype = ZPROP_SRC_INHERITED;
3758 right_justify = B_FALSE;
3761 if (cb->cb_json) {
3762 if (pl->pl_prop == ZFS_PROP_NAME)
3763 continue;
3764 const char *prop_name;
3765 if (pl->pl_prop != ZPROP_USERPROP)
3766 prop_name = zfs_prop_to_name(pl->pl_prop);
3767 else
3768 prop_name = pl->pl_user_prop;
3769 if (zprop_nvlist_one_property(
3770 prop_name, propstr,
3771 sourcetype, source, NULL, props,
3772 cb->cb_json_as_int) != 0)
3773 nomem();
3774 } else {
3776 * zfs_list_avail_color() needs
3777 * ZFS_PROP_AVAILABLE + USED, so we need another
3778 * for() search for the USED part when no colors
3779 * wanted, we can skip the whole thing
3781 if (use_color() && pl->pl_prop == ZFS_PROP_AVAILABLE) {
3782 zprop_list_t *pl2 = cb->cb_proplist;
3783 for (; pl2 != NULL; pl2 = pl2->pl_next) {
3784 if (pl2->pl_prop == ZFS_PROP_USED) {
3785 color_start(
3786 zfs_list_avail_color(zhp));
3788 * found it, no need for more
3789 * loops
3791 break;
3797 * If this is being called in scripted mode, or if
3798 * this is the last column and it is left-justified,
3799 * don't include a width format specifier.
3801 if (cb->cb_scripted || (pl->pl_next == NULL &&
3802 !right_justify))
3803 (void) fputs(propstr, stdout);
3804 else if (right_justify) {
3805 (void) printf("%*s", (int)pl->pl_width,
3806 propstr);
3807 } else {
3808 (void) printf("%-*s", (int)pl->pl_width,
3809 propstr);
3812 if (pl->pl_prop == ZFS_PROP_AVAILABLE)
3813 color_end();
3816 if (cb->cb_json) {
3817 fnvlist_add_nvlist(item, "properties", props);
3818 fnvlist_add_nvlist(d, zfs_get_name(zhp), item);
3819 fnvlist_free(props);
3820 fnvlist_free(item);
3821 } else
3822 (void) putchar('\n');
3826 * Generic callback function to list a dataset or snapshot.
3828 static int
3829 list_callback(zfs_handle_t *zhp, void *data)
3831 list_cbdata_t *cbp = data;
3833 if (cbp->cb_first) {
3834 if (!cbp->cb_scripted && !cbp->cb_json)
3835 print_header(cbp);
3836 cbp->cb_first = B_FALSE;
3839 collect_dataset(zhp, cbp);
3841 return (0);
3844 static int
3845 zfs_do_list(int argc, char **argv)
3847 int c;
3848 char default_fields[] =
3849 "name,used,available,referenced,mountpoint";
3850 int types = ZFS_TYPE_DATASET;
3851 boolean_t types_specified = B_FALSE;
3852 char *fields = default_fields;
3853 list_cbdata_t cb = { 0 };
3854 int limit = 0;
3855 int ret = 0;
3856 zfs_sort_column_t *sortcol = NULL;
3857 int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
3858 nvlist_t *data = NULL;
3860 struct option long_options[] = {
3861 {"json", no_argument, NULL, 'j'},
3862 {"json-int", no_argument, NULL, ZFS_OPTION_JSON_NUMS_AS_INT},
3863 {0, 0, 0, 0}
3866 /* check options */
3867 while ((c = getopt_long(argc, argv, "jHS:d:o:prs:t:", long_options,
3868 NULL)) != -1) {
3869 switch (c) {
3870 case 'o':
3871 fields = optarg;
3872 break;
3873 case 'p':
3874 cb.cb_literal = B_TRUE;
3875 flags |= ZFS_ITER_LITERAL_PROPS;
3876 break;
3877 case 'd':
3878 limit = parse_depth(optarg, &flags);
3879 break;
3880 case 'r':
3881 flags |= ZFS_ITER_RECURSE;
3882 break;
3883 case 'j':
3884 cb.cb_json = B_TRUE;
3885 cb.cb_jsobj = zfs_json_schema(0, 1);
3886 data = fnvlist_alloc();
3887 fnvlist_add_nvlist(cb.cb_jsobj, "datasets", data);
3888 fnvlist_free(data);
3889 break;
3890 case ZFS_OPTION_JSON_NUMS_AS_INT:
3891 cb.cb_json_as_int = B_TRUE;
3892 cb.cb_literal = B_TRUE;
3893 break;
3894 case 'H':
3895 cb.cb_scripted = B_TRUE;
3896 break;
3897 case 's':
3898 if (zfs_add_sort_column(&sortcol, optarg,
3899 B_FALSE) != 0) {
3900 (void) fprintf(stderr,
3901 gettext("invalid property '%s'\n"), optarg);
3902 usage(B_FALSE);
3904 break;
3905 case 'S':
3906 if (zfs_add_sort_column(&sortcol, optarg,
3907 B_TRUE) != 0) {
3908 (void) fprintf(stderr,
3909 gettext("invalid property '%s'\n"), optarg);
3910 usage(B_FALSE);
3912 break;
3913 case 't':
3914 types = 0;
3915 types_specified = B_TRUE;
3916 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
3918 for (char *tok; (tok = strsep(&optarg, ",")); ) {
3919 static const char *const type_subopts[] = {
3920 "filesystem",
3921 "fs",
3922 "volume",
3923 "vol",
3924 "snapshot",
3925 "snap",
3926 "bookmark",
3927 "all"
3929 static const int type_types[] = {
3930 ZFS_TYPE_FILESYSTEM,
3931 ZFS_TYPE_FILESYSTEM,
3932 ZFS_TYPE_VOLUME,
3933 ZFS_TYPE_VOLUME,
3934 ZFS_TYPE_SNAPSHOT,
3935 ZFS_TYPE_SNAPSHOT,
3936 ZFS_TYPE_BOOKMARK,
3937 ZFS_TYPE_DATASET | ZFS_TYPE_BOOKMARK
3940 for (c = 0; c < ARRAY_SIZE(type_subopts); ++c)
3941 if (strcmp(tok, type_subopts[c]) == 0) {
3942 types |= type_types[c];
3943 goto found3;
3946 (void) fprintf(stderr,
3947 gettext("invalid type '%s'\n"), tok);
3948 usage(B_FALSE);
3949 found3:;
3951 break;
3952 case ':':
3953 (void) fprintf(stderr, gettext("missing argument for "
3954 "'%c' option\n"), optopt);
3955 usage(B_FALSE);
3956 break;
3957 case '?':
3958 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3959 optopt);
3960 usage(B_FALSE);
3964 argc -= optind;
3965 argv += optind;
3967 if (!cb.cb_json && cb.cb_json_as_int) {
3968 (void) fprintf(stderr, gettext("'--json-int' only works with"
3969 " '-j' option\n"));
3970 usage(B_FALSE);
3974 * If "-o space" and no types were specified, don't display snapshots.
3976 if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3977 types &= ~ZFS_TYPE_SNAPSHOT;
3980 * Handle users who want to list all snapshots or bookmarks
3981 * of the current dataset (ex. 'zfs list -t snapshot <dataset>').
3983 if ((types == ZFS_TYPE_SNAPSHOT || types == ZFS_TYPE_BOOKMARK) &&
3984 argc > 0 && (flags & ZFS_ITER_RECURSE) == 0 && limit == 0) {
3985 flags |= (ZFS_ITER_DEPTH_LIMIT | ZFS_ITER_RECURSE);
3986 limit = 1;
3990 * If the user specifies '-o all', the zprop_get_list() doesn't
3991 * normally include the name of the dataset. For 'zfs list', we always
3992 * want this property to be first.
3994 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3995 != 0)
3996 usage(B_FALSE);
3998 cb.cb_first = B_TRUE;
4001 * If we are only going to list and sort by properties that are "fast"
4002 * then we can use "simple" mode and avoid populating the properties
4003 * nvlist.
4005 if (zfs_list_only_by_fast(cb.cb_proplist) &&
4006 zfs_sort_only_by_fast(sortcol))
4007 flags |= ZFS_ITER_SIMPLE;
4009 ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
4010 limit, list_callback, &cb);
4012 if (ret == 0 && cb.cb_json)
4013 zcmd_print_json(cb.cb_jsobj);
4014 else if (ret != 0 && cb.cb_json)
4015 nvlist_free(cb.cb_jsobj);
4017 zprop_free_list(cb.cb_proplist);
4018 zfs_free_sort_columns(sortcol);
4020 if (ret == 0 && cb.cb_first && !cb.cb_scripted)
4021 (void) fprintf(stderr, gettext("no datasets available\n"));
4023 return (ret);
4027 * zfs rename [-fu] <fs | snap | vol> <fs | snap | vol>
4028 * zfs rename [-f] -p <fs | vol> <fs | vol>
4029 * zfs rename [-u] -r <snap> <snap>
4031 * Renames the given dataset to another of the same type.
4033 * The '-p' flag creates all the non-existing ancestors of the target first.
4034 * The '-u' flag prevents file systems from being remounted during rename.
4036 static int
4037 zfs_do_rename(int argc, char **argv)
4039 zfs_handle_t *zhp;
4040 renameflags_t flags = { 0 };
4041 int c;
4042 int ret = 0;
4043 int types;
4044 boolean_t parents = B_FALSE;
4046 /* check options */
4047 while ((c = getopt(argc, argv, "pruf")) != -1) {
4048 switch (c) {
4049 case 'p':
4050 parents = B_TRUE;
4051 break;
4052 case 'r':
4053 flags.recursive = B_TRUE;
4054 break;
4055 case 'u':
4056 flags.nounmount = B_TRUE;
4057 break;
4058 case 'f':
4059 flags.forceunmount = B_TRUE;
4060 break;
4061 case '?':
4062 default:
4063 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4064 optopt);
4065 usage(B_FALSE);
4069 argc -= optind;
4070 argv += optind;
4072 /* check number of arguments */
4073 if (argc < 1) {
4074 (void) fprintf(stderr, gettext("missing source dataset "
4075 "argument\n"));
4076 usage(B_FALSE);
4078 if (argc < 2) {
4079 (void) fprintf(stderr, gettext("missing target dataset "
4080 "argument\n"));
4081 usage(B_FALSE);
4083 if (argc > 2) {
4084 (void) fprintf(stderr, gettext("too many arguments\n"));
4085 usage(B_FALSE);
4088 if (flags.recursive && parents) {
4089 (void) fprintf(stderr, gettext("-p and -r options are mutually "
4090 "exclusive\n"));
4091 usage(B_FALSE);
4094 if (flags.nounmount && parents) {
4095 (void) fprintf(stderr, gettext("-u and -p options are mutually "
4096 "exclusive\n"));
4097 usage(B_FALSE);
4100 if (flags.recursive && strchr(argv[0], '@') == 0) {
4101 (void) fprintf(stderr, gettext("source dataset for recursive "
4102 "rename must be a snapshot\n"));
4103 usage(B_FALSE);
4106 if (flags.nounmount)
4107 types = ZFS_TYPE_FILESYSTEM;
4108 else if (parents)
4109 types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
4110 else
4111 types = ZFS_TYPE_DATASET;
4113 if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL)
4114 return (1);
4116 /* If we were asked and the name looks good, try to create ancestors. */
4117 if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
4118 zfs_create_ancestors(g_zfs, argv[1]) != 0) {
4119 zfs_close(zhp);
4120 return (1);
4123 ret = (zfs_rename(zhp, argv[1], flags) != 0);
4125 zfs_close(zhp);
4126 return (ret);
4130 * zfs promote <fs>
4132 * Promotes the given clone fs to be the parent
4134 static int
4135 zfs_do_promote(int argc, char **argv)
4137 zfs_handle_t *zhp;
4138 int ret = 0;
4140 /* check options */
4141 if (argc > 1 && argv[1][0] == '-') {
4142 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4143 argv[1][1]);
4144 usage(B_FALSE);
4147 /* check number of arguments */
4148 if (argc < 2) {
4149 (void) fprintf(stderr, gettext("missing clone filesystem"
4150 " argument\n"));
4151 usage(B_FALSE);
4153 if (argc > 2) {
4154 (void) fprintf(stderr, gettext("too many arguments\n"));
4155 usage(B_FALSE);
4158 zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4159 if (zhp == NULL)
4160 return (1);
4162 ret = (zfs_promote(zhp) != 0);
4165 zfs_close(zhp);
4166 return (ret);
4169 static int
4170 zfs_do_redact(int argc, char **argv)
4172 char *snap = NULL;
4173 char *bookname = NULL;
4174 char **rsnaps = NULL;
4175 int numrsnaps = 0;
4176 argv++;
4177 argc--;
4178 if (argc < 3) {
4179 (void) fprintf(stderr, gettext("too few arguments\n"));
4180 usage(B_FALSE);
4183 snap = argv[0];
4184 bookname = argv[1];
4185 rsnaps = argv + 2;
4186 numrsnaps = argc - 2;
4188 nvlist_t *rsnapnv = fnvlist_alloc();
4190 for (int i = 0; i < numrsnaps; i++) {
4191 fnvlist_add_boolean(rsnapnv, rsnaps[i]);
4194 int err = lzc_redact(snap, bookname, rsnapnv);
4195 fnvlist_free(rsnapnv);
4197 switch (err) {
4198 case 0:
4199 break;
4200 case ENOENT: {
4201 zfs_handle_t *zhp = zfs_open(g_zfs, snap, ZFS_TYPE_SNAPSHOT);
4202 if (zhp == NULL) {
4203 (void) fprintf(stderr, gettext("provided snapshot %s "
4204 "does not exist\n"), snap);
4205 } else {
4206 zfs_close(zhp);
4208 for (int i = 0; i < numrsnaps; i++) {
4209 zhp = zfs_open(g_zfs, rsnaps[i], ZFS_TYPE_SNAPSHOT);
4210 if (zhp == NULL) {
4211 (void) fprintf(stderr, gettext("provided "
4212 "snapshot %s does not exist\n"), rsnaps[i]);
4213 } else {
4214 zfs_close(zhp);
4217 break;
4219 case EEXIST:
4220 (void) fprintf(stderr, gettext("specified redaction bookmark "
4221 "(%s) provided already exists\n"), bookname);
4222 break;
4223 case ENAMETOOLONG:
4224 (void) fprintf(stderr, gettext("provided bookmark name cannot "
4225 "be used, final name would be too long\n"));
4226 break;
4227 case E2BIG:
4228 (void) fprintf(stderr, gettext("too many redaction snapshots "
4229 "specified\n"));
4230 break;
4231 case EINVAL:
4232 if (strchr(bookname, '#') != NULL)
4233 (void) fprintf(stderr, gettext(
4234 "redaction bookmark name must not contain '#'\n"));
4235 else
4236 (void) fprintf(stderr, gettext(
4237 "redaction snapshot must be descendent of "
4238 "snapshot being redacted\n"));
4239 break;
4240 case EALREADY:
4241 (void) fprintf(stderr, gettext("attempted to redact redacted "
4242 "dataset or with respect to redacted dataset\n"));
4243 break;
4244 case ENOTSUP:
4245 (void) fprintf(stderr, gettext("redaction bookmarks feature "
4246 "not enabled\n"));
4247 break;
4248 case EXDEV:
4249 (void) fprintf(stderr, gettext("potentially invalid redaction "
4250 "snapshot; full dataset names required\n"));
4251 break;
4252 case ESRCH:
4253 (void) fprintf(stderr, gettext("attempted to resume redaction "
4254 " with a mismatched redaction list\n"));
4255 break;
4256 default:
4257 (void) fprintf(stderr, gettext("internal error: %s\n"),
4258 strerror(errno));
4261 return (err);
4265 * zfs rollback [-rRf] <snapshot>
4267 * -r Delete any intervening snapshots before doing rollback
4268 * -R Delete any snapshots and their clones
4269 * -f ignored for backwards compatibility
4271 * Given a filesystem, rollback to a specific snapshot, discarding any changes
4272 * since then and making it the active dataset. If more recent snapshots exist,
4273 * the command will complain unless the '-r' flag is given.
4275 typedef struct rollback_cbdata {
4276 uint64_t cb_create;
4277 uint8_t cb_younger_ds_printed;
4278 boolean_t cb_first;
4279 int cb_doclones;
4280 char *cb_target;
4281 int cb_error;
4282 boolean_t cb_recurse;
4283 } rollback_cbdata_t;
4285 static int
4286 rollback_check_dependent(zfs_handle_t *zhp, void *data)
4288 rollback_cbdata_t *cbp = data;
4290 if (cbp->cb_first && cbp->cb_recurse) {
4291 (void) fprintf(stderr, gettext("cannot rollback to "
4292 "'%s': clones of previous snapshots exist\n"),
4293 cbp->cb_target);
4294 (void) fprintf(stderr, gettext("use '-R' to "
4295 "force deletion of the following clones and "
4296 "dependents:\n"));
4297 cbp->cb_first = 0;
4298 cbp->cb_error = 1;
4301 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
4303 zfs_close(zhp);
4304 return (0);
4309 * Report some snapshots/bookmarks more recent than the one specified.
4310 * Used when '-r' is not specified. We reuse this same callback for the
4311 * snapshot dependents - if 'cb_dependent' is set, then this is a
4312 * dependent and we should report it without checking the transaction group.
4314 static int
4315 rollback_check(zfs_handle_t *zhp, void *data)
4317 rollback_cbdata_t *cbp = data;
4319 * Max number of younger snapshots and/or bookmarks to display before
4320 * we stop the iteration.
4322 const uint8_t max_younger = 32;
4324 if (cbp->cb_doclones) {
4325 zfs_close(zhp);
4326 return (0);
4329 if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
4330 if (cbp->cb_first && !cbp->cb_recurse) {
4331 (void) fprintf(stderr, gettext("cannot "
4332 "rollback to '%s': more recent snapshots "
4333 "or bookmarks exist\n"),
4334 cbp->cb_target);
4335 (void) fprintf(stderr, gettext("use '-r' to "
4336 "force deletion of the following "
4337 "snapshots and bookmarks:\n"));
4338 cbp->cb_first = 0;
4339 cbp->cb_error = 1;
4342 if (cbp->cb_recurse) {
4343 if (zfs_iter_dependents_v2(zhp, 0, B_TRUE,
4344 rollback_check_dependent, cbp) != 0) {
4345 zfs_close(zhp);
4346 return (-1);
4348 } else {
4349 (void) fprintf(stderr, "%s\n",
4350 zfs_get_name(zhp));
4351 cbp->cb_younger_ds_printed++;
4354 zfs_close(zhp);
4356 if (cbp->cb_younger_ds_printed == max_younger) {
4358 * This non-recursive rollback is going to fail due to the
4359 * presence of snapshots and/or bookmarks that are younger than
4360 * the rollback target.
4361 * We printed some of the offending objects, now we stop
4362 * zfs_iter_snapshot/bookmark iteration so we can fail fast and
4363 * avoid iterating over the rest of the younger objects
4365 (void) fprintf(stderr, gettext("Output limited to %d "
4366 "snapshots/bookmarks\n"), max_younger);
4367 return (-1);
4369 return (0);
4372 static int
4373 zfs_do_rollback(int argc, char **argv)
4375 int ret = 0;
4376 int c;
4377 boolean_t force = B_FALSE;
4378 rollback_cbdata_t cb = { 0 };
4379 zfs_handle_t *zhp, *snap;
4380 char parentname[ZFS_MAX_DATASET_NAME_LEN];
4381 char *delim;
4382 uint64_t min_txg = 0;
4384 /* check options */
4385 while ((c = getopt(argc, argv, "rRf")) != -1) {
4386 switch (c) {
4387 case 'r':
4388 cb.cb_recurse = 1;
4389 break;
4390 case 'R':
4391 cb.cb_recurse = 1;
4392 cb.cb_doclones = 1;
4393 break;
4394 case 'f':
4395 force = B_TRUE;
4396 break;
4397 case '?':
4398 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4399 optopt);
4400 usage(B_FALSE);
4404 argc -= optind;
4405 argv += optind;
4407 /* check number of arguments */
4408 if (argc < 1) {
4409 (void) fprintf(stderr, gettext("missing dataset argument\n"));
4410 usage(B_FALSE);
4412 if (argc > 1) {
4413 (void) fprintf(stderr, gettext("too many arguments\n"));
4414 usage(B_FALSE);
4417 /* open the snapshot */
4418 if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
4419 return (1);
4421 /* open the parent dataset */
4422 (void) strlcpy(parentname, argv[0], sizeof (parentname));
4423 verify((delim = strrchr(parentname, '@')) != NULL);
4424 *delim = '\0';
4425 if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
4426 zfs_close(snap);
4427 return (1);
4431 * Check for more recent snapshots and/or clones based on the presence
4432 * of '-r' and '-R'.
4434 cb.cb_target = argv[0];
4435 cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
4436 cb.cb_first = B_TRUE;
4437 cb.cb_error = 0;
4439 if (cb.cb_create > 0)
4440 min_txg = cb.cb_create;
4442 if ((ret = zfs_iter_snapshots_v2(zhp, 0, rollback_check, &cb,
4443 min_txg, 0)) != 0)
4444 goto out;
4445 if ((ret = zfs_iter_bookmarks_v2(zhp, 0, rollback_check, &cb)) != 0)
4446 goto out;
4448 if ((ret = cb.cb_error) != 0)
4449 goto out;
4452 * Rollback parent to the given snapshot.
4454 ret = zfs_rollback(zhp, snap, force);
4456 out:
4457 zfs_close(snap);
4458 zfs_close(zhp);
4460 if (ret == 0)
4461 return (0);
4462 else
4463 return (1);
4467 * zfs set property=value ... { fs | snap | vol } ...
4469 * Sets the given properties for all datasets specified on the command line.
4472 static int
4473 set_callback(zfs_handle_t *zhp, void *data)
4475 zprop_set_cbdata_t *cb = data;
4476 int ret = zfs_prop_set_list_flags(zhp, cb->cb_proplist, cb->cb_flags);
4478 if (ret != 0 || libzfs_errno(g_zfs) != EZFS_SUCCESS) {
4479 switch (libzfs_errno(g_zfs)) {
4480 case EZFS_MOUNTFAILED:
4481 (void) fprintf(stderr, gettext("property may be set "
4482 "but unable to remount filesystem\n"));
4483 break;
4484 case EZFS_SHARENFSFAILED:
4485 (void) fprintf(stderr, gettext("property may be set "
4486 "but unable to reshare filesystem\n"));
4487 break;
4490 return (ret);
4493 static int
4494 zfs_do_set(int argc, char **argv)
4496 zprop_set_cbdata_t cb = { 0 };
4497 int ds_start = -1; /* argv idx of first dataset arg */
4498 int ret = 0;
4499 int i, c;
4501 /* check options */
4502 while ((c = getopt(argc, argv, "u")) != -1) {
4503 switch (c) {
4504 case 'u':
4505 cb.cb_flags |= ZFS_SET_NOMOUNT;
4506 break;
4507 case '?':
4508 default:
4509 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4510 optopt);
4511 usage(B_FALSE);
4515 argc -= optind;
4516 argv += optind;
4518 /* check number of arguments */
4519 if (argc < 1) {
4520 (void) fprintf(stderr, gettext("missing arguments\n"));
4521 usage(B_FALSE);
4523 if (argc < 2) {
4524 if (strchr(argv[0], '=') == NULL) {
4525 (void) fprintf(stderr, gettext("missing property=value "
4526 "argument(s)\n"));
4527 } else {
4528 (void) fprintf(stderr, gettext("missing dataset "
4529 "name(s)\n"));
4531 usage(B_FALSE);
4534 /* validate argument order: prop=val args followed by dataset args */
4535 for (i = 0; i < argc; i++) {
4536 if (strchr(argv[i], '=') != NULL) {
4537 if (ds_start > 0) {
4538 /* out-of-order prop=val argument */
4539 (void) fprintf(stderr, gettext("invalid "
4540 "argument order\n"));
4541 usage(B_FALSE);
4543 } else if (ds_start < 0) {
4544 ds_start = i;
4547 if (ds_start < 0) {
4548 (void) fprintf(stderr, gettext("missing dataset name(s)\n"));
4549 usage(B_FALSE);
4552 /* Populate a list of property settings */
4553 if (nvlist_alloc(&cb.cb_proplist, NV_UNIQUE_NAME, 0) != 0)
4554 nomem();
4555 for (i = 0; i < ds_start; i++) {
4556 if (!parseprop(cb.cb_proplist, argv[i])) {
4557 ret = -1;
4558 goto error;
4562 ret = zfs_for_each(argc - ds_start, argv + ds_start, 0,
4563 ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, &cb);
4565 error:
4566 nvlist_free(cb.cb_proplist);
4567 return (ret);
4570 typedef struct snap_cbdata {
4571 nvlist_t *sd_nvl;
4572 boolean_t sd_recursive;
4573 const char *sd_snapname;
4574 } snap_cbdata_t;
4576 static int
4577 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
4579 snap_cbdata_t *sd = arg;
4580 char *name;
4581 int rv = 0;
4582 int error;
4584 if (sd->sd_recursive &&
4585 zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
4586 zfs_close(zhp);
4587 return (0);
4590 error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
4591 if (error == -1)
4592 nomem();
4593 fnvlist_add_boolean(sd->sd_nvl, name);
4594 free(name);
4596 if (sd->sd_recursive)
4597 rv = zfs_iter_filesystems_v2(zhp, 0, zfs_snapshot_cb, sd);
4598 zfs_close(zhp);
4599 return (rv);
4603 * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
4605 * Creates a snapshot with the given name. While functionally equivalent to
4606 * 'zfs create', it is a separate command to differentiate intent.
4608 static int
4609 zfs_do_snapshot(int argc, char **argv)
4611 int ret = 0;
4612 int c;
4613 nvlist_t *props;
4614 snap_cbdata_t sd = { 0 };
4615 boolean_t multiple_snaps = B_FALSE;
4617 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
4618 nomem();
4619 if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
4620 nomem();
4622 /* check options */
4623 while ((c = getopt(argc, argv, "ro:")) != -1) {
4624 switch (c) {
4625 case 'o':
4626 if (!parseprop(props, optarg)) {
4627 nvlist_free(sd.sd_nvl);
4628 nvlist_free(props);
4629 return (1);
4631 break;
4632 case 'r':
4633 sd.sd_recursive = B_TRUE;
4634 multiple_snaps = B_TRUE;
4635 break;
4636 case '?':
4637 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4638 optopt);
4639 goto usage;
4643 argc -= optind;
4644 argv += optind;
4646 /* check number of arguments */
4647 if (argc < 1) {
4648 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
4649 goto usage;
4652 if (argc > 1)
4653 multiple_snaps = B_TRUE;
4654 for (; argc > 0; argc--, argv++) {
4655 char *atp;
4656 zfs_handle_t *zhp;
4658 atp = strchr(argv[0], '@');
4659 if (atp == NULL)
4660 goto usage;
4661 *atp = '\0';
4662 sd.sd_snapname = atp + 1;
4663 zhp = zfs_open(g_zfs, argv[0],
4664 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4665 if (zhp == NULL)
4666 goto usage;
4667 if (zfs_snapshot_cb(zhp, &sd) != 0)
4668 goto usage;
4671 ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
4672 nvlist_free(sd.sd_nvl);
4673 nvlist_free(props);
4674 if (ret != 0 && multiple_snaps)
4675 (void) fprintf(stderr, gettext("no snapshots were created\n"));
4676 return (ret != 0);
4678 usage:
4679 nvlist_free(sd.sd_nvl);
4680 nvlist_free(props);
4681 usage(B_FALSE);
4682 return (-1);
4686 * Array of prefixes to exclude –
4687 * a linear search, even if executed for each dataset,
4688 * is plenty good enough.
4690 typedef struct zfs_send_exclude_arg {
4691 size_t count;
4692 const char **list;
4693 } zfs_send_exclude_arg_t;
4695 static boolean_t
4696 zfs_do_send_exclude(zfs_handle_t *zhp, void *context)
4698 zfs_send_exclude_arg_t *excludes = context;
4699 const char *name = zfs_get_name(zhp);
4701 for (size_t i = 0; i < excludes->count; ++i) {
4702 size_t len = strlen(excludes->list[i]);
4703 if (strncmp(name, excludes->list[i], len) == 0 &&
4704 memchr("/@", name[len], sizeof ("/@")))
4705 return (B_FALSE);
4708 return (B_TRUE);
4712 * Send a backup stream to stdout.
4714 static int
4715 zfs_do_send(int argc, char **argv)
4717 char *fromname = NULL;
4718 char *toname = NULL;
4719 char *resume_token = NULL;
4720 char *cp;
4721 zfs_handle_t *zhp;
4722 sendflags_t flags = { 0 };
4723 int c, err;
4724 nvlist_t *dbgnv = NULL;
4725 char *redactbook = NULL;
4726 zfs_send_exclude_arg_t excludes = { 0 };
4728 struct option long_options[] = {
4729 {"replicate", no_argument, NULL, 'R'},
4730 {"skip-missing", no_argument, NULL, 's'},
4731 {"redact", required_argument, NULL, 'd'},
4732 {"props", no_argument, NULL, 'p'},
4733 {"parsable", no_argument, NULL, 'P'},
4734 {"dedup", no_argument, NULL, 'D'},
4735 {"proctitle", no_argument, NULL, 'V'},
4736 {"verbose", no_argument, NULL, 'v'},
4737 {"dryrun", no_argument, NULL, 'n'},
4738 {"large-block", no_argument, NULL, 'L'},
4739 {"embed", no_argument, NULL, 'e'},
4740 {"resume", required_argument, NULL, 't'},
4741 {"compressed", no_argument, NULL, 'c'},
4742 {"raw", no_argument, NULL, 'w'},
4743 {"backup", no_argument, NULL, 'b'},
4744 {"holds", no_argument, NULL, 'h'},
4745 {"saved", no_argument, NULL, 'S'},
4746 {"exclude", required_argument, NULL, 'X'},
4747 {0, 0, 0, 0}
4750 /* check options */
4751 while ((c = getopt_long(argc, argv, ":i:I:RsDpVvnPLeht:cwbd:SX:",
4752 long_options, NULL)) != -1) {
4753 switch (c) {
4754 case 'X':
4755 for (char *ds; (ds = strsep(&optarg, ",")) != NULL; ) {
4756 if (!zfs_name_valid(ds, ZFS_TYPE_DATASET) ||
4757 strchr(ds, '/') == NULL) {
4758 (void) fprintf(stderr, gettext("-X %s: "
4759 "not a valid non-root dataset name"
4760 ".\n"), ds);
4761 usage(B_FALSE);
4763 excludes.list = safe_realloc(excludes.list,
4764 sizeof (char *) * (excludes.count + 1));
4765 excludes.list[excludes.count++] = ds;
4767 break;
4768 case 'i':
4769 if (fromname)
4770 usage(B_FALSE);
4771 fromname = optarg;
4772 break;
4773 case 'I':
4774 if (fromname)
4775 usage(B_FALSE);
4776 fromname = optarg;
4777 flags.doall = B_TRUE;
4778 break;
4779 case 'R':
4780 flags.replicate = B_TRUE;
4781 break;
4782 case 's':
4783 flags.skipmissing = B_TRUE;
4784 break;
4785 case 'd':
4786 redactbook = optarg;
4787 break;
4788 case 'p':
4789 flags.props = B_TRUE;
4790 break;
4791 case 'b':
4792 flags.backup = B_TRUE;
4793 break;
4794 case 'h':
4795 flags.holds = B_TRUE;
4796 break;
4797 case 'P':
4798 flags.parsable = B_TRUE;
4799 break;
4800 case 'V':
4801 flags.progressastitle = B_TRUE;
4802 break;
4803 case 'v':
4804 flags.verbosity++;
4805 flags.progress = B_TRUE;
4806 break;
4807 case 'D':
4808 (void) fprintf(stderr,
4809 gettext("WARNING: deduplicated send is no "
4810 "longer supported. A regular,\n"
4811 "non-deduplicated stream will be generated.\n\n"));
4812 break;
4813 case 'n':
4814 flags.dryrun = B_TRUE;
4815 break;
4816 case 'L':
4817 flags.largeblock = B_TRUE;
4818 break;
4819 case 'e':
4820 flags.embed_data = B_TRUE;
4821 break;
4822 case 't':
4823 resume_token = optarg;
4824 break;
4825 case 'c':
4826 flags.compress = B_TRUE;
4827 break;
4828 case 'w':
4829 flags.raw = B_TRUE;
4830 flags.compress = B_TRUE;
4831 flags.embed_data = B_TRUE;
4832 flags.largeblock = B_TRUE;
4833 break;
4834 case 'S':
4835 flags.saved = B_TRUE;
4836 break;
4837 case ':':
4839 * If a parameter was not passed, optopt contains the
4840 * value that would normally lead us into the
4841 * appropriate case statement. If it's > 256, then this
4842 * must be a longopt and we should look at argv to get
4843 * the string. Otherwise it's just the character, so we
4844 * should use it directly.
4846 if (optopt <= UINT8_MAX) {
4847 (void) fprintf(stderr,
4848 gettext("missing argument for '%c' "
4849 "option\n"), optopt);
4850 } else {
4851 (void) fprintf(stderr,
4852 gettext("missing argument for '%s' "
4853 "option\n"), argv[optind - 1]);
4855 free(excludes.list);
4856 usage(B_FALSE);
4857 break;
4858 case '?':
4859 default:
4861 * If an invalid flag was passed, optopt contains the
4862 * character if it was a short flag, or 0 if it was a
4863 * longopt.
4865 if (optopt != 0) {
4866 (void) fprintf(stderr,
4867 gettext("invalid option '%c'\n"), optopt);
4868 } else {
4869 (void) fprintf(stderr,
4870 gettext("invalid option '%s'\n"),
4871 argv[optind - 1]);
4874 free(excludes.list);
4875 usage(B_FALSE);
4879 if ((flags.parsable || flags.progressastitle) && flags.verbosity == 0)
4880 flags.verbosity = 1;
4882 if (excludes.count > 0 && !flags.replicate) {
4883 free(excludes.list);
4884 (void) fprintf(stderr, gettext("Cannot specify "
4885 "dataset exclusion (-X) on a non-recursive "
4886 "send.\n"));
4887 return (1);
4890 argc -= optind;
4891 argv += optind;
4893 if (resume_token != NULL) {
4894 if (fromname != NULL || flags.replicate || flags.props ||
4895 flags.backup || flags.holds ||
4896 flags.saved || redactbook != NULL) {
4897 free(excludes.list);
4898 (void) fprintf(stderr,
4899 gettext("invalid flags combined with -t\n"));
4900 usage(B_FALSE);
4902 if (argc > 0) {
4903 free(excludes.list);
4904 (void) fprintf(stderr, gettext("too many arguments\n"));
4905 usage(B_FALSE);
4907 } else {
4908 if (argc < 1) {
4909 free(excludes.list);
4910 (void) fprintf(stderr,
4911 gettext("missing snapshot argument\n"));
4912 usage(B_FALSE);
4914 if (argc > 1) {
4915 free(excludes.list);
4916 (void) fprintf(stderr, gettext("too many arguments\n"));
4917 usage(B_FALSE);
4921 if (flags.saved) {
4922 if (fromname != NULL || flags.replicate || flags.props ||
4923 flags.doall || flags.backup ||
4924 flags.holds || flags.largeblock || flags.embed_data ||
4925 flags.compress || flags.raw || redactbook != NULL) {
4926 free(excludes.list);
4928 (void) fprintf(stderr, gettext("incompatible flags "
4929 "combined with saved send flag\n"));
4930 usage(B_FALSE);
4932 if (strchr(argv[0], '@') != NULL) {
4933 free(excludes.list);
4935 (void) fprintf(stderr, gettext("saved send must "
4936 "specify the dataset with partially-received "
4937 "state\n"));
4938 usage(B_FALSE);
4942 if (flags.raw && redactbook != NULL) {
4943 free(excludes.list);
4944 (void) fprintf(stderr,
4945 gettext("Error: raw sends may not be redacted.\n"));
4946 return (1);
4949 if (!flags.dryrun && isatty(STDOUT_FILENO)) {
4950 free(excludes.list);
4951 (void) fprintf(stderr,
4952 gettext("Error: Stream can not be written to a terminal.\n"
4953 "You must redirect standard output.\n"));
4954 return (1);
4957 if (flags.saved) {
4958 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
4959 if (zhp == NULL) {
4960 free(excludes.list);
4961 return (1);
4964 err = zfs_send_saved(zhp, &flags, STDOUT_FILENO,
4965 resume_token);
4966 free(excludes.list);
4967 zfs_close(zhp);
4968 return (err != 0);
4969 } else if (resume_token != NULL) {
4970 free(excludes.list);
4971 return (zfs_send_resume(g_zfs, &flags, STDOUT_FILENO,
4972 resume_token));
4975 if (flags.skipmissing && !flags.replicate) {
4976 free(excludes.list);
4977 (void) fprintf(stderr,
4978 gettext("skip-missing flag can only be used in "
4979 "conjunction with replicate\n"));
4980 usage(B_FALSE);
4984 * For everything except -R and -I, use the new, cleaner code path.
4986 if (!(flags.replicate || flags.doall)) {
4987 char frombuf[ZFS_MAX_DATASET_NAME_LEN];
4989 if (fromname != NULL && (strchr(fromname, '#') == NULL &&
4990 strchr(fromname, '@') == NULL)) {
4992 * Neither bookmark or snapshot was specified. Print a
4993 * warning, and assume snapshot.
4995 (void) fprintf(stderr, "Warning: incremental source "
4996 "didn't specify type, assuming snapshot. Use '@' "
4997 "or '#' prefix to avoid ambiguity.\n");
4998 (void) snprintf(frombuf, sizeof (frombuf), "@%s",
4999 fromname);
5000 fromname = frombuf;
5002 if (fromname != NULL &&
5003 (fromname[0] == '#' || fromname[0] == '@')) {
5005 * Incremental source name begins with # or @.
5006 * Default to same fs as target.
5008 char tmpbuf[ZFS_MAX_DATASET_NAME_LEN];
5009 (void) strlcpy(tmpbuf, fromname, sizeof (tmpbuf));
5010 (void) strlcpy(frombuf, argv[0], sizeof (frombuf));
5011 cp = strchr(frombuf, '@');
5012 if (cp != NULL)
5013 *cp = '\0';
5014 (void) strlcat(frombuf, tmpbuf, sizeof (frombuf));
5015 fromname = frombuf;
5018 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
5019 if (zhp == NULL) {
5020 free(excludes.list);
5021 return (1);
5023 err = zfs_send_one(zhp, fromname, STDOUT_FILENO, &flags,
5024 redactbook);
5026 free(excludes.list);
5027 zfs_close(zhp);
5028 return (err != 0);
5031 if (fromname != NULL && strchr(fromname, '#')) {
5032 (void) fprintf(stderr,
5033 gettext("Error: multiple snapshots cannot be "
5034 "sent from a bookmark.\n"));
5035 free(excludes.list);
5036 return (1);
5039 if (redactbook != NULL) {
5040 (void) fprintf(stderr, gettext("Error: multiple snapshots "
5041 "cannot be sent redacted.\n"));
5042 free(excludes.list);
5043 return (1);
5046 if ((cp = strchr(argv[0], '@')) == NULL) {
5047 (void) fprintf(stderr, gettext("Error: "
5048 "Unsupported flag with filesystem or bookmark.\n"));
5049 free(excludes.list);
5050 return (1);
5052 *cp = '\0';
5053 toname = cp + 1;
5054 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5055 if (zhp == NULL) {
5056 free(excludes.list);
5057 return (1);
5061 * If they specified the full path to the snapshot, chop off
5062 * everything except the short name of the snapshot, but special
5063 * case if they specify the origin.
5065 if (fromname && (cp = strchr(fromname, '@')) != NULL) {
5066 char origin[ZFS_MAX_DATASET_NAME_LEN];
5067 zprop_source_t src;
5069 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
5070 origin, sizeof (origin), &src, NULL, 0, B_FALSE);
5072 if (strcmp(origin, fromname) == 0) {
5073 fromname = NULL;
5074 flags.fromorigin = B_TRUE;
5075 } else {
5076 *cp = '\0';
5077 if (cp != fromname && strcmp(argv[0], fromname)) {
5078 zfs_close(zhp);
5079 free(excludes.list);
5080 (void) fprintf(stderr,
5081 gettext("incremental source must be "
5082 "in same filesystem\n"));
5083 usage(B_FALSE);
5085 fromname = cp + 1;
5086 if (strchr(fromname, '@') || strchr(fromname, '/')) {
5087 zfs_close(zhp);
5088 free(excludes.list);
5089 (void) fprintf(stderr,
5090 gettext("invalid incremental source\n"));
5091 usage(B_FALSE);
5096 if (flags.replicate && fromname == NULL)
5097 flags.doall = B_TRUE;
5099 err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO,
5100 excludes.count > 0 ? zfs_do_send_exclude : NULL,
5101 &excludes, flags.verbosity >= 3 ? &dbgnv : NULL);
5103 if (flags.verbosity >= 3 && dbgnv != NULL) {
5105 * dump_nvlist prints to stdout, but that's been
5106 * redirected to a file. Make it print to stderr
5107 * instead.
5109 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
5110 dump_nvlist(dbgnv, 0);
5111 nvlist_free(dbgnv);
5114 zfs_close(zhp);
5115 free(excludes.list);
5116 return (err != 0);
5120 * Restore a backup stream from stdin.
5122 static int
5123 zfs_do_receive(int argc, char **argv)
5125 int c, err = 0;
5126 recvflags_t flags = { 0 };
5127 boolean_t abort_resumable = B_FALSE;
5128 nvlist_t *props;
5130 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
5131 nomem();
5133 /* check options */
5134 while ((c = getopt(argc, argv, ":o:x:dehMnuvFsAc")) != -1) {
5135 switch (c) {
5136 case 'o':
5137 if (!parseprop(props, optarg)) {
5138 nvlist_free(props);
5139 usage(B_FALSE);
5141 break;
5142 case 'x':
5143 if (!parsepropname(props, optarg)) {
5144 nvlist_free(props);
5145 usage(B_FALSE);
5147 break;
5148 case 'd':
5149 if (flags.istail) {
5150 (void) fprintf(stderr, gettext("invalid option "
5151 "combination: -d and -e are mutually "
5152 "exclusive\n"));
5153 usage(B_FALSE);
5155 flags.isprefix = B_TRUE;
5156 break;
5157 case 'e':
5158 if (flags.isprefix) {
5159 (void) fprintf(stderr, gettext("invalid option "
5160 "combination: -d and -e are mutually "
5161 "exclusive\n"));
5162 usage(B_FALSE);
5164 flags.istail = B_TRUE;
5165 break;
5166 case 'h':
5167 flags.skipholds = B_TRUE;
5168 break;
5169 case 'M':
5170 flags.forceunmount = B_TRUE;
5171 break;
5172 case 'n':
5173 flags.dryrun = B_TRUE;
5174 break;
5175 case 'u':
5176 flags.nomount = B_TRUE;
5177 break;
5178 case 'v':
5179 flags.verbose = B_TRUE;
5180 break;
5181 case 's':
5182 flags.resumable = B_TRUE;
5183 break;
5184 case 'F':
5185 flags.force = B_TRUE;
5186 break;
5187 case 'A':
5188 abort_resumable = B_TRUE;
5189 break;
5190 case 'c':
5191 flags.heal = B_TRUE;
5192 break;
5193 case ':':
5194 (void) fprintf(stderr, gettext("missing argument for "
5195 "'%c' option\n"), optopt);
5196 usage(B_FALSE);
5197 break;
5198 case '?':
5199 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5200 optopt);
5201 usage(B_FALSE);
5205 argc -= optind;
5206 argv += optind;
5208 /* zfs recv -e (use "tail" name) implies -d (remove dataset "head") */
5209 if (flags.istail)
5210 flags.isprefix = B_TRUE;
5212 /* check number of arguments */
5213 if (argc < 1) {
5214 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
5215 usage(B_FALSE);
5217 if (argc > 1) {
5218 (void) fprintf(stderr, gettext("too many arguments\n"));
5219 usage(B_FALSE);
5222 if (abort_resumable) {
5223 if (flags.isprefix || flags.istail || flags.dryrun ||
5224 flags.resumable || flags.nomount) {
5225 (void) fprintf(stderr, gettext("invalid option\n"));
5226 usage(B_FALSE);
5229 char namebuf[ZFS_MAX_DATASET_NAME_LEN];
5230 (void) snprintf(namebuf, sizeof (namebuf),
5231 "%s/%%recv", argv[0]);
5233 if (zfs_dataset_exists(g_zfs, namebuf,
5234 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) {
5235 zfs_handle_t *zhp = zfs_open(g_zfs,
5236 namebuf, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5237 if (zhp == NULL) {
5238 nvlist_free(props);
5239 return (1);
5241 err = zfs_destroy(zhp, B_FALSE);
5242 zfs_close(zhp);
5243 } else {
5244 zfs_handle_t *zhp = zfs_open(g_zfs,
5245 argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5246 if (zhp == NULL)
5247 usage(B_FALSE);
5248 if (!zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) ||
5249 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
5250 NULL, 0, NULL, NULL, 0, B_TRUE) == -1) {
5251 (void) fprintf(stderr,
5252 gettext("'%s' does not have any "
5253 "resumable receive state to abort\n"),
5254 argv[0]);
5255 nvlist_free(props);
5256 zfs_close(zhp);
5257 return (1);
5259 err = zfs_destroy(zhp, B_FALSE);
5260 zfs_close(zhp);
5262 nvlist_free(props);
5263 return (err != 0);
5266 if (isatty(STDIN_FILENO)) {
5267 (void) fprintf(stderr,
5268 gettext("Error: Backup stream can not be read "
5269 "from a terminal.\n"
5270 "You must redirect standard input.\n"));
5271 nvlist_free(props);
5272 return (1);
5274 err = zfs_receive(g_zfs, argv[0], props, &flags, STDIN_FILENO, NULL);
5275 nvlist_free(props);
5277 return (err != 0);
5281 * allow/unallow stuff
5283 /* copied from zfs/sys/dsl_deleg.h */
5284 #define ZFS_DELEG_PERM_CREATE "create"
5285 #define ZFS_DELEG_PERM_DESTROY "destroy"
5286 #define ZFS_DELEG_PERM_SNAPSHOT "snapshot"
5287 #define ZFS_DELEG_PERM_ROLLBACK "rollback"
5288 #define ZFS_DELEG_PERM_CLONE "clone"
5289 #define ZFS_DELEG_PERM_PROMOTE "promote"
5290 #define ZFS_DELEG_PERM_RENAME "rename"
5291 #define ZFS_DELEG_PERM_MOUNT "mount"
5292 #define ZFS_DELEG_PERM_SHARE "share"
5293 #define ZFS_DELEG_PERM_SEND "send"
5294 #define ZFS_DELEG_PERM_RECEIVE "receive"
5295 #define ZFS_DELEG_PERM_ALLOW "allow"
5296 #define ZFS_DELEG_PERM_USERPROP "userprop"
5297 #define ZFS_DELEG_PERM_VSCAN "vscan" /* ??? */
5298 #define ZFS_DELEG_PERM_USERQUOTA "userquota"
5299 #define ZFS_DELEG_PERM_GROUPQUOTA "groupquota"
5300 #define ZFS_DELEG_PERM_USERUSED "userused"
5301 #define ZFS_DELEG_PERM_GROUPUSED "groupused"
5302 #define ZFS_DELEG_PERM_USEROBJQUOTA "userobjquota"
5303 #define ZFS_DELEG_PERM_GROUPOBJQUOTA "groupobjquota"
5304 #define ZFS_DELEG_PERM_USEROBJUSED "userobjused"
5305 #define ZFS_DELEG_PERM_GROUPOBJUSED "groupobjused"
5307 #define ZFS_DELEG_PERM_HOLD "hold"
5308 #define ZFS_DELEG_PERM_RELEASE "release"
5309 #define ZFS_DELEG_PERM_DIFF "diff"
5310 #define ZFS_DELEG_PERM_BOOKMARK "bookmark"
5311 #define ZFS_DELEG_PERM_LOAD_KEY "load-key"
5312 #define ZFS_DELEG_PERM_CHANGE_KEY "change-key"
5314 #define ZFS_DELEG_PERM_PROJECTUSED "projectused"
5315 #define ZFS_DELEG_PERM_PROJECTQUOTA "projectquota"
5316 #define ZFS_DELEG_PERM_PROJECTOBJUSED "projectobjused"
5317 #define ZFS_DELEG_PERM_PROJECTOBJQUOTA "projectobjquota"
5319 #define ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
5321 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
5322 { ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
5323 { ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
5324 { ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
5325 { ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
5326 { ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
5327 { ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
5328 { ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
5329 { ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
5330 { ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
5331 { ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
5332 { ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
5333 { ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
5334 { ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
5335 { ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
5336 { ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
5337 { ZFS_DELEG_PERM_BOOKMARK, ZFS_DELEG_NOTE_BOOKMARK },
5338 { ZFS_DELEG_PERM_LOAD_KEY, ZFS_DELEG_NOTE_LOAD_KEY },
5339 { ZFS_DELEG_PERM_CHANGE_KEY, ZFS_DELEG_NOTE_CHANGE_KEY },
5341 { ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
5342 { ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
5343 { ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
5344 { ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
5345 { ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
5346 { ZFS_DELEG_PERM_USEROBJQUOTA, ZFS_DELEG_NOTE_USEROBJQUOTA },
5347 { ZFS_DELEG_PERM_USEROBJUSED, ZFS_DELEG_NOTE_USEROBJUSED },
5348 { ZFS_DELEG_PERM_GROUPOBJQUOTA, ZFS_DELEG_NOTE_GROUPOBJQUOTA },
5349 { ZFS_DELEG_PERM_GROUPOBJUSED, ZFS_DELEG_NOTE_GROUPOBJUSED },
5350 { ZFS_DELEG_PERM_PROJECTUSED, ZFS_DELEG_NOTE_PROJECTUSED },
5351 { ZFS_DELEG_PERM_PROJECTQUOTA, ZFS_DELEG_NOTE_PROJECTQUOTA },
5352 { ZFS_DELEG_PERM_PROJECTOBJUSED, ZFS_DELEG_NOTE_PROJECTOBJUSED },
5353 { ZFS_DELEG_PERM_PROJECTOBJQUOTA, ZFS_DELEG_NOTE_PROJECTOBJQUOTA },
5354 { NULL, ZFS_DELEG_NOTE_NONE }
5357 /* permission structure */
5358 typedef struct deleg_perm {
5359 zfs_deleg_who_type_t dp_who_type;
5360 const char *dp_name;
5361 boolean_t dp_local;
5362 boolean_t dp_descend;
5363 } deleg_perm_t;
5365 /* */
5366 typedef struct deleg_perm_node {
5367 deleg_perm_t dpn_perm;
5369 uu_avl_node_t dpn_avl_node;
5370 } deleg_perm_node_t;
5372 typedef struct fs_perm fs_perm_t;
5374 /* permissions set */
5375 typedef struct who_perm {
5376 zfs_deleg_who_type_t who_type;
5377 const char *who_name; /* id */
5378 char who_ug_name[256]; /* user/group name */
5379 fs_perm_t *who_fsperm; /* uplink */
5381 uu_avl_t *who_deleg_perm_avl; /* permissions */
5382 } who_perm_t;
5384 /* */
5385 typedef struct who_perm_node {
5386 who_perm_t who_perm;
5387 uu_avl_node_t who_avl_node;
5388 } who_perm_node_t;
5390 typedef struct fs_perm_set fs_perm_set_t;
5391 /* fs permissions */
5392 struct fs_perm {
5393 const char *fsp_name;
5395 uu_avl_t *fsp_sc_avl; /* sets,create */
5396 uu_avl_t *fsp_uge_avl; /* user,group,everyone */
5398 fs_perm_set_t *fsp_set; /* uplink */
5401 /* */
5402 typedef struct fs_perm_node {
5403 fs_perm_t fspn_fsperm;
5404 uu_avl_t *fspn_avl;
5406 uu_list_node_t fspn_list_node;
5407 } fs_perm_node_t;
5409 /* top level structure */
5410 struct fs_perm_set {
5411 uu_list_pool_t *fsps_list_pool;
5412 uu_list_t *fsps_list; /* list of fs_perms */
5414 uu_avl_pool_t *fsps_named_set_avl_pool;
5415 uu_avl_pool_t *fsps_who_perm_avl_pool;
5416 uu_avl_pool_t *fsps_deleg_perm_avl_pool;
5419 static inline const char *
5420 deleg_perm_type(zfs_deleg_note_t note)
5422 /* subcommands */
5423 switch (note) {
5424 /* SUBCOMMANDS */
5425 /* OTHER */
5426 case ZFS_DELEG_NOTE_GROUPQUOTA:
5427 case ZFS_DELEG_NOTE_GROUPUSED:
5428 case ZFS_DELEG_NOTE_USERPROP:
5429 case ZFS_DELEG_NOTE_USERQUOTA:
5430 case ZFS_DELEG_NOTE_USERUSED:
5431 case ZFS_DELEG_NOTE_USEROBJQUOTA:
5432 case ZFS_DELEG_NOTE_USEROBJUSED:
5433 case ZFS_DELEG_NOTE_GROUPOBJQUOTA:
5434 case ZFS_DELEG_NOTE_GROUPOBJUSED:
5435 case ZFS_DELEG_NOTE_PROJECTUSED:
5436 case ZFS_DELEG_NOTE_PROJECTQUOTA:
5437 case ZFS_DELEG_NOTE_PROJECTOBJUSED:
5438 case ZFS_DELEG_NOTE_PROJECTOBJQUOTA:
5439 /* other */
5440 return (gettext("other"));
5441 default:
5442 return (gettext("subcommand"));
5446 static int
5447 who_type2weight(zfs_deleg_who_type_t who_type)
5449 int res;
5450 switch (who_type) {
5451 case ZFS_DELEG_NAMED_SET_SETS:
5452 case ZFS_DELEG_NAMED_SET:
5453 res = 0;
5454 break;
5455 case ZFS_DELEG_CREATE_SETS:
5456 case ZFS_DELEG_CREATE:
5457 res = 1;
5458 break;
5459 case ZFS_DELEG_USER_SETS:
5460 case ZFS_DELEG_USER:
5461 res = 2;
5462 break;
5463 case ZFS_DELEG_GROUP_SETS:
5464 case ZFS_DELEG_GROUP:
5465 res = 3;
5466 break;
5467 case ZFS_DELEG_EVERYONE_SETS:
5468 case ZFS_DELEG_EVERYONE:
5469 res = 4;
5470 break;
5471 default:
5472 res = -1;
5475 return (res);
5478 static int
5479 who_perm_compare(const void *larg, const void *rarg, void *unused)
5481 (void) unused;
5482 const who_perm_node_t *l = larg;
5483 const who_perm_node_t *r = rarg;
5484 zfs_deleg_who_type_t ltype = l->who_perm.who_type;
5485 zfs_deleg_who_type_t rtype = r->who_perm.who_type;
5486 int lweight = who_type2weight(ltype);
5487 int rweight = who_type2weight(rtype);
5488 int res = lweight - rweight;
5489 if (res == 0)
5490 res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
5491 ZFS_MAX_DELEG_NAME-1);
5493 if (res == 0)
5494 return (0);
5495 if (res > 0)
5496 return (1);
5497 else
5498 return (-1);
5501 static int
5502 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
5504 (void) unused;
5505 const deleg_perm_node_t *l = larg;
5506 const deleg_perm_node_t *r = rarg;
5507 int res = strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
5508 ZFS_MAX_DELEG_NAME-1);
5510 if (res == 0)
5511 return (0);
5513 if (res > 0)
5514 return (1);
5515 else
5516 return (-1);
5519 static inline void
5520 fs_perm_set_init(fs_perm_set_t *fspset)
5522 memset(fspset, 0, sizeof (fs_perm_set_t));
5524 if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
5525 sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
5526 NULL, UU_DEFAULT)) == NULL)
5527 nomem();
5528 if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
5529 UU_DEFAULT)) == NULL)
5530 nomem();
5532 if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
5533 "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
5534 who_perm_node_t, who_avl_node), who_perm_compare,
5535 UU_DEFAULT)) == NULL)
5536 nomem();
5538 if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
5539 "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
5540 who_perm_node_t, who_avl_node), who_perm_compare,
5541 UU_DEFAULT)) == NULL)
5542 nomem();
5544 if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
5545 "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
5546 deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
5547 == NULL)
5548 nomem();
5551 static inline void fs_perm_fini(fs_perm_t *);
5552 static inline void who_perm_fini(who_perm_t *);
5554 static inline void
5555 fs_perm_set_fini(fs_perm_set_t *fspset)
5557 fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
5559 while (node != NULL) {
5560 fs_perm_node_t *next_node =
5561 uu_list_next(fspset->fsps_list, node);
5562 fs_perm_t *fsperm = &node->fspn_fsperm;
5563 fs_perm_fini(fsperm);
5564 uu_list_remove(fspset->fsps_list, node);
5565 free(node);
5566 node = next_node;
5569 uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
5570 uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
5571 uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
5574 static inline void
5575 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
5576 const char *name)
5578 deleg_perm->dp_who_type = type;
5579 deleg_perm->dp_name = name;
5582 static inline void
5583 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
5584 zfs_deleg_who_type_t type, const char *name)
5586 uu_avl_pool_t *pool;
5587 pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
5589 memset(who_perm, 0, sizeof (who_perm_t));
5591 if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
5592 UU_DEFAULT)) == NULL)
5593 nomem();
5595 who_perm->who_type = type;
5596 who_perm->who_name = name;
5597 who_perm->who_fsperm = fsperm;
5600 static inline void
5601 who_perm_fini(who_perm_t *who_perm)
5603 deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
5605 while (node != NULL) {
5606 deleg_perm_node_t *next_node =
5607 uu_avl_next(who_perm->who_deleg_perm_avl, node);
5609 uu_avl_remove(who_perm->who_deleg_perm_avl, node);
5610 free(node);
5611 node = next_node;
5614 uu_avl_destroy(who_perm->who_deleg_perm_avl);
5617 static inline void
5618 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
5620 uu_avl_pool_t *nset_pool = fspset->fsps_named_set_avl_pool;
5621 uu_avl_pool_t *who_pool = fspset->fsps_who_perm_avl_pool;
5623 memset(fsperm, 0, sizeof (fs_perm_t));
5625 if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
5626 == NULL)
5627 nomem();
5629 if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
5630 == NULL)
5631 nomem();
5633 fsperm->fsp_set = fspset;
5634 fsperm->fsp_name = fsname;
5637 static inline void
5638 fs_perm_fini(fs_perm_t *fsperm)
5640 who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
5641 while (node != NULL) {
5642 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
5643 node);
5644 who_perm_t *who_perm = &node->who_perm;
5645 who_perm_fini(who_perm);
5646 uu_avl_remove(fsperm->fsp_sc_avl, node);
5647 free(node);
5648 node = next_node;
5651 node = uu_avl_first(fsperm->fsp_uge_avl);
5652 while (node != NULL) {
5653 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
5654 node);
5655 who_perm_t *who_perm = &node->who_perm;
5656 who_perm_fini(who_perm);
5657 uu_avl_remove(fsperm->fsp_uge_avl, node);
5658 free(node);
5659 node = next_node;
5662 uu_avl_destroy(fsperm->fsp_sc_avl);
5663 uu_avl_destroy(fsperm->fsp_uge_avl);
5666 static void
5667 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
5668 zfs_deleg_who_type_t who_type, const char *name, char locality)
5670 uu_avl_index_t idx = 0;
5672 deleg_perm_node_t *found_node = NULL;
5673 deleg_perm_t *deleg_perm = &node->dpn_perm;
5675 deleg_perm_init(deleg_perm, who_type, name);
5677 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
5678 == NULL)
5679 uu_avl_insert(avl, node, idx);
5680 else {
5681 node = found_node;
5682 deleg_perm = &node->dpn_perm;
5686 switch (locality) {
5687 case ZFS_DELEG_LOCAL:
5688 deleg_perm->dp_local = B_TRUE;
5689 break;
5690 case ZFS_DELEG_DESCENDENT:
5691 deleg_perm->dp_descend = B_TRUE;
5692 break;
5693 case ZFS_DELEG_NA:
5694 break;
5695 default:
5696 assert(B_FALSE); /* invalid locality */
5700 static inline int
5701 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
5703 nvpair_t *nvp = NULL;
5704 fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
5705 uu_avl_t *avl = who_perm->who_deleg_perm_avl;
5706 zfs_deleg_who_type_t who_type = who_perm->who_type;
5708 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5709 const char *name = nvpair_name(nvp);
5710 data_type_t type = nvpair_type(nvp);
5711 uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
5712 deleg_perm_node_t *node =
5713 safe_malloc(sizeof (deleg_perm_node_t));
5715 VERIFY(type == DATA_TYPE_BOOLEAN);
5717 uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
5718 set_deleg_perm_node(avl, node, who_type, name, locality);
5721 return (0);
5724 static inline int
5725 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
5727 nvpair_t *nvp = NULL;
5728 fs_perm_set_t *fspset = fsperm->fsp_set;
5730 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5731 nvlist_t *nvl2 = NULL;
5732 const char *name = nvpair_name(nvp);
5733 uu_avl_t *avl = NULL;
5734 uu_avl_pool_t *avl_pool = NULL;
5735 zfs_deleg_who_type_t perm_type = name[0];
5736 char perm_locality = name[1];
5737 const char *perm_name = name + 3;
5738 who_perm_t *who_perm = NULL;
5740 assert('$' == name[2]);
5742 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
5743 return (-1);
5745 switch (perm_type) {
5746 case ZFS_DELEG_CREATE:
5747 case ZFS_DELEG_CREATE_SETS:
5748 case ZFS_DELEG_NAMED_SET:
5749 case ZFS_DELEG_NAMED_SET_SETS:
5750 avl_pool = fspset->fsps_named_set_avl_pool;
5751 avl = fsperm->fsp_sc_avl;
5752 break;
5753 case ZFS_DELEG_USER:
5754 case ZFS_DELEG_USER_SETS:
5755 case ZFS_DELEG_GROUP:
5756 case ZFS_DELEG_GROUP_SETS:
5757 case ZFS_DELEG_EVERYONE:
5758 case ZFS_DELEG_EVERYONE_SETS:
5759 avl_pool = fspset->fsps_who_perm_avl_pool;
5760 avl = fsperm->fsp_uge_avl;
5761 break;
5763 default:
5764 assert(!"unhandled zfs_deleg_who_type_t");
5767 who_perm_node_t *found_node = NULL;
5768 who_perm_node_t *node = safe_malloc(
5769 sizeof (who_perm_node_t));
5770 who_perm = &node->who_perm;
5771 uu_avl_index_t idx = 0;
5773 uu_avl_node_init(node, &node->who_avl_node, avl_pool);
5774 who_perm_init(who_perm, fsperm, perm_type, perm_name);
5776 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
5777 == NULL) {
5778 if (avl == fsperm->fsp_uge_avl) {
5779 uid_t rid = 0;
5780 struct passwd *p = NULL;
5781 struct group *g = NULL;
5782 const char *nice_name = NULL;
5784 switch (perm_type) {
5785 case ZFS_DELEG_USER_SETS:
5786 case ZFS_DELEG_USER:
5787 rid = atoi(perm_name);
5788 p = getpwuid(rid);
5789 if (p)
5790 nice_name = p->pw_name;
5791 break;
5792 case ZFS_DELEG_GROUP_SETS:
5793 case ZFS_DELEG_GROUP:
5794 rid = atoi(perm_name);
5795 g = getgrgid(rid);
5796 if (g)
5797 nice_name = g->gr_name;
5798 break;
5800 default:
5801 break;
5804 if (nice_name != NULL) {
5805 (void) strlcpy(
5806 node->who_perm.who_ug_name,
5807 nice_name, 256);
5808 } else {
5809 /* User or group unknown */
5810 (void) snprintf(
5811 node->who_perm.who_ug_name,
5812 sizeof (node->who_perm.who_ug_name),
5813 "(unknown: %d)", rid);
5817 uu_avl_insert(avl, node, idx);
5818 } else {
5819 node = found_node;
5820 who_perm = &node->who_perm;
5823 assert(who_perm != NULL);
5824 (void) parse_who_perm(who_perm, nvl2, perm_locality);
5827 return (0);
5830 static inline int
5831 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
5833 nvpair_t *nvp = NULL;
5834 uu_avl_index_t idx = 0;
5836 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5837 nvlist_t *nvl2 = NULL;
5838 const char *fsname = nvpair_name(nvp);
5839 data_type_t type = nvpair_type(nvp);
5840 fs_perm_t *fsperm = NULL;
5841 fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
5843 fsperm = &node->fspn_fsperm;
5845 VERIFY(DATA_TYPE_NVLIST == type);
5847 uu_list_node_init(node, &node->fspn_list_node,
5848 fspset->fsps_list_pool);
5850 idx = uu_list_numnodes(fspset->fsps_list);
5851 fs_perm_init(fsperm, fspset, fsname);
5853 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
5854 return (-1);
5856 (void) parse_fs_perm(fsperm, nvl2);
5858 uu_list_insert(fspset->fsps_list, node, idx);
5861 return (0);
5864 static inline const char *
5865 deleg_perm_comment(zfs_deleg_note_t note)
5867 const char *str = "";
5869 /* subcommands */
5870 switch (note) {
5871 /* SUBCOMMANDS */
5872 case ZFS_DELEG_NOTE_ALLOW:
5873 str = gettext("Must also have the permission that is being"
5874 "\n\t\t\t\tallowed");
5875 break;
5876 case ZFS_DELEG_NOTE_CLONE:
5877 str = gettext("Must also have the 'create' ability and 'mount'"
5878 "\n\t\t\t\tability in the origin file system");
5879 break;
5880 case ZFS_DELEG_NOTE_CREATE:
5881 str = gettext("Must also have the 'mount' ability");
5882 break;
5883 case ZFS_DELEG_NOTE_DESTROY:
5884 str = gettext("Must also have the 'mount' ability");
5885 break;
5886 case ZFS_DELEG_NOTE_DIFF:
5887 str = gettext("Allows lookup of paths within a dataset;"
5888 "\n\t\t\t\tgiven an object number. Ordinary users need this"
5889 "\n\t\t\t\tin order to use zfs diff");
5890 break;
5891 case ZFS_DELEG_NOTE_HOLD:
5892 str = gettext("Allows adding a user hold to a snapshot");
5893 break;
5894 case ZFS_DELEG_NOTE_MOUNT:
5895 str = gettext("Allows mount/umount of ZFS datasets");
5896 break;
5897 case ZFS_DELEG_NOTE_PROMOTE:
5898 str = gettext("Must also have the 'mount'\n\t\t\t\tand"
5899 " 'promote' ability in the origin file system");
5900 break;
5901 case ZFS_DELEG_NOTE_RECEIVE:
5902 str = gettext("Must also have the 'mount' and 'create'"
5903 " ability");
5904 break;
5905 case ZFS_DELEG_NOTE_RELEASE:
5906 str = gettext("Allows releasing a user hold which\n\t\t\t\t"
5907 "might destroy the snapshot");
5908 break;
5909 case ZFS_DELEG_NOTE_RENAME:
5910 str = gettext("Must also have the 'mount' and 'create'"
5911 "\n\t\t\t\tability in the new parent");
5912 break;
5913 case ZFS_DELEG_NOTE_ROLLBACK:
5914 str = gettext("");
5915 break;
5916 case ZFS_DELEG_NOTE_SEND:
5917 str = gettext("");
5918 break;
5919 case ZFS_DELEG_NOTE_SHARE:
5920 str = gettext("Allows sharing file systems over NFS or SMB"
5921 "\n\t\t\t\tprotocols");
5922 break;
5923 case ZFS_DELEG_NOTE_SNAPSHOT:
5924 str = gettext("");
5925 break;
5926 case ZFS_DELEG_NOTE_LOAD_KEY:
5927 str = gettext("Allows loading or unloading an encryption key");
5928 break;
5929 case ZFS_DELEG_NOTE_CHANGE_KEY:
5930 str = gettext("Allows changing or adding an encryption key");
5931 break;
5933 * case ZFS_DELEG_NOTE_VSCAN:
5934 * str = gettext("");
5935 * break;
5937 /* OTHER */
5938 case ZFS_DELEG_NOTE_GROUPQUOTA:
5939 str = gettext("Allows accessing any groupquota@... property");
5940 break;
5941 case ZFS_DELEG_NOTE_GROUPUSED:
5942 str = gettext("Allows reading any groupused@... property");
5943 break;
5944 case ZFS_DELEG_NOTE_USERPROP:
5945 str = gettext("Allows changing any user property");
5946 break;
5947 case ZFS_DELEG_NOTE_USERQUOTA:
5948 str = gettext("Allows accessing any userquota@... property");
5949 break;
5950 case ZFS_DELEG_NOTE_USERUSED:
5951 str = gettext("Allows reading any userused@... property");
5952 break;
5953 case ZFS_DELEG_NOTE_USEROBJQUOTA:
5954 str = gettext("Allows accessing any userobjquota@... property");
5955 break;
5956 case ZFS_DELEG_NOTE_GROUPOBJQUOTA:
5957 str = gettext("Allows accessing any \n\t\t\t\t"
5958 "groupobjquota@... property");
5959 break;
5960 case ZFS_DELEG_NOTE_GROUPOBJUSED:
5961 str = gettext("Allows reading any groupobjused@... property");
5962 break;
5963 case ZFS_DELEG_NOTE_USEROBJUSED:
5964 str = gettext("Allows reading any userobjused@... property");
5965 break;
5966 case ZFS_DELEG_NOTE_PROJECTQUOTA:
5967 str = gettext("Allows accessing any projectquota@... property");
5968 break;
5969 case ZFS_DELEG_NOTE_PROJECTOBJQUOTA:
5970 str = gettext("Allows accessing any \n\t\t\t\t"
5971 "projectobjquota@... property");
5972 break;
5973 case ZFS_DELEG_NOTE_PROJECTUSED:
5974 str = gettext("Allows reading any projectused@... property");
5975 break;
5976 case ZFS_DELEG_NOTE_PROJECTOBJUSED:
5977 str = gettext("Allows accessing any \n\t\t\t\t"
5978 "projectobjused@... property");
5979 break;
5980 /* other */
5981 default:
5982 str = "";
5985 return (str);
5988 struct allow_opts {
5989 boolean_t local;
5990 boolean_t descend;
5991 boolean_t user;
5992 boolean_t group;
5993 boolean_t everyone;
5994 boolean_t create;
5995 boolean_t set;
5996 boolean_t recursive; /* unallow only */
5997 boolean_t prt_usage;
5999 boolean_t prt_perms;
6000 char *who;
6001 char *perms;
6002 const char *dataset;
6005 static inline int
6006 prop_cmp(const void *a, const void *b)
6008 const char *str1 = *(const char **)a;
6009 const char *str2 = *(const char **)b;
6010 return (strcmp(str1, str2));
6013 static void
6014 allow_usage(boolean_t un, boolean_t requested, const char *msg)
6016 const char *opt_desc[] = {
6017 "-h", gettext("show this help message and exit"),
6018 "-l", gettext("set permission locally"),
6019 "-d", gettext("set permission for descents"),
6020 "-u", gettext("set permission for user"),
6021 "-g", gettext("set permission for group"),
6022 "-e", gettext("set permission for everyone"),
6023 "-c", gettext("set create time permission"),
6024 "-s", gettext("define permission set"),
6025 /* unallow only */
6026 "-r", gettext("remove permissions recursively"),
6028 size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
6029 size_t allow_size = unallow_size - 2;
6030 const char *props[ZFS_NUM_PROPS];
6031 int i;
6032 size_t count = 0;
6033 FILE *fp = requested ? stdout : stderr;
6034 zprop_desc_t *pdtbl = zfs_prop_get_table();
6035 const char *fmt = gettext("%-16s %-14s\t%s\n");
6037 (void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
6038 HELP_ALLOW));
6039 (void) fprintf(fp, gettext("Options:\n"));
6040 for (i = 0; i < (un ? unallow_size : allow_size); i += 2) {
6041 const char *opt = opt_desc[i];
6042 const char *optdsc = opt_desc[i + 1];
6043 (void) fprintf(fp, gettext(" %-10s %s\n"), opt, optdsc);
6046 (void) fprintf(fp, gettext("\nThe following permissions are "
6047 "supported:\n\n"));
6048 (void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
6049 gettext("NOTES"));
6050 for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
6051 const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
6052 zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
6053 const char *perm_type = deleg_perm_type(perm_note);
6054 const char *perm_comment = deleg_perm_comment(perm_note);
6055 (void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
6058 for (i = 0; i < ZFS_NUM_PROPS; i++) {
6059 zprop_desc_t *pd = &pdtbl[i];
6060 if (pd->pd_visible != B_TRUE)
6061 continue;
6063 if (pd->pd_attr == PROP_READONLY)
6064 continue;
6066 props[count++] = pd->pd_name;
6068 props[count] = NULL;
6070 qsort(props, count, sizeof (char *), prop_cmp);
6072 for (i = 0; i < count; i++)
6073 (void) fprintf(fp, fmt, props[i], gettext("property"), "");
6075 if (msg != NULL)
6076 (void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
6078 exit(requested ? 0 : 2);
6081 static inline const char *
6082 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
6083 char **permsp)
6085 if (un && argc == expected_argc - 1)
6086 *permsp = NULL;
6087 else if (argc == expected_argc)
6088 *permsp = argv[argc - 2];
6089 else
6090 allow_usage(un, B_FALSE,
6091 gettext("wrong number of parameters\n"));
6093 return (argv[argc - 1]);
6096 static void
6097 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
6099 int uge_sum = opts->user + opts->group + opts->everyone;
6100 int csuge_sum = opts->create + opts->set + uge_sum;
6101 int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
6102 int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
6104 if (uge_sum > 1)
6105 allow_usage(un, B_FALSE,
6106 gettext("-u, -g, and -e are mutually exclusive\n"));
6108 if (opts->prt_usage) {
6109 if (argc == 0 && all_sum == 0)
6110 allow_usage(un, B_TRUE, NULL);
6111 else
6112 usage(B_FALSE);
6115 if (opts->set) {
6116 if (csuge_sum > 1)
6117 allow_usage(un, B_FALSE,
6118 gettext("invalid options combined with -s\n"));
6120 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
6121 if (argv[0][0] != '@')
6122 allow_usage(un, B_FALSE,
6123 gettext("invalid set name: missing '@' prefix\n"));
6124 opts->who = argv[0];
6125 } else if (opts->create) {
6126 if (ldcsuge_sum > 1)
6127 allow_usage(un, B_FALSE,
6128 gettext("invalid options combined with -c\n"));
6129 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
6130 } else if (opts->everyone) {
6131 if (csuge_sum > 1)
6132 allow_usage(un, B_FALSE,
6133 gettext("invalid options combined with -e\n"));
6134 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
6135 } else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
6136 == 0) {
6137 opts->everyone = B_TRUE;
6138 argc--;
6139 argv++;
6140 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
6141 } else if (argc == 1 && !un) {
6142 opts->prt_perms = B_TRUE;
6143 opts->dataset = argv[argc-1];
6144 } else {
6145 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
6146 opts->who = argv[0];
6149 if (!opts->local && !opts->descend) {
6150 opts->local = B_TRUE;
6151 opts->descend = B_TRUE;
6155 static void
6156 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
6157 const char *who, char *perms, nvlist_t *top_nvl)
6159 int i;
6160 char ld[2] = { '\0', '\0' };
6161 char who_buf[MAXNAMELEN + 32];
6162 char base_type = '\0';
6163 char set_type = '\0';
6164 nvlist_t *base_nvl = NULL;
6165 nvlist_t *set_nvl = NULL;
6166 nvlist_t *nvl;
6168 if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
6169 nomem();
6170 if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) != 0)
6171 nomem();
6173 switch (type) {
6174 case ZFS_DELEG_NAMED_SET_SETS:
6175 case ZFS_DELEG_NAMED_SET:
6176 set_type = ZFS_DELEG_NAMED_SET_SETS;
6177 base_type = ZFS_DELEG_NAMED_SET;
6178 ld[0] = ZFS_DELEG_NA;
6179 break;
6180 case ZFS_DELEG_CREATE_SETS:
6181 case ZFS_DELEG_CREATE:
6182 set_type = ZFS_DELEG_CREATE_SETS;
6183 base_type = ZFS_DELEG_CREATE;
6184 ld[0] = ZFS_DELEG_NA;
6185 break;
6186 case ZFS_DELEG_USER_SETS:
6187 case ZFS_DELEG_USER:
6188 set_type = ZFS_DELEG_USER_SETS;
6189 base_type = ZFS_DELEG_USER;
6190 if (local)
6191 ld[0] = ZFS_DELEG_LOCAL;
6192 if (descend)
6193 ld[1] = ZFS_DELEG_DESCENDENT;
6194 break;
6195 case ZFS_DELEG_GROUP_SETS:
6196 case ZFS_DELEG_GROUP:
6197 set_type = ZFS_DELEG_GROUP_SETS;
6198 base_type = ZFS_DELEG_GROUP;
6199 if (local)
6200 ld[0] = ZFS_DELEG_LOCAL;
6201 if (descend)
6202 ld[1] = ZFS_DELEG_DESCENDENT;
6203 break;
6204 case ZFS_DELEG_EVERYONE_SETS:
6205 case ZFS_DELEG_EVERYONE:
6206 set_type = ZFS_DELEG_EVERYONE_SETS;
6207 base_type = ZFS_DELEG_EVERYONE;
6208 if (local)
6209 ld[0] = ZFS_DELEG_LOCAL;
6210 if (descend)
6211 ld[1] = ZFS_DELEG_DESCENDENT;
6212 break;
6214 default:
6215 assert(set_type != '\0' && base_type != '\0');
6218 if (perms != NULL) {
6219 char *curr = perms;
6220 char *end = curr + strlen(perms);
6222 while (curr < end) {
6223 char *delim = strchr(curr, ',');
6224 if (delim == NULL)
6225 delim = end;
6226 else
6227 *delim = '\0';
6229 if (curr[0] == '@')
6230 nvl = set_nvl;
6231 else
6232 nvl = base_nvl;
6234 (void) nvlist_add_boolean(nvl, curr);
6235 if (delim != end)
6236 *delim = ',';
6237 curr = delim + 1;
6240 for (i = 0; i < 2; i++) {
6241 char locality = ld[i];
6242 if (locality == 0)
6243 continue;
6245 if (!nvlist_empty(base_nvl)) {
6246 if (who != NULL)
6247 (void) snprintf(who_buf,
6248 sizeof (who_buf), "%c%c$%s",
6249 base_type, locality, who);
6250 else
6251 (void) snprintf(who_buf,
6252 sizeof (who_buf), "%c%c$",
6253 base_type, locality);
6255 (void) nvlist_add_nvlist(top_nvl, who_buf,
6256 base_nvl);
6260 if (!nvlist_empty(set_nvl)) {
6261 if (who != NULL)
6262 (void) snprintf(who_buf,
6263 sizeof (who_buf), "%c%c$%s",
6264 set_type, locality, who);
6265 else
6266 (void) snprintf(who_buf,
6267 sizeof (who_buf), "%c%c$",
6268 set_type, locality);
6270 (void) nvlist_add_nvlist(top_nvl, who_buf,
6271 set_nvl);
6274 } else {
6275 for (i = 0; i < 2; i++) {
6276 char locality = ld[i];
6277 if (locality == 0)
6278 continue;
6280 if (who != NULL)
6281 (void) snprintf(who_buf, sizeof (who_buf),
6282 "%c%c$%s", base_type, locality, who);
6283 else
6284 (void) snprintf(who_buf, sizeof (who_buf),
6285 "%c%c$", base_type, locality);
6286 (void) nvlist_add_boolean(top_nvl, who_buf);
6288 if (who != NULL)
6289 (void) snprintf(who_buf, sizeof (who_buf),
6290 "%c%c$%s", set_type, locality, who);
6291 else
6292 (void) snprintf(who_buf, sizeof (who_buf),
6293 "%c%c$", set_type, locality);
6294 (void) nvlist_add_boolean(top_nvl, who_buf);
6299 static int
6300 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
6302 if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
6303 nomem();
6305 if (opts->set) {
6306 store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
6307 opts->descend, opts->who, opts->perms, *nvlp);
6308 } else if (opts->create) {
6309 store_allow_perm(ZFS_DELEG_CREATE, opts->local,
6310 opts->descend, NULL, opts->perms, *nvlp);
6311 } else if (opts->everyone) {
6312 store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
6313 opts->descend, NULL, opts->perms, *nvlp);
6314 } else {
6315 char *curr = opts->who;
6316 char *end = curr + strlen(curr);
6318 while (curr < end) {
6319 const char *who;
6320 zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
6321 char *endch;
6322 char *delim = strchr(curr, ',');
6323 char errbuf[256];
6324 char id[64];
6325 struct passwd *p = NULL;
6326 struct group *g = NULL;
6328 uid_t rid;
6329 if (delim == NULL)
6330 delim = end;
6331 else
6332 *delim = '\0';
6334 rid = (uid_t)strtol(curr, &endch, 0);
6335 if (opts->user) {
6336 who_type = ZFS_DELEG_USER;
6337 if (*endch != '\0')
6338 p = getpwnam(curr);
6339 else
6340 p = getpwuid(rid);
6342 if (p != NULL)
6343 rid = p->pw_uid;
6344 else if (*endch != '\0') {
6345 (void) snprintf(errbuf, sizeof (errbuf),
6346 gettext("invalid user %s\n"), curr);
6347 allow_usage(un, B_TRUE, errbuf);
6349 } else if (opts->group) {
6350 who_type = ZFS_DELEG_GROUP;
6351 if (*endch != '\0')
6352 g = getgrnam(curr);
6353 else
6354 g = getgrgid(rid);
6356 if (g != NULL)
6357 rid = g->gr_gid;
6358 else if (*endch != '\0') {
6359 (void) snprintf(errbuf, sizeof (errbuf),
6360 gettext("invalid group %s\n"),
6361 curr);
6362 allow_usage(un, B_TRUE, errbuf);
6364 } else {
6365 if (*endch != '\0') {
6366 p = getpwnam(curr);
6367 } else {
6368 p = getpwuid(rid);
6371 if (p == NULL) {
6372 if (*endch != '\0') {
6373 g = getgrnam(curr);
6374 } else {
6375 g = getgrgid(rid);
6379 if (p != NULL) {
6380 who_type = ZFS_DELEG_USER;
6381 rid = p->pw_uid;
6382 } else if (g != NULL) {
6383 who_type = ZFS_DELEG_GROUP;
6384 rid = g->gr_gid;
6385 } else {
6386 (void) snprintf(errbuf, sizeof (errbuf),
6387 gettext("invalid user/group %s\n"),
6388 curr);
6389 allow_usage(un, B_TRUE, errbuf);
6393 (void) sprintf(id, "%u", rid);
6394 who = id;
6396 store_allow_perm(who_type, opts->local,
6397 opts->descend, who, opts->perms, *nvlp);
6398 curr = delim + 1;
6402 return (0);
6405 static void
6406 print_set_creat_perms(uu_avl_t *who_avl)
6408 const char *sc_title[] = {
6409 gettext("Permission sets:\n"),
6410 gettext("Create time permissions:\n"),
6411 NULL
6413 who_perm_node_t *who_node = NULL;
6414 int prev_weight = -1;
6416 for (who_node = uu_avl_first(who_avl); who_node != NULL;
6417 who_node = uu_avl_next(who_avl, who_node)) {
6418 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
6419 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
6420 const char *who_name = who_node->who_perm.who_name;
6421 int weight = who_type2weight(who_type);
6422 boolean_t first = B_TRUE;
6423 deleg_perm_node_t *deleg_node;
6425 if (prev_weight != weight) {
6426 (void) printf("%s", sc_title[weight]);
6427 prev_weight = weight;
6430 if (who_name == NULL || strnlen(who_name, 1) == 0)
6431 (void) printf("\t");
6432 else
6433 (void) printf("\t%s ", who_name);
6435 for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
6436 deleg_node = uu_avl_next(avl, deleg_node)) {
6437 if (first) {
6438 (void) printf("%s",
6439 deleg_node->dpn_perm.dp_name);
6440 first = B_FALSE;
6441 } else
6442 (void) printf(",%s",
6443 deleg_node->dpn_perm.dp_name);
6446 (void) printf("\n");
6450 static void
6451 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
6452 const char *title)
6454 who_perm_node_t *who_node = NULL;
6455 boolean_t prt_title = B_TRUE;
6456 uu_avl_walk_t *walk;
6458 if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
6459 nomem();
6461 while ((who_node = uu_avl_walk_next(walk)) != NULL) {
6462 const char *who_name = who_node->who_perm.who_name;
6463 const char *nice_who_name = who_node->who_perm.who_ug_name;
6464 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
6465 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
6466 char delim = ' ';
6467 deleg_perm_node_t *deleg_node;
6468 boolean_t prt_who = B_TRUE;
6470 for (deleg_node = uu_avl_first(avl);
6471 deleg_node != NULL;
6472 deleg_node = uu_avl_next(avl, deleg_node)) {
6473 if (local != deleg_node->dpn_perm.dp_local ||
6474 descend != deleg_node->dpn_perm.dp_descend)
6475 continue;
6477 if (prt_who) {
6478 const char *who = NULL;
6479 if (prt_title) {
6480 prt_title = B_FALSE;
6481 (void) printf("%s", title);
6484 switch (who_type) {
6485 case ZFS_DELEG_USER_SETS:
6486 case ZFS_DELEG_USER:
6487 who = gettext("user");
6488 if (nice_who_name)
6489 who_name = nice_who_name;
6490 break;
6491 case ZFS_DELEG_GROUP_SETS:
6492 case ZFS_DELEG_GROUP:
6493 who = gettext("group");
6494 if (nice_who_name)
6495 who_name = nice_who_name;
6496 break;
6497 case ZFS_DELEG_EVERYONE_SETS:
6498 case ZFS_DELEG_EVERYONE:
6499 who = gettext("everyone");
6500 who_name = NULL;
6501 break;
6503 default:
6504 assert(who != NULL);
6507 prt_who = B_FALSE;
6508 if (who_name == NULL)
6509 (void) printf("\t%s", who);
6510 else
6511 (void) printf("\t%s %s", who, who_name);
6514 (void) printf("%c%s", delim,
6515 deleg_node->dpn_perm.dp_name);
6516 delim = ',';
6519 if (!prt_who)
6520 (void) printf("\n");
6523 uu_avl_walk_end(walk);
6526 static void
6527 print_fs_perms(fs_perm_set_t *fspset)
6529 fs_perm_node_t *node = NULL;
6530 char buf[MAXNAMELEN + 32];
6531 const char *dsname = buf;
6533 for (node = uu_list_first(fspset->fsps_list); node != NULL;
6534 node = uu_list_next(fspset->fsps_list, node)) {
6535 uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
6536 uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
6537 int left = 0;
6539 (void) snprintf(buf, sizeof (buf),
6540 gettext("---- Permissions on %s "),
6541 node->fspn_fsperm.fsp_name);
6542 (void) printf("%s", dsname);
6543 left = 70 - strlen(buf);
6544 while (left-- > 0)
6545 (void) printf("-");
6546 (void) printf("\n");
6548 print_set_creat_perms(sc_avl);
6549 print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
6550 gettext("Local permissions:\n"));
6551 print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
6552 gettext("Descendent permissions:\n"));
6553 print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
6554 gettext("Local+Descendent permissions:\n"));
6558 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
6560 struct deleg_perms {
6561 boolean_t un;
6562 nvlist_t *nvl;
6565 static int
6566 set_deleg_perms(zfs_handle_t *zhp, void *data)
6568 struct deleg_perms *perms = (struct deleg_perms *)data;
6569 zfs_type_t zfs_type = zfs_get_type(zhp);
6571 if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
6572 return (0);
6574 return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
6577 static int
6578 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
6580 zfs_handle_t *zhp;
6581 nvlist_t *perm_nvl = NULL;
6582 nvlist_t *update_perm_nvl = NULL;
6583 int error = 1;
6584 int c;
6585 struct allow_opts opts = { 0 };
6587 const char *optstr = un ? "ldugecsrh" : "ldugecsh";
6589 /* check opts */
6590 while ((c = getopt(argc, argv, optstr)) != -1) {
6591 switch (c) {
6592 case 'l':
6593 opts.local = B_TRUE;
6594 break;
6595 case 'd':
6596 opts.descend = B_TRUE;
6597 break;
6598 case 'u':
6599 opts.user = B_TRUE;
6600 break;
6601 case 'g':
6602 opts.group = B_TRUE;
6603 break;
6604 case 'e':
6605 opts.everyone = B_TRUE;
6606 break;
6607 case 's':
6608 opts.set = B_TRUE;
6609 break;
6610 case 'c':
6611 opts.create = B_TRUE;
6612 break;
6613 case 'r':
6614 opts.recursive = B_TRUE;
6615 break;
6616 case ':':
6617 (void) fprintf(stderr, gettext("missing argument for "
6618 "'%c' option\n"), optopt);
6619 usage(B_FALSE);
6620 break;
6621 case 'h':
6622 opts.prt_usage = B_TRUE;
6623 break;
6624 case '?':
6625 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6626 optopt);
6627 usage(B_FALSE);
6631 argc -= optind;
6632 argv += optind;
6634 /* check arguments */
6635 parse_allow_args(argc, argv, un, &opts);
6637 /* try to open the dataset */
6638 if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
6639 ZFS_TYPE_VOLUME)) == NULL) {
6640 (void) fprintf(stderr, "Failed to open dataset: %s\n",
6641 opts.dataset);
6642 return (-1);
6645 if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
6646 goto cleanup2;
6648 fs_perm_set_init(&fs_perm_set);
6649 if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
6650 (void) fprintf(stderr, "Failed to parse fsacl permissions\n");
6651 goto cleanup1;
6654 if (opts.prt_perms)
6655 print_fs_perms(&fs_perm_set);
6656 else {
6657 (void) construct_fsacl_list(un, &opts, &update_perm_nvl);
6658 if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
6659 goto cleanup0;
6661 if (un && opts.recursive) {
6662 struct deleg_perms data = { un, update_perm_nvl };
6663 if (zfs_iter_filesystems_v2(zhp, 0, set_deleg_perms,
6664 &data) != 0)
6665 goto cleanup0;
6669 error = 0;
6671 cleanup0:
6672 nvlist_free(perm_nvl);
6673 nvlist_free(update_perm_nvl);
6674 cleanup1:
6675 fs_perm_set_fini(&fs_perm_set);
6676 cleanup2:
6677 zfs_close(zhp);
6679 return (error);
6682 static int
6683 zfs_do_allow(int argc, char **argv)
6685 return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
6688 static int
6689 zfs_do_unallow(int argc, char **argv)
6691 return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
6694 static int
6695 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
6697 int errors = 0;
6698 int i;
6699 const char *tag;
6700 boolean_t recursive = B_FALSE;
6701 const char *opts = holding ? "rt" : "r";
6702 int c;
6704 /* check options */
6705 while ((c = getopt(argc, argv, opts)) != -1) {
6706 switch (c) {
6707 case 'r':
6708 recursive = B_TRUE;
6709 break;
6710 case '?':
6711 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6712 optopt);
6713 usage(B_FALSE);
6717 argc -= optind;
6718 argv += optind;
6720 /* check number of arguments */
6721 if (argc < 2)
6722 usage(B_FALSE);
6724 tag = argv[0];
6725 --argc;
6726 ++argv;
6728 if (holding && tag[0] == '.') {
6729 /* tags starting with '.' are reserved for libzfs */
6730 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
6731 usage(B_FALSE);
6734 for (i = 0; i < argc; ++i) {
6735 zfs_handle_t *zhp;
6736 char parent[ZFS_MAX_DATASET_NAME_LEN];
6737 const char *delim;
6738 char *path = argv[i];
6740 delim = strchr(path, '@');
6741 if (delim == NULL) {
6742 (void) fprintf(stderr,
6743 gettext("'%s' is not a snapshot\n"), path);
6744 ++errors;
6745 continue;
6747 (void) strlcpy(parent, path, MIN(sizeof (parent),
6748 delim - path + 1));
6750 zhp = zfs_open(g_zfs, parent,
6751 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
6752 if (zhp == NULL) {
6753 ++errors;
6754 continue;
6756 if (holding) {
6757 if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
6758 ++errors;
6759 } else {
6760 if (zfs_release(zhp, delim+1, tag, recursive) != 0)
6761 ++errors;
6763 zfs_close(zhp);
6766 return (errors != 0);
6770 * zfs hold [-r] [-t] <tag> <snap> ...
6772 * -r Recursively hold
6774 * Apply a user-hold with the given tag to the list of snapshots.
6776 static int
6777 zfs_do_hold(int argc, char **argv)
6779 return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
6783 * zfs release [-r] <tag> <snap> ...
6785 * -r Recursively release
6787 * Release a user-hold with the given tag from the list of snapshots.
6789 static int
6790 zfs_do_release(int argc, char **argv)
6792 return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
6795 typedef struct holds_cbdata {
6796 boolean_t cb_recursive;
6797 const char *cb_snapname;
6798 nvlist_t **cb_nvlp;
6799 size_t cb_max_namelen;
6800 size_t cb_max_taglen;
6801 } holds_cbdata_t;
6803 #define STRFTIME_FMT_STR "%a %b %e %H:%M %Y"
6804 #define DATETIME_BUF_LEN (32)
6808 static void
6809 print_holds(boolean_t scripted, int nwidth, int tagwidth, nvlist_t *nvl,
6810 boolean_t parsable)
6812 int i;
6813 nvpair_t *nvp = NULL;
6814 const char *const hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
6815 const char *col;
6817 if (!scripted) {
6818 for (i = 0; i < 3; i++) {
6819 col = gettext(hdr_cols[i]);
6820 if (i < 2)
6821 (void) printf("%-*s ", i ? tagwidth : nwidth,
6822 col);
6823 else
6824 (void) printf("%s\n", col);
6828 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
6829 const char *zname = nvpair_name(nvp);
6830 nvlist_t *nvl2;
6831 nvpair_t *nvp2 = NULL;
6832 (void) nvpair_value_nvlist(nvp, &nvl2);
6833 while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
6834 char tsbuf[DATETIME_BUF_LEN];
6835 const char *tagname = nvpair_name(nvp2);
6836 uint64_t val = 0;
6837 time_t time;
6838 struct tm t;
6840 (void) nvpair_value_uint64(nvp2, &val);
6841 time = (time_t)val;
6842 (void) localtime_r(&time, &t);
6843 (void) strftime(tsbuf, DATETIME_BUF_LEN,
6844 gettext(STRFTIME_FMT_STR), &t);
6846 if (scripted) {
6847 if (parsable) {
6848 (void) printf("%s\t%s\t%ld\n", zname,
6849 tagname, time);
6850 } else {
6851 (void) printf("%s\t%s\t%s\n", zname,
6852 tagname, tsbuf);
6854 } else {
6855 if (parsable) {
6856 (void) printf("%-*s %-*s %ld\n",
6857 nwidth, zname, tagwidth,
6858 tagname, time);
6859 } else {
6860 (void) printf("%-*s %-*s %s\n",
6861 nwidth, zname, tagwidth,
6862 tagname, tsbuf);
6870 * Generic callback function to list a dataset or snapshot.
6872 static int
6873 holds_callback(zfs_handle_t *zhp, void *data)
6875 holds_cbdata_t *cbp = data;
6876 nvlist_t *top_nvl = *cbp->cb_nvlp;
6877 nvlist_t *nvl = NULL;
6878 nvpair_t *nvp = NULL;
6879 const char *zname = zfs_get_name(zhp);
6880 size_t znamelen = strlen(zname);
6882 if (cbp->cb_recursive) {
6883 const char *snapname;
6884 char *delim = strchr(zname, '@');
6885 if (delim == NULL)
6886 return (0);
6888 snapname = delim + 1;
6889 if (strcmp(cbp->cb_snapname, snapname))
6890 return (0);
6893 if (zfs_get_holds(zhp, &nvl) != 0)
6894 return (-1);
6896 if (znamelen > cbp->cb_max_namelen)
6897 cbp->cb_max_namelen = znamelen;
6899 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
6900 const char *tag = nvpair_name(nvp);
6901 size_t taglen = strlen(tag);
6902 if (taglen > cbp->cb_max_taglen)
6903 cbp->cb_max_taglen = taglen;
6906 return (nvlist_add_nvlist(top_nvl, zname, nvl));
6910 * zfs holds [-rHp] <snap> ...
6912 * -r Lists holds that are set on the named snapshots recursively.
6913 * -H Scripted mode; elide headers and separate columns by tabs.
6914 * -p Display values in parsable (literal) format.
6916 static int
6917 zfs_do_holds(int argc, char **argv)
6919 int c;
6920 boolean_t errors = B_FALSE;
6921 boolean_t scripted = B_FALSE;
6922 boolean_t recursive = B_FALSE;
6923 boolean_t parsable = B_FALSE;
6925 int types = ZFS_TYPE_SNAPSHOT;
6926 holds_cbdata_t cb = { 0 };
6928 int limit = 0;
6929 int ret = 0;
6930 int flags = 0;
6932 /* check options */
6933 while ((c = getopt(argc, argv, "rHp")) != -1) {
6934 switch (c) {
6935 case 'r':
6936 recursive = B_TRUE;
6937 break;
6938 case 'H':
6939 scripted = B_TRUE;
6940 break;
6941 case 'p':
6942 parsable = B_TRUE;
6943 break;
6944 case '?':
6945 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6946 optopt);
6947 usage(B_FALSE);
6951 if (recursive) {
6952 types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
6953 flags |= ZFS_ITER_RECURSE;
6956 argc -= optind;
6957 argv += optind;
6959 /* check number of arguments */
6960 if (argc < 1)
6961 usage(B_FALSE);
6963 nvlist_t *nvl = fnvlist_alloc();
6965 for (int i = 0; i < argc; ++i) {
6966 char *snapshot = argv[i];
6967 const char *delim;
6968 const char *snapname;
6970 delim = strchr(snapshot, '@');
6971 if (delim == NULL) {
6972 (void) fprintf(stderr,
6973 gettext("'%s' is not a snapshot\n"), snapshot);
6974 errors = B_TRUE;
6975 continue;
6977 snapname = delim + 1;
6978 if (recursive)
6979 snapshot[delim - snapshot] = '\0';
6981 cb.cb_recursive = recursive;
6982 cb.cb_snapname = snapname;
6983 cb.cb_nvlp = &nvl;
6986 * 1. collect holds data, set format options
6988 ret = zfs_for_each(1, argv + i, flags, types, NULL, NULL, limit,
6989 holds_callback, &cb);
6990 if (ret != 0)
6991 errors = B_TRUE;
6995 * 2. print holds data
6997 print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl,
6998 parsable);
7000 if (nvlist_empty(nvl))
7001 (void) fprintf(stderr, gettext("no datasets available\n"));
7003 nvlist_free(nvl);
7005 return (errors);
7008 #define CHECK_SPINNER 30
7009 #define SPINNER_TIME 3 /* seconds */
7010 #define MOUNT_TIME 1 /* seconds */
7012 typedef struct get_all_state {
7013 char **ga_datasets;
7014 int ga_count;
7015 boolean_t ga_verbose;
7016 get_all_cb_t *ga_cbp;
7017 } get_all_state_t;
7019 static int
7020 get_one_dataset(zfs_handle_t *zhp, void *data)
7022 static const char *const spin[] = { "-", "\\", "|", "/" };
7023 static int spinval = 0;
7024 static int spincheck = 0;
7025 static time_t last_spin_time = (time_t)0;
7026 get_all_state_t *state = data;
7027 zfs_type_t type = zfs_get_type(zhp);
7029 if (state->ga_verbose) {
7030 if (--spincheck < 0) {
7031 time_t now = time(NULL);
7032 if (last_spin_time + SPINNER_TIME < now) {
7033 update_progress(spin[spinval++ % 4]);
7034 last_spin_time = now;
7036 spincheck = CHECK_SPINNER;
7041 * Iterate over any nested datasets.
7043 if (zfs_iter_filesystems_v2(zhp, 0, get_one_dataset, data) != 0) {
7044 zfs_close(zhp);
7045 return (1);
7049 * Skip any datasets whose type does not match.
7051 if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
7052 zfs_close(zhp);
7053 return (0);
7055 libzfs_add_handle(state->ga_cbp, zhp);
7056 assert(state->ga_cbp->cb_used <= state->ga_cbp->cb_alloc);
7058 return (0);
7061 static int
7062 get_recursive_datasets(zfs_handle_t *zhp, void *data)
7064 get_all_state_t *state = data;
7065 int len = strlen(zfs_get_name(zhp));
7066 for (int i = 0; i < state->ga_count; ++i) {
7067 if (strcmp(state->ga_datasets[i], zfs_get_name(zhp)) == 0)
7068 return (get_one_dataset(zhp, data));
7069 else if ((strncmp(state->ga_datasets[i], zfs_get_name(zhp),
7070 len) == 0) && state->ga_datasets[i][len] == '/') {
7071 (void) zfs_iter_filesystems_v2(zhp, 0,
7072 get_recursive_datasets, data);
7075 zfs_close(zhp);
7076 return (0);
7079 static void
7080 get_all_datasets(get_all_state_t *state)
7082 if (state->ga_verbose)
7083 set_progress_header(gettext("Reading ZFS config"));
7084 if (state->ga_datasets == NULL)
7085 (void) zfs_iter_root(g_zfs, get_one_dataset, state);
7086 else
7087 (void) zfs_iter_root(g_zfs, get_recursive_datasets, state);
7089 if (state->ga_verbose)
7090 finish_progress(gettext("done."));
7094 * Generic callback for sharing or mounting filesystems. Because the code is so
7095 * similar, we have a common function with an extra parameter to determine which
7096 * mode we are using.
7098 typedef enum { OP_SHARE, OP_MOUNT } share_mount_op_t;
7100 typedef struct share_mount_state {
7101 share_mount_op_t sm_op;
7102 boolean_t sm_verbose;
7103 int sm_flags;
7104 char *sm_options;
7105 enum sa_protocol sm_proto; /* only valid for OP_SHARE */
7106 pthread_mutex_t sm_lock; /* protects the remaining fields */
7107 uint_t sm_total; /* number of filesystems to process */
7108 uint_t sm_done; /* number of filesystems processed */
7109 int sm_status; /* -1 if any of the share/mount operations failed */
7110 } share_mount_state_t;
7113 * Share or mount a dataset.
7115 static int
7116 share_mount_one(zfs_handle_t *zhp, int op, int flags, enum sa_protocol protocol,
7117 boolean_t explicit, const char *options)
7119 char mountpoint[ZFS_MAXPROPLEN];
7120 char shareopts[ZFS_MAXPROPLEN];
7121 char smbshareopts[ZFS_MAXPROPLEN];
7122 const char *cmdname = op == OP_SHARE ? "share" : "mount";
7123 struct mnttab mnt;
7124 uint64_t zoned, canmount;
7125 boolean_t shared_nfs, shared_smb;
7127 assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
7130 * Check to make sure we can mount/share this dataset. If we
7131 * are in the global zone and the filesystem is exported to a
7132 * local zone, or if we are in a local zone and the
7133 * filesystem is not exported, then it is an error.
7135 zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
7137 if (zoned && getzoneid() == GLOBAL_ZONEID) {
7138 if (!explicit)
7139 return (0);
7141 (void) fprintf(stderr, gettext("cannot %s '%s': "
7142 "dataset is exported to a local zone\n"), cmdname,
7143 zfs_get_name(zhp));
7144 return (1);
7146 } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
7147 if (!explicit)
7148 return (0);
7150 (void) fprintf(stderr, gettext("cannot %s '%s': "
7151 "permission denied\n"), cmdname,
7152 zfs_get_name(zhp));
7153 return (1);
7157 * Ignore any filesystems which don't apply to us. This
7158 * includes those with a legacy mountpoint, or those with
7159 * legacy share options.
7161 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
7162 sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
7163 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
7164 sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
7165 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
7166 sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
7168 if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
7169 strcmp(smbshareopts, "off") == 0) {
7170 if (!explicit)
7171 return (0);
7173 (void) fprintf(stderr, gettext("cannot share '%s': "
7174 "legacy share\n"), zfs_get_name(zhp));
7175 (void) fprintf(stderr, gettext("use exports(5) or "
7176 "smb.conf(5) to share this filesystem, or set "
7177 "the sharenfs or sharesmb property\n"));
7178 return (1);
7182 * We cannot share or mount legacy filesystems. If the
7183 * shareopts is non-legacy but the mountpoint is legacy, we
7184 * treat it as a legacy share.
7186 if (strcmp(mountpoint, "legacy") == 0) {
7187 if (!explicit)
7188 return (0);
7190 (void) fprintf(stderr, gettext("cannot %s '%s': "
7191 "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
7192 (void) fprintf(stderr, gettext("use %s(8) to "
7193 "%s this filesystem\n"), cmdname, cmdname);
7194 return (1);
7197 if (strcmp(mountpoint, "none") == 0) {
7198 if (!explicit)
7199 return (0);
7201 (void) fprintf(stderr, gettext("cannot %s '%s': no "
7202 "mountpoint set\n"), cmdname, zfs_get_name(zhp));
7203 return (1);
7207 * canmount explicit outcome
7208 * on no pass through
7209 * on yes pass through
7210 * off no return 0
7211 * off yes display error, return 1
7212 * noauto no return 0
7213 * noauto yes pass through
7215 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
7216 if (canmount == ZFS_CANMOUNT_OFF) {
7217 if (!explicit)
7218 return (0);
7220 (void) fprintf(stderr, gettext("cannot %s '%s': "
7221 "'canmount' property is set to 'off'\n"), cmdname,
7222 zfs_get_name(zhp));
7223 return (1);
7224 } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
7226 * When performing a 'zfs mount -a', we skip any mounts for
7227 * datasets that have 'noauto' set. Sharing a dataset with
7228 * 'noauto' set is only allowed if it's mounted.
7230 if (op == OP_MOUNT)
7231 return (0);
7232 if (op == OP_SHARE && !zfs_is_mounted(zhp, NULL)) {
7233 /* also purge it from existing exports */
7234 zfs_unshare(zhp, mountpoint, NULL);
7235 return (0);
7240 * If this filesystem is encrypted and does not have
7241 * a loaded key, we can not mount it.
7243 if ((flags & MS_CRYPT) == 0 &&
7244 zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) != ZIO_CRYPT_OFF &&
7245 zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS) ==
7246 ZFS_KEYSTATUS_UNAVAILABLE) {
7247 if (!explicit)
7248 return (0);
7250 (void) fprintf(stderr, gettext("cannot %s '%s': "
7251 "encryption key not loaded\n"), cmdname, zfs_get_name(zhp));
7252 return (1);
7256 * If this filesystem is inconsistent and has a receive resume
7257 * token, we can not mount it.
7259 if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) &&
7260 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
7261 NULL, 0, NULL, NULL, 0, B_TRUE) == 0) {
7262 if (!explicit)
7263 return (0);
7265 (void) fprintf(stderr, gettext("cannot %s '%s': "
7266 "Contains partially-completed state from "
7267 "\"zfs receive -s\", which can be resumed with "
7268 "\"zfs send -t\"\n"),
7269 cmdname, zfs_get_name(zhp));
7270 return (1);
7273 if (zfs_prop_get_int(zhp, ZFS_PROP_REDACTED) && !(flags & MS_FORCE)) {
7274 if (!explicit)
7275 return (0);
7277 (void) fprintf(stderr, gettext("cannot %s '%s': "
7278 "Dataset is not complete, was created by receiving "
7279 "a redacted zfs send stream.\n"), cmdname,
7280 zfs_get_name(zhp));
7281 return (1);
7285 * At this point, we have verified that the mountpoint and/or
7286 * shareopts are appropriate for auto management. If the
7287 * filesystem is already mounted or shared, return (failing
7288 * for explicit requests); otherwise mount or share the
7289 * filesystem.
7291 switch (op) {
7292 case OP_SHARE: {
7293 enum sa_protocol prot[] = {SA_PROTOCOL_NFS, SA_NO_PROTOCOL};
7294 shared_nfs = zfs_is_shared(zhp, NULL, prot);
7295 *prot = SA_PROTOCOL_SMB;
7296 shared_smb = zfs_is_shared(zhp, NULL, prot);
7298 if ((shared_nfs && shared_smb) ||
7299 (shared_nfs && strcmp(shareopts, "on") == 0 &&
7300 strcmp(smbshareopts, "off") == 0) ||
7301 (shared_smb && strcmp(smbshareopts, "on") == 0 &&
7302 strcmp(shareopts, "off") == 0)) {
7303 if (!explicit)
7304 return (0);
7306 (void) fprintf(stderr, gettext("cannot share "
7307 "'%s': filesystem already shared\n"),
7308 zfs_get_name(zhp));
7309 return (1);
7312 if (!zfs_is_mounted(zhp, NULL) &&
7313 zfs_mount(zhp, NULL, flags) != 0)
7314 return (1);
7316 *prot = protocol;
7317 if (zfs_share(zhp, protocol == SA_NO_PROTOCOL ? NULL : prot))
7318 return (1);
7321 break;
7323 case OP_MOUNT:
7324 mnt.mnt_mntopts = (char *)(options ?: "");
7326 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
7327 zfs_is_mounted(zhp, NULL)) {
7328 if (!explicit)
7329 return (0);
7331 (void) fprintf(stderr, gettext("cannot mount "
7332 "'%s': filesystem already mounted\n"),
7333 zfs_get_name(zhp));
7334 return (1);
7337 if (zfs_mount(zhp, options, flags) != 0)
7338 return (1);
7339 break;
7342 return (0);
7346 * Reports progress in the form "(current/total)". Not thread-safe.
7348 static void
7349 report_mount_progress(int current, int total)
7351 static time_t last_progress_time = 0;
7352 time_t now = time(NULL);
7353 char info[32];
7355 /* display header if we're here for the first time */
7356 if (current == 1) {
7357 set_progress_header(gettext("Mounting ZFS filesystems"));
7358 } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
7359 /* too soon to report again */
7360 return;
7363 last_progress_time = now;
7365 (void) sprintf(info, "(%d/%d)", current, total);
7367 if (current == total)
7368 finish_progress(info);
7369 else
7370 update_progress(info);
7374 * zfs_foreach_mountpoint() callback that mounts or shares one filesystem and
7375 * updates the progress meter.
7377 static int
7378 share_mount_one_cb(zfs_handle_t *zhp, void *arg)
7380 share_mount_state_t *sms = arg;
7381 int ret;
7383 ret = share_mount_one(zhp, sms->sm_op, sms->sm_flags, sms->sm_proto,
7384 B_FALSE, sms->sm_options);
7386 pthread_mutex_lock(&sms->sm_lock);
7387 if (ret != 0)
7388 sms->sm_status = ret;
7389 sms->sm_done++;
7390 if (sms->sm_verbose)
7391 report_mount_progress(sms->sm_done, sms->sm_total);
7392 pthread_mutex_unlock(&sms->sm_lock);
7393 return (ret);
7396 static void
7397 append_options(char *mntopts, char *newopts)
7399 int len = strlen(mntopts);
7401 /* original length plus new string to append plus 1 for the comma */
7402 if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
7403 (void) fprintf(stderr, gettext("the opts argument for "
7404 "'%s' option is too long (more than %d chars)\n"),
7405 "-o", MNT_LINE_MAX);
7406 usage(B_FALSE);
7409 if (*mntopts)
7410 mntopts[len++] = ',';
7412 (void) strcpy(&mntopts[len], newopts);
7415 static enum sa_protocol
7416 sa_protocol_decode(const char *protocol)
7418 for (enum sa_protocol i = 0; i < ARRAY_SIZE(sa_protocol_names); ++i)
7419 if (strcmp(protocol, sa_protocol_names[i]) == 0)
7420 return (i);
7422 (void) fputs(gettext("share type must be one of: "), stderr);
7423 for (enum sa_protocol i = 0;
7424 i < ARRAY_SIZE(sa_protocol_names); ++i)
7425 (void) fprintf(stderr, "%s%s",
7426 i != 0 ? ", " : "", sa_protocol_names[i]);
7427 (void) fputc('\n', stderr);
7428 usage(B_FALSE);
7431 static int
7432 share_mount(int op, int argc, char **argv)
7434 int do_all = 0;
7435 int recursive = 0;
7436 boolean_t verbose = B_FALSE;
7437 boolean_t json = B_FALSE;
7438 int c, ret = 0;
7439 char *options = NULL;
7440 int flags = 0;
7441 nvlist_t *jsobj, *data, *item;
7442 const uint_t mount_nthr = 512;
7443 uint_t nthr;
7444 jsobj = data = item = NULL;
7446 struct option long_options[] = {
7447 {"json", no_argument, NULL, 'j'},
7448 {0, 0, 0, 0}
7451 /* check options */
7452 while ((c = getopt_long(argc, argv,
7453 op == OP_MOUNT ? ":ajRlvo:Of" : "al",
7454 op == OP_MOUNT ? long_options : NULL, NULL)) != -1) {
7455 switch (c) {
7456 case 'a':
7457 do_all = 1;
7458 break;
7459 case 'R':
7460 recursive = 1;
7461 break;
7462 case 'v':
7463 verbose = B_TRUE;
7464 break;
7465 case 'l':
7466 flags |= MS_CRYPT;
7467 break;
7468 case 'j':
7469 json = B_TRUE;
7470 jsobj = zfs_json_schema(0, 1);
7471 data = fnvlist_alloc();
7472 break;
7473 case 'o':
7474 if (*optarg == '\0') {
7475 (void) fprintf(stderr, gettext("empty mount "
7476 "options (-o) specified\n"));
7477 usage(B_FALSE);
7480 if (options == NULL)
7481 options = safe_malloc(MNT_LINE_MAX + 1);
7483 /* option validation is done later */
7484 append_options(options, optarg);
7485 break;
7486 case 'O':
7487 flags |= MS_OVERLAY;
7488 break;
7489 case 'f':
7490 flags |= MS_FORCE;
7491 break;
7492 case ':':
7493 (void) fprintf(stderr, gettext("missing argument for "
7494 "'%c' option\n"), optopt);
7495 usage(B_FALSE);
7496 break;
7497 case '?':
7498 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7499 optopt);
7500 usage(B_FALSE);
7504 argc -= optind;
7505 argv += optind;
7507 if (json && argc != 0) {
7508 (void) fprintf(stderr, gettext("too many arguments\n"));
7509 usage(B_FALSE);
7512 /* check number of arguments */
7513 if (do_all || recursive) {
7514 enum sa_protocol protocol = SA_NO_PROTOCOL;
7516 if (op == OP_SHARE && argc > 0) {
7517 protocol = sa_protocol_decode(argv[0]);
7518 argc--;
7519 argv++;
7522 if (argc != 0 && do_all) {
7523 (void) fprintf(stderr, gettext("too many arguments\n"));
7524 usage(B_FALSE);
7527 if (argc == 0 && recursive) {
7528 (void) fprintf(stderr,
7529 gettext("no dataset provided\n"));
7530 usage(B_FALSE);
7533 start_progress_timer();
7534 get_all_cb_t cb = { 0 };
7535 get_all_state_t state = { 0 };
7536 if (argc == 0) {
7537 state.ga_datasets = NULL;
7538 state.ga_count = -1;
7539 } else {
7540 zfs_handle_t *zhp;
7541 for (int i = 0; i < argc; i++) {
7542 zhp = zfs_open(g_zfs, argv[i],
7543 ZFS_TYPE_FILESYSTEM);
7544 if (zhp == NULL)
7545 usage(B_FALSE);
7546 zfs_close(zhp);
7548 state.ga_datasets = argv;
7549 state.ga_count = argc;
7551 state.ga_verbose = verbose;
7552 state.ga_cbp = &cb;
7553 get_all_datasets(&state);
7555 if (cb.cb_used == 0) {
7556 free(options);
7557 return (0);
7560 share_mount_state_t share_mount_state = { 0 };
7561 share_mount_state.sm_op = op;
7562 share_mount_state.sm_verbose = verbose;
7563 share_mount_state.sm_flags = flags;
7564 share_mount_state.sm_options = options;
7565 share_mount_state.sm_proto = protocol;
7566 share_mount_state.sm_total = cb.cb_used;
7567 pthread_mutex_init(&share_mount_state.sm_lock, NULL);
7569 /* For a 'zfs share -a' operation start with a clean slate. */
7570 if (op == OP_SHARE)
7571 zfs_truncate_shares(NULL);
7574 * libshare isn't mt-safe, so only do the operation in parallel
7575 * if we're mounting. Additionally, the key-loading option must
7576 * be serialized so that we can prompt the user for their keys
7577 * in a consistent manner.
7579 nthr = op == OP_MOUNT && !(flags & MS_CRYPT) ? mount_nthr : 1;
7580 zfs_foreach_mountpoint(g_zfs, cb.cb_handles, cb.cb_used,
7581 share_mount_one_cb, &share_mount_state, nthr);
7582 zfs_commit_shares(NULL);
7584 ret = share_mount_state.sm_status;
7586 for (int i = 0; i < cb.cb_used; i++)
7587 zfs_close(cb.cb_handles[i]);
7588 free(cb.cb_handles);
7589 } else if (argc == 0) {
7590 FILE *mnttab;
7591 struct mnttab entry;
7593 if ((op == OP_SHARE) || (options != NULL)) {
7594 (void) fprintf(stderr, gettext("missing filesystem "
7595 "argument (specify -a for all)\n"));
7596 usage(B_FALSE);
7600 * When mount is given no arguments, go through
7601 * /proc/self/mounts and display any active ZFS mounts.
7602 * We hide any snapshots, since they are controlled
7603 * automatically.
7606 if ((mnttab = fopen(MNTTAB, "re")) == NULL) {
7607 free(options);
7608 return (ENOENT);
7611 while (getmntent(mnttab, &entry) == 0) {
7612 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
7613 strchr(entry.mnt_special, '@') != NULL)
7614 continue;
7615 if (json) {
7616 item = fnvlist_alloc();
7617 fnvlist_add_string(item, "filesystem",
7618 entry.mnt_special);
7619 fnvlist_add_string(item, "mountpoint",
7620 entry.mnt_mountp);
7621 fnvlist_add_nvlist(data, entry.mnt_special,
7622 item);
7623 fnvlist_free(item);
7624 } else {
7625 (void) printf("%-30s %s\n", entry.mnt_special,
7626 entry.mnt_mountp);
7630 (void) fclose(mnttab);
7631 if (json) {
7632 fnvlist_add_nvlist(jsobj, "datasets", data);
7633 if (nvlist_empty(data))
7634 fnvlist_free(jsobj);
7635 else
7636 zcmd_print_json(jsobj);
7637 fnvlist_free(data);
7639 } else {
7640 zfs_handle_t *zhp;
7642 if (argc > 1) {
7643 (void) fprintf(stderr,
7644 gettext("too many arguments\n"));
7645 usage(B_FALSE);
7648 if ((zhp = zfs_open(g_zfs, argv[0],
7649 ZFS_TYPE_FILESYSTEM)) == NULL) {
7650 ret = 1;
7651 } else {
7652 ret = share_mount_one(zhp, op, flags, SA_NO_PROTOCOL,
7653 B_TRUE, options);
7654 zfs_commit_shares(NULL);
7655 zfs_close(zhp);
7659 free(options);
7660 return (ret);
7664 * zfs mount -a
7665 * zfs mount filesystem
7667 * Mount all filesystems, or mount the given filesystem.
7669 static int
7670 zfs_do_mount(int argc, char **argv)
7672 return (share_mount(OP_MOUNT, argc, argv));
7676 * zfs share -a [nfs | smb]
7677 * zfs share filesystem
7679 * Share all filesystems, or share the given filesystem.
7681 static int
7682 zfs_do_share(int argc, char **argv)
7684 return (share_mount(OP_SHARE, argc, argv));
7687 typedef struct unshare_unmount_node {
7688 zfs_handle_t *un_zhp;
7689 char *un_mountp;
7690 uu_avl_node_t un_avlnode;
7691 } unshare_unmount_node_t;
7693 static int
7694 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
7696 (void) unused;
7697 const unshare_unmount_node_t *l = larg;
7698 const unshare_unmount_node_t *r = rarg;
7700 return (strcmp(l->un_mountp, r->un_mountp));
7704 * Convenience routine used by zfs_do_umount() and manual_unmount(). Given an
7705 * absolute path, find the entry /proc/self/mounts, verify that it's a
7706 * ZFS filesystem, and unmount it appropriately.
7708 static int
7709 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
7711 zfs_handle_t *zhp;
7712 int ret = 0;
7713 struct stat64 statbuf;
7714 struct extmnttab entry;
7715 const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
7716 ino_t path_inode;
7719 * Search for the given (major,minor) pair in the mount table.
7722 if (getextmntent(path, &entry, &statbuf) != 0) {
7723 if (op == OP_SHARE) {
7724 (void) fprintf(stderr, gettext("cannot %s '%s': not "
7725 "currently mounted\n"), cmdname, path);
7726 return (1);
7728 (void) fprintf(stderr, gettext("warning: %s not in"
7729 "/proc/self/mounts\n"), path);
7730 if ((ret = umount2(path, flags)) != 0)
7731 (void) fprintf(stderr, gettext("%s: %s\n"), path,
7732 strerror(errno));
7733 return (ret != 0);
7735 path_inode = statbuf.st_ino;
7737 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
7738 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
7739 "filesystem\n"), cmdname, path);
7740 return (1);
7743 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
7744 ZFS_TYPE_FILESYSTEM)) == NULL)
7745 return (1);
7747 ret = 1;
7748 if (stat64(entry.mnt_mountp, &statbuf) != 0) {
7749 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
7750 cmdname, path, strerror(errno));
7751 goto out;
7752 } else if (statbuf.st_ino != path_inode) {
7753 (void) fprintf(stderr, gettext("cannot "
7754 "%s '%s': not a mountpoint\n"), cmdname, path);
7755 goto out;
7758 if (op == OP_SHARE) {
7759 char nfs_mnt_prop[ZFS_MAXPROPLEN];
7760 char smbshare_prop[ZFS_MAXPROPLEN];
7762 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
7763 sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
7764 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
7765 sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
7767 if (strcmp(nfs_mnt_prop, "off") == 0 &&
7768 strcmp(smbshare_prop, "off") == 0) {
7769 (void) fprintf(stderr, gettext("cannot unshare "
7770 "'%s': legacy share\n"), path);
7771 (void) fprintf(stderr, gettext("use exportfs(8) "
7772 "or smbcontrol(1) to unshare this filesystem\n"));
7773 } else if (!zfs_is_shared(zhp, NULL, NULL)) {
7774 (void) fprintf(stderr, gettext("cannot unshare '%s': "
7775 "not currently shared\n"), path);
7776 } else {
7777 ret = zfs_unshare(zhp, path, NULL);
7778 zfs_commit_shares(NULL);
7780 } else {
7781 char mtpt_prop[ZFS_MAXPROPLEN];
7783 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
7784 sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
7786 if (is_manual) {
7787 ret = zfs_unmount(zhp, NULL, flags);
7788 } else if (strcmp(mtpt_prop, "legacy") == 0) {
7789 (void) fprintf(stderr, gettext("cannot unmount "
7790 "'%s': legacy mountpoint\n"),
7791 zfs_get_name(zhp));
7792 (void) fprintf(stderr, gettext("use umount(8) "
7793 "to unmount this filesystem\n"));
7794 } else {
7795 ret = zfs_unmountall(zhp, flags);
7799 out:
7800 zfs_close(zhp);
7802 return (ret != 0);
7806 * Generic callback for unsharing or unmounting a filesystem.
7808 static int
7809 unshare_unmount(int op, int argc, char **argv)
7811 int do_all = 0;
7812 int flags = 0;
7813 int ret = 0;
7814 int c;
7815 zfs_handle_t *zhp;
7816 char nfs_mnt_prop[ZFS_MAXPROPLEN];
7817 char sharesmb[ZFS_MAXPROPLEN];
7819 /* check options */
7820 while ((c = getopt(argc, argv, op == OP_SHARE ? ":a" : "afu")) != -1) {
7821 switch (c) {
7822 case 'a':
7823 do_all = 1;
7824 break;
7825 case 'f':
7826 flags |= MS_FORCE;
7827 break;
7828 case 'u':
7829 flags |= MS_CRYPT;
7830 break;
7831 case ':':
7832 (void) fprintf(stderr, gettext("missing argument for "
7833 "'%c' option\n"), optopt);
7834 usage(B_FALSE);
7835 break;
7836 case '?':
7837 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7838 optopt);
7839 usage(B_FALSE);
7843 argc -= optind;
7844 argv += optind;
7846 if (do_all) {
7848 * We could make use of zfs_for_each() to walk all datasets in
7849 * the system, but this would be very inefficient, especially
7850 * since we would have to linearly search /proc/self/mounts for
7851 * each one. Instead, do one pass through /proc/self/mounts
7852 * looking for zfs entries and call zfs_unmount() for each one.
7854 * Things get a little tricky if the administrator has created
7855 * mountpoints beneath other ZFS filesystems. In this case, we
7856 * have to unmount the deepest filesystems first. To accomplish
7857 * this, we place all the mountpoints in an AVL tree sorted by
7858 * the special type (dataset name), and walk the result in
7859 * reverse to make sure to get any snapshots first.
7861 FILE *mnttab;
7862 struct mnttab entry;
7863 uu_avl_pool_t *pool;
7864 uu_avl_t *tree = NULL;
7865 unshare_unmount_node_t *node;
7866 uu_avl_index_t idx;
7867 uu_avl_walk_t *walk;
7868 enum sa_protocol *protocol = NULL,
7869 single_protocol[] = {SA_NO_PROTOCOL, SA_NO_PROTOCOL};
7871 if (op == OP_SHARE && argc > 0) {
7872 *single_protocol = sa_protocol_decode(argv[0]);
7873 protocol = single_protocol;
7874 argc--;
7875 argv++;
7878 if (argc != 0) {
7879 (void) fprintf(stderr, gettext("too many arguments\n"));
7880 usage(B_FALSE);
7883 if (((pool = uu_avl_pool_create("unmount_pool",
7884 sizeof (unshare_unmount_node_t),
7885 offsetof(unshare_unmount_node_t, un_avlnode),
7886 unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
7887 ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
7888 nomem();
7890 if ((mnttab = fopen(MNTTAB, "re")) == NULL) {
7891 uu_avl_destroy(tree);
7892 uu_avl_pool_destroy(pool);
7893 return (ENOENT);
7896 while (getmntent(mnttab, &entry) == 0) {
7898 /* ignore non-ZFS entries */
7899 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
7900 continue;
7902 /* ignore snapshots */
7903 if (strchr(entry.mnt_special, '@') != NULL)
7904 continue;
7906 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
7907 ZFS_TYPE_FILESYSTEM)) == NULL) {
7908 ret = 1;
7909 continue;
7913 * Ignore datasets that are excluded/restricted by
7914 * parent pool name.
7916 if (zpool_skip_pool(zfs_get_pool_name(zhp))) {
7917 zfs_close(zhp);
7918 continue;
7921 switch (op) {
7922 case OP_SHARE:
7923 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
7924 nfs_mnt_prop,
7925 sizeof (nfs_mnt_prop),
7926 NULL, NULL, 0, B_FALSE) == 0);
7927 if (strcmp(nfs_mnt_prop, "off") != 0)
7928 break;
7929 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
7930 nfs_mnt_prop,
7931 sizeof (nfs_mnt_prop),
7932 NULL, NULL, 0, B_FALSE) == 0);
7933 if (strcmp(nfs_mnt_prop, "off") == 0)
7934 continue;
7935 break;
7936 case OP_MOUNT:
7937 /* Ignore legacy mounts */
7938 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
7939 nfs_mnt_prop,
7940 sizeof (nfs_mnt_prop),
7941 NULL, NULL, 0, B_FALSE) == 0);
7942 if (strcmp(nfs_mnt_prop, "legacy") == 0)
7943 continue;
7944 /* Ignore canmount=noauto mounts */
7945 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
7946 ZFS_CANMOUNT_NOAUTO)
7947 continue;
7948 break;
7949 default:
7950 break;
7953 node = safe_malloc(sizeof (unshare_unmount_node_t));
7954 node->un_zhp = zhp;
7955 node->un_mountp = safe_strdup(entry.mnt_mountp);
7957 uu_avl_node_init(node, &node->un_avlnode, pool);
7959 if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
7960 uu_avl_insert(tree, node, idx);
7961 } else {
7962 zfs_close(node->un_zhp);
7963 free(node->un_mountp);
7964 free(node);
7967 (void) fclose(mnttab);
7970 * Walk the AVL tree in reverse, unmounting each filesystem and
7971 * removing it from the AVL tree in the process.
7973 if ((walk = uu_avl_walk_start(tree,
7974 UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
7975 nomem();
7977 while ((node = uu_avl_walk_next(walk)) != NULL) {
7978 const char *mntarg = NULL;
7980 uu_avl_remove(tree, node);
7981 switch (op) {
7982 case OP_SHARE:
7983 if (zfs_unshare(node->un_zhp,
7984 node->un_mountp, protocol) != 0)
7985 ret = 1;
7986 break;
7988 case OP_MOUNT:
7989 if (zfs_unmount(node->un_zhp,
7990 mntarg, flags) != 0)
7991 ret = 1;
7992 break;
7995 zfs_close(node->un_zhp);
7996 free(node->un_mountp);
7997 free(node);
8000 if (op == OP_SHARE)
8001 zfs_commit_shares(protocol);
8003 uu_avl_walk_end(walk);
8004 uu_avl_destroy(tree);
8005 uu_avl_pool_destroy(pool);
8007 } else {
8008 if (argc != 1) {
8009 if (argc == 0)
8010 (void) fprintf(stderr,
8011 gettext("missing filesystem argument\n"));
8012 else
8013 (void) fprintf(stderr,
8014 gettext("too many arguments\n"));
8015 usage(B_FALSE);
8019 * We have an argument, but it may be a full path or a ZFS
8020 * filesystem. Pass full paths off to unmount_path() (shared by
8021 * manual_unmount), otherwise open the filesystem and pass to
8022 * zfs_unmount().
8024 if (argv[0][0] == '/')
8025 return (unshare_unmount_path(op, argv[0],
8026 flags, B_FALSE));
8028 if ((zhp = zfs_open(g_zfs, argv[0],
8029 ZFS_TYPE_FILESYSTEM)) == NULL)
8030 return (1);
8032 verify(zfs_prop_get(zhp, op == OP_SHARE ?
8033 ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
8034 nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
8035 NULL, 0, B_FALSE) == 0);
8037 switch (op) {
8038 case OP_SHARE:
8039 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
8040 nfs_mnt_prop,
8041 sizeof (nfs_mnt_prop),
8042 NULL, NULL, 0, B_FALSE) == 0);
8043 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
8044 sharesmb, sizeof (sharesmb), NULL, NULL,
8045 0, B_FALSE) == 0);
8047 if (strcmp(nfs_mnt_prop, "off") == 0 &&
8048 strcmp(sharesmb, "off") == 0) {
8049 (void) fprintf(stderr, gettext("cannot "
8050 "unshare '%s': legacy share\n"),
8051 zfs_get_name(zhp));
8052 (void) fprintf(stderr, gettext("use "
8053 "exports(5) or smb.conf(5) to unshare "
8054 "this filesystem\n"));
8055 ret = 1;
8056 } else if (!zfs_is_shared(zhp, NULL, NULL)) {
8057 (void) fprintf(stderr, gettext("cannot "
8058 "unshare '%s': not currently "
8059 "shared\n"), zfs_get_name(zhp));
8060 ret = 1;
8061 } else if (zfs_unshareall(zhp, NULL) != 0) {
8062 ret = 1;
8064 break;
8066 case OP_MOUNT:
8067 if (strcmp(nfs_mnt_prop, "legacy") == 0) {
8068 (void) fprintf(stderr, gettext("cannot "
8069 "unmount '%s': legacy "
8070 "mountpoint\n"), zfs_get_name(zhp));
8071 (void) fprintf(stderr, gettext("use "
8072 "umount(8) to unmount this "
8073 "filesystem\n"));
8074 ret = 1;
8075 } else if (!zfs_is_mounted(zhp, NULL)) {
8076 (void) fprintf(stderr, gettext("cannot "
8077 "unmount '%s': not currently "
8078 "mounted\n"),
8079 zfs_get_name(zhp));
8080 ret = 1;
8081 } else if (zfs_unmountall(zhp, flags) != 0) {
8082 ret = 1;
8084 break;
8087 zfs_close(zhp);
8090 return (ret);
8094 * zfs unmount [-fu] -a
8095 * zfs unmount [-fu] filesystem
8097 * Unmount all filesystems, or a specific ZFS filesystem.
8099 static int
8100 zfs_do_unmount(int argc, char **argv)
8102 return (unshare_unmount(OP_MOUNT, argc, argv));
8106 * zfs unshare -a
8107 * zfs unshare filesystem
8109 * Unshare all filesystems, or a specific ZFS filesystem.
8111 static int
8112 zfs_do_unshare(int argc, char **argv)
8114 return (unshare_unmount(OP_SHARE, argc, argv));
8117 static int
8118 find_command_idx(const char *command, int *idx)
8120 int i;
8122 for (i = 0; i < NCOMMAND; i++) {
8123 if (command_table[i].name == NULL)
8124 continue;
8126 if (strcmp(command, command_table[i].name) == 0) {
8127 *idx = i;
8128 return (0);
8131 return (1);
8134 static int
8135 zfs_do_diff(int argc, char **argv)
8137 zfs_handle_t *zhp;
8138 int flags = 0;
8139 char *tosnap = NULL;
8140 char *fromsnap = NULL;
8141 char *atp, *copy;
8142 int err = 0;
8143 int c;
8144 struct sigaction sa;
8146 while ((c = getopt(argc, argv, "FHth")) != -1) {
8147 switch (c) {
8148 case 'F':
8149 flags |= ZFS_DIFF_CLASSIFY;
8150 break;
8151 case 'H':
8152 flags |= ZFS_DIFF_PARSEABLE;
8153 break;
8154 case 't':
8155 flags |= ZFS_DIFF_TIMESTAMP;
8156 break;
8157 case 'h':
8158 flags |= ZFS_DIFF_NO_MANGLE;
8159 break;
8160 default:
8161 (void) fprintf(stderr,
8162 gettext("invalid option '%c'\n"), optopt);
8163 usage(B_FALSE);
8167 argc -= optind;
8168 argv += optind;
8170 if (argc < 1) {
8171 (void) fprintf(stderr,
8172 gettext("must provide at least one snapshot name\n"));
8173 usage(B_FALSE);
8176 if (argc > 2) {
8177 (void) fprintf(stderr, gettext("too many arguments\n"));
8178 usage(B_FALSE);
8181 fromsnap = argv[0];
8182 tosnap = (argc == 2) ? argv[1] : NULL;
8184 copy = NULL;
8185 if (*fromsnap != '@')
8186 copy = strdup(fromsnap);
8187 else if (tosnap)
8188 copy = strdup(tosnap);
8189 if (copy == NULL)
8190 usage(B_FALSE);
8192 if ((atp = strchr(copy, '@')) != NULL)
8193 *atp = '\0';
8195 if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL) {
8196 free(copy);
8197 return (1);
8199 free(copy);
8202 * Ignore SIGPIPE so that the library can give us
8203 * information on any failure
8205 if (sigemptyset(&sa.sa_mask) == -1) {
8206 err = errno;
8207 goto out;
8209 sa.sa_flags = 0;
8210 sa.sa_handler = SIG_IGN;
8211 if (sigaction(SIGPIPE, &sa, NULL) == -1) {
8212 err = errno;
8213 goto out;
8216 err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
8217 out:
8218 zfs_close(zhp);
8220 return (err != 0);
8224 * zfs bookmark <fs@source>|<fs#source> <fs#bookmark>
8226 * Creates a bookmark with the given name from the source snapshot
8227 * or creates a copy of an existing source bookmark.
8229 static int
8230 zfs_do_bookmark(int argc, char **argv)
8232 char *source, *bookname;
8233 char expbuf[ZFS_MAX_DATASET_NAME_LEN];
8234 int source_type;
8235 nvlist_t *nvl;
8236 int ret = 0;
8237 int c;
8239 /* check options */
8240 while ((c = getopt(argc, argv, "")) != -1) {
8241 switch (c) {
8242 case '?':
8243 (void) fprintf(stderr,
8244 gettext("invalid option '%c'\n"), optopt);
8245 goto usage;
8249 argc -= optind;
8250 argv += optind;
8252 /* check number of arguments */
8253 if (argc < 1) {
8254 (void) fprintf(stderr, gettext("missing source argument\n"));
8255 goto usage;
8257 if (argc < 2) {
8258 (void) fprintf(stderr, gettext("missing bookmark argument\n"));
8259 goto usage;
8262 source = argv[0];
8263 bookname = argv[1];
8265 if (strchr(source, '@') == NULL && strchr(source, '#') == NULL) {
8266 (void) fprintf(stderr,
8267 gettext("invalid source name '%s': "
8268 "must contain a '@' or '#'\n"), source);
8269 goto usage;
8271 if (strchr(bookname, '#') == NULL) {
8272 (void) fprintf(stderr,
8273 gettext("invalid bookmark name '%s': "
8274 "must contain a '#'\n"), bookname);
8275 goto usage;
8279 * expand source or bookname to full path:
8280 * one of them may be specified as short name
8283 char **expand;
8284 char *source_short, *bookname_short;
8285 source_short = strpbrk(source, "@#");
8286 bookname_short = strpbrk(bookname, "#");
8287 if (source_short == source &&
8288 bookname_short == bookname) {
8289 (void) fprintf(stderr, gettext(
8290 "either source or bookmark must be specified as "
8291 "full dataset paths"));
8292 goto usage;
8293 } else if (source_short != source &&
8294 bookname_short != bookname) {
8295 expand = NULL;
8296 } else if (source_short != source) {
8297 strlcpy(expbuf, source, sizeof (expbuf));
8298 expand = &bookname;
8299 } else if (bookname_short != bookname) {
8300 strlcpy(expbuf, bookname, sizeof (expbuf));
8301 expand = &source;
8302 } else {
8303 abort();
8305 if (expand != NULL) {
8306 *strpbrk(expbuf, "@#") = '\0'; /* dataset name in buf */
8307 (void) strlcat(expbuf, *expand, sizeof (expbuf));
8308 *expand = expbuf;
8312 /* determine source type */
8313 switch (*strpbrk(source, "@#")) {
8314 case '@': source_type = ZFS_TYPE_SNAPSHOT; break;
8315 case '#': source_type = ZFS_TYPE_BOOKMARK; break;
8316 default: abort();
8319 /* test the source exists */
8320 zfs_handle_t *zhp;
8321 zhp = zfs_open(g_zfs, source, source_type);
8322 if (zhp == NULL)
8323 goto usage;
8324 zfs_close(zhp);
8326 nvl = fnvlist_alloc();
8327 fnvlist_add_string(nvl, bookname, source);
8328 ret = lzc_bookmark(nvl, NULL);
8329 fnvlist_free(nvl);
8331 if (ret != 0) {
8332 const char *err_msg = NULL;
8333 char errbuf[1024];
8335 (void) snprintf(errbuf, sizeof (errbuf),
8336 dgettext(TEXT_DOMAIN,
8337 "cannot create bookmark '%s'"), bookname);
8339 switch (ret) {
8340 case EXDEV:
8341 err_msg = "bookmark is in a different pool";
8342 break;
8343 case ZFS_ERR_BOOKMARK_SOURCE_NOT_ANCESTOR:
8344 err_msg = "source is not an ancestor of the "
8345 "new bookmark's dataset";
8346 break;
8347 case EEXIST:
8348 err_msg = "bookmark exists";
8349 break;
8350 case EINVAL:
8351 err_msg = "invalid argument";
8352 break;
8353 case ENOTSUP:
8354 err_msg = "bookmark feature not enabled";
8355 break;
8356 case ENOSPC:
8357 err_msg = "out of space";
8358 break;
8359 case ENOENT:
8360 err_msg = "dataset does not exist";
8361 break;
8362 default:
8363 (void) zfs_standard_error(g_zfs, ret, errbuf);
8364 break;
8366 if (err_msg != NULL) {
8367 (void) fprintf(stderr, "%s: %s\n", errbuf,
8368 dgettext(TEXT_DOMAIN, err_msg));
8372 return (ret != 0);
8374 usage:
8375 usage(B_FALSE);
8376 return (-1);
8379 static int
8380 zfs_do_channel_program(int argc, char **argv)
8382 int ret, fd, c;
8383 size_t progsize, progread;
8384 nvlist_t *outnvl = NULL;
8385 uint64_t instrlimit = ZCP_DEFAULT_INSTRLIMIT;
8386 uint64_t memlimit = ZCP_DEFAULT_MEMLIMIT;
8387 boolean_t sync_flag = B_TRUE, json_output = B_FALSE;
8388 zpool_handle_t *zhp;
8390 struct option long_options[] = {
8391 {"json", no_argument, NULL, 'j'},
8392 {0, 0, 0, 0}
8395 /* check options */
8396 while ((c = getopt_long(argc, argv, "nt:m:j", long_options,
8397 NULL)) != -1) {
8398 switch (c) {
8399 case 't':
8400 case 'm': {
8401 uint64_t arg;
8402 char *endp;
8404 errno = 0;
8405 arg = strtoull(optarg, &endp, 0);
8406 if (errno != 0 || *endp != '\0') {
8407 (void) fprintf(stderr, gettext(
8408 "invalid argument "
8409 "'%s': expected integer\n"), optarg);
8410 goto usage;
8413 if (c == 't') {
8414 instrlimit = arg;
8415 } else {
8416 ASSERT3U(c, ==, 'm');
8417 memlimit = arg;
8419 break;
8421 case 'n': {
8422 sync_flag = B_FALSE;
8423 break;
8425 case 'j': {
8426 json_output = B_TRUE;
8427 break;
8429 case '?':
8430 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8431 optopt);
8432 goto usage;
8436 argc -= optind;
8437 argv += optind;
8439 if (argc < 2) {
8440 (void) fprintf(stderr,
8441 gettext("invalid number of arguments\n"));
8442 goto usage;
8445 const char *poolname = argv[0];
8446 const char *filename = argv[1];
8447 if (strcmp(filename, "-") == 0) {
8448 fd = 0;
8449 filename = "standard input";
8450 } else if ((fd = open(filename, O_RDONLY)) < 0) {
8451 (void) fprintf(stderr, gettext("cannot open '%s': %s\n"),
8452 filename, strerror(errno));
8453 return (1);
8456 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
8457 (void) fprintf(stderr, gettext("cannot open pool '%s'\n"),
8458 poolname);
8459 if (fd != 0)
8460 (void) close(fd);
8461 return (1);
8463 zpool_close(zhp);
8466 * Read in the channel program, expanding the program buffer as
8467 * necessary.
8469 progread = 0;
8470 progsize = 1024;
8471 char *progbuf = safe_malloc(progsize);
8472 do {
8473 ret = read(fd, progbuf + progread, progsize - progread);
8474 progread += ret;
8475 if (progread == progsize && ret > 0) {
8476 progsize *= 2;
8477 progbuf = safe_realloc(progbuf, progsize);
8479 } while (ret > 0);
8481 if (fd != 0)
8482 (void) close(fd);
8483 if (ret < 0) {
8484 free(progbuf);
8485 (void) fprintf(stderr,
8486 gettext("cannot read '%s': %s\n"),
8487 filename, strerror(errno));
8488 return (1);
8490 progbuf[progread] = '\0';
8493 * Any remaining arguments are passed as arguments to the lua script as
8494 * a string array:
8496 * "argv" -> [ "arg 1", ... "arg n" ],
8499 nvlist_t *argnvl = fnvlist_alloc();
8500 fnvlist_add_string_array(argnvl, ZCP_ARG_CLIARGV,
8501 (const char **)argv + 2, argc - 2);
8503 if (sync_flag) {
8504 ret = lzc_channel_program(poolname, progbuf,
8505 instrlimit, memlimit, argnvl, &outnvl);
8506 } else {
8507 ret = lzc_channel_program_nosync(poolname, progbuf,
8508 instrlimit, memlimit, argnvl, &outnvl);
8511 if (ret != 0) {
8513 * On error, report the error message handed back by lua if one
8514 * exists. Otherwise, generate an appropriate error message,
8515 * falling back on strerror() for an unexpected return code.
8517 const char *errstring = NULL;
8518 const char *msg = gettext("Channel program execution failed");
8519 uint64_t instructions = 0;
8520 if (outnvl != NULL && nvlist_exists(outnvl, ZCP_RET_ERROR)) {
8521 const char *es = NULL;
8522 (void) nvlist_lookup_string(outnvl,
8523 ZCP_RET_ERROR, &es);
8524 if (es == NULL)
8525 errstring = strerror(ret);
8526 else
8527 errstring = es;
8528 if (ret == ETIME) {
8529 (void) nvlist_lookup_uint64(outnvl,
8530 ZCP_ARG_INSTRLIMIT, &instructions);
8532 } else {
8533 switch (ret) {
8534 case EINVAL:
8535 errstring =
8536 "Invalid instruction or memory limit.";
8537 break;
8538 case ENOMEM:
8539 errstring = "Return value too large.";
8540 break;
8541 case ENOSPC:
8542 errstring = "Memory limit exhausted.";
8543 break;
8544 case ETIME:
8545 errstring = "Timed out.";
8546 break;
8547 case EPERM:
8548 errstring = "Permission denied. Channel "
8549 "programs must be run as root.";
8550 break;
8551 default:
8552 (void) zfs_standard_error(g_zfs, ret, msg);
8555 if (errstring != NULL)
8556 (void) fprintf(stderr, "%s:\n%s\n", msg, errstring);
8558 if (ret == ETIME && instructions != 0)
8559 (void) fprintf(stderr,
8560 gettext("%llu Lua instructions\n"),
8561 (u_longlong_t)instructions);
8562 } else {
8563 if (json_output) {
8564 (void) nvlist_print_json(stdout, outnvl);
8565 } else if (nvlist_empty(outnvl)) {
8566 (void) fprintf(stdout, gettext("Channel program fully "
8567 "executed and did not produce output.\n"));
8568 } else {
8569 (void) fprintf(stdout, gettext("Channel program fully "
8570 "executed and produced output:\n"));
8571 dump_nvlist(outnvl, 4);
8575 free(progbuf);
8576 fnvlist_free(outnvl);
8577 fnvlist_free(argnvl);
8578 return (ret != 0);
8580 usage:
8581 usage(B_FALSE);
8582 return (-1);
8586 typedef struct loadkey_cbdata {
8587 boolean_t cb_loadkey;
8588 boolean_t cb_recursive;
8589 boolean_t cb_noop;
8590 char *cb_keylocation;
8591 uint64_t cb_numfailed;
8592 uint64_t cb_numattempted;
8593 } loadkey_cbdata_t;
8595 static int
8596 load_key_callback(zfs_handle_t *zhp, void *data)
8598 int ret;
8599 boolean_t is_encroot;
8600 loadkey_cbdata_t *cb = data;
8601 uint64_t keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
8604 * If we are working recursively, we want to skip loading / unloading
8605 * keys for non-encryption roots and datasets whose keys are already
8606 * in the desired end-state.
8608 if (cb->cb_recursive) {
8609 ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
8610 if (ret != 0)
8611 return (ret);
8612 if (!is_encroot)
8613 return (0);
8615 if ((cb->cb_loadkey && keystatus == ZFS_KEYSTATUS_AVAILABLE) ||
8616 (!cb->cb_loadkey && keystatus == ZFS_KEYSTATUS_UNAVAILABLE))
8617 return (0);
8620 cb->cb_numattempted++;
8622 if (cb->cb_loadkey)
8623 ret = zfs_crypto_load_key(zhp, cb->cb_noop, cb->cb_keylocation);
8624 else
8625 ret = zfs_crypto_unload_key(zhp);
8627 if (ret != 0) {
8628 cb->cb_numfailed++;
8629 return (ret);
8632 return (0);
8635 static int
8636 load_unload_keys(int argc, char **argv, boolean_t loadkey)
8638 int c, ret = 0, flags = 0;
8639 boolean_t do_all = B_FALSE;
8640 loadkey_cbdata_t cb = { 0 };
8642 cb.cb_loadkey = loadkey;
8644 while ((c = getopt(argc, argv, "anrL:")) != -1) {
8645 /* noop and alternate keylocations only apply to zfs load-key */
8646 if (loadkey) {
8647 switch (c) {
8648 case 'n':
8649 cb.cb_noop = B_TRUE;
8650 continue;
8651 case 'L':
8652 cb.cb_keylocation = optarg;
8653 continue;
8654 default:
8655 break;
8659 switch (c) {
8660 case 'a':
8661 do_all = B_TRUE;
8662 cb.cb_recursive = B_TRUE;
8663 break;
8664 case 'r':
8665 flags |= ZFS_ITER_RECURSE;
8666 cb.cb_recursive = B_TRUE;
8667 break;
8668 default:
8669 (void) fprintf(stderr,
8670 gettext("invalid option '%c'\n"), optopt);
8671 usage(B_FALSE);
8675 argc -= optind;
8676 argv += optind;
8678 if (!do_all && argc == 0) {
8679 (void) fprintf(stderr,
8680 gettext("Missing dataset argument or -a option\n"));
8681 usage(B_FALSE);
8684 if (do_all && argc != 0) {
8685 (void) fprintf(stderr,
8686 gettext("Cannot specify dataset with -a option\n"));
8687 usage(B_FALSE);
8690 if (cb.cb_recursive && cb.cb_keylocation != NULL &&
8691 strcmp(cb.cb_keylocation, "prompt") != 0) {
8692 (void) fprintf(stderr, gettext("alternate keylocation may only "
8693 "be 'prompt' with -r or -a\n"));
8694 usage(B_FALSE);
8697 ret = zfs_for_each(argc, argv, flags,
8698 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME, NULL, NULL, 0,
8699 load_key_callback, &cb);
8701 if (cb.cb_noop || (cb.cb_recursive && cb.cb_numattempted != 0)) {
8702 (void) printf(gettext("%llu / %llu key(s) successfully %s\n"),
8703 (u_longlong_t)(cb.cb_numattempted - cb.cb_numfailed),
8704 (u_longlong_t)cb.cb_numattempted,
8705 loadkey ? (cb.cb_noop ? "verified" : "loaded") :
8706 "unloaded");
8709 if (cb.cb_numfailed != 0)
8710 ret = -1;
8712 return (ret);
8715 static int
8716 zfs_do_load_key(int argc, char **argv)
8718 return (load_unload_keys(argc, argv, B_TRUE));
8722 static int
8723 zfs_do_unload_key(int argc, char **argv)
8725 return (load_unload_keys(argc, argv, B_FALSE));
8728 static int
8729 zfs_do_change_key(int argc, char **argv)
8731 int c, ret;
8732 uint64_t keystatus;
8733 boolean_t loadkey = B_FALSE, inheritkey = B_FALSE;
8734 zfs_handle_t *zhp = NULL;
8735 nvlist_t *props = fnvlist_alloc();
8737 while ((c = getopt(argc, argv, "lio:")) != -1) {
8738 switch (c) {
8739 case 'l':
8740 loadkey = B_TRUE;
8741 break;
8742 case 'i':
8743 inheritkey = B_TRUE;
8744 break;
8745 case 'o':
8746 if (!parseprop(props, optarg)) {
8747 nvlist_free(props);
8748 return (1);
8750 break;
8751 default:
8752 (void) fprintf(stderr,
8753 gettext("invalid option '%c'\n"), optopt);
8754 usage(B_FALSE);
8758 if (inheritkey && !nvlist_empty(props)) {
8759 (void) fprintf(stderr,
8760 gettext("Properties not allowed for inheriting\n"));
8761 usage(B_FALSE);
8764 argc -= optind;
8765 argv += optind;
8767 if (argc < 1) {
8768 (void) fprintf(stderr, gettext("Missing dataset argument\n"));
8769 usage(B_FALSE);
8772 if (argc > 1) {
8773 (void) fprintf(stderr, gettext("Too many arguments\n"));
8774 usage(B_FALSE);
8777 zhp = zfs_open(g_zfs, argv[argc - 1],
8778 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
8779 if (zhp == NULL)
8780 usage(B_FALSE);
8782 if (loadkey) {
8783 keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
8784 if (keystatus != ZFS_KEYSTATUS_AVAILABLE) {
8785 ret = zfs_crypto_load_key(zhp, B_FALSE, NULL);
8786 if (ret != 0) {
8787 nvlist_free(props);
8788 zfs_close(zhp);
8789 return (-1);
8793 /* refresh the properties so the new keystatus is visible */
8794 zfs_refresh_properties(zhp);
8797 ret = zfs_crypto_rewrap(zhp, props, inheritkey);
8798 if (ret != 0) {
8799 nvlist_free(props);
8800 zfs_close(zhp);
8801 return (-1);
8804 nvlist_free(props);
8805 zfs_close(zhp);
8806 return (0);
8810 * 1) zfs project [-d|-r] <file|directory ...>
8811 * List project ID and inherit flag of file(s) or directories.
8812 * -d: List the directory itself, not its children.
8813 * -r: List subdirectories recursively.
8815 * 2) zfs project -C [-k] [-r] <file|directory ...>
8816 * Clear project inherit flag and/or ID on the file(s) or directories.
8817 * -k: Keep the project ID unchanged. If not specified, the project ID
8818 * will be reset as zero.
8819 * -r: Clear on subdirectories recursively.
8821 * 3) zfs project -c [-0] [-d|-r] [-p id] <file|directory ...>
8822 * Check project ID and inherit flag on the file(s) or directories,
8823 * report the outliers.
8824 * -0: Print file name followed by a NUL instead of newline.
8825 * -d: Check the directory itself, not its children.
8826 * -p: Specify the referenced ID for comparing with the target file(s)
8827 * or directories' project IDs. If not specified, the target (top)
8828 * directory's project ID will be used as the referenced one.
8829 * -r: Check subdirectories recursively.
8831 * 4) zfs project [-p id] [-r] [-s] <file|directory ...>
8832 * Set project ID and/or inherit flag on the file(s) or directories.
8833 * -p: Set the project ID as the given id.
8834 * -r: Set on subdirectories recursively. If not specify "-p" option,
8835 * it will use top-level directory's project ID as the given id,
8836 * then set both project ID and inherit flag on all descendants
8837 * of the top-level directory.
8838 * -s: Set project inherit flag.
8840 static int
8841 zfs_do_project(int argc, char **argv)
8843 zfs_project_control_t zpc = {
8844 .zpc_expected_projid = ZFS_INVALID_PROJID,
8845 .zpc_op = ZFS_PROJECT_OP_DEFAULT,
8846 .zpc_dironly = B_FALSE,
8847 .zpc_keep_projid = B_FALSE,
8848 .zpc_newline = B_TRUE,
8849 .zpc_recursive = B_FALSE,
8850 .zpc_set_flag = B_FALSE,
8852 int ret = 0, c;
8854 if (argc < 2)
8855 usage(B_FALSE);
8857 while ((c = getopt(argc, argv, "0Ccdkp:rs")) != -1) {
8858 switch (c) {
8859 case '0':
8860 zpc.zpc_newline = B_FALSE;
8861 break;
8862 case 'C':
8863 if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8864 (void) fprintf(stderr, gettext("cannot "
8865 "specify '-C' '-c' '-s' together\n"));
8866 usage(B_FALSE);
8869 zpc.zpc_op = ZFS_PROJECT_OP_CLEAR;
8870 break;
8871 case 'c':
8872 if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8873 (void) fprintf(stderr, gettext("cannot "
8874 "specify '-C' '-c' '-s' together\n"));
8875 usage(B_FALSE);
8878 zpc.zpc_op = ZFS_PROJECT_OP_CHECK;
8879 break;
8880 case 'd':
8881 zpc.zpc_dironly = B_TRUE;
8882 /* overwrite "-r" option */
8883 zpc.zpc_recursive = B_FALSE;
8884 break;
8885 case 'k':
8886 zpc.zpc_keep_projid = B_TRUE;
8887 break;
8888 case 'p': {
8889 char *endptr;
8891 errno = 0;
8892 zpc.zpc_expected_projid = strtoull(optarg, &endptr, 0);
8893 if (errno != 0 || *endptr != '\0') {
8894 (void) fprintf(stderr,
8895 gettext("project ID must be less than "
8896 "%u\n"), UINT32_MAX);
8897 usage(B_FALSE);
8899 if (zpc.zpc_expected_projid >= UINT32_MAX) {
8900 (void) fprintf(stderr,
8901 gettext("invalid project ID\n"));
8902 usage(B_FALSE);
8904 break;
8906 case 'r':
8907 zpc.zpc_recursive = B_TRUE;
8908 /* overwrite "-d" option */
8909 zpc.zpc_dironly = B_FALSE;
8910 break;
8911 case 's':
8912 if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8913 (void) fprintf(stderr, gettext("cannot "
8914 "specify '-C' '-c' '-s' together\n"));
8915 usage(B_FALSE);
8918 zpc.zpc_set_flag = B_TRUE;
8919 zpc.zpc_op = ZFS_PROJECT_OP_SET;
8920 break;
8921 default:
8922 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8923 optopt);
8924 usage(B_FALSE);
8928 if (zpc.zpc_op == ZFS_PROJECT_OP_DEFAULT) {
8929 if (zpc.zpc_expected_projid != ZFS_INVALID_PROJID)
8930 zpc.zpc_op = ZFS_PROJECT_OP_SET;
8931 else
8932 zpc.zpc_op = ZFS_PROJECT_OP_LIST;
8935 switch (zpc.zpc_op) {
8936 case ZFS_PROJECT_OP_LIST:
8937 if (zpc.zpc_keep_projid) {
8938 (void) fprintf(stderr,
8939 gettext("'-k' is only valid together with '-C'\n"));
8940 usage(B_FALSE);
8942 if (!zpc.zpc_newline) {
8943 (void) fprintf(stderr,
8944 gettext("'-0' is only valid together with '-c'\n"));
8945 usage(B_FALSE);
8947 break;
8948 case ZFS_PROJECT_OP_CHECK:
8949 if (zpc.zpc_keep_projid) {
8950 (void) fprintf(stderr,
8951 gettext("'-k' is only valid together with '-C'\n"));
8952 usage(B_FALSE);
8954 break;
8955 case ZFS_PROJECT_OP_CLEAR:
8956 if (zpc.zpc_dironly) {
8957 (void) fprintf(stderr,
8958 gettext("'-d' is useless together with '-C'\n"));
8959 usage(B_FALSE);
8961 if (!zpc.zpc_newline) {
8962 (void) fprintf(stderr,
8963 gettext("'-0' is only valid together with '-c'\n"));
8964 usage(B_FALSE);
8966 if (zpc.zpc_expected_projid != ZFS_INVALID_PROJID) {
8967 (void) fprintf(stderr,
8968 gettext("'-p' is useless together with '-C'\n"));
8969 usage(B_FALSE);
8971 break;
8972 case ZFS_PROJECT_OP_SET:
8973 if (zpc.zpc_dironly) {
8974 (void) fprintf(stderr,
8975 gettext("'-d' is useless for set project ID and/or "
8976 "inherit flag\n"));
8977 usage(B_FALSE);
8979 if (zpc.zpc_keep_projid) {
8980 (void) fprintf(stderr,
8981 gettext("'-k' is only valid together with '-C'\n"));
8982 usage(B_FALSE);
8984 if (!zpc.zpc_newline) {
8985 (void) fprintf(stderr,
8986 gettext("'-0' is only valid together with '-c'\n"));
8987 usage(B_FALSE);
8989 break;
8990 default:
8991 ASSERT(0);
8992 break;
8995 argv += optind;
8996 argc -= optind;
8997 if (argc == 0) {
8998 (void) fprintf(stderr,
8999 gettext("missing file or directory target(s)\n"));
9000 usage(B_FALSE);
9003 for (int i = 0; i < argc; i++) {
9004 int err;
9006 err = zfs_project_handle(argv[i], &zpc);
9007 if (err && !ret)
9008 ret = err;
9011 return (ret);
9014 static int
9015 zfs_do_wait(int argc, char **argv)
9017 boolean_t enabled[ZFS_WAIT_NUM_ACTIVITIES];
9018 int error = 0, i;
9019 int c;
9021 /* By default, wait for all types of activity. */
9022 for (i = 0; i < ZFS_WAIT_NUM_ACTIVITIES; i++)
9023 enabled[i] = B_TRUE;
9025 while ((c = getopt(argc, argv, "t:")) != -1) {
9026 switch (c) {
9027 case 't':
9028 /* Reset activities array */
9029 memset(&enabled, 0, sizeof (enabled));
9031 for (char *tok; (tok = strsep(&optarg, ",")); ) {
9032 static const char *const col_subopts[
9033 ZFS_WAIT_NUM_ACTIVITIES] = { "deleteq" };
9035 for (i = 0; i < ARRAY_SIZE(col_subopts); ++i)
9036 if (strcmp(tok, col_subopts[i]) == 0) {
9037 enabled[i] = B_TRUE;
9038 goto found;
9041 (void) fprintf(stderr,
9042 gettext("invalid activity '%s'\n"), tok);
9043 usage(B_FALSE);
9044 found:;
9046 break;
9047 case '?':
9048 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
9049 optopt);
9050 usage(B_FALSE);
9054 argv += optind;
9055 argc -= optind;
9056 if (argc < 1) {
9057 (void) fprintf(stderr, gettext("missing 'filesystem' "
9058 "argument\n"));
9059 usage(B_FALSE);
9061 if (argc > 1) {
9062 (void) fprintf(stderr, gettext("too many arguments\n"));
9063 usage(B_FALSE);
9066 zfs_handle_t *zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM);
9067 if (zhp == NULL)
9068 return (1);
9070 for (;;) {
9071 boolean_t missing = B_FALSE;
9072 boolean_t any_waited = B_FALSE;
9074 for (int i = 0; i < ZFS_WAIT_NUM_ACTIVITIES; i++) {
9075 boolean_t waited;
9077 if (!enabled[i])
9078 continue;
9080 error = zfs_wait_status(zhp, i, &missing, &waited);
9081 if (error != 0 || missing)
9082 break;
9084 any_waited = (any_waited || waited);
9087 if (error != 0 || missing || !any_waited)
9088 break;
9091 zfs_close(zhp);
9093 return (error);
9097 * Display version message
9099 static int
9100 zfs_do_version(int argc, char **argv)
9102 int c;
9103 nvlist_t *jsobj = NULL, *zfs_ver = NULL;
9104 boolean_t json = B_FALSE;
9106 struct option long_options[] = {
9107 {"json", no_argument, NULL, 'j'},
9108 {0, 0, 0, 0}
9111 while ((c = getopt_long(argc, argv, "j", long_options, NULL)) != -1) {
9112 switch (c) {
9113 case 'j':
9114 json = B_TRUE;
9115 jsobj = zfs_json_schema(0, 1);
9116 break;
9117 case '?':
9118 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
9119 optopt);
9120 usage(B_FALSE);
9124 argc -= optind;
9125 if (argc != 0) {
9126 (void) fprintf(stderr, "too many arguments\n");
9127 usage(B_FALSE);
9130 if (json) {
9131 zfs_ver = zfs_version_nvlist();
9132 if (zfs_ver) {
9133 fnvlist_add_nvlist(jsobj, "zfs_version", zfs_ver);
9134 zcmd_print_json(jsobj);
9135 fnvlist_free(zfs_ver);
9136 return (0);
9137 } else
9138 return (-1);
9139 } else
9140 return (zfs_version_print() != 0);
9143 /* Display documentation */
9144 static int
9145 zfs_do_help(int argc, char **argv)
9147 char page[MAXNAMELEN];
9148 if (argc < 3 || strcmp(argv[2], "zfs") == 0)
9149 strcpy(page, "zfs");
9150 else if (strcmp(argv[2], "concepts") == 0 ||
9151 strcmp(argv[2], "props") == 0)
9152 snprintf(page, sizeof (page), "zfs%s", argv[2]);
9153 else
9154 snprintf(page, sizeof (page), "zfs-%s", argv[2]);
9156 execlp("man", "man", page, NULL);
9158 fprintf(stderr, "couldn't run man program: %s", strerror(errno));
9159 return (-1);
9163 main(int argc, char **argv)
9165 int ret = 0;
9166 int i = 0;
9167 const char *cmdname;
9168 char **newargv;
9170 (void) setlocale(LC_ALL, "");
9171 (void) setlocale(LC_NUMERIC, "C");
9172 (void) textdomain(TEXT_DOMAIN);
9174 opterr = 0;
9177 * Make sure the user has specified some command.
9179 if (argc < 2) {
9180 (void) fprintf(stderr, gettext("missing command\n"));
9181 usage(B_FALSE);
9184 cmdname = argv[1];
9187 * The 'umount' command is an alias for 'unmount'
9189 if (strcmp(cmdname, "umount") == 0)
9190 cmdname = "unmount";
9193 * The 'recv' command is an alias for 'receive'
9195 if (strcmp(cmdname, "recv") == 0)
9196 cmdname = "receive";
9199 * The 'snap' command is an alias for 'snapshot'
9201 if (strcmp(cmdname, "snap") == 0)
9202 cmdname = "snapshot";
9205 * Special case '-?'
9207 if ((strcmp(cmdname, "-?") == 0) ||
9208 (strcmp(cmdname, "--help") == 0))
9209 usage(B_TRUE);
9212 * Special case '-V|--version'
9214 if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
9215 return (zfs_version_print() != 0);
9218 * Special case 'help'
9220 if (strcmp(cmdname, "help") == 0)
9221 return (zfs_do_help(argc, argv));
9223 if ((g_zfs = libzfs_init()) == NULL) {
9224 (void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
9225 return (1);
9228 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
9230 libzfs_print_on_error(g_zfs, B_TRUE);
9232 zfs_setproctitle_init(argc, argv, environ);
9235 * Many commands modify input strings for string parsing reasons.
9236 * We create a copy to protect the original argv.
9238 newargv = safe_malloc((argc + 1) * sizeof (newargv[0]));
9239 for (i = 0; i < argc; i++)
9240 newargv[i] = strdup(argv[i]);
9241 newargv[argc] = NULL;
9244 * Run the appropriate command.
9246 libzfs_mnttab_cache(g_zfs, B_TRUE);
9247 if (find_command_idx(cmdname, &i) == 0) {
9248 current_command = &command_table[i];
9249 ret = command_table[i].func(argc - 1, newargv + 1);
9250 } else if (strchr(cmdname, '=') != NULL) {
9251 verify(find_command_idx("set", &i) == 0);
9252 current_command = &command_table[i];
9253 ret = command_table[i].func(argc, newargv);
9254 } else {
9255 (void) fprintf(stderr, gettext("unrecognized "
9256 "command '%s'\n"), cmdname);
9257 usage(B_FALSE);
9258 ret = 1;
9261 for (i = 0; i < argc; i++)
9262 free(newargv[i]);
9263 free(newargv);
9265 if (ret == 0 && log_history)
9266 (void) zpool_log_history(g_zfs, history_str);
9268 libzfs_fini(g_zfs);
9271 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
9272 * for the purposes of running ::findleaks.
9274 if (getenv("ZFS_ABORT") != NULL) {
9275 (void) printf("dumping core by request\n");
9276 abort();
9279 return (ret);
9283 * zfs zone nsfile filesystem
9285 * Add or delete the given dataset to/from the namespace.
9287 #ifdef __linux__
9288 static int
9289 zfs_do_zone_impl(int argc, char **argv, boolean_t attach)
9291 zfs_handle_t *zhp;
9292 int ret;
9294 if (argc < 3) {
9295 (void) fprintf(stderr, gettext("missing argument(s)\n"));
9296 usage(B_FALSE);
9298 if (argc > 3) {
9299 (void) fprintf(stderr, gettext("too many arguments\n"));
9300 usage(B_FALSE);
9303 zhp = zfs_open(g_zfs, argv[2], ZFS_TYPE_FILESYSTEM);
9304 if (zhp == NULL)
9305 return (1);
9307 ret = (zfs_userns(zhp, argv[1], attach) != 0);
9309 zfs_close(zhp);
9310 return (ret);
9313 static int
9314 zfs_do_zone(int argc, char **argv)
9316 return (zfs_do_zone_impl(argc, argv, B_TRUE));
9319 static int
9320 zfs_do_unzone(int argc, char **argv)
9322 return (zfs_do_zone_impl(argc, argv, B_FALSE));
9324 #endif
9326 #ifdef __FreeBSD__
9327 #include <sys/jail.h>
9328 #include <jail.h>
9330 * Attach/detach the given dataset to/from the given jail
9332 static int
9333 zfs_do_jail_impl(int argc, char **argv, boolean_t attach)
9335 zfs_handle_t *zhp;
9336 int jailid, ret;
9338 /* check number of arguments */
9339 if (argc < 3) {
9340 (void) fprintf(stderr, gettext("missing argument(s)\n"));
9341 usage(B_FALSE);
9343 if (argc > 3) {
9344 (void) fprintf(stderr, gettext("too many arguments\n"));
9345 usage(B_FALSE);
9348 jailid = jail_getid(argv[1]);
9349 if (jailid < 0) {
9350 (void) fprintf(stderr, gettext("invalid jail id or name\n"));
9351 usage(B_FALSE);
9354 zhp = zfs_open(g_zfs, argv[2], ZFS_TYPE_FILESYSTEM);
9355 if (zhp == NULL)
9356 return (1);
9358 ret = (zfs_jail(zhp, jailid, attach) != 0);
9360 zfs_close(zhp);
9361 return (ret);
9365 * zfs jail jailid filesystem
9367 * Attach the given dataset to the given jail
9369 static int
9370 zfs_do_jail(int argc, char **argv)
9372 return (zfs_do_jail_impl(argc, argv, B_TRUE));
9376 * zfs unjail jailid filesystem
9378 * Detach the given dataset from the given jail
9380 static int
9381 zfs_do_unjail(int argc, char **argv)
9383 return (zfs_do_jail_impl(argc, argv, B_FALSE));
9385 #endif