tcp_input.c revision 169405
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 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
30 * $FreeBSD: head/sys/netinet/tcp_input.c 169405 2007-05-09 06:09:40Z maxim $
31 */
32
33#include "opt_ipfw.h"		/* for ipfw_fwd	*/
34#include "opt_inet.h"
35#include "opt_inet6.h"
36#include "opt_ipsec.h"
37#include "opt_mac.h"
38#include "opt_tcpdebug.h"
39
40#include <sys/param.h>
41#include <sys/kernel.h>
42#include <sys/malloc.h>
43#include <sys/mbuf.h>
44#include <sys/proc.h>		/* for proc0 declaration */
45#include <sys/protosw.h>
46#include <sys/signalvar.h>
47#include <sys/socket.h>
48#include <sys/socketvar.h>
49#include <sys/sysctl.h>
50#include <sys/syslog.h>
51#include <sys/systm.h>
52
53#include <machine/cpu.h>	/* before tcp_seq.h, for tcp_random18() */
54
55#include <vm/uma.h>
56
57#include <net/if.h>
58#include <net/route.h>
59
60#include <netinet/in.h>
61#include <netinet/in_pcb.h>
62#include <netinet/in_systm.h>
63#include <netinet/in_var.h>
64#include <netinet/ip.h>
65#include <netinet/ip_icmp.h>	/* required for icmp_var.h */
66#include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
67#include <netinet/ip_var.h>
68#include <netinet/ip_options.h>
69#include <netinet/ip6.h>
70#include <netinet/icmp6.h>
71#include <netinet6/in6_pcb.h>
72#include <netinet6/ip6_var.h>
73#include <netinet6/nd6.h>
74#include <netinet/tcp.h>
75#include <netinet/tcp_fsm.h>
76#include <netinet/tcp_seq.h>
77#include <netinet/tcp_timer.h>
78#include <netinet/tcp_var.h>
79#include <netinet6/tcp6_var.h>
80#include <netinet/tcpip.h>
81#ifdef TCPDEBUG
82#include <netinet/tcp_debug.h>
83#endif /* TCPDEBUG */
84
85#ifdef FAST_IPSEC
86#include <netipsec/ipsec.h>
87#include <netipsec/ipsec6.h>
88#endif /*FAST_IPSEC*/
89
90#ifdef IPSEC
91#include <netinet6/ipsec.h>
92#include <netinet6/ipsec6.h>
93#include <netkey/key.h>
94#endif /*IPSEC*/
95
96#include <machine/in_cksum.h>
97
98#include <security/mac/mac_framework.h>
99
100static const int tcprexmtthresh = 3;
101
102struct	tcpstat tcpstat;
103SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
104    &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
105
106static int tcp_log_in_vain = 0;
107SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
108    &tcp_log_in_vain, 0, "Log all incoming TCP segments to closed ports");
109
110static int blackhole = 0;
111SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
112    &blackhole, 0, "Do not send RST on segments to closed ports");
113
114int tcp_delack_enabled = 1;
115SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
116    &tcp_delack_enabled, 0,
117    "Delay ACK to try and piggyback it onto a data packet");
118
119static int drop_synfin = 0;
120SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
121    &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
122
123static int tcp_do_rfc3042 = 1;
124SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
125    &tcp_do_rfc3042, 0, "Enable RFC 3042 (Limited Transmit)");
126
127static int tcp_do_rfc3390 = 1;
128SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
129    &tcp_do_rfc3390, 0,
130    "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
131
132static int tcp_insecure_rst = 0;
133SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
134    &tcp_insecure_rst, 0,
135    "Follow the old (insecure) criteria for accepting RST packets");
136
137SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
138    "TCP Segment Reassembly Queue");
139
140static int tcp_reass_maxseg = 0;
141SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RDTUN,
142    &tcp_reass_maxseg, 0,
143    "Global maximum number of TCP Segments in Reassembly Queue");
144
145int tcp_reass_qsize = 0;
146SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
147    &tcp_reass_qsize, 0,
148    "Global number of TCP Segments currently in Reassembly Queue");
149
150static int tcp_reass_maxqlen = 48;
151SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxqlen, CTLFLAG_RW,
152    &tcp_reass_maxqlen, 0,
153    "Maximum number of TCP Segments per individual Reassembly Queue");
154
155static int tcp_reass_overflows = 0;
156SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
157    &tcp_reass_overflows, 0,
158    "Global number of TCP Segment Reassembly Queue Overflows");
159
160int	tcp_do_autorcvbuf = 1;
161SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
162    &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
163
164int	tcp_autorcvbuf_inc = 16*1024;
165SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
166    &tcp_autorcvbuf_inc, 0,
167    "Incrementor step size of automatic receive buffer");
168
169int	tcp_autorcvbuf_max = 256*1024;
170SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
171    &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
172
173struct inpcbhead tcb;
174#define	tcb6	tcb  /* for KAME src sync over BSD*'s */
175struct inpcbinfo tcbinfo;
176
177static void	 tcp_dooptions(struct tcpopt *, u_char *, int, int);
178static void	 tcp_do_segment(struct mbuf *, struct tcphdr *,
179		     struct socket *, struct tcpcb *, int, int);
180static void	 tcp_dropwithreset(struct mbuf *, struct tcphdr *,
181		     struct tcpcb *, int, int);
182static void	 tcp_pulloutofband(struct socket *,
183		     struct tcphdr *, struct mbuf *, int);
184static int	 tcp_reass(struct tcpcb *, struct tcphdr *, int *,
185		     struct mbuf *);
186static void	 tcp_xmit_timer(struct tcpcb *, int);
187static void	 tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
188static int	 tcp_timewait(struct inpcb *, struct tcpopt *,
189		     struct tcphdr *, struct mbuf *, int);
190
191/* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
192#ifdef INET6
193#define ND6_HINT(tp) \
194do { \
195	if ((tp) && (tp)->t_inpcb && \
196	    ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
197		nd6_nud_hint(NULL, NULL, 0); \
198} while (0)
199#else
200#define ND6_HINT(tp)
201#endif
202
203/*
204 * Indicate whether this ack should be delayed.  We can delay the ack if
205 *	- there is no delayed ack timer in progress and
206 *	- our last ack wasn't a 0-sized window.  We never want to delay
207 *	  the ack that opens up a 0-sized window and
208 *		- delayed acks are enabled or
209 *		- this is a half-synchronized T/TCP connection.
210 */
211#define DELAY_ACK(tp)							\
212	((!tcp_timer_active(tp, TT_DELACK) &&				\
213	    (tp->t_flags & TF_RXWIN0SENT) == 0) &&			\
214	    (tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
215
216/* Initialize TCP reassembly queue */
217static void
218tcp_reass_zone_change(void *tag)
219{
220
221	tcp_reass_maxseg = nmbclusters / 16;
222	uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
223}
224
225uma_zone_t	tcp_reass_zone;
226void
227tcp_reass_init()
228{
229	tcp_reass_maxseg = nmbclusters / 16;
230	TUNABLE_INT_FETCH("net.inet.tcp.reass.maxsegments",
231	    &tcp_reass_maxseg);
232	tcp_reass_zone = uma_zcreate("tcpreass", sizeof (struct tseg_qent),
233	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
234	uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
235	EVENTHANDLER_REGISTER(nmbclusters_change,
236	    tcp_reass_zone_change, NULL, EVENTHANDLER_PRI_ANY);
237}
238
239static int
240tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
241{
242	struct tseg_qent *q;
243	struct tseg_qent *p = NULL;
244	struct tseg_qent *nq;
245	struct tseg_qent *te = NULL;
246	struct socket *so = tp->t_inpcb->inp_socket;
247	int flags;
248
249	INP_LOCK_ASSERT(tp->t_inpcb);
250
251	/*
252	 * XXX: tcp_reass() is rather inefficient with its data structures
253	 * and should be rewritten (see NetBSD for optimizations).  While
254	 * doing that it should move to its own file tcp_reass.c.
255	 */
256
257	/*
258	 * Call with th==NULL after become established to
259	 * force pre-ESTABLISHED data up to user socket.
260	 */
261	if (th == NULL)
262		goto present;
263
264	/*
265	 * Limit the number of segments in the reassembly queue to prevent
266	 * holding on to too many segments (and thus running out of mbufs).
267	 * Make sure to let the missing segment through which caused this
268	 * queue.  Always keep one global queue entry spare to be able to
269	 * process the missing segment.
270	 */
271	if (th->th_seq != tp->rcv_nxt &&
272	    (tcp_reass_qsize + 1 >= tcp_reass_maxseg ||
273	     tp->t_segqlen >= tcp_reass_maxqlen)) {
274		tcp_reass_overflows++;
275		tcpstat.tcps_rcvmemdrop++;
276		m_freem(m);
277		*tlenp = 0;
278		return (0);
279	}
280
281	/*
282	 * Allocate a new queue entry. If we can't, or hit the zone limit
283	 * just drop the pkt.
284	 */
285	te = uma_zalloc(tcp_reass_zone, M_NOWAIT);
286	if (te == NULL) {
287		tcpstat.tcps_rcvmemdrop++;
288		m_freem(m);
289		*tlenp = 0;
290		return (0);
291	}
292	tp->t_segqlen++;
293	tcp_reass_qsize++;
294
295	/*
296	 * Find a segment which begins after this one does.
297	 */
298	LIST_FOREACH(q, &tp->t_segq, tqe_q) {
299		if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
300			break;
301		p = q;
302	}
303
304	/*
305	 * If there is a preceding segment, it may provide some of
306	 * our data already.  If so, drop the data from the incoming
307	 * segment.  If it provides all of our data, drop us.
308	 */
309	if (p != NULL) {
310		int i;
311		/* conversion to int (in i) handles seq wraparound */
312		i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
313		if (i > 0) {
314			if (i >= *tlenp) {
315				tcpstat.tcps_rcvduppack++;
316				tcpstat.tcps_rcvdupbyte += *tlenp;
317				m_freem(m);
318				uma_zfree(tcp_reass_zone, te);
319				tp->t_segqlen--;
320				tcp_reass_qsize--;
321				/*
322				 * Try to present any queued data
323				 * at the left window edge to the user.
324				 * This is needed after the 3-WHS
325				 * completes.
326				 */
327				goto present;	/* ??? */
328			}
329			m_adj(m, i);
330			*tlenp -= i;
331			th->th_seq += i;
332		}
333	}
334	tcpstat.tcps_rcvoopack++;
335	tcpstat.tcps_rcvoobyte += *tlenp;
336
337	/*
338	 * While we overlap succeeding segments trim them or,
339	 * if they are completely covered, dequeue them.
340	 */
341	while (q) {
342		int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
343		if (i <= 0)
344			break;
345		if (i < q->tqe_len) {
346			q->tqe_th->th_seq += i;
347			q->tqe_len -= i;
348			m_adj(q->tqe_m, i);
349			break;
350		}
351
352		nq = LIST_NEXT(q, tqe_q);
353		LIST_REMOVE(q, tqe_q);
354		m_freem(q->tqe_m);
355		uma_zfree(tcp_reass_zone, q);
356		tp->t_segqlen--;
357		tcp_reass_qsize--;
358		q = nq;
359	}
360
361	/* Insert the new segment queue entry into place. */
362	te->tqe_m = m;
363	te->tqe_th = th;
364	te->tqe_len = *tlenp;
365
366	if (p == NULL) {
367		LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
368	} else {
369		LIST_INSERT_AFTER(p, te, tqe_q);
370	}
371
372present:
373	/*
374	 * Present data to user, advancing rcv_nxt through
375	 * completed sequence space.
376	 */
377	if (!TCPS_HAVEESTABLISHED(tp->t_state))
378		return (0);
379	q = LIST_FIRST(&tp->t_segq);
380	if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
381		return (0);
382	SOCKBUF_LOCK(&so->so_rcv);
383	do {
384		tp->rcv_nxt += q->tqe_len;
385		flags = q->tqe_th->th_flags & TH_FIN;
386		nq = LIST_NEXT(q, tqe_q);
387		LIST_REMOVE(q, tqe_q);
388		if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
389			m_freem(q->tqe_m);
390		else
391			sbappendstream_locked(&so->so_rcv, q->tqe_m);
392		uma_zfree(tcp_reass_zone, q);
393		tp->t_segqlen--;
394		tcp_reass_qsize--;
395		q = nq;
396	} while (q && q->tqe_th->th_seq == tp->rcv_nxt);
397	ND6_HINT(tp);
398	sorwakeup_locked(so);
399	return (flags);
400}
401
402/*
403 * TCP input routine, follows pages 65-76 of the
404 * protocol specification dated September, 1981 very closely.
405 */
406#ifdef INET6
407int
408tcp6_input(struct mbuf **mp, int *offp, int proto)
409{
410	struct mbuf *m = *mp;
411	struct in6_ifaddr *ia6;
412
413	IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
414
415	/*
416	 * draft-itojun-ipv6-tcp-to-anycast
417	 * better place to put this in?
418	 */
419	ia6 = ip6_getdstifaddr(m);
420	if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
421		struct ip6_hdr *ip6;
422
423		ip6 = mtod(m, struct ip6_hdr *);
424		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
425			    (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
426		return IPPROTO_DONE;
427	}
428
429	tcp_input(m, *offp);
430	return IPPROTO_DONE;
431}
432#endif
433
434void
435tcp_input(struct mbuf *m, int off0)
436{
437	struct tcphdr *th;
438	struct ip *ip = NULL;
439	struct ipovly *ipov;
440	struct inpcb *inp = NULL;
441	struct tcpcb *tp = NULL;
442	struct socket *so = NULL;
443	u_char *optp = NULL;
444	int optlen = 0;
445	int len, tlen, off;
446	int drop_hdrlen;
447	int thflags;
448	int rstreason = 0;	/* For badport_bandlim accounting purposes */
449#ifdef IPFIREWALL_FORWARD
450	struct m_tag *fwd_tag;
451#endif
452#ifdef INET6
453	struct ip6_hdr *ip6 = NULL;
454	int isipv6;
455	char ip6buf[INET6_ADDRSTRLEN];
456#else
457	const int isipv6 = 0;
458#endif
459	struct tcpopt to;		/* options in this segment */
460
461#ifdef TCPDEBUG
462	/*
463	 * The size of tcp_saveipgen must be the size of the max ip header,
464	 * now IPv6.
465	 */
466	u_char tcp_saveipgen[IP6_HDR_LEN];
467	struct tcphdr tcp_savetcp;
468	short ostate = 0;
469#endif
470
471#ifdef INET6
472	isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
473#endif
474
475	to.to_flags = 0;
476	tcpstat.tcps_rcvtotal++;
477
478	if (isipv6) {
479#ifdef INET6
480		/* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
481		ip6 = mtod(m, struct ip6_hdr *);
482		tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
483		if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
484			tcpstat.tcps_rcvbadsum++;
485			goto drop;
486		}
487		th = (struct tcphdr *)((caddr_t)ip6 + off0);
488
489		/*
490		 * Be proactive about unspecified IPv6 address in source.
491		 * As we use all-zero to indicate unbounded/unconnected pcb,
492		 * unspecified IPv6 address can be used to confuse us.
493		 *
494		 * Note that packets with unspecified IPv6 destination is
495		 * already dropped in ip6_input.
496		 */
497		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
498			/* XXX stat */
499			goto drop;
500		}
501#else
502		th = NULL;		/* XXX: avoid compiler warning */
503#endif
504	} else {
505		/*
506		 * Get IP and TCP header together in first mbuf.
507		 * Note: IP leaves IP header in first mbuf.
508		 */
509		if (off0 > sizeof (struct ip)) {
510			ip_stripoptions(m, (struct mbuf *)0);
511			off0 = sizeof(struct ip);
512		}
513		if (m->m_len < sizeof (struct tcpiphdr)) {
514			if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
515			    == NULL) {
516				tcpstat.tcps_rcvshort++;
517				return;
518			}
519		}
520		ip = mtod(m, struct ip *);
521		ipov = (struct ipovly *)ip;
522		th = (struct tcphdr *)((caddr_t)ip + off0);
523		tlen = ip->ip_len;
524
525		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
526			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
527				th->th_sum = m->m_pkthdr.csum_data;
528			else
529				th->th_sum = in_pseudo(ip->ip_src.s_addr,
530						ip->ip_dst.s_addr,
531						htonl(m->m_pkthdr.csum_data +
532							ip->ip_len +
533							IPPROTO_TCP));
534			th->th_sum ^= 0xffff;
535#ifdef TCPDEBUG
536			ipov->ih_len = (u_short)tlen;
537			ipov->ih_len = htons(ipov->ih_len);
538#endif
539		} else {
540			/*
541			 * Checksum extended TCP header and data.
542			 */
543			len = sizeof (struct ip) + tlen;
544			bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
545			ipov->ih_len = (u_short)tlen;
546			ipov->ih_len = htons(ipov->ih_len);
547			th->th_sum = in_cksum(m, len);
548		}
549		if (th->th_sum) {
550			tcpstat.tcps_rcvbadsum++;
551			goto drop;
552		}
553		/* Re-initialization for later version check */
554		ip->ip_v = IPVERSION;
555	}
556
557	/*
558	 * Check that TCP offset makes sense,
559	 * pull out TCP options and adjust length.		XXX
560	 */
561	off = th->th_off << 2;
562	if (off < sizeof (struct tcphdr) || off > tlen) {
563		tcpstat.tcps_rcvbadoff++;
564		goto drop;
565	}
566	tlen -= off;	/* tlen is used instead of ti->ti_len */
567	if (off > sizeof (struct tcphdr)) {
568		if (isipv6) {
569#ifdef INET6
570			IP6_EXTHDR_CHECK(m, off0, off, );
571			ip6 = mtod(m, struct ip6_hdr *);
572			th = (struct tcphdr *)((caddr_t)ip6 + off0);
573#endif
574		} else {
575			if (m->m_len < sizeof(struct ip) + off) {
576				if ((m = m_pullup(m, sizeof (struct ip) + off))
577				    == NULL) {
578					tcpstat.tcps_rcvshort++;
579					return;
580				}
581				ip = mtod(m, struct ip *);
582				ipov = (struct ipovly *)ip;
583				th = (struct tcphdr *)((caddr_t)ip + off0);
584			}
585		}
586		optlen = off - sizeof (struct tcphdr);
587		optp = (u_char *)(th + 1);
588	}
589	thflags = th->th_flags;
590
591	/*
592	 * If the drop_synfin option is enabled, drop all packets with
593	 * both the SYN and FIN bits set. This prevents e.g. nmap from
594	 * identifying the TCP/IP stack.
595	 *
596	 * This is a violation of the TCP specification.
597	 */
598	if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
599		goto drop;
600
601	/*
602	 * Convert TCP protocol specific fields to host format.
603	 */
604	th->th_seq = ntohl(th->th_seq);
605	th->th_ack = ntohl(th->th_ack);
606	th->th_win = ntohs(th->th_win);
607	th->th_urp = ntohs(th->th_urp);
608
609	/*
610	 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
611	 */
612	drop_hdrlen = off0 + off;
613
614	/*
615	 * Locate pcb for segment.
616	 */
617	INP_INFO_WLOCK(&tcbinfo);
618findpcb:
619	INP_INFO_WLOCK_ASSERT(&tcbinfo);
620#ifdef IPFIREWALL_FORWARD
621	/* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
622	fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
623
624	if (fwd_tag != NULL && isipv6 == 0) {	/* IPv6 support is not yet */
625		struct sockaddr_in *next_hop;
626
627		next_hop = (struct sockaddr_in *)(fwd_tag+1);
628		/*
629		 * Transparently forwarded. Pretend to be the destination.
630		 * already got one like this?
631		 */
632		inp = in_pcblookup_hash(&tcbinfo,
633					ip->ip_src, th->th_sport,
634					ip->ip_dst, th->th_dport,
635					0, m->m_pkthdr.rcvif);
636		if (!inp) {
637			/* It's new.  Try to find the ambushing socket. */
638			inp = in_pcblookup_hash(&tcbinfo,
639						ip->ip_src, th->th_sport,
640						next_hop->sin_addr,
641						next_hop->sin_port ?
642						    ntohs(next_hop->sin_port) :
643						    th->th_dport,
644						INPLOOKUP_WILDCARD,
645						m->m_pkthdr.rcvif);
646		}
647		/* Remove the tag from the packet.  We don't need it anymore. */
648		m_tag_delete(m, fwd_tag);
649	} else
650#endif /* IPFIREWALL_FORWARD */
651	{
652		if (isipv6) {
653#ifdef INET6
654			inp = in6_pcblookup_hash(&tcbinfo,
655						 &ip6->ip6_src, th->th_sport,
656						 &ip6->ip6_dst, th->th_dport,
657						 INPLOOKUP_WILDCARD,
658						 m->m_pkthdr.rcvif);
659#endif
660		} else
661			inp = in_pcblookup_hash(&tcbinfo,
662						ip->ip_src, th->th_sport,
663						ip->ip_dst, th->th_dport,
664						INPLOOKUP_WILDCARD,
665						m->m_pkthdr.rcvif);
666	}
667
668#if defined(IPSEC) || defined(FAST_IPSEC)
669#ifdef INET6
670	if (isipv6 && inp != NULL && ipsec6_in_reject(m, inp)) {
671#ifdef IPSEC
672		ipsec6stat.in_polvio++;
673#endif
674		goto dropunlock;
675	} else
676#endif /* INET6 */
677	if (inp != NULL && ipsec4_in_reject(m, inp)) {
678#ifdef IPSEC
679		ipsecstat.in_polvio++;
680#endif
681		goto dropunlock;
682	}
683#endif /*IPSEC || FAST_IPSEC*/
684
685	/*
686	 * If the INPCB does not exist then all data in the incoming
687	 * segment is discarded and an appropriate RST is sent back.
688	 */
689	if (inp == NULL) {
690		/*
691		 * Log communication attempts to ports that are not
692		 * in use.
693		 */
694		if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
695		    tcp_log_in_vain == 2) {
696#ifndef INET6
697			char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
698#else
699			char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
700			if (isipv6) {
701				strcpy(dbuf, "[");
702				strcat(dbuf,
703				    ip6_sprintf(ip6buf, &ip6->ip6_dst));
704				strcat(dbuf, "]");
705				strcpy(sbuf, "[");
706				strcat(sbuf,
707				    ip6_sprintf(ip6buf, &ip6->ip6_src));
708				strcat(sbuf, "]");
709			} else
710#endif /* INET6 */
711			{
712				strcpy(dbuf, inet_ntoa(ip->ip_dst));
713				strcpy(sbuf, inet_ntoa(ip->ip_src));
714			}
715			log(LOG_INFO,
716			    "Connection attempt to TCP %s:%d "
717			    "from %s:%d flags:0x%02x\n",
718			    dbuf, ntohs(th->th_dport), sbuf,
719			    ntohs(th->th_sport), thflags);
720		}
721		/*
722		 * When blackholing do not respond with a RST but
723		 * completely ignore the segment and drop it.
724		 */
725		if ((blackhole == 1 && (thflags & TH_SYN)) ||
726		    blackhole == 2)
727			goto dropunlock;
728
729		rstreason = BANDLIM_RST_CLOSEDPORT;
730		goto dropwithreset;
731	}
732	INP_LOCK(inp);
733
734	/* Check the minimum TTL for socket. */
735	if (inp->inp_ip_minttl != 0) {
736#ifdef INET6
737		if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
738			goto dropunlock;
739		else
740#endif
741		if (inp->inp_ip_minttl > ip->ip_ttl)
742			goto dropunlock;
743	}
744
745	/*
746	 * A previous connection in TIMEWAIT state is supposed to catch
747	 * stray or duplicate segments arriving late.  If this segment
748	 * was a legitimate new connection attempt the old INPCB gets
749	 * removed and we can try again to find a listening socket.
750	 */
751	if (inp->inp_vflag & INP_TIMEWAIT) {
752		if (thflags & TH_SYN)
753			tcp_dooptions(&to, optp, optlen, TO_SYN);
754		/* NB: tcp_timewait unlocks the INP and frees the mbuf. */
755		if (tcp_timewait(inp, &to, th, m, tlen))
756			goto findpcb;
757		INP_INFO_WUNLOCK(&tcbinfo);
758		return;
759	}
760	/*
761	 * The TCPCB may no longer exist if the connection is winding
762	 * down or it is in the CLOSED state.  Either way we drop the
763	 * segment and send an appropriate response.
764	 */
765	tp = intotcpcb(inp);
766	if (tp == NULL) {
767		rstreason = BANDLIM_RST_CLOSEDPORT;
768		goto dropwithreset;
769	}
770	if (tp->t_state == TCPS_CLOSED)
771		goto dropunlock;	/* XXX: dropwithreset??? */
772
773#ifdef MAC
774	INP_LOCK_ASSERT(inp);
775	if (mac_check_inpcb_deliver(inp, m))
776		goto dropunlock;
777#endif
778	so = inp->inp_socket;
779	KASSERT(so != NULL, ("%s: so == NULL", __func__));
780#ifdef TCPDEBUG
781	if (so->so_options & SO_DEBUG) {
782		ostate = tp->t_state;
783#ifdef INET6
784		if (isipv6)
785			bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
786		else
787#endif /* INET6 */
788			bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
789		tcp_savetcp = *th;
790	}
791#endif
792	/*
793	 * When the socket is accepting connections (the INPCB is in LISTEN
794	 * state) we look into the SYN cache if this is a new connection
795	 * attempt or the completion of a previous one.
796	 */
797	if (so->so_options & SO_ACCEPTCONN) {
798		struct in_conninfo inc;
799
800		KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
801		    "tp not listening", __func__));
802
803		bzero(&inc, sizeof(inc));
804		inc.inc_isipv6 = isipv6;
805#ifdef INET6
806		if (isipv6) {
807			inc.inc6_faddr = ip6->ip6_src;
808			inc.inc6_laddr = ip6->ip6_dst;
809		} else
810#endif
811		{
812			inc.inc_faddr = ip->ip_src;
813			inc.inc_laddr = ip->ip_dst;
814		}
815		inc.inc_fport = th->th_sport;
816		inc.inc_lport = th->th_dport;
817
818		/*
819		 * If the state is LISTEN then ignore segment if it contains
820		 * a RST.  If the segment contains an ACK then it is bad and
821		 * send a RST.  If it does not contain a SYN then it is not
822		 * interesting; drop it.
823		 *
824		 * If the state is SYN_RECEIVED (syncache) and seg contains
825		 * an ACK, but not for our SYN/ACK, send a RST.  If the seg
826		 * contains a RST, check the sequence number to see if it
827		 * is a valid reset segment.
828		 */
829		if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
830			if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
831				/*
832				 * Parse the TCP options here because
833				 * syncookies need access to the reflected
834				 * timestamp.
835				 */
836				tcp_dooptions(&to, optp, optlen, 0);
837				/*
838				 * NB: syncache_expand() doesn't unlock
839				 * inp and tcpinfo locks.
840				 */
841				if (!syncache_expand(&inc, &to, th, &so, m)) {
842					/*
843					 * No syncache entry or ACK was not
844					 * for our SYN/ACK.  Send a RST.
845					 */
846					rstreason = BANDLIM_RST_OPENPORT;
847					goto dropwithreset;
848				}
849				if (so == NULL) {
850					/*
851					 * We completed the 3-way handshake
852					 * but could not allocate a socket
853					 * either due to memory shortage,
854					 * listen queue length limits or
855					 * global socket limits.
856					 */
857					rstreason = BANDLIM_UNLIMITED;
858					goto dropwithreset;
859				}
860				/*
861				 * Socket is created in state SYN_RECEIVED.
862				 * Continue processing segment.
863				 */
864				INP_UNLOCK(inp);	/* listen socket */
865				inp = sotoinpcb(so);
866				INP_LOCK(inp);		/* new connection */
867				tp = intotcpcb(inp);
868				/*
869				 * Process the segment and the data it
870				 * contains.  tcp_do_segment() consumes
871				 * the mbuf chain and unlocks the inpcb.
872				 */
873				tcp_do_segment(m, th, so, tp, drop_hdrlen,
874						tlen);
875				INP_INFO_UNLOCK_ASSERT(&tcbinfo);
876				return;
877			}
878			if (thflags & TH_RST) {
879				syncache_chkrst(&inc, th);
880				goto dropunlock;
881			}
882			if (thflags & TH_ACK) {
883				syncache_badack(&inc);
884				tcpstat.tcps_badsyn++;
885				rstreason = BANDLIM_RST_OPENPORT;
886				goto dropwithreset;
887			}
888			goto dropunlock;
889		}
890
891		/*
892		 * Segment's flags are (SYN) or (SYN|FIN).
893		 */
894#ifdef INET6
895		/*
896		 * If deprecated address is forbidden,
897		 * we do not accept SYN to deprecated interface
898		 * address to prevent any new inbound connection from
899		 * getting established.
900		 * When we do not accept SYN, we send a TCP RST,
901		 * with deprecated source address (instead of dropping
902		 * it).  We compromise it as it is much better for peer
903		 * to send a RST, and RST will be the final packet
904		 * for the exchange.
905		 *
906		 * If we do not forbid deprecated addresses, we accept
907		 * the SYN packet.  RFC2462 does not suggest dropping
908		 * SYN in this case.
909		 * If we decipher RFC2462 5.5.4, it says like this:
910		 * 1. use of deprecated addr with existing
911		 *    communication is okay - "SHOULD continue to be
912		 *    used"
913		 * 2. use of it with new communication:
914		 *   (2a) "SHOULD NOT be used if alternate address
915		 *        with sufficient scope is available"
916		 *   (2b) nothing mentioned otherwise.
917		 * Here we fall into (2b) case as we have no choice in
918		 * our source address selection - we must obey the peer.
919		 *
920		 * The wording in RFC2462 is confusing, and there are
921		 * multiple description text for deprecated address
922		 * handling - worse, they are not exactly the same.
923		 * I believe 5.5.4 is the best one, so we follow 5.5.4.
924		 */
925		if (isipv6 && !ip6_use_deprecated) {
926			struct in6_ifaddr *ia6;
927
928			if ((ia6 = ip6_getdstifaddr(m)) &&
929			    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
930				rstreason = BANDLIM_RST_OPENPORT;
931				goto dropwithreset;
932			}
933		}
934#endif
935		/*
936		 * Basic sanity checks on incoming SYN requests:
937		 *
938		 * Don't bother responding if the destination was a
939		 * broadcast according to RFC1122 4.2.3.10, p. 104.
940		 *
941		 * If it is from this socket, drop it, it must be forged.
942		 *
943		 * Note that it is quite possible to receive unicast
944		 * link-layer packets with a broadcast IP address. Use
945		 * in_broadcast() to find them.
946		 */
947		if (m->m_flags & (M_BCAST|M_MCAST))
948			goto dropunlock;
949		if (isipv6) {
950#ifdef INET6
951			if (th->th_dport == th->th_sport &&
952			    IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src))
953				goto dropunlock;
954			if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
955			    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
956				goto dropunlock;
957#endif
958		} else {
959			if (th->th_dport == th->th_sport &&
960			    ip->ip_dst.s_addr == ip->ip_src.s_addr)
961				goto dropunlock;
962			if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
963			    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
964			    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
965			    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
966				goto dropunlock;
967		}
968		/*
969		 * SYN appears to be valid.  Create compressed TCP state
970		 * for syncache.
971		 */
972#ifdef TCPDEBUG
973		if (so->so_options & SO_DEBUG)
974			tcp_trace(TA_INPUT, ostate, tp,
975			    (void *)tcp_saveipgen, &tcp_savetcp, 0);
976#endif
977		tcp_dooptions(&to, optp, optlen, TO_SYN);
978		syncache_add(&inc, &to, th, inp, &so, m);
979		/*
980		 * Entry added to syncache and mbuf consumed.
981		 * Everything unlocked already by syncache_add().
982		 */
983		return;
984	}
985
986	/*
987	 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or late
988	 * state.  tcp_do_segment() always consumes the mbuf chain, unlocks the
989	 * inpcb, and unlocks the pcbinfo.
990	 */
991	tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen);
992	INP_INFO_UNLOCK_ASSERT(&tcbinfo);
993	return;
994
995dropwithreset:
996	INP_INFO_WLOCK_ASSERT(&tcbinfo);
997	tcp_dropwithreset(m, th, tp, tlen, rstreason);
998	m = NULL;	/* mbuf chain got consumed. */
999dropunlock:
1000	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1001	if (inp != NULL)
1002		INP_UNLOCK(inp);
1003	INP_INFO_WUNLOCK(&tcbinfo);
1004drop:
1005	INP_INFO_UNLOCK_ASSERT(&tcbinfo);
1006	if (m != NULL)
1007		m_freem(m);
1008	return;
1009}
1010
1011static void
1012tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1013    struct tcpcb *tp, int drop_hdrlen, int tlen)
1014{
1015	int thflags, acked, ourfinisacked, needoutput = 0;
1016	int headlocked = 1;
1017	int rstreason, todrop, win;
1018	u_long tiwin;
1019	struct tcpopt to;
1020
1021#ifdef TCPDEBUG
1022	/*
1023	 * The size of tcp_saveipgen must be the size of the max ip header,
1024	 * now IPv6.
1025	 */
1026	u_char tcp_saveipgen[IP6_HDR_LEN];
1027	struct tcphdr tcp_savetcp;
1028	short ostate = 0;
1029#endif
1030	thflags = th->th_flags;
1031
1032	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1033	INP_LOCK_ASSERT(tp->t_inpcb);
1034	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1035	    __func__));
1036	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1037	    __func__));
1038
1039	/*
1040	 * Segment received on connection.
1041	 * Reset idle time and keep-alive timer.
1042	 */
1043	tp->t_rcvtime = ticks;
1044	if (TCPS_HAVEESTABLISHED(tp->t_state))
1045		tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1046
1047	/*
1048	 * Unscale the window into a 32-bit value.
1049	 * This value is bogus for the TCPS_SYN_SENT state
1050	 * and is overwritten later.
1051	 */
1052	tiwin = th->th_win << tp->snd_scale;
1053
1054	/*
1055	 * Parse options on any incoming segment.
1056	 */
1057	tcp_dooptions(&to, (u_char *)(th + 1),
1058	    (th->th_off << 2) - sizeof(struct tcphdr),
1059	    (thflags & TH_SYN) ? TO_SYN : 0);
1060
1061	/*
1062	 * If echoed timestamp is later than the current time,
1063	 * fall back to non RFC1323 RTT calculation.  Normalize
1064	 * timestamp if syncookies were used when this connection
1065	 * was established.
1066	 */
1067	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1068		to.to_tsecr -= tp->ts_offset;
1069		if (TSTMP_GT(to.to_tsecr, ticks))
1070			to.to_tsecr = 0;
1071	}
1072
1073	/*
1074	 * Process options only when we get SYN/ACK back. The SYN case
1075	 * for incoming connections is handled in tcp_syncache.
1076	 * XXX this is traditional behavior, may need to be cleaned up.
1077	 */
1078	if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1079		if ((to.to_flags & TOF_SCALE) &&
1080		    (tp->t_flags & TF_REQ_SCALE)) {
1081			tp->t_flags |= TF_RCVD_SCALE;
1082			tp->snd_scale = to.to_wscale;
1083			tp->snd_wnd = th->th_win << tp->snd_scale;
1084			tiwin = tp->snd_wnd;
1085		}
1086		if (to.to_flags & TOF_TS) {
1087			tp->t_flags |= TF_RCVD_TSTMP;
1088			tp->ts_recent = to.to_tsval;
1089			tp->ts_recent_age = ticks;
1090		}
1091		/* Initial send window, already scaled. */
1092		tp->snd_wnd = th->th_win;
1093		if (to.to_flags & TOF_MSS)
1094			tcp_mss(tp, to.to_mss);
1095		if ((tp->t_flags & TF_SACK_PERMIT) &&
1096		    (to.to_flags & TOF_SACKPERM) == 0)
1097			tp->t_flags &= ~TF_SACK_PERMIT;
1098	}
1099
1100	/*
1101	 * Header prediction: check for the two common cases
1102	 * of a uni-directional data xfer.  If the packet has
1103	 * no control flags, is in-sequence, the window didn't
1104	 * change and we're not retransmitting, it's a
1105	 * candidate.  If the length is zero and the ack moved
1106	 * forward, we're the sender side of the xfer.  Just
1107	 * free the data acked & wake any higher level process
1108	 * that was blocked waiting for space.  If the length
1109	 * is non-zero and the ack didn't move, we're the
1110	 * receiver side.  If we're getting packets in-order
1111	 * (the reassembly queue is empty), add the data to
1112	 * the socket buffer and note that we need a delayed ack.
1113	 * Make sure that the hidden state-flags are also off.
1114	 * Since we check for TCPS_ESTABLISHED first, it can only
1115	 * be TH_NEEDSYN.
1116	 */
1117	if (tp->t_state == TCPS_ESTABLISHED &&
1118	    th->th_seq == tp->rcv_nxt &&
1119	    (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1120	    tp->snd_nxt == tp->snd_max &&
1121	    tiwin && tiwin == tp->snd_wnd &&
1122	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1123	    LIST_EMPTY(&tp->t_segq) &&
1124	    ((to.to_flags & TOF_TS) == 0 ||
1125	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1126
1127		/*
1128		 * If last ACK falls within this segment's sequence numbers,
1129		 * record the timestamp.
1130		 * NOTE that the test is modified according to the latest
1131		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1132		 */
1133		if ((to.to_flags & TOF_TS) != 0 &&
1134		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1135			tp->ts_recent_age = ticks;
1136			tp->ts_recent = to.to_tsval;
1137		}
1138
1139		if (tlen == 0) {
1140			if (SEQ_GT(th->th_ack, tp->snd_una) &&
1141			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
1142			    tp->snd_cwnd >= tp->snd_wnd &&
1143			    ((!tcp_do_newreno &&
1144			      !(tp->t_flags & TF_SACK_PERMIT) &&
1145			      tp->t_dupacks < tcprexmtthresh) ||
1146			     ((tcp_do_newreno ||
1147			       (tp->t_flags & TF_SACK_PERMIT)) &&
1148			      !IN_FASTRECOVERY(tp) &&
1149			      (to.to_flags & TOF_SACK) == 0 &&
1150			      TAILQ_EMPTY(&tp->snd_holes)))) {
1151				KASSERT(headlocked,
1152				    ("%s: headlocked", __func__));
1153				INP_INFO_WUNLOCK(&tcbinfo);
1154				headlocked = 0;
1155				/*
1156				 * this is a pure ack for outstanding data.
1157				 */
1158				++tcpstat.tcps_predack;
1159				/*
1160				 * "bad retransmit" recovery
1161				 */
1162				if (tp->t_rxtshift == 1 &&
1163				    ticks < tp->t_badrxtwin) {
1164					++tcpstat.tcps_sndrexmitbad;
1165					tp->snd_cwnd = tp->snd_cwnd_prev;
1166					tp->snd_ssthresh =
1167					    tp->snd_ssthresh_prev;
1168					tp->snd_recover = tp->snd_recover_prev;
1169					if (tp->t_flags & TF_WASFRECOVERY)
1170					    ENTER_FASTRECOVERY(tp);
1171					tp->snd_nxt = tp->snd_max;
1172					tp->t_badrxtwin = 0;
1173				}
1174
1175				/*
1176				 * Recalculate the transmit timer / rtt.
1177				 *
1178				 * Some boxes send broken timestamp replies
1179				 * during the SYN+ACK phase, ignore
1180				 * timestamps of 0 or we could calculate a
1181				 * huge RTT and blow up the retransmit timer.
1182				 */
1183				if ((to.to_flags & TOF_TS) != 0 &&
1184				    to.to_tsecr) {
1185					if (!tp->t_rttlow ||
1186					    tp->t_rttlow > ticks - to.to_tsecr)
1187						tp->t_rttlow = ticks - to.to_tsecr;
1188					tcp_xmit_timer(tp,
1189					    ticks - to.to_tsecr + 1);
1190				} else if (tp->t_rtttime &&
1191				    SEQ_GT(th->th_ack, tp->t_rtseq)) {
1192					if (!tp->t_rttlow ||
1193					    tp->t_rttlow > ticks - tp->t_rtttime)
1194						tp->t_rttlow = ticks - tp->t_rtttime;
1195					tcp_xmit_timer(tp,
1196							ticks - tp->t_rtttime);
1197				}
1198				tcp_xmit_bandwidth_limit(tp, th->th_ack);
1199				acked = th->th_ack - tp->snd_una;
1200				tcpstat.tcps_rcvackpack++;
1201				tcpstat.tcps_rcvackbyte += acked;
1202				sbdrop(&so->so_snd, acked);
1203				if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1204				    SEQ_LEQ(th->th_ack, tp->snd_recover))
1205					tp->snd_recover = th->th_ack - 1;
1206				tp->snd_una = th->th_ack;
1207				/*
1208				 * pull snd_wl2 up to prevent seq wrap relative
1209				 * to th_ack.
1210				 */
1211				tp->snd_wl2 = th->th_ack;
1212				tp->t_dupacks = 0;
1213				m_freem(m);
1214				ND6_HINT(tp); /* some progress has been done */
1215
1216				/*
1217				 * If all outstanding data are acked, stop
1218				 * retransmit timer, otherwise restart timer
1219				 * using current (possibly backed-off) value.
1220				 * If process is waiting for space,
1221				 * wakeup/selwakeup/signal.  If data
1222				 * are ready to send, let tcp_output
1223				 * decide between more output or persist.
1224
1225#ifdef TCPDEBUG
1226				if (so->so_options & SO_DEBUG)
1227					tcp_trace(TA_INPUT, ostate, tp,
1228					    (void *)tcp_saveipgen,
1229					    &tcp_savetcp, 0);
1230#endif
1231				 */
1232				if (tp->snd_una == tp->snd_max)
1233					tcp_timer_activate(tp, TT_REXMT, 0);
1234				else if (!tcp_timer_active(tp, TT_PERSIST))
1235					tcp_timer_activate(tp, TT_REXMT,
1236						      tp->t_rxtcur);
1237
1238				sowwakeup(so);
1239				if (so->so_snd.sb_cc)
1240					(void) tcp_output(tp);
1241				goto check_delack;
1242			}
1243		} else if (th->th_ack == tp->snd_una &&
1244		    tlen <= sbspace(&so->so_rcv)) {
1245			int newsize = 0;	/* automatic sockbuf scaling */
1246
1247			KASSERT(headlocked, ("%s: headlocked", __func__));
1248			INP_INFO_WUNLOCK(&tcbinfo);
1249			headlocked = 0;
1250			/*
1251			 * this is a pure, in-sequence data packet
1252			 * with nothing on the reassembly queue and
1253			 * we have enough buffer space to take it.
1254			 */
1255			/* Clean receiver SACK report if present */
1256			if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1257				tcp_clean_sackreport(tp);
1258			++tcpstat.tcps_preddat;
1259			tp->rcv_nxt += tlen;
1260			/*
1261			 * Pull snd_wl1 up to prevent seq wrap relative to
1262			 * th_seq.
1263			 */
1264			tp->snd_wl1 = th->th_seq;
1265			/*
1266			 * Pull rcv_up up to prevent seq wrap relative to
1267			 * rcv_nxt.
1268			 */
1269			tp->rcv_up = tp->rcv_nxt;
1270			tcpstat.tcps_rcvpack++;
1271			tcpstat.tcps_rcvbyte += tlen;
1272			ND6_HINT(tp);	/* some progress has been done */
1273#ifdef TCPDEBUG
1274			if (so->so_options & SO_DEBUG)
1275				tcp_trace(TA_INPUT, ostate, tp,
1276				    (void *)tcp_saveipgen, &tcp_savetcp, 0);
1277#endif
1278		/*
1279		 * Automatic sizing of receive socket buffer.  Often the send
1280		 * buffer size is not optimally adjusted to the actual network
1281		 * conditions at hand (delay bandwidth product).  Setting the
1282		 * buffer size too small limits throughput on links with high
1283		 * bandwidth and high delay (eg. trans-continental/oceanic links).
1284		 *
1285		 * On the receive side the socket buffer memory is only rarely
1286		 * used to any significant extent.  This allows us to be much
1287		 * more aggressive in scaling the receive socket buffer.  For
1288		 * the case that the buffer space is actually used to a large
1289		 * extent and we run out of kernel memory we can simply drop
1290		 * the new segments; TCP on the sender will just retransmit it
1291		 * later.  Setting the buffer size too big may only consume too
1292		 * much kernel memory if the application doesn't read() from
1293		 * the socket or packet loss or reordering makes use of the
1294		 * reassembly queue.
1295		 *
1296		 * The criteria to step up the receive buffer one notch are:
1297		 *  1. the number of bytes received during the time it takes
1298		 *     one timestamp to be reflected back to us (the RTT);
1299		 *  2. received bytes per RTT is within seven eighth of the
1300		 *     current socket buffer size;
1301		 *  3. receive buffer size has not hit maximal automatic size;
1302		 *
1303		 * This algorithm does one step per RTT at most and only if
1304		 * we receive a bulk stream w/o packet losses or reorderings.
1305		 * Shrinking the buffer during idle times is not necessary as
1306		 * it doesn't consume any memory when idle.
1307		 *
1308		 * TODO: Only step up if the application is actually serving
1309		 * the buffer to better manage the socket buffer resources.
1310		 */
1311			if (tcp_do_autorcvbuf &&
1312			    to.to_tsecr &&
1313			    (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1314				if (to.to_tsecr > tp->rfbuf_ts &&
1315				    to.to_tsecr - tp->rfbuf_ts < hz) {
1316					if (tp->rfbuf_cnt >
1317					    (so->so_rcv.sb_hiwat / 8 * 7) &&
1318					    so->so_rcv.sb_hiwat <
1319					    tcp_autorcvbuf_max) {
1320						newsize =
1321						    min(so->so_rcv.sb_hiwat +
1322						    tcp_autorcvbuf_inc,
1323						    tcp_autorcvbuf_max);
1324					}
1325					/* Start over with next RTT. */
1326					tp->rfbuf_ts = 0;
1327					tp->rfbuf_cnt = 0;
1328				} else
1329					tp->rfbuf_cnt += tlen;	/* add up */
1330			}
1331
1332			/* Add data to socket buffer. */
1333			SOCKBUF_LOCK(&so->so_rcv);
1334			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1335				m_freem(m);
1336			} else {
1337				/*
1338				 * Set new socket buffer size.
1339				 * Give up when limit is reached.
1340				 */
1341				if (newsize)
1342					if (!sbreserve_locked(&so->so_rcv,
1343					    newsize, so, curthread))
1344						so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1345				m_adj(m, drop_hdrlen);	/* delayed header drop */
1346				sbappendstream_locked(&so->so_rcv, m);
1347			}
1348			sorwakeup_locked(so);
1349			if (DELAY_ACK(tp)) {
1350				tp->t_flags |= TF_DELACK;
1351			} else {
1352				tp->t_flags |= TF_ACKNOW;
1353				tcp_output(tp);
1354			}
1355			goto check_delack;
1356		}
1357	}
1358
1359	/*
1360	 * Calculate amount of space in receive window,
1361	 * and then do TCP input processing.
1362	 * Receive window is amount of space in rcv queue,
1363	 * but not less than advertised window.
1364	 */
1365	win = sbspace(&so->so_rcv);
1366	if (win < 0)
1367		win = 0;
1368	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1369
1370	/* Reset receive buffer auto scaling when not in bulk receive mode. */
1371	tp->rfbuf_ts = 0;
1372	tp->rfbuf_cnt = 0;
1373
1374	switch (tp->t_state) {
1375
1376	/*
1377	 * If the state is SYN_RECEIVED:
1378	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
1379	 */
1380	case TCPS_SYN_RECEIVED:
1381		if ((thflags & TH_ACK) &&
1382		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1383		     SEQ_GT(th->th_ack, tp->snd_max))) {
1384				rstreason = BANDLIM_RST_OPENPORT;
1385				goto dropwithreset;
1386		}
1387		break;
1388
1389	/*
1390	 * If the state is SYN_SENT:
1391	 *	if seg contains an ACK, but not for our SYN, drop the input.
1392	 *	if seg contains a RST, then drop the connection.
1393	 *	if seg does not contain SYN, then drop it.
1394	 * Otherwise this is an acceptable SYN segment
1395	 *	initialize tp->rcv_nxt and tp->irs
1396	 *	if seg contains ack then advance tp->snd_una
1397	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1398	 *	arrange for segment to be acked (eventually)
1399	 *	continue processing rest of data/controls, beginning with URG
1400	 */
1401	case TCPS_SYN_SENT:
1402		if ((thflags & TH_ACK) &&
1403		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1404		     SEQ_GT(th->th_ack, tp->snd_max))) {
1405			rstreason = BANDLIM_UNLIMITED;
1406			goto dropwithreset;
1407		}
1408		if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
1409			tp = tcp_drop(tp, ECONNREFUSED);
1410		if (thflags & TH_RST)
1411			goto drop;
1412		if (!(thflags & TH_SYN))
1413			goto drop;
1414
1415		tp->irs = th->th_seq;
1416		tcp_rcvseqinit(tp);
1417		if (thflags & TH_ACK) {
1418			tcpstat.tcps_connects++;
1419			soisconnected(so);
1420#ifdef MAC
1421			SOCK_LOCK(so);
1422			mac_set_socket_peer_from_mbuf(m, so);
1423			SOCK_UNLOCK(so);
1424#endif
1425			/* Do window scaling on this connection? */
1426			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1427				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1428				tp->rcv_scale = tp->request_r_scale;
1429			}
1430			tp->rcv_adv += tp->rcv_wnd;
1431			tp->snd_una++;		/* SYN is acked */
1432			/*
1433			 * If there's data, delay ACK; if there's also a FIN
1434			 * ACKNOW will be turned on later.
1435			 */
1436			if (DELAY_ACK(tp) && tlen != 0)
1437				tcp_timer_activate(tp, TT_DELACK,
1438				    tcp_delacktime);
1439			else
1440				tp->t_flags |= TF_ACKNOW;
1441			/*
1442			 * Received <SYN,ACK> in SYN_SENT[*] state.
1443			 * Transitions:
1444			 *	SYN_SENT  --> ESTABLISHED
1445			 *	SYN_SENT* --> FIN_WAIT_1
1446			 */
1447			tp->t_starttime = ticks;
1448			if (tp->t_flags & TF_NEEDFIN) {
1449				tp->t_state = TCPS_FIN_WAIT_1;
1450				tp->t_flags &= ~TF_NEEDFIN;
1451				thflags &= ~TH_SYN;
1452			} else {
1453				tp->t_state = TCPS_ESTABLISHED;
1454				tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1455			}
1456		} else {
1457			/*
1458			 * Received initial SYN in SYN-SENT[*] state =>
1459			 * simultaneous open.  If segment contains CC option
1460			 * and there is a cached CC, apply TAO test.
1461			 * If it succeeds, connection is * half-synchronized.
1462			 * Otherwise, do 3-way handshake:
1463			 *        SYN-SENT -> SYN-RECEIVED
1464			 *        SYN-SENT* -> SYN-RECEIVED*
1465			 * If there was no CC option, clear cached CC value.
1466			 */
1467			tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1468			tcp_timer_activate(tp, TT_REXMT, 0);
1469			tp->t_state = TCPS_SYN_RECEIVED;
1470		}
1471
1472		KASSERT(headlocked, ("%s: trimthenstep6: head not locked",
1473		    __func__));
1474		INP_LOCK_ASSERT(tp->t_inpcb);
1475
1476		/*
1477		 * Advance th->th_seq to correspond to first data byte.
1478		 * If data, trim to stay within window,
1479		 * dropping FIN if necessary.
1480		 */
1481		th->th_seq++;
1482		if (tlen > tp->rcv_wnd) {
1483			todrop = tlen - tp->rcv_wnd;
1484			m_adj(m, -todrop);
1485			tlen = tp->rcv_wnd;
1486			thflags &= ~TH_FIN;
1487			tcpstat.tcps_rcvpackafterwin++;
1488			tcpstat.tcps_rcvbyteafterwin += todrop;
1489		}
1490		tp->snd_wl1 = th->th_seq - 1;
1491		tp->rcv_up = th->th_seq;
1492		/*
1493		 * Client side of transaction: already sent SYN and data.
1494		 * If the remote host used T/TCP to validate the SYN,
1495		 * our data will be ACK'd; if so, enter normal data segment
1496		 * processing in the middle of step 5, ack processing.
1497		 * Otherwise, goto step 6.
1498		 */
1499		if (thflags & TH_ACK)
1500			goto process_ACK;
1501
1502		goto step6;
1503
1504	/*
1505	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1506	 *      do normal processing.
1507	 *
1508	 * NB: Leftover from RFC1644 T/TCP.  Cases to be reused later.
1509	 */
1510	case TCPS_LAST_ACK:
1511	case TCPS_CLOSING:
1512		break;  /* continue normal processing */
1513	}
1514
1515	/*
1516	 * States other than LISTEN or SYN_SENT.
1517	 * First check the RST flag and sequence number since reset segments
1518	 * are exempt from the timestamp and connection count tests.  This
1519	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1520	 * below which allowed reset segments in half the sequence space
1521	 * to fall though and be processed (which gives forged reset
1522	 * segments with a random sequence number a 50 percent chance of
1523	 * killing a connection).
1524	 * Then check timestamp, if present.
1525	 * Then check the connection count, if present.
1526	 * Then check that at least some bytes of segment are within
1527	 * receive window.  If segment begins before rcv_nxt,
1528	 * drop leading data (and SYN); if nothing left, just ack.
1529	 *
1530	 *
1531	 * If the RST bit is set, check the sequence number to see
1532	 * if this is a valid reset segment.
1533	 * RFC 793 page 37:
1534	 *   In all states except SYN-SENT, all reset (RST) segments
1535	 *   are validated by checking their SEQ-fields.  A reset is
1536	 *   valid if its sequence number is in the window.
1537	 * Note: this does not take into account delayed ACKs, so
1538	 *   we should test against last_ack_sent instead of rcv_nxt.
1539	 *   The sequence number in the reset segment is normally an
1540	 *   echo of our outgoing acknowlegement numbers, but some hosts
1541	 *   send a reset with the sequence number at the rightmost edge
1542	 *   of our receive window, and we have to handle this case.
1543	 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1544	 *   that brute force RST attacks are possible.  To combat this,
1545	 *   we use a much stricter check while in the ESTABLISHED state,
1546	 *   only accepting RSTs where the sequence number is equal to
1547	 *   last_ack_sent.  In all other states (the states in which a
1548	 *   RST is more likely), the more permissive check is used.
1549	 * If we have multiple segments in flight, the intial reset
1550	 * segment sequence numbers will be to the left of last_ack_sent,
1551	 * but they will eventually catch up.
1552	 * In any case, it never made sense to trim reset segments to
1553	 * fit the receive window since RFC 1122 says:
1554	 *   4.2.2.12  RST Segment: RFC-793 Section 3.4
1555	 *
1556	 *    A TCP SHOULD allow a received RST segment to include data.
1557	 *
1558	 *    DISCUSSION
1559	 *         It has been suggested that a RST segment could contain
1560	 *         ASCII text that encoded and explained the cause of the
1561	 *         RST.  No standard has yet been established for such
1562	 *         data.
1563	 *
1564	 * If the reset segment passes the sequence number test examine
1565	 * the state:
1566	 *    SYN_RECEIVED STATE:
1567	 *	If passive open, return to LISTEN state.
1568	 *	If active open, inform user that connection was refused.
1569	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1570	 *	Inform user that connection was reset, and close tcb.
1571	 *    CLOSING, LAST_ACK STATES:
1572	 *	Close the tcb.
1573	 *    TIME_WAIT STATE:
1574	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
1575	 *      RFC 1337.
1576	 */
1577	if (thflags & TH_RST) {
1578		if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1579		    SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1580			switch (tp->t_state) {
1581
1582			case TCPS_SYN_RECEIVED:
1583				so->so_error = ECONNREFUSED;
1584				goto close;
1585
1586			case TCPS_ESTABLISHED:
1587				if (tcp_insecure_rst == 0 &&
1588				    !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1589				    SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1590				    !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1591				    SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1592					tcpstat.tcps_badrst++;
1593					goto drop;
1594				}
1595			case TCPS_FIN_WAIT_1:
1596			case TCPS_FIN_WAIT_2:
1597			case TCPS_CLOSE_WAIT:
1598				so->so_error = ECONNRESET;
1599			close:
1600				tp->t_state = TCPS_CLOSED;
1601				tcpstat.tcps_drops++;
1602				KASSERT(headlocked, ("%s: trimthenstep6: "
1603				    "tcp_close: head not locked", __func__));
1604				tp = tcp_close(tp);
1605				break;
1606
1607			case TCPS_CLOSING:
1608			case TCPS_LAST_ACK:
1609				KASSERT(headlocked, ("%s: trimthenstep6: "
1610				    "tcp_close.2: head not locked", __func__));
1611				tp = tcp_close(tp);
1612				break;
1613			}
1614		}
1615		goto drop;
1616	}
1617
1618	/*
1619	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1620	 * and it's less than ts_recent, drop it.
1621	 */
1622	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1623	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1624
1625		/* Check to see if ts_recent is over 24 days old.  */
1626		if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1627			/*
1628			 * Invalidate ts_recent.  If this segment updates
1629			 * ts_recent, the age will be reset later and ts_recent
1630			 * will get a valid value.  If it does not, setting
1631			 * ts_recent to zero will at least satisfy the
1632			 * requirement that zero be placed in the timestamp
1633			 * echo reply when ts_recent isn't valid.  The
1634			 * age isn't reset until we get a valid ts_recent
1635			 * because we don't want out-of-order segments to be
1636			 * dropped when ts_recent is old.
1637			 */
1638			tp->ts_recent = 0;
1639		} else {
1640			tcpstat.tcps_rcvduppack++;
1641			tcpstat.tcps_rcvdupbyte += tlen;
1642			tcpstat.tcps_pawsdrop++;
1643			if (tlen)
1644				goto dropafterack;
1645			goto drop;
1646		}
1647	}
1648
1649	/*
1650	 * In the SYN-RECEIVED state, validate that the packet belongs to
1651	 * this connection before trimming the data to fit the receive
1652	 * window.  Check the sequence number versus IRS since we know
1653	 * the sequence numbers haven't wrapped.  This is a partial fix
1654	 * for the "LAND" DoS attack.
1655	 */
1656	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1657		rstreason = BANDLIM_RST_OPENPORT;
1658		goto dropwithreset;
1659	}
1660
1661	todrop = tp->rcv_nxt - th->th_seq;
1662	if (todrop > 0) {
1663		if (thflags & TH_SYN) {
1664			thflags &= ~TH_SYN;
1665			th->th_seq++;
1666			if (th->th_urp > 1)
1667				th->th_urp--;
1668			else
1669				thflags &= ~TH_URG;
1670			todrop--;
1671		}
1672		/*
1673		 * Following if statement from Stevens, vol. 2, p. 960.
1674		 */
1675		if (todrop > tlen
1676		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1677			/*
1678			 * Any valid FIN must be to the left of the window.
1679			 * At this point the FIN must be a duplicate or out
1680			 * of sequence; drop it.
1681			 */
1682			thflags &= ~TH_FIN;
1683
1684			/*
1685			 * Send an ACK to resynchronize and drop any data.
1686			 * But keep on processing for RST or ACK.
1687			 */
1688			tp->t_flags |= TF_ACKNOW;
1689			todrop = tlen;
1690			tcpstat.tcps_rcvduppack++;
1691			tcpstat.tcps_rcvdupbyte += todrop;
1692		} else {
1693			tcpstat.tcps_rcvpartduppack++;
1694			tcpstat.tcps_rcvpartdupbyte += todrop;
1695		}
1696		drop_hdrlen += todrop;	/* drop from the top afterwards */
1697		th->th_seq += todrop;
1698		tlen -= todrop;
1699		if (th->th_urp > todrop)
1700			th->th_urp -= todrop;
1701		else {
1702			thflags &= ~TH_URG;
1703			th->th_urp = 0;
1704		}
1705	}
1706
1707	/*
1708	 * If new data are received on a connection after the
1709	 * user processes are gone, then RST the other end.
1710	 */
1711	if ((so->so_state & SS_NOFDREF) &&
1712	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1713		KASSERT(headlocked, ("%s: trimthenstep6: tcp_close.3: head "
1714		    "not locked", __func__));
1715		tp = tcp_close(tp);
1716		tcpstat.tcps_rcvafterclose++;
1717		rstreason = BANDLIM_UNLIMITED;
1718		goto dropwithreset;
1719	}
1720
1721	/*
1722	 * If segment ends after window, drop trailing data
1723	 * (and PUSH and FIN); if nothing left, just ACK.
1724	 */
1725	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1726	if (todrop > 0) {
1727		tcpstat.tcps_rcvpackafterwin++;
1728		if (todrop >= tlen) {
1729			tcpstat.tcps_rcvbyteafterwin += tlen;
1730			/*
1731			 * If window is closed can only take segments at
1732			 * window edge, and have to drop data and PUSH from
1733			 * incoming segments.  Continue processing, but
1734			 * remember to ack.  Otherwise, drop segment
1735			 * and ack.
1736			 */
1737			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1738				tp->t_flags |= TF_ACKNOW;
1739				tcpstat.tcps_rcvwinprobe++;
1740			} else
1741				goto dropafterack;
1742		} else
1743			tcpstat.tcps_rcvbyteafterwin += todrop;
1744		m_adj(m, -todrop);
1745		tlen -= todrop;
1746		thflags &= ~(TH_PUSH|TH_FIN);
1747	}
1748
1749	/*
1750	 * If last ACK falls within this segment's sequence numbers,
1751	 * record its timestamp.
1752	 * NOTE:
1753	 * 1) That the test incorporates suggestions from the latest
1754	 *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
1755	 * 2) That updating only on newer timestamps interferes with
1756	 *    our earlier PAWS tests, so this check should be solely
1757	 *    predicated on the sequence space of this segment.
1758	 * 3) That we modify the segment boundary check to be
1759	 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
1760	 *    instead of RFC1323's
1761	 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
1762	 *    This modified check allows us to overcome RFC1323's
1763	 *    limitations as described in Stevens TCP/IP Illustrated
1764	 *    Vol. 2 p.869. In such cases, we can still calculate the
1765	 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
1766	 */
1767	if ((to.to_flags & TOF_TS) != 0 &&
1768	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1769	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1770		((thflags & (TH_SYN|TH_FIN)) != 0))) {
1771		tp->ts_recent_age = ticks;
1772		tp->ts_recent = to.to_tsval;
1773	}
1774
1775	/*
1776	 * If a SYN is in the window, then this is an
1777	 * error and we send an RST and drop the connection.
1778	 */
1779	if (thflags & TH_SYN) {
1780		KASSERT(headlocked, ("%s: tcp_drop: trimthenstep6: "
1781		    "head not locked", __func__));
1782		tp = tcp_drop(tp, ECONNRESET);
1783		rstreason = BANDLIM_UNLIMITED;
1784		goto drop;
1785	}
1786
1787	/*
1788	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1789	 * flag is on (half-synchronized state), then queue data for
1790	 * later processing; else drop segment and return.
1791	 */
1792	if ((thflags & TH_ACK) == 0) {
1793		if (tp->t_state == TCPS_SYN_RECEIVED ||
1794		    (tp->t_flags & TF_NEEDSYN))
1795			goto step6;
1796		else if (tp->t_flags & TF_ACKNOW)
1797			goto dropafterack;
1798		else
1799			goto drop;
1800	}
1801
1802	/*
1803	 * Ack processing.
1804	 */
1805	switch (tp->t_state) {
1806
1807	/*
1808	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1809	 * ESTABLISHED state and continue processing.
1810	 * The ACK was checked above.
1811	 */
1812	case TCPS_SYN_RECEIVED:
1813
1814		tcpstat.tcps_connects++;
1815		soisconnected(so);
1816		/* Do window scaling? */
1817		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1818			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1819			tp->rcv_scale = tp->request_r_scale;
1820			tp->snd_wnd = tiwin;
1821		}
1822		/*
1823		 * Make transitions:
1824		 *      SYN-RECEIVED  -> ESTABLISHED
1825		 *      SYN-RECEIVED* -> FIN-WAIT-1
1826		 */
1827		tp->t_starttime = ticks;
1828		if (tp->t_flags & TF_NEEDFIN) {
1829			tp->t_state = TCPS_FIN_WAIT_1;
1830			tp->t_flags &= ~TF_NEEDFIN;
1831		} else {
1832			tp->t_state = TCPS_ESTABLISHED;
1833			tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1834		}
1835		/*
1836		 * If segment contains data or ACK, will call tcp_reass()
1837		 * later; if not, do so now to pass queued data to user.
1838		 */
1839		if (tlen == 0 && (thflags & TH_FIN) == 0)
1840			(void) tcp_reass(tp, (struct tcphdr *)0, 0,
1841			    (struct mbuf *)0);
1842		tp->snd_wl1 = th->th_seq - 1;
1843		/* FALLTHROUGH */
1844
1845	/*
1846	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1847	 * ACKs.  If the ack is in the range
1848	 *	tp->snd_una < th->th_ack <= tp->snd_max
1849	 * then advance tp->snd_una to th->th_ack and drop
1850	 * data from the retransmission queue.  If this ACK reflects
1851	 * more up to date window information we update our window information.
1852	 */
1853	case TCPS_ESTABLISHED:
1854	case TCPS_FIN_WAIT_1:
1855	case TCPS_FIN_WAIT_2:
1856	case TCPS_CLOSE_WAIT:
1857	case TCPS_CLOSING:
1858	case TCPS_LAST_ACK:
1859		if (SEQ_GT(th->th_ack, tp->snd_max)) {
1860			tcpstat.tcps_rcvacktoomuch++;
1861			goto dropafterack;
1862		}
1863		if ((tp->t_flags & TF_SACK_PERMIT) &&
1864		    ((to.to_flags & TOF_SACK) ||
1865		     !TAILQ_EMPTY(&tp->snd_holes)))
1866			tcp_sack_doack(tp, &to, th->th_ack);
1867		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1868			if (tlen == 0 && tiwin == tp->snd_wnd) {
1869				tcpstat.tcps_rcvdupack++;
1870				/*
1871				 * If we have outstanding data (other than
1872				 * a window probe), this is a completely
1873				 * duplicate ack (ie, window info didn't
1874				 * change), the ack is the biggest we've
1875				 * seen and we've seen exactly our rexmt
1876				 * threshhold of them, assume a packet
1877				 * has been dropped and retransmit it.
1878				 * Kludge snd_nxt & the congestion
1879				 * window so we send only this one
1880				 * packet.
1881				 *
1882				 * We know we're losing at the current
1883				 * window size so do congestion avoidance
1884				 * (set ssthresh to half the current window
1885				 * and pull our congestion window back to
1886				 * the new ssthresh).
1887				 *
1888				 * Dup acks mean that packets have left the
1889				 * network (they're now cached at the receiver)
1890				 * so bump cwnd by the amount in the receiver
1891				 * to keep a constant cwnd packets in the
1892				 * network.
1893				 */
1894				if (!tcp_timer_active(tp, TT_REXMT) ||
1895				    th->th_ack != tp->snd_una)
1896					tp->t_dupacks = 0;
1897				else if (++tp->t_dupacks > tcprexmtthresh ||
1898				    ((tcp_do_newreno ||
1899				      (tp->t_flags & TF_SACK_PERMIT)) &&
1900				     IN_FASTRECOVERY(tp))) {
1901					if ((tp->t_flags & TF_SACK_PERMIT) &&
1902					    IN_FASTRECOVERY(tp)) {
1903						int awnd;
1904
1905						/*
1906						 * Compute the amount of data in flight first.
1907						 * We can inject new data into the pipe iff
1908						 * we have less than 1/2 the original window's
1909						 * worth of data in flight.
1910						 */
1911						awnd = (tp->snd_nxt - tp->snd_fack) +
1912							tp->sackhint.sack_bytes_rexmit;
1913						if (awnd < tp->snd_ssthresh) {
1914							tp->snd_cwnd += tp->t_maxseg;
1915							if (tp->snd_cwnd > tp->snd_ssthresh)
1916								tp->snd_cwnd = tp->snd_ssthresh;
1917						}
1918					} else
1919						tp->snd_cwnd += tp->t_maxseg;
1920					(void) tcp_output(tp);
1921					goto drop;
1922				} else if (tp->t_dupacks == tcprexmtthresh) {
1923					tcp_seq onxt = tp->snd_nxt;
1924					u_int win;
1925
1926					/*
1927					 * If we're doing sack, check to
1928					 * see if we're already in sack
1929					 * recovery. If we're not doing sack,
1930					 * check to see if we're in newreno
1931					 * recovery.
1932					 */
1933					if (tp->t_flags & TF_SACK_PERMIT) {
1934						if (IN_FASTRECOVERY(tp)) {
1935							tp->t_dupacks = 0;
1936							break;
1937						}
1938					} else if (tcp_do_newreno) {
1939						if (SEQ_LEQ(th->th_ack,
1940						    tp->snd_recover)) {
1941							tp->t_dupacks = 0;
1942							break;
1943						}
1944					}
1945					win = min(tp->snd_wnd, tp->snd_cwnd) /
1946					    2 / tp->t_maxseg;
1947					if (win < 2)
1948						win = 2;
1949					tp->snd_ssthresh = win * tp->t_maxseg;
1950					ENTER_FASTRECOVERY(tp);
1951					tp->snd_recover = tp->snd_max;
1952					tcp_timer_activate(tp, TT_REXMT, 0);
1953					tp->t_rtttime = 0;
1954					if (tp->t_flags & TF_SACK_PERMIT) {
1955						tcpstat.tcps_sack_recovery_episode++;
1956						tp->sack_newdata = tp->snd_nxt;
1957						tp->snd_cwnd = tp->t_maxseg;
1958						(void) tcp_output(tp);
1959						goto drop;
1960					}
1961					tp->snd_nxt = th->th_ack;
1962					tp->snd_cwnd = tp->t_maxseg;
1963					(void) tcp_output(tp);
1964					KASSERT(tp->snd_limited <= 2,
1965					    ("%s: tp->snd_limited too big",
1966					    __func__));
1967					tp->snd_cwnd = tp->snd_ssthresh +
1968					     tp->t_maxseg *
1969					     (tp->t_dupacks - tp->snd_limited);
1970					if (SEQ_GT(onxt, tp->snd_nxt))
1971						tp->snd_nxt = onxt;
1972					goto drop;
1973				} else if (tcp_do_rfc3042) {
1974					u_long oldcwnd = tp->snd_cwnd;
1975					tcp_seq oldsndmax = tp->snd_max;
1976					u_int sent;
1977
1978					KASSERT(tp->t_dupacks == 1 ||
1979					    tp->t_dupacks == 2,
1980					    ("%s: dupacks not 1 or 2",
1981					    __func__));
1982					if (tp->t_dupacks == 1)
1983						tp->snd_limited = 0;
1984					tp->snd_cwnd =
1985					    (tp->snd_nxt - tp->snd_una) +
1986					    (tp->t_dupacks - tp->snd_limited) *
1987					    tp->t_maxseg;
1988					(void) tcp_output(tp);
1989					sent = tp->snd_max - oldsndmax;
1990					if (sent > tp->t_maxseg) {
1991						KASSERT((tp->t_dupacks == 2 &&
1992						    tp->snd_limited == 0) ||
1993						   (sent == tp->t_maxseg + 1 &&
1994						    tp->t_flags & TF_SENTFIN),
1995						    ("%s: sent too much",
1996						    __func__));
1997						tp->snd_limited = 2;
1998					} else if (sent > 0)
1999						++tp->snd_limited;
2000					tp->snd_cwnd = oldcwnd;
2001					goto drop;
2002				}
2003			} else
2004				tp->t_dupacks = 0;
2005			break;
2006		}
2007
2008		KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2009		    ("%s: th_ack <= snd_una", __func__));
2010
2011		/*
2012		 * If the congestion window was inflated to account
2013		 * for the other side's cached packets, retract it.
2014		 */
2015		if (tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) {
2016			if (IN_FASTRECOVERY(tp)) {
2017				if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2018					if (tp->t_flags & TF_SACK_PERMIT)
2019						tcp_sack_partialack(tp, th);
2020					else
2021						tcp_newreno_partial_ack(tp, th);
2022				} else {
2023					/*
2024					 * Out of fast recovery.
2025					 * Window inflation should have left us
2026					 * with approximately snd_ssthresh
2027					 * outstanding data.
2028					 * But in case we would be inclined to
2029					 * send a burst, better to do it via
2030					 * the slow start mechanism.
2031					 */
2032					if (SEQ_GT(th->th_ack +
2033							tp->snd_ssthresh,
2034						   tp->snd_max))
2035						tp->snd_cwnd = tp->snd_max -
2036								th->th_ack +
2037								tp->t_maxseg;
2038					else
2039						tp->snd_cwnd = tp->snd_ssthresh;
2040				}
2041			}
2042		} else {
2043			if (tp->t_dupacks >= tcprexmtthresh &&
2044			    tp->snd_cwnd > tp->snd_ssthresh)
2045				tp->snd_cwnd = tp->snd_ssthresh;
2046		}
2047		tp->t_dupacks = 0;
2048		/*
2049		 * If we reach this point, ACK is not a duplicate,
2050		 *     i.e., it ACKs something we sent.
2051		 */
2052		if (tp->t_flags & TF_NEEDSYN) {
2053			/*
2054			 * T/TCP: Connection was half-synchronized, and our
2055			 * SYN has been ACK'd (so connection is now fully
2056			 * synchronized).  Go to non-starred state,
2057			 * increment snd_una for ACK of SYN, and check if
2058			 * we can do window scaling.
2059			 */
2060			tp->t_flags &= ~TF_NEEDSYN;
2061			tp->snd_una++;
2062			/* Do window scaling? */
2063			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2064				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
2065				tp->rcv_scale = tp->request_r_scale;
2066				/* Send window already scaled. */
2067			}
2068		}
2069
2070process_ACK:
2071		KASSERT(headlocked, ("%s: process_ACK: head not locked",
2072		    __func__));
2073		INP_LOCK_ASSERT(tp->t_inpcb);
2074
2075		acked = th->th_ack - tp->snd_una;
2076		tcpstat.tcps_rcvackpack++;
2077		tcpstat.tcps_rcvackbyte += acked;
2078
2079		/*
2080		 * If we just performed our first retransmit, and the ACK
2081		 * arrives within our recovery window, then it was a mistake
2082		 * to do the retransmit in the first place.  Recover our
2083		 * original cwnd and ssthresh, and proceed to transmit where
2084		 * we left off.
2085		 */
2086		if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2087			++tcpstat.tcps_sndrexmitbad;
2088			tp->snd_cwnd = tp->snd_cwnd_prev;
2089			tp->snd_ssthresh = tp->snd_ssthresh_prev;
2090			tp->snd_recover = tp->snd_recover_prev;
2091			if (tp->t_flags & TF_WASFRECOVERY)
2092				ENTER_FASTRECOVERY(tp);
2093			tp->snd_nxt = tp->snd_max;
2094			tp->t_badrxtwin = 0;	/* XXX probably not required */
2095		}
2096
2097		/*
2098		 * If we have a timestamp reply, update smoothed
2099		 * round trip time.  If no timestamp is present but
2100		 * transmit timer is running and timed sequence
2101		 * number was acked, update smoothed round trip time.
2102		 * Since we now have an rtt measurement, cancel the
2103		 * timer backoff (cf., Phil Karn's retransmit alg.).
2104		 * Recompute the initial retransmit timer.
2105		 *
2106		 * Some boxes send broken timestamp replies
2107		 * during the SYN+ACK phase, ignore
2108		 * timestamps of 0 or we could calculate a
2109		 * huge RTT and blow up the retransmit timer.
2110		 */
2111		if ((to.to_flags & TOF_TS) != 0 &&
2112		    to.to_tsecr) {
2113			if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2114				tp->t_rttlow = ticks - to.to_tsecr;
2115			tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2116		} else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2117			if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2118				tp->t_rttlow = ticks - tp->t_rtttime;
2119			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2120		}
2121		tcp_xmit_bandwidth_limit(tp, th->th_ack);
2122
2123		/*
2124		 * If all outstanding data is acked, stop retransmit
2125		 * timer and remember to restart (more output or persist).
2126		 * If there is more data to be acked, restart retransmit
2127		 * timer, using current (possibly backed-off) value.
2128		 */
2129		if (th->th_ack == tp->snd_max) {
2130			tcp_timer_activate(tp, TT_REXMT, 0);
2131			needoutput = 1;
2132		} else if (!tcp_timer_active(tp, TT_PERSIST))
2133			tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2134
2135		/*
2136		 * If no data (only SYN) was ACK'd,
2137		 *    skip rest of ACK processing.
2138		 */
2139		if (acked == 0)
2140			goto step6;
2141
2142		/*
2143		 * When new data is acked, open the congestion window.
2144		 * If the window gives us less than ssthresh packets
2145		 * in flight, open exponentially (maxseg per packet).
2146		 * Otherwise open linearly: maxseg per window
2147		 * (maxseg^2 / cwnd per packet).
2148		 */
2149		if ((!tcp_do_newreno && !(tp->t_flags & TF_SACK_PERMIT)) ||
2150		    !IN_FASTRECOVERY(tp)) {
2151			u_int cw = tp->snd_cwnd;
2152			u_int incr = tp->t_maxseg;
2153			if (cw > tp->snd_ssthresh)
2154				incr = incr * incr / cw;
2155			tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2156		}
2157		SOCKBUF_LOCK(&so->so_snd);
2158		if (acked > so->so_snd.sb_cc) {
2159			tp->snd_wnd -= so->so_snd.sb_cc;
2160			sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2161			ourfinisacked = 1;
2162		} else {
2163			sbdrop_locked(&so->so_snd, acked);
2164			tp->snd_wnd -= acked;
2165			ourfinisacked = 0;
2166		}
2167		sowwakeup_locked(so);
2168		/* detect una wraparound */
2169		if ((tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2170		    !IN_FASTRECOVERY(tp) &&
2171		    SEQ_GT(tp->snd_una, tp->snd_recover) &&
2172		    SEQ_LEQ(th->th_ack, tp->snd_recover))
2173			tp->snd_recover = th->th_ack - 1;
2174		if ((tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2175		    IN_FASTRECOVERY(tp) &&
2176		    SEQ_GEQ(th->th_ack, tp->snd_recover))
2177			EXIT_FASTRECOVERY(tp);
2178		tp->snd_una = th->th_ack;
2179		if (tp->t_flags & TF_SACK_PERMIT) {
2180			if (SEQ_GT(tp->snd_una, tp->snd_recover))
2181				tp->snd_recover = tp->snd_una;
2182		}
2183		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2184			tp->snd_nxt = tp->snd_una;
2185
2186		switch (tp->t_state) {
2187
2188		/*
2189		 * In FIN_WAIT_1 STATE in addition to the processing
2190		 * for the ESTABLISHED state if our FIN is now acknowledged
2191		 * then enter FIN_WAIT_2.
2192		 */
2193		case TCPS_FIN_WAIT_1:
2194			if (ourfinisacked) {
2195				/*
2196				 * If we can't receive any more
2197				 * data, then closing user can proceed.
2198				 * Starting the timer is contrary to the
2199				 * specification, but if we don't get a FIN
2200				 * we'll hang forever.
2201				 */
2202		/* XXXjl
2203		 * we should release the tp also, and use a
2204		 * compressed state.
2205		 */
2206				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2207					int timeout;
2208
2209					soisdisconnected(so);
2210					timeout = (tcp_fast_finwait2_recycle) ?
2211						tcp_finwait2_timeout : tcp_maxidle;
2212					tcp_timer_activate(tp, TT_2MSL, timeout);
2213				}
2214				tp->t_state = TCPS_FIN_WAIT_2;
2215			}
2216			break;
2217
2218		/*
2219		 * In CLOSING STATE in addition to the processing for
2220		 * the ESTABLISHED state if the ACK acknowledges our FIN
2221		 * then enter the TIME-WAIT state, otherwise ignore
2222		 * the segment.
2223		 */
2224		case TCPS_CLOSING:
2225			if (ourfinisacked) {
2226				KASSERT(headlocked, ("%s: process_ACK: "
2227				    "head not locked", __func__));
2228				tcp_twstart(tp);
2229				INP_INFO_WUNLOCK(&tcbinfo);
2230				headlocked = 0;
2231				m_freem(m);
2232				return;
2233			}
2234			break;
2235
2236		/*
2237		 * In LAST_ACK, we may still be waiting for data to drain
2238		 * and/or to be acked, as well as for the ack of our FIN.
2239		 * If our FIN is now acknowledged, delete the TCB,
2240		 * enter the closed state and return.
2241		 */
2242		case TCPS_LAST_ACK:
2243			if (ourfinisacked) {
2244				KASSERT(headlocked, ("%s: process_ACK: "
2245				    "tcp_close: head not locked", __func__));
2246				tp = tcp_close(tp);
2247				goto drop;
2248			}
2249			break;
2250		}
2251	}
2252
2253step6:
2254	KASSERT(headlocked, ("%s: step6: head not locked", __func__));
2255	INP_LOCK_ASSERT(tp->t_inpcb);
2256
2257	/*
2258	 * Update window information.
2259	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2260	 */
2261	if ((thflags & TH_ACK) &&
2262	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2263	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2264	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2265		/* keep track of pure window updates */
2266		if (tlen == 0 &&
2267		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2268			tcpstat.tcps_rcvwinupd++;
2269		tp->snd_wnd = tiwin;
2270		tp->snd_wl1 = th->th_seq;
2271		tp->snd_wl2 = th->th_ack;
2272		if (tp->snd_wnd > tp->max_sndwnd)
2273			tp->max_sndwnd = tp->snd_wnd;
2274		needoutput = 1;
2275	}
2276
2277	/*
2278	 * Process segments with URG.
2279	 */
2280	if ((thflags & TH_URG) && th->th_urp &&
2281	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2282		/*
2283		 * This is a kludge, but if we receive and accept
2284		 * random urgent pointers, we'll crash in
2285		 * soreceive.  It's hard to imagine someone
2286		 * actually wanting to send this much urgent data.
2287		 */
2288		SOCKBUF_LOCK(&so->so_rcv);
2289		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2290			th->th_urp = 0;			/* XXX */
2291			thflags &= ~TH_URG;		/* XXX */
2292			SOCKBUF_UNLOCK(&so->so_rcv);	/* XXX */
2293			goto dodata;			/* XXX */
2294		}
2295		/*
2296		 * If this segment advances the known urgent pointer,
2297		 * then mark the data stream.  This should not happen
2298		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2299		 * a FIN has been received from the remote side.
2300		 * In these states we ignore the URG.
2301		 *
2302		 * According to RFC961 (Assigned Protocols),
2303		 * the urgent pointer points to the last octet
2304		 * of urgent data.  We continue, however,
2305		 * to consider it to indicate the first octet
2306		 * of data past the urgent section as the original
2307		 * spec states (in one of two places).
2308		 */
2309		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2310			tp->rcv_up = th->th_seq + th->th_urp;
2311			so->so_oobmark = so->so_rcv.sb_cc +
2312			    (tp->rcv_up - tp->rcv_nxt) - 1;
2313			if (so->so_oobmark == 0)
2314				so->so_rcv.sb_state |= SBS_RCVATMARK;
2315			sohasoutofband(so);
2316			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2317		}
2318		SOCKBUF_UNLOCK(&so->so_rcv);
2319		/*
2320		 * Remove out of band data so doesn't get presented to user.
2321		 * This can happen independent of advancing the URG pointer,
2322		 * but if two URG's are pending at once, some out-of-band
2323		 * data may creep in... ick.
2324		 */
2325		if (th->th_urp <= (u_long)tlen &&
2326		    !(so->so_options & SO_OOBINLINE)) {
2327			/* hdr drop is delayed */
2328			tcp_pulloutofband(so, th, m, drop_hdrlen);
2329		}
2330	} else {
2331		/*
2332		 * If no out of band data is expected,
2333		 * pull receive urgent pointer along
2334		 * with the receive window.
2335		 */
2336		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2337			tp->rcv_up = tp->rcv_nxt;
2338	}
2339dodata:							/* XXX */
2340	KASSERT(headlocked, ("%s: dodata: head not locked", __func__));
2341	INP_LOCK_ASSERT(tp->t_inpcb);
2342
2343	/*
2344	 * Process the segment text, merging it into the TCP sequencing queue,
2345	 * and arranging for acknowledgment of receipt if necessary.
2346	 * This process logically involves adjusting tp->rcv_wnd as data
2347	 * is presented to the user (this happens in tcp_usrreq.c,
2348	 * case PRU_RCVD).  If a FIN has already been received on this
2349	 * connection then we just ignore the text.
2350	 */
2351	if ((tlen || (thflags & TH_FIN)) &&
2352	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2353		tcp_seq save_start = th->th_seq;
2354		tcp_seq save_end = th->th_seq + tlen;
2355		m_adj(m, drop_hdrlen);	/* delayed header drop */
2356		/*
2357		 * Insert segment which includes th into TCP reassembly queue
2358		 * with control block tp.  Set thflags to whether reassembly now
2359		 * includes a segment with FIN.  This handles the common case
2360		 * inline (segment is the next to be received on an established
2361		 * connection, and the queue is empty), avoiding linkage into
2362		 * and removal from the queue and repetition of various
2363		 * conversions.
2364		 * Set DELACK for segments received in order, but ack
2365		 * immediately when segments are out of order (so
2366		 * fast retransmit can work).
2367		 */
2368		if (th->th_seq == tp->rcv_nxt &&
2369		    LIST_EMPTY(&tp->t_segq) &&
2370		    TCPS_HAVEESTABLISHED(tp->t_state)) {
2371			if (DELAY_ACK(tp))
2372				tp->t_flags |= TF_DELACK;
2373			else
2374				tp->t_flags |= TF_ACKNOW;
2375			tp->rcv_nxt += tlen;
2376			thflags = th->th_flags & TH_FIN;
2377			tcpstat.tcps_rcvpack++;
2378			tcpstat.tcps_rcvbyte += tlen;
2379			ND6_HINT(tp);
2380			SOCKBUF_LOCK(&so->so_rcv);
2381			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2382				m_freem(m);
2383			else
2384				sbappendstream_locked(&so->so_rcv, m);
2385			sorwakeup_locked(so);
2386		} else {
2387			thflags = tcp_reass(tp, th, &tlen, m);
2388			tp->t_flags |= TF_ACKNOW;
2389		}
2390		if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2391			tcp_update_sack_list(tp, save_start, save_end);
2392#if 0
2393		/*
2394		 * Note the amount of data that peer has sent into
2395		 * our window, in order to estimate the sender's
2396		 * buffer size.
2397		 * XXX: Unused.
2398		 */
2399		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2400#endif
2401	} else {
2402		m_freem(m);
2403		thflags &= ~TH_FIN;
2404	}
2405
2406	/*
2407	 * If FIN is received ACK the FIN and let the user know
2408	 * that the connection is closing.
2409	 */
2410	if (thflags & TH_FIN) {
2411		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2412			socantrcvmore(so);
2413			/*
2414			 * If connection is half-synchronized
2415			 * (ie NEEDSYN flag on) then delay ACK,
2416			 * so it may be piggybacked when SYN is sent.
2417			 * Otherwise, since we received a FIN then no
2418			 * more input can be expected, send ACK now.
2419			 */
2420			if (tp->t_flags & TF_NEEDSYN)
2421				tp->t_flags |= TF_DELACK;
2422			else
2423				tp->t_flags |= TF_ACKNOW;
2424			tp->rcv_nxt++;
2425		}
2426		switch (tp->t_state) {
2427
2428		/*
2429		 * In SYN_RECEIVED and ESTABLISHED STATES
2430		 * enter the CLOSE_WAIT state.
2431		 */
2432		case TCPS_SYN_RECEIVED:
2433			tp->t_starttime = ticks;
2434			/*FALLTHROUGH*/
2435		case TCPS_ESTABLISHED:
2436			tp->t_state = TCPS_CLOSE_WAIT;
2437			break;
2438
2439		/*
2440		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2441		 * enter the CLOSING state.
2442		 */
2443		case TCPS_FIN_WAIT_1:
2444			tp->t_state = TCPS_CLOSING;
2445			break;
2446
2447		/*
2448		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2449		 * starting the time-wait timer, turning off the other
2450		 * standard timers.
2451		 */
2452		case TCPS_FIN_WAIT_2:
2453			KASSERT(headlocked == 1, ("%s: dodata: "
2454			    "TCP_FIN_WAIT_2: head not locked", __func__));
2455			tcp_twstart(tp);
2456			INP_INFO_WUNLOCK(&tcbinfo);
2457			return;
2458		}
2459	}
2460	INP_INFO_WUNLOCK(&tcbinfo);
2461	headlocked = 0;
2462#ifdef TCPDEBUG
2463	if (so->so_options & SO_DEBUG)
2464		tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2465			  &tcp_savetcp, 0);
2466#endif
2467
2468	/*
2469	 * Return any desired output.
2470	 */
2471	if (needoutput || (tp->t_flags & TF_ACKNOW))
2472		(void) tcp_output(tp);
2473
2474check_delack:
2475	KASSERT(headlocked == 0, ("%s: check_delack: head locked",
2476	    __func__));
2477	INP_INFO_UNLOCK_ASSERT(&tcbinfo);
2478	INP_LOCK_ASSERT(tp->t_inpcb);
2479	if (tp->t_flags & TF_DELACK) {
2480		tp->t_flags &= ~TF_DELACK;
2481		tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2482	}
2483	INP_UNLOCK(tp->t_inpcb);
2484	return;
2485
2486dropafterack:
2487	KASSERT(headlocked, ("%s: dropafterack: head not locked", __func__));
2488	/*
2489	 * Generate an ACK dropping incoming segment if it occupies
2490	 * sequence space, where the ACK reflects our state.
2491	 *
2492	 * We can now skip the test for the RST flag since all
2493	 * paths to this code happen after packets containing
2494	 * RST have been dropped.
2495	 *
2496	 * In the SYN-RECEIVED state, don't send an ACK unless the
2497	 * segment we received passes the SYN-RECEIVED ACK test.
2498	 * If it fails send a RST.  This breaks the loop in the
2499	 * "LAND" DoS attack, and also prevents an ACK storm
2500	 * between two listening ports that have been sent forged
2501	 * SYN segments, each with the source address of the other.
2502	 */
2503	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2504	    (SEQ_GT(tp->snd_una, th->th_ack) ||
2505	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
2506		rstreason = BANDLIM_RST_OPENPORT;
2507		goto dropwithreset;
2508	}
2509#ifdef TCPDEBUG
2510	if (so->so_options & SO_DEBUG)
2511		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2512			  &tcp_savetcp, 0);
2513#endif
2514	KASSERT(headlocked, ("%s: headlocked should be 1", __func__));
2515	INP_INFO_WUNLOCK(&tcbinfo);
2516	tp->t_flags |= TF_ACKNOW;
2517	(void) tcp_output(tp);
2518	INP_UNLOCK(tp->t_inpcb);
2519	m_freem(m);
2520	return;
2521
2522dropwithreset:
2523	KASSERT(headlocked, ("%s: dropwithreset: head not locked", __func__));
2524
2525	tcp_dropwithreset(m, th, tp, tlen, rstreason);
2526
2527	if (tp != NULL)
2528		INP_UNLOCK(tp->t_inpcb);
2529	if (headlocked)
2530		INP_INFO_WUNLOCK(&tcbinfo);
2531	return;
2532
2533drop:
2534	/*
2535	 * Drop space held by incoming segment and return.
2536	 */
2537#ifdef TCPDEBUG
2538	if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2539		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2540			  &tcp_savetcp, 0);
2541#endif
2542	if (tp != NULL)
2543		INP_UNLOCK(tp->t_inpcb);
2544	if (headlocked)
2545		INP_INFO_WUNLOCK(&tcbinfo);
2546	m_freem(m);
2547	return;
2548}
2549
2550/*
2551 * Issue RST and make ACK acceptable to originator of segment.
2552 * The mbuf must still include the original packet header.
2553 * tp may be NULL.
2554 */
2555static void
2556tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2557    int tlen, int rstreason)
2558{
2559	struct ip *ip;
2560#ifdef INET6
2561	struct ip6_hdr *ip6;
2562#endif
2563	/* Don't bother if destination was broadcast/multicast. */
2564	if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2565		goto drop;
2566#ifdef INET6
2567	if (mtod(m, struct ip *)->ip_v == 6) {
2568		ip6 = mtod(m, struct ip6_hdr *);
2569		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2570		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2571			goto drop;
2572		/* IPv6 anycast check is done at tcp6_input() */
2573	} else
2574#endif
2575	{
2576		ip = mtod(m, struct ip *);
2577		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2578		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2579		    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2580		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2581			goto drop;
2582	}
2583
2584	/* Perform bandwidth limiting. */
2585	if (badport_bandlim(rstreason) < 0)
2586		goto drop;
2587
2588	/* tcp_respond consumes the mbuf chain. */
2589	if (th->th_flags & TH_ACK) {
2590		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
2591		    th->th_ack, TH_RST);
2592	} else {
2593		if (th->th_flags & TH_SYN)
2594			tlen++;
2595		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2596		    (tcp_seq)0, TH_RST|TH_ACK);
2597	}
2598	return;
2599drop:
2600	m_freem(m);
2601	return;
2602}
2603
2604/*
2605 * Parse TCP options and place in tcpopt.
2606 */
2607static void
2608tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
2609{
2610	int opt, optlen;
2611
2612	to->to_flags = 0;
2613	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2614		opt = cp[0];
2615		if (opt == TCPOPT_EOL)
2616			break;
2617		if (opt == TCPOPT_NOP)
2618			optlen = 1;
2619		else {
2620			if (cnt < 2)
2621				break;
2622			optlen = cp[1];
2623			if (optlen < 2 || optlen > cnt)
2624				break;
2625		}
2626		switch (opt) {
2627		case TCPOPT_MAXSEG:
2628			if (optlen != TCPOLEN_MAXSEG)
2629				continue;
2630			if (!(flags & TO_SYN))
2631				continue;
2632			to->to_flags |= TOF_MSS;
2633			bcopy((char *)cp + 2,
2634			    (char *)&to->to_mss, sizeof(to->to_mss));
2635			to->to_mss = ntohs(to->to_mss);
2636			break;
2637		case TCPOPT_WINDOW:
2638			if (optlen != TCPOLEN_WINDOW)
2639				continue;
2640			if (!(flags & TO_SYN))
2641				continue;
2642			to->to_flags |= TOF_SCALE;
2643			to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2644			break;
2645		case TCPOPT_TIMESTAMP:
2646			if (optlen != TCPOLEN_TIMESTAMP)
2647				continue;
2648			to->to_flags |= TOF_TS;
2649			bcopy((char *)cp + 2,
2650			    (char *)&to->to_tsval, sizeof(to->to_tsval));
2651			to->to_tsval = ntohl(to->to_tsval);
2652			bcopy((char *)cp + 6,
2653			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2654			to->to_tsecr = ntohl(to->to_tsecr);
2655			break;
2656#ifdef TCP_SIGNATURE
2657		/*
2658		 * XXX In order to reply to a host which has set the
2659		 * TCP_SIGNATURE option in its initial SYN, we have to
2660		 * record the fact that the option was observed here
2661		 * for the syncache code to perform the correct response.
2662		 */
2663		case TCPOPT_SIGNATURE:
2664			if (optlen != TCPOLEN_SIGNATURE)
2665				continue;
2666			to->to_flags |= TOF_SIGNATURE;
2667			to->to_signature = cp + 2;
2668			break;
2669#endif
2670		case TCPOPT_SACK_PERMITTED:
2671			if (optlen != TCPOLEN_SACK_PERMITTED)
2672				continue;
2673			if (!(flags & TO_SYN))
2674				continue;
2675			if (!tcp_do_sack)
2676				continue;
2677			to->to_flags |= TOF_SACKPERM;
2678			break;
2679		case TCPOPT_SACK:
2680			if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2681				continue;
2682			if (flags & TO_SYN)
2683				continue;
2684			to->to_flags |= TOF_SACK;
2685			to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2686			to->to_sacks = cp + 2;
2687			tcpstat.tcps_sack_rcv_blocks++;
2688			break;
2689		default:
2690			continue;
2691		}
2692	}
2693}
2694
2695/*
2696 * Pull out of band byte out of a segment so
2697 * it doesn't appear in the user's data queue.
2698 * It is still reflected in the segment length for
2699 * sequencing purposes.
2700 */
2701static void
2702tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
2703    int off)
2704{
2705	int cnt = off + th->th_urp - 1;
2706
2707	while (cnt >= 0) {
2708		if (m->m_len > cnt) {
2709			char *cp = mtod(m, caddr_t) + cnt;
2710			struct tcpcb *tp = sototcpcb(so);
2711
2712			tp->t_iobc = *cp;
2713			tp->t_oobflags |= TCPOOB_HAVEDATA;
2714			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2715			m->m_len--;
2716			if (m->m_flags & M_PKTHDR)
2717				m->m_pkthdr.len--;
2718			return;
2719		}
2720		cnt -= m->m_len;
2721		m = m->m_next;
2722		if (m == NULL)
2723			break;
2724	}
2725	panic("tcp_pulloutofband");
2726}
2727
2728/*
2729 * Collect new round-trip time estimate
2730 * and update averages and current timeout.
2731 */
2732static void
2733tcp_xmit_timer(struct tcpcb *tp, int rtt)
2734{
2735	int delta;
2736
2737	INP_LOCK_ASSERT(tp->t_inpcb);
2738
2739	tcpstat.tcps_rttupdated++;
2740	tp->t_rttupdated++;
2741	if (tp->t_srtt != 0) {
2742		/*
2743		 * srtt is stored as fixed point with 5 bits after the
2744		 * binary point (i.e., scaled by 8).  The following magic
2745		 * is equivalent to the smoothing algorithm in rfc793 with
2746		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2747		 * point).  Adjust rtt to origin 0.
2748		 */
2749		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2750			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2751
2752		if ((tp->t_srtt += delta) <= 0)
2753			tp->t_srtt = 1;
2754
2755		/*
2756		 * We accumulate a smoothed rtt variance (actually, a
2757		 * smoothed mean difference), then set the retransmit
2758		 * timer to smoothed rtt + 4 times the smoothed variance.
2759		 * rttvar is stored as fixed point with 4 bits after the
2760		 * binary point (scaled by 16).  The following is
2761		 * equivalent to rfc793 smoothing with an alpha of .75
2762		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2763		 * rfc793's wired-in beta.
2764		 */
2765		if (delta < 0)
2766			delta = -delta;
2767		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2768		if ((tp->t_rttvar += delta) <= 0)
2769			tp->t_rttvar = 1;
2770		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2771		    tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2772	} else {
2773		/*
2774		 * No rtt measurement yet - use the unsmoothed rtt.
2775		 * Set the variance to half the rtt (so our first
2776		 * retransmit happens at 3*rtt).
2777		 */
2778		tp->t_srtt = rtt << TCP_RTT_SHIFT;
2779		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2780		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2781	}
2782	tp->t_rtttime = 0;
2783	tp->t_rxtshift = 0;
2784
2785	/*
2786	 * the retransmit should happen at rtt + 4 * rttvar.
2787	 * Because of the way we do the smoothing, srtt and rttvar
2788	 * will each average +1/2 tick of bias.  When we compute
2789	 * the retransmit timer, we want 1/2 tick of rounding and
2790	 * 1 extra tick because of +-1/2 tick uncertainty in the
2791	 * firing of the timer.  The bias will give us exactly the
2792	 * 1.5 tick we need.  But, because the bias is
2793	 * statistical, we have to test that we don't drop below
2794	 * the minimum feasible timer (which is 2 ticks).
2795	 */
2796	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2797		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2798
2799	/*
2800	 * We received an ack for a packet that wasn't retransmitted;
2801	 * it is probably safe to discard any error indications we've
2802	 * received recently.  This isn't quite right, but close enough
2803	 * for now (a route might have failed after we sent a segment,
2804	 * and the return path might not be symmetrical).
2805	 */
2806	tp->t_softerror = 0;
2807}
2808
2809/*
2810 * Determine a reasonable value for maxseg size.
2811 * If the route is known, check route for mtu.
2812 * If none, use an mss that can be handled on the outgoing
2813 * interface without forcing IP to fragment; if bigger than
2814 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2815 * to utilize large mbufs.  If no route is found, route has no mtu,
2816 * or the destination isn't local, use a default, hopefully conservative
2817 * size (usually 512 or the default IP max size, but no more than the mtu
2818 * of the interface), as we can't discover anything about intervening
2819 * gateways or networks.  We also initialize the congestion/slow start
2820 * window to be a single segment if the destination isn't local.
2821 * While looking at the routing entry, we also initialize other path-dependent
2822 * parameters from pre-set or cached values in the routing entry.
2823 *
2824 * Also take into account the space needed for options that we
2825 * send regularly.  Make maxseg shorter by that amount to assure
2826 * that we can send maxseg amount of data even when the options
2827 * are present.  Store the upper limit of the length of options plus
2828 * data in maxopd.
2829 *
2830 *
2831 * In case of T/TCP, we call this routine during implicit connection
2832 * setup as well (offer = -1), to initialize maxseg from the cached
2833 * MSS of our peer.
2834 *
2835 * NOTE that this routine is only called when we process an incoming
2836 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
2837 */
2838void
2839tcp_mss(struct tcpcb *tp, int offer)
2840{
2841	int rtt, mss;
2842	u_long bufsize;
2843	u_long maxmtu;
2844	struct inpcb *inp = tp->t_inpcb;
2845	struct socket *so;
2846	struct hc_metrics_lite metrics;
2847	int origoffer = offer;
2848	int mtuflags = 0;
2849#ifdef INET6
2850	int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2851	size_t min_protoh = isipv6 ?
2852			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2853			    sizeof (struct tcpiphdr);
2854#else
2855	const size_t min_protoh = sizeof(struct tcpiphdr);
2856#endif
2857
2858	/* initialize */
2859#ifdef INET6
2860	if (isipv6) {
2861		maxmtu = tcp_maxmtu6(&inp->inp_inc, &mtuflags);
2862		tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
2863	} else
2864#endif
2865	{
2866		maxmtu = tcp_maxmtu(&inp->inp_inc, &mtuflags);
2867		tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2868	}
2869	so = inp->inp_socket;
2870
2871	/*
2872	 * no route to sender, stay with default mss and return
2873	 */
2874	if (maxmtu == 0)
2875		return;
2876
2877	/* what have we got? */
2878	switch (offer) {
2879		case 0:
2880			/*
2881			 * Offer == 0 means that there was no MSS on the SYN
2882			 * segment, in this case we use tcp_mssdflt.
2883			 */
2884			offer =
2885#ifdef INET6
2886				isipv6 ? tcp_v6mssdflt :
2887#endif
2888				tcp_mssdflt;
2889			break;
2890
2891		case -1:
2892			/*
2893			 * Offer == -1 means that we didn't receive SYN yet.
2894			 */
2895			/* FALLTHROUGH */
2896
2897		default:
2898			/*
2899			 * Prevent DoS attack with too small MSS. Round up
2900			 * to at least minmss.
2901			 */
2902			offer = max(offer, tcp_minmss);
2903			/*
2904			 * Sanity check: make sure that maxopd will be large
2905			 * enough to allow some data on segments even if the
2906			 * all the option space is used (40bytes).  Otherwise
2907			 * funny things may happen in tcp_output.
2908			 */
2909			offer = max(offer, 64);
2910	}
2911
2912	/*
2913	 * rmx information is now retrieved from tcp_hostcache
2914	 */
2915	tcp_hc_get(&inp->inp_inc, &metrics);
2916
2917	/*
2918	 * if there's a discovered mtu int tcp hostcache, use it
2919	 * else, use the link mtu.
2920	 */
2921	if (metrics.rmx_mtu)
2922		mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
2923	else {
2924#ifdef INET6
2925		if (isipv6) {
2926			mss = maxmtu - min_protoh;
2927			if (!path_mtu_discovery &&
2928			    !in6_localaddr(&inp->in6p_faddr))
2929				mss = min(mss, tcp_v6mssdflt);
2930		} else
2931#endif
2932		{
2933			mss = maxmtu - min_protoh;
2934			if (!path_mtu_discovery &&
2935			    !in_localaddr(inp->inp_faddr))
2936				mss = min(mss, tcp_mssdflt);
2937		}
2938	}
2939	mss = min(mss, offer);
2940
2941	/*
2942	 * maxopd stores the maximum length of data AND options
2943	 * in a segment; maxseg is the amount of data in a normal
2944	 * segment.  We need to store this value (maxopd) apart
2945	 * from maxseg, because now every segment carries options
2946	 * and thus we normally have somewhat less data in segments.
2947	 */
2948	tp->t_maxopd = mss;
2949
2950	/*
2951	 * origoffer==-1 indicates, that no segments were received yet.
2952	 * In this case we just guess.
2953	 */
2954	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2955	    (origoffer == -1 ||
2956	     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2957		mss -= TCPOLEN_TSTAMP_APPA;
2958	tp->t_maxseg = mss;
2959
2960#if	(MCLBYTES & (MCLBYTES - 1)) == 0
2961		if (mss > MCLBYTES)
2962			mss &= ~(MCLBYTES-1);
2963#else
2964		if (mss > MCLBYTES)
2965			mss = mss / MCLBYTES * MCLBYTES;
2966#endif
2967	tp->t_maxseg = mss;
2968
2969	/*
2970	 * If there's a pipesize, change the socket buffer to that size,
2971	 * don't change if sb_hiwat is different than default (then it
2972	 * has been changed on purpose with setsockopt).
2973	 * Make the socket buffers an integral number of mss units;
2974	 * if the mss is larger than the socket buffer, decrease the mss.
2975	 */
2976	SOCKBUF_LOCK(&so->so_snd);
2977	if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
2978		bufsize = metrics.rmx_sendpipe;
2979	else
2980		bufsize = so->so_snd.sb_hiwat;
2981	if (bufsize < mss)
2982		mss = bufsize;
2983	else {
2984		bufsize = roundup(bufsize, mss);
2985		if (bufsize > sb_max)
2986			bufsize = sb_max;
2987		if (bufsize > so->so_snd.sb_hiwat)
2988			(void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
2989	}
2990	SOCKBUF_UNLOCK(&so->so_snd);
2991	tp->t_maxseg = mss;
2992
2993	SOCKBUF_LOCK(&so->so_rcv);
2994	if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
2995		bufsize = metrics.rmx_recvpipe;
2996	else
2997		bufsize = so->so_rcv.sb_hiwat;
2998	if (bufsize > mss) {
2999		bufsize = roundup(bufsize, mss);
3000		if (bufsize > sb_max)
3001			bufsize = sb_max;
3002		if (bufsize > so->so_rcv.sb_hiwat)
3003			(void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3004	}
3005	SOCKBUF_UNLOCK(&so->so_rcv);
3006	/*
3007	 * While we're here, check the others too
3008	 */
3009	if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
3010		tp->t_srtt = rtt;
3011		tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3012		tcpstat.tcps_usedrtt++;
3013		if (metrics.rmx_rttvar) {
3014			tp->t_rttvar = metrics.rmx_rttvar;
3015			tcpstat.tcps_usedrttvar++;
3016		} else {
3017			/* default variation is +- 1 rtt */
3018			tp->t_rttvar =
3019			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3020		}
3021		TCPT_RANGESET(tp->t_rxtcur,
3022			      ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3023			      tp->t_rttmin, TCPTV_REXMTMAX);
3024	}
3025	if (metrics.rmx_ssthresh) {
3026		/*
3027		 * There's some sort of gateway or interface
3028		 * buffer limit on the path.  Use this to set
3029		 * the slow start threshhold, but set the
3030		 * threshold to no less than 2*mss.
3031		 */
3032		tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
3033		tcpstat.tcps_usedssthresh++;
3034	}
3035	if (metrics.rmx_bandwidth)
3036		tp->snd_bandwidth = metrics.rmx_bandwidth;
3037
3038	/*
3039	 * Set the slow-start flight size depending on whether this
3040	 * is a local network or not.
3041	 *
3042	 * Extend this so we cache the cwnd too and retrieve it here.
3043	 * Make cwnd even bigger than RFC3390 suggests but only if we
3044	 * have previous experience with the remote host. Be careful
3045	 * not make cwnd bigger than remote receive window or our own
3046	 * send socket buffer. Maybe put some additional upper bound
3047	 * on the retrieved cwnd. Should do incremental updates to
3048	 * hostcache when cwnd collapses so next connection doesn't
3049	 * overloads the path again.
3050	 *
3051	 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
3052	 * We currently check only in syncache_socket for that.
3053	 */
3054#define TCP_METRICS_CWND
3055#ifdef TCP_METRICS_CWND
3056	if (metrics.rmx_cwnd)
3057		tp->snd_cwnd = max(mss,
3058				min(metrics.rmx_cwnd / 2,
3059				 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
3060	else
3061#endif
3062	if (tcp_do_rfc3390)
3063		tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3064#ifdef INET6
3065	else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
3066		 (!isipv6 && in_localaddr(inp->inp_faddr)))
3067#else
3068	else if (in_localaddr(inp->inp_faddr))
3069#endif
3070		tp->snd_cwnd = mss * ss_fltsz_local;
3071	else
3072		tp->snd_cwnd = mss * ss_fltsz;
3073
3074	/* Check the interface for TSO capabilities. */
3075	if (mtuflags & CSUM_TSO)
3076		tp->t_flags |= TF_TSO;
3077}
3078
3079/*
3080 * Determine the MSS option to send on an outgoing SYN.
3081 */
3082int
3083tcp_mssopt(struct in_conninfo *inc)
3084{
3085	int mss = 0;
3086	u_long maxmtu = 0;
3087	u_long thcmtu = 0;
3088	size_t min_protoh;
3089#ifdef INET6
3090	int isipv6 = inc->inc_isipv6 ? 1 : 0;
3091#endif
3092
3093	KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3094
3095#ifdef INET6
3096	if (isipv6) {
3097		mss = tcp_v6mssdflt;
3098		maxmtu = tcp_maxmtu6(inc, NULL);
3099		thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3100		min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3101	} else
3102#endif
3103	{
3104		mss = tcp_mssdflt;
3105		maxmtu = tcp_maxmtu(inc, NULL);
3106		thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3107		min_protoh = sizeof(struct tcpiphdr);
3108	}
3109	if (maxmtu && thcmtu)
3110		mss = min(maxmtu, thcmtu) - min_protoh;
3111	else if (maxmtu || thcmtu)
3112		mss = max(maxmtu, thcmtu) - min_protoh;
3113
3114	return (mss);
3115}
3116
3117
3118/*
3119 * On a partial ack arrives, force the retransmission of the
3120 * next unacknowledged segment.  Do not clear tp->t_dupacks.
3121 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3122 * be started again.
3123 */
3124static void
3125tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3126{
3127	tcp_seq onxt = tp->snd_nxt;
3128	u_long  ocwnd = tp->snd_cwnd;
3129
3130	tcp_timer_activate(tp, TT_REXMT, 0);
3131	tp->t_rtttime = 0;
3132	tp->snd_nxt = th->th_ack;
3133	/*
3134	 * Set snd_cwnd to one segment beyond acknowledged offset.
3135	 * (tp->snd_una has not yet been updated when this function is called.)
3136	 */
3137	tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3138	tp->t_flags |= TF_ACKNOW;
3139	(void) tcp_output(tp);
3140	tp->snd_cwnd = ocwnd;
3141	if (SEQ_GT(onxt, tp->snd_nxt))
3142		tp->snd_nxt = onxt;
3143	/*
3144	 * Partial window deflation.  Relies on fact that tp->snd_una
3145	 * not updated yet.
3146	 */
3147	if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3148		tp->snd_cwnd -= th->th_ack - tp->snd_una;
3149	else
3150		tp->snd_cwnd = 0;
3151	tp->snd_cwnd += tp->t_maxseg;
3152}
3153
3154/*
3155 * Returns 1 if the TIME_WAIT state was killed and we should start over,
3156 * looking for a pcb in the listen state.  Returns 0 otherwise.
3157 */
3158static int
3159tcp_timewait(struct inpcb *inp, struct tcpopt *to, struct tcphdr *th,
3160    struct mbuf *m, int tlen)
3161{
3162	struct tcptw *tw;
3163	int thflags;
3164	tcp_seq seq;
3165#ifdef INET6
3166	int isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
3167#else
3168	const int isipv6 = 0;
3169#endif
3170
3171	/* tcbinfo lock required for tcp_twclose(), tcp_timer_2msl_reset(). */
3172	INP_INFO_WLOCK_ASSERT(&tcbinfo);
3173	INP_LOCK_ASSERT(inp);
3174
3175	/*
3176	 * XXXRW: Time wait state for inpcb has been recycled, but inpcb is
3177	 * still present.  This is undesirable, but temporarily necessary
3178	 * until we work out how to handle inpcb's who's timewait state has
3179	 * been removed.
3180	 */
3181	tw = intotw(inp);
3182	if (tw == NULL)
3183		goto drop;
3184
3185	thflags = th->th_flags;
3186
3187	/*
3188	 * NOTE: for FIN_WAIT_2 (to be added later),
3189	 * must validate sequence number before accepting RST
3190	 */
3191
3192	/*
3193	 * If the segment contains RST:
3194	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
3195	 *      RFC 1337.
3196	 */
3197	if (thflags & TH_RST)
3198		goto drop;
3199
3200#if 0
3201/* PAWS not needed at the moment */
3202	/*
3203	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
3204	 * and it's less than ts_recent, drop it.
3205	 */
3206	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
3207	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
3208		if ((thflags & TH_ACK) == 0)
3209			goto drop;
3210		goto ack;
3211	}
3212	/*
3213	 * ts_recent is never updated because we never accept new segments.
3214	 */
3215#endif
3216
3217	/*
3218	 * If a new connection request is received
3219	 * while in TIME_WAIT, drop the old connection
3220	 * and start over if the sequence numbers
3221	 * are above the previous ones.
3222	 */
3223	if ((thflags & TH_SYN) && SEQ_GT(th->th_seq, tw->rcv_nxt)) {
3224		tcp_twclose(tw, 0);
3225		return (1);
3226	}
3227
3228	/*
3229	 * Drop the the segment if it does not contain an ACK.
3230	 */
3231	if ((thflags & TH_ACK) == 0)
3232		goto drop;
3233
3234	/*
3235	 * Reset the 2MSL timer if this is a duplicate FIN.
3236	 */
3237	if (thflags & TH_FIN) {
3238		seq = th->th_seq + tlen + (thflags & TH_SYN ? 1 : 0);
3239		if (seq + 1 == tw->rcv_nxt)
3240			tcp_timer_2msl_reset(tw, 1);
3241	}
3242
3243	/*
3244	 * Acknowledge the segment if it has data or is not a duplicate ACK.
3245	 */
3246	if (thflags != TH_ACK || tlen != 0 ||
3247	    th->th_seq != tw->rcv_nxt || th->th_ack != tw->snd_nxt)
3248		tcp_twrespond(tw, TH_ACK);
3249	goto drop;
3250
3251	/*
3252	 * Generate a RST, dropping incoming segment.
3253	 * Make ACK acceptable to originator of segment.
3254	 * Don't bother to respond if destination was broadcast/multicast.
3255	 */
3256	if (m->m_flags & (M_BCAST|M_MCAST))
3257		goto drop;
3258	if (isipv6) {
3259		struct ip6_hdr *ip6;
3260
3261		/* IPv6 anycast check is done at tcp6_input() */
3262		ip6 = mtod(m, struct ip6_hdr *);
3263		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3264		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3265			goto drop;
3266	} else {
3267		struct ip *ip;
3268
3269		ip = mtod(m, struct ip *);
3270		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3271		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3272		    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3273		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3274			goto drop;
3275	}
3276	if (thflags & TH_ACK) {
3277		tcp_respond(NULL,
3278		    mtod(m, void *), th, m, 0, th->th_ack, TH_RST);
3279	} else {
3280		seq = th->th_seq + (thflags & TH_SYN ? 1 : 0);
3281		tcp_respond(NULL,
3282		    mtod(m, void *), th, m, seq, 0, TH_RST|TH_ACK);
3283	}
3284	INP_UNLOCK(inp);
3285	return (0);
3286
3287drop:
3288	INP_UNLOCK(inp);
3289	m_freem(m);
3290	return (0);
3291}
3292