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