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