计算机科学 · 第 4 册 · 本科二年级

University Computer Science — Year 2

本书暂未推出简体中文版。现有版本:English。

University Computer Science — Year 2 · 本科二年级

19The Transport Layer: UDP and TCP

The town’s table of people is sent in 100-byte packets over a link that loses a fifth of them, duplicates some and delivers others out of order:

$ python file_copy.py
file: 2986 bytes in 30 packets
link: 12 of 53 packets lost, some duplicated, some reordered
received 2986 bytes, identical to the original: True
Output 19.1. A file across a bad link (a seeded simulation).

Twelve packets were lost on the way, and yet the copy is exact. The network layer of Chapter 18 promises nothing: packets may be lost, duplicated or reordered. The transport layer builds, on top of it, what programs want: a conversation between two programs (not just two machines), and, for TCP, a stream of bytes that arrives complete and in order, as the sockets of Chapter 16 assumed. This chapter derives the protocols that do it, measures what they cost, and ends with how TCP shares the network with everyone else.

You already know

Book 2: a sender numbers its messages, the receiver acknowledges them, and the sender repeats a message whose acknowledgement does not come in time; one bit of numbering is enough when one message is in flight (the alternating-bit protocol). Chapter 16: a port number names a program on a machine; TCP sockets carry a byte stream, UDP sockets datagrams. Chapter 18: IP delivers packets between machines, at best.

19.1 Ports and UDP

IP brings a packet to a machine; the transport layer brings it to a program.

Definition 19.1 (Multiplexing and demultiplexing)

A transport protocol multiplexes the messages of many programs into the packets of one machine, labelling each with a source and a destination port number, and demultiplexes the packets it receives, handing each to the program that owns its destination port. A conversation is named by four numbers: both addresses and both ports.

Ports 0 to 1023 are the system ports of well-known services, 1024 to 49151 are registered to applications, and 49152 to 65535 are left free for the temporary ports clients use (the range the registry recommends; Linux uses its own, 32 768 to 60 999, as Chapter 16 noted). UDP adds nothing else: its header is 8 bytes, the two ports, a length that counts header and data, and a checksum.

$ python udp_header.py
header: ac 9f ac 9e 00 0d 00 00  message: 77 68 6f 20 37
source port 44191, destination port 44190, length 13 = 8 + 5
Output 19.2. The UDP header of a 5-byte request.

A UDP datagram may be lost, duplicated or reordered, exactly like the packet that carries it. Programs that prefer speed to completeness (a voice call, a game, a name lookup that can simply be asked again) use it as it is; the others need reliable transfer.

19.2 Reliable transfer

Definition 19.2 (Reliable data transfer)

A protocol provides reliable data transfer over a channel that may lose, duplicate or reorder packets if the receiver hands its program every item the sender was given, each exactly once, in the order given. Stop-and-wait is the protocol in which the sender has at most one packet unacknowledged.

The protocols of this section run in a small simulator: a link with a one-way delay of 50 ms, 1 ms to put a packet on the wire, and seeded loss, duplication and reordering.

19.2.1 Stop-and-wait

Definition 19.3 (Sequence number, acknowledgement, timeout)

A sequence number is a number a sender puts in each packet so that the receiver can tell new packets from repeated ones and put them in order. An acknowledgement is a packet from the receiver that names a sequence number it has received; it is cumulative when it vouches for every packet up to that number. The round-trip time (RTT) is the time from sending a packet to receiving its acknowledgement, and the retransmission timeout is how long the sender waits for an acknowledgement before sending the packet again.

Stop-and-wait sends one packet and waits for its acknowledgement; if none comes before the timeout, it sends the packet again. A 1-bit sequence number tells a new packet from a repeated one.

class Sender:
    def __init__(self, sim, data, timeout):
        self.sim, self.data, self.timeout = sim, data, timeout
        self.next, self.bit, self.timer = 0, 0, 0
        self.link = None

    def start(self):
        if self.next < len(self.data):
            self.link.send((self.bit, self.data[self.next]))
            self.timer += 1                      # a new timer; older ones are void
            self.sim.at(self.sim.now + self.timeout, self.expire, self.timer)

    def expire(self, timer):
        if timer == self.timer:                  # no acknowledgement came: send again
            self.start()

    def on_ack(self, bit):
        if bit == self.bit:                      # the ack of the packet in flight
            self.next, self.bit = self.next + 1, 1 - self.bit
            self.start()                         # (a duplicate ack is ignored)
Listing 19.1. The sender of stop-and-wait code/bachelor-2/19-transport-layer/listings/stop_and_wait.py
$ python stop_and_wait.py
loss 0.0: delivered intact True, 200 packets sent for 200, 20.3 s
loss 0.1: delivered intact True, 250 packets sent for 200, 27.9 s
loss 0.3: delivered intact True, 430 packets sent for 200, 54.9 s
Output 19.3. 200 packets, 5 % of them duplicated, at three loss rates.

It is correct, but slow: 200 packets take 20 seconds even without loss, because the link carries a packet for 1 ms and then sits idle for the 100 ms round trip.

Proposition 19.4 (Utilisation)

Let a packet of LL bits take L/RL/R to send at rate RR, and let RTT be the round-trip time. Without loss, the fraction of time a stop-and-wait sender keeps the link busy is

U=L/RRTT+L/R,U = \frac{L/R}{\mathrm{RTT} + L/R} ,

and a sender allowed WW packets in flight reaches min⁡(1,WU)\min\bigl(1, W U\bigr).

Proof. A cycle starts when a packet starts. It occupies the link for L/RL/R; its acknowledgement comes back RTT after the packet has been sent completely, and the next packet starts then, so a cycle lasts RTT+L/R\mathrm{RTT} + L/R and the link is busy for L/RL/R of it. With a window of WW, the sender sends WW packets back to back in each cycle, unless the link is full before the first acknowledgement returns, which happens when WL/R≥RTT+L/RW L/R \ge \mathrm{RTT} + L/R. ∎

Here U=1/101U = 1/101: about 1 %. The cure is to keep several packets in flight.

19.2.2 Sliding windows

Definition 19.5 (Window, sequence numbers)

In a sliding-window protocol, the sender may have up to WW packets sent but not yet acknowledged, the window. Packets carry sequence numbers on kk bits, so numbers are counted modulo 2k2^k. When the oldest packet of the window is acknowledged, the window slides forward. In go-back-N the receiver accepts packets only in order and acknowledges cumulatively, and a timeout makes the sender send its whole window again; in selective repeat the receiver also keeps packets that arrive early, acknowledges each packet separately, and the sender sends again only the packets whose own timer expires.

A sender’s view of the sequence space with k = 3: numbers repeat after 8. When the ack of packet 3 arrives, the window moves one place right and one more packet may go.
A sender’s view of the sequence space with k=3k = 3: numbers repeat after 8. When the ack of packet 3 arrives, the window moves one place right and one more packet may go.

The two ways to repeat what is lost differ in how much they keep. The go-back-N receiver acknowledges the last packet it has accepted in order; the sender keeps one timer, for its oldest packet.

    def fill(self):
        while self.next < len(self.data) and self.next < self.base + self.W:
            self.link.send((self.next % self.M, self.data[self.next]))
            if self.next == self.base:
                self.arm()
            self.next += 1

    def arm(self):
        self.timer += 1
        self.sim.at(self.sim.now + self.timeout, self.expire, self.timer)

    def expire(self, timer):
        if timer == self.timer and self.base < self.next:
            self.next = self.base                # go back: resend the whole window
            self.fill()

    def on_ack(self, seq):
        offset = (seq - self.base) % self.M      # how far past base this ack reaches
        if offset < self.next - self.base:
            self.base += offset + 1              # cumulative: all up to seq arrived
            if self.base < self.next:
                self.arm()
            else:
                self.timer += 1                  # nothing in flight: no timer
            self.fill()
Listing 19.2. The go-back-N sender: fill the window, go back on a timeout, slide on an ack code/bachelor-2/19-transport-layer/listings/go_back_n.py
    def on_packet(self, packet):
        seq, item = packet
        if seq == self.expected % self.M:        # the next one in order: accept
            self.out.append(item)
            self.expected += 1
            self.done = self.clock.now           # time of the last delivery
        self.link.send((self.expected - 1) % self.M)   # ack the last in-order packet
Listing 19.3. The go-back-N receiver code/bachelor-2/19-transport-layer/listings/go_back_n.py
$ python go_back_n.py
no loss: link utilisation against the window (RTT 100 ms, 1 ms per packet)
  W   1: measured 0.010, formula 0.010
  W   7: measured 0.069, formula 0.069
  W  31: measured 0.303, formula 0.307
  W 127: measured 0.990, formula 1.000
loss 5 %, duplicates 2 %, W 31:
  intact True, 13408 sent for 5000, 76.3 s
Output 19.4. Utilisation against the window, then a lossy link.

Without loss the measured utilisation follows Proposition 19.4. With 5 % loss, go-back-N sends 13 408 packets for 5 000: each loss throws away the window behind it. Selective repeat keeps those packets instead: its receiver accepts any packet within its own window of WW and buffers it, and its sender keeps a timer per packet (Exercise 19.7).

    def on_packet(self, packet):
        seq, item = packet
        offset = (seq - self.base) % self.M
        if offset < self.W:                      # inside the window: keep it
            self.buffer.setdefault(self.base + offset, item)
            while self.base in self.buffer:      # deliver what is now in order
                self.out.append(self.buffer.pop(self.base))
                self.base += 1
                self.done = self.clock.now
            self.link.send(seq)
        elif offset >= self.M - self.W:          # the window before: already delivered
            self.link.send(seq)                  # its ack was lost; ack it again
Listing 19.4. The selective-repeat receiver: buffer, deliver in order, acknowledge each packet code/bachelor-2/19-transport-layer/listings/selective_repeat.py
$ python selective_repeat.py
loss 5 %, duplicates 2 %, W 31:
  intact True, 5531 sent for 5000, 36.7 s
Output 19.5. The same link: 531 extra packets instead of 8 408.

How large may the window be, for kk bits of sequence number? The receiver must never take an old packet, sent again, for a new one with the same number.

Proposition 19.6 (Go-back-N window)

On a channel that may lose and duplicate packets but does not reorder them, go-back-N with kk-bit sequence numbers is correct if and only if W≤2k−1W \le 2^k - 1.

The proof is Exercise 19.8. For selective repeat, the receiver’s window moves too, and the bound is halved.

Theorem 19.7 (Selective-repeat window)

On such a channel, selective repeat with kk-bit sequence numbers and windows of WW at both ends is correct if and only if W≤2k−1W \le 2^{k-1}.

Proof. Let the receiver expect packet bb (all before it have been delivered). The sender has had acknowledgements for every packet before b−Wb - W, since it could not have sent packet b−1b - 1 otherwise; so any packet it may still send, new or repeated, is numbered from b−Wb - W to b+W−1b + W - 1. These 2W2W numbers are distinct modulo 2k2^k when 2W≤2k2W \le 2^k, so the receiver tells apart the packets of its window, bb to b+W−1b + W - 1, from the old ones, b−Wb - W to b−1b - 1, which it only acknowledges again. That proves sufficiency. Conversely, if W≥2k−1+1W \ge 2^{k-1} + 1, let the sender send packets 00 to W−1W - 1, all received and all acknowledgements lost. The receiver now expects WW to 2W−12W - 1, and 2W−1≥2k2W - 1 \ge 2^k, so its window contains the number 2k≡02^k \equiv 0. The sender, timing out, repeats packet 0, which the receiver stores as packet 2k2^k: wrong data is delivered. ∎

$ python sr_too_wide.py
the sender sends packets 0, 1, 2 with sequence numbers 0, 1, 2
  receiver acks 0
  receiver acks 1
  receiver acks 2
all three acks are lost; the sender times out and resends packet 0 (sequence 0)
  receiver acks 0
the receiver keeps it as packet 4: {4: 'packet 0'}
later the real packet 3 arrives
  receiver acks 3
the receiver delivered: ['packet 0', 'packet 1', 'packet 2', 'packet 3', 'packet 0']
Output 19.6. The second half of the proof, staged with k=2k = 2 and W=3W = 3.

On a channel that reorders packets, an old packet can arrive very late, and no window is safe unless the sequence space is much larger than what can be in flight. TCP numbers bytes with 32 bits for that reason.

19.3 TCP

TCP is a sliding-window protocol over a byte stream. Each segment carries a 32-bit sequence number, the position of its first byte in the stream, and a 32-bit acknowledgement number, the next byte expected: acknowledgements are cumulative, as in go-back-N, but the receiver keeps segments that arrive early, as in selective repeat. The header, at least 20 bytes, also holds the two ports, a window size, a checksum, and flags such as SYN, ACK and FIN.

19.3.1 Connections

Definition 19.8 (TCP connection)

A TCP connection is the state two ends keep about one byte stream in each direction: the sequence numbers sent and acknowledged, the windows, and a connection state such as ESTABLISHED. It is opened by a three-way handshake: the client sends SYN with its starting sequence number, the server answers SYN+ACK with its own, and the client acknowledges it. Each end later closes its direction separately with FIN.

The states of a connection form a finite automaton:

$ python tcp_states.py
client  open as client   -> SYN-SENT      send SYN
client  receive SYN+ACK  -> ESTABLISHED   send ACK
server  open as server   -> LISTEN
server  receive SYN      -> SYN-RECEIVED  send SYN+ACK
server  receive ACK      -> ESTABLISHED
the client closes first:
client  close            -> FIN-WAIT-1    send FIN
client  receive ACK      -> FIN-WAIT-2
client  receive FIN      -> TIME-WAIT     send ACK
client  2 MSL pass       -> CLOSED
server  receive FIN      -> CLOSE-WAIT    send ACK
server  close            -> LAST-ACK      send FIN
server  receive ACK      -> CLOSED
Output 19.7. The handshake and a close, as transitions of TCP’s state machine.
The handshake and a close initiated by the client, with the state each end enters (time runs downwards). The side that closes first waits in TIME-WAIT before forgetting the connection.
The handshake and a close initiated by the client, with the state each end enters (time runs downwards). The side that closes first waits in TIME-WAIT before forgetting the connection.

The side that closes first stays in TIME-WAIT for twice the maximum lifetime of a segment (4 minutes in the standard, much less in practice), so that a late segment of this connection cannot be taken for part of a new one between the same ports; this is the state that made SO_REUSEADDR necessary in Chapter 16.

19.3.2 The retransmission timeout

A timer set too short sends needless copies; set too long, it leaves the link idle after a loss. TCP sets it from the round-trip times it measures, smoothing both their mean and their variation.

Method 19.9 (Retransmission timeout)

For the first round-trip sample RR, set SRTT=R\mathrm{SRTT} = R and RTTVAR=R/2\mathrm{RTTVAR} = R/2. For each later sample, set RTTVAR←34RTTVAR+14∣SRTT−R∣\mathrm{RTTVAR} \leftarrow \frac34 \mathrm{RTTVAR} + \frac14 |\mathrm{SRTT} - R|, then SRTT←78SRTT+18R\mathrm{SRTT} \leftarrow \frac78 \mathrm{SRTT} + \frac18 R. The timeout is RTO=SRTT+4 RTTVAR\mathrm{RTO} = \mathrm{SRTT} + 4\,\mathrm{RTTVAR}, at least 1 second, and it is doubled each time it expires.

def estimate(samples):
    srtt = rttvar = None
    for r in samples:
        if srtt is None:                         # the first measurement
            srtt, rttvar = r, r / 2
        else:                                    # rttvar first, with the old srtt
            rttvar = (1 - BETA) * rttvar + BETA * abs(srtt - r)
            srtt = (1 - ALPHA) * srtt + ALPHA * r
        computed = srtt + K * rttvar
        yield r, srtt, rttvar, computed, max(computed, MIN_RTO)
Listing 19.5. The estimator code/bachelor-2/19-transport-layer/listings/rto.py
$ python rto.py
 sample    srtt  rttvar  srtt+4var    rto
    100   100.0    50.0   300.0  1000.0
    120   102.5    42.5   272.5  1000.0
     90   100.9    35.0   240.9  1000.0
    110   102.1    28.5   216.1  1000.0
    400   139.3    95.9   522.8  1000.0
    100   134.4    81.7   461.3  1000.0
    105   130.7    68.6   405.3  1000.0
Output 19.8. One sample of 400 ms among samples near 100 ms. Some lines are left out.

The spike raises the variation at once and the mean slowly, so the timeout jumps and then decays. On a fast network the 1-second floor dominates.

19.3.3 Flow control

The receiving program may read slower than the network delivers.

Definition 19.10 (Flow control)

Each TCP acknowledgement carries the free space left in the receiver’s buffer, the receive window, and the sender never has more unacknowledged bytes in flight than that. This is flow control: it protects the receiver, as congestion control protects the network.

A small receive buffer therefore limits throughput, even on a loopback connection:

$ python bulk_transfer.py
receive buffer 4096 bytes                827 MB/s
receive buffer 65536 bytes              4863 MB/s
receive buffer the system's default     5891 MB/s
Output 19.9. 256 MiB over TCP on 127.0.0.1, on the laptop, with the receiver’s buffer set three ways.

19.4 Congestion control

A window large enough to fill the sender’s link may still be too large for a slower link further on, shared with other connections. Packets then queue in a router until its buffer overflows and they are dropped. TCP reads a loss as a sign of congestion and slows down.

Definition 19.11 (Congestion, congestion window)

A network is congested when packets arrive at a router faster than it can forward them, so that its queue grows and packets are dropped. A TCP sender limits its own rate by a congestion window, a number of bytes it may have in flight, which it raises while acknowledgements come and lowers when a loss shows congestion. Raising it by a constant per round trip and multiplying it by a constant below 1 at a loss is additive increase, multiplicative decrease (AIMD).

Method 19.12 (TCP congestion control)

The sender keeps a congestion window cwnd and sends at most min⁡(cwnd,receive window)\min(\text{cwnd}, \text{receive window}). Slow start: cwnd starts at a few segments (one in the simplest form, used in this chapter’s simulator) and grows by one segment per acknowledgement, doubling every round trip, up to a threshold ssthresh. Congestion avoidance: above it, cwnd grows by about one segment per round trip. On three duplicate acknowledgements (fast retransmit), the sender resends the missing segment at once and halves cwnd (fast recovery); on a timeout, it sets ssthresh to half the data in flight and cwnd to one segment, and slow-starts again.

Growing by one segment per round trip and halving on a loss is AIMD. Its window draws a sawtooth:

The congestion window of aimd.py with one packet in 500 lost: slow start doubles the window up to the threshold 64, congestion avoidance adds one segment per round trip until the first loss halves it at 70, and the sawtooth of additive increase and halving follows.
The congestion window of aimd.py with one packet in 500 lost: slow start doubles the window up to the threshold 64, congestion avoidance adds one segment per round trip until the first loss halves it at 70, and the sawtooth of additive increase and halving follows.

The sawtooth gives TCP’s throughput as a function of the loss rate.

Proposition 19.13 (Throughput law)

If one packet in 1/p1/p is lost, periodically, and the window grows by one segment per round trip and halves at each loss, the average throughput is

MSSRTT32p\frac{\mathrm{MSS}}{\mathrm{RTT}} \sqrt{\frac{3}{2p}}

where MSS is the segment size.

The derivation, from the area under one tooth, is Exercise 19.10. The simulator checks it:

$ python aimd.py
     p   sqrt(3/2p)  periodic  error   random  error  (packets per RTT)
  0.01       12.25     11.11  -9.3%    12.46  +1.7%
 0.003       22.36     21.33  -4.6%    23.39  +4.6%
 0.001       38.73     37.75  -2.5%    40.79  +5.3%
0.0003       70.71     69.49  -1.7%    75.43  +6.7%
Output 19.10. Packets per round trip, simulated over 200 000 round trips, against the law.

With periodic losses the simulation lands within 3 % of the law once p≤0.001p \le 0.001; with p=0.01p = 0.01 the window is only about 16 segments and whole segments count. With random losses the throughput is a few per cent higher: losses are irregular and the window sometimes grows longer.

19.5 Fairness

When several connections share a link, AIMD also divides it fairly.

Definition 19.14 (Fairness, Jain’s index)

An allocation of a link among nn flows is fair when the flows that want more than an equal share all get the same share. Jain’s index of shares x1,…,xnx_1, \dots, x_n is

J=(∑ixi)2n∑ixi2,J = \frac{(\sum_i x_i)^2}{n \sum_i x_i^2} ,

which is 1 for equal shares and 1/n1/n when one flow has everything.

Theorem 19.15 (AIMD is fair)

Two flows share a link of capacity CC. In each round, if x1+x2≤Cx_1 + x_2 \le C both add a>0a > 0, and otherwise both multiply by b∈(0,1)b \in (0, 1). Then x1−x2→0x_1 - x_2 \to 0: the shares become equal.

Proof. An increase leaves x1−x2x_1 - x_2 unchanged, and a decrease multiplies it by bb. Decreases happen infinitely often: after at most ⌈C/(2a)⌉+1\lceil C / (2a) \rceil + 1 increases in a row, x1+x2x_1 + x_2 exceeds CC. So ∣x1−x2∣|x_1 - x_2| is multiplied by bb infinitely often and never grows: it tends to 0. ∎

Two AIMD flows starting at 4 and 40 with C = 50. Increases move parallel to the fair line; each decrease moves towards the origin, halving the distance to it.
Two AIMD flows starting at 4 and 40 with C=50C = 50. Increases move parallel to the fair line; each decrease moves towards the origin, halving the distance to it.
$ python fairness.py
round      x1      x2   index
    0    4.00   40.00  0.5990
   25   14.50   23.50  0.9469
   50   14.88   17.12  0.9951
   75   12.72   13.28  0.9995
  100   23.86   24.14  1.0000
  125   20.96   21.04  1.0000
  150   17.99   18.01  1.0000
  175   15.00   15.00  1.0000
  200   26.00   26.00  1.0000
Output 19.11. The shares and Jain’s index every 25 rounds.

Jain’s index measures how equal the shares are. Fairness holds only among flows that see the same round trip; a flow with a longer one adds its segment less often, and gets less (Exercise 19.11). Multiplying on increase instead of adding would keep the ratio of the shares for ever (Exercise 19.12).

Facts as of 2026

TCP is no longer the only reliable transport. QUIC, standardised in May 2021, runs over UDP and provides several independent streams in one encrypted connection, with a faster connection setup and the ability to keep a connection when a phone changes network; it carries a large share of web traffic. Its loss recovery and congestion control follow the principles of this chapter.

19.6 Exercises

Exercise 19.1 ★

Go-back-N with W=4W = 4 sends packets 0 to 9. Packet 2 is lost once, and the acknowledgement of packet 5 is lost. List the packets sent, in order, until all are acknowledged, assuming the timer expires only when needed.

Solution

Solution of Exercise 19.1.

The sender sends 0, 1, 2, 3; the acks of 0 and 1 let it send 4 and 5. Packet 2 is lost, so the receiver discards 3, 4 and 5 and acknowledges 1 each time. The timer of packet 2 expires: the sender goes back and sends 2, 3, 4, 5 again. All arrive; the acks of 2, 3 and 4 let it send 6, 7 and 8. The ack of 5 is lost, but the ack of 6 is cumulative and covers 5, so 9 follows. In all: 0 1 2 3 4 5 2 3 4 5 6 7 8 9. The lost acknowledgement costs nothing.

Exercise 19.2 ★

In Output 19.6, which packets does the receiver deliver, which is wrong, and what window would have prevented it with k=2k = 2?

Solution

Solution of Exercise 19.2.

It delivers packets 0, 1, 2 and 3 correctly, then the stale copy of packet 0, which it had stored as packet 4. The fifth item delivered is wrong, and the real packet 4, when it comes, will be taken as a duplicate. With k=2k = 2, a window of 2=2k−12 = 2^{k-1} prevents it (Theorem 19.7): the receiver’s window after packets 0 and 1 is {2,3}\{2, 3\}, and a repeated 0 falls in the window before, which is only acknowledged again.

Exercise 19.3 ★

Write the receiver of stop-and-wait for the sender of Output 19.3: it must deliver each item once and acknowledge every packet, duplicates included. Why must it acknowledge duplicates?

Solution

Solution of Exercise 19.3.

class Receiver:
    def __init__(self):
        self.expected, self.out, self.link = 0, [], None
        self.clock, self.done = None, 0.0

    def on_packet(self, packet):
        bit, item = packet
        if bit == self.expected:                 # new data: keep it
            self.out.append(item)
            self.expected = 1 - self.expected
            self.done = self.clock.now
        self.link.send(bit)                      # acknowledge, even a duplicate
The receiver of stop-and-wait code/bachelor-2/19-transport-layer/listings/stop_and_wait.py

A duplicate arrives because the sender did not get the acknowledgement of the original, lost or late. If the receiver did not acknowledge it again, the sender would send it for ever.

Exercise 19.4 ★

A link of 1 Gbit/s connects two towns 3000 km apart (a round trip of 30 ms). Packets are 1500 bytes. Compute the utilisation of stop-and-wait, and the window that fills the link.

Solution

Solution of Exercise 19.4.

L/R=12 000/109L/R = 12\,000 / 10^9 s =12= 12 µs, so U=0.012/(30+0.012)≈0.0004U = 0.012 / (30 + 0.012) \approx 0.0004: 0.04 % of the link. The window that fills it is (RTT+L/R)/(L/R)≈2 501(\mathrm{RTT} + L/R)/(L/R) \approx 2\,501 packets, about 3.75 MB in flight: the product of the rate and the round trip, which a long fast link needs in its windows.

Exercise 19.5 ★★

Compute SRTT, RTTVAR and the timeout for the samples 800, 800, 1600 and 800 ms, and check them with rto.py, whose second series is these samples. Why does the timeout of the third sample exceed 1600?

Solution

Solution of Exercise 19.5.

First sample: SRTT 800, RTTVAR 400, timeout 800+4×400=2400800 + 4 \times 400 = 2400. Second: RTTVAR =34400+140=300= \frac34 400 + \frac14 0 = 300, SRTT 800, timeout 2000. Third: RTTVAR =34300+14∣800−1600∣=425= \frac34 300 + \frac14 |800 - 1600| = 425, SRTT =78800+181600=900= \frac78 800 + \frac18 1600 = 900, timeout 900+1700=2600900 + 1700 = 2600. Fourth: RTTVAR =34425+14100=343.75= \frac34 425 + \frac14 100 = 343.75, SRTT =887.5= 887.5, timeout 2262.5. These are the values rto.py prints for this series, none clamped since all exceed 1000:

$ python rto.py
 sample    srtt  rttvar  srtt+4var    rto
    800   800.0   400.0  2400.0  2400.0
    800   800.0   300.0  2000.0  2000.0
   1600   900.0   425.0  2600.0  2600.0
    800   887.5   343.8  2262.5  2262.5
Output 19.13. The second series of samples. Some lines are left out.

The third timeout exceeds the 1600 just measured because the variation term grows at once with the surprise, so that the next sample of 1600 would not cause a needless retransmission.

Exercise 19.6 ★★

This receiver acknowledges each packet it receives, in order or not. Explain the output.

class WrongReceiver(Receiver):
    def on_packet(self, packet):
        seq, item = packet
        if seq == self.expected % self.M:
            self.out.append(item)
            self.expected += 1
            self.done = self.clock.now
        self.link.send(seq)                      # the bug: ack it, in order or not
Listing 19.6. A wrong acknowledgement code/bachelor-2/19-transport-layer/listings/exo_gbn_ack.py
$ python exo_gbn_ack.py
delivered 520 of 1000; intact False
first missing packets: [7, 8, 9, 10, 11]
Output 19.12. With 5 % loss.
Solution

Solution of Exercise 19.6.

When packet 7 is lost and packet 8 arrives, the receiver acknowledges 8. The sender reads acknowledgements as cumulative, so it believes 7 arrived, slides past it and never sends it again. The receiver, still waiting for sequence number 7 (modulo 16), later accepts packet 23, which has that number, as if it were packet 7: the stream is corrupted, and from then on its expectations and the sender’s no longer meet. Only 520 items are delivered, wrong ones among them. A go-back-N receiver must acknowledge the last packet it accepted in order.

Exercise 19.7 ★★

Write the sender of selective repeat, with a timer per packet, for the receiver of Listing 19.4.

Solution

Solution of Exercise 19.7.

class Sender:
    def __init__(self, sim, data, k, window, timeout):
        assert window <= 2 ** (k - 1), "selective repeat needs W <= 2^(k-1)"
        self.sim, self.data, self.timeout = sim, data, timeout
        self.M, self.W = 2**k, window
        self.base = self.next = 0
        self.acked, self.link = set(), None

    def fill(self):
        while self.next < len(self.data) and self.next < self.base + self.W:
            self.send(self.next)
            self.next += 1

    def send(self, i):
        self.link.send((i % self.M, self.data[i]))
        self.sim.at(self.sim.now + self.timeout, self.expire, i)

    def expire(self, i):
        if i >= self.base and i not in self.acked:
            self.send(i)                         # resend this packet only

    def on_ack(self, seq):
        offset = (seq - self.base) % self.M
        if offset < self.next - self.base:
            self.acked.add(self.base + offset)
            while self.base in self.acked:       # slide past every acked packet
                self.acked.discard(self.base)
                self.base += 1
            self.fill()
The selective-repeat sender code/bachelor-2/19-transport-layer/listings/selective_repeat.py

Each packet sent schedules its own expiry; an expiry does nothing if the packet has been acknowledged or slid past in the meantime. An acknowledgement marks one packet, and the base slides past every marked packet at its front. The tests run it with W=2k−1W = 2^{k-1} under loss and duplication, and with jitter when the sequence space is large.

Exercise 19.8 ★★

Prove Proposition 19.6.

Solution

Solution of Exercise 19.8.

Number packets by their absolute index; packet ii carries i mod 2ki \bmod 2^k. Let the receiver expect packet ee.

Data. The receiver accepted e−1e - 1, sent at some time tt; at tt the sender’s window held e−1e - 1, so its base was at least e−We - W, and the base never decreases. The channel keeps the order, so every packet arriving now was sent after tt, and is at least e−We - W. It is at most e+W−1e + W - 1, since the sender’s base cannot pass ee (it moves only on acknowledgements of accepted packets). A packet ii with i≡ei \equiv e and ∣i−e∣≤W<2k|i - e| \le W < 2^k is ee itself, so the receiver accepts exactly the right packet.

Acknowledgements. They arrive in the order sent, and each acknowledges the last packet accepted, so an arriving acknowledgement aa satisfies base−1≤a≤next−1\text{base} - 1 \le a \le \text{next} - 1, where next −- base ≤W\le W. Its offset a−basea - \text{base} ranges over W+1W + 1 values from −1-1 to W−1W - 1, which are distinct modulo 2k2^k exactly when W+1≤2kW + 1 \le 2^k; then the sender reads every acknowledgement correctly. So W≤2k−1W \le 2^k - 1 suffices.

Necessity. With W=2kW = 2^k, let packets 00 to 2k−12^k - 1 all arrive and all their acknowledgements be lost. The sender goes back and repeats packet 0; the receiver, expecting packet 2k2^k, whose number is 0, accepts the old packet as new.

Exercise 19.9 ★★

Add fast retransmit to the go-back-N sender: at the third duplicate acknowledgement, go back at once instead of waiting for the timer. Measure the effect with 2 % loss.

Solution

Solution of Exercise 19.9.

class FastSender(go_back_n.Sender):
    def __init__(self, *args):
        super().__init__(*args)
        self.dups = 0

    def on_ack(self, seq):
        if (seq - self.base) % self.M == self.M - 1 and self.base < self.next:
            self.dups += 1                       # an ack for base - 1: a duplicate
            if self.dups == 3:                   # three: base is surely lost
                self.next = self.base            # go back now, not at the timeout
                self.arm()
                self.fill()
            return
        self.dups = 0
        super().on_ack(seq)
Going back at the third duplicate acknowledgement code/bachelor-2/19-transport-layer/listings/fast_retransmit.py
$ python fast_retransmit.py
timeout only     intact True  8162 sent  54.0 s
fast retransmit  intact True  8162 sent  24.7 s
Output 19.14. 5000 packets, 2 % loss, timeout 300 ms.

An acknowledgement for the packet before the base is a duplicate: packets after a loss keep arriving and keep being answered with the same number. Three of them make the loss nearly certain, a round trip after it, instead of the 300 ms of the timer. The packets sent are the same; the transfer takes 24.7 s instead of 54.0.

Exercise 19.10 ★★★

Prove Proposition 19.13: in the steady state the window grows from W/2W/2 to WW between two losses; count the packets sent in one tooth and set it to 1/p1/p.

Solution

Solution of Exercise 19.10.

In the steady state, a loss halves the window from WW to W/2W/2, and it then grows by one per round trip until it reaches WW again and the next loss comes: a tooth lasts W/2W/2 round trips. The packets sent in a tooth are W2+(W2+1)+⋯+W≈W2⋅3W4=38W2\frac W2 + (\frac W2 + 1) + \dots + W \approx \frac W2 \cdot \frac{3W}{4} = \frac38 W^2, the number of round trips times the average window. One packet in 1/p1/p is lost, so 38W2=1/p\frac38 W^2 = 1/p and W=8/(3p)W = \sqrt{8/(3p)}. The throughput is the packets of a tooth over its duration:

1/p(W/2) RTT=2pW RTT=1RTT⋅2p3p8=1RTT32p\frac{1/p}{(W/2)\,\mathrm{RTT}} = \frac{2}{pW\,\mathrm{RTT}} = \frac{1}{\mathrm{RTT}} \cdot \frac{2}{p} \sqrt{\frac{3p}{8}} = \frac{1}{\mathrm{RTT}} \sqrt{\frac{3}{2p}}

segments per second, and multiplying by the segment size MSS gives the law.

Exercise 19.11 ★★★

Simulate two AIMD flows sharing a link, whose round trips are 1 and 2 time units, with losses that hit both. Measure their shares of the link and Jain’s index, and explain the ratio.

Solution

Solution of Exercise 19.11.

$ python exo_rtt_unfair.py
shares of the link: flow 1 0.800, flow 2 0.200
fairness index: 0.735
Output 19.15. Round trips of 1 and 2 time units, shared losses.

A flow’s rate is its window divided by its round trip. Flow 1’s rate grows by 1 per time unit; flow 2’s window grows by 1 every 2 units, so its rate grows by 1/21/2 per 2 units, 1/41/4 per unit. Between two shared losses each rate climbs from half its peak, so the peaks, and the averages, stand in the ratio of the growth rates, 4:14 : 1: shares 0.80.8 and 0.20.2, and J=(0.8+0.2)2/(2(0.64+0.04))≈0.735J = (0.8 + 0.2)^2 / (2 (0.64 + 0.04)) \approx 0.735. Under AIMD with shared losses, a flow’s share falls as the square of its round trip.

Exercise 19.12 ★★★

Show that with multiplicative increase and multiplicative decrease (xi←c xix_i \leftarrow c\,x_i with c>1c > 1, and xi←b xix_i \leftarrow b\,x_i), the ratio x1/x2x_1/x_2 never changes, so two flows never converge to fairness. What about additive increase and additive decrease?

Solution

Solution of Exercise 19.12.

Under MIMD every step multiplies x1x_1 and x2x_2 by the same factor, cc or bb, so x1/x2x_1/x_2 never changes: flows that start unequal stay unequal in the same ratio, for ever. Under additive increase and additive decrease, every step adds the same amount to both, so x1−x2x_1 - x_2 never changes, and again the flows do not converge. AIMD works because one of its two moves, the decrease, shrinks the difference and the other keeps it.

19.7 Problem: Sending the town archive across a bad link

Problem 19.1

Weekend problem — Sending the town archive across a bad link

The town sends its archive, 10 000 packets of 1000 bytes, to the lighthouse over a link of 8 Mbit/s with a round trip of 100 ms that loses 1 packet in 100.

Part I — Stop-and-wait.

  1. How long does one packet take to send, and what is the utilisation of stop-and-wait?
  2. Estimate how long the archive takes with stop-and-wait and no loss.
  3. With 1 % loss and a timeout of 300 ms, how much does the expected time grow?
  4. Why does stop-and-wait need a sequence number at all, and why does one bit suffice?
  5. What goes wrong if the channel can reorder packets?
  6. Why is the timeout chosen longer than the round trip?

Part II — Windows.

  1. What window fills the link?
  2. With 4-bit sequence numbers, what is the largest window for go-back-N, and for selective repeat?
  3. With each protocol and that window, estimate the packets sent per loss.
  4. Using Output 19.4, compare the two protocols at 5 % loss.
  5. Why does TCP number bytes with 32 bits rather than packets with 4?
  6. The lighthouse’s program reads slowly. Which mechanism protects it, and how?

Part III — Congestion.

  1. Starting from one segment, how many round trips does slow start take to reach the window of question 7?
  2. In congestion avoidance with 1 % loss, what average throughput does the law predict, in Mbit/s?
  3. Is the archive transfer limited by the link or by the losses?
  4. What loss rate would let TCP fill the link?
  5. Why does TCP halve its window after a loss rather than reduce it by one segment?
  6. Read in Output 19.10 how close the law is at p=0.01p = 0.01, and why.

Part IV — Two transfers sharing the link.

  1. A second transfer starts on the same link. Using Theorem 19.15, what shares do they converge to?
  2. In Output 19.11, after how many rounds is Jain’s index above 0.99?
  3. Why do the shares keep oscillating although the index reaches 1?
  4. If the second transfer’s round trip were twice as long, what share would it get?
  5. Why would a program that opens ten connections at once get more than its share?
  6. State the result: the 3/(2p)\sqrt{3/(2p)} law, checked by simulation within a few per cent.
Solution

Solution of Problem 19.1.

1. 80008000 bits at 8 Mbit/s: 1 ms. U=1/(100+1)≈1 %U = 1/(100 + 1) \approx 1~\%.

2. 10 000×10110\,000 \times 101 ms ≈1010\approx 1010 s, about 17 minutes.

3. A cycle fails when the packet or its acknowledgement is lost, about 2 % of the time, and then costs a timeout of 300 ms instead of 101 ms. That adds about 0.02×300=60.02 \times 300 = 6 ms per packet on average: some 6 %, a minute more.

4. When an acknowledgement is lost the sender repeats the packet, and the receiver must tell the copy from the next packet. With one packet in flight and no reordering, the packet that arrives is either the one expected or the one just accepted: one bit tells which.

5. A delayed old copy can arrive when the receiver expects the same bit again, two packets later, and be accepted as new.

6. No acknowledgement can arrive before a round trip; a shorter timer would repeat every packet.

7. (RTT+L/R)/(L/R)=101(\mathrm{RTT} + L/R)/(L/R) = 101 packets.

8. Go-back-N: 24−1=152^4 - 1 = 15. Selective repeat: 23=82^3 = 8. Both are far below 101, so the sequence numbers limit the utilisation to about 15 % and 8 %.

9. Go-back-N resends the whole window behind a loss, up to 15 packets; selective repeat resends the lost packet only.

10. For 5 000 packets, go-back-N sent 13 408 and took 76.3 s; selective repeat sent 5 531 and took 36.7 s.

11. A fast link with a long round trip needs millions of bytes in flight, and an old segment can survive for minutes; 32-bit numbers give 4 GiB of space, so that a number does not come round again while an old segment with it may still exist, at ordinary speeds.

12. Flow control: each acknowledgement advertises the free space in the receiver’s buffer, and the sender keeps no more than that in flight.

13. Doubling from 1, the window exceeds 101 after 7 round trips (27=1282^7 = 128).

14. 3/0.02≈12.2\sqrt{3/0.02} \approx 12.2 segments per round trip, 12.2×800012.2 \times 8000 bits per 0.1 s: about 1 Mbit/s.

15. By the losses: 1 Mbit/s against a link of 8.

16. 3/(2p)≥101\sqrt{3/(2p)} \ge 101 gives p≤3/(2×1012)≈1.5×10−4p \le 3/(2 \times 101^2) \approx 1.5 \times 10^{-4}, one loss in about 6800 packets.

17. A queue that overflows must be drained quickly, which only a large cut does; and the multiplicative decrease is what makes the shares converge (Theorem 19.15, Exercise 19.12).

18. 9.3 % below: the window is only about 16 segments, so whole segments, and the round in which the loss falls, weigh in the average; the law assumes a continuous window.

19. Equal shares, half the link each, on average.

20. The index is 0.947 at round 25 and 0.995 at round 50: between the two.

21. Both flows still add one per round and halve together at each loss: their sum oscillates, while their difference has vanished. The index measures equality, not stability.

22. One fifth, by Exercise 19.11.

23. Fairness holds per connection: ten connections against one other get about ten shares in eleven.

24. The 3/(2p)\sqrt{3/(2p)} law, checked by simulation: within 3 % for periodic losses once p≤0.001p \le 0.001 (2.5 % and 1.7 % at p=0.001p = 0.001 and 0.00030.0003), and a few per cent above it with random losses.

本章定义的术语

在术语表中查看全部 1050 个术语