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