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