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