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