xref: /illumos-gate/usr/src/lib/libzfs/common/libzfs_pool.c (revision c1d5c2a48971d1705730e1ade6a1bc4d56587416)
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 	char msg[1024];
1166 	int ret = -1;
1167 
1168 	(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1169 	    "cannot create '%s'"), pool);
1170 
1171 	if (!zpool_name_valid(hdl, B_FALSE, pool))
1172 		return (zfs_error(hdl, EZFS_INVALIDNAME, msg));
1173 
1174 	if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
1175 		return (-1);
1176 
1177 	if (props) {
1178 		prop_flags_t flags = { .create = B_TRUE, .import = B_FALSE };
1179 
1180 		if ((zc_props = zpool_valid_proplist(hdl, pool, props,
1181 		    SPA_VERSION_1, flags, msg)) == NULL) {
1182 			goto create_failed;
1183 		}
1184 	}
1185 
1186 	if (fsprops) {
1187 		uint64_t zoned;
1188 		char *zonestr;
1189 
1190 		zoned = ((nvlist_lookup_string(fsprops,
1191 		    zfs_prop_to_name(ZFS_PROP_ZONED), &zonestr) == 0) &&
1192 		    strcmp(zonestr, "on") == 0);
1193 
1194 		if ((zc_fsprops = zfs_valid_proplist(hdl, ZFS_TYPE_FILESYSTEM,
1195 		    fsprops, zoned, NULL, NULL, msg)) == NULL) {
1196 			goto create_failed;
1197 		}
1198 
1199 		if (nvlist_exists(zc_fsprops,
1200 		    zfs_prop_to_name(ZFS_PROP_SPECIAL_SMALL_BLOCKS)) &&
1201 		    !zpool_has_special_vdev(nvroot)) {
1202 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1203 			    "%s property requires a special vdev"),
1204 			    zfs_prop_to_name(ZFS_PROP_SPECIAL_SMALL_BLOCKS));
1205 			(void) zfs_error(hdl, EZFS_BADPROP, msg);
1206 			goto create_failed;
1207 		}
1208 
1209 		if (!zc_props &&
1210 		    (nvlist_alloc(&zc_props, NV_UNIQUE_NAME, 0) != 0)) {
1211 			goto create_failed;
1212 		}
1213 		if (nvlist_add_nvlist(zc_props,
1214 		    ZPOOL_ROOTFS_PROPS, zc_fsprops) != 0) {
1215 			goto create_failed;
1216 		}
1217 	}
1218 
1219 	if (zc_props && zcmd_write_src_nvlist(hdl, &zc, zc_props) != 0)
1220 		goto create_failed;
1221 
1222 	(void) strlcpy(zc.zc_name, pool, sizeof (zc.zc_name));
1223 
1224 	if ((ret = zfs_ioctl(hdl, ZFS_IOC_POOL_CREATE, &zc)) != 0) {
1225 
1226 		zcmd_free_nvlists(&zc);
1227 		nvlist_free(zc_props);
1228 		nvlist_free(zc_fsprops);
1229 
1230 		switch (errno) {
1231 		case EBUSY:
1232 			/*
1233 			 * This can happen if the user has specified the same
1234 			 * device multiple times.  We can't reliably detect this
1235 			 * until we try to add it and see we already have a
1236 			 * label.
1237 			 */
1238 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1239 			    "one or more vdevs refer to the same device"));
1240 			return (zfs_error(hdl, EZFS_BADDEV, msg));
1241 
1242 		case ERANGE:
1243 			/*
1244 			 * This happens if the record size is smaller or larger
1245 			 * than the allowed size range, or not a power of 2.
1246 			 *
1247 			 * NOTE: although zfs_valid_proplist is called earlier,
1248 			 * this case may have slipped through since the
1249 			 * pool does not exist yet and it is therefore
1250 			 * impossible to read properties e.g. max blocksize
1251 			 * from the pool.
1252 			 */
1253 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1254 			    "record size invalid"));
1255 			return (zfs_error(hdl, EZFS_BADPROP, msg));
1256 
1257 		case EOVERFLOW:
1258 			/*
1259 			 * This occurs when one of the devices is below
1260 			 * SPA_MINDEVSIZE.  Unfortunately, we can't detect which
1261 			 * device was the problem device since there's no
1262 			 * reliable way to determine device size from userland.
1263 			 */
1264 			{
1265 				char buf[64];
1266 
1267 				zfs_nicenum(SPA_MINDEVSIZE, buf, sizeof (buf));
1268 
1269 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1270 				    "one or more devices is less than the "
1271 				    "minimum size (%s)"), buf);
1272 			}
1273 			return (zfs_error(hdl, EZFS_BADDEV, msg));
1274 
1275 		case ENOSPC:
1276 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1277 			    "one or more devices is out of space"));
1278 			return (zfs_error(hdl, EZFS_BADDEV, msg));
1279 
1280 		default:
1281 			return (zpool_standard_error(hdl, errno, msg));
1282 		}
1283 	}
1284 
1285 create_failed:
1286 	zcmd_free_nvlists(&zc);
1287 	nvlist_free(zc_props);
1288 	nvlist_free(zc_fsprops);
1289 	return (ret);
1290 }
1291 
1292 /*
1293  * Destroy the given pool.  It is up to the caller to ensure that there are no
1294  * datasets left in the pool.
1295  */
1296 int
1297 zpool_destroy(zpool_handle_t *zhp, const char *log_str)
1298 {
1299 	zfs_cmd_t zc = { 0 };
1300 	zfs_handle_t *zfp = NULL;
1301 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1302 	char msg[1024];
1303 
1304 	if (zhp->zpool_state == POOL_STATE_ACTIVE &&
1305 	    (zfp = zfs_open(hdl, zhp->zpool_name, ZFS_TYPE_FILESYSTEM)) == NULL)
1306 		return (-1);
1307 
1308 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1309 	zc.zc_history = (uint64_t)(uintptr_t)log_str;
1310 
1311 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_DESTROY, &zc) != 0) {
1312 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1313 		    "cannot destroy '%s'"), zhp->zpool_name);
1314 
1315 		if (errno == EROFS) {
1316 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1317 			    "one or more devices is read only"));
1318 			(void) zfs_error(hdl, EZFS_BADDEV, msg);
1319 		} else {
1320 			(void) zpool_standard_error(hdl, errno, msg);
1321 		}
1322 
1323 		if (zfp)
1324 			zfs_close(zfp);
1325 		return (-1);
1326 	}
1327 
1328 	if (zfp) {
1329 		remove_mountpoint(zfp);
1330 		zfs_close(zfp);
1331 	}
1332 
1333 	return (0);
1334 }
1335 
1336 /*
1337  * Create a checkpoint in the given pool.
1338  */
1339 int
1340 zpool_checkpoint(zpool_handle_t *zhp)
1341 {
1342 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1343 	char msg[1024];
1344 	int error;
1345 
1346 	error = lzc_pool_checkpoint(zhp->zpool_name);
1347 	if (error != 0) {
1348 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1349 		    "cannot checkpoint '%s'"), zhp->zpool_name);
1350 		(void) zpool_standard_error(hdl, error, msg);
1351 		return (-1);
1352 	}
1353 
1354 	return (0);
1355 }
1356 
1357 /*
1358  * Discard the checkpoint from the given pool.
1359  */
1360 int
1361 zpool_discard_checkpoint(zpool_handle_t *zhp)
1362 {
1363 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1364 	char msg[1024];
1365 	int error;
1366 
1367 	error = lzc_pool_checkpoint_discard(zhp->zpool_name);
1368 	if (error != 0) {
1369 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1370 		    "cannot discard checkpoint in '%s'"), zhp->zpool_name);
1371 		(void) zpool_standard_error(hdl, error, msg);
1372 		return (-1);
1373 	}
1374 
1375 	return (0);
1376 }
1377 
1378 /*
1379  * Add the given vdevs to the pool.  The caller must have already performed the
1380  * necessary verification to ensure that the vdev specification is well-formed.
1381  */
1382 int
1383 zpool_add(zpool_handle_t *zhp, nvlist_t *nvroot)
1384 {
1385 	zfs_cmd_t zc = { 0 };
1386 	int ret;
1387 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1388 	char msg[1024];
1389 	nvlist_t **spares, **l2cache;
1390 	uint_t nspares, nl2cache;
1391 
1392 	(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1393 	    "cannot add to '%s'"), zhp->zpool_name);
1394 
1395 	if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) <
1396 	    SPA_VERSION_SPARES &&
1397 	    nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1398 	    &spares, &nspares) == 0) {
1399 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be "
1400 		    "upgraded to add hot spares"));
1401 		return (zfs_error(hdl, EZFS_BADVERSION, msg));
1402 	}
1403 
1404 	if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) <
1405 	    SPA_VERSION_L2CACHE &&
1406 	    nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1407 	    &l2cache, &nl2cache) == 0) {
1408 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be "
1409 		    "upgraded to add cache devices"));
1410 		return (zfs_error(hdl, EZFS_BADVERSION, msg));
1411 	}
1412 
1413 	if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
1414 		return (-1);
1415 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1416 
1417 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_ADD, &zc) != 0) {
1418 		switch (errno) {
1419 		case EBUSY:
1420 			/*
1421 			 * This can happen if the user has specified the same
1422 			 * device multiple times.  We can't reliably detect this
1423 			 * until we try to add it and see we already have a
1424 			 * label.
1425 			 */
1426 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1427 			    "one or more vdevs refer to the same device"));
1428 			(void) zfs_error(hdl, EZFS_BADDEV, msg);
1429 			break;
1430 
1431 		case EINVAL:
1432 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1433 			    "invalid config; a pool with removing/removed "
1434 			    "vdevs does not support adding raidz vdevs"));
1435 			(void) zfs_error(hdl, EZFS_BADDEV, msg);
1436 			break;
1437 
1438 		case EOVERFLOW:
1439 			/*
1440 			 * This occurrs when one of the devices is below
1441 			 * SPA_MINDEVSIZE.  Unfortunately, we can't detect which
1442 			 * device was the problem device since there's no
1443 			 * reliable way to determine device size from userland.
1444 			 */
1445 			{
1446 				char buf[64];
1447 
1448 				zfs_nicenum(SPA_MINDEVSIZE, buf, sizeof (buf));
1449 
1450 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1451 				    "device is less than the minimum "
1452 				    "size (%s)"), buf);
1453 			}
1454 			(void) zfs_error(hdl, EZFS_BADDEV, msg);
1455 			break;
1456 
1457 		case ENOTSUP:
1458 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1459 			    "pool must be upgraded to add these vdevs"));
1460 			(void) zfs_error(hdl, EZFS_BADVERSION, msg);
1461 			break;
1462 
1463 		case EDOM:
1464 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1465 			    "root pool can not have multiple vdevs"
1466 			    " or separate logs"));
1467 			(void) zfs_error(hdl, EZFS_POOL_NOTSUP, msg);
1468 			break;
1469 
1470 		default:
1471 			(void) zpool_standard_error(hdl, errno, msg);
1472 		}
1473 
1474 		ret = -1;
1475 	} else {
1476 		ret = 0;
1477 	}
1478 
1479 	zcmd_free_nvlists(&zc);
1480 
1481 	return (ret);
1482 }
1483 
1484 /*
1485  * Exports the pool from the system.  The caller must ensure that there are no
1486  * mounted datasets in the pool.
1487  */
1488 static int
1489 zpool_export_common(zpool_handle_t *zhp, boolean_t force, boolean_t hardforce,
1490     const char *log_str)
1491 {
1492 	zfs_cmd_t zc = { 0 };
1493 	char msg[1024];
1494 
1495 	(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1496 	    "cannot export '%s'"), zhp->zpool_name);
1497 
1498 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1499 	zc.zc_cookie = force;
1500 	zc.zc_guid = hardforce;
1501 	zc.zc_history = (uint64_t)(uintptr_t)log_str;
1502 
1503 	if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_EXPORT, &zc) != 0) {
1504 		switch (errno) {
1505 		case EXDEV:
1506 			zfs_error_aux(zhp->zpool_hdl, dgettext(TEXT_DOMAIN,
1507 			    "use '-f' to override the following errors:\n"
1508 			    "'%s' has an active shared spare which could be"
1509 			    " used by other pools once '%s' is exported."),
1510 			    zhp->zpool_name, zhp->zpool_name);
1511 			return (zfs_error(zhp->zpool_hdl, EZFS_ACTIVE_SPARE,
1512 			    msg));
1513 		default:
1514 			return (zpool_standard_error_fmt(zhp->zpool_hdl, errno,
1515 			    msg));
1516 		}
1517 	}
1518 
1519 	return (0);
1520 }
1521 
1522 int
1523 zpool_export(zpool_handle_t *zhp, boolean_t force, const char *log_str)
1524 {
1525 	return (zpool_export_common(zhp, force, B_FALSE, log_str));
1526 }
1527 
1528 int
1529 zpool_export_force(zpool_handle_t *zhp, const char *log_str)
1530 {
1531 	return (zpool_export_common(zhp, B_TRUE, B_TRUE, log_str));
1532 }
1533 
1534 static void
1535 zpool_rewind_exclaim(libzfs_handle_t *hdl, const char *name, boolean_t dryrun,
1536     nvlist_t *config)
1537 {
1538 	nvlist_t *nv = NULL;
1539 	uint64_t rewindto;
1540 	int64_t loss = -1;
1541 	struct tm t;
1542 	char timestr[128];
1543 
1544 	if (!hdl->libzfs_printerr || config == NULL)
1545 		return;
1546 
1547 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nv) != 0 ||
1548 	    nvlist_lookup_nvlist(nv, ZPOOL_CONFIG_REWIND_INFO, &nv) != 0) {
1549 		return;
1550 	}
1551 
1552 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_TIME, &rewindto) != 0)
1553 		return;
1554 	(void) nvlist_lookup_int64(nv, ZPOOL_CONFIG_REWIND_TIME, &loss);
1555 
1556 	if (localtime_r((time_t *)&rewindto, &t) != NULL &&
1557 	    strftime(timestr, 128, 0, &t) != 0) {
1558 		if (dryrun) {
1559 			(void) printf(dgettext(TEXT_DOMAIN,
1560 			    "Would be able to return %s "
1561 			    "to its state as of %s.\n"),
1562 			    name, timestr);
1563 		} else {
1564 			(void) printf(dgettext(TEXT_DOMAIN,
1565 			    "Pool %s returned to its state as of %s.\n"),
1566 			    name, timestr);
1567 		}
1568 		if (loss > 120) {
1569 			(void) printf(dgettext(TEXT_DOMAIN,
1570 			    "%s approximately %lld "),
1571 			    dryrun ? "Would discard" : "Discarded",
1572 			    (loss + 30) / 60);
1573 			(void) printf(dgettext(TEXT_DOMAIN,
1574 			    "minutes of transactions.\n"));
1575 		} else if (loss > 0) {
1576 			(void) printf(dgettext(TEXT_DOMAIN,
1577 			    "%s approximately %lld "),
1578 			    dryrun ? "Would discard" : "Discarded", loss);
1579 			(void) printf(dgettext(TEXT_DOMAIN,
1580 			    "seconds of transactions.\n"));
1581 		}
1582 	}
1583 }
1584 
1585 void
1586 zpool_explain_recover(libzfs_handle_t *hdl, const char *name, int reason,
1587     nvlist_t *config)
1588 {
1589 	nvlist_t *nv = NULL;
1590 	int64_t loss = -1;
1591 	uint64_t edata = UINT64_MAX;
1592 	uint64_t rewindto;
1593 	struct tm t;
1594 	char timestr[128];
1595 
1596 	if (!hdl->libzfs_printerr)
1597 		return;
1598 
1599 	if (reason >= 0)
1600 		(void) printf(dgettext(TEXT_DOMAIN, "action: "));
1601 	else
1602 		(void) printf(dgettext(TEXT_DOMAIN, "\t"));
1603 
1604 	/* All attempted rewinds failed if ZPOOL_CONFIG_LOAD_TIME missing */
1605 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nv) != 0 ||
1606 	    nvlist_lookup_nvlist(nv, ZPOOL_CONFIG_REWIND_INFO, &nv) != 0 ||
1607 	    nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_TIME, &rewindto) != 0)
1608 		goto no_info;
1609 
1610 	(void) nvlist_lookup_int64(nv, ZPOOL_CONFIG_REWIND_TIME, &loss);
1611 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_DATA_ERRORS,
1612 	    &edata);
1613 
1614 	(void) printf(dgettext(TEXT_DOMAIN,
1615 	    "Recovery is possible, but will result in some data loss.\n"));
1616 
1617 	if (localtime_r((time_t *)&rewindto, &t) != NULL &&
1618 	    strftime(timestr, 128, 0, &t) != 0) {
1619 		(void) printf(dgettext(TEXT_DOMAIN,
1620 		    "\tReturning the pool to its state as of %s\n"
1621 		    "\tshould correct the problem.  "),
1622 		    timestr);
1623 	} else {
1624 		(void) printf(dgettext(TEXT_DOMAIN,
1625 		    "\tReverting the pool to an earlier state "
1626 		    "should correct the problem.\n\t"));
1627 	}
1628 
1629 	if (loss > 120) {
1630 		(void) printf(dgettext(TEXT_DOMAIN,
1631 		    "Approximately %lld minutes of data\n"
1632 		    "\tmust be discarded, irreversibly.  "), (loss + 30) / 60);
1633 	} else if (loss > 0) {
1634 		(void) printf(dgettext(TEXT_DOMAIN,
1635 		    "Approximately %lld seconds of data\n"
1636 		    "\tmust be discarded, irreversibly.  "), loss);
1637 	}
1638 	if (edata != 0 && edata != UINT64_MAX) {
1639 		if (edata == 1) {
1640 			(void) printf(dgettext(TEXT_DOMAIN,
1641 			    "After rewind, at least\n"
1642 			    "\tone persistent user-data error will remain.  "));
1643 		} else {
1644 			(void) printf(dgettext(TEXT_DOMAIN,
1645 			    "After rewind, several\n"
1646 			    "\tpersistent user-data errors will remain.  "));
1647 		}
1648 	}
1649 	(void) printf(dgettext(TEXT_DOMAIN,
1650 	    "Recovery can be attempted\n\tby executing 'zpool %s -F %s'.  "),
1651 	    reason >= 0 ? "clear" : "import", name);
1652 
1653 	(void) printf(dgettext(TEXT_DOMAIN,
1654 	    "A scrub of the pool\n"
1655 	    "\tis strongly recommended after recovery.\n"));
1656 	return;
1657 
1658 no_info:
1659 	(void) printf(dgettext(TEXT_DOMAIN,
1660 	    "Destroy and re-create the pool from\n\ta backup source.\n"));
1661 }
1662 
1663 /*
1664  * zpool_import() is a contracted interface. Should be kept the same
1665  * if possible.
1666  *
1667  * Applications should use zpool_import_props() to import a pool with
1668  * new properties value to be set.
1669  */
1670 int
1671 zpool_import(libzfs_handle_t *hdl, nvlist_t *config, const char *newname,
1672     char *altroot)
1673 {
1674 	nvlist_t *props = NULL;
1675 	int ret;
1676 
1677 	if (altroot != NULL) {
1678 		if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
1679 			return (zfs_error_fmt(hdl, EZFS_NOMEM,
1680 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1681 			    newname));
1682 		}
1683 
1684 		if (nvlist_add_string(props,
1685 		    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), altroot) != 0 ||
1686 		    nvlist_add_string(props,
1687 		    zpool_prop_to_name(ZPOOL_PROP_CACHEFILE), "none") != 0) {
1688 			nvlist_free(props);
1689 			return (zfs_error_fmt(hdl, EZFS_NOMEM,
1690 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1691 			    newname));
1692 		}
1693 	}
1694 
1695 	ret = zpool_import_props(hdl, config, newname, props,
1696 	    ZFS_IMPORT_NORMAL);
1697 	nvlist_free(props);
1698 	return (ret);
1699 }
1700 
1701 static void
1702 print_vdev_tree(libzfs_handle_t *hdl, const char *name, nvlist_t *nv,
1703     int indent)
1704 {
1705 	nvlist_t **child;
1706 	uint_t c, children;
1707 	char *vname;
1708 	uint64_t is_log = 0;
1709 
1710 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG,
1711 	    &is_log);
1712 
1713 	if (name != NULL)
1714 		(void) printf("\t%*s%s%s\n", indent, "", name,
1715 		    is_log ? " [log]" : "");
1716 
1717 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1718 	    &child, &children) != 0)
1719 		return;
1720 
1721 	for (c = 0; c < children; c++) {
1722 		vname = zpool_vdev_name(hdl, NULL, child[c], VDEV_NAME_TYPE_ID);
1723 		print_vdev_tree(hdl, vname, child[c], indent + 2);
1724 		free(vname);
1725 	}
1726 }
1727 
1728 void
1729 zpool_print_unsup_feat(nvlist_t *config)
1730 {
1731 	nvlist_t *nvinfo, *unsup_feat;
1732 
1733 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nvinfo) ==
1734 	    0);
1735 	verify(nvlist_lookup_nvlist(nvinfo, ZPOOL_CONFIG_UNSUP_FEAT,
1736 	    &unsup_feat) == 0);
1737 
1738 	for (nvpair_t *nvp = nvlist_next_nvpair(unsup_feat, NULL); nvp != NULL;
1739 	    nvp = nvlist_next_nvpair(unsup_feat, nvp)) {
1740 		char *desc;
1741 
1742 		verify(nvpair_type(nvp) == DATA_TYPE_STRING);
1743 		verify(nvpair_value_string(nvp, &desc) == 0);
1744 
1745 		if (strlen(desc) > 0)
1746 			(void) printf("\t%s (%s)\n", nvpair_name(nvp), desc);
1747 		else
1748 			(void) printf("\t%s\n", nvpair_name(nvp));
1749 	}
1750 }
1751 
1752 /*
1753  * Import the given pool using the known configuration and a list of
1754  * properties to be set. The configuration should have come from
1755  * zpool_find_import(). The 'newname' parameters control whether the pool
1756  * is imported with a different name.
1757  */
1758 int
1759 zpool_import_props(libzfs_handle_t *hdl, nvlist_t *config, const char *newname,
1760     nvlist_t *props, int flags)
1761 {
1762 	zfs_cmd_t zc = { 0 };
1763 	zpool_load_policy_t policy;
1764 	nvlist_t *nv = NULL;
1765 	nvlist_t *nvinfo = NULL;
1766 	nvlist_t *missing = NULL;
1767 	char *thename;
1768 	char *origname;
1769 	int ret;
1770 	int error = 0;
1771 	char errbuf[1024];
1772 
1773 	verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1774 	    &origname) == 0);
1775 
1776 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1777 	    "cannot import pool '%s'"), origname);
1778 
1779 	if (newname != NULL) {
1780 		if (!zpool_name_valid(hdl, B_FALSE, newname))
1781 			return (zfs_error_fmt(hdl, EZFS_INVALIDNAME,
1782 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1783 			    newname));
1784 		thename = (char *)newname;
1785 	} else {
1786 		thename = origname;
1787 	}
1788 
1789 	if (props != NULL) {
1790 		uint64_t version;
1791 		prop_flags_t flags = { .create = B_FALSE, .import = B_TRUE };
1792 
1793 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
1794 		    &version) == 0);
1795 
1796 		if ((props = zpool_valid_proplist(hdl, origname,
1797 		    props, version, flags, errbuf)) == NULL)
1798 			return (-1);
1799 		if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) {
1800 			nvlist_free(props);
1801 			return (-1);
1802 		}
1803 		nvlist_free(props);
1804 	}
1805 
1806 	(void) strlcpy(zc.zc_name, thename, sizeof (zc.zc_name));
1807 
1808 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1809 	    &zc.zc_guid) == 0);
1810 
1811 	if (zcmd_write_conf_nvlist(hdl, &zc, config) != 0) {
1812 		zcmd_free_nvlists(&zc);
1813 		return (-1);
1814 	}
1815 	if (zcmd_alloc_dst_nvlist(hdl, &zc, zc.zc_nvlist_conf_size * 2) != 0) {
1816 		zcmd_free_nvlists(&zc);
1817 		return (-1);
1818 	}
1819 
1820 	zc.zc_cookie = flags;
1821 	while ((ret = zfs_ioctl(hdl, ZFS_IOC_POOL_IMPORT, &zc)) != 0 &&
1822 	    errno == ENOMEM) {
1823 		if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
1824 			zcmd_free_nvlists(&zc);
1825 			return (-1);
1826 		}
1827 	}
1828 	if (ret != 0)
1829 		error = errno;
1830 
1831 	(void) zcmd_read_dst_nvlist(hdl, &zc, &nv);
1832 
1833 	zcmd_free_nvlists(&zc);
1834 
1835 	zpool_get_load_policy(config, &policy);
1836 
1837 	if (error) {
1838 		char desc[1024];
1839 		char aux[256];
1840 
1841 		/*
1842 		 * Dry-run failed, but we print out what success
1843 		 * looks like if we found a best txg
1844 		 */
1845 		if (policy.zlp_rewind & ZPOOL_TRY_REWIND) {
1846 			zpool_rewind_exclaim(hdl, newname ? origname : thename,
1847 			    B_TRUE, nv);
1848 			nvlist_free(nv);
1849 			return (-1);
1850 		}
1851 
1852 		if (newname == NULL)
1853 			(void) snprintf(desc, sizeof (desc),
1854 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1855 			    thename);
1856 		else
1857 			(void) snprintf(desc, sizeof (desc),
1858 			    dgettext(TEXT_DOMAIN, "cannot import '%s' as '%s'"),
1859 			    origname, thename);
1860 
1861 		switch (error) {
1862 		case ENOTSUP:
1863 			if (nv != NULL && nvlist_lookup_nvlist(nv,
1864 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0 &&
1865 			    nvlist_exists(nvinfo, ZPOOL_CONFIG_UNSUP_FEAT)) {
1866 				(void) printf(dgettext(TEXT_DOMAIN, "This "
1867 				    "pool uses the following feature(s) not "
1868 				    "supported by this system:\n"));
1869 				zpool_print_unsup_feat(nv);
1870 				if (nvlist_exists(nvinfo,
1871 				    ZPOOL_CONFIG_CAN_RDONLY)) {
1872 					(void) printf(dgettext(TEXT_DOMAIN,
1873 					    "All unsupported features are only "
1874 					    "required for writing to the pool."
1875 					    "\nThe pool can be imported using "
1876 					    "'-o readonly=on'.\n"));
1877 				}
1878 			}
1879 			/*
1880 			 * Unsupported version.
1881 			 */
1882 			(void) zfs_error(hdl, EZFS_BADVERSION, desc);
1883 			break;
1884 
1885 		case EREMOTEIO:
1886 			if (nv != NULL && nvlist_lookup_nvlist(nv,
1887 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0) {
1888 				char *hostname = "<unknown>";
1889 				uint64_t hostid = 0;
1890 				mmp_state_t mmp_state;
1891 
1892 				mmp_state = fnvlist_lookup_uint64(nvinfo,
1893 				    ZPOOL_CONFIG_MMP_STATE);
1894 
1895 				if (nvlist_exists(nvinfo,
1896 				    ZPOOL_CONFIG_MMP_HOSTNAME))
1897 					hostname = fnvlist_lookup_string(nvinfo,
1898 					    ZPOOL_CONFIG_MMP_HOSTNAME);
1899 
1900 				if (nvlist_exists(nvinfo,
1901 				    ZPOOL_CONFIG_MMP_HOSTID))
1902 					hostid = fnvlist_lookup_uint64(nvinfo,
1903 					    ZPOOL_CONFIG_MMP_HOSTID);
1904 
1905 				if (mmp_state == MMP_STATE_ACTIVE) {
1906 					(void) snprintf(aux, sizeof (aux),
1907 					    dgettext(TEXT_DOMAIN, "pool is imp"
1908 					    "orted on host '%s' (hostid=%lx).\n"
1909 					    "Export the pool on the other "
1910 					    "system, then run 'zpool import'."),
1911 					    hostname, (unsigned long) hostid);
1912 				} else if (mmp_state == MMP_STATE_NO_HOSTID) {
1913 					(void) snprintf(aux, sizeof (aux),
1914 					    dgettext(TEXT_DOMAIN, "pool has "
1915 					    "the multihost property on and "
1916 					    "the\nsystem's hostid is not "
1917 					    "set.\n"));
1918 				}
1919 
1920 				(void) zfs_error_aux(hdl, aux);
1921 			}
1922 			(void) zfs_error(hdl, EZFS_ACTIVE_POOL, desc);
1923 			break;
1924 
1925 		case EINVAL:
1926 			(void) zfs_error(hdl, EZFS_INVALCONFIG, desc);
1927 			break;
1928 
1929 		case EROFS:
1930 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1931 			    "one or more devices is read only"));
1932 			(void) zfs_error(hdl, EZFS_BADDEV, desc);
1933 			break;
1934 
1935 		case ENXIO:
1936 			if (nv && nvlist_lookup_nvlist(nv,
1937 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0 &&
1938 			    nvlist_lookup_nvlist(nvinfo,
1939 			    ZPOOL_CONFIG_MISSING_DEVICES, &missing) == 0) {
1940 				(void) printf(dgettext(TEXT_DOMAIN,
1941 				    "The devices below are missing or "
1942 				    "corrupted, use '-m' to import the pool "
1943 				    "anyway:\n"));
1944 				print_vdev_tree(hdl, NULL, missing, 2);
1945 				(void) printf("\n");
1946 			}
1947 			(void) zpool_standard_error(hdl, error, desc);
1948 			break;
1949 
1950 		case EEXIST:
1951 			(void) zpool_standard_error(hdl, error, desc);
1952 			break;
1953 		case ENAMETOOLONG:
1954 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1955 			    "new name of at least one dataset is longer than "
1956 			    "the maximum allowable length"));
1957 			(void) zfs_error(hdl, EZFS_NAMETOOLONG, desc);
1958 			break;
1959 		default:
1960 			(void) zpool_standard_error(hdl, error, desc);
1961 			zpool_explain_recover(hdl,
1962 			    newname ? origname : thename, -error, nv);
1963 			break;
1964 		}
1965 
1966 		nvlist_free(nv);
1967 		ret = -1;
1968 	} else {
1969 		zpool_handle_t *zhp;
1970 
1971 		/*
1972 		 * This should never fail, but play it safe anyway.
1973 		 */
1974 		if (zpool_open_silent(hdl, thename, &zhp) != 0)
1975 			ret = -1;
1976 		else if (zhp != NULL)
1977 			zpool_close(zhp);
1978 		if (policy.zlp_rewind &
1979 		    (ZPOOL_DO_REWIND | ZPOOL_TRY_REWIND)) {
1980 			zpool_rewind_exclaim(hdl, newname ? origname : thename,
1981 			    ((policy.zlp_rewind & ZPOOL_TRY_REWIND) != 0), nv);
1982 		}
1983 		nvlist_free(nv);
1984 		return (0);
1985 	}
1986 
1987 	return (ret);
1988 }
1989 
1990 /*
1991  * Scan the pool.
1992  */
1993 int
1994 zpool_scan(zpool_handle_t *zhp, pool_scan_func_t func, pool_scrub_cmd_t cmd)
1995 {
1996 	zfs_cmd_t zc = { 0 };
1997 	char msg[1024];
1998 	int err;
1999 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2000 
2001 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2002 	zc.zc_cookie = func;
2003 	zc.zc_flags = cmd;
2004 
2005 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_SCAN, &zc) == 0)
2006 		return (0);
2007 
2008 	err = errno;
2009 
2010 	/* ECANCELED on a scrub means we resumed a paused scrub */
2011 	if (err == ECANCELED && func == POOL_SCAN_SCRUB &&
2012 	    cmd == POOL_SCRUB_NORMAL)
2013 		return (0);
2014 
2015 	if (err == ENOENT && func != POOL_SCAN_NONE && cmd == POOL_SCRUB_NORMAL)
2016 		return (0);
2017 
2018 	if (func == POOL_SCAN_SCRUB) {
2019 		if (cmd == POOL_SCRUB_PAUSE) {
2020 			(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2021 			    "cannot pause scrubbing %s"), zc.zc_name);
2022 		} else {
2023 			assert(cmd == POOL_SCRUB_NORMAL);
2024 			(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2025 			    "cannot scrub %s"), zc.zc_name);
2026 		}
2027 	} else if (func == POOL_SCAN_RESILVER) {
2028 		assert(cmd == POOL_SCRUB_NORMAL);
2029 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2030 		    "cannot restart resilver on %s"), zc.zc_name);
2031 	} else if (func == POOL_SCAN_NONE) {
2032 		(void) snprintf(msg, sizeof (msg),
2033 		    dgettext(TEXT_DOMAIN, "cannot cancel scrubbing %s"),
2034 		    zc.zc_name);
2035 	} else {
2036 		assert(!"unexpected result");
2037 	}
2038 
2039 	if (err == EBUSY) {
2040 		nvlist_t *nvroot;
2041 		pool_scan_stat_t *ps = NULL;
2042 		uint_t psc;
2043 
2044 		verify(nvlist_lookup_nvlist(zhp->zpool_config,
2045 		    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
2046 		(void) nvlist_lookup_uint64_array(nvroot,
2047 		    ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &psc);
2048 		if (ps && ps->pss_func == POOL_SCAN_SCRUB) {
2049 			if (cmd == POOL_SCRUB_PAUSE)
2050 				return (zfs_error(hdl, EZFS_SCRUB_PAUSED, msg));
2051 			else
2052 				return (zfs_error(hdl, EZFS_SCRUBBING, msg));
2053 		} else {
2054 			return (zfs_error(hdl, EZFS_RESILVERING, msg));
2055 		}
2056 	} else if (err == ENOENT) {
2057 		return (zfs_error(hdl, EZFS_NO_SCRUB, msg));
2058 	} else if (err == ENOTSUP && func == POOL_SCAN_RESILVER) {
2059 		return (zfs_error(hdl, EZFS_NO_RESILVER_DEFER, msg));
2060 	} else {
2061 		return (zpool_standard_error(hdl, err, msg));
2062 	}
2063 }
2064 
2065 static int
2066 xlate_init_err(int err)
2067 {
2068 	switch (err) {
2069 	case ENODEV:
2070 		return (EZFS_NODEVICE);
2071 	case EINVAL:
2072 	case EROFS:
2073 		return (EZFS_BADDEV);
2074 	case EBUSY:
2075 		return (EZFS_INITIALIZING);
2076 	case ESRCH:
2077 		return (EZFS_NO_INITIALIZE);
2078 	}
2079 	return (err);
2080 }
2081 
2082 /*
2083  * Begin, suspend, or cancel the initialization (initializing of all free
2084  * blocks) for the given vdevs in the given pool.
2085  */
2086 int
2087 zpool_initialize(zpool_handle_t *zhp, pool_initialize_func_t cmd_type,
2088     nvlist_t *vds)
2089 {
2090 	char msg[1024];
2091 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2092 
2093 	nvlist_t *errlist;
2094 
2095 	/* translate vdev names to guids */
2096 	nvlist_t *vdev_guids = fnvlist_alloc();
2097 	nvlist_t *guids_to_paths = fnvlist_alloc();
2098 	boolean_t spare, cache;
2099 	nvlist_t *tgt;
2100 	nvpair_t *elem;
2101 
2102 	for (elem = nvlist_next_nvpair(vds, NULL); elem != NULL;
2103 	    elem = nvlist_next_nvpair(vds, elem)) {
2104 		char *vd_path = nvpair_name(elem);
2105 		tgt = zpool_find_vdev(zhp, vd_path, &spare, &cache, NULL);
2106 
2107 		if ((tgt == NULL) || cache || spare) {
2108 			(void) snprintf(msg, sizeof (msg),
2109 			    dgettext(TEXT_DOMAIN, "cannot initialize '%s'"),
2110 			    vd_path);
2111 			int err = (tgt == NULL) ? EZFS_NODEVICE :
2112 			    (spare ? EZFS_ISSPARE : EZFS_ISL2CACHE);
2113 			fnvlist_free(vdev_guids);
2114 			fnvlist_free(guids_to_paths);
2115 			return (zfs_error(hdl, err, msg));
2116 		}
2117 
2118 		uint64_t guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
2119 		fnvlist_add_uint64(vdev_guids, vd_path, guid);
2120 
2121 		(void) snprintf(msg, sizeof (msg), "%llu", guid);
2122 		fnvlist_add_string(guids_to_paths, msg, vd_path);
2123 	}
2124 
2125 	int err = lzc_initialize(zhp->zpool_name, cmd_type, vdev_guids,
2126 	    &errlist);
2127 	fnvlist_free(vdev_guids);
2128 
2129 	if (err == 0) {
2130 		fnvlist_free(guids_to_paths);
2131 		return (0);
2132 	}
2133 
2134 	nvlist_t *vd_errlist = NULL;
2135 	if (errlist != NULL) {
2136 		vd_errlist = fnvlist_lookup_nvlist(errlist,
2137 		    ZPOOL_INITIALIZE_VDEVS);
2138 	}
2139 
2140 	(void) snprintf(msg, sizeof (msg),
2141 	    dgettext(TEXT_DOMAIN, "operation failed"));
2142 
2143 	for (elem = nvlist_next_nvpair(vd_errlist, NULL); elem != NULL;
2144 	    elem = nvlist_next_nvpair(vd_errlist, elem)) {
2145 		int64_t vd_error = xlate_init_err(fnvpair_value_int64(elem));
2146 		char *path = fnvlist_lookup_string(guids_to_paths,
2147 		    nvpair_name(elem));
2148 		(void) zfs_error_fmt(hdl, vd_error, "cannot initialize '%s'",
2149 		    path);
2150 	}
2151 
2152 	fnvlist_free(guids_to_paths);
2153 	if (vd_errlist != NULL)
2154 		return (-1);
2155 
2156 	return (zpool_standard_error(hdl, err, msg));
2157 }
2158 
2159 /*
2160  * This provides a very minimal check whether a given string is likely a
2161  * c#t#d# style string.  Users of this are expected to do their own
2162  * verification of the s# part.
2163  */
2164 #define	CTD_CHECK(str)  (str && str[0] == 'c' && isdigit(str[1]))
2165 
2166 /*
2167  * More elaborate version for ones which may start with "/dev/dsk/"
2168  * and the like.
2169  */
2170 static int
2171 ctd_check_path(char *str)
2172 {
2173 	/*
2174 	 * If it starts with a slash, check the last component.
2175 	 */
2176 	if (str && str[0] == '/') {
2177 		char *tmp = strrchr(str, '/');
2178 
2179 		/*
2180 		 * If it ends in "/old", check the second-to-last
2181 		 * component of the string instead.
2182 		 */
2183 		if (tmp != str && strcmp(tmp, "/old") == 0) {
2184 			for (tmp--; *tmp != '/'; tmp--)
2185 				;
2186 		}
2187 		str = tmp + 1;
2188 	}
2189 	return (CTD_CHECK(str));
2190 }
2191 
2192 /*
2193  * Find a vdev that matches the search criteria specified. We use the
2194  * the nvpair name to determine how we should look for the device.
2195  * 'avail_spare' is set to TRUE if the provided guid refers to an AVAIL
2196  * spare; but FALSE if its an INUSE spare.
2197  */
2198 static nvlist_t *
2199 vdev_to_nvlist_iter(nvlist_t *nv, nvlist_t *search, boolean_t *avail_spare,
2200     boolean_t *l2cache, boolean_t *log)
2201 {
2202 	uint_t c, children;
2203 	nvlist_t **child;
2204 	nvlist_t *ret;
2205 	uint64_t is_log;
2206 	char *srchkey;
2207 	nvpair_t *pair = nvlist_next_nvpair(search, NULL);
2208 
2209 	/* Nothing to look for */
2210 	if (search == NULL || pair == NULL)
2211 		return (NULL);
2212 
2213 	/* Obtain the key we will use to search */
2214 	srchkey = nvpair_name(pair);
2215 
2216 	switch (nvpair_type(pair)) {
2217 	case DATA_TYPE_UINT64:
2218 		if (strcmp(srchkey, ZPOOL_CONFIG_GUID) == 0) {
2219 			uint64_t srchval, theguid;
2220 
2221 			verify(nvpair_value_uint64(pair, &srchval) == 0);
2222 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
2223 			    &theguid) == 0);
2224 			if (theguid == srchval)
2225 				return (nv);
2226 		}
2227 		break;
2228 
2229 	case DATA_TYPE_STRING: {
2230 		char *srchval, *val;
2231 
2232 		verify(nvpair_value_string(pair, &srchval) == 0);
2233 		if (nvlist_lookup_string(nv, srchkey, &val) != 0)
2234 			break;
2235 
2236 		/*
2237 		 * Search for the requested value. Special cases:
2238 		 *
2239 		 * - ZPOOL_CONFIG_PATH for whole disk entries. To support
2240 		 *   UEFI boot, these end in "s0" or "s0/old" or "s1" or
2241 		 *   "s1/old".   The "s0" or "s1" part is hidden from the user,
2242 		 *   but included in the string, so this matches around it.
2243 		 * - looking for a top-level vdev name (i.e. ZPOOL_CONFIG_TYPE).
2244 		 *
2245 		 * Otherwise, all other searches are simple string compares.
2246 		 */
2247 		if (strcmp(srchkey, ZPOOL_CONFIG_PATH) == 0 &&
2248 		    ctd_check_path(val)) {
2249 			uint64_t wholedisk = 0;
2250 
2251 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
2252 			    &wholedisk);
2253 			if (wholedisk) {
2254 				int slen = strlen(srchval);
2255 				int vlen = strlen(val);
2256 
2257 				if (slen != vlen - 2)
2258 					break;
2259 
2260 				/*
2261 				 * make_leaf_vdev() should only set
2262 				 * wholedisk for ZPOOL_CONFIG_PATHs which
2263 				 * will include "/dev/dsk/", giving plenty of
2264 				 * room for the indices used next.
2265 				 */
2266 				ASSERT(vlen >= 6);
2267 
2268 				/*
2269 				 * strings identical except trailing "s0"
2270 				 */
2271 				if ((strcmp(&val[vlen - 2], "s0") == 0 ||
2272 				    strcmp(&val[vlen - 2], "s1") == 0) &&
2273 				    strncmp(srchval, val, slen) == 0)
2274 					return (nv);
2275 
2276 				/*
2277 				 * strings identical except trailing "s0/old"
2278 				 */
2279 				if ((strcmp(&val[vlen - 6], "s0/old") == 0 ||
2280 				    strcmp(&val[vlen - 6], "s1/old") == 0) &&
2281 				    strcmp(&srchval[slen - 4], "/old") == 0 &&
2282 				    strncmp(srchval, val, slen - 4) == 0)
2283 					return (nv);
2284 
2285 				break;
2286 			}
2287 		} else if (strcmp(srchkey, ZPOOL_CONFIG_TYPE) == 0 && val) {
2288 			char *type, *idx, *end, *p;
2289 			uint64_t id, vdev_id;
2290 
2291 			/*
2292 			 * Determine our vdev type, keeping in mind
2293 			 * that the srchval is composed of a type and
2294 			 * vdev id pair (i.e. mirror-4).
2295 			 */
2296 			if ((type = strdup(srchval)) == NULL)
2297 				return (NULL);
2298 
2299 			if ((p = strrchr(type, '-')) == NULL) {
2300 				free(type);
2301 				break;
2302 			}
2303 			idx = p + 1;
2304 			*p = '\0';
2305 
2306 			/*
2307 			 * If the types don't match then keep looking.
2308 			 */
2309 			if (strncmp(val, type, strlen(val)) != 0) {
2310 				free(type);
2311 				break;
2312 			}
2313 
2314 			verify(zpool_vdev_is_interior(type));
2315 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID,
2316 			    &id) == 0);
2317 
2318 			errno = 0;
2319 			vdev_id = strtoull(idx, &end, 10);
2320 
2321 			free(type);
2322 			if (errno != 0)
2323 				return (NULL);
2324 
2325 			/*
2326 			 * Now verify that we have the correct vdev id.
2327 			 */
2328 			if (vdev_id == id)
2329 				return (nv);
2330 		}
2331 
2332 		/*
2333 		 * Common case
2334 		 */
2335 		if (strcmp(srchval, val) == 0)
2336 			return (nv);
2337 		break;
2338 	}
2339 
2340 	default:
2341 		break;
2342 	}
2343 
2344 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2345 	    &child, &children) != 0)
2346 		return (NULL);
2347 
2348 	for (c = 0; c < children; c++) {
2349 		if ((ret = vdev_to_nvlist_iter(child[c], search,
2350 		    avail_spare, l2cache, NULL)) != NULL) {
2351 			/*
2352 			 * The 'is_log' value is only set for the toplevel
2353 			 * vdev, not the leaf vdevs.  So we always lookup the
2354 			 * log device from the root of the vdev tree (where
2355 			 * 'log' is non-NULL).
2356 			 */
2357 			if (log != NULL &&
2358 			    nvlist_lookup_uint64(child[c],
2359 			    ZPOOL_CONFIG_IS_LOG, &is_log) == 0 &&
2360 			    is_log) {
2361 				*log = B_TRUE;
2362 			}
2363 			return (ret);
2364 		}
2365 	}
2366 
2367 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
2368 	    &child, &children) == 0) {
2369 		for (c = 0; c < children; c++) {
2370 			if ((ret = vdev_to_nvlist_iter(child[c], search,
2371 			    avail_spare, l2cache, NULL)) != NULL) {
2372 				*avail_spare = B_TRUE;
2373 				return (ret);
2374 			}
2375 		}
2376 	}
2377 
2378 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
2379 	    &child, &children) == 0) {
2380 		for (c = 0; c < children; c++) {
2381 			if ((ret = vdev_to_nvlist_iter(child[c], search,
2382 			    avail_spare, l2cache, NULL)) != NULL) {
2383 				*l2cache = B_TRUE;
2384 				return (ret);
2385 			}
2386 		}
2387 	}
2388 
2389 	return (NULL);
2390 }
2391 
2392 /*
2393  * Given a physical path (minus the "/devices" prefix), find the
2394  * associated vdev.
2395  */
2396 nvlist_t *
2397 zpool_find_vdev_by_physpath(zpool_handle_t *zhp, const char *ppath,
2398     boolean_t *avail_spare, boolean_t *l2cache, boolean_t *log)
2399 {
2400 	nvlist_t *search, *nvroot, *ret;
2401 
2402 	verify(nvlist_alloc(&search, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2403 	verify(nvlist_add_string(search, ZPOOL_CONFIG_PHYS_PATH, ppath) == 0);
2404 
2405 	verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
2406 	    &nvroot) == 0);
2407 
2408 	*avail_spare = B_FALSE;
2409 	*l2cache = B_FALSE;
2410 	if (log != NULL)
2411 		*log = B_FALSE;
2412 	ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log);
2413 	nvlist_free(search);
2414 
2415 	return (ret);
2416 }
2417 
2418 /*
2419  * Determine if we have an "interior" top-level vdev (i.e mirror/raidz).
2420  */
2421 static boolean_t
2422 zpool_vdev_is_interior(const char *name)
2423 {
2424 	if (strncmp(name, VDEV_TYPE_RAIDZ, strlen(VDEV_TYPE_RAIDZ)) == 0 ||
2425 	    strncmp(name, VDEV_TYPE_SPARE, strlen(VDEV_TYPE_SPARE)) == 0 ||
2426 	    strncmp(name,
2427 	    VDEV_TYPE_REPLACING, strlen(VDEV_TYPE_REPLACING)) == 0 ||
2428 	    strncmp(name, VDEV_TYPE_MIRROR, strlen(VDEV_TYPE_MIRROR)) == 0)
2429 		return (B_TRUE);
2430 	return (B_FALSE);
2431 }
2432 
2433 nvlist_t *
2434 zpool_find_vdev(zpool_handle_t *zhp, const char *path, boolean_t *avail_spare,
2435     boolean_t *l2cache, boolean_t *log)
2436 {
2437 	char buf[MAXPATHLEN];
2438 	char *end;
2439 	nvlist_t *nvroot, *search, *ret;
2440 	uint64_t guid;
2441 
2442 	verify(nvlist_alloc(&search, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2443 
2444 	guid = strtoull(path, &end, 10);
2445 	if (guid != 0 && *end == '\0') {
2446 		verify(nvlist_add_uint64(search, ZPOOL_CONFIG_GUID, guid) == 0);
2447 	} else if (zpool_vdev_is_interior(path)) {
2448 		verify(nvlist_add_string(search, ZPOOL_CONFIG_TYPE, path) == 0);
2449 	} else if (path[0] != '/') {
2450 		(void) snprintf(buf, sizeof (buf), "%s/%s", ZFS_DISK_ROOT,
2451 		    path);
2452 		verify(nvlist_add_string(search, ZPOOL_CONFIG_PATH, buf) == 0);
2453 	} else {
2454 		verify(nvlist_add_string(search, ZPOOL_CONFIG_PATH, path) == 0);
2455 	}
2456 
2457 	verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
2458 	    &nvroot) == 0);
2459 
2460 	*avail_spare = B_FALSE;
2461 	*l2cache = B_FALSE;
2462 	if (log != NULL)
2463 		*log = B_FALSE;
2464 	ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log);
2465 	nvlist_free(search);
2466 
2467 	return (ret);
2468 }
2469 
2470 static int
2471 vdev_is_online(nvlist_t *nv)
2472 {
2473 	uint64_t ival;
2474 
2475 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE, &ival) == 0 ||
2476 	    nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED, &ival) == 0 ||
2477 	    nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED, &ival) == 0)
2478 		return (0);
2479 
2480 	return (1);
2481 }
2482 
2483 /*
2484  * Helper function for zpool_get_physpaths().
2485  */
2486 static int
2487 vdev_get_one_physpath(nvlist_t *config, char *physpath, size_t physpath_size,
2488     size_t *bytes_written)
2489 {
2490 	size_t bytes_left, pos, rsz;
2491 	char *tmppath;
2492 	const char *format;
2493 
2494 	if (nvlist_lookup_string(config, ZPOOL_CONFIG_PHYS_PATH,
2495 	    &tmppath) != 0)
2496 		return (EZFS_NODEVICE);
2497 
2498 	pos = *bytes_written;
2499 	bytes_left = physpath_size - pos;
2500 	format = (pos == 0) ? "%s" : " %s";
2501 
2502 	rsz = snprintf(physpath + pos, bytes_left, format, tmppath);
2503 	*bytes_written += rsz;
2504 
2505 	if (rsz >= bytes_left) {
2506 		/* if physpath was not copied properly, clear it */
2507 		if (bytes_left != 0) {
2508 			physpath[pos] = 0;
2509 		}
2510 		return (EZFS_NOSPC);
2511 	}
2512 	return (0);
2513 }
2514 
2515 static int
2516 vdev_get_physpaths(nvlist_t *nv, char *physpath, size_t phypath_size,
2517     size_t *rsz, boolean_t is_spare)
2518 {
2519 	char *type;
2520 	int ret;
2521 
2522 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
2523 		return (EZFS_INVALCONFIG);
2524 
2525 	if (strcmp(type, VDEV_TYPE_DISK) == 0) {
2526 		/*
2527 		 * An active spare device has ZPOOL_CONFIG_IS_SPARE set.
2528 		 * For a spare vdev, we only want to boot from the active
2529 		 * spare device.
2530 		 */
2531 		if (is_spare) {
2532 			uint64_t spare = 0;
2533 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE,
2534 			    &spare);
2535 			if (!spare)
2536 				return (EZFS_INVALCONFIG);
2537 		}
2538 
2539 		if (vdev_is_online(nv)) {
2540 			if ((ret = vdev_get_one_physpath(nv, physpath,
2541 			    phypath_size, rsz)) != 0)
2542 				return (ret);
2543 		}
2544 	} else if (strcmp(type, VDEV_TYPE_MIRROR) == 0 ||
2545 	    strcmp(type, VDEV_TYPE_RAIDZ) == 0 ||
2546 	    strcmp(type, VDEV_TYPE_REPLACING) == 0 ||
2547 	    (is_spare = (strcmp(type, VDEV_TYPE_SPARE) == 0))) {
2548 		nvlist_t **child;
2549 		uint_t count;
2550 		int i, ret;
2551 
2552 		if (nvlist_lookup_nvlist_array(nv,
2553 		    ZPOOL_CONFIG_CHILDREN, &child, &count) != 0)
2554 			return (EZFS_INVALCONFIG);
2555 
2556 		for (i = 0; i < count; i++) {
2557 			ret = vdev_get_physpaths(child[i], physpath,
2558 			    phypath_size, rsz, is_spare);
2559 			if (ret == EZFS_NOSPC)
2560 				return (ret);
2561 		}
2562 	}
2563 
2564 	return (EZFS_POOL_INVALARG);
2565 }
2566 
2567 /*
2568  * Get phys_path for a root pool config.
2569  * Return 0 on success; non-zero on failure.
2570  */
2571 static int
2572 zpool_get_config_physpath(nvlist_t *config, char *physpath, size_t phypath_size)
2573 {
2574 	size_t rsz;
2575 	nvlist_t *vdev_root;
2576 	nvlist_t **child;
2577 	uint_t count;
2578 	char *type;
2579 
2580 	rsz = 0;
2581 
2582 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2583 	    &vdev_root) != 0)
2584 		return (EZFS_INVALCONFIG);
2585 
2586 	if (nvlist_lookup_string(vdev_root, ZPOOL_CONFIG_TYPE, &type) != 0 ||
2587 	    nvlist_lookup_nvlist_array(vdev_root, ZPOOL_CONFIG_CHILDREN,
2588 	    &child, &count) != 0)
2589 		return (EZFS_INVALCONFIG);
2590 
2591 	/*
2592 	 * root pool can only have a single top-level vdev.
2593 	 */
2594 	if (strcmp(type, VDEV_TYPE_ROOT) != 0 || count != 1)
2595 		return (EZFS_POOL_INVALARG);
2596 
2597 	(void) vdev_get_physpaths(child[0], physpath, phypath_size, &rsz,
2598 	    B_FALSE);
2599 
2600 	/* No online devices */
2601 	if (rsz == 0)
2602 		return (EZFS_NODEVICE);
2603 
2604 	return (0);
2605 }
2606 
2607 /*
2608  * Get phys_path for a root pool
2609  * Return 0 on success; non-zero on failure.
2610  */
2611 int
2612 zpool_get_physpath(zpool_handle_t *zhp, char *physpath, size_t phypath_size)
2613 {
2614 	return (zpool_get_config_physpath(zhp->zpool_config, physpath,
2615 	    phypath_size));
2616 }
2617 
2618 /*
2619  * If the device has being dynamically expanded then we need to relabel
2620  * the disk to use the new unallocated space.
2621  */
2622 static int
2623 zpool_relabel_disk(libzfs_handle_t *hdl, const char *name)
2624 {
2625 	char path[MAXPATHLEN];
2626 	char errbuf[1024];
2627 	int fd, error;
2628 	int (*_efi_use_whole_disk)(int);
2629 
2630 	if ((_efi_use_whole_disk = (int (*)(int))dlsym(RTLD_DEFAULT,
2631 	    "efi_use_whole_disk")) == NULL)
2632 		return (-1);
2633 
2634 	(void) snprintf(path, sizeof (path), "%s/%s", ZFS_RDISK_ROOT, name);
2635 
2636 	if ((fd = open(path, O_RDWR | O_NDELAY)) < 0) {
2637 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot "
2638 		    "relabel '%s': unable to open device"), name);
2639 		return (zfs_error(hdl, EZFS_OPENFAILED, errbuf));
2640 	}
2641 
2642 	/*
2643 	 * It's possible that we might encounter an error if the device
2644 	 * does not have any unallocated space left. If so, we simply
2645 	 * ignore that error and continue on.
2646 	 */
2647 	error = _efi_use_whole_disk(fd);
2648 	(void) close(fd);
2649 	if (error && error != VT_ENOSPC) {
2650 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot "
2651 		    "relabel '%s': unable to read disk capacity"), name);
2652 		return (zfs_error(hdl, EZFS_NOCAP, errbuf));
2653 	}
2654 	return (0);
2655 }
2656 
2657 /*
2658  * Bring the specified vdev online.   The 'flags' parameter is a set of the
2659  * ZFS_ONLINE_* flags.
2660  */
2661 int
2662 zpool_vdev_online(zpool_handle_t *zhp, const char *path, int flags,
2663     vdev_state_t *newstate)
2664 {
2665 	zfs_cmd_t zc = { 0 };
2666 	char msg[1024];
2667 	char *pathname;
2668 	nvlist_t *tgt;
2669 	boolean_t avail_spare, l2cache, islog;
2670 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2671 
2672 	if (flags & ZFS_ONLINE_EXPAND) {
2673 		(void) snprintf(msg, sizeof (msg),
2674 		    dgettext(TEXT_DOMAIN, "cannot expand %s"), path);
2675 	} else {
2676 		(void) snprintf(msg, sizeof (msg),
2677 		    dgettext(TEXT_DOMAIN, "cannot online %s"), path);
2678 	}
2679 
2680 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2681 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
2682 	    &islog)) == NULL)
2683 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
2684 
2685 	verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2686 
2687 	if (avail_spare)
2688 		return (zfs_error(hdl, EZFS_ISSPARE, msg));
2689 
2690 	if ((flags & ZFS_ONLINE_EXPAND ||
2691 	    zpool_get_prop_int(zhp, ZPOOL_PROP_AUTOEXPAND, NULL)) &&
2692 	    nvlist_lookup_string(tgt, ZPOOL_CONFIG_PATH, &pathname) == 0) {
2693 		uint64_t wholedisk = 0;
2694 
2695 		(void) nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_WHOLE_DISK,
2696 		    &wholedisk);
2697 
2698 		/*
2699 		 * XXX - L2ARC 1.0 devices can't support expansion.
2700 		 */
2701 		if (l2cache) {
2702 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2703 			    "cannot expand cache devices"));
2704 			return (zfs_error(hdl, EZFS_VDEVNOTSUP, msg));
2705 		}
2706 
2707 		if (wholedisk) {
2708 			pathname += strlen(ZFS_DISK_ROOT) + 1;
2709 			(void) zpool_relabel_disk(hdl, pathname);
2710 		}
2711 	}
2712 
2713 	zc.zc_cookie = VDEV_STATE_ONLINE;
2714 	zc.zc_obj = flags;
2715 
2716 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) != 0) {
2717 		if (errno == EINVAL) {
2718 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "was split "
2719 			    "from this pool into a new one.  Use '%s' "
2720 			    "instead"), "zpool detach");
2721 			return (zfs_error(hdl, EZFS_POSTSPLIT_ONLINE, msg));
2722 		}
2723 		return (zpool_standard_error(hdl, errno, msg));
2724 	}
2725 
2726 	*newstate = zc.zc_cookie;
2727 	return (0);
2728 }
2729 
2730 /*
2731  * Take the specified vdev offline
2732  */
2733 int
2734 zpool_vdev_offline(zpool_handle_t *zhp, const char *path, boolean_t istmp)
2735 {
2736 	zfs_cmd_t zc = { 0 };
2737 	char msg[1024];
2738 	nvlist_t *tgt;
2739 	boolean_t avail_spare, l2cache;
2740 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2741 
2742 	(void) snprintf(msg, sizeof (msg),
2743 	    dgettext(TEXT_DOMAIN, "cannot offline %s"), path);
2744 
2745 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2746 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
2747 	    NULL)) == NULL)
2748 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
2749 
2750 	verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2751 
2752 	if (avail_spare)
2753 		return (zfs_error(hdl, EZFS_ISSPARE, msg));
2754 
2755 	zc.zc_cookie = VDEV_STATE_OFFLINE;
2756 	zc.zc_obj = istmp ? ZFS_OFFLINE_TEMPORARY : 0;
2757 
2758 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2759 		return (0);
2760 
2761 	switch (errno) {
2762 	case EBUSY:
2763 
2764 		/*
2765 		 * There are no other replicas of this device.
2766 		 */
2767 		return (zfs_error(hdl, EZFS_NOREPLICAS, msg));
2768 
2769 	case EEXIST:
2770 		/*
2771 		 * The log device has unplayed logs
2772 		 */
2773 		return (zfs_error(hdl, EZFS_UNPLAYED_LOGS, msg));
2774 
2775 	default:
2776 		return (zpool_standard_error(hdl, errno, msg));
2777 	}
2778 }
2779 
2780 /*
2781  * Mark the given vdev faulted.
2782  */
2783 int
2784 zpool_vdev_fault(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux)
2785 {
2786 	zfs_cmd_t zc = { 0 };
2787 	char msg[1024];
2788 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2789 
2790 	(void) snprintf(msg, sizeof (msg),
2791 	    dgettext(TEXT_DOMAIN, "cannot fault %llu"), guid);
2792 
2793 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2794 	zc.zc_guid = guid;
2795 	zc.zc_cookie = VDEV_STATE_FAULTED;
2796 	zc.zc_obj = aux;
2797 
2798 	if (ioctl(hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2799 		return (0);
2800 
2801 	switch (errno) {
2802 	case EBUSY:
2803 
2804 		/*
2805 		 * There are no other replicas of this device.
2806 		 */
2807 		return (zfs_error(hdl, EZFS_NOREPLICAS, msg));
2808 
2809 	default:
2810 		return (zpool_standard_error(hdl, errno, msg));
2811 	}
2812 
2813 }
2814 
2815 /*
2816  * Mark the given vdev degraded.
2817  */
2818 int
2819 zpool_vdev_degrade(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux)
2820 {
2821 	zfs_cmd_t zc = { 0 };
2822 	char msg[1024];
2823 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2824 
2825 	(void) snprintf(msg, sizeof (msg),
2826 	    dgettext(TEXT_DOMAIN, "cannot degrade %llu"), guid);
2827 
2828 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2829 	zc.zc_guid = guid;
2830 	zc.zc_cookie = VDEV_STATE_DEGRADED;
2831 	zc.zc_obj = aux;
2832 
2833 	if (ioctl(hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2834 		return (0);
2835 
2836 	return (zpool_standard_error(hdl, errno, msg));
2837 }
2838 
2839 /*
2840  * Returns TRUE if the given nvlist is a vdev that was originally swapped in as
2841  * a hot spare.
2842  */
2843 static boolean_t
2844 is_replacing_spare(nvlist_t *search, nvlist_t *tgt, int which)
2845 {
2846 	nvlist_t **child;
2847 	uint_t c, children;
2848 	char *type;
2849 
2850 	if (nvlist_lookup_nvlist_array(search, ZPOOL_CONFIG_CHILDREN, &child,
2851 	    &children) == 0) {
2852 		verify(nvlist_lookup_string(search, ZPOOL_CONFIG_TYPE,
2853 		    &type) == 0);
2854 
2855 		if (strcmp(type, VDEV_TYPE_SPARE) == 0 &&
2856 		    children == 2 && child[which] == tgt)
2857 			return (B_TRUE);
2858 
2859 		for (c = 0; c < children; c++)
2860 			if (is_replacing_spare(child[c], tgt, which))
2861 				return (B_TRUE);
2862 	}
2863 
2864 	return (B_FALSE);
2865 }
2866 
2867 /*
2868  * Attach new_disk (fully described by nvroot) to old_disk.
2869  * If 'replacing' is specified, the new disk will replace the old one.
2870  */
2871 int
2872 zpool_vdev_attach(zpool_handle_t *zhp,
2873     const char *old_disk, const char *new_disk, nvlist_t *nvroot, int replacing)
2874 {
2875 	zfs_cmd_t zc = { 0 };
2876 	char msg[1024];
2877 	int ret;
2878 	nvlist_t *tgt;
2879 	boolean_t avail_spare, l2cache, islog;
2880 	uint64_t val;
2881 	char *newname;
2882 	nvlist_t **child;
2883 	uint_t children;
2884 	nvlist_t *config_root;
2885 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2886 	boolean_t rootpool = zpool_is_bootable(zhp);
2887 
2888 	if (replacing)
2889 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2890 		    "cannot replace %s with %s"), old_disk, new_disk);
2891 	else
2892 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2893 		    "cannot attach %s to %s"), new_disk, old_disk);
2894 
2895 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2896 	if ((tgt = zpool_find_vdev(zhp, old_disk, &avail_spare, &l2cache,
2897 	    &islog)) == NULL)
2898 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
2899 
2900 	if (avail_spare)
2901 		return (zfs_error(hdl, EZFS_ISSPARE, msg));
2902 
2903 	if (l2cache)
2904 		return (zfs_error(hdl, EZFS_ISL2CACHE, msg));
2905 
2906 	verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2907 	zc.zc_cookie = replacing;
2908 
2909 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
2910 	    &child, &children) != 0 || children != 1) {
2911 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2912 		    "new device must be a single disk"));
2913 		return (zfs_error(hdl, EZFS_INVALCONFIG, msg));
2914 	}
2915 
2916 	verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
2917 	    ZPOOL_CONFIG_VDEV_TREE, &config_root) == 0);
2918 
2919 	if ((newname = zpool_vdev_name(NULL, NULL, child[0], 0)) == NULL)
2920 		return (-1);
2921 
2922 	/*
2923 	 * If the target is a hot spare that has been swapped in, we can only
2924 	 * replace it with another hot spare.
2925 	 */
2926 	if (replacing &&
2927 	    nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_IS_SPARE, &val) == 0 &&
2928 	    (zpool_find_vdev(zhp, newname, &avail_spare, &l2cache,
2929 	    NULL) == NULL || !avail_spare) &&
2930 	    is_replacing_spare(config_root, tgt, 1)) {
2931 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2932 		    "can only be replaced by another hot spare"));
2933 		free(newname);
2934 		return (zfs_error(hdl, EZFS_BADTARGET, msg));
2935 	}
2936 
2937 	free(newname);
2938 
2939 	if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
2940 		return (-1);
2941 
2942 	ret = zfs_ioctl(hdl, ZFS_IOC_VDEV_ATTACH, &zc);
2943 
2944 	zcmd_free_nvlists(&zc);
2945 
2946 	if (ret == 0) {
2947 		if (rootpool) {
2948 			/*
2949 			 * XXX need a better way to prevent user from
2950 			 * booting up a half-baked vdev.
2951 			 */
2952 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Make "
2953 			    "sure to wait until resilver is done "
2954 			    "before rebooting.\n"));
2955 		}
2956 		return (0);
2957 	}
2958 
2959 	switch (errno) {
2960 	case ENOTSUP:
2961 		/*
2962 		 * Can't attach to or replace this type of vdev.
2963 		 */
2964 		if (replacing) {
2965 			uint64_t version = zpool_get_prop_int(zhp,
2966 			    ZPOOL_PROP_VERSION, NULL);
2967 
2968 			if (islog)
2969 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2970 				    "cannot replace a log with a spare"));
2971 			else if (version >= SPA_VERSION_MULTI_REPLACE)
2972 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2973 				    "already in replacing/spare config; wait "
2974 				    "for completion or use 'zpool detach'"));
2975 			else
2976 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2977 				    "cannot replace a replacing device"));
2978 		} else {
2979 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2980 			    "can only attach to mirrors and top-level "
2981 			    "disks"));
2982 		}
2983 		(void) zfs_error(hdl, EZFS_BADTARGET, msg);
2984 		break;
2985 
2986 	case EINVAL:
2987 		/*
2988 		 * The new device must be a single disk.
2989 		 */
2990 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2991 		    "new device must be a single disk"));
2992 		(void) zfs_error(hdl, EZFS_INVALCONFIG, msg);
2993 		break;
2994 
2995 	case EBUSY:
2996 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "%s is busy, "
2997 		    "or device removal is in progress"),
2998 		    new_disk);
2999 		(void) zfs_error(hdl, EZFS_BADDEV, msg);
3000 		break;
3001 
3002 	case EOVERFLOW:
3003 		/*
3004 		 * The new device is too small.
3005 		 */
3006 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3007 		    "device is too small"));
3008 		(void) zfs_error(hdl, EZFS_BADDEV, msg);
3009 		break;
3010 
3011 	case EDOM:
3012 		/*
3013 		 * The new device has a different alignment requirement.
3014 		 */
3015 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3016 		    "devices have different sector alignment"));
3017 		(void) zfs_error(hdl, EZFS_BADDEV, msg);
3018 		break;
3019 
3020 	case ENAMETOOLONG:
3021 		/*
3022 		 * The resulting top-level vdev spec won't fit in the label.
3023 		 */
3024 		(void) zfs_error(hdl, EZFS_DEVOVERFLOW, msg);
3025 		break;
3026 
3027 	default:
3028 		(void) zpool_standard_error(hdl, errno, msg);
3029 	}
3030 
3031 	return (-1);
3032 }
3033 
3034 /*
3035  * Detach the specified device.
3036  */
3037 int
3038 zpool_vdev_detach(zpool_handle_t *zhp, const char *path)
3039 {
3040 	zfs_cmd_t zc = { 0 };
3041 	char msg[1024];
3042 	nvlist_t *tgt;
3043 	boolean_t avail_spare, l2cache;
3044 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3045 
3046 	(void) snprintf(msg, sizeof (msg),
3047 	    dgettext(TEXT_DOMAIN, "cannot detach %s"), path);
3048 
3049 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3050 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3051 	    NULL)) == NULL)
3052 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
3053 
3054 	if (avail_spare)
3055 		return (zfs_error(hdl, EZFS_ISSPARE, msg));
3056 
3057 	if (l2cache)
3058 		return (zfs_error(hdl, EZFS_ISL2CACHE, msg));
3059 
3060 	verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
3061 
3062 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_DETACH, &zc) == 0)
3063 		return (0);
3064 
3065 	switch (errno) {
3066 
3067 	case ENOTSUP:
3068 		/*
3069 		 * Can't detach from this type of vdev.
3070 		 */
3071 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "only "
3072 		    "applicable to mirror and replacing vdevs"));
3073 		(void) zfs_error(hdl, EZFS_BADTARGET, msg);
3074 		break;
3075 
3076 	case EBUSY:
3077 		/*
3078 		 * There are no other replicas of this device.
3079 		 */
3080 		(void) zfs_error(hdl, EZFS_NOREPLICAS, msg);
3081 		break;
3082 
3083 	default:
3084 		(void) zpool_standard_error(hdl, errno, msg);
3085 	}
3086 
3087 	return (-1);
3088 }
3089 
3090 /*
3091  * Find a mirror vdev in the source nvlist.
3092  *
3093  * The mchild array contains a list of disks in one of the top-level mirrors
3094  * of the source pool.  The schild array contains a list of disks that the
3095  * user specified on the command line.  We loop over the mchild array to
3096  * see if any entry in the schild array matches.
3097  *
3098  * If a disk in the mchild array is found in the schild array, we return
3099  * the index of that entry.  Otherwise we return -1.
3100  */
3101 static int
3102 find_vdev_entry(zpool_handle_t *zhp, nvlist_t **mchild, uint_t mchildren,
3103     nvlist_t **schild, uint_t schildren)
3104 {
3105 	uint_t mc;
3106 
3107 	for (mc = 0; mc < mchildren; mc++) {
3108 		uint_t sc;
3109 		char *mpath = zpool_vdev_name(zhp->zpool_hdl, zhp,
3110 		    mchild[mc], 0);
3111 
3112 		for (sc = 0; sc < schildren; sc++) {
3113 			char *spath = zpool_vdev_name(zhp->zpool_hdl, zhp,
3114 			    schild[sc], 0);
3115 			boolean_t result = (strcmp(mpath, spath) == 0);
3116 
3117 			free(spath);
3118 			if (result) {
3119 				free(mpath);
3120 				return (mc);
3121 			}
3122 		}
3123 
3124 		free(mpath);
3125 	}
3126 
3127 	return (-1);
3128 }
3129 
3130 /*
3131  * Split a mirror pool.  If newroot points to null, then a new nvlist
3132  * is generated and it is the responsibility of the caller to free it.
3133  */
3134 int
3135 zpool_vdev_split(zpool_handle_t *zhp, char *newname, nvlist_t **newroot,
3136     nvlist_t *props, splitflags_t flags)
3137 {
3138 	zfs_cmd_t zc = { 0 };
3139 	char msg[1024];
3140 	nvlist_t *tree, *config, **child, **newchild, *newconfig = NULL;
3141 	nvlist_t **varray = NULL, *zc_props = NULL;
3142 	uint_t c, children, newchildren, lastlog = 0, vcount, found = 0;
3143 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3144 	uint64_t vers;
3145 	boolean_t freelist = B_FALSE, memory_err = B_TRUE;
3146 	int retval = 0;
3147 
3148 	(void) snprintf(msg, sizeof (msg),
3149 	    dgettext(TEXT_DOMAIN, "Unable to split %s"), zhp->zpool_name);
3150 
3151 	if (!zpool_name_valid(hdl, B_FALSE, newname))
3152 		return (zfs_error(hdl, EZFS_INVALIDNAME, msg));
3153 
3154 	if ((config = zpool_get_config(zhp, NULL)) == NULL) {
3155 		(void) fprintf(stderr, gettext("Internal error: unable to "
3156 		    "retrieve pool configuration\n"));
3157 		return (-1);
3158 	}
3159 
3160 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &tree)
3161 	    == 0);
3162 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION, &vers) == 0);
3163 
3164 	if (props) {
3165 		prop_flags_t flags = { .create = B_FALSE, .import = B_TRUE };
3166 		if ((zc_props = zpool_valid_proplist(hdl, zhp->zpool_name,
3167 		    props, vers, flags, msg)) == NULL)
3168 			return (-1);
3169 	}
3170 
3171 	if (nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN, &child,
3172 	    &children) != 0) {
3173 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3174 		    "Source pool is missing vdev tree"));
3175 		nvlist_free(zc_props);
3176 		return (-1);
3177 	}
3178 
3179 	varray = zfs_alloc(hdl, children * sizeof (nvlist_t *));
3180 	vcount = 0;
3181 
3182 	if (*newroot == NULL ||
3183 	    nvlist_lookup_nvlist_array(*newroot, ZPOOL_CONFIG_CHILDREN,
3184 	    &newchild, &newchildren) != 0)
3185 		newchildren = 0;
3186 
3187 	for (c = 0; c < children; c++) {
3188 		uint64_t is_log = B_FALSE, is_hole = B_FALSE;
3189 		char *type;
3190 		nvlist_t **mchild, *vdev;
3191 		uint_t mchildren;
3192 		int entry;
3193 
3194 		/*
3195 		 * Unlike cache & spares, slogs are stored in the
3196 		 * ZPOOL_CONFIG_CHILDREN array.  We filter them out here.
3197 		 */
3198 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
3199 		    &is_log);
3200 		(void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
3201 		    &is_hole);
3202 		if (is_log || is_hole) {
3203 			/*
3204 			 * Create a hole vdev and put it in the config.
3205 			 */
3206 			if (nvlist_alloc(&vdev, NV_UNIQUE_NAME, 0) != 0)
3207 				goto out;
3208 			if (nvlist_add_string(vdev, ZPOOL_CONFIG_TYPE,
3209 			    VDEV_TYPE_HOLE) != 0)
3210 				goto out;
3211 			if (nvlist_add_uint64(vdev, ZPOOL_CONFIG_IS_HOLE,
3212 			    1) != 0)
3213 				goto out;
3214 			if (lastlog == 0)
3215 				lastlog = vcount;
3216 			varray[vcount++] = vdev;
3217 			continue;
3218 		}
3219 		lastlog = 0;
3220 		verify(nvlist_lookup_string(child[c], ZPOOL_CONFIG_TYPE, &type)
3221 		    == 0);
3222 		if (strcmp(type, VDEV_TYPE_MIRROR) != 0) {
3223 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3224 			    "Source pool must be composed only of mirrors\n"));
3225 			retval = zfs_error(hdl, EZFS_INVALCONFIG, msg);
3226 			goto out;
3227 		}
3228 
3229 		verify(nvlist_lookup_nvlist_array(child[c],
3230 		    ZPOOL_CONFIG_CHILDREN, &mchild, &mchildren) == 0);
3231 
3232 		/* find or add an entry for this top-level vdev */
3233 		if (newchildren > 0 &&
3234 		    (entry = find_vdev_entry(zhp, mchild, mchildren,
3235 		    newchild, newchildren)) >= 0) {
3236 			/* We found a disk that the user specified. */
3237 			vdev = mchild[entry];
3238 			++found;
3239 		} else {
3240 			/* User didn't specify a disk for this vdev. */
3241 			vdev = mchild[mchildren - 1];
3242 		}
3243 
3244 		if (nvlist_dup(vdev, &varray[vcount++], 0) != 0)
3245 			goto out;
3246 	}
3247 
3248 	/* did we find every disk the user specified? */
3249 	if (found != newchildren) {
3250 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "Device list must "
3251 		    "include at most one disk from each mirror"));
3252 		retval = zfs_error(hdl, EZFS_INVALCONFIG, msg);
3253 		goto out;
3254 	}
3255 
3256 	/* Prepare the nvlist for populating. */
3257 	if (*newroot == NULL) {
3258 		if (nvlist_alloc(newroot, NV_UNIQUE_NAME, 0) != 0)
3259 			goto out;
3260 		freelist = B_TRUE;
3261 		if (nvlist_add_string(*newroot, ZPOOL_CONFIG_TYPE,
3262 		    VDEV_TYPE_ROOT) != 0)
3263 			goto out;
3264 	} else {
3265 		verify(nvlist_remove_all(*newroot, ZPOOL_CONFIG_CHILDREN) == 0);
3266 	}
3267 
3268 	/* Add all the children we found */
3269 	if (nvlist_add_nvlist_array(*newroot, ZPOOL_CONFIG_CHILDREN, varray,
3270 	    lastlog == 0 ? vcount : lastlog) != 0)
3271 		goto out;
3272 
3273 	/*
3274 	 * If we're just doing a dry run, exit now with success.
3275 	 */
3276 	if (flags.dryrun) {
3277 		memory_err = B_FALSE;
3278 		freelist = B_FALSE;
3279 		goto out;
3280 	}
3281 
3282 	/* now build up the config list & call the ioctl */
3283 	if (nvlist_alloc(&newconfig, NV_UNIQUE_NAME, 0) != 0)
3284 		goto out;
3285 
3286 	if (nvlist_add_nvlist(newconfig,
3287 	    ZPOOL_CONFIG_VDEV_TREE, *newroot) != 0 ||
3288 	    nvlist_add_string(newconfig,
3289 	    ZPOOL_CONFIG_POOL_NAME, newname) != 0 ||
3290 	    nvlist_add_uint64(newconfig, ZPOOL_CONFIG_VERSION, vers) != 0)
3291 		goto out;
3292 
3293 	/*
3294 	 * The new pool is automatically part of the namespace unless we
3295 	 * explicitly export it.
3296 	 */
3297 	if (!flags.import)
3298 		zc.zc_cookie = ZPOOL_EXPORT_AFTER_SPLIT;
3299 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3300 	(void) strlcpy(zc.zc_string, newname, sizeof (zc.zc_string));
3301 	if (zcmd_write_conf_nvlist(hdl, &zc, newconfig) != 0)
3302 		goto out;
3303 	if (zc_props != NULL && zcmd_write_src_nvlist(hdl, &zc, zc_props) != 0)
3304 		goto out;
3305 
3306 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SPLIT, &zc) != 0) {
3307 		retval = zpool_standard_error(hdl, errno, msg);
3308 		goto out;
3309 	}
3310 
3311 	freelist = B_FALSE;
3312 	memory_err = B_FALSE;
3313 
3314 out:
3315 	if (varray != NULL) {
3316 		int v;
3317 
3318 		for (v = 0; v < vcount; v++)
3319 			nvlist_free(varray[v]);
3320 		free(varray);
3321 	}
3322 	zcmd_free_nvlists(&zc);
3323 	nvlist_free(zc_props);
3324 	nvlist_free(newconfig);
3325 	if (freelist) {
3326 		nvlist_free(*newroot);
3327 		*newroot = NULL;
3328 	}
3329 
3330 	if (retval != 0)
3331 		return (retval);
3332 
3333 	if (memory_err)
3334 		return (no_memory(hdl));
3335 
3336 	return (0);
3337 }
3338 
3339 /*
3340  * Remove the given device.
3341  */
3342 int
3343 zpool_vdev_remove(zpool_handle_t *zhp, const char *path)
3344 {
3345 	zfs_cmd_t zc = { 0 };
3346 	char msg[1024];
3347 	nvlist_t *tgt;
3348 	boolean_t avail_spare, l2cache, islog;
3349 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3350 	uint64_t version;
3351 
3352 	(void) snprintf(msg, sizeof (msg),
3353 	    dgettext(TEXT_DOMAIN, "cannot remove %s"), path);
3354 
3355 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3356 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3357 	    &islog)) == NULL)
3358 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
3359 
3360 	version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
3361 	if (islog && version < SPA_VERSION_HOLES) {
3362 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3363 		    "pool must be upgraded to support log removal"));
3364 		return (zfs_error(hdl, EZFS_BADVERSION, msg));
3365 	}
3366 
3367 	if (!islog && !avail_spare && !l2cache && zpool_is_bootable(zhp)) {
3368 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3369 		    "root pool can not have removed devices, "
3370 		    "because GRUB does not understand them"));
3371 		return (zfs_error(hdl, EINVAL, msg));
3372 	}
3373 
3374 	zc.zc_guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
3375 
3376 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_REMOVE, &zc) == 0)
3377 		return (0);
3378 
3379 	switch (errno) {
3380 
3381 	case EINVAL:
3382 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3383 		    "invalid config; all top-level vdevs must "
3384 		    "have the same sector size and not be raidz."));
3385 		(void) zfs_error(hdl, EZFS_INVALCONFIG, msg);
3386 		break;
3387 
3388 	case EBUSY:
3389 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3390 		    "Pool busy; removal may already be in progress"));
3391 		(void) zfs_error(hdl, EZFS_BUSY, msg);
3392 		break;
3393 
3394 	default:
3395 		(void) zpool_standard_error(hdl, errno, msg);
3396 	}
3397 	return (-1);
3398 }
3399 
3400 int
3401 zpool_vdev_remove_cancel(zpool_handle_t *zhp)
3402 {
3403 	zfs_cmd_t zc = { 0 };
3404 	char msg[1024];
3405 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3406 
3407 	(void) snprintf(msg, sizeof (msg),
3408 	    dgettext(TEXT_DOMAIN, "cannot cancel removal"));
3409 
3410 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3411 	zc.zc_cookie = 1;
3412 
3413 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_REMOVE, &zc) == 0)
3414 		return (0);
3415 
3416 	return (zpool_standard_error(hdl, errno, msg));
3417 }
3418 
3419 int
3420 zpool_vdev_indirect_size(zpool_handle_t *zhp, const char *path,
3421     uint64_t *sizep)
3422 {
3423 	char msg[1024];
3424 	nvlist_t *tgt;
3425 	boolean_t avail_spare, l2cache, islog;
3426 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3427 
3428 	(void) snprintf(msg, sizeof (msg),
3429 	    dgettext(TEXT_DOMAIN, "cannot determine indirect size of %s"),
3430 	    path);
3431 
3432 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3433 	    &islog)) == NULL)
3434 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
3435 
3436 	if (avail_spare || l2cache || islog) {
3437 		*sizep = 0;
3438 		return (0);
3439 	}
3440 
3441 	if (nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_INDIRECT_SIZE, sizep) != 0) {
3442 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3443 		    "indirect size not available"));
3444 		return (zfs_error(hdl, EINVAL, msg));
3445 	}
3446 	return (0);
3447 }
3448 
3449 /*
3450  * Clear the errors for the pool, or the particular device if specified.
3451  */
3452 int
3453 zpool_clear(zpool_handle_t *zhp, const char *path, nvlist_t *rewindnvl)
3454 {
3455 	zfs_cmd_t zc = { 0 };
3456 	char msg[1024];
3457 	nvlist_t *tgt;
3458 	zpool_load_policy_t policy;
3459 	boolean_t avail_spare, l2cache;
3460 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3461 	nvlist_t *nvi = NULL;
3462 	int error;
3463 
3464 	if (path)
3465 		(void) snprintf(msg, sizeof (msg),
3466 		    dgettext(TEXT_DOMAIN, "cannot clear errors for %s"),
3467 		    path);
3468 	else
3469 		(void) snprintf(msg, sizeof (msg),
3470 		    dgettext(TEXT_DOMAIN, "cannot clear errors for %s"),
3471 		    zhp->zpool_name);
3472 
3473 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3474 	if (path) {
3475 		if ((tgt = zpool_find_vdev(zhp, path, &avail_spare,
3476 		    &l2cache, NULL)) == NULL)
3477 			return (zfs_error(hdl, EZFS_NODEVICE, msg));
3478 
3479 		/*
3480 		 * Don't allow error clearing for hot spares.  Do allow
3481 		 * error clearing for l2cache devices.
3482 		 */
3483 		if (avail_spare)
3484 			return (zfs_error(hdl, EZFS_ISSPARE, msg));
3485 
3486 		verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID,
3487 		    &zc.zc_guid) == 0);
3488 	}
3489 
3490 	zpool_get_load_policy(rewindnvl, &policy);
3491 	zc.zc_cookie = policy.zlp_rewind;
3492 
3493 	if (zcmd_alloc_dst_nvlist(hdl, &zc, zhp->zpool_config_size * 2) != 0)
3494 		return (-1);
3495 
3496 	if (zcmd_write_src_nvlist(hdl, &zc, rewindnvl) != 0)
3497 		return (-1);
3498 
3499 	while ((error = zfs_ioctl(hdl, ZFS_IOC_CLEAR, &zc)) != 0 &&
3500 	    errno == ENOMEM) {
3501 		if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
3502 			zcmd_free_nvlists(&zc);
3503 			return (-1);
3504 		}
3505 	}
3506 
3507 	if (!error || ((policy.zlp_rewind & ZPOOL_TRY_REWIND) &&
3508 	    errno != EPERM && errno != EACCES)) {
3509 		if (policy.zlp_rewind &
3510 		    (ZPOOL_DO_REWIND | ZPOOL_TRY_REWIND)) {
3511 			(void) zcmd_read_dst_nvlist(hdl, &zc, &nvi);
3512 			zpool_rewind_exclaim(hdl, zc.zc_name,
3513 			    ((policy.zlp_rewind & ZPOOL_TRY_REWIND) != 0),
3514 			    nvi);
3515 			nvlist_free(nvi);
3516 		}
3517 		zcmd_free_nvlists(&zc);
3518 		return (0);
3519 	}
3520 
3521 	zcmd_free_nvlists(&zc);
3522 	return (zpool_standard_error(hdl, errno, msg));
3523 }
3524 
3525 /*
3526  * Similar to zpool_clear(), but takes a GUID (used by fmd).
3527  */
3528 int
3529 zpool_vdev_clear(zpool_handle_t *zhp, uint64_t guid)
3530 {
3531 	zfs_cmd_t zc = { 0 };
3532 	char msg[1024];
3533 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3534 
3535 	(void) snprintf(msg, sizeof (msg),
3536 	    dgettext(TEXT_DOMAIN, "cannot clear errors for %llx"),
3537 	    guid);
3538 
3539 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3540 	zc.zc_guid = guid;
3541 	zc.zc_cookie = ZPOOL_NO_REWIND;
3542 
3543 	if (ioctl(hdl->libzfs_fd, ZFS_IOC_CLEAR, &zc) == 0)
3544 		return (0);
3545 
3546 	return (zpool_standard_error(hdl, errno, msg));
3547 }
3548 
3549 /*
3550  * Change the GUID for a pool.
3551  */
3552 int
3553 zpool_reguid(zpool_handle_t *zhp)
3554 {
3555 	char msg[1024];
3556 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3557 	zfs_cmd_t zc = { 0 };
3558 
3559 	(void) snprintf(msg, sizeof (msg),
3560 	    dgettext(TEXT_DOMAIN, "cannot reguid '%s'"), zhp->zpool_name);
3561 
3562 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3563 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_REGUID, &zc) == 0)
3564 		return (0);
3565 
3566 	return (zpool_standard_error(hdl, errno, msg));
3567 }
3568 
3569 /*
3570  * Reopen the pool.
3571  */
3572 int
3573 zpool_reopen(zpool_handle_t *zhp)
3574 {
3575 	zfs_cmd_t zc = { 0 };
3576 	char msg[1024];
3577 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3578 
3579 	(void) snprintf(msg, sizeof (msg),
3580 	    dgettext(TEXT_DOMAIN, "cannot reopen '%s'"),
3581 	    zhp->zpool_name);
3582 
3583 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3584 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_REOPEN, &zc) == 0)
3585 		return (0);
3586 	return (zpool_standard_error(hdl, errno, msg));
3587 }
3588 
3589 /* call into libzfs_core to execute the sync IOCTL per pool */
3590 int
3591 zpool_sync_one(zpool_handle_t *zhp, void *data)
3592 {
3593 	int ret;
3594 	libzfs_handle_t *hdl = zpool_get_handle(zhp);
3595 	const char *pool_name = zpool_get_name(zhp);
3596 	boolean_t *force = data;
3597 	nvlist_t *innvl = fnvlist_alloc();
3598 
3599 	fnvlist_add_boolean_value(innvl, "force", *force);
3600 	if ((ret = lzc_sync(pool_name, innvl, NULL)) != 0) {
3601 		nvlist_free(innvl);
3602 		return (zpool_standard_error_fmt(hdl, ret,
3603 		    dgettext(TEXT_DOMAIN, "sync '%s' failed"), pool_name));
3604 	}
3605 	nvlist_free(innvl);
3606 
3607 	return (0);
3608 }
3609 
3610 /*
3611  * Convert from a devid string to a path.
3612  */
3613 static char *
3614 devid_to_path(char *devid_str)
3615 {
3616 	ddi_devid_t devid;
3617 	char *minor;
3618 	char *path;
3619 	devid_nmlist_t *list = NULL;
3620 	int ret;
3621 
3622 	if (devid_str_decode(devid_str, &devid, &minor) != 0)
3623 		return (NULL);
3624 
3625 	ret = devid_deviceid_to_nmlist("/dev", devid, minor, &list);
3626 
3627 	devid_str_free(minor);
3628 	devid_free(devid);
3629 
3630 	if (ret != 0)
3631 		return (NULL);
3632 
3633 	/*
3634 	 * In a case the strdup() fails, we will just return NULL below.
3635 	 */
3636 	path = strdup(list[0].devname);
3637 
3638 	devid_free_nmlist(list);
3639 
3640 	return (path);
3641 }
3642 
3643 /*
3644  * Convert from a path to a devid string.
3645  */
3646 static char *
3647 path_to_devid(const char *path)
3648 {
3649 	int fd;
3650 	ddi_devid_t devid;
3651 	char *minor, *ret;
3652 
3653 	if ((fd = open(path, O_RDONLY)) < 0)
3654 		return (NULL);
3655 
3656 	minor = NULL;
3657 	ret = NULL;
3658 	if (devid_get(fd, &devid) == 0) {
3659 		if (devid_get_minor_name(fd, &minor) == 0)
3660 			ret = devid_str_encode(devid, minor);
3661 		if (minor != NULL)
3662 			devid_str_free(minor);
3663 		devid_free(devid);
3664 	}
3665 	(void) close(fd);
3666 
3667 	return (ret);
3668 }
3669 
3670 /*
3671  * Issue the necessary ioctl() to update the stored path value for the vdev.  We
3672  * ignore any failure here, since a common case is for an unprivileged user to
3673  * type 'zpool status', and we'll display the correct information anyway.
3674  */
3675 static void
3676 set_path(zpool_handle_t *zhp, nvlist_t *nv, const char *path)
3677 {
3678 	zfs_cmd_t zc = { 0 };
3679 
3680 	(void) strncpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3681 	(void) strncpy(zc.zc_value, path, sizeof (zc.zc_value));
3682 	verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
3683 	    &zc.zc_guid) == 0);
3684 
3685 	(void) ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_VDEV_SETPATH, &zc);
3686 }
3687 
3688 /*
3689  * Given a vdev, return the name to display in iostat.  If the vdev has a path,
3690  * we use that, stripping off any leading "/dev/dsk/"; if not, we use the type.
3691  * We also check if this is a whole disk, in which case we strip off the
3692  * trailing 's0' slice name.
3693  *
3694  * This routine is also responsible for identifying when disks have been
3695  * reconfigured in a new location.  The kernel will have opened the device by
3696  * devid, but the path will still refer to the old location.  To catch this, we
3697  * first do a path -> devid translation (which is fast for the common case).  If
3698  * the devid matches, we're done.  If not, we do a reverse devid -> path
3699  * translation and issue the appropriate ioctl() to update the path of the vdev.
3700  * If 'zhp' is NULL, then this is an exported pool, and we don't need to do any
3701  * of these checks.
3702  */
3703 char *
3704 zpool_vdev_name(libzfs_handle_t *hdl, zpool_handle_t *zhp, nvlist_t *nv,
3705     int name_flags)
3706 {
3707 	char *path, *devid, *env;
3708 	uint64_t value;
3709 	char buf[64];
3710 	vdev_stat_t *vs;
3711 	uint_t vsc;
3712 
3713 	env = getenv("ZPOOL_VDEV_NAME_PATH");
3714 	if (env && (strtoul(env, NULL, 0) > 0 ||
3715 	    !strncasecmp(env, "YES", 3) || !strncasecmp(env, "ON", 2)))
3716 		name_flags |= VDEV_NAME_PATH;
3717 
3718 	env = getenv("ZPOOL_VDEV_NAME_GUID");
3719 	if (env && (strtoul(env, NULL, 0) > 0 ||
3720 	    !strncasecmp(env, "YES", 3) || !strncasecmp(env, "ON", 2)))
3721 		name_flags |= VDEV_NAME_GUID;
3722 
3723 	env = getenv("ZPOOL_VDEV_NAME_FOLLOW_LINKS");
3724 	if (env && (strtoul(env, NULL, 0) > 0 ||
3725 	    !strncasecmp(env, "YES", 3) || !strncasecmp(env, "ON", 2)))
3726 		name_flags |= VDEV_NAME_FOLLOW_LINKS;
3727 
3728 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT, &value) == 0 ||
3729 	    name_flags & VDEV_NAME_GUID) {
3730 		nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &value);
3731 		(void) snprintf(buf, sizeof (buf), "%llu", (u_longlong_t)value);
3732 		path = buf;
3733 	} else if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
3734 
3735 		/*
3736 		 * If the device is dead (faulted, offline, etc) then don't
3737 		 * bother opening it.  Otherwise we may be forcing the user to
3738 		 * open a misbehaving device, which can have undesirable
3739 		 * effects.
3740 		 */
3741 		if ((nvlist_lookup_uint64_array(nv, ZPOOL_CONFIG_VDEV_STATS,
3742 		    (uint64_t **)&vs, &vsc) != 0 ||
3743 		    vs->vs_state >= VDEV_STATE_DEGRADED) &&
3744 		    zhp != NULL &&
3745 		    nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &devid) == 0) {
3746 			/*
3747 			 * Determine if the current path is correct.
3748 			 */
3749 			char *newdevid = path_to_devid(path);
3750 
3751 			if (newdevid == NULL ||
3752 			    strcmp(devid, newdevid) != 0) {
3753 				char *newpath;
3754 
3755 				if ((newpath = devid_to_path(devid)) != NULL) {
3756 					/*
3757 					 * Update the path appropriately.
3758 					 */
3759 					set_path(zhp, nv, newpath);
3760 					if (nvlist_add_string(nv,
3761 					    ZPOOL_CONFIG_PATH, newpath) == 0)
3762 						verify(nvlist_lookup_string(nv,
3763 						    ZPOOL_CONFIG_PATH,
3764 						    &path) == 0);
3765 					free(newpath);
3766 				}
3767 			}
3768 
3769 			if (newdevid)
3770 				devid_str_free(newdevid);
3771 		}
3772 
3773 		if (name_flags & VDEV_NAME_FOLLOW_LINKS) {
3774 			char *rp = realpath(path, NULL);
3775 			if (rp) {
3776 				strlcpy(buf, rp, sizeof (buf));
3777 				path = buf;
3778 				free(rp);
3779 			}
3780 		}
3781 
3782 		if (strncmp(path, ZFS_DISK_ROOTD, strlen(ZFS_DISK_ROOTD)) == 0)
3783 			path += strlen(ZFS_DISK_ROOTD);
3784 
3785 		/*
3786 		 * Remove the partition from the path it this is a whole disk.
3787 		 */
3788 		if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK, &value)
3789 		    == 0 && value && !(name_flags & VDEV_NAME_PATH)) {
3790 			int pathlen = strlen(path);
3791 			char *tmp = zfs_strdup(hdl, path);
3792 
3793 			/*
3794 			 * If it starts with c#, and ends with "s0" or "s1",
3795 			 * chop the slice off, or if it ends with "s0/old" or
3796 			 * "s1/old", remove the slice from the middle.
3797 			 */
3798 			if (CTD_CHECK(tmp)) {
3799 				if (strcmp(&tmp[pathlen - 2], "s0") == 0 ||
3800 				    strcmp(&tmp[pathlen - 2], "s1") == 0) {
3801 					tmp[pathlen - 2] = '\0';
3802 				} else if (pathlen > 6 &&
3803 				    (strcmp(&tmp[pathlen - 6], "s0/old") == 0 ||
3804 				    strcmp(&tmp[pathlen - 6], "s1/old") == 0)) {
3805 					(void) strcpy(&tmp[pathlen - 6],
3806 					    "/old");
3807 				}
3808 			}
3809 			return (tmp);
3810 		}
3811 	} else {
3812 		verify(nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &path) == 0);
3813 
3814 		/*
3815 		 * If it's a raidz device, we need to stick in the parity level.
3816 		 */
3817 		if (strcmp(path, VDEV_TYPE_RAIDZ) == 0) {
3818 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
3819 			    &value) == 0);
3820 			(void) snprintf(buf, sizeof (buf), "%s%llu", path,
3821 			    (u_longlong_t)value);
3822 			path = buf;
3823 		}
3824 
3825 		/*
3826 		 * We identify each top-level vdev by using a <type-id>
3827 		 * naming convention.
3828 		 */
3829 		if (name_flags & VDEV_NAME_TYPE_ID) {
3830 			uint64_t id;
3831 
3832 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID,
3833 			    &id) == 0);
3834 			(void) snprintf(buf, sizeof (buf), "%s-%llu", path,
3835 			    (u_longlong_t)id);
3836 			path = buf;
3837 		}
3838 	}
3839 
3840 	return (zfs_strdup(hdl, path));
3841 }
3842 
3843 static int
3844 zbookmark_mem_compare(const void *a, const void *b)
3845 {
3846 	return (memcmp(a, b, sizeof (zbookmark_phys_t)));
3847 }
3848 
3849 /*
3850  * Retrieve the persistent error log, uniquify the members, and return to the
3851  * caller.
3852  */
3853 int
3854 zpool_get_errlog(zpool_handle_t *zhp, nvlist_t **nverrlistp)
3855 {
3856 	zfs_cmd_t zc = { 0 };
3857 	uint64_t count;
3858 	zbookmark_phys_t *zb = NULL;
3859 	int i;
3860 
3861 	/*
3862 	 * Retrieve the raw error list from the kernel.  If the number of errors
3863 	 * has increased, allocate more space and continue until we get the
3864 	 * entire list.
3865 	 */
3866 	verify(nvlist_lookup_uint64(zhp->zpool_config, ZPOOL_CONFIG_ERRCOUNT,
3867 	    &count) == 0);
3868 	if (count == 0)
3869 		return (0);
3870 	if ((zc.zc_nvlist_dst = (uintptr_t)zfs_alloc(zhp->zpool_hdl,
3871 	    count * sizeof (zbookmark_phys_t))) == (uintptr_t)NULL)
3872 		return (-1);
3873 	zc.zc_nvlist_dst_size = count;
3874 	(void) strcpy(zc.zc_name, zhp->zpool_name);
3875 	for (;;) {
3876 		if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_ERROR_LOG,
3877 		    &zc) != 0) {
3878 			free((void *)(uintptr_t)zc.zc_nvlist_dst);
3879 			if (errno == ENOMEM) {
3880 				void *dst;
3881 
3882 				count = zc.zc_nvlist_dst_size;
3883 				dst = zfs_alloc(zhp->zpool_hdl, count *
3884 				    sizeof (zbookmark_phys_t));
3885 				if (dst == NULL)
3886 					return (-1);
3887 				zc.zc_nvlist_dst = (uintptr_t)dst;
3888 			} else {
3889 				return (-1);
3890 			}
3891 		} else {
3892 			break;
3893 		}
3894 	}
3895 
3896 	/*
3897 	 * Sort the resulting bookmarks.  This is a little confusing due to the
3898 	 * implementation of ZFS_IOC_ERROR_LOG.  The bookmarks are copied last
3899 	 * to first, and 'zc_nvlist_dst_size' indicates the number of boomarks
3900 	 * _not_ copied as part of the process.  So we point the start of our
3901 	 * array appropriate and decrement the total number of elements.
3902 	 */
3903 	zb = ((zbookmark_phys_t *)(uintptr_t)zc.zc_nvlist_dst) +
3904 	    zc.zc_nvlist_dst_size;
3905 	count -= zc.zc_nvlist_dst_size;
3906 
3907 	qsort(zb, count, sizeof (zbookmark_phys_t), zbookmark_mem_compare);
3908 
3909 	verify(nvlist_alloc(nverrlistp, 0, KM_SLEEP) == 0);
3910 
3911 	/*
3912 	 * Fill in the nverrlistp with nvlist's of dataset and object numbers.
3913 	 */
3914 	for (i = 0; i < count; i++) {
3915 		nvlist_t *nv;
3916 
3917 		/* ignoring zb_blkid and zb_level for now */
3918 		if (i > 0 && zb[i-1].zb_objset == zb[i].zb_objset &&
3919 		    zb[i-1].zb_object == zb[i].zb_object)
3920 			continue;
3921 
3922 		if (nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) != 0)
3923 			goto nomem;
3924 		if (nvlist_add_uint64(nv, ZPOOL_ERR_DATASET,
3925 		    zb[i].zb_objset) != 0) {
3926 			nvlist_free(nv);
3927 			goto nomem;
3928 		}
3929 		if (nvlist_add_uint64(nv, ZPOOL_ERR_OBJECT,
3930 		    zb[i].zb_object) != 0) {
3931 			nvlist_free(nv);
3932 			goto nomem;
3933 		}
3934 		if (nvlist_add_nvlist(*nverrlistp, "ejk", nv) != 0) {
3935 			nvlist_free(nv);
3936 			goto nomem;
3937 		}
3938 		nvlist_free(nv);
3939 	}
3940 
3941 	free((void *)(uintptr_t)zc.zc_nvlist_dst);
3942 	return (0);
3943 
3944 nomem:
3945 	free((void *)(uintptr_t)zc.zc_nvlist_dst);
3946 	return (no_memory(zhp->zpool_hdl));
3947 }
3948 
3949 /*
3950  * Upgrade a ZFS pool to the latest on-disk version.
3951  */
3952 int
3953 zpool_upgrade(zpool_handle_t *zhp, uint64_t new_version)
3954 {
3955 	zfs_cmd_t zc = { 0 };
3956 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3957 
3958 	(void) strcpy(zc.zc_name, zhp->zpool_name);
3959 	zc.zc_cookie = new_version;
3960 
3961 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_UPGRADE, &zc) != 0)
3962 		return (zpool_standard_error_fmt(hdl, errno,
3963 		    dgettext(TEXT_DOMAIN, "cannot upgrade '%s'"),
3964 		    zhp->zpool_name));
3965 	return (0);
3966 }
3967 
3968 void
3969 zfs_save_arguments(int argc, char **argv, char *string, int len)
3970 {
3971 	(void) strlcpy(string, basename(argv[0]), len);
3972 	for (int i = 1; i < argc; i++) {
3973 		(void) strlcat(string, " ", len);
3974 		(void) strlcat(string, argv[i], len);
3975 	}
3976 }
3977 
3978 int
3979 zpool_log_history(libzfs_handle_t *hdl, const char *message)
3980 {
3981 	zfs_cmd_t zc = { 0 };
3982 	nvlist_t *args;
3983 	int err;
3984 
3985 	args = fnvlist_alloc();
3986 	fnvlist_add_string(args, "message", message);
3987 	err = zcmd_write_src_nvlist(hdl, &zc, args);
3988 	if (err == 0)
3989 		err = ioctl(hdl->libzfs_fd, ZFS_IOC_LOG_HISTORY, &zc);
3990 	nvlist_free(args);
3991 	zcmd_free_nvlists(&zc);
3992 	return (err);
3993 }
3994 
3995 /*
3996  * Perform ioctl to get some command history of a pool.
3997  *
3998  * 'buf' is the buffer to fill up to 'len' bytes.  'off' is the
3999  * logical offset of the history buffer to start reading from.
4000  *
4001  * Upon return, 'off' is the next logical offset to read from and
4002  * 'len' is the actual amount of bytes read into 'buf'.
4003  */
4004 static int
4005 get_history(zpool_handle_t *zhp, char *buf, uint64_t *off, uint64_t *len)
4006 {
4007 	zfs_cmd_t zc = { 0 };
4008 	libzfs_handle_t *hdl = zhp->zpool_hdl;
4009 
4010 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
4011 
4012 	zc.zc_history = (uint64_t)(uintptr_t)buf;
4013 	zc.zc_history_len = *len;
4014 	zc.zc_history_offset = *off;
4015 
4016 	if (ioctl(hdl->libzfs_fd, ZFS_IOC_POOL_GET_HISTORY, &zc) != 0) {
4017 		switch (errno) {
4018 		case EPERM:
4019 			return (zfs_error_fmt(hdl, EZFS_PERM,
4020 			    dgettext(TEXT_DOMAIN,
4021 			    "cannot show history for pool '%s'"),
4022 			    zhp->zpool_name));
4023 		case ENOENT:
4024 			return (zfs_error_fmt(hdl, EZFS_NOHISTORY,
4025 			    dgettext(TEXT_DOMAIN, "cannot get history for pool "
4026 			    "'%s'"), zhp->zpool_name));
4027 		case ENOTSUP:
4028 			return (zfs_error_fmt(hdl, EZFS_BADVERSION,
4029 			    dgettext(TEXT_DOMAIN, "cannot get history for pool "
4030 			    "'%s', pool must be upgraded"), zhp->zpool_name));
4031 		default:
4032 			return (zpool_standard_error_fmt(hdl, errno,
4033 			    dgettext(TEXT_DOMAIN,
4034 			    "cannot get history for '%s'"), zhp->zpool_name));
4035 		}
4036 	}
4037 
4038 	*len = zc.zc_history_len;
4039 	*off = zc.zc_history_offset;
4040 
4041 	return (0);
4042 }
4043 
4044 /*
4045  * Process the buffer of nvlists, unpacking and storing each nvlist record
4046  * into 'records'.  'leftover' is set to the number of bytes that weren't
4047  * processed as there wasn't a complete record.
4048  */
4049 int
4050 zpool_history_unpack(char *buf, uint64_t bytes_read, uint64_t *leftover,
4051     nvlist_t ***records, uint_t *numrecords)
4052 {
4053 	uint64_t reclen;
4054 	nvlist_t *nv;
4055 	int i;
4056 
4057 	while (bytes_read > sizeof (reclen)) {
4058 
4059 		/* get length of packed record (stored as little endian) */
4060 		for (i = 0, reclen = 0; i < sizeof (reclen); i++)
4061 			reclen += (uint64_t)(((uchar_t *)buf)[i]) << (8*i);
4062 
4063 		if (bytes_read < sizeof (reclen) + reclen)
4064 			break;
4065 
4066 		/* unpack record */
4067 		if (nvlist_unpack(buf + sizeof (reclen), reclen, &nv, 0) != 0)
4068 			return (ENOMEM);
4069 		bytes_read -= sizeof (reclen) + reclen;
4070 		buf += sizeof (reclen) + reclen;
4071 
4072 		/* add record to nvlist array */
4073 		(*numrecords)++;
4074 		if (ISP2(*numrecords + 1)) {
4075 			*records = realloc(*records,
4076 			    *numrecords * 2 * sizeof (nvlist_t *));
4077 		}
4078 		(*records)[*numrecords - 1] = nv;
4079 	}
4080 
4081 	*leftover = bytes_read;
4082 	return (0);
4083 }
4084 
4085 /*
4086  * Retrieve the command history of a pool.
4087  */
4088 int
4089 zpool_get_history(zpool_handle_t *zhp, nvlist_t **nvhisp)
4090 {
4091 	char *buf;
4092 	int buflen = 128 * 1024;
4093 	uint64_t off = 0;
4094 	nvlist_t **records = NULL;
4095 	uint_t numrecords = 0;
4096 	int err, i;
4097 
4098 	buf = malloc(buflen);
4099 	if (buf == NULL)
4100 		return (ENOMEM);
4101 	do {
4102 		uint64_t bytes_read = buflen;
4103 		uint64_t leftover;
4104 
4105 		if ((err = get_history(zhp, buf, &off, &bytes_read)) != 0)
4106 			break;
4107 
4108 		/* if nothing else was read in, we're at EOF, just return */
4109 		if (!bytes_read)
4110 			break;
4111 
4112 		if ((err = zpool_history_unpack(buf, bytes_read,
4113 		    &leftover, &records, &numrecords)) != 0)
4114 			break;
4115 		off -= leftover;
4116 		if (leftover == bytes_read) {
4117 			/*
4118 			 * no progress made, because buffer is not big enough
4119 			 * to hold this record; resize and retry.
4120 			 */
4121 			buflen *= 2;
4122 			free(buf);
4123 			buf = malloc(buflen);
4124 			if (buf == NULL)
4125 				return (ENOMEM);
4126 		}
4127 
4128 		/* CONSTCOND */
4129 	} while (1);
4130 
4131 	free(buf);
4132 
4133 	if (!err) {
4134 		verify(nvlist_alloc(nvhisp, NV_UNIQUE_NAME, 0) == 0);
4135 		verify(nvlist_add_nvlist_array(*nvhisp, ZPOOL_HIST_RECORD,
4136 		    records, numrecords) == 0);
4137 	}
4138 	for (i = 0; i < numrecords; i++)
4139 		nvlist_free(records[i]);
4140 	free(records);
4141 
4142 	return (err);
4143 }
4144 
4145 void
4146 zpool_obj_to_path(zpool_handle_t *zhp, uint64_t dsobj, uint64_t obj,
4147     char *pathname, size_t len)
4148 {
4149 	zfs_cmd_t zc = { 0 };
4150 	boolean_t mounted = B_FALSE;
4151 	char *mntpnt = NULL;
4152 	char dsname[ZFS_MAX_DATASET_NAME_LEN];
4153 
4154 	if (dsobj == 0) {
4155 		/* special case for the MOS */
4156 		(void) snprintf(pathname, len, "<metadata>:<0x%llx>", obj);
4157 		return;
4158 	}
4159 
4160 	/* get the dataset's name */
4161 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
4162 	zc.zc_obj = dsobj;
4163 	if (ioctl(zhp->zpool_hdl->libzfs_fd,
4164 	    ZFS_IOC_DSOBJ_TO_DSNAME, &zc) != 0) {
4165 		/* just write out a path of two object numbers */
4166 		(void) snprintf(pathname, len, "<0x%llx>:<0x%llx>",
4167 		    dsobj, obj);
4168 		return;
4169 	}
4170 	(void) strlcpy(dsname, zc.zc_value, sizeof (dsname));
4171 
4172 	/* find out if the dataset is mounted */
4173 	mounted = is_mounted(zhp->zpool_hdl, dsname, &mntpnt);
4174 
4175 	/* get the corrupted object's path */
4176 	(void) strlcpy(zc.zc_name, dsname, sizeof (zc.zc_name));
4177 	zc.zc_obj = obj;
4178 	if (ioctl(zhp->zpool_hdl->libzfs_fd, ZFS_IOC_OBJ_TO_PATH,
4179 	    &zc) == 0) {
4180 		if (mounted) {
4181 			(void) snprintf(pathname, len, "%s%s", mntpnt,
4182 			    zc.zc_value);
4183 		} else {
4184 			(void) snprintf(pathname, len, "%s:%s",
4185 			    dsname, zc.zc_value);
4186 		}
4187 	} else {
4188 		(void) snprintf(pathname, len, "%s:<0x%llx>", dsname, obj);
4189 	}
4190 	free(mntpnt);
4191 }
4192 
4193 /*
4194  * Read the EFI label from the config, if a label does not exist then
4195  * pass back the error to the caller. If the caller has passed a non-NULL
4196  * diskaddr argument then we set it to the starting address of the EFI
4197  * partition. If the caller has passed a non-NULL boolean argument, then
4198  * we set it to indicate if the disk does have efi system partition.
4199  */
4200 static int
4201 read_efi_label(nvlist_t *config, diskaddr_t *sb, boolean_t *system)
4202 {
4203 	char *path;
4204 	int fd;
4205 	char diskname[MAXPATHLEN];
4206 	boolean_t boot = B_FALSE;
4207 	int err = -1;
4208 	int slice;
4209 
4210 	if (nvlist_lookup_string(config, ZPOOL_CONFIG_PATH, &path) != 0)
4211 		return (err);
4212 
4213 	(void) snprintf(diskname, sizeof (diskname), "%s%s", ZFS_RDISK_ROOT,
4214 	    strrchr(path, '/'));
4215 	if ((fd = open(diskname, O_RDONLY|O_NDELAY)) >= 0) {
4216 		struct dk_gpt *vtoc;
4217 
4218 		if ((err = efi_alloc_and_read(fd, &vtoc)) >= 0) {
4219 			for (slice = 0; slice < vtoc->efi_nparts; slice++) {
4220 				if (vtoc->efi_parts[slice].p_tag == V_SYSTEM)
4221 					boot = B_TRUE;
4222 				if (vtoc->efi_parts[slice].p_tag == V_USR)
4223 					break;
4224 			}
4225 			if (sb != NULL && vtoc->efi_parts[slice].p_tag == V_USR)
4226 				*sb = vtoc->efi_parts[slice].p_start;
4227 			if (system != NULL)
4228 				*system = boot;
4229 			efi_free(vtoc);
4230 		}
4231 		(void) close(fd);
4232 	}
4233 	return (err);
4234 }
4235 
4236 /*
4237  * determine where a partition starts on a disk in the current
4238  * configuration
4239  */
4240 static diskaddr_t
4241 find_start_block(nvlist_t *config)
4242 {
4243 	nvlist_t **child;
4244 	uint_t c, children;
4245 	diskaddr_t sb = MAXOFFSET_T;
4246 	uint64_t wholedisk;
4247 
4248 	if (nvlist_lookup_nvlist_array(config,
4249 	    ZPOOL_CONFIG_CHILDREN, &child, &children) != 0) {
4250 		if (nvlist_lookup_uint64(config,
4251 		    ZPOOL_CONFIG_WHOLE_DISK,
4252 		    &wholedisk) != 0 || !wholedisk) {
4253 			return (MAXOFFSET_T);
4254 		}
4255 		if (read_efi_label(config, &sb, NULL) < 0)
4256 			sb = MAXOFFSET_T;
4257 		return (sb);
4258 	}
4259 
4260 	for (c = 0; c < children; c++) {
4261 		sb = find_start_block(child[c]);
4262 		if (sb != MAXOFFSET_T) {
4263 			return (sb);
4264 		}
4265 	}
4266 	return (MAXOFFSET_T);
4267 }
4268 
4269 /*
4270  * Label an individual disk.  The name provided is the short name,
4271  * stripped of any leading /dev path.
4272  */
4273 int
4274 zpool_label_disk(libzfs_handle_t *hdl, zpool_handle_t *zhp, const char *name,
4275     zpool_boot_label_t boot_type, uint64_t boot_size, int *slice)
4276 {
4277 	char path[MAXPATHLEN];
4278 	struct dk_gpt *vtoc;
4279 	int fd;
4280 	size_t resv = EFI_MIN_RESV_SIZE;
4281 	uint64_t slice_size;
4282 	diskaddr_t start_block;
4283 	char errbuf[1024];
4284 
4285 	/* prepare an error message just in case */
4286 	(void) snprintf(errbuf, sizeof (errbuf),
4287 	    dgettext(TEXT_DOMAIN, "cannot label '%s'"), name);
4288 
4289 	if (zhp) {
4290 		nvlist_t *nvroot;
4291 
4292 		verify(nvlist_lookup_nvlist(zhp->zpool_config,
4293 		    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
4294 
4295 		if (zhp->zpool_start_block == 0)
4296 			start_block = find_start_block(nvroot);
4297 		else
4298 			start_block = zhp->zpool_start_block;
4299 		zhp->zpool_start_block = start_block;
4300 	} else {
4301 		/* new pool */
4302 		start_block = NEW_START_BLOCK;
4303 	}
4304 
4305 	(void) snprintf(path, sizeof (path), "%s/%s%s", ZFS_RDISK_ROOT, name,
4306 	    BACKUP_SLICE);
4307 
4308 	if ((fd = open(path, O_RDWR | O_NDELAY)) < 0) {
4309 		/*
4310 		 * This shouldn't happen.  We've long since verified that this
4311 		 * is a valid device.
4312 		 */
4313 		zfs_error_aux(hdl,
4314 		    dgettext(TEXT_DOMAIN, "unable to open device"));
4315 		return (zfs_error(hdl, EZFS_OPENFAILED, errbuf));
4316 	}
4317 
4318 	if (efi_alloc_and_init(fd, EFI_NUMPAR, &vtoc) != 0) {
4319 		/*
4320 		 * The only way this can fail is if we run out of memory, or we
4321 		 * were unable to read the disk's capacity
4322 		 */
4323 		if (errno == ENOMEM)
4324 			(void) no_memory(hdl);
4325 
4326 		(void) close(fd);
4327 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4328 		    "unable to read disk capacity"), name);
4329 
4330 		return (zfs_error(hdl, EZFS_NOCAP, errbuf));
4331 	}
4332 
4333 	/*
4334 	 * Why we use V_USR: V_BACKUP confuses users, and is considered
4335 	 * disposable by some EFI utilities (since EFI doesn't have a backup
4336 	 * slice).  V_UNASSIGNED is supposed to be used only for zero size
4337 	 * partitions, and efi_write() will fail if we use it.  V_ROOT, V_BOOT,
4338 	 * etc. were all pretty specific.  V_USR is as close to reality as we
4339 	 * can get, in the absence of V_OTHER.
4340 	 */
4341 	/* first fix the partition start block */
4342 	if (start_block == MAXOFFSET_T)
4343 		start_block = NEW_START_BLOCK;
4344 
4345 	/*
4346 	 * EFI System partition is using slice 0.
4347 	 * ZFS is on slice 1 and slice 8 is reserved.
4348 	 * We assume the GPT partition table without system
4349 	 * partition has zfs p_start == NEW_START_BLOCK.
4350 	 * If start_block != NEW_START_BLOCK, it means we have
4351 	 * system partition. Correct solution would be to query/cache vtoc
4352 	 * from existing vdev member.
4353 	 */
4354 	if (boot_type == ZPOOL_CREATE_BOOT_LABEL) {
4355 		if (boot_size % vtoc->efi_lbasize != 0) {
4356 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4357 			    "boot partition size must be a multiple of %d"),
4358 			    vtoc->efi_lbasize);
4359 			(void) close(fd);
4360 			efi_free(vtoc);
4361 			return (zfs_error(hdl, EZFS_LABELFAILED, errbuf));
4362 		}
4363 		/*
4364 		 * System partition size checks.
4365 		 * Note the 1MB is quite arbitrary value, since we
4366 		 * are creating dedicated pool, it should be enough
4367 		 * to hold fat + efi bootloader. May need to be
4368 		 * adjusted if the bootloader size will grow.
4369 		 */
4370 		if (boot_size < 1024 * 1024) {
4371 			char buf[64];
4372 			zfs_nicenum(boot_size, buf, sizeof (buf));
4373 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4374 			    "Specified size %s for EFI System partition is too "
4375 			    "small, the minimum size is 1MB."), buf);
4376 			(void) close(fd);
4377 			efi_free(vtoc);
4378 			return (zfs_error(hdl, EZFS_LABELFAILED, errbuf));
4379 		}
4380 		/* 33MB is tested with mkfs -F pcfs */
4381 		if (hdl->libzfs_printerr &&
4382 		    ((vtoc->efi_lbasize == 512 &&
4383 		    boot_size < 33 * 1024 * 1024) ||
4384 		    (vtoc->efi_lbasize == 4096 &&
4385 		    boot_size < 256 * 1024 * 1024)))  {
4386 			char buf[64];
4387 			zfs_nicenum(boot_size, buf, sizeof (buf));
4388 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
4389 			    "Warning: EFI System partition size %s is "
4390 			    "not allowing to create FAT32 file\nsystem, which "
4391 			    "may result in unbootable system.\n"), buf);
4392 		}
4393 		/* Adjust zfs partition start by size of system partition. */
4394 		start_block += boot_size / vtoc->efi_lbasize;
4395 	}
4396 
4397 	if (start_block == NEW_START_BLOCK) {
4398 		/*
4399 		 * Use default layout.
4400 		 * ZFS is on slice 0 and slice 8 is reserved.
4401 		 */
4402 		slice_size = vtoc->efi_last_u_lba + 1;
4403 		slice_size -= EFI_MIN_RESV_SIZE;
4404 		slice_size -= start_block;
4405 		if (slice != NULL)
4406 			*slice = 0;
4407 
4408 		vtoc->efi_parts[0].p_start = start_block;
4409 		vtoc->efi_parts[0].p_size = slice_size;
4410 
4411 		vtoc->efi_parts[0].p_tag = V_USR;
4412 		(void) strcpy(vtoc->efi_parts[0].p_name, "zfs");
4413 
4414 		vtoc->efi_parts[8].p_start = slice_size + start_block;
4415 		vtoc->efi_parts[8].p_size = resv;
4416 		vtoc->efi_parts[8].p_tag = V_RESERVED;
4417 	} else {
4418 		slice_size = start_block - NEW_START_BLOCK;
4419 		vtoc->efi_parts[0].p_start = NEW_START_BLOCK;
4420 		vtoc->efi_parts[0].p_size = slice_size;
4421 		vtoc->efi_parts[0].p_tag = V_SYSTEM;
4422 		(void) strcpy(vtoc->efi_parts[0].p_name, "loader");
4423 		if (slice != NULL)
4424 			*slice = 1;
4425 		/* prepare slice 1 */
4426 		slice_size = vtoc->efi_last_u_lba + 1 - slice_size;
4427 		slice_size -= resv;
4428 		slice_size -= NEW_START_BLOCK;
4429 		vtoc->efi_parts[1].p_start = start_block;
4430 		vtoc->efi_parts[1].p_size = slice_size;
4431 		vtoc->efi_parts[1].p_tag = V_USR;
4432 		(void) strcpy(vtoc->efi_parts[1].p_name, "zfs");
4433 
4434 		vtoc->efi_parts[8].p_start = slice_size + start_block;
4435 		vtoc->efi_parts[8].p_size = resv;
4436 		vtoc->efi_parts[8].p_tag = V_RESERVED;
4437 	}
4438 
4439 	if (efi_write(fd, vtoc) != 0) {
4440 		/*
4441 		 * Some block drivers (like pcata) may not support EFI
4442 		 * GPT labels.  Print out a helpful error message dir-
4443 		 * ecting the user to manually label the disk and give
4444 		 * a specific slice.
4445 		 */
4446 		(void) close(fd);
4447 		efi_free(vtoc);
4448 
4449 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4450 		    "try using fdisk(1M) and then provide a specific slice"));
4451 		return (zfs_error(hdl, EZFS_LABELFAILED, errbuf));
4452 	}
4453 
4454 	(void) close(fd);
4455 	efi_free(vtoc);
4456 	return (0);
4457 }
4458 
4459 static boolean_t
4460 supported_dump_vdev_type(libzfs_handle_t *hdl, nvlist_t *config, char *errbuf)
4461 {
4462 	char *type;
4463 	nvlist_t **child;
4464 	uint_t children, c;
4465 
4466 	verify(nvlist_lookup_string(config, ZPOOL_CONFIG_TYPE, &type) == 0);
4467 	if (strcmp(type, VDEV_TYPE_FILE) == 0 ||
4468 	    strcmp(type, VDEV_TYPE_HOLE) == 0 ||
4469 	    strcmp(type, VDEV_TYPE_MISSING) == 0) {
4470 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4471 		    "vdev type '%s' is not supported"), type);
4472 		(void) zfs_error(hdl, EZFS_VDEVNOTSUP, errbuf);
4473 		return (B_FALSE);
4474 	}
4475 	if (nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_CHILDREN,
4476 	    &child, &children) == 0) {
4477 		for (c = 0; c < children; c++) {
4478 			if (!supported_dump_vdev_type(hdl, child[c], errbuf))
4479 				return (B_FALSE);
4480 		}
4481 	}
4482 	return (B_TRUE);
4483 }
4484 
4485 /*
4486  * Check if this zvol is allowable for use as a dump device; zero if
4487  * it is, > 0 if it isn't, < 0 if it isn't a zvol.
4488  *
4489  * Allowable storage configurations include mirrors, all raidz variants, and
4490  * pools with log, cache, and spare devices.  Pools which are backed by files or
4491  * have missing/hole vdevs are not suitable.
4492  */
4493 int
4494 zvol_check_dump_config(char *arg)
4495 {
4496 	zpool_handle_t *zhp = NULL;
4497 	nvlist_t *config, *nvroot;
4498 	char *p, *volname;
4499 	nvlist_t **top;
4500 	uint_t toplevels;
4501 	libzfs_handle_t *hdl;
4502 	char errbuf[1024];
4503 	char poolname[ZFS_MAX_DATASET_NAME_LEN];
4504 	int pathlen = strlen(ZVOL_FULL_DEV_DIR);
4505 	int ret = 1;
4506 
4507 	if (strncmp(arg, ZVOL_FULL_DEV_DIR, pathlen)) {
4508 		return (-1);
4509 	}
4510 
4511 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4512 	    "dump is not supported on device '%s'"), arg);
4513 
4514 	if ((hdl = libzfs_init()) == NULL)
4515 		return (1);
4516 	libzfs_print_on_error(hdl, B_TRUE);
4517 
4518 	volname = arg + pathlen;
4519 
4520 	/* check the configuration of the pool */
4521 	if ((p = strchr(volname, '/')) == NULL) {
4522 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4523 		    "malformed dataset name"));
4524 		(void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
4525 		return (1);
4526 	} else if (p - volname >= ZFS_MAX_DATASET_NAME_LEN) {
4527 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4528 		    "dataset name is too long"));
4529 		(void) zfs_error(hdl, EZFS_NAMETOOLONG, errbuf);
4530 		return (1);
4531 	} else {
4532 		(void) strncpy(poolname, volname, p - volname);
4533 		poolname[p - volname] = '\0';
4534 	}
4535 
4536 	if ((zhp = zpool_open(hdl, poolname)) == NULL) {
4537 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4538 		    "could not open pool '%s'"), poolname);
4539 		(void) zfs_error(hdl, EZFS_OPENFAILED, errbuf);
4540 		goto out;
4541 	}
4542 	config = zpool_get_config(zhp, NULL);
4543 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4544 	    &nvroot) != 0) {
4545 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4546 		    "could not obtain vdev configuration for  '%s'"), poolname);
4547 		(void) zfs_error(hdl, EZFS_INVALCONFIG, errbuf);
4548 		goto out;
4549 	}
4550 
4551 	verify(nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
4552 	    &top, &toplevels) == 0);
4553 
4554 	if (!supported_dump_vdev_type(hdl, top[0], errbuf)) {
4555 		goto out;
4556 	}
4557 	ret = 0;
4558 
4559 out:
4560 	if (zhp)
4561 		zpool_close(zhp);
4562 	libzfs_fini(hdl);
4563 	return (ret);
4564 }
4565