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 https://opensource.org/licenses/CDDL-1.0.
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 2015 Nexenta Systems, Inc.  All rights reserved.
24  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
26  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
27  * Copyright (c) 2018 Datto Inc.
28  * Copyright (c) 2017 Open-E, Inc. All Rights Reserved.
29  * Copyright (c) 2017, Intel Corporation.
30  * Copyright (c) 2018, loli10K <ezomori.nozomu@gmail.com>
31  * Copyright (c) 2021, Colm Buckley <colm@tuatha.org>
32  * Copyright (c) 2021, Klara Inc.
33  */
34 
35 #include <errno.h>
36 #include <libintl.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <strings.h>
40 #include <unistd.h>
41 #include <libgen.h>
42 #include <zone.h>
43 #include <sys/stat.h>
44 #include <sys/efi_partition.h>
45 #include <sys/systeminfo.h>
46 #include <sys/zfs_ioctl.h>
47 #include <sys/zfs_sysfs.h>
48 #include <sys/vdev_disk.h>
49 #include <sys/types.h>
50 #include <dlfcn.h>
51 #include <libzutil.h>
52 #include <fcntl.h>
53 
54 #include "zfs_namecheck.h"
55 #include "zfs_prop.h"
56 #include "libzfs_impl.h"
57 #include "zfs_comutil.h"
58 #include "zfeature_common.h"
59 
60 static boolean_t zpool_vdev_is_interior(const char *name);
61 
62 typedef struct prop_flags {
63 	int create:1;	/* Validate property on creation */
64 	int import:1;	/* Validate property on import */
65 	int vdevprop:1;	/* Validate property as a VDEV property */
66 } prop_flags_t;
67 
68 /*
69  * ====================================================================
70  *   zpool property functions
71  * ====================================================================
72  */
73 
74 static int
75 zpool_get_all_props(zpool_handle_t *zhp)
76 {
77 	zfs_cmd_t zc = {"\0"};
78 	libzfs_handle_t *hdl = zhp->zpool_hdl;
79 
80 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
81 
82 	zcmd_alloc_dst_nvlist(hdl, &zc, 0);
83 
84 	while (zfs_ioctl(hdl, ZFS_IOC_POOL_GET_PROPS, &zc) != 0) {
85 		if (errno == ENOMEM)
86 			zcmd_expand_dst_nvlist(hdl, &zc);
87 		else {
88 			zcmd_free_nvlists(&zc);
89 			return (-1);
90 		}
91 	}
92 
93 	if (zcmd_read_dst_nvlist(hdl, &zc, &zhp->zpool_props) != 0) {
94 		zcmd_free_nvlists(&zc);
95 		return (-1);
96 	}
97 
98 	zcmd_free_nvlists(&zc);
99 
100 	return (0);
101 }
102 
103 int
104 zpool_props_refresh(zpool_handle_t *zhp)
105 {
106 	nvlist_t *old_props;
107 
108 	old_props = zhp->zpool_props;
109 
110 	if (zpool_get_all_props(zhp) != 0)
111 		return (-1);
112 
113 	nvlist_free(old_props);
114 	return (0);
115 }
116 
117 static const char *
118 zpool_get_prop_string(zpool_handle_t *zhp, zpool_prop_t prop,
119     zprop_source_t *src)
120 {
121 	nvlist_t *nv, *nvl;
122 	const char *value;
123 	zprop_source_t source;
124 
125 	nvl = zhp->zpool_props;
126 	if (nvlist_lookup_nvlist(nvl, zpool_prop_to_name(prop), &nv) == 0) {
127 		source = fnvlist_lookup_uint64(nv, ZPROP_SOURCE);
128 		value = fnvlist_lookup_string(nv, ZPROP_VALUE);
129 	} else {
130 		source = ZPROP_SRC_DEFAULT;
131 		if ((value = zpool_prop_default_string(prop)) == NULL)
132 			value = "-";
133 	}
134 
135 	if (src)
136 		*src = source;
137 
138 	return (value);
139 }
140 
141 uint64_t
142 zpool_get_prop_int(zpool_handle_t *zhp, zpool_prop_t prop, zprop_source_t *src)
143 {
144 	nvlist_t *nv, *nvl;
145 	uint64_t value;
146 	zprop_source_t source;
147 
148 	if (zhp->zpool_props == NULL && zpool_get_all_props(zhp)) {
149 		/*
150 		 * zpool_get_all_props() has most likely failed because
151 		 * the pool is faulted, but if all we need is the top level
152 		 * vdev's guid then get it from the zhp config nvlist.
153 		 */
154 		if ((prop == ZPOOL_PROP_GUID) &&
155 		    (nvlist_lookup_nvlist(zhp->zpool_config,
156 		    ZPOOL_CONFIG_VDEV_TREE, &nv) == 0) &&
157 		    (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &value)
158 		    == 0)) {
159 			return (value);
160 		}
161 		return (zpool_prop_default_numeric(prop));
162 	}
163 
164 	nvl = zhp->zpool_props;
165 	if (nvlist_lookup_nvlist(nvl, zpool_prop_to_name(prop), &nv) == 0) {
166 		source = fnvlist_lookup_uint64(nv, ZPROP_SOURCE);
167 		value = fnvlist_lookup_uint64(nv, ZPROP_VALUE);
168 	} else {
169 		source = ZPROP_SRC_DEFAULT;
170 		value = zpool_prop_default_numeric(prop);
171 	}
172 
173 	if (src)
174 		*src = source;
175 
176 	return (value);
177 }
178 
179 /*
180  * Map VDEV STATE to printed strings.
181  */
182 const char *
183 zpool_state_to_name(vdev_state_t state, vdev_aux_t aux)
184 {
185 	switch (state) {
186 	case VDEV_STATE_CLOSED:
187 	case VDEV_STATE_OFFLINE:
188 		return (gettext("OFFLINE"));
189 	case VDEV_STATE_REMOVED:
190 		return (gettext("REMOVED"));
191 	case VDEV_STATE_CANT_OPEN:
192 		if (aux == VDEV_AUX_CORRUPT_DATA || aux == VDEV_AUX_BAD_LOG)
193 			return (gettext("FAULTED"));
194 		else if (aux == VDEV_AUX_SPLIT_POOL)
195 			return (gettext("SPLIT"));
196 		else
197 			return (gettext("UNAVAIL"));
198 	case VDEV_STATE_FAULTED:
199 		return (gettext("FAULTED"));
200 	case VDEV_STATE_DEGRADED:
201 		return (gettext("DEGRADED"));
202 	case VDEV_STATE_HEALTHY:
203 		return (gettext("ONLINE"));
204 
205 	default:
206 		break;
207 	}
208 
209 	return (gettext("UNKNOWN"));
210 }
211 
212 /*
213  * Map POOL STATE to printed strings.
214  */
215 const char *
216 zpool_pool_state_to_name(pool_state_t state)
217 {
218 	switch (state) {
219 	default:
220 		break;
221 	case POOL_STATE_ACTIVE:
222 		return (gettext("ACTIVE"));
223 	case POOL_STATE_EXPORTED:
224 		return (gettext("EXPORTED"));
225 	case POOL_STATE_DESTROYED:
226 		return (gettext("DESTROYED"));
227 	case POOL_STATE_SPARE:
228 		return (gettext("SPARE"));
229 	case POOL_STATE_L2CACHE:
230 		return (gettext("L2CACHE"));
231 	case POOL_STATE_UNINITIALIZED:
232 		return (gettext("UNINITIALIZED"));
233 	case POOL_STATE_UNAVAIL:
234 		return (gettext("UNAVAIL"));
235 	case POOL_STATE_POTENTIALLY_ACTIVE:
236 		return (gettext("POTENTIALLY_ACTIVE"));
237 	}
238 
239 	return (gettext("UNKNOWN"));
240 }
241 
242 /*
243  * Given a pool handle, return the pool health string ("ONLINE", "DEGRADED",
244  * "SUSPENDED", etc).
245  */
246 const char *
247 zpool_get_state_str(zpool_handle_t *zhp)
248 {
249 	zpool_errata_t errata;
250 	zpool_status_t status;
251 	const char *str;
252 
253 	status = zpool_get_status(zhp, NULL, &errata);
254 
255 	if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
256 		str = gettext("FAULTED");
257 	} else if (status == ZPOOL_STATUS_IO_FAILURE_WAIT ||
258 	    status == ZPOOL_STATUS_IO_FAILURE_MMP) {
259 		str = gettext("SUSPENDED");
260 	} else {
261 		nvlist_t *nvroot = fnvlist_lookup_nvlist(
262 		    zpool_get_config(zhp, NULL), ZPOOL_CONFIG_VDEV_TREE);
263 		uint_t vsc;
264 		vdev_stat_t *vs = (vdev_stat_t *)fnvlist_lookup_uint64_array(
265 		    nvroot, ZPOOL_CONFIG_VDEV_STATS, &vsc);
266 		str = zpool_state_to_name(vs->vs_state, vs->vs_aux);
267 	}
268 	return (str);
269 }
270 
271 /*
272  * Get a zpool property value for 'prop' and return the value in
273  * a pre-allocated buffer.
274  */
275 int
276 zpool_get_prop(zpool_handle_t *zhp, zpool_prop_t prop, char *buf,
277     size_t len, zprop_source_t *srctype, boolean_t literal)
278 {
279 	uint64_t intval;
280 	const char *strval;
281 	zprop_source_t src = ZPROP_SRC_NONE;
282 
283 	if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
284 		switch (prop) {
285 		case ZPOOL_PROP_NAME:
286 			(void) strlcpy(buf, zpool_get_name(zhp), len);
287 			break;
288 
289 		case ZPOOL_PROP_HEALTH:
290 			(void) strlcpy(buf, zpool_get_state_str(zhp), len);
291 			break;
292 
293 		case ZPOOL_PROP_GUID:
294 			intval = zpool_get_prop_int(zhp, prop, &src);
295 			(void) snprintf(buf, len, "%llu", (u_longlong_t)intval);
296 			break;
297 
298 		case ZPOOL_PROP_ALTROOT:
299 		case ZPOOL_PROP_CACHEFILE:
300 		case ZPOOL_PROP_COMMENT:
301 		case ZPOOL_PROP_COMPATIBILITY:
302 			if (zhp->zpool_props != NULL ||
303 			    zpool_get_all_props(zhp) == 0) {
304 				(void) strlcpy(buf,
305 				    zpool_get_prop_string(zhp, prop, &src),
306 				    len);
307 				break;
308 			}
309 			zfs_fallthrough;
310 		default:
311 			(void) strlcpy(buf, "-", len);
312 			break;
313 		}
314 
315 		if (srctype != NULL)
316 			*srctype = src;
317 		return (0);
318 	}
319 
320 	if (zhp->zpool_props == NULL && zpool_get_all_props(zhp) &&
321 	    prop != ZPOOL_PROP_NAME)
322 		return (-1);
323 
324 	switch (zpool_prop_get_type(prop)) {
325 	case PROP_TYPE_STRING:
326 		(void) strlcpy(buf, zpool_get_prop_string(zhp, prop, &src),
327 		    len);
328 		break;
329 
330 	case PROP_TYPE_NUMBER:
331 		intval = zpool_get_prop_int(zhp, prop, &src);
332 
333 		switch (prop) {
334 		case ZPOOL_PROP_SIZE:
335 		case ZPOOL_PROP_ALLOCATED:
336 		case ZPOOL_PROP_FREE:
337 		case ZPOOL_PROP_FREEING:
338 		case ZPOOL_PROP_LEAKED:
339 		case ZPOOL_PROP_ASHIFT:
340 		case ZPOOL_PROP_MAXBLOCKSIZE:
341 		case ZPOOL_PROP_MAXDNODESIZE:
342 			if (literal)
343 				(void) snprintf(buf, len, "%llu",
344 				    (u_longlong_t)intval);
345 			else
346 				(void) zfs_nicenum(intval, buf, len);
347 			break;
348 
349 		case ZPOOL_PROP_EXPANDSZ:
350 		case ZPOOL_PROP_CHECKPOINT:
351 			if (intval == 0) {
352 				(void) strlcpy(buf, "-", len);
353 			} else if (literal) {
354 				(void) snprintf(buf, len, "%llu",
355 				    (u_longlong_t)intval);
356 			} else {
357 				(void) zfs_nicebytes(intval, buf, len);
358 			}
359 			break;
360 
361 		case ZPOOL_PROP_CAPACITY:
362 			if (literal) {
363 				(void) snprintf(buf, len, "%llu",
364 				    (u_longlong_t)intval);
365 			} else {
366 				(void) snprintf(buf, len, "%llu%%",
367 				    (u_longlong_t)intval);
368 			}
369 			break;
370 
371 		case ZPOOL_PROP_FRAGMENTATION:
372 			if (intval == UINT64_MAX) {
373 				(void) strlcpy(buf, "-", len);
374 			} else if (literal) {
375 				(void) snprintf(buf, len, "%llu",
376 				    (u_longlong_t)intval);
377 			} else {
378 				(void) snprintf(buf, len, "%llu%%",
379 				    (u_longlong_t)intval);
380 			}
381 			break;
382 
383 		case ZPOOL_PROP_DEDUPRATIO:
384 			if (literal)
385 				(void) snprintf(buf, len, "%llu.%02llu",
386 				    (u_longlong_t)(intval / 100),
387 				    (u_longlong_t)(intval % 100));
388 			else
389 				(void) snprintf(buf, len, "%llu.%02llux",
390 				    (u_longlong_t)(intval / 100),
391 				    (u_longlong_t)(intval % 100));
392 			break;
393 
394 		case ZPOOL_PROP_HEALTH:
395 			(void) strlcpy(buf, zpool_get_state_str(zhp), len);
396 			break;
397 		case ZPOOL_PROP_VERSION:
398 			if (intval >= SPA_VERSION_FEATURES) {
399 				(void) snprintf(buf, len, "-");
400 				break;
401 			}
402 			zfs_fallthrough;
403 		default:
404 			(void) snprintf(buf, len, "%llu", (u_longlong_t)intval);
405 		}
406 		break;
407 
408 	case PROP_TYPE_INDEX:
409 		intval = zpool_get_prop_int(zhp, prop, &src);
410 		if (zpool_prop_index_to_string(prop, intval, &strval)
411 		    != 0)
412 			return (-1);
413 		(void) strlcpy(buf, strval, len);
414 		break;
415 
416 	default:
417 		abort();
418 	}
419 
420 	if (srctype)
421 		*srctype = src;
422 
423 	return (0);
424 }
425 
426 /*
427  * Check if the bootfs name has the same pool name as it is set to.
428  * Assuming bootfs is a valid dataset name.
429  */
430 static boolean_t
431 bootfs_name_valid(const char *pool, const char *bootfs)
432 {
433 	int len = strlen(pool);
434 	if (bootfs[0] == '\0')
435 		return (B_TRUE);
436 
437 	if (!zfs_name_valid(bootfs, ZFS_TYPE_FILESYSTEM|ZFS_TYPE_SNAPSHOT))
438 		return (B_FALSE);
439 
440 	if (strncmp(pool, bootfs, len) == 0 &&
441 	    (bootfs[len] == '/' || bootfs[len] == '\0'))
442 		return (B_TRUE);
443 
444 	return (B_FALSE);
445 }
446 
447 /*
448  * Given an nvlist of zpool properties to be set, validate that they are
449  * correct, and parse any numeric properties (index, boolean, etc) if they are
450  * specified as strings.
451  */
452 static nvlist_t *
453 zpool_valid_proplist(libzfs_handle_t *hdl, const char *poolname,
454     nvlist_t *props, uint64_t version, prop_flags_t flags, char *errbuf)
455 {
456 	nvpair_t *elem;
457 	nvlist_t *retprops;
458 	zpool_prop_t prop;
459 	char *strval;
460 	uint64_t intval;
461 	char *slash, *check;
462 	struct stat64 statbuf;
463 	zpool_handle_t *zhp;
464 	char report[1024];
465 
466 	if (nvlist_alloc(&retprops, NV_UNIQUE_NAME, 0) != 0) {
467 		(void) no_memory(hdl);
468 		return (NULL);
469 	}
470 
471 	elem = NULL;
472 	while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
473 		const char *propname = nvpair_name(elem);
474 
475 		if (flags.vdevprop && zpool_prop_vdev(propname)) {
476 			vdev_prop_t vprop = vdev_name_to_prop(propname);
477 
478 			if (vdev_prop_readonly(vprop)) {
479 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' "
480 				    "is readonly"), propname);
481 				(void) zfs_error(hdl, EZFS_PROPREADONLY,
482 				    errbuf);
483 				goto error;
484 			}
485 
486 			if (zprop_parse_value(hdl, elem, vprop, ZFS_TYPE_VDEV,
487 			    retprops, &strval, &intval, errbuf) != 0)
488 				goto error;
489 
490 			continue;
491 		} else if (flags.vdevprop && vdev_prop_user(propname)) {
492 			if (nvlist_add_nvpair(retprops, elem) != 0) {
493 				(void) no_memory(hdl);
494 				goto error;
495 			}
496 			continue;
497 		} else if (flags.vdevprop) {
498 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
499 			    "invalid property: '%s'"), propname);
500 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
501 			goto error;
502 		}
503 
504 		prop = zpool_name_to_prop(propname);
505 		if (prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname)) {
506 			int err;
507 			char *fname = strchr(propname, '@') + 1;
508 
509 			err = zfeature_lookup_name(fname, NULL);
510 			if (err != 0) {
511 				ASSERT3U(err, ==, ENOENT);
512 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
513 				    "feature '%s' unsupported by kernel"),
514 				    fname);
515 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
516 				goto error;
517 			}
518 
519 			if (nvpair_type(elem) != DATA_TYPE_STRING) {
520 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
521 				    "'%s' must be a string"), propname);
522 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
523 				goto error;
524 			}
525 
526 			(void) nvpair_value_string(elem, &strval);
527 			if (strcmp(strval, ZFS_FEATURE_ENABLED) != 0 &&
528 			    strcmp(strval, ZFS_FEATURE_DISABLED) != 0) {
529 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
530 				    "property '%s' can only be set to "
531 				    "'enabled' or 'disabled'"), propname);
532 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
533 				goto error;
534 			}
535 
536 			if (!flags.create &&
537 			    strcmp(strval, ZFS_FEATURE_DISABLED) == 0) {
538 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
539 				    "property '%s' can only be set to "
540 				    "'disabled' at creation time"), propname);
541 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
542 				goto error;
543 			}
544 
545 			if (nvlist_add_uint64(retprops, propname, 0) != 0) {
546 				(void) no_memory(hdl);
547 				goto error;
548 			}
549 			continue;
550 		}
551 
552 		/*
553 		 * Make sure this property is valid and applies to this type.
554 		 */
555 		if (prop == ZPOOL_PROP_INVAL) {
556 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
557 			    "invalid property '%s'"), propname);
558 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
559 			goto error;
560 		}
561 
562 		if (zpool_prop_readonly(prop)) {
563 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' "
564 			    "is readonly"), propname);
565 			(void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
566 			goto error;
567 		}
568 
569 		if (!flags.create && zpool_prop_setonce(prop)) {
570 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
571 			    "property '%s' can only be set at "
572 			    "creation time"), propname);
573 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
574 			goto error;
575 		}
576 
577 		if (zprop_parse_value(hdl, elem, prop, ZFS_TYPE_POOL, retprops,
578 		    &strval, &intval, errbuf) != 0)
579 			goto error;
580 
581 		/*
582 		 * Perform additional checking for specific properties.
583 		 */
584 		switch (prop) {
585 		case ZPOOL_PROP_VERSION:
586 			if (intval < version ||
587 			    !SPA_VERSION_IS_SUPPORTED(intval)) {
588 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
589 				    "property '%s' number %llu is invalid."),
590 				    propname, (unsigned long long)intval);
591 				(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
592 				goto error;
593 			}
594 			break;
595 
596 		case ZPOOL_PROP_ASHIFT:
597 			if (intval != 0 &&
598 			    (intval < ASHIFT_MIN || intval > ASHIFT_MAX)) {
599 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
600 				    "property '%s' number %llu is invalid, "
601 				    "only values between %" PRId32 " and %"
602 				    PRId32 " are allowed."),
603 				    propname, (unsigned long long)intval,
604 				    ASHIFT_MIN, ASHIFT_MAX);
605 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
606 				goto error;
607 			}
608 			break;
609 
610 		case ZPOOL_PROP_BOOTFS:
611 			if (flags.create || flags.import) {
612 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
613 				    "property '%s' cannot be set at creation "
614 				    "or import time"), propname);
615 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
616 				goto error;
617 			}
618 
619 			if (version < SPA_VERSION_BOOTFS) {
620 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
621 				    "pool must be upgraded to support "
622 				    "'%s' property"), propname);
623 				(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
624 				goto error;
625 			}
626 
627 			/*
628 			 * bootfs property value has to be a dataset name and
629 			 * the dataset has to be in the same pool as it sets to.
630 			 */
631 			if (!bootfs_name_valid(poolname, strval)) {
632 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' "
633 				    "is an invalid name"), strval);
634 				(void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
635 				goto error;
636 			}
637 
638 			if ((zhp = zpool_open_canfail(hdl, poolname)) == NULL) {
639 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
640 				    "could not open pool '%s'"), poolname);
641 				(void) zfs_error(hdl, EZFS_OPENFAILED, errbuf);
642 				goto error;
643 			}
644 			zpool_close(zhp);
645 			break;
646 
647 		case ZPOOL_PROP_ALTROOT:
648 			if (!flags.create && !flags.import) {
649 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
650 				    "property '%s' can only be set during pool "
651 				    "creation or import"), propname);
652 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
653 				goto error;
654 			}
655 
656 			if (strval[0] != '/') {
657 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
658 				    "bad alternate root '%s'"), strval);
659 				(void) zfs_error(hdl, EZFS_BADPATH, errbuf);
660 				goto error;
661 			}
662 			break;
663 
664 		case ZPOOL_PROP_CACHEFILE:
665 			if (strval[0] == '\0')
666 				break;
667 
668 			if (strcmp(strval, "none") == 0)
669 				break;
670 
671 			if (strval[0] != '/') {
672 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
673 				    "property '%s' must be empty, an "
674 				    "absolute path, or 'none'"), propname);
675 				(void) zfs_error(hdl, EZFS_BADPATH, errbuf);
676 				goto error;
677 			}
678 
679 			slash = strrchr(strval, '/');
680 
681 			if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
682 			    strcmp(slash, "/..") == 0) {
683 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
684 				    "'%s' is not a valid file"), strval);
685 				(void) zfs_error(hdl, EZFS_BADPATH, errbuf);
686 				goto error;
687 			}
688 
689 			*slash = '\0';
690 
691 			if (strval[0] != '\0' &&
692 			    (stat64(strval, &statbuf) != 0 ||
693 			    !S_ISDIR(statbuf.st_mode))) {
694 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
695 				    "'%s' is not a valid directory"),
696 				    strval);
697 				(void) zfs_error(hdl, EZFS_BADPATH, errbuf);
698 				goto error;
699 			}
700 
701 			*slash = '/';
702 			break;
703 
704 		case ZPOOL_PROP_COMPATIBILITY:
705 			switch (zpool_load_compat(strval, NULL, report, 1024)) {
706 			case ZPOOL_COMPATIBILITY_OK:
707 			case ZPOOL_COMPATIBILITY_WARNTOKEN:
708 				break;
709 			case ZPOOL_COMPATIBILITY_BADFILE:
710 			case ZPOOL_COMPATIBILITY_BADTOKEN:
711 			case ZPOOL_COMPATIBILITY_NOFILES:
712 				zfs_error_aux(hdl, "%s", report);
713 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
714 				goto error;
715 			}
716 			break;
717 
718 		case ZPOOL_PROP_COMMENT:
719 			for (check = strval; *check != '\0'; check++) {
720 				if (!isprint(*check)) {
721 					zfs_error_aux(hdl,
722 					    dgettext(TEXT_DOMAIN,
723 					    "comment may only have printable "
724 					    "characters"));
725 					(void) zfs_error(hdl, EZFS_BADPROP,
726 					    errbuf);
727 					goto error;
728 				}
729 			}
730 			if (strlen(strval) > ZPROP_MAX_COMMENT) {
731 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
732 				    "comment must not exceed %d characters"),
733 				    ZPROP_MAX_COMMENT);
734 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
735 				goto error;
736 			}
737 			break;
738 		case ZPOOL_PROP_READONLY:
739 			if (!flags.import) {
740 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
741 				    "property '%s' can only be set at "
742 				    "import time"), propname);
743 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
744 				goto error;
745 			}
746 			break;
747 		case ZPOOL_PROP_MULTIHOST:
748 			if (get_system_hostid() == 0) {
749 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
750 				    "requires a non-zero system hostid"));
751 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
752 				goto error;
753 			}
754 			break;
755 		case ZPOOL_PROP_DEDUPDITTO:
756 			printf("Note: property '%s' no longer has "
757 			    "any effect\n", propname);
758 			break;
759 
760 		default:
761 			break;
762 		}
763 	}
764 
765 	return (retprops);
766 error:
767 	nvlist_free(retprops);
768 	return (NULL);
769 }
770 
771 /*
772  * Set zpool property : propname=propval.
773  */
774 int
775 zpool_set_prop(zpool_handle_t *zhp, const char *propname, const char *propval)
776 {
777 	zfs_cmd_t zc = {"\0"};
778 	int ret = -1;
779 	char errbuf[ERRBUFLEN];
780 	nvlist_t *nvl = NULL;
781 	nvlist_t *realprops;
782 	uint64_t version;
783 	prop_flags_t flags = { 0 };
784 
785 	(void) snprintf(errbuf, sizeof (errbuf),
786 	    dgettext(TEXT_DOMAIN, "cannot set property for '%s'"),
787 	    zhp->zpool_name);
788 
789 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
790 		return (no_memory(zhp->zpool_hdl));
791 
792 	if (nvlist_add_string(nvl, propname, propval) != 0) {
793 		nvlist_free(nvl);
794 		return (no_memory(zhp->zpool_hdl));
795 	}
796 
797 	version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
798 	if ((realprops = zpool_valid_proplist(zhp->zpool_hdl,
799 	    zhp->zpool_name, nvl, version, flags, errbuf)) == NULL) {
800 		nvlist_free(nvl);
801 		return (-1);
802 	}
803 
804 	nvlist_free(nvl);
805 	nvl = realprops;
806 
807 	/*
808 	 * Execute the corresponding ioctl() to set this property.
809 	 */
810 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
811 
812 	zcmd_write_src_nvlist(zhp->zpool_hdl, &zc, nvl);
813 
814 	ret = zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_SET_PROPS, &zc);
815 
816 	zcmd_free_nvlists(&zc);
817 	nvlist_free(nvl);
818 
819 	if (ret)
820 		(void) zpool_standard_error(zhp->zpool_hdl, errno, errbuf);
821 	else
822 		(void) zpool_props_refresh(zhp);
823 
824 	return (ret);
825 }
826 
827 int
828 zpool_expand_proplist(zpool_handle_t *zhp, zprop_list_t **plp,
829     zfs_type_t type, boolean_t literal)
830 {
831 	libzfs_handle_t *hdl = zhp->zpool_hdl;
832 	zprop_list_t *entry;
833 	char buf[ZFS_MAXPROPLEN];
834 	nvlist_t *features = NULL;
835 	nvpair_t *nvp;
836 	zprop_list_t **last;
837 	boolean_t firstexpand = (NULL == *plp);
838 	int i;
839 
840 	if (zprop_expand_list(hdl, plp, type) != 0)
841 		return (-1);
842 
843 	if (type == ZFS_TYPE_VDEV)
844 		return (0);
845 
846 	last = plp;
847 	while (*last != NULL)
848 		last = &(*last)->pl_next;
849 
850 	if ((*plp)->pl_all)
851 		features = zpool_get_features(zhp);
852 
853 	if ((*plp)->pl_all && firstexpand) {
854 		for (i = 0; i < SPA_FEATURES; i++) {
855 			zprop_list_t *entry = zfs_alloc(hdl,
856 			    sizeof (zprop_list_t));
857 			entry->pl_prop = ZPROP_USERPROP;
858 			entry->pl_user_prop = zfs_asprintf(hdl, "feature@%s",
859 			    spa_feature_table[i].fi_uname);
860 			entry->pl_width = strlen(entry->pl_user_prop);
861 			entry->pl_all = B_TRUE;
862 
863 			*last = entry;
864 			last = &entry->pl_next;
865 		}
866 	}
867 
868 	/* add any unsupported features */
869 	for (nvp = nvlist_next_nvpair(features, NULL);
870 	    nvp != NULL; nvp = nvlist_next_nvpair(features, nvp)) {
871 		char *propname;
872 		boolean_t found;
873 		zprop_list_t *entry;
874 
875 		if (zfeature_is_supported(nvpair_name(nvp)))
876 			continue;
877 
878 		propname = zfs_asprintf(hdl, "unsupported@%s",
879 		    nvpair_name(nvp));
880 
881 		/*
882 		 * Before adding the property to the list make sure that no
883 		 * other pool already added the same property.
884 		 */
885 		found = B_FALSE;
886 		entry = *plp;
887 		while (entry != NULL) {
888 			if (entry->pl_user_prop != NULL &&
889 			    strcmp(propname, entry->pl_user_prop) == 0) {
890 				found = B_TRUE;
891 				break;
892 			}
893 			entry = entry->pl_next;
894 		}
895 		if (found) {
896 			free(propname);
897 			continue;
898 		}
899 
900 		entry = zfs_alloc(hdl, sizeof (zprop_list_t));
901 		entry->pl_prop = ZPROP_USERPROP;
902 		entry->pl_user_prop = propname;
903 		entry->pl_width = strlen(entry->pl_user_prop);
904 		entry->pl_all = B_TRUE;
905 
906 		*last = entry;
907 		last = &entry->pl_next;
908 	}
909 
910 	for (entry = *plp; entry != NULL; entry = entry->pl_next) {
911 		if (entry->pl_fixed && !literal)
912 			continue;
913 
914 		if (entry->pl_prop != ZPROP_USERPROP &&
915 		    zpool_get_prop(zhp, entry->pl_prop, buf, sizeof (buf),
916 		    NULL, literal) == 0) {
917 			if (strlen(buf) > entry->pl_width)
918 				entry->pl_width = strlen(buf);
919 		}
920 	}
921 
922 	return (0);
923 }
924 
925 int
926 vdev_expand_proplist(zpool_handle_t *zhp, const char *vdevname,
927     zprop_list_t **plp)
928 {
929 	zprop_list_t *entry;
930 	char buf[ZFS_MAXPROPLEN];
931 	char *strval = NULL;
932 	int err = 0;
933 	nvpair_t *elem = NULL;
934 	nvlist_t *vprops = NULL;
935 	nvlist_t *propval = NULL;
936 	const char *propname;
937 	vdev_prop_t prop;
938 	zprop_list_t **last;
939 
940 	for (entry = *plp; entry != NULL; entry = entry->pl_next) {
941 		if (entry->pl_fixed)
942 			continue;
943 
944 		if (zpool_get_vdev_prop(zhp, vdevname, entry->pl_prop,
945 		    entry->pl_user_prop, buf, sizeof (buf), NULL,
946 		    B_FALSE) == 0) {
947 			if (strlen(buf) > entry->pl_width)
948 				entry->pl_width = strlen(buf);
949 		}
950 		if (entry->pl_prop == VDEV_PROP_NAME &&
951 		    strlen(vdevname) > entry->pl_width)
952 			entry->pl_width = strlen(vdevname);
953 	}
954 
955 	/* Handle the all properties case */
956 	last = plp;
957 	if (*last != NULL && (*last)->pl_all == B_TRUE) {
958 		while (*last != NULL)
959 			last = &(*last)->pl_next;
960 
961 		err = zpool_get_all_vdev_props(zhp, vdevname, &vprops);
962 		if (err != 0)
963 			return (err);
964 
965 		while ((elem = nvlist_next_nvpair(vprops, elem)) != NULL) {
966 			propname = nvpair_name(elem);
967 
968 			/* Skip properties that are not user defined */
969 			if ((prop = vdev_name_to_prop(propname)) !=
970 			    VDEV_PROP_USERPROP)
971 				continue;
972 
973 			if (nvpair_value_nvlist(elem, &propval) != 0)
974 				continue;
975 
976 			strval = fnvlist_lookup_string(propval, ZPROP_VALUE);
977 
978 			entry = zfs_alloc(zhp->zpool_hdl,
979 			    sizeof (zprop_list_t));
980 			entry->pl_prop = prop;
981 			entry->pl_user_prop = zfs_strdup(zhp->zpool_hdl,
982 			    propname);
983 			entry->pl_width = strlen(strval);
984 			entry->pl_all = B_TRUE;
985 			*last = entry;
986 			last = &entry->pl_next;
987 		}
988 	}
989 
990 	return (0);
991 }
992 
993 /*
994  * Get the state for the given feature on the given ZFS pool.
995  */
996 int
997 zpool_prop_get_feature(zpool_handle_t *zhp, const char *propname, char *buf,
998     size_t len)
999 {
1000 	uint64_t refcount;
1001 	boolean_t found = B_FALSE;
1002 	nvlist_t *features = zpool_get_features(zhp);
1003 	boolean_t supported;
1004 	const char *feature = strchr(propname, '@') + 1;
1005 
1006 	supported = zpool_prop_feature(propname);
1007 	ASSERT(supported || zpool_prop_unsupported(propname));
1008 
1009 	/*
1010 	 * Convert from feature name to feature guid. This conversion is
1011 	 * unnecessary for unsupported@... properties because they already
1012 	 * use guids.
1013 	 */
1014 	if (supported) {
1015 		int ret;
1016 		spa_feature_t fid;
1017 
1018 		ret = zfeature_lookup_name(feature, &fid);
1019 		if (ret != 0) {
1020 			(void) strlcpy(buf, "-", len);
1021 			return (ENOTSUP);
1022 		}
1023 		feature = spa_feature_table[fid].fi_guid;
1024 	}
1025 
1026 	if (nvlist_lookup_uint64(features, feature, &refcount) == 0)
1027 		found = B_TRUE;
1028 
1029 	if (supported) {
1030 		if (!found) {
1031 			(void) strlcpy(buf, ZFS_FEATURE_DISABLED, len);
1032 		} else  {
1033 			if (refcount == 0)
1034 				(void) strlcpy(buf, ZFS_FEATURE_ENABLED, len);
1035 			else
1036 				(void) strlcpy(buf, ZFS_FEATURE_ACTIVE, len);
1037 		}
1038 	} else {
1039 		if (found) {
1040 			if (refcount == 0) {
1041 				(void) strcpy(buf, ZFS_UNSUPPORTED_INACTIVE);
1042 			} else {
1043 				(void) strcpy(buf, ZFS_UNSUPPORTED_READONLY);
1044 			}
1045 		} else {
1046 			(void) strlcpy(buf, "-", len);
1047 			return (ENOTSUP);
1048 		}
1049 	}
1050 
1051 	return (0);
1052 }
1053 
1054 /*
1055  * Validate the given pool name, optionally putting an extended error message in
1056  * 'buf'.
1057  */
1058 boolean_t
1059 zpool_name_valid(libzfs_handle_t *hdl, boolean_t isopen, const char *pool)
1060 {
1061 	namecheck_err_t why;
1062 	char what;
1063 	int ret;
1064 
1065 	ret = pool_namecheck(pool, &why, &what);
1066 
1067 	/*
1068 	 * The rules for reserved pool names were extended at a later point.
1069 	 * But we need to support users with existing pools that may now be
1070 	 * invalid.  So we only check for this expanded set of names during a
1071 	 * create (or import), and only in userland.
1072 	 */
1073 	if (ret == 0 && !isopen &&
1074 	    (strncmp(pool, "mirror", 6) == 0 ||
1075 	    strncmp(pool, "raidz", 5) == 0 ||
1076 	    strncmp(pool, "draid", 5) == 0 ||
1077 	    strncmp(pool, "spare", 5) == 0 ||
1078 	    strcmp(pool, "log") == 0)) {
1079 		if (hdl != NULL)
1080 			zfs_error_aux(hdl,
1081 			    dgettext(TEXT_DOMAIN, "name is reserved"));
1082 		return (B_FALSE);
1083 	}
1084 
1085 
1086 	if (ret != 0) {
1087 		if (hdl != NULL) {
1088 			switch (why) {
1089 			case NAME_ERR_TOOLONG:
1090 				zfs_error_aux(hdl,
1091 				    dgettext(TEXT_DOMAIN, "name is too long"));
1092 				break;
1093 
1094 			case NAME_ERR_INVALCHAR:
1095 				zfs_error_aux(hdl,
1096 				    dgettext(TEXT_DOMAIN, "invalid character "
1097 				    "'%c' in pool name"), what);
1098 				break;
1099 
1100 			case NAME_ERR_NOLETTER:
1101 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1102 				    "name must begin with a letter"));
1103 				break;
1104 
1105 			case NAME_ERR_RESERVED:
1106 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1107 				    "name is reserved"));
1108 				break;
1109 
1110 			case NAME_ERR_DISKLIKE:
1111 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1112 				    "pool name is reserved"));
1113 				break;
1114 
1115 			case NAME_ERR_LEADING_SLASH:
1116 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1117 				    "leading slash in name"));
1118 				break;
1119 
1120 			case NAME_ERR_EMPTY_COMPONENT:
1121 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1122 				    "empty component in name"));
1123 				break;
1124 
1125 			case NAME_ERR_TRAILING_SLASH:
1126 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1127 				    "trailing slash in name"));
1128 				break;
1129 
1130 			case NAME_ERR_MULTIPLE_DELIMITERS:
1131 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1132 				    "multiple '@' and/or '#' delimiters in "
1133 				    "name"));
1134 				break;
1135 
1136 			case NAME_ERR_NO_AT:
1137 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1138 				    "permission set is missing '@'"));
1139 				break;
1140 
1141 			default:
1142 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1143 				    "(%d) not defined"), why);
1144 				break;
1145 			}
1146 		}
1147 		return (B_FALSE);
1148 	}
1149 
1150 	return (B_TRUE);
1151 }
1152 
1153 /*
1154  * Open a handle to the given pool, even if the pool is currently in the FAULTED
1155  * state.
1156  */
1157 zpool_handle_t *
1158 zpool_open_canfail(libzfs_handle_t *hdl, const char *pool)
1159 {
1160 	zpool_handle_t *zhp;
1161 	boolean_t missing;
1162 
1163 	/*
1164 	 * Make sure the pool name is valid.
1165 	 */
1166 	if (!zpool_name_valid(hdl, B_TRUE, pool)) {
1167 		(void) zfs_error_fmt(hdl, EZFS_INVALIDNAME,
1168 		    dgettext(TEXT_DOMAIN, "cannot open '%s'"),
1169 		    pool);
1170 		return (NULL);
1171 	}
1172 
1173 	zhp = zfs_alloc(hdl, sizeof (zpool_handle_t));
1174 
1175 	zhp->zpool_hdl = hdl;
1176 	(void) strlcpy(zhp->zpool_name, pool, sizeof (zhp->zpool_name));
1177 
1178 	if (zpool_refresh_stats(zhp, &missing) != 0) {
1179 		zpool_close(zhp);
1180 		return (NULL);
1181 	}
1182 
1183 	if (missing) {
1184 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "no such pool"));
1185 		(void) zfs_error_fmt(hdl, EZFS_NOENT,
1186 		    dgettext(TEXT_DOMAIN, "cannot open '%s'"), pool);
1187 		zpool_close(zhp);
1188 		return (NULL);
1189 	}
1190 
1191 	return (zhp);
1192 }
1193 
1194 /*
1195  * Like the above, but silent on error.  Used when iterating over pools (because
1196  * the configuration cache may be out of date).
1197  */
1198 int
1199 zpool_open_silent(libzfs_handle_t *hdl, const char *pool, zpool_handle_t **ret)
1200 {
1201 	zpool_handle_t *zhp;
1202 	boolean_t missing;
1203 
1204 	zhp = zfs_alloc(hdl, sizeof (zpool_handle_t));
1205 
1206 	zhp->zpool_hdl = hdl;
1207 	(void) strlcpy(zhp->zpool_name, pool, sizeof (zhp->zpool_name));
1208 
1209 	if (zpool_refresh_stats(zhp, &missing) != 0) {
1210 		zpool_close(zhp);
1211 		return (-1);
1212 	}
1213 
1214 	if (missing) {
1215 		zpool_close(zhp);
1216 		*ret = NULL;
1217 		return (0);
1218 	}
1219 
1220 	*ret = zhp;
1221 	return (0);
1222 }
1223 
1224 /*
1225  * Similar to zpool_open_canfail(), but refuses to open pools in the faulted
1226  * state.
1227  */
1228 zpool_handle_t *
1229 zpool_open(libzfs_handle_t *hdl, const char *pool)
1230 {
1231 	zpool_handle_t *zhp;
1232 
1233 	if ((zhp = zpool_open_canfail(hdl, pool)) == NULL)
1234 		return (NULL);
1235 
1236 	if (zhp->zpool_state == POOL_STATE_UNAVAIL) {
1237 		(void) zfs_error_fmt(hdl, EZFS_POOLUNAVAIL,
1238 		    dgettext(TEXT_DOMAIN, "cannot open '%s'"), zhp->zpool_name);
1239 		zpool_close(zhp);
1240 		return (NULL);
1241 	}
1242 
1243 	return (zhp);
1244 }
1245 
1246 /*
1247  * Close the handle.  Simply frees the memory associated with the handle.
1248  */
1249 void
1250 zpool_close(zpool_handle_t *zhp)
1251 {
1252 	nvlist_free(zhp->zpool_config);
1253 	nvlist_free(zhp->zpool_old_config);
1254 	nvlist_free(zhp->zpool_props);
1255 	free(zhp);
1256 }
1257 
1258 /*
1259  * Return the name of the pool.
1260  */
1261 const char *
1262 zpool_get_name(zpool_handle_t *zhp)
1263 {
1264 	return (zhp->zpool_name);
1265 }
1266 
1267 
1268 /*
1269  * Return the state of the pool (ACTIVE or UNAVAILABLE)
1270  */
1271 int
1272 zpool_get_state(zpool_handle_t *zhp)
1273 {
1274 	return (zhp->zpool_state);
1275 }
1276 
1277 /*
1278  * Check if vdev list contains a special vdev
1279  */
1280 static boolean_t
1281 zpool_has_special_vdev(nvlist_t *nvroot)
1282 {
1283 	nvlist_t **child;
1284 	uint_t children;
1285 
1286 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN, &child,
1287 	    &children) == 0) {
1288 		for (uint_t c = 0; c < children; c++) {
1289 			char *bias;
1290 
1291 			if (nvlist_lookup_string(child[c],
1292 			    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias) == 0 &&
1293 			    strcmp(bias, VDEV_ALLOC_BIAS_SPECIAL) == 0) {
1294 				return (B_TRUE);
1295 			}
1296 		}
1297 	}
1298 	return (B_FALSE);
1299 }
1300 
1301 /*
1302  * Check if vdev list contains a dRAID vdev
1303  */
1304 static boolean_t
1305 zpool_has_draid_vdev(nvlist_t *nvroot)
1306 {
1307 	nvlist_t **child;
1308 	uint_t children;
1309 
1310 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
1311 	    &child, &children) == 0) {
1312 		for (uint_t c = 0; c < children; c++) {
1313 			char *type;
1314 
1315 			if (nvlist_lookup_string(child[c],
1316 			    ZPOOL_CONFIG_TYPE, &type) == 0 &&
1317 			    strcmp(type, VDEV_TYPE_DRAID) == 0) {
1318 				return (B_TRUE);
1319 			}
1320 		}
1321 	}
1322 	return (B_FALSE);
1323 }
1324 
1325 /*
1326  * Output a dRAID top-level vdev name in to the provided buffer.
1327  */
1328 static char *
1329 zpool_draid_name(char *name, int len, uint64_t data, uint64_t parity,
1330     uint64_t spares, uint64_t children)
1331 {
1332 	snprintf(name, len, "%s%llu:%llud:%lluc:%llus",
1333 	    VDEV_TYPE_DRAID, (u_longlong_t)parity, (u_longlong_t)data,
1334 	    (u_longlong_t)children, (u_longlong_t)spares);
1335 
1336 	return (name);
1337 }
1338 
1339 /*
1340  * Return B_TRUE if the provided name is a dRAID spare name.
1341  */
1342 boolean_t
1343 zpool_is_draid_spare(const char *name)
1344 {
1345 	uint64_t spare_id, parity, vdev_id;
1346 
1347 	if (sscanf(name, VDEV_TYPE_DRAID "%llu-%llu-%llu",
1348 	    (u_longlong_t *)&parity, (u_longlong_t *)&vdev_id,
1349 	    (u_longlong_t *)&spare_id) == 3) {
1350 		return (B_TRUE);
1351 	}
1352 
1353 	return (B_FALSE);
1354 }
1355 
1356 /*
1357  * Create the named pool, using the provided vdev list.  It is assumed
1358  * that the consumer has already validated the contents of the nvlist, so we
1359  * don't have to worry about error semantics.
1360  */
1361 int
1362 zpool_create(libzfs_handle_t *hdl, const char *pool, nvlist_t *nvroot,
1363     nvlist_t *props, nvlist_t *fsprops)
1364 {
1365 	zfs_cmd_t zc = {"\0"};
1366 	nvlist_t *zc_fsprops = NULL;
1367 	nvlist_t *zc_props = NULL;
1368 	nvlist_t *hidden_args = NULL;
1369 	uint8_t *wkeydata = NULL;
1370 	uint_t wkeylen = 0;
1371 	char errbuf[ERRBUFLEN];
1372 	int ret = -1;
1373 
1374 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1375 	    "cannot create '%s'"), pool);
1376 
1377 	if (!zpool_name_valid(hdl, B_FALSE, pool))
1378 		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
1379 
1380 	zcmd_write_conf_nvlist(hdl, &zc, nvroot);
1381 
1382 	if (props) {
1383 		prop_flags_t flags = { .create = B_TRUE, .import = B_FALSE };
1384 
1385 		if ((zc_props = zpool_valid_proplist(hdl, pool, props,
1386 		    SPA_VERSION_1, flags, errbuf)) == NULL) {
1387 			goto create_failed;
1388 		}
1389 	}
1390 
1391 	if (fsprops) {
1392 		uint64_t zoned;
1393 		char *zonestr;
1394 
1395 		zoned = ((nvlist_lookup_string(fsprops,
1396 		    zfs_prop_to_name(ZFS_PROP_ZONED), &zonestr) == 0) &&
1397 		    strcmp(zonestr, "on") == 0);
1398 
1399 		if ((zc_fsprops = zfs_valid_proplist(hdl, ZFS_TYPE_FILESYSTEM,
1400 		    fsprops, zoned, NULL, NULL, B_TRUE, errbuf)) == NULL) {
1401 			goto create_failed;
1402 		}
1403 
1404 		if (nvlist_exists(zc_fsprops,
1405 		    zfs_prop_to_name(ZFS_PROP_SPECIAL_SMALL_BLOCKS)) &&
1406 		    !zpool_has_special_vdev(nvroot)) {
1407 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1408 			    "%s property requires a special vdev"),
1409 			    zfs_prop_to_name(ZFS_PROP_SPECIAL_SMALL_BLOCKS));
1410 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1411 			goto create_failed;
1412 		}
1413 
1414 		if (!zc_props &&
1415 		    (nvlist_alloc(&zc_props, NV_UNIQUE_NAME, 0) != 0)) {
1416 			goto create_failed;
1417 		}
1418 		if (zfs_crypto_create(hdl, NULL, zc_fsprops, props, B_TRUE,
1419 		    &wkeydata, &wkeylen) != 0) {
1420 			zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf);
1421 			goto create_failed;
1422 		}
1423 		if (nvlist_add_nvlist(zc_props,
1424 		    ZPOOL_ROOTFS_PROPS, zc_fsprops) != 0) {
1425 			goto create_failed;
1426 		}
1427 		if (wkeydata != NULL) {
1428 			if (nvlist_alloc(&hidden_args, NV_UNIQUE_NAME, 0) != 0)
1429 				goto create_failed;
1430 
1431 			if (nvlist_add_uint8_array(hidden_args, "wkeydata",
1432 			    wkeydata, wkeylen) != 0)
1433 				goto create_failed;
1434 
1435 			if (nvlist_add_nvlist(zc_props, ZPOOL_HIDDEN_ARGS,
1436 			    hidden_args) != 0)
1437 				goto create_failed;
1438 		}
1439 	}
1440 
1441 	if (zc_props)
1442 		zcmd_write_src_nvlist(hdl, &zc, zc_props);
1443 
1444 	(void) strlcpy(zc.zc_name, pool, sizeof (zc.zc_name));
1445 
1446 	if ((ret = zfs_ioctl(hdl, ZFS_IOC_POOL_CREATE, &zc)) != 0) {
1447 
1448 		zcmd_free_nvlists(&zc);
1449 		nvlist_free(zc_props);
1450 		nvlist_free(zc_fsprops);
1451 		nvlist_free(hidden_args);
1452 		if (wkeydata != NULL)
1453 			free(wkeydata);
1454 
1455 		switch (errno) {
1456 		case EBUSY:
1457 			/*
1458 			 * This can happen if the user has specified the same
1459 			 * device multiple times.  We can't reliably detect this
1460 			 * until we try to add it and see we already have a
1461 			 * label.  This can also happen under if the device is
1462 			 * part of an active md or lvm device.
1463 			 */
1464 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1465 			    "one or more vdevs refer to the same device, or "
1466 			    "one of\nthe devices is part of an active md or "
1467 			    "lvm device"));
1468 			return (zfs_error(hdl, EZFS_BADDEV, errbuf));
1469 
1470 		case ERANGE:
1471 			/*
1472 			 * This happens if the record size is smaller or larger
1473 			 * than the allowed size range, or not a power of 2.
1474 			 *
1475 			 * NOTE: although zfs_valid_proplist is called earlier,
1476 			 * this case may have slipped through since the
1477 			 * pool does not exist yet and it is therefore
1478 			 * impossible to read properties e.g. max blocksize
1479 			 * from the pool.
1480 			 */
1481 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1482 			    "record size invalid"));
1483 			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
1484 
1485 		case EOVERFLOW:
1486 			/*
1487 			 * This occurs when one of the devices is below
1488 			 * SPA_MINDEVSIZE.  Unfortunately, we can't detect which
1489 			 * device was the problem device since there's no
1490 			 * reliable way to determine device size from userland.
1491 			 */
1492 			{
1493 				char buf[64];
1494 
1495 				zfs_nicebytes(SPA_MINDEVSIZE, buf,
1496 				    sizeof (buf));
1497 
1498 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1499 				    "one or more devices is less than the "
1500 				    "minimum size (%s)"), buf);
1501 			}
1502 			return (zfs_error(hdl, EZFS_BADDEV, errbuf));
1503 
1504 		case ENOSPC:
1505 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1506 			    "one or more devices is out of space"));
1507 			return (zfs_error(hdl, EZFS_BADDEV, errbuf));
1508 
1509 		case EINVAL:
1510 			if (zpool_has_draid_vdev(nvroot) &&
1511 			    zfeature_lookup_name("draid", NULL) != 0) {
1512 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1513 				    "dRAID vdevs are unsupported by the "
1514 				    "kernel"));
1515 				return (zfs_error(hdl, EZFS_BADDEV, errbuf));
1516 			} else {
1517 				return (zpool_standard_error(hdl, errno,
1518 				    errbuf));
1519 			}
1520 
1521 		default:
1522 			return (zpool_standard_error(hdl, errno, errbuf));
1523 		}
1524 	}
1525 
1526 create_failed:
1527 	zcmd_free_nvlists(&zc);
1528 	nvlist_free(zc_props);
1529 	nvlist_free(zc_fsprops);
1530 	nvlist_free(hidden_args);
1531 	if (wkeydata != NULL)
1532 		free(wkeydata);
1533 	return (ret);
1534 }
1535 
1536 /*
1537  * Destroy the given pool.  It is up to the caller to ensure that there are no
1538  * datasets left in the pool.
1539  */
1540 int
1541 zpool_destroy(zpool_handle_t *zhp, const char *log_str)
1542 {
1543 	zfs_cmd_t zc = {"\0"};
1544 	zfs_handle_t *zfp = NULL;
1545 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1546 	char errbuf[ERRBUFLEN];
1547 
1548 	if (zhp->zpool_state == POOL_STATE_ACTIVE &&
1549 	    (zfp = zfs_open(hdl, zhp->zpool_name, ZFS_TYPE_FILESYSTEM)) == NULL)
1550 		return (-1);
1551 
1552 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1553 	zc.zc_history = (uint64_t)(uintptr_t)log_str;
1554 
1555 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_DESTROY, &zc) != 0) {
1556 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1557 		    "cannot destroy '%s'"), zhp->zpool_name);
1558 
1559 		if (errno == EROFS) {
1560 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1561 			    "one or more devices is read only"));
1562 			(void) zfs_error(hdl, EZFS_BADDEV, errbuf);
1563 		} else {
1564 			(void) zpool_standard_error(hdl, errno, errbuf);
1565 		}
1566 
1567 		if (zfp)
1568 			zfs_close(zfp);
1569 		return (-1);
1570 	}
1571 
1572 	if (zfp) {
1573 		remove_mountpoint(zfp);
1574 		zfs_close(zfp);
1575 	}
1576 
1577 	return (0);
1578 }
1579 
1580 /*
1581  * Create a checkpoint in the given pool.
1582  */
1583 int
1584 zpool_checkpoint(zpool_handle_t *zhp)
1585 {
1586 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1587 	char errbuf[ERRBUFLEN];
1588 	int error;
1589 
1590 	error = lzc_pool_checkpoint(zhp->zpool_name);
1591 	if (error != 0) {
1592 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1593 		    "cannot checkpoint '%s'"), zhp->zpool_name);
1594 		(void) zpool_standard_error(hdl, error, errbuf);
1595 		return (-1);
1596 	}
1597 
1598 	return (0);
1599 }
1600 
1601 /*
1602  * Discard the checkpoint from the given pool.
1603  */
1604 int
1605 zpool_discard_checkpoint(zpool_handle_t *zhp)
1606 {
1607 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1608 	char errbuf[ERRBUFLEN];
1609 	int error;
1610 
1611 	error = lzc_pool_checkpoint_discard(zhp->zpool_name);
1612 	if (error != 0) {
1613 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1614 		    "cannot discard checkpoint in '%s'"), zhp->zpool_name);
1615 		(void) zpool_standard_error(hdl, error, errbuf);
1616 		return (-1);
1617 	}
1618 
1619 	return (0);
1620 }
1621 
1622 /*
1623  * Add the given vdevs to the pool.  The caller must have already performed the
1624  * necessary verification to ensure that the vdev specification is well-formed.
1625  */
1626 int
1627 zpool_add(zpool_handle_t *zhp, nvlist_t *nvroot)
1628 {
1629 	zfs_cmd_t zc = {"\0"};
1630 	int ret;
1631 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1632 	char errbuf[ERRBUFLEN];
1633 	nvlist_t **spares, **l2cache;
1634 	uint_t nspares, nl2cache;
1635 
1636 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1637 	    "cannot add to '%s'"), zhp->zpool_name);
1638 
1639 	if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) <
1640 	    SPA_VERSION_SPARES &&
1641 	    nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1642 	    &spares, &nspares) == 0) {
1643 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be "
1644 		    "upgraded to add hot spares"));
1645 		return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
1646 	}
1647 
1648 	if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) <
1649 	    SPA_VERSION_L2CACHE &&
1650 	    nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1651 	    &l2cache, &nl2cache) == 0) {
1652 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be "
1653 		    "upgraded to add cache devices"));
1654 		return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
1655 	}
1656 
1657 	zcmd_write_conf_nvlist(hdl, &zc, nvroot);
1658 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1659 
1660 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_ADD, &zc) != 0) {
1661 		switch (errno) {
1662 		case EBUSY:
1663 			/*
1664 			 * This can happen if the user has specified the same
1665 			 * device multiple times.  We can't reliably detect this
1666 			 * until we try to add it and see we already have a
1667 			 * label.
1668 			 */
1669 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1670 			    "one or more vdevs refer to the same device"));
1671 			(void) zfs_error(hdl, EZFS_BADDEV, errbuf);
1672 			break;
1673 
1674 		case EINVAL:
1675 
1676 			if (zpool_has_draid_vdev(nvroot) &&
1677 			    zfeature_lookup_name("draid", NULL) != 0) {
1678 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1679 				    "dRAID vdevs are unsupported by the "
1680 				    "kernel"));
1681 			} else {
1682 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1683 				    "invalid config; a pool with removing/"
1684 				    "removed vdevs does not support adding "
1685 				    "raidz or dRAID vdevs"));
1686 			}
1687 
1688 			(void) zfs_error(hdl, EZFS_BADDEV, errbuf);
1689 			break;
1690 
1691 		case EOVERFLOW:
1692 			/*
1693 			 * This occurs when one of the devices is below
1694 			 * SPA_MINDEVSIZE.  Unfortunately, we can't detect which
1695 			 * device was the problem device since there's no
1696 			 * reliable way to determine device size from userland.
1697 			 */
1698 			{
1699 				char buf[64];
1700 
1701 				zfs_nicebytes(SPA_MINDEVSIZE, buf,
1702 				    sizeof (buf));
1703 
1704 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1705 				    "device is less than the minimum "
1706 				    "size (%s)"), buf);
1707 			}
1708 			(void) zfs_error(hdl, EZFS_BADDEV, errbuf);
1709 			break;
1710 
1711 		case ENOTSUP:
1712 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1713 			    "pool must be upgraded to add these vdevs"));
1714 			(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
1715 			break;
1716 
1717 		default:
1718 			(void) zpool_standard_error(hdl, errno, errbuf);
1719 		}
1720 
1721 		ret = -1;
1722 	} else {
1723 		ret = 0;
1724 	}
1725 
1726 	zcmd_free_nvlists(&zc);
1727 
1728 	return (ret);
1729 }
1730 
1731 /*
1732  * Exports the pool from the system.  The caller must ensure that there are no
1733  * mounted datasets in the pool.
1734  */
1735 static int
1736 zpool_export_common(zpool_handle_t *zhp, boolean_t force, boolean_t hardforce,
1737     const char *log_str)
1738 {
1739 	zfs_cmd_t zc = {"\0"};
1740 
1741 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1742 	zc.zc_cookie = force;
1743 	zc.zc_guid = hardforce;
1744 	zc.zc_history = (uint64_t)(uintptr_t)log_str;
1745 
1746 	if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_EXPORT, &zc) != 0) {
1747 		switch (errno) {
1748 		case EXDEV:
1749 			zfs_error_aux(zhp->zpool_hdl, dgettext(TEXT_DOMAIN,
1750 			    "use '-f' to override the following errors:\n"
1751 			    "'%s' has an active shared spare which could be"
1752 			    " used by other pools once '%s' is exported."),
1753 			    zhp->zpool_name, zhp->zpool_name);
1754 			return (zfs_error_fmt(zhp->zpool_hdl, EZFS_ACTIVE_SPARE,
1755 			    dgettext(TEXT_DOMAIN, "cannot export '%s'"),
1756 			    zhp->zpool_name));
1757 		default:
1758 			return (zpool_standard_error_fmt(zhp->zpool_hdl, errno,
1759 			    dgettext(TEXT_DOMAIN, "cannot export '%s'"),
1760 			    zhp->zpool_name));
1761 		}
1762 	}
1763 
1764 	return (0);
1765 }
1766 
1767 int
1768 zpool_export(zpool_handle_t *zhp, boolean_t force, const char *log_str)
1769 {
1770 	return (zpool_export_common(zhp, force, B_FALSE, log_str));
1771 }
1772 
1773 int
1774 zpool_export_force(zpool_handle_t *zhp, const char *log_str)
1775 {
1776 	return (zpool_export_common(zhp, B_TRUE, B_TRUE, log_str));
1777 }
1778 
1779 static void
1780 zpool_rewind_exclaim(libzfs_handle_t *hdl, const char *name, boolean_t dryrun,
1781     nvlist_t *config)
1782 {
1783 	nvlist_t *nv = NULL;
1784 	uint64_t rewindto;
1785 	int64_t loss = -1;
1786 	struct tm t;
1787 	char timestr[128];
1788 
1789 	if (!hdl->libzfs_printerr || config == NULL)
1790 		return;
1791 
1792 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nv) != 0 ||
1793 	    nvlist_lookup_nvlist(nv, ZPOOL_CONFIG_REWIND_INFO, &nv) != 0) {
1794 		return;
1795 	}
1796 
1797 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_TIME, &rewindto) != 0)
1798 		return;
1799 	(void) nvlist_lookup_int64(nv, ZPOOL_CONFIG_REWIND_TIME, &loss);
1800 
1801 	if (localtime_r((time_t *)&rewindto, &t) != NULL &&
1802 	    strftime(timestr, 128, "%c", &t) != 0) {
1803 		if (dryrun) {
1804 			(void) printf(dgettext(TEXT_DOMAIN,
1805 			    "Would be able to return %s "
1806 			    "to its state as of %s.\n"),
1807 			    name, timestr);
1808 		} else {
1809 			(void) printf(dgettext(TEXT_DOMAIN,
1810 			    "Pool %s returned to its state as of %s.\n"),
1811 			    name, timestr);
1812 		}
1813 		if (loss > 120) {
1814 			(void) printf(dgettext(TEXT_DOMAIN,
1815 			    "%s approximately %lld "),
1816 			    dryrun ? "Would discard" : "Discarded",
1817 			    ((longlong_t)loss + 30) / 60);
1818 			(void) printf(dgettext(TEXT_DOMAIN,
1819 			    "minutes of transactions.\n"));
1820 		} else if (loss > 0) {
1821 			(void) printf(dgettext(TEXT_DOMAIN,
1822 			    "%s approximately %lld "),
1823 			    dryrun ? "Would discard" : "Discarded",
1824 			    (longlong_t)loss);
1825 			(void) printf(dgettext(TEXT_DOMAIN,
1826 			    "seconds of transactions.\n"));
1827 		}
1828 	}
1829 }
1830 
1831 void
1832 zpool_explain_recover(libzfs_handle_t *hdl, const char *name, int reason,
1833     nvlist_t *config)
1834 {
1835 	nvlist_t *nv = NULL;
1836 	int64_t loss = -1;
1837 	uint64_t edata = UINT64_MAX;
1838 	uint64_t rewindto;
1839 	struct tm t;
1840 	char timestr[128];
1841 
1842 	if (!hdl->libzfs_printerr)
1843 		return;
1844 
1845 	if (reason >= 0)
1846 		(void) printf(dgettext(TEXT_DOMAIN, "action: "));
1847 	else
1848 		(void) printf(dgettext(TEXT_DOMAIN, "\t"));
1849 
1850 	/* All attempted rewinds failed if ZPOOL_CONFIG_LOAD_TIME missing */
1851 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nv) != 0 ||
1852 	    nvlist_lookup_nvlist(nv, ZPOOL_CONFIG_REWIND_INFO, &nv) != 0 ||
1853 	    nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_TIME, &rewindto) != 0)
1854 		goto no_info;
1855 
1856 	(void) nvlist_lookup_int64(nv, ZPOOL_CONFIG_REWIND_TIME, &loss);
1857 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_DATA_ERRORS,
1858 	    &edata);
1859 
1860 	(void) printf(dgettext(TEXT_DOMAIN,
1861 	    "Recovery is possible, but will result in some data loss.\n"));
1862 
1863 	if (localtime_r((time_t *)&rewindto, &t) != NULL &&
1864 	    strftime(timestr, 128, "%c", &t) != 0) {
1865 		(void) printf(dgettext(TEXT_DOMAIN,
1866 		    "\tReturning the pool to its state as of %s\n"
1867 		    "\tshould correct the problem.  "),
1868 		    timestr);
1869 	} else {
1870 		(void) printf(dgettext(TEXT_DOMAIN,
1871 		    "\tReverting the pool to an earlier state "
1872 		    "should correct the problem.\n\t"));
1873 	}
1874 
1875 	if (loss > 120) {
1876 		(void) printf(dgettext(TEXT_DOMAIN,
1877 		    "Approximately %lld minutes of data\n"
1878 		    "\tmust be discarded, irreversibly.  "),
1879 		    ((longlong_t)loss + 30) / 60);
1880 	} else if (loss > 0) {
1881 		(void) printf(dgettext(TEXT_DOMAIN,
1882 		    "Approximately %lld seconds of data\n"
1883 		    "\tmust be discarded, irreversibly.  "),
1884 		    (longlong_t)loss);
1885 	}
1886 	if (edata != 0 && edata != UINT64_MAX) {
1887 		if (edata == 1) {
1888 			(void) printf(dgettext(TEXT_DOMAIN,
1889 			    "After rewind, at least\n"
1890 			    "\tone persistent user-data error will remain.  "));
1891 		} else {
1892 			(void) printf(dgettext(TEXT_DOMAIN,
1893 			    "After rewind, several\n"
1894 			    "\tpersistent user-data errors will remain.  "));
1895 		}
1896 	}
1897 	(void) printf(dgettext(TEXT_DOMAIN,
1898 	    "Recovery can be attempted\n\tby executing 'zpool %s -F %s'.  "),
1899 	    reason >= 0 ? "clear" : "import", name);
1900 
1901 	(void) printf(dgettext(TEXT_DOMAIN,
1902 	    "A scrub of the pool\n"
1903 	    "\tis strongly recommended after recovery.\n"));
1904 	return;
1905 
1906 no_info:
1907 	(void) printf(dgettext(TEXT_DOMAIN,
1908 	    "Destroy and re-create the pool from\n\ta backup source.\n"));
1909 }
1910 
1911 /*
1912  * zpool_import() is a contracted interface. Should be kept the same
1913  * if possible.
1914  *
1915  * Applications should use zpool_import_props() to import a pool with
1916  * new properties value to be set.
1917  */
1918 int
1919 zpool_import(libzfs_handle_t *hdl, nvlist_t *config, const char *newname,
1920     char *altroot)
1921 {
1922 	nvlist_t *props = NULL;
1923 	int ret;
1924 
1925 	if (altroot != NULL) {
1926 		if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
1927 			return (zfs_error_fmt(hdl, EZFS_NOMEM,
1928 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1929 			    newname));
1930 		}
1931 
1932 		if (nvlist_add_string(props,
1933 		    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), altroot) != 0 ||
1934 		    nvlist_add_string(props,
1935 		    zpool_prop_to_name(ZPOOL_PROP_CACHEFILE), "none") != 0) {
1936 			nvlist_free(props);
1937 			return (zfs_error_fmt(hdl, EZFS_NOMEM,
1938 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1939 			    newname));
1940 		}
1941 	}
1942 
1943 	ret = zpool_import_props(hdl, config, newname, props,
1944 	    ZFS_IMPORT_NORMAL);
1945 	nvlist_free(props);
1946 	return (ret);
1947 }
1948 
1949 static void
1950 print_vdev_tree(libzfs_handle_t *hdl, const char *name, nvlist_t *nv,
1951     int indent)
1952 {
1953 	nvlist_t **child;
1954 	uint_t c, children;
1955 	char *vname;
1956 	uint64_t is_log = 0;
1957 
1958 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG,
1959 	    &is_log);
1960 
1961 	if (name != NULL)
1962 		(void) printf("\t%*s%s%s\n", indent, "", name,
1963 		    is_log ? " [log]" : "");
1964 
1965 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1966 	    &child, &children) != 0)
1967 		return;
1968 
1969 	for (c = 0; c < children; c++) {
1970 		vname = zpool_vdev_name(hdl, NULL, child[c], VDEV_NAME_TYPE_ID);
1971 		print_vdev_tree(hdl, vname, child[c], indent + 2);
1972 		free(vname);
1973 	}
1974 }
1975 
1976 void
1977 zpool_print_unsup_feat(nvlist_t *config)
1978 {
1979 	nvlist_t *nvinfo, *unsup_feat;
1980 
1981 	nvinfo = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO);
1982 	unsup_feat = fnvlist_lookup_nvlist(nvinfo, ZPOOL_CONFIG_UNSUP_FEAT);
1983 
1984 	for (nvpair_t *nvp = nvlist_next_nvpair(unsup_feat, NULL);
1985 	    nvp != NULL; nvp = nvlist_next_nvpair(unsup_feat, nvp)) {
1986 		char *desc = fnvpair_value_string(nvp);
1987 		if (strlen(desc) > 0)
1988 			(void) printf("\t%s (%s)\n", nvpair_name(nvp), desc);
1989 		else
1990 			(void) printf("\t%s\n", nvpair_name(nvp));
1991 	}
1992 }
1993 
1994 /*
1995  * Import the given pool using the known configuration and a list of
1996  * properties to be set. The configuration should have come from
1997  * zpool_find_import(). The 'newname' parameters control whether the pool
1998  * is imported with a different name.
1999  */
2000 int
2001 zpool_import_props(libzfs_handle_t *hdl, nvlist_t *config, const char *newname,
2002     nvlist_t *props, int flags)
2003 {
2004 	zfs_cmd_t zc = {"\0"};
2005 	zpool_load_policy_t policy;
2006 	nvlist_t *nv = NULL;
2007 	nvlist_t *nvinfo = NULL;
2008 	nvlist_t *missing = NULL;
2009 	const char *thename;
2010 	char *origname;
2011 	int ret;
2012 	int error = 0;
2013 	char errbuf[ERRBUFLEN];
2014 
2015 	origname = fnvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME);
2016 
2017 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2018 	    "cannot import pool '%s'"), origname);
2019 
2020 	if (newname != NULL) {
2021 		if (!zpool_name_valid(hdl, B_FALSE, newname))
2022 			return (zfs_error_fmt(hdl, EZFS_INVALIDNAME,
2023 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
2024 			    newname));
2025 		thename = newname;
2026 	} else {
2027 		thename = origname;
2028 	}
2029 
2030 	if (props != NULL) {
2031 		uint64_t version;
2032 		prop_flags_t flags = { .create = B_FALSE, .import = B_TRUE };
2033 
2034 		version = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION);
2035 
2036 		if ((props = zpool_valid_proplist(hdl, origname,
2037 		    props, version, flags, errbuf)) == NULL)
2038 			return (-1);
2039 		zcmd_write_src_nvlist(hdl, &zc, props);
2040 		nvlist_free(props);
2041 	}
2042 
2043 	(void) strlcpy(zc.zc_name, thename, sizeof (zc.zc_name));
2044 
2045 	zc.zc_guid = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID);
2046 
2047 	zcmd_write_conf_nvlist(hdl, &zc, config);
2048 	zcmd_alloc_dst_nvlist(hdl, &zc, zc.zc_nvlist_conf_size * 2);
2049 
2050 	zc.zc_cookie = flags;
2051 	while ((ret = zfs_ioctl(hdl, ZFS_IOC_POOL_IMPORT, &zc)) != 0 &&
2052 	    errno == ENOMEM)
2053 		zcmd_expand_dst_nvlist(hdl, &zc);
2054 	if (ret != 0)
2055 		error = errno;
2056 
2057 	(void) zcmd_read_dst_nvlist(hdl, &zc, &nv);
2058 
2059 	zcmd_free_nvlists(&zc);
2060 
2061 	zpool_get_load_policy(config, &policy);
2062 
2063 	if (error) {
2064 		char desc[1024];
2065 		char aux[256];
2066 
2067 		/*
2068 		 * Dry-run failed, but we print out what success
2069 		 * looks like if we found a best txg
2070 		 */
2071 		if (policy.zlp_rewind & ZPOOL_TRY_REWIND) {
2072 			zpool_rewind_exclaim(hdl, newname ? origname : thename,
2073 			    B_TRUE, nv);
2074 			nvlist_free(nv);
2075 			return (-1);
2076 		}
2077 
2078 		if (newname == NULL)
2079 			(void) snprintf(desc, sizeof (desc),
2080 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
2081 			    thename);
2082 		else
2083 			(void) snprintf(desc, sizeof (desc),
2084 			    dgettext(TEXT_DOMAIN, "cannot import '%s' as '%s'"),
2085 			    origname, thename);
2086 
2087 		switch (error) {
2088 		case ENOTSUP:
2089 			if (nv != NULL && nvlist_lookup_nvlist(nv,
2090 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0 &&
2091 			    nvlist_exists(nvinfo, ZPOOL_CONFIG_UNSUP_FEAT)) {
2092 				(void) printf(dgettext(TEXT_DOMAIN, "This "
2093 				    "pool uses the following feature(s) not "
2094 				    "supported by this system:\n"));
2095 				zpool_print_unsup_feat(nv);
2096 				if (nvlist_exists(nvinfo,
2097 				    ZPOOL_CONFIG_CAN_RDONLY)) {
2098 					(void) printf(dgettext(TEXT_DOMAIN,
2099 					    "All unsupported features are only "
2100 					    "required for writing to the pool."
2101 					    "\nThe pool can be imported using "
2102 					    "'-o readonly=on'.\n"));
2103 				}
2104 			}
2105 			/*
2106 			 * Unsupported version.
2107 			 */
2108 			(void) zfs_error(hdl, EZFS_BADVERSION, desc);
2109 			break;
2110 
2111 		case EREMOTEIO:
2112 			if (nv != NULL && nvlist_lookup_nvlist(nv,
2113 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0) {
2114 				const char *hostname = "<unknown>";
2115 				uint64_t hostid = 0;
2116 				mmp_state_t mmp_state;
2117 
2118 				mmp_state = fnvlist_lookup_uint64(nvinfo,
2119 				    ZPOOL_CONFIG_MMP_STATE);
2120 
2121 				if (nvlist_exists(nvinfo,
2122 				    ZPOOL_CONFIG_MMP_HOSTNAME))
2123 					hostname = fnvlist_lookup_string(nvinfo,
2124 					    ZPOOL_CONFIG_MMP_HOSTNAME);
2125 
2126 				if (nvlist_exists(nvinfo,
2127 				    ZPOOL_CONFIG_MMP_HOSTID))
2128 					hostid = fnvlist_lookup_uint64(nvinfo,
2129 					    ZPOOL_CONFIG_MMP_HOSTID);
2130 
2131 				if (mmp_state == MMP_STATE_ACTIVE) {
2132 					(void) snprintf(aux, sizeof (aux),
2133 					    dgettext(TEXT_DOMAIN, "pool is imp"
2134 					    "orted on host '%s' (hostid=%lx).\n"
2135 					    "Export the pool on the other "
2136 					    "system, then run 'zpool import'."),
2137 					    hostname, (unsigned long) hostid);
2138 				} else if (mmp_state == MMP_STATE_NO_HOSTID) {
2139 					(void) snprintf(aux, sizeof (aux),
2140 					    dgettext(TEXT_DOMAIN, "pool has "
2141 					    "the multihost property on and "
2142 					    "the\nsystem's hostid is not set. "
2143 					    "Set a unique system hostid with "
2144 					    "the zgenhostid(8) command.\n"));
2145 				}
2146 
2147 				(void) zfs_error_aux(hdl, "%s", aux);
2148 			}
2149 			(void) zfs_error(hdl, EZFS_ACTIVE_POOL, desc);
2150 			break;
2151 
2152 		case EINVAL:
2153 			(void) zfs_error(hdl, EZFS_INVALCONFIG, desc);
2154 			break;
2155 
2156 		case EROFS:
2157 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2158 			    "one or more devices is read only"));
2159 			(void) zfs_error(hdl, EZFS_BADDEV, desc);
2160 			break;
2161 
2162 		case ENXIO:
2163 			if (nv && nvlist_lookup_nvlist(nv,
2164 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0 &&
2165 			    nvlist_lookup_nvlist(nvinfo,
2166 			    ZPOOL_CONFIG_MISSING_DEVICES, &missing) == 0) {
2167 				(void) printf(dgettext(TEXT_DOMAIN,
2168 				    "The devices below are missing or "
2169 				    "corrupted, use '-m' to import the pool "
2170 				    "anyway:\n"));
2171 				print_vdev_tree(hdl, NULL, missing, 2);
2172 				(void) printf("\n");
2173 			}
2174 			(void) zpool_standard_error(hdl, error, desc);
2175 			break;
2176 
2177 		case EEXIST:
2178 			(void) zpool_standard_error(hdl, error, desc);
2179 			break;
2180 
2181 		case EBUSY:
2182 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2183 			    "one or more devices are already in use\n"));
2184 			(void) zfs_error(hdl, EZFS_BADDEV, desc);
2185 			break;
2186 		case ENAMETOOLONG:
2187 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2188 			    "new name of at least one dataset is longer than "
2189 			    "the maximum allowable length"));
2190 			(void) zfs_error(hdl, EZFS_NAMETOOLONG, desc);
2191 			break;
2192 		default:
2193 			(void) zpool_standard_error(hdl, error, desc);
2194 			zpool_explain_recover(hdl,
2195 			    newname ? origname : thename, -error, nv);
2196 			break;
2197 		}
2198 
2199 		nvlist_free(nv);
2200 		ret = -1;
2201 	} else {
2202 		zpool_handle_t *zhp;
2203 
2204 		/*
2205 		 * This should never fail, but play it safe anyway.
2206 		 */
2207 		if (zpool_open_silent(hdl, thename, &zhp) != 0)
2208 			ret = -1;
2209 		else if (zhp != NULL)
2210 			zpool_close(zhp);
2211 		if (policy.zlp_rewind &
2212 		    (ZPOOL_DO_REWIND | ZPOOL_TRY_REWIND)) {
2213 			zpool_rewind_exclaim(hdl, newname ? origname : thename,
2214 			    ((policy.zlp_rewind & ZPOOL_TRY_REWIND) != 0), nv);
2215 		}
2216 		nvlist_free(nv);
2217 		return (0);
2218 	}
2219 
2220 	return (ret);
2221 }
2222 
2223 /*
2224  * Translate vdev names to guids.  If a vdev_path is determined to be
2225  * unsuitable then a vd_errlist is allocated and the vdev path and errno
2226  * are added to it.
2227  */
2228 static int
2229 zpool_translate_vdev_guids(zpool_handle_t *zhp, nvlist_t *vds,
2230     nvlist_t *vdev_guids, nvlist_t *guids_to_paths, nvlist_t **vd_errlist)
2231 {
2232 	nvlist_t *errlist = NULL;
2233 	int error = 0;
2234 
2235 	for (nvpair_t *elem = nvlist_next_nvpair(vds, NULL); elem != NULL;
2236 	    elem = nvlist_next_nvpair(vds, elem)) {
2237 		boolean_t spare, cache;
2238 
2239 		char *vd_path = nvpair_name(elem);
2240 		nvlist_t *tgt = zpool_find_vdev(zhp, vd_path, &spare, &cache,
2241 		    NULL);
2242 
2243 		if ((tgt == NULL) || cache || spare) {
2244 			if (errlist == NULL) {
2245 				errlist = fnvlist_alloc();
2246 				error = EINVAL;
2247 			}
2248 
2249 			uint64_t err = (tgt == NULL) ? EZFS_NODEVICE :
2250 			    (spare ? EZFS_ISSPARE : EZFS_ISL2CACHE);
2251 			fnvlist_add_int64(errlist, vd_path, err);
2252 			continue;
2253 		}
2254 
2255 		uint64_t guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
2256 		fnvlist_add_uint64(vdev_guids, vd_path, guid);
2257 
2258 		char msg[MAXNAMELEN];
2259 		(void) snprintf(msg, sizeof (msg), "%llu", (u_longlong_t)guid);
2260 		fnvlist_add_string(guids_to_paths, msg, vd_path);
2261 	}
2262 
2263 	if (error != 0) {
2264 		verify(errlist != NULL);
2265 		if (vd_errlist != NULL)
2266 			*vd_errlist = errlist;
2267 		else
2268 			fnvlist_free(errlist);
2269 	}
2270 
2271 	return (error);
2272 }
2273 
2274 static int
2275 xlate_init_err(int err)
2276 {
2277 	switch (err) {
2278 	case ENODEV:
2279 		return (EZFS_NODEVICE);
2280 	case EINVAL:
2281 	case EROFS:
2282 		return (EZFS_BADDEV);
2283 	case EBUSY:
2284 		return (EZFS_INITIALIZING);
2285 	case ESRCH:
2286 		return (EZFS_NO_INITIALIZE);
2287 	}
2288 	return (err);
2289 }
2290 
2291 /*
2292  * Begin, suspend, or cancel the initialization (initializing of all free
2293  * blocks) for the given vdevs in the given pool.
2294  */
2295 static int
2296 zpool_initialize_impl(zpool_handle_t *zhp, pool_initialize_func_t cmd_type,
2297     nvlist_t *vds, boolean_t wait)
2298 {
2299 	int err;
2300 
2301 	nvlist_t *vdev_guids = fnvlist_alloc();
2302 	nvlist_t *guids_to_paths = fnvlist_alloc();
2303 	nvlist_t *vd_errlist = NULL;
2304 	nvlist_t *errlist;
2305 	nvpair_t *elem;
2306 
2307 	err = zpool_translate_vdev_guids(zhp, vds, vdev_guids,
2308 	    guids_to_paths, &vd_errlist);
2309 
2310 	if (err != 0) {
2311 		verify(vd_errlist != NULL);
2312 		goto list_errors;
2313 	}
2314 
2315 	err = lzc_initialize(zhp->zpool_name, cmd_type,
2316 	    vdev_guids, &errlist);
2317 
2318 	if (err != 0) {
2319 		if (errlist != NULL) {
2320 			vd_errlist = fnvlist_lookup_nvlist(errlist,
2321 			    ZPOOL_INITIALIZE_VDEVS);
2322 			goto list_errors;
2323 		}
2324 		(void) zpool_standard_error(zhp->zpool_hdl, err,
2325 		    dgettext(TEXT_DOMAIN, "operation failed"));
2326 		goto out;
2327 	}
2328 
2329 	if (wait) {
2330 		for (elem = nvlist_next_nvpair(vdev_guids, NULL); elem != NULL;
2331 		    elem = nvlist_next_nvpair(vdev_guids, elem)) {
2332 
2333 			uint64_t guid = fnvpair_value_uint64(elem);
2334 
2335 			err = lzc_wait_tag(zhp->zpool_name,
2336 			    ZPOOL_WAIT_INITIALIZE, guid, NULL);
2337 			if (err != 0) {
2338 				(void) zpool_standard_error_fmt(zhp->zpool_hdl,
2339 				    err, dgettext(TEXT_DOMAIN, "error "
2340 				    "waiting for '%s' to initialize"),
2341 				    nvpair_name(elem));
2342 
2343 				goto out;
2344 			}
2345 		}
2346 	}
2347 	goto out;
2348 
2349 list_errors:
2350 	for (elem = nvlist_next_nvpair(vd_errlist, NULL); elem != NULL;
2351 	    elem = nvlist_next_nvpair(vd_errlist, elem)) {
2352 		int64_t vd_error = xlate_init_err(fnvpair_value_int64(elem));
2353 		char *path;
2354 
2355 		if (nvlist_lookup_string(guids_to_paths, nvpair_name(elem),
2356 		    &path) != 0)
2357 			path = nvpair_name(elem);
2358 
2359 		(void) zfs_error_fmt(zhp->zpool_hdl, vd_error,
2360 		    "cannot initialize '%s'", path);
2361 	}
2362 
2363 out:
2364 	fnvlist_free(vdev_guids);
2365 	fnvlist_free(guids_to_paths);
2366 
2367 	if (vd_errlist != NULL)
2368 		fnvlist_free(vd_errlist);
2369 
2370 	return (err == 0 ? 0 : -1);
2371 }
2372 
2373 int
2374 zpool_initialize(zpool_handle_t *zhp, pool_initialize_func_t cmd_type,
2375     nvlist_t *vds)
2376 {
2377 	return (zpool_initialize_impl(zhp, cmd_type, vds, B_FALSE));
2378 }
2379 
2380 int
2381 zpool_initialize_wait(zpool_handle_t *zhp, pool_initialize_func_t cmd_type,
2382     nvlist_t *vds)
2383 {
2384 	return (zpool_initialize_impl(zhp, cmd_type, vds, B_TRUE));
2385 }
2386 
2387 static int
2388 xlate_trim_err(int err)
2389 {
2390 	switch (err) {
2391 	case ENODEV:
2392 		return (EZFS_NODEVICE);
2393 	case EINVAL:
2394 	case EROFS:
2395 		return (EZFS_BADDEV);
2396 	case EBUSY:
2397 		return (EZFS_TRIMMING);
2398 	case ESRCH:
2399 		return (EZFS_NO_TRIM);
2400 	case EOPNOTSUPP:
2401 		return (EZFS_TRIM_NOTSUP);
2402 	}
2403 	return (err);
2404 }
2405 
2406 static int
2407 zpool_trim_wait(zpool_handle_t *zhp, nvlist_t *vdev_guids)
2408 {
2409 	int err;
2410 	nvpair_t *elem;
2411 
2412 	for (elem = nvlist_next_nvpair(vdev_guids, NULL); elem != NULL;
2413 	    elem = nvlist_next_nvpair(vdev_guids, elem)) {
2414 
2415 		uint64_t guid = fnvpair_value_uint64(elem);
2416 
2417 		err = lzc_wait_tag(zhp->zpool_name,
2418 		    ZPOOL_WAIT_TRIM, guid, NULL);
2419 		if (err != 0) {
2420 			(void) zpool_standard_error_fmt(zhp->zpool_hdl,
2421 			    err, dgettext(TEXT_DOMAIN, "error "
2422 			    "waiting to trim '%s'"), nvpair_name(elem));
2423 
2424 			return (err);
2425 		}
2426 	}
2427 	return (0);
2428 }
2429 
2430 /*
2431  * Check errlist and report any errors, omitting ones which should be
2432  * suppressed. Returns B_TRUE if any errors were reported.
2433  */
2434 static boolean_t
2435 check_trim_errs(zpool_handle_t *zhp, trimflags_t *trim_flags,
2436     nvlist_t *guids_to_paths, nvlist_t *vds, nvlist_t *errlist)
2437 {
2438 	nvpair_t *elem;
2439 	boolean_t reported_errs = B_FALSE;
2440 	int num_vds = 0;
2441 	int num_suppressed_errs = 0;
2442 
2443 	for (elem = nvlist_next_nvpair(vds, NULL);
2444 	    elem != NULL; elem = nvlist_next_nvpair(vds, elem)) {
2445 		num_vds++;
2446 	}
2447 
2448 	for (elem = nvlist_next_nvpair(errlist, NULL);
2449 	    elem != NULL; elem = nvlist_next_nvpair(errlist, elem)) {
2450 		int64_t vd_error = xlate_trim_err(fnvpair_value_int64(elem));
2451 		char *path;
2452 
2453 		/*
2454 		 * If only the pool was specified, and it was not a secure
2455 		 * trim then suppress warnings for individual vdevs which
2456 		 * do not support trimming.
2457 		 */
2458 		if (vd_error == EZFS_TRIM_NOTSUP &&
2459 		    trim_flags->fullpool &&
2460 		    !trim_flags->secure) {
2461 			num_suppressed_errs++;
2462 			continue;
2463 		}
2464 
2465 		reported_errs = B_TRUE;
2466 		if (nvlist_lookup_string(guids_to_paths, nvpair_name(elem),
2467 		    &path) != 0)
2468 			path = nvpair_name(elem);
2469 
2470 		(void) zfs_error_fmt(zhp->zpool_hdl, vd_error,
2471 		    "cannot trim '%s'", path);
2472 	}
2473 
2474 	if (num_suppressed_errs == num_vds) {
2475 		(void) zfs_error_aux(zhp->zpool_hdl, dgettext(TEXT_DOMAIN,
2476 		    "no devices in pool support trim operations"));
2477 		(void) (zfs_error(zhp->zpool_hdl, EZFS_TRIM_NOTSUP,
2478 		    dgettext(TEXT_DOMAIN, "cannot trim")));
2479 		reported_errs = B_TRUE;
2480 	}
2481 
2482 	return (reported_errs);
2483 }
2484 
2485 /*
2486  * Begin, suspend, or cancel the TRIM (discarding of all free blocks) for
2487  * the given vdevs in the given pool.
2488  */
2489 int
2490 zpool_trim(zpool_handle_t *zhp, pool_trim_func_t cmd_type, nvlist_t *vds,
2491     trimflags_t *trim_flags)
2492 {
2493 	int err;
2494 	int retval = 0;
2495 
2496 	nvlist_t *vdev_guids = fnvlist_alloc();
2497 	nvlist_t *guids_to_paths = fnvlist_alloc();
2498 	nvlist_t *errlist = NULL;
2499 
2500 	err = zpool_translate_vdev_guids(zhp, vds, vdev_guids,
2501 	    guids_to_paths, &errlist);
2502 	if (err != 0) {
2503 		check_trim_errs(zhp, trim_flags, guids_to_paths, vds, errlist);
2504 		retval = -1;
2505 		goto out;
2506 	}
2507 
2508 	err = lzc_trim(zhp->zpool_name, cmd_type, trim_flags->rate,
2509 	    trim_flags->secure, vdev_guids, &errlist);
2510 	if (err != 0) {
2511 		nvlist_t *vd_errlist;
2512 		if (errlist != NULL && nvlist_lookup_nvlist(errlist,
2513 		    ZPOOL_TRIM_VDEVS, &vd_errlist) == 0) {
2514 			if (check_trim_errs(zhp, trim_flags, guids_to_paths,
2515 			    vds, vd_errlist)) {
2516 				retval = -1;
2517 				goto out;
2518 			}
2519 		} else {
2520 			char errbuf[ERRBUFLEN];
2521 
2522 			(void) snprintf(errbuf, sizeof (errbuf),
2523 			    dgettext(TEXT_DOMAIN, "operation failed"));
2524 			zpool_standard_error(zhp->zpool_hdl, err, errbuf);
2525 			retval = -1;
2526 			goto out;
2527 		}
2528 	}
2529 
2530 
2531 	if (trim_flags->wait)
2532 		retval = zpool_trim_wait(zhp, vdev_guids);
2533 
2534 out:
2535 	if (errlist != NULL)
2536 		fnvlist_free(errlist);
2537 	fnvlist_free(vdev_guids);
2538 	fnvlist_free(guids_to_paths);
2539 	return (retval);
2540 }
2541 
2542 /*
2543  * Scan the pool.
2544  */
2545 int
2546 zpool_scan(zpool_handle_t *zhp, pool_scan_func_t func, pool_scrub_cmd_t cmd)
2547 {
2548 	zfs_cmd_t zc = {"\0"};
2549 	char errbuf[ERRBUFLEN];
2550 	int err;
2551 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2552 
2553 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2554 	zc.zc_cookie = func;
2555 	zc.zc_flags = cmd;
2556 
2557 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_SCAN, &zc) == 0)
2558 		return (0);
2559 
2560 	err = errno;
2561 
2562 	/* ECANCELED on a scrub means we resumed a paused scrub */
2563 	if (err == ECANCELED && func == POOL_SCAN_SCRUB &&
2564 	    cmd == POOL_SCRUB_NORMAL)
2565 		return (0);
2566 
2567 	if (err == ENOENT && func != POOL_SCAN_NONE && cmd == POOL_SCRUB_NORMAL)
2568 		return (0);
2569 
2570 	if (func == POOL_SCAN_SCRUB) {
2571 		if (cmd == POOL_SCRUB_PAUSE) {
2572 			(void) snprintf(errbuf, sizeof (errbuf),
2573 			    dgettext(TEXT_DOMAIN, "cannot pause scrubbing %s"),
2574 			    zc.zc_name);
2575 		} else {
2576 			assert(cmd == POOL_SCRUB_NORMAL);
2577 			(void) snprintf(errbuf, sizeof (errbuf),
2578 			    dgettext(TEXT_DOMAIN, "cannot scrub %s"),
2579 			    zc.zc_name);
2580 		}
2581 	} else if (func == POOL_SCAN_RESILVER) {
2582 		assert(cmd == POOL_SCRUB_NORMAL);
2583 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2584 		    "cannot restart resilver on %s"), zc.zc_name);
2585 	} else if (func == POOL_SCAN_NONE) {
2586 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2587 		    "cannot cancel scrubbing %s"), zc.zc_name);
2588 	} else {
2589 		assert(!"unexpected result");
2590 	}
2591 
2592 	if (err == EBUSY) {
2593 		nvlist_t *nvroot;
2594 		pool_scan_stat_t *ps = NULL;
2595 		uint_t psc;
2596 
2597 		nvroot = fnvlist_lookup_nvlist(zhp->zpool_config,
2598 		    ZPOOL_CONFIG_VDEV_TREE);
2599 		(void) nvlist_lookup_uint64_array(nvroot,
2600 		    ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &psc);
2601 		if (ps && ps->pss_func == POOL_SCAN_SCRUB &&
2602 		    ps->pss_state == DSS_SCANNING) {
2603 			if (cmd == POOL_SCRUB_PAUSE)
2604 				return (zfs_error(hdl, EZFS_SCRUB_PAUSED,
2605 				    errbuf));
2606 			else
2607 				return (zfs_error(hdl, EZFS_SCRUBBING, errbuf));
2608 		} else {
2609 			return (zfs_error(hdl, EZFS_RESILVERING, errbuf));
2610 		}
2611 	} else if (err == ENOENT) {
2612 		return (zfs_error(hdl, EZFS_NO_SCRUB, errbuf));
2613 	} else if (err == ENOTSUP && func == POOL_SCAN_RESILVER) {
2614 		return (zfs_error(hdl, EZFS_NO_RESILVER_DEFER, errbuf));
2615 	} else {
2616 		return (zpool_standard_error(hdl, err, errbuf));
2617 	}
2618 }
2619 
2620 /*
2621  * Find a vdev that matches the search criteria specified. We use the
2622  * the nvpair name to determine how we should look for the device.
2623  * 'avail_spare' is set to TRUE if the provided guid refers to an AVAIL
2624  * spare; but FALSE if its an INUSE spare.
2625  */
2626 static nvlist_t *
2627 vdev_to_nvlist_iter(nvlist_t *nv, nvlist_t *search, boolean_t *avail_spare,
2628     boolean_t *l2cache, boolean_t *log)
2629 {
2630 	uint_t c, children;
2631 	nvlist_t **child;
2632 	nvlist_t *ret;
2633 	uint64_t is_log;
2634 	char *srchkey;
2635 	nvpair_t *pair = nvlist_next_nvpair(search, NULL);
2636 
2637 	/* Nothing to look for */
2638 	if (search == NULL || pair == NULL)
2639 		return (NULL);
2640 
2641 	/* Obtain the key we will use to search */
2642 	srchkey = nvpair_name(pair);
2643 
2644 	switch (nvpair_type(pair)) {
2645 	case DATA_TYPE_UINT64:
2646 		if (strcmp(srchkey, ZPOOL_CONFIG_GUID) == 0) {
2647 			uint64_t srchval = fnvpair_value_uint64(pair);
2648 			uint64_t theguid = fnvlist_lookup_uint64(nv,
2649 			    ZPOOL_CONFIG_GUID);
2650 			if (theguid == srchval)
2651 				return (nv);
2652 		}
2653 		break;
2654 
2655 	case DATA_TYPE_STRING: {
2656 		char *srchval, *val;
2657 
2658 		srchval = fnvpair_value_string(pair);
2659 		if (nvlist_lookup_string(nv, srchkey, &val) != 0)
2660 			break;
2661 
2662 		/*
2663 		 * Search for the requested value. Special cases:
2664 		 *
2665 		 * - ZPOOL_CONFIG_PATH for whole disk entries.  These end in
2666 		 *   "-part1", or "p1".  The suffix is hidden from the user,
2667 		 *   but included in the string, so this matches around it.
2668 		 * - ZPOOL_CONFIG_PATH for short names zfs_strcmp_shortname()
2669 		 *   is used to check all possible expanded paths.
2670 		 * - looking for a top-level vdev name (i.e. ZPOOL_CONFIG_TYPE).
2671 		 *
2672 		 * Otherwise, all other searches are simple string compares.
2673 		 */
2674 		if (strcmp(srchkey, ZPOOL_CONFIG_PATH) == 0) {
2675 			uint64_t wholedisk = 0;
2676 
2677 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
2678 			    &wholedisk);
2679 			if (zfs_strcmp_pathname(srchval, val, wholedisk) == 0)
2680 				return (nv);
2681 
2682 		} else if (strcmp(srchkey, ZPOOL_CONFIG_TYPE) == 0 && val) {
2683 			char *type, *idx, *end, *p;
2684 			uint64_t id, vdev_id;
2685 
2686 			/*
2687 			 * Determine our vdev type, keeping in mind
2688 			 * that the srchval is composed of a type and
2689 			 * vdev id pair (i.e. mirror-4).
2690 			 */
2691 			if ((type = strdup(srchval)) == NULL)
2692 				return (NULL);
2693 
2694 			if ((p = strrchr(type, '-')) == NULL) {
2695 				free(type);
2696 				break;
2697 			}
2698 			idx = p + 1;
2699 			*p = '\0';
2700 
2701 			/*
2702 			 * If the types don't match then keep looking.
2703 			 */
2704 			if (strncmp(val, type, strlen(val)) != 0) {
2705 				free(type);
2706 				break;
2707 			}
2708 
2709 			verify(zpool_vdev_is_interior(type));
2710 
2711 			id = fnvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID);
2712 			errno = 0;
2713 			vdev_id = strtoull(idx, &end, 10);
2714 
2715 			/*
2716 			 * If we are looking for a raidz and a parity is
2717 			 * specified, make sure it matches.
2718 			 */
2719 			int rzlen = strlen(VDEV_TYPE_RAIDZ);
2720 			assert(rzlen == strlen(VDEV_TYPE_DRAID));
2721 			int typlen = strlen(type);
2722 			if ((strncmp(type, VDEV_TYPE_RAIDZ, rzlen) == 0 ||
2723 			    strncmp(type, VDEV_TYPE_DRAID, rzlen) == 0) &&
2724 			    typlen != rzlen) {
2725 				uint64_t vdev_parity;
2726 				int parity = *(type + rzlen) - '0';
2727 
2728 				if (parity <= 0 || parity > 3 ||
2729 				    (typlen - rzlen) != 1) {
2730 					/*
2731 					 * Nonsense parity specified, can
2732 					 * never match
2733 					 */
2734 					free(type);
2735 					return (NULL);
2736 				}
2737 				vdev_parity = fnvlist_lookup_uint64(nv,
2738 				    ZPOOL_CONFIG_NPARITY);
2739 				if ((int)vdev_parity != parity) {
2740 					free(type);
2741 					break;
2742 				}
2743 			}
2744 
2745 			free(type);
2746 			if (errno != 0)
2747 				return (NULL);
2748 
2749 			/*
2750 			 * Now verify that we have the correct vdev id.
2751 			 */
2752 			if (vdev_id == id)
2753 				return (nv);
2754 		}
2755 
2756 		/*
2757 		 * Common case
2758 		 */
2759 		if (strcmp(srchval, val) == 0)
2760 			return (nv);
2761 		break;
2762 	}
2763 
2764 	default:
2765 		break;
2766 	}
2767 
2768 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2769 	    &child, &children) != 0)
2770 		return (NULL);
2771 
2772 	for (c = 0; c < children; c++) {
2773 		if ((ret = vdev_to_nvlist_iter(child[c], search,
2774 		    avail_spare, l2cache, NULL)) != NULL) {
2775 			/*
2776 			 * The 'is_log' value is only set for the toplevel
2777 			 * vdev, not the leaf vdevs.  So we always lookup the
2778 			 * log device from the root of the vdev tree (where
2779 			 * 'log' is non-NULL).
2780 			 */
2781 			if (log != NULL &&
2782 			    nvlist_lookup_uint64(child[c],
2783 			    ZPOOL_CONFIG_IS_LOG, &is_log) == 0 &&
2784 			    is_log) {
2785 				*log = B_TRUE;
2786 			}
2787 			return (ret);
2788 		}
2789 	}
2790 
2791 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
2792 	    &child, &children) == 0) {
2793 		for (c = 0; c < children; c++) {
2794 			if ((ret = vdev_to_nvlist_iter(child[c], search,
2795 			    avail_spare, l2cache, NULL)) != NULL) {
2796 				*avail_spare = B_TRUE;
2797 				return (ret);
2798 			}
2799 		}
2800 	}
2801 
2802 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
2803 	    &child, &children) == 0) {
2804 		for (c = 0; c < children; c++) {
2805 			if ((ret = vdev_to_nvlist_iter(child[c], search,
2806 			    avail_spare, l2cache, NULL)) != NULL) {
2807 				*l2cache = B_TRUE;
2808 				return (ret);
2809 			}
2810 		}
2811 	}
2812 
2813 	return (NULL);
2814 }
2815 
2816 /*
2817  * Given a physical path or guid, find the associated vdev.
2818  */
2819 nvlist_t *
2820 zpool_find_vdev_by_physpath(zpool_handle_t *zhp, const char *ppath,
2821     boolean_t *avail_spare, boolean_t *l2cache, boolean_t *log)
2822 {
2823 	nvlist_t *search, *nvroot, *ret;
2824 	uint64_t guid;
2825 	char *end;
2826 
2827 	search = fnvlist_alloc();
2828 
2829 	guid = strtoull(ppath, &end, 0);
2830 	if (guid != 0 && *end == '\0') {
2831 		fnvlist_add_uint64(search, ZPOOL_CONFIG_GUID, guid);
2832 	} else {
2833 		fnvlist_add_string(search, ZPOOL_CONFIG_PHYS_PATH, ppath);
2834 	}
2835 
2836 	nvroot = fnvlist_lookup_nvlist(zhp->zpool_config,
2837 	    ZPOOL_CONFIG_VDEV_TREE);
2838 
2839 	*avail_spare = B_FALSE;
2840 	*l2cache = B_FALSE;
2841 	if (log != NULL)
2842 		*log = B_FALSE;
2843 	ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log);
2844 	fnvlist_free(search);
2845 
2846 	return (ret);
2847 }
2848 
2849 /*
2850  * Determine if we have an "interior" top-level vdev (i.e mirror/raidz).
2851  */
2852 static boolean_t
2853 zpool_vdev_is_interior(const char *name)
2854 {
2855 	if (strncmp(name, VDEV_TYPE_RAIDZ, strlen(VDEV_TYPE_RAIDZ)) == 0 ||
2856 	    strncmp(name, VDEV_TYPE_SPARE, strlen(VDEV_TYPE_SPARE)) == 0 ||
2857 	    strncmp(name,
2858 	    VDEV_TYPE_REPLACING, strlen(VDEV_TYPE_REPLACING)) == 0 ||
2859 	    strncmp(name, VDEV_TYPE_MIRROR, strlen(VDEV_TYPE_MIRROR)) == 0)
2860 		return (B_TRUE);
2861 
2862 	if (strncmp(name, VDEV_TYPE_DRAID, strlen(VDEV_TYPE_DRAID)) == 0 &&
2863 	    !zpool_is_draid_spare(name))
2864 		return (B_TRUE);
2865 
2866 	return (B_FALSE);
2867 }
2868 
2869 nvlist_t *
2870 zpool_find_vdev(zpool_handle_t *zhp, const char *path, boolean_t *avail_spare,
2871     boolean_t *l2cache, boolean_t *log)
2872 {
2873 	char *end;
2874 	nvlist_t *nvroot, *search, *ret;
2875 	uint64_t guid;
2876 
2877 	search = fnvlist_alloc();
2878 
2879 	guid = strtoull(path, &end, 0);
2880 	if (guid != 0 && *end == '\0') {
2881 		fnvlist_add_uint64(search, ZPOOL_CONFIG_GUID, guid);
2882 	} else if (zpool_vdev_is_interior(path)) {
2883 		fnvlist_add_string(search, ZPOOL_CONFIG_TYPE, path);
2884 	} else {
2885 		fnvlist_add_string(search, ZPOOL_CONFIG_PATH, path);
2886 	}
2887 
2888 	nvroot = fnvlist_lookup_nvlist(zhp->zpool_config,
2889 	    ZPOOL_CONFIG_VDEV_TREE);
2890 
2891 	*avail_spare = B_FALSE;
2892 	*l2cache = B_FALSE;
2893 	if (log != NULL)
2894 		*log = B_FALSE;
2895 	ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log);
2896 	fnvlist_free(search);
2897 
2898 	return (ret);
2899 }
2900 
2901 /*
2902  * Convert a vdev path to a GUID.  Returns GUID or 0 on error.
2903  *
2904  * If is_spare, is_l2cache, or is_log is non-NULL, then store within it
2905  * if the VDEV is a spare, l2cache, or log device.  If they're NULL then
2906  * ignore them.
2907  */
2908 static uint64_t
2909 zpool_vdev_path_to_guid_impl(zpool_handle_t *zhp, const char *path,
2910     boolean_t *is_spare, boolean_t *is_l2cache, boolean_t *is_log)
2911 {
2912 	boolean_t spare = B_FALSE, l2cache = B_FALSE, log = B_FALSE;
2913 	nvlist_t *tgt;
2914 
2915 	if ((tgt = zpool_find_vdev(zhp, path, &spare, &l2cache,
2916 	    &log)) == NULL)
2917 		return (0);
2918 
2919 	if (is_spare != NULL)
2920 		*is_spare = spare;
2921 	if (is_l2cache != NULL)
2922 		*is_l2cache = l2cache;
2923 	if (is_log != NULL)
2924 		*is_log = log;
2925 
2926 	return (fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID));
2927 }
2928 
2929 /* Convert a vdev path to a GUID.  Returns GUID or 0 on error. */
2930 uint64_t
2931 zpool_vdev_path_to_guid(zpool_handle_t *zhp, const char *path)
2932 {
2933 	return (zpool_vdev_path_to_guid_impl(zhp, path, NULL, NULL, NULL));
2934 }
2935 
2936 /*
2937  * Bring the specified vdev online.   The 'flags' parameter is a set of the
2938  * ZFS_ONLINE_* flags.
2939  */
2940 int
2941 zpool_vdev_online(zpool_handle_t *zhp, const char *path, int flags,
2942     vdev_state_t *newstate)
2943 {
2944 	zfs_cmd_t zc = {"\0"};
2945 	char errbuf[ERRBUFLEN];
2946 	nvlist_t *tgt;
2947 	boolean_t avail_spare, l2cache, islog;
2948 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2949 
2950 	if (flags & ZFS_ONLINE_EXPAND) {
2951 		(void) snprintf(errbuf, sizeof (errbuf),
2952 		    dgettext(TEXT_DOMAIN, "cannot expand %s"), path);
2953 	} else {
2954 		(void) snprintf(errbuf, sizeof (errbuf),
2955 		    dgettext(TEXT_DOMAIN, "cannot online %s"), path);
2956 	}
2957 
2958 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2959 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
2960 	    &islog)) == NULL)
2961 		return (zfs_error(hdl, EZFS_NODEVICE, errbuf));
2962 
2963 	zc.zc_guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
2964 
2965 	if (avail_spare)
2966 		return (zfs_error(hdl, EZFS_ISSPARE, errbuf));
2967 
2968 #ifndef __FreeBSD__
2969 	char *pathname;
2970 	if ((flags & ZFS_ONLINE_EXPAND ||
2971 	    zpool_get_prop_int(zhp, ZPOOL_PROP_AUTOEXPAND, NULL)) &&
2972 	    nvlist_lookup_string(tgt, ZPOOL_CONFIG_PATH, &pathname) == 0) {
2973 		uint64_t wholedisk = 0;
2974 
2975 		(void) nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_WHOLE_DISK,
2976 		    &wholedisk);
2977 
2978 		/*
2979 		 * XXX - L2ARC 1.0 devices can't support expansion.
2980 		 */
2981 		if (l2cache) {
2982 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2983 			    "cannot expand cache devices"));
2984 			return (zfs_error(hdl, EZFS_VDEVNOTSUP, errbuf));
2985 		}
2986 
2987 		if (wholedisk) {
2988 			const char *fullpath = path;
2989 			char buf[MAXPATHLEN];
2990 			int error;
2991 
2992 			if (path[0] != '/') {
2993 				error = zfs_resolve_shortname(path, buf,
2994 				    sizeof (buf));
2995 				if (error != 0)
2996 					return (zfs_error(hdl, EZFS_NODEVICE,
2997 					    errbuf));
2998 
2999 				fullpath = buf;
3000 			}
3001 
3002 			error = zpool_relabel_disk(hdl, fullpath, errbuf);
3003 			if (error != 0)
3004 				return (error);
3005 		}
3006 	}
3007 #endif
3008 
3009 	zc.zc_cookie = VDEV_STATE_ONLINE;
3010 	zc.zc_obj = flags;
3011 
3012 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) != 0) {
3013 		if (errno == EINVAL) {
3014 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "was split "
3015 			    "from this pool into a new one.  Use '%s' "
3016 			    "instead"), "zpool detach");
3017 			return (zfs_error(hdl, EZFS_POSTSPLIT_ONLINE, errbuf));
3018 		}
3019 		return (zpool_standard_error(hdl, errno, errbuf));
3020 	}
3021 
3022 	*newstate = zc.zc_cookie;
3023 	return (0);
3024 }
3025 
3026 /*
3027  * Take the specified vdev offline
3028  */
3029 int
3030 zpool_vdev_offline(zpool_handle_t *zhp, const char *path, boolean_t istmp)
3031 {
3032 	zfs_cmd_t zc = {"\0"};
3033 	char errbuf[ERRBUFLEN];
3034 	nvlist_t *tgt;
3035 	boolean_t avail_spare, l2cache;
3036 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3037 
3038 	(void) snprintf(errbuf, sizeof (errbuf),
3039 	    dgettext(TEXT_DOMAIN, "cannot offline %s"), path);
3040 
3041 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3042 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3043 	    NULL)) == NULL)
3044 		return (zfs_error(hdl, EZFS_NODEVICE, errbuf));
3045 
3046 	zc.zc_guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
3047 
3048 	if (avail_spare)
3049 		return (zfs_error(hdl, EZFS_ISSPARE, errbuf));
3050 
3051 	zc.zc_cookie = VDEV_STATE_OFFLINE;
3052 	zc.zc_obj = istmp ? ZFS_OFFLINE_TEMPORARY : 0;
3053 
3054 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
3055 		return (0);
3056 
3057 	switch (errno) {
3058 	case EBUSY:
3059 
3060 		/*
3061 		 * There are no other replicas of this device.
3062 		 */
3063 		return (zfs_error(hdl, EZFS_NOREPLICAS, errbuf));
3064 
3065 	case EEXIST:
3066 		/*
3067 		 * The log device has unplayed logs
3068 		 */
3069 		return (zfs_error(hdl, EZFS_UNPLAYED_LOGS, errbuf));
3070 
3071 	default:
3072 		return (zpool_standard_error(hdl, errno, errbuf));
3073 	}
3074 }
3075 
3076 /*
3077  * Remove the specified vdev asynchronously from the configuration, so
3078  * that it may come ONLINE if reinserted. This is called from zed on
3079  * Udev remove event.
3080  * Note: We also have a similar function zpool_vdev_remove() that
3081  * removes the vdev from the pool.
3082  */
3083 int
3084 zpool_vdev_remove_wanted(zpool_handle_t *zhp, const char *path)
3085 {
3086 	zfs_cmd_t zc = {"\0"};
3087 	char errbuf[ERRBUFLEN];
3088 	nvlist_t *tgt;
3089 	boolean_t avail_spare, l2cache;
3090 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3091 
3092 	(void) snprintf(errbuf, sizeof (errbuf),
3093 	    dgettext(TEXT_DOMAIN, "cannot remove %s"), path);
3094 
3095 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3096 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3097 	    NULL)) == NULL)
3098 		return (zfs_error(hdl, EZFS_NODEVICE, errbuf));
3099 
3100 	zc.zc_guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
3101 
3102 	if (avail_spare)
3103 		return (zfs_error(hdl, EZFS_ISSPARE, errbuf));
3104 
3105 	zc.zc_cookie = VDEV_STATE_REMOVED;
3106 
3107 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
3108 		return (0);
3109 
3110 	return (zpool_standard_error(hdl, errno, errbuf));
3111 }
3112 
3113 /*
3114  * Mark the given vdev faulted.
3115  */
3116 int
3117 zpool_vdev_fault(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux)
3118 {
3119 	zfs_cmd_t zc = {"\0"};
3120 	char errbuf[ERRBUFLEN];
3121 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3122 
3123 	(void) snprintf(errbuf, sizeof (errbuf),
3124 	    dgettext(TEXT_DOMAIN, "cannot fault %llu"), (u_longlong_t)guid);
3125 
3126 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3127 	zc.zc_guid = guid;
3128 	zc.zc_cookie = VDEV_STATE_FAULTED;
3129 	zc.zc_obj = aux;
3130 
3131 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
3132 		return (0);
3133 
3134 	switch (errno) {
3135 	case EBUSY:
3136 
3137 		/*
3138 		 * There are no other replicas of this device.
3139 		 */
3140 		return (zfs_error(hdl, EZFS_NOREPLICAS, errbuf));
3141 
3142 	default:
3143 		return (zpool_standard_error(hdl, errno, errbuf));
3144 	}
3145 
3146 }
3147 
3148 /*
3149  * Mark the given vdev degraded.
3150  */
3151 int
3152 zpool_vdev_degrade(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux)
3153 {
3154 	zfs_cmd_t zc = {"\0"};
3155 	char errbuf[ERRBUFLEN];
3156 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3157 
3158 	(void) snprintf(errbuf, sizeof (errbuf),
3159 	    dgettext(TEXT_DOMAIN, "cannot degrade %llu"), (u_longlong_t)guid);
3160 
3161 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3162 	zc.zc_guid = guid;
3163 	zc.zc_cookie = VDEV_STATE_DEGRADED;
3164 	zc.zc_obj = aux;
3165 
3166 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
3167 		return (0);
3168 
3169 	return (zpool_standard_error(hdl, errno, errbuf));
3170 }
3171 
3172 /*
3173  * Returns TRUE if the given nvlist is a vdev that was originally swapped in as
3174  * a hot spare.
3175  */
3176 static boolean_t
3177 is_replacing_spare(nvlist_t *search, nvlist_t *tgt, int which)
3178 {
3179 	nvlist_t **child;
3180 	uint_t c, children;
3181 
3182 	if (nvlist_lookup_nvlist_array(search, ZPOOL_CONFIG_CHILDREN, &child,
3183 	    &children) == 0) {
3184 		char *type = fnvlist_lookup_string(search, ZPOOL_CONFIG_TYPE);
3185 		if ((strcmp(type, VDEV_TYPE_SPARE) == 0 ||
3186 		    strcmp(type, VDEV_TYPE_DRAID_SPARE) == 0) &&
3187 		    children == 2 && child[which] == tgt)
3188 			return (B_TRUE);
3189 
3190 		for (c = 0; c < children; c++)
3191 			if (is_replacing_spare(child[c], tgt, which))
3192 				return (B_TRUE);
3193 	}
3194 
3195 	return (B_FALSE);
3196 }
3197 
3198 /*
3199  * Attach new_disk (fully described by nvroot) to old_disk.
3200  * If 'replacing' is specified, the new disk will replace the old one.
3201  */
3202 int
3203 zpool_vdev_attach(zpool_handle_t *zhp, const char *old_disk,
3204     const char *new_disk, nvlist_t *nvroot, int replacing, boolean_t rebuild)
3205 {
3206 	zfs_cmd_t zc = {"\0"};
3207 	char errbuf[ERRBUFLEN];
3208 	int ret;
3209 	nvlist_t *tgt;
3210 	boolean_t avail_spare, l2cache, islog;
3211 	uint64_t val;
3212 	char *newname;
3213 	nvlist_t **child;
3214 	uint_t children;
3215 	nvlist_t *config_root;
3216 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3217 
3218 	if (replacing)
3219 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3220 		    "cannot replace %s with %s"), old_disk, new_disk);
3221 	else
3222 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3223 		    "cannot attach %s to %s"), new_disk, old_disk);
3224 
3225 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3226 	if ((tgt = zpool_find_vdev(zhp, old_disk, &avail_spare, &l2cache,
3227 	    &islog)) == NULL)
3228 		return (zfs_error(hdl, EZFS_NODEVICE, errbuf));
3229 
3230 	if (avail_spare)
3231 		return (zfs_error(hdl, EZFS_ISSPARE, errbuf));
3232 
3233 	if (l2cache)
3234 		return (zfs_error(hdl, EZFS_ISL2CACHE, errbuf));
3235 
3236 	zc.zc_guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
3237 	zc.zc_cookie = replacing;
3238 	zc.zc_simple = rebuild;
3239 
3240 	if (rebuild &&
3241 	    zfeature_lookup_guid("org.openzfs:device_rebuild", NULL) != 0) {
3242 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3243 		    "the loaded zfs module doesn't support device rebuilds"));
3244 		return (zfs_error(hdl, EZFS_POOL_NOTSUP, errbuf));
3245 	}
3246 
3247 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
3248 	    &child, &children) != 0 || children != 1) {
3249 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3250 		    "new device must be a single disk"));
3251 		return (zfs_error(hdl, EZFS_INVALCONFIG, errbuf));
3252 	}
3253 
3254 	config_root = fnvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
3255 	    ZPOOL_CONFIG_VDEV_TREE);
3256 
3257 	if ((newname = zpool_vdev_name(NULL, NULL, child[0], 0)) == NULL)
3258 		return (-1);
3259 
3260 	/*
3261 	 * If the target is a hot spare that has been swapped in, we can only
3262 	 * replace it with another hot spare.
3263 	 */
3264 	if (replacing &&
3265 	    nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_IS_SPARE, &val) == 0 &&
3266 	    (zpool_find_vdev(zhp, newname, &avail_spare, &l2cache,
3267 	    NULL) == NULL || !avail_spare) &&
3268 	    is_replacing_spare(config_root, tgt, 1)) {
3269 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3270 		    "can only be replaced by another hot spare"));
3271 		free(newname);
3272 		return (zfs_error(hdl, EZFS_BADTARGET, errbuf));
3273 	}
3274 
3275 	free(newname);
3276 
3277 	zcmd_write_conf_nvlist(hdl, &zc, nvroot);
3278 
3279 	ret = zfs_ioctl(hdl, ZFS_IOC_VDEV_ATTACH, &zc);
3280 
3281 	zcmd_free_nvlists(&zc);
3282 
3283 	if (ret == 0)
3284 		return (0);
3285 
3286 	switch (errno) {
3287 	case ENOTSUP:
3288 		/*
3289 		 * Can't attach to or replace this type of vdev.
3290 		 */
3291 		if (replacing) {
3292 			uint64_t version = zpool_get_prop_int(zhp,
3293 			    ZPOOL_PROP_VERSION, NULL);
3294 
3295 			if (islog) {
3296 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3297 				    "cannot replace a log with a spare"));
3298 			} else if (rebuild) {
3299 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3300 				    "only mirror and dRAID vdevs support "
3301 				    "sequential reconstruction"));
3302 			} else if (zpool_is_draid_spare(new_disk)) {
3303 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3304 				    "dRAID spares can only replace child "
3305 				    "devices in their parent's dRAID vdev"));
3306 			} else if (version >= SPA_VERSION_MULTI_REPLACE) {
3307 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3308 				    "already in replacing/spare config; wait "
3309 				    "for completion or use 'zpool detach'"));
3310 			} else {
3311 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3312 				    "cannot replace a replacing device"));
3313 			}
3314 		} else {
3315 			char status[64] = {0};
3316 			zpool_prop_get_feature(zhp,
3317 			    "feature@device_rebuild", status, 63);
3318 			if (rebuild &&
3319 			    strncmp(status, ZFS_FEATURE_DISABLED, 64) == 0) {
3320 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3321 				    "device_rebuild feature must be enabled "
3322 				    "in order to use sequential "
3323 				    "reconstruction"));
3324 			} else {
3325 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3326 				    "can only attach to mirrors and top-level "
3327 				    "disks"));
3328 			}
3329 		}
3330 		(void) zfs_error(hdl, EZFS_BADTARGET, errbuf);
3331 		break;
3332 
3333 	case EINVAL:
3334 		/*
3335 		 * The new device must be a single disk.
3336 		 */
3337 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3338 		    "new device must be a single disk"));
3339 		(void) zfs_error(hdl, EZFS_INVALCONFIG, errbuf);
3340 		break;
3341 
3342 	case EBUSY:
3343 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "%s is busy, "
3344 		    "or device removal is in progress"),
3345 		    new_disk);
3346 		(void) zfs_error(hdl, EZFS_BADDEV, errbuf);
3347 		break;
3348 
3349 	case EOVERFLOW:
3350 		/*
3351 		 * The new device is too small.
3352 		 */
3353 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3354 		    "device is too small"));
3355 		(void) zfs_error(hdl, EZFS_BADDEV, errbuf);
3356 		break;
3357 
3358 	case EDOM:
3359 		/*
3360 		 * The new device has a different optimal sector size.
3361 		 */
3362 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3363 		    "new device has a different optimal sector size; use the "
3364 		    "option '-o ashift=N' to override the optimal size"));
3365 		(void) zfs_error(hdl, EZFS_BADDEV, errbuf);
3366 		break;
3367 
3368 	case ENAMETOOLONG:
3369 		/*
3370 		 * The resulting top-level vdev spec won't fit in the label.
3371 		 */
3372 		(void) zfs_error(hdl, EZFS_DEVOVERFLOW, errbuf);
3373 		break;
3374 
3375 	default:
3376 		(void) zpool_standard_error(hdl, errno, errbuf);
3377 	}
3378 
3379 	return (-1);
3380 }
3381 
3382 /*
3383  * Detach the specified device.
3384  */
3385 int
3386 zpool_vdev_detach(zpool_handle_t *zhp, const char *path)
3387 {
3388 	zfs_cmd_t zc = {"\0"};
3389 	char errbuf[ERRBUFLEN];
3390 	nvlist_t *tgt;
3391 	boolean_t avail_spare, l2cache;
3392 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3393 
3394 	(void) snprintf(errbuf, sizeof (errbuf),
3395 	    dgettext(TEXT_DOMAIN, "cannot detach %s"), path);
3396 
3397 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3398 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3399 	    NULL)) == NULL)
3400 		return (zfs_error(hdl, EZFS_NODEVICE, errbuf));
3401 
3402 	if (avail_spare)
3403 		return (zfs_error(hdl, EZFS_ISSPARE, errbuf));
3404 
3405 	if (l2cache)
3406 		return (zfs_error(hdl, EZFS_ISL2CACHE, errbuf));
3407 
3408 	zc.zc_guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
3409 
3410 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_DETACH, &zc) == 0)
3411 		return (0);
3412 
3413 	switch (errno) {
3414 
3415 	case ENOTSUP:
3416 		/*
3417 		 * Can't detach from this type of vdev.
3418 		 */
3419 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "only "
3420 		    "applicable to mirror and replacing vdevs"));
3421 		(void) zfs_error(hdl, EZFS_BADTARGET, errbuf);
3422 		break;
3423 
3424 	case EBUSY:
3425 		/*
3426 		 * There are no other replicas of this device.
3427 		 */
3428 		(void) zfs_error(hdl, EZFS_NOREPLICAS, errbuf);
3429 		break;
3430 
3431 	default:
3432 		(void) zpool_standard_error(hdl, errno, errbuf);
3433 	}
3434 
3435 	return (-1);
3436 }
3437 
3438 /*
3439  * Find a mirror vdev in the source nvlist.
3440  *
3441  * The mchild array contains a list of disks in one of the top-level mirrors
3442  * of the source pool.  The schild array contains a list of disks that the
3443  * user specified on the command line.  We loop over the mchild array to
3444  * see if any entry in the schild array matches.
3445  *
3446  * If a disk in the mchild array is found in the schild array, we return
3447  * the index of that entry.  Otherwise we return -1.
3448  */
3449 static int
3450 find_vdev_entry(zpool_handle_t *zhp, nvlist_t **mchild, uint_t mchildren,
3451     nvlist_t **schild, uint_t schildren)
3452 {
3453 	uint_t mc;
3454 
3455 	for (mc = 0; mc < mchildren; mc++) {
3456 		uint_t sc;
3457 		char *mpath = zpool_vdev_name(zhp->zpool_hdl, zhp,
3458 		    mchild[mc], 0);
3459 
3460 		for (sc = 0; sc < schildren; sc++) {
3461 			char *spath = zpool_vdev_name(zhp->zpool_hdl, zhp,
3462 			    schild[sc], 0);
3463 			boolean_t result = (strcmp(mpath, spath) == 0);
3464 
3465 			free(spath);
3466 			if (result) {
3467 				free(mpath);
3468 				return (mc);
3469 			}
3470 		}
3471 
3472 		free(mpath);
3473 	}
3474 
3475 	return (-1);
3476 }
3477 
3478 /*
3479  * Split a mirror pool.  If newroot points to null, then a new nvlist
3480  * is generated and it is the responsibility of the caller to free it.
3481  */
3482 int
3483 zpool_vdev_split(zpool_handle_t *zhp, char *newname, nvlist_t **newroot,
3484     nvlist_t *props, splitflags_t flags)
3485 {
3486 	zfs_cmd_t zc = {"\0"};
3487 	char errbuf[ERRBUFLEN], *bias;
3488 	nvlist_t *tree, *config, **child, **newchild, *newconfig = NULL;
3489 	nvlist_t **varray = NULL, *zc_props = NULL;
3490 	uint_t c, children, newchildren, lastlog = 0, vcount, found = 0;
3491 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3492 	uint64_t vers, readonly = B_FALSE;
3493 	boolean_t freelist = B_FALSE, memory_err = B_TRUE;
3494 	int retval = 0;
3495 
3496 	(void) snprintf(errbuf, sizeof (errbuf),
3497 	    dgettext(TEXT_DOMAIN, "Unable to split %s"), zhp->zpool_name);
3498 
3499 	if (!zpool_name_valid(hdl, B_FALSE, newname))
3500 		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3501 
3502 	if ((config = zpool_get_config(zhp, NULL)) == NULL) {
3503 		(void) fprintf(stderr, gettext("Internal error: unable to "
3504 		    "retrieve pool configuration\n"));
3505 		return (-1);
3506 	}
3507 
3508 	tree = fnvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE);
3509 	vers = fnvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION);
3510 
3511 	if (props) {
3512 		prop_flags_t flags = { .create = B_FALSE, .import = B_TRUE };
3513 		if ((zc_props = zpool_valid_proplist(hdl, zhp->zpool_name,
3514 		    props, vers, flags, errbuf)) == NULL)
3515 			return (-1);
3516 		(void) nvlist_lookup_uint64(zc_props,
3517 		    zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
3518 		if (readonly) {
3519 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3520 			    "property %s can only be set at import time"),
3521 			    zpool_prop_to_name(ZPOOL_PROP_READONLY));
3522 			return (-1);
3523 		}
3524 	}
3525 
3526 	if (nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN, &child,
3527 	    &children) != 0) {
3528 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3529 		    "Source pool is missing vdev tree"));
3530 		nvlist_free(zc_props);
3531 		return (-1);
3532 	}
3533 
3534 	varray = zfs_alloc(hdl, children * sizeof (nvlist_t *));
3535 	vcount = 0;
3536 
3537 	if (*newroot == NULL ||
3538 	    nvlist_lookup_nvlist_array(*newroot, ZPOOL_CONFIG_CHILDREN,
3539 	    &newchild, &newchildren) != 0)
3540 		newchildren = 0;
3541 
3542 	for (c = 0; c < children; c++) {
3543 		uint64_t is_log = B_FALSE, is_hole = B_FALSE;
3544 		boolean_t is_special = B_FALSE, is_dedup = B_FALSE;
3545 		char *type;
3546 		nvlist_t **mchild, *vdev;
3547 		uint_t mchildren;
3548 		int entry;
3549 
3550 		/*
3551 		 * Unlike cache & spares, slogs are stored in the
3552 		 * ZPOOL_CONFIG_CHILDREN array.  We filter them out here.
3553 		 */
3554 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3555 		    &is_log);
3556 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
3557 		    &is_hole);
3558 		if (is_log || is_hole) {
3559 			/*
3560 			 * Create a hole vdev and put it in the config.
3561 			 */
3562 			if (nvlist_alloc(&vdev, NV_UNIQUE_NAME, 0) != 0)
3563 				goto out;
3564 			if (nvlist_add_string(vdev, ZPOOL_CONFIG_TYPE,
3565 			    VDEV_TYPE_HOLE) != 0)
3566 				goto out;
3567 			if (nvlist_add_uint64(vdev, ZPOOL_CONFIG_IS_HOLE,
3568 			    1) != 0)
3569 				goto out;
3570 			if (lastlog == 0)
3571 				lastlog = vcount;
3572 			varray[vcount++] = vdev;
3573 			continue;
3574 		}
3575 		lastlog = 0;
3576 		type = fnvlist_lookup_string(child[c], ZPOOL_CONFIG_TYPE);
3577 
3578 		if (strcmp(type, VDEV_TYPE_INDIRECT) == 0) {
3579 			vdev = child[c];
3580 			if (nvlist_dup(vdev, &varray[vcount++], 0) != 0)
3581 				goto out;
3582 			continue;
3583 		} else if (strcmp(type, VDEV_TYPE_MIRROR) != 0) {
3584 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3585 			    "Source pool must be composed only of mirrors\n"));
3586 			retval = zfs_error(hdl, EZFS_INVALCONFIG, errbuf);
3587 			goto out;
3588 		}
3589 
3590 		if (nvlist_lookup_string(child[c],
3591 		    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias) == 0) {
3592 			if (strcmp(bias, VDEV_ALLOC_BIAS_SPECIAL) == 0)
3593 				is_special = B_TRUE;
3594 			else if (strcmp(bias, VDEV_ALLOC_BIAS_DEDUP) == 0)
3595 				is_dedup = B_TRUE;
3596 		}
3597 		verify(nvlist_lookup_nvlist_array(child[c],
3598 		    ZPOOL_CONFIG_CHILDREN, &mchild, &mchildren) == 0);
3599 
3600 		/* find or add an entry for this top-level vdev */
3601 		if (newchildren > 0 &&
3602 		    (entry = find_vdev_entry(zhp, mchild, mchildren,
3603 		    newchild, newchildren)) >= 0) {
3604 			/* We found a disk that the user specified. */
3605 			vdev = mchild[entry];
3606 			++found;
3607 		} else {
3608 			/* User didn't specify a disk for this vdev. */
3609 			vdev = mchild[mchildren - 1];
3610 		}
3611 
3612 		if (nvlist_dup(vdev, &varray[vcount++], 0) != 0)
3613 			goto out;
3614 
3615 		if (flags.dryrun != 0) {
3616 			if (is_dedup == B_TRUE) {
3617 				if (nvlist_add_string(varray[vcount - 1],
3618 				    ZPOOL_CONFIG_ALLOCATION_BIAS,
3619 				    VDEV_ALLOC_BIAS_DEDUP) != 0)
3620 					goto out;
3621 			} else if (is_special == B_TRUE) {
3622 				if (nvlist_add_string(varray[vcount - 1],
3623 				    ZPOOL_CONFIG_ALLOCATION_BIAS,
3624 				    VDEV_ALLOC_BIAS_SPECIAL) != 0)
3625 					goto out;
3626 			}
3627 		}
3628 	}
3629 
3630 	/* did we find every disk the user specified? */
3631 	if (found != newchildren) {
3632 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Device list must "
3633 		    "include at most one disk from each mirror"));
3634 		retval = zfs_error(hdl, EZFS_INVALCONFIG, errbuf);
3635 		goto out;
3636 	}
3637 
3638 	/* Prepare the nvlist for populating. */
3639 	if (*newroot == NULL) {
3640 		if (nvlist_alloc(newroot, NV_UNIQUE_NAME, 0) != 0)
3641 			goto out;
3642 		freelist = B_TRUE;
3643 		if (nvlist_add_string(*newroot, ZPOOL_CONFIG_TYPE,
3644 		    VDEV_TYPE_ROOT) != 0)
3645 			goto out;
3646 	} else {
3647 		verify(nvlist_remove_all(*newroot, ZPOOL_CONFIG_CHILDREN) == 0);
3648 	}
3649 
3650 	/* Add all the children we found */
3651 	if (nvlist_add_nvlist_array(*newroot, ZPOOL_CONFIG_CHILDREN,
3652 	    (const nvlist_t **)varray, lastlog == 0 ? vcount : lastlog) != 0)
3653 		goto out;
3654 
3655 	/*
3656 	 * If we're just doing a dry run, exit now with success.
3657 	 */
3658 	if (flags.dryrun) {
3659 		memory_err = B_FALSE;
3660 		freelist = B_FALSE;
3661 		goto out;
3662 	}
3663 
3664 	/* now build up the config list & call the ioctl */
3665 	if (nvlist_alloc(&newconfig, NV_UNIQUE_NAME, 0) != 0)
3666 		goto out;
3667 
3668 	if (nvlist_add_nvlist(newconfig,
3669 	    ZPOOL_CONFIG_VDEV_TREE, *newroot) != 0 ||
3670 	    nvlist_add_string(newconfig,
3671 	    ZPOOL_CONFIG_POOL_NAME, newname) != 0 ||
3672 	    nvlist_add_uint64(newconfig, ZPOOL_CONFIG_VERSION, vers) != 0)
3673 		goto out;
3674 
3675 	/*
3676 	 * The new pool is automatically part of the namespace unless we
3677 	 * explicitly export it.
3678 	 */
3679 	if (!flags.import)
3680 		zc.zc_cookie = ZPOOL_EXPORT_AFTER_SPLIT;
3681 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3682 	(void) strlcpy(zc.zc_string, newname, sizeof (zc.zc_string));
3683 	zcmd_write_conf_nvlist(hdl, &zc, newconfig);
3684 	if (zc_props != NULL)
3685 		zcmd_write_src_nvlist(hdl, &zc, zc_props);
3686 
3687 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SPLIT, &zc) != 0) {
3688 		retval = zpool_standard_error(hdl, errno, errbuf);
3689 		goto out;
3690 	}
3691 
3692 	freelist = B_FALSE;
3693 	memory_err = B_FALSE;
3694 
3695 out:
3696 	if (varray != NULL) {
3697 		int v;
3698 
3699 		for (v = 0; v < vcount; v++)
3700 			nvlist_free(varray[v]);
3701 		free(varray);
3702 	}
3703 	zcmd_free_nvlists(&zc);
3704 	nvlist_free(zc_props);
3705 	nvlist_free(newconfig);
3706 	if (freelist) {
3707 		nvlist_free(*newroot);
3708 		*newroot = NULL;
3709 	}
3710 
3711 	if (retval != 0)
3712 		return (retval);
3713 
3714 	if (memory_err)
3715 		return (no_memory(hdl));
3716 
3717 	return (0);
3718 }
3719 
3720 /*
3721  * Remove the given device.
3722  */
3723 int
3724 zpool_vdev_remove(zpool_handle_t *zhp, const char *path)
3725 {
3726 	zfs_cmd_t zc = {"\0"};
3727 	char errbuf[ERRBUFLEN];
3728 	nvlist_t *tgt;
3729 	boolean_t avail_spare, l2cache, islog;
3730 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3731 	uint64_t version;
3732 
3733 	(void) snprintf(errbuf, sizeof (errbuf),
3734 	    dgettext(TEXT_DOMAIN, "cannot remove %s"), path);
3735 
3736 	if (zpool_is_draid_spare(path)) {
3737 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3738 		    "dRAID spares cannot be removed"));
3739 		return (zfs_error(hdl, EZFS_NODEVICE, errbuf));
3740 	}
3741 
3742 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3743 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3744 	    &islog)) == NULL)
3745 		return (zfs_error(hdl, EZFS_NODEVICE, errbuf));
3746 
3747 	version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
3748 	if (islog && version < SPA_VERSION_HOLES) {
3749 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3750 		    "pool must be upgraded to support log removal"));
3751 		return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
3752 	}
3753 
3754 	zc.zc_guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
3755 
3756 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_REMOVE, &zc) == 0)
3757 		return (0);
3758 
3759 	switch (errno) {
3760 
3761 	case EINVAL:
3762 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3763 		    "invalid config; all top-level vdevs must "
3764 		    "have the same sector size and not be raidz."));
3765 		(void) zfs_error(hdl, EZFS_INVALCONFIG, errbuf);
3766 		break;
3767 
3768 	case EBUSY:
3769 		if (islog) {
3770 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3771 			    "Mount encrypted datasets to replay logs."));
3772 		} else {
3773 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3774 			    "Pool busy; removal may already be in progress"));
3775 		}
3776 		(void) zfs_error(hdl, EZFS_BUSY, errbuf);
3777 		break;
3778 
3779 	case EACCES:
3780 		if (islog) {
3781 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3782 			    "Mount encrypted datasets to replay logs."));
3783 			(void) zfs_error(hdl, EZFS_BUSY, errbuf);
3784 		} else {
3785 			(void) zpool_standard_error(hdl, errno, errbuf);
3786 		}
3787 		break;
3788 
3789 	default:
3790 		(void) zpool_standard_error(hdl, errno, errbuf);
3791 	}
3792 	return (-1);
3793 }
3794 
3795 int
3796 zpool_vdev_remove_cancel(zpool_handle_t *zhp)
3797 {
3798 	zfs_cmd_t zc = {{0}};
3799 	char errbuf[ERRBUFLEN];
3800 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3801 
3802 	(void) snprintf(errbuf, sizeof (errbuf),
3803 	    dgettext(TEXT_DOMAIN, "cannot cancel removal"));
3804 
3805 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3806 	zc.zc_cookie = 1;
3807 
3808 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_REMOVE, &zc) == 0)
3809 		return (0);
3810 
3811 	return (zpool_standard_error(hdl, errno, errbuf));
3812 }
3813 
3814 int
3815 zpool_vdev_indirect_size(zpool_handle_t *zhp, const char *path,
3816     uint64_t *sizep)
3817 {
3818 	char errbuf[ERRBUFLEN];
3819 	nvlist_t *tgt;
3820 	boolean_t avail_spare, l2cache, islog;
3821 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3822 
3823 	(void) snprintf(errbuf, sizeof (errbuf),
3824 	    dgettext(TEXT_DOMAIN, "cannot determine indirect size of %s"),
3825 	    path);
3826 
3827 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3828 	    &islog)) == NULL)
3829 		return (zfs_error(hdl, EZFS_NODEVICE, errbuf));
3830 
3831 	if (avail_spare || l2cache || islog) {
3832 		*sizep = 0;
3833 		return (0);
3834 	}
3835 
3836 	if (nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_INDIRECT_SIZE, sizep) != 0) {
3837 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3838 		    "indirect size not available"));
3839 		return (zfs_error(hdl, EINVAL, errbuf));
3840 	}
3841 	return (0);
3842 }
3843 
3844 /*
3845  * Clear the errors for the pool, or the particular device if specified.
3846  */
3847 int
3848 zpool_clear(zpool_handle_t *zhp, const char *path, nvlist_t *rewindnvl)
3849 {
3850 	zfs_cmd_t zc = {"\0"};
3851 	char errbuf[ERRBUFLEN];
3852 	nvlist_t *tgt;
3853 	zpool_load_policy_t policy;
3854 	boolean_t avail_spare, l2cache;
3855 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3856 	nvlist_t *nvi = NULL;
3857 	int error;
3858 
3859 	if (path)
3860 		(void) snprintf(errbuf, sizeof (errbuf),
3861 		    dgettext(TEXT_DOMAIN, "cannot clear errors for %s"),
3862 		    path);
3863 	else
3864 		(void) snprintf(errbuf, sizeof (errbuf),
3865 		    dgettext(TEXT_DOMAIN, "cannot clear errors for %s"),
3866 		    zhp->zpool_name);
3867 
3868 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3869 	if (path) {
3870 		if ((tgt = zpool_find_vdev(zhp, path, &avail_spare,
3871 		    &l2cache, NULL)) == NULL)
3872 			return (zfs_error(hdl, EZFS_NODEVICE, errbuf));
3873 
3874 		/*
3875 		 * Don't allow error clearing for hot spares.  Do allow
3876 		 * error clearing for l2cache devices.
3877 		 */
3878 		if (avail_spare)
3879 			return (zfs_error(hdl, EZFS_ISSPARE, errbuf));
3880 
3881 		zc.zc_guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
3882 	}
3883 
3884 	zpool_get_load_policy(rewindnvl, &policy);
3885 	zc.zc_cookie = policy.zlp_rewind;
3886 
3887 	zcmd_alloc_dst_nvlist(hdl, &zc, zhp->zpool_config_size * 2);
3888 	zcmd_write_src_nvlist(hdl, &zc, rewindnvl);
3889 
3890 	while ((error = zfs_ioctl(hdl, ZFS_IOC_CLEAR, &zc)) != 0 &&
3891 	    errno == ENOMEM)
3892 		zcmd_expand_dst_nvlist(hdl, &zc);
3893 
3894 	if (!error || ((policy.zlp_rewind & ZPOOL_TRY_REWIND) &&
3895 	    errno != EPERM && errno != EACCES)) {
3896 		if (policy.zlp_rewind &
3897 		    (ZPOOL_DO_REWIND | ZPOOL_TRY_REWIND)) {
3898 			(void) zcmd_read_dst_nvlist(hdl, &zc, &nvi);
3899 			zpool_rewind_exclaim(hdl, zc.zc_name,
3900 			    ((policy.zlp_rewind & ZPOOL_TRY_REWIND) != 0),
3901 			    nvi);
3902 			nvlist_free(nvi);
3903 		}
3904 		zcmd_free_nvlists(&zc);
3905 		return (0);
3906 	}
3907 
3908 	zcmd_free_nvlists(&zc);
3909 	return (zpool_standard_error(hdl, errno, errbuf));
3910 }
3911 
3912 /*
3913  * Similar to zpool_clear(), but takes a GUID (used by fmd).
3914  */
3915 int
3916 zpool_vdev_clear(zpool_handle_t *zhp, uint64_t guid)
3917 {
3918 	zfs_cmd_t zc = {"\0"};
3919 	char errbuf[ERRBUFLEN];
3920 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3921 
3922 	(void) snprintf(errbuf, sizeof (errbuf),
3923 	    dgettext(TEXT_DOMAIN, "cannot clear errors for %llx"),
3924 	    (u_longlong_t)guid);
3925 
3926 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3927 	zc.zc_guid = guid;
3928 	zc.zc_cookie = ZPOOL_NO_REWIND;
3929 
3930 	if (zfs_ioctl(hdl, ZFS_IOC_CLEAR, &zc) == 0)
3931 		return (0);
3932 
3933 	return (zpool_standard_error(hdl, errno, errbuf));
3934 }
3935 
3936 /*
3937  * Change the GUID for a pool.
3938  */
3939 int
3940 zpool_reguid(zpool_handle_t *zhp)
3941 {
3942 	char errbuf[ERRBUFLEN];
3943 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3944 	zfs_cmd_t zc = {"\0"};
3945 
3946 	(void) snprintf(errbuf, sizeof (errbuf),
3947 	    dgettext(TEXT_DOMAIN, "cannot reguid '%s'"), zhp->zpool_name);
3948 
3949 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3950 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_REGUID, &zc) == 0)
3951 		return (0);
3952 
3953 	return (zpool_standard_error(hdl, errno, errbuf));
3954 }
3955 
3956 /*
3957  * Reopen the pool.
3958  */
3959 int
3960 zpool_reopen_one(zpool_handle_t *zhp, void *data)
3961 {
3962 	libzfs_handle_t *hdl = zpool_get_handle(zhp);
3963 	const char *pool_name = zpool_get_name(zhp);
3964 	boolean_t *scrub_restart = data;
3965 	int error;
3966 
3967 	error = lzc_reopen(pool_name, *scrub_restart);
3968 	if (error) {
3969 		return (zpool_standard_error_fmt(hdl, error,
3970 		    dgettext(TEXT_DOMAIN, "cannot reopen '%s'"), pool_name));
3971 	}
3972 
3973 	return (0);
3974 }
3975 
3976 /* call into libzfs_core to execute the sync IOCTL per pool */
3977 int
3978 zpool_sync_one(zpool_handle_t *zhp, void *data)
3979 {
3980 	int ret;
3981 	libzfs_handle_t *hdl = zpool_get_handle(zhp);
3982 	const char *pool_name = zpool_get_name(zhp);
3983 	boolean_t *force = data;
3984 	nvlist_t *innvl = fnvlist_alloc();
3985 
3986 	fnvlist_add_boolean_value(innvl, "force", *force);
3987 	if ((ret = lzc_sync(pool_name, innvl, NULL)) != 0) {
3988 		nvlist_free(innvl);
3989 		return (zpool_standard_error_fmt(hdl, ret,
3990 		    dgettext(TEXT_DOMAIN, "sync '%s' failed"), pool_name));
3991 	}
3992 	nvlist_free(innvl);
3993 
3994 	return (0);
3995 }
3996 
3997 #define	PATH_BUF_LEN	64
3998 
3999 /*
4000  * Given a vdev, return the name to display in iostat.  If the vdev has a path,
4001  * we use that, stripping off any leading "/dev/dsk/"; if not, we use the type.
4002  * We also check if this is a whole disk, in which case we strip off the
4003  * trailing 's0' slice name.
4004  *
4005  * This routine is also responsible for identifying when disks have been
4006  * reconfigured in a new location.  The kernel will have opened the device by
4007  * devid, but the path will still refer to the old location.  To catch this, we
4008  * first do a path -> devid translation (which is fast for the common case).  If
4009  * the devid matches, we're done.  If not, we do a reverse devid -> path
4010  * translation and issue the appropriate ioctl() to update the path of the vdev.
4011  * If 'zhp' is NULL, then this is an exported pool, and we don't need to do any
4012  * of these checks.
4013  */
4014 char *
4015 zpool_vdev_name(libzfs_handle_t *hdl, zpool_handle_t *zhp, nvlist_t *nv,
4016     int name_flags)
4017 {
4018 	char *type, *tpath;
4019 	const char *path;
4020 	uint64_t value;
4021 	char buf[PATH_BUF_LEN];
4022 	char tmpbuf[PATH_BUF_LEN * 2];
4023 
4024 	/*
4025 	 * vdev_name will be "root"/"root-0" for the root vdev, but it is the
4026 	 * zpool name that will be displayed to the user.
4027 	 */
4028 	type = fnvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE);
4029 	if (zhp != NULL && strcmp(type, "root") == 0)
4030 		return (zfs_strdup(hdl, zpool_get_name(zhp)));
4031 
4032 	if (libzfs_envvar_is_set("ZPOOL_VDEV_NAME_PATH"))
4033 		name_flags |= VDEV_NAME_PATH;
4034 	if (libzfs_envvar_is_set("ZPOOL_VDEV_NAME_GUID"))
4035 		name_flags |= VDEV_NAME_GUID;
4036 	if (libzfs_envvar_is_set("ZPOOL_VDEV_NAME_FOLLOW_LINKS"))
4037 		name_flags |= VDEV_NAME_FOLLOW_LINKS;
4038 
4039 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT, &value) == 0 ||
4040 	    name_flags & VDEV_NAME_GUID) {
4041 		(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &value);
4042 		(void) snprintf(buf, sizeof (buf), "%llu", (u_longlong_t)value);
4043 		path = buf;
4044 	} else if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &tpath) == 0) {
4045 		path = tpath;
4046 
4047 		if (name_flags & VDEV_NAME_FOLLOW_LINKS) {
4048 			char *rp = realpath(path, NULL);
4049 			if (rp) {
4050 				strlcpy(buf, rp, sizeof (buf));
4051 				path = buf;
4052 				free(rp);
4053 			}
4054 		}
4055 
4056 		/*
4057 		 * For a block device only use the name.
4058 		 */
4059 		if ((strcmp(type, VDEV_TYPE_DISK) == 0) &&
4060 		    !(name_flags & VDEV_NAME_PATH)) {
4061 			path = zfs_strip_path(path);
4062 		}
4063 
4064 		/*
4065 		 * Remove the partition from the path if this is a whole disk.
4066 		 */
4067 		if (strcmp(type, VDEV_TYPE_DRAID_SPARE) != 0 &&
4068 		    nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK, &value)
4069 		    == 0 && value && !(name_flags & VDEV_NAME_PATH)) {
4070 			return (zfs_strip_partition(path));
4071 		}
4072 	} else {
4073 		path = type;
4074 
4075 		/*
4076 		 * If it's a raidz device, we need to stick in the parity level.
4077 		 */
4078 		if (strcmp(path, VDEV_TYPE_RAIDZ) == 0) {
4079 			value = fnvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY);
4080 			(void) snprintf(buf, sizeof (buf), "%s%llu", path,
4081 			    (u_longlong_t)value);
4082 			path = buf;
4083 		}
4084 
4085 		/*
4086 		 * If it's a dRAID device, we add parity, groups, and spares.
4087 		 */
4088 		if (strcmp(path, VDEV_TYPE_DRAID) == 0) {
4089 			uint64_t ndata, nparity, nspares;
4090 			nvlist_t **child;
4091 			uint_t children;
4092 
4093 			verify(nvlist_lookup_nvlist_array(nv,
4094 			    ZPOOL_CONFIG_CHILDREN, &child, &children) == 0);
4095 			nparity = fnvlist_lookup_uint64(nv,
4096 			    ZPOOL_CONFIG_NPARITY);
4097 			ndata = fnvlist_lookup_uint64(nv,
4098 			    ZPOOL_CONFIG_DRAID_NDATA);
4099 			nspares = fnvlist_lookup_uint64(nv,
4100 			    ZPOOL_CONFIG_DRAID_NSPARES);
4101 
4102 			path = zpool_draid_name(buf, sizeof (buf), ndata,
4103 			    nparity, nspares, children);
4104 		}
4105 
4106 		/*
4107 		 * We identify each top-level vdev by using a <type-id>
4108 		 * naming convention.
4109 		 */
4110 		if (name_flags & VDEV_NAME_TYPE_ID) {
4111 			uint64_t id = fnvlist_lookup_uint64(nv,
4112 			    ZPOOL_CONFIG_ID);
4113 			(void) snprintf(tmpbuf, sizeof (tmpbuf), "%s-%llu",
4114 			    path, (u_longlong_t)id);
4115 			path = tmpbuf;
4116 		}
4117 	}
4118 
4119 	return (zfs_strdup(hdl, path));
4120 }
4121 
4122 static int
4123 zbookmark_mem_compare(const void *a, const void *b)
4124 {
4125 	return (memcmp(a, b, sizeof (zbookmark_phys_t)));
4126 }
4127 
4128 /*
4129  * Retrieve the persistent error log, uniquify the members, and return to the
4130  * caller.
4131  */
4132 int
4133 zpool_get_errlog(zpool_handle_t *zhp, nvlist_t **nverrlistp)
4134 {
4135 	zfs_cmd_t zc = {"\0"};
4136 	libzfs_handle_t *hdl = zhp->zpool_hdl;
4137 	uint64_t count;
4138 	zbookmark_phys_t *zb = NULL;
4139 	int i;
4140 
4141 	/*
4142 	 * Retrieve the raw error list from the kernel.  If the number of errors
4143 	 * has increased, allocate more space and continue until we get the
4144 	 * entire list.
4145 	 */
4146 	count = fnvlist_lookup_uint64(zhp->zpool_config, ZPOOL_CONFIG_ERRCOUNT);
4147 	if (count == 0)
4148 		return (0);
4149 	zc.zc_nvlist_dst = (uintptr_t)zfs_alloc(zhp->zpool_hdl,
4150 	    count * sizeof (zbookmark_phys_t));
4151 	zc.zc_nvlist_dst_size = count;
4152 	(void) strcpy(zc.zc_name, zhp->zpool_name);
4153 	for (;;) {
4154 		if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_ERROR_LOG,
4155 		    &zc) != 0) {
4156 			free((void *)(uintptr_t)zc.zc_nvlist_dst);
4157 			if (errno == ENOMEM) {
4158 				void *dst;
4159 
4160 				count = zc.zc_nvlist_dst_size;
4161 				dst = zfs_alloc(zhp->zpool_hdl, count *
4162 				    sizeof (zbookmark_phys_t));
4163 				zc.zc_nvlist_dst = (uintptr_t)dst;
4164 			} else {
4165 				return (zpool_standard_error_fmt(hdl, errno,
4166 				    dgettext(TEXT_DOMAIN, "errors: List of "
4167 				    "errors unavailable")));
4168 			}
4169 		} else {
4170 			break;
4171 		}
4172 	}
4173 
4174 	/*
4175 	 * Sort the resulting bookmarks.  This is a little confusing due to the
4176 	 * implementation of ZFS_IOC_ERROR_LOG.  The bookmarks are copied last
4177 	 * to first, and 'zc_nvlist_dst_size' indicates the number of bookmarks
4178 	 * _not_ copied as part of the process.  So we point the start of our
4179 	 * array appropriate and decrement the total number of elements.
4180 	 */
4181 	zb = ((zbookmark_phys_t *)(uintptr_t)zc.zc_nvlist_dst) +
4182 	    zc.zc_nvlist_dst_size;
4183 	count -= zc.zc_nvlist_dst_size;
4184 
4185 	qsort(zb, count, sizeof (zbookmark_phys_t), zbookmark_mem_compare);
4186 
4187 	verify(nvlist_alloc(nverrlistp, 0, KM_SLEEP) == 0);
4188 
4189 	/*
4190 	 * Fill in the nverrlistp with nvlist's of dataset and object numbers.
4191 	 */
4192 	for (i = 0; i < count; i++) {
4193 		nvlist_t *nv;
4194 
4195 		/* ignoring zb_blkid and zb_level for now */
4196 		if (i > 0 && zb[i-1].zb_objset == zb[i].zb_objset &&
4197 		    zb[i-1].zb_object == zb[i].zb_object)
4198 			continue;
4199 
4200 		if (nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) != 0)
4201 			goto nomem;
4202 		if (nvlist_add_uint64(nv, ZPOOL_ERR_DATASET,
4203 		    zb[i].zb_objset) != 0) {
4204 			nvlist_free(nv);
4205 			goto nomem;
4206 		}
4207 		if (nvlist_add_uint64(nv, ZPOOL_ERR_OBJECT,
4208 		    zb[i].zb_object) != 0) {
4209 			nvlist_free(nv);
4210 			goto nomem;
4211 		}
4212 		if (nvlist_add_nvlist(*nverrlistp, "ejk", nv) != 0) {
4213 			nvlist_free(nv);
4214 			goto nomem;
4215 		}
4216 		nvlist_free(nv);
4217 	}
4218 
4219 	free((void *)(uintptr_t)zc.zc_nvlist_dst);
4220 	return (0);
4221 
4222 nomem:
4223 	free((void *)(uintptr_t)zc.zc_nvlist_dst);
4224 	return (no_memory(zhp->zpool_hdl));
4225 }
4226 
4227 /*
4228  * Upgrade a ZFS pool to the latest on-disk version.
4229  */
4230 int
4231 zpool_upgrade(zpool_handle_t *zhp, uint64_t new_version)
4232 {
4233 	zfs_cmd_t zc = {"\0"};
4234 	libzfs_handle_t *hdl = zhp->zpool_hdl;
4235 
4236 	(void) strcpy(zc.zc_name, zhp->zpool_name);
4237 	zc.zc_cookie = new_version;
4238 
4239 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_UPGRADE, &zc) != 0)
4240 		return (zpool_standard_error_fmt(hdl, errno,
4241 		    dgettext(TEXT_DOMAIN, "cannot upgrade '%s'"),
4242 		    zhp->zpool_name));
4243 	return (0);
4244 }
4245 
4246 void
4247 zfs_save_arguments(int argc, char **argv, char *string, int len)
4248 {
4249 	int i;
4250 
4251 	(void) strlcpy(string, zfs_basename(argv[0]), len);
4252 	for (i = 1; i < argc; i++) {
4253 		(void) strlcat(string, " ", len);
4254 		(void) strlcat(string, argv[i], len);
4255 	}
4256 }
4257 
4258 int
4259 zpool_log_history(libzfs_handle_t *hdl, const char *message)
4260 {
4261 	zfs_cmd_t zc = {"\0"};
4262 	nvlist_t *args;
4263 
4264 	args = fnvlist_alloc();
4265 	fnvlist_add_string(args, "message", message);
4266 	zcmd_write_src_nvlist(hdl, &zc, args);
4267 	int err = zfs_ioctl(hdl, ZFS_IOC_LOG_HISTORY, &zc);
4268 	nvlist_free(args);
4269 	zcmd_free_nvlists(&zc);
4270 	return (err);
4271 }
4272 
4273 /*
4274  * Perform ioctl to get some command history of a pool.
4275  *
4276  * 'buf' is the buffer to fill up to 'len' bytes.  'off' is the
4277  * logical offset of the history buffer to start reading from.
4278  *
4279  * Upon return, 'off' is the next logical offset to read from and
4280  * 'len' is the actual amount of bytes read into 'buf'.
4281  */
4282 static int
4283 get_history(zpool_handle_t *zhp, char *buf, uint64_t *off, uint64_t *len)
4284 {
4285 	zfs_cmd_t zc = {"\0"};
4286 	libzfs_handle_t *hdl = zhp->zpool_hdl;
4287 
4288 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
4289 
4290 	zc.zc_history = (uint64_t)(uintptr_t)buf;
4291 	zc.zc_history_len = *len;
4292 	zc.zc_history_offset = *off;
4293 
4294 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_GET_HISTORY, &zc) != 0) {
4295 		switch (errno) {
4296 		case EPERM:
4297 			return (zfs_error_fmt(hdl, EZFS_PERM,
4298 			    dgettext(TEXT_DOMAIN,
4299 			    "cannot show history for pool '%s'"),
4300 			    zhp->zpool_name));
4301 		case ENOENT:
4302 			return (zfs_error_fmt(hdl, EZFS_NOHISTORY,
4303 			    dgettext(TEXT_DOMAIN, "cannot get history for pool "
4304 			    "'%s'"), zhp->zpool_name));
4305 		case ENOTSUP:
4306 			return (zfs_error_fmt(hdl, EZFS_BADVERSION,
4307 			    dgettext(TEXT_DOMAIN, "cannot get history for pool "
4308 			    "'%s', pool must be upgraded"), zhp->zpool_name));
4309 		default:
4310 			return (zpool_standard_error_fmt(hdl, errno,
4311 			    dgettext(TEXT_DOMAIN,
4312 			    "cannot get history for '%s'"), zhp->zpool_name));
4313 		}
4314 	}
4315 
4316 	*len = zc.zc_history_len;
4317 	*off = zc.zc_history_offset;
4318 
4319 	return (0);
4320 }
4321 
4322 /*
4323  * Retrieve the command history of a pool.
4324  */
4325 int
4326 zpool_get_history(zpool_handle_t *zhp, nvlist_t **nvhisp, uint64_t *off,
4327     boolean_t *eof)
4328 {
4329 	libzfs_handle_t *hdl = zhp->zpool_hdl;
4330 	char *buf;
4331 	int buflen = 128 * 1024;
4332 	nvlist_t **records = NULL;
4333 	uint_t numrecords = 0;
4334 	int err = 0, i;
4335 	uint64_t start = *off;
4336 
4337 	buf = zfs_alloc(hdl, buflen);
4338 
4339 	/* process about 1MiB a time */
4340 	while (*off - start < 1024 * 1024) {
4341 		uint64_t bytes_read = buflen;
4342 		uint64_t leftover;
4343 
4344 		if ((err = get_history(zhp, buf, off, &bytes_read)) != 0)
4345 			break;
4346 
4347 		/* if nothing else was read in, we're at EOF, just return */
4348 		if (!bytes_read) {
4349 			*eof = B_TRUE;
4350 			break;
4351 		}
4352 
4353 		if ((err = zpool_history_unpack(buf, bytes_read,
4354 		    &leftover, &records, &numrecords)) != 0) {
4355 			zpool_standard_error_fmt(hdl, err,
4356 			    dgettext(TEXT_DOMAIN,
4357 			    "cannot get history for '%s'"), zhp->zpool_name);
4358 			break;
4359 		}
4360 		*off -= leftover;
4361 		if (leftover == bytes_read) {
4362 			/*
4363 			 * no progress made, because buffer is not big enough
4364 			 * to hold this record; resize and retry.
4365 			 */
4366 			buflen *= 2;
4367 			free(buf);
4368 			buf = zfs_alloc(hdl, buflen);
4369 		}
4370 	}
4371 
4372 	free(buf);
4373 
4374 	if (!err) {
4375 		*nvhisp = fnvlist_alloc();
4376 		fnvlist_add_nvlist_array(*nvhisp, ZPOOL_HIST_RECORD,
4377 		    (const nvlist_t **)records, numrecords);
4378 	}
4379 	for (i = 0; i < numrecords; i++)
4380 		nvlist_free(records[i]);
4381 	free(records);
4382 
4383 	return (err);
4384 }
4385 
4386 /*
4387  * Retrieve the next event given the passed 'zevent_fd' file descriptor.
4388  * If there is a new event available 'nvp' will contain a newly allocated
4389  * nvlist and 'dropped' will be set to the number of missed events since
4390  * the last call to this function.  When 'nvp' is set to NULL it indicates
4391  * no new events are available.  In either case the function returns 0 and
4392  * it is up to the caller to free 'nvp'.  In the case of a fatal error the
4393  * function will return a non-zero value.  When the function is called in
4394  * blocking mode (the default, unless the ZEVENT_NONBLOCK flag is passed),
4395  * it will not return until a new event is available.
4396  */
4397 int
4398 zpool_events_next(libzfs_handle_t *hdl, nvlist_t **nvp,
4399     int *dropped, unsigned flags, int zevent_fd)
4400 {
4401 	zfs_cmd_t zc = {"\0"};
4402 	int error = 0;
4403 
4404 	*nvp = NULL;
4405 	*dropped = 0;
4406 	zc.zc_cleanup_fd = zevent_fd;
4407 
4408 	if (flags & ZEVENT_NONBLOCK)
4409 		zc.zc_guid = ZEVENT_NONBLOCK;
4410 
4411 	zcmd_alloc_dst_nvlist(hdl, &zc, ZEVENT_SIZE);
4412 
4413 retry:
4414 	if (zfs_ioctl(hdl, ZFS_IOC_EVENTS_NEXT, &zc) != 0) {
4415 		switch (errno) {
4416 		case ESHUTDOWN:
4417 			error = zfs_error_fmt(hdl, EZFS_POOLUNAVAIL,
4418 			    dgettext(TEXT_DOMAIN, "zfs shutdown"));
4419 			goto out;
4420 		case ENOENT:
4421 			/* Blocking error case should not occur */
4422 			if (!(flags & ZEVENT_NONBLOCK))
4423 				error = zpool_standard_error_fmt(hdl, errno,
4424 				    dgettext(TEXT_DOMAIN, "cannot get event"));
4425 
4426 			goto out;
4427 		case ENOMEM:
4428 			zcmd_expand_dst_nvlist(hdl, &zc);
4429 			goto retry;
4430 		default:
4431 			error = zpool_standard_error_fmt(hdl, errno,
4432 			    dgettext(TEXT_DOMAIN, "cannot get event"));
4433 			goto out;
4434 		}
4435 	}
4436 
4437 	error = zcmd_read_dst_nvlist(hdl, &zc, nvp);
4438 	if (error != 0)
4439 		goto out;
4440 
4441 	*dropped = (int)zc.zc_cookie;
4442 out:
4443 	zcmd_free_nvlists(&zc);
4444 
4445 	return (error);
4446 }
4447 
4448 /*
4449  * Clear all events.
4450  */
4451 int
4452 zpool_events_clear(libzfs_handle_t *hdl, int *count)
4453 {
4454 	zfs_cmd_t zc = {"\0"};
4455 
4456 	if (zfs_ioctl(hdl, ZFS_IOC_EVENTS_CLEAR, &zc) != 0)
4457 		return (zpool_standard_error(hdl, errno,
4458 		    dgettext(TEXT_DOMAIN, "cannot clear events")));
4459 
4460 	if (count != NULL)
4461 		*count = (int)zc.zc_cookie; /* # of events cleared */
4462 
4463 	return (0);
4464 }
4465 
4466 /*
4467  * Seek to a specific EID, ZEVENT_SEEK_START, or ZEVENT_SEEK_END for
4468  * the passed zevent_fd file handle.  On success zero is returned,
4469  * otherwise -1 is returned and hdl->libzfs_error is set to the errno.
4470  */
4471 int
4472 zpool_events_seek(libzfs_handle_t *hdl, uint64_t eid, int zevent_fd)
4473 {
4474 	zfs_cmd_t zc = {"\0"};
4475 	int error = 0;
4476 
4477 	zc.zc_guid = eid;
4478 	zc.zc_cleanup_fd = zevent_fd;
4479 
4480 	if (zfs_ioctl(hdl, ZFS_IOC_EVENTS_SEEK, &zc) != 0) {
4481 		switch (errno) {
4482 		case ENOENT:
4483 			error = zfs_error_fmt(hdl, EZFS_NOENT,
4484 			    dgettext(TEXT_DOMAIN, "cannot get event"));
4485 			break;
4486 
4487 		case ENOMEM:
4488 			error = zfs_error_fmt(hdl, EZFS_NOMEM,
4489 			    dgettext(TEXT_DOMAIN, "cannot get event"));
4490 			break;
4491 
4492 		default:
4493 			error = zpool_standard_error_fmt(hdl, errno,
4494 			    dgettext(TEXT_DOMAIN, "cannot get event"));
4495 			break;
4496 		}
4497 	}
4498 
4499 	return (error);
4500 }
4501 
4502 static void
4503 zpool_obj_to_path_impl(zpool_handle_t *zhp, uint64_t dsobj, uint64_t obj,
4504     char *pathname, size_t len, boolean_t always_unmounted)
4505 {
4506 	zfs_cmd_t zc = {"\0"};
4507 	boolean_t mounted = B_FALSE;
4508 	char *mntpnt = NULL;
4509 	char dsname[ZFS_MAX_DATASET_NAME_LEN];
4510 
4511 	if (dsobj == 0) {
4512 		/* special case for the MOS */
4513 		(void) snprintf(pathname, len, "<metadata>:<0x%llx>",
4514 		    (longlong_t)obj);
4515 		return;
4516 	}
4517 
4518 	/* get the dataset's name */
4519 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
4520 	zc.zc_obj = dsobj;
4521 	if (zfs_ioctl(zhp->zpool_hdl,
4522 	    ZFS_IOC_DSOBJ_TO_DSNAME, &zc) != 0) {
4523 		/* just write out a path of two object numbers */
4524 		(void) snprintf(pathname, len, "<0x%llx>:<0x%llx>",
4525 		    (longlong_t)dsobj, (longlong_t)obj);
4526 		return;
4527 	}
4528 	(void) strlcpy(dsname, zc.zc_value, sizeof (dsname));
4529 
4530 	/* find out if the dataset is mounted */
4531 	mounted = !always_unmounted && is_mounted(zhp->zpool_hdl, dsname,
4532 	    &mntpnt);
4533 
4534 	/* get the corrupted object's path */
4535 	(void) strlcpy(zc.zc_name, dsname, sizeof (zc.zc_name));
4536 	zc.zc_obj = obj;
4537 	if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_OBJ_TO_PATH,
4538 	    &zc) == 0) {
4539 		if (mounted) {
4540 			(void) snprintf(pathname, len, "%s%s", mntpnt,
4541 			    zc.zc_value);
4542 		} else {
4543 			(void) snprintf(pathname, len, "%s:%s",
4544 			    dsname, zc.zc_value);
4545 		}
4546 	} else {
4547 		(void) snprintf(pathname, len, "%s:<0x%llx>", dsname,
4548 		    (longlong_t)obj);
4549 	}
4550 	free(mntpnt);
4551 }
4552 
4553 void
4554 zpool_obj_to_path(zpool_handle_t *zhp, uint64_t dsobj, uint64_t obj,
4555     char *pathname, size_t len)
4556 {
4557 	zpool_obj_to_path_impl(zhp, dsobj, obj, pathname, len, B_FALSE);
4558 }
4559 
4560 void
4561 zpool_obj_to_path_ds(zpool_handle_t *zhp, uint64_t dsobj, uint64_t obj,
4562     char *pathname, size_t len)
4563 {
4564 	zpool_obj_to_path_impl(zhp, dsobj, obj, pathname, len, B_TRUE);
4565 }
4566 /*
4567  * Wait while the specified activity is in progress in the pool.
4568  */
4569 int
4570 zpool_wait(zpool_handle_t *zhp, zpool_wait_activity_t activity)
4571 {
4572 	boolean_t missing;
4573 
4574 	int error = zpool_wait_status(zhp, activity, &missing, NULL);
4575 
4576 	if (missing) {
4577 		(void) zpool_standard_error_fmt(zhp->zpool_hdl, ENOENT,
4578 		    dgettext(TEXT_DOMAIN, "error waiting in pool '%s'"),
4579 		    zhp->zpool_name);
4580 		return (ENOENT);
4581 	} else {
4582 		return (error);
4583 	}
4584 }
4585 
4586 /*
4587  * Wait for the given activity and return the status of the wait (whether or not
4588  * any waiting was done) in the 'waited' parameter. Non-existent pools are
4589  * reported via the 'missing' parameter, rather than by printing an error
4590  * message. This is convenient when this function is called in a loop over a
4591  * long period of time (as it is, for example, by zpool's wait cmd). In that
4592  * scenario, a pool being exported or destroyed should be considered a normal
4593  * event, so we don't want to print an error when we find that the pool doesn't
4594  * exist.
4595  */
4596 int
4597 zpool_wait_status(zpool_handle_t *zhp, zpool_wait_activity_t activity,
4598     boolean_t *missing, boolean_t *waited)
4599 {
4600 	int error = lzc_wait(zhp->zpool_name, activity, waited);
4601 	*missing = (error == ENOENT);
4602 	if (*missing)
4603 		return (0);
4604 
4605 	if (error != 0) {
4606 		(void) zpool_standard_error_fmt(zhp->zpool_hdl, error,
4607 		    dgettext(TEXT_DOMAIN, "error waiting in pool '%s'"),
4608 		    zhp->zpool_name);
4609 	}
4610 
4611 	return (error);
4612 }
4613 
4614 int
4615 zpool_set_bootenv(zpool_handle_t *zhp, const nvlist_t *envmap)
4616 {
4617 	int error = lzc_set_bootenv(zhp->zpool_name, envmap);
4618 	if (error != 0) {
4619 		(void) zpool_standard_error_fmt(zhp->zpool_hdl, error,
4620 		    dgettext(TEXT_DOMAIN,
4621 		    "error setting bootenv in pool '%s'"), zhp->zpool_name);
4622 	}
4623 
4624 	return (error);
4625 }
4626 
4627 int
4628 zpool_get_bootenv(zpool_handle_t *zhp, nvlist_t **nvlp)
4629 {
4630 	nvlist_t *nvl;
4631 	int error;
4632 
4633 	nvl = NULL;
4634 	error = lzc_get_bootenv(zhp->zpool_name, &nvl);
4635 	if (error != 0) {
4636 		(void) zpool_standard_error_fmt(zhp->zpool_hdl, error,
4637 		    dgettext(TEXT_DOMAIN,
4638 		    "error getting bootenv in pool '%s'"), zhp->zpool_name);
4639 	} else {
4640 		*nvlp = nvl;
4641 	}
4642 
4643 	return (error);
4644 }
4645 
4646 /*
4647  * Attempt to read and parse feature file(s) (from "compatibility" property).
4648  * Files contain zpool feature names, comma or whitespace-separated.
4649  * Comments (# character to next newline) are discarded.
4650  *
4651  * Arguments:
4652  *  compatibility : string containing feature filenames
4653  *  features : either NULL or pointer to array of boolean
4654  *  report : either NULL or pointer to string buffer
4655  *  rlen : length of "report" buffer
4656  *
4657  * compatibility is NULL (unset), "", "off", "legacy", or list of
4658  * comma-separated filenames. filenames should either be absolute,
4659  * or relative to:
4660  *   1) ZPOOL_SYSCONF_COMPAT_D (eg: /etc/zfs/compatibility.d) or
4661  *   2) ZPOOL_DATA_COMPAT_D (eg: /usr/share/zfs/compatibility.d).
4662  * (Unset), "" or "off" => enable all features
4663  * "legacy" => disable all features
4664  *
4665  * Any feature names read from files which match unames in spa_feature_table
4666  * will have the corresponding boolean set in the features array (if non-NULL).
4667  * If more than one feature set specified, only features present in *all* of
4668  * them will be set.
4669  *
4670  * "report" if not NULL will be populated with a suitable status message.
4671  *
4672  * Return values:
4673  *   ZPOOL_COMPATIBILITY_OK : files read and parsed ok
4674  *   ZPOOL_COMPATIBILITY_BADFILE : file too big or not a text file
4675  *   ZPOOL_COMPATIBILITY_BADTOKEN : SYSCONF file contains invalid feature name
4676  *   ZPOOL_COMPATIBILITY_WARNTOKEN : DATA file contains invalid feature name
4677  *   ZPOOL_COMPATIBILITY_NOFILES : no feature files found
4678  */
4679 zpool_compat_status_t
4680 zpool_load_compat(const char *compat, boolean_t *features, char *report,
4681     size_t rlen)
4682 {
4683 	int sdirfd, ddirfd, featfd;
4684 	struct stat fs;
4685 	char *fc;
4686 	char *ps, *ls, *ws;
4687 	char *file, *line, *word;
4688 
4689 	char l_compat[ZFS_MAXPROPLEN];
4690 
4691 	boolean_t ret_nofiles = B_TRUE;
4692 	boolean_t ret_badfile = B_FALSE;
4693 	boolean_t ret_badtoken = B_FALSE;
4694 	boolean_t ret_warntoken = B_FALSE;
4695 
4696 	/* special cases (unset), "" and "off" => enable all features */
4697 	if (compat == NULL || compat[0] == '\0' ||
4698 	    strcmp(compat, ZPOOL_COMPAT_OFF) == 0) {
4699 		if (features != NULL)
4700 			for (uint_t i = 0; i < SPA_FEATURES; i++)
4701 				features[i] = B_TRUE;
4702 		if (report != NULL)
4703 			strlcpy(report, gettext("all features enabled"), rlen);
4704 		return (ZPOOL_COMPATIBILITY_OK);
4705 	}
4706 
4707 	/* Final special case "legacy" => disable all features */
4708 	if (strcmp(compat, ZPOOL_COMPAT_LEGACY) == 0) {
4709 		if (features != NULL)
4710 			for (uint_t i = 0; i < SPA_FEATURES; i++)
4711 				features[i] = B_FALSE;
4712 		if (report != NULL)
4713 			strlcpy(report, gettext("all features disabled"), rlen);
4714 		return (ZPOOL_COMPATIBILITY_OK);
4715 	}
4716 
4717 	/*
4718 	 * Start with all true; will be ANDed with results from each file
4719 	 */
4720 	if (features != NULL)
4721 		for (uint_t i = 0; i < SPA_FEATURES; i++)
4722 			features[i] = B_TRUE;
4723 
4724 	char err_badfile[ZFS_MAXPROPLEN] = "";
4725 	char err_badtoken[ZFS_MAXPROPLEN] = "";
4726 
4727 	/*
4728 	 * We ignore errors from the directory open()
4729 	 * as they're only needed if the filename is relative
4730 	 * which will be checked during the openat().
4731 	 */
4732 
4733 /* O_PATH safer than O_RDONLY if system allows it */
4734 #if defined(O_PATH)
4735 #define	ZC_DIR_FLAGS (O_DIRECTORY | O_CLOEXEC | O_PATH)
4736 #else
4737 #define	ZC_DIR_FLAGS (O_DIRECTORY | O_CLOEXEC | O_RDONLY)
4738 #endif
4739 
4740 	sdirfd = open(ZPOOL_SYSCONF_COMPAT_D, ZC_DIR_FLAGS);
4741 	ddirfd = open(ZPOOL_DATA_COMPAT_D, ZC_DIR_FLAGS);
4742 
4743 	(void) strlcpy(l_compat, compat, ZFS_MAXPROPLEN);
4744 
4745 	for (file = strtok_r(l_compat, ",", &ps);
4746 	    file != NULL;
4747 	    file = strtok_r(NULL, ",", &ps)) {
4748 
4749 		boolean_t l_features[SPA_FEATURES];
4750 
4751 		enum { Z_SYSCONF, Z_DATA } source;
4752 
4753 		/* try sysconfdir first, then datadir */
4754 		source = Z_SYSCONF;
4755 		if ((featfd = openat(sdirfd, file, O_RDONLY | O_CLOEXEC)) < 0) {
4756 			featfd = openat(ddirfd, file, O_RDONLY | O_CLOEXEC);
4757 			source = Z_DATA;
4758 		}
4759 
4760 		/* File readable and correct size? */
4761 		if (featfd < 0 ||
4762 		    fstat(featfd, &fs) < 0 ||
4763 		    fs.st_size < 1 ||
4764 		    fs.st_size > ZPOOL_COMPAT_MAXSIZE) {
4765 			(void) close(featfd);
4766 			strlcat(err_badfile, file, ZFS_MAXPROPLEN);
4767 			strlcat(err_badfile, " ", ZFS_MAXPROPLEN);
4768 			ret_badfile = B_TRUE;
4769 			continue;
4770 		}
4771 
4772 /* Prefault the file if system allows */
4773 #if defined(MAP_POPULATE)
4774 #define	ZC_MMAP_FLAGS (MAP_PRIVATE | MAP_POPULATE)
4775 #elif defined(MAP_PREFAULT_READ)
4776 #define	ZC_MMAP_FLAGS (MAP_PRIVATE | MAP_PREFAULT_READ)
4777 #else
4778 #define	ZC_MMAP_FLAGS (MAP_PRIVATE)
4779 #endif
4780 
4781 		/* private mmap() so we can strtok safely */
4782 		fc = (char *)mmap(NULL, fs.st_size, PROT_READ | PROT_WRITE,
4783 		    ZC_MMAP_FLAGS, featfd, 0);
4784 		(void) close(featfd);
4785 
4786 		/* map ok, and last character == newline? */
4787 		if (fc == MAP_FAILED || fc[fs.st_size - 1] != '\n') {
4788 			(void) munmap((void *) fc, fs.st_size);
4789 			strlcat(err_badfile, file, ZFS_MAXPROPLEN);
4790 			strlcat(err_badfile, " ", ZFS_MAXPROPLEN);
4791 			ret_badfile = B_TRUE;
4792 			continue;
4793 		}
4794 
4795 		ret_nofiles = B_FALSE;
4796 
4797 		for (uint_t i = 0; i < SPA_FEATURES; i++)
4798 			l_features[i] = B_FALSE;
4799 
4800 		/* replace final newline with NULL to ensure string ends */
4801 		fc[fs.st_size - 1] = '\0';
4802 
4803 		for (line = strtok_r(fc, "\n", &ls);
4804 		    line != NULL;
4805 		    line = strtok_r(NULL, "\n", &ls)) {
4806 			/* discard comments */
4807 			char *r = strchr(line, '#');
4808 			if (r != NULL)
4809 				*r = '\0';
4810 
4811 			for (word = strtok_r(line, ", \t", &ws);
4812 			    word != NULL;
4813 			    word = strtok_r(NULL, ", \t", &ws)) {
4814 				/* Find matching feature name */
4815 				uint_t f;
4816 				for (f = 0; f < SPA_FEATURES; f++) {
4817 					zfeature_info_t *fi =
4818 					    &spa_feature_table[f];
4819 					if (strcmp(word, fi->fi_uname) == 0) {
4820 						l_features[f] = B_TRUE;
4821 						break;
4822 					}
4823 				}
4824 				if (f < SPA_FEATURES)
4825 					continue;
4826 
4827 				/* found an unrecognized word */
4828 				/* lightly sanitize it */
4829 				if (strlen(word) > 32)
4830 					word[32] = '\0';
4831 				for (char *c = word; *c != '\0'; c++)
4832 					if (!isprint(*c))
4833 						*c = '?';
4834 
4835 				strlcat(err_badtoken, word, ZFS_MAXPROPLEN);
4836 				strlcat(err_badtoken, " ", ZFS_MAXPROPLEN);
4837 				if (source == Z_SYSCONF)
4838 					ret_badtoken = B_TRUE;
4839 				else
4840 					ret_warntoken = B_TRUE;
4841 			}
4842 		}
4843 		(void) munmap((void *) fc, fs.st_size);
4844 
4845 		if (features != NULL)
4846 			for (uint_t i = 0; i < SPA_FEATURES; i++)
4847 				features[i] &= l_features[i];
4848 	}
4849 	(void) close(sdirfd);
4850 	(void) close(ddirfd);
4851 
4852 	/* Return the most serious error */
4853 	if (ret_badfile) {
4854 		if (report != NULL)
4855 			snprintf(report, rlen, gettext("could not read/"
4856 			    "parse feature file(s): %s"), err_badfile);
4857 		return (ZPOOL_COMPATIBILITY_BADFILE);
4858 	}
4859 	if (ret_nofiles) {
4860 		if (report != NULL)
4861 			strlcpy(report,
4862 			    gettext("no valid compatibility files specified"),
4863 			    rlen);
4864 		return (ZPOOL_COMPATIBILITY_NOFILES);
4865 	}
4866 	if (ret_badtoken) {
4867 		if (report != NULL)
4868 			snprintf(report, rlen, gettext("invalid feature "
4869 			    "name(s) in local compatibility files: %s"),
4870 			    err_badtoken);
4871 		return (ZPOOL_COMPATIBILITY_BADTOKEN);
4872 	}
4873 	if (ret_warntoken) {
4874 		if (report != NULL)
4875 			snprintf(report, rlen, gettext("unrecognized feature "
4876 			    "name(s) in distribution compatibility files: %s"),
4877 			    err_badtoken);
4878 		return (ZPOOL_COMPATIBILITY_WARNTOKEN);
4879 	}
4880 	if (report != NULL)
4881 		strlcpy(report, gettext("compatibility set ok"), rlen);
4882 	return (ZPOOL_COMPATIBILITY_OK);
4883 }
4884 
4885 static int
4886 zpool_vdev_guid(zpool_handle_t *zhp, const char *vdevname, uint64_t *vdev_guid)
4887 {
4888 	nvlist_t *tgt;
4889 	boolean_t avail_spare, l2cache;
4890 
4891 	verify(zhp != NULL);
4892 	if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
4893 		char errbuf[ERRBUFLEN];
4894 		(void) snprintf(errbuf, sizeof (errbuf),
4895 		    dgettext(TEXT_DOMAIN, "pool is in an unavailable state"));
4896 		return (zfs_error(zhp->zpool_hdl, EZFS_POOLUNAVAIL, errbuf));
4897 	}
4898 
4899 	if ((tgt = zpool_find_vdev(zhp, vdevname, &avail_spare, &l2cache,
4900 	    NULL)) == NULL) {
4901 		char errbuf[ERRBUFLEN];
4902 		(void) snprintf(errbuf, sizeof (errbuf),
4903 		    dgettext(TEXT_DOMAIN, "can not find %s in %s"),
4904 		    vdevname, zhp->zpool_name);
4905 		return (zfs_error(zhp->zpool_hdl, EZFS_NODEVICE, errbuf));
4906 	}
4907 
4908 	*vdev_guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
4909 	return (0);
4910 }
4911 
4912 /*
4913  * Get a vdev property value for 'prop' and return the value in
4914  * a pre-allocated buffer.
4915  */
4916 int
4917 zpool_get_vdev_prop_value(nvlist_t *nvprop, vdev_prop_t prop, char *prop_name,
4918     char *buf, size_t len, zprop_source_t *srctype, boolean_t literal)
4919 {
4920 	nvlist_t *nv;
4921 	const char *strval;
4922 	uint64_t intval;
4923 	zprop_source_t src = ZPROP_SRC_NONE;
4924 
4925 	if (prop == VDEV_PROP_USERPROP) {
4926 		/* user property, prop_name must contain the property name */
4927 		assert(prop_name != NULL);
4928 		if (nvlist_lookup_nvlist(nvprop, prop_name, &nv) == 0) {
4929 			src = fnvlist_lookup_uint64(nv, ZPROP_SOURCE);
4930 			strval = fnvlist_lookup_string(nv, ZPROP_VALUE);
4931 		} else {
4932 			/* user prop not found */
4933 			return (-1);
4934 		}
4935 		(void) strlcpy(buf, strval, len);
4936 		if (srctype)
4937 			*srctype = src;
4938 		return (0);
4939 	}
4940 
4941 	if (prop_name == NULL)
4942 		prop_name = (char *)vdev_prop_to_name(prop);
4943 
4944 	switch (vdev_prop_get_type(prop)) {
4945 	case PROP_TYPE_STRING:
4946 		if (nvlist_lookup_nvlist(nvprop, prop_name, &nv) == 0) {
4947 			src = fnvlist_lookup_uint64(nv, ZPROP_SOURCE);
4948 			strval = fnvlist_lookup_string(nv, ZPROP_VALUE);
4949 		} else {
4950 			src = ZPROP_SRC_DEFAULT;
4951 			if ((strval = vdev_prop_default_string(prop)) == NULL)
4952 				strval = "-";
4953 		}
4954 		(void) strlcpy(buf, strval, len);
4955 		break;
4956 
4957 	case PROP_TYPE_NUMBER:
4958 		if (nvlist_lookup_nvlist(nvprop, prop_name, &nv) == 0) {
4959 			src = fnvlist_lookup_uint64(nv, ZPROP_SOURCE);
4960 			intval = fnvlist_lookup_uint64(nv, ZPROP_VALUE);
4961 		} else {
4962 			src = ZPROP_SRC_DEFAULT;
4963 			intval = vdev_prop_default_numeric(prop);
4964 		}
4965 
4966 		switch (prop) {
4967 		case VDEV_PROP_ASIZE:
4968 		case VDEV_PROP_PSIZE:
4969 		case VDEV_PROP_SIZE:
4970 		case VDEV_PROP_BOOTSIZE:
4971 		case VDEV_PROP_ALLOCATED:
4972 		case VDEV_PROP_FREE:
4973 		case VDEV_PROP_READ_ERRORS:
4974 		case VDEV_PROP_WRITE_ERRORS:
4975 		case VDEV_PROP_CHECKSUM_ERRORS:
4976 		case VDEV_PROP_INITIALIZE_ERRORS:
4977 		case VDEV_PROP_OPS_NULL:
4978 		case VDEV_PROP_OPS_READ:
4979 		case VDEV_PROP_OPS_WRITE:
4980 		case VDEV_PROP_OPS_FREE:
4981 		case VDEV_PROP_OPS_CLAIM:
4982 		case VDEV_PROP_OPS_TRIM:
4983 		case VDEV_PROP_BYTES_NULL:
4984 		case VDEV_PROP_BYTES_READ:
4985 		case VDEV_PROP_BYTES_WRITE:
4986 		case VDEV_PROP_BYTES_FREE:
4987 		case VDEV_PROP_BYTES_CLAIM:
4988 		case VDEV_PROP_BYTES_TRIM:
4989 			if (literal) {
4990 				(void) snprintf(buf, len, "%llu",
4991 				    (u_longlong_t)intval);
4992 			} else {
4993 				(void) zfs_nicenum(intval, buf, len);
4994 			}
4995 			break;
4996 		case VDEV_PROP_EXPANDSZ:
4997 			if (intval == 0) {
4998 				(void) strlcpy(buf, "-", len);
4999 			} else if (literal) {
5000 				(void) snprintf(buf, len, "%llu",
5001 				    (u_longlong_t)intval);
5002 			} else {
5003 				(void) zfs_nicenum(intval, buf, len);
5004 			}
5005 			break;
5006 		case VDEV_PROP_CAPACITY:
5007 			if (literal) {
5008 				(void) snprintf(buf, len, "%llu",
5009 				    (u_longlong_t)intval);
5010 			} else {
5011 				(void) snprintf(buf, len, "%llu%%",
5012 				    (u_longlong_t)intval);
5013 			}
5014 			break;
5015 		case VDEV_PROP_FRAGMENTATION:
5016 			if (intval == UINT64_MAX) {
5017 				(void) strlcpy(buf, "-", len);
5018 			} else {
5019 				(void) snprintf(buf, len, "%llu%%",
5020 				    (u_longlong_t)intval);
5021 			}
5022 			break;
5023 		case VDEV_PROP_STATE:
5024 			if (literal) {
5025 				(void) snprintf(buf, len, "%llu",
5026 				    (u_longlong_t)intval);
5027 			} else {
5028 				(void) strlcpy(buf, zpool_state_to_name(intval,
5029 				    VDEV_AUX_NONE), len);
5030 			}
5031 			break;
5032 		default:
5033 			(void) snprintf(buf, len, "%llu",
5034 			    (u_longlong_t)intval);
5035 		}
5036 		break;
5037 
5038 	case PROP_TYPE_INDEX:
5039 		if (nvlist_lookup_nvlist(nvprop, prop_name, &nv) == 0) {
5040 			src = fnvlist_lookup_uint64(nv, ZPROP_SOURCE);
5041 			intval = fnvlist_lookup_uint64(nv, ZPROP_VALUE);
5042 		} else {
5043 			src = ZPROP_SRC_DEFAULT;
5044 			intval = vdev_prop_default_numeric(prop);
5045 		}
5046 		if (vdev_prop_index_to_string(prop, intval,
5047 		    (const char **)&strval) != 0)
5048 			return (-1);
5049 		(void) strlcpy(buf, strval, len);
5050 		break;
5051 
5052 	default:
5053 		abort();
5054 	}
5055 
5056 	if (srctype)
5057 		*srctype = src;
5058 
5059 	return (0);
5060 }
5061 
5062 /*
5063  * Get a vdev property value for 'prop_name' and return the value in
5064  * a pre-allocated buffer.
5065  */
5066 int
5067 zpool_get_vdev_prop(zpool_handle_t *zhp, const char *vdevname, vdev_prop_t prop,
5068     char *prop_name, char *buf, size_t len, zprop_source_t *srctype,
5069     boolean_t literal)
5070 {
5071 	nvlist_t *reqnvl, *reqprops;
5072 	nvlist_t *retprops = NULL;
5073 	uint64_t vdev_guid = 0;
5074 	int ret;
5075 
5076 	if ((ret = zpool_vdev_guid(zhp, vdevname, &vdev_guid)) != 0)
5077 		return (ret);
5078 
5079 	if (nvlist_alloc(&reqnvl, NV_UNIQUE_NAME, 0) != 0)
5080 		return (no_memory(zhp->zpool_hdl));
5081 	if (nvlist_alloc(&reqprops, NV_UNIQUE_NAME, 0) != 0)
5082 		return (no_memory(zhp->zpool_hdl));
5083 
5084 	fnvlist_add_uint64(reqnvl, ZPOOL_VDEV_PROPS_GET_VDEV, vdev_guid);
5085 
5086 	if (prop != VDEV_PROP_USERPROP) {
5087 		/* prop_name overrides prop value */
5088 		if (prop_name != NULL)
5089 			prop = vdev_name_to_prop(prop_name);
5090 		else
5091 			prop_name = (char *)vdev_prop_to_name(prop);
5092 		assert(prop < VDEV_NUM_PROPS);
5093 	}
5094 
5095 	assert(prop_name != NULL);
5096 	if (nvlist_add_uint64(reqprops, prop_name, prop) != 0) {
5097 		nvlist_free(reqnvl);
5098 		nvlist_free(reqprops);
5099 		return (no_memory(zhp->zpool_hdl));
5100 	}
5101 
5102 	fnvlist_add_nvlist(reqnvl, ZPOOL_VDEV_PROPS_GET_PROPS, reqprops);
5103 
5104 	ret = lzc_get_vdev_prop(zhp->zpool_name, reqnvl, &retprops);
5105 
5106 	if (ret == 0) {
5107 		ret = zpool_get_vdev_prop_value(retprops, prop, prop_name, buf,
5108 		    len, srctype, literal);
5109 	} else {
5110 		char errbuf[ERRBUFLEN];
5111 		(void) snprintf(errbuf, sizeof (errbuf),
5112 		    dgettext(TEXT_DOMAIN, "cannot get vdev property %s from"
5113 		    " %s in %s"), prop_name, vdevname, zhp->zpool_name);
5114 		(void) zpool_standard_error(zhp->zpool_hdl, ret, errbuf);
5115 	}
5116 
5117 	nvlist_free(reqnvl);
5118 	nvlist_free(reqprops);
5119 	nvlist_free(retprops);
5120 
5121 	return (ret);
5122 }
5123 
5124 /*
5125  * Get all vdev properties
5126  */
5127 int
5128 zpool_get_all_vdev_props(zpool_handle_t *zhp, const char *vdevname,
5129     nvlist_t **outnvl)
5130 {
5131 	nvlist_t *nvl = NULL;
5132 	uint64_t vdev_guid = 0;
5133 	int ret;
5134 
5135 	if ((ret = zpool_vdev_guid(zhp, vdevname, &vdev_guid)) != 0)
5136 		return (ret);
5137 
5138 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5139 		return (no_memory(zhp->zpool_hdl));
5140 
5141 	fnvlist_add_uint64(nvl, ZPOOL_VDEV_PROPS_GET_VDEV, vdev_guid);
5142 
5143 	ret = lzc_get_vdev_prop(zhp->zpool_name, nvl, outnvl);
5144 
5145 	nvlist_free(nvl);
5146 
5147 	if (ret) {
5148 		char errbuf[ERRBUFLEN];
5149 		(void) snprintf(errbuf, sizeof (errbuf),
5150 		    dgettext(TEXT_DOMAIN, "cannot get vdev properties for"
5151 		    " %s in %s"), vdevname, zhp->zpool_name);
5152 		(void) zpool_standard_error(zhp->zpool_hdl, errno, errbuf);
5153 	}
5154 
5155 	return (ret);
5156 }
5157 
5158 /*
5159  * Set vdev property
5160  */
5161 int
5162 zpool_set_vdev_prop(zpool_handle_t *zhp, const char *vdevname,
5163     const char *propname, const char *propval)
5164 {
5165 	int ret;
5166 	nvlist_t *nvl = NULL;
5167 	nvlist_t *outnvl = NULL;
5168 	nvlist_t *props;
5169 	nvlist_t *realprops;
5170 	prop_flags_t flags = { 0 };
5171 	uint64_t version;
5172 	uint64_t vdev_guid;
5173 
5174 	if ((ret = zpool_vdev_guid(zhp, vdevname, &vdev_guid)) != 0)
5175 		return (ret);
5176 
5177 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5178 		return (no_memory(zhp->zpool_hdl));
5179 	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
5180 		return (no_memory(zhp->zpool_hdl));
5181 
5182 	fnvlist_add_uint64(nvl, ZPOOL_VDEV_PROPS_SET_VDEV, vdev_guid);
5183 
5184 	if (nvlist_add_string(props, propname, propval) != 0) {
5185 		nvlist_free(props);
5186 		return (no_memory(zhp->zpool_hdl));
5187 	}
5188 
5189 	char errbuf[ERRBUFLEN];
5190 	(void) snprintf(errbuf, sizeof (errbuf),
5191 	    dgettext(TEXT_DOMAIN, "cannot set property %s for %s on %s"),
5192 	    propname, vdevname, zhp->zpool_name);
5193 
5194 	flags.vdevprop = 1;
5195 	version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
5196 	if ((realprops = zpool_valid_proplist(zhp->zpool_hdl,
5197 	    zhp->zpool_name, props, version, flags, errbuf)) == NULL) {
5198 		nvlist_free(props);
5199 		nvlist_free(nvl);
5200 		return (-1);
5201 	}
5202 
5203 	nvlist_free(props);
5204 	props = realprops;
5205 
5206 	fnvlist_add_nvlist(nvl, ZPOOL_VDEV_PROPS_SET_PROPS, props);
5207 
5208 	ret = lzc_set_vdev_prop(zhp->zpool_name, nvl, &outnvl);
5209 
5210 	nvlist_free(props);
5211 	nvlist_free(nvl);
5212 	nvlist_free(outnvl);
5213 
5214 	if (ret)
5215 		(void) zpool_standard_error(zhp->zpool_hdl, errno, errbuf);
5216 
5217 	return (ret);
5218 }
5219