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 */
21
22/*
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright 2020 Joyent, Inc.
25 * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
26 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
27 * Copyright (c) 2017 Datto Inc.
28 */
29
30/*
31 * Internal utility routines for the ZFS library.
32 */
33
34#include <ctype.h>
35#include <errno.h>
36#include <fcntl.h>
37#include <libintl.h>
38#include <stdarg.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <strings.h>
42#include <math.h>
43#include <sys/filio.h>
44#include <sys/mnttab.h>
45#include <sys/mntent.h>
46#include <sys/types.h>
47#include <libcmdutils.h>
48
49#include <libzfs.h>
50#include <libzfs_core.h>
51
52#include "libzfs_impl.h"
53#include "zfs_prop.h"
54#include "zfs_comutil.h"
55#include "zfeature_common.h"
56#include <libzutil.h>
57
58int
59libzfs_errno(libzfs_handle_t *hdl)
60{
61	return (hdl->libzfs_error);
62}
63
64const char *
65libzfs_error_action(libzfs_handle_t *hdl)
66{
67	return (hdl->libzfs_action);
68}
69
70const char *
71libzfs_error_description(libzfs_handle_t *hdl)
72{
73	if (hdl->libzfs_desc[0] != '\0')
74		return (hdl->libzfs_desc);
75
76	switch (hdl->libzfs_error) {
77	case EZFS_NOMEM:
78		return (dgettext(TEXT_DOMAIN, "out of memory"));
79	case EZFS_BADPROP:
80		return (dgettext(TEXT_DOMAIN, "invalid property value"));
81	case EZFS_PROPREADONLY:
82		return (dgettext(TEXT_DOMAIN, "read-only property"));
83	case EZFS_PROPTYPE:
84		return (dgettext(TEXT_DOMAIN, "property doesn't apply to "
85		    "datasets of this type"));
86	case EZFS_PROPNONINHERIT:
87		return (dgettext(TEXT_DOMAIN, "property cannot be inherited"));
88	case EZFS_PROPSPACE:
89		return (dgettext(TEXT_DOMAIN, "invalid quota or reservation"));
90	case EZFS_BADTYPE:
91		return (dgettext(TEXT_DOMAIN, "operation not applicable to "
92		    "datasets of this type"));
93	case EZFS_BUSY:
94		return (dgettext(TEXT_DOMAIN, "pool or dataset is busy"));
95	case EZFS_EXISTS:
96		return (dgettext(TEXT_DOMAIN, "pool or dataset exists"));
97	case EZFS_NOENT:
98		return (dgettext(TEXT_DOMAIN, "no such pool or dataset"));
99	case EZFS_BADSTREAM:
100		return (dgettext(TEXT_DOMAIN, "invalid backup stream"));
101	case EZFS_DSREADONLY:
102		return (dgettext(TEXT_DOMAIN, "dataset is read-only"));
103	case EZFS_VOLTOOBIG:
104		return (dgettext(TEXT_DOMAIN, "volume size exceeds limit for "
105		    "this system"));
106	case EZFS_INVALIDNAME:
107		return (dgettext(TEXT_DOMAIN, "invalid name"));
108	case EZFS_BADRESTORE:
109		return (dgettext(TEXT_DOMAIN, "unable to restore to "
110		    "destination"));
111	case EZFS_BADBACKUP:
112		return (dgettext(TEXT_DOMAIN, "backup failed"));
113	case EZFS_BADTARGET:
114		return (dgettext(TEXT_DOMAIN, "invalid target vdev"));
115	case EZFS_NODEVICE:
116		return (dgettext(TEXT_DOMAIN, "no such device in pool"));
117	case EZFS_BADDEV:
118		return (dgettext(TEXT_DOMAIN, "invalid device"));
119	case EZFS_NOREPLICAS:
120		return (dgettext(TEXT_DOMAIN, "no valid replicas"));
121	case EZFS_RESILVERING:
122		return (dgettext(TEXT_DOMAIN, "currently resilvering"));
123	case EZFS_BADVERSION:
124		return (dgettext(TEXT_DOMAIN, "unsupported version or "
125		    "feature"));
126	case EZFS_POOLUNAVAIL:
127		return (dgettext(TEXT_DOMAIN, "pool is unavailable"));
128	case EZFS_DEVOVERFLOW:
129		return (dgettext(TEXT_DOMAIN, "too many devices in one vdev"));
130	case EZFS_BADPATH:
131		return (dgettext(TEXT_DOMAIN, "must be an absolute path"));
132	case EZFS_CROSSTARGET:
133		return (dgettext(TEXT_DOMAIN, "operation crosses datasets or "
134		    "pools"));
135	case EZFS_ZONED:
136		return (dgettext(TEXT_DOMAIN, "dataset in use by local zone"));
137	case EZFS_MOUNTFAILED:
138		return (dgettext(TEXT_DOMAIN, "mount failed"));
139	case EZFS_UMOUNTFAILED:
140		return (dgettext(TEXT_DOMAIN, "umount failed"));
141	case EZFS_UNSHARENFSFAILED:
142		return (dgettext(TEXT_DOMAIN, "unshare(1M) failed"));
143	case EZFS_SHARENFSFAILED:
144		return (dgettext(TEXT_DOMAIN, "share(1M) failed"));
145	case EZFS_UNSHARESMBFAILED:
146		return (dgettext(TEXT_DOMAIN, "smb remove share failed"));
147	case EZFS_SHARESMBFAILED:
148		return (dgettext(TEXT_DOMAIN, "smb add share failed"));
149	case EZFS_PERM:
150		return (dgettext(TEXT_DOMAIN, "permission denied"));
151	case EZFS_NOSPC:
152		return (dgettext(TEXT_DOMAIN, "out of space"));
153	case EZFS_FAULT:
154		return (dgettext(TEXT_DOMAIN, "bad address"));
155	case EZFS_IO:
156		return (dgettext(TEXT_DOMAIN, "I/O error"));
157	case EZFS_INTR:
158		return (dgettext(TEXT_DOMAIN, "signal received"));
159	case EZFS_ISSPARE:
160		return (dgettext(TEXT_DOMAIN, "device is reserved as a hot "
161		    "spare"));
162	case EZFS_INVALCONFIG:
163		return (dgettext(TEXT_DOMAIN, "invalid vdev configuration"));
164	case EZFS_RECURSIVE:
165		return (dgettext(TEXT_DOMAIN, "recursive dataset dependency"));
166	case EZFS_NOHISTORY:
167		return (dgettext(TEXT_DOMAIN, "no history available"));
168	case EZFS_POOLPROPS:
169		return (dgettext(TEXT_DOMAIN, "failed to retrieve "
170		    "pool properties"));
171	case EZFS_POOL_NOTSUP:
172		return (dgettext(TEXT_DOMAIN, "operation not supported "
173		    "on this type of pool"));
174	case EZFS_POOL_INVALARG:
175		return (dgettext(TEXT_DOMAIN, "invalid argument for "
176		    "this pool operation"));
177	case EZFS_NAMETOOLONG:
178		return (dgettext(TEXT_DOMAIN, "dataset name is too long"));
179	case EZFS_OPENFAILED:
180		return (dgettext(TEXT_DOMAIN, "open failed"));
181	case EZFS_NOCAP:
182		return (dgettext(TEXT_DOMAIN,
183		    "disk capacity information could not be retrieved"));
184	case EZFS_LABELFAILED:
185		return (dgettext(TEXT_DOMAIN, "write of label failed"));
186	case EZFS_BADWHO:
187		return (dgettext(TEXT_DOMAIN, "invalid user/group"));
188	case EZFS_BADPERM:
189		return (dgettext(TEXT_DOMAIN, "invalid permission"));
190	case EZFS_BADPERMSET:
191		return (dgettext(TEXT_DOMAIN, "invalid permission set name"));
192	case EZFS_NODELEGATION:
193		return (dgettext(TEXT_DOMAIN, "delegated administration is "
194		    "disabled on pool"));
195	case EZFS_BADCACHE:
196		return (dgettext(TEXT_DOMAIN, "invalid or missing cache file"));
197	case EZFS_ISL2CACHE:
198		return (dgettext(TEXT_DOMAIN, "device is in use as a cache"));
199	case EZFS_VDEVNOTSUP:
200		return (dgettext(TEXT_DOMAIN, "vdev specification is not "
201		    "supported"));
202	case EZFS_NOTSUP:
203		return (dgettext(TEXT_DOMAIN, "operation not supported "
204		    "on this dataset"));
205	case EZFS_IOC_NOTSUPPORTED:
206		return (dgettext(TEXT_DOMAIN, "operation not supported by "
207		    "zfs kernel module"));
208	case EZFS_ACTIVE_SPARE:
209		return (dgettext(TEXT_DOMAIN, "pool has active shared spare "
210		    "device"));
211	case EZFS_UNPLAYED_LOGS:
212		return (dgettext(TEXT_DOMAIN, "log device has unplayed intent "
213		    "logs"));
214	case EZFS_REFTAG_RELE:
215		return (dgettext(TEXT_DOMAIN, "no such tag on this dataset"));
216	case EZFS_REFTAG_HOLD:
217		return (dgettext(TEXT_DOMAIN, "tag already exists on this "
218		    "dataset"));
219	case EZFS_TAGTOOLONG:
220		return (dgettext(TEXT_DOMAIN, "tag too long"));
221	case EZFS_PIPEFAILED:
222		return (dgettext(TEXT_DOMAIN, "pipe create failed"));
223	case EZFS_THREADCREATEFAILED:
224		return (dgettext(TEXT_DOMAIN, "thread create failed"));
225	case EZFS_POSTSPLIT_ONLINE:
226		return (dgettext(TEXT_DOMAIN, "disk was split from this pool "
227		    "into a new one"));
228	case EZFS_SCRUB_PAUSED:
229		return (dgettext(TEXT_DOMAIN, "scrub is paused; "
230		    "use 'zpool scrub' to resume"));
231	case EZFS_SCRUBBING:
232		return (dgettext(TEXT_DOMAIN, "currently scrubbing; "
233		    "use 'zpool scrub -s' to cancel current scrub"));
234	case EZFS_NO_SCRUB:
235		return (dgettext(TEXT_DOMAIN, "there is no active scrub"));
236	case EZFS_DIFF:
237		return (dgettext(TEXT_DOMAIN, "unable to generate diffs"));
238	case EZFS_DIFFDATA:
239		return (dgettext(TEXT_DOMAIN, "invalid diff data"));
240	case EZFS_POOLREADONLY:
241		return (dgettext(TEXT_DOMAIN, "pool is read-only"));
242	case EZFS_NO_PENDING:
243		return (dgettext(TEXT_DOMAIN, "operation is not "
244		    "in progress"));
245	case EZFS_CHECKPOINT_EXISTS:
246		return (dgettext(TEXT_DOMAIN, "checkpoint exists"));
247	case EZFS_DISCARDING_CHECKPOINT:
248		return (dgettext(TEXT_DOMAIN, "currently discarding "
249		    "checkpoint"));
250	case EZFS_NO_CHECKPOINT:
251		return (dgettext(TEXT_DOMAIN, "checkpoint does not exist"));
252	case EZFS_DEVRM_IN_PROGRESS:
253		return (dgettext(TEXT_DOMAIN, "device removal in progress"));
254	case EZFS_VDEV_TOO_BIG:
255		return (dgettext(TEXT_DOMAIN, "device exceeds supported size"));
256	case EZFS_ACTIVE_POOL:
257		return (dgettext(TEXT_DOMAIN, "pool is imported on a "
258		    "different host"));
259	case EZFS_CRYPTOFAILED:
260		return (dgettext(TEXT_DOMAIN, "encryption failure"));
261	case EZFS_TOOMANY:
262		return (dgettext(TEXT_DOMAIN, "argument list too long"));
263	case EZFS_INITIALIZING:
264		return (dgettext(TEXT_DOMAIN, "currently initializing"));
265	case EZFS_NO_INITIALIZE:
266		return (dgettext(TEXT_DOMAIN, "there is no active "
267		    "initialization"));
268	case EZFS_WRONG_PARENT:
269		return (dgettext(TEXT_DOMAIN, "invalid parent dataset"));
270	case EZFS_TRIMMING:
271		return (dgettext(TEXT_DOMAIN, "currently trimming"));
272	case EZFS_NO_TRIM:
273		return (dgettext(TEXT_DOMAIN, "there is no active trim"));
274	case EZFS_TRIM_NOTSUP:
275		return (dgettext(TEXT_DOMAIN, "trim operations are not "
276		    "supported by this device"));
277	case EZFS_NO_RESILVER_DEFER:
278		return (dgettext(TEXT_DOMAIN, "this action requires the "
279		    "resilver_defer feature"));
280	case EZFS_UNKNOWN:
281		return (dgettext(TEXT_DOMAIN, "unknown error"));
282	default:
283		assert(hdl->libzfs_error == 0);
284		return (dgettext(TEXT_DOMAIN, "no error"));
285	}
286}
287
288/*PRINTFLIKE2*/
289void
290zfs_error_aux(libzfs_handle_t *hdl, const char *fmt, ...)
291{
292	va_list ap;
293
294	va_start(ap, fmt);
295
296	(void) vsnprintf(hdl->libzfs_desc, sizeof (hdl->libzfs_desc),
297	    fmt, ap);
298	hdl->libzfs_desc_active = 1;
299
300	va_end(ap);
301}
302
303static void
304zfs_verror(libzfs_handle_t *hdl, int error, const char *fmt, va_list ap)
305{
306	(void) vsnprintf(hdl->libzfs_action, sizeof (hdl->libzfs_action),
307	    fmt, ap);
308	hdl->libzfs_error = error;
309
310	if (hdl->libzfs_desc_active)
311		hdl->libzfs_desc_active = 0;
312	else
313		hdl->libzfs_desc[0] = '\0';
314
315	if (hdl->libzfs_printerr) {
316		if (error == EZFS_UNKNOWN) {
317			(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "internal "
318			    "error: %s\n"), libzfs_error_description(hdl));
319			abort();
320		}
321
322		(void) fprintf(stderr, "%s: %s\n", hdl->libzfs_action,
323		    libzfs_error_description(hdl));
324		if (error == EZFS_NOMEM)
325			exit(1);
326	}
327}
328
329int
330zfs_error(libzfs_handle_t *hdl, int error, const char *msg)
331{
332	return (zfs_error_fmt(hdl, error, "%s", msg));
333}
334
335/*PRINTFLIKE3*/
336int
337zfs_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
338{
339	va_list ap;
340
341	va_start(ap, fmt);
342
343	zfs_verror(hdl, error, fmt, ap);
344
345	va_end(ap);
346
347	return (-1);
348}
349
350static int
351zfs_common_error(libzfs_handle_t *hdl, int error, const char *fmt,
352    va_list ap)
353{
354	switch (error) {
355	case EPERM:
356	case EACCES:
357		zfs_verror(hdl, EZFS_PERM, fmt, ap);
358		return (-1);
359
360	case ECANCELED:
361		zfs_verror(hdl, EZFS_NODELEGATION, fmt, ap);
362		return (-1);
363
364	case EIO:
365		zfs_verror(hdl, EZFS_IO, fmt, ap);
366		return (-1);
367
368	case EFAULT:
369		zfs_verror(hdl, EZFS_FAULT, fmt, ap);
370		return (-1);
371
372	case EINTR:
373		zfs_verror(hdl, EZFS_INTR, fmt, ap);
374		return (-1);
375	}
376
377	return (0);
378}
379
380int
381zfs_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
382{
383	return (zfs_standard_error_fmt(hdl, error, "%s", msg));
384}
385
386/*PRINTFLIKE3*/
387int
388zfs_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
389{
390	va_list ap;
391
392	va_start(ap, fmt);
393
394	if (zfs_common_error(hdl, error, fmt, ap) != 0) {
395		va_end(ap);
396		return (-1);
397	}
398
399	switch (error) {
400	case ENXIO:
401	case ENODEV:
402	case EPIPE:
403		zfs_verror(hdl, EZFS_IO, fmt, ap);
404		break;
405
406	case ENOENT:
407		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
408		    "dataset does not exist"));
409		zfs_verror(hdl, EZFS_NOENT, fmt, ap);
410		break;
411
412	case ENOSPC:
413	case EDQUOT:
414		zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
415		return (-1);
416
417	case EEXIST:
418		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
419		    "dataset already exists"));
420		zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
421		break;
422
423	case EBUSY:
424		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
425		    "dataset is busy"));
426		zfs_verror(hdl, EZFS_BUSY, fmt, ap);
427		break;
428	case EROFS:
429		zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
430		break;
431	case ENAMETOOLONG:
432		zfs_verror(hdl, EZFS_NAMETOOLONG, fmt, ap);
433		break;
434	case ENOTSUP:
435		zfs_verror(hdl, EZFS_BADVERSION, fmt, ap);
436		break;
437	case EAGAIN:
438		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
439		    "pool I/O is currently suspended"));
440		zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
441		break;
442	case EREMOTEIO:
443		zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
444		break;
445	case ZFS_ERR_IOC_CMD_UNAVAIL:
446		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
447		    "module does not support this operation. A reboot may "
448		    "be required to enable this operation."));
449		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
450		break;
451	case ZFS_ERR_IOC_ARG_UNAVAIL:
452		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
453		    "module does not support an option for this operation. "
454		    "A reboot may be required to enable this option."));
455		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
456		break;
457	case ZFS_ERR_IOC_ARG_REQUIRED:
458	case ZFS_ERR_IOC_ARG_BADTYPE:
459		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
460		break;
461	default:
462		zfs_error_aux(hdl, strerror(error));
463		zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
464		break;
465	}
466
467	va_end(ap);
468	return (-1);
469}
470
471int
472zpool_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
473{
474	return (zpool_standard_error_fmt(hdl, error, "%s", msg));
475}
476
477/*PRINTFLIKE3*/
478int
479zpool_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
480{
481	va_list ap;
482
483	va_start(ap, fmt);
484
485	if (zfs_common_error(hdl, error, fmt, ap) != 0) {
486		va_end(ap);
487		return (-1);
488	}
489
490	switch (error) {
491	case ENODEV:
492		zfs_verror(hdl, EZFS_NODEVICE, fmt, ap);
493		break;
494
495	case ENOENT:
496		zfs_error_aux(hdl,
497		    dgettext(TEXT_DOMAIN, "no such pool or dataset"));
498		zfs_verror(hdl, EZFS_NOENT, fmt, ap);
499		break;
500
501	case EEXIST:
502		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
503		    "pool already exists"));
504		zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
505		break;
506
507	case EBUSY:
508		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool is busy"));
509		zfs_verror(hdl, EZFS_BUSY, fmt, ap);
510		break;
511
512	case ENXIO:
513		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
514		    "one or more devices is currently unavailable"));
515		zfs_verror(hdl, EZFS_BADDEV, fmt, ap);
516		break;
517
518	case ENAMETOOLONG:
519		zfs_verror(hdl, EZFS_DEVOVERFLOW, fmt, ap);
520		break;
521
522	case ENOTSUP:
523		zfs_verror(hdl, EZFS_POOL_NOTSUP, fmt, ap);
524		break;
525
526	case EINVAL:
527		zfs_verror(hdl, EZFS_POOL_INVALARG, fmt, ap);
528		break;
529
530	case ENOSPC:
531	case EDQUOT:
532		zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
533		return (-1);
534
535	case EAGAIN:
536		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
537		    "pool I/O is currently suspended"));
538		zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
539		break;
540
541	case EROFS:
542		zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
543		break;
544	/* There is no pending operation to cancel */
545	case ENOTACTIVE:
546		zfs_verror(hdl, EZFS_NO_PENDING, fmt, ap);
547		break;
548	case EREMOTEIO:
549		zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
550		break;
551	case ZFS_ERR_CHECKPOINT_EXISTS:
552		zfs_verror(hdl, EZFS_CHECKPOINT_EXISTS, fmt, ap);
553		break;
554	case ZFS_ERR_DISCARDING_CHECKPOINT:
555		zfs_verror(hdl, EZFS_DISCARDING_CHECKPOINT, fmt, ap);
556		break;
557	case ZFS_ERR_NO_CHECKPOINT:
558		zfs_verror(hdl, EZFS_NO_CHECKPOINT, fmt, ap);
559		break;
560	case ZFS_ERR_DEVRM_IN_PROGRESS:
561		zfs_verror(hdl, EZFS_DEVRM_IN_PROGRESS, fmt, ap);
562		break;
563	case ZFS_ERR_VDEV_TOO_BIG:
564		zfs_verror(hdl, EZFS_VDEV_TOO_BIG, fmt, ap);
565		break;
566	case ZFS_ERR_IOC_CMD_UNAVAIL:
567		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
568		    "module does not support this operation. A reboot may "
569		    "be required to enable this operation."));
570		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
571		break;
572	case ZFS_ERR_IOC_ARG_UNAVAIL:
573		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
574		    "module does not support an option for this operation. "
575		    "A reboot may be required to enable this option."));
576		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
577		break;
578	case ZFS_ERR_IOC_ARG_REQUIRED:
579	case ZFS_ERR_IOC_ARG_BADTYPE:
580		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
581		break;
582	default:
583		zfs_error_aux(hdl, strerror(error));
584		zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
585	}
586
587	va_end(ap);
588	return (-1);
589}
590
591/*
592 * Display an out of memory error message and abort the current program.
593 */
594int
595no_memory(libzfs_handle_t *hdl)
596{
597	return (zfs_error(hdl, EZFS_NOMEM, "internal error"));
598}
599
600/*
601 * A safe form of malloc() which will die if the allocation fails.
602 */
603void *
604zfs_alloc(libzfs_handle_t *hdl, size_t size)
605{
606	void *data;
607
608	if ((data = calloc(1, size)) == NULL)
609		(void) no_memory(hdl);
610
611	return (data);
612}
613
614/*
615 * A safe form of asprintf() which will die if the allocation fails.
616 */
617/*PRINTFLIKE2*/
618char *
619zfs_asprintf(libzfs_handle_t *hdl, const char *fmt, ...)
620{
621	va_list ap;
622	char *ret;
623	int err;
624
625	va_start(ap, fmt);
626
627	err = vasprintf(&ret, fmt, ap);
628
629	va_end(ap);
630
631	if (err < 0)
632		(void) no_memory(hdl);
633
634	return (ret);
635}
636
637/*
638 * A safe form of realloc(), which also zeroes newly allocated space.
639 */
640void *
641zfs_realloc(libzfs_handle_t *hdl, void *ptr, size_t oldsize, size_t newsize)
642{
643	void *ret;
644
645	if ((ret = realloc(ptr, newsize)) == NULL) {
646		(void) no_memory(hdl);
647		return (NULL);
648	}
649
650	bzero((char *)ret + oldsize, (newsize - oldsize));
651	return (ret);
652}
653
654/*
655 * A safe form of strdup() which will die if the allocation fails.
656 */
657char *
658zfs_strdup(libzfs_handle_t *hdl, const char *str)
659{
660	char *ret;
661
662	if ((ret = strdup(str)) == NULL)
663		(void) no_memory(hdl);
664
665	return (ret);
666}
667
668void
669libzfs_print_on_error(libzfs_handle_t *hdl, boolean_t printerr)
670{
671	hdl->libzfs_printerr = printerr;
672}
673
674libzfs_handle_t *
675libzfs_init(void)
676{
677	libzfs_handle_t *hdl;
678
679	if ((hdl = calloc(1, sizeof (libzfs_handle_t))) == NULL) {
680		return (NULL);
681	}
682
683	if (regcomp(&hdl->libzfs_urire, URI_REGEX, REG_EXTENDED) != 0) {
684		free(hdl);
685		return (NULL);
686	}
687
688	if ((hdl->libzfs_fd = open(ZFS_DEV, O_RDWR)) < 0) {
689		regfree(&hdl->libzfs_urire);
690		free(hdl);
691		return (NULL);
692	}
693
694	if ((hdl->libzfs_mnttab = fopen(MNTTAB, "rF")) == NULL) {
695		(void) close(hdl->libzfs_fd);
696		regfree(&hdl->libzfs_urire);
697		free(hdl);
698		return (NULL);
699	}
700
701	hdl->libzfs_sharetab = fopen("/etc/dfs/sharetab", "rF");
702
703	if (libzfs_core_init() != 0) {
704		(void) close(hdl->libzfs_fd);
705		(void) fclose(hdl->libzfs_mnttab);
706		(void) fclose(hdl->libzfs_sharetab);
707		regfree(&hdl->libzfs_urire);
708		free(hdl);
709		return (NULL);
710	}
711
712	zfs_prop_init();
713	zpool_prop_init();
714	zpool_feature_init();
715	libzfs_mnttab_init(hdl);
716
717	if (getenv("ZFS_PROP_DEBUG") != NULL) {
718		hdl->libzfs_prop_debug = B_TRUE;
719	}
720
721	return (hdl);
722}
723
724void
725libzfs_fini(libzfs_handle_t *hdl)
726{
727	(void) close(hdl->libzfs_fd);
728	if (hdl->libzfs_mnttab != NULL)
729		(void) fclose(hdl->libzfs_mnttab);
730	if (hdl->libzfs_sharetab != NULL)
731		(void) fclose(hdl->libzfs_sharetab);
732	if (hdl->libzfs_devlink != NULL)
733		(void) di_devlink_fini(&hdl->libzfs_devlink);
734	zfs_uninit_libshare(hdl);
735	zpool_free_handles(hdl);
736	libzfs_fru_clear(hdl, B_TRUE);
737	namespace_clear(hdl);
738	libzfs_mnttab_fini(hdl);
739	libzfs_core_fini();
740	regfree(&hdl->libzfs_urire);
741	free(hdl);
742}
743
744libzfs_handle_t *
745zpool_get_handle(zpool_handle_t *zhp)
746{
747	return (zhp->zpool_hdl);
748}
749
750libzfs_handle_t *
751zfs_get_handle(zfs_handle_t *zhp)
752{
753	return (zhp->zfs_hdl);
754}
755
756zpool_handle_t *
757zfs_get_pool_handle(const zfs_handle_t *zhp)
758{
759	return (zhp->zpool_hdl);
760}
761
762/*
763 * Given a name, determine whether or not it's a valid path
764 * (starts with '/' or "./").  If so, walk the mnttab trying
765 * to match the device number.  If not, treat the path as an
766 * fs/vol/snap/bkmark name.
767 */
768zfs_handle_t *
769zfs_path_to_zhandle(libzfs_handle_t *hdl, char *path, zfs_type_t argtype)
770{
771	struct stat64 statbuf;
772	struct extmnttab entry;
773	int ret;
774
775	if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
776		/*
777		 * It's not a valid path, assume it's a name of type 'argtype'.
778		 */
779		return (zfs_open(hdl, path, argtype));
780	}
781
782	if (stat64(path, &statbuf) != 0) {
783		(void) fprintf(stderr, "%s: %s\n", path, strerror(errno));
784		return (NULL);
785	}
786
787	rewind(hdl->libzfs_mnttab);
788	while ((ret = getextmntent(hdl->libzfs_mnttab, &entry, 0)) == 0) {
789		if (makedevice(entry.mnt_major, entry.mnt_minor) ==
790		    statbuf.st_dev) {
791			break;
792		}
793	}
794	if (ret != 0) {
795		return (NULL);
796	}
797
798	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
799		(void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
800		    path);
801		return (NULL);
802	}
803
804	return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
805}
806
807/*
808 * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
809 * an ioctl().
810 */
811int
812zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
813{
814	if (len == 0)
815		len = 16 * 1024;
816	zc->zc_nvlist_dst_size = len;
817	zc->zc_nvlist_dst =
818	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
819	if (zc->zc_nvlist_dst == 0)
820		return (-1);
821
822	return (0);
823}
824
825/*
826 * Called when an ioctl() which returns an nvlist fails with ENOMEM.  This will
827 * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
828 * filled in by the kernel to indicate the actual required size.
829 */
830int
831zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
832{
833	free((void *)(uintptr_t)zc->zc_nvlist_dst);
834	zc->zc_nvlist_dst =
835	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
836	if (zc->zc_nvlist_dst == 0)
837		return (-1);
838
839	return (0);
840}
841
842/*
843 * Called to free the src and dst nvlists stored in the command structure.
844 */
845void
846zcmd_free_nvlists(zfs_cmd_t *zc)
847{
848	free((void *)(uintptr_t)zc->zc_nvlist_conf);
849	free((void *)(uintptr_t)zc->zc_nvlist_src);
850	free((void *)(uintptr_t)zc->zc_nvlist_dst);
851	zc->zc_nvlist_conf = 0;
852	zc->zc_nvlist_src = 0;
853	zc->zc_nvlist_dst = 0;
854}
855
856static int
857zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
858    nvlist_t *nvl)
859{
860	char *packed;
861	size_t len;
862
863	verify(nvlist_size(nvl, &len, NV_ENCODE_NATIVE) == 0);
864
865	if ((packed = zfs_alloc(hdl, len)) == NULL)
866		return (-1);
867
868	verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
869
870	*outnv = (uint64_t)(uintptr_t)packed;
871	*outlen = len;
872
873	return (0);
874}
875
876int
877zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
878{
879	return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
880	    &zc->zc_nvlist_conf_size, nvl));
881}
882
883int
884zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
885{
886	return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
887	    &zc->zc_nvlist_src_size, nvl));
888}
889
890/*
891 * Unpacks an nvlist from the ZFS ioctl command structure.
892 */
893int
894zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
895{
896	if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
897	    zc->zc_nvlist_dst_size, nvlp, 0) != 0)
898		return (no_memory(hdl));
899
900	return (0);
901}
902
903int
904zfs_ioctl(libzfs_handle_t *hdl, int request, zfs_cmd_t *zc)
905{
906	return (ioctl(hdl->libzfs_fd, request, zc));
907}
908
909/*
910 * ================================================================
911 * API shared by zfs and zpool property management
912 * ================================================================
913 */
914
915static void
916zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
917{
918	zprop_list_t *pl = cbp->cb_proplist;
919	int i;
920	char *title;
921	size_t len;
922
923	cbp->cb_first = B_FALSE;
924	if (cbp->cb_scripted)
925		return;
926
927	/*
928	 * Start with the length of the column headers.
929	 */
930	cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
931	cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
932	    "PROPERTY"));
933	cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
934	    "VALUE"));
935	cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
936	    "RECEIVED"));
937	cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
938	    "SOURCE"));
939
940	/* first property is always NAME */
941	assert(cbp->cb_proplist->pl_prop ==
942	    ((type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME : ZFS_PROP_NAME));
943
944	/*
945	 * Go through and calculate the widths for each column.  For the
946	 * 'source' column, we kludge it up by taking the worst-case scenario of
947	 * inheriting from the longest name.  This is acceptable because in the
948	 * majority of cases 'SOURCE' is the last column displayed, and we don't
949	 * use the width anyway.  Note that the 'VALUE' column can be oversized,
950	 * if the name of the property is much longer than any values we find.
951	 */
952	for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
953		/*
954		 * 'PROPERTY' column
955		 */
956		if (pl->pl_prop != ZPROP_INVAL) {
957			const char *propname = (type == ZFS_TYPE_POOL) ?
958			    zpool_prop_to_name(pl->pl_prop) :
959			    zfs_prop_to_name(pl->pl_prop);
960
961			len = strlen(propname);
962			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
963				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
964		} else {
965			len = strlen(pl->pl_user_prop);
966			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
967				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
968		}
969
970		/*
971		 * 'VALUE' column.  The first property is always the 'name'
972		 * property that was tacked on either by /sbin/zfs's
973		 * zfs_do_get() or when calling zprop_expand_list(), so we
974		 * ignore its width.  If the user specified the name property
975		 * to display, then it will be later in the list in any case.
976		 */
977		if (pl != cbp->cb_proplist &&
978		    pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
979			cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
980
981		/* 'RECEIVED' column. */
982		if (pl != cbp->cb_proplist &&
983		    pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
984			cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
985
986		/*
987		 * 'NAME' and 'SOURCE' columns
988		 */
989		if (pl->pl_prop == (type == ZFS_TYPE_POOL ? ZPOOL_PROP_NAME :
990		    ZFS_PROP_NAME) &&
991		    pl->pl_width > cbp->cb_colwidths[GET_COL_NAME]) {
992			cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
993			cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
994			    strlen(dgettext(TEXT_DOMAIN, "inherited from"));
995		}
996	}
997
998	/*
999	 * Now go through and print the headers.
1000	 */
1001	for (i = 0; i < ZFS_GET_NCOLS; i++) {
1002		switch (cbp->cb_columns[i]) {
1003		case GET_COL_NAME:
1004			title = dgettext(TEXT_DOMAIN, "NAME");
1005			break;
1006		case GET_COL_PROPERTY:
1007			title = dgettext(TEXT_DOMAIN, "PROPERTY");
1008			break;
1009		case GET_COL_VALUE:
1010			title = dgettext(TEXT_DOMAIN, "VALUE");
1011			break;
1012		case GET_COL_RECVD:
1013			title = dgettext(TEXT_DOMAIN, "RECEIVED");
1014			break;
1015		case GET_COL_SOURCE:
1016			title = dgettext(TEXT_DOMAIN, "SOURCE");
1017			break;
1018		default:
1019			title = NULL;
1020		}
1021
1022		if (title != NULL) {
1023			if (i == (ZFS_GET_NCOLS - 1) ||
1024			    cbp->cb_columns[i + 1] == GET_COL_NONE)
1025				(void) printf("%s", title);
1026			else
1027				(void) printf("%-*s  ",
1028				    cbp->cb_colwidths[cbp->cb_columns[i]],
1029				    title);
1030		}
1031	}
1032	(void) printf("\n");
1033}
1034
1035/*
1036 * Display a single line of output, according to the settings in the callback
1037 * structure.
1038 */
1039void
1040zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
1041    const char *propname, const char *value, zprop_source_t sourcetype,
1042    const char *source, const char *recvd_value)
1043{
1044	int i;
1045	const char *str = NULL;
1046	char buf[128];
1047
1048	/*
1049	 * Ignore those source types that the user has chosen to ignore.
1050	 */
1051	if ((sourcetype & cbp->cb_sources) == 0)
1052		return;
1053
1054	if (cbp->cb_first)
1055		zprop_print_headers(cbp, cbp->cb_type);
1056
1057	for (i = 0; i < ZFS_GET_NCOLS; i++) {
1058		switch (cbp->cb_columns[i]) {
1059		case GET_COL_NAME:
1060			str = name;
1061			break;
1062
1063		case GET_COL_PROPERTY:
1064			str = propname;
1065			break;
1066
1067		case GET_COL_VALUE:
1068			str = value;
1069			break;
1070
1071		case GET_COL_SOURCE:
1072			switch (sourcetype) {
1073			case ZPROP_SRC_NONE:
1074				str = "-";
1075				break;
1076
1077			case ZPROP_SRC_DEFAULT:
1078				str = "default";
1079				break;
1080
1081			case ZPROP_SRC_LOCAL:
1082				str = "local";
1083				break;
1084
1085			case ZPROP_SRC_TEMPORARY:
1086				str = "temporary";
1087				break;
1088
1089			case ZPROP_SRC_INHERITED:
1090				(void) snprintf(buf, sizeof (buf),
1091				    "inherited from %s", source);
1092				str = buf;
1093				break;
1094			case ZPROP_SRC_RECEIVED:
1095				str = "received";
1096				break;
1097
1098			default:
1099				str = NULL;
1100				assert(!"unhandled zprop_source_t");
1101			}
1102			break;
1103
1104		case GET_COL_RECVD:
1105			str = (recvd_value == NULL ? "-" : recvd_value);
1106			break;
1107
1108		default:
1109			continue;
1110		}
1111
1112		if (cbp->cb_columns[i + 1] == GET_COL_NONE)
1113			(void) printf("%s", str);
1114		else if (cbp->cb_scripted)
1115			(void) printf("%s\t", str);
1116		else
1117			(void) printf("%-*s  ",
1118			    cbp->cb_colwidths[cbp->cb_columns[i]],
1119			    str);
1120	}
1121
1122	(void) printf("\n");
1123}
1124
1125/*
1126 * Given a numeric suffix, convert the value into a number of bits that the
1127 * resulting value must be shifted.
1128 */
1129static int
1130str2shift(libzfs_handle_t *hdl, const char *buf)
1131{
1132	const char *ends = "BKMGTPEZ";
1133	int i;
1134
1135	if (buf[0] == '\0')
1136		return (0);
1137	for (i = 0; i < strlen(ends); i++) {
1138		if (toupper(buf[0]) == ends[i])
1139			break;
1140	}
1141	if (i == strlen(ends)) {
1142		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1143		    "invalid numeric suffix '%s'"), buf);
1144		return (-1);
1145	}
1146
1147	/*
1148	 * We want to allow trailing 'b' characters for 'GB' or 'Mb'.  But don't
1149	 * allow 'BB' - that's just weird.
1150	 */
1151	if (buf[1] == '\0' || (toupper(buf[1]) == 'B' && buf[2] == '\0' &&
1152	    toupper(buf[0]) != 'B'))
1153		return (10*i);
1154
1155	zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1156	    "invalid numeric suffix '%s'"), buf);
1157	return (-1);
1158}
1159
1160/*
1161 * Convert a string of the form '100G' into a real number.  Used when setting
1162 * properties or creating a volume.  'buf' is used to place an extended error
1163 * message for the caller to use.
1164 */
1165int
1166zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1167{
1168	char *end;
1169	int shift;
1170
1171	*num = 0;
1172
1173	/* Check to see if this looks like a number.  */
1174	if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1175		if (hdl)
1176			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1177			    "bad numeric value '%s'"), value);
1178		return (-1);
1179	}
1180
1181	/* Rely on strtoull() to process the numeric portion.  */
1182	errno = 0;
1183	*num = strtoull(value, &end, 10);
1184
1185	/*
1186	 * Check for ERANGE, which indicates that the value is too large to fit
1187	 * in a 64-bit value.
1188	 */
1189	if (errno == ERANGE) {
1190		if (hdl)
1191			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1192			    "numeric value is too large"));
1193		return (-1);
1194	}
1195
1196	/*
1197	 * If we have a decimal value, then do the computation with floating
1198	 * point arithmetic.  Otherwise, use standard arithmetic.
1199	 */
1200	if (*end == '.') {
1201		double fval = strtod(value, &end);
1202
1203		if ((shift = str2shift(hdl, end)) == -1)
1204			return (-1);
1205
1206		fval *= pow(2, shift);
1207
1208		if (fval > UINT64_MAX) {
1209			if (hdl)
1210				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1211				    "numeric value is too large"));
1212			return (-1);
1213		}
1214
1215		*num = (uint64_t)fval;
1216	} else {
1217		if ((shift = str2shift(hdl, end)) == -1)
1218			return (-1);
1219
1220		/* Check for overflow */
1221		if (shift >= 64 || (*num << shift) >> shift != *num) {
1222			if (hdl)
1223				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1224				    "numeric value is too large"));
1225			return (-1);
1226		}
1227
1228		*num <<= shift;
1229	}
1230
1231	return (0);
1232}
1233
1234/*
1235 * Given a propname=value nvpair to set, parse any numeric properties
1236 * (index, boolean, etc) if they are specified as strings and add the
1237 * resulting nvpair to the returned nvlist.
1238 *
1239 * At the DSL layer, all properties are either 64-bit numbers or strings.
1240 * We want the user to be able to ignore this fact and specify properties
1241 * as native values (numbers, for example) or as strings (to simplify
1242 * command line utilities).  This also handles converting index types
1243 * (compression, checksum, etc) from strings to their on-disk index.
1244 */
1245int
1246zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1247    zfs_type_t type, nvlist_t *ret, char **svalp, uint64_t *ivalp,
1248    const char *errbuf)
1249{
1250	data_type_t datatype = nvpair_type(elem);
1251	zprop_type_t proptype;
1252	const char *propname;
1253	char *value;
1254	boolean_t isnone = B_FALSE;
1255	boolean_t isauto = B_FALSE;
1256
1257	if (type == ZFS_TYPE_POOL) {
1258		proptype = zpool_prop_get_type(prop);
1259		propname = zpool_prop_to_name(prop);
1260	} else {
1261		proptype = zfs_prop_get_type(prop);
1262		propname = zfs_prop_to_name(prop);
1263	}
1264
1265	/*
1266	 * Convert any properties to the internal DSL value types.
1267	 */
1268	*svalp = NULL;
1269	*ivalp = 0;
1270
1271	switch (proptype) {
1272	case PROP_TYPE_STRING:
1273		if (datatype != DATA_TYPE_STRING) {
1274			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1275			    "'%s' must be a string"), nvpair_name(elem));
1276			goto error;
1277		}
1278		(void) nvpair_value_string(elem, svalp);
1279		if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1280			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1281			    "'%s' is too long"), nvpair_name(elem));
1282			goto error;
1283		}
1284		break;
1285
1286	case PROP_TYPE_NUMBER:
1287		if (datatype == DATA_TYPE_STRING) {
1288			(void) nvpair_value_string(elem, &value);
1289			if (strcmp(value, "none") == 0) {
1290				isnone = B_TRUE;
1291			} else if (strcmp(value, "auto") == 0) {
1292				isauto = B_TRUE;
1293			} else if (zfs_nicestrtonum(hdl, value, ivalp) != 0) {
1294				goto error;
1295			}
1296		} else if (datatype == DATA_TYPE_UINT64) {
1297			(void) nvpair_value_uint64(elem, ivalp);
1298		} else {
1299			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1300			    "'%s' must be a number"), nvpair_name(elem));
1301			goto error;
1302		}
1303
1304		/*
1305		 * Quota special: force 'none' and don't allow 0.
1306		 */
1307		if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1308		    (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1309			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1310			    "use 'none' to disable quota/refquota"));
1311			goto error;
1312		}
1313
1314		/*
1315		 * Special handling for "*_limit=none". In this case it's not
1316		 * 0 but UINT64_MAX.
1317		 */
1318		if ((type & ZFS_TYPE_DATASET) && isnone &&
1319		    (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1320		    prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1321			*ivalp = UINT64_MAX;
1322		}
1323
1324		/*
1325		 * Special handling for setting 'refreservation' to 'auto'.  Use
1326		 * UINT64_MAX to tell the caller to use zfs_fix_auto_resv().
1327		 * 'auto' is only allowed on volumes.
1328		 */
1329		if (isauto) {
1330			switch (prop) {
1331			case ZFS_PROP_REFRESERVATION:
1332				if ((type & ZFS_TYPE_VOLUME) == 0) {
1333					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1334					    "'%s=auto' only allowed on "
1335					    "volumes"), nvpair_name(elem));
1336					goto error;
1337				}
1338				*ivalp = UINT64_MAX;
1339				break;
1340			default:
1341				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1342				    "'auto' is invalid value for '%s'"),
1343				    nvpair_name(elem));
1344				goto error;
1345			}
1346		}
1347
1348		break;
1349
1350	case PROP_TYPE_INDEX:
1351		if (datatype != DATA_TYPE_STRING) {
1352			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1353			    "'%s' must be a string"), nvpair_name(elem));
1354			goto error;
1355		}
1356
1357		(void) nvpair_value_string(elem, &value);
1358
1359		if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1360			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1361			    "'%s' must be one of '%s'"), propname,
1362			    zprop_values(prop, type));
1363			goto error;
1364		}
1365		break;
1366
1367	default:
1368		abort();
1369	}
1370
1371	/*
1372	 * Add the result to our return set of properties.
1373	 */
1374	if (*svalp != NULL) {
1375		if (nvlist_add_string(ret, propname, *svalp) != 0) {
1376			(void) no_memory(hdl);
1377			return (-1);
1378		}
1379	} else {
1380		if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1381			(void) no_memory(hdl);
1382			return (-1);
1383		}
1384	}
1385
1386	return (0);
1387error:
1388	(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1389	return (-1);
1390}
1391
1392static int
1393addlist(libzfs_handle_t *hdl, char *propname, zprop_list_t **listp,
1394    zfs_type_t type)
1395{
1396	int prop;
1397	zprop_list_t *entry;
1398
1399	prop = zprop_name_to_prop(propname, type);
1400
1401	if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type))
1402		prop = ZPROP_INVAL;
1403
1404	/*
1405	 * When no property table entry can be found, return failure if
1406	 * this is a pool property or if this isn't a user-defined
1407	 * dataset property,
1408	 */
1409	if (prop == ZPROP_INVAL && ((type == ZFS_TYPE_POOL &&
1410	    !zpool_prop_feature(propname) &&
1411	    !zpool_prop_unsupported(propname)) ||
1412	    (type == ZFS_TYPE_DATASET && !zfs_prop_user(propname) &&
1413	    !zfs_prop_userquota(propname) && !zfs_prop_written(propname)))) {
1414		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1415		    "invalid property '%s'"), propname);
1416		return (zfs_error(hdl, EZFS_BADPROP,
1417		    dgettext(TEXT_DOMAIN, "bad property list")));
1418	}
1419
1420	if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1421		return (-1);
1422
1423	entry->pl_prop = prop;
1424	if (prop == ZPROP_INVAL) {
1425		if ((entry->pl_user_prop = zfs_strdup(hdl, propname)) ==
1426		    NULL) {
1427			free(entry);
1428			return (-1);
1429		}
1430		entry->pl_width = strlen(propname);
1431	} else {
1432		entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1433		    type);
1434	}
1435
1436	*listp = entry;
1437
1438	return (0);
1439}
1440
1441/*
1442 * Given a comma-separated list of properties, construct a property list
1443 * containing both user-defined and native properties.  This function will
1444 * return a NULL list if 'all' is specified, which can later be expanded
1445 * by zprop_expand_list().
1446 */
1447int
1448zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1449    zfs_type_t type)
1450{
1451	*listp = NULL;
1452
1453	/*
1454	 * If 'all' is specified, return a NULL list.
1455	 */
1456	if (strcmp(props, "all") == 0)
1457		return (0);
1458
1459	/*
1460	 * If no props were specified, return an error.
1461	 */
1462	if (props[0] == '\0') {
1463		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1464		    "no properties specified"));
1465		return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
1466		    "bad property list")));
1467	}
1468
1469	/*
1470	 * It would be nice to use getsubopt() here, but the inclusion of column
1471	 * aliases makes this more effort than it's worth.
1472	 */
1473	while (*props != '\0') {
1474		size_t len;
1475		char *p;
1476		char c;
1477
1478		if ((p = strchr(props, ',')) == NULL) {
1479			len = strlen(props);
1480			p = props + len;
1481		} else {
1482			len = p - props;
1483		}
1484
1485		/*
1486		 * Check for empty options.
1487		 */
1488		if (len == 0) {
1489			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1490			    "empty property name"));
1491			return (zfs_error(hdl, EZFS_BADPROP,
1492			    dgettext(TEXT_DOMAIN, "bad property list")));
1493		}
1494
1495		/*
1496		 * Check all regular property names.
1497		 */
1498		c = props[len];
1499		props[len] = '\0';
1500
1501		if (strcmp(props, "space") == 0) {
1502			static char *spaceprops[] = {
1503				"name", "avail", "used", "usedbysnapshots",
1504				"usedbydataset", "usedbyrefreservation",
1505				"usedbychildren", NULL
1506			};
1507			int i;
1508
1509			for (i = 0; spaceprops[i]; i++) {
1510				if (addlist(hdl, spaceprops[i], listp, type))
1511					return (-1);
1512				listp = &(*listp)->pl_next;
1513			}
1514		} else {
1515			if (addlist(hdl, props, listp, type))
1516				return (-1);
1517			listp = &(*listp)->pl_next;
1518		}
1519
1520		props = p;
1521		if (c == ',')
1522			props++;
1523	}
1524
1525	return (0);
1526}
1527
1528void
1529zprop_free_list(zprop_list_t *pl)
1530{
1531	zprop_list_t *next;
1532
1533	while (pl != NULL) {
1534		next = pl->pl_next;
1535		free(pl->pl_user_prop);
1536		free(pl);
1537		pl = next;
1538	}
1539}
1540
1541typedef struct expand_data {
1542	zprop_list_t	**last;
1543	libzfs_handle_t	*hdl;
1544	zfs_type_t type;
1545} expand_data_t;
1546
1547int
1548zprop_expand_list_cb(int prop, void *cb)
1549{
1550	zprop_list_t *entry;
1551	expand_data_t *edp = cb;
1552
1553	if ((entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t))) == NULL)
1554		return (ZPROP_INVAL);
1555
1556	entry->pl_prop = prop;
1557	entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
1558	entry->pl_all = B_TRUE;
1559
1560	*(edp->last) = entry;
1561	edp->last = &entry->pl_next;
1562
1563	return (ZPROP_CONT);
1564}
1565
1566int
1567zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
1568{
1569	zprop_list_t *entry;
1570	zprop_list_t **last;
1571	expand_data_t exp;
1572
1573	if (*plp == NULL) {
1574		/*
1575		 * If this is the very first time we've been called for an 'all'
1576		 * specification, expand the list to include all native
1577		 * properties.
1578		 */
1579		last = plp;
1580
1581		exp.last = last;
1582		exp.hdl = hdl;
1583		exp.type = type;
1584
1585		if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
1586		    B_FALSE, type) == ZPROP_INVAL)
1587			return (-1);
1588
1589		/*
1590		 * Add 'name' to the beginning of the list, which is handled
1591		 * specially.
1592		 */
1593		if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1594			return (-1);
1595
1596		entry->pl_prop = (type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME :
1597		    ZFS_PROP_NAME;
1598		entry->pl_width = zprop_width(entry->pl_prop,
1599		    &entry->pl_fixed, type);
1600		entry->pl_all = B_TRUE;
1601		entry->pl_next = *plp;
1602		*plp = entry;
1603	}
1604	return (0);
1605}
1606
1607int
1608zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
1609    zfs_type_t type)
1610{
1611	return (zprop_iter_common(func, cb, show_all, ordered, type));
1612}
1613
1614/*
1615 * zfs_get_hole_count retrieves the number of holes (blocks which are
1616 * zero-filled) in the specified file using the _FIO_COUNT_FILLED ioctl. It
1617 * also optionally fetches the block size when bs is non-NULL. With hole count
1618 * and block size the full space consumed by the holes of a file can be
1619 * calculated.
1620 *
1621 * On success, zero is returned, the count argument is set to the
1622 * number of holes, and the bs argument is set to the block size (if it is
1623 * not NULL). On error, a non-zero errno is returned and the values in count
1624 * and bs are undefined.
1625 */
1626int
1627zfs_get_hole_count(const char *path, uint64_t *count, uint64_t *bs)
1628{
1629	int fd, err;
1630	struct stat64 ss;
1631	uint64_t fill;
1632
1633	fd = open(path, O_RDONLY | O_LARGEFILE);
1634	if (fd == -1)
1635		return (errno);
1636
1637	if (ioctl(fd, _FIO_COUNT_FILLED, &fill) == -1) {
1638		err = errno;
1639		(void) close(fd);
1640		return (err);
1641	}
1642
1643	if (fstat64(fd, &ss) == -1) {
1644		err = errno;
1645		(void) close(fd);
1646		return (err);
1647	}
1648
1649	*count = (ss.st_size + ss.st_blksize - 1) / ss.st_blksize - fill;
1650	VERIFY3S(*count, >=, 0);
1651	if (bs != NULL) {
1652		*bs = ss.st_blksize;
1653	}
1654
1655	if (close(fd) == -1) {
1656		return (errno);
1657	}
1658	return (0);
1659}
1660