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