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