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