1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
25  * Copyright 2019 Joyent, Inc.
26  * Copyright 2016 Nexenta Systems, Inc.
27  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
28  * Copyright (c) 2017 Datto Inc.
29  * Copyright (c) 2017, Intel Corporation.
30  */
31 
32 #include <ctype.h>
33 #include <errno.h>
34 #include <devid.h>
35 #include <fcntl.h>
36 #include <libintl.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <strings.h>
40 #include <unistd.h>
41 #include <libgen.h>
42 #include <sys/efi_partition.h>
43 #include <sys/vtoc.h>
44 #include <sys/zfs_ioctl.h>
45 #include <dlfcn.h>
46 #include <libzutil.h>
47 
48 #include "zfs_namecheck.h"
49 #include "zfs_prop.h"
50 #include "libzfs_impl.h"
51 #include "zfs_comutil.h"
52 #include "zfeature_common.h"
53 
54 static int read_efi_label(nvlist_t *, diskaddr_t *, boolean_t *);
55 static boolean_t zpool_vdev_is_interior(const char *name);
56 
57 #define	BACKUP_SLICE	"s2"
58 
59 typedef struct prop_flags {
60 	int create:1;	/* Validate property on creation */
61 	int import:1;	/* Validate property on import */
62 } prop_flags_t;
63 
64 /*
65  * ====================================================================
66  *   zpool property functions
67  * ====================================================================
68  */
69 
70 static int
zpool_get_all_props(zpool_handle_t * zhp)71 zpool_get_all_props(zpool_handle_t *zhp)
72 {
73 	zfs_cmd_t zc = { 0 };
74 	libzfs_handle_t *hdl = zhp->zpool_hdl;
75 
76 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
77 
78 	if (zcmd_alloc_dst_nvlist(hdl, &zc, 0) != 0)
79 		return (-1);
80 
81 	while (ioctl(hdl->libzfs_fd, ZFS_IOC_POOL_GET_PROPS, &zc) != 0) {
82 		if (errno == ENOMEM) {
83 			if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
84 				zcmd_free_nvlists(&zc);
85 				return (-1);
86 			}
87 		} else {
88 			zcmd_free_nvlists(&zc);
89 			return (-1);
90 		}
91 	}
92 
93 	if (zcmd_read_dst_nvlist(hdl, &zc, &zhp->zpool_props) != 0) {
94 		zcmd_free_nvlists(&zc);
95 		return (-1);
96 	}
97 
98 	zcmd_free_nvlists(&zc);
99 
100 	return (0);
101 }
102 
103 static int
zpool_props_refresh(zpool_handle_t * zhp)104 zpool_props_refresh(zpool_handle_t *zhp)
105 {
106 	nvlist_t *old_props;
107 
108 	old_props = zhp->zpool_props;
109 
110 	if (zpool_get_all_props(zhp) != 0)
111 		return (-1);
112 
113 	nvlist_free(old_props);
114 	return (0);
115 }
116 
117 static char *
zpool_get_prop_string(zpool_handle_t * zhp,zpool_prop_t prop,zprop_source_t * src)118 zpool_get_prop_string(zpool_handle_t *zhp, zpool_prop_t prop,
119     zprop_source_t *src)
120 {
121 	nvlist_t *nv, *nvl;
122 	uint64_t ival;
123 	char *value;
124 	zprop_source_t source;
125 
126 	nvl = zhp->zpool_props;
127 	if (nvlist_lookup_nvlist(nvl, zpool_prop_to_name(prop), &nv) == 0) {
128 		verify(nvlist_lookup_uint64(nv, ZPROP_SOURCE, &ival) == 0);
129 		source = ival;
130 		verify(nvlist_lookup_string(nv, ZPROP_VALUE, &value) == 0);
131 	} else {
132 		source = ZPROP_SRC_DEFAULT;
133 		if ((value = (char *)zpool_prop_default_string(prop)) == NULL)
134 			value = "-";
135 	}
136 
137 	if (src)
138 		*src = source;
139 
140 	return (value);
141 }
142 
143 uint64_t
zpool_get_prop_int(zpool_handle_t * zhp,zpool_prop_t prop,zprop_source_t * src)144 zpool_get_prop_int(zpool_handle_t *zhp, zpool_prop_t prop, zprop_source_t *src)
145 {
146 	nvlist_t *nv, *nvl;
147 	uint64_t value;
148 	zprop_source_t source;
149 
150 	if (zhp->zpool_props == NULL && zpool_get_all_props(zhp)) {
151 		/*
152 		 * zpool_get_all_props() has most likely failed because
153 		 * the pool is faulted, but if all we need is the top level
154 		 * vdev's guid then get it from the zhp config nvlist.
155 		 */
156 		if ((prop == ZPOOL_PROP_GUID) &&
157 		    (nvlist_lookup_nvlist(zhp->zpool_config,
158 		    ZPOOL_CONFIG_VDEV_TREE, &nv) == 0) &&
159 		    (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &value)
160 		    == 0)) {
161 			return (value);
162 		}
163 		return (zpool_prop_default_numeric(prop));
164 	}
165 
166 	nvl = zhp->zpool_props;
167 	if (nvlist_lookup_nvlist(nvl, zpool_prop_to_name(prop), &nv) == 0) {
168 		verify(nvlist_lookup_uint64(nv, ZPROP_SOURCE, &value) == 0);
169 		source = value;
170 		verify(nvlist_lookup_uint64(nv, ZPROP_VALUE, &value) == 0);
171 	} else {
172 		source = ZPROP_SRC_DEFAULT;
173 		value = zpool_prop_default_numeric(prop);
174 	}
175 
176 	if (src)
177 		*src = source;
178 
179 	return (value);
180 }
181 
182 /*
183  * Map VDEV STATE to printed strings.
184  */
185 const char *
zpool_state_to_name(vdev_state_t state,vdev_aux_t aux)186 zpool_state_to_name(vdev_state_t state, vdev_aux_t aux)
187 {
188 	switch (state) {
189 	case VDEV_STATE_CLOSED:
190 	case VDEV_STATE_OFFLINE:
191 		return (gettext("OFFLINE"));
192 	case VDEV_STATE_REMOVED:
193 		return (gettext("REMOVED"));
194 	case VDEV_STATE_CANT_OPEN:
195 		if (aux == VDEV_AUX_CORRUPT_DATA || aux == VDEV_AUX_BAD_LOG)
196 			return (gettext("FAULTED"));
197 		else if (aux == VDEV_AUX_SPLIT_POOL)
198 			return (gettext("SPLIT"));
199 		else
200 			return (gettext("UNAVAIL"));
201 	case VDEV_STATE_FAULTED:
202 		return (gettext("FAULTED"));
203 	case VDEV_STATE_DEGRADED:
204 		return (gettext("DEGRADED"));
205 	case VDEV_STATE_HEALTHY:
206 		return (gettext("ONLINE"));
207 
208 	default:
209 		break;
210 	}
211 
212 	return (gettext("UNKNOWN"));
213 }
214 
215 /*
216  * Map POOL STATE to printed strings.
217  */
218 const char *
zpool_pool_state_to_name(pool_state_t state)219 zpool_pool_state_to_name(pool_state_t state)
220 {
221 	switch (state) {
222 	case POOL_STATE_ACTIVE:
223 		return (gettext("ACTIVE"));
224 	case POOL_STATE_EXPORTED:
225 		return (gettext("EXPORTED"));
226 	case POOL_STATE_DESTROYED:
227 		return (gettext("DESTROYED"));
228 	case POOL_STATE_SPARE:
229 		return (gettext("SPARE"));
230 	case POOL_STATE_L2CACHE:
231 		return (gettext("L2CACHE"));
232 	case POOL_STATE_UNINITIALIZED:
233 		return (gettext("UNINITIALIZED"));
234 	case POOL_STATE_UNAVAIL:
235 		return (gettext("UNAVAIL"));
236 	case POOL_STATE_POTENTIALLY_ACTIVE:
237 		return (gettext("POTENTIALLY_ACTIVE"));
238 	}
239 
240 	return (gettext("UNKNOWN"));
241 }
242 
243 /*
244  * Get a zpool property value for 'prop' and return the value in
245  * a pre-allocated buffer.
246  */
247 int
zpool_get_prop(zpool_handle_t * zhp,zpool_prop_t prop,char * buf,size_t len,zprop_source_t * srctype,boolean_t literal)248 zpool_get_prop(zpool_handle_t *zhp, zpool_prop_t prop, char *buf, size_t len,
249     zprop_source_t *srctype, boolean_t literal)
250 {
251 	uint64_t intval;
252 	const char *strval;
253 	zprop_source_t src = ZPROP_SRC_NONE;
254 	nvlist_t *nvroot;
255 	vdev_stat_t *vs;
256 	uint_t vsc;
257 
258 	if (zpool_get_state(zhp) == POOL_STATE_UNAVAIL) {
259 		switch (prop) {
260 		case ZPOOL_PROP_NAME:
261 			(void) strlcpy(buf, zpool_get_name(zhp), len);
262 			break;
263 
264 		case ZPOOL_PROP_HEALTH:
265 			(void) strlcpy(buf, "FAULTED", len);
266 			break;
267 
268 		case ZPOOL_PROP_GUID:
269 			intval = zpool_get_prop_int(zhp, prop, &src);
270 			(void) snprintf(buf, len, "%llu", intval);
271 			break;
272 
273 		case ZPOOL_PROP_ALTROOT:
274 		case ZPOOL_PROP_CACHEFILE:
275 		case ZPOOL_PROP_COMMENT:
276 			if (zhp->zpool_props != NULL ||
277 			    zpool_get_all_props(zhp) == 0) {
278 				(void) strlcpy(buf,
279 				    zpool_get_prop_string(zhp, prop, &src),
280 				    len);
281 				break;
282 			}
283 			/* FALLTHROUGH */
284 		default:
285 			(void) strlcpy(buf, "-", len);
286 			break;
287 		}
288 
289 		if (srctype != NULL)
290 			*srctype = src;
291 		return (0);
292 	}
293 
294 	if (zhp->zpool_props == NULL && zpool_get_all_props(zhp) &&
295 	    prop != ZPOOL_PROP_NAME)
296 		return (-1);
297 
298 	switch (zpool_prop_get_type(prop)) {
299 	case PROP_TYPE_STRING:
300 		(void) strlcpy(buf, zpool_get_prop_string(zhp, prop, &src),
301 		    len);
302 		break;
303 
304 	case PROP_TYPE_NUMBER:
305 		intval = zpool_get_prop_int(zhp, prop, &src);
306 
307 		switch (prop) {
308 		case ZPOOL_PROP_SIZE:
309 		case ZPOOL_PROP_ALLOCATED:
310 		case ZPOOL_PROP_FREE:
311 		case ZPOOL_PROP_FREEING:
312 		case ZPOOL_PROP_LEAKED:
313 		case ZPOOL_PROP_ASHIFT:
314 			if (literal) {
315 				(void) snprintf(buf, len, "%llu",
316 				    (u_longlong_t)intval);
317 			} else {
318 				(void) zfs_nicenum(intval, buf, len);
319 			}
320 			break;
321 		case ZPOOL_PROP_BOOTSIZE:
322 		case ZPOOL_PROP_EXPANDSZ:
323 		case ZPOOL_PROP_CHECKPOINT:
324 			if (intval == 0) {
325 				(void) strlcpy(buf, "-", len);
326 			} else if (literal) {
327 				(void) snprintf(buf, len, "%llu",
328 				    (u_longlong_t)intval);
329 			} else {
330 				(void) zfs_nicenum(intval, buf, len);
331 			}
332 			break;
333 		case ZPOOL_PROP_CAPACITY:
334 			if (literal) {
335 				(void) snprintf(buf, len, "%llu",
336 				    (u_longlong_t)intval);
337 			} else {
338 				(void) snprintf(buf, len, "%llu%%",
339 				    (u_longlong_t)intval);
340 			}
341 			break;
342 		case ZPOOL_PROP_FRAGMENTATION:
343 			if (intval == UINT64_MAX) {
344 				(void) strlcpy(buf, "-", len);
345 			} else if (literal) {
346 				(void) snprintf(buf, len, "%llu",
347 				    (u_longlong_t)intval);
348 			} else {
349 				(void) snprintf(buf, len, "%llu%%",
350 				    (u_longlong_t)intval);
351 			}
352 			break;
353 		case ZPOOL_PROP_DEDUPRATIO:
354 			if (literal)
355 				(void) snprintf(buf, len, "%llu.%02llu",
356 				    (u_longlong_t)(intval / 100),
357 				    (u_longlong_t)(intval % 100));
358 			else
359 				(void) snprintf(buf, len, "%llu.%02llux",
360 				    (u_longlong_t)(intval / 100),
361 				    (u_longlong_t)(intval % 100));
362 			break;
363 		case ZPOOL_PROP_HEALTH:
364 			verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
365 			    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
366 			verify(nvlist_lookup_uint64_array(nvroot,
367 			    ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
368 			    == 0);
369 
370 			(void) strlcpy(buf, zpool_state_to_name(intval,
371 			    vs->vs_aux), len);
372 			break;
373 		case ZPOOL_PROP_VERSION:
374 			if (intval >= SPA_VERSION_FEATURES) {
375 				(void) snprintf(buf, len, "-");
376 				break;
377 			}
378 			/* FALLTHROUGH */
379 		default:
380 			(void) snprintf(buf, len, "%llu", intval);
381 		}
382 		break;
383 
384 	case PROP_TYPE_INDEX:
385 		intval = zpool_get_prop_int(zhp, prop, &src);
386 		if (zpool_prop_index_to_string(prop, intval, &strval)
387 		    != 0)
388 			return (-1);
389 		(void) strlcpy(buf, strval, len);
390 		break;
391 
392 	default:
393 		abort();
394 	}
395 
396 	if (srctype)
397 		*srctype = src;
398 
399 	return (0);
400 }
401 
402 /*
403  * Check if the bootfs name has the same pool name as it is set to.
404  * Assuming bootfs is a valid dataset name.
405  */
406 static boolean_t
bootfs_name_valid(const char * pool,const char * bootfs)407 bootfs_name_valid(const char *pool, const char *bootfs)
408 {
409 	int len = strlen(pool);
410 	if (bootfs[0] == '\0')
411 		return (B_TRUE);
412 
413 	if (!zfs_name_valid(bootfs, ZFS_TYPE_FILESYSTEM|ZFS_TYPE_SNAPSHOT))
414 		return (B_FALSE);
415 
416 	if (strncmp(pool, bootfs, len) == 0 &&
417 	    (bootfs[len] == '/' || bootfs[len] == '\0'))
418 		return (B_TRUE);
419 
420 	return (B_FALSE);
421 }
422 
423 boolean_t
zpool_is_bootable(zpool_handle_t * zhp)424 zpool_is_bootable(zpool_handle_t *zhp)
425 {
426 	char bootfs[ZFS_MAX_DATASET_NAME_LEN];
427 
428 	return (zpool_get_prop(zhp, ZPOOL_PROP_BOOTFS, bootfs,
429 	    sizeof (bootfs), NULL, B_FALSE) == 0 && strncmp(bootfs, "-",
430 	    sizeof (bootfs)) != 0);
431 }
432 
433 
434 /*
435  * Given an nvlist of zpool properties to be set, validate that they are
436  * correct, and parse any numeric properties (index, boolean, etc) if they are
437  * specified as strings.
438  */
439 static nvlist_t *
zpool_valid_proplist(libzfs_handle_t * hdl,const char * poolname,nvlist_t * props,uint64_t version,prop_flags_t flags,char * errbuf)440 zpool_valid_proplist(libzfs_handle_t *hdl, const char *poolname,
441     nvlist_t *props, uint64_t version, prop_flags_t flags, char *errbuf)
442 {
443 	nvpair_t *elem;
444 	nvlist_t *retprops;
445 	zpool_prop_t prop;
446 	char *strval;
447 	uint64_t intval;
448 	char *slash, *check;
449 	struct stat64 statbuf;
450 	zpool_handle_t *zhp;
451 
452 	if (nvlist_alloc(&retprops, NV_UNIQUE_NAME, 0) != 0) {
453 		(void) no_memory(hdl);
454 		return (NULL);
455 	}
456 
457 	elem = NULL;
458 	while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
459 		const char *propname = nvpair_name(elem);
460 
461 		prop = zpool_name_to_prop(propname);
462 		if (prop == ZPOOL_PROP_INVAL && zpool_prop_feature(propname)) {
463 			int err;
464 			char *fname = strchr(propname, '@') + 1;
465 
466 			err = zfeature_lookup_name(fname, NULL);
467 			if (err != 0) {
468 				ASSERT3U(err, ==, ENOENT);
469 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
470 				    "invalid feature '%s', '%s'"), fname,
471 				    propname);
472 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
473 				goto error;
474 			}
475 
476 			if (nvpair_type(elem) != DATA_TYPE_STRING) {
477 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
478 				    "'%s' must be a string"), propname);
479 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
480 				goto error;
481 			}
482 
483 			(void) nvpair_value_string(elem, &strval);
484 			if (strcmp(strval, ZFS_FEATURE_ENABLED) != 0 &&
485 			    strcmp(strval, ZFS_FEATURE_DISABLED) != 0) {
486 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
487 				    "property '%s' can only be set to "
488 				    "'enabled' or 'disabled'"), propname);
489 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
490 				goto error;
491 			}
492 
493 			if (nvlist_add_uint64(retprops, propname, 0) != 0) {
494 				(void) no_memory(hdl);
495 				goto error;
496 			}
497 			continue;
498 		}
499 
500 		/*
501 		 * Make sure this property is valid and applies to this type.
502 		 */
503 		if (prop == ZPOOL_PROP_INVAL) {
504 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
505 			    "invalid property '%s'"), propname);
506 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
507 			goto error;
508 		}
509 
510 		if (zpool_prop_readonly(prop)) {
511 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' "
512 			    "is readonly"), propname);
513 			(void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
514 			goto error;
515 		}
516 
517 		if (zprop_parse_value(hdl, elem, prop, ZFS_TYPE_POOL, retprops,
518 		    &strval, &intval, errbuf) != 0)
519 			goto error;
520 
521 		/*
522 		 * Perform additional checking for specific properties.
523 		 */
524 		switch (prop) {
525 		case ZPOOL_PROP_VERSION:
526 			if (intval < version ||
527 			    !SPA_VERSION_IS_SUPPORTED(intval)) {
528 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
529 				    "property '%s' number %d is invalid."),
530 				    propname, intval);
531 				(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
532 				goto error;
533 			}
534 			break;
535 
536 		case ZPOOL_PROP_BOOTSIZE:
537 			if (!flags.create) {
538 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
539 				    "property '%s' can only be set during pool "
540 				    "creation"), propname);
541 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
542 				goto error;
543 			}
544 			break;
545 
546 		case ZPOOL_PROP_ASHIFT:
547 			if (intval != 0 &&
548 			    (intval < ASHIFT_MIN || intval > ASHIFT_MAX)) {
549 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
550 				    "invalid '%s=%d' property: only values "
551 				    "between %" PRId32 " and %" PRId32 " "
552 				    "are allowed.\n"),
553 				    propname, intval, ASHIFT_MIN, ASHIFT_MAX);
554 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
555 				goto error;
556 			}
557 			break;
558 
559 		case ZPOOL_PROP_BOOTFS:
560 			if (flags.create || flags.import) {
561 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
562 				    "property '%s' cannot be set at creation "
563 				    "or import time"), propname);
564 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
565 				goto error;
566 			}
567 
568 			if (version < SPA_VERSION_BOOTFS) {
569 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
570 				    "pool must be upgraded to support "
571 				    "'%s' property"), propname);
572 				(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
573 				goto error;
574 			}
575 
576 			/*
577 			 * bootfs property value has to be a dataset name and
578 			 * the dataset has to be in the same pool as it sets to.
579 			 */
580 			if (!bootfs_name_valid(poolname, strval)) {
581 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "'%s' "
582 				    "is an invalid name"), strval);
583 				(void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
584 				goto error;
585 			}
586 
587 			if ((zhp = zpool_open_canfail(hdl, poolname)) == NULL) {
588 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
589 				    "could not open pool '%s'"), poolname);
590 				(void) zfs_error(hdl, EZFS_OPENFAILED, errbuf);
591 				goto error;
592 			}
593 			zpool_close(zhp);
594 			break;
595 
596 		case ZPOOL_PROP_ALTROOT:
597 			if (!flags.create && !flags.import) {
598 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
599 				    "property '%s' can only be set during pool "
600 				    "creation or import"), propname);
601 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
602 				goto error;
603 			}
604 
605 			if (strval[0] != '/') {
606 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
607 				    "bad alternate root '%s'"), strval);
608 				(void) zfs_error(hdl, EZFS_BADPATH, errbuf);
609 				goto error;
610 			}
611 			break;
612 
613 		case ZPOOL_PROP_CACHEFILE:
614 			if (strval[0] == '\0')
615 				break;
616 
617 			if (strcmp(strval, "none") == 0)
618 				break;
619 
620 			if (strval[0] != '/') {
621 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
622 				    "property '%s' must be empty, an "
623 				    "absolute path, or 'none'"), propname);
624 				(void) zfs_error(hdl, EZFS_BADPATH, errbuf);
625 				goto error;
626 			}
627 
628 			slash = strrchr(strval, '/');
629 
630 			if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
631 			    strcmp(slash, "/..") == 0) {
632 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
633 				    "'%s' is not a valid file"), strval);
634 				(void) zfs_error(hdl, EZFS_BADPATH, errbuf);
635 				goto error;
636 			}
637 
638 			*slash = '\0';
639 
640 			if (strval[0] != '\0' &&
641 			    (stat64(strval, &statbuf) != 0 ||
642 			    !S_ISDIR(statbuf.st_mode))) {
643 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
644 				    "'%s' is not a valid directory"),
645 				    strval);
646 				(void) zfs_error(hdl, EZFS_BADPATH, errbuf);
647 				goto error;
648 			}
649 
650 			*slash = '/';
651 			break;
652 
653 		case ZPOOL_PROP_COMMENT:
654 			for (check = strval; *check != '\0'; check++) {
655 				if (!isprint(*check)) {
656 					zfs_error_aux(hdl,
657 					    dgettext(TEXT_DOMAIN,
658 					    "comment may only have printable "
659 					    "characters"));
660 					(void) zfs_error(hdl, EZFS_BADPROP,
661 					    errbuf);
662 					goto error;
663 				}
664 			}
665 			if (strlen(strval) > ZPROP_MAX_COMMENT) {
666 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
667 				    "comment must not exceed %d characters"),
668 				    ZPROP_MAX_COMMENT);
669 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
670 				goto error;
671 			}
672 			break;
673 
674 		case ZPOOL_PROP_READONLY:
675 			if (!flags.import) {
676 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
677 				    "property '%s' can only be set at "
678 				    "import time"), propname);
679 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
680 				goto error;
681 			}
682 			break;
683 
684 		case ZPOOL_PROP_TNAME:
685 			if (!flags.create) {
686 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
687 				    "property '%s' can only be set at "
688 				    "creation time"), propname);
689 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
690 				goto error;
691 			}
692 			break;
693 
694 		case ZPOOL_PROP_MULTIHOST:
695 			if (get_system_hostid() == 0) {
696 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
697 				    "requires a non-zero system hostid"));
698 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
699 				goto error;
700 			}
701 			break;
702 
703 		default:
704 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
705 			    "property '%s'(%d) not defined"), propname, prop);
706 			break;
707 		}
708 	}
709 
710 	return (retprops);
711 error:
712 	nvlist_free(retprops);
713 	return (NULL);
714 }
715 
716 /*
717  * Set zpool property : propname=propval.
718  */
719 int
zpool_set_prop(zpool_handle_t * zhp,const char * propname,const char * propval)720 zpool_set_prop(zpool_handle_t *zhp, const char *propname, const char *propval)
721 {
722 	zfs_cmd_t zc = { 0 };
723 	int ret = -1;
724 	char errbuf[1024];
725 	nvlist_t *nvl = NULL;
726 	nvlist_t *realprops;
727 	uint64_t version;
728 	prop_flags_t flags = { 0 };
729 
730 	(void) snprintf(errbuf, sizeof (errbuf),
731 	    dgettext(TEXT_DOMAIN, "cannot set property for '%s'"),
732 	    zhp->zpool_name);
733 
734 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
735 		return (no_memory(zhp->zpool_hdl));
736 
737 	if (nvlist_add_string(nvl, propname, propval) != 0) {
738 		nvlist_free(nvl);
739 		return (no_memory(zhp->zpool_hdl));
740 	}
741 
742 	version = zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL);
743 	if ((realprops = zpool_valid_proplist(zhp->zpool_hdl,
744 	    zhp->zpool_name, nvl, version, flags, errbuf)) == NULL) {
745 		nvlist_free(nvl);
746 		return (-1);
747 	}
748 
749 	nvlist_free(nvl);
750 	nvl = realprops;
751 
752 	/*
753 	 * Execute the corresponding ioctl() to set this property.
754 	 */
755 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
756 
757 	if (zcmd_write_src_nvlist(zhp->zpool_hdl, &zc, nvl) != 0) {
758 		nvlist_free(nvl);
759 		return (-1);
760 	}
761 
762 	ret = zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_SET_PROPS, &zc);
763 
764 	zcmd_free_nvlists(&zc);
765 	nvlist_free(nvl);
766 
767 	if (ret)
768 		(void) zpool_standard_error(zhp->zpool_hdl, errno, errbuf);
769 	else
770 		(void) zpool_props_refresh(zhp);
771 
772 	return (ret);
773 }
774 
775 int
zpool_expand_proplist(zpool_handle_t * zhp,zprop_list_t ** plp)776 zpool_expand_proplist(zpool_handle_t *zhp, zprop_list_t **plp)
777 {
778 	libzfs_handle_t *hdl = zhp->zpool_hdl;
779 	zprop_list_t *entry;
780 	char buf[ZFS_MAXPROPLEN];
781 	nvlist_t *features = NULL;
782 	zprop_list_t **last;
783 	boolean_t firstexpand = (NULL == *plp);
784 
785 	if (zprop_expand_list(hdl, plp, ZFS_TYPE_POOL) != 0)
786 		return (-1);
787 
788 	last = plp;
789 	while (*last != NULL)
790 		last = &(*last)->pl_next;
791 
792 	if ((*plp)->pl_all)
793 		features = zpool_get_features(zhp);
794 
795 	if ((*plp)->pl_all && firstexpand) {
796 		for (int i = 0; i < SPA_FEATURES; i++) {
797 			zprop_list_t *entry = zfs_alloc(hdl,
798 			    sizeof (zprop_list_t));
799 			entry->pl_prop = ZPROP_INVAL;
800 			entry->pl_user_prop = zfs_asprintf(hdl, "feature@%s",
801 			    spa_feature_table[i].fi_uname);
802 			entry->pl_width = strlen(entry->pl_user_prop);
803 			entry->pl_all = B_TRUE;
804 
805 			*last = entry;
806 			last = &entry->pl_next;
807 		}
808 	}
809 
810 	/* add any unsupported features */
811 	for (nvpair_t *nvp = nvlist_next_nvpair(features, NULL);
812 	    nvp != NULL; nvp = nvlist_next_nvpair(features, nvp)) {
813 		char *propname;
814 		boolean_t found;
815 		zprop_list_t *entry;
816 
817 		if (zfeature_is_supported(nvpair_name(nvp)))
818 			continue;
819 
820 		propname = zfs_asprintf(hdl, "unsupported@%s",
821 		    nvpair_name(nvp));
822 
823 		/*
824 		 * Before adding the property to the list make sure that no
825 		 * other pool already added the same property.
826 		 */
827 		found = B_FALSE;
828 		entry = *plp;
829 		while (entry != NULL) {
830 			if (entry->pl_user_prop != NULL &&
831 			    strcmp(propname, entry->pl_user_prop) == 0) {
832 				found = B_TRUE;
833 				break;
834 			}
835 			entry = entry->pl_next;
836 		}
837 		if (found) {
838 			free(propname);
839 			continue;
840 		}
841 
842 		entry = zfs_alloc(hdl, sizeof (zprop_list_t));
843 		entry->pl_prop = ZPROP_INVAL;
844 		entry->pl_user_prop = propname;
845 		entry->pl_width = strlen(entry->pl_user_prop);
846 		entry->pl_all = B_TRUE;
847 
848 		*last = entry;
849 		last = &entry->pl_next;
850 	}
851 
852 	for (entry = *plp; entry != NULL; entry = entry->pl_next) {
853 
854 		if (entry->pl_fixed)
855 			continue;
856 
857 		if (entry->pl_prop != ZPROP_INVAL &&
858 		    zpool_get_prop(zhp, entry->pl_prop, buf, sizeof (buf),
859 		    NULL, B_FALSE) == 0) {
860 			if (strlen(buf) > entry->pl_width)
861 				entry->pl_width = strlen(buf);
862 		}
863 	}
864 
865 	return (0);
866 }
867 
868 /*
869  * Get the state for the given feature on the given ZFS pool.
870  */
871 int
zpool_prop_get_feature(zpool_handle_t * zhp,const char * propname,char * buf,size_t len)872 zpool_prop_get_feature(zpool_handle_t *zhp, const char *propname, char *buf,
873     size_t len)
874 {
875 	uint64_t refcount;
876 	boolean_t found = B_FALSE;
877 	nvlist_t *features = zpool_get_features(zhp);
878 	boolean_t supported;
879 	const char *feature = strchr(propname, '@') + 1;
880 
881 	supported = zpool_prop_feature(propname);
882 	ASSERT(supported || zpool_prop_unsupported(propname));
883 
884 	/*
885 	 * Convert from feature name to feature guid. This conversion is
886 	 * unecessary for unsupported@... properties because they already
887 	 * use guids.
888 	 */
889 	if (supported) {
890 		int ret;
891 		spa_feature_t fid;
892 
893 		ret = zfeature_lookup_name(feature, &fid);
894 		if (ret != 0) {
895 			(void) strlcpy(buf, "-", len);
896 			return (ENOTSUP);
897 		}
898 		feature = spa_feature_table[fid].fi_guid;
899 	}
900 
901 	if (nvlist_lookup_uint64(features, feature, &refcount) == 0)
902 		found = B_TRUE;
903 
904 	if (supported) {
905 		if (!found) {
906 			(void) strlcpy(buf, ZFS_FEATURE_DISABLED, len);
907 		} else  {
908 			if (refcount == 0)
909 				(void) strlcpy(buf, ZFS_FEATURE_ENABLED, len);
910 			else
911 				(void) strlcpy(buf, ZFS_FEATURE_ACTIVE, len);
912 		}
913 	} else {
914 		if (found) {
915 			if (refcount == 0) {
916 				(void) strcpy(buf, ZFS_UNSUPPORTED_INACTIVE);
917 			} else {
918 				(void) strcpy(buf, ZFS_UNSUPPORTED_READONLY);
919 			}
920 		} else {
921 			(void) strlcpy(buf, "-", len);
922 			return (ENOTSUP);
923 		}
924 	}
925 
926 	return (0);
927 }
928 
929 /*
930  * Don't start the slice at the default block of 34; many storage
931  * devices will use a stripe width of 128k, so start there instead.
932  */
933 #define	NEW_START_BLOCK	256
934 
935 /*
936  * Validate the given pool name, optionally putting an extended error message in
937  * 'buf'.
938  */
939 boolean_t
zpool_name_valid(libzfs_handle_t * hdl,boolean_t isopen,const char * pool)940 zpool_name_valid(libzfs_handle_t *hdl, boolean_t isopen, const char *pool)
941 {
942 	namecheck_err_t why;
943 	char what;
944 	int ret;
945 
946 	ret = pool_namecheck(pool, &why, &what);
947 
948 	/*
949 	 * The rules for reserved pool names were extended at a later point.
950 	 * But we need to support users with existing pools that may now be
951 	 * invalid.  So we only check for this expanded set of names during a
952 	 * create (or import), and only in userland.
953 	 */
954 	if (ret == 0 && !isopen &&
955 	    (strncmp(pool, "mirror", 6) == 0 ||
956 	    strncmp(pool, "raidz", 5) == 0 ||
957 	    strncmp(pool, "spare", 5) == 0 ||
958 	    strcmp(pool, "log") == 0)) {
959 		if (hdl != NULL)
960 			zfs_error_aux(hdl,
961 			    dgettext(TEXT_DOMAIN, "name is reserved"));
962 		return (B_FALSE);
963 	}
964 
965 
966 	if (ret != 0) {
967 		if (hdl != NULL) {
968 			switch (why) {
969 			case NAME_ERR_TOOLONG:
970 				zfs_error_aux(hdl,
971 				    dgettext(TEXT_DOMAIN, "name is too long"));
972 				break;
973 
974 			case NAME_ERR_INVALCHAR:
975 				zfs_error_aux(hdl,
976 				    dgettext(TEXT_DOMAIN, "invalid character "
977 				    "'%c' in pool name"), what);
978 				break;
979 
980 			case NAME_ERR_NOLETTER:
981 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
982 				    "name must begin with a letter"));
983 				break;
984 
985 			case NAME_ERR_RESERVED:
986 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
987 				    "name is reserved"));
988 				break;
989 
990 			case NAME_ERR_DISKLIKE:
991 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
992 				    "pool name is reserved"));
993 				break;
994 
995 			case NAME_ERR_LEADING_SLASH:
996 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
997 				    "leading slash in name"));
998 				break;
999 
1000 			case NAME_ERR_EMPTY_COMPONENT:
1001 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1002 				    "empty component in name"));
1003 				break;
1004 
1005 			case NAME_ERR_TRAILING_SLASH:
1006 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1007 				    "trailing slash in name"));
1008 				break;
1009 
1010 			case NAME_ERR_MULTIPLE_DELIMITERS:
1011 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1012 				    "multiple '@' and/or '#' delimiters in "
1013 				    "name"));
1014 				break;
1015 
1016 			default:
1017 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1018 				    "(%d) not defined"), why);
1019 				break;
1020 			}
1021 		}
1022 		return (B_FALSE);
1023 	}
1024 
1025 	return (B_TRUE);
1026 }
1027 
1028 /*
1029  * Open a handle to the given pool, even if the pool is currently in the FAULTED
1030  * state.
1031  */
1032 zpool_handle_t *
zpool_open_canfail(libzfs_handle_t * hdl,const char * pool)1033 zpool_open_canfail(libzfs_handle_t *hdl, const char *pool)
1034 {
1035 	zpool_handle_t *zhp;
1036 	boolean_t missing;
1037 
1038 	/*
1039 	 * Make sure the pool name is valid.
1040 	 */
1041 	if (!zpool_name_valid(hdl, B_TRUE, pool)) {
1042 		(void) zfs_error_fmt(hdl, EZFS_INVALIDNAME,
1043 		    dgettext(TEXT_DOMAIN, "cannot open '%s'"),
1044 		    pool);
1045 		return (NULL);
1046 	}
1047 
1048 	if ((zhp = zfs_alloc(hdl, sizeof (zpool_handle_t))) == NULL)
1049 		return (NULL);
1050 
1051 	zhp->zpool_hdl = hdl;
1052 	(void) strlcpy(zhp->zpool_name, pool, sizeof (zhp->zpool_name));
1053 
1054 	if (zpool_refresh_stats(zhp, &missing) != 0) {
1055 		zpool_close(zhp);
1056 		return (NULL);
1057 	}
1058 
1059 	if (missing) {
1060 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "no such pool"));
1061 		(void) zfs_error_fmt(hdl, EZFS_NOENT,
1062 		    dgettext(TEXT_DOMAIN, "cannot open '%s'"), pool);
1063 		zpool_close(zhp);
1064 		return (NULL);
1065 	}
1066 
1067 	return (zhp);
1068 }
1069 
1070 /*
1071  * Like the above, but silent on error.  Used when iterating over pools (because
1072  * the configuration cache may be out of date).
1073  */
1074 int
zpool_open_silent(libzfs_handle_t * hdl,const char * pool,zpool_handle_t ** ret)1075 zpool_open_silent(libzfs_handle_t *hdl, const char *pool, zpool_handle_t **ret)
1076 {
1077 	zpool_handle_t *zhp;
1078 	boolean_t missing;
1079 
1080 	if ((zhp = zfs_alloc(hdl, sizeof (zpool_handle_t))) == NULL)
1081 		return (-1);
1082 
1083 	zhp->zpool_hdl = hdl;
1084 	(void) strlcpy(zhp->zpool_name, pool, sizeof (zhp->zpool_name));
1085 
1086 	if (zpool_refresh_stats(zhp, &missing) != 0) {
1087 		zpool_close(zhp);
1088 		return (-1);
1089 	}
1090 
1091 	if (missing) {
1092 		zpool_close(zhp);
1093 		*ret = NULL;
1094 		return (0);
1095 	}
1096 
1097 	*ret = zhp;
1098 	return (0);
1099 }
1100 
1101 /*
1102  * Similar to zpool_open_canfail(), but refuses to open pools in the faulted
1103  * state.
1104  */
1105 zpool_handle_t *
zpool_open(libzfs_handle_t * hdl,const char * pool)1106 zpool_open(libzfs_handle_t *hdl, const char *pool)
1107 {
1108 	zpool_handle_t *zhp;
1109 
1110 	if ((zhp = zpool_open_canfail(hdl, pool)) == NULL)
1111 		return (NULL);
1112 
1113 	if (zhp->zpool_state == POOL_STATE_UNAVAIL) {
1114 		(void) zfs_error_fmt(hdl, EZFS_POOLUNAVAIL,
1115 		    dgettext(TEXT_DOMAIN, "cannot open '%s'"), zhp->zpool_name);
1116 		zpool_close(zhp);
1117 		return (NULL);
1118 	}
1119 
1120 	return (zhp);
1121 }
1122 
1123 /*
1124  * Close the handle.  Simply frees the memory associated with the handle.
1125  */
1126 void
zpool_close(zpool_handle_t * zhp)1127 zpool_close(zpool_handle_t *zhp)
1128 {
1129 	nvlist_free(zhp->zpool_config);
1130 	nvlist_free(zhp->zpool_old_config);
1131 	nvlist_free(zhp->zpool_props);
1132 	free(zhp);
1133 }
1134 
1135 /*
1136  * Return the name of the pool.
1137  */
1138 const char *
zpool_get_name(zpool_handle_t * zhp)1139 zpool_get_name(zpool_handle_t *zhp)
1140 {
1141 	return (zhp->zpool_name);
1142 }
1143 
1144 
1145 /*
1146  * Return the state of the pool (ACTIVE or UNAVAILABLE)
1147  */
1148 int
zpool_get_state(zpool_handle_t * zhp)1149 zpool_get_state(zpool_handle_t *zhp)
1150 {
1151 	return (zhp->zpool_state);
1152 }
1153 
1154 /*
1155  * Check if vdev list contains a special vdev
1156  */
1157 static boolean_t
zpool_has_special_vdev(nvlist_t * nvroot)1158 zpool_has_special_vdev(nvlist_t *nvroot)
1159 {
1160 	nvlist_t **child;
1161 	uint_t children;
1162 
1163 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN, &child,
1164 	    &children) == 0) {
1165 		for (uint_t c = 0; c < children; c++) {
1166 			char *bias;
1167 
1168 			if (nvlist_lookup_string(child[c],
1169 			    ZPOOL_CONFIG_ALLOCATION_BIAS, &bias) == 0 &&
1170 			    strcmp(bias, VDEV_ALLOC_BIAS_SPECIAL) == 0) {
1171 				return (B_TRUE);
1172 			}
1173 		}
1174 	}
1175 	return (B_FALSE);
1176 }
1177 
1178 /*
1179  * Create the named pool, using the provided vdev list.  It is assumed
1180  * that the consumer has already validated the contents of the nvlist, so we
1181  * don't have to worry about error semantics.
1182  */
1183 int
zpool_create(libzfs_handle_t * hdl,const char * pool,nvlist_t * nvroot,nvlist_t * props,nvlist_t * fsprops)1184 zpool_create(libzfs_handle_t *hdl, const char *pool, nvlist_t *nvroot,
1185     nvlist_t *props, nvlist_t *fsprops)
1186 {
1187 	zfs_cmd_t zc = { 0 };
1188 	nvlist_t *zc_fsprops = NULL;
1189 	nvlist_t *zc_props = NULL;
1190 	nvlist_t *hidden_args = NULL;
1191 	uint8_t *wkeydata = NULL;
1192 	uint_t wkeylen = 0;
1193 	char msg[1024];
1194 	int ret = -1;
1195 
1196 	(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1197 	    "cannot create '%s'"), pool);
1198 
1199 	if (!zpool_name_valid(hdl, B_FALSE, pool))
1200 		return (zfs_error(hdl, EZFS_INVALIDNAME, msg));
1201 
1202 	if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
1203 		return (-1);
1204 
1205 	if (props) {
1206 		prop_flags_t flags = { .create = B_TRUE, .import = B_FALSE };
1207 
1208 		if ((zc_props = zpool_valid_proplist(hdl, pool, props,
1209 		    SPA_VERSION_1, flags, msg)) == NULL) {
1210 			goto create_failed;
1211 		}
1212 	}
1213 
1214 	if (fsprops) {
1215 		uint64_t zoned;
1216 		char *zonestr;
1217 
1218 		zoned = ((nvlist_lookup_string(fsprops,
1219 		    zfs_prop_to_name(ZFS_PROP_ZONED), &zonestr) == 0) &&
1220 		    strcmp(zonestr, "on") == 0);
1221 
1222 		if ((zc_fsprops = zfs_valid_proplist(hdl, ZFS_TYPE_FILESYSTEM,
1223 		    fsprops, zoned, NULL, NULL, B_TRUE, msg)) == NULL) {
1224 			goto create_failed;
1225 		}
1226 
1227 		if (nvlist_exists(zc_fsprops,
1228 		    zfs_prop_to_name(ZFS_PROP_SPECIAL_SMALL_BLOCKS)) &&
1229 		    !zpool_has_special_vdev(nvroot)) {
1230 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1231 			    "%s property requires a special vdev"),
1232 			    zfs_prop_to_name(ZFS_PROP_SPECIAL_SMALL_BLOCKS));
1233 			(void) zfs_error(hdl, EZFS_BADPROP, msg);
1234 			goto create_failed;
1235 		}
1236 
1237 		if (!zc_props &&
1238 		    (nvlist_alloc(&zc_props, NV_UNIQUE_NAME, 0) != 0)) {
1239 			goto create_failed;
1240 		}
1241 		if (zfs_crypto_create(hdl, NULL, zc_fsprops, props, B_TRUE,
1242 		    &wkeydata, &wkeylen) != 0) {
1243 			(void) zfs_error(hdl, EZFS_CRYPTOFAILED, msg);
1244 			goto create_failed;
1245 		}
1246 		if (nvlist_add_nvlist(zc_props,
1247 		    ZPOOL_ROOTFS_PROPS, zc_fsprops) != 0) {
1248 			goto create_failed;
1249 		}
1250 		if (wkeydata != NULL) {
1251 			if (nvlist_alloc(&hidden_args, NV_UNIQUE_NAME, 0) != 0)
1252 				goto create_failed;
1253 
1254 			if (nvlist_add_uint8_array(hidden_args, "wkeydata",
1255 			    wkeydata, wkeylen) != 0)
1256 				goto create_failed;
1257 
1258 			if (nvlist_add_nvlist(zc_props, ZPOOL_HIDDEN_ARGS,
1259 			    hidden_args) != 0)
1260 				goto create_failed;
1261 		}
1262 	}
1263 
1264 	if (zc_props && zcmd_write_src_nvlist(hdl, &zc, zc_props) != 0)
1265 		goto create_failed;
1266 
1267 	(void) strlcpy(zc.zc_name, pool, sizeof (zc.zc_name));
1268 
1269 	if ((ret = zfs_ioctl(hdl, ZFS_IOC_POOL_CREATE, &zc)) != 0) {
1270 
1271 		zcmd_free_nvlists(&zc);
1272 		nvlist_free(zc_props);
1273 		nvlist_free(zc_fsprops);
1274 		nvlist_free(hidden_args);
1275 		if (wkeydata != NULL)
1276 			free(wkeydata);
1277 
1278 		switch (errno) {
1279 		case EBUSY:
1280 			/*
1281 			 * This can happen if the user has specified the same
1282 			 * device multiple times.  We can't reliably detect this
1283 			 * until we try to add it and see we already have a
1284 			 * label.
1285 			 */
1286 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1287 			    "one or more vdevs refer to the same device"));
1288 			return (zfs_error(hdl, EZFS_BADDEV, msg));
1289 
1290 		case ERANGE:
1291 			/*
1292 			 * This happens if the record size is smaller or larger
1293 			 * than the allowed size range, or not a power of 2.
1294 			 *
1295 			 * NOTE: although zfs_valid_proplist is called earlier,
1296 			 * this case may have slipped through since the
1297 			 * pool does not exist yet and it is therefore
1298 			 * impossible to read properties e.g. max blocksize
1299 			 * from the pool.
1300 			 */
1301 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1302 			    "record size invalid"));
1303 			return (zfs_error(hdl, EZFS_BADPROP, msg));
1304 
1305 		case EOVERFLOW:
1306 			/*
1307 			 * This occurs when one of the devices is below
1308 			 * SPA_MINDEVSIZE.  Unfortunately, we can't detect which
1309 			 * device was the problem device since there's no
1310 			 * reliable way to determine device size from userland.
1311 			 */
1312 			{
1313 				char buf[64];
1314 
1315 				zfs_nicenum(SPA_MINDEVSIZE, buf, sizeof (buf));
1316 
1317 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1318 				    "one or more devices is less than the "
1319 				    "minimum size (%s)"), buf);
1320 			}
1321 			return (zfs_error(hdl, EZFS_BADDEV, msg));
1322 
1323 		case ENOSPC:
1324 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1325 			    "one or more devices is out of space"));
1326 			return (zfs_error(hdl, EZFS_BADDEV, msg));
1327 
1328 		default:
1329 			return (zpool_standard_error(hdl, errno, msg));
1330 		}
1331 	}
1332 
1333 create_failed:
1334 	zcmd_free_nvlists(&zc);
1335 	nvlist_free(zc_props);
1336 	nvlist_free(zc_fsprops);
1337 	nvlist_free(hidden_args);
1338 	if (wkeydata != NULL)
1339 		free(wkeydata);
1340 	return (ret);
1341 }
1342 
1343 /*
1344  * Destroy the given pool.  It is up to the caller to ensure that there are no
1345  * datasets left in the pool.
1346  */
1347 int
zpool_destroy(zpool_handle_t * zhp,const char * log_str)1348 zpool_destroy(zpool_handle_t *zhp, const char *log_str)
1349 {
1350 	zfs_cmd_t zc = { 0 };
1351 	zfs_handle_t *zfp = NULL;
1352 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1353 	char msg[1024];
1354 
1355 	if (zhp->zpool_state == POOL_STATE_ACTIVE &&
1356 	    (zfp = zfs_open(hdl, zhp->zpool_name, ZFS_TYPE_FILESYSTEM)) == NULL)
1357 		return (-1);
1358 
1359 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1360 	zc.zc_history = (uint64_t)(uintptr_t)log_str;
1361 
1362 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_DESTROY, &zc) != 0) {
1363 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1364 		    "cannot destroy '%s'"), zhp->zpool_name);
1365 
1366 		if (errno == EROFS) {
1367 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1368 			    "one or more devices is read only"));
1369 			(void) zfs_error(hdl, EZFS_BADDEV, msg);
1370 		} else {
1371 			(void) zpool_standard_error(hdl, errno, msg);
1372 		}
1373 
1374 		if (zfp)
1375 			zfs_close(zfp);
1376 		return (-1);
1377 	}
1378 
1379 	if (zfp) {
1380 		remove_mountpoint(zfp);
1381 		zfs_close(zfp);
1382 	}
1383 
1384 	return (0);
1385 }
1386 
1387 /*
1388  * Create a checkpoint in the given pool.
1389  */
1390 int
zpool_checkpoint(zpool_handle_t * zhp)1391 zpool_checkpoint(zpool_handle_t *zhp)
1392 {
1393 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1394 	char msg[1024];
1395 	int error;
1396 
1397 	error = lzc_pool_checkpoint(zhp->zpool_name);
1398 	if (error != 0) {
1399 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1400 		    "cannot checkpoint '%s'"), zhp->zpool_name);
1401 		(void) zpool_standard_error(hdl, error, msg);
1402 		return (-1);
1403 	}
1404 
1405 	return (0);
1406 }
1407 
1408 /*
1409  * Discard the checkpoint from the given pool.
1410  */
1411 int
zpool_discard_checkpoint(zpool_handle_t * zhp)1412 zpool_discard_checkpoint(zpool_handle_t *zhp)
1413 {
1414 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1415 	char msg[1024];
1416 	int error;
1417 
1418 	error = lzc_pool_checkpoint_discard(zhp->zpool_name);
1419 	if (error != 0) {
1420 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1421 		    "cannot discard checkpoint in '%s'"), zhp->zpool_name);
1422 		(void) zpool_standard_error(hdl, error, msg);
1423 		return (-1);
1424 	}
1425 
1426 	return (0);
1427 }
1428 
1429 /*
1430  * Add the given vdevs to the pool.  The caller must have already performed the
1431  * necessary verification to ensure that the vdev specification is well-formed.
1432  */
1433 int
zpool_add(zpool_handle_t * zhp,nvlist_t * nvroot)1434 zpool_add(zpool_handle_t *zhp, nvlist_t *nvroot)
1435 {
1436 	zfs_cmd_t zc = { 0 };
1437 	int ret;
1438 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1439 	char msg[1024];
1440 	nvlist_t **spares, **l2cache;
1441 	uint_t nspares, nl2cache;
1442 
1443 	(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1444 	    "cannot add to '%s'"), zhp->zpool_name);
1445 
1446 	if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) <
1447 	    SPA_VERSION_SPARES &&
1448 	    nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1449 	    &spares, &nspares) == 0) {
1450 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be "
1451 		    "upgraded to add hot spares"));
1452 		return (zfs_error(hdl, EZFS_BADVERSION, msg));
1453 	}
1454 
1455 	if (zpool_get_prop_int(zhp, ZPOOL_PROP_VERSION, NULL) <
1456 	    SPA_VERSION_L2CACHE &&
1457 	    nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1458 	    &l2cache, &nl2cache) == 0) {
1459 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool must be "
1460 		    "upgraded to add cache devices"));
1461 		return (zfs_error(hdl, EZFS_BADVERSION, msg));
1462 	}
1463 
1464 	if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
1465 		return (-1);
1466 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1467 
1468 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_ADD, &zc) != 0) {
1469 		switch (errno) {
1470 		case EBUSY:
1471 			/*
1472 			 * This can happen if the user has specified the same
1473 			 * device multiple times.  We can't reliably detect this
1474 			 * until we try to add it and see we already have a
1475 			 * label.
1476 			 */
1477 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1478 			    "one or more vdevs refer to the same device"));
1479 			(void) zfs_error(hdl, EZFS_BADDEV, msg);
1480 			break;
1481 
1482 		case EINVAL:
1483 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1484 			    "invalid config; a pool with removing/removed "
1485 			    "vdevs does not support adding raidz vdevs"));
1486 			(void) zfs_error(hdl, EZFS_BADDEV, msg);
1487 			break;
1488 
1489 		case EOVERFLOW:
1490 			/*
1491 			 * This occurrs when one of the devices is below
1492 			 * SPA_MINDEVSIZE.  Unfortunately, we can't detect which
1493 			 * device was the problem device since there's no
1494 			 * reliable way to determine device size from userland.
1495 			 */
1496 			{
1497 				char buf[64];
1498 
1499 				zfs_nicenum(SPA_MINDEVSIZE, buf, sizeof (buf));
1500 
1501 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1502 				    "device is less than the minimum "
1503 				    "size (%s)"), buf);
1504 			}
1505 			(void) zfs_error(hdl, EZFS_BADDEV, msg);
1506 			break;
1507 
1508 		case ENOTSUP:
1509 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1510 			    "pool must be upgraded to add these vdevs"));
1511 			(void) zfs_error(hdl, EZFS_BADVERSION, msg);
1512 			break;
1513 
1514 		default:
1515 			(void) zpool_standard_error(hdl, errno, msg);
1516 		}
1517 
1518 		ret = -1;
1519 	} else {
1520 		ret = 0;
1521 	}
1522 
1523 	zcmd_free_nvlists(&zc);
1524 
1525 	return (ret);
1526 }
1527 
1528 /*
1529  * Exports the pool from the system.  The caller must ensure that there are no
1530  * mounted datasets in the pool.
1531  */
1532 static int
zpool_export_common(zpool_handle_t * zhp,boolean_t force,boolean_t hardforce,const char * log_str)1533 zpool_export_common(zpool_handle_t *zhp, boolean_t force, boolean_t hardforce,
1534     const char *log_str)
1535 {
1536 	zfs_cmd_t zc = { 0 };
1537 	char msg[1024];
1538 
1539 	(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
1540 	    "cannot export '%s'"), zhp->zpool_name);
1541 
1542 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
1543 	zc.zc_cookie = force;
1544 	zc.zc_guid = hardforce;
1545 	zc.zc_history = (uint64_t)(uintptr_t)log_str;
1546 
1547 	if (zfs_ioctl(zhp->zpool_hdl, ZFS_IOC_POOL_EXPORT, &zc) != 0) {
1548 		switch (errno) {
1549 		case EXDEV:
1550 			zfs_error_aux(zhp->zpool_hdl, dgettext(TEXT_DOMAIN,
1551 			    "use '-f' to override the following errors:\n"
1552 			    "'%s' has an active shared spare which could be"
1553 			    " used by other pools once '%s' is exported."),
1554 			    zhp->zpool_name, zhp->zpool_name);
1555 			return (zfs_error(zhp->zpool_hdl, EZFS_ACTIVE_SPARE,
1556 			    msg));
1557 		default:
1558 			return (zpool_standard_error_fmt(zhp->zpool_hdl, errno,
1559 			    msg));
1560 		}
1561 	}
1562 
1563 	return (0);
1564 }
1565 
1566 int
zpool_export(zpool_handle_t * zhp,boolean_t force,const char * log_str)1567 zpool_export(zpool_handle_t *zhp, boolean_t force, const char *log_str)
1568 {
1569 	return (zpool_export_common(zhp, force, B_FALSE, log_str));
1570 }
1571 
1572 int
zpool_export_force(zpool_handle_t * zhp,const char * log_str)1573 zpool_export_force(zpool_handle_t *zhp, const char *log_str)
1574 {
1575 	return (zpool_export_common(zhp, B_TRUE, B_TRUE, log_str));
1576 }
1577 
1578 static void
zpool_rewind_exclaim(libzfs_handle_t * hdl,const char * name,boolean_t dryrun,nvlist_t * config)1579 zpool_rewind_exclaim(libzfs_handle_t *hdl, const char *name, boolean_t dryrun,
1580     nvlist_t *config)
1581 {
1582 	nvlist_t *nv = NULL;
1583 	uint64_t rewindto;
1584 	int64_t loss = -1;
1585 	struct tm t;
1586 	char timestr[128];
1587 
1588 	if (!hdl->libzfs_printerr || config == NULL)
1589 		return;
1590 
1591 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nv) != 0 ||
1592 	    nvlist_lookup_nvlist(nv, ZPOOL_CONFIG_REWIND_INFO, &nv) != 0) {
1593 		return;
1594 	}
1595 
1596 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_TIME, &rewindto) != 0)
1597 		return;
1598 	(void) nvlist_lookup_int64(nv, ZPOOL_CONFIG_REWIND_TIME, &loss);
1599 
1600 	if (localtime_r((time_t *)&rewindto, &t) != NULL &&
1601 	    strftime(timestr, 128, 0, &t) != 0) {
1602 		if (dryrun) {
1603 			(void) printf(dgettext(TEXT_DOMAIN,
1604 			    "Would be able to return %s "
1605 			    "to its state as of %s.\n"),
1606 			    name, timestr);
1607 		} else {
1608 			(void) printf(dgettext(TEXT_DOMAIN,
1609 			    "Pool %s returned to its state as of %s.\n"),
1610 			    name, timestr);
1611 		}
1612 		if (loss > 120) {
1613 			(void) printf(dgettext(TEXT_DOMAIN,
1614 			    "%s approximately %lld "),
1615 			    dryrun ? "Would discard" : "Discarded",
1616 			    (loss + 30) / 60);
1617 			(void) printf(dgettext(TEXT_DOMAIN,
1618 			    "minutes of transactions.\n"));
1619 		} else if (loss > 0) {
1620 			(void) printf(dgettext(TEXT_DOMAIN,
1621 			    "%s approximately %lld "),
1622 			    dryrun ? "Would discard" : "Discarded", loss);
1623 			(void) printf(dgettext(TEXT_DOMAIN,
1624 			    "seconds of transactions.\n"));
1625 		}
1626 	}
1627 }
1628 
1629 void
zpool_explain_recover(libzfs_handle_t * hdl,const char * name,int reason,nvlist_t * config)1630 zpool_explain_recover(libzfs_handle_t *hdl, const char *name, int reason,
1631     nvlist_t *config)
1632 {
1633 	nvlist_t *nv = NULL;
1634 	int64_t loss = -1;
1635 	uint64_t edata = UINT64_MAX;
1636 	uint64_t rewindto;
1637 	struct tm t;
1638 	char timestr[128];
1639 
1640 	if (!hdl->libzfs_printerr)
1641 		return;
1642 
1643 	if (reason >= 0)
1644 		(void) printf(dgettext(TEXT_DOMAIN, "action: "));
1645 	else
1646 		(void) printf(dgettext(TEXT_DOMAIN, "\t"));
1647 
1648 	/* All attempted rewinds failed if ZPOOL_CONFIG_LOAD_TIME missing */
1649 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nv) != 0 ||
1650 	    nvlist_lookup_nvlist(nv, ZPOOL_CONFIG_REWIND_INFO, &nv) != 0 ||
1651 	    nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_TIME, &rewindto) != 0)
1652 		goto no_info;
1653 
1654 	(void) nvlist_lookup_int64(nv, ZPOOL_CONFIG_REWIND_TIME, &loss);
1655 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_LOAD_DATA_ERRORS,
1656 	    &edata);
1657 
1658 	(void) printf(dgettext(TEXT_DOMAIN,
1659 	    "Recovery is possible, but will result in some data loss.\n"));
1660 
1661 	if (localtime_r((time_t *)&rewindto, &t) != NULL &&
1662 	    strftime(timestr, 128, 0, &t) != 0) {
1663 		(void) printf(dgettext(TEXT_DOMAIN,
1664 		    "\tReturning the pool to its state as of %s\n"
1665 		    "\tshould correct the problem.  "),
1666 		    timestr);
1667 	} else {
1668 		(void) printf(dgettext(TEXT_DOMAIN,
1669 		    "\tReverting the pool to an earlier state "
1670 		    "should correct the problem.\n\t"));
1671 	}
1672 
1673 	if (loss > 120) {
1674 		(void) printf(dgettext(TEXT_DOMAIN,
1675 		    "Approximately %lld minutes of data\n"
1676 		    "\tmust be discarded, irreversibly.  "), (loss + 30) / 60);
1677 	} else if (loss > 0) {
1678 		(void) printf(dgettext(TEXT_DOMAIN,
1679 		    "Approximately %lld seconds of data\n"
1680 		    "\tmust be discarded, irreversibly.  "), loss);
1681 	}
1682 	if (edata != 0 && edata != UINT64_MAX) {
1683 		if (edata == 1) {
1684 			(void) printf(dgettext(TEXT_DOMAIN,
1685 			    "After rewind, at least\n"
1686 			    "\tone persistent user-data error will remain.  "));
1687 		} else {
1688 			(void) printf(dgettext(TEXT_DOMAIN,
1689 			    "After rewind, several\n"
1690 			    "\tpersistent user-data errors will remain.  "));
1691 		}
1692 	}
1693 	(void) printf(dgettext(TEXT_DOMAIN,
1694 	    "Recovery can be attempted\n\tby executing 'zpool %s -F %s'.  "),
1695 	    reason >= 0 ? "clear" : "import", name);
1696 
1697 	(void) printf(dgettext(TEXT_DOMAIN,
1698 	    "A scrub of the pool\n"
1699 	    "\tis strongly recommended after recovery.\n"));
1700 	return;
1701 
1702 no_info:
1703 	(void) printf(dgettext(TEXT_DOMAIN,
1704 	    "Destroy and re-create the pool from\n\ta backup source.\n"));
1705 }
1706 
1707 /*
1708  * zpool_import() is a contracted interface. Should be kept the same
1709  * if possible.
1710  *
1711  * Applications should use zpool_import_props() to import a pool with
1712  * new properties value to be set.
1713  */
1714 int
zpool_import(libzfs_handle_t * hdl,nvlist_t * config,const char * newname,char * altroot)1715 zpool_import(libzfs_handle_t *hdl, nvlist_t *config, const char *newname,
1716     char *altroot)
1717 {
1718 	nvlist_t *props = NULL;
1719 	int ret;
1720 
1721 	if (altroot != NULL) {
1722 		if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
1723 			return (zfs_error_fmt(hdl, EZFS_NOMEM,
1724 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1725 			    newname));
1726 		}
1727 
1728 		if (nvlist_add_string(props,
1729 		    zpool_prop_to_name(ZPOOL_PROP_ALTROOT), altroot) != 0 ||
1730 		    nvlist_add_string(props,
1731 		    zpool_prop_to_name(ZPOOL_PROP_CACHEFILE), "none") != 0) {
1732 			nvlist_free(props);
1733 			return (zfs_error_fmt(hdl, EZFS_NOMEM,
1734 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1735 			    newname));
1736 		}
1737 	}
1738 
1739 	ret = zpool_import_props(hdl, config, newname, props,
1740 	    ZFS_IMPORT_NORMAL);
1741 	nvlist_free(props);
1742 	return (ret);
1743 }
1744 
1745 static void
print_vdev_tree(libzfs_handle_t * hdl,const char * name,nvlist_t * nv,int indent)1746 print_vdev_tree(libzfs_handle_t *hdl, const char *name, nvlist_t *nv,
1747     int indent)
1748 {
1749 	nvlist_t **child;
1750 	uint_t c, children;
1751 	char *vname;
1752 	uint64_t is_log = 0;
1753 
1754 	(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG,
1755 	    &is_log);
1756 
1757 	if (name != NULL)
1758 		(void) printf("\t%*s%s%s\n", indent, "", name,
1759 		    is_log ? " [log]" : "");
1760 
1761 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1762 	    &child, &children) != 0)
1763 		return;
1764 
1765 	for (c = 0; c < children; c++) {
1766 		vname = zpool_vdev_name(hdl, NULL, child[c], VDEV_NAME_TYPE_ID);
1767 		print_vdev_tree(hdl, vname, child[c], indent + 2);
1768 		free(vname);
1769 	}
1770 }
1771 
1772 void
zpool_print_unsup_feat(nvlist_t * config)1773 zpool_print_unsup_feat(nvlist_t *config)
1774 {
1775 	nvlist_t *nvinfo, *unsup_feat;
1776 
1777 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_LOAD_INFO, &nvinfo) ==
1778 	    0);
1779 	verify(nvlist_lookup_nvlist(nvinfo, ZPOOL_CONFIG_UNSUP_FEAT,
1780 	    &unsup_feat) == 0);
1781 
1782 	for (nvpair_t *nvp = nvlist_next_nvpair(unsup_feat, NULL); nvp != NULL;
1783 	    nvp = nvlist_next_nvpair(unsup_feat, nvp)) {
1784 		char *desc;
1785 
1786 		verify(nvpair_type(nvp) == DATA_TYPE_STRING);
1787 		verify(nvpair_value_string(nvp, &desc) == 0);
1788 
1789 		if (strlen(desc) > 0)
1790 			(void) printf("\t%s (%s)\n", nvpair_name(nvp), desc);
1791 		else
1792 			(void) printf("\t%s\n", nvpair_name(nvp));
1793 	}
1794 }
1795 
1796 /*
1797  * Import the given pool using the known configuration and a list of
1798  * properties to be set. The configuration should have come from
1799  * zpool_find_import(). The 'newname' parameters control whether the pool
1800  * is imported with a different name.
1801  */
1802 int
zpool_import_props(libzfs_handle_t * hdl,nvlist_t * config,const char * newname,nvlist_t * props,int flags)1803 zpool_import_props(libzfs_handle_t *hdl, nvlist_t *config, const char *newname,
1804     nvlist_t *props, int flags)
1805 {
1806 	zfs_cmd_t zc = { 0 };
1807 	zpool_load_policy_t policy;
1808 	nvlist_t *nv = NULL;
1809 	nvlist_t *nvinfo = NULL;
1810 	nvlist_t *missing = NULL;
1811 	char *thename;
1812 	char *origname;
1813 	int ret;
1814 	int error = 0;
1815 	char errbuf[1024];
1816 
1817 	verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1818 	    &origname) == 0);
1819 
1820 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1821 	    "cannot import pool '%s'"), origname);
1822 
1823 	if (newname != NULL) {
1824 		if (!zpool_name_valid(hdl, B_FALSE, newname))
1825 			return (zfs_error_fmt(hdl, EZFS_INVALIDNAME,
1826 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1827 			    newname));
1828 		thename = (char *)newname;
1829 	} else {
1830 		thename = origname;
1831 	}
1832 
1833 	if (props != NULL) {
1834 		uint64_t version;
1835 		prop_flags_t flags = { .create = B_FALSE, .import = B_TRUE };
1836 
1837 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
1838 		    &version) == 0);
1839 
1840 		if ((props = zpool_valid_proplist(hdl, origname,
1841 		    props, version, flags, errbuf)) == NULL)
1842 			return (-1);
1843 		if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) {
1844 			nvlist_free(props);
1845 			return (-1);
1846 		}
1847 		nvlist_free(props);
1848 	}
1849 
1850 	(void) strlcpy(zc.zc_name, thename, sizeof (zc.zc_name));
1851 
1852 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1853 	    &zc.zc_guid) == 0);
1854 
1855 	if (zcmd_write_conf_nvlist(hdl, &zc, config) != 0) {
1856 		zcmd_free_nvlists(&zc);
1857 		return (-1);
1858 	}
1859 	if (zcmd_alloc_dst_nvlist(hdl, &zc, zc.zc_nvlist_conf_size * 2) != 0) {
1860 		zcmd_free_nvlists(&zc);
1861 		return (-1);
1862 	}
1863 
1864 	zc.zc_cookie = flags;
1865 	while ((ret = zfs_ioctl(hdl, ZFS_IOC_POOL_IMPORT, &zc)) != 0 &&
1866 	    errno == ENOMEM) {
1867 		if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
1868 			zcmd_free_nvlists(&zc);
1869 			return (-1);
1870 		}
1871 	}
1872 	if (ret != 0)
1873 		error = errno;
1874 
1875 	(void) zcmd_read_dst_nvlist(hdl, &zc, &nv);
1876 
1877 	zcmd_free_nvlists(&zc);
1878 
1879 	zpool_get_load_policy(config, &policy);
1880 
1881 	if (error) {
1882 		char desc[1024];
1883 		char aux[256];
1884 
1885 		/*
1886 		 * Dry-run failed, but we print out what success
1887 		 * looks like if we found a best txg
1888 		 */
1889 		if (policy.zlp_rewind & ZPOOL_TRY_REWIND) {
1890 			zpool_rewind_exclaim(hdl, newname ? origname : thename,
1891 			    B_TRUE, nv);
1892 			nvlist_free(nv);
1893 			return (-1);
1894 		}
1895 
1896 		if (newname == NULL)
1897 			(void) snprintf(desc, sizeof (desc),
1898 			    dgettext(TEXT_DOMAIN, "cannot import '%s'"),
1899 			    thename);
1900 		else
1901 			(void) snprintf(desc, sizeof (desc),
1902 			    dgettext(TEXT_DOMAIN, "cannot import '%s' as '%s'"),
1903 			    origname, thename);
1904 
1905 		switch (error) {
1906 		case ENOTSUP:
1907 			if (nv != NULL && nvlist_lookup_nvlist(nv,
1908 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0 &&
1909 			    nvlist_exists(nvinfo, ZPOOL_CONFIG_UNSUP_FEAT)) {
1910 				(void) printf(dgettext(TEXT_DOMAIN, "This "
1911 				    "pool uses the following feature(s) not "
1912 				    "supported by this system:\n"));
1913 				zpool_print_unsup_feat(nv);
1914 				if (nvlist_exists(nvinfo,
1915 				    ZPOOL_CONFIG_CAN_RDONLY)) {
1916 					(void) printf(dgettext(TEXT_DOMAIN,
1917 					    "All unsupported features are only "
1918 					    "required for writing to the pool."
1919 					    "\nThe pool can be imported using "
1920 					    "'-o readonly=on'.\n"));
1921 				}
1922 			}
1923 			/*
1924 			 * Unsupported version.
1925 			 */
1926 			(void) zfs_error(hdl, EZFS_BADVERSION, desc);
1927 			break;
1928 
1929 		case EREMOTEIO:
1930 			if (nv != NULL && nvlist_lookup_nvlist(nv,
1931 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0) {
1932 				char *hostname = "<unknown>";
1933 				uint64_t hostid = 0;
1934 				mmp_state_t mmp_state;
1935 
1936 				mmp_state = fnvlist_lookup_uint64(nvinfo,
1937 				    ZPOOL_CONFIG_MMP_STATE);
1938 
1939 				if (nvlist_exists(nvinfo,
1940 				    ZPOOL_CONFIG_MMP_HOSTNAME))
1941 					hostname = fnvlist_lookup_string(nvinfo,
1942 					    ZPOOL_CONFIG_MMP_HOSTNAME);
1943 
1944 				if (nvlist_exists(nvinfo,
1945 				    ZPOOL_CONFIG_MMP_HOSTID))
1946 					hostid = fnvlist_lookup_uint64(nvinfo,
1947 					    ZPOOL_CONFIG_MMP_HOSTID);
1948 
1949 				if (mmp_state == MMP_STATE_ACTIVE) {
1950 					(void) snprintf(aux, sizeof (aux),
1951 					    dgettext(TEXT_DOMAIN, "pool is imp"
1952 					    "orted on host '%s' (hostid=%lx).\n"
1953 					    "Export the pool on the other "
1954 					    "system, then run 'zpool import'."),
1955 					    hostname, (unsigned long) hostid);
1956 				} else if (mmp_state == MMP_STATE_NO_HOSTID) {
1957 					(void) snprintf(aux, sizeof (aux),
1958 					    dgettext(TEXT_DOMAIN, "pool has "
1959 					    "the multihost property on and "
1960 					    "the\nsystem's hostid is not "
1961 					    "set.\n"));
1962 				}
1963 
1964 				(void) zfs_error_aux(hdl, aux);
1965 			}
1966 			(void) zfs_error(hdl, EZFS_ACTIVE_POOL, desc);
1967 			break;
1968 
1969 		case EINVAL:
1970 			(void) zfs_error(hdl, EZFS_INVALCONFIG, desc);
1971 			break;
1972 
1973 		case EROFS:
1974 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1975 			    "one or more devices is read only"));
1976 			(void) zfs_error(hdl, EZFS_BADDEV, desc);
1977 			break;
1978 
1979 		case ENXIO:
1980 			if (nv && nvlist_lookup_nvlist(nv,
1981 			    ZPOOL_CONFIG_LOAD_INFO, &nvinfo) == 0 &&
1982 			    nvlist_lookup_nvlist(nvinfo,
1983 			    ZPOOL_CONFIG_MISSING_DEVICES, &missing) == 0) {
1984 				(void) printf(dgettext(TEXT_DOMAIN,
1985 				    "The devices below are missing or "
1986 				    "corrupted, use '-m' to import the pool "
1987 				    "anyway:\n"));
1988 				print_vdev_tree(hdl, NULL, missing, 2);
1989 				(void) printf("\n");
1990 			}
1991 			(void) zpool_standard_error(hdl, error, desc);
1992 			break;
1993 
1994 		case EEXIST:
1995 			(void) zpool_standard_error(hdl, error, desc);
1996 			break;
1997 		case ENAMETOOLONG:
1998 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1999 			    "new name of at least one dataset is longer than "
2000 			    "the maximum allowable length"));
2001 			(void) zfs_error(hdl, EZFS_NAMETOOLONG, desc);
2002 			break;
2003 		default:
2004 			(void) zpool_standard_error(hdl, error, desc);
2005 			zpool_explain_recover(hdl,
2006 			    newname ? origname : thename, -error, nv);
2007 			break;
2008 		}
2009 
2010 		nvlist_free(nv);
2011 		ret = -1;
2012 	} else {
2013 		zpool_handle_t *zhp;
2014 
2015 		/*
2016 		 * This should never fail, but play it safe anyway.
2017 		 */
2018 		if (zpool_open_silent(hdl, thename, &zhp) != 0)
2019 			ret = -1;
2020 		else if (zhp != NULL)
2021 			zpool_close(zhp);
2022 		if (policy.zlp_rewind &
2023 		    (ZPOOL_DO_REWIND | ZPOOL_TRY_REWIND)) {
2024 			zpool_rewind_exclaim(hdl, newname ? origname : thename,
2025 			    ((policy.zlp_rewind & ZPOOL_TRY_REWIND) != 0), nv);
2026 		}
2027 		nvlist_free(nv);
2028 		return (0);
2029 	}
2030 
2031 	return (ret);
2032 }
2033 
2034 /*
2035  * Translate vdev names to guids.  If a vdev_path is determined to be
2036  * unsuitable then a vd_errlist is allocated and the vdev path and errno
2037  * are added to it.
2038  */
2039 static int
zpool_translate_vdev_guids(zpool_handle_t * zhp,nvlist_t * vds,nvlist_t * vdev_guids,nvlist_t * guids_to_paths,nvlist_t ** vd_errlist)2040 zpool_translate_vdev_guids(zpool_handle_t *zhp, nvlist_t *vds,
2041     nvlist_t *vdev_guids, nvlist_t *guids_to_paths, nvlist_t **vd_errlist)
2042 {
2043 	nvlist_t *errlist = NULL;
2044 	int error = 0;
2045 
2046 	for (nvpair_t *elem = nvlist_next_nvpair(vds, NULL); elem != NULL;
2047 	    elem = nvlist_next_nvpair(vds, elem)) {
2048 		boolean_t spare, cache;
2049 
2050 		char *vd_path = nvpair_name(elem);
2051 		nvlist_t *tgt = zpool_find_vdev(zhp, vd_path, &spare, &cache,
2052 		    NULL);
2053 
2054 		if ((tgt == NULL) || cache || spare) {
2055 			if (errlist == NULL) {
2056 				errlist = fnvlist_alloc();
2057 				error = EINVAL;
2058 			}
2059 
2060 			uint64_t err = (tgt == NULL) ? EZFS_NODEVICE :
2061 			    (spare ? EZFS_ISSPARE : EZFS_ISL2CACHE);
2062 			fnvlist_add_int64(errlist, vd_path, err);
2063 			continue;
2064 		}
2065 
2066 		uint64_t guid = fnvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID);
2067 		fnvlist_add_uint64(vdev_guids, vd_path, guid);
2068 
2069 		char msg[MAXNAMELEN];
2070 		(void) snprintf(msg, sizeof (msg), "%llu", (u_longlong_t)guid);
2071 		fnvlist_add_string(guids_to_paths, msg, vd_path);
2072 	}
2073 
2074 	if (error != 0) {
2075 		verify(errlist != NULL);
2076 		if (vd_errlist != NULL)
2077 			*vd_errlist = errlist;
2078 		else
2079 			fnvlist_free(errlist);
2080 	}
2081 
2082 	return (error);
2083 }
2084 
2085 /*
2086  * Scan the pool.
2087  */
2088 int
zpool_scan(zpool_handle_t * zhp,pool_scan_func_t func,pool_scrub_cmd_t cmd)2089 zpool_scan(zpool_handle_t *zhp, pool_scan_func_t func, pool_scrub_cmd_t cmd)
2090 {
2091 	zfs_cmd_t zc = { 0 };
2092 	char msg[1024];
2093 	int err;
2094 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2095 
2096 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2097 	zc.zc_cookie = func;
2098 	zc.zc_flags = cmd;
2099 
2100 	if (zfs_ioctl(hdl, ZFS_IOC_POOL_SCAN, &zc) == 0)
2101 		return (0);
2102 
2103 	err = errno;
2104 
2105 	/* ECANCELED on a scrub means we resumed a paused scrub */
2106 	if (err == ECANCELED && func == POOL_SCAN_SCRUB &&
2107 	    cmd == POOL_SCRUB_NORMAL)
2108 		return (0);
2109 
2110 	if (err == ENOENT && func != POOL_SCAN_NONE && cmd == POOL_SCRUB_NORMAL)
2111 		return (0);
2112 
2113 	if (func == POOL_SCAN_SCRUB) {
2114 		if (cmd == POOL_SCRUB_PAUSE) {
2115 			(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2116 			    "cannot pause scrubbing %s"), zc.zc_name);
2117 		} else {
2118 			assert(cmd == POOL_SCRUB_NORMAL);
2119 			(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2120 			    "cannot scrub %s"), zc.zc_name);
2121 		}
2122 	} else if (func == POOL_SCAN_RESILVER) {
2123 		assert(cmd == POOL_SCRUB_NORMAL);
2124 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
2125 		    "cannot restart resilver on %s"), zc.zc_name);
2126 	} else if (func == POOL_SCAN_NONE) {
2127 		(void) snprintf(msg, sizeof (msg),
2128 		    dgettext(TEXT_DOMAIN, "cannot cancel scrubbing %s"),
2129 		    zc.zc_name);
2130 	} else {
2131 		assert(!"unexpected result");
2132 	}
2133 
2134 	if (err == EBUSY) {
2135 		nvlist_t *nvroot;
2136 		pool_scan_stat_t *ps = NULL;
2137 		uint_t psc;
2138 
2139 		verify(nvlist_lookup_nvlist(zhp->zpool_config,
2140 		    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
2141 		(void) nvlist_lookup_uint64_array(nvroot,
2142 		    ZPOOL_CONFIG_SCAN_STATS, (uint64_t **)&ps, &psc);
2143 		if (ps && ps->pss_func == POOL_SCAN_SCRUB) {
2144 			if (cmd == POOL_SCRUB_PAUSE)
2145 				return (zfs_error(hdl, EZFS_SCRUB_PAUSED, msg));
2146 			else
2147 				return (zfs_error(hdl, EZFS_SCRUBBING, msg));
2148 		} else {
2149 			return (zfs_error(hdl, EZFS_RESILVERING, msg));
2150 		}
2151 	} else if (err == ENOENT) {
2152 		return (zfs_error(hdl, EZFS_NO_SCRUB, msg));
2153 	} else if (err == ENOTSUP && func == POOL_SCAN_RESILVER) {
2154 		return (zfs_error(hdl, EZFS_NO_RESILVER_DEFER, msg));
2155 	} else {
2156 		return (zpool_standard_error(hdl, err, msg));
2157 	}
2158 }
2159 
2160 static int
xlate_init_err(int err)2161 xlate_init_err(int err)
2162 {
2163 	switch (err) {
2164 	case ENODEV:
2165 		return (EZFS_NODEVICE);
2166 	case EINVAL:
2167 	case EROFS:
2168 		return (EZFS_BADDEV);
2169 	case EBUSY:
2170 		return (EZFS_INITIALIZING);
2171 	case ESRCH:
2172 		return (EZFS_NO_INITIALIZE);
2173 	}
2174 	return (err);
2175 }
2176 
2177 /*
2178  * Begin, suspend, or cancel the initialization (initializing of all free
2179  * blocks) for the given vdevs in the given pool.
2180  */
2181 int
zpool_initialize(zpool_handle_t * zhp,pool_initialize_func_t cmd_type,nvlist_t * vds)2182 zpool_initialize(zpool_handle_t *zhp, pool_initialize_func_t cmd_type,
2183     nvlist_t *vds)
2184 {
2185 	char msg[1024];
2186 	int err;
2187 
2188 	nvlist_t *vdev_guids = fnvlist_alloc();
2189 	nvlist_t *guids_to_paths = fnvlist_alloc();
2190 	nvlist_t *vd_errlist = NULL;
2191 	nvlist_t *errlist;
2192 	nvpair_t *elem;
2193 
2194 	err = zpool_translate_vdev_guids(zhp, vds, vdev_guids,
2195 	    guids_to_paths, &vd_errlist);
2196 
2197 	if (err == 0) {
2198 		err = lzc_initialize(zhp->zpool_name, cmd_type,
2199 		    vdev_guids, &errlist);
2200 		if (err == 0) {
2201 			fnvlist_free(vdev_guids);
2202 			fnvlist_free(guids_to_paths);
2203 			return (0);
2204 		}
2205 
2206 		if (errlist != NULL) {
2207 			vd_errlist = fnvlist_lookup_nvlist(errlist,
2208 			    ZPOOL_INITIALIZE_VDEVS);
2209 		}
2210 
2211 		(void) snprintf(msg, sizeof (msg),
2212 		    dgettext(TEXT_DOMAIN, "operation failed"));
2213 	} else {
2214 		verify(vd_errlist != NULL);
2215 	}
2216 
2217 	for (elem = nvlist_next_nvpair(vd_errlist, NULL); elem != NULL;
2218 	    elem = nvlist_next_nvpair(vd_errlist, elem)) {
2219 		int64_t vd_error = xlate_init_err(fnvpair_value_int64(elem));
2220 		char *path;
2221 
2222 		if (nvlist_lookup_string(guids_to_paths, nvpair_name(elem),
2223 		    &path) != 0)
2224 			path = nvpair_name(elem);
2225 
2226 		(void) zfs_error_fmt(zhp->zpool_hdl, vd_error,
2227 		    "cannot initialize '%s'", path);
2228 	}
2229 
2230 	fnvlist_free(vdev_guids);
2231 	fnvlist_free(guids_to_paths);
2232 
2233 	if (vd_errlist != NULL) {
2234 		fnvlist_free(vd_errlist);
2235 		return (-1);
2236 	}
2237 
2238 	return (zpool_standard_error(zhp->zpool_hdl, err, msg));
2239 }
2240 
2241 static int
xlate_trim_err(int err)2242 xlate_trim_err(int err)
2243 {
2244 	switch (err) {
2245 	case ENODEV:
2246 		return (EZFS_NODEVICE);
2247 	case EINVAL:
2248 	case EROFS:
2249 		return (EZFS_BADDEV);
2250 	case EBUSY:
2251 		return (EZFS_TRIMMING);
2252 	case ESRCH:
2253 		return (EZFS_NO_TRIM);
2254 	case EOPNOTSUPP:
2255 		return (EZFS_TRIM_NOTSUP);
2256 	}
2257 	return (err);
2258 }
2259 
2260 /*
2261  * Begin, suspend, or cancel the TRIM (discarding of all free blocks) for
2262  * the given vdevs in the given pool.
2263  */
2264 int
zpool_trim(zpool_handle_t * zhp,pool_trim_func_t cmd_type,nvlist_t * vds,trimflags_t * trim_flags)2265 zpool_trim(zpool_handle_t *zhp, pool_trim_func_t cmd_type, nvlist_t *vds,
2266     trimflags_t *trim_flags)
2267 {
2268 	char msg[1024];
2269 	int err;
2270 
2271 	nvlist_t *vdev_guids = fnvlist_alloc();
2272 	nvlist_t *guids_to_paths = fnvlist_alloc();
2273 	nvlist_t *vd_errlist = NULL;
2274 	nvlist_t *errlist;
2275 	nvpair_t *elem;
2276 
2277 	err = zpool_translate_vdev_guids(zhp, vds, vdev_guids,
2278 	    guids_to_paths, &vd_errlist);
2279 	if (err == 0) {
2280 		err = lzc_trim(zhp->zpool_name, cmd_type, trim_flags->rate,
2281 		    trim_flags->secure, vdev_guids, &errlist);
2282 		if (err == 0) {
2283 			fnvlist_free(vdev_guids);
2284 			fnvlist_free(guids_to_paths);
2285 			return (0);
2286 		}
2287 
2288 		if (errlist != NULL) {
2289 			vd_errlist = fnvlist_lookup_nvlist(errlist,
2290 			    ZPOOL_TRIM_VDEVS);
2291 		}
2292 
2293 		(void) snprintf(msg, sizeof (msg),
2294 		    dgettext(TEXT_DOMAIN, "operation failed"));
2295 	} else {
2296 		verify(vd_errlist != NULL);
2297 	}
2298 
2299 	for (elem = nvlist_next_nvpair(vd_errlist, NULL);
2300 	    elem != NULL; elem = nvlist_next_nvpair(vd_errlist, elem)) {
2301 		int64_t vd_error = xlate_trim_err(fnvpair_value_int64(elem));
2302 		char *path;
2303 		/*
2304 		 * If only the pool was specified, and it was not a secure
2305 		 * trim then suppress warnings for individual vdevs which
2306 		 * do not support trimming.
2307 		 */
2308 		if (vd_error == EZFS_TRIM_NOTSUP &&
2309 		    trim_flags->fullpool &&
2310 		    !trim_flags->secure) {
2311 			continue;
2312 		}
2313 
2314 		if (nvlist_lookup_string(guids_to_paths, nvpair_name(elem),
2315 		    &path) != 0)
2316 			path = nvpair_name(elem);
2317 
2318 		(void) zfs_error_fmt(zhp->zpool_hdl, vd_error,
2319 		    "cannot trim '%s'", path);
2320 	}
2321 
2322 	fnvlist_free(vdev_guids);
2323 	fnvlist_free(guids_to_paths);
2324 
2325 	if (vd_errlist != NULL) {
2326 		fnvlist_free(vd_errlist);
2327 		return (-1);
2328 	}
2329 
2330 	return (zpool_standard_error(zhp->zpool_hdl, err, msg));
2331 }
2332 
2333 /*
2334  * This provides a very minimal check whether a given string is likely a
2335  * c#t#d# style string.  Users of this are expected to do their own
2336  * verification of the s# part.
2337  */
2338 #define	CTD_CHECK(str)  (str && str[0] == 'c' && isdigit(str[1]))
2339 
2340 /*
2341  * More elaborate version for ones which may start with "/dev/dsk/"
2342  * and the like.
2343  */
2344 static int
ctd_check_path(char * str)2345 ctd_check_path(char *str)
2346 {
2347 	/*
2348 	 * If it starts with a slash, check the last component.
2349 	 */
2350 	if (str && str[0] == '/') {
2351 		char *tmp = strrchr(str, '/');
2352 
2353 		/*
2354 		 * If it ends in "/old", check the second-to-last
2355 		 * component of the string instead.
2356 		 */
2357 		if (tmp != str && strcmp(tmp, "/old") == 0) {
2358 			for (tmp--; *tmp != '/'; tmp--)
2359 				;
2360 		}
2361 		str = tmp + 1;
2362 	}
2363 	return (CTD_CHECK(str));
2364 }
2365 
2366 /*
2367  * Find a vdev that matches the search criteria specified. We use the
2368  * the nvpair name to determine how we should look for the device.
2369  * 'avail_spare' is set to TRUE if the provided guid refers to an AVAIL
2370  * spare; but FALSE if its an INUSE spare.
2371  */
2372 static nvlist_t *
vdev_to_nvlist_iter(nvlist_t * nv,nvlist_t * search,boolean_t * avail_spare,boolean_t * l2cache,boolean_t * log)2373 vdev_to_nvlist_iter(nvlist_t *nv, nvlist_t *search, boolean_t *avail_spare,
2374     boolean_t *l2cache, boolean_t *log)
2375 {
2376 	uint_t c, children;
2377 	nvlist_t **child;
2378 	nvlist_t *ret;
2379 	uint64_t is_log;
2380 	char *srchkey;
2381 	nvpair_t *pair = nvlist_next_nvpair(search, NULL);
2382 
2383 	/* Nothing to look for */
2384 	if (search == NULL || pair == NULL)
2385 		return (NULL);
2386 
2387 	/* Obtain the key we will use to search */
2388 	srchkey = nvpair_name(pair);
2389 
2390 	switch (nvpair_type(pair)) {
2391 	case DATA_TYPE_UINT64:
2392 		if (strcmp(srchkey, ZPOOL_CONFIG_GUID) == 0) {
2393 			uint64_t srchval, theguid;
2394 
2395 			verify(nvpair_value_uint64(pair, &srchval) == 0);
2396 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID,
2397 			    &theguid) == 0);
2398 			if (theguid == srchval)
2399 				return (nv);
2400 		}
2401 		break;
2402 
2403 	case DATA_TYPE_STRING: {
2404 		char *srchval, *val;
2405 
2406 		verify(nvpair_value_string(pair, &srchval) == 0);
2407 		if (nvlist_lookup_string(nv, srchkey, &val) != 0)
2408 			break;
2409 
2410 		/*
2411 		 * Search for the requested value. Special cases:
2412 		 *
2413 		 * - ZPOOL_CONFIG_PATH for whole disk entries. To support
2414 		 *   UEFI boot, these end in "s0" or "s0/old" or "s1" or
2415 		 *   "s1/old".   The "s0" or "s1" part is hidden from the user,
2416 		 *   but included in the string, so this matches around it.
2417 		 * - looking for a top-level vdev name (i.e. ZPOOL_CONFIG_TYPE).
2418 		 *
2419 		 * Otherwise, all other searches are simple string compares.
2420 		 */
2421 		if (strcmp(srchkey, ZPOOL_CONFIG_PATH) == 0 &&
2422 		    ctd_check_path(val)) {
2423 			uint64_t wholedisk = 0;
2424 
2425 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
2426 			    &wholedisk);
2427 			if (wholedisk) {
2428 				int slen = strlen(srchval);
2429 				int vlen = strlen(val);
2430 
2431 				if (slen != vlen - 2)
2432 					break;
2433 
2434 				/*
2435 				 * make_leaf_vdev() should only set
2436 				 * wholedisk for ZPOOL_CONFIG_PATHs which
2437 				 * will include "/dev/dsk/", giving plenty of
2438 				 * room for the indices used next.
2439 				 */
2440 				ASSERT(vlen >= 6);
2441 
2442 				/*
2443 				 * strings identical except trailing "s0"
2444 				 */
2445 				if ((strcmp(&val[vlen - 2], "s0") == 0 ||
2446 				    strcmp(&val[vlen - 2], "s1") == 0) &&
2447 				    strncmp(srchval, val, slen) == 0)
2448 					return (nv);
2449 
2450 				/*
2451 				 * strings identical except trailing "s0/old"
2452 				 */
2453 				if ((strcmp(&val[vlen - 6], "s0/old") == 0 ||
2454 				    strcmp(&val[vlen - 6], "s1/old") == 0) &&
2455 				    strcmp(&srchval[slen - 4], "/old") == 0 &&
2456 				    strncmp(srchval, val, slen - 4) == 0)
2457 					return (nv);
2458 
2459 				break;
2460 			}
2461 		} else if (strcmp(srchkey, ZPOOL_CONFIG_TYPE) == 0 && val) {
2462 			char *type, *idx, *end, *p;
2463 			uint64_t id, vdev_id;
2464 
2465 			/*
2466 			 * Determine our vdev type, keeping in mind
2467 			 * that the srchval is composed of a type and
2468 			 * vdev id pair (i.e. mirror-4).
2469 			 */
2470 			if ((type = strdup(srchval)) == NULL)
2471 				return (NULL);
2472 
2473 			if ((p = strrchr(type, '-')) == NULL) {
2474 				free(type);
2475 				break;
2476 			}
2477 			idx = p + 1;
2478 			*p = '\0';
2479 
2480 			/*
2481 			 * If the types don't match then keep looking.
2482 			 */
2483 			if (strncmp(val, type, strlen(val)) != 0) {
2484 				free(type);
2485 				break;
2486 			}
2487 
2488 			verify(zpool_vdev_is_interior(type));
2489 			verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID,
2490 			    &id) == 0);
2491 
2492 			errno = 0;
2493 			vdev_id = strtoull(idx, &end, 10);
2494 
2495 			free(type);
2496 			if (errno != 0)
2497 				return (NULL);
2498 
2499 			/*
2500 			 * Now verify that we have the correct vdev id.
2501 			 */
2502 			if (vdev_id == id)
2503 				return (nv);
2504 		}
2505 
2506 		/*
2507 		 * Common case
2508 		 */
2509 		if (strcmp(srchval, val) == 0)
2510 			return (nv);
2511 		break;
2512 	}
2513 
2514 	default:
2515 		break;
2516 	}
2517 
2518 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2519 	    &child, &children) != 0)
2520 		return (NULL);
2521 
2522 	for (c = 0; c < children; c++) {
2523 		if ((ret = vdev_to_nvlist_iter(child[c], search,
2524 		    avail_spare, l2cache, NULL)) != NULL) {
2525 			/*
2526 			 * The 'is_log' value is only set for the toplevel
2527 			 * vdev, not the leaf vdevs.  So we always lookup the
2528 			 * log device from the root of the vdev tree (where
2529 			 * 'log' is non-NULL).
2530 			 */
2531 			if (log != NULL &&
2532 			    nvlist_lookup_uint64(child[c],
2533 			    ZPOOL_CONFIG_IS_LOG, &is_log) == 0 &&
2534 			    is_log) {
2535 				*log = B_TRUE;
2536 			}
2537 			return (ret);
2538 		}
2539 	}
2540 
2541 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_SPARES,
2542 	    &child, &children) == 0) {
2543 		for (c = 0; c < children; c++) {
2544 			if ((ret = vdev_to_nvlist_iter(child[c], search,
2545 			    avail_spare, l2cache, NULL)) != NULL) {
2546 				*avail_spare = B_TRUE;
2547 				return (ret);
2548 			}
2549 		}
2550 	}
2551 
2552 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_L2CACHE,
2553 	    &child, &children) == 0) {
2554 		for (c = 0; c < children; c++) {
2555 			if ((ret = vdev_to_nvlist_iter(child[c], search,
2556 			    avail_spare, l2cache, NULL)) != NULL) {
2557 				*l2cache = B_TRUE;
2558 				return (ret);
2559 			}
2560 		}
2561 	}
2562 
2563 	return (NULL);
2564 }
2565 
2566 /*
2567  * Given a physical path (minus the "/devices" prefix), find the
2568  * associated vdev.
2569  */
2570 nvlist_t *
zpool_find_vdev_by_physpath(zpool_handle_t * zhp,const char * ppath,boolean_t * avail_spare,boolean_t * l2cache,boolean_t * log)2571 zpool_find_vdev_by_physpath(zpool_handle_t *zhp, const char *ppath,
2572     boolean_t *avail_spare, boolean_t *l2cache, boolean_t *log)
2573 {
2574 	nvlist_t *search, *nvroot, *ret;
2575 
2576 	verify(nvlist_alloc(&search, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2577 	verify(nvlist_add_string(search, ZPOOL_CONFIG_PHYS_PATH, ppath) == 0);
2578 
2579 	verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
2580 	    &nvroot) == 0);
2581 
2582 	*avail_spare = B_FALSE;
2583 	*l2cache = B_FALSE;
2584 	if (log != NULL)
2585 		*log = B_FALSE;
2586 	ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log);
2587 	nvlist_free(search);
2588 
2589 	return (ret);
2590 }
2591 
2592 /*
2593  * Determine if we have an "interior" top-level vdev (i.e mirror/raidz).
2594  */
2595 static boolean_t
zpool_vdev_is_interior(const char * name)2596 zpool_vdev_is_interior(const char *name)
2597 {
2598 	if (strncmp(name, VDEV_TYPE_RAIDZ, strlen(VDEV_TYPE_RAIDZ)) == 0 ||
2599 	    strncmp(name, VDEV_TYPE_SPARE, strlen(VDEV_TYPE_SPARE)) == 0 ||
2600 	    strncmp(name,
2601 	    VDEV_TYPE_REPLACING, strlen(VDEV_TYPE_REPLACING)) == 0 ||
2602 	    strncmp(name, VDEV_TYPE_MIRROR, strlen(VDEV_TYPE_MIRROR)) == 0)
2603 		return (B_TRUE);
2604 	return (B_FALSE);
2605 }
2606 
2607 nvlist_t *
zpool_find_vdev(zpool_handle_t * zhp,const char * path,boolean_t * avail_spare,boolean_t * l2cache,boolean_t * log)2608 zpool_find_vdev(zpool_handle_t *zhp, const char *path, boolean_t *avail_spare,
2609     boolean_t *l2cache, boolean_t *log)
2610 {
2611 	char buf[MAXPATHLEN];
2612 	char *end;
2613 	nvlist_t *nvroot, *search, *ret;
2614 	uint64_t guid;
2615 
2616 	verify(nvlist_alloc(&search, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2617 
2618 	guid = strtoull(path, &end, 10);
2619 	if (guid != 0 && *end == '\0') {
2620 		verify(nvlist_add_uint64(search, ZPOOL_CONFIG_GUID, guid) == 0);
2621 	} else if (zpool_vdev_is_interior(path)) {
2622 		verify(nvlist_add_string(search, ZPOOL_CONFIG_TYPE, path) == 0);
2623 	} else if (path[0] != '/') {
2624 		(void) snprintf(buf, sizeof (buf), "%s/%s", ZFS_DISK_ROOT,
2625 		    path);
2626 		verify(nvlist_add_string(search, ZPOOL_CONFIG_PATH, buf) == 0);
2627 	} else {
2628 		verify(nvlist_add_string(search, ZPOOL_CONFIG_PATH, path) == 0);
2629 	}
2630 
2631 	verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
2632 	    &nvroot) == 0);
2633 
2634 	*avail_spare = B_FALSE;
2635 	*l2cache = B_FALSE;
2636 	if (log != NULL)
2637 		*log = B_FALSE;
2638 	ret = vdev_to_nvlist_iter(nvroot, search, avail_spare, l2cache, log);
2639 	nvlist_free(search);
2640 
2641 	return (ret);
2642 }
2643 
2644 static int
vdev_is_online(nvlist_t * nv)2645 vdev_is_online(nvlist_t *nv)
2646 {
2647 	uint64_t ival;
2648 
2649 	if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE, &ival) == 0 ||
2650 	    nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED, &ival) == 0 ||
2651 	    nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED, &ival) == 0)
2652 		return (0);
2653 
2654 	return (1);
2655 }
2656 
2657 /*
2658  * Helper function for zpool_get_physpaths().
2659  */
2660 static int
vdev_get_one_physpath(nvlist_t * config,char * physpath,size_t physpath_size,size_t * bytes_written)2661 vdev_get_one_physpath(nvlist_t *config, char *physpath, size_t physpath_size,
2662     size_t *bytes_written)
2663 {
2664 	size_t bytes_left, pos, rsz;
2665 	char *tmppath;
2666 	const char *format;
2667 
2668 	if (nvlist_lookup_string(config, ZPOOL_CONFIG_PHYS_PATH,
2669 	    &tmppath) != 0)
2670 		return (EZFS_NODEVICE);
2671 
2672 	pos = *bytes_written;
2673 	bytes_left = physpath_size - pos;
2674 	format = (pos == 0) ? "%s" : " %s";
2675 
2676 	rsz = snprintf(physpath + pos, bytes_left, format, tmppath);
2677 	*bytes_written += rsz;
2678 
2679 	if (rsz >= bytes_left) {
2680 		/* if physpath was not copied properly, clear it */
2681 		if (bytes_left != 0) {
2682 			physpath[pos] = 0;
2683 		}
2684 		return (EZFS_NOSPC);
2685 	}
2686 	return (0);
2687 }
2688 
2689 static int
vdev_get_physpaths(nvlist_t * nv,char * physpath,size_t phypath_size,size_t * rsz,boolean_t is_spare)2690 vdev_get_physpaths(nvlist_t *nv, char *physpath, size_t phypath_size,
2691     size_t *rsz, boolean_t is_spare)
2692 {
2693 	char *type;
2694 	int ret;
2695 
2696 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
2697 		return (EZFS_INVALCONFIG);
2698 
2699 	if (strcmp(type, VDEV_TYPE_DISK) == 0) {
2700 		/*
2701 		 * An active spare device has ZPOOL_CONFIG_IS_SPARE set.
2702 		 * For a spare vdev, we only want to boot from the active
2703 		 * spare device.
2704 		 */
2705 		if (is_spare) {
2706 			uint64_t spare = 0;
2707 			(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE,
2708 			    &spare);
2709 			if (!spare)
2710 				return (EZFS_INVALCONFIG);
2711 		}
2712 
2713 		if (vdev_is_online(nv)) {
2714 			if ((ret = vdev_get_one_physpath(nv, physpath,
2715 			    phypath_size, rsz)) != 0)
2716 				return (ret);
2717 		}
2718 	} else if (strcmp(type, VDEV_TYPE_MIRROR) == 0 ||
2719 	    strcmp(type, VDEV_TYPE_RAIDZ) == 0 ||
2720 	    strcmp(type, VDEV_TYPE_REPLACING) == 0 ||
2721 	    (is_spare = (strcmp(type, VDEV_TYPE_SPARE) == 0))) {
2722 		nvlist_t **child;
2723 		uint_t count;
2724 		int i, ret;
2725 
2726 		if (nvlist_lookup_nvlist_array(nv,
2727 		    ZPOOL_CONFIG_CHILDREN, &child, &count) != 0)
2728 			return (EZFS_INVALCONFIG);
2729 
2730 		for (i = 0; i < count; i++) {
2731 			ret = vdev_get_physpaths(child[i], physpath,
2732 			    phypath_size, rsz, is_spare);
2733 			if (ret == EZFS_NOSPC)
2734 				return (ret);
2735 		}
2736 	}
2737 
2738 	return (EZFS_POOL_INVALARG);
2739 }
2740 
2741 /*
2742  * Get phys_path for a root pool config.
2743  * Return 0 on success; non-zero on failure.
2744  */
2745 static int
zpool_get_config_physpath(nvlist_t * config,char * physpath,size_t phypath_size)2746 zpool_get_config_physpath(nvlist_t *config, char *physpath, size_t phypath_size)
2747 {
2748 	size_t rsz;
2749 	nvlist_t *vdev_root;
2750 	nvlist_t **child;
2751 	uint_t count;
2752 	char *type;
2753 
2754 	rsz = 0;
2755 
2756 	if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
2757 	    &vdev_root) != 0)
2758 		return (EZFS_INVALCONFIG);
2759 
2760 	if (nvlist_lookup_string(vdev_root, ZPOOL_CONFIG_TYPE, &type) != 0 ||
2761 	    nvlist_lookup_nvlist_array(vdev_root, ZPOOL_CONFIG_CHILDREN,
2762 	    &child, &count) != 0)
2763 		return (EZFS_INVALCONFIG);
2764 
2765 	/*
2766 	 * root pool can only have a single top-level vdev.
2767 	 */
2768 	if (strcmp(type, VDEV_TYPE_ROOT) != 0 || count != 1)
2769 		return (EZFS_POOL_INVALARG);
2770 
2771 	(void) vdev_get_physpaths(child[0], physpath, phypath_size, &rsz,
2772 	    B_FALSE);
2773 
2774 	/* No online devices */
2775 	if (rsz == 0)
2776 		return (EZFS_NODEVICE);
2777 
2778 	return (0);
2779 }
2780 
2781 /*
2782  * Get phys_path for a root pool
2783  * Return 0 on success; non-zero on failure.
2784  */
2785 int
zpool_get_physpath(zpool_handle_t * zhp,char * physpath,size_t phypath_size)2786 zpool_get_physpath(zpool_handle_t *zhp, char *physpath, size_t phypath_size)
2787 {
2788 	return (zpool_get_config_physpath(zhp->zpool_config, physpath,
2789 	    phypath_size));
2790 }
2791 
2792 /*
2793  * If the device has being dynamically expanded then we need to relabel
2794  * the disk to use the new unallocated space.
2795  */
2796 static int
zpool_relabel_disk(libzfs_handle_t * hdl,const char * name,const char * msg)2797 zpool_relabel_disk(libzfs_handle_t *hdl, const char *name, const char *msg)
2798 {
2799 	char path[MAXPATHLEN];
2800 	int fd, error;
2801 	int (*_efi_use_whole_disk)(int);
2802 
2803 	if ((_efi_use_whole_disk = (int (*)(int))dlsym(RTLD_DEFAULT,
2804 	    "efi_use_whole_disk")) == NULL)
2805 		return (-1);
2806 
2807 	(void) snprintf(path, sizeof (path), "%s/%s", ZFS_RDISK_ROOT, name);
2808 
2809 	if ((fd = open(path, O_RDWR | O_NDELAY)) < 0) {
2810 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot "
2811 		    "relabel '%s': unable to open device"), name);
2812 		return (zfs_error(hdl, EZFS_OPENFAILED, msg));
2813 	}
2814 
2815 	/*
2816 	 * It's possible that we might encounter an error if the device
2817 	 * does not have any unallocated space left. If so, we simply
2818 	 * ignore that error and continue on.
2819 	 */
2820 	error = _efi_use_whole_disk(fd);
2821 	(void) close(fd);
2822 	if (error && error != VT_ENOSPC) {
2823 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "cannot "
2824 		    "relabel '%s': unable to read disk capacity"), name);
2825 		return (zfs_error(hdl, EZFS_NOCAP, msg));
2826 	}
2827 	return (0);
2828 }
2829 
2830 /*
2831  * Bring the specified vdev online.   The 'flags' parameter is a set of the
2832  * ZFS_ONLINE_* flags.
2833  */
2834 int
zpool_vdev_online(zpool_handle_t * zhp,const char * path,int flags,vdev_state_t * newstate)2835 zpool_vdev_online(zpool_handle_t *zhp, const char *path, int flags,
2836     vdev_state_t *newstate)
2837 {
2838 	zfs_cmd_t zc = { 0 };
2839 	char msg[1024];
2840 	char *pathname;
2841 	nvlist_t *tgt;
2842 	boolean_t avail_spare, l2cache, islog;
2843 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2844 	int error;
2845 
2846 	if (flags & ZFS_ONLINE_EXPAND) {
2847 		(void) snprintf(msg, sizeof (msg),
2848 		    dgettext(TEXT_DOMAIN, "cannot expand %s"), path);
2849 	} else {
2850 		(void) snprintf(msg, sizeof (msg),
2851 		    dgettext(TEXT_DOMAIN, "cannot online %s"), path);
2852 	}
2853 
2854 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2855 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
2856 	    &islog)) == NULL)
2857 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
2858 
2859 	verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2860 
2861 	if (avail_spare)
2862 		return (zfs_error(hdl, EZFS_ISSPARE, msg));
2863 
2864 	if ((flags & ZFS_ONLINE_EXPAND ||
2865 	    zpool_get_prop_int(zhp, ZPOOL_PROP_AUTOEXPAND, NULL)) &&
2866 	    nvlist_lookup_string(tgt, ZPOOL_CONFIG_PATH, &pathname) == 0) {
2867 		uint64_t wholedisk = 0;
2868 
2869 		(void) nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_WHOLE_DISK,
2870 		    &wholedisk);
2871 
2872 		/*
2873 		 * XXX - L2ARC 1.0 devices can't support expansion.
2874 		 */
2875 		if (l2cache) {
2876 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2877 			    "cannot expand cache devices"));
2878 			return (zfs_error(hdl, EZFS_VDEVNOTSUP, msg));
2879 		}
2880 
2881 		if (wholedisk) {
2882 			pathname += strlen(ZFS_DISK_ROOT) + 1;
2883 			error = zpool_relabel_disk(hdl, pathname, msg);
2884 			if (error != 0)
2885 				return (error);
2886 		}
2887 	}
2888 
2889 	zc.zc_cookie = VDEV_STATE_ONLINE;
2890 	zc.zc_obj = flags;
2891 
2892 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) != 0) {
2893 		if (errno == EINVAL) {
2894 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "was split "
2895 			    "from this pool into a new one.  Use '%s' "
2896 			    "instead"), "zpool detach");
2897 			return (zfs_error(hdl, EZFS_POSTSPLIT_ONLINE, msg));
2898 		}
2899 		return (zpool_standard_error(hdl, errno, msg));
2900 	}
2901 
2902 	*newstate = zc.zc_cookie;
2903 	return (0);
2904 }
2905 
2906 /*
2907  * Take the specified vdev offline
2908  */
2909 int
zpool_vdev_offline(zpool_handle_t * zhp,const char * path,boolean_t istmp)2910 zpool_vdev_offline(zpool_handle_t *zhp, const char *path, boolean_t istmp)
2911 {
2912 	zfs_cmd_t zc = { 0 };
2913 	char msg[1024];
2914 	nvlist_t *tgt;
2915 	boolean_t avail_spare, l2cache;
2916 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2917 
2918 	(void) snprintf(msg, sizeof (msg),
2919 	    dgettext(TEXT_DOMAIN, "cannot offline %s"), path);
2920 
2921 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2922 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
2923 	    NULL)) == NULL)
2924 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
2925 
2926 	verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
2927 
2928 	if (avail_spare)
2929 		return (zfs_error(hdl, EZFS_ISSPARE, msg));
2930 
2931 	zc.zc_cookie = VDEV_STATE_OFFLINE;
2932 	zc.zc_obj = istmp ? ZFS_OFFLINE_TEMPORARY : 0;
2933 
2934 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2935 		return (0);
2936 
2937 	switch (errno) {
2938 	case EBUSY:
2939 
2940 		/*
2941 		 * There are no other replicas of this device.
2942 		 */
2943 		return (zfs_error(hdl, EZFS_NOREPLICAS, msg));
2944 
2945 	case EEXIST:
2946 		/*
2947 		 * The log device has unplayed logs
2948 		 */
2949 		return (zfs_error(hdl, EZFS_UNPLAYED_LOGS, msg));
2950 
2951 	default:
2952 		return (zpool_standard_error(hdl, errno, msg));
2953 	}
2954 }
2955 
2956 /*
2957  * Mark the given vdev faulted.
2958  */
2959 int
zpool_vdev_fault(zpool_handle_t * zhp,uint64_t guid,vdev_aux_t aux)2960 zpool_vdev_fault(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux)
2961 {
2962 	zfs_cmd_t zc = { 0 };
2963 	char msg[1024];
2964 	libzfs_handle_t *hdl = zhp->zpool_hdl;
2965 
2966 	(void) snprintf(msg, sizeof (msg),
2967 	    dgettext(TEXT_DOMAIN, "cannot fault %llu"), guid);
2968 
2969 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
2970 	zc.zc_guid = guid;
2971 	zc.zc_cookie = VDEV_STATE_FAULTED;
2972 	zc.zc_obj = aux;
2973 
2974 	if (ioctl(hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
2975 		return (0);
2976 
2977 	switch (errno) {
2978 	case EBUSY:
2979 
2980 		/*
2981 		 * There are no other replicas of this device.
2982 		 */
2983 		return (zfs_error(hdl, EZFS_NOREPLICAS, msg));
2984 
2985 	default:
2986 		return (zpool_standard_error(hdl, errno, msg));
2987 	}
2988 
2989 }
2990 
2991 /*
2992  * Mark the given vdev degraded.
2993  */
2994 int
zpool_vdev_degrade(zpool_handle_t * zhp,uint64_t guid,vdev_aux_t aux)2995 zpool_vdev_degrade(zpool_handle_t *zhp, uint64_t guid, vdev_aux_t aux)
2996 {
2997 	zfs_cmd_t zc = { 0 };
2998 	char msg[1024];
2999 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3000 
3001 	(void) snprintf(msg, sizeof (msg),
3002 	    dgettext(TEXT_DOMAIN, "cannot degrade %llu"), guid);
3003 
3004 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3005 	zc.zc_guid = guid;
3006 	zc.zc_cookie = VDEV_STATE_DEGRADED;
3007 	zc.zc_obj = aux;
3008 
3009 	if (ioctl(hdl->libzfs_fd, ZFS_IOC_VDEV_SET_STATE, &zc) == 0)
3010 		return (0);
3011 
3012 	return (zpool_standard_error(hdl, errno, msg));
3013 }
3014 
3015 /*
3016  * Returns TRUE if the given nvlist is a vdev that was originally swapped in as
3017  * a hot spare.
3018  */
3019 static boolean_t
is_replacing_spare(nvlist_t * search,nvlist_t * tgt,int which)3020 is_replacing_spare(nvlist_t *search, nvlist_t *tgt, int which)
3021 {
3022 	nvlist_t **child;
3023 	uint_t c, children;
3024 	char *type;
3025 
3026 	if (nvlist_lookup_nvlist_array(search, ZPOOL_CONFIG_CHILDREN, &child,
3027 	    &children) == 0) {
3028 		verify(nvlist_lookup_string(search, ZPOOL_CONFIG_TYPE,
3029 		    &type) == 0);
3030 
3031 		if (strcmp(type, VDEV_TYPE_SPARE) == 0 &&
3032 		    children == 2 && child[which] == tgt)
3033 			return (B_TRUE);
3034 
3035 		for (c = 0; c < children; c++)
3036 			if (is_replacing_spare(child[c], tgt, which))
3037 				return (B_TRUE);
3038 	}
3039 
3040 	return (B_FALSE);
3041 }
3042 
3043 /*
3044  * Attach new_disk (fully described by nvroot) to old_disk.
3045  * If 'replacing' is specified, the new disk will replace the old one.
3046  */
3047 int
zpool_vdev_attach(zpool_handle_t * zhp,const char * old_disk,const char * new_disk,nvlist_t * nvroot,int replacing)3048 zpool_vdev_attach(zpool_handle_t *zhp,
3049     const char *old_disk, const char *new_disk, nvlist_t *nvroot, int replacing)
3050 {
3051 	zfs_cmd_t zc = { 0 };
3052 	char msg[1024];
3053 	int ret;
3054 	nvlist_t *tgt, *newvd;
3055 	boolean_t avail_spare, l2cache, islog;
3056 	uint64_t val;
3057 	char *newname;
3058 	nvlist_t **child;
3059 	uint_t children;
3060 	nvlist_t *config_root;
3061 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3062 	boolean_t rootpool = zpool_is_bootable(zhp);
3063 
3064 	if (replacing)
3065 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
3066 		    "cannot replace %s with %s"), old_disk, new_disk);
3067 	else
3068 		(void) snprintf(msg, sizeof (msg), dgettext(TEXT_DOMAIN,
3069 		    "cannot attach %s to %s"), new_disk, old_disk);
3070 
3071 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3072 	if ((tgt = zpool_find_vdev(zhp, old_disk, &avail_spare, &l2cache,
3073 	    &islog)) == NULL)
3074 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
3075 
3076 	if (avail_spare)
3077 		return (zfs_error(hdl, EZFS_ISSPARE, msg));
3078 
3079 	if (l2cache)
3080 		return (zfs_error(hdl, EZFS_ISL2CACHE, msg));
3081 
3082 	verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
3083 	zc.zc_cookie = replacing;
3084 
3085 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
3086 	    &child, &children) != 0 || children != 1) {
3087 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3088 		    "new device must be a single disk"));
3089 		return (zfs_error(hdl, EZFS_INVALCONFIG, msg));
3090 	}
3091 
3092 	verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
3093 	    ZPOOL_CONFIG_VDEV_TREE, &config_root) == 0);
3094 
3095 	if ((newname = zpool_vdev_name(NULL, NULL, child[0], 0)) == NULL)
3096 		return (-1);
3097 
3098 	newvd = zpool_find_vdev(zhp, newname, &avail_spare, &l2cache, NULL);
3099 	/*
3100 	 * If the target is a hot spare that has been swapped in, we can only
3101 	 * replace it with another hot spare.
3102 	 */
3103 	if (replacing &&
3104 	    nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_IS_SPARE, &val) == 0 &&
3105 	    (newvd == NULL || !avail_spare) &&
3106 	    is_replacing_spare(config_root, tgt, 1)) {
3107 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3108 		    "can only be replaced by another hot spare"));
3109 		free(newname);
3110 		return (zfs_error(hdl, EZFS_BADTARGET, msg));
3111 	}
3112 
3113 	free(newname);
3114 
3115 	if (replacing && avail_spare && !vdev_is_online(newvd)) {
3116 		(void) zpool_standard_error(hdl, ENXIO, msg);
3117 		return (-1);
3118 	}
3119 
3120 	if (zcmd_write_conf_nvlist(hdl, &zc, nvroot) != 0)
3121 		return (-1);
3122 
3123 	ret = zfs_ioctl(hdl, ZFS_IOC_VDEV_ATTACH, &zc);
3124 
3125 	zcmd_free_nvlists(&zc);
3126 
3127 	if (ret == 0) {
3128 		if (rootpool) {
3129 			/*
3130 			 * XXX need a better way to prevent user from
3131 			 * booting up a half-baked vdev.
3132 			 */
3133 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Make "
3134 			    "sure to wait until resilver is done "
3135 			    "before rebooting.\n"));
3136 		}
3137 		return (0);
3138 	}
3139 
3140 	switch (errno) {
3141 	case ENOTSUP:
3142 		/*
3143 		 * Can't attach to or replace this type of vdev.
3144 		 */
3145 		if (replacing) {
3146 			uint64_t version = zpool_get_prop_int(zhp,
3147 			    ZPOOL_PROP_VERSION, NULL);
3148 
3149 			if (islog)
3150 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3151 				    "cannot replace a log with a spare"));
3152 			else if (version >= SPA_VERSION_MULTI_REPLACE)
3153 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3154 				    "already in replacing/spare config; wait "
3155 				    "for completion or use 'zpool detach'"));
3156 			else
3157 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3158 				    "cannot replace a replacing device"));
3159 		} else {
3160 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3161 			    "can only attach to mirrors and top-level "
3162 			    "disks"));
3163 		}
3164 		(void) zfs_error(hdl, EZFS_BADTARGET, msg);
3165 		break;
3166 
3167 	case EINVAL:
3168 		/*
3169 		 * The new device must be a single disk.
3170 		 */
3171 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3172 		    "new device must be a single disk"));
3173 		(void) zfs_error(hdl, EZFS_INVALCONFIG, msg);
3174 		break;
3175 
3176 	case EBUSY:
3177 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "%s is busy, "
3178 		    "or device removal is in progress"),
3179 		    new_disk);
3180 		(void) zfs_error(hdl, EZFS_BADDEV, msg);
3181 		break;
3182 
3183 	case EOVERFLOW:
3184 		/*
3185 		 * The new device is too small.
3186 		 */
3187 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3188 		    "device is too small"));
3189 		(void) zfs_error(hdl, EZFS_BADDEV, msg);
3190 		break;
3191 
3192 	case EDOM:
3193 		/*
3194 		 * The new device has a different optimal sector size.
3195 		 */
3196 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3197 		    "new device has a different optimal sector size; use the "
3198 		    "option '-o ashift=N' to override the optimal size"));
3199 		(void) zfs_error(hdl, EZFS_BADDEV, msg);
3200 		break;
3201 
3202 	case ENAMETOOLONG:
3203 		/*
3204 		 * The resulting top-level vdev spec won't fit in the label.
3205 		 */
3206 		(void) zfs_error(hdl, EZFS_DEVOVERFLOW, msg);
3207 		break;
3208 
3209 	default:
3210 		(void) zpool_standard_error(hdl, errno, msg);
3211 	}
3212 
3213 	return (-1);
3214 }
3215 
3216 /*
3217  * Detach the specified device.
3218  */
3219 int
zpool_vdev_detach(zpool_handle_t * zhp,const char * path)3220 zpool_vdev_detach(zpool_handle_t *zhp, const char *path)
3221 {
3222 	zfs_cmd_t zc = { 0 };
3223 	char msg[1024];
3224 	nvlist_t *tgt;
3225 	boolean_t avail_spare, l2cache;
3226 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3227 
3228 	(void) snprintf(msg, sizeof (msg),
3229 	    dgettext(TEXT_DOMAIN, "cannot detach %s"), path);
3230 
3231 	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
3232 	if ((tgt = zpool_find_vdev(zhp, path, &avail_spare, &l2cache,
3233 	    NULL)) == NULL)
3234 		return (zfs_error(hdl, EZFS_NODEVICE, msg));
3235 
3236 	if (avail_spare)
3237 		return (zfs_error(hdl, EZFS_ISSPARE, msg));
3238 
3239 	if (l2cache)
3240 		return (zfs_error(hdl, EZFS_ISL2CACHE, msg));
3241 
3242 	verify(nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_GUID, &zc.zc_guid) == 0);
3243 
3244 	if (zfs_ioctl(hdl, ZFS_IOC_VDEV_DETACH, &zc) == 0)
3245 		return (0);
3246 
3247 	switch (errno) {
3248 
3249 	case ENOTSUP:
3250 		/*
3251 		 * Can't detach from this type of vdev.
3252 		 */
3253 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "only "
3254 		    "applicable to mirror and replacing vdevs"));
3255 		(void) zfs_error(hdl, EZFS_BADTARGET, msg);
3256 		break;
3257 
3258 	case EBUSY:
3259 		/*
3260 		 * There are no other replicas of this device.
3261 		 */
3262 		(void) zfs_error(hdl, EZFS_NOREPLICAS, msg);
3263 		break;
3264 
3265 	default:
3266 		(void) zpool_standard_error(hdl, errno, msg);
3267 	}
3268 
3269 	return (-1);
3270 }
3271 
3272 /*
3273  * Find a mirror vdev in the source nvlist.
3274  *
3275  * The mchild array contains a list of disks in one of the top-level mirrors
3276  * of the source pool.  The schild array contains a list of disks that the
3277  * user specified on the command line.  We loop over the mchild array to
3278  * see if any entry in the schild array matches.
3279  *
3280  * If a disk in the mchild array is found in the schild array, we return
3281  * the index of that entry.  Otherwise we return -1.
3282  */
3283 static int
find_vdev_entry(zpool_handle_t * zhp,nvlist_t ** mchild,uint_t mchildren,nvlist_t ** schild,uint_t schildren)3284 find_vdev_entry(zpool_handle_t *zhp, nvlist_t **mchild, uint_t mchildren,
3285     nvlist_t **schild, uint_t schildren)
3286 {
3287 	uint_t mc;
3288 
3289 	for (mc = 0; mc < mchildren; mc++) {
3290 		uint_t sc;
3291 		char *mpath = zpool_vdev_name(zhp->zpool_hdl, zhp,
3292 		    mchild[mc], 0);
3293 
3294 		for (sc = 0; sc < schildren; sc++) {
3295 			char *spath = zpool_vdev_name(zhp->zpool_hdl, zhp,
3296 			    schild[sc], 0);
3297 			boolean_t result = (strcmp(mpath, spath) == 0);
3298 
3299 			free(spath);
3300 			if (result) {
3301 				free(mpath);
3302 				return (mc);
3303 			}
3304 		}
3305 
3306 		free(mpath);
3307 	}
3308 
3309 	return (-1);
3310 }
3311 
3312 /*
3313  * Split a mirror pool.  If newroot points to null, then a new nvlist
3314  * is generated and it is the responsibility of the caller to free it.
3315  */
3316 int
zpool_vdev_split(zpool_handle_t * zhp,char * newname,nvlist_t ** newroot,nvlist_t * props,splitflags_t flags)3317 zpool_vdev_split(zpool_handle_t *zhp, char *newname, nvlist_t **newroot,
3318     nvlist_t *props, splitflags_t flags)
3319 {
3320 	zfs_cmd_t zc = { 0 };
3321 	char msg[1024];
3322 	nvlist_t *tree, *config, **child, **newchild, *newconfig = NULL;
3323 	nvlist_t **varray = NULL, *zc_props = NULL;
3324 	uint_t c, children, newchildren, lastlog = 0, vcount, found = 0;
3325 	libzfs_handle_t *hdl = zhp->zpool_hdl;
3326 	uint64_t vers;
3327 	boolean_t freelist = B_FALSE, memory_err = B_TRUE;
3328 	int retval = 0;
3329 
3330 	(void) snprintf(msg, sizeof (msg),
3331 	    dgettext(TEXT_DOMAIN, "Unable to split %s"), zhp->zpool_name);
3332 
3333 	if (!zpool_name_valid(hdl, B_FALSE, newname))
3334 		return (zfs_error(hdl, EZFS_INVALIDNAME, msg));
3335 
3336 	if ((config = zpool_get_config(zhp, NULL)) == NULL) {
3337 		(void) fprintf(stderr, gettext("Internal error: unable to "
3338 		    "retrieve pool configuration\n"));
3339 		return (-1);
3340 	}
3341 
3342 	verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &tree)
3343 	    == 0);
3344 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION, &vers) == 0);
3345 
3346 	if (props) {
3347 		prop_flags_t flags = { .create = B_FALSE, .import = B_TRUE };
<