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