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