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