12 "github.com/RoaringBitmap/roaring"
13 "github.com/anacrolix/generics/heap"
14 "github.com/anacrolix/log"
15 "github.com/anacrolix/multiless"
17 requestStrategy "github.com/anacrolix/torrent/request-strategy"
18 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
22 // Since we have to store all the requests in memory, we can't reasonably exceed what could be
23 // indexed with the memory space available.
27 func (t *Torrent) requestStrategyPieceOrderState(i int) requestStrategy.PieceRequestOrderState {
28 return requestStrategy.PieceRequestOrderState{
29 Priority: t.piece(i).purePriority(),
30 Partial: t.piecePartiallyDownloaded(i),
31 Availability: t.piece(i).availability(),
36 gob.Register(peerId{})
44 func (p peerId) Uintptr() uintptr {
48 func (p peerId) GobEncode() (b []byte, _ error) {
49 *(*reflect.SliceHeader)(unsafe.Pointer(&b)) = reflect.SliceHeader{
50 Data: uintptr(unsafe.Pointer(&p.ptr)),
51 Len: int(unsafe.Sizeof(p.ptr)),
52 Cap: int(unsafe.Sizeof(p.ptr)),
57 func (p *peerId) GobDecode(b []byte) error {
58 if uintptr(len(b)) != unsafe.Sizeof(p.ptr) {
61 ptr := unsafe.Pointer(&b[0])
62 p.ptr = *(*uintptr)(ptr)
64 dst := reflect.SliceHeader{
65 Data: uintptr(unsafe.Pointer(&p.Peer)),
66 Len: int(unsafe.Sizeof(p.Peer)),
67 Cap: int(unsafe.Sizeof(p.Peer)),
69 copy(*(*[]byte)(unsafe.Pointer(&dst)), b)
74 RequestIndex = requestStrategy.RequestIndex
75 chunkIndexType = requestStrategy.ChunkIndex
78 type desiredPeerRequests struct {
79 requestIndexes []RequestIndex
81 pieceStates []requestStrategy.PieceRequestOrderState
84 func (p *desiredPeerRequests) lessByValue(leftRequest, rightRequest RequestIndex) bool {
86 leftPieceIndex := t.pieceIndexOfRequestIndex(leftRequest)
87 rightPieceIndex := t.pieceIndexOfRequestIndex(rightRequest)
89 // Push requests that can't be served right now to the end. But we don't throw them away unless
90 // there's a better alternative. This is for when we're using the fast extension and get choked
91 // but our requests could still be good when we get unchoked.
92 if p.peer.peerChoking {
94 !p.peer.peerAllowedFast.Contains(leftPieceIndex),
95 !p.peer.peerAllowedFast.Contains(rightPieceIndex),
98 leftPiece := &p.pieceStates[leftPieceIndex]
99 rightPiece := &p.pieceStates[rightPieceIndex]
100 // Putting this first means we can steal requests from lesser-performing peers for our first few
102 priority := func() piecePriority {
103 // Technically we would be happy with the cached priority here, except we don't actually
104 // cache it anymore, and Torrent.piecePriority just does another lookup of *Piece to resolve
105 // the priority through Piece.purePriority, which is probably slower.
106 leftPriority := leftPiece.Priority
107 rightPriority := rightPiece.Priority
113 if leftPriority != rightPriority {
114 panic("expected equal")
122 leftRequestState := t.requestState[leftRequest]
123 rightRequestState := t.requestState[rightRequest]
124 leftPeer := leftRequestState.peer
125 rightPeer := rightRequestState.peer
126 // Prefer chunks already requested from this peer.
127 ml = ml.Bool(rightPeer == p.peer, leftPeer == p.peer)
128 // Prefer unrequested chunks.
129 ml = ml.Bool(rightPeer == nil, leftPeer == nil)
134 // The right peer should also be set, or we'd have resolved the computation by now.
136 rightPeer.requestState.Requests.GetCardinality(),
137 leftPeer.requestState.Requests.GetCardinality(),
139 // Could either of the lastRequested be Zero? That's what checking an existing peer is for.
140 leftLast := leftRequestState.when
141 rightLast := rightRequestState.when
142 if leftLast.IsZero() || rightLast.IsZero() {
143 panic("expected non-zero last requested times")
145 // We want the most-recently requested on the left. Clients like Transmission serve requests
146 // in received order, so the most recently-requested is the one that has the longest until
147 // it will be served and therefore is the best candidate to cancel.
148 ml = ml.CmpInt64(rightLast.Sub(leftLast).Nanoseconds())
151 leftPiece.Availability,
152 rightPiece.Availability)
153 if priority == PiecePriorityReadahead {
154 // TODO: For readahead in particular, it would be even better to consider distance from the
155 // reader position so that reads earlier in a torrent don't starve reads later in the
156 // torrent. This would probably require reconsideration of how readahead priority works.
157 ml = ml.Int(leftPieceIndex, rightPieceIndex)
159 ml = ml.Int(t.pieceRequestOrder[leftPieceIndex], t.pieceRequestOrder[rightPieceIndex])
164 type desiredRequestState struct {
165 Requests desiredPeerRequests
169 func (p *Peer) getDesiredRequestState() (desired desiredRequestState) {
174 if t.closed.IsSet() {
177 if t.dataDownloadDisallowed.Bool() {
180 input := t.getRequestStrategyInput()
181 requestHeap := desiredPeerRequests{
183 pieceStates: t.requestPieceStates,
184 requestIndexes: t.requestIndexes,
186 // Caller-provided allocation for roaring bitmap iteration.
187 var it typedRoaring.Iterator[RequestIndex]
188 requestStrategy.GetRequestablePieces(
190 t.getPieceRequestOrder(),
191 func(ih InfoHash, pieceIndex int, pieceExtra requestStrategy.PieceRequestOrderState) {
192 if ih != t.infoHash {
195 if !p.peerHasPiece(pieceIndex) {
198 requestHeap.pieceStates[pieceIndex] = pieceExtra
199 allowedFast := p.peerAllowedFast.Contains(pieceIndex)
200 t.iterUndirtiedRequestIndexesInPiece(&it, pieceIndex, func(r requestStrategy.RequestIndex) {
202 // We must signal interest to request this. TODO: We could set interested if the
203 // peers pieces (minus the allowed fast set) overlap with our missing pieces if
204 // there are any readers, or any pending pieces.
205 desired.Interested = true
206 // We can make or will allow sustaining a request here if we're not choked, or
207 // have made the request previously (presumably while unchoked), and haven't had
208 // the peer respond yet (and the request was retained because we are using the
210 if p.peerChoking && !p.requestState.Requests.Contains(r) {
211 // We can't request this right now.
215 cancelled := &p.requestState.Cancelled
216 if !cancelled.IsEmpty() && cancelled.Contains(r) {
217 // Can't re-request while awaiting acknowledgement.
220 requestHeap.requestIndexes = append(requestHeap.requestIndexes, r)
224 t.assertPendingRequests()
225 desired.Requests = requestHeap
229 func (p *Peer) maybeUpdateActualRequestState() {
230 if p.closed.IsSet() {
233 if p.needRequestUpdate == "" {
236 if p.needRequestUpdate == peerUpdateRequestsTimerReason {
237 since := time.Since(p.lastRequestUpdate)
238 if since < updateRequestsTimerDuration {
243 context.Background(),
244 pprof.Labels("update request", p.needRequestUpdate),
245 func(_ context.Context) {
246 next := p.getDesiredRequestState()
247 p.applyRequestState(next)
248 p.t.cacheNextRequestIndexesForReuse(next.Requests.requestIndexes)
253 func (t *Torrent) cacheNextRequestIndexesForReuse(slice []RequestIndex) {
254 // The incoming slice can be smaller when getDesiredRequestState short circuits on some
256 if cap(slice) > cap(t.requestIndexes) {
257 t.requestIndexes = slice[:0]
261 // Whether we should allow sending not interested ("losing interest") to the peer. I noticed
262 // qBitTorrent seems to punish us for sending not interested when we're streaming and don't
263 // currently need anything.
264 func (p *Peer) allowSendNotInterested() bool {
265 // Except for caching, we're not likely to lose pieces very soon.
266 if p.t.haveAllPieces() {
269 all, known := p.peerHasAllPieces()
273 // Allow losing interest if we have all the pieces the peer has.
274 return roaring.AndNot(p.peerPieces(), &p.t._completedPieces).IsEmpty()
277 // Transmit/action the request state to the peer.
278 func (p *Peer) applyRequestState(next desiredRequestState) {
279 current := &p.requestState
280 // Make interest sticky
281 if !next.Interested && p.requestState.Interested {
282 if !p.allowSendNotInterested() {
283 next.Interested = true
286 if !p.setInterested(next.Interested) {
290 orig := next.Requests.requestIndexes
291 requestHeap := heap.InterfaceForSlice(
292 &next.Requests.requestIndexes,
293 next.Requests.lessByValue,
295 heap.Init(requestHeap)
298 originalRequestCount := current.Requests.GetCardinality()
300 if requestHeap.Len() == 0 {
303 numPending := maxRequests(current.Requests.GetCardinality() + current.Cancelled.GetCardinality())
304 if numPending >= p.nominalMaxRequests() {
307 req := heap.Pop(requestHeap)
308 if cap(next.Requests.requestIndexes) != cap(orig) {
311 existing := t.requestingPeer(req)
312 if existing != nil && existing != p {
313 // Don't steal from the poor.
314 diff := int64(current.Requests.GetCardinality()) + 1 - (int64(existing.uncancelledRequests()) - 1)
315 // Steal a request that leaves us with one more request than the existing peer
316 // connection if the stealer more recently received a chunk.
317 if diff > 1 || (diff == 1 && p.lastUsefulChunkReceived.Before(existing.lastUsefulChunkReceived)) {
322 more = p.mustRequest(req)
328 // This might fail if we incorrectly determine that we can fit up to the maximum allowed
329 // requests into the available write buffer space. We don't want that to happen because it
330 // makes our peak requests dependent on how much was already in the buffer.
332 "couldn't fill apply entire request state [newRequests=%v]",
333 current.Requests.GetCardinality()-originalRequestCount))
335 newPeakRequests := maxRequests(current.Requests.GetCardinality() - originalRequestCount)
337 // "requests %v->%v (peak %v->%v) reason %q (peer %v)",
338 // originalRequestCount, current.Requests.GetCardinality(), p.peakRequests, newPeakRequests, p.needRequestUpdate, p)
339 p.peakRequests = newPeakRequests
340 p.needRequestUpdate = ""
341 p.lastRequestUpdate = time.Now()
342 if enableUpdateRequestsTimer {
343 p.updateRequestsTimer.Reset(updateRequestsTimerDuration)
347 // This could be set to 10s to match the unchoke/request update interval recommended by some
348 // specifications. I've set it shorter to trigger it more often for testing for now.
350 updateRequestsTimerDuration = 3 * time.Second
351 enableUpdateRequestsTimer = false