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