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