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