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