]> git.proxmox.com Git - mirror_zfs.git/blame - lib/libzfs/libzfs_import.c
Disable efi_debug in --enable-debug builds
[mirror_zfs.git] / lib / libzfs / libzfs_import.c
CommitLineData
34dc7c2f
BB
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/*
0fdd8d64 22 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
572e2857 23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
3bc7e0fb 24 * Copyright (c) 2012 by Delphix. All rights reserved.
ee42b3d6 25 * Copyright 2015 RackTop Systems.
39fc0cb5 26 * Copyright (c) 2016, Intel Corporation.
34dc7c2f
BB
27 */
28
34dc7c2f
BB
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
428870ff 45#include <ctype.h>
34dc7c2f
BB
46#include <devid.h>
47#include <dirent.h>
48#include <errno.h>
49#include <libintl.h>
39fc0cb5
DB
50#ifdef HAVE_LIBUDEV
51#include <libudev.h>
52#include <sched.h>
53#endif
428870ff 54#include <stddef.h>
34dc7c2f
BB
55#include <stdlib.h>
56#include <string.h>
57#include <sys/stat.h>
58#include <unistd.h>
59#include <fcntl.h>
428870ff
BB
60#include <sys/vtoc.h>
61#include <sys/dktp/fdisk.h>
62#include <sys/efi_partition.h>
34dc7c2f 63#include <sys/vdev_impl.h>
d603ed6c 64#include <blkid/blkid.h>
34dc7c2f
BB
65#include "libzfs.h"
66#include "libzfs_impl.h"
67
68/*
69 * Intermediate structures used to gather configuration information.
70 */
71typedef struct config_entry {
72 uint64_t ce_txg;
73 nvlist_t *ce_config;
74 struct config_entry *ce_next;
75} config_entry_t;
76
77typedef struct vdev_entry {
78 uint64_t ve_guid;
79 config_entry_t *ve_configs;
80 struct vdev_entry *ve_next;
81} vdev_entry_t;
82
83typedef struct pool_entry {
84 uint64_t pe_guid;
85 vdev_entry_t *pe_vdevs;
86 struct pool_entry *pe_next;
87} pool_entry_t;
88
89typedef struct name_entry {
90 char *ne_name;
91 uint64_t ne_guid;
44867b6d 92 uint64_t ne_order;
7d90f569 93 uint64_t ne_num_labels;
34dc7c2f
BB
94 struct name_entry *ne_next;
95} name_entry_t;
96
97typedef struct pool_list {
98 pool_entry_t *pools;
99 name_entry_t *names;
100} pool_list_t;
101
39fc0cb5
DB
102/*
103 * Linux persistent device strings for vdev labels
104 *
105 * based on libudev for consistency with libudev disk add/remove events
106 */
107#ifdef HAVE_LIBUDEV
108
109#define DEV_BYID_PATH "/dev/disk/by-id/"
110
111typedef struct vdev_dev_strs {
112 char vds_devid[128];
113 char vds_devphys[128];
114} vdev_dev_strs_t;
115
116/*
117 * Obtain the persistent device id string (describes what)
118 *
119 * used by ZED auto-{online,expand,replace}
120 */
121static int
122udev_device_get_devid(struct udev_device *dev, char *bufptr, size_t buflen)
123{
124 struct udev_list_entry *entry;
125 const char *bus;
126 char devbyid[MAXPATHLEN];
127
128 /* The bus based by-id path is preferred */
129 bus = udev_device_get_property_value(dev, "ID_BUS");
130
131 if (bus == NULL) {
132 const char *dm_uuid;
133
134 /*
135 * For multipath nodes use the persistent uuid based identifier
136 *
137 * Example: /dev/disk/by-id/dm-uuid-mpath-35000c5006304de3f
138 */
139 dm_uuid = udev_device_get_property_value(dev, "DM_UUID");
140 if (dm_uuid != NULL) {
141 (void) snprintf(bufptr, buflen, "dm-uuid-%s", dm_uuid);
142 return (0);
143 }
144 return (ENODATA);
145 }
146
147 /*
148 * locate the bus specific by-id link
149 */
150 (void) snprintf(devbyid, sizeof (devbyid), "%s%s-", DEV_BYID_PATH, bus);
151 entry = udev_device_get_devlinks_list_entry(dev);
152 while (entry != NULL) {
153 const char *name;
154
155 name = udev_list_entry_get_name(entry);
156 if (strncmp(name, devbyid, strlen(devbyid)) == 0) {
157 name += strlen(DEV_BYID_PATH);
158 (void) strlcpy(bufptr, name, buflen);
159 return (0);
160 }
161 entry = udev_list_entry_get_next(entry);
162 }
163
164 return (ENODATA);
165}
166
167/*
168 * Obtain the persistent physical location string (describes where)
169 *
170 * used by ZED auto-{online,expand,replace}
171 */
172static int
173udev_device_get_physical(struct udev_device *dev, char *bufptr, size_t buflen)
174{
175 const char *physpath, *value;
176
177 /*
178 * Skip indirect multipath device nodes
179 */
180 value = udev_device_get_property_value(dev, "DM_MULTIPATH_DEVICE_PATH");
181 if (value != NULL && strcmp(value, "1") == 0)
182 return (ENODATA); /* skip physical for multipath nodes */
183
184 physpath = udev_device_get_property_value(dev, "ID_PATH");
185 if (physpath != NULL && physpath[0] != '\0') {
186 (void) strlcpy(bufptr, physpath, buflen);
187 return (0);
188 }
189
190 return (ENODATA);
191}
192
193/*
194 * A disk is considered a multipath whole disk when:
195 * DEVNAME key value has "dm-"
196 * DM_NAME key value has "mpath" prefix
197 * DM_UUID key exists
198 * ID_PART_TABLE_TYPE key does not exist or is not gpt
199 */
200static boolean_t
201udev_mpath_whole_disk(struct udev_device *dev)
202{
203 const char *devname, *mapname, *type, *uuid;
204
205 devname = udev_device_get_property_value(dev, "DEVNAME");
206 mapname = udev_device_get_property_value(dev, "DM_NAME");
207 type = udev_device_get_property_value(dev, "ID_PART_TABLE_TYPE");
208 uuid = udev_device_get_property_value(dev, "DM_UUID");
209
210 if ((devname != NULL && strncmp(devname, "/dev/dm-", 8) == 0) &&
211 (mapname != NULL && strncmp(mapname, "mpath", 5) == 0) &&
212 ((type == NULL) || (strcmp(type, "gpt") != 0)) &&
213 (uuid != NULL)) {
214 return (B_TRUE);
215 }
216
217 return (B_FALSE);
218}
219
220/*
221 * Check if a disk is effectively a multipath whole disk
222 */
223boolean_t
224is_mpath_whole_disk(const char *path)
225{
226 struct udev *udev;
227 struct udev_device *dev = NULL;
228 char nodepath[MAXPATHLEN];
229 char *sysname;
230 boolean_t wholedisk = B_FALSE;
231
232 if (realpath(path, nodepath) == NULL)
233 return (B_FALSE);
234 sysname = strrchr(nodepath, '/') + 1;
235 if (strncmp(sysname, "dm-", 3) != 0)
236 return (B_FALSE);
237 if ((udev = udev_new()) == NULL)
238 return (B_FALSE);
239 if ((dev = udev_device_new_from_subsystem_sysname(udev, "block",
240 sysname)) == NULL) {
241 udev_device_unref(dev);
242 return (B_FALSE);
243 }
244
245 wholedisk = udev_mpath_whole_disk(dev);
246
247 udev_device_unref(dev);
248 return (wholedisk);
249}
250
251static int
252udev_device_is_ready(struct udev_device *dev)
253{
254#ifdef HAVE_LIBUDEV_UDEV_DEVICE_GET_IS_INITIALIZED
255 return (udev_device_get_is_initialized(dev));
256#else
257 /* wait for DEVLINKS property to be initialized */
258 return (udev_device_get_property_value(dev, "DEVLINKS") != NULL);
259#endif
260}
261
2d82ea8b
BB
262/*
263 * Wait up to timeout_ms for udev to set up the device node. The device is
264 * considered ready when libudev determines it has been initialized, all of
265 * the device links have been verified to exist, and it has been allowed to
266 * settle. At this point the device the device can be accessed reliably.
267 * Depending on the complexity of the udev rules this process could take
268 * several seconds.
269 */
270int
271zpool_label_disk_wait(char *path, int timeout_ms)
272{
273 struct udev *udev;
274 struct udev_device *dev = NULL;
275 char nodepath[MAXPATHLEN];
276 char *sysname = NULL;
277 int ret = ENODEV;
278 int settle_ms = 50;
279 long sleep_ms = 10;
280 hrtime_t start, settle;
281
282 if ((udev = udev_new()) == NULL)
283 return (ENXIO);
284
285 start = gethrtime();
286 settle = 0;
287
288 do {
289 if (sysname == NULL) {
290 if (realpath(path, nodepath) != NULL) {
291 sysname = strrchr(nodepath, '/') + 1;
292 } else {
293 (void) usleep(sleep_ms * MILLISEC);
294 continue;
295 }
296 }
297
298 dev = udev_device_new_from_subsystem_sysname(udev,
299 "block", sysname);
300 if ((dev != NULL) && udev_device_is_ready(dev)) {
301 struct udev_list_entry *links, *link;
302
303 ret = 0;
304 links = udev_device_get_devlinks_list_entry(dev);
305
306 udev_list_entry_foreach(link, links) {
307 struct stat64 statbuf;
308 const char *name;
309
310 name = udev_list_entry_get_name(link);
311 errno = 0;
312 if (stat64(name, &statbuf) == 0 && errno == 0)
313 continue;
314
315 settle = 0;
316 ret = ENODEV;
317 break;
318 }
319
320 if (ret == 0) {
321 if (settle == 0) {
322 settle = gethrtime();
323 } else if (NSEC2MSEC(gethrtime() - settle) >=
324 settle_ms) {
325 udev_device_unref(dev);
326 break;
327 }
328 }
329 }
330
331 udev_device_unref(dev);
332 (void) usleep(sleep_ms * MILLISEC);
333
334 } while (NSEC2MSEC(gethrtime() - start) < timeout_ms);
335
336 udev_unref(udev);
337
338 return (ret);
339}
340
341
39fc0cb5
DB
342/*
343 * Encode the persistent devices strings
344 * used for the vdev disk label
345 */
346static int
347encode_device_strings(const char *path, vdev_dev_strs_t *ds,
348 boolean_t wholedisk)
34dc7c2f 349{
39fc0cb5
DB
350 struct udev *udev;
351 struct udev_device *dev = NULL;
352 char nodepath[MAXPATHLEN];
353 char *sysname;
354 int ret = ENODEV;
355 hrtime_t start;
356
357 if ((udev = udev_new()) == NULL)
358 return (ENXIO);
359
360 /* resolve path to a runtime device node instance */
361 if (realpath(path, nodepath) == NULL)
362 goto no_dev;
363
364 sysname = strrchr(nodepath, '/') + 1;
365
366 /*
367 * Wait up to 3 seconds for udev to set up the device node context
368 */
369 start = gethrtime();
370 do {
371 dev = udev_device_new_from_subsystem_sysname(udev, "block",
372 sysname);
373 if (dev == NULL)
374 goto no_dev;
375 if (udev_device_is_ready(dev))
376 break; /* udev ready */
377
378 udev_device_unref(dev);
379 dev = NULL;
380
381 if (NSEC2MSEC(gethrtime() - start) < 10)
382 (void) sched_yield(); /* yield/busy wait up to 10ms */
383 else
384 (void) usleep(10 * MILLISEC);
385
386 } while (NSEC2MSEC(gethrtime() - start) < (3 * MILLISEC));
387
388 if (dev == NULL)
389 goto no_dev;
390
391 /*
392 * Only whole disks require extra device strings
393 */
394 if (!wholedisk && !udev_mpath_whole_disk(dev))
395 goto no_dev;
396
397 ret = udev_device_get_devid(dev, ds->vds_devid, sizeof (ds->vds_devid));
398 if (ret != 0)
399 goto no_dev_ref;
400
401 /* physical location string (optional) */
402 if (udev_device_get_physical(dev, ds->vds_devphys,
403 sizeof (ds->vds_devphys)) != 0) {
404 ds->vds_devphys[0] = '\0'; /* empty string --> not available */
34dc7c2f 405 }
39fc0cb5
DB
406
407no_dev_ref:
408 udev_device_unref(dev);
409no_dev:
410 udev_unref(udev);
34dc7c2f
BB
411
412 return (ret);
413}
414
39fc0cb5
DB
415/*
416 * Update a leaf vdev's persistent device strings (Linux only)
417 *
418 * - only applies for a dedicated leaf vdev (aka whole disk)
419 * - updated during pool create|add|attach|import
420 * - used for matching device matching during auto-{online,expand,replace}
421 * - stored in a leaf disk config label (i.e. alongside 'path' NVP)
422 * - these strings are currently not used in kernel (i.e. for vdev_disk_open)
423 *
424 * single device node example:
425 * devid: 'scsi-MG03SCA300_350000494a8cb3d67-part1'
426 * phys_path: 'pci-0000:04:00.0-sas-0x50000394a8cb3d67-lun-0'
427 *
428 * multipath device node example:
429 * devid: 'dm-uuid-mpath-35000c5006304de3f'
430 */
431void
432update_vdev_config_dev_strs(nvlist_t *nv)
433{
434 vdev_dev_strs_t vds;
435 char *env, *type, *path;
436 uint64_t wholedisk = 0;
437
438 /*
439 * For the benefit of legacy ZFS implementations, allow
440 * for opting out of devid strings in the vdev label.
441 *
442 * example use:
443 * env ZFS_VDEV_DEVID_OPT_OUT=YES zpool import dozer
444 *
445 * explanation:
446 * Older ZFS on Linux implementations had issues when attempting to
447 * display pool config VDEV names if a "devid" NVP value is present
448 * in the pool's config.
449 *
450 * For example, a pool that originated on illumos platform would
451 * have a devid value in the config and "zpool status" would fail
452 * when listing the config.
453 *
454 * A pool can be stripped of any "devid" values on import or
455 * prevented from adding them on zpool create|add by setting
456 * ZFS_VDEV_DEVID_OPT_OUT.
457 */
458 env = getenv("ZFS_VDEV_DEVID_OPT_OUT");
459 if (env && (strtoul(env, NULL, 0) > 0 ||
460 !strncasecmp(env, "YES", 3) || !strncasecmp(env, "ON", 2))) {
461 (void) nvlist_remove_all(nv, ZPOOL_CONFIG_DEVID);
462 (void) nvlist_remove_all(nv, ZPOOL_CONFIG_PHYS_PATH);
463 return;
464 }
465
466 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0 ||
467 strcmp(type, VDEV_TYPE_DISK) != 0) {
468 return;
469 }
470 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) != 0)
471 return;
472 (void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK, &wholedisk);
473
474 /*
475 * Update device string values in config nvlist
476 */
477 if (encode_device_strings(path, &vds, (boolean_t)wholedisk) == 0) {
478 (void) nvlist_add_string(nv, ZPOOL_CONFIG_DEVID, vds.vds_devid);
479 if (vds.vds_devphys[0] != '\0') {
480 (void) nvlist_add_string(nv, ZPOOL_CONFIG_PHYS_PATH,
481 vds.vds_devphys);
482 }
483 } else {
484 /* clear out any stale entries */
485 (void) nvlist_remove_all(nv, ZPOOL_CONFIG_DEVID);
486 (void) nvlist_remove_all(nv, ZPOOL_CONFIG_PHYS_PATH);
487 }
488}
489#else
490
491boolean_t
492is_mpath_whole_disk(const char *path)
493{
494 return (B_FALSE);
495}
496
2d82ea8b
BB
497/*
498 * Wait up to timeout_ms for udev to set up the device node. The device is
499 * considered ready when the provided path have been verified to exist and
500 * it has been allowed to settle. At this point the device the device can
501 * be accessed reliably. Depending on the complexity of the udev rules thisi
502 * process could take several seconds.
503 */
504int
505zpool_label_disk_wait(char *path, int timeout_ms)
506{
507 int settle_ms = 50;
508 long sleep_ms = 10;
509 hrtime_t start, settle;
510 struct stat64 statbuf;
511
512 start = gethrtime();
513 settle = 0;
514
515 do {
516 errno = 0;
517 if ((stat64(path, &statbuf) == 0) && (errno == 0)) {
518 if (settle == 0)
519 settle = gethrtime();
520 else if (NSEC2MSEC(gethrtime() - settle) >= settle_ms)
521 return (0);
522 } else if (errno != ENOENT) {
523 return (errno);
524 }
525
526 usleep(sleep_ms * MILLISEC);
527 } while (NSEC2MSEC(gethrtime() - start) < timeout_ms);
528
529 return (ENODEV);
530}
531
39fc0cb5
DB
532void
533update_vdev_config_dev_strs(nvlist_t *nv)
534{
535}
536
537#endif /* HAVE_LIBUDEV */
538
34dc7c2f
BB
539
540/*
541 * Go through and fix up any path and/or devid information for the given vdev
542 * configuration.
543 */
544static int
545fix_paths(nvlist_t *nv, name_entry_t *names)
546{
547 nvlist_t **child;
548 uint_t c, children;
549 uint64_t guid;
550 name_entry_t *ne, *best;
39fc0cb5 551 char *path;
34dc7c2f
BB
552
553 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
554 &child, &children) == 0) {
555 for (c = 0; c < children; c++)
556 if (fix_paths(child[c], names) != 0)
557 return (-1);
558 return (0);
559 }
560
561 /*
562 * This is a leaf (file or disk) vdev. In either case, go through
563 * the name list and see if we find a matching guid. If so, replace
564 * the path and see if we can calculate a new devid.
565 *
566 * There may be multiple names associated with a particular guid, in
44867b6d
BB
567 * which case we have overlapping partitions or multiple paths to the
568 * same disk. In this case we prefer to use the path name which
569 * matches the ZPOOL_CONFIG_PATH. If no matching entry is found we
570 * use the lowest order device which corresponds to the first match
571 * while traversing the ZPOOL_IMPORT_PATH search path.
34dc7c2f
BB
572 */
573 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0);
574 if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) != 0)
575 path = NULL;
576
34dc7c2f
BB
577 best = NULL;
578 for (ne = names; ne != NULL; ne = ne->ne_next) {
579 if (ne->ne_guid == guid) {
34dc7c2f
BB
580
581 if (path == NULL) {
582 best = ne;
583 break;
584 }
585
44867b6d 586 if ((strlen(path) == strlen(ne->ne_name)) &&
d1d7e268 587 strncmp(path, ne->ne_name, strlen(path)) == 0) {
34dc7c2f 588 best = ne;
44867b6d 589 break;
34dc7c2f 590 }
44867b6d 591
7d90f569 592 if (best == NULL) {
44867b6d 593 best = ne;
7d90f569
BB
594 continue;
595 }
596
597 /* Prefer paths with move vdev labels. */
598 if (ne->ne_num_labels > best->ne_num_labels) {
599 best = ne;
600 continue;
601 }
602
603 /* Prefer paths earlier in the search order. */
604 if (best->ne_num_labels == best->ne_num_labels &&
605 ne->ne_order < best->ne_order) {
606 best = ne;
607 continue;
608 }
34dc7c2f
BB
609 }
610 }
611
612 if (best == NULL)
613 return (0);
614
615 if (nvlist_add_string(nv, ZPOOL_CONFIG_PATH, best->ne_name) != 0)
616 return (-1);
617
39fc0cb5
DB
618 /* Linux only - update ZPOOL_CONFIG_DEVID and ZPOOL_CONFIG_PHYS_PATH */
619 update_vdev_config_dev_strs(nv);
34dc7c2f
BB
620
621 return (0);
622}
623
624/*
625 * Add the given configuration to the list of known devices.
626 */
627static int
628add_config(libzfs_handle_t *hdl, pool_list_t *pl, const char *path,
7d90f569 629 int order, int num_labels, nvlist_t *config)
34dc7c2f
BB
630{
631 uint64_t pool_guid, vdev_guid, top_guid, txg, state;
632 pool_entry_t *pe;
633 vdev_entry_t *ve;
634 config_entry_t *ce;
635 name_entry_t *ne;
636
637 /*
638 * If this is a hot spare not currently in use or level 2 cache
639 * device, add it to the list of names to translate, but don't do
640 * anything else.
641 */
642 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
643 &state) == 0 &&
644 (state == POOL_STATE_SPARE || state == POOL_STATE_L2CACHE) &&
645 nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, &vdev_guid) == 0) {
646 if ((ne = zfs_alloc(hdl, sizeof (name_entry_t))) == NULL)
647 return (-1);
648
649 if ((ne->ne_name = zfs_strdup(hdl, path)) == NULL) {
650 free(ne);
651 return (-1);
652 }
653 ne->ne_guid = vdev_guid;
44867b6d 654 ne->ne_order = order;
7d90f569 655 ne->ne_num_labels = num_labels;
34dc7c2f
BB
656 ne->ne_next = pl->names;
657 pl->names = ne;
658 return (0);
659 }
660
661 /*
662 * If we have a valid config but cannot read any of these fields, then
663 * it means we have a half-initialized label. In vdev_label_init()
664 * we write a label with txg == 0 so that we can identify the device
665 * in case the user refers to the same disk later on. If we fail to
666 * create the pool, we'll be left with a label in this state
667 * which should not be considered part of a valid pool.
668 */
669 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
670 &pool_guid) != 0 ||
671 nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID,
672 &vdev_guid) != 0 ||
673 nvlist_lookup_uint64(config, ZPOOL_CONFIG_TOP_GUID,
674 &top_guid) != 0 ||
675 nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
676 &txg) != 0 || txg == 0) {
677 nvlist_free(config);
678 return (0);
679 }
680
681 /*
682 * First, see if we know about this pool. If not, then add it to the
683 * list of known pools.
684 */
685 for (pe = pl->pools; pe != NULL; pe = pe->pe_next) {
686 if (pe->pe_guid == pool_guid)
687 break;
688 }
689
690 if (pe == NULL) {
691 if ((pe = zfs_alloc(hdl, sizeof (pool_entry_t))) == NULL) {
692 nvlist_free(config);
693 return (-1);
694 }
695 pe->pe_guid = pool_guid;
696 pe->pe_next = pl->pools;
697 pl->pools = pe;
698 }
699
700 /*
701 * Second, see if we know about this toplevel vdev. Add it if its
702 * missing.
703 */
704 for (ve = pe->pe_vdevs; ve != NULL; ve = ve->ve_next) {
705 if (ve->ve_guid == top_guid)
706 break;
707 }
708
709 if (ve == NULL) {
710 if ((ve = zfs_alloc(hdl, sizeof (vdev_entry_t))) == NULL) {
711 nvlist_free(config);
712 return (-1);
713 }
714 ve->ve_guid = top_guid;
715 ve->ve_next = pe->pe_vdevs;
716 pe->pe_vdevs = ve;
717 }
718
719 /*
720 * Third, see if we have a config with a matching transaction group. If
721 * so, then we do nothing. Otherwise, add it to the list of known
722 * configs.
723 */
724 for (ce = ve->ve_configs; ce != NULL; ce = ce->ce_next) {
725 if (ce->ce_txg == txg)
726 break;
727 }
728
729 if (ce == NULL) {
730 if ((ce = zfs_alloc(hdl, sizeof (config_entry_t))) == NULL) {
731 nvlist_free(config);
732 return (-1);
733 }
734 ce->ce_txg = txg;
735 ce->ce_config = config;
736 ce->ce_next = ve->ve_configs;
737 ve->ve_configs = ce;
738 } else {
739 nvlist_free(config);
740 }
741
742 /*
743 * At this point we've successfully added our config to the list of
744 * known configs. The last thing to do is add the vdev guid -> path
745 * mappings so that we can fix up the configuration as necessary before
746 * doing the import.
747 */
748 if ((ne = zfs_alloc(hdl, sizeof (name_entry_t))) == NULL)
749 return (-1);
750
751 if ((ne->ne_name = zfs_strdup(hdl, path)) == NULL) {
752 free(ne);
753 return (-1);
754 }
755
756 ne->ne_guid = vdev_guid;
44867b6d 757 ne->ne_order = order;
7d90f569 758 ne->ne_num_labels = num_labels;
34dc7c2f
BB
759 ne->ne_next = pl->names;
760 pl->names = ne;
761
762 return (0);
763}
764
765/*
766 * Returns true if the named pool matches the given GUID.
767 */
768static int
769pool_active(libzfs_handle_t *hdl, const char *name, uint64_t guid,
770 boolean_t *isactive)
771{
772 zpool_handle_t *zhp;
773 uint64_t theguid;
774
775 if (zpool_open_silent(hdl, name, &zhp) != 0)
776 return (-1);
777
778 if (zhp == NULL) {
779 *isactive = B_FALSE;
780 return (0);
781 }
782
783 verify(nvlist_lookup_uint64(zhp->zpool_config, ZPOOL_CONFIG_POOL_GUID,
784 &theguid) == 0);
785
786 zpool_close(zhp);
787
788 *isactive = (theguid == guid);
789 return (0);
790}
791
792static nvlist_t *
793refresh_config(libzfs_handle_t *hdl, nvlist_t *config)
794{
795 nvlist_t *nvl;
13fe0198 796 zfs_cmd_t zc = {"\0"};
34dc7c2f
BB
797 int err;
798
799 if (zcmd_write_conf_nvlist(hdl, &zc, config) != 0)
800 return (NULL);
801
802 if (zcmd_alloc_dst_nvlist(hdl, &zc,
803 zc.zc_nvlist_conf_size * 2) != 0) {
804 zcmd_free_nvlists(&zc);
805 return (NULL);
806 }
807
808 while ((err = ioctl(hdl->libzfs_fd, ZFS_IOC_POOL_TRYIMPORT,
809 &zc)) != 0 && errno == ENOMEM) {
810 if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
811 zcmd_free_nvlists(&zc);
812 return (NULL);
813 }
814 }
815
816 if (err) {
34dc7c2f
BB
817 zcmd_free_nvlists(&zc);
818 return (NULL);
819 }
820
821 if (zcmd_read_dst_nvlist(hdl, &zc, &nvl) != 0) {
822 zcmd_free_nvlists(&zc);
823 return (NULL);
824 }
825
826 zcmd_free_nvlists(&zc);
827 return (nvl);
828}
829
428870ff
BB
830/*
831 * Determine if the vdev id is a hole in the namespace.
832 */
833boolean_t
834vdev_is_hole(uint64_t *hole_array, uint_t holes, uint_t id)
835{
d6320ddb
BB
836 int c;
837
838 for (c = 0; c < holes; c++) {
428870ff
BB
839
840 /* Top-level is a hole */
841 if (hole_array[c] == id)
842 return (B_TRUE);
843 }
844 return (B_FALSE);
845}
846
34dc7c2f
BB
847/*
848 * Convert our list of pools into the definitive set of configurations. We
849 * start by picking the best config for each toplevel vdev. Once that's done,
850 * we assemble the toplevel vdevs into a full config for the pool. We make a
851 * pass to fix up any incorrect paths, and then add it to the main list to
852 * return to the user.
853 */
854static nvlist_t *
855get_configs(libzfs_handle_t *hdl, pool_list_t *pl, boolean_t active_ok)
856{
857 pool_entry_t *pe;
858 vdev_entry_t *ve;
859 config_entry_t *ce;
d4ed6673 860 nvlist_t *ret = NULL, *config = NULL, *tmp = NULL, *nvtop, *nvroot;
34dc7c2f
BB
861 nvlist_t **spares, **l2cache;
862 uint_t i, nspares, nl2cache;
863 boolean_t config_seen;
864 uint64_t best_txg;
3bc7e0fb
GW
865 char *name, *hostname = NULL;
866 uint64_t guid;
34dc7c2f
BB
867 uint_t children = 0;
868 nvlist_t **child = NULL;
428870ff
BB
869 uint_t holes;
870 uint64_t *hole_array, max_id;
34dc7c2f
BB
871 uint_t c;
872 boolean_t isactive;
873 uint64_t hostid;
874 nvlist_t *nvl;
428870ff 875 boolean_t valid_top_config = B_FALSE;
34dc7c2f
BB
876
877 if (nvlist_alloc(&ret, 0, 0) != 0)
878 goto nomem;
879
880 for (pe = pl->pools; pe != NULL; pe = pe->pe_next) {
428870ff 881 uint64_t id, max_txg = 0;
34dc7c2f
BB
882
883 if (nvlist_alloc(&config, NV_UNIQUE_NAME, 0) != 0)
884 goto nomem;
885 config_seen = B_FALSE;
886
887 /*
888 * Iterate over all toplevel vdevs. Grab the pool configuration
889 * from the first one we find, and then go through the rest and
890 * add them as necessary to the 'vdevs' member of the config.
891 */
892 for (ve = pe->pe_vdevs; ve != NULL; ve = ve->ve_next) {
893
894 /*
895 * Determine the best configuration for this vdev by
896 * selecting the config with the latest transaction
897 * group.
898 */
899 best_txg = 0;
900 for (ce = ve->ve_configs; ce != NULL;
901 ce = ce->ce_next) {
902
903 if (ce->ce_txg > best_txg) {
904 tmp = ce->ce_config;
905 best_txg = ce->ce_txg;
906 }
907 }
908
428870ff
BB
909 /*
910 * We rely on the fact that the max txg for the
911 * pool will contain the most up-to-date information
912 * about the valid top-levels in the vdev namespace.
913 */
914 if (best_txg > max_txg) {
915 (void) nvlist_remove(config,
916 ZPOOL_CONFIG_VDEV_CHILDREN,
917 DATA_TYPE_UINT64);
918 (void) nvlist_remove(config,
919 ZPOOL_CONFIG_HOLE_ARRAY,
920 DATA_TYPE_UINT64_ARRAY);
921
922 max_txg = best_txg;
923 hole_array = NULL;
924 holes = 0;
925 max_id = 0;
926 valid_top_config = B_FALSE;
927
928 if (nvlist_lookup_uint64(tmp,
929 ZPOOL_CONFIG_VDEV_CHILDREN, &max_id) == 0) {
930 verify(nvlist_add_uint64(config,
931 ZPOOL_CONFIG_VDEV_CHILDREN,
932 max_id) == 0);
933 valid_top_config = B_TRUE;
934 }
935
936 if (nvlist_lookup_uint64_array(tmp,
937 ZPOOL_CONFIG_HOLE_ARRAY, &hole_array,
938 &holes) == 0) {
939 verify(nvlist_add_uint64_array(config,
940 ZPOOL_CONFIG_HOLE_ARRAY,
941 hole_array, holes) == 0);
942 }
943 }
944
34dc7c2f
BB
945 if (!config_seen) {
946 /*
947 * Copy the relevant pieces of data to the pool
948 * configuration:
949 *
950 * version
3bc7e0fb
GW
951 * pool guid
952 * name
d96eb2b1 953 * comment (if available)
3bc7e0fb 954 * pool state
34dc7c2f
BB
955 * hostid (if available)
956 * hostname (if available)
957 */
295304be 958 uint64_t state, version;
3bc7e0fb
GW
959 char *comment = NULL;
960
961 version = fnvlist_lookup_uint64(tmp,
962 ZPOOL_CONFIG_VERSION);
963 fnvlist_add_uint64(config,
964 ZPOOL_CONFIG_VERSION, version);
965 guid = fnvlist_lookup_uint64(tmp,
966 ZPOOL_CONFIG_POOL_GUID);
967 fnvlist_add_uint64(config,
968 ZPOOL_CONFIG_POOL_GUID, guid);
969 name = fnvlist_lookup_string(tmp,
970 ZPOOL_CONFIG_POOL_NAME);
971 fnvlist_add_string(config,
972 ZPOOL_CONFIG_POOL_NAME, name);
34dc7c2f 973
d96eb2b1 974 if (nvlist_lookup_string(tmp,
3bc7e0fb
GW
975 ZPOOL_CONFIG_COMMENT, &comment) == 0)
976 fnvlist_add_string(config,
977 ZPOOL_CONFIG_COMMENT, comment);
d96eb2b1 978
3bc7e0fb
GW
979 state = fnvlist_lookup_uint64(tmp,
980 ZPOOL_CONFIG_POOL_STATE);
981 fnvlist_add_uint64(config,
982 ZPOOL_CONFIG_POOL_STATE, state);
d96eb2b1 983
34dc7c2f
BB
984 hostid = 0;
985 if (nvlist_lookup_uint64(tmp,
986 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
3bc7e0fb
GW
987 fnvlist_add_uint64(config,
988 ZPOOL_CONFIG_HOSTID, hostid);
989 hostname = fnvlist_lookup_string(tmp,
990 ZPOOL_CONFIG_HOSTNAME);
991 fnvlist_add_string(config,
992 ZPOOL_CONFIG_HOSTNAME, hostname);
34dc7c2f
BB
993 }
994
995 config_seen = B_TRUE;
996 }
997
998 /*
999 * Add this top-level vdev to the child array.
1000 */
1001 verify(nvlist_lookup_nvlist(tmp,
1002 ZPOOL_CONFIG_VDEV_TREE, &nvtop) == 0);
1003 verify(nvlist_lookup_uint64(nvtop, ZPOOL_CONFIG_ID,
1004 &id) == 0);
428870ff 1005
34dc7c2f
BB
1006 if (id >= children) {
1007 nvlist_t **newchild;
1008
1009 newchild = zfs_alloc(hdl, (id + 1) *
1010 sizeof (nvlist_t *));
1011 if (newchild == NULL)
1012 goto nomem;
1013
1014 for (c = 0; c < children; c++)
1015 newchild[c] = child[c];
1016
1017 free(child);
1018 child = newchild;
1019 children = id + 1;
1020 }
1021 if (nvlist_dup(nvtop, &child[id], 0) != 0)
1022 goto nomem;
1023
1024 }
1025
428870ff
BB
1026 /*
1027 * If we have information about all the top-levels then
1028 * clean up the nvlist which we've constructed. This
1029 * means removing any extraneous devices that are
1030 * beyond the valid range or adding devices to the end
1031 * of our array which appear to be missing.
1032 */
1033 if (valid_top_config) {
1034 if (max_id < children) {
1035 for (c = max_id; c < children; c++)
1036 nvlist_free(child[c]);
1037 children = max_id;
1038 } else if (max_id > children) {
1039 nvlist_t **newchild;
1040
1041 newchild = zfs_alloc(hdl, (max_id) *
1042 sizeof (nvlist_t *));
1043 if (newchild == NULL)
1044 goto nomem;
1045
1046 for (c = 0; c < children; c++)
1047 newchild[c] = child[c];
1048
1049 free(child);
1050 child = newchild;
1051 children = max_id;
1052 }
1053 }
1054
34dc7c2f
BB
1055 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1056 &guid) == 0);
1057
428870ff
BB
1058 /*
1059 * The vdev namespace may contain holes as a result of
1060 * device removal. We must add them back into the vdev
1061 * tree before we process any missing devices.
1062 */
1063 if (holes > 0) {
1064 ASSERT(valid_top_config);
1065
1066 for (c = 0; c < children; c++) {
1067 nvlist_t *holey;
1068
1069 if (child[c] != NULL ||
1070 !vdev_is_hole(hole_array, holes, c))
1071 continue;
1072
1073 if (nvlist_alloc(&holey, NV_UNIQUE_NAME,
1074 0) != 0)
1075 goto nomem;
1076
1077 /*
1078 * Holes in the namespace are treated as
1079 * "hole" top-level vdevs and have a
1080 * special flag set on them.
1081 */
1082 if (nvlist_add_string(holey,
1083 ZPOOL_CONFIG_TYPE,
1084 VDEV_TYPE_HOLE) != 0 ||
1085 nvlist_add_uint64(holey,
1086 ZPOOL_CONFIG_ID, c) != 0 ||
1087 nvlist_add_uint64(holey,
0fdd8d64
MT
1088 ZPOOL_CONFIG_GUID, 0ULL) != 0) {
1089 nvlist_free(holey);
428870ff 1090 goto nomem;
0fdd8d64 1091 }
428870ff
BB
1092 child[c] = holey;
1093 }
1094 }
1095
34dc7c2f
BB
1096 /*
1097 * Look for any missing top-level vdevs. If this is the case,
1098 * create a faked up 'missing' vdev as a placeholder. We cannot
1099 * simply compress the child array, because the kernel performs
1100 * certain checks to make sure the vdev IDs match their location
1101 * in the configuration.
1102 */
428870ff 1103 for (c = 0; c < children; c++) {
34dc7c2f
BB
1104 if (child[c] == NULL) {
1105 nvlist_t *missing;
1106 if (nvlist_alloc(&missing, NV_UNIQUE_NAME,
1107 0) != 0)
1108 goto nomem;
1109 if (nvlist_add_string(missing,
1110 ZPOOL_CONFIG_TYPE,
1111 VDEV_TYPE_MISSING) != 0 ||
1112 nvlist_add_uint64(missing,
1113 ZPOOL_CONFIG_ID, c) != 0 ||
1114 nvlist_add_uint64(missing,
1115 ZPOOL_CONFIG_GUID, 0ULL) != 0) {
1116 nvlist_free(missing);
1117 goto nomem;
1118 }
1119 child[c] = missing;
1120 }
428870ff 1121 }
34dc7c2f
BB
1122
1123 /*
1124 * Put all of this pool's top-level vdevs into a root vdev.
1125 */
1126 if (nvlist_alloc(&nvroot, NV_UNIQUE_NAME, 0) != 0)
1127 goto nomem;
1128 if (nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
1129 VDEV_TYPE_ROOT) != 0 ||
1130 nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) != 0 ||
1131 nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, guid) != 0 ||
1132 nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
1133 child, children) != 0) {
1134 nvlist_free(nvroot);
1135 goto nomem;
1136 }
1137
1138 for (c = 0; c < children; c++)
1139 nvlist_free(child[c]);
1140 free(child);
1141 children = 0;
1142 child = NULL;
1143
1144 /*
1145 * Go through and fix up any paths and/or devids based on our
1146 * known list of vdev GUID -> path mappings.
1147 */
1148 if (fix_paths(nvroot, pl->names) != 0) {
1149 nvlist_free(nvroot);
1150 goto nomem;
1151 }
1152
1153 /*
1154 * Add the root vdev to this pool's configuration.
1155 */
1156 if (nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1157 nvroot) != 0) {
1158 nvlist_free(nvroot);
1159 goto nomem;
1160 }
1161 nvlist_free(nvroot);
1162
1163 /*
1164 * zdb uses this path to report on active pools that were
1165 * imported or created using -R.
1166 */
1167 if (active_ok)
1168 goto add_pool;
1169
1170 /*
1171 * Determine if this pool is currently active, in which case we
1172 * can't actually import it.
1173 */
1174 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1175 &name) == 0);
1176 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1177 &guid) == 0);
1178
1179 if (pool_active(hdl, name, guid, &isactive) != 0)
1180 goto error;
1181
1182 if (isactive) {
1183 nvlist_free(config);
1184 config = NULL;
1185 continue;
1186 }
1187
428870ff
BB
1188 if ((nvl = refresh_config(hdl, config)) == NULL) {
1189 nvlist_free(config);
1190 config = NULL;
1191 continue;
1192 }
34dc7c2f
BB
1193
1194 nvlist_free(config);
1195 config = nvl;
1196
1197 /*
1198 * Go through and update the paths for spares, now that we have
1199 * them.
1200 */
1201 verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1202 &nvroot) == 0);
1203 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
1204 &spares, &nspares) == 0) {
1205 for (i = 0; i < nspares; i++) {
1206 if (fix_paths(spares[i], pl->names) != 0)
1207 goto nomem;
1208 }
1209 }
1210
1211 /*
1212 * Update the paths for l2cache devices.
1213 */
1214 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
1215 &l2cache, &nl2cache) == 0) {
1216 for (i = 0; i < nl2cache; i++) {
1217 if (fix_paths(l2cache[i], pl->names) != 0)
1218 goto nomem;
1219 }
1220 }
1221
1222 /*
1223 * Restore the original information read from the actual label.
1224 */
1225 (void) nvlist_remove(config, ZPOOL_CONFIG_HOSTID,
1226 DATA_TYPE_UINT64);
1227 (void) nvlist_remove(config, ZPOOL_CONFIG_HOSTNAME,
1228 DATA_TYPE_STRING);
1229 if (hostid != 0) {
1230 verify(nvlist_add_uint64(config, ZPOOL_CONFIG_HOSTID,
1231 hostid) == 0);
1232 verify(nvlist_add_string(config, ZPOOL_CONFIG_HOSTNAME,
1233 hostname) == 0);
1234 }
1235
1236add_pool:
1237 /*
1238 * Add this pool to the list of configs.
1239 */
1240 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
1241 &name) == 0);
1242 if (nvlist_add_nvlist(ret, name, config) != 0)
1243 goto nomem;
1244
1245 nvlist_free(config);
1246 config = NULL;
1247 }
1248
1249 return (ret);
1250
1251nomem:
1252 (void) no_memory(hdl);
1253error:
1254 nvlist_free(config);
1255 nvlist_free(ret);
1256 for (c = 0; c < children; c++)
1257 nvlist_free(child[c]);
1258 free(child);
1259
1260 return (NULL);
1261}
1262
1263/*
1264 * Return the offset of the given label.
1265 */
1266static uint64_t
1267label_offset(uint64_t size, int l)
1268{
1269 ASSERT(P2PHASE_TYPED(size, sizeof (vdev_label_t), uint64_t) == 0);
1270 return (l * sizeof (vdev_label_t) + (l < VDEV_LABELS / 2 ?
1271 0 : size - VDEV_LABELS * sizeof (vdev_label_t)));
1272}
1273
1274/*
1275 * Given a file descriptor, read the label information and return an nvlist
7d90f569
BB
1276 * describing the configuration, if there is one. The number of valid
1277 * labels found will be returned in num_labels when non-NULL.
34dc7c2f
BB
1278 */
1279int
7d90f569 1280zpool_read_label(int fd, nvlist_t **config, int *num_labels)
34dc7c2f
BB
1281{
1282 struct stat64 statbuf;
7d90f569 1283 int l, count = 0;
34dc7c2f 1284 vdev_label_t *label;
7d90f569
BB
1285 nvlist_t *expected_config = NULL;
1286 uint64_t expected_guid = 0, size;
34dc7c2f
BB
1287
1288 *config = NULL;
1289
ff3510c1 1290 if (fstat64_blk(fd, &statbuf) == -1)
34dc7c2f
BB
1291 return (0);
1292 size = P2ALIGN_TYPED(statbuf.st_size, sizeof (vdev_label_t), uint64_t);
1293
1294 if ((label = malloc(sizeof (vdev_label_t))) == NULL)
1295 return (-1);
1296
1297 for (l = 0; l < VDEV_LABELS; l++) {
7d90f569
BB
1298 uint64_t state, guid, txg;
1299
b128c09f 1300 if (pread64(fd, label, sizeof (vdev_label_t),
34dc7c2f
BB
1301 label_offset(size, l)) != sizeof (vdev_label_t))
1302 continue;
1303
1304 if (nvlist_unpack(label->vl_vdev_phys.vp_nvlist,
1305 sizeof (label->vl_vdev_phys.vp_nvlist), config, 0) != 0)
1306 continue;
1307
7d90f569
BB
1308 if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_GUID,
1309 &guid) != 0 || guid == 0) {
1310 nvlist_free(*config);
1311 continue;
1312 }
1313
34dc7c2f
BB
1314 if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_STATE,
1315 &state) != 0 || state > POOL_STATE_L2CACHE) {
1316 nvlist_free(*config);
1317 continue;
1318 }
1319
1320 if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
1321 (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_TXG,
1322 &txg) != 0 || txg == 0)) {
1323 nvlist_free(*config);
1324 continue;
1325 }
1326
7d90f569
BB
1327 if (expected_guid) {
1328 if (expected_guid == guid)
1329 count++;
1330
1331 nvlist_free(*config);
1332 } else {
1333 expected_config = *config;
1334 expected_guid = guid;
1335 count++;
1336 }
34dc7c2f
BB
1337 }
1338
7d90f569
BB
1339 if (num_labels != NULL)
1340 *num_labels = count;
1341
34dc7c2f 1342 free(label);
7d90f569
BB
1343 *config = expected_config;
1344
34dc7c2f
BB
1345 return (0);
1346}
1347
519129ff
BB
1348typedef struct rdsk_node {
1349 char *rn_name;
1350 int rn_num_labels;
1351 int rn_dfd;
1352 libzfs_handle_t *rn_hdl;
1353 nvlist_t *rn_config;
1354 avl_tree_t *rn_avl;
1355 avl_node_t rn_node;
1356 boolean_t rn_nozpool;
1357} rdsk_node_t;
1358
1359static int
1360slice_cache_compare(const void *arg1, const void *arg2)
1361{
1362 const char *nm1 = ((rdsk_node_t *)arg1)->rn_name;
1363 const char *nm2 = ((rdsk_node_t *)arg2)->rn_name;
1364 char *nm1slice, *nm2slice;
1365 int rv;
1366
1367 /*
1368 * partitions one and three (slices zero and two) are the most
1369 * likely to provide results, so put those first
1370 */
1371 nm1slice = strstr(nm1, "part1");
1372 nm2slice = strstr(nm2, "part1");
1373 if (nm1slice && !nm2slice) {
1374 return (-1);
1375 }
1376 if (!nm1slice && nm2slice) {
1377 return (1);
1378 }
1379 nm1slice = strstr(nm1, "part3");
1380 nm2slice = strstr(nm2, "part3");
1381 if (nm1slice && !nm2slice) {
1382 return (-1);
1383 }
1384 if (!nm1slice && nm2slice) {
1385 return (1);
1386 }
1387
1388 rv = strcmp(nm1, nm2);
1389 if (rv == 0)
1390 return (0);
1391 return (rv > 0 ? 1 : -1);
1392}
1393
1394#ifndef __linux__
1395static void
1396check_one_slice(avl_tree_t *r, char *diskname, uint_t partno,
1397 diskaddr_t size, uint_t blksz)
1398{
1399 rdsk_node_t tmpnode;
1400 rdsk_node_t *node;
1401 char sname[MAXNAMELEN];
1402
1403 tmpnode.rn_name = &sname[0];
1404 (void) snprintf(tmpnode.rn_name, MAXNAMELEN, "%s%u",
1405 diskname, partno);
1406 /* too small to contain a zpool? */
1407 if ((size < (SPA_MINDEVSIZE / blksz)) &&
1408 (node = avl_find(r, &tmpnode, NULL)))
1409 node->rn_nozpool = B_TRUE;
1410}
1411#endif
1412
1413static void
1414nozpool_all_slices(avl_tree_t *r, const char *sname)
1415{
1416#ifndef __linux__
1417 char diskname[MAXNAMELEN];
1418 char *ptr;
1419 int i;
1420
1421 (void) strncpy(diskname, sname, MAXNAMELEN);
1422 if (((ptr = strrchr(diskname, 's')) == NULL) &&
1423 ((ptr = strrchr(diskname, 'p')) == NULL))
1424 return;
1425 ptr[0] = 's';
1426 ptr[1] = '\0';
1427 for (i = 0; i < NDKMAP; i++)
1428 check_one_slice(r, diskname, i, 0, 1);
1429 ptr[0] = 'p';
1430 for (i = 0; i <= FD_NUMPART; i++)
1431 check_one_slice(r, diskname, i, 0, 1);
1432#endif
1433}
1434
1435static void
1436check_slices(avl_tree_t *r, int fd, const char *sname)
1437{
1438#ifndef __linux__
1439 struct extvtoc vtoc;
1440 struct dk_gpt *gpt;
1441 char diskname[MAXNAMELEN];
1442 char *ptr;
1443 int i;
1444
1445 (void) strncpy(diskname, sname, MAXNAMELEN);
1446 if ((ptr = strrchr(diskname, 's')) == NULL || !isdigit(ptr[1]))
1447 return;
1448 ptr[1] = '\0';
1449
1450 if (read_extvtoc(fd, &vtoc) >= 0) {
1451 for (i = 0; i < NDKMAP; i++)
1452 check_one_slice(r, diskname, i,
1453 vtoc.v_part[i].p_size, vtoc.v_sectorsz);
1454 } else if (efi_alloc_and_read(fd, &gpt) >= 0) {
1455 /*
1456 * on x86 we'll still have leftover links that point
1457 * to slices s[9-15], so use NDKMAP instead
1458 */
1459 for (i = 0; i < NDKMAP; i++)
1460 check_one_slice(r, diskname, i,
1461 gpt->efi_parts[i].p_size, gpt->efi_lbasize);
1462 /* nodes p[1-4] are never used with EFI labels */
1463 ptr[0] = 'p';
1464 for (i = 1; i <= FD_NUMPART; i++)
1465 check_one_slice(r, diskname, i, 0, 1);
1466 efi_free(gpt);
1467 }
1468#endif
1469}
1470
8fc5674c
NB
1471static boolean_t
1472is_watchdog_dev(char *dev)
1473{
1474 /* For 'watchdog' dev */
1475 if (strcmp(dev, "watchdog") == 0)
1476 return (B_TRUE);
1477
1478 /* For 'watchdog<digit><whatever> */
1479 if (strstr(dev, "watchdog") == dev && isdigit(dev[8]))
1480 return (B_TRUE);
1481
1482 return (B_FALSE);
1483}
1484
519129ff
BB
1485static void
1486zpool_open_func(void *arg)
1487{
1488 rdsk_node_t *rn = arg;
1489 struct stat64 statbuf;
1490 nvlist_t *config;
1491 int num_labels;
1492 int fd;
1493
1494 if (rn->rn_nozpool)
1495 return;
1496#ifdef __linux__
1497 /*
1498 * Skip devices with well known prefixes there can be side effects
1499 * when opening devices which need to be avoided.
1500 *
519129ff 1501 * hpet - High Precision Event Timer
519129ff
BB
1502 * watchdog - Watchdog must be closed in a special way.
1503 */
8fc5674c
NB
1504 if ((strcmp(rn->rn_name, "hpet") == 0) ||
1505 is_watchdog_dev(rn->rn_name))
519129ff
BB
1506 return;
1507
1508 /*
1509 * Ignore failed stats. We only want regular files and block devices.
1510 */
1511 if (fstatat64(rn->rn_dfd, rn->rn_name, &statbuf, 0) != 0 ||
1512 (!S_ISREG(statbuf.st_mode) && !S_ISBLK(statbuf.st_mode)))
1513 return;
1514
1515 if ((fd = openat64(rn->rn_dfd, rn->rn_name, O_RDONLY)) < 0) {
1516 /* symlink to a device that's no longer there */
1517 if (errno == ENOENT)
1518 nozpool_all_slices(rn->rn_avl, rn->rn_name);
1519 return;
1520 }
1521#else
1522 if ((fd = openat64(rn->rn_dfd, rn->rn_name, O_RDONLY)) < 0) {
1523 /* symlink to a device that's no longer there */
1524 if (errno == ENOENT)
1525 nozpool_all_slices(rn->rn_avl, rn->rn_name);
1526 return;
1527 }
1528 /*
1529 * Ignore failed stats. We only want regular
1530 * files, character devs and block devs.
1531 */
1532 if (fstat64(fd, &statbuf) != 0 ||
1533 (!S_ISREG(statbuf.st_mode) &&
1534 !S_ISCHR(statbuf.st_mode) &&
1535 !S_ISBLK(statbuf.st_mode))) {
1536 (void) close(fd);
1537 return;
1538 }
1539#endif
1540 /* this file is too small to hold a zpool */
1541 if (S_ISREG(statbuf.st_mode) &&
1542 statbuf.st_size < SPA_MINDEVSIZE) {
1543 (void) close(fd);
1544 return;
1545 } else if (!S_ISREG(statbuf.st_mode)) {
1546 /*
1547 * Try to read the disk label first so we don't have to
1548 * open a bunch of minor nodes that can't have a zpool.
1549 */
1550 check_slices(rn->rn_avl, fd, rn->rn_name);
1551 }
1552
1553 if ((zpool_read_label(fd, &config, &num_labels)) != 0) {
1554 (void) close(fd);
1555 (void) no_memory(rn->rn_hdl);
1556 return;
1557 }
1558
1559 if (num_labels == 0) {
1560 (void) close(fd);
1561 nvlist_free(config);
1562 return;
1563 }
1564
1565 (void) close(fd);
1566
1567 rn->rn_config = config;
1568 rn->rn_num_labels = num_labels;
519129ff
BB
1569}
1570
51a3ae72
DK
1571/*
1572 * Given a file descriptor, clear (zero) the label information. This function
131cc95c
DK
1573 * is used in the appliance stack as part of the ZFS sysevent module and
1574 * to implement the "zpool labelclear" command.
51a3ae72
DK
1575 */
1576int
1577zpool_clear_label(int fd)
1578{
1579 struct stat64 statbuf;
1580 int l;
1581 vdev_label_t *label;
1582 uint64_t size;
1583
1584 if (fstat64_blk(fd, &statbuf) == -1)
1585 return (0);
1586 size = P2ALIGN_TYPED(statbuf.st_size, sizeof (vdev_label_t), uint64_t);
1587
1588 if ((label = calloc(sizeof (vdev_label_t), 1)) == NULL)
1589 return (-1);
1590
1591 for (l = 0; l < VDEV_LABELS; l++) {
1592 if (pwrite64(fd, label, sizeof (vdev_label_t),
4def05f8
RY
1593 label_offset(size, l)) != sizeof (vdev_label_t)) {
1594 free(label);
51a3ae72 1595 return (-1);
4def05f8 1596 }
51a3ae72
DK
1597 }
1598
1599 free(label);
1600 return (0);
1601}
1602
d603ed6c
BB
1603/*
1604 * Use libblkid to quickly search for zfs devices
1605 */
428870ff 1606static int
d603ed6c 1607zpool_find_import_blkid(libzfs_handle_t *hdl, pool_list_t *pools)
428870ff 1608{
d603ed6c
BB
1609 blkid_cache cache;
1610 blkid_dev_iterate iter;
1611 blkid_dev dev;
1612 const char *devname;
428870ff 1613 nvlist_t *config;
7d90f569 1614 int fd, err, num_labels;
428870ff 1615
d603ed6c
BB
1616 err = blkid_get_cache(&cache, NULL);
1617 if (err != 0) {
1618 (void) zfs_error_fmt(hdl, EZFS_BADCACHE,
1619 dgettext(TEXT_DOMAIN, "blkid_get_cache() %d"), err);
1620 goto err_blkid1;
428870ff
BB
1621 }
1622
d603ed6c
BB
1623 err = blkid_probe_all(cache);
1624 if (err != 0) {
1625 (void) zfs_error_fmt(hdl, EZFS_BADCACHE,
1626 dgettext(TEXT_DOMAIN, "blkid_probe_all() %d"), err);
1627 goto err_blkid2;
428870ff 1628 }
428870ff 1629
d603ed6c
BB
1630 iter = blkid_dev_iterate_begin(cache);
1631 if (iter == NULL) {
1632 (void) zfs_error_fmt(hdl, EZFS_BADCACHE,
1633 dgettext(TEXT_DOMAIN, "blkid_dev_iterate_begin()"));
1634 goto err_blkid2;
1635 }
428870ff 1636
1db7b9be 1637 err = blkid_dev_set_search(iter, "TYPE", "zfs_member");
d603ed6c
BB
1638 if (err != 0) {
1639 (void) zfs_error_fmt(hdl, EZFS_BADCACHE,
1640 dgettext(TEXT_DOMAIN, "blkid_dev_set_search() %d"), err);
1641 goto err_blkid3;
428870ff 1642 }
428870ff 1643
d603ed6c
BB
1644 while (blkid_dev_next(iter, &dev) == 0) {
1645 devname = blkid_dev_devname(dev);
1646 if ((fd = open64(devname, O_RDONLY)) < 0)
1647 continue;
428870ff 1648
7d90f569 1649 err = zpool_read_label(fd, &config, &num_labels);
d603ed6c 1650 (void) close(fd);
428870ff 1651
d603ed6c
BB
1652 if (err != 0) {
1653 (void) no_memory(hdl);
1654 goto err_blkid3;
1655 }
428870ff 1656
d603ed6c 1657 if (config != NULL) {
7d90f569
BB
1658 err = add_config(hdl, pools, devname, 0,
1659 num_labels, config);
d603ed6c
BB
1660 if (err != 0)
1661 goto err_blkid3;
1662 }
428870ff
BB
1663 }
1664
d603ed6c
BB
1665err_blkid3:
1666 blkid_dev_iterate_end(iter);
1667err_blkid2:
1668 blkid_put_cache(cache);
1669err_blkid1:
d1d7e268 1670 return (err);
428870ff
BB
1671}
1672
eac47204 1673char *
44867b6d
BB
1674zpool_default_import_path[DEFAULT_IMPORT_PATH_SIZE] = {
1675 "/dev/disk/by-vdev", /* Custom rules, use first if they exist */
44867b6d 1676 "/dev/mapper", /* Use multipath devices before components */
95003f70
TC
1677 "/dev/disk/by-partlabel", /* Single unique entry set by user */
1678 "/dev/disk/by-partuuid", /* Generated partition uuid */
1679 "/dev/disk/by-label", /* Custom persistent labels */
44867b6d
BB
1680 "/dev/disk/by-uuid", /* Single unique entry and persistent */
1681 "/dev/disk/by-id", /* May be multiple entries and persistent */
1682 "/dev/disk/by-path", /* Encodes physical location and persistent */
44867b6d
BB
1683 "/dev" /* UNSAFE device names will change */
1684};
1685
34dc7c2f
BB
1686/*
1687 * Given a list of directories to search, find all pools stored on disk. This
1688 * includes partial pools which are not available to import. If no args are
1689 * given (argc is 0), then the default directory (/dev/dsk) is searched.
b128c09f
BB
1690 * poolname or guid (but not both) are provided by the caller when trying
1691 * to import a specific pool.
34dc7c2f 1692 */
b128c09f 1693static nvlist_t *
428870ff 1694zpool_find_import_impl(libzfs_handle_t *hdl, importargs_t *iarg)
34dc7c2f 1695{
519129ff 1696 int i, dirs = iarg->paths;
34dc7c2f
BB
1697 struct dirent64 *dp;
1698 char path[MAXPATHLEN];
428870ff 1699 char *end, **dir = iarg->path;
34dc7c2f 1700 size_t pathleft;
519129ff 1701 nvlist_t *ret = NULL;
34dc7c2f
BB
1702 pool_list_t pools = { 0 };
1703 pool_entry_t *pe, *penext;
1704 vdev_entry_t *ve, *venext;
1705 config_entry_t *ce, *cenext;
1706 name_entry_t *ne, *nenext;
519129ff
BB
1707 avl_tree_t slice_cache;
1708 rdsk_node_t *slice;
1709 void *cookie;
d603ed6c
BB
1710
1711 verify(iarg->poolname == NULL || iarg->guid == 0);
34dc7c2f 1712
7d11e37e
BB
1713 /*
1714 * Prefer to locate pool member vdevs using libblkid. Only fall
1715 * back to legacy directory scanning when explicitly requested or
1716 * if an error is encountered when consulted the libblkid cache.
1717 */
428870ff 1718 if (dirs == 0) {
7d11e37e 1719 if (!iarg->scan && (zpool_find_import_blkid(hdl, &pools) == 0))
d603ed6c
BB
1720 goto skip_scanning;
1721
44867b6d
BB
1722 dir = zpool_default_import_path;
1723 dirs = DEFAULT_IMPORT_PATH_SIZE;
34dc7c2f
BB
1724 }
1725
1726 /*
1727 * Go through and read the label configuration information from every
1728 * possible device, organizing the information according to pool GUID
1729 * and toplevel GUID.
1730 */
428870ff 1731 for (i = 0; i < dirs; i++) {
519129ff 1732 taskq_t *t;
34dc7c2f
BB
1733 char *rdsk;
1734 int dfd;
0fdd8d64
MT
1735 boolean_t config_failed = B_FALSE;
1736 DIR *dirp;
34dc7c2f
BB
1737
1738 /* use realpath to normalize the path */
428870ff 1739 if (realpath(dir[i], path) == 0) {
44867b6d
BB
1740
1741 /* it is safe to skip missing search paths */
1742 if (errno == ENOENT)
1743 continue;
1744
1745 zfs_error_aux(hdl, strerror(errno));
34dc7c2f 1746 (void) zfs_error_fmt(hdl, EZFS_BADPATH,
428870ff 1747 dgettext(TEXT_DOMAIN, "cannot open '%s'"), dir[i]);
34dc7c2f
BB
1748 goto error;
1749 }
1750 end = &path[strlen(path)];
1751 *end++ = '/';
1752 *end = 0;
1753 pathleft = &path[sizeof (path)] - end;
1754
1755 /*
1756 * Using raw devices instead of block devices when we're
1757 * reading the labels skips a bunch of slow operations during
1758 * close(2) processing, so we replace /dev/dsk with /dev/rdsk.
1759 */
1760 if (strcmp(path, "/dev/dsk/") == 0)
1761 rdsk = "/dev/rdsk/";
1762 else
1763 rdsk = path;
1764
1765 if ((dfd = open64(rdsk, O_RDONLY)) < 0 ||
1766 (dirp = fdopendir(dfd)) == NULL) {
0fdd8d64
MT
1767 if (dfd >= 0)
1768 (void) close(dfd);
34dc7c2f
BB
1769 zfs_error_aux(hdl, strerror(errno));
1770 (void) zfs_error_fmt(hdl, EZFS_BADPATH,
1771 dgettext(TEXT_DOMAIN, "cannot open '%s'"),
1772 rdsk);
1773 goto error;
1774 }
1775
519129ff
BB
1776 avl_create(&slice_cache, slice_cache_compare,
1777 sizeof (rdsk_node_t), offsetof(rdsk_node_t, rn_node));
1778
34dc7c2f
BB
1779 /*
1780 * This is not MT-safe, but we have no MT consumers of libzfs
1781 */
1782 while ((dp = readdir64(dirp)) != NULL) {
1783 const char *name = dp->d_name;
1784 if (name[0] == '.' &&
1785 (name[1] == 0 || (name[1] == '.' && name[2] == 0)))
1786 continue;
1787
519129ff
BB
1788 slice = zfs_alloc(hdl, sizeof (rdsk_node_t));
1789 slice->rn_name = zfs_strdup(hdl, name);
1790 slice->rn_avl = &slice_cache;
1791 slice->rn_dfd = dfd;
1792 slice->rn_hdl = hdl;
1793 slice->rn_nozpool = B_FALSE;
1794 avl_add(&slice_cache, slice);
1795 }
505d9655 1796
519129ff
BB
1797 /*
1798 * create a thread pool to do all of this in parallel;
1799 * rn_nozpool is not protected, so this is racy in that
1800 * multiple tasks could decide that the same slice can
1801 * not hold a zpool, which is benign. Also choose
1802 * double the number of processors; we hold a lot of
1803 * locks in the kernel, so going beyond this doesn't
1804 * buy us much.
1805 */
519129ff
BB
1806 t = taskq_create("z_import", 2 * boot_ncpus, defclsyspri,
1807 2 * boot_ncpus, INT_MAX, TASKQ_PREPOPULATE);
1808 for (slice = avl_first(&slice_cache); slice;
1809 (slice = avl_walk(&slice_cache, slice,
1810 AVL_AFTER)))
1811 (void) taskq_dispatch(t, zpool_open_func, slice,
1812 TQ_SLEEP);
1813 taskq_wait(t);
1814 taskq_destroy(t);
519129ff
BB
1815
1816 cookie = NULL;
1817 while ((slice = avl_destroy_nodes(&slice_cache,
1818 &cookie)) != NULL) {
0fdd8d64 1819 if (slice->rn_config != NULL && !config_failed) {
519129ff 1820 nvlist_t *config = slice->rn_config;
b128c09f 1821 boolean_t matched = B_TRUE;
30b937ee 1822
519129ff
BB
1823 if (iarg->poolname != NULL) {
1824 char *pname;
b128c09f 1825
519129ff
BB
1826 matched = nvlist_lookup_string(config,
1827 ZPOOL_CONFIG_POOL_NAME,
1828 &pname) == 0 &&
1829 strcmp(iarg->poolname, pname) == 0;
428870ff 1830 } else if (iarg->guid != 0) {
b128c09f
BB
1831 uint64_t this_guid;
1832
1833 matched = nvlist_lookup_uint64(config,
1834 ZPOOL_CONFIG_POOL_GUID,
1835 &this_guid) == 0 &&
428870ff 1836 iarg->guid == this_guid;
b128c09f
BB
1837 }
1838 if (!matched) {
1839 nvlist_free(config);
0fdd8d64
MT
1840 } else {
1841 /*
1842 * use the non-raw path for the config
1843 */
1844 (void) strlcpy(end, slice->rn_name,
1845 pathleft);
1846 if (add_config(hdl, &pools, path, i+1,
1847 slice->rn_num_labels, config) != 0)
1848 config_failed = B_TRUE;
b128c09f 1849 }
34dc7c2f 1850 }
519129ff
BB
1851 free(slice->rn_name);
1852 free(slice);
34dc7c2f 1853 }
519129ff 1854 avl_destroy(&slice_cache);
34dc7c2f
BB
1855
1856 (void) closedir(dirp);
0fdd8d64
MT
1857
1858 if (config_failed)
1859 goto error;
34dc7c2f
BB
1860 }
1861
d603ed6c 1862skip_scanning:
428870ff 1863 ret = get_configs(hdl, &pools, iarg->can_be_active);
34dc7c2f
BB
1864
1865error:
1866 for (pe = pools.pools; pe != NULL; pe = penext) {
1867 penext = pe->pe_next;
1868 for (ve = pe->pe_vdevs; ve != NULL; ve = venext) {
1869 venext = ve->ve_next;
1870 for (ce = ve->ve_configs; ce != NULL; ce = cenext) {
1871 cenext = ce->ce_next;
1872 if (ce->ce_config)
1873 nvlist_free(ce->ce_config);
1874 free(ce);
1875 }
1876 free(ve);
1877 }
1878 free(pe);
1879 }
1880
1881 for (ne = pools.names; ne != NULL; ne = nenext) {
1882 nenext = ne->ne_next;
0fdd8d64 1883 free(ne->ne_name);
34dc7c2f
BB
1884 free(ne);
1885 }
1886
34dc7c2f
BB
1887 return (ret);
1888}
1889
b128c09f
BB
1890nvlist_t *
1891zpool_find_import(libzfs_handle_t *hdl, int argc, char **argv)
1892{
428870ff 1893 importargs_t iarg = { 0 };
b128c09f 1894
428870ff
BB
1895 iarg.paths = argc;
1896 iarg.path = argv;
b128c09f 1897
428870ff 1898 return (zpool_find_import_impl(hdl, &iarg));
b128c09f
BB
1899}
1900
34dc7c2f
BB
1901/*
1902 * Given a cache file, return the contents as a list of importable pools.
b128c09f
BB
1903 * poolname or guid (but not both) are provided by the caller when trying
1904 * to import a specific pool.
34dc7c2f
BB
1905 */
1906nvlist_t *
1907zpool_find_import_cached(libzfs_handle_t *hdl, const char *cachefile,
b128c09f 1908 char *poolname, uint64_t guid)
34dc7c2f
BB
1909{
1910 char *buf;
1911 int fd;
1912 struct stat64 statbuf;
1913 nvlist_t *raw, *src, *dst;
1914 nvlist_t *pools;
1915 nvpair_t *elem;
1916 char *name;
b128c09f 1917 uint64_t this_guid;
34dc7c2f
BB
1918 boolean_t active;
1919
b128c09f
BB
1920 verify(poolname == NULL || guid == 0);
1921
34dc7c2f
BB
1922 if ((fd = open(cachefile, O_RDONLY)) < 0) {
1923 zfs_error_aux(hdl, "%s", strerror(errno));
1924 (void) zfs_error(hdl, EZFS_BADCACHE,
1925 dgettext(TEXT_DOMAIN, "failed to open cache file"));
1926 return (NULL);
1927 }
1928
1929 if (fstat64(fd, &statbuf) != 0) {
1930 zfs_error_aux(hdl, "%s", strerror(errno));
1931 (void) close(fd);
1932 (void) zfs_error(hdl, EZFS_BADCACHE,
1933 dgettext(TEXT_DOMAIN, "failed to get size of cache file"));
1934 return (NULL);
1935 }
1936
1937 if ((buf = zfs_alloc(hdl, statbuf.st_size)) == NULL) {
1938 (void) close(fd);
1939 return (NULL);
1940 }
1941
1942 if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
1943 (void) close(fd);
1944 free(buf);
1945 (void) zfs_error(hdl, EZFS_BADCACHE,
1946 dgettext(TEXT_DOMAIN,
1947 "failed to read cache file contents"));
1948 return (NULL);
1949 }
1950
1951 (void) close(fd);
1952
1953 if (nvlist_unpack(buf, statbuf.st_size, &raw, 0) != 0) {
1954 free(buf);
1955 (void) zfs_error(hdl, EZFS_BADCACHE,
1956 dgettext(TEXT_DOMAIN,
1957 "invalid or corrupt cache file contents"));
1958 return (NULL);
1959 }
1960
1961 free(buf);
1962
1963 /*
1964 * Go through and get the current state of the pools and refresh their
1965 * state.
1966 */
1967 if (nvlist_alloc(&pools, 0, 0) != 0) {
1968 (void) no_memory(hdl);
1969 nvlist_free(raw);
1970 return (NULL);
1971 }
1972
1973 elem = NULL;
1974 while ((elem = nvlist_next_nvpair(raw, elem)) != NULL) {
ab2894e6 1975 src = fnvpair_value_nvlist(elem);
34dc7c2f 1976
ab2894e6 1977 name = fnvlist_lookup_string(src, ZPOOL_CONFIG_POOL_NAME);
b128c09f
BB
1978 if (poolname != NULL && strcmp(poolname, name) != 0)
1979 continue;
1980
ab2894e6
MA
1981 this_guid = fnvlist_lookup_uint64(src, ZPOOL_CONFIG_POOL_GUID);
1982 if (guid != 0 && guid != this_guid)
1983 continue;
34dc7c2f 1984
b128c09f
BB
1985 if (pool_active(hdl, name, this_guid, &active) != 0) {
1986 nvlist_free(raw);
1987 nvlist_free(pools);
1988 return (NULL);
1989 }
34dc7c2f 1990
b128c09f
BB
1991 if (active)
1992 continue;
34dc7c2f 1993
b128c09f
BB
1994 if ((dst = refresh_config(hdl, src)) == NULL) {
1995 nvlist_free(raw);
1996 nvlist_free(pools);
1997 return (NULL);
1998 }
34dc7c2f 1999
b128c09f
BB
2000 if (nvlist_add_nvlist(pools, nvpair_name(elem), dst) != 0) {
2001 (void) no_memory(hdl);
34dc7c2f 2002 nvlist_free(dst);
b128c09f
BB
2003 nvlist_free(raw);
2004 nvlist_free(pools);
2005 return (NULL);
34dc7c2f 2006 }
b128c09f 2007 nvlist_free(dst);
34dc7c2f
BB
2008 }
2009
2010 nvlist_free(raw);
2011 return (pools);
2012}
2013
428870ff
BB
2014static int
2015name_or_guid_exists(zpool_handle_t *zhp, void *data)
2016{
2017 importargs_t *import = data;
2018 int found = 0;
2019
2020 if (import->poolname != NULL) {
2021 char *pool_name;
2022
2023 verify(nvlist_lookup_string(zhp->zpool_config,
2024 ZPOOL_CONFIG_POOL_NAME, &pool_name) == 0);
2025 if (strcmp(pool_name, import->poolname) == 0)
2026 found = 1;
2027 } else {
2028 uint64_t pool_guid;
2029
2030 verify(nvlist_lookup_uint64(zhp->zpool_config,
2031 ZPOOL_CONFIG_POOL_GUID, &pool_guid) == 0);
2032 if (pool_guid == import->guid)
2033 found = 1;
2034 }
2035
2036 zpool_close(zhp);
2037 return (found);
2038}
2039
2040nvlist_t *
2041zpool_search_import(libzfs_handle_t *hdl, importargs_t *import)
2042{
2043 verify(import->poolname == NULL || import->guid == 0);
2044
2045 if (import->unique)
2046 import->exists = zpool_iter(hdl, name_or_guid_exists, import);
2047
2048 if (import->cachefile != NULL)
2049 return (zpool_find_import_cached(hdl, import->cachefile,
2050 import->poolname, import->guid));
2051
2052 return (zpool_find_import_impl(hdl, import));
2053}
34dc7c2f
BB
2054
2055boolean_t
2056find_guid(nvlist_t *nv, uint64_t guid)
2057{
2058 uint64_t tmp;
2059 nvlist_t **child;
2060 uint_t c, children;
2061
2062 verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &tmp) == 0);
2063 if (tmp == guid)
2064 return (B_TRUE);
2065
2066 if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
2067 &child, &children) == 0) {
2068 for (c = 0; c < children; c++)
2069 if (find_guid(child[c], guid))
2070 return (B_TRUE);
2071 }
2072
2073 return (B_FALSE);
2074}
2075
2076typedef struct aux_cbdata {
2077 const char *cb_type;
2078 uint64_t cb_guid;
2079 zpool_handle_t *cb_zhp;
2080} aux_cbdata_t;
2081
2082static int
2083find_aux(zpool_handle_t *zhp, void *data)
2084{
2085 aux_cbdata_t *cbp = data;
2086 nvlist_t **list;
2087 uint_t i, count;
2088 uint64_t guid;
2089 nvlist_t *nvroot;
2090
2091 verify(nvlist_lookup_nvlist(zhp->zpool_config, ZPOOL_CONFIG_VDEV_TREE,
2092 &nvroot) == 0);
2093
2094 if (nvlist_lookup_nvlist_array(nvroot, cbp->cb_type,
2095 &list, &count) == 0) {
2096 for (i = 0; i < count; i++) {
2097 verify(nvlist_lookup_uint64(list[i],
2098 ZPOOL_CONFIG_GUID, &guid) == 0);
2099 if (guid == cbp->cb_guid) {
2100 cbp->cb_zhp = zhp;
2101 return (1);
2102 }
2103 }
2104 }
2105
2106 zpool_close(zhp);
2107 return (0);
2108}
2109
2110/*
2111 * Determines if the pool is in use. If so, it returns true and the state of
2112 * the pool as well as the name of the pool. Both strings are allocated and
2113 * must be freed by the caller.
2114 */
2115int
2116zpool_in_use(libzfs_handle_t *hdl, int fd, pool_state_t *state, char **namestr,
2117 boolean_t *inuse)
2118{
2119 nvlist_t *config;
2120 char *name;
2121 boolean_t ret;
2122 uint64_t guid, vdev_guid;
2123 zpool_handle_t *zhp;
2124 nvlist_t *pool_config;
2125 uint64_t stateval, isspare;
2126 aux_cbdata_t cb = { 0 };
2127 boolean_t isactive;
2128
2129 *inuse = B_FALSE;
2130
7d90f569 2131 if (zpool_read_label(fd, &config, NULL) != 0) {
34dc7c2f
BB
2132 (void) no_memory(hdl);
2133 return (-1);
2134 }
2135
2136 if (config == NULL)
2137 return (0);
2138
2139 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
2140 &stateval) == 0);
2141 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID,
2142 &vdev_guid) == 0);
2143
2144 if (stateval != POOL_STATE_SPARE && stateval != POOL_STATE_L2CACHE) {
2145 verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
2146 &name) == 0);
2147 verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
2148 &guid) == 0);
2149 }
2150
2151 switch (stateval) {
2152 case POOL_STATE_EXPORTED:
572e2857
BB
2153 /*
2154 * A pool with an exported state may in fact be imported
2155 * read-only, so check the in-core state to see if it's
2156 * active and imported read-only. If it is, set
2157 * its state to active.
2158 */
2159 if (pool_active(hdl, name, guid, &isactive) == 0 && isactive &&
02f8fe42
JJS
2160 (zhp = zpool_open_canfail(hdl, name)) != NULL) {
2161 if (zpool_get_prop_int(zhp, ZPOOL_PROP_READONLY, NULL))
2162 stateval = POOL_STATE_ACTIVE;
2163
2164 /*
2165 * All we needed the zpool handle for is the
2166 * readonly prop check.
2167 */
2168 zpool_close(zhp);
2169 }
572e2857 2170
34dc7c2f
BB
2171 ret = B_TRUE;
2172 break;
2173
2174 case POOL_STATE_ACTIVE:
2175 /*
2176 * For an active pool, we have to determine if it's really part
2177 * of a currently active pool (in which case the pool will exist
2178 * and the guid will be the same), or whether it's part of an
2179 * active pool that was disconnected without being explicitly
2180 * exported.
2181 */
2182 if (pool_active(hdl, name, guid, &isactive) != 0) {
2183 nvlist_free(config);
2184 return (-1);
2185 }
2186
2187 if (isactive) {
2188 /*
2189 * Because the device may have been removed while
2190 * offlined, we only report it as active if the vdev is
2191 * still present in the config. Otherwise, pretend like
2192 * it's not in use.
2193 */
2194 if ((zhp = zpool_open_canfail(hdl, name)) != NULL &&
2195 (pool_config = zpool_get_config(zhp, NULL))
2196 != NULL) {
2197 nvlist_t *nvroot;
2198
2199 verify(nvlist_lookup_nvlist(pool_config,
2200 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
2201 ret = find_guid(nvroot, vdev_guid);
2202 } else {
2203 ret = B_FALSE;
2204 }
2205
2206 /*
2207 * If this is an active spare within another pool, we
2208 * treat it like an unused hot spare. This allows the
2209 * user to create a pool with a hot spare that currently
2210 * in use within another pool. Since we return B_TRUE,
2211 * libdiskmgt will continue to prevent generic consumers
2212 * from using the device.
2213 */
2214 if (ret && nvlist_lookup_uint64(config,
2215 ZPOOL_CONFIG_IS_SPARE, &isspare) == 0 && isspare)
2216 stateval = POOL_STATE_SPARE;
2217
2218 if (zhp != NULL)
2219 zpool_close(zhp);
2220 } else {
2221 stateval = POOL_STATE_POTENTIALLY_ACTIVE;
2222 ret = B_TRUE;
2223 }
2224 break;
2225
2226 case POOL_STATE_SPARE:
2227 /*
2228 * For a hot spare, it can be either definitively in use, or
2229 * potentially active. To determine if it's in use, we iterate
2230 * over all pools in the system and search for one with a spare
2231 * with a matching guid.
2232 *
2233 * Due to the shared nature of spares, we don't actually report
2234 * the potentially active case as in use. This means the user
2235 * can freely create pools on the hot spares of exported pools,
2236 * but to do otherwise makes the resulting code complicated, and
2237 * we end up having to deal with this case anyway.
2238 */
2239 cb.cb_zhp = NULL;
2240 cb.cb_guid = vdev_guid;
2241 cb.cb_type = ZPOOL_CONFIG_SPARES;
2242 if (zpool_iter(hdl, find_aux, &cb) == 1) {
2243 name = (char *)zpool_get_name(cb.cb_zhp);
0fdd8d64 2244 ret = B_TRUE;
34dc7c2f 2245 } else {
0fdd8d64 2246 ret = B_FALSE;
34dc7c2f
BB
2247 }
2248 break;
2249
2250 case POOL_STATE_L2CACHE:
2251
2252 /*
2253 * Check if any pool is currently using this l2cache device.
2254 */
2255 cb.cb_zhp = NULL;
2256 cb.cb_guid = vdev_guid;
2257 cb.cb_type = ZPOOL_CONFIG_L2CACHE;
2258 if (zpool_iter(hdl, find_aux, &cb) == 1) {
2259 name = (char *)zpool_get_name(cb.cb_zhp);
0fdd8d64 2260 ret = B_TRUE;
34dc7c2f 2261 } else {
0fdd8d64 2262 ret = B_FALSE;
34dc7c2f
BB
2263 }
2264 break;
2265
2266 default:
2267 ret = B_FALSE;
2268 }
2269
2270
2271 if (ret) {
2272 if ((*namestr = zfs_strdup(hdl, name)) == NULL) {
2273 if (cb.cb_zhp)
2274 zpool_close(cb.cb_zhp);
2275 nvlist_free(config);
2276 return (-1);
2277 }
2278 *state = (pool_state_t)stateval;
2279 }
2280
2281 if (cb.cb_zhp)
2282 zpool_close(cb.cb_zhp);
2283
2284 nvlist_free(config);
2285 *inuse = ret;
2286 return (0);
2287}