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