13 "github.com/anacrolix/log"
14 "github.com/anacrolix/multiless"
16 request_strategy "github.com/anacrolix/torrent/request-strategy"
19 func (t *Torrent) requestStrategyPieceOrderState(i int) request_strategy.PieceRequestOrderState {
20 return request_strategy.PieceRequestOrderState{
21 Priority: t.piece(i).purePriority(),
22 Partial: t.piecePartiallyDownloaded(i),
23 Availability: t.piece(i).availability(),
28 gob.Register(peerId{})
36 func (p peerId) Uintptr() uintptr {
40 func (p peerId) GobEncode() (b []byte, _ error) {
41 *(*reflect.SliceHeader)(unsafe.Pointer(&b)) = reflect.SliceHeader{
42 Data: uintptr(unsafe.Pointer(&p.ptr)),
43 Len: int(unsafe.Sizeof(p.ptr)),
44 Cap: int(unsafe.Sizeof(p.ptr)),
49 func (p *peerId) GobDecode(b []byte) error {
50 if uintptr(len(b)) != unsafe.Sizeof(p.ptr) {
53 ptr := unsafe.Pointer(&b[0])
54 p.ptr = *(*uintptr)(ptr)
56 dst := reflect.SliceHeader{
57 Data: uintptr(unsafe.Pointer(&p.Peer)),
58 Len: int(unsafe.Sizeof(p.Peer)),
59 Cap: int(unsafe.Sizeof(p.Peer)),
61 copy(*(*[]byte)(unsafe.Pointer(&dst)), b)
66 RequestIndex = request_strategy.RequestIndex
67 chunkIndexType = request_strategy.ChunkIndex
70 type desiredPeerRequests struct {
71 requestIndexes []RequestIndex
75 func (p *desiredPeerRequests) Len() int {
76 return len(p.requestIndexes)
79 func (p *desiredPeerRequests) Less(i, j int) bool {
80 leftRequest := p.requestIndexes[i]
81 rightRequest := p.requestIndexes[j]
83 leftPieceIndex := t.pieceIndexOfRequestIndex(leftRequest)
84 rightPieceIndex := t.pieceIndexOfRequestIndex(rightRequest)
86 // Push requests that can't be served right now to the end. But we don't throw them away unless
87 // there's a better alternative. This is for when we're using the fast extension and get choked
88 // but our requests could still be good when we get unchoked.
89 if p.peer.peerChoking {
91 !p.peer.peerAllowedFast.Contains(leftPieceIndex),
92 !p.peer.peerAllowedFast.Contains(rightPieceIndex),
95 leftPiece := t.piece(leftPieceIndex)
96 rightPiece := t.piece(rightPieceIndex)
97 // Putting this first means we can steal requests from lesser-performing peers for our first few
99 priority := func() piecePriority {
100 // Technically we would be happy with the cached priority here, except we don't actually
101 // cache it anymore, and Torrent.piecePriority just does another lookup of *Piece to resolve
102 // the priority through Piece.purePriority, which is probably slower.
103 leftPriority := leftPiece.purePriority()
104 rightPriority := rightPiece.purePriority()
110 if leftPriority != rightPriority {
111 panic("expected equal")
119 leftPeer := t.pendingRequests[leftRequest]
120 rightPeer := t.pendingRequests[rightRequest]
121 // Prefer chunks already requested from this peer.
122 ml = ml.Bool(rightPeer == p.peer, leftPeer == p.peer)
123 // Prefer unrequested chunks.
124 ml = ml.Bool(rightPeer == nil, leftPeer == nil)
129 // The right peer should also be set, or we'd have resolved the computation by now.
131 rightPeer.requestState.Requests.GetCardinality(),
132 leftPeer.requestState.Requests.GetCardinality(),
134 // Could either of the lastRequested be Zero? That's what checking an existing peer is for.
135 leftLast := t.lastRequested[leftRequest]
136 rightLast := t.lastRequested[rightRequest]
137 if leftLast.IsZero() || rightLast.IsZero() {
138 panic("expected non-zero last requested times")
140 // We want the most-recently requested on the left. Clients like Transmission serve requests
141 // in received order, so the most recently-requested is the one that has the longest until
142 // it will be served and therefore is the best candidate to cancel.
143 ml = ml.CmpInt64(rightLast.Sub(leftLast).Nanoseconds())
146 leftPiece.relativeAvailability,
147 rightPiece.relativeAvailability)
148 if priority == PiecePriorityReadahead {
149 // TODO: For readahead in particular, it would be even better to consider distance from the
150 // reader position so that reads earlier in a torrent don't starve reads later in the
151 // torrent. This would probably require reconsideration of how readahead priority works.
152 ml = ml.Int(leftPieceIndex, rightPieceIndex)
154 // TODO: To prevent unnecessarily requesting from disparate pieces, and to ensure pieces are
155 // selected randomly when availability is even, there should be some fixed ordering of
161 func (p *desiredPeerRequests) Swap(i, j int) {
162 p.requestIndexes[i], p.requestIndexes[j] = p.requestIndexes[j], p.requestIndexes[i]
165 func (p *desiredPeerRequests) Push(x interface{}) {
166 p.requestIndexes = append(p.requestIndexes, x.(RequestIndex))
169 func (p *desiredPeerRequests) Pop() interface{} {
170 last := len(p.requestIndexes) - 1
171 x := p.requestIndexes[last]
172 p.requestIndexes = p.requestIndexes[:last]
176 type desiredRequestState struct {
177 Requests desiredPeerRequests
181 func (p *Peer) getDesiredRequestState() (desired desiredRequestState) {
185 if p.t.closed.IsSet() {
188 input := p.t.getRequestStrategyInput()
189 requestHeap := desiredPeerRequests{
192 request_strategy.GetRequestablePieces(
194 p.t.getPieceRequestOrder(),
195 func(ih InfoHash, pieceIndex int) {
196 if ih != p.t.infoHash {
199 if !p.peerHasPiece(pieceIndex) {
202 allowedFast := p.peerAllowedFast.Contains(pieceIndex)
203 p.t.piece(pieceIndex).undirtiedChunksIter.Iter(func(ci request_strategy.ChunkIndex) {
204 r := p.t.pieceRequestIndexOffset(pieceIndex) + ci
206 // We must signal interest to request this. TODO: We could set interested if the
207 // peers pieces (minus the allowed fast set) overlap with our missing pieces if
208 // there are any readers, or any pending pieces.
209 desired.Interested = true
210 // We can make or will allow sustaining a request here if we're not choked, or
211 // have made the request previously (presumably while unchoked), and haven't had
212 // the peer respond yet (and the request was retained because we are using the
214 if p.peerChoking && !p.requestState.Requests.Contains(r) {
215 // We can't request this right now.
219 if p.requestState.Cancelled.Contains(r) {
220 // Can't re-request while awaiting acknowledgement.
223 requestHeap.requestIndexes = append(requestHeap.requestIndexes, r)
227 p.t.assertPendingRequests()
228 desired.Requests = requestHeap
232 func (p *Peer) maybeUpdateActualRequestState() {
233 if p.closed.IsSet() {
236 if p.needRequestUpdate == "" {
239 if p.needRequestUpdate == peerUpdateRequestsTimerReason {
240 since := time.Since(p.lastRequestUpdate)
241 if since < updateRequestsTimerDuration {
246 context.Background(),
247 pprof.Labels("update request", p.needRequestUpdate),
248 func(_ context.Context) {
249 next := p.getDesiredRequestState()
250 p.applyRequestState(next)
255 // Transmit/action the request state to the peer.
256 func (p *Peer) applyRequestState(next desiredRequestState) {
257 current := &p.requestState
258 if !p.setInterested(next.Interested) {
259 panic("insufficient write buffer")
262 requestHeap := &next.Requests
264 originalRequestCount := current.Requests.GetCardinality()
265 // We're either here on a timer, or because we ran out of requests. Both are valid reasons to
266 // alter peakRequests.
267 if originalRequestCount != 0 && p.needRequestUpdate != peerUpdateRequestsTimerReason {
269 "expected zero existing requests (%v) for update reason %q",
270 originalRequestCount, p.needRequestUpdate))
272 heap.Init(requestHeap)
273 for requestHeap.Len() != 0 && maxRequests(current.Requests.GetCardinality()+current.Cancelled.GetCardinality()) < p.nominalMaxRequests() {
274 req := heap.Pop(requestHeap).(RequestIndex)
275 existing := t.requestingPeer(req)
276 if existing != nil && existing != p {
277 // Don't steal from the poor.
278 diff := int64(current.Requests.GetCardinality()) + 1 - (int64(existing.uncancelledRequests()) - 1)
279 // Steal a request that leaves us with one more request than the existing peer
280 // connection if the stealer more recently received a chunk.
281 if diff > 1 || (diff == 1 && p.lastUsefulChunkReceived.Before(existing.lastUsefulChunkReceived)) {
286 more = p.mustRequest(req)
292 // This might fail if we incorrectly determine that we can fit up to the maximum allowed
293 // requests into the available write buffer space. We don't want that to happen because it
294 // makes our peak requests dependent on how much was already in the buffer.
296 "couldn't fill apply entire request state [newRequests=%v]",
297 current.Requests.GetCardinality()-originalRequestCount))
299 newPeakRequests := maxRequests(current.Requests.GetCardinality() - originalRequestCount)
301 // "requests %v->%v (peak %v->%v) reason %q (peer %v)",
302 // originalRequestCount, current.Requests.GetCardinality(), p.peakRequests, newPeakRequests, p.needRequestUpdate, p)
303 p.peakRequests = newPeakRequests
304 p.needRequestUpdate = ""
305 p.lastRequestUpdate = time.Now()
306 p.updateRequestsTimer.Reset(updateRequestsTimerDuration)
309 // This could be set to 10s to match the unchoke/request update interval recommended by some
310 // specifications. I've set it shorter to trigger it more often for testing for now.
311 const updateRequestsTimerDuration = 3 * time.Second