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