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.
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.
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.
21 * Portions of this software were developed by Robert N. M. Watson under
22 * contract to Juniper Networks, Inc.
24 * Portions of this software were developed by Randall R. Stewart while
25 * working for Netflix Inc.
27 * Redistribution and use in source and binary forms, with or without
28 * modification, are permitted provided that the following conditions
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.
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
51 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
54 #include <sys/cdefs.h>
55 __FBSDID("$FreeBSD$");
58 #include "opt_inet6.h"
59 #include "opt_ipsec.h"
60 #include "opt_tcpdebug.h"
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>
68 #include <sys/proc.h> /* for proc0 declaration */
69 #include <sys/protosw.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>
78 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
82 #include <net/route.h>
85 #define TCPSTATES /* for logging */
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>
110 #include <netinet/tcp_debug.h>
111 #endif /* TCPDEBUG */
113 #include <netinet/tcp_offload.h>
117 #include <netipsec/ipsec.h>
118 #include <netipsec/ipsec6.h>
121 #include <machine/in_cksum.h>
123 #include <security/mac/mac_framework.h>
125 VNET_DECLARE(int, tcp_autorcvbuf_inc);
126 #define V_tcp_autorcvbuf_inc VNET(tcp_autorcvbuf_inc)
127 VNET_DECLARE(int, tcp_autorcvbuf_max);
128 #define V_tcp_autorcvbuf_max VNET(tcp_autorcvbuf_max)
129 VNET_DECLARE(int, tcp_do_rfc3042);
130 #define V_tcp_do_rfc3042 VNET(tcp_do_rfc3042)
131 VNET_DECLARE(int, tcp_do_autorcvbuf);
132 #define V_tcp_do_autorcvbuf VNET(tcp_do_autorcvbuf)
133 VNET_DECLARE(int, tcp_insecure_rst);
134 #define V_tcp_insecure_rst VNET(tcp_insecure_rst)
135 VNET_DECLARE(int, tcp_insecure_syn);
136 #define V_tcp_insecure_syn VNET(tcp_insecure_syn)
138 static void tcp_do_segment_fastslow(struct mbuf *, struct tcphdr *,
139 struct socket *, struct tcpcb *, int, int, uint8_t,
142 static void tcp_do_segment_fastack(struct mbuf *, struct tcphdr *,
143 struct socket *, struct tcpcb *, int, int, uint8_t,
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.
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)))
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.
170 tcp_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)
178 * The size of tcp_saveipgen must be the size of the max ip header,
181 u_char tcp_saveipgen[IP6_HDR_LEN];
182 struct tcphdr tcp_savetcp;
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)
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) {
200 TCPSTAT_INC(tcps_rcvwinupd);
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;
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).
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;
220 * This is a pure ack for outstanding data.
222 if (ti_locked == TI_RLOCKED) {
223 INP_INFO_RUNLOCK(&V_tcbinfo);
225 ti_locked = TI_UNLOCKED;
227 TCPSTAT_INC(tcps_predack);
230 * "bad retransmit" recovery.
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);
239 * Recalculate the transmit timer / rtt.
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.
246 if ((to->to_flags & TOF_TS) != 0 &&
250 t = tcp_ts_getticks() - to->to_tsecr;
251 if (!tp->t_rttlow || tp->t_rttlow > t)
254 TCP_TS_TO_TICKS(t) + 1);
255 } else if (tp->t_rtttime &&
256 SEQ_GT(th->th_ack, tp->t_rtseq)) {
258 tp->t_rttlow > ticks - tp->t_rtttime)
259 tp->t_rttlow = ticks - tp->t_rtttime;
261 ticks - tp->t_rtttime);
263 if (winup_only == 0) {
264 acked = BYTES_THIS_ACK(tp, th);
266 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
267 hhook_run_tcp_est_in(tp, th, to);
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;
276 * Let the congestion control algorithm update
277 * congestion control related information. This
278 * typically means increasing the congestion
281 cc_ack_received(tp, th, CC_ACK);
283 tp->snd_una = th->th_ack;
285 * Pull snd_wl2 up to prevent seq wrap relative
288 tp->snd_wl2 = th->th_ack;
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.
301 if (so->so_options & SO_DEBUG)
302 tcp_trace(TA_INPUT, ostate, tp,
303 (void *)tcp_saveipgen,
306 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
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,
315 * Window update only, just free the mbufs and
316 * send out whatever we can.
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);
328 if (tp->t_flags & TF_DELACK) {
329 tp->t_flags &= ~TF_DELACK;
330 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
332 INP_WUNLOCK(tp->t_inpcb);
336 * Here nothing is really faster, its just that we
337 * have broken out the fast-data path also just like
341 tcp_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)
345 int newsize = 0; /* automatic sockbuf scaling */
348 * The size of tcp_saveipgen must be the size of the max ip header,
351 u_char tcp_saveipgen[IP6_HDR_LEN];
352 struct tcphdr tcp_savetcp;
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).
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;
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.
372 if (ti_locked == TI_RLOCKED) {
373 INP_INFO_RUNLOCK(&V_tcbinfo);
375 ti_locked = TI_UNLOCKED;
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);
383 * Pull snd_wl1 up to prevent seq wrap relative to
386 tp->snd_wl1 = th->th_seq;
388 * Pull rcv_up up to prevent seq wrap relative to
391 tp->rcv_up = tp->rcv_nxt;
392 TCPSTAT_ADD(tcps_rcvbyte, tlen);
394 if (so->so_options & SO_DEBUG)
395 tcp_trace(TA_INPUT, ostate, tp,
396 (void *)tcp_saveipgen, &tcp_savetcp, 0);
398 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
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).
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
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;
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.
431 * TODO: Only step up if the application is actually serving
432 * the buffer to better manage the socket buffer resources.
434 if (V_tcp_do_autorcvbuf &&
435 (to->to_flags & TOF_TS) &&
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) {
441 (so->so_rcv.sb_hiwat / 8 * 7) &&
442 so->so_rcv.sb_hiwat <
443 V_tcp_autorcvbuf_max) {
445 min(so->so_rcv.sb_hiwat +
446 V_tcp_autorcvbuf_inc,
447 V_tcp_autorcvbuf_max);
449 /* Start over with next RTT. */
453 tp->rfbuf_cnt += tlen; /* add up */
456 /* Add data to socket buffer. */
457 SOCKBUF_LOCK(&so->so_rcv);
458 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
462 * Set new socket buffer size.
463 * Give up when limit is reached.
466 if (!sbreserve_locked(&so->so_rcv,
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);
472 /* NB: sorwakeup_locked() does an implicit unlock. */
473 sorwakeup_locked(so);
474 if (DELAY_ACK(tp, tlen)) {
475 tp->t_flags |= TF_DELACK;
477 tp->t_flags |= TF_ACKNOW;
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);
485 if (tp->t_flags & TF_DELACK) {
486 tp->t_flags &= ~TF_DELACK;
487 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
489 INP_WUNLOCK(tp->t_inpcb);
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
499 tcp_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)
503 int acked, ourfinisacked, needoutput = 0;
504 int rstreason, todrop, win;
506 struct in_conninfo *inc;
507 struct mbuf *mfree = NULL;
510 * The size of tcp_saveipgen must be the size of the max ip header,
513 u_char tcp_saveipgen[IP6_HDR_LEN];
514 struct tcphdr tcp_savetcp;
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.
523 inc = &tp->t_inpcb->inp_inc;
524 win = sbspace(&so->so_rcv);
527 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
529 /* Reset receive buffer auto scaling when not in bulk receive mode. */
533 switch (tp->t_state) {
536 * If the state is SYN_RECEIVED:
537 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
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;
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
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
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;
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);
574 if (thflags & TH_RST)
576 if (!(thflags & TH_SYN))
579 tp->irs = th->th_seq;
581 if (thflags & TH_ACK) {
582 TCPSTAT_INC(tcps_connects);
585 mac_socketpeer_set_from_mbuf(m, so);
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;
592 tp->rcv_adv += imin(tp->rcv_wnd,
593 TCP_MAXWIN << tp->rcv_scale);
594 tp->snd_una++; /* SYN is acked */
596 * If there's data, delay ACK; if there's also a FIN
597 * ACKNOW will be turned on later.
599 if (DELAY_ACK(tp, tlen) && tlen != 0)
600 tcp_timer_activate(tp, TT_DELACK,
603 tp->t_flags |= TF_ACKNOW;
605 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
606 tp->t_flags |= TF_ECN_PERMIT;
607 TCPSTAT_INC(tcps_ecn_shs);
611 * Received <SYN,ACK> in SYN_SENT[*] state.
613 * SYN_SENT --> ESTABLISHED
614 * SYN_SENT* --> FIN_WAIT_1
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;
622 tcp_state_change(tp, TCPS_ESTABLISHED);
623 TCP_PROBE5(connect__established, NULL, tp,
624 mtod(m, const char *), tp, th);
626 tcp_timer_activate(tp, TT_KEEP,
631 * Received initial SYN in SYN-SENT[*] state =>
633 * If it succeeds, connection is * half-synchronized.
634 * Otherwise, do 3-way handshake:
635 * SYN-SENT -> SYN-RECEIVED
636 * SYN-SENT* -> SYN-RECEIVED*
638 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
639 tcp_timer_activate(tp, TT_REXMT, 0);
640 tcp_state_change(tp, TCPS_SYN_RECEIVED);
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);
649 * Advance th->th_seq to correspond to first data byte.
650 * If data, trim to stay within window,
651 * dropping FIN if necessary.
654 if (tlen > tp->rcv_wnd) {
655 todrop = tlen - tp->rcv_wnd;
659 TCPSTAT_INC(tcps_rcvpackafterwin);
660 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
662 tp->snd_wl1 = th->th_seq - 1;
663 tp->rcv_up = th->th_seq;
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.
671 if (thflags & TH_ACK)
677 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
678 * do normal processing.
680 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
684 break; /* continue normal processing */
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.
702 if (thflags & TH_RST) {
704 * RFC5961 Section 3.2
706 * - RST drops connection only if SEG.SEQ == RCV.NXT.
707 * - If RST is in window, we send challenge ACK.
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.
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",
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;
733 case TCPS_ESTABLISHED:
734 case TCPS_FIN_WAIT_1:
735 case TCPS_FIN_WAIT_2:
736 case TCPS_CLOSE_WAIT:
739 so->so_error = ECONNRESET;
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;
758 * RFC5961 Section 4.2
759 * Send challenge ACK for any SYN in synchronized state.
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);
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;
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;
783 * RFC 1323 PAWS: If we have a timestamp reply on this segment
784 * and it's less than ts_recent, drop it.
786 if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
787 TSTMP_LT(to->to_tsval, tp->ts_recent)) {
789 /* Check to see if ts_recent is over 24 days old. */
790 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
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.
804 TCPSTAT_INC(tcps_rcvduppack);
805 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
806 TCPSTAT_INC(tcps_pawsdrop);
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.
820 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
821 rstreason = BANDLIM_RST_OPENPORT;
825 todrop = tp->rcv_nxt - th->th_seq;
827 if (thflags & TH_SYN) {
837 * Following if statement from Stevens, vol. 2, p. 960.
840 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
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.
849 * Send an ACK to resynchronize and drop any data.
850 * But keep on processing for RST or ACK.
852 tp->t_flags |= TF_ACKNOW;
854 TCPSTAT_INC(tcps_rcvduppack);
855 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
857 TCPSTAT_INC(tcps_rcvpartduppack);
858 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
860 drop_hdrlen += todrop; /* drop from the top afterwards */
861 th->th_seq += todrop;
863 if (th->th_urp > todrop)
864 th->th_urp -= todrop;
872 * If new data are received on a connection after the
873 * user processes are gone, then RST the other end.
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);
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);
889 TCPSTAT_INC(tcps_rcvafterclose);
890 rstreason = BANDLIM_UNLIMITED;
895 * If segment ends after window, drop trailing data
896 * (and PUSH and FIN); if nothing left, just ACK.
898 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
900 TCPSTAT_INC(tcps_rcvpackafterwin);
901 if (todrop >= tlen) {
902 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
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
910 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
911 tp->t_flags |= TF_ACKNOW;
912 TCPSTAT_INC(tcps_rcvwinprobe);
916 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
919 thflags &= ~(TH_PUSH|TH_FIN);
923 * If last ACK falls within this segment's sequence numbers,
924 * record its timestamp.
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.
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;
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.
953 if ((thflags & TH_ACK) == 0) {
954 if (tp->t_state == TCPS_SYN_RECEIVED ||
955 (tp->t_flags & TF_NEEDSYN))
957 else if (tp->t_flags & TF_ACKNOW)
966 switch (tp->t_state) {
969 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
970 * ESTABLISHED state and continue processing.
971 * The ACK was checked above.
973 case TCPS_SYN_RECEIVED:
975 TCPSTAT_INC(tcps_connects);
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;
985 * SYN-RECEIVED -> ESTABLISHED
986 * SYN-RECEIVED* -> FIN-WAIT-1
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;
993 tcp_state_change(tp, TCPS_ESTABLISHED);
994 TCP_PROBE5(accept__established, NULL, tp,
995 mtod(m, const char *), tp, th);
997 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
1000 * If segment contains data or ACK, will call tcp_reass()
1001 * later; if not, do so now to pass queued data to user.
1003 if (tlen == 0 && (thflags & TH_FIN) == 0)
1004 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1006 tp->snd_wl1 = th->th_seq - 1;
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.
1017 case TCPS_ESTABLISHED:
1018 case TCPS_FIN_WAIT_1:
1019 case TCPS_FIN_WAIT_2:
1020 case TCPS_CLOSE_WAIT:
1023 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1024 TCPSTAT_INC(tcps_rcvacktoomuch);
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);
1033 * Reset the value so that previous (valid) value
1034 * from the last ack with SACK doesn't get used.
1036 tp->sackhint.sacked_bytes = 0;
1038 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1039 hhook_run_tcp_est_in(tp, th, to);
1041 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1042 if (tlen == 0 && tiwin == tp->snd_wnd) {
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.
1050 if ((thflags & TH_FIN) &&
1051 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
1055 TCPSTAT_INC(tcps_rcvdupack);
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
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).
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
1081 * When using TCP ECN, notify the peer that
1082 * we reduced the cwnd.
1084 if (!tcp_timer_active(tp, TT_REXMT) ||
1085 th->th_ack != tp->snd_una)
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)) {
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.
1100 if (V_tcp_do_rfc6675_pipe)
1101 awnd = tcp_compute_pipe(tp);
1103 awnd = (tp->snd_nxt - tp->snd_fack) +
1104 tp->sackhint.sack_bytes_rexmit;
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;
1112 tp->snd_cwnd += tp->t_maxseg;
1113 (void) tp->t_fb->tfb_tcp_output(tp);
1115 } else if (tp->t_dupacks == tcprexmtthresh) {
1116 tcp_seq onxt = tp->snd_nxt;
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
1125 if (tp->t_flags & TF_SACK_PERMIT) {
1126 if (IN_FASTRECOVERY(tp->t_flags)) {
1131 if (SEQ_LEQ(th->th_ack,
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);
1142 if (tp->t_flags & TF_SACK_PERMIT) {
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);
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",
1156 tp->snd_cwnd = tp->snd_ssthresh +
1158 (tp->t_dupacks - tp->snd_limited);
1159 if (SEQ_GT(onxt, tp->snd_nxt))
1162 } else if (V_tcp_do_rfc3042) {
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.
1173 cc_ack_received(tp, th, CC_DUPACK);
1174 u_long oldcwnd = tp->snd_cwnd;
1175 tcp_seq oldsndmax = tp->snd_max;
1179 KASSERT(tp->t_dupacks == 1 ||
1181 ("%s: dupacks not 1 or 2",
1183 if (tp->t_dupacks == 1)
1184 tp->snd_limited = 0;
1186 (tp->snd_nxt - tp->snd_una) +
1187 (tp->t_dupacks - tp->snd_limited) *
1190 * Only call tcp_output when there
1191 * is new data available to be sent.
1192 * Otherwise we would send pure ACKs.
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);
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",
1208 tp->snd_limited = 2;
1209 } else if (sent > 0)
1211 tp->snd_cwnd = oldcwnd;
1219 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
1220 ("%s: th_ack <= snd_una", __func__));
1223 * If the congestion window was inflated to account
1224 * for the other side's cached packets, retract it.
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);
1231 tcp_newreno_partial_ack(tp, th);
1233 cc_post_recovery(tp, th);
1237 * If we reach this point, ACK is not a duplicate,
1238 * i.e., it ACKs something we sent.
1240 if (tp->t_flags & TF_NEEDSYN) {
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.
1248 tp->t_flags &= ~TF_NEEDSYN;
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. */
1259 INP_WLOCK_ASSERT(tp->t_inpcb);
1261 acked = BYTES_THIS_ACK(tp, th);
1262 TCPSTAT_INC(tcps_rcvackpack);
1263 TCPSTAT_ADD(tcps_rcvackbyte, acked);
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
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);
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.
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.
1290 if ((to->to_flags & TOF_TS) != 0 && to->to_tsecr) {
1293 t = tcp_ts_getticks() - to->to_tsecr;
1294 if (!tp->t_rttlow || 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);
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.
1309 if (th->th_ack == tp->snd_max) {
1310 tcp_timer_activate(tp, TT_REXMT, 0);
1312 } else if (!tcp_timer_active(tp, TT_PERSIST))
1313 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
1316 * If no data (only SYN) was ACK'd,
1317 * skip rest of ACK processing.
1323 * Let the congestion control algorithm update congestion
1324 * control related information. This typically means increasing
1325 * the congestion window.
1327 cc_ack_received(tp, th, CC_ACK);
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));
1336 mfree = sbcut_locked(&so->so_snd, acked);
1337 tp->snd_wnd -= acked;
1340 /* NB: sowwakeup_locked() does an implicit unlock. */
1341 sowwakeup_locked(so);
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);
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;
1358 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1359 tp->snd_nxt = tp->snd_una;
1361 switch (tp->t_state) {
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.
1368 case TCPS_FIN_WAIT_1:
1369 if (ourfinisacked) {
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.
1378 * we should release the tp also, and use a
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 :
1388 tcp_state_change(tp, TCPS_FIN_WAIT_2);
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
1399 if (ourfinisacked) {
1400 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1402 INP_INFO_RUNLOCK(&V_tcbinfo);
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.
1415 if (ourfinisacked) {
1416 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1425 INP_WLOCK_ASSERT(tp->t_inpcb);
1428 * Update window information.
1429 * Don't look at window if no ACK: TAC's send garbage on first SYN.
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 */
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;
1448 * Process segments with URG.
1450 if ((thflags & TH_URG) && th->th_urp &&
1451 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
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.
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 */
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.
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).
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;
1486 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1488 SOCKBUF_UNLOCK(&so->so_rcv);
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.
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);
1502 * If no out of band data is expected,
1503 * pull receive urgent pointer along
1504 * with the receive window.
1506 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1507 tp->rcv_up = tp->rcv_nxt;
1510 INP_WLOCK_ASSERT(tp->t_inpcb);
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.
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 */
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
1532 * Set DELACK for segments received in order, but ack
1533 * immediately when segments are out of order (so
1534 * fast retransmit can work).
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;
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)
1551 sbappendstream_locked(&so->so_rcv, m, 0);
1552 /* NB: sorwakeup_locked() does an implicit unlock. */
1553 sorwakeup_locked(so);
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.
1561 thflags = tcp_reass(tp, th, &tlen, m);
1562 tp->t_flags |= TF_ACKNOW;
1564 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
1565 tcp_update_sack_list(tp, save_start, save_start + tlen);
1568 * Note the amount of data that peer has sent into
1569 * our window, in order to estimate the sender's
1573 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
1574 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1576 len = so->so_rcv.sb_hiwat;
1584 * If FIN is received ACK the FIN and let the user know
1585 * that the connection is closing.
1587 if (thflags & TH_FIN) {
1588 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
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.
1597 if (tp->t_flags & TF_NEEDSYN)
1598 tp->t_flags |= TF_DELACK;
1600 tp->t_flags |= TF_ACKNOW;
1603 switch (tp->t_state) {
1606 * In SYN_RECEIVED and ESTABLISHED STATES
1607 * enter the CLOSE_WAIT state.
1609 case TCPS_SYN_RECEIVED:
1610 tp->t_starttime = ticks;
1612 case TCPS_ESTABLISHED:
1613 tcp_state_change(tp, TCPS_CLOSE_WAIT);
1617 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1618 * enter the CLOSING state.
1620 case TCPS_FIN_WAIT_1:
1621 tcp_state_change(tp, TCPS_CLOSING);
1625 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1626 * starting the time-wait timer, turning off the other
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__,
1636 INP_INFO_RUNLOCK(&V_tcbinfo);
1640 if (ti_locked == TI_RLOCKED) {
1641 INP_INFO_RUNLOCK(&V_tcbinfo);
1643 ti_locked = TI_UNLOCKED;
1646 if (so->so_options & SO_DEBUG)
1647 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
1650 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
1653 * Return any desired output.
1655 if (needoutput || (tp->t_flags & TF_ACKNOW))
1656 (void) tp->t_fb->tfb_tcp_output(tp);
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);
1663 if (tp->t_flags & TF_DELACK) {
1664 tp->t_flags &= ~TF_DELACK;
1665 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
1667 INP_WUNLOCK(tp->t_inpcb);
1672 * Generate an ACK dropping incoming segment if it occupies
1673 * sequence space, where the ACK reflects our state.
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.
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.
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;
1693 if (so->so_options & SO_DEBUG)
1694 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
1697 TCP_PROBE3(debug__drop, tp, th, mtod(m, const char *));
1698 if (ti_locked == TI_RLOCKED) {
1699 INP_INFO_RUNLOCK(&V_tcbinfo);
1701 ti_locked = TI_UNLOCKED;
1703 tp->t_flags |= TF_ACKNOW;
1704 (void) tp->t_fb->tfb_tcp_output(tp);
1705 INP_WUNLOCK(tp->t_inpcb);
1710 if (ti_locked == TI_RLOCKED) {
1711 INP_INFO_RUNLOCK(&V_tcbinfo);
1713 ti_locked = TI_UNLOCKED;
1716 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1717 INP_WUNLOCK(tp->t_inpcb);
1719 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1723 if (ti_locked == TI_RLOCKED) {
1724 INP_INFO_RUNLOCK(&V_tcbinfo);
1725 ti_locked = TI_UNLOCKED;
1729 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1733 * Drop space held by incoming segment and return.
1736 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1737 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
1740 TCP_PROBE3(debug__drop, tp, th, mtod(m, const char *));
1742 INP_WUNLOCK(tp->t_inpcb);
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.
1755 tcp_do_segment_fastslow(struct mbuf *m, struct tcphdr *th, struct socket *so,
1756 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1763 struct in_conninfo *inc;
1766 thflags = th->th_flags;
1767 tp->sackhint.last_sack_ack = 0;
1768 inc = &tp->t_inpcb->inp_inc;
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.
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);
1782 if (ti_locked == TI_RLOCKED) {
1783 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1785 KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST "
1786 "ti_locked: %d", __func__, ti_locked));
1787 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1791 INP_WLOCK_ASSERT(tp->t_inpcb);
1792 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1794 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
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.
1803 tp->t_rcvtime = ticks;
1804 if (TCPS_HAVEESTABLISHED(tp->t_state))
1805 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
1808 * Unscale the window into a 32-bit value.
1809 * For the SYN_SENT state the scale is zero.
1811 tiwin = th->th_win << tp->snd_scale;
1814 * TCP ECN processing.
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) {
1821 tp->t_flags |= TF_ECN_SND_ECE;
1822 TCPSTAT_INC(tcps_ecn_ce);
1824 case IPTOS_ECN_ECT0:
1825 TCPSTAT_INC(tcps_ecn_ect0);
1827 case IPTOS_ECN_ECT1:
1828 TCPSTAT_INC(tcps_ecn_ect1);
1831 /* Congestion experienced. */
1832 if (thflags & TH_ECE) {
1833 cc_cong_signal(tp, th, CC_ECN);
1838 * Parse options on any incoming segment.
1840 tcp_dooptions(&to, (u_char *)(th + 1),
1841 (th->th_off << 2) - sizeof(struct tcphdr),
1842 (thflags & TH_SYN) ? TO_SYN : 0);
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
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()))
1856 * If timestamps were negotiated during SYN/ACK they should
1857 * appear on every segment during this session and vice versa.
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__);
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__);
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.
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;
1888 * Initial send window. It will be updated with
1889 * the next incoming segment to the scaled value.
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();
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;
1904 if (__predict_true((tlen == 0))) {
1906 * The ack moved forward and we have a window (non-zero)
1908 * The ack did not move forward, but the window increased.
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)))) {
1916 * Data incoming, use the old entry criteria
1917 * for fast-path with data.
1919 if ((tiwin && tiwin == tp->snd_wnd)) {
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
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 &&
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)))) {
1955 tcp_do_fastack(m, th, so, tp, &to, drop_hdrlen, tlen,
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,
1967 tcp_do_slowpath(m, th, so, tp, &to, drop_hdrlen, tlen,
1968 ti_locked, tiwin, thflags);
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
1982 tcp_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)
1990 * The size of tcp_saveipgen must be the size of the max ip header,
1993 u_char tcp_saveipgen[IP6_HDR_LEN];
1994 struct tcphdr tcp_savetcp;
1999 if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
2000 /* Old ack, behind (or duplicate to) the last one rcv'd */
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 */
2008 if (__predict_false(tiwin == 0)) {
2012 if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
2013 /* Above what we have sent? */
2016 if (__predict_false(tp->snd_nxt != tp->snd_max)) {
2017 /* We are retransmitting */
2020 if (__predict_false(tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN))) {
2021 /* We need a SYN or a FIN, unlikely.. */
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? */
2028 if (__predict_false(IN_RECOVERY(tp->t_flags))) {
2029 /* Still recovering */
2032 if (__predict_false(to->to_flags & TOF_SACK)) {
2033 /* Sack included in the ack.. */
2036 if (!TAILQ_EMPTY(&tp->snd_holes)) {
2037 /* We have sack holes on our scoreboard */
2040 /* Ok if we reach here, we can process a fast-ack */
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) {
2047 TCPSTAT_INC(tcps_rcvwinupd);
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;
2055 * Pull snd_wl2 up to prevent seq wrap relative
2058 tp->snd_wl2 = th->th_ack;
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).
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;
2071 * This is a pure ack for outstanding data.
2073 if (ti_locked == TI_RLOCKED) {
2074 INP_INFO_RUNLOCK(&V_tcbinfo);
2076 ti_locked = TI_UNLOCKED;
2078 TCPSTAT_INC(tcps_predack);
2081 * "bad retransmit" recovery.
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);
2090 * Recalculate the transmit timer / rtt.
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.
2097 if ((to->to_flags & TOF_TS) != 0 &&
2101 t = tcp_ts_getticks() - to->to_tsecr;
2102 if (!tp->t_rttlow || tp->t_rttlow > t)
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;
2112 ticks - tp->t_rtttime);
2114 if (winup_only == 0) {
2115 acked = BYTES_THIS_ACK(tp, th);
2117 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2118 hhook_run_tcp_est_in(tp, th, to);
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;
2127 * Let the congestion control algorithm update
2128 * congestion control related information. This
2129 * typically means increasing the congestion
2132 cc_ack_received(tp, th, CC_ACK);
2134 tp->snd_una = th->th_ack;
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.
2147 if (so->so_options & SO_DEBUG)
2148 tcp_trace(TA_INPUT, ostate, tp,
2149 (void *)tcp_saveipgen,
2152 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
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,
2159 /* Wake up the socket if we have room to write more */
2163 * Window update only, just free the mbufs and
2164 * send out whatever we can.
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);
2175 if (tp->t_flags & TF_DELACK) {
2176 tp->t_flags &= ~TF_DELACK;
2177 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2179 INP_WUNLOCK(tp->t_inpcb);
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).
2198 tcp_do_segment_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
2199 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
2205 struct in_conninfo *inc;
2208 thflags = th->th_flags;
2209 tp->sackhint.last_sack_ack = 0;
2210 inc = &tp->t_inpcb->inp_inc;
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.
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);
2224 if (ti_locked == TI_RLOCKED) {
2225 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2227 KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST "
2228 "ti_locked: %d", __func__, ti_locked));
2229 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2233 INP_WLOCK_ASSERT(tp->t_inpcb);
2234 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
2236 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
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.
2245 tp->t_rcvtime = ticks;
2246 if (TCPS_HAVEESTABLISHED(tp->t_state))
2247 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2250 * Unscale the window into a 32-bit value.
2251 * For the SYN_SENT state the scale is zero.
2253 tiwin = th->th_win << tp->snd_scale;
2256 * TCP ECN processing.
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) {
2263 tp->t_flags |= TF_ECN_SND_ECE;
2264 TCPSTAT_INC(tcps_ecn_ce);
2266 case IPTOS_ECN_ECT0:
2267 TCPSTAT_INC(tcps_ecn_ect0);
2269 case IPTOS_ECN_ECT1:
2270 TCPSTAT_INC(tcps_ecn_ect1);
2273 /* Congestion experienced. */
2274 if (thflags & TH_ECE) {
2275 cc_cong_signal(tp, th, CC_ECN);
2280 * Parse options on any incoming segment.
2282 tcp_dooptions(&to, (u_char *)(th + 1),
2283 (th->th_off << 2) - sizeof(struct tcphdr),
2284 (thflags & TH_SYN) ? TO_SYN : 0);
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
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()))
2298 * If timestamps were negotiated during SYN/ACK they should
2299 * appear on every segment during this session and vice versa.
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__);
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__);
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.
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;
2330 * Initial send window. It will be updated with
2331 * the next incoming segment to the scaled value.
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();
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;
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
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)) {
2373 tcp_do_slowpath(m, th, so, tp, &to, drop_hdrlen, tlen,
2374 ti_locked, tiwin, thflags);
2377 struct 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,
2384 struct 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
2392 tcp_addfastpaths(module_t mod, int type, void *data)
2398 err = register_tcp_functions(&__tcp_fastack, M_WAITOK);
2400 printf("Failed to register fastack module -- err:%d\n", err);
2403 err = register_tcp_functions(&__tcp_fastslow, M_WAITOK);
2405 printf("Failed to register fastslow module -- err:%d\n", err);
2406 deregister_tcp_functions(&__tcp_fastack);
2411 if ((__tcp_fastslow.tfb_refcnt) ||( __tcp_fastack.tfb_refcnt)) {
2416 err = deregister_tcp_functions(&__tcp_fastack);
2419 err = deregister_tcp_functions(&__tcp_fastslow);
2425 return (EOPNOTSUPP);
2430 static moduledata_t new_tcp_fastpaths = {
2431 .name = "tcp_fastpaths",
2432 .evhand = tcp_addfastpaths,
2436 MODULE_VERSION(kern_tcpfastpaths, 1);
2437 DECLARE_MODULE(kern_tcpfastpaths, new_tcp_fastpaths, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);