xref: /titanic_44/usr/src/lib/libzfs/common/libzfs_import.c (revision 39c23413b8df94a95f67b34cfd4a4dfc3fd0b48d)
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 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * Pool import support functions.
30  *
31  * To import a pool, we rely on reading the configuration information from the
32  * ZFS label of each device.  If we successfully read the label, then we
33  * organize the configuration information in the following hierarchy:
34  *
35  * 	pool guid -> toplevel vdev guid -> label txg
36  *
37  * Duplicate entries matching this same tuple will be discarded.  Once we have
38  * examined every device, we pick the best label txg config for each toplevel
39  * vdev.  We then arrange these toplevel vdevs into a complete pool config, and
40  * update any paths that have changed.  Finally, we attempt to import the pool
41  * using our derived config, and record the results.
42  */
43 
44 #include <devid.h>
45 #include <dirent.h>
46 #include <errno.h>
47 #include <libintl.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <sys/stat.h>
51 #include <unistd.h>
52 #include <fcntl.h>
53 
54 #include <sys/vdev_impl.h>
55 
56 #include "libzfs.h"
57 #include "libzfs_impl.h"
58 
59 /*
60  * Intermediate structures used to gather configuration information.
61  */
62 typedef struct config_entry {
63 	uint64_t		ce_txg;
64 	nvlist_t		*ce_config;
65 	struct config_entry	*ce_next;
66 } config_entry_t;
67 
68 typedef struct vdev_entry {
69 	uint64_t		ve_guid;
70 	config_entry_t		*ve_configs;
71 	struct vdev_entry	*ve_next;
72 } vdev_entry_t;
73 
74 typedef struct pool_entry {
75 	uint64_t		pe_guid;
76 	vdev_entry_t		*pe_vdevs;
77 	struct pool_entry	*pe_next;
78 } pool_entry_t;
79 
80 typedef struct name_entry {
81 	char			*ne_name;
82 	uint64_t		ne_guid;
83 	struct name_entry	*ne_next;
84 } name_entry_t;
85 
86 typedef struct pool_list {
87 	pool_entry_t		*pools;
88 	name_entry_t		*names;
89 } pool_list_t;
90 
91 static char *
92 get_devid(const char *path)
93 {
94 	int fd;
95 	ddi_devid_t devid;
96 	char *minor, *ret;
97 
98 	if ((fd = open(path, O_RDONLY)) < 0)
99 		return (NULL);
100 
101 	minor = NULL;
102 	ret = NULL;
103 	if (devid_get(fd, &devid) == 0) {
104 		if (devid_get_minor_name(fd, &minor) == 0)
105 			ret = devid_str_encode(devid, minor);
106 		if (minor != NULL)
107 			devid_str_free(minor);
108 		devid_free(devid);
109 	}
110 	(void) close(fd);
111 
112 	return (ret);
113 }
114 
115 
116 /*
117  * Go through and fix up any path and/or devid information for the given vdev
118  * configuration.
119  */
120 static int
121 fix_paths(nvlist_t *nv, name_entry_t *names)
122 {
123 	nvlist_t **child;
124 	uint_t c, children;
125 	uint64_t guid;
126 	name_entry_t *ne, *best;
127 	char *path, *devid;
128 	int matched;
129 
130 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
131 	    &child, &children) == 0) {
132 		for (c = 0; c < children; c++)
133 			if (fix_paths(child[c], names) != 0)
134 				return (-1);
135 		return (0);
136 	}
137 
138 	/*
139 	 * This is a leaf (file or disk) vdev.  In either case, go through
140 	 * the name list and see if we find a matching guid.  If so, replace
141 	 * the path and see if we can calculate a new devid.
142 	 *
143 	 * There may be multiple names associated with a particular guid, in
144 	 * which case we have overlapping slices or multiple paths to the same
145 	 * disk.  If this is the case, then we want to pick the path that is
146 	 * the most similar to the original, where "most similar" is the number
147 	 * of matching characters starting from the end of the path.  This will
148 	 * preserve slice numbers even if the disks have been reorganized, and
149 	 * will also catch preferred disk names if multiple paths exist.
150 	 */
151 	verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0);
152 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) != 0)
153 		path = NULL;
154 
155 	matched = 0;
156 	best = NULL;
157 	for (ne = names; ne != NULL; ne = ne->ne_next) {
158 		if (ne->ne_guid == guid) {
159 			const char *src, *dst;
160 			int count;
161 
162 			if (path == NULL) {
163 				best = ne;
164 				break;
165 			}
166 
167 			src = ne->ne_name + strlen(ne->ne_name) - 1;
168 			dst = path + strlen(path) - 1;
169 			for (count = 0; src >= ne->ne_name && dst >= path;
170 			    src--, dst--, count++)
171 				if (*src != *dst)
172 					break;
173 
174 			/*
175 			 * At this point, 'count' is the number of characters
176 			 * matched from the end.
177 			 */
178 			if (count > matched || best == NULL) {
179 				best = ne;
180 				matched = count;
181 			}
182 		}
183 	}
184 
185 	if (best == NULL)
186 		return (0);
187 
188 	if (nvlist_add_string(nv, ZPOOL_CONFIG_PATH, best->ne_name) != 0)
189 		return (-1);
190 
191 	if ((devid = get_devid(best->ne_name)) == NULL) {
192 		(void) nvlist_remove_all(nv, ZPOOL_CONFIG_DEVID);
193 	} else {
194 		if (nvlist_add_string(nv, ZPOOL_CONFIG_DEVID, devid) != 0)
195 			return (-1);
196 		devid_str_free(devid);
197 	}
198 
199 	return (0);
200 }
201 
202 /*
203  * Add the given configuration to the list of known devices.
204  */
205 static int
206 add_config(libzfs_handle_t *hdl, pool_list_t *pl, const char *path,
207     nvlist_t *config)
208 {
209 	uint64_t pool_guid, vdev_guid, top_guid, txg, state;
210 	pool_entry_t *pe;
211 	vdev_entry_t *ve;
212 	config_entry_t *ce;
213 	name_entry_t *ne;
214 
215 	/*
216 	 * If this is a hot spare not currently in use, add it to the list of
217 	 * names to translate, but don't do anything else.
218 	 */
219 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
220 	    &state) == 0 && state == POOL_STATE_SPARE &&
221 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, &vdev_guid) == 0) {
222 		if ((ne = zfs_alloc(hdl, sizeof (name_entry_t))) == NULL)
223 		    return (-1);
224 
225 		if ((ne->ne_name = zfs_strdup(hdl, path)) == NULL) {
226 			free(ne);
227 			return (-1);
228 		}
229 		ne->ne_guid = vdev_guid;
230 		ne->ne_next = pl->names;
231 		pl->names = ne;
232 		return (0);
233 	}
234 
235 	/*
236 	 * If we have a valid config but cannot read any of these fields, then
237 	 * it means we have a half-initialized label.  In vdev_label_init()
238 	 * we write a label with txg == 0 so that we can identify the device
239 	 * in case the user refers to the same disk later on.  If we fail to
240 	 * create the pool, we'll be left with a label in this state
241 	 * which should not be considered part of a valid pool.
242 	 */
243 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
244 	    &pool_guid) != 0 ||
245 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID,
246 	    &vdev_guid) != 0 ||
247 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_TOP_GUID,
248 	    &top_guid) != 0 ||
249 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
250 	    &txg) != 0 || txg == 0) {
251 		nvlist_free(config);
252 		return (0);
253 	}
254 
255 	/*
256 	 * First, see if we know about this pool.  If not, then add it to the
257 	 * list of known pools.
258 	 */
259 	for (pe = pl->pools; pe != NULL; pe = pe->pe_next) {
260 		if (pe->pe_guid == pool_guid)
261 			break;
262 	}
263 
264 	if (pe == NULL) {
265 		if ((pe = zfs_alloc(hdl, sizeof (pool_entry_t))) == NULL) {
266 			nvlist_free(config);
267 			return (-1);
268 		}
269 		pe->pe_guid = pool_guid;
270 		pe->pe_next = pl->pools;
271 		pl->pools = pe;
272 	}
273 
274 	/*
275 	 * Second, see if we know about this toplevel vdev.  Add it if its
276 	 * missing.
277 	 */
278 	for (ve = pe->pe_vdevs; ve != NULL; ve = ve->ve_next) {
279 		if (ve->ve_guid == top_guid)
280 			break;
281 	}
282 
283 	if (ve == NULL) {
284 		if ((ve = zfs_alloc(hdl, sizeof (vdev_entry_t))) == NULL) {
285 			nvlist_free(config);
286 			return (-1);
287 		}
288 		ve->ve_guid = top_guid;
289 		ve->ve_next = pe->pe_vdevs;
290 		pe->pe_vdevs = ve;
291 	}
292 
293 	/*
294 	 * Third, see if we have a config with a matching transaction group.  If
295 	 * so, then we do nothing.  Otherwise, add it to the list of known
296 	 * configs.
297 	 */
298 	for (ce = ve->ve_configs; ce != NULL; ce = ce->ce_next) {
299 		if (ce->ce_txg == txg)
300 			break;
301 	}
302 
303 	if (ce == NULL) {
304 		if ((ce = zfs_alloc(hdl, sizeof (config_entry_t))) == NULL) {
305 			nvlist_free(config);
306 			return (-1);
307 		}
308 		ce->ce_txg = txg;
309 		ce->ce_config = config;
310 		ce->ce_next = ve->ve_configs;
311 		ve->ve_configs = ce;
312 	} else {
313 		nvlist_free(config);
314 	}
315 
316 	/*
317 	 * At this point we've successfully added our config to the list of
318 	 * known configs.  The last thing to do is add the vdev guid -> path
319 	 * mappings so that we can fix up the configuration as necessary before
320 	 * doing the import.
321 	 */
322 	if ((ne = zfs_alloc(hdl, sizeof (name_entry_t))) == NULL)
323 		return (-1);
324 
325 	if ((ne->ne_name = zfs_strdup(hdl, path)) == NULL) {
326 		free(ne);
327 		return (-1);
328 	}
329 
330 	ne->ne_guid = vdev_guid;
331 	ne->ne_next = pl->names;
332 	pl->names = ne;
333 
334 	return (0);
335 }
336 
337 /*
338  * Returns true if the named pool matches the given GUID.
339  */
340 static int
341 pool_active(libzfs_handle_t *hdl, const char *name, uint64_t guid,
342     boolean_t *isactive)
343 {
344 	zpool_handle_t *zhp;
345 	uint64_t theguid;
346 
347 	if (zpool_open_silent(hdl, name, &zhp) != 0)
348 		return (-1);
349 
350 	if (zhp == NULL) {
351 		*isactive = B_FALSE;
352 		return (0);
353 	}
354 
355 	verify(nvlist_lookup_uint64(zhp->zpool_config, ZPOOL_CONFIG_POOL_GUID,
356 	    &theguid) == 0);
357 
358 	zpool_close(zhp);
359 
360 	*isactive = (theguid == guid);
361 	return (0);
362 }
363 
364 /*
365  * Convert our list of pools into the definitive set of configurations.  We
366  * start by picking the best config for each toplevel vdev.  Once that's done,
367  * we assemble the toplevel vdevs into a full config for the pool.  We make a
368  * pass to fix up any incorrect paths, and then add it to the main list to
369  * return to the user.
370  */
371 static nvlist_t *
372 get_configs(libzfs_handle_t *hdl, pool_list_t *pl)
373 {
374 	pool_entry_t *pe;
375 	vdev_entry_t *ve;
376 	config_entry_t *ce;
377 	nvlist_t *ret = NULL, *config = NULL, *tmp, *nvtop, *nvroot;
378 	nvlist_t **spares;
379 	uint_t i, nspares;
380 	boolean_t config_seen;
381 	uint64_t best_txg;
382 	char *name;
383 	zfs_cmd_t zc = { 0 };
384 	uint64_t version, guid;
385 	size_t len;
386 	int err;
387 	uint_t children = 0;
388 	nvlist_t **child = NULL;
389 	uint_t c;
390 	boolean_t isactive;
391 
392 	if (nvlist_alloc(&ret, 0, 0) != 0)
393 		goto nomem;
394 
395 	for (pe = pl->pools; pe != NULL; pe = pe->pe_next) {
396 		uint64_t id;
397 
398 		if (nvlist_alloc(&config, NV_UNIQUE_NAME, 0) != 0)
399 			goto nomem;
400 		config_seen = B_FALSE;
401 
402 		/*
403 		 * Iterate over all toplevel vdevs.  Grab the pool configuration
404 		 * from the first one we find, and then go through the rest and
405 		 * add them as necessary to the 'vdevs' member of the config.
406 		 */
407 		for (ve = pe->pe_vdevs; ve != NULL; ve = ve->ve_next) {
408 
409 			/*
410 			 * Determine the best configuration for this vdev by
411 			 * selecting the config with the latest transaction
412 			 * group.
413 			 */
414 			best_txg = 0;
415 			for (ce = ve->ve_configs; ce != NULL;
416 			    ce = ce->ce_next) {
417 
418 				if (ce->ce_txg > best_txg) {
419 					tmp = ce->ce_config;
420 					best_txg = ce->ce_txg;
421 				}
422 			}
423 
424 			if (!config_seen) {
425 				/*
426 				 * Copy the relevant pieces of data to the pool
427 				 * configuration:
428 				 *
429 				 *	version
430 				 * 	pool guid
431 				 * 	name
432 				 * 	pool state
433 				 */
434 				uint64_t state;
435 
436 				verify(nvlist_lookup_uint64(tmp,
437 				    ZPOOL_CONFIG_VERSION, &version) == 0);
438 				if (nvlist_add_uint64(config,
439 				    ZPOOL_CONFIG_VERSION, version) != 0)
440 					goto nomem;
441 				verify(nvlist_lookup_uint64(tmp,
442 				    ZPOOL_CONFIG_POOL_GUID, &guid) == 0);
443 				if (nvlist_add_uint64(config,
444 				    ZPOOL_CONFIG_POOL_GUID, guid) != 0)
445 					goto nomem;
446 				verify(nvlist_lookup_string(tmp,
447 				    ZPOOL_CONFIG_POOL_NAME, &name) == 0);
448 				if (nvlist_add_string(config,
449 				    ZPOOL_CONFIG_POOL_NAME, name) != 0)
450 					goto nomem;
451 				verify(nvlist_lookup_uint64(tmp,
452 				    ZPOOL_CONFIG_POOL_STATE, &state) == 0);
453 				if (nvlist_add_uint64(config,
454 				    ZPOOL_CONFIG_POOL_STATE, state) != 0)
455 					goto nomem;
456 
457 				config_seen = B_TRUE;
458 			}
459 
460 			/*
461 			 * Add this top-level vdev to the child array.
462 			 */
463 			verify(nvlist_lookup_nvlist(tmp,
464 			    ZPOOL_CONFIG_VDEV_TREE, &nvtop) == 0);
465 			verify(nvlist_lookup_uint64(nvtop, ZPOOL_CONFIG_ID,
466 			    &id) == 0);
467 			if (id >= children) {
468 				nvlist_t **newchild;
469 
470 				newchild = zfs_alloc(hdl, (id + 1) *
471 				    sizeof (nvlist_t *));
472 				if (newchild == NULL)
473 					goto nomem;
474 
475 				for (c = 0; c < children; c++)
476 					newchild[c] = child[c];
477 
478 				free(child);
479 				child = newchild;
480 				children = id + 1;
481 			}
482 			if (nvlist_dup(nvtop, &child[id], 0) != 0)
483 				goto nomem;
484 
485 		}
486 
487 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
488 		    &guid) == 0);
489 
490 		/*
491 		 * Look for any missing top-level vdevs.  If this is the case,
492 		 * create a faked up 'missing' vdev as a placeholder.  We cannot
493 		 * simply compress the child array, because the kernel performs
494 		 * certain checks to make sure the vdev IDs match their location
495 		 * in the configuration.
496 		 */
497 		for (c = 0; c < children; c++)
498 			if (child[c] == NULL) {
499 				nvlist_t *missing;
500 				if (nvlist_alloc(&missing, NV_UNIQUE_NAME,
501 				    0) != 0)
502 					goto nomem;
503 				if (nvlist_add_string(missing,
504 				    ZPOOL_CONFIG_TYPE,
505 				    VDEV_TYPE_MISSING) != 0 ||
506 				    nvlist_add_uint64(missing,
507 				    ZPOOL_CONFIG_ID, c) != 0 ||
508 				    nvlist_add_uint64(missing,
509 				    ZPOOL_CONFIG_GUID, 0ULL) != 0) {
510 					nvlist_free(missing);
511 					goto nomem;
512 				}
513 				child[c] = missing;
514 			}
515 
516 		/*
517 		 * Put all of this pool's top-level vdevs into a root vdev.
518 		 */
519 		if (nvlist_alloc(&nvroot, NV_UNIQUE_NAME, 0) != 0)
520 			goto nomem;
521 		if (nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
522 		    VDEV_TYPE_ROOT) != 0 ||
523 		    nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) != 0 ||
524 		    nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, guid) != 0 ||
525 		    nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
526 		    child, children) != 0) {
527 			nvlist_free(nvroot);
528 			goto nomem;
529 		}
530 
531 		for (c = 0; c < children; c++)
532 			nvlist_free(child[c]);
533 		free(child);
534 		children = 0;
535 		child = NULL;
536 
537 		/*
538 		 * Go through and fix up any paths and/or devids based on our
539 		 * known list of vdev GUID -> path mappings.
540 		 */
541 		if (fix_paths(nvroot, pl->names) != 0) {
542 			nvlist_free(nvroot);
543 			goto nomem;
544 		}
545 
546 		/*
547 		 * Add the root vdev to this pool's configuration.
548 		 */
549 		if (nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
550 		    nvroot) != 0) {
551 			nvlist_free(nvroot);
552 			goto nomem;
553 		}
554 		nvlist_free(nvroot);
555 
556 		/*
557 		 * Determine if this pool is currently active, in which case we
558 		 * can't actually import it.
559 		 */
560 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
561 		    &name) == 0);
562 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
563 		    &guid) == 0);
564 
565 		if (pool_active(hdl, name, guid, &isactive) != 0)
566 			goto error;
567 
568 		if (isactive) {
569 			nvlist_free(config);
570 			config = NULL;
571 			continue;
572 		}
573 
574 		/*
575 		 * Try to do the import in order to get vdev state.
576 		 */
577 		if (zcmd_write_src_nvlist(hdl, &zc, config, &len) != 0)
578 			goto error;
579 
580 		nvlist_free(config);
581 		config = NULL;
582 
583 		if (zcmd_alloc_dst_nvlist(hdl, &zc, len * 2) != 0) {
584 			zcmd_free_nvlists(&zc);
585 			goto error;
586 		}
587 
588 		while ((err = ioctl(hdl->libzfs_fd, ZFS_IOC_POOL_TRYIMPORT,
589 		    &zc)) != 0 && errno == ENOMEM) {
590 			if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
591 				zcmd_free_nvlists(&zc);
592 				goto error;
593 			}
594 		}
595 
596 		if (err) {
597 			(void) zpool_standard_error(hdl, errno,
598 			    dgettext(TEXT_DOMAIN, "cannot discover pools"));
599 			zcmd_free_nvlists(&zc);
600 			goto error;
601 		}
602 
603 		if (zcmd_read_dst_nvlist(hdl, &zc, &config) != 0) {
604 			zcmd_free_nvlists(&zc);
605 			goto error;
606 		}
607 
608 		zcmd_free_nvlists(&zc);
609 
610 		/*
611 		 * Go through and update the paths for spares, now that we have
612 		 * them.
613 		 */
614 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
615 		    &nvroot) == 0);
616 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
617 		    &spares, &nspares) == 0) {
618 			for (i = 0; i < nspares; i++) {
619 				if (fix_paths(spares[i], pl->names) != 0)
620 					goto nomem;
621 			}
622 		}
623 
624 		if (set_pool_health(config) != 0)
625 			goto nomem;
626 
627 		/*
628 		 * Add this pool to the list of configs.
629 		 */
630 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
631 		    &name) == 0);
632 		if (nvlist_add_nvlist(ret, name, config) != 0)
633 			goto nomem;
634 
635 		nvlist_free(config);
636 		config = NULL;
637 	}
638 
639 	return (ret);
640 
641 nomem:
642 	(void) no_memory(hdl);
643 error:
644 	nvlist_free(config);
645 	nvlist_free(ret);
646 	for (c = 0; c < children; c++)
647 		nvlist_free(child[c]);
648 	free(child);
649 
650 	return (NULL);
651 }
652 
653 /*
654  * Return the offset of the given label.
655  */
656 static uint64_t
657 label_offset(size_t size, int l)
658 {
659 	return (l * sizeof (vdev_label_t) + (l < VDEV_LABELS / 2 ?
660 	    0 : size - VDEV_LABELS * sizeof (vdev_label_t)));
661 }
662 
663 /*
664  * Given a file descriptor, read the label information and return an nvlist
665  * describing the configuration, if there is one.
666  */
667 int
668 zpool_read_label(int fd, nvlist_t **config)
669 {
670 	struct stat64 statbuf;
671 	int l;
672 	vdev_label_t *label;
673 	uint64_t state, txg;
674 
675 	*config = NULL;
676 
677 	if (fstat64(fd, &statbuf) == -1)
678 		return (0);
679 
680 	if ((label = malloc(sizeof (vdev_label_t))) == NULL)
681 		return (-1);
682 
683 	for (l = 0; l < VDEV_LABELS; l++) {
684 		if (pread(fd, label, sizeof (vdev_label_t),
685 		    label_offset(statbuf.st_size, l)) != sizeof (vdev_label_t))
686 			continue;
687 
688 		if (nvlist_unpack(label->vl_vdev_phys.vp_nvlist,
689 		    sizeof (label->vl_vdev_phys.vp_nvlist), config, 0) != 0)
690 			continue;
691 
692 		if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_STATE,
693 		    &state) != 0 || state > POOL_STATE_SPARE) {
694 			nvlist_free(*config);
695 			continue;
696 		}
697 
698 		if (state != POOL_STATE_SPARE &&
699 		    (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_TXG,
700 		    &txg) != 0 || txg == 0)) {
701 			nvlist_free(*config);
702 			continue;
703 		}
704 
705 		free(label);
706 		return (0);
707 	}
708 
709 	free(label);
710 	*config = NULL;
711 	return (0);
712 }
713 
714 /*
715  * Given a list of directories to search, find all pools stored on disk.  This
716  * includes partial pools which are not available to import.  If no args are
717  * given (argc is 0), then the default directory (/dev/dsk) is searched.
718  */
719 nvlist_t *
720 zpool_find_import(libzfs_handle_t *hdl, int argc, char **argv)
721 {
722 	int i;
723 	DIR *dirp;
724 	struct dirent64 *dp;
725 	char path[MAXPATHLEN];
726 	struct stat64 statbuf;
727 	nvlist_t *ret = NULL, *config;
728 	static char *default_dir = "/dev/dsk";
729 	int fd;
730 	pool_list_t pools = { 0 };
731 	pool_entry_t *pe, *penext;
732 	vdev_entry_t *ve, *venext;
733 	config_entry_t *ce, *cenext;
734 	name_entry_t *ne, *nenext;
735 
736 
737 	if (argc == 0) {
738 		argc = 1;
739 		argv = &default_dir;
740 	}
741 
742 	/*
743 	 * Go through and read the label configuration information from every
744 	 * possible device, organizing the information according to pool GUID
745 	 * and toplevel GUID.
746 	 */
747 	for (i = 0; i < argc; i++) {
748 		if (argv[i][0] != '/') {
749 			(void) zfs_error_fmt(hdl, EZFS_BADPATH,
750 			    dgettext(TEXT_DOMAIN, "cannot open '%s'"),
751 			    argv[i]);
752 			goto error;
753 		}
754 
755 		if ((dirp = opendir(argv[i])) == NULL) {
756 			zfs_error_aux(hdl, strerror(errno));
757 			(void) zfs_error_fmt(hdl, EZFS_BADPATH,
758 			    dgettext(TEXT_DOMAIN, "cannot open '%s'"),
759 			    argv[i]);
760 			goto error;
761 		}
762 
763 		/*
764 		 * This is not MT-safe, but we have no MT consumers of libzfs
765 		 */
766 		while ((dp = readdir64(dirp)) != NULL) {
767 
768 			(void) snprintf(path, sizeof (path), "%s/%s",
769 			    argv[i], dp->d_name);
770 
771 			if (stat64(path, &statbuf) != 0)
772 				continue;
773 
774 			/*
775 			 * Ignore directories (which includes "." and "..").
776 			 */
777 			if (S_ISDIR(statbuf.st_mode))
778 				continue;
779 
780 			/*
781 			 * Ignore special (non-character or non-block) files.
782 			 */
783 			if (!S_ISREG(statbuf.st_mode) &&
784 			    !S_ISBLK(statbuf.st_mode))
785 				continue;
786 
787 			if ((fd = open64(path, O_RDONLY)) < 0)
788 				continue;
789 
790 			if ((zpool_read_label(fd, &config)) != 0) {
791 				(void) no_memory(hdl);
792 				goto error;
793 			}
794 
795 			(void) close(fd);
796 
797 			if (config != NULL)
798 				if (add_config(hdl, &pools, path, config) != 0)
799 					goto error;
800 		}
801 	}
802 
803 	ret = get_configs(hdl, &pools);
804 
805 error:
806 	for (pe = pools.pools; pe != NULL; pe = penext) {
807 		penext = pe->pe_next;
808 		for (ve = pe->pe_vdevs; ve != NULL; ve = venext) {
809 			venext = ve->ve_next;
810 			for (ce = ve->ve_configs; ce != NULL; ce = cenext) {
811 				cenext = ce->ce_next;
812 				if (ce->ce_config)
813 					nvlist_free(ce->ce_config);
814 				free(ce);
815 			}
816 			free(ve);
817 		}
818 		free(pe);
819 	}
820 
821 	for (ne = pools.names; ne != NULL; ne = nenext) {
822 		nenext = ne->ne_next;
823 		if (ne->ne_name)
824 			free(ne->ne_name);
825 		free(ne);
826 	}
827 
828 
829 	return (ret);
830 }
831 
832 boolean_t
833 find_guid(nvlist_t *nv, uint64_t guid)
834 {
835 	uint64_t tmp;
836 	nvlist_t **child;
837 	uint_t c, children;
838 
839 	verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &tmp) == 0);
840 	if (tmp == guid)
841 		return (B_TRUE);
842 
843 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
844 	    &child, &children) == 0) {
845 		for (c = 0; c < children; c++)
846 			if (find_guid(child[c], guid))
847 				return (B_TRUE);
848 	}
849 
850 	return (B_FALSE);
851 }
852 
853 typedef struct spare_cbdata {
854 	uint64_t	cb_guid;
855 	zpool_handle_t	*cb_zhp;
856 } spare_cbdata_t;
857 
858 static int
859 find_spare(zpool_handle_t *zhp, void *data)
860 {
861 	spare_cbdata_t *cbp = data;
862 	nvlist_t **spares;
863 	uint_t i, nspares;
864 	uint64_t guid;
865 	nvlist_t *nvroot;
866 
867 	verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
868 	    &nvroot) == 0);
869 
870 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
871 	    &spares, &nspares) == 0) {
872 		for (i = 0; i < nspares; i++) {
873 			verify(nvlist_lookup_uint64(spares[i],
874 			    ZPOOL_CONFIG_GUID, &guid) == 0);
875 			if (guid == cbp->cb_guid) {
876 				cbp->cb_zhp = zhp;
877 				return (1);
878 			}
879 		}
880 	}
881 
882 	zpool_close(zhp);
883 	return (0);
884 }
885 
886 /*
887  * Determines if the pool is in use.  If so, it returns true and the state of
888  * the pool as well as the name of the pool.  Both strings are allocated and
889  * must be freed by the caller.
890  */
891 int
892 zpool_in_use(libzfs_handle_t *hdl, int fd, pool_state_t *state, char **namestr,
893     boolean_t *inuse)
894 {
895 	nvlist_t *config;
896 	char *name;
897 	boolean_t ret;
898 	uint64_t guid, vdev_guid;
899 	zpool_handle_t *zhp;
900 	nvlist_t *pool_config;
901 	uint64_t stateval, isspare;
902 	spare_cbdata_t cb = { 0 };
903 	boolean_t isactive;
904 
905 	*inuse = B_FALSE;
906 
907 	if (zpool_read_label(fd, &config) != 0) {
908 		(void) no_memory(hdl);
909 		return (-1);
910 	}
911 
912 	if (config == NULL)
913 		return (0);
914 
915 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
916 	    &stateval) == 0);
917 	verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID,
918 	    &vdev_guid) == 0);
919 
920 	if (stateval != POOL_STATE_SPARE) {
921 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
922 		    &name) == 0);
923 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
924 		    &guid) == 0);
925 	}
926 
927 	switch (stateval) {
928 	case POOL_STATE_EXPORTED:
929 		ret = B_TRUE;
930 		break;
931 
932 	case POOL_STATE_ACTIVE:
933 		/*
934 		 * For an active pool, we have to determine if it's really part
935 		 * of a currently active pool (in which case the pool will exist
936 		 * and the guid will be the same), or whether it's part of an
937 		 * active pool that was disconnected without being explicitly
938 		 * exported.
939 		 */
940 		if (pool_active(hdl, name, guid, &isactive) != 0) {
941 			nvlist_free(config);
942 			return (-1);
943 		}
944 
945 		if (isactive) {
946 			/*
947 			 * Because the device may have been removed while
948 			 * offlined, we only report it as active if the vdev is
949 			 * still present in the config.  Otherwise, pretend like
950 			 * it's not in use.
951 			 */
952 			if ((zhp = zpool_open_canfail(hdl, name)) != NULL &&
953 			    (pool_config = zpool_get_config(zhp, NULL))
954 			    != NULL) {
955 				nvlist_t *nvroot;
956 
957 				verify(nvlist_lookup_nvlist(pool_config,
958 				    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
959 				ret = find_guid(nvroot, vdev_guid);
960 			} else {
961 				ret = B_FALSE;
962 			}
963 
964 			/*
965 			 * If this is an active spare within another pool, we
966 			 * treat it like an unused hot spare.  This allows the
967 			 * user to create a pool with a hot spare that currently
968 			 * in use within another pool.  Since we return B_TRUE,
969 			 * libdiskmgt will continue to prevent generic consumers
970 			 * from using the device.
971 			 */
972 			if (ret && nvlist_lookup_uint64(config,
973 			    ZPOOL_CONFIG_IS_SPARE, &isspare) == 0 && isspare)
974 				stateval = POOL_STATE_SPARE;
975 
976 			if (zhp != NULL)
977 				zpool_close(zhp);
978 		} else {
979 			stateval = POOL_STATE_POTENTIALLY_ACTIVE;
980 			ret = B_TRUE;
981 		}
982 		break;
983 
984 	case POOL_STATE_SPARE:
985 		/*
986 		 * For a hot spare, it can be either definitively in use, or
987 		 * potentially active.  To determine if it's in use, we iterate
988 		 * over all pools in the system and search for one with a spare
989 		 * with a matching guid.
990 		 *
991 		 * Due to the shared nature of spares, we don't actually report
992 		 * the potentially active case as in use.  This means the user
993 		 * can freely create pools on the hot spares of exported pools,
994 		 * but to do otherwise makes the resulting code complicated, and
995 		 * we end up having to deal with this case anyway.
996 		 */
997 		cb.cb_zhp = NULL;
998 		cb.cb_guid = vdev_guid;
999 		if (zpool_iter(hdl, find_spare, &cb) == 1) {
1000 			name = (char *)zpool_get_name(cb.cb_zhp);
1001 			ret = TRUE;
1002 		} else {
1003 			ret = FALSE;
1004 		}
1005 		break;
1006 
1007 	default:
1008 		ret = B_FALSE;
1009 	}
1010 
1011 
1012 	if (ret) {
1013 		if ((*namestr = zfs_strdup(hdl, name)) == NULL) {
1014 			nvlist_free(config);
1015 			return (-1);
1016 		}
1017 		*state = (pool_state_t)stateval;
1018 	}
1019 
1020 	if (cb.cb_zhp)
1021 		zpool_close(cb.cb_zhp);
1022 
1023 	nvlist_free(config);
1024 	*inuse = ret;
1025 	return (0);
1026 }
1027