xref: /freebsd/sys/contrib/openzfs/module/zfs/zfs_fm.c (revision 725a9f47324d42037db93c27ceb40d4956872f3e)
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 https://opensource.org/licenses/CDDL-1.0.
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * Copyright (c) 2012,2021 by Delphix. All rights reserved.
28  */
29 
30 #include <sys/spa.h>
31 #include <sys/spa_impl.h>
32 #include <sys/vdev.h>
33 #include <sys/vdev_impl.h>
34 #include <sys/zio.h>
35 #include <sys/zio_checksum.h>
36 
37 #include <sys/fm/fs/zfs.h>
38 #include <sys/fm/protocol.h>
39 #include <sys/fm/util.h>
40 #include <sys/sysevent.h>
41 
42 /*
43  * This general routine is responsible for generating all the different ZFS
44  * ereports.  The payload is dependent on the class, and which arguments are
45  * supplied to the function:
46  *
47  * 	EREPORT			POOL	VDEV	IO
48  * 	block			X	X	X
49  * 	data			X		X
50  * 	device			X	X
51  * 	pool			X
52  *
53  * If we are in a loading state, all errors are chained together by the same
54  * SPA-wide ENA (Error Numeric Association).
55  *
56  * For isolated I/O requests, we get the ENA from the zio_t. The propagation
57  * gets very complicated due to RAID-Z, gang blocks, and vdev caching.  We want
58  * to chain together all ereports associated with a logical piece of data.  For
59  * read I/Os, there  are basically three 'types' of I/O, which form a roughly
60  * layered diagram:
61  *
62  * 	+---------------+
63  * 	| Aggregate I/O |	No associated logical data or device
64  * 	+---------------+
65  *              |
66  *              V
67  * 	+---------------+	Reads associated with a piece of logical data.
68  * 	|   Read I/O    |	This includes reads on behalf of RAID-Z,
69  * 	+---------------+       mirrors, gang blocks, retries, etc.
70  *              |
71  *              V
72  * 	+---------------+	Reads associated with a particular device, but
73  * 	| Physical I/O  |	no logical data.  Issued as part of vdev caching
74  * 	+---------------+	and I/O aggregation.
75  *
76  * Note that 'physical I/O' here is not the same terminology as used in the rest
77  * of ZIO.  Typically, 'physical I/O' simply means that there is no attached
78  * blockpointer.  But I/O with no associated block pointer can still be related
79  * to a logical piece of data (i.e. RAID-Z requests).
80  *
81  * Purely physical I/O always have unique ENAs.  They are not related to a
82  * particular piece of logical data, and therefore cannot be chained together.
83  * We still generate an ereport, but the DE doesn't correlate it with any
84  * logical piece of data.  When such an I/O fails, the delegated I/O requests
85  * will issue a retry, which will trigger the 'real' ereport with the correct
86  * ENA.
87  *
88  * We keep track of the ENA for a ZIO chain through the 'io_logical' member.
89  * When a new logical I/O is issued, we set this to point to itself.  Child I/Os
90  * then inherit this pointer, so that when it is first set subsequent failures
91  * will use the same ENA.  For vdev cache fill and queue aggregation I/O,
92  * this pointer is set to NULL, and no ereport will be generated (since it
93  * doesn't actually correspond to any particular device or piece of data,
94  * and the caller will always retry without caching or queueing anyway).
95  *
96  * For checksum errors, we want to include more information about the actual
97  * error which occurs.  Accordingly, we build an ereport when the error is
98  * noticed, but instead of sending it in immediately, we hang it off of the
99  * io_cksum_report field of the logical IO.  When the logical IO completes
100  * (successfully or not), zfs_ereport_finish_checksum() is called with the
101  * good and bad versions of the buffer (if available), and we annotate the
102  * ereport with information about the differences.
103  */
104 
105 #ifdef _KERNEL
106 /*
107  * Duplicate ereport Detection
108  *
109  * Some ereports are retained momentarily for detecting duplicates.  These
110  * are kept in a recent_events_node_t in both a time-ordered list and an AVL
111  * tree of recent unique ereports.
112  *
113  * The lifespan of these recent ereports is bounded (15 mins) and a cleaner
114  * task is used to purge stale entries.
115  */
116 static list_t recent_events_list;
117 static avl_tree_t recent_events_tree;
118 static kmutex_t recent_events_lock;
119 static taskqid_t recent_events_cleaner_tqid;
120 
121 /*
122  * Each node is about 128 bytes so 2,000 would consume 1/4 MiB.
123  *
124  * This setting can be changed dynamically and setting it to zero
125  * disables duplicate detection.
126  */
127 static unsigned int zfs_zevent_retain_max = 2000;
128 
129 /*
130  * The lifespan for a recent ereport entry. The default of 15 minutes is
131  * intended to outlive the zfs diagnosis engine's threshold of 10 errors
132  * over a period of 10 minutes.
133  */
134 static unsigned int zfs_zevent_retain_expire_secs = 900;
135 
136 typedef enum zfs_subclass {
137 	ZSC_IO,
138 	ZSC_DATA,
139 	ZSC_CHECKSUM
140 } zfs_subclass_t;
141 
142 typedef struct {
143 	/* common criteria */
144 	uint64_t	re_pool_guid;
145 	uint64_t	re_vdev_guid;
146 	int		re_io_error;
147 	uint64_t	re_io_size;
148 	uint64_t	re_io_offset;
149 	zfs_subclass_t	re_subclass;
150 	zio_priority_t	re_io_priority;
151 
152 	/* logical zio criteria (optional) */
153 	zbookmark_phys_t re_io_bookmark;
154 
155 	/* internal state */
156 	avl_node_t	re_tree_link;
157 	list_node_t	re_list_link;
158 	uint64_t	re_timestamp;
159 } recent_events_node_t;
160 
161 static int
162 recent_events_compare(const void *a, const void *b)
163 {
164 	const recent_events_node_t *node1 = a;
165 	const recent_events_node_t *node2 = b;
166 	int cmp;
167 
168 	/*
169 	 * The comparison order here is somewhat arbitrary.
170 	 * What's important is that if every criteria matches, then it
171 	 * is a duplicate (i.e. compare returns 0)
172 	 */
173 	if ((cmp = TREE_CMP(node1->re_subclass, node2->re_subclass)) != 0)
174 		return (cmp);
175 	if ((cmp = TREE_CMP(node1->re_pool_guid, node2->re_pool_guid)) != 0)
176 		return (cmp);
177 	if ((cmp = TREE_CMP(node1->re_vdev_guid, node2->re_vdev_guid)) != 0)
178 		return (cmp);
179 	if ((cmp = TREE_CMP(node1->re_io_error, node2->re_io_error)) != 0)
180 		return (cmp);
181 	if ((cmp = TREE_CMP(node1->re_io_priority, node2->re_io_priority)) != 0)
182 		return (cmp);
183 	if ((cmp = TREE_CMP(node1->re_io_size, node2->re_io_size)) != 0)
184 		return (cmp);
185 	if ((cmp = TREE_CMP(node1->re_io_offset, node2->re_io_offset)) != 0)
186 		return (cmp);
187 
188 	const zbookmark_phys_t *zb1 = &node1->re_io_bookmark;
189 	const zbookmark_phys_t *zb2 = &node2->re_io_bookmark;
190 
191 	if ((cmp = TREE_CMP(zb1->zb_objset, zb2->zb_objset)) != 0)
192 		return (cmp);
193 	if ((cmp = TREE_CMP(zb1->zb_object, zb2->zb_object)) != 0)
194 		return (cmp);
195 	if ((cmp = TREE_CMP(zb1->zb_level, zb2->zb_level)) != 0)
196 		return (cmp);
197 	if ((cmp = TREE_CMP(zb1->zb_blkid, zb2->zb_blkid)) != 0)
198 		return (cmp);
199 
200 	return (0);
201 }
202 
203 /*
204  * workaround: vdev properties don't have inheritance
205  */
206 static uint64_t
207 vdev_prop_get_inherited(vdev_t *vd, vdev_prop_t prop)
208 {
209 	uint64_t propdef, propval;
210 
211 	propdef = vdev_prop_default_numeric(prop);
212 	switch (prop) {
213 		case VDEV_PROP_CHECKSUM_N:
214 			propval = vd->vdev_checksum_n;
215 			break;
216 		case VDEV_PROP_CHECKSUM_T:
217 			propval = vd->vdev_checksum_t;
218 			break;
219 		case VDEV_PROP_IO_N:
220 			propval = vd->vdev_io_n;
221 			break;
222 		case VDEV_PROP_IO_T:
223 			propval = vd->vdev_io_t;
224 			break;
225 		case VDEV_PROP_SLOW_IO_N:
226 			propval = vd->vdev_slow_io_n;
227 			break;
228 		case VDEV_PROP_SLOW_IO_T:
229 			propval = vd->vdev_slow_io_t;
230 			break;
231 		default:
232 			propval = propdef;
233 			break;
234 	}
235 
236 	if (propval != propdef)
237 		return (propval);
238 
239 	if (vd->vdev_parent == NULL)
240 		return (propdef);
241 
242 	return (vdev_prop_get_inherited(vd->vdev_parent, prop));
243 }
244 
245 static void zfs_ereport_schedule_cleaner(void);
246 
247 /*
248  * background task to clean stale recent event nodes.
249  */
250 static void
251 zfs_ereport_cleaner(void *arg)
252 {
253 	recent_events_node_t *entry;
254 	uint64_t now = gethrtime();
255 
256 	/*
257 	 * purge expired entries
258 	 */
259 	mutex_enter(&recent_events_lock);
260 	while ((entry = list_tail(&recent_events_list)) != NULL) {
261 		uint64_t age = NSEC2SEC(now - entry->re_timestamp);
262 		if (age <= zfs_zevent_retain_expire_secs)
263 			break;
264 
265 		/* remove expired node */
266 		avl_remove(&recent_events_tree, entry);
267 		list_remove(&recent_events_list, entry);
268 		kmem_free(entry, sizeof (*entry));
269 	}
270 
271 	/* Restart the cleaner if more entries remain */
272 	recent_events_cleaner_tqid = 0;
273 	if (!list_is_empty(&recent_events_list))
274 		zfs_ereport_schedule_cleaner();
275 
276 	mutex_exit(&recent_events_lock);
277 }
278 
279 static void
280 zfs_ereport_schedule_cleaner(void)
281 {
282 	ASSERT(MUTEX_HELD(&recent_events_lock));
283 
284 	uint64_t timeout = SEC2NSEC(zfs_zevent_retain_expire_secs + 1);
285 
286 	recent_events_cleaner_tqid = taskq_dispatch_delay(
287 	    system_delay_taskq, zfs_ereport_cleaner, NULL, TQ_SLEEP,
288 	    ddi_get_lbolt() + NSEC_TO_TICK(timeout));
289 }
290 
291 /*
292  * Clear entries for a given vdev or all vdevs in a pool when vdev == NULL
293  */
294 void
295 zfs_ereport_clear(spa_t *spa, vdev_t *vd)
296 {
297 	uint64_t vdev_guid, pool_guid;
298 
299 	ASSERT(vd != NULL || spa != NULL);
300 	if (vd == NULL) {
301 		vdev_guid = 0;
302 		pool_guid = spa_guid(spa);
303 	} else {
304 		vdev_guid = vd->vdev_guid;
305 		pool_guid = 0;
306 	}
307 
308 	mutex_enter(&recent_events_lock);
309 
310 	recent_events_node_t *next = list_head(&recent_events_list);
311 	while (next != NULL) {
312 		recent_events_node_t *entry = next;
313 
314 		next = list_next(&recent_events_list, next);
315 
316 		if (entry->re_vdev_guid == vdev_guid ||
317 		    entry->re_pool_guid == pool_guid) {
318 			avl_remove(&recent_events_tree, entry);
319 			list_remove(&recent_events_list, entry);
320 			kmem_free(entry, sizeof (*entry));
321 		}
322 	}
323 
324 	mutex_exit(&recent_events_lock);
325 }
326 
327 /*
328  * Check if an ereport would be a duplicate of one recently posted.
329  *
330  * An ereport is considered a duplicate if the set of criteria in
331  * recent_events_node_t all match.
332  *
333  * Only FM_EREPORT_ZFS_IO, FM_EREPORT_ZFS_DATA, and FM_EREPORT_ZFS_CHECKSUM
334  * are candidates for duplicate checking.
335  */
336 static boolean_t
337 zfs_ereport_is_duplicate(const char *subclass, spa_t *spa, vdev_t *vd,
338     const zbookmark_phys_t *zb, zio_t *zio, uint64_t offset, uint64_t size)
339 {
340 	recent_events_node_t search = {0}, *entry;
341 
342 	if (vd == NULL || zio == NULL)
343 		return (B_FALSE);
344 
345 	if (zfs_zevent_retain_max == 0)
346 		return (B_FALSE);
347 
348 	if (strcmp(subclass, FM_EREPORT_ZFS_IO) == 0)
349 		search.re_subclass = ZSC_IO;
350 	else if (strcmp(subclass, FM_EREPORT_ZFS_DATA) == 0)
351 		search.re_subclass = ZSC_DATA;
352 	else if (strcmp(subclass, FM_EREPORT_ZFS_CHECKSUM) == 0)
353 		search.re_subclass = ZSC_CHECKSUM;
354 	else
355 		return (B_FALSE);
356 
357 	search.re_pool_guid = spa_guid(spa);
358 	search.re_vdev_guid = vd->vdev_guid;
359 	search.re_io_error = zio->io_error;
360 	search.re_io_priority = zio->io_priority;
361 	/* if size is supplied use it over what's in zio */
362 	if (size) {
363 		search.re_io_size = size;
364 		search.re_io_offset = offset;
365 	} else {
366 		search.re_io_size = zio->io_size;
367 		search.re_io_offset = zio->io_offset;
368 	}
369 
370 	/* grab optional logical zio criteria */
371 	if (zb != NULL) {
372 		search.re_io_bookmark.zb_objset = zb->zb_objset;
373 		search.re_io_bookmark.zb_object = zb->zb_object;
374 		search.re_io_bookmark.zb_level = zb->zb_level;
375 		search.re_io_bookmark.zb_blkid = zb->zb_blkid;
376 	}
377 
378 	uint64_t now = gethrtime();
379 
380 	mutex_enter(&recent_events_lock);
381 
382 	/* check if we have seen this one recently */
383 	entry = avl_find(&recent_events_tree, &search, NULL);
384 	if (entry != NULL) {
385 		uint64_t age = NSEC2SEC(now - entry->re_timestamp);
386 
387 		/*
388 		 * There is still an active cleaner (since we're here).
389 		 * Reset the last seen time for this duplicate entry
390 		 * so that its lifespand gets extended.
391 		 */
392 		list_remove(&recent_events_list, entry);
393 		list_insert_head(&recent_events_list, entry);
394 		entry->re_timestamp = now;
395 
396 		zfs_zevent_track_duplicate();
397 		mutex_exit(&recent_events_lock);
398 
399 		return (age <= zfs_zevent_retain_expire_secs);
400 	}
401 
402 	if (avl_numnodes(&recent_events_tree) >= zfs_zevent_retain_max) {
403 		/* recycle oldest node */
404 		entry = list_tail(&recent_events_list);
405 		ASSERT(entry != NULL);
406 		list_remove(&recent_events_list, entry);
407 		avl_remove(&recent_events_tree, entry);
408 	} else {
409 		entry = kmem_alloc(sizeof (recent_events_node_t), KM_SLEEP);
410 	}
411 
412 	/* record this as a recent ereport */
413 	*entry = search;
414 	avl_add(&recent_events_tree, entry);
415 	list_insert_head(&recent_events_list, entry);
416 	entry->re_timestamp = now;
417 
418 	/* Start a cleaner if not already scheduled */
419 	if (recent_events_cleaner_tqid == 0)
420 		zfs_ereport_schedule_cleaner();
421 
422 	mutex_exit(&recent_events_lock);
423 	return (B_FALSE);
424 }
425 
426 void
427 zfs_zevent_post_cb(nvlist_t *nvl, nvlist_t *detector)
428 {
429 	if (nvl)
430 		fm_nvlist_destroy(nvl, FM_NVA_FREE);
431 
432 	if (detector)
433 		fm_nvlist_destroy(detector, FM_NVA_FREE);
434 }
435 
436 /*
437  * We want to rate limit ZIO delay, deadman, and checksum events so as to not
438  * flood zevent consumers when a disk is acting up.
439  *
440  * Returns 1 if we're ratelimiting, 0 if not.
441  */
442 static int
443 zfs_is_ratelimiting_event(const char *subclass, vdev_t *vd)
444 {
445 	int rc = 0;
446 	/*
447 	 * zfs_ratelimit() returns 1 if we're *not* ratelimiting and 0 if we
448 	 * are.  Invert it to get our return value.
449 	 */
450 	if (strcmp(subclass, FM_EREPORT_ZFS_DELAY) == 0) {
451 		rc = !zfs_ratelimit(&vd->vdev_delay_rl);
452 	} else if (strcmp(subclass, FM_EREPORT_ZFS_DEADMAN) == 0) {
453 		rc = !zfs_ratelimit(&vd->vdev_deadman_rl);
454 	} else if (strcmp(subclass, FM_EREPORT_ZFS_CHECKSUM) == 0) {
455 		rc = !zfs_ratelimit(&vd->vdev_checksum_rl);
456 	}
457 
458 	if (rc)	{
459 		/* We're rate limiting */
460 		fm_erpt_dropped_increment();
461 	}
462 
463 	return (rc);
464 }
465 
466 /*
467  * Return B_TRUE if the event actually posted, B_FALSE if not.
468  */
469 static boolean_t
470 zfs_ereport_start(nvlist_t **ereport_out, nvlist_t **detector_out,
471     const char *subclass, spa_t *spa, vdev_t *vd, const zbookmark_phys_t *zb,
472     zio_t *zio, uint64_t stateoroffset, uint64_t size)
473 {
474 	nvlist_t *ereport, *detector;
475 
476 	uint64_t ena;
477 	char class[64];
478 
479 	if ((ereport = fm_nvlist_create(NULL)) == NULL)
480 		return (B_FALSE);
481 
482 	if ((detector = fm_nvlist_create(NULL)) == NULL) {
483 		fm_nvlist_destroy(ereport, FM_NVA_FREE);
484 		return (B_FALSE);
485 	}
486 
487 	/*
488 	 * Serialize ereport generation
489 	 */
490 	mutex_enter(&spa->spa_errlist_lock);
491 
492 	/*
493 	 * Determine the ENA to use for this event.  If we are in a loading
494 	 * state, use a SPA-wide ENA.  Otherwise, if we are in an I/O state, use
495 	 * a root zio-wide ENA.  Otherwise, simply use a unique ENA.
496 	 */
497 	if (spa_load_state(spa) != SPA_LOAD_NONE) {
498 		if (spa->spa_ena == 0)
499 			spa->spa_ena = fm_ena_generate(0, FM_ENA_FMT1);
500 		ena = spa->spa_ena;
501 	} else if (zio != NULL && zio->io_logical != NULL) {
502 		if (zio->io_logical->io_ena == 0)
503 			zio->io_logical->io_ena =
504 			    fm_ena_generate(0, FM_ENA_FMT1);
505 		ena = zio->io_logical->io_ena;
506 	} else {
507 		ena = fm_ena_generate(0, FM_ENA_FMT1);
508 	}
509 
510 	/*
511 	 * Construct the full class, detector, and other standard FMA fields.
512 	 */
513 	(void) snprintf(class, sizeof (class), "%s.%s",
514 	    ZFS_ERROR_CLASS, subclass);
515 
516 	fm_fmri_zfs_set(detector, FM_ZFS_SCHEME_VERSION, spa_guid(spa),
517 	    vd != NULL ? vd->vdev_guid : 0);
518 
519 	fm_ereport_set(ereport, FM_EREPORT_VERSION, class, ena, detector, NULL);
520 
521 	/*
522 	 * Construct the per-ereport payload, depending on which parameters are
523 	 * passed in.
524 	 */
525 
526 	/*
527 	 * Generic payload members common to all ereports.
528 	 */
529 	fm_payload_set(ereport,
530 	    FM_EREPORT_PAYLOAD_ZFS_POOL, DATA_TYPE_STRING, spa_name(spa),
531 	    FM_EREPORT_PAYLOAD_ZFS_POOL_GUID, DATA_TYPE_UINT64, spa_guid(spa),
532 	    FM_EREPORT_PAYLOAD_ZFS_POOL_STATE, DATA_TYPE_UINT64,
533 	    (uint64_t)spa_state(spa),
534 	    FM_EREPORT_PAYLOAD_ZFS_POOL_CONTEXT, DATA_TYPE_INT32,
535 	    (int32_t)spa_load_state(spa), NULL);
536 
537 	fm_payload_set(ereport, FM_EREPORT_PAYLOAD_ZFS_POOL_FAILMODE,
538 	    DATA_TYPE_STRING,
539 	    spa_get_failmode(spa) == ZIO_FAILURE_MODE_WAIT ?
540 	    FM_EREPORT_FAILMODE_WAIT :
541 	    spa_get_failmode(spa) == ZIO_FAILURE_MODE_CONTINUE ?
542 	    FM_EREPORT_FAILMODE_CONTINUE : FM_EREPORT_FAILMODE_PANIC,
543 	    NULL);
544 
545 	if (vd != NULL) {
546 		vdev_t *pvd = vd->vdev_parent;
547 		vdev_queue_t *vq = &vd->vdev_queue;
548 		vdev_stat_t *vs = &vd->vdev_stat;
549 		vdev_t *spare_vd;
550 		uint64_t *spare_guids;
551 		char **spare_paths;
552 		int i, spare_count;
553 
554 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_ZFS_VDEV_GUID,
555 		    DATA_TYPE_UINT64, vd->vdev_guid,
556 		    FM_EREPORT_PAYLOAD_ZFS_VDEV_TYPE,
557 		    DATA_TYPE_STRING, vd->vdev_ops->vdev_op_type, NULL);
558 		if (vd->vdev_path != NULL)
559 			fm_payload_set(ereport,
560 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_PATH,
561 			    DATA_TYPE_STRING, vd->vdev_path, NULL);
562 		if (vd->vdev_devid != NULL)
563 			fm_payload_set(ereport,
564 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_DEVID,
565 			    DATA_TYPE_STRING, vd->vdev_devid, NULL);
566 		if (vd->vdev_fru != NULL)
567 			fm_payload_set(ereport,
568 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_FRU,
569 			    DATA_TYPE_STRING, vd->vdev_fru, NULL);
570 		if (vd->vdev_enc_sysfs_path != NULL)
571 			fm_payload_set(ereport,
572 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_ENC_SYSFS_PATH,
573 			    DATA_TYPE_STRING, vd->vdev_enc_sysfs_path, NULL);
574 		if (vd->vdev_ashift)
575 			fm_payload_set(ereport,
576 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_ASHIFT,
577 			    DATA_TYPE_UINT64, vd->vdev_ashift, NULL);
578 
579 		if (vq != NULL) {
580 			fm_payload_set(ereport,
581 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_COMP_TS,
582 			    DATA_TYPE_UINT64, vq->vq_io_complete_ts, NULL);
583 			fm_payload_set(ereport,
584 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_DELTA_TS,
585 			    DATA_TYPE_UINT64, vq->vq_io_delta_ts, NULL);
586 		}
587 
588 		if (vs != NULL) {
589 			fm_payload_set(ereport,
590 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_READ_ERRORS,
591 			    DATA_TYPE_UINT64, vs->vs_read_errors,
592 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_WRITE_ERRORS,
593 			    DATA_TYPE_UINT64, vs->vs_write_errors,
594 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_CKSUM_ERRORS,
595 			    DATA_TYPE_UINT64, vs->vs_checksum_errors,
596 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_DELAYS,
597 			    DATA_TYPE_UINT64, vs->vs_slow_ios,
598 			    NULL);
599 		}
600 
601 		if (pvd != NULL) {
602 			fm_payload_set(ereport,
603 			    FM_EREPORT_PAYLOAD_ZFS_PARENT_GUID,
604 			    DATA_TYPE_UINT64, pvd->vdev_guid,
605 			    FM_EREPORT_PAYLOAD_ZFS_PARENT_TYPE,
606 			    DATA_TYPE_STRING, pvd->vdev_ops->vdev_op_type,
607 			    NULL);
608 			if (pvd->vdev_path)
609 				fm_payload_set(ereport,
610 				    FM_EREPORT_PAYLOAD_ZFS_PARENT_PATH,
611 				    DATA_TYPE_STRING, pvd->vdev_path, NULL);
612 			if (pvd->vdev_devid)
613 				fm_payload_set(ereport,
614 				    FM_EREPORT_PAYLOAD_ZFS_PARENT_DEVID,
615 				    DATA_TYPE_STRING, pvd->vdev_devid, NULL);
616 		}
617 
618 		spare_count = spa->spa_spares.sav_count;
619 		spare_paths = kmem_zalloc(sizeof (char *) * spare_count,
620 		    KM_SLEEP);
621 		spare_guids = kmem_zalloc(sizeof (uint64_t) * spare_count,
622 		    KM_SLEEP);
623 
624 		for (i = 0; i < spare_count; i++) {
625 			spare_vd = spa->spa_spares.sav_vdevs[i];
626 			if (spare_vd) {
627 				spare_paths[i] = spare_vd->vdev_path;
628 				spare_guids[i] = spare_vd->vdev_guid;
629 			}
630 		}
631 
632 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_ZFS_VDEV_SPARE_PATHS,
633 		    DATA_TYPE_STRING_ARRAY, spare_count, spare_paths,
634 		    FM_EREPORT_PAYLOAD_ZFS_VDEV_SPARE_GUIDS,
635 		    DATA_TYPE_UINT64_ARRAY, spare_count, spare_guids, NULL);
636 
637 		kmem_free(spare_guids, sizeof (uint64_t) * spare_count);
638 		kmem_free(spare_paths, sizeof (char *) * spare_count);
639 	}
640 
641 	if (zio != NULL) {
642 		/*
643 		 * Payload common to all I/Os.
644 		 */
645 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_ZFS_ZIO_ERR,
646 		    DATA_TYPE_INT32, zio->io_error, NULL);
647 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_ZFS_ZIO_FLAGS,
648 		    DATA_TYPE_INT32, zio->io_flags, NULL);
649 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_ZFS_ZIO_STAGE,
650 		    DATA_TYPE_UINT32, zio->io_stage, NULL);
651 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_ZFS_ZIO_PIPELINE,
652 		    DATA_TYPE_UINT32, zio->io_pipeline, NULL);
653 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_ZFS_ZIO_DELAY,
654 		    DATA_TYPE_UINT64, zio->io_delay, NULL);
655 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_ZFS_ZIO_TIMESTAMP,
656 		    DATA_TYPE_UINT64, zio->io_timestamp, NULL);
657 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_ZFS_ZIO_DELTA,
658 		    DATA_TYPE_UINT64, zio->io_delta, NULL);
659 		fm_payload_set(ereport, FM_EREPORT_PAYLOAD_ZFS_ZIO_PRIORITY,
660 		    DATA_TYPE_UINT32, zio->io_priority, NULL);
661 
662 		/*
663 		 * If the 'size' parameter is non-zero, it indicates this is a
664 		 * RAID-Z or other I/O where the physical offset and length are
665 		 * provided for us, instead of within the zio_t.
666 		 */
667 		if (vd != NULL) {
668 			if (size)
669 				fm_payload_set(ereport,
670 				    FM_EREPORT_PAYLOAD_ZFS_ZIO_OFFSET,
671 				    DATA_TYPE_UINT64, stateoroffset,
672 				    FM_EREPORT_PAYLOAD_ZFS_ZIO_SIZE,
673 				    DATA_TYPE_UINT64, size, NULL);
674 			else
675 				fm_payload_set(ereport,
676 				    FM_EREPORT_PAYLOAD_ZFS_ZIO_OFFSET,
677 				    DATA_TYPE_UINT64, zio->io_offset,
678 				    FM_EREPORT_PAYLOAD_ZFS_ZIO_SIZE,
679 				    DATA_TYPE_UINT64, zio->io_size, NULL);
680 		}
681 	} else if (vd != NULL) {
682 		/*
683 		 * If we have a vdev but no zio, this is a device fault, and the
684 		 * 'stateoroffset' parameter indicates the previous state of the
685 		 * vdev.
686 		 */
687 		fm_payload_set(ereport,
688 		    FM_EREPORT_PAYLOAD_ZFS_PREV_STATE,
689 		    DATA_TYPE_UINT64, stateoroffset, NULL);
690 	}
691 
692 	/*
693 	 * Payload for I/Os with corresponding logical information.
694 	 */
695 	if (zb != NULL && (zio == NULL || zio->io_logical != NULL)) {
696 		fm_payload_set(ereport,
697 		    FM_EREPORT_PAYLOAD_ZFS_ZIO_OBJSET,
698 		    DATA_TYPE_UINT64, zb->zb_objset,
699 		    FM_EREPORT_PAYLOAD_ZFS_ZIO_OBJECT,
700 		    DATA_TYPE_UINT64, zb->zb_object,
701 		    FM_EREPORT_PAYLOAD_ZFS_ZIO_LEVEL,
702 		    DATA_TYPE_INT64, zb->zb_level,
703 		    FM_EREPORT_PAYLOAD_ZFS_ZIO_BLKID,
704 		    DATA_TYPE_UINT64, zb->zb_blkid, NULL);
705 	}
706 
707 	/*
708 	 * Payload for tuning the zed
709 	 */
710 	if (vd != NULL && strcmp(subclass, FM_EREPORT_ZFS_CHECKSUM) == 0) {
711 		uint64_t cksum_n, cksum_t;
712 
713 		cksum_n = vdev_prop_get_inherited(vd, VDEV_PROP_CHECKSUM_N);
714 		if (cksum_n != vdev_prop_default_numeric(VDEV_PROP_CHECKSUM_N))
715 			fm_payload_set(ereport,
716 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_CKSUM_N,
717 			    DATA_TYPE_UINT64,
718 			    cksum_n,
719 			    NULL);
720 
721 		cksum_t = vdev_prop_get_inherited(vd, VDEV_PROP_CHECKSUM_T);
722 		if (cksum_t != vdev_prop_default_numeric(VDEV_PROP_CHECKSUM_T))
723 			fm_payload_set(ereport,
724 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_CKSUM_T,
725 			    DATA_TYPE_UINT64,
726 			    cksum_t,
727 			    NULL);
728 	}
729 
730 	if (vd != NULL && strcmp(subclass, FM_EREPORT_ZFS_IO) == 0) {
731 		uint64_t io_n, io_t;
732 
733 		io_n = vdev_prop_get_inherited(vd, VDEV_PROP_IO_N);
734 		if (io_n != vdev_prop_default_numeric(VDEV_PROP_IO_N))
735 			fm_payload_set(ereport,
736 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_IO_N,
737 			    DATA_TYPE_UINT64,
738 			    io_n,
739 			    NULL);
740 
741 		io_t = vdev_prop_get_inherited(vd, VDEV_PROP_IO_T);
742 		if (io_t != vdev_prop_default_numeric(VDEV_PROP_IO_T))
743 			fm_payload_set(ereport,
744 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_IO_T,
745 			    DATA_TYPE_UINT64,
746 			    io_t,
747 			    NULL);
748 	}
749 
750 	if (vd != NULL && strcmp(subclass, FM_EREPORT_ZFS_DELAY) == 0) {
751 		uint64_t slow_io_n, slow_io_t;
752 
753 		slow_io_n = vdev_prop_get_inherited(vd, VDEV_PROP_SLOW_IO_N);
754 		if (slow_io_n != vdev_prop_default_numeric(VDEV_PROP_SLOW_IO_N))
755 			fm_payload_set(ereport,
756 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_SLOW_IO_N,
757 			    DATA_TYPE_UINT64,
758 			    slow_io_n,
759 			    NULL);
760 
761 		slow_io_t = vdev_prop_get_inherited(vd, VDEV_PROP_SLOW_IO_T);
762 		if (slow_io_t != vdev_prop_default_numeric(VDEV_PROP_SLOW_IO_T))
763 			fm_payload_set(ereport,
764 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_SLOW_IO_T,
765 			    DATA_TYPE_UINT64,
766 			    slow_io_t,
767 			    NULL);
768 	}
769 
770 	mutex_exit(&spa->spa_errlist_lock);
771 
772 	*ereport_out = ereport;
773 	*detector_out = detector;
774 	return (B_TRUE);
775 }
776 
777 /* if it's <= 128 bytes, save the corruption directly */
778 #define	ZFM_MAX_INLINE		(128 / sizeof (uint64_t))
779 
780 #define	MAX_RANGES		16
781 
782 typedef struct zfs_ecksum_info {
783 	/* inline arrays of bits set and cleared. */
784 	uint64_t zei_bits_set[ZFM_MAX_INLINE];
785 	uint64_t zei_bits_cleared[ZFM_MAX_INLINE];
786 
787 	/*
788 	 * for each range, the number of bits set and cleared.  The Hamming
789 	 * distance between the good and bad buffers is the sum of them all.
790 	 */
791 	uint32_t zei_range_sets[MAX_RANGES];
792 	uint32_t zei_range_clears[MAX_RANGES];
793 
794 	struct zei_ranges {
795 		uint32_t	zr_start;
796 		uint32_t	zr_end;
797 	} zei_ranges[MAX_RANGES];
798 
799 	size_t	zei_range_count;
800 	uint32_t zei_mingap;
801 	uint32_t zei_allowed_mingap;
802 
803 } zfs_ecksum_info_t;
804 
805 static void
806 update_bad_bits(uint64_t value_arg, uint32_t *count)
807 {
808 	size_t i;
809 	size_t bits = 0;
810 	uint64_t value = BE_64(value_arg);
811 
812 	/* We store the bits in big-endian (largest-first) order */
813 	for (i = 0; i < 64; i++) {
814 		if (value & (1ull << i))
815 			++bits;
816 	}
817 	/* update the count of bits changed */
818 	*count += bits;
819 }
820 
821 /*
822  * We've now filled up the range array, and need to increase "mingap" and
823  * shrink the range list accordingly.  zei_mingap is always the smallest
824  * distance between array entries, so we set the new_allowed_gap to be
825  * one greater than that.  We then go through the list, joining together
826  * any ranges which are closer than the new_allowed_gap.
827  *
828  * By construction, there will be at least one.  We also update zei_mingap
829  * to the new smallest gap, to prepare for our next invocation.
830  */
831 static void
832 zei_shrink_ranges(zfs_ecksum_info_t *eip)
833 {
834 	uint32_t mingap = UINT32_MAX;
835 	uint32_t new_allowed_gap = eip->zei_mingap + 1;
836 
837 	size_t idx, output;
838 	size_t max = eip->zei_range_count;
839 
840 	struct zei_ranges *r = eip->zei_ranges;
841 
842 	ASSERT3U(eip->zei_range_count, >, 0);
843 	ASSERT3U(eip->zei_range_count, <=, MAX_RANGES);
844 
845 	output = idx = 0;
846 	while (idx < max - 1) {
847 		uint32_t start = r[idx].zr_start;
848 		uint32_t end = r[idx].zr_end;
849 
850 		while (idx < max - 1) {
851 			idx++;
852 
853 			uint32_t nstart = r[idx].zr_start;
854 			uint32_t nend = r[idx].zr_end;
855 
856 			uint32_t gap = nstart - end;
857 			if (gap < new_allowed_gap) {
858 				end = nend;
859 				continue;
860 			}
861 			if (gap < mingap)
862 				mingap = gap;
863 			break;
864 		}
865 		r[output].zr_start = start;
866 		r[output].zr_end = end;
867 		output++;
868 	}
869 	ASSERT3U(output, <, eip->zei_range_count);
870 	eip->zei_range_count = output;
871 	eip->zei_mingap = mingap;
872 	eip->zei_allowed_mingap = new_allowed_gap;
873 }
874 
875 static void
876 zei_add_range(zfs_ecksum_info_t *eip, int start, int end)
877 {
878 	struct zei_ranges *r = eip->zei_ranges;
879 	size_t count = eip->zei_range_count;
880 
881 	if (count >= MAX_RANGES) {
882 		zei_shrink_ranges(eip);
883 		count = eip->zei_range_count;
884 	}
885 	if (count == 0) {
886 		eip->zei_mingap = UINT32_MAX;
887 		eip->zei_allowed_mingap = 1;
888 	} else {
889 		int gap = start - r[count - 1].zr_end;
890 
891 		if (gap < eip->zei_allowed_mingap) {
892 			r[count - 1].zr_end = end;
893 			return;
894 		}
895 		if (gap < eip->zei_mingap)
896 			eip->zei_mingap = gap;
897 	}
898 	r[count].zr_start = start;
899 	r[count].zr_end = end;
900 	eip->zei_range_count++;
901 }
902 
903 static size_t
904 zei_range_total_size(zfs_ecksum_info_t *eip)
905 {
906 	struct zei_ranges *r = eip->zei_ranges;
907 	size_t count = eip->zei_range_count;
908 	size_t result = 0;
909 	size_t idx;
910 
911 	for (idx = 0; idx < count; idx++)
912 		result += (r[idx].zr_end - r[idx].zr_start);
913 
914 	return (result);
915 }
916 
917 static zfs_ecksum_info_t *
918 annotate_ecksum(nvlist_t *ereport, zio_bad_cksum_t *info,
919     const abd_t *goodabd, const abd_t *badabd, size_t size,
920     boolean_t drop_if_identical)
921 {
922 	const uint64_t *good;
923 	const uint64_t *bad;
924 
925 	size_t nui64s = size / sizeof (uint64_t);
926 
927 	size_t inline_size;
928 	int no_inline = 0;
929 	size_t idx;
930 	size_t range;
931 
932 	size_t offset = 0;
933 	ssize_t start = -1;
934 
935 	zfs_ecksum_info_t *eip = kmem_zalloc(sizeof (*eip), KM_SLEEP);
936 
937 	/* don't do any annotation for injected checksum errors */
938 	if (info != NULL && info->zbc_injected)
939 		return (eip);
940 
941 	if (info != NULL && info->zbc_has_cksum) {
942 		fm_payload_set(ereport,
943 		    FM_EREPORT_PAYLOAD_ZFS_CKSUM_ALGO,
944 		    DATA_TYPE_STRING,
945 		    info->zbc_checksum_name,
946 		    NULL);
947 
948 		if (info->zbc_byteswapped) {
949 			fm_payload_set(ereport,
950 			    FM_EREPORT_PAYLOAD_ZFS_CKSUM_BYTESWAP,
951 			    DATA_TYPE_BOOLEAN, 1,
952 			    NULL);
953 		}
954 	}
955 
956 	if (badabd == NULL || goodabd == NULL)
957 		return (eip);
958 
959 	ASSERT3U(nui64s, <=, UINT32_MAX);
960 	ASSERT3U(size, ==, nui64s * sizeof (uint64_t));
961 	ASSERT3U(size, <=, SPA_MAXBLOCKSIZE);
962 	ASSERT3U(size, <=, UINT32_MAX);
963 
964 	good = (const uint64_t *) abd_borrow_buf_copy((abd_t *)goodabd, size);
965 	bad = (const uint64_t *) abd_borrow_buf_copy((abd_t *)badabd, size);
966 
967 	/* build up the range list by comparing the two buffers. */
968 	for (idx = 0; idx < nui64s; idx++) {
969 		if (good[idx] == bad[idx]) {
970 			if (start == -1)
971 				continue;
972 
973 			zei_add_range(eip, start, idx);
974 			start = -1;
975 		} else {
976 			if (start != -1)
977 				continue;
978 
979 			start = idx;
980 		}
981 	}
982 	if (start != -1)
983 		zei_add_range(eip, start, idx);
984 
985 	/* See if it will fit in our inline buffers */
986 	inline_size = zei_range_total_size(eip);
987 	if (inline_size > ZFM_MAX_INLINE)
988 		no_inline = 1;
989 
990 	/*
991 	 * If there is no change and we want to drop if the buffers are
992 	 * identical, do so.
993 	 */
994 	if (inline_size == 0 && drop_if_identical) {
995 		kmem_free(eip, sizeof (*eip));
996 		abd_return_buf((abd_t *)goodabd, (void *)good, size);
997 		abd_return_buf((abd_t *)badabd, (void *)bad, size);
998 		return (NULL);
999 	}
1000 
1001 	/*
1002 	 * Now walk through the ranges, filling in the details of the
1003 	 * differences.  Also convert our uint64_t-array offsets to byte
1004 	 * offsets.
1005 	 */
1006 	for (range = 0; range < eip->zei_range_count; range++) {
1007 		size_t start = eip->zei_ranges[range].zr_start;
1008 		size_t end = eip->zei_ranges[range].zr_end;
1009 
1010 		for (idx = start; idx < end; idx++) {
1011 			uint64_t set, cleared;
1012 
1013 			// bits set in bad, but not in good
1014 			set = ((~good[idx]) & bad[idx]);
1015 			// bits set in good, but not in bad
1016 			cleared = (good[idx] & (~bad[idx]));
1017 
1018 			if (!no_inline) {
1019 				ASSERT3U(offset, <, inline_size);
1020 				eip->zei_bits_set[offset] = set;
1021 				eip->zei_bits_cleared[offset] = cleared;
1022 				offset++;
1023 			}
1024 
1025 			update_bad_bits(set, &eip->zei_range_sets[range]);
1026 			update_bad_bits(cleared, &eip->zei_range_clears[range]);
1027 		}
1028 
1029 		/* convert to byte offsets */
1030 		eip->zei_ranges[range].zr_start	*= sizeof (uint64_t);
1031 		eip->zei_ranges[range].zr_end	*= sizeof (uint64_t);
1032 	}
1033 
1034 	abd_return_buf((abd_t *)goodabd, (void *)good, size);
1035 	abd_return_buf((abd_t *)badabd, (void *)bad, size);
1036 
1037 	eip->zei_allowed_mingap	*= sizeof (uint64_t);
1038 	inline_size		*= sizeof (uint64_t);
1039 
1040 	/* fill in ereport */
1041 	fm_payload_set(ereport,
1042 	    FM_EREPORT_PAYLOAD_ZFS_BAD_OFFSET_RANGES,
1043 	    DATA_TYPE_UINT32_ARRAY, 2 * eip->zei_range_count,
1044 	    (uint32_t *)eip->zei_ranges,
1045 	    FM_EREPORT_PAYLOAD_ZFS_BAD_RANGE_MIN_GAP,
1046 	    DATA_TYPE_UINT32, eip->zei_allowed_mingap,
1047 	    FM_EREPORT_PAYLOAD_ZFS_BAD_RANGE_SETS,
1048 	    DATA_TYPE_UINT32_ARRAY, eip->zei_range_count, eip->zei_range_sets,
1049 	    FM_EREPORT_PAYLOAD_ZFS_BAD_RANGE_CLEARS,
1050 	    DATA_TYPE_UINT32_ARRAY, eip->zei_range_count, eip->zei_range_clears,
1051 	    NULL);
1052 
1053 	if (!no_inline) {
1054 		fm_payload_set(ereport,
1055 		    FM_EREPORT_PAYLOAD_ZFS_BAD_SET_BITS,
1056 		    DATA_TYPE_UINT8_ARRAY,
1057 		    inline_size, (uint8_t *)eip->zei_bits_set,
1058 		    FM_EREPORT_PAYLOAD_ZFS_BAD_CLEARED_BITS,
1059 		    DATA_TYPE_UINT8_ARRAY,
1060 		    inline_size, (uint8_t *)eip->zei_bits_cleared,
1061 		    NULL);
1062 	}
1063 	return (eip);
1064 }
1065 #else
1066 void
1067 zfs_ereport_clear(spa_t *spa, vdev_t *vd)
1068 {
1069 	(void) spa, (void) vd;
1070 }
1071 #endif
1072 
1073 /*
1074  * Make sure our event is still valid for the given zio/vdev/pool.  For example,
1075  * we don't want to keep logging events for a faulted or missing vdev.
1076  */
1077 boolean_t
1078 zfs_ereport_is_valid(const char *subclass, spa_t *spa, vdev_t *vd, zio_t *zio)
1079 {
1080 #ifdef _KERNEL
1081 	/*
1082 	 * If we are doing a spa_tryimport() or in recovery mode,
1083 	 * ignore errors.
1084 	 */
1085 	if (spa_load_state(spa) == SPA_LOAD_TRYIMPORT ||
1086 	    spa_load_state(spa) == SPA_LOAD_RECOVER)
1087 		return (B_FALSE);
1088 
1089 	/*
1090 	 * If we are in the middle of opening a pool, and the previous attempt
1091 	 * failed, don't bother logging any new ereports - we're just going to
1092 	 * get the same diagnosis anyway.
1093 	 */
1094 	if (spa_load_state(spa) != SPA_LOAD_NONE &&
1095 	    spa->spa_last_open_failed)
1096 		return (B_FALSE);
1097 
1098 	if (zio != NULL) {
1099 		/* If this is not a read or write zio, ignore the error */
1100 		if (zio->io_type != ZIO_TYPE_READ &&
1101 		    zio->io_type != ZIO_TYPE_WRITE)
1102 			return (B_FALSE);
1103 
1104 		if (vd != NULL) {
1105 			/*
1106 			 * If the vdev has already been marked as failing due
1107 			 * to a failed probe, then ignore any subsequent I/O
1108 			 * errors, as the DE will automatically fault the vdev
1109 			 * on the first such failure.  This also catches cases
1110 			 * where vdev_remove_wanted is set and the device has
1111 			 * not yet been asynchronously placed into the REMOVED
1112 			 * state.
1113 			 */
1114 			if (zio->io_vd == vd && !vdev_accessible(vd, zio))
1115 				return (B_FALSE);
1116 
1117 			/*
1118 			 * Ignore checksum errors for reads from DTL regions of
1119 			 * leaf vdevs.
1120 			 */
1121 			if (zio->io_type == ZIO_TYPE_READ &&
1122 			    zio->io_error == ECKSUM &&
1123 			    vd->vdev_ops->vdev_op_leaf &&
1124 			    vdev_dtl_contains(vd, DTL_MISSING, zio->io_txg, 1))
1125 				return (B_FALSE);
1126 		}
1127 	}
1128 
1129 	/*
1130 	 * For probe failure, we want to avoid posting ereports if we've
1131 	 * already removed the device in the meantime.
1132 	 */
1133 	if (vd != NULL &&
1134 	    strcmp(subclass, FM_EREPORT_ZFS_PROBE_FAILURE) == 0 &&
1135 	    (vd->vdev_remove_wanted || vd->vdev_state == VDEV_STATE_REMOVED))
1136 		return (B_FALSE);
1137 
1138 	/* Ignore bogus delay events (like from ioctls or unqueued IOs) */
1139 	if ((strcmp(subclass, FM_EREPORT_ZFS_DELAY) == 0) &&
1140 	    (zio != NULL) && (!zio->io_timestamp)) {
1141 		return (B_FALSE);
1142 	}
1143 #else
1144 	(void) subclass, (void) spa, (void) vd, (void) zio;
1145 #endif
1146 	return (B_TRUE);
1147 }
1148 
1149 /*
1150  * Post an ereport for the given subclass
1151  *
1152  * Returns
1153  * - 0 if an event was posted
1154  * - EINVAL if there was a problem posting event
1155  * - EBUSY if the event was rate limited
1156  * - EALREADY if the event was already posted (duplicate)
1157  */
1158 int
1159 zfs_ereport_post(const char *subclass, spa_t *spa, vdev_t *vd,
1160     const zbookmark_phys_t *zb, zio_t *zio, uint64_t state)
1161 {
1162 	int rc = 0;
1163 #ifdef _KERNEL
1164 	nvlist_t *ereport = NULL;
1165 	nvlist_t *detector = NULL;
1166 
1167 	if (!zfs_ereport_is_valid(subclass, spa, vd, zio))
1168 		return (EINVAL);
1169 
1170 	if (zfs_ereport_is_duplicate(subclass, spa, vd, zb, zio, 0, 0))
1171 		return (SET_ERROR(EALREADY));
1172 
1173 	if (zfs_is_ratelimiting_event(subclass, vd))
1174 		return (SET_ERROR(EBUSY));
1175 
1176 	if (!zfs_ereport_start(&ereport, &detector, subclass, spa, vd,
1177 	    zb, zio, state, 0))
1178 		return (SET_ERROR(EINVAL));	/* couldn't post event */
1179 
1180 	if (ereport == NULL)
1181 		return (SET_ERROR(EINVAL));
1182 
1183 	/* Cleanup is handled by the callback function */
1184 	rc = zfs_zevent_post(ereport, detector, zfs_zevent_post_cb);
1185 #else
1186 	(void) subclass, (void) spa, (void) vd, (void) zb, (void) zio,
1187 	    (void) state;
1188 #endif
1189 	return (rc);
1190 }
1191 
1192 /*
1193  * Prepare a checksum ereport
1194  *
1195  * Returns
1196  * - 0 if an event was posted
1197  * - EINVAL if there was a problem posting event
1198  * - EBUSY if the event was rate limited
1199  * - EALREADY if the event was already posted (duplicate)
1200  */
1201 int
1202 zfs_ereport_start_checksum(spa_t *spa, vdev_t *vd, const zbookmark_phys_t *zb,
1203     struct zio *zio, uint64_t offset, uint64_t length, zio_bad_cksum_t *info)
1204 {
1205 	zio_cksum_report_t *report;
1206 
1207 #ifdef _KERNEL
1208 	if (!zfs_ereport_is_valid(FM_EREPORT_ZFS_CHECKSUM, spa, vd, zio))
1209 		return (SET_ERROR(EINVAL));
1210 
1211 	if (zfs_ereport_is_duplicate(FM_EREPORT_ZFS_CHECKSUM, spa, vd, zb, zio,
1212 	    offset, length))
1213 		return (SET_ERROR(EALREADY));
1214 
1215 	if (zfs_is_ratelimiting_event(FM_EREPORT_ZFS_CHECKSUM, vd))
1216 		return (SET_ERROR(EBUSY));
1217 #else
1218 	(void) zb, (void) offset;
1219 #endif
1220 
1221 	report = kmem_zalloc(sizeof (*report), KM_SLEEP);
1222 
1223 	zio_vsd_default_cksum_report(zio, report);
1224 
1225 	/* copy the checksum failure information if it was provided */
1226 	if (info != NULL) {
1227 		report->zcr_ckinfo = kmem_zalloc(sizeof (*info), KM_SLEEP);
1228 		memcpy(report->zcr_ckinfo, info, sizeof (*info));
1229 	}
1230 
1231 	report->zcr_sector = 1ULL << vd->vdev_top->vdev_ashift;
1232 	report->zcr_align =
1233 	    vdev_psize_to_asize(vd->vdev_top, report->zcr_sector);
1234 	report->zcr_length = length;
1235 
1236 #ifdef _KERNEL
1237 	(void) zfs_ereport_start(&report->zcr_ereport, &report->zcr_detector,
1238 	    FM_EREPORT_ZFS_CHECKSUM, spa, vd, zb, zio, offset, length);
1239 
1240 	if (report->zcr_ereport == NULL) {
1241 		zfs_ereport_free_checksum(report);
1242 		return (0);
1243 	}
1244 #endif
1245 
1246 	mutex_enter(&spa->spa_errlist_lock);
1247 	report->zcr_next = zio->io_logical->io_cksum_report;
1248 	zio->io_logical->io_cksum_report = report;
1249 	mutex_exit(&spa->spa_errlist_lock);
1250 	return (0);
1251 }
1252 
1253 void
1254 zfs_ereport_finish_checksum(zio_cksum_report_t *report, const abd_t *good_data,
1255     const abd_t *bad_data, boolean_t drop_if_identical)
1256 {
1257 #ifdef _KERNEL
1258 	zfs_ecksum_info_t *info;
1259 
1260 	info = annotate_ecksum(report->zcr_ereport, report->zcr_ckinfo,
1261 	    good_data, bad_data, report->zcr_length, drop_if_identical);
1262 	if (info != NULL)
1263 		zfs_zevent_post(report->zcr_ereport,
1264 		    report->zcr_detector, zfs_zevent_post_cb);
1265 	else
1266 		zfs_zevent_post_cb(report->zcr_ereport, report->zcr_detector);
1267 
1268 	report->zcr_ereport = report->zcr_detector = NULL;
1269 	if (info != NULL)
1270 		kmem_free(info, sizeof (*info));
1271 #else
1272 	(void) report, (void) good_data, (void) bad_data,
1273 	    (void) drop_if_identical;
1274 #endif
1275 }
1276 
1277 void
1278 zfs_ereport_free_checksum(zio_cksum_report_t *rpt)
1279 {
1280 #ifdef _KERNEL
1281 	if (rpt->zcr_ereport != NULL) {
1282 		fm_nvlist_destroy(rpt->zcr_ereport,
1283 		    FM_NVA_FREE);
1284 		fm_nvlist_destroy(rpt->zcr_detector,
1285 		    FM_NVA_FREE);
1286 	}
1287 #endif
1288 	rpt->zcr_free(rpt->zcr_cbdata, rpt->zcr_cbinfo);
1289 
1290 	if (rpt->zcr_ckinfo != NULL)
1291 		kmem_free(rpt->zcr_ckinfo, sizeof (*rpt->zcr_ckinfo));
1292 
1293 	kmem_free(rpt, sizeof (*rpt));
1294 }
1295 
1296 /*
1297  * Post a checksum ereport
1298  *
1299  * Returns
1300  * - 0 if an event was posted
1301  * - EINVAL if there was a problem posting event
1302  * - EBUSY if the event was rate limited
1303  * - EALREADY if the event was already posted (duplicate)
1304  */
1305 int
1306 zfs_ereport_post_checksum(spa_t *spa, vdev_t *vd, const zbookmark_phys_t *zb,
1307     struct zio *zio, uint64_t offset, uint64_t length,
1308     const abd_t *good_data, const abd_t *bad_data, zio_bad_cksum_t *zbc)
1309 {
1310 	int rc = 0;
1311 #ifdef _KERNEL
1312 	nvlist_t *ereport = NULL;
1313 	nvlist_t *detector = NULL;
1314 	zfs_ecksum_info_t *info;
1315 
1316 	if (!zfs_ereport_is_valid(FM_EREPORT_ZFS_CHECKSUM, spa, vd, zio))
1317 		return (SET_ERROR(EINVAL));
1318 
1319 	if (zfs_ereport_is_duplicate(FM_EREPORT_ZFS_CHECKSUM, spa, vd, zb, zio,
1320 	    offset, length))
1321 		return (SET_ERROR(EALREADY));
1322 
1323 	if (zfs_is_ratelimiting_event(FM_EREPORT_ZFS_CHECKSUM, vd))
1324 		return (SET_ERROR(EBUSY));
1325 
1326 	if (!zfs_ereport_start(&ereport, &detector, FM_EREPORT_ZFS_CHECKSUM,
1327 	    spa, vd, zb, zio, offset, length) || (ereport == NULL)) {
1328 		return (SET_ERROR(EINVAL));
1329 	}
1330 
1331 	info = annotate_ecksum(ereport, zbc, good_data, bad_data, length,
1332 	    B_FALSE);
1333 
1334 	if (info != NULL) {
1335 		rc = zfs_zevent_post(ereport, detector, zfs_zevent_post_cb);
1336 		kmem_free(info, sizeof (*info));
1337 	}
1338 #else
1339 	(void) spa, (void) vd, (void) zb, (void) zio, (void) offset,
1340 	    (void) length, (void) good_data, (void) bad_data, (void) zbc;
1341 #endif
1342 	return (rc);
1343 }
1344 
1345 /*
1346  * The 'sysevent.fs.zfs.*' events are signals posted to notify user space of
1347  * change in the pool.  All sysevents are listed in sys/sysevent/eventdefs.h
1348  * and are designed to be consumed by the ZFS Event Daemon (ZED).  For
1349  * additional details refer to the zed(8) man page.
1350  */
1351 nvlist_t *
1352 zfs_event_create(spa_t *spa, vdev_t *vd, const char *type, const char *name,
1353     nvlist_t *aux)
1354 {
1355 	nvlist_t *resource = NULL;
1356 #ifdef _KERNEL
1357 	char class[64];
1358 
1359 	if (spa_load_state(spa) == SPA_LOAD_TRYIMPORT)
1360 		return (NULL);
1361 
1362 	if ((resource = fm_nvlist_create(NULL)) == NULL)
1363 		return (NULL);
1364 
1365 	(void) snprintf(class, sizeof (class), "%s.%s.%s", type,
1366 	    ZFS_ERROR_CLASS, name);
1367 	VERIFY0(nvlist_add_uint8(resource, FM_VERSION, FM_RSRC_VERSION));
1368 	VERIFY0(nvlist_add_string(resource, FM_CLASS, class));
1369 	VERIFY0(nvlist_add_string(resource,
1370 	    FM_EREPORT_PAYLOAD_ZFS_POOL, spa_name(spa)));
1371 	VERIFY0(nvlist_add_uint64(resource,
1372 	    FM_EREPORT_PAYLOAD_ZFS_POOL_GUID, spa_guid(spa)));
1373 	VERIFY0(nvlist_add_uint64(resource,
1374 	    FM_EREPORT_PAYLOAD_ZFS_POOL_STATE, spa_state(spa)));
1375 	VERIFY0(nvlist_add_int32(resource,
1376 	    FM_EREPORT_PAYLOAD_ZFS_POOL_CONTEXT, spa_load_state(spa)));
1377 
1378 	if (vd) {
1379 		VERIFY0(nvlist_add_uint64(resource,
1380 		    FM_EREPORT_PAYLOAD_ZFS_VDEV_GUID, vd->vdev_guid));
1381 		VERIFY0(nvlist_add_uint64(resource,
1382 		    FM_EREPORT_PAYLOAD_ZFS_VDEV_STATE, vd->vdev_state));
1383 		if (vd->vdev_path != NULL)
1384 			VERIFY0(nvlist_add_string(resource,
1385 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_PATH, vd->vdev_path));
1386 		if (vd->vdev_devid != NULL)
1387 			VERIFY0(nvlist_add_string(resource,
1388 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_DEVID, vd->vdev_devid));
1389 		if (vd->vdev_fru != NULL)
1390 			VERIFY0(nvlist_add_string(resource,
1391 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_FRU, vd->vdev_fru));
1392 		if (vd->vdev_enc_sysfs_path != NULL)
1393 			VERIFY0(nvlist_add_string(resource,
1394 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_ENC_SYSFS_PATH,
1395 			    vd->vdev_enc_sysfs_path));
1396 	}
1397 
1398 	/* also copy any optional payload data */
1399 	if (aux) {
1400 		nvpair_t *elem = NULL;
1401 
1402 		while ((elem = nvlist_next_nvpair(aux, elem)) != NULL)
1403 			(void) nvlist_add_nvpair(resource, elem);
1404 	}
1405 #else
1406 	(void) spa, (void) vd, (void) type, (void) name, (void) aux;
1407 #endif
1408 	return (resource);
1409 }
1410 
1411 static void
1412 zfs_post_common(spa_t *spa, vdev_t *vd, const char *type, const char *name,
1413     nvlist_t *aux)
1414 {
1415 #ifdef _KERNEL
1416 	nvlist_t *resource;
1417 
1418 	resource = zfs_event_create(spa, vd, type, name, aux);
1419 	if (resource)
1420 		zfs_zevent_post(resource, NULL, zfs_zevent_post_cb);
1421 #else
1422 	(void) spa, (void) vd, (void) type, (void) name, (void) aux;
1423 #endif
1424 }
1425 
1426 /*
1427  * The 'resource.fs.zfs.removed' event is an internal signal that the given vdev
1428  * has been removed from the system.  This will cause the DE to ignore any
1429  * recent I/O errors, inferring that they are due to the asynchronous device
1430  * removal.
1431  */
1432 void
1433 zfs_post_remove(spa_t *spa, vdev_t *vd)
1434 {
1435 	zfs_post_common(spa, vd, FM_RSRC_CLASS, FM_RESOURCE_REMOVED, NULL);
1436 }
1437 
1438 /*
1439  * The 'resource.fs.zfs.autoreplace' event is an internal signal that the pool
1440  * has the 'autoreplace' property set, and therefore any broken vdevs will be
1441  * handled by higher level logic, and no vdev fault should be generated.
1442  */
1443 void
1444 zfs_post_autoreplace(spa_t *spa, vdev_t *vd)
1445 {
1446 	zfs_post_common(spa, vd, FM_RSRC_CLASS, FM_RESOURCE_AUTOREPLACE, NULL);
1447 }
1448 
1449 /*
1450  * The 'resource.fs.zfs.statechange' event is an internal signal that the
1451  * given vdev has transitioned its state to DEGRADED or HEALTHY.  This will
1452  * cause the retire agent to repair any outstanding fault management cases
1453  * open because the device was not found (fault.fs.zfs.device).
1454  */
1455 void
1456 zfs_post_state_change(spa_t *spa, vdev_t *vd, uint64_t laststate)
1457 {
1458 #ifdef _KERNEL
1459 	nvlist_t *aux;
1460 
1461 	/*
1462 	 * Add optional supplemental keys to payload
1463 	 */
1464 	aux = fm_nvlist_create(NULL);
1465 	if (vd && aux) {
1466 		if (vd->vdev_physpath) {
1467 			fnvlist_add_string(aux,
1468 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_PHYSPATH,
1469 			    vd->vdev_physpath);
1470 		}
1471 		if (vd->vdev_enc_sysfs_path) {
1472 			fnvlist_add_string(aux,
1473 			    FM_EREPORT_PAYLOAD_ZFS_VDEV_ENC_SYSFS_PATH,
1474 			    vd->vdev_enc_sysfs_path);
1475 		}
1476 
1477 		fnvlist_add_uint64(aux,
1478 		    FM_EREPORT_PAYLOAD_ZFS_VDEV_LASTSTATE, laststate);
1479 	}
1480 
1481 	zfs_post_common(spa, vd, FM_RSRC_CLASS, FM_RESOURCE_STATECHANGE,
1482 	    aux);
1483 
1484 	if (aux)
1485 		fm_nvlist_destroy(aux, FM_NVA_FREE);
1486 #else
1487 	(void) spa, (void) vd, (void) laststate;
1488 #endif
1489 }
1490 
1491 #ifdef _KERNEL
1492 void
1493 zfs_ereport_init(void)
1494 {
1495 	mutex_init(&recent_events_lock, NULL, MUTEX_DEFAULT, NULL);
1496 	list_create(&recent_events_list, sizeof (recent_events_node_t),
1497 	    offsetof(recent_events_node_t, re_list_link));
1498 	avl_create(&recent_events_tree,  recent_events_compare,
1499 	    sizeof (recent_events_node_t), offsetof(recent_events_node_t,
1500 	    re_tree_link));
1501 }
1502 
1503 /*
1504  * This 'early' fini needs to run before zfs_fini() which on Linux waits
1505  * for the system_delay_taskq to drain.
1506  */
1507 void
1508 zfs_ereport_taskq_fini(void)
1509 {
1510 	mutex_enter(&recent_events_lock);
1511 	if (recent_events_cleaner_tqid != 0) {
1512 		taskq_cancel_id(system_delay_taskq, recent_events_cleaner_tqid);
1513 		recent_events_cleaner_tqid = 0;
1514 	}
1515 	mutex_exit(&recent_events_lock);
1516 }
1517 
1518 void
1519 zfs_ereport_fini(void)
1520 {
1521 	recent_events_node_t *entry;
1522 
1523 	while ((entry = list_remove_head(&recent_events_list)) != NULL) {
1524 		avl_remove(&recent_events_tree, entry);
1525 		kmem_free(entry, sizeof (*entry));
1526 	}
1527 	avl_destroy(&recent_events_tree);
1528 	list_destroy(&recent_events_list);
1529 	mutex_destroy(&recent_events_lock);
1530 }
1531 
1532 void
1533 zfs_ereport_snapshot_post(const char *subclass, spa_t *spa, const char *name)
1534 {
1535 	nvlist_t *aux;
1536 
1537 	aux = fm_nvlist_create(NULL);
1538 	fnvlist_add_string(aux, FM_EREPORT_PAYLOAD_ZFS_SNAPSHOT_NAME, name);
1539 
1540 	zfs_post_common(spa, NULL, FM_RSRC_CLASS, subclass, aux);
1541 	fm_nvlist_destroy(aux, FM_NVA_FREE);
1542 }
1543 
1544 /*
1545  * Post when a event when a zvol is created or removed
1546  *
1547  * This is currently only used by macOS, since it uses the event to create
1548  * symlinks between the volume name (mypool/myvol) and the actual /dev
1549  * device (/dev/disk3).  For example:
1550  *
1551  * /var/run/zfs/dsk/mypool/myvol -> /dev/disk3
1552  *
1553  * name: The full name of the zvol ("mypool/myvol")
1554  * dev_name: The full /dev name for the zvol ("/dev/disk3")
1555  * raw_name: The raw  /dev name for the zvol ("/dev/rdisk3")
1556  */
1557 void
1558 zfs_ereport_zvol_post(const char *subclass, const char *name,
1559     const char *dev_name, const char *raw_name)
1560 {
1561 	nvlist_t *aux;
1562 	char *r;
1563 
1564 	boolean_t locked = mutex_owned(&spa_namespace_lock);
1565 	if (!locked) mutex_enter(&spa_namespace_lock);
1566 	spa_t *spa = spa_lookup(name);
1567 	if (!locked) mutex_exit(&spa_namespace_lock);
1568 
1569 	if (spa == NULL)
1570 		return;
1571 
1572 	aux = fm_nvlist_create(NULL);
1573 	fnvlist_add_string(aux, FM_EREPORT_PAYLOAD_ZFS_DEVICE_NAME, dev_name);
1574 	fnvlist_add_string(aux, FM_EREPORT_PAYLOAD_ZFS_RAW_DEVICE_NAME,
1575 	    raw_name);
1576 	r = strchr(name, '/');
1577 	if (r && r[1])
1578 		fnvlist_add_string(aux, FM_EREPORT_PAYLOAD_ZFS_VOLUME, &r[1]);
1579 
1580 	zfs_post_common(spa, NULL, FM_RSRC_CLASS, subclass, aux);
1581 	fm_nvlist_destroy(aux, FM_NVA_FREE);
1582 }
1583 
1584 EXPORT_SYMBOL(zfs_ereport_post);
1585 EXPORT_SYMBOL(zfs_ereport_is_valid);
1586 EXPORT_SYMBOL(zfs_ereport_post_checksum);
1587 EXPORT_SYMBOL(zfs_post_remove);
1588 EXPORT_SYMBOL(zfs_post_autoreplace);
1589 EXPORT_SYMBOL(zfs_post_state_change);
1590 
1591 ZFS_MODULE_PARAM(zfs_zevent, zfs_zevent_, retain_max, UINT, ZMOD_RW,
1592 	"Maximum recent zevents records to retain for duplicate checking");
1593 ZFS_MODULE_PARAM(zfs_zevent, zfs_zevent_, retain_expire_secs, UINT, ZMOD_RW,
1594 	"Expiration time for recent zevents records");
1595 #endif /* _KERNEL */
1596