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