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