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