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