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