]> Sergey Matveev's repositories - btrtrc.git/blob - piece.go
Move undirtiedChunksIter into its own file
[btrtrc.git] / piece.go
1 package torrent
2
3 import (
4         "encoding/gob"
5         "fmt"
6         "sync"
7
8         "github.com/anacrolix/chansync"
9         "github.com/anacrolix/missinggo/v2/bitmap"
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         undirtiedChunksIter undirtiedChunksIter
46 }
47
48 func (p *Piece) String() string {
49         return fmt.Sprintf("%s/%d", p.t.infoHash.HexString(), p.index)
50 }
51
52 func (p *Piece) Info() metainfo.Piece {
53         return p.t.info.Piece(int(p.index))
54 }
55
56 func (p *Piece) Storage() storage.Piece {
57         return p.t.storage.Piece(p.Info())
58 }
59
60 func (p *Piece) pendingChunkIndex(chunkIndex chunkIndexType) bool {
61         return !p.chunkIndexDirty(chunkIndex)
62 }
63
64 func (p *Piece) pendingChunk(cs ChunkSpec, chunkSize pp.Integer) bool {
65         return p.pendingChunkIndex(chunkIndexFromChunkSpec(cs, chunkSize))
66 }
67
68 func (p *Piece) hasDirtyChunks() bool {
69         return p.numDirtyChunks() != 0
70 }
71
72 func (p *Piece) numDirtyChunks() chunkIndexType {
73         return chunkIndexType(roaringBitmapRangeCardinality[RequestIndex](
74                 &p.t.dirtyChunks,
75                 p.requestIndexOffset(),
76                 p.t.pieceRequestIndexOffset(p.index+1)))
77 }
78
79 func (p *Piece) unpendChunkIndex(i chunkIndexType) {
80         p.t.dirtyChunks.Add(p.requestIndexOffset() + i)
81         p.t.updatePieceRequestOrder(p.index)
82         p.readerCond.Broadcast()
83 }
84
85 func (p *Piece) pendChunkIndex(i RequestIndex) {
86         p.t.dirtyChunks.Remove(p.requestIndexOffset() + i)
87         p.t.updatePieceRequestOrder(p.index)
88 }
89
90 func (p *Piece) numChunks() chunkIndexType {
91         return p.t.pieceNumChunks(p.index)
92 }
93
94 func (p *Piece) incrementPendingWrites() {
95         p.pendingWritesMutex.Lock()
96         p.pendingWrites++
97         p.pendingWritesMutex.Unlock()
98 }
99
100 func (p *Piece) decrementPendingWrites() {
101         p.pendingWritesMutex.Lock()
102         if p.pendingWrites == 0 {
103                 panic("assertion")
104         }
105         p.pendingWrites--
106         if p.pendingWrites == 0 {
107                 p.noPendingWrites.Broadcast()
108         }
109         p.pendingWritesMutex.Unlock()
110 }
111
112 func (p *Piece) waitNoPendingWrites() {
113         p.pendingWritesMutex.Lock()
114         for p.pendingWrites != 0 {
115                 p.noPendingWrites.Wait()
116         }
117         p.pendingWritesMutex.Unlock()
118 }
119
120 func (p *Piece) chunkIndexDirty(chunk chunkIndexType) bool {
121         return p.t.dirtyChunks.Contains(p.requestIndexOffset() + chunk)
122 }
123
124 func (p *Piece) chunkIndexSpec(chunk chunkIndexType) ChunkSpec {
125         return chunkIndexSpec(pp.Integer(chunk), p.length(), p.chunkSize())
126 }
127
128 func (p *Piece) numDirtyBytes() (ret pp.Integer) {
129         // defer func() {
130         //      if ret > p.length() {
131         //              panic("too many dirty bytes")
132         //      }
133         // }()
134         numRegularDirtyChunks := p.numDirtyChunks()
135         if p.chunkIndexDirty(p.numChunks() - 1) {
136                 numRegularDirtyChunks--
137                 ret += p.chunkIndexSpec(p.lastChunkIndex()).Length
138         }
139         ret += pp.Integer(numRegularDirtyChunks) * p.chunkSize()
140         return
141 }
142
143 func (p *Piece) length() pp.Integer {
144         return p.t.pieceLength(p.index)
145 }
146
147 func (p *Piece) chunkSize() pp.Integer {
148         return p.t.chunkSize
149 }
150
151 func (p *Piece) lastChunkIndex() chunkIndexType {
152         return p.numChunks() - 1
153 }
154
155 func (p *Piece) bytesLeft() (ret pp.Integer) {
156         if p.t.pieceComplete(p.index) {
157                 return 0
158         }
159         return p.length() - p.numDirtyBytes()
160 }
161
162 // Forces the piece data to be rehashed.
163 func (p *Piece) VerifyData() {
164         p.t.cl.lock()
165         defer p.t.cl.unlock()
166         target := p.numVerifies + 1
167         if p.hashing {
168                 target++
169         }
170         // log.Printf("target: %d", target)
171         p.t.queuePieceCheck(p.index)
172         for {
173                 // log.Printf("got %d verifies", p.numVerifies)
174                 if p.numVerifies >= target {
175                         break
176                 }
177                 p.t.cl.event.Wait()
178         }
179         // log.Print("done")
180 }
181
182 func (p *Piece) queuedForHash() bool {
183         return p.t.piecesQueuedForHash.Get(bitmap.BitIndex(p.index))
184 }
185
186 func (p *Piece) torrentBeginOffset() int64 {
187         return int64(p.index) * p.t.info.PieceLength
188 }
189
190 func (p *Piece) torrentEndOffset() int64 {
191         return p.torrentBeginOffset() + int64(p.length())
192 }
193
194 func (p *Piece) SetPriority(prio piecePriority) {
195         p.t.cl.lock()
196         defer p.t.cl.unlock()
197         p.priority = prio
198         p.t.updatePiecePriority(p.index, "Piece.SetPriority")
199 }
200
201 func (p *Piece) purePriority() (ret piecePriority) {
202         for _, f := range p.files {
203                 ret.Raise(f.prio)
204         }
205         if p.t.readerNowPieces().Contains(bitmap.BitIndex(p.index)) {
206                 ret.Raise(PiecePriorityNow)
207         }
208         // if t._readerNowPieces.Contains(piece - 1) {
209         //      return PiecePriorityNext
210         // }
211         if p.t.readerReadaheadPieces().Contains(bitmap.BitIndex(p.index)) {
212                 ret.Raise(PiecePriorityReadahead)
213         }
214         ret.Raise(p.priority)
215         return
216 }
217
218 func (p *Piece) uncachedPriority() (ret piecePriority) {
219         if p.hashing || p.marking || p.t.pieceComplete(p.index) || p.queuedForHash() {
220                 return PiecePriorityNone
221         }
222         return p.purePriority()
223 }
224
225 // Tells the Client to refetch the completion status from storage, updating priority etc. if
226 // necessary. Might be useful if you know the state of the piece data has changed externally.
227 func (p *Piece) UpdateCompletion() {
228         p.t.cl.lock()
229         defer p.t.cl.unlock()
230         p.t.updatePieceCompletion(p.index)
231 }
232
233 func (p *Piece) completion() (ret storage.Completion) {
234         ret.Complete = p.t.pieceComplete(p.index)
235         ret.Ok = p.storageCompletionOk
236         return
237 }
238
239 func (p *Piece) allChunksDirty() bool {
240         return p.numDirtyChunks() == p.numChunks()
241 }
242
243 func (p *Piece) State() PieceState {
244         return p.t.PieceState(p.index)
245 }
246
247 func init() {
248         gob.Register(undirtiedChunksIter{})
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 }