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