xref: /titanic_44/usr/src/lib/libzfs/common/libzfs_pool.c (revision 12ae924a5d4f6af89ee47f2908555a487618d82b)
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, 2015 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[ZFS_MAX_DATASET_NAME_LEN];
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_DELIMITERS:
915 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
916 				    "multiple '@' and/or '#' delimiters in "
917 				    "name"));
918 				break;
919 
920 			}
921 		}
922 		return (B_FALSE);
923 	}
924 
925 	return (B_TRUE);
926 }
927 
928 /*
929  * Open a handle to the given pool, even if the pool is currently in the FAULTED
930  * state.
931  */
932 zpool_handle_t *
933 zpool_open_canfail(libzfs_handle_t *hdl, const char *pool)
934 {
935 	zpool_handle_t *zhp;
936 	boolean_t missing;
937 
938 	/*
939 	 * Make sure the pool name is valid.
940 	 */
941 	if (!zpool_name_valid(hdl, B_TRUE, pool)) {
942 		(void) zfs_error_fmt(hdl, EZFS_INVALIDNAME,
943 		    dgettext(TEXT_DOMAIN, "cannot open '%s'"),
944 		    pool);
945 		return (NULL);
946 	}
947 
948 	if ((zhp = zfs_alloc(hdl, sizeof (zpool_handle_t))) == NULL)
949 		return (NULL);
950 
951 	zhp->zpool_hdl = hdl;
952 	(void) strlcpy(zhp->zpool_name, pool, sizeof (zhp->zpool_name));
953 
954 	if (zpool_refresh_stats(zhp, &missing) != 0) {
955 		zpool_close(zhp);
956 		return (NULL);
957 	}
958 
959 	if (missing) {
960 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "no such pool"));
961 		(void) zfs_error_fmt(hdl, EZFS_NOENT,
962 		    dgettext(TEXT_DOMAIN, "cannot open '%s'"), pool);
963 		zpool_close(zhp);
964 		return (NULL);
965 	}
966 
967 	return (zhp);
968 }
969 
970 /*
971  * Like the above, but silent on error.  Used when iterating over pools (because
972  * the configuration cache may be out of date).
973  */
974 int
975 zpool_open_silent(libzfs_handle_t *hdl, const char *pool, zpool_handle_t **ret)
976 {
977 	zpool_handle_t *zhp;
978 	boolean_t missing;
979 
980 	if ((zhp = zfs_alloc(hdl, sizeof (zpool_handle_t))) == NULL)
981 		return (-1);
982 
983 	zhp->zpool_hdl = hdl;
984 	(void) strlcpy(zhp->zpool_name, pool, sizeof (zhp->zpool_name));
985 
986 	if (zpool_refresh_stats(zhp, &missing) != 0) {
987 		zpool_close(zhp);
988 		return (-1);
989 	}
990 
991 	if (missing) {
992 		zpool_close(zhp);
993 		*ret = NULL;
994 		return (0);
995 	}
996 
997 	*ret = zhp;
998 	return (0);
999 }
1000 
1001 /*
1002  * Similar to zpool_open_canfail(), but refuses to open pools in the faulted
1003  * state.
1004  */
1005 zpool_handle_t *
1006 zpool_open(libzfs_handle_t *hdl, const char *pool)
1007 {
1008 	zpool_handle_t *zhp;
1009 
1010 	if ((zhp = zpool_open_canfail(hdl, pool)) == NULL)
1011 		return (NULL);
1012 
1013 	if (zhp->zpool_state == POOL_STATE_UNAVAIL) {
1014 		(void) zfs_error_fmt(hdl, EZFS_POOLUNAVAIL,
1015 		    dgettext(TEXT_DOMAIN, "cannot open '%s'"), zhp->zpool_name);
1016 		zpool_close(zhp);
1017 		return (NULL);
1018 	}
1019 
1020 	return (zhp);
1021 }
1022 
1023 /*
1024  * Close the handle.  Simply frees the memory associated with the handle.
1025  */
1026 void
1027 zpool_close(zpool_handle_t *zhp)
1028 {
1029 	nvlist_free(zhp->zpool_config);
1030 	nvlist_free(zhp->zpool_old_config);
1031 	nvlist_free(zhp->zpool_props);
1032 	free(zhp);
1033 }
1034 
1035 /*
1036  * Return the name of the pool.
1037  */
1038 const char *
1039 zpool_get_name(zpool_handle_t *zhp)
1040 {
1041 	return (zhp->zpool_name);
1042 }
1043 
1044 
1045 /*
1046  * Return the state of the pool (ACTIVE or UNAVAILABLE)
1047  */
1048 int
1049 zpool_get_state(zpool_handle_t *zhp)
1050 {
1051 	return (zhp->zpool_state);
1052 }
1053 
1054 /*
1055  * Create the named pool, using the provided vdev list.  It is assumed
1056  * that the consumer has already validated the contents of the nvlist, so we
1057  * don't have to worry about error semantics.
1058  */
1059 int
1060 zpool_create(libzfs_handle_t *hdl, const char *pool, nvlist_t *nvroot,
1061     nvlist_t *props, nvlist_t *fsprops)
1062 {
1063 	zfs_cmd_t zc = { 0 };
1064 	nvlist_t *zc_fsprops = NULL;
1065 	nvlist_t *zc_props = NULL;
1066 	char msg[1024];
1067 	int ret = -1;
1068 
1069 	(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1070 	    "cannot create '%s'"), pool);
1071 
1072 	if (!zpool_name_valid(hdl, B_FALSE, pool))
1073 		return (zfs_error(hdl, EZFS_INVALIDNAME, msg));
1074 
1075 	if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
1076 		return (-1);
1077 
1078 	if (props) {
1079 		prop_flags_t flags = { .create = B_TRUE, .import = B_FALSE };
1080 
1081 		if ((zc_props = zpool_valid_proplist(hdl, pool, props,
1082 		    SPA_VERSION_1, flags, msg)) == NULL) {
1083 			goto create_failed;
1084 		}
1085 	}
1086 
1087 	if (fsprops) {
1088 		uint64_t zoned;
1089 		char *zonestr;
1090 
1091 		zoned = ((nvlist_lookup_string(fsprops,
1092 		    zfs_prop_to_name(ZFS_PROP_ZONED), &zonestr) == 0) &&
1093 		    strcmp(zonestr, "on") == 0);
1094 
1095 		if ((zc_fsprops = zfs_valid_proplist(hdl,
1096 		    ZFS_TYPE_FILESYSTEM, fsprops, zoned, NULL, msg)) == NULL) {
1097 			goto create_failed;
1098 		}
1099 		if (!zc_props &&
1100 		    (nvlist_alloc(&zc_props, NV_UNIQUE_NAME, 0) != 0)) {
1101 			goto create_failed;
1102 		}
1103 		if (nvlist_add_nvlist(zc_props,
1104 		    ZPOOL_ROOTFS_PROPS, zc_fsprops) != 0) {
1105 			goto create_failed;
1106 		}
1107 	}
1108 
1109 	if (zc_props && zcmd_write_src_nvlist(hdl, &zc, zc_props) != 0)
1110 		goto create_failed;
1111 
1112 	(void) strlcpy(zc.zc_name, pool, sizeof (zc.zc_name));
1113 
1114 	if ((ret = zfs_ioctl(hdl, ZFS_IOC_POOL_CREATE, &zc)) != 0) {
1115 
1116 		zcmd_free_nvlists(&zc);
1117 		nvlist_free(zc_props);
1118 		nvlist_free(zc_fsprops);
1119 
1120 		switch (errno) {
1121 		case EBUSY:
1122 			/*
1123 			 * This can happen if the user has specified the same
1124 			 * device multiple times.  We can't reliably detect this
1125 			 * until we try to add it and see we already have a
1126 			 * label.
1127 			 */
1128 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1129 			    "one or more vdevs refer to the same device"));
1130 			return (zfs_error(hdl, EZFS_BADDEV, msg));
1131 
1132 		case EOVERFLOW:
1133 			/*
1134 			 * This occurs when one of the devices is below
1135 			 * SPA_MINDEVSIZE.  Unfortunately, we can't detect which
1136 			 * device was the problem device since there's no
1137 			 * reliable way to determine device size from userland.
1138 			 */
1139 			{
1140 				char buf[64];
1141 
1142 				zfs_nicenum(SPA_MINDEVSIZE, buf, sizeof (buf));
1143 
1144 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1145 				    "one or more devices is less than the "
1146 				    "minimum size (%s)"), buf);
1147 			}
1148 			return (zfs_error(hdl, EZFS_BADDEV, msg));
1149 
1150 		case ENOSPC:
1151 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1152 			    "one or more devices is out of space"));
1153 			return (zfs_error(hdl, EZFS_BADDEV, msg));
1154 
1155 		case ENOTBLK:
1156 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1157 			    "cache device must be a disk or disk slice"));
1158 			return (zfs_error(hdl, EZFS_BADDEV, msg));
1159 
1160 		default:
1161 			return (zpool_standard_error(hdl, errno, msg));
1162 		}
1163 	}
1164 
1165 create_failed:
1166 	zcmd_free_nvlists(&zc);
1167 	nvlist_free(zc_props);
1168 	nvlist_free(zc_fsprops);
1169 	return (ret);
1170 }
1171 
1172 /*
1173  * Destroy the given pool.  It is up to the caller to ensure that there are no
1174  * datasets left in the pool.
1175  */
1176 int
1177 zpool_destroy(zpool_handle_t *zhp, const char *log_str)
1178 {
1179 	zfs_cmd_t zc = { 0 };
1180 	zfs_handle_t *zfp = NULL;
1181 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1182 	char msg[1024];
1183 
1184 	if (zhp->zpool_state == POOL_STATE_ACTIVE &&
1185 	    (zfp = zfs_open(hdl, zhp->zpool_name, ZFS_TYPE_FILESYSTEM)) == NULL)
1186 		return (-1);
1187 
1188 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1189 	zc.zc_history = (uint64_t)(uintptr_t)log_str;
1190 
1191 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_DESTROY, &zc) != 0) {
1192 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1193 		    "cannot destroy '%s'"), zhp->zpool_name);
1194 
1195 		if (errno == EROFS) {
1196 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1197 			    "one or more devices is read only"));
1198 			(void) zfs_error(hdl, EZFS_BADDEV, msg);
1199 		} else {
1200 			(void) zpool_standard_error(hdl, errno, msg);
1201 		}
1202 
1203 		if (zfp)
1204 			zfs_close(zfp);
1205 		return (-1);
1206 	}
1207 
1208 	if (zfp) {
1209 		remove_mountpoint(zfp);
1210 		zfs_close(zfp);
1211 	}
1212 
1213 	return (0);
1214 }
1215 
1216 /*
1217  * Add the given vdevs to the pool.  The caller must have already performed the
1218  * necessary verification to ensure that the vdev specification is well-formed.
1219  */
1220 int
1221 zpool_add(zpool_handle_t *zhp, nvlist_t *nvroot)
1222 {
1223 	zfs_cmd_t zc = { 0 };
1224 	int ret;
1225 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1226 	char msg[1024];
1227 	nvlist_t **spares, **l2cache;
1228 	uint_t nspares, nl2cache;
1229 
1230 	(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1231 	    "cannot add to '%s'"), zhp->zpool_name);
1232 
1233 	if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) <
1234 	    SPA_VERSION_SPARES &&
1235 	    nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1236 	    &spares, &nspares) == 0) {
1237 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be "
1238 		    "upgraded to add hot spares"));
1239 		return (zfs_error(hdl, EZFS_BADVERSION, msg));
1240 	}
1241 
1242 	if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) <
1243 	    SPA_VERSION_L2CACHE &&
1244 	    nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1245 	    &l2cache, &nl2cache) == 0) {
1246 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be "
1247 		    "upgraded to add cache devices"));
1248 		return (zfs_error(hdl, EZFS_BADVERSION, msg));
1249 	}
1250 
1251 	if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
1252 		return (-1);
1253 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1254 
1255 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_ADD, &zc) != 0) {
1256 		switch (errno) {
1257 		case EBUSY:
1258 			/*
1259 			 * This can happen if the user has specified the same
1260 			 * device multiple times.  We can't reliably detect this
1261 			 * until we try to add it and see we already have a
1262 			 * label.
1263 			 */
1264 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1265 			    "one or more vdevs refer to the same device"));
1266 			(void) zfs_error(hdl, EZFS_BADDEV, msg);
1267 			break;
1268 
1269 		case EOVERFLOW:
1270 			/*
1271 			 * This occurrs when one of the devices is below
1272 			 * SPA_MINDEVSIZE.  Unfortunately, we can't detect which
1273 			 * device was the problem device since there's no
1274 			 * reliable way to determine device size from userland.
1275 			 */
1276 			{
1277 				char buf[64];
1278 
1279 				zfs_nicenum(SPA_MINDEVSIZE, buf, sizeof (buf));
1280 
1281 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1282 				    "device is less than the minimum "
1283 				    "size (%s)"), buf);
1284 			}
1285 			(void) zfs_error(hdl, EZFS_BADDEV, msg);
1286 			break;
1287 
1288 		case ENOTSUP:
1289 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1290 			    "pool must be upgraded to add these vdevs"));
1291 			(void) zfs_error(hdl, EZFS_BADVERSION, msg);
1292 			break;
1293 
1294 		case EDOM:
1295 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1296 			    "root pool can not have multiple vdevs"
1297 			    " or separate logs"));
1298 			(void) zfs_error(hdl, EZFS_POOL_NOTSUP, msg);
1299 			break;
1300 
1301 		case ENOTBLK:
1302 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1303 			    "cache device must be a disk or disk slice"));
1304 			(void) zfs_error(hdl, EZFS_BADDEV, msg);
1305 			break;
1306 
1307 		default:
1308 			(void) zpool_standard_error(hdl, errno, msg);
1309 		}
1310 
1311 		ret = -1;
1312 	} else {
1313 		ret = 0;
1314 	}
1315 
1316 	zcmd_free_nvlists(&zc);
1317 
1318 	return (ret);
1319 }
1320 
1321 /*
1322  * Exports the pool from the system.  The caller must ensure that there are no
1323  * mounted datasets in the pool.
1324  */
1325 static int
1326 zpool_export_common(zpool_handle_t *zhp, boolean_t force, boolean_t hardforce,
1327     const char *log_str)
1328 {
1329 	zfs_cmd_t zc = { 0 };
1330 	char msg[1024];
1331 
1332 	(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1333 	    "cannot export '%s'"), zhp->zpool_name);
1334 
1335 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1336 	zc.zc_cookie = force;
1337 	zc.zc_guid = hardforce;
1338 	zc.zc_history = (uint64_t)(uintptr_t)log_str;
1339 
1340 	if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_EXPORT, &zc) != 0) {
1341 		switch (errno) {
1342 		case EXDEV:
1343 			zfs_error_aux(zhp->zpool_hdl, dgettext(TEXT_DOMAIN,
1344 			    "use '-f' to override the following errors:\n"
1345 			    "'%s' has an active shared spare which could be"
1346 			    " used by other pools once '%s' is exported."),
1347 			    zhp->zpool_name, zhp->zpool_name);
1348 			return (zfs_error(zhp->zpool_hdl, EZFS_ACTIVE_SPARE,
1349 			    msg));
1350 		default:
1351 			return (zpool_standard_error_fmt(zhp->zpool_hdl, errno,
1352 			    msg));
1353 		}
1354 	}
1355 
1356 	return (0);
1357 }
1358 
1359 int
1360 zpool_export(zpool_handle_t *zhp, boolean_t force, const char *log_str)
1361 {
1362 	return (zpool_export_common(zhp, force, B_FALSE, log_str));
1363 }
1364 
1365 int
1366 zpool_export_force(zpool_handle_t *zhp, const char *log_str)
1367 {
1368 	return (zpool_export_common(zhp, B_TRUE, B_TRUE, log_str));
1369 }
1370 
1371 static void
1372 zpool_rewind_exclaim(libzfs_handle_t *hdl, const char *name, boolean_t dryrun,
1373     nvlist_t *config)
1374 {
1375 	nvlist_t *nv = NULL;
1376 	uint64_t rewindto;
1377 	int64_t loss = -1;
1378 	struct tm t;
1379 	char timestr[128];
1380 
1381 	if (!hdl->libzfs_printerr || config == NULL)
1382 		return;
1383 
1384 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nv) != 0 ||
1385 	    nvlist_lookup_nvlist(nv, ZPOOL_CONFIG_REWIND_INFO, &nv) != 0) {
1386 		return;
1387 	}
1388 
1389 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_TIME, &rewindto) != 0)
1390 		return;
1391 	(void) nvlist_lookup_int64(nv, ZPOOL_CONFIG_REWIND_TIME, &loss);
1392 
1393 	if (localtime_r((time_t *)&rewindto, &t) != NULL &&
1394 	    strftime(timestr, 128, 0, &t) != 0) {
1395 		if (dryrun) {
1396 			(void) printf(dgettext(TEXT_DOMAIN,
1397 			    "Would be able to return %s "
1398 			    "to its state as of %s.\n"),
1399 			    name, timestr);
1400 		} else {
1401 			(void) printf(dgettext(TEXT_DOMAIN,
1402 			    "Pool %s returned to its state as of %s.\n"),
1403 			    name, timestr);
1404 		}
1405 		if (loss > 120) {
1406 			(void) printf(dgettext(TEXT_DOMAIN,
1407 			    "%s approximately %lld "),
1408 			    dryrun ? "Would discard" : "Discarded",
1409 			    (loss + 30) / 60);
1410 			(void) printf(dgettext(TEXT_DOMAIN,
1411 			    "minutes of transactions.\n"));
1412 		} else if (loss > 0) {
1413 			(void) printf(dgettext(TEXT_DOMAIN,
1414 			    "%s approximately %lld "),
1415 			    dryrun ? "Would discard" : "Discarded", loss);
1416 			(void) printf(dgettext(TEXT_DOMAIN,
1417 			    "seconds of transactions.\n"));
1418 		}
1419 	}
1420 }
1421 
1422 void
1423 zpool_explain_recover(libzfs_handle_t *hdl, const char *name, int reason,
1424     nvlist_t *config)
1425 {
1426 	nvlist_t *nv = NULL;
1427 	int64_t loss = -1;
1428 	uint64_t edata = UINT64_MAX;
1429 	uint64_t rewindto;
1430 	struct tm t;
1431 	char timestr[128];
1432 
1433 	if (!hdl->libzfs_printerr)
1434 		return;
1435 
1436 	if (reason >= 0)
1437 		(void) printf(dgettext(TEXT_DOMAIN, "action: "));
1438 	else
1439 		(void) printf(dgettext(TEXT_DOMAIN, "\t"));
1440 
1441 	/* All attempted rewinds failed if ZPOOL_CONFIG_LOAD_TIME missing */
1442 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nv) != 0 ||
1443 	    nvlist_lookup_nvlist(nv, ZPOOL_CONFIG_REWIND_INFO, &nv) != 0 ||
1444 	    nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_TIME, &rewindto) != 0)
1445 		goto no_info;
1446 
1447 	(void) nvlist_lookup_int64(nv, ZPOOL_CONFIG_REWIND_TIME, &loss);
1448 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_DATA_ERRORS,
1449 	    &edata);
1450 
1451 	(void) printf(dgettext(TEXT_DOMAIN,
1452 	    "Recovery is possible, but will result in some data loss.\n"));
1453 
1454 	if (localtime_r((time_t *)&rewindto, &t) != NULL &&
1455 	    strftime(timestr, 128, 0, &t) != 0) {
1456 		(void) printf(dgettext(TEXT_DOMAIN,
1457 		    "\tReturning the pool to its state as of %s\n"
1458 		    "\tshould correct the problem.  "),
1459 		    timestr);
1460 	} else {
1461 		(void) printf(dgettext(TEXT_DOMAIN,
1462 		    "\tReverting the pool to an earlier state "
1463 		    "should correct the problem.\n\t"));
1464 	}
1465 
1466 	if (loss > 120) {
1467 		(void) printf(dgettext(TEXT_DOMAIN,
1468 		    "Approximately %lld minutes of data\n"
1469 		    "\tmust be discarded, irreversibly.  "), (loss + 30) / 60);
1470 	} else if (loss > 0) {
1471 		(void) printf(dgettext(TEXT_DOMAIN,
1472 		    "Approximately %lld seconds of data\n"
1473 		    "\tmust be discarded, irreversibly.  "), loss);
1474 	}
1475 	if (edata != 0 && edata != UINT64_MAX) {
1476 		if (edata == 1) {
1477 			(void) printf(dgettext(TEXT_DOMAIN,
1478 			    "After rewind, at least\n"
1479 			    "\tone persistent user-data error will remain.  "));
1480 		} else {
1481 			(void) printf(dgettext(TEXT_DOMAIN,
1482 			    "After rewind, several\n"
1483 			    "\tpersistent user-data errors will remain.  "));
1484 		}
1485 	}
1486 	(void) printf(dgettext(TEXT_DOMAIN,
1487 	    "Recovery can be attempted\n\tby executing 'zpool %s -F %s'.  "),
1488 	    reason >= 0 ? "clear" : "import", name);
1489 
1490 	(void) printf(dgettext(TEXT_DOMAIN,
1491 	    "A scrub of the pool\n"
1492 	    "\tis strongly recommended after recovery.\n"));
1493 	return;
1494 
1495 no_info:
1496 	(void) printf(dgettext(TEXT_DOMAIN,
1497 	    "Destroy and re-create the pool from\n\ta backup source.\n"));
1498 }
1499 
1500 /*
1501  * zpool_import() is a contracted interface. Should be kept the same
1502  * if possible.
1503  *
1504  * Applications should use zpool_import_props() to import a pool with
1505  * new properties value to be set.
1506  */
1507 int
1508 zpool_import(libzfs_handle_t *hdl, nvlist_t *config, const char *newname,
1509     char *altroot)
1510 {
1511 	nvlist_t *props = NULL;
1512 	int ret;
1513 
1514 	if (altroot != NULL) {
1515 		if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
1516 			return (zfs_error_fmt(hdl, EZFS_NOMEM,
1517 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1518 			    newname));
1519 		}
1520 
1521 		if (nvlist_add_string(props,
1522 		    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), altroot) != 0 ||
1523 		    nvlist_add_string(props,
1524 		    zpool_prop_to_name(ZPOOL_PROP_CACHEFILE), "none") != 0) {
1525 			nvlist_free(props);
1526 			return (zfs_error_fmt(hdl, EZFS_NOMEM,
1527 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1528 			    newname));
1529 		}
1530 	}
1531 
1532 	ret = zpool_import_props(hdl, config, newname, props,
1533 	    ZFS_IMPORT_NORMAL);
1534 	nvlist_free(props);
1535 	return (ret);
1536 }
1537 
1538 static void
1539 print_vdev_tree(libzfs_handle_t *hdl, const char *name, nvlist_t *nv,
1540     int indent)
1541 {
1542 	nvlist_t **child;
1543 	uint_t c, children;
1544 	char *vname;
1545 	uint64_t is_log = 0;
1546 
1547 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG,
1548 	    &is_log);
1549 
1550 	if (name != NULL)
1551 		(void) printf("\t%*s%s%s\n", indent, "", name,
1552 		    is_log ? " [log]" : "");
1553 
1554 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1555 	    &child, &children) != 0)
1556 		return;
1557 
1558 	for (c = 0; c < children; c++) {
1559 		vname = zpool_vdev_name(hdl, NULL, child[c], B_TRUE);
1560 		print_vdev_tree(hdl, vname, child[c], indent + 2);
1561 		free(vname);
1562 	}
1563 }
1564 
1565 void
1566 zpool_print_unsup_feat(nvlist_t *config)
1567 {
1568 	nvlist_t *nvinfo, *unsup_feat;
1569 
1570 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nvinfo) ==
1571 	    0);
1572 	verify(nvlist_lookup_nvlist(nvinfo, ZPOOL_CONFIG_UNSUP_FEAT,
1573 	    &unsup_feat) == 0);
1574 
1575 	for (nvpair_t *nvp = nvlist_next_nvpair(unsup_feat, NULL); nvp != NULL;
1576 	    nvp = nvlist_next_nvpair(unsup_feat, nvp)) {
1577 		char *desc;
1578 
1579 		verify(nvpair_type(nvp) == DATA_TYPE_STRING);
1580 		verify(nvpair_value_string(nvp, &desc) == 0);
1581 
1582 		if (strlen(desc) > 0)
1583 			(void) printf("\t%s (%s)\n", nvpair_name(nvp), desc);
1584 		else
1585 			(void) printf("\t%s\n", nvpair_name(nvp));
1586 	}
1587 }
1588 
1589 /*
1590  * Import the given pool using the known configuration and a list of
1591  * properties to be set. The configuration should have come from
1592  * zpool_find_import(). The 'newname' parameters control whether the pool
1593  * is imported with a different name.
1594  */
1595 int
1596 zpool_import_props(libzfs_handle_t *hdl, nvlist_t *config, const char *newname,
1597     nvlist_t *props, int flags)
1598 {
1599 	zfs_cmd_t zc = { 0 };
1600 	zpool_rewind_policy_t policy;
1601 	nvlist_t *nv = NULL;
1602 	nvlist_t *nvinfo = NULL;
1603 	nvlist_t *missing = NULL;
1604 	char *thename;
1605 	char *origname;
1606 	int ret;
1607 	int error = 0;
1608 	char errbuf[1024];
1609 
1610 	verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1611 	    &origname) == 0);
1612 
1613 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1614 	    "cannot import pool '%s'"), origname);
1615 
1616 	if (newname != NULL) {
1617 		if (!zpool_name_valid(hdl, B_FALSE, newname))
1618 			return (zfs_error_fmt(hdl, EZFS_INVALIDNAME,
1619 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1620 			    newname));
1621 		thename = (char *)newname;
1622 	} else {
1623 		thename = origname;
1624 	}
1625 
1626 	if (props != NULL) {
1627 		uint64_t version;
1628 		prop_flags_t flags = { .create = B_FALSE, .import = B_TRUE };
1629 
1630 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
1631 		    &version) == 0);
1632 
1633 		if ((props = zpool_valid_proplist(hdl, origname,
1634 		    props, version, flags, errbuf)) == NULL)
1635 			return (-1);
1636 		if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) {
1637 			nvlist_free(props);
1638 			return (-1);
1639 		}
1640 		nvlist_free(props);
1641 	}
1642 
1643 	(void) strlcpy(zc.zc_name, thename, sizeof (zc.zc_name));
1644 
1645 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1646 	    &zc.zc_guid) == 0);
1647 
1648 	if (zcmd_write_conf_nvlist(hdl, &zc, config) != 0) {
1649 		zcmd_free_nvlists(&zc);
1650 		return (-1);
1651 	}
1652 	if (zcmd_alloc_dst_nvlist(hdl, &zc, zc.zc_nvlist_conf_size * 2) != 0) {
1653 		zcmd_free_nvlists(&zc);
1654 		return (-1);
1655 	}
1656 
1657 	zc.zc_cookie = flags;
1658 	while ((ret = zfs_ioctl(hdl, ZFS_IOC_POOL_IMPORT, &zc)) != 0 &&
1659 	    errno == ENOMEM) {
1660 		if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
1661 			zcmd_free_nvlists(&zc);
1662 			return (-1);
1663 		}
1664 	}
1665 	if (ret != 0)
1666 		error = errno;
1667 
1668 	(void) zcmd_read_dst_nvlist(hdl, &zc, &nv);
1669 
1670 	zcmd_free_nvlists(&zc);
1671 
1672 	zpool_get_rewind_policy(config, &policy);
1673 
1674 	if (error) {
1675 		char desc[1024];
1676 
1677 		/*
1678 		 * Dry-run failed, but we print out what success
1679 		 * looks like if we found a best txg
1680 		 */
1681 		if (policy.zrp_request & ZPOOL_TRY_REWIND) {
1682 			zpool_rewind_exclaim(hdl, newname ? origname : thename,
1683 			    B_TRUE, nv);
1684 			nvlist_free(nv);
1685 			return (-1);
1686 		}
1687 
1688 		if (newname == NULL)
1689 			(void) snprintf(desc, sizeof (desc),
1690 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1691 			    thename);
1692 		else
1693 			(void) snprintf(desc, sizeof (desc),
1694 			    dgettext(TEXT_DOMAIN, "cannot import '%s' as '%s'"),
1695 			    origname, thename);
1696 
1697 		switch (error) {
1698 		case ENOTSUP:
1699 			if (nv != NULL && nvlist_lookup_nvlist(nv,
1700 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0 &&
1701 			    nvlist_exists(nvinfo, ZPOOL_CONFIG_UNSUP_FEAT)) {
1702 				(void) printf(dgettext(TEXT_DOMAIN, "This "
1703 				    "pool uses the following feature(s) not "
1704 				    "supported by this system:\n"));
1705 				zpool_print_unsup_feat(nv);
1706 				if (nvlist_exists(nvinfo,
1707 				    ZPOOL_CONFIG_CAN_RDONLY)) {
1708 					(void) printf(dgettext(TEXT_DOMAIN,
1709 					    "All unsupported features are only "
1710 					    "required for writing to the pool."
1711 					    "\nThe pool can be imported using "
1712 					    "'-o readonly=on'.\n"));
1713 				}
1714 			}
1715 			/*
1716 			 * Unsupported version.
1717 			 */
1718 			(void) zfs_error(hdl, EZFS_BADVERSION, desc);
1719 			break;
1720 
1721 		case EINVAL:
1722 			(void) zfs_error(hdl, EZFS_INVALCONFIG, desc);
1723 			break;
1724 
1725 		case EROFS:
1726 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1727 			    "one or more devices is read only"));
1728 			(void) zfs_error(hdl, EZFS_BADDEV, desc);
1729 			break;
1730 
1731 		case ENXIO:
1732 			if (nv && nvlist_lookup_nvlist(nv,
1733 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0 &&
1734 			    nvlist_lookup_nvlist(nvinfo,
1735 			    ZPOOL_CONFIG_MISSING_DEVICES, &missing) == 0) {
1736 				(void) printf(dgettext(TEXT_DOMAIN,
1737 				    "The devices below are missing, use "
1738 				    "'-m' to import the pool anyway:\n"));
1739 				print_vdev_tree(hdl, NULL, missing, 2);
1740 				(void) printf("\n");
1741 			}
1742 			(void) zpool_standard_error(hdl, error, desc);
1743 			break;
1744 
1745 		case EEXIST:
1746 			(void) zpool_standard_error(hdl, error, desc);
1747 			break;
1748 
1749 		default:
1750 			(void) zpool_standard_error(hdl, error, desc);
1751 			zpool_explain_recover(hdl,
1752 			    newname ? origname : thename, -error, nv);
1753 			break;
1754 		}
1755 
1756 		nvlist_free(nv);
1757 		ret = -1;
1758 	} else {
1759 		zpool_handle_t *zhp;
1760 
1761 		/*
1762 		 * This should never fail, but play it safe anyway.
1763 		 */
1764 		if (zpool_open_silent(hdl, thename, &zhp) != 0)
1765 			ret = -1;
1766 		else if (zhp != NULL)
1767 			zpool_close(zhp);
1768 		if (policy.zrp_request &
1769 		    (ZPOOL_DO_REWIND | ZPOOL_TRY_REWIND)) {
1770 			zpool_rewind_exclaim(hdl, newname ? origname : thename,
1771 			    ((policy.zrp_request & ZPOOL_TRY_REWIND) != 0), nv);
1772 		}
1773 		nvlist_free(nv);
1774 		return (0);
1775 	}
1776 
1777 	return (ret);
1778 }
1779 
1780 /*
1781  * Scan the pool.
1782  */
1783 int
1784 zpool_scan(zpool_handle_t *zhp, pool_scan_func_t func)
1785 {
1786 	zfs_cmd_t zc = { 0 };
1787 	char msg[1024];
1788 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1789 
1790 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1791 	zc.zc_cookie = func;
1792 
1793 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_SCAN, &zc) == 0 ||
1794 	    (errno == ENOENT && func != POOL_SCAN_NONE))
1795 		return (0);
1796 
1797 	if (func == POOL_SCAN_SCRUB) {
1798 		(void) snprintf(msg, sizeof (msg),
1799 		    dgettext(TEXT_DOMAIN, "cannot scrub %s"), zc.zc_name);
1800 	} else if (func == POOL_SCAN_NONE) {
1801 		(void) snprintf(msg, sizeof (msg),
1802 		    dgettext(TEXT_DOMAIN, "cannot cancel scrubbing %s"),
1803 		    zc.zc_name);
1804 	} else {
1805 		assert(!"unexpected result");
1806 	}
1807 
1808 	if (errno == EBUSY) {
1809 		nvlist_t *nvroot;
1810 		pool_scan_stat_t *ps = NULL;
1811 		uint_t psc;
1812 
1813 		verify(nvlist_lookup_nvlist(zhp->zpool_config,
1814 		    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
1815 		(void) nvlist_lookup_uint64_array(nvroot,
1816 		    ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &psc);
1817 		if (ps && ps->pss_func == POOL_SCAN_SCRUB)
1818 			return (zfs_error(hdl, EZFS_SCRUBBING, msg));
1819 		else
1820 			return (zfs_error(hdl, EZFS_RESILVERING, msg));
1821 	} else if (errno == ENOENT) {
1822 		return (zfs_error(hdl, EZFS_NO_SCRUB, msg));
1823 	} else {
1824 		return (zpool_standard_error(hdl, errno, msg));
1825 	}
1826 }
1827 
1828 /*
1829  * This provides a very minimal check whether a given string is likely a
1830  * c#t#d# style string.  Users of this are expected to do their own
1831  * verification of the s# part.
1832  */
1833 #define	CTD_CHECK(str)  (str && str[0] == 'c' && isdigit(str[1]))
1834 
1835 /*
1836  * More elaborate version for ones which may start with "/dev/dsk/"
1837  * and the like.
1838  */
1839 static int
1840 ctd_check_path(char *str) {
1841 	/*
1842 	 * If it starts with a slash, check the last component.
1843 	 */
1844 	if (str && str[0] == '/') {
1845 		char *tmp = strrchr(str, '/');
1846 
1847 		/*
1848 		 * If it ends in "/old", check the second-to-last
1849 		 * component of the string instead.
1850 		 */
1851 		if (tmp != str && strcmp(tmp, "/old") == 0) {
1852 			for (tmp--; *tmp != '/'; tmp--)
1853 				;
1854 		}
1855 		str = tmp + 1;
1856 	}
1857 	return (CTD_CHECK(str));
1858 }
1859 
1860 /*
1861  * Find a vdev that matches the search criteria specified. We use the
1862  * the nvpair name to determine how we should look for the device.
1863  * 'avail_spare' is set to TRUE if the provided guid refers to an AVAIL
1864  * spare; but FALSE if its an INUSE spare.
1865  */
1866 static nvlist_t *
1867 vdev_to_nvlist_iter(nvlist_t *nv, nvlist_t *search, boolean_t *avail_spare,
1868     boolean_t *l2cache, boolean_t *log)
1869 {
1870 	uint_t c, children;
1871 	nvlist_t **child;
1872 	nvlist_t *ret;
1873 	uint64_t is_log;
1874 	char *srchkey;
1875 	nvpair_t *pair = nvlist_next_nvpair(search, NULL);
1876 
1877 	/* Nothing to look for */
1878 	if (search == NULL || pair == NULL)
1879 		return (NULL);
1880 
1881 	/* Obtain the key we will use to search */
1882 	srchkey = nvpair_name(pair);
1883 
1884 	switch (nvpair_type(pair)) {
1885 	case DATA_TYPE_UINT64:
1886 		if (strcmp(srchkey, ZPOOL_CONFIG_GUID) == 0) {
1887 			uint64_t srchval, theguid;
1888 
1889 			verify(nvpair_value_uint64(pair, &srchval) == 0);
1890 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
1891 			    &theguid) == 0);
1892 			if (theguid == srchval)
1893 				return (nv);
1894 		}
1895 		break;
1896 
1897 	case DATA_TYPE_STRING: {
1898 		char *srchval, *val;
1899 
1900 		verify(nvpair_value_string(pair, &srchval) == 0);
1901 		if (nvlist_lookup_string(nv, srchkey, &val) != 0)
1902 			break;
1903 
1904 		/*
1905 		 * Search for the requested value. Special cases:
1906 		 *
1907 		 * - ZPOOL_CONFIG_PATH for whole disk entries.  These end in
1908 		 *   "s0" or "s0/old".  The "s0" part is hidden from the user,
1909 		 *   but included in the string, so this matches around it.
1910 		 * - looking for a top-level vdev name (i.e. ZPOOL_CONFIG_TYPE).
1911 		 *
1912 		 * Otherwise, all other searches are simple string compares.
1913 		 */
1914 		if (strcmp(srchkey, ZPOOL_CONFIG_PATH) == 0 &&
1915 		    ctd_check_path(val)) {
1916 			uint64_t wholedisk = 0;
1917 
1918 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
1919 			    &wholedisk);
1920 			if (wholedisk) {
1921 				int slen = strlen(srchval);
1922 				int vlen = strlen(val);
1923 
1924 				if (slen != vlen - 2)
1925 					break;
1926 
1927 				/*
1928 				 * make_leaf_vdev() should only set
1929 				 * wholedisk for ZPOOL_CONFIG_PATHs which
1930 				 * will include "/dev/dsk/", giving plenty of
1931 				 * room for the indices used next.
1932 				 */
1933 				ASSERT(vlen >= 6);
1934 
1935 				/*
1936 				 * strings identical except trailing "s0"
1937 				 */
1938 				if (strcmp(&val[vlen - 2], "s0") == 0 &&
1939 				    strncmp(srchval, val, slen) == 0)
1940 					return (nv);
1941 
1942 				/*
1943 				 * strings identical except trailing "s0/old"
1944 				 */
1945 				if (strcmp(&val[vlen - 6], "s0/old") == 0 &&
1946 				    strcmp(&srchval[slen - 4], "/old") == 0 &&
1947 				    strncmp(srchval, val, slen - 4) == 0)
1948 					return (nv);
1949 
1950 				break;
1951 			}
1952 		} else if (strcmp(srchkey, ZPOOL_CONFIG_TYPE) == 0 && val) {
1953 			char *type, *idx, *end, *p;
1954 			uint64_t id, vdev_id;
1955 
1956 			/*
1957 			 * Determine our vdev type, keeping in mind
1958 			 * that the srchval is composed of a type and
1959 			 * vdev id pair (i.e. mirror-4).
1960 			 */
1961 			if ((type = strdup(srchval)) == NULL)
1962 				return (NULL);
1963 
1964 			if ((p = strrchr(type, '-')) == NULL) {
1965 				free(type);
1966 				break;
1967 			}
1968 			idx = p + 1;
1969 			*p = '\0';
1970 
1971 			/*
1972 			 * If the types don't match then keep looking.
1973 			 */
1974 			if (strncmp(val, type, strlen(val)) != 0) {
1975 				free(type);
1976 				break;
1977 			}
1978 
1979 			verify(strncmp(type, VDEV_TYPE_RAIDZ,
1980 			    strlen(VDEV_TYPE_RAIDZ)) == 0 ||
1981 			    strncmp(type, VDEV_TYPE_MIRROR,
1982 			    strlen(VDEV_TYPE_MIRROR)) == 0);
1983 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID,
1984 			    &id) == 0);
1985 
1986 			errno = 0;
1987 			vdev_id = strtoull(idx, &end, 10);
1988 
1989 			free(type);
1990 			if (errno != 0)
1991 				return (NULL);
1992 
1993 			/*
1994 			 * Now verify that we have the correct vdev id.
1995 			 */
1996 			if (vdev_id == id)
1997 				return (nv);
1998 		}
1999 
2000 		/*
2001 		 * Common case
2002 		 */
2003 		if (strcmp(srchval, val) == 0)
2004 			return (nv);
2005 		break;
2006 	}
2007 
2008 	default:
2009 		break;
2010 	}
2011 
2012 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2013 	    &child, &children) != 0)
2014 		return (NULL);
2015 
2016 	for (c = 0; c < children; c++) {
2017 		if ((ret = vdev_to_nvlist_iter(child[c], search,
2018 		    avail_spare, l2cache, NULL)) != NULL) {
2019 			/*
2020 			 * The 'is_log' value is only set for the toplevel
2021 			 * vdev, not the leaf vdevs.  So we always lookup the
2022 			 * log device from the root of the vdev tree (where
2023 			 * 'log' is non-NULL).
2024 			 */
2025 			if (log != NULL &&
2026 			    nvlist_lookup_uint64(child[c],
2027 			    ZPOOL_CONFIG_IS_LOG, &is_log) == 0 &&
2028 			    is_log) {
2029 				*log = B_TRUE;
2030 			}
2031 			return (ret);
2032 		}
2033 	}
2034 
2035 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
2036 	    &child, &children) == 0) {
2037 		for (c = 0; c < children; c++) {
2038 			if ((ret = vdev_to_nvlist_iter(child[c], search,
2039 			    avail_spare, l2cache, NULL)) != NULL) {
2040 				*avail_spare = B_TRUE;
2041 				return (ret);
2042 			}
2043 		}
2044 	}
2045 
2046 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
2047 	    &child, &children) == 0) {
2048 		for (c = 0; c < children; c++) {
2049 			if ((ret = vdev_to_nvlist_iter(child[c], search,
2050 			    avail_spare, l2cache, NULL)) != NULL) {
2051 				*l2cache = B_TRUE;
2052 				return (ret);
2053 			}
2054 		}
2055 	}
2056 
2057 	return (NULL);
2058 }
2059 
2060 /*
2061  * Given a physical path (minus the "/devices" prefix), find the
2062  * associated vdev.
2063  */
2064 nvlist_t *
2065 zpool_find_vdev_by_physpath(zpool_handle_t *zhp, const char *ppath,
2066     boolean_t *avail_spare, boolean_t *l2cache, boolean_t *log)
2067 {
2068 	nvlist_t *search, *nvroot, *ret;
2069 
2070 	verify(nvlist_alloc(&search, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2071 	verify(nvlist_add_string(search, ZPOOL_CONFIG_PHYS_PATH, ppath) == 0);
2072 
2073 	verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
2074 	    &nvroot) == 0);
2075 
2076 	*avail_spare = B_FALSE;
2077 	*l2cache = B_FALSE;
2078 	if (log != NULL)
2079 		*log = B_FALSE;
2080 	ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log);
2081 	nvlist_free(search);
2082 
2083 	return (ret);
2084 }
2085 
2086 /*
2087  * Determine if we have an "interior" top-level vdev (i.e mirror/raidz).
2088  */
2089 boolean_t
2090 zpool_vdev_is_interior(const char *name)
2091 {
2092 	if (strncmp(name, VDEV_TYPE_RAIDZ, strlen(VDEV_TYPE_RAIDZ)) == 0 ||
2093 	    strncmp(name, VDEV_TYPE_MIRROR, strlen(VDEV_TYPE_MIRROR)) == 0)
2094 		return (B_TRUE);
2095 	return (B_FALSE);
2096 }
2097 
2098 nvlist_t *
2099 zpool_find_vdev(zpool_handle_t *zhp, const char *path, boolean_t *avail_spare,
2100     boolean_t *l2cache, boolean_t *log)
2101 {
2102 	char buf[MAXPATHLEN];
2103 	char *end;
2104 	nvlist_t *nvroot, *search, *ret;
2105 	uint64_t guid;
2106 
2107 	verify(nvlist_alloc(&search, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2108 
2109 	guid = strtoull(path, &end, 10);
2110 	if (guid != 0 && *end == '\0') {
2111 		verify(nvlist_add_uint64(search, ZPOOL_CONFIG_GUID, guid) == 0);
2112 	} else if (zpool_vdev_is_interior(path)) {
2113 		verify(nvlist_add_string(search, ZPOOL_CONFIG_TYPE, path) == 0);
2114 	} else if (path[0] != '/') {
2115 		(void) snprintf(buf, sizeof (buf), "%s%s", "/dev/dsk/", path);
2116 		verify(nvlist_add_string(search, ZPOOL_CONFIG_PATH, buf) == 0);
2117 	} else {
2118 		verify(nvlist_add_string(search, ZPOOL_CONFIG_PATH, path) == 0);
2119 	}
2120 
2121 	verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
2122 	    &nvroot) == 0);
2123 
2124 	*avail_spare = B_FALSE;
2125 	*l2cache = B_FALSE;
2126 	if (log != NULL)
2127 		*log = B_FALSE;
2128 	ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log);
2129 	nvlist_free(search);
2130 
2131 	return (ret);
2132 }
2133 
2134 static int
2135 vdev_online(nvlist_t *nv)
2136 {
2137 	uint64_t ival;
2138 
2139 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE, &ival) == 0 ||
2140 	    nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED, &ival) == 0 ||
2141 	    nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED, &ival) == 0)
2142 		return (0);
2143 
2144 	return (1);
2145 }
2146 
2147 /*
2148  * Helper function for zpool_get_physpaths().
2149  */
2150 static int
2151 vdev_get_one_physpath(nvlist_t *config, char *physpath, size_t physpath_size,
2152     size_t *bytes_written)
2153 {
2154 	size_t bytes_left, pos, rsz;
2155 	char *tmppath;
2156 	const char *format;
2157 
2158 	if (nvlist_lookup_string(config, ZPOOL_CONFIG_PHYS_PATH,
2159 	    &tmppath) != 0)
2160 		return (EZFS_NODEVICE);
2161 
2162 	pos = *bytes_written;
2163 	bytes_left = physpath_size - pos;
2164 	format = (pos == 0) ? "%s" : " %s";
2165 
2166 	rsz = snprintf(physpath + pos, bytes_left, format, tmppath);
2167 	*bytes_written += rsz;
2168 
2169 	if (rsz >= bytes_left) {
2170 		/* if physpath was not copied properly, clear it */
2171 		if (bytes_left != 0) {
2172 			physpath[pos] = 0;
2173 		}
2174 		return (EZFS_NOSPC);
2175 	}
2176 	return (0);
2177 }
2178 
2179 static int
2180 vdev_get_physpaths(nvlist_t *nv, char *physpath, size_t phypath_size,
2181     size_t *rsz, boolean_t is_spare)
2182 {
2183 	char *type;
2184 	int ret;
2185 
2186 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
2187 		return (EZFS_INVALCONFIG);
2188 
2189 	if (strcmp(type, VDEV_TYPE_DISK) == 0) {
2190 		/*
2191 		 * An active spare device has ZPOOL_CONFIG_IS_SPARE set.
2192 		 * For a spare vdev, we only want to boot from the active
2193 		 * spare device.
2194 		 */
2195 		if (is_spare) {
2196 			uint64_t spare = 0;
2197 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE,
2198 			    &spare);
2199 			if (!spare)
2200 				return (EZFS_INVALCONFIG);
2201 		}
2202 
2203 		if (vdev_online(nv)) {
2204 			if ((ret = vdev_get_one_physpath(nv, physpath,
2205 			    phypath_size, rsz)) != 0)
2206 				return (ret);
2207 		}
2208 	} else if (strcmp(type, VDEV_TYPE_MIRROR) == 0 ||
2209 	    strcmp(type, VDEV_TYPE_REPLACING) == 0 ||
2210 	    (is_spare = (strcmp(type, VDEV_TYPE_SPARE) == 0))) {
2211 		nvlist_t **child;
2212 		uint_t count;
2213 		int i, ret;
2214 
2215 		if (nvlist_lookup_nvlist_array(nv,
2216 		    ZPOOL_CONFIG_CHILDREN, &child, &count) != 0)
2217 			return (EZFS_INVALCONFIG);
2218 
2219 		for (i = 0; i < count; i++) {
2220 			ret = vdev_get_physpaths(child[i], physpath,
2221 			    phypath_size, rsz, is_spare);
2222 			if (ret == EZFS_NOSPC)
2223 				return (ret);
2224 		}
2225 	}
2226 
2227 	return (EZFS_POOL_INVALARG);
2228 }
2229 
2230 /*
2231  * Get phys_path for a root pool config.
2232  * Return 0 on success; non-zero on failure.
2233  */
2234 static int
2235 zpool_get_config_physpath(nvlist_t *config, char *physpath, size_t phypath_size)
2236 {
2237 	size_t rsz;
2238 	nvlist_t *vdev_root;
2239 	nvlist_t **child;
2240 	uint_t count;
2241 	char *type;
2242 
2243 	rsz = 0;
2244 
2245 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2246 	    &vdev_root) != 0)
2247 		return (EZFS_INVALCONFIG);
2248 
2249 	if (nvlist_lookup_string(vdev_root, ZPOOL_CONFIG_TYPE, &type) != 0 ||
2250 	    nvlist_lookup_nvlist_array(vdev_root, ZPOOL_CONFIG_CHILDREN,
2251 	    &child, &count) != 0)
2252 		return (EZFS_INVALCONFIG);
2253 
2254 	/*
2255 	 * root pool can only have a single top-level vdev.
2256 	 */
2257 	if (strcmp(type, VDEV_TYPE_ROOT) != 0 || count != 1)
2258 		return (EZFS_POOL_INVALARG);
2259 
2260 	(void) vdev_get_physpaths(child[0], physpath, phypath_size, &rsz,
2261 	    B_FALSE);
2262 
2263 	/* No online devices */
2264 	if (rsz == 0)
2265 		return (EZFS_NODEVICE);
2266 
2267 	return (0);
2268 }
2269 
2270 /*
2271  * Get phys_path for a root pool
2272  * Return 0 on success; non-zero on failure.
2273  */
2274 int
2275 zpool_get_physpath(zpool_handle_t *zhp, char *physpath, size_t phypath_size)
2276 {
2277 	return (zpool_get_config_physpath(zhp->zpool_config, physpath,
2278 	    phypath_size));
2279 }
2280 
2281 /*
2282  * If the device has being dynamically expanded then we need to relabel
2283  * the disk to use the new unallocated space.
2284  */
2285 static int
2286 zpool_relabel_disk(libzfs_handle_t *hdl, const char *name)
2287 {
2288 	char path[MAXPATHLEN];
2289 	char errbuf[1024];
2290 	int fd, error;
2291 	int (*_efi_use_whole_disk)(int);
2292 
2293 	if ((_efi_use_whole_disk = (int (*)(int))dlsym(RTLD_DEFAULT,
2294 	    "efi_use_whole_disk")) == NULL)
2295 		return (-1);
2296 
2297 	(void) snprintf(path, sizeof (path), "%s/%s", RDISK_ROOT, name);
2298 
2299 	if ((fd = open(path, O_RDWR | O_NDELAY)) < 0) {
2300 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot "
2301 		    "relabel '%s': unable to open device"), name);
2302 		return (zfs_error(hdl, EZFS_OPENFAILED, errbuf));
2303 	}
2304 
2305 	/*
2306 	 * It's possible that we might encounter an error if the device
2307 	 * does not have any unallocated space left. If so, we simply
2308 	 * ignore that error and continue on.
2309 	 */
2310 	error = _efi_use_whole_disk(fd);
2311 	(void) close(fd);
2312 	if (error && error != VT_ENOSPC) {
2313 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot "
2314 		    "relabel '%s': unable to read disk capacity"), name);
2315 		return (zfs_error(hdl, EZFS_NOCAP, errbuf));
2316 	}
2317 	return (0);
2318 }
2319 
2320 /*
2321  * Bring the specified vdev online.   The 'flags' parameter is a set of the
2322  * ZFS_ONLINE_* flags.
2323  */
2324 int
2325 zpool_vdev_online(zpool_handle_t *zhp, const char *path, int flags,
2326     vdev_state_t *newstate)
2327 {
2328 	zfs_cmd_t zc = { 0 };
2329 	char msg[1024];
2330 	nvlist_t *tgt;
2331 	boolean_t avail_spare, l2cache, islog;
2332 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2333 
2334 	if (flags & ZFS_ONLINE_EXPAND) {
2335 		(void) snprintf(msg, sizeof (msg),
2336 		    dgettext(TEXT_DOMAIN, "cannot expand %s"), path);
2337 	} else {
2338 		(void) snprintf(msg, sizeof (msg),
2339 		    dgettext(TEXT_DOMAIN, "cannot online %s"), path);
2340 	}
2341 
2342 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2343 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
2344 	    &islog)) == NULL)
2345 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
2346 
2347 	verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2348 
2349 	if (avail_spare)
2350 		return (zfs_error(hdl, EZFS_ISSPARE, msg));
2351 
2352 	if (flags & ZFS_ONLINE_EXPAND ||
2353 	    zpool_get_prop_int(zhp, ZPOOL_PROP_AUTOEXPAND, NULL)) {
2354 		char *pathname = NULL;
2355 		uint64_t wholedisk = 0;
2356 
2357 		(void) nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_WHOLE_DISK,
2358 		    &wholedisk);
2359 		verify(nvlist_lookup_string(tgt, ZPOOL_CONFIG_PATH,
2360 		    &pathname) == 0);
2361 
2362 		/*
2363 		 * XXX - L2ARC 1.0 devices can't support expansion.
2364 		 */
2365 		if (l2cache) {
2366 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2367 			    "cannot expand cache devices"));
2368 			return (zfs_error(hdl, EZFS_VDEVNOTSUP, msg));
2369 		}
2370 
2371 		if (wholedisk) {
2372 			pathname += strlen(DISK_ROOT) + 1;
2373 			(void) zpool_relabel_disk(hdl, pathname);
2374 		}
2375 	}
2376 
2377 	zc.zc_cookie = VDEV_STATE_ONLINE;
2378 	zc.zc_obj = flags;
2379 
2380 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) != 0) {
2381 		if (errno == EINVAL) {
2382 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "was split "
2383 			    "from this pool into a new one.  Use '%s' "
2384 			    "instead"), "zpool detach");
2385 			return (zfs_error(hdl, EZFS_POSTSPLIT_ONLINE, msg));
2386 		}
2387 		return (zpool_standard_error(hdl, errno, msg));
2388 	}
2389 
2390 	*newstate = zc.zc_cookie;
2391 	return (0);
2392 }
2393 
2394 /*
2395  * Take the specified vdev offline
2396  */
2397 int
2398 zpool_vdev_offline(zpool_handle_t *zhp, const char *path, boolean_t istmp)
2399 {
2400 	zfs_cmd_t zc = { 0 };
2401 	char msg[1024];
2402 	nvlist_t *tgt;
2403 	boolean_t avail_spare, l2cache;
2404 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2405 
2406 	(void) snprintf(msg, sizeof (msg),
2407 	    dgettext(TEXT_DOMAIN, "cannot offline %s"), path);
2408 
2409 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2410 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
2411 	    NULL)) == NULL)
2412 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
2413 
2414 	verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2415 
2416 	if (avail_spare)
2417 		return (zfs_error(hdl, EZFS_ISSPARE, msg));
2418 
2419 	zc.zc_cookie = VDEV_STATE_OFFLINE;
2420 	zc.zc_obj = istmp ? ZFS_OFFLINE_TEMPORARY : 0;
2421 
2422 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2423 		return (0);
2424 
2425 	switch (errno) {
2426 	case EBUSY:
2427 
2428 		/*
2429 		 * There are no other replicas of this device.
2430 		 */
2431 		return (zfs_error(hdl, EZFS_NOREPLICAS, msg));
2432 
2433 	case EEXIST:
2434 		/*
2435 		 * The log device has unplayed logs
2436 		 */
2437 		return (zfs_error(hdl, EZFS_UNPLAYED_LOGS, msg));
2438 
2439 	default:
2440 		return (zpool_standard_error(hdl, errno, msg));
2441 	}
2442 }
2443 
2444 /*
2445  * Mark the given vdev faulted.
2446  */
2447 int
2448 zpool_vdev_fault(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux)
2449 {
2450 	zfs_cmd_t zc = { 0 };
2451 	char msg[1024];
2452 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2453 
2454 	(void) snprintf(msg, sizeof (msg),
2455 	    dgettext(TEXT_DOMAIN, "cannot fault %llu"), guid);
2456 
2457 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2458 	zc.zc_guid = guid;
2459 	zc.zc_cookie = VDEV_STATE_FAULTED;
2460 	zc.zc_obj = aux;
2461 
2462 	if (ioctl(hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2463 		return (0);
2464 
2465 	switch (errno) {
2466 	case EBUSY:
2467 
2468 		/*
2469 		 * There are no other replicas of this device.
2470 		 */
2471 		return (zfs_error(hdl, EZFS_NOREPLICAS, msg));
2472 
2473 	default:
2474 		return (zpool_standard_error(hdl, errno, msg));
2475 	}
2476 
2477 }
2478 
2479 /*
2480  * Mark the given vdev degraded.
2481  */
2482 int
2483 zpool_vdev_degrade(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux)
2484 {
2485 	zfs_cmd_t zc = { 0 };
2486 	char msg[1024];
2487 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2488 
2489 	(void) snprintf(msg, sizeof (msg),
2490 	    dgettext(TEXT_DOMAIN, "cannot degrade %llu"), guid);
2491 
2492 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2493 	zc.zc_guid = guid;
2494 	zc.zc_cookie = VDEV_STATE_DEGRADED;
2495 	zc.zc_obj = aux;
2496 
2497 	if (ioctl(hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2498 		return (0);
2499 
2500 	return (zpool_standard_error(hdl, errno, msg));
2501 }
2502 
2503 /*
2504  * Returns TRUE if the given nvlist is a vdev that was originally swapped in as
2505  * a hot spare.
2506  */
2507 static boolean_t
2508 is_replacing_spare(nvlist_t *search, nvlist_t *tgt, int which)
2509 {
2510 	nvlist_t **child;
2511 	uint_t c, children;
2512 	char *type;
2513 
2514 	if (nvlist_lookup_nvlist_array(search, ZPOOL_CONFIG_CHILDREN, &child,
2515 	    &children) == 0) {
2516 		verify(nvlist_lookup_string(search, ZPOOL_CONFIG_TYPE,
2517 		    &type) == 0);
2518 
2519 		if (strcmp(type, VDEV_TYPE_SPARE) == 0 &&
2520 		    children == 2 && child[which] == tgt)
2521 			return (B_TRUE);
2522 
2523 		for (c = 0; c < children; c++)
2524 			if (is_replacing_spare(child[c], tgt, which))
2525 				return (B_TRUE);
2526 	}
2527 
2528 	return (B_FALSE);
2529 }
2530 
2531 /*
2532  * Attach new_disk (fully described by nvroot) to old_disk.
2533  * If 'replacing' is specified, the new disk will replace the old one.
2534  */
2535 int
2536 zpool_vdev_attach(zpool_handle_t *zhp,
2537     const char *old_disk, const char *new_disk, nvlist_t *nvroot, int replacing)
2538 {
2539 	zfs_cmd_t zc = { 0 };
2540 	char msg[1024];
2541 	int ret;
2542 	nvlist_t *tgt;
2543 	boolean_t avail_spare, l2cache, islog;
2544 	uint64_t val;
2545 	char *newname;
2546 	nvlist_t **child;
2547 	uint_t children;
2548 	nvlist_t *config_root;
2549 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2550 	boolean_t rootpool = zpool_is_bootable(zhp);
2551 
2552 	if (replacing)
2553 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2554 		    "cannot replace %s with %s"), old_disk, new_disk);
2555 	else
2556 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2557 		    "cannot attach %s to %s"), new_disk, old_disk);
2558 
2559 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2560 	if ((tgt = zpool_find_vdev(zhp, old_disk, &avail_spare, &l2cache,
2561 	    &islog)) == 0)
2562 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
2563 
2564 	if (avail_spare)
2565 		return (zfs_error(hdl, EZFS_ISSPARE, msg));
2566 
2567 	if (l2cache)
2568 		return (zfs_error(hdl, EZFS_ISL2CACHE, msg));
2569 
2570 	verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2571 	zc.zc_cookie = replacing;
2572 
2573 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
2574 	    &child, &children) != 0 || children != 1) {
2575 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2576 		    "new device must be a single disk"));
2577 		return (zfs_error(hdl, EZFS_INVALCONFIG, msg));
2578 	}
2579 
2580 	verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
2581 	    ZPOOL_CONFIG_VDEV_TREE, &config_root) == 0);
2582 
2583 	if ((newname = zpool_vdev_name(NULL, NULL, child[0], B_FALSE)) == NULL)
2584 		return (-1);
2585 
2586 	/*
2587 	 * If the target is a hot spare that has been swapped in, we can only
2588 	 * replace it with another hot spare.
2589 	 */
2590 	if (replacing &&
2591 	    nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_IS_SPARE, &val) == 0 &&
2592 	    (zpool_find_vdev(zhp, newname, &avail_spare, &l2cache,
2593 	    NULL) == NULL || !avail_spare) &&
2594 	    is_replacing_spare(config_root, tgt, 1)) {
2595 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2596 		    "can only be replaced by another hot spare"));
2597 		free(newname);
2598 		return (zfs_error(hdl, EZFS_BADTARGET, msg));
2599 	}
2600 
2601 	free(newname);
2602 
2603 	if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
2604 		return (-1);
2605 
2606 	ret = zfs_ioctl(hdl, ZFS_IOC_VDEV_ATTACH, &zc);
2607 
2608 	zcmd_free_nvlists(&zc);
2609 
2610 	if (ret == 0) {
2611 		if (rootpool) {
2612 			/*
2613 			 * XXX need a better way to prevent user from
2614 			 * booting up a half-baked vdev.
2615 			 */
2616 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Make "
2617 			    "sure to wait until resilver is done "
2618 			    "before rebooting.\n"));
2619 		}
2620 		return (0);
2621 	}
2622 
2623 	switch (errno) {
2624 	case ENOTSUP:
2625 		/*
2626 		 * Can't attach to or replace this type of vdev.
2627 		 */
2628 		if (replacing) {
2629 			uint64_t version = zpool_get_prop_int(zhp,
2630 			    ZPOOL_PROP_VERSION, NULL);
2631 
2632 			if (islog)
2633 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2634 				    "cannot replace a log with a spare"));
2635 			else if (version >= SPA_VERSION_MULTI_REPLACE)
2636 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2637 				    "already in replacing/spare config; wait "
2638 				    "for completion or use 'zpool detach'"));
2639 			else
2640 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2641 				    "cannot replace a replacing device"));
2642 		} else {
2643 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2644 			    "can only attach to mirrors and top-level "
2645 			    "disks"));
2646 		}
2647 		(void) zfs_error(hdl, EZFS_BADTARGET, msg);
2648 		break;
2649 
2650 	case EINVAL:
2651 		/*
2652 		 * The new device must be a single disk.
2653 		 */
2654 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2655 		    "new device must be a single disk"));
2656 		(void) zfs_error(hdl, EZFS_INVALCONFIG, msg);
2657 		break;
2658 
2659 	case EBUSY:
2660 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "%s is busy"),
2661 		    new_disk);
2662 		(void) zfs_error(hdl, EZFS_BADDEV, msg);
2663 		break;
2664 
2665 	case EOVERFLOW:
2666 		/*
2667 		 * The new device is too small.
2668 		 */
2669 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2670 		    "device is too small"));
2671 		(void) zfs_error(hdl, EZFS_BADDEV, msg);
2672 		break;
2673 
2674 	case EDOM:
2675 		/*
2676 		 * The new device has a different alignment requirement.
2677 		 */
2678 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2679 		    "devices have different sector alignment"));
2680 		(void) zfs_error(hdl, EZFS_BADDEV, msg);
2681 		break;
2682 
2683 	case ENAMETOOLONG:
2684 		/*
2685 		 * The resulting top-level vdev spec won't fit in the label.
2686 		 */
2687 		(void) zfs_error(hdl, EZFS_DEVOVERFLOW, msg);
2688 		break;
2689 
2690 	default:
2691 		(void) zpool_standard_error(hdl, errno, msg);
2692 	}
2693 
2694 	return (-1);
2695 }
2696 
2697 /*
2698  * Detach the specified device.
2699  */
2700 int
2701 zpool_vdev_detach(zpool_handle_t *zhp, const char *path)
2702 {
2703 	zfs_cmd_t zc = { 0 };
2704 	char msg[1024];
2705 	nvlist_t *tgt;
2706 	boolean_t avail_spare, l2cache;
2707 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2708 
2709 	(void) snprintf(msg, sizeof (msg),
2710 	    dgettext(TEXT_DOMAIN, "cannot detach %s"), path);
2711 
2712 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2713 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
2714 	    NULL)) == 0)
2715 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
2716 
2717 	if (avail_spare)
2718 		return (zfs_error(hdl, EZFS_ISSPARE, msg));
2719 
2720 	if (l2cache)
2721 		return (zfs_error(hdl, EZFS_ISL2CACHE, msg));
2722 
2723 	verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2724 
2725 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_DETACH, &zc) == 0)
2726 		return (0);
2727 
2728 	switch (errno) {
2729 
2730 	case ENOTSUP:
2731 		/*
2732 		 * Can't detach from this type of vdev.
2733 		 */
2734 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "only "
2735 		    "applicable to mirror and replacing vdevs"));
2736 		(void) zfs_error(hdl, EZFS_BADTARGET, msg);
2737 		break;
2738 
2739 	case EBUSY:
2740 		/*
2741 		 * There are no other replicas of this device.
2742 		 */
2743 		(void) zfs_error(hdl, EZFS_NOREPLICAS, msg);
2744 		break;
2745 
2746 	default:
2747 		(void) zpool_standard_error(hdl, errno, msg);
2748 	}
2749 
2750 	return (-1);
2751 }
2752 
2753 /*
2754  * Find a mirror vdev in the source nvlist.
2755  *
2756  * The mchild array contains a list of disks in one of the top-level mirrors
2757  * of the source pool.  The schild array contains a list of disks that the
2758  * user specified on the command line.  We loop over the mchild array to
2759  * see if any entry in the schild array matches.
2760  *
2761  * If a disk in the mchild array is found in the schild array, we return
2762  * the index of that entry.  Otherwise we return -1.
2763  */
2764 static int
2765 find_vdev_entry(zpool_handle_t *zhp, nvlist_t **mchild, uint_t mchildren,
2766     nvlist_t **schild, uint_t schildren)
2767 {
2768 	uint_t mc;
2769 
2770 	for (mc = 0; mc < mchildren; mc++) {
2771 		uint_t sc;
2772 		char *mpath = zpool_vdev_name(zhp->zpool_hdl, zhp,
2773 		    mchild[mc], B_FALSE);
2774 
2775 		for (sc = 0; sc < schildren; sc++) {
2776 			char *spath = zpool_vdev_name(zhp->zpool_hdl, zhp,
2777 			    schild[sc], B_FALSE);
2778 			boolean_t result = (strcmp(mpath, spath) == 0);
2779 
2780 			free(spath);
2781 			if (result) {
2782 				free(mpath);
2783 				return (mc);
2784 			}
2785 		}
2786 
2787 		free(mpath);
2788 	}
2789 
2790 	return (-1);
2791 }
2792 
2793 /*
2794  * Split a mirror pool.  If newroot points to null, then a new nvlist
2795  * is generated and it is the responsibility of the caller to free it.
2796  */
2797 int
2798 zpool_vdev_split(zpool_handle_t *zhp, char *newname, nvlist_t **newroot,
2799     nvlist_t *props, splitflags_t flags)
2800 {
2801 	zfs_cmd_t zc = { 0 };
2802 	char msg[1024];
2803 	nvlist_t *tree, *config, **child, **newchild, *newconfig = NULL;
2804 	nvlist_t **varray = NULL, *zc_props = NULL;
2805 	uint_t c, children, newchildren, lastlog = 0, vcount, found = 0;
2806 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2807 	uint64_t vers;
2808 	boolean_t freelist = B_FALSE, memory_err = B_TRUE;
2809 	int retval = 0;
2810 
2811 	(void) snprintf(msg, sizeof (msg),
2812 	    dgettext(TEXT_DOMAIN, "Unable to split %s"), zhp->zpool_name);
2813 
2814 	if (!zpool_name_valid(hdl, B_FALSE, newname))
2815 		return (zfs_error(hdl, EZFS_INVALIDNAME, msg));
2816 
2817 	if ((config = zpool_get_config(zhp, NULL)) == NULL) {
2818 		(void) fprintf(stderr, gettext("Internal error: unable to "
2819 		    "retrieve pool configuration\n"));
2820 		return (-1);
2821 	}
2822 
2823 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &tree)
2824 	    == 0);
2825 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION, &vers) == 0);
2826 
2827 	if (props) {
2828 		prop_flags_t flags = { .create = B_FALSE, .import = B_TRUE };
2829 		if ((zc_props = zpool_valid_proplist(hdl, zhp->zpool_name,
2830 		    props, vers, flags, msg)) == NULL)
2831 			return (-1);
2832 	}
2833 
2834 	if (nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN, &child,
2835 	    &children) != 0) {
2836 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2837 		    "Source pool is missing vdev tree"));
2838 		nvlist_free(zc_props);
2839 		return (-1);
2840 	}
2841 
2842 	varray = zfs_alloc(hdl, children * sizeof (nvlist_t *));
2843 	vcount = 0;
2844 
2845 	if (*newroot == NULL ||
2846 	    nvlist_lookup_nvlist_array(*newroot, ZPOOL_CONFIG_CHILDREN,
2847 	    &newchild, &newchildren) != 0)
2848 		newchildren = 0;
2849 
2850 	for (c = 0; c < children; c++) {
2851 		uint64_t is_log = B_FALSE, is_hole = B_FALSE;
2852 		char *type;
2853 		nvlist_t **mchild, *vdev;
2854 		uint_t mchildren;
2855 		int entry;
2856 
2857 		/*
2858 		 * Unlike cache & spares, slogs are stored in the
2859 		 * ZPOOL_CONFIG_CHILDREN array.  We filter them out here.
2860 		 */
2861 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
2862 		    &is_log);
2863 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
2864 		    &is_hole);
2865 		if (is_log || is_hole) {
2866 			/*
2867 			 * Create a hole vdev and put it in the config.
2868 			 */
2869 			if (nvlist_alloc(&vdev, NV_UNIQUE_NAME, 0) != 0)
2870 				goto out;
2871 			if (nvlist_add_string(vdev, ZPOOL_CONFIG_TYPE,
2872 			    VDEV_TYPE_HOLE) != 0)
2873 				goto out;
2874 			if (nvlist_add_uint64(vdev, ZPOOL_CONFIG_IS_HOLE,
2875 			    1) != 0)
2876 				goto out;
2877 			if (lastlog == 0)
2878 				lastlog = vcount;
2879 			varray[vcount++] = vdev;
2880 			continue;
2881 		}
2882 		lastlog = 0;
2883 		verify(nvlist_lookup_string(child[c], ZPOOL_CONFIG_TYPE, &type)
2884 		    == 0);
2885 		if (strcmp(type, VDEV_TYPE_MIRROR) != 0) {
2886 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2887 			    "Source pool must be composed only of mirrors\n"));
2888 			retval = zfs_error(hdl, EZFS_INVALCONFIG, msg);
2889 			goto out;
2890 		}
2891 
2892 		verify(nvlist_lookup_nvlist_array(child[c],
2893 		    ZPOOL_CONFIG_CHILDREN, &mchild, &mchildren) == 0);
2894 
2895 		/* find or add an entry for this top-level vdev */
2896 		if (newchildren > 0 &&
2897 		    (entry = find_vdev_entry(zhp, mchild, mchildren,
2898 		    newchild, newchildren)) >= 0) {
2899 			/* We found a disk that the user specified. */
2900 			vdev = mchild[entry];
2901 			++found;
2902 		} else {
2903 			/* User didn't specify a disk for this vdev. */
2904 			vdev = mchild[mchildren - 1];
2905 		}
2906 
2907 		if (nvlist_dup(vdev, &varray[vcount++], 0) != 0)
2908 			goto out;
2909 	}
2910 
2911 	/* did we find every disk the user specified? */
2912 	if (found != newchildren) {
2913 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Device list must "
2914 		    "include at most one disk from each mirror"));
2915 		retval = zfs_error(hdl, EZFS_INVALCONFIG, msg);
2916 		goto out;
2917 	}
2918 
2919 	/* Prepare the nvlist for populating. */
2920 	if (*newroot == NULL) {
2921 		if (nvlist_alloc(newroot, NV_UNIQUE_NAME, 0) != 0)
2922 			goto out;
2923 		freelist = B_TRUE;
2924 		if (nvlist_add_string(*newroot, ZPOOL_CONFIG_TYPE,
2925 		    VDEV_TYPE_ROOT) != 0)
2926 			goto out;
2927 	} else {
2928 		verify(nvlist_remove_all(*newroot, ZPOOL_CONFIG_CHILDREN) == 0);
2929 	}
2930 
2931 	/* Add all the children we found */
2932 	if (nvlist_add_nvlist_array(*newroot, ZPOOL_CONFIG_CHILDREN, varray,
2933 	    lastlog == 0 ? vcount : lastlog) != 0)
2934 		goto out;
2935 
2936 	/*
2937 	 * If we're just doing a dry run, exit now with success.
2938 	 */
2939 	if (flags.dryrun) {
2940 		memory_err = B_FALSE;
2941 		freelist = B_FALSE;
2942 		goto out;
2943 	}
2944 
2945 	/* now build up the config list & call the ioctl */
2946 	if (nvlist_alloc(&newconfig, NV_UNIQUE_NAME, 0) != 0)
2947 		goto out;
2948 
2949 	if (nvlist_add_nvlist(newconfig,
2950 	    ZPOOL_CONFIG_VDEV_TREE, *newroot) != 0 ||
2951 	    nvlist_add_string(newconfig,
2952 	    ZPOOL_CONFIG_POOL_NAME, newname) != 0 ||
2953 	    nvlist_add_uint64(newconfig, ZPOOL_CONFIG_VERSION, vers) != 0)
2954 		goto out;
2955 
2956 	/*
2957 	 * The new pool is automatically part of the namespace unless we
2958 	 * explicitly export it.
2959 	 */
2960 	if (!flags.import)
2961 		zc.zc_cookie = ZPOOL_EXPORT_AFTER_SPLIT;
2962 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2963 	(void) strlcpy(zc.zc_string, newname, sizeof (zc.zc_string));
2964 	if (zcmd_write_conf_nvlist(hdl, &zc, newconfig) != 0)
2965 		goto out;
2966 	if (zc_props != NULL && zcmd_write_src_nvlist(hdl, &zc, zc_props) != 0)
2967 		goto out;
2968 
2969 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SPLIT, &zc) != 0) {
2970 		retval = zpool_standard_error(hdl, errno, msg);
2971 		goto out;
2972 	}
2973 
2974 	freelist = B_FALSE;
2975 	memory_err = B_FALSE;
2976 
2977 out:
2978 	if (varray != NULL) {
2979 		int v;
2980 
2981 		for (v = 0; v < vcount; v++)
2982 			nvlist_free(varray[v]);
2983 		free(varray);
2984 	}
2985 	zcmd_free_nvlists(&zc);
2986 	nvlist_free(zc_props);
2987 	nvlist_free(newconfig);
2988 	if (freelist) {
2989 		nvlist_free(*newroot);
2990 		*newroot = NULL;
2991 	}
2992 
2993 	if (retval != 0)
2994 		return (retval);
2995 
2996 	if (memory_err)
2997 		return (no_memory(hdl));
2998 
2999 	return (0);
3000 }
3001 
3002 /*
3003  * Remove the given device.  Currently, this is supported only for hot spares
3004  * and level 2 cache devices.
3005  */
3006 int
3007 zpool_vdev_remove(zpool_handle_t *zhp, const char *path)
3008 {
3009 	zfs_cmd_t zc = { 0 };
3010 	char msg[1024];
3011 	nvlist_t *tgt;
3012 	boolean_t avail_spare, l2cache, islog;
3013 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3014 	uint64_t version;
3015 
3016 	(void) snprintf(msg, sizeof (msg),
3017 	    dgettext(TEXT_DOMAIN, "cannot remove %s"), path);
3018 
3019 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3020 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3021 	    &islog)) == 0)
3022 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
3023 	/*
3024 	 * XXX - this should just go away.
3025 	 */
3026 	if (!avail_spare && !l2cache && !islog) {
3027 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3028 		    "only inactive hot spares, cache, top-level, "
3029 		    "or log devices can be removed"));
3030 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
3031 	}
3032 
3033 	version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
3034 	if (islog && version < SPA_VERSION_HOLES) {
3035 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3036 		    "pool must be upgrade to support log removal"));
3037 		return (zfs_error(hdl, EZFS_BADVERSION, msg));
3038 	}
3039 
3040 	verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
3041 
3042 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_REMOVE, &zc) == 0)
3043 		return (0);
3044 
3045 	return (zpool_standard_error(hdl, errno, msg));
3046 }
3047 
3048 /*
3049  * Clear the errors for the pool, or the particular device if specified.
3050  */
3051 int
3052 zpool_clear(zpool_handle_t *zhp, const char *path, nvlist_t *rewindnvl)
3053 {
3054 	zfs_cmd_t zc = { 0 };
3055 	char msg[1024];
3056 	nvlist_t *tgt;
3057 	zpool_rewind_policy_t policy;
3058 	boolean_t avail_spare, l2cache;
3059 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3060 	nvlist_t *nvi = NULL;
3061 	int error;
3062 
3063 	if (path)
3064 		(void) snprintf(msg, sizeof (msg),
3065 		    dgettext(TEXT_DOMAIN, "cannot clear errors for %s"),
3066 		    path);
3067 	else
3068 		(void) snprintf(msg, sizeof (msg),
3069 		    dgettext(TEXT_DOMAIN, "cannot clear errors for %s"),
3070 		    zhp->zpool_name);
3071 
3072 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3073 	if (path) {
3074 		if ((tgt = zpool_find_vdev(zhp, path, &avail_spare,
3075 		    &l2cache, NULL)) == 0)
3076 			return (zfs_error(hdl, EZFS_NODEVICE, msg));
3077 
3078 		/*
3079 		 * Don't allow error clearing for hot spares.  Do allow
3080 		 * error clearing for l2cache devices.
3081 		 */
3082 		if (avail_spare)
3083 			return (zfs_error(hdl, EZFS_ISSPARE, msg));
3084 
3085 		verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID,
3086 		    &zc.zc_guid) == 0);
3087 	}
3088 
3089 	zpool_get_rewind_policy(rewindnvl, &policy);
3090 	zc.zc_cookie = policy.zrp_request;
3091 
3092 	if (zcmd_alloc_dst_nvlist(hdl, &zc, zhp->zpool_config_size * 2) != 0)
3093 		return (-1);
3094 
3095 	if (zcmd_write_src_nvlist(hdl, &zc, rewindnvl) != 0)
3096 		return (-1);
3097 
3098 	while ((error = zfs_ioctl(hdl, ZFS_IOC_CLEAR, &zc)) != 0 &&
3099 	    errno == ENOMEM) {
3100 		if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
3101 			zcmd_free_nvlists(&zc);
3102 			return (-1);
3103 		}
3104 	}
3105 
3106 	if (!error || ((policy.zrp_request & ZPOOL_TRY_REWIND) &&
3107 	    errno != EPERM && errno != EACCES)) {
3108 		if (policy.zrp_request &
3109 		    (ZPOOL_DO_REWIND | ZPOOL_TRY_REWIND)) {
3110 			(void) zcmd_read_dst_nvlist(hdl, &zc, &nvi);
3111 			zpool_rewind_exclaim(hdl, zc.zc_name,
3112 			    ((policy.zrp_request & ZPOOL_TRY_REWIND) != 0),
3113 			    nvi);
3114 			nvlist_free(nvi);
3115 		}
3116 		zcmd_free_nvlists(&zc);
3117 		return (0);
3118 	}
3119 
3120 	zcmd_free_nvlists(&zc);
3121 	return (zpool_standard_error(hdl, errno, msg));
3122 }
3123 
3124 /*
3125  * Similar to zpool_clear(), but takes a GUID (used by fmd).
3126  */
3127 int
3128 zpool_vdev_clear(zpool_handle_t *zhp, uint64_t guid)
3129 {
3130 	zfs_cmd_t zc = { 0 };
3131 	char msg[1024];
3132 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3133 
3134 	(void) snprintf(msg, sizeof (msg),
3135 	    dgettext(TEXT_DOMAIN, "cannot clear errors for %llx"),
3136 	    guid);
3137 
3138 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3139 	zc.zc_guid = guid;
3140 	zc.zc_cookie = ZPOOL_NO_REWIND;
3141 
3142 	if (ioctl(hdl->libzfs_fd, ZFS_IOC_CLEAR, &zc) == 0)
3143 		return (0);
3144 
3145 	return (zpool_standard_error(hdl, errno, msg));
3146 }
3147 
3148 /*
3149  * Change the GUID for a pool.
3150  */
3151 int
3152 zpool_reguid(zpool_handle_t *zhp)
3153 {
3154 	char msg[1024];
3155 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3156 	zfs_cmd_t zc = { 0 };
3157 
3158 	(void) snprintf(msg, sizeof (msg),
3159 	    dgettext(TEXT_DOMAIN, "cannot reguid '%s'"), zhp->zpool_name);
3160 
3161 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3162 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_REGUID, &zc) == 0)
3163 		return (0);
3164 
3165 	return (zpool_standard_error(hdl, errno, msg));
3166 }
3167 
3168 /*
3169  * Reopen the pool.
3170  */
3171 int
3172 zpool_reopen(zpool_handle_t *zhp)
3173 {
3174 	zfs_cmd_t zc = { 0 };
3175 	char msg[1024];
3176 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3177 
3178 	(void) snprintf(msg, sizeof (msg),
3179 	    dgettext(TEXT_DOMAIN, "cannot reopen '%s'"),
3180 	    zhp->zpool_name);
3181 
3182 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3183 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_REOPEN, &zc) == 0)
3184 		return (0);
3185 	return (zpool_standard_error(hdl, errno, msg));
3186 }
3187 
3188 /*
3189  * Convert from a devid string to a path.
3190  */
3191 static char *
3192 devid_to_path(char *devid_str)
3193 {
3194 	ddi_devid_t devid;
3195 	char *minor;
3196 	char *path;
3197 	devid_nmlist_t *list = NULL;
3198 	int ret;
3199 
3200 	if (devid_str_decode(devid_str, &devid, &minor) != 0)
3201 		return (NULL);
3202 
3203 	ret = devid_deviceid_to_nmlist("/dev", devid, minor, &list);
3204 
3205 	devid_str_free(minor);
3206 	devid_free(devid);
3207 
3208 	if (ret != 0)
3209 		return (NULL);
3210 
3211 	/*
3212 	 * In a case the strdup() fails, we will just return NULL below.
3213 	 */
3214 	path = strdup(list[0].devname);
3215 
3216 	devid_free_nmlist(list);
3217 
3218 	return (path);
3219 }
3220 
3221 /*
3222  * Convert from a path to a devid string.
3223  */
3224 static char *
3225 path_to_devid(const char *path)
3226 {
3227 	int fd;
3228 	ddi_devid_t devid;
3229 	char *minor, *ret;
3230 
3231 	if ((fd = open(path, O_RDONLY)) < 0)
3232 		return (NULL);
3233 
3234 	minor = NULL;
3235 	ret = NULL;
3236 	if (devid_get(fd, &devid) == 0) {
3237 		if (devid_get_minor_name(fd, &minor) == 0)
3238 			ret = devid_str_encode(devid, minor);
3239 		if (minor != NULL)
3240 			devid_str_free(minor);
3241 		devid_free(devid);
3242 	}
3243 	(void) close(fd);
3244 
3245 	return (ret);
3246 }
3247 
3248 /*
3249  * Issue the necessary ioctl() to update the stored path value for the vdev.  We
3250  * ignore any failure here, since a common case is for an unprivileged user to
3251  * type 'zpool status', and we'll display the correct information anyway.
3252  */
3253 static void
3254 set_path(zpool_handle_t *zhp, nvlist_t *nv, const char *path)
3255 {
3256 	zfs_cmd_t zc = { 0 };
3257 
3258 	(void) strncpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3259 	(void) strncpy(zc.zc_value, path, sizeof (zc.zc_value));
3260 	verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
3261 	    &zc.zc_guid) == 0);
3262 
3263 	(void) ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_VDEV_SETPATH, &zc);
3264 }
3265 
3266 /*
3267  * Given a vdev, return the name to display in iostat.  If the vdev has a path,
3268  * we use that, stripping off any leading "/dev/dsk/"; if not, we use the type.
3269  * We also check if this is a whole disk, in which case we strip off the
3270  * trailing 's0' slice name.
3271  *
3272  * This routine is also responsible for identifying when disks have been
3273  * reconfigured in a new location.  The kernel will have opened the device by
3274  * devid, but the path will still refer to the old location.  To catch this, we
3275  * first do a path -> devid translation (which is fast for the common case).  If
3276  * the devid matches, we're done.  If not, we do a reverse devid -> path
3277  * translation and issue the appropriate ioctl() to update the path of the vdev.
3278  * If 'zhp' is NULL, then this is an exported pool, and we don't need to do any
3279  * of these checks.
3280  */
3281 char *
3282 zpool_vdev_name(libzfs_handle_t *hdl, zpool_handle_t *zhp, nvlist_t *nv,
3283     boolean_t verbose)
3284 {
3285 	char *path, *devid;
3286 	uint64_t value;
3287 	char buf[64];
3288 	vdev_stat_t *vs;
3289 	uint_t vsc;
3290 
3291 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
3292 	    &value) == 0) {
3293 		verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
3294 		    &value) == 0);
3295 		(void) snprintf(buf, sizeof (buf), "%llu",
3296 		    (u_longlong_t)value);
3297 		path = buf;
3298 	} else if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
3299 
3300 		/*
3301 		 * If the device is dead (faulted, offline, etc) then don't
3302 		 * bother opening it.  Otherwise we may be forcing the user to
3303 		 * open a misbehaving device, which can have undesirable
3304 		 * effects.
3305 		 */
3306 		if ((nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
3307 		    (uint64_t **)&vs, &vsc) != 0 ||
3308 		    vs->vs_state >= VDEV_STATE_DEGRADED) &&
3309 		    zhp != NULL &&
3310 		    nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &devid) == 0) {
3311 			/*
3312 			 * Determine if the current path is correct.
3313 			 */
3314 			char *newdevid = path_to_devid(path);
3315 
3316 			if (newdevid == NULL ||
3317 			    strcmp(devid, newdevid) != 0) {
3318 				char *newpath;
3319 
3320 				if ((newpath = devid_to_path(devid)) != NULL) {
3321 					/*
3322 					 * Update the path appropriately.
3323 					 */
3324 					set_path(zhp, nv, newpath);
3325 					if (nvlist_add_string(nv,
3326 					    ZPOOL_CONFIG_PATH, newpath) == 0)
3327 						verify(nvlist_lookup_string(nv,
3328 						    ZPOOL_CONFIG_PATH,
3329 						    &path) == 0);
3330 					free(newpath);
3331 				}
3332 			}
3333 
3334 			if (newdevid)
3335 				devid_str_free(newdevid);
3336 		}
3337 
3338 		if (strncmp(path, "/dev/dsk/", 9) == 0)
3339 			path += 9;
3340 
3341 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
3342 		    &value) == 0 && value) {
3343 			int pathlen = strlen(path);
3344 			char *tmp = zfs_strdup(hdl, path);
3345 
3346 			/*
3347 			 * If it starts with c#, and ends with "s0", chop
3348 			 * the "s0" off, or if it ends with "s0/old", remove
3349 			 * the "s0" from the middle.
3350 			 */
3351 			if (CTD_CHECK(tmp)) {
3352 				if (strcmp(&tmp[pathlen - 2], "s0") == 0) {
3353 					tmp[pathlen - 2] = '\0';
3354 				} else if (pathlen > 6 &&
3355 				    strcmp(&tmp[pathlen - 6], "s0/old") == 0) {
3356 					(void) strcpy(&tmp[pathlen - 6],
3357 					    "/old");
3358 				}
3359 			}
3360 			return (tmp);
3361 		}
3362 	} else {
3363 		verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &path) == 0);
3364 
3365 		/*
3366 		 * If it's a raidz device, we need to stick in the parity level.
3367 		 */
3368 		if (strcmp(path, VDEV_TYPE_RAIDZ) == 0) {
3369 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
3370 			    &value) == 0);
3371 			(void) snprintf(buf, sizeof (buf), "%s%llu", path,
3372 			    (u_longlong_t)value);
3373 			path = buf;
3374 		}
3375 
3376 		/*
3377 		 * We identify each top-level vdev by using a <type-id>
3378 		 * naming convention.
3379 		 */
3380 		if (verbose) {
3381 			uint64_t id;
3382 
3383 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID,
3384 			    &id) == 0);
3385 			(void) snprintf(buf, sizeof (buf), "%s-%llu", path,
3386 			    (u_longlong_t)id);
3387 			path = buf;
3388 		}
3389 	}
3390 
3391 	return (zfs_strdup(hdl, path));
3392 }
3393 
3394 static int
3395 zbookmark_mem_compare(const void *a, const void *b)
3396 {
3397 	return (memcmp(a, b, sizeof (zbookmark_phys_t)));
3398 }
3399 
3400 /*
3401  * Retrieve the persistent error log, uniquify the members, and return to the
3402  * caller.
3403  */
3404 int
3405 zpool_get_errlog(zpool_handle_t *zhp, nvlist_t **nverrlistp)
3406 {
3407 	zfs_cmd_t zc = { 0 };
3408 	uint64_t count;
3409 	zbookmark_phys_t *zb = NULL;
3410 	int i;
3411 
3412 	/*
3413 	 * Retrieve the raw error list from the kernel.  If the number of errors
3414 	 * has increased, allocate more space and continue until we get the
3415 	 * entire list.
3416 	 */
3417 	verify(nvlist_lookup_uint64(zhp->zpool_config, ZPOOL_CONFIG_ERRCOUNT,
3418 	    &count) == 0);
3419 	if (count == 0)
3420 		return (0);
3421 	if ((zc.zc_nvlist_dst = (uintptr_t)zfs_alloc(zhp->zpool_hdl,
3422 	    count * sizeof (zbookmark_phys_t))) == (uintptr_t)NULL)
3423 		return (-1);
3424 	zc.zc_nvlist_dst_size = count;
3425 	(void) strcpy(zc.zc_name, zhp->zpool_name);
3426 	for (;;) {
3427 		if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_ERROR_LOG,
3428 		    &zc) != 0) {
3429 			free((void *)(uintptr_t)zc.zc_nvlist_dst);
3430 			if (errno == ENOMEM) {
3431 				void *dst;
3432 
3433 				count = zc.zc_nvlist_dst_size;
3434 				dst = zfs_alloc(zhp->zpool_hdl, count *
3435 				    sizeof (zbookmark_phys_t));
3436 				if (dst == NULL)
3437 					return (-1);
3438 				zc.zc_nvlist_dst = (uintptr_t)dst;
3439 			} else {
3440 				return (-1);
3441 			}
3442 		} else {
3443 			break;
3444 		}
3445 	}
3446 
3447 	/*
3448 	 * Sort the resulting bookmarks.  This is a little confusing due to the
3449 	 * implementation of ZFS_IOC_ERROR_LOG.  The bookmarks are copied last
3450 	 * to first, and 'zc_nvlist_dst_size' indicates the number of boomarks
3451 	 * _not_ copied as part of the process.  So we point the start of our
3452 	 * array appropriate and decrement the total number of elements.
3453 	 */
3454 	zb = ((zbookmark_phys_t *)(uintptr_t)zc.zc_nvlist_dst) +
3455 	    zc.zc_nvlist_dst_size;
3456 	count -= zc.zc_nvlist_dst_size;
3457 
3458 	qsort(zb, count, sizeof (zbookmark_phys_t), zbookmark_mem_compare);
3459 
3460 	verify(nvlist_alloc(nverrlistp, 0, KM_SLEEP) == 0);
3461 
3462 	/*
3463 	 * Fill in the nverrlistp with nvlist's of dataset and object numbers.
3464 	 */
3465 	for (i = 0; i < count; i++) {
3466 		nvlist_t *nv;
3467 
3468 		/* ignoring zb_blkid and zb_level for now */
3469 		if (i > 0 && zb[i-1].zb_objset == zb[i].zb_objset &&
3470 		    zb[i-1].zb_object == zb[i].zb_object)
3471 			continue;
3472 
3473 		if (nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) != 0)
3474 			goto nomem;
3475 		if (nvlist_add_uint64(nv, ZPOOL_ERR_DATASET,
3476 		    zb[i].zb_objset) != 0) {
3477 			nvlist_free(nv);
3478 			goto nomem;
3479 		}
3480 		if (nvlist_add_uint64(nv, ZPOOL_ERR_OBJECT,
3481 		    zb[i].zb_object) != 0) {
3482 			nvlist_free(nv);
3483 			goto nomem;
3484 		}
3485 		if (nvlist_add_nvlist(*nverrlistp, "ejk", nv) != 0) {
3486 			nvlist_free(nv);
3487 			goto nomem;
3488 		}
3489 		nvlist_free(nv);
3490 	}
3491 
3492 	free((void *)(uintptr_t)zc.zc_nvlist_dst);
3493 	return (0);
3494 
3495 nomem:
3496 	free((void *)(uintptr_t)zc.zc_nvlist_dst);
3497 	return (no_memory(zhp->zpool_hdl));
3498 }
3499 
3500 /*
3501  * Upgrade a ZFS pool to the latest on-disk version.
3502  */
3503 int
3504 zpool_upgrade(zpool_handle_t *zhp, uint64_t new_version)
3505 {
3506 	zfs_cmd_t zc = { 0 };
3507 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3508 
3509 	(void) strcpy(zc.zc_name, zhp->zpool_name);
3510 	zc.zc_cookie = new_version;
3511 
3512 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_UPGRADE, &zc) != 0)
3513 		return (zpool_standard_error_fmt(hdl, errno,
3514 		    dgettext(TEXT_DOMAIN, "cannot upgrade '%s'"),
3515 		    zhp->zpool_name));
3516 	return (0);
3517 }
3518 
3519 void
3520 zfs_save_arguments(int argc, char **argv, char *string, int len)
3521 {
3522 	(void) strlcpy(string, basename(argv[0]), len);
3523 	for (int i = 1; i < argc; i++) {
3524 		(void) strlcat(string, " ", len);
3525 		(void) strlcat(string, argv[i], len);
3526 	}
3527 }
3528 
3529 int
3530 zpool_log_history(libzfs_handle_t *hdl, const char *message)
3531 {
3532 	zfs_cmd_t zc = { 0 };
3533 	nvlist_t *args;
3534 	int err;
3535 
3536 	args = fnvlist_alloc();
3537 	fnvlist_add_string(args, "message", message);
3538 	err = zcmd_write_src_nvlist(hdl, &zc, args);
3539 	if (err == 0)
3540 		err = ioctl(hdl->libzfs_fd, ZFS_IOC_LOG_HISTORY, &zc);
3541 	nvlist_free(args);
3542 	zcmd_free_nvlists(&zc);
3543 	return (err);
3544 }
3545 
3546 /*
3547  * Perform ioctl to get some command history of a pool.
3548  *
3549  * 'buf' is the buffer to fill up to 'len' bytes.  'off' is the
3550  * logical offset of the history buffer to start reading from.
3551  *
3552  * Upon return, 'off' is the next logical offset to read from and
3553  * 'len' is the actual amount of bytes read into 'buf'.
3554  */
3555 static int
3556 get_history(zpool_handle_t *zhp, char *buf, uint64_t *off, uint64_t *len)
3557 {
3558 	zfs_cmd_t zc = { 0 };
3559 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3560 
3561 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3562 
3563 	zc.zc_history = (uint64_t)(uintptr_t)buf;
3564 	zc.zc_history_len = *len;
3565 	zc.zc_history_offset = *off;
3566 
3567 	if (ioctl(hdl->libzfs_fd, ZFS_IOC_POOL_GET_HISTORY, &zc) != 0) {
3568 		switch (errno) {
3569 		case EPERM:
3570 			return (zfs_error_fmt(hdl, EZFS_PERM,
3571 			    dgettext(TEXT_DOMAIN,
3572 			    "cannot show history for pool '%s'"),
3573 			    zhp->zpool_name));
3574 		case ENOENT:
3575 			return (zfs_error_fmt(hdl, EZFS_NOHISTORY,
3576 			    dgettext(TEXT_DOMAIN, "cannot get history for pool "
3577 			    "'%s'"), zhp->zpool_name));
3578 		case ENOTSUP:
3579 			return (zfs_error_fmt(hdl, EZFS_BADVERSION,
3580 			    dgettext(TEXT_DOMAIN, "cannot get history for pool "
3581 			    "'%s', pool must be upgraded"), zhp->zpool_name));
3582 		default:
3583 			return (zpool_standard_error_fmt(hdl, errno,
3584 			    dgettext(TEXT_DOMAIN,
3585 			    "cannot get history for '%s'"), zhp->zpool_name));
3586 		}
3587 	}
3588 
3589 	*len = zc.zc_history_len;
3590 	*off = zc.zc_history_offset;
3591 
3592 	return (0);
3593 }
3594 
3595 /*
3596  * Process the buffer of nvlists, unpacking and storing each nvlist record
3597  * into 'records'.  'leftover' is set to the number of bytes that weren't
3598  * processed as there wasn't a complete record.
3599  */
3600 int
3601 zpool_history_unpack(char *buf, uint64_t bytes_read, uint64_t *leftover,
3602     nvlist_t ***records, uint_t *numrecords)
3603 {
3604 	uint64_t reclen;
3605 	nvlist_t *nv;
3606 	int i;
3607 
3608 	while (bytes_read > sizeof (reclen)) {
3609 
3610 		/* get length of packed record (stored as little endian) */
3611 		for (i = 0, reclen = 0; i < sizeof (reclen); i++)
3612 			reclen += (uint64_t)(((uchar_t *)buf)[i]) << (8*i);
3613 
3614 		if (bytes_read < sizeof (reclen) + reclen)
3615 			break;
3616 
3617 		/* unpack record */
3618 		if (nvlist_unpack(buf + sizeof (reclen), reclen, &nv, 0) != 0)
3619 			return (ENOMEM);
3620 		bytes_read -= sizeof (reclen) + reclen;
3621 		buf += sizeof (reclen) + reclen;
3622 
3623 		/* add record to nvlist array */
3624 		(*numrecords)++;
3625 		if (ISP2(*numrecords + 1)) {
3626 			*records = realloc(*records,
3627 			    *numrecords * 2 * sizeof (nvlist_t *));
3628 		}
3629 		(*records)[*numrecords - 1] = nv;
3630 	}
3631 
3632 	*leftover = bytes_read;
3633 	return (0);
3634 }
3635 
3636 /*
3637  * Retrieve the command history of a pool.
3638  */
3639 int
3640 zpool_get_history(zpool_handle_t *zhp, nvlist_t **nvhisp)
3641 {
3642 	char *buf;
3643 	int buflen = 128 * 1024;
3644 	uint64_t off = 0;
3645 	nvlist_t **records = NULL;
3646 	uint_t numrecords = 0;
3647 	int err, i;
3648 
3649 	buf = malloc(buflen);
3650 	if (buf == NULL)
3651 		return (ENOMEM);
3652 	do {
3653 		uint64_t bytes_read = buflen;
3654 		uint64_t leftover;
3655 
3656 		if ((err = get_history(zhp, buf, &off, &bytes_read)) != 0)
3657 			break;
3658 
3659 		/* if nothing else was read in, we're at EOF, just return */
3660 		if (!bytes_read)
3661 			break;
3662 
3663 		if ((err = zpool_history_unpack(buf, bytes_read,
3664 		    &leftover, &records, &numrecords)) != 0)
3665 			break;
3666 		off -= leftover;
3667 		if (leftover == bytes_read) {
3668 			/*
3669 			 * no progress made, because buffer is not big enough
3670 			 * to hold this record; resize and retry.
3671 			 */
3672 			buflen *= 2;
3673 			free(buf);
3674 			buf = malloc(buflen);
3675 			if (buf == NULL)
3676 				return (ENOMEM);
3677 		}
3678 
3679 		/* CONSTCOND */
3680 	} while (1);
3681 
3682 	free(buf);
3683 
3684 	if (!err) {
3685 		verify(nvlist_alloc(nvhisp, NV_UNIQUE_NAME, 0) == 0);
3686 		verify(nvlist_add_nvlist_array(*nvhisp, ZPOOL_HIST_RECORD,
3687 		    records, numrecords) == 0);
3688 	}
3689 	for (i = 0; i < numrecords; i++)
3690 		nvlist_free(records[i]);
3691 	free(records);
3692 
3693 	return (err);
3694 }
3695 
3696 void
3697 zpool_obj_to_path(zpool_handle_t *zhp, uint64_t dsobj, uint64_t obj,
3698     char *pathname, size_t len)
3699 {
3700 	zfs_cmd_t zc = { 0 };
3701 	boolean_t mounted = B_FALSE;
3702 	char *mntpnt = NULL;
3703 	char dsname[ZFS_MAX_DATASET_NAME_LEN];
3704 
3705 	if (dsobj == 0) {
3706 		/* special case for the MOS */
3707 		(void) snprintf(pathname, len, "<metadata>:<0x%llx>", obj);
3708 		return;
3709 	}
3710 
3711 	/* get the dataset's name */
3712 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3713 	zc.zc_obj = dsobj;
3714 	if (ioctl(zhp->zpool_hdl->libzfs_fd,
3715 	    ZFS_IOC_DSOBJ_TO_DSNAME, &zc) != 0) {
3716 		/* just write out a path of two object numbers */
3717 		(void) snprintf(pathname, len, "<0x%llx>:<0x%llx>",
3718 		    dsobj, obj);
3719 		return;
3720 	}
3721 	(void) strlcpy(dsname, zc.zc_value, sizeof (dsname));
3722 
3723 	/* find out if the dataset is mounted */
3724 	mounted = is_mounted(zhp->zpool_hdl, dsname, &mntpnt);
3725 
3726 	/* get the corrupted object's path */
3727 	(void) strlcpy(zc.zc_name, dsname, sizeof (zc.zc_name));
3728 	zc.zc_obj = obj;
3729 	if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_OBJ_TO_PATH,
3730 	    &zc) == 0) {
3731 		if (mounted) {
3732 			(void) snprintf(pathname, len, "%s%s", mntpnt,
3733 			    zc.zc_value);
3734 		} else {
3735 			(void) snprintf(pathname, len, "%s:%s",
3736 			    dsname, zc.zc_value);
3737 		}
3738 	} else {
3739 		(void) snprintf(pathname, len, "%s:<0x%llx>", dsname, obj);
3740 	}
3741 	free(mntpnt);
3742 }
3743 
3744 /*
3745  * Read the EFI label from the config, if a label does not exist then
3746  * pass back the error to the caller. If the caller has passed a non-NULL
3747  * diskaddr argument then we set it to the starting address of the EFI
3748  * partition.
3749  */
3750 static int
3751 read_efi_label(nvlist_t *config, diskaddr_t *sb)
3752 {
3753 	char *path;
3754 	int fd;
3755 	char diskname[MAXPATHLEN];
3756 	int err = -1;
3757 
3758 	if (nvlist_lookup_string(config, ZPOOL_CONFIG_PATH, &path) != 0)
3759 		return (err);
3760 
3761 	(void) snprintf(diskname, sizeof (diskname), "%s%s", RDISK_ROOT,
3762 	    strrchr(path, '/'));
3763 	if ((fd = open(diskname, O_RDONLY|O_NDELAY)) >= 0) {
3764 		struct dk_gpt *vtoc;
3765 
3766 		if ((err = efi_alloc_and_read(fd, &vtoc)) >= 0) {
3767 			if (sb != NULL)
3768 				*sb = vtoc->efi_parts[0].p_start;
3769 			efi_free(vtoc);
3770 		}
3771 		(void) close(fd);
3772 	}
3773 	return (err);
3774 }
3775 
3776 /*
3777  * determine where a partition starts on a disk in the current
3778  * configuration
3779  */
3780 static diskaddr_t
3781 find_start_block(nvlist_t *config)
3782 {
3783 	nvlist_t **child;
3784 	uint_t c, children;
3785 	diskaddr_t sb = MAXOFFSET_T;
3786 	uint64_t wholedisk;
3787 
3788 	if (nvlist_lookup_nvlist_array(config,
3789 	    ZPOOL_CONFIG_CHILDREN, &child, &children) != 0) {
3790 		if (nvlist_lookup_uint64(config,
3791 		    ZPOOL_CONFIG_WHOLE_DISK,
3792 		    &wholedisk) != 0 || !wholedisk) {
3793 			return (MAXOFFSET_T);
3794 		}
3795 		if (read_efi_label(config, &sb) < 0)
3796 			sb = MAXOFFSET_T;
3797 		return (sb);
3798 	}
3799 
3800 	for (c = 0; c < children; c++) {
3801 		sb = find_start_block(child[c]);
3802 		if (sb != MAXOFFSET_T) {
3803 			return (sb);
3804 		}
3805 	}
3806 	return (MAXOFFSET_T);
3807 }
3808 
3809 /*
3810  * Label an individual disk.  The name provided is the short name,
3811  * stripped of any leading /dev path.
3812  */
3813 int
3814 zpool_label_disk(libzfs_handle_t *hdl, zpool_handle_t *zhp, char *name)
3815 {
3816 	char path[MAXPATHLEN];
3817 	struct dk_gpt *vtoc;
3818 	int fd;
3819 	size_t resv = EFI_MIN_RESV_SIZE;
3820 	uint64_t slice_size;
3821 	diskaddr_t start_block;
3822 	char errbuf[1024];
3823 
3824 	/* prepare an error message just in case */
3825 	(void) snprintf(errbuf, sizeof (errbuf),
3826 	    dgettext(TEXT_DOMAIN, "cannot label '%s'"), name);
3827 
3828 	if (zhp) {
3829 		nvlist_t *nvroot;
3830 
3831 		verify(nvlist_lookup_nvlist(zhp->zpool_config,
3832 		    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
3833 
3834 		if (zhp->zpool_start_block == 0)
3835 			start_block = find_start_block(nvroot);
3836 		else
3837 			start_block = zhp->zpool_start_block;
3838 		zhp->zpool_start_block = start_block;
3839 	} else {
3840 		/* new pool */
3841 		start_block = NEW_START_BLOCK;
3842 	}
3843 
3844 	(void) snprintf(path, sizeof (path), "%s/%s%s", RDISK_ROOT, name,
3845 	    BACKUP_SLICE);
3846 
3847 	if ((fd = open(path, O_RDWR | O_NDELAY)) < 0) {
3848 		/*
3849 		 * This shouldn't happen.  We've long since verified that this
3850 		 * is a valid device.
3851 		 */
3852 		zfs_error_aux(hdl,
3853 		    dgettext(TEXT_DOMAIN, "unable to open device"));
3854 		return (zfs_error(hdl, EZFS_OPENFAILED, errbuf));
3855 	}
3856 
3857 	if (efi_alloc_and_init(fd, EFI_NUMPAR, &vtoc) != 0) {
3858 		/*
3859 		 * The only way this can fail is if we run out of memory, or we
3860 		 * were unable to read the disk's capacity
3861 		 */
3862 		if (errno == ENOMEM)
3863 			(void) no_memory(hdl);
3864 
3865 		(void) close(fd);
3866 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3867 		    "unable to read disk capacity"), name);
3868 
3869 		return (zfs_error(hdl, EZFS_NOCAP, errbuf));
3870 	}
3871 
3872 	slice_size = vtoc->efi_last_u_lba + 1;
3873 	slice_size -= EFI_MIN_RESV_SIZE;
3874 	if (start_block == MAXOFFSET_T)
3875 		start_block = NEW_START_BLOCK;
3876 	slice_size -= start_block;
3877 
3878 	vtoc->efi_parts[0].p_start = start_block;
3879 	vtoc->efi_parts[0].p_size = slice_size;
3880 
3881 	/*
3882 	 * Why we use V_USR: V_BACKUP confuses users, and is considered
3883 	 * disposable by some EFI utilities (since EFI doesn't have a backup
3884 	 * slice).  V_UNASSIGNED is supposed to be used only for zero size
3885 	 * partitions, and efi_write() will fail if we use it.  V_ROOT, V_BOOT,
3886 	 * etc. were all pretty specific.  V_USR is as close to reality as we
3887 	 * can get, in the absence of V_OTHER.
3888 	 */
3889 	vtoc->efi_parts[0].p_tag = V_USR;
3890 	(void) strcpy(vtoc->efi_parts[0].p_name, "zfs");
3891 
3892 	vtoc->efi_parts[8].p_start = slice_size + start_block;
3893 	vtoc->efi_parts[8].p_size = resv;
3894 	vtoc->efi_parts[8].p_tag = V_RESERVED;
3895 
3896 	if (efi_write(fd, vtoc) != 0) {
3897 		/*
3898 		 * Some block drivers (like pcata) may not support EFI
3899 		 * GPT labels.  Print out a helpful error message dir-
3900 		 * ecting the user to manually label the disk and give
3901 		 * a specific slice.
3902 		 */
3903 		(void) close(fd);
3904 		efi_free(vtoc);
3905 
3906 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3907 		    "try using fdisk(1M) and then provide a specific slice"));
3908 		return (zfs_error(hdl, EZFS_LABELFAILED, errbuf));
3909 	}
3910 
3911 	(void) close(fd);
3912 	efi_free(vtoc);
3913 	return (0);
3914 }
3915 
3916 static boolean_t
3917 supported_dump_vdev_type(libzfs_handle_t *hdl, nvlist_t *config, char *errbuf)
3918 {
3919 	char *type;
3920 	nvlist_t **child;
3921 	uint_t children, c;
3922 
3923 	verify(nvlist_lookup_string(config, ZPOOL_CONFIG_TYPE, &type) == 0);
3924 	if (strcmp(type, VDEV_TYPE_FILE) == 0 ||
3925 	    strcmp(type, VDEV_TYPE_HOLE) == 0 ||
3926 	    strcmp(type, VDEV_TYPE_MISSING) == 0) {
3927 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3928 		    "vdev type '%s' is not supported"), type);
3929 		(void) zfs_error(hdl, EZFS_VDEVNOTSUP, errbuf);
3930 		return (B_FALSE);
3931 	}
3932 	if (nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_CHILDREN,
3933 	    &child, &children) == 0) {
3934 		for (c = 0; c < children; c++) {
3935 			if (!supported_dump_vdev_type(hdl, child[c], errbuf))
3936 				return (B_FALSE);
3937 		}
3938 	}
3939 	return (B_TRUE);
3940 }
3941 
3942 /*
3943  * Check if this zvol is allowable for use as a dump device; zero if
3944  * it is, > 0 if it isn't, < 0 if it isn't a zvol.
3945  *
3946  * Allowable storage configurations include mirrors, all raidz variants, and
3947  * pools with log, cache, and spare devices.  Pools which are backed by files or
3948  * have missing/hole vdevs are not suitable.
3949  */
3950 int
3951 zvol_check_dump_config(char *arg)
3952 {
3953 	zpool_handle_t *zhp = NULL;
3954 	nvlist_t *config, *nvroot;
3955 	char *p, *volname;
3956 	nvlist_t **top;
3957 	uint_t toplevels;
3958 	libzfs_handle_t *hdl;
3959 	char errbuf[1024];
3960 	char poolname[ZFS_MAX_DATASET_NAME_LEN];
3961 	int pathlen = strlen(ZVOL_FULL_DEV_DIR);
3962 	int ret = 1;
3963 
3964 	if (strncmp(arg, ZVOL_FULL_DEV_DIR, pathlen)) {
3965 		return (-1);
3966 	}
3967 
3968 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3969 	    "dump is not supported on device '%s'"), arg);
3970 
3971 	if ((hdl = libzfs_init()) == NULL)
3972 		return (1);
3973 	libzfs_print_on_error(hdl, B_TRUE);
3974 
3975 	volname = arg + pathlen;
3976 
3977 	/* check the configuration of the pool */
3978 	if ((p = strchr(volname, '/')) == NULL) {
3979 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3980 		    "malformed dataset name"));
3981 		(void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
3982 		return (1);
3983 	} else if (p - volname >= ZFS_MAX_DATASET_NAME_LEN) {
3984 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3985 		    "dataset name is too long"));
3986 		(void) zfs_error(hdl, EZFS_NAMETOOLONG, errbuf);
3987 		return (1);
3988 	} else {
3989 		(void) strncpy(poolname, volname, p - volname);
3990 		poolname[p - volname] = '\0';
3991 	}
3992 
3993 	if ((zhp = zpool_open(hdl, poolname)) == NULL) {
3994 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3995 		    "could not open pool '%s'"), poolname);
3996 		(void) zfs_error(hdl, EZFS_OPENFAILED, errbuf);
3997 		goto out;
3998 	}
3999 	config = zpool_get_config(zhp, NULL);
4000 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4001 	    &nvroot) != 0) {
4002 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4003 		    "could not obtain vdev configuration for  '%s'"), poolname);
4004 		(void) zfs_error(hdl, EZFS_INVALCONFIG, errbuf);
4005 		goto out;
4006 	}
4007 
4008 	verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
4009 	    &top, &toplevels) == 0);
4010 
4011 	if (!supported_dump_vdev_type(hdl, top[0], errbuf)) {
4012 		goto out;
4013 	}
4014 	ret = 0;
4015 
4016 out:
4017 	if (zhp)
4018 		zpool_close(zhp);
4019 	libzfs_fini(hdl);
4020 	return (ret);
4021 }
4022