tcp_input.c revision 207369
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 207369 2010-04-29 11:52:42Z bz $");
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_addrs(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				tcp_xmit_bandwidth_limit(tp, th->th_ack);
1325				acked = th->th_ack - tp->snd_una;
1326				TCPSTAT_INC(tcps_rcvackpack);
1327				TCPSTAT_ADD(tcps_rcvackbyte, acked);
1328				sbdrop(&so->so_snd, acked);
1329				if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1330				    SEQ_LEQ(th->th_ack, tp->snd_recover))
1331					tp->snd_recover = th->th_ack - 1;
1332				tp->snd_una = th->th_ack;
1333				/*
1334				 * Pull snd_wl2 up to prevent seq wrap relative
1335				 * to th_ack.
1336				 */
1337				tp->snd_wl2 = th->th_ack;
1338				tp->t_dupacks = 0;
1339				m_freem(m);
1340				ND6_HINT(tp); /* Some progress has been made. */
1341
1342				/*
1343				 * If all outstanding data are acked, stop
1344				 * retransmit timer, otherwise restart timer
1345				 * using current (possibly backed-off) value.
1346				 * If process is waiting for space,
1347				 * wakeup/selwakeup/signal.  If data
1348				 * are ready to send, let tcp_output
1349				 * decide between more output or persist.
1350				 */
1351#ifdef TCPDEBUG
1352				if (so->so_options & SO_DEBUG)
1353					tcp_trace(TA_INPUT, ostate, tp,
1354					    (void *)tcp_saveipgen,
1355					    &tcp_savetcp, 0);
1356#endif
1357				if (tp->snd_una == tp->snd_max)
1358					tcp_timer_activate(tp, TT_REXMT, 0);
1359				else if (!tcp_timer_active(tp, TT_PERSIST))
1360					tcp_timer_activate(tp, TT_REXMT,
1361						      tp->t_rxtcur);
1362				sowwakeup(so);
1363				if (so->so_snd.sb_cc)
1364					(void) tcp_output(tp);
1365				goto check_delack;
1366			}
1367		} else if (th->th_ack == tp->snd_una &&
1368		    tlen <= sbspace(&so->so_rcv)) {
1369			int newsize = 0;	/* automatic sockbuf scaling */
1370
1371			/*
1372			 * This is a pure, in-sequence data packet with
1373			 * nothing on the reassembly queue and we have enough
1374			 * buffer space to take it.
1375			 */
1376			if (ti_locked == TI_RLOCKED)
1377				INP_INFO_RUNLOCK(&V_tcbinfo);
1378			else if (ti_locked == TI_WLOCKED)
1379				INP_INFO_WUNLOCK(&V_tcbinfo);
1380			else
1381				panic("%s: ti_locked %d on pure data "
1382				    "segment", __func__, ti_locked);
1383			ti_locked = TI_UNLOCKED;
1384
1385			/* Clean receiver SACK report if present */
1386			if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1387				tcp_clean_sackreport(tp);
1388			TCPSTAT_INC(tcps_preddat);
1389			tp->rcv_nxt += tlen;
1390			/*
1391			 * Pull snd_wl1 up to prevent seq wrap relative to
1392			 * th_seq.
1393			 */
1394			tp->snd_wl1 = th->th_seq;
1395			/*
1396			 * Pull rcv_up up to prevent seq wrap relative to
1397			 * rcv_nxt.
1398			 */
1399			tp->rcv_up = tp->rcv_nxt;
1400			TCPSTAT_INC(tcps_rcvpack);
1401			TCPSTAT_ADD(tcps_rcvbyte, tlen);
1402			ND6_HINT(tp);	/* Some progress has been made */
1403#ifdef TCPDEBUG
1404			if (so->so_options & SO_DEBUG)
1405				tcp_trace(TA_INPUT, ostate, tp,
1406				    (void *)tcp_saveipgen, &tcp_savetcp, 0);
1407#endif
1408		/*
1409		 * Automatic sizing of receive socket buffer.  Often the send
1410		 * buffer size is not optimally adjusted to the actual network
1411		 * conditions at hand (delay bandwidth product).  Setting the
1412		 * buffer size too small limits throughput on links with high
1413		 * bandwidth and high delay (eg. trans-continental/oceanic links).
1414		 *
1415		 * On the receive side the socket buffer memory is only rarely
1416		 * used to any significant extent.  This allows us to be much
1417		 * more aggressive in scaling the receive socket buffer.  For
1418		 * the case that the buffer space is actually used to a large
1419		 * extent and we run out of kernel memory we can simply drop
1420		 * the new segments; TCP on the sender will just retransmit it
1421		 * later.  Setting the buffer size too big may only consume too
1422		 * much kernel memory if the application doesn't read() from
1423		 * the socket or packet loss or reordering makes use of the
1424		 * reassembly queue.
1425		 *
1426		 * The criteria to step up the receive buffer one notch are:
1427		 *  1. the number of bytes received during the time it takes
1428		 *     one timestamp to be reflected back to us (the RTT);
1429		 *  2. received bytes per RTT is within seven eighth of the
1430		 *     current socket buffer size;
1431		 *  3. receive buffer size has not hit maximal automatic size;
1432		 *
1433		 * This algorithm does one step per RTT at most and only if
1434		 * we receive a bulk stream w/o packet losses or reorderings.
1435		 * Shrinking the buffer during idle times is not necessary as
1436		 * it doesn't consume any memory when idle.
1437		 *
1438		 * TODO: Only step up if the application is actually serving
1439		 * the buffer to better manage the socket buffer resources.
1440		 */
1441			if (V_tcp_do_autorcvbuf &&
1442			    to.to_tsecr &&
1443			    (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1444				if (to.to_tsecr > tp->rfbuf_ts &&
1445				    to.to_tsecr - tp->rfbuf_ts < hz) {
1446					if (tp->rfbuf_cnt >
1447					    (so->so_rcv.sb_hiwat / 8 * 7) &&
1448					    so->so_rcv.sb_hiwat <
1449					    V_tcp_autorcvbuf_max) {
1450						newsize =
1451						    min(so->so_rcv.sb_hiwat +
1452						    V_tcp_autorcvbuf_inc,
1453						    V_tcp_autorcvbuf_max);
1454					}
1455					/* Start over with next RTT. */
1456					tp->rfbuf_ts = 0;
1457					tp->rfbuf_cnt = 0;
1458				} else
1459					tp->rfbuf_cnt += tlen;	/* add up */
1460			}
1461
1462			/* Add data to socket buffer. */
1463			SOCKBUF_LOCK(&so->so_rcv);
1464			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1465				m_freem(m);
1466			} else {
1467				/*
1468				 * Set new socket buffer size.
1469				 * Give up when limit is reached.
1470				 */
1471				if (newsize)
1472					if (!sbreserve_locked(&so->so_rcv,
1473					    newsize, so, NULL))
1474						so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1475				m_adj(m, drop_hdrlen);	/* delayed header drop */
1476				sbappendstream_locked(&so->so_rcv, m);
1477			}
1478			/* NB: sorwakeup_locked() does an implicit unlock. */
1479			sorwakeup_locked(so);
1480			if (DELAY_ACK(tp)) {
1481				tp->t_flags |= TF_DELACK;
1482			} else {
1483				tp->t_flags |= TF_ACKNOW;
1484				tcp_output(tp);
1485			}
1486			goto check_delack;
1487		}
1488	}
1489
1490	/*
1491	 * Calculate amount of space in receive window,
1492	 * and then do TCP input processing.
1493	 * Receive window is amount of space in rcv queue,
1494	 * but not less than advertised window.
1495	 */
1496	win = sbspace(&so->so_rcv);
1497	if (win < 0)
1498		win = 0;
1499	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1500
1501	/* Reset receive buffer auto scaling when not in bulk receive mode. */
1502	tp->rfbuf_ts = 0;
1503	tp->rfbuf_cnt = 0;
1504
1505	switch (tp->t_state) {
1506
1507	/*
1508	 * If the state is SYN_RECEIVED:
1509	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
1510	 */
1511	case TCPS_SYN_RECEIVED:
1512		if ((thflags & TH_ACK) &&
1513		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1514		     SEQ_GT(th->th_ack, tp->snd_max))) {
1515				rstreason = BANDLIM_RST_OPENPORT;
1516				goto dropwithreset;
1517		}
1518		break;
1519
1520	/*
1521	 * If the state is SYN_SENT:
1522	 *	if seg contains an ACK, but not for our SYN, drop the input.
1523	 *	if seg contains a RST, then drop the connection.
1524	 *	if seg does not contain SYN, then drop it.
1525	 * Otherwise this is an acceptable SYN segment
1526	 *	initialize tp->rcv_nxt and tp->irs
1527	 *	if seg contains ack then advance tp->snd_una
1528	 *	if seg contains an ECE and ECN support is enabled, the stream
1529	 *	    is ECN capable.
1530	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1531	 *	arrange for segment to be acked (eventually)
1532	 *	continue processing rest of data/controls, beginning with URG
1533	 */
1534	case TCPS_SYN_SENT:
1535		if ((thflags & TH_ACK) &&
1536		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1537		     SEQ_GT(th->th_ack, tp->snd_max))) {
1538			rstreason = BANDLIM_UNLIMITED;
1539			goto dropwithreset;
1540		}
1541		if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
1542			tp = tcp_drop(tp, ECONNREFUSED);
1543		if (thflags & TH_RST)
1544			goto drop;
1545		if (!(thflags & TH_SYN))
1546			goto drop;
1547
1548		tp->irs = th->th_seq;
1549		tcp_rcvseqinit(tp);
1550		if (thflags & TH_ACK) {
1551			TCPSTAT_INC(tcps_connects);
1552			soisconnected(so);
1553#ifdef MAC
1554			mac_socketpeer_set_from_mbuf(m, so);
1555#endif
1556			/* Do window scaling on this connection? */
1557			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1558				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1559				tp->rcv_scale = tp->request_r_scale;
1560			}
1561			tp->rcv_adv += tp->rcv_wnd;
1562			tp->snd_una++;		/* SYN is acked */
1563			/*
1564			 * If there's data, delay ACK; if there's also a FIN
1565			 * ACKNOW will be turned on later.
1566			 */
1567			if (DELAY_ACK(tp) && tlen != 0)
1568				tcp_timer_activate(tp, TT_DELACK,
1569				    tcp_delacktime);
1570			else
1571				tp->t_flags |= TF_ACKNOW;
1572
1573			if ((thflags & TH_ECE) && V_tcp_do_ecn) {
1574				tp->t_flags |= TF_ECN_PERMIT;
1575				TCPSTAT_INC(tcps_ecn_shs);
1576			}
1577
1578			/*
1579			 * Received <SYN,ACK> in SYN_SENT[*] state.
1580			 * Transitions:
1581			 *	SYN_SENT  --> ESTABLISHED
1582			 *	SYN_SENT* --> FIN_WAIT_1
1583			 */
1584			tp->t_starttime = ticks;
1585			if (tp->t_flags & TF_NEEDFIN) {
1586				tp->t_state = TCPS_FIN_WAIT_1;
1587				tp->t_flags &= ~TF_NEEDFIN;
1588				thflags &= ~TH_SYN;
1589			} else {
1590				tp->t_state = TCPS_ESTABLISHED;
1591				tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1592			}
1593		} else {
1594			/*
1595			 * Received initial SYN in SYN-SENT[*] state =>
1596			 * simultaneous open.  If segment contains CC option
1597			 * and there is a cached CC, apply TAO test.
1598			 * If it succeeds, connection is * half-synchronized.
1599			 * Otherwise, do 3-way handshake:
1600			 *        SYN-SENT -> SYN-RECEIVED
1601			 *        SYN-SENT* -> SYN-RECEIVED*
1602			 * If there was no CC option, clear cached CC value.
1603			 */
1604			tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1605			tcp_timer_activate(tp, TT_REXMT, 0);
1606			tp->t_state = TCPS_SYN_RECEIVED;
1607		}
1608
1609		KASSERT(ti_locked == TI_WLOCKED, ("%s: trimthenstep6: "
1610		    "ti_locked %d", __func__, ti_locked));
1611		INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1612		INP_WLOCK_ASSERT(tp->t_inpcb);
1613
1614		/*
1615		 * Advance th->th_seq to correspond to first data byte.
1616		 * If data, trim to stay within window,
1617		 * dropping FIN if necessary.
1618		 */
1619		th->th_seq++;
1620		if (tlen > tp->rcv_wnd) {
1621			todrop = tlen - tp->rcv_wnd;
1622			m_adj(m, -todrop);
1623			tlen = tp->rcv_wnd;
1624			thflags &= ~TH_FIN;
1625			TCPSTAT_INC(tcps_rcvpackafterwin);
1626			TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1627		}
1628		tp->snd_wl1 = th->th_seq - 1;
1629		tp->rcv_up = th->th_seq;
1630		/*
1631		 * Client side of transaction: already sent SYN and data.
1632		 * If the remote host used T/TCP to validate the SYN,
1633		 * our data will be ACK'd; if so, enter normal data segment
1634		 * processing in the middle of step 5, ack processing.
1635		 * Otherwise, goto step 6.
1636		 */
1637		if (thflags & TH_ACK)
1638			goto process_ACK;
1639
1640		goto step6;
1641
1642	/*
1643	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1644	 *      do normal processing.
1645	 *
1646	 * NB: Leftover from RFC1644 T/TCP.  Cases to be reused later.
1647	 */
1648	case TCPS_LAST_ACK:
1649	case TCPS_CLOSING:
1650		break;  /* continue normal processing */
1651	}
1652
1653	/*
1654	 * States other than LISTEN or SYN_SENT.
1655	 * First check the RST flag and sequence number since reset segments
1656	 * are exempt from the timestamp and connection count tests.  This
1657	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1658	 * below which allowed reset segments in half the sequence space
1659	 * to fall though and be processed (which gives forged reset
1660	 * segments with a random sequence number a 50 percent chance of
1661	 * killing a connection).
1662	 * Then check timestamp, if present.
1663	 * Then check the connection count, if present.
1664	 * Then check that at least some bytes of segment are within
1665	 * receive window.  If segment begins before rcv_nxt,
1666	 * drop leading data (and SYN); if nothing left, just ack.
1667	 *
1668	 *
1669	 * If the RST bit is set, check the sequence number to see
1670	 * if this is a valid reset segment.
1671	 * RFC 793 page 37:
1672	 *   In all states except SYN-SENT, all reset (RST) segments
1673	 *   are validated by checking their SEQ-fields.  A reset is
1674	 *   valid if its sequence number is in the window.
1675	 * Note: this does not take into account delayed ACKs, so
1676	 *   we should test against last_ack_sent instead of rcv_nxt.
1677	 *   The sequence number in the reset segment is normally an
1678	 *   echo of our outgoing acknowlegement numbers, but some hosts
1679	 *   send a reset with the sequence number at the rightmost edge
1680	 *   of our receive window, and we have to handle this case.
1681	 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1682	 *   that brute force RST attacks are possible.  To combat this,
1683	 *   we use a much stricter check while in the ESTABLISHED state,
1684	 *   only accepting RSTs where the sequence number is equal to
1685	 *   last_ack_sent.  In all other states (the states in which a
1686	 *   RST is more likely), the more permissive check is used.
1687	 * If we have multiple segments in flight, the initial reset
1688	 * segment sequence numbers will be to the left of last_ack_sent,
1689	 * but they will eventually catch up.
1690	 * In any case, it never made sense to trim reset segments to
1691	 * fit the receive window since RFC 1122 says:
1692	 *   4.2.2.12  RST Segment: RFC-793 Section 3.4
1693	 *
1694	 *    A TCP SHOULD allow a received RST segment to include data.
1695	 *
1696	 *    DISCUSSION
1697	 *         It has been suggested that a RST segment could contain
1698	 *         ASCII text that encoded and explained the cause of the
1699	 *         RST.  No standard has yet been established for such
1700	 *         data.
1701	 *
1702	 * If the reset segment passes the sequence number test examine
1703	 * the state:
1704	 *    SYN_RECEIVED STATE:
1705	 *	If passive open, return to LISTEN state.
1706	 *	If active open, inform user that connection was refused.
1707	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1708	 *	Inform user that connection was reset, and close tcb.
1709	 *    CLOSING, LAST_ACK STATES:
1710	 *	Close the tcb.
1711	 *    TIME_WAIT STATE:
1712	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
1713	 *      RFC 1337.
1714	 */
1715	if (thflags & TH_RST) {
1716		if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1717		    SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1718			switch (tp->t_state) {
1719
1720			case TCPS_SYN_RECEIVED:
1721				so->so_error = ECONNREFUSED;
1722				goto close;
1723
1724			case TCPS_ESTABLISHED:
1725				if (V_tcp_insecure_rst == 0 &&
1726				    !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1727				    SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1728				    !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1729				    SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1730					TCPSTAT_INC(tcps_badrst);
1731					goto drop;
1732				}
1733				/* FALLTHROUGH */
1734			case TCPS_FIN_WAIT_1:
1735			case TCPS_FIN_WAIT_2:
1736			case TCPS_CLOSE_WAIT:
1737				so->so_error = ECONNRESET;
1738			close:
1739				KASSERT(ti_locked == TI_WLOCKED,
1740				    ("tcp_do_segment: TH_RST 1 ti_locked %d",
1741				    ti_locked));
1742				INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1743
1744				tp->t_state = TCPS_CLOSED;
1745				TCPSTAT_INC(tcps_drops);
1746				tp = tcp_close(tp);
1747				break;
1748
1749			case TCPS_CLOSING:
1750			case TCPS_LAST_ACK:
1751				KASSERT(ti_locked == TI_WLOCKED,
1752				    ("tcp_do_segment: TH_RST 2 ti_locked %d",
1753				    ti_locked));
1754				INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1755
1756				tp = tcp_close(tp);
1757				break;
1758			}
1759		}
1760		goto drop;
1761	}
1762
1763	/*
1764	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1765	 * and it's less than ts_recent, drop it.
1766	 */
1767	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1768	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1769
1770		/* Check to see if ts_recent is over 24 days old.  */
1771		if (ticks - tp->ts_recent_age > TCP_PAWS_IDLE) {
1772			/*
1773			 * Invalidate ts_recent.  If this segment updates
1774			 * ts_recent, the age will be reset later and ts_recent
1775			 * will get a valid value.  If it does not, setting
1776			 * ts_recent to zero will at least satisfy the
1777			 * requirement that zero be placed in the timestamp
1778			 * echo reply when ts_recent isn't valid.  The
1779			 * age isn't reset until we get a valid ts_recent
1780			 * because we don't want out-of-order segments to be
1781			 * dropped when ts_recent is old.
1782			 */
1783			tp->ts_recent = 0;
1784		} else {
1785			TCPSTAT_INC(tcps_rcvduppack);
1786			TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
1787			TCPSTAT_INC(tcps_pawsdrop);
1788			if (tlen)
1789				goto dropafterack;
1790			goto drop;
1791		}
1792	}
1793
1794	/*
1795	 * In the SYN-RECEIVED state, validate that the packet belongs to
1796	 * this connection before trimming the data to fit the receive
1797	 * window.  Check the sequence number versus IRS since we know
1798	 * the sequence numbers haven't wrapped.  This is a partial fix
1799	 * for the "LAND" DoS attack.
1800	 */
1801	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1802		rstreason = BANDLIM_RST_OPENPORT;
1803		goto dropwithreset;
1804	}
1805
1806	todrop = tp->rcv_nxt - th->th_seq;
1807	if (todrop > 0) {
1808		/*
1809		 * If this is a duplicate SYN for our current connection,
1810		 * advance over it and pretend and it's not a SYN.
1811		 */
1812		if (thflags & TH_SYN && th->th_seq == tp->irs) {
1813			thflags &= ~TH_SYN;
1814			th->th_seq++;
1815			if (th->th_urp > 1)
1816				th->th_urp--;
1817			else
1818				thflags &= ~TH_URG;
1819			todrop--;
1820		}
1821		/*
1822		 * Following if statement from Stevens, vol. 2, p. 960.
1823		 */
1824		if (todrop > tlen
1825		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1826			/*
1827			 * Any valid FIN must be to the left of the window.
1828			 * At this point the FIN must be a duplicate or out
1829			 * of sequence; drop it.
1830			 */
1831			thflags &= ~TH_FIN;
1832
1833			/*
1834			 * Send an ACK to resynchronize and drop any data.
1835			 * But keep on processing for RST or ACK.
1836			 */
1837			tp->t_flags |= TF_ACKNOW;
1838			todrop = tlen;
1839			TCPSTAT_INC(tcps_rcvduppack);
1840			TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
1841		} else {
1842			TCPSTAT_INC(tcps_rcvpartduppack);
1843			TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
1844		}
1845		drop_hdrlen += todrop;	/* drop from the top afterwards */
1846		th->th_seq += todrop;
1847		tlen -= todrop;
1848		if (th->th_urp > todrop)
1849			th->th_urp -= todrop;
1850		else {
1851			thflags &= ~TH_URG;
1852			th->th_urp = 0;
1853		}
1854	}
1855
1856	/*
1857	 * If new data are received on a connection after the
1858	 * user processes are gone, then RST the other end.
1859	 */
1860	if ((so->so_state & SS_NOFDREF) &&
1861	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1862		char *s;
1863
1864		KASSERT(ti_locked == TI_WLOCKED, ("%s: SS_NOFDEREF && "
1865		    "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
1866		INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1867
1868		if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
1869			log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data after socket "
1870			    "was closed, sending RST and removing tcpcb\n",
1871			    s, __func__, tcpstates[tp->t_state], tlen);
1872			free(s, M_TCPLOG);
1873		}
1874		tp = tcp_close(tp);
1875		TCPSTAT_INC(tcps_rcvafterclose);
1876		rstreason = BANDLIM_UNLIMITED;
1877		goto dropwithreset;
1878	}
1879
1880	/*
1881	 * If segment ends after window, drop trailing data
1882	 * (and PUSH and FIN); if nothing left, just ACK.
1883	 */
1884	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1885	if (todrop > 0) {
1886		TCPSTAT_INC(tcps_rcvpackafterwin);
1887		if (todrop >= tlen) {
1888			TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
1889			/*
1890			 * If window is closed can only take segments at
1891			 * window edge, and have to drop data and PUSH from
1892			 * incoming segments.  Continue processing, but
1893			 * remember to ack.  Otherwise, drop segment
1894			 * and ack.
1895			 */
1896			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1897				tp->t_flags |= TF_ACKNOW;
1898				TCPSTAT_INC(tcps_rcvwinprobe);
1899			} else
1900				goto dropafterack;
1901		} else
1902			TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1903		m_adj(m, -todrop);
1904		tlen -= todrop;
1905		thflags &= ~(TH_PUSH|TH_FIN);
1906	}
1907
1908	/*
1909	 * If last ACK falls within this segment's sequence numbers,
1910	 * record its timestamp.
1911	 * NOTE:
1912	 * 1) That the test incorporates suggestions from the latest
1913	 *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
1914	 * 2) That updating only on newer timestamps interferes with
1915	 *    our earlier PAWS tests, so this check should be solely
1916	 *    predicated on the sequence space of this segment.
1917	 * 3) That we modify the segment boundary check to be
1918	 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
1919	 *    instead of RFC1323's
1920	 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
1921	 *    This modified check allows us to overcome RFC1323's
1922	 *    limitations as described in Stevens TCP/IP Illustrated
1923	 *    Vol. 2 p.869. In such cases, we can still calculate the
1924	 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
1925	 */
1926	if ((to.to_flags & TOF_TS) != 0 &&
1927	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1928	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1929		((thflags & (TH_SYN|TH_FIN)) != 0))) {
1930		tp->ts_recent_age = ticks;
1931		tp->ts_recent = to.to_tsval;
1932	}
1933
1934	/*
1935	 * If a SYN is in the window, then this is an
1936	 * error and we send an RST and drop the connection.
1937	 */
1938	if (thflags & TH_SYN) {
1939		KASSERT(ti_locked == TI_WLOCKED,
1940		    ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
1941		INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1942
1943		tp = tcp_drop(tp, ECONNRESET);
1944		rstreason = BANDLIM_UNLIMITED;
1945		goto drop;
1946	}
1947
1948	/*
1949	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1950	 * flag is on (half-synchronized state), then queue data for
1951	 * later processing; else drop segment and return.
1952	 */
1953	if ((thflags & TH_ACK) == 0) {
1954		if (tp->t_state == TCPS_SYN_RECEIVED ||
1955		    (tp->t_flags & TF_NEEDSYN))
1956			goto step6;
1957		else if (tp->t_flags & TF_ACKNOW)
1958			goto dropafterack;
1959		else
1960			goto drop;
1961	}
1962
1963	/*
1964	 * Ack processing.
1965	 */
1966	switch (tp->t_state) {
1967
1968	/*
1969	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1970	 * ESTABLISHED state and continue processing.
1971	 * The ACK was checked above.
1972	 */
1973	case TCPS_SYN_RECEIVED:
1974
1975		TCPSTAT_INC(tcps_connects);
1976		soisconnected(so);
1977		/* Do window scaling? */
1978		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1979			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1980			tp->rcv_scale = tp->request_r_scale;
1981			tp->snd_wnd = tiwin;
1982		}
1983		/*
1984		 * Make transitions:
1985		 *      SYN-RECEIVED  -> ESTABLISHED
1986		 *      SYN-RECEIVED* -> FIN-WAIT-1
1987		 */
1988		tp->t_starttime = ticks;
1989		if (tp->t_flags & TF_NEEDFIN) {
1990			tp->t_state = TCPS_FIN_WAIT_1;
1991			tp->t_flags &= ~TF_NEEDFIN;
1992		} else {
1993			tp->t_state = TCPS_ESTABLISHED;
1994			tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1995		}
1996		/*
1997		 * If segment contains data or ACK, will call tcp_reass()
1998		 * later; if not, do so now to pass queued data to user.
1999		 */
2000		if (tlen == 0 && (thflags & TH_FIN) == 0)
2001			(void) tcp_reass(tp, (struct tcphdr *)0, 0,
2002			    (struct mbuf *)0);
2003		tp->snd_wl1 = th->th_seq - 1;
2004		/* FALLTHROUGH */
2005
2006	/*
2007	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2008	 * ACKs.  If the ack is in the range
2009	 *	tp->snd_una < th->th_ack <= tp->snd_max
2010	 * then advance tp->snd_una to th->th_ack and drop
2011	 * data from the retransmission queue.  If this ACK reflects
2012	 * more up to date window information we update our window information.
2013	 */
2014	case TCPS_ESTABLISHED:
2015	case TCPS_FIN_WAIT_1:
2016	case TCPS_FIN_WAIT_2:
2017	case TCPS_CLOSE_WAIT:
2018	case TCPS_CLOSING:
2019	case TCPS_LAST_ACK:
2020		if (SEQ_GT(th->th_ack, tp->snd_max)) {
2021			TCPSTAT_INC(tcps_rcvacktoomuch);
2022			goto dropafterack;
2023		}
2024		if ((tp->t_flags & TF_SACK_PERMIT) &&
2025		    ((to.to_flags & TOF_SACK) ||
2026		     !TAILQ_EMPTY(&tp->snd_holes)))
2027			tcp_sack_doack(tp, &to, th->th_ack);
2028		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2029			if (tlen == 0 && tiwin == tp->snd_wnd) {
2030				TCPSTAT_INC(tcps_rcvdupack);
2031				/*
2032				 * If we have outstanding data (other than
2033				 * a window probe), this is a completely
2034				 * duplicate ack (ie, window info didn't
2035				 * change), the ack is the biggest we've
2036				 * seen and we've seen exactly our rexmt
2037				 * threshhold of them, assume a packet
2038				 * has been dropped and retransmit it.
2039				 * Kludge snd_nxt & the congestion
2040				 * window so we send only this one
2041				 * packet.
2042				 *
2043				 * We know we're losing at the current
2044				 * window size so do congestion avoidance
2045				 * (set ssthresh to half the current window
2046				 * and pull our congestion window back to
2047				 * the new ssthresh).
2048				 *
2049				 * Dup acks mean that packets have left the
2050				 * network (they're now cached at the receiver)
2051				 * so bump cwnd by the amount in the receiver
2052				 * to keep a constant cwnd packets in the
2053				 * network.
2054				 *
2055				 * When using TCP ECN, notify the peer that
2056				 * we reduced the cwnd.
2057				 */
2058				if (!tcp_timer_active(tp, TT_REXMT) ||
2059				    th->th_ack != tp->snd_una)
2060					tp->t_dupacks = 0;
2061				else if (++tp->t_dupacks > tcprexmtthresh ||
2062				    ((V_tcp_do_newreno ||
2063				      (tp->t_flags & TF_SACK_PERMIT)) &&
2064				     IN_FASTRECOVERY(tp))) {
2065					if ((tp->t_flags & TF_SACK_PERMIT) &&
2066					    IN_FASTRECOVERY(tp)) {
2067						int awnd;
2068
2069						/*
2070						 * Compute the amount of data in flight first.
2071						 * We can inject new data into the pipe iff
2072						 * we have less than 1/2 the original window's
2073						 * worth of data in flight.
2074						 */
2075						awnd = (tp->snd_nxt - tp->snd_fack) +
2076							tp->sackhint.sack_bytes_rexmit;
2077						if (awnd < tp->snd_ssthresh) {
2078							tp->snd_cwnd += tp->t_maxseg;
2079							if (tp->snd_cwnd > tp->snd_ssthresh)
2080								tp->snd_cwnd = tp->snd_ssthresh;
2081						}
2082					} else
2083						tp->snd_cwnd += tp->t_maxseg;
2084					(void) tcp_output(tp);
2085					goto drop;
2086				} else if (tp->t_dupacks == tcprexmtthresh) {
2087					tcp_seq onxt = tp->snd_nxt;
2088
2089					/*
2090					 * If we're doing sack, check to
2091					 * see if we're already in sack
2092					 * recovery. If we're not doing sack,
2093					 * check to see if we're in newreno
2094					 * recovery.
2095					 */
2096					if (tp->t_flags & TF_SACK_PERMIT) {
2097						if (IN_FASTRECOVERY(tp)) {
2098							tp->t_dupacks = 0;
2099							break;
2100						}
2101					} else if (V_tcp_do_newreno ||
2102					    V_tcp_do_ecn) {
2103						if (SEQ_LEQ(th->th_ack,
2104						    tp->snd_recover)) {
2105							tp->t_dupacks = 0;
2106							break;
2107						}
2108					}
2109					tcp_congestion_exp(tp);
2110					tcp_timer_activate(tp, TT_REXMT, 0);
2111					tp->t_rtttime = 0;
2112					if (tp->t_flags & TF_SACK_PERMIT) {
2113						TCPSTAT_INC(
2114						    tcps_sack_recovery_episode);
2115						tp->sack_newdata = tp->snd_nxt;
2116						tp->snd_cwnd = tp->t_maxseg;
2117						(void) tcp_output(tp);
2118						goto drop;
2119					}
2120					tp->snd_nxt = th->th_ack;
2121					tp->snd_cwnd = tp->t_maxseg;
2122					(void) tcp_output(tp);
2123					KASSERT(tp->snd_limited <= 2,
2124					    ("%s: tp->snd_limited too big",
2125					    __func__));
2126					tp->snd_cwnd = tp->snd_ssthresh +
2127					     tp->t_maxseg *
2128					     (tp->t_dupacks - tp->snd_limited);
2129					if (SEQ_GT(onxt, tp->snd_nxt))
2130						tp->snd_nxt = onxt;
2131					goto drop;
2132				} else if (V_tcp_do_rfc3042) {
2133					u_long oldcwnd = tp->snd_cwnd;
2134					tcp_seq oldsndmax = tp->snd_max;
2135					u_int sent;
2136
2137					KASSERT(tp->t_dupacks == 1 ||
2138					    tp->t_dupacks == 2,
2139					    ("%s: dupacks not 1 or 2",
2140					    __func__));
2141					if (tp->t_dupacks == 1)
2142						tp->snd_limited = 0;
2143					tp->snd_cwnd =
2144					    (tp->snd_nxt - tp->snd_una) +
2145					    (tp->t_dupacks - tp->snd_limited) *
2146					    tp->t_maxseg;
2147					(void) tcp_output(tp);
2148					sent = tp->snd_max - oldsndmax;
2149					if (sent > tp->t_maxseg) {
2150						KASSERT((tp->t_dupacks == 2 &&
2151						    tp->snd_limited == 0) ||
2152						   (sent == tp->t_maxseg + 1 &&
2153						    tp->t_flags & TF_SENTFIN),
2154						    ("%s: sent too much",
2155						    __func__));
2156						tp->snd_limited = 2;
2157					} else if (sent > 0)
2158						++tp->snd_limited;
2159					tp->snd_cwnd = oldcwnd;
2160					goto drop;
2161				}
2162			} else
2163				tp->t_dupacks = 0;
2164			break;
2165		}
2166
2167		KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2168		    ("%s: th_ack <= snd_una", __func__));
2169
2170		/*
2171		 * If the congestion window was inflated to account
2172		 * for the other side's cached packets, retract it.
2173		 */
2174		if (V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) {
2175			if (IN_FASTRECOVERY(tp)) {
2176				if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2177					if (tp->t_flags & TF_SACK_PERMIT)
2178						tcp_sack_partialack(tp, th);
2179					else
2180						tcp_newreno_partial_ack(tp, th);
2181				} else {
2182					/*
2183					 * Out of fast recovery.
2184					 * Window inflation should have left us
2185					 * with approximately snd_ssthresh
2186					 * outstanding data.
2187					 * But in case we would be inclined to
2188					 * send a burst, better to do it via
2189					 * the slow start mechanism.
2190					 */
2191					if (SEQ_GT(th->th_ack +
2192							tp->snd_ssthresh,
2193						   tp->snd_max))
2194						tp->snd_cwnd = tp->snd_max -
2195								th->th_ack +
2196								tp->t_maxseg;
2197					else
2198						tp->snd_cwnd = tp->snd_ssthresh;
2199				}
2200			}
2201		} else {
2202			if (tp->t_dupacks >= tcprexmtthresh &&
2203			    tp->snd_cwnd > tp->snd_ssthresh)
2204				tp->snd_cwnd = tp->snd_ssthresh;
2205		}
2206		tp->t_dupacks = 0;
2207		/*
2208		 * If we reach this point, ACK is not a duplicate,
2209		 *     i.e., it ACKs something we sent.
2210		 */
2211		if (tp->t_flags & TF_NEEDSYN) {
2212			/*
2213			 * T/TCP: Connection was half-synchronized, and our
2214			 * SYN has been ACK'd (so connection is now fully
2215			 * synchronized).  Go to non-starred state,
2216			 * increment snd_una for ACK of SYN, and check if
2217			 * we can do window scaling.
2218			 */
2219			tp->t_flags &= ~TF_NEEDSYN;
2220			tp->snd_una++;
2221			/* Do window scaling? */
2222			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2223				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
2224				tp->rcv_scale = tp->request_r_scale;
2225				/* Send window already scaled. */
2226			}
2227		}
2228
2229process_ACK:
2230		INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2231		KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2232		    ("tcp_input: process_ACK ti_locked %d", ti_locked));
2233		INP_WLOCK_ASSERT(tp->t_inpcb);
2234
2235		acked = th->th_ack - tp->snd_una;
2236		TCPSTAT_INC(tcps_rcvackpack);
2237		TCPSTAT_ADD(tcps_rcvackbyte, acked);
2238
2239		/*
2240		 * If we just performed our first retransmit, and the ACK
2241		 * arrives within our recovery window, then it was a mistake
2242		 * to do the retransmit in the first place.  Recover our
2243		 * original cwnd and ssthresh, and proceed to transmit where
2244		 * we left off.
2245		 */
2246		if (tp->t_rxtshift == 1 && (int)(ticks - tp->t_badrxtwin) < 0) {
2247			TCPSTAT_INC(tcps_sndrexmitbad);
2248			tp->snd_cwnd = tp->snd_cwnd_prev;
2249			tp->snd_ssthresh = tp->snd_ssthresh_prev;
2250			tp->snd_recover = tp->snd_recover_prev;
2251			if (tp->t_flags & TF_WASFRECOVERY)
2252				ENTER_FASTRECOVERY(tp);
2253			tp->snd_nxt = tp->snd_max;
2254			tp->t_badrxtwin = 0;	/* XXX probably not required */
2255		}
2256
2257		/*
2258		 * If we have a timestamp reply, update smoothed
2259		 * round trip time.  If no timestamp is present but
2260		 * transmit timer is running and timed sequence
2261		 * number was acked, update smoothed round trip time.
2262		 * Since we now have an rtt measurement, cancel the
2263		 * timer backoff (cf., Phil Karn's retransmit alg.).
2264		 * Recompute the initial retransmit timer.
2265		 *
2266		 * Some boxes send broken timestamp replies
2267		 * during the SYN+ACK phase, ignore
2268		 * timestamps of 0 or we could calculate a
2269		 * huge RTT and blow up the retransmit timer.
2270		 */
2271		if ((to.to_flags & TOF_TS) != 0 &&
2272		    to.to_tsecr) {
2273			if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2274				tp->t_rttlow = ticks - to.to_tsecr;
2275			tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2276		} else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2277			if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2278				tp->t_rttlow = ticks - tp->t_rtttime;
2279			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2280		}
2281		tcp_xmit_bandwidth_limit(tp, th->th_ack);
2282
2283		/*
2284		 * If all outstanding data is acked, stop retransmit
2285		 * timer and remember to restart (more output or persist).
2286		 * If there is more data to be acked, restart retransmit
2287		 * timer, using current (possibly backed-off) value.
2288		 */
2289		if (th->th_ack == tp->snd_max) {
2290			tcp_timer_activate(tp, TT_REXMT, 0);
2291			needoutput = 1;
2292		} else if (!tcp_timer_active(tp, TT_PERSIST))
2293			tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2294
2295		/*
2296		 * If no data (only SYN) was ACK'd,
2297		 *    skip rest of ACK processing.
2298		 */
2299		if (acked == 0)
2300			goto step6;
2301
2302		/*
2303		 * When new data is acked, open the congestion window.
2304		 * Method depends on which congestion control state we're
2305		 * in (slow start or cong avoid) and if ABC (RFC 3465) is
2306		 * enabled.
2307		 *
2308		 * slow start: cwnd <= ssthresh
2309		 * cong avoid: cwnd > ssthresh
2310		 *
2311		 * slow start and ABC (RFC 3465):
2312		 *   Grow cwnd exponentially by the amount of data
2313		 *   ACKed capping the max increment per ACK to
2314		 *   (abc_l_var * maxseg) bytes.
2315		 *
2316		 * slow start without ABC (RFC 2581):
2317		 *   Grow cwnd exponentially by maxseg per ACK.
2318		 *
2319		 * cong avoid and ABC (RFC 3465):
2320		 *   Grow cwnd linearly by maxseg per RTT for each
2321		 *   cwnd worth of ACKed data.
2322		 *
2323		 * cong avoid without ABC (RFC 2581):
2324		 *   Grow cwnd linearly by approximately maxseg per RTT using
2325		 *   maxseg^2 / cwnd per ACK as the increment.
2326		 *   If cwnd > maxseg^2, fix the cwnd increment at 1 byte to
2327		 *   avoid capping cwnd.
2328		 */
2329		if ((!V_tcp_do_newreno && !(tp->t_flags & TF_SACK_PERMIT)) ||
2330		    !IN_FASTRECOVERY(tp)) {
2331			u_int cw = tp->snd_cwnd;
2332			u_int incr = tp->t_maxseg;
2333			/* In congestion avoidance? */
2334			if (cw > tp->snd_ssthresh) {
2335				if (V_tcp_do_rfc3465) {
2336					tp->t_bytes_acked += acked;
2337					if (tp->t_bytes_acked >= tp->snd_cwnd)
2338						tp->t_bytes_acked -= cw;
2339					else
2340						incr = 0;
2341				}
2342				else
2343					incr = max((incr * incr / cw), 1);
2344			/*
2345			 * In slow-start with ABC enabled and no RTO in sight?
2346			 * (Must not use abc_l_var > 1 if slow starting after an
2347			 * RTO. On RTO, snd_nxt = snd_una, so the snd_nxt ==
2348			 * snd_max check is sufficient to handle this).
2349			 */
2350			} else if (V_tcp_do_rfc3465 &&
2351			    tp->snd_nxt == tp->snd_max)
2352				incr = min(acked,
2353				    V_tcp_abc_l_var * tp->t_maxseg);
2354			/* ABC is on by default, so (incr == 0) frequently. */
2355			if (incr > 0)
2356				tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2357		}
2358		SOCKBUF_LOCK(&so->so_snd);
2359		if (acked > so->so_snd.sb_cc) {
2360			tp->snd_wnd -= so->so_snd.sb_cc;
2361			sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2362			ourfinisacked = 1;
2363		} else {
2364			sbdrop_locked(&so->so_snd, acked);
2365			tp->snd_wnd -= acked;
2366			ourfinisacked = 0;
2367		}
2368		/* NB: sowwakeup_locked() does an implicit unlock. */
2369		sowwakeup_locked(so);
2370		/* Detect una wraparound. */
2371		if ((V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2372		    !IN_FASTRECOVERY(tp) &&
2373		    SEQ_GT(tp->snd_una, tp->snd_recover) &&
2374		    SEQ_LEQ(th->th_ack, tp->snd_recover))
2375			tp->snd_recover = th->th_ack - 1;
2376		if ((V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2377		    IN_FASTRECOVERY(tp) &&
2378		    SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2379			EXIT_FASTRECOVERY(tp);
2380			tp->t_bytes_acked = 0;
2381		}
2382		tp->snd_una = th->th_ack;
2383		if (tp->t_flags & TF_SACK_PERMIT) {
2384			if (SEQ_GT(tp->snd_una, tp->snd_recover))
2385				tp->snd_recover = tp->snd_una;
2386		}
2387		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2388			tp->snd_nxt = tp->snd_una;
2389
2390		switch (tp->t_state) {
2391
2392		/*
2393		 * In FIN_WAIT_1 STATE in addition to the processing
2394		 * for the ESTABLISHED state if our FIN is now acknowledged
2395		 * then enter FIN_WAIT_2.
2396		 */
2397		case TCPS_FIN_WAIT_1:
2398			if (ourfinisacked) {
2399				/*
2400				 * If we can't receive any more
2401				 * data, then closing user can proceed.
2402				 * Starting the timer is contrary to the
2403				 * specification, but if we don't get a FIN
2404				 * we'll hang forever.
2405				 *
2406				 * XXXjl:
2407				 * we should release the tp also, and use a
2408				 * compressed state.
2409				 */
2410				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2411					int timeout;
2412
2413					soisdisconnected(so);
2414					timeout = (tcp_fast_finwait2_recycle) ?
2415						tcp_finwait2_timeout : tcp_maxidle;
2416					tcp_timer_activate(tp, TT_2MSL, timeout);
2417				}
2418				tp->t_state = TCPS_FIN_WAIT_2;
2419			}
2420			break;
2421
2422		/*
2423		 * In CLOSING STATE in addition to the processing for
2424		 * the ESTABLISHED state if the ACK acknowledges our FIN
2425		 * then enter the TIME-WAIT state, otherwise ignore
2426		 * the segment.
2427		 */
2428		case TCPS_CLOSING:
2429			if (ourfinisacked) {
2430				INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2431				tcp_twstart(tp);
2432				INP_INFO_WUNLOCK(&V_tcbinfo);
2433				m_freem(m);
2434				return;
2435			}
2436			break;
2437
2438		/*
2439		 * In LAST_ACK, we may still be waiting for data to drain
2440		 * and/or to be acked, as well as for the ack of our FIN.
2441		 * If our FIN is now acknowledged, delete the TCB,
2442		 * enter the closed state and return.
2443		 */
2444		case TCPS_LAST_ACK:
2445			if (ourfinisacked) {
2446				INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2447				tp = tcp_close(tp);
2448				goto drop;
2449			}
2450			break;
2451		}
2452	}
2453
2454step6:
2455	INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2456	KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2457	    ("tcp_do_segment: step6 ti_locked %d", ti_locked));
2458	INP_WLOCK_ASSERT(tp->t_inpcb);
2459
2460	/*
2461	 * Update window information.
2462	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2463	 */
2464	if ((thflags & TH_ACK) &&
2465	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2466	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2467	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2468		/* keep track of pure window updates */
2469		if (tlen == 0 &&
2470		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2471			TCPSTAT_INC(tcps_rcvwinupd);
2472		tp->snd_wnd = tiwin;
2473		tp->snd_wl1 = th->th_seq;
2474		tp->snd_wl2 = th->th_ack;
2475		if (tp->snd_wnd > tp->max_sndwnd)
2476			tp->max_sndwnd = tp->snd_wnd;
2477		needoutput = 1;
2478	}
2479
2480	/*
2481	 * Process segments with URG.
2482	 */
2483	if ((thflags & TH_URG) && th->th_urp &&
2484	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2485		/*
2486		 * This is a kludge, but if we receive and accept
2487		 * random urgent pointers, we'll crash in
2488		 * soreceive.  It's hard to imagine someone
2489		 * actually wanting to send this much urgent data.
2490		 */
2491		SOCKBUF_LOCK(&so->so_rcv);
2492		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2493			th->th_urp = 0;			/* XXX */
2494			thflags &= ~TH_URG;		/* XXX */
2495			SOCKBUF_UNLOCK(&so->so_rcv);	/* XXX */
2496			goto dodata;			/* XXX */
2497		}
2498		/*
2499		 * If this segment advances the known urgent pointer,
2500		 * then mark the data stream.  This should not happen
2501		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2502		 * a FIN has been received from the remote side.
2503		 * In these states we ignore the URG.
2504		 *
2505		 * According to RFC961 (Assigned Protocols),
2506		 * the urgent pointer points to the last octet
2507		 * of urgent data.  We continue, however,
2508		 * to consider it to indicate the first octet
2509		 * of data past the urgent section as the original
2510		 * spec states (in one of two places).
2511		 */
2512		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2513			tp->rcv_up = th->th_seq + th->th_urp;
2514			so->so_oobmark = so->so_rcv.sb_cc +
2515			    (tp->rcv_up - tp->rcv_nxt) - 1;
2516			if (so->so_oobmark == 0)
2517				so->so_rcv.sb_state |= SBS_RCVATMARK;
2518			sohasoutofband(so);
2519			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2520		}
2521		SOCKBUF_UNLOCK(&so->so_rcv);
2522		/*
2523		 * Remove out of band data so doesn't get presented to user.
2524		 * This can happen independent of advancing the URG pointer,
2525		 * but if two URG's are pending at once, some out-of-band
2526		 * data may creep in... ick.
2527		 */
2528		if (th->th_urp <= (u_long)tlen &&
2529		    !(so->so_options & SO_OOBINLINE)) {
2530			/* hdr drop is delayed */
2531			tcp_pulloutofband(so, th, m, drop_hdrlen);
2532		}
2533	} else {
2534		/*
2535		 * If no out of band data is expected,
2536		 * pull receive urgent pointer along
2537		 * with the receive window.
2538		 */
2539		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2540			tp->rcv_up = tp->rcv_nxt;
2541	}
2542dodata:							/* XXX */
2543	INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2544	KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2545	    ("tcp_do_segment: dodata ti_locked %d", ti_locked));
2546	INP_WLOCK_ASSERT(tp->t_inpcb);
2547
2548	/*
2549	 * Process the segment text, merging it into the TCP sequencing queue,
2550	 * and arranging for acknowledgment of receipt if necessary.
2551	 * This process logically involves adjusting tp->rcv_wnd as data
2552	 * is presented to the user (this happens in tcp_usrreq.c,
2553	 * case PRU_RCVD).  If a FIN has already been received on this
2554	 * connection then we just ignore the text.
2555	 */
2556	if ((tlen || (thflags & TH_FIN)) &&
2557	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2558		tcp_seq save_start = th->th_seq;
2559		m_adj(m, drop_hdrlen);	/* delayed header drop */
2560		/*
2561		 * Insert segment which includes th into TCP reassembly queue
2562		 * with control block tp.  Set thflags to whether reassembly now
2563		 * includes a segment with FIN.  This handles the common case
2564		 * inline (segment is the next to be received on an established
2565		 * connection, and the queue is empty), avoiding linkage into
2566		 * and removal from the queue and repetition of various
2567		 * conversions.
2568		 * Set DELACK for segments received in order, but ack
2569		 * immediately when segments are out of order (so
2570		 * fast retransmit can work).
2571		 */
2572		if (th->th_seq == tp->rcv_nxt &&
2573		    LIST_EMPTY(&tp->t_segq) &&
2574		    TCPS_HAVEESTABLISHED(tp->t_state)) {
2575			if (DELAY_ACK(tp))
2576				tp->t_flags |= TF_DELACK;
2577			else
2578				tp->t_flags |= TF_ACKNOW;
2579			tp->rcv_nxt += tlen;
2580			thflags = th->th_flags & TH_FIN;
2581			TCPSTAT_INC(tcps_rcvpack);
2582			TCPSTAT_ADD(tcps_rcvbyte, tlen);
2583			ND6_HINT(tp);
2584			SOCKBUF_LOCK(&so->so_rcv);
2585			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2586				m_freem(m);
2587			else
2588				sbappendstream_locked(&so->so_rcv, m);
2589			/* NB: sorwakeup_locked() does an implicit unlock. */
2590			sorwakeup_locked(so);
2591		} else {
2592			/*
2593			 * XXX: Due to the header drop above "th" is
2594			 * theoretically invalid by now.  Fortunately
2595			 * m_adj() doesn't actually frees any mbufs
2596			 * when trimming from the head.
2597			 */
2598			thflags = tcp_reass(tp, th, &tlen, m);
2599			tp->t_flags |= TF_ACKNOW;
2600		}
2601		if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2602			tcp_update_sack_list(tp, save_start, save_start + tlen);
2603#if 0
2604		/*
2605		 * Note the amount of data that peer has sent into
2606		 * our window, in order to estimate the sender's
2607		 * buffer size.
2608		 * XXX: Unused.
2609		 */
2610		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2611#endif
2612	} else {
2613		m_freem(m);
2614		thflags &= ~TH_FIN;
2615	}
2616
2617	/*
2618	 * If FIN is received ACK the FIN and let the user know
2619	 * that the connection is closing.
2620	 */
2621	if (thflags & TH_FIN) {
2622		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2623			socantrcvmore(so);
2624			/*
2625			 * If connection is half-synchronized
2626			 * (ie NEEDSYN flag on) then delay ACK,
2627			 * so it may be piggybacked when SYN is sent.
2628			 * Otherwise, since we received a FIN then no
2629			 * more input can be expected, send ACK now.
2630			 */
2631			if (tp->t_flags & TF_NEEDSYN)
2632				tp->t_flags |= TF_DELACK;
2633			else
2634				tp->t_flags |= TF_ACKNOW;
2635			tp->rcv_nxt++;
2636		}
2637		switch (tp->t_state) {
2638
2639		/*
2640		 * In SYN_RECEIVED and ESTABLISHED STATES
2641		 * enter the CLOSE_WAIT state.
2642		 */
2643		case TCPS_SYN_RECEIVED:
2644			tp->t_starttime = ticks;
2645			/* FALLTHROUGH */
2646		case TCPS_ESTABLISHED:
2647			tp->t_state = TCPS_CLOSE_WAIT;
2648			break;
2649
2650		/*
2651		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2652		 * enter the CLOSING state.
2653		 */
2654		case TCPS_FIN_WAIT_1:
2655			tp->t_state = TCPS_CLOSING;
2656			break;
2657
2658		/*
2659		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2660		 * starting the time-wait timer, turning off the other
2661		 * standard timers.
2662		 */
2663		case TCPS_FIN_WAIT_2:
2664			INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2665			KASSERT(ti_locked == TI_WLOCKED, ("%s: dodata "
2666			    "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
2667			    ti_locked));
2668
2669			tcp_twstart(tp);
2670			INP_INFO_WUNLOCK(&V_tcbinfo);
2671			return;
2672		}
2673	}
2674	if (ti_locked == TI_RLOCKED)
2675		INP_INFO_RUNLOCK(&V_tcbinfo);
2676	else if (ti_locked == TI_WLOCKED)
2677		INP_INFO_WUNLOCK(&V_tcbinfo);
2678	else
2679		panic("%s: dodata epilogue ti_locked %d", __func__,
2680		    ti_locked);
2681	ti_locked = TI_UNLOCKED;
2682
2683#ifdef TCPDEBUG
2684	if (so->so_options & SO_DEBUG)
2685		tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2686			  &tcp_savetcp, 0);
2687#endif
2688
2689	/*
2690	 * Return any desired output.
2691	 */
2692	if (needoutput || (tp->t_flags & TF_ACKNOW))
2693		(void) tcp_output(tp);
2694
2695check_delack:
2696	KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
2697	    __func__, ti_locked));
2698	INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2699	INP_WLOCK_ASSERT(tp->t_inpcb);
2700
2701	if (tp->t_flags & TF_DELACK) {
2702		tp->t_flags &= ~TF_DELACK;
2703		tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2704	}
2705	INP_WUNLOCK(tp->t_inpcb);
2706	return;
2707
2708dropafterack:
2709	KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2710	    ("tcp_do_segment: dropafterack ti_locked %d", ti_locked));
2711
2712	/*
2713	 * Generate an ACK dropping incoming segment if it occupies
2714	 * sequence space, where the ACK reflects our state.
2715	 *
2716	 * We can now skip the test for the RST flag since all
2717	 * paths to this code happen after packets containing
2718	 * RST have been dropped.
2719	 *
2720	 * In the SYN-RECEIVED state, don't send an ACK unless the
2721	 * segment we received passes the SYN-RECEIVED ACK test.
2722	 * If it fails send a RST.  This breaks the loop in the
2723	 * "LAND" DoS attack, and also prevents an ACK storm
2724	 * between two listening ports that have been sent forged
2725	 * SYN segments, each with the source address of the other.
2726	 */
2727	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2728	    (SEQ_GT(tp->snd_una, th->th_ack) ||
2729	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
2730		rstreason = BANDLIM_RST_OPENPORT;
2731		goto dropwithreset;
2732	}
2733#ifdef TCPDEBUG
2734	if (so->so_options & SO_DEBUG)
2735		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2736			  &tcp_savetcp, 0);
2737#endif
2738	if (ti_locked == TI_RLOCKED)
2739		INP_INFO_RUNLOCK(&V_tcbinfo);
2740	else if (ti_locked == TI_WLOCKED)
2741		INP_INFO_WUNLOCK(&V_tcbinfo);
2742	else
2743		panic("%s: dropafterack epilogue ti_locked %d", __func__,
2744		    ti_locked);
2745	ti_locked = TI_UNLOCKED;
2746
2747	tp->t_flags |= TF_ACKNOW;
2748	(void) tcp_output(tp);
2749	INP_WUNLOCK(tp->t_inpcb);
2750	m_freem(m);
2751	return;
2752
2753dropwithreset:
2754	if (ti_locked == TI_RLOCKED)
2755		INP_INFO_RUNLOCK(&V_tcbinfo);
2756	else if (ti_locked == TI_WLOCKED)
2757		INP_INFO_WUNLOCK(&V_tcbinfo);
2758	else
2759		panic("%s: dropwithreset ti_locked %d", __func__, ti_locked);
2760	ti_locked = TI_UNLOCKED;
2761
2762	if (tp != NULL) {
2763		tcp_dropwithreset(m, th, tp, tlen, rstreason);
2764		INP_WUNLOCK(tp->t_inpcb);
2765	} else
2766		tcp_dropwithreset(m, th, NULL, tlen, rstreason);
2767	return;
2768
2769drop:
2770	if (ti_locked == TI_RLOCKED)
2771		INP_INFO_RUNLOCK(&V_tcbinfo);
2772	else if (ti_locked == TI_WLOCKED)
2773		INP_INFO_WUNLOCK(&V_tcbinfo);
2774#ifdef INVARIANTS
2775	else
2776		INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2777#endif
2778	ti_locked = TI_UNLOCKED;
2779
2780	/*
2781	 * Drop space held by incoming segment and return.
2782	 */
2783#ifdef TCPDEBUG
2784	if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2785		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2786			  &tcp_savetcp, 0);
2787#endif
2788	if (tp != NULL)
2789		INP_WUNLOCK(tp->t_inpcb);
2790	m_freem(m);
2791}
2792
2793/*
2794 * Issue RST and make ACK acceptable to originator of segment.
2795 * The mbuf must still include the original packet header.
2796 * tp may be NULL.
2797 */
2798static void
2799tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2800    int tlen, int rstreason)
2801{
2802	struct ip *ip;
2803#ifdef INET6
2804	struct ip6_hdr *ip6;
2805#endif
2806
2807	if (tp != NULL) {
2808		INP_WLOCK_ASSERT(tp->t_inpcb);
2809	}
2810
2811	/* Don't bother if destination was broadcast/multicast. */
2812	if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2813		goto drop;
2814#ifdef INET6
2815	if (mtod(m, struct ip *)->ip_v == 6) {
2816		ip6 = mtod(m, struct ip6_hdr *);
2817		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2818		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2819			goto drop;
2820		/* IPv6 anycast check is done at tcp6_input() */
2821	} else
2822#endif
2823	{
2824		ip = mtod(m, struct ip *);
2825		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2826		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2827		    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2828		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2829			goto drop;
2830	}
2831
2832	/* Perform bandwidth limiting. */
2833	if (badport_bandlim(rstreason) < 0)
2834		goto drop;
2835
2836	/* tcp_respond consumes the mbuf chain. */
2837	if (th->th_flags & TH_ACK) {
2838		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
2839		    th->th_ack, TH_RST);
2840	} else {
2841		if (th->th_flags & TH_SYN)
2842			tlen++;
2843		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2844		    (tcp_seq)0, TH_RST|TH_ACK);
2845	}
2846	return;
2847drop:
2848	m_freem(m);
2849}
2850
2851/*
2852 * Parse TCP options and place in tcpopt.
2853 */
2854static void
2855tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
2856{
2857	int opt, optlen;
2858
2859	to->to_flags = 0;
2860	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2861		opt = cp[0];
2862		if (opt == TCPOPT_EOL)
2863			break;
2864		if (opt == TCPOPT_NOP)
2865			optlen = 1;
2866		else {
2867			if (cnt < 2)
2868				break;
2869			optlen = cp[1];
2870			if (optlen < 2 || optlen > cnt)
2871				break;
2872		}
2873		switch (opt) {
2874		case TCPOPT_MAXSEG:
2875			if (optlen != TCPOLEN_MAXSEG)
2876				continue;
2877			if (!(flags & TO_SYN))
2878				continue;
2879			to->to_flags |= TOF_MSS;
2880			bcopy((char *)cp + 2,
2881			    (char *)&to->to_mss, sizeof(to->to_mss));
2882			to->to_mss = ntohs(to->to_mss);
2883			break;
2884		case TCPOPT_WINDOW:
2885			if (optlen != TCPOLEN_WINDOW)
2886				continue;
2887			if (!(flags & TO_SYN))
2888				continue;
2889			to->to_flags |= TOF_SCALE;
2890			to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2891			break;
2892		case TCPOPT_TIMESTAMP:
2893			if (optlen != TCPOLEN_TIMESTAMP)
2894				continue;
2895			to->to_flags |= TOF_TS;
2896			bcopy((char *)cp + 2,
2897			    (char *)&to->to_tsval, sizeof(to->to_tsval));
2898			to->to_tsval = ntohl(to->to_tsval);
2899			bcopy((char *)cp + 6,
2900			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2901			to->to_tsecr = ntohl(to->to_tsecr);
2902			break;
2903#ifdef TCP_SIGNATURE
2904		/*
2905		 * XXX In order to reply to a host which has set the
2906		 * TCP_SIGNATURE option in its initial SYN, we have to
2907		 * record the fact that the option was observed here
2908		 * for the syncache code to perform the correct response.
2909		 */
2910		case TCPOPT_SIGNATURE:
2911			if (optlen != TCPOLEN_SIGNATURE)
2912				continue;
2913			to->to_flags |= TOF_SIGNATURE;
2914			to->to_signature = cp + 2;
2915			break;
2916#endif
2917		case TCPOPT_SACK_PERMITTED:
2918			if (optlen != TCPOLEN_SACK_PERMITTED)
2919				continue;
2920			if (!(flags & TO_SYN))
2921				continue;
2922			if (!V_tcp_do_sack)
2923				continue;
2924			to->to_flags |= TOF_SACKPERM;
2925			break;
2926		case TCPOPT_SACK:
2927			if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2928				continue;
2929			if (flags & TO_SYN)
2930				continue;
2931			to->to_flags |= TOF_SACK;
2932			to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2933			to->to_sacks = cp + 2;
2934			TCPSTAT_INC(tcps_sack_rcv_blocks);
2935			break;
2936		default:
2937			continue;
2938		}
2939	}
2940}
2941
2942/*
2943 * Pull out of band byte out of a segment so
2944 * it doesn't appear in the user's data queue.
2945 * It is still reflected in the segment length for
2946 * sequencing purposes.
2947 */
2948static void
2949tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
2950    int off)
2951{
2952	int cnt = off + th->th_urp - 1;
2953
2954	while (cnt >= 0) {
2955		if (m->m_len > cnt) {
2956			char *cp = mtod(m, caddr_t) + cnt;
2957			struct tcpcb *tp = sototcpcb(so);
2958
2959			INP_WLOCK_ASSERT(tp->t_inpcb);
2960
2961			tp->t_iobc = *cp;
2962			tp->t_oobflags |= TCPOOB_HAVEDATA;
2963			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2964			m->m_len--;
2965			if (m->m_flags & M_PKTHDR)
2966				m->m_pkthdr.len--;
2967			return;
2968		}
2969		cnt -= m->m_len;
2970		m = m->m_next;
2971		if (m == NULL)
2972			break;
2973	}
2974	panic("tcp_pulloutofband");
2975}
2976
2977/*
2978 * Collect new round-trip time estimate
2979 * and update averages and current timeout.
2980 */
2981static void
2982tcp_xmit_timer(struct tcpcb *tp, int rtt)
2983{
2984	int delta;
2985
2986	INP_WLOCK_ASSERT(tp->t_inpcb);
2987
2988	TCPSTAT_INC(tcps_rttupdated);
2989	tp->t_rttupdated++;
2990	if (tp->t_srtt != 0) {
2991		/*
2992		 * srtt is stored as fixed point with 5 bits after the
2993		 * binary point (i.e., scaled by 8).  The following magic
2994		 * is equivalent to the smoothing algorithm in rfc793 with
2995		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2996		 * point).  Adjust rtt to origin 0.
2997		 */
2998		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2999			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3000
3001		if ((tp->t_srtt += delta) <= 0)
3002			tp->t_srtt = 1;
3003
3004		/*
3005		 * We accumulate a smoothed rtt variance (actually, a
3006		 * smoothed mean difference), then set the retransmit
3007		 * timer to smoothed rtt + 4 times the smoothed variance.
3008		 * rttvar is stored as fixed point with 4 bits after the
3009		 * binary point (scaled by 16).  The following is
3010		 * equivalent to rfc793 smoothing with an alpha of .75
3011		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
3012		 * rfc793's wired-in beta.
3013		 */
3014		if (delta < 0)
3015			delta = -delta;
3016		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3017		if ((tp->t_rttvar += delta) <= 0)
3018			tp->t_rttvar = 1;
3019		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3020		    tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3021	} else {
3022		/*
3023		 * No rtt measurement yet - use the unsmoothed rtt.
3024		 * Set the variance to half the rtt (so our first
3025		 * retransmit happens at 3*rtt).
3026		 */
3027		tp->t_srtt = rtt << TCP_RTT_SHIFT;
3028		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3029		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3030	}
3031	tp->t_rtttime = 0;
3032	tp->t_rxtshift = 0;
3033
3034	/*
3035	 * the retransmit should happen at rtt + 4 * rttvar.
3036	 * Because of the way we do the smoothing, srtt and rttvar
3037	 * will each average +1/2 tick of bias.  When we compute
3038	 * the retransmit timer, we want 1/2 tick of rounding and
3039	 * 1 extra tick because of +-1/2 tick uncertainty in the
3040	 * firing of the timer.  The bias will give us exactly the
3041	 * 1.5 tick we need.  But, because the bias is
3042	 * statistical, we have to test that we don't drop below
3043	 * the minimum feasible timer (which is 2 ticks).
3044	 */
3045	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3046		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3047
3048	/*
3049	 * We received an ack for a packet that wasn't retransmitted;
3050	 * it is probably safe to discard any error indications we've
3051	 * received recently.  This isn't quite right, but close enough
3052	 * for now (a route might have failed after we sent a segment,
3053	 * and the return path might not be symmetrical).
3054	 */
3055	tp->t_softerror = 0;
3056}
3057
3058/*
3059 * Determine a reasonable value for maxseg size.
3060 * If the route is known, check route for mtu.
3061 * If none, use an mss that can be handled on the outgoing
3062 * interface without forcing IP to fragment; if bigger than
3063 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3064 * to utilize large mbufs.  If no route is found, route has no mtu,
3065 * or the destination isn't local, use a default, hopefully conservative
3066 * size (usually 512 or the default IP max size, but no more than the mtu
3067 * of the interface), as we can't discover anything about intervening
3068 * gateways or networks.  We also initialize the congestion/slow start
3069 * window to be a single segment if the destination isn't local.
3070 * While looking at the routing entry, we also initialize other path-dependent
3071 * parameters from pre-set or cached values in the routing entry.
3072 *
3073 * Also take into account the space needed for options that we
3074 * send regularly.  Make maxseg shorter by that amount to assure
3075 * that we can send maxseg amount of data even when the options
3076 * are present.  Store the upper limit of the length of options plus
3077 * data in maxopd.
3078 *
3079 * In case of T/TCP, we call this routine during implicit connection
3080 * setup as well (offer = -1), to initialize maxseg from the cached
3081 * MSS of our peer.
3082 *
3083 * NOTE that this routine is only called when we process an incoming
3084 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
3085 */
3086void
3087tcp_mss_update(struct tcpcb *tp, int offer,
3088    struct hc_metrics_lite *metricptr, int *mtuflags)
3089{
3090	int mss;
3091	u_long maxmtu;
3092	struct inpcb *inp = tp->t_inpcb;
3093	struct hc_metrics_lite metrics;
3094	int origoffer = offer;
3095#ifdef INET6
3096	int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3097	size_t min_protoh = isipv6 ?
3098			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3099			    sizeof (struct tcpiphdr);
3100#else
3101	const size_t min_protoh = sizeof(struct tcpiphdr);
3102#endif
3103
3104	INP_WLOCK_ASSERT(tp->t_inpcb);
3105
3106	/* Initialize. */
3107#ifdef INET6
3108	if (isipv6) {
3109		maxmtu = tcp_maxmtu6(&inp->inp_inc, mtuflags);
3110		tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt;
3111	} else
3112#endif
3113	{
3114		maxmtu = tcp_maxmtu(&inp->inp_inc, mtuflags);
3115		tp->t_maxopd = tp->t_maxseg = V_tcp_mssdflt;
3116	}
3117
3118	/*
3119	 * No route to sender, stay with default mss and return.
3120	 */
3121	if (maxmtu == 0) {
3122		/*
3123		 * In case we return early we need to initialize metrics
3124		 * to a defined state as tcp_hc_get() would do for us
3125		 * if there was no cache hit.
3126		 */
3127		if (metricptr != NULL)
3128			bzero(metricptr, sizeof(struct hc_metrics_lite));
3129		return;
3130	}
3131
3132	/* What have we got? */
3133	switch (offer) {
3134		case 0:
3135			/*
3136			 * Offer == 0 means that there was no MSS on the SYN
3137			 * segment, in this case we use tcp_mssdflt as
3138			 * already assigned to t_maxopd above.
3139			 */
3140			offer = tp->t_maxopd;
3141			break;
3142
3143		case -1:
3144			/*
3145			 * Offer == -1 means that we didn't receive SYN yet.
3146			 */
3147			/* FALLTHROUGH */
3148
3149		default:
3150			/*
3151			 * Prevent DoS attack with too small MSS. Round up
3152			 * to at least minmss.
3153			 */
3154			offer = max(offer, V_tcp_minmss);
3155	}
3156
3157	/*
3158	 * rmx information is now retrieved from tcp_hostcache.
3159	 */
3160	tcp_hc_get(&inp->inp_inc, &metrics);
3161	if (metricptr != NULL)
3162		bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3163
3164	/*
3165	 * If there's a discovered mtu int tcp hostcache, use it
3166	 * else, use the link mtu.
3167	 */
3168	if (metrics.rmx_mtu)
3169		mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3170	else {
3171#ifdef INET6
3172		if (isipv6) {
3173			mss = maxmtu - min_protoh;
3174			if (!V_path_mtu_discovery &&
3175			    !in6_localaddr(&inp->in6p_faddr))
3176				mss = min(mss, V_tcp_v6mssdflt);
3177		} else
3178#endif
3179		{
3180			mss = maxmtu - min_protoh;
3181			if (!V_path_mtu_discovery &&
3182			    !in_localaddr(inp->inp_faddr))
3183				mss = min(mss, V_tcp_mssdflt);
3184		}
3185		/*
3186		 * XXX - The above conditional (mss = maxmtu - min_protoh)
3187		 * probably violates the TCP spec.
3188		 * The problem is that, since we don't know the
3189		 * other end's MSS, we are supposed to use a conservative
3190		 * default.  But, if we do that, then MTU discovery will
3191		 * never actually take place, because the conservative
3192		 * default is much less than the MTUs typically seen
3193		 * on the Internet today.  For the moment, we'll sweep
3194		 * this under the carpet.
3195		 *
3196		 * The conservative default might not actually be a problem
3197		 * if the only case this occurs is when sending an initial
3198		 * SYN with options and data to a host we've never talked
3199		 * to before.  Then, they will reply with an MSS value which
3200		 * will get recorded and the new parameters should get
3201		 * recomputed.  For Further Study.
3202		 */
3203	}
3204	mss = min(mss, offer);
3205
3206	/*
3207	 * Sanity check: make sure that maxopd will be large
3208	 * enough to allow some data on segments even if the
3209	 * all the option space is used (40bytes).  Otherwise
3210	 * funny things may happen in tcp_output.
3211	 */
3212	mss = max(mss, 64);
3213
3214	/*
3215	 * maxopd stores the maximum length of data AND options
3216	 * in a segment; maxseg is the amount of data in a normal
3217	 * segment.  We need to store this value (maxopd) apart
3218	 * from maxseg, because now every segment carries options
3219	 * and thus we normally have somewhat less data in segments.
3220	 */
3221	tp->t_maxopd = mss;
3222
3223	/*
3224	 * origoffer==-1 indicates that no segments were received yet.
3225	 * In this case we just guess.
3226	 */
3227	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3228	    (origoffer == -1 ||
3229	     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3230		mss -= TCPOLEN_TSTAMP_APPA;
3231
3232#if	(MCLBYTES & (MCLBYTES - 1)) == 0
3233	if (mss > MCLBYTES)
3234		mss &= ~(MCLBYTES-1);
3235#else
3236	if (mss > MCLBYTES)
3237		mss = mss / MCLBYTES * MCLBYTES;
3238#endif
3239	tp->t_maxseg = mss;
3240}
3241
3242void
3243tcp_mss(struct tcpcb *tp, int offer)
3244{
3245	int rtt, mss;
3246	u_long bufsize;
3247	struct inpcb *inp;
3248	struct socket *so;
3249	struct hc_metrics_lite metrics;
3250	int mtuflags = 0;
3251#ifdef INET6
3252	int isipv6;
3253#endif
3254	KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3255
3256	tcp_mss_update(tp, offer, &metrics, &mtuflags);
3257
3258	mss = tp->t_maxseg;
3259	inp = tp->t_inpcb;
3260#ifdef INET6
3261	isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3262#endif
3263
3264	/*
3265	 * If there's a pipesize, change the socket buffer to that size,
3266	 * don't change if sb_hiwat is different than default (then it
3267	 * has been changed on purpose with setsockopt).
3268	 * Make the socket buffers an integral number of mss units;
3269	 * if the mss is larger than the socket buffer, decrease the mss.
3270	 */
3271	so = inp->inp_socket;
3272	SOCKBUF_LOCK(&so->so_snd);
3273	if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
3274		bufsize = metrics.rmx_sendpipe;
3275	else
3276		bufsize = so->so_snd.sb_hiwat;
3277	if (bufsize < mss)
3278		mss = bufsize;
3279	else {
3280		bufsize = roundup(bufsize, mss);
3281		if (bufsize > sb_max)
3282			bufsize = sb_max;
3283		if (bufsize > so->so_snd.sb_hiwat)
3284			(void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3285	}
3286	SOCKBUF_UNLOCK(&so->so_snd);
3287	tp->t_maxseg = mss;
3288
3289	SOCKBUF_LOCK(&so->so_rcv);
3290	if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
3291		bufsize = metrics.rmx_recvpipe;
3292	else
3293		bufsize = so->so_rcv.sb_hiwat;
3294	if (bufsize > mss) {
3295		bufsize = roundup(bufsize, mss);
3296		if (bufsize > sb_max)
3297			bufsize = sb_max;
3298		if (bufsize > so->so_rcv.sb_hiwat)
3299			(void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3300	}
3301	SOCKBUF_UNLOCK(&so->so_rcv);
3302	/*
3303	 * While we're here, check the others too.
3304	 */
3305	if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
3306		tp->t_srtt = rtt;
3307		tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3308		TCPSTAT_INC(tcps_usedrtt);
3309		if (metrics.rmx_rttvar) {
3310			tp->t_rttvar = metrics.rmx_rttvar;
3311			TCPSTAT_INC(tcps_usedrttvar);
3312		} else {
3313			/* default variation is +- 1 rtt */
3314			tp->t_rttvar =
3315			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3316		}
3317		TCPT_RANGESET(tp->t_rxtcur,
3318			      ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3319			      tp->t_rttmin, TCPTV_REXMTMAX);
3320	}
3321	if (metrics.rmx_ssthresh) {
3322		/*
3323		 * There's some sort of gateway or interface
3324		 * buffer limit on the path.  Use this to set
3325		 * the slow start threshhold, but set the
3326		 * threshold to no less than 2*mss.
3327		 */
3328		tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
3329		TCPSTAT_INC(tcps_usedssthresh);
3330	}
3331	if (metrics.rmx_bandwidth)
3332		tp->snd_bandwidth = metrics.rmx_bandwidth;
3333
3334	/*
3335	 * Set the slow-start flight size depending on whether this
3336	 * is a local network or not.
3337	 *
3338	 * Extend this so we cache the cwnd too and retrieve it here.
3339	 * Make cwnd even bigger than RFC3390 suggests but only if we
3340	 * have previous experience with the remote host. Be careful
3341	 * not make cwnd bigger than remote receive window or our own
3342	 * send socket buffer. Maybe put some additional upper bound
3343	 * on the retrieved cwnd. Should do incremental updates to
3344	 * hostcache when cwnd collapses so next connection doesn't
3345	 * overloads the path again.
3346	 *
3347	 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
3348	 * We currently check only in syncache_socket for that.
3349	 */
3350#define TCP_METRICS_CWND
3351#ifdef TCP_METRICS_CWND
3352	if (metrics.rmx_cwnd)
3353		tp->snd_cwnd = max(mss,
3354				min(metrics.rmx_cwnd / 2,
3355				 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
3356	else
3357#endif
3358	if (V_tcp_do_rfc3390)
3359		tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3360#ifdef INET6
3361	else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
3362		 (!isipv6 && in_localaddr(inp->inp_faddr)))
3363#else
3364	else if (in_localaddr(inp->inp_faddr))
3365#endif
3366		tp->snd_cwnd = mss * V_ss_fltsz_local;
3367	else
3368		tp->snd_cwnd = mss * V_ss_fltsz;
3369
3370	/* Check the interface for TSO capabilities. */
3371	if (mtuflags & CSUM_TSO)
3372		tp->t_flags |= TF_TSO;
3373}
3374
3375/*
3376 * Determine the MSS option to send on an outgoing SYN.
3377 */
3378int
3379tcp_mssopt(struct in_conninfo *inc)
3380{
3381	int mss = 0;
3382	u_long maxmtu = 0;
3383	u_long thcmtu = 0;
3384	size_t min_protoh;
3385
3386	KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3387
3388#ifdef INET6
3389	if (inc->inc_flags & INC_ISIPV6) {
3390		mss = V_tcp_v6mssdflt;
3391		maxmtu = tcp_maxmtu6(inc, NULL);
3392		thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3393		min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3394	} else
3395#endif
3396	{
3397		mss = V_tcp_mssdflt;
3398		maxmtu = tcp_maxmtu(inc, NULL);
3399		thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3400		min_protoh = sizeof(struct tcpiphdr);
3401	}
3402	if (maxmtu && thcmtu)
3403		mss = min(maxmtu, thcmtu) - min_protoh;
3404	else if (maxmtu || thcmtu)
3405		mss = max(maxmtu, thcmtu) - min_protoh;
3406
3407	return (mss);
3408}
3409
3410
3411/*
3412 * On a partial ack arrives, force the retransmission of the
3413 * next unacknowledged segment.  Do not clear tp->t_dupacks.
3414 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3415 * be started again.
3416 */
3417static void
3418tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3419{
3420	tcp_seq onxt = tp->snd_nxt;
3421	u_long  ocwnd = tp->snd_cwnd;
3422
3423	INP_WLOCK_ASSERT(tp->t_inpcb);
3424
3425	tcp_timer_activate(tp, TT_REXMT, 0);
3426	tp->t_rtttime = 0;
3427	tp->snd_nxt = th->th_ack;
3428	/*
3429	 * Set snd_cwnd to one segment beyond acknowledged offset.
3430	 * (tp->snd_una has not yet been updated when this function is called.)
3431	 */
3432	tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3433	tp->t_flags |= TF_ACKNOW;
3434	(void) tcp_output(tp);
3435	tp->snd_cwnd = ocwnd;
3436	if (SEQ_GT(onxt, tp->snd_nxt))
3437		tp->snd_nxt = onxt;
3438	/*
3439	 * Partial window deflation.  Relies on fact that tp->snd_una
3440	 * not updated yet.
3441	 */
3442	if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3443		tp->snd_cwnd -= th->th_ack - tp->snd_una;
3444	else
3445		tp->snd_cwnd = 0;
3446	tp->snd_cwnd += tp->t_maxseg;
3447}
3448