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 2015 Nexenta Systems, Inc. All rights reserved.
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
25  * Copyright 2015 RackTop Systems.
26  * Copyright (c) 2016, Intel Corporation.
27  * Copyright (c) 2021, Colm Buckley <[email protected]>
28  */
29 
30 /*
31  * Pool import support functions.
32  *
33  * Used by zpool, ztest, zdb, and zhack to locate importable configs. Since
34  * these commands are expected to run in the global zone, we can assume
35  * that the devices are all readable when called.
36  *
37  * To import a pool, we rely on reading the configuration information from the
38  * ZFS label of each device.  If we successfully read the label, then we
39  * organize the configuration information in the following hierarchy:
40  *
41  *	pool guid -> toplevel vdev guid -> label txg
42  *
43  * Duplicate entries matching this same tuple will be discarded.  Once we have
44  * examined every device, we pick the best label txg config for each toplevel
45  * vdev.  We then arrange these toplevel vdevs into a complete pool config, and
46  * update any paths that have changed.  Finally, we attempt to import the pool
47  * using our derived config, and record the results.
48  */
49 
50 #include <aio.h>
51 #include <ctype.h>
52 #include <dirent.h>
53 #include <errno.h>
54 #include <libintl.h>
55 #include <libgen.h>
56 #include <stddef.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <sys/stat.h>
60 #include <unistd.h>
61 #include <fcntl.h>
62 #include <sys/dktp/fdisk.h>
63 #include <sys/vdev_impl.h>
64 #include <sys/fs/zfs.h>
65 
66 #include <thread_pool.h>
67 #include <libzutil.h>
68 #include <libnvpair.h>
69 
70 #include "zutil_import.h"
71 
72 /*PRINTFLIKE2*/
73 static void
zutil_error_aux(libpc_handle_t * hdl,const char * fmt,...)74 zutil_error_aux(libpc_handle_t *hdl, const char *fmt, ...)
75 {
76 	va_list ap;
77 
78 	va_start(ap, fmt);
79 
80 	(void) vsnprintf(hdl->lpc_desc, sizeof (hdl->lpc_desc), fmt, ap);
81 	hdl->lpc_desc_active = B_TRUE;
82 
83 	va_end(ap);
84 }
85 
86 static void
zutil_verror(libpc_handle_t * hdl,const char * error,const char * fmt,va_list ap)87 zutil_verror(libpc_handle_t *hdl, const char *error, const char *fmt,
88     va_list ap)
89 {
90 	char action[1024];
91 
92 	(void) vsnprintf(action, sizeof (action), fmt, ap);
93 
94 	if (hdl->lpc_desc_active)
95 		hdl->lpc_desc_active = B_FALSE;
96 	else
97 		hdl->lpc_desc[0] = '\0';
98 
99 	if (hdl->lpc_printerr) {
100 		if (hdl->lpc_desc[0] != '\0')
101 			error = hdl->lpc_desc;
102 
103 		(void) fprintf(stderr, "%s: %s\n", action, error);
104 	}
105 }
106 
107 /*PRINTFLIKE3*/
108 static int
zutil_error_fmt(libpc_handle_t * hdl,const char * error,const char * fmt,...)109 zutil_error_fmt(libpc_handle_t *hdl, const char *error, const char *fmt, ...)
110 {
111 	va_list ap;
112 
113 	va_start(ap, fmt);
114 
115 	zutil_verror(hdl, error, fmt, ap);
116 
117 	va_end(ap);
118 
119 	return (-1);
120 }
121 
122 static int
zutil_error(libpc_handle_t * hdl,const char * error,const char * msg)123 zutil_error(libpc_handle_t *hdl, const char *error, const char *msg)
124 {
125 	return (zutil_error_fmt(hdl, error, "%s", msg));
126 }
127 
128 static int
zutil_no_memory(libpc_handle_t * hdl)129 zutil_no_memory(libpc_handle_t *hdl)
130 {
131 	zutil_error(hdl, EZFS_NOMEM, "internal error");
132 	exit(1);
133 }
134 
135 void *
zutil_alloc(libpc_handle_t * hdl,size_t size)136 zutil_alloc(libpc_handle_t *hdl, size_t size)
137 {
138 	void *data;
139 
140 	if ((data = calloc(1, size)) == NULL)
141 		(void) zutil_no_memory(hdl);
142 
143 	return (data);
144 }
145 
146 char *
zutil_strdup(libpc_handle_t * hdl,const char * str)147 zutil_strdup(libpc_handle_t *hdl, const char *str)
148 {
149 	char *ret;
150 
151 	if ((ret = strdup(str)) == NULL)
152 		(void) zutil_no_memory(hdl);
153 
154 	return (ret);
155 }
156 
157 /*
158  * Intermediate structures used to gather configuration information.
159  */
160 typedef struct config_entry {
161 	uint64_t		ce_txg;
162 	nvlist_t		*ce_config;
163 	struct config_entry	*ce_next;
164 } config_entry_t;
165 
166 typedef struct vdev_entry {
167 	uint64_t		ve_guid;
168 	config_entry_t		*ve_configs;
169 	struct vdev_entry	*ve_next;
170 } vdev_entry_t;
171 
172 typedef struct pool_entry {
173 	uint64_t		pe_guid;
174 	vdev_entry_t		*pe_vdevs;
175 	struct pool_entry	*pe_next;
176 } pool_entry_t;
177 
178 typedef struct name_entry {
179 	char			*ne_name;
180 	uint64_t		ne_guid;
181 	uint64_t		ne_order;
182 	uint64_t		ne_num_labels;
183 	struct name_entry	*ne_next;
184 } name_entry_t;
185 
186 typedef struct pool_list {
187 	pool_entry_t		*pools;
188 	name_entry_t		*names;
189 } pool_list_t;
190 
191 /*
192  * Go through and fix up any path and/or devid information for the given vdev
193  * configuration.
194  */
195 static int
fix_paths(libpc_handle_t * hdl,nvlist_t * nv,name_entry_t * names)196 fix_paths(libpc_handle_t *hdl, nvlist_t *nv, name_entry_t *names)
197 {
198 	nvlist_t **child;
199 	uint_t c, children;
200 	uint64_t guid;
201 	name_entry_t *ne, *best;
202 	char *path;
203 
204 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
205 	    &child, &children) == 0) {
206 		for (c = 0; c < children; c++)
207 			if (fix_paths(hdl, child[c], names) != 0)
208 				return (-1);
209 		return (0);
210 	}
211 
212 	/*
213 	 * This is a leaf (file or disk) vdev.  In either case, go through
214 	 * the name list and see if we find a matching guid.  If so, replace
215 	 * the path and see if we can calculate a new devid.
216 	 *
217 	 * There may be multiple names associated with a particular guid, in
218 	 * which case we have overlapping partitions or multiple paths to the
219 	 * same disk.  In this case we prefer to use the path name which
220 	 * matches the ZPOOL_CONFIG_PATH.  If no matching entry is found we
221 	 * use the lowest order device which corresponds to the first match
222 	 * while traversing the ZPOOL_IMPORT_PATH search path.
223 	 */
224 	verify(nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) == 0);
225 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) != 0)
226 		path = NULL;
227 
228 	best = NULL;
229 	for (ne = names; ne != NULL; ne = ne->ne_next) {
230 		if (ne->ne_guid == guid) {
231 			if (path == NULL) {
232 				best = ne;
233 				break;
234 			}
235 
236 			if ((strlen(path) == strlen(ne->ne_name)) &&
237 			    strncmp(path, ne->ne_name, strlen(path)) == 0) {
238 				best = ne;
239 				break;
240 			}
241 
242 			if (best == NULL) {
243 				best = ne;
244 				continue;
245 			}
246 
247 			/* Prefer paths with move vdev labels. */
248 			if (ne->ne_num_labels > best->ne_num_labels) {
249 				best = ne;
250 				continue;
251 			}
252 
253 			/* Prefer paths earlier in the search order. */
254 			if (ne->ne_num_labels == best->ne_num_labels &&
255 			    ne->ne_order < best->ne_order) {
256 				best = ne;
257 				continue;
258 			}
259 		}
260 	}
261 
262 	if (best == NULL)
263 		return (0);
264 
265 	if (nvlist_add_string(nv, ZPOOL_CONFIG_PATH, best->ne_name) != 0)
266 		return (-1);
267 
268 	update_vdev_config_dev_strs(nv);
269 
270 	return (0);
271 }
272 
273 /*
274  * Add the given configuration to the list of known devices.
275  */
276 static int
add_config(libpc_handle_t * hdl,pool_list_t * pl,const char * path,int order,int num_labels,nvlist_t * config)277 add_config(libpc_handle_t *hdl, pool_list_t *pl, const char *path,
278     int order, int num_labels, nvlist_t *config)
279 {
280 	uint64_t pool_guid, vdev_guid, top_guid, txg, state;
281 	pool_entry_t *pe;
282 	vdev_entry_t *ve;
283 	config_entry_t *ce;
284 	name_entry_t *ne;
285 
286 	/*
287 	 * If this is a hot spare not currently in use or level 2 cache
288 	 * device, add it to the list of names to translate, but don't do
289 	 * anything else.
290 	 */
291 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_STATE,
292 	    &state) == 0 &&
293 	    (state == POOL_STATE_SPARE || state == POOL_STATE_L2CACHE) &&
294 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, &vdev_guid) == 0) {
295 		if ((ne = zutil_alloc(hdl, sizeof (name_entry_t))) == NULL)
296 			return (-1);
297 
298 		if ((ne->ne_name = zutil_strdup(hdl, path)) == NULL) {
299 			free(ne);
300 			return (-1);
301 		}
302 		ne->ne_guid = vdev_guid;
303 		ne->ne_order = order;
304 		ne->ne_num_labels = num_labels;
305 		ne->ne_next = pl->names;
306 		pl->names = ne;
307 
308 		return (0);
309 	}
310 
311 	/*
312 	 * If we have a valid config but cannot read any of these fields, then
313 	 * it means we have a half-initialized label.  In vdev_label_init()
314 	 * we write a label with txg == 0 so that we can identify the device
315 	 * in case the user refers to the same disk later on.  If we fail to
316 	 * create the pool, we'll be left with a label in this state
317 	 * which should not be considered part of a valid pool.
318 	 */
319 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
320 	    &pool_guid) != 0 ||
321 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID,
322 	    &vdev_guid) != 0 ||
323 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_TOP_GUID,
324 	    &top_guid) != 0 ||
325 	    nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
326 	    &txg) != 0 || txg == 0) {
327 		return (0);
328 	}
329 
330 	/*
331 	 * First, see if we know about this pool.  If not, then add it to the
332 	 * list of known pools.
333 	 */
334 	for (pe = pl->pools; pe != NULL; pe = pe->pe_next) {
335 		if (pe->pe_guid == pool_guid)
336 			break;
337 	}
338 
339 	if (pe == NULL) {
340 		if ((pe = zutil_alloc(hdl, sizeof (pool_entry_t))) == NULL) {
341 			return (-1);
342 		}
343 		pe->pe_guid = pool_guid;
344 		pe->pe_next = pl->pools;
345 		pl->pools = pe;
346 	}
347 
348 	/*
349 	 * Second, see if we know about this toplevel vdev.  Add it if its
350 	 * missing.
351 	 */
352 	for (ve = pe->pe_vdevs; ve != NULL; ve = ve->ve_next) {
353 		if (ve->ve_guid == top_guid)
354 			break;
355 	}
356 
357 	if (ve == NULL) {
358 		if ((ve = zutil_alloc(hdl, sizeof (vdev_entry_t))) == NULL) {
359 			return (-1);
360 		}
361 		ve->ve_guid = top_guid;
362 		ve->ve_next = pe->pe_vdevs;
363 		pe->pe_vdevs = ve;
364 	}
365 
366 	/*
367 	 * Third, see if we have a config with a matching transaction group.  If
368 	 * so, then we do nothing.  Otherwise, add it to the list of known
369 	 * configs.
370 	 */
371 	for (ce = ve->ve_configs; ce != NULL; ce = ce->ce_next) {
372 		if (ce->ce_txg == txg)
373 			break;
374 	}
375 
376 	if (ce == NULL) {
377 		if ((ce = zutil_alloc(hdl, sizeof (config_entry_t))) == NULL) {
378 			return (-1);
379 		}
380 		ce->ce_txg = txg;
381 		ce->ce_config = fnvlist_dup(config);
382 		ce->ce_next = ve->ve_configs;
383 		ve->ve_configs = ce;
384 	}
385 
386 	/*
387 	 * At this point we've successfully added our config to the list of
388 	 * known configs.  The last thing to do is add the vdev guid -> path
389 	 * mappings so that we can fix up the configuration as necessary before
390 	 * doing the import.
391 	 */
392 	if ((ne = zutil_alloc(hdl, sizeof (name_entry_t))) == NULL)
393 		return (-1);
394 
395 	if ((ne->ne_name = zutil_strdup(hdl, path)) == NULL) {
396 		free(ne);
397 		return (-1);
398 	}
399 
400 	ne->ne_guid = vdev_guid;
401 	ne->ne_order = order;
402 	ne->ne_num_labels = num_labels;
403 	ne->ne_next = pl->names;
404 	pl->names = ne;
405 
406 	return (0);
407 }
408 
409 static int
zutil_pool_active(libpc_handle_t * hdl,const char * name,uint64_t guid,boolean_t * isactive)410 zutil_pool_active(libpc_handle_t *hdl, const char *name, uint64_t guid,
411     boolean_t *isactive)
412 {
413 	ASSERT(hdl->lpc_ops->pco_pool_active != NULL);
414 
415 	int error = hdl->lpc_ops->pco_pool_active(hdl->lpc_lib_handle, name,
416 	    guid, isactive);
417 
418 	return (error);
419 }
420 
421 static nvlist_t *
zutil_refresh_config(libpc_handle_t * hdl,nvlist_t * tryconfig)422 zutil_refresh_config(libpc_handle_t *hdl, nvlist_t *tryconfig)
423 {
424 	ASSERT(hdl->lpc_ops->pco_refresh_config != NULL);
425 
426 	return (hdl->lpc_ops->pco_refresh_config(hdl->lpc_lib_handle,
427 	    tryconfig));
428 }
429 
430 /*
431  * Determine if the vdev id is a hole in the namespace.
432  */
433 static boolean_t
vdev_is_hole(uint64_t * hole_array,uint_t holes,uint_t id)434 vdev_is_hole(uint64_t *hole_array, uint_t holes, uint_t id)
435 {
436 	int c;
437 
438 	for (c = 0; c < holes; c++) {
439 
440 		/* Top-level is a hole */
441 		if (hole_array[c] == id)
442 			return (B_TRUE);
443 	}
444 	return (B_FALSE);
445 }
446 
447 /*
448  * Convert our list of pools into the definitive set of configurations.  We
449  * start by picking the best config for each toplevel vdev.  Once that's done,
450  * we assemble the toplevel vdevs into a full config for the pool.  We make a
451  * pass to fix up any incorrect paths, and then add it to the main list to
452  * return to the user.
453  */
454 static nvlist_t *
get_configs(libpc_handle_t * hdl,pool_list_t * pl,boolean_t active_ok,nvlist_t * policy)455 get_configs(libpc_handle_t *hdl, pool_list_t *pl, boolean_t active_ok,
456     nvlist_t *policy)
457 {
458 	pool_entry_t *pe;
459 	vdev_entry_t *ve;
460 	config_entry_t *ce;
461 	nvlist_t *ret = NULL, *config = NULL, *tmp = NULL, *nvtop, *nvroot;
462 	nvlist_t **spares, **l2cache;
463 	uint_t i, nspares, nl2cache;
464 	boolean_t config_seen;
465 	uint64_t best_txg;
466 	char *name, *hostname = NULL;
467 	uint64_t guid;
468 	uint_t children = 0;
469 	nvlist_t **child = NULL;
470 	uint_t holes;
471 	uint64_t *hole_array, max_id;
472 	uint_t c;
473 	boolean_t isactive;
474 	uint64_t hostid;
475 	nvlist_t *nvl;
476 	boolean_t valid_top_config = B_FALSE;
477 
478 	if (nvlist_alloc(&ret, 0, 0) != 0)
479 		goto nomem;
480 
481 	for (pe = pl->pools; pe != NULL; pe = pe->pe_next) {
482 		uint64_t id, max_txg = 0;
483 
484 		if (nvlist_alloc(&config, NV_UNIQUE_NAME, 0) != 0)
485 			goto nomem;
486 		config_seen = B_FALSE;
487 
488 		/*
489 		 * Iterate over all toplevel vdevs.  Grab the pool configuration
490 		 * from the first one we find, and then go through the rest and
491 		 * add them as necessary to the 'vdevs' member of the config.
492 		 */
493 		for (ve = pe->pe_vdevs; ve != NULL; ve = ve->ve_next) {
494 
495 			/*
496 			 * Determine the best configuration for this vdev by
497 			 * selecting the config with the latest transaction
498 			 * group.
499 			 */
500 			best_txg = 0;
501 			for (ce = ve->ve_configs; ce != NULL;
502 			    ce = ce->ce_next) {
503 
504 				if (ce->ce_txg > best_txg) {
505 					tmp = ce->ce_config;
506 					best_txg = ce->ce_txg;
507 				}
508 			}
509 
510 			/*
511 			 * We rely on the fact that the max txg for the
512 			 * pool will contain the most up-to-date information
513 			 * about the valid top-levels in the vdev namespace.
514 			 */
515 			if (best_txg > max_txg) {
516 				(void) nvlist_remove(config,
517 				    ZPOOL_CONFIG_VDEV_CHILDREN,
518 				    DATA_TYPE_UINT64);
519 				(void) nvlist_remove(config,
520 				    ZPOOL_CONFIG_HOLE_ARRAY,
521 				    DATA_TYPE_UINT64_ARRAY);
522 
523 				max_txg = best_txg;
524 				hole_array = NULL;
525 				holes = 0;
526 				max_id = 0;
527 				valid_top_config = B_FALSE;
528 
529 				if (nvlist_lookup_uint64(tmp,
530 				    ZPOOL_CONFIG_VDEV_CHILDREN, &max_id) == 0) {
531 					verify(nvlist_add_uint64(config,
532 					    ZPOOL_CONFIG_VDEV_CHILDREN,
533 					    max_id) == 0);
534 					valid_top_config = B_TRUE;
535 				}
536 
537 				if (nvlist_lookup_uint64_array(tmp,
538 				    ZPOOL_CONFIG_HOLE_ARRAY, &hole_array,
539 				    &holes) == 0) {
540 					verify(nvlist_add_uint64_array(config,
541 					    ZPOOL_CONFIG_HOLE_ARRAY,
542 					    hole_array, holes) == 0);
543 				}
544 			}
545 
546 			if (!config_seen) {
547 				/*
548 				 * Copy the relevant pieces of data to the pool
549 				 * configuration:
550 				 *
551 				 *	version
552 				 *	pool guid
553 				 *	name
554 				 *	comment (if available)
555 				 *	compatibility features (if available)
556 				 *	pool state
557 				 *	hostid (if available)
558 				 *	hostname (if available)
559 				 */
560 				uint64_t state, version;
561 				char *comment = NULL;
562 				char *compatibility = NULL;
563 
564 				version = fnvlist_lookup_uint64(tmp,
565 				    ZPOOL_CONFIG_VERSION);
566 				fnvlist_add_uint64(config,
567 				    ZPOOL_CONFIG_VERSION, version);
568 				guid = fnvlist_lookup_uint64(tmp,
569 				    ZPOOL_CONFIG_POOL_GUID);
570 				fnvlist_add_uint64(config,
571 				    ZPOOL_CONFIG_POOL_GUID, guid);
572 				name = fnvlist_lookup_string(tmp,
573 				    ZPOOL_CONFIG_POOL_NAME);
574 				fnvlist_add_string(config,
575 				    ZPOOL_CONFIG_POOL_NAME, name);
576 
577 				if (nvlist_lookup_string(tmp,
578 				    ZPOOL_CONFIG_COMMENT, &comment) == 0)
579 					fnvlist_add_string(config,
580 					    ZPOOL_CONFIG_COMMENT, comment);
581 
582 				if (nvlist_lookup_string(tmp,
583 				    ZPOOL_CONFIG_COMPATIBILITY,
584 				    &compatibility) == 0)
585 					fnvlist_add_string(config,
586 					    ZPOOL_CONFIG_COMPATIBILITY,
587 					    compatibility);
588 
589 				state = fnvlist_lookup_uint64(tmp,
590 				    ZPOOL_CONFIG_POOL_STATE);
591 				fnvlist_add_uint64(config,
592 				    ZPOOL_CONFIG_POOL_STATE, state);
593 
594 				hostid = 0;
595 				if (nvlist_lookup_uint64(tmp,
596 				    ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
597 					fnvlist_add_uint64(config,
598 					    ZPOOL_CONFIG_HOSTID, hostid);
599 					hostname = fnvlist_lookup_string(tmp,
600 					    ZPOOL_CONFIG_HOSTNAME);
601 					fnvlist_add_string(config,
602 					    ZPOOL_CONFIG_HOSTNAME, hostname);
603 				}
604 
605 				config_seen = B_TRUE;
606 			}
607 
608 			/*
609 			 * Add this top-level vdev to the child array.
610 			 */
611 			verify(nvlist_lookup_nvlist(tmp,
612 			    ZPOOL_CONFIG_VDEV_TREE, &nvtop) == 0);
613 			verify(nvlist_lookup_uint64(nvtop, ZPOOL_CONFIG_ID,
614 			    &id) == 0);
615 
616 			if (id >= children) {
617 				nvlist_t **newchild;
618 
619 				newchild = zutil_alloc(hdl, (id + 1) *
620 				    sizeof (nvlist_t *));
621 				if (newchild == NULL)
622 					goto nomem;
623 
624 				for (c = 0; c < children; c++)
625 					newchild[c] = child[c];
626 
627 				free(child);
628 				child = newchild;
629 				children = id + 1;
630 			}
631 			if (nvlist_dup(nvtop, &child[id], 0) != 0)
632 				goto nomem;
633 
634 		}
635 
636 		/*
637 		 * If we have information about all the top-levels then
638 		 * clean up the nvlist which we've constructed. This
639 		 * means removing any extraneous devices that are
640 		 * beyond the valid range or adding devices to the end
641 		 * of our array which appear to be missing.
642 		 */
643 		if (valid_top_config) {
644 			if (max_id < children) {
645 				for (c = max_id; c < children; c++)
646 					nvlist_free(child[c]);
647 				children = max_id;
648 			} else if (max_id > children) {
649 				nvlist_t **newchild;
650 
651 				newchild = zutil_alloc(hdl, (max_id) *
652 				    sizeof (nvlist_t *));
653 				if (newchild == NULL)
654 					goto nomem;
655 
656 				for (c = 0; c < children; c++)
657 					newchild[c] = child[c];
658 
659 				free(child);
660 				child = newchild;
661 				children = max_id;
662 			}
663 		}
664 
665 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
666 		    &guid) == 0);
667 
668 		/*
669 		 * The vdev namespace may contain holes as a result of
670 		 * device removal. We must add them back into the vdev
671 		 * tree before we process any missing devices.
672 		 */
673 		if (holes > 0) {
674 			ASSERT(valid_top_config);
675 
676 			for (c = 0; c < children; c++) {
677 				nvlist_t *holey;
678 
679 				if (child[c] != NULL ||
680 				    !vdev_is_hole(hole_array, holes, c))
681 					continue;
682 
683 				if (nvlist_alloc(&holey, NV_UNIQUE_NAME,
684 				    0) != 0)
685 					goto nomem;
686 
687 				/*
688 				 * Holes in the namespace are treated as
689 				 * "hole" top-level vdevs and have a
690 				 * special flag set on them.
691 				 */
692 				if (nvlist_add_string(holey,
693 				    ZPOOL_CONFIG_TYPE,
694 				    VDEV_TYPE_HOLE) != 0 ||
695 				    nvlist_add_uint64(holey,
696 				    ZPOOL_CONFIG_ID, c) != 0 ||
697 				    nvlist_add_uint64(holey,
698 				    ZPOOL_CONFIG_GUID, 0ULL) != 0) {
699 					nvlist_free(holey);
700 					goto nomem;
701 				}
702 				child[c] = holey;
703 			}
704 		}
705 
706 		/*
707 		 * Look for any missing top-level vdevs.  If this is the case,
708 		 * create a faked up 'missing' vdev as a placeholder.  We cannot
709 		 * simply compress the child array, because the kernel performs
710 		 * certain checks to make sure the vdev IDs match their location
711 		 * in the configuration.
712 		 */
713 		for (c = 0; c < children; c++) {
714 			if (child[c] == NULL) {
715 				nvlist_t *missing;
716 				if (nvlist_alloc(&missing, NV_UNIQUE_NAME,
717 				    0) != 0)
718 					goto nomem;
719 				if (nvlist_add_string(missing,
720 				    ZPOOL_CONFIG_TYPE,
721 				    VDEV_TYPE_MISSING) != 0 ||
722 				    nvlist_add_uint64(missing,
723 				    ZPOOL_CONFIG_ID, c) != 0 ||
724 				    nvlist_add_uint64(missing,
725 				    ZPOOL_CONFIG_GUID, 0ULL) != 0) {
726 					nvlist_free(missing);
727 					goto nomem;
728 				}
729 				child[c] = missing;
730 			}
731 		}
732 
733 		/*
734 		 * Put all of this pool's top-level vdevs into a root vdev.
735 		 */
736 		if (nvlist_alloc(&nvroot, NV_UNIQUE_NAME, 0) != 0)
737 			goto nomem;
738 		if (nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
739 		    VDEV_TYPE_ROOT) != 0 ||
740 		    nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) != 0 ||
741 		    nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, guid) != 0 ||
742 		    nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
743 		    child, children) != 0) {
744 			nvlist_free(nvroot);
745 			goto nomem;
746 		}
747 
748 		for (c = 0; c < children; c++)
749 			nvlist_free(child[c]);
750 		free(child);
751 		children = 0;
752 		child = NULL;
753 
754 		/*
755 		 * Go through and fix up any paths and/or devids based on our
756 		 * known list of vdev GUID -> path mappings.
757 		 */
758 		if (fix_paths(hdl, nvroot, pl->names) != 0) {
759 			nvlist_free(nvroot);
760 			goto nomem;
761 		}
762 
763 		/*
764 		 * Add the root vdev to this pool's configuration.
765 		 */
766 		if (nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
767 		    nvroot) != 0) {
768 			nvlist_free(nvroot);
769 			goto nomem;
770 		}
771 		nvlist_free(nvroot);
772 
773 		/*
774 		 * zdb uses this path to report on active pools that were
775 		 * imported or created using -R.
776 		 */
777 		if (active_ok)
778 			goto add_pool;
779 
780 		/*
781 		 * Determine if this pool is currently active, in which case we
782 		 * can't actually import it.
783 		 */
784 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
785 		    &name) == 0);
786 		verify(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
787 		    &guid) == 0);
788 
789 		if (zutil_pool_active(hdl, name, guid, &isactive) != 0)
790 			goto error;
791 
792 		if (isactive) {
793 			nvlist_free(config);
794 			config = NULL;
795 			continue;
796 		}
797 
798 		if (policy != NULL) {
799 			if (nvlist_add_nvlist(config, ZPOOL_LOAD_POLICY,
800 			    policy) != 0)
801 				goto nomem;
802 		}
803 
804 		if ((nvl = zutil_refresh_config(hdl, config)) == NULL) {
805 			nvlist_free(config);
806 			config = NULL;
807 			continue;
808 		}
809 
810 		nvlist_free(config);
811 		config = nvl;
812 
813 		/*
814 		 * Go through and update the paths for spares, now that we have
815 		 * them.
816 		 */
817 		verify(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
818 		    &nvroot) == 0);
819 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
820 		    &spares, &nspares) == 0) {
821 			for (i = 0; i < nspares; i++) {
822 				if (fix_paths(hdl, spares[i], pl->names) != 0)
823 					goto nomem;
824 			}
825 		}
826 
827 		/*
828 		 * Update the paths for l2cache devices.
829 		 */
830 		if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
831 		    &l2cache, &nl2cache) == 0) {
832 			for (i = 0; i < nl2cache; i++) {
833 				if (fix_paths(hdl, l2cache[i], pl->names) != 0)
834 					goto nomem;
835 			}
836 		}
837 
838 		/*
839 		 * Restore the original information read from the actual label.
840 		 */
841 		(void) nvlist_remove(config, ZPOOL_CONFIG_HOSTID,
842 		    DATA_TYPE_UINT64);
843 		(void) nvlist_remove(config, ZPOOL_CONFIG_HOSTNAME,
844 		    DATA_TYPE_STRING);
845 		if (hostid != 0) {
846 			verify(nvlist_add_uint64(config, ZPOOL_CONFIG_HOSTID,
847 			    hostid) == 0);
848 			verify(nvlist_add_string(config, ZPOOL_CONFIG_HOSTNAME,
849 			    hostname) == 0);
850 		}
851 
852 add_pool:
853 		/*
854 		 * Add this pool to the list of configs.
855 		 */
856 		verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
857 		    &name) == 0);
858 
859 		if (nvlist_add_nvlist(ret, name, config) != 0)
860 			goto nomem;
861 
862 		nvlist_free(config);
863 		config = NULL;
864 	}
865 
866 	return (ret);
867 
868 nomem:
869 	(void) zutil_no_memory(hdl);
870 error:
871 	nvlist_free(config);
872 	nvlist_free(ret);
873 	for (c = 0; c < children; c++)
874 		nvlist_free(child[c]);
875 	free(child);
876 
877 	return (NULL);
878 }
879 
880 /*
881  * Return the offset of the given label.
882  */
883 static uint64_t
label_offset(uint64_t size,int l)884 label_offset(uint64_t size, int l)
885 {
886 	ASSERT(P2PHASE_TYPED(size, sizeof (vdev_label_t), uint64_t) == 0);
887 	return (l * sizeof (vdev_label_t) + (l < VDEV_LABELS / 2 ?
888 	    0 : size - VDEV_LABELS * sizeof (vdev_label_t)));
889 }
890 
891 /*
892  * The same description applies as to zpool_read_label below,
893  * except here we do it without aio, presumably because an aio call
894  * errored out in a way we think not using it could circumvent.
895  */
896 static int
zpool_read_label_slow(int fd,nvlist_t ** config,int * num_labels)897 zpool_read_label_slow(int fd, nvlist_t **config, int *num_labels)
898 {
899 	struct stat64 statbuf;
900 	int l, count = 0;
901 	vdev_phys_t *label;
902 	nvlist_t *expected_config = NULL;
903 	uint64_t expected_guid = 0, size;
904 	int error;
905 
906 	*config = NULL;
907 
908 	if (fstat64_blk(fd, &statbuf) == -1)
909 		return (0);
910 	size = P2ALIGN_TYPED(statbuf.st_size, sizeof (vdev_label_t), uint64_t);
911 
912 	error = posix_memalign((void **)&label, PAGESIZE, sizeof (*label));
913 	if (error)
914 		return (-1);
915 
916 	for (l = 0; l < VDEV_LABELS; l++) {
917 		uint64_t state, guid, txg;
918 		off_t offset = label_offset(size, l) + VDEV_SKIP_SIZE;
919 
920 		if (pread64(fd, label, sizeof (vdev_phys_t),
921 		    offset) != sizeof (vdev_phys_t))
922 			continue;
923 
924 		if (nvlist_unpack(label->vp_nvlist,
925 		    sizeof (label->vp_nvlist), config, 0) != 0)
926 			continue;
927 
928 		if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_GUID,
929 		    &guid) != 0 || guid == 0) {
930 			nvlist_free(*config);
931 			continue;
932 		}
933 
934 		if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_STATE,
935 		    &state) != 0 || state > POOL_STATE_L2CACHE) {
936 			nvlist_free(*config);
937 			continue;
938 		}
939 
940 		if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
941 		    (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_TXG,
942 		    &txg) != 0 || txg == 0)) {
943 			nvlist_free(*config);
944 			continue;
945 		}
946 
947 		if (expected_guid) {
948 			if (expected_guid == guid)
949 				count++;
950 
951 			nvlist_free(*config);
952 		} else {
953 			expected_config = *config;
954 			expected_guid = guid;
955 			count++;
956 		}
957 	}
958 
959 	if (num_labels != NULL)
960 		*num_labels = count;
961 
962 	free(label);
963 	*config = expected_config;
964 
965 	return (0);
966 }
967 
968 /*
969  * Given a file descriptor, read the label information and return an nvlist
970  * describing the configuration, if there is one.  The number of valid
971  * labels found will be returned in num_labels when non-NULL.
972  */
973 int
zpool_read_label(int fd,nvlist_t ** config,int * num_labels)974 zpool_read_label(int fd, nvlist_t **config, int *num_labels)
975 {
976 	struct stat64 statbuf;
977 	struct aiocb aiocbs[VDEV_LABELS];
978 	struct aiocb *aiocbps[VDEV_LABELS];
979 	vdev_phys_t *labels;
980 	nvlist_t *expected_config = NULL;
981 	uint64_t expected_guid = 0, size;
982 	int error, l, count = 0;
983 
984 	*config = NULL;
985 
986 	if (fstat64_blk(fd, &statbuf) == -1)
987 		return (0);
988 	size = P2ALIGN_TYPED(statbuf.st_size, sizeof (vdev_label_t), uint64_t);
989 
990 	error = posix_memalign((void **)&labels, PAGESIZE,
991 	    VDEV_LABELS * sizeof (*labels));
992 	if (error)
993 		return (-1);
994 
995 	memset(aiocbs, 0, sizeof (aiocbs));
996 	for (l = 0; l < VDEV_LABELS; l++) {
997 		off_t offset = label_offset(size, l) + VDEV_SKIP_SIZE;
998 
999 		aiocbs[l].aio_fildes = fd;
1000 		aiocbs[l].aio_offset = offset;
1001 		aiocbs[l].aio_buf = &labels[l];
1002 		aiocbs[l].aio_nbytes = sizeof (vdev_phys_t);
1003 		aiocbs[l].aio_lio_opcode = LIO_READ;
1004 		aiocbps[l] = &aiocbs[l];
1005 	}
1006 
1007 	if (lio_listio(LIO_WAIT, aiocbps, VDEV_LABELS, NULL) != 0) {
1008 		int saved_errno = errno;
1009 		boolean_t do_slow = B_FALSE;
1010 		error = -1;
1011 
1012 		if (errno == EAGAIN || errno == EINTR || errno == EIO) {
1013 			/*
1014 			 * A portion of the requests may have been submitted.
1015 			 * Clean them up.
1016 			 */
1017 			for (l = 0; l < VDEV_LABELS; l++) {
1018 				errno = 0;
1019 				switch (aio_error(&aiocbs[l])) {
1020 				case EINVAL:
1021 					break;
1022 				case EINPROGRESS:
1023 					// This shouldn't be possible to
1024 					// encounter, die if we do.
1025 					ASSERT(B_FALSE);
1026 					fallthrough;
1027 				case EOPNOTSUPP:
1028 				case ENOSYS:
1029 					do_slow = B_TRUE;
1030 					fallthrough;
1031 				case 0:
1032 				default:
1033 					(void) aio_return(&aiocbs[l]);
1034 				}
1035 			}
1036 		}
1037 		if (do_slow) {
1038 			/*
1039 			 * At least some IO involved access unsafe-for-AIO
1040 			 * files. Let's try again, without AIO this time.
1041 			 */
1042 			error = zpool_read_label_slow(fd, config, num_labels);
1043 			saved_errno = errno;
1044 		}
1045 		free(labels);
1046 		errno = saved_errno;
1047 		return (error);
1048 	}
1049 
1050 	for (l = 0; l < VDEV_LABELS; l++) {
1051 		uint64_t state, guid, txg;
1052 
1053 		if (aio_return(&aiocbs[l]) != sizeof (vdev_phys_t))
1054 			continue;
1055 
1056 		if (nvlist_unpack(labels[l].vp_nvlist,
1057 		    sizeof (labels[l].vp_nvlist), config, 0) != 0)
1058 			continue;
1059 
1060 		if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_GUID,
1061 		    &guid) != 0 || guid == 0) {
1062 			nvlist_free(*config);
1063 			continue;
1064 		}
1065 
1066 		if (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_STATE,
1067 		    &state) != 0 || state > POOL_STATE_L2CACHE) {
1068 			nvlist_free(*config);
1069 			continue;
1070 		}
1071 
1072 		if (state != POOL_STATE_SPARE && state != POOL_STATE_L2CACHE &&
1073 		    (nvlist_lookup_uint64(*config, ZPOOL_CONFIG_POOL_TXG,
1074 		    &txg) != 0 || txg == 0)) {
1075 			nvlist_free(*config);
1076 			continue;
1077 		}
1078 
1079 		if (expected_guid) {
1080 			if (expected_guid == guid)
1081 				count++;
1082 
1083 			nvlist_free(*config);
1084 		} else {
1085 			expected_config = *config;
1086 			expected_guid = guid;
1087 			count++;
1088 		}
1089 	}
1090 
1091 	if (num_labels != NULL)
1092 		*num_labels = count;
1093 
1094 	free(labels);
1095 	*config = expected_config;
1096 
1097 	return (0);
1098 }
1099 
1100 /*
1101  * Sorted by full path and then vdev guid to allow for multiple entries with
1102  * the same full path name.  This is required because it's possible to
1103  * have multiple block devices with labels that refer to the same
1104  * ZPOOL_CONFIG_PATH yet have different vdev guids.  In this case both
1105  * entries need to be added to the cache.  Scenarios where this can occur
1106  * include overwritten pool labels, devices which are visible from multiple
1107  * hosts and multipath devices.
1108  */
1109 int
slice_cache_compare(const void * arg1,const void * arg2)1110 slice_cache_compare(const void *arg1, const void *arg2)
1111 {
1112 	const char  *nm1 = ((rdsk_node_t *)arg1)->rn_name;
1113 	const char  *nm2 = ((rdsk_node_t *)arg2)->rn_name;
1114 	uint64_t guid1 = ((rdsk_node_t *)arg1)->rn_vdev_guid;
1115 	uint64_t guid2 = ((rdsk_node_t *)arg2)->rn_vdev_guid;
1116 	int rv;
1117 
1118 	rv = TREE_ISIGN(strcmp(nm1, nm2));
1119 	if (rv)
1120 		return (rv);
1121 
1122 	return (TREE_CMP(guid1, guid2));
1123 }
1124 
1125 static int
label_paths_impl(libpc_handle_t * hdl,nvlist_t * nvroot,uint64_t pool_guid,uint64_t vdev_guid,char ** path,char ** devid)1126 label_paths_impl(libpc_handle_t *hdl, nvlist_t *nvroot, uint64_t pool_guid,
1127     uint64_t vdev_guid, char **path, char **devid)
1128 {
1129 	nvlist_t **child;
1130 	uint_t c, children;
1131 	uint64_t guid;
1132 	char *val;
1133 	int error;
1134 
1135 	if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
1136 	    &child, &children) == 0) {
1137 		for (c = 0; c < children; c++) {
1138 			error  = label_paths_impl(hdl, child[c],
1139 			    pool_guid, vdev_guid, path, devid);
1140 			if (error)
1141 				return (error);
1142 		}
1143 		return (0);
1144 	}
1145 
1146 	if (nvroot == NULL)
1147 		return (0);
1148 
1149 	error = nvlist_lookup_uint64(nvroot, ZPOOL_CONFIG_GUID, &guid);
1150 	if ((error != 0) || (guid != vdev_guid))
1151 		return (0);
1152 
1153 	error = nvlist_lookup_string(nvroot, ZPOOL_CONFIG_PATH, &val);
1154 	if (error == 0)
1155 		*path = val;
1156 
1157 	error = nvlist_lookup_string(nvroot, ZPOOL_CONFIG_DEVID, &val);
1158 	if (error == 0)
1159 		*devid = val;
1160 
1161 	return (0);
1162 }
1163 
1164 /*
1165  * Given a disk label fetch the ZPOOL_CONFIG_PATH and ZPOOL_CONFIG_DEVID
1166  * and store these strings as config_path and devid_path respectively.
1167  * The returned pointers are only valid as long as label remains valid.
1168  */
1169 int
label_paths(libpc_handle_t * hdl,nvlist_t * label,char ** path,char ** devid)1170 label_paths(libpc_handle_t *hdl, nvlist_t *label, char **path, char **devid)
1171 {
1172 	nvlist_t *nvroot;
1173 	uint64_t pool_guid;
1174 	uint64_t vdev_guid;
1175 
1176 	*path = NULL;
1177 	*devid = NULL;
1178 
1179 	if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_VDEV_TREE, &nvroot) ||
1180 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_GUID, &pool_guid) ||
1181 	    nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &vdev_guid))
1182 		return (ENOENT);
1183 
1184 	return (label_paths_impl(hdl, nvroot, pool_guid, vdev_guid, path,
1185 	    devid));
1186 }
1187 
1188 static void
zpool_find_import_scan_add_slice(libpc_handle_t * hdl,pthread_mutex_t * lock,avl_tree_t * cache,const char * path,const char * name,int order)1189 zpool_find_import_scan_add_slice(libpc_handle_t *hdl, pthread_mutex_t *lock,
1190     avl_tree_t *cache, const char *path, const char *name, int order)
1191 {
1192 	avl_index_t where;
1193 	rdsk_node_t *slice;
1194 
1195 	slice = zutil_alloc(hdl, sizeof (rdsk_node_t));
1196 	if (asprintf(&slice->rn_name, "%s/%s", path, name) == -1) {
1197 		free(slice);
1198 		return;
1199 	}
1200 	slice->rn_vdev_guid = 0;
1201 	slice->rn_lock = lock;
1202 	slice->rn_avl = cache;
1203 	slice->rn_hdl = hdl;
1204 	slice->rn_order = order + IMPORT_ORDER_SCAN_OFFSET;
1205 	slice->rn_labelpaths = B_FALSE;
1206 
1207 	pthread_mutex_lock(lock);
1208 	if (avl_find(cache, slice, &where)) {
1209 		free(slice->rn_name);
1210 		free(slice);
1211 	} else {
1212 		avl_insert(cache, slice, where);
1213 	}
1214 	pthread_mutex_unlock(lock);
1215 }
1216 
1217 static int
zpool_find_import_scan_dir(libpc_handle_t * hdl,pthread_mutex_t * lock,avl_tree_t * cache,const char * dir,int order)1218 zpool_find_import_scan_dir(libpc_handle_t *hdl, pthread_mutex_t *lock,
1219     avl_tree_t *cache, const char *dir, int order)
1220 {
1221 	int error;
1222 	char path[MAXPATHLEN];
1223 	struct dirent64 *dp;
1224 	DIR *dirp;
1225 
1226 	if (realpath(dir, path) == NULL) {
1227 		error = errno;
1228 		if (error == ENOENT)
1229 			return (0);
1230 
1231 		zutil_error_aux(hdl, strerror(error));
1232 		(void) zutil_error_fmt(hdl, EZFS_BADPATH, dgettext(
1233 		    TEXT_DOMAIN, "cannot resolve path '%s'"), dir);
1234 		return (error);
1235 	}
1236 
1237 	dirp = opendir(path);
1238 	if (dirp == NULL) {
1239 		error = errno;
1240 		zutil_error_aux(hdl, strerror(error));
1241 		(void) zutil_error_fmt(hdl, EZFS_BADPATH,
1242 		    dgettext(TEXT_DOMAIN, "cannot open '%s'"), path);
1243 		return (error);
1244 	}
1245 
1246 	while ((dp = readdir64(dirp)) != NULL) {
1247 		const char *name = dp->d_name;
1248 		if (name[0] == '.' &&
1249 		    (name[1] == 0 || (name[1] == '.' && name[2] == 0)))
1250 			continue;
1251 
1252 		zpool_find_import_scan_add_slice(hdl, lock, cache, path, name,
1253 		    order);
1254 	}
1255 
1256 	(void) closedir(dirp);
1257 	return (0);
1258 }
1259 
1260 static int
zpool_find_import_scan_path(libpc_handle_t * hdl,pthread_mutex_t * lock,avl_tree_t * cache,const char * dir,int order)1261 zpool_find_import_scan_path(libpc_handle_t *hdl, pthread_mutex_t *lock,
1262     avl_tree_t *cache, const char *dir, int order)
1263 {
1264 	int error = 0;
1265 	char path[MAXPATHLEN];
1266 	char *d, *b;
1267 	char *dpath, *name;
1268 
1269 	/*
1270 	 * Separate the directory part and last part of the
1271 	 * path. We do this so that we can get the realpath of
1272 	 * the directory. We don't get the realpath on the
1273 	 * whole path because if it's a symlink, we want the
1274 	 * path of the symlink not where it points to.
1275 	 */
1276 	d = zutil_strdup(hdl, dir);
1277 	b = zutil_strdup(hdl, dir);
1278 	dpath = dirname(d);
1279 	name = basename(b);
1280 
1281 	if (realpath(dpath, path) == NULL) {
1282 		error = errno;
1283 		if (error == ENOENT) {
1284 			error = 0;
1285 			goto out;
1286 		}
1287 
1288 		zutil_error_aux(hdl, strerror(error));
1289 		(void) zutil_error_fmt(hdl, EZFS_BADPATH, dgettext(
1290 		    TEXT_DOMAIN, "cannot resolve path '%s'"), dir);
1291 		goto out;
1292 	}
1293 
1294 	zpool_find_import_scan_add_slice(hdl, lock, cache, path, name, order);
1295 
1296 out:
1297 	free(b);
1298 	free(d);
1299 	return (error);
1300 }
1301 
1302 /*
1303  * Scan a list of directories for zfs devices.
1304  */
1305 static int
zpool_find_import_scan(libpc_handle_t * hdl,pthread_mutex_t * lock,avl_tree_t ** slice_cache,const char * const * dir,size_t dirs)1306 zpool_find_import_scan(libpc_handle_t *hdl, pthread_mutex_t *lock,
1307     avl_tree_t **slice_cache, const char * const *dir, size_t dirs)
1308 {
1309 	avl_tree_t *cache;
1310 	rdsk_node_t *slice;
1311 	void *cookie;
1312 	int i, error;
1313 
1314 	*slice_cache = NULL;
1315 	cache = zutil_alloc(hdl, sizeof (avl_tree_t));
1316 	avl_create(cache, slice_cache_compare, sizeof (rdsk_node_t),
1317 	    offsetof(rdsk_node_t, rn_node));
1318 
1319 	for (i = 0; i < dirs; i++) {
1320 		struct stat sbuf;
1321 
1322 		if (stat(dir[i], &sbuf) != 0) {
1323 			error = errno;
1324 			if (error == ENOENT)
1325 				continue;
1326 
1327 			zutil_error_aux(hdl, strerror(error));
1328 			(void) zutil_error_fmt(hdl, EZFS_BADPATH, dgettext(
1329 			    TEXT_DOMAIN, "cannot resolve path '%s'"), dir[i]);
1330 			goto error;
1331 		}
1332 
1333 		/*
1334 		 * If dir[i] is a directory, we walk through it and add all
1335 		 * the entries to the cache. If it's not a directory, we just
1336 		 * add it to the cache.
1337 		 */
1338 		if (S_ISDIR(sbuf.st_mode)) {
1339 			if ((error = zpool_find_import_scan_dir(hdl, lock,
1340 			    cache, dir[i], i)) != 0)
1341 				goto error;
1342 		} else {
1343 			if ((error = zpool_find_import_scan_path(hdl, lock,
1344 			    cache, dir[i], i)) != 0)
1345 				goto error;
1346 		}
1347 	}
1348 
1349 	*slice_cache = cache;
1350 	return (0);
1351 
1352 error:
1353 	cookie = NULL;
1354 	while ((slice = avl_destroy_nodes(cache, &cookie)) != NULL) {
1355 		free(slice->rn_name);
1356 		free(slice);
1357 	}
1358 	free(cache);
1359 
1360 	return (error);
1361 }
1362 
1363 /*
1364  * Given a list of directories to search, find all pools stored on disk.  This
1365  * includes partial pools which are not available to import.  If no args are
1366  * given (argc is 0), then the default directory (/dev/dsk) is searched.
1367  * poolname or guid (but not both) are provided by the caller when trying
1368  * to import a specific pool.
1369  */
1370 static nvlist_t *
zpool_find_import_impl(libpc_handle_t * hdl,importargs_t * iarg,pthread_mutex_t * lock,avl_tree_t * cache)1371 zpool_find_import_impl(libpc_handle_t *hdl, importargs_t *iarg,
1372     pthread_mutex_t *lock, avl_tree_t *cache)
1373 {
1374 	nvlist_t *ret = NULL;
1375 	pool_list_t pools = { 0 };
1376 	pool_entry_t *pe, *penext;
1377 	vdev_entry_t *ve, *venext;
1378 	config_entry_t *ce, *cenext;
1379 	name_entry_t *ne, *nenext;
1380 	rdsk_node_t *slice;
1381 	void *cookie;
1382 	tpool_t *t;
1383 
1384 	verify(iarg->poolname == NULL || iarg->guid == 0);
1385 
1386 	/*
1387 	 * Create a thread pool to parallelize the process of reading and
1388 	 * validating labels, a large number of threads can be used due to
1389 	 * minimal contention.
1390 	 */
1391 	t = tpool_create(1, 2 * sysconf(_SC_NPROCESSORS_ONLN), 0, NULL);
1392 	for (slice = avl_first(cache); slice;
1393 	    (slice = avl_walk(cache, slice, AVL_AFTER)))
1394 		(void) tpool_dispatch(t, zpool_open_func, slice);
1395 
1396 	tpool_wait(t);
1397 	tpool_destroy(t);
1398 
1399 	/*
1400 	 * Process the cache, filtering out any entries which are not
1401 	 * for the specified pool then adding matching label configs.
1402 	 */
1403 	cookie = NULL;
1404 	while ((slice = avl_destroy_nodes(cache, &cookie)) != NULL) {
1405 		if (slice->rn_config != NULL) {
1406 			nvlist_t *config = slice->rn_config;
1407 			boolean_t matched = B_TRUE;
1408 			boolean_t aux = B_FALSE;
1409 			int fd;
1410 
1411 			/*
1412 			 * Check if it's a spare or l2cache device. If it is,
1413 			 * we need to skip the name and guid check since they
1414 			 * don't exist on aux device label.
1415 			 */
1416 			if (iarg->poolname != NULL || iarg->guid != 0) {
1417 				uint64_t state;
1418 				aux = nvlist_lookup_uint64(config,
1419 				    ZPOOL_CONFIG_POOL_STATE, &state) == 0 &&
1420 				    (state == POOL_STATE_SPARE ||
1421 				    state == POOL_STATE_L2CACHE);
1422 			}
1423 
1424 			if (iarg->poolname != NULL && !aux) {
1425 				char *pname;
1426 
1427 				matched = nvlist_lookup_string(config,
1428 				    ZPOOL_CONFIG_POOL_NAME, &pname) == 0 &&
1429 				    strcmp(iarg->poolname, pname) == 0;
1430 			} else if (iarg->guid != 0 && !aux) {
1431 				uint64_t this_guid;
1432 
1433 				matched = nvlist_lookup_uint64(config,
1434 				    ZPOOL_CONFIG_POOL_GUID, &this_guid) == 0 &&
1435 				    iarg->guid == this_guid;
1436 			}
1437 			if (matched) {
1438 				/*
1439 				 * Verify all remaining entries can be opened
1440 				 * exclusively. This will prune all underlying
1441 				 * multipath devices which otherwise could
1442 				 * result in the vdev appearing as UNAVAIL.
1443 				 *
1444 				 * Under zdb, this step isn't required and
1445 				 * would prevent a zdb -e of active pools with
1446 				 * no cachefile.
1447 				 */
1448 				fd = open(slice->rn_name,
1449 				    O_RDONLY | O_EXCL | O_CLOEXEC);
1450 				if (fd >= 0 || iarg->can_be_active) {
1451 					if (fd >= 0)
1452 						close(fd);
1453 					add_config(hdl, &pools,
1454 					    slice->rn_name, slice->rn_order,
1455 					    slice->rn_num_labels, config);
1456 				}
1457 			}
1458 			nvlist_free(config);
1459 		}
1460 		free(slice->rn_name);
1461 		free(slice);
1462 	}
1463 	avl_destroy(cache);
1464 	free(cache);
1465 
1466 	ret = get_configs(hdl, &pools, iarg->can_be_active, iarg->policy);
1467 
1468 	for (pe = pools.pools; pe != NULL; pe = penext) {
1469 		penext = pe->pe_next;
1470 		for (ve = pe->pe_vdevs; ve != NULL; ve = venext) {
1471 			venext = ve->ve_next;
1472 			for (ce = ve->ve_configs; ce != NULL; ce = cenext) {
1473 				cenext = ce->ce_next;
1474 				nvlist_free(ce->ce_config);
1475 				free(ce);
1476 			}
1477 			free(ve);
1478 		}
1479 		free(pe);
1480 	}
1481 
1482 	for (ne = pools.names; ne != NULL; ne = nenext) {
1483 		nenext = ne->ne_next;
1484 		free(ne->ne_name);
1485 		free(ne);
1486 	}
1487 
1488 	return (ret);
1489 }
1490 
1491 /*
1492  * Given a config, discover the paths for the devices which
1493  * exist in the config.
1494  */
1495 static int
discover_cached_paths(libpc_handle_t * hdl,nvlist_t * nv,avl_tree_t * cache,pthread_mutex_t * lock)1496 discover_cached_paths(libpc_handle_t *hdl, nvlist_t *nv,
1497     avl_tree_t *cache, pthread_mutex_t *lock)
1498 {
1499 	char *path = NULL;
1500 	uint_t children;
1501 	nvlist_t **child;
1502 
1503 	if (nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1504 	    &child, &children) == 0) {
1505 		for (int c = 0; c < children; c++) {
1506 			discover_cached_paths(hdl, child[c], cache, lock);
1507 		}
1508 	}
1509 
1510 	/*
1511 	 * Once we have the path, we need to add the directory to
1512 	 * our directory cache.
1513 	 */
1514 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &path) == 0) {
1515 		return (zpool_find_import_scan_dir(hdl, lock, cache,
1516 		    dirname(path), 0));
1517 	}
1518 	return (0);
1519 }
1520 
1521 /*
1522  * Given a cache file, return the contents as a list of importable pools.
1523  * poolname or guid (but not both) are provided by the caller when trying
1524  * to import a specific pool.
1525  */
1526 static nvlist_t *
zpool_find_import_cached(libpc_handle_t * hdl,importargs_t * iarg)1527 zpool_find_import_cached(libpc_handle_t *hdl, importargs_t *iarg)
1528 {
1529 	char *buf;
1530 	int fd;
1531 	struct stat64 statbuf;
1532 	nvlist_t *raw, *src, *dst;
1533 	nvlist_t *pools;
1534 	nvpair_t *elem;
1535 	char *name;
1536 	uint64_t this_guid;
1537 	boolean_t active;
1538 
1539 	verify(iarg->poolname == NULL || iarg->guid == 0);
1540 
1541 	if ((fd = open(iarg->cachefile, O_RDONLY | O_CLOEXEC)) < 0) {
1542 		zutil_error_aux(hdl, "%s", strerror(errno));
1543 		(void) zutil_error(hdl, EZFS_BADCACHE,
1544 		    dgettext(TEXT_DOMAIN, "failed to open cache file"));
1545 		return (NULL);
1546 	}
1547 
1548 	if (fstat64(fd, &statbuf) != 0) {
1549 		zutil_error_aux(hdl, "%s", strerror(errno));
1550 		(void) close(fd);
1551 		(void) zutil_error(hdl, EZFS_BADCACHE,
1552 		    dgettext(TEXT_DOMAIN, "failed to get size of cache file"));
1553 		return (NULL);
1554 	}
1555 
1556 	if ((buf = zutil_alloc(hdl, statbuf.st_size)) == NULL) {
1557 		(void) close(fd);
1558 		return (NULL);
1559 	}
1560 
1561 	if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
1562 		(void) close(fd);
1563 		free(buf);
1564 		(void) zutil_error(hdl, EZFS_BADCACHE,
1565 		    dgettext(TEXT_DOMAIN,
1566 		    "failed to read cache file contents"));
1567 		return (NULL);
1568 	}
1569 
1570 	(void) close(fd);
1571 
1572 	if (nvlist_unpack(buf, statbuf.st_size, &raw, 0) != 0) {
1573 		free(buf);
1574 		(void) zutil_error(hdl, EZFS_BADCACHE,
1575 		    dgettext(TEXT_DOMAIN,
1576 		    "invalid or corrupt cache file contents"));
1577 		return (NULL);
1578 	}
1579 
1580 	free(buf);
1581 
1582 	/*
1583 	 * Go through and get the current state of the pools and refresh their
1584 	 * state.
1585 	 */
1586 	if (nvlist_alloc(&pools, 0, 0) != 0) {
1587 		(void) zutil_no_memory(hdl);
1588 		nvlist_free(raw);
1589 		return (NULL);
1590 	}
1591 
1592 	elem = NULL;
1593 	while ((elem = nvlist_next_nvpair(raw, elem)) != NULL) {
1594 		src = fnvpair_value_nvlist(elem);
1595 
1596 		name = fnvlist_lookup_string(src, ZPOOL_CONFIG_POOL_NAME);
1597 		if (iarg->poolname != NULL && strcmp(iarg->poolname, name) != 0)
1598 			continue;
1599 
1600 		this_guid = fnvlist_lookup_uint64(src, ZPOOL_CONFIG_POOL_GUID);
1601 		if (iarg->guid != 0 && iarg->guid != this_guid)
1602 			continue;
1603 
1604 		if (zutil_pool_active(hdl, name, this_guid, &active) != 0) {
1605 			nvlist_free(raw);
1606 			nvlist_free(pools);
1607 			return (NULL);
1608 		}
1609 
1610 		if (active)
1611 			continue;
1612 
1613 		if (iarg->scan) {
1614 			uint64_t saved_guid = iarg->guid;
1615 			const char *saved_poolname = iarg->poolname;
1616 			pthread_mutex_t lock;
1617 
1618 			/*
1619 			 * Create the device cache that will hold the
1620 			 * devices we will scan based on the cachefile.
1621 			 * This will get destroyed and freed by
1622 			 * zpool_find_import_impl.
1623 			 */
1624 			avl_tree_t *cache = zutil_alloc(hdl,
1625 			    sizeof (avl_tree_t));
1626 			avl_create(cache, slice_cache_compare,
1627 			    sizeof (rdsk_node_t),
1628 			    offsetof(rdsk_node_t, rn_node));
1629 			nvlist_t *nvroot = fnvlist_lookup_nvlist(src,
1630 			    ZPOOL_CONFIG_VDEV_TREE);
1631 
1632 			/*
1633 			 * We only want to find the pool with this_guid.
1634 			 * We will reset these values back later.
1635 			 */
1636 			iarg->guid = this_guid;
1637 			iarg->poolname = NULL;
1638 
1639 			/*
1640 			 * We need to build up a cache of devices that exists
1641 			 * in the paths pointed to by the cachefile. This allows
1642 			 * us to preserve the device namespace that was
1643 			 * originally specified by the user but also lets us
1644 			 * scan devices in those directories in case they had
1645 			 * been renamed.
1646 			 */
1647 			pthread_mutex_init(&lock, NULL);
1648 			discover_cached_paths(hdl, nvroot, cache, &lock);
1649 			nvlist_t *nv = zpool_find_import_impl(hdl, iarg,
1650 			    &lock, cache);
1651 			pthread_mutex_destroy(&lock);
1652 
1653 			/*
1654 			 * zpool_find_import_impl will return back
1655 			 * a list of pools that it found based on the
1656 			 * device cache. There should only be one pool
1657 			 * since we're looking for a specific guid.
1658 			 * We will use that pool to build up the final
1659 			 * pool nvlist which is returned back to the
1660 			 * caller.
1661 			 */
1662 			nvpair_t *pair = nvlist_next_nvpair(nv, NULL);
1663 			fnvlist_add_nvlist(pools, nvpair_name(pair),
1664 			    fnvpair_value_nvlist(pair));
1665 
1666 			VERIFY3P(nvlist_next_nvpair(nv, pair), ==, NULL);
1667 
1668 			iarg->guid = saved_guid;
1669 			iarg->poolname = saved_poolname;
1670 			continue;
1671 		}
1672 
1673 		if (nvlist_add_string(src, ZPOOL_CONFIG_CACHEFILE,
1674 		    iarg->cachefile) != 0) {
1675 			(void) zutil_no_memory(hdl);
1676 			nvlist_free(raw);
1677 			nvlist_free(pools);
1678 			return (NULL);
1679 		}
1680 
1681 		update_vdevs_config_dev_sysfs_path(src);
1682 
1683 		if ((dst = zutil_refresh_config(hdl, src)) == NULL) {
1684 			nvlist_free(raw);
1685 			nvlist_free(pools);
1686 			return (NULL);
1687 		}
1688 
1689 		if (nvlist_add_nvlist(pools, nvpair_name(elem), dst) != 0) {
1690 			(void) zutil_no_memory(hdl);
1691 			nvlist_free(dst);
1692 			nvlist_free(raw);
1693 			nvlist_free(pools);
1694 			return (NULL);
1695 		}
1696 		nvlist_free(dst);
1697 	}
1698 	nvlist_free(raw);
1699 	return (pools);
1700 }
1701 
1702 static nvlist_t *
zpool_find_import(libpc_handle_t * hdl,importargs_t * iarg)1703 zpool_find_import(libpc_handle_t *hdl, importargs_t *iarg)
1704 {
1705 	pthread_mutex_t lock;
1706 	avl_tree_t *cache;
1707 	nvlist_t *pools = NULL;
1708 
1709 	verify(iarg->poolname == NULL || iarg->guid == 0);
1710 	pthread_mutex_init(&lock, NULL);
1711 
1712 	/*
1713 	 * Locate pool member vdevs by blkid or by directory scanning.
1714 	 * On success a newly allocated AVL tree which is populated with an
1715 	 * entry for each discovered vdev will be returned in the cache.
1716 	 * It's the caller's responsibility to consume and destroy this tree.
1717 	 */
1718 	if (iarg->scan || iarg->paths != 0) {
1719 		size_t dirs = iarg->paths;
1720 		const char * const *dir = (const char * const *)iarg->path;
1721 
1722 		if (dirs == 0)
1723 			dir = zpool_default_search_paths(&dirs);
1724 
1725 		if (zpool_find_import_scan(hdl, &lock, &cache,
1726 		    dir, dirs) != 0) {
1727 			pthread_mutex_destroy(&lock);
1728 			return (NULL);
1729 		}
1730 	} else {
1731 		if (zpool_find_import_blkid(hdl, &lock, &cache) != 0) {
1732 			pthread_mutex_destroy(&lock);
1733 			return (NULL);
1734 		}
1735 	}
1736 
1737 	pools = zpool_find_import_impl(hdl, iarg, &lock, cache);
1738 	pthread_mutex_destroy(&lock);
1739 	return (pools);
1740 }
1741 
1742 
1743 nvlist_t *
zpool_search_import(void * hdl,importargs_t * import,const pool_config_ops_t * pco)1744 zpool_search_import(void *hdl, importargs_t *import,
1745     const pool_config_ops_t *pco)
1746 {
1747 	libpc_handle_t handle = { 0 };
1748 	nvlist_t *pools = NULL;
1749 
1750 	handle.lpc_lib_handle = hdl;
1751 	handle.lpc_ops = pco;
1752 	handle.lpc_printerr = B_TRUE;
1753 
1754 	verify(import->poolname == NULL || import->guid == 0);
1755 
1756 	if (import->cachefile != NULL)
1757 		pools = zpool_find_import_cached(&handle, import);
1758 	else
1759 		pools = zpool_find_import(&handle, import);
1760 
1761 	if ((pools == NULL || nvlist_empty(pools)) &&
1762 	    handle.lpc_open_access_error && geteuid() != 0) {
1763 		(void) zutil_error(&handle, EZFS_EACESS, dgettext(TEXT_DOMAIN,
1764 		    "no pools found"));
1765 	}
1766 
1767 	return (pools);
1768 }
1769 
1770 static boolean_t
pool_match(nvlist_t * cfg,char * tgt)1771 pool_match(nvlist_t *cfg, char *tgt)
1772 {
1773 	uint64_t v, guid = strtoull(tgt, NULL, 0);
1774 	char *s;
1775 
1776 	if (guid != 0) {
1777 		if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &v) == 0)
1778 			return (v == guid);
1779 	} else {
1780 		if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &s) == 0)
1781 			return (strcmp(s, tgt) == 0);
1782 	}
1783 	return (B_FALSE);
1784 }
1785 
1786 int
zpool_find_config(void * hdl,const char * target,nvlist_t ** configp,importargs_t * args,const pool_config_ops_t * pco)1787 zpool_find_config(void *hdl, const char *target, nvlist_t **configp,
1788     importargs_t *args, const pool_config_ops_t *pco)
1789 {
1790 	nvlist_t *pools;
1791 	nvlist_t *match = NULL;
1792 	nvlist_t *config = NULL;
1793 	char *sepp = NULL;
1794 	char sep = '\0';
1795 	int count = 0;
1796 	char *targetdup = strdup(target);
1797 
1798 	*configp = NULL;
1799 
1800 	if ((sepp = strpbrk(targetdup, "/@")) != NULL) {
1801 		sep = *sepp;
1802 		*sepp = '\0';
1803 	}
1804 
1805 	pools = zpool_search_import(hdl, args, pco);
1806 
1807 	if (pools != NULL) {
1808 		nvpair_t *elem = NULL;
1809 		while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
1810 			VERIFY0(nvpair_value_nvlist(elem, &config));
1811 			if (pool_match(config, targetdup)) {
1812 				count++;
1813 				if (match != NULL) {
1814 					/* multiple matches found */
1815 					continue;
1816 				} else {
1817 					match = fnvlist_dup(config);
1818 				}
1819 			}
1820 		}
1821 		fnvlist_free(pools);
1822 	}
1823 
1824 	if (count == 0) {
1825 		free(targetdup);
1826 		return (ENOENT);
1827 	}
1828 
1829 	if (count > 1) {
1830 		free(targetdup);
1831 		fnvlist_free(match);
1832 		return (EINVAL);
1833 	}
1834 
1835 	*configp = match;
1836 	free(targetdup);
1837 
1838 	return (0);
1839 }
1840 
1841 /*
1842  * Internal function for iterating over the vdevs.
1843  *
1844  * For each vdev, func() will be called and will be passed 'zhp' (which is
1845  * typically the zpool_handle_t cast as a void pointer), the vdev's nvlist, and
1846  * a user-defined data pointer).
1847  *
1848  * The return values from all the func() calls will be OR'd together and
1849  * returned.
1850  */
1851 int
for_each_vdev_cb(void * zhp,nvlist_t * nv,pool_vdev_iter_f func,void * data)1852 for_each_vdev_cb(void *zhp, nvlist_t *nv, pool_vdev_iter_f func,
1853     void *data)
1854 {
1855 	nvlist_t **child;
1856 	uint_t c, children;
1857 	int ret = 0;
1858 	int i;
1859 	char *type;
1860 
1861 	const char *list[] = {
1862 	    ZPOOL_CONFIG_SPARES,
1863 	    ZPOOL_CONFIG_L2CACHE,
1864 	    ZPOOL_CONFIG_CHILDREN
1865 	};
1866 
1867 	for (i = 0; i < ARRAY_SIZE(list); i++) {
1868 		if (nvlist_lookup_nvlist_array(nv, list[i], &child,
1869 		    &children) == 0) {
1870 			for (c = 0; c < children; c++) {
1871 				uint64_t ishole = 0;
1872 
1873 				(void) nvlist_lookup_uint64(child[c],
1874 				    ZPOOL_CONFIG_IS_HOLE, &ishole);
1875 
1876 				if (ishole)
1877 					continue;
1878 
1879 				ret |= for_each_vdev_cb(zhp, child[c],
1880 				    func, data);
1881 			}
1882 		}
1883 	}
1884 
1885 	if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
1886 		return (ret);
1887 
1888 	/* Don't run our function on root vdevs */
1889 	if (strcmp(type, VDEV_TYPE_ROOT) != 0) {
1890 		ret |= func(zhp, nv, data);
1891 	}
1892 
1893 	return (ret);
1894 }
1895 
1896 /*
1897  * Given an ZPOOL_CONFIG_VDEV_TREE nvpair, iterate over all the vdevs, calling
1898  * func() for each one.  func() is passed the vdev's nvlist and an optional
1899  * user-defined 'data' pointer.
1900  */
1901 int
for_each_vdev_in_nvlist(nvlist_t * nvroot,pool_vdev_iter_f func,void * data)1902 for_each_vdev_in_nvlist(nvlist_t *nvroot, pool_vdev_iter_f func, void *data)
1903 {
1904 	return (for_each_vdev_cb(NULL, nvroot, func, data));
1905 }
1906