7 "github.com/anacrolix/chansync"
8 g "github.com/anacrolix/generics"
9 "github.com/anacrolix/missinggo/v2/bitmap"
11 "github.com/anacrolix/torrent/metainfo"
12 pp "github.com/anacrolix/torrent/peer_protocol"
13 "github.com/anacrolix/torrent/storage"
17 // The completed piece SHA1 hash, from the metainfo "pieces" field. Nil if the info is not V1
20 hashV2 g.Option[[32]byte]
25 readerCond chansync.BroadcastCond
30 storageCompletionOk bool
32 publicPieceState PieceState
33 priority PiecePriority
34 // Availability adjustment for this piece relative to len(Torrent.connsWithAllPieces). This is
35 // incremented for any piece a peer has when a peer has a piece, Torrent.haveInfo is true, and
36 // the Peer isn't recorded in Torrent.connsWithAllPieces.
37 relativeAvailability int
39 // This can be locked when the Client lock is taken, but probably not vice versa.
40 pendingWritesMutex sync.Mutex
42 noPendingWrites sync.Cond
44 // Connections that have written data to this piece since its last check.
45 // This can include connections that have closed.
46 dirtiers map[*Peer]struct{}
49 func (p *Piece) String() string {
50 return fmt.Sprintf("%s/%d", p.t.canonicalShortInfohash().HexString(), p.index)
53 func (p *Piece) Info() metainfo.Piece {
54 return p.t.info.Piece(p.index)
57 func (p *Piece) Storage() storage.Piece {
58 var pieceHash g.Option[[]byte]
60 pieceHash.Set(p.hash.Bytes())
61 } else if !p.hasPieceLayer() {
62 pieceHash.Set(p.mustGetOnlyFile().piecesRoot.UnwrapPtr()[:])
63 } else if p.hashV2.Ok {
64 pieceHash.Set(p.hashV2.Value[:])
66 return p.t.storage.PieceWithHash(p.Info(), pieceHash)
69 func (p *Piece) Flush() {
70 if p.t.storage.Flush != nil {
71 _ = p.t.storage.Flush()
75 func (p *Piece) pendingChunkIndex(chunkIndex chunkIndexType) bool {
76 return !p.chunkIndexDirty(chunkIndex)
79 func (p *Piece) pendingChunk(cs ChunkSpec, chunkSize pp.Integer) bool {
80 return p.pendingChunkIndex(chunkIndexFromChunkSpec(cs, chunkSize))
83 func (p *Piece) hasDirtyChunks() bool {
84 return p.numDirtyChunks() != 0
87 func (p *Piece) numDirtyChunks() chunkIndexType {
88 return chunkIndexType(roaringBitmapRangeCardinality[RequestIndex](
90 p.requestIndexOffset(),
91 p.t.pieceRequestIndexOffset(p.index+1)))
94 func (p *Piece) unpendChunkIndex(i chunkIndexType) {
95 p.t.dirtyChunks.Add(p.requestIndexOffset() + i)
96 p.t.updatePieceRequestOrderPiece(p.index)
97 p.readerCond.Broadcast()
100 func (p *Piece) pendChunkIndex(i RequestIndex) {
101 p.t.dirtyChunks.Remove(p.requestIndexOffset() + i)
102 p.t.updatePieceRequestOrderPiece(p.index)
105 func (p *Piece) numChunks() chunkIndexType {
106 return p.t.pieceNumChunks(p.index)
109 func (p *Piece) incrementPendingWrites() {
110 p.pendingWritesMutex.Lock()
112 p.pendingWritesMutex.Unlock()
115 func (p *Piece) decrementPendingWrites() {
116 p.pendingWritesMutex.Lock()
117 if p.pendingWrites == 0 {
121 if p.pendingWrites == 0 {
122 p.noPendingWrites.Broadcast()
124 p.pendingWritesMutex.Unlock()
127 func (p *Piece) waitNoPendingWrites() {
128 p.pendingWritesMutex.Lock()
129 for p.pendingWrites != 0 {
130 p.noPendingWrites.Wait()
132 p.pendingWritesMutex.Unlock()
135 func (p *Piece) chunkIndexDirty(chunk chunkIndexType) bool {
136 return p.t.dirtyChunks.Contains(p.requestIndexOffset() + chunk)
139 func (p *Piece) chunkIndexSpec(chunk chunkIndexType) ChunkSpec {
140 return chunkIndexSpec(pp.Integer(chunk), p.length(), p.chunkSize())
143 func (p *Piece) numDirtyBytes() (ret pp.Integer) {
145 // if ret > p.length() {
146 // panic("too many dirty bytes")
149 numRegularDirtyChunks := p.numDirtyChunks()
150 if p.chunkIndexDirty(p.numChunks() - 1) {
151 numRegularDirtyChunks--
152 ret += p.chunkIndexSpec(p.lastChunkIndex()).Length
154 ret += pp.Integer(numRegularDirtyChunks) * p.chunkSize()
158 func (p *Piece) length() pp.Integer {
159 return p.t.pieceLength(p.index)
162 func (p *Piece) chunkSize() pp.Integer {
166 func (p *Piece) lastChunkIndex() chunkIndexType {
167 return p.numChunks() - 1
170 func (p *Piece) bytesLeft() (ret pp.Integer) {
171 if p.t.pieceComplete(p.index) {
174 return p.length() - p.numDirtyBytes()
177 // Forces the piece data to be rehashed.
178 func (p *Piece) VerifyData() {
180 defer p.t.cl.unlock()
181 target := p.numVerifies + 1
185 // log.Printf("target: %d", target)
186 p.t.queuePieceCheck(p.index)
188 // log.Printf("got %d verifies", p.numVerifies)
189 if p.numVerifies >= target {
197 func (p *Piece) queuedForHash() bool {
198 return p.t.piecesQueuedForHash.Get(bitmap.BitIndex(p.index))
201 func (p *Piece) torrentBeginOffset() int64 {
202 return int64(p.index) * p.t.info.PieceLength
205 func (p *Piece) torrentEndOffset() int64 {
206 return p.torrentBeginOffset() + int64(p.t.usualPieceSize())
209 func (p *Piece) SetPriority(prio PiecePriority) {
211 defer p.t.cl.unlock()
213 p.t.updatePiecePriority(p.index, "Piece.SetPriority")
216 // This is priority based only on piece, file and reader priorities.
217 func (p *Piece) purePriority() (ret PiecePriority) {
218 for _, f := range p.files {
221 if p.t.readerNowPieces().Contains(bitmap.BitIndex(p.index)) {
222 ret.Raise(PiecePriorityNow)
224 // if t._readerNowPieces.Contains(piece - 1) {
225 // return PiecePriorityNext
227 if p.t.readerReadaheadPieces().Contains(bitmap.BitIndex(p.index)) {
228 ret.Raise(PiecePriorityReadahead)
230 ret.Raise(p.priority)
234 func (p *Piece) ignoreForRequests() bool {
235 return p.hashing || p.marking || !p.haveHash() || p.t.pieceComplete(p.index) || p.queuedForHash()
238 // This is the priority adjusted for piece state like completion, hashing etc.
239 func (p *Piece) effectivePriority() (ret PiecePriority) {
240 if p.ignoreForRequests() {
241 return PiecePriorityNone
243 return p.purePriority()
246 // Tells the Client to refetch the completion status from storage, updating priority etc. if
247 // necessary. Might be useful if you know the state of the piece data has changed externally.
248 func (p *Piece) UpdateCompletion() {
250 defer p.t.cl.unlock()
251 p.t.updatePieceCompletion(p.index)
254 func (p *Piece) completion() (ret storage.Completion) {
255 ret.Complete = p.t.pieceComplete(p.index)
256 ret.Ok = p.storageCompletionOk
260 func (p *Piece) allChunksDirty() bool {
261 return p.numDirtyChunks() == p.numChunks()
264 func (p *Piece) State() PieceState {
265 return p.t.PieceState(p.index)
268 func (p *Piece) requestIndexOffset() RequestIndex {
269 return p.t.pieceRequestIndexOffset(p.index)
272 func (p *Piece) availability() int {
273 return len(p.t.connsWithAllPieces) + p.relativeAvailability
276 // For v2 torrents, files are aligned to pieces so there should always only be a single file for a
278 func (p *Piece) mustGetOnlyFile() *File {
279 if len(p.files) != 1 {
285 // Sets the v2 piece hash, queuing initial piece checks if appropriate.
286 func (p *Piece) setV2Hash(v2h [32]byte) {
287 // See Torrent.onSetInfo. We want to trigger an initial check if appropriate, if we didn't yet
288 // have a piece hash (can occur with v2 when we don't start with piece layers).
289 p.t.storageLock.Lock()
290 oldV2Hash := p.hashV2.Set(v2h)
291 p.t.storageLock.Unlock()
292 if !oldV2Hash.Ok && p.hash == nil {
293 p.t.updatePieceCompletion(p.index)
294 p.t.queueInitialPieceCheck(p.index)
298 // Can't do certain things if we don't know the piece hash.
299 func (p *Piece) haveHash() bool {
303 if !p.hasPieceLayer() {
309 func (p *Piece) hasPieceLayer() bool {
310 return int64(p.length()) > p.t.info.PieceLength