]> git.proxmox.com Git - mirror_zfs.git/blame - lib/libzfs/libzfs_util.c
Add zfs_prepare_disk script for disk firmware install
[mirror_zfs.git] / lib / libzfs / libzfs_util.c
CommitLineData
34dc7c2f
BB
1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
1d3ba0bf 9 * or https://opensource.org/licenses/CDDL-1.0.
34dc7c2f
BB
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
9ae529ec 21
34dc7c2f 22/*
428870ff 23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
c14ca145 24 * Copyright 2020 Joyent, Inc. All rights reserved.
c15d36c6 25 * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
23d70cde 26 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
0ea05c64 27 * Copyright (c) 2017 Datto Inc.
8fb79fdd
AJ
28 * Copyright (c) 2020 The FreeBSD Foundation
29 *
30 * Portions of this software were developed by Allan Jude
31 * under sponsorship from the FreeBSD Foundation.
34dc7c2f
BB
32 */
33
34dc7c2f
BB
34/*
35 * Internal utility routines for the ZFS library.
36 */
37
38#include <errno.h>
39#include <fcntl.h>
40#include <libintl.h>
41#include <stdarg.h>
42#include <stdio.h>
43#include <stdlib.h>
44#include <strings.h>
45#include <unistd.h>
34dc7c2f 46#include <math.h>
37086897
AZ
47#if LIBFETCH_DYNAMIC
48#include <dlfcn.h>
49#endif
d603ed6c 50#include <sys/stat.h>
34dc7c2f
BB
51#include <sys/mnttab.h>
52#include <sys/mntent.h>
53#include <sys/types.h>
120ff39a 54#include <sys/wait.h>
34dc7c2f
BB
55
56#include <libzfs.h>
6f1ffb06 57#include <libzfs_core.h>
34dc7c2f
BB
58
59#include "libzfs_impl.h"
60#include "zfs_prop.h"
9ae529ec 61#include "zfeature_common.h"
dc03fa30 62#include <zfs_fletcher.h>
e89f1295 63#include <libzutil.h>
34dc7c2f 64
c14ca145
JK
65/*
66 * We only care about the scheme in order to match the scheme
67 * with the handler. Each handler should validate the full URI
68 * as necessary.
69 */
70#define URI_REGEX "^\\([A-Za-z][A-Za-z0-9+.\\-]*\\):"
73cdcc63 71
34dc7c2f
BB
72int
73libzfs_errno(libzfs_handle_t *hdl)
74{
75 return (hdl->libzfs_error);
76}
77
78const char *
79libzfs_error_action(libzfs_handle_t *hdl)
80{
81 return (hdl->libzfs_action);
82}
83
84const char *
85libzfs_error_description(libzfs_handle_t *hdl)
86{
87 if (hdl->libzfs_desc[0] != '\0')
88 return (hdl->libzfs_desc);
89
90 switch (hdl->libzfs_error) {
91 case EZFS_NOMEM:
92 return (dgettext(TEXT_DOMAIN, "out of memory"));
93 case EZFS_BADPROP:
94 return (dgettext(TEXT_DOMAIN, "invalid property value"));
95 case EZFS_PROPREADONLY:
572e2857 96 return (dgettext(TEXT_DOMAIN, "read-only property"));
34dc7c2f
BB
97 case EZFS_PROPTYPE:
98 return (dgettext(TEXT_DOMAIN, "property doesn't apply to "
99 "datasets of this type"));
100 case EZFS_PROPNONINHERIT:
101 return (dgettext(TEXT_DOMAIN, "property cannot be inherited"));
102 case EZFS_PROPSPACE:
103 return (dgettext(TEXT_DOMAIN, "invalid quota or reservation"));
104 case EZFS_BADTYPE:
105 return (dgettext(TEXT_DOMAIN, "operation not applicable to "
106 "datasets of this type"));
107 case EZFS_BUSY:
108 return (dgettext(TEXT_DOMAIN, "pool or dataset is busy"));
109 case EZFS_EXISTS:
110 return (dgettext(TEXT_DOMAIN, "pool or dataset exists"));
111 case EZFS_NOENT:
112 return (dgettext(TEXT_DOMAIN, "no such pool or dataset"));
113 case EZFS_BADSTREAM:
114 return (dgettext(TEXT_DOMAIN, "invalid backup stream"));
115 case EZFS_DSREADONLY:
572e2857 116 return (dgettext(TEXT_DOMAIN, "dataset is read-only"));
34dc7c2f
BB
117 case EZFS_VOLTOOBIG:
118 return (dgettext(TEXT_DOMAIN, "volume size exceeds limit for "
119 "this system"));
34dc7c2f
BB
120 case EZFS_INVALIDNAME:
121 return (dgettext(TEXT_DOMAIN, "invalid name"));
122 case EZFS_BADRESTORE:
123 return (dgettext(TEXT_DOMAIN, "unable to restore to "
124 "destination"));
125 case EZFS_BADBACKUP:
126 return (dgettext(TEXT_DOMAIN, "backup failed"));
127 case EZFS_BADTARGET:
128 return (dgettext(TEXT_DOMAIN, "invalid target vdev"));
129 case EZFS_NODEVICE:
130 return (dgettext(TEXT_DOMAIN, "no such device in pool"));
131 case EZFS_BADDEV:
132 return (dgettext(TEXT_DOMAIN, "invalid device"));
133 case EZFS_NOREPLICAS:
134 return (dgettext(TEXT_DOMAIN, "no valid replicas"));
135 case EZFS_RESILVERING:
136 return (dgettext(TEXT_DOMAIN, "currently resilvering"));
137 case EZFS_BADVERSION:
9ae529ec
CS
138 return (dgettext(TEXT_DOMAIN, "unsupported version or "
139 "feature"));
34dc7c2f
BB
140 case EZFS_POOLUNAVAIL:
141 return (dgettext(TEXT_DOMAIN, "pool is unavailable"));
142 case EZFS_DEVOVERFLOW:
143 return (dgettext(TEXT_DOMAIN, "too many devices in one vdev"));
144 case EZFS_BADPATH:
145 return (dgettext(TEXT_DOMAIN, "must be an absolute path"));
146 case EZFS_CROSSTARGET:
147 return (dgettext(TEXT_DOMAIN, "operation crosses datasets or "
148 "pools"));
149 case EZFS_ZONED:
150 return (dgettext(TEXT_DOMAIN, "dataset in use by local zone"));
151 case EZFS_MOUNTFAILED:
152 return (dgettext(TEXT_DOMAIN, "mount failed"));
153 case EZFS_UMOUNTFAILED:
76d04993 154 return (dgettext(TEXT_DOMAIN, "unmount failed"));
34dc7c2f 155 case EZFS_UNSHARENFSFAILED:
76d04993 156 return (dgettext(TEXT_DOMAIN, "NFS share removal failed"));
34dc7c2f 157 case EZFS_SHARENFSFAILED:
76d04993 158 return (dgettext(TEXT_DOMAIN, "NFS share creation failed"));
34dc7c2f 159 case EZFS_UNSHARESMBFAILED:
76d04993 160 return (dgettext(TEXT_DOMAIN, "SMB share removal failed"));
34dc7c2f 161 case EZFS_SHARESMBFAILED:
76d04993 162 return (dgettext(TEXT_DOMAIN, "SMB share creation failed"));
34dc7c2f
BB
163 case EZFS_PERM:
164 return (dgettext(TEXT_DOMAIN, "permission denied"));
165 case EZFS_NOSPC:
166 return (dgettext(TEXT_DOMAIN, "out of space"));
428870ff
BB
167 case EZFS_FAULT:
168 return (dgettext(TEXT_DOMAIN, "bad address"));
34dc7c2f
BB
169 case EZFS_IO:
170 return (dgettext(TEXT_DOMAIN, "I/O error"));
171 case EZFS_INTR:
172 return (dgettext(TEXT_DOMAIN, "signal received"));
6c8e9f09
AZ
173 case EZFS_CKSUM:
174 return (dgettext(TEXT_DOMAIN, "insufficient replicas"));
34dc7c2f
BB
175 case EZFS_ISSPARE:
176 return (dgettext(TEXT_DOMAIN, "device is reserved as a hot "
177 "spare"));
178 case EZFS_INVALCONFIG:
179 return (dgettext(TEXT_DOMAIN, "invalid vdev configuration"));
180 case EZFS_RECURSIVE:
181 return (dgettext(TEXT_DOMAIN, "recursive dataset dependency"));
182 case EZFS_NOHISTORY:
183 return (dgettext(TEXT_DOMAIN, "no history available"));
34dc7c2f
BB
184 case EZFS_POOLPROPS:
185 return (dgettext(TEXT_DOMAIN, "failed to retrieve "
186 "pool properties"));
187 case EZFS_POOL_NOTSUP:
188 return (dgettext(TEXT_DOMAIN, "operation not supported "
189 "on this type of pool"));
190 case EZFS_POOL_INVALARG:
191 return (dgettext(TEXT_DOMAIN, "invalid argument for "
192 "this pool operation"));
193 case EZFS_NAMETOOLONG:
194 return (dgettext(TEXT_DOMAIN, "dataset name is too long"));
195 case EZFS_OPENFAILED:
196 return (dgettext(TEXT_DOMAIN, "open failed"));
197 case EZFS_NOCAP:
198 return (dgettext(TEXT_DOMAIN,
199 "disk capacity information could not be retrieved"));
200 case EZFS_LABELFAILED:
201 return (dgettext(TEXT_DOMAIN, "write of label failed"));
202 case EZFS_BADWHO:
203 return (dgettext(TEXT_DOMAIN, "invalid user/group"));
204 case EZFS_BADPERM:
205 return (dgettext(TEXT_DOMAIN, "invalid permission"));
206 case EZFS_BADPERMSET:
207 return (dgettext(TEXT_DOMAIN, "invalid permission set name"));
208 case EZFS_NODELEGATION:
209 return (dgettext(TEXT_DOMAIN, "delegated administration is "
210 "disabled on pool"));
34dc7c2f
BB
211 case EZFS_BADCACHE:
212 return (dgettext(TEXT_DOMAIN, "invalid or missing cache file"));
213 case EZFS_ISL2CACHE:
214 return (dgettext(TEXT_DOMAIN, "device is in use as a cache"));
215 case EZFS_VDEVNOTSUP:
216 return (dgettext(TEXT_DOMAIN, "vdev specification is not "
217 "supported"));
b128c09f
BB
218 case EZFS_NOTSUP:
219 return (dgettext(TEXT_DOMAIN, "operation not supported "
220 "on this dataset"));
b83a0e2d
DB
221 case EZFS_IOC_NOTSUPPORTED:
222 return (dgettext(TEXT_DOMAIN, "operation not supported by "
223 "zfs kernel module"));
b128c09f
BB
224 case EZFS_ACTIVE_SPARE:
225 return (dgettext(TEXT_DOMAIN, "pool has active shared spare "
226 "device"));
9babb374
BB
227 case EZFS_UNPLAYED_LOGS:
228 return (dgettext(TEXT_DOMAIN, "log device has unplayed intent "
229 "logs"));
45d1cae3
BB
230 case EZFS_REFTAG_RELE:
231 return (dgettext(TEXT_DOMAIN, "no such tag on this dataset"));
232 case EZFS_REFTAG_HOLD:
233 return (dgettext(TEXT_DOMAIN, "tag already exists on this "
234 "dataset"));
428870ff
BB
235 case EZFS_TAGTOOLONG:
236 return (dgettext(TEXT_DOMAIN, "tag too long"));
237 case EZFS_PIPEFAILED:
238 return (dgettext(TEXT_DOMAIN, "pipe create failed"));
239 case EZFS_THREADCREATEFAILED:
240 return (dgettext(TEXT_DOMAIN, "thread create failed"));
241 case EZFS_POSTSPLIT_ONLINE:
242 return (dgettext(TEXT_DOMAIN, "disk was split from this pool "
243 "into a new one"));
0ea05c64
AP
244 case EZFS_SCRUB_PAUSED:
245 return (dgettext(TEXT_DOMAIN, "scrub is paused; "
482eeef8
GA
246 "use 'zpool scrub' to resume scrub"));
247 case EZFS_SCRUB_PAUSED_TO_CANCEL:
248 return (dgettext(TEXT_DOMAIN, "scrub is paused; "
249 "use 'zpool scrub' to resume or 'zpool scrub -s' to "
250 "cancel scrub"));
428870ff
BB
251 case EZFS_SCRUBBING:
252 return (dgettext(TEXT_DOMAIN, "currently scrubbing; "
482eeef8
GA
253 "use 'zpool scrub -s' to cancel scrub"));
254 case EZFS_ERRORSCRUBBING:
255 return (dgettext(TEXT_DOMAIN, "currently error scrubbing; "
256 "use 'zpool scrub -s' to cancel error scrub"));
257 case EZFS_ERRORSCRUB_PAUSED:
258 return (dgettext(TEXT_DOMAIN, "error scrub is paused; "
259 "use 'zpool scrub -e' to resume error scrub"));
428870ff
BB
260 case EZFS_NO_SCRUB:
261 return (dgettext(TEXT_DOMAIN, "there is no active scrub"));
572e2857
BB
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"));
a1d477c2
MA
268 case EZFS_NO_PENDING:
269 return (dgettext(TEXT_DOMAIN, "operation is not "
270 "in progress"));
d2734cce
SD
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"));
379ca9cf
OF
282 case EZFS_ACTIVE_POOL:
283 return (dgettext(TEXT_DOMAIN, "pool is imported on a "
284 "different host"));
b5256303
TC
285 case EZFS_CRYPTOFAILED:
286 return (dgettext(TEXT_DOMAIN, "encryption failure"));
619f0976
GW
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"));
d8d418ff 294 case EZFS_WRONG_PARENT:
295 return (dgettext(TEXT_DOMAIN, "invalid parent dataset"));
1b939560
BB
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"));
fa241660
TC
303 case EZFS_NO_RESILVER_DEFER:
304 return (dgettext(TEXT_DOMAIN, "this action requires the "
305 "resilver_defer feature"));
43a85362
SD
306 case EZFS_EXPORT_IN_PROGRESS:
307 return (dgettext(TEXT_DOMAIN, "pool export in progress"));
9a49d3f3
BB
308 case EZFS_REBUILDING:
309 return (dgettext(TEXT_DOMAIN, "currently sequentially "
310 "resilvering"));
2a673e76
AJ
311 case EZFS_VDEV_NOTSUP:
312 return (dgettext(TEXT_DOMAIN, "operation not supported "
313 "on this type of vdev"));
4ed5e250
WA
314 case EZFS_NOT_USER_NAMESPACE:
315 return (dgettext(TEXT_DOMAIN, "the provided file "
316 "was not a user namespace file"));
3ed9d688
JP
317 case EZFS_RESUME_EXISTS:
318 return (dgettext(TEXT_DOMAIN, "Resuming recv on existing "
319 "dataset without force"));
34dc7c2f
BB
320 case EZFS_UNKNOWN:
321 return (dgettext(TEXT_DOMAIN, "unknown error"));
322 default:
323 assert(hdl->libzfs_error == 0);
324 return (dgettext(TEXT_DOMAIN, "no error"));
325 }
326}
327
34dc7c2f
BB
328void
329zfs_error_aux(libzfs_handle_t *hdl, const char *fmt, ...)
330{
331 va_list ap;
332
333 va_start(ap, fmt);
334
335 (void) vsnprintf(hdl->libzfs_desc, sizeof (hdl->libzfs_desc),
336 fmt, ap);
337 hdl->libzfs_desc_active = 1;
338
339 va_end(ap);
340}
341
342static void
343zfs_verror(libzfs_handle_t *hdl, int error, const char *fmt, va_list ap)
344{
345 (void) vsnprintf(hdl->libzfs_action, sizeof (hdl->libzfs_action),
346 fmt, ap);
347 hdl->libzfs_error = error;
348
349 if (hdl->libzfs_desc_active)
350 hdl->libzfs_desc_active = 0;
351 else
352 hdl->libzfs_desc[0] = '\0';
353
354 if (hdl->libzfs_printerr) {
355 if (error == EZFS_UNKNOWN) {
356 (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "internal "
24f98ed3
AJ
357 "error: %s: %s\n"), hdl->libzfs_action,
358 libzfs_error_description(hdl));
34dc7c2f
BB
359 abort();
360 }
361
362 (void) fprintf(stderr, "%s: %s\n", hdl->libzfs_action,
363 libzfs_error_description(hdl));
364 if (error == EZFS_NOMEM)
365 exit(1);
366 }
367}
368
369int
370zfs_error(libzfs_handle_t *hdl, int error, const char *msg)
371{
372 return (zfs_error_fmt(hdl, error, "%s", msg));
373}
374
34dc7c2f
BB
375int
376zfs_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
377{
378 va_list ap;
379
380 va_start(ap, fmt);
381
382 zfs_verror(hdl, error, fmt, ap);
383
384 va_end(ap);
385
386 return (-1);
387}
388
389static int
390zfs_common_error(libzfs_handle_t *hdl, int error, const char *fmt,
391 va_list ap)
392{
393 switch (error) {
394 case EPERM:
395 case EACCES:
396 zfs_verror(hdl, EZFS_PERM, fmt, ap);
397 return (-1);
398
399 case ECANCELED:
400 zfs_verror(hdl, EZFS_NODELEGATION, fmt, ap);
401 return (-1);
402
403 case EIO:
404 zfs_verror(hdl, EZFS_IO, fmt, ap);
405 return (-1);
406
428870ff
BB
407 case EFAULT:
408 zfs_verror(hdl, EZFS_FAULT, fmt, ap);
409 return (-1);
410
34dc7c2f
BB
411 case EINTR:
412 zfs_verror(hdl, EZFS_INTR, fmt, ap);
413 return (-1);
6c8e9f09
AZ
414
415 case ECKSUM:
416 zfs_verror(hdl, EZFS_CKSUM, fmt, ap);
417 return (-1);
34dc7c2f
BB
418 }
419
420 return (0);
421}
422
423int
424zfs_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
425{
426 return (zfs_standard_error_fmt(hdl, error, "%s", msg));
427}
428
34dc7c2f
BB
429int
430zfs_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
431{
432 va_list ap;
433
434 va_start(ap, fmt);
435
436 if (zfs_common_error(hdl, error, fmt, ap) != 0) {
437 va_end(ap);
438 return (-1);
439 }
440
441 switch (error) {
442 case ENXIO:
443 case ENODEV:
330d06f9 444 case EPIPE:
34dc7c2f
BB
445 zfs_verror(hdl, EZFS_IO, fmt, ap);
446 break;
447
448 case ENOENT:
449 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
450 "dataset does not exist"));
451 zfs_verror(hdl, EZFS_NOENT, fmt, ap);
452 break;
453
454 case ENOSPC:
455 case EDQUOT:
456 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
b264d9b3 457 break;
34dc7c2f
BB
458
459 case EEXIST:
460 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
461 "dataset already exists"));
462 zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
463 break;
464
465 case EBUSY:
466 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
467 "dataset is busy"));
468 zfs_verror(hdl, EZFS_BUSY, fmt, ap);
469 break;
470 case EROFS:
572e2857 471 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
34dc7c2f
BB
472 break;
473 case ENAMETOOLONG:
474 zfs_verror(hdl, EZFS_NAMETOOLONG, fmt, ap);
475 break;
476 case ENOTSUP:
477 zfs_verror(hdl, EZFS_BADVERSION, fmt, ap);
478 break;
9babb374
BB
479 case EAGAIN:
480 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
481 "pool I/O is currently suspended"));
482 zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
483 break;
379ca9cf
OF
484 case EREMOTEIO:
485 zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
486 break;
30af21b0 487 case ZFS_ERR_UNKNOWN_SEND_STREAM_FEATURE:
b83a0e2d
DB
488 case ZFS_ERR_IOC_CMD_UNAVAIL:
489 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
490 "module does not support this operation. A reboot may "
491 "be required to enable this operation."));
492 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
493 break;
494 case ZFS_ERR_IOC_ARG_UNAVAIL:
495 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
496 "module does not support an option for this operation. "
497 "A reboot may be required to enable this option."));
498 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
499 break;
500 case ZFS_ERR_IOC_ARG_REQUIRED:
501 case ZFS_ERR_IOC_ARG_BADTYPE:
502 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
503 break;
d8d418ff 504 case ZFS_ERR_WRONG_PARENT:
505 zfs_verror(hdl, EZFS_WRONG_PARENT, fmt, ap);
506 break;
8fb79fdd
AJ
507 case ZFS_ERR_BADPROP:
508 zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
509 break;
4ed5e250
WA
510 case ZFS_ERR_NOT_USER_NAMESPACE:
511 zfs_verror(hdl, EZFS_NOT_USER_NAMESPACE, fmt, ap);
512 break;
34dc7c2f 513 default:
f00f4690 514 zfs_error_aux(hdl, "%s", strerror(error));
34dc7c2f
BB
515 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
516 break;
517 }
518
519 va_end(ap);
520 return (-1);
521}
522
0ce2de63
AS
523void
524zfs_setprop_error(libzfs_handle_t *hdl, zfs_prop_t prop, int err,
525 char *errbuf)
526{
527 switch (err) {
528
529 case ENOSPC:
530 /*
531 * For quotas and reservations, ENOSPC indicates
532 * something different; setting a quota or reservation
533 * doesn't use any disk space.
534 */
535 switch (prop) {
536 case ZFS_PROP_QUOTA:
537 case ZFS_PROP_REFQUOTA:
538 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
539 "size is less than current used or "
540 "reserved space"));
541 (void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
542 break;
543
544 case ZFS_PROP_RESERVATION:
545 case ZFS_PROP_REFRESERVATION:
546 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
547 "size is greater than available space"));
548 (void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
549 break;
550
551 default:
552 (void) zfs_standard_error(hdl, err, errbuf);
553 break;
554 }
555 break;
556
557 case EBUSY:
558 (void) zfs_standard_error(hdl, EBUSY, errbuf);
559 break;
560
561 case EROFS:
562 (void) zfs_error(hdl, EZFS_DSREADONLY, errbuf);
563 break;
564
565 case E2BIG:
566 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
567 "property value too long"));
568 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
569 break;
570
571 case ENOTSUP:
572 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
573 "pool and or dataset must be upgraded to set this "
574 "property or value"));
575 (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
576 break;
577
578 case ERANGE:
579 if (prop == ZFS_PROP_COMPRESSION ||
580 prop == ZFS_PROP_DNODESIZE ||
581 prop == ZFS_PROP_RECORDSIZE) {
582 (void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
583 "property setting is not allowed on "
584 "bootable datasets"));
585 (void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
586 } else if (prop == ZFS_PROP_CHECKSUM ||
587 prop == ZFS_PROP_DEDUP) {
588 (void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
589 "property setting is not allowed on "
590 "root pools"));
591 (void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
592 } else {
593 (void) zfs_standard_error(hdl, err, errbuf);
594 }
595 break;
596
597 case EINVAL:
598 if (prop == ZPROP_INVAL) {
599 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
600 } else {
601 (void) zfs_standard_error(hdl, err, errbuf);
602 }
603 break;
604
8fb79fdd
AJ
605 case ZFS_ERR_BADPROP:
606 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
607 break;
608
0ce2de63
AS
609 case EACCES:
610 if (prop == ZFS_PROP_KEYLOCATION) {
611 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
612 "keylocation may only be set on encryption roots"));
613 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
614 } else {
615 (void) zfs_standard_error(hdl, err, errbuf);
616 }
617 break;
618
619 case EOVERFLOW:
620 /*
621 * This platform can't address a volume this big.
622 */
623#ifdef _ILP32
624 if (prop == ZFS_PROP_VOLSIZE) {
625 (void) zfs_error(hdl, EZFS_VOLTOOBIG, errbuf);
626 break;
627 }
9a70e97f 628 zfs_fallthrough;
0ce2de63 629#endif
0ce2de63
AS
630 default:
631 (void) zfs_standard_error(hdl, err, errbuf);
632 }
633}
634
34dc7c2f
BB
635int
636zpool_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
637{
638 return (zpool_standard_error_fmt(hdl, error, "%s", msg));
639}
640
34dc7c2f
BB
641int
642zpool_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
643{
644 va_list ap;
645
646 va_start(ap, fmt);
647
648 if (zfs_common_error(hdl, error, fmt, ap) != 0) {
649 va_end(ap);
650 return (-1);
651 }
652
653 switch (error) {
654 case ENODEV:
655 zfs_verror(hdl, EZFS_NODEVICE, fmt, ap);
656 break;
657
658 case ENOENT:
659 zfs_error_aux(hdl,
660 dgettext(TEXT_DOMAIN, "no such pool or dataset"));
661 zfs_verror(hdl, EZFS_NOENT, fmt, ap);
662 break;
663
664 case EEXIST:
665 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
666 "pool already exists"));
667 zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
668 break;
669
670 case EBUSY:
671 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool is busy"));
b128c09f 672 zfs_verror(hdl, EZFS_BUSY, fmt, ap);
34dc7c2f
BB
673 break;
674
a1d477c2
MA
675 /* There is no pending operation to cancel */
676 case ENOTACTIVE:
677 zfs_verror(hdl, EZFS_NO_PENDING, fmt, ap);
678 break;
679
34dc7c2f
BB
680 case ENXIO:
681 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
682 "one or more devices is currently unavailable"));
683 zfs_verror(hdl, EZFS_BADDEV, fmt, ap);
684 break;
685
686 case ENAMETOOLONG:
687 zfs_verror(hdl, EZFS_DEVOVERFLOW, fmt, ap);
688 break;
689
690 case ENOTSUP:
691 zfs_verror(hdl, EZFS_POOL_NOTSUP, fmt, ap);
692 break;
693
694 case EINVAL:
695 zfs_verror(hdl, EZFS_POOL_INVALARG, fmt, ap);
696 break;
697
698 case ENOSPC:
699 case EDQUOT:
700 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
7c6d9472 701 break;
572e2857 702
9babb374
BB
703 case EAGAIN:
704 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
705 "pool I/O is currently suspended"));
706 zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
707 break;
34dc7c2f 708
572e2857
BB
709 case EROFS:
710 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
711 break;
385f9691
D
712 case EDOM:
713 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
714 "block size out of range or does not match"));
715 zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
716 break;
379ca9cf
OF
717 case EREMOTEIO:
718 zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
719 break;
d2734cce
SD
720 case ZFS_ERR_CHECKPOINT_EXISTS:
721 zfs_verror(hdl, EZFS_CHECKPOINT_EXISTS, fmt, ap);
722 break;
723 case ZFS_ERR_DISCARDING_CHECKPOINT:
724 zfs_verror(hdl, EZFS_DISCARDING_CHECKPOINT, fmt, ap);
725 break;
726 case ZFS_ERR_NO_CHECKPOINT:
727 zfs_verror(hdl, EZFS_NO_CHECKPOINT, fmt, ap);
728 break;
729 case ZFS_ERR_DEVRM_IN_PROGRESS:
730 zfs_verror(hdl, EZFS_DEVRM_IN_PROGRESS, fmt, ap);
731 break;
732 case ZFS_ERR_VDEV_TOO_BIG:
733 zfs_verror(hdl, EZFS_VDEV_TOO_BIG, fmt, ap);
734 break;
43a85362
SD
735 case ZFS_ERR_EXPORT_IN_PROGRESS:
736 zfs_verror(hdl, EZFS_EXPORT_IN_PROGRESS, fmt, ap);
737 break;
9a49d3f3
BB
738 case ZFS_ERR_RESILVER_IN_PROGRESS:
739 zfs_verror(hdl, EZFS_RESILVERING, fmt, ap);
740 break;
741 case ZFS_ERR_REBUILD_IN_PROGRESS:
742 zfs_verror(hdl, EZFS_REBUILDING, fmt, ap);
743 break;
8fb79fdd
AJ
744 case ZFS_ERR_BADPROP:
745 zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
746 break;
2a673e76
AJ
747 case ZFS_ERR_VDEV_NOTSUP:
748 zfs_verror(hdl, EZFS_VDEV_NOTSUP, fmt, ap);
749 break;
b83a0e2d
DB
750 case ZFS_ERR_IOC_CMD_UNAVAIL:
751 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
752 "module does not support this operation. A reboot may "
753 "be required to enable this operation."));
754 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
755 break;
756 case ZFS_ERR_IOC_ARG_UNAVAIL:
757 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
758 "module does not support an option for this operation. "
759 "A reboot may be required to enable this option."));
760 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
761 break;
762 case ZFS_ERR_IOC_ARG_REQUIRED:
763 case ZFS_ERR_IOC_ARG_BADTYPE:
764 zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
765 break;
34dc7c2f 766 default:
f00f4690 767 zfs_error_aux(hdl, "%s", strerror(error));
34dc7c2f
BB
768 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
769 }
770
771 va_end(ap);
772 return (-1);
773}
774
775/*
776 * Display an out of memory error message and abort the current program.
777 */
778int
779no_memory(libzfs_handle_t *hdl)
780{
781 return (zfs_error(hdl, EZFS_NOMEM, "internal error"));
782}
783
784/*
785 * A safe form of malloc() which will die if the allocation fails.
786 */
787void *
788zfs_alloc(libzfs_handle_t *hdl, size_t size)
789{
790 void *data;
791
792 if ((data = calloc(1, size)) == NULL)
793 (void) no_memory(hdl);
794
795 return (data);
796}
797
572e2857
BB
798/*
799 * A safe form of asprintf() which will die if the allocation fails.
800 */
572e2857
BB
801char *
802zfs_asprintf(libzfs_handle_t *hdl, const char *fmt, ...)
803{
804 va_list ap;
805 char *ret;
806 int err;
807
808 va_start(ap, fmt);
809
810 err = vasprintf(&ret, fmt, ap);
811
812 va_end(ap);
813
2babd200 814 if (err < 0) {
572e2857 815 (void) no_memory(hdl);
2babd200
AZ
816 ret = NULL;
817 }
572e2857
BB
818
819 return (ret);
820}
821
34dc7c2f
BB
822/*
823 * A safe form of realloc(), which also zeroes newly allocated space.
824 */
825void *
826zfs_realloc(libzfs_handle_t *hdl, void *ptr, size_t oldsize, size_t newsize)
827{
828 void *ret;
829
830 if ((ret = realloc(ptr, newsize)) == NULL) {
831 (void) no_memory(hdl);
34dc7c2f
BB
832 return (NULL);
833 }
834
861166b0 835 memset((char *)ret + oldsize, 0, newsize - oldsize);
34dc7c2f
BB
836 return (ret);
837}
838
839/*
840 * A safe form of strdup() which will die if the allocation fails.
841 */
842char *
843zfs_strdup(libzfs_handle_t *hdl, const char *str)
844{
845 char *ret;
846
847 if ((ret = strdup(str)) == NULL)
848 (void) no_memory(hdl);
849
850 return (ret);
851}
852
34dc7c2f
BB
853void
854libzfs_print_on_error(libzfs_handle_t *hdl, boolean_t printerr)
855{
856 hdl->libzfs_printerr = printerr;
857}
858
d6418de0
TH
859/*
860 * Read lines from an open file descriptor and store them in an array of
861 * strings until EOF. lines[] will be allocated and populated with all the
862 * lines read. All newlines are replaced with NULL terminators for
863 * convenience. lines[] must be freed after use with libzfs_free_str_array().
864 *
865 * Returns the number of lines read.
866 */
867static int
868libzfs_read_stdout_from_fd(int fd, char **lines[])
869{
870
871 FILE *fp;
872 int lines_cnt = 0;
873 size_t len = 0;
874 char *line = NULL;
875 char **tmp_lines = NULL, **tmp;
d6418de0
TH
876
877 fp = fdopen(fd, "r");
5da63539
AZ
878 if (fp == NULL) {
879 close(fd);
d6418de0 880 return (0);
5da63539 881 }
7c20ceeb 882 while (getline(&line, &len, fp) != -1) {
d6418de0
TH
883 tmp = realloc(tmp_lines, sizeof (*tmp_lines) * (lines_cnt + 1));
884 if (tmp == NULL) {
885 /* Return the lines we were able to process */
886 break;
887 }
888 tmp_lines = tmp;
889
7c20ceeb
AZ
890 /* Remove newline if not EOF */
891 if (line[strlen(line) - 1] == '\n')
892 line[strlen(line) - 1] = '\0';
893
894 tmp_lines[lines_cnt] = strdup(line);
895 if (tmp_lines[lines_cnt] == NULL)
896 break;
897 ++lines_cnt;
d6418de0 898 }
7c20ceeb 899 free(line);
d6418de0
TH
900 fclose(fp);
901 *lines = tmp_lines;
902 return (lines_cnt);
903}
904
905static int
906libzfs_run_process_impl(const char *path, char *argv[], char *env[], int flags,
907 char **lines[], int *lines_cnt)
4b1abce9
NB
908{
909 pid_t pid;
65037d9b 910 int error, devnull_fd;
d6418de0
TH
911 int link[2];
912
913 /*
914 * Setup a pipe between our child and parent process if we're
915 * reading stdout.
916 */
30dadd5c 917 if (lines != NULL && pipe2(link, O_NONBLOCK | O_CLOEXEC) == -1)
64b2e7d7 918 return (-EPIPE);
4b1abce9 919
93ef5003 920 pid = fork();
4b1abce9 921 if (pid == 0) {
d6418de0 922 /* Child process */
10b575d0 923 devnull_fd = open("/dev/null", O_WRONLY | O_CLOEXEC);
3132cb39
GB
924
925 if (devnull_fd < 0)
926 _exit(-1);
927
d6418de0 928 if (!(flags & STDOUT_VERBOSE) && (lines == NULL))
3132cb39 929 (void) dup2(devnull_fd, STDOUT_FILENO);
d6418de0
TH
930 else if (lines != NULL) {
931 /* Save the output to lines[] */
932 dup2(link[1], STDOUT_FILENO);
d6418de0 933 }
9ac97c2a
BB
934
935 if (!(flags & STDERR_VERBOSE))
3132cb39
GB
936 (void) dup2(devnull_fd, STDERR_FILENO);
937
d6418de0
TH
938 if (flags & NO_DEFAULT_PATH) {
939 if (env == NULL)
940 execv(path, argv);
941 else
942 execve(path, argv, env);
943 } else {
944 if (env == NULL)
945 execvp(path, argv);
946 else
947 execvpe(path, argv, env);
948 }
949
4b1abce9
NB
950 _exit(-1);
951 } else if (pid > 0) {
d6418de0 952 /* Parent process */
4b1abce9
NB
953 int status;
954
65037d9b 955 while ((error = waitpid(pid, &status, 0)) == -1 &&
30dadd5c
AZ
956 errno == EINTR)
957 ;
65037d9b 958 if (error < 0 || !WIFEXITED(status))
d1d7e268 959 return (-1);
4b1abce9 960
d6418de0
TH
961 if (lines != NULL) {
962 close(link[1]);
963 *lines_cnt = libzfs_read_stdout_from_fd(link[0], lines);
964 }
d1d7e268 965 return (WEXITSTATUS(status));
4b1abce9
NB
966 }
967
d1d7e268 968 return (-1);
4b1abce9
NB
969}
970
d6418de0
TH
971int
972libzfs_run_process(const char *path, char *argv[], int flags)
973{
974 return (libzfs_run_process_impl(path, argv, NULL, flags, NULL, NULL));
975}
976
977/*
978 * Run a command and store its stdout lines in an array of strings (lines[]).
979 * lines[] is allocated and populated for you, and the number of lines is set in
980 * lines_cnt. lines[] must be freed after use with libzfs_free_str_array().
981 * All newlines (\n) in lines[] are terminated for convenience.
982 */
983int
984libzfs_run_process_get_stdout(const char *path, char *argv[], char *env[],
985 char **lines[], int *lines_cnt)
986{
987 return (libzfs_run_process_impl(path, argv, env, 0, lines, lines_cnt));
988}
989
990/*
991 * Same as libzfs_run_process_get_stdout(), but run without $PATH set. This
992 * means that *path needs to be the full path to the executable.
993 */
994int
995libzfs_run_process_get_stdout_nopath(const char *path, char *argv[],
996 char *env[], char **lines[], int *lines_cnt)
997{
998 return (libzfs_run_process_impl(path, argv, env, NO_DEFAULT_PATH,
999 lines, lines_cnt));
1000}
1001
1002/*
1003 * Free an array of strings. Free both the strings contained in the array and
1004 * the array itself.
1005 */
1006void
1007libzfs_free_str_array(char **strs, int count)
1008{
1009 while (--count >= 0)
1010 free(strs[count]);
1011
1012 free(strs);
1013}
1014
1015/*
1016 * Returns 1 if environment variable is set to "YES", "yes", "ON", "on", or
1017 * a non-zero number.
1018 *
1019 * Returns 0 otherwise.
1020 */
a926aab9
AZ
1021boolean_t
1022libzfs_envvar_is_set(const char *envvar)
d6418de0
TH
1023{
1024 char *env = getenv(envvar);
a926aab9 1025 return (env && (strtoul(env, NULL, 0) > 0 ||
d6418de0 1026 (!strncasecmp(env, "YES", 3) && strnlen(env, 4) == 3) ||
a926aab9 1027 (!strncasecmp(env, "ON", 2) && strnlen(env, 3) == 2)));
d6418de0
TH
1028}
1029
34dc7c2f
BB
1030libzfs_handle_t *
1031libzfs_init(void)
1032{
1033 libzfs_handle_t *hdl;
87abfcba 1034 int error;
7a6c12fd 1035 char *env;
34dc7c2f 1036
e191b60d 1037 if ((error = libzfs_load_module()) != 0) {
65037d9b 1038 errno = error;
4b1abce9
NB
1039 return (NULL);
1040 }
1041
572e2857 1042 if ((hdl = calloc(1, sizeof (libzfs_handle_t))) == NULL) {
34dc7c2f
BB
1043 return (NULL);
1044 }
1045
c14ca145
JK
1046 if (regcomp(&hdl->libzfs_urire, URI_REGEX, 0) != 0) {
1047 free(hdl);
1048 return (NULL);
1049 }
1050
92ffd87a 1051 if ((hdl->libzfs_fd = open(ZFS_DEV, O_RDWR|O_EXCL|O_CLOEXEC)) < 0) {
34dc7c2f
BB
1052 free(hdl);
1053 return (NULL);
1054 }
1055
6f1ffb06
MA
1056 if (libzfs_core_init() != 0) {
1057 (void) close(hdl->libzfs_fd);
6f1ffb06
MA
1058 free(hdl);
1059 return (NULL);
1060 }
1061
34dc7c2f
BB
1062 zfs_prop_init();
1063 zpool_prop_init();
9ae529ec 1064 zpool_feature_init();
2a673e76 1065 vdev_prop_init();
9babb374 1066 libzfs_mnttab_init(hdl);
dc03fa30 1067 fletcher_4_init();
34dc7c2f 1068
d99a0153
CW
1069 if (getenv("ZFS_PROP_DEBUG") != NULL) {
1070 hdl->libzfs_prop_debug = B_TRUE;
1071 }
7a6c12fd
AJ
1072 if ((env = getenv("ZFS_SENDRECV_MAX_NVLIST")) != NULL) {
1073 if ((error = zfs_nicestrtonum(hdl, env,
1074 &hdl->libzfs_max_nvlist))) {
1075 errno = error;
908d43d0 1076 (void) close(hdl->libzfs_fd);
908d43d0 1077 free(hdl);
7a6c12fd
AJ
1078 return (NULL);
1079 }
1080 } else {
1081 hdl->libzfs_max_nvlist = (SPA_MAXBLOCKSIZE * 4);
1082 }
d99a0153 1083
e8bcb693
DB
1084 /*
1085 * For testing, remove some settable properties and features
1086 */
1087 if (libzfs_envvar_is_set("ZFS_SYSFS_PROP_SUPPORT_TEST")) {
1088 zprop_desc_t *proptbl;
1089
1090 proptbl = zpool_prop_get_table();
1091 proptbl[ZPOOL_PROP_COMMENT].pd_zfs_mod_supported = B_FALSE;
1092
1093 proptbl = zfs_prop_get_table();
1094 proptbl[ZFS_PROP_DNODESIZE].pd_zfs_mod_supported = B_FALSE;
1095
1096 zfeature_info_t *ftbl = spa_feature_table;
1097 ftbl[SPA_FEATURE_LARGE_BLOCKS].fi_zfs_mod_supported = B_FALSE;
1098 }
1099
34dc7c2f
BB
1100 return (hdl);
1101}
1102
1103void
1104libzfs_fini(libzfs_handle_t *hdl)
1105{
1106 (void) close(hdl->libzfs_fd);
b128c09f 1107 zpool_free_handles(hdl);
34dc7c2f 1108 namespace_clear(hdl);
9babb374 1109 libzfs_mnttab_fini(hdl);
6f1ffb06 1110 libzfs_core_fini();
c14ca145 1111 regfree(&hdl->libzfs_urire);
dc03fa30 1112 fletcher_4_fini();
37086897
AZ
1113#if LIBFETCH_DYNAMIC
1114 if (hdl->libfetch != (void *)-1 && hdl->libfetch != NULL)
1115 (void) dlclose(hdl->libfetch);
1116 free(hdl->libfetch_load_error);
1117#endif
34dc7c2f
BB
1118 free(hdl);
1119}
1120
1121libzfs_handle_t *
1122zpool_get_handle(zpool_handle_t *zhp)
1123{
1124 return (zhp->zpool_hdl);
1125}
1126
1127libzfs_handle_t *
1128zfs_get_handle(zfs_handle_t *zhp)
1129{
1130 return (zhp->zfs_hdl);
1131}
1132
b128c09f
BB
1133zpool_handle_t *
1134zfs_get_pool_handle(const zfs_handle_t *zhp)
1135{
1136 return (zhp->zpool_hdl);
1137}
1138
34dc7c2f
BB
1139/*
1140 * Given a name, determine whether or not it's a valid path
1141 * (starts with '/' or "./"). If so, walk the mnttab trying
1142 * to match the device number. If not, treat the path as an
aeacdefe 1143 * fs/vol/snap/bkmark name.
34dc7c2f
BB
1144 */
1145zfs_handle_t *
b197457c 1146zfs_path_to_zhandle(libzfs_handle_t *hdl, const char *path, zfs_type_t argtype)
34dc7c2f
BB
1147{
1148 struct stat64 statbuf;
1149 struct extmnttab entry;
34dc7c2f
BB
1150
1151 if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
1152 /*
1153 * It's not a valid path, assume it's a name of type 'argtype'.
1154 */
1155 return (zfs_open(hdl, path, argtype));
1156 }
1157
d31277ab 1158 if (getextmntent(path, &entry, &statbuf) != 0)
34dc7c2f 1159 return (NULL);
34dc7c2f
BB
1160
1161 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
1162 (void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
1163 path);
1164 return (NULL);
1165 }
1166
1167 return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
1168}
1169
1170/*
1171 * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
1172 * an ioctl().
1173 */
18dbf5c8 1174void
34dc7c2f
BB
1175zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
1176{
1177 if (len == 0)
85ce79bb 1178 len = 256 * 1024;
34dc7c2f 1179 zc->zc_nvlist_dst_size = len;
23de906c
CW
1180 zc->zc_nvlist_dst =
1181 (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
34dc7c2f
BB
1182}
1183
1184/*
1185 * Called when an ioctl() which returns an nvlist fails with ENOMEM. This will
1186 * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
1187 * filled in by the kernel to indicate the actual required size.
1188 */
18dbf5c8 1189void
34dc7c2f
BB
1190zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
1191{
1192 free((void *)(uintptr_t)zc->zc_nvlist_dst);
23de906c
CW
1193 zc->zc_nvlist_dst =
1194 (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
34dc7c2f
BB
1195}
1196
1197/*
1198 * Called to free the src and dst nvlists stored in the command structure.
1199 */
1200void
1201zcmd_free_nvlists(zfs_cmd_t *zc)
1202{
1203 free((void *)(uintptr_t)zc->zc_nvlist_conf);
1204 free((void *)(uintptr_t)zc->zc_nvlist_src);
1205 free((void *)(uintptr_t)zc->zc_nvlist_dst);
23de906c
CW
1206 zc->zc_nvlist_conf = 0;
1207 zc->zc_nvlist_src = 0;
1208 zc->zc_nvlist_dst = 0;
34dc7c2f
BB
1209}
1210
18dbf5c8 1211static void
34dc7c2f
BB
1212zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
1213 nvlist_t *nvl)
1214{
1215 char *packed;
34dc7c2f 1216
8bb9ecf4 1217 size_t len = fnvlist_size(nvl);
18dbf5c8 1218 packed = zfs_alloc(hdl, len);
34dc7c2f
BB
1219
1220 verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
1221
1222 *outnv = (uint64_t)(uintptr_t)packed;
1223 *outlen = len;
34dc7c2f
BB
1224}
1225
18dbf5c8 1226void
34dc7c2f
BB
1227zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1228{
18dbf5c8
AZ
1229 zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
1230 &zc->zc_nvlist_conf_size, nvl);
34dc7c2f
BB
1231}
1232
18dbf5c8 1233void
34dc7c2f
BB
1234zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1235{
18dbf5c8
AZ
1236 zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
1237 &zc->zc_nvlist_src_size, nvl);
34dc7c2f
BB
1238}
1239
1240/*
1241 * Unpacks an nvlist from the ZFS ioctl command structure.
1242 */
1243int
1244zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
1245{
1246 if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
1247 zc->zc_nvlist_dst_size, nvlp, 0) != 0)
1248 return (no_memory(hdl));
1249
1250 return (0);
1251}
1252
34dc7c2f
BB
1253/*
1254 * ================================================================
1255 * API shared by zfs and zpool property management
1256 * ================================================================
1257 */
1258
1259static void
1260zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
1261{
6a42939f 1262 zprop_list_t *pl;
34dc7c2f
BB
1263 int i;
1264 char *title;
1265 size_t len;
1266
1267 cbp->cb_first = B_FALSE;
1268 if (cbp->cb_scripted)
1269 return;
1270
1271 /*
1272 * Start with the length of the column headers.
1273 */
1274 cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
1275 cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
1276 "PROPERTY"));
1277 cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
1278 "VALUE"));
428870ff
BB
1279 cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
1280 "RECEIVED"));
34dc7c2f
BB
1281 cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
1282 "SOURCE"));
1283
fb5f0bc8
BB
1284 /* first property is always NAME */
1285 assert(cbp->cb_proplist->pl_prop ==
2a673e76
AJ
1286 ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1287 ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME : ZFS_PROP_NAME)));
fb5f0bc8 1288
34dc7c2f
BB
1289 /*
1290 * Go through and calculate the widths for each column. For the
1291 * 'source' column, we kludge it up by taking the worst-case scenario of
1292 * inheriting from the longest name. This is acceptable because in the
1293 * majority of cases 'SOURCE' is the last column displayed, and we don't
1294 * use the width anyway. Note that the 'VALUE' column can be oversized,
428870ff 1295 * if the name of the property is much longer than any values we find.
34dc7c2f
BB
1296 */
1297 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
1298 /*
1299 * 'PROPERTY' column
1300 */
4ff7a8fa 1301 if (pl->pl_prop != ZPROP_USERPROP) {
34dc7c2f
BB
1302 const char *propname = (type == ZFS_TYPE_POOL) ?
1303 zpool_prop_to_name(pl->pl_prop) :
2a673e76
AJ
1304 ((type == ZFS_TYPE_VDEV) ?
1305 vdev_prop_to_name(pl->pl_prop) :
1306 zfs_prop_to_name(pl->pl_prop));
34dc7c2f 1307
2a673e76 1308 assert(propname != NULL);
34dc7c2f
BB
1309 len = strlen(propname);
1310 if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1311 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1312 } else {
2a673e76 1313 assert(pl->pl_user_prop != NULL);
34dc7c2f
BB
1314 len = strlen(pl->pl_user_prop);
1315 if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1316 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1317 }
1318
1319 /*
fb5f0bc8
BB
1320 * 'VALUE' column. The first property is always the 'name'
1321 * property that was tacked on either by /sbin/zfs's
1322 * zfs_do_get() or when calling zprop_expand_list(), so we
1323 * ignore its width. If the user specified the name property
1324 * to display, then it will be later in the list in any case.
34dc7c2f 1325 */
fb5f0bc8 1326 if (pl != cbp->cb_proplist &&
34dc7c2f
BB
1327 pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
1328 cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
1329
428870ff
BB
1330 /* 'RECEIVED' column. */
1331 if (pl != cbp->cb_proplist &&
1332 pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
1333 cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
1334
34dc7c2f
BB
1335 /*
1336 * 'NAME' and 'SOURCE' columns
1337 */
2a673e76
AJ
1338 if (pl->pl_prop == ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1339 ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME :
1340 ZFS_PROP_NAME)) && pl->pl_width >
1341 cbp->cb_colwidths[GET_COL_NAME]) {
34dc7c2f
BB
1342 cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
1343 cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
1344 strlen(dgettext(TEXT_DOMAIN, "inherited from"));
1345 }
1346 }
1347
1348 /*
1349 * Now go through and print the headers.
1350 */
428870ff 1351 for (i = 0; i < ZFS_GET_NCOLS; i++) {
34dc7c2f
BB
1352 switch (cbp->cb_columns[i]) {
1353 case GET_COL_NAME:
1354 title = dgettext(TEXT_DOMAIN, "NAME");
1355 break;
1356 case GET_COL_PROPERTY:
1357 title = dgettext(TEXT_DOMAIN, "PROPERTY");
1358 break;
1359 case GET_COL_VALUE:
1360 title = dgettext(TEXT_DOMAIN, "VALUE");
1361 break;
428870ff
BB
1362 case GET_COL_RECVD:
1363 title = dgettext(TEXT_DOMAIN, "RECEIVED");
1364 break;
34dc7c2f
BB
1365 case GET_COL_SOURCE:
1366 title = dgettext(TEXT_DOMAIN, "SOURCE");
1367 break;
1368 default:
1369 title = NULL;
1370 }
1371
1372 if (title != NULL) {
428870ff
BB
1373 if (i == (ZFS_GET_NCOLS - 1) ||
1374 cbp->cb_columns[i + 1] == GET_COL_NONE)
34dc7c2f
BB
1375 (void) printf("%s", title);
1376 else
1377 (void) printf("%-*s ",
1378 cbp->cb_colwidths[cbp->cb_columns[i]],
1379 title);
1380 }
1381 }
1382 (void) printf("\n");
1383}
1384
1385/*
1386 * Display a single line of output, according to the settings in the callback
1387 * structure.
1388 */
1389void
1390zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
1391 const char *propname, const char *value, zprop_source_t sourcetype,
428870ff 1392 const char *source, const char *recvd_value)
34dc7c2f
BB
1393{
1394 int i;
d4ed6673 1395 const char *str = NULL;
34dc7c2f
BB
1396 char buf[128];
1397
1398 /*
1399 * Ignore those source types that the user has chosen to ignore.
1400 */
1401 if ((sourcetype & cbp->cb_sources) == 0)
1402 return;
1403
1404 if (cbp->cb_first)
1405 zprop_print_headers(cbp, cbp->cb_type);
1406
428870ff 1407 for (i = 0; i < ZFS_GET_NCOLS; i++) {
34dc7c2f
BB
1408 switch (cbp->cb_columns[i]) {
1409 case GET_COL_NAME:
1410 str = name;
1411 break;
1412
1413 case GET_COL_PROPERTY:
1414 str = propname;
1415 break;
1416
1417 case GET_COL_VALUE:
1418 str = value;
1419 break;
1420
1421 case GET_COL_SOURCE:
1422 switch (sourcetype) {
1423 case ZPROP_SRC_NONE:
1424 str = "-";
1425 break;
1426
1427 case ZPROP_SRC_DEFAULT:
1428 str = "default";
1429 break;
1430
1431 case ZPROP_SRC_LOCAL:
1432 str = "local";
1433 break;
1434
1435 case ZPROP_SRC_TEMPORARY:
1436 str = "temporary";
1437 break;
1438
1439 case ZPROP_SRC_INHERITED:
1440 (void) snprintf(buf, sizeof (buf),
1441 "inherited from %s", source);
1442 str = buf;
1443 break;
428870ff
BB
1444 case ZPROP_SRC_RECEIVED:
1445 str = "received";
1446 break;
23d70cde
GM
1447
1448 default:
1449 str = NULL;
1450 assert(!"unhandled zprop_source_t");
34dc7c2f
BB
1451 }
1452 break;
1453
428870ff
BB
1454 case GET_COL_RECVD:
1455 str = (recvd_value == NULL ? "-" : recvd_value);
1456 break;
1457
34dc7c2f
BB
1458 default:
1459 continue;
1460 }
1461
23827a4c
G
1462 if (i == (ZFS_GET_NCOLS - 1) ||
1463 cbp->cb_columns[i + 1] == GET_COL_NONE)
34dc7c2f
BB
1464 (void) printf("%s", str);
1465 else if (cbp->cb_scripted)
1466 (void) printf("%s\t", str);
1467 else
1468 (void) printf("%-*s ",
1469 cbp->cb_colwidths[cbp->cb_columns[i]],
1470 str);
34dc7c2f
BB
1471 }
1472
1473 (void) printf("\n");
1474}
1475
1476/*
1477 * Given a numeric suffix, convert the value into a number of bits that the
1478 * resulting value must be shifted.
1479 */
1480static int
1481str2shift(libzfs_handle_t *hdl, const char *buf)
1482{
1483 const char *ends = "BKMGTPEZ";
1484 int i;
1485
1486 if (buf[0] == '\0')
1487 return (0);
1488 for (i = 0; i < strlen(ends); i++) {
1489 if (toupper(buf[0]) == ends[i])
1490 break;
1491 }
1492 if (i == strlen(ends)) {
53c2ec1d
JL
1493 if (hdl)
1494 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1495 "invalid numeric suffix '%s'"), buf);
34dc7c2f
BB
1496 return (-1);
1497 }
1498
1499 /*
826ab7ad
RL
1500 * Allow 'G' = 'GB' = 'GiB', case-insensitively.
1501 * However, 'BB' and 'BiB' are disallowed.
34dc7c2f 1502 */
826ab7ad
RL
1503 if (buf[1] == '\0' ||
1504 (toupper(buf[0]) != 'B' &&
d1d7e268
MK
1505 ((toupper(buf[1]) == 'B' && buf[2] == '\0') ||
1506 (toupper(buf[1]) == 'I' && toupper(buf[2]) == 'B' &&
1507 buf[3] == '\0'))))
1508 return (10 * i);
34dc7c2f 1509
53c2ec1d
JL
1510 if (hdl)
1511 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1512 "invalid numeric suffix '%s'"), buf);
34dc7c2f
BB
1513 return (-1);
1514}
1515
1516/*
1517 * Convert a string of the form '100G' into a real number. Used when setting
1518 * properties or creating a volume. 'buf' is used to place an extended error
1519 * message for the caller to use.
1520 */
1521int
1522zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1523{
1524 char *end;
1525 int shift;
1526
1527 *num = 0;
1528
1529 /* Check to see if this looks like a number. */
1530 if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1531 if (hdl)
1532 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1533 "bad numeric value '%s'"), value);
1534 return (-1);
1535 }
1536
428870ff 1537 /* Rely on strtoull() to process the numeric portion. */
34dc7c2f 1538 errno = 0;
d164b209 1539 *num = strtoull(value, &end, 10);
34dc7c2f
BB
1540
1541 /*
1542 * Check for ERANGE, which indicates that the value is too large to fit
1543 * in a 64-bit value.
1544 */
1545 if (errno == ERANGE) {
1546 if (hdl)
1547 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1548 "numeric value is too large"));
1549 return (-1);
1550 }
1551
1552 /*
1553 * If we have a decimal value, then do the computation with floating
1554 * point arithmetic. Otherwise, use standard arithmetic.
1555 */
1556 if (*end == '.') {
1557 double fval = strtod(value, &end);
1558
1559 if ((shift = str2shift(hdl, end)) == -1)
1560 return (-1);
1561
1562 fval *= pow(2, shift);
1563
4d32abaa
RM
1564 /*
1565 * UINT64_MAX is not exactly representable as a double.
1566 * The closest representation is UINT64_MAX + 1, so we
1567 * use a >= comparison instead of > for the bounds check.
1568 */
1569 if (fval >= (double)UINT64_MAX) {
34dc7c2f
BB
1570 if (hdl)
1571 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1572 "numeric value is too large"));
1573 return (-1);
1574 }
1575
1576 *num = (uint64_t)fval;
1577 } else {
1578 if ((shift = str2shift(hdl, end)) == -1)
1579 return (-1);
1580
1581 /* Check for overflow */
1582 if (shift >= 64 || (*num << shift) >> shift != *num) {
1583 if (hdl)
1584 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1585 "numeric value is too large"));
1586 return (-1);
1587 }
1588
1589 *num <<= shift;
1590 }
1591
1592 return (0);
1593}
1594
1595/*
1596 * Given a propname=value nvpair to set, parse any numeric properties
1597 * (index, boolean, etc) if they are specified as strings and add the
1598 * resulting nvpair to the returned nvlist.
1599 *
1600 * At the DSL layer, all properties are either 64-bit numbers or strings.
1601 * We want the user to be able to ignore this fact and specify properties
1602 * as native values (numbers, for example) or as strings (to simplify
1603 * command line utilities). This also handles converting index types
1604 * (compression, checksum, etc) from strings to their on-disk index.
1605 */
1606int
1607zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
d1807f16 1608 zfs_type_t type, nvlist_t *ret, const char **svalp, uint64_t *ivalp,
34dc7c2f
BB
1609 const char *errbuf)
1610{
1611 data_type_t datatype = nvpair_type(elem);
1612 zprop_type_t proptype;
1613 const char *propname;
d1807f16 1614 const char *value;
34dc7c2f 1615 boolean_t isnone = B_FALSE;
d22f3a82 1616 boolean_t isauto = B_FALSE;
b6ca6193 1617 int err = 0;
34dc7c2f
BB
1618
1619 if (type == ZFS_TYPE_POOL) {
1620 proptype = zpool_prop_get_type(prop);
1621 propname = zpool_prop_to_name(prop);
2a673e76
AJ
1622 } else if (type == ZFS_TYPE_VDEV) {
1623 proptype = vdev_prop_get_type(prop);
1624 propname = vdev_prop_to_name(prop);
34dc7c2f
BB
1625 } else {
1626 proptype = zfs_prop_get_type(prop);
1627 propname = zfs_prop_to_name(prop);
1628 }
1629
1630 /*
1631 * Convert any properties to the internal DSL value types.
1632 */
1633 *svalp = NULL;
1634 *ivalp = 0;
1635
1636 switch (proptype) {
1637 case PROP_TYPE_STRING:
1638 if (datatype != DATA_TYPE_STRING) {
1639 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1640 "'%s' must be a string"), nvpair_name(elem));
1641 goto error;
1642 }
b6ca6193 1643 err = nvpair_value_string(elem, svalp);
1644 if (err != 0) {
1645 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1646 "'%s' is invalid"), nvpair_name(elem));
1647 goto error;
1648 }
34dc7c2f
BB
1649 if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1650 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1651 "'%s' is too long"), nvpair_name(elem));
1652 goto error;
1653 }
1654 break;
1655
1656 case PROP_TYPE_NUMBER:
1657 if (datatype == DATA_TYPE_STRING) {
1658 (void) nvpair_value_string(elem, &value);
1659 if (strcmp(value, "none") == 0) {
1660 isnone = B_TRUE;
d22f3a82
MG
1661 } else if (strcmp(value, "auto") == 0) {
1662 isauto = B_TRUE;
1663 } else if (zfs_nicestrtonum(hdl, value, ivalp) != 0) {
34dc7c2f
BB
1664 goto error;
1665 }
1666 } else if (datatype == DATA_TYPE_UINT64) {
1667 (void) nvpair_value_uint64(elem, ivalp);
1668 } else {
1669 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1670 "'%s' must be a number"), nvpair_name(elem));
1671 goto error;
1672 }
1673
1674 /*
1675 * Quota special: force 'none' and don't allow 0.
1676 */
1677 if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1678 (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1679 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1680 "use 'none' to disable quota/refquota"));
1681 goto error;
1682 }
788eb90c
JJ
1683
1684 /*
1685 * Special handling for "*_limit=none". In this case it's not
1686 * 0 but UINT64_MAX.
1687 */
1688 if ((type & ZFS_TYPE_DATASET) && isnone &&
1689 (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1690 prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1691 *ivalp = UINT64_MAX;
1692 }
69f024a5
RW
1693
1694 /*
1695 * Special handling for "checksum_*=none". In this case it's not
1696 * 0 but UINT64_MAX.
1697 */
1698 if ((type & ZFS_TYPE_VDEV) && isnone &&
1699 (prop == VDEV_PROP_CHECKSUM_N ||
1700 prop == VDEV_PROP_CHECKSUM_T ||
1701 prop == VDEV_PROP_IO_N ||
1702 prop == VDEV_PROP_IO_T)) {
1703 *ivalp = UINT64_MAX;
1704 }
d22f3a82
MG
1705
1706 /*
1707 * Special handling for setting 'refreservation' to 'auto'. Use
1708 * UINT64_MAX to tell the caller to use zfs_fix_auto_resv().
1709 * 'auto' is only allowed on volumes.
1710 */
1711 if (isauto) {
1712 switch (prop) {
1713 case ZFS_PROP_REFRESERVATION:
1714 if ((type & ZFS_TYPE_VOLUME) == 0) {
1715 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1716 "'%s=auto' only allowed on "
1717 "volumes"), nvpair_name(elem));
1718 goto error;
1719 }
1720 *ivalp = UINT64_MAX;
1721 break;
1722 default:
1723 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1724 "'auto' is invalid value for '%s'"),
1725 nvpair_name(elem));
1726 goto error;
1727 }
1728 }
1729
34dc7c2f
BB
1730 break;
1731
1732 case PROP_TYPE_INDEX:
1733 if (datatype != DATA_TYPE_STRING) {
1734 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1735 "'%s' must be a string"), nvpair_name(elem));
1736 goto error;
1737 }
1738
1739 (void) nvpair_value_string(elem, &value);
1740
1741 if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1742 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1743 "'%s' must be one of '%s'"), propname,
1744 zprop_values(prop, type));
1745 goto error;
1746 }
1747 break;
1748
1749 default:
1750 abort();
1751 }
1752
1753 /*
1754 * Add the result to our return set of properties.
1755 */
1756 if (*svalp != NULL) {
1757 if (nvlist_add_string(ret, propname, *svalp) != 0) {
1758 (void) no_memory(hdl);
1759 return (-1);
1760 }
1761 } else {
1762 if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1763 (void) no_memory(hdl);
1764 return (-1);
1765 }
1766 }
1767
1768 return (0);
1769error:
1770 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1771 return (-1);
1772}
1773
b128c09f 1774static int
539d16c3 1775addlist(libzfs_handle_t *hdl, const char *propname, zprop_list_t **listp,
b128c09f
BB
1776 zfs_type_t type)
1777{
539d16c3 1778 int prop = zprop_name_to_prop(propname, type);
962d5242 1779 if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type, B_FALSE))
b128c09f
BB
1780 prop = ZPROP_INVAL;
1781
1782 /*
2a673e76
AJ
1783 * Return failure if no property table entry was found and this isn't
1784 * a user-defined property.
b128c09f 1785 */
4ff7a8fa 1786 if (prop == ZPROP_USERPROP && ((type == ZFS_TYPE_POOL &&
8eae2d21 1787 !zfs_prop_user(propname) &&
9ae529ec
CS
1788 !zpool_prop_feature(propname) &&
1789 !zpool_prop_unsupported(propname)) ||
2a673e76
AJ
1790 ((type == ZFS_TYPE_DATASET) && !zfs_prop_user(propname) &&
1791 !zfs_prop_userquota(propname) && !zfs_prop_written(propname)) ||
1792 ((type == ZFS_TYPE_VDEV) && !vdev_prop_user(propname)))) {
b128c09f
BB
1793 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1794 "invalid property '%s'"), propname);
1795 return (zfs_error(hdl, EZFS_BADPROP,
1796 dgettext(TEXT_DOMAIN, "bad property list")));
1797 }
1798
539d16c3
AZ
1799 zprop_list_t *entry = zfs_alloc(hdl, sizeof (*entry));
1800
b128c09f 1801 entry->pl_prop = prop;
4ff7a8fa 1802 if (prop == ZPROP_USERPROP) {
f4826a2d 1803 entry->pl_user_prop = zfs_strdup(hdl, propname);
b128c09f
BB
1804 entry->pl_width = strlen(propname);
1805 } else {
1806 entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1807 type);
1808 }
1809
1810 *listp = entry;
1811
1812 return (0);
1813}
1814
34dc7c2f
BB
1815/*
1816 * Given a comma-separated list of properties, construct a property list
1817 * containing both user-defined and native properties. This function will
1818 * return a NULL list if 'all' is specified, which can later be expanded
1819 * by zprop_expand_list().
1820 */
1821int
1822zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1823 zfs_type_t type)
1824{
34dc7c2f 1825 *listp = NULL;
34dc7c2f
BB
1826
1827 /*
1828 * If 'all' is specified, return a NULL list.
1829 */
1830 if (strcmp(props, "all") == 0)
1831 return (0);
1832
1833 /*
1834 * If no props were specified, return an error.
1835 */
1836 if (props[0] == '\0') {
1837 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1838 "no properties specified"));
1839 return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
1840 "bad property list")));
1841 }
1842
539d16c3
AZ
1843 for (char *p; (p = strsep(&props, ",")); )
1844 if (strcmp(p, "space") == 0) {
1845 static const char *const spaceprops[] = {
b128c09f
BB
1846 "name", "avail", "used", "usedbysnapshots",
1847 "usedbydataset", "usedbyrefreservation",
539d16c3 1848 "usedbychildren"
b128c09f 1849 };
b128c09f 1850
539d16c3 1851 for (int i = 0; i < ARRAY_SIZE(spaceprops); i++) {
b128c09f
BB
1852 if (addlist(hdl, spaceprops[i], listp, type))
1853 return (-1);
1854 listp = &(*listp)->pl_next;
34dc7c2f 1855 }
34dc7c2f 1856 } else {
539d16c3 1857 if (addlist(hdl, p, listp, type))
b128c09f
BB
1858 return (-1);
1859 listp = &(*listp)->pl_next;
34dc7c2f
BB
1860 }
1861
34dc7c2f
BB
1862 return (0);
1863}
1864
1865void
1866zprop_free_list(zprop_list_t *pl)
1867{
1868 zprop_list_t *next;
1869
1870 while (pl != NULL) {
1871 next = pl->pl_next;
1872 free(pl->pl_user_prop);
1873 free(pl);
1874 pl = next;
1875 }
1876}
1877
1878typedef struct expand_data {
1879 zprop_list_t **last;
1880 libzfs_handle_t *hdl;
1881 zfs_type_t type;
1882} expand_data_t;
1883
65c7cc49 1884static int
34dc7c2f
BB
1885zprop_expand_list_cb(int prop, void *cb)
1886{
1887 zprop_list_t *entry;
1888 expand_data_t *edp = cb;
1889
18dbf5c8 1890 entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t));
34dc7c2f
BB
1891
1892 entry->pl_prop = prop;
1893 entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
1894 entry->pl_all = B_TRUE;
1895
1896 *(edp->last) = entry;
1897 edp->last = &entry->pl_next;
1898
1899 return (ZPROP_CONT);
1900}
1901
1902int
1903zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
1904{
1905 zprop_list_t *entry;
1906 zprop_list_t **last;
1907 expand_data_t exp;
1908
1909 if (*plp == NULL) {
1910 /*
1911 * If this is the very first time we've been called for an 'all'
1912 * specification, expand the list to include all native
1913 * properties.
1914 */
1915 last = plp;
1916
1917 exp.last = last;
1918 exp.hdl = hdl;
1919 exp.type = type;
1920
1921 if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
1922 B_FALSE, type) == ZPROP_INVAL)
1923 return (-1);
1924
1925 /*
1926 * Add 'name' to the beginning of the list, which is handled
1927 * specially.
1928 */
f4826a2d 1929 entry = zfs_alloc(hdl, sizeof (zprop_list_t));
2a673e76
AJ
1930 entry->pl_prop = ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1931 ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME : ZFS_PROP_NAME));
34dc7c2f
BB
1932 entry->pl_width = zprop_width(entry->pl_prop,
1933 &entry->pl_fixed, type);
1934 entry->pl_all = B_TRUE;
1935 entry->pl_next = *plp;
1936 *plp = entry;
1937 }
1938 return (0);
1939}
1940
1941int
1942zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
1943 zfs_type_t type)
1944{
1945 return (zprop_iter_common(func, cb, show_all, ordered, type));
1946}
50478c6d 1947
2b4f2fc9
AZ
1948const char *
1949zfs_version_userland(void)
50478c6d 1950{
2b4f2fc9 1951 return (ZFS_META_ALIAS);
50478c6d
T
1952}
1953
50478c6d
T
1954/*
1955 * Prints both zfs userland and kernel versions
2b4f2fc9 1956 * Returns 0 on success, and -1 on error
50478c6d
T
1957 */
1958int
1959zfs_version_print(void)
1960{
2b4f2fc9 1961 (void) puts(ZFS_META_ALIAS);
50478c6d 1962
2b4f2fc9
AZ
1963 char *kver = zfs_version_kernel();
1964 if (kver == NULL) {
50478c6d
T
1965 fprintf(stderr, "zfs_version_kernel() failed: %s\n",
1966 strerror(errno));
1967 return (-1);
1968 }
1969
2b4f2fc9
AZ
1970 (void) printf("zfs-kmod-%s\n", kver);
1971 free(kver);
50478c6d
T
1972 return (0);
1973}
9fb2771a
TH
1974
1975/*
1976 * Return 1 if the user requested ANSI color output, and our terminal supports
1977 * it. Return 0 for no color.
1978 */
6ecdd35b 1979int
9fb2771a
TH
1980use_color(void)
1981{
1982 static int use_color = -1;
1983 char *term;
1984
1985 /*
1986 * Optimization:
1987 *
1988 * For each zpool invocation, we do a single check to see if we should
1989 * be using color or not, and cache that value for the lifetime of the
1990 * the zpool command. That makes it cheap to call use_color() when
1991 * we're printing with color. We assume that the settings are not going
1992 * to change during the invocation of a zpool command (the user isn't
1993 * going to change the ZFS_COLOR value while zpool is running, for
1994 * example).
1995 */
1996 if (use_color != -1) {
1997 /*
1998 * We've already figured out if we should be using color or
1999 * not. Return the cached value.
2000 */
2001 return (use_color);
2002 }
2003
2004 term = getenv("TERM");
2005 /*
2006 * The user sets the ZFS_COLOR env var set to enable zpool ANSI color
2007 * output. However if NO_COLOR is set (https://no-color.org/) then
2008 * don't use it. Also, don't use color if terminal doesn't support
2009 * it.
2010 */
2011 if (libzfs_envvar_is_set("ZFS_COLOR") &&
2012 !libzfs_envvar_is_set("NO_COLOR") &&
2013 isatty(STDOUT_FILENO) && term && strcmp("dumb", term) != 0 &&
2014 strcmp("unknown", term) != 0) {
2015 /* Color supported */
2016 use_color = 1;
2017 } else {
2018 use_color = 0;
2019 }
2020
2021 return (use_color);
2022}
2023
2024/*
80f2cdcd
TR
2025 * The functions color_start() and color_end() are used for when you want
2026 * to colorize a block of text.
9fb2771a 2027 *
80f2cdcd
TR
2028 * For example:
2029 * color_start(ANSI_RED)
9fb2771a
TH
2030 * printf("hello");
2031 * printf("world");
2032 * color_end();
2033 */
2034void
a926aab9 2035color_start(const char *color)
9fb2771a 2036{
80f2cdcd 2037 if (color && use_color()) {
a926aab9 2038 fputs(color, stdout);
fb11b157
ECR
2039 fflush(stdout);
2040 }
9fb2771a
TH
2041}
2042
2043void
2044color_end(void)
2045{
fb11b157 2046 if (use_color()) {
a926aab9 2047 fputs(ANSI_RESET, stdout);
fb11b157
ECR
2048 fflush(stdout);
2049 }
2050
9fb2771a
TH
2051}
2052
80f2cdcd
TR
2053/*
2054 * printf() with a color. If color is NULL, then do a normal printf.
2055 */
9fb2771a 2056int
a926aab9 2057printf_color(const char *color, const char *format, ...)
9fb2771a
TH
2058{
2059 va_list aptr;
2060 int rc;
2061
2062 if (color)
2063 color_start(color);
2064
2065 va_start(aptr, format);
2066 rc = vprintf(format, aptr);
2067 va_end(aptr);
2068
2069 if (color)
2070 color_end();
2071
2072 return (rc);
2073}
b53077a9
TH
2074
2075/* PATH + 5 env vars + a NULL entry = 7 */
2076#define ZPOOL_VDEV_SCRIPT_ENV_COUNT 7
2077
2078/*
2079 * There's a few places where ZFS will call external scripts (like the script
2080 * in zpool.d/ and `zfs_prepare_disk`). These scripts are called with a
2081 * reduced $PATH, and some vdev specific environment vars set. This function
2082 * will allocate an populate the environment variable array that is passed to
2083 * these scripts. The user must free the arrays with zpool_vdev_free_env() when
2084 * they are done.
2085 *
2086 * The following env vars will be set (but value could be blank):
2087 *
2088 * POOL_NAME
2089 * VDEV_PATH
2090 * VDEV_UPATH
2091 * VDEV_ENC_SYSFS_PATH
2092 *
2093 * In addition, you can set an optional environment variable named 'opt_key'
2094 * to 'opt_val' if you want.
2095 *
2096 * Returns allocated env[] array on success, NULL otherwise.
2097 */
2098char **
2099zpool_vdev_script_alloc_env(const char *pool_name,
2100 const char *vdev_path, const char *vdev_upath,
2101 const char *vdev_enc_sysfs_path, const char *opt_key, const char *opt_val)
2102{
2103 char **env = NULL;
2104 int rc;
2105
2106 env = calloc(ZPOOL_VDEV_SCRIPT_ENV_COUNT, sizeof (*env));
2107 if (!env)
2108 return (NULL);
2109
2110 env[0] = strdup("PATH=/bin:/sbin:/usr/bin:/usr/sbin");
2111 if (!env[0])
2112 goto error;
2113
2114 /* Setup our custom environment variables */
2115 rc = asprintf(&env[1], "POOL_NAME=%s", pool_name ? pool_name : "");
2116 if (rc == -1) {
2117 env[1] = NULL;
2118 goto error;
2119 }
2120
2121 rc = asprintf(&env[2], "VDEV_PATH=%s", vdev_path ? vdev_path : "");
2122 if (rc == -1) {
2123 env[2] = NULL;
2124 goto error;
2125 }
2126
2127 rc = asprintf(&env[3], "VDEV_UPATH=%s", vdev_upath ? vdev_upath : "");
2128 if (rc == -1) {
2129 env[3] = NULL;
2130 goto error;
2131 }
2132
2133 rc = asprintf(&env[4], "VDEV_ENC_SYSFS_PATH=%s",
2134 vdev_enc_sysfs_path ? vdev_enc_sysfs_path : "");
2135 if (rc == -1) {
2136 env[4] = NULL;
2137 goto error;
2138 }
2139
2140 if (opt_key != NULL) {
2141 rc = asprintf(&env[5], "%s=%s", opt_key,
2142 opt_val ? opt_val : "");
2143 if (rc == -1) {
2144 env[5] = NULL;
2145 goto error;
2146 }
2147 }
2148
2149 return (env);
2150
2151error:
2152 for (int i = 0; i < ZPOOL_VDEV_SCRIPT_ENV_COUNT; i++)
2153 free(env[i]);
2154
2155 free(env);
2156
2157 return (NULL);
2158}
2159
2160/*
2161 * Free the env[] array that was allocated by zpool_vdev_script_alloc_env().
2162 */
2163void
2164zpool_vdev_script_free_env(char **env)
2165{
2166 for (int i = 0; i < ZPOOL_VDEV_SCRIPT_ENV_COUNT; i++)
2167 free(env[i]);
2168
2169 free(env);
2170}
2171
2172/*
2173 * Prepare a disk by (optionally) running a program before labeling the disk.
2174 * This can be useful for installing disk firmware or doing some pre-flight
2175 * checks on the disk before it becomes part of the pool. The program run is
2176 * located at ZFSEXECDIR/zfs_prepare_disk
2177 * (E.x: /usr/local/libexec/zfs/zfs_prepare_disk).
2178 *
2179 * Return 0 on success, non-zero on failure.
2180 */
2181int
2182zpool_prepare_disk(zpool_handle_t *zhp, nvlist_t *vdev_nv,
2183 const char *prepare_str, char **lines[], int *lines_cnt)
2184{
2185 const char *script_path = ZFSEXECDIR "/zfs_prepare_disk";
2186 const char *pool_name;
2187 int rc = 0;
2188
2189 /* Path to script and a NULL entry */
2190 char *argv[2] = {(char *)script_path};
2191 char **env = NULL;
2192 const char *path = NULL, *enc_sysfs_path = NULL;
2193 char *upath;
2194 *lines_cnt = 0;
2195
2196 if (access(script_path, X_OK) != 0) {
2197 /* No script, nothing to do */
2198 return (0);
2199 }
2200
2201 (void) nvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_PATH, &path);
2202 (void) nvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_VDEV_ENC_SYSFS_PATH,
2203 &enc_sysfs_path);
2204
2205 upath = zfs_get_underlying_path(path);
2206 pool_name = zhp ? zpool_get_name(zhp) : NULL;
2207
2208 env = zpool_vdev_script_alloc_env(pool_name, path, upath,
2209 enc_sysfs_path, "VDEV_PREPARE", prepare_str);
2210
2211 free(upath);
2212
2213 if (env == NULL) {
2214 return (ENOMEM);
2215 }
2216
2217 rc = libzfs_run_process_get_stdout(script_path, argv, env, lines,
2218 lines_cnt);
2219
2220 zpool_vdev_script_free_env(env);
2221
2222 return (rc);
2223}
2224
2225/*
2226 * Optionally run a script and then label a disk. The script can be used to
2227 * prepare a disk for inclusion into the pool. For example, it might update
2228 * the disk's firmware or check its health.
2229 *
2230 * The 'name' provided is the short name, stripped of any leading
2231 * /dev path, and is passed to zpool_label_disk. vdev_nv is the nvlist for
2232 * the vdev. prepare_str is a string that gets passed as the VDEV_PREPARE
2233 * env variable to the script.
2234 *
2235 * The following env vars are passed to the script:
2236 *
2237 * POOL_NAME: The pool name (blank during zpool create)
2238 * VDEV_PREPARE: Reason why the disk is being prepared for inclusion:
2239 * "create", "add", "replace", or "autoreplace"
2240 * VDEV_PATH: Path to the disk
2241 * VDEV_UPATH: One of the 'underlying paths' to the disk. This is
2242 * useful for DM devices.
2243 * VDEV_ENC_SYSFS_PATH: Path to the disk's enclosure sysfs path, if available.
2244 *
2245 * Note, some of these values can be blank.
2246 *
2247 * Return 0 on success, non-zero otherwise.
2248 */
2249int
2250zpool_prepare_and_label_disk(libzfs_handle_t *hdl, zpool_handle_t *zhp,
2251 const char *name, nvlist_t *vdev_nv, const char *prepare_str,
2252 char **lines[], int *lines_cnt)
2253{
2254 int rc;
2255 char vdev_path[MAXPATHLEN];
2256 (void) snprintf(vdev_path, sizeof (vdev_path), "%s/%s", DISK_ROOT,
2257 name);
2258
2259 /* zhp will be NULL when creating a pool */
2260 rc = zpool_prepare_disk(zhp, vdev_nv, prepare_str, lines, lines_cnt);
2261 if (rc != 0)
2262 return (rc);
2263
2264 rc = zpool_label_disk(hdl, zhp, name);
2265 return (rc);
2266}