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 leftPiece := t.piece(int(leftPieceIndex))
96 rightPiece := t.piece(int(rightPieceIndex))
97 // Putting this first means we can steal requests from lesser-performing peers for our first few
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 -int(leftPiece.purePriority()),
104 -int(rightPiece.purePriority()),
106 leftPeer := t.pendingRequests[leftRequest]
107 rightPeer := t.pendingRequests[rightRequest]
108 ml = ml.Bool(rightPeer == p.peer, leftPeer == p.peer)
109 ml = ml.Bool(rightPeer == nil, leftPeer == nil)
114 // The right peer should also be set, or we'd have resolved the computation by now.
116 rightPeer.requestState.Requests.GetCardinality(),
117 leftPeer.requestState.Requests.GetCardinality(),
119 // Could either of the lastRequested be Zero? That's what checking an existing peer is for.
120 leftLast := t.lastRequested[leftRequest]
121 rightLast := t.lastRequested[rightRequest]
122 if leftLast.IsZero() || rightLast.IsZero() {
123 panic("expected non-zero last requested times")
125 // We want the most-recently requested on the left. Clients like Transmission serve requests
126 // in received order, so the most recently-requested is the one that has the longest until
127 // it will be served and therefore is the best candidate to cancel.
128 ml = ml.CmpInt64(rightLast.Sub(leftLast).Nanoseconds())
131 int(leftPiece.relativeAvailability),
132 int(rightPiece.relativeAvailability))
136 func (p *peerRequests) Swap(i, j int) {
137 p.requestIndexes[i], p.requestIndexes[j] = p.requestIndexes[j], p.requestIndexes[i]
140 func (p *peerRequests) Push(x interface{}) {
141 p.requestIndexes = append(p.requestIndexes, x.(RequestIndex))
144 func (p *peerRequests) Pop() interface{} {
145 last := len(p.requestIndexes) - 1
146 x := p.requestIndexes[last]
147 p.requestIndexes = p.requestIndexes[:last]
151 type desiredRequestState struct {
152 Requests peerRequests
156 func (p *Peer) getDesiredRequestState() (desired desiredRequestState) {
160 if p.t.closed.IsSet() {
163 input := p.t.getRequestStrategyInput()
164 requestHeap := peerRequests{
167 request_strategy.GetRequestablePieces(
169 p.t.getPieceRequestOrder(),
170 func(ih InfoHash, pieceIndex int) {
171 if ih != p.t.infoHash {
174 if !p.peerHasPiece(pieceIndex) {
177 allowedFast := p.peerAllowedFast.ContainsInt(pieceIndex)
178 p.t.piece(pieceIndex).undirtiedChunksIter.Iter(func(ci request_strategy.ChunkIndex) {
179 r := p.t.pieceRequestIndexOffset(pieceIndex) + ci
181 // We must signal interest to request this. TODO: We could set interested if the
182 // peers pieces (minus the allowed fast set) overlap with our missing pieces if
183 // there are any readers, or any pending pieces.
184 desired.Interested = true
185 // We can make or will allow sustaining a request here if we're not choked, or
186 // have made the request previously (presumably while unchoked), and haven't had
187 // the peer respond yet (and the request was retained because we are using the
189 if p.peerChoking && !p.requestState.Requests.Contains(r) {
190 // We can't request this right now.
194 if p.requestState.Cancelled.Contains(r) {
195 // Can't re-request while awaiting acknowledgement.
198 requestHeap.requestIndexes = append(requestHeap.requestIndexes, r)
202 p.t.assertPendingRequests()
203 desired.Requests = requestHeap
207 func (p *Peer) maybeUpdateActualRequestState() {
208 if p.closed.IsSet() {
211 if p.needRequestUpdate == "" {
214 if p.needRequestUpdate == peerUpdateRequestsTimerReason {
215 since := time.Since(p.lastRequestUpdate)
216 if since < updateRequestsTimerDuration {
221 context.Background(),
222 pprof.Labels("update request", p.needRequestUpdate),
223 func(_ context.Context) {
224 next := p.getDesiredRequestState()
225 p.applyRequestState(next)
230 // Transmit/action the request state to the peer.
231 func (p *Peer) applyRequestState(next desiredRequestState) {
232 current := &p.requestState
233 if !p.setInterested(next.Interested) {
234 panic("insufficient write buffer")
237 requestHeap := &next.Requests
239 originalRequestCount := current.Requests.GetCardinality()
240 // We're either here on a timer, or because we ran out of requests. Both are valid reasons to
241 // alter peakRequests.
242 if originalRequestCount != 0 && p.needRequestUpdate != peerUpdateRequestsTimerReason {
244 "expected zero existing requests (%v) for update reason %q",
245 originalRequestCount, p.needRequestUpdate))
247 heap.Init(requestHeap)
248 for requestHeap.Len() != 0 && maxRequests(current.Requests.GetCardinality()+current.Cancelled.GetCardinality()) < p.nominalMaxRequests() {
249 req := heap.Pop(requestHeap).(RequestIndex)
250 existing := t.requestingPeer(req)
251 if existing != nil && existing != p {
252 // Don't steal from the poor.
253 diff := int64(current.Requests.GetCardinality()) + 1 - (int64(existing.uncancelledRequests()) - 1)
254 // Steal a request that leaves us with one more request than the existing peer
255 // connection if the stealer more recently received a chunk.
256 if diff > 1 || (diff == 1 && p.lastUsefulChunkReceived.Before(existing.lastUsefulChunkReceived)) {
261 more = p.mustRequest(req)
267 // This might fail if we incorrectly determine that we can fit up to the maximum allowed
268 // requests into the available write buffer space. We don't want that to happen because it
269 // makes our peak requests dependent on how much was already in the buffer.
271 "couldn't fill apply entire request state [newRequests=%v]",
272 current.Requests.GetCardinality()-originalRequestCount))
274 newPeakRequests := maxRequests(current.Requests.GetCardinality() - originalRequestCount)
276 // "requests %v->%v (peak %v->%v) reason %q (peer %v)",
277 // originalRequestCount, current.Requests.GetCardinality(), p.peakRequests, newPeakRequests, p.needRequestUpdate, p)
278 p.peakRequests = newPeakRequests
279 p.needRequestUpdate = ""
280 p.lastRequestUpdate = time.Now()
281 p.updateRequestsTimer.Reset(updateRequestsTimerDuration)
284 // This could be set to 10s to match the unchoke/request update interval recommended by some
285 // specifications. I've set it shorter to trigger it more often for testing for now.
286 const updateRequestsTimerDuration = 3 * time.Second