2 * Copyright (c) 2002, 2003, 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2002, 2003, 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
36 * The Regents of the University of California. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
63 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
67 #include "opt_inet6.h"
68 #include "opt_ipsec.h"
69 #include "opt_tcpdebug.h"
70 #include "opt_tcp_input.h"
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/kernel.h>
75 #include <sys/sysctl.h>
76 #include <sys/malloc.h>
78 #include <sys/proc.h> /* for proc0 declaration */
79 #include <sys/protosw.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82 #include <sys/syslog.h>
83 #include <sys/in_cksum.h>
85 #include <sys/socketvar2.h>
87 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
88 #include <machine/stdarg.h>
91 #include <net/route.h>
93 #include <netinet/in.h>
94 #include <netinet/in_systm.h>
95 #include <netinet/ip.h>
96 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
97 #include <netinet/in_var.h>
98 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
99 #include <netinet/in_pcb.h>
100 #include <netinet/ip_var.h>
101 #include <netinet/ip6.h>
102 #include <netinet/icmp6.h>
103 #include <netinet6/nd6.h>
104 #include <netinet6/ip6_var.h>
105 #include <netinet6/in6_pcb.h>
106 #include <netinet/tcp.h>
107 #include <netinet/tcp_fsm.h>
108 #include <netinet/tcp_seq.h>
109 #include <netinet/tcp_timer.h>
110 #include <netinet/tcp_timer2.h>
111 #include <netinet/tcp_var.h>
112 #include <netinet6/tcp6_var.h>
113 #include <netinet/tcpip.h>
116 #include <netinet/tcp_debug.h>
118 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
119 struct tcphdr tcp_savetcp;
123 #include <netproto/ipsec/ipsec.h>
124 #include <netproto/ipsec/ipsec6.h>
128 #include <netinet6/ipsec.h>
129 #include <netinet6/ipsec6.h>
130 #include <netproto/key/key.h>
134 * Limit burst of new packets during SACK based fast recovery
135 * or extended limited transmit.
137 #define TCP_SACK_MAXBURST 4
139 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
141 static int log_in_vain = 0;
142 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
143 &log_in_vain, 0, "Log all incoming TCP connections");
145 static int blackhole = 0;
146 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
147 &blackhole, 0, "Do not send RST when dropping refused connections");
149 int tcp_delack_enabled = 1;
150 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
151 &tcp_delack_enabled, 0,
152 "Delay ACK to try and piggyback it onto a data packet");
154 #ifdef TCP_DROP_SYNFIN
155 static int drop_synfin = 0;
156 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
157 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
160 static int tcp_do_limitedtransmit = 1;
161 SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
162 &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
164 static int tcp_do_early_retransmit = 1;
165 SYSCTL_INT(_net_inet_tcp, OID_AUTO, earlyretransmit, CTLFLAG_RW,
166 &tcp_do_early_retransmit, 0, "Early retransmit");
168 int tcp_aggregate_acks = 1;
169 SYSCTL_INT(_net_inet_tcp, OID_AUTO, aggregate_acks, CTLFLAG_RW,
170 &tcp_aggregate_acks, 0, "Aggregate built-up acks into one ack");
172 static int tcp_do_eifel_detect = 1;
173 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
174 &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
176 static int tcp_do_abc = 1;
177 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc, CTLFLAG_RW,
179 "TCP Appropriate Byte Counting (RFC 3465)");
182 * The following value actually takes range [25ms, 250ms],
183 * given that most modern systems use 1ms ~ 10ms as the unit
184 * of timestamp option.
186 static u_int tcp_paws_tolerance = 25;
187 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, paws_tolerance, CTLFLAG_RW,
188 &tcp_paws_tolerance, 0, "RFC1323 PAWS tolerance");
191 * Define as tunable for easy testing with SACK on and off.
192 * Warning: do not change setting in the middle of an existing active TCP flow,
193 * else strange things might happen to that flow.
196 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sack, CTLFLAG_RW,
197 &tcp_do_sack, 0, "Enable SACK Algorithms");
199 int tcp_do_smartsack = 1;
200 SYSCTL_INT(_net_inet_tcp, OID_AUTO, smartsack, CTLFLAG_RW,
201 &tcp_do_smartsack, 0, "Enable Smart SACK Algorithms");
203 int tcp_do_rescuesack = 1;
204 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rescuesack, CTLFLAG_RW,
205 &tcp_do_rescuesack, 0, "Rescue retransmission for SACK");
207 int tcp_aggressive_rescuesack = 0;
208 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rescuesack_agg, CTLFLAG_RW,
209 &tcp_aggressive_rescuesack, 0, "Aggressive rescue retransmission for SACK");
211 static int tcp_force_sackrxt = 1;
212 SYSCTL_INT(_net_inet_tcp, OID_AUTO, force_sackrxt, CTLFLAG_RW,
213 &tcp_force_sackrxt, 0, "Allowed forced SACK retransmit burst");
215 int tcp_do_rfc6675 = 1;
216 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc6675, CTLFLAG_RW,
217 &tcp_do_rfc6675, 0, "Enable RFC6675");
219 int tcp_rfc6675_rxt = 0;
220 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc6675_rxt, CTLFLAG_RW,
221 &tcp_rfc6675_rxt, 0, "Enable RFC6675 retransmit");
223 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
224 "TCP Segment Reassembly Queue");
226 int tcp_reass_maxseg = 0;
227 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
228 &tcp_reass_maxseg, 0,
229 "Global maximum number of TCP Segments in Reassembly Queue");
231 int tcp_reass_qsize = 0;
232 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
234 "Global number of TCP Segments currently in Reassembly Queue");
236 static int tcp_reass_overflows = 0;
237 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
238 &tcp_reass_overflows, 0,
239 "Global number of TCP Segment Reassembly Queue Overflows");
241 int tcp_do_autorcvbuf = 1;
242 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
243 &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
245 int tcp_autorcvbuf_inc = 16*1024;
246 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
247 &tcp_autorcvbuf_inc, 0,
248 "Incrementor step size of automatic receive buffer");
250 int tcp_autorcvbuf_max = 2*1024*1024;
251 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
252 &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
254 int tcp_sosend_agglim = 3;
255 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sosend_agglim, CTLFLAG_RW,
256 &tcp_sosend_agglim, 0, "TCP sosend mbuf aggregation limit");
258 int tcp_sosend_async = 1;
259 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sosend_async, CTLFLAG_RW,
260 &tcp_sosend_async, 0, "TCP asynchronized pru_send");
262 static int tcp_ignore_redun_dsack = 1;
263 SYSCTL_INT(_net_inet_tcp, OID_AUTO, ignore_redun_dsack, CTLFLAG_RW,
264 &tcp_ignore_redun_dsack, 0, "Ignore redundant DSACK");
266 static int tcp_reuseport_ext = 1;
267 SYSCTL_INT(_net_inet_tcp, OID_AUTO, reuseport_ext, CTLFLAG_RW,
268 &tcp_reuseport_ext, 0, "SO_REUSEPORT extension");
270 static void tcp_dooptions(struct tcpopt *, u_char *, int, boolean_t,
272 static void tcp_pulloutofband(struct socket *,
273 struct tcphdr *, struct mbuf *, int);
274 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
276 static void tcp_xmit_timer(struct tcpcb *, int, tcp_seq);
277 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *, int);
278 static void tcp_sack_rexmt(struct tcpcb *, boolean_t);
279 static boolean_t tcp_sack_limitedxmit(struct tcpcb *);
280 static int tcp_rmx_msl(const struct tcpcb *);
281 static void tcp_established(struct tcpcb *);
282 static boolean_t tcp_recv_dupack(struct tcpcb *, tcp_seq, u_int);
284 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
286 #define ND6_HINT(tp) \
288 if ((tp) && (tp)->t_inpcb && \
289 ((tp)->t_inpcb->inp_vflag & INP_IPV6) && \
290 (tp)->t_inpcb->in6p_route.ro_rt) \
291 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
298 * Indicate whether this ack should be delayed. We can delay the ack if
299 * - delayed acks are enabled and
300 * - there is no delayed ack timer in progress and
301 * - our last ack wasn't a 0-sized window. We never want to delay
302 * the ack that opens up a 0-sized window.
304 #define DELAY_ACK(tp) \
305 (tcp_delack_enabled && !tcp_callout_pending(tp, tp->tt_delack) && \
306 !(tp->t_flags & TF_RXWIN0SENT))
308 #define acceptable_window_update(tp, th, tiwin) \
309 (SEQ_LT(tp->snd_wl1, th->th_seq) || \
310 (tp->snd_wl1 == th->th_seq && \
311 (SEQ_LT(tp->snd_wl2, th->th_ack) || \
312 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))
314 #define iceildiv(n, d) (((n)+(d)-1) / (d))
315 #define need_early_retransmit(tp, ownd) \
316 (tcp_do_early_retransmit && \
317 (tcp_do_eifel_detect && (tp->t_flags & TF_RCVD_TSTMP)) && \
318 ownd < ((tp->t_rxtthresh + 1) * tp->t_maxseg) && \
319 tp->t_dupacks + 1 >= iceildiv(ownd, tp->t_maxseg) && \
320 (!TCP_DO_SACK(tp) || ownd <= tp->t_maxseg || \
321 tcp_sack_has_sacked(&tp->scb, ownd - tp->t_maxseg)))
324 * Returns TRUE, if this segment can be merged with the last
325 * pending segment in the reassemble queue and this segment
326 * does not overlap with the pending segment immediately
327 * preceeding the last pending segment.
329 static __inline boolean_t
330 tcp_paws_canreasslast(const struct tcpcb *tp, const struct tcphdr *th, int tlen)
332 const struct tseg_qent *last, *prev;
334 last = TAILQ_LAST(&tp->t_segq, tsegqe_head);
338 /* This segment comes immediately after the last pending segment */
339 if (last->tqe_th->th_seq + last->tqe_len == th->th_seq) {
340 if (last->tqe_th->th_flags & TH_FIN) {
341 /* No segments should follow segment w/ FIN */
347 if (th->th_seq + tlen != last->tqe_th->th_seq)
349 /* This segment comes immediately before the last pending segment */
351 prev = TAILQ_PREV(last, tsegqe_head, tqe_q);
354 * No pending preceeding segment, we assume this segment
355 * could be reassembled.
360 /* This segment does not overlap with the preceeding segment */
361 if (SEQ_GEQ(th->th_seq, prev->tqe_th->th_seq + prev->tqe_len))
368 tcp_ncr_update_rxtthresh(struct tcpcb *tp)
370 int old_rxtthresh = tp->t_rxtthresh;
371 uint32_t ownd = tp->snd_max - tp->snd_una;
373 tp->t_rxtthresh = max(tcprexmtthresh, ((ownd / tp->t_maxseg) >> 1));
374 if (tp->t_rxtthresh != old_rxtthresh) {
375 tcp_sack_update_lostseq(&tp->scb, tp->snd_una,
376 tp->t_maxseg, tp->t_rxtthresh);
381 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
384 struct tseg_qent *p = NULL;
385 struct tseg_qent *te;
386 struct socket *so = tp->t_inpcb->inp_socket;
390 * Call with th == NULL after become established to
391 * force pre-ESTABLISHED data up to user socket.
397 * Limit the number of segments in the reassembly queue to prevent
398 * holding on to too many segments (and thus running out of mbufs).
399 * Make sure to let the missing segment through which caused this
400 * queue. Always keep one global queue entry spare to be able to
401 * process the missing segment.
403 if (th->th_seq != tp->rcv_nxt &&
404 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
405 tcp_reass_overflows++;
406 tcpstat.tcps_rcvmemdrop++;
408 /* no SACK block to report */
409 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
413 /* Allocate a new queue entry. */
414 te = kmalloc(sizeof(struct tseg_qent), M_TSEGQ, M_INTWAIT | M_NULLOK);
416 tcpstat.tcps_rcvmemdrop++;
418 /* no SACK block to report */
419 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
422 atomic_add_int(&tcp_reass_qsize, 1);
424 if (th->th_flags & TH_FIN)
425 tp->t_flags |= TF_QUEDFIN;
428 * Find a segment which begins after this one does.
430 TAILQ_FOREACH(q, &tp->t_segq, tqe_q) {
431 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
437 * If there is a preceding segment, it may provide some of
438 * our data already. If so, drop the data from the incoming
439 * segment. If it provides all of our data, drop us.
444 /* conversion to int (in i) handles seq wraparound */
445 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
446 if (i > 0) { /* overlaps preceding segment */
448 (TSACK_F_DUPSEG | TSACK_F_ENCLOSESEG);
449 /* enclosing block starts w/ preceding segment */
450 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
452 if (th->th_flags & TH_FIN)
453 p->tqe_th->th_flags |= TH_FIN;
455 /* preceding encloses incoming segment */
456 tp->encloseblk.rblk_end = TCP_SACK_BLKEND(
457 p->tqe_th->th_seq + p->tqe_len,
458 p->tqe_th->th_flags);
459 tcpstat.tcps_rcvduppack++;
460 tcpstat.tcps_rcvdupbyte += *tlenp;
463 atomic_add_int(&tcp_reass_qsize, -1);
465 * Try to present any queued data
466 * at the left window edge to the user.
467 * This is needed after the 3-WHS
470 goto present; /* ??? */
475 /* incoming segment end is enclosing block end */
476 tp->encloseblk.rblk_end = TCP_SACK_BLKEND(
477 th->th_seq + *tlenp, th->th_flags);
478 /* trim end of reported D-SACK block */
479 tp->reportblk.rblk_end = th->th_seq;
482 tcpstat.tcps_rcvoopack++;
483 tcpstat.tcps_rcvoobyte += *tlenp;
486 * While we overlap succeeding segments trim them or,
487 * if they are completely covered, dequeue them.
490 tcp_seq_diff_t i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
491 tcp_seq qend = q->tqe_th->th_seq + q->tqe_len;
492 tcp_seq qend_sack = TCP_SACK_BLKEND(qend, q->tqe_th->th_flags);
493 struct tseg_qent *nq;
497 if (!(tp->sack_flags & TSACK_F_DUPSEG)) {
498 /* first time through */
499 tp->sack_flags |= (TSACK_F_DUPSEG | TSACK_F_ENCLOSESEG);
500 tp->encloseblk = tp->reportblk;
501 /* report trailing duplicate D-SACK segment */
502 tp->reportblk.rblk_start = q->tqe_th->th_seq;
504 if ((tp->sack_flags & TSACK_F_ENCLOSESEG) &&
505 SEQ_GT(qend_sack, tp->encloseblk.rblk_end)) {
506 /* extend enclosing block if one exists */
507 tp->encloseblk.rblk_end = qend_sack;
509 if (i < q->tqe_len) {
510 q->tqe_th->th_seq += i;
516 if (q->tqe_th->th_flags & TH_FIN)
517 th->th_flags |= TH_FIN;
519 nq = TAILQ_NEXT(q, tqe_q);
520 TAILQ_REMOVE(&tp->t_segq, q, tqe_q);
523 atomic_add_int(&tcp_reass_qsize, -1);
527 /* Insert the new segment queue entry into place. */
530 te->tqe_len = *tlenp;
532 /* check if can coalesce with following segment */
533 if (q != NULL && (th->th_seq + *tlenp == q->tqe_th->th_seq)) {
536 te->tqe_len += q->tqe_len;
537 if (q->tqe_th->th_flags & TH_FIN)
538 te->tqe_th->th_flags |= TH_FIN;
539 tend_sack = TCP_SACK_BLKEND(te->tqe_th->th_seq + te->tqe_len,
540 te->tqe_th->th_flags);
542 m_cat(te->tqe_m, q->tqe_m);
543 tp->encloseblk.rblk_end = tend_sack;
545 * When not reporting a duplicate segment, use
546 * the larger enclosing block as the SACK block.
548 if (!(tp->sack_flags & TSACK_F_DUPSEG))
549 tp->reportblk.rblk_end = tend_sack;
550 TAILQ_REMOVE(&tp->t_segq, q, tqe_q);
552 atomic_add_int(&tcp_reass_qsize, -1);
556 TAILQ_INSERT_HEAD(&tp->t_segq, te, tqe_q);
558 /* check if can coalesce with preceding segment */
559 if (p->tqe_th->th_seq + p->tqe_len == th->th_seq) {
560 if (te->tqe_th->th_flags & TH_FIN)
561 p->tqe_th->th_flags |= TH_FIN;
562 p->tqe_len += te->tqe_len;
563 m_cat(p->tqe_m, te->tqe_m);
564 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
566 * When not reporting a duplicate segment, use
567 * the larger enclosing block as the SACK block.
569 if (!(tp->sack_flags & TSACK_F_DUPSEG))
570 tp->reportblk.rblk_start = p->tqe_th->th_seq;
572 atomic_add_int(&tcp_reass_qsize, -1);
574 TAILQ_INSERT_AFTER(&tp->t_segq, p, te, tqe_q);
580 * Present data to user, advancing rcv_nxt through
581 * completed sequence space.
583 if (!TCPS_HAVEESTABLISHED(tp->t_state))
585 q = TAILQ_FIRST(&tp->t_segq);
586 if (q == NULL || q->tqe_th->th_seq != tp->rcv_nxt)
588 tp->rcv_nxt += q->tqe_len;
589 if (!(tp->sack_flags & TSACK_F_DUPSEG)) {
590 /* no SACK block to report since ACK advanced */
591 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
593 /* no enclosing block to report since ACK advanced */
594 tp->sack_flags &= ~TSACK_F_ENCLOSESEG;
595 flags = q->tqe_th->th_flags & TH_FIN;
596 TAILQ_REMOVE(&tp->t_segq, q, tqe_q);
597 KASSERT(TAILQ_EMPTY(&tp->t_segq) ||
598 TAILQ_FIRST(&tp->t_segq)->tqe_th->th_seq != tp->rcv_nxt,
599 ("segment not coalesced"));
600 if (so->so_state & SS_CANTRCVMORE) {
603 lwkt_gettoken(&so->so_rcv.ssb_token);
604 ssb_appendstream(&so->so_rcv, q->tqe_m);
605 lwkt_reltoken(&so->so_rcv.ssb_token);
608 atomic_add_int(&tcp_reass_qsize, -1);
615 * TCP input routine, follows pages 65-76 of the
616 * protocol specification dated September, 1981 very closely.
620 tcp6_input(struct mbuf **mp, int *offp, int proto)
622 struct mbuf *m = *mp;
623 struct in6_ifaddr *ia6;
625 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
628 * draft-itojun-ipv6-tcp-to-anycast
629 * better place to put this in?
631 ia6 = ip6_getdstifaddr(m);
632 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
633 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
634 offsetof(struct ip6_hdr, ip6_dst));
635 return (IPPROTO_DONE);
638 tcp_input(mp, offp, proto);
639 return (IPPROTO_DONE);
644 tcp_input(struct mbuf **mp, int *offp, int proto)
648 struct ip *ip = NULL;
650 struct inpcb *inp = NULL;
656 struct tcpcb *tp = NULL;
658 struct socket *so = NULL;
660 boolean_t ourfinisacked, needoutput = FALSE, delayed_dupack = FALSE;
661 tcp_seq th_dupack = 0; /* XXX gcc warning */
662 u_int to_flags = 0; /* XXX gcc warning */
665 struct tcpopt to; /* options in this segment */
666 struct sockaddr_in *next_hop = NULL;
667 int rstreason; /* For badport_bandlim accounting purposes */
669 struct ip6_hdr *ip6 = NULL;
674 const boolean_t isipv6 = FALSE;
684 tcpstat.tcps_rcvtotal++;
686 if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
689 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
690 KKASSERT(mtag != NULL);
691 next_hop = m_tag_data(mtag);
695 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
699 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
700 ip6 = mtod(m, struct ip6_hdr *);
701 tlen = (sizeof *ip6) + ntohs(ip6->ip6_plen) - off0;
702 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
703 tcpstat.tcps_rcvbadsum++;
706 th = (struct tcphdr *)((caddr_t)ip6 + off0);
709 * Be proactive about unspecified IPv6 address in source.
710 * As we use all-zero to indicate unbounded/unconnected pcb,
711 * unspecified IPv6 address can be used to confuse us.
713 * Note that packets with unspecified IPv6 destination is
714 * already dropped in ip6_input.
716 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
722 * Get IP and TCP header together in first mbuf.
723 * Note: IP leaves IP header in first mbuf.
725 if (off0 > sizeof(struct ip)) {
727 off0 = sizeof(struct ip);
729 /* already checked and pulled up in ip_demux() */
730 KASSERT(m->m_len >= sizeof(struct tcpiphdr),
731 ("TCP header not in one mbuf: m->m_len %d", m->m_len));
732 ip = mtod(m, struct ip *);
733 ipov = (struct ipovly *)ip;
734 th = (struct tcphdr *)((caddr_t)ip + off0);
737 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
738 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
739 th->th_sum = m->m_pkthdr.csum_data;
741 th->th_sum = in_pseudo(ip->ip_src.s_addr,
743 htonl(m->m_pkthdr.csum_data +
746 th->th_sum ^= 0xffff;
749 * Checksum extended TCP header and data.
751 len = sizeof(struct ip) + tlen;
752 bzero(ipov->ih_x1, sizeof ipov->ih_x1);
753 ipov->ih_len = (u_short)tlen;
754 ipov->ih_len = htons(ipov->ih_len);
755 th->th_sum = in_cksum(m, len);
758 tcpstat.tcps_rcvbadsum++;
762 /* Re-initialization for later version check */
763 ip->ip_v = IPVERSION;
768 * Check that TCP offset makes sense,
769 * pull out TCP options and adjust length. XXX
771 off = th->th_off << 2;
772 /* already checked and pulled up in ip_demux() */
773 KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
774 ("bad TCP data offset %d (tlen %d)", off, tlen));
775 tlen -= off; /* tlen is used instead of ti->ti_len */
776 if (off > sizeof(struct tcphdr)) {
778 IP6_EXTHDR_CHECK(m, off0, off, IPPROTO_DONE);
779 ip6 = mtod(m, struct ip6_hdr *);
780 th = (struct tcphdr *)((caddr_t)ip6 + off0);
782 /* already pulled up in ip_demux() */
783 KASSERT(m->m_len >= sizeof(struct ip) + off,
784 ("TCP header and options not in one mbuf: "
785 "m_len %d, off %d", m->m_len, off));
787 optlen = off - sizeof(struct tcphdr);
788 optp = (u_char *)(th + 1);
790 thflags = th->th_flags;
792 #ifdef TCP_DROP_SYNFIN
794 * If the drop_synfin option is enabled, drop all packets with
795 * both the SYN and FIN bits set. This prevents e.g. nmap from
796 * identifying the TCP/IP stack.
798 * This is a violation of the TCP specification.
800 if (drop_synfin && (thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN))
805 * Convert TCP protocol specific fields to host format.
807 th->th_seq = ntohl(th->th_seq);
808 th->th_ack = ntohl(th->th_ack);
809 th->th_win = ntohs(th->th_win);
810 th->th_urp = ntohs(th->th_urp);
813 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
814 * until after ip6_savecontrol() is called and before other functions
815 * which don't want those proto headers.
816 * Because ip6_savecontrol() is going to parse the mbuf to
817 * search for data to be passed up to user-land, it wants mbuf
818 * parameters to be unchanged.
819 * XXX: the call of ip6_savecontrol() has been obsoleted based on
820 * latest version of the advanced API (20020110).
822 drop_hdrlen = off0 + off;
825 * Locate pcb for segment.
828 /* IPFIREWALL_FORWARD section */
829 if (next_hop != NULL && !isipv6) { /* IPv6 support is not there yet */
831 * Transparently forwarded. Pretend to be the destination.
832 * already got one like this?
834 cpu = mycpu->gd_cpuid;
835 inp = in_pcblookup_hash(&tcbinfo[cpu],
836 ip->ip_src, th->th_sport,
837 ip->ip_dst, th->th_dport,
838 0, m->m_pkthdr.rcvif);
841 * It's new. Try to find the ambushing socket.
845 * The rest of the ipfw code stores the port in
847 * (The IP address is still in network order.)
849 in_port_t dport = next_hop->sin_port ?
850 htons(next_hop->sin_port) :
853 cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
854 next_hop->sin_addr.s_addr, dport);
855 inp = in_pcblookup_hash(&tcbinfo[cpu],
856 ip->ip_src, th->th_sport,
857 next_hop->sin_addr, dport,
858 1, m->m_pkthdr.rcvif);
862 inp = in6_pcblookup_hash(&tcbinfo[0],
863 &ip6->ip6_src, th->th_sport,
864 &ip6->ip6_dst, th->th_dport,
865 1, m->m_pkthdr.rcvif);
867 cpu = mycpu->gd_cpuid;
868 inp = in_pcblookup_pkthash(&tcbinfo[cpu],
869 ip->ip_src, th->th_sport,
870 ip->ip_dst, th->th_dport,
871 1, m->m_pkthdr.rcvif,
872 tcp_reuseport_ext ? m : NULL);
877 * If the state is CLOSED (i.e., TCB does not exist) then
878 * all data in the incoming segment is discarded.
879 * If the TCB exists but is in CLOSED state, it is embryonic,
880 * but should either do a listen or a connect soon.
885 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
887 char dbuf[sizeof "aaa.bbb.ccc.ddd"];
888 char sbuf[sizeof "aaa.bbb.ccc.ddd"];
892 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
895 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
898 strcpy(dbuf, inet_ntoa(ip->ip_dst));
899 strcpy(sbuf, inet_ntoa(ip->ip_src));
901 switch (log_in_vain) {
903 if (!(thflags & TH_SYN))
907 "Connection attempt to TCP %s:%d "
908 "from %s:%d flags:0x%02x\n",
909 dbuf, ntohs(th->th_dport), sbuf,
910 ntohs(th->th_sport), thflags);
919 if (thflags & TH_SYN)
928 rstreason = BANDLIM_RST_CLOSEDPORT;
934 if (ipsec6_in_reject_so(m, inp->inp_socket)) {
935 ipsec6stat.in_polvio++;
939 if (ipsec4_in_reject_so(m, inp->inp_socket)) {
940 ipsecstat.in_polvio++;
947 if (ipsec6_in_reject(m, inp))
950 if (ipsec4_in_reject(m, inp))
954 /* Check the minimum TTL for socket. */
956 if ((isipv6 ? ip6->ip6_hlim : ip->ip_ttl) < inp->inp_ip_minttl)
962 rstreason = BANDLIM_RST_CLOSEDPORT;
965 if (tp->t_state <= TCPS_CLOSED)
968 so = inp->inp_socket;
971 if (so->so_options & SO_DEBUG) {
972 ostate = tp->t_state;
974 bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
976 bcopy(ip, tcp_saveipgen, sizeof(*ip));
981 bzero(&to, sizeof to);
983 if (so->so_options & SO_ACCEPTCONN) {
984 struct in_conninfo inc;
987 inc.inc_isipv6 = (isipv6 == TRUE);
990 inc.inc6_faddr = ip6->ip6_src;
991 inc.inc6_laddr = ip6->ip6_dst;
992 inc.inc6_route.ro_rt = NULL; /* XXX */
994 inc.inc_faddr = ip->ip_src;
995 inc.inc_laddr = ip->ip_dst;
996 inc.inc_route.ro_rt = NULL; /* XXX */
998 inc.inc_fport = th->th_sport;
999 inc.inc_lport = th->th_dport;
1002 * If the state is LISTEN then ignore segment if it contains
1003 * a RST. If the segment contains an ACK then it is bad and
1004 * send a RST. If it does not contain a SYN then it is not
1005 * interesting; drop it.
1007 * If the state is SYN_RECEIVED (syncache) and seg contains
1008 * an ACK, but not for our SYN/ACK, send a RST. If the seg
1009 * contains a RST, check the sequence number to see if it
1010 * is a valid reset segment.
1012 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
1013 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) == TH_ACK) {
1014 if (!syncache_expand(&inc, th, &so, m)) {
1016 * No syncache entry, or ACK was not
1017 * for our SYN/ACK. Send a RST.
1019 tcpstat.tcps_badsyn++;
1020 rstreason = BANDLIM_RST_OPENPORT;
1025 * Could not complete 3-way handshake,
1026 * connection is being closed down, and
1027 * syncache will free mbuf.
1030 return(IPPROTO_DONE);
1033 * We must be in the correct protocol thread
1034 * for this connection.
1036 KKASSERT(so->so_port == &curthread->td_msgport);
1039 * Socket is created in state SYN_RECEIVED.
1040 * Continue processing segment.
1043 tp = intotcpcb(inp);
1045 * This is what would have happened in
1046 * tcp_output() when the SYN,ACK was sent.
1048 tp->snd_up = tp->snd_una;
1049 tp->snd_max = tp->snd_nxt = tp->iss + 1;
1050 tp->last_ack_sent = tp->rcv_nxt;
1054 if (thflags & TH_RST) {
1055 syncache_chkrst(&inc, th);
1058 if (thflags & TH_ACK) {
1059 syncache_badack(&inc);
1060 tcpstat.tcps_badsyn++;
1061 rstreason = BANDLIM_RST_OPENPORT;
1068 * Segment's flags are (SYN) or (SYN | FIN).
1072 * If deprecated address is forbidden,
1073 * we do not accept SYN to deprecated interface
1074 * address to prevent any new inbound connection from
1075 * getting established.
1076 * When we do not accept SYN, we send a TCP RST,
1077 * with deprecated source address (instead of dropping
1078 * it). We compromise it as it is much better for peer
1079 * to send a RST, and RST will be the final packet
1082 * If we do not forbid deprecated addresses, we accept
1083 * the SYN packet. RFC2462 does not suggest dropping
1085 * If we decipher RFC2462 5.5.4, it says like this:
1086 * 1. use of deprecated addr with existing
1087 * communication is okay - "SHOULD continue to be
1089 * 2. use of it with new communication:
1090 * (2a) "SHOULD NOT be used if alternate address
1091 * with sufficient scope is available"
1092 * (2b) nothing mentioned otherwise.
1093 * Here we fall into (2b) case as we have no choice in
1094 * our source address selection - we must obey the peer.
1096 * The wording in RFC2462 is confusing, and there are
1097 * multiple description text for deprecated address
1098 * handling - worse, they are not exactly the same.
1099 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1101 if (isipv6 && !ip6_use_deprecated) {
1102 struct in6_ifaddr *ia6;
1104 if ((ia6 = ip6_getdstifaddr(m)) &&
1105 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1107 rstreason = BANDLIM_RST_OPENPORT;
1113 * If it is from this socket, drop it, it must be forged.
1114 * Don't bother responding if the destination was a broadcast.
1116 if (th->th_dport == th->th_sport) {
1118 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
1122 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
1127 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1129 * Note that it is quite possible to receive unicast
1130 * link-layer packets with a broadcast IP address. Use
1131 * in_broadcast() to find them.
1133 if (m->m_flags & (M_BCAST | M_MCAST))
1136 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1137 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
1140 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1141 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1142 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1143 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1147 * SYN appears to be valid; create compressed TCP state
1148 * for syncache, or perform t/tcp connection.
1150 if (so->so_qlen <= so->so_qlimit) {
1151 tcp_dooptions(&to, optp, optlen, TRUE, th->th_ack);
1152 if (!syncache_add(&inc, &to, th, so, m))
1156 * Entry added to syncache, mbuf used to
1157 * send SYN,ACK packet.
1159 return(IPPROTO_DONE);
1166 * Should not happen - syncache should pick up these connections.
1168 * Once we are past handling listen sockets we must be in the
1169 * correct protocol processing thread.
1171 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN state"));
1172 KKASSERT(so->so_port == &curthread->td_msgport);
1174 /* Unscale the window into a 32-bit value. */
1175 if (!(thflags & TH_SYN))
1176 tiwin = th->th_win << tp->snd_scale;
1181 * This is the second part of the MSS DoS prevention code (after
1182 * minmss on the sending side) and it deals with too many too small
1183 * tcp packets in a too short timeframe (1 second).
1185 * XXX Removed. This code was crap. It does not scale to network
1186 * speed, and default values break NFS. Gone.
1191 * Segment received on connection.
1193 * Reset idle time and keep-alive timer. Don't waste time if less
1194 * then a second has elapsed.
1196 if ((int)(ticks - tp->t_rcvtime) > hz)
1197 tcp_timer_keep_activity(tp, thflags);
1201 * XXX this is tradtitional behavior, may need to be cleaned up.
1203 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0, th->th_ack);
1204 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1205 if ((to.to_flags & TOF_SCALE) && (tp->t_flags & TF_REQ_SCALE)) {
1206 tp->t_flags |= TF_RCVD_SCALE;
1207 tp->snd_scale = to.to_requested_s_scale;
1211 * Initial send window; will be updated upon next ACK
1213 tp->snd_wnd = th->th_win;
1215 if (to.to_flags & TOF_TS) {
1216 tp->t_flags |= TF_RCVD_TSTMP;
1217 tp->ts_recent = to.to_tsval;
1218 tp->ts_recent_age = ticks;
1220 if (!(to.to_flags & TOF_MSS))
1222 tcp_mss(tp, to.to_mss);
1224 * Only set the TF_SACK_PERMITTED per-connection flag
1225 * if we got a SACK_PERMITTED option from the other side
1226 * and the global tcp_do_sack variable is true.
1228 if (tcp_do_sack && (to.to_flags & TOF_SACK_PERMITTED))
1229 tp->t_flags |= TF_SACK_PERMITTED;
1233 * Header prediction: check for the two common cases
1234 * of a uni-directional data xfer. If the packet has
1235 * no control flags, is in-sequence, the window didn't
1236 * change and we're not retransmitting, it's a
1237 * candidate. If the length is zero and the ack moved
1238 * forward, we're the sender side of the xfer. Just
1239 * free the data acked & wake any higher level process
1240 * that was blocked waiting for space. If the length
1241 * is non-zero and the ack didn't move, we're the
1242 * receiver side. If we're getting packets in-order
1243 * (the reassembly queue is empty), add the data to
1244 * the socket buffer and note that we need a delayed ack.
1245 * Make sure that the hidden state-flags are also off.
1246 * Since we check for TCPS_ESTABLISHED above, it can only
1249 if (tp->t_state == TCPS_ESTABLISHED &&
1250 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1251 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1252 (!(to.to_flags & TOF_TS) ||
1253 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1254 th->th_seq == tp->rcv_nxt &&
1255 tp->snd_nxt == tp->snd_max) {
1258 * If last ACK falls within this segment's sequence numbers,
1259 * record the timestamp.
1260 * NOTE that the test is modified according to the latest
1261 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1263 if ((to.to_flags & TOF_TS) &&
1264 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1265 tp->ts_recent_age = ticks;
1266 tp->ts_recent = to.to_tsval;
1270 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1271 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1272 tp->snd_cwnd >= tp->snd_wnd &&
1273 !IN_FASTRECOVERY(tp)) {
1275 * This is a pure ack for outstanding data.
1277 ++tcpstat.tcps_predack;
1279 * "bad retransmit" recovery
1281 * If Eifel detection applies, then
1282 * it is deterministic, so use it
1283 * unconditionally over the old heuristic.
1284 * Otherwise, fall back to the old heuristic.
1286 if (tcp_do_eifel_detect &&
1287 (to.to_flags & TOF_TS) && to.to_tsecr &&
1288 (tp->rxt_flags & TRXT_F_FIRSTACCACK)) {
1289 /* Eifel detection applicable. */
1290 if (to.to_tsecr < tp->t_rexmtTS) {
1291 tcp_revert_congestion_state(tp);
1292 ++tcpstat.tcps_eifeldetected;
1293 if (tp->t_rxtshift != 1 ||
1294 ticks >= tp->t_badrxtwin)
1295 ++tcpstat.tcps_rttcantdetect;
1297 } else if (tp->t_rxtshift == 1 &&
1298 ticks < tp->t_badrxtwin) {
1299 tcp_revert_congestion_state(tp);
1300 ++tcpstat.tcps_rttdetected;
1302 tp->rxt_flags &= ~(TRXT_F_FIRSTACCACK |
1303 TRXT_F_FASTREXMT | TRXT_F_EARLYREXMT);
1305 * Recalculate the retransmit timer / rtt.
1307 * Some machines (certain windows boxes)
1308 * send broken timestamp replies during the
1309 * SYN+ACK phase, ignore timestamps of 0.
1311 if ((to.to_flags & TOF_TS) && to.to_tsecr) {
1313 ticks - to.to_tsecr + 1,
1315 } else if (tp->t_rtttime &&
1316 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1318 ticks - tp->t_rtttime,
1321 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1322 acked = th->th_ack - tp->snd_una;
1323 tcpstat.tcps_rcvackpack++;
1324 tcpstat.tcps_rcvackbyte += acked;
1325 sbdrop(&so->so_snd.sb, acked);
1326 tp->snd_recover = th->th_ack - 1;
1327 tp->snd_una = th->th_ack;
1330 * Update window information.
1332 if (tiwin != tp->snd_wnd &&
1333 acceptable_window_update(tp, th, tiwin)) {
1334 /* keep track of pure window updates */
1335 if (tp->snd_wl2 == th->th_ack &&
1336 tiwin > tp->snd_wnd)
1337 tcpstat.tcps_rcvwinupd++;
1338 tp->snd_wnd = tiwin;
1339 tp->snd_wl1 = th->th_seq;
1340 tp->snd_wl2 = th->th_ack;
1341 if (tp->snd_wnd > tp->max_sndwnd)
1342 tp->max_sndwnd = tp->snd_wnd;
1345 ND6_HINT(tp); /* some progress has been done */
1347 * If all outstanding data are acked, stop
1348 * retransmit timer, otherwise restart timer
1349 * using current (possibly backed-off) value.
1350 * If process is waiting for space,
1351 * wakeup/selwakeup/signal. If data
1352 * are ready to send, let tcp_output
1353 * decide between more output or persist.
1355 if (tp->snd_una == tp->snd_max) {
1356 tcp_callout_stop(tp, tp->tt_rexmt);
1357 } else if (!tcp_callout_active(tp,
1359 tcp_callout_reset(tp, tp->tt_rexmt,
1360 tp->t_rxtcur, tcp_timer_rexmt);
1363 if (so->so_snd.ssb_cc > 0 &&
1364 !tcp_output_pending(tp))
1365 tcp_output_fair(tp);
1366 return(IPPROTO_DONE);
1368 } else if (tiwin == tp->snd_wnd &&
1369 th->th_ack == tp->snd_una &&
1370 TAILQ_EMPTY(&tp->t_segq) &&
1371 tlen <= ssb_space(&so->so_rcv)) {
1372 u_long newsize = 0; /* automatic sockbuf scaling */
1374 * This is a pure, in-sequence data packet
1375 * with nothing on the reassembly queue and
1376 * we have enough buffer space to take it.
1378 ++tcpstat.tcps_preddat;
1379 tp->rcv_nxt += tlen;
1380 tcpstat.tcps_rcvpack++;
1381 tcpstat.tcps_rcvbyte += tlen;
1382 ND6_HINT(tp); /* some progress has been done */
1384 * Automatic sizing of receive socket buffer. Often the send
1385 * buffer size is not optimally adjusted to the actual network
1386 * conditions at hand (delay bandwidth product). Setting the
1387 * buffer size too small limits throughput on links with high
1388 * bandwidth and high delay (eg. trans-continental/oceanic links).
1390 * On the receive side the socket buffer memory is only rarely
1391 * used to any significant extent. This allows us to be much
1392 * more aggressive in scaling the receive socket buffer. For
1393 * the case that the buffer space is actually used to a large
1394 * extent and we run out of kernel memory we can simply drop
1395 * the new segments; TCP on the sender will just retransmit it
1396 * later. Setting the buffer size too big may only consume too
1397 * much kernel memory if the application doesn't read() from
1398 * the socket or packet loss or reordering makes use of the
1401 * The criteria to step up the receive buffer one notch are:
1402 * 1. the number of bytes received during the time it takes
1403 * one timestamp to be reflected back to us (the RTT);
1404 * 2. received bytes per RTT is within seven eighth of the
1405 * current socket buffer size;
1406 * 3. receive buffer size has not hit maximal automatic size;
1408 * This algorithm does one step per RTT at most and only if
1409 * we receive a bulk stream w/o packet losses or reorderings.
1410 * Shrinking the buffer during idle times is not necessary as
1411 * it doesn't consume any memory when idle.
1413 * TODO: Only step up if the application is actually serving
1414 * the buffer to better manage the socket buffer resources.
1416 if (tcp_do_autorcvbuf &&
1418 (so->so_rcv.ssb_flags & SSB_AUTOSIZE)) {
1419 if (to.to_tsecr > tp->rfbuf_ts &&
1420 to.to_tsecr - tp->rfbuf_ts < hz) {
1422 (so->so_rcv.ssb_hiwat / 8 * 7) &&
1423 so->so_rcv.ssb_hiwat <
1424 tcp_autorcvbuf_max) {
1426 ulmin(so->so_rcv.ssb_hiwat +
1428 tcp_autorcvbuf_max);
1430 /* Start over with next RTT. */
1434 tp->rfbuf_cnt += tlen; /* add up */
1437 * Add data to socket buffer.
1439 if (so->so_state & SS_CANTRCVMORE) {
1443 * Set new socket buffer size, give up when
1446 * Adjusting the size can mess up ACK
1447 * sequencing when pure window updates are
1448 * being avoided (which is the default),
1451 lwkt_gettoken(&so->so_rcv.ssb_token);
1453 tp->t_flags |= TF_RXRESIZED;
1454 if (!ssb_reserve(&so->so_rcv, newsize,
1456 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1459 (TCP_MAXWIN << tp->rcv_scale)) {
1460 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1463 m_adj(m, drop_hdrlen); /* delayed header drop */
1464 ssb_appendstream(&so->so_rcv, m);
1465 lwkt_reltoken(&so->so_rcv.ssb_token);
1469 * This code is responsible for most of the ACKs
1470 * the TCP stack sends back after receiving a data
1471 * packet. Note that the DELAY_ACK check fails if
1472 * the delack timer is already running, which results
1473 * in an ack being sent every other packet (which is
1476 * We then further aggregate acks by not actually
1477 * sending one until the protocol thread has completed
1478 * processing the current backlog of packets. This
1479 * does not delay the ack any further, but allows us
1480 * to take advantage of the packet aggregation that
1481 * high speed NICs do (usually blocks of 8-10 packets)
1482 * to send a single ack rather then four or five acks,
1483 * greatly reducing the ack rate, the return channel
1484 * bandwidth, and the protocol overhead on both ends.
1486 * Since this also has the effect of slowing down
1487 * the exponential slow-start ramp-up, systems with
1488 * very large bandwidth-delay products might want
1489 * to turn the feature off.
1491 if (DELAY_ACK(tp)) {
1492 tcp_callout_reset(tp, tp->tt_delack,
1493 tcp_delacktime, tcp_timer_delack);
1494 } else if (tcp_aggregate_acks) {
1495 tp->t_flags |= TF_ACKNOW;
1496 if (!(tp->t_flags & TF_ONOUTPUTQ)) {
1497 tp->t_flags |= TF_ONOUTPUTQ;
1498 tp->tt_cpu = mycpu->gd_cpuid;
1500 &tcpcbackq[tp->tt_cpu],
1504 tp->t_flags |= TF_ACKNOW;
1507 return(IPPROTO_DONE);
1512 * Calculate amount of space in receive window,
1513 * and then do TCP input processing.
1514 * Receive window is amount of space in rcv queue,
1515 * but not less than advertised window.
1517 recvwin = ssb_space(&so->so_rcv);
1520 tp->rcv_wnd = imax(recvwin, (int)(tp->rcv_adv - tp->rcv_nxt));
1522 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1526 switch (tp->t_state) {
1528 * If the state is SYN_RECEIVED:
1529 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1531 case TCPS_SYN_RECEIVED:
1532 if ((thflags & TH_ACK) &&
1533 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1534 SEQ_GT(th->th_ack, tp->snd_max))) {
1535 rstreason = BANDLIM_RST_OPENPORT;
1541 * If the state is SYN_SENT:
1542 * if seg contains an ACK, but not for our SYN, drop the input.
1543 * if seg contains a RST, then drop the connection.
1544 * if seg does not contain SYN, then drop it.
1545 * Otherwise this is an acceptable SYN segment
1546 * initialize tp->rcv_nxt and tp->irs
1547 * if seg contains ack then advance tp->snd_una
1548 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1549 * arrange for segment to be acked (eventually)
1550 * continue processing rest of data/controls, beginning with URG
1553 if ((thflags & TH_ACK) &&
1554 (SEQ_LEQ(th->th_ack, tp->iss) ||
1555 SEQ_GT(th->th_ack, tp->snd_max))) {
1556 rstreason = BANDLIM_UNLIMITED;
1559 if (thflags & TH_RST) {
1560 if (thflags & TH_ACK)
1561 tp = tcp_drop(tp, ECONNREFUSED);
1564 if (!(thflags & TH_SYN))
1567 tp->irs = th->th_seq;
1569 if (thflags & TH_ACK) {
1570 /* Our SYN was acked. */
1571 tcpstat.tcps_connects++;
1573 /* Do window scaling on this connection? */
1574 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1575 (TF_RCVD_SCALE | TF_REQ_SCALE))
1576 tp->rcv_scale = tp->request_r_scale;
1577 tp->rcv_adv += tp->rcv_wnd;
1578 tp->snd_una++; /* SYN is acked */
1579 tcp_callout_stop(tp, tp->tt_rexmt);
1581 * If there's data, delay ACK; if there's also a FIN
1582 * ACKNOW will be turned on later.
1584 if (DELAY_ACK(tp) && tlen != 0) {
1585 tcp_callout_reset(tp, tp->tt_delack,
1586 tcp_delacktime, tcp_timer_delack);
1588 tp->t_flags |= TF_ACKNOW;
1591 * Received <SYN,ACK> in SYN_SENT[*] state.
1593 * SYN_SENT --> ESTABLISHED
1594 * SYN_SENT* --> FIN_WAIT_1
1596 tp->t_starttime = ticks;
1597 if (tp->t_flags & TF_NEEDFIN) {
1598 tp->t_state = TCPS_FIN_WAIT_1;
1599 tp->t_flags &= ~TF_NEEDFIN;
1602 tcp_established(tp);
1606 * Received initial SYN in SYN-SENT[*] state =>
1607 * simultaneous open.
1608 * Do 3-way handshake:
1609 * SYN-SENT -> SYN-RECEIVED
1610 * SYN-SENT* -> SYN-RECEIVED*
1612 tp->t_flags |= TF_ACKNOW;
1613 tcp_callout_stop(tp, tp->tt_rexmt);
1614 tp->t_state = TCPS_SYN_RECEIVED;
1618 * Advance th->th_seq to correspond to first data byte.
1619 * If data, trim to stay within window,
1620 * dropping FIN if necessary.
1623 if (tlen > tp->rcv_wnd) {
1624 todrop = tlen - tp->rcv_wnd;
1628 tcpstat.tcps_rcvpackafterwin++;
1629 tcpstat.tcps_rcvbyteafterwin += todrop;
1631 tp->snd_wl1 = th->th_seq - 1;
1632 tp->rcv_up = th->th_seq;
1634 * Client side of transaction: already sent SYN and data.
1635 * If the remote host used T/TCP to validate the SYN,
1636 * our data will be ACK'd; if so, enter normal data segment
1637 * processing in the middle of step 5, ack processing.
1638 * Otherwise, goto step 6.
1640 if (thflags & TH_ACK)
1646 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1647 * do normal processing (we no longer bother with T/TCP).
1651 case TCPS_TIME_WAIT:
1652 break; /* continue normal processing */
1656 * States other than LISTEN or SYN_SENT.
1657 * First check the RST flag and sequence number since reset segments
1658 * are exempt from the timestamp and connection count tests. This
1659 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1660 * below which allowed reset segments in half the sequence space
1661 * to fall though and be processed (which gives forged reset
1662 * segments with a random sequence number a 50 percent chance of
1663 * killing a connection).
1664 * Then check timestamp, if present.
1665 * Then check the connection count, if present.
1666 * Then check that at least some bytes of segment are within
1667 * receive window. If segment begins before rcv_nxt,
1668 * drop leading data (and SYN); if nothing left, just ack.
1671 * If the RST bit is set, check the sequence number to see
1672 * if this is a valid reset segment.
1674 * In all states except SYN-SENT, all reset (RST) segments
1675 * are validated by checking their SEQ-fields. A reset is
1676 * valid if its sequence number is in the window.
1677 * Note: this does not take into account delayed ACKs, so
1678 * we should test against last_ack_sent instead of rcv_nxt.
1679 * The sequence number in the reset segment is normally an
1680 * echo of our outgoing acknowledgement numbers, but some hosts
1681 * send a reset with the sequence number at the rightmost edge
1682 * of our receive window, and we have to handle this case.
1683 * If we have multiple segments in flight, the intial reset
1684 * segment sequence numbers will be to the left of last_ack_sent,
1685 * but they will eventually catch up.
1686 * In any case, it never made sense to trim reset segments to
1687 * fit the receive window since RFC 1122 says:
1688 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1690 * A TCP SHOULD allow a received RST segment to include data.
1693 * It has been suggested that a RST segment could contain
1694 * ASCII text that encoded and explained the cause of the
1695 * RST. No standard has yet been established for such
1698 * If the reset segment passes the sequence number test examine
1700 * SYN_RECEIVED STATE:
1701 * If passive open, return to LISTEN state.
1702 * If active open, inform user that connection was refused.
1703 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1704 * Inform user that connection was reset, and close tcb.
1705 * CLOSING, LAST_ACK STATES:
1708 * Drop the segment - see Stevens, vol. 2, p. 964 and
1711 if (thflags & TH_RST) {
1712 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1713 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1714 switch (tp->t_state) {
1716 case TCPS_SYN_RECEIVED:
1717 so->so_error = ECONNREFUSED;
1720 case TCPS_ESTABLISHED:
1721 case TCPS_FIN_WAIT_1:
1722 case TCPS_FIN_WAIT_2:
1723 case TCPS_CLOSE_WAIT:
1724 so->so_error = ECONNRESET;
1726 tp->t_state = TCPS_CLOSED;
1727 tcpstat.tcps_drops++;
1736 case TCPS_TIME_WAIT:
1744 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1745 * and it's less than ts_recent, drop it.
1747 if ((to.to_flags & TOF_TS) && tp->ts_recent != 0 &&
1748 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1749 /* Check to see if ts_recent is over 24 days old. */
1750 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1752 * Invalidate ts_recent. If this segment updates
1753 * ts_recent, the age will be reset later and ts_recent
1754 * will get a valid value. If it does not, setting
1755 * ts_recent to zero will at least satisfy the
1756 * requirement that zero be placed in the timestamp
1757 * echo reply when ts_recent isn't valid. The
1758 * age isn't reset until we get a valid ts_recent
1759 * because we don't want out-of-order segments to be
1760 * dropped when ts_recent is old.
1763 } else if (tcp_paws_tolerance && tlen != 0 &&
1764 tp->t_state == TCPS_ESTABLISHED &&
1765 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK&&
1766 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1767 th->th_ack == tp->snd_una &&
1768 tiwin == tp->snd_wnd &&
1769 TSTMP_GEQ(to.to_tsval + tcp_paws_tolerance, tp->ts_recent)&&
1770 (th->th_seq == tp->rcv_nxt ||
1771 (SEQ_GT(th->th_seq, tp->rcv_nxt) &&
1772 tcp_paws_canreasslast(tp, th, tlen)))) {
1774 * This tends to prevent valid new segments from being
1775 * dropped by the reordered segments sent by the fast
1776 * retransmission algorithm on the sending side, i.e.
1777 * the fast retransmitted segment w/ larger timestamp
1778 * arrives earlier than the previously sent new segments
1779 * w/ smaller timestamp.
1781 * If following conditions are met, the segment is
1783 * - The segment contains data
1784 * - The connection is established
1785 * - The header does not contain important flags
1786 * - SYN or FIN is not needed
1787 * - It does not acknowledge new data
1788 * - Receive window is not changed
1789 * - The timestamp is within "acceptable" range
1790 * - The new segment is what we are expecting or
1791 * the new segment could be merged w/ the last
1792 * pending segment on the reassemble queue
1794 tcpstat.tcps_pawsaccept++;
1795 tcpstat.tcps_pawsdrop++;
1797 tcpstat.tcps_rcvduppack++;
1798 tcpstat.tcps_rcvdupbyte += tlen;
1799 tcpstat.tcps_pawsdrop++;
1807 * In the SYN-RECEIVED state, validate that the packet belongs to
1808 * this connection before trimming the data to fit the receive
1809 * window. Check the sequence number versus IRS since we know
1810 * the sequence numbers haven't wrapped. This is a partial fix
1811 * for the "LAND" DoS attack.
1813 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1814 rstreason = BANDLIM_RST_OPENPORT;
1818 todrop = tp->rcv_nxt - th->th_seq;
1820 if (TCP_DO_SACK(tp)) {
1821 /* Report duplicate segment at head of packet. */
1822 tp->reportblk.rblk_start = th->th_seq;
1823 tp->reportblk.rblk_end = TCP_SACK_BLKEND(
1824 th->th_seq + tlen, thflags);
1825 if (SEQ_GT(tp->reportblk.rblk_end, tp->rcv_nxt))
1826 tp->reportblk.rblk_end = tp->rcv_nxt;
1827 tp->sack_flags |= (TSACK_F_DUPSEG | TSACK_F_SACKLEFT);
1828 tp->t_flags |= TF_ACKNOW;
1830 if (thflags & TH_SYN) {
1840 * Following if statement from Stevens, vol. 2, p. 960.
1842 if (todrop > tlen ||
1843 (todrop == tlen && !(thflags & TH_FIN))) {
1845 * Any valid FIN must be to the left of the window.
1846 * At this point the FIN must be a duplicate or out
1847 * of sequence; drop it.
1852 * Send an ACK to resynchronize and drop any data.
1853 * But keep on processing for RST or ACK.
1855 tp->t_flags |= TF_ACKNOW;
1857 tcpstat.tcps_rcvduppack++;
1858 tcpstat.tcps_rcvdupbyte += todrop;
1860 tcpstat.tcps_rcvpartduppack++;
1861 tcpstat.tcps_rcvpartdupbyte += todrop;
1863 drop_hdrlen += todrop; /* drop from the top afterwards */
1864 th->th_seq += todrop;
1866 if (th->th_urp > todrop)
1867 th->th_urp -= todrop;
1875 * If new data are received on a connection after the
1876 * user processes are gone, then RST the other end.
1878 if ((so->so_state & SS_NOFDREF) &&
1879 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1881 tcpstat.tcps_rcvafterclose++;
1882 rstreason = BANDLIM_UNLIMITED;
1887 * If segment ends after window, drop trailing data
1888 * (and PUSH and FIN); if nothing left, just ACK.
1890 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1892 tcpstat.tcps_rcvpackafterwin++;
1893 if (todrop >= tlen) {
1894 tcpstat.tcps_rcvbyteafterwin += tlen;
1896 * If a new connection request is received
1897 * while in TIME_WAIT, drop the old connection
1898 * and start over if the sequence numbers
1899 * are above the previous ones.
1901 if (thflags & TH_SYN &&
1902 tp->t_state == TCPS_TIME_WAIT &&
1903 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1908 * If window is closed can only take segments at
1909 * window edge, and have to drop data and PUSH from
1910 * incoming segments. Continue processing, but
1911 * remember to ack. Otherwise, drop segment
1914 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1915 tp->t_flags |= TF_ACKNOW;
1916 tcpstat.tcps_rcvwinprobe++;
1920 tcpstat.tcps_rcvbyteafterwin += todrop;
1923 thflags &= ~(TH_PUSH | TH_FIN);
1927 * If last ACK falls within this segment's sequence numbers,
1928 * record its timestamp.
1930 * 1) That the test incorporates suggestions from the latest
1931 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1932 * 2) That updating only on newer timestamps interferes with
1933 * our earlier PAWS tests, so this check should be solely
1934 * predicated on the sequence space of this segment.
1935 * 3) That we modify the segment boundary check to be
1936 * Last.ACK.Sent <= SEG.SEQ + SEG.LEN
1937 * instead of RFC1323's
1938 * Last.ACK.Sent < SEG.SEQ + SEG.LEN,
1939 * This modified check allows us to overcome RFC1323's
1940 * limitations as described in Stevens TCP/IP Illustrated
1941 * Vol. 2 p.869. In such cases, we can still calculate the
1942 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1944 if ((to.to_flags & TOF_TS) && SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1945 SEQ_LEQ(tp->last_ack_sent, (th->th_seq + tlen
1946 + ((thflags & TH_SYN) != 0)
1947 + ((thflags & TH_FIN) != 0)))) {
1948 tp->ts_recent_age = ticks;
1949 tp->ts_recent = to.to_tsval;
1953 * If a SYN is in the window, then this is an
1954 * error and we send an RST and drop the connection.
1956 if (thflags & TH_SYN) {
1957 tp = tcp_drop(tp, ECONNRESET);
1958 rstreason = BANDLIM_UNLIMITED;
1963 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1964 * flag is on (half-synchronized state), then queue data for
1965 * later processing; else drop segment and return.
1967 if (!(thflags & TH_ACK)) {
1968 if (tp->t_state == TCPS_SYN_RECEIVED ||
1969 (tp->t_flags & TF_NEEDSYN))
1978 switch (tp->t_state) {
1980 * In SYN_RECEIVED state, the ACK acknowledges our SYN, so enter
1981 * ESTABLISHED state and continue processing.
1982 * The ACK was checked above.
1984 case TCPS_SYN_RECEIVED:
1986 tcpstat.tcps_connects++;
1988 /* Do window scaling? */
1989 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1990 (TF_RCVD_SCALE | TF_REQ_SCALE))
1991 tp->rcv_scale = tp->request_r_scale;
1994 * SYN-RECEIVED -> ESTABLISHED
1995 * SYN-RECEIVED* -> FIN-WAIT-1
1997 tp->t_starttime = ticks;
1998 if (tp->t_flags & TF_NEEDFIN) {
1999 tp->t_state = TCPS_FIN_WAIT_1;
2000 tp->t_flags &= ~TF_NEEDFIN;
2002 tcp_established(tp);
2005 * If segment contains data or ACK, will call tcp_reass()
2006 * later; if not, do so now to pass queued data to user.
2008 if (tlen == 0 && !(thflags & TH_FIN))
2009 tcp_reass(tp, NULL, NULL, NULL);
2013 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2014 * ACKs. If the ack is in the range
2015 * tp->snd_una < th->th_ack <= tp->snd_max
2016 * then advance tp->snd_una to th->th_ack and drop
2017 * data from the retransmission queue. If this ACK reflects
2018 * more up to date window information we update our window information.
2020 case TCPS_ESTABLISHED:
2021 case TCPS_FIN_WAIT_1:
2022 case TCPS_FIN_WAIT_2:
2023 case TCPS_CLOSE_WAIT:
2026 case TCPS_TIME_WAIT:
2028 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2029 boolean_t maynotdup = FALSE;
2031 if (TCP_DO_SACK(tp))
2032 tcp_sack_update_scoreboard(tp, &to);
2034 if (tlen != 0 || tiwin != tp->snd_wnd ||
2035 ((thflags & TH_FIN) && !(tp->t_flags & TF_SAWFIN)))
2038 if (!tcp_callout_active(tp, tp->tt_rexmt) ||
2039 th->th_ack != tp->snd_una) {
2041 tcpstat.tcps_rcvdupack++;
2046 #define DELAY_DUPACK \
2048 delayed_dupack = TRUE; \
2049 th_dupack = th->th_ack; \
2050 to_flags = to.to_flags; \
2053 if (!tcp_do_rfc6675 ||
2056 (TOF_SACK | TOF_SACK_REDUNDANT))
2064 if ((thflags & TH_FIN) && !(tp->t_flags & TF_QUEDFIN)) {
2066 * This could happen, if the reassemable
2067 * queue overflew or was drained. Don't
2068 * drop this FIN here; defer the duplicated
2069 * ACK processing until this FIN gets queued.
2076 if (tcp_recv_dupack(tp, th->th_ack, to.to_flags))
2082 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
2084 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2086 * Detected optimistic ACK attack.
2087 * Force slow-start to de-synchronize attack.
2089 tp->snd_cwnd = tp->t_maxseg;
2092 tcpstat.tcps_rcvacktoomuch++;
2096 * If we reach this point, ACK is not a duplicate,
2097 * i.e., it ACKs something we sent.
2099 if (tp->t_flags & TF_NEEDSYN) {
2101 * T/TCP: Connection was half-synchronized, and our
2102 * SYN has been ACK'd (so connection is now fully
2103 * synchronized). Go to non-starred state,
2104 * increment snd_una for ACK of SYN, and check if
2105 * we can do window scaling.
2107 tp->t_flags &= ~TF_NEEDSYN;
2109 /* Do window scaling? */
2110 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
2111 (TF_RCVD_SCALE | TF_REQ_SCALE))
2112 tp->rcv_scale = tp->request_r_scale;
2116 acked = th->th_ack - tp->snd_una;
2117 tcpstat.tcps_rcvackpack++;
2118 tcpstat.tcps_rcvackbyte += acked;
2120 if (tcp_do_eifel_detect && acked > 0 &&
2121 (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
2122 (tp->rxt_flags & TRXT_F_FIRSTACCACK)) {
2123 /* Eifel detection applicable. */
2124 if (to.to_tsecr < tp->t_rexmtTS) {
2125 ++tcpstat.tcps_eifeldetected;
2126 tcp_revert_congestion_state(tp);
2127 if (tp->t_rxtshift != 1 ||
2128 ticks >= tp->t_badrxtwin)
2129 ++tcpstat.tcps_rttcantdetect;
2131 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2133 * If we just performed our first retransmit,
2134 * and the ACK arrives within our recovery window,
2135 * then it was a mistake to do the retransmit
2136 * in the first place. Recover our original cwnd
2137 * and ssthresh, and proceed to transmit where we
2140 tcp_revert_congestion_state(tp);
2141 ++tcpstat.tcps_rttdetected;
2145 * If we have a timestamp reply, update smoothed
2146 * round trip time. If no timestamp is present but
2147 * transmit timer is running and timed sequence
2148 * number was acked, update smoothed round trip time.
2149 * Since we now have an rtt measurement, cancel the
2150 * timer backoff (cf., Phil Karn's retransmit alg.).
2151 * Recompute the initial retransmit timer.
2153 * Some machines (certain windows boxes) send broken
2154 * timestamp replies during the SYN+ACK phase, ignore
2157 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
2158 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1, th->th_ack);
2159 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2160 tcp_xmit_timer(tp, ticks - tp->t_rtttime, th->th_ack);
2161 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2164 * If no data (only SYN) was ACK'd,
2165 * skip rest of ACK processing.
2170 /* Stop looking for an acceptable ACK since one was received. */
2171 tp->rxt_flags &= ~(TRXT_F_FIRSTACCACK |
2172 TRXT_F_FASTREXMT | TRXT_F_EARLYREXMT);
2174 if (acked > so->so_snd.ssb_cc) {
2175 tp->snd_wnd -= so->so_snd.ssb_cc;
2176 sbdrop(&so->so_snd.sb, (int)so->so_snd.ssb_cc);
2177 ourfinisacked = TRUE;
2179 sbdrop(&so->so_snd.sb, acked);
2180 tp->snd_wnd -= acked;
2181 ourfinisacked = FALSE;
2186 * Update window information.
2188 if (acceptable_window_update(tp, th, tiwin)) {
2189 /* keep track of pure window updates */
2190 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2191 tiwin > tp->snd_wnd)
2192 tcpstat.tcps_rcvwinupd++;
2193 tp->snd_wnd = tiwin;
2194 tp->snd_wl1 = th->th_seq;
2195 tp->snd_wl2 = th->th_ack;
2196 if (tp->snd_wnd > tp->max_sndwnd)
2197 tp->max_sndwnd = tp->snd_wnd;
2201 tp->snd_una = th->th_ack;
2202 if (TCP_DO_SACK(tp))
2203 tcp_sack_update_scoreboard(tp, &to);
2204 if (IN_FASTRECOVERY(tp)) {
2205 if (SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2206 EXIT_FASTRECOVERY(tp);
2209 * If the congestion window was inflated
2210 * to account for the other side's
2211 * cached packets, retract it.
2213 if (!TCP_DO_SACK(tp))
2214 tp->snd_cwnd = tp->snd_ssthresh;
2217 * Window inflation should have left us
2218 * with approximately snd_ssthresh outstanding
2219 * data. But, in case we would be inclined
2220 * to send a burst, better do it using
2223 if (SEQ_GT(th->th_ack + tp->snd_cwnd,
2224 tp->snd_max + 2 * tp->t_maxseg))
2226 (tp->snd_max - tp->snd_una) +
2231 if (TCP_DO_SACK(tp)) {
2232 tp->snd_max_rexmt = tp->snd_max;
2234 tp->snd_una == tp->rexmt_high);
2236 tcp_newreno_partial_ack(tp, th, acked);
2242 * Open the congestion window. When in slow-start,
2243 * open exponentially: maxseg per packet. Otherwise,
2244 * open linearly: maxseg per window.
2246 if (tp->snd_cwnd <= tp->snd_ssthresh) {
2248 (SEQ_LT(tp->snd_nxt, tp->snd_max) ?
2249 tp->t_maxseg : 2 * tp->t_maxseg);
2252 tp->snd_cwnd += tcp_do_abc ?
2253 min(acked, abc_sslimit) : tp->t_maxseg;
2255 /* linear increase */
2256 tp->snd_wacked += tcp_do_abc ? acked :
2258 if (tp->snd_wacked >= tp->snd_cwnd) {
2259 tp->snd_wacked -= tp->snd_cwnd;
2260 tp->snd_cwnd += tp->t_maxseg;
2263 tp->snd_cwnd = min(tp->snd_cwnd,
2264 TCP_MAXWIN << tp->snd_scale);
2265 tp->snd_recover = th->th_ack - 1;
2267 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2268 tp->snd_nxt = tp->snd_una;
2271 * If all outstanding data is acked, stop retransmit
2272 * timer and remember to restart (more output or persist).
2273 * If there is more data to be acked, restart retransmit
2274 * timer, using current (possibly backed-off) value.
2276 if (th->th_ack == tp->snd_max) {
2277 tcp_callout_stop(tp, tp->tt_rexmt);
2279 } else if (!tcp_callout_active(tp, tp->tt_persist)) {
2280 tcp_callout_reset(tp, tp->tt_rexmt, tp->t_rxtcur,
2284 switch (tp->t_state) {
2286 * In FIN_WAIT_1 STATE in addition to the processing
2287 * for the ESTABLISHED state if our FIN is now acknowledged
2288 * then enter FIN_WAIT_2.
2290 case TCPS_FIN_WAIT_1:
2291 if (ourfinisacked) {
2293 * If we can't receive any more
2294 * data, then closing user can proceed.
2295 * Starting the timer is contrary to the
2296 * specification, but if we don't get a FIN
2297 * we'll hang forever.
2299 if (so->so_state & SS_CANTRCVMORE) {
2300 soisdisconnected(so);
2301 tcp_callout_reset(tp, tp->tt_2msl,
2302 tp->t_maxidle, tcp_timer_2msl);
2304 tp->t_state = TCPS_FIN_WAIT_2;
2309 * In CLOSING STATE in addition to the processing for
2310 * the ESTABLISHED state if the ACK acknowledges our FIN
2311 * then enter the TIME-WAIT state, otherwise ignore
2315 if (ourfinisacked) {
2316 tp->t_state = TCPS_TIME_WAIT;
2317 tcp_canceltimers(tp);
2318 tcp_callout_reset(tp, tp->tt_2msl,
2319 2 * tcp_rmx_msl(tp),
2321 soisdisconnected(so);
2326 * In LAST_ACK, we may still be waiting for data to drain
2327 * and/or to be acked, as well as for the ack of our FIN.
2328 * If our FIN is now acknowledged, delete the TCB,
2329 * enter the closed state and return.
2332 if (ourfinisacked) {
2339 * In TIME_WAIT state the only thing that should arrive
2340 * is a retransmission of the remote FIN. Acknowledge
2341 * it and restart the finack timer.
2343 case TCPS_TIME_WAIT:
2344 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2352 * Update window information.
2353 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2355 if ((thflags & TH_ACK) &&
2356 acceptable_window_update(tp, th, tiwin)) {
2357 /* keep track of pure window updates */
2358 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2359 tiwin > tp->snd_wnd)
2360 tcpstat.tcps_rcvwinupd++;
2361 tp->snd_wnd = tiwin;
2362 tp->snd_wl1 = th->th_seq;
2363 tp->snd_wl2 = th->th_ack;
2364 if (tp->snd_wnd > tp->max_sndwnd)
2365 tp->max_sndwnd = tp->snd_wnd;
2370 * Process segments with URG.
2372 if ((thflags & TH_URG) && th->th_urp &&
2373 !TCPS_HAVERCVDFIN(tp->t_state)) {
2375 * This is a kludge, but if we receive and accept
2376 * random urgent pointers, we'll crash in
2377 * soreceive. It's hard to imagine someone
2378 * actually wanting to send this much urgent data.
2380 if (th->th_urp + so->so_rcv.ssb_cc > sb_max) {
2381 th->th_urp = 0; /* XXX */
2382 thflags &= ~TH_URG; /* XXX */
2383 goto dodata; /* XXX */
2386 * If this segment advances the known urgent pointer,
2387 * then mark the data stream. This should not happen
2388 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2389 * a FIN has been received from the remote side.
2390 * In these states we ignore the URG.
2392 * According to RFC961 (Assigned Protocols),
2393 * the urgent pointer points to the last octet
2394 * of urgent data. We continue, however,
2395 * to consider it to indicate the first octet
2396 * of data past the urgent section as the original
2397 * spec states (in one of two places).
2399 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
2400 tp->rcv_up = th->th_seq + th->th_urp;
2401 so->so_oobmark = so->so_rcv.ssb_cc +
2402 (tp->rcv_up - tp->rcv_nxt) - 1;
2403 if (so->so_oobmark == 0)
2404 sosetstate(so, SS_RCVATMARK);
2406 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2409 * Remove out of band data so doesn't get presented to user.
2410 * This can happen independent of advancing the URG pointer,
2411 * but if two URG's are pending at once, some out-of-band
2412 * data may creep in... ick.
2414 if (th->th_urp <= (u_long)tlen &&
2415 !(so->so_options & SO_OOBINLINE)) {
2416 /* hdr drop is delayed */
2417 tcp_pulloutofband(so, th, m, drop_hdrlen);
2421 * If no out of band data is expected,
2422 * pull receive urgent pointer along
2423 * with the receive window.
2425 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2426 tp->rcv_up = tp->rcv_nxt;
2431 * Process the segment text, merging it into the TCP sequencing queue,
2432 * and arranging for acknowledgment of receipt if necessary.
2433 * This process logically involves adjusting tp->rcv_wnd as data
2434 * is presented to the user (this happens in tcp_usrreq.c,
2435 * case PRU_RCVD). If a FIN has already been received on this
2436 * connection then we just ignore the text.
2438 if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
2439 if (thflags & TH_FIN)
2440 tp->t_flags |= TF_SAWFIN;
2441 m_adj(m, drop_hdrlen); /* delayed header drop */
2443 * Insert segment which includes th into TCP reassembly queue
2444 * with control block tp. Set thflags to whether reassembly now
2445 * includes a segment with FIN. This handles the common case
2446 * inline (segment is the next to be received on an established
2447 * connection, and the queue is empty), avoiding linkage into
2448 * and removal from the queue and repetition of various
2450 * Set DELACK for segments received in order, but ack
2451 * immediately when segments are out of order (so
2452 * fast retransmit can work).
2454 if (th->th_seq == tp->rcv_nxt &&
2455 TAILQ_EMPTY(&tp->t_segq) &&
2456 TCPS_HAVEESTABLISHED(tp->t_state)) {
2457 if (thflags & TH_FIN)
2458 tp->t_flags |= TF_QUEDFIN;
2459 if (DELAY_ACK(tp)) {
2460 tcp_callout_reset(tp, tp->tt_delack,
2461 tcp_delacktime, tcp_timer_delack);
2463 tp->t_flags |= TF_ACKNOW;
2465 tp->rcv_nxt += tlen;
2466 thflags = th->th_flags & TH_FIN;
2467 tcpstat.tcps_rcvpack++;
2468 tcpstat.tcps_rcvbyte += tlen;
2470 if (so->so_state & SS_CANTRCVMORE) {
2473 lwkt_gettoken(&so->so_rcv.ssb_token);
2474 ssb_appendstream(&so->so_rcv, m);
2475 lwkt_reltoken(&so->so_rcv.ssb_token);
2479 if (!(tp->sack_flags & TSACK_F_DUPSEG)) {
2480 /* Initialize SACK report block. */
2481 tp->reportblk.rblk_start = th->th_seq;
2482 tp->reportblk.rblk_end = TCP_SACK_BLKEND(
2483 th->th_seq + tlen, thflags);
2485 thflags = tcp_reass(tp, th, &tlen, m);
2486 tp->t_flags |= TF_ACKNOW;
2490 * Note the amount of data that peer has sent into
2491 * our window, in order to estimate the sender's
2494 len = so->so_rcv.ssb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2501 * If FIN is received ACK the FIN and let the user know
2502 * that the connection is closing.
2504 if (thflags & TH_FIN) {
2505 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
2508 * If connection is half-synchronized
2509 * (ie NEEDSYN flag on) then delay ACK,
2510 * so it may be piggybacked when SYN is sent.
2511 * Otherwise, since we received a FIN then no
2512 * more input can be expected, send ACK now.
2514 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN)) {
2515 tcp_callout_reset(tp, tp->tt_delack,
2516 tcp_delacktime, tcp_timer_delack);
2518 tp->t_flags |= TF_ACKNOW;
2523 switch (tp->t_state) {
2525 * In SYN_RECEIVED and ESTABLISHED STATES
2526 * enter the CLOSE_WAIT state.
2528 case TCPS_SYN_RECEIVED:
2529 tp->t_starttime = ticks;
2531 case TCPS_ESTABLISHED:
2532 tp->t_state = TCPS_CLOSE_WAIT;
2536 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2537 * enter the CLOSING state.
2539 case TCPS_FIN_WAIT_1:
2540 tp->t_state = TCPS_CLOSING;
2544 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2545 * starting the time-wait timer, turning off the other
2548 case TCPS_FIN_WAIT_2:
2549 tp->t_state = TCPS_TIME_WAIT;
2550 tcp_canceltimers(tp);
2551 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2553 soisdisconnected(so);
2557 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2559 case TCPS_TIME_WAIT:
2560 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2567 if (so->so_options & SO_DEBUG)
2568 tcp_trace(TA_INPUT, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2572 * Delayed duplicated ACK processing
2574 if (delayed_dupack && tcp_recv_dupack(tp, th_dupack, to_flags))
2578 * Return any desired output.
2580 if ((tp->t_flags & TF_ACKNOW) ||
2581 (needoutput && tcp_sack_report_needed(tp))) {
2582 tcp_output_cancel(tp);
2583 tcp_output_fair(tp);
2584 } else if (needoutput && !tcp_output_pending(tp)) {
2585 tcp_output_fair(tp);
2587 tcp_sack_report_cleanup(tp);
2588 return(IPPROTO_DONE);
2592 * Generate an ACK dropping incoming segment if it occupies
2593 * sequence space, where the ACK reflects our state.
2595 * We can now skip the test for the RST flag since all
2596 * paths to this code happen after packets containing
2597 * RST have been dropped.
2599 * In the SYN-RECEIVED state, don't send an ACK unless the
2600 * segment we received passes the SYN-RECEIVED ACK test.
2601 * If it fails send a RST. This breaks the loop in the
2602 * "LAND" DoS attack, and also prevents an ACK storm
2603 * between two listening ports that have been sent forged
2604 * SYN segments, each with the source address of the other.
2606 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2607 (SEQ_GT(tp->snd_una, th->th_ack) ||
2608 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2609 rstreason = BANDLIM_RST_OPENPORT;
2613 if (so->so_options & SO_DEBUG)
2614 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2617 tp->t_flags |= TF_ACKNOW;
2619 tcp_sack_report_cleanup(tp);
2620 return(IPPROTO_DONE);
2624 * Generate a RST, dropping incoming segment.
2625 * Make ACK acceptable to originator of segment.
2626 * Don't bother to respond if destination was broadcast/multicast.
2628 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
2631 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2632 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2635 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2636 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2637 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2638 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2641 /* IPv6 anycast check is done at tcp6_input() */
2644 * Perform bandwidth limiting.
2647 if (badport_bandlim(rstreason) < 0)
2652 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2653 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2655 if (thflags & TH_ACK)
2656 /* mtod() below is safe as long as hdr dropping is delayed */
2657 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2660 if (thflags & TH_SYN)
2662 /* mtod() below is safe as long as hdr dropping is delayed */
2663 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2664 (tcp_seq)0, TH_RST | TH_ACK);
2667 tcp_sack_report_cleanup(tp);
2668 return(IPPROTO_DONE);
2672 * Drop space held by incoming segment and return.
2675 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2676 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2680 tcp_sack_report_cleanup(tp);
2681 return(IPPROTO_DONE);
2685 * Parse TCP options and place in tcpopt.
2688 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn,
2694 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2696 if (opt == TCPOPT_EOL)
2698 if (opt == TCPOPT_NOP)
2704 if (optlen < 2 || optlen > cnt)
2709 if (optlen != TCPOLEN_MAXSEG)
2713 to->to_flags |= TOF_MSS;
2714 bcopy(cp + 2, &to->to_mss, sizeof to->to_mss);
2715 to->to_mss = ntohs(to->to_mss);
2718 if (optlen != TCPOLEN_WINDOW)
2722 to->to_flags |= TOF_SCALE;
2723 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2725 case TCPOPT_TIMESTAMP:
2726 if (optlen != TCPOLEN_TIMESTAMP)
2728 to->to_flags |= TOF_TS;
2729 bcopy(cp + 2, &to->to_tsval, sizeof to->to_tsval);
2730 to->to_tsval = ntohl(to->to_tsval);
2731 bcopy(cp + 6, &to->to_tsecr, sizeof to->to_tsecr);
2732 to->to_tsecr = ntohl(to->to_tsecr);
2734 * If echoed timestamp is later than the current time,
2735 * fall back to non RFC1323 RTT calculation.
2737 if (to->to_tsecr != 0 && TSTMP_GT(to->to_tsecr, ticks))
2740 case TCPOPT_SACK_PERMITTED:
2741 if (optlen != TCPOLEN_SACK_PERMITTED)
2745 to->to_flags |= TOF_SACK_PERMITTED;
2748 if ((optlen - 2) & 0x07) /* not multiple of 8 */
2750 to->to_nsackblocks = (optlen - 2) / 8;
2751 to->to_sackblocks = (struct raw_sackblock *) (cp + 2);
2752 to->to_flags |= TOF_SACK;
2753 for (i = 0; i < to->to_nsackblocks; i++) {
2754 struct raw_sackblock *r = &to->to_sackblocks[i];
2756 r->rblk_start = ntohl(r->rblk_start);
2757 r->rblk_end = ntohl(r->rblk_end);
2759 if (SEQ_LEQ(r->rblk_end, r->rblk_start)) {
2761 * Invalid SACK block; discard all
2764 tcpstat.tcps_rcvbadsackopt++;
2765 to->to_nsackblocks = 0;
2766 to->to_sackblocks = NULL;
2767 to->to_flags &= ~TOF_SACK;
2771 if ((to->to_flags & TOF_SACK) &&
2772 tcp_sack_ndsack_blocks(to->to_sackblocks,
2773 to->to_nsackblocks, ack))
2774 to->to_flags |= TOF_DSACK;
2776 #ifdef TCP_SIGNATURE
2778 * XXX In order to reply to a host which has set the
2779 * TCP_SIGNATURE option in its initial SYN, we have to
2780 * record the fact that the option was observed here
2781 * for the syncache code to perform the correct response.
2783 case TCPOPT_SIGNATURE:
2784 if (optlen != TCPOLEN_SIGNATURE)
2786 to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2788 #endif /* TCP_SIGNATURE */
2796 * Pull out of band byte out of a segment so
2797 * it doesn't appear in the user's data queue.
2798 * It is still reflected in the segment length for
2799 * sequencing purposes.
2800 * "off" is the delayed to be dropped hdrlen.
2803 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
2805 int cnt = off + th->th_urp - 1;
2808 if (m->m_len > cnt) {
2809 char *cp = mtod(m, caddr_t) + cnt;
2810 struct tcpcb *tp = sototcpcb(so);
2813 tp->t_oobflags |= TCPOOB_HAVEDATA;
2814 bcopy(cp + 1, cp, m->m_len - cnt - 1);
2816 if (m->m_flags & M_PKTHDR)
2825 panic("tcp_pulloutofband");
2829 * Collect new round-trip time estimate
2830 * and update averages and current timeout.
2833 tcp_xmit_timer(struct tcpcb *tp, int rtt, tcp_seq ack)
2837 tcpstat.tcps_rttupdated++;
2839 if ((tp->rxt_flags & TRXT_F_REBASERTO) &&
2840 SEQ_GT(ack, tp->snd_max_prev)) {
2841 #ifdef DEBUG_EIFEL_RESPONSE
2842 kprintf("srtt/rttvar, prev %d/%d, cur %d/%d, ",
2843 tp->t_srtt_prev, tp->t_rttvar_prev,
2844 tp->t_srtt, tp->t_rttvar);
2847 tcpstat.tcps_eifelresponse++;
2849 tp->rxt_flags &= ~TRXT_F_REBASERTO;
2850 tp->t_srtt = max(tp->t_srtt_prev, (rtt << TCP_RTT_SHIFT));
2851 tp->t_rttvar = max(tp->t_rttvar_prev,
2852 (rtt << (TCP_RTTVAR_SHIFT - 1)));
2853 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2854 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2856 #ifdef DEBUG_EIFEL_RESPONSE
2857 kprintf("new %d/%d ", tp->t_srtt, tp->t_rttvar);
2859 } else if (tp->t_srtt != 0) {
2863 * srtt is stored as fixed point with 5 bits after the
2864 * binary point (i.e., scaled by 8). The following magic
2865 * is equivalent to the smoothing algorithm in rfc793 with
2866 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2867 * point). Adjust rtt to origin 0.
2869 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2870 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2872 if ((tp->t_srtt += delta) <= 0)
2876 * We accumulate a smoothed rtt variance (actually, a
2877 * smoothed mean difference), then set the retransmit
2878 * timer to smoothed rtt + 4 times the smoothed variance.
2879 * rttvar is stored as fixed point with 4 bits after the
2880 * binary point (scaled by 16). The following is
2881 * equivalent to rfc793 smoothing with an alpha of .75
2882 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2883 * rfc793's wired-in beta.
2887 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2888 if ((tp->t_rttvar += delta) <= 0)
2890 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2891 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2894 * No rtt measurement yet - use the unsmoothed rtt.
2895 * Set the variance to half the rtt (so our first
2896 * retransmit happens at 3*rtt).
2898 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2899 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2900 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2905 #ifdef DEBUG_EIFEL_RESPONSE
2907 kprintf("| rxtcur prev %d, old %d, ",
2908 tp->t_rxtcur_prev, tp->t_rxtcur);
2913 * the retransmit should happen at rtt + 4 * rttvar.
2914 * Because of the way we do the smoothing, srtt and rttvar
2915 * will each average +1/2 tick of bias. When we compute
2916 * the retransmit timer, we want 1/2 tick of rounding and
2917 * 1 extra tick because of +-1/2 tick uncertainty in the
2918 * firing of the timer. The bias will give us exactly the
2919 * 1.5 tick we need. But, because the bias is
2920 * statistical, we have to test that we don't drop below
2921 * the minimum feasible timer (which is 2 ticks).
2923 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2924 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2927 if (tp->t_rxtcur < tp->t_rxtcur_prev + tcp_eifel_rtoinc) {
2929 * RFC4015 requires that the new RTO is at least
2930 * 2*G (tcp_eifel_rtoinc) greater then the RTO
2931 * (t_rxtcur_prev) when the spurious retransmit
2934 * The above condition could be true, if the SRTT
2935 * and RTTVAR used to calculate t_rxtcur_prev
2936 * resulted in a value less than t_rttmin. So
2937 * simply increasing SRTT by tcp_eifel_rtoinc when
2938 * preparing for the Eifel response could not ensure
2939 * that the new RTO will be tcp_eifel_rtoinc greater
2942 tp->t_rxtcur = tp->t_rxtcur_prev + tcp_eifel_rtoinc;
2944 #ifdef DEBUG_EIFEL_RESPONSE
2945 kprintf("new %d\n", tp->t_rxtcur);
2950 * We received an ack for a packet that wasn't retransmitted;
2951 * it is probably safe to discard any error indications we've
2952 * received recently. This isn't quite right, but close enough
2953 * for now (a route might have failed after we sent a segment,
2954 * and the return path might not be symmetrical).
2956 tp->t_softerror = 0;
2960 * Determine a reasonable value for maxseg size.
2961 * If the route is known, check route for mtu.
2962 * If none, use an mss that can be handled on the outgoing
2963 * interface without forcing IP to fragment; if bigger than
2964 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2965 * to utilize large mbufs. If no route is found, route has no mtu,
2966 * or the destination isn't local, use a default, hopefully conservative
2967 * size (usually 512 or the default IP max size, but no more than the mtu
2968 * of the interface), as we can't discover anything about intervening
2969 * gateways or networks. We also initialize the congestion/slow start
2970 * window to be a single segment if the destination isn't local.
2971 * While looking at the routing entry, we also initialize other path-dependent
2972 * parameters from pre-set or cached values in the routing entry.
2974 * Also take into account the space needed for options that we
2975 * send regularly. Make maxseg shorter by that amount to assure
2976 * that we can send maxseg amount of data even when the options
2977 * are present. Store the upper limit of the length of options plus
2980 * NOTE that this routine is only called when we process an incoming
2981 * segment, for outgoing segments only tcp_mssopt is called.
2984 tcp_mss(struct tcpcb *tp, int offer)
2990 struct inpcb *inp = tp->t_inpcb;
2993 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2994 size_t min_protoh = isipv6 ?
2995 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2996 sizeof(struct tcpiphdr);
2998 const boolean_t isipv6 = FALSE;
2999 const size_t min_protoh = sizeof(struct tcpiphdr);
3003 rt = tcp_rtlookup6(&inp->inp_inc);
3005 rt = tcp_rtlookup(&inp->inp_inc);
3007 tp->t_maxopd = tp->t_maxseg =
3008 (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3012 so = inp->inp_socket;
3015 * Offer == 0 means that there was no MSS on the SYN segment,
3016 * in this case we use either the interface mtu or tcp_mssdflt.
3018 * An offer which is too large will be cut down later.
3022 if (in6_localaddr(&inp->in6p_faddr)) {
3023 offer = ND_IFINFO(rt->rt_ifp)->linkmtu -
3026 offer = tcp_v6mssdflt;
3029 if (in_localaddr(inp->inp_faddr))
3030 offer = ifp->if_mtu - min_protoh;
3032 offer = tcp_mssdflt;
3037 * Prevent DoS attack with too small MSS. Round up
3038 * to at least minmss.
3040 * Sanity check: make sure that maxopd will be large
3041 * enough to allow some data on segments even is the
3042 * all the option space is used (40bytes). Otherwise
3043 * funny things may happen in tcp_output.
3045 offer = max(offer, tcp_minmss);
3046 offer = max(offer, 64);
3048 rt->rt_rmx.rmx_mssopt = offer;
3051 * While we're here, check if there's an initial rtt
3052 * or rttvar. Convert from the route-table units
3053 * to scaled multiples of the slow timeout timer.
3055 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
3057 * XXX the lock bit for RTT indicates that the value
3058 * is also a minimum value; this is subject to time.
3060 if (rt->rt_rmx.rmx_locks & RTV_RTT)
3061 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
3062 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
3063 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3064 tcpstat.tcps_usedrtt++;
3065 if (rt->rt_rmx.rmx_rttvar) {
3066 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
3067 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
3068 tcpstat.tcps_usedrttvar++;
3070 /* default variation is +- 1 rtt */
3072 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3074 TCPT_RANGESET(tp->t_rxtcur,
3075 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3076 tp->t_rttmin, TCPTV_REXMTMAX);
3080 * if there's an mtu associated with the route, use it
3081 * else, use the link mtu. Take the smaller of mss or offer
3084 if (rt->rt_rmx.rmx_mtu) {
3085 mss = rt->rt_rmx.rmx_mtu - min_protoh;
3088 mss = ND_IFINFO(rt->rt_ifp)->linkmtu - min_protoh;
3090 mss = ifp->if_mtu - min_protoh;
3092 mss = min(mss, offer);
3095 * maxopd stores the maximum length of data AND options
3096 * in a segment; maxseg is the amount of data in a normal
3097 * segment. We need to store this value (maxopd) apart
3098 * from maxseg, because now every segment carries options
3099 * and thus we normally have somewhat less data in segments.
3103 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
3104 ((tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3105 mss -= TCPOLEN_TSTAMP_APPA;
3107 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3109 mss &= ~(MCLBYTES-1);
3112 mss = mss / MCLBYTES * MCLBYTES;
3115 * If there's a pipesize, change the socket buffer
3116 * to that size. Make the socket buffers an integral
3117 * number of mss units; if the mss is larger than
3118 * the socket buffer, decrease the mss.
3121 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
3123 bufsize = so->so_snd.ssb_hiwat;
3127 bufsize = roundup(bufsize, mss);
3128 if (bufsize > sb_max)
3130 if (bufsize > so->so_snd.ssb_hiwat)
3131 ssb_reserve(&so->so_snd, bufsize, so, NULL);
3136 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
3138 bufsize = so->so_rcv.ssb_hiwat;
3139 if (bufsize > mss) {
3140 bufsize = roundup(bufsize, mss);
3141 if (bufsize > sb_max)
3143 if (bufsize > so->so_rcv.ssb_hiwat) {
3144 lwkt_gettoken(&so->so_rcv.ssb_token);
3145 ssb_reserve(&so->so_rcv, bufsize, so, NULL);
3146 lwkt_reltoken(&so->so_rcv.ssb_token);
3151 * Set the slow-start flight size
3153 * NOTE: t_maxseg must have been configured!
3155 tp->snd_cwnd = tcp_initial_window(tp);
3157 if (rt->rt_rmx.rmx_ssthresh) {
3159 * There's some sort of gateway or interface
3160 * buffer limit on the path. Use this to set
3161 * the slow start threshhold, but set the
3162 * threshold to no less than 2*mss.
3164 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3165 tcpstat.tcps_usedssthresh++;
3170 * Determine the MSS option to send on an outgoing SYN.
3173 tcp_mssopt(struct tcpcb *tp)
3178 ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3179 int min_protoh = isipv6 ?
3180 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
3181 sizeof(struct tcpiphdr);
3183 const boolean_t isipv6 = FALSE;
3184 const size_t min_protoh = sizeof(struct tcpiphdr);
3188 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
3190 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
3192 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3194 return (rt->rt_ifp->if_mtu - min_protoh);
3198 * When a partial ack arrives, force the retransmission of the
3199 * next unacknowledged segment. Do not exit Fast Recovery.
3201 * Implement the Slow-but-Steady variant of NewReno by restarting the
3202 * the retransmission timer. Turn it off here so it can be restarted
3203 * later in tcp_output().
3206 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th, int acked)
3208 tcp_seq old_snd_nxt = tp->snd_nxt;
3209 u_long ocwnd = tp->snd_cwnd;
3211 tcp_callout_stop(tp, tp->tt_rexmt);
3213 tp->snd_nxt = th->th_ack;
3214 /* Set snd_cwnd to one segment beyond acknowledged offset. */
3215 tp->snd_cwnd = tp->t_maxseg;
3216 tp->t_flags |= TF_ACKNOW;
3218 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3219 tp->snd_nxt = old_snd_nxt;
3220 /* partial window deflation */
3222 tp->snd_cwnd = ocwnd - acked + tp->t_maxseg;
3224 tp->snd_cwnd = tp->t_maxseg;
3228 * In contrast to the Slow-but-Steady NewReno variant,
3229 * we do not reset the retransmission timer for SACK retransmissions,
3230 * except when retransmitting snd_una.
3233 tcp_sack_rexmt(struct tcpcb *tp, boolean_t force)
3235 tcp_seq old_snd_nxt = tp->snd_nxt;
3236 u_long ocwnd = tp->snd_cwnd;
3238 int nseg = 0; /* consecutive new segments */
3239 int nseg_rexmt = 0; /* retransmitted segments */
3243 uint32_t unsacked = tcp_sack_first_unsacked_len(tp);
3246 * Try to fill the first hole in the receiver's
3249 maxrexmt = howmany(unsacked, tp->t_maxseg);
3250 if (maxrexmt > tcp_force_sackrxt)
3251 maxrexmt = tcp_force_sackrxt;
3255 pipe = tcp_sack_compute_pipe(tp);
3256 while (((tcp_seq_diff_t)(ocwnd - pipe) >= (tcp_seq_diff_t)tp->t_maxseg
3257 || (force && nseg_rexmt < maxrexmt && nseg == 0)) &&
3258 (!tcp_do_smartsack || nseg < TCP_SACK_MAXBURST)) {
3259 tcp_seq old_snd_max, old_rexmt_high, nextrexmt;
3260 uint32_t sent, seglen;
3264 old_rexmt_high = tp->rexmt_high;
3265 if (!tcp_sack_nextseg(tp, &nextrexmt, &seglen, &rescue)) {
3266 tp->rexmt_high = old_rexmt_high;
3271 * If the next tranmission is a rescue retranmission,
3272 * we check whether we have already sent some data
3273 * (either new segments or retransmitted segments)
3274 * into the the network or not. Since the idea of rescue
3275 * retransmission is to sustain ACK clock, as long as
3276 * some segments are in the network, ACK clock will be
3279 if (rescue && (nseg_rexmt > 0 || nseg > 0)) {
3280 tp->rexmt_high = old_rexmt_high;
3284 if (nextrexmt == tp->snd_max)
3288 tp->snd_nxt = nextrexmt;
3289 tp->snd_cwnd = nextrexmt - tp->snd_una + seglen;
3290 old_snd_max = tp->snd_max;
3291 if (nextrexmt == tp->snd_una)
3292 tcp_callout_stop(tp, tp->tt_rexmt);
3293 tp->t_flags |= TF_XMITNOW;
3294 error = tcp_output(tp);
3296 tp->rexmt_high = old_rexmt_high;
3299 sent = tp->snd_nxt - nextrexmt;
3301 tp->rexmt_high = old_rexmt_high;
3305 tcpstat.tcps_sndsackpack++;
3306 tcpstat.tcps_sndsackbyte += sent;
3309 tcpstat.tcps_sackrescue++;
3310 tp->rexmt_rescue = tp->snd_nxt;
3311 tp->sack_flags |= TSACK_F_SACKRESCUED;
3314 if (SEQ_LT(nextrexmt, old_snd_max) &&
3315 SEQ_LT(tp->rexmt_high, tp->snd_nxt)) {
3316 tp->rexmt_high = seq_min(tp->snd_nxt, old_snd_max);
3317 if (tcp_aggressive_rescuesack &&
3318 (tp->sack_flags & TSACK_F_SACKRESCUED) &&
3319 SEQ_LT(tp->rexmt_rescue, tp->rexmt_high)) {
3320 /* Drag RescueRxt along with HighRxt */
3321 tp->rexmt_rescue = tp->rexmt_high;
3325 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3326 tp->snd_nxt = old_snd_nxt;
3327 tp->snd_cwnd = ocwnd;
3331 * Return TRUE, if some new segments are sent
3334 tcp_sack_limitedxmit(struct tcpcb *tp)
3336 tcp_seq oldsndnxt = tp->snd_nxt;
3337 tcp_seq oldsndmax = tp->snd_max;
3338 u_long ocwnd = tp->snd_cwnd;
3339 uint32_t pipe, sent;
3340 boolean_t ret = FALSE;
3341 tcp_seq_diff_t cwnd_left;
3344 tp->rexmt_high = tp->snd_una - 1;
3345 pipe = tcp_sack_compute_pipe(tp);
3346 cwnd_left = (tcp_seq_diff_t)(ocwnd - pipe);
3347 if (cwnd_left < (tcp_seq_diff_t)tp->t_maxseg)
3350 if (tcp_do_smartsack)
3351 cwnd_left = ulmin(cwnd_left, tp->t_maxseg * TCP_SACK_MAXBURST);
3353 next = tp->snd_nxt = tp->snd_max;
3354 tp->snd_cwnd = tp->snd_nxt - tp->snd_una +
3355 rounddown(cwnd_left, tp->t_maxseg);
3357 tp->t_flags |= TF_XMITNOW;
3360 sent = tp->snd_nxt - next;
3362 tcpstat.tcps_sndlimited += howmany(sent, tp->t_maxseg);
3366 if (SEQ_LT(oldsndnxt, oldsndmax)) {
3367 KASSERT(SEQ_GEQ(oldsndnxt, tp->snd_una),
3368 ("snd_una moved in other threads"));
3369 tp->snd_nxt = oldsndnxt;
3371 tp->snd_cwnd = ocwnd;
3373 if (ret && TCP_DO_NCR(tp))
3374 tcp_ncr_update_rxtthresh(tp);
3380 * Reset idle time and keep-alive timer, typically called when a valid
3381 * tcp packet is received but may also be called when FASTKEEP is set
3382 * to prevent the previous long-timeout from calculating to a drop.
3384 * Only update t_rcvtime for non-SYN packets.
3386 * Handle the case where one side thinks the connection is established
3387 * but the other side has, say, rebooted without cleaning out the
3388 * connection. The SYNs could be construed as an attack and wind
3389 * up ignored, but in case it isn't an attack we can validate the
3390 * connection by forcing a keepalive.
3393 tcp_timer_keep_activity(struct tcpcb *tp, int thflags)
3395 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3396 if ((thflags & (TH_SYN | TH_ACK)) == TH_SYN) {
3397 tp->t_flags |= TF_KEEPALIVE;
3398 tcp_callout_reset(tp, tp->tt_keep, hz / 2,
3401 tp->t_rcvtime = ticks;
3402 tp->t_flags &= ~TF_KEEPALIVE;
3403 tcp_callout_reset(tp, tp->tt_keep,
3411 tcp_rmx_msl(const struct tcpcb *tp)
3414 struct inpcb *inp = tp->t_inpcb;
3417 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3419 const boolean_t isipv6 = FALSE;
3423 rt = tcp_rtlookup6(&inp->inp_inc);
3425 rt = tcp_rtlookup(&inp->inp_inc);
3426 if (rt == NULL || rt->rt_rmx.rmx_msl == 0)
3429 msl = (rt->rt_rmx.rmx_msl * hz) / 1000;
3437 tcp_established(struct tcpcb *tp)
3439 tp->t_state = TCPS_ESTABLISHED;
3440 tcp_callout_reset(tp, tp->tt_keep, tp->t_keepidle, tcp_timer_keep);
3442 if (tp->t_rxtsyn > 0) {
3445 * "If the timer expires awaiting the ACK of a SYN segment
3446 * and the TCP implementation is using an RTO less than 3
3447 * seconds, the RTO MUST be re-initialized to 3 seconds
3448 * when data transmission begins"
3450 if (tp->t_rxtcur < TCPTV_RTOBASE3)
3451 tp->t_rxtcur = TCPTV_RTOBASE3;
3456 * Returns TRUE, if the ACK should be dropped
3459 tcp_recv_dupack(struct tcpcb *tp, tcp_seq th_ack, u_int to_flags)
3461 boolean_t fast_sack_rexmt = TRUE;
3463 tcpstat.tcps_rcvdupack++;
3466 * We have outstanding data (other than a window probe),
3467 * this is a completely duplicate ack (ie, window info
3468 * didn't change), the ack is the biggest we've seen and
3469 * we've seen exactly our rexmt threshhold of them, so
3470 * assume a packet has been dropped and retransmit it.
3471 * Kludge snd_nxt & the congestion window so we send only
3474 if (IN_FASTRECOVERY(tp)) {
3475 if (TCP_DO_SACK(tp)) {
3476 boolean_t force = FALSE;
3478 if (tp->snd_una == tp->rexmt_high &&
3479 (to_flags & (TOF_SACK | TOF_SACK_REDUNDANT)) ==
3482 * New segments got SACKed and
3483 * no retransmit yet.
3488 /* No artifical cwnd inflation. */
3489 tcp_sack_rexmt(tp, force);
3492 * Dup acks mean that packets have left
3493 * the network (they're now cached at the
3494 * receiver) so bump cwnd by the amount in
3495 * the receiver to keep a constant cwnd
3496 * packets in the network.
3498 tp->snd_cwnd += tp->t_maxseg;
3502 } else if (SEQ_LT(th_ack, tp->snd_recover)) {
3505 } else if (tcp_ignore_redun_dsack && TCP_DO_SACK(tp) &&
3506 (to_flags & (TOF_DSACK | TOF_SACK_REDUNDANT)) ==
3507 (TOF_DSACK | TOF_SACK_REDUNDANT)) {
3509 * If the ACK carries DSACK and other SACK blocks
3510 * carry information that we have already known,
3511 * don't count this ACK as duplicate ACK. This
3512 * prevents spurious early retransmit and fast
3513 * retransmit. This also meets the requirement of
3514 * RFC3042 that new segments should not be sent if
3515 * the SACK blocks do not contain new information
3516 * (XXX we actually loosen the requirment that only
3517 * DSACK is checked here).
3519 * This kind of ACKs are usually sent after spurious
3522 /* Do nothing; don't change t_dupacks */
3524 } else if (tp->t_dupacks == 0 && TCP_DO_NCR(tp)) {
3525 tcp_ncr_update_rxtthresh(tp);
3528 if (++tp->t_dupacks == tp->t_rxtthresh) {
3529 tcp_seq old_snd_nxt;
3533 if (tcp_do_eifel_detect && (tp->t_flags & TF_RCVD_TSTMP)) {
3534 tcp_save_congestion_state(tp);
3535 tp->rxt_flags |= TRXT_F_FASTREXMT;
3538 * We know we're losing at the current window size,
3539 * so do congestion avoidance: set ssthresh to half
3540 * the current window and pull our congestion window
3541 * back to the new ssthresh.
3543 win = min(tp->snd_wnd, tp->snd_cwnd) / 2 / tp->t_maxseg;
3546 tp->snd_ssthresh = win * tp->t_maxseg;
3547 ENTER_FASTRECOVERY(tp);
3548 tp->snd_recover = tp->snd_max;
3549 tcp_callout_stop(tp, tp->tt_rexmt);
3551 old_snd_nxt = tp->snd_nxt;
3552 tp->snd_nxt = th_ack;
3553 if (TCP_DO_SACK(tp)) {
3556 rxtlen = tcp_sack_first_unsacked_len(tp);
3557 if (rxtlen > tp->t_maxseg)
3558 rxtlen = tp->t_maxseg;
3559 tp->snd_cwnd = rxtlen;
3561 tp->snd_cwnd = tp->t_maxseg;
3564 ++tcpstat.tcps_sndfastrexmit;
3565 tp->snd_cwnd = tp->snd_ssthresh;
3566 tp->rexmt_high = tp->snd_nxt;
3567 tp->sack_flags &= ~TSACK_F_SACKRESCUED;
3568 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3569 tp->snd_nxt = old_snd_nxt;
3570 KASSERT(tp->snd_limited <= 2, ("tp->snd_limited too big"));
3571 if (TCP_DO_SACK(tp)) {
3572 if (fast_sack_rexmt)
3573 tcp_sack_rexmt(tp, FALSE);
3575 tp->snd_cwnd += tp->t_maxseg *
3576 (tp->t_dupacks - tp->snd_limited);
3578 } else if ((tcp_do_rfc6675 && TCP_DO_SACK(tp)) || TCP_DO_NCR(tp)) {
3580 * The RFC6675 recommends to reduce the byte threshold,
3581 * and enter fast retransmit if IsLost(snd_una). However,
3582 * if we use IsLost(snd_una) based fast retransmit here,
3583 * segments reordering will cause spurious retransmit. So
3584 * we defer the IsLost(snd_una) based fast retransmit until
3585 * the extended limited transmit can't send any segments and
3586 * early retransmit can't be done.
3588 if (tcp_rfc6675_rxt && tcp_do_rfc6675 &&
3589 tcp_sack_islost(&tp->scb, tp->snd_una))
3590 goto fastretransmit;
3592 if (tcp_do_limitedtransmit || TCP_DO_NCR(tp)) {
3593 if (!tcp_sack_limitedxmit(tp)) {
3594 /* outstanding data */
3595 uint32_t ownd = tp->snd_max - tp->snd_una;
3597 if (need_early_retransmit(tp, ownd)) {
3598 ++tcpstat.tcps_sndearlyrexmit;
3599 tp->rxt_flags |= TRXT_F_EARLYREXMT;
3600 goto fastretransmit;
3601 } else if (tcp_do_rfc6675 &&
3602 tcp_sack_islost(&tp->scb, tp->snd_una)) {
3603 fast_sack_rexmt = FALSE;
3604 goto fastretransmit;
3608 } else if (tcp_do_limitedtransmit) {
3609 u_long oldcwnd = tp->snd_cwnd;
3610 tcp_seq oldsndmax = tp->snd_max;
3611 tcp_seq oldsndnxt = tp->snd_nxt;
3612 /* outstanding data */
3613 uint32_t ownd = tp->snd_max - tp->snd_una;
3616 KASSERT(tp->t_dupacks == 1 || tp->t_dupacks == 2,
3617 ("dupacks not 1 or 2"));
3618 if (tp->t_dupacks == 1)
3619 tp->snd_limited = 0;
3620 tp->snd_nxt = tp->snd_max;
3621 tp->snd_cwnd = ownd +
3622 (tp->t_dupacks - tp->snd_limited) * tp->t_maxseg;
3623 tp->t_flags |= TF_XMITNOW;
3626 if (SEQ_LT(oldsndnxt, oldsndmax)) {
3627 KASSERT(SEQ_GEQ(oldsndnxt, tp->snd_una),
3628 ("snd_una moved in other threads"));
3629 tp->snd_nxt = oldsndnxt;
3631 tp->snd_cwnd = oldcwnd;
3632 sent = tp->snd_max - oldsndmax;
3633 if (sent > tp->t_maxseg) {
3634 KASSERT((tp->t_dupacks == 2 && tp->snd_limited == 0) ||
3635 (sent == tp->t_maxseg + 1 &&
3636 (tp->t_flags & TF_SENTFIN)),
3638 KASSERT(sent <= tp->t_maxseg * 2,
3639 ("sent too many segments"));
3640 tp->snd_limited = 2;
3641 tcpstat.tcps_sndlimited += 2;
3642 } else if (sent > 0) {
3644 ++tcpstat.tcps_sndlimited;
3645 } else if (need_early_retransmit(tp, ownd)) {
3646 ++tcpstat.tcps_sndearlyrexmit;
3647 tp->rxt_flags |= TRXT_F_EARLYREXMT;
3648 goto fastretransmit;