Force fault a vdev with 'zpool offline -f'
[zfs.git] / lib / libzfs / libzfs_util.c
blobc281f9eb3239cdf35efc150bc0b14e672d270fa6
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
25 * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
26 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
30 * Internal utility routines for the ZFS library.
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <libintl.h>
36 #include <stdarg.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <strings.h>
40 #include <unistd.h>
41 #include <ctype.h>
42 #include <math.h>
43 #include <sys/stat.h>
44 #include <sys/mnttab.h>
45 #include <sys/mntent.h>
46 #include <sys/types.h>
47 #include <sys/wait.h>
49 #include <libzfs.h>
50 #include <libzfs_core.h>
52 #include "libzfs_impl.h"
53 #include "zfs_prop.h"
54 #include "zfeature_common.h"
55 #include <zfs_fletcher.h>
57 int
58 libzfs_errno(libzfs_handle_t *hdl)
60 return (hdl->libzfs_error);
63 const char *
64 libzfs_error_init(int error)
66 switch (error) {
67 case ENXIO:
68 return (dgettext(TEXT_DOMAIN, "The ZFS modules are not "
69 "loaded.\nTry running '/sbin/modprobe zfs' as root "
70 "to load them.\n"));
71 case ENOENT:
72 return (dgettext(TEXT_DOMAIN, "/dev/zfs and /proc/self/mounts "
73 "are required.\nTry running 'udevadm trigger' and 'mount "
74 "-t proc proc /proc' as root.\n"));
75 case ENOEXEC:
76 return (dgettext(TEXT_DOMAIN, "The ZFS modules cannot be "
77 "auto-loaded.\nTry running '/sbin/modprobe zfs' as "
78 "root to manually load them.\n"));
79 case EACCES:
80 return (dgettext(TEXT_DOMAIN, "Permission denied the "
81 "ZFS utilities must be run as root.\n"));
82 default:
83 return (dgettext(TEXT_DOMAIN, "Failed to initialize the "
84 "libzfs library.\n"));
88 const char *
89 libzfs_error_action(libzfs_handle_t *hdl)
91 return (hdl->libzfs_action);
94 const char *
95 libzfs_error_description(libzfs_handle_t *hdl)
97 if (hdl->libzfs_desc[0] != '\0')
98 return (hdl->libzfs_desc);
100 switch (hdl->libzfs_error) {
101 case EZFS_NOMEM:
102 return (dgettext(TEXT_DOMAIN, "out of memory"));
103 case EZFS_BADPROP:
104 return (dgettext(TEXT_DOMAIN, "invalid property value"));
105 case EZFS_PROPREADONLY:
106 return (dgettext(TEXT_DOMAIN, "read-only property"));
107 case EZFS_PROPTYPE:
108 return (dgettext(TEXT_DOMAIN, "property doesn't apply to "
109 "datasets of this type"));
110 case EZFS_PROPNONINHERIT:
111 return (dgettext(TEXT_DOMAIN, "property cannot be inherited"));
112 case EZFS_PROPSPACE:
113 return (dgettext(TEXT_DOMAIN, "invalid quota or reservation"));
114 case EZFS_BADTYPE:
115 return (dgettext(TEXT_DOMAIN, "operation not applicable to "
116 "datasets of this type"));
117 case EZFS_BUSY:
118 return (dgettext(TEXT_DOMAIN, "pool or dataset is busy"));
119 case EZFS_EXISTS:
120 return (dgettext(TEXT_DOMAIN, "pool or dataset exists"));
121 case EZFS_NOENT:
122 return (dgettext(TEXT_DOMAIN, "no such pool or dataset"));
123 case EZFS_BADSTREAM:
124 return (dgettext(TEXT_DOMAIN, "invalid backup stream"));
125 case EZFS_DSREADONLY:
126 return (dgettext(TEXT_DOMAIN, "dataset is read-only"));
127 case EZFS_VOLTOOBIG:
128 return (dgettext(TEXT_DOMAIN, "volume size exceeds limit for "
129 "this system"));
130 case EZFS_INVALIDNAME:
131 return (dgettext(TEXT_DOMAIN, "invalid name"));
132 case EZFS_BADRESTORE:
133 return (dgettext(TEXT_DOMAIN, "unable to restore to "
134 "destination"));
135 case EZFS_BADBACKUP:
136 return (dgettext(TEXT_DOMAIN, "backup failed"));
137 case EZFS_BADTARGET:
138 return (dgettext(TEXT_DOMAIN, "invalid target vdev"));
139 case EZFS_NODEVICE:
140 return (dgettext(TEXT_DOMAIN, "no such device in pool"));
141 case EZFS_BADDEV:
142 return (dgettext(TEXT_DOMAIN, "invalid device"));
143 case EZFS_NOREPLICAS:
144 return (dgettext(TEXT_DOMAIN, "no valid replicas"));
145 case EZFS_RESILVERING:
146 return (dgettext(TEXT_DOMAIN, "currently resilvering"));
147 case EZFS_BADVERSION:
148 return (dgettext(TEXT_DOMAIN, "unsupported version or "
149 "feature"));
150 case EZFS_POOLUNAVAIL:
151 return (dgettext(TEXT_DOMAIN, "pool is unavailable"));
152 case EZFS_DEVOVERFLOW:
153 return (dgettext(TEXT_DOMAIN, "too many devices in one vdev"));
154 case EZFS_BADPATH:
155 return (dgettext(TEXT_DOMAIN, "must be an absolute path"));
156 case EZFS_CROSSTARGET:
157 return (dgettext(TEXT_DOMAIN, "operation crosses datasets or "
158 "pools"));
159 case EZFS_ZONED:
160 return (dgettext(TEXT_DOMAIN, "dataset in use by local zone"));
161 case EZFS_MOUNTFAILED:
162 return (dgettext(TEXT_DOMAIN, "mount failed"));
163 case EZFS_UMOUNTFAILED:
164 return (dgettext(TEXT_DOMAIN, "umount failed"));
165 case EZFS_UNSHARENFSFAILED:
166 return (dgettext(TEXT_DOMAIN, "unshare(1M) failed"));
167 case EZFS_SHARENFSFAILED:
168 return (dgettext(TEXT_DOMAIN, "share(1M) failed"));
169 case EZFS_UNSHARESMBFAILED:
170 return (dgettext(TEXT_DOMAIN, "smb remove share failed"));
171 case EZFS_SHARESMBFAILED:
172 return (dgettext(TEXT_DOMAIN, "smb add share failed"));
173 case EZFS_PERM:
174 return (dgettext(TEXT_DOMAIN, "permission denied"));
175 case EZFS_NOSPC:
176 return (dgettext(TEXT_DOMAIN, "out of space"));
177 case EZFS_FAULT:
178 return (dgettext(TEXT_DOMAIN, "bad address"));
179 case EZFS_IO:
180 return (dgettext(TEXT_DOMAIN, "I/O error"));
181 case EZFS_INTR:
182 return (dgettext(TEXT_DOMAIN, "signal received"));
183 case EZFS_ISSPARE:
184 return (dgettext(TEXT_DOMAIN, "device is reserved as a hot "
185 "spare"));
186 case EZFS_INVALCONFIG:
187 return (dgettext(TEXT_DOMAIN, "invalid vdev configuration"));
188 case EZFS_RECURSIVE:
189 return (dgettext(TEXT_DOMAIN, "recursive dataset dependency"));
190 case EZFS_NOHISTORY:
191 return (dgettext(TEXT_DOMAIN, "no history available"));
192 case EZFS_POOLPROPS:
193 return (dgettext(TEXT_DOMAIN, "failed to retrieve "
194 "pool properties"));
195 case EZFS_POOL_NOTSUP:
196 return (dgettext(TEXT_DOMAIN, "operation not supported "
197 "on this type of pool"));
198 case EZFS_POOL_INVALARG:
199 return (dgettext(TEXT_DOMAIN, "invalid argument for "
200 "this pool operation"));
201 case EZFS_NAMETOOLONG:
202 return (dgettext(TEXT_DOMAIN, "dataset name is too long"));
203 case EZFS_OPENFAILED:
204 return (dgettext(TEXT_DOMAIN, "open failed"));
205 case EZFS_NOCAP:
206 return (dgettext(TEXT_DOMAIN,
207 "disk capacity information could not be retrieved"));
208 case EZFS_LABELFAILED:
209 return (dgettext(TEXT_DOMAIN, "write of label failed"));
210 case EZFS_BADWHO:
211 return (dgettext(TEXT_DOMAIN, "invalid user/group"));
212 case EZFS_BADPERM:
213 return (dgettext(TEXT_DOMAIN, "invalid permission"));
214 case EZFS_BADPERMSET:
215 return (dgettext(TEXT_DOMAIN, "invalid permission set name"));
216 case EZFS_NODELEGATION:
217 return (dgettext(TEXT_DOMAIN, "delegated administration is "
218 "disabled on pool"));
219 case EZFS_BADCACHE:
220 return (dgettext(TEXT_DOMAIN, "invalid or missing cache file"));
221 case EZFS_ISL2CACHE:
222 return (dgettext(TEXT_DOMAIN, "device is in use as a cache"));
223 case EZFS_VDEVNOTSUP:
224 return (dgettext(TEXT_DOMAIN, "vdev specification is not "
225 "supported"));
226 case EZFS_NOTSUP:
227 return (dgettext(TEXT_DOMAIN, "operation not supported "
228 "on this dataset"));
229 case EZFS_ACTIVE_SPARE:
230 return (dgettext(TEXT_DOMAIN, "pool has active shared spare "
231 "device"));
232 case EZFS_UNPLAYED_LOGS:
233 return (dgettext(TEXT_DOMAIN, "log device has unplayed intent "
234 "logs"));
235 case EZFS_REFTAG_RELE:
236 return (dgettext(TEXT_DOMAIN, "no such tag on this dataset"));
237 case EZFS_REFTAG_HOLD:
238 return (dgettext(TEXT_DOMAIN, "tag already exists on this "
239 "dataset"));
240 case EZFS_TAGTOOLONG:
241 return (dgettext(TEXT_DOMAIN, "tag too long"));
242 case EZFS_PIPEFAILED:
243 return (dgettext(TEXT_DOMAIN, "pipe create failed"));
244 case EZFS_THREADCREATEFAILED:
245 return (dgettext(TEXT_DOMAIN, "thread create failed"));
246 case EZFS_POSTSPLIT_ONLINE:
247 return (dgettext(TEXT_DOMAIN, "disk was split from this pool "
248 "into a new one"));
249 case EZFS_SCRUBBING:
250 return (dgettext(TEXT_DOMAIN, "currently scrubbing; "
251 "use 'zpool scrub -s' to cancel current scrub"));
252 case EZFS_NO_SCRUB:
253 return (dgettext(TEXT_DOMAIN, "there is no active scrub"));
254 case EZFS_DIFF:
255 return (dgettext(TEXT_DOMAIN, "unable to generate diffs"));
256 case EZFS_DIFFDATA:
257 return (dgettext(TEXT_DOMAIN, "invalid diff data"));
258 case EZFS_POOLREADONLY:
259 return (dgettext(TEXT_DOMAIN, "pool is read-only"));
260 case EZFS_UNKNOWN:
261 return (dgettext(TEXT_DOMAIN, "unknown error"));
262 default:
263 assert(hdl->libzfs_error == 0);
264 return (dgettext(TEXT_DOMAIN, "no error"));
268 /*PRINTFLIKE2*/
269 void
270 zfs_error_aux(libzfs_handle_t *hdl, const char *fmt, ...)
272 va_list ap;
274 va_start(ap, fmt);
276 (void) vsnprintf(hdl->libzfs_desc, sizeof (hdl->libzfs_desc),
277 fmt, ap);
278 hdl->libzfs_desc_active = 1;
280 va_end(ap);
283 static void
284 zfs_verror(libzfs_handle_t *hdl, int error, const char *fmt, va_list ap)
286 (void) vsnprintf(hdl->libzfs_action, sizeof (hdl->libzfs_action),
287 fmt, ap);
288 hdl->libzfs_error = error;
290 if (hdl->libzfs_desc_active)
291 hdl->libzfs_desc_active = 0;
292 else
293 hdl->libzfs_desc[0] = '\0';
295 if (hdl->libzfs_printerr) {
296 if (error == EZFS_UNKNOWN) {
297 (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "internal "
298 "error: %s\n"), libzfs_error_description(hdl));
299 abort();
302 (void) fprintf(stderr, "%s: %s\n", hdl->libzfs_action,
303 libzfs_error_description(hdl));
304 if (error == EZFS_NOMEM)
305 exit(1);
310 zfs_error(libzfs_handle_t *hdl, int error, const char *msg)
312 return (zfs_error_fmt(hdl, error, "%s", msg));
315 /*PRINTFLIKE3*/
317 zfs_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
319 va_list ap;
321 va_start(ap, fmt);
323 zfs_verror(hdl, error, fmt, ap);
325 va_end(ap);
327 return (-1);
330 static int
331 zfs_common_error(libzfs_handle_t *hdl, int error, const char *fmt,
332 va_list ap)
334 switch (error) {
335 case EPERM:
336 case EACCES:
337 zfs_verror(hdl, EZFS_PERM, fmt, ap);
338 return (-1);
340 case ECANCELED:
341 zfs_verror(hdl, EZFS_NODELEGATION, fmt, ap);
342 return (-1);
344 case EIO:
345 zfs_verror(hdl, EZFS_IO, fmt, ap);
346 return (-1);
348 case EFAULT:
349 zfs_verror(hdl, EZFS_FAULT, fmt, ap);
350 return (-1);
352 case EINTR:
353 zfs_verror(hdl, EZFS_INTR, fmt, ap);
354 return (-1);
357 return (0);
361 zfs_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
363 return (zfs_standard_error_fmt(hdl, error, "%s", msg));
366 /*PRINTFLIKE3*/
368 zfs_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
370 va_list ap;
372 va_start(ap, fmt);
374 if (zfs_common_error(hdl, error, fmt, ap) != 0) {
375 va_end(ap);
376 return (-1);
379 switch (error) {
380 case ENXIO:
381 case ENODEV:
382 case EPIPE:
383 zfs_verror(hdl, EZFS_IO, fmt, ap);
384 break;
386 case ENOENT:
387 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
388 "dataset does not exist"));
389 zfs_verror(hdl, EZFS_NOENT, fmt, ap);
390 break;
392 case ENOSPC:
393 case EDQUOT:
394 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
395 break;
397 case EEXIST:
398 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
399 "dataset already exists"));
400 zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
401 break;
403 case EBUSY:
404 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
405 "dataset is busy"));
406 zfs_verror(hdl, EZFS_BUSY, fmt, ap);
407 break;
408 case EROFS:
409 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
410 break;
411 case ENAMETOOLONG:
412 zfs_verror(hdl, EZFS_NAMETOOLONG, fmt, ap);
413 break;
414 case ENOTSUP:
415 zfs_verror(hdl, EZFS_BADVERSION, fmt, ap);
416 break;
417 case EAGAIN:
418 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
419 "pool I/O is currently suspended"));
420 zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
421 break;
422 default:
423 zfs_error_aux(hdl, strerror(error));
424 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
425 break;
428 va_end(ap);
429 return (-1);
433 zpool_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
435 return (zpool_standard_error_fmt(hdl, error, "%s", msg));
438 /*PRINTFLIKE3*/
440 zpool_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
442 va_list ap;
444 va_start(ap, fmt);
446 if (zfs_common_error(hdl, error, fmt, ap) != 0) {
447 va_end(ap);
448 return (-1);
451 switch (error) {
452 case ENODEV:
453 zfs_verror(hdl, EZFS_NODEVICE, fmt, ap);
454 break;
456 case ENOENT:
457 zfs_error_aux(hdl,
458 dgettext(TEXT_DOMAIN, "no such pool or dataset"));
459 zfs_verror(hdl, EZFS_NOENT, fmt, ap);
460 break;
462 case EEXIST:
463 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
464 "pool already exists"));
465 zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
466 break;
468 case EBUSY:
469 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool is busy"));
470 zfs_verror(hdl, EZFS_BUSY, fmt, ap);
471 break;
473 case ENXIO:
474 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
475 "one or more devices is currently unavailable"));
476 zfs_verror(hdl, EZFS_BADDEV, fmt, ap);
477 break;
479 case ENAMETOOLONG:
480 zfs_verror(hdl, EZFS_DEVOVERFLOW, fmt, ap);
481 break;
483 case ENOTSUP:
484 zfs_verror(hdl, EZFS_POOL_NOTSUP, fmt, ap);
485 break;
487 case EINVAL:
488 zfs_verror(hdl, EZFS_POOL_INVALARG, fmt, ap);
489 break;
491 case ENOSPC:
492 case EDQUOT:
493 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
494 return (-1);
496 case EAGAIN:
497 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
498 "pool I/O is currently suspended"));
499 zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
500 break;
502 case EROFS:
503 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
504 break;
505 case EDOM:
506 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
507 "block size out of range or does not match"));
508 zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
509 break;
511 default:
512 zfs_error_aux(hdl, strerror(error));
513 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
516 va_end(ap);
517 return (-1);
521 * Display an out of memory error message and abort the current program.
524 no_memory(libzfs_handle_t *hdl)
526 return (zfs_error(hdl, EZFS_NOMEM, "internal error"));
530 * A safe form of malloc() which will die if the allocation fails.
532 void *
533 zfs_alloc(libzfs_handle_t *hdl, size_t size)
535 void *data;
537 if ((data = calloc(1, size)) == NULL)
538 (void) no_memory(hdl);
540 return (data);
544 * A safe form of asprintf() which will die if the allocation fails.
546 /*PRINTFLIKE2*/
547 char *
548 zfs_asprintf(libzfs_handle_t *hdl, const char *fmt, ...)
550 va_list ap;
551 char *ret;
552 int err;
554 va_start(ap, fmt);
556 err = vasprintf(&ret, fmt, ap);
558 va_end(ap);
560 if (err < 0)
561 (void) no_memory(hdl);
563 return (ret);
567 * A safe form of realloc(), which also zeroes newly allocated space.
569 void *
570 zfs_realloc(libzfs_handle_t *hdl, void *ptr, size_t oldsize, size_t newsize)
572 void *ret;
574 if ((ret = realloc(ptr, newsize)) == NULL) {
575 (void) no_memory(hdl);
576 return (NULL);
579 bzero((char *)ret + oldsize, (newsize - oldsize));
580 return (ret);
584 * A safe form of strdup() which will die if the allocation fails.
586 char *
587 zfs_strdup(libzfs_handle_t *hdl, const char *str)
589 char *ret;
591 if ((ret = strdup(str)) == NULL)
592 (void) no_memory(hdl);
594 return (ret);
598 * Convert a number to an appropriately human-readable output.
600 void
601 zfs_nicenum_format(uint64_t num, char *buf, size_t buflen,
602 enum zfs_nicenum_format format)
604 uint64_t n = num;
605 int index = 0;
606 const char *u;
607 const char *units[3][7] = {
608 [ZFS_NICENUM_1024] = {"", "K", "M", "G", "T", "P", "E"},
609 [ZFS_NICENUM_BYTES] = {"B", "K", "M", "G", "T", "P", "E"},
610 [ZFS_NICENUM_TIME] = {"ns", "us", "ms", "s", "?", "?", "?"}
613 const int units_len[] = {[ZFS_NICENUM_1024] = 6,
614 [ZFS_NICENUM_BYTES] = 6,
615 [ZFS_NICENUM_TIME] = 4};
617 const int k_unit[] = { [ZFS_NICENUM_1024] = 1024,
618 [ZFS_NICENUM_BYTES] = 1024,
619 [ZFS_NICENUM_TIME] = 1000};
621 double val;
623 if (format == ZFS_NICENUM_RAW) {
624 snprintf(buf, buflen, "%llu", (u_longlong_t)num);
625 return;
629 while (n >= k_unit[format] && index < units_len[format]) {
630 n /= k_unit[format];
631 index++;
634 u = units[format][index];
636 /* Don't print 0ns times */
637 if ((format == ZFS_NICENUM_TIME) && (num == 0)) {
638 (void) snprintf(buf, buflen, "-");
639 } else if ((index == 0) || ((num %
640 (uint64_t)powl(k_unit[format], index)) == 0)) {
642 * If this is an even multiple of the base, always display
643 * without any decimal precision.
645 (void) snprintf(buf, buflen, "%llu%s", (u_longlong_t)n, u);
647 } else {
649 * We want to choose a precision that reflects the best choice
650 * for fitting in 5 characters. This can get rather tricky when
651 * we have numbers that are very close to an order of magnitude.
652 * For example, when displaying 10239 (which is really 9.999K),
653 * we want only a single place of precision for 10.0K. We could
654 * develop some complex heuristics for this, but it's much
655 * easier just to try each combination in turn.
657 int i;
658 for (i = 2; i >= 0; i--) {
659 val = (double)num /
660 (uint64_t)powl(k_unit[format], index);
663 * Don't print floating point values for time. Note,
664 * we use floor() instead of round() here, since
665 * round can result in undesirable results. For
666 * example, if "num" is in the range of
667 * 999500-999999, it will print out "1000us". This
668 * doesn't happen if we use floor().
670 if (format == ZFS_NICENUM_TIME) {
671 if (snprintf(buf, buflen, "%d%s",
672 (unsigned int) floor(val), u) <= 5)
673 break;
675 } else {
676 if (snprintf(buf, buflen, "%.*f%s", i,
677 val, u) <= 5)
678 break;
685 * Convert a number to an appropriately human-readable output.
687 void
688 zfs_nicenum(uint64_t num, char *buf, size_t buflen)
690 zfs_nicenum_format(num, buf, buflen, ZFS_NICENUM_1024);
694 * Convert a time to an appropriately human-readable output.
695 * @num: Time in nanoseconds
697 void
698 zfs_nicetime(uint64_t num, char *buf, size_t buflen)
700 zfs_nicenum_format(num, buf, buflen, ZFS_NICENUM_TIME);
704 * Print out a raw number with correct column spacing
706 void
707 zfs_niceraw(uint64_t num, char *buf, size_t buflen)
709 zfs_nicenum_format(num, buf, buflen, ZFS_NICENUM_RAW);
713 * Convert a number of bytes to an appropriately human-readable output.
715 void
716 zfs_nicebytes(uint64_t num, char *buf, size_t buflen)
718 zfs_nicenum_format(num, buf, buflen, ZFS_NICENUM_BYTES);
721 void
722 libzfs_print_on_error(libzfs_handle_t *hdl, boolean_t printerr)
724 hdl->libzfs_printerr = printerr;
727 static int
728 libzfs_module_loaded(const char *module)
730 const char path_prefix[] = "/sys/module/";
731 char path[256];
733 memcpy(path, path_prefix, sizeof (path_prefix) - 1);
734 strcpy(path + sizeof (path_prefix) - 1, module);
736 return (access(path, F_OK) == 0);
741 * Read lines from an open file descriptor and store them in an array of
742 * strings until EOF. lines[] will be allocated and populated with all the
743 * lines read. All newlines are replaced with NULL terminators for
744 * convenience. lines[] must be freed after use with libzfs_free_str_array().
746 * Returns the number of lines read.
748 static int
749 libzfs_read_stdout_from_fd(int fd, char **lines[])
752 FILE *fp;
753 int lines_cnt = 0;
754 size_t len = 0;
755 char *line = NULL;
756 char **tmp_lines = NULL, **tmp;
757 char *nl = NULL;
758 int rc;
760 fp = fdopen(fd, "r");
761 if (fp == NULL)
762 return (0);
763 while (1) {
764 rc = getline(&line, &len, fp);
765 if (rc == -1)
766 break;
768 tmp = realloc(tmp_lines, sizeof (*tmp_lines) * (lines_cnt + 1));
769 if (tmp == NULL) {
770 /* Return the lines we were able to process */
771 break;
773 tmp_lines = tmp;
775 /* Terminate newlines */
776 if ((nl = strchr(line, '\n')) != NULL)
777 *nl = '\0';
778 tmp_lines[lines_cnt] = line;
779 lines_cnt++;
780 line = NULL;
782 fclose(fp);
783 *lines = tmp_lines;
784 return (lines_cnt);
787 static int
788 libzfs_run_process_impl(const char *path, char *argv[], char *env[], int flags,
789 char **lines[], int *lines_cnt)
791 pid_t pid;
792 int error, devnull_fd;
793 int link[2];
796 * Setup a pipe between our child and parent process if we're
797 * reading stdout.
799 if ((lines != NULL) && pipe(link) == -1)
800 return (-ESTRPIPE);
802 pid = vfork();
803 if (pid == 0) {
804 /* Child process */
805 devnull_fd = open("/dev/null", O_WRONLY);
807 if (devnull_fd < 0)
808 _exit(-1);
810 if (!(flags & STDOUT_VERBOSE) && (lines == NULL))
811 (void) dup2(devnull_fd, STDOUT_FILENO);
812 else if (lines != NULL) {
813 /* Save the output to lines[] */
814 dup2(link[1], STDOUT_FILENO);
815 close(link[0]);
816 close(link[1]);
819 if (!(flags & STDERR_VERBOSE))
820 (void) dup2(devnull_fd, STDERR_FILENO);
822 close(devnull_fd);
824 if (flags & NO_DEFAULT_PATH) {
825 if (env == NULL)
826 execv(path, argv);
827 else
828 execve(path, argv, env);
829 } else {
830 if (env == NULL)
831 execvp(path, argv);
832 else
833 execvpe(path, argv, env);
836 _exit(-1);
837 } else if (pid > 0) {
838 /* Parent process */
839 int status;
841 while ((error = waitpid(pid, &status, 0)) == -1 &&
842 errno == EINTR) { }
843 if (error < 0 || !WIFEXITED(status))
844 return (-1);
846 if (lines != NULL) {
847 close(link[1]);
848 *lines_cnt = libzfs_read_stdout_from_fd(link[0], lines);
850 return (WEXITSTATUS(status));
853 return (-1);
857 libzfs_run_process(const char *path, char *argv[], int flags)
859 return (libzfs_run_process_impl(path, argv, NULL, flags, NULL, NULL));
863 * Run a command and store its stdout lines in an array of strings (lines[]).
864 * lines[] is allocated and populated for you, and the number of lines is set in
865 * lines_cnt. lines[] must be freed after use with libzfs_free_str_array().
866 * All newlines (\n) in lines[] are terminated for convenience.
869 libzfs_run_process_get_stdout(const char *path, char *argv[], char *env[],
870 char **lines[], int *lines_cnt)
872 return (libzfs_run_process_impl(path, argv, env, 0, lines, lines_cnt));
876 * Same as libzfs_run_process_get_stdout(), but run without $PATH set. This
877 * means that *path needs to be the full path to the executable.
880 libzfs_run_process_get_stdout_nopath(const char *path, char *argv[],
881 char *env[], char **lines[], int *lines_cnt)
883 return (libzfs_run_process_impl(path, argv, env, NO_DEFAULT_PATH,
884 lines, lines_cnt));
888 * Free an array of strings. Free both the strings contained in the array and
889 * the array itself.
891 void
892 libzfs_free_str_array(char **strs, int count)
894 while (--count >= 0)
895 free(strs[count]);
897 free(strs);
901 * Returns 1 if environment variable is set to "YES", "yes", "ON", "on", or
902 * a non-zero number.
904 * Returns 0 otherwise.
907 libzfs_envvar_is_set(char *envvar)
909 char *env = getenv(envvar);
910 if (env && (strtoul(env, NULL, 0) > 0 ||
911 (!strncasecmp(env, "YES", 3) && strnlen(env, 4) == 3) ||
912 (!strncasecmp(env, "ON", 2) && strnlen(env, 3) == 2)))
913 return (1);
915 return (0);
919 * Verify the required ZFS_DEV device is available and optionally attempt
920 * to load the ZFS modules. Under normal circumstances the modules
921 * should already have been loaded by some external mechanism.
923 * Environment variables:
924 * - ZFS_MODULE_LOADING="YES|yes|ON|on" - Attempt to load modules.
925 * - ZFS_MODULE_TIMEOUT="<seconds>" - Seconds to wait for ZFS_DEV
927 static int
928 libzfs_load_module(const char *module)
930 char *argv[4] = {"/sbin/modprobe", "-q", (char *)module, (char *)0};
931 char *load_str, *timeout_str;
932 long timeout = 10; /* seconds */
933 long busy_timeout = 10; /* milliseconds */
934 int load = 0, fd;
935 hrtime_t start;
937 /* Optionally request module loading */
938 if (!libzfs_module_loaded(module)) {
939 load_str = getenv("ZFS_MODULE_LOADING");
940 if (load_str) {
941 if (!strncasecmp(load_str, "YES", strlen("YES")) ||
942 !strncasecmp(load_str, "ON", strlen("ON")))
943 load = 1;
944 else
945 load = 0;
948 if (load && libzfs_run_process("/sbin/modprobe", argv, 0))
949 return (ENOEXEC);
952 /* Module loading is synchronous it must be available */
953 if (!libzfs_module_loaded(module))
954 return (ENXIO);
957 * Device creation by udev is asynchronous and waiting may be
958 * required. Busy wait for 10ms and then fall back to polling every
959 * 10ms for the allowed timeout (default 10s, max 10m). This is
960 * done to optimize for the common case where the device is
961 * immediately available and to avoid penalizing the possible
962 * case where udev is slow or unable to create the device.
964 timeout_str = getenv("ZFS_MODULE_TIMEOUT");
965 if (timeout_str) {
966 timeout = strtol(timeout_str, NULL, 0);
967 timeout = MAX(MIN(timeout, (10 * 60)), 0); /* 0 <= N <= 600 */
970 start = gethrtime();
971 do {
972 fd = open(ZFS_DEV, O_RDWR);
973 if (fd >= 0) {
974 (void) close(fd);
975 return (0);
976 } else if (errno != ENOENT) {
977 return (errno);
978 } else if (NSEC2MSEC(gethrtime() - start) < busy_timeout) {
979 sched_yield();
980 } else {
981 usleep(10 * MILLISEC);
983 } while (NSEC2MSEC(gethrtime() - start) < (timeout * MILLISEC));
985 return (ENOENT);
988 libzfs_handle_t *
989 libzfs_init(void)
991 libzfs_handle_t *hdl;
992 int error;
994 error = libzfs_load_module(ZFS_DRIVER);
995 if (error) {
996 errno = error;
997 return (NULL);
1000 if ((hdl = calloc(1, sizeof (libzfs_handle_t))) == NULL) {
1001 return (NULL);
1004 if ((hdl->libzfs_fd = open(ZFS_DEV, O_RDWR)) < 0) {
1005 free(hdl);
1006 return (NULL);
1009 #ifdef HAVE_SETMNTENT
1010 if ((hdl->libzfs_mnttab = setmntent(MNTTAB, "r")) == NULL) {
1011 #else
1012 if ((hdl->libzfs_mnttab = fopen(MNTTAB, "r")) == NULL) {
1013 #endif
1014 (void) close(hdl->libzfs_fd);
1015 free(hdl);
1016 return (NULL);
1019 hdl->libzfs_sharetab = fopen(ZFS_SHARETAB, "r");
1021 if (libzfs_core_init() != 0) {
1022 (void) close(hdl->libzfs_fd);
1023 (void) fclose(hdl->libzfs_mnttab);
1024 if (hdl->libzfs_sharetab)
1025 (void) fclose(hdl->libzfs_sharetab);
1026 free(hdl);
1027 return (NULL);
1030 zfs_prop_init();
1031 zpool_prop_init();
1032 zpool_feature_init();
1033 libzfs_mnttab_init(hdl);
1034 fletcher_4_init();
1036 return (hdl);
1039 void
1040 libzfs_fini(libzfs_handle_t *hdl)
1042 (void) close(hdl->libzfs_fd);
1043 if (hdl->libzfs_mnttab)
1044 #ifdef HAVE_SETMNTENT
1045 (void) endmntent(hdl->libzfs_mnttab);
1046 #else
1047 (void) fclose(hdl->libzfs_mnttab);
1048 #endif
1049 if (hdl->libzfs_sharetab)
1050 (void) fclose(hdl->libzfs_sharetab);
1051 zfs_uninit_libshare(hdl);
1052 zpool_free_handles(hdl);
1053 libzfs_fru_clear(hdl, B_TRUE);
1054 namespace_clear(hdl);
1055 libzfs_mnttab_fini(hdl);
1056 libzfs_core_fini();
1057 fletcher_4_fini();
1058 free(hdl);
1061 libzfs_handle_t *
1062 zpool_get_handle(zpool_handle_t *zhp)
1064 return (zhp->zpool_hdl);
1067 libzfs_handle_t *
1068 zfs_get_handle(zfs_handle_t *zhp)
1070 return (zhp->zfs_hdl);
1073 zpool_handle_t *
1074 zfs_get_pool_handle(const zfs_handle_t *zhp)
1076 return (zhp->zpool_hdl);
1080 * Given a name, determine whether or not it's a valid path
1081 * (starts with '/' or "./"). If so, walk the mnttab trying
1082 * to match the device number. If not, treat the path as an
1083 * fs/vol/snap/bkmark name.
1085 zfs_handle_t *
1086 zfs_path_to_zhandle(libzfs_handle_t *hdl, char *path, zfs_type_t argtype)
1088 struct stat64 statbuf;
1089 struct extmnttab entry;
1090 int ret;
1092 if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
1094 * It's not a valid path, assume it's a name of type 'argtype'.
1096 return (zfs_open(hdl, path, argtype));
1099 if (stat64(path, &statbuf) != 0) {
1100 (void) fprintf(stderr, "%s: %s\n", path, strerror(errno));
1101 return (NULL);
1104 /* Reopen MNTTAB to prevent reading stale data from open file */
1105 if (freopen(MNTTAB, "r", hdl->libzfs_mnttab) == NULL)
1106 return (NULL);
1108 while ((ret = getextmntent(hdl->libzfs_mnttab, &entry, 0)) == 0) {
1109 if (makedevice(entry.mnt_major, entry.mnt_minor) ==
1110 statbuf.st_dev) {
1111 break;
1114 if (ret != 0) {
1115 return (NULL);
1118 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
1119 (void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
1120 path);
1121 return (NULL);
1124 return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
1128 * Append partition suffix to an otherwise fully qualified device path.
1129 * This is used to generate the name the full path as its stored in
1130 * ZPOOL_CONFIG_PATH for whole disk devices. On success the new length
1131 * of 'path' will be returned on error a negative value is returned.
1134 zfs_append_partition(char *path, size_t max_len)
1136 int len = strlen(path);
1138 if ((strncmp(path, UDISK_ROOT, strlen(UDISK_ROOT)) == 0) ||
1139 (strncmp(path, ZVOL_ROOT, strlen(ZVOL_ROOT)) == 0)) {
1140 if (len + 6 >= max_len)
1141 return (-1);
1143 (void) strcat(path, "-part1");
1144 len += 6;
1145 } else {
1146 if (len + 2 >= max_len)
1147 return (-1);
1149 if (isdigit(path[len-1])) {
1150 (void) strcat(path, "p1");
1151 len += 2;
1152 } else {
1153 (void) strcat(path, "1");
1154 len += 1;
1158 return (len);
1162 * Given a shorthand device name check if a file by that name exists in any
1163 * of the 'zpool_default_import_path' or ZPOOL_IMPORT_PATH directories. If
1164 * one is found, store its fully qualified path in the 'path' buffer passed
1165 * by the caller and return 0, otherwise return an error.
1168 zfs_resolve_shortname(const char *name, char *path, size_t len)
1170 int i, error = -1;
1171 char *dir, *env, *envdup;
1173 env = getenv("ZPOOL_IMPORT_PATH");
1174 errno = ENOENT;
1176 if (env) {
1177 envdup = strdup(env);
1178 dir = strtok(envdup, ":");
1179 while (dir && error) {
1180 (void) snprintf(path, len, "%s/%s", dir, name);
1181 error = access(path, F_OK);
1182 dir = strtok(NULL, ":");
1184 free(envdup);
1185 } else {
1186 for (i = 0; i < DEFAULT_IMPORT_PATH_SIZE && error < 0; i++) {
1187 (void) snprintf(path, len, "%s/%s",
1188 zpool_default_import_path[i], name);
1189 error = access(path, F_OK);
1193 return (error ? ENOENT : 0);
1197 * Given a shorthand device name look for a match against 'cmp_name'. This
1198 * is done by checking all prefix expansions using either the default
1199 * 'zpool_default_import_paths' or the ZPOOL_IMPORT_PATH environment
1200 * variable. Proper partition suffixes will be appended if this is a
1201 * whole disk. When a match is found 0 is returned otherwise ENOENT.
1203 static int
1204 zfs_strcmp_shortname(char *name, char *cmp_name, int wholedisk)
1206 int path_len, cmp_len, i = 0, error = ENOENT;
1207 char *dir, *env, *envdup = NULL;
1208 char path_name[MAXPATHLEN];
1210 cmp_len = strlen(cmp_name);
1211 env = getenv("ZPOOL_IMPORT_PATH");
1213 if (env) {
1214 envdup = strdup(env);
1215 dir = strtok(envdup, ":");
1216 } else {
1217 dir = zpool_default_import_path[i];
1220 while (dir) {
1221 /* Trim trailing directory slashes from ZPOOL_IMPORT_PATH */
1222 while (dir[strlen(dir)-1] == '/')
1223 dir[strlen(dir)-1] = '\0';
1225 path_len = snprintf(path_name, MAXPATHLEN, "%s/%s", dir, name);
1226 if (wholedisk)
1227 path_len = zfs_append_partition(path_name, MAXPATHLEN);
1229 if ((path_len == cmp_len) && strcmp(path_name, cmp_name) == 0) {
1230 error = 0;
1231 break;
1234 if (env) {
1235 dir = strtok(NULL, ":");
1236 } else if (++i < DEFAULT_IMPORT_PATH_SIZE) {
1237 dir = zpool_default_import_path[i];
1238 } else {
1239 dir = NULL;
1243 if (env)
1244 free(envdup);
1246 return (error);
1250 * Given either a shorthand or fully qualified path name look for a match
1251 * against 'cmp'. The passed name will be expanded as needed for comparison
1252 * purposes and redundant slashes stripped to ensure an accurate match.
1255 zfs_strcmp_pathname(char *name, char *cmp, int wholedisk)
1257 int path_len, cmp_len;
1258 char path_name[MAXPATHLEN];
1259 char cmp_name[MAXPATHLEN];
1260 char *dir, *dup;
1262 /* Strip redundant slashes if one exists due to ZPOOL_IMPORT_PATH */
1263 memset(cmp_name, 0, MAXPATHLEN);
1264 dup = strdup(cmp);
1265 dir = strtok(dup, "/");
1266 while (dir) {
1267 strlcat(cmp_name, "/", sizeof (cmp_name));
1268 strlcat(cmp_name, dir, sizeof (cmp_name));
1269 dir = strtok(NULL, "/");
1271 free(dup);
1273 if (name[0] != '/')
1274 return (zfs_strcmp_shortname(name, cmp_name, wholedisk));
1276 (void) strlcpy(path_name, name, MAXPATHLEN);
1277 path_len = strlen(path_name);
1278 cmp_len = strlen(cmp_name);
1280 if (wholedisk) {
1281 path_len = zfs_append_partition(path_name, MAXPATHLEN);
1282 if (path_len == -1)
1283 return (ENOMEM);
1286 if ((path_len != cmp_len) || strcmp(path_name, cmp_name))
1287 return (ENOENT);
1289 return (0);
1293 * Given a full path to a device determine if that device appears in the
1294 * import search path. If it does return the first match and store the
1295 * index in the passed 'order' variable, otherwise return an error.
1298 zfs_path_order(char *name, int *order)
1300 int i = 0, error = ENOENT;
1301 char *dir, *env, *envdup;
1303 env = getenv("ZPOOL_IMPORT_PATH");
1304 if (env) {
1305 envdup = strdup(env);
1306 dir = strtok(envdup, ":");
1307 while (dir) {
1308 if (strncmp(name, dir, strlen(dir)) == 0) {
1309 *order = i;
1310 error = 0;
1311 break;
1313 dir = strtok(NULL, ":");
1314 i++;
1316 free(envdup);
1317 } else {
1318 for (i = 0; i < DEFAULT_IMPORT_PATH_SIZE; i++) {
1319 if (strncmp(name, zpool_default_import_path[i],
1320 strlen(zpool_default_import_path[i])) == 0) {
1321 *order = i;
1322 error = 0;
1323 break;
1328 return (error);
1332 * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
1333 * an ioctl().
1336 zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
1338 if (len == 0)
1339 len = 16 * 1024;
1340 zc->zc_nvlist_dst_size = len;
1341 zc->zc_nvlist_dst =
1342 (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1343 if (zc->zc_nvlist_dst == 0)
1344 return (-1);
1346 return (0);
1350 * Called when an ioctl() which returns an nvlist fails with ENOMEM. This will
1351 * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
1352 * filled in by the kernel to indicate the actual required size.
1355 zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
1357 free((void *)(uintptr_t)zc->zc_nvlist_dst);
1358 zc->zc_nvlist_dst =
1359 (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1360 if (zc->zc_nvlist_dst == 0)
1361 return (-1);
1363 return (0);
1367 * Called to free the src and dst nvlists stored in the command structure.
1369 void
1370 zcmd_free_nvlists(zfs_cmd_t *zc)
1372 free((void *)(uintptr_t)zc->zc_nvlist_conf);
1373 free((void *)(uintptr_t)zc->zc_nvlist_src);
1374 free((void *)(uintptr_t)zc->zc_nvlist_dst);
1375 zc->zc_nvlist_conf = 0;
1376 zc->zc_nvlist_src = 0;
1377 zc->zc_nvlist_dst = 0;
1380 static int
1381 zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
1382 nvlist_t *nvl)
1384 char *packed;
1385 size_t len;
1387 verify(nvlist_size(nvl, &len, NV_ENCODE_NATIVE) == 0);
1389 if ((packed = zfs_alloc(hdl, len)) == NULL)
1390 return (-1);
1392 verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
1394 *outnv = (uint64_t)(uintptr_t)packed;
1395 *outlen = len;
1397 return (0);
1401 zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1403 return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
1404 &zc->zc_nvlist_conf_size, nvl));
1408 zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1410 return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
1411 &zc->zc_nvlist_src_size, nvl));
1415 * Unpacks an nvlist from the ZFS ioctl command structure.
1418 zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
1420 if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
1421 zc->zc_nvlist_dst_size, nvlp, 0) != 0)
1422 return (no_memory(hdl));
1424 return (0);
1428 zfs_ioctl(libzfs_handle_t *hdl, int request, zfs_cmd_t *zc)
1430 return (ioctl(hdl->libzfs_fd, request, zc));
1434 * ================================================================
1435 * API shared by zfs and zpool property management
1436 * ================================================================
1439 static void
1440 zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
1442 zprop_list_t *pl = cbp->cb_proplist;
1443 int i;
1444 char *title;
1445 size_t len;
1447 cbp->cb_first = B_FALSE;
1448 if (cbp->cb_scripted)
1449 return;
1452 * Start with the length of the column headers.
1454 cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
1455 cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
1456 "PROPERTY"));
1457 cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
1458 "VALUE"));
1459 cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
1460 "RECEIVED"));
1461 cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
1462 "SOURCE"));
1464 /* first property is always NAME */
1465 assert(cbp->cb_proplist->pl_prop ==
1466 ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME : ZFS_PROP_NAME));
1469 * Go through and calculate the widths for each column. For the
1470 * 'source' column, we kludge it up by taking the worst-case scenario of
1471 * inheriting from the longest name. This is acceptable because in the
1472 * majority of cases 'SOURCE' is the last column displayed, and we don't
1473 * use the width anyway. Note that the 'VALUE' column can be oversized,
1474 * if the name of the property is much longer than any values we find.
1476 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
1478 * 'PROPERTY' column
1480 if (pl->pl_prop != ZPROP_INVAL) {
1481 const char *propname = (type == ZFS_TYPE_POOL) ?
1482 zpool_prop_to_name(pl->pl_prop) :
1483 zfs_prop_to_name(pl->pl_prop);
1485 len = strlen(propname);
1486 if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1487 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1488 } else {
1489 len = strlen(pl->pl_user_prop);
1490 if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1491 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1495 * 'VALUE' column. The first property is always the 'name'
1496 * property that was tacked on either by /sbin/zfs's
1497 * zfs_do_get() or when calling zprop_expand_list(), so we
1498 * ignore its width. If the user specified the name property
1499 * to display, then it will be later in the list in any case.
1501 if (pl != cbp->cb_proplist &&
1502 pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
1503 cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
1505 /* 'RECEIVED' column. */
1506 if (pl != cbp->cb_proplist &&
1507 pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
1508 cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
1511 * 'NAME' and 'SOURCE' columns
1513 if (pl->pl_prop == (type == ZFS_TYPE_POOL ? ZPOOL_PROP_NAME :
1514 ZFS_PROP_NAME) &&
1515 pl->pl_width > cbp->cb_colwidths[GET_COL_NAME]) {
1516 cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
1517 cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
1518 strlen(dgettext(TEXT_DOMAIN, "inherited from"));
1523 * Now go through and print the headers.
1525 for (i = 0; i < ZFS_GET_NCOLS; i++) {
1526 switch (cbp->cb_columns[i]) {
1527 case GET_COL_NAME:
1528 title = dgettext(TEXT_DOMAIN, "NAME");
1529 break;
1530 case GET_COL_PROPERTY:
1531 title = dgettext(TEXT_DOMAIN, "PROPERTY");
1532 break;
1533 case GET_COL_VALUE:
1534 title = dgettext(TEXT_DOMAIN, "VALUE");
1535 break;
1536 case GET_COL_RECVD:
1537 title = dgettext(TEXT_DOMAIN, "RECEIVED");
1538 break;
1539 case GET_COL_SOURCE:
1540 title = dgettext(TEXT_DOMAIN, "SOURCE");
1541 break;
1542 default:
1543 title = NULL;
1546 if (title != NULL) {
1547 if (i == (ZFS_GET_NCOLS - 1) ||
1548 cbp->cb_columns[i + 1] == GET_COL_NONE)
1549 (void) printf("%s", title);
1550 else
1551 (void) printf("%-*s ",
1552 cbp->cb_colwidths[cbp->cb_columns[i]],
1553 title);
1556 (void) printf("\n");
1560 * Display a single line of output, according to the settings in the callback
1561 * structure.
1563 void
1564 zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
1565 const char *propname, const char *value, zprop_source_t sourcetype,
1566 const char *source, const char *recvd_value)
1568 int i;
1569 const char *str = NULL;
1570 char buf[128];
1573 * Ignore those source types that the user has chosen to ignore.
1575 if ((sourcetype & cbp->cb_sources) == 0)
1576 return;
1578 if (cbp->cb_first)
1579 zprop_print_headers(cbp, cbp->cb_type);
1581 for (i = 0; i < ZFS_GET_NCOLS; i++) {
1582 switch (cbp->cb_columns[i]) {
1583 case GET_COL_NAME:
1584 str = name;
1585 break;
1587 case GET_COL_PROPERTY:
1588 str = propname;
1589 break;
1591 case GET_COL_VALUE:
1592 str = value;
1593 break;
1595 case GET_COL_SOURCE:
1596 switch (sourcetype) {
1597 case ZPROP_SRC_NONE:
1598 str = "-";
1599 break;
1601 case ZPROP_SRC_DEFAULT:
1602 str = "default";
1603 break;
1605 case ZPROP_SRC_LOCAL:
1606 str = "local";
1607 break;
1609 case ZPROP_SRC_TEMPORARY:
1610 str = "temporary";
1611 break;
1613 case ZPROP_SRC_INHERITED:
1614 (void) snprintf(buf, sizeof (buf),
1615 "inherited from %s", source);
1616 str = buf;
1617 break;
1618 case ZPROP_SRC_RECEIVED:
1619 str = "received";
1620 break;
1622 default:
1623 str = NULL;
1624 assert(!"unhandled zprop_source_t");
1626 break;
1628 case GET_COL_RECVD:
1629 str = (recvd_value == NULL ? "-" : recvd_value);
1630 break;
1632 default:
1633 continue;
1636 if (i == (ZFS_GET_NCOLS - 1) ||
1637 cbp->cb_columns[i + 1] == GET_COL_NONE)
1638 (void) printf("%s", str);
1639 else if (cbp->cb_scripted)
1640 (void) printf("%s\t", str);
1641 else
1642 (void) printf("%-*s ",
1643 cbp->cb_colwidths[cbp->cb_columns[i]],
1644 str);
1647 (void) printf("\n");
1651 * Given a numeric suffix, convert the value into a number of bits that the
1652 * resulting value must be shifted.
1654 static int
1655 str2shift(libzfs_handle_t *hdl, const char *buf)
1657 const char *ends = "BKMGTPEZ";
1658 int i;
1660 if (buf[0] == '\0')
1661 return (0);
1662 for (i = 0; i < strlen(ends); i++) {
1663 if (toupper(buf[0]) == ends[i])
1664 break;
1666 if (i == strlen(ends)) {
1667 if (hdl)
1668 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1669 "invalid numeric suffix '%s'"), buf);
1670 return (-1);
1674 * Allow 'G' = 'GB' = 'GiB', case-insensitively.
1675 * However, 'BB' and 'BiB' are disallowed.
1677 if (buf[1] == '\0' ||
1678 (toupper(buf[0]) != 'B' &&
1679 ((toupper(buf[1]) == 'B' && buf[2] == '\0') ||
1680 (toupper(buf[1]) == 'I' && toupper(buf[2]) == 'B' &&
1681 buf[3] == '\0'))))
1682 return (10 * i);
1684 if (hdl)
1685 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1686 "invalid numeric suffix '%s'"), buf);
1687 return (-1);
1691 * Convert a string of the form '100G' into a real number. Used when setting
1692 * properties or creating a volume. 'buf' is used to place an extended error
1693 * message for the caller to use.
1696 zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1698 char *end;
1699 int shift;
1701 *num = 0;
1703 /* Check to see if this looks like a number. */
1704 if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1705 if (hdl)
1706 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1707 "bad numeric value '%s'"), value);
1708 return (-1);
1711 /* Rely on strtoull() to process the numeric portion. */
1712 errno = 0;
1713 *num = strtoull(value, &end, 10);
1716 * Check for ERANGE, which indicates that the value is too large to fit
1717 * in a 64-bit value.
1719 if (errno == ERANGE) {
1720 if (hdl)
1721 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1722 "numeric value is too large"));
1723 return (-1);
1727 * If we have a decimal value, then do the computation with floating
1728 * point arithmetic. Otherwise, use standard arithmetic.
1730 if (*end == '.') {
1731 double fval = strtod(value, &end);
1733 if ((shift = str2shift(hdl, end)) == -1)
1734 return (-1);
1736 fval *= pow(2, shift);
1738 if (fval > UINT64_MAX) {
1739 if (hdl)
1740 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1741 "numeric value is too large"));
1742 return (-1);
1745 *num = (uint64_t)fval;
1746 } else {
1747 if ((shift = str2shift(hdl, end)) == -1)
1748 return (-1);
1750 /* Check for overflow */
1751 if (shift >= 64 || (*num << shift) >> shift != *num) {
1752 if (hdl)
1753 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1754 "numeric value is too large"));
1755 return (-1);
1758 *num <<= shift;
1761 return (0);
1765 * Given a propname=value nvpair to set, parse any numeric properties
1766 * (index, boolean, etc) if they are specified as strings and add the
1767 * resulting nvpair to the returned nvlist.
1769 * At the DSL layer, all properties are either 64-bit numbers or strings.
1770 * We want the user to be able to ignore this fact and specify properties
1771 * as native values (numbers, for example) or as strings (to simplify
1772 * command line utilities). This also handles converting index types
1773 * (compression, checksum, etc) from strings to their on-disk index.
1776 zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1777 zfs_type_t type, nvlist_t *ret, char **svalp, uint64_t *ivalp,
1778 const char *errbuf)
1780 data_type_t datatype = nvpair_type(elem);
1781 zprop_type_t proptype;
1782 const char *propname;
1783 char *value;
1784 boolean_t isnone = B_FALSE;
1785 int err = 0;
1787 if (type == ZFS_TYPE_POOL) {
1788 proptype = zpool_prop_get_type(prop);
1789 propname = zpool_prop_to_name(prop);
1790 } else {
1791 proptype = zfs_prop_get_type(prop);
1792 propname = zfs_prop_to_name(prop);
1796 * Convert any properties to the internal DSL value types.
1798 *svalp = NULL;
1799 *ivalp = 0;
1801 switch (proptype) {
1802 case PROP_TYPE_STRING:
1803 if (datatype != DATA_TYPE_STRING) {
1804 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1805 "'%s' must be a string"), nvpair_name(elem));
1806 goto error;
1808 err = nvpair_value_string(elem, svalp);
1809 if (err != 0) {
1810 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1811 "'%s' is invalid"), nvpair_name(elem));
1812 goto error;
1814 if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1815 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1816 "'%s' is too long"), nvpair_name(elem));
1817 goto error;
1819 break;
1821 case PROP_TYPE_NUMBER:
1822 if (datatype == DATA_TYPE_STRING) {
1823 (void) nvpair_value_string(elem, &value);
1824 if (strcmp(value, "none") == 0) {
1825 isnone = B_TRUE;
1826 } else if (zfs_nicestrtonum(hdl, value, ivalp)
1827 != 0) {
1828 goto error;
1830 } else if (datatype == DATA_TYPE_UINT64) {
1831 (void) nvpair_value_uint64(elem, ivalp);
1832 } else {
1833 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1834 "'%s' must be a number"), nvpair_name(elem));
1835 goto error;
1839 * Quota special: force 'none' and don't allow 0.
1841 if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1842 (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1843 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1844 "use 'none' to disable quota/refquota"));
1845 goto error;
1849 * Special handling for "*_limit=none". In this case it's not
1850 * 0 but UINT64_MAX.
1852 if ((type & ZFS_TYPE_DATASET) && isnone &&
1853 (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1854 prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1855 *ivalp = UINT64_MAX;
1857 break;
1859 case PROP_TYPE_INDEX:
1860 if (datatype != DATA_TYPE_STRING) {
1861 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1862 "'%s' must be a string"), nvpair_name(elem));
1863 goto error;
1866 (void) nvpair_value_string(elem, &value);
1868 if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1869 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1870 "'%s' must be one of '%s'"), propname,
1871 zprop_values(prop, type));
1872 goto error;
1874 break;
1876 default:
1877 abort();
1881 * Add the result to our return set of properties.
1883 if (*svalp != NULL) {
1884 if (nvlist_add_string(ret, propname, *svalp) != 0) {
1885 (void) no_memory(hdl);
1886 return (-1);
1888 } else {
1889 if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1890 (void) no_memory(hdl);
1891 return (-1);
1895 return (0);
1896 error:
1897 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1898 return (-1);
1901 static int
1902 addlist(libzfs_handle_t *hdl, char *propname, zprop_list_t **listp,
1903 zfs_type_t type)
1905 int prop;
1906 zprop_list_t *entry;
1908 prop = zprop_name_to_prop(propname, type);
1910 if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type, B_FALSE))
1911 prop = ZPROP_INVAL;
1914 * When no property table entry can be found, return failure if
1915 * this is a pool property or if this isn't a user-defined
1916 * dataset property,
1918 if (prop == ZPROP_INVAL && ((type == ZFS_TYPE_POOL &&
1919 !zpool_prop_feature(propname) &&
1920 !zpool_prop_unsupported(propname)) ||
1921 (type == ZFS_TYPE_DATASET && !zfs_prop_user(propname) &&
1922 !zfs_prop_userquota(propname) && !zfs_prop_written(propname)))) {
1923 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1924 "invalid property '%s'"), propname);
1925 return (zfs_error(hdl, EZFS_BADPROP,
1926 dgettext(TEXT_DOMAIN, "bad property list")));
1929 if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1930 return (-1);
1932 entry->pl_prop = prop;
1933 if (prop == ZPROP_INVAL) {
1934 if ((entry->pl_user_prop = zfs_strdup(hdl, propname)) ==
1935 NULL) {
1936 free(entry);
1937 return (-1);
1939 entry->pl_width = strlen(propname);
1940 } else {
1941 entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1942 type);
1945 *listp = entry;
1947 return (0);
1951 * Given a comma-separated list of properties, construct a property list
1952 * containing both user-defined and native properties. This function will
1953 * return a NULL list if 'all' is specified, which can later be expanded
1954 * by zprop_expand_list().
1957 zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1958 zfs_type_t type)
1960 *listp = NULL;
1963 * If 'all' is specified, return a NULL list.
1965 if (strcmp(props, "all") == 0)
1966 return (0);
1969 * If no props were specified, return an error.
1971 if (props[0] == '\0') {
1972 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1973 "no properties specified"));
1974 return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
1975 "bad property list")));
1979 * It would be nice to use getsubopt() here, but the inclusion of column
1980 * aliases makes this more effort than it's worth.
1982 while (*props != '\0') {
1983 size_t len;
1984 char *p;
1985 char c;
1987 if ((p = strchr(props, ',')) == NULL) {
1988 len = strlen(props);
1989 p = props + len;
1990 } else {
1991 len = p - props;
1995 * Check for empty options.
1997 if (len == 0) {
1998 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1999 "empty property name"));
2000 return (zfs_error(hdl, EZFS_BADPROP,
2001 dgettext(TEXT_DOMAIN, "bad property list")));
2005 * Check all regular property names.
2007 c = props[len];
2008 props[len] = '\0';
2010 if (strcmp(props, "space") == 0) {
2011 static char *spaceprops[] = {
2012 "name", "avail", "used", "usedbysnapshots",
2013 "usedbydataset", "usedbyrefreservation",
2014 "usedbychildren", NULL
2016 int i;
2018 for (i = 0; spaceprops[i]; i++) {
2019 if (addlist(hdl, spaceprops[i], listp, type))
2020 return (-1);
2021 listp = &(*listp)->pl_next;
2023 } else {
2024 if (addlist(hdl, props, listp, type))
2025 return (-1);
2026 listp = &(*listp)->pl_next;
2029 props = p;
2030 if (c == ',')
2031 props++;
2034 return (0);
2037 void
2038 zprop_free_list(zprop_list_t *pl)
2040 zprop_list_t *next;
2042 while (pl != NULL) {
2043 next = pl->pl_next;
2044 free(pl->pl_user_prop);
2045 free(pl);
2046 pl = next;
2050 typedef struct expand_data {
2051 zprop_list_t **last;
2052 libzfs_handle_t *hdl;
2053 zfs_type_t type;
2054 } expand_data_t;
2057 zprop_expand_list_cb(int prop, void *cb)
2059 zprop_list_t *entry;
2060 expand_data_t *edp = cb;
2062 if ((entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t))) == NULL)
2063 return (ZPROP_INVAL);
2065 entry->pl_prop = prop;
2066 entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
2067 entry->pl_all = B_TRUE;
2069 *(edp->last) = entry;
2070 edp->last = &entry->pl_next;
2072 return (ZPROP_CONT);
2076 zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
2078 zprop_list_t *entry;
2079 zprop_list_t **last;
2080 expand_data_t exp;
2082 if (*plp == NULL) {
2084 * If this is the very first time we've been called for an 'all'
2085 * specification, expand the list to include all native
2086 * properties.
2088 last = plp;
2090 exp.last = last;
2091 exp.hdl = hdl;
2092 exp.type = type;
2094 if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
2095 B_FALSE, type) == ZPROP_INVAL)
2096 return (-1);
2099 * Add 'name' to the beginning of the list, which is handled
2100 * specially.
2102 if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
2103 return (-1);
2105 entry->pl_prop = (type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
2106 ZFS_PROP_NAME;
2107 entry->pl_width = zprop_width(entry->pl_prop,
2108 &entry->pl_fixed, type);
2109 entry->pl_all = B_TRUE;
2110 entry->pl_next = *plp;
2111 *plp = entry;
2113 return (0);
2117 zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
2118 zfs_type_t type)
2120 return (zprop_iter_common(func, cb, show_all, ordered, type));