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 peerRequests struct {
71 requestIndexes []RequestIndex
75 func (p *peerRequests) Len() int {
76 return len(p.requestIndexes)
79 func (p *peerRequests) Less(i, j int) bool {
80 leftRequest := p.requestIndexes[i]
81 rightRequest := p.requestIndexes[j]
83 leftPieceIndex := leftRequest / t.chunksPerRegularPiece()
84 rightPieceIndex := rightRequest / t.chunksPerRegularPiece()
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 leftPeer := t.pendingRequests[leftRequest]
96 rightPeer := t.pendingRequests[rightRequest]
97 ml = ml.Bool(rightPeer == p.peer, leftPeer == p.peer)
98 ml = ml.Bool(rightPeer == nil, leftPeer == nil)
103 // The right peer should also be set, or we'd have resolved the computation by now.
105 rightPeer.requestState.Requests.GetCardinality(),
106 leftPeer.requestState.Requests.GetCardinality(),
108 // Could either of the lastRequested be Zero? That's what checking an existing peer is for.
109 leftLast := t.lastRequested[leftRequest]
110 rightLast := t.lastRequested[rightRequest]
111 if leftLast.IsZero() || rightLast.IsZero() {
112 panic("expected non-zero last requested times")
114 // We want the most-recently requested on the left. Clients like Transmission serve requests
115 // in received order, so the most recently-requested is the one that has the longest until
116 // it will be served and therefore is the best candidate to cancel.
117 ml = ml.CmpInt64(rightLast.Sub(leftLast).Nanoseconds())
119 leftPiece := t.piece(int(leftPieceIndex))
120 rightPiece := t.piece(int(rightPieceIndex))
122 // Technically we would be happy with the cached priority here, except we don't actually
123 // cache it anymore, and Torrent.piecePriority just does another lookup of *Piece to resolve
124 // the priority through Piece.purePriority, which is probably slower.
125 -int(leftPiece.purePriority()),
126 -int(rightPiece.purePriority()),
129 int(leftPiece.relativeAvailability),
130 int(rightPiece.relativeAvailability))
134 func (p *peerRequests) Swap(i, j int) {
135 p.requestIndexes[i], p.requestIndexes[j] = p.requestIndexes[j], p.requestIndexes[i]
138 func (p *peerRequests) Push(x interface{}) {
139 p.requestIndexes = append(p.requestIndexes, x.(RequestIndex))
142 func (p *peerRequests) Pop() interface{} {
143 last := len(p.requestIndexes) - 1
144 x := p.requestIndexes[last]
145 p.requestIndexes = p.requestIndexes[:last]
149 type desiredRequestState struct {
150 Requests peerRequests
154 func (p *Peer) getDesiredRequestState() (desired desiredRequestState) {
158 if p.t.closed.IsSet() {
161 input := p.t.getRequestStrategyInput()
162 requestHeap := peerRequests{
165 request_strategy.GetRequestablePieces(
167 p.t.getPieceRequestOrder(),
168 func(ih InfoHash, pieceIndex int) {
169 if ih != p.t.infoHash {
172 if !p.peerHasPiece(pieceIndex) {
175 allowedFast := p.peerAllowedFast.ContainsInt(pieceIndex)
176 p.t.piece(pieceIndex).undirtiedChunksIter.Iter(func(ci request_strategy.ChunkIndex) {
177 r := p.t.pieceRequestIndexOffset(pieceIndex) + ci
179 // We must signal interest to request this. TODO: We could set interested if the
180 // peers pieces (minus the allowed fast set) overlap with our missing pieces if
181 // there are any readers, or any pending pieces.
182 desired.Interested = true
183 // We can make or will allow sustaining a request here if we're not choked, or
184 // have made the request previously (presumably while unchoked), and haven't had
185 // the peer respond yet (and the request was retained because we are using the
187 if p.peerChoking && !p.requestState.Requests.Contains(r) {
188 // We can't request this right now.
192 if p.requestState.Cancelled.Contains(r) {
193 // Can't re-request while awaiting acknowledgement.
196 requestHeap.requestIndexes = append(requestHeap.requestIndexes, r)
200 p.t.assertPendingRequests()
201 desired.Requests = requestHeap
205 func (p *Peer) maybeUpdateActualRequestState() {
206 if p.closed.IsSet() {
209 if p.needRequestUpdate == "" {
212 if p.needRequestUpdate == peerUpdateRequestsTimerReason {
213 since := time.Since(p.lastRequestUpdate)
214 if since < updateRequestsTimerDuration {
219 context.Background(),
220 pprof.Labels("update request", p.needRequestUpdate),
221 func(_ context.Context) {
222 next := p.getDesiredRequestState()
223 p.applyRequestState(next)
228 // Transmit/action the request state to the peer.
229 func (p *Peer) applyRequestState(next desiredRequestState) {
230 current := &p.requestState
231 if !p.setInterested(next.Interested) {
232 panic("insufficient write buffer")
235 requestHeap := &next.Requests
237 originalRequestCount := current.Requests.GetCardinality()
238 // We're either here on a timer, or because we ran out of requests. Both are valid reasons to
239 // alter peakRequests.
240 if originalRequestCount != 0 && p.needRequestUpdate != peerUpdateRequestsTimerReason {
242 "expected zero existing requests (%v) for update reason %q",
243 originalRequestCount, p.needRequestUpdate))
245 heap.Init(requestHeap)
246 for requestHeap.Len() != 0 && maxRequests(current.Requests.GetCardinality()+current.Cancelled.GetCardinality()) < p.nominalMaxRequests() {
247 req := heap.Pop(requestHeap).(RequestIndex)
248 existing := t.requestingPeer(req)
249 if existing != nil && existing != p {
250 // Don't steal from the poor.
251 diff := int64(current.Requests.GetCardinality()) + 1 - (int64(existing.uncancelledRequests()) - 1)
252 // Steal a request that leaves us with one more request than the existing peer
253 // connection if the stealer more recently received a chunk.
254 if diff > 1 || (diff == 1 && p.lastUsefulChunkReceived.Before(existing.lastUsefulChunkReceived)) {
259 more = p.mustRequest(req)
265 // This might fail if we incorrectly determine that we can fit up to the maximum allowed
266 // requests into the available write buffer space. We don't want that to happen because it
267 // makes our peak requests dependent on how much was already in the buffer.
269 "couldn't fill apply entire request state [newRequests=%v]",
270 current.Requests.GetCardinality()-originalRequestCount))
272 newPeakRequests := maxRequests(current.Requests.GetCardinality() - originalRequestCount)
274 // "requests %v->%v (peak %v->%v) reason %q (peer %v)",
275 // originalRequestCount, current.Requests.GetCardinality(), p.peakRequests, newPeakRequests, p.needRequestUpdate, p)
276 p.peakRequests = newPeakRequests
277 p.needRequestUpdate = ""
278 p.lastRequestUpdate = time.Now()
279 p.updateRequestsTimer.Reset(updateRequestsTimerDuration)
282 // This could be set to 10s to match the unchoke/request update interval recommended by some
283 // specifications. I've set it shorter to trigger it more often for testing for now.
284 const updateRequestsTimerDuration = 3 * time.Second