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