本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 2 · 本科二年级
17The Link Layer
The town’s lighthouse is told by radio when to light its lamp. One evening a burst of noise flips a single bit of the message on its way:
$ python lighthouse.py
sent: LAMP ON AT 20:00 check 788582f7
received: LAMP ON AT 21:00 check 788582f7
recomputed check of what arrived: c039e592
frame dropped
“20:00” became “21:00”: the character 0 is the byte 0x30 and 1 is 0x31, one bit apart. The message still reads well, so no person would notice. The receiver noticed because the sender had added four bytes computed from the message, a check, and the received message no longer matches it. This chapter is about the bottom of the network: how a stream of bits on one wire or one radio channel is cut into frames, how errors are detected, how many machines share one medium, and how a frame finds its way across a local network.
You already know
Book 2: the network is built in layers, each using the one below; a protocol is a set of rules that both sides follow. The physics series: a signal on a wire or in the air weakens with distance and picks up noise. Chapter 16: bytes sent over a socket arrive intact and in order; this chapter and the next two show who makes that true.
17.1 Links and frames
Definition 17.1 (Link, frame)
A link connects machines that can reach each other directly: a cable between two machines, or a radio channel that all of them hear. The link layer carries frames: a frame is a block of bytes with a header (who sends it, to whom, what it carries), a payload, and a check. The link layer hands frames to the layer above; a frame never leaves its link.
The first problem is to find where a frame begins and ends in a stream of bits. A common answer marks the ends with a special byte, the flag. A flag byte inside the payload must then be disguised.
Method 17.2 (Byte stuffing)
Frames begin and end with the flag 0x7e. Inside a frame, the sender replaces each byte 0x7e or 0x7d by the escape 0x7d followed by the byte XOR 0x20. The receiver cuts the stream at the flags, and in each frame replaces 0x7d, by XOR 0x20.
def stuff(payload):
out = bytearray([FLAG])
for b in payload:
if b in (FLAG, ESC):
out += bytes([ESC, b ^ 0x20]) # never a flag inside the frame
else:
out.append(b)
out.append(FLAG)
return bytes(out)
def unstuff(frame):
assert frame[0] == FLAG and frame[-1] == FLAG
out, escaped = bytearray(), False
for b in frame[1:-1]:
if escaped:
out.append(b ^ 0x20)
escaped = False
elif b == ESC:
escaped = True
else:
out.append(b)
return bytes(out)
$ python stuffing.py
payload: 41 7e 42 7d 43
on the wire: 7e 41 7d 5e 42 7d 5d 43 7e 7e 4f 4b 7e
frames found: ['41 7e 42 7d 43', '4f 4b']
After stuffing, 0x7e occurs only at the ends of a frame, so the cut at the flags is exact. XOR with 0x20 is its own inverse, which is why the receiver applies the same operation.
17.2 Detecting errors
Noise flips bits.
Definition 17.3 (Error-detecting code, checksum)
An error-detecting code adds to each block of data a few check bits computed from it; the receiver computes them again from what arrived, and drops the block if they differ. A checksum is a check computed by adding the data as numbers; a parity bit, below, is the smallest check.
No check catches every error: the question is which errors each one is sure to catch.
17.2.1 Parity
Definition 17.4 (Parity bit)
The even parity bit of a block of bits is 1 if the block has an odd number of 1s, and 0 otherwise, so that the block and its parity bit together hold an even number of 1s.
Proposition 17.5 (Parity)
A parity bit detects every error that flips an odd number of bits of the block and its parity bit, and no error that flips an even number.
Proof. Sent, the block and its bit hold an even number of 1s. Each flip changes that number by , so after flips it has changed by modulo 2: it is odd, and the receiver sees the error, exactly when is odd. ∎
$ python parity.py
bytes: 4c 41 4d 50 parity bits: [1, 0, 0, 0]
one flip in byte 2: [1, 0, 1, 0] -> byte 2 fails
two flips in byte 2: [1, 0, 0, 0] -> nothing seen
grid: row 2 and column 3 disagree: flip bit 3 of byte 2
corrected: True
Arranged as a grid, with a parity bit per row (byte) and a parity byte for the columns, parity does more: a single flip makes exactly one row and one column wrong, and their crossing is the bit to flip back. The code corrects the error (Exercise 17.3). The price is one bit in nine, plus a byte per block.
17.2.2 The Internet checksum
The Internet’s own protocols use a cheaper check.
Definition 17.6 (Internet checksum)
The Internet checksum adds the data as 16-bit words, adding each carry out of the top back in at the bottom (the one’s complement sum), and sends the complement of the result. The receiver adds everything, checksum included, and expects ffff.
def ones_sum(data):
if len(data) % 2:
data += b"\0"
total = 0
for i in range(0, len(data), 2):
total += data[i] << 8 | data[i + 1]
total = (total & 0xFFFF) + (total >> 16) # add the carry back at the bottom
return total
def checksum(data):
return ~ones_sum(data) & 0xFFFF
$ python inet_checksum.py
checksum: 360e
receiver's sum with it: ffff
two words swapped: ffff
one bit flipped: 0100
A sum does not depend on the order of its terms, so swapping two words passes unseen. The checksum is fast to compute in software, which is why the Internet layers use it; the links, which see the noise, use a stronger check.
17.2.3 Cyclic redundancy codes
A cyclic redundancy code treats a string of bits as a polynomial whose coefficients are 0 or 1: the bits are . Coefficients are added modulo 2, so adding is XOR, with no carries, and . Polynomials can be multiplied and divided with remainder exactly as with numbers, the subtractions in a long division being XORs.
Definition 17.7 (Cyclic redundancy code)
Let be a polynomial of degree whose constant term is 1, the generator. A message is sent as , where is the remainder of divided by : the message followed by check bits. The receiver accepts a frame if divides it. This is a cyclic redundancy code, or CRC.
Since and , : every frame sent is a multiple of . The long division is mechanical:
$ python long_division.py
11010110110000 message followed by 4 zeros
10011 XOR g
--------------
01001110110000
10011 XOR g
--------------
00000010110000
10011 XOR g
--------------
00000000101000
10011 XOR g
--------------
00000000001110
remainder: 1110; the frame sent: 1101011011 1110
def remainder(message, n, g):
"""Remainder of message(x) * x^r divided by g(x): message has n bits, g degree r."""
r = g.bit_length() - 1
value = message << r
for i in range(n + r - 1, r - 1, -1): # from the top bit down to bit r
if value >> i & 1:
value ^= g << (i - r) # subtract g, written under bit i
return value
If the noise adds an error (a 1 at each flipped bit), the receiver gets , and since divides , it accepts exactly when divides . So the errors a CRC misses are the multiples of its generator, and choosing a CRC is choosing .
Definition 17.8 (Burst error)
A burst of length is an error whose first and last flipped bits are positions apart, counting both; the bits between them may be flipped or not.
Theorem 17.9 (Bursts)
A CRC whose generator has degree and constant term 1 detects every burst of length .
Proof. Such an error is , where has degree and constant term 1. First, if divides for some , then divides : write ; the constant term of is that of , because ’s is 1, and it is 0, because has none; so , and gives . Applying this times, if divided it would divide . But a nonzero multiple of has degree at least , and is nonzero of degree less than . So does not divide . ∎
Proposition 17.10 (Odd numbers of flips)
If divides the generator, the CRC detects every error with an odd number of flipped bits.
The proof is Exercise 17.8; the idea is to evaluate polynomials at . The 16-bit generator
has four terms, so it is divisible by , and both results apply. They can be checked by brute force on a frame of 4 bytes and its 16 check bits:
$ python burst_check.py
frame of 48 bits; burst length, bursts tried, bursts undetected
1 48 0
2 47 0
8 2624 0
15 278528 0
16 540672 0
17 1048576 32
all bursts of 1 to 16 bits: 1114111 tried, 0 undetected
Not one burst of 16 bits or fewer passes. Of the bursts of 17 bits, exactly one pattern per position passes: the generator itself, shifted.
17.2.4 CRC-32 in practice
The 32-bit CRC of Ethernet uses a generator of degree 32 written 0x104c11db7 as a bit vector. Real CRCs add two details to the definition. The hardware sends each byte lowest bit first, so the bits are processed in that order, and the generator appears reversed, as 0xedb88320. The register starts at all ones, so that leading zero bytes
change the check, and the result is complemented. The same CRC-32 protects zip and gzip files and PNG images:
def crc32_bitwise(data):
"""CRC-32 of zlib: bits taken lowest first, so the generator is reversed."""
crc = 0xFFFFFFFF
for byte in data:
crc ^= byte
for _ in range(8):
crc = (crc >> 1) ^ 0xEDB88320 if crc & 1 else crc >> 1
return crc ^ 0xFFFFFFFF
def _step8(b):
for _ in range(8):
b = (b >> 1) ^ 0xEDB88320 if b & 1 else b >> 1
return b
TABLE = [_step8(b) for b in range(256)] # the eight steps of each byte value
def crc32_table(data):
crc = 0xFFFFFFFF
for byte in data:
crc = TABLE[(crc ^ byte) & 0xFF] ^ (crc >> 8)
return crc ^ 0xFFFFFFFF
$ python crc.py
0x04c11db7 reversed: 0xedb88320
input bitwise table zlib
'' 00000000 00000000 00000000
'a' e8b7be43 e8b7be43 e8b7be43
'123456789' cbf43926 cbf43926 cbf43926
'LAMP ON AT 20:00' 788582f7 788582f7 788582f7
'1024 bytes' b70b4c26 b70b4c26 b70b4c26
crc16(LAMP) = 2a56, by division: 2a56
zlib.crc32.The table holds, for each byte value, the effect of eight steps of the bitwise loop; one lookup replaces eight steps. The same table in C gives the same values:
uint32_t crc32(const unsigned char *data, size_t n)
{
uint32_t crc = 0xFFFFFFFFu;
for (size_t i = 0; i < n; i++)
crc = table[(crc ^ data[i]) & 0xFF] ^ (crc >> 8);
return crc ^ 0xFFFFFFFFu;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o crc32 crc32.c -lm && ./crc32
00000000 ""
e8b7be43 "a"
cbf43926 "123456789"
788582f7 "LAMP ON AT 20:00"
17.3 Sharing a medium
On a radio channel, every station hears every other.
Definition 17.11 (Multiple access protocol, collision)
When several stations share one medium and two transmit at once, their signals mix and both frames are lost: a collision. A multiple access protocol (or medium access protocol) is the rule by which each station decides when to transmit.
History
In 1970, Norman Abramson described the ALOHA system, which linked terminals on several Hawaiian islands to one computer over a shared radio channel. Its rule was the simplest possible: send when you have a frame; if no acknowledgement comes, wait a random time and send again.
In slotted ALOHA, time is cut into slots of one frame each, and a station sends only at the start of a slot. A slot is useful when exactly one station sends. Let stations each send in a slot with probability , so that frames are tried per slot on average.
Proposition 17.12 (Slotted ALOHA)
The fraction of useful slots is , which tends to as grows. The maximum of is , at .
Proof. Exactly one station sends with probability : one of the sends, and the others do not. As grows, and . The maximum is Exercise 17.10. ∎
$ python aloha_sim.py
G simulated G e^-G
0.25 0.194 0.195
0.50 0.308 0.303
0.75 0.351 0.354
1.00 0.369 0.368
1.25 0.362 0.358
1.50 0.340 0.335
1.75 0.309 0.304
2.00 0.267 0.271
2.25 0.239 0.237
2.50 0.205 0.205
2.75 0.177 0.176
3.00 0.147 0.149
On a cable, a station can do better: listen first. Carrier sense multiple access with collision detection (CSMA/CD), the rule of the first Ethernets, sends only when the medium is quiet, keeps listening while sending, and stops as soon as it hears a collision. It then waits a random number of slots before trying again, chosen by binary exponential backoff (defined below): after its -th collision on a frame, a station waits a number of slots drawn uniformly from to . Each collision doubles the range, so the stations spread out until one gets through; Exercise 17.9 measures the delay.
Definition 17.13 (ALOHA, CSMA/CD, binary exponential backoff)
In ALOHA a station sends whenever it has a frame and, after a collision, again after a random delay; slotted ALOHA sends only at the start of a time slot. CSMA/CD senses the medium before sending and stops on hearing a collision. Binary exponential backoff draws the delay after the -th collision uniformly among slots.
Carrier sense fails on radio, where a station may not hear every other one. If and are both in range of but not of each other, each senses a quiet medium and sends to , and their frames collide at without either hearing it.
17.4 Ethernet and switches
Definition 17.15 (MAC address, broadcast address)
A MAC address is the 6-byte address of a network interface on its link, written as six hexadecimal bytes, 02:00:00:00:00:01. In the first byte, the lowest bit marks a group address (a frame for several receivers), and the next bit a locally administered one, chosen by its owner rather than by the maker. The address ff:ff:ff:ff:ff:ff, the broadcast address, means every interface on the link.
An Ethernet frame has a 14-byte header (destination, source, type), a payload of 46 to 1500 bytes, shorter payloads being padded, and a 4-byte CRC-32. The type says what the payload is: 0800 an IPv4 packet, 0806 an ARP message (Section 17.5), 86dd an IPv6 packet.
def arp_request(sender_mac, sender_ip, target_ip):
return (
(1).to_bytes(2, "big") # hardware: Ethernet
+ (0x0800).to_bytes(2, "big") # protocol: IPv4
+ bytes([6, 4]) # address lengths
+ (1).to_bytes(2, "big") # operation: request
+ sender_mac + sender_ip + bytes(6) + target_ip # target MAC: unknown
)
def ethernet(dst, src, ethertype, payload):
body = dst + src + ethertype.to_bytes(2, "big") + payload.ljust(46, b"\0")
return body + zlib.crc32(body).to_bytes(4, "little") # the frame check
$ python ethernet_frame.py
0000 ff ff ff ff ff ff 02 00 00 00 00 01 08 06 00 01
0010 08 00 06 04 00 01 02 00 00 00 00 01 0a 00 00 01
0020 00 00 00 00 00 00 0a 00 00 02 00 00 00 00 00 00
0030 00 00 00 00 00 00 00 00 00 00 00 00 e8 6f 4d f8
64 bytes: destination ff:ff:ff:ff:ff:ff, source 02:00:00:00:00:01
type 0806, payload 46 bytes (28 of ARP), check e86f4df8
source's first byte 02: group bit 0, local bit 1
receiver's check: True
Definition 17.16 (Network switch, switch table)
A network switch is a box with many ports, each linked to a machine or another switch, that receives each frame and sends it on only through the ports where its destination may be. Its switch table maps MAC addresses to ports.
Machines on one Ethernet are connected by switches. A switch needs no configuration, because it learns its table.
Method 17.17 (Self-learning switch)
For each frame that arrives on port : record in the table that its source is reachable through . Then, if the destination is in the table on a port other than , send the frame on that port only (forward); if it is in the table on port , drop it (filter: the receiver already heard it); if it is not in the table, or is a broadcast, send it on every port except (flood).
class Switch:
def __init__(self, ports):
self.ports = ports
self.table = {} # MAC address -> port
def receive(self, src, dst, port):
"""Return the ports the frame leaves by."""
self.table[src] = port # learn: src is reachable through port
if dst in self.table:
out = self.table[dst]
return [] if out == port else [out] # filter, or forward
return [p for p in self.ports if p != port] # unknown: flood
$ python switch_sim.py
A -> B flood to [2, 3, 4, 5] table A:1
B -> A forward to [1] table A:1 B:2
C -> A forward to [1] table A:1 B:2 C:3
A -> C forward to [3] table A:1 B:2 C:3
E -> B forward to [2] table A:1 B:2 C:3 E:5
D -> F flood to [1, 2, 3, 5] table A:1 B:2 C:3 D:4 E:5
The first frame from is flooded, since nobody knows yet; ’s answer is forwarded, since is now known. After a few frames the switch floods only for unknown or broadcast destinations. Several switches can be connected in a tree, and learning works through them (Exercise 17.5). A loop, though, would make a flooded frame circle forever, each switch flooding it again. Real networks keep a spare cable for safety anyway; the switches then run the spanning tree protocol, in which they elect one switch as root and switch off the ports that would close a loop, leaving a tree, and switch a spare port on again when a cable fails.
17.5 Address resolution
The layer above addresses machines by IP address (Chapter 18); the link needs a MAC address.
Definition 17.18 (Address resolution)
Address resolution finds the MAC address of the interface that holds a given IP address on the same link; on Ethernet with IPv4 it is done by the address resolution protocol (ARP).
Method 17.19 (ARP)
To send to IP address on its link, a machine looks up in its ARP cache. If the address is missing, it broadcasts a request (operation 1): “who has ? tell me, at this IP and MAC address”. The machine whose address is records the asker in its cache and sends a reply (operation 2) with its MAC address; the asker records it. Entries expire after a while, so that a machine that changed its interface is found again.
The request of Output 17.10 is such a broadcast: hardware type 1 (Ethernet), protocol 0800 (IPv4), address lengths 6 and 4, operation 1, the sender’s two addresses, an unknown target MAC address (zeros) and the target IP address 0a 00 00 02, that is 10.0.0.2.
$ python arp_sim.py
t= 0 A: broadcast 'who has 10.0.0.3? tell 10.0.0.1'
B: not mine, ignored
C: reply '10.0.0.3 is at 02:00:00:00:00:03' to A
A: frame sent to 02:00:00:00:00:03
t= 5 A: 10.0.0.3 is 02:00:00:00:00:03 (cache), frame sent
t= 9 C: 10.0.0.1 is 02:00:00:00:00:01 (cache), frame sent
t= 70 A: broadcast 'who has 10.0.0.3? tell 10.0.0.1'
B: not mine, ignored
C: reply '10.0.0.3 is at 02:00:00:00:00:03' to A
A: frame sent to 02:00:00:00:00:03
ARP trusts every reply. A machine that answers for an address that is not its own receives the frames meant for it; networks defend against this by having switches check replies against the addresses they handed out, and by encrypting what travels above the link, as the Year 3 volume explains.
17.6 Wireless links
A radio link differs from a cable in three ways. The signal weakens quickly with distance and through walls, so its error rate is far higher, and many wireless links resend a frame themselves: the receiver acknowledges each frame, and the sender repeats it when no acknowledgement comes. Second, a station cannot listen while it sends, its own signal drowning every other, so it cannot detect a collision. Third, not every station hears every other: these are the hidden terminals of Definition 17.14, whose frames collide at the receiver. Wireless networks therefore avoid collisions (CSMA/CA): a station waits a random backoff even when the channel is quiet, and may first reserve the channel with a short request that the receiver answers with a short “clear to send”, which every station near the receiver, hidden or not, hears.
17.7 Exercises
Exercise 17.1 ★
Give the even parity bits of the bytes 0x4c, 0x41, 0x4d and 0x50, and check your answer against Output 17.3. Which of the following errors does a parity bit per byte detect: one flip in each of two bytes; three flips in one byte; two flips in one byte?
Solution
Solution of Exercise 17.1.
0x4c has three 1s, so its bit is 1; 0x41 , 0x4d and 0x50 have two, four and two, so their bits are 0: [1, 0, 0, 0], as printed. One flip in each of two bytes is detected, in both bytes; three flips in one byte are detected (an odd number); two flips in one byte are missed (Proposition 17.5).
Exercise 17.2 ★
This checksum forgets to add its carries back. Find the line, and explain why the first input gives the right value and the second does not.
def checksum_nofold(data):
total = 0
for i in range(0, len(data), 2):
total += data[i] << 8 | data[i + 1]
return ~total & 0xFFFF
$ python exo_nofold.py
4c 41 4d 50 right 666e without folding 666e
ff f0 00 20 right ffee without folding ffef
Solution
Solution of Exercise 17.2.
The loop adds the words but never folds total; the final ~total & 0xFFFF then throws the carries away instead of adding them back. For LAMP, : no carry, so both versions agree. For ff f0 00 20, ; the one’s complement sum is , whose complement is ffee, while dropping the carry leaves 0x0010 and ffef. The bug shows only on data whose sum overflows, which is why a test on short text missed it. The fix is the line total = (total & 0xFFFF) + (total >> 16) in the loop.
Exercise 17.3 ★
Write correct(data, rows, col), which takes the data, its row parity bits and its column parity byte, corrects any single flipped bit (in the data or in the parities) and returns None when it cannot.
Solution
Solution of Exercise 17.3.
def correct(data, rows, col):
"""Return the data with at most one flipped data bit corrected, or None."""
bad_rows = [i for i, b in enumerate(data) if parity(b) != rows[i]]
now = 0
for b in data:
now ^= b
diff = now ^ col # columns whose parity is wrong
if not bad_rows and diff == 0:
return bytes(data)
if len(bad_rows) == 1 and diff and diff & (diff - 1) == 0:
out = bytearray(data)
out[bad_rows[0]] ^= diff # the one bit at the crossing
return bytes(out)
if len(bad_rows) == 1 and diff == 0: # the row's own parity bit flipped
return bytes(data)
if not bad_rows and diff & (diff - 1) == 0: # one bit of the parity byte
return bytes(data)
return None # more than one flip: give up
diff has a 1 in each column whose parity is wrong. One wrong row and one wrong column: the data bit at their crossing flipped, and XOR with diff puts it back. One wrong row and no wrong column: the row’s parity bit itself flipped, and the data is intact. No wrong row and one wrong column: a bit of the parity byte flipped. Anything else needs two flips or more. The test flips each of the 32 data bits, each row bit and each column bit, and checks that two flips in different rows give None.
Exercise 17.4 ★
By long division, compute the 3 check bits of the message with . Check that the frame sent is divisible by .
Exercise 17.5 ★★
Two switches are connected by a cable between port 3 of and port 1 of ; hosts and are on ports 1 and 2 of , and on ports 2 and 3 of . Starting from empty tables, the frames , , , , , are sent. Give both tables at the end, and say which frames were flooded by which switch.
Solution
Solution of Exercise 17.5.
$ python exo_switch.py
s1 A:1 B:2 C:3 D:3
s2 A:1 B:1 C:2 D:3
: both switches learn and flood ( on ports 2 and 3, on 2 and 3). : learns on 2 and forwards on 1; learns on 3 and forwards on 1. : nobody knows , so floods on 1 and 2, and on 1 and 2; both learn . , and are forwarded, by alone. Each switch sees every host behind the other switch on the port of the cable: C:3 D:3 in , A:1 B:1 in . Two frames were flooded, by both switches.
Exercise 17.6 ★★
This decoder drops the escape bytes. Explain its output and fix it.
def unstuff_wrong(frame):
return bytes(b for b in frame[1:-1] if b != 0x7D)
$ python exo_unstuff.py
sent: 41 7e 42 7d 43
decoded: 41 5e 42 5d 43
Solution
Solution of Exercise 17.6.
Stuffing sent 7e as 7d 5e and 7d as 7d 5d. The decoder drops each 7d but leaves the byte after it as it is, so 5e and 5d come out instead of 7e and 7d. It must XOR the byte that follows an escape with 0x20, as unstuff does. A second bug waits: a payload byte 7d would be dropped too, if it ever arrived unescaped from a faulty sender; unstuff treats it as an escape, which at least keeps the rule in one place.
Exercise 17.7 ★★
Write a CRC with the generator , most significant bit first, bit by bit and with a table of 256 entries, and test that they agree with each other and with remainder (Listing 17.3).
Solution
Solution of Exercise 17.7.
def crc8_bitwise(data):
crc = 0
for byte in data:
crc ^= byte
for _ in range(8):
crc = ((crc << 1) ^ G) & 0xFF if crc & 0x80 else (crc << 1) & 0xFF
return crc
TABLE = [crc8_bitwise(bytes([b])) for b in range(256)]
def crc8_table(data):
crc = 0
for byte in data:
crc = TABLE[crc ^ byte] # the whole state is one byte
return crc
With an 8-bit register and the message taken most significant bit first, each byte enters the register whole, so TABLE[b] is the CRC of the single byte and the table step needs no shift: the state after a byte is the table entry of the register XOR the byte. The test checks both against remainder(m, 8n, 0x107) on 40 random messages.
Exercise 17.8 ★★
Prove Proposition 17.10. Hint: for a polynomial , is the number of its terms modulo 2.
Solution
Solution of Exercise 17.8.
For a polynomial , is the sum of its coefficients, so it is the number of its terms modulo 2, and , since evaluation respects products. Let be an error that passes the CRC: divides , and divides , so for some . Then : has an even number of terms, that is, an even number of flipped bits. So every error with an odd number of flips is detected.
Exercise 17.9 ★★
Simulate stations that each have one frame to send at time 0 and follow binary exponential backoff on a slotted channel. Measure the mean number of slots until every frame is through and the mean delay of a frame, for . How do they grow with ?
Solution
Solution of Exercise 17.9.
def run(k, rng, cap=10):
"""Slots until every frame is through; and the mean slot at which a frame is."""
wait = [0] * k # slots each station still waits
collisions = [0] * k
done, t, finish = set(), 0, []
while len(done) < k:
ready = [s for s in range(k) if s not in done and wait[s] == 0]
if len(ready) == 1:
done.add(ready[0])
finish.append(t + 1)
elif len(ready) > 1: # a collision: everyone in it backs off
for s in ready:
collisions[s] += 1
wait[s] = rng.randrange(2 ** min(collisions[s], cap)) + 1
for s in range(k):
if s not in done and wait[s] > 0:
wait[s] -= 1
t += 1
return t, sum(finish) / k
$ python backoff_sim.py
k slots to finish mean delay of a frame (slots)
2 5.2 4.5
4 14.1 9.0
8 37.7 18.8
16 99.1 39.6
32 240.9 78.6
A collision costs one slot here, an idealisation of CSMA/CD. The mean delay of a frame grows about linearly, close to slots: the stations spread out until the window is about as large as their number, and then go through roughly one at a time. The time until the last frame grows faster, about 2.5 times per doubling of : the unlucky stations have collided many times and wait in windows much larger than needed. That unfairness is the known weakness of exponential backoff.
Exercise 17.10 ★★★
Prove that is largest at . In pure ALOHA, a station sends whenever it likes; a frame is lost if any other frame starts within one frame time before or after it. With attempts forming a Poisson process of frames per frame time, the throughput is . Find its maximum, and explain the factor 2.
Solution
Solution of Exercise 17.10.
, positive for and negative after: the maximum is at , and it is . In pure ALOHA, a frame sent at time survives if no other frame starts in : one starting just before overlaps its beginning, one starting just after its end. That interval has length 2 frame times, so with Poisson attempts no other start falls in it with probability , and the throughput is . Its derivative is , so the maximum is at and equals : half of slotted ALOHA’s, because slots halve the vulnerable interval.
Exercise 17.11 ★★★
Show that a burst passes a CRC exactly when does, so that checking every burst on a frame reduces to checking every pattern once. For CRC-16, count the patterns of lengths 17 and 18 that pass, compare with Output 17.6, and explain both counts.
Solution
Solution of Exercise 17.11.
The proof of Theorem 17.9 shows that if divides then it divides ; conversely, if divides it divides . So divides exactly when it divides , whatever the position .
$ python burst_fraction.py
length 2: 1 patterns, 0 divisible by g
length 16: 16384 patterns, 0 divisible by g
length 17: 32768 patterns, 1 divisible by g
length 18: 65536 patterns, 1 divisible by g
A burst of length 17 is of degree 16 with constant term 1. If divides it, with of degree 0, so : one pattern in . In Output 17.6, that one pattern sits at each of the positions, hence 32. For length 18, has degree 1 and its constant term must be 1 (as ), so : one pattern in . In general, for bursts longer than the fraction is .
Exercise 17.12 ★★★
On frames of bits, show that exactly of the nonzero error patterns pass a CRC of degree , about one in . With dividing , what fraction of the patterns with an even number of flips pass?
Solution
Solution of Exercise 17.12.
An error pattern on bits is a polynomial of degree less than , and it passes when . Each of degree less than gives such an , and different give different ; conversely the quotient of a multiple of of degree less than has degree less than . There are such , one of them 0, so nonzero patterns pass out of , about . If divides , every multiple of has an even number of terms (Exercise 17.8), and the even patterns, of them (with 0), contain all multiples: a fraction of them pass, twice the average, while no odd pattern passes.
17.8 Problem: The noisy link to the lighthouse
Problem 17.1
Weekend problem — The noisy link to the lighthouse
The harbour sends short frames to the lighthouse over a radio link: a 4-byte command followed by 16 check bits of CRC-16, with . Noise comes in bursts.
Part I — Framing.
- Frames are separated by the flag
0x7e. Stuff the payload7d 7e 00 7e. - What is the longest a stuffed payload of bytes can be, and for which payloads?
- Both flags between two frames are lost in the noise. What does the receiver see, and does the CRC of this problem catch it?
- Why does the CRC cover the payload before stuffing rather than after?
- The lighthouse could instead receive a length byte before each payload. Why is a length byte risky on a noisy link, where a flag is not?
- How many bytes cross the link for the command
LAMP, its check and two flags?
Part II — Detecting errors.
- The last line of the output of
crc.pygives the check bits ofLAMP. Write the 6 bytes sent, and say why the receiver’s CRC of the whole frame is 0. - Why can one parity bit per frame not protect this link against bursts?
- Using Theorem 17.9, which bursts is CRC-16 sure to detect?
- Using Proposition 17.10, which other errors is it sure to detect?
- In Output 17.6, why are there 32 undetected bursts of length 17 and not more?
The listing below draws random error patterns on the 48-bit frame. What count of undetected patterns does Exercise 17.12 predict? Compare with the output.
$ python random_errors.py random error patterns: 16777216 undetected: 256, expected about 256 with an even number of flips: 256; with an odd number: 0Output 17.15. Random error patterns through CRC-16.
Part III — Sharing the radio channel.
- Five buoys report to the harbour on the same channel with slotted ALOHA. Each sends in a slot with probability . What is the probability that a slot is useful?
- Which makes it largest, and what is the largest value? Compare with .
- Why can the buoys not use collision detection?
- The lighthouse and a buoy behind the headland both hear the harbour, but not each other. Name the problem and say what it causes.
- How does a short reservation exchange help, and what does it cost?
- Why does every frame need an acknowledgement on this link, when a cable often needs none?
Part IV — Choosing a CRC.
- Bursts of up to 20 bits are common on this link. Is CRC-16 enough? What does CRC-32 guarantee instead?
- What does CRC-32 cost per frame, in bytes and in computation, against CRC-16?
- A frame carries 4 bytes of data. What fraction of the frame is check bits with each CRC?
- Bursts of 20 bits occur in one frame in a thousand. Estimate how many corrupted frames CRC-16 lets through per million frames.
- Why is a CRC computed by a table in software, or by a shift register in hardware, rather than by the bit-by-bit division of Listing 17.3?
- State the result: no burst of 16 bits or fewer passes CRC-16, and random errors pass at the predicted rate , with the counts of the simulation.
Solution
Solution of Problem 17.1.
1. 7e 7d 5d 7d 5e 00 7d 5e 7e: each 7d and 7e becomes two bytes.
2. bytes (plus the two flags), when every byte of the payload is 7e or 7d.
3. Two frames run together into one, of 12 bytes. The CRC does not catch it: it is accepted every time, not with probability . Each frame , , check included, is a multiple of , and with a register that starts at zero and no final complement the merged frame is , a multiple of too, so its check is 0. Only a length check (6 bytes expected) rejects it, or a CRC whose register starts at all ones, as real links use: then the second frame’s check no longer matches what comes before it. (With one flag lost the frames stay apart, since stuffing.py puts two flags between frames.)
4. The check protects the command, whatever the framing; the receiver removes the stuffing first, then checks. The check bytes are stuffed like the payload, so a check that contains 7e cannot end a frame early.
5. If the length byte is hit, the receiver reads the wrong number of bytes, takes the wrong place for the next length, and every later frame is misread until something resynchronises it. A damaged flag costs only the frames on both sides of it: the next flag is found again.
6. LAMP is 4c 41 4d 50 and its check is 2a 56; none is 7e or 7d, so 6 bytes plus 2 flags: 8 bytes.
7. 4c 41 4d 50 2a 56. The frame is , a multiple of ; the receiver’s CRC is the remainder of by , which is 0.
8. A burst often flips an even number of bits, which one parity bit never sees.
9. Every burst of 16 bits or fewer.
10. Every error with an odd number of flipped bits, since , so divides .
11. A burst of 17 bits passes only if its pattern is itself (Exercise 17.11): one pattern per position, and there are positions.
12. . The simulation counted 256, all with an even number of flips, as Proposition 17.10 demands. That it is exactly 256 is luck: the standard deviation of such a count is about .
13. Exactly one of the five sends: .
14. The derivative is , zero at , where the value is , more than : with few stations the useful fraction at its best is larger, and it decreases to as grows.
15. A radio cannot hear while it sends: its own signal is far stronger than any other at its antenna. And the collision that matters happens at the receiver, which the sender may not hear at all.
16. The hidden terminal problem: each finds the channel quiet, both send, and their frames collide at the harbour, which receives neither; neither sender knows.
17. A sender first sends a short request; the harbour answers with a short “clear to send”, heard by every station near the harbour, the hidden one included, which then keeps quiet for the time announced. Collisions can now hit only the short requests. The cost is two short frames and their delay for every data frame, which pays only for long frames.
18. Noise and collisions lose far more frames on radio than on a cable, and the sender cannot detect a collision; an acknowledgement on the link lets it resend at once, instead of leaving the loss to the much slower layers above.
19. No: bursts of 17 to 20 bits each pass with probability about or (Exercise 17.11). CRC-32 detects every burst of up to 32 bits.
20. Two more bytes per frame. With tables, the computation is one lookup per byte in both cases; the table grows from 512 bytes to 1 KiB.
21. with CRC-16; with CRC-32.
22. A burst of 20 bits passes with probability (its pattern must be with of degree 3 and constant term 1: 4 patterns of ). Per million frames, 1000 have such a burst, and pass: about one bad command in 65 million frames.
23. A table does in one lookup what takes eight shifts and tests; a hardware shift register with a few XOR gates handles each bit as it arrives on the wire, at the speed of the link, with no memory at all.
24. Of 1 114 111 bursts of 1 to 16 bits, none passed CRC-16; of random error patterns, 256 passed, the predicted , all of them with an even number of flips.