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