Linux Networking for Robots

A control packet can wait 40 ms for no reason a faster link would fix. Follow one packet from the network card to your code, and learn the knob at every stage.

Learn what Linux does with a packet between the wire and your program, why small control messages stall, and which setting moves each stage.

Pick TCP control channel and watch a 40 ms stall appear. Switch on TCP_NODELAY, then raise the interrupt delay and move the receive queue away from the consumer. Then we build every stage from zero.

You need a rough idea of what a network packet is (a small bundle of bytes with an address on it). We build the rest from zero.

Built from primary sources: the Linux kernel networking documentation (NAPI, scaling, timestamping, AF_XDP), RFC 1122, and Cloudflare’s million packets per second post. The full list is in the Field Guide.

Follow one packet

0 µs

A model, not a measurement. The 40 ms comes from Linux’s minimum delayed-ACK timer, HZ/25 in include/net/tcp.h. Every microsecond figure for the other stages is illustrative, chosen to show the order of magnitude and the direction each knob pushes. Chapters 1 to 7 explain each stage and name the tool that measures yours.

Chapter 0

The 40 ms Stall on the Control Channel

See two helpful TCP rules wait for each other, and remove the wait with one line of code

A laptop sends commands to a robot arm. Each command is small: an 8-byte header that says how long the message is, then a 40-byte body with the joint targets. The link is gigabit Ethernet and almost nothing else uses it. Yet every few commands arrive 40 ms late. The arm stutters.

You try the obvious fix. You buy a 10 gigabit link. Nothing changes. The stall is not about speed. Two rules inside TCP are each waiting for the other one to move first. This chapter takes the two rules apart.

Some words first

A packet is a small bundle of bytes with an address on the front, like a letter in an envelope. TCP is the service that turns many packets into one reliable, ordered stream of bytes. Reliable means that the receiver sends back a short note, an ACK (acknowledgement), for the bytes it got. If the sender hears no ACK, it sends the bytes again.

Your program hands bytes to TCP with a write, a call such as send(). TCP cuts the stream into segments, the pieces that travel in one packet. Every segment wears about 40 bytes of header (20 for IP, 20 for TCP). One byte of data in a 41-byte packet wastes 98% of the wire.

Rule one: Nagle’s algorithm

In 1984 John Nagle saw a network drowning in tiny packets, one per keystroke (RFC 896). His fix was a single unconditional rule. If earlier data still has no ACK, do not send new small data. Wait.

The host requirements standard states it the same way. If there is unacknowledged data, TCP “buffers all user data” until the outstanding data is acknowledged or a full-sized segment can go (RFC 1122, section 4.2.3.4). Waiting lets many small writes join into one bigger packet. That is the Nagle algorithm.

Rule two: delayed ACK

The receiver has its own trick. Sending a bare ACK costs a whole packet, so it waits a little. Maybe it will soon have data of its own, and the ACK can ride on that packet for free. This is the delayed ACK. The standard says the delay must be less than 0.5 seconds, and a stream of full segments should get an ACK at least every second segment (RFC 1122, section 4.2.3.2).

Linux picks short timers. In include/net/tcp.h, TCP_DELACK_MIN is HZ/25 and TCP_DELACK_MAX is HZ/5. HZ counts kernel ticks per second, so HZ/25 is 1/25 of a second, which is 40 ms, and HZ/5 is 200 ms. That is where the number comes from.

How two good rules make a bad one

Follow one command. Your code does two writes in a row: the header, then the body.

  1. The header write finds no unacknowledged data, so TCP sends it at once.
  2. The body write finds that the header has no ACK yet. Nagle holds the body.
  3. The receiver gets the header. It is only half a message, so the application cannot answer. With nothing to send back, delayed ACK holds the ACK for up to 40 ms.
  4. The 40 ms timer fires. The ACK goes out. The sender wakes and releases the body.

Each side waits for the other. Nagle waits for the ACK. The ACK waits for data that Nagle holds back. The timer is the only thing that breaks the tie. Try each switch in the device below, and watch where the red gap appears.

Break the deadlock

Time runs down the page. The left line is the sender, the right line is the receiver. Choose how the code writes, then switch on the sender’s or the receiver’s fix.

Illustrative timing: a 0.1 ms one-way delay on a quiet local link. The 40 ms is Linux’s minimum delayed-ACK timer, HZ/25. The arrows cross at a fixed slope so you can see them; only the vertical gaps between events are to scale.

Worked numbers

Take 0.1 ms one way. The header leaves at 0 and arrives at 0.1 ms. The ACK waits until 40.1 ms and reaches the sender at 40.2 ms. The body leaves then and arrives at 40.3 ms. The command takes 40.3 ms instead of 0.1 ms.

That also caps the rate. One command per 40.3 ms is about 25 commands per second. Each command is 48 bytes plus 80 bytes of header and data, so 128 bytes on the TCP layer. At 25 per second that is 3,200 bytes per second, or 25.6 kbit/s. A gigabit link is then 99.997% idle. A faster link could only make it idler.

Three fixes, in order of preference

Write once. Build the whole message in one buffer, or use writev(), which sends several buffers in one call. The first small segment finds no unacknowledged data and leaves at once. There is no second write to hold. This fix costs nothing.

Turn Nagle off on the sender with TCP_NODELAY. The manual says it makes segments go “as soon as possible, even if there is only a small amount of data.” RFC 1122 requires that an application can do this per connection, and names real-time display updates as a case that needs it. This stops the sender from waiting. It does not stop the receiver from delaying its ACK, which is fine because nobody waits for it now.

Ask the receiver for quick ACKs with TCP_QUICKACK. This works, but the kernel can drop out of quickack mode by itself, so code that depends on it sets the option again after each read. Most robot code prefers NODELAY.

There is a fourth choice. Do not carry control on TCP at all. A UDP message is one packet, with no Nagle and no ACK. You then own loss and order, which Chapter 1 shows can fail when a buffer fills. For the exact C calls, see the Field Guide.

Failure mode: symptom, measurement, fix

Symptom: command latency has two clusters, one near 0 and one near 40 ms. The link is idle. Measurement: run tcpdump -ttt -i eth0 port 5000. The -ttt flag prints the time since the previous packet. You will see the header segment, a 40 ms gap, an ACK, and then the body. Fix: write once, or set TCP_NODELAY, and capture again. The gap is gone.

The road

The stall lives at the top of the stack. Below it, every stage from the wire to your code has a knob like this one. The hero at the top of the page runs them all together.

  1. The receive path: ring, interrupt, NAPI, softirq, socket, and the drops at the end.
  2. Interrupt coalescing: trading microseconds for CPU time.
  3. Queues and cores: RSS, RPS, RFS, XPS and the cross-core wake-up.
  4. Busy polling and timestamps: spending CPU to save time, and telling the truth about time.
  5. Linux networking as a platform skill: routes, tc, namespaces, tunnels.
  6. Wi-Fi power save and bufferbloat: delay that grows in queues.
  7. Kernel bypass: io_uring, AF_XDP, DPDK, RDMA, and what you take on.
  8. Field Guide: numbers, checklist, code, and links onward.

Kernel basics, if you need them, are in Kernel Internals for Platform Engineers. For the full real-time Linux story, see Real-Time Linux. A lesson on rings, queues and drops in general is planned in the same series.

A sender does two small writes. The second is held for 40 ms on an idle gigabit link. What is waiting for what?

Chapter 1

The RX Path: Ring, IRQ, NAPI, Softirq, Socket

Follow one packet through seven stages, and find the two places where Linux throws it away

A lidar on your robot sends UDP packets to a perception program, thousands per second. The program works for an hour. Then it reports a gap in the scan: a few packets never arrived. The cable is fine and the lidar sent them all. Somewhere between the wire and your recvmsg() call, Linux dropped some.

To find where, you must know the road. A packet crosses seven stages. Each stage has an owner, a queue, and a counter that tells you if it lost anything.

Stage by stage

The NIC (network interface card) is the chip that talks to the wire. It does not hand a packet to the CPU directly. At start-up, the driver builds a ring in main memory: a circular list of descriptors, each one a small record that says “write the next packet at this address, this many bytes available”. When a frame arrives, the NIC writes it into memory itself, with no CPU help. This is DMA, direct memory access. Then the NIC marks the descriptor as full.

Now the CPU must find out. The NIC raises an interrupt, a signal that makes a CPU core stop its work and run a handler. A handler must be quick. At a million packets per second you cannot afford a full handler per packet. So the interrupt handler does almost nothing. It tells the kernel “poll this device” and masks the interrupt, so the NIC stays quiet while the real work runs.

The real work is NAPI, the New API. The kernel documentation says a driver calls napi_schedule() from its interrupt handler and keeps interrupts masked while polling runs. NAPI normally runs in softirq context: a deferred task that runs right after the interrupt, on the same core, ahead of ordinary programs. The driver’s poll function gets a budget, the most packets it may take in one go. If work remains it returns exactly the budget and the kernel polls again. When the ring is empty, it unmasks the interrupt.

For each packet, the poll function builds an sk_buff, the kernel’s record of one packet. Then the packet climbs the stack. GRO (generic receive offload) may merge several TCP segments into one big one. Firewall hooks run. The IP layer checks the address. The UDP or TCP layer finds the socket from the ports.

A socket is your program’s end of a connection. It has a receive buffer, a queue of packets waiting to be read. The kernel appends the packet there and wakes any thread that sleeps in recvmsg(). That thread must be scheduled onto a core, and then the kernel copies the bytes into your buffer. The transmit path is the mirror image, passing through a queue called the qdisc on the way out (Chapter 5).

Send a packet down the stack

Press Send a packet and watch it travel. Tap any stage to read what lives there and which counter watches it.

A teaching diagram of the Linux receive path for a typical driver. Real drivers differ in detail, and names such as the drop counters vary by NIC.

Where packets die

Packets can be lost at three places, and each one has its own counter. Knowing which counter moves tells you which stage is too slow.

  1. The ring is full. The NIC has no free descriptor, so it drops the frame. The driver counts it. Run ethtool -S eth0; counter names vary by driver. The post from Cloudflare shows rx_nodesc_drop_cnt on its NIC. ethtool -g eth0 shows the ring size, and ethtool -G changes it.
  2. NAPI cannot keep up. The file /proc/net/softnet_stat has one line per CPU. The second column counts packets dropped from the backlog, and the third counts times the poll ran out of budget.
  3. The socket buffer is full. The kernel got the packet but your program did not read it fast enough. UDP counts this as RcvbufErrors in netstat -su. ss -m shows the buffer for each socket.

The Cloudflare post shows the third case. In one test the kernel delivered only about 440,000 packets per second to its receiver program, and 123.8 thousand packets per second were counted as RcvbufErrors. The kernel received the packets, and the program did not read them fast enough. Both ends of that sentence matter: the program is the slow part, not the network.

A worked overflow

The socket buffer is a queue with a fixed size. You set it with SO_RCVBUF. The manual notes that the kernel doubles the value you give it, to leave room for bookkeeping, and that /proc/sys/net/core/rmem_max caps it. Think of it in packet slots to keep the arithmetic simple.

Say packets arrive at 300,000 per second and your program reads 250,000 per second. The queue grows by 50,000 packets each second. A buffer of 128 slots fills in 128 / 50,000 = 2.56 ms. After that, 50,000 packets per second are lost. A bigger buffer only delays the drops. If the program is slower than the arrival rate, the buffer cannot save you.

Now change the story. The program reads 250,000 per second, faster than the average arrival of 200,000. It should never drop. But the lidar sends in bursts: 2.5 ms of packets at four times the average rate, then 7.5 ms of quiet. During a burst the arrivals are 800,000 per second against 250,000 read, so the queue grows by 550,000 per second. In 2.5 ms that is 1,375 packets. A 128-slot buffer overflows. A 1,408-slot buffer just survives, and the quiet gap drains it. Here a bigger buffer is the right fix. Try both stories in the device below.

Overflow the socket buffer

The purple line is how many packets sit in the buffer over 40 ms. The dashed line is its size. Red marks packets lost. Change the arrival rate, the reader speed and the buffer.

300k/s
250k/s
128

Toy model in packet slots, computed live in 0.02 ms steps. Real buffers count bytes, including per-packet overhead, so a slot here is a simplification. The rates are illustrative.

Failure mode: symptom, measurement, fix

Symptom: gaps in the lidar stream, and no errors in your program. Measurement: read the three counters before and after a run. If RcvbufErrors grew, the buffer overflowed. Compare your read rate to the arrival rate. Fix: if the program is slower on average, make it faster, or pin it to a core and give it a thread of its own. If it is only bursts, raise SO_RCVBUF and, if the kernel caps it, net.core.rmem_max. If the ring counter grew instead, raise the ring with ethtool -G or find why NAPI is slow.

As for time: how long does a packet take to cross all seven stages? On a modern server the kernel UDP path typically costs tens of microseconds. Treat that as an order of magnitude, not a promise, and measure your own board. The hero at the top models it with illustrative numbers.

Chapters 2 to 4 take the stages one at a time. For a general lesson on queues that overflow, see the real-time Linux material in Real-Time Linux, and for timing budgets in a robot, Robot Real-Time Performance.

The UDP counter RcvbufErrors grows while the NIC drop counters stay at zero. Where are packets being lost?

Chapter 2

Interrupt Coalescing: Latency for CPU

Learn why the network card waits before it interrupts, and why waiting hurts a sparse control stream most

You test a new driver release. Two boards bounce a 64-byte UDP message back and forth. Before the update the round trip was steady. After it, most trips are still fast, but one in twenty takes 150 microseconds longer. Nothing in your code changed. The new driver switched on a feature that helps servers and hurts you.

The feature is interrupt coalescing. This chapter shows what it does, what it costs, and why a robot should often turn it down.

Why the card waits

Chapter 1 said that a NIC raises an interrupt when a frame lands in the ring. An interrupt is not free. The core must stop its work, save its state, run the handler, and later return. That cost is the same whether the packet is small or large. It also throws away some of the CPU’s warm cache.

Now count. At 100,000 packets per second, one interrupt per packet is 100,000 interrupts per second. If each one costs 4 microseconds (an illustrative figure), that is 400 milliseconds of every second. The core spends 40% of its time just being interrupted, before it reads a single byte.

So the card is allowed to wait a little. When the first packet arrives it starts a timer. It lets more packets pile into the ring. It raises one interrupt for the whole batch. The kernel’s NAPI poll then drains them all in one pass. Fewer interrupts, less overhead, more CPU left for your program.

The knobs

You read and set them with ethtool. The command ethtool -c eth0 shows them. The command ethtool -C eth0 rx-usecs 50 rx-frames 16 changes them. The kernel’s netlink interface names three of them like this:

The interrupt fires when the timer ends or the packet count is reached, whichever comes first. Details differ between drivers, and some NICs restart the timer on every packet. Read your driver’s notes and test. Not every card supports every parameter either; the kernel only reports the ones the driver declares.

The trade, as arithmetic

Let r be the packet rate and w the wait window, so k = r × w is the number of extra packets that arrive during the wait. Each interrupt then serves about 1 + k packets, up to the frame limit. So the interrupt rate is r / (1 + k).

The latency cost depends on whether anyone else arrives. If a packet is alone in the window, it waits the whole window. If others arrive, the average wait is about half the window. Averaging the two cases gives the curve you will see below. All times here come from a small model, so treat them as the shape of the trade, not as measurements.

Worked example, a busy stream. Take r = 100,000 packets per second and 4 µs per interrupt, plus 0.3 µs per packet to process.

  1. No coalescing: 100,000 interrupts per second × 4 µs = 40% of a core, plus 3% for the packets. Total 43%. Added latency 0.
  2. With w = 50 µs: k = 100,000 × 0.00005 = 5. Interrupts = 100,000 / 6 = 16,667 per second, which is 6.7% of a core, plus 3%. Total 9.7%. Average added latency about 25 µs, worst 50 µs.

That is a good trade for a server. It saves 33 percentage points of a core for 25 microseconds.

Worked example, a control stream. Now take r = 2,000 packets per second, a typical command or sensor rate, with w = 100 µs. Then k = 2,000 × 0.0001 = 0.2. Almost every packet is alone in its window, so it waits nearly the full 100 µs: the average is about 91 µs. The interrupt rate falls only from 2,000 to 1,667 per second. At 4 µs each, you saved 0.13% of a core.

That is the whole lesson in one comparison. Coalescing saves a lot when traffic is heavy. It saves almost nothing when traffic is sparse, and it still charges the full delay. A sparse real-time stream pays the price and gets nothing back.

Trade microseconds for CPU

The warm line is the average added delay; the dashed line is the worst case. The yellow line is the CPU used by interrupts and packets. Pick a traffic rate, then slide the delay.

100 µs
32

Model, not a measurement: 4 µs per interrupt and 0.3 µs per packet are illustrative; real costs depend on the CPU, the driver and the cache. The adaptive rule here (8 µs below 10k/s, 50 µs below 50k/s, 125 µs above) is a stand-in for a driver’s own algorithm. Planning range used in this lesson: adaptive coalescing can add tens to a couple of hundred microseconds; measure your NIC.

Slide the rate to 500,000 per second and the delay to 0. The CPU line passes 100%. The core cannot answer every interrupt and the ring fills. That is the other danger, and it is why the answer is never a blanket “turn it all off”.

Failure mode: symptom, measurement, fix

Symptom: the median round trip is good, but a tail of slow trips appears after a driver or kernel change. Measurement: run ethtool -c eth0 and note rx-usecs and whether adaptive RX is on. Then run a ping-pong test of your own message size and plot the whole distribution, not the average. A fixed step of about the coalescing delay is the sign. Fix: on the interface or queue that carries real-time traffic, set adaptive-rx off rx-usecs 0 rx-frames 1 and accept the extra CPU. Chapter 3 shows how to give the real-time flow its own queue, so the heavy traffic on other queues keeps its batching.

On real hardware

Use two machines with a gigabit or faster NIC, or a Jetson and a laptop. Run ethtool -c on both ends, then a UDP ping-pong at your control size, once with the defaults and once with rx-usecs 0 adaptive-rx off. Compare the 99th percentile, not only the median. Note which settings the driver refuses; that tells you what the card supports.

A 2,000 packet-per-second control link has rx-usecs set to 100. What does coalescing do for it?

Chapter 3

Multi-Queue: RSS, RPS/RFS, XPS and Cross-Core Wake-ups

Place the receive work on the same core as the program that reads it, and see what each wrong placement costs

A perception box has eight CPU threads. The camera feed arrives at 300,000 packets per second. One thread sits at 100% in %soft in mpstat, while the other seven idle. The program that reads the feed runs on a different thread again. Every packet is touched by two cores, and one core is the bottleneck.

This chapter is about where work runs. The packet path of Chapter 1 does not say which core runs each stage. Linux gives you tools to choose.

One queue, one core: the old problem

A simple NIC has one ring. Every interrupt goes to one core, and that core runs the whole NAPI poll. Speed is capped by what one core can do. Modern NICs have many rings, called queues, and one interrupt per queue. The next question is how a packet picks a queue.

RSS: the card picks

Receive Side Scaling (RSS) does it in hardware. The kernel documentation says the NIC applies a filter, usually a Toeplitz hash over the addresses and ports, and the low bits of the hash index an indirection table whose entries hold queue numbers. Every packet of one flow has the same addresses and ports, so it has the same hash and lands in the same queue. A flow is one stream of packets between the same two endpoints. Keeping a flow on one queue keeps its packets in order.

Each queue has its own interrupt. You can see them in /proc/interrupts. You choose which core serves each one by writing a core list into /proc/irq/<N>/smp_affinity_list. The kernel documentation warns that the irqbalance daemon can override manual settings, so stop it if you pin by hand. For low latency, the same document advises as many queues as CPUs, limited to physical cores, since hyperthreads showed no benefit for interrupt handling in its tests.

The hash does not know about your program. Eight queues spread flows evenly, but they do not put a flow near its reader. Worse, a robot often has one important flow. One flow means one hash, so one queue, so one core. The Cloudflare post met this: its NIC hashed UDP on the two IP addresses only and ignored ports, so traffic between one pair of hosts all went to one of 11 queues.

RPS, RFS and XPS: software steering

Receive Packet Steering (RPS) is RSS in software. After the interrupt core picks up a packet, RPS hands it to another core’s backlog queue. You turn it on with a CPU bitmap in /sys/class/net/<dev>/queues/rx-<n>/rps_cpus. The default is zero, which means off. The documentation notes the catch: RPS adds inter-processor interrupts (IPIs), signals sent from one core to wake another.

Receive Flow Steering (RFS) is smarter. Its stated goal is to raise the data cache hit rate by steering a flow to the CPU where the consuming thread runs. The kernel records, in a table, which CPU last read each flow. You size the table with /proc/sys/net/core/rps_sock_flow_entries; the document cites 65,536 as working well on a moderately loaded server. Accelerated RFS pushes that choice into the NIC itself, so the hardware sends the flow straight to a queue whose interrupt is near the reader. It needs a kernel built with CONFIG_RFS_ACCEL, driver support, and ntuple filters on.

Transmit Packet Steering (XPS) is the same idea for sending. A map in /sys/class/net/<dev>/queues/tx-<n>/xps_cpus picks the transmit queue by the sending CPU, which lowers lock contention and the cache misses on transmit completion.

Why the wrong core costs time

Suppose the interrupt and softirq run on core 0 and your thread sleeps on core 5. When the packet joins the socket buffer, the kernel must wake the thread on core 5. If core 5 is idle, it needs an IPI, then it must leave its idle state. And the packet data, the sk_buff and the socket are in core 0’s cache, not core 5’s. Core 5 must fetch them across the chip, or across the link between two CPU sockets. That is the cross-core wake-up.

Cloudflare measured the cost on one 2015 server, receiving UDP with a simple program on a single core. The rate that core could take depended only on where the receiver ran compared to the queue’s interrupt:

Receiver placementPackets per secondTime per packet
Same CPU as the receive queueup to about 430,0002.3 µs
Same NUMA node, other coreabout 360,0002.8 µs
Other NUMA nodeabout 330,0003.0 µs
Hyperthread sibling of the queue’s CPUabout 200,0005.0 µs

The time per packet is 1 divided by the rate: 1 / 430,000 s is 2.3 µs. A packet on the wrong core costs about 0.5 µs more, and on a hyperthread sibling, which shares the core’s execution units with the interrupt work, it costs 2.7 µs more. The post also saw a four-fold slowdown in one test across NUMA nodes. It concluded that both the receive queues and the receiver processes belong on a single NUMA node. A NUMA node is a group of cores that share one bank of memory; reaching the other node’s memory is slower.

Place the queue and the reader

Each box is one CPU thread. Two boxes joined together are the two hyperthreads of one core; two cores make a NUMA node. Choose where the queue’s interrupt runs and where your program runs.

0
5

The four rates are Cloudflare’s, measured on one 2015 server and described in “How to receive a million packets per second”. Your hardware will differ in the numbers and agree in the order. The layout here (two nodes, two cores each, two hyperthreads each) is a teaching layout, not your machine; read yours with lscpu -e.

Fix: give the real-time flow its own queue and its own core

The recipe has four parts. First, give the NIC enough queues: ethtool -L eth0 combined 4. Second, steer the real-time flow, and only that flow, to one queue with an ntuple rule: ethtool -N eth0 flow-type udp4 dst-port 14550 action 3 (port 14550 is an example). Third, write the core list for that queue’s interrupt, for example echo 5 > /proc/irq/<N>/smp_affinity_list. Fourth, pin your program to the same core, or to its sibling in the same node, with taskset -c 5 or your scheduler’s affinity call. The bulk traffic keeps the other queues.

Symptom: one core is busy in softirq, and jitter climbs when the camera is active. Measurement: mpstat -P ALL 1, per-queue counters from ethtool -S, and /proc/interrupts to see which core serves which queue. Use perf sched timehist to see the delay between a thread becoming runnable and actually running. Fix: the recipe above, then measure again.

On real hardware

On a Jetson or any multi-core Linux board, run cat /proc/interrupts | grep eth to see queue interrupts, then send a UDP stream and watch mpstat -P ALL 1. Move the receiver with taskset and note how the packets per second change. For the kernel side of scheduling and interrupts, see Kernel Internals for Platform Engineers.

The NIC’s queue interrupt runs on CPU 0 and your program runs on CPU 5 in the other NUMA node. What is the most direct improvement?

Chapter 4

Busy Polling and Timestamps

Spend CPU to cut microseconds, then learn where on the path a timestamp is honest

A camera and a motion sensor both send data to a Linux board. A filter must fuse them, and it needs to know when each reading was taken. The sensor packets arrive every 500 microseconds. Your code reads each packet and calls clock_gettime(). The fused track is a little off, and it gets worse when the CPU is busy. The time you stamped is not the time the data arrived.

This chapter has two halves. Busy polling is about getting the packet sooner. Timestamping is about knowing when it really came.

Busy polling: do not sleep, ask

Normally your thread sleeps in recvmsg() until the packet is ready. Waking it takes a chain of events: interrupt, softirq, socket queue, scheduler wake-up. Each link adds time (Chapter 1).

With busy polling the thread does not sleep. It spins in a loop and asks the NIC’s queue directly, from its own core, whether a packet has landed. The kernel documentation describes it as processing packets “before the interrupt fires”. The wake-up chain mostly vanishes. The packet path runs on your core, so even the cross-core hand-off of Chapter 3 goes away.

The price is plain: a core that spins is a core that is 100% busy while it waits. You buy microseconds with CPU time.

You turn it on in three ways. The socket option SO_BUSY_POLL sets, in the manual’s words, the approximate time in microseconds to busy poll on a blocking receive when there is no data. The sysctls net.core.busy_read (for blocking reads) and net.core.busy_poll (for poll() and select()) set a default for every socket. Both default to 0, which is off. The kernel must be built with CONFIG_NET_RX_BUSY_POLL, and the NIC driver must support it. Raising the value on one socket needs the CAP_NET_ADMIN privilege. A newer option, SO_PREFER_BUSY_POLL, lets the application promise to poll regularly so the driver can keep its interrupts masked.

When spinning pays, and when it only burns power

Spinning is a bet that the packet comes soon. The spin lasts s microseconds. If the packet arrives inside that window, your thread catches it at once. If it does not, the spin ends, the thread goes to sleep, and the CPU time was wasted.

Worked example. Packets come every 500 µs (2,000 per second). Suppose a wake-up costs 12 µs more than a polled receive (an illustrative figure).

  1. Spin 50 µs: the next packet is 500 µs away. Each wait you spin 50 µs, find nothing, and sleep. You burn 10% of a core (50 / 500) and save 0 µs.
  2. Spin 500 µs: you always catch the packet. Latency drops by 12 µs, and you burn 100% of the core.

There is no middle road for regular traffic. A short spin is the worst of both. For busy-polling to help, the spin must cover the typical gap between packets, and you must be willing to give that core away. Try it below.

Spin or sleep

The bars compare one packet’s receive delay with a sleeping thread and with the spin you set, and the CPU the spin burns. Pick how often packets arrive, then set SO_BUSY_POLL.

50 µs

Model: a sleeping receive costs 3 µs plus a 12 µs wake-up chain; a spinning receive catches the packet in 3 µs if it arrives inside the spin. All figures are illustrative, packets are evenly spaced, and a real system adds jitter. Measure with your own traffic.

Timestamps: which clock, taken where

A timestamp is a number, but also a claim: “this happened at this moment”. The claim is only true for the place where the clock was read. If you read it in your program after recvmsg() returns, you have added every wait of Chapters 1 to 3. The wait can change from packet to packet. That is jitter hidden inside your data.

The socket option SO_TIMESTAMPING asks the kernel to stamp packets earlier. The kernel documentation lists the points:

A hardware stamp comes from the NIC’s own clock, the PHC (PTP hardware clock). It is a separate clock from the system clock, and you keep the two in step with PTP tools. Red Hat’s documentation says PTP with hardware support can reach sub-microsecond accuracy. Software timestamps use the system clock and carry whatever delay the kernel added; that is commonly microseconds to tens of microseconds. How to keep clocks in step is its own subject: see Time and Sync. Here we only ask where the stamp is taken. The command ethtool -T eth0 lists what your NIC can do.

Pick where to stamp

The packet reaches the wire at time zero. Each mark is a place a clock can be read. Choose one, and see how late its stamp is. The interrupt delay moves the later marks.

50 µs

Illustrative delays: a hardware stamp is taken within about 0.05 µs of the wire; the kernel stamp comes after the interrupt delay plus 3 µs of interrupt and 5 µs of NAPI; the stamp in your program adds a 10 µs socket queue and wake-up and a 6 µs copy. The robot speed of 2 m/s is an example.

Failure mode: symptom, measurement, fix

Symptom: fused data is off by an amount that changes with CPU load. Or a packet capture on the sender says a message left at one time, while the receiver says it came much later, and the gap does not match the cable. Measurement: a capture on the sender’s own kernel shows when the kernel handed the packet to the driver. It does not show the wire. The packet may still wait in the NIC. Fix: use hardware timestamps on both ends, enabled through SO_TIMESTAMPING with the RAW_HARDWARE flag so the NIC’s stamps are reported, or capture on a mirror port of the switch, which sees the real wire.

On real hardware

On an Intel or Realtek NIC board, run ethtool -T eth0 and note whether hardware RX stamps are listed. Then send a packet every 500 µs, set SO_BUSY_POLL to 0, then 600, and measure the receive delay and the CPU of the reading core with top. Compare against your table of expectations.

Packets arrive every 500 µs. You set SO_BUSY_POLL to 50 µs. What happens?

Chapter 5

Linux Networking as a Platform Skill: Routing, tc, Namespaces, VPN

Learn the six tools that shape how traffic leaves a robot, and use one of them to protect a control link from a log upload

A field robot has one network link. Over it go three things: 200 kbit/s of arm commands, 6 Mbit/s of camera video, and logs. An operator starts a log upload. Within seconds the arm commands lag by 100 milliseconds and the arm wobbles. The upload and the commands share one queue, and the upload filled it.

Chapters 0 to 4 were about receiving. A robot also sends, and it sits in a network that has more than one path, one firewall, and sometimes a tunnel. This chapter lists the tools Linux gives you to manage all of that, then works one of them in detail.

The six tools, in plain words

netlink and iproute2. Linux has one channel, called netlink, through which programs configure the network stack. The ip command from the iproute2 package speaks it. ip addr shows addresses, ip route shows routes, and ip monitor prints changes as they happen. Your robot software can speak netlink too, for example to notice that Wi-Fi dropped.

Routes and tables. A route says “to reach this address range, send packets out of that interface, to that next hop.” A robot with Wi-Fi and a cellular modem has two paths to the internet. Linux can keep several routing tables, and ip rule picks a table from the packet’s source or mark. That is policy routing, the way to say “telemetry goes over cellular, video over Wi-Fi.”

Firewall. nftables (the newer tool) and iptables (the older one) filter and rewrite packets inside the stack, at the hooks seen in Chapter 1. A robot should accept only what it needs: one port for control, one for video.

Namespaces. A network namespace is a private copy of the network stack: its own interfaces, routes, firewall rules and sockets. ip netns add robot creates one. A veth pair, made with ip link add veth0 type veth peer name veth1, is a virtual cable between two namespaces. You can test a robot’s network behaviour on a laptop, with no hardware, and containers rely on the same feature.

TUN/TAP and VLANs. A TUN interface looks like a network card to the kernel, but a program holds the other end. The program reads and writes whole IP packets. A TAP interface does the same with Ethernet frames. VPNs and simulators use them. A VLAN puts a tag in each Ethernet frame (IEEE 802.1Q), so one cable carries several separate networks, for example one for control and one for guests. The tag also holds a 3-bit priority field.

Tunnels and VPNs. WireGuard builds an encrypted tunnel with very little set-up. The quick start is two steps: create an interface with ip link add dev wg0 type wireguard, then configure it with wg set wg0 listen-port 51820 private-key ... peer ... allowed-ips ... endpoint .... The robot can then reach the operator’s network as if both were on one cable.

Queueing: the tool for our stall

Every outgoing packet passes through a queue before it reaches the NIC. The kernel calls the queue a qdisc, a queueing discipline. It decides which packet leaves next. A qdisc is the transmit mirror of the receive buffer in Chapter 1. Look at yours with tc qdisc show. Many distributions set fq_codel as the default (Chapter 6 explains why); check yours.

The tc tool (traffic control) changes it. One simple qdisc is prio. The manual says it creates a fixed set of bands, three by default, and that “band 0 is dequeued first”: the scheduler empties band 0 before it looks at band 1, and band 1 before band 2. A packet picks its band from its priority (the SO_PRIORITY socket option or the TOS bits through the priomap) or from a tc filter rule that matches its port. The manual adds a warning: heavy traffic in the low bands can starve the higher numbers, so a shaper may be needed.

Worked numbers

Take a 10 Mbit/s link. One full-size packet is 1,500 bytes, which is 12,000 bits, and it takes 12,000 / 10,000,000 = 1.2 ms to send.

  1. One shared queue. The upload offers 6 Mbit/s and the video 6 Mbit/s: 12.2 Mbit/s with commands, more than the link. The queue fills to its limit. At 100 packets, that is 100 × 12,000 = 1,200,000 bits, which takes 120 ms to drain. A command waits behind all of it: 120 ms.
  2. prio, commands in band 0. The command waits only for the packet being sent right now, at most 1.2 ms. The video takes band 1 and the upload gets what is left: 10 − 0.2 − 6 = 3.8 Mbit/s.

One rule changed the command delay by a factor of 100. No bandwidth was added. The queue only changed who goes first.

Build the qdisc

The link is shared by commands (0.2 Mbit/s), video (6) and a log upload (6). Choose how the queue is built. Then change the link speed and see who gets what.

10 Mbit/s

Fluid model: 1,500-byte packets, a 100-packet shared queue, strict priority for the prio set-ups. The ports (14550, 5600, 9000) are examples. A prio qdisc only helps if the queue builds in your own qdisc; if the real bottleneck is a modem past your NIC, shape to just below its rate first, the topic of Teleop Transport.

Failure mode: symptom, measurement, fix

Symptom: control delay grows when bulk traffic starts, and shrinks when it stops. Measurement: run a steady ping or a small UDP ping-pong to the robot while the upload runs, and watch the round-trip time climb. tc -s qdisc show dev eth0 shows the backlog in packets and bytes, and the drops. Fix: classify the control traffic into the top band, and keep it small and rare so it cannot starve the rest. Test the band order with the same ping, and keep a rule for the case where the control band itself misbehaves.

On real hardware

On any Linux board with a spare Ethernet port, make a 10 Mbit/s bottleneck with ethtool -s eth0 speed 10 duplex full autoneg off (if the NIC allows it), start iperf3 in one terminal and a ping in another, and apply the three set-ups in turn. This shows the same bars as the device. Embedded Linux background is in Embedded Linux.

A 10 Mbit/s link is shared by commands and a bulk upload in one queue of 100 packets. Which change gives the commands the smallest delay?

Chapter 6

Wi-Fi Power Save and Bufferbloat

See why a link can feel fast when idle and slow under load, and which two settings fix most of it

An operator drives a robot over Wi-Fi. Idle, the ping to the robot is 20 ms and the video is smooth. The operator starts a map download. The ping jumps to half a second, the joystick feels like it is wired to molasses, and the download itself finishes just fine. Throughput is perfect. Delay is not.

A second problem hides in the same radio. Before the download starts, a few pings arrive 60 to 100 ms late, in a regular rhythm, even though nothing else is on the link. These are two different causes. This chapter takes them one at a time.

Cause one: the radio naps

A Wi-Fi client saves battery by sleeping between moments of traffic. The access point (AP) keeps packets for a sleeping client, and tells it about them in a regular beacon, a short broadcast message. The Linux wireless documentation gives the standard beacon interval as 100 TU, where one time unit (TU) is 1,024 microseconds. That is 102.4 ms.

So a packet that reaches the AP while your robot sleeps may wait until the next beacon, up to 102.4 ms. The delay looks like a spike that repeats about every 100 ms. The exact pattern depends on the AP’s settings (its DTIM period, the number of beacons between special broadcast beacons) and on the driver. Treat 102.4 ms as the upper scale, and measure.

Check and change it with iw dev wlan0 get power_save and iw dev wlan0 set power_save off. NetworkManager can switch it back on at each reconnect, so make the change in its configuration for a permanent fix. A robot that is plugged in should not nap.

Cause two: the line that never empties

Every router and radio has a buffer, a waiting line for packets that arrive faster than the link can send. A queue is that line. Time in the queue is delay: with q packets waiting and the link sending R packets per millisecond, a new packet waits q / R ms.

TCP is greedy. It keeps raising its sending window until a packet is dropped, because a drop is its only signal that the link is full. With a small buffer, the drop comes quickly. With a huge buffer, the drop comes late, after the line is very long. The queue then stays full for as long as the download lasts. This is bufferbloat: too much buffer, which hides congestion and adds delay without adding speed.

Worked numbers. Take a 20 Mbit/s link and 1,500-byte packets of 12,000 bits.

  1. The link sends 20,000,000 / 12,000 = 1,667 packets per second, which is 1.667 per millisecond.
  2. With a buffer of 800 packets, a full queue means 800 / 1.667 = 480 ms of waiting.
  3. Add the 20 ms base round trip: the ping under load reads about 500 ms, up from 20.
  4. The ideal window is the bandwidth-delay product, the packets in flight on an empty line: 1.667 × 20 ms = 33 packets. The other 800 are only waiting.

A buffer of 800 packets bought no speed. It cost 480 ms of delay.

Smart queues

CoDel (controlled delay) is a queue rule that watches the time packets wait, not the length. If the waiting time stays above a target for a whole interval, it drops a packet, then drops more often until the delay falls. In the Linux kernel source the defaults are a 5 ms target and a 100 ms interval; the fq_codel manual shows the same. The sender then sees an early drop and backs off long before the line is long.

fq_codel adds one more idea: it splits traffic into many flows (1,024 by default) and serves them in turn. A thin flow, like your joystick commands, does not wait behind a fat download. CAKE is a newer rule that bundles shaping and flow fairness. Switch to it with tc qdisc replace dev wlan0 root fq_codel, or cake bandwidth 20mbit on a link where you know the rate.

ECN (explicit congestion notification) lets the queue mark a packet instead of dropping it. The receiver echoes the mark and the sender slows down, with no lost packet to resend. L4S (RFC 9330) goes further. Its stated aim is low queuing latency, low congestion loss and scalable throughput, using a modified ECN signal and sender algorithms that react in small steps.

Fill the buffer

A download starts at 5 seconds. The line is the ping to the robot. Choose a queue rule, then change the buffer size, and turn Wi-Fi power save on to see the idle spikes.

800
20 Mbit/s

A fluid model with one greedy sender: the window grows by 0.6 packets per millisecond and halves on a drop or mark; CoDel uses a 5 ms target and a 100 ms interval with drops spaced at interval / √count. The power-save spikes use the 102.4 ms beacon interval as the largest wait and apply only before the download, while the radio is idle. fq_codel is drawn as a thin probe that skips the bulk queue. Real behaviour varies by driver and access point.

Failure mode: symptom, measurement, fix

Symptom: round-trip time that is fine idle and several times worse under load, or regular spikes when idle. Measurement: run a ping with a short gap, for example ping -i 0.2, and look at the whole histogram. Run it again while a bulk transfer is active. The tool flent rrul (realtime response under load) automates the test. Check iw dev wlan0 get power_save. Fix: power save off on powered robots; fq_codel or CAKE on the bottleneck. If the bottleneck is a modem you cannot change, shape your outgoing traffic to just under its rate so that the queue forms in your own smart qdisc.

On real hardware

Use two machines, one on Wi-Fi. Run ping -i 0.2 to the robot for a minute idle, once with power save on and once off. Then start iperf3 and ping again. Plot both histograms. For the wider view of distributed delay and timing, read Failure and Time and Distributed Trouble.

A 20 Mbit/s link with an 800-packet FIFO buffer shows 500 ms pings during a download. What is the main cause?

Chapter 7

Kernel Bypass: io_uring, AF_XDP, DPDK, RDMA, and the Price

Climb the ladder of ways to skip the kernel, see what each rung removes, and list what you must then do yourself

You have tuned everything. Coalescing is off, the queue sits on the right core, busy polling is on. The packet still spends about 20 microseconds in the kernel, and your loop needs 5. Someone says: skip the kernel. This is real, and some systems do it. This chapter shows what it buys, in order of cost, and what you pay.

The short answer for most robots is that you will not need it. Linux networking, done right, meets a control loop of hundreds of microseconds. Bypass matters when the budget is a few microseconds, such as high-rate sensor capture or packet processing. You should still know the ladder, so you can tell when a claim about it is reasonable.

The ladder, rung by rung

Rung 0, ordinary sockets. Everything in Chapters 1 to 4. The kernel does ARP, IP, UDP and TCP for you, and every copy and wake-up is its cost to pay.

Rung 1, io_uring. io_uring is a Linux interface where you and the kernel share two rings in memory: a submission ring for requests and a completion ring for results. You queue many operations and make one system call, or none. It does not skip the network stack, but it removes per-call overhead and, in newer kernels, copies. The Linux 6.0 release notes list “networking zerocopy send”. Zero-copy receive (IORING_OP_RECV_ZC) was merged for Linux 6.15. It needs help from the NIC: header/data split (ethtool -G eth0 tcp-data-split on), flow steering that sends only your flow to a chosen queue, RSS rules that keep other traffic off that queue, and at least two queues. The kernel does not configure the NIC for you, which means that the set-up is your job.

Rung 2 and 3, AF_XDP. XDP runs a small program in the driver, on the packet, before the normal stack sees it. An AF_XDP socket lets that program hand the raw frame to your process through shared memory. The kernel documentation describes the pieces: a UMEM, a block of memory split into equal frames, and four rings, fill and completion for giving and getting back frames, and RX and TX for packet descriptors. Each ring has a single producer and a single consumer, so no locks are needed.

It runs in two modes. In copy mode the data is still copied into your memory. In zero-copy mode the NIC writes the frame straight into your UMEM. You choose with bind flags. With no flag, the kernel tries zero-copy and quietly falls back to copy. With XDP_ZEROCOPY, the bind fails if zero-copy is not available. With XDP_COPY it forces copy mode. You can read the result with the XDP_OPTIONS socket option and look for XDP_OPTIONS_ZEROCOPY. The documentation also recommends the XDP_USE_NEED_WAKEUP flag, which saves system calls.

Rung 4, DPDK. The Data Plane Development Kit takes the NIC away from the kernel and drives it from your process. Its poll mode drivers are, in its programmer’s guide, “designed to work without asynchronous, interrupt-based signaling mechanisms.” Your cores spin on the rings, as in busy polling, but with no kernel at all. No interrupt, no softirq, no socket. It is also a full stack of its own: memory pools, packet buffers, and core assignment.

Rung 5, RDMA. Remote direct memory access lets one machine read or write another’s memory through the NIC, with the CPU out of the data path. Compared with sockets, it offers lower latency, lower CPU load and higher bandwidth. Some RoCE (RDMA over Ethernet) adapters list a latency as low as 1.3 microseconds. It needs RDMA-capable NICs and a fabric configured for it.

What each rung removes, and what you then own

Every stage you skip is a stage you must write, test and keep secure. On AF_XDP or DPDK, the kernel no longer answers ARP requests for you. It no longer builds IP headers, checks UDP checksums, joins fragments, applies firewall rules, or lets tcpdump see the traffic in the usual way. Your program does. You also give up isolation between processes that the kernel enforced. A bug in your parser is now a bug in a trusted component.

Climb the ladder

Each bar is one way to receive a packet, split into the stages that remain. Choose a rung and read what you now own. Turn the driver switch off to see AF_XDP fall back to copy mode.

Illustrative stage costs in microseconds, taken from this lesson’s hero model and changed only where a rung removes a stage. RDMA is drawn at 1.5 µs, close to the 1.3 µs best-case figure published for some RoCE adapters. Real numbers depend on the NIC, the kernel and the message size; the order of the ladder is the point.

Failure mode: symptom, measurement, fix

Symptom: you moved to AF_XDP and latency barely improved. Measurement: read the socket’s options for XDP_OPTIONS_ZEROCOPY. If it is not set, the driver gave you copy mode, and part of the gain is gone. Fix: bind with XDP_ZEROCOPY so a missing driver feature becomes an error, not a silent fall-back, and pick a NIC and driver that support it. Then re-measure, since the gain you expected only exists where the whole path is zero-copy.

On real hardware

Try AF_XDP on a Linux machine with an XDP-capable driver. The xdpsock sample in the kernel tree has flags for copy and zero-copy modes. Run both and compare the packets per second and the CPU. If zero-copy fails to bind, you have just read your driver’s support. See the Field Guide for the checklist.

You bind an AF_XDP socket with no copy or zero-copy flag, and the driver does not support zero-copy. What happens, and how do you avoid being surprised?

Chapter 8

Field Guide

Keep the numbers, the checklist and the core code for tuning a real-time network path

A packet crosses a ring, an interrupt, a poll, a protocol layer, a socket buffer and a wake-up before your code sees it. Each stage has a wait, a queue, a counter and a knob. The 40 ms stall in Chapter 0 was the loudest of these, and one line removed it. The other stages cost microseconds, and they add up when the budget is tight.

The numbers and terms

Some figures come from a source we opened. Others are illustrative orders of magnitude from this lesson’s models. The last column says which.

WhatValueWhere it comes from
Delayed-ACK timer, Linux minimum and maximum40 ms (HZ/25) and 200 ms (HZ/5)include/net/tcp.h: TCP_DELACK_MIN, TCP_DELACK_MAX
Delayed ACK in the standardunder 0.5 s; ACK every 2nd full segmentRFC 1122, section 4.2.3.2
Nagle rulehold small data while earlier data is unacknowledgedRFC 896; RFC 1122, section 4.2.3.4
Kernel receive path for one UDP packettens of microsecondsOrder of magnitude, illustrative; measure your board
Adaptive interrupt coalescingtens to about 200 µs addedPlanning range, illustrative; read with ethtool -c
RSS indirection table sizeat least 4 times the queue count (about 16% imbalance)Kernel “Scaling in the Networking Stack”
One core receiving UDP, by placement430k, 360k, 330k, 200k packets per secondCloudflare, 2015 server: same CPU, same node, other node, hyperthread sibling
Busy polling defaultsbusy_read and busy_poll are 0 (off)Kernel sysctl notes; socket(7)
Hardware PTP timestampssub-microsecond accuracyRed Hat PTP documentation
Wi-Fi beacon interval100 TU = 102.4 msLinux wireless power-save documentation
CoDel defaults; fq_codel flows5 ms target, 100 ms interval; 1,024 flowsKernel codel_params_init; tc-fq_codel(8)
prio qdisc3 bands by default; band 0 firsttc-prio(8)
io_uring zero-copysend from Linux 6.0; receive from 6.15Linux 6.0 release notes; the 6.15 io_uring pull request
AF_XDP bind flagsXDP_COPY, XDP_ZEROCOPY, none (try zero-copy)Kernel AF_XDP documentation
Best-case RoCE adapter latencyas low as 1.3 µsRoCE article (vendor-level figure; a best case)

The checklist, in packet order

Tick what you have done on a real flow. The order follows the path from the application back to the wire.

Tune a real-time flow

Tick each item you have checked or done. The read-out names the next one.

A teaching checklist, not a certification. Each item matches a chapter, and each has a counter or tool that shows whether it worked. Kernel bypass (Chapter 7) is deliberately not on the list: reach for it only when the numbers say you must.

The core as code

This C opens a control socket without Nagle in the right priority band, and a UDP socket with a sized buffer, a spin, and hardware timestamps. Priority 6 maps to band 0 in the default priomap; values above 6 need the CAP_NET_ADMIN privilege.

c#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <linux/net_tstamp.h>
#include <linux/errqueue.h>

/* TCP control channel: no Nagle wait, top transmit band. */
int open_control(void) {
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    int one = 1, prio = 6;
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one);   /* Chapter 0 */
    setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &prio, sizeof prio);   /* priomap: 6 -> band 0 (Chapter 5) */
    return fd;
}

/* UDP sensor feed: big buffer, short spin, hardware RX stamps. */
int open_feed(void) {
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    int rcvbuf = 4 << 20;                                     /* the kernel doubles it; capped by rmem_max (Chapter 1) */
    int spin_us = 500;                                       /* must cover the packet gap (Chapter 4) */
    int flags = SOF_TIMESTAMPING_RX_HARDWARE | SOF_TIMESTAMPING_RAW_HARDWARE;
    setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof rcvbuf);
    setsockopt(fd, SOL_SOCKET, SO_BUSY_POLL, &spin_us, sizeof spin_us);
    setsockopt(fd, SOL_SOCKET, SO_TIMESTAMPING, &flags, sizeof flags);
    return fd;
}

/* Read one packet and the NIC's own stamp (ts[2] holds the hardware time). */
int recv_with_stamp(int fd, void *buf, size_t n, struct timespec *hw) {
    char ctl[256];
    struct iovec iov = { buf, n };
    struct msghdr m = { .msg_iov = &iov, .msg_iovlen = 1, .msg_control = ctl, .msg_controllen = sizeof ctl };
    int got = recvmsg(fd, &m, 0);
    for (struct cmsghdr *c = CMSG_FIRSTHDR(&m); c; c = CMSG_NXTHDR(&m, c))
        if (c->cmsg_level == SOL_SOCKET && c->cmsg_type == SCM_TIMESTAMPING)
            *hw = ((struct scm_timestamping *)CMSG_DATA(c))->ts[2];
    return got;
}

The shell side of the same recipe, for one real-time UDP flow on port 14550, with its queue and core. Replace the queue number and the interrupt number with yours from /proc/interrupts.

shell# Coalescing off on the real-time interface
ethtool -C eth0 adaptive-rx off rx-usecs 0 rx-frames 1
# Four queues; steer the flow to queue 3; put queue 3's interrupt on core 5
ethtool -L eth0 combined 4
ethtool -N eth0 flow-type udp4 dst-port 14550 action 3
echo 5 > /proc/irq/IRQ_OF_QUEUE_3/smp_affinity_list
# Run the reader on core 5
taskset -c 5 ./perception_feed
# Check the three drop counters
ethtool -S eth0 | grep -i drop; cat /proc/net/softnet_stat; netstat -su | grep -i rcvbuf

The last piece is the model behind Chapter 2, in a few lines of Python. Change the numbers to your board’s and run it before you touch a setting.

pythonimport math

def coalescing(pps, rx_usecs, rx_frames, irq_us=4.0, pkt_us=0.3):
    """Average added delay and CPU share for one receive queue."""
    if rx_usecs <= 0 or rx_frames <= 1:
        irqs, delay = pps, 0.0                            # one interrupt per packet
    else:
        k_raw = pps * rx_usecs / 1e6                      # extra packets that arrive in the window
        k = min(k_raw, rx_frames - 1)
        window = rx_usecs if k_raw <= rx_frames - 1 else (rx_frames - 1) / pps * 1e6
        alone = math.exp(-k)                              # chance a packet is the only one in its window
        delay = window * (alone + 0.5 * (1 - alone))
        irqs = pps / (1 + k)
    cpu = (irqs * irq_us + pps * pkt_us) / 1e6
    return delay, irqs, cpu

print(coalescing(100_000, 50, 32))   # ~25 us added, ~16.7k interrupts/s, ~9.7% of a core
print(coalescing(2_000, 100, 32))     # ~91 us added, ~1.7k interrupts/s: pays the delay, saves nothing

Where it sits in the field

This lesson is the packet’s view of a bigger system. For the kernel machinery behind interrupts and scheduling, read Kernel Internals for Platform Engineers, and for the real-time kernel itself, Real-Time Linux. Clock agreement across machines is in Time and Sync. The same ideas, applied to a messaging protocol on top of the wire, are in Wire Protocol and Real-Time Updates. For distributed timing in general, see Failure and Time and Distributed Trouble.

Operator links are the next heavy flow on a robot, and Teleop Transport builds on this queue work. Camera links come after that; Low-Latency Video picks up where the queue discipline ends. For the host side of a Linux board, Embedded Linux; for budgets in a running robot, Sensor and Actuator Integration and Robot Real-Time Performance. Lessons planned for the same series cover rings, queues and drops in general and eBPF probes that watch every stage live; they have no page yet.

The takeaway. Every stage from the NIC ring to recvmsg() has a wait, a queue and a knob. A 40 ms stall came from two rules waiting for each other, and one line removed it. The rest are microseconds you trade against CPU. Find the stage with the counter, turn one knob, and measure again.

Sources and credit

This lesson was built from primary sources, opened and checked: the Linux kernel documentation for NAPI, scaling in the networking stack, timestamping, AF_XDP, io_uring zero-copy receive and ethtool netlink; the include/net/tcp.h header; the man pages tcp(7), socket(7) and tc-prio(8); RFC 896, RFC 1122 and RFC 9330; the Cloudflare post on receiving a million packets per second; the WireGuard quick start; the DPDK programmer’s guide; the Linux 6.0 release notes; and Red Hat’s PTP documentation. Figures that none of these gave are marked illustrative where they appear. The models in the devices are ours; they show direction and order of magnitude, not your board’s numbers.

Your control link has a 40 ms tail, an idle CPU and no packet loss. Which first step best matches the evidence?

Now press Teach and draw, from memory, one packet crossing the seven stages, naming the counter and the knob at each. Then go back to the packet at the top, switch to the TCP control channel, and explain the 40 ms bar before you turn TCP_NODELAY on.

Linux Networking for Robots: The Packet's Journey
Linux kernel networking docs · RFC 1122 · Cloudflare, a million packets per second · Back to Gleams