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