TCP 内核模块实现源码分析
TCP 定义在 RFC 793 , updat 1122, 3168, 6093, 6528
管理连接 && 收发数据
TCP 提供 可靠的、 流量控制的、 端到端 的数据流服务。
可靠的 实现方式:
1. TCP 将数据分成不同的segment
2. TCP 使用定时器来控制时间
3. TCP 始终使用确认机制
4. TCP 首部数据检验
5. TCP 可以重组数据包
6. TCP 丢弃重复数据
7. TCP 提供流量控制
内核源码文件列表:
tcp.c
tcp_input.c
tcp_output.c
tcp_timer.c
tcp_ipv4.c
tcp_minisocks.c
tcp_cong.c
tcp_metrics.c
tcp_fastopen.c
tcp_rate.c
tcp_recovery.c
tcp_ulp.c
tcp_offload.c
1. TCP 首部报文格式 include/uapi/linux/tcp.h
struct tcphdr { __be16 source; __be16 dest; __be32 seq; __be32 ack_seq; #if defined(__LITTLE_ENDIAN_BITFIELD) __u16 res1:4, doff:4, fin:1, syn:1, rst:1, psh:1, ack:1, urg:1, ece:1, cwr:1; #elif defined(__BIG_ENDIAN_BITFIELD) __u16 doff:4, res1:4, cwr:1, ece:1, urg:1, ack:1, psh:1, rst:1, syn:1, fin:1; #else #error "Adjust your <asm/byteorder.h> defines" #endif __be16 window; __sum16 check; __be16 urg_ptr; };
TCP 首部20字节
TCP 初始化
net/ipv4/af_inet.c 定义tcp_ptotocol 对象
/* thinking of making this const? Don't. * early_demux can change based on sysctl. */ static struct net_protocol tcp_protocol = { .early_demux = tcp_v4_early_demux, .early_demux_handler = tcp_v4_early_demux, .handler = tcp_v4_rcv, .err_handler = tcp_v4_err, .no_policy = 1, .netns_ok = 1, .icmp_strict_tag_validation = 1, };
初始化tcp 协议
static int __init inet_init(void) { ... if (inet_add_protocol(&tcp_protocol, IPPROTO_TCP) < 0) pr_crit("%s: Cannot add TCP protocol\n", __func__); .... }
调用 tcp_proc_register 注册tcp协议
int tcp_proc_register(struct net *net, struct tcp_seq_afinfo *afinfo) { int rc = 0; struct proc_dir_entry *p; afinfo->seq_ops.start = tcp_seq_start; afinfo->seq_ops.next = tcp_seq_next; afinfo->seq_ops.stop = tcp_seq_stop; p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net, afinfo->seq_fops, afinfo); if (!p) rc = -ENOMEM; return rc; }
每个连接,TCP管理4个不同的时间 net/ipv4/tcp_timer.c
重传时间: 在发送SYN请求后,等待另一方的确认时间
确认延迟时间: TIME_WAIT 2* MSL
保持时间 : 空闲连接的另一端何时关闭或重启
Zero Window probe timer: 窗口大小信息不断变化

浙公网安备 33010602011771号