《TCP/IP详解 卷2》 笔记:TCP的输入函数:tcp_input

TCP输入处理是系统中最长的一部分代码,tcp_input函数约有1100行代码(预警!)。它完全遵循RFC793中定义的输入事件处理步骤,这些步骤详细定义了如何根据连接的当前状态,处理不同的输入报文段。

当发现分组IP首部中的协议字段是TCP协议时,IP协议的软中断处理函数ipintr调用tcp_input函数进行处理。tcp_input函数我删去了处理URG标志的流程,它的代码如下:

/*
 * TCP input routine, follows pages 65-76 of the
 * protocol specification dated September, 1981 very closely.
 */
void
tcp_input(m, iphlen)
	register struct mbuf *m;
	int iphlen;
{
	register struct tcpiphdr *ti;
	register struct inpcb *inp;
	u_char *optp = NULL;
	int optlen;
	int len, tlen, off;
	register struct tcpcb *tp = 0;
	register int tiflags;
	struct socket *so;
	int todrop, acked, ourfinisacked, needoutput = 0;
	short ostate;
	struct in_addr laddr;
	int dropsocket = 0;
	int iss = 0;
	u_long tiwin, ts_val, ts_ecr;
	int ts_present = 0;

	tcpstat.tcps_rcvtotal++;
	/*
	 * Get IP and TCP header together in first mbuf.
	 * Note: IP leaves IP header in first mbuf.
	 */
	ti = mtod(m, struct tcpiphdr *);
	if (iphlen > sizeof (struct ip)) /*IP首部包含选项?*/
		ip_stripoptions(m, (struct mbuf *)0); /*过滤掉IP首部选项*/
	if (m->m_len < sizeof (struct tcpiphdr)) { /*IP首部和TCP首部不在一个mbuf?*/
		if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) { /*将IP首部和TCP首部调整到一个mbuf中*/
			tcpstat.tcps_rcvshort++;
			return;
		}
		ti = mtod(m, struct tcpiphdr *);
	}

	/*
	 * Checksum extended TCP header and data.
	 */
	tlen = ((struct ip *)ti)->ip_len; /*经过IP层处理后,tlen是TCP报文段的长度*/
	len = sizeof (struct ip) + tlen; /*IP数据报总长度*/
	ti->ti_next = ti->ti_prev = 0;
	ti->ti_x1 = 0;
	ti->ti_len = (u_short)tlen;
	HTONS(ti->ti_len);
	if (ti->ti_sum = in_cksum(m, len)) { /*验证校验和失败,丢弃报文*/
		tcpstat.tcps_rcvbadsum++;
		goto drop;
	}

	/*
	 * Check that TCP offset makes sense,
	 * pull out TCP options and adjust length.		XXX
	 */
	off = ti->ti_off << 2; /*TCP首部的长度*/
	if (off < sizeof (struct tcphdr) || off > tlen) { /*无效的TCP首部,丢弃*/
		tcpstat.tcps_rcvbadoff++;
		goto drop;
	}
	tlen -= off; /*数据的长度*/
	ti->ti_len = tlen;
	if (off > sizeof (struct tcphdr)) { /*TCP首部包含选项?*/
		if (m->m_len < sizeof(struct ip) + off) { /*TCP首部和选项不在一个mbuf?*/
			if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) { /*将IP首部和TCP首部调整到一个mbuf中*/*/
				tcpstat.tcps_rcvshort++;
				return;
			}
			ti = mtod(m, struct tcpiphdr *);
		}
		optlen = off - sizeof (struct tcphdr); /*TCP选项的长度*/
		optp = mtod(m, u_char *) + sizeof (struct tcpiphdr); /*指向选项*/
		/* 
		 * Do quick retrieval of timestamp options ("options
		 * prediction?").  If timestamp is the only option and it's
		 * formatted as recommended in RFC 1323 appendix A, we
		 * quickly get the values now and not bother calling
		 * tcp_dooptions(), etc.
		 */
		if ((optlen == TCPOLEN_TSTAMP_APPA ||
		     (optlen > TCPOLEN_TSTAMP_APPA &&
			optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
		     *(u_long *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
		     (ti->ti_flags & TH_SYN) == 0) { /*选项中只包含时间戳选项?*/
			ts_present = 1; 
			ts_val = ntohl(*(u_long *)(optp + 4)); /*记录对端的时间戳*/
			ts_ecr = ntohl(*(u_long *)(optp + 8)); /*记录本端回显的时间戳*/
			optp = NULL;	/* we've parsed the options */
		}
	}
	tiflags = ti->ti_flags; /*获取TCP首部中的标志*/

	/*
	 * Convert TCP protocol specific fields to host format.
	 */
	NTOHL(ti->ti_seq);
	NTOHL(ti->ti_ack);
	NTOHS(ti->ti_win);
	NTOHS(ti->ti_urp);

	/*
	 * Locate pcb for segment.
	 */
findpcb:
	inp = tcp_last_inpcb;
	if (inp->inp_lport != ti->ti_dport ||
	    inp->inp_fport != ti->ti_sport ||
	    inp->inp_faddr.s_addr != ti->ti_src.s_addr ||
	    inp->inp_laddr.s_addr != ti->ti_dst.s_addr) {
		inp = in_pcblookup(&tcb, ti->ti_src, ti->ti_sport,
		    ti->ti_dst, ti->ti_dport, INPLOOKUP_WILDCARD); /*根据源IP地址、源端口号、目的IP地址和目的端口号
		查找合适的inpcb结构*/
		if (inp)
			tcp_last_inpcb = inp; /*记录最新查找到的inpcb*/
		++tcpstat.tcps_pcbcachemiss;
	}

	/*
	 * If the state is CLOSED (i.e., TCB does not exist) then
	 * all data in the incoming segment is discarded.
	 * If the TCB exists but is in CLOSED state, it is embryonic,
	 * but should either do a listen or a connect soon.
	 */
	if (inp == 0) /*找不到inpcb,丢弃报文,并发送RST*/
		goto dropwithreset;
	tp = intotcpcb(inp);
	if (tp == 0) /*没有tcpcb?丢弃报文,并发送RST*/
		goto dropwithreset;
	if (tp->t_state == TCPS_CLOSED) /*连接状态为CLOSED,丢弃报文*/
		goto drop;
	
	/* Unscale the window into a 32-bit value. */
	if ((tiflags & TH_SYN) == 0) /*计算通告的窗口大小*/
		tiwin = ti->ti_win << tp->snd_scale;
	else
		tiwin = ti->ti_win;

	so = inp->inp_socket;
	if (so->so_options & SO_ACCEPTCONN) { /*该socket是监听socket?
		SO_ACCEPTCONN标志在执行listen系统调用时被置上!*/
		if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) { /*收到的不是纯SYN报文?*/
			/*
			 * Note: dropwithreset makes sure we don't
			 * send a reset in response to a RST.
			 */
			if (tiflags & TH_ACK) { /*带ACK标志的无效的SYN报文,丢弃,并发送RST*/
				tcpstat.tcps_badsyn++;
				goto dropwithreset;
			}
			goto drop; /*丢弃报文*/
		}
		so = sonewconn(so, 0); /*创建一个新的socket!*/
		if (so == 0)
			goto drop;
		/*
		 * This is ugly, but ....
		 *
		 * Mark socket as temporary until we're
		 * committed to keeping it.  The code at
		 * ``drop'' and ``dropwithreset'' check the
		 * flag dropsocket to see if the temporary
		 * socket created here should be discarded.
		 * We mark the socket as discardable until
		 * we're committed to it below in TCPS_LISTEN.
		 */
		dropsocket++;
		inp = (struct inpcb *)so->so_pcb;
		inp->inp_laddr = ti->ti_dst; /*设置新socket的本地地址*/
		inp->inp_lport = ti->ti_dport; /*设置新socket的本地端口*/
		tp = intotcpcb(inp);
		tp->t_state = TCPS_LISTEN; /*连接状态设置为TCPS_LISTEN!会执行329行的流程*/

		/* Compute proper scaling value from buffer space
		 */
		while (tp->request_r_scale < TCP_MAX_WINSHIFT && /*根据接收缓冲区大小计算窗口缩放因子*/
		   TCP_MAXWIN << tp->request_r_scale < so->so_rcv.sb_hiwat)
			tp->request_r_scale++;
	}


	/*
	 * Segment received on connection.
	 * Reset idle time and keep-alive timer.
	 */
	tp->t_idle = 0; /*连接空闲时间清零*/
	tp->t_timer[TCPT_KEEP] = tcp_keepidle; /*保活定时器复位*/

	/*
	 * Process options if not in LISTEN state,
	 * else do it below (after getting remote address).
	 */
	if (optp && tp->t_state != TCPS_LISTEN) /*解析不是LISTEN状态的TCP选项*/
		tcp_dooptions(tp, optp, optlen, ti,
			&ts_present, &ts_val, &ts_ecr);

	/* 
	 * Header prediction: check for the two common cases
	 * of a uni-directional data xfer.  If the packet has
	 * no control flags, is in-sequence, the window didn't
	 * change and we're not retransmitting, it's a
	 * candidate.  If the length is zero and the ack moved
	 * forward, we're the sender side of the xfer.  Just
	 * free the data acked & wake any higher level process
	 * that was blocked waiting for space.  If the length
	 * is non-zero and the ack didn't move, we're the
	 * receiver side.  If we're getting packets in-order
	 * (the reassembly queue is empty), add the data to
	 * the socket buffer and note that we need a delayed ack.
	 */
	 /*首部预测算法,tcp_input函数的一条快速路径!*/
	if (tp->t_state == TCPS_ESTABLISHED && /*连接处于ESTABLISHED状态*/
	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK && /*只有ACK标志*/
	    (!ts_present || TSTMP_GEQ(ts_val, tp->ts_recent)) && /*没有时间戳或是新的时间戳*/
	    ti->ti_seq == tp->rcv_nxt && /*序列号是期望收到下一个数据的序列号*/
	    tiwin && tiwin == tp->snd_wnd && /*对端通告的窗口大小没有变化*/
	    tp->snd_nxt == tp->snd_max) { /*上一个报文段不是重传报文*/


		if (ts_present && TSTMP_GEQ(ts_val, tp->ts_recent) &&
			SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) { /*哪个时间戳需要回显,正确的算法!!!!*/
			tp->ts_recent_age = tcp_now; /*最近一次ts_recent被更新的时间戳*/
			tp->ts_recent = ts_val; /*对端发送的最新的有效时间戳*/
		}

		if (ti->ti_len == 0) { /*不包含任何数据*/
			if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
			    SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
			    tp->snd_cwnd >= tp->snd_wnd) { /*有效的纯ACK报文段*/
				/*
				 * this is a pure ack for outstanding data.
				 */
				++tcpstat.tcps_predack;
				if (ts_present) /*如果有时间戳,根据时间戳就可计算报文的RTT,然后更新RTO*/
					tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
				else if (tp->t_rtt && /*如果没有时间戳,根据t_rtt计算报文的RTT,然后更新RTO*/
					    SEQ_GT(ti->ti_ack, tp->t_rtseq))
					tcp_xmit_timer(tp, tp->t_rtt);
				acked = ti->ti_ack - tp->snd_una; /*ACK已确认的字节数*/
				tcpstat.tcps_rcvackpack++; /*更新统计*/
				tcpstat.tcps_rcvackbyte += acked;
				sbdrop(&so->so_snd, acked); /*丢弃发送缓冲区中已被确认的数据*/
				tp->snd_una = ti->ti_ack; /*更新snd_una指针*/
				m_freem(m); /*没有数据,可释放该mbuf*/

				/*
				 * If all outstanding data are acked, stop
				 * retransmit timer, otherwise restart timer
				 * using current (possibly backed-off) value.
				 * If process is waiting for space,
				 * wakeup/selwakeup/signal.  If data
				 * are ready to send, let tcp_output
				 * decide between more output or persist.
				 */
				if (tp->snd_una == tp->snd_max) /*没有数据需要被确认?重传定时器复位*/
					tp->t_timer[TCPT_REXMT] = 0;
				else if (tp->t_timer[TCPT_PERSIST] == 0) /*否则不是持续状态?启动重传定时器*/
					tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;

				if (so->so_snd.sb_flags & SB_NOTIFY) /*唤醒在发送缓冲区等待的进程*/
					sowwakeup(so);
				if (so->so_snd.sb_cc) /*还有待发送的数据,调用tcp_output发送*/
					(void) tcp_output(tp);
				return;
			}
		} else if (ti->ti_ack == tp->snd_una && /*正常数据报文段,ACK标志置位,但是未确认任何数据*/
		    tp->seg_next == (struct tcpiphdr *)tp &&
		    ti->ti_len <= sbspace(&so->so_rcv)) {
			/*
			 * this is a pure, in-sequence data packet
			 * with nothing on the reassembly queue and
			 * we have enough buffer space to take it.
			 */
			++tcpstat.tcps_preddat;
			tp->rcv_nxt += ti->ti_len; /*更新rcv_nxt*/
			tcpstat.tcps_rcvpack++;
			tcpstat.tcps_rcvbyte += ti->ti_len;
			/*
			 * Drop TCP, IP headers and TCP options then add data
			 * to socket buffer.
			 */
			m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr); /*丢弃IP首部,TCP首部*/
			m->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
			sbappend(&so->so_rcv, m); /*将数据添加到接收缓冲区*/
			sorwakeup(so); /*唤醒在接收缓冲区等待的进程*/
			tp->t_flags |= TF_DELACK; /*置延迟的ACK标志*/
			return;
		}
	} /*首部预测算法结束*/

	/*
	 * Drop TCP, IP headers and TCP options.
	 */
	m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr); /*丢弃IP首部,TCP首部*/
	m->m_len  -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);

	/*
	 * Calculate amount of space in receive window,
	 * and then do TCP input processing.
	 * Receive window is amount of space in rcv queue,
	 * but not less than advertised window.
	 */
	{ int win;

	win = sbspace(&so->so_rcv); /*接收缓冲区可用空间*/
	if (win < 0)
		win = 0;
	tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt)); /*更新接收窗口大小*/
	}

	switch (tp->t_state) {

	/*
	 * If the state is LISTEN then ignore segment if it contains an RST.
	 * If the segment contains an ACK then it is bad and send a RST.
	 * If it does not contain a SYN then it is not interesting; drop it.
	 * Don't bother responding if the destination was a broadcast.
	 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
	 * tp->iss, and send a segment:
	 *     <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
	 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
	 * Fill in remote peer address fields if not previously specified.
	 * Enter SYN_RECEIVED state, and process any other fields of this
	 * segment in this state.
	 */
	case TCPS_LISTEN: { /*被动打开,期待接收SYN,然后发送SYN、ACK*/
		struct mbuf *am;
		register struct sockaddr_in *sin;

#ifdef already_done
		if (tiflags & TH_RST) /*报文带RST标志,丢弃*/
			goto drop;
		if (tiflags & TH_ACK) /*报文带ACK标志,丢弃,发送RST*/
			goto dropwithreset;
		if ((tiflags & TH_SYN) == 0) /*非SYN报文,丢弃*/
			goto drop;
#endif
		/*
		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
		 * in_broadcast() should never return true on a received
		 * packet with M_BCAST not set.
		 */
		if (m->m_flags & (M_BCAST|M_MCAST) || /*丢弃广播和多播的SYN报文*/
		    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
			goto drop;
		am = m_get(M_DONTWAIT, MT_SONAME);	/*获取一个保存sockaddr_in结构的mbuf*/
		if (am == NULL)
			goto drop;
		am->m_len = sizeof (struct sockaddr_in);
		sin = mtod(am, struct sockaddr_in *);
		sin->sin_family = AF_INET;
		sin->sin_len = sizeof(*sin);
		sin->sin_addr = ti->ti_src; /*源IP地址*/
		sin->sin_port = ti->ti_sport; /*源端口号*/
		bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
		laddr = inp->inp_laddr;
		if (inp->inp_laddr.s_addr == INADDR_ANY)
			inp->inp_laddr = ti->ti_dst;
		if (in_pcbconnect(inp, am)) { /*设置socket的外部地址和外部端口号!*/
			inp->inp_laddr = laddr;
			(void) m_free(am);
			goto drop;
		}
		(void) m_free(am); /*释放的临时mbuf*/
		tp->t_template = tcp_template(tp); /*获取一个TCP IP首部模板*/
		if (tp->t_template == 0) {
			tp = tcp_drop(tp, ENOBUFS);
			dropsocket = 0;		/* socket is already gone */
			goto drop;
		}
		if (optp) /*解析LISTEN状态的TCP选项*/*/
			tcp_dooptions(tp, optp, optlen, ti,
				&ts_present, &ts_val, &ts_ecr);
		if (iss)
			tp->iss = iss; /*初始的发送序列号*/
		else
			tp->iss = tcp_iss;
		tcp_iss += TCP_ISSINCR/4;
		tp->irs = ti->ti_seq; /*初始的接收序列号*/
		tcp_sendseqinit(tp); /*初始化发送序列空间*/
			/*(tp)->snd_una = (tp)->snd_nxt = (tp)->snd_max = (tp)->snd_up = (tp)->iss*/
		tcp_rcvseqinit(tp); /*初始化接收序列空间*/
			/*(tp)->rcv_adv = (tp)->rcv_nxt = (tp)->irs + 1*/
		tp->t_flags |= TF_ACKNOW; /*立即发送ACK*/
		tp->t_state = TCPS_SYN_RECEIVED; /*转移到SYN_RECEIVED状态,发送SYN、ACK*/
		tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT; /*启动连接建立定时器*/
		dropsocket = 0;		/* committed to socket */
		tcpstat.tcps_accepts++;
		goto trimthenstep6;
		}

	/*
	 * If the state is SYN_SENT:
	 *	if seg contains an ACK, but not for our SYN, drop the input.
	 *	if seg contains a RST, then drop the connection.
	 *	if seg does not contain SYN, then drop it.
	 * Otherwise this is an acceptable SYN segment
	 *	initialize tp->rcv_nxt and tp->irs
	 *	if seg contains ack then advance tp->snd_una
	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
	 *	arrange for segment to be acked (eventually)
	 *	continue processing rest of data/controls, beginning with URG
	 */
	case TCPS_SYN_SENT: /*主动打开,已经发送过SYN,期待接收SYN、ACK*/
		if ((tiflags & TH_ACK) &&
		    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
		     SEQ_GT(ti->ti_ack, tp->snd_max))) /*无效的ACK,发送RST*/
			goto dropwithreset;
		if (tiflags & TH_RST) { /*带RST标志*/
			if (tiflags & TH_ACK) /*又带ACK标志,对端拒绝连接,丢弃连接*/
				tp = tcp_drop(tp, ECONNREFUSED);
			goto drop;
		}
		if ((tiflags & TH_SYN) == 0) /*不带SYN标志,丢弃*/
			goto drop;
		if (tiflags & TH_ACK) { /*带ACK标志*/
			tp->snd_una = ti->ti_ack; /*更新snd_una指针*/
			if (SEQ_LT(tp->snd_nxt, tp->snd_una)) /*更新snd_nxt指针*/
				tp->snd_nxt = tp->snd_una;
		}
		tp->t_timer[TCPT_REXMT] = 0;
		tp->irs = ti->ti_seq; /*初始的接收序列号*/*/
		tcp_rcvseqinit(tp); /*初始化接收序列空间*/
			/*(tp)->rcv_adv = (tp)->rcv_nxt = (tp)->irs + 1*/
		tp->t_flags |= TF_ACKNOW; /*立即发送ACK*/*/
		if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) { /*收到的ACK已经确认了发送的SYN*/
			tcpstat.tcps_connects++;
			soisconnected(so); /*TCP连接已建立*/
			tp->t_state = TCPS_ESTABLISHED; /*状态转移到ESTABLISHED!*/
			/* Do window scaling on this connection? */
			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
				(TF_RCVD_SCALE|TF_REQ_SCALE)) { /*记录窗口缩放因子*/
				tp->snd_scale = tp->requested_s_scale;
				tp->rcv_scale = tp->request_r_scale;
			}
			(void) tcp_reass(tp, (struct tcpiphdr *)0, /*由于数据可能在连接未建立之前到达,调用tcp_reass将数据放入接收缓冲区*/
				(struct mbuf *)0);
			/*
			 * if we didn't have to retransmit the SYN,
			 * use its rtt as our initial srtt & rtt var.
			 */
			if (tp->t_rtt) /*如果第一个SYN正被计时,计算第一个RTO*/
				tcp_xmit_timer(tp, tp->t_rtt);
		} else
			tp->t_state = TCPS_SYN_RECEIVED; /*同时打开*/

trimthenstep6:
		/*
		 * Advance ti->ti_seq to correspond to first data byte.
		 * If data, trim to stay within window,
		 * dropping FIN if necessary.
		 */
		ti->ti_seq++; /*SYN标志占用一个序号,SYN报文可能带有数据?*/
		if (ti->ti_len > tp->rcv_wnd) { /*丢弃超过接收窗口的数据*/
			todrop = ti->ti_len - tp->rcv_wnd;
			m_adj(m, -todrop);
			ti->ti_len = tp->rcv_wnd;
			tiflags &= ~TH_FIN;
			tcpstat.tcps_rcvpackafterwin++;
			tcpstat.tcps_rcvbyteafterwin += todrop;
		}
		tp->snd_wl1 = ti->ti_seq - 1; /*会强制更新3个窗口变量*/
		tp->rcv_up = ti->ti_seq;
		goto step6; /*调到879行*/
	}

	/*
	 * States other than LISTEN or SYN_SENT.
	 * First check timestamp, if present.
	 * Then check that at least some bytes of segment are within 
	 * receive window.  If segment begins before rcv_nxt,
	 * drop leading data (and SYN); if nothing left, just ack.
	 * 
	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
	 * and it's less than ts_recent, drop it.
	 */
	if (ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
	    TSTMP_LT(ts_val, tp->ts_recent)) { /*重复的报文段*/

		/* Check to see if ts_recent is over 24 days old.  */
		if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) { /*时间戳已经回绕*/
			/*
			 * Invalidate ts_recent.  If this segment updates
			 * ts_recent, the age will be reset later and ts_recent
			 * will get a valid value.  If it does not, setting
			 * ts_recent to zero will at least satisfy the
			 * requirement that zero be placed in the timestamp
			 * echo reply when ts_recent isn't valid.  The
			 * age isn't reset until we get a valid ts_recent
			 * because we don't want out-of-order segments to be
			 * dropped when ts_recent is old.
			 */
			tp->ts_recent = 0; /*使记录的对端的时间戳无效*/
		} else { /*更新统计信息*/
			tcpstat.tcps_rcvduppack++;
			tcpstat.tcps_rcvdupbyte += ti->ti_len;
			tcpstat.tcps_pawsdrop++;
			goto dropafterack;
		}
	}

	todrop = tp->rcv_nxt - ti->ti_seq; /*超过接收窗口左边沿的字节数*/
	if (todrop > 0) {
		if (tiflags & TH_SYN) { /*重复的SYN?*/
			tiflags &= ~TH_SYN;
			ti->ti_seq++;
			if (ti->ti_urp > 1) 
				ti->ti_urp--;
			else
				tiflags &= ~TH_URG;
			todrop--;
		}
		if (todrop > ti->ti_len || 
			todrop == ti->ti_len && (tiflags & TH_FIN) == 0 ) { //完全重复的报文段
			tiflags &= ~TH_FIN;
			tp->t_flags |= TF_ACKNOW; //立即发送ACK
			todrop = ti->ti_len;
			tcpstat.tcps_rcvduppack++;
			tcpstat.tcps_rcvdupbyte += ti->ti_len;
		} else { //部分重复
			tcpstat.tcps_rcvpartduppack++;
			tcpstat.tcps_rcvpartdupbyte += todrop;
		}
		m_adj(m, todrop); /*丢弃重复的数据,修正TCP首部中相关字段*/
		ti->ti_seq += todrop;
		ti->ti_len -= todrop;
		if (ti->ti_urp > todrop)
			ti->ti_urp -= todrop;
		else {
			tiflags &= ~TH_URG;
			ti->ti_urp = 0;
		}
	}

	/*
	 * If new data are received on a connection after the
	 * user processes are gone, then RST the other end.
	 */
	if ((so->so_state & SS_NOFDREF) &&
	    tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) { /*应用程序关闭了连接,如果收到数据,则发送RST*/
		tp = tcp_close(tp);
		tcpstat.tcps_rcvafterclose++;
		goto dropwithreset;
	}

	/*
	 * If segment ends after window, drop trailing data
	 * (and PUSH and FIN); if nothing left, just ACK.
	 */
	todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd); /*超过接收窗口右边沿的字节数*/
	if (todrop > 0) {
		tcpstat.tcps_rcvpackafterwin++;
		if (todrop >= ti->ti_len) { /*完全重复的报文段*/
			tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
			/*
			 * If a new connection request is received
			 * while in TIME_WAIT, drop the old connection
			 * and start over if the sequence numbers
			 * are above the previous ones.
			 */
			if (tiflags & TH_SYN &&
			    tp->t_state == TCPS_TIME_WAIT &&
			    SEQ_GT(ti->ti_seq, tp->rcv_nxt)) { /*重建连接??*/
				iss = tp->snd_nxt + TCP_ISSINCR;
				tp = tcp_close(tp);
				goto findpcb;
			}
			/*
			 * If window is closed can only take segments at
			 * window edge, and have to drop data and PUSH from
			 * incoming segments.  Continue processing, but
			 * remember to ack.  Otherwise, drop segment
			 * and ack.
			 */
			if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) { /*收到了窗口探测报文,立即发送ACK*/
				tp->t_flags |= TF_ACKNOW;
				tcpstat.tcps_rcvwinprobe++;
			} else
				goto dropafterack;
		} else
			tcpstat.tcps_rcvbyteafterwin += todrop;
		m_adj(m, -todrop); /*丢弃重复的数据,修正TCP首部中相关字段*/
		ti->ti_len -= todrop;
		tiflags &= ~(TH_PUSH|TH_FIN);
	}

	if (ts_present && TSTMP_GEQ(ts_val, tp->ts_recent) &&
	   SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) { //哪个时间戳需要回显,正确的算法!!!!
		tp->ts_recent_age = tcp_now; //最近一次ts_recent被更新的时间戳
		tp->ts_recent = ts_val; //对端发送的最新的有效时间戳
	}
	/*
	 * If the RST bit is set examine the state:
	 *    SYN_RECEIVED STATE:
	 *	If passive open, return to LISTEN state.
	 *	If active open, inform user that connection was refused.
	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
	 *	Inform user that connection was reset, and close tcb.
	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
	 *	Close the tcb.
	 */
	if (tiflags&TH_RST) switch (tp->t_state) { /*处理RST标志*/

	case TCPS_SYN_RECEIVED:
		so->so_error = ECONNREFUSED;
		goto close;

	case TCPS_ESTABLISHED:
	case TCPS_FIN_WAIT_1:
	case TCPS_FIN_WAIT_2:
	case TCPS_CLOSE_WAIT:
		so->so_error = ECONNRESET;
	close:
		tp->t_state = TCPS_CLOSED;
		tcpstat.tcps_drops++;
		tp = tcp_close(tp);
		goto drop;

	case TCPS_CLOSING:
	case TCPS_LAST_ACK:
	case TCPS_TIME_WAIT:
		tp = tcp_close(tp);
		goto drop;
	}

	/*
	 * If a SYN is in the window, then this is an
	 * error and we send an RST and drop the connection.
	 */
	if (tiflags & TH_SYN) {
		tp = tcp_drop(tp, ECONNRESET);
		goto dropwithreset;
	}

	/*
	 * If the ACK bit is off we drop the segment and return.
	 */
	if ((tiflags & TH_ACK) == 0)
		goto drop;
	
	/*
	 * Ack processing.
	 */
	switch (tp->t_state) { /*处理ACK标志*/

	/*
	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
	 * ESTABLISHED state and continue processing, otherwise
	 * send an RST.
	 */
	case TCPS_SYN_RECEIVED: /*服务端,期待收到SYN、ACK,然后发送ACK*/
		if (SEQ_GT(tp->snd_una, ti->ti_ack) ||
		    SEQ_GT(ti->ti_ack, tp->snd_max)) /*无效的ACK,发送RST*/
			goto dropwithreset;
		tcpstat.tcps_connects++;
		soisconnected(so); /*连接已经建立*/
		tp->t_state = TCPS_ESTABLISHED; /*状态转移到ESTABLISHED!*/
		/* Do window scaling? */
		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
			(TF_RCVD_SCALE|TF_REQ_SCALE)) { /*记录窗口缩放因子*/
			tp->snd_scale = tp->requested_s_scale;
			tp->rcv_scale = tp->request_r_scale;
		}
		(void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0); /*将数据加入到接收缓冲区*/
		tp->snd_wl1 = ti->ti_seq - 1; /*会强制更新3个窗口变量*/
		/* fall into ... */

	/*
	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
	 * ACKs.  If the ack is in the range
	 *	tp->snd_una < ti->ti_ack <= tp->snd_max
	 * then advance tp->snd_una to ti->ti_ack and drop
	 * data from the retransmission queue.  If this ACK reflects
	 * more up to date window information we update our window information.
	 */
	case TCPS_ESTABLISHED:
	case TCPS_FIN_WAIT_1:
	case TCPS_FIN_WAIT_2:
	case TCPS_CLOSE_WAIT:
	case TCPS_CLOSING:
	case TCPS_LAST_ACK:
	case TCPS_TIME_WAIT:
		/*快速重传和快速恢复算法 !!!*/
		if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) { /*接收到重复的ACK,即1. ACK未确认数据*/
			if (ti->ti_len == 0 && tiwin == tp->snd_wnd) { /*2. 报文没有携带数据 3. 通告的窗口大小未变*/
				tcpstat.tcps_rcvdupack++;
				/*
				 * If we have outstanding data (other than
				 * a window probe), this is a completely
				 * duplicate ack (ie, window info didn't
				 * change), the ack is the biggest we've
				 * seen and we've seen exactly our rexmt
				 * threshhold of them, assume a packet
				 * has been dropped and retransmit it.
				 * Kludge snd_nxt & the congestion
				 * window so we send only this one
				 * packet.
				 *
				 * We know we're losing at the current
				 * window size so do congestion avoidance
				 * (set ssthresh to half the current window
				 * and pull our congestion window back to
				 * the new ssthresh).
				 *
				 * Dup acks mean that packets have left the
				 * network (they're now cached at the receiver) 
				 * so bump cwnd by the amount in the receiver
				 * to keep a constant cwnd packets in the
				 * network.
				 */
				if (tp->t_timer[TCPT_REXMT] == 0 || 
				    ti->ti_ack != tp->snd_una) 
					tp->t_dupacks = 0; /*重复的ACK计算清零*/
				else if (++tp->t_dupacks == tcprexmtthresh) { /*4. 重传定时器已启动 5. 
					确认字段是TCP收到的最大确认序列号 可确定是完全重复的ACK。
					如果重复的ACK次数为3*/
					tcp_seq onxt = tp->snd_nxt;
					/*令慢启动门限为当前拥塞窗口的一半,最小值为两个报文段*/
					u_int win =
					    min(tp->snd_wnd, tp->snd_cwnd) / 2 /
						tp->t_maxseg;

					if (win < 2)
						win = 2;
					tp->snd_ssthresh = win * tp->t_maxseg;
					tp->t_timer[TCPT_REXMT] = 0; /*关闭重传定时器*/
					tp->t_rtt = 0; /*关闭报文段计时*/
					tp->snd_nxt = ti->ti_ack; 
					tp->snd_cwnd = tp->t_maxseg; /*拥塞窗口设置为一个报文段大小*/
					(void) tcp_output(tp); /*重传报文段*/
					tp->snd_cwnd = tp->snd_ssthresh +
					       tp->t_maxseg * tp->t_dupacks; /*重传后,拥塞窗口大小为慢启动门限加上3倍的报文段大小*/
					if (SEQ_GT(onxt, tp->snd_nxt))
						tp->snd_nxt = onxt;
					goto drop;
				} else if (tp->t_dupacks > tcprexmtthresh) { /*重复的ACK超过3*/
					tp->snd_cwnd += tp->t_maxseg; /*增大拥塞窗口大小增大一个报文段大小*/
					(void) tcp_output(tp); /*发送数据*/
					goto drop;
				}
			} else /*重复的ACK计算清零*/
				tp->t_dupacks = 0;
			break;
		}
		/*
		 * If the congestion window was inflated to account
		 * for the other side's cached packets, retract it.
		 */
		if (tp->t_dupacks > tcprexmtthresh && /*非重复ACK,快速重传结束*/
		    tp->snd_cwnd > tp->snd_ssthresh)
			tp->snd_cwnd = tp->snd_ssthresh;
		tp->t_dupacks = 0; /*重复的ACK计算清零*/
		acked = ti->ti_ack - tp->snd_una; /*ACK确认的字节数*/
		tcpstat.tcps_rcvackpack++;
		tcpstat.tcps_rcvackbyte += acked;

		/*
		 * If we have a timestamp reply, update smoothed
		 * round trip time.  If no timestamp is present but
		 * transmit timer is running and timed sequence
		 * number was acked, update smoothed round trip time.
		 * Since we now have an rtt measurement, cancel the
		 * timer backoff (cf., Phil Karn's retransmit alg.).
		 * Recompute the initial retransmit timer.
		 */
		/*计算RTT,根据RTT计算RTO*/
		if (ts_present)
			tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
		else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
			tcp_xmit_timer(tp,tp->t_rtt);

		/*
		 * If all outstanding data is acked, stop retransmit
		 * timer and remember to restart (more output or persist).
		 * If there is more data to be acked, restart retransmit
		 * timer, using current (possibly backed-off) value.
		 */
		if (ti->ti_ack == tp->snd_max) { /*ACK已经确认了所有的数据,关闭重传定时器*/
			tp->t_timer[TCPT_REXMT] = 0;
			needoutput = 1; /*发送窗口已增大,发送更多数据!*/
		} else if (tp->t_timer[TCPT_PERSIST] == 0) /*非持续状态,启动重传定时器*/
			tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
		/*
		 * When new data is acked, open the congestion window.
		 * If the window gives us less than ssthresh packets
		 * in flight, open exponentially (maxseg per packet).
		 * Otherwise open linearly: maxseg per window
		 * (maxseg * (maxseg / cwnd) per packet).
		 */
		{ /*慢启动和拥塞避免,更新拥塞窗口!!*/
		register u_int cw = tp->snd_cwnd; 
		register u_int incr = tp->t_maxseg;

		if (cw > tp->snd_ssthresh) /*正在进行拥塞避免,否则正在进行慢启动*/
			incr = incr * incr / cw;
		tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale); /*更新拥塞窗口大小*/
		}
		if (acked > so->so_snd.sb_cc) { /*发送缓冲区所有的数据被确认,同时说明发送的FIN已被确认*/
			tp->snd_wnd -= so->so_snd.sb_cc; /*更新发送窗口大小*/
			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc); /*丢弃发送缓冲区中的数据*/
			ourfinisacked = 1;
		} else {
			sbdrop(&so->so_snd, acked); /*丢弃已被确认的数据*/
			tp->snd_wnd -= acked; /*更新发送窗口大小*/
			ourfinisacked = 0;
		}
		if (so->so_snd.sb_flags & SB_NOTIFY) /*唤醒在发送缓冲区等待的进程*/*/
			sowwakeup(so);
		tp->snd_una = ti->ti_ack; /*更新snd_una指针*/
		if (SEQ_LT(tp->snd_nxt, tp->snd_una)) /*更新snd_nxt指针*/
			tp->snd_nxt = tp->snd_una;

		switch (tp->t_state) { /*特殊状态下的ACK处理*/

		/*
		 * In FIN_WAIT_1 STATE in addition to the processing
		 * for the ESTABLISHED state if our FIN is now acknowledged
		 * then enter FIN_WAIT_2.
		 */
		case TCPS_FIN_WAIT_1: /*主动关闭,已发送过FIN,期待接收ACK*/
			if (ourfinisacked) { /*发送的FIN被确认*/
				/*
				 * If we can't receive any more
				 * data, then closing user can proceed.
				 * Starting the timer is contrary to the
				 * specification, but if we don't get a FIN
				 * we'll hang forever.
				 */
				if (so->so_state & SS_CANTRCVMORE) { /*当应用程序完全关闭了连接时,启动FIN_WAIT_2定时器*/
					soisdisconnected(so);
					tp->t_timer[TCPT_2MSL] = tcp_maxidle;
				}
				tp->t_state = TCPS_FIN_WAIT_2; /*转移到FIN_WAIT_2状态*/
			}
			break;

	 	/*
		 * In CLOSING STATE in addition to the processing for
		 * the ESTABLISHED state if the ACK acknowledges our FIN
		 * then enter the TIME-WAIT state, otherwise ignore
		 * the segment.
		 */
		case TCPS_CLOSING: /*同时关闭??*/
			if (ourfinisacked) {
				tp->t_state = TCPS_TIME_WAIT;
				tcp_canceltimers(tp);
				tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
				soisdisconnected(so);
			}
			break;

		/*
		 * In LAST_ACK, we may still be waiting for data to drain
		 * and/or to be acked, as well as for the ack of our FIN.
		 * If our FIN is now acknowledged, delete the TCB,
		 * enter the closed state and return.
		 */
		case TCPS_LAST_ACK: /*服务端,已发送过FIN,等待接收最后一个ACK*/
			if (ourfinisacked) { /*FIN已被确认,关闭连接*/
				tp = tcp_close(tp);
				goto drop;
			}
			break;

		/*
		 * In TIME_WAIT state the only thing that should arrive
		 * is a retransmission of the remote FIN.  Acknowledge
		 * it and restart the finack timer.
		 */
		case TCPS_TIME_WAIT: /*如果对端发送的FIN丢失,对端会重传FIN(带有ACK),那么丢弃报文并重传ACK*/
			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL; /*重新启动TIME_WAIT定时器*/
			goto dropafterack;
		}
	}

step6:
	/*
	 * Update window information.
	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
	 */
	 /*snd_wl1记录最后接收报文段的序号(对端的序号),用于更新发送窗口*/
	 /*snd_wl2记录最后接收报文段的确认序号(本端的序号),用于更新发送窗口*/
	if ((tiflags & TH_ACK) && /*ACK标志置位*/
	    (SEQ_LT(tp->snd_wl1, ti->ti_seq) || tp->snd_wl1 == ti->ti_seq && /*报文携带了新数据*/
	    (SEQ_LT(tp->snd_wl2, ti->ti_ack) || /*未携带新数据,但确认了数据*/
	     tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))) { /*未携带新数据,未确认数据,但通告窗口大于当前发送窗口*/
		/* keep track of pure window updates */
		if (ti->ti_len == 0 &&
		    tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd) /*窗口更新报文统计*/
			tcpstat.tcps_rcvwinupd++;
		tp->snd_wnd = tiwin; /*更新发送窗口(由对端通告的)大小*/
		tp->snd_wl1 = ti->ti_seq; /*更新snd_wl1指针*/
		tp->snd_wl2 = ti->ti_ack; /*更新snd_wl2指针*/
		if (tp->snd_wnd > tp->max_sndwnd)
			tp->max_sndwnd = tp->snd_wnd;
		needoutput = 1; /*发送窗口已增大,发送更多数据!*/
	}

	/*
	 * If no out of band data is expected,
	 * pull receive urgent pointer along
	 * with the receive window.
	 */
	if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
		tp->rcv_up = tp->rcv_nxt;
dodata:							/* XXX */

	/*
	 * Process the segment text, merging it into the TCP sequencing queue,
	 * and arranging for acknowledgment of receipt if necessary.
	 * This process logically involves adjusting tp->rcv_wnd as data
	 * is presented to the user (this happens in tcp_usrreq.c,
	 * case PRU_RCVD).  If a FIN has already been received on this
	 * connection then we just ignore the text.
	 */
	if ((ti->ti_len || (tiflags&TH_FIN)) &&
	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
		TCP_REASS(tp, ti, m, so, tiflags); /*调用宏TCP_REASS处理数据*/
		/*
		 * Note the amount of data that peer has sent into
		 * our window, in order to estimate the sender's
		 * buffer size.
		 */
		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
	} else {
		m_freem(m);
		tiflags &= ~TH_FIN;
	}

	/*
	 * If FIN is received ACK the FIN and let the user know
	 * that the connection is closing.
	 */
	if (tiflags & TH_FIN) { /*处理FIN标志*/
		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
			socantrcvmore(so); /*不能再接收数据*/
			tp->t_flags |= TF_ACKNOW; /*立即发送ACK*/
			tp->rcv_nxt++;
		}
		switch (tp->t_state) {

	 	/*
		 * In SYN_RECEIVED and ESTABLISHED STATES
		 * enter the CLOSE_WAIT state.
		 */
		case TCPS_SYN_RECEIVED:
		case TCPS_ESTABLISHED:
			tp->t_state = TCPS_CLOSE_WAIT;
			break;

	 	/*
		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
		 * enter the CLOSING state.
		 */
		case TCPS_FIN_WAIT_1:
			tp->t_state = TCPS_CLOSING;
			break;

	 	/*
		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
		 * starting the time-wait timer, turning off the other 
		 * standard timers.
		 */
		case TCPS_FIN_WAIT_2: /*进入TIME_WAIT状态*/
			tp->t_state = TCPS_TIME_WAIT;
			tcp_canceltimers(tp);
			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
			soisdisconnected(so); /*连接已断开*/
			break;

		/*
		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
		 */
		case TCPS_TIME_WAIT:
			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
			break;
		}
	}

	/*
	 * Return any desired output.
	 */
	if (needoutput || (tp->t_flags & TF_ACKNOW)) /*如果要立即发送ACK或有更多的数据要发送,调用tcp_output*/
		(void) tcp_output(tp);
	return;

dropafterack: /*发送ACK,然后丢弃报文*/
	/*
	 * Generate an ACK dropping incoming segment if it occupies
	 * sequence space, where the ACK reflects our state.
	 */
	if (tiflags & TH_RST)
		goto drop;
	m_freem(m);
	tp->t_flags |= TF_ACKNOW;
	(void) tcp_output(tp);
	return;

dropwithreset: /*发送RST,然后丢弃报文*/
	/*
	 * Generate a RST, dropping incoming segment.
	 * Make ACK acceptable to originator of segment.
	 * Don't bother to respond if destination was broadcast/multicast.
	 */
	if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
	    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
		goto drop;
	if (tiflags & TH_ACK) /*带有ACK,RST报文序号字段是接收到的确认序列号,确认序列号字段是0*/
		tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
	else {
		if (tiflags & TH_SYN) /*如果到达的SYN请求与不存在的服务器建立连接,会执行这段代码*/
			ti->ti_len++;
		tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0, /*不带有ACK,RST报文带有ACK标志,
			序号字段是0,确认序列号字段是接收到的序号字段*/
		    TH_RST|TH_ACK);
	}
	/* destroy temporarily created socket */
	if (dropsocket)
		(void) soabort(so);
	return;

drop: /*直接丢弃报文*/
	/*
	 * Drop space held by incoming segment and return.
	 */
	m_freem(m);
	/* destroy temporarily created socket */
	if (dropsocket)
		(void) soabort(so);
	return;
}

sonewconn函数为新连接创建一个socket,它的代码如下:

/*
 * When an attempt at a new connection is noted on a socket
 * which accepts connections, sonewconn is called.  If the
 * connection is possible (subject to space constraints, etc.)
 * then we allocate a new structure, propoerly linked into the
 * data structure of the original socket, and return this.
 * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
 *
 * Currently, sonewconn() is defined as sonewconn1() in socketvar.h
 * to catch calls that are missing the (new) second parameter.
 */
struct socket *
sonewconn(head, connstatus)
	register struct socket *head;
	int connstatus;
{
	register struct socket *so;
	int soqueue = connstatus ? 1 : 0;

	if (head->so_qlen + head->so_q0len > 3 * head->so_qlimit / 2) /*不能再接收一个新连接,返回NULL*/
		return ((struct socket *)0);
	MALLOC(so, struct socket *, sizeof(*so), M_SOCKET, M_DONTWAIT); /*分配一个socket结构*/
	if (so == NULL) 
		return ((struct socket *)0);
	bzero((caddr_t)so, sizeof(*so));
	so->so_type = head->so_type;
	so->so_options = head->so_options &~ SO_ACCEPTCONN; /*去掉SO_ACCEPTCONN标志位,继承监听socket的选项*/
	so->so_linger = head->so_linger;
	so->so_state = head->so_state | SS_NOFDREF; /*该socket没有与描述符关联*/
	so->so_proto = head->so_proto;
	so->so_timeo = head->so_timeo;
	so->so_pgid = head->so_pgid;
	(void) soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat); /*设置socket的接收缓冲区和发送缓冲区大小*/
	soqinsque(head, so, soqueue); /*将socket加入等待完成三次握手的连接队列*/
	if ((*so->so_proto->pr_usrreq)(so, PRU_ATTACH, /*以PRU_ATTACH命令调用tcp_usrreq函数*/
	    (struct mbuf *)0, (struct mbuf *)0, (struct mbuf *)0)) { 
		(void) soqremque(so, soqueue);
		(void) free((caddr_t)so, M_SOCKET);
		return ((struct socket *)0);
	}
	if (connstatus) { /*连接已经建立*/
		sorwakeup(head); 
		wakeup((caddr_t)&head->so_timeo); /*唤醒等待在accept系统调用的进程!*/
		so->so_state |= connstatus;
	}
	return (so);
}

处理TCP连接请求的过程如下:


处理TCP选项的函数tcp_dooptions的代码如下:

void
tcp_dooptions(tp, cp, cnt, ti, ts_present, ts_val, ts_ecr)
	struct tcpcb *tp;
	u_char *cp;
	int cnt;
	struct tcpiphdr *ti;
	int *ts_present;
	u_long *ts_val, *ts_ecr;
{
	u_short mss;
	int opt, optlen;

	for (; cnt > 0; cnt -= optlen, cp += optlen) {
		opt = cp[0];
		if (opt == TCPOPT_EOL) /*选项结束*/
			break;
		if (opt == TCPOPT_NOP)
			optlen = 1;
		else {
			optlen = cp[1];
			if (optlen <= 0)
				break;
		}
		switch (opt) {

		default:
			continue;

		case TCPOPT_MAXSEG: /*MSS选项*/
			if (optlen != TCPOLEN_MAXSEG)
				continue;
			if (!(ti->ti_flags & TH_SYN))
				continue;
			bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
			NTOHS(mss);
			(void) tcp_mss(tp, mss);	/* 调用tcp_mss函数处理 */
			break;

		case TCPOPT_WINDOW: /*窗口缩放因子选项*/
			if (optlen != TCPOLEN_WINDOW)
				continue;
			if (!(ti->ti_flags & TH_SYN))
				continue;
			tp->t_flags |= TF_RCVD_SCALE;
			tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
			break;

		case TCPOPT_TIMESTAMP: /*时间戳选项*/
			if (optlen != TCPOLEN_TIMESTAMP)
				continue;
			*ts_present = 1;
			bcopy((char *)cp + 2, (char *) ts_val, sizeof(*ts_val));
			NTOHL(*ts_val);
			bcopy((char *)cp + 6, (char *) ts_ecr, sizeof(*ts_ecr));
			NTOHL(*ts_ecr);

			/* 
			 * A timestamp received in a SYN makes
			 * it ok to send timestamp requests and replies.
			 */
			if (ti->ti_flags & TH_SYN) { /*SYN报文的时间戳*/
				tp->t_flags |= TF_RCVD_TSTMP;
				tp->ts_recent = *ts_val;
				tp->ts_recent_age = tcp_now;
			}
			break;
		}
	}
}
处理接收数据的TCP_REASS宏定义如下:
/*
 * Insert segment ti into reassembly queue of tcp with
 * control block tp.  Return TH_FIN if reassembly now includes
 * a segment with FIN.  The macro form does the common case inline
 * (segment is the next to be received on an established connection,
 * and the queue is empty), avoiding linkage into and removal
 * from the queue and repetition of various conversions.
 * Set DELACK for segments received in order, but ack immediately
 * when segments are out of order (so fast retransmit can work).  2103
 */
#define	TCP_REASS(tp, ti, m, so, flags) { \
	if ((ti)->ti_seq == (tp)->rcv_nxt && \
	    (tp)->seg_next == (struct tcpiphdr *)(tp) && \
	    (tp)->t_state == TCPS_ESTABLISHED) { \
		tp->t_flags |= TF_DELACK; \
		(tp)->rcv_nxt += (ti)->ti_len; \
		flags = (ti)->ti_flags & TH_FIN; \
		tcpstat.tcps_rcvpack++;\
		tcpstat.tcps_rcvbyte += (ti)->ti_len;\
		sbappend(&(so)->so_rcv, (m)); \
		sorwakeup(so); \
	} else { \
		(flags) = tcp_reass((tp), (ti), (m)); \
		tp->t_flags |= TF_ACKNOW; \
	} \
}
如果到达的数据顺序正确 ,置上延迟ACK标志,更新rcv_nxt指针,并把数据添加到socket的接收缓冲区中。如果数据顺序错误,宏会调用tcp_reass函数,把数据加入到连接的重组队列中(新到数据有可能填充队列中的缺口,从而将已排队的数据添加到socket的接收缓冲区中)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值