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