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