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