fastpath.c revision 310212
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 * Copyright (c) 2015 Netflix Inc.
10 * All rights reserved.
11 *
12 * Portions of this software were developed at the Centre for Advanced Internet
13 * Architectures, Swinburne University of Technology, by Lawrence Stewart,
14 * James Healy and David Hayes, made possible in part by a grant from the Cisco
15 * University Research Program Fund at Community Foundation Silicon Valley.
16 *
17 * Portions of this software were developed at the Centre for Advanced
18 * Internet Architectures, Swinburne University of Technology, Melbourne,
19 * Australia by David Hayes under sponsorship from the FreeBSD Foundation.
20 *
21 * Portions of this software were developed by Robert N. M. Watson under
22 * contract to Juniper Networks, Inc.
23 *
24 * Portions of this software were developed by Randall R. Stewart while
25 * working for Netflix Inc.
26 *
27 * Redistribution and use in source and binary forms, with or without
28 * modification, are permitted provided that the following conditions
29 * are met:
30 * 1. Redistributions of source code must retain the above copyright
31 *    notice, this list of conditions and the following disclaimer.
32 * 2. Redistributions in binary form must reproduce the above copyright
33 *    notice, this list of conditions and the following disclaimer in the
34 *    documentation and/or other materials provided with the distribution.
35 * 4. Neither the name of the University nor the names of its contributors
36 *    may be used to endorse or promote products derived from this software
37 *    without specific prior written permission.
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
40 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
42 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
43 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
44 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
45 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
47 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
48 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
49 * SUCH DAMAGE.
50 *
51 *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
52 */
53
54#include <sys/cdefs.h>
55__FBSDID("$FreeBSD: stable/11/sys/netinet/tcp_stacks/fastpath.c 310212 2016-12-18 12:23:48Z tuexen $");
56
57#include "opt_inet.h"
58#include "opt_inet6.h"
59#include "opt_ipsec.h"
60#include "opt_tcpdebug.h"
61
62#include <sys/param.h>
63#include <sys/module.h>
64#include <sys/kernel.h>
65#include <sys/hhook.h>
66#include <sys/malloc.h>
67#include <sys/mbuf.h>
68#include <sys/proc.h>		/* for proc0 declaration */
69#include <sys/protosw.h>
70#include <sys/sdt.h>
71#include <sys/signalvar.h>
72#include <sys/socket.h>
73#include <sys/socketvar.h>
74#include <sys/sysctl.h>
75#include <sys/syslog.h>
76#include <sys/systm.h>
77
78#include <machine/cpu.h>	/* before tcp_seq.h, for tcp_random18() */
79
80#include <vm/uma.h>
81
82#include <net/route.h>
83#include <net/vnet.h>
84
85#define TCPSTATES		/* for logging */
86
87#include <netinet/in.h>
88#include <netinet/in_kdtrace.h>
89#include <netinet/in_pcb.h>
90#include <netinet/in_systm.h>
91#include <netinet/ip.h>
92#include <netinet/ip_icmp.h>	/* required for icmp_var.h */
93#include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
94#include <netinet/ip_var.h>
95#include <netinet/ip_options.h>
96#include <netinet/ip6.h>
97#include <netinet/icmp6.h>
98#include <netinet6/in6_pcb.h>
99#include <netinet6/ip6_var.h>
100#include <netinet/tcp.h>
101#include <netinet/tcp_fsm.h>
102#include <netinet/tcp_seq.h>
103#include <netinet/tcp_timer.h>
104#include <netinet/tcp_var.h>
105#include <netinet6/tcp6_var.h>
106#include <netinet/tcpip.h>
107#include <netinet/tcp_syncache.h>
108#include <netinet/cc/cc.h>
109#ifdef TCPDEBUG
110#include <netinet/tcp_debug.h>
111#endif /* TCPDEBUG */
112#ifdef TCP_OFFLOAD
113#include <netinet/tcp_offload.h>
114#endif
115
116#ifdef IPSEC
117#include <netipsec/ipsec.h>
118#include <netipsec/ipsec6.h>
119#endif /*IPSEC*/
120
121#include <machine/in_cksum.h>
122
123#include <security/mac/mac_framework.h>
124
125VNET_DECLARE(int, tcp_autorcvbuf_inc);
126#define	V_tcp_autorcvbuf_inc	VNET(tcp_autorcvbuf_inc)
127VNET_DECLARE(int, tcp_autorcvbuf_max);
128#define	V_tcp_autorcvbuf_max	VNET(tcp_autorcvbuf_max)
129VNET_DECLARE(int, tcp_do_rfc3042);
130#define	V_tcp_do_rfc3042	VNET(tcp_do_rfc3042)
131VNET_DECLARE(int, tcp_do_autorcvbuf);
132#define	V_tcp_do_autorcvbuf	VNET(tcp_do_autorcvbuf)
133VNET_DECLARE(int, tcp_insecure_rst);
134#define	V_tcp_insecure_rst	VNET(tcp_insecure_rst)
135VNET_DECLARE(int, tcp_insecure_syn);
136#define	V_tcp_insecure_syn	VNET(tcp_insecure_syn)
137
138static void	 tcp_do_segment_fastslow(struct mbuf *, struct tcphdr *,
139			struct socket *, struct tcpcb *, int, int, uint8_t,
140			int);
141
142static void	 tcp_do_segment_fastack(struct mbuf *, struct tcphdr *,
143			struct socket *, struct tcpcb *, int, int, uint8_t,
144			int);
145
146/*
147 * Indicate whether this ack should be delayed.  We can delay the ack if
148 * following conditions are met:
149 *	- There is no delayed ack timer in progress.
150 *	- Our last ack wasn't a 0-sized window. We never want to delay
151 *	  the ack that opens up a 0-sized window.
152 *	- LRO wasn't used for this segment. We make sure by checking that the
153 *	  segment size is not larger than the MSS.
154 */
155#define DELAY_ACK(tp, tlen)						\
156	((!tcp_timer_active(tp, TT_DELACK) &&				\
157	    (tp->t_flags & TF_RXWIN0SENT) == 0) &&			\
158	    (tlen <= tp->t_maxseg) &&					\
159	    (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
160
161/*
162 * So how is this faster than the normal fast ack?
163 * It basically allows us to also stay in the fastpath
164 * when a window-update ack also arrives. In testing
165 * we saw only 25-30% of connections doing fastpath
166 * due to the fact that along with moving forward
167 * in sequence the window was also updated.
168 */
169static void
170tcp_do_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
171	       struct tcpcb *tp, struct tcpopt *to, int drop_hdrlen, int tlen,
172	       int ti_locked, u_long tiwin)
173{
174	int acked;
175	int winup_only=0;
176#ifdef TCPDEBUG
177	/*
178	 * The size of tcp_saveipgen must be the size of the max ip header,
179	 * now IPv6.
180	 */
181	u_char tcp_saveipgen[IP6_HDR_LEN];
182	struct tcphdr tcp_savetcp;
183	short ostate = 0;
184#endif
185        /*
186	 * The following if statement will be true if
187	 * we are doing the win_up_in_fp <and>
188	 * - We have more new data (SEQ_LT(tp->snd_wl1, th->th_seq)) <or>
189	 * - No more new data, but we have an ack for new data
190	 *   (tp->snd_wl1 == th->th_seq && SEQ_LT(tp->snd_wl2, th->th_ack))
191	 * - No more new data, the same ack point but the window grew
192	 *   (tp->snd_wl1 == th->th_seq && tp->snd_wl2 == th->th_ack && twin > tp->snd_wnd)
193	 */
194	if ((SEQ_LT(tp->snd_wl1, th->th_seq) ||
195	     (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
196					    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
197		/* keep track of pure window updates */
198		if (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd) {
199			winup_only = 1;
200			TCPSTAT_INC(tcps_rcvwinupd);
201		}
202		tp->snd_wnd = tiwin;
203		tp->snd_wl1 = th->th_seq;
204		tp->snd_wl2 = th->th_ack;
205		if (tp->snd_wnd > tp->max_sndwnd)
206			tp->max_sndwnd = tp->snd_wnd;
207	}
208	/*
209	 * If last ACK falls within this segment's sequence numbers,
210	 * record the timestamp.
211	 * NOTE that the test is modified according to the latest
212	 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
213	 */
214	if ((to->to_flags & TOF_TS) != 0 &&
215	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
216		tp->ts_recent_age = tcp_ts_getticks();
217		tp->ts_recent = to->to_tsval;
218	}
219	/*
220	 * This is a pure ack for outstanding data.
221	 */
222	if (ti_locked == TI_RLOCKED) {
223		INP_INFO_RUNLOCK(&V_tcbinfo);
224	}
225	ti_locked = TI_UNLOCKED;
226
227	TCPSTAT_INC(tcps_predack);
228
229	/*
230	 * "bad retransmit" recovery.
231	 */
232	if (tp->t_rxtshift == 1 &&
233	    tp->t_flags & TF_PREVVALID &&
234	    (int)(ticks - tp->t_badrxtwin) < 0) {
235		cc_cong_signal(tp, th, CC_RTO_ERR);
236	}
237
238	/*
239	 * Recalculate the transmit timer / rtt.
240	 *
241	 * Some boxes send broken timestamp replies
242	 * during the SYN+ACK phase, ignore
243	 * timestamps of 0 or we could calculate a
244	 * huge RTT and blow up the retransmit timer.
245	 */
246	if ((to->to_flags & TOF_TS) != 0 &&
247	    to->to_tsecr) {
248		u_int t;
249
250		t = tcp_ts_getticks() - to->to_tsecr;
251		if (!tp->t_rttlow || tp->t_rttlow > t)
252			tp->t_rttlow = t;
253		tcp_xmit_timer(tp,
254			       TCP_TS_TO_TICKS(t) + 1);
255	} else if (tp->t_rtttime &&
256		   SEQ_GT(th->th_ack, tp->t_rtseq)) {
257		if (!tp->t_rttlow ||
258		    tp->t_rttlow > ticks - tp->t_rtttime)
259			tp->t_rttlow = ticks - tp->t_rtttime;
260		tcp_xmit_timer(tp,
261			       ticks - tp->t_rtttime);
262	}
263	if (winup_only == 0) {
264		acked = BYTES_THIS_ACK(tp, th);
265
266		/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
267		hhook_run_tcp_est_in(tp, th, to);
268
269		TCPSTAT_ADD(tcps_rcvackbyte, acked);
270		sbdrop(&so->so_snd, acked);
271		if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
272		    SEQ_LEQ(th->th_ack, tp->snd_recover))
273			tp->snd_recover = th->th_ack - 1;
274
275		/*
276		 * Let the congestion control algorithm update
277		 * congestion control related information. This
278		 * typically means increasing the congestion
279		 * window.
280		 */
281		cc_ack_received(tp, th, CC_ACK);
282
283		tp->snd_una = th->th_ack;
284		/*
285		 * Pull snd_wl2 up to prevent seq wrap relative
286		 * to th_ack.
287		 */
288		tp->snd_wl2 = th->th_ack;
289		tp->t_dupacks = 0;
290
291		/*
292		 * If all outstanding data are acked, stop
293		 * retransmit timer, otherwise restart timer
294		 * using current (possibly backed-off) value.
295		 * If process is waiting for space,
296		 * wakeup/selwakeup/signal.  If data
297		 * are ready to send, let tcp_output
298		 * decide between more output or persist.
299		 */
300#ifdef TCPDEBUG
301		if (so->so_options & SO_DEBUG)
302			tcp_trace(TA_INPUT, ostate, tp,
303				  (void *)tcp_saveipgen,
304				  &tcp_savetcp, 0);
305#endif
306		TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
307		m_freem(m);
308		if (tp->snd_una == tp->snd_max)
309			tcp_timer_activate(tp, TT_REXMT, 0);
310		else if (!tcp_timer_active(tp, TT_PERSIST))
311			tcp_timer_activate(tp, TT_REXMT,
312					   tp->t_rxtcur);
313	} else {
314		/*
315		 * Window update only, just free the mbufs and
316		 * send out whatever we can.
317		 */
318		m_freem(m);
319	}
320	sowwakeup(so);
321	if (sbavail(&so->so_snd))
322		(void) tcp_output(tp);
323	KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
324					    __func__, ti_locked));
325	INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
326	INP_WLOCK_ASSERT(tp->t_inpcb);
327
328	if (tp->t_flags & TF_DELACK) {
329		tp->t_flags &= ~TF_DELACK;
330		tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
331	}
332	INP_WUNLOCK(tp->t_inpcb);
333}
334
335/*
336 * Here nothing is really faster, its just that we
337 * have broken out the fast-data path also just like
338 * the fast-ack.
339 */
340static void
341tcp_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
342		   struct tcpcb *tp, struct tcpopt *to, int drop_hdrlen, int tlen,
343		   int ti_locked, u_long tiwin)
344{
345	int newsize = 0;	/* automatic sockbuf scaling */
346#ifdef TCPDEBUG
347	/*
348	 * The size of tcp_saveipgen must be the size of the max ip header,
349	 * now IPv6.
350	 */
351	u_char tcp_saveipgen[IP6_HDR_LEN];
352	struct tcphdr tcp_savetcp;
353	short ostate = 0;
354#endif
355	/*
356	 * If last ACK falls within this segment's sequence numbers,
357	 * record the timestamp.
358	 * NOTE that the test is modified according to the latest
359	 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
360	 */
361	if ((to->to_flags & TOF_TS) != 0 &&
362	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
363		tp->ts_recent_age = tcp_ts_getticks();
364		tp->ts_recent = to->to_tsval;
365	}
366
367	/*
368	 * This is a pure, in-sequence data packet with
369	 * nothing on the reassembly queue and we have enough
370	 * buffer space to take it.
371	 */
372	if (ti_locked == TI_RLOCKED) {
373		INP_INFO_RUNLOCK(&V_tcbinfo);
374	}
375	ti_locked = TI_UNLOCKED;
376
377	/* Clean receiver SACK report if present */
378	if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
379		tcp_clean_sackreport(tp);
380	TCPSTAT_INC(tcps_preddat);
381	tp->rcv_nxt += tlen;
382	/*
383	 * Pull snd_wl1 up to prevent seq wrap relative to
384	 * th_seq.
385	 */
386	tp->snd_wl1 = th->th_seq;
387	/*
388	 * Pull rcv_up up to prevent seq wrap relative to
389	 * rcv_nxt.
390	 */
391	tp->rcv_up = tp->rcv_nxt;
392	TCPSTAT_ADD(tcps_rcvbyte, tlen);
393#ifdef TCPDEBUG
394	if (so->so_options & SO_DEBUG)
395		tcp_trace(TA_INPUT, ostate, tp,
396			  (void *)tcp_saveipgen, &tcp_savetcp, 0);
397#endif
398	TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
399	/*
400	 * Automatic sizing of receive socket buffer.  Often the send
401	 * buffer size is not optimally adjusted to the actual network
402	 * conditions at hand (delay bandwidth product).  Setting the
403	 * buffer size too small limits throughput on links with high
404	 * bandwidth and high delay (eg. trans-continental/oceanic links).
405	 *
406	 * On the receive side the socket buffer memory is only rarely
407	 * used to any significant extent.  This allows us to be much
408	 * more aggressive in scaling the receive socket buffer.  For
409	 * the case that the buffer space is actually used to a large
410	 * extent and we run out of kernel memory we can simply drop
411	 * the new segments; TCP on the sender will just retransmit it
412	 * later.  Setting the buffer size too big may only consume too
413	 * much kernel memory if the application doesn't read() from
414	 * the socket or packet loss or reordering makes use of the
415	 * reassembly queue.
416	 *
417	 * The criteria to step up the receive buffer one notch are:
418	 *  1. Application has not set receive buffer size with
419	 *     SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
420	 *  2. the number of bytes received during the time it takes
421	 *     one timestamp to be reflected back to us (the RTT);
422	 *  3. received bytes per RTT is within seven eighth of the
423	 *     current socket buffer size;
424	 *  4. receive buffer size has not hit maximal automatic size;
425	 *
426	 * This algorithm does one step per RTT at most and only if
427	 * we receive a bulk stream w/o packet losses or reorderings.
428	 * Shrinking the buffer during idle times is not necessary as
429	 * it doesn't consume any memory when idle.
430	 *
431	 * TODO: Only step up if the application is actually serving
432	 * the buffer to better manage the socket buffer resources.
433	 */
434	if (V_tcp_do_autorcvbuf &&
435	    (to->to_flags & TOF_TS) &&
436	    to->to_tsecr &&
437	    (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
438		if (TSTMP_GT(to->to_tsecr, tp->rfbuf_ts) &&
439		    to->to_tsecr - tp->rfbuf_ts < hz) {
440			if (tp->rfbuf_cnt >
441			    (so->so_rcv.sb_hiwat / 8 * 7) &&
442			    so->so_rcv.sb_hiwat <
443			    V_tcp_autorcvbuf_max) {
444				newsize =
445					min(so->so_rcv.sb_hiwat +
446					    V_tcp_autorcvbuf_inc,
447					    V_tcp_autorcvbuf_max);
448			}
449			/* Start over with next RTT. */
450			tp->rfbuf_ts = 0;
451			tp->rfbuf_cnt = 0;
452		} else
453			tp->rfbuf_cnt += tlen;	/* add up */
454	}
455
456	/* Add data to socket buffer. */
457	SOCKBUF_LOCK(&so->so_rcv);
458	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
459		m_freem(m);
460	} else {
461		/*
462		 * Set new socket buffer size.
463		 * Give up when limit is reached.
464		 */
465		if (newsize)
466			if (!sbreserve_locked(&so->so_rcv,
467					      newsize, so, NULL))
468				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
469		m_adj(m, drop_hdrlen);	/* delayed header drop */
470		sbappendstream_locked(&so->so_rcv, m, 0);
471	}
472	/* NB: sorwakeup_locked() does an implicit unlock. */
473	sorwakeup_locked(so);
474	if (DELAY_ACK(tp, tlen)) {
475		tp->t_flags |= TF_DELACK;
476	} else {
477		tp->t_flags |= TF_ACKNOW;
478		tcp_output(tp);
479	}
480	KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
481					    __func__, ti_locked));
482	INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
483	INP_WLOCK_ASSERT(tp->t_inpcb);
484
485	if (tp->t_flags & TF_DELACK) {
486		tp->t_flags &= ~TF_DELACK;
487		tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
488	}
489	INP_WUNLOCK(tp->t_inpcb);
490}
491
492/*
493 * The slow-path is the clone of the long long part
494 * of tcp_do_segment past all the fast-path stuff. We
495 * use it here by two different callers, the fast/slow and
496 * the fastack only.
497 */
498static void
499tcp_do_slowpath(struct mbuf *m, struct tcphdr *th, struct socket *so,
500		struct tcpcb *tp, struct tcpopt *to, int drop_hdrlen, int tlen,
501		int ti_locked, u_long tiwin, int thflags)
502{
503	int  acked, ourfinisacked, needoutput = 0;
504	int rstreason, todrop, win;
505	char *s;
506	struct in_conninfo *inc;
507	struct mbuf *mfree = NULL;
508#ifdef TCPDEBUG
509	/*
510	 * The size of tcp_saveipgen must be the size of the max ip header,
511	 * now IPv6.
512	 */
513	u_char tcp_saveipgen[IP6_HDR_LEN];
514	struct tcphdr tcp_savetcp;
515	short ostate = 0;
516#endif
517	/*
518	 * Calculate amount of space in receive window,
519	 * and then do TCP input processing.
520	 * Receive window is amount of space in rcv queue,
521	 * but not less than advertised window.
522	 */
523	inc = &tp->t_inpcb->inp_inc;
524	win = sbspace(&so->so_rcv);
525	if (win < 0)
526		win = 0;
527	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
528
529	/* Reset receive buffer auto scaling when not in bulk receive mode. */
530	tp->rfbuf_ts = 0;
531	tp->rfbuf_cnt = 0;
532
533	switch (tp->t_state) {
534
535	/*
536	 * If the state is SYN_RECEIVED:
537	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
538	 */
539	case TCPS_SYN_RECEIVED:
540		if ((thflags & TH_ACK) &&
541		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
542		     SEQ_GT(th->th_ack, tp->snd_max))) {
543				rstreason = BANDLIM_RST_OPENPORT;
544				goto dropwithreset;
545		}
546		break;
547
548	/*
549	 * If the state is SYN_SENT:
550	 *	if seg contains an ACK, but not for our SYN, drop the input.
551	 *	if seg contains a RST, then drop the connection.
552	 *	if seg does not contain SYN, then drop it.
553	 * Otherwise this is an acceptable SYN segment
554	 *	initialize tp->rcv_nxt and tp->irs
555	 *	if seg contains ack then advance tp->snd_una
556	 *	if seg contains an ECE and ECN support is enabled, the stream
557	 *	    is ECN capable.
558	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
559	 *	arrange for segment to be acked (eventually)
560	 *	continue processing rest of data/controls, beginning with URG
561	 */
562	case TCPS_SYN_SENT:
563		if ((thflags & TH_ACK) &&
564		    (SEQ_LEQ(th->th_ack, tp->iss) ||
565		     SEQ_GT(th->th_ack, tp->snd_max))) {
566			rstreason = BANDLIM_UNLIMITED;
567			goto dropwithreset;
568		}
569		if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
570			TCP_PROBE5(connect__refused, NULL, tp,
571			    mtod(m, const char *), tp, th);
572			tp = tcp_drop(tp, ECONNREFUSED);
573		}
574		if (thflags & TH_RST)
575			goto drop;
576		if (!(thflags & TH_SYN))
577			goto drop;
578
579		tp->irs = th->th_seq;
580		tcp_rcvseqinit(tp);
581		if (thflags & TH_ACK) {
582			TCPSTAT_INC(tcps_connects);
583			soisconnected(so);
584#ifdef MAC
585			mac_socketpeer_set_from_mbuf(m, so);
586#endif
587			/* Do window scaling on this connection? */
588			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
589				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
590				tp->rcv_scale = tp->request_r_scale;
591			}
592			tp->rcv_adv += imin(tp->rcv_wnd,
593			    TCP_MAXWIN << tp->rcv_scale);
594			tp->snd_una++;		/* SYN is acked */
595			/*
596			 * If there's data, delay ACK; if there's also a FIN
597			 * ACKNOW will be turned on later.
598			 */
599			if (DELAY_ACK(tp, tlen) && tlen != 0)
600				tcp_timer_activate(tp, TT_DELACK,
601				    tcp_delacktime);
602			else
603				tp->t_flags |= TF_ACKNOW;
604
605			if ((thflags & TH_ECE) && V_tcp_do_ecn) {
606				tp->t_flags |= TF_ECN_PERMIT;
607				TCPSTAT_INC(tcps_ecn_shs);
608			}
609
610			/*
611			 * Received <SYN,ACK> in SYN_SENT[*] state.
612			 * Transitions:
613			 *	SYN_SENT  --> ESTABLISHED
614			 *	SYN_SENT* --> FIN_WAIT_1
615			 */
616			tp->t_starttime = ticks;
617			if (tp->t_flags & TF_NEEDFIN) {
618				tcp_state_change(tp, TCPS_FIN_WAIT_1);
619				tp->t_flags &= ~TF_NEEDFIN;
620				thflags &= ~TH_SYN;
621			} else {
622				tcp_state_change(tp, TCPS_ESTABLISHED);
623				TCP_PROBE5(connect__established, NULL, tp,
624				    mtod(m, const char *), tp, th);
625				cc_conn_init(tp);
626				tcp_timer_activate(tp, TT_KEEP,
627				    TP_KEEPIDLE(tp));
628			}
629		} else {
630			/*
631			 * Received initial SYN in SYN-SENT[*] state =>
632			 * simultaneous open.
633			 * If it succeeds, connection is * half-synchronized.
634			 * Otherwise, do 3-way handshake:
635			 *        SYN-SENT -> SYN-RECEIVED
636			 *        SYN-SENT* -> SYN-RECEIVED*
637			 */
638			tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
639			tcp_timer_activate(tp, TT_REXMT, 0);
640			tcp_state_change(tp, TCPS_SYN_RECEIVED);
641		}
642
643		KASSERT(ti_locked == TI_RLOCKED, ("%s: trimthenstep6: "
644		    "ti_locked %d", __func__, ti_locked));
645		INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
646		INP_WLOCK_ASSERT(tp->t_inpcb);
647
648		/*
649		 * Advance th->th_seq to correspond to first data byte.
650		 * If data, trim to stay within window,
651		 * dropping FIN if necessary.
652		 */
653		th->th_seq++;
654		if (tlen > tp->rcv_wnd) {
655			todrop = tlen - tp->rcv_wnd;
656			m_adj(m, -todrop);
657			tlen = tp->rcv_wnd;
658			thflags &= ~TH_FIN;
659			TCPSTAT_INC(tcps_rcvpackafterwin);
660			TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
661		}
662		tp->snd_wl1 = th->th_seq - 1;
663		tp->rcv_up = th->th_seq;
664		/*
665		 * Client side of transaction: already sent SYN and data.
666		 * If the remote host used T/TCP to validate the SYN,
667		 * our data will be ACK'd; if so, enter normal data segment
668		 * processing in the middle of step 5, ack processing.
669		 * Otherwise, goto step 6.
670		 */
671		if (thflags & TH_ACK)
672			goto process_ACK;
673
674		goto step6;
675
676	/*
677	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
678	 *      do normal processing.
679	 *
680	 * NB: Leftover from RFC1644 T/TCP.  Cases to be reused later.
681	 */
682	case TCPS_LAST_ACK:
683	case TCPS_CLOSING:
684		break;  /* continue normal processing */
685	}
686
687	/*
688	 * States other than LISTEN or SYN_SENT.
689	 * First check the RST flag and sequence number since reset segments
690	 * are exempt from the timestamp and connection count tests.  This
691	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
692	 * below which allowed reset segments in half the sequence space
693	 * to fall though and be processed (which gives forged reset
694	 * segments with a random sequence number a 50 percent chance of
695	 * killing a connection).
696	 * Then check timestamp, if present.
697	 * Then check the connection count, if present.
698	 * Then check that at least some bytes of segment are within
699	 * receive window.  If segment begins before rcv_nxt,
700	 * drop leading data (and SYN); if nothing left, just ack.
701	 */
702	if (thflags & TH_RST) {
703		/*
704		 * RFC5961 Section 3.2
705		 *
706		 * - RST drops connection only if SEG.SEQ == RCV.NXT.
707		 * - If RST is in window, we send challenge ACK.
708		 *
709		 * Note: to take into account delayed ACKs, we should
710		 *   test against last_ack_sent instead of rcv_nxt.
711		 * Note 2: we handle special case of closed window, not
712		 *   covered by the RFC.
713		 */
714		if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
715		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
716		    (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
717			INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
718			KASSERT(ti_locked == TI_RLOCKED,
719			    ("%s: TH_RST ti_locked %d, th %p tp %p",
720			    __func__, ti_locked, th, tp));
721			KASSERT(tp->t_state != TCPS_SYN_SENT,
722			    ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
723			    __func__, th, tp));
724
725			if (V_tcp_insecure_rst ||
726			    tp->last_ack_sent == th->th_seq) {
727				TCPSTAT_INC(tcps_drops);
728				/* Drop the connection. */
729				switch (tp->t_state) {
730				case TCPS_SYN_RECEIVED:
731					so->so_error = ECONNREFUSED;
732					goto close;
733				case TCPS_ESTABLISHED:
734				case TCPS_FIN_WAIT_1:
735				case TCPS_FIN_WAIT_2:
736				case TCPS_CLOSE_WAIT:
737				case TCPS_CLOSING:
738				case TCPS_LAST_ACK:
739					so->so_error = ECONNRESET;
740				close:
741					/* FALLTHROUGH */
742				default:
743					tp = tcp_close(tp);
744				}
745			} else {
746				TCPSTAT_INC(tcps_badrst);
747				/* Send challenge ACK. */
748				tcp_respond(tp, mtod(m, void *), th, m,
749				    tp->rcv_nxt, tp->snd_nxt, TH_ACK);
750				tp->last_ack_sent = tp->rcv_nxt;
751				m = NULL;
752			}
753		}
754		goto drop;
755	}
756
757	/*
758	 * RFC5961 Section 4.2
759	 * Send challenge ACK for any SYN in synchronized state.
760	 */
761	if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT) {
762		KASSERT(ti_locked == TI_RLOCKED,
763		    ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
764		INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
765
766		TCPSTAT_INC(tcps_badsyn);
767		if (V_tcp_insecure_syn &&
768		    SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
769		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
770			tp = tcp_drop(tp, ECONNRESET);
771			rstreason = BANDLIM_UNLIMITED;
772		} else {
773			/* Send challenge ACK. */
774			tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
775			    tp->snd_nxt, TH_ACK);
776			tp->last_ack_sent = tp->rcv_nxt;
777			m = NULL;
778		}
779		goto drop;
780	}
781
782	/*
783	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
784	 * and it's less than ts_recent, drop it.
785	 */
786	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
787	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
788
789		/* Check to see if ts_recent is over 24 days old.  */
790		if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
791			/*
792			 * Invalidate ts_recent.  If this segment updates
793			 * ts_recent, the age will be reset later and ts_recent
794			 * will get a valid value.  If it does not, setting
795			 * ts_recent to zero will at least satisfy the
796			 * requirement that zero be placed in the timestamp
797			 * echo reply when ts_recent isn't valid.  The
798			 * age isn't reset until we get a valid ts_recent
799			 * because we don't want out-of-order segments to be
800			 * dropped when ts_recent is old.
801			 */
802			tp->ts_recent = 0;
803		} else {
804			TCPSTAT_INC(tcps_rcvduppack);
805			TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
806			TCPSTAT_INC(tcps_pawsdrop);
807			if (tlen)
808				goto dropafterack;
809			goto drop;
810		}
811	}
812
813	/*
814	 * In the SYN-RECEIVED state, validate that the packet belongs to
815	 * this connection before trimming the data to fit the receive
816	 * window.  Check the sequence number versus IRS since we know
817	 * the sequence numbers haven't wrapped.  This is a partial fix
818	 * for the "LAND" DoS attack.
819	 */
820	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
821		rstreason = BANDLIM_RST_OPENPORT;
822		goto dropwithreset;
823	}
824
825	todrop = tp->rcv_nxt - th->th_seq;
826	if (todrop > 0) {
827		if (thflags & TH_SYN) {
828			thflags &= ~TH_SYN;
829			th->th_seq++;
830			if (th->th_urp > 1)
831				th->th_urp--;
832			else
833				thflags &= ~TH_URG;
834			todrop--;
835		}
836		/*
837		 * Following if statement from Stevens, vol. 2, p. 960.
838		 */
839		if (todrop > tlen
840		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
841			/*
842			 * Any valid FIN must be to the left of the window.
843			 * At this point the FIN must be a duplicate or out
844			 * of sequence; drop it.
845			 */
846			thflags &= ~TH_FIN;
847
848			/*
849			 * Send an ACK to resynchronize and drop any data.
850			 * But keep on processing for RST or ACK.
851			 */
852			tp->t_flags |= TF_ACKNOW;
853			todrop = tlen;
854			TCPSTAT_INC(tcps_rcvduppack);
855			TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
856		} else {
857			TCPSTAT_INC(tcps_rcvpartduppack);
858			TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
859		}
860		drop_hdrlen += todrop;	/* drop from the top afterwards */
861		th->th_seq += todrop;
862		tlen -= todrop;
863		if (th->th_urp > todrop)
864			th->th_urp -= todrop;
865		else {
866			thflags &= ~TH_URG;
867			th->th_urp = 0;
868		}
869	}
870
871	/*
872	 * If new data are received on a connection after the
873	 * user processes are gone, then RST the other end.
874	 */
875	if ((so->so_state & SS_NOFDREF) &&
876	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
877		KASSERT(ti_locked == TI_RLOCKED, ("%s: SS_NOFDEREF && "
878		    "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
879		INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
880
881		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
882			log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
883			    "after socket was closed, "
884			    "sending RST and removing tcpcb\n",
885			    s, __func__, tcpstates[tp->t_state], tlen);
886			free(s, M_TCPLOG);
887		}
888		tp = tcp_close(tp);
889		TCPSTAT_INC(tcps_rcvafterclose);
890		rstreason = BANDLIM_UNLIMITED;
891		goto dropwithreset;
892	}
893
894	/*
895	 * If segment ends after window, drop trailing data
896	 * (and PUSH and FIN); if nothing left, just ACK.
897	 */
898	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
899	if (todrop > 0) {
900		TCPSTAT_INC(tcps_rcvpackafterwin);
901		if (todrop >= tlen) {
902			TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
903			/*
904			 * If window is closed can only take segments at
905			 * window edge, and have to drop data and PUSH from
906			 * incoming segments.  Continue processing, but
907			 * remember to ack.  Otherwise, drop segment
908			 * and ack.
909			 */
910			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
911				tp->t_flags |= TF_ACKNOW;
912				TCPSTAT_INC(tcps_rcvwinprobe);
913			} else
914				goto dropafterack;
915		} else
916			TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
917		m_adj(m, -todrop);
918		tlen -= todrop;
919		thflags &= ~(TH_PUSH|TH_FIN);
920	}
921
922	/*
923	 * If last ACK falls within this segment's sequence numbers,
924	 * record its timestamp.
925	 * NOTE:
926	 * 1) That the test incorporates suggestions from the latest
927	 *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
928	 * 2) That updating only on newer timestamps interferes with
929	 *    our earlier PAWS tests, so this check should be solely
930	 *    predicated on the sequence space of this segment.
931	 * 3) That we modify the segment boundary check to be
932	 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
933	 *    instead of RFC1323's
934	 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
935	 *    This modified check allows us to overcome RFC1323's
936	 *    limitations as described in Stevens TCP/IP Illustrated
937	 *    Vol. 2 p.869. In such cases, we can still calculate the
938	 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
939	 */
940	if ((to->to_flags & TOF_TS) != 0 &&
941	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
942	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
943		((thflags & (TH_SYN|TH_FIN)) != 0))) {
944		tp->ts_recent_age = tcp_ts_getticks();
945		tp->ts_recent = to->to_tsval;
946	}
947
948	/*
949	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
950	 * flag is on (half-synchronized state), then queue data for
951	 * later processing; else drop segment and return.
952	 */
953	if ((thflags & TH_ACK) == 0) {
954		if (tp->t_state == TCPS_SYN_RECEIVED ||
955		    (tp->t_flags & TF_NEEDSYN))
956			goto step6;
957		else if (tp->t_flags & TF_ACKNOW)
958			goto dropafterack;
959		else
960			goto drop;
961	}
962
963	/*
964	 * Ack processing.
965	 */
966	switch (tp->t_state) {
967
968	/*
969	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
970	 * ESTABLISHED state and continue processing.
971	 * The ACK was checked above.
972	 */
973	case TCPS_SYN_RECEIVED:
974
975		TCPSTAT_INC(tcps_connects);
976		soisconnected(so);
977		/* Do window scaling? */
978		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
979			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
980			tp->rcv_scale = tp->request_r_scale;
981			tp->snd_wnd = tiwin;
982		}
983		/*
984		 * Make transitions:
985		 *      SYN-RECEIVED  -> ESTABLISHED
986		 *      SYN-RECEIVED* -> FIN-WAIT-1
987		 */
988		tp->t_starttime = ticks;
989		if (tp->t_flags & TF_NEEDFIN) {
990			tcp_state_change(tp, TCPS_FIN_WAIT_1);
991			tp->t_flags &= ~TF_NEEDFIN;
992		} else {
993			tcp_state_change(tp, TCPS_ESTABLISHED);
994			TCP_PROBE5(accept__established, NULL, tp,
995			    mtod(m, const char *), tp, th);
996			cc_conn_init(tp);
997			tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
998		}
999		/*
1000		 * If segment contains data or ACK, will call tcp_reass()
1001		 * later; if not, do so now to pass queued data to user.
1002		 */
1003		if (tlen == 0 && (thflags & TH_FIN) == 0)
1004			(void) tcp_reass(tp, (struct tcphdr *)0, 0,
1005			    (struct mbuf *)0);
1006		tp->snd_wl1 = th->th_seq - 1;
1007		/* FALLTHROUGH */
1008
1009	/*
1010	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1011	 * ACKs.  If the ack is in the range
1012	 *	tp->snd_una < th->th_ack <= tp->snd_max
1013	 * then advance tp->snd_una to th->th_ack and drop
1014	 * data from the retransmission queue.  If this ACK reflects
1015	 * more up to date window information we update our window information.
1016	 */
1017	case TCPS_ESTABLISHED:
1018	case TCPS_FIN_WAIT_1:
1019	case TCPS_FIN_WAIT_2:
1020	case TCPS_CLOSE_WAIT:
1021	case TCPS_CLOSING:
1022	case TCPS_LAST_ACK:
1023		if (SEQ_GT(th->th_ack, tp->snd_max)) {
1024			TCPSTAT_INC(tcps_rcvacktoomuch);
1025			goto dropafterack;
1026		}
1027		if ((tp->t_flags & TF_SACK_PERMIT) &&
1028		    ((to->to_flags & TOF_SACK) ||
1029		     !TAILQ_EMPTY(&tp->snd_holes)))
1030			tcp_sack_doack(tp, to, th->th_ack);
1031		else
1032			/*
1033			 * Reset the value so that previous (valid) value
1034			 * from the last ack with SACK doesn't get used.
1035			 */
1036			tp->sackhint.sacked_bytes = 0;
1037
1038		/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1039		hhook_run_tcp_est_in(tp, th, to);
1040
1041		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1042			if (tlen == 0 && tiwin == tp->snd_wnd) {
1043				/*
1044				 * If this is the first time we've seen a
1045				 * FIN from the remote, this is not a
1046				 * duplicate and it needs to be processed
1047				 * normally.  This happens during a
1048				 * simultaneous close.
1049				 */
1050				if ((thflags & TH_FIN) &&
1051				    (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
1052					tp->t_dupacks = 0;
1053					break;
1054				}
1055				TCPSTAT_INC(tcps_rcvdupack);
1056				/*
1057				 * If we have outstanding data (other than
1058				 * a window probe), this is a completely
1059				 * duplicate ack (ie, window info didn't
1060				 * change and FIN isn't set),
1061				 * the ack is the biggest we've
1062				 * seen and we've seen exactly our rexmt
1063				 * threshold of them, assume a packet
1064				 * has been dropped and retransmit it.
1065				 * Kludge snd_nxt & the congestion
1066				 * window so we send only this one
1067				 * packet.
1068				 *
1069				 * We know we're losing at the current
1070				 * window size so do congestion avoidance
1071				 * (set ssthresh to half the current window
1072				 * and pull our congestion window back to
1073				 * the new ssthresh).
1074				 *
1075				 * Dup acks mean that packets have left the
1076				 * network (they're now cached at the receiver)
1077				 * so bump cwnd by the amount in the receiver
1078				 * to keep a constant cwnd packets in the
1079				 * network.
1080				 *
1081				 * When using TCP ECN, notify the peer that
1082				 * we reduced the cwnd.
1083				 */
1084				if (!tcp_timer_active(tp, TT_REXMT) ||
1085				    th->th_ack != tp->snd_una)
1086					tp->t_dupacks = 0;
1087				else if (++tp->t_dupacks > tcprexmtthresh ||
1088				     IN_FASTRECOVERY(tp->t_flags)) {
1089					cc_ack_received(tp, th, CC_DUPACK);
1090					if ((tp->t_flags & TF_SACK_PERMIT) &&
1091					    IN_FASTRECOVERY(tp->t_flags)) {
1092						int awnd;
1093
1094						/*
1095						 * Compute the amount of data in flight first.
1096						 * We can inject new data into the pipe iff
1097						 * we have less than 1/2 the original window's
1098						 * worth of data in flight.
1099						 */
1100						if (V_tcp_do_rfc6675_pipe)
1101							awnd = tcp_compute_pipe(tp);
1102						else
1103							awnd = (tp->snd_nxt - tp->snd_fack) +
1104								tp->sackhint.sack_bytes_rexmit;
1105
1106						if (awnd < tp->snd_ssthresh) {
1107							tp->snd_cwnd += tp->t_maxseg;
1108							if (tp->snd_cwnd > tp->snd_ssthresh)
1109								tp->snd_cwnd = tp->snd_ssthresh;
1110						}
1111					} else
1112						tp->snd_cwnd += tp->t_maxseg;
1113					(void) tp->t_fb->tfb_tcp_output(tp);
1114					goto drop;
1115				} else if (tp->t_dupacks == tcprexmtthresh) {
1116					tcp_seq onxt = tp->snd_nxt;
1117
1118					/*
1119					 * If we're doing sack, check to
1120					 * see if we're already in sack
1121					 * recovery. If we're not doing sack,
1122					 * check to see if we're in newreno
1123					 * recovery.
1124					 */
1125					if (tp->t_flags & TF_SACK_PERMIT) {
1126						if (IN_FASTRECOVERY(tp->t_flags)) {
1127							tp->t_dupacks = 0;
1128							break;
1129						}
1130					} else {
1131						if (SEQ_LEQ(th->th_ack,
1132						    tp->snd_recover)) {
1133							tp->t_dupacks = 0;
1134							break;
1135						}
1136					}
1137					/* Congestion signal before ack. */
1138					cc_cong_signal(tp, th, CC_NDUPACK);
1139					cc_ack_received(tp, th, CC_DUPACK);
1140					tcp_timer_activate(tp, TT_REXMT, 0);
1141					tp->t_rtttime = 0;
1142					if (tp->t_flags & TF_SACK_PERMIT) {
1143						TCPSTAT_INC(
1144						    tcps_sack_recovery_episode);
1145						tp->sack_newdata = tp->snd_nxt;
1146						tp->snd_cwnd = tp->t_maxseg;
1147						(void) tp->t_fb->tfb_tcp_output(tp);
1148						goto drop;
1149					}
1150					tp->snd_nxt = th->th_ack;
1151					tp->snd_cwnd = tp->t_maxseg;
1152					(void) tp->t_fb->tfb_tcp_output(tp);
1153					KASSERT(tp->snd_limited <= 2,
1154					    ("%s: tp->snd_limited too big",
1155					    __func__));
1156					tp->snd_cwnd = tp->snd_ssthresh +
1157					     tp->t_maxseg *
1158					     (tp->t_dupacks - tp->snd_limited);
1159					if (SEQ_GT(onxt, tp->snd_nxt))
1160						tp->snd_nxt = onxt;
1161					goto drop;
1162				} else if (V_tcp_do_rfc3042) {
1163					/*
1164					 * Process first and second duplicate
1165					 * ACKs. Each indicates a segment
1166					 * leaving the network, creating room
1167					 * for more. Make sure we can send a
1168					 * packet on reception of each duplicate
1169					 * ACK by increasing snd_cwnd by one
1170					 * segment. Restore the original
1171					 * snd_cwnd after packet transmission.
1172					 */
1173					cc_ack_received(tp, th, CC_DUPACK);
1174					u_long oldcwnd = tp->snd_cwnd;
1175					tcp_seq oldsndmax = tp->snd_max;
1176					u_int sent;
1177					int avail;
1178
1179					KASSERT(tp->t_dupacks == 1 ||
1180					    tp->t_dupacks == 2,
1181					    ("%s: dupacks not 1 or 2",
1182					    __func__));
1183					if (tp->t_dupacks == 1)
1184						tp->snd_limited = 0;
1185					tp->snd_cwnd =
1186					    (tp->snd_nxt - tp->snd_una) +
1187					    (tp->t_dupacks - tp->snd_limited) *
1188					    tp->t_maxseg;
1189					/*
1190					 * Only call tcp_output when there
1191					 * is new data available to be sent.
1192					 * Otherwise we would send pure ACKs.
1193					 */
1194					SOCKBUF_LOCK(&so->so_snd);
1195					avail = sbavail(&so->so_snd) -
1196					    (tp->snd_nxt - tp->snd_una);
1197					SOCKBUF_UNLOCK(&so->so_snd);
1198					if (avail > 0)
1199						(void) tp->t_fb->tfb_tcp_output(tp);
1200					sent = tp->snd_max - oldsndmax;
1201					if (sent > tp->t_maxseg) {
1202						KASSERT((tp->t_dupacks == 2 &&
1203						    tp->snd_limited == 0) ||
1204						   (sent == tp->t_maxseg + 1 &&
1205						    tp->t_flags & TF_SENTFIN),
1206						    ("%s: sent too much",
1207						    __func__));
1208						tp->snd_limited = 2;
1209					} else if (sent > 0)
1210						++tp->snd_limited;
1211					tp->snd_cwnd = oldcwnd;
1212					goto drop;
1213				}
1214			} else
1215				tp->t_dupacks = 0;
1216			break;
1217		}
1218
1219		KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
1220		    ("%s: th_ack <= snd_una", __func__));
1221
1222		/*
1223		 * If the congestion window was inflated to account
1224		 * for the other side's cached packets, retract it.
1225		 */
1226		if (IN_FASTRECOVERY(tp->t_flags)) {
1227			if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1228				if (tp->t_flags & TF_SACK_PERMIT)
1229					tcp_sack_partialack(tp, th);
1230				else
1231					tcp_newreno_partial_ack(tp, th);
1232			} else
1233				cc_post_recovery(tp, th);
1234		}
1235		tp->t_dupacks = 0;
1236		/*
1237		 * If we reach this point, ACK is not a duplicate,
1238		 *     i.e., it ACKs something we sent.
1239		 */
1240		if (tp->t_flags & TF_NEEDSYN) {
1241			/*
1242			 * T/TCP: Connection was half-synchronized, and our
1243			 * SYN has been ACK'd (so connection is now fully
1244			 * synchronized).  Go to non-starred state,
1245			 * increment snd_una for ACK of SYN, and check if
1246			 * we can do window scaling.
1247			 */
1248			tp->t_flags &= ~TF_NEEDSYN;
1249			tp->snd_una++;
1250			/* Do window scaling? */
1251			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1252				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1253				tp->rcv_scale = tp->request_r_scale;
1254				/* Send window already scaled. */
1255			}
1256		}
1257
1258process_ACK:
1259		INP_WLOCK_ASSERT(tp->t_inpcb);
1260
1261		acked = BYTES_THIS_ACK(tp, th);
1262		TCPSTAT_INC(tcps_rcvackpack);
1263		TCPSTAT_ADD(tcps_rcvackbyte, acked);
1264
1265		/*
1266		 * If we just performed our first retransmit, and the ACK
1267		 * arrives within our recovery window, then it was a mistake
1268		 * to do the retransmit in the first place.  Recover our
1269		 * original cwnd and ssthresh, and proceed to transmit where
1270		 * we left off.
1271		 */
1272		if (tp->t_rxtshift == 1 && tp->t_flags & TF_PREVVALID &&
1273		    (int)(ticks - tp->t_badrxtwin) < 0)
1274			cc_cong_signal(tp, th, CC_RTO_ERR);
1275
1276		/*
1277		 * If we have a timestamp reply, update smoothed
1278		 * round trip time.  If no timestamp is present but
1279		 * transmit timer is running and timed sequence
1280		 * number was acked, update smoothed round trip time.
1281		 * Since we now have an rtt measurement, cancel the
1282		 * timer backoff (cf., Phil Karn's retransmit alg.).
1283		 * Recompute the initial retransmit timer.
1284		 *
1285		 * Some boxes send broken timestamp replies
1286		 * during the SYN+ACK phase, ignore
1287		 * timestamps of 0 or we could calculate a
1288		 * huge RTT and blow up the retransmit timer.
1289		 */
1290		if ((to->to_flags & TOF_TS) != 0 && to->to_tsecr) {
1291			u_int t;
1292
1293			t = tcp_ts_getticks() - to->to_tsecr;
1294			if (!tp->t_rttlow || tp->t_rttlow > t)
1295				tp->t_rttlow = t;
1296			tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
1297		} else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
1298			if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
1299				tp->t_rttlow = ticks - tp->t_rtttime;
1300			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1301		}
1302
1303		/*
1304		 * If all outstanding data is acked, stop retransmit
1305		 * timer and remember to restart (more output or persist).
1306		 * If there is more data to be acked, restart retransmit
1307		 * timer, using current (possibly backed-off) value.
1308		 */
1309		if (th->th_ack == tp->snd_max) {
1310			tcp_timer_activate(tp, TT_REXMT, 0);
1311			needoutput = 1;
1312		} else if (!tcp_timer_active(tp, TT_PERSIST))
1313			tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
1314
1315		/*
1316		 * If no data (only SYN) was ACK'd,
1317		 *    skip rest of ACK processing.
1318		 */
1319		if (acked == 0)
1320			goto step6;
1321
1322		/*
1323		 * Let the congestion control algorithm update congestion
1324		 * control related information. This typically means increasing
1325		 * the congestion window.
1326		 */
1327		cc_ack_received(tp, th, CC_ACK);
1328
1329		SOCKBUF_LOCK(&so->so_snd);
1330		if (acked > sbavail(&so->so_snd)) {
1331			tp->snd_wnd -= sbavail(&so->so_snd);
1332			mfree = sbcut_locked(&so->so_snd,
1333			    (int)sbavail(&so->so_snd));
1334			ourfinisacked = 1;
1335		} else {
1336			mfree = sbcut_locked(&so->so_snd, acked);
1337			tp->snd_wnd -= acked;
1338			ourfinisacked = 0;
1339		}
1340		/* NB: sowwakeup_locked() does an implicit unlock. */
1341		sowwakeup_locked(so);
1342		m_freem(mfree);
1343		/* Detect una wraparound. */
1344		if (!IN_RECOVERY(tp->t_flags) &&
1345		    SEQ_GT(tp->snd_una, tp->snd_recover) &&
1346		    SEQ_LEQ(th->th_ack, tp->snd_recover))
1347			tp->snd_recover = th->th_ack - 1;
1348		/* XXXLAS: Can this be moved up into cc_post_recovery? */
1349		if (IN_RECOVERY(tp->t_flags) &&
1350		    SEQ_GEQ(th->th_ack, tp->snd_recover)) {
1351			EXIT_RECOVERY(tp->t_flags);
1352		}
1353		tp->snd_una = th->th_ack;
1354		if (tp->t_flags & TF_SACK_PERMIT) {
1355			if (SEQ_GT(tp->snd_una, tp->snd_recover))
1356				tp->snd_recover = tp->snd_una;
1357		}
1358		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1359			tp->snd_nxt = tp->snd_una;
1360
1361		switch (tp->t_state) {
1362
1363		/*
1364		 * In FIN_WAIT_1 STATE in addition to the processing
1365		 * for the ESTABLISHED state if our FIN is now acknowledged
1366		 * then enter FIN_WAIT_2.
1367		 */
1368		case TCPS_FIN_WAIT_1:
1369			if (ourfinisacked) {
1370				/*
1371				 * If we can't receive any more
1372				 * data, then closing user can proceed.
1373				 * Starting the timer is contrary to the
1374				 * specification, but if we don't get a FIN
1375				 * we'll hang forever.
1376				 *
1377				 * XXXjl:
1378				 * we should release the tp also, and use a
1379				 * compressed state.
1380				 */
1381				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1382					soisdisconnected(so);
1383					tcp_timer_activate(tp, TT_2MSL,
1384					    (tcp_fast_finwait2_recycle ?
1385					    tcp_finwait2_timeout :
1386					    TP_MAXIDLE(tp)));
1387				}
1388				tcp_state_change(tp, TCPS_FIN_WAIT_2);
1389			}
1390			break;
1391
1392		/*
1393		 * In CLOSING STATE in addition to the processing for
1394		 * the ESTABLISHED state if the ACK acknowledges our FIN
1395		 * then enter the TIME-WAIT state, otherwise ignore
1396		 * the segment.
1397		 */
1398		case TCPS_CLOSING:
1399			if (ourfinisacked) {
1400				INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1401				tcp_twstart(tp);
1402				INP_INFO_RUNLOCK(&V_tcbinfo);
1403				m_freem(m);
1404				return;
1405			}
1406			break;
1407
1408		/*
1409		 * In LAST_ACK, we may still be waiting for data to drain
1410		 * and/or to be acked, as well as for the ack of our FIN.
1411		 * If our FIN is now acknowledged, delete the TCB,
1412		 * enter the closed state and return.
1413		 */
1414		case TCPS_LAST_ACK:
1415			if (ourfinisacked) {
1416				INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1417				tp = tcp_close(tp);
1418				goto drop;
1419			}
1420			break;
1421		}
1422	}
1423
1424step6:
1425	INP_WLOCK_ASSERT(tp->t_inpcb);
1426
1427	/*
1428	 * Update window information.
1429	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1430	 */
1431	if ((thflags & TH_ACK) &&
1432	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
1433	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
1434	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
1435		/* keep track of pure window updates */
1436		if (tlen == 0 &&
1437		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
1438			TCPSTAT_INC(tcps_rcvwinupd);
1439		tp->snd_wnd = tiwin;
1440		tp->snd_wl1 = th->th_seq;
1441		tp->snd_wl2 = th->th_ack;
1442		if (tp->snd_wnd > tp->max_sndwnd)
1443			tp->max_sndwnd = tp->snd_wnd;
1444		needoutput = 1;
1445	}
1446
1447	/*
1448	 * Process segments with URG.
1449	 */
1450	if ((thflags & TH_URG) && th->th_urp &&
1451	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1452		/*
1453		 * This is a kludge, but if we receive and accept
1454		 * random urgent pointers, we'll crash in
1455		 * soreceive.  It's hard to imagine someone
1456		 * actually wanting to send this much urgent data.
1457		 */
1458		SOCKBUF_LOCK(&so->so_rcv);
1459		if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
1460			th->th_urp = 0;			/* XXX */
1461			thflags &= ~TH_URG;		/* XXX */
1462			SOCKBUF_UNLOCK(&so->so_rcv);	/* XXX */
1463			goto dodata;			/* XXX */
1464		}
1465		/*
1466		 * If this segment advances the known urgent pointer,
1467		 * then mark the data stream.  This should not happen
1468		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1469		 * a FIN has been received from the remote side.
1470		 * In these states we ignore the URG.
1471		 *
1472		 * According to RFC961 (Assigned Protocols),
1473		 * the urgent pointer points to the last octet
1474		 * of urgent data.  We continue, however,
1475		 * to consider it to indicate the first octet
1476		 * of data past the urgent section as the original
1477		 * spec states (in one of two places).
1478		 */
1479		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
1480			tp->rcv_up = th->th_seq + th->th_urp;
1481			so->so_oobmark = sbavail(&so->so_rcv) +
1482			    (tp->rcv_up - tp->rcv_nxt) - 1;
1483			if (so->so_oobmark == 0)
1484				so->so_rcv.sb_state |= SBS_RCVATMARK;
1485			sohasoutofband(so);
1486			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1487		}
1488		SOCKBUF_UNLOCK(&so->so_rcv);
1489		/*
1490		 * Remove out of band data so doesn't get presented to user.
1491		 * This can happen independent of advancing the URG pointer,
1492		 * but if two URG's are pending at once, some out-of-band
1493		 * data may creep in... ick.
1494		 */
1495		if (th->th_urp <= (u_long)tlen &&
1496		    !(so->so_options & SO_OOBINLINE)) {
1497			/* hdr drop is delayed */
1498			tcp_pulloutofband(so, th, m, drop_hdrlen);
1499		}
1500	} else {
1501		/*
1502		 * If no out of band data is expected,
1503		 * pull receive urgent pointer along
1504		 * with the receive window.
1505		 */
1506		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1507			tp->rcv_up = tp->rcv_nxt;
1508	}
1509dodata:							/* XXX */
1510	INP_WLOCK_ASSERT(tp->t_inpcb);
1511
1512	/*
1513	 * Process the segment text, merging it into the TCP sequencing queue,
1514	 * and arranging for acknowledgment of receipt if necessary.
1515	 * This process logically involves adjusting tp->rcv_wnd as data
1516	 * is presented to the user (this happens in tcp_usrreq.c,
1517	 * case PRU_RCVD).  If a FIN has already been received on this
1518	 * connection then we just ignore the text.
1519	 */
1520	if ((tlen || (thflags & TH_FIN)) &&
1521	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1522		tcp_seq save_start = th->th_seq;
1523		m_adj(m, drop_hdrlen);	/* delayed header drop */
1524		/*
1525		 * Insert segment which includes th into TCP reassembly queue
1526		 * with control block tp.  Set thflags to whether reassembly now
1527		 * includes a segment with FIN.  This handles the common case
1528		 * inline (segment is the next to be received on an established
1529		 * connection, and the queue is empty), avoiding linkage into
1530		 * and removal from the queue and repetition of various
1531		 * conversions.
1532		 * Set DELACK for segments received in order, but ack
1533		 * immediately when segments are out of order (so
1534		 * fast retransmit can work).
1535		 */
1536		if (th->th_seq == tp->rcv_nxt &&
1537		    LIST_EMPTY(&tp->t_segq) &&
1538		    TCPS_HAVEESTABLISHED(tp->t_state)) {
1539			if (DELAY_ACK(tp, tlen))
1540				tp->t_flags |= TF_DELACK;
1541			else
1542				tp->t_flags |= TF_ACKNOW;
1543			tp->rcv_nxt += tlen;
1544			thflags = th->th_flags & TH_FIN;
1545			TCPSTAT_INC(tcps_rcvpack);
1546			TCPSTAT_ADD(tcps_rcvbyte, tlen);
1547			SOCKBUF_LOCK(&so->so_rcv);
1548			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
1549				m_freem(m);
1550			else
1551				sbappendstream_locked(&so->so_rcv, m, 0);
1552			/* NB: sorwakeup_locked() does an implicit unlock. */
1553			sorwakeup_locked(so);
1554		} else {
1555			/*
1556			 * XXX: Due to the header drop above "th" is
1557			 * theoretically invalid by now.  Fortunately
1558			 * m_adj() doesn't actually frees any mbufs
1559			 * when trimming from the head.
1560			 */
1561			thflags = tcp_reass(tp, th, &tlen, m);
1562			tp->t_flags |= TF_ACKNOW;
1563		}
1564		if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
1565			tcp_update_sack_list(tp, save_start, save_start + tlen);
1566#if 0
1567		/*
1568		 * Note the amount of data that peer has sent into
1569		 * our window, in order to estimate the sender's
1570		 * buffer size.
1571		 * XXX: Unused.
1572		 */
1573		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
1574			len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1575		else
1576			len = so->so_rcv.sb_hiwat;
1577#endif
1578	} else {
1579		m_freem(m);
1580		thflags &= ~TH_FIN;
1581	}
1582
1583	/*
1584	 * If FIN is received ACK the FIN and let the user know
1585	 * that the connection is closing.
1586	 */
1587	if (thflags & TH_FIN) {
1588		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1589			socantrcvmore(so);
1590			/*
1591			 * If connection is half-synchronized
1592			 * (ie NEEDSYN flag on) then delay ACK,
1593			 * so it may be piggybacked when SYN is sent.
1594			 * Otherwise, since we received a FIN then no
1595			 * more input can be expected, send ACK now.
1596			 */
1597			if (tp->t_flags & TF_NEEDSYN)
1598				tp->t_flags |= TF_DELACK;
1599			else
1600				tp->t_flags |= TF_ACKNOW;
1601			tp->rcv_nxt++;
1602		}
1603		switch (tp->t_state) {
1604
1605		/*
1606		 * In SYN_RECEIVED and ESTABLISHED STATES
1607		 * enter the CLOSE_WAIT state.
1608		 */
1609		case TCPS_SYN_RECEIVED:
1610			tp->t_starttime = ticks;
1611			/* FALLTHROUGH */
1612		case TCPS_ESTABLISHED:
1613			tcp_state_change(tp, TCPS_CLOSE_WAIT);
1614			break;
1615
1616		/*
1617		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1618		 * enter the CLOSING state.
1619		 */
1620		case TCPS_FIN_WAIT_1:
1621			tcp_state_change(tp, TCPS_CLOSING);
1622			break;
1623
1624		/*
1625		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1626		 * starting the time-wait timer, turning off the other
1627		 * standard timers.
1628		 */
1629		case TCPS_FIN_WAIT_2:
1630			INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1631			KASSERT(ti_locked == TI_RLOCKED, ("%s: dodata "
1632			    "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
1633			    ti_locked));
1634
1635			tcp_twstart(tp);
1636			INP_INFO_RUNLOCK(&V_tcbinfo);
1637			return;
1638		}
1639	}
1640	if (ti_locked == TI_RLOCKED) {
1641		INP_INFO_RUNLOCK(&V_tcbinfo);
1642	}
1643	ti_locked = TI_UNLOCKED;
1644
1645#ifdef TCPDEBUG
1646	if (so->so_options & SO_DEBUG)
1647		tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
1648			  &tcp_savetcp, 0);
1649#endif
1650	TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
1651
1652	/*
1653	 * Return any desired output.
1654	 */
1655	if (needoutput || (tp->t_flags & TF_ACKNOW))
1656		(void) tp->t_fb->tfb_tcp_output(tp);
1657
1658	KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
1659	    __func__, ti_locked));
1660	INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1661	INP_WLOCK_ASSERT(tp->t_inpcb);
1662
1663	if (tp->t_flags & TF_DELACK) {
1664		tp->t_flags &= ~TF_DELACK;
1665		tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
1666	}
1667	INP_WUNLOCK(tp->t_inpcb);
1668	return;
1669
1670dropafterack:
1671	/*
1672	 * Generate an ACK dropping incoming segment if it occupies
1673	 * sequence space, where the ACK reflects our state.
1674	 *
1675	 * We can now skip the test for the RST flag since all
1676	 * paths to this code happen after packets containing
1677	 * RST have been dropped.
1678	 *
1679	 * In the SYN-RECEIVED state, don't send an ACK unless the
1680	 * segment we received passes the SYN-RECEIVED ACK test.
1681	 * If it fails send a RST.  This breaks the loop in the
1682	 * "LAND" DoS attack, and also prevents an ACK storm
1683	 * between two listening ports that have been sent forged
1684	 * SYN segments, each with the source address of the other.
1685	 */
1686	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
1687	    (SEQ_GT(tp->snd_una, th->th_ack) ||
1688	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
1689		rstreason = BANDLIM_RST_OPENPORT;
1690		goto dropwithreset;
1691	}
1692#ifdef TCPDEBUG
1693	if (so->so_options & SO_DEBUG)
1694		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
1695			  &tcp_savetcp, 0);
1696#endif
1697	TCP_PROBE3(debug__drop, tp, th, mtod(m, const char *));
1698	if (ti_locked == TI_RLOCKED) {
1699		INP_INFO_RUNLOCK(&V_tcbinfo);
1700	}
1701	ti_locked = TI_UNLOCKED;
1702
1703	tp->t_flags |= TF_ACKNOW;
1704	(void) tp->t_fb->tfb_tcp_output(tp);
1705	INP_WUNLOCK(tp->t_inpcb);
1706	m_freem(m);
1707	return;
1708
1709dropwithreset:
1710	if (ti_locked == TI_RLOCKED) {
1711		INP_INFO_RUNLOCK(&V_tcbinfo);
1712	}
1713	ti_locked = TI_UNLOCKED;
1714
1715	if (tp != NULL) {
1716		tcp_dropwithreset(m, th, tp, tlen, rstreason);
1717		INP_WUNLOCK(tp->t_inpcb);
1718	} else
1719		tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1720	return;
1721
1722drop:
1723	if (ti_locked == TI_RLOCKED) {
1724		INP_INFO_RUNLOCK(&V_tcbinfo);
1725		ti_locked = TI_UNLOCKED;
1726	}
1727#ifdef INVARIANTS
1728	else
1729		INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1730#endif
1731
1732	/*
1733	 * Drop space held by incoming segment and return.
1734	 */
1735#ifdef TCPDEBUG
1736	if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1737		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
1738			  &tcp_savetcp, 0);
1739#endif
1740	TCP_PROBE3(debug__drop, tp, th, mtod(m, const char *));
1741	if (tp != NULL)
1742		INP_WUNLOCK(tp->t_inpcb);
1743	m_freem(m);
1744}
1745
1746
1747/*
1748 * Do fast slow is a combination of the original
1749 * tcp_dosegment and a split fastpath, one function
1750 * for the fast-ack which also includes allowing fastpath
1751 * for window advanced in sequence acks. And also a
1752 * sub-function that handles the insequence data.
1753 */
1754void
1755tcp_do_segment_fastslow(struct mbuf *m, struct tcphdr *th, struct socket *so,
1756			struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1757			int ti_locked)
1758{
1759	int thflags;
1760	u_long tiwin;
1761	char *s;
1762	int can_enter;
1763	struct in_conninfo *inc;
1764	struct tcpopt to;
1765
1766	thflags = th->th_flags;
1767	tp->sackhint.last_sack_ack = 0;
1768	inc = &tp->t_inpcb->inp_inc;
1769	/*
1770	 * If this is either a state-changing packet or current state isn't
1771	 * established, we require a write lock on tcbinfo.  Otherwise, we
1772	 * allow the tcbinfo to be in either alocked or unlocked, as the
1773	 * caller may have unnecessarily acquired a write lock due to a race.
1774	 */
1775	if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1776	    tp->t_state != TCPS_ESTABLISHED) {
1777		KASSERT(ti_locked == TI_RLOCKED, ("%s ti_locked %d for "
1778						  "SYN/FIN/RST/!EST", __func__, ti_locked));
1779		INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1780	} else {
1781#ifdef INVARIANTS
1782		if (ti_locked == TI_RLOCKED) {
1783			INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1784		} else {
1785			KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST "
1786							   "ti_locked: %d", __func__, ti_locked));
1787			INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1788		}
1789#endif
1790	}
1791	INP_WLOCK_ASSERT(tp->t_inpcb);
1792	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1793					    __func__));
1794	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1795						__func__));
1796
1797	/*
1798	 * Segment received on connection.
1799	 * Reset idle time and keep-alive timer.
1800	 * XXX: This should be done after segment
1801	 * validation to ignore broken/spoofed segs.
1802	 */
1803	tp->t_rcvtime = ticks;
1804	if (TCPS_HAVEESTABLISHED(tp->t_state))
1805		tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
1806
1807	/*
1808	 * Unscale the window into a 32-bit value.
1809	 * For the SYN_SENT state the scale is zero.
1810	 */
1811	tiwin = th->th_win << tp->snd_scale;
1812
1813	/*
1814	 * TCP ECN processing.
1815	 */
1816	if (tp->t_flags & TF_ECN_PERMIT) {
1817		if (thflags & TH_CWR)
1818			tp->t_flags &= ~TF_ECN_SND_ECE;
1819		switch (iptos & IPTOS_ECN_MASK) {
1820		case IPTOS_ECN_CE:
1821			tp->t_flags |= TF_ECN_SND_ECE;
1822			TCPSTAT_INC(tcps_ecn_ce);
1823			break;
1824		case IPTOS_ECN_ECT0:
1825			TCPSTAT_INC(tcps_ecn_ect0);
1826			break;
1827		case IPTOS_ECN_ECT1:
1828			TCPSTAT_INC(tcps_ecn_ect1);
1829			break;
1830		}
1831		/* Congestion experienced. */
1832		if (thflags & TH_ECE) {
1833			cc_cong_signal(tp, th, CC_ECN);
1834		}
1835	}
1836
1837	/*
1838	 * Parse options on any incoming segment.
1839	 */
1840	tcp_dooptions(&to, (u_char *)(th + 1),
1841		      (th->th_off << 2) - sizeof(struct tcphdr),
1842		      (thflags & TH_SYN) ? TO_SYN : 0);
1843
1844	/*
1845	 * If echoed timestamp is later than the current time,
1846	 * fall back to non RFC1323 RTT calculation.  Normalize
1847	 * timestamp if syncookies were used when this connection
1848	 * was established.
1849	 */
1850	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1851		to.to_tsecr -= tp->ts_offset;
1852		if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1853			to.to_tsecr = 0;
1854	}
1855	/*
1856	 * If timestamps were negotiated during SYN/ACK they should
1857	 * appear on every segment during this session and vice versa.
1858	 */
1859	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1860		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1861			log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1862			    "no action\n", s, __func__);
1863			free(s, M_TCPLOG);
1864		}
1865	}
1866	if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
1867		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1868			log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1869			    "no action\n", s, __func__);
1870			free(s, M_TCPLOG);
1871		}
1872	}
1873
1874	/*
1875	 * Process options only when we get SYN/ACK back. The SYN case
1876	 * for incoming connections is handled in tcp_syncache.
1877	 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1878	 * or <SYN,ACK>) segment itself is never scaled.
1879	 * XXX this is traditional behavior, may need to be cleaned up.
1880	 */
1881	if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1882		if ((to.to_flags & TOF_SCALE) &&
1883		    (tp->t_flags & TF_REQ_SCALE)) {
1884			tp->t_flags |= TF_RCVD_SCALE;
1885			tp->snd_scale = to.to_wscale;
1886		}
1887		/*
1888		 * Initial send window.  It will be updated with
1889		 * the next incoming segment to the scaled value.
1890		 */
1891		tp->snd_wnd = th->th_win;
1892		if (to.to_flags & TOF_TS) {
1893			tp->t_flags |= TF_RCVD_TSTMP;
1894			tp->ts_recent = to.to_tsval;
1895			tp->ts_recent_age = tcp_ts_getticks();
1896		}
1897		if (to.to_flags & TOF_MSS)
1898			tcp_mss(tp, to.to_mss);
1899		if ((tp->t_flags & TF_SACK_PERMIT) &&
1900		    (to.to_flags & TOF_SACKPERM) == 0)
1901			tp->t_flags &= ~TF_SACK_PERMIT;
1902	}
1903	can_enter = 0;
1904	if (__predict_true((tlen == 0))) {
1905		/*
1906		 * The ack moved forward and we have a window (non-zero)
1907		 * <or>
1908		 * The ack did not move forward, but the window increased.
1909		 */
1910		if (__predict_true((SEQ_GT(th->th_ack, tp->snd_una) && tiwin) ||
1911				   ((th->th_ack == tp->snd_una) && tiwin && (tiwin > tp->snd_wnd)))) {
1912			can_enter = 1;
1913		}
1914	} else {
1915		/*
1916		 * Data incoming, use the old entry criteria
1917		 * for fast-path with data.
1918		 */
1919		if ((tiwin && tiwin == tp->snd_wnd)) {
1920			can_enter = 1;
1921		}
1922	}
1923	/*
1924	 * Header prediction: check for the two common cases
1925	 * of a uni-directional data xfer.  If the packet has
1926	 * no control flags, is in-sequence, the window didn't
1927	 * change and we're not retransmitting, it's a
1928	 * candidate.  If the length is zero and the ack moved
1929	 * forward, we're the sender side of the xfer.  Just
1930	 * free the data acked & wake any higher level process
1931	 * that was blocked waiting for space.  If the length
1932	 * is non-zero and the ack didn't move, we're the
1933	 * receiver side.  If we're getting packets in-order
1934	 * (the reassembly queue is empty), add the data to
1935	 * the socket buffer and note that we need a delayed ack.
1936	 * Make sure that the hidden state-flags are also off.
1937	 * Since we check for TCPS_ESTABLISHED first, it can only
1938	 * be TH_NEEDSYN.
1939	 */
1940	if (__predict_true(tp->t_state == TCPS_ESTABLISHED &&
1941	    th->th_seq == tp->rcv_nxt &&
1942	    (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1943	    tp->snd_nxt == tp->snd_max &&
1944	    can_enter &&
1945	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1946	    LIST_EMPTY(&tp->t_segq) &&
1947	    ((to.to_flags & TOF_TS) == 0 ||
1948	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)))) {
1949		if (__predict_true((tlen == 0) &&
1950		    (SEQ_LEQ(th->th_ack, tp->snd_max) &&
1951		     !IN_RECOVERY(tp->t_flags) &&
1952		     (to.to_flags & TOF_SACK) == 0 &&
1953		     TAILQ_EMPTY(&tp->snd_holes)))) {
1954			/* We are done */
1955			tcp_do_fastack(m, th, so, tp, &to, drop_hdrlen, tlen,
1956				       ti_locked, tiwin);
1957			return;
1958		} else if ((tlen) &&
1959			   (th->th_ack == tp->snd_una &&
1960			    tlen <= sbspace(&so->so_rcv))) {
1961			tcp_do_fastnewdata(m, th, so, tp, &to, drop_hdrlen, tlen,
1962					   ti_locked, tiwin);
1963			/* We are done */
1964			return;
1965		}
1966	}
1967	tcp_do_slowpath(m, th, so, tp, &to, drop_hdrlen, tlen,
1968			ti_locked, tiwin, thflags);
1969}
1970
1971
1972/*
1973 * This subfunction is used to try to highly optimize the
1974 * fast path. We again allow window updates that are
1975 * in sequence to remain in the fast-path. We also add
1976 * in the __predict's to attempt to help the compiler.
1977 * Note that if we return a 0, then we can *not* process
1978 * it and the caller should push the packet into the
1979 * slow-path.
1980 */
1981static int
1982tcp_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
1983	       struct tcpcb *tp, struct tcpopt *to, int drop_hdrlen, int tlen,
1984	       int ti_locked, u_long tiwin)
1985{
1986	int acked;
1987	int winup_only=0;
1988#ifdef TCPDEBUG
1989	/*
1990	 * The size of tcp_saveipgen must be the size of the max ip header,
1991	 * now IPv6.
1992	 */
1993	u_char tcp_saveipgen[IP6_HDR_LEN];
1994	struct tcphdr tcp_savetcp;
1995	short ostate = 0;
1996#endif
1997
1998
1999	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
2000		/* Old ack, behind (or duplicate to) the last one rcv'd */
2001		return (0);
2002	}
2003	if (__predict_false(th->th_ack == tp->snd_una) &&
2004	    __predict_false(tiwin <= tp->snd_wnd)) {
2005		/* duplicate ack <or> a shrinking dup ack with shrinking window */
2006		return (0);
2007	}
2008	if (__predict_false(tiwin == 0)) {
2009		/* zero window */
2010		return (0);
2011	}
2012	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
2013		/* Above what we have sent? */
2014		return (0);
2015	}
2016	if (__predict_false(tp->snd_nxt != tp->snd_max)) {
2017		/* We are retransmitting */
2018		return (0);
2019	}
2020	if (__predict_false(tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN))) {
2021		/* We need a SYN or a FIN, unlikely.. */
2022		return (0);
2023	}
2024	if((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
2025		/* Timestamp is behind .. old ack with seq wrap? */
2026		return (0);
2027	}
2028	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
2029		/* Still recovering */
2030		return (0);
2031	}
2032	if (__predict_false(to->to_flags & TOF_SACK)) {
2033		/* Sack included in the ack..  */
2034		return (0);
2035	}
2036	if (!TAILQ_EMPTY(&tp->snd_holes)) {
2037		/* We have sack holes on our scoreboard */
2038		return (0);
2039	}
2040	/* Ok if we reach here, we can process a fast-ack */
2041
2042	/* Did the window get updated? */
2043	if (tiwin != tp->snd_wnd) {
2044		/* keep track of pure window updates */
2045		if (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd) {
2046			winup_only = 1;
2047			TCPSTAT_INC(tcps_rcvwinupd);
2048		}
2049		tp->snd_wnd = tiwin;
2050		tp->snd_wl1 = th->th_seq;
2051		if (tp->snd_wnd > tp->max_sndwnd)
2052			tp->max_sndwnd = tp->snd_wnd;
2053	}
2054	/*
2055	 * Pull snd_wl2 up to prevent seq wrap relative
2056	 * to th_ack.
2057	 */
2058	tp->snd_wl2 = th->th_ack;
2059	/*
2060	 * If last ACK falls within this segment's sequence numbers,
2061	 * record the timestamp.
2062	 * NOTE that the test is modified according to the latest
2063	 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2064	 */
2065	if ((to->to_flags & TOF_TS) != 0 &&
2066	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
2067		tp->ts_recent_age = tcp_ts_getticks();
2068		tp->ts_recent = to->to_tsval;
2069	}
2070	/*
2071	 * This is a pure ack for outstanding data.
2072	 */
2073	if (ti_locked == TI_RLOCKED) {
2074		INP_INFO_RUNLOCK(&V_tcbinfo);
2075	}
2076	ti_locked = TI_UNLOCKED;
2077
2078	TCPSTAT_INC(tcps_predack);
2079
2080	/*
2081	 * "bad retransmit" recovery.
2082	 */
2083	if (tp->t_rxtshift == 1 &&
2084	    tp->t_flags & TF_PREVVALID &&
2085	    (int)(ticks - tp->t_badrxtwin) < 0) {
2086		cc_cong_signal(tp, th, CC_RTO_ERR);
2087	}
2088
2089	/*
2090	 * Recalculate the transmit timer / rtt.
2091	 *
2092	 * Some boxes send broken timestamp replies
2093	 * during the SYN+ACK phase, ignore
2094	 * timestamps of 0 or we could calculate a
2095	 * huge RTT and blow up the retransmit timer.
2096	 */
2097	if ((to->to_flags & TOF_TS) != 0 &&
2098	    to->to_tsecr) {
2099		u_int t;
2100
2101		t = tcp_ts_getticks() - to->to_tsecr;
2102		if (!tp->t_rttlow || tp->t_rttlow > t)
2103			tp->t_rttlow = t;
2104		tcp_xmit_timer(tp,
2105			       TCP_TS_TO_TICKS(t) + 1);
2106	} else if (tp->t_rtttime &&
2107		   SEQ_GT(th->th_ack, tp->t_rtseq)) {
2108		if (!tp->t_rttlow ||
2109		    tp->t_rttlow > ticks - tp->t_rtttime)
2110			tp->t_rttlow = ticks - tp->t_rtttime;
2111		tcp_xmit_timer(tp,
2112			       ticks - tp->t_rtttime);
2113	}
2114	if (winup_only == 0) {
2115		acked = BYTES_THIS_ACK(tp, th);
2116
2117		/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2118		hhook_run_tcp_est_in(tp, th, to);
2119
2120		TCPSTAT_ADD(tcps_rcvackbyte, acked);
2121		sbdrop(&so->so_snd, acked);
2122		if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
2123		    SEQ_LEQ(th->th_ack, tp->snd_recover))
2124			tp->snd_recover = th->th_ack - 1;
2125
2126		/*
2127		 * Let the congestion control algorithm update
2128		 * congestion control related information. This
2129		 * typically means increasing the congestion
2130		 * window.
2131		 */
2132		cc_ack_received(tp, th, CC_ACK);
2133
2134		tp->snd_una = th->th_ack;
2135		tp->t_dupacks = 0;
2136
2137		/*
2138		 * If all outstanding data are acked, stop
2139		 * retransmit timer, otherwise restart timer
2140		 * using current (possibly backed-off) value.
2141		 * If process is waiting for space,
2142		 * wakeup/selwakeup/signal.  If data
2143		 * are ready to send, let tcp_output
2144		 * decide between more output or persist.
2145		 */
2146#ifdef TCPDEBUG
2147		if (so->so_options & SO_DEBUG)
2148			tcp_trace(TA_INPUT, ostate, tp,
2149				  (void *)tcp_saveipgen,
2150				  &tcp_savetcp, 0);
2151#endif
2152		TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
2153		m_freem(m);
2154		if (tp->snd_una == tp->snd_max)
2155			tcp_timer_activate(tp, TT_REXMT, 0);
2156		else if (!tcp_timer_active(tp, TT_PERSIST))
2157			tcp_timer_activate(tp, TT_REXMT,
2158					   tp->t_rxtcur);
2159		/* Wake up the socket if we have room to write more */
2160		sowwakeup(so);
2161	} else {
2162		/*
2163		 * Window update only, just free the mbufs and
2164		 * send out whatever we can.
2165		 */
2166		m_freem(m);
2167	}
2168	if (sbavail(&so->so_snd))
2169		(void) tcp_output(tp);
2170	KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
2171					    __func__, ti_locked));
2172	INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2173	INP_WLOCK_ASSERT(tp->t_inpcb);
2174
2175	if (tp->t_flags & TF_DELACK) {
2176		tp->t_flags &= ~TF_DELACK;
2177		tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2178	}
2179	INP_WUNLOCK(tp->t_inpcb);
2180	return (1);
2181}
2182
2183/*
2184 * This tcp-do-segment concentrates on making the fastest
2185 * ack processing path. It does not have a fast-path for
2186 * data (it possibly could which would then eliminate the
2187 * need for fast-slow above). For a content distributor having
2188 * large outgoing elephants and very very little coming in
2189 * having no fastpath for data does not really help (since you
2190 * don't get much data in). The most important thing is
2191 * processing ack's quickly and getting the rest of the data
2192 * output to the peer as quickly as possible. This routine
2193 * seems to be about an overall 3% faster then the old
2194 * tcp_do_segment and keeps us in the fast-path for packets
2195 * much more (by allowing window updates to also stay in the fastpath).
2196 */
2197void
2198tcp_do_segment_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
2199		       struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
2200		       int ti_locked)
2201{
2202	int thflags;
2203	u_long tiwin;
2204	char *s;
2205	struct in_conninfo *inc;
2206	struct tcpopt to;
2207
2208	thflags = th->th_flags;
2209	tp->sackhint.last_sack_ack = 0;
2210	inc = &tp->t_inpcb->inp_inc;
2211	/*
2212	 * If this is either a state-changing packet or current state isn't
2213	 * established, we require a write lock on tcbinfo.  Otherwise, we
2214	 * allow the tcbinfo to be in either alocked or unlocked, as the
2215	 * caller may have unnecessarily acquired a write lock due to a race.
2216	 */
2217	if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
2218	    tp->t_state != TCPS_ESTABLISHED) {
2219		KASSERT(ti_locked == TI_RLOCKED, ("%s ti_locked %d for "
2220						  "SYN/FIN/RST/!EST", __func__, ti_locked));
2221		INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2222	} else {
2223#ifdef INVARIANTS
2224		if (ti_locked == TI_RLOCKED) {
2225			INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2226		} else {
2227			KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST "
2228							   "ti_locked: %d", __func__, ti_locked));
2229			INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2230		}
2231#endif
2232	}
2233	INP_WLOCK_ASSERT(tp->t_inpcb);
2234	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
2235					    __func__));
2236	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
2237						__func__));
2238
2239	/*
2240	 * Segment received on connection.
2241	 * Reset idle time and keep-alive timer.
2242	 * XXX: This should be done after segment
2243	 * validation to ignore broken/spoofed segs.
2244	 */
2245	tp->t_rcvtime = ticks;
2246	if (TCPS_HAVEESTABLISHED(tp->t_state))
2247		tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2248
2249	/*
2250	 * Unscale the window into a 32-bit value.
2251	 * For the SYN_SENT state the scale is zero.
2252	 */
2253	tiwin = th->th_win << tp->snd_scale;
2254
2255	/*
2256	 * TCP ECN processing.
2257	 */
2258	if (tp->t_flags & TF_ECN_PERMIT) {
2259		if (thflags & TH_CWR)
2260			tp->t_flags &= ~TF_ECN_SND_ECE;
2261		switch (iptos & IPTOS_ECN_MASK) {
2262		case IPTOS_ECN_CE:
2263			tp->t_flags |= TF_ECN_SND_ECE;
2264			TCPSTAT_INC(tcps_ecn_ce);
2265			break;
2266		case IPTOS_ECN_ECT0:
2267			TCPSTAT_INC(tcps_ecn_ect0);
2268			break;
2269		case IPTOS_ECN_ECT1:
2270			TCPSTAT_INC(tcps_ecn_ect1);
2271			break;
2272		}
2273		/* Congestion experienced. */
2274		if (thflags & TH_ECE) {
2275			cc_cong_signal(tp, th, CC_ECN);
2276		}
2277	}
2278
2279	/*
2280	 * Parse options on any incoming segment.
2281	 */
2282	tcp_dooptions(&to, (u_char *)(th + 1),
2283		      (th->th_off << 2) - sizeof(struct tcphdr),
2284		      (thflags & TH_SYN) ? TO_SYN : 0);
2285
2286	/*
2287	 * If echoed timestamp is later than the current time,
2288	 * fall back to non RFC1323 RTT calculation.  Normalize
2289	 * timestamp if syncookies were used when this connection
2290	 * was established.
2291	 */
2292	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
2293		to.to_tsecr -= tp->ts_offset;
2294		if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
2295			to.to_tsecr = 0;
2296	}
2297	/*
2298	 * If timestamps were negotiated during SYN/ACK they should
2299	 * appear on every segment during this session and vice versa.
2300	 */
2301	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
2302		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
2303			log(LOG_DEBUG, "%s; %s: Timestamp missing, "
2304			    "no action\n", s, __func__);
2305			free(s, M_TCPLOG);
2306		}
2307	}
2308	if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
2309		if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
2310			log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
2311			    "no action\n", s, __func__);
2312			free(s, M_TCPLOG);
2313		}
2314	}
2315
2316	/*
2317	 * Process options only when we get SYN/ACK back. The SYN case
2318	 * for incoming connections is handled in tcp_syncache.
2319	 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
2320	 * or <SYN,ACK>) segment itself is never scaled.
2321	 * XXX this is traditional behavior, may need to be cleaned up.
2322	 */
2323	if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
2324		if ((to.to_flags & TOF_SCALE) &&
2325		    (tp->t_flags & TF_REQ_SCALE)) {
2326			tp->t_flags |= TF_RCVD_SCALE;
2327			tp->snd_scale = to.to_wscale;
2328		}
2329		/*
2330		 * Initial send window.  It will be updated with
2331		 * the next incoming segment to the scaled value.
2332		 */
2333		tp->snd_wnd = th->th_win;
2334		if (to.to_flags & TOF_TS) {
2335			tp->t_flags |= TF_RCVD_TSTMP;
2336			tp->ts_recent = to.to_tsval;
2337			tp->ts_recent_age = tcp_ts_getticks();
2338		}
2339		if (to.to_flags & TOF_MSS)
2340			tcp_mss(tp, to.to_mss);
2341		if ((tp->t_flags & TF_SACK_PERMIT) &&
2342		    (to.to_flags & TOF_SACKPERM) == 0)
2343			tp->t_flags &= ~TF_SACK_PERMIT;
2344	}
2345	/*
2346	 * Header prediction: check for the two common cases
2347	 * of a uni-directional data xfer.  If the packet has
2348	 * no control flags, is in-sequence, the window didn't
2349	 * change and we're not retransmitting, it's a
2350	 * candidate.  If the length is zero and the ack moved
2351	 * forward, we're the sender side of the xfer.  Just
2352	 * free the data acked & wake any higher level process
2353	 * that was blocked waiting for space.  If the length
2354	 * is non-zero and the ack didn't move, we're the
2355	 * receiver side.  If we're getting packets in-order
2356	 * (the reassembly queue is empty), add the data to
2357	 * the socket buffer and note that we need a delayed ack.
2358	 * Make sure that the hidden state-flags are also off.
2359	 * Since we check for TCPS_ESTABLISHED first, it can only
2360	 * be TH_NEEDSYN.
2361	 */
2362	if (__predict_true(tp->t_state == TCPS_ESTABLISHED) &&
2363	    __predict_true(((to.to_flags & TOF_SACK) == 0)) &&
2364	    __predict_true(tlen == 0) &&
2365	    __predict_true((thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK) &&
2366	    __predict_true(LIST_EMPTY(&tp->t_segq)) &&
2367	    __predict_true(th->th_seq == tp->rcv_nxt)) {
2368		    if (tcp_fastack(m, th, so, tp, &to, drop_hdrlen, tlen,
2369				    ti_locked, tiwin)) {
2370			    return;
2371		    }
2372	}
2373	tcp_do_slowpath(m, th, so, tp, &to, drop_hdrlen, tlen,
2374			ti_locked, tiwin, thflags);
2375}
2376
2377struct tcp_function_block __tcp_fastslow = {
2378	.tfb_tcp_block_name = "fastslow",
2379	.tfb_tcp_output = tcp_output,
2380	.tfb_tcp_do_segment = tcp_do_segment_fastslow,
2381	.tfb_tcp_ctloutput = tcp_default_ctloutput,
2382};
2383
2384struct tcp_function_block __tcp_fastack = {
2385	.tfb_tcp_block_name = "fastack",
2386	.tfb_tcp_output = tcp_output,
2387	.tfb_tcp_do_segment = tcp_do_segment_fastack,
2388	.tfb_tcp_ctloutput = tcp_default_ctloutput
2389};
2390
2391static int
2392tcp_addfastpaths(module_t mod, int type, void *data)
2393{
2394	int err=0;
2395
2396	switch (type) {
2397	case MOD_LOAD:
2398		err = register_tcp_functions(&__tcp_fastack, M_WAITOK);
2399		if (err) {
2400			printf("Failed to register fastack module -- err:%d\n", err);
2401			return(err);
2402		}
2403		err = register_tcp_functions(&__tcp_fastslow, M_WAITOK);
2404		if (err) {
2405			printf("Failed to register fastslow module -- err:%d\n", err);
2406			deregister_tcp_functions(&__tcp_fastack);
2407			return(err);
2408		}
2409		break;
2410	case MOD_QUIESCE:
2411		if ((__tcp_fastslow.tfb_refcnt) ||( __tcp_fastack.tfb_refcnt)) {
2412			return(EBUSY);
2413		}
2414		break;
2415	case MOD_UNLOAD:
2416		err = deregister_tcp_functions(&__tcp_fastack);
2417		if (err == EBUSY)
2418			break;
2419		err = deregister_tcp_functions(&__tcp_fastslow);
2420		if (err == EBUSY)
2421			break;
2422		err = 0;
2423		break;
2424	default:
2425		return (EOPNOTSUPP);
2426	}
2427	return (err);
2428}
2429
2430static moduledata_t new_tcp_fastpaths = {
2431	.name = "tcp_fastpaths",
2432	.evhand = tcp_addfastpaths,
2433	.priv = 0
2434};
2435
2436MODULE_VERSION(kern_tcpfastpaths, 1);
2437DECLARE_MODULE(kern_tcpfastpaths, new_tcp_fastpaths, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
2438