]> Sergey Matveev's repositories - btrtrc.git/blob - piece.go
Drop support for go 1.20
[btrtrc.git] / piece.go
1 package torrent
2
3 import (
4         "fmt"
5         "sync"
6
7         "github.com/anacrolix/chansync"
8         "github.com/anacrolix/missinggo/v2/bitmap"
9
10         "github.com/anacrolix/torrent/metainfo"
11         pp "github.com/anacrolix/torrent/peer_protocol"
12         "github.com/anacrolix/torrent/storage"
13 )
14
15 type Piece struct {
16         // The completed piece SHA1 hash, from the metainfo "pieces" field.
17         hash  *metainfo.Hash
18         t     *Torrent
19         index pieceIndex
20         files []*File
21
22         readerCond chansync.BroadcastCond
23
24         numVerifies         int64
25         hashing             bool
26         marking             bool
27         storageCompletionOk bool
28
29         publicPieceState PieceState
30         priority         piecePriority
31         // Availability adjustment for this piece relative to len(Torrent.connsWithAllPieces). This is
32         // incremented for any piece a peer has when a peer has a piece, Torrent.haveInfo is true, and
33         // the Peer isn't recorded in Torrent.connsWithAllPieces.
34         relativeAvailability int
35
36         // This can be locked when the Client lock is taken, but probably not vice versa.
37         pendingWritesMutex sync.Mutex
38         pendingWrites      int
39         noPendingWrites    sync.Cond
40
41         // Connections that have written data to this piece since its last check.
42         // This can include connections that have closed.
43         dirtiers map[*Peer]struct{}
44 }
45
46 func (p *Piece) String() string {
47         return fmt.Sprintf("%s/%d", p.t.infoHash.HexString(), p.index)
48 }
49
50 func (p *Piece) Info() metainfo.Piece {
51         return p.t.info.Piece(int(p.index))
52 }
53
54 func (p *Piece) Storage() storage.Piece {
55         return p.t.storage.Piece(p.Info())
56 }
57
58 func (p *Piece) Flush() {
59         if p.t.storage.Flush != nil {
60                 _ = p.t.storage.Flush()
61         }
62 }
63
64 func (p *Piece) pendingChunkIndex(chunkIndex chunkIndexType) bool {
65         return !p.chunkIndexDirty(chunkIndex)
66 }
67
68 func (p *Piece) pendingChunk(cs ChunkSpec, chunkSize pp.Integer) bool {
69         return p.pendingChunkIndex(chunkIndexFromChunkSpec(cs, chunkSize))
70 }
71
72 func (p *Piece) hasDirtyChunks() bool {
73         return p.numDirtyChunks() != 0
74 }
75
76 func (p *Piece) numDirtyChunks() chunkIndexType {
77         return chunkIndexType(roaringBitmapRangeCardinality[RequestIndex](
78                 &p.t.dirtyChunks,
79                 p.requestIndexOffset(),
80                 p.t.pieceRequestIndexOffset(p.index+1)))
81 }
82
83 func (p *Piece) unpendChunkIndex(i chunkIndexType) {
84         p.t.dirtyChunks.Add(p.requestIndexOffset() + i)
85         p.t.updatePieceRequestOrder(p.index)
86         p.readerCond.Broadcast()
87 }
88
89 func (p *Piece) pendChunkIndex(i RequestIndex) {
90         p.t.dirtyChunks.Remove(p.requestIndexOffset() + i)
91         p.t.updatePieceRequestOrder(p.index)
92 }
93
94 func (p *Piece) numChunks() chunkIndexType {
95         return p.t.pieceNumChunks(p.index)
96 }
97
98 func (p *Piece) incrementPendingWrites() {
99         p.pendingWritesMutex.Lock()
100         p.pendingWrites++
101         p.pendingWritesMutex.Unlock()
102 }
103
104 func (p *Piece) decrementPendingWrites() {
105         p.pendingWritesMutex.Lock()
106         if p.pendingWrites == 0 {
107                 panic("assertion")
108         }
109         p.pendingWrites--
110         if p.pendingWrites == 0 {
111                 p.noPendingWrites.Broadcast()
112         }
113         p.pendingWritesMutex.Unlock()
114 }
115
116 func (p *Piece) waitNoPendingWrites() {
117         p.pendingWritesMutex.Lock()
118         for p.pendingWrites != 0 {
119                 p.noPendingWrites.Wait()
120         }
121         p.pendingWritesMutex.Unlock()
122 }
123
124 func (p *Piece) chunkIndexDirty(chunk chunkIndexType) bool {
125         return p.t.dirtyChunks.Contains(p.requestIndexOffset() + chunk)
126 }
127
128 func (p *Piece) chunkIndexSpec(chunk chunkIndexType) ChunkSpec {
129         return chunkIndexSpec(pp.Integer(chunk), p.length(), p.chunkSize())
130 }
131
132 func (p *Piece) numDirtyBytes() (ret pp.Integer) {
133         // defer func() {
134         //      if ret > p.length() {
135         //              panic("too many dirty bytes")
136         //      }
137         // }()
138         numRegularDirtyChunks := p.numDirtyChunks()
139         if p.chunkIndexDirty(p.numChunks() - 1) {
140                 numRegularDirtyChunks--
141                 ret += p.chunkIndexSpec(p.lastChunkIndex()).Length
142         }
143         ret += pp.Integer(numRegularDirtyChunks) * p.chunkSize()
144         return
145 }
146
147 func (p *Piece) length() pp.Integer {
148         return p.t.pieceLength(p.index)
149 }
150
151 func (p *Piece) chunkSize() pp.Integer {
152         return p.t.chunkSize
153 }
154
155 func (p *Piece) lastChunkIndex() chunkIndexType {
156         return p.numChunks() - 1
157 }
158
159 func (p *Piece) bytesLeft() (ret pp.Integer) {
160         if p.t.pieceComplete(p.index) {
161                 return 0
162         }
163         return p.length() - p.numDirtyBytes()
164 }
165
166 // Forces the piece data to be rehashed.
167 func (p *Piece) VerifyData() {
168         p.t.cl.lock()
169         defer p.t.cl.unlock()
170         target := p.numVerifies + 1
171         if p.hashing {
172                 target++
173         }
174         // log.Printf("target: %d", target)
175         p.t.queuePieceCheck(p.index)
176         for {
177                 // log.Printf("got %d verifies", p.numVerifies)
178                 if p.numVerifies >= target {
179                         break
180                 }
181                 p.t.cl.event.Wait()
182         }
183         // log.Print("done")
184 }
185
186 func (p *Piece) queuedForHash() bool {
187         return p.t.piecesQueuedForHash.Get(bitmap.BitIndex(p.index))
188 }
189
190 func (p *Piece) torrentBeginOffset() int64 {
191         return int64(p.index) * p.t.info.PieceLength
192 }
193
194 func (p *Piece) torrentEndOffset() int64 {
195         return p.torrentBeginOffset() + int64(p.length())
196 }
197
198 func (p *Piece) SetPriority(prio piecePriority) {
199         p.t.cl.lock()
200         defer p.t.cl.unlock()
201         p.priority = prio
202         p.t.updatePiecePriority(p.index, "Piece.SetPriority")
203 }
204
205 func (p *Piece) purePriority() (ret piecePriority) {
206         for _, f := range p.files {
207                 ret.Raise(f.prio)
208         }
209         if p.t.readerNowPieces().Contains(bitmap.BitIndex(p.index)) {
210                 ret.Raise(PiecePriorityNow)
211         }
212         // if t._readerNowPieces.Contains(piece - 1) {
213         //      return PiecePriorityNext
214         // }
215         if p.t.readerReadaheadPieces().Contains(bitmap.BitIndex(p.index)) {
216                 ret.Raise(PiecePriorityReadahead)
217         }
218         ret.Raise(p.priority)
219         return
220 }
221
222 func (p *Piece) uncachedPriority() (ret piecePriority) {
223         if p.hashing || p.marking || p.t.pieceComplete(p.index) || p.queuedForHash() {
224                 return PiecePriorityNone
225         }
226         return p.purePriority()
227 }
228
229 // Tells the Client to refetch the completion status from storage, updating priority etc. if
230 // necessary. Might be useful if you know the state of the piece data has changed externally.
231 func (p *Piece) UpdateCompletion() {
232         p.t.cl.lock()
233         defer p.t.cl.unlock()
234         p.t.updatePieceCompletion(p.index)
235 }
236
237 func (p *Piece) completion() (ret storage.Completion) {
238         ret.Complete = p.t.pieceComplete(p.index)
239         ret.Ok = p.storageCompletionOk
240         return
241 }
242
243 func (p *Piece) allChunksDirty() bool {
244         return p.numDirtyChunks() == p.numChunks()
245 }
246
247 func (p *Piece) State() PieceState {
248         return p.t.PieceState(p.index)
249 }
250
251 func (p *Piece) requestIndexOffset() RequestIndex {
252         return p.t.pieceRequestIndexOffset(p.index)
253 }
254
255 func (p *Piece) availability() int {
256         return len(p.t.connsWithAllPieces) + p.relativeAvailability
257 }