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