]> Sergey Matveev's repositories - btrtrc.git/blob - piece.go
Fix piece getting queued for hash multiple times
[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         storageCompletionOk bool
54
55         publicPieceState PieceState
56         priority         piecePriority
57
58         // This can be locked when the Client lock is taken, but probably not vice versa.
59         pendingWritesMutex sync.Mutex
60         pendingWrites      int
61         noPendingWrites    sync.Cond
62
63         // Connections that have written data to this piece since its last check.
64         // This can include connections that have closed.
65         dirtiers map[*peer]struct{}
66 }
67
68 func (p *Piece) String() string {
69         return fmt.Sprintf("%s/%d", p.t.infoHash.HexString(), p.index)
70 }
71
72 func (p *Piece) Info() metainfo.Piece {
73         return p.t.info.Piece(int(p.index))
74 }
75
76 func (p *Piece) Storage() storage.Piece {
77         return p.t.storage.Piece(p.Info())
78 }
79
80 func (p *Piece) pendingChunkIndex(chunkIndex int) bool {
81         return !p._dirtyChunks.Contains(chunkIndex)
82 }
83
84 func (p *Piece) pendingChunk(cs chunkSpec, chunkSize pp.Integer) bool {
85         return p.pendingChunkIndex(chunkIndex(cs, chunkSize))
86 }
87
88 func (p *Piece) hasDirtyChunks() bool {
89         return p._dirtyChunks.Len() != 0
90 }
91
92 func (p *Piece) numDirtyChunks() pp.Integer {
93         return pp.Integer(p._dirtyChunks.Len())
94 }
95
96 func (p *Piece) unpendChunkIndex(i int) {
97         p._dirtyChunks.Add(i)
98         p.t.tickleReaders()
99 }
100
101 func (p *Piece) pendChunkIndex(i int) {
102         p._dirtyChunks.Remove(i)
103 }
104
105 func (p *Piece) numChunks() pp.Integer {
106         return p.t.pieceNumChunks(p.index)
107 }
108
109 func (p *Piece) incrementPendingWrites() {
110         p.pendingWritesMutex.Lock()
111         p.pendingWrites++
112         p.pendingWritesMutex.Unlock()
113 }
114
115 func (p *Piece) decrementPendingWrites() {
116         p.pendingWritesMutex.Lock()
117         if p.pendingWrites == 0 {
118                 panic("assertion")
119         }
120         p.pendingWrites--
121         if p.pendingWrites == 0 {
122                 p.noPendingWrites.Broadcast()
123         }
124         p.pendingWritesMutex.Unlock()
125 }
126
127 func (p *Piece) waitNoPendingWrites() {
128         p.pendingWritesMutex.Lock()
129         for p.pendingWrites != 0 {
130                 p.noPendingWrites.Wait()
131         }
132         p.pendingWritesMutex.Unlock()
133 }
134
135 func (p *Piece) chunkIndexDirty(chunk pp.Integer) bool {
136         return p._dirtyChunks.Contains(bitmap.BitIndex(chunk))
137 }
138
139 func (p *Piece) chunkIndexSpec(chunk pp.Integer) chunkSpec {
140         return chunkIndexSpec(chunk, p.length(), p.chunkSize())
141 }
142
143 func (p *Piece) chunkIndexRequest(chunkIndex pp.Integer) request {
144         return request{
145                 pp.Integer(p.index),
146                 chunkIndexSpec(chunkIndex, p.length(), p.chunkSize()),
147         }
148 }
149
150 func (p *Piece) numDirtyBytes() (ret pp.Integer) {
151         // defer func() {
152         //      if ret > p.length() {
153         //              panic("too many dirty bytes")
154         //      }
155         // }()
156         numRegularDirtyChunks := p.numDirtyChunks()
157         if p.chunkIndexDirty(p.numChunks() - 1) {
158                 numRegularDirtyChunks--
159                 ret += p.chunkIndexSpec(p.lastChunkIndex()).Length
160         }
161         ret += pp.Integer(numRegularDirtyChunks) * p.chunkSize()
162         return
163 }
164
165 func (p *Piece) length() pp.Integer {
166         return p.t.pieceLength(p.index)
167 }
168
169 func (p *Piece) chunkSize() pp.Integer {
170         return p.t.chunkSize
171 }
172
173 func (p *Piece) lastChunkIndex() pp.Integer {
174         return p.numChunks() - 1
175 }
176
177 func (p *Piece) bytesLeft() (ret pp.Integer) {
178         if p.t.pieceComplete(p.index) {
179                 return 0
180         }
181         return p.length() - p.numDirtyBytes()
182 }
183
184 // Forces the piece data to be rehashed.
185 func (p *Piece) VerifyData() {
186         p.t.cl.lock()
187         defer p.t.cl.unlock()
188         target := p.numVerifies + 1
189         if p.hashing {
190                 target++
191         }
192         //log.Printf("target: %d", target)
193         p.t.queuePieceCheck(p.index)
194         for {
195                 //log.Printf("got %d verifies", p.numVerifies)
196                 if p.numVerifies >= target {
197                         break
198                 }
199                 p.t.cl.event.Wait()
200         }
201         // log.Print("done")
202 }
203
204 func (p *Piece) queuedForHash() bool {
205         return p.t.piecesQueuedForHash.Get(bitmap.BitIndex(p.index))
206 }
207
208 func (p *Piece) torrentBeginOffset() int64 {
209         return int64(p.index) * p.t.info.PieceLength
210 }
211
212 func (p *Piece) torrentEndOffset() int64 {
213         return p.torrentBeginOffset() + int64(p.length())
214 }
215
216 func (p *Piece) SetPriority(prio piecePriority) {
217         p.t.cl.lock()
218         defer p.t.cl.unlock()
219         p.priority = prio
220         p.t.updatePiecePriority(p.index)
221 }
222
223 func (p *Piece) uncachedPriority() (ret piecePriority) {
224         if p.t.pieceComplete(p.index) || p.t.pieceQueuedForHash(p.index) || p.t.hashingPiece(p.index) {
225                 return PiecePriorityNone
226         }
227         for _, f := range p.files {
228                 ret.Raise(f.prio)
229         }
230         if p.t.readerNowPieces().Contains(int(p.index)) {
231                 ret.Raise(PiecePriorityNow)
232         }
233         // if t._readerNowPieces.Contains(piece - 1) {
234         //      return PiecePriorityNext
235         // }
236         if p.t.readerReadaheadPieces().Contains(bitmap.BitIndex(p.index)) {
237                 ret.Raise(PiecePriorityReadahead)
238         }
239         ret.Raise(p.priority)
240         return
241 }
242
243 func (p *Piece) UpdateCompletion() {
244         p.t.cl.lock()
245         defer p.t.cl.unlock()
246         p.t.updatePieceCompletion(p.index)
247 }
248
249 func (p *Piece) completion() (ret storage.Completion) {
250         ret.Complete = p.t.pieceComplete(p.index)
251         ret.Ok = p.storageCompletionOk
252         return
253 }
254
255 func (p *Piece) allChunksDirty() bool {
256         return p._dirtyChunks.Len() == int(p.numChunks())
257 }
258
259 func (p *Piece) requestStrategyPiece() requestStrategyPiece {
260         return p
261 }
262
263 func (p *Piece) dirtyChunks() bitmap.Bitmap {
264         return p._dirtyChunks
265 }
266
267 func (p *Piece) State() PieceState {
268         return p.t.PieceState(p.index)
269 }