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