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