xref: /freebsd/sys/contrib/openzfs/lib/libzutil/zutil_import.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 /*
13  * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
14  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
15  * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
16  * Copyright 2015 RackTop Systems.
17  * Copyright (c) 2016, Intel Corporation.
18  * Copyright (c) 2021, Colm Buckley <colm@tuatha.org>
19  */
20 
21 /*
22  * Pool import support functions.
23  *
24  * Used by zpool, ztest, zdb, and zhack to locate importable configs. Since
25  * these commands are expected to run in the global zone, we can assume
26  * that the devices are all readable when called.
27  *
28  * To import a pool, we rely on reading the configuration information from the
29  * ZFS label of each device.  If we successfully read the label, then we
30  * organize the configuration information in the following hierarchy:
31  *
32  *	pool guid -> toplevel vdev guid -> label txg
33  *
34  * Duplicate entries matching this same tuple will be discarded.  Once we have
35  * examined every device, we pick the best label txg config for each toplevel
36  * vdev.  We then arrange these toplevel vdevs into a complete pool config, and
37  * update any paths that have changed.  Finally, we attempt to import the pool
38  * using our derived config, and record the results.
39  */
40 
41 #ifdef HAVE_AIO_H
42 #include <aio.h>
43 #endif
44 #include <ctype.h>
45 #include <dirent.h>
46 #include <errno.h>
47 #include <libintl.h>
48 #include <libgen.h>
49 #include <stddef.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <sys/stat.h>
53 #include <unistd.h>
54 #include <fcntl.h>
55 #include <sys/dktp/fdisk.h>
56 #include <sys/vdev_impl.h>
57 #include <sys/fs/zfs.h>
58 #include <sys/taskq.h>
59 
60 #include <libzutil.h>
61 #include <libnvpair.h>
62 
63 #include "zutil_import.h"
64 
65 const char *
libpc_error_description(libpc_handle_t * hdl)66 libpc_error_description(libpc_handle_t *hdl)
67 {
68 	if (hdl->lpc_desc[0] != '\0')
69 		return (hdl->lpc_desc);
70 
71 	switch (hdl->lpc_error) {
72 	case LPC_BADCACHE:
73 		return (dgettext(TEXT_DOMAIN, "invalid or missing cache file"));
74 	case LPC_BADPATH:
75 		return (dgettext(TEXT_DOMAIN, "must be an absolute path"));
76 	case LPC_NOMEM:
77 		return (dgettext(TEXT_DOMAIN, "out of memory"));
78 	case LPC_EACCESS:
79 		return (dgettext(TEXT_DOMAIN, "some devices require root "
80 		    "privileges"));
81 	case LPC_UNKNOWN:
82 		return (dgettext(TEXT_DOMAIN, "unknown error"));
83 	default:
84 		assert(hdl->lpc_error == 0);
85 		return (dgettext(TEXT_DOMAIN, "no error"));
86 	}
87 }
88 
89 static __attribute__((format(printf, 2, 3))) void
zutil_error_aux(libpc_handle_t * hdl,const char * fmt,...)90 zutil_error_aux(libpc_handle_t *hdl, const char *fmt, ...)
91 {
92 	va_list ap;
93 
94 	va_start(ap, fmt);
95 
96 	(void) vsnprintf(hdl->lpc_desc, sizeof (hdl->lpc_desc), fmt, ap);
97 	hdl->lpc_desc_active = B_TRUE;
98 
99 	va_end(ap);
100 }
101 
102 static void
zutil_verror(libpc_handle_t * hdl,lpc_error_t error,const char * fmt,va_list ap)103 zutil_verror(libpc_handle_t *hdl, lpc_error_t error, const char *fmt,
104     va_list ap)
105 {
106 	char action[1024];
107 
108 	(void) vsnprintf(action, sizeof (action), fmt, ap);
109 	hdl->lpc_error = error;
110 
111 	if (hdl->lpc_desc_active)
112 		hdl->lpc_desc_active = B_FALSE;
113 	else
114 		hdl->lpc_desc[0] = '\0';
115 
116 	if (hdl->lpc_printerr)
117 		(void) fprintf(stderr, "%s: %s\n", action,
118 		    libpc_error_description(hdl));
119 }
120 
121 static __attribute__((format(printf, 3, 4))) int
zutil_error_fmt(libpc_handle_t * hdl,lpc_error_t error,const char * fmt,...)122 zutil_error_fmt(libpc_handle_t *hdl, lpc_error_t error,
123     const char *fmt, ...)
124 {
125 	va_list ap;
126 
127 	va_start(ap, fmt);
128 
129 	zutil_verror(hdl, error, fmt, ap);
130 
131 	va_end(ap);
132 
133 	return (-1);
134 }
135 
136 static int
zutil_error(libpc_handle_t * hdl,lpc_error_t error,const char * msg)137 zutil_error(libpc_handle_t *hdl, lpc_error_t error, const char *msg)
138 {
139 	return (zutil_error_fmt(hdl, error, "%s", msg));
140 }
141 
142 static int
zutil_no_memory(libpc_handle_t * hdl)143 zutil_no_memory(libpc_handle_t *hdl)
144 {
145 	zutil_error(hdl, LPC_NOMEM, "internal error");
146 	exit(1);
147 }
148 
149 void *
zutil_alloc(libpc_handle_t * hdl,size_t size)150 zutil_alloc(libpc_handle_t *hdl, size_t size)
151 {
152 	void *data;
153 
154 	if ((data = calloc(1, size)) == NULL)
155 		(void) zutil_no_memory(hdl);
156 
157 	return (data);
158 }
159 
160 char *
zutil_strdup(libpc_handle_t * hdl,const char * str)161 zutil_strdup(libpc_handle_t *hdl, const char *str)
162 {
163 	char *ret;
164 
165 	if ((ret = strdup(str)) == NULL)
166 		(void) zutil_no_memory(hdl);
167 
168 	return (ret);
169 }
170 
171 static char *
zutil_strndup(libpc_handle_t * hdl,const char * str,size_t n)172 zutil_strndup(libpc_handle_t *hdl, const char *str, size_t n)
173 {
174 	char *ret;
175 
176 	if ((ret = strndup(str, n)) == NULL)
177 		(void) zutil_no_memory(hdl);
178 
179 	return (ret);
180 }
181 
182 /*
183  * Intermediate structures used to gather configuration information.
184  */
185 typedef struct config_entry {
186 	uint64_t		ce_txg;
187 	nvlist_t		*ce_config;
188 	struct config_entry	*ce_next;
189 } config_entry_t;
190 
191 typedef struct vdev_entry {
192 	uint64_t		ve_guid;
193 	config_entry_t		*ve_configs;
194 	struct vdev_entry	*ve_next;
195 } vdev_entry_t;
196 
197 typedef struct pool_entry {
198 	uint64_t		pe_guid;
199 	vdev_entry_t		*pe_vdevs;
200 	struct pool_entry	*pe_next;
201 } pool_entry_t;
202 
203 typedef struct name_entry {
204 	char			*ne_name;
205 	uint64_t		ne_guid;
206 	uint64_t		ne_order;
207 	uint64_t		ne_num_labels;
208 	struct name_entry	*ne_next;
209 } name_entry_t;
210 
211 typedef struct pool_list {
212 	pool_entry_t		*pools;
213 	name_entry_t		*names;
214 } pool_list_t;
215 
216 /*
217  * Go through and fix up any path and/or devid information for the given vdev
218  * configuration.
219  */
220 static int
fix_paths(libpc_handle_t * hdl,nvlist_t * nv,name_entry_t * names)221 fix_paths(libpc_handle_t *hdl, nvlist_t *nv, name_entry_t *names)
222 {
223 	nvlist_t **child;
224 	uint_t c, children;
225 	uint64_t guid;
226 	name_entry_t *ne, *best;
227 	const char *path;
228 
229 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
230 	    &child, &children) == 0) {
231 		for (c = 0; c < children; c++)
232 			if (fix_paths(hdl, child[c], names) != 0)
233 				return (-1);
234 		return (0);
235 	}
236 
237 	/*
238 	 * This is a leaf (file or disk) vdev.  In either case, go through
239 	 * the name list and see if we find a matching guid.  If so, replace
240 	 * the path and see if we can calculate a new devid.
241 	 *
242 	 * There may be multiple names associated with a particular guid, in
243 	 * which case we have overlapping partitions or multiple paths to the
244 	 * same disk.  In this case we prefer to use the path name which
245 	 * matches the ZPOOL_CONFIG_PATH.  If no matching entry is found we
246 	 * use the lowest order device which corresponds to the first match
247 	 * while traversing the ZPOOL_IMPORT_PATH search path.
248 	 */
249 	verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0);
250 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) != 0)
251 		path = NULL;
252 
253 	best = NULL;
254 	for (ne = names; ne != NULL; ne = ne->ne_next) {
255 		if (ne->ne_guid == guid) {
256 			if (path == NULL) {
257 				best = ne;
258 				break;
259 			}
260 
261 			if ((strlen(path) == strlen(ne->ne_name)) &&
262 			    strncmp(path, ne->ne_name, strlen(path)) == 0) {
263 				best = ne;
264 				break;
265 			}
266 
267 			if (best == NULL) {
268 				best = ne;
269 				continue;
270 			}
271 
272 			/* Prefer paths with move vdev labels. */
273 			if (ne->ne_num_labels > best->ne_num_labels) {
274 				best = ne;
275 				continue;
276 			}
277 
278 			/* Prefer paths earlier in the search order. */
279 			if (ne->ne_num_labels == best->ne_num_labels &&
280 			    ne->ne_order < best->ne_order) {
281 				best = ne;
282 				continue;
283 			}
284 		}
285 	}
286 
287 	if (best == NULL)
288 		return (0);
289 
290 	if (nvlist_add_string(nv, ZPOOL_CONFIG_PATH, best->ne_name) != 0)
291 		return (-1);
292 
293 	update_vdev_config_dev_strs(nv);
294 
295 	return (0);
296 }
297 
298 /*
299  * Determine if the path in the given spare or l2cache vdev config still
300  * refers to the expected device.  Unlike the vdev tree, which is built
301  * from the scanned labels, these configs are read from the pool's MOS
302  * by a tryimport.  Their path may be a persistent name (by-id, by-vdev,
303  * multipath, ...) which is perfectly valid yet absent from the list of
304  * scanned names, in which case fix_paths() would needlessly rewrite it
305  * to some scanned name of last resort (e.g. a bare /dev basename which
306  * is not stable across reboots).  The device is verified much as the
307  * scanned candidates are: the path must name a device type which is
308  * safe to probe, a label must be readable from it and the label vdev
309  * guid must match the expected one.  As in zpool_find_import_impl(),
310  * the device must also be openable exclusively, otherwise it may be
311  * an in-use multipath component.
312  */
313 static boolean_t
aux_path_active(nvlist_t * nv)314 aux_path_active(nvlist_t *nv)
315 {
316 	const char *path;
317 	uint64_t guid, label_guid;
318 	nvlist_t *label = NULL;
319 	int fd, num_labels;
320 	boolean_t active = B_FALSE;
321 
322 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) != 0 ||
323 	    nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
324 		return (B_FALSE);
325 
326 	/*
327 	 * The path comes from the pool's MOS and may name anything, so
328 	 * check it is safe to probe first.  O_NONBLOCK below keeps the open
329 	 * of a FIFO swapped in after this check from blocking, and the type
330 	 * of the opened descriptor is re-checked below before it is used.
331 	 */
332 	if (!zpool_dev_probe_ok(path))
333 		return (B_FALSE);
334 
335 	/*
336 	 * Preferentially open using O_DIRECT to bypass the block device
337 	 * cache which may be stale for multipath devices.  An EINVAL errno
338 	 * indicates O_DIRECT is unsupported so fallback to just O_RDONLY.
339 	 */
340 	fd = open(path, O_RDONLY | O_EXCL | O_NONBLOCK | O_DIRECT | O_CLOEXEC);
341 	if (fd < 0 && errno == EINVAL)
342 		fd = open(path, O_RDONLY | O_EXCL | O_NONBLOCK | O_CLOEXEC);
343 	if (fd < 0)
344 		return (B_FALSE);
345 
346 	/*
347 	 * zpool_dev_probe_ok() stat'd the name, but if the path was a
348 	 * symlink it could have been repointed at a different node before
349 	 * the open() above.  Re-check the type of the descriptor we now
350 	 * hold so a crafted MOS path cannot make us read a label from an
351 	 * unexpected node.
352 	 */
353 	if (!zpool_dev_probe_ok_fd(fd)) {
354 		(void) close(fd);
355 		return (B_FALSE);
356 	}
357 
358 	if (zpool_read_label(fd, &label, &num_labels) == 0 && label != NULL) {
359 		if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
360 		    &label_guid) == 0 && label_guid == guid)
361 			active = B_TRUE;
362 		nvlist_free(label);
363 	}
364 
365 	(void) close(fd);
366 
367 	return (active);
368 }
369 
370 /*
371  * Add the given configuration to the list of known devices.
372  */
373 static int
add_config(libpc_handle_t * hdl,pool_list_t * pl,const char * path,int order,int num_labels,nvlist_t * config)374 add_config(libpc_handle_t *hdl, pool_list_t *pl, const char *path,
375     int order, int num_labels, nvlist_t *config)
376 {
377 	uint64_t pool_guid, vdev_guid, top_guid, txg, state;
378 	pool_entry_t *pe;
379 	vdev_entry_t *ve;
380 	config_entry_t *ce;
381 	name_entry_t *ne;
382 
383 	/*
384 	 * If this is a hot spare not currently in use or level 2 cache
385 	 * device, add it to the list of names to translate, but don't do
386 	 * anything else.
387 	 */
388 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
389 	    &state) == 0 &&
390 	    (state == POOL_STATE_SPARE || state == POOL_STATE_L2CACHE) &&
391 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, &vdev_guid) == 0) {
392 		if ((ne = zutil_alloc(hdl, sizeof (name_entry_t))) == NULL)
393 			return (-1);
394 
395 		if ((ne->ne_name = zutil_strdup(hdl, path)) == NULL) {
396 			free(ne);
397 			return (-1);
398 		}
399 		ne->ne_guid = vdev_guid;
400 		ne->ne_order = order;
401 		ne->ne_num_labels = num_labels;
402 		ne->ne_next = pl->names;
403 		pl->names = ne;
404 
405 		return (0);
406 	}
407 
408 	/*
409 	 * If we have a valid config but cannot read any of these fields, then
410 	 * it means we have a half-initialized label.  In vdev_label_init()
411 	 * we write a label with txg == 0 so that we can identify the device
412 	 * in case the user refers to the same disk later on.  If we fail to
413 	 * create the pool, we'll be left with a label in this state
414 	 * which should not be considered part of a valid pool.
415 	 */
416 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
417 	    &pool_guid) != 0 ||
418 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID,
419 	    &vdev_guid) != 0 ||
420 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_TOP_GUID,
421 	    &top_guid) != 0 ||
422 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
423 	    &txg) != 0 || txg == 0) {
424 		return (0);
425 	}
426 
427 	/*
428 	 * First, see if we know about this pool.  If not, then add it to the
429 	 * list of known pools.
430 	 */
431 	for (pe = pl->pools; pe != NULL; pe = pe->pe_next) {
432 		if (pe->pe_guid == pool_guid)
433 			break;
434 	}
435 
436 	if (pe == NULL) {
437 		if ((pe = zutil_alloc(hdl, sizeof (pool_entry_t))) == NULL) {
438 			return (-1);
439 		}
440 		pe->pe_guid = pool_guid;
441 		pe->pe_next = pl->pools;
442 		pl->pools = pe;
443 	}
444 
445 	/*
446 	 * Second, see if we know about this toplevel vdev.  Add it if its
447 	 * missing.
448 	 */
449 	for (ve = pe->pe_vdevs; ve != NULL; ve = ve->ve_next) {
450 		if (ve->ve_guid == top_guid)
451 			break;
452 	}
453 
454 	if (ve == NULL) {
455 		if ((ve = zutil_alloc(hdl, sizeof (vdev_entry_t))) == NULL) {
456 			return (-1);
457 		}
458 		ve->ve_guid = top_guid;
459 		ve->ve_next = pe->pe_vdevs;
460 		pe->pe_vdevs = ve;
461 	}
462 
463 	/*
464 	 * Third, see if we have a config with a matching transaction group.  If
465 	 * so, then we do nothing.  Otherwise, add it to the list of known
466 	 * configs.
467 	 */
468 	for (ce = ve->ve_configs; ce != NULL; ce = ce->ce_next) {
469 		if (ce->ce_txg == txg)
470 			break;
471 	}
472 
473 	if (ce == NULL) {
474 		if ((ce = zutil_alloc(hdl, sizeof (config_entry_t))) == NULL) {
475 			return (-1);
476 		}
477 		ce->ce_txg = txg;
478 		ce->ce_config = fnvlist_dup(config);
479 		ce->ce_next = ve->ve_configs;
480 		ve->ve_configs = ce;
481 	}
482 
483 	/*
484 	 * At this point we've successfully added our config to the list of
485 	 * known configs.  The last thing to do is add the vdev guid -> path
486 	 * mappings so that we can fix up the configuration as necessary before
487 	 * doing the import.
488 	 */
489 	if ((ne = zutil_alloc(hdl, sizeof (name_entry_t))) == NULL)
490 		return (-1);
491 
492 	if ((ne->ne_name = zutil_strdup(hdl, path)) == NULL) {
493 		free(ne);
494 		return (-1);
495 	}
496 
497 	ne->ne_guid = vdev_guid;
498 	ne->ne_order = order;
499 	ne->ne_num_labels = num_labels;
500 	ne->ne_next = pl->names;
501 	pl->names = ne;
502 
503 	return (0);
504 }
505 
506 static int
zutil_pool_active(libpc_handle_t * hdl,const char * name,uint64_t guid,boolean_t * isactive)507 zutil_pool_active(libpc_handle_t *hdl, const char *name, uint64_t guid,
508     boolean_t *isactive)
509 {
510 	ASSERT(hdl->lpc_ops->pco_pool_active != NULL);
511 
512 	int error = hdl->lpc_ops->pco_pool_active(hdl->lpc_lib_handle, name,
513 	    guid, isactive);
514 
515 	return (error);
516 }
517 
518 static nvlist_t *
zutil_refresh_config(libpc_handle_t * hdl,nvlist_t * tryconfig)519 zutil_refresh_config(libpc_handle_t *hdl, nvlist_t *tryconfig)
520 {
521 	ASSERT(hdl->lpc_ops->pco_refresh_config != NULL);
522 
523 	return (hdl->lpc_ops->pco_refresh_config(hdl->lpc_lib_handle,
524 	    tryconfig));
525 }
526 
527 /*
528  * Determine if the vdev id is a hole in the namespace.
529  */
530 static boolean_t
vdev_is_hole(uint64_t * hole_array,uint_t holes,uint_t id)531 vdev_is_hole(uint64_t *hole_array, uint_t holes, uint_t id)
532 {
533 	int c;
534 
535 	for (c = 0; c < holes; c++) {
536 
537 		/* Top-level is a hole */
538 		if (hole_array[c] == id)
539 			return (B_TRUE);
540 	}
541 	return (B_FALSE);
542 }
543 
544 /*
545  * Convert our list of pools into the definitive set of configurations.  We
546  * start by picking the best config for each toplevel vdev.  Once that's done,
547  * we assemble the toplevel vdevs into a full config for the pool.  We make a
548  * pass to fix up any incorrect paths, and then add it to the main list to
549  * return to the user.
550  */
551 static nvlist_t *
get_configs(libpc_handle_t * hdl,pool_list_t * pl,boolean_t active_ok,boolean_t keep_aux_path,nvlist_t * policy)552 get_configs(libpc_handle_t *hdl, pool_list_t *pl, boolean_t active_ok,
553     boolean_t keep_aux_path, nvlist_t *policy)
554 {
555 	pool_entry_t *pe;
556 	vdev_entry_t *ve;
557 	config_entry_t *ce;
558 	nvlist_t *ret = NULL, *config = NULL, *tmp = NULL, *nvtop, *nvroot;
559 	nvlist_t **spares, **l2cache;
560 	uint_t i, nspares, nl2cache;
561 	boolean_t config_seen;
562 	uint64_t best_txg;
563 	const char *name, *hostname = NULL;
564 	uint64_t guid;
565 	uint_t children = 0;
566 	nvlist_t **child = NULL;
567 	uint64_t *hole_array, max_id;
568 	uint_t c;
569 	boolean_t isactive;
570 	nvlist_t *nvl;
571 	boolean_t valid_top_config = B_FALSE;
572 
573 	if (nvlist_alloc(&ret, 0, 0) != 0)
574 		goto nomem;
575 
576 	for (pe = pl->pools; pe != NULL; pe = pe->pe_next) {
577 		uint64_t id, max_txg = 0, hostid = 0;
578 		uint_t holes = 0;
579 
580 		if (nvlist_alloc(&config, NV_UNIQUE_NAME, 0) != 0)
581 			goto nomem;
582 		config_seen = B_FALSE;
583 
584 		/*
585 		 * Iterate over all toplevel vdevs.  Grab the pool configuration
586 		 * from the first one we find, and then go through the rest and
587 		 * add them as necessary to the 'vdevs' member of the config.
588 		 */
589 		for (ve = pe->pe_vdevs; ve != NULL; ve = ve->ve_next) {
590 
591 			/*
592 			 * Determine the best configuration for this vdev by
593 			 * selecting the config with the latest transaction
594 			 * group.
595 			 */
596 			best_txg = 0;
597 			for (ce = ve->ve_configs; ce != NULL;
598 			    ce = ce->ce_next) {
599 
600 				if (ce->ce_txg > best_txg) {
601 					tmp = ce->ce_config;
602 					best_txg = ce->ce_txg;
603 				}
604 			}
605 
606 			/*
607 			 * We rely on the fact that the max txg for the
608 			 * pool will contain the most up-to-date information
609 			 * about the valid top-levels in the vdev namespace.
610 			 */
611 			if (best_txg > max_txg) {
612 				(void) nvlist_remove(config,
613 				    ZPOOL_CONFIG_VDEV_CHILDREN,
614 				    DATA_TYPE_UINT64);
615 				(void) nvlist_remove(config,
616 				    ZPOOL_CONFIG_HOLE_ARRAY,
617 				    DATA_TYPE_UINT64_ARRAY);
618 
619 				max_txg = best_txg;
620 				hole_array = NULL;
621 				holes = 0;
622 				max_id = 0;
623 				valid_top_config = B_FALSE;
624 
625 				if (nvlist_lookup_uint64(tmp,
626 				    ZPOOL_CONFIG_VDEV_CHILDREN, &max_id) == 0) {
627 					verify(nvlist_add_uint64(config,
628 					    ZPOOL_CONFIG_VDEV_CHILDREN,
629 					    max_id) == 0);
630 					valid_top_config = B_TRUE;
631 				}
632 
633 				if (nvlist_lookup_uint64_array(tmp,
634 				    ZPOOL_CONFIG_HOLE_ARRAY, &hole_array,
635 				    &holes) == 0) {
636 					verify(nvlist_add_uint64_array(config,
637 					    ZPOOL_CONFIG_HOLE_ARRAY,
638 					    hole_array, holes) == 0);
639 				}
640 			}
641 
642 			if (!config_seen) {
643 				/*
644 				 * Copy the relevant pieces of data to the pool
645 				 * configuration:
646 				 *
647 				 *	version
648 				 *	pool guid
649 				 *	name
650 				 *	comment (if available)
651 				 *	compatibility features (if available)
652 				 *	pool state
653 				 *	hostid (if available)
654 				 *	hostname (if available)
655 				 */
656 				uint64_t state, version;
657 				const char *comment = NULL;
658 				const char *compatibility = NULL;
659 
660 				version = fnvlist_lookup_uint64(tmp,
661 				    ZPOOL_CONFIG_VERSION);
662 				fnvlist_add_uint64(config,
663 				    ZPOOL_CONFIG_VERSION, version);
664 				guid = fnvlist_lookup_uint64(tmp,
665 				    ZPOOL_CONFIG_POOL_GUID);
666 				fnvlist_add_uint64(config,
667 				    ZPOOL_CONFIG_POOL_GUID, guid);
668 				name = fnvlist_lookup_string(tmp,
669 				    ZPOOL_CONFIG_POOL_NAME);
670 				fnvlist_add_string(config,
671 				    ZPOOL_CONFIG_POOL_NAME, name);
672 
673 				if (nvlist_lookup_string(tmp,
674 				    ZPOOL_CONFIG_COMMENT, &comment) == 0)
675 					fnvlist_add_string(config,
676 					    ZPOOL_CONFIG_COMMENT, comment);
677 
678 				if (nvlist_lookup_string(tmp,
679 				    ZPOOL_CONFIG_COMPATIBILITY,
680 				    &compatibility) == 0)
681 					fnvlist_add_string(config,
682 					    ZPOOL_CONFIG_COMPATIBILITY,
683 					    compatibility);
684 
685 				state = fnvlist_lookup_uint64(tmp,
686 				    ZPOOL_CONFIG_POOL_STATE);
687 				fnvlist_add_uint64(config,
688 				    ZPOOL_CONFIG_POOL_STATE, state);
689 
690 				hostid = 0;
691 				if (nvlist_lookup_uint64(tmp,
692 				    ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
693 					fnvlist_add_uint64(config,
694 					    ZPOOL_CONFIG_HOSTID, hostid);
695 					hostname = fnvlist_lookup_string(tmp,
696 					    ZPOOL_CONFIG_HOSTNAME);
697 					fnvlist_add_string(config,
698 					    ZPOOL_CONFIG_HOSTNAME, hostname);
699 				}
700 
701 				config_seen = B_TRUE;
702 			}
703 
704 			/*
705 			 * Add this top-level vdev to the child array.
706 			 */
707 			verify(nvlist_lookup_nvlist(tmp,
708 			    ZPOOL_CONFIG_VDEV_TREE, &nvtop) == 0);
709 			verify(nvlist_lookup_uint64(nvtop, ZPOOL_CONFIG_ID,
710 			    &id) == 0);
711 
712 			if (id >= children) {
713 				nvlist_t **newchild;
714 
715 				newchild = zutil_alloc(hdl, (id + 1) *
716 				    sizeof (nvlist_t *));
717 				if (newchild == NULL)
718 					goto nomem;
719 
720 				for (c = 0; c < children; c++)
721 					newchild[c] = child[c];
722 
723 				free(child);
724 				child = newchild;
725 				children = id + 1;
726 			}
727 			if (nvlist_dup(nvtop, &child[id], 0) != 0)
728 				goto nomem;
729 
730 		}
731 
732 		/*
733 		 * If we have information about all the top-levels then
734 		 * clean up the nvlist which we've constructed. This
735 		 * means removing any extraneous devices that are
736 		 * beyond the valid range or adding devices to the end
737 		 * of our array which appear to be missing.
738 		 */
739 		if (valid_top_config) {
740 			if (max_id < children) {
741 				for (c = max_id; c < children; c++)
742 					nvlist_free(child[c]);
743 				children = max_id;
744 			} else if (max_id > children) {
745 				nvlist_t **newchild;
746 
747 				newchild = zutil_alloc(hdl, (max_id) *
748 				    sizeof (nvlist_t *));
749 				if (newchild == NULL)
750 					goto nomem;
751 
752 				for (c = 0; c < children; c++)
753 					newchild[c] = child[c];
754 
755 				free(child);
756 				child = newchild;
757 				children = max_id;
758 			}
759 		}
760 
761 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
762 		    &guid) == 0);
763 
764 		/*
765 		 * The vdev namespace may contain holes as a result of
766 		 * device removal. We must add them back into the vdev
767 		 * tree before we process any missing devices.
768 		 */
769 		if (holes > 0) {
770 			ASSERT(valid_top_config);
771 
772 			for (c = 0; c < children; c++) {
773 				nvlist_t *holey;
774 
775 				if (child[c] != NULL ||
776 				    !vdev_is_hole(hole_array, holes, c))
777 					continue;
778 
779 				if (nvlist_alloc(&holey, NV_UNIQUE_NAME,
780 				    0) != 0)
781 					goto nomem;
782 
783 				/*
784 				 * Holes in the namespace are treated as
785 				 * "hole" top-level vdevs and have a
786 				 * special flag set on them.
787 				 */
788 				if (nvlist_add_string(holey,
789 				    ZPOOL_CONFIG_TYPE,
790 				    VDEV_TYPE_HOLE) != 0 ||
791 				    nvlist_add_uint64(holey,
792 				    ZPOOL_CONFIG_ID, c) != 0 ||
793 				    nvlist_add_uint64(holey,
794 				    ZPOOL_CONFIG_GUID, 0ULL) != 0) {
795 					nvlist_free(holey);
796 					goto nomem;
797 				}
798 				child[c] = holey;
799 			}
800 		}
801 
802 		/*
803 		 * Look for any missing top-level vdevs.  If this is the case,
804 		 * create a faked up 'missing' vdev as a placeholder.  We cannot
805 		 * simply compress the child array, because the kernel performs
806 		 * certain checks to make sure the vdev IDs match their location
807 		 * in the configuration.
808 		 */
809 		for (c = 0; c < children; c++) {
810 			if (child[c] == NULL) {
811 				nvlist_t *missing;
812 				if (nvlist_alloc(&missing, NV_UNIQUE_NAME,
813 				    0) != 0)
814 					goto nomem;
815 				if (nvlist_add_string(missing,
816 				    ZPOOL_CONFIG_TYPE,
817 				    VDEV_TYPE_MISSING) != 0 ||
818 				    nvlist_add_uint64(missing,
819 				    ZPOOL_CONFIG_ID, c) != 0 ||
820 				    nvlist_add_uint64(missing,
821 				    ZPOOL_CONFIG_GUID, 0ULL) != 0) {
822 					nvlist_free(missing);
823 					goto nomem;
824 				}
825 				child[c] = missing;
826 			}
827 		}
828 
829 		/*
830 		 * Put all of this pool's top-level vdevs into a root vdev.
831 		 */
832 		if (nvlist_alloc(&nvroot, NV_UNIQUE_NAME, 0) != 0)
833 			goto nomem;
834 		if (nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
835 		    VDEV_TYPE_ROOT) != 0 ||
836 		    nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) != 0 ||
837 		    nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, guid) != 0 ||
838 		    nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
839 		    (const nvlist_t **)child, children) != 0) {
840 			nvlist_free(nvroot);
841 			goto nomem;
842 		}
843 
844 		for (c = 0; c < children; c++)
845 			nvlist_free(child[c]);
846 		free(child);
847 		children = 0;
848 		child = NULL;
849 
850 		/*
851 		 * Go through and fix up any paths and/or devids based on our
852 		 * known list of vdev GUID -> path mappings.
853 		 */
854 		if (fix_paths(hdl, nvroot, pl->names) != 0) {
855 			nvlist_free(nvroot);
856 			goto nomem;
857 		}
858 
859 		/*
860 		 * Add the root vdev to this pool's configuration.
861 		 */
862 		if (nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
863 		    nvroot) != 0) {
864 			nvlist_free(nvroot);
865 			goto nomem;
866 		}
867 		nvlist_free(nvroot);
868 
869 		/*
870 		 * zdb uses this path to report on active pools that were
871 		 * imported or created using -R.
872 		 */
873 		if (active_ok)
874 			goto add_pool;
875 
876 		/*
877 		 * Determine if this pool is currently active, in which case we
878 		 * can't actually import it.
879 		 */
880 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
881 		    &name) == 0);
882 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
883 		    &guid) == 0);
884 
885 		if (zutil_pool_active(hdl, name, guid, &isactive) != 0)
886 			goto error;
887 
888 		if (isactive) {
889 			nvlist_free(config);
890 			config = NULL;
891 			continue;
892 		}
893 
894 		if (policy != NULL) {
895 			if (nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
896 			    policy) != 0)
897 				goto nomem;
898 		}
899 
900 		if ((nvl = zutil_refresh_config(hdl, config)) == NULL) {
901 			nvlist_free(config);
902 			config = NULL;
903 			continue;
904 		}
905 
906 		nvlist_free(config);
907 		config = nvl;
908 
909 		/*
910 		 * Go through and update the paths for spares, now that we have
911 		 * them.  A path which still refers to the expected device is
912 		 * kept as is, it may well be more persistent than any of the
913 		 * scanned names.
914 		 */
915 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
916 		    &nvroot) == 0);
917 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
918 		    &spares, &nspares) == 0) {
919 			for (i = 0; i < nspares; i++) {
920 				if (keep_aux_path &&
921 				    aux_path_active(spares[i])) {
922 					update_vdev_config_dev_strs(spares[i]);
923 					continue;
924 				}
925 				if (fix_paths(hdl, spares[i], pl->names) != 0)
926 					goto nomem;
927 			}
928 		}
929 
930 		/*
931 		 * Update the paths for l2cache devices.
932 		 */
933 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
934 		    &l2cache, &nl2cache) == 0) {
935 			for (i = 0; i < nl2cache; i++) {
936 				if (keep_aux_path &&
937 				    aux_path_active(l2cache[i])) {
938 					update_vdev_config_dev_strs(l2cache[i]);
939 					continue;
940 				}
941 				if (fix_paths(hdl, l2cache[i], pl->names) != 0)
942 					goto nomem;
943 			}
944 		}
945 
946 		/*
947 		 * Restore the original information read from the actual label.
948 		 */
949 		(void) nvlist_remove(config, ZPOOL_CONFIG_HOSTID,
950 		    DATA_TYPE_UINT64);
951 		(void) nvlist_remove(config, ZPOOL_CONFIG_HOSTNAME,
952 		    DATA_TYPE_STRING);
953 		if (hostid != 0) {
954 			verify(nvlist_add_uint64(config, ZPOOL_CONFIG_HOSTID,
955 			    hostid) == 0);
956 			verify(nvlist_add_string(config, ZPOOL_CONFIG_HOSTNAME,
957 			    hostname) == 0);
958 		}
959 
960 add_pool:
961 		/*
962 		 * Add this pool to the list of configs.
963 		 */
964 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
965 		    &name) == 0);
966 
967 		if (nvlist_add_nvlist(ret, name, config) != 0)
968 			goto nomem;
969 
970 		nvlist_free(config);
971 		config = NULL;
972 	}
973 
974 	return (ret);
975 
976 nomem:
977 	(void) zutil_no_memory(hdl);
978 error:
979 	nvlist_free(config);
980 	nvlist_free(ret);
981 	for (c = 0; c < children; c++)
982 		nvlist_free(child[c]);
983 	free(child);
984 
985 	return (NULL);
986 }
987 
988 /*
989  * Return the offset of the given label.
990  */
991 static uint64_t
label_offset(uint64_t size,int l)992 label_offset(uint64_t size, int l)
993 {
994 	ASSERT0(P2PHASE_TYPED(size, sizeof (vdev_label_t), uint64_t));
995 	return (l * sizeof (vdev_label_t) + (l < VDEV_LABELS / 2 ?
996 	    0 : size - VDEV_LABELS * sizeof (vdev_label_t)));
997 }
998 
999 /*
1000  * The same description applies as to zpool_read_label below,
1001  * except here we do it without aio, presumably because an aio call
1002  * errored out in a way we think not using it could circumvent.
1003  */
1004 static int
zpool_read_label_slow(int fd,nvlist_t ** config,int * num_labels)1005 zpool_read_label_slow(int fd, nvlist_t **config, int *num_labels)
1006 {
1007 	struct stat64 statbuf;
1008 	int l, count = 0;
1009 	vdev_phys_t *label;
1010 	nvlist_t *expected_config = NULL;
1011 	uint64_t expected_guid = 0, size;
1012 
1013 	*config = NULL;
1014 
1015 	if (fstat64_blk(fd, &statbuf) == -1)
1016 		return (0);
1017 	size = P2ALIGN_TYPED(statbuf.st_size, sizeof (vdev_label_t), uint64_t);
1018 
1019 	label = (vdev_phys_t *)umem_alloc_aligned(sizeof (*label), PAGESIZE,
1020 	    UMEM_DEFAULT);
1021 	if (label == NULL)
1022 		return (-1);
1023 
1024 	for (l = 0; l < VDEV_LABELS; l++) {
1025 		uint64_t state, guid, txg;
1026 		off_t offset = label_offset(size, l) + VDEV_SKIP_SIZE;
1027 
1028 		if (pread64(fd, label, sizeof (vdev_phys_t),
1029 		    offset) != sizeof (vdev_phys_t))
1030 			continue;
1031 
1032 		if (nvlist_unpack(label->vp_nvlist,
1033 		    sizeof (label->vp_nvlist), config, 0) != 0)
1034 			continue;
1035 
1036 		if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_GUID,
1037 		    &guid) != 0 || guid == 0) {
1038 			nvlist_free(*config);
1039 			continue;
1040 		}
1041 
1042 		if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_STATE,
1043 		    &state) != 0 || state > POOL_STATE_L2CACHE) {
1044 			nvlist_free(*config);
1045 			continue;
1046 		}
1047 
1048 		if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
1049 		    (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_TXG,
1050 		    &txg) != 0 || txg == 0)) {
1051 			nvlist_free(*config);
1052 			continue;
1053 		}
1054 
1055 		if (expected_guid) {
1056 			if (expected_guid == guid)
1057 				count++;
1058 
1059 			nvlist_free(*config);
1060 		} else {
1061 			expected_config = *config;
1062 			expected_guid = guid;
1063 			count++;
1064 		}
1065 	}
1066 
1067 	if (num_labels != NULL)
1068 		*num_labels = count;
1069 
1070 	umem_free_aligned(label, sizeof (*label));
1071 	*config = expected_config;
1072 
1073 	return (0);
1074 }
1075 
1076 /*
1077  * Given a file descriptor, read the label information and return an nvlist
1078  * describing the configuration, if there is one.  The number of valid
1079  * labels found will be returned in num_labels when non-NULL.
1080  */
1081 int
zpool_read_label(int fd,nvlist_t ** config,int * num_labels)1082 zpool_read_label(int fd, nvlist_t **config, int *num_labels)
1083 {
1084 #ifndef HAVE_AIO_H
1085 	return (zpool_read_label_slow(fd, config, num_labels));
1086 #else
1087 	struct stat64 statbuf;
1088 	struct aiocb aiocbs[VDEV_LABELS];
1089 	struct aiocb *aiocbps[VDEV_LABELS];
1090 	vdev_phys_t *labels;
1091 	nvlist_t *expected_config = NULL;
1092 	uint64_t expected_guid = 0, size;
1093 	int error, l, count = 0;
1094 
1095 	*config = NULL;
1096 
1097 	if (fstat64_blk(fd, &statbuf) == -1)
1098 		return (0);
1099 	size = P2ALIGN_TYPED(statbuf.st_size, sizeof (vdev_label_t), uint64_t);
1100 
1101 	labels = (vdev_phys_t *)umem_alloc_aligned(
1102 	    VDEV_LABELS * sizeof (*labels), PAGESIZE, UMEM_DEFAULT);
1103 	if (labels == NULL)
1104 		return (-1);
1105 
1106 	memset(aiocbs, 0, sizeof (aiocbs));
1107 	for (l = 0; l < VDEV_LABELS; l++) {
1108 		off_t offset = label_offset(size, l) + VDEV_SKIP_SIZE;
1109 
1110 		aiocbs[l].aio_fildes = fd;
1111 		aiocbs[l].aio_offset = offset;
1112 		aiocbs[l].aio_buf = &labels[l];
1113 		aiocbs[l].aio_nbytes = sizeof (vdev_phys_t);
1114 		aiocbs[l].aio_lio_opcode = LIO_READ;
1115 		aiocbps[l] = &aiocbs[l];
1116 	}
1117 
1118 	if (lio_listio(LIO_WAIT, aiocbps, VDEV_LABELS, NULL) != 0) {
1119 		int saved_errno = errno;
1120 		boolean_t do_slow = B_FALSE;
1121 		error = -1;
1122 
1123 		if (errno == EAGAIN || errno == EINTR || errno == EIO) {
1124 			/*
1125 			 * A portion of the requests may have been submitted.
1126 			 * Clean them up.
1127 			 */
1128 			for (l = 0; l < VDEV_LABELS; l++) {
1129 				errno = 0;
1130 				switch (aio_error(&aiocbs[l])) {
1131 				case EINVAL:
1132 					break;
1133 				case EINPROGRESS:
1134 					/*
1135 					 * This shouldn't be possible to
1136 					 * encounter, die if we do.
1137 					 */
1138 					ASSERT(B_FALSE);
1139 					zfs_fallthrough;
1140 				case EREMOTEIO:
1141 					/*
1142 					 * May be returned by an NVMe device
1143 					 * which is visible in /dev/ but due
1144 					 * to a low-level format change, or
1145 					 * other error, needs to be rescanned.
1146 					 * Try the slow method.
1147 					 */
1148 					zfs_fallthrough;
1149 				case EAGAIN:
1150 				case EOPNOTSUPP:
1151 				case ENOSYS:
1152 					do_slow = B_TRUE;
1153 					zfs_fallthrough;
1154 				case 0:
1155 				default:
1156 					(void) aio_return(&aiocbs[l]);
1157 				}
1158 			}
1159 		}
1160 		if (do_slow) {
1161 			/*
1162 			 * At least some IO involved access unsafe-for-AIO
1163 			 * files. Let's try again, without AIO this time.
1164 			 */
1165 			error = zpool_read_label_slow(fd, config, num_labels);
1166 			saved_errno = errno;
1167 		}
1168 		umem_free_aligned(labels, VDEV_LABELS * sizeof (*labels));
1169 		errno = saved_errno;
1170 		return (error);
1171 	}
1172 
1173 	for (l = 0; l < VDEV_LABELS; l++) {
1174 		uint64_t state, guid, txg;
1175 
1176 		if (aio_return(&aiocbs[l]) != sizeof (vdev_phys_t))
1177 			continue;
1178 
1179 		if (nvlist_unpack(labels[l].vp_nvlist,
1180 		    sizeof (labels[l].vp_nvlist), config, 0) != 0)
1181 			continue;
1182 
1183 		if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_GUID,
1184 		    &guid) != 0 || guid == 0) {
1185 			nvlist_free(*config);
1186 			continue;
1187 		}
1188 
1189 		if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_STATE,
1190 		    &state) != 0 || state > POOL_STATE_L2CACHE) {
1191 			nvlist_free(*config);
1192 			continue;
1193 		}
1194 
1195 		if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
1196 		    (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_TXG,
1197 		    &txg) != 0 || txg == 0)) {
1198 			nvlist_free(*config);
1199 			continue;
1200 		}
1201 
1202 		if (expected_guid) {
1203 			if (expected_guid == guid)
1204 				count++;
1205 
1206 			nvlist_free(*config);
1207 		} else {
1208 			expected_config = *config;
1209 			expected_guid = guid;
1210 			count++;
1211 		}
1212 	}
1213 
1214 	if (num_labels != NULL)
1215 		*num_labels = count;
1216 
1217 	umem_free_aligned(labels, VDEV_LABELS * sizeof (*labels));
1218 	*config = expected_config;
1219 
1220 	return (0);
1221 #endif
1222 }
1223 
1224 /*
1225  * Sorted by full path and then vdev guid to allow for multiple entries with
1226  * the same full path name.  This is required because it's possible to
1227  * have multiple block devices with labels that refer to the same
1228  * ZPOOL_CONFIG_PATH yet have different vdev guids.  In this case both
1229  * entries need to be added to the cache.  Scenarios where this can occur
1230  * include overwritten pool labels, devices which are visible from multiple
1231  * hosts and multipath devices.
1232  */
1233 int
slice_cache_compare(const void * arg1,const void * arg2)1234 slice_cache_compare(const void *arg1, const void *arg2)
1235 {
1236 	const char  *nm1 = ((rdsk_node_t *)arg1)->rn_name;
1237 	const char  *nm2 = ((rdsk_node_t *)arg2)->rn_name;
1238 	uint64_t guid1 = ((rdsk_node_t *)arg1)->rn_vdev_guid;
1239 	uint64_t guid2 = ((rdsk_node_t *)arg2)->rn_vdev_guid;
1240 	int rv;
1241 
1242 	rv = TREE_ISIGN(strcmp(nm1, nm2));
1243 	if (rv)
1244 		return (rv);
1245 
1246 	return (TREE_CMP(guid1, guid2));
1247 }
1248 
1249 static int
label_paths_impl(libpc_handle_t * hdl,nvlist_t * nvroot,uint64_t pool_guid,uint64_t vdev_guid,const char ** path,const char ** devid)1250 label_paths_impl(libpc_handle_t *hdl, nvlist_t *nvroot, uint64_t pool_guid,
1251     uint64_t vdev_guid, const char **path, const char **devid)
1252 {
1253 	nvlist_t **child;
1254 	uint_t c, children;
1255 	uint64_t guid;
1256 	const char *val;
1257 	int error;
1258 
1259 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
1260 	    &child, &children) == 0) {
1261 		for (c = 0; c < children; c++) {
1262 			error  = label_paths_impl(hdl, child[c],
1263 			    pool_guid, vdev_guid, path, devid);
1264 			if (error)
1265 				return (error);
1266 		}
1267 		return (0);
1268 	}
1269 
1270 	if (nvroot == NULL)
1271 		return (0);
1272 
1273 	error = nvlist_lookup_uint64(nvroot, ZPOOL_CONFIG_GUID, &guid);
1274 	if ((error != 0) || (guid != vdev_guid))
1275 		return (0);
1276 
1277 	error = nvlist_lookup_string(nvroot, ZPOOL_CONFIG_PATH, &val);
1278 	if (error == 0)
1279 		*path = val;
1280 
1281 	error = nvlist_lookup_string(nvroot, ZPOOL_CONFIG_DEVID, &val);
1282 	if (error == 0)
1283 		*devid = val;
1284 
1285 	return (0);
1286 }
1287 
1288 /*
1289  * Given a disk label fetch the ZPOOL_CONFIG_PATH and ZPOOL_CONFIG_DEVID
1290  * and store these strings as config_path and devid_path respectively.
1291  * The returned pointers are only valid as long as label remains valid.
1292  */
1293 int
label_paths(libpc_handle_t * hdl,nvlist_t * label,const char ** path,const char ** devid)1294 label_paths(libpc_handle_t *hdl, nvlist_t *label, const char **path,
1295     const char **devid)
1296 {
1297 	nvlist_t *nvroot;
1298 	uint64_t pool_guid;
1299 	uint64_t vdev_guid;
1300 	uint64_t state;
1301 
1302 	*path = NULL;
1303 	*devid = NULL;
1304 	if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &vdev_guid) != 0)
1305 		return (ENOENT);
1306 
1307 	/*
1308 	 * In case of spare or l2cache, we directly return path/devid from the
1309 	 * label.
1310 	 */
1311 	if (!(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE, &state)) &&
1312 	    (state == POOL_STATE_SPARE || state == POOL_STATE_L2CACHE)) {
1313 		(void) nvlist_lookup_string(label, ZPOOL_CONFIG_PATH, path);
1314 		(void) nvlist_lookup_string(label, ZPOOL_CONFIG_DEVID, devid);
1315 		return (0);
1316 	}
1317 
1318 	if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_VDEV_TREE, &nvroot) ||
1319 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID, &pool_guid))
1320 		return (ENOENT);
1321 
1322 	return (label_paths_impl(hdl, nvroot, pool_guid, vdev_guid, path,
1323 	    devid));
1324 }
1325 
1326 static void
zpool_find_import_scan_add_slice(libpc_handle_t * hdl,pthread_mutex_t * lock,avl_tree_t * cache,const char * path,const char * name,int order)1327 zpool_find_import_scan_add_slice(libpc_handle_t *hdl, pthread_mutex_t *lock,
1328     avl_tree_t *cache, const char *path, const char *name, int order)
1329 {
1330 	avl_index_t where;
1331 	rdsk_node_t *slice;
1332 
1333 	slice = zutil_alloc(hdl, sizeof (rdsk_node_t));
1334 	if (asprintf(&slice->rn_name, "%s/%s", path, name) == -1) {
1335 		free(slice);
1336 		return;
1337 	}
1338 	slice->rn_vdev_guid = 0;
1339 	slice->rn_lock = lock;
1340 	slice->rn_avl = cache;
1341 	slice->rn_hdl = hdl;
1342 	slice->rn_order = order + IMPORT_ORDER_SCAN_OFFSET;
1343 	slice->rn_labelpaths = B_FALSE;
1344 
1345 	pthread_mutex_lock(lock);
1346 	if (avl_find(cache, slice, &where)) {
1347 		free(slice->rn_name);
1348 		free(slice);
1349 	} else {
1350 		avl_insert(cache, slice, where);
1351 	}
1352 	pthread_mutex_unlock(lock);
1353 }
1354 
1355 static int
zpool_find_import_scan_dir(libpc_handle_t * hdl,pthread_mutex_t * lock,avl_tree_t * cache,const char * dir,int order)1356 zpool_find_import_scan_dir(libpc_handle_t *hdl, pthread_mutex_t *lock,
1357     avl_tree_t *cache, const char *dir, int order)
1358 {
1359 	int error;
1360 	char path[MAXPATHLEN];
1361 	struct dirent64 *dp;
1362 	DIR *dirp;
1363 
1364 	if (realpath(dir, path) == NULL) {
1365 		error = errno;
1366 		if (error == ENOENT)
1367 			return (0);
1368 
1369 		zutil_error_aux(hdl, "%s", zfs_strerror(error));
1370 		(void) zutil_error_fmt(hdl, LPC_BADPATH, dgettext(TEXT_DOMAIN,
1371 		    "cannot resolve path '%s'"), dir);
1372 		return (error);
1373 	}
1374 
1375 	dirp = opendir(path);
1376 	if (dirp == NULL) {
1377 		error = errno;
1378 		zutil_error_aux(hdl, "%s", zfs_strerror(error));
1379 		(void) zutil_error_fmt(hdl, LPC_BADPATH, dgettext(TEXT_DOMAIN,
1380 		    "cannot open '%s'"), path);
1381 		return (error);
1382 	}
1383 
1384 	while ((dp = readdir64(dirp)) != NULL) {
1385 		const char *name = dp->d_name;
1386 		if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0)
1387 			continue;
1388 
1389 		switch (dp->d_type) {
1390 		case DT_UNKNOWN:
1391 		case DT_BLK:
1392 		case DT_LNK:
1393 #ifdef __FreeBSD__
1394 		case DT_CHR:
1395 #endif
1396 		case DT_REG:
1397 			break;
1398 		default:
1399 			continue;
1400 		}
1401 
1402 		zpool_find_import_scan_add_slice(hdl, lock, cache, path, name,
1403 		    order);
1404 	}
1405 
1406 	(void) closedir(dirp);
1407 	return (0);
1408 }
1409 
1410 static int
zpool_find_import_scan_path(libpc_handle_t * hdl,pthread_mutex_t * lock,avl_tree_t * cache,const char * dir,int order)1411 zpool_find_import_scan_path(libpc_handle_t *hdl, pthread_mutex_t *lock,
1412     avl_tree_t *cache, const char *dir, int order)
1413 {
1414 	int error = 0;
1415 	char path[MAXPATHLEN];
1416 	char *d = NULL;
1417 	ssize_t dl;
1418 	const char *dpath, *name;
1419 
1420 	/*
1421 	 * Separate the directory and the basename.
1422 	 * We do this so that we can get the realpath of
1423 	 * the directory. We don't get the realpath on the
1424 	 * whole path because if it's a symlink, we want the
1425 	 * path of the symlink not where it points to.
1426 	 */
1427 	name = zfs_basename(dir);
1428 	if ((dl = zfs_dirnamelen(dir)) == -1)
1429 		dpath = ".";
1430 	else
1431 		dpath = d = zutil_strndup(hdl, dir, dl);
1432 
1433 	if (realpath(dpath, path) == NULL) {
1434 		error = errno;
1435 		if (error == ENOENT) {
1436 			error = 0;
1437 			goto out;
1438 		}
1439 
1440 		zutil_error_aux(hdl, "%s", zfs_strerror(error));
1441 		(void) zutil_error_fmt(hdl, LPC_BADPATH, dgettext(TEXT_DOMAIN,
1442 		    "cannot resolve path '%s'"), dir);
1443 		goto out;
1444 	}
1445 
1446 	zpool_find_import_scan_add_slice(hdl, lock, cache, path, name, order);
1447 
1448 out:
1449 	free(d);
1450 	return (error);
1451 }
1452 
1453 /*
1454  * Scan a list of directories for zfs devices.
1455  */
1456 static int
zpool_find_import_scan(libpc_handle_t * hdl,pthread_mutex_t * lock,avl_tree_t ** slice_cache,const char * const * dir,size_t dirs)1457 zpool_find_import_scan(libpc_handle_t *hdl, pthread_mutex_t *lock,
1458     avl_tree_t **slice_cache, const char * const *dir, size_t dirs)
1459 {
1460 	avl_tree_t *cache;
1461 	rdsk_node_t *slice;
1462 	void *cookie;
1463 	int i, error;
1464 
1465 	*slice_cache = NULL;
1466 	cache = zutil_alloc(hdl, sizeof (avl_tree_t));
1467 	avl_create(cache, slice_cache_compare, sizeof (rdsk_node_t),
1468 	    offsetof(rdsk_node_t, rn_node));
1469 
1470 	for (i = 0; i < dirs; i++) {
1471 		struct stat sbuf;
1472 
1473 		if (stat(dir[i], &sbuf) != 0) {
1474 			error = errno;
1475 			if (error == ENOENT)
1476 				continue;
1477 
1478 			zutil_error_aux(hdl, "%s", zfs_strerror(error));
1479 			(void) zutil_error_fmt(hdl, LPC_BADPATH, dgettext(
1480 			    TEXT_DOMAIN, "cannot resolve path '%s'"), dir[i]);
1481 			goto error;
1482 		}
1483 
1484 		/*
1485 		 * If dir[i] is a directory, we walk through it and add all
1486 		 * the entries to the cache. If it's not a directory, we just
1487 		 * add it to the cache.
1488 		 */
1489 		if (S_ISDIR(sbuf.st_mode)) {
1490 			if ((error = zpool_find_import_scan_dir(hdl, lock,
1491 			    cache, dir[i], i)) != 0)
1492 				goto error;
1493 		} else {
1494 			if ((error = zpool_find_import_scan_path(hdl, lock,
1495 			    cache, dir[i], i)) != 0)
1496 				goto error;
1497 		}
1498 	}
1499 
1500 	*slice_cache = cache;
1501 	return (0);
1502 
1503 error:
1504 	cookie = NULL;
1505 	while ((slice = avl_destroy_nodes(cache, &cookie)) != NULL) {
1506 		free(slice->rn_name);
1507 		free(slice);
1508 	}
1509 	free(cache);
1510 
1511 	return (error);
1512 }
1513 
1514 /*
1515  * Given a list of directories to search, find all pools stored on disk.  This
1516  * includes partial pools which are not available to import.  If no args are
1517  * given (argc is 0), then the default directory (/dev/dsk) is searched.
1518  * poolname or guid (but not both) are provided by the caller when trying
1519  * to import a specific pool.
1520  */
1521 static nvlist_t *
zpool_find_import_impl(libpc_handle_t * hdl,importargs_t * iarg,pthread_mutex_t * lock,avl_tree_t * cache)1522 zpool_find_import_impl(libpc_handle_t *hdl, importargs_t *iarg,
1523     pthread_mutex_t *lock, avl_tree_t *cache)
1524 {
1525 	(void) lock;
1526 	nvlist_t *ret = NULL;
1527 	pool_list_t pools = { 0 };
1528 	pool_entry_t *pe, *penext;
1529 	vdev_entry_t *ve, *venext;
1530 	config_entry_t *ce, *cenext;
1531 	name_entry_t *ne, *nenext;
1532 	rdsk_node_t *slice;
1533 	void *cookie;
1534 	taskq_t *tq;
1535 
1536 	verify(iarg->poolname == NULL || iarg->guid == 0);
1537 
1538 	/*
1539 	 * Create a thread pool to parallelize the process of reading and
1540 	 * validating labels, a large number of threads can be used due to
1541 	 * minimal contention.
1542 	 */
1543 	long threads = 2 * sysconf(_SC_NPROCESSORS_ONLN);
1544 #ifdef HAVE_AIO_H
1545 	long am;
1546 #ifdef _SC_AIO_LISTIO_MAX
1547 	am = sysconf(_SC_AIO_LISTIO_MAX);
1548 	if (am >= VDEV_LABELS)
1549 		threads = MIN(threads, am / VDEV_LABELS);
1550 #endif
1551 #ifdef _SC_AIO_MAX
1552 	am = sysconf(_SC_AIO_MAX);
1553 	if (am >= VDEV_LABELS)
1554 		threads = MIN(threads, am / VDEV_LABELS);
1555 #endif
1556 #endif
1557 	tq = taskq_create("zpool_find_import", threads, minclsyspri, 1, INT_MAX,
1558 	    TASKQ_DYNAMIC);
1559 	for (slice = avl_first(cache); slice;
1560 	    (slice = avl_walk(cache, slice, AVL_AFTER)))
1561 		(void) taskq_dispatch(tq, zpool_open_func, slice, TQ_SLEEP);
1562 
1563 	taskq_wait(tq);
1564 	taskq_destroy(tq);
1565 
1566 	/*
1567 	 * Process the cache, filtering out any entries which are not
1568 	 * for the specified pool then adding matching label configs.
1569 	 */
1570 	cookie = NULL;
1571 	while ((slice = avl_destroy_nodes(cache, &cookie)) != NULL) {
1572 		if (slice->rn_config != NULL) {
1573 			nvlist_t *config = slice->rn_config;
1574 			boolean_t matched = B_TRUE;
1575 			boolean_t aux = B_FALSE;
1576 			int fd;
1577 
1578 			/*
1579 			 * Check if it's a spare or l2cache device. If it is,
1580 			 * we need to skip the name and guid check since they
1581 			 * don't exist on aux device label.
1582 			 */
1583 			if (iarg->poolname != NULL || iarg->guid != 0) {
1584 				uint64_t state;
1585 				aux = nvlist_lookup_uint64(config,
1586 				    ZPOOL_CONFIG_POOL_STATE, &state) == 0 &&
1587 				    (state == POOL_STATE_SPARE ||
1588 				    state == POOL_STATE_L2CACHE);
1589 			}
1590 
1591 			if (iarg->poolname != NULL && !aux) {
1592 				const char *pname;
1593 
1594 				matched = nvlist_lookup_string(config,
1595 				    ZPOOL_CONFIG_POOL_NAME, &pname) == 0 &&
1596 				    strcmp(iarg->poolname, pname) == 0;
1597 			} else if (iarg->guid != 0 && !aux) {
1598 				uint64_t this_guid;
1599 
1600 				matched = nvlist_lookup_uint64(config,
1601 				    ZPOOL_CONFIG_POOL_GUID, &this_guid) == 0 &&
1602 				    iarg->guid == this_guid;
1603 			}
1604 			if (matched) {
1605 				/*
1606 				 * Verify all remaining entries can be opened
1607 				 * exclusively. This will prune all underlying
1608 				 * multipath devices which otherwise could
1609 				 * result in the vdev appearing as UNAVAIL.
1610 				 *
1611 				 * Under zdb, this step isn't required and
1612 				 * would prevent a zdb -e of active pools with
1613 				 * no cachefile.
1614 				 */
1615 				fd = open(slice->rn_name,
1616 				    O_RDONLY | O_EXCL | O_CLOEXEC);
1617 				if (fd >= 0 || iarg->can_be_active) {
1618 					if (fd >= 0)
1619 						close(fd);
1620 					add_config(hdl, &pools,
1621 					    slice->rn_name, slice->rn_order,
1622 					    slice->rn_num_labels, config);
1623 				}
1624 			}
1625 			nvlist_free(config);
1626 		}
1627 		free(slice->rn_name);
1628 		free(slice);
1629 	}
1630 	avl_destroy(cache);
1631 	free(cache);
1632 
1633 	/*
1634 	 * Existing spare and l2cache paths may only be trusted when the
1635 	 * search locations were not chosen by the caller.  An import from
1636 	 * user supplied directories (or a scan of them) is the documented
1637 	 * way to deliberately rewrite all of the pool's device paths, so
1638 	 * in that case they must be derived from the scanned names alone.
1639 	 */
1640 	ret = get_configs(hdl, &pools, iarg->can_be_active,
1641 	    iarg->paths == 0 && !iarg->scan, iarg->policy);
1642 
1643 	for (pe = pools.pools; pe != NULL; pe = penext) {
1644 		penext = pe->pe_next;
1645 		for (ve = pe->pe_vdevs; ve != NULL; ve = venext) {
1646 			venext = ve->ve_next;
1647 			for (ce = ve->ve_configs; ce != NULL; ce = cenext) {
1648 				cenext = ce->ce_next;
1649 				nvlist_free(ce->ce_config);
1650 				free(ce);
1651 			}
1652 			free(ve);
1653 		}
1654 		free(pe);
1655 	}
1656 
1657 	for (ne = pools.names; ne != NULL; ne = nenext) {
1658 		nenext = ne->ne_next;
1659 		free(ne->ne_name);
1660 		free(ne);
1661 	}
1662 
1663 	return (ret);
1664 }
1665 
1666 /*
1667  * Given a config, discover the paths for the devices which
1668  * exist in the config.
1669  */
1670 static int
discover_cached_paths(libpc_handle_t * hdl,nvlist_t * nv,avl_tree_t * cache,pthread_mutex_t * lock)1671 discover_cached_paths(libpc_handle_t *hdl, nvlist_t *nv,
1672     avl_tree_t *cache, pthread_mutex_t *lock)
1673 {
1674 	const char *path = NULL;
1675 	ssize_t dl;
1676 	uint_t children;
1677 	nvlist_t **child;
1678 
1679 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1680 	    &child, &children) == 0) {
1681 		for (int c = 0; c < children; c++) {
1682 			discover_cached_paths(hdl, child[c], cache, lock);
1683 		}
1684 	}
1685 
1686 	/*
1687 	 * Once we have the path, we need to add the directory to
1688 	 * our directory cache.
1689 	 */
1690 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
1691 		int ret;
1692 		char c = '\0';
1693 		if ((dl = zfs_dirnamelen(path)) == -1) {
1694 			path = ".";
1695 		} else {
1696 			c = path[dl];
1697 			((char *)path)[dl] = '\0';
1698 
1699 		}
1700 		ret = zpool_find_import_scan_dir(hdl, lock, cache,
1701 		    path, 0);
1702 		if (c != '\0')
1703 			((char *)path)[dl] = c;
1704 
1705 		return (ret);
1706 	}
1707 	return (0);
1708 }
1709 
1710 /*
1711  * Given a cache file, return the contents as a list of importable pools.
1712  * poolname or guid (but not both) are provided by the caller when trying
1713  * to import a specific pool.
1714  */
1715 static nvlist_t *
zpool_find_import_cached(libpc_handle_t * hdl,importargs_t * iarg)1716 zpool_find_import_cached(libpc_handle_t *hdl, importargs_t *iarg)
1717 {
1718 	char *buf;
1719 	int fd;
1720 	struct stat64 statbuf;
1721 	nvlist_t *raw, *src, *dst;
1722 	nvlist_t *pools;
1723 	nvpair_t *elem;
1724 	const char *name;
1725 	uint64_t this_guid;
1726 	boolean_t active;
1727 
1728 	verify(iarg->poolname == NULL || iarg->guid == 0);
1729 
1730 	if ((fd = open(iarg->cachefile, O_RDONLY | O_CLOEXEC)) < 0) {
1731 		zutil_error_aux(hdl, "%s", zfs_strerror(errno));
1732 		(void) zutil_error(hdl, LPC_BADCACHE, dgettext(TEXT_DOMAIN,
1733 		    "failed to open cache file"));
1734 		return (NULL);
1735 	}
1736 
1737 	if (fstat64(fd, &statbuf) != 0) {
1738 		zutil_error_aux(hdl, "%s", zfs_strerror(errno));
1739 		(void) close(fd);
1740 		(void) zutil_error(hdl, LPC_BADCACHE, dgettext(TEXT_DOMAIN,
1741 		    "failed to get size of cache file"));
1742 		return (NULL);
1743 	}
1744 
1745 	if ((buf = zutil_alloc(hdl, statbuf.st_size)) == NULL) {
1746 		(void) close(fd);
1747 		return (NULL);
1748 	}
1749 
1750 	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
1751 		(void) close(fd);
1752 		free(buf);
1753 		(void) zutil_error(hdl, LPC_BADCACHE, dgettext(TEXT_DOMAIN,
1754 		    "failed to read cache file contents"));
1755 		return (NULL);
1756 	}
1757 
1758 	(void) close(fd);
1759 
1760 	if (nvlist_unpack(buf, statbuf.st_size, &raw, 0) != 0) {
1761 		free(buf);
1762 		(void) zutil_error(hdl, LPC_BADCACHE, dgettext(TEXT_DOMAIN,
1763 		    "invalid or corrupt cache file contents"));
1764 		return (NULL);
1765 	}
1766 
1767 	free(buf);
1768 
1769 	/*
1770 	 * Go through and get the current state of the pools and refresh their
1771 	 * state.
1772 	 */
1773 	if (nvlist_alloc(&pools, 0, 0) != 0) {
1774 		(void) zutil_no_memory(hdl);
1775 		nvlist_free(raw);
1776 		return (NULL);
1777 	}
1778 
1779 	elem = NULL;
1780 	while ((elem = nvlist_next_nvpair(raw, elem)) != NULL) {
1781 		src = fnvpair_value_nvlist(elem);
1782 
1783 		name = fnvlist_lookup_string(src, ZPOOL_CONFIG_POOL_NAME);
1784 		if (iarg->poolname != NULL && strcmp(iarg->poolname, name) != 0)
1785 			continue;
1786 
1787 		this_guid = fnvlist_lookup_uint64(src, ZPOOL_CONFIG_POOL_GUID);
1788 		if (iarg->guid != 0 && iarg->guid != this_guid)
1789 			continue;
1790 
1791 		if (zutil_pool_active(hdl, name, this_guid, &active) != 0) {
1792 			nvlist_free(raw);
1793 			nvlist_free(pools);
1794 			return (NULL);
1795 		}
1796 
1797 		if (active)
1798 			continue;
1799 
1800 		if (iarg->scan) {
1801 			uint64_t saved_guid = iarg->guid;
1802 			const char *saved_poolname = iarg->poolname;
1803 			pthread_mutex_t lock;
1804 
1805 			/*
1806 			 * Create the device cache that will hold the
1807 			 * devices we will scan based on the cachefile.
1808 			 * This will get destroyed and freed by
1809 			 * zpool_find_import_impl.
1810 			 */
1811 			avl_tree_t *cache = zutil_alloc(hdl,
1812 			    sizeof (avl_tree_t));
1813 			avl_create(cache, slice_cache_compare,
1814 			    sizeof (rdsk_node_t),
1815 			    offsetof(rdsk_node_t, rn_node));
1816 			nvlist_t *nvroot = fnvlist_lookup_nvlist(src,
1817 			    ZPOOL_CONFIG_VDEV_TREE);
1818 
1819 			/*
1820 			 * We only want to find the pool with this_guid.
1821 			 * We will reset these values back later.
1822 			 */
1823 			iarg->guid = this_guid;
1824 			iarg->poolname = NULL;
1825 
1826 			/*
1827 			 * We need to build up a cache of devices that exists
1828 			 * in the paths pointed to by the cachefile. This allows
1829 			 * us to preserve the device namespace that was
1830 			 * originally specified by the user but also lets us
1831 			 * scan devices in those directories in case they had
1832 			 * been renamed.
1833 			 */
1834 			pthread_mutex_init(&lock, NULL);
1835 			discover_cached_paths(hdl, nvroot, cache, &lock);
1836 			nvlist_t *nv = zpool_find_import_impl(hdl, iarg,
1837 			    &lock, cache);
1838 			pthread_mutex_destroy(&lock);
1839 
1840 			/*
1841 			 * zpool_find_import_impl will return back
1842 			 * a list of pools that it found based on the
1843 			 * device cache. There should only be one pool
1844 			 * since we're looking for a specific guid.
1845 			 * We will use that pool to build up the final
1846 			 * pool nvlist which is returned back to the
1847 			 * caller.
1848 			 */
1849 			nvpair_t *pair = nvlist_next_nvpair(nv, NULL);
1850 			if (pair == NULL)
1851 				continue;
1852 			fnvlist_add_nvlist(pools, nvpair_name(pair),
1853 			    fnvpair_value_nvlist(pair));
1854 
1855 			VERIFY0P(nvlist_next_nvpair(nv, pair));
1856 
1857 			iarg->guid = saved_guid;
1858 			iarg->poolname = saved_poolname;
1859 			continue;
1860 		}
1861 
1862 		if (nvlist_add_string(src, ZPOOL_CONFIG_CACHEFILE,
1863 		    iarg->cachefile) != 0) {
1864 			(void) zutil_no_memory(hdl);
1865 			nvlist_free(raw);
1866 			nvlist_free(pools);
1867 			return (NULL);
1868 		}
1869 
1870 		update_vdevs_config_dev_sysfs_path(src);
1871 
1872 		if ((dst = zutil_refresh_config(hdl, src)) == NULL) {
1873 			nvlist_free(raw);
1874 			nvlist_free(pools);
1875 			return (NULL);
1876 		}
1877 
1878 		if (nvlist_add_nvlist(pools, nvpair_name(elem), dst) != 0) {
1879 			(void) zutil_no_memory(hdl);
1880 			nvlist_free(dst);
1881 			nvlist_free(raw);
1882 			nvlist_free(pools);
1883 			return (NULL);
1884 		}
1885 		nvlist_free(dst);
1886 	}
1887 	nvlist_free(raw);
1888 	return (pools);
1889 }
1890 
1891 static nvlist_t *
zpool_find_import(libpc_handle_t * hdl,importargs_t * iarg)1892 zpool_find_import(libpc_handle_t *hdl, importargs_t *iarg)
1893 {
1894 	pthread_mutex_t lock;
1895 	avl_tree_t *cache;
1896 	nvlist_t *pools = NULL;
1897 
1898 	verify(iarg->poolname == NULL || iarg->guid == 0);
1899 	pthread_mutex_init(&lock, NULL);
1900 
1901 	/*
1902 	 * Locate pool member vdevs by blkid or by directory scanning.
1903 	 * On success a newly allocated AVL tree which is populated with an
1904 	 * entry for each discovered vdev will be returned in the cache.
1905 	 * It's the caller's responsibility to consume and destroy this tree.
1906 	 */
1907 	if (iarg->scan || iarg->paths != 0) {
1908 		size_t dirs = iarg->paths;
1909 		const char * const *dir = (const char * const *)iarg->path;
1910 
1911 		if (dirs == 0)
1912 			dir = zpool_default_search_paths(&dirs);
1913 
1914 		if (zpool_find_import_scan(hdl, &lock, &cache,
1915 		    dir, dirs) != 0) {
1916 			pthread_mutex_destroy(&lock);
1917 			return (NULL);
1918 		}
1919 	} else {
1920 		if (zpool_find_import_blkid(hdl, &lock, &cache) != 0) {
1921 			pthread_mutex_destroy(&lock);
1922 			return (NULL);
1923 		}
1924 	}
1925 
1926 	pools = zpool_find_import_impl(hdl, iarg, &lock, cache);
1927 	pthread_mutex_destroy(&lock);
1928 	return (pools);
1929 }
1930 
1931 
1932 nvlist_t *
zpool_search_import(libpc_handle_t * hdl,importargs_t * import)1933 zpool_search_import(libpc_handle_t *hdl, importargs_t *import)
1934 {
1935 	nvlist_t *pools = NULL;
1936 
1937 	verify(import->poolname == NULL || import->guid == 0);
1938 
1939 	if (import->cachefile != NULL)
1940 		pools = zpool_find_import_cached(hdl, import);
1941 	else
1942 		pools = zpool_find_import(hdl, import);
1943 
1944 	if ((pools == NULL || nvlist_empty(pools)) &&
1945 	    hdl->lpc_open_access_error && geteuid() != 0) {
1946 		(void) zutil_error(hdl, LPC_EACCESS, dgettext(TEXT_DOMAIN,
1947 		    "no pools found"));
1948 	}
1949 
1950 	return (pools);
1951 }
1952 
1953 static boolean_t
pool_match(nvlist_t * cfg,const char * tgt)1954 pool_match(nvlist_t *cfg, const char *tgt)
1955 {
1956 	uint64_t v, guid = strtoull(tgt, NULL, 0);
1957 	const char *s;
1958 
1959 	if (guid != 0) {
1960 		if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &v) == 0)
1961 			return (v == guid);
1962 	} else {
1963 		if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &s) == 0)
1964 			return (strcmp(s, tgt) == 0);
1965 	}
1966 	return (B_FALSE);
1967 }
1968 
1969 int
zpool_find_config(libpc_handle_t * hdl,const char * target,nvlist_t ** configp,importargs_t * args)1970 zpool_find_config(libpc_handle_t *hdl, const char *target, nvlist_t **configp,
1971     importargs_t *args)
1972 {
1973 	nvlist_t *pools;
1974 	nvlist_t *match = NULL;
1975 	nvlist_t *config = NULL;
1976 	char *sepp = NULL;
1977 	int count = 0;
1978 	char *targetdup = strdup(target);
1979 
1980 	if (targetdup == NULL)
1981 		return (ENOMEM);
1982 
1983 	*configp = NULL;
1984 
1985 	if ((sepp = strpbrk(targetdup, "/@")) != NULL)
1986 		*sepp = '\0';
1987 
1988 	pools = zpool_search_import(hdl, args);
1989 	if (pools == NULL) {
1990 		zutil_error_aux(hdl, dgettext(TEXT_DOMAIN, "no pools found"));
1991 		(void) zutil_error_fmt(hdl, LPC_UNKNOWN, dgettext(TEXT_DOMAIN,
1992 		    "failed to find config for pool '%s'"), targetdup);
1993 		free(targetdup);
1994 		return (ENOENT);
1995 	}
1996 
1997 	nvpair_t *elem = NULL;
1998 	while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
1999 		VERIFY0(nvpair_value_nvlist(elem, &config));
2000 		if (pool_match(config, targetdup)) {
2001 			count++;
2002 			if (match != NULL) {
2003 				/* multiple matches found */
2004 				continue;
2005 			} else {
2006 				match = fnvlist_dup(config);
2007 			}
2008 		}
2009 	}
2010 	fnvlist_free(pools);
2011 
2012 	if (count == 0) {
2013 		zutil_error_aux(hdl, dgettext(TEXT_DOMAIN,
2014 		    "no matching pools"));
2015 		(void) zutil_error_fmt(hdl, LPC_UNKNOWN, dgettext(TEXT_DOMAIN,
2016 		    "failed to find config for pool '%s'"), targetdup);
2017 		free(targetdup);
2018 		return (ENOENT);
2019 	}
2020 
2021 	if (count > 1) {
2022 		zutil_error_aux(hdl, dgettext(TEXT_DOMAIN,
2023 		    "more than one matching pool"));
2024 		(void) zutil_error_fmt(hdl, LPC_UNKNOWN, dgettext(TEXT_DOMAIN,
2025 		    "failed to find config for pool '%s'"), targetdup);
2026 		free(targetdup);
2027 		fnvlist_free(match);
2028 		return (EINVAL);
2029 	}
2030 
2031 	*configp = match;
2032 	free(targetdup);
2033 
2034 	return (0);
2035 }
2036 
2037 /* Return if a vdev is a leaf vdev.  Note: draid spares are leaf vdevs. */
2038 static boolean_t
vdev_is_leaf(nvlist_t * nv)2039 vdev_is_leaf(nvlist_t *nv)
2040 {
2041 	uint_t children = 0;
2042 	nvlist_t **child;
2043 
2044 	(void) nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2045 	    &child, &children);
2046 
2047 	return (children == 0);
2048 }
2049 
2050 /* Return if a vdev is a leaf vdev and a real device (disk or file) */
2051 static boolean_t
vdev_is_real_leaf(nvlist_t * nv)2052 vdev_is_real_leaf(nvlist_t *nv)
2053 {
2054 	const char *type = NULL;
2055 	if (!vdev_is_leaf(nv))
2056 		return (B_FALSE);
2057 
2058 	(void) nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type);
2059 	if ((strcmp(type, VDEV_TYPE_DISK) == 0) ||
2060 	    (strcmp(type, VDEV_TYPE_FILE) == 0)) {
2061 		return (B_TRUE);
2062 	}
2063 
2064 	return (B_FALSE);
2065 }
2066 
2067 /*
2068  * This function is called by our FOR_EACH_VDEV() macros.
2069  *
2070  * state:   State machine status (stored inside of a (nvlist_t *))
2071  * nv:	     The current vdev nvlist_t we are iterating over.
2072  * last_nv: The previous vdev nvlist_t we returned to the user in
2073  *          the last iteration of FOR_EACH_VDEV().  We use it
2074  *          to find the next vdev nvlist_t we should return.
2075  * real_leaves_only: Only return leaf vdevs.
2076  *
2077  * Returns 1 if we found the next vdev nvlist_t for this iteration.  0 if
2078  * we're still searching for it.
2079  */
2080 static int
__for_each_vdev_macro_helper_func(void * state,nvlist_t * nv,void * last_nv,boolean_t real_leaves_only)2081 __for_each_vdev_macro_helper_func(void *state, nvlist_t *nv, void *last_nv,
2082     boolean_t real_leaves_only)
2083 {
2084 	enum {FIRST_NV = 0, NEXT_IS_MATCH = 1, STOP_LOOKING = 2};
2085 
2086 	/* The very first entry in the NV list is a special case */
2087 	if (*((nvlist_t **)state) == (nvlist_t *)FIRST_NV) {
2088 		if (real_leaves_only && !vdev_is_real_leaf(nv))
2089 			return (0);
2090 
2091 		*((nvlist_t **)last_nv) = nv;
2092 		*((nvlist_t **)state) = (nvlist_t *)STOP_LOOKING;
2093 		return (1);
2094 	}
2095 
2096 	/*
2097 	 * We came across our last_nv, meaning the next one is the one we
2098 	 * want
2099 	 */
2100 	if (nv == *((nvlist_t **)last_nv)) {
2101 		/* Next iteration of this function will return the nvlist_t */
2102 		*((nvlist_t **)state) = (nvlist_t *)NEXT_IS_MATCH;
2103 		return (0);
2104 	}
2105 
2106 	/*
2107 	 * We marked NEXT_IS_MATCH on the previous iteration, so this is the one
2108 	 * we want.
2109 	 */
2110 	if (*(nvlist_t **)state == (nvlist_t *)NEXT_IS_MATCH) {
2111 		if (real_leaves_only && !vdev_is_real_leaf(nv))
2112 			return (0);
2113 
2114 		*((nvlist_t **)last_nv) = nv;
2115 		*((nvlist_t **)state) = (nvlist_t *)STOP_LOOKING;
2116 		return (1);
2117 	}
2118 
2119 	return (0);
2120 }
2121 
2122 int
for_each_vdev_macro_helper_func(void * state,nvlist_t * nv,void * last_nv)2123 for_each_vdev_macro_helper_func(void *state, nvlist_t *nv, void *last_nv)
2124 {
2125 	return (__for_each_vdev_macro_helper_func(state, nv, last_nv, B_FALSE));
2126 }
2127 
2128 int
for_each_real_leaf_vdev_macro_helper_func(void * state,nvlist_t * nv,void * last_nv)2129 for_each_real_leaf_vdev_macro_helper_func(void *state, nvlist_t *nv,
2130     void *last_nv)
2131 {
2132 	return (__for_each_vdev_macro_helper_func(state, nv, last_nv, B_TRUE));
2133 }
2134 
2135 /*
2136  * Internal function for iterating over the vdevs.
2137  *
2138  * For each vdev, func() will be called and will be passed 'zhp' (which is
2139  * typically the zpool_handle_t cast as a void pointer), the vdev's nvlist, and
2140  * a user-defined data pointer).
2141  *
2142  * The return values from all the func() calls will be OR'd together and
2143  * returned.
2144  */
2145 int
for_each_vdev_cb(void * zhp,nvlist_t * nv,pool_vdev_iter_f func,void * data)2146 for_each_vdev_cb(void *zhp, nvlist_t *nv, pool_vdev_iter_f func,
2147     void *data)
2148 {
2149 	nvlist_t **child;
2150 	uint_t c, children;
2151 	int ret = 0;
2152 	int i;
2153 	const char *type;
2154 
2155 	const char *list[] = {
2156 	    ZPOOL_CONFIG_SPARES,
2157 	    ZPOOL_CONFIG_L2CACHE,
2158 	    ZPOOL_CONFIG_CHILDREN
2159 	};
2160 
2161 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
2162 		return (ret);
2163 
2164 	/* Don't run our function on indirect vdevs */
2165 	if (strcmp(type, VDEV_TYPE_INDIRECT) != 0) {
2166 		ret |= func(zhp, nv, data);
2167 	}
2168 
2169 	for (i = 0; i < ARRAY_SIZE(list); i++) {
2170 		if (nvlist_lookup_nvlist_array(nv, list[i], &child,
2171 		    &children) == 0) {
2172 			for (c = 0; c < children; c++) {
2173 				uint64_t ishole = 0;
2174 
2175 				(void) nvlist_lookup_uint64(child[c],
2176 				    ZPOOL_CONFIG_IS_HOLE, &ishole);
2177 
2178 				if (ishole)
2179 					continue;
2180 
2181 				ret |= for_each_vdev_cb(zhp, child[c],
2182 				    func, data);
2183 			}
2184 		}
2185 	}
2186 
2187 	return (ret);
2188 }
2189 
2190 /*
2191  * Given an ZPOOL_CONFIG_VDEV_TREE nvpair, iterate over all the vdevs, calling
2192  * func() for each one.  func() is passed the vdev's nvlist and an optional
2193  * user-defined 'data' pointer.
2194  */
2195 int
for_each_vdev_in_nvlist(nvlist_t * nvroot,pool_vdev_iter_f func,void * data)2196 for_each_vdev_in_nvlist(nvlist_t *nvroot, pool_vdev_iter_f func, void *data)
2197 {
2198 	return (for_each_vdev_cb(NULL, nvroot, func, data));
2199 }
2200