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