xref: /illumos-gate/usr/src/lib/libzutil/common/zutil_import.c (revision 1a2d662a91cee3bf82f41cd47c7ae6f3825d9db2)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2017 Nexenta Systems, Inc.
24  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
26  * Copyright 2015 RackTop Systems.
27  * Copyright (c) 2016, Intel Corporation.
28  * Copyright 2020 Joyent, Inc.
29  * Copyright 2023 Oxide Computer Company
30  */
31 
32 /*
33  * Pool import support functions.
34  *
35  * Used by zpool, ztest, zdb, and zhack to locate importable configs. Since
36  * these commands are expected to run in the global zone, we can assume
37  * that the devices are all readable when called.
38  *
39  * To import a pool, we rely on reading the configuration information from the
40  * ZFS label of each device.  If we successfully read the label, then we
41  * organize the configuration information in the following hierarchy:
42  *
43  *	pool guid -> toplevel vdev guid -> label txg
44  *
45  * Duplicate entries matching this same tuple will be discarded.  Once we have
46  * examined every device, we pick the best label txg config for each toplevel
47  * vdev.  We then arrange these toplevel vdevs into a complete pool config, and
48  * update any paths that have changed.  Finally, we attempt to import the pool
49  * using our derived config, and record the results.
50  */
51 
52 #include <stdio.h>
53 #include <stdarg.h>
54 #include <assert.h>
55 #include <ctype.h>
56 #include <devid.h>
57 #include <dirent.h>
58 #include <errno.h>
59 #include <libintl.h>
60 #include <stddef.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <sys/stat.h>
64 #include <unistd.h>
65 #include <fcntl.h>
66 #include <sys/vtoc.h>
67 #include <sys/dktp/fdisk.h>
68 #include <sys/efi_partition.h>
69 #include <sys/vdev_impl.h>
70 #include <sys/fs/zfs.h>
71 
72 #include <thread_pool.h>
73 #include <libzutil.h>
74 #include <libnvpair.h>
75 
76 #include "zutil_import.h"
77 
78 #ifdef NDEBUG
79 #define	verify(EX)	((void)(EX))
80 #else
81 #define	verify(EX)	assert(EX)
82 #endif
83 
84 /*PRINTFLIKE2*/
85 static void
86 zutil_error_aux(libpc_handle_t *hdl, const char *fmt, ...)
87 {
88 	va_list ap;
89 
90 	va_start(ap, fmt);
91 
92 	(void) vsnprintf(hdl->lpc_desc, sizeof (hdl->lpc_desc), fmt, ap);
93 	hdl->lpc_desc_active = B_TRUE;
94 
95 	va_end(ap);
96 }
97 
98 static void
99 zutil_verror(libpc_handle_t *hdl, const char *error, const char *fmt,
100     va_list ap)
101 {
102 	char action[1024];
103 
104 	(void) vsnprintf(action, sizeof (action), fmt, ap);
105 
106 	if (hdl->lpc_desc_active)
107 		hdl->lpc_desc_active = B_FALSE;
108 	else
109 		hdl->lpc_desc[0] = '\0';
110 
111 	if (hdl->lpc_printerr) {
112 		if (hdl->lpc_desc[0] != '\0')
113 			error = hdl->lpc_desc;
114 
115 		(void) fprintf(stderr, "%s: %s\n", action, error);
116 	}
117 }
118 
119 /*PRINTFLIKE3*/
120 static int
121 zutil_error_fmt(libpc_handle_t *hdl, const char *error, const char *fmt, ...)
122 {
123 	va_list ap;
124 
125 	va_start(ap, fmt);
126 
127 	zutil_verror(hdl, error, fmt, ap);
128 
129 	va_end(ap);
130 
131 	return (-1);
132 }
133 
134 static int
135 zutil_error(libpc_handle_t *hdl, const char *error, const char *msg)
136 {
137 	return (zutil_error_fmt(hdl, error, "%s", msg));
138 }
139 
140 static int
141 zutil_no_memory(libpc_handle_t *hdl)
142 {
143 	(void) zutil_error(hdl, EZFS_NOMEM, "internal error");
144 	exit(1);
145 }
146 
147 void *
148 zutil_alloc(libpc_handle_t *hdl, size_t size)
149 {
150 	void *data;
151 
152 	if ((data = calloc(1, size)) == NULL)
153 		(void) zutil_no_memory(hdl);
154 
155 	return (data);
156 }
157 
158 char *
159 zutil_strdup(libpc_handle_t *hdl, const char *str)
160 {
161 	char *ret;
162 
163 	if ((ret = strdup(str)) == NULL)
164 		(void) zutil_no_memory(hdl);
165 
166 	return (ret);
167 }
168 
169 /*
170  * Intermediate structures used to gather configuration information.
171  */
172 typedef struct config_entry {
173 	uint64_t		ce_txg;
174 	nvlist_t		*ce_config;
175 	struct config_entry	*ce_next;
176 } config_entry_t;
177 
178 typedef struct vdev_entry {
179 	uint64_t		ve_guid;
180 	config_entry_t		*ve_configs;
181 	struct vdev_entry	*ve_next;
182 } vdev_entry_t;
183 
184 typedef struct pool_entry {
185 	uint64_t		pe_guid;
186 	vdev_entry_t		*pe_vdevs;
187 	struct pool_entry	*pe_next;
188 } pool_entry_t;
189 
190 typedef struct name_entry {
191 	char			*ne_name;
192 	uint64_t		ne_guid;
193 	struct name_entry	*ne_next;
194 } name_entry_t;
195 
196 typedef struct pool_list {
197 	pool_entry_t		*pools;
198 	name_entry_t		*names;
199 } pool_list_t;
200 
201 /*
202  * Go through and fix up any path and/or devid information for the given vdev
203  * configuration.
204  */
205 static int
206 fix_paths(nvlist_t *nv, name_entry_t *names)
207 {
208 	nvlist_t **child;
209 	uint_t c, children;
210 	uint64_t guid;
211 	name_entry_t *ne, *best;
212 	char *path, *devid;
213 	int matched;
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(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 slices or multiple paths to the same
230 	 * disk.  If this is the case, then we want to pick the path that is
231 	 * the most similar to the original, where "most similar" is the number
232 	 * of matching characters starting from the end of the path.  This will
233 	 * preserve slice numbers even if the disks have been reorganized, and
234 	 * will also catch preferred disk names if multiple paths exist.
235 	 */
236 	verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0);
237 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) != 0)
238 		path = NULL;
239 
240 	matched = 0;
241 	best = NULL;
242 	for (ne = names; ne != NULL; ne = ne->ne_next) {
243 		if (ne->ne_guid == guid) {
244 			const char *src, *dst;
245 			int count;
246 
247 			if (path == NULL) {
248 				best = ne;
249 				break;
250 			}
251 
252 			src = ne->ne_name + strlen(ne->ne_name) - 1;
253 			dst = path + strlen(path) - 1;
254 			for (count = 0; src >= ne->ne_name && dst >= path;
255 			    src--, dst--, count++)
256 				if (*src != *dst)
257 					break;
258 
259 			/*
260 			 * At this point, 'count' is the number of characters
261 			 * matched from the end.
262 			 */
263 			if (count > matched || best == NULL) {
264 				best = ne;
265 				matched = count;
266 			}
267 		}
268 	}
269 
270 	if (best == NULL)
271 		return (0);
272 
273 	if (nvlist_add_string(nv, ZPOOL_CONFIG_PATH, best->ne_name) != 0)
274 		return (-1);
275 
276 	if ((devid = devid_str_from_path(best->ne_name)) == NULL) {
277 		(void) nvlist_remove_all(nv, ZPOOL_CONFIG_DEVID);
278 	} else {
279 		if (nvlist_add_string(nv, ZPOOL_CONFIG_DEVID, devid) != 0) {
280 			devid_str_free(devid);
281 			return (-1);
282 		}
283 		devid_str_free(devid);
284 	}
285 
286 	return (0);
287 }
288 
289 /*
290  * Add the given configuration to the list of known devices.
291  */
292 static int
293 add_config(libpc_handle_t *hdl, pool_list_t *pl, const char *path,
294     int order, int num_labels, nvlist_t *config)
295 {
296 	uint64_t pool_guid, vdev_guid, top_guid, txg, state;
297 	pool_entry_t *pe;
298 	vdev_entry_t *ve;
299 	config_entry_t *ce;
300 	name_entry_t *ne;
301 
302 	/*
303 	 * If this is a hot spare not currently in use or level 2 cache
304 	 * device, add it to the list of names to translate, but don't do
305 	 * anything else.
306 	 */
307 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
308 	    &state) == 0 &&
309 	    (state == POOL_STATE_SPARE || state == POOL_STATE_L2CACHE) &&
310 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, &vdev_guid) == 0) {
311 		if ((ne = zutil_alloc(hdl, sizeof (name_entry_t))) == NULL)
312 			return (-1);
313 
314 		if ((ne->ne_name = zutil_strdup(hdl, path)) == NULL) {
315 			free(ne);
316 			return (-1);
317 		}
318 
319 		ne->ne_guid = vdev_guid;
320 		ne->ne_next = pl->names;
321 		pl->names = ne;
322 
323 		return (0);
324 	}
325 
326 	/*
327 	 * If we have a valid config but cannot read any of these fields, then
328 	 * it means we have a half-initialized label.  In vdev_label_init()
329 	 * we write a label with txg == 0 so that we can identify the device
330 	 * in case the user refers to the same disk later on.  If we fail to
331 	 * create the pool, we'll be left with a label in this state
332 	 * which should not be considered part of a valid pool.
333 	 */
334 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
335 	    &pool_guid) != 0 ||
336 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID,
337 	    &vdev_guid) != 0 ||
338 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_TOP_GUID,
339 	    &top_guid) != 0 ||
340 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
341 	    &txg) != 0 || txg == 0) {
342 		return (0);
343 	}
344 
345 	/*
346 	 * First, see if we know about this pool.  If not, then add it to the
347 	 * list of known pools.
348 	 */
349 	for (pe = pl->pools; pe != NULL; pe = pe->pe_next) {
350 		if (pe->pe_guid == pool_guid)
351 			break;
352 	}
353 
354 	if (pe == NULL) {
355 		if ((pe = zutil_alloc(hdl, sizeof (pool_entry_t))) == NULL) {
356 			return (-1);
357 		}
358 		pe->pe_guid = pool_guid;
359 		pe->pe_next = pl->pools;
360 		pl->pools = pe;
361 	}
362 
363 	/*
364 	 * Second, see if we know about this toplevel vdev.  Add it if its
365 	 * missing.
366 	 */
367 	for (ve = pe->pe_vdevs; ve != NULL; ve = ve->ve_next) {
368 		if (ve->ve_guid == top_guid)
369 			break;
370 	}
371 
372 	if (ve == NULL) {
373 		if ((ve = zutil_alloc(hdl, sizeof (vdev_entry_t))) == NULL) {
374 			return (-1);
375 		}
376 		ve->ve_guid = top_guid;
377 		ve->ve_next = pe->pe_vdevs;
378 		pe->pe_vdevs = ve;
379 	}
380 
381 	/*
382 	 * Third, see if we have a config with a matching transaction group.  If
383 	 * so, then we do nothing.  Otherwise, add it to the list of known
384 	 * configs.
385 	 */
386 	for (ce = ve->ve_configs; ce != NULL; ce = ce->ce_next) {
387 		if (ce->ce_txg == txg)
388 			break;
389 	}
390 
391 	if (ce == NULL) {
392 		if ((ce = zutil_alloc(hdl, sizeof (config_entry_t))) == NULL) {
393 			return (-1);
394 		}
395 		ce->ce_txg = txg;
396 		ce->ce_config = fnvlist_dup(config);
397 		ce->ce_next = ve->ve_configs;
398 		ve->ve_configs = ce;
399 	}
400 
401 	/*
402 	 * At this point we've successfully added our config to the list of
403 	 * known configs.  The last thing to do is add the vdev guid -> path
404 	 * mappings so that we can fix up the configuration as necessary before
405 	 * doing the import.
406 	 */
407 	if ((ne = zutil_alloc(hdl, sizeof (name_entry_t))) == NULL)
408 		return (-1);
409 
410 	if ((ne->ne_name = zutil_strdup(hdl, path)) == NULL) {
411 		free(ne);
412 		return (-1);
413 	}
414 
415 	ne->ne_guid = vdev_guid;
416 	ne->ne_next = pl->names;
417 	pl->names = ne;
418 
419 	return (0);
420 }
421 
422 /*
423  * Returns true if the named pool matches the given GUID.
424  */
425 static int
426 zutil_pool_active(libpc_handle_t *hdl, const char *name, uint64_t guid,
427     boolean_t *isactive)
428 {
429 	ASSERT(hdl->lpc_ops->pco_pool_active != NULL);
430 
431 	int error = hdl->lpc_ops->pco_pool_active(hdl->lpc_lib_handle, name,
432 	    guid, isactive);
433 
434 	return (error);
435 }
436 
437 static nvlist_t *
438 zutil_refresh_config(libpc_handle_t *hdl, nvlist_t *tryconfig)
439 {
440 	ASSERT(hdl->lpc_ops->pco_refresh_config != NULL);
441 
442 	return (hdl->lpc_ops->pco_refresh_config(hdl->lpc_lib_handle,
443 	    tryconfig));
444 }
445 
446 /*
447  * Determine if the vdev id is a hole in the namespace.
448  */
449 static boolean_t
450 vdev_is_hole(uint64_t *hole_array, uint_t holes, uint_t id)
451 {
452 	for (int c = 0; c < holes; c++) {
453 
454 		/* Top-level is a hole */
455 		if (hole_array[c] == id)
456 			return (B_TRUE);
457 	}
458 	return (B_FALSE);
459 }
460 
461 /*
462  * Convert our list of pools into the definitive set of configurations.  We
463  * start by picking the best config for each toplevel vdev.  Once that's done,
464  * we assemble the toplevel vdevs into a full config for the pool.  We make a
465  * pass to fix up any incorrect paths, and then add it to the main list to
466  * return to the user.
467  */
468 static nvlist_t *
469 get_configs(libpc_handle_t *hdl, pool_list_t *pl, boolean_t active_ok,
470     nvlist_t *policy)
471 {
472 	pool_entry_t *pe;
473 	vdev_entry_t *ve;
474 	config_entry_t *ce;
475 	nvlist_t *ret = NULL, *config = NULL, *tmp = NULL, *nvtop, *nvroot;
476 	nvlist_t **spares, **l2cache;
477 	uint_t i, nspares, nl2cache;
478 	boolean_t config_seen;
479 	uint64_t best_txg;
480 	char *name, *hostname = NULL;
481 	uint64_t guid;
482 	uint_t children = 0;
483 	nvlist_t **child = NULL;
484 	uint_t holes;
485 	uint64_t *hole_array, max_id;
486 	uint_t c;
487 	boolean_t isactive;
488 	uint64_t hostid;
489 	nvlist_t *nvl;
490 	boolean_t found_one = B_FALSE;
491 	boolean_t valid_top_config = B_FALSE;
492 
493 	if (nvlist_alloc(&ret, 0, 0) != 0)
494 		goto nomem;
495 
496 	for (pe = pl->pools; pe != NULL; pe = pe->pe_next) {
497 		uint64_t id, max_txg = 0;
498 
499 		if (nvlist_alloc(&config, NV_UNIQUE_NAME, 0) != 0)
500 			goto nomem;
501 		config_seen = B_FALSE;
502 
503 		/*
504 		 * Iterate over all toplevel vdevs.  Grab the pool configuration
505 		 * from the first one we find, and then go through the rest and
506 		 * add them as necessary to the 'vdevs' member of the config.
507 		 */
508 		for (ve = pe->pe_vdevs; ve != NULL; ve = ve->ve_next) {
509 
510 			/*
511 			 * Determine the best configuration for this vdev by
512 			 * selecting the config with the latest transaction
513 			 * group.
514 			 */
515 			best_txg = 0;
516 			for (ce = ve->ve_configs; ce != NULL;
517 			    ce = ce->ce_next) {
518 
519 				if (ce->ce_txg > best_txg) {
520 					tmp = ce->ce_config;
521 					best_txg = ce->ce_txg;
522 				}
523 			}
524 
525 			/*
526 			 * We rely on the fact that the max txg for the
527 			 * pool will contain the most up-to-date information
528 			 * about the valid top-levels in the vdev namespace.
529 			 */
530 			if (best_txg > max_txg) {
531 				(void) nvlist_remove(config,
532 				    ZPOOL_CONFIG_VDEV_CHILDREN,
533 				    DATA_TYPE_UINT64);
534 				(void) nvlist_remove(config,
535 				    ZPOOL_CONFIG_HOLE_ARRAY,
536 				    DATA_TYPE_UINT64_ARRAY);
537 
538 				max_txg = best_txg;
539 				hole_array = NULL;
540 				holes = 0;
541 				max_id = 0;
542 				valid_top_config = B_FALSE;
543 
544 				if (nvlist_lookup_uint64(tmp,
545 				    ZPOOL_CONFIG_VDEV_CHILDREN, &max_id) == 0) {
546 					verify(nvlist_add_uint64(config,
547 					    ZPOOL_CONFIG_VDEV_CHILDREN,
548 					    max_id) == 0);
549 					valid_top_config = B_TRUE;
550 				}
551 
552 				if (nvlist_lookup_uint64_array(tmp,
553 				    ZPOOL_CONFIG_HOLE_ARRAY, &hole_array,
554 				    &holes) == 0) {
555 					verify(nvlist_add_uint64_array(config,
556 					    ZPOOL_CONFIG_HOLE_ARRAY,
557 					    hole_array, holes) == 0);
558 				}
559 			}
560 
561 			if (!config_seen) {
562 				/*
563 				 * Copy the relevant pieces of data to the pool
564 				 * configuration:
565 				 *
566 				 *	version
567 				 *	pool guid
568 				 *	name
569 				 *	comment (if available)
570 				 *	pool state
571 				 *	hostid (if available)
572 				 *	hostname (if available)
573 				 */
574 				uint64_t state, version;
575 				char *comment = NULL;
576 
577 				version = fnvlist_lookup_uint64(tmp,
578 				    ZPOOL_CONFIG_VERSION);
579 				fnvlist_add_uint64(config,
580 				    ZPOOL_CONFIG_VERSION, version);
581 				guid = fnvlist_lookup_uint64(tmp,
582 				    ZPOOL_CONFIG_POOL_GUID);
583 				fnvlist_add_uint64(config,
584 				    ZPOOL_CONFIG_POOL_GUID, guid);
585 				name = fnvlist_lookup_string(tmp,
586 				    ZPOOL_CONFIG_POOL_NAME);
587 				fnvlist_add_string(config,
588 				    ZPOOL_CONFIG_POOL_NAME, name);
589 
590 				if (nvlist_lookup_string(tmp,
591 				    ZPOOL_CONFIG_COMMENT, &comment) == 0)
592 					fnvlist_add_string(config,
593 					    ZPOOL_CONFIG_COMMENT, comment);
594 
595 				state = fnvlist_lookup_uint64(tmp,
596 				    ZPOOL_CONFIG_POOL_STATE);
597 				fnvlist_add_uint64(config,
598 				    ZPOOL_CONFIG_POOL_STATE, state);
599 
600 				hostid = 0;
601 				if (nvlist_lookup_uint64(tmp,
602 				    ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
603 					fnvlist_add_uint64(config,
604 					    ZPOOL_CONFIG_HOSTID, hostid);
605 					hostname = fnvlist_lookup_string(tmp,
606 					    ZPOOL_CONFIG_HOSTNAME);
607 					fnvlist_add_string(config,
608 					    ZPOOL_CONFIG_HOSTNAME, hostname);
609 				}
610 
611 				config_seen = B_TRUE;
612 			}
613 
614 			/*
615 			 * Add this top-level vdev to the child array.
616 			 */
617 			verify(nvlist_lookup_nvlist(tmp,
618 			    ZPOOL_CONFIG_VDEV_TREE, &nvtop) == 0);
619 			verify(nvlist_lookup_uint64(nvtop, ZPOOL_CONFIG_ID,
620 			    &id) == 0);
621 
622 			if (id >= children) {
623 				nvlist_t **newchild;
624 
625 				newchild = zutil_alloc(hdl, (id + 1) *
626 				    sizeof (nvlist_t *));
627 				if (newchild == NULL)
628 					goto nomem;
629 
630 				for (c = 0; c < children; c++)
631 					newchild[c] = child[c];
632 
633 				free(child);
634 				child = newchild;
635 				children = id + 1;
636 			}
637 			if (nvlist_dup(nvtop, &child[id], 0) != 0)
638 				goto nomem;
639 
640 		}
641 
642 		/*
643 		 * If we have information about all the top-levels then
644 		 * clean up the nvlist which we've constructed. This
645 		 * means removing any extraneous devices that are
646 		 * beyond the valid range or adding devices to the end
647 		 * of our array which appear to be missing.
648 		 */
649 		if (valid_top_config) {
650 			if (max_id < children) {
651 				for (c = max_id; c < children; c++)
652 					nvlist_free(child[c]);
653 				children = max_id;
654 			} else if (max_id > children) {
655 				nvlist_t **newchild;
656 
657 				newchild = zutil_alloc(hdl, (max_id) *
658 				    sizeof (nvlist_t *));
659 				if (newchild == NULL)
660 					goto nomem;
661 
662 				for (c = 0; c < children; c++)
663 					newchild[c] = child[c];
664 
665 				free(child);
666 				child = newchild;
667 				children = max_id;
668 			}
669 		}
670 
671 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
672 		    &guid) == 0);
673 
674 		/*
675 		 * The vdev namespace may contain holes as a result of
676 		 * device removal. We must add them back into the vdev
677 		 * tree before we process any missing devices.
678 		 */
679 		if (holes > 0) {
680 			ASSERT(valid_top_config);
681 
682 			for (c = 0; c < children; c++) {
683 				nvlist_t *holey;
684 
685 				if (child[c] != NULL ||
686 				    !vdev_is_hole(hole_array, holes, c))
687 					continue;
688 
689 				if (nvlist_alloc(&holey, NV_UNIQUE_NAME,
690 				    0) != 0)
691 					goto nomem;
692 
693 				/*
694 				 * Holes in the namespace are treated as
695 				 * "hole" top-level vdevs and have a
696 				 * special flag set on them.
697 				 */
698 				if (nvlist_add_string(holey,
699 				    ZPOOL_CONFIG_TYPE,
700 				    VDEV_TYPE_HOLE) != 0 ||
701 				    nvlist_add_uint64(holey,
702 				    ZPOOL_CONFIG_ID, c) != 0 ||
703 				    nvlist_add_uint64(holey,
704 				    ZPOOL_CONFIG_GUID, 0ULL) != 0) {
705 					nvlist_free(holey);
706 					goto nomem;
707 				}
708 				child[c] = holey;
709 			}
710 		}
711 
712 		/*
713 		 * Look for any missing top-level vdevs.  If this is the case,
714 		 * create a faked up 'missing' vdev as a placeholder.  We cannot
715 		 * simply compress the child array, because the kernel performs
716 		 * certain checks to make sure the vdev IDs match their location
717 		 * in the configuration.
718 		 */
719 		for (c = 0; c < children; c++) {
720 			if (child[c] == NULL) {
721 				nvlist_t *missing;
722 				if (nvlist_alloc(&missing, NV_UNIQUE_NAME,
723 				    0) != 0)
724 					goto nomem;
725 				if (nvlist_add_string(missing,
726 				    ZPOOL_CONFIG_TYPE,
727 				    VDEV_TYPE_MISSING) != 0 ||
728 				    nvlist_add_uint64(missing,
729 				    ZPOOL_CONFIG_ID, c) != 0 ||
730 				    nvlist_add_uint64(missing,
731 				    ZPOOL_CONFIG_GUID, 0ULL) != 0) {
732 					nvlist_free(missing);
733 					goto nomem;
734 				}
735 				child[c] = missing;
736 			}
737 		}
738 
739 		/*
740 		 * Put all of this pool's top-level vdevs into a root vdev.
741 		 */
742 		if (nvlist_alloc(&nvroot, NV_UNIQUE_NAME, 0) != 0)
743 			goto nomem;
744 		if (nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
745 		    VDEV_TYPE_ROOT) != 0 ||
746 		    nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) != 0 ||
747 		    nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, guid) != 0 ||
748 		    nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
749 		    child, children) != 0) {
750 			nvlist_free(nvroot);
751 			goto nomem;
752 		}
753 
754 		for (c = 0; c < children; c++)
755 			nvlist_free(child[c]);
756 		free(child);
757 		children = 0;
758 		child = NULL;
759 
760 		/*
761 		 * Go through and fix up any paths and/or devids based on our
762 		 * known list of vdev GUID -> path mappings.
763 		 */
764 		if (fix_paths(nvroot, pl->names) != 0) {
765 			nvlist_free(nvroot);
766 			goto nomem;
767 		}
768 
769 		/*
770 		 * Add the root vdev to this pool's configuration.
771 		 */
772 		if (nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
773 		    nvroot) != 0) {
774 			nvlist_free(nvroot);
775 			goto nomem;
776 		}
777 		nvlist_free(nvroot);
778 
779 		/*
780 		 * zdb uses this path to report on active pools that were
781 		 * imported or created using -R.
782 		 */
783 		if (active_ok)
784 			goto add_pool;
785 
786 		/*
787 		 * Determine if this pool is currently active, in which case we
788 		 * can't actually import it.
789 		 */
790 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
791 		    &name) == 0);
792 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
793 		    &guid) == 0);
794 
795 		if (zutil_pool_active(hdl, name, guid, &isactive) != 0)
796 			goto error;
797 
798 		if (isactive) {
799 			nvlist_free(config);
800 			config = NULL;
801 			continue;
802 		}
803 
804 		if (policy != NULL) {
805 			if (nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
806 			    policy) != 0)
807 				goto nomem;
808 		}
809 
810 		if ((nvl = zutil_refresh_config(hdl, config)) == NULL) {
811 			nvlist_free(config);
812 			config = NULL;
813 			continue;
814 		}
815 
816 		nvlist_free(config);
817 		config = nvl;
818 
819 		/*
820 		 * Go through and update the paths for spares, now that we have
821 		 * them.
822 		 */
823 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
824 		    &nvroot) == 0);
825 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
826 		    &spares, &nspares) == 0) {
827 			for (i = 0; i < nspares; i++) {
828 				if (fix_paths(spares[i], pl->names) != 0)
829 					goto nomem;
830 			}
831 		}
832 
833 		/*
834 		 * Update the paths for l2cache devices.
835 		 */
836 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
837 		    &l2cache, &nl2cache) == 0) {
838 			for (i = 0; i < nl2cache; i++) {
839 				if (fix_paths(l2cache[i], pl->names) != 0)
840 					goto nomem;
841 			}
842 		}
843 
844 		/*
845 		 * Restore the original information read from the actual label.
846 		 */
847 		(void) nvlist_remove(config, ZPOOL_CONFIG_HOSTID,
848 		    DATA_TYPE_UINT64);
849 		(void) nvlist_remove(config, ZPOOL_CONFIG_HOSTNAME,
850 		    DATA_TYPE_STRING);
851 		if (hostid != 0) {
852 			verify(nvlist_add_uint64(config, ZPOOL_CONFIG_HOSTID,
853 			    hostid) == 0);
854 			verify(nvlist_add_string(config, ZPOOL_CONFIG_HOSTNAME,
855 			    hostname) == 0);
856 		}
857 
858 add_pool:
859 		/*
860 		 * Add this pool to the list of configs.
861 		 */
862 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
863 		    &name) == 0);
864 		if (nvlist_add_nvlist(ret, name, config) != 0)
865 			goto nomem;
866 
867 		found_one = B_TRUE;
868 		nvlist_free(config);
869 		config = NULL;
870 	}
871 
872 	if (!found_one) {
873 		nvlist_free(ret);
874 		ret = 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  * Given a file descriptor, read the label information and return an nvlist
904  * describing the configuration, if there is one. The number of valid
905  * labels found will be returned in num_labels when non-NULL.
906  */
907 int
908 zpool_read_label(int fd, nvlist_t **config, int *num_labels)
909 {
910 	struct stat64 statbuf;
911 	int l, count = 0;
912 	vdev_label_t *label;
913 	nvlist_t *expected_config = NULL;
914 	uint64_t expected_guid = 0, size;
915 
916 	*config = NULL;
917 
918 	if (num_labels != NULL)
919 		*num_labels = 0;
920 
921 	if (fstat64(fd, &statbuf) == -1)
922 		return (0);
923 	size = P2ALIGN_TYPED(statbuf.st_size, sizeof (vdev_label_t), uint64_t);
924 
925 	if ((label = malloc(sizeof (vdev_label_t))) == NULL)
926 		return (-1);
927 
928 	for (l = 0; l < VDEV_LABELS; l++) {
929 		uint64_t state, guid, txg;
930 
931 		if (pread64(fd, label, sizeof (vdev_label_t),
932 		    label_offset(size, l)) != sizeof (vdev_label_t))
933 			continue;
934 
935 		if (nvlist_unpack(label->vl_vdev_phys.vp_nvlist,
936 		    sizeof (label->vl_vdev_phys.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 static int
980 slice_cache_compare(const void *arg1, const void *arg2)
981 {
982 	const char  *nm1 = ((rdsk_node_t *)arg1)->rn_name;
983 	const char  *nm2 = ((rdsk_node_t *)arg2)->rn_name;
984 	char *nm1slice, *nm2slice;
985 	int rv;
986 
987 	/*
988 	 * slices zero and two are the most likely to provide results,
989 	 * so put those first
990 	 */
991 	nm1slice = strstr(nm1, "s0");
992 	nm2slice = strstr(nm2, "s0");
993 	if (nm1slice && !nm2slice) {
994 		return (-1);
995 	}
996 	if (!nm1slice && nm2slice) {
997 		return (1);
998 	}
999 	nm1slice = strstr(nm1, "s2");
1000 	nm2slice = strstr(nm2, "s2");
1001 	if (nm1slice && !nm2slice) {
1002 		return (-1);
1003 	}
1004 	if (!nm1slice && nm2slice) {
1005 		return (1);
1006 	}
1007 
1008 	rv = strcmp(nm1, nm2);
1009 	if (rv == 0)
1010 		return (0);
1011 	return (rv > 0 ? 1 : -1);
1012 }
1013 
1014 static void
1015 check_one_slice(avl_tree_t *r, char *diskname, uint_t partno,
1016     diskaddr_t size, uint_t blksz)
1017 {
1018 	rdsk_node_t tmpnode;
1019 	rdsk_node_t *node;
1020 	char sname[MAXNAMELEN];
1021 
1022 	tmpnode.rn_name = &sname[0];
1023 	(void) snprintf(tmpnode.rn_name, MAXNAMELEN, "%s%u",
1024 	    diskname, partno);
1025 	/*
1026 	 * protect against division by zero for disk labels that
1027 	 * contain a bogus sector size
1028 	 */
1029 	if (blksz == 0)
1030 		blksz = DEV_BSIZE;
1031 	/* too small to contain a zpool? */
1032 	if ((size < (SPA_MINDEVSIZE / blksz)) &&
1033 	    (node = avl_find(r, &tmpnode, NULL)))
1034 		node->rn_nozpool = B_TRUE;
1035 }
1036 
1037 static void
1038 nozpool_all_slices(avl_tree_t *r, const char *sname)
1039 {
1040 	char diskname[MAXNAMELEN];
1041 	char *ptr;
1042 	int i;
1043 
1044 	(void) strncpy(diskname, sname, MAXNAMELEN);
1045 	if (((ptr = strrchr(diskname, 's')) == NULL) &&
1046 	    ((ptr = strrchr(diskname, 'p')) == NULL))
1047 		return;
1048 	ptr[0] = 's';
1049 	ptr[1] = '\0';
1050 	for (i = 0; i < NDKMAP; i++)
1051 		check_one_slice(r, diskname, i, 0, 1);
1052 	ptr[0] = 'p';
1053 	for (i = 0; i <= FD_NUMPART; i++)
1054 		check_one_slice(r, diskname, i, 0, 1);
1055 }
1056 
1057 static void
1058 check_slices(avl_tree_t *r, int fd, const char *sname)
1059 {
1060 	struct extvtoc vtoc;
1061 	struct dk_gpt *gpt;
1062 	char diskname[MAXNAMELEN];
1063 	char *ptr;
1064 	int i;
1065 
1066 	(void) strncpy(diskname, sname, MAXNAMELEN);
1067 	if ((ptr = strrchr(diskname, 's')) == NULL || !isdigit(ptr[1]))
1068 		return;
1069 	ptr[1] = '\0';
1070 
1071 	if (read_extvtoc(fd, &vtoc) >= 0) {
1072 		for (i = 0; i < NDKMAP; i++)
1073 			check_one_slice(r, diskname, i,
1074 			    vtoc.v_part[i].p_size, vtoc.v_sectorsz);
1075 	} else if (efi_alloc_and_read(fd, &gpt) >= 0) {
1076 		/*
1077 		 * on x86 we'll still have leftover links that point
1078 		 * to slices s[9-15], so use NDKMAP instead
1079 		 */
1080 		for (i = 0; i < NDKMAP; i++)
1081 			check_one_slice(r, diskname, i,
1082 			    gpt->efi_parts[i].p_size, gpt->efi_lbasize);
1083 		/* nodes p[1-4] are never used with EFI labels */
1084 		ptr[0] = 'p';
1085 		for (i = 1; i <= FD_NUMPART; i++)
1086 			check_one_slice(r, diskname, i, 0, 1);
1087 		efi_free(gpt);
1088 	}
1089 }
1090 
1091 void
1092 zpool_open_func(void *arg)
1093 {
1094 	rdsk_node_t *rn = arg;
1095 	struct stat64 statbuf;
1096 	nvlist_t *config;
1097 	int error;
1098 	int num_labels = 0;
1099 	int fd;
1100 
1101 	if (rn->rn_nozpool)
1102 		return;
1103 	if ((fd = openat64(rn->rn_dfd, rn->rn_name, O_RDONLY)) < 0) {
1104 		/* symlink to a device that's no longer there */
1105 		if (errno == ENOENT)
1106 			nozpool_all_slices(rn->rn_avl, rn->rn_name);
1107 		return;
1108 	}
1109 	/*
1110 	 * Ignore failed stats.  We only want regular
1111 	 * files, character devs and block devs.
1112 	 */
1113 	if (fstat64(fd, &statbuf) != 0 ||
1114 	    (!S_ISREG(statbuf.st_mode) &&
1115 	    !S_ISCHR(statbuf.st_mode) &&
1116 	    !S_ISBLK(statbuf.st_mode))) {
1117 		(void) close(fd);
1118 		return;
1119 	}
1120 	/* this file is too small to hold a zpool */
1121 	if (S_ISREG(statbuf.st_mode) &&
1122 	    statbuf.st_size < SPA_MINDEVSIZE) {
1123 		(void) close(fd);
1124 		return;
1125 	} else if (!S_ISREG(statbuf.st_mode)) {
1126 		/*
1127 		 * Try to read the disk label first so we don't have to
1128 		 * open a bunch of minor nodes that can't have a zpool.
1129 		 */
1130 		check_slices(rn->rn_avl, fd, rn->rn_name);
1131 	}
1132 
1133 	error = zpool_read_label(fd, &config, &num_labels);
1134 	if (error != 0) {
1135 		(void) close(fd);
1136 		return;
1137 	}
1138 
1139 	if (num_labels == 0) {
1140 		(void) close(fd);
1141 		nvlist_free(config);
1142 		return;
1143 	}
1144 
1145 	(void) close(fd);
1146 
1147 	rn->rn_config = config;
1148 	rn->rn_num_labels = num_labels;
1149 }
1150 
1151 /*
1152  * Given a list of directories to search, find all pools stored on disk.  This
1153  * includes partial pools which are not available to import.  If no args are
1154  * given (argc is 0), then the default directory (/dev/dsk) is searched.
1155  * poolname or guid (but not both) are provided by the caller when trying
1156  * to import a specific pool.
1157  */
1158 static nvlist_t *
1159 zpool_find_import_impl(libpc_handle_t *hdl, importargs_t *iarg)
1160 {
1161 	int i, dirs = iarg->paths;
1162 	struct dirent64 *dp;
1163 	char path[MAXPATHLEN];
1164 	char *end, **dir = iarg->path;
1165 	size_t pathleft;
1166 	nvlist_t *ret = NULL;
1167 	static char *default_dir = ZFS_DISK_ROOT;
1168 	pool_list_t pools = { 0 };
1169 	pool_entry_t *pe, *penext;
1170 	vdev_entry_t *ve, *venext;
1171 	config_entry_t *ce, *cenext;
1172 	name_entry_t *ne, *nenext;
1173 	avl_tree_t slice_cache;
1174 	rdsk_node_t *slice;
1175 	void *cookie;
1176 
1177 	if (dirs == 0) {
1178 		dirs = 1;
1179 		dir = &default_dir;
1180 	}
1181 
1182 	/*
1183 	 * Go through and read the label configuration information from every
1184 	 * possible device, organizing the information according to pool GUID
1185 	 * and toplevel GUID.
1186 	 */
1187 	for (i = 0; i < dirs; i++) {
1188 		tpool_t *t;
1189 		char rdsk[MAXPATHLEN];
1190 		int dfd;
1191 		boolean_t config_failed = B_FALSE;
1192 		DIR *dirp;
1193 
1194 		/* use realpath to normalize the path */
1195 		if (realpath(dir[i], path) == 0) {
1196 			(void) zutil_error_fmt(hdl, EZFS_BADPATH,
1197 			    dgettext(TEXT_DOMAIN, "cannot open '%s'"), dir[i]);
1198 			goto error;
1199 		}
1200 		end = &path[strlen(path)];
1201 		*end++ = '/';
1202 		*end = 0;
1203 		pathleft = &path[sizeof (path)] - end;
1204 
1205 		/*
1206 		 * Using raw devices instead of block devices when we're
1207 		 * reading the labels skips a bunch of slow operations during
1208 		 * close(2) processing, so we replace /dev/dsk with /dev/rdsk.
1209 		 */
1210 		if (strcmp(path, ZFS_DISK_ROOTD) == 0)
1211 			(void) strlcpy(rdsk, ZFS_RDISK_ROOTD, sizeof (rdsk));
1212 		else
1213 			(void) strlcpy(rdsk, path, sizeof (rdsk));
1214 
1215 		if ((dfd = open64(rdsk, O_RDONLY)) < 0 ||
1216 		    (dirp = fdopendir(dfd)) == NULL) {
1217 			if (dfd >= 0)
1218 				(void) close(dfd);
1219 			zutil_error_aux(hdl, strerror(errno));
1220 			(void) zutil_error_fmt(hdl, EZFS_BADPATH,
1221 			    dgettext(TEXT_DOMAIN, "cannot open '%s'"),
1222 			    rdsk);
1223 			goto error;
1224 		}
1225 
1226 		avl_create(&slice_cache, slice_cache_compare,
1227 		    sizeof (rdsk_node_t), offsetof(rdsk_node_t, rn_node));
1228 		/*
1229 		 * This is not MT-safe, but we have no MT consumers of libzutil
1230 		 */
1231 		while ((dp = readdir64(dirp)) != NULL) {
1232 			char *name = dp->d_name;
1233 			avl_index_t where;
1234 
1235 			if (name[0] == '.' &&
1236 			    (name[1] == 0 || (name[1] == '.' && name[2] == 0)))
1237 				continue;
1238 
1239 			slice = zutil_alloc(hdl, sizeof (rdsk_node_t));
1240 			slice->rn_name = name;
1241 			slice->rn_avl = &slice_cache;
1242 			slice->rn_dfd = dfd;
1243 			slice->rn_hdl = hdl;
1244 			slice->rn_nozpool = B_FALSE;
1245 			/*
1246 			 * readdir(3C) buffers several directory entries per
1247 			 * actual read operation. It is possible that if
1248 			 * directory entries appear between reading one chunk
1249 			 * and the next, that the same entry name can end up
1250 			 * being returned more than once. We need to check that
1251 			 * this entry doesn't already exist before adding it to
1252 			 * the tree.
1253 			 */
1254 			if (avl_find(&slice_cache, slice, &where) == NULL) {
1255 				slice->rn_name = zutil_strdup(hdl, name);
1256 				avl_insert(&slice_cache, slice, where);
1257 			} else {
1258 				free(slice);
1259 			}
1260 		}
1261 		/*
1262 		 * create a thread pool to do all of this in parallel;
1263 		 * rn_nozpool is not protected, so this is racy in that
1264 		 * multiple tasks could decide that the same slice can
1265 		 * not hold a zpool, which is benign.  Also choose
1266 		 * double the number of processors; we hold a lot of
1267 		 * locks in the kernel, so going beyond this doesn't
1268 		 * buy us much.
1269 		 */
1270 		t = tpool_create(1, 2 * sysconf(_SC_NPROCESSORS_ONLN),
1271 		    0, NULL);
1272 		for (slice = avl_first(&slice_cache); slice;
1273 		    (slice = avl_walk(&slice_cache, slice,
1274 		    AVL_AFTER)))
1275 			(void) tpool_dispatch(t, zpool_open_func, slice);
1276 		tpool_wait(t);
1277 		tpool_destroy(t);
1278 
1279 		cookie = NULL;
1280 		while ((slice = avl_destroy_nodes(&slice_cache,
1281 		    &cookie)) != NULL) {
1282 			if (slice->rn_config != NULL && !config_failed) {
1283 				nvlist_t *config = slice->rn_config;
1284 				boolean_t matched = B_TRUE;
1285 
1286 				if (iarg->poolname != NULL) {
1287 					char *pname;
1288 
1289 					matched = nvlist_lookup_string(config,
1290 					    ZPOOL_CONFIG_POOL_NAME,
1291 					    &pname) == 0 &&
1292 					    strcmp(iarg->poolname, pname) == 0;
1293 				} else if (iarg->guid != 0) {
1294 					uint64_t this_guid;
1295 
1296 					matched = nvlist_lookup_uint64(config,
1297 					    ZPOOL_CONFIG_POOL_GUID,
1298 					    &this_guid) == 0 &&
1299 					    iarg->guid == this_guid;
1300 				}
1301 				if (matched) {
1302 					/*
1303 					 * use the non-raw path for the config
1304 					 */
1305 					(void) strlcpy(end, slice->rn_name,
1306 					    pathleft);
1307 					(void) add_config(hdl, &pools,
1308 					    path, slice->rn_order,
1309 					    slice->rn_num_labels, config);
1310 				}
1311 				nvlist_free(config);
1312 			}
1313 			free(slice->rn_name);
1314 			free(slice);
1315 		}
1316 		avl_destroy(&slice_cache);
1317 
1318 		(void) closedir(dirp);
1319 
1320 		if (config_failed)
1321 			goto error;
1322 	}
1323 
1324 	ret = get_configs(hdl, &pools, iarg->can_be_active, iarg->policy);
1325 
1326 error:
1327 	for (pe = pools.pools; pe != NULL; pe = penext) {
1328 		penext = pe->pe_next;
1329 		for (ve = pe->pe_vdevs; ve != NULL; ve = venext) {
1330 			venext = ve->ve_next;
1331 			for (ce = ve->ve_configs; ce != NULL; ce = cenext) {
1332 				cenext = ce->ce_next;
1333 				nvlist_free(ce->ce_config);
1334 				free(ce);
1335 			}
1336 			free(ve);
1337 		}
1338 		free(pe);
1339 	}
1340 
1341 	for (ne = pools.names; ne != NULL; ne = nenext) {
1342 		nenext = ne->ne_next;
1343 		free(ne->ne_name);
1344 		free(ne);
1345 	}
1346 
1347 	return (ret);
1348 }
1349 
1350 /*
1351  * Given a cache file, return the contents as a list of importable pools.
1352  * poolname or guid (but not both) are provided by the caller when trying
1353  * to import a specific pool.
1354  */
1355 static nvlist_t *
1356 zpool_find_import_cached(libpc_handle_t *hdl, const char *cachefile,
1357     const char *poolname, uint64_t guid)
1358 {
1359 	char *buf;
1360 	int fd;
1361 	struct stat64 statbuf;
1362 	nvlist_t *raw, *src, *dst;
1363 	nvlist_t *pools;
1364 	nvpair_t *elem;
1365 	char *name;
1366 	uint64_t this_guid;
1367 	boolean_t active;
1368 
1369 	verify(poolname == NULL || guid == 0);
1370 
1371 	if ((fd = open(cachefile, O_RDONLY)) < 0) {
1372 		zutil_error_aux(hdl, "%s", strerror(errno));
1373 		(void) zutil_error(hdl, EZFS_BADCACHE,
1374 		    dgettext(TEXT_DOMAIN, "failed to open cache file"));
1375 		return (NULL);
1376 	}
1377 
1378 	if (fstat64(fd, &statbuf) != 0) {
1379 		zutil_error_aux(hdl, "%s", strerror(errno));
1380 		(void) close(fd);
1381 		(void) zutil_error(hdl, EZFS_BADCACHE,
1382 		    dgettext(TEXT_DOMAIN, "failed to get size of cache file"));
1383 		return (NULL);
1384 	}
1385 
1386 	if ((buf = zutil_alloc(hdl, statbuf.st_size)) == NULL) {
1387 		(void) close(fd);
1388 		return (NULL);
1389 	}
1390 
1391 	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
1392 		(void) close(fd);
1393 		free(buf);
1394 		(void) zutil_error(hdl, EZFS_BADCACHE,
1395 		    dgettext(TEXT_DOMAIN,
1396 		    "failed to read cache file contents"));
1397 		return (NULL);
1398 	}
1399 
1400 	(void) close(fd);
1401 
1402 	if (nvlist_unpack(buf, statbuf.st_size, &raw, 0) != 0) {
1403 		free(buf);
1404 		(void) zutil_error(hdl, EZFS_BADCACHE,
1405 		    dgettext(TEXT_DOMAIN,
1406 		    "invalid or corrupt cache file contents"));
1407 		return (NULL);
1408 	}
1409 
1410 	free(buf);
1411 
1412 	/*
1413 	 * Go through and get the current state of the pools and refresh their
1414 	 * state.
1415 	 */
1416 	if (nvlist_alloc(&pools, 0, 0) != 0) {
1417 		(void) zutil_no_memory(hdl);
1418 		nvlist_free(raw);
1419 		return (NULL);
1420 	}
1421 
1422 	elem = NULL;
1423 	while ((elem = nvlist_next_nvpair(raw, elem)) != NULL) {
1424 		src = fnvpair_value_nvlist(elem);
1425 
1426 		name = fnvlist_lookup_string(src, ZPOOL_CONFIG_POOL_NAME);
1427 		if (poolname != NULL && strcmp(poolname, name) != 0)
1428 			continue;
1429 
1430 		this_guid = fnvlist_lookup_uint64(src, ZPOOL_CONFIG_POOL_GUID);
1431 		if (guid != 0 && guid != this_guid)
1432 			continue;
1433 
1434 		if (zutil_pool_active(hdl, name, this_guid, &active) != 0) {
1435 			nvlist_free(raw);
1436 			nvlist_free(pools);
1437 			return (NULL);
1438 		}
1439 
1440 		if (active)
1441 			continue;
1442 
1443 		if (nvlist_add_string(src, ZPOOL_CONFIG_CACHEFILE,
1444 		    cachefile) != 0) {
1445 			(void) zutil_no_memory(hdl);
1446 			nvlist_free(raw);
1447 			nvlist_free(pools);
1448 			return (NULL);
1449 		}
1450 
1451 		if ((dst = zutil_refresh_config(hdl, src)) == NULL) {
1452 			nvlist_free(raw);
1453 			nvlist_free(pools);
1454 			return (NULL);
1455 		}
1456 
1457 		if (nvlist_add_nvlist(pools, nvpair_name(elem), dst) != 0) {
1458 			(void) zutil_no_memory(hdl);
1459 			nvlist_free(dst);
1460 			nvlist_free(raw);
1461 			nvlist_free(pools);
1462 			return (NULL);
1463 		}
1464 		nvlist_free(dst);
1465 	}
1466 
1467 	nvlist_free(raw);
1468 	return (pools);
1469 }
1470 
1471 nvlist_t *
1472 zpool_search_import(void *hdl, importargs_t *import,
1473     const pool_config_ops_t *pco)
1474 {
1475 	libpc_handle_t handle = { 0 };
1476 	nvlist_t *pools = NULL;
1477 
1478 	handle.lpc_lib_handle = hdl;
1479 	handle.lpc_ops = pco;
1480 	handle.lpc_printerr = B_TRUE;
1481 
1482 	verify(import->poolname == NULL || import->guid == 0);
1483 
1484 	if (import->cachefile != NULL)
1485 		pools = zpool_find_import_cached(&handle, import->cachefile,
1486 		    import->poolname, import->guid);
1487 	else
1488 		pools = zpool_find_import_impl(&handle, import);
1489 
1490 	if ((pools == NULL || nvlist_empty(pools)) &&
1491 	    handle.lpc_open_access_error && geteuid() != 0) {
1492 		(void) zutil_error(&handle, EZFS_EACESS, dgettext(TEXT_DOMAIN,
1493 		    "no pools found"));
1494 	}
1495 
1496 	return (pools);
1497 }
1498 
1499 static boolean_t
1500 pool_match(nvlist_t *cfg, char *tgt)
1501 {
1502 	uint64_t v, guid = strtoull(tgt, NULL, 0);
1503 	char *s;
1504 
1505 	if (guid != 0) {
1506 		if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &v) == 0)
1507 			return (v == guid);
1508 	} else {
1509 		if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &s) == 0)
1510 			return (strcmp(s, tgt) == 0);
1511 	}
1512 	return (B_FALSE);
1513 }
1514 
1515 int
1516 zpool_find_config(void *hdl, const char *target, nvlist_t **configp,
1517     importargs_t *args, const pool_config_ops_t *pco)
1518 {
1519 	nvlist_t *pools;
1520 	nvlist_t *match = NULL;
1521 	nvlist_t *config = NULL;
1522 	char *sepp = NULL;
1523 	int count = 0;
1524 	char *targetdup = strdup(target);
1525 
1526 	*configp = NULL;
1527 
1528 	if ((sepp = strpbrk(targetdup, "/@")) != NULL) {
1529 		*sepp = '\0';
1530 	}
1531 
1532 	pools = zpool_search_import(hdl, args, pco);
1533 
1534 	if (pools != NULL) {
1535 		nvpair_t *elem = NULL;
1536 		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
1537 			VERIFY0(nvpair_value_nvlist(elem, &config));
1538 			if (pool_match(config, targetdup)) {
1539 				count++;
1540 				if (match != NULL) {
1541 					/* multiple matches found */
1542 					continue;
1543 				} else {
1544 					match = config;
1545 				}
1546 			}
1547 		}
1548 	}
1549 
1550 	if (count == 0) {
1551 		free(targetdup);
1552 		return (ENOENT);
1553 	}
1554 
1555 	if (count > 1) {
1556 		free(targetdup);
1557 		return (EINVAL);
1558 	}
1559 
1560 	*configp = match;
1561 	free(targetdup);
1562 
1563 	return (0);
1564 }
1565