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