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