]> Sergey Matveev's repositories - btrtrc.git/blob - piece.go
Use rejiggered missinggo bitmap
[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 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         // Chunks we've written to since the last check. The chunk offset and
21         // length can be determined by the request chunkSize in use.
22         _dirtyChunks bitmap.Bitmap
23
24         numVerifies         int64
25         hashing             bool
26         marking             bool
27         storageCompletionOk bool
28
29         publicPieceState PieceState
30         priority         piecePriority
31         availability     int64
32
33         // This can be locked when the Client lock is taken, but probably not vice versa.
34         pendingWritesMutex sync.Mutex
35         pendingWrites      int
36         noPendingWrites    sync.Cond
37
38         // Connections that have written data to this piece since its last check.
39         // This can include connections that have closed.
40         dirtiers map[*Peer]struct{}
41 }
42
43 func (p *Piece) String() string {
44         return fmt.Sprintf("%s/%d", p.t.infoHash.HexString(), p.index)
45 }
46
47 func (p *Piece) Info() metainfo.Piece {
48         return p.t.info.Piece(int(p.index))
49 }
50
51 func (p *Piece) Storage() storage.Piece {
52         return p.t.storage.Piece(p.Info())
53 }
54
55 func (p *Piece) pendingChunkIndex(chunkIndex int) bool {
56         return !p._dirtyChunks.Contains(bitmap.BitIndex(chunkIndex))
57 }
58
59 func (p *Piece) pendingChunk(cs ChunkSpec, chunkSize pp.Integer) bool {
60         return p.pendingChunkIndex(chunkIndex(cs, chunkSize))
61 }
62
63 func (p *Piece) hasDirtyChunks() bool {
64         return p._dirtyChunks.Len() != 0
65 }
66
67 func (p *Piece) numDirtyChunks() pp.Integer {
68         return pp.Integer(p._dirtyChunks.Len())
69 }
70
71 func (p *Piece) unpendChunkIndex(i int) {
72         p._dirtyChunks.Add(bitmap.BitIndex(i))
73         p.t.tickleReaders()
74 }
75
76 func (p *Piece) pendChunkIndex(i int) {
77         p._dirtyChunks.Remove(bitmap.BitIndex(i))
78 }
79
80 func (p *Piece) numChunks() pp.Integer {
81         return p.t.pieceNumChunks(p.index)
82 }
83
84 func (p *Piece) incrementPendingWrites() {
85         p.pendingWritesMutex.Lock()
86         p.pendingWrites++
87         p.pendingWritesMutex.Unlock()
88 }
89
90 func (p *Piece) decrementPendingWrites() {
91         p.pendingWritesMutex.Lock()
92         if p.pendingWrites == 0 {
93                 panic("assertion")
94         }
95         p.pendingWrites--
96         if p.pendingWrites == 0 {
97                 p.noPendingWrites.Broadcast()
98         }
99         p.pendingWritesMutex.Unlock()
100 }
101
102 func (p *Piece) waitNoPendingWrites() {
103         p.pendingWritesMutex.Lock()
104         for p.pendingWrites != 0 {
105                 p.noPendingWrites.Wait()
106         }
107         p.pendingWritesMutex.Unlock()
108 }
109
110 func (p *Piece) chunkIndexDirty(chunk pp.Integer) bool {
111         return p._dirtyChunks.Contains(bitmap.BitIndex(chunk))
112 }
113
114 func (p *Piece) chunkIndexSpec(chunk pp.Integer) ChunkSpec {
115         return chunkIndexSpec(chunk, p.length(), p.chunkSize())
116 }
117
118 func (p *Piece) chunkIndexRequest(chunkIndex pp.Integer) Request {
119         return Request{
120                 pp.Integer(p.index),
121                 p.chunkIndexSpec(chunkIndex),
122         }
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() pp.Integer {
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)
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.t.pieceComplete(p.index) || p.t.pieceQueuedForHash(p.index) || p.t.hashingPiece(p.index) {
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._dirtyChunks.Len() == bitmap.BitRange(p.numChunks())
238 }
239
240 func (p *Piece) dirtyChunks() bitmap.Bitmap {
241         return p._dirtyChunks
242 }
243
244 func (p *Piece) State() PieceState {
245         return p.t.PieceState(p.index)
246 }
247
248 func (p *Piece) iterUndirtiedChunks(f func(cs ChunkSpec) bool) bool {
249         for i := pp.Integer(0); i < p.numChunks(); i++ {
250                 if p.chunkIndexDirty(i) {
251                         continue
252                 }
253                 if !f(p.chunkIndexSpec(i)) {
254                         return false
255                 }
256         }
257         return true
258 }