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