tcp_input.c revision 107961
1/*
2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
34 * $FreeBSD: head/sys/netinet/tcp_input.c 107961 2002-12-17 00:24:48Z dillon $
35 */
36
37#include "opt_ipfw.h"		/* for ipfw_fwd		*/
38#include "opt_inet6.h"
39#include "opt_ipsec.h"
40#include "opt_mac.h"
41#include "opt_tcpdebug.h"
42#include "opt_tcp_input.h"
43
44#include <sys/param.h>
45#include <sys/kernel.h>
46#include <sys/mac.h>
47#include <sys/malloc.h>
48#include <sys/mbuf.h>
49#include <sys/proc.h>		/* for proc0 declaration */
50#include <sys/protosw.h>
51#include <sys/signalvar.h>
52#include <sys/socket.h>
53#include <sys/socketvar.h>
54#include <sys/sysctl.h>
55#include <sys/syslog.h>
56#include <sys/systm.h>
57
58#include <machine/cpu.h>	/* before tcp_seq.h, for tcp_random18() */
59
60#include <net/if.h>
61#include <net/route.h>
62
63#include <netinet/in.h>
64#include <netinet/in_pcb.h>
65#include <netinet/in_systm.h>
66#include <netinet/in_var.h>
67#include <netinet/ip.h>
68#include <netinet/ip_icmp.h>	/* for ICMP_BANDLIM		*/
69#include <netinet/icmp_var.h>	/* for ICMP_BANDLIM		*/
70#include <netinet/ip_var.h>
71#include <netinet/ip6.h>
72#include <netinet/icmp6.h>
73#include <netinet6/in6_pcb.h>
74#include <netinet6/ip6_var.h>
75#include <netinet6/nd6.h>
76#include <netinet/tcp.h>
77#include <netinet/tcp_fsm.h>
78#include <netinet/tcp_seq.h>
79#include <netinet/tcp_timer.h>
80#include <netinet/tcp_var.h>
81#include <netinet6/tcp6_var.h>
82#include <netinet/tcpip.h>
83#ifdef TCPDEBUG
84#include <netinet/tcp_debug.h>
85#endif /* TCPDEBUG */
86
87#ifdef FAST_IPSEC
88#include <netipsec/ipsec.h>
89#include <netipsec/ipsec6.h>
90#endif /*FAST_IPSEC*/
91
92#ifdef IPSEC
93#include <netinet6/ipsec.h>
94#include <netinet6/ipsec6.h>
95#include <netkey/key.h>
96#endif /*IPSEC*/
97
98#include <machine/in_cksum.h>
99
100MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
101
102static const int tcprexmtthresh = 3;
103tcp_cc	tcp_ccgen;
104
105struct	tcpstat tcpstat;
106SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
107    &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
108
109static int log_in_vain = 0;
110SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
111    &log_in_vain, 0, "Log all incoming TCP connections");
112
113static int blackhole = 0;
114SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
115	&blackhole, 0, "Do not send RST when dropping refused connections");
116
117int tcp_delack_enabled = 1;
118SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
119    &tcp_delack_enabled, 0,
120    "Delay ACK to try and piggyback it onto a data packet");
121
122#ifdef TCP_DROP_SYNFIN
123static int drop_synfin = 0;
124SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
125    &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
126#endif
127
128struct inpcbhead tcb;
129#define	tcb6	tcb  /* for KAME src sync over BSD*'s */
130struct inpcbinfo tcbinfo;
131struct mtx	*tcbinfo_mtx;
132
133static void	 tcp_dooptions(struct tcpopt *, u_char *, int, int);
134static void	 tcp_pulloutofband(struct socket *,
135		     struct tcphdr *, struct mbuf *, int);
136static int	 tcp_reass(struct tcpcb *, struct tcphdr *, int *,
137		     struct mbuf *);
138static void	 tcp_xmit_timer(struct tcpcb *, int);
139static void	 tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
140
141/* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
142#ifdef INET6
143#define ND6_HINT(tp) \
144do { \
145	if ((tp) && (tp)->t_inpcb && \
146	    ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
147	    (tp)->t_inpcb->in6p_route.ro_rt) \
148		nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
149} while (0)
150#else
151#define ND6_HINT(tp)
152#endif
153
154/*
155 * Indicate whether this ack should be delayed.  We can delay the ack if
156 *	- delayed acks are enabled and
157 *	- there is no delayed ack timer in progress and
158 *	- our last ack wasn't a 0-sized window.  We never want to delay
159 *	  the ack that opens up a 0-sized window.
160 */
161#define DELAY_ACK(tp) \
162	(tcp_delack_enabled && !callout_pending(tp->tt_delack) && \
163	(tp->t_flags & TF_RXWIN0SENT) == 0)
164
165static int
166tcp_reass(tp, th, tlenp, m)
167	register struct tcpcb *tp;
168	register struct tcphdr *th;
169	int *tlenp;
170	struct mbuf *m;
171{
172	struct tseg_qent *q;
173	struct tseg_qent *p = NULL;
174	struct tseg_qent *nq;
175	struct tseg_qent *te;
176	struct socket *so = tp->t_inpcb->inp_socket;
177	int flags;
178
179	/*
180	 * Call with th==0 after become established to
181	 * force pre-ESTABLISHED data up to user socket.
182	 */
183	if (th == 0)
184		goto present;
185
186	/* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
187	MALLOC(te, struct tseg_qent *, sizeof (struct tseg_qent), M_TSEGQ,
188	       M_NOWAIT);
189	if (te == NULL) {
190		tcpstat.tcps_rcvmemdrop++;
191		m_freem(m);
192		return (0);
193	}
194
195	/*
196	 * Find a segment which begins after this one does.
197	 */
198	LIST_FOREACH(q, &tp->t_segq, tqe_q) {
199		if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
200			break;
201		p = q;
202	}
203
204	/*
205	 * If there is a preceding segment, it may provide some of
206	 * our data already.  If so, drop the data from the incoming
207	 * segment.  If it provides all of our data, drop us.
208	 */
209	if (p != NULL) {
210		register int i;
211		/* conversion to int (in i) handles seq wraparound */
212		i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
213		if (i > 0) {
214			if (i >= *tlenp) {
215				tcpstat.tcps_rcvduppack++;
216				tcpstat.tcps_rcvdupbyte += *tlenp;
217				m_freem(m);
218				FREE(te, M_TSEGQ);
219				/*
220				 * Try to present any queued data
221				 * at the left window edge to the user.
222				 * This is needed after the 3-WHS
223				 * completes.
224				 */
225				goto present;	/* ??? */
226			}
227			m_adj(m, i);
228			*tlenp -= i;
229			th->th_seq += i;
230		}
231	}
232	tcpstat.tcps_rcvoopack++;
233	tcpstat.tcps_rcvoobyte += *tlenp;
234
235	/*
236	 * While we overlap succeeding segments trim them or,
237	 * if they are completely covered, dequeue them.
238	 */
239	while (q) {
240		register int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
241		if (i <= 0)
242			break;
243		if (i < q->tqe_len) {
244			q->tqe_th->th_seq += i;
245			q->tqe_len -= i;
246			m_adj(q->tqe_m, i);
247			break;
248		}
249
250		nq = LIST_NEXT(q, tqe_q);
251		LIST_REMOVE(q, tqe_q);
252		m_freem(q->tqe_m);
253		FREE(q, M_TSEGQ);
254		q = nq;
255	}
256
257	/* Insert the new segment queue entry into place. */
258	te->tqe_m = m;
259	te->tqe_th = th;
260	te->tqe_len = *tlenp;
261
262	if (p == NULL) {
263		LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
264	} else {
265		LIST_INSERT_AFTER(p, te, tqe_q);
266	}
267
268present:
269	/*
270	 * Present data to user, advancing rcv_nxt through
271	 * completed sequence space.
272	 */
273	if (!TCPS_HAVEESTABLISHED(tp->t_state))
274		return (0);
275	q = LIST_FIRST(&tp->t_segq);
276	if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
277		return (0);
278	do {
279		tp->rcv_nxt += q->tqe_len;
280		flags = q->tqe_th->th_flags & TH_FIN;
281		nq = LIST_NEXT(q, tqe_q);
282		LIST_REMOVE(q, tqe_q);
283		if (so->so_state & SS_CANTRCVMORE)
284			m_freem(q->tqe_m);
285		else
286			sbappend(&so->so_rcv, q->tqe_m);
287		FREE(q, M_TSEGQ);
288		q = nq;
289	} while (q && q->tqe_th->th_seq == tp->rcv_nxt);
290	ND6_HINT(tp);
291	sorwakeup(so);
292	return (flags);
293}
294
295/*
296 * TCP input routine, follows pages 65-76 of the
297 * protocol specification dated September, 1981 very closely.
298 */
299#ifdef INET6
300int
301tcp6_input(mp, offp, proto)
302	struct mbuf **mp;
303	int *offp, proto;
304{
305	register struct mbuf *m = *mp;
306	struct in6_ifaddr *ia6;
307
308	IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
309
310	/*
311	 * draft-itojun-ipv6-tcp-to-anycast
312	 * better place to put this in?
313	 */
314	ia6 = ip6_getdstifaddr(m);
315	if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
316		struct ip6_hdr *ip6;
317
318		ip6 = mtod(m, struct ip6_hdr *);
319		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
320			    (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
321		return IPPROTO_DONE;
322	}
323
324	tcp_input(m, *offp);
325	return IPPROTO_DONE;
326}
327#endif
328
329void
330tcp_input(m, off0)
331	register struct mbuf *m;
332	int off0;
333{
334	register struct tcphdr *th;
335	register struct ip *ip = NULL;
336	register struct ipovly *ipov;
337	register struct inpcb *inp = NULL;
338	u_char *optp = NULL;
339	int optlen = 0;
340	int len, tlen, off;
341	int drop_hdrlen;
342	register struct tcpcb *tp = 0;
343	register int thflags;
344	struct socket *so = 0;
345	int todrop, acked, ourfinisacked, needoutput = 0;
346	u_long tiwin;
347	struct tcpopt to;		/* options in this segment */
348	struct rmxp_tao *taop;		/* pointer to our TAO cache entry */
349	struct rmxp_tao	tao_noncached;	/* in case there's no cached entry */
350	int headlocked = 0;
351	struct sockaddr_in *next_hop = NULL;
352	int rstreason; /* For badport_bandlim accounting purposes */
353
354	struct ip6_hdr *ip6 = NULL;
355#ifdef INET6
356	int isipv6;
357#else
358	const int isipv6 = 0;
359#endif
360
361#ifdef TCPDEBUG
362	/*
363	 * The size of tcp_saveipgen must be the size of the max ip header,
364	 * now IPv6.
365	 */
366	u_char tcp_saveipgen[40];
367	struct tcphdr tcp_savetcp;
368	short ostate = 0;
369#endif
370
371#ifdef MAC
372	int error;
373#endif
374
375	/* Grab info from MT_TAG mbufs prepended to the chain. */
376	for (;m && m->m_type == MT_TAG; m = m->m_next) {
377		if (m->_m_tag_id == PACKET_TAG_IPFORWARD)
378			next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
379	}
380#ifdef INET6
381	isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
382#endif
383	bzero((char *)&to, sizeof(to));
384
385	tcpstat.tcps_rcvtotal++;
386
387	if (isipv6) {
388		/* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
389		ip6 = mtod(m, struct ip6_hdr *);
390		tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
391		if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
392			tcpstat.tcps_rcvbadsum++;
393			goto drop;
394		}
395		th = (struct tcphdr *)((caddr_t)ip6 + off0);
396
397		/*
398		 * Be proactive about unspecified IPv6 address in source.
399		 * As we use all-zero to indicate unbounded/unconnected pcb,
400		 * unspecified IPv6 address can be used to confuse us.
401		 *
402		 * Note that packets with unspecified IPv6 destination is
403		 * already dropped in ip6_input.
404		 */
405		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
406			/* XXX stat */
407			goto drop;
408		}
409	} else {
410		/*
411		 * Get IP and TCP header together in first mbuf.
412		 * Note: IP leaves IP header in first mbuf.
413		 */
414		if (off0 > sizeof (struct ip)) {
415			ip_stripoptions(m, (struct mbuf *)0);
416			off0 = sizeof(struct ip);
417		}
418		if (m->m_len < sizeof (struct tcpiphdr)) {
419			if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
420				tcpstat.tcps_rcvshort++;
421				return;
422			}
423		}
424		ip = mtod(m, struct ip *);
425		ipov = (struct ipovly *)ip;
426		th = (struct tcphdr *)((caddr_t)ip + off0);
427		tlen = ip->ip_len;
428
429		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
430			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
431				th->th_sum = m->m_pkthdr.csum_data;
432			else
433				th->th_sum = in_pseudo(ip->ip_src.s_addr,
434						ip->ip_dst.s_addr,
435						htonl(m->m_pkthdr.csum_data +
436							ip->ip_len +
437							IPPROTO_TCP));
438			th->th_sum ^= 0xffff;
439		} else {
440			/*
441			 * Checksum extended TCP header and data.
442			 */
443			len = sizeof (struct ip) + tlen;
444			bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
445			ipov->ih_len = (u_short)tlen;
446			ipov->ih_len = htons(ipov->ih_len);
447			th->th_sum = in_cksum(m, len);
448		}
449		if (th->th_sum) {
450			tcpstat.tcps_rcvbadsum++;
451			goto drop;
452		}
453#ifdef INET6
454		/* Re-initialization for later version check */
455		ip->ip_v = IPVERSION;
456#endif
457	}
458
459	/*
460	 * Check that TCP offset makes sense,
461	 * pull out TCP options and adjust length.		XXX
462	 */
463	off = th->th_off << 2;
464	if (off < sizeof (struct tcphdr) || off > tlen) {
465		tcpstat.tcps_rcvbadoff++;
466		goto drop;
467	}
468	tlen -= off;	/* tlen is used instead of ti->ti_len */
469	if (off > sizeof (struct tcphdr)) {
470		if (isipv6) {
471			IP6_EXTHDR_CHECK(m, off0, off, );
472			ip6 = mtod(m, struct ip6_hdr *);
473			th = (struct tcphdr *)((caddr_t)ip6 + off0);
474		} else {
475			if (m->m_len < sizeof(struct ip) + off) {
476				if ((m = m_pullup(m, sizeof (struct ip) + off))
477						== 0) {
478					tcpstat.tcps_rcvshort++;
479					return;
480				}
481				ip = mtod(m, struct ip *);
482				ipov = (struct ipovly *)ip;
483				th = (struct tcphdr *)((caddr_t)ip + off0);
484			}
485		}
486		optlen = off - sizeof (struct tcphdr);
487		optp = (u_char *)(th + 1);
488	}
489	thflags = th->th_flags;
490
491#ifdef TCP_DROP_SYNFIN
492	/*
493	 * If the drop_synfin option is enabled, drop all packets with
494	 * both the SYN and FIN bits set. This prevents e.g. nmap from
495	 * identifying the TCP/IP stack.
496	 *
497	 * This is a violation of the TCP specification.
498	 */
499	if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
500		goto drop;
501#endif
502
503	/*
504	 * Convert TCP protocol specific fields to host format.
505	 */
506	th->th_seq = ntohl(th->th_seq);
507	th->th_ack = ntohl(th->th_ack);
508	th->th_win = ntohs(th->th_win);
509	th->th_urp = ntohs(th->th_urp);
510
511	/*
512	 * Delay droping TCP, IP headers, IPv6 ext headers, and TCP options,
513	 * until after ip6_savecontrol() is called and before other functions
514	 * which don't want those proto headers.
515	 * Because ip6_savecontrol() is going to parse the mbuf to
516	 * search for data to be passed up to user-land, it wants mbuf
517	 * parameters to be unchanged.
518	 * XXX: the call of ip6_savecontrol() has been obsoleted based on
519	 * latest version of the advanced API (20020110).
520	 */
521	drop_hdrlen = off0 + off;
522
523	/*
524	 * Locate pcb for segment.
525	 */
526	INP_INFO_WLOCK(&tcbinfo);
527	headlocked = 1;
528findpcb:
529	/* IPFIREWALL_FORWARD section */
530	if (next_hop != NULL && isipv6 == 0) {	/* IPv6 support is not yet */
531		/*
532		 * Transparently forwarded. Pretend to be the destination.
533		 * already got one like this?
534		 */
535		inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
536					ip->ip_dst, th->th_dport,
537					0, m->m_pkthdr.rcvif);
538		if (!inp) {
539			/* It's new.  Try find the ambushing socket. */
540			inp = in_pcblookup_hash(&tcbinfo,
541						ip->ip_src, th->th_sport,
542						next_hop->sin_addr,
543						next_hop->sin_port ?
544						    ntohs(next_hop->sin_port) :
545						    th->th_dport,
546						1, m->m_pkthdr.rcvif);
547		}
548	} else {
549		if (isipv6)
550			inp = in6_pcblookup_hash(&tcbinfo,
551						 &ip6->ip6_src, th->th_sport,
552						 &ip6->ip6_dst, th->th_dport,
553						 1, m->m_pkthdr.rcvif);
554		else
555			inp = in_pcblookup_hash(&tcbinfo,
556						ip->ip_src, th->th_sport,
557						ip->ip_dst, th->th_dport,
558						1, m->m_pkthdr.rcvif);
559      }
560
561#ifdef IPSEC
562	if (isipv6) {
563		if (inp != NULL && ipsec6_in_reject_so(m, inp->inp_socket)) {
564			ipsec6stat.in_polvio++;
565			goto drop;
566		}
567	} else {
568		if (inp != NULL && ipsec4_in_reject_so(m, inp->inp_socket)) {
569			ipsecstat.in_polvio++;
570			goto drop;
571		}
572	}
573#endif
574#ifdef FAST_IPSEC
575	if (isipv6) {
576		if (inp != NULL && ipsec6_in_reject(m, inp)) {
577			goto drop;
578		}
579	} else
580	if (inp != NULL && ipsec4_in_reject(m, inp)) {
581		goto drop;
582	}
583#endif /*FAST_IPSEC*/
584
585	/*
586	 * If the state is CLOSED (i.e., TCB does not exist) then
587	 * all data in the incoming segment is discarded.
588	 * If the TCB exists but is in CLOSED state, it is embryonic,
589	 * but should either do a listen or a connect soon.
590	 */
591	if (inp == NULL) {
592		if (log_in_vain) {
593#ifdef INET6
594			char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
595#else
596			char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
597#endif
598
599			if (isipv6) {
600				strcpy(dbuf, "[");
601				strcpy(sbuf, "[");
602				strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
603				strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
604				strcat(dbuf, "]");
605				strcat(sbuf, "]");
606			} else {
607				strcpy(dbuf, inet_ntoa(ip->ip_dst));
608				strcpy(sbuf, inet_ntoa(ip->ip_src));
609			}
610			switch (log_in_vain) {
611			case 1:
612				if (thflags & TH_SYN)
613					log(LOG_INFO,
614					    "Connection attempt to TCP %s:%d "
615					    "from %s:%d\n",
616					    dbuf, ntohs(th->th_dport), sbuf,
617					    ntohs(th->th_sport));
618				break;
619			case 2:
620				log(LOG_INFO,
621				    "Connection attempt to TCP %s:%d "
622				    "from %s:%d flags:0x%x\n",
623				    dbuf, ntohs(th->th_dport), sbuf,
624				    ntohs(th->th_sport), thflags);
625				break;
626			default:
627				break;
628			}
629		}
630		if (blackhole) {
631			switch (blackhole) {
632			case 1:
633				if (thflags & TH_SYN)
634					goto drop;
635				break;
636			case 2:
637				goto drop;
638			default:
639				goto drop;
640			}
641		}
642		rstreason = BANDLIM_RST_CLOSEDPORT;
643		goto dropwithreset;
644	}
645	INP_LOCK(inp);
646	tp = intotcpcb(inp);
647	if (tp == 0) {
648		INP_UNLOCK(inp);
649		rstreason = BANDLIM_RST_CLOSEDPORT;
650		goto dropwithreset;
651	}
652	if (tp->t_state == TCPS_CLOSED)
653		goto drop;
654
655	/* Unscale the window into a 32-bit value. */
656	if ((thflags & TH_SYN) == 0)
657		tiwin = th->th_win << tp->snd_scale;
658	else
659		tiwin = th->th_win;
660
661	so = inp->inp_socket;
662#ifdef MAC
663	error = mac_check_socket_deliver(so, m);
664	if (error)
665		goto drop;
666#endif
667	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
668		struct in_conninfo inc;
669#ifdef TCPDEBUG
670		if (so->so_options & SO_DEBUG) {
671			ostate = tp->t_state;
672			if (isipv6)
673				bcopy((char *)ip6, (char *)tcp_saveipgen,
674					sizeof(*ip6));
675			else
676				bcopy((char *)ip, (char *)tcp_saveipgen,
677					sizeof(*ip));
678			tcp_savetcp = *th;
679		}
680#endif
681		/* skip if this isn't a listen socket */
682		if ((so->so_options & SO_ACCEPTCONN) == 0)
683			goto after_listen;
684#ifdef INET6
685		inc.inc_isipv6 = isipv6;
686#endif
687		if (isipv6) {
688			inc.inc6_faddr = ip6->ip6_src;
689			inc.inc6_laddr = ip6->ip6_dst;
690			inc.inc6_route.ro_rt = NULL;		/* XXX */
691		} else {
692			inc.inc_faddr = ip->ip_src;
693			inc.inc_laddr = ip->ip_dst;
694			inc.inc_route.ro_rt = NULL;		/* XXX */
695		}
696		inc.inc_fport = th->th_sport;
697		inc.inc_lport = th->th_dport;
698
699	        /*
700	         * If the state is LISTEN then ignore segment if it contains
701		 * a RST.  If the segment contains an ACK then it is bad and
702		 * send a RST.  If it does not contain a SYN then it is not
703		 * interesting; drop it.
704		 *
705		 * If the state is SYN_RECEIVED (syncache) and seg contains
706		 * an ACK, but not for our SYN/ACK, send a RST.  If the seg
707		 * contains a RST, check the sequence number to see if it
708		 * is a valid reset segment.
709		 */
710		if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
711			if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
712				if (!syncache_expand(&inc, th, &so, m)) {
713					/*
714					 * No syncache entry, or ACK was not
715					 * for our SYN/ACK.  Send a RST.
716					 */
717					tcpstat.tcps_badsyn++;
718					rstreason = BANDLIM_RST_OPENPORT;
719					goto dropwithreset;
720				}
721				if (so == NULL) {
722					/*
723					 * Could not complete 3-way handshake,
724					 * connection is being closed down, and
725					 * syncache will free mbuf.
726					 */
727					INP_UNLOCK(inp);
728					INP_INFO_WUNLOCK(&tcbinfo);
729					return;
730				}
731				/*
732				 * Socket is created in state SYN_RECEIVED.
733				 * Continue processing segment.
734				 */
735				INP_UNLOCK(inp);
736				inp = sotoinpcb(so);
737				INP_LOCK(inp);
738				tp = intotcpcb(inp);
739				/*
740				 * This is what would have happened in
741				 * tcp_output() when the SYN,ACK was sent.
742				 */
743				tp->snd_up = tp->snd_una;
744				tp->snd_max = tp->snd_nxt = tp->iss + 1;
745				tp->last_ack_sent = tp->rcv_nxt;
746/*
747 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
748 * until the _second_ ACK is received:
749 *    rcv SYN (set wscale opts)	 --> send SYN/ACK, set snd_wnd = window.
750 *    rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
751 *        move to ESTAB, set snd_wnd to tiwin.
752 */
753				tp->snd_wnd = tiwin;	/* unscaled */
754				goto after_listen;
755			}
756			if (thflags & TH_RST) {
757				syncache_chkrst(&inc, th);
758				goto drop;
759			}
760			if (thflags & TH_ACK) {
761				syncache_badack(&inc);
762				tcpstat.tcps_badsyn++;
763				rstreason = BANDLIM_RST_OPENPORT;
764				goto dropwithreset;
765			}
766			goto drop;
767		}
768
769		/*
770		 * Segment's flags are (SYN) or (SYN|FIN).
771		 */
772#ifdef INET6
773		/*
774		 * If deprecated address is forbidden,
775		 * we do not accept SYN to deprecated interface
776		 * address to prevent any new inbound connection from
777		 * getting established.
778		 * When we do not accept SYN, we send a TCP RST,
779		 * with deprecated source address (instead of dropping
780		 * it).  We compromise it as it is much better for peer
781		 * to send a RST, and RST will be the final packet
782		 * for the exchange.
783		 *
784		 * If we do not forbid deprecated addresses, we accept
785		 * the SYN packet.  RFC2462 does not suggest dropping
786		 * SYN in this case.
787		 * If we decipher RFC2462 5.5.4, it says like this:
788		 * 1. use of deprecated addr with existing
789		 *    communication is okay - "SHOULD continue to be
790		 *    used"
791		 * 2. use of it with new communication:
792		 *   (2a) "SHOULD NOT be used if alternate address
793		 *        with sufficient scope is available"
794		 *   (2b) nothing mentioned otherwise.
795		 * Here we fall into (2b) case as we have no choice in
796		 * our source address selection - we must obey the peer.
797		 *
798		 * The wording in RFC2462 is confusing, and there are
799		 * multiple description text for deprecated address
800		 * handling - worse, they are not exactly the same.
801		 * I believe 5.5.4 is the best one, so we follow 5.5.4.
802		 */
803		if (isipv6 && !ip6_use_deprecated) {
804			struct in6_ifaddr *ia6;
805
806			if ((ia6 = ip6_getdstifaddr(m)) &&
807			    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
808				INP_UNLOCK(inp);
809				tp = NULL;
810				rstreason = BANDLIM_RST_OPENPORT;
811				goto dropwithreset;
812			}
813		}
814#endif
815		/*
816		 * If it is from this socket, drop it, it must be forged.
817		 * Don't bother responding if the destination was a broadcast.
818		 */
819		if (th->th_dport == th->th_sport) {
820			if (isipv6) {
821				if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
822						       &ip6->ip6_src))
823					goto drop;
824			} else {
825				if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
826					goto drop;
827			}
828		}
829		/*
830		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
831		 *
832		 * Note that it is quite possible to receive unicast
833		 * link-layer packets with a broadcast IP address. Use
834		 * in_broadcast() to find them.
835		 */
836		if (m->m_flags & (M_BCAST|M_MCAST))
837			goto drop;
838		if (isipv6) {
839			if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
840			    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
841				goto drop;
842		} else {
843			if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
844			    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
845			    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
846			    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
847				goto drop;
848		}
849		/*
850		 * SYN appears to be valid; create compressed TCP state
851		 * for syncache, or perform t/tcp connection.
852		 */
853		if (so->so_qlen <= so->so_qlimit) {
854			tcp_dooptions(&to, optp, optlen, 1);
855			if (!syncache_add(&inc, &to, th, &so, m))
856				goto drop;
857			if (so == NULL) {
858				/*
859				 * Entry added to syncache, mbuf used to
860				 * send SYN,ACK packet.
861				 */
862				KASSERT(headlocked, ("headlocked"));
863				INP_UNLOCK(inp);
864				INP_INFO_WUNLOCK(&tcbinfo);
865				return;
866			}
867			/*
868			 * Segment passed TAO tests.
869			 */
870			INP_UNLOCK(inp);
871			inp = sotoinpcb(so);
872			INP_LOCK(inp);
873			tp = intotcpcb(inp);
874			tp->snd_wnd = tiwin;
875			tp->t_starttime = ticks;
876			tp->t_state = TCPS_ESTABLISHED;
877
878			/*
879			 * If there is a FIN, or if there is data and the
880			 * connection is local, then delay SYN,ACK(SYN) in
881			 * the hope of piggy-backing it on a response
882			 * segment.  Otherwise must send ACK now in case
883			 * the other side is slow starting.
884			 */
885			if (DELAY_ACK(tp) &&
886			    ((thflags & TH_FIN) ||
887			     (tlen != 0 &&
888			      ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
889			       (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
890				callout_reset(tp->tt_delack, tcp_delacktime,
891						tcp_timer_delack, tp);
892				tp->t_flags |= TF_NEEDSYN;
893			} else
894				tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
895
896			tcpstat.tcps_connects++;
897			soisconnected(so);
898			goto trimthenstep6;
899		}
900		goto drop;
901	}
902after_listen:
903
904/* XXX temp debugging */
905	/* should not happen - syncache should pick up these connections */
906	if (tp->t_state == TCPS_LISTEN)
907		panic("tcp_input: TCPS_LISTEN");
908
909	/*
910	 * Segment received on connection.
911	 * Reset idle time and keep-alive timer.
912	 */
913	tp->t_rcvtime = ticks;
914	if (TCPS_HAVEESTABLISHED(tp->t_state))
915		callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
916
917	/*
918	 * Process options.
919	 * XXX this is tradtitional behavior, may need to be cleaned up.
920	 */
921	tcp_dooptions(&to, optp, optlen, thflags & TH_SYN);
922	if (thflags & TH_SYN) {
923		if (to.to_flags & TOF_SCALE) {
924			tp->t_flags |= TF_RCVD_SCALE;
925			tp->requested_s_scale = to.to_requested_s_scale;
926		}
927		if (to.to_flags & TOF_TS) {
928			tp->t_flags |= TF_RCVD_TSTMP;
929			tp->ts_recent = to.to_tsval;
930			tp->ts_recent_age = ticks;
931		}
932		if (to.to_flags & (TOF_CC|TOF_CCNEW))
933			tp->t_flags |= TF_RCVD_CC;
934		if (to.to_flags & TOF_MSS)
935			tcp_mss(tp, to.to_mss);
936	}
937
938	/*
939	 * Header prediction: check for the two common cases
940	 * of a uni-directional data xfer.  If the packet has
941	 * no control flags, is in-sequence, the window didn't
942	 * change and we're not retransmitting, it's a
943	 * candidate.  If the length is zero and the ack moved
944	 * forward, we're the sender side of the xfer.  Just
945	 * free the data acked & wake any higher level process
946	 * that was blocked waiting for space.  If the length
947	 * is non-zero and the ack didn't move, we're the
948	 * receiver side.  If we're getting packets in-order
949	 * (the reassembly queue is empty), add the data to
950	 * the socket buffer and note that we need a delayed ack.
951	 * Make sure that the hidden state-flags are also off.
952	 * Since we check for TCPS_ESTABLISHED above, it can only
953	 * be TH_NEEDSYN.
954	 */
955	if (tp->t_state == TCPS_ESTABLISHED &&
956	    (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
957	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
958	    ((to.to_flags & TOF_TS) == 0 ||
959	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
960	    /*
961	     * Using the CC option is compulsory if once started:
962	     *   the segment is OK if no T/TCP was negotiated or
963	     *   if the segment has a CC option equal to CCrecv
964	     */
965	    ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
966	     ((to.to_flags & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
967	    th->th_seq == tp->rcv_nxt &&
968	    tiwin && tiwin == tp->snd_wnd &&
969	    tp->snd_nxt == tp->snd_max) {
970
971		/*
972		 * If last ACK falls within this segment's sequence numbers,
973		 * record the timestamp.
974		 * NOTE that the test is modified according to the latest
975		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
976		 */
977		if ((to.to_flags & TOF_TS) != 0 &&
978		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
979			tp->ts_recent_age = ticks;
980			tp->ts_recent = to.to_tsval;
981		}
982
983		if (tlen == 0) {
984			if (SEQ_GT(th->th_ack, tp->snd_una) &&
985			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
986			    tp->snd_cwnd >= tp->snd_wnd &&
987			    tp->t_dupacks < tcprexmtthresh) {
988				KASSERT(headlocked, ("headlocked"));
989				INP_INFO_WUNLOCK(&tcbinfo);
990				headlocked = 0;
991				/*
992				 * this is a pure ack for outstanding data.
993				 */
994				++tcpstat.tcps_predack;
995				/*
996				 * "bad retransmit" recovery
997				 */
998				if (tp->t_rxtshift == 1 &&
999				    ticks < tp->t_badrxtwin) {
1000					tp->snd_cwnd = tp->snd_cwnd_prev;
1001					tp->snd_ssthresh =
1002					    tp->snd_ssthresh_prev;
1003					tp->snd_nxt = tp->snd_max;
1004					tp->t_badrxtwin = 0;
1005				}
1006
1007				/*
1008				 * Recalculate the transmit timer / rtt.
1009				 *
1010				 * Some boxes send broken timestamp replies
1011				 * during the SYN+ACK phase, ignore
1012				 * timestamps of 0 or we could calculate a
1013				 * huge RTT and blow up the retransmit timer.
1014				 */
1015				if ((to.to_flags & TOF_TS) != 0 &&
1016				    to.to_tsecr) {
1017					tcp_xmit_timer(tp,
1018					    ticks - to.to_tsecr + 1);
1019				} else if (tp->t_rtttime &&
1020					    SEQ_GT(th->th_ack, tp->t_rtseq)) {
1021					tcp_xmit_timer(tp,
1022							ticks - tp->t_rtttime);
1023				}
1024				tcp_xmit_bandwidth_limit(tp, th->th_ack);
1025				acked = th->th_ack - tp->snd_una;
1026				tcpstat.tcps_rcvackpack++;
1027				tcpstat.tcps_rcvackbyte += acked;
1028				sbdrop(&so->so_snd, acked);
1029				/*
1030				 * pull snd_wl2 up to prevent seq wrap relative
1031				 * to th_ack.
1032				 */
1033				tp->snd_wl2 = tp->snd_una = th->th_ack;
1034				tp->t_dupacks = 0;
1035				m_freem(m);
1036				ND6_HINT(tp); /* some progress has been done */
1037
1038				/*
1039				 * If all outstanding data are acked, stop
1040				 * retransmit timer, otherwise restart timer
1041				 * using current (possibly backed-off) value.
1042				 * If process is waiting for space,
1043				 * wakeup/selwakeup/signal.  If data
1044				 * are ready to send, let tcp_output
1045				 * decide between more output or persist.
1046				 */
1047				if (tp->snd_una == tp->snd_max)
1048					callout_stop(tp->tt_rexmt);
1049				else if (!callout_active(tp->tt_persist))
1050					callout_reset(tp->tt_rexmt,
1051						      tp->t_rxtcur,
1052						      tcp_timer_rexmt, tp);
1053
1054				sowwakeup(so);
1055				if (so->so_snd.sb_cc)
1056					(void) tcp_output(tp);
1057				INP_UNLOCK(inp);
1058				return;
1059			}
1060		} else if (th->th_ack == tp->snd_una &&
1061		    LIST_EMPTY(&tp->t_segq) &&
1062		    tlen <= sbspace(&so->so_rcv)) {
1063			KASSERT(headlocked, ("headlocked"));
1064			INP_INFO_WUNLOCK(&tcbinfo);
1065			headlocked = 0;
1066			/*
1067			 * this is a pure, in-sequence data packet
1068			 * with nothing on the reassembly queue and
1069			 * we have enough buffer space to take it.
1070			 */
1071			++tcpstat.tcps_preddat;
1072			tp->rcv_nxt += tlen;
1073			/*
1074			 * Pull snd_wl1 up to prevent seq wrap relative to
1075			 * th_seq.
1076			 */
1077			tp->snd_wl1 = th->th_seq;
1078			/*
1079			 * Pull rcv_up up to prevent seq wrap relative to
1080			 * rcv_nxt.
1081			 */
1082			tp->rcv_up = tp->rcv_nxt;
1083			tcpstat.tcps_rcvpack++;
1084			tcpstat.tcps_rcvbyte += tlen;
1085			ND6_HINT(tp);	/* some progress has been done */
1086			/*
1087			 * Add data to socket buffer.
1088			 */
1089			if (so->so_state & SS_CANTRCVMORE) {
1090				m_freem(m);
1091			} else {
1092				m_adj(m, drop_hdrlen);	/* delayed header drop */
1093				sbappend(&so->so_rcv, m);
1094			}
1095			sorwakeup(so);
1096			if (DELAY_ACK(tp)) {
1097	                        callout_reset(tp->tt_delack, tcp_delacktime,
1098	                            tcp_timer_delack, tp);
1099			} else {
1100				tp->t_flags |= TF_ACKNOW;
1101				tcp_output(tp);
1102			}
1103			INP_UNLOCK(inp);
1104			return;
1105		}
1106	}
1107
1108	/*
1109	 * Calculate amount of space in receive window,
1110	 * and then do TCP input processing.
1111	 * Receive window is amount of space in rcv queue,
1112	 * but not less than advertised window.
1113	 */
1114	{ int win;
1115
1116	win = sbspace(&so->so_rcv);
1117	if (win < 0)
1118		win = 0;
1119	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1120	}
1121
1122	switch (tp->t_state) {
1123
1124	/*
1125	 * If the state is SYN_RECEIVED:
1126	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
1127	 */
1128	case TCPS_SYN_RECEIVED:
1129		if ((thflags & TH_ACK) &&
1130		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1131		     SEQ_GT(th->th_ack, tp->snd_max))) {
1132				rstreason = BANDLIM_RST_OPENPORT;
1133				goto dropwithreset;
1134		}
1135		break;
1136
1137	/*
1138	 * If the state is SYN_SENT:
1139	 *	if seg contains an ACK, but not for our SYN, drop the input.
1140	 *	if seg contains a RST, then drop the connection.
1141	 *	if seg does not contain SYN, then drop it.
1142	 * Otherwise this is an acceptable SYN segment
1143	 *	initialize tp->rcv_nxt and tp->irs
1144	 *	if seg contains ack then advance tp->snd_una
1145	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1146	 *	arrange for segment to be acked (eventually)
1147	 *	continue processing rest of data/controls, beginning with URG
1148	 */
1149	case TCPS_SYN_SENT:
1150		if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1151			taop = &tao_noncached;
1152			bzero(taop, sizeof(*taop));
1153		}
1154
1155		if ((thflags & TH_ACK) &&
1156		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1157		     SEQ_GT(th->th_ack, tp->snd_max))) {
1158			/*
1159			 * If we have a cached CCsent for the remote host,
1160			 * hence we haven't just crashed and restarted,
1161			 * do not send a RST.  This may be a retransmission
1162			 * from the other side after our earlier ACK was lost.
1163			 * Our new SYN, when it arrives, will serve as the
1164			 * needed ACK.
1165			 */
1166			if (taop->tao_ccsent != 0)
1167				goto drop;
1168			else {
1169				rstreason = BANDLIM_UNLIMITED;
1170				goto dropwithreset;
1171			}
1172		}
1173		if (thflags & TH_RST) {
1174			if (thflags & TH_ACK)
1175				tp = tcp_drop(tp, ECONNREFUSED);
1176			goto drop;
1177		}
1178		if ((thflags & TH_SYN) == 0)
1179			goto drop;
1180		tp->snd_wnd = th->th_win;	/* initial send window */
1181		tp->cc_recv = to.to_cc;		/* foreign CC */
1182
1183		tp->irs = th->th_seq;
1184		tcp_rcvseqinit(tp);
1185		if (thflags & TH_ACK) {
1186			/*
1187			 * Our SYN was acked.  If segment contains CC.ECHO
1188			 * option, check it to make sure this segment really
1189			 * matches our SYN.  If not, just drop it as old
1190			 * duplicate, but send an RST if we're still playing
1191			 * by the old rules.  If no CC.ECHO option, make sure
1192			 * we don't get fooled into using T/TCP.
1193			 */
1194			if (to.to_flags & TOF_CCECHO) {
1195				if (tp->cc_send != to.to_ccecho) {
1196					if (taop->tao_ccsent != 0)
1197						goto drop;
1198					else {
1199						rstreason = BANDLIM_UNLIMITED;
1200						goto dropwithreset;
1201					}
1202				}
1203			} else
1204				tp->t_flags &= ~TF_RCVD_CC;
1205			tcpstat.tcps_connects++;
1206			soisconnected(so);
1207#ifdef MAC
1208			mac_set_socket_peer_from_mbuf(m, so);
1209#endif
1210			/* Do window scaling on this connection? */
1211			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1212				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1213				tp->snd_scale = tp->requested_s_scale;
1214				tp->rcv_scale = tp->request_r_scale;
1215			}
1216			/* Segment is acceptable, update cache if undefined. */
1217			if (taop->tao_ccsent == 0)
1218				taop->tao_ccsent = to.to_ccecho;
1219
1220			tp->rcv_adv += tp->rcv_wnd;
1221			tp->snd_una++;		/* SYN is acked */
1222			/*
1223			 * If there's data, delay ACK; if there's also a FIN
1224			 * ACKNOW will be turned on later.
1225			 */
1226			if (DELAY_ACK(tp) && tlen != 0)
1227                                callout_reset(tp->tt_delack, tcp_delacktime,
1228                                    tcp_timer_delack, tp);
1229			else
1230				tp->t_flags |= TF_ACKNOW;
1231			/*
1232			 * Received <SYN,ACK> in SYN_SENT[*] state.
1233			 * Transitions:
1234			 *	SYN_SENT  --> ESTABLISHED
1235			 *	SYN_SENT* --> FIN_WAIT_1
1236			 */
1237			tp->t_starttime = ticks;
1238			if (tp->t_flags & TF_NEEDFIN) {
1239				tp->t_state = TCPS_FIN_WAIT_1;
1240				tp->t_flags &= ~TF_NEEDFIN;
1241				thflags &= ~TH_SYN;
1242			} else {
1243				tp->t_state = TCPS_ESTABLISHED;
1244				callout_reset(tp->tt_keep, tcp_keepidle,
1245					      tcp_timer_keep, tp);
1246			}
1247		} else {
1248			/*
1249		 	 * Received initial SYN in SYN-SENT[*] state =>
1250		 	 * simultaneous open.  If segment contains CC option
1251		 	 * and there is a cached CC, apply TAO test.
1252		 	 * If it succeeds, connection is * half-synchronized.
1253		 	 * Otherwise, do 3-way handshake:
1254		 	 *        SYN-SENT -> SYN-RECEIVED
1255		 	 *        SYN-SENT* -> SYN-RECEIVED*
1256		 	 * If there was no CC option, clear cached CC value.
1257		 	 */
1258			tp->t_flags |= TF_ACKNOW;
1259			callout_stop(tp->tt_rexmt);
1260			if (to.to_flags & TOF_CC) {
1261				if (taop->tao_cc != 0 &&
1262				    CC_GT(to.to_cc, taop->tao_cc)) {
1263					/*
1264					 * update cache and make transition:
1265					 *        SYN-SENT -> ESTABLISHED*
1266					 *        SYN-SENT* -> FIN-WAIT-1*
1267					 */
1268					taop->tao_cc = to.to_cc;
1269					tp->t_starttime = ticks;
1270					if (tp->t_flags & TF_NEEDFIN) {
1271						tp->t_state = TCPS_FIN_WAIT_1;
1272						tp->t_flags &= ~TF_NEEDFIN;
1273					} else {
1274						tp->t_state = TCPS_ESTABLISHED;
1275						callout_reset(tp->tt_keep,
1276							      tcp_keepidle,
1277							      tcp_timer_keep,
1278							      tp);
1279					}
1280					tp->t_flags |= TF_NEEDSYN;
1281				} else
1282					tp->t_state = TCPS_SYN_RECEIVED;
1283			} else {
1284				/* CC.NEW or no option => invalidate cache */
1285				taop->tao_cc = 0;
1286				tp->t_state = TCPS_SYN_RECEIVED;
1287			}
1288		}
1289
1290trimthenstep6:
1291		/*
1292		 * Advance th->th_seq to correspond to first data byte.
1293		 * If data, trim to stay within window,
1294		 * dropping FIN if necessary.
1295		 */
1296		th->th_seq++;
1297		if (tlen > tp->rcv_wnd) {
1298			todrop = tlen - tp->rcv_wnd;
1299			m_adj(m, -todrop);
1300			tlen = tp->rcv_wnd;
1301			thflags &= ~TH_FIN;
1302			tcpstat.tcps_rcvpackafterwin++;
1303			tcpstat.tcps_rcvbyteafterwin += todrop;
1304		}
1305		tp->snd_wl1 = th->th_seq - 1;
1306		tp->rcv_up = th->th_seq;
1307		/*
1308		 * Client side of transaction: already sent SYN and data.
1309		 * If the remote host used T/TCP to validate the SYN,
1310		 * our data will be ACK'd; if so, enter normal data segment
1311		 * processing in the middle of step 5, ack processing.
1312		 * Otherwise, goto step 6.
1313		 */
1314 		if (thflags & TH_ACK)
1315			goto process_ACK;
1316
1317		goto step6;
1318
1319	/*
1320	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1321	 *	if segment contains a SYN and CC [not CC.NEW] option:
1322	 *              if state == TIME_WAIT and connection duration > MSL,
1323	 *                  drop packet and send RST;
1324	 *
1325	 *		if SEG.CC > CCrecv then is new SYN, and can implicitly
1326	 *		    ack the FIN (and data) in retransmission queue.
1327	 *                  Complete close and delete TCPCB.  Then reprocess
1328	 *                  segment, hoping to find new TCPCB in LISTEN state;
1329	 *
1330	 *		else must be old SYN; drop it.
1331	 *      else do normal processing.
1332	 */
1333	case TCPS_LAST_ACK:
1334	case TCPS_CLOSING:
1335	case TCPS_TIME_WAIT:
1336		if ((thflags & TH_SYN) &&
1337		    (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1338			if (tp->t_state == TCPS_TIME_WAIT &&
1339					(ticks - tp->t_starttime) > tcp_msl) {
1340				rstreason = BANDLIM_UNLIMITED;
1341				goto dropwithreset;
1342			}
1343			if (CC_GT(to.to_cc, tp->cc_recv)) {
1344				tp = tcp_close(tp);
1345				goto findpcb;
1346			}
1347			else
1348				goto drop;
1349		}
1350 		break;  /* continue normal processing */
1351	}
1352
1353	/*
1354	 * States other than LISTEN or SYN_SENT.
1355	 * First check the RST flag and sequence number since reset segments
1356	 * are exempt from the timestamp and connection count tests.  This
1357	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1358	 * below which allowed reset segments in half the sequence space
1359	 * to fall though and be processed (which gives forged reset
1360	 * segments with a random sequence number a 50 percent chance of
1361	 * killing a connection).
1362	 * Then check timestamp, if present.
1363	 * Then check the connection count, if present.
1364	 * Then check that at least some bytes of segment are within
1365	 * receive window.  If segment begins before rcv_nxt,
1366	 * drop leading data (and SYN); if nothing left, just ack.
1367	 *
1368	 *
1369	 * If the RST bit is set, check the sequence number to see
1370	 * if this is a valid reset segment.
1371	 * RFC 793 page 37:
1372	 *   In all states except SYN-SENT, all reset (RST) segments
1373	 *   are validated by checking their SEQ-fields.  A reset is
1374	 *   valid if its sequence number is in the window.
1375	 * Note: this does not take into account delayed ACKs, so
1376	 *   we should test against last_ack_sent instead of rcv_nxt.
1377	 *   The sequence number in the reset segment is normally an
1378	 *   echo of our outgoing acknowlegement numbers, but some hosts
1379	 *   send a reset with the sequence number at the rightmost edge
1380	 *   of our receive window, and we have to handle this case.
1381	 * If we have multiple segments in flight, the intial reset
1382	 * segment sequence numbers will be to the left of last_ack_sent,
1383	 * but they will eventually catch up.
1384	 * In any case, it never made sense to trim reset segments to
1385	 * fit the receive window since RFC 1122 says:
1386	 *   4.2.2.12  RST Segment: RFC-793 Section 3.4
1387	 *
1388	 *    A TCP SHOULD allow a received RST segment to include data.
1389	 *
1390	 *    DISCUSSION
1391	 *         It has been suggested that a RST segment could contain
1392	 *         ASCII text that encoded and explained the cause of the
1393	 *         RST.  No standard has yet been established for such
1394	 *         data.
1395	 *
1396	 * If the reset segment passes the sequence number test examine
1397	 * the state:
1398	 *    SYN_RECEIVED STATE:
1399	 *	If passive open, return to LISTEN state.
1400	 *	If active open, inform user that connection was refused.
1401	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1402	 *	Inform user that connection was reset, and close tcb.
1403	 *    CLOSING, LAST_ACK STATES:
1404	 *	Close the tcb.
1405	 *    TIME_WAIT STATE:
1406	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
1407	 *      RFC 1337.
1408	 */
1409	if (thflags & TH_RST) {
1410		if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1411		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1412			switch (tp->t_state) {
1413
1414			case TCPS_SYN_RECEIVED:
1415				so->so_error = ECONNREFUSED;
1416				goto close;
1417
1418			case TCPS_ESTABLISHED:
1419			case TCPS_FIN_WAIT_1:
1420			case TCPS_FIN_WAIT_2:
1421			case TCPS_CLOSE_WAIT:
1422				so->so_error = ECONNRESET;
1423			close:
1424				tp->t_state = TCPS_CLOSED;
1425				tcpstat.tcps_drops++;
1426				tp = tcp_close(tp);
1427				break;
1428
1429			case TCPS_CLOSING:
1430			case TCPS_LAST_ACK:
1431				tp = tcp_close(tp);
1432				break;
1433
1434			case TCPS_TIME_WAIT:
1435				break;
1436			}
1437		}
1438		goto drop;
1439	}
1440
1441	/*
1442	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1443	 * and it's less than ts_recent, drop it.
1444	 */
1445	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1446	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1447
1448		/* Check to see if ts_recent is over 24 days old.  */
1449		if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1450			/*
1451			 * Invalidate ts_recent.  If this segment updates
1452			 * ts_recent, the age will be reset later and ts_recent
1453			 * will get a valid value.  If it does not, setting
1454			 * ts_recent to zero will at least satisfy the
1455			 * requirement that zero be placed in the timestamp
1456			 * echo reply when ts_recent isn't valid.  The
1457			 * age isn't reset until we get a valid ts_recent
1458			 * because we don't want out-of-order segments to be
1459			 * dropped when ts_recent is old.
1460			 */
1461			tp->ts_recent = 0;
1462		} else {
1463			tcpstat.tcps_rcvduppack++;
1464			tcpstat.tcps_rcvdupbyte += tlen;
1465			tcpstat.tcps_pawsdrop++;
1466			if (tlen) {
1467				goto dropafterack;
1468			} else {
1469				printf("PAWS ack-on-ack loop avoided\n");
1470				goto drop;
1471			}
1472		}
1473	}
1474
1475	/*
1476	 * T/TCP mechanism
1477	 *   If T/TCP was negotiated and the segment doesn't have CC,
1478	 *   or if its CC is wrong then drop the segment.
1479	 *   RST segments do not have to comply with this.
1480	 */
1481	if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1482	    ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1483 		goto dropafterack;
1484
1485	/*
1486	 * In the SYN-RECEIVED state, validate that the packet belongs to
1487	 * this connection before trimming the data to fit the receive
1488	 * window.  Check the sequence number versus IRS since we know
1489	 * the sequence numbers haven't wrapped.  This is a partial fix
1490	 * for the "LAND" DoS attack.
1491	 */
1492	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1493		rstreason = BANDLIM_RST_OPENPORT;
1494		goto dropwithreset;
1495	}
1496
1497	todrop = tp->rcv_nxt - th->th_seq;
1498	if (todrop > 0) {
1499		if (thflags & TH_SYN) {
1500			thflags &= ~TH_SYN;
1501			th->th_seq++;
1502			if (th->th_urp > 1)
1503				th->th_urp--;
1504			else
1505				thflags &= ~TH_URG;
1506			todrop--;
1507		}
1508		/*
1509		 * Following if statement from Stevens, vol. 2, p. 960.
1510		 */
1511		if (todrop > tlen
1512		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1513			/*
1514			 * Any valid FIN must be to the left of the window.
1515			 * At this point the FIN must be a duplicate or out
1516			 * of sequence; drop it.
1517			 */
1518			thflags &= ~TH_FIN;
1519
1520			/*
1521			 * Send an ACK to resynchronize and drop any data.
1522			 * But keep on processing for RST or ACK.
1523			 */
1524			tp->t_flags |= TF_ACKNOW;
1525			todrop = tlen;
1526			tcpstat.tcps_rcvduppack++;
1527			tcpstat.tcps_rcvdupbyte += todrop;
1528		} else {
1529			tcpstat.tcps_rcvpartduppack++;
1530			tcpstat.tcps_rcvpartdupbyte += todrop;
1531		}
1532		drop_hdrlen += todrop;	/* drop from the top afterwards */
1533		th->th_seq += todrop;
1534		tlen -= todrop;
1535		if (th->th_urp > todrop)
1536			th->th_urp -= todrop;
1537		else {
1538			thflags &= ~TH_URG;
1539			th->th_urp = 0;
1540		}
1541	}
1542
1543	/*
1544	 * If new data are received on a connection after the
1545	 * user processes are gone, then RST the other end.
1546	 */
1547	if ((so->so_state & SS_NOFDREF) &&
1548	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1549		tp = tcp_close(tp);
1550		tcpstat.tcps_rcvafterclose++;
1551		rstreason = BANDLIM_UNLIMITED;
1552		goto dropwithreset;
1553	}
1554
1555	/*
1556	 * If segment ends after window, drop trailing data
1557	 * (and PUSH and FIN); if nothing left, just ACK.
1558	 */
1559	todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1560	if (todrop > 0) {
1561		tcpstat.tcps_rcvpackafterwin++;
1562		if (todrop >= tlen) {
1563			tcpstat.tcps_rcvbyteafterwin += tlen;
1564			/*
1565			 * If a new connection request is received
1566			 * while in TIME_WAIT, drop the old connection
1567			 * and start over if the sequence numbers
1568			 * are above the previous ones.
1569			 */
1570			if (thflags & TH_SYN &&
1571			    tp->t_state == TCPS_TIME_WAIT &&
1572			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1573				tp = tcp_close(tp);
1574				goto findpcb;
1575			}
1576			/*
1577			 * If window is closed can only take segments at
1578			 * window edge, and have to drop data and PUSH from
1579			 * incoming segments.  Continue processing, but
1580			 * remember to ack.  Otherwise, drop segment
1581			 * and ack.
1582			 */
1583			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1584				tp->t_flags |= TF_ACKNOW;
1585				tcpstat.tcps_rcvwinprobe++;
1586			} else
1587				goto dropafterack;
1588		} else
1589			tcpstat.tcps_rcvbyteafterwin += todrop;
1590		m_adj(m, -todrop);
1591		tlen -= todrop;
1592		thflags &= ~(TH_PUSH|TH_FIN);
1593	}
1594
1595	/*
1596	 * If last ACK falls within this segment's sequence numbers,
1597	 * record its timestamp.
1598	 * NOTE that the test is modified according to the latest
1599	 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1600	 */
1601	if ((to.to_flags & TOF_TS) != 0 &&
1602	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1603		tp->ts_recent_age = ticks;
1604		tp->ts_recent = to.to_tsval;
1605	}
1606
1607	/*
1608	 * If a SYN is in the window, then this is an
1609	 * error and we send an RST and drop the connection.
1610	 */
1611	if (thflags & TH_SYN) {
1612		tp = tcp_drop(tp, ECONNRESET);
1613		rstreason = BANDLIM_UNLIMITED;
1614		goto dropwithreset;
1615	}
1616
1617	/*
1618	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1619	 * flag is on (half-synchronized state), then queue data for
1620	 * later processing; else drop segment and return.
1621	 */
1622	if ((thflags & TH_ACK) == 0) {
1623		if (tp->t_state == TCPS_SYN_RECEIVED ||
1624		    (tp->t_flags & TF_NEEDSYN))
1625			goto step6;
1626		else
1627			goto drop;
1628	}
1629
1630	/*
1631	 * Ack processing.
1632	 */
1633	switch (tp->t_state) {
1634
1635	/*
1636	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1637	 * ESTABLISHED state and continue processing.
1638	 * The ACK was checked above.
1639	 */
1640	case TCPS_SYN_RECEIVED:
1641
1642		tcpstat.tcps_connects++;
1643		soisconnected(so);
1644		/* Do window scaling? */
1645		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1646			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1647			tp->snd_scale = tp->requested_s_scale;
1648			tp->rcv_scale = tp->request_r_scale;
1649		}
1650		/*
1651		 * Upon successful completion of 3-way handshake,
1652		 * update cache.CC if it was undefined, pass any queued
1653		 * data to the user, and advance state appropriately.
1654		 */
1655		if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1656		    taop->tao_cc == 0)
1657			taop->tao_cc = tp->cc_recv;
1658
1659		/*
1660		 * Make transitions:
1661		 *      SYN-RECEIVED  -> ESTABLISHED
1662		 *      SYN-RECEIVED* -> FIN-WAIT-1
1663		 */
1664		tp->t_starttime = ticks;
1665		if (tp->t_flags & TF_NEEDFIN) {
1666			tp->t_state = TCPS_FIN_WAIT_1;
1667			tp->t_flags &= ~TF_NEEDFIN;
1668		} else {
1669			tp->t_state = TCPS_ESTABLISHED;
1670			callout_reset(tp->tt_keep, tcp_keepidle,
1671				      tcp_timer_keep, tp);
1672		}
1673		/*
1674		 * If segment contains data or ACK, will call tcp_reass()
1675		 * later; if not, do so now to pass queued data to user.
1676		 */
1677		if (tlen == 0 && (thflags & TH_FIN) == 0)
1678			(void) tcp_reass(tp, (struct tcphdr *)0, 0,
1679			    (struct mbuf *)0);
1680		tp->snd_wl1 = th->th_seq - 1;
1681		/* FALLTHROUGH */
1682
1683	/*
1684	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1685	 * ACKs.  If the ack is in the range
1686	 *	tp->snd_una < th->th_ack <= tp->snd_max
1687	 * then advance tp->snd_una to th->th_ack and drop
1688	 * data from the retransmission queue.  If this ACK reflects
1689	 * more up to date window information we update our window information.
1690	 */
1691	case TCPS_ESTABLISHED:
1692	case TCPS_FIN_WAIT_1:
1693	case TCPS_FIN_WAIT_2:
1694	case TCPS_CLOSE_WAIT:
1695	case TCPS_CLOSING:
1696	case TCPS_LAST_ACK:
1697	case TCPS_TIME_WAIT:
1698
1699		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1700			if (tlen == 0 && tiwin == tp->snd_wnd) {
1701				tcpstat.tcps_rcvdupack++;
1702				/*
1703				 * If we have outstanding data (other than
1704				 * a window probe), this is a completely
1705				 * duplicate ack (ie, window info didn't
1706				 * change), the ack is the biggest we've
1707				 * seen and we've seen exactly our rexmt
1708				 * threshhold of them, assume a packet
1709				 * has been dropped and retransmit it.
1710				 * Kludge snd_nxt & the congestion
1711				 * window so we send only this one
1712				 * packet.
1713				 *
1714				 * We know we're losing at the current
1715				 * window size so do congestion avoidance
1716				 * (set ssthresh to half the current window
1717				 * and pull our congestion window back to
1718				 * the new ssthresh).
1719				 *
1720				 * Dup acks mean that packets have left the
1721				 * network (they're now cached at the receiver)
1722				 * so bump cwnd by the amount in the receiver
1723				 * to keep a constant cwnd packets in the
1724				 * network.
1725				 */
1726				if (!callout_active(tp->tt_rexmt) ||
1727				    th->th_ack != tp->snd_una)
1728					tp->t_dupacks = 0;
1729				else if (++tp->t_dupacks == tcprexmtthresh) {
1730					tcp_seq onxt = tp->snd_nxt;
1731					u_int win =
1732					    min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1733						tp->t_maxseg;
1734					if (tcp_do_newreno &&
1735					    SEQ_LT(th->th_ack,
1736						   tp->snd_recover)) {
1737						/* False retransmit, should not
1738						 * cut window
1739						 */
1740						tp->snd_cwnd += tp->t_maxseg;
1741						tp->t_dupacks = 0;
1742						(void) tcp_output(tp);
1743						goto drop;
1744					}
1745					if (win < 2)
1746						win = 2;
1747					tp->snd_ssthresh = win * tp->t_maxseg;
1748					tp->snd_recover = tp->snd_max;
1749					callout_stop(tp->tt_rexmt);
1750					tp->t_rtttime = 0;
1751					tp->snd_nxt = th->th_ack;
1752					tp->snd_cwnd = tp->t_maxseg;
1753					(void) tcp_output(tp);
1754					tp->snd_cwnd = tp->snd_ssthresh +
1755						tp->t_maxseg * tp->t_dupacks;
1756					if (SEQ_GT(onxt, tp->snd_nxt))
1757						tp->snd_nxt = onxt;
1758					goto drop;
1759				} else if (tp->t_dupacks > tcprexmtthresh) {
1760					tp->snd_cwnd += tp->t_maxseg;
1761					(void) tcp_output(tp);
1762					goto drop;
1763				}
1764			} else
1765				tp->t_dupacks = 0;
1766			break;
1767		}
1768		/*
1769		 * If the congestion window was inflated to account
1770		 * for the other side's cached packets, retract it.
1771		 */
1772		if (tcp_do_newreno) {
1773			int is_partialack = SEQ_LT(th->th_ack, tp->snd_recover);
1774			if (tp->t_dupacks >= tcprexmtthresh) {
1775				if (is_partialack) {
1776					tcp_newreno_partial_ack(tp, th);
1777				} else {
1778					/*
1779					 * Window inflation should have left us
1780					 * with approximately snd_ssthresh
1781					 * outstanding data.
1782					 * But in case we would be inclined to
1783					 * send a burst, better to do it via
1784					 * the slow start mechanism.
1785					 */
1786					if (SEQ_GT(th->th_ack +
1787							tp->snd_ssthresh,
1788						   tp->snd_max))
1789						tp->snd_cwnd = tp->snd_max -
1790								th->th_ack +
1791								tp->t_maxseg;
1792					else
1793						tp->snd_cwnd = tp->snd_ssthresh;
1794				}
1795			}
1796			/*
1797			 * Reset dupacks, except on partial acks in
1798			 *   fast recovery.
1799			 */
1800			if (!(tp->t_dupacks >= tcprexmtthresh && is_partialack))
1801				tp->t_dupacks = 0;
1802                } else {
1803                        if (tp->t_dupacks >= tcprexmtthresh &&
1804                            tp->snd_cwnd > tp->snd_ssthresh)
1805				tp->snd_cwnd = tp->snd_ssthresh;
1806			tp->t_dupacks = 0;
1807                }
1808		if (SEQ_GT(th->th_ack, tp->snd_max)) {
1809			tcpstat.tcps_rcvacktoomuch++;
1810			goto dropafterack;
1811		}
1812		/*
1813		 * If we reach this point, ACK is not a duplicate,
1814		 *     i.e., it ACKs something we sent.
1815		 */
1816		if (tp->t_flags & TF_NEEDSYN) {
1817			/*
1818			 * T/TCP: Connection was half-synchronized, and our
1819			 * SYN has been ACK'd (so connection is now fully
1820			 * synchronized).  Go to non-starred state,
1821			 * increment snd_una for ACK of SYN, and check if
1822			 * we can do window scaling.
1823			 */
1824			tp->t_flags &= ~TF_NEEDSYN;
1825			tp->snd_una++;
1826			/* Do window scaling? */
1827			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1828				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1829				tp->snd_scale = tp->requested_s_scale;
1830				tp->rcv_scale = tp->request_r_scale;
1831			}
1832		}
1833
1834process_ACK:
1835		acked = th->th_ack - tp->snd_una;
1836		tcpstat.tcps_rcvackpack++;
1837		tcpstat.tcps_rcvackbyte += acked;
1838
1839		/*
1840		 * If we just performed our first retransmit, and the ACK
1841		 * arrives within our recovery window, then it was a mistake
1842		 * to do the retransmit in the first place.  Recover our
1843		 * original cwnd and ssthresh, and proceed to transmit where
1844		 * we left off.
1845		 */
1846		if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1847			++tcpstat.tcps_sndrexmitbad;
1848			tp->snd_cwnd = tp->snd_cwnd_prev;
1849			tp->snd_ssthresh = tp->snd_ssthresh_prev;
1850			tp->snd_nxt = tp->snd_max;
1851			tp->t_badrxtwin = 0;	/* XXX probably not required */
1852		}
1853
1854		/*
1855		 * If we have a timestamp reply, update smoothed
1856		 * round trip time.  If no timestamp is present but
1857		 * transmit timer is running and timed sequence
1858		 * number was acked, update smoothed round trip time.
1859		 * Since we now have an rtt measurement, cancel the
1860		 * timer backoff (cf., Phil Karn's retransmit alg.).
1861		 * Recompute the initial retransmit timer.
1862		 *
1863		 * Some boxes send broken timestamp replies
1864		 * during the SYN+ACK phase, ignore
1865		 * timestamps of 0 or we could calculate a
1866		 * huge RTT and blow up the retransmit timer.
1867		 */
1868		if ((to.to_flags & TOF_TS) != 0 &&
1869		    to.to_tsecr) {
1870			tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1871		} else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
1872			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1873		}
1874		tcp_xmit_bandwidth_limit(tp, th->th_ack);
1875
1876		/*
1877		 * If all outstanding data is acked, stop retransmit
1878		 * timer and remember to restart (more output or persist).
1879		 * If there is more data to be acked, restart retransmit
1880		 * timer, using current (possibly backed-off) value.
1881		 */
1882		if (th->th_ack == tp->snd_max) {
1883			callout_stop(tp->tt_rexmt);
1884			needoutput = 1;
1885		} else if (!callout_active(tp->tt_persist))
1886			callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1887				      tcp_timer_rexmt, tp);
1888
1889		/*
1890		 * If no data (only SYN) was ACK'd,
1891		 *    skip rest of ACK processing.
1892		 */
1893		if (acked == 0)
1894			goto step6;
1895
1896		/*
1897		 * When new data is acked, open the congestion window.
1898		 * If the window gives us less than ssthresh packets
1899		 * in flight, open exponentially (maxseg per packet).
1900		 * Otherwise open linearly: maxseg per window
1901		 * (maxseg^2 / cwnd per packet).
1902		 */
1903		{
1904		register u_int cw = tp->snd_cwnd;
1905		register u_int incr = tp->t_maxseg;
1906
1907		if (cw > tp->snd_ssthresh)
1908			incr = incr * incr / cw;
1909		/*
1910		 * If t_dupacks != 0 here, it indicates that we are still
1911		 * in NewReno fast recovery mode, so we leave the congestion
1912		 * window alone.
1913		 */
1914		if (!tcp_do_newreno || tp->t_dupacks == 0)
1915			tp->snd_cwnd = min(cw + incr,TCP_MAXWIN<<tp->snd_scale);
1916		}
1917		if (acked > so->so_snd.sb_cc) {
1918			tp->snd_wnd -= so->so_snd.sb_cc;
1919			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1920			ourfinisacked = 1;
1921		} else {
1922			sbdrop(&so->so_snd, acked);
1923			tp->snd_wnd -= acked;
1924			ourfinisacked = 0;
1925		}
1926		sowwakeup(so);
1927		tp->snd_una = th->th_ack;
1928		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1929			tp->snd_nxt = tp->snd_una;
1930
1931		switch (tp->t_state) {
1932
1933		/*
1934		 * In FIN_WAIT_1 STATE in addition to the processing
1935		 * for the ESTABLISHED state if our FIN is now acknowledged
1936		 * then enter FIN_WAIT_2.
1937		 */
1938		case TCPS_FIN_WAIT_1:
1939			if (ourfinisacked) {
1940				/*
1941				 * If we can't receive any more
1942				 * data, then closing user can proceed.
1943				 * Starting the timer is contrary to the
1944				 * specification, but if we don't get a FIN
1945				 * we'll hang forever.
1946				 */
1947				if (so->so_state & SS_CANTRCVMORE) {
1948					soisdisconnected(so);
1949					callout_reset(tp->tt_2msl, tcp_maxidle,
1950						      tcp_timer_2msl, tp);
1951				}
1952				tp->t_state = TCPS_FIN_WAIT_2;
1953			}
1954			break;
1955
1956	 	/*
1957		 * In CLOSING STATE in addition to the processing for
1958		 * the ESTABLISHED state if the ACK acknowledges our FIN
1959		 * then enter the TIME-WAIT state, otherwise ignore
1960		 * the segment.
1961		 */
1962		case TCPS_CLOSING:
1963			if (ourfinisacked) {
1964				tp->t_state = TCPS_TIME_WAIT;
1965				tcp_canceltimers(tp);
1966				/* Shorten TIME_WAIT [RFC-1644, p.28] */
1967				if (tp->cc_recv != 0 &&
1968				    (ticks - tp->t_starttime) < tcp_msl)
1969					callout_reset(tp->tt_2msl,
1970						      tp->t_rxtcur *
1971						      TCPTV_TWTRUNC,
1972						      tcp_timer_2msl, tp);
1973				else
1974					callout_reset(tp->tt_2msl, 2 * tcp_msl,
1975						      tcp_timer_2msl, tp);
1976				soisdisconnected(so);
1977			}
1978			break;
1979
1980		/*
1981		 * In LAST_ACK, we may still be waiting for data to drain
1982		 * and/or to be acked, as well as for the ack of our FIN.
1983		 * If our FIN is now acknowledged, delete the TCB,
1984		 * enter the closed state and return.
1985		 */
1986		case TCPS_LAST_ACK:
1987			if (ourfinisacked) {
1988				tp = tcp_close(tp);
1989				goto drop;
1990			}
1991			break;
1992
1993		/*
1994		 * In TIME_WAIT state the only thing that should arrive
1995		 * is a retransmission of the remote FIN.  Acknowledge
1996		 * it and restart the finack timer.
1997		 */
1998		case TCPS_TIME_WAIT:
1999			callout_reset(tp->tt_2msl, 2 * tcp_msl,
2000				      tcp_timer_2msl, tp);
2001			goto dropafterack;
2002		}
2003	}
2004
2005step6:
2006	/*
2007	 * Update window information.
2008	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2009	 */
2010	if ((thflags & TH_ACK) &&
2011	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2012	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2013	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2014		/* keep track of pure window updates */
2015		if (tlen == 0 &&
2016		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2017			tcpstat.tcps_rcvwinupd++;
2018		tp->snd_wnd = tiwin;
2019		tp->snd_wl1 = th->th_seq;
2020		tp->snd_wl2 = th->th_ack;
2021		if (tp->snd_wnd > tp->max_sndwnd)
2022			tp->max_sndwnd = tp->snd_wnd;
2023		needoutput = 1;
2024	}
2025
2026	/*
2027	 * Process segments with URG.
2028	 */
2029	if ((thflags & TH_URG) && th->th_urp &&
2030	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2031		/*
2032		 * This is a kludge, but if we receive and accept
2033		 * random urgent pointers, we'll crash in
2034		 * soreceive.  It's hard to imagine someone
2035		 * actually wanting to send this much urgent data.
2036		 */
2037		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2038			th->th_urp = 0;			/* XXX */
2039			thflags &= ~TH_URG;		/* XXX */
2040			goto dodata;			/* XXX */
2041		}
2042		/*
2043		 * If this segment advances the known urgent pointer,
2044		 * then mark the data stream.  This should not happen
2045		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2046		 * a FIN has been received from the remote side.
2047		 * In these states we ignore the URG.
2048		 *
2049		 * According to RFC961 (Assigned Protocols),
2050		 * the urgent pointer points to the last octet
2051		 * of urgent data.  We continue, however,
2052		 * to consider it to indicate the first octet
2053		 * of data past the urgent section as the original
2054		 * spec states (in one of two places).
2055		 */
2056		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2057			tp->rcv_up = th->th_seq + th->th_urp;
2058			so->so_oobmark = so->so_rcv.sb_cc +
2059			    (tp->rcv_up - tp->rcv_nxt) - 1;
2060			if (so->so_oobmark == 0)
2061				so->so_state |= SS_RCVATMARK;
2062			sohasoutofband(so);
2063			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2064		}
2065		/*
2066		 * Remove out of band data so doesn't get presented to user.
2067		 * This can happen independent of advancing the URG pointer,
2068		 * but if two URG's are pending at once, some out-of-band
2069		 * data may creep in... ick.
2070		 */
2071		if (th->th_urp <= (u_long)tlen &&
2072		    !(so->so_options & SO_OOBINLINE)) {
2073			/* hdr drop is delayed */
2074			tcp_pulloutofband(so, th, m, drop_hdrlen);
2075		}
2076	} else {
2077		/*
2078		 * If no out of band data is expected,
2079		 * pull receive urgent pointer along
2080		 * with the receive window.
2081		 */
2082		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2083			tp->rcv_up = tp->rcv_nxt;
2084	}
2085dodata:							/* XXX */
2086	KASSERT(headlocked, ("headlocked"));
2087	INP_INFO_WUNLOCK(&tcbinfo);
2088	headlocked = 0;
2089	/*
2090	 * Process the segment text, merging it into the TCP sequencing queue,
2091	 * and arranging for acknowledgment of receipt if necessary.
2092	 * This process logically involves adjusting tp->rcv_wnd as data
2093	 * is presented to the user (this happens in tcp_usrreq.c,
2094	 * case PRU_RCVD).  If a FIN has already been received on this
2095	 * connection then we just ignore the text.
2096	 */
2097	if ((tlen || (thflags & TH_FIN)) &&
2098	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2099		m_adj(m, drop_hdrlen);	/* delayed header drop */
2100		/*
2101		 * Insert segment which includes th into TCP reassembly queue
2102		 * with control block tp.  Set thflags to whether reassembly now
2103		 * includes a segment with FIN.  This handles the common case
2104		 * inline (segment is the next to be received on an established
2105		 * connection, and the queue is empty), avoiding linkage into
2106		 * and removal from the queue and repetition of various
2107		 * conversions.
2108		 * Set DELACK for segments received in order, but ack
2109		 * immediately when segments are out of order (so
2110		 * fast retransmit can work).
2111		 */
2112		if (th->th_seq == tp->rcv_nxt &&
2113		    LIST_EMPTY(&tp->t_segq) &&
2114		    TCPS_HAVEESTABLISHED(tp->t_state)) {
2115			if (DELAY_ACK(tp))
2116				callout_reset(tp->tt_delack, tcp_delacktime,
2117					      tcp_timer_delack, tp);
2118			else
2119				tp->t_flags |= TF_ACKNOW;
2120			tp->rcv_nxt += tlen;
2121			thflags = th->th_flags & TH_FIN;
2122			tcpstat.tcps_rcvpack++;
2123			tcpstat.tcps_rcvbyte += tlen;
2124			ND6_HINT(tp);
2125			if (so->so_state & SS_CANTRCVMORE)
2126				m_freem(m);
2127			else
2128				sbappend(&so->so_rcv, m);
2129			sorwakeup(so);
2130		} else {
2131			thflags = tcp_reass(tp, th, &tlen, m);
2132			tp->t_flags |= TF_ACKNOW;
2133		}
2134
2135		/*
2136		 * Note the amount of data that peer has sent into
2137		 * our window, in order to estimate the sender's
2138		 * buffer size.
2139		 */
2140		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2141	} else {
2142		m_freem(m);
2143		thflags &= ~TH_FIN;
2144	}
2145
2146	/*
2147	 * If FIN is received ACK the FIN and let the user know
2148	 * that the connection is closing.
2149	 */
2150	if (thflags & TH_FIN) {
2151		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2152			socantrcvmore(so);
2153			/*
2154			 * If connection is half-synchronized
2155			 * (ie NEEDSYN flag on) then delay ACK,
2156			 * so it may be piggybacked when SYN is sent.
2157			 * Otherwise, since we received a FIN then no
2158			 * more input can be expected, send ACK now.
2159			 */
2160			if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2161                                callout_reset(tp->tt_delack, tcp_delacktime,
2162                                    tcp_timer_delack, tp);
2163			else
2164				tp->t_flags |= TF_ACKNOW;
2165			tp->rcv_nxt++;
2166		}
2167		switch (tp->t_state) {
2168
2169	 	/*
2170		 * In SYN_RECEIVED and ESTABLISHED STATES
2171		 * enter the CLOSE_WAIT state.
2172		 */
2173		case TCPS_SYN_RECEIVED:
2174			tp->t_starttime = ticks;
2175			/*FALLTHROUGH*/
2176		case TCPS_ESTABLISHED:
2177			tp->t_state = TCPS_CLOSE_WAIT;
2178			break;
2179
2180	 	/*
2181		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2182		 * enter the CLOSING state.
2183		 */
2184		case TCPS_FIN_WAIT_1:
2185			tp->t_state = TCPS_CLOSING;
2186			break;
2187
2188	 	/*
2189		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2190		 * starting the time-wait timer, turning off the other
2191		 * standard timers.
2192		 */
2193		case TCPS_FIN_WAIT_2:
2194			tp->t_state = TCPS_TIME_WAIT;
2195			tcp_canceltimers(tp);
2196			/* Shorten TIME_WAIT [RFC-1644, p.28] */
2197			if (tp->cc_recv != 0 &&
2198			    (ticks - tp->t_starttime) < tcp_msl) {
2199				callout_reset(tp->tt_2msl,
2200					      tp->t_rxtcur * TCPTV_TWTRUNC,
2201					      tcp_timer_2msl, tp);
2202				/* For transaction client, force ACK now. */
2203				tp->t_flags |= TF_ACKNOW;
2204			}
2205			else
2206				callout_reset(tp->tt_2msl, 2 * tcp_msl,
2207					      tcp_timer_2msl, tp);
2208			soisdisconnected(so);
2209			break;
2210
2211		/*
2212		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2213		 */
2214		case TCPS_TIME_WAIT:
2215			callout_reset(tp->tt_2msl, 2 * tcp_msl,
2216				      tcp_timer_2msl, tp);
2217			break;
2218		}
2219	}
2220#ifdef TCPDEBUG
2221	if (so->so_options & SO_DEBUG)
2222		tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2223			  &tcp_savetcp, 0);
2224#endif
2225
2226	/*
2227	 * Return any desired output.
2228	 */
2229	if (needoutput || (tp->t_flags & TF_ACKNOW))
2230		(void) tcp_output(tp);
2231	INP_UNLOCK(inp);
2232	return;
2233
2234dropafterack:
2235	/*
2236	 * Generate an ACK dropping incoming segment if it occupies
2237	 * sequence space, where the ACK reflects our state.
2238	 *
2239	 * We can now skip the test for the RST flag since all
2240	 * paths to this code happen after packets containing
2241	 * RST have been dropped.
2242	 *
2243	 * In the SYN-RECEIVED state, don't send an ACK unless the
2244	 * segment we received passes the SYN-RECEIVED ACK test.
2245	 * If it fails send a RST.  This breaks the loop in the
2246	 * "LAND" DoS attack, and also prevents an ACK storm
2247	 * between two listening ports that have been sent forged
2248	 * SYN segments, each with the source address of the other.
2249	 */
2250	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2251	    (SEQ_GT(tp->snd_una, th->th_ack) ||
2252	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
2253		rstreason = BANDLIM_RST_OPENPORT;
2254		goto dropwithreset;
2255	}
2256#ifdef TCPDEBUG
2257	if (so->so_options & SO_DEBUG)
2258		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2259			  &tcp_savetcp, 0);
2260#endif
2261	if (headlocked)
2262		INP_INFO_WUNLOCK(&tcbinfo);
2263	m_freem(m);
2264	tp->t_flags |= TF_ACKNOW;
2265	(void) tcp_output(tp);
2266	INP_UNLOCK(inp);
2267	return;
2268
2269dropwithreset:
2270	/*
2271	 * Generate a RST, dropping incoming segment.
2272	 * Make ACK acceptable to originator of segment.
2273	 * Don't bother to respond if destination was broadcast/multicast.
2274	 */
2275	if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2276		goto drop;
2277	if (isipv6) {
2278		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2279		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2280			goto drop;
2281	} else {
2282		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2283		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2284	    	    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2285	    	    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2286			goto drop;
2287	}
2288	/* IPv6 anycast check is done at tcp6_input() */
2289
2290	/*
2291	 * Perform bandwidth limiting.
2292	 */
2293	if (badport_bandlim(rstreason) < 0)
2294		goto drop;
2295
2296#ifdef TCPDEBUG
2297	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2298		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2299			  &tcp_savetcp, 0);
2300#endif
2301
2302	if (tp)
2303		INP_UNLOCK(inp);
2304
2305	if (thflags & TH_ACK)
2306		/* mtod() below is safe as long as hdr dropping is delayed */
2307		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2308			    TH_RST);
2309	else {
2310		if (thflags & TH_SYN)
2311			tlen++;
2312		/* mtod() below is safe as long as hdr dropping is delayed */
2313		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2314			    (tcp_seq)0, TH_RST|TH_ACK);
2315	}
2316	if (headlocked)
2317		INP_INFO_WUNLOCK(&tcbinfo);
2318	return;
2319
2320drop:
2321	/*
2322	 * Drop space held by incoming segment and return.
2323	 */
2324#ifdef TCPDEBUG
2325	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2326		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2327			  &tcp_savetcp, 0);
2328#endif
2329	if (tp)
2330		INP_UNLOCK(inp);
2331	m_freem(m);
2332	if (headlocked)
2333		INP_INFO_WUNLOCK(&tcbinfo);
2334	return;
2335}
2336
2337/*
2338 * Parse TCP options and place in tcpopt.
2339 */
2340static void
2341tcp_dooptions(to, cp, cnt, is_syn)
2342	struct tcpopt *to;
2343	u_char *cp;
2344	int cnt;
2345{
2346	int opt, optlen;
2347
2348	to->to_flags = 0;
2349	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2350		opt = cp[0];
2351		if (opt == TCPOPT_EOL)
2352			break;
2353		if (opt == TCPOPT_NOP)
2354			optlen = 1;
2355		else {
2356			if (cnt < 2)
2357				break;
2358			optlen = cp[1];
2359			if (optlen < 2 || optlen > cnt)
2360				break;
2361		}
2362		switch (opt) {
2363		case TCPOPT_MAXSEG:
2364			if (optlen != TCPOLEN_MAXSEG)
2365				continue;
2366			if (!is_syn)
2367				continue;
2368			to->to_flags |= TOF_MSS;
2369			bcopy((char *)cp + 2,
2370			    (char *)&to->to_mss, sizeof(to->to_mss));
2371			to->to_mss = ntohs(to->to_mss);
2372			break;
2373		case TCPOPT_WINDOW:
2374			if (optlen != TCPOLEN_WINDOW)
2375				continue;
2376			if (! is_syn)
2377				continue;
2378			to->to_flags |= TOF_SCALE;
2379			to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2380			break;
2381		case TCPOPT_TIMESTAMP:
2382			if (optlen != TCPOLEN_TIMESTAMP)
2383				continue;
2384			to->to_flags |= TOF_TS;
2385			bcopy((char *)cp + 2,
2386			    (char *)&to->to_tsval, sizeof(to->to_tsval));
2387			to->to_tsval = ntohl(to->to_tsval);
2388			bcopy((char *)cp + 6,
2389			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2390			to->to_tsecr = ntohl(to->to_tsecr);
2391			break;
2392		case TCPOPT_CC:
2393			if (optlen != TCPOLEN_CC)
2394				continue;
2395			to->to_flags |= TOF_CC;
2396			bcopy((char *)cp + 2,
2397			    (char *)&to->to_cc, sizeof(to->to_cc));
2398			to->to_cc = ntohl(to->to_cc);
2399			break;
2400		case TCPOPT_CCNEW:
2401			if (optlen != TCPOLEN_CC)
2402				continue;
2403			if (!is_syn)
2404				continue;
2405			to->to_flags |= TOF_CCNEW;
2406			bcopy((char *)cp + 2,
2407			    (char *)&to->to_cc, sizeof(to->to_cc));
2408			to->to_cc = ntohl(to->to_cc);
2409			break;
2410		case TCPOPT_CCECHO:
2411			if (optlen != TCPOLEN_CC)
2412				continue;
2413			if (!is_syn)
2414				continue;
2415			to->to_flags |= TOF_CCECHO;
2416			bcopy((char *)cp + 2,
2417			    (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2418			to->to_ccecho = ntohl(to->to_ccecho);
2419			break;
2420		default:
2421			continue;
2422		}
2423	}
2424}
2425
2426/*
2427 * Pull out of band byte out of a segment so
2428 * it doesn't appear in the user's data queue.
2429 * It is still reflected in the segment length for
2430 * sequencing purposes.
2431 */
2432static void
2433tcp_pulloutofband(so, th, m, off)
2434	struct socket *so;
2435	struct tcphdr *th;
2436	register struct mbuf *m;
2437	int off;		/* delayed to be droped hdrlen */
2438{
2439	int cnt = off + th->th_urp - 1;
2440
2441	while (cnt >= 0) {
2442		if (m->m_len > cnt) {
2443			char *cp = mtod(m, caddr_t) + cnt;
2444			struct tcpcb *tp = sototcpcb(so);
2445
2446			tp->t_iobc = *cp;
2447			tp->t_oobflags |= TCPOOB_HAVEDATA;
2448			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2449			m->m_len--;
2450			if (m->m_flags & M_PKTHDR)
2451				m->m_pkthdr.len--;
2452			return;
2453		}
2454		cnt -= m->m_len;
2455		m = m->m_next;
2456		if (m == 0)
2457			break;
2458	}
2459	panic("tcp_pulloutofband");
2460}
2461
2462/*
2463 * Collect new round-trip time estimate
2464 * and update averages and current timeout.
2465 */
2466static void
2467tcp_xmit_timer(tp, rtt)
2468	register struct tcpcb *tp;
2469	int rtt;
2470{
2471	register int delta;
2472
2473	tcpstat.tcps_rttupdated++;
2474	tp->t_rttupdated++;
2475	if (tp->t_srtt != 0) {
2476		/*
2477		 * srtt is stored as fixed point with 5 bits after the
2478		 * binary point (i.e., scaled by 8).  The following magic
2479		 * is equivalent to the smoothing algorithm in rfc793 with
2480		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2481		 * point).  Adjust rtt to origin 0.
2482		 */
2483		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2484			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2485
2486		if ((tp->t_srtt += delta) <= 0)
2487			tp->t_srtt = 1;
2488
2489		/*
2490		 * We accumulate a smoothed rtt variance (actually, a
2491		 * smoothed mean difference), then set the retransmit
2492		 * timer to smoothed rtt + 4 times the smoothed variance.
2493		 * rttvar is stored as fixed point with 4 bits after the
2494		 * binary point (scaled by 16).  The following is
2495		 * equivalent to rfc793 smoothing with an alpha of .75
2496		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2497		 * rfc793's wired-in beta.
2498		 */
2499		if (delta < 0)
2500			delta = -delta;
2501		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2502		if ((tp->t_rttvar += delta) <= 0)
2503			tp->t_rttvar = 1;
2504		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2505		    tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2506	} else {
2507		/*
2508		 * No rtt measurement yet - use the unsmoothed rtt.
2509		 * Set the variance to half the rtt (so our first
2510		 * retransmit happens at 3*rtt).
2511		 */
2512		tp->t_srtt = rtt << TCP_RTT_SHIFT;
2513		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2514		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2515	}
2516	tp->t_rtttime = 0;
2517	tp->t_rxtshift = 0;
2518
2519	/*
2520	 * the retransmit should happen at rtt + 4 * rttvar.
2521	 * Because of the way we do the smoothing, srtt and rttvar
2522	 * will each average +1/2 tick of bias.  When we compute
2523	 * the retransmit timer, we want 1/2 tick of rounding and
2524	 * 1 extra tick because of +-1/2 tick uncertainty in the
2525	 * firing of the timer.  The bias will give us exactly the
2526	 * 1.5 tick we need.  But, because the bias is
2527	 * statistical, we have to test that we don't drop below
2528	 * the minimum feasible timer (which is 2 ticks).
2529	 */
2530	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2531		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2532
2533	/*
2534	 * We received an ack for a packet that wasn't retransmitted;
2535	 * it is probably safe to discard any error indications we've
2536	 * received recently.  This isn't quite right, but close enough
2537	 * for now (a route might have failed after we sent a segment,
2538	 * and the return path might not be symmetrical).
2539	 */
2540	tp->t_softerror = 0;
2541}
2542
2543/*
2544 * Determine a reasonable value for maxseg size.
2545 * If the route is known, check route for mtu.
2546 * If none, use an mss that can be handled on the outgoing
2547 * interface without forcing IP to fragment; if bigger than
2548 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2549 * to utilize large mbufs.  If no route is found, route has no mtu,
2550 * or the destination isn't local, use a default, hopefully conservative
2551 * size (usually 512 or the default IP max size, but no more than the mtu
2552 * of the interface), as we can't discover anything about intervening
2553 * gateways or networks.  We also initialize the congestion/slow start
2554 * window to be a single segment if the destination isn't local.
2555 * While looking at the routing entry, we also initialize other path-dependent
2556 * parameters from pre-set or cached values in the routing entry.
2557 *
2558 * Also take into account the space needed for options that we
2559 * send regularly.  Make maxseg shorter by that amount to assure
2560 * that we can send maxseg amount of data even when the options
2561 * are present.  Store the upper limit of the length of options plus
2562 * data in maxopd.
2563 *
2564 * NOTE that this routine is only called when we process an incoming
2565 * segment, for outgoing segments only tcp_mssopt is called.
2566 *
2567 * In case of T/TCP, we call this routine during implicit connection
2568 * setup as well (offer = -1), to initialize maxseg from the cached
2569 * MSS of our peer.
2570 */
2571void
2572tcp_mss(tp, offer)
2573	struct tcpcb *tp;
2574	int offer;
2575{
2576	register struct rtentry *rt;
2577	struct ifnet *ifp;
2578	register int rtt, mss;
2579	u_long bufsize;
2580	struct inpcb *inp = tp->t_inpcb;
2581	struct socket *so;
2582	struct rmxp_tao *taop;
2583	int origoffer = offer;
2584#ifdef INET6
2585	int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2586	size_t min_protoh = isipv6 ?
2587			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2588			    sizeof (struct tcpiphdr);
2589#else
2590	const int isipv6 = 0;
2591	const size_t min_protoh = sizeof (struct tcpiphdr);
2592#endif
2593
2594	if (isipv6)
2595		rt = tcp_rtlookup6(&inp->inp_inc);
2596	else
2597		rt = tcp_rtlookup(&inp->inp_inc);
2598	if (rt == NULL) {
2599		tp->t_maxopd = tp->t_maxseg =
2600				isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2601		return;
2602	}
2603	ifp = rt->rt_ifp;
2604	so = inp->inp_socket;
2605
2606	taop = rmx_taop(rt->rt_rmx);
2607	/*
2608	 * Offer == -1 means that we didn't receive SYN yet,
2609	 * use cached value in that case;
2610	 */
2611	if (offer == -1)
2612		offer = taop->tao_mssopt;
2613	/*
2614	 * Offer == 0 means that there was no MSS on the SYN segment,
2615	 * in this case we use tcp_mssdflt.
2616	 */
2617	if (offer == 0)
2618		offer = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2619	else
2620		/*
2621		 * Sanity check: make sure that maxopd will be large
2622		 * enough to allow some data on segments even is the
2623		 * all the option space is used (40bytes).  Otherwise
2624		 * funny things may happen in tcp_output.
2625		 */
2626		offer = max(offer, 64);
2627	taop->tao_mssopt = offer;
2628
2629	/*
2630	 * While we're here, check if there's an initial rtt
2631	 * or rttvar.  Convert from the route-table units
2632	 * to scaled multiples of the slow timeout timer.
2633	 */
2634	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2635		/*
2636		 * XXX the lock bit for RTT indicates that the value
2637		 * is also a minimum value; this is subject to time.
2638		 */
2639		if (rt->rt_rmx.rmx_locks & RTV_RTT)
2640			tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2641		tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2642		tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2643		tcpstat.tcps_usedrtt++;
2644		if (rt->rt_rmx.rmx_rttvar) {
2645			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2646			    (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2647			tcpstat.tcps_usedrttvar++;
2648		} else {
2649			/* default variation is +- 1 rtt */
2650			tp->t_rttvar =
2651			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2652		}
2653		TCPT_RANGESET(tp->t_rxtcur,
2654			      ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2655			      tp->t_rttmin, TCPTV_REXMTMAX);
2656	}
2657	/*
2658	 * if there's an mtu associated with the route, use it
2659	 * else, use the link mtu.
2660	 */
2661	if (rt->rt_rmx.rmx_mtu)
2662		mss = rt->rt_rmx.rmx_mtu - min_protoh;
2663	else {
2664		if (isipv6) {
2665			mss = nd_ifinfo[rt->rt_ifp->if_index].linkmtu -
2666				min_protoh;
2667			if (!in6_localaddr(&inp->in6p_faddr))
2668				mss = min(mss, tcp_v6mssdflt);
2669		} else {
2670			mss = ifp->if_mtu - min_protoh;
2671			if (!in_localaddr(inp->inp_faddr))
2672				mss = min(mss, tcp_mssdflt);
2673		}
2674	}
2675	mss = min(mss, offer);
2676	/*
2677	 * maxopd stores the maximum length of data AND options
2678	 * in a segment; maxseg is the amount of data in a normal
2679	 * segment.  We need to store this value (maxopd) apart
2680	 * from maxseg, because now every segment carries options
2681	 * and thus we normally have somewhat less data in segments.
2682	 */
2683	tp->t_maxopd = mss;
2684
2685	/*
2686	 * In case of T/TCP, origoffer==-1 indicates, that no segments
2687	 * were received yet.  In this case we just guess, otherwise
2688	 * we do the same as before T/TCP.
2689	 */
2690 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2691	    (origoffer == -1 ||
2692	     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2693		mss -= TCPOLEN_TSTAMP_APPA;
2694 	if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2695	    (origoffer == -1 ||
2696	     (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2697		mss -= TCPOLEN_CC_APPA;
2698
2699#if	(MCLBYTES & (MCLBYTES - 1)) == 0
2700		if (mss > MCLBYTES)
2701			mss &= ~(MCLBYTES-1);
2702#else
2703		if (mss > MCLBYTES)
2704			mss = mss / MCLBYTES * MCLBYTES;
2705#endif
2706	/*
2707	 * If there's a pipesize, change the socket buffer
2708	 * to that size.  Make the socket buffers an integral
2709	 * number of mss units; if the mss is larger than
2710	 * the socket buffer, decrease the mss.
2711	 */
2712#ifdef RTV_SPIPE
2713	if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2714#endif
2715		bufsize = so->so_snd.sb_hiwat;
2716	if (bufsize < mss)
2717		mss = bufsize;
2718	else {
2719		bufsize = roundup(bufsize, mss);
2720		if (bufsize > sb_max)
2721			bufsize = sb_max;
2722		if (bufsize > so->so_snd.sb_hiwat)
2723			(void)sbreserve(&so->so_snd, bufsize, so, NULL);
2724	}
2725	tp->t_maxseg = mss;
2726
2727#ifdef RTV_RPIPE
2728	if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2729#endif
2730		bufsize = so->so_rcv.sb_hiwat;
2731	if (bufsize > mss) {
2732		bufsize = roundup(bufsize, mss);
2733		if (bufsize > sb_max)
2734			bufsize = sb_max;
2735		if (bufsize > so->so_rcv.sb_hiwat)
2736			(void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2737	}
2738
2739	/*
2740	 * Set the slow-start flight size depending on whether this
2741	 * is a local network or not.
2742	 */
2743	if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2744	    (!isipv6 && in_localaddr(inp->inp_faddr)))
2745		tp->snd_cwnd = mss * ss_fltsz_local;
2746	else
2747		tp->snd_cwnd = mss * ss_fltsz;
2748
2749	if (rt->rt_rmx.rmx_ssthresh) {
2750		/*
2751		 * There's some sort of gateway or interface
2752		 * buffer limit on the path.  Use this to set
2753		 * the slow start threshhold, but set the
2754		 * threshold to no less than 2*mss.
2755		 */
2756		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2757		tcpstat.tcps_usedssthresh++;
2758	}
2759}
2760
2761/*
2762 * Determine the MSS option to send on an outgoing SYN.
2763 */
2764int
2765tcp_mssopt(tp)
2766	struct tcpcb *tp;
2767{
2768	struct rtentry *rt;
2769#ifdef INET6
2770	int isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2771	size_t min_protoh = isipv6 ?
2772			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2773			    sizeof (struct tcpiphdr);
2774#else
2775	const int isipv6 = 0;
2776	const size_t min_protoh = sizeof (struct tcpiphdr);
2777#endif
2778
2779	if (isipv6)
2780		rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
2781	else
2782		rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
2783	if (rt == NULL)
2784		return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2785
2786	return (rt->rt_ifp->if_mtu - min_protoh);
2787}
2788
2789
2790/*
2791 * On a partial ack arrives, force the retransmission of the
2792 * next unacknowledged segment.  Do not clear tp->t_dupacks.
2793 * By setting snd_nxt to ti_ack, this forces retransmission timer to
2794 * be started again.
2795 */
2796static void
2797tcp_newreno_partial_ack(tp, th)
2798	struct tcpcb *tp;
2799	struct tcphdr *th;
2800{
2801	tcp_seq onxt = tp->snd_nxt;
2802	u_long  ocwnd = tp->snd_cwnd;
2803
2804	callout_stop(tp->tt_rexmt);
2805	tp->t_rtttime = 0;
2806	tp->snd_nxt = th->th_ack;
2807	/*
2808	 * Set snd_cwnd to one segment beyond acknowledged offset.
2809	 * (tp->snd_una has not yet been updated when this function is called.)
2810	 */
2811	tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
2812	tp->t_flags |= TF_ACKNOW;
2813	(void) tcp_output(tp);
2814	tp->snd_cwnd = ocwnd;
2815	if (SEQ_GT(onxt, tp->snd_nxt))
2816		tp->snd_nxt = onxt;
2817	/*
2818	 * Partial window deflation.  Relies on fact that tp->snd_una
2819	 * not updated yet.
2820	 */
2821	tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);
2822}
2823