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