On this page
TCP/IP Protocol Stack
Coverage: IPv4/IPv6 receive/transmit paths → TCP state machine → congestion control (CUBIC/BBR) → flow control (sliding window) → socket buffer (sk_wmem/sk_rmem) → TCP fast path Kernel versions: 2.6 ~ 6.x
Overview
The Linux TCP/IP stack is one of the most highly optimized subsystems in the kernel. In the fast path (established sockets, in-order packets), processing each packet takes only a few dozen instructions. This article focuses on the TCP receive fast path and congestion control.
IPv4 Receive and Transmit
ip_rcv → ip_local_deliver (Receiving)
// net/ipv4/ip_input.c
├─ Validation: version==4, checksum OK, valid length
├─ netfilter
└─
├─ Route lookup: → dst_entry
│ → RTN_LOCAL: for local delivery →
│ → RTN_UNICAST: forwarding →
└─
├─ netfilter
└─
└─ ipprot->handler → /
ip_queue_xmit (Transmitting)
// net/ipv4/ip_output.c
├─ Route lookup: → dst_entry + source IP
├─ Construct IP header: protocol, TTL, DF flag, ...
├─ netfilter NF_INET_LOCAL_OUT
└─
├─ netfilter NF_INET_POST_ROUTING
└─ → QoS qdisc → NIC driver
TCP Fast Path: tcp_rcv_established
// net/ipv4/tcp_input.c
// This is the hottest path for TCP packet reception (established socket, in-order packets)
// fast path (90%+ of packets take this route):
├─ Check header prediction:
│ ├─ PSH bit set? → skip
│ ├─ In-order? ✓
│ ├─ Window non-zero? ✓
│ └─ URG/RST/SYN? → skip
│
├─ Copy data to receive queue:
│ └─ → directly to user buffer?
│
├─ Update rcv_nxt, window advertisement
│
└─ If data is in queue → → wake up epoll/read
// slow path:
└─ / SACK / window full / FIN / RST →
TCP State Machine
Congestion Control
// net/ipv4/tcp_cong.c
// Pluggable congestion control modules:
;
// CUBIC (default):
// cwnd = C * (t - K)^3 + W_max
// K = cube_root(W_max * beta / C)
// Advantages: Fast recovery, fairness, good performance on high-speed links
// BBR (Bottleneck Bandwidth and RTT, Google):
// Not loss-based, but based on BDP (Bandwidth-Delay Product)
// Measurements: max BW (last 10 rounds) and min RTT (last 10 seconds)
// Goal: Keep inflight ≈ BDP
// Advantages: Significantly outperforms CUBIC on bufferbloat-prone links
TCP Socket Buffer Tuning
# Send buffer (default 16KB, auto-grows to max)
# Receive buffer
# Auto-tuning (enabled by default):
# sk_wmem and sk_rmem auto-grow based on RTT and bandwidth probing
# → High BDP links do not require manually setting large buffers
Debugging
# TCP connection states
# Congestion control
# Packet loss/retransmission statistics
|
|
# Trace TCP state changes
References
- Source Code:
net/ipv4/tcp_input.c,net/ipv4/tcp_output.c,net/ipv4/tcp_cong.c,net/ipv4/tcp_cubic.c,net/ipv4/tcp_bbr.c - RFCs: RFC 793 (TCP), RFC 5681 (Congestion Control), RFC 8312 (CUBIC)
- LWN: "TCP fast path", "BBR congestion control"
Keywords: tcp_rcv_established, fast path, CUBIC, BBR, congestion control, socket buffer, TCP state machine