Fix false assertion in dmu_tx_dirty_buf() on cloning
[zfs.git] / lib / libzfs / libzfs_util.c
blob7cc91f984a4002f0349e9b2c19104b59bbe30cda
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 2020 Joyent, Inc. All rights reserved.
25 * Copyright (c) 2011, 2024 by Delphix. All rights reserved.
26 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
27 * Copyright (c) 2017 Datto Inc.
28 * Copyright (c) 2020 The FreeBSD Foundation
30 * Portions of this software were developed by Allan Jude
31 * under sponsorship from the FreeBSD Foundation.
35 * Internal utility routines for the ZFS library.
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <libintl.h>
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <strings.h>
45 #include <unistd.h>
46 #include <math.h>
47 #if LIBFETCH_DYNAMIC
48 #include <dlfcn.h>
49 #endif
50 #include <sys/stat.h>
51 #include <sys/mnttab.h>
52 #include <sys/mntent.h>
53 #include <sys/types.h>
54 #include <sys/wait.h>
56 #include <libzfs.h>
57 #include <libzfs_core.h>
59 #include "libzfs_impl.h"
60 #include "zfs_prop.h"
61 #include "zfeature_common.h"
62 #include <zfs_fletcher.h>
63 #include <libzutil.h>
66 * We only care about the scheme in order to match the scheme
67 * with the handler. Each handler should validate the full URI
68 * as necessary.
70 #define URI_REGEX "^\\([A-Za-z][A-Za-z0-9+.\\-]*\\):"
71 #define STR_NUMS "0123456789"
73 int
74 libzfs_errno(libzfs_handle_t *hdl)
76 return (hdl->libzfs_error);
79 const char *
80 libzfs_error_action(libzfs_handle_t *hdl)
82 return (hdl->libzfs_action);
85 const char *
86 libzfs_error_description(libzfs_handle_t *hdl)
88 if (hdl->libzfs_desc[0] != '\0')
89 return (hdl->libzfs_desc);
91 switch (hdl->libzfs_error) {
92 case EZFS_NOMEM:
93 return (dgettext(TEXT_DOMAIN, "out of memory"));
94 case EZFS_BADPROP:
95 return (dgettext(TEXT_DOMAIN, "invalid property value"));
96 case EZFS_PROPREADONLY:
97 return (dgettext(TEXT_DOMAIN, "read-only property"));
98 case EZFS_PROPTYPE:
99 return (dgettext(TEXT_DOMAIN, "property doesn't apply to "
100 "datasets of this type"));
101 case EZFS_PROPNONINHERIT:
102 return (dgettext(TEXT_DOMAIN, "property cannot be inherited"));
103 case EZFS_PROPSPACE:
104 return (dgettext(TEXT_DOMAIN, "invalid quota or reservation"));
105 case EZFS_BADTYPE:
106 return (dgettext(TEXT_DOMAIN, "operation not applicable to "
107 "datasets of this type"));
108 case EZFS_BUSY:
109 return (dgettext(TEXT_DOMAIN, "pool or dataset is busy"));
110 case EZFS_EXISTS:
111 return (dgettext(TEXT_DOMAIN, "pool or dataset exists"));
112 case EZFS_NOENT:
113 return (dgettext(TEXT_DOMAIN, "no such pool or dataset"));
114 case EZFS_BADSTREAM:
115 return (dgettext(TEXT_DOMAIN, "invalid backup stream"));
116 case EZFS_DSREADONLY:
117 return (dgettext(TEXT_DOMAIN, "dataset is read-only"));
118 case EZFS_VOLTOOBIG:
119 return (dgettext(TEXT_DOMAIN, "volume size exceeds limit for "
120 "this system"));
121 case EZFS_INVALIDNAME:
122 return (dgettext(TEXT_DOMAIN, "invalid name"));
123 case EZFS_BADRESTORE:
124 return (dgettext(TEXT_DOMAIN, "unable to restore to "
125 "destination"));
126 case EZFS_BADBACKUP:
127 return (dgettext(TEXT_DOMAIN, "backup failed"));
128 case EZFS_BADTARGET:
129 return (dgettext(TEXT_DOMAIN, "invalid target vdev"));
130 case EZFS_NODEVICE:
131 return (dgettext(TEXT_DOMAIN, "no such device in pool"));
132 case EZFS_BADDEV:
133 return (dgettext(TEXT_DOMAIN, "invalid device"));
134 case EZFS_NOREPLICAS:
135 return (dgettext(TEXT_DOMAIN, "no valid replicas"));
136 case EZFS_RESILVERING:
137 return (dgettext(TEXT_DOMAIN, "currently resilvering"));
138 case EZFS_BADVERSION:
139 return (dgettext(TEXT_DOMAIN, "unsupported version or "
140 "feature"));
141 case EZFS_POOLUNAVAIL:
142 return (dgettext(TEXT_DOMAIN, "pool is unavailable"));
143 case EZFS_DEVOVERFLOW:
144 return (dgettext(TEXT_DOMAIN, "too many devices in one vdev"));
145 case EZFS_BADPATH:
146 return (dgettext(TEXT_DOMAIN, "must be an absolute path"));
147 case EZFS_CROSSTARGET:
148 return (dgettext(TEXT_DOMAIN, "operation crosses datasets or "
149 "pools"));
150 case EZFS_ZONED:
151 return (dgettext(TEXT_DOMAIN, "dataset in use by local zone"));
152 case EZFS_MOUNTFAILED:
153 return (dgettext(TEXT_DOMAIN, "mount failed"));
154 case EZFS_UMOUNTFAILED:
155 return (dgettext(TEXT_DOMAIN, "unmount failed"));
156 case EZFS_UNSHARENFSFAILED:
157 return (dgettext(TEXT_DOMAIN, "NFS share removal failed"));
158 case EZFS_SHARENFSFAILED:
159 return (dgettext(TEXT_DOMAIN, "NFS share creation failed"));
160 case EZFS_UNSHARESMBFAILED:
161 return (dgettext(TEXT_DOMAIN, "SMB share removal failed"));
162 case EZFS_SHARESMBFAILED:
163 return (dgettext(TEXT_DOMAIN, "SMB share creation failed"));
164 case EZFS_PERM:
165 return (dgettext(TEXT_DOMAIN, "permission denied"));
166 case EZFS_NOSPC:
167 return (dgettext(TEXT_DOMAIN, "out of space"));
168 case EZFS_FAULT:
169 return (dgettext(TEXT_DOMAIN, "bad address"));
170 case EZFS_IO:
171 return (dgettext(TEXT_DOMAIN, "I/O error"));
172 case EZFS_INTR:
173 return (dgettext(TEXT_DOMAIN, "signal received"));
174 case EZFS_CKSUM:
175 return (dgettext(TEXT_DOMAIN, "insufficient replicas"));
176 case EZFS_ISSPARE:
177 return (dgettext(TEXT_DOMAIN, "device is reserved as a hot "
178 "spare"));
179 case EZFS_INVALCONFIG:
180 return (dgettext(TEXT_DOMAIN, "invalid vdev configuration"));
181 case EZFS_RECURSIVE:
182 return (dgettext(TEXT_DOMAIN, "recursive dataset dependency"));
183 case EZFS_NOHISTORY:
184 return (dgettext(TEXT_DOMAIN, "no history available"));
185 case EZFS_POOLPROPS:
186 return (dgettext(TEXT_DOMAIN, "failed to retrieve "
187 "pool properties"));
188 case EZFS_POOL_NOTSUP:
189 return (dgettext(TEXT_DOMAIN, "operation not supported "
190 "on this type of pool"));
191 case EZFS_POOL_INVALARG:
192 return (dgettext(TEXT_DOMAIN, "invalid argument for "
193 "this pool operation"));
194 case EZFS_NAMETOOLONG:
195 return (dgettext(TEXT_DOMAIN, "dataset name is too long"));
196 case EZFS_OPENFAILED:
197 return (dgettext(TEXT_DOMAIN, "open failed"));
198 case EZFS_NOCAP:
199 return (dgettext(TEXT_DOMAIN,
200 "disk capacity information could not be retrieved"));
201 case EZFS_LABELFAILED:
202 return (dgettext(TEXT_DOMAIN, "write of label failed"));
203 case EZFS_BADWHO:
204 return (dgettext(TEXT_DOMAIN, "invalid user/group"));
205 case EZFS_BADPERM:
206 return (dgettext(TEXT_DOMAIN, "invalid permission"));
207 case EZFS_BADPERMSET:
208 return (dgettext(TEXT_DOMAIN, "invalid permission set name"));
209 case EZFS_NODELEGATION:
210 return (dgettext(TEXT_DOMAIN, "delegated administration is "
211 "disabled on pool"));
212 case EZFS_BADCACHE:
213 return (dgettext(TEXT_DOMAIN, "invalid or missing cache file"));
214 case EZFS_ISL2CACHE:
215 return (dgettext(TEXT_DOMAIN, "device is in use as a cache"));
216 case EZFS_VDEVNOTSUP:
217 return (dgettext(TEXT_DOMAIN, "vdev specification is not "
218 "supported"));
219 case EZFS_NOTSUP:
220 return (dgettext(TEXT_DOMAIN, "operation not supported "
221 "on this dataset"));
222 case EZFS_IOC_NOTSUPPORTED:
223 return (dgettext(TEXT_DOMAIN, "operation not supported by "
224 "zfs kernel module"));
225 case EZFS_ACTIVE_SPARE:
226 return (dgettext(TEXT_DOMAIN, "pool has active shared spare "
227 "device"));
228 case EZFS_UNPLAYED_LOGS:
229 return (dgettext(TEXT_DOMAIN, "log device has unplayed intent "
230 "logs"));
231 case EZFS_REFTAG_RELE:
232 return (dgettext(TEXT_DOMAIN, "no such tag on this dataset"));
233 case EZFS_REFTAG_HOLD:
234 return (dgettext(TEXT_DOMAIN, "tag already exists on this "
235 "dataset"));
236 case EZFS_TAGTOOLONG:
237 return (dgettext(TEXT_DOMAIN, "tag too long"));
238 case EZFS_PIPEFAILED:
239 return (dgettext(TEXT_DOMAIN, "pipe create failed"));
240 case EZFS_THREADCREATEFAILED:
241 return (dgettext(TEXT_DOMAIN, "thread create failed"));
242 case EZFS_POSTSPLIT_ONLINE:
243 return (dgettext(TEXT_DOMAIN, "disk was split from this pool "
244 "into a new one"));
245 case EZFS_SCRUB_PAUSED:
246 return (dgettext(TEXT_DOMAIN, "scrub is paused; "
247 "use 'zpool scrub' to resume scrub"));
248 case EZFS_SCRUB_PAUSED_TO_CANCEL:
249 return (dgettext(TEXT_DOMAIN, "scrub is paused; "
250 "use 'zpool scrub' to resume or 'zpool scrub -s' to "
251 "cancel scrub"));
252 case EZFS_SCRUBBING:
253 return (dgettext(TEXT_DOMAIN, "currently scrubbing; "
254 "use 'zpool scrub -s' to cancel scrub"));
255 case EZFS_ERRORSCRUBBING:
256 return (dgettext(TEXT_DOMAIN, "currently error scrubbing; "
257 "use 'zpool scrub -s' to cancel error scrub"));
258 case EZFS_ERRORSCRUB_PAUSED:
259 return (dgettext(TEXT_DOMAIN, "error scrub is paused; "
260 "use 'zpool scrub -e' to resume error scrub"));
261 case EZFS_NO_SCRUB:
262 return (dgettext(TEXT_DOMAIN, "there is no active scrub"));
263 case EZFS_DIFF:
264 return (dgettext(TEXT_DOMAIN, "unable to generate diffs"));
265 case EZFS_DIFFDATA:
266 return (dgettext(TEXT_DOMAIN, "invalid diff data"));
267 case EZFS_POOLREADONLY:
268 return (dgettext(TEXT_DOMAIN, "pool is read-only"));
269 case EZFS_NO_PENDING:
270 return (dgettext(TEXT_DOMAIN, "operation is not "
271 "in progress"));
272 case EZFS_CHECKPOINT_EXISTS:
273 return (dgettext(TEXT_DOMAIN, "checkpoint exists"));
274 case EZFS_DISCARDING_CHECKPOINT:
275 return (dgettext(TEXT_DOMAIN, "currently discarding "
276 "checkpoint"));
277 case EZFS_NO_CHECKPOINT:
278 return (dgettext(TEXT_DOMAIN, "checkpoint does not exist"));
279 case EZFS_DEVRM_IN_PROGRESS:
280 return (dgettext(TEXT_DOMAIN, "device removal in progress"));
281 case EZFS_VDEV_TOO_BIG:
282 return (dgettext(TEXT_DOMAIN, "device exceeds supported size"));
283 case EZFS_ACTIVE_POOL:
284 return (dgettext(TEXT_DOMAIN, "pool is imported on a "
285 "different host"));
286 case EZFS_CRYPTOFAILED:
287 return (dgettext(TEXT_DOMAIN, "encryption failure"));
288 case EZFS_TOOMANY:
289 return (dgettext(TEXT_DOMAIN, "argument list too long"));
290 case EZFS_INITIALIZING:
291 return (dgettext(TEXT_DOMAIN, "currently initializing"));
292 case EZFS_NO_INITIALIZE:
293 return (dgettext(TEXT_DOMAIN, "there is no active "
294 "initialization"));
295 case EZFS_WRONG_PARENT:
296 return (dgettext(TEXT_DOMAIN, "invalid parent dataset"));
297 case EZFS_TRIMMING:
298 return (dgettext(TEXT_DOMAIN, "currently trimming"));
299 case EZFS_NO_TRIM:
300 return (dgettext(TEXT_DOMAIN, "there is no active trim"));
301 case EZFS_TRIM_NOTSUP:
302 return (dgettext(TEXT_DOMAIN, "trim operations are not "
303 "supported by this device"));
304 case EZFS_NO_RESILVER_DEFER:
305 return (dgettext(TEXT_DOMAIN, "this action requires the "
306 "resilver_defer feature"));
307 case EZFS_EXPORT_IN_PROGRESS:
308 return (dgettext(TEXT_DOMAIN, "pool export in progress"));
309 case EZFS_REBUILDING:
310 return (dgettext(TEXT_DOMAIN, "currently sequentially "
311 "resilvering"));
312 case EZFS_VDEV_NOTSUP:
313 return (dgettext(TEXT_DOMAIN, "operation not supported "
314 "on this type of vdev"));
315 case EZFS_NOT_USER_NAMESPACE:
316 return (dgettext(TEXT_DOMAIN, "the provided file "
317 "was not a user namespace file"));
318 case EZFS_RESUME_EXISTS:
319 return (dgettext(TEXT_DOMAIN, "Resuming recv on existing "
320 "dataset without force"));
321 case EZFS_RAIDZ_EXPAND_IN_PROGRESS:
322 return (dgettext(TEXT_DOMAIN, "raidz expansion in progress"));
323 case EZFS_ASHIFT_MISMATCH:
324 return (dgettext(TEXT_DOMAIN, "adding devices with "
325 "different physical sector sizes is not allowed"));
326 case EZFS_UNKNOWN:
327 return (dgettext(TEXT_DOMAIN, "unknown error"));
328 default:
329 assert(hdl->libzfs_error == 0);
330 return (dgettext(TEXT_DOMAIN, "no error"));
334 void
335 zfs_error_aux(libzfs_handle_t *hdl, const char *fmt, ...)
337 va_list ap;
339 va_start(ap, fmt);
341 (void) vsnprintf(hdl->libzfs_desc, sizeof (hdl->libzfs_desc),
342 fmt, ap);
343 hdl->libzfs_desc_active = 1;
345 va_end(ap);
348 static void
349 zfs_verror(libzfs_handle_t *hdl, int error, const char *fmt, va_list ap)
351 (void) vsnprintf(hdl->libzfs_action, sizeof (hdl->libzfs_action),
352 fmt, ap);
353 hdl->libzfs_error = error;
355 if (hdl->libzfs_desc_active)
356 hdl->libzfs_desc_active = 0;
357 else
358 hdl->libzfs_desc[0] = '\0';
360 if (hdl->libzfs_printerr) {
361 if (error == EZFS_UNKNOWN) {
362 (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "internal "
363 "error: %s: %s\n"), hdl->libzfs_action,
364 libzfs_error_description(hdl));
365 abort();
368 (void) fprintf(stderr, "%s: %s\n", hdl->libzfs_action,
369 libzfs_error_description(hdl));
370 if (error == EZFS_NOMEM)
371 exit(1);
376 zfs_error(libzfs_handle_t *hdl, int error, const char *msg)
378 return (zfs_error_fmt(hdl, error, "%s", msg));
382 zfs_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
384 va_list ap;
386 va_start(ap, fmt);
388 zfs_verror(hdl, error, fmt, ap);
390 va_end(ap);
392 return (-1);
395 static int
396 zfs_common_error(libzfs_handle_t *hdl, int error, const char *fmt,
397 va_list ap)
399 switch (error) {
400 case EPERM:
401 case EACCES:
402 zfs_verror(hdl, EZFS_PERM, fmt, ap);
403 return (-1);
405 case ECANCELED:
406 zfs_verror(hdl, EZFS_NODELEGATION, fmt, ap);
407 return (-1);
409 case EIO:
410 zfs_verror(hdl, EZFS_IO, fmt, ap);
411 return (-1);
413 case EFAULT:
414 zfs_verror(hdl, EZFS_FAULT, fmt, ap);
415 return (-1);
417 case EINTR:
418 zfs_verror(hdl, EZFS_INTR, fmt, ap);
419 return (-1);
421 case ECKSUM:
422 zfs_verror(hdl, EZFS_CKSUM, fmt, ap);
423 return (-1);
426 return (0);
430 zfs_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
432 return (zfs_standard_error_fmt(hdl, error, "%s", msg));
436 zfs_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
438 va_list ap;
440 va_start(ap, fmt);
442 if (zfs_common_error(hdl, error, fmt, ap) != 0) {
443 va_end(ap);
444 return (-1);
447 switch (error) {
448 case ENXIO:
449 case ENODEV:
450 case EPIPE:
451 zfs_verror(hdl, EZFS_IO, fmt, ap);
452 break;
454 case ENOENT:
455 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
456 "dataset does not exist"));
457 zfs_verror(hdl, EZFS_NOENT, fmt, ap);
458 break;
460 case ENOSPC:
461 case EDQUOT:
462 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
463 break;
465 case EEXIST:
466 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
467 "dataset already exists"));
468 zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
469 break;
471 case EBUSY:
472 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
473 "dataset is busy"));
474 zfs_verror(hdl, EZFS_BUSY, fmt, ap);
475 break;
476 case EROFS:
477 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
478 break;
479 case ENAMETOOLONG:
480 zfs_verror(hdl, EZFS_NAMETOOLONG, fmt, ap);
481 break;
482 case ENOTSUP:
483 zfs_verror(hdl, EZFS_BADVERSION, fmt, ap);
484 break;
485 case EAGAIN:
486 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
487 "pool I/O is currently suspended"));
488 zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
489 break;
490 case EREMOTEIO:
491 zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
492 break;
493 case ZFS_ERR_UNKNOWN_SEND_STREAM_FEATURE:
494 case ZFS_ERR_IOC_CMD_UNAVAIL:
495 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
496 "module does not support this operation. A reboot may "
497 "be required to enable this operation."));
498 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
499 break;
500 case ZFS_ERR_IOC_ARG_UNAVAIL:
501 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
502 "module does not support an option for this operation. "
503 "A reboot may be required to enable this option."));
504 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
505 break;
506 case ZFS_ERR_IOC_ARG_REQUIRED:
507 case ZFS_ERR_IOC_ARG_BADTYPE:
508 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
509 break;
510 case ZFS_ERR_WRONG_PARENT:
511 zfs_verror(hdl, EZFS_WRONG_PARENT, fmt, ap);
512 break;
513 case ZFS_ERR_BADPROP:
514 zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
515 break;
516 case ZFS_ERR_NOT_USER_NAMESPACE:
517 zfs_verror(hdl, EZFS_NOT_USER_NAMESPACE, fmt, ap);
518 break;
519 default:
520 zfs_error_aux(hdl, "%s", zfs_strerror(error));
521 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
522 break;
525 va_end(ap);
526 return (-1);
529 void
530 zfs_setprop_error(libzfs_handle_t *hdl, zfs_prop_t prop, int err,
531 char *errbuf)
533 switch (err) {
535 case ENOSPC:
537 * For quotas and reservations, ENOSPC indicates
538 * something different; setting a quota or reservation
539 * doesn't use any disk space.
541 switch (prop) {
542 case ZFS_PROP_QUOTA:
543 case ZFS_PROP_REFQUOTA:
544 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
545 "size is less than current used or "
546 "reserved space"));
547 (void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
548 break;
550 case ZFS_PROP_RESERVATION:
551 case ZFS_PROP_REFRESERVATION:
552 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
553 "size is greater than available space"));
554 (void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
555 break;
557 default:
558 (void) zfs_standard_error(hdl, err, errbuf);
559 break;
561 break;
563 case EBUSY:
564 (void) zfs_standard_error(hdl, EBUSY, errbuf);
565 break;
567 case EROFS:
568 (void) zfs_error(hdl, EZFS_DSREADONLY, errbuf);
569 break;
571 case E2BIG:
572 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
573 "property value too long"));
574 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
575 break;
577 case ENOTSUP:
578 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
579 "pool and or dataset must be upgraded to set this "
580 "property or value"));
581 (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
582 break;
584 case ERANGE:
585 if (prop == ZFS_PROP_COMPRESSION ||
586 prop == ZFS_PROP_DNODESIZE ||
587 prop == ZFS_PROP_RECORDSIZE) {
588 (void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
589 "property setting is not allowed on "
590 "bootable datasets"));
591 (void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
592 } else if (prop == ZFS_PROP_CHECKSUM ||
593 prop == ZFS_PROP_DEDUP) {
594 (void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
595 "property setting is not allowed on "
596 "root pools"));
597 (void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
598 } else {
599 (void) zfs_standard_error(hdl, err, errbuf);
601 break;
603 case EINVAL:
604 if (prop == ZPROP_INVAL) {
605 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
606 } else {
607 (void) zfs_standard_error(hdl, err, errbuf);
609 break;
611 case ZFS_ERR_BADPROP:
612 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
613 break;
615 case EACCES:
616 if (prop == ZFS_PROP_KEYLOCATION) {
617 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
618 "keylocation may only be set on encryption roots"));
619 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
620 } else {
621 (void) zfs_standard_error(hdl, err, errbuf);
623 break;
625 case EOVERFLOW:
627 * This platform can't address a volume this big.
629 #ifdef _ILP32
630 if (prop == ZFS_PROP_VOLSIZE) {
631 (void) zfs_error(hdl, EZFS_VOLTOOBIG, errbuf);
632 break;
634 zfs_fallthrough;
635 #endif
636 default:
637 (void) zfs_standard_error(hdl, err, errbuf);
642 zpool_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
644 return (zpool_standard_error_fmt(hdl, error, "%s", msg));
648 zpool_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
650 va_list ap;
652 va_start(ap, fmt);
654 if (zfs_common_error(hdl, error, fmt, ap) != 0) {
655 va_end(ap);
656 return (-1);
659 switch (error) {
660 case ENODEV:
661 zfs_verror(hdl, EZFS_NODEVICE, fmt, ap);
662 break;
664 case ENOENT:
665 zfs_error_aux(hdl,
666 dgettext(TEXT_DOMAIN, "no such pool or dataset"));
667 zfs_verror(hdl, EZFS_NOENT, fmt, ap);
668 break;
670 case EEXIST:
671 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
672 "pool already exists"));
673 zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
674 break;
676 case EBUSY:
677 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool is busy"));
678 zfs_verror(hdl, EZFS_BUSY, fmt, ap);
679 break;
681 /* There is no pending operation to cancel */
682 case ENOTACTIVE:
683 zfs_verror(hdl, EZFS_NO_PENDING, fmt, ap);
684 break;
686 case ENXIO:
687 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
688 "one or more devices is currently unavailable"));
689 zfs_verror(hdl, EZFS_BADDEV, fmt, ap);
690 break;
692 case ENAMETOOLONG:
693 zfs_verror(hdl, EZFS_DEVOVERFLOW, fmt, ap);
694 break;
696 case ENOTSUP:
697 zfs_verror(hdl, EZFS_POOL_NOTSUP, fmt, ap);
698 break;
700 case EINVAL:
701 zfs_verror(hdl, EZFS_POOL_INVALARG, fmt, ap);
702 break;
704 case ENOSPC:
705 case EDQUOT:
706 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
707 break;
709 case EAGAIN:
710 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
711 "pool I/O is currently suspended"));
712 zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
713 break;
715 case EROFS:
716 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
717 break;
718 case EDOM:
719 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
720 "block size out of range or does not match"));
721 zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
722 break;
723 case EREMOTEIO:
724 zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
725 break;
726 case ZFS_ERR_CHECKPOINT_EXISTS:
727 zfs_verror(hdl, EZFS_CHECKPOINT_EXISTS, fmt, ap);
728 break;
729 case ZFS_ERR_DISCARDING_CHECKPOINT:
730 zfs_verror(hdl, EZFS_DISCARDING_CHECKPOINT, fmt, ap);
731 break;
732 case ZFS_ERR_NO_CHECKPOINT:
733 zfs_verror(hdl, EZFS_NO_CHECKPOINT, fmt, ap);
734 break;
735 case ZFS_ERR_DEVRM_IN_PROGRESS:
736 zfs_verror(hdl, EZFS_DEVRM_IN_PROGRESS, fmt, ap);
737 break;
738 case ZFS_ERR_VDEV_TOO_BIG:
739 zfs_verror(hdl, EZFS_VDEV_TOO_BIG, fmt, ap);
740 break;
741 case ZFS_ERR_EXPORT_IN_PROGRESS:
742 zfs_verror(hdl, EZFS_EXPORT_IN_PROGRESS, fmt, ap);
743 break;
744 case ZFS_ERR_RESILVER_IN_PROGRESS:
745 zfs_verror(hdl, EZFS_RESILVERING, fmt, ap);
746 break;
747 case ZFS_ERR_REBUILD_IN_PROGRESS:
748 zfs_verror(hdl, EZFS_REBUILDING, fmt, ap);
749 break;
750 case ZFS_ERR_BADPROP:
751 zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
752 break;
753 case ZFS_ERR_VDEV_NOTSUP:
754 zfs_verror(hdl, EZFS_VDEV_NOTSUP, fmt, ap);
755 break;
756 case ZFS_ERR_IOC_CMD_UNAVAIL:
757 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
758 "module does not support this operation. A reboot may "
759 "be required to enable this operation."));
760 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
761 break;
762 case ZFS_ERR_IOC_ARG_UNAVAIL:
763 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
764 "module does not support an option for this operation. "
765 "A reboot may be required to enable this option."));
766 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
767 break;
768 case ZFS_ERR_IOC_ARG_REQUIRED:
769 case ZFS_ERR_IOC_ARG_BADTYPE:
770 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
771 break;
772 case ZFS_ERR_RAIDZ_EXPAND_IN_PROGRESS:
773 zfs_verror(hdl, EZFS_RAIDZ_EXPAND_IN_PROGRESS, fmt, ap);
774 break;
775 case ZFS_ERR_ASHIFT_MISMATCH:
776 zfs_verror(hdl, EZFS_ASHIFT_MISMATCH, fmt, ap);
777 break;
778 default:
779 zfs_error_aux(hdl, "%s", zfs_strerror(error));
780 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
783 va_end(ap);
784 return (-1);
788 * Display an out of memory error message and abort the current program.
791 no_memory(libzfs_handle_t *hdl)
793 return (zfs_error(hdl, EZFS_NOMEM, "internal error"));
797 * A safe form of malloc() which will die if the allocation fails.
799 void *
800 zfs_alloc(libzfs_handle_t *hdl, size_t size)
802 void *data;
804 if ((data = calloc(1, size)) == NULL)
805 (void) no_memory(hdl);
807 return (data);
811 * A safe form of asprintf() which will die if the allocation fails.
813 char *
814 zfs_asprintf(libzfs_handle_t *hdl, const char *fmt, ...)
816 va_list ap;
817 char *ret;
818 int err;
820 va_start(ap, fmt);
822 err = vasprintf(&ret, fmt, ap);
824 va_end(ap);
826 if (err < 0) {
827 (void) no_memory(hdl);
828 ret = NULL;
831 return (ret);
835 * A safe form of realloc(), which also zeroes newly allocated space.
837 void *
838 zfs_realloc(libzfs_handle_t *hdl, void *ptr, size_t oldsize, size_t newsize)
840 void *ret;
842 if ((ret = realloc(ptr, newsize)) == NULL) {
843 (void) no_memory(hdl);
844 return (NULL);
847 memset((char *)ret + oldsize, 0, newsize - oldsize);
848 return (ret);
852 * A safe form of strdup() which will die if the allocation fails.
854 char *
855 zfs_strdup(libzfs_handle_t *hdl, const char *str)
857 char *ret;
859 if ((ret = strdup(str)) == NULL)
860 (void) no_memory(hdl);
862 return (ret);
865 void
866 libzfs_print_on_error(libzfs_handle_t *hdl, boolean_t printerr)
868 hdl->libzfs_printerr = printerr;
872 * Read lines from an open file descriptor and store them in an array of
873 * strings until EOF. lines[] will be allocated and populated with all the
874 * lines read. All newlines are replaced with NULL terminators for
875 * convenience. lines[] must be freed after use with libzfs_free_str_array().
877 * Returns the number of lines read.
879 static int
880 libzfs_read_stdout_from_fd(int fd, char **lines[])
883 FILE *fp;
884 int lines_cnt = 0;
885 size_t len = 0;
886 char *line = NULL;
887 char **tmp_lines = NULL, **tmp;
889 fp = fdopen(fd, "r");
890 if (fp == NULL) {
891 close(fd);
892 return (0);
894 while (getline(&line, &len, fp) != -1) {
895 tmp = realloc(tmp_lines, sizeof (*tmp_lines) * (lines_cnt + 1));
896 if (tmp == NULL) {
897 /* Return the lines we were able to process */
898 break;
900 tmp_lines = tmp;
902 /* Remove newline if not EOF */
903 if (line[strlen(line) - 1] == '\n')
904 line[strlen(line) - 1] = '\0';
906 tmp_lines[lines_cnt] = strdup(line);
907 if (tmp_lines[lines_cnt] == NULL)
908 break;
909 ++lines_cnt;
911 free(line);
912 fclose(fp);
913 *lines = tmp_lines;
914 return (lines_cnt);
917 static int
918 libzfs_run_process_impl(const char *path, char *argv[], char *env[], int flags,
919 char **lines[], int *lines_cnt)
921 pid_t pid;
922 int error, devnull_fd;
923 int link[2];
926 * Setup a pipe between our child and parent process if we're
927 * reading stdout.
929 if (lines != NULL && pipe2(link, O_NONBLOCK | O_CLOEXEC) == -1)
930 return (-EPIPE);
932 pid = fork();
933 if (pid == 0) {
934 /* Child process */
935 setpgid(0, 0);
936 devnull_fd = open("/dev/null", O_WRONLY | O_CLOEXEC);
938 if (devnull_fd < 0)
939 _exit(-1);
941 if (!(flags & STDOUT_VERBOSE) && (lines == NULL))
942 (void) dup2(devnull_fd, STDOUT_FILENO);
943 else if (lines != NULL) {
944 /* Save the output to lines[] */
945 dup2(link[1], STDOUT_FILENO);
948 if (!(flags & STDERR_VERBOSE))
949 (void) dup2(devnull_fd, STDERR_FILENO);
951 if (flags & NO_DEFAULT_PATH) {
952 if (env == NULL)
953 execv(path, argv);
954 else
955 execve(path, argv, env);
956 } else {
957 if (env == NULL)
958 execvp(path, argv);
959 else
960 execvpe(path, argv, env);
963 _exit(-1);
964 } else if (pid > 0) {
965 /* Parent process */
966 int status;
968 while ((error = waitpid(pid, &status, 0)) == -1 &&
969 errno == EINTR)
971 if (error < 0 || !WIFEXITED(status))
972 return (-1);
974 if (lines != NULL) {
975 close(link[1]);
976 *lines_cnt = libzfs_read_stdout_from_fd(link[0], lines);
978 return (WEXITSTATUS(status));
981 return (-1);
985 libzfs_run_process(const char *path, char *argv[], int flags)
987 return (libzfs_run_process_impl(path, argv, NULL, flags, NULL, NULL));
991 * Run a command and store its stdout lines in an array of strings (lines[]).
992 * lines[] is allocated and populated for you, and the number of lines is set in
993 * lines_cnt. lines[] must be freed after use with libzfs_free_str_array().
994 * All newlines (\n) in lines[] are terminated for convenience.
997 libzfs_run_process_get_stdout(const char *path, char *argv[], char *env[],
998 char **lines[], int *lines_cnt)
1000 return (libzfs_run_process_impl(path, argv, env, 0, lines, lines_cnt));
1004 * Same as libzfs_run_process_get_stdout(), but run without $PATH set. This
1005 * means that *path needs to be the full path to the executable.
1008 libzfs_run_process_get_stdout_nopath(const char *path, char *argv[],
1009 char *env[], char **lines[], int *lines_cnt)
1011 return (libzfs_run_process_impl(path, argv, env, NO_DEFAULT_PATH,
1012 lines, lines_cnt));
1016 * Free an array of strings. Free both the strings contained in the array and
1017 * the array itself.
1019 void
1020 libzfs_free_str_array(char **strs, int count)
1022 while (--count >= 0)
1023 free(strs[count]);
1025 free(strs);
1029 * Returns 1 if environment variable is set to "YES", "yes", "ON", "on", or
1030 * a non-zero number.
1032 * Returns 0 otherwise.
1034 boolean_t
1035 libzfs_envvar_is_set(const char *envvar)
1037 char *env = getenv(envvar);
1038 return (env && (strtoul(env, NULL, 0) > 0 ||
1039 (!strncasecmp(env, "YES", 3) && strnlen(env, 4) == 3) ||
1040 (!strncasecmp(env, "ON", 2) && strnlen(env, 3) == 2)));
1043 libzfs_handle_t *
1044 libzfs_init(void)
1046 libzfs_handle_t *hdl;
1047 int error;
1048 char *env;
1050 if ((error = libzfs_load_module()) != 0) {
1051 errno = error;
1052 return (NULL);
1055 if ((hdl = calloc(1, sizeof (libzfs_handle_t))) == NULL) {
1056 return (NULL);
1059 if (regcomp(&hdl->libzfs_urire, URI_REGEX, 0) != 0) {
1060 free(hdl);
1061 return (NULL);
1064 if ((hdl->libzfs_fd = open(ZFS_DEV, O_RDWR|O_EXCL|O_CLOEXEC)) < 0) {
1065 free(hdl);
1066 return (NULL);
1069 if (libzfs_core_init() != 0) {
1070 (void) close(hdl->libzfs_fd);
1071 free(hdl);
1072 return (NULL);
1075 zfs_prop_init();
1076 zpool_prop_init();
1077 zpool_feature_init();
1078 vdev_prop_init();
1079 libzfs_mnttab_init(hdl);
1080 fletcher_4_init();
1082 if (getenv("ZFS_PROP_DEBUG") != NULL) {
1083 hdl->libzfs_prop_debug = B_TRUE;
1085 if ((env = getenv("ZFS_SENDRECV_MAX_NVLIST")) != NULL) {
1086 if ((error = zfs_nicestrtonum(hdl, env,
1087 &hdl->libzfs_max_nvlist))) {
1088 errno = error;
1089 (void) close(hdl->libzfs_fd);
1090 free(hdl);
1091 return (NULL);
1093 } else {
1094 hdl->libzfs_max_nvlist = (SPA_MAXBLOCKSIZE * 4);
1098 * For testing, remove some settable properties and features
1100 if (libzfs_envvar_is_set("ZFS_SYSFS_PROP_SUPPORT_TEST")) {
1101 zprop_desc_t *proptbl;
1103 proptbl = zpool_prop_get_table();
1104 proptbl[ZPOOL_PROP_COMMENT].pd_zfs_mod_supported = B_FALSE;
1106 proptbl = zfs_prop_get_table();
1107 proptbl[ZFS_PROP_DNODESIZE].pd_zfs_mod_supported = B_FALSE;
1109 zfeature_info_t *ftbl = spa_feature_table;
1110 ftbl[SPA_FEATURE_LARGE_BLOCKS].fi_zfs_mod_supported = B_FALSE;
1113 return (hdl);
1116 void
1117 libzfs_fini(libzfs_handle_t *hdl)
1119 (void) close(hdl->libzfs_fd);
1120 zpool_free_handles(hdl);
1121 namespace_clear(hdl);
1122 libzfs_mnttab_fini(hdl);
1123 libzfs_core_fini();
1124 regfree(&hdl->libzfs_urire);
1125 fletcher_4_fini();
1126 #if LIBFETCH_DYNAMIC
1127 if (hdl->libfetch != (void *)-1 && hdl->libfetch != NULL)
1128 (void) dlclose(hdl->libfetch);
1129 free(hdl->libfetch_load_error);
1130 #endif
1131 free(hdl);
1134 libzfs_handle_t *
1135 zpool_get_handle(zpool_handle_t *zhp)
1137 return (zhp->zpool_hdl);
1140 libzfs_handle_t *
1141 zfs_get_handle(zfs_handle_t *zhp)
1143 return (zhp->zfs_hdl);
1146 zpool_handle_t *
1147 zfs_get_pool_handle(const zfs_handle_t *zhp)
1149 return (zhp->zpool_hdl);
1153 * Given a name, determine whether or not it's a valid path
1154 * (starts with '/' or "./"). If so, walk the mnttab trying
1155 * to match the device number. If not, treat the path as an
1156 * fs/vol/snap/bkmark name.
1158 zfs_handle_t *
1159 zfs_path_to_zhandle(libzfs_handle_t *hdl, const char *path, zfs_type_t argtype)
1161 struct stat64 statbuf;
1162 struct extmnttab entry;
1164 if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
1166 * It's not a valid path, assume it's a name of type 'argtype'.
1168 return (zfs_open(hdl, path, argtype));
1171 if (getextmntent(path, &entry, &statbuf) != 0)
1172 return (NULL);
1174 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
1175 (void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
1176 path);
1177 return (NULL);
1180 return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
1184 * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
1185 * an ioctl().
1187 void
1188 zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
1190 if (len == 0)
1191 len = 256 * 1024;
1192 zc->zc_nvlist_dst_size = len;
1193 zc->zc_nvlist_dst =
1194 (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1198 * Called when an ioctl() which returns an nvlist fails with ENOMEM. This will
1199 * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
1200 * filled in by the kernel to indicate the actual required size.
1202 void
1203 zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
1205 free((void *)(uintptr_t)zc->zc_nvlist_dst);
1206 zc->zc_nvlist_dst =
1207 (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1211 * Called to free the src and dst nvlists stored in the command structure.
1213 void
1214 zcmd_free_nvlists(zfs_cmd_t *zc)
1216 free((void *)(uintptr_t)zc->zc_nvlist_conf);
1217 free((void *)(uintptr_t)zc->zc_nvlist_src);
1218 free((void *)(uintptr_t)zc->zc_nvlist_dst);
1219 zc->zc_nvlist_conf = 0;
1220 zc->zc_nvlist_src = 0;
1221 zc->zc_nvlist_dst = 0;
1224 static void
1225 zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
1226 nvlist_t *nvl)
1228 char *packed;
1230 size_t len = fnvlist_size(nvl);
1231 packed = zfs_alloc(hdl, len);
1233 verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
1235 *outnv = (uint64_t)(uintptr_t)packed;
1236 *outlen = len;
1239 void
1240 zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1242 zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
1243 &zc->zc_nvlist_conf_size, nvl);
1246 void
1247 zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1249 zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
1250 &zc->zc_nvlist_src_size, nvl);
1254 * Unpacks an nvlist from the ZFS ioctl command structure.
1257 zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
1259 if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
1260 zc->zc_nvlist_dst_size, nvlp, 0) != 0)
1261 return (no_memory(hdl));
1263 return (0);
1267 * ================================================================
1268 * API shared by zfs and zpool property management
1269 * ================================================================
1272 void
1273 zcmd_print_json(nvlist_t *nvl)
1275 nvlist_print_json(stdout, nvl);
1276 (void) putchar('\n');
1277 nvlist_free(nvl);
1280 static void
1281 zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
1283 zprop_list_t *pl;
1284 int i;
1285 char *title;
1286 size_t len;
1288 cbp->cb_first = B_FALSE;
1289 if (cbp->cb_scripted)
1290 return;
1293 * Start with the length of the column headers.
1295 cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
1296 cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
1297 "PROPERTY"));
1298 cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
1299 "VALUE"));
1300 cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
1301 "RECEIVED"));
1302 cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
1303 "SOURCE"));
1305 /* first property is always NAME */
1306 assert(cbp->cb_proplist->pl_prop ==
1307 ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1308 ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME : ZFS_PROP_NAME)));
1311 * Go through and calculate the widths for each column. For the
1312 * 'source' column, we kludge it up by taking the worst-case scenario of
1313 * inheriting from the longest name. This is acceptable because in the
1314 * majority of cases 'SOURCE' is the last column displayed, and we don't
1315 * use the width anyway. Note that the 'VALUE' column can be oversized,
1316 * if the name of the property is much longer than any values we find.
1318 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
1320 * 'PROPERTY' column
1322 if (pl->pl_prop != ZPROP_USERPROP) {
1323 const char *propname = (type == ZFS_TYPE_POOL) ?
1324 zpool_prop_to_name(pl->pl_prop) :
1325 ((type == ZFS_TYPE_VDEV) ?
1326 vdev_prop_to_name(pl->pl_prop) :
1327 zfs_prop_to_name(pl->pl_prop));
1329 assert(propname != NULL);
1330 len = strlen(propname);
1331 if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1332 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1333 } else {
1334 assert(pl->pl_user_prop != NULL);
1335 len = strlen(pl->pl_user_prop);
1336 if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1337 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1341 * 'VALUE' column. The first property is always the 'name'
1342 * property that was tacked on either by /sbin/zfs's
1343 * zfs_do_get() or when calling zprop_expand_list(), so we
1344 * ignore its width. If the user specified the name property
1345 * to display, then it will be later in the list in any case.
1347 if (pl != cbp->cb_proplist &&
1348 pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
1349 cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
1351 /* 'RECEIVED' column. */
1352 if (pl != cbp->cb_proplist &&
1353 pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
1354 cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
1357 * 'NAME' and 'SOURCE' columns
1359 if (pl->pl_prop == ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1360 ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME :
1361 ZFS_PROP_NAME)) && pl->pl_width >
1362 cbp->cb_colwidths[GET_COL_NAME]) {
1363 cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
1364 cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
1365 strlen(dgettext(TEXT_DOMAIN, "inherited from"));
1370 * Now go through and print the headers.
1372 for (i = 0; i < ZFS_GET_NCOLS; i++) {
1373 switch (cbp->cb_columns[i]) {
1374 case GET_COL_NAME:
1375 title = dgettext(TEXT_DOMAIN, "NAME");
1376 break;
1377 case GET_COL_PROPERTY:
1378 title = dgettext(TEXT_DOMAIN, "PROPERTY");
1379 break;
1380 case GET_COL_VALUE:
1381 title = dgettext(TEXT_DOMAIN, "VALUE");
1382 break;
1383 case GET_COL_RECVD:
1384 title = dgettext(TEXT_DOMAIN, "RECEIVED");
1385 break;
1386 case GET_COL_SOURCE:
1387 title = dgettext(TEXT_DOMAIN, "SOURCE");
1388 break;
1389 default:
1390 title = NULL;
1393 if (title != NULL) {
1394 if (i == (ZFS_GET_NCOLS - 1) ||
1395 cbp->cb_columns[i + 1] == GET_COL_NONE)
1396 (void) printf("%s", title);
1397 else
1398 (void) printf("%-*s ",
1399 cbp->cb_colwidths[cbp->cb_columns[i]],
1400 title);
1403 (void) printf("\n");
1407 * Add property value and source to provided nvlist, according to
1408 * settings in cb structure. Later to be printed in JSON format.
1411 zprop_nvlist_one_property(const char *propname,
1412 const char *value, zprop_source_t sourcetype, const char *source,
1413 const char *recvd_value, nvlist_t *nvl, boolean_t as_int)
1415 int ret = 0;
1416 nvlist_t *src_nv, *prop;
1417 boolean_t all_numeric = strspn(value, STR_NUMS) == strlen(value);
1418 src_nv = prop = NULL;
1420 if ((nvlist_alloc(&prop, NV_UNIQUE_NAME, 0) != 0) ||
1421 (nvlist_alloc(&src_nv, NV_UNIQUE_NAME, 0) != 0)) {
1422 ret = -1;
1423 goto err;
1426 if (as_int && all_numeric) {
1427 uint64_t val;
1428 sscanf(value, "%lld", (u_longlong_t *)&val);
1429 if (nvlist_add_uint64(prop, "value", val) != 0) {
1430 ret = -1;
1431 goto err;
1433 } else {
1434 if (nvlist_add_string(prop, "value", value) != 0) {
1435 ret = -1;
1436 goto err;
1440 switch (sourcetype) {
1441 case ZPROP_SRC_NONE:
1442 if (nvlist_add_string(src_nv, "type", "NONE") != 0 ||
1443 (nvlist_add_string(src_nv, "data", "-") != 0)) {
1444 ret = -1;
1445 goto err;
1447 break;
1448 case ZPROP_SRC_DEFAULT:
1449 if (nvlist_add_string(src_nv, "type", "DEFAULT") != 0 ||
1450 (nvlist_add_string(src_nv, "data", "-") != 0)) {
1451 ret = -1;
1452 goto err;
1454 break;
1455 case ZPROP_SRC_LOCAL:
1456 if (nvlist_add_string(src_nv, "type", "LOCAL") != 0 ||
1457 (nvlist_add_string(src_nv, "data", "-") != 0)) {
1458 ret = -1;
1459 goto err;
1461 break;
1462 case ZPROP_SRC_TEMPORARY:
1463 if (nvlist_add_string(src_nv, "type", "TEMPORARY") != 0 ||
1464 (nvlist_add_string(src_nv, "data", "-") != 0)) {
1465 ret = -1;
1466 goto err;
1468 break;
1469 case ZPROP_SRC_INHERITED:
1470 if (nvlist_add_string(src_nv, "type", "INHERITED") != 0 ||
1471 (nvlist_add_string(src_nv, "data", source) != 0)) {
1472 ret = -1;
1473 goto err;
1475 break;
1476 case ZPROP_SRC_RECEIVED:
1477 if (nvlist_add_string(src_nv, "type", "RECEIVED") != 0 ||
1478 (nvlist_add_string(src_nv, "data",
1479 (recvd_value == NULL ? "-" : recvd_value)) != 0)) {
1480 ret = -1;
1481 goto err;
1483 break;
1484 default:
1485 assert(!"unhandled zprop_source_t");
1486 if (nvlist_add_string(src_nv, "type",
1487 "unhandled zprop_source_t") != 0) {
1488 ret = -1;
1489 goto err;
1492 if ((nvlist_add_nvlist(prop, "source", src_nv) != 0) ||
1493 (nvlist_add_nvlist(nvl, propname, prop)) != 0) {
1494 ret = -1;
1495 goto err;
1497 err:
1498 nvlist_free(src_nv);
1499 nvlist_free(prop);
1500 return (ret);
1504 * Display a single line of output, according to the settings in the callback
1505 * structure.
1507 void
1508 zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
1509 const char *propname, const char *value, zprop_source_t sourcetype,
1510 const char *source, const char *recvd_value)
1512 int i;
1513 const char *str = NULL;
1514 char buf[128];
1517 * Ignore those source types that the user has chosen to ignore.
1519 if ((sourcetype & cbp->cb_sources) == 0)
1520 return;
1522 if (cbp->cb_first)
1523 zprop_print_headers(cbp, cbp->cb_type);
1525 for (i = 0; i < ZFS_GET_NCOLS; i++) {
1526 switch (cbp->cb_columns[i]) {
1527 case GET_COL_NAME:
1528 str = name;
1529 break;
1531 case GET_COL_PROPERTY:
1532 str = propname;
1533 break;
1535 case GET_COL_VALUE:
1536 str = value;
1537 break;
1539 case GET_COL_SOURCE:
1540 switch (sourcetype) {
1541 case ZPROP_SRC_NONE:
1542 str = "-";
1543 break;
1545 case ZPROP_SRC_DEFAULT:
1546 str = "default";
1547 break;
1549 case ZPROP_SRC_LOCAL:
1550 str = "local";
1551 break;
1553 case ZPROP_SRC_TEMPORARY:
1554 str = "temporary";
1555 break;
1557 case ZPROP_SRC_INHERITED:
1558 (void) snprintf(buf, sizeof (buf),
1559 "inherited from %s", source);
1560 str = buf;
1561 break;
1562 case ZPROP_SRC_RECEIVED:
1563 str = "received";
1564 break;
1566 default:
1567 str = NULL;
1568 assert(!"unhandled zprop_source_t");
1570 break;
1572 case GET_COL_RECVD:
1573 str = (recvd_value == NULL ? "-" : recvd_value);
1574 break;
1576 default:
1577 continue;
1580 if (i == (ZFS_GET_NCOLS - 1) ||
1581 cbp->cb_columns[i + 1] == GET_COL_NONE)
1582 (void) printf("%s", str);
1583 else if (cbp->cb_scripted)
1584 (void) printf("%s\t", str);
1585 else
1586 (void) printf("%-*s ",
1587 cbp->cb_colwidths[cbp->cb_columns[i]],
1588 str);
1591 (void) printf("\n");
1595 zprop_collect_property(const char *name, zprop_get_cbdata_t *cbp,
1596 const char *propname, const char *value, zprop_source_t sourcetype,
1597 const char *source, const char *recvd_value, nvlist_t *nvl)
1599 if (cbp->cb_json) {
1600 if ((sourcetype & cbp->cb_sources) == 0)
1601 return (0);
1602 else {
1603 return (zprop_nvlist_one_property(propname, value,
1604 sourcetype, source, recvd_value, nvl,
1605 cbp->cb_json_as_int));
1607 } else {
1608 zprop_print_one_property(name, cbp,
1609 propname, value, sourcetype, source, recvd_value);
1610 return (0);
1615 * Given a numeric suffix, convert the value into a number of bits that the
1616 * resulting value must be shifted.
1618 static int
1619 str2shift(libzfs_handle_t *hdl, const char *buf)
1621 const char *ends = "BKMGTPEZ";
1622 int i, len;
1624 if (buf[0] == '\0')
1625 return (0);
1627 len = strlen(ends);
1628 for (i = 0; i < len; i++) {
1629 if (toupper(buf[0]) == ends[i])
1630 break;
1632 if (i == len) {
1633 if (hdl)
1634 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1635 "invalid numeric suffix '%s'"), buf);
1636 return (-1);
1640 * Allow 'G' = 'GB' = 'GiB', case-insensitively.
1641 * However, 'BB' and 'BiB' are disallowed.
1643 if (buf[1] == '\0' ||
1644 (toupper(buf[0]) != 'B' &&
1645 ((toupper(buf[1]) == 'B' && buf[2] == '\0') ||
1646 (toupper(buf[1]) == 'I' && toupper(buf[2]) == 'B' &&
1647 buf[3] == '\0'))))
1648 return (10 * i);
1650 if (hdl)
1651 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1652 "invalid numeric suffix '%s'"), buf);
1653 return (-1);
1657 * Convert a string of the form '100G' into a real number. Used when setting
1658 * properties or creating a volume. 'buf' is used to place an extended error
1659 * message for the caller to use.
1662 zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1664 char *end;
1665 int shift;
1667 *num = 0;
1669 /* Check to see if this looks like a number. */
1670 if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1671 if (hdl)
1672 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1673 "bad numeric value '%s'"), value);
1674 return (-1);
1677 /* Rely on strtoull() to process the numeric portion. */
1678 errno = 0;
1679 *num = strtoull(value, &end, 10);
1682 * Check for ERANGE, which indicates that the value is too large to fit
1683 * in a 64-bit value.
1685 if (errno == ERANGE) {
1686 if (hdl)
1687 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1688 "numeric value is too large"));
1689 return (-1);
1693 * If we have a decimal value, then do the computation with floating
1694 * point arithmetic. Otherwise, use standard arithmetic.
1696 if (*end == '.') {
1697 double fval = strtod(value, &end);
1699 if ((shift = str2shift(hdl, end)) == -1)
1700 return (-1);
1702 fval *= pow(2, shift);
1705 * UINT64_MAX is not exactly representable as a double.
1706 * The closest representation is UINT64_MAX + 1, so we
1707 * use a >= comparison instead of > for the bounds check.
1709 if (fval >= (double)UINT64_MAX) {
1710 if (hdl)
1711 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1712 "numeric value is too large"));
1713 return (-1);
1716 *num = (uint64_t)fval;
1717 } else {
1718 if ((shift = str2shift(hdl, end)) == -1)
1719 return (-1);
1721 /* Check for overflow */
1722 if (shift >= 64 || (*num << shift) >> shift != *num) {
1723 if (hdl)
1724 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1725 "numeric value is too large"));
1726 return (-1);
1729 *num <<= shift;
1732 return (0);
1736 * Given a propname=value nvpair to set, parse any numeric properties
1737 * (index, boolean, etc) if they are specified as strings and add the
1738 * resulting nvpair to the returned nvlist.
1740 * At the DSL layer, all properties are either 64-bit numbers or strings.
1741 * We want the user to be able to ignore this fact and specify properties
1742 * as native values (numbers, for example) or as strings (to simplify
1743 * command line utilities). This also handles converting index types
1744 * (compression, checksum, etc) from strings to their on-disk index.
1747 zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1748 zfs_type_t type, nvlist_t *ret, const char **svalp, uint64_t *ivalp,
1749 const char *errbuf)
1751 data_type_t datatype = nvpair_type(elem);
1752 zprop_type_t proptype;
1753 const char *propname;
1754 const char *value;
1755 boolean_t isnone = B_FALSE;
1756 boolean_t isauto = B_FALSE;
1757 int err = 0;
1759 if (type == ZFS_TYPE_POOL) {
1760 proptype = zpool_prop_get_type(prop);
1761 propname = zpool_prop_to_name(prop);
1762 } else if (type == ZFS_TYPE_VDEV) {
1763 proptype = vdev_prop_get_type(prop);
1764 propname = vdev_prop_to_name(prop);
1765 } else {
1766 proptype = zfs_prop_get_type(prop);
1767 propname = zfs_prop_to_name(prop);
1771 * Convert any properties to the internal DSL value types.
1773 *svalp = NULL;
1774 *ivalp = 0;
1776 switch (proptype) {
1777 case PROP_TYPE_STRING:
1778 if (datatype != DATA_TYPE_STRING) {
1779 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1780 "'%s' must be a string"), nvpair_name(elem));
1781 goto error;
1783 err = nvpair_value_string(elem, svalp);
1784 if (err != 0) {
1785 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1786 "'%s' is invalid"), nvpair_name(elem));
1787 goto error;
1789 if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1790 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1791 "'%s' is too long"), nvpair_name(elem));
1792 goto error;
1794 break;
1796 case PROP_TYPE_NUMBER:
1797 if (datatype == DATA_TYPE_STRING) {
1798 (void) nvpair_value_string(elem, &value);
1799 if (strcmp(value, "none") == 0) {
1800 isnone = B_TRUE;
1801 } else if (strcmp(value, "auto") == 0) {
1802 isauto = B_TRUE;
1803 } else if (zfs_nicestrtonum(hdl, value, ivalp) != 0) {
1804 goto error;
1806 } else if (datatype == DATA_TYPE_UINT64) {
1807 (void) nvpair_value_uint64(elem, ivalp);
1808 } else {
1809 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1810 "'%s' must be a number"), nvpair_name(elem));
1811 goto error;
1815 * Quota special: force 'none' and don't allow 0.
1817 if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1818 (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1819 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1820 "use 'none' to disable quota/refquota"));
1821 goto error;
1824 * Pool dedup table quota; force use of 'none' instead of 0
1826 if ((type & ZFS_TYPE_POOL) && *ivalp == 0 &&
1827 (!isnone && !isauto) &&
1828 prop == ZPOOL_PROP_DEDUP_TABLE_QUOTA) {
1829 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1830 "use 'none' to disable ddt table quota"));
1831 goto error;
1835 * Special handling for "*_limit=none". In this case it's not
1836 * 0 but UINT64_MAX.
1838 if ((type & ZFS_TYPE_DATASET) && isnone &&
1839 (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1840 prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1841 *ivalp = UINT64_MAX;
1845 * Special handling for "checksum_*=none". In this case it's not
1846 * 0 but UINT64_MAX.
1848 if ((type & ZFS_TYPE_VDEV) && isnone &&
1849 (prop == VDEV_PROP_CHECKSUM_N ||
1850 prop == VDEV_PROP_CHECKSUM_T ||
1851 prop == VDEV_PROP_IO_N ||
1852 prop == VDEV_PROP_IO_T ||
1853 prop == VDEV_PROP_SLOW_IO_N ||
1854 prop == VDEV_PROP_SLOW_IO_T)) {
1855 *ivalp = UINT64_MAX;
1859 * Special handling for setting 'refreservation' to 'auto'. Use
1860 * UINT64_MAX to tell the caller to use zfs_fix_auto_resv().
1861 * 'auto' is only allowed on volumes.
1863 if (isauto) {
1864 switch (prop) {
1865 case ZFS_PROP_REFRESERVATION:
1866 if ((type & ZFS_TYPE_VOLUME) == 0) {
1867 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1868 "'%s=auto' only allowed on "
1869 "volumes"), nvpair_name(elem));
1870 goto error;
1872 *ivalp = UINT64_MAX;
1873 break;
1874 case ZPOOL_PROP_DEDUP_TABLE_QUOTA:
1875 ASSERT(type & ZFS_TYPE_POOL);
1876 *ivalp = UINT64_MAX;
1877 break;
1878 default:
1879 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1880 "'auto' is invalid value for '%s'"),
1881 nvpair_name(elem));
1882 goto error;
1886 break;
1888 case PROP_TYPE_INDEX:
1889 if (datatype != DATA_TYPE_STRING) {
1890 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1891 "'%s' must be a string"), nvpair_name(elem));
1892 goto error;
1895 (void) nvpair_value_string(elem, &value);
1897 if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1898 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1899 "'%s' must be one of '%s'"), propname,
1900 zprop_values(prop, type));
1901 goto error;
1903 break;
1905 default:
1906 abort();
1910 * Add the result to our return set of properties.
1912 if (*svalp != NULL) {
1913 if (nvlist_add_string(ret, propname, *svalp) != 0) {
1914 (void) no_memory(hdl);
1915 return (-1);
1917 } else {
1918 if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1919 (void) no_memory(hdl);
1920 return (-1);
1924 return (0);
1925 error:
1926 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1927 return (-1);
1930 static int
1931 addlist(libzfs_handle_t *hdl, const char *propname, zprop_list_t **listp,
1932 zfs_type_t type)
1934 int prop = zprop_name_to_prop(propname, type);
1935 if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type, B_FALSE))
1936 prop = ZPROP_INVAL;
1939 * Return failure if no property table entry was found and this isn't
1940 * a user-defined property.
1942 if (prop == ZPROP_USERPROP && ((type == ZFS_TYPE_POOL &&
1943 !zfs_prop_user(propname) &&
1944 !zpool_prop_feature(propname) &&
1945 !zpool_prop_unsupported(propname)) ||
1946 ((type == ZFS_TYPE_DATASET) && !zfs_prop_user(propname) &&
1947 !zfs_prop_userquota(propname) && !zfs_prop_written(propname)) ||
1948 ((type == ZFS_TYPE_VDEV) && !vdev_prop_user(propname)))) {
1949 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1950 "invalid property '%s'"), propname);
1951 return (zfs_error(hdl, EZFS_BADPROP,
1952 dgettext(TEXT_DOMAIN, "bad property list")));
1955 zprop_list_t *entry = zfs_alloc(hdl, sizeof (*entry));
1957 entry->pl_prop = prop;
1958 if (prop == ZPROP_USERPROP) {
1959 entry->pl_user_prop = zfs_strdup(hdl, propname);
1960 entry->pl_width = strlen(propname);
1961 } else {
1962 entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1963 type);
1966 *listp = entry;
1968 return (0);
1972 * Given a comma-separated list of properties, construct a property list
1973 * containing both user-defined and native properties. This function will
1974 * return a NULL list if 'all' is specified, which can later be expanded
1975 * by zprop_expand_list().
1978 zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1979 zfs_type_t type)
1981 *listp = NULL;
1984 * If 'all' is specified, return a NULL list.
1986 if (strcmp(props, "all") == 0)
1987 return (0);
1990 * If no props were specified, return an error.
1992 if (props[0] == '\0') {
1993 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1994 "no properties specified"));
1995 return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
1996 "bad property list")));
1999 for (char *p; (p = strsep(&props, ",")); )
2000 if (strcmp(p, "space") == 0) {
2001 static const char *const spaceprops[] = {
2002 "name", "avail", "used", "usedbysnapshots",
2003 "usedbydataset", "usedbyrefreservation",
2004 "usedbychildren"
2007 for (int i = 0; i < ARRAY_SIZE(spaceprops); i++) {
2008 if (addlist(hdl, spaceprops[i], listp, type))
2009 return (-1);
2010 listp = &(*listp)->pl_next;
2012 } else {
2013 if (addlist(hdl, p, listp, type))
2014 return (-1);
2015 listp = &(*listp)->pl_next;
2018 return (0);
2021 void
2022 zprop_free_list(zprop_list_t *pl)
2024 zprop_list_t *next;
2026 while (pl != NULL) {
2027 next = pl->pl_next;
2028 free(pl->pl_user_prop);
2029 free(pl);
2030 pl = next;
2034 typedef struct expand_data {
2035 zprop_list_t **last;
2036 libzfs_handle_t *hdl;
2037 zfs_type_t type;
2038 } expand_data_t;
2040 static int
2041 zprop_expand_list_cb(int prop, void *cb)
2043 zprop_list_t *entry;
2044 expand_data_t *edp = cb;
2046 entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t));
2048 entry->pl_prop = prop;
2049 entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
2050 entry->pl_all = B_TRUE;
2052 *(edp->last) = entry;
2053 edp->last = &entry->pl_next;
2055 return (ZPROP_CONT);
2059 zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
2061 zprop_list_t *entry;
2062 zprop_list_t **last;
2063 expand_data_t exp;
2065 if (*plp == NULL) {
2067 * If this is the very first time we've been called for an 'all'
2068 * specification, expand the list to include all native
2069 * properties.
2071 last = plp;
2073 exp.last = last;
2074 exp.hdl = hdl;
2075 exp.type = type;
2077 if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
2078 B_FALSE, type) == ZPROP_INVAL)
2079 return (-1);
2082 * Add 'name' to the beginning of the list, which is handled
2083 * specially.
2085 entry = zfs_alloc(hdl, sizeof (zprop_list_t));
2086 entry->pl_prop = ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
2087 ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME : ZFS_PROP_NAME));
2088 entry->pl_width = zprop_width(entry->pl_prop,
2089 &entry->pl_fixed, type);
2090 entry->pl_all = B_TRUE;
2091 entry->pl_next = *plp;
2092 *plp = entry;
2094 return (0);
2098 zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
2099 zfs_type_t type)
2101 return (zprop_iter_common(func, cb, show_all, ordered, type));
2104 const char *
2105 zfs_version_userland(void)
2107 return (ZFS_META_ALIAS);
2111 * Prints both zfs userland and kernel versions
2112 * Returns 0 on success, and -1 on error
2115 zfs_version_print(void)
2117 (void) puts(ZFS_META_ALIAS);
2119 char *kver = zfs_version_kernel();
2120 if (kver == NULL) {
2121 fprintf(stderr, "zfs_version_kernel() failed: %s\n",
2122 zfs_strerror(errno));
2123 return (-1);
2126 (void) printf("zfs-kmod-%s\n", kver);
2127 free(kver);
2128 return (0);
2132 * Returns an nvlist with both zfs userland and kernel versions.
2133 * Returns NULL on error.
2135 nvlist_t *
2136 zfs_version_nvlist(void)
2138 nvlist_t *nvl;
2139 char kmod_ver[64];
2140 if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
2141 return (NULL);
2142 if (nvlist_add_string(nvl, "userland", ZFS_META_ALIAS) != 0)
2143 goto err;
2144 char *kver = zfs_version_kernel();
2145 if (kver == NULL) {
2146 fprintf(stderr, "zfs_version_kernel() failed: %s\n",
2147 zfs_strerror(errno));
2148 goto err;
2150 (void) snprintf(kmod_ver, 64, "zfs-kmod-%s", kver);
2151 if (nvlist_add_string(nvl, "kernel", kmod_ver) != 0)
2152 goto err;
2153 return (nvl);
2154 err:
2155 nvlist_free(nvl);
2156 return (NULL);
2160 * Return 1 if the user requested ANSI color output, and our terminal supports
2161 * it. Return 0 for no color.
2164 use_color(void)
2166 static int use_color = -1;
2167 char *term;
2170 * Optimization:
2172 * For each zpool invocation, we do a single check to see if we should
2173 * be using color or not, and cache that value for the lifetime of the
2174 * the zpool command. That makes it cheap to call use_color() when
2175 * we're printing with color. We assume that the settings are not going
2176 * to change during the invocation of a zpool command (the user isn't
2177 * going to change the ZFS_COLOR value while zpool is running, for
2178 * example).
2180 if (use_color != -1) {
2182 * We've already figured out if we should be using color or
2183 * not. Return the cached value.
2185 return (use_color);
2188 term = getenv("TERM");
2190 * The user sets the ZFS_COLOR env var set to enable zpool ANSI color
2191 * output. However if NO_COLOR is set (https://no-color.org/) then
2192 * don't use it. Also, don't use color if terminal doesn't support
2193 * it.
2195 if (libzfs_envvar_is_set("ZFS_COLOR") &&
2196 !libzfs_envvar_is_set("NO_COLOR") &&
2197 isatty(STDOUT_FILENO) && term && strcmp("dumb", term) != 0 &&
2198 strcmp("unknown", term) != 0) {
2199 /* Color supported */
2200 use_color = 1;
2201 } else {
2202 use_color = 0;
2205 return (use_color);
2209 * The functions color_start() and color_end() are used for when you want
2210 * to colorize a block of text.
2212 * For example:
2213 * color_start(ANSI_RED)
2214 * printf("hello");
2215 * printf("world");
2216 * color_end();
2218 void
2219 color_start(const char *color)
2221 if (color && use_color()) {
2222 fputs(color, stdout);
2223 fflush(stdout);
2227 void
2228 color_end(void)
2230 if (use_color()) {
2231 fputs(ANSI_RESET, stdout);
2232 fflush(stdout);
2238 * printf() with a color. If color is NULL, then do a normal printf.
2241 printf_color(const char *color, const char *format, ...)
2243 va_list aptr;
2244 int rc;
2246 if (color)
2247 color_start(color);
2249 va_start(aptr, format);
2250 rc = vprintf(format, aptr);
2251 va_end(aptr);
2253 if (color)
2254 color_end();
2256 return (rc);
2259 /* PATH + 5 env vars + a NULL entry = 7 */
2260 #define ZPOOL_VDEV_SCRIPT_ENV_COUNT 7
2263 * There's a few places where ZFS will call external scripts (like the script
2264 * in zpool.d/ and `zfs_prepare_disk`). These scripts are called with a
2265 * reduced $PATH, and some vdev specific environment vars set. This function
2266 * will allocate an populate the environment variable array that is passed to
2267 * these scripts. The user must free the arrays with zpool_vdev_free_env() when
2268 * they are done.
2270 * The following env vars will be set (but value could be blank):
2272 * POOL_NAME
2273 * VDEV_PATH
2274 * VDEV_UPATH
2275 * VDEV_ENC_SYSFS_PATH
2277 * In addition, you can set an optional environment variable named 'opt_key'
2278 * to 'opt_val' if you want.
2280 * Returns allocated env[] array on success, NULL otherwise.
2282 char **
2283 zpool_vdev_script_alloc_env(const char *pool_name,
2284 const char *vdev_path, const char *vdev_upath,
2285 const char *vdev_enc_sysfs_path, const char *opt_key, const char *opt_val)
2287 char **env = NULL;
2288 int rc;
2290 env = calloc(ZPOOL_VDEV_SCRIPT_ENV_COUNT, sizeof (*env));
2291 if (!env)
2292 return (NULL);
2294 env[0] = strdup("PATH=/bin:/sbin:/usr/bin:/usr/sbin");
2295 if (!env[0])
2296 goto error;
2298 /* Setup our custom environment variables */
2299 rc = asprintf(&env[1], "POOL_NAME=%s", pool_name ? pool_name : "");
2300 if (rc == -1) {
2301 env[1] = NULL;
2302 goto error;
2305 rc = asprintf(&env[2], "VDEV_PATH=%s", vdev_path ? vdev_path : "");
2306 if (rc == -1) {
2307 env[2] = NULL;
2308 goto error;
2311 rc = asprintf(&env[3], "VDEV_UPATH=%s", vdev_upath ? vdev_upath : "");
2312 if (rc == -1) {
2313 env[3] = NULL;
2314 goto error;
2317 rc = asprintf(&env[4], "VDEV_ENC_SYSFS_PATH=%s",
2318 vdev_enc_sysfs_path ? vdev_enc_sysfs_path : "");
2319 if (rc == -1) {
2320 env[4] = NULL;
2321 goto error;
2324 if (opt_key != NULL) {
2325 rc = asprintf(&env[5], "%s=%s", opt_key,
2326 opt_val ? opt_val : "");
2327 if (rc == -1) {
2328 env[5] = NULL;
2329 goto error;
2333 return (env);
2335 error:
2336 for (int i = 0; i < ZPOOL_VDEV_SCRIPT_ENV_COUNT; i++)
2337 free(env[i]);
2339 free(env);
2341 return (NULL);
2345 * Free the env[] array that was allocated by zpool_vdev_script_alloc_env().
2347 void
2348 zpool_vdev_script_free_env(char **env)
2350 for (int i = 0; i < ZPOOL_VDEV_SCRIPT_ENV_COUNT; i++)
2351 free(env[i]);
2353 free(env);
2357 * Prepare a disk by (optionally) running a program before labeling the disk.
2358 * This can be useful for installing disk firmware or doing some pre-flight
2359 * checks on the disk before it becomes part of the pool. The program run is
2360 * located at ZFSEXECDIR/zfs_prepare_disk
2361 * (E.x: /usr/local/libexec/zfs/zfs_prepare_disk).
2363 * Return 0 on success, non-zero on failure.
2366 zpool_prepare_disk(zpool_handle_t *zhp, nvlist_t *vdev_nv,
2367 const char *prepare_str, char **lines[], int *lines_cnt)
2369 const char *script_path = ZFSEXECDIR "/zfs_prepare_disk";
2370 const char *pool_name;
2371 int rc = 0;
2373 /* Path to script and a NULL entry */
2374 char *argv[2] = {(char *)script_path};
2375 char **env = NULL;
2376 const char *path = NULL, *enc_sysfs_path = NULL;
2377 char *upath;
2378 *lines_cnt = 0;
2380 if (access(script_path, X_OK) != 0) {
2381 /* No script, nothing to do */
2382 return (0);
2385 (void) nvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_PATH, &path);
2386 (void) nvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_VDEV_ENC_SYSFS_PATH,
2387 &enc_sysfs_path);
2389 upath = zfs_get_underlying_path(path);
2390 pool_name = zhp ? zpool_get_name(zhp) : NULL;
2392 env = zpool_vdev_script_alloc_env(pool_name, path, upath,
2393 enc_sysfs_path, "VDEV_PREPARE", prepare_str);
2395 free(upath);
2397 if (env == NULL) {
2398 return (ENOMEM);
2401 rc = libzfs_run_process_get_stdout(script_path, argv, env, lines,
2402 lines_cnt);
2404 zpool_vdev_script_free_env(env);
2406 return (rc);
2410 * Optionally run a script and then label a disk. The script can be used to
2411 * prepare a disk for inclusion into the pool. For example, it might update
2412 * the disk's firmware or check its health.
2414 * The 'name' provided is the short name, stripped of any leading
2415 * /dev path, and is passed to zpool_label_disk. vdev_nv is the nvlist for
2416 * the vdev. prepare_str is a string that gets passed as the VDEV_PREPARE
2417 * env variable to the script.
2419 * The following env vars are passed to the script:
2421 * POOL_NAME: The pool name (blank during zpool create)
2422 * VDEV_PREPARE: Reason why the disk is being prepared for inclusion:
2423 * "create", "add", "replace", or "autoreplace"
2424 * VDEV_PATH: Path to the disk
2425 * VDEV_UPATH: One of the 'underlying paths' to the disk. This is
2426 * useful for DM devices.
2427 * VDEV_ENC_SYSFS_PATH: Path to the disk's enclosure sysfs path, if available.
2429 * Note, some of these values can be blank.
2431 * Return 0 on success, non-zero otherwise.
2434 zpool_prepare_and_label_disk(libzfs_handle_t *hdl, zpool_handle_t *zhp,
2435 const char *name, nvlist_t *vdev_nv, const char *prepare_str,
2436 char **lines[], int *lines_cnt)
2438 int rc;
2439 char vdev_path[MAXPATHLEN];
2440 (void) snprintf(vdev_path, sizeof (vdev_path), "%s/%s", DISK_ROOT,
2441 name);
2443 /* zhp will be NULL when creating a pool */
2444 rc = zpool_prepare_disk(zhp, vdev_nv, prepare_str, lines, lines_cnt);
2445 if (rc != 0)
2446 return (rc);
2448 rc = zpool_label_disk(hdl, zhp, name);
2449 return (rc);