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