]> git.proxmox.com Git - mirror_zfs.git/blame - lib/libzfs/libzfs_util.c
Prebaked scripts for zpool status/iostat -c
[mirror_zfs.git] / lib / libzfs / libzfs_util.c
CommitLineData
34dc7c2f
BB
1/*
2 * CDDL HEADER START
3 *
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.
7 *
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.
12 *
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]
18 *
19 * CDDL HEADER END
20 */
9ae529ec 21
34dc7c2f 22/*
428870ff 23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
788eb90c 24 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
23de906c 25 * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
23d70cde 26 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
34dc7c2f
BB
27 */
28
34dc7c2f
BB
29/*
30 * Internal utility routines for the ZFS library.
31 */
32
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>
d603ed6c 43#include <sys/stat.h>
34dc7c2f
BB
44#include <sys/mnttab.h>
45#include <sys/mntent.h>
46#include <sys/types.h>
120ff39a 47#include <sys/wait.h>
34dc7c2f
BB
48
49#include <libzfs.h>
6f1ffb06 50#include <libzfs_core.h>
34dc7c2f
BB
51
52#include "libzfs_impl.h"
53#include "zfs_prop.h"
9ae529ec 54#include "zfeature_common.h"
dc03fa30 55#include <zfs_fletcher.h>
34dc7c2f
BB
56
57int
58libzfs_errno(libzfs_handle_t *hdl)
59{
60 return (hdl->libzfs_error);
61}
62
65037d9b
BB
63const char *
64libzfs_error_init(int error)
65{
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:
79251738 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"));
65037d9b
BB
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"));
85 }
86}
87
34dc7c2f
BB
88const char *
89libzfs_error_action(libzfs_handle_t *hdl)
90{
91 return (hdl->libzfs_action);
92}
93
94const char *
95libzfs_error_description(libzfs_handle_t *hdl)
96{
97 if (hdl->libzfs_desc[0] != '\0')
98 return (hdl->libzfs_desc);
99
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:
572e2857 106 return (dgettext(TEXT_DOMAIN, "read-only property"));
34dc7c2f
BB
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:
572e2857 126 return (dgettext(TEXT_DOMAIN, "dataset is read-only"));
34dc7c2f
BB
127 case EZFS_VOLTOOBIG:
128 return (dgettext(TEXT_DOMAIN, "volume size exceeds limit for "
129 "this system"));
34dc7c2f
BB
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:
9ae529ec
CS
148 return (dgettext(TEXT_DOMAIN, "unsupported version or "
149 "feature"));
34dc7c2f
BB
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"));
34dc7c2f
BB
173 case EZFS_PERM:
174 return (dgettext(TEXT_DOMAIN, "permission denied"));
175 case EZFS_NOSPC:
176 return (dgettext(TEXT_DOMAIN, "out of space"));
428870ff
BB
177 case EZFS_FAULT:
178 return (dgettext(TEXT_DOMAIN, "bad address"));
34dc7c2f
BB
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"));
34dc7c2f
BB
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"));
34dc7c2f
BB
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"));
b128c09f
BB
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"));
9babb374
BB
232 case EZFS_UNPLAYED_LOGS:
233 return (dgettext(TEXT_DOMAIN, "log device has unplayed intent "
234 "logs"));
45d1cae3
BB
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"));
428870ff
BB
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"));
572e2857
BB
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"));
34dc7c2f
BB
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"));
265 }
266}
267
268/*PRINTFLIKE2*/
269void
270zfs_error_aux(libzfs_handle_t *hdl, const char *fmt, ...)
271{
272 va_list ap;
273
274 va_start(ap, fmt);
275
276 (void) vsnprintf(hdl->libzfs_desc, sizeof (hdl->libzfs_desc),
277 fmt, ap);
278 hdl->libzfs_desc_active = 1;
279
280 va_end(ap);
281}
282
283static void
284zfs_verror(libzfs_handle_t *hdl, int error, const char *fmt, va_list ap)
285{
286 (void) vsnprintf(hdl->libzfs_action, sizeof (hdl->libzfs_action),
287 fmt, ap);
288 hdl->libzfs_error = error;
289
290 if (hdl->libzfs_desc_active)
291 hdl->libzfs_desc_active = 0;
292 else
293 hdl->libzfs_desc[0] = '\0';
294
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();
300 }
301
302 (void) fprintf(stderr, "%s: %s\n", hdl->libzfs_action,
303 libzfs_error_description(hdl));
304 if (error == EZFS_NOMEM)
305 exit(1);
306 }
307}
308
309int
310zfs_error(libzfs_handle_t *hdl, int error, const char *msg)
311{
312 return (zfs_error_fmt(hdl, error, "%s", msg));
313}
314
315/*PRINTFLIKE3*/
316int
317zfs_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
318{
319 va_list ap;
320
321 va_start(ap, fmt);
322
323 zfs_verror(hdl, error, fmt, ap);
324
325 va_end(ap);
326
327 return (-1);
328}
329
330static int
331zfs_common_error(libzfs_handle_t *hdl, int error, const char *fmt,
332 va_list ap)
333{
334 switch (error) {
335 case EPERM:
336 case EACCES:
337 zfs_verror(hdl, EZFS_PERM, fmt, ap);
338 return (-1);
339
340 case ECANCELED:
341 zfs_verror(hdl, EZFS_NODELEGATION, fmt, ap);
342 return (-1);
343
344 case EIO:
345 zfs_verror(hdl, EZFS_IO, fmt, ap);
346 return (-1);
347
428870ff
BB
348 case EFAULT:
349 zfs_verror(hdl, EZFS_FAULT, fmt, ap);
350 return (-1);
351
34dc7c2f
BB
352 case EINTR:
353 zfs_verror(hdl, EZFS_INTR, fmt, ap);
354 return (-1);
355 }
356
357 return (0);
358}
359
360int
361zfs_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
362{
363 return (zfs_standard_error_fmt(hdl, error, "%s", msg));
364}
365
366/*PRINTFLIKE3*/
367int
368zfs_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
369{
370 va_list ap;
371
372 va_start(ap, fmt);
373
374 if (zfs_common_error(hdl, error, fmt, ap) != 0) {
375 va_end(ap);
376 return (-1);
377 }
378
379 switch (error) {
380 case ENXIO:
381 case ENODEV:
330d06f9 382 case EPIPE:
34dc7c2f
BB
383 zfs_verror(hdl, EZFS_IO, fmt, ap);
384 break;
385
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;
391
392 case ENOSPC:
393 case EDQUOT:
394 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
b264d9b3 395 break;
34dc7c2f
BB
396
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;
402
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:
572e2857 409 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
34dc7c2f
BB
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;
9babb374
BB
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;
34dc7c2f 422 default:
428870ff 423 zfs_error_aux(hdl, strerror(error));
34dc7c2f
BB
424 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
425 break;
426 }
427
428 va_end(ap);
429 return (-1);
430}
431
432int
433zpool_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
434{
435 return (zpool_standard_error_fmt(hdl, error, "%s", msg));
436}
437
438/*PRINTFLIKE3*/
439int
440zpool_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
441{
442 va_list ap;
443
444 va_start(ap, fmt);
445
446 if (zfs_common_error(hdl, error, fmt, ap) != 0) {
447 va_end(ap);
448 return (-1);
449 }
450
451 switch (error) {
452 case ENODEV:
453 zfs_verror(hdl, EZFS_NODEVICE, fmt, ap);
454 break;
455
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;
461
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;
467
468 case EBUSY:
469 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool is busy"));
b128c09f 470 zfs_verror(hdl, EZFS_BUSY, fmt, ap);
34dc7c2f
BB
471 break;
472
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;
478
479 case ENAMETOOLONG:
480 zfs_verror(hdl, EZFS_DEVOVERFLOW, fmt, ap);
481 break;
482
483 case ENOTSUP:
484 zfs_verror(hdl, EZFS_POOL_NOTSUP, fmt, ap);
485 break;
486
487 case EINVAL:
488 zfs_verror(hdl, EZFS_POOL_INVALARG, fmt, ap);
489 break;
490
491 case ENOSPC:
492 case EDQUOT:
493 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
494 return (-1);
572e2857 495
9babb374
BB
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;
34dc7c2f 501
572e2857
BB
502 case EROFS:
503 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
504 break;
385f9691
D
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;
572e2857 510
34dc7c2f
BB
511 default:
512 zfs_error_aux(hdl, strerror(error));
513 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
514 }
515
516 va_end(ap);
517 return (-1);
518}
519
520/*
521 * Display an out of memory error message and abort the current program.
522 */
523int
524no_memory(libzfs_handle_t *hdl)
525{
526 return (zfs_error(hdl, EZFS_NOMEM, "internal error"));
527}
528
529/*
530 * A safe form of malloc() which will die if the allocation fails.
531 */
532void *
533zfs_alloc(libzfs_handle_t *hdl, size_t size)
534{
535 void *data;
536
537 if ((data = calloc(1, size)) == NULL)
538 (void) no_memory(hdl);
539
540 return (data);
541}
542
572e2857
BB
543/*
544 * A safe form of asprintf() which will die if the allocation fails.
545 */
546/*PRINTFLIKE2*/
547char *
548zfs_asprintf(libzfs_handle_t *hdl, const char *fmt, ...)
549{
550 va_list ap;
551 char *ret;
552 int err;
553
554 va_start(ap, fmt);
555
556 err = vasprintf(&ret, fmt, ap);
557
558 va_end(ap);
559
560 if (err < 0)
561 (void) no_memory(hdl);
562
563 return (ret);
564}
565
34dc7c2f
BB
566/*
567 * A safe form of realloc(), which also zeroes newly allocated space.
568 */
569void *
570zfs_realloc(libzfs_handle_t *hdl, void *ptr, size_t oldsize, size_t newsize)
571{
572 void *ret;
573
574 if ((ret = realloc(ptr, newsize)) == NULL) {
575 (void) no_memory(hdl);
34dc7c2f
BB
576 return (NULL);
577 }
578
579 bzero((char *)ret + oldsize, (newsize - oldsize));
580 return (ret);
581}
582
583/*
584 * A safe form of strdup() which will die if the allocation fails.
585 */
586char *
587zfs_strdup(libzfs_handle_t *hdl, const char *str)
588{
589 char *ret;
590
591 if ((ret = strdup(str)) == NULL)
592 (void) no_memory(hdl);
593
594 return (ret);
595}
596
597/*
598 * Convert a number to an appropriately human-readable output.
599 */
600void
193a37cb
TH
601zfs_nicenum_format(uint64_t num, char *buf, size_t buflen,
602 enum zfs_nicenum_format format)
34dc7c2f
BB
603{
604 uint64_t n = num;
605 int index = 0;
193a37cb
TH
606 const char *u;
607 const char *units[3][7] = {
608 [ZFS_NICENUM_1024] = {"", "K", "M", "G", "T", "P", "E"},
609 [ZFS_NICENUM_TIME] = {"ns", "us", "ms", "s", "?", "?", "?"}
610 };
611
612 const int units_len[] = {[ZFS_NICENUM_1024] = 6,
613 [ZFS_NICENUM_TIME] = 4};
614
615 const int k_unit[] = { [ZFS_NICENUM_1024] = 1024,
616 [ZFS_NICENUM_TIME] = 1000};
617
618 double val;
34dc7c2f 619
193a37cb 620 if (format == ZFS_NICENUM_RAW) {
02730c33 621 snprintf(buf, buflen, "%llu", (u_longlong_t)num);
193a37cb
TH
622 return;
623 }
624
625
626 while (n >= k_unit[format] && index < units_len[format]) {
627 n /= k_unit[format];
34dc7c2f
BB
628 index++;
629 }
630
193a37cb 631 u = units[format][index];
34dc7c2f 632
193a37cb
TH
633 /* Don't print 0ns times */
634 if ((format == ZFS_NICENUM_TIME) && (num == 0)) {
635 (void) snprintf(buf, buflen, "-");
636 } else if ((index == 0) || ((num %
02730c33 637 (uint64_t)powl(k_unit[format], index)) == 0)) {
34dc7c2f
BB
638 /*
639 * If this is an even multiple of the base, always display
640 * without any decimal precision.
641 */
02730c33 642 (void) snprintf(buf, buflen, "%llu%s", (u_longlong_t)n, u);
193a37cb 643
34dc7c2f
BB
644 } else {
645 /*
646 * We want to choose a precision that reflects the best choice
647 * for fitting in 5 characters. This can get rather tricky when
648 * we have numbers that are very close to an order of magnitude.
649 * For example, when displaying 10239 (which is really 9.999K),
650 * we want only a single place of precision for 10.0K. We could
651 * develop some complex heuristics for this, but it's much
652 * easier just to try each combination in turn.
653 */
654 int i;
655 for (i = 2; i >= 0; i--) {
02730c33
BB
656 val = (double)num /
657 (uint64_t)powl(k_unit[format], index);
193a37cb
TH
658
659 /*
660 * Don't print floating point values for time. Note,
661 * we use floor() instead of round() here, since
662 * round can result in undesirable results. For
663 * example, if "num" is in the range of
664 * 999500-999999, it will print out "1000us". This
665 * doesn't happen if we use floor().
666 */
667 if (format == ZFS_NICENUM_TIME) {
668 if (snprintf(buf, buflen, "%d%s",
669 (unsigned int) floor(val), u) <= 5)
670 break;
671
672 } else {
673 if (snprintf(buf, buflen, "%.*f%s", i,
674 val, u) <= 5)
675 break;
676 }
34dc7c2f
BB
677 }
678 }
679}
680
193a37cb
TH
681/*
682 * Convert a number to an appropriately human-readable output.
683 */
684void
685zfs_nicenum(uint64_t num, char *buf, size_t buflen)
686{
687 zfs_nicenum_format(num, buf, buflen, ZFS_NICENUM_1024);
688}
689
690/*
691 * Convert a time to an appropriately human-readable output.
692 * @num: Time in nanoseconds
693 */
694void
695zfs_nicetime(uint64_t num, char *buf, size_t buflen)
696{
697 zfs_nicenum_format(num, buf, buflen, ZFS_NICENUM_TIME);
698}
699
700/*
701 * Print out a raw number with correct column spacing
702 */
703void
704zfs_niceraw(uint64_t num, char *buf, size_t buflen)
705{
706 zfs_nicenum_format(num, buf, buflen, ZFS_NICENUM_RAW);
707}
708
709
710
34dc7c2f
BB
711void
712libzfs_print_on_error(libzfs_handle_t *hdl, boolean_t printerr)
713{
714 hdl->libzfs_printerr = printerr;
715}
716
4b1abce9
NB
717static int
718libzfs_module_loaded(const char *module)
719{
f09398ce
ED
720 const char path_prefix[] = "/sys/module/";
721 char path[256];
722
d1d7e268
MK
723 memcpy(path, path_prefix, sizeof (path_prefix) - 1);
724 strcpy(path + sizeof (path_prefix) - 1, module);
4b1abce9 725
f09398ce 726 return (access(path, F_OK) == 0);
4b1abce9
NB
727}
728
d6418de0
TH
729
730/*
731 * Read lines from an open file descriptor and store them in an array of
732 * strings until EOF. lines[] will be allocated and populated with all the
733 * lines read. All newlines are replaced with NULL terminators for
734 * convenience. lines[] must be freed after use with libzfs_free_str_array().
735 *
736 * Returns the number of lines read.
737 */
738static int
739libzfs_read_stdout_from_fd(int fd, char **lines[])
740{
741
742 FILE *fp;
743 int lines_cnt = 0;
744 size_t len = 0;
745 char *line = NULL;
746 char **tmp_lines = NULL, **tmp;
747 char *nl = NULL;
748 int rc;
749
750 fp = fdopen(fd, "r");
751 if (fp == NULL)
752 return (0);
753 while (1) {
754 rc = getline(&line, &len, fp);
755 if (rc == -1)
756 break;
757
758 tmp = realloc(tmp_lines, sizeof (*tmp_lines) * (lines_cnt + 1));
759 if (tmp == NULL) {
760 /* Return the lines we were able to process */
761 break;
762 }
763 tmp_lines = tmp;
764
765 /* Terminate newlines */
766 if ((nl = strchr(line, '\n')) != NULL)
767 *nl = '\0';
768 tmp_lines[lines_cnt] = line;
769 lines_cnt++;
770 line = NULL;
771 }
772 fclose(fp);
773 *lines = tmp_lines;
774 return (lines_cnt);
775}
776
777static int
778libzfs_run_process_impl(const char *path, char *argv[], char *env[], int flags,
779 char **lines[], int *lines_cnt)
4b1abce9
NB
780{
781 pid_t pid;
65037d9b 782 int error, devnull_fd;
d6418de0
TH
783 int link[2];
784
785 /*
786 * Setup a pipe between our child and parent process if we're
787 * reading stdout.
788 */
789 if ((lines != NULL) && pipe(link) == -1)
790 return (-ESTRPIPE);
4b1abce9
NB
791
792 pid = vfork();
793 if (pid == 0) {
d6418de0 794 /* Child process */
3132cb39
GB
795 devnull_fd = open("/dev/null", O_WRONLY);
796
797 if (devnull_fd < 0)
798 _exit(-1);
799
d6418de0 800 if (!(flags & STDOUT_VERBOSE) && (lines == NULL))
3132cb39 801 (void) dup2(devnull_fd, STDOUT_FILENO);
d6418de0
TH
802 else if (lines != NULL) {
803 /* Save the output to lines[] */
804 dup2(link[1], STDOUT_FILENO);
805 close(link[0]);
806 close(link[1]);
807 }
9ac97c2a
BB
808
809 if (!(flags & STDERR_VERBOSE))
3132cb39
GB
810 (void) dup2(devnull_fd, STDERR_FILENO);
811
812 close(devnull_fd);
9ac97c2a 813
d6418de0
TH
814 if (flags & NO_DEFAULT_PATH) {
815 if (env == NULL)
816 execv(path, argv);
817 else
818 execve(path, argv, env);
819 } else {
820 if (env == NULL)
821 execvp(path, argv);
822 else
823 execvpe(path, argv, env);
824 }
825
4b1abce9
NB
826 _exit(-1);
827 } else if (pid > 0) {
d6418de0 828 /* Parent process */
4b1abce9
NB
829 int status;
830
65037d9b 831 while ((error = waitpid(pid, &status, 0)) == -1 &&
02730c33 832 errno == EINTR) { }
65037d9b 833 if (error < 0 || !WIFEXITED(status))
d1d7e268 834 return (-1);
4b1abce9 835
d6418de0
TH
836 if (lines != NULL) {
837 close(link[1]);
838 *lines_cnt = libzfs_read_stdout_from_fd(link[0], lines);
839 }
d1d7e268 840 return (WEXITSTATUS(status));
4b1abce9
NB
841 }
842
d1d7e268 843 return (-1);
4b1abce9
NB
844}
845
d6418de0
TH
846int
847libzfs_run_process(const char *path, char *argv[], int flags)
848{
849 return (libzfs_run_process_impl(path, argv, NULL, flags, NULL, NULL));
850}
851
852/*
853 * Run a command and store its stdout lines in an array of strings (lines[]).
854 * lines[] is allocated and populated for you, and the number of lines is set in
855 * lines_cnt. lines[] must be freed after use with libzfs_free_str_array().
856 * All newlines (\n) in lines[] are terminated for convenience.
857 */
858int
859libzfs_run_process_get_stdout(const char *path, char *argv[], char *env[],
860 char **lines[], int *lines_cnt)
861{
862 return (libzfs_run_process_impl(path, argv, env, 0, lines, lines_cnt));
863}
864
865/*
866 * Same as libzfs_run_process_get_stdout(), but run without $PATH set. This
867 * means that *path needs to be the full path to the executable.
868 */
869int
870libzfs_run_process_get_stdout_nopath(const char *path, char *argv[],
871 char *env[], char **lines[], int *lines_cnt)
872{
873 return (libzfs_run_process_impl(path, argv, env, NO_DEFAULT_PATH,
874 lines, lines_cnt));
875}
876
877/*
878 * Free an array of strings. Free both the strings contained in the array and
879 * the array itself.
880 */
881void
882libzfs_free_str_array(char **strs, int count)
883{
884 while (--count >= 0)
885 free(strs[count]);
886
887 free(strs);
888}
889
890/*
891 * Returns 1 if environment variable is set to "YES", "yes", "ON", "on", or
892 * a non-zero number.
893 *
894 * Returns 0 otherwise.
895 */
896int
897libzfs_envvar_is_set(char *envvar)
898{
899 char *env = getenv(envvar);
900 if (env && (strtoul(env, NULL, 0) > 0 ||
901 (!strncasecmp(env, "YES", 3) && strnlen(env, 4) == 3) ||
902 (!strncasecmp(env, "ON", 2) && strnlen(env, 3) == 2)))
903 return (1);
904
905 return (0);
906}
907
87abfcba
BB
908/*
909 * Verify the required ZFS_DEV device is available and optionally attempt
910 * to load the ZFS modules. Under normal circumstances the modules
911 * should already have been loaded by some external mechanism.
912 *
913 * Environment variables:
914 * - ZFS_MODULE_LOADING="YES|yes|ON|on" - Attempt to load modules.
915 * - ZFS_MODULE_TIMEOUT="<seconds>" - Seconds to wait for ZFS_DEV
916 */
65037d9b 917static int
4b1abce9
NB
918libzfs_load_module(const char *module)
919{
920 char *argv[4] = {"/sbin/modprobe", "-q", (char *)module, (char *)0};
87abfcba
BB
921 char *load_str, *timeout_str;
922 long timeout = 10; /* seconds */
923 long busy_timeout = 10; /* milliseconds */
924 int load = 0, fd;
925 hrtime_t start;
926
927 /* Optionally request module loading */
928 if (!libzfs_module_loaded(module)) {
929 load_str = getenv("ZFS_MODULE_LOADING");
930 if (load_str) {
931 if (!strncasecmp(load_str, "YES", strlen("YES")) ||
932 !strncasecmp(load_str, "ON", strlen("ON")))
933 load = 1;
934 else
935 load = 0;
936 }
4b1abce9 937
87abfcba
BB
938 if (load && libzfs_run_process("/sbin/modprobe", argv, 0))
939 return (ENOEXEC);
940 }
941
942 /* Module loading is synchronous it must be available */
943 if (!libzfs_module_loaded(module))
944 return (ENXIO);
945
946 /*
947 * Device creation by udev is asynchronous and waiting may be
948 * required. Busy wait for 10ms and then fall back to polling every
949 * 10ms for the allowed timeout (default 10s, max 10m). This is
950 * done to optimize for the common case where the device is
951 * immediately available and to avoid penalizing the possible
952 * case where udev is slow or unable to create the device.
953 */
954 timeout_str = getenv("ZFS_MODULE_TIMEOUT");
955 if (timeout_str) {
956 timeout = strtol(timeout_str, NULL, 0);
957 timeout = MAX(MIN(timeout, (10 * 60)), 0); /* 0 <= N <= 600 */
958 }
959
960 start = gethrtime();
961 do {
962 fd = open(ZFS_DEV, O_RDWR);
963 if (fd >= 0) {
964 (void) close(fd);
965 return (0);
966 } else if (errno != ENOENT) {
967 return (errno);
968 } else if (NSEC2MSEC(gethrtime() - start) < busy_timeout) {
969 sched_yield();
970 } else {
971 usleep(10 * MILLISEC);
972 }
973 } while (NSEC2MSEC(gethrtime() - start) < (timeout * MILLISEC));
feb46b92 974
87abfcba 975 return (ENOENT);
4b1abce9
NB
976}
977
34dc7c2f
BB
978libzfs_handle_t *
979libzfs_init(void)
980{
981 libzfs_handle_t *hdl;
87abfcba 982 int error;
34dc7c2f 983
87abfcba
BB
984 error = libzfs_load_module(ZFS_DRIVER);
985 if (error) {
65037d9b 986 errno = error;
4b1abce9
NB
987 return (NULL);
988 }
989
572e2857 990 if ((hdl = calloc(1, sizeof (libzfs_handle_t))) == NULL) {
34dc7c2f
BB
991 return (NULL);
992 }
993
994 if ((hdl->libzfs_fd = open(ZFS_DEV, O_RDWR)) < 0) {
995 free(hdl);
996 return (NULL);
997 }
998
2eadf037
BB
999#ifdef HAVE_SETMNTENT
1000 if ((hdl->libzfs_mnttab = setmntent(MNTTAB, "r")) == NULL) {
1001#else
34dc7c2f 1002 if ((hdl->libzfs_mnttab = fopen(MNTTAB, "r")) == NULL) {
2eadf037 1003#endif
34dc7c2f
BB
1004 (void) close(hdl->libzfs_fd);
1005 free(hdl);
1006 return (NULL);
1007 }
1008
2bac6814 1009 hdl->libzfs_sharetab = fopen(ZFS_SHARETAB, "r");
34dc7c2f 1010
6f1ffb06
MA
1011 if (libzfs_core_init() != 0) {
1012 (void) close(hdl->libzfs_fd);
1013 (void) fclose(hdl->libzfs_mnttab);
2bac6814 1014 if (hdl->libzfs_sharetab)
1015 (void) fclose(hdl->libzfs_sharetab);
6f1ffb06
MA
1016 free(hdl);
1017 return (NULL);
1018 }
1019
34dc7c2f
BB
1020 zfs_prop_init();
1021 zpool_prop_init();
9ae529ec 1022 zpool_feature_init();
9babb374 1023 libzfs_mnttab_init(hdl);
dc03fa30 1024 fletcher_4_init();
34dc7c2f
BB
1025
1026 return (hdl);
1027}
1028
1029void
1030libzfs_fini(libzfs_handle_t *hdl)
1031{
1032 (void) close(hdl->libzfs_fd);
1033 if (hdl->libzfs_mnttab)
2eadf037
BB
1034#ifdef HAVE_SETMNTENT
1035 (void) endmntent(hdl->libzfs_mnttab);
1036#else
34dc7c2f 1037 (void) fclose(hdl->libzfs_mnttab);
2eadf037 1038#endif
34dc7c2f
BB
1039 if (hdl->libzfs_sharetab)
1040 (void) fclose(hdl->libzfs_sharetab);
1041 zfs_uninit_libshare(hdl);
b128c09f 1042 zpool_free_handles(hdl);
428870ff 1043 libzfs_fru_clear(hdl, B_TRUE);
34dc7c2f 1044 namespace_clear(hdl);
9babb374 1045 libzfs_mnttab_fini(hdl);
6f1ffb06 1046 libzfs_core_fini();
dc03fa30 1047 fletcher_4_fini();
34dc7c2f
BB
1048 free(hdl);
1049}
1050
1051libzfs_handle_t *
1052zpool_get_handle(zpool_handle_t *zhp)
1053{
1054 return (zhp->zpool_hdl);
1055}
1056
1057libzfs_handle_t *
1058zfs_get_handle(zfs_handle_t *zhp)
1059{
1060 return (zhp->zfs_hdl);
1061}
1062
b128c09f
BB
1063zpool_handle_t *
1064zfs_get_pool_handle(const zfs_handle_t *zhp)
1065{
1066 return (zhp->zpool_hdl);
1067}
1068
34dc7c2f
BB
1069/*
1070 * Given a name, determine whether or not it's a valid path
1071 * (starts with '/' or "./"). If so, walk the mnttab trying
1072 * to match the device number. If not, treat the path as an
aeacdefe 1073 * fs/vol/snap/bkmark name.
34dc7c2f
BB
1074 */
1075zfs_handle_t *
1076zfs_path_to_zhandle(libzfs_handle_t *hdl, char *path, zfs_type_t argtype)
1077{
1078 struct stat64 statbuf;
1079 struct extmnttab entry;
1080 int ret;
1081
1082 if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
1083 /*
1084 * It's not a valid path, assume it's a name of type 'argtype'.
1085 */
1086 return (zfs_open(hdl, path, argtype));
1087 }
1088
1089 if (stat64(path, &statbuf) != 0) {
1090 (void) fprintf(stderr, "%s: %s\n", path, strerror(errno));
1091 return (NULL);
1092 }
1093
cbca6076
JL
1094 /* Reopen MNTTAB to prevent reading stale data from open file */
1095 if (freopen(MNTTAB, "r", hdl->libzfs_mnttab) == NULL)
1096 return (NULL);
1097
34dc7c2f
BB
1098 while ((ret = getextmntent(hdl->libzfs_mnttab, &entry, 0)) == 0) {
1099 if (makedevice(entry.mnt_major, entry.mnt_minor) ==
1100 statbuf.st_dev) {
1101 break;
1102 }
1103 }
1104 if (ret != 0) {
1105 return (NULL);
1106 }
1107
1108 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
1109 (void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
1110 path);
1111 return (NULL);
1112 }
1113
1114 return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
1115}
1116
79e7242a 1117/*
eac47204
BB
1118 * Append partition suffix to an otherwise fully qualified device path.
1119 * This is used to generate the name the full path as its stored in
1120 * ZPOOL_CONFIG_PATH for whole disk devices. On success the new length
1121 * of 'path' will be returned on error a negative value is returned.
79e7242a
NB
1122 */
1123int
eac47204
BB
1124zfs_append_partition(char *path, size_t max_len)
1125{
1126 int len = strlen(path);
1127
6bb24f4d
BB
1128 if ((strncmp(path, UDISK_ROOT, strlen(UDISK_ROOT)) == 0) ||
1129 (strncmp(path, ZVOL_ROOT, strlen(ZVOL_ROOT)) == 0)) {
eac47204
BB
1130 if (len + 6 >= max_len)
1131 return (-1);
1132
1133 (void) strcat(path, "-part1");
1134 len += 6;
1135 } else {
1136 if (len + 2 >= max_len)
1137 return (-1);
1138
1139 if (isdigit(path[len-1])) {
1140 (void) strcat(path, "p1");
1141 len += 2;
1142 } else {
1143 (void) strcat(path, "1");
1144 len += 1;
1145 }
79e7242a 1146 }
b04c9fc0 1147
eac47204 1148 return (len);
79e7242a
NB
1149}
1150
1151/*
eac47204
BB
1152 * Given a shorthand device name check if a file by that name exists in any
1153 * of the 'zpool_default_import_path' or ZPOOL_IMPORT_PATH directories. If
1154 * one is found, store its fully qualified path in the 'path' buffer passed
1155 * by the caller and return 0, otherwise return an error.
79e7242a 1156 */
eac47204
BB
1157int
1158zfs_resolve_shortname(const char *name, char *path, size_t len)
79e7242a 1159{
eac47204
BB
1160 int i, error = -1;
1161 char *dir, *env, *envdup;
1162
1163 env = getenv("ZPOOL_IMPORT_PATH");
1164 errno = ENOENT;
1165
1166 if (env) {
1167 envdup = strdup(env);
1168 dir = strtok(envdup, ":");
1169 while (dir && error) {
1170 (void) snprintf(path, len, "%s/%s", dir, name);
1171 error = access(path, F_OK);
1172 dir = strtok(NULL, ":");
1173 }
1174 free(envdup);
1175 } else {
1176 for (i = 0; i < DEFAULT_IMPORT_PATH_SIZE && error < 0; i++) {
1177 (void) snprintf(path, len, "%s/%s",
1178 zpool_default_import_path[i], name);
1179 error = access(path, F_OK);
1180 }
1181 }
1182
1183 return (error ? ENOENT : 0);
1184}
1185
1186/*
1187 * Given a shorthand device name look for a match against 'cmp_name'. This
1188 * is done by checking all prefix expansions using either the default
1189 * 'zpool_default_import_paths' or the ZPOOL_IMPORT_PATH environment
1190 * variable. Proper partition suffixes will be appended if this is a
1191 * whole disk. When a match is found 0 is returned otherwise ENOENT.
1192 */
1193static int
1194zfs_strcmp_shortname(char *name, char *cmp_name, int wholedisk)
1195{
1196 int path_len, cmp_len, i = 0, error = ENOENT;
1197 char *dir, *env, *envdup = NULL;
1198 char path_name[MAXPATHLEN];
1199
1200 cmp_len = strlen(cmp_name);
1201 env = getenv("ZPOOL_IMPORT_PATH");
1202
1203 if (env) {
1204 envdup = strdup(env);
1205 dir = strtok(envdup, ":");
1206 } else {
1207 dir = zpool_default_import_path[i];
1208 }
1209
1210 while (dir) {
1211 /* Trim trailing directory slashes from ZPOOL_IMPORT_PATH */
1212 while (dir[strlen(dir)-1] == '/')
1213 dir[strlen(dir)-1] = '\0';
1214
1215 path_len = snprintf(path_name, MAXPATHLEN, "%s/%s", dir, name);
1216 if (wholedisk)
1217 path_len = zfs_append_partition(path_name, MAXPATHLEN);
1218
d1d7e268 1219 if ((path_len == cmp_len) && strcmp(path_name, cmp_name) == 0) {
eac47204
BB
1220 error = 0;
1221 break;
1222 }
1223
1224 if (env) {
1225 dir = strtok(NULL, ":");
1226 } else if (++i < DEFAULT_IMPORT_PATH_SIZE) {
1227 dir = zpool_default_import_path[i];
1228 } else {
1229 dir = NULL;
1230 }
1231 }
1232
1233 if (env)
1234 free(envdup);
1235
1236 return (error);
1237}
1238
1239/*
1240 * Given either a shorthand or fully qualified path name look for a match
1241 * against 'cmp'. The passed name will be expanded as needed for comparison
1242 * purposes and redundant slashes stripped to ensure an accurate match.
1243 */
1244int
1245zfs_strcmp_pathname(char *name, char *cmp, int wholedisk)
1246{
1247 int path_len, cmp_len;
1248 char path_name[MAXPATHLEN];
1249 char cmp_name[MAXPATHLEN];
eea93094 1250 char *dir, *dup;
eac47204
BB
1251
1252 /* Strip redundant slashes if one exists due to ZPOOL_IMPORT_PATH */
1253 memset(cmp_name, 0, MAXPATHLEN);
eea93094
BB
1254 dup = strdup(cmp);
1255 dir = strtok(dup, "/");
eac47204 1256 while (dir) {
0b78aeae
B
1257 strlcat(cmp_name, "/", sizeof (cmp_name));
1258 strlcat(cmp_name, dir, sizeof (cmp_name));
eac47204
BB
1259 dir = strtok(NULL, "/");
1260 }
eea93094 1261 free(dup);
eac47204
BB
1262
1263 if (name[0] != '/')
d1d7e268 1264 return (zfs_strcmp_shortname(name, cmp_name, wholedisk));
eac47204 1265
928ee9fe 1266 (void) strlcpy(path_name, name, MAXPATHLEN);
eac47204
BB
1267 path_len = strlen(path_name);
1268 cmp_len = strlen(cmp_name);
1269
1270 if (wholedisk) {
1271 path_len = zfs_append_partition(path_name, MAXPATHLEN);
1272 if (path_len == -1)
1273 return (ENOMEM);
1274 }
1275
1276 if ((path_len != cmp_len) || strcmp(path_name, cmp_name))
1277 return (ENOENT);
1278
1279 return (0);
79e7242a
NB
1280}
1281
83bf769d
BB
1282/*
1283 * Given a full path to a device determine if that device appears in the
1284 * import search path. If it does return the first match and store the
1285 * index in the passed 'order' variable, otherwise return an error.
1286 */
1287int
1288zfs_path_order(char *name, int *order)
1289{
1290 int i = 0, error = ENOENT;
1291 char *dir, *env, *envdup;
1292
1293 env = getenv("ZPOOL_IMPORT_PATH");
1294 if (env) {
1295 envdup = strdup(env);
1296 dir = strtok(envdup, ":");
1297 while (dir) {
1298 if (strncmp(name, dir, strlen(dir)) == 0) {
1299 *order = i;
1300 error = 0;
1301 break;
1302 }
1303 dir = strtok(NULL, ":");
1304 i++;
1305 }
1306 free(envdup);
1307 } else {
1308 for (i = 0; i < DEFAULT_IMPORT_PATH_SIZE; i++) {
1309 if (strncmp(name, zpool_default_import_path[i],
1310 strlen(zpool_default_import_path[i])) == 0) {
1311 *order = i;
1312 error = 0;
1313 break;
1314 }
1315 }
1316 }
1317
1318 return (error);
1319}
1320
34dc7c2f
BB
1321/*
1322 * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
1323 * an ioctl().
1324 */
1325int
1326zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
1327{
1328 if (len == 0)
572e2857 1329 len = 16 * 1024;
34dc7c2f 1330 zc->zc_nvlist_dst_size = len;
23de906c
CW
1331 zc->zc_nvlist_dst =
1332 (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1333 if (zc->zc_nvlist_dst == 0)
34dc7c2f
BB
1334 return (-1);
1335
1336 return (0);
1337}
1338
1339/*
1340 * Called when an ioctl() which returns an nvlist fails with ENOMEM. This will
1341 * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
1342 * filled in by the kernel to indicate the actual required size.
1343 */
1344int
1345zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
1346{
1347 free((void *)(uintptr_t)zc->zc_nvlist_dst);
23de906c
CW
1348 zc->zc_nvlist_dst =
1349 (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1350 if (zc->zc_nvlist_dst == 0)
34dc7c2f
BB
1351 return (-1);
1352
1353 return (0);
1354}
1355
1356/*
1357 * Called to free the src and dst nvlists stored in the command structure.
1358 */
1359void
1360zcmd_free_nvlists(zfs_cmd_t *zc)
1361{
1362 free((void *)(uintptr_t)zc->zc_nvlist_conf);
1363 free((void *)(uintptr_t)zc->zc_nvlist_src);
1364 free((void *)(uintptr_t)zc->zc_nvlist_dst);
23de906c
CW
1365 zc->zc_nvlist_conf = 0;
1366 zc->zc_nvlist_src = 0;
1367 zc->zc_nvlist_dst = 0;
34dc7c2f
BB
1368}
1369
1370static int
1371zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
1372 nvlist_t *nvl)
1373{
1374 char *packed;
1375 size_t len;
1376
1377 verify(nvlist_size(nvl, &len, NV_ENCODE_NATIVE) == 0);
1378
1379 if ((packed = zfs_alloc(hdl, len)) == NULL)
1380 return (-1);
1381
1382 verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
1383
1384 *outnv = (uint64_t)(uintptr_t)packed;
1385 *outlen = len;
1386
1387 return (0);
1388}
1389
1390int
1391zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1392{
1393 return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
1394 &zc->zc_nvlist_conf_size, nvl));
1395}
1396
1397int
1398zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1399{
1400 return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
1401 &zc->zc_nvlist_src_size, nvl));
1402}
1403
1404/*
1405 * Unpacks an nvlist from the ZFS ioctl command structure.
1406 */
1407int
1408zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
1409{
1410 if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
1411 zc->zc_nvlist_dst_size, nvlp, 0) != 0)
1412 return (no_memory(hdl));
1413
1414 return (0);
1415}
1416
1417int
1418zfs_ioctl(libzfs_handle_t *hdl, int request, zfs_cmd_t *zc)
1419{
6f1ffb06 1420 return (ioctl(hdl->libzfs_fd, request, zc));
34dc7c2f
BB
1421}
1422
1423/*
1424 * ================================================================
1425 * API shared by zfs and zpool property management
1426 * ================================================================
1427 */
1428
1429static void
1430zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
1431{
1432 zprop_list_t *pl = cbp->cb_proplist;
1433 int i;
1434 char *title;
1435 size_t len;
1436
1437 cbp->cb_first = B_FALSE;
1438 if (cbp->cb_scripted)
1439 return;
1440
1441 /*
1442 * Start with the length of the column headers.
1443 */
1444 cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
1445 cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
1446 "PROPERTY"));
1447 cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
1448 "VALUE"));
428870ff
BB
1449 cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
1450 "RECEIVED"));
34dc7c2f
BB
1451 cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
1452 "SOURCE"));
1453
fb5f0bc8
BB
1454 /* first property is always NAME */
1455 assert(cbp->cb_proplist->pl_prop ==
1456 ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME : ZFS_PROP_NAME));
1457
34dc7c2f
BB
1458 /*
1459 * Go through and calculate the widths for each column. For the
1460 * 'source' column, we kludge it up by taking the worst-case scenario of
1461 * inheriting from the longest name. This is acceptable because in the
1462 * majority of cases 'SOURCE' is the last column displayed, and we don't
1463 * use the width anyway. Note that the 'VALUE' column can be oversized,
428870ff 1464 * if the name of the property is much longer than any values we find.
34dc7c2f
BB
1465 */
1466 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
1467 /*
1468 * 'PROPERTY' column
1469 */
1470 if (pl->pl_prop != ZPROP_INVAL) {
1471 const char *propname = (type == ZFS_TYPE_POOL) ?
1472 zpool_prop_to_name(pl->pl_prop) :
1473 zfs_prop_to_name(pl->pl_prop);
1474
1475 len = strlen(propname);
1476 if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1477 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1478 } else {
1479 len = strlen(pl->pl_user_prop);
1480 if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1481 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1482 }
1483
1484 /*
fb5f0bc8
BB
1485 * 'VALUE' column. The first property is always the 'name'
1486 * property that was tacked on either by /sbin/zfs's
1487 * zfs_do_get() or when calling zprop_expand_list(), so we
1488 * ignore its width. If the user specified the name property
1489 * to display, then it will be later in the list in any case.
34dc7c2f 1490 */
fb5f0bc8 1491 if (pl != cbp->cb_proplist &&
34dc7c2f
BB
1492 pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
1493 cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
1494
428870ff
BB
1495 /* 'RECEIVED' column. */
1496 if (pl != cbp->cb_proplist &&
1497 pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
1498 cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
1499
34dc7c2f
BB
1500 /*
1501 * 'NAME' and 'SOURCE' columns
1502 */
1503 if (pl->pl_prop == (type == ZFS_TYPE_POOL ? ZPOOL_PROP_NAME :
1504 ZFS_PROP_NAME) &&
1505 pl->pl_width > cbp->cb_colwidths[GET_COL_NAME]) {
1506 cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
1507 cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
1508 strlen(dgettext(TEXT_DOMAIN, "inherited from"));
1509 }
1510 }
1511
1512 /*
1513 * Now go through and print the headers.
1514 */
428870ff 1515 for (i = 0; i < ZFS_GET_NCOLS; i++) {
34dc7c2f
BB
1516 switch (cbp->cb_columns[i]) {
1517 case GET_COL_NAME:
1518 title = dgettext(TEXT_DOMAIN, "NAME");
1519 break;
1520 case GET_COL_PROPERTY:
1521 title = dgettext(TEXT_DOMAIN, "PROPERTY");
1522 break;
1523 case GET_COL_VALUE:
1524 title = dgettext(TEXT_DOMAIN, "VALUE");
1525 break;
428870ff
BB
1526 case GET_COL_RECVD:
1527 title = dgettext(TEXT_DOMAIN, "RECEIVED");
1528 break;
34dc7c2f
BB
1529 case GET_COL_SOURCE:
1530 title = dgettext(TEXT_DOMAIN, "SOURCE");
1531 break;
1532 default:
1533 title = NULL;
1534 }
1535
1536 if (title != NULL) {
428870ff
BB
1537 if (i == (ZFS_GET_NCOLS - 1) ||
1538 cbp->cb_columns[i + 1] == GET_COL_NONE)
34dc7c2f
BB
1539 (void) printf("%s", title);
1540 else
1541 (void) printf("%-*s ",
1542 cbp->cb_colwidths[cbp->cb_columns[i]],
1543 title);
1544 }
1545 }
1546 (void) printf("\n");
1547}
1548
1549/*
1550 * Display a single line of output, according to the settings in the callback
1551 * structure.
1552 */
1553void
1554zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
1555 const char *propname, const char *value, zprop_source_t sourcetype,
428870ff 1556 const char *source, const char *recvd_value)
34dc7c2f
BB
1557{
1558 int i;
d4ed6673 1559 const char *str = NULL;
34dc7c2f
BB
1560 char buf[128];
1561
1562 /*
1563 * Ignore those source types that the user has chosen to ignore.
1564 */
1565 if ((sourcetype & cbp->cb_sources) == 0)
1566 return;
1567
1568 if (cbp->cb_first)
1569 zprop_print_headers(cbp, cbp->cb_type);
1570
428870ff 1571 for (i = 0; i < ZFS_GET_NCOLS; i++) {
34dc7c2f
BB
1572 switch (cbp->cb_columns[i]) {
1573 case GET_COL_NAME:
1574 str = name;
1575 break;
1576
1577 case GET_COL_PROPERTY:
1578 str = propname;
1579 break;
1580
1581 case GET_COL_VALUE:
1582 str = value;
1583 break;
1584
1585 case GET_COL_SOURCE:
1586 switch (sourcetype) {
1587 case ZPROP_SRC_NONE:
1588 str = "-";
1589 break;
1590
1591 case ZPROP_SRC_DEFAULT:
1592 str = "default";
1593 break;
1594
1595 case ZPROP_SRC_LOCAL:
1596 str = "local";
1597 break;
1598
1599 case ZPROP_SRC_TEMPORARY:
1600 str = "temporary";
1601 break;
1602
1603 case ZPROP_SRC_INHERITED:
1604 (void) snprintf(buf, sizeof (buf),
1605 "inherited from %s", source);
1606 str = buf;
1607 break;
428870ff
BB
1608 case ZPROP_SRC_RECEIVED:
1609 str = "received";
1610 break;
23d70cde
GM
1611
1612 default:
1613 str = NULL;
1614 assert(!"unhandled zprop_source_t");
34dc7c2f
BB
1615 }
1616 break;
1617
428870ff
BB
1618 case GET_COL_RECVD:
1619 str = (recvd_value == NULL ? "-" : recvd_value);
1620 break;
1621
34dc7c2f
BB
1622 default:
1623 continue;
1624 }
1625
23827a4c
G
1626 if (i == (ZFS_GET_NCOLS - 1) ||
1627 cbp->cb_columns[i + 1] == GET_COL_NONE)
34dc7c2f
BB
1628 (void) printf("%s", str);
1629 else if (cbp->cb_scripted)
1630 (void) printf("%s\t", str);
1631 else
1632 (void) printf("%-*s ",
1633 cbp->cb_colwidths[cbp->cb_columns[i]],
1634 str);
34dc7c2f
BB
1635 }
1636
1637 (void) printf("\n");
1638}
1639
1640/*
1641 * Given a numeric suffix, convert the value into a number of bits that the
1642 * resulting value must be shifted.
1643 */
1644static int
1645str2shift(libzfs_handle_t *hdl, const char *buf)
1646{
1647 const char *ends = "BKMGTPEZ";
1648 int i;
1649
1650 if (buf[0] == '\0')
1651 return (0);
1652 for (i = 0; i < strlen(ends); i++) {
1653 if (toupper(buf[0]) == ends[i])
1654 break;
1655 }
1656 if (i == strlen(ends)) {
53c2ec1d
JL
1657 if (hdl)
1658 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1659 "invalid numeric suffix '%s'"), buf);
34dc7c2f
BB
1660 return (-1);
1661 }
1662
1663 /*
826ab7ad
RL
1664 * Allow 'G' = 'GB' = 'GiB', case-insensitively.
1665 * However, 'BB' and 'BiB' are disallowed.
34dc7c2f 1666 */
826ab7ad
RL
1667 if (buf[1] == '\0' ||
1668 (toupper(buf[0]) != 'B' &&
d1d7e268
MK
1669 ((toupper(buf[1]) == 'B' && buf[2] == '\0') ||
1670 (toupper(buf[1]) == 'I' && toupper(buf[2]) == 'B' &&
1671 buf[3] == '\0'))))
1672 return (10 * i);
34dc7c2f 1673
53c2ec1d
JL
1674 if (hdl)
1675 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1676 "invalid numeric suffix '%s'"), buf);
34dc7c2f
BB
1677 return (-1);
1678}
1679
1680/*
1681 * Convert a string of the form '100G' into a real number. Used when setting
1682 * properties or creating a volume. 'buf' is used to place an extended error
1683 * message for the caller to use.
1684 */
1685int
1686zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1687{
1688 char *end;
1689 int shift;
1690
1691 *num = 0;
1692
1693 /* Check to see if this looks like a number. */
1694 if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1695 if (hdl)
1696 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1697 "bad numeric value '%s'"), value);
1698 return (-1);
1699 }
1700
428870ff 1701 /* Rely on strtoull() to process the numeric portion. */
34dc7c2f 1702 errno = 0;
d164b209 1703 *num = strtoull(value, &end, 10);
34dc7c2f
BB
1704
1705 /*
1706 * Check for ERANGE, which indicates that the value is too large to fit
1707 * in a 64-bit value.
1708 */
1709 if (errno == ERANGE) {
1710 if (hdl)
1711 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1712 "numeric value is too large"));
1713 return (-1);
1714 }
1715
1716 /*
1717 * If we have a decimal value, then do the computation with floating
1718 * point arithmetic. Otherwise, use standard arithmetic.
1719 */
1720 if (*end == '.') {
1721 double fval = strtod(value, &end);
1722
1723 if ((shift = str2shift(hdl, end)) == -1)
1724 return (-1);
1725
1726 fval *= pow(2, shift);
1727
1728 if (fval > UINT64_MAX) {
1729 if (hdl)
1730 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1731 "numeric value is too large"));
1732 return (-1);
1733 }
1734
1735 *num = (uint64_t)fval;
1736 } else {
1737 if ((shift = str2shift(hdl, end)) == -1)
1738 return (-1);
1739
1740 /* Check for overflow */
1741 if (shift >= 64 || (*num << shift) >> shift != *num) {
1742 if (hdl)
1743 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1744 "numeric value is too large"));
1745 return (-1);
1746 }
1747
1748 *num <<= shift;
1749 }
1750
1751 return (0);
1752}
1753
1754/*
1755 * Given a propname=value nvpair to set, parse any numeric properties
1756 * (index, boolean, etc) if they are specified as strings and add the
1757 * resulting nvpair to the returned nvlist.
1758 *
1759 * At the DSL layer, all properties are either 64-bit numbers or strings.
1760 * We want the user to be able to ignore this fact and specify properties
1761 * as native values (numbers, for example) or as strings (to simplify
1762 * command line utilities). This also handles converting index types
1763 * (compression, checksum, etc) from strings to their on-disk index.
1764 */
1765int
1766zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1767 zfs_type_t type, nvlist_t *ret, char **svalp, uint64_t *ivalp,
1768 const char *errbuf)
1769{
1770 data_type_t datatype = nvpair_type(elem);
1771 zprop_type_t proptype;
1772 const char *propname;
1773 char *value;
1774 boolean_t isnone = B_FALSE;
b6ca6193 1775 int err = 0;
34dc7c2f
BB
1776
1777 if (type == ZFS_TYPE_POOL) {
1778 proptype = zpool_prop_get_type(prop);
1779 propname = zpool_prop_to_name(prop);
1780 } else {
1781 proptype = zfs_prop_get_type(prop);
1782 propname = zfs_prop_to_name(prop);
1783 }
1784
1785 /*
1786 * Convert any properties to the internal DSL value types.
1787 */
1788 *svalp = NULL;
1789 *ivalp = 0;
1790
1791 switch (proptype) {
1792 case PROP_TYPE_STRING:
1793 if (datatype != DATA_TYPE_STRING) {
1794 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1795 "'%s' must be a string"), nvpair_name(elem));
1796 goto error;
1797 }
b6ca6193 1798 err = nvpair_value_string(elem, svalp);
1799 if (err != 0) {
1800 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1801 "'%s' is invalid"), nvpair_name(elem));
1802 goto error;
1803 }
34dc7c2f
BB
1804 if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1805 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1806 "'%s' is too long"), nvpair_name(elem));
1807 goto error;
1808 }
1809 break;
1810
1811 case PROP_TYPE_NUMBER:
1812 if (datatype == DATA_TYPE_STRING) {
1813 (void) nvpair_value_string(elem, &value);
1814 if (strcmp(value, "none") == 0) {
1815 isnone = B_TRUE;
1816 } else if (zfs_nicestrtonum(hdl, value, ivalp)
1817 != 0) {
1818 goto error;
1819 }
1820 } else if (datatype == DATA_TYPE_UINT64) {
1821 (void) nvpair_value_uint64(elem, ivalp);
1822 } else {
1823 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1824 "'%s' must be a number"), nvpair_name(elem));
1825 goto error;
1826 }
1827
1828 /*
1829 * Quota special: force 'none' and don't allow 0.
1830 */
1831 if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1832 (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1833 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1834 "use 'none' to disable quota/refquota"));
1835 goto error;
1836 }
788eb90c
JJ
1837
1838 /*
1839 * Special handling for "*_limit=none". In this case it's not
1840 * 0 but UINT64_MAX.
1841 */
1842 if ((type & ZFS_TYPE_DATASET) && isnone &&
1843 (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1844 prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1845 *ivalp = UINT64_MAX;
1846 }
34dc7c2f
BB
1847 break;
1848
1849 case PROP_TYPE_INDEX:
1850 if (datatype != DATA_TYPE_STRING) {
1851 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1852 "'%s' must be a string"), nvpair_name(elem));
1853 goto error;
1854 }
1855
1856 (void) nvpair_value_string(elem, &value);
1857
1858 if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1859 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1860 "'%s' must be one of '%s'"), propname,
1861 zprop_values(prop, type));
1862 goto error;
1863 }
1864 break;
1865
1866 default:
1867 abort();
1868 }
1869
1870 /*
1871 * Add the result to our return set of properties.
1872 */
1873 if (*svalp != NULL) {
1874 if (nvlist_add_string(ret, propname, *svalp) != 0) {
1875 (void) no_memory(hdl);
1876 return (-1);
1877 }
1878 } else {
1879 if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1880 (void) no_memory(hdl);
1881 return (-1);
1882 }
1883 }
1884
1885 return (0);
1886error:
1887 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1888 return (-1);
1889}
1890
b128c09f
BB
1891static int
1892addlist(libzfs_handle_t *hdl, char *propname, zprop_list_t **listp,
1893 zfs_type_t type)
1894{
1895 int prop;
1896 zprop_list_t *entry;
1897
1898 prop = zprop_name_to_prop(propname, type);
1899
962d5242 1900 if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type, B_FALSE))
b128c09f
BB
1901 prop = ZPROP_INVAL;
1902
1903 /*
1904 * When no property table entry can be found, return failure if
1905 * this is a pool property or if this isn't a user-defined
1906 * dataset property,
1907 */
9ae529ec
CS
1908 if (prop == ZPROP_INVAL && ((type == ZFS_TYPE_POOL &&
1909 !zpool_prop_feature(propname) &&
1910 !zpool_prop_unsupported(propname)) ||
1911 (type == ZFS_TYPE_DATASET && !zfs_prop_user(propname) &&
1912 !zfs_prop_userquota(propname) && !zfs_prop_written(propname)))) {
b128c09f
BB
1913 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1914 "invalid property '%s'"), propname);
1915 return (zfs_error(hdl, EZFS_BADPROP,
1916 dgettext(TEXT_DOMAIN, "bad property list")));
1917 }
1918
1919 if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1920 return (-1);
1921
1922 entry->pl_prop = prop;
1923 if (prop == ZPROP_INVAL) {
9ae529ec
CS
1924 if ((entry->pl_user_prop = zfs_strdup(hdl, propname)) ==
1925 NULL) {
b128c09f
BB
1926 free(entry);
1927 return (-1);
1928 }
1929 entry->pl_width = strlen(propname);
1930 } else {
1931 entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1932 type);
1933 }
1934
1935 *listp = entry;
1936
1937 return (0);
1938}
1939
34dc7c2f
BB
1940/*
1941 * Given a comma-separated list of properties, construct a property list
1942 * containing both user-defined and native properties. This function will
1943 * return a NULL list if 'all' is specified, which can later be expanded
1944 * by zprop_expand_list().
1945 */
1946int
1947zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1948 zfs_type_t type)
1949{
34dc7c2f 1950 *listp = NULL;
34dc7c2f
BB
1951
1952 /*
1953 * If 'all' is specified, return a NULL list.
1954 */
1955 if (strcmp(props, "all") == 0)
1956 return (0);
1957
1958 /*
1959 * If no props were specified, return an error.
1960 */
1961 if (props[0] == '\0') {
1962 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1963 "no properties specified"));
1964 return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
1965 "bad property list")));
1966 }
1967
1968 /*
1969 * It would be nice to use getsubopt() here, but the inclusion of column
1970 * aliases makes this more effort than it's worth.
1971 */
b128c09f
BB
1972 while (*props != '\0') {
1973 size_t len;
1974 char *p;
1975 char c;
1976
1977 if ((p = strchr(props, ',')) == NULL) {
1978 len = strlen(props);
1979 p = props + len;
34dc7c2f 1980 } else {
b128c09f 1981 len = p - props;
34dc7c2f
BB
1982 }
1983
1984 /*
1985 * Check for empty options.
1986 */
1987 if (len == 0) {
1988 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1989 "empty property name"));
1990 return (zfs_error(hdl, EZFS_BADPROP,
1991 dgettext(TEXT_DOMAIN, "bad property list")));
1992 }
1993
1994 /*
1995 * Check all regular property names.
1996 */
b128c09f
BB
1997 c = props[len];
1998 props[len] = '\0';
1999
2000 if (strcmp(props, "space") == 0) {
2001 static char *spaceprops[] = {
2002 "name", "avail", "used", "usedbysnapshots",
2003 "usedbydataset", "usedbyrefreservation",
2004 "usedbychildren", NULL
2005 };
2006 int i;
2007
2008 for (i = 0; spaceprops[i]; i++) {
2009 if (addlist(hdl, spaceprops[i], listp, type))
2010 return (-1);
2011 listp = &(*listp)->pl_next;
34dc7c2f 2012 }
34dc7c2f 2013 } else {
b128c09f
BB
2014 if (addlist(hdl, props, listp, type))
2015 return (-1);
2016 listp = &(*listp)->pl_next;
34dc7c2f
BB
2017 }
2018
b128c09f 2019 props = p;
34dc7c2f 2020 if (c == ',')
b128c09f 2021 props++;
34dc7c2f
BB
2022 }
2023
2024 return (0);
2025}
2026
2027void
2028zprop_free_list(zprop_list_t *pl)
2029{
2030 zprop_list_t *next;
2031
2032 while (pl != NULL) {
2033 next = pl->pl_next;
2034 free(pl->pl_user_prop);
2035 free(pl);
2036 pl = next;
2037 }
2038}
2039
2040typedef struct expand_data {
2041 zprop_list_t **last;
2042 libzfs_handle_t *hdl;
2043 zfs_type_t type;
2044} expand_data_t;
2045
2046int
2047zprop_expand_list_cb(int prop, void *cb)
2048{
2049 zprop_list_t *entry;
2050 expand_data_t *edp = cb;
2051
2052 if ((entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t))) == NULL)
2053 return (ZPROP_INVAL);
2054
2055 entry->pl_prop = prop;
2056 entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
2057 entry->pl_all = B_TRUE;
2058
2059 *(edp->last) = entry;
2060 edp->last = &entry->pl_next;
2061
2062 return (ZPROP_CONT);
2063}
2064
2065int
2066zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
2067{
2068 zprop_list_t *entry;
2069 zprop_list_t **last;
2070 expand_data_t exp;
2071
2072 if (*plp == NULL) {
2073 /*
2074 * If this is the very first time we've been called for an 'all'
2075 * specification, expand the list to include all native
2076 * properties.
2077 */
2078 last = plp;
2079
2080 exp.last = last;
2081 exp.hdl = hdl;
2082 exp.type = type;
2083
2084 if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
2085 B_FALSE, type) == ZPROP_INVAL)
2086 return (-1);
2087
2088 /*
2089 * Add 'name' to the beginning of the list, which is handled
2090 * specially.
2091 */
2092 if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
2093 return (-1);
2094
2095 entry->pl_prop = (type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
2096 ZFS_PROP_NAME;
2097 entry->pl_width = zprop_width(entry->pl_prop,
2098 &entry->pl_fixed, type);
2099 entry->pl_all = B_TRUE;
2100 entry->pl_next = *plp;
2101 *plp = entry;
2102 }
2103 return (0);
2104}
2105
2106int
2107zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
2108 zfs_type_t type)
2109{
2110 return (zprop_iter_common(func, cb, show_all, ordered, type));
2111}