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