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