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