]> Sergey Matveev's repositories - btrtrc.git/blob - piece.go
Rework to improve work stealing and try to thread peers through all request pieces
[btrtrc.git] / piece.go
1 package torrent
2
3 import (
4         "fmt"
5         "sync"
6
7         "github.com/anacrolix/missinggo/v2/bitmap"
8
9         "github.com/anacrolix/torrent/metainfo"
10         pp "github.com/anacrolix/torrent/peer_protocol"
11         "github.com/anacrolix/torrent/storage"
12 )
13
14 // Describes the importance of obtaining a particular piece.
15 type piecePriority byte
16
17 func (pp *piecePriority) Raise(maybe piecePriority) bool {
18         if maybe > *pp {
19                 *pp = maybe
20                 return true
21         }
22         return false
23 }
24
25 // Priority for use in PriorityBitmap
26 func (me piecePriority) BitmapPriority() int {
27         return -int(me)
28 }
29
30 const (
31         PiecePriorityNone      piecePriority = iota // Not wanted. Must be the zero value.
32         PiecePriorityNormal                         // Wanted.
33         PiecePriorityHigh                           // Wanted a lot.
34         PiecePriorityReadahead                      // May be required soon.
35         // Succeeds a piece where a read occurred. Currently the same as Now,
36         // apparently due to issues with caching.
37         PiecePriorityNext
38         PiecePriorityNow // A Reader is reading in this piece. Highest urgency.
39 )
40
41 type Piece struct {
42         // The completed piece SHA1 hash, from the metainfo "pieces" field.
43         hash  *metainfo.Hash
44         t     *Torrent
45         index pieceIndex
46         files []*File
47         // Chunks we've written to since the last check. The chunk offset and
48         // length can be determined by the request chunkSize in use.
49         _dirtyChunks bitmap.Bitmap
50
51         numVerifies         int64
52         hashing             bool
53         marking             bool
54         storageCompletionOk bool
55
56         publicPieceState PieceState
57         priority         piecePriority
58         availability     int64
59
60         // This can be locked when the Client lock is taken, but probably not vice versa.
61         pendingWritesMutex sync.Mutex
62         pendingWrites      int
63         noPendingWrites    sync.Cond
64
65         // Connections that have written data to this piece since its last check.
66         // This can include connections that have closed.
67         dirtiers map[*Peer]struct{}
68 }
69
70 func (p *Piece) String() string {
71         return fmt.Sprintf("%s/%d", p.t.infoHash.HexString(), p.index)
72 }
73
74 func (p *Piece) Info() metainfo.Piece {
75         return p.t.info.Piece(int(p.index))
76 }
77
78 func (p *Piece) Storage() storage.Piece {
79         return p.t.storage.Piece(p.Info())
80 }
81
82 func (p *Piece) pendingChunkIndex(chunkIndex int) bool {
83         return !p._dirtyChunks.Contains(chunkIndex)
84 }
85
86 func (p *Piece) pendingChunk(cs ChunkSpec, chunkSize pp.Integer) bool {
87         return p.pendingChunkIndex(chunkIndex(cs, chunkSize))
88 }
89
90 func (p *Piece) hasDirtyChunks() bool {
91         return p._dirtyChunks.Len() != 0
92 }
93
94 func (p *Piece) numDirtyChunks() pp.Integer {
95         return pp.Integer(p._dirtyChunks.Len())
96 }
97
98 func (p *Piece) unpendChunkIndex(i int) {
99         p._dirtyChunks.Add(i)
100         p.t.tickleReaders()
101 }
102
103 func (p *Piece) pendChunkIndex(i int) {
104         p._dirtyChunks.Remove(i)
105 }
106
107 func (p *Piece) numChunks() pp.Integer {
108         return p.t.pieceNumChunks(p.index)
109 }
110
111 func (p *Piece) incrementPendingWrites() {
112         p.pendingWritesMutex.Lock()
113         p.pendingWrites++
114         p.pendingWritesMutex.Unlock()
115 }
116
117 func (p *Piece) decrementPendingWrites() {
118         p.pendingWritesMutex.Lock()
119         if p.pendingWrites == 0 {
120                 panic("assertion")
121         }
122         p.pendingWrites--
123         if p.pendingWrites == 0 {
124                 p.noPendingWrites.Broadcast()
125         }
126         p.pendingWritesMutex.Unlock()
127 }
128
129 func (p *Piece) waitNoPendingWrites() {
130         p.pendingWritesMutex.Lock()
131         for p.pendingWrites != 0 {
132                 p.noPendingWrites.Wait()
133         }
134         p.pendingWritesMutex.Unlock()
135 }
136
137 func (p *Piece) chunkIndexDirty(chunk pp.Integer) bool {
138         return p._dirtyChunks.Contains(bitmap.BitIndex(chunk))
139 }
140
141 func (p *Piece) chunkIndexSpec(chunk pp.Integer) ChunkSpec {
142         return chunkIndexSpec(chunk, p.length(), p.chunkSize())
143 }
144
145 func (p *Piece) chunkIndexRequest(chunkIndex pp.Integer) Request {
146         return Request{
147                 pp.Integer(p.index),
148                 p.chunkIndexSpec(chunkIndex),
149         }
150 }
151
152 func (p *Piece) numDirtyBytes() (ret pp.Integer) {
153         // defer func() {
154         //      if ret > p.length() {
155         //              panic("too many dirty bytes")
156         //      }
157         // }()
158         numRegularDirtyChunks := p.numDirtyChunks()
159         if p.chunkIndexDirty(p.numChunks() - 1) {
160                 numRegularDirtyChunks--
161                 ret += p.chunkIndexSpec(p.lastChunkIndex()).Length
162         }
163         ret += pp.Integer(numRegularDirtyChunks) * p.chunkSize()
164         return
165 }
166
167 func (p *Piece) length() pp.Integer {
168         return p.t.pieceLength(p.index)
169 }
170
171 func (p *Piece) chunkSize() pp.Integer {
172         return p.t.chunkSize
173 }
174
175 func (p *Piece) lastChunkIndex() pp.Integer {
176         return p.numChunks() - 1
177 }
178
179 func (p *Piece) bytesLeft() (ret pp.Integer) {
180         if p.t.pieceComplete(p.index) {
181                 return 0
182         }
183         return p.length() - p.numDirtyBytes()
184 }
185
186 // Forces the piece data to be rehashed.
187 func (p *Piece) VerifyData() {
188         p.t.cl.lock()
189         defer p.t.cl.unlock()
190         target := p.numVerifies + 1
191         if p.hashing {
192                 target++
193         }
194         //log.Printf("target: %d", target)
195         p.t.queuePieceCheck(p.index)
196         for {
197                 //log.Printf("got %d verifies", p.numVerifies)
198                 if p.numVerifies >= target {
199                         break
200                 }
201                 p.t.cl.event.Wait()
202         }
203         // log.Print("done")
204 }
205
206 func (p *Piece) queuedForHash() bool {
207         return p.t.piecesQueuedForHash.Get(bitmap.BitIndex(p.index))
208 }
209
210 func (p *Piece) torrentBeginOffset() int64 {
211         return int64(p.index) * p.t.info.PieceLength
212 }
213
214 func (p *Piece) torrentEndOffset() int64 {
215         return p.torrentBeginOffset() + int64(p.length())
216 }
217
218 func (p *Piece) SetPriority(prio piecePriority) {
219         p.t.cl.lock()
220         defer p.t.cl.unlock()
221         p.priority = prio
222         p.t.updatePiecePriority(p.index)
223 }
224
225 func (p *Piece) purePriority() (ret piecePriority) {
226         for _, f := range p.files {
227                 ret.Raise(f.prio)
228         }
229         if p.t.readerNowPieces().Contains(int(p.index)) {
230                 ret.Raise(PiecePriorityNow)
231         }
232         // if t._readerNowPieces.Contains(piece - 1) {
233         //      return PiecePriorityNext
234         // }
235         if p.t.readerReadaheadPieces().Contains(bitmap.BitIndex(p.index)) {
236                 ret.Raise(PiecePriorityReadahead)
237         }
238         ret.Raise(p.priority)
239         return
240 }
241
242 func (p *Piece) uncachedPriority() (ret piecePriority) {
243         if p.t.pieceComplete(p.index) || p.t.pieceQueuedForHash(p.index) || p.t.hashingPiece(p.index) {
244                 return PiecePriorityNone
245         }
246         return p.purePriority()
247 }
248
249 // Tells the Client to refetch the completion status from storage, updating priority etc. if
250 // necessary. Might be useful if you know the state of the piece data has changed externally.
251 func (p *Piece) UpdateCompletion() {
252         p.t.cl.lock()
253         defer p.t.cl.unlock()
254         p.t.updatePieceCompletion(p.index)
255 }
256
257 func (p *Piece) completion() (ret storage.Completion) {
258         ret.Complete = p.t.pieceComplete(p.index)
259         ret.Ok = p.storageCompletionOk
260         return
261 }
262
263 func (p *Piece) allChunksDirty() bool {
264         return p._dirtyChunks.Len() == int(p.numChunks())
265 }
266
267 func (p *Piece) dirtyChunks() bitmap.Bitmap {
268         return p._dirtyChunks
269 }
270
271 func (p *Piece) State() PieceState {
272         return p.t.PieceState(p.index)
273 }
274
275 func (p *Piece) iterUndirtiedChunks(f func(ChunkSpec) bool) bool {
276         for i := pp.Integer(0); i < p.numChunks(); i++ {
277                 if p.chunkIndexDirty(i) {
278                         continue
279                 }
280                 if !f(p.chunkIndexSpec(i)) {
281                         return false
282                 }
283         }
284         return true
285 }