xref: /freebsd/sys/contrib/openzfs/module/zfs/spa_errlog.c (revision 4d846d260e2b9a3d4d0a701462568268cbfe7a5b)
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 (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2013, 2014, Delphix. All rights reserved.
24  * Copyright (c) 2019 Datto Inc.
25  * Copyright (c) 2021, 2022, George Amanakis. All rights reserved.
26  */
27 
28 /*
29  * Routines to manage the on-disk persistent error log.
30  *
31  * Each pool stores a log of all logical data errors seen during normal
32  * operation.  This is actually the union of two distinct logs: the last log,
33  * and the current log.  All errors seen are logged to the current log.  When a
34  * scrub completes, the current log becomes the last log, the last log is thrown
35  * out, and the current log is reinitialized.  This way, if an error is somehow
36  * corrected, a new scrub will show that it no longer exists, and will be
37  * deleted from the log when the scrub completes.
38  *
39  * The log is stored using a ZAP object whose key is a string form of the
40  * zbookmark_phys tuple (objset, object, level, blkid), and whose contents is an
41  * optional 'objset:object' human-readable string describing the data.  When an
42  * error is first logged, this string will be empty, indicating that no name is
43  * known.  This prevents us from having to issue a potentially large amount of
44  * I/O to discover the object name during an error path.  Instead, we do the
45  * calculation when the data is requested, storing the result so future queries
46  * will be faster.
47  *
48  * If the head_errlog feature is enabled, a different on-disk format is used.
49  * The error log of each head dataset is stored separately in the zap object
50  * and keyed by the head id. This enables listing every dataset affected in
51  * userland. In order to be able to track whether an error block has been
52  * modified or added to snapshots since it was marked as an error, a new tuple
53  * is introduced: zbookmark_err_phys_t. It allows the storage of the birth
54  * transaction group of an error block on-disk. The birth transaction group is
55  * used by check_filesystem() to assess whether this block was freed,
56  * re-written or added to a snapshot since its marking as an error.
57  *
58  * This log is then shipped into an nvlist where the key is the dataset name and
59  * the value is the object name.  Userland is then responsible for uniquifying
60  * this list and displaying it to the user.
61  */
62 
63 #include <sys/dmu_tx.h>
64 #include <sys/spa.h>
65 #include <sys/spa_impl.h>
66 #include <sys/zap.h>
67 #include <sys/zio.h>
68 #include <sys/dsl_dir.h>
69 #include <sys/dmu_objset.h>
70 #include <sys/dbuf.h>
71 #include <sys/zfs_znode.h>
72 
73 #define	NAME_MAX_LEN 64
74 
75 typedef struct clones {
76 	uint64_t clone_ds;
77 	list_node_t node;
78 } clones_t;
79 
80 /*
81  * spa_upgrade_errlog_limit : A zfs module parameter that controls the number
82  *		of on-disk error log entries that will be converted to the new
83  *		format when enabling head_errlog. Defaults to 0 which converts
84  *		all log entries.
85  */
86 static uint_t spa_upgrade_errlog_limit = 0;
87 
88 /*
89  * Convert a bookmark to a string.
90  */
91 static void
92 bookmark_to_name(zbookmark_phys_t *zb, char *buf, size_t len)
93 {
94 	(void) snprintf(buf, len, "%llx:%llx:%llx:%llx",
95 	    (u_longlong_t)zb->zb_objset, (u_longlong_t)zb->zb_object,
96 	    (u_longlong_t)zb->zb_level, (u_longlong_t)zb->zb_blkid);
97 }
98 
99 /*
100  * Convert an err_phys to a string.
101  */
102 static void
103 errphys_to_name(zbookmark_err_phys_t *zep, char *buf, size_t len)
104 {
105 	(void) snprintf(buf, len, "%llx:%llx:%llx:%llx",
106 	    (u_longlong_t)zep->zb_object, (u_longlong_t)zep->zb_level,
107 	    (u_longlong_t)zep->zb_blkid, (u_longlong_t)zep->zb_birth);
108 }
109 
110 /*
111  * Convert a string to a err_phys.
112  */
113 static void
114 name_to_errphys(char *buf, zbookmark_err_phys_t *zep)
115 {
116 	zep->zb_object = zfs_strtonum(buf, &buf);
117 	ASSERT(*buf == ':');
118 	zep->zb_level = (int)zfs_strtonum(buf + 1, &buf);
119 	ASSERT(*buf == ':');
120 	zep->zb_blkid = zfs_strtonum(buf + 1, &buf);
121 	ASSERT(*buf == ':');
122 	zep->zb_birth = zfs_strtonum(buf + 1, &buf);
123 	ASSERT(*buf == '\0');
124 }
125 
126 /*
127  * Convert a string to a bookmark.
128  */
129 static void
130 name_to_bookmark(char *buf, zbookmark_phys_t *zb)
131 {
132 	zb->zb_objset = zfs_strtonum(buf, &buf);
133 	ASSERT(*buf == ':');
134 	zb->zb_object = zfs_strtonum(buf + 1, &buf);
135 	ASSERT(*buf == ':');
136 	zb->zb_level = (int)zfs_strtonum(buf + 1, &buf);
137 	ASSERT(*buf == ':');
138 	zb->zb_blkid = zfs_strtonum(buf + 1, &buf);
139 	ASSERT(*buf == '\0');
140 }
141 
142 #ifdef _KERNEL
143 static void
144 zep_to_zb(uint64_t dataset, zbookmark_err_phys_t *zep, zbookmark_phys_t *zb)
145 {
146 	zb->zb_objset = dataset;
147 	zb->zb_object = zep->zb_object;
148 	zb->zb_level = zep->zb_level;
149 	zb->zb_blkid = zep->zb_blkid;
150 }
151 #endif
152 
153 static void
154 name_to_object(char *buf, uint64_t *obj)
155 {
156 	*obj = zfs_strtonum(buf, &buf);
157 	ASSERT(*buf == '\0');
158 }
159 
160 /*
161  * Retrieve the head filesystem.
162  */
163 static int get_head_ds(spa_t *spa, uint64_t dsobj, uint64_t *head_ds)
164 {
165 	dsl_dataset_t *ds;
166 	int error = dsl_dataset_hold_obj_flags(spa->spa_dsl_pool,
167 	    dsobj, DS_HOLD_FLAG_DECRYPT, FTAG, &ds);
168 
169 	if (error != 0)
170 		return (error);
171 
172 	ASSERT(head_ds);
173 	*head_ds = dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj;
174 	dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
175 
176 	return (error);
177 }
178 
179 /*
180  * Log an uncorrectable error to the persistent error log.  We add it to the
181  * spa's list of pending errors.  The changes are actually synced out to disk
182  * during spa_errlog_sync().
183  */
184 void
185 spa_log_error(spa_t *spa, const zbookmark_phys_t *zb, const uint64_t *birth)
186 {
187 	spa_error_entry_t search;
188 	spa_error_entry_t *new;
189 	avl_tree_t *tree;
190 	avl_index_t where;
191 
192 	/*
193 	 * If we are trying to import a pool, ignore any errors, as we won't be
194 	 * writing to the pool any time soon.
195 	 */
196 	if (spa_load_state(spa) == SPA_LOAD_TRYIMPORT)
197 		return;
198 
199 	mutex_enter(&spa->spa_errlist_lock);
200 
201 	/*
202 	 * If we have had a request to rotate the log, log it to the next list
203 	 * instead of the current one.
204 	 */
205 	if (spa->spa_scrub_active || spa->spa_scrub_finished)
206 		tree = &spa->spa_errlist_scrub;
207 	else
208 		tree = &spa->spa_errlist_last;
209 
210 	search.se_bookmark = *zb;
211 	if (avl_find(tree, &search, &where) != NULL) {
212 		mutex_exit(&spa->spa_errlist_lock);
213 		return;
214 	}
215 
216 	new = kmem_zalloc(sizeof (spa_error_entry_t), KM_SLEEP);
217 	new->se_bookmark = *zb;
218 
219 	/*
220 	 * If the head_errlog feature is enabled, store the birth txg now. In
221 	 * case the file is deleted before spa_errlog_sync() runs, we will not
222 	 * be able to retrieve the birth txg.
223 	 */
224 	if (spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {
225 		new->se_zep.zb_object = zb->zb_object;
226 		new->se_zep.zb_level = zb->zb_level;
227 		new->se_zep.zb_blkid = zb->zb_blkid;
228 
229 		/*
230 		 * birth may end up being NULL, e.g. in zio_done(). We
231 		 * will handle this in process_error_block().
232 		 */
233 		if (birth != NULL)
234 			new->se_zep.zb_birth = *birth;
235 	}
236 
237 	avl_insert(tree, new, where);
238 	mutex_exit(&spa->spa_errlist_lock);
239 }
240 
241 #ifdef _KERNEL
242 static int
243 find_birth_txg(dsl_dataset_t *ds, zbookmark_err_phys_t *zep,
244     uint64_t *birth_txg)
245 {
246 	objset_t *os;
247 	int error = dmu_objset_from_ds(ds, &os);
248 	if (error != 0)
249 		return (error);
250 
251 	dnode_t *dn;
252 	blkptr_t bp;
253 
254 	error = dnode_hold(os, zep->zb_object, FTAG, &dn);
255 	if (error != 0)
256 		return (error);
257 
258 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
259 	error = dbuf_dnode_findbp(dn, zep->zb_level, zep->zb_blkid, &bp, NULL,
260 	    NULL);
261 	if (error == 0 && BP_IS_HOLE(&bp))
262 		error = SET_ERROR(ENOENT);
263 
264 	*birth_txg = bp.blk_birth;
265 	rw_exit(&dn->dn_struct_rwlock);
266 	dnode_rele(dn, FTAG);
267 	return (error);
268 }
269 
270 /*
271  * Copy the bookmark to the end of the user-space buffer which starts at
272  * uaddr and has *count unused entries, and decrement *count by 1.
273  */
274 static int
275 copyout_entry(const zbookmark_phys_t *zb, void *uaddr, uint64_t *count)
276 {
277 	if (*count == 0)
278 		return (SET_ERROR(ENOMEM));
279 
280 	*count -= 1;
281 	if (copyout(zb, (char *)uaddr + (*count) * sizeof (zbookmark_phys_t),
282 	    sizeof (zbookmark_phys_t)) != 0)
283 		return (SET_ERROR(EFAULT));
284 	return (0);
285 }
286 
287 /*
288  * Each time the error block is referenced by a snapshot or clone, add a
289  * zbookmark_phys_t entry to the userspace array at uaddr. The array is
290  * filled from the back and the in-out parameter *count is modified to be the
291  * number of unused entries at the beginning of the array.
292  */
293 static int
294 check_filesystem(spa_t *spa, uint64_t head_ds, zbookmark_err_phys_t *zep,
295     void *uaddr, uint64_t *count, list_t *clones_list)
296 {
297 	dsl_dataset_t *ds;
298 	dsl_pool_t *dp = spa->spa_dsl_pool;
299 
300 	int error = dsl_dataset_hold_obj_flags(dp, head_ds,
301 	    DS_HOLD_FLAG_DECRYPT, FTAG, &ds);
302 	if (error != 0)
303 		return (error);
304 
305 	uint64_t latest_txg;
306 	uint64_t txg_to_consider = spa->spa_syncing_txg;
307 	boolean_t check_snapshot = B_TRUE;
308 	error = find_birth_txg(ds, zep, &latest_txg);
309 
310 	/*
311 	 * If find_birth_txg() errors out otherwise, let txg_to_consider be
312 	 * equal to the spa's syncing txg: if check_filesystem() errors out
313 	 * then affected snapshots or clones will not be checked.
314 	 */
315 	if (error == 0 && zep->zb_birth == latest_txg) {
316 		/* Block neither free nor rewritten. */
317 		zbookmark_phys_t zb;
318 		zep_to_zb(head_ds, zep, &zb);
319 		error = copyout_entry(&zb, uaddr, count);
320 		if (error != 0) {
321 			dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
322 			return (error);
323 		}
324 		check_snapshot = B_FALSE;
325 	} else if (error == 0) {
326 		txg_to_consider = latest_txg;
327 	}
328 
329 	/*
330 	 * Retrieve the number of snapshots if the dataset is not a snapshot.
331 	 */
332 	uint64_t snap_count = 0;
333 	if (dsl_dataset_phys(ds)->ds_snapnames_zapobj != 0) {
334 
335 		error = zap_count(spa->spa_meta_objset,
336 		    dsl_dataset_phys(ds)->ds_snapnames_zapobj, &snap_count);
337 
338 		if (error != 0) {
339 			dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
340 			return (error);
341 		}
342 	}
343 
344 	if (snap_count == 0) {
345 		/* Filesystem without snapshots. */
346 		dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
347 		return (0);
348 	}
349 
350 	uint64_t *snap_obj_array = kmem_zalloc(snap_count * sizeof (uint64_t),
351 	    KM_SLEEP);
352 
353 	int aff_snap_count = 0;
354 	uint64_t snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
355 	uint64_t snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
356 	uint64_t zap_clone = dsl_dir_phys(ds->ds_dir)->dd_clones;
357 
358 	dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
359 
360 	/* Check only snapshots created from this file system. */
361 	while (snap_obj != 0 && zep->zb_birth < snap_obj_txg &&
362 	    snap_obj_txg <= txg_to_consider) {
363 
364 		error = dsl_dataset_hold_obj_flags(dp, snap_obj,
365 		    DS_HOLD_FLAG_DECRYPT, FTAG, &ds);
366 		if (error != 0)
367 			goto out;
368 
369 		if (dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj != head_ds) {
370 			snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
371 			snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
372 			dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
373 			continue;
374 		}
375 
376 		boolean_t affected = B_TRUE;
377 		if (check_snapshot) {
378 			uint64_t blk_txg;
379 			error = find_birth_txg(ds, zep, &blk_txg);
380 			affected = (error == 0 && zep->zb_birth == blk_txg);
381 		}
382 
383 		/* Report errors in snapshots. */
384 		if (affected) {
385 			snap_obj_array[aff_snap_count] = snap_obj;
386 			aff_snap_count++;
387 
388 			zbookmark_phys_t zb;
389 			zep_to_zb(snap_obj, zep, &zb);
390 			error = copyout_entry(&zb, uaddr, count);
391 			if (error != 0) {
392 				dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT,
393 				    FTAG);
394 				goto out;
395 			}
396 		}
397 		snap_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
398 		snap_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
399 		dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
400 	}
401 
402 	if (zap_clone == 0 || aff_snap_count == 0)
403 		return (0);
404 
405 	/* Check clones. */
406 	zap_cursor_t *zc;
407 	zap_attribute_t *za;
408 
409 	zc = kmem_zalloc(sizeof (zap_cursor_t), KM_SLEEP);
410 	za = kmem_zalloc(sizeof (zap_attribute_t), KM_SLEEP);
411 
412 	for (zap_cursor_init(zc, spa->spa_meta_objset, zap_clone);
413 	    zap_cursor_retrieve(zc, za) == 0;
414 	    zap_cursor_advance(zc)) {
415 
416 		dsl_dataset_t *clone;
417 		error = dsl_dataset_hold_obj_flags(dp, za->za_first_integer,
418 		    DS_HOLD_FLAG_DECRYPT, FTAG, &clone);
419 
420 		if (error != 0)
421 			break;
422 
423 		/*
424 		 * Only clones whose origins were affected could also
425 		 * have affected snapshots.
426 		 */
427 		boolean_t found = B_FALSE;
428 		for (int i = 0; i < snap_count; i++) {
429 			if (dsl_dir_phys(clone->ds_dir)->dd_origin_obj
430 			    == snap_obj_array[i])
431 				found = B_TRUE;
432 		}
433 		dsl_dataset_rele_flags(clone, DS_HOLD_FLAG_DECRYPT, FTAG);
434 
435 		if (!found)
436 			continue;
437 
438 		clones_t *ct = kmem_zalloc(sizeof (*ct), KM_SLEEP);
439 		ct->clone_ds = za->za_first_integer;
440 		list_insert_tail(clones_list, ct);
441 	}
442 
443 	zap_cursor_fini(zc);
444 	kmem_free(za, sizeof (*za));
445 	kmem_free(zc, sizeof (*zc));
446 
447 out:
448 	kmem_free(snap_obj_array, sizeof (*snap_obj_array));
449 	return (error);
450 }
451 
452 static int
453 find_top_affected_fs(spa_t *spa, uint64_t head_ds, zbookmark_err_phys_t *zep,
454     uint64_t *top_affected_fs)
455 {
456 	uint64_t oldest_dsobj;
457 	int error = dsl_dataset_oldest_snapshot(spa, head_ds, zep->zb_birth,
458 	    &oldest_dsobj);
459 	if (error != 0)
460 		return (error);
461 
462 	dsl_dataset_t *ds;
463 	error = dsl_dataset_hold_obj_flags(spa->spa_dsl_pool, oldest_dsobj,
464 	    DS_HOLD_FLAG_DECRYPT, FTAG, &ds);
465 	if (error != 0)
466 		return (error);
467 
468 	*top_affected_fs =
469 	    dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj;
470 	dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
471 	return (0);
472 }
473 
474 static int
475 process_error_block(spa_t *spa, uint64_t head_ds, zbookmark_err_phys_t *zep,
476     void *uaddr, uint64_t *count)
477 {
478 	/*
479 	 * If zb_birth == 0 or head_ds == 0 it means we failed to retrieve the
480 	 * birth txg or the head filesystem of the block pointer. This may
481 	 * happen e.g. when an encrypted filesystem is not mounted or when
482 	 * the key is not loaded. In this case do not proceed to
483 	 * check_filesystem(), instead do the accounting here.
484 	 */
485 	if (zep->zb_birth == 0 || head_ds == 0) {
486 		zbookmark_phys_t zb;
487 		zep_to_zb(head_ds, zep, &zb);
488 		int error = copyout_entry(&zb, uaddr, count);
489 		if (error != 0) {
490 			return (error);
491 		}
492 		return (0);
493 	}
494 
495 	uint64_t top_affected_fs;
496 	uint64_t init_count = *count;
497 	int error = find_top_affected_fs(spa, head_ds, zep, &top_affected_fs);
498 	if (error == 0) {
499 		clones_t *ct;
500 		list_t clones_list;
501 
502 		list_create(&clones_list, sizeof (clones_t),
503 		    offsetof(clones_t, node));
504 
505 		error = check_filesystem(spa, top_affected_fs, zep,
506 		    uaddr, count, &clones_list);
507 
508 		while ((ct = list_remove_head(&clones_list)) != NULL) {
509 			error = check_filesystem(spa, ct->clone_ds, zep,
510 			    uaddr, count, &clones_list);
511 			kmem_free(ct, sizeof (*ct));
512 
513 			if (error) {
514 				while (!list_is_empty(&clones_list)) {
515 					ct = list_remove_head(&clones_list);
516 					kmem_free(ct, sizeof (*ct));
517 				}
518 				break;
519 			}
520 		}
521 
522 		list_destroy(&clones_list);
523 	}
524 	if (error == 0 && init_count == *count) {
525 		/*
526 		 * If we reach this point, no errors have been detected
527 		 * in the checked filesystems/snapshots. Before returning mark
528 		 * the error block to be removed from the error lists and logs.
529 		 */
530 		zbookmark_phys_t zb;
531 		zep_to_zb(head_ds, zep, &zb);
532 		spa_remove_error(spa, &zb, &zep->zb_birth);
533 	}
534 
535 	return (error);
536 }
537 #endif
538 
539 /*
540  * If a healed bookmark matches an entry in the error log we stash it in a tree
541  * so that we can later remove the related log entries in sync context.
542  */
543 static void
544 spa_add_healed_error(spa_t *spa, uint64_t obj, zbookmark_phys_t *healed_zb,
545     const uint64_t *birth)
546 {
547 	char name[NAME_MAX_LEN];
548 
549 	if (obj == 0)
550 		return;
551 
552 	boolean_t held_list = B_FALSE;
553 	boolean_t held_log = B_FALSE;
554 
555 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {
556 		bookmark_to_name(healed_zb, name, sizeof (name));
557 
558 		if (zap_contains(spa->spa_meta_objset, healed_zb->zb_objset,
559 		    name) == 0) {
560 			if (!MUTEX_HELD(&spa->spa_errlog_lock)) {
561 				mutex_enter(&spa->spa_errlog_lock);
562 				held_log = B_TRUE;
563 			}
564 
565 			/*
566 			 * Found an error matching healed zb, add zb to our
567 			 * tree of healed errors
568 			 */
569 			avl_tree_t *tree = &spa->spa_errlist_healed;
570 			spa_error_entry_t search;
571 			spa_error_entry_t *new;
572 			avl_index_t where;
573 			search.se_bookmark = *healed_zb;
574 			if (!MUTEX_HELD(&spa->spa_errlist_lock)) {
575 				mutex_enter(&spa->spa_errlist_lock);
576 				held_list = B_TRUE;
577 			}
578 			if (avl_find(tree, &search, &where) != NULL) {
579 				if (held_list)
580 					mutex_exit(&spa->spa_errlist_lock);
581 				if (held_log)
582 					mutex_exit(&spa->spa_errlog_lock);
583 				return;
584 			}
585 			new = kmem_zalloc(sizeof (spa_error_entry_t), KM_SLEEP);
586 			new->se_bookmark = *healed_zb;
587 			avl_insert(tree, new, where);
588 			if (held_list)
589 				mutex_exit(&spa->spa_errlist_lock);
590 			if (held_log)
591 				mutex_exit(&spa->spa_errlog_lock);
592 		}
593 		return;
594 	}
595 
596 	zbookmark_err_phys_t healed_zep;
597 	healed_zep.zb_object = healed_zb->zb_object;
598 	healed_zep.zb_level = healed_zb->zb_level;
599 	healed_zep.zb_blkid = healed_zb->zb_blkid;
600 
601 	if (birth != NULL)
602 		healed_zep.zb_birth = *birth;
603 	else
604 		healed_zep.zb_birth = 0;
605 
606 	errphys_to_name(&healed_zep, name, sizeof (name));
607 
608 	zap_cursor_t zc;
609 	zap_attribute_t za;
610 	for (zap_cursor_init(&zc, spa->spa_meta_objset, spa->spa_errlog_last);
611 	    zap_cursor_retrieve(&zc, &za) == 0; zap_cursor_advance(&zc)) {
612 		if (zap_contains(spa->spa_meta_objset, za.za_first_integer,
613 		    name) == 0) {
614 			if (!MUTEX_HELD(&spa->spa_errlog_lock)) {
615 				mutex_enter(&spa->spa_errlog_lock);
616 				held_log = B_TRUE;
617 			}
618 
619 			avl_tree_t *tree = &spa->spa_errlist_healed;
620 			spa_error_entry_t search;
621 			spa_error_entry_t *new;
622 			avl_index_t where;
623 			search.se_bookmark = *healed_zb;
624 
625 			if (!MUTEX_HELD(&spa->spa_errlist_lock)) {
626 				mutex_enter(&spa->spa_errlist_lock);
627 				held_list = B_TRUE;
628 			}
629 
630 			if (avl_find(tree, &search, &where) != NULL) {
631 				if (held_list)
632 					mutex_exit(&spa->spa_errlist_lock);
633 				if (held_log)
634 					mutex_exit(&spa->spa_errlog_lock);
635 				continue;
636 			}
637 			new = kmem_zalloc(sizeof (spa_error_entry_t), KM_SLEEP);
638 			new->se_bookmark = *healed_zb;
639 			new->se_zep = healed_zep;
640 			avl_insert(tree, new, where);
641 
642 			if (held_list)
643 				mutex_exit(&spa->spa_errlist_lock);
644 			if (held_log)
645 				mutex_exit(&spa->spa_errlog_lock);
646 		}
647 	}
648 	zap_cursor_fini(&zc);
649 }
650 
651 /*
652  * If this error exists in the given tree remove it.
653  */
654 static void
655 remove_error_from_list(spa_t *spa, avl_tree_t *t, const zbookmark_phys_t *zb)
656 {
657 	spa_error_entry_t search, *found;
658 	avl_index_t where;
659 
660 	mutex_enter(&spa->spa_errlist_lock);
661 	search.se_bookmark = *zb;
662 	if ((found = avl_find(t, &search, &where)) != NULL) {
663 		avl_remove(t, found);
664 		kmem_free(found, sizeof (spa_error_entry_t));
665 	}
666 	mutex_exit(&spa->spa_errlist_lock);
667 }
668 
669 
670 /*
671  * Removes all of the recv healed errors from both on-disk error logs
672  */
673 static void
674 spa_remove_healed_errors(spa_t *spa, avl_tree_t *s, avl_tree_t *l, dmu_tx_t *tx)
675 {
676 	char name[NAME_MAX_LEN];
677 	spa_error_entry_t *se;
678 	void *cookie = NULL;
679 
680 	ASSERT(MUTEX_HELD(&spa->spa_errlog_lock));
681 
682 	while ((se = avl_destroy_nodes(&spa->spa_errlist_healed,
683 	    &cookie)) != NULL) {
684 		remove_error_from_list(spa, s, &se->se_bookmark);
685 		remove_error_from_list(spa, l, &se->se_bookmark);
686 		kmem_free(se, sizeof (spa_error_entry_t));
687 
688 		if (!spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {
689 			bookmark_to_name(&se->se_bookmark, name, sizeof (name));
690 			(void) zap_remove(spa->spa_meta_objset,
691 			    spa->spa_errlog_last, name, tx);
692 			(void) zap_remove(spa->spa_meta_objset,
693 			    spa->spa_errlog_scrub, name, tx);
694 		} else {
695 			errphys_to_name(&se->se_zep, name, sizeof (name));
696 			zap_cursor_t zc;
697 			zap_attribute_t za;
698 			for (zap_cursor_init(&zc, spa->spa_meta_objset,
699 			    spa->spa_errlog_last);
700 			    zap_cursor_retrieve(&zc, &za) == 0;
701 			    zap_cursor_advance(&zc)) {
702 				zap_remove(spa->spa_meta_objset,
703 				    za.za_first_integer, name, tx);
704 			}
705 			zap_cursor_fini(&zc);
706 
707 			for (zap_cursor_init(&zc, spa->spa_meta_objset,
708 			    spa->spa_errlog_scrub);
709 			    zap_cursor_retrieve(&zc, &za) == 0;
710 			    zap_cursor_advance(&zc)) {
711 				zap_remove(spa->spa_meta_objset,
712 				    za.za_first_integer, name, tx);
713 			}
714 			zap_cursor_fini(&zc);
715 		}
716 	}
717 }
718 
719 /*
720  * Stash away healed bookmarks to remove them from the on-disk error logs
721  * later in spa_remove_healed_errors().
722  */
723 void
724 spa_remove_error(spa_t *spa, zbookmark_phys_t *zb, const uint64_t *birth)
725 {
726 	spa_add_healed_error(spa, spa->spa_errlog_last, zb, birth);
727 	spa_add_healed_error(spa, spa->spa_errlog_scrub, zb, birth);
728 }
729 
730 static uint64_t
731 approx_errlog_size_impl(spa_t *spa, uint64_t spa_err_obj)
732 {
733 	if (spa_err_obj == 0)
734 		return (0);
735 	uint64_t total = 0;
736 
737 	zap_cursor_t zc;
738 	zap_attribute_t za;
739 	for (zap_cursor_init(&zc, spa->spa_meta_objset, spa_err_obj);
740 	    zap_cursor_retrieve(&zc, &za) == 0; zap_cursor_advance(&zc)) {
741 		uint64_t count;
742 		if (zap_count(spa->spa_meta_objset, za.za_first_integer,
743 		    &count) == 0)
744 			total += count;
745 	}
746 	zap_cursor_fini(&zc);
747 	return (total);
748 }
749 
750 /*
751  * Return the approximate number of errors currently in the error log.  This
752  * will be nonzero if there are some errors, but otherwise it may be more
753  * or less than the number of entries returned by spa_get_errlog().
754  */
755 uint64_t
756 spa_approx_errlog_size(spa_t *spa)
757 {
758 	uint64_t total = 0;
759 
760 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {
761 		mutex_enter(&spa->spa_errlog_lock);
762 		uint64_t count;
763 		if (spa->spa_errlog_scrub != 0 &&
764 		    zap_count(spa->spa_meta_objset, spa->spa_errlog_scrub,
765 		    &count) == 0)
766 			total += count;
767 
768 		if (spa->spa_errlog_last != 0 && !spa->spa_scrub_finished &&
769 		    zap_count(spa->spa_meta_objset, spa->spa_errlog_last,
770 		    &count) == 0)
771 			total += count;
772 		mutex_exit(&spa->spa_errlog_lock);
773 
774 	} else {
775 		mutex_enter(&spa->spa_errlog_lock);
776 		total += approx_errlog_size_impl(spa, spa->spa_errlog_last);
777 		total += approx_errlog_size_impl(spa, spa->spa_errlog_scrub);
778 		mutex_exit(&spa->spa_errlog_lock);
779 	}
780 	mutex_enter(&spa->spa_errlist_lock);
781 	total += avl_numnodes(&spa->spa_errlist_last);
782 	total += avl_numnodes(&spa->spa_errlist_scrub);
783 	mutex_exit(&spa->spa_errlist_lock);
784 	return (total);
785 }
786 
787 /*
788  * This function sweeps through an on-disk error log and stores all bookmarks
789  * as error bookmarks in a new ZAP object. At the end we discard the old one,
790  * and spa_update_errlog() will set the spa's on-disk error log to new ZAP
791  * object.
792  */
793 static void
794 sync_upgrade_errlog(spa_t *spa, uint64_t spa_err_obj, uint64_t *newobj,
795     dmu_tx_t *tx)
796 {
797 	zap_cursor_t zc;
798 	zap_attribute_t za;
799 	zbookmark_phys_t zb;
800 	uint64_t count;
801 
802 	*newobj = zap_create(spa->spa_meta_objset, DMU_OT_ERROR_LOG,
803 	    DMU_OT_NONE, 0, tx);
804 
805 	/*
806 	 * If we cannnot perform the upgrade we should clear the old on-disk
807 	 * error logs.
808 	 */
809 	if (zap_count(spa->spa_meta_objset, spa_err_obj, &count) != 0) {
810 		VERIFY0(dmu_object_free(spa->spa_meta_objset, spa_err_obj, tx));
811 		return;
812 	}
813 
814 	for (zap_cursor_init(&zc, spa->spa_meta_objset, spa_err_obj);
815 	    zap_cursor_retrieve(&zc, &za) == 0;
816 	    zap_cursor_advance(&zc)) {
817 		if (spa_upgrade_errlog_limit != 0 &&
818 		    zc.zc_cd == spa_upgrade_errlog_limit)
819 			break;
820 
821 		name_to_bookmark(za.za_name, &zb);
822 
823 		zbookmark_err_phys_t zep;
824 		zep.zb_object = zb.zb_object;
825 		zep.zb_level = zb.zb_level;
826 		zep.zb_blkid = zb.zb_blkid;
827 		zep.zb_birth = 0;
828 
829 		/*
830 		 * In case of an error we should simply continue instead of
831 		 * returning prematurely. See the next comment.
832 		 */
833 		uint64_t head_ds;
834 		dsl_pool_t *dp = spa->spa_dsl_pool;
835 		dsl_dataset_t *ds;
836 		objset_t *os;
837 
838 		int error = dsl_dataset_hold_obj_flags(dp, zb.zb_objset,
839 		    DS_HOLD_FLAG_DECRYPT, FTAG, &ds);
840 		if (error != 0)
841 			continue;
842 
843 		head_ds = dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj;
844 
845 		/*
846 		 * The objset and the dnode are required for getting the block
847 		 * pointer, which is used to determine if BP_IS_HOLE(). If
848 		 * getting the objset or the dnode fails, do not create a
849 		 * zap entry (presuming we know the dataset) as this may create
850 		 * spurious errors that we cannot ever resolve. If an error is
851 		 * truly persistent, it should re-appear after a scan.
852 		 */
853 		if (dmu_objset_from_ds(ds, &os) != 0) {
854 			dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
855 			continue;
856 		}
857 
858 		dnode_t *dn;
859 		blkptr_t bp;
860 
861 		if (dnode_hold(os, zep.zb_object, FTAG, &dn) != 0) {
862 			dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
863 			continue;
864 		}
865 
866 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
867 		error = dbuf_dnode_findbp(dn, zep.zb_level, zep.zb_blkid, &bp,
868 		    NULL, NULL);
869 		if (error == EACCES)
870 			error = 0;
871 		else if (!error)
872 			zep.zb_birth = bp.blk_birth;
873 
874 		rw_exit(&dn->dn_struct_rwlock);
875 		dnode_rele(dn, FTAG);
876 		dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
877 
878 		if (error != 0 || BP_IS_HOLE(&bp))
879 			continue;
880 
881 		uint64_t err_obj;
882 		error = zap_lookup_int_key(spa->spa_meta_objset, *newobj,
883 		    head_ds, &err_obj);
884 
885 		if (error == ENOENT) {
886 			err_obj = zap_create(spa->spa_meta_objset,
887 			    DMU_OT_ERROR_LOG, DMU_OT_NONE, 0, tx);
888 
889 			(void) zap_update_int_key(spa->spa_meta_objset,
890 			    *newobj, head_ds, err_obj, tx);
891 		}
892 
893 		char buf[64];
894 		errphys_to_name(&zep, buf, sizeof (buf));
895 
896 		const char *name = "";
897 		(void) zap_update(spa->spa_meta_objset, err_obj,
898 		    buf, 1, strlen(name) + 1, name, tx);
899 	}
900 	zap_cursor_fini(&zc);
901 
902 	VERIFY0(dmu_object_free(spa->spa_meta_objset, spa_err_obj, tx));
903 }
904 
905 void
906 spa_upgrade_errlog(spa_t *spa, dmu_tx_t *tx)
907 {
908 	uint64_t newobj = 0;
909 
910 	mutex_enter(&spa->spa_errlog_lock);
911 	if (spa->spa_errlog_last != 0) {
912 		sync_upgrade_errlog(spa, spa->spa_errlog_last, &newobj, tx);
913 		spa->spa_errlog_last = newobj;
914 	}
915 
916 	if (spa->spa_errlog_scrub != 0) {
917 		sync_upgrade_errlog(spa, spa->spa_errlog_scrub, &newobj, tx);
918 		spa->spa_errlog_scrub = newobj;
919 	}
920 	mutex_exit(&spa->spa_errlog_lock);
921 }
922 
923 #ifdef _KERNEL
924 /*
925  * If an error block is shared by two datasets it will be counted twice.
926  */
927 static int
928 process_error_log(spa_t *spa, uint64_t obj, void *uaddr, uint64_t *count)
929 {
930 	if (obj == 0)
931 		return (0);
932 
933 	zap_cursor_t *zc;
934 	zap_attribute_t *za;
935 
936 	zc = kmem_zalloc(sizeof (zap_cursor_t), KM_SLEEP);
937 	za = kmem_zalloc(sizeof (zap_attribute_t), KM_SLEEP);
938 
939 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {
940 		for (zap_cursor_init(zc, spa->spa_meta_objset, obj);
941 		    zap_cursor_retrieve(zc, za) == 0;
942 		    zap_cursor_advance(zc)) {
943 			if (*count == 0) {
944 				zap_cursor_fini(zc);
945 				kmem_free(zc, sizeof (*zc));
946 				kmem_free(za, sizeof (*za));
947 				return (SET_ERROR(ENOMEM));
948 			}
949 
950 			zbookmark_phys_t zb;
951 			name_to_bookmark(za->za_name, &zb);
952 
953 			int error = copyout_entry(&zb, uaddr, count);
954 			if (error != 0) {
955 				zap_cursor_fini(zc);
956 				kmem_free(zc, sizeof (*zc));
957 				kmem_free(za, sizeof (*za));
958 				return (error);
959 			}
960 		}
961 		zap_cursor_fini(zc);
962 		kmem_free(zc, sizeof (*zc));
963 		kmem_free(za, sizeof (*za));
964 		return (0);
965 	}
966 
967 	for (zap_cursor_init(zc, spa->spa_meta_objset, obj);
968 	    zap_cursor_retrieve(zc, za) == 0;
969 	    zap_cursor_advance(zc)) {
970 
971 		zap_cursor_t *head_ds_cursor;
972 		zap_attribute_t *head_ds_attr;
973 
974 		head_ds_cursor = kmem_zalloc(sizeof (zap_cursor_t), KM_SLEEP);
975 		head_ds_attr = kmem_zalloc(sizeof (zap_attribute_t), KM_SLEEP);
976 
977 		uint64_t head_ds_err_obj = za->za_first_integer;
978 		uint64_t head_ds;
979 		name_to_object(za->za_name, &head_ds);
980 		for (zap_cursor_init(head_ds_cursor, spa->spa_meta_objset,
981 		    head_ds_err_obj); zap_cursor_retrieve(head_ds_cursor,
982 		    head_ds_attr) == 0; zap_cursor_advance(head_ds_cursor)) {
983 
984 			zbookmark_err_phys_t head_ds_block;
985 			name_to_errphys(head_ds_attr->za_name, &head_ds_block);
986 			int error = process_error_block(spa, head_ds,
987 			    &head_ds_block, uaddr, count);
988 
989 			if (error != 0) {
990 				zap_cursor_fini(head_ds_cursor);
991 				kmem_free(head_ds_cursor,
992 				    sizeof (*head_ds_cursor));
993 				kmem_free(head_ds_attr, sizeof (*head_ds_attr));
994 
995 				zap_cursor_fini(zc);
996 				kmem_free(za, sizeof (*za));
997 				kmem_free(zc, sizeof (*zc));
998 				return (error);
999 			}
1000 		}
1001 		zap_cursor_fini(head_ds_cursor);
1002 		kmem_free(head_ds_cursor, sizeof (*head_ds_cursor));
1003 		kmem_free(head_ds_attr, sizeof (*head_ds_attr));
1004 	}
1005 	zap_cursor_fini(zc);
1006 	kmem_free(za, sizeof (*za));
1007 	kmem_free(zc, sizeof (*zc));
1008 	return (0);
1009 }
1010 
1011 static int
1012 process_error_list(spa_t *spa, avl_tree_t *list, void *uaddr, uint64_t *count)
1013 {
1014 	spa_error_entry_t *se;
1015 
1016 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {
1017 		for (se = avl_first(list); se != NULL;
1018 		    se = AVL_NEXT(list, se)) {
1019 			int error =
1020 			    copyout_entry(&se->se_bookmark, uaddr, count);
1021 			if (error != 0) {
1022 				return (error);
1023 			}
1024 		}
1025 		return (0);
1026 	}
1027 
1028 	for (se = avl_first(list); se != NULL; se = AVL_NEXT(list, se)) {
1029 		uint64_t head_ds = 0;
1030 		int error = get_head_ds(spa, se->se_bookmark.zb_objset,
1031 		    &head_ds);
1032 
1033 		/*
1034 		 * If get_head_ds() errors out, set the head filesystem
1035 		 * to the filesystem stored in the bookmark of the
1036 		 * error block.
1037 		 */
1038 		if (error != 0)
1039 			head_ds = se->se_bookmark.zb_objset;
1040 
1041 		error = process_error_block(spa, head_ds,
1042 		    &se->se_zep, uaddr, count);
1043 		if (error != 0)
1044 			return (error);
1045 	}
1046 	return (0);
1047 }
1048 #endif
1049 
1050 /*
1051  * Copy all known errors to userland as an array of bookmarks.  This is
1052  * actually a union of the on-disk last log and current log, as well as any
1053  * pending error requests.
1054  *
1055  * Because the act of reading the on-disk log could cause errors to be
1056  * generated, we have two separate locks: one for the error log and one for the
1057  * in-core error lists.  We only need the error list lock to log and error, so
1058  * we grab the error log lock while we read the on-disk logs, and only pick up
1059  * the error list lock when we are finished.
1060  */
1061 int
1062 spa_get_errlog(spa_t *spa, void *uaddr, uint64_t *count)
1063 {
1064 	int ret = 0;
1065 
1066 #ifdef _KERNEL
1067 	/*
1068 	 * The pool config lock is needed to hold a dataset_t via (among other
1069 	 * places) process_error_list() -> process_error_block()->
1070 	 * find_top_affected_fs(), and lock ordering requires that we get it
1071 	 * before the spa_errlog_lock.
1072 	 */
1073 	dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
1074 	mutex_enter(&spa->spa_errlog_lock);
1075 
1076 	ret = process_error_log(spa, spa->spa_errlog_scrub, uaddr, count);
1077 
1078 	if (!ret && !spa->spa_scrub_finished)
1079 		ret = process_error_log(spa, spa->spa_errlog_last, uaddr,
1080 		    count);
1081 
1082 	mutex_enter(&spa->spa_errlist_lock);
1083 	if (!ret)
1084 		ret = process_error_list(spa, &spa->spa_errlist_scrub, uaddr,
1085 		    count);
1086 	if (!ret)
1087 		ret = process_error_list(spa, &spa->spa_errlist_last, uaddr,
1088 		    count);
1089 	mutex_exit(&spa->spa_errlist_lock);
1090 
1091 	mutex_exit(&spa->spa_errlog_lock);
1092 	dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
1093 #else
1094 	(void) spa, (void) uaddr, (void) count;
1095 #endif
1096 
1097 	return (ret);
1098 }
1099 
1100 /*
1101  * Called when a scrub completes.  This simply set a bit which tells which AVL
1102  * tree to add new errors.  spa_errlog_sync() is responsible for actually
1103  * syncing the changes to the underlying objects.
1104  */
1105 void
1106 spa_errlog_rotate(spa_t *spa)
1107 {
1108 	mutex_enter(&spa->spa_errlist_lock);
1109 	spa->spa_scrub_finished = B_TRUE;
1110 	mutex_exit(&spa->spa_errlist_lock);
1111 }
1112 
1113 /*
1114  * Discard any pending errors from the spa_t.  Called when unloading a faulted
1115  * pool, as the errors encountered during the open cannot be synced to disk.
1116  */
1117 void
1118 spa_errlog_drain(spa_t *spa)
1119 {
1120 	spa_error_entry_t *se;
1121 	void *cookie;
1122 
1123 	mutex_enter(&spa->spa_errlist_lock);
1124 
1125 	cookie = NULL;
1126 	while ((se = avl_destroy_nodes(&spa->spa_errlist_last,
1127 	    &cookie)) != NULL)
1128 		kmem_free(se, sizeof (spa_error_entry_t));
1129 	cookie = NULL;
1130 	while ((se = avl_destroy_nodes(&spa->spa_errlist_scrub,
1131 	    &cookie)) != NULL)
1132 		kmem_free(se, sizeof (spa_error_entry_t));
1133 
1134 	mutex_exit(&spa->spa_errlist_lock);
1135 }
1136 
1137 /*
1138  * Process a list of errors into the current on-disk log.
1139  */
1140 void
1141 sync_error_list(spa_t *spa, avl_tree_t *t, uint64_t *obj, dmu_tx_t *tx)
1142 {
1143 	spa_error_entry_t *se;
1144 	char buf[NAME_MAX_LEN];
1145 	void *cookie;
1146 
1147 	if (avl_numnodes(t) == 0)
1148 		return;
1149 
1150 	/* create log if necessary */
1151 	if (*obj == 0)
1152 		*obj = zap_create(spa->spa_meta_objset, DMU_OT_ERROR_LOG,
1153 		    DMU_OT_NONE, 0, tx);
1154 
1155 	/* add errors to the current log */
1156 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {
1157 		for (se = avl_first(t); se != NULL; se = AVL_NEXT(t, se)) {
1158 			bookmark_to_name(&se->se_bookmark, buf, sizeof (buf));
1159 
1160 			const char *name = se->se_name ? se->se_name : "";
1161 			(void) zap_update(spa->spa_meta_objset, *obj, buf, 1,
1162 			    strlen(name) + 1, name, tx);
1163 		}
1164 	} else {
1165 		for (se = avl_first(t); se != NULL; se = AVL_NEXT(t, se)) {
1166 			zbookmark_err_phys_t zep;
1167 			zep.zb_object = se->se_zep.zb_object;
1168 			zep.zb_level = se->se_zep.zb_level;
1169 			zep.zb_blkid = se->se_zep.zb_blkid;
1170 			zep.zb_birth = se->se_zep.zb_birth;
1171 
1172 			uint64_t head_ds = 0;
1173 			int error = get_head_ds(spa, se->se_bookmark.zb_objset,
1174 			    &head_ds);
1175 
1176 			/*
1177 			 * If get_head_ds() errors out, set the head filesystem
1178 			 * to the filesystem stored in the bookmark of the
1179 			 * error block.
1180 			 */
1181 			if (error != 0)
1182 				head_ds = se->se_bookmark.zb_objset;
1183 
1184 			uint64_t err_obj;
1185 			error = zap_lookup_int_key(spa->spa_meta_objset,
1186 			    *obj, head_ds, &err_obj);
1187 
1188 			if (error == ENOENT) {
1189 				err_obj = zap_create(spa->spa_meta_objset,
1190 				    DMU_OT_ERROR_LOG, DMU_OT_NONE, 0, tx);
1191 
1192 				(void) zap_update_int_key(spa->spa_meta_objset,
1193 				    *obj, head_ds, err_obj, tx);
1194 			}
1195 			errphys_to_name(&zep, buf, sizeof (buf));
1196 
1197 			const char *name = se->se_name ? se->se_name : "";
1198 			(void) zap_update(spa->spa_meta_objset,
1199 			    err_obj, buf, 1, strlen(name) + 1, name, tx);
1200 		}
1201 	}
1202 	/* purge the error list */
1203 	cookie = NULL;
1204 	while ((se = avl_destroy_nodes(t, &cookie)) != NULL)
1205 		kmem_free(se, sizeof (spa_error_entry_t));
1206 }
1207 
1208 static void
1209 delete_errlog(spa_t *spa, uint64_t spa_err_obj, dmu_tx_t *tx)
1210 {
1211 	if (spa_feature_is_enabled(spa, SPA_FEATURE_HEAD_ERRLOG)) {
1212 		zap_cursor_t zc;
1213 		zap_attribute_t za;
1214 		for (zap_cursor_init(&zc, spa->spa_meta_objset, spa_err_obj);
1215 		    zap_cursor_retrieve(&zc, &za) == 0;
1216 		    zap_cursor_advance(&zc)) {
1217 			VERIFY0(dmu_object_free(spa->spa_meta_objset,
1218 			    za.za_first_integer, tx));
1219 		}
1220 		zap_cursor_fini(&zc);
1221 	}
1222 	VERIFY0(dmu_object_free(spa->spa_meta_objset, spa_err_obj, tx));
1223 }
1224 
1225 /*
1226  * Sync the error log out to disk.  This is a little tricky because the act of
1227  * writing the error log requires the spa_errlist_lock.  So, we need to lock the
1228  * error lists, take a copy of the lists, and then reinitialize them.  Then, we
1229  * drop the error list lock and take the error log lock, at which point we
1230  * do the errlog processing.  Then, if we encounter an I/O error during this
1231  * process, we can successfully add the error to the list.  Note that this will
1232  * result in the perpetual recycling of errors, but it is an unlikely situation
1233  * and not a performance critical operation.
1234  */
1235 void
1236 spa_errlog_sync(spa_t *spa, uint64_t txg)
1237 {
1238 	dmu_tx_t *tx;
1239 	avl_tree_t scrub, last;
1240 	int scrub_finished;
1241 
1242 	mutex_enter(&spa->spa_errlist_lock);
1243 
1244 	/*
1245 	 * Bail out early under normal circumstances.
1246 	 */
1247 	if (avl_numnodes(&spa->spa_errlist_scrub) == 0 &&
1248 	    avl_numnodes(&spa->spa_errlist_last) == 0 &&
1249 	    avl_numnodes(&spa->spa_errlist_healed) == 0 &&
1250 	    !spa->spa_scrub_finished) {
1251 		mutex_exit(&spa->spa_errlist_lock);
1252 		return;
1253 	}
1254 
1255 	spa_get_errlists(spa, &last, &scrub);
1256 	scrub_finished = spa->spa_scrub_finished;
1257 	spa->spa_scrub_finished = B_FALSE;
1258 
1259 	mutex_exit(&spa->spa_errlist_lock);
1260 
1261 	/*
1262 	 * The pool config lock is needed to hold a dataset_t via
1263 	 * sync_error_list() -> get_head_ds(), and lock ordering
1264 	 * requires that we get it before the spa_errlog_lock.
1265 	 */
1266 	dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
1267 	mutex_enter(&spa->spa_errlog_lock);
1268 
1269 	tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
1270 
1271 	/*
1272 	 * Remove healed errors from errors.
1273 	 */
1274 	spa_remove_healed_errors(spa, &last, &scrub, tx);
1275 
1276 	/*
1277 	 * Sync out the current list of errors.
1278 	 */
1279 	sync_error_list(spa, &last, &spa->spa_errlog_last, tx);
1280 
1281 	/*
1282 	 * Rotate the log if necessary.
1283 	 */
1284 	if (scrub_finished) {
1285 		if (spa->spa_errlog_last != 0)
1286 			delete_errlog(spa, spa->spa_errlog_last, tx);
1287 		spa->spa_errlog_last = spa->spa_errlog_scrub;
1288 		spa->spa_errlog_scrub = 0;
1289 
1290 		sync_error_list(spa, &scrub, &spa->spa_errlog_last, tx);
1291 	}
1292 
1293 	/*
1294 	 * Sync out any pending scrub errors.
1295 	 */
1296 	sync_error_list(spa, &scrub, &spa->spa_errlog_scrub, tx);
1297 
1298 	/*
1299 	 * Update the MOS to reflect the new values.
1300 	 */
1301 	(void) zap_update(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1302 	    DMU_POOL_ERRLOG_LAST, sizeof (uint64_t), 1,
1303 	    &spa->spa_errlog_last, tx);
1304 	(void) zap_update(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1305 	    DMU_POOL_ERRLOG_SCRUB, sizeof (uint64_t), 1,
1306 	    &spa->spa_errlog_scrub, tx);
1307 
1308 	dmu_tx_commit(tx);
1309 
1310 	mutex_exit(&spa->spa_errlog_lock);
1311 	dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
1312 }
1313 
1314 static void
1315 delete_dataset_errlog(spa_t *spa, uint64_t spa_err_obj, uint64_t ds,
1316     dmu_tx_t *tx)
1317 {
1318 	if (spa_err_obj == 0)
1319 		return;
1320 
1321 	zap_cursor_t zc;
1322 	zap_attribute_t za;
1323 	for (zap_cursor_init(&zc, spa->spa_meta_objset, spa_err_obj);
1324 	    zap_cursor_retrieve(&zc, &za) == 0; zap_cursor_advance(&zc)) {
1325 		uint64_t head_ds;
1326 		name_to_object(za.za_name, &head_ds);
1327 		if (head_ds == ds) {
1328 			(void) zap_remove(spa->spa_meta_objset, spa_err_obj,
1329 			    za.za_name, tx);
1330 			VERIFY0(dmu_object_free(spa->spa_meta_objset,
1331 			    za.za_first_integer, tx));
1332 			break;
1333 		}
1334 	}
1335 	zap_cursor_fini(&zc);
1336 }
1337 
1338 void
1339 spa_delete_dataset_errlog(spa_t *spa, uint64_t ds, dmu_tx_t *tx)
1340 {
1341 	mutex_enter(&spa->spa_errlog_lock);
1342 	delete_dataset_errlog(spa, spa->spa_errlog_scrub, ds, tx);
1343 	delete_dataset_errlog(spa, spa->spa_errlog_last, ds, tx);
1344 	mutex_exit(&spa->spa_errlog_lock);
1345 }
1346 
1347 static int
1348 find_txg_ancestor_snapshot(spa_t *spa, uint64_t new_head, uint64_t old_head,
1349     uint64_t *txg)
1350 {
1351 	dsl_dataset_t *ds;
1352 	dsl_pool_t *dp = spa->spa_dsl_pool;
1353 
1354 	int error = dsl_dataset_hold_obj_flags(dp, old_head,
1355 	    DS_HOLD_FLAG_DECRYPT, FTAG, &ds);
1356 	if (error != 0)
1357 		return (error);
1358 
1359 	uint64_t prev_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
1360 	uint64_t prev_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
1361 
1362 	while (prev_obj != 0) {
1363 		dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
1364 		if ((error = dsl_dataset_hold_obj_flags(dp, prev_obj,
1365 		    DS_HOLD_FLAG_DECRYPT, FTAG, &ds)) == 0 &&
1366 		    dsl_dir_phys(ds->ds_dir)->dd_head_dataset_obj == new_head)
1367 			break;
1368 
1369 		if (error != 0)
1370 			return (error);
1371 
1372 		prev_obj_txg = dsl_dataset_phys(ds)->ds_prev_snap_txg;
1373 		prev_obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
1374 	}
1375 	dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
1376 	ASSERT(prev_obj != 0);
1377 	*txg = prev_obj_txg;
1378 	return (0);
1379 }
1380 
1381 static void
1382 swap_errlog(spa_t *spa, uint64_t spa_err_obj, uint64_t new_head, uint64_t
1383     old_head, dmu_tx_t *tx)
1384 {
1385 	if (spa_err_obj == 0)
1386 		return;
1387 
1388 	uint64_t old_head_errlog;
1389 	int error = zap_lookup_int_key(spa->spa_meta_objset, spa_err_obj,
1390 	    old_head, &old_head_errlog);
1391 
1392 	/* If no error log, then there is nothing to do. */
1393 	if (error != 0)
1394 		return;
1395 
1396 	uint64_t txg;
1397 	error = find_txg_ancestor_snapshot(spa, new_head, old_head, &txg);
1398 	if (error != 0)
1399 		return;
1400 
1401 	/*
1402 	 * Create an error log if the file system being promoted does not
1403 	 * already have one.
1404 	 */
1405 	uint64_t new_head_errlog;
1406 	error = zap_lookup_int_key(spa->spa_meta_objset, spa_err_obj, new_head,
1407 	    &new_head_errlog);
1408 
1409 	if (error != 0) {
1410 		new_head_errlog = zap_create(spa->spa_meta_objset,
1411 		    DMU_OT_ERROR_LOG, DMU_OT_NONE, 0, tx);
1412 
1413 		(void) zap_update_int_key(spa->spa_meta_objset, spa_err_obj,
1414 		    new_head, new_head_errlog, tx);
1415 	}
1416 
1417 	zap_cursor_t zc;
1418 	zap_attribute_t za;
1419 	zbookmark_err_phys_t err_block;
1420 	for (zap_cursor_init(&zc, spa->spa_meta_objset, old_head_errlog);
1421 	    zap_cursor_retrieve(&zc, &za) == 0; zap_cursor_advance(&zc)) {
1422 
1423 		const char *name = "";
1424 		name_to_errphys(za.za_name, &err_block);
1425 		if (err_block.zb_birth < txg) {
1426 			(void) zap_update(spa->spa_meta_objset, new_head_errlog,
1427 			    za.za_name, 1, strlen(name) + 1, name, tx);
1428 
1429 			(void) zap_remove(spa->spa_meta_objset, old_head_errlog,
1430 			    za.za_name, tx);
1431 		}
1432 	}
1433 	zap_cursor_fini(&zc);
1434 }
1435 
1436 void
1437 spa_swap_errlog(spa_t *spa, uint64_t new_head_ds, uint64_t old_head_ds,
1438     dmu_tx_t *tx)
1439 {
1440 	mutex_enter(&spa->spa_errlog_lock);
1441 	swap_errlog(spa, spa->spa_errlog_scrub, new_head_ds, old_head_ds, tx);
1442 	swap_errlog(spa, spa->spa_errlog_last, new_head_ds, old_head_ds, tx);
1443 	mutex_exit(&spa->spa_errlog_lock);
1444 }
1445 
1446 #if defined(_KERNEL)
1447 /* error handling */
1448 EXPORT_SYMBOL(spa_log_error);
1449 EXPORT_SYMBOL(spa_approx_errlog_size);
1450 EXPORT_SYMBOL(spa_get_errlog);
1451 EXPORT_SYMBOL(spa_errlog_rotate);
1452 EXPORT_SYMBOL(spa_errlog_drain);
1453 EXPORT_SYMBOL(spa_errlog_sync);
1454 EXPORT_SYMBOL(spa_get_errlists);
1455 EXPORT_SYMBOL(spa_delete_dataset_errlog);
1456 EXPORT_SYMBOL(spa_swap_errlog);
1457 EXPORT_SYMBOL(sync_error_list);
1458 EXPORT_SYMBOL(spa_upgrade_errlog);
1459 #endif
1460 
1461 /* BEGIN CSTYLED */
1462 ZFS_MODULE_PARAM(zfs_spa, spa_, upgrade_errlog_limit, UINT, ZMOD_RW,
1463 	"Limit the number of errors which will be upgraded to the new "
1464 	"on-disk error log when enabling head_errlog");
1465 /* END CSTYLED */
1466