xref: /freebsd/sys/contrib/openzfs/cmd/zed/agents/zfs_mod.c (revision f9fd7337f63698f33239c58c07bf430198235a22)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2012 by Delphix. All rights reserved.
24  * Copyright 2014 Nexenta Systems, Inc. All rights reserved.
25  * Copyright (c) 2016, 2017, Intel Corporation.
26  * Copyright (c) 2017 Open-E, Inc. All Rights Reserved.
27  */
28 
29 /*
30  * ZFS syseventd module.
31  *
32  * file origin: openzfs/usr/src/cmd/syseventd/modules/zfs_mod/zfs_mod.c
33  *
34  * The purpose of this module is to identify when devices are added to the
35  * system, and appropriately online or replace the affected vdevs.
36  *
37  * When a device is added to the system:
38  *
39  * 	1. Search for any vdevs whose devid matches that of the newly added
40  *	   device.
41  *
42  * 	2. If no vdevs are found, then search for any vdevs whose udev path
43  *	   matches that of the new device.
44  *
45  *	3. If no vdevs match by either method, then ignore the event.
46  *
47  * 	4. Attempt to online the device with a flag to indicate that it should
48  *	   be unspared when resilvering completes.  If this succeeds, then the
49  *	   same device was inserted and we should continue normally.
50  *
51  *	5. If the pool does not have the 'autoreplace' property set, attempt to
52  *	   online the device again without the unspare flag, which will
53  *	   generate a FMA fault.
54  *
55  *	6. If the pool has the 'autoreplace' property set, and the matching vdev
56  *	   is a whole disk, then label the new disk and attempt a 'zpool
57  *	   replace'.
58  *
59  * The module responds to EC_DEV_ADD events.  The special ESC_ZFS_VDEV_CHECK
60  * event indicates that a device failed to open during pool load, but the
61  * autoreplace property was set.  In this case, we deferred the associated
62  * FMA fault until our module had a chance to process the autoreplace logic.
63  * If the device could not be replaced, then the second online attempt will
64  * trigger the FMA fault that we skipped earlier.
65  *
66  * On Linux udev provides a disk insert for both the disk and the partition.
67  */
68 
69 #include <ctype.h>
70 #include <fcntl.h>
71 #include <libnvpair.h>
72 #include <libzfs.h>
73 #include <libzutil.h>
74 #include <limits.h>
75 #include <stddef.h>
76 #include <stdlib.h>
77 #include <string.h>
78 #include <syslog.h>
79 #include <sys/list.h>
80 #include <sys/sunddi.h>
81 #include <sys/sysevent/eventdefs.h>
82 #include <sys/sysevent/dev.h>
83 #include <thread_pool.h>
84 #include <pthread.h>
85 #include <unistd.h>
86 #include <errno.h>
87 #include "zfs_agents.h"
88 #include "../zed_log.h"
89 
90 #define	DEV_BYID_PATH	"/dev/disk/by-id/"
91 #define	DEV_BYPATH_PATH	"/dev/disk/by-path/"
92 #define	DEV_BYVDEV_PATH	"/dev/disk/by-vdev/"
93 
94 typedef void (*zfs_process_func_t)(zpool_handle_t *, nvlist_t *, boolean_t);
95 
96 libzfs_handle_t *g_zfshdl;
97 list_t g_pool_list;	/* list of unavailable pools at initialization */
98 list_t g_device_list;	/* list of disks with asynchronous label request */
99 tpool_t *g_tpool;
100 boolean_t g_enumeration_done;
101 pthread_t g_zfs_tid;	/* zfs_enum_pools() thread */
102 
103 typedef struct unavailpool {
104 	zpool_handle_t	*uap_zhp;
105 	list_node_t	uap_node;
106 } unavailpool_t;
107 
108 typedef struct pendingdev {
109 	char		pd_physpath[128];
110 	list_node_t	pd_node;
111 } pendingdev_t;
112 
113 static int
114 zfs_toplevel_state(zpool_handle_t *zhp)
115 {
116 	nvlist_t *nvroot;
117 	vdev_stat_t *vs;
118 	unsigned int c;
119 
120 	verify(nvlist_lookup_nvlist(zpool_get_config(zhp, NULL),
121 	    ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
122 	verify(nvlist_lookup_uint64_array(nvroot, ZPOOL_CONFIG_VDEV_STATS,
123 	    (uint64_t **)&vs, &c) == 0);
124 	return (vs->vs_state);
125 }
126 
127 static int
128 zfs_unavail_pool(zpool_handle_t *zhp, void *data)
129 {
130 	zed_log_msg(LOG_INFO, "zfs_unavail_pool: examining '%s' (state %d)",
131 	    zpool_get_name(zhp), (int)zfs_toplevel_state(zhp));
132 
133 	if (zfs_toplevel_state(zhp) < VDEV_STATE_DEGRADED) {
134 		unavailpool_t *uap;
135 		uap = malloc(sizeof (unavailpool_t));
136 		uap->uap_zhp = zhp;
137 		list_insert_tail((list_t *)data, uap);
138 	} else {
139 		zpool_close(zhp);
140 	}
141 	return (0);
142 }
143 
144 /*
145  * Two stage replace on Linux
146  * since we get disk notifications
147  * we can wait for partitioned disk slice to show up!
148  *
149  * First stage tags the disk, initiates async partitioning, and returns
150  * Second stage finds the tag and proceeds to ZFS labeling/replace
151  *
152  * disk-add --> label-disk + tag-disk --> partition-add --> zpool_vdev_attach
153  *
154  * 1. physical match with no fs, no partition
155  *	tag it top, partition disk
156  *
157  * 2. physical match again, see partition and tag
158  *
159  */
160 
161 /*
162  * The device associated with the given vdev (either by devid or physical path)
163  * has been added to the system.  If 'isdisk' is set, then we only attempt a
164  * replacement if it's a whole disk.  This also implies that we should label the
165  * disk first.
166  *
167  * First, we attempt to online the device (making sure to undo any spare
168  * operation when finished).  If this succeeds, then we're done.  If it fails,
169  * and the new state is VDEV_CANT_OPEN, it indicates that the device was opened,
170  * but that the label was not what we expected.  If the 'autoreplace' property
171  * is enabled, then we relabel the disk (if specified), and attempt a 'zpool
172  * replace'.  If the online is successful, but the new state is something else
173  * (REMOVED or FAULTED), it indicates that we're out of sync or in some sort of
174  * race, and we should avoid attempting to relabel the disk.
175  *
176  * Also can arrive here from a ESC_ZFS_VDEV_CHECK event
177  */
178 static void
179 zfs_process_add(zpool_handle_t *zhp, nvlist_t *vdev, boolean_t labeled)
180 {
181 	char *path;
182 	vdev_state_t newstate;
183 	nvlist_t *nvroot, *newvd;
184 	pendingdev_t *device;
185 	uint64_t wholedisk = 0ULL;
186 	uint64_t offline = 0ULL;
187 	uint64_t guid = 0ULL;
188 	char *physpath = NULL, *new_devid = NULL, *enc_sysfs_path = NULL;
189 	char rawpath[PATH_MAX], fullpath[PATH_MAX];
190 	char devpath[PATH_MAX];
191 	int ret;
192 	boolean_t is_dm = B_FALSE;
193 	boolean_t is_sd = B_FALSE;
194 	uint_t c;
195 	vdev_stat_t *vs;
196 
197 	if (nvlist_lookup_string(vdev, ZPOOL_CONFIG_PATH, &path) != 0)
198 		return;
199 
200 	/* Skip healthy disks */
201 	verify(nvlist_lookup_uint64_array(vdev, ZPOOL_CONFIG_VDEV_STATS,
202 	    (uint64_t **)&vs, &c) == 0);
203 	if (vs->vs_state == VDEV_STATE_HEALTHY) {
204 		zed_log_msg(LOG_INFO, "%s: %s is already healthy, skip it.",
205 		    __func__, path);
206 		return;
207 	}
208 
209 	(void) nvlist_lookup_string(vdev, ZPOOL_CONFIG_PHYS_PATH, &physpath);
210 	(void) nvlist_lookup_string(vdev, ZPOOL_CONFIG_VDEV_ENC_SYSFS_PATH,
211 	    &enc_sysfs_path);
212 	(void) nvlist_lookup_uint64(vdev, ZPOOL_CONFIG_WHOLE_DISK, &wholedisk);
213 	(void) nvlist_lookup_uint64(vdev, ZPOOL_CONFIG_OFFLINE, &offline);
214 	(void) nvlist_lookup_uint64(vdev, ZPOOL_CONFIG_GUID, &guid);
215 
216 	if (offline)
217 		return;  /* don't intervene if it was taken offline */
218 
219 	is_dm = zfs_dev_is_dm(path);
220 	zed_log_msg(LOG_INFO, "zfs_process_add: pool '%s' vdev '%s', phys '%s'"
221 	    " wholedisk %d, %s dm (guid %llu)", zpool_get_name(zhp), path,
222 	    physpath ? physpath : "NULL", wholedisk, is_dm ? "is" : "not",
223 	    (long long unsigned int)guid);
224 
225 	/*
226 	 * The VDEV guid is preferred for identification (gets passed in path)
227 	 */
228 	if (guid != 0) {
229 		(void) snprintf(fullpath, sizeof (fullpath), "%llu",
230 		    (long long unsigned int)guid);
231 	} else {
232 		/*
233 		 * otherwise use path sans partition suffix for whole disks
234 		 */
235 		(void) strlcpy(fullpath, path, sizeof (fullpath));
236 		if (wholedisk) {
237 			char *spath = zfs_strip_partition(fullpath);
238 			if (!spath) {
239 				zed_log_msg(LOG_INFO, "%s: Can't alloc",
240 				    __func__);
241 				return;
242 			}
243 
244 			(void) strlcpy(fullpath, spath, sizeof (fullpath));
245 			free(spath);
246 		}
247 	}
248 
249 	/*
250 	 * Attempt to online the device.
251 	 */
252 	if (zpool_vdev_online(zhp, fullpath,
253 	    ZFS_ONLINE_CHECKREMOVE | ZFS_ONLINE_UNSPARE, &newstate) == 0 &&
254 	    (newstate == VDEV_STATE_HEALTHY ||
255 	    newstate == VDEV_STATE_DEGRADED)) {
256 		zed_log_msg(LOG_INFO, "  zpool_vdev_online: vdev %s is %s",
257 		    fullpath, (newstate == VDEV_STATE_HEALTHY) ?
258 		    "HEALTHY" : "DEGRADED");
259 		return;
260 	}
261 
262 	/*
263 	 * vdev_id alias rule for using scsi_debug devices (FMA automated
264 	 * testing)
265 	 */
266 	if (physpath != NULL && strcmp("scsidebug", physpath) == 0)
267 		is_sd = B_TRUE;
268 
269 	/*
270 	 * If the pool doesn't have the autoreplace property set, then use
271 	 * vdev online to trigger a FMA fault by posting an ereport.
272 	 */
273 	if (!zpool_get_prop_int(zhp, ZPOOL_PROP_AUTOREPLACE, NULL) ||
274 	    !(wholedisk || is_dm) || (physpath == NULL)) {
275 		(void) zpool_vdev_online(zhp, fullpath, ZFS_ONLINE_FORCEFAULT,
276 		    &newstate);
277 		zed_log_msg(LOG_INFO, "Pool's autoreplace is not enabled or "
278 		    "not a whole disk for '%s'", fullpath);
279 		return;
280 	}
281 
282 	/*
283 	 * Convert physical path into its current device node.  Rawpath
284 	 * needs to be /dev/disk/by-vdev for a scsi_debug device since
285 	 * /dev/disk/by-path will not be present.
286 	 */
287 	(void) snprintf(rawpath, sizeof (rawpath), "%s%s",
288 	    is_sd ? DEV_BYVDEV_PATH : DEV_BYPATH_PATH, physpath);
289 
290 	if (realpath(rawpath, devpath) == NULL && !is_dm) {
291 		zed_log_msg(LOG_INFO, "  realpath: %s failed (%s)",
292 		    rawpath, strerror(errno));
293 
294 		(void) zpool_vdev_online(zhp, fullpath, ZFS_ONLINE_FORCEFAULT,
295 		    &newstate);
296 
297 		zed_log_msg(LOG_INFO, "  zpool_vdev_online: %s FORCEFAULT (%s)",
298 		    fullpath, libzfs_error_description(g_zfshdl));
299 		return;
300 	}
301 
302 	/* Only autoreplace bad disks */
303 	if ((vs->vs_state != VDEV_STATE_DEGRADED) &&
304 	    (vs->vs_state != VDEV_STATE_FAULTED) &&
305 	    (vs->vs_state != VDEV_STATE_CANT_OPEN)) {
306 		return;
307 	}
308 
309 	nvlist_lookup_string(vdev, "new_devid", &new_devid);
310 
311 	if (is_dm) {
312 		/* Don't label device mapper or multipath disks. */
313 	} else if (!labeled) {
314 		/*
315 		 * we're auto-replacing a raw disk, so label it first
316 		 */
317 		char *leafname;
318 
319 		/*
320 		 * If this is a request to label a whole disk, then attempt to
321 		 * write out the label.  Before we can label the disk, we need
322 		 * to map the physical string that was matched on to the under
323 		 * lying device node.
324 		 *
325 		 * If any part of this process fails, then do a force online
326 		 * to trigger a ZFS fault for the device (and any hot spare
327 		 * replacement).
328 		 */
329 		leafname = strrchr(devpath, '/') + 1;
330 
331 		/*
332 		 * If this is a request to label a whole disk, then attempt to
333 		 * write out the label.
334 		 */
335 		if (zpool_label_disk(g_zfshdl, zhp, leafname) != 0) {
336 			zed_log_msg(LOG_INFO, "  zpool_label_disk: could not "
337 			    "label '%s' (%s)", leafname,
338 			    libzfs_error_description(g_zfshdl));
339 
340 			(void) zpool_vdev_online(zhp, fullpath,
341 			    ZFS_ONLINE_FORCEFAULT, &newstate);
342 			return;
343 		}
344 
345 		/*
346 		 * The disk labeling is asynchronous on Linux. Just record
347 		 * this label request and return as there will be another
348 		 * disk add event for the partition after the labeling is
349 		 * completed.
350 		 */
351 		device = malloc(sizeof (pendingdev_t));
352 		(void) strlcpy(device->pd_physpath, physpath,
353 		    sizeof (device->pd_physpath));
354 		list_insert_tail(&g_device_list, device);
355 
356 		zed_log_msg(LOG_INFO, "  zpool_label_disk: async '%s' (%llu)",
357 		    leafname, (u_longlong_t)guid);
358 
359 		return;	/* resumes at EC_DEV_ADD.ESC_DISK for partition */
360 
361 	} else /* labeled */ {
362 		boolean_t found = B_FALSE;
363 		/*
364 		 * match up with request above to label the disk
365 		 */
366 		for (device = list_head(&g_device_list); device != NULL;
367 		    device = list_next(&g_device_list, device)) {
368 			if (strcmp(physpath, device->pd_physpath) == 0) {
369 				list_remove(&g_device_list, device);
370 				free(device);
371 				found = B_TRUE;
372 				break;
373 			}
374 			zed_log_msg(LOG_INFO, "zpool_label_disk: %s != %s",
375 			    physpath, device->pd_physpath);
376 		}
377 		if (!found) {
378 			/* unexpected partition slice encountered */
379 			zed_log_msg(LOG_INFO, "labeled disk %s unexpected here",
380 			    fullpath);
381 			(void) zpool_vdev_online(zhp, fullpath,
382 			    ZFS_ONLINE_FORCEFAULT, &newstate);
383 			return;
384 		}
385 
386 		zed_log_msg(LOG_INFO, "  zpool_label_disk: resume '%s' (%llu)",
387 		    physpath, (u_longlong_t)guid);
388 
389 		(void) snprintf(devpath, sizeof (devpath), "%s%s",
390 		    DEV_BYID_PATH, new_devid);
391 	}
392 
393 	/*
394 	 * Construct the root vdev to pass to zpool_vdev_attach().  While adding
395 	 * the entire vdev structure is harmless, we construct a reduced set of
396 	 * path/physpath/wholedisk to keep it simple.
397 	 */
398 	if (nvlist_alloc(&nvroot, NV_UNIQUE_NAME, 0) != 0) {
399 		zed_log_msg(LOG_WARNING, "zfs_mod: nvlist_alloc out of memory");
400 		return;
401 	}
402 	if (nvlist_alloc(&newvd, NV_UNIQUE_NAME, 0) != 0) {
403 		zed_log_msg(LOG_WARNING, "zfs_mod: nvlist_alloc out of memory");
404 		nvlist_free(nvroot);
405 		return;
406 	}
407 
408 	if (nvlist_add_string(newvd, ZPOOL_CONFIG_TYPE, VDEV_TYPE_DISK) != 0 ||
409 	    nvlist_add_string(newvd, ZPOOL_CONFIG_PATH, path) != 0 ||
410 	    nvlist_add_string(newvd, ZPOOL_CONFIG_DEVID, new_devid) != 0 ||
411 	    (physpath != NULL && nvlist_add_string(newvd,
412 	    ZPOOL_CONFIG_PHYS_PATH, physpath) != 0) ||
413 	    (enc_sysfs_path != NULL && nvlist_add_string(newvd,
414 	    ZPOOL_CONFIG_VDEV_ENC_SYSFS_PATH, enc_sysfs_path) != 0) ||
415 	    nvlist_add_uint64(newvd, ZPOOL_CONFIG_WHOLE_DISK, wholedisk) != 0 ||
416 	    nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT) != 0 ||
417 	    nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN, &newvd,
418 	    1) != 0) {
419 		zed_log_msg(LOG_WARNING, "zfs_mod: unable to add nvlist pairs");
420 		nvlist_free(newvd);
421 		nvlist_free(nvroot);
422 		return;
423 	}
424 
425 	nvlist_free(newvd);
426 
427 	/*
428 	 * Wait for udev to verify the links exist, then auto-replace
429 	 * the leaf disk at same physical location.
430 	 */
431 	if (zpool_label_disk_wait(path, 3000) != 0) {
432 		zed_log_msg(LOG_WARNING, "zfs_mod: expected replacement "
433 		    "disk %s is missing", path);
434 		nvlist_free(nvroot);
435 		return;
436 	}
437 
438 	ret = zpool_vdev_attach(zhp, fullpath, path, nvroot, B_TRUE, B_FALSE);
439 
440 	zed_log_msg(LOG_INFO, "  zpool_vdev_replace: %s with %s (%s)",
441 	    fullpath, path, (ret == 0) ? "no errors" :
442 	    libzfs_error_description(g_zfshdl));
443 
444 	nvlist_free(nvroot);
445 }
446 
447 /*
448  * Utility functions to find a vdev matching given criteria.
449  */
450 typedef struct dev_data {
451 	const char		*dd_compare;
452 	const char		*dd_prop;
453 	zfs_process_func_t	dd_func;
454 	boolean_t		dd_found;
455 	boolean_t		dd_islabeled;
456 	uint64_t		dd_pool_guid;
457 	uint64_t		dd_vdev_guid;
458 	const char		*dd_new_devid;
459 } dev_data_t;
460 
461 static void
462 zfs_iter_vdev(zpool_handle_t *zhp, nvlist_t *nvl, void *data)
463 {
464 	dev_data_t *dp = data;
465 	char *path = NULL;
466 	uint_t c, children;
467 	nvlist_t **child;
468 
469 	/*
470 	 * First iterate over any children.
471 	 */
472 	if (nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN,
473 	    &child, &children) == 0) {
474 		for (c = 0; c < children; c++)
475 			zfs_iter_vdev(zhp, child[c], data);
476 	}
477 
478 	/*
479 	 * Iterate over any spares and cache devices
480 	 */
481 	if (nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_SPARES,
482 	    &child, &children) == 0) {
483 		for (c = 0; c < children; c++)
484 			zfs_iter_vdev(zhp, child[c], data);
485 	}
486 	if (nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_L2CACHE,
487 	    &child, &children) == 0) {
488 		for (c = 0; c < children; c++)
489 			zfs_iter_vdev(zhp, child[c], data);
490 	}
491 
492 	/* once a vdev was matched and processed there is nothing left to do */
493 	if (dp->dd_found)
494 		return;
495 
496 	/*
497 	 * Match by GUID if available otherwise fallback to devid or physical
498 	 */
499 	if (dp->dd_vdev_guid != 0) {
500 		uint64_t guid;
501 
502 		if (nvlist_lookup_uint64(nvl, ZPOOL_CONFIG_GUID,
503 		    &guid) != 0 || guid != dp->dd_vdev_guid) {
504 			return;
505 		}
506 		zed_log_msg(LOG_INFO, "  zfs_iter_vdev: matched on %llu", guid);
507 		dp->dd_found = B_TRUE;
508 
509 	} else if (dp->dd_compare != NULL) {
510 		/*
511 		 * NOTE: On Linux there is an event for partition, so unlike
512 		 * illumos, substring matching is not required to accommodate
513 		 * the partition suffix. An exact match will be present in
514 		 * the dp->dd_compare value.
515 		 */
516 		if (nvlist_lookup_string(nvl, dp->dd_prop, &path) != 0 ||
517 		    strcmp(dp->dd_compare, path) != 0)
518 			return;
519 
520 		zed_log_msg(LOG_INFO, "  zfs_iter_vdev: matched %s on %s",
521 		    dp->dd_prop, path);
522 		dp->dd_found = B_TRUE;
523 
524 		/* pass the new devid for use by replacing code */
525 		if (dp->dd_new_devid != NULL) {
526 			(void) nvlist_add_string(nvl, "new_devid",
527 			    dp->dd_new_devid);
528 		}
529 	}
530 
531 	(dp->dd_func)(zhp, nvl, dp->dd_islabeled);
532 }
533 
534 static void
535 zfs_enable_ds(void *arg)
536 {
537 	unavailpool_t *pool = (unavailpool_t *)arg;
538 
539 	(void) zpool_enable_datasets(pool->uap_zhp, NULL, 0);
540 	zpool_close(pool->uap_zhp);
541 	free(pool);
542 }
543 
544 static int
545 zfs_iter_pool(zpool_handle_t *zhp, void *data)
546 {
547 	nvlist_t *config, *nvl;
548 	dev_data_t *dp = data;
549 	uint64_t pool_guid;
550 	unavailpool_t *pool;
551 
552 	zed_log_msg(LOG_INFO, "zfs_iter_pool: evaluating vdevs on %s (by %s)",
553 	    zpool_get_name(zhp), dp->dd_vdev_guid ? "GUID" : dp->dd_prop);
554 
555 	/*
556 	 * For each vdev in this pool, look for a match to apply dd_func
557 	 */
558 	if ((config = zpool_get_config(zhp, NULL)) != NULL) {
559 		if (dp->dd_pool_guid == 0 ||
560 		    (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
561 		    &pool_guid) == 0 && pool_guid == dp->dd_pool_guid)) {
562 			(void) nvlist_lookup_nvlist(config,
563 			    ZPOOL_CONFIG_VDEV_TREE, &nvl);
564 			zfs_iter_vdev(zhp, nvl, data);
565 		}
566 	}
567 
568 	/*
569 	 * if this pool was originally unavailable,
570 	 * then enable its datasets asynchronously
571 	 */
572 	if (g_enumeration_done)  {
573 		for (pool = list_head(&g_pool_list); pool != NULL;
574 		    pool = list_next(&g_pool_list, pool)) {
575 
576 			if (strcmp(zpool_get_name(zhp),
577 			    zpool_get_name(pool->uap_zhp)))
578 				continue;
579 			if (zfs_toplevel_state(zhp) >= VDEV_STATE_DEGRADED) {
580 				list_remove(&g_pool_list, pool);
581 				(void) tpool_dispatch(g_tpool, zfs_enable_ds,
582 				    pool);
583 				break;
584 			}
585 		}
586 	}
587 
588 	zpool_close(zhp);
589 	return (dp->dd_found);	/* cease iteration after a match */
590 }
591 
592 /*
593  * Given a physical device location, iterate over all
594  * (pool, vdev) pairs which correspond to that location.
595  */
596 static boolean_t
597 devphys_iter(const char *physical, const char *devid, zfs_process_func_t func,
598     boolean_t is_slice)
599 {
600 	dev_data_t data = { 0 };
601 
602 	data.dd_compare = physical;
603 	data.dd_func = func;
604 	data.dd_prop = ZPOOL_CONFIG_PHYS_PATH;
605 	data.dd_found = B_FALSE;
606 	data.dd_islabeled = is_slice;
607 	data.dd_new_devid = devid;	/* used by auto replace code */
608 
609 	(void) zpool_iter(g_zfshdl, zfs_iter_pool, &data);
610 
611 	return (data.dd_found);
612 }
613 
614 /*
615  * Given a device identifier, find any vdevs with a matching devid.
616  * On Linux we can match devid directly which is always a whole disk.
617  */
618 static boolean_t
619 devid_iter(const char *devid, zfs_process_func_t func, boolean_t is_slice)
620 {
621 	dev_data_t data = { 0 };
622 
623 	data.dd_compare = devid;
624 	data.dd_func = func;
625 	data.dd_prop = ZPOOL_CONFIG_DEVID;
626 	data.dd_found = B_FALSE;
627 	data.dd_islabeled = is_slice;
628 	data.dd_new_devid = devid;
629 
630 	(void) zpool_iter(g_zfshdl, zfs_iter_pool, &data);
631 
632 	return (data.dd_found);
633 }
634 
635 /*
636  * Handle a EC_DEV_ADD.ESC_DISK event.
637  *
638  * illumos
639  *	Expects: DEV_PHYS_PATH string in schema
640  *	Matches: vdev's ZPOOL_CONFIG_PHYS_PATH or ZPOOL_CONFIG_DEVID
641  *
642  *      path: '/dev/dsk/c0t1d0s0' (persistent)
643  *     devid: 'id1,sd@SATA_____Hitachi_HDS72101______JP2940HZ3H74MC/a'
644  * phys_path: '/pci@0,0/pci103c,1609@11/disk@1,0:a'
645  *
646  * linux
647  *	provides: DEV_PHYS_PATH and DEV_IDENTIFIER strings in schema
648  *	Matches: vdev's ZPOOL_CONFIG_PHYS_PATH or ZPOOL_CONFIG_DEVID
649  *
650  *      path: '/dev/sdc1' (not persistent)
651  *     devid: 'ata-SAMSUNG_HD204UI_S2HGJD2Z805891-part1'
652  * phys_path: 'pci-0000:04:00.0-sas-0x4433221106000000-lun-0'
653  */
654 static int
655 zfs_deliver_add(nvlist_t *nvl, boolean_t is_lofi)
656 {
657 	char *devpath = NULL, *devid;
658 	boolean_t is_slice;
659 
660 	/*
661 	 * Expecting a devid string and an optional physical location
662 	 */
663 	if (nvlist_lookup_string(nvl, DEV_IDENTIFIER, &devid) != 0)
664 		return (-1);
665 
666 	(void) nvlist_lookup_string(nvl, DEV_PHYS_PATH, &devpath);
667 
668 	is_slice = (nvlist_lookup_boolean(nvl, DEV_IS_PART) == 0);
669 
670 	zed_log_msg(LOG_INFO, "zfs_deliver_add: adding %s (%s) (is_slice %d)",
671 	    devid, devpath ? devpath : "NULL", is_slice);
672 
673 	/*
674 	 * Iterate over all vdevs looking for a match in the following order:
675 	 * 1. ZPOOL_CONFIG_DEVID (identifies the unique disk)
676 	 * 2. ZPOOL_CONFIG_PHYS_PATH (identifies disk physical location).
677 	 *
678 	 * For disks, we only want to pay attention to vdevs marked as whole
679 	 * disks or are a multipath device.
680 	 */
681 	if (!devid_iter(devid, zfs_process_add, is_slice) && devpath != NULL)
682 		(void) devphys_iter(devpath, devid, zfs_process_add, is_slice);
683 
684 	return (0);
685 }
686 
687 /*
688  * Called when we receive a VDEV_CHECK event, which indicates a device could not
689  * be opened during initial pool open, but the autoreplace property was set on
690  * the pool.  In this case, we treat it as if it were an add event.
691  */
692 static int
693 zfs_deliver_check(nvlist_t *nvl)
694 {
695 	dev_data_t data = { 0 };
696 
697 	if (nvlist_lookup_uint64(nvl, ZFS_EV_POOL_GUID,
698 	    &data.dd_pool_guid) != 0 ||
699 	    nvlist_lookup_uint64(nvl, ZFS_EV_VDEV_GUID,
700 	    &data.dd_vdev_guid) != 0 ||
701 	    data.dd_vdev_guid == 0)
702 		return (0);
703 
704 	zed_log_msg(LOG_INFO, "zfs_deliver_check: pool '%llu', vdev %llu",
705 	    data.dd_pool_guid, data.dd_vdev_guid);
706 
707 	data.dd_func = zfs_process_add;
708 
709 	(void) zpool_iter(g_zfshdl, zfs_iter_pool, &data);
710 
711 	return (0);
712 }
713 
714 static int
715 zfsdle_vdev_online(zpool_handle_t *zhp, void *data)
716 {
717 	char *devname = data;
718 	boolean_t avail_spare, l2cache;
719 	nvlist_t *tgt;
720 	int error;
721 
722 	zed_log_msg(LOG_INFO, "zfsdle_vdev_online: searching for '%s' in '%s'",
723 	    devname, zpool_get_name(zhp));
724 
725 	if ((tgt = zpool_find_vdev_by_physpath(zhp, devname,
726 	    &avail_spare, &l2cache, NULL)) != NULL) {
727 		char *path, fullpath[MAXPATHLEN];
728 		uint64_t wholedisk;
729 
730 		error = nvlist_lookup_string(tgt, ZPOOL_CONFIG_PATH, &path);
731 		if (error) {
732 			zpool_close(zhp);
733 			return (0);
734 		}
735 
736 		error = nvlist_lookup_uint64(tgt, ZPOOL_CONFIG_WHOLE_DISK,
737 		    &wholedisk);
738 		if (error)
739 			wholedisk = 0;
740 
741 		if (wholedisk) {
742 			path = strrchr(path, '/');
743 			if (path != NULL) {
744 				path = zfs_strip_partition(path + 1);
745 				if (path == NULL) {
746 					zpool_close(zhp);
747 					return (0);
748 				}
749 			} else {
750 				zpool_close(zhp);
751 				return (0);
752 			}
753 
754 			(void) strlcpy(fullpath, path, sizeof (fullpath));
755 			free(path);
756 
757 			/*
758 			 * We need to reopen the pool associated with this
759 			 * device so that the kernel can update the size of
760 			 * the expanded device.  When expanding there is no
761 			 * need to restart the scrub from the beginning.
762 			 */
763 			boolean_t scrub_restart = B_FALSE;
764 			(void) zpool_reopen_one(zhp, &scrub_restart);
765 		} else {
766 			(void) strlcpy(fullpath, path, sizeof (fullpath));
767 		}
768 
769 		if (zpool_get_prop_int(zhp, ZPOOL_PROP_AUTOEXPAND, NULL)) {
770 			vdev_state_t newstate;
771 
772 			if (zpool_get_state(zhp) != POOL_STATE_UNAVAIL) {
773 				error = zpool_vdev_online(zhp, fullpath, 0,
774 				    &newstate);
775 				zed_log_msg(LOG_INFO, "zfsdle_vdev_online: "
776 				    "setting device '%s' to ONLINE state "
777 				    "in pool '%s': %d", fullpath,
778 				    zpool_get_name(zhp), error);
779 			}
780 		}
781 		zpool_close(zhp);
782 		return (1);
783 	}
784 	zpool_close(zhp);
785 	return (0);
786 }
787 
788 /*
789  * This function handles the ESC_DEV_DLE device change event.  Use the
790  * provided vdev guid when looking up a disk or partition, when the guid
791  * is not present assume the entire disk is owned by ZFS and append the
792  * expected -part1 partition information then lookup by physical path.
793  */
794 static int
795 zfs_deliver_dle(nvlist_t *nvl)
796 {
797 	char *devname, name[MAXPATHLEN];
798 	uint64_t guid;
799 
800 	if (nvlist_lookup_uint64(nvl, ZFS_EV_VDEV_GUID, &guid) == 0) {
801 		sprintf(name, "%llu", (u_longlong_t)guid);
802 	} else if (nvlist_lookup_string(nvl, DEV_PHYS_PATH, &devname) == 0) {
803 		strlcpy(name, devname, MAXPATHLEN);
804 		zfs_append_partition(name, MAXPATHLEN);
805 	} else {
806 		zed_log_msg(LOG_INFO, "zfs_deliver_dle: no guid or physpath");
807 	}
808 
809 	if (zpool_iter(g_zfshdl, zfsdle_vdev_online, name) != 1) {
810 		zed_log_msg(LOG_INFO, "zfs_deliver_dle: device '%s' not "
811 		    "found", name);
812 		return (1);
813 	}
814 
815 	return (0);
816 }
817 
818 /*
819  * syseventd daemon module event handler
820  *
821  * Handles syseventd daemon zfs device related events:
822  *
823  *	EC_DEV_ADD.ESC_DISK
824  *	EC_DEV_STATUS.ESC_DEV_DLE
825  *	EC_ZFS.ESC_ZFS_VDEV_CHECK
826  *
827  * Note: assumes only one thread active at a time (not thread safe)
828  */
829 static int
830 zfs_slm_deliver_event(const char *class, const char *subclass, nvlist_t *nvl)
831 {
832 	int ret;
833 	boolean_t is_lofi = B_FALSE, is_check = B_FALSE, is_dle = B_FALSE;
834 
835 	if (strcmp(class, EC_DEV_ADD) == 0) {
836 		/*
837 		 * We're mainly interested in disk additions, but we also listen
838 		 * for new loop devices, to allow for simplified testing.
839 		 */
840 		if (strcmp(subclass, ESC_DISK) == 0)
841 			is_lofi = B_FALSE;
842 		else if (strcmp(subclass, ESC_LOFI) == 0)
843 			is_lofi = B_TRUE;
844 		else
845 			return (0);
846 
847 		is_check = B_FALSE;
848 	} else if (strcmp(class, EC_ZFS) == 0 &&
849 	    strcmp(subclass, ESC_ZFS_VDEV_CHECK) == 0) {
850 		/*
851 		 * This event signifies that a device failed to open
852 		 * during pool load, but the 'autoreplace' property was
853 		 * set, so we should pretend it's just been added.
854 		 */
855 		is_check = B_TRUE;
856 	} else if (strcmp(class, EC_DEV_STATUS) == 0 &&
857 	    strcmp(subclass, ESC_DEV_DLE) == 0) {
858 		is_dle = B_TRUE;
859 	} else {
860 		return (0);
861 	}
862 
863 	if (is_dle)
864 		ret = zfs_deliver_dle(nvl);
865 	else if (is_check)
866 		ret = zfs_deliver_check(nvl);
867 	else
868 		ret = zfs_deliver_add(nvl, is_lofi);
869 
870 	return (ret);
871 }
872 
873 /*ARGSUSED*/
874 static void *
875 zfs_enum_pools(void *arg)
876 {
877 	(void) zpool_iter(g_zfshdl, zfs_unavail_pool, (void *)&g_pool_list);
878 	/*
879 	 * Linux - instead of using a thread pool, each list entry
880 	 * will spawn a thread when an unavailable pool transitions
881 	 * to available. zfs_slm_fini will wait for these threads.
882 	 */
883 	g_enumeration_done = B_TRUE;
884 	return (NULL);
885 }
886 
887 /*
888  * called from zed daemon at startup
889  *
890  * sent messages from zevents or udev monitor
891  *
892  * For now, each agent has its own libzfs instance
893  */
894 int
895 zfs_slm_init()
896 {
897 	if ((g_zfshdl = libzfs_init()) == NULL)
898 		return (-1);
899 
900 	/*
901 	 * collect a list of unavailable pools (asynchronously,
902 	 * since this can take a while)
903 	 */
904 	list_create(&g_pool_list, sizeof (struct unavailpool),
905 	    offsetof(struct unavailpool, uap_node));
906 
907 	if (pthread_create(&g_zfs_tid, NULL, zfs_enum_pools, NULL) != 0) {
908 		list_destroy(&g_pool_list);
909 		libzfs_fini(g_zfshdl);
910 		return (-1);
911 	}
912 
913 	list_create(&g_device_list, sizeof (struct pendingdev),
914 	    offsetof(struct pendingdev, pd_node));
915 
916 	return (0);
917 }
918 
919 void
920 zfs_slm_fini()
921 {
922 	unavailpool_t *pool;
923 	pendingdev_t *device;
924 
925 	/* wait for zfs_enum_pools thread to complete */
926 	(void) pthread_join(g_zfs_tid, NULL);
927 	/* destroy the thread pool */
928 	if (g_tpool != NULL) {
929 		tpool_wait(g_tpool);
930 		tpool_destroy(g_tpool);
931 	}
932 
933 	while ((pool = (list_head(&g_pool_list))) != NULL) {
934 		list_remove(&g_pool_list, pool);
935 		zpool_close(pool->uap_zhp);
936 		free(pool);
937 	}
938 	list_destroy(&g_pool_list);
939 
940 	while ((device = (list_head(&g_device_list))) != NULL) {
941 		list_remove(&g_device_list, device);
942 		free(device);
943 	}
944 	list_destroy(&g_device_list);
945 
946 	libzfs_fini(g_zfshdl);
947 }
948 
949 void
950 zfs_slm_event(const char *class, const char *subclass, nvlist_t *nvl)
951 {
952 	zed_log_msg(LOG_INFO, "zfs_slm_event: %s.%s", class, subclass);
953 	(void) zfs_slm_deliver_event(class, subclass, nvl);
954 }
955