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