Skip to content

Commit f1069a3

Browse files
authored
eth/downloader: improve deliverNodeData (bnb-chain#3588)
Commit d3b751e accidentally deleted a crucial 'return' statement, leading to a crash in case of an issue with node data. This change improves the fix in PR bnb-chain#3591 by removing the lock entirely.
1 parent 2718b42 commit f1069a3

1 file changed

Lines changed: 52 additions & 72 deletions

File tree

‎eth/downloader/queue.go‎

Lines changed: 52 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import (
2323
"errors"
2424
"fmt"
2525
"sync"
26-
"sync/atomic"
2726
"time"
2827

2928
"github.com/ethereum/go-ethereum/common"
@@ -101,10 +100,9 @@ type queue struct {
101100
stateTaskQueue *prque.Prque // [eth/63] Priority queue of the hashes to fetch the node data for
102101
statePendPool map[string]*fetchRequest // [eth/63] Currently pending node data retrieval operations
103102

104-
stateDatabase ethdb.Database // [eth/63] Trie database to populate during state reassembly
105-
stateScheduler *state.StateSync // [eth/63] State trie synchronisation scheduler and integrator
106-
stateProcessors int32 // [eth/63] Number of currently running state processors
107-
stateSchedLock sync.RWMutex // [eth/63] Lock serialising access to the state scheduler
103+
stateDatabase ethdb.Database // [eth/63] Trie database to populate during state reassembly
104+
stateScheduler *state.StateSync // [eth/63] State trie synchronisation scheduler and integrator
105+
stateWriters int // [eth/63] Number of running state DB writer goroutines
108106

109107
resultCache []*fetchResult // Downloaded but not yet delivered fetch results
110108
resultOffset uint64 // Offset of the first cached fetch result in the block chain
@@ -143,9 +141,6 @@ func (q *queue) Reset() {
143141
q.lock.Lock()
144142
defer q.lock.Unlock()
145143

146-
q.stateSchedLock.Lock()
147-
defer q.stateSchedLock.Unlock()
148-
149144
q.closed = false
150145
q.mode = FullSync
151146
q.fastSyncPivot = 0
@@ -209,13 +204,24 @@ func (q *queue) PendingReceipts() int {
209204

210205
// PendingNodeData retrieves the number of node data entries pending for retrieval.
211206
func (q *queue) PendingNodeData() int {
212-
q.stateSchedLock.RLock()
213-
defer q.stateSchedLock.RUnlock()
207+
q.lock.Lock()
208+
defer q.lock.Unlock()
214209

210+
return q.pendingNodeDataLocked()
211+
}
212+
213+
// pendingNodeDataLocked retrieves the number of node data entries pending for retrieval.
214+
// The caller must hold q.lock.
215+
func (q *queue) pendingNodeDataLocked() int {
216+
var n int
215217
if q.stateScheduler != nil {
216-
return q.stateScheduler.Pending()
218+
n = q.stateScheduler.Pending()
219+
}
220+
// Ensure that PendingNodeData doesn't return 0 until all state is written.
221+
if q.stateWriters > 0 {
222+
n++
217223
}
218-
return 0
224+
return n
219225
}
220226

221227
// InFlightHeaders retrieves whether there are header fetch requests currently
@@ -251,7 +257,7 @@ func (q *queue) InFlightNodeData() bool {
251257
q.lock.Lock()
252258
defer q.lock.Unlock()
253259

254-
return len(q.statePendPool)+int(atomic.LoadInt32(&q.stateProcessors)) > 0
260+
return len(q.statePendPool)+q.stateWriters > 0
255261
}
256262

257263
// Idle returns if the queue is fully idle or has some data still inside. This
@@ -264,12 +270,9 @@ func (q *queue) Idle() bool {
264270
pending := len(q.blockPendPool) + len(q.receiptPendPool) + len(q.statePendPool)
265271
cached := len(q.blockDonePool) + len(q.receiptDonePool)
266272

267-
q.stateSchedLock.RLock()
268273
if q.stateScheduler != nil {
269274
queued += q.stateScheduler.Pending()
270275
}
271-
q.stateSchedLock.RUnlock()
272-
273276
return (queued + pending + cached) == 0
274277
}
275278

@@ -398,9 +401,7 @@ func (q *queue) Schedule(headers []*types.Header, from uint64) []*types.Header {
398401
req.Hashes = make(map[common.Hash]int) // Make sure executing requests fail, but don't disappear
399402
}
400403

401-
q.stateSchedLock.Lock()
402404
q.stateScheduler = state.NewStateSync(header.Root, q.stateDatabase)
403-
q.stateSchedLock.Unlock()
404405
}
405406
inserts = append(inserts, header)
406407
q.headerHead = hash
@@ -459,7 +460,7 @@ func (q *queue) countProcessableItems() int {
459460
// resultCache has space for fsHeaderForceVerify items. Not
460461
// doing this could leave us unable to download the required
461462
// amount of headers.
462-
if i > 0 || len(q.stateTaskPool) > 0 || q.PendingNodeData() > 0 {
463+
if i > 0 || len(q.stateTaskPool) > 0 || q.pendingNodeDataLocked() > 0 {
463464
return i
464465
}
465466
for j := 0; j < fsHeaderForceVerify; j++ {
@@ -524,9 +525,6 @@ func (q *queue) ReserveHeaders(p *peer, count int) *fetchRequest {
524525
func (q *queue) ReserveNodeData(p *peer, count int) *fetchRequest {
525526
// Create a task generator to fetch status-fetch tasks if all schedules ones are done
526527
generator := func(max int) {
527-
q.stateSchedLock.Lock()
528-
defer q.stateSchedLock.Unlock()
529-
530528
if q.stateScheduler != nil {
531529
for _, hash := range q.stateScheduler.Missing(max) {
532530
q.stateTaskPool[hash] = q.stateTaskIndex
@@ -1068,7 +1066,7 @@ func (q *queue) DeliverNodeData(id string, data [][]byte, callback func(int, boo
10681066
}
10691067
}
10701068
// Iterate over the downloaded data and verify each of them
1071-
accepted, errs := 0, make([]error, 0)
1069+
errs := make([]error, 0)
10721070
process := []trie.SyncResult{}
10731071
for _, blob := range data {
10741072
// Skip any state trie entries that were not requested
@@ -1079,68 +1077,50 @@ func (q *queue) DeliverNodeData(id string, data [][]byte, callback func(int, boo
10791077
}
10801078
// Inject the next state trie item into the processing queue
10811079
process = append(process, trie.SyncResult{Hash: hash, Data: blob})
1082-
accepted++
1083-
10841080
delete(request.Hashes, hash)
10851081
delete(q.stateTaskPool, hash)
10861082
}
1087-
// Start the asynchronous node state data injection
1088-
atomic.AddInt32(&q.stateProcessors, 1)
1089-
go func() {
1090-
defer atomic.AddInt32(&q.stateProcessors, -1)
1091-
q.deliverNodeData(process, callback)
1092-
}()
10931083
// Return all failed or missing fetches to the queue
10941084
for hash, index := range request.Hashes {
10951085
q.stateTaskQueue.Push(hash, float32(index))
10961086
}
1087+
if q.stateScheduler == nil {
1088+
return 0, errNoFetchesPending
1089+
}
1090+
1091+
// Run valid nodes through the trie download scheduler. It writes completed nodes to a
1092+
// batch, which is committed asynchronously. This may lead to over-fetches because the
1093+
// scheduler treats everything as written after Process has returned, but it's
1094+
// unlikely to be an issue in practice.
1095+
batch := q.stateDatabase.NewBatch()
1096+
progressed, nproc, procerr := q.stateScheduler.Process(process, batch)
1097+
q.stateWriters += 1
1098+
go func() {
1099+
if procerr == nil {
1100+
nproc = len(process)
1101+
procerr = batch.Write()
1102+
}
1103+
// Return processing errors through the callback so the sync gets canceled. The
1104+
// number of writers is decremented prior to the call so PendingNodeData will
1105+
// return zero when the callback runs.
1106+
q.lock.Lock()
1107+
q.stateWriters -= 1
1108+
q.lock.Unlock()
1109+
callback(nproc, progressed, procerr)
1110+
// Wake up WaitResults after the state has been written because it might be
1111+
// waiting for completion of the pivot block's state download.
1112+
q.active.Signal()
1113+
}()
1114+
10971115
// If none of the data items were good, it's a stale delivery
10981116
switch {
10991117
case len(errs) == 0:
1100-
return accepted, nil
1118+
return len(process), nil
11011119
case len(errs) == len(request.Hashes):
1102-
return accepted, errStaleDelivery
1120+
return len(process), errStaleDelivery
11031121
default:
1104-
return accepted, fmt.Errorf("multiple failures: %v", errs)
1105-
}
1106-
}
1107-
1108-
// deliverNodeData is the asynchronous node data processor that injects a batch
1109-
// of sync results into the state scheduler.
1110-
func (q *queue) deliverNodeData(results []trie.SyncResult, callback func(int, bool, error)) {
1111-
// Wake up WaitResults after the state has been written because it
1112-
// might be waiting for the pivot block state to get completed.
1113-
defer q.active.Signal()
1114-
1115-
// Process results one by one to permit task fetches in between
1116-
progressed := false
1117-
for i, result := range results {
1118-
q.stateSchedLock.Lock()
1119-
1120-
if q.stateScheduler == nil {
1121-
// Syncing aborted since this async delivery started, bail out
1122-
q.stateSchedLock.Unlock()
1123-
callback(i, progressed, errNoFetchesPending)
1124-
return
1125-
}
1126-
1127-
batch := q.stateDatabase.NewBatch()
1128-
prog, _, err := q.stateScheduler.Process([]trie.SyncResult{result}, batch)
1129-
if err != nil {
1130-
q.stateSchedLock.Unlock()
1131-
callback(i, progressed, err)
1132-
return
1133-
}
1134-
if err = batch.Write(); err != nil {
1135-
q.stateSchedLock.Unlock()
1136-
callback(i, progressed, err)
1137-
return // TODO(karalabe): If a DB write fails (disk full), we ought to cancel the sync
1138-
}
1139-
// Item processing succeeded, release the lock (temporarily)
1140-
progressed = progressed || prog
1141-
q.stateSchedLock.Unlock()
1122+
return len(process), fmt.Errorf("multiple failures: %v", errs)
11421123
}
1143-
callback(len(results), progressed, nil)
11441124
}
11451125

11461126
// Prepare configures the result cache to allow accepting and caching inbound

0 commit comments

Comments
 (0)