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