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

University Computer Science — Year 2

本书暂未推出简体中文版。现有版本: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:

“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

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.

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)
Listing 17.1. Stuffing and unstuffing code/bachelor-2/17-link-layer/listings/stuffing.py
$ 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']
Output 17.2. Two frames on the wire.

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.

No check catches every error: the question is which errors each one is sure to catch.

17.2.1 Parity

Proof. Sent, the block and its bit hold an even number of 1s. Each flip changes that number by ±1\pm 1, so after kk flips it has changed by kk modulo 2: it is odd, and the receiver sees the error, exactly when kk is odd. ∎

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.

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
Listing 17.2. The one’s complement sum and the checksum code/bachelor-2/17-link-layer/listings/inet_checksum.py
$ python inet_checksum.py
checksum: 360e
receiver's sum with it: ffff
two words swapped:      ffff
one bit flipped:        0100
Output 17.4. It catches a flipped bit, not two swapped words.

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 11011101 are x3+x2+1x^3 + x^2 + 1. Coefficients are added modulo 2, so adding is XOR, with no carries, and xk+xk=0x^k + x^k = 0. Polynomials can be multiplied and divided with remainder exactly as with numbers, the subtractions in a long division being XORs.

Since Mxr=Qg+RM x^r = Q g + R and R+R=0R + R = 0, T=Mxr+R=QgT = M x^r + R = Q g: every frame sent is a multiple of gg. 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
Output 17.5. A CRC by long division, with g(x)=x4+x+1g(x) = x^4 + x + 1: XOR gg under every leading 1.

If the noise adds an error E(x)E(x) (a 1 at each flipped bit), the receiver gets T+ET + E, and since gg divides TT, it accepts exactly when gg divides EE. So the errors a CRC misses are the multiples of its generator, and choosing a CRC is choosing gg.

Proof. Such an error is E(x)=xiB(x)E(x) = x^i B(x), where BB has degree b−1<rb - 1 < r and constant term 1. First, if gg divides xC(x)x C(x) for some CC, then gg divides CC: write xC=gQxC = gQ; the constant term of gQgQ is that of QQ, because gg’s is 1, and it is 0, because xCxC has none; so Q=xQ′Q = xQ', and xC=x gQ′xC = x\,gQ' gives C=gQ′C = gQ'. Applying this ii times, if gg divided EE it would divide BB. But a nonzero multiple of gg has degree at least rr, and BB is nonzero of degree less than rr. So gg does not divide EE. ∎

The proof is Exercise 17.8; the idea is to evaluate polynomials at x=1x = 1. The 16-bit generator

x16+x12+x5+1x^{16} + x^{12} + x^5 + 1 has four terms, so it is divisible by x+1x + 1, and both results apply. They can be checked by brute force on a frame of 4 bytes and its 16 check bits:

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:

$ 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
Output 17.7. Three ways, one value: ours agrees with 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;
}
Listing 17.5. The table-driven CRC-32 in C code/bachelor-2/17-link-layer/listings/crc32.c
$ gcc -std=c17 -O2 -Wall -Wextra -o crc32 crc32.c -lm && ./crc32
00000000  ""
e8b7be43  "a"
cbf43926  "123456789"
788582f7  "LAMP ON AT 20:00"
Output 17.8. The values of the C program.

17.3 Sharing a medium

On a radio channel, every station hears every other.

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 nn stations each send in a slot with probability p=G/np = G/n, so that GG frames are tried per slot on average.

Proof. Exactly one station sends with probability n⋅p(1−p)n−1=G(1−G/n)n−1n \cdot p (1 - p)^{n-1} = G (1 - G/n)^{n-1}: one of the nn sends, and the n−1n - 1 others do not. As nn grows, (1−G/n)n→e−G(1 - G/n)^{n} \to e^{-G} and (1−G/n)−1→1(1 - G/n)^{-1} \to 1. The maximum is Exercise 17.10. ∎

The points of  against G e-G. Too few attempts leave slots empty; too many waste them in collisions. At best, 37 slots in 100 are useful.
The points of Output 17.9 against Ge−GG e^{-G}. Too few attempts leave slots empty; too many waste them in collisions. At best, 37 slots in 100 are useful.

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 cc-th collision on a frame, a station waits a number of slots drawn uniformly from 00 to 2min⁡(c,10)−12^{\min(c,10)} - 1. Each collision doubles the range, so the stations spread out until one gets through; Exercise 17.9 measures the delay.

Carrier sense fails on radio, where a station may not hear every other one. If AA and CC are both in range of BB but not of each other, each senses a quiet medium and sends to BB, and their frames collide at BB without either hearing it.

17.4 Ethernet and switches

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.

An Ethernet frame. The CRC-32 covers the header and the payload; a frame is therefore 64 to 1518 bytes long.
An Ethernet frame. The CRC-32 covers the header and the payload; a frame is therefore 64 to 1518 bytes long.

Machines on one Ethernet are connected by switches. A switch needs no configuration, because it learns its table.

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
Listing 17.7. A self-learning switch code/bachelor-2/17-link-layer/listings/switch_sim.py
$ 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
Output 17.11. Five hosts on ports 1 to 5; the table after each frame.

The first frame from AA is flooded, since nobody knows BB yet; BB’s answer is forwarded, since AA 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.

The plug of an Ethernet cable: eight gold contacts for four twisted pairs of copper wires. Photograph: David Monniaux, CC BY-SA 3.0.
The plug of an Ethernet cable: eight gold contacts for four twisted pairs of copper wires. Photograph: David Monniaux, CC BY-SA 3.0.

17.5 Address resolution

The layer above addresses machines by IP address (Chapter 18); the link needs a MAC address.

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
Output 17.12. Three hosts; cache entries live 60 seconds in this simulation.
An ARP exchange. The request reaches everyone; the reply and the frame reach only their addressee. A second frame to C needs no request until the entry expires.
An ARP exchange. The request reaches everyone; the reply and the frame reach only their addressee. A second frame to C needs no request until the entry expires.

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.

Plugging a cable into a switch. Each port is a link of its own: the switch decides which links a frame crosses.
Plugging a cable into a switch. Each port is a link of its own: the switch decides which links a frame crosses.

17.7 Exercises

17.8 Problem: The noisy link to the lighthouse

本章定义的术语

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