zfs_debug: Restore log size limit for userspace
[zfs.git] / cmd / zfs / zfs_main.c
blob97397726c709beaaa7390a75073952f20334c9d2
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 if (zprop_nvlist_one_property(
3765 zfs_prop_to_name(pl->pl_prop), propstr,
3766 sourcetype, source, NULL, props,
3767 cb->cb_json_as_int) != 0)
3768 nomem();
3769 } else {
3771 * zfs_list_avail_color() needs
3772 * ZFS_PROP_AVAILABLE + USED, so we need another
3773 * for() search for the USED part when no colors
3774 * wanted, we can skip the whole thing
3776 if (use_color() && pl->pl_prop == ZFS_PROP_AVAILABLE) {
3777 zprop_list_t *pl2 = cb->cb_proplist;
3778 for (; pl2 != NULL; pl2 = pl2->pl_next) {
3779 if (pl2->pl_prop == ZFS_PROP_USED) {
3780 color_start(
3781 zfs_list_avail_color(zhp));
3783 * found it, no need for more
3784 * loops
3786 break;
3792 * If this is being called in scripted mode, or if
3793 * this is the last column and it is left-justified,
3794 * don't include a width format specifier.
3796 if (cb->cb_scripted || (pl->pl_next == NULL &&
3797 !right_justify))
3798 (void) fputs(propstr, stdout);
3799 else if (right_justify) {
3800 (void) printf("%*s", (int)pl->pl_width,
3801 propstr);
3802 } else {
3803 (void) printf("%-*s", (int)pl->pl_width,
3804 propstr);
3807 if (pl->pl_prop == ZFS_PROP_AVAILABLE)
3808 color_end();
3811 if (cb->cb_json) {
3812 fnvlist_add_nvlist(item, "properties", props);
3813 fnvlist_add_nvlist(d, zfs_get_name(zhp), item);
3814 fnvlist_free(props);
3815 fnvlist_free(item);
3816 } else
3817 (void) putchar('\n');
3821 * Generic callback function to list a dataset or snapshot.
3823 static int
3824 list_callback(zfs_handle_t *zhp, void *data)
3826 list_cbdata_t *cbp = data;
3828 if (cbp->cb_first) {
3829 if (!cbp->cb_scripted && !cbp->cb_json)
3830 print_header(cbp);
3831 cbp->cb_first = B_FALSE;
3834 collect_dataset(zhp, cbp);
3836 return (0);
3839 static int
3840 zfs_do_list(int argc, char **argv)
3842 int c;
3843 char default_fields[] =
3844 "name,used,available,referenced,mountpoint";
3845 int types = ZFS_TYPE_DATASET;
3846 boolean_t types_specified = B_FALSE;
3847 char *fields = default_fields;
3848 list_cbdata_t cb = { 0 };
3849 int limit = 0;
3850 int ret = 0;
3851 zfs_sort_column_t *sortcol = NULL;
3852 int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
3853 nvlist_t *data = NULL;
3855 struct option long_options[] = {
3856 {"json", no_argument, NULL, 'j'},
3857 {"json-int", no_argument, NULL, ZFS_OPTION_JSON_NUMS_AS_INT},
3858 {0, 0, 0, 0}
3861 /* check options */
3862 while ((c = getopt_long(argc, argv, "jHS:d:o:prs:t:", long_options,
3863 NULL)) != -1) {
3864 switch (c) {
3865 case 'o':
3866 fields = optarg;
3867 break;
3868 case 'p':
3869 cb.cb_literal = B_TRUE;
3870 flags |= ZFS_ITER_LITERAL_PROPS;
3871 break;
3872 case 'd':
3873 limit = parse_depth(optarg, &flags);
3874 break;
3875 case 'r':
3876 flags |= ZFS_ITER_RECURSE;
3877 break;
3878 case 'j':
3879 cb.cb_json = B_TRUE;
3880 cb.cb_jsobj = zfs_json_schema(0, 1);
3881 data = fnvlist_alloc();
3882 fnvlist_add_nvlist(cb.cb_jsobj, "datasets", data);
3883 fnvlist_free(data);
3884 break;
3885 case ZFS_OPTION_JSON_NUMS_AS_INT:
3886 cb.cb_json_as_int = B_TRUE;
3887 cb.cb_literal = B_TRUE;
3888 break;
3889 case 'H':
3890 cb.cb_scripted = B_TRUE;
3891 break;
3892 case 's':
3893 if (zfs_add_sort_column(&sortcol, optarg,
3894 B_FALSE) != 0) {
3895 (void) fprintf(stderr,
3896 gettext("invalid property '%s'\n"), optarg);
3897 usage(B_FALSE);
3899 break;
3900 case 'S':
3901 if (zfs_add_sort_column(&sortcol, optarg,
3902 B_TRUE) != 0) {
3903 (void) fprintf(stderr,
3904 gettext("invalid property '%s'\n"), optarg);
3905 usage(B_FALSE);
3907 break;
3908 case 't':
3909 types = 0;
3910 types_specified = B_TRUE;
3911 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
3913 for (char *tok; (tok = strsep(&optarg, ",")); ) {
3914 static const char *const type_subopts[] = {
3915 "filesystem",
3916 "fs",
3917 "volume",
3918 "vol",
3919 "snapshot",
3920 "snap",
3921 "bookmark",
3922 "all"
3924 static const int type_types[] = {
3925 ZFS_TYPE_FILESYSTEM,
3926 ZFS_TYPE_FILESYSTEM,
3927 ZFS_TYPE_VOLUME,
3928 ZFS_TYPE_VOLUME,
3929 ZFS_TYPE_SNAPSHOT,
3930 ZFS_TYPE_SNAPSHOT,
3931 ZFS_TYPE_BOOKMARK,
3932 ZFS_TYPE_DATASET | ZFS_TYPE_BOOKMARK
3935 for (c = 0; c < ARRAY_SIZE(type_subopts); ++c)
3936 if (strcmp(tok, type_subopts[c]) == 0) {
3937 types |= type_types[c];
3938 goto found3;
3941 (void) fprintf(stderr,
3942 gettext("invalid type '%s'\n"), tok);
3943 usage(B_FALSE);
3944 found3:;
3946 break;
3947 case ':':
3948 (void) fprintf(stderr, gettext("missing argument for "
3949 "'%c' option\n"), optopt);
3950 usage(B_FALSE);
3951 break;
3952 case '?':
3953 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3954 optopt);
3955 usage(B_FALSE);
3959 argc -= optind;
3960 argv += optind;
3962 if (!cb.cb_json && cb.cb_json_as_int) {
3963 (void) fprintf(stderr, gettext("'--json-int' only works with"
3964 " '-j' option\n"));
3965 usage(B_FALSE);
3969 * If "-o space" and no types were specified, don't display snapshots.
3971 if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3972 types &= ~ZFS_TYPE_SNAPSHOT;
3975 * Handle users who want to list all snapshots or bookmarks
3976 * of the current dataset (ex. 'zfs list -t snapshot <dataset>').
3978 if ((types == ZFS_TYPE_SNAPSHOT || types == ZFS_TYPE_BOOKMARK) &&
3979 argc > 0 && (flags & ZFS_ITER_RECURSE) == 0 && limit == 0) {
3980 flags |= (ZFS_ITER_DEPTH_LIMIT | ZFS_ITER_RECURSE);
3981 limit = 1;
3985 * If the user specifies '-o all', the zprop_get_list() doesn't
3986 * normally include the name of the dataset. For 'zfs list', we always
3987 * want this property to be first.
3989 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3990 != 0)
3991 usage(B_FALSE);
3993 cb.cb_first = B_TRUE;
3996 * If we are only going to list and sort by properties that are "fast"
3997 * then we can use "simple" mode and avoid populating the properties
3998 * nvlist.
4000 if (zfs_list_only_by_fast(cb.cb_proplist) &&
4001 zfs_sort_only_by_fast(sortcol))
4002 flags |= ZFS_ITER_SIMPLE;
4004 ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
4005 limit, list_callback, &cb);
4007 if (ret == 0 && cb.cb_json)
4008 zcmd_print_json(cb.cb_jsobj);
4009 else if (ret != 0 && cb.cb_json)
4010 nvlist_free(cb.cb_jsobj);
4012 zprop_free_list(cb.cb_proplist);
4013 zfs_free_sort_columns(sortcol);
4015 if (ret == 0 && cb.cb_first && !cb.cb_scripted)
4016 (void) fprintf(stderr, gettext("no datasets available\n"));
4018 return (ret);
4022 * zfs rename [-fu] <fs | snap | vol> <fs | snap | vol>
4023 * zfs rename [-f] -p <fs | vol> <fs | vol>
4024 * zfs rename [-u] -r <snap> <snap>
4026 * Renames the given dataset to another of the same type.
4028 * The '-p' flag creates all the non-existing ancestors of the target first.
4029 * The '-u' flag prevents file systems from being remounted during rename.
4031 static int
4032 zfs_do_rename(int argc, char **argv)
4034 zfs_handle_t *zhp;
4035 renameflags_t flags = { 0 };
4036 int c;
4037 int ret = 0;
4038 int types;
4039 boolean_t parents = B_FALSE;
4041 /* check options */
4042 while ((c = getopt(argc, argv, "pruf")) != -1) {
4043 switch (c) {
4044 case 'p':
4045 parents = B_TRUE;
4046 break;
4047 case 'r':
4048 flags.recursive = B_TRUE;
4049 break;
4050 case 'u':
4051 flags.nounmount = B_TRUE;
4052 break;
4053 case 'f':
4054 flags.forceunmount = B_TRUE;
4055 break;
4056 case '?':
4057 default:
4058 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4059 optopt);
4060 usage(B_FALSE);
4064 argc -= optind;
4065 argv += optind;
4067 /* check number of arguments */
4068 if (argc < 1) {
4069 (void) fprintf(stderr, gettext("missing source dataset "
4070 "argument\n"));
4071 usage(B_FALSE);
4073 if (argc < 2) {
4074 (void) fprintf(stderr, gettext("missing target dataset "
4075 "argument\n"));
4076 usage(B_FALSE);
4078 if (argc > 2) {
4079 (void) fprintf(stderr, gettext("too many arguments\n"));
4080 usage(B_FALSE);
4083 if (flags.recursive && parents) {
4084 (void) fprintf(stderr, gettext("-p and -r options are mutually "
4085 "exclusive\n"));
4086 usage(B_FALSE);
4089 if (flags.nounmount && parents) {
4090 (void) fprintf(stderr, gettext("-u and -p options are mutually "
4091 "exclusive\n"));
4092 usage(B_FALSE);
4095 if (flags.recursive && strchr(argv[0], '@') == 0) {
4096 (void) fprintf(stderr, gettext("source dataset for recursive "
4097 "rename must be a snapshot\n"));
4098 usage(B_FALSE);
4101 if (flags.nounmount)
4102 types = ZFS_TYPE_FILESYSTEM;
4103 else if (parents)
4104 types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
4105 else
4106 types = ZFS_TYPE_DATASET;
4108 if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL)
4109 return (1);
4111 /* If we were asked and the name looks good, try to create ancestors. */
4112 if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
4113 zfs_create_ancestors(g_zfs, argv[1]) != 0) {
4114 zfs_close(zhp);
4115 return (1);
4118 ret = (zfs_rename(zhp, argv[1], flags) != 0);
4120 zfs_close(zhp);
4121 return (ret);
4125 * zfs promote <fs>
4127 * Promotes the given clone fs to be the parent
4129 static int
4130 zfs_do_promote(int argc, char **argv)
4132 zfs_handle_t *zhp;
4133 int ret = 0;
4135 /* check options */
4136 if (argc > 1 && argv[1][0] == '-') {
4137 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4138 argv[1][1]);
4139 usage(B_FALSE);
4142 /* check number of arguments */
4143 if (argc < 2) {
4144 (void) fprintf(stderr, gettext("missing clone filesystem"
4145 " argument\n"));
4146 usage(B_FALSE);
4148 if (argc > 2) {
4149 (void) fprintf(stderr, gettext("too many arguments\n"));
4150 usage(B_FALSE);
4153 zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4154 if (zhp == NULL)
4155 return (1);
4157 ret = (zfs_promote(zhp) != 0);
4160 zfs_close(zhp);
4161 return (ret);
4164 static int
4165 zfs_do_redact(int argc, char **argv)
4167 char *snap = NULL;
4168 char *bookname = NULL;
4169 char **rsnaps = NULL;
4170 int numrsnaps = 0;
4171 argv++;
4172 argc--;
4173 if (argc < 3) {
4174 (void) fprintf(stderr, gettext("too few arguments\n"));
4175 usage(B_FALSE);
4178 snap = argv[0];
4179 bookname = argv[1];
4180 rsnaps = argv + 2;
4181 numrsnaps = argc - 2;
4183 nvlist_t *rsnapnv = fnvlist_alloc();
4185 for (int i = 0; i < numrsnaps; i++) {
4186 fnvlist_add_boolean(rsnapnv, rsnaps[i]);
4189 int err = lzc_redact(snap, bookname, rsnapnv);
4190 fnvlist_free(rsnapnv);
4192 switch (err) {
4193 case 0:
4194 break;
4195 case ENOENT: {
4196 zfs_handle_t *zhp = zfs_open(g_zfs, snap, ZFS_TYPE_SNAPSHOT);
4197 if (zhp == NULL) {
4198 (void) fprintf(stderr, gettext("provided snapshot %s "
4199 "does not exist\n"), snap);
4200 } else {
4201 zfs_close(zhp);
4203 for (int i = 0; i < numrsnaps; i++) {
4204 zhp = zfs_open(g_zfs, rsnaps[i], ZFS_TYPE_SNAPSHOT);
4205 if (zhp == NULL) {
4206 (void) fprintf(stderr, gettext("provided "
4207 "snapshot %s does not exist\n"), rsnaps[i]);
4208 } else {
4209 zfs_close(zhp);
4212 break;
4214 case EEXIST:
4215 (void) fprintf(stderr, gettext("specified redaction bookmark "
4216 "(%s) provided already exists\n"), bookname);
4217 break;
4218 case ENAMETOOLONG:
4219 (void) fprintf(stderr, gettext("provided bookmark name cannot "
4220 "be used, final name would be too long\n"));
4221 break;
4222 case E2BIG:
4223 (void) fprintf(stderr, gettext("too many redaction snapshots "
4224 "specified\n"));
4225 break;
4226 case EINVAL:
4227 if (strchr(bookname, '#') != NULL)
4228 (void) fprintf(stderr, gettext(
4229 "redaction bookmark name must not contain '#'\n"));
4230 else
4231 (void) fprintf(stderr, gettext(
4232 "redaction snapshot must be descendent of "
4233 "snapshot being redacted\n"));
4234 break;
4235 case EALREADY:
4236 (void) fprintf(stderr, gettext("attempted to redact redacted "
4237 "dataset or with respect to redacted dataset\n"));
4238 break;
4239 case ENOTSUP:
4240 (void) fprintf(stderr, gettext("redaction bookmarks feature "
4241 "not enabled\n"));
4242 break;
4243 case EXDEV:
4244 (void) fprintf(stderr, gettext("potentially invalid redaction "
4245 "snapshot; full dataset names required\n"));
4246 break;
4247 case ESRCH:
4248 (void) fprintf(stderr, gettext("attempted to resume redaction "
4249 " with a mismatched redaction list\n"));
4250 break;
4251 default:
4252 (void) fprintf(stderr, gettext("internal error: %s\n"),
4253 strerror(errno));
4256 return (err);
4260 * zfs rollback [-rRf] <snapshot>
4262 * -r Delete any intervening snapshots before doing rollback
4263 * -R Delete any snapshots and their clones
4264 * -f ignored for backwards compatibility
4266 * Given a filesystem, rollback to a specific snapshot, discarding any changes
4267 * since then and making it the active dataset. If more recent snapshots exist,
4268 * the command will complain unless the '-r' flag is given.
4270 typedef struct rollback_cbdata {
4271 uint64_t cb_create;
4272 uint8_t cb_younger_ds_printed;
4273 boolean_t cb_first;
4274 int cb_doclones;
4275 char *cb_target;
4276 int cb_error;
4277 boolean_t cb_recurse;
4278 } rollback_cbdata_t;
4280 static int
4281 rollback_check_dependent(zfs_handle_t *zhp, void *data)
4283 rollback_cbdata_t *cbp = data;
4285 if (cbp->cb_first && cbp->cb_recurse) {
4286 (void) fprintf(stderr, gettext("cannot rollback to "
4287 "'%s': clones of previous snapshots exist\n"),
4288 cbp->cb_target);
4289 (void) fprintf(stderr, gettext("use '-R' to "
4290 "force deletion of the following clones and "
4291 "dependents:\n"));
4292 cbp->cb_first = 0;
4293 cbp->cb_error = 1;
4296 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
4298 zfs_close(zhp);
4299 return (0);
4304 * Report some snapshots/bookmarks more recent than the one specified.
4305 * Used when '-r' is not specified. We reuse this same callback for the
4306 * snapshot dependents - if 'cb_dependent' is set, then this is a
4307 * dependent and we should report it without checking the transaction group.
4309 static int
4310 rollback_check(zfs_handle_t *zhp, void *data)
4312 rollback_cbdata_t *cbp = data;
4314 * Max number of younger snapshots and/or bookmarks to display before
4315 * we stop the iteration.
4317 const uint8_t max_younger = 32;
4319 if (cbp->cb_doclones) {
4320 zfs_close(zhp);
4321 return (0);
4324 if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
4325 if (cbp->cb_first && !cbp->cb_recurse) {
4326 (void) fprintf(stderr, gettext("cannot "
4327 "rollback to '%s': more recent snapshots "
4328 "or bookmarks exist\n"),
4329 cbp->cb_target);
4330 (void) fprintf(stderr, gettext("use '-r' to "
4331 "force deletion of the following "
4332 "snapshots and bookmarks:\n"));
4333 cbp->cb_first = 0;
4334 cbp->cb_error = 1;
4337 if (cbp->cb_recurse) {
4338 if (zfs_iter_dependents_v2(zhp, 0, B_TRUE,
4339 rollback_check_dependent, cbp) != 0) {
4340 zfs_close(zhp);
4341 return (-1);
4343 } else {
4344 (void) fprintf(stderr, "%s\n",
4345 zfs_get_name(zhp));
4346 cbp->cb_younger_ds_printed++;
4349 zfs_close(zhp);
4351 if (cbp->cb_younger_ds_printed == max_younger) {
4353 * This non-recursive rollback is going to fail due to the
4354 * presence of snapshots and/or bookmarks that are younger than
4355 * the rollback target.
4356 * We printed some of the offending objects, now we stop
4357 * zfs_iter_snapshot/bookmark iteration so we can fail fast and
4358 * avoid iterating over the rest of the younger objects
4360 (void) fprintf(stderr, gettext("Output limited to %d "
4361 "snapshots/bookmarks\n"), max_younger);
4362 return (-1);
4364 return (0);
4367 static int
4368 zfs_do_rollback(int argc, char **argv)
4370 int ret = 0;
4371 int c;
4372 boolean_t force = B_FALSE;
4373 rollback_cbdata_t cb = { 0 };
4374 zfs_handle_t *zhp, *snap;
4375 char parentname[ZFS_MAX_DATASET_NAME_LEN];
4376 char *delim;
4377 uint64_t min_txg = 0;
4379 /* check options */
4380 while ((c = getopt(argc, argv, "rRf")) != -1) {
4381 switch (c) {
4382 case 'r':
4383 cb.cb_recurse = 1;
4384 break;
4385 case 'R':
4386 cb.cb_recurse = 1;
4387 cb.cb_doclones = 1;
4388 break;
4389 case 'f':
4390 force = B_TRUE;
4391 break;
4392 case '?':
4393 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4394 optopt);
4395 usage(B_FALSE);
4399 argc -= optind;
4400 argv += optind;
4402 /* check number of arguments */
4403 if (argc < 1) {
4404 (void) fprintf(stderr, gettext("missing dataset argument\n"));
4405 usage(B_FALSE);
4407 if (argc > 1) {
4408 (void) fprintf(stderr, gettext("too many arguments\n"));
4409 usage(B_FALSE);
4412 /* open the snapshot */
4413 if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
4414 return (1);
4416 /* open the parent dataset */
4417 (void) strlcpy(parentname, argv[0], sizeof (parentname));
4418 verify((delim = strrchr(parentname, '@')) != NULL);
4419 *delim = '\0';
4420 if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
4421 zfs_close(snap);
4422 return (1);
4426 * Check for more recent snapshots and/or clones based on the presence
4427 * of '-r' and '-R'.
4429 cb.cb_target = argv[0];
4430 cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
4431 cb.cb_first = B_TRUE;
4432 cb.cb_error = 0;
4434 if (cb.cb_create > 0)
4435 min_txg = cb.cb_create;
4437 if ((ret = zfs_iter_snapshots_v2(zhp, 0, rollback_check, &cb,
4438 min_txg, 0)) != 0)
4439 goto out;
4440 if ((ret = zfs_iter_bookmarks_v2(zhp, 0, rollback_check, &cb)) != 0)
4441 goto out;
4443 if ((ret = cb.cb_error) != 0)
4444 goto out;
4447 * Rollback parent to the given snapshot.
4449 ret = zfs_rollback(zhp, snap, force);
4451 out:
4452 zfs_close(snap);
4453 zfs_close(zhp);
4455 if (ret == 0)
4456 return (0);
4457 else
4458 return (1);
4462 * zfs set property=value ... { fs | snap | vol } ...
4464 * Sets the given properties for all datasets specified on the command line.
4467 static int
4468 set_callback(zfs_handle_t *zhp, void *data)
4470 zprop_set_cbdata_t *cb = data;
4471 int ret = zfs_prop_set_list_flags(zhp, cb->cb_proplist, cb->cb_flags);
4473 if (ret != 0 || libzfs_errno(g_zfs) != EZFS_SUCCESS) {
4474 switch (libzfs_errno(g_zfs)) {
4475 case EZFS_MOUNTFAILED:
4476 (void) fprintf(stderr, gettext("property may be set "
4477 "but unable to remount filesystem\n"));
4478 break;
4479 case EZFS_SHARENFSFAILED:
4480 (void) fprintf(stderr, gettext("property may be set "
4481 "but unable to reshare filesystem\n"));
4482 break;
4485 return (ret);
4488 static int
4489 zfs_do_set(int argc, char **argv)
4491 zprop_set_cbdata_t cb = { 0 };
4492 int ds_start = -1; /* argv idx of first dataset arg */
4493 int ret = 0;
4494 int i, c;
4496 /* check options */
4497 while ((c = getopt(argc, argv, "u")) != -1) {
4498 switch (c) {
4499 case 'u':
4500 cb.cb_flags |= ZFS_SET_NOMOUNT;
4501 break;
4502 case '?':
4503 default:
4504 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4505 optopt);
4506 usage(B_FALSE);
4510 argc -= optind;
4511 argv += optind;
4513 /* check number of arguments */
4514 if (argc < 1) {
4515 (void) fprintf(stderr, gettext("missing arguments\n"));
4516 usage(B_FALSE);
4518 if (argc < 2) {
4519 if (strchr(argv[0], '=') == NULL) {
4520 (void) fprintf(stderr, gettext("missing property=value "
4521 "argument(s)\n"));
4522 } else {
4523 (void) fprintf(stderr, gettext("missing dataset "
4524 "name(s)\n"));
4526 usage(B_FALSE);
4529 /* validate argument order: prop=val args followed by dataset args */
4530 for (i = 0; i < argc; i++) {
4531 if (strchr(argv[i], '=') != NULL) {
4532 if (ds_start > 0) {
4533 /* out-of-order prop=val argument */
4534 (void) fprintf(stderr, gettext("invalid "
4535 "argument order\n"));
4536 usage(B_FALSE);
4538 } else if (ds_start < 0) {
4539 ds_start = i;
4542 if (ds_start < 0) {
4543 (void) fprintf(stderr, gettext("missing dataset name(s)\n"));
4544 usage(B_FALSE);
4547 /* Populate a list of property settings */
4548 if (nvlist_alloc(&cb.cb_proplist, NV_UNIQUE_NAME, 0) != 0)
4549 nomem();
4550 for (i = 0; i < ds_start; i++) {
4551 if (!parseprop(cb.cb_proplist, argv[i])) {
4552 ret = -1;
4553 goto error;
4557 ret = zfs_for_each(argc - ds_start, argv + ds_start, 0,
4558 ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, &cb);
4560 error:
4561 nvlist_free(cb.cb_proplist);
4562 return (ret);
4565 typedef struct snap_cbdata {
4566 nvlist_t *sd_nvl;
4567 boolean_t sd_recursive;
4568 const char *sd_snapname;
4569 } snap_cbdata_t;
4571 static int
4572 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
4574 snap_cbdata_t *sd = arg;
4575 char *name;
4576 int rv = 0;
4577 int error;
4579 if (sd->sd_recursive &&
4580 zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
4581 zfs_close(zhp);
4582 return (0);
4585 error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
4586 if (error == -1)
4587 nomem();
4588 fnvlist_add_boolean(sd->sd_nvl, name);
4589 free(name);
4591 if (sd->sd_recursive)
4592 rv = zfs_iter_filesystems_v2(zhp, 0, zfs_snapshot_cb, sd);
4593 zfs_close(zhp);
4594 return (rv);
4598 * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
4600 * Creates a snapshot with the given name. While functionally equivalent to
4601 * 'zfs create', it is a separate command to differentiate intent.
4603 static int
4604 zfs_do_snapshot(int argc, char **argv)
4606 int ret = 0;
4607 int c;
4608 nvlist_t *props;
4609 snap_cbdata_t sd = { 0 };
4610 boolean_t multiple_snaps = B_FALSE;
4612 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
4613 nomem();
4614 if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
4615 nomem();
4617 /* check options */
4618 while ((c = getopt(argc, argv, "ro:")) != -1) {
4619 switch (c) {
4620 case 'o':
4621 if (!parseprop(props, optarg)) {
4622 nvlist_free(sd.sd_nvl);
4623 nvlist_free(props);
4624 return (1);
4626 break;
4627 case 'r':
4628 sd.sd_recursive = B_TRUE;
4629 multiple_snaps = B_TRUE;
4630 break;
4631 case '?':
4632 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4633 optopt);
4634 goto usage;
4638 argc -= optind;
4639 argv += optind;
4641 /* check number of arguments */
4642 if (argc < 1) {
4643 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
4644 goto usage;
4647 if (argc > 1)
4648 multiple_snaps = B_TRUE;
4649 for (; argc > 0; argc--, argv++) {
4650 char *atp;
4651 zfs_handle_t *zhp;
4653 atp = strchr(argv[0], '@');
4654 if (atp == NULL)
4655 goto usage;
4656 *atp = '\0';
4657 sd.sd_snapname = atp + 1;
4658 zhp = zfs_open(g_zfs, argv[0],
4659 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4660 if (zhp == NULL)
4661 goto usage;
4662 if (zfs_snapshot_cb(zhp, &sd) != 0)
4663 goto usage;
4666 ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
4667 nvlist_free(sd.sd_nvl);
4668 nvlist_free(props);
4669 if (ret != 0 && multiple_snaps)
4670 (void) fprintf(stderr, gettext("no snapshots were created\n"));
4671 return (ret != 0);
4673 usage:
4674 nvlist_free(sd.sd_nvl);
4675 nvlist_free(props);
4676 usage(B_FALSE);
4677 return (-1);
4681 * Array of prefixes to exclude –
4682 * a linear search, even if executed for each dataset,
4683 * is plenty good enough.
4685 typedef struct zfs_send_exclude_arg {
4686 size_t count;
4687 const char **list;
4688 } zfs_send_exclude_arg_t;
4690 static boolean_t
4691 zfs_do_send_exclude(zfs_handle_t *zhp, void *context)
4693 zfs_send_exclude_arg_t *excludes = context;
4694 const char *name = zfs_get_name(zhp);
4696 for (size_t i = 0; i < excludes->count; ++i) {
4697 size_t len = strlen(excludes->list[i]);
4698 if (strncmp(name, excludes->list[i], len) == 0 &&
4699 memchr("/@", name[len], sizeof ("/@")))
4700 return (B_FALSE);
4703 return (B_TRUE);
4707 * Send a backup stream to stdout.
4709 static int
4710 zfs_do_send(int argc, char **argv)
4712 char *fromname = NULL;
4713 char *toname = NULL;
4714 char *resume_token = NULL;
4715 char *cp;
4716 zfs_handle_t *zhp;
4717 sendflags_t flags = { 0 };
4718 int c, err;
4719 nvlist_t *dbgnv = NULL;
4720 char *redactbook = NULL;
4721 zfs_send_exclude_arg_t excludes = { 0 };
4723 struct option long_options[] = {
4724 {"replicate", no_argument, NULL, 'R'},
4725 {"skip-missing", no_argument, NULL, 's'},
4726 {"redact", required_argument, NULL, 'd'},
4727 {"props", no_argument, NULL, 'p'},
4728 {"parsable", no_argument, NULL, 'P'},
4729 {"dedup", no_argument, NULL, 'D'},
4730 {"proctitle", no_argument, NULL, 'V'},
4731 {"verbose", no_argument, NULL, 'v'},
4732 {"dryrun", no_argument, NULL, 'n'},
4733 {"large-block", no_argument, NULL, 'L'},
4734 {"embed", no_argument, NULL, 'e'},
4735 {"resume", required_argument, NULL, 't'},
4736 {"compressed", no_argument, NULL, 'c'},
4737 {"raw", no_argument, NULL, 'w'},
4738 {"backup", no_argument, NULL, 'b'},
4739 {"holds", no_argument, NULL, 'h'},
4740 {"saved", no_argument, NULL, 'S'},
4741 {"exclude", required_argument, NULL, 'X'},
4742 {0, 0, 0, 0}
4745 /* check options */
4746 while ((c = getopt_long(argc, argv, ":i:I:RsDpVvnPLeht:cwbd:SX:",
4747 long_options, NULL)) != -1) {
4748 switch (c) {
4749 case 'X':
4750 for (char *ds; (ds = strsep(&optarg, ",")) != NULL; ) {
4751 if (!zfs_name_valid(ds, ZFS_TYPE_DATASET) ||
4752 strchr(ds, '/') == NULL) {
4753 (void) fprintf(stderr, gettext("-X %s: "
4754 "not a valid non-root dataset name"
4755 ".\n"), ds);
4756 usage(B_FALSE);
4758 excludes.list = safe_realloc(excludes.list,
4759 sizeof (char *) * (excludes.count + 1));
4760 excludes.list[excludes.count++] = ds;
4762 break;
4763 case 'i':
4764 if (fromname)
4765 usage(B_FALSE);
4766 fromname = optarg;
4767 break;
4768 case 'I':
4769 if (fromname)
4770 usage(B_FALSE);
4771 fromname = optarg;
4772 flags.doall = B_TRUE;
4773 break;
4774 case 'R':
4775 flags.replicate = B_TRUE;
4776 break;
4777 case 's':
4778 flags.skipmissing = B_TRUE;
4779 break;
4780 case 'd':
4781 redactbook = optarg;
4782 break;
4783 case 'p':
4784 flags.props = B_TRUE;
4785 break;
4786 case 'b':
4787 flags.backup = B_TRUE;
4788 break;
4789 case 'h':
4790 flags.holds = B_TRUE;
4791 break;
4792 case 'P':
4793 flags.parsable = B_TRUE;
4794 break;
4795 case 'V':
4796 flags.progressastitle = B_TRUE;
4797 break;
4798 case 'v':
4799 flags.verbosity++;
4800 flags.progress = B_TRUE;
4801 break;
4802 case 'D':
4803 (void) fprintf(stderr,
4804 gettext("WARNING: deduplicated send is no "
4805 "longer supported. A regular,\n"
4806 "non-deduplicated stream will be generated.\n\n"));
4807 break;
4808 case 'n':
4809 flags.dryrun = B_TRUE;
4810 break;
4811 case 'L':
4812 flags.largeblock = B_TRUE;
4813 break;
4814 case 'e':
4815 flags.embed_data = B_TRUE;
4816 break;
4817 case 't':
4818 resume_token = optarg;
4819 break;
4820 case 'c':
4821 flags.compress = B_TRUE;
4822 break;
4823 case 'w':
4824 flags.raw = B_TRUE;
4825 flags.compress = B_TRUE;
4826 flags.embed_data = B_TRUE;
4827 flags.largeblock = B_TRUE;
4828 break;
4829 case 'S':
4830 flags.saved = B_TRUE;
4831 break;
4832 case ':':
4834 * If a parameter was not passed, optopt contains the
4835 * value that would normally lead us into the
4836 * appropriate case statement. If it's > 256, then this
4837 * must be a longopt and we should look at argv to get
4838 * the string. Otherwise it's just the character, so we
4839 * should use it directly.
4841 if (optopt <= UINT8_MAX) {
4842 (void) fprintf(stderr,
4843 gettext("missing argument for '%c' "
4844 "option\n"), optopt);
4845 } else {
4846 (void) fprintf(stderr,
4847 gettext("missing argument for '%s' "
4848 "option\n"), argv[optind - 1]);
4850 free(excludes.list);
4851 usage(B_FALSE);
4852 break;
4853 case '?':
4854 default:
4856 * If an invalid flag was passed, optopt contains the
4857 * character if it was a short flag, or 0 if it was a
4858 * longopt.
4860 if (optopt != 0) {
4861 (void) fprintf(stderr,
4862 gettext("invalid option '%c'\n"), optopt);
4863 } else {
4864 (void) fprintf(stderr,
4865 gettext("invalid option '%s'\n"),
4866 argv[optind - 1]);
4869 free(excludes.list);
4870 usage(B_FALSE);
4874 if ((flags.parsable || flags.progressastitle) && flags.verbosity == 0)
4875 flags.verbosity = 1;
4877 if (excludes.count > 0 && !flags.replicate) {
4878 free(excludes.list);
4879 (void) fprintf(stderr, gettext("Cannot specify "
4880 "dataset exclusion (-X) on a non-recursive "
4881 "send.\n"));
4882 return (1);
4885 argc -= optind;
4886 argv += optind;
4888 if (resume_token != NULL) {
4889 if (fromname != NULL || flags.replicate || flags.props ||
4890 flags.backup || flags.holds ||
4891 flags.saved || redactbook != NULL) {
4892 free(excludes.list);
4893 (void) fprintf(stderr,
4894 gettext("invalid flags combined with -t\n"));
4895 usage(B_FALSE);
4897 if (argc > 0) {
4898 free(excludes.list);
4899 (void) fprintf(stderr, gettext("too many arguments\n"));
4900 usage(B_FALSE);
4902 } else {
4903 if (argc < 1) {
4904 free(excludes.list);
4905 (void) fprintf(stderr,
4906 gettext("missing snapshot argument\n"));
4907 usage(B_FALSE);
4909 if (argc > 1) {
4910 free(excludes.list);
4911 (void) fprintf(stderr, gettext("too many arguments\n"));
4912 usage(B_FALSE);
4916 if (flags.saved) {
4917 if (fromname != NULL || flags.replicate || flags.props ||
4918 flags.doall || flags.backup ||
4919 flags.holds || flags.largeblock || flags.embed_data ||
4920 flags.compress || flags.raw || redactbook != NULL) {
4921 free(excludes.list);
4923 (void) fprintf(stderr, gettext("incompatible flags "
4924 "combined with saved send flag\n"));
4925 usage(B_FALSE);
4927 if (strchr(argv[0], '@') != NULL) {
4928 free(excludes.list);
4930 (void) fprintf(stderr, gettext("saved send must "
4931 "specify the dataset with partially-received "
4932 "state\n"));
4933 usage(B_FALSE);
4937 if (flags.raw && redactbook != NULL) {
4938 free(excludes.list);
4939 (void) fprintf(stderr,
4940 gettext("Error: raw sends may not be redacted.\n"));
4941 return (1);
4944 if (!flags.dryrun && isatty(STDOUT_FILENO)) {
4945 free(excludes.list);
4946 (void) fprintf(stderr,
4947 gettext("Error: Stream can not be written to a terminal.\n"
4948 "You must redirect standard output.\n"));
4949 return (1);
4952 if (flags.saved) {
4953 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
4954 if (zhp == NULL) {
4955 free(excludes.list);
4956 return (1);
4959 err = zfs_send_saved(zhp, &flags, STDOUT_FILENO,
4960 resume_token);
4961 free(excludes.list);
4962 zfs_close(zhp);
4963 return (err != 0);
4964 } else if (resume_token != NULL) {
4965 free(excludes.list);
4966 return (zfs_send_resume(g_zfs, &flags, STDOUT_FILENO,
4967 resume_token));
4970 if (flags.skipmissing && !flags.replicate) {
4971 free(excludes.list);
4972 (void) fprintf(stderr,
4973 gettext("skip-missing flag can only be used in "
4974 "conjunction with replicate\n"));
4975 usage(B_FALSE);
4979 * For everything except -R and -I, use the new, cleaner code path.
4981 if (!(flags.replicate || flags.doall)) {
4982 char frombuf[ZFS_MAX_DATASET_NAME_LEN];
4984 if (fromname != NULL && (strchr(fromname, '#') == NULL &&
4985 strchr(fromname, '@') == NULL)) {
4987 * Neither bookmark or snapshot was specified. Print a
4988 * warning, and assume snapshot.
4990 (void) fprintf(stderr, "Warning: incremental source "
4991 "didn't specify type, assuming snapshot. Use '@' "
4992 "or '#' prefix to avoid ambiguity.\n");
4993 (void) snprintf(frombuf, sizeof (frombuf), "@%s",
4994 fromname);
4995 fromname = frombuf;
4997 if (fromname != NULL &&
4998 (fromname[0] == '#' || fromname[0] == '@')) {
5000 * Incremental source name begins with # or @.
5001 * Default to same fs as target.
5003 char tmpbuf[ZFS_MAX_DATASET_NAME_LEN];
5004 (void) strlcpy(tmpbuf, fromname, sizeof (tmpbuf));
5005 (void) strlcpy(frombuf, argv[0], sizeof (frombuf));
5006 cp = strchr(frombuf, '@');
5007 if (cp != NULL)
5008 *cp = '\0';
5009 (void) strlcat(frombuf, tmpbuf, sizeof (frombuf));
5010 fromname = frombuf;
5013 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
5014 if (zhp == NULL) {
5015 free(excludes.list);
5016 return (1);
5018 err = zfs_send_one(zhp, fromname, STDOUT_FILENO, &flags,
5019 redactbook);
5021 free(excludes.list);
5022 zfs_close(zhp);
5023 return (err != 0);
5026 if (fromname != NULL && strchr(fromname, '#')) {
5027 (void) fprintf(stderr,
5028 gettext("Error: multiple snapshots cannot be "
5029 "sent from a bookmark.\n"));
5030 free(excludes.list);
5031 return (1);
5034 if (redactbook != NULL) {
5035 (void) fprintf(stderr, gettext("Error: multiple snapshots "
5036 "cannot be sent redacted.\n"));
5037 free(excludes.list);
5038 return (1);
5041 if ((cp = strchr(argv[0], '@')) == NULL) {
5042 (void) fprintf(stderr, gettext("Error: "
5043 "Unsupported flag with filesystem or bookmark.\n"));
5044 free(excludes.list);
5045 return (1);
5047 *cp = '\0';
5048 toname = cp + 1;
5049 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5050 if (zhp == NULL) {
5051 free(excludes.list);
5052 return (1);
5056 * If they specified the full path to the snapshot, chop off
5057 * everything except the short name of the snapshot, but special
5058 * case if they specify the origin.
5060 if (fromname && (cp = strchr(fromname, '@')) != NULL) {
5061 char origin[ZFS_MAX_DATASET_NAME_LEN];
5062 zprop_source_t src;
5064 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
5065 origin, sizeof (origin), &src, NULL, 0, B_FALSE);
5067 if (strcmp(origin, fromname) == 0) {
5068 fromname = NULL;
5069 flags.fromorigin = B_TRUE;
5070 } else {
5071 *cp = '\0';
5072 if (cp != fromname && strcmp(argv[0], fromname)) {
5073 zfs_close(zhp);
5074 free(excludes.list);
5075 (void) fprintf(stderr,
5076 gettext("incremental source must be "
5077 "in same filesystem\n"));
5078 usage(B_FALSE);
5080 fromname = cp + 1;
5081 if (strchr(fromname, '@') || strchr(fromname, '/')) {
5082 zfs_close(zhp);
5083 free(excludes.list);
5084 (void) fprintf(stderr,
5085 gettext("invalid incremental source\n"));
5086 usage(B_FALSE);
5091 if (flags.replicate && fromname == NULL)
5092 flags.doall = B_TRUE;
5094 err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO,
5095 excludes.count > 0 ? zfs_do_send_exclude : NULL,
5096 &excludes, flags.verbosity >= 3 ? &dbgnv : NULL);
5098 if (flags.verbosity >= 3 && dbgnv != NULL) {
5100 * dump_nvlist prints to stdout, but that's been
5101 * redirected to a file. Make it print to stderr
5102 * instead.
5104 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
5105 dump_nvlist(dbgnv, 0);
5106 nvlist_free(dbgnv);
5109 zfs_close(zhp);
5110 free(excludes.list);
5111 return (err != 0);
5115 * Restore a backup stream from stdin.
5117 static int
5118 zfs_do_receive(int argc, char **argv)
5120 int c, err = 0;
5121 recvflags_t flags = { 0 };
5122 boolean_t abort_resumable = B_FALSE;
5123 nvlist_t *props;
5125 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
5126 nomem();
5128 /* check options */
5129 while ((c = getopt(argc, argv, ":o:x:dehMnuvFsAc")) != -1) {
5130 switch (c) {
5131 case 'o':
5132 if (!parseprop(props, optarg)) {
5133 nvlist_free(props);
5134 usage(B_FALSE);
5136 break;
5137 case 'x':
5138 if (!parsepropname(props, optarg)) {
5139 nvlist_free(props);
5140 usage(B_FALSE);
5142 break;
5143 case 'd':
5144 if (flags.istail) {
5145 (void) fprintf(stderr, gettext("invalid option "
5146 "combination: -d and -e are mutually "
5147 "exclusive\n"));
5148 usage(B_FALSE);
5150 flags.isprefix = B_TRUE;
5151 break;
5152 case 'e':
5153 if (flags.isprefix) {
5154 (void) fprintf(stderr, gettext("invalid option "
5155 "combination: -d and -e are mutually "
5156 "exclusive\n"));
5157 usage(B_FALSE);
5159 flags.istail = B_TRUE;
5160 break;
5161 case 'h':
5162 flags.skipholds = B_TRUE;
5163 break;
5164 case 'M':
5165 flags.forceunmount = B_TRUE;
5166 break;
5167 case 'n':
5168 flags.dryrun = B_TRUE;
5169 break;
5170 case 'u':
5171 flags.nomount = B_TRUE;
5172 break;
5173 case 'v':
5174 flags.verbose = B_TRUE;
5175 break;
5176 case 's':
5177 flags.resumable = B_TRUE;
5178 break;
5179 case 'F':
5180 flags.force = B_TRUE;
5181 break;
5182 case 'A':
5183 abort_resumable = B_TRUE;
5184 break;
5185 case 'c':
5186 flags.heal = B_TRUE;
5187 break;
5188 case ':':
5189 (void) fprintf(stderr, gettext("missing argument for "
5190 "'%c' option\n"), optopt);
5191 usage(B_FALSE);
5192 break;
5193 case '?':
5194 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5195 optopt);
5196 usage(B_FALSE);
5200 argc -= optind;
5201 argv += optind;
5203 /* zfs recv -e (use "tail" name) implies -d (remove dataset "head") */
5204 if (flags.istail)
5205 flags.isprefix = B_TRUE;
5207 /* check number of arguments */
5208 if (argc < 1) {
5209 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
5210 usage(B_FALSE);
5212 if (argc > 1) {
5213 (void) fprintf(stderr, gettext("too many arguments\n"));
5214 usage(B_FALSE);
5217 if (abort_resumable) {
5218 if (flags.isprefix || flags.istail || flags.dryrun ||
5219 flags.resumable || flags.nomount) {
5220 (void) fprintf(stderr, gettext("invalid option\n"));
5221 usage(B_FALSE);
5224 char namebuf[ZFS_MAX_DATASET_NAME_LEN];
5225 (void) snprintf(namebuf, sizeof (namebuf),
5226 "%s/%%recv", argv[0]);
5228 if (zfs_dataset_exists(g_zfs, namebuf,
5229 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) {
5230 zfs_handle_t *zhp = zfs_open(g_zfs,
5231 namebuf, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5232 if (zhp == NULL) {
5233 nvlist_free(props);
5234 return (1);
5236 err = zfs_destroy(zhp, B_FALSE);
5237 zfs_close(zhp);
5238 } else {
5239 zfs_handle_t *zhp = zfs_open(g_zfs,
5240 argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5241 if (zhp == NULL)
5242 usage(B_FALSE);
5243 if (!zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) ||
5244 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
5245 NULL, 0, NULL, NULL, 0, B_TRUE) == -1) {
5246 (void) fprintf(stderr,
5247 gettext("'%s' does not have any "
5248 "resumable receive state to abort\n"),
5249 argv[0]);
5250 nvlist_free(props);
5251 zfs_close(zhp);
5252 return (1);
5254 err = zfs_destroy(zhp, B_FALSE);
5255 zfs_close(zhp);
5257 nvlist_free(props);
5258 return (err != 0);
5261 if (isatty(STDIN_FILENO)) {
5262 (void) fprintf(stderr,
5263 gettext("Error: Backup stream can not be read "
5264 "from a terminal.\n"
5265 "You must redirect standard input.\n"));
5266 nvlist_free(props);
5267 return (1);
5269 err = zfs_receive(g_zfs, argv[0], props, &flags, STDIN_FILENO, NULL);
5270 nvlist_free(props);
5272 return (err != 0);
5276 * allow/unallow stuff
5278 /* copied from zfs/sys/dsl_deleg.h */
5279 #define ZFS_DELEG_PERM_CREATE "create"
5280 #define ZFS_DELEG_PERM_DESTROY "destroy"
5281 #define ZFS_DELEG_PERM_SNAPSHOT "snapshot"
5282 #define ZFS_DELEG_PERM_ROLLBACK "rollback"
5283 #define ZFS_DELEG_PERM_CLONE "clone"
5284 #define ZFS_DELEG_PERM_PROMOTE "promote"
5285 #define ZFS_DELEG_PERM_RENAME "rename"
5286 #define ZFS_DELEG_PERM_MOUNT "mount"
5287 #define ZFS_DELEG_PERM_SHARE "share"
5288 #define ZFS_DELEG_PERM_SEND "send"
5289 #define ZFS_DELEG_PERM_RECEIVE "receive"
5290 #define ZFS_DELEG_PERM_ALLOW "allow"
5291 #define ZFS_DELEG_PERM_USERPROP "userprop"
5292 #define ZFS_DELEG_PERM_VSCAN "vscan" /* ??? */
5293 #define ZFS_DELEG_PERM_USERQUOTA "userquota"
5294 #define ZFS_DELEG_PERM_GROUPQUOTA "groupquota"
5295 #define ZFS_DELEG_PERM_USERUSED "userused"
5296 #define ZFS_DELEG_PERM_GROUPUSED "groupused"
5297 #define ZFS_DELEG_PERM_USEROBJQUOTA "userobjquota"
5298 #define ZFS_DELEG_PERM_GROUPOBJQUOTA "groupobjquota"
5299 #define ZFS_DELEG_PERM_USEROBJUSED "userobjused"
5300 #define ZFS_DELEG_PERM_GROUPOBJUSED "groupobjused"
5302 #define ZFS_DELEG_PERM_HOLD "hold"
5303 #define ZFS_DELEG_PERM_RELEASE "release"
5304 #define ZFS_DELEG_PERM_DIFF "diff"
5305 #define ZFS_DELEG_PERM_BOOKMARK "bookmark"
5306 #define ZFS_DELEG_PERM_LOAD_KEY "load-key"
5307 #define ZFS_DELEG_PERM_CHANGE_KEY "change-key"
5309 #define ZFS_DELEG_PERM_PROJECTUSED "projectused"
5310 #define ZFS_DELEG_PERM_PROJECTQUOTA "projectquota"
5311 #define ZFS_DELEG_PERM_PROJECTOBJUSED "projectobjused"
5312 #define ZFS_DELEG_PERM_PROJECTOBJQUOTA "projectobjquota"
5314 #define ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
5316 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
5317 { ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
5318 { ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
5319 { ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
5320 { ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
5321 { ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
5322 { ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
5323 { ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
5324 { ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
5325 { ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
5326 { ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
5327 { ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
5328 { ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
5329 { ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
5330 { ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
5331 { ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
5332 { ZFS_DELEG_PERM_BOOKMARK, ZFS_DELEG_NOTE_BOOKMARK },
5333 { ZFS_DELEG_PERM_LOAD_KEY, ZFS_DELEG_NOTE_LOAD_KEY },
5334 { ZFS_DELEG_PERM_CHANGE_KEY, ZFS_DELEG_NOTE_CHANGE_KEY },
5336 { ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
5337 { ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
5338 { ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
5339 { ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
5340 { ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
5341 { ZFS_DELEG_PERM_USEROBJQUOTA, ZFS_DELEG_NOTE_USEROBJQUOTA },
5342 { ZFS_DELEG_PERM_USEROBJUSED, ZFS_DELEG_NOTE_USEROBJUSED },
5343 { ZFS_DELEG_PERM_GROUPOBJQUOTA, ZFS_DELEG_NOTE_GROUPOBJQUOTA },
5344 { ZFS_DELEG_PERM_GROUPOBJUSED, ZFS_DELEG_NOTE_GROUPOBJUSED },
5345 { ZFS_DELEG_PERM_PROJECTUSED, ZFS_DELEG_NOTE_PROJECTUSED },
5346 { ZFS_DELEG_PERM_PROJECTQUOTA, ZFS_DELEG_NOTE_PROJECTQUOTA },
5347 { ZFS_DELEG_PERM_PROJECTOBJUSED, ZFS_DELEG_NOTE_PROJECTOBJUSED },
5348 { ZFS_DELEG_PERM_PROJECTOBJQUOTA, ZFS_DELEG_NOTE_PROJECTOBJQUOTA },
5349 { NULL, ZFS_DELEG_NOTE_NONE }
5352 /* permission structure */
5353 typedef struct deleg_perm {
5354 zfs_deleg_who_type_t dp_who_type;
5355 const char *dp_name;
5356 boolean_t dp_local;
5357 boolean_t dp_descend;
5358 } deleg_perm_t;
5360 /* */
5361 typedef struct deleg_perm_node {
5362 deleg_perm_t dpn_perm;
5364 uu_avl_node_t dpn_avl_node;
5365 } deleg_perm_node_t;
5367 typedef struct fs_perm fs_perm_t;
5369 /* permissions set */
5370 typedef struct who_perm {
5371 zfs_deleg_who_type_t who_type;
5372 const char *who_name; /* id */
5373 char who_ug_name[256]; /* user/group name */
5374 fs_perm_t *who_fsperm; /* uplink */
5376 uu_avl_t *who_deleg_perm_avl; /* permissions */
5377 } who_perm_t;
5379 /* */
5380 typedef struct who_perm_node {
5381 who_perm_t who_perm;
5382 uu_avl_node_t who_avl_node;
5383 } who_perm_node_t;
5385 typedef struct fs_perm_set fs_perm_set_t;
5386 /* fs permissions */
5387 struct fs_perm {
5388 const char *fsp_name;
5390 uu_avl_t *fsp_sc_avl; /* sets,create */
5391 uu_avl_t *fsp_uge_avl; /* user,group,everyone */
5393 fs_perm_set_t *fsp_set; /* uplink */
5396 /* */
5397 typedef struct fs_perm_node {
5398 fs_perm_t fspn_fsperm;
5399 uu_avl_t *fspn_avl;
5401 uu_list_node_t fspn_list_node;
5402 } fs_perm_node_t;
5404 /* top level structure */
5405 struct fs_perm_set {
5406 uu_list_pool_t *fsps_list_pool;
5407 uu_list_t *fsps_list; /* list of fs_perms */
5409 uu_avl_pool_t *fsps_named_set_avl_pool;
5410 uu_avl_pool_t *fsps_who_perm_avl_pool;
5411 uu_avl_pool_t *fsps_deleg_perm_avl_pool;
5414 static inline const char *
5415 deleg_perm_type(zfs_deleg_note_t note)
5417 /* subcommands */
5418 switch (note) {
5419 /* SUBCOMMANDS */
5420 /* OTHER */
5421 case ZFS_DELEG_NOTE_GROUPQUOTA:
5422 case ZFS_DELEG_NOTE_GROUPUSED:
5423 case ZFS_DELEG_NOTE_USERPROP:
5424 case ZFS_DELEG_NOTE_USERQUOTA:
5425 case ZFS_DELEG_NOTE_USERUSED:
5426 case ZFS_DELEG_NOTE_USEROBJQUOTA:
5427 case ZFS_DELEG_NOTE_USEROBJUSED:
5428 case ZFS_DELEG_NOTE_GROUPOBJQUOTA:
5429 case ZFS_DELEG_NOTE_GROUPOBJUSED:
5430 case ZFS_DELEG_NOTE_PROJECTUSED:
5431 case ZFS_DELEG_NOTE_PROJECTQUOTA:
5432 case ZFS_DELEG_NOTE_PROJECTOBJUSED:
5433 case ZFS_DELEG_NOTE_PROJECTOBJQUOTA:
5434 /* other */
5435 return (gettext("other"));
5436 default:
5437 return (gettext("subcommand"));
5441 static int
5442 who_type2weight(zfs_deleg_who_type_t who_type)
5444 int res;
5445 switch (who_type) {
5446 case ZFS_DELEG_NAMED_SET_SETS:
5447 case ZFS_DELEG_NAMED_SET:
5448 res = 0;
5449 break;
5450 case ZFS_DELEG_CREATE_SETS:
5451 case ZFS_DELEG_CREATE:
5452 res = 1;
5453 break;
5454 case ZFS_DELEG_USER_SETS:
5455 case ZFS_DELEG_USER:
5456 res = 2;
5457 break;
5458 case ZFS_DELEG_GROUP_SETS:
5459 case ZFS_DELEG_GROUP:
5460 res = 3;
5461 break;
5462 case ZFS_DELEG_EVERYONE_SETS:
5463 case ZFS_DELEG_EVERYONE:
5464 res = 4;
5465 break;
5466 default:
5467 res = -1;
5470 return (res);
5473 static int
5474 who_perm_compare(const void *larg, const void *rarg, void *unused)
5476 (void) unused;
5477 const who_perm_node_t *l = larg;
5478 const who_perm_node_t *r = rarg;
5479 zfs_deleg_who_type_t ltype = l->who_perm.who_type;
5480 zfs_deleg_who_type_t rtype = r->who_perm.who_type;
5481 int lweight = who_type2weight(ltype);
5482 int rweight = who_type2weight(rtype);
5483 int res = lweight - rweight;
5484 if (res == 0)
5485 res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
5486 ZFS_MAX_DELEG_NAME-1);
5488 if (res == 0)
5489 return (0);
5490 if (res > 0)
5491 return (1);
5492 else
5493 return (-1);
5496 static int
5497 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
5499 (void) unused;
5500 const deleg_perm_node_t *l = larg;
5501 const deleg_perm_node_t *r = rarg;
5502 int res = strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
5503 ZFS_MAX_DELEG_NAME-1);
5505 if (res == 0)
5506 return (0);
5508 if (res > 0)
5509 return (1);
5510 else
5511 return (-1);
5514 static inline void
5515 fs_perm_set_init(fs_perm_set_t *fspset)
5517 memset(fspset, 0, sizeof (fs_perm_set_t));
5519 if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
5520 sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
5521 NULL, UU_DEFAULT)) == NULL)
5522 nomem();
5523 if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
5524 UU_DEFAULT)) == NULL)
5525 nomem();
5527 if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
5528 "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
5529 who_perm_node_t, who_avl_node), who_perm_compare,
5530 UU_DEFAULT)) == NULL)
5531 nomem();
5533 if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
5534 "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
5535 who_perm_node_t, who_avl_node), who_perm_compare,
5536 UU_DEFAULT)) == NULL)
5537 nomem();
5539 if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
5540 "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
5541 deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
5542 == NULL)
5543 nomem();
5546 static inline void fs_perm_fini(fs_perm_t *);
5547 static inline void who_perm_fini(who_perm_t *);
5549 static inline void
5550 fs_perm_set_fini(fs_perm_set_t *fspset)
5552 fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
5554 while (node != NULL) {
5555 fs_perm_node_t *next_node =
5556 uu_list_next(fspset->fsps_list, node);
5557 fs_perm_t *fsperm = &node->fspn_fsperm;
5558 fs_perm_fini(fsperm);
5559 uu_list_remove(fspset->fsps_list, node);
5560 free(node);
5561 node = next_node;
5564 uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
5565 uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
5566 uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
5569 static inline void
5570 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
5571 const char *name)
5573 deleg_perm->dp_who_type = type;
5574 deleg_perm->dp_name = name;
5577 static inline void
5578 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
5579 zfs_deleg_who_type_t type, const char *name)
5581 uu_avl_pool_t *pool;
5582 pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
5584 memset(who_perm, 0, sizeof (who_perm_t));
5586 if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
5587 UU_DEFAULT)) == NULL)
5588 nomem();
5590 who_perm->who_type = type;
5591 who_perm->who_name = name;
5592 who_perm->who_fsperm = fsperm;
5595 static inline void
5596 who_perm_fini(who_perm_t *who_perm)
5598 deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
5600 while (node != NULL) {
5601 deleg_perm_node_t *next_node =
5602 uu_avl_next(who_perm->who_deleg_perm_avl, node);
5604 uu_avl_remove(who_perm->who_deleg_perm_avl, node);
5605 free(node);
5606 node = next_node;
5609 uu_avl_destroy(who_perm->who_deleg_perm_avl);
5612 static inline void
5613 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
5615 uu_avl_pool_t *nset_pool = fspset->fsps_named_set_avl_pool;
5616 uu_avl_pool_t *who_pool = fspset->fsps_who_perm_avl_pool;
5618 memset(fsperm, 0, sizeof (fs_perm_t));
5620 if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
5621 == NULL)
5622 nomem();
5624 if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
5625 == NULL)
5626 nomem();
5628 fsperm->fsp_set = fspset;
5629 fsperm->fsp_name = fsname;
5632 static inline void
5633 fs_perm_fini(fs_perm_t *fsperm)
5635 who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
5636 while (node != NULL) {
5637 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
5638 node);
5639 who_perm_t *who_perm = &node->who_perm;
5640 who_perm_fini(who_perm);
5641 uu_avl_remove(fsperm->fsp_sc_avl, node);
5642 free(node);
5643 node = next_node;
5646 node = uu_avl_first(fsperm->fsp_uge_avl);
5647 while (node != NULL) {
5648 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
5649 node);
5650 who_perm_t *who_perm = &node->who_perm;
5651 who_perm_fini(who_perm);
5652 uu_avl_remove(fsperm->fsp_uge_avl, node);
5653 free(node);
5654 node = next_node;
5657 uu_avl_destroy(fsperm->fsp_sc_avl);
5658 uu_avl_destroy(fsperm->fsp_uge_avl);
5661 static void
5662 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
5663 zfs_deleg_who_type_t who_type, const char *name, char locality)
5665 uu_avl_index_t idx = 0;
5667 deleg_perm_node_t *found_node = NULL;
5668 deleg_perm_t *deleg_perm = &node->dpn_perm;
5670 deleg_perm_init(deleg_perm, who_type, name);
5672 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
5673 == NULL)
5674 uu_avl_insert(avl, node, idx);
5675 else {
5676 node = found_node;
5677 deleg_perm = &node->dpn_perm;
5681 switch (locality) {
5682 case ZFS_DELEG_LOCAL:
5683 deleg_perm->dp_local = B_TRUE;
5684 break;
5685 case ZFS_DELEG_DESCENDENT:
5686 deleg_perm->dp_descend = B_TRUE;
5687 break;
5688 case ZFS_DELEG_NA:
5689 break;
5690 default:
5691 assert(B_FALSE); /* invalid locality */
5695 static inline int
5696 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
5698 nvpair_t *nvp = NULL;
5699 fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
5700 uu_avl_t *avl = who_perm->who_deleg_perm_avl;
5701 zfs_deleg_who_type_t who_type = who_perm->who_type;
5703 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5704 const char *name = nvpair_name(nvp);
5705 data_type_t type = nvpair_type(nvp);
5706 uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
5707 deleg_perm_node_t *node =
5708 safe_malloc(sizeof (deleg_perm_node_t));
5710 VERIFY(type == DATA_TYPE_BOOLEAN);
5712 uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
5713 set_deleg_perm_node(avl, node, who_type, name, locality);
5716 return (0);
5719 static inline int
5720 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
5722 nvpair_t *nvp = NULL;
5723 fs_perm_set_t *fspset = fsperm->fsp_set;
5725 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5726 nvlist_t *nvl2 = NULL;
5727 const char *name = nvpair_name(nvp);
5728 uu_avl_t *avl = NULL;
5729 uu_avl_pool_t *avl_pool = NULL;
5730 zfs_deleg_who_type_t perm_type = name[0];
5731 char perm_locality = name[1];
5732 const char *perm_name = name + 3;
5733 who_perm_t *who_perm = NULL;
5735 assert('$' == name[2]);
5737 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
5738 return (-1);
5740 switch (perm_type) {
5741 case ZFS_DELEG_CREATE:
5742 case ZFS_DELEG_CREATE_SETS:
5743 case ZFS_DELEG_NAMED_SET:
5744 case ZFS_DELEG_NAMED_SET_SETS:
5745 avl_pool = fspset->fsps_named_set_avl_pool;
5746 avl = fsperm->fsp_sc_avl;
5747 break;
5748 case ZFS_DELEG_USER:
5749 case ZFS_DELEG_USER_SETS:
5750 case ZFS_DELEG_GROUP:
5751 case ZFS_DELEG_GROUP_SETS:
5752 case ZFS_DELEG_EVERYONE:
5753 case ZFS_DELEG_EVERYONE_SETS:
5754 avl_pool = fspset->fsps_who_perm_avl_pool;
5755 avl = fsperm->fsp_uge_avl;
5756 break;
5758 default:
5759 assert(!"unhandled zfs_deleg_who_type_t");
5762 who_perm_node_t *found_node = NULL;
5763 who_perm_node_t *node = safe_malloc(
5764 sizeof (who_perm_node_t));
5765 who_perm = &node->who_perm;
5766 uu_avl_index_t idx = 0;
5768 uu_avl_node_init(node, &node->who_avl_node, avl_pool);
5769 who_perm_init(who_perm, fsperm, perm_type, perm_name);
5771 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
5772 == NULL) {
5773 if (avl == fsperm->fsp_uge_avl) {
5774 uid_t rid = 0;
5775 struct passwd *p = NULL;
5776 struct group *g = NULL;
5777 const char *nice_name = NULL;
5779 switch (perm_type) {
5780 case ZFS_DELEG_USER_SETS:
5781 case ZFS_DELEG_USER:
5782 rid = atoi(perm_name);
5783 p = getpwuid(rid);
5784 if (p)
5785 nice_name = p->pw_name;
5786 break;
5787 case ZFS_DELEG_GROUP_SETS:
5788 case ZFS_DELEG_GROUP:
5789 rid = atoi(perm_name);
5790 g = getgrgid(rid);
5791 if (g)
5792 nice_name = g->gr_name;
5793 break;
5795 default:
5796 break;
5799 if (nice_name != NULL) {
5800 (void) strlcpy(
5801 node->who_perm.who_ug_name,
5802 nice_name, 256);
5803 } else {
5804 /* User or group unknown */
5805 (void) snprintf(
5806 node->who_perm.who_ug_name,
5807 sizeof (node->who_perm.who_ug_name),
5808 "(unknown: %d)", rid);
5812 uu_avl_insert(avl, node, idx);
5813 } else {
5814 node = found_node;
5815 who_perm = &node->who_perm;
5818 assert(who_perm != NULL);
5819 (void) parse_who_perm(who_perm, nvl2, perm_locality);
5822 return (0);
5825 static inline int
5826 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
5828 nvpair_t *nvp = NULL;
5829 uu_avl_index_t idx = 0;
5831 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5832 nvlist_t *nvl2 = NULL;
5833 const char *fsname = nvpair_name(nvp);
5834 data_type_t type = nvpair_type(nvp);
5835 fs_perm_t *fsperm = NULL;
5836 fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
5838 fsperm = &node->fspn_fsperm;
5840 VERIFY(DATA_TYPE_NVLIST == type);
5842 uu_list_node_init(node, &node->fspn_list_node,
5843 fspset->fsps_list_pool);
5845 idx = uu_list_numnodes(fspset->fsps_list);
5846 fs_perm_init(fsperm, fspset, fsname);
5848 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
5849 return (-1);
5851 (void) parse_fs_perm(fsperm, nvl2);
5853 uu_list_insert(fspset->fsps_list, node, idx);
5856 return (0);
5859 static inline const char *
5860 deleg_perm_comment(zfs_deleg_note_t note)
5862 const char *str = "";
5864 /* subcommands */
5865 switch (note) {
5866 /* SUBCOMMANDS */
5867 case ZFS_DELEG_NOTE_ALLOW:
5868 str = gettext("Must also have the permission that is being"
5869 "\n\t\t\t\tallowed");
5870 break;
5871 case ZFS_DELEG_NOTE_CLONE:
5872 str = gettext("Must also have the 'create' ability and 'mount'"
5873 "\n\t\t\t\tability in the origin file system");
5874 break;
5875 case ZFS_DELEG_NOTE_CREATE:
5876 str = gettext("Must also have the 'mount' ability");
5877 break;
5878 case ZFS_DELEG_NOTE_DESTROY:
5879 str = gettext("Must also have the 'mount' ability");
5880 break;
5881 case ZFS_DELEG_NOTE_DIFF:
5882 str = gettext("Allows lookup of paths within a dataset;"
5883 "\n\t\t\t\tgiven an object number. Ordinary users need this"
5884 "\n\t\t\t\tin order to use zfs diff");
5885 break;
5886 case ZFS_DELEG_NOTE_HOLD:
5887 str = gettext("Allows adding a user hold to a snapshot");
5888 break;
5889 case ZFS_DELEG_NOTE_MOUNT:
5890 str = gettext("Allows mount/umount of ZFS datasets");
5891 break;
5892 case ZFS_DELEG_NOTE_PROMOTE:
5893 str = gettext("Must also have the 'mount'\n\t\t\t\tand"
5894 " 'promote' ability in the origin file system");
5895 break;
5896 case ZFS_DELEG_NOTE_RECEIVE:
5897 str = gettext("Must also have the 'mount' and 'create'"
5898 " ability");
5899 break;
5900 case ZFS_DELEG_NOTE_RELEASE:
5901 str = gettext("Allows releasing a user hold which\n\t\t\t\t"
5902 "might destroy the snapshot");
5903 break;
5904 case ZFS_DELEG_NOTE_RENAME:
5905 str = gettext("Must also have the 'mount' and 'create'"
5906 "\n\t\t\t\tability in the new parent");
5907 break;
5908 case ZFS_DELEG_NOTE_ROLLBACK:
5909 str = gettext("");
5910 break;
5911 case ZFS_DELEG_NOTE_SEND:
5912 str = gettext("");
5913 break;
5914 case ZFS_DELEG_NOTE_SHARE:
5915 str = gettext("Allows sharing file systems over NFS or SMB"
5916 "\n\t\t\t\tprotocols");
5917 break;
5918 case ZFS_DELEG_NOTE_SNAPSHOT:
5919 str = gettext("");
5920 break;
5921 case ZFS_DELEG_NOTE_LOAD_KEY:
5922 str = gettext("Allows loading or unloading an encryption key");
5923 break;
5924 case ZFS_DELEG_NOTE_CHANGE_KEY:
5925 str = gettext("Allows changing or adding an encryption key");
5926 break;
5928 * case ZFS_DELEG_NOTE_VSCAN:
5929 * str = gettext("");
5930 * break;
5932 /* OTHER */
5933 case ZFS_DELEG_NOTE_GROUPQUOTA:
5934 str = gettext("Allows accessing any groupquota@... property");
5935 break;
5936 case ZFS_DELEG_NOTE_GROUPUSED:
5937 str = gettext("Allows reading any groupused@... property");
5938 break;
5939 case ZFS_DELEG_NOTE_USERPROP:
5940 str = gettext("Allows changing any user property");
5941 break;
5942 case ZFS_DELEG_NOTE_USERQUOTA:
5943 str = gettext("Allows accessing any userquota@... property");
5944 break;
5945 case ZFS_DELEG_NOTE_USERUSED:
5946 str = gettext("Allows reading any userused@... property");
5947 break;
5948 case ZFS_DELEG_NOTE_USEROBJQUOTA:
5949 str = gettext("Allows accessing any userobjquota@... property");
5950 break;
5951 case ZFS_DELEG_NOTE_GROUPOBJQUOTA:
5952 str = gettext("Allows accessing any \n\t\t\t\t"
5953 "groupobjquota@... property");
5954 break;
5955 case ZFS_DELEG_NOTE_GROUPOBJUSED:
5956 str = gettext("Allows reading any groupobjused@... property");
5957 break;
5958 case ZFS_DELEG_NOTE_USEROBJUSED:
5959 str = gettext("Allows reading any userobjused@... property");
5960 break;
5961 case ZFS_DELEG_NOTE_PROJECTQUOTA:
5962 str = gettext("Allows accessing any projectquota@... property");
5963 break;
5964 case ZFS_DELEG_NOTE_PROJECTOBJQUOTA:
5965 str = gettext("Allows accessing any \n\t\t\t\t"
5966 "projectobjquota@... property");
5967 break;
5968 case ZFS_DELEG_NOTE_PROJECTUSED:
5969 str = gettext("Allows reading any projectused@... property");
5970 break;
5971 case ZFS_DELEG_NOTE_PROJECTOBJUSED:
5972 str = gettext("Allows accessing any \n\t\t\t\t"
5973 "projectobjused@... property");
5974 break;
5975 /* other */
5976 default:
5977 str = "";
5980 return (str);
5983 struct allow_opts {
5984 boolean_t local;
5985 boolean_t descend;
5986 boolean_t user;
5987 boolean_t group;
5988 boolean_t everyone;
5989 boolean_t create;
5990 boolean_t set;
5991 boolean_t recursive; /* unallow only */
5992 boolean_t prt_usage;
5994 boolean_t prt_perms;
5995 char *who;
5996 char *perms;
5997 const char *dataset;
6000 static inline int
6001 prop_cmp(const void *a, const void *b)
6003 const char *str1 = *(const char **)a;
6004 const char *str2 = *(const char **)b;
6005 return (strcmp(str1, str2));
6008 static void
6009 allow_usage(boolean_t un, boolean_t requested, const char *msg)
6011 const char *opt_desc[] = {
6012 "-h", gettext("show this help message and exit"),
6013 "-l", gettext("set permission locally"),
6014 "-d", gettext("set permission for descents"),
6015 "-u", gettext("set permission for user"),
6016 "-g", gettext("set permission for group"),
6017 "-e", gettext("set permission for everyone"),
6018 "-c", gettext("set create time permission"),
6019 "-s", gettext("define permission set"),
6020 /* unallow only */
6021 "-r", gettext("remove permissions recursively"),
6023 size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
6024 size_t allow_size = unallow_size - 2;
6025 const char *props[ZFS_NUM_PROPS];
6026 int i;
6027 size_t count = 0;
6028 FILE *fp = requested ? stdout : stderr;
6029 zprop_desc_t *pdtbl = zfs_prop_get_table();
6030 const char *fmt = gettext("%-16s %-14s\t%s\n");
6032 (void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
6033 HELP_ALLOW));
6034 (void) fprintf(fp, gettext("Options:\n"));
6035 for (i = 0; i < (un ? unallow_size : allow_size); i += 2) {
6036 const char *opt = opt_desc[i];
6037 const char *optdsc = opt_desc[i + 1];
6038 (void) fprintf(fp, gettext(" %-10s %s\n"), opt, optdsc);
6041 (void) fprintf(fp, gettext("\nThe following permissions are "
6042 "supported:\n\n"));
6043 (void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
6044 gettext("NOTES"));
6045 for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
6046 const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
6047 zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
6048 const char *perm_type = deleg_perm_type(perm_note);
6049 const char *perm_comment = deleg_perm_comment(perm_note);
6050 (void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
6053 for (i = 0; i < ZFS_NUM_PROPS; i++) {
6054 zprop_desc_t *pd = &pdtbl[i];
6055 if (pd->pd_visible != B_TRUE)
6056 continue;
6058 if (pd->pd_attr == PROP_READONLY)
6059 continue;
6061 props[count++] = pd->pd_name;
6063 props[count] = NULL;
6065 qsort(props, count, sizeof (char *), prop_cmp);
6067 for (i = 0; i < count; i++)
6068 (void) fprintf(fp, fmt, props[i], gettext("property"), "");
6070 if (msg != NULL)
6071 (void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
6073 exit(requested ? 0 : 2);
6076 static inline const char *
6077 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
6078 char **permsp)
6080 if (un && argc == expected_argc - 1)
6081 *permsp = NULL;
6082 else if (argc == expected_argc)
6083 *permsp = argv[argc - 2];
6084 else
6085 allow_usage(un, B_FALSE,
6086 gettext("wrong number of parameters\n"));
6088 return (argv[argc - 1]);
6091 static void
6092 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
6094 int uge_sum = opts->user + opts->group + opts->everyone;
6095 int csuge_sum = opts->create + opts->set + uge_sum;
6096 int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
6097 int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
6099 if (uge_sum > 1)
6100 allow_usage(un, B_FALSE,
6101 gettext("-u, -g, and -e are mutually exclusive\n"));
6103 if (opts->prt_usage) {
6104 if (argc == 0 && all_sum == 0)
6105 allow_usage(un, B_TRUE, NULL);
6106 else
6107 usage(B_FALSE);
6110 if (opts->set) {
6111 if (csuge_sum > 1)
6112 allow_usage(un, B_FALSE,
6113 gettext("invalid options combined with -s\n"));
6115 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
6116 if (argv[0][0] != '@')
6117 allow_usage(un, B_FALSE,
6118 gettext("invalid set name: missing '@' prefix\n"));
6119 opts->who = argv[0];
6120 } else if (opts->create) {
6121 if (ldcsuge_sum > 1)
6122 allow_usage(un, B_FALSE,
6123 gettext("invalid options combined with -c\n"));
6124 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
6125 } else if (opts->everyone) {
6126 if (csuge_sum > 1)
6127 allow_usage(un, B_FALSE,
6128 gettext("invalid options combined with -e\n"));
6129 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
6130 } else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
6131 == 0) {
6132 opts->everyone = B_TRUE;
6133 argc--;
6134 argv++;
6135 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
6136 } else if (argc == 1 && !un) {
6137 opts->prt_perms = B_TRUE;
6138 opts->dataset = argv[argc-1];
6139 } else {
6140 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
6141 opts->who = argv[0];
6144 if (!opts->local && !opts->descend) {
6145 opts->local = B_TRUE;
6146 opts->descend = B_TRUE;
6150 static void
6151 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
6152 const char *who, char *perms, nvlist_t *top_nvl)
6154 int i;
6155 char ld[2] = { '\0', '\0' };
6156 char who_buf[MAXNAMELEN + 32];
6157 char base_type = '\0';
6158 char set_type = '\0';
6159 nvlist_t *base_nvl = NULL;
6160 nvlist_t *set_nvl = NULL;
6161 nvlist_t *nvl;
6163 if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
6164 nomem();
6165 if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) != 0)
6166 nomem();
6168 switch (type) {
6169 case ZFS_DELEG_NAMED_SET_SETS:
6170 case ZFS_DELEG_NAMED_SET:
6171 set_type = ZFS_DELEG_NAMED_SET_SETS;
6172 base_type = ZFS_DELEG_NAMED_SET;
6173 ld[0] = ZFS_DELEG_NA;
6174 break;
6175 case ZFS_DELEG_CREATE_SETS:
6176 case ZFS_DELEG_CREATE:
6177 set_type = ZFS_DELEG_CREATE_SETS;
6178 base_type = ZFS_DELEG_CREATE;
6179 ld[0] = ZFS_DELEG_NA;
6180 break;
6181 case ZFS_DELEG_USER_SETS:
6182 case ZFS_DELEG_USER:
6183 set_type = ZFS_DELEG_USER_SETS;
6184 base_type = ZFS_DELEG_USER;
6185 if (local)
6186 ld[0] = ZFS_DELEG_LOCAL;
6187 if (descend)
6188 ld[1] = ZFS_DELEG_DESCENDENT;
6189 break;
6190 case ZFS_DELEG_GROUP_SETS:
6191 case ZFS_DELEG_GROUP:
6192 set_type = ZFS_DELEG_GROUP_SETS;
6193 base_type = ZFS_DELEG_GROUP;
6194 if (local)
6195 ld[0] = ZFS_DELEG_LOCAL;
6196 if (descend)
6197 ld[1] = ZFS_DELEG_DESCENDENT;
6198 break;
6199 case ZFS_DELEG_EVERYONE_SETS:
6200 case ZFS_DELEG_EVERYONE:
6201 set_type = ZFS_DELEG_EVERYONE_SETS;
6202 base_type = ZFS_DELEG_EVERYONE;
6203 if (local)
6204 ld[0] = ZFS_DELEG_LOCAL;
6205 if (descend)
6206 ld[1] = ZFS_DELEG_DESCENDENT;
6207 break;
6209 default:
6210 assert(set_type != '\0' && base_type != '\0');
6213 if (perms != NULL) {
6214 char *curr = perms;
6215 char *end = curr + strlen(perms);
6217 while (curr < end) {
6218 char *delim = strchr(curr, ',');
6219 if (delim == NULL)
6220 delim = end;
6221 else
6222 *delim = '\0';
6224 if (curr[0] == '@')
6225 nvl = set_nvl;
6226 else
6227 nvl = base_nvl;
6229 (void) nvlist_add_boolean(nvl, curr);
6230 if (delim != end)
6231 *delim = ',';
6232 curr = delim + 1;
6235 for (i = 0; i < 2; i++) {
6236 char locality = ld[i];
6237 if (locality == 0)
6238 continue;
6240 if (!nvlist_empty(base_nvl)) {
6241 if (who != NULL)
6242 (void) snprintf(who_buf,
6243 sizeof (who_buf), "%c%c$%s",
6244 base_type, locality, who);
6245 else
6246 (void) snprintf(who_buf,
6247 sizeof (who_buf), "%c%c$",
6248 base_type, locality);
6250 (void) nvlist_add_nvlist(top_nvl, who_buf,
6251 base_nvl);
6255 if (!nvlist_empty(set_nvl)) {
6256 if (who != NULL)
6257 (void) snprintf(who_buf,
6258 sizeof (who_buf), "%c%c$%s",
6259 set_type, locality, who);
6260 else
6261 (void) snprintf(who_buf,
6262 sizeof (who_buf), "%c%c$",
6263 set_type, locality);
6265 (void) nvlist_add_nvlist(top_nvl, who_buf,
6266 set_nvl);
6269 } else {
6270 for (i = 0; i < 2; i++) {
6271 char locality = ld[i];
6272 if (locality == 0)
6273 continue;
6275 if (who != NULL)
6276 (void) snprintf(who_buf, sizeof (who_buf),
6277 "%c%c$%s", base_type, locality, who);
6278 else
6279 (void) snprintf(who_buf, sizeof (who_buf),
6280 "%c%c$", base_type, locality);
6281 (void) nvlist_add_boolean(top_nvl, who_buf);
6283 if (who != NULL)
6284 (void) snprintf(who_buf, sizeof (who_buf),
6285 "%c%c$%s", set_type, locality, who);
6286 else
6287 (void) snprintf(who_buf, sizeof (who_buf),
6288 "%c%c$", set_type, locality);
6289 (void) nvlist_add_boolean(top_nvl, who_buf);
6294 static int
6295 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
6297 if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
6298 nomem();
6300 if (opts->set) {
6301 store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
6302 opts->descend, opts->who, opts->perms, *nvlp);
6303 } else if (opts->create) {
6304 store_allow_perm(ZFS_DELEG_CREATE, opts->local,
6305 opts->descend, NULL, opts->perms, *nvlp);
6306 } else if (opts->everyone) {
6307 store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
6308 opts->descend, NULL, opts->perms, *nvlp);
6309 } else {
6310 char *curr = opts->who;
6311 char *end = curr + strlen(curr);
6313 while (curr < end) {
6314 const char *who;
6315 zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
6316 char *endch;
6317 char *delim = strchr(curr, ',');
6318 char errbuf[256];
6319 char id[64];
6320 struct passwd *p = NULL;
6321 struct group *g = NULL;
6323 uid_t rid;
6324 if (delim == NULL)
6325 delim = end;
6326 else
6327 *delim = '\0';
6329 rid = (uid_t)strtol(curr, &endch, 0);
6330 if (opts->user) {
6331 who_type = ZFS_DELEG_USER;
6332 if (*endch != '\0')
6333 p = getpwnam(curr);
6334 else
6335 p = getpwuid(rid);
6337 if (p != NULL)
6338 rid = p->pw_uid;
6339 else if (*endch != '\0') {
6340 (void) snprintf(errbuf, sizeof (errbuf),
6341 gettext("invalid user %s\n"), curr);
6342 allow_usage(un, B_TRUE, errbuf);
6344 } else if (opts->group) {
6345 who_type = ZFS_DELEG_GROUP;
6346 if (*endch != '\0')
6347 g = getgrnam(curr);
6348 else
6349 g = getgrgid(rid);
6351 if (g != NULL)
6352 rid = g->gr_gid;
6353 else if (*endch != '\0') {
6354 (void) snprintf(errbuf, sizeof (errbuf),
6355 gettext("invalid group %s\n"),
6356 curr);
6357 allow_usage(un, B_TRUE, errbuf);
6359 } else {
6360 if (*endch != '\0') {
6361 p = getpwnam(curr);
6362 } else {
6363 p = getpwuid(rid);
6366 if (p == NULL) {
6367 if (*endch != '\0') {
6368 g = getgrnam(curr);
6369 } else {
6370 g = getgrgid(rid);
6374 if (p != NULL) {
6375 who_type = ZFS_DELEG_USER;
6376 rid = p->pw_uid;
6377 } else if (g != NULL) {
6378 who_type = ZFS_DELEG_GROUP;
6379 rid = g->gr_gid;
6380 } else {
6381 (void) snprintf(errbuf, sizeof (errbuf),
6382 gettext("invalid user/group %s\n"),
6383 curr);
6384 allow_usage(un, B_TRUE, errbuf);
6388 (void) sprintf(id, "%u", rid);
6389 who = id;
6391 store_allow_perm(who_type, opts->local,
6392 opts->descend, who, opts->perms, *nvlp);
6393 curr = delim + 1;
6397 return (0);
6400 static void
6401 print_set_creat_perms(uu_avl_t *who_avl)
6403 const char *sc_title[] = {
6404 gettext("Permission sets:\n"),
6405 gettext("Create time permissions:\n"),
6406 NULL
6408 who_perm_node_t *who_node = NULL;
6409 int prev_weight = -1;
6411 for (who_node = uu_avl_first(who_avl); who_node != NULL;
6412 who_node = uu_avl_next(who_avl, who_node)) {
6413 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
6414 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
6415 const char *who_name = who_node->who_perm.who_name;
6416 int weight = who_type2weight(who_type);
6417 boolean_t first = B_TRUE;
6418 deleg_perm_node_t *deleg_node;
6420 if (prev_weight != weight) {
6421 (void) printf("%s", sc_title[weight]);
6422 prev_weight = weight;
6425 if (who_name == NULL || strnlen(who_name, 1) == 0)
6426 (void) printf("\t");
6427 else
6428 (void) printf("\t%s ", who_name);
6430 for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
6431 deleg_node = uu_avl_next(avl, deleg_node)) {
6432 if (first) {
6433 (void) printf("%s",
6434 deleg_node->dpn_perm.dp_name);
6435 first = B_FALSE;
6436 } else
6437 (void) printf(",%s",
6438 deleg_node->dpn_perm.dp_name);
6441 (void) printf("\n");
6445 static void
6446 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
6447 const char *title)
6449 who_perm_node_t *who_node = NULL;
6450 boolean_t prt_title = B_TRUE;
6451 uu_avl_walk_t *walk;
6453 if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
6454 nomem();
6456 while ((who_node = uu_avl_walk_next(walk)) != NULL) {
6457 const char *who_name = who_node->who_perm.who_name;
6458 const char *nice_who_name = who_node->who_perm.who_ug_name;
6459 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
6460 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
6461 char delim = ' ';
6462 deleg_perm_node_t *deleg_node;
6463 boolean_t prt_who = B_TRUE;
6465 for (deleg_node = uu_avl_first(avl);
6466 deleg_node != NULL;
6467 deleg_node = uu_avl_next(avl, deleg_node)) {
6468 if (local != deleg_node->dpn_perm.dp_local ||
6469 descend != deleg_node->dpn_perm.dp_descend)
6470 continue;
6472 if (prt_who) {
6473 const char *who = NULL;
6474 if (prt_title) {
6475 prt_title = B_FALSE;
6476 (void) printf("%s", title);
6479 switch (who_type) {
6480 case ZFS_DELEG_USER_SETS:
6481 case ZFS_DELEG_USER:
6482 who = gettext("user");
6483 if (nice_who_name)
6484 who_name = nice_who_name;
6485 break;
6486 case ZFS_DELEG_GROUP_SETS:
6487 case ZFS_DELEG_GROUP:
6488 who = gettext("group");
6489 if (nice_who_name)
6490 who_name = nice_who_name;
6491 break;
6492 case ZFS_DELEG_EVERYONE_SETS:
6493 case ZFS_DELEG_EVERYONE:
6494 who = gettext("everyone");
6495 who_name = NULL;
6496 break;
6498 default:
6499 assert(who != NULL);
6502 prt_who = B_FALSE;
6503 if (who_name == NULL)
6504 (void) printf("\t%s", who);
6505 else
6506 (void) printf("\t%s %s", who, who_name);
6509 (void) printf("%c%s", delim,
6510 deleg_node->dpn_perm.dp_name);
6511 delim = ',';
6514 if (!prt_who)
6515 (void) printf("\n");
6518 uu_avl_walk_end(walk);
6521 static void
6522 print_fs_perms(fs_perm_set_t *fspset)
6524 fs_perm_node_t *node = NULL;
6525 char buf[MAXNAMELEN + 32];
6526 const char *dsname = buf;
6528 for (node = uu_list_first(fspset->fsps_list); node != NULL;
6529 node = uu_list_next(fspset->fsps_list, node)) {
6530 uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
6531 uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
6532 int left = 0;
6534 (void) snprintf(buf, sizeof (buf),
6535 gettext("---- Permissions on %s "),
6536 node->fspn_fsperm.fsp_name);
6537 (void) printf("%s", dsname);
6538 left = 70 - strlen(buf);
6539 while (left-- > 0)
6540 (void) printf("-");
6541 (void) printf("\n");
6543 print_set_creat_perms(sc_avl);
6544 print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
6545 gettext("Local permissions:\n"));
6546 print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
6547 gettext("Descendent permissions:\n"));
6548 print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
6549 gettext("Local+Descendent permissions:\n"));
6553 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
6555 struct deleg_perms {
6556 boolean_t un;
6557 nvlist_t *nvl;
6560 static int
6561 set_deleg_perms(zfs_handle_t *zhp, void *data)
6563 struct deleg_perms *perms = (struct deleg_perms *)data;
6564 zfs_type_t zfs_type = zfs_get_type(zhp);
6566 if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
6567 return (0);
6569 return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
6572 static int
6573 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
6575 zfs_handle_t *zhp;
6576 nvlist_t *perm_nvl = NULL;
6577 nvlist_t *update_perm_nvl = NULL;
6578 int error = 1;
6579 int c;
6580 struct allow_opts opts = { 0 };
6582 const char *optstr = un ? "ldugecsrh" : "ldugecsh";
6584 /* check opts */
6585 while ((c = getopt(argc, argv, optstr)) != -1) {
6586 switch (c) {
6587 case 'l':
6588 opts.local = B_TRUE;
6589 break;
6590 case 'd':
6591 opts.descend = B_TRUE;
6592 break;
6593 case 'u':
6594 opts.user = B_TRUE;
6595 break;
6596 case 'g':
6597 opts.group = B_TRUE;
6598 break;
6599 case 'e':
6600 opts.everyone = B_TRUE;
6601 break;
6602 case 's':
6603 opts.set = B_TRUE;
6604 break;
6605 case 'c':
6606 opts.create = B_TRUE;
6607 break;
6608 case 'r':
6609 opts.recursive = B_TRUE;
6610 break;
6611 case ':':
6612 (void) fprintf(stderr, gettext("missing argument for "
6613 "'%c' option\n"), optopt);
6614 usage(B_FALSE);
6615 break;
6616 case 'h':
6617 opts.prt_usage = B_TRUE;
6618 break;
6619 case '?':
6620 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6621 optopt);
6622 usage(B_FALSE);
6626 argc -= optind;
6627 argv += optind;
6629 /* check arguments */
6630 parse_allow_args(argc, argv, un, &opts);
6632 /* try to open the dataset */
6633 if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
6634 ZFS_TYPE_VOLUME)) == NULL) {
6635 (void) fprintf(stderr, "Failed to open dataset: %s\n",
6636 opts.dataset);
6637 return (-1);
6640 if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
6641 goto cleanup2;
6643 fs_perm_set_init(&fs_perm_set);
6644 if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
6645 (void) fprintf(stderr, "Failed to parse fsacl permissions\n");
6646 goto cleanup1;
6649 if (opts.prt_perms)
6650 print_fs_perms(&fs_perm_set);
6651 else {
6652 (void) construct_fsacl_list(un, &opts, &update_perm_nvl);
6653 if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
6654 goto cleanup0;
6656 if (un && opts.recursive) {
6657 struct deleg_perms data = { un, update_perm_nvl };
6658 if (zfs_iter_filesystems_v2(zhp, 0, set_deleg_perms,
6659 &data) != 0)
6660 goto cleanup0;
6664 error = 0;
6666 cleanup0:
6667 nvlist_free(perm_nvl);
6668 nvlist_free(update_perm_nvl);
6669 cleanup1:
6670 fs_perm_set_fini(&fs_perm_set);
6671 cleanup2:
6672 zfs_close(zhp);
6674 return (error);
6677 static int
6678 zfs_do_allow(int argc, char **argv)
6680 return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
6683 static int
6684 zfs_do_unallow(int argc, char **argv)
6686 return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
6689 static int
6690 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
6692 int errors = 0;
6693 int i;
6694 const char *tag;
6695 boolean_t recursive = B_FALSE;
6696 const char *opts = holding ? "rt" : "r";
6697 int c;
6699 /* check options */
6700 while ((c = getopt(argc, argv, opts)) != -1) {
6701 switch (c) {
6702 case 'r':
6703 recursive = B_TRUE;
6704 break;
6705 case '?':
6706 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6707 optopt);
6708 usage(B_FALSE);
6712 argc -= optind;
6713 argv += optind;
6715 /* check number of arguments */
6716 if (argc < 2)
6717 usage(B_FALSE);
6719 tag = argv[0];
6720 --argc;
6721 ++argv;
6723 if (holding && tag[0] == '.') {
6724 /* tags starting with '.' are reserved for libzfs */
6725 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
6726 usage(B_FALSE);
6729 for (i = 0; i < argc; ++i) {
6730 zfs_handle_t *zhp;
6731 char parent[ZFS_MAX_DATASET_NAME_LEN];
6732 const char *delim;
6733 char *path = argv[i];
6735 delim = strchr(path, '@');
6736 if (delim == NULL) {
6737 (void) fprintf(stderr,
6738 gettext("'%s' is not a snapshot\n"), path);
6739 ++errors;
6740 continue;
6742 (void) strlcpy(parent, path, MIN(sizeof (parent),
6743 delim - path + 1));
6745 zhp = zfs_open(g_zfs, parent,
6746 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
6747 if (zhp == NULL) {
6748 ++errors;
6749 continue;
6751 if (holding) {
6752 if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
6753 ++errors;
6754 } else {
6755 if (zfs_release(zhp, delim+1, tag, recursive) != 0)
6756 ++errors;
6758 zfs_close(zhp);
6761 return (errors != 0);
6765 * zfs hold [-r] [-t] <tag> <snap> ...
6767 * -r Recursively hold
6769 * Apply a user-hold with the given tag to the list of snapshots.
6771 static int
6772 zfs_do_hold(int argc, char **argv)
6774 return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
6778 * zfs release [-r] <tag> <snap> ...
6780 * -r Recursively release
6782 * Release a user-hold with the given tag from the list of snapshots.
6784 static int
6785 zfs_do_release(int argc, char **argv)
6787 return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
6790 typedef struct holds_cbdata {
6791 boolean_t cb_recursive;
6792 const char *cb_snapname;
6793 nvlist_t **cb_nvlp;
6794 size_t cb_max_namelen;
6795 size_t cb_max_taglen;
6796 } holds_cbdata_t;
6798 #define STRFTIME_FMT_STR "%a %b %e %H:%M %Y"
6799 #define DATETIME_BUF_LEN (32)
6803 static void
6804 print_holds(boolean_t scripted, int nwidth, int tagwidth, nvlist_t *nvl,
6805 boolean_t parsable)
6807 int i;
6808 nvpair_t *nvp = NULL;
6809 const char *const hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
6810 const char *col;
6812 if (!scripted) {
6813 for (i = 0; i < 3; i++) {
6814 col = gettext(hdr_cols[i]);
6815 if (i < 2)
6816 (void) printf("%-*s ", i ? tagwidth : nwidth,
6817 col);
6818 else
6819 (void) printf("%s\n", col);
6823 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
6824 const char *zname = nvpair_name(nvp);
6825 nvlist_t *nvl2;
6826 nvpair_t *nvp2 = NULL;
6827 (void) nvpair_value_nvlist(nvp, &nvl2);
6828 while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
6829 char tsbuf[DATETIME_BUF_LEN];
6830 const char *tagname = nvpair_name(nvp2);
6831 uint64_t val = 0;
6832 time_t time;
6833 struct tm t;
6835 (void) nvpair_value_uint64(nvp2, &val);
6836 time = (time_t)val;
6837 (void) localtime_r(&time, &t);
6838 (void) strftime(tsbuf, DATETIME_BUF_LEN,
6839 gettext(STRFTIME_FMT_STR), &t);
6841 if (scripted) {
6842 if (parsable) {
6843 (void) printf("%s\t%s\t%ld\n", zname,
6844 tagname, time);
6845 } else {
6846 (void) printf("%s\t%s\t%s\n", zname,
6847 tagname, tsbuf);
6849 } else {
6850 if (parsable) {
6851 (void) printf("%-*s %-*s %ld\n",
6852 nwidth, zname, tagwidth,
6853 tagname, time);
6854 } else {
6855 (void) printf("%-*s %-*s %s\n",
6856 nwidth, zname, tagwidth,
6857 tagname, tsbuf);
6865 * Generic callback function to list a dataset or snapshot.
6867 static int
6868 holds_callback(zfs_handle_t *zhp, void *data)
6870 holds_cbdata_t *cbp = data;
6871 nvlist_t *top_nvl = *cbp->cb_nvlp;
6872 nvlist_t *nvl = NULL;
6873 nvpair_t *nvp = NULL;
6874 const char *zname = zfs_get_name(zhp);
6875 size_t znamelen = strlen(zname);
6877 if (cbp->cb_recursive) {
6878 const char *snapname;
6879 char *delim = strchr(zname, '@');
6880 if (delim == NULL)
6881 return (0);
6883 snapname = delim + 1;
6884 if (strcmp(cbp->cb_snapname, snapname))
6885 return (0);
6888 if (zfs_get_holds(zhp, &nvl) != 0)
6889 return (-1);
6891 if (znamelen > cbp->cb_max_namelen)
6892 cbp->cb_max_namelen = znamelen;
6894 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
6895 const char *tag = nvpair_name(nvp);
6896 size_t taglen = strlen(tag);
6897 if (taglen > cbp->cb_max_taglen)
6898 cbp->cb_max_taglen = taglen;
6901 return (nvlist_add_nvlist(top_nvl, zname, nvl));
6905 * zfs holds [-rHp] <snap> ...
6907 * -r Lists holds that are set on the named snapshots recursively.
6908 * -H Scripted mode; elide headers and separate columns by tabs.
6909 * -p Display values in parsable (literal) format.
6911 static int
6912 zfs_do_holds(int argc, char **argv)
6914 int c;
6915 boolean_t errors = B_FALSE;
6916 boolean_t scripted = B_FALSE;
6917 boolean_t recursive = B_FALSE;
6918 boolean_t parsable = B_FALSE;
6920 int types = ZFS_TYPE_SNAPSHOT;
6921 holds_cbdata_t cb = { 0 };
6923 int limit = 0;
6924 int ret = 0;
6925 int flags = 0;
6927 /* check options */
6928 while ((c = getopt(argc, argv, "rHp")) != -1) {
6929 switch (c) {
6930 case 'r':
6931 recursive = B_TRUE;
6932 break;
6933 case 'H':
6934 scripted = B_TRUE;
6935 break;
6936 case 'p':
6937 parsable = B_TRUE;
6938 break;
6939 case '?':
6940 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6941 optopt);
6942 usage(B_FALSE);
6946 if (recursive) {
6947 types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
6948 flags |= ZFS_ITER_RECURSE;
6951 argc -= optind;
6952 argv += optind;
6954 /* check number of arguments */
6955 if (argc < 1)
6956 usage(B_FALSE);
6958 nvlist_t *nvl = fnvlist_alloc();
6960 for (int i = 0; i < argc; ++i) {
6961 char *snapshot = argv[i];
6962 const char *delim;
6963 const char *snapname;
6965 delim = strchr(snapshot, '@');
6966 if (delim == NULL) {
6967 (void) fprintf(stderr,
6968 gettext("'%s' is not a snapshot\n"), snapshot);
6969 errors = B_TRUE;
6970 continue;
6972 snapname = delim + 1;
6973 if (recursive)
6974 snapshot[delim - snapshot] = '\0';
6976 cb.cb_recursive = recursive;
6977 cb.cb_snapname = snapname;
6978 cb.cb_nvlp = &nvl;
6981 * 1. collect holds data, set format options
6983 ret = zfs_for_each(1, argv + i, flags, types, NULL, NULL, limit,
6984 holds_callback, &cb);
6985 if (ret != 0)
6986 errors = B_TRUE;
6990 * 2. print holds data
6992 print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl,
6993 parsable);
6995 if (nvlist_empty(nvl))
6996 (void) fprintf(stderr, gettext("no datasets available\n"));
6998 nvlist_free(nvl);
7000 return (errors);
7003 #define CHECK_SPINNER 30
7004 #define SPINNER_TIME 3 /* seconds */
7005 #define MOUNT_TIME 1 /* seconds */
7007 typedef struct get_all_state {
7008 char **ga_datasets;
7009 int ga_count;
7010 boolean_t ga_verbose;
7011 get_all_cb_t *ga_cbp;
7012 } get_all_state_t;
7014 static int
7015 get_one_dataset(zfs_handle_t *zhp, void *data)
7017 static const char *const spin[] = { "-", "\\", "|", "/" };
7018 static int spinval = 0;
7019 static int spincheck = 0;
7020 static time_t last_spin_time = (time_t)0;
7021 get_all_state_t *state = data;
7022 zfs_type_t type = zfs_get_type(zhp);
7024 if (state->ga_verbose) {
7025 if (--spincheck < 0) {
7026 time_t now = time(NULL);
7027 if (last_spin_time + SPINNER_TIME < now) {
7028 update_progress(spin[spinval++ % 4]);
7029 last_spin_time = now;
7031 spincheck = CHECK_SPINNER;
7036 * Iterate over any nested datasets.
7038 if (zfs_iter_filesystems_v2(zhp, 0, get_one_dataset, data) != 0) {
7039 zfs_close(zhp);
7040 return (1);
7044 * Skip any datasets whose type does not match.
7046 if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
7047 zfs_close(zhp);
7048 return (0);
7050 libzfs_add_handle(state->ga_cbp, zhp);
7051 assert(state->ga_cbp->cb_used <= state->ga_cbp->cb_alloc);
7053 return (0);
7056 static int
7057 get_recursive_datasets(zfs_handle_t *zhp, void *data)
7059 get_all_state_t *state = data;
7060 int len = strlen(zfs_get_name(zhp));
7061 for (int i = 0; i < state->ga_count; ++i) {
7062 if (strcmp(state->ga_datasets[i], zfs_get_name(zhp)) == 0)
7063 return (get_one_dataset(zhp, data));
7064 else if ((strncmp(state->ga_datasets[i], zfs_get_name(zhp),
7065 len) == 0) && state->ga_datasets[i][len] == '/') {
7066 (void) zfs_iter_filesystems_v2(zhp, 0,
7067 get_recursive_datasets, data);
7070 zfs_close(zhp);
7071 return (0);
7074 static void
7075 get_all_datasets(get_all_state_t *state)
7077 if (state->ga_verbose)
7078 set_progress_header(gettext("Reading ZFS config"));
7079 if (state->ga_datasets == NULL)
7080 (void) zfs_iter_root(g_zfs, get_one_dataset, state);
7081 else
7082 (void) zfs_iter_root(g_zfs, get_recursive_datasets, state);
7084 if (state->ga_verbose)
7085 finish_progress(gettext("done."));
7089 * Generic callback for sharing or mounting filesystems. Because the code is so
7090 * similar, we have a common function with an extra parameter to determine which
7091 * mode we are using.
7093 typedef enum { OP_SHARE, OP_MOUNT } share_mount_op_t;
7095 typedef struct share_mount_state {
7096 share_mount_op_t sm_op;
7097 boolean_t sm_verbose;
7098 int sm_flags;
7099 char *sm_options;
7100 enum sa_protocol sm_proto; /* only valid for OP_SHARE */
7101 pthread_mutex_t sm_lock; /* protects the remaining fields */
7102 uint_t sm_total; /* number of filesystems to process */
7103 uint_t sm_done; /* number of filesystems processed */
7104 int sm_status; /* -1 if any of the share/mount operations failed */
7105 } share_mount_state_t;
7108 * Share or mount a dataset.
7110 static int
7111 share_mount_one(zfs_handle_t *zhp, int op, int flags, enum sa_protocol protocol,
7112 boolean_t explicit, const char *options)
7114 char mountpoint[ZFS_MAXPROPLEN];
7115 char shareopts[ZFS_MAXPROPLEN];
7116 char smbshareopts[ZFS_MAXPROPLEN];
7117 const char *cmdname = op == OP_SHARE ? "share" : "mount";
7118 struct mnttab mnt;
7119 uint64_t zoned, canmount;
7120 boolean_t shared_nfs, shared_smb;
7122 assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
7125 * Check to make sure we can mount/share this dataset. If we
7126 * are in the global zone and the filesystem is exported to a
7127 * local zone, or if we are in a local zone and the
7128 * filesystem is not exported, then it is an error.
7130 zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
7132 if (zoned && getzoneid() == GLOBAL_ZONEID) {
7133 if (!explicit)
7134 return (0);
7136 (void) fprintf(stderr, gettext("cannot %s '%s': "
7137 "dataset is exported to a local zone\n"), cmdname,
7138 zfs_get_name(zhp));
7139 return (1);
7141 } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
7142 if (!explicit)
7143 return (0);
7145 (void) fprintf(stderr, gettext("cannot %s '%s': "
7146 "permission denied\n"), cmdname,
7147 zfs_get_name(zhp));
7148 return (1);
7152 * Ignore any filesystems which don't apply to us. This
7153 * includes those with a legacy mountpoint, or those with
7154 * legacy share options.
7156 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
7157 sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
7158 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
7159 sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
7160 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
7161 sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
7163 if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
7164 strcmp(smbshareopts, "off") == 0) {
7165 if (!explicit)
7166 return (0);
7168 (void) fprintf(stderr, gettext("cannot share '%s': "
7169 "legacy share\n"), zfs_get_name(zhp));
7170 (void) fprintf(stderr, gettext("use exports(5) or "
7171 "smb.conf(5) to share this filesystem, or set "
7172 "the sharenfs or sharesmb property\n"));
7173 return (1);
7177 * We cannot share or mount legacy filesystems. If the
7178 * shareopts is non-legacy but the mountpoint is legacy, we
7179 * treat it as a legacy share.
7181 if (strcmp(mountpoint, "legacy") == 0) {
7182 if (!explicit)
7183 return (0);
7185 (void) fprintf(stderr, gettext("cannot %s '%s': "
7186 "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
7187 (void) fprintf(stderr, gettext("use %s(8) to "
7188 "%s this filesystem\n"), cmdname, cmdname);
7189 return (1);
7192 if (strcmp(mountpoint, "none") == 0) {
7193 if (!explicit)
7194 return (0);
7196 (void) fprintf(stderr, gettext("cannot %s '%s': no "
7197 "mountpoint set\n"), cmdname, zfs_get_name(zhp));
7198 return (1);
7202 * canmount explicit outcome
7203 * on no pass through
7204 * on yes pass through
7205 * off no return 0
7206 * off yes display error, return 1
7207 * noauto no return 0
7208 * noauto yes pass through
7210 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
7211 if (canmount == ZFS_CANMOUNT_OFF) {
7212 if (!explicit)
7213 return (0);
7215 (void) fprintf(stderr, gettext("cannot %s '%s': "
7216 "'canmount' property is set to 'off'\n"), cmdname,
7217 zfs_get_name(zhp));
7218 return (1);
7219 } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
7221 * When performing a 'zfs mount -a', we skip any mounts for
7222 * datasets that have 'noauto' set. Sharing a dataset with
7223 * 'noauto' set is only allowed if it's mounted.
7225 if (op == OP_MOUNT)
7226 return (0);
7227 if (op == OP_SHARE && !zfs_is_mounted(zhp, NULL)) {
7228 /* also purge it from existing exports */
7229 zfs_unshare(zhp, mountpoint, NULL);
7230 return (0);
7235 * If this filesystem is encrypted and does not have
7236 * a loaded key, we can not mount it.
7238 if ((flags & MS_CRYPT) == 0 &&
7239 zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) != ZIO_CRYPT_OFF &&
7240 zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS) ==
7241 ZFS_KEYSTATUS_UNAVAILABLE) {
7242 if (!explicit)
7243 return (0);
7245 (void) fprintf(stderr, gettext("cannot %s '%s': "
7246 "encryption key not loaded\n"), cmdname, zfs_get_name(zhp));
7247 return (1);
7251 * If this filesystem is inconsistent and has a receive resume
7252 * token, we can not mount it.
7254 if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) &&
7255 zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
7256 NULL, 0, NULL, NULL, 0, B_TRUE) == 0) {
7257 if (!explicit)
7258 return (0);
7260 (void) fprintf(stderr, gettext("cannot %s '%s': "
7261 "Contains partially-completed state from "
7262 "\"zfs receive -s\", which can be resumed with "
7263 "\"zfs send -t\"\n"),
7264 cmdname, zfs_get_name(zhp));
7265 return (1);
7268 if (zfs_prop_get_int(zhp, ZFS_PROP_REDACTED) && !(flags & MS_FORCE)) {
7269 if (!explicit)
7270 return (0);
7272 (void) fprintf(stderr, gettext("cannot %s '%s': "
7273 "Dataset is not complete, was created by receiving "
7274 "a redacted zfs send stream.\n"), cmdname,
7275 zfs_get_name(zhp));
7276 return (1);
7280 * At this point, we have verified that the mountpoint and/or
7281 * shareopts are appropriate for auto management. If the
7282 * filesystem is already mounted or shared, return (failing
7283 * for explicit requests); otherwise mount or share the
7284 * filesystem.
7286 switch (op) {
7287 case OP_SHARE: {
7288 enum sa_protocol prot[] = {SA_PROTOCOL_NFS, SA_NO_PROTOCOL};
7289 shared_nfs = zfs_is_shared(zhp, NULL, prot);
7290 *prot = SA_PROTOCOL_SMB;
7291 shared_smb = zfs_is_shared(zhp, NULL, prot);
7293 if ((shared_nfs && shared_smb) ||
7294 (shared_nfs && strcmp(shareopts, "on") == 0 &&
7295 strcmp(smbshareopts, "off") == 0) ||
7296 (shared_smb && strcmp(smbshareopts, "on") == 0 &&
7297 strcmp(shareopts, "off") == 0)) {
7298 if (!explicit)
7299 return (0);
7301 (void) fprintf(stderr, gettext("cannot share "
7302 "'%s': filesystem already shared\n"),
7303 zfs_get_name(zhp));
7304 return (1);
7307 if (!zfs_is_mounted(zhp, NULL) &&
7308 zfs_mount(zhp, NULL, flags) != 0)
7309 return (1);
7311 *prot = protocol;
7312 if (zfs_share(zhp, protocol == SA_NO_PROTOCOL ? NULL : prot))
7313 return (1);
7316 break;
7318 case OP_MOUNT:
7319 mnt.mnt_mntopts = (char *)(options ?: "");
7321 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
7322 zfs_is_mounted(zhp, NULL)) {
7323 if (!explicit)
7324 return (0);
7326 (void) fprintf(stderr, gettext("cannot mount "
7327 "'%s': filesystem already mounted\n"),
7328 zfs_get_name(zhp));
7329 return (1);
7332 if (zfs_mount(zhp, options, flags) != 0)
7333 return (1);
7334 break;
7337 return (0);
7341 * Reports progress in the form "(current/total)". Not thread-safe.
7343 static void
7344 report_mount_progress(int current, int total)
7346 static time_t last_progress_time = 0;
7347 time_t now = time(NULL);
7348 char info[32];
7350 /* display header if we're here for the first time */
7351 if (current == 1) {
7352 set_progress_header(gettext("Mounting ZFS filesystems"));
7353 } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
7354 /* too soon to report again */
7355 return;
7358 last_progress_time = now;
7360 (void) sprintf(info, "(%d/%d)", current, total);
7362 if (current == total)
7363 finish_progress(info);
7364 else
7365 update_progress(info);
7369 * zfs_foreach_mountpoint() callback that mounts or shares one filesystem and
7370 * updates the progress meter.
7372 static int
7373 share_mount_one_cb(zfs_handle_t *zhp, void *arg)
7375 share_mount_state_t *sms = arg;
7376 int ret;
7378 ret = share_mount_one(zhp, sms->sm_op, sms->sm_flags, sms->sm_proto,
7379 B_FALSE, sms->sm_options);
7381 pthread_mutex_lock(&sms->sm_lock);
7382 if (ret != 0)
7383 sms->sm_status = ret;
7384 sms->sm_done++;
7385 if (sms->sm_verbose)
7386 report_mount_progress(sms->sm_done, sms->sm_total);
7387 pthread_mutex_unlock(&sms->sm_lock);
7388 return (ret);
7391 static void
7392 append_options(char *mntopts, char *newopts)
7394 int len = strlen(mntopts);
7396 /* original length plus new string to append plus 1 for the comma */
7397 if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
7398 (void) fprintf(stderr, gettext("the opts argument for "
7399 "'%s' option is too long (more than %d chars)\n"),
7400 "-o", MNT_LINE_MAX);
7401 usage(B_FALSE);
7404 if (*mntopts)
7405 mntopts[len++] = ',';
7407 (void) strcpy(&mntopts[len], newopts);
7410 static enum sa_protocol
7411 sa_protocol_decode(const char *protocol)
7413 for (enum sa_protocol i = 0; i < ARRAY_SIZE(sa_protocol_names); ++i)
7414 if (strcmp(protocol, sa_protocol_names[i]) == 0)
7415 return (i);
7417 (void) fputs(gettext("share type must be one of: "), stderr);
7418 for (enum sa_protocol i = 0;
7419 i < ARRAY_SIZE(sa_protocol_names); ++i)
7420 (void) fprintf(stderr, "%s%s",
7421 i != 0 ? ", " : "", sa_protocol_names[i]);
7422 (void) fputc('\n', stderr);
7423 usage(B_FALSE);
7426 static int
7427 share_mount(int op, int argc, char **argv)
7429 int do_all = 0;
7430 int recursive = 0;
7431 boolean_t verbose = B_FALSE;
7432 boolean_t json = B_FALSE;
7433 int c, ret = 0;
7434 char *options = NULL;
7435 int flags = 0;
7436 nvlist_t *jsobj, *data, *item;
7437 const uint_t mount_nthr = 512;
7438 uint_t nthr;
7439 jsobj = data = item = NULL;
7441 struct option long_options[] = {
7442 {"json", no_argument, NULL, 'j'},
7443 {0, 0, 0, 0}
7446 /* check options */
7447 while ((c = getopt_long(argc, argv,
7448 op == OP_MOUNT ? ":ajRlvo:Of" : "al",
7449 op == OP_MOUNT ? long_options : NULL, NULL)) != -1) {
7450 switch (c) {
7451 case 'a':
7452 do_all = 1;
7453 break;
7454 case 'R':
7455 recursive = 1;
7456 break;
7457 case 'v':
7458 verbose = B_TRUE;
7459 break;
7460 case 'l':
7461 flags |= MS_CRYPT;
7462 break;
7463 case 'j':
7464 json = B_TRUE;
7465 jsobj = zfs_json_schema(0, 1);
7466 data = fnvlist_alloc();
7467 break;
7468 case 'o':
7469 if (*optarg == '\0') {
7470 (void) fprintf(stderr, gettext("empty mount "
7471 "options (-o) specified\n"));
7472 usage(B_FALSE);
7475 if (options == NULL)
7476 options = safe_malloc(MNT_LINE_MAX + 1);
7478 /* option validation is done later */
7479 append_options(options, optarg);
7480 break;
7481 case 'O':
7482 flags |= MS_OVERLAY;
7483 break;
7484 case 'f':
7485 flags |= MS_FORCE;
7486 break;
7487 case ':':
7488 (void) fprintf(stderr, gettext("missing argument for "
7489 "'%c' option\n"), optopt);
7490 usage(B_FALSE);
7491 break;
7492 case '?':
7493 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7494 optopt);
7495 usage(B_FALSE);
7499 argc -= optind;
7500 argv += optind;
7502 if (json && argc != 0) {
7503 (void) fprintf(stderr, gettext("too many arguments\n"));
7504 usage(B_FALSE);
7507 /* check number of arguments */
7508 if (do_all || recursive) {
7509 enum sa_protocol protocol = SA_NO_PROTOCOL;
7511 if (op == OP_SHARE && argc > 0) {
7512 protocol = sa_protocol_decode(argv[0]);
7513 argc--;
7514 argv++;
7517 if (argc != 0 && do_all) {
7518 (void) fprintf(stderr, gettext("too many arguments\n"));
7519 usage(B_FALSE);
7522 if (argc == 0 && recursive) {
7523 (void) fprintf(stderr,
7524 gettext("no dataset provided\n"));
7525 usage(B_FALSE);
7528 start_progress_timer();
7529 get_all_cb_t cb = { 0 };
7530 get_all_state_t state = { 0 };
7531 if (argc == 0) {
7532 state.ga_datasets = NULL;
7533 state.ga_count = -1;
7534 } else {
7535 zfs_handle_t *zhp;
7536 for (int i = 0; i < argc; i++) {
7537 zhp = zfs_open(g_zfs, argv[i],
7538 ZFS_TYPE_FILESYSTEM);
7539 if (zhp == NULL)
7540 usage(B_FALSE);
7541 zfs_close(zhp);
7543 state.ga_datasets = argv;
7544 state.ga_count = argc;
7546 state.ga_verbose = verbose;
7547 state.ga_cbp = &cb;
7548 get_all_datasets(&state);
7550 if (cb.cb_used == 0) {
7551 free(options);
7552 return (0);
7555 share_mount_state_t share_mount_state = { 0 };
7556 share_mount_state.sm_op = op;
7557 share_mount_state.sm_verbose = verbose;
7558 share_mount_state.sm_flags = flags;
7559 share_mount_state.sm_options = options;
7560 share_mount_state.sm_proto = protocol;
7561 share_mount_state.sm_total = cb.cb_used;
7562 pthread_mutex_init(&share_mount_state.sm_lock, NULL);
7564 /* For a 'zfs share -a' operation start with a clean slate. */
7565 if (op == OP_SHARE)
7566 zfs_truncate_shares(NULL);
7569 * libshare isn't mt-safe, so only do the operation in parallel
7570 * if we're mounting. Additionally, the key-loading option must
7571 * be serialized so that we can prompt the user for their keys
7572 * in a consistent manner.
7574 nthr = op == OP_MOUNT && !(flags & MS_CRYPT) ? mount_nthr : 1;
7575 zfs_foreach_mountpoint(g_zfs, cb.cb_handles, cb.cb_used,
7576 share_mount_one_cb, &share_mount_state, nthr);
7577 zfs_commit_shares(NULL);
7579 ret = share_mount_state.sm_status;
7581 for (int i = 0; i < cb.cb_used; i++)
7582 zfs_close(cb.cb_handles[i]);
7583 free(cb.cb_handles);
7584 } else if (argc == 0) {
7585 FILE *mnttab;
7586 struct mnttab entry;
7588 if ((op == OP_SHARE) || (options != NULL)) {
7589 (void) fprintf(stderr, gettext("missing filesystem "
7590 "argument (specify -a for all)\n"));
7591 usage(B_FALSE);
7595 * When mount is given no arguments, go through
7596 * /proc/self/mounts and display any active ZFS mounts.
7597 * We hide any snapshots, since they are controlled
7598 * automatically.
7601 if ((mnttab = fopen(MNTTAB, "re")) == NULL) {
7602 free(options);
7603 return (ENOENT);
7606 while (getmntent(mnttab, &entry) == 0) {
7607 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
7608 strchr(entry.mnt_special, '@') != NULL)
7609 continue;
7610 if (json) {
7611 item = fnvlist_alloc();
7612 fnvlist_add_string(item, "filesystem",
7613 entry.mnt_special);
7614 fnvlist_add_string(item, "mountpoint",
7615 entry.mnt_mountp);
7616 fnvlist_add_nvlist(data, entry.mnt_special,
7617 item);
7618 fnvlist_free(item);
7619 } else {
7620 (void) printf("%-30s %s\n", entry.mnt_special,
7621 entry.mnt_mountp);
7625 (void) fclose(mnttab);
7626 if (json) {
7627 fnvlist_add_nvlist(jsobj, "datasets", data);
7628 if (nvlist_empty(data))
7629 fnvlist_free(jsobj);
7630 else
7631 zcmd_print_json(jsobj);
7632 fnvlist_free(data);
7634 } else {
7635 zfs_handle_t *zhp;
7637 if (argc > 1) {
7638 (void) fprintf(stderr,
7639 gettext("too many arguments\n"));
7640 usage(B_FALSE);
7643 if ((zhp = zfs_open(g_zfs, argv[0],
7644 ZFS_TYPE_FILESYSTEM)) == NULL) {
7645 ret = 1;
7646 } else {
7647 ret = share_mount_one(zhp, op, flags, SA_NO_PROTOCOL,
7648 B_TRUE, options);
7649 zfs_commit_shares(NULL);
7650 zfs_close(zhp);
7654 free(options);
7655 return (ret);
7659 * zfs mount -a
7660 * zfs mount filesystem
7662 * Mount all filesystems, or mount the given filesystem.
7664 static int
7665 zfs_do_mount(int argc, char **argv)
7667 return (share_mount(OP_MOUNT, argc, argv));
7671 * zfs share -a [nfs | smb]
7672 * zfs share filesystem
7674 * Share all filesystems, or share the given filesystem.
7676 static int
7677 zfs_do_share(int argc, char **argv)
7679 return (share_mount(OP_SHARE, argc, argv));
7682 typedef struct unshare_unmount_node {
7683 zfs_handle_t *un_zhp;
7684 char *un_mountp;
7685 uu_avl_node_t un_avlnode;
7686 } unshare_unmount_node_t;
7688 static int
7689 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
7691 (void) unused;
7692 const unshare_unmount_node_t *l = larg;
7693 const unshare_unmount_node_t *r = rarg;
7695 return (strcmp(l->un_mountp, r->un_mountp));
7699 * Convenience routine used by zfs_do_umount() and manual_unmount(). Given an
7700 * absolute path, find the entry /proc/self/mounts, verify that it's a
7701 * ZFS filesystem, and unmount it appropriately.
7703 static int
7704 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
7706 zfs_handle_t *zhp;
7707 int ret = 0;
7708 struct stat64 statbuf;
7709 struct extmnttab entry;
7710 const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
7711 ino_t path_inode;
7714 * Search for the given (major,minor) pair in the mount table.
7717 if (getextmntent(path, &entry, &statbuf) != 0) {
7718 if (op == OP_SHARE) {
7719 (void) fprintf(stderr, gettext("cannot %s '%s': not "
7720 "currently mounted\n"), cmdname, path);
7721 return (1);
7723 (void) fprintf(stderr, gettext("warning: %s not in"
7724 "/proc/self/mounts\n"), path);
7725 if ((ret = umount2(path, flags)) != 0)
7726 (void) fprintf(stderr, gettext("%s: %s\n"), path,
7727 strerror(errno));
7728 return (ret != 0);
7730 path_inode = statbuf.st_ino;
7732 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
7733 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
7734 "filesystem\n"), cmdname, path);
7735 return (1);
7738 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
7739 ZFS_TYPE_FILESYSTEM)) == NULL)
7740 return (1);
7742 ret = 1;
7743 if (stat64(entry.mnt_mountp, &statbuf) != 0) {
7744 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
7745 cmdname, path, strerror(errno));
7746 goto out;
7747 } else if (statbuf.st_ino != path_inode) {
7748 (void) fprintf(stderr, gettext("cannot "
7749 "%s '%s': not a mountpoint\n"), cmdname, path);
7750 goto out;
7753 if (op == OP_SHARE) {
7754 char nfs_mnt_prop[ZFS_MAXPROPLEN];
7755 char smbshare_prop[ZFS_MAXPROPLEN];
7757 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
7758 sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
7759 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
7760 sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
7762 if (strcmp(nfs_mnt_prop, "off") == 0 &&
7763 strcmp(smbshare_prop, "off") == 0) {
7764 (void) fprintf(stderr, gettext("cannot unshare "
7765 "'%s': legacy share\n"), path);
7766 (void) fprintf(stderr, gettext("use exportfs(8) "
7767 "or smbcontrol(1) to unshare this filesystem\n"));
7768 } else if (!zfs_is_shared(zhp, NULL, NULL)) {
7769 (void) fprintf(stderr, gettext("cannot unshare '%s': "
7770 "not currently shared\n"), path);
7771 } else {
7772 ret = zfs_unshare(zhp, path, NULL);
7773 zfs_commit_shares(NULL);
7775 } else {
7776 char mtpt_prop[ZFS_MAXPROPLEN];
7778 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
7779 sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
7781 if (is_manual) {
7782 ret = zfs_unmount(zhp, NULL, flags);
7783 } else if (strcmp(mtpt_prop, "legacy") == 0) {
7784 (void) fprintf(stderr, gettext("cannot unmount "
7785 "'%s': legacy mountpoint\n"),
7786 zfs_get_name(zhp));
7787 (void) fprintf(stderr, gettext("use umount(8) "
7788 "to unmount this filesystem\n"));
7789 } else {
7790 ret = zfs_unmountall(zhp, flags);
7794 out:
7795 zfs_close(zhp);
7797 return (ret != 0);
7801 * Generic callback for unsharing or unmounting a filesystem.
7803 static int
7804 unshare_unmount(int op, int argc, char **argv)
7806 int do_all = 0;
7807 int flags = 0;
7808 int ret = 0;
7809 int c;
7810 zfs_handle_t *zhp;
7811 char nfs_mnt_prop[ZFS_MAXPROPLEN];
7812 char sharesmb[ZFS_MAXPROPLEN];
7814 /* check options */
7815 while ((c = getopt(argc, argv, op == OP_SHARE ? ":a" : "afu")) != -1) {
7816 switch (c) {
7817 case 'a':
7818 do_all = 1;
7819 break;
7820 case 'f':
7821 flags |= MS_FORCE;
7822 break;
7823 case 'u':
7824 flags |= MS_CRYPT;
7825 break;
7826 case ':':
7827 (void) fprintf(stderr, gettext("missing argument for "
7828 "'%c' option\n"), optopt);
7829 usage(B_FALSE);
7830 break;
7831 case '?':
7832 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
7833 optopt);
7834 usage(B_FALSE);
7838 argc -= optind;
7839 argv += optind;
7841 if (do_all) {
7843 * We could make use of zfs_for_each() to walk all datasets in
7844 * the system, but this would be very inefficient, especially
7845 * since we would have to linearly search /proc/self/mounts for
7846 * each one. Instead, do one pass through /proc/self/mounts
7847 * looking for zfs entries and call zfs_unmount() for each one.
7849 * Things get a little tricky if the administrator has created
7850 * mountpoints beneath other ZFS filesystems. In this case, we
7851 * have to unmount the deepest filesystems first. To accomplish
7852 * this, we place all the mountpoints in an AVL tree sorted by
7853 * the special type (dataset name), and walk the result in
7854 * reverse to make sure to get any snapshots first.
7856 FILE *mnttab;
7857 struct mnttab entry;
7858 uu_avl_pool_t *pool;
7859 uu_avl_t *tree = NULL;
7860 unshare_unmount_node_t *node;
7861 uu_avl_index_t idx;
7862 uu_avl_walk_t *walk;
7863 enum sa_protocol *protocol = NULL,
7864 single_protocol[] = {SA_NO_PROTOCOL, SA_NO_PROTOCOL};
7866 if (op == OP_SHARE && argc > 0) {
7867 *single_protocol = sa_protocol_decode(argv[0]);
7868 protocol = single_protocol;
7869 argc--;
7870 argv++;
7873 if (argc != 0) {
7874 (void) fprintf(stderr, gettext("too many arguments\n"));
7875 usage(B_FALSE);
7878 if (((pool = uu_avl_pool_create("unmount_pool",
7879 sizeof (unshare_unmount_node_t),
7880 offsetof(unshare_unmount_node_t, un_avlnode),
7881 unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
7882 ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
7883 nomem();
7885 if ((mnttab = fopen(MNTTAB, "re")) == NULL) {
7886 uu_avl_destroy(tree);
7887 uu_avl_pool_destroy(pool);
7888 return (ENOENT);
7891 while (getmntent(mnttab, &entry) == 0) {
7893 /* ignore non-ZFS entries */
7894 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
7895 continue;
7897 /* ignore snapshots */
7898 if (strchr(entry.mnt_special, '@') != NULL)
7899 continue;
7901 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
7902 ZFS_TYPE_FILESYSTEM)) == NULL) {
7903 ret = 1;
7904 continue;
7908 * Ignore datasets that are excluded/restricted by
7909 * parent pool name.
7911 if (zpool_skip_pool(zfs_get_pool_name(zhp))) {
7912 zfs_close(zhp);
7913 continue;
7916 switch (op) {
7917 case OP_SHARE:
7918 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
7919 nfs_mnt_prop,
7920 sizeof (nfs_mnt_prop),
7921 NULL, NULL, 0, B_FALSE) == 0);
7922 if (strcmp(nfs_mnt_prop, "off") != 0)
7923 break;
7924 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
7925 nfs_mnt_prop,
7926 sizeof (nfs_mnt_prop),
7927 NULL, NULL, 0, B_FALSE) == 0);
7928 if (strcmp(nfs_mnt_prop, "off") == 0)
7929 continue;
7930 break;
7931 case OP_MOUNT:
7932 /* Ignore legacy mounts */
7933 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
7934 nfs_mnt_prop,
7935 sizeof (nfs_mnt_prop),
7936 NULL, NULL, 0, B_FALSE) == 0);
7937 if (strcmp(nfs_mnt_prop, "legacy") == 0)
7938 continue;
7939 /* Ignore canmount=noauto mounts */
7940 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
7941 ZFS_CANMOUNT_NOAUTO)
7942 continue;
7943 break;
7944 default:
7945 break;
7948 node = safe_malloc(sizeof (unshare_unmount_node_t));
7949 node->un_zhp = zhp;
7950 node->un_mountp = safe_strdup(entry.mnt_mountp);
7952 uu_avl_node_init(node, &node->un_avlnode, pool);
7954 if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
7955 uu_avl_insert(tree, node, idx);
7956 } else {
7957 zfs_close(node->un_zhp);
7958 free(node->un_mountp);
7959 free(node);
7962 (void) fclose(mnttab);
7965 * Walk the AVL tree in reverse, unmounting each filesystem and
7966 * removing it from the AVL tree in the process.
7968 if ((walk = uu_avl_walk_start(tree,
7969 UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
7970 nomem();
7972 while ((node = uu_avl_walk_next(walk)) != NULL) {
7973 const char *mntarg = NULL;
7975 uu_avl_remove(tree, node);
7976 switch (op) {
7977 case OP_SHARE:
7978 if (zfs_unshare(node->un_zhp,
7979 node->un_mountp, protocol) != 0)
7980 ret = 1;
7981 break;
7983 case OP_MOUNT:
7984 if (zfs_unmount(node->un_zhp,
7985 mntarg, flags) != 0)
7986 ret = 1;
7987 break;
7990 zfs_close(node->un_zhp);
7991 free(node->un_mountp);
7992 free(node);
7995 if (op == OP_SHARE)
7996 zfs_commit_shares(protocol);
7998 uu_avl_walk_end(walk);
7999 uu_avl_destroy(tree);
8000 uu_avl_pool_destroy(pool);
8002 } else {
8003 if (argc != 1) {
8004 if (argc == 0)
8005 (void) fprintf(stderr,
8006 gettext("missing filesystem argument\n"));
8007 else
8008 (void) fprintf(stderr,
8009 gettext("too many arguments\n"));
8010 usage(B_FALSE);
8014 * We have an argument, but it may be a full path or a ZFS
8015 * filesystem. Pass full paths off to unmount_path() (shared by
8016 * manual_unmount), otherwise open the filesystem and pass to
8017 * zfs_unmount().
8019 if (argv[0][0] == '/')
8020 return (unshare_unmount_path(op, argv[0],
8021 flags, B_FALSE));
8023 if ((zhp = zfs_open(g_zfs, argv[0],
8024 ZFS_TYPE_FILESYSTEM)) == NULL)
8025 return (1);
8027 verify(zfs_prop_get(zhp, op == OP_SHARE ?
8028 ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
8029 nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
8030 NULL, 0, B_FALSE) == 0);
8032 switch (op) {
8033 case OP_SHARE:
8034 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
8035 nfs_mnt_prop,
8036 sizeof (nfs_mnt_prop),
8037 NULL, NULL, 0, B_FALSE) == 0);
8038 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
8039 sharesmb, sizeof (sharesmb), NULL, NULL,
8040 0, B_FALSE) == 0);
8042 if (strcmp(nfs_mnt_prop, "off") == 0 &&
8043 strcmp(sharesmb, "off") == 0) {
8044 (void) fprintf(stderr, gettext("cannot "
8045 "unshare '%s': legacy share\n"),
8046 zfs_get_name(zhp));
8047 (void) fprintf(stderr, gettext("use "
8048 "exports(5) or smb.conf(5) to unshare "
8049 "this filesystem\n"));
8050 ret = 1;
8051 } else if (!zfs_is_shared(zhp, NULL, NULL)) {
8052 (void) fprintf(stderr, gettext("cannot "
8053 "unshare '%s': not currently "
8054 "shared\n"), zfs_get_name(zhp));
8055 ret = 1;
8056 } else if (zfs_unshareall(zhp, NULL) != 0) {
8057 ret = 1;
8059 break;
8061 case OP_MOUNT:
8062 if (strcmp(nfs_mnt_prop, "legacy") == 0) {
8063 (void) fprintf(stderr, gettext("cannot "
8064 "unmount '%s': legacy "
8065 "mountpoint\n"), zfs_get_name(zhp));
8066 (void) fprintf(stderr, gettext("use "
8067 "umount(8) to unmount this "
8068 "filesystem\n"));
8069 ret = 1;
8070 } else if (!zfs_is_mounted(zhp, NULL)) {
8071 (void) fprintf(stderr, gettext("cannot "
8072 "unmount '%s': not currently "
8073 "mounted\n"),
8074 zfs_get_name(zhp));
8075 ret = 1;
8076 } else if (zfs_unmountall(zhp, flags) != 0) {
8077 ret = 1;
8079 break;
8082 zfs_close(zhp);
8085 return (ret);
8089 * zfs unmount [-fu] -a
8090 * zfs unmount [-fu] filesystem
8092 * Unmount all filesystems, or a specific ZFS filesystem.
8094 static int
8095 zfs_do_unmount(int argc, char **argv)
8097 return (unshare_unmount(OP_MOUNT, argc, argv));
8101 * zfs unshare -a
8102 * zfs unshare filesystem
8104 * Unshare all filesystems, or a specific ZFS filesystem.
8106 static int
8107 zfs_do_unshare(int argc, char **argv)
8109 return (unshare_unmount(OP_SHARE, argc, argv));
8112 static int
8113 find_command_idx(const char *command, int *idx)
8115 int i;
8117 for (i = 0; i < NCOMMAND; i++) {
8118 if (command_table[i].name == NULL)
8119 continue;
8121 if (strcmp(command, command_table[i].name) == 0) {
8122 *idx = i;
8123 return (0);
8126 return (1);
8129 static int
8130 zfs_do_diff(int argc, char **argv)
8132 zfs_handle_t *zhp;
8133 int flags = 0;
8134 char *tosnap = NULL;
8135 char *fromsnap = NULL;
8136 char *atp, *copy;
8137 int err = 0;
8138 int c;
8139 struct sigaction sa;
8141 while ((c = getopt(argc, argv, "FHth")) != -1) {
8142 switch (c) {
8143 case 'F':
8144 flags |= ZFS_DIFF_CLASSIFY;
8145 break;
8146 case 'H':
8147 flags |= ZFS_DIFF_PARSEABLE;
8148 break;
8149 case 't':
8150 flags |= ZFS_DIFF_TIMESTAMP;
8151 break;
8152 case 'h':
8153 flags |= ZFS_DIFF_NO_MANGLE;
8154 break;
8155 default:
8156 (void) fprintf(stderr,
8157 gettext("invalid option '%c'\n"), optopt);
8158 usage(B_FALSE);
8162 argc -= optind;
8163 argv += optind;
8165 if (argc < 1) {
8166 (void) fprintf(stderr,
8167 gettext("must provide at least one snapshot name\n"));
8168 usage(B_FALSE);
8171 if (argc > 2) {
8172 (void) fprintf(stderr, gettext("too many arguments\n"));
8173 usage(B_FALSE);
8176 fromsnap = argv[0];
8177 tosnap = (argc == 2) ? argv[1] : NULL;
8179 copy = NULL;
8180 if (*fromsnap != '@')
8181 copy = strdup(fromsnap);
8182 else if (tosnap)
8183 copy = strdup(tosnap);
8184 if (copy == NULL)
8185 usage(B_FALSE);
8187 if ((atp = strchr(copy, '@')) != NULL)
8188 *atp = '\0';
8190 if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL) {
8191 free(copy);
8192 return (1);
8194 free(copy);
8197 * Ignore SIGPIPE so that the library can give us
8198 * information on any failure
8200 if (sigemptyset(&sa.sa_mask) == -1) {
8201 err = errno;
8202 goto out;
8204 sa.sa_flags = 0;
8205 sa.sa_handler = SIG_IGN;
8206 if (sigaction(SIGPIPE, &sa, NULL) == -1) {
8207 err = errno;
8208 goto out;
8211 err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
8212 out:
8213 zfs_close(zhp);
8215 return (err != 0);
8219 * zfs bookmark <fs@source>|<fs#source> <fs#bookmark>
8221 * Creates a bookmark with the given name from the source snapshot
8222 * or creates a copy of an existing source bookmark.
8224 static int
8225 zfs_do_bookmark(int argc, char **argv)
8227 char *source, *bookname;
8228 char expbuf[ZFS_MAX_DATASET_NAME_LEN];
8229 int source_type;
8230 nvlist_t *nvl;
8231 int ret = 0;
8232 int c;
8234 /* check options */
8235 while ((c = getopt(argc, argv, "")) != -1) {
8236 switch (c) {
8237 case '?':
8238 (void) fprintf(stderr,
8239 gettext("invalid option '%c'\n"), optopt);
8240 goto usage;
8244 argc -= optind;
8245 argv += optind;
8247 /* check number of arguments */
8248 if (argc < 1) {
8249 (void) fprintf(stderr, gettext("missing source argument\n"));
8250 goto usage;
8252 if (argc < 2) {
8253 (void) fprintf(stderr, gettext("missing bookmark argument\n"));
8254 goto usage;
8257 source = argv[0];
8258 bookname = argv[1];
8260 if (strchr(source, '@') == NULL && strchr(source, '#') == NULL) {
8261 (void) fprintf(stderr,
8262 gettext("invalid source name '%s': "
8263 "must contain a '@' or '#'\n"), source);
8264 goto usage;
8266 if (strchr(bookname, '#') == NULL) {
8267 (void) fprintf(stderr,
8268 gettext("invalid bookmark name '%s': "
8269 "must contain a '#'\n"), bookname);
8270 goto usage;
8274 * expand source or bookname to full path:
8275 * one of them may be specified as short name
8278 char **expand;
8279 char *source_short, *bookname_short;
8280 source_short = strpbrk(source, "@#");
8281 bookname_short = strpbrk(bookname, "#");
8282 if (source_short == source &&
8283 bookname_short == bookname) {
8284 (void) fprintf(stderr, gettext(
8285 "either source or bookmark must be specified as "
8286 "full dataset paths"));
8287 goto usage;
8288 } else if (source_short != source &&
8289 bookname_short != bookname) {
8290 expand = NULL;
8291 } else if (source_short != source) {
8292 strlcpy(expbuf, source, sizeof (expbuf));
8293 expand = &bookname;
8294 } else if (bookname_short != bookname) {
8295 strlcpy(expbuf, bookname, sizeof (expbuf));
8296 expand = &source;
8297 } else {
8298 abort();
8300 if (expand != NULL) {
8301 *strpbrk(expbuf, "@#") = '\0'; /* dataset name in buf */
8302 (void) strlcat(expbuf, *expand, sizeof (expbuf));
8303 *expand = expbuf;
8307 /* determine source type */
8308 switch (*strpbrk(source, "@#")) {
8309 case '@': source_type = ZFS_TYPE_SNAPSHOT; break;
8310 case '#': source_type = ZFS_TYPE_BOOKMARK; break;
8311 default: abort();
8314 /* test the source exists */
8315 zfs_handle_t *zhp;
8316 zhp = zfs_open(g_zfs, source, source_type);
8317 if (zhp == NULL)
8318 goto usage;
8319 zfs_close(zhp);
8321 nvl = fnvlist_alloc();
8322 fnvlist_add_string(nvl, bookname, source);
8323 ret = lzc_bookmark(nvl, NULL);
8324 fnvlist_free(nvl);
8326 if (ret != 0) {
8327 const char *err_msg = NULL;
8328 char errbuf[1024];
8330 (void) snprintf(errbuf, sizeof (errbuf),
8331 dgettext(TEXT_DOMAIN,
8332 "cannot create bookmark '%s'"), bookname);
8334 switch (ret) {
8335 case EXDEV:
8336 err_msg = "bookmark is in a different pool";
8337 break;
8338 case ZFS_ERR_BOOKMARK_SOURCE_NOT_ANCESTOR:
8339 err_msg = "source is not an ancestor of the "
8340 "new bookmark's dataset";
8341 break;
8342 case EEXIST:
8343 err_msg = "bookmark exists";
8344 break;
8345 case EINVAL:
8346 err_msg = "invalid argument";
8347 break;
8348 case ENOTSUP:
8349 err_msg = "bookmark feature not enabled";
8350 break;
8351 case ENOSPC:
8352 err_msg = "out of space";
8353 break;
8354 case ENOENT:
8355 err_msg = "dataset does not exist";
8356 break;
8357 default:
8358 (void) zfs_standard_error(g_zfs, ret, errbuf);
8359 break;
8361 if (err_msg != NULL) {
8362 (void) fprintf(stderr, "%s: %s\n", errbuf,
8363 dgettext(TEXT_DOMAIN, err_msg));
8367 return (ret != 0);
8369 usage:
8370 usage(B_FALSE);
8371 return (-1);
8374 static int
8375 zfs_do_channel_program(int argc, char **argv)
8377 int ret, fd, c;
8378 size_t progsize, progread;
8379 nvlist_t *outnvl = NULL;
8380 uint64_t instrlimit = ZCP_DEFAULT_INSTRLIMIT;
8381 uint64_t memlimit = ZCP_DEFAULT_MEMLIMIT;
8382 boolean_t sync_flag = B_TRUE, json_output = B_FALSE;
8383 zpool_handle_t *zhp;
8385 struct option long_options[] = {
8386 {"json", no_argument, NULL, 'j'},
8387 {0, 0, 0, 0}
8390 /* check options */
8391 while ((c = getopt_long(argc, argv, "nt:m:j", long_options,
8392 NULL)) != -1) {
8393 switch (c) {
8394 case 't':
8395 case 'm': {
8396 uint64_t arg;
8397 char *endp;
8399 errno = 0;
8400 arg = strtoull(optarg, &endp, 0);
8401 if (errno != 0 || *endp != '\0') {
8402 (void) fprintf(stderr, gettext(
8403 "invalid argument "
8404 "'%s': expected integer\n"), optarg);
8405 goto usage;
8408 if (c == 't') {
8409 instrlimit = arg;
8410 } else {
8411 ASSERT3U(c, ==, 'm');
8412 memlimit = arg;
8414 break;
8416 case 'n': {
8417 sync_flag = B_FALSE;
8418 break;
8420 case 'j': {
8421 json_output = B_TRUE;
8422 break;
8424 case '?':
8425 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8426 optopt);
8427 goto usage;
8431 argc -= optind;
8432 argv += optind;
8434 if (argc < 2) {
8435 (void) fprintf(stderr,
8436 gettext("invalid number of arguments\n"));
8437 goto usage;
8440 const char *poolname = argv[0];
8441 const char *filename = argv[1];
8442 if (strcmp(filename, "-") == 0) {
8443 fd = 0;
8444 filename = "standard input";
8445 } else if ((fd = open(filename, O_RDONLY)) < 0) {
8446 (void) fprintf(stderr, gettext("cannot open '%s': %s\n"),
8447 filename, strerror(errno));
8448 return (1);
8451 if ((zhp = zpool_open(g_zfs, poolname)) == NULL) {
8452 (void) fprintf(stderr, gettext("cannot open pool '%s'\n"),
8453 poolname);
8454 if (fd != 0)
8455 (void) close(fd);
8456 return (1);
8458 zpool_close(zhp);
8461 * Read in the channel program, expanding the program buffer as
8462 * necessary.
8464 progread = 0;
8465 progsize = 1024;
8466 char *progbuf = safe_malloc(progsize);
8467 do {
8468 ret = read(fd, progbuf + progread, progsize - progread);
8469 progread += ret;
8470 if (progread == progsize && ret > 0) {
8471 progsize *= 2;
8472 progbuf = safe_realloc(progbuf, progsize);
8474 } while (ret > 0);
8476 if (fd != 0)
8477 (void) close(fd);
8478 if (ret < 0) {
8479 free(progbuf);
8480 (void) fprintf(stderr,
8481 gettext("cannot read '%s': %s\n"),
8482 filename, strerror(errno));
8483 return (1);
8485 progbuf[progread] = '\0';
8488 * Any remaining arguments are passed as arguments to the lua script as
8489 * a string array:
8491 * "argv" -> [ "arg 1", ... "arg n" ],
8494 nvlist_t *argnvl = fnvlist_alloc();
8495 fnvlist_add_string_array(argnvl, ZCP_ARG_CLIARGV,
8496 (const char **)argv + 2, argc - 2);
8498 if (sync_flag) {
8499 ret = lzc_channel_program(poolname, progbuf,
8500 instrlimit, memlimit, argnvl, &outnvl);
8501 } else {
8502 ret = lzc_channel_program_nosync(poolname, progbuf,
8503 instrlimit, memlimit, argnvl, &outnvl);
8506 if (ret != 0) {
8508 * On error, report the error message handed back by lua if one
8509 * exists. Otherwise, generate an appropriate error message,
8510 * falling back on strerror() for an unexpected return code.
8512 const char *errstring = NULL;
8513 const char *msg = gettext("Channel program execution failed");
8514 uint64_t instructions = 0;
8515 if (outnvl != NULL && nvlist_exists(outnvl, ZCP_RET_ERROR)) {
8516 const char *es = NULL;
8517 (void) nvlist_lookup_string(outnvl,
8518 ZCP_RET_ERROR, &es);
8519 if (es == NULL)
8520 errstring = strerror(ret);
8521 else
8522 errstring = es;
8523 if (ret == ETIME) {
8524 (void) nvlist_lookup_uint64(outnvl,
8525 ZCP_ARG_INSTRLIMIT, &instructions);
8527 } else {
8528 switch (ret) {
8529 case EINVAL:
8530 errstring =
8531 "Invalid instruction or memory limit.";
8532 break;
8533 case ENOMEM:
8534 errstring = "Return value too large.";
8535 break;
8536 case ENOSPC:
8537 errstring = "Memory limit exhausted.";
8538 break;
8539 case ETIME:
8540 errstring = "Timed out.";
8541 break;
8542 case EPERM:
8543 errstring = "Permission denied. Channel "
8544 "programs must be run as root.";
8545 break;
8546 default:
8547 (void) zfs_standard_error(g_zfs, ret, msg);
8550 if (errstring != NULL)
8551 (void) fprintf(stderr, "%s:\n%s\n", msg, errstring);
8553 if (ret == ETIME && instructions != 0)
8554 (void) fprintf(stderr,
8555 gettext("%llu Lua instructions\n"),
8556 (u_longlong_t)instructions);
8557 } else {
8558 if (json_output) {
8559 (void) nvlist_print_json(stdout, outnvl);
8560 } else if (nvlist_empty(outnvl)) {
8561 (void) fprintf(stdout, gettext("Channel program fully "
8562 "executed and did not produce output.\n"));
8563 } else {
8564 (void) fprintf(stdout, gettext("Channel program fully "
8565 "executed and produced output:\n"));
8566 dump_nvlist(outnvl, 4);
8570 free(progbuf);
8571 fnvlist_free(outnvl);
8572 fnvlist_free(argnvl);
8573 return (ret != 0);
8575 usage:
8576 usage(B_FALSE);
8577 return (-1);
8581 typedef struct loadkey_cbdata {
8582 boolean_t cb_loadkey;
8583 boolean_t cb_recursive;
8584 boolean_t cb_noop;
8585 char *cb_keylocation;
8586 uint64_t cb_numfailed;
8587 uint64_t cb_numattempted;
8588 } loadkey_cbdata_t;
8590 static int
8591 load_key_callback(zfs_handle_t *zhp, void *data)
8593 int ret;
8594 boolean_t is_encroot;
8595 loadkey_cbdata_t *cb = data;
8596 uint64_t keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
8599 * If we are working recursively, we want to skip loading / unloading
8600 * keys for non-encryption roots and datasets whose keys are already
8601 * in the desired end-state.
8603 if (cb->cb_recursive) {
8604 ret = zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
8605 if (ret != 0)
8606 return (ret);
8607 if (!is_encroot)
8608 return (0);
8610 if ((cb->cb_loadkey && keystatus == ZFS_KEYSTATUS_AVAILABLE) ||
8611 (!cb->cb_loadkey && keystatus == ZFS_KEYSTATUS_UNAVAILABLE))
8612 return (0);
8615 cb->cb_numattempted++;
8617 if (cb->cb_loadkey)
8618 ret = zfs_crypto_load_key(zhp, cb->cb_noop, cb->cb_keylocation);
8619 else
8620 ret = zfs_crypto_unload_key(zhp);
8622 if (ret != 0) {
8623 cb->cb_numfailed++;
8624 return (ret);
8627 return (0);
8630 static int
8631 load_unload_keys(int argc, char **argv, boolean_t loadkey)
8633 int c, ret = 0, flags = 0;
8634 boolean_t do_all = B_FALSE;
8635 loadkey_cbdata_t cb = { 0 };
8637 cb.cb_loadkey = loadkey;
8639 while ((c = getopt(argc, argv, "anrL:")) != -1) {
8640 /* noop and alternate keylocations only apply to zfs load-key */
8641 if (loadkey) {
8642 switch (c) {
8643 case 'n':
8644 cb.cb_noop = B_TRUE;
8645 continue;
8646 case 'L':
8647 cb.cb_keylocation = optarg;
8648 continue;
8649 default:
8650 break;
8654 switch (c) {
8655 case 'a':
8656 do_all = B_TRUE;
8657 cb.cb_recursive = B_TRUE;
8658 break;
8659 case 'r':
8660 flags |= ZFS_ITER_RECURSE;
8661 cb.cb_recursive = B_TRUE;
8662 break;
8663 default:
8664 (void) fprintf(stderr,
8665 gettext("invalid option '%c'\n"), optopt);
8666 usage(B_FALSE);
8670 argc -= optind;
8671 argv += optind;
8673 if (!do_all && argc == 0) {
8674 (void) fprintf(stderr,
8675 gettext("Missing dataset argument or -a option\n"));
8676 usage(B_FALSE);
8679 if (do_all && argc != 0) {
8680 (void) fprintf(stderr,
8681 gettext("Cannot specify dataset with -a option\n"));
8682 usage(B_FALSE);
8685 if (cb.cb_recursive && cb.cb_keylocation != NULL &&
8686 strcmp(cb.cb_keylocation, "prompt") != 0) {
8687 (void) fprintf(stderr, gettext("alternate keylocation may only "
8688 "be 'prompt' with -r or -a\n"));
8689 usage(B_FALSE);
8692 ret = zfs_for_each(argc, argv, flags,
8693 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME, NULL, NULL, 0,
8694 load_key_callback, &cb);
8696 if (cb.cb_noop || (cb.cb_recursive && cb.cb_numattempted != 0)) {
8697 (void) printf(gettext("%llu / %llu key(s) successfully %s\n"),
8698 (u_longlong_t)(cb.cb_numattempted - cb.cb_numfailed),
8699 (u_longlong_t)cb.cb_numattempted,
8700 loadkey ? (cb.cb_noop ? "verified" : "loaded") :
8701 "unloaded");
8704 if (cb.cb_numfailed != 0)
8705 ret = -1;
8707 return (ret);
8710 static int
8711 zfs_do_load_key(int argc, char **argv)
8713 return (load_unload_keys(argc, argv, B_TRUE));
8717 static int
8718 zfs_do_unload_key(int argc, char **argv)
8720 return (load_unload_keys(argc, argv, B_FALSE));
8723 static int
8724 zfs_do_change_key(int argc, char **argv)
8726 int c, ret;
8727 uint64_t keystatus;
8728 boolean_t loadkey = B_FALSE, inheritkey = B_FALSE;
8729 zfs_handle_t *zhp = NULL;
8730 nvlist_t *props = fnvlist_alloc();
8732 while ((c = getopt(argc, argv, "lio:")) != -1) {
8733 switch (c) {
8734 case 'l':
8735 loadkey = B_TRUE;
8736 break;
8737 case 'i':
8738 inheritkey = B_TRUE;
8739 break;
8740 case 'o':
8741 if (!parseprop(props, optarg)) {
8742 nvlist_free(props);
8743 return (1);
8745 break;
8746 default:
8747 (void) fprintf(stderr,
8748 gettext("invalid option '%c'\n"), optopt);
8749 usage(B_FALSE);
8753 if (inheritkey && !nvlist_empty(props)) {
8754 (void) fprintf(stderr,
8755 gettext("Properties not allowed for inheriting\n"));
8756 usage(B_FALSE);
8759 argc -= optind;
8760 argv += optind;
8762 if (argc < 1) {
8763 (void) fprintf(stderr, gettext("Missing dataset argument\n"));
8764 usage(B_FALSE);
8767 if (argc > 1) {
8768 (void) fprintf(stderr, gettext("Too many arguments\n"));
8769 usage(B_FALSE);
8772 zhp = zfs_open(g_zfs, argv[argc - 1],
8773 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
8774 if (zhp == NULL)
8775 usage(B_FALSE);
8777 if (loadkey) {
8778 keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
8779 if (keystatus != ZFS_KEYSTATUS_AVAILABLE) {
8780 ret = zfs_crypto_load_key(zhp, B_FALSE, NULL);
8781 if (ret != 0) {
8782 nvlist_free(props);
8783 zfs_close(zhp);
8784 return (-1);
8788 /* refresh the properties so the new keystatus is visible */
8789 zfs_refresh_properties(zhp);
8792 ret = zfs_crypto_rewrap(zhp, props, inheritkey);
8793 if (ret != 0) {
8794 nvlist_free(props);
8795 zfs_close(zhp);
8796 return (-1);
8799 nvlist_free(props);
8800 zfs_close(zhp);
8801 return (0);
8805 * 1) zfs project [-d|-r] <file|directory ...>
8806 * List project ID and inherit flag of file(s) or directories.
8807 * -d: List the directory itself, not its children.
8808 * -r: List subdirectories recursively.
8810 * 2) zfs project -C [-k] [-r] <file|directory ...>
8811 * Clear project inherit flag and/or ID on the file(s) or directories.
8812 * -k: Keep the project ID unchanged. If not specified, the project ID
8813 * will be reset as zero.
8814 * -r: Clear on subdirectories recursively.
8816 * 3) zfs project -c [-0] [-d|-r] [-p id] <file|directory ...>
8817 * Check project ID and inherit flag on the file(s) or directories,
8818 * report the outliers.
8819 * -0: Print file name followed by a NUL instead of newline.
8820 * -d: Check the directory itself, not its children.
8821 * -p: Specify the referenced ID for comparing with the target file(s)
8822 * or directories' project IDs. If not specified, the target (top)
8823 * directory's project ID will be used as the referenced one.
8824 * -r: Check subdirectories recursively.
8826 * 4) zfs project [-p id] [-r] [-s] <file|directory ...>
8827 * Set project ID and/or inherit flag on the file(s) or directories.
8828 * -p: Set the project ID as the given id.
8829 * -r: Set on subdirectories recursively. If not specify "-p" option,
8830 * it will use top-level directory's project ID as the given id,
8831 * then set both project ID and inherit flag on all descendants
8832 * of the top-level directory.
8833 * -s: Set project inherit flag.
8835 static int
8836 zfs_do_project(int argc, char **argv)
8838 zfs_project_control_t zpc = {
8839 .zpc_expected_projid = ZFS_INVALID_PROJID,
8840 .zpc_op = ZFS_PROJECT_OP_DEFAULT,
8841 .zpc_dironly = B_FALSE,
8842 .zpc_keep_projid = B_FALSE,
8843 .zpc_newline = B_TRUE,
8844 .zpc_recursive = B_FALSE,
8845 .zpc_set_flag = B_FALSE,
8847 int ret = 0, c;
8849 if (argc < 2)
8850 usage(B_FALSE);
8852 while ((c = getopt(argc, argv, "0Ccdkp:rs")) != -1) {
8853 switch (c) {
8854 case '0':
8855 zpc.zpc_newline = B_FALSE;
8856 break;
8857 case 'C':
8858 if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8859 (void) fprintf(stderr, gettext("cannot "
8860 "specify '-C' '-c' '-s' together\n"));
8861 usage(B_FALSE);
8864 zpc.zpc_op = ZFS_PROJECT_OP_CLEAR;
8865 break;
8866 case 'c':
8867 if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8868 (void) fprintf(stderr, gettext("cannot "
8869 "specify '-C' '-c' '-s' together\n"));
8870 usage(B_FALSE);
8873 zpc.zpc_op = ZFS_PROJECT_OP_CHECK;
8874 break;
8875 case 'd':
8876 zpc.zpc_dironly = B_TRUE;
8877 /* overwrite "-r" option */
8878 zpc.zpc_recursive = B_FALSE;
8879 break;
8880 case 'k':
8881 zpc.zpc_keep_projid = B_TRUE;
8882 break;
8883 case 'p': {
8884 char *endptr;
8886 errno = 0;
8887 zpc.zpc_expected_projid = strtoull(optarg, &endptr, 0);
8888 if (errno != 0 || *endptr != '\0') {
8889 (void) fprintf(stderr,
8890 gettext("project ID must be less than "
8891 "%u\n"), UINT32_MAX);
8892 usage(B_FALSE);
8894 if (zpc.zpc_expected_projid >= UINT32_MAX) {
8895 (void) fprintf(stderr,
8896 gettext("invalid project ID\n"));
8897 usage(B_FALSE);
8899 break;
8901 case 'r':
8902 zpc.zpc_recursive = B_TRUE;
8903 /* overwrite "-d" option */
8904 zpc.zpc_dironly = B_FALSE;
8905 break;
8906 case 's':
8907 if (zpc.zpc_op != ZFS_PROJECT_OP_DEFAULT) {
8908 (void) fprintf(stderr, gettext("cannot "
8909 "specify '-C' '-c' '-s' together\n"));
8910 usage(B_FALSE);
8913 zpc.zpc_set_flag = B_TRUE;
8914 zpc.zpc_op = ZFS_PROJECT_OP_SET;
8915 break;
8916 default:
8917 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
8918 optopt);
8919 usage(B_FALSE);
8923 if (zpc.zpc_op == ZFS_PROJECT_OP_DEFAULT) {
8924 if (zpc.zpc_expected_projid != ZFS_INVALID_PROJID)
8925 zpc.zpc_op = ZFS_PROJECT_OP_SET;
8926 else
8927 zpc.zpc_op = ZFS_PROJECT_OP_LIST;
8930 switch (zpc.zpc_op) {
8931 case ZFS_PROJECT_OP_LIST:
8932 if (zpc.zpc_keep_projid) {
8933 (void) fprintf(stderr,
8934 gettext("'-k' is only valid together with '-C'\n"));
8935 usage(B_FALSE);
8937 if (!zpc.zpc_newline) {
8938 (void) fprintf(stderr,
8939 gettext("'-0' is only valid together with '-c'\n"));
8940 usage(B_FALSE);
8942 break;
8943 case ZFS_PROJECT_OP_CHECK:
8944 if (zpc.zpc_keep_projid) {
8945 (void) fprintf(stderr,
8946 gettext("'-k' is only valid together with '-C'\n"));
8947 usage(B_FALSE);
8949 break;
8950 case ZFS_PROJECT_OP_CLEAR:
8951 if (zpc.zpc_dironly) {
8952 (void) fprintf(stderr,
8953 gettext("'-d' is useless together with '-C'\n"));
8954 usage(B_FALSE);
8956 if (!zpc.zpc_newline) {
8957 (void) fprintf(stderr,
8958 gettext("'-0' is only valid together with '-c'\n"));
8959 usage(B_FALSE);
8961 if (zpc.zpc_expected_projid != ZFS_INVALID_PROJID) {
8962 (void) fprintf(stderr,
8963 gettext("'-p' is useless together with '-C'\n"));
8964 usage(B_FALSE);
8966 break;
8967 case ZFS_PROJECT_OP_SET:
8968 if (zpc.zpc_dironly) {
8969 (void) fprintf(stderr,
8970 gettext("'-d' is useless for set project ID and/or "
8971 "inherit flag\n"));
8972 usage(B_FALSE);
8974 if (zpc.zpc_keep_projid) {
8975 (void) fprintf(stderr,
8976 gettext("'-k' is only valid together with '-C'\n"));
8977 usage(B_FALSE);
8979 if (!zpc.zpc_newline) {
8980 (void) fprintf(stderr,
8981 gettext("'-0' is only valid together with '-c'\n"));
8982 usage(B_FALSE);
8984 break;
8985 default:
8986 ASSERT(0);
8987 break;
8990 argv += optind;
8991 argc -= optind;
8992 if (argc == 0) {
8993 (void) fprintf(stderr,
8994 gettext("missing file or directory target(s)\n"));
8995 usage(B_FALSE);
8998 for (int i = 0; i < argc; i++) {
8999 int err;
9001 err = zfs_project_handle(argv[i], &zpc);
9002 if (err && !ret)
9003 ret = err;
9006 return (ret);
9009 static int
9010 zfs_do_wait(int argc, char **argv)
9012 boolean_t enabled[ZFS_WAIT_NUM_ACTIVITIES];
9013 int error = 0, i;
9014 int c;
9016 /* By default, wait for all types of activity. */
9017 for (i = 0; i < ZFS_WAIT_NUM_ACTIVITIES; i++)
9018 enabled[i] = B_TRUE;
9020 while ((c = getopt(argc, argv, "t:")) != -1) {
9021 switch (c) {
9022 case 't':
9023 /* Reset activities array */
9024 memset(&enabled, 0, sizeof (enabled));
9026 for (char *tok; (tok = strsep(&optarg, ",")); ) {
9027 static const char *const col_subopts[
9028 ZFS_WAIT_NUM_ACTIVITIES] = { "deleteq" };
9030 for (i = 0; i < ARRAY_SIZE(col_subopts); ++i)
9031 if (strcmp(tok, col_subopts[i]) == 0) {
9032 enabled[i] = B_TRUE;
9033 goto found;
9036 (void) fprintf(stderr,
9037 gettext("invalid activity '%s'\n"), tok);
9038 usage(B_FALSE);
9039 found:;
9041 break;
9042 case '?':
9043 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
9044 optopt);
9045 usage(B_FALSE);
9049 argv += optind;
9050 argc -= optind;
9051 if (argc < 1) {
9052 (void) fprintf(stderr, gettext("missing 'filesystem' "
9053 "argument\n"));
9054 usage(B_FALSE);
9056 if (argc > 1) {
9057 (void) fprintf(stderr, gettext("too many arguments\n"));
9058 usage(B_FALSE);
9061 zfs_handle_t *zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM);
9062 if (zhp == NULL)
9063 return (1);
9065 for (;;) {
9066 boolean_t missing = B_FALSE;
9067 boolean_t any_waited = B_FALSE;
9069 for (int i = 0; i < ZFS_WAIT_NUM_ACTIVITIES; i++) {
9070 boolean_t waited;
9072 if (!enabled[i])
9073 continue;
9075 error = zfs_wait_status(zhp, i, &missing, &waited);
9076 if (error != 0 || missing)
9077 break;
9079 any_waited = (any_waited || waited);
9082 if (error != 0 || missing || !any_waited)
9083 break;
9086 zfs_close(zhp);
9088 return (error);
9092 * Display version message
9094 static int
9095 zfs_do_version(int argc, char **argv)
9097 int c;
9098 nvlist_t *jsobj = NULL, *zfs_ver = NULL;
9099 boolean_t json = B_FALSE;
9101 struct option long_options[] = {
9102 {"json", no_argument, NULL, 'j'},
9103 {0, 0, 0, 0}
9106 while ((c = getopt_long(argc, argv, "j", long_options, NULL)) != -1) {
9107 switch (c) {
9108 case 'j':
9109 json = B_TRUE;
9110 jsobj = zfs_json_schema(0, 1);
9111 break;
9112 case '?':
9113 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
9114 optopt);
9115 usage(B_FALSE);
9119 argc -= optind;
9120 if (argc != 0) {
9121 (void) fprintf(stderr, "too many arguments\n");
9122 usage(B_FALSE);
9125 if (json) {
9126 zfs_ver = zfs_version_nvlist();
9127 if (zfs_ver) {
9128 fnvlist_add_nvlist(jsobj, "zfs_version", zfs_ver);
9129 zcmd_print_json(jsobj);
9130 fnvlist_free(zfs_ver);
9131 return (0);
9132 } else
9133 return (-1);
9134 } else
9135 return (zfs_version_print() != 0);
9138 /* Display documentation */
9139 static int
9140 zfs_do_help(int argc, char **argv)
9142 char page[MAXNAMELEN];
9143 if (argc < 3 || strcmp(argv[2], "zfs") == 0)
9144 strcpy(page, "zfs");
9145 else if (strcmp(argv[2], "concepts") == 0 ||
9146 strcmp(argv[2], "props") == 0)
9147 snprintf(page, sizeof (page), "zfs%s", argv[2]);
9148 else
9149 snprintf(page, sizeof (page), "zfs-%s", argv[2]);
9151 execlp("man", "man", page, NULL);
9153 fprintf(stderr, "couldn't run man program: %s", strerror(errno));
9154 return (-1);
9158 main(int argc, char **argv)
9160 int ret = 0;
9161 int i = 0;
9162 const char *cmdname;
9163 char **newargv;
9165 (void) setlocale(LC_ALL, "");
9166 (void) setlocale(LC_NUMERIC, "C");
9167 (void) textdomain(TEXT_DOMAIN);
9169 opterr = 0;
9172 * Make sure the user has specified some command.
9174 if (argc < 2) {
9175 (void) fprintf(stderr, gettext("missing command\n"));
9176 usage(B_FALSE);
9179 cmdname = argv[1];
9182 * The 'umount' command is an alias for 'unmount'
9184 if (strcmp(cmdname, "umount") == 0)
9185 cmdname = "unmount";
9188 * The 'recv' command is an alias for 'receive'
9190 if (strcmp(cmdname, "recv") == 0)
9191 cmdname = "receive";
9194 * The 'snap' command is an alias for 'snapshot'
9196 if (strcmp(cmdname, "snap") == 0)
9197 cmdname = "snapshot";
9200 * Special case '-?'
9202 if ((strcmp(cmdname, "-?") == 0) ||
9203 (strcmp(cmdname, "--help") == 0))
9204 usage(B_TRUE);
9207 * Special case '-V|--version'
9209 if ((strcmp(cmdname, "-V") == 0) || (strcmp(cmdname, "--version") == 0))
9210 return (zfs_version_print() != 0);
9213 * Special case 'help'
9215 if (strcmp(cmdname, "help") == 0)
9216 return (zfs_do_help(argc, argv));
9218 if ((g_zfs = libzfs_init()) == NULL) {
9219 (void) fprintf(stderr, "%s\n", libzfs_error_init(errno));
9220 return (1);
9223 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
9225 libzfs_print_on_error(g_zfs, B_TRUE);
9227 zfs_setproctitle_init(argc, argv, environ);
9230 * Many commands modify input strings for string parsing reasons.
9231 * We create a copy to protect the original argv.
9233 newargv = safe_malloc((argc + 1) * sizeof (newargv[0]));
9234 for (i = 0; i < argc; i++)
9235 newargv[i] = strdup(argv[i]);
9236 newargv[argc] = NULL;
9239 * Run the appropriate command.
9241 libzfs_mnttab_cache(g_zfs, B_TRUE);
9242 if (find_command_idx(cmdname, &i) == 0) {
9243 current_command = &command_table[i];
9244 ret = command_table[i].func(argc - 1, newargv + 1);
9245 } else if (strchr(cmdname, '=') != NULL) {
9246 verify(find_command_idx("set", &i) == 0);
9247 current_command = &command_table[i];
9248 ret = command_table[i].func(argc, newargv);
9249 } else {
9250 (void) fprintf(stderr, gettext("unrecognized "
9251 "command '%s'\n"), cmdname);
9252 usage(B_FALSE);
9253 ret = 1;
9256 for (i = 0; i < argc; i++)
9257 free(newargv[i]);
9258 free(newargv);
9260 if (ret == 0 && log_history)
9261 (void) zpool_log_history(g_zfs, history_str);
9263 libzfs_fini(g_zfs);
9266 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
9267 * for the purposes of running ::findleaks.
9269 if (getenv("ZFS_ABORT") != NULL) {
9270 (void) printf("dumping core by request\n");
9271 abort();
9274 return (ret);
9278 * zfs zone nsfile filesystem
9280 * Add or delete the given dataset to/from the namespace.
9282 #ifdef __linux__
9283 static int
9284 zfs_do_zone_impl(int argc, char **argv, boolean_t attach)
9286 zfs_handle_t *zhp;
9287 int ret;
9289 if (argc < 3) {
9290 (void) fprintf(stderr, gettext("missing argument(s)\n"));
9291 usage(B_FALSE);
9293 if (argc > 3) {
9294 (void) fprintf(stderr, gettext("too many arguments\n"));
9295 usage(B_FALSE);
9298 zhp = zfs_open(g_zfs, argv[2], ZFS_TYPE_FILESYSTEM);
9299 if (zhp == NULL)
9300 return (1);
9302 ret = (zfs_userns(zhp, argv[1], attach) != 0);
9304 zfs_close(zhp);
9305 return (ret);
9308 static int
9309 zfs_do_zone(int argc, char **argv)
9311 return (zfs_do_zone_impl(argc, argv, B_TRUE));
9314 static int
9315 zfs_do_unzone(int argc, char **argv)
9317 return (zfs_do_zone_impl(argc, argv, B_FALSE));
9319 #endif
9321 #ifdef __FreeBSD__
9322 #include <sys/jail.h>
9323 #include <jail.h>
9325 * Attach/detach the given dataset to/from the given jail
9327 static int
9328 zfs_do_jail_impl(int argc, char **argv, boolean_t attach)
9330 zfs_handle_t *zhp;
9331 int jailid, ret;
9333 /* check number of arguments */
9334 if (argc < 3) {
9335 (void) fprintf(stderr, gettext("missing argument(s)\n"));
9336 usage(B_FALSE);
9338 if (argc > 3) {
9339 (void) fprintf(stderr, gettext("too many arguments\n"));
9340 usage(B_FALSE);
9343 jailid = jail_getid(argv[1]);
9344 if (jailid < 0) {
9345 (void) fprintf(stderr, gettext("invalid jail id or name\n"));
9346 usage(B_FALSE);
9349 zhp = zfs_open(g_zfs, argv[2], ZFS_TYPE_FILESYSTEM);
9350 if (zhp == NULL)
9351 return (1);
9353 ret = (zfs_jail(zhp, jailid, attach) != 0);
9355 zfs_close(zhp);
9356 return (ret);
9360 * zfs jail jailid filesystem
9362 * Attach the given dataset to the given jail
9364 static int
9365 zfs_do_jail(int argc, char **argv)
9367 return (zfs_do_jail_impl(argc, argv, B_TRUE));
9371 * zfs unjail jailid filesystem
9373 * Detach the given dataset from the given jail
9375 static int
9376 zfs_do_unjail(int argc, char **argv)
9378 return (zfs_do_jail_impl(argc, argv, B_FALSE));
9380 #endif