From 267fe9a6b70d2d812f0ac6f19945d9488d10ba35 Mon Sep 17 00:00:00 2001
From: Mark Andrews <marka@isc.org>
Date: Tue, 8 Sep 2020 13:42:07 +1000
Subject: [PATCH] Pause dbiterator ealier to prevent lock-order-inversion

    WARNING: ThreadSanitizer: lock-order-inversion (potential deadlock)
    Cycle in lock order graph: M1 (0x000000000000) => M2 (0x000000000000) => M1

    Mutex M2 acquired here while holding mutex M1 in thread T1:
    #0 pthread_rwlock_rdlock <null>
    #1 isc_rwlock_lock lib/isc/rwlock.c:48:3
    #2 findnodeintree lib/dns/rbtdb.c:2877:2
    #3 findnode lib/dns/rbtdb.c:2941:10
    #4 dns_db_findnode lib/dns/db.c:439:11
    #5 resume_addnsec3chain lib/dns/zone.c:3776:11
    #6 rss_post lib/dns/zone.c:20659:3
    #7 setnsec3param lib/dns/zone.c:20471:3
    #8 dispatch lib/isc/task.c:1152:7
    #9 run lib/isc/task.c:1344:2

    Mutex M1 previously acquired by the same thread here:
    #0 pthread_mutex_lock <null>
    #1 rss_post lib/dns/zone.c:20658:3
    #2 setnsec3param lib/dns/zone.c:20471:3
    #3 dispatch lib/isc/task.c:1152:7
    #4 run lib/isc/task.c:1344:2

    Mutex M1 acquired here while holding mutex M2 in thread T2:
    #0 pthread_mutex_lock <null>
    #1 zone_nsec3chain lib/dns/zone.c:8666:5
    #2 zone_maintenance lib/dns/zone.c:11063:4
    #3 zone_timer lib/dns/zone.c:14098:2
    #4 dispatch lib/isc/task.c:1152:7
    #5 run lib/isc/task.c:1344:2

    Mutex M2 previously acquired by the same thread here:
    #0 pthread_rwlock_rdlock <null>
    #1 isc_rwlock_lock lib/isc/rwlock.c:48:3
    #2 resume_iteration lib/dns/rbtdb.c:9357:2
    #3 dbiterator_next lib/dns/rbtdb.c:9647:3
    #4 dns_dbiterator_next lib/dns/dbiterator.c:87:10
    #5 zone_nsec3chain lib/dns/zone.c:8656:13
    #6 zone_maintenance lib/dns/zone.c:11063:4
    #7 zone_timer lib/dns/zone.c:14098:2
    #8 dispatch lib/isc/task.c:1152:7
    #9 run lib/isc/task.c:1344:2

(cherry picked from commit 9e584a45114849637c0ab04e9410ba5fc00b054d)
Conflict: NA
Reference: https://gitlab.isc.org/isc-projects/bind9/-/commit/267fe9a6b70d2d812f0ac6f19945d9488d10ba35
---
 lib/dns/zone.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/dns/zone.c b/lib/dns/zone.c
index a81733f828..096ff82f34 100644
--- a/lib/dns/zone.c
+++ b/lib/dns/zone.c
@@ -8093,12 +8093,12 @@ zone_nsec3chain(dns_zone_t *zone) {
 				goto same_removechain;
 			}
 			if (result == ISC_R_NOMORE) {
+				dns_dbiterator_pause(nsec3chain->dbiterator);
 				LOCK_ZONE(zone);
 				ISC_LIST_UNLINK(zone->nsec3chain, nsec3chain,
 						link);
 				UNLOCK_ZONE(zone);
 				ISC_LIST_APPEND(cleanup, nsec3chain, link);
-				dns_dbiterator_pause(nsec3chain->dbiterator);
 				result = fixup_nsec3param(db, version,
 							  nsec3chain, false,
 							  privatetype,
-- 
2.23.0

