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 * 4. 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 void tcp_dooptions(struct tcpopt *, u_char *, int, boolean_t,
268 static void tcp_pulloutofband(struct socket *,
269 struct tcphdr *, struct mbuf *, int);
270 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
272 static void tcp_xmit_timer(struct tcpcb *, int, tcp_seq);
273 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *, int);
274 static void tcp_sack_rexmt(struct tcpcb *, boolean_t);
275 static boolean_t tcp_sack_limitedxmit(struct tcpcb *);
276 static int tcp_rmx_msl(const struct tcpcb *);
277 static void tcp_established(struct tcpcb *);
278 static boolean_t tcp_recv_dupack(struct tcpcb *, tcp_seq, u_int);
280 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
282 #define ND6_HINT(tp) \
284 if ((tp) && (tp)->t_inpcb && \
285 ((tp)->t_inpcb->inp_vflag & INP_IPV6) && \
286 (tp)->t_inpcb->in6p_route.ro_rt) \
287 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
294 * Indicate whether this ack should be delayed. We can delay the ack if
295 * - delayed acks are enabled and
296 * - there is no delayed ack timer in progress and
297 * - our last ack wasn't a 0-sized window. We never want to delay
298 * the ack that opens up a 0-sized window.
300 #define DELAY_ACK(tp) \
301 (tcp_delack_enabled && !tcp_callout_pending(tp, tp->tt_delack) && \
302 !(tp->t_flags & TF_RXWIN0SENT))
304 #define acceptable_window_update(tp, th, tiwin) \
305 (SEQ_LT(tp->snd_wl1, th->th_seq) || \
306 (tp->snd_wl1 == th->th_seq && \
307 (SEQ_LT(tp->snd_wl2, th->th_ack) || \
308 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))
310 #define iceildiv(n, d) (((n)+(d)-1) / (d))
311 #define need_early_retransmit(tp, ownd) \
312 (tcp_do_early_retransmit && \
313 (tcp_do_eifel_detect && (tp->t_flags & TF_RCVD_TSTMP)) && \
314 ownd < ((tp->t_rxtthresh + 1) * tp->t_maxseg) && \
315 tp->t_dupacks + 1 >= iceildiv(ownd, tp->t_maxseg) && \
316 (!TCP_DO_SACK(tp) || ownd <= tp->t_maxseg || \
317 tcp_sack_has_sacked(&tp->scb, ownd - tp->t_maxseg)))
320 * Returns TRUE, if this segment can be merged with the last
321 * pending segment in the reassemble queue and this segment
322 * does not overlap with the pending segment immediately
323 * preceeding the last pending segment.
325 static __inline boolean_t
326 tcp_paws_canreasslast(const struct tcpcb *tp, const struct tcphdr *th, int tlen)
328 const struct tseg_qent *last, *prev;
330 last = TAILQ_LAST(&tp->t_segq, tsegqe_head);
334 /* This segment comes immediately after the last pending segment */
335 if (last->tqe_th->th_seq + last->tqe_len == th->th_seq) {
336 if (last->tqe_th->th_flags & TH_FIN) {
337 /* No segments should follow segment w/ FIN */
343 if (th->th_seq + tlen != last->tqe_th->th_seq)
345 /* This segment comes immediately before the last pending segment */
347 prev = TAILQ_PREV(last, tsegqe_head, tqe_q);
350 * No pending preceeding segment, we assume this segment
351 * could be reassembled.
356 /* This segment does not overlap with the preceeding segment */
357 if (SEQ_GEQ(th->th_seq, prev->tqe_th->th_seq + prev->tqe_len))
364 tcp_ncr_update_rxtthresh(struct tcpcb *tp)
366 int old_rxtthresh = tp->t_rxtthresh;
367 uint32_t ownd = tp->snd_max - tp->snd_una;
369 tp->t_rxtthresh = max(tcprexmtthresh, ((ownd / tp->t_maxseg) >> 1));
370 if (tp->t_rxtthresh != old_rxtthresh) {
371 tcp_sack_update_lostseq(&tp->scb, tp->snd_una,
372 tp->t_maxseg, tp->t_rxtthresh);
377 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
380 struct tseg_qent *p = NULL;
381 struct tseg_qent *te;
382 struct socket *so = tp->t_inpcb->inp_socket;
386 * Call with th == NULL after become established to
387 * force pre-ESTABLISHED data up to user socket.
393 * Limit the number of segments in the reassembly queue to prevent
394 * holding on to too many segments (and thus running out of mbufs).
395 * Make sure to let the missing segment through which caused this
396 * queue. Always keep one global queue entry spare to be able to
397 * process the missing segment.
399 if (th->th_seq != tp->rcv_nxt &&
400 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
401 tcp_reass_overflows++;
402 tcpstat.tcps_rcvmemdrop++;
404 /* no SACK block to report */
405 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
409 /* Allocate a new queue entry. */
410 te = kmalloc(sizeof(struct tseg_qent), M_TSEGQ, M_INTWAIT | M_NULLOK);
412 tcpstat.tcps_rcvmemdrop++;
414 /* no SACK block to report */
415 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
418 atomic_add_int(&tcp_reass_qsize, 1);
420 if (th->th_flags & TH_FIN)
421 tp->t_flags |= TF_QUEDFIN;
424 * Find a segment which begins after this one does.
426 TAILQ_FOREACH(q, &tp->t_segq, tqe_q) {
427 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
433 * If there is a preceding segment, it may provide some of
434 * our data already. If so, drop the data from the incoming
435 * segment. If it provides all of our data, drop us.
440 /* conversion to int (in i) handles seq wraparound */
441 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
442 if (i > 0) { /* overlaps preceding segment */
444 (TSACK_F_DUPSEG | TSACK_F_ENCLOSESEG);
445 /* enclosing block starts w/ preceding segment */
446 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
448 if (th->th_flags & TH_FIN)
449 p->tqe_th->th_flags |= TH_FIN;
451 /* preceding encloses incoming segment */
452 tp->encloseblk.rblk_end = TCP_SACK_BLKEND(
453 p->tqe_th->th_seq + p->tqe_len,
454 p->tqe_th->th_flags);
455 tcpstat.tcps_rcvduppack++;
456 tcpstat.tcps_rcvdupbyte += *tlenp;
459 atomic_add_int(&tcp_reass_qsize, -1);
461 * Try to present any queued data
462 * at the left window edge to the user.
463 * This is needed after the 3-WHS
466 goto present; /* ??? */
471 /* incoming segment end is enclosing block end */
472 tp->encloseblk.rblk_end = TCP_SACK_BLKEND(
473 th->th_seq + *tlenp, th->th_flags);
474 /* trim end of reported D-SACK block */
475 tp->reportblk.rblk_end = th->th_seq;
478 tcpstat.tcps_rcvoopack++;
479 tcpstat.tcps_rcvoobyte += *tlenp;
482 * While we overlap succeeding segments trim them or,
483 * if they are completely covered, dequeue them.
486 tcp_seq_diff_t i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
487 tcp_seq qend = q->tqe_th->th_seq + q->tqe_len;
488 tcp_seq qend_sack = TCP_SACK_BLKEND(qend, q->tqe_th->th_flags);
489 struct tseg_qent *nq;
493 if (!(tp->sack_flags & TSACK_F_DUPSEG)) {
494 /* first time through */
495 tp->sack_flags |= (TSACK_F_DUPSEG | TSACK_F_ENCLOSESEG);
496 tp->encloseblk = tp->reportblk;
497 /* report trailing duplicate D-SACK segment */
498 tp->reportblk.rblk_start = q->tqe_th->th_seq;
500 if ((tp->sack_flags & TSACK_F_ENCLOSESEG) &&
501 SEQ_GT(qend_sack, tp->encloseblk.rblk_end)) {
502 /* extend enclosing block if one exists */
503 tp->encloseblk.rblk_end = qend_sack;
505 if (i < q->tqe_len) {
506 q->tqe_th->th_seq += i;
512 if (q->tqe_th->th_flags & TH_FIN)
513 th->th_flags |= TH_FIN;
515 nq = TAILQ_NEXT(q, tqe_q);
516 TAILQ_REMOVE(&tp->t_segq, q, tqe_q);
519 atomic_add_int(&tcp_reass_qsize, -1);
523 /* Insert the new segment queue entry into place. */
526 te->tqe_len = *tlenp;
528 /* check if can coalesce with following segment */
529 if (q != NULL && (th->th_seq + *tlenp == q->tqe_th->th_seq)) {
532 te->tqe_len += q->tqe_len;
533 if (q->tqe_th->th_flags & TH_FIN)
534 te->tqe_th->th_flags |= TH_FIN;
535 tend_sack = TCP_SACK_BLKEND(te->tqe_th->th_seq + te->tqe_len,
536 te->tqe_th->th_flags);
538 m_cat(te->tqe_m, q->tqe_m);
539 tp->encloseblk.rblk_end = tend_sack;
541 * When not reporting a duplicate segment, use
542 * the larger enclosing block as the SACK block.
544 if (!(tp->sack_flags & TSACK_F_DUPSEG))
545 tp->reportblk.rblk_end = tend_sack;
546 TAILQ_REMOVE(&tp->t_segq, q, tqe_q);
548 atomic_add_int(&tcp_reass_qsize, -1);
552 TAILQ_INSERT_HEAD(&tp->t_segq, te, tqe_q);
554 /* check if can coalesce with preceding segment */
555 if (p->tqe_th->th_seq + p->tqe_len == th->th_seq) {
556 if (te->tqe_th->th_flags & TH_FIN)
557 p->tqe_th->th_flags |= TH_FIN;
558 p->tqe_len += te->tqe_len;
559 m_cat(p->tqe_m, te->tqe_m);
560 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
562 * When not reporting a duplicate segment, use
563 * the larger enclosing block as the SACK block.
565 if (!(tp->sack_flags & TSACK_F_DUPSEG))
566 tp->reportblk.rblk_start = p->tqe_th->th_seq;
568 atomic_add_int(&tcp_reass_qsize, -1);
570 TAILQ_INSERT_AFTER(&tp->t_segq, p, te, tqe_q);
576 * Present data to user, advancing rcv_nxt through
577 * completed sequence space.
579 if (!TCPS_HAVEESTABLISHED(tp->t_state))
581 q = TAILQ_FIRST(&tp->t_segq);
582 if (q == NULL || q->tqe_th->th_seq != tp->rcv_nxt)
584 tp->rcv_nxt += q->tqe_len;
585 if (!(tp->sack_flags & TSACK_F_DUPSEG)) {
586 /* no SACK block to report since ACK advanced */
587 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
589 /* no enclosing block to report since ACK advanced */
590 tp->sack_flags &= ~TSACK_F_ENCLOSESEG;
591 flags = q->tqe_th->th_flags & TH_FIN;
592 TAILQ_REMOVE(&tp->t_segq, q, tqe_q);
593 KASSERT(TAILQ_EMPTY(&tp->t_segq) ||
594 TAILQ_FIRST(&tp->t_segq)->tqe_th->th_seq != tp->rcv_nxt,
595 ("segment not coalesced"));
596 if (so->so_state & SS_CANTRCVMORE) {
599 lwkt_gettoken(&so->so_rcv.ssb_token);
600 ssb_appendstream(&so->so_rcv, q->tqe_m);
601 lwkt_reltoken(&so->so_rcv.ssb_token);
604 atomic_add_int(&tcp_reass_qsize, -1);
611 * TCP input routine, follows pages 65-76 of the
612 * protocol specification dated September, 1981 very closely.
616 tcp6_input(struct mbuf **mp, int *offp, int proto)
618 struct mbuf *m = *mp;
619 struct in6_ifaddr *ia6;
621 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
624 * draft-itojun-ipv6-tcp-to-anycast
625 * better place to put this in?
627 ia6 = ip6_getdstifaddr(m);
628 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
629 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
630 offsetof(struct ip6_hdr, ip6_dst));
631 return (IPPROTO_DONE);
634 tcp_input(mp, offp, proto);
635 return (IPPROTO_DONE);
640 tcp_input(struct mbuf **mp, int *offp, int proto)
644 struct ip *ip = NULL;
646 struct inpcb *inp = NULL;
652 struct tcpcb *tp = NULL;
654 struct socket *so = NULL;
656 boolean_t ourfinisacked, needoutput = FALSE, delayed_dupack = FALSE;
657 tcp_seq th_dupack = 0; /* XXX gcc warning */
658 u_int to_flags = 0; /* XXX gcc warning */
661 struct tcpopt to; /* options in this segment */
662 struct sockaddr_in *next_hop = NULL;
663 int rstreason; /* For badport_bandlim accounting purposes */
665 struct ip6_hdr *ip6 = NULL;
670 const boolean_t isipv6 = FALSE;
680 tcpstat.tcps_rcvtotal++;
682 if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
685 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
686 KKASSERT(mtag != NULL);
687 next_hop = m_tag_data(mtag);
691 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
695 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
696 ip6 = mtod(m, struct ip6_hdr *);
697 tlen = (sizeof *ip6) + ntohs(ip6->ip6_plen) - off0;
698 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
699 tcpstat.tcps_rcvbadsum++;
702 th = (struct tcphdr *)((caddr_t)ip6 + off0);
705 * Be proactive about unspecified IPv6 address in source.
706 * As we use all-zero to indicate unbounded/unconnected pcb,
707 * unspecified IPv6 address can be used to confuse us.
709 * Note that packets with unspecified IPv6 destination is
710 * already dropped in ip6_input.
712 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
718 * Get IP and TCP header together in first mbuf.
719 * Note: IP leaves IP header in first mbuf.
721 if (off0 > sizeof(struct ip)) {
723 off0 = sizeof(struct ip);
725 /* already checked and pulled up in ip_demux() */
726 KASSERT(m->m_len >= sizeof(struct tcpiphdr),
727 ("TCP header not in one mbuf: m->m_len %d", m->m_len));
728 ip = mtod(m, struct ip *);
729 ipov = (struct ipovly *)ip;
730 th = (struct tcphdr *)((caddr_t)ip + off0);
733 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
734 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
735 th->th_sum = m->m_pkthdr.csum_data;
737 th->th_sum = in_pseudo(ip->ip_src.s_addr,
739 htonl(m->m_pkthdr.csum_data +
742 th->th_sum ^= 0xffff;
745 * Checksum extended TCP header and data.
747 len = sizeof(struct ip) + tlen;
748 bzero(ipov->ih_x1, sizeof ipov->ih_x1);
749 ipov->ih_len = (u_short)tlen;
750 ipov->ih_len = htons(ipov->ih_len);
751 th->th_sum = in_cksum(m, len);
754 tcpstat.tcps_rcvbadsum++;
758 /* Re-initialization for later version check */
759 ip->ip_v = IPVERSION;
764 * Check that TCP offset makes sense,
765 * pull out TCP options and adjust length. XXX
767 off = th->th_off << 2;
768 /* already checked and pulled up in ip_demux() */
769 KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
770 ("bad TCP data offset %d (tlen %d)", off, tlen));
771 tlen -= off; /* tlen is used instead of ti->ti_len */
772 if (off > sizeof(struct tcphdr)) {
774 IP6_EXTHDR_CHECK(m, off0, off, IPPROTO_DONE);
775 ip6 = mtod(m, struct ip6_hdr *);
776 th = (struct tcphdr *)((caddr_t)ip6 + off0);
778 /* already pulled up in ip_demux() */
779 KASSERT(m->m_len >= sizeof(struct ip) + off,
780 ("TCP header and options not in one mbuf: "
781 "m_len %d, off %d", m->m_len, off));
783 optlen = off - sizeof(struct tcphdr);
784 optp = (u_char *)(th + 1);
786 thflags = th->th_flags;
788 #ifdef TCP_DROP_SYNFIN
790 * If the drop_synfin option is enabled, drop all packets with
791 * both the SYN and FIN bits set. This prevents e.g. nmap from
792 * identifying the TCP/IP stack.
794 * This is a violation of the TCP specification.
796 if (drop_synfin && (thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN))
801 * Convert TCP protocol specific fields to host format.
803 th->th_seq = ntohl(th->th_seq);
804 th->th_ack = ntohl(th->th_ack);
805 th->th_win = ntohs(th->th_win);
806 th->th_urp = ntohs(th->th_urp);
809 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
810 * until after ip6_savecontrol() is called and before other functions
811 * which don't want those proto headers.
812 * Because ip6_savecontrol() is going to parse the mbuf to
813 * search for data to be passed up to user-land, it wants mbuf
814 * parameters to be unchanged.
815 * XXX: the call of ip6_savecontrol() has been obsoleted based on
816 * latest version of the advanced API (20020110).
818 drop_hdrlen = off0 + off;
821 * Locate pcb for segment.
824 /* IPFIREWALL_FORWARD section */
825 if (next_hop != NULL && !isipv6) { /* IPv6 support is not there yet */
827 * Transparently forwarded. Pretend to be the destination.
828 * already got one like this?
830 cpu = mycpu->gd_cpuid;
831 inp = in_pcblookup_hash(&tcbinfo[cpu],
832 ip->ip_src, th->th_sport,
833 ip->ip_dst, th->th_dport,
834 0, m->m_pkthdr.rcvif);
837 * It's new. Try to find the ambushing socket.
841 * The rest of the ipfw code stores the port in
843 * (The IP address is still in network order.)
845 in_port_t dport = next_hop->sin_port ?
846 htons(next_hop->sin_port) :
849 cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
850 next_hop->sin_addr.s_addr, dport);
851 inp = in_pcblookup_hash(&tcbinfo[cpu],
852 ip->ip_src, th->th_sport,
853 next_hop->sin_addr, dport,
854 1, m->m_pkthdr.rcvif);
858 inp = in6_pcblookup_hash(&tcbinfo[0],
859 &ip6->ip6_src, th->th_sport,
860 &ip6->ip6_dst, th->th_dport,
861 1, m->m_pkthdr.rcvif);
863 cpu = mycpu->gd_cpuid;
864 inp = in_pcblookup_hash(&tcbinfo[cpu],
865 ip->ip_src, th->th_sport,
866 ip->ip_dst, th->th_dport,
867 1, m->m_pkthdr.rcvif);
872 * If the state is CLOSED (i.e., TCB does not exist) then
873 * all data in the incoming segment is discarded.
874 * If the TCB exists but is in CLOSED state, it is embryonic,
875 * but should either do a listen or a connect soon.
880 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
882 char dbuf[sizeof "aaa.bbb.ccc.ddd"];
883 char sbuf[sizeof "aaa.bbb.ccc.ddd"];
887 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
890 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
893 strcpy(dbuf, inet_ntoa(ip->ip_dst));
894 strcpy(sbuf, inet_ntoa(ip->ip_src));
896 switch (log_in_vain) {
898 if (!(thflags & TH_SYN))
902 "Connection attempt to TCP %s:%d "
903 "from %s:%d flags:0x%02x\n",
904 dbuf, ntohs(th->th_dport), sbuf,
905 ntohs(th->th_sport), thflags);
914 if (thflags & TH_SYN)
923 rstreason = BANDLIM_RST_CLOSEDPORT;
929 if (ipsec6_in_reject_so(m, inp->inp_socket)) {
930 ipsec6stat.in_polvio++;
934 if (ipsec4_in_reject_so(m, inp->inp_socket)) {
935 ipsecstat.in_polvio++;
942 if (ipsec6_in_reject(m, inp))
945 if (ipsec4_in_reject(m, inp))
949 /* Check the minimum TTL for socket. */
951 if ((isipv6 ? ip6->ip6_hlim : ip->ip_ttl) < inp->inp_ip_minttl)
957 rstreason = BANDLIM_RST_CLOSEDPORT;
960 if (tp->t_state <= TCPS_CLOSED)
963 so = inp->inp_socket;
966 if (so->so_options & SO_DEBUG) {
967 ostate = tp->t_state;
969 bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
971 bcopy(ip, tcp_saveipgen, sizeof(*ip));
976 bzero(&to, sizeof to);
978 if (so->so_options & SO_ACCEPTCONN) {
979 struct in_conninfo inc;
982 inc.inc_isipv6 = (isipv6 == TRUE);
985 inc.inc6_faddr = ip6->ip6_src;
986 inc.inc6_laddr = ip6->ip6_dst;
987 inc.inc6_route.ro_rt = NULL; /* XXX */
989 inc.inc_faddr = ip->ip_src;
990 inc.inc_laddr = ip->ip_dst;
991 inc.inc_route.ro_rt = NULL; /* XXX */
993 inc.inc_fport = th->th_sport;
994 inc.inc_lport = th->th_dport;
997 * If the state is LISTEN then ignore segment if it contains
998 * a RST. If the segment contains an ACK then it is bad and
999 * send a RST. If it does not contain a SYN then it is not
1000 * interesting; drop it.
1002 * If the state is SYN_RECEIVED (syncache) and seg contains
1003 * an ACK, but not for our SYN/ACK, send a RST. If the seg
1004 * contains a RST, check the sequence number to see if it
1005 * is a valid reset segment.
1007 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
1008 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) == TH_ACK) {
1009 if (!syncache_expand(&inc, th, &so, m)) {
1011 * No syncache entry, or ACK was not
1012 * for our SYN/ACK. Send a RST.
1014 tcpstat.tcps_badsyn++;
1015 rstreason = BANDLIM_RST_OPENPORT;
1020 * Could not complete 3-way handshake,
1021 * connection is being closed down, and
1022 * syncache will free mbuf.
1025 return(IPPROTO_DONE);
1028 * We must be in the correct protocol thread
1029 * for this connection.
1031 KKASSERT(so->so_port == &curthread->td_msgport);
1034 * Socket is created in state SYN_RECEIVED.
1035 * Continue processing segment.
1038 tp = intotcpcb(inp);
1040 * This is what would have happened in
1041 * tcp_output() when the SYN,ACK was sent.
1043 tp->snd_up = tp->snd_una;
1044 tp->snd_max = tp->snd_nxt = tp->iss + 1;
1045 tp->last_ack_sent = tp->rcv_nxt;
1049 if (thflags & TH_RST) {
1050 syncache_chkrst(&inc, th);
1053 if (thflags & TH_ACK) {
1054 syncache_badack(&inc);
1055 tcpstat.tcps_badsyn++;
1056 rstreason = BANDLIM_RST_OPENPORT;
1063 * Segment's flags are (SYN) or (SYN | FIN).
1067 * If deprecated address is forbidden,
1068 * we do not accept SYN to deprecated interface
1069 * address to prevent any new inbound connection from
1070 * getting established.
1071 * When we do not accept SYN, we send a TCP RST,
1072 * with deprecated source address (instead of dropping
1073 * it). We compromise it as it is much better for peer
1074 * to send a RST, and RST will be the final packet
1077 * If we do not forbid deprecated addresses, we accept
1078 * the SYN packet. RFC2462 does not suggest dropping
1080 * If we decipher RFC2462 5.5.4, it says like this:
1081 * 1. use of deprecated addr with existing
1082 * communication is okay - "SHOULD continue to be
1084 * 2. use of it with new communication:
1085 * (2a) "SHOULD NOT be used if alternate address
1086 * with sufficient scope is available"
1087 * (2b) nothing mentioned otherwise.
1088 * Here we fall into (2b) case as we have no choice in
1089 * our source address selection - we must obey the peer.
1091 * The wording in RFC2462 is confusing, and there are
1092 * multiple description text for deprecated address
1093 * handling - worse, they are not exactly the same.
1094 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1096 if (isipv6 && !ip6_use_deprecated) {
1097 struct in6_ifaddr *ia6;
1099 if ((ia6 = ip6_getdstifaddr(m)) &&
1100 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1102 rstreason = BANDLIM_RST_OPENPORT;
1108 * If it is from this socket, drop it, it must be forged.
1109 * Don't bother responding if the destination was a broadcast.
1111 if (th->th_dport == th->th_sport) {
1113 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
1117 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
1122 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1124 * Note that it is quite possible to receive unicast
1125 * link-layer packets with a broadcast IP address. Use
1126 * in_broadcast() to find them.
1128 if (m->m_flags & (M_BCAST | M_MCAST))
1131 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1132 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
1135 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1136 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1137 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1138 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1142 * SYN appears to be valid; create compressed TCP state
1143 * for syncache, or perform t/tcp connection.
1145 if (so->so_qlen <= so->so_qlimit) {
1146 tcp_dooptions(&to, optp, optlen, TRUE, th->th_ack);
1147 if (!syncache_add(&inc, &to, th, so, m))
1151 * Entry added to syncache, mbuf used to
1152 * send SYN,ACK packet.
1154 return(IPPROTO_DONE);
1161 * Should not happen - syncache should pick up these connections.
1163 * Once we are past handling listen sockets we must be in the
1164 * correct protocol processing thread.
1166 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN state"));
1167 KKASSERT(so->so_port == &curthread->td_msgport);
1169 /* Unscale the window into a 32-bit value. */
1170 if (!(thflags & TH_SYN))
1171 tiwin = th->th_win << tp->snd_scale;
1176 * This is the second part of the MSS DoS prevention code (after
1177 * minmss on the sending side) and it deals with too many too small
1178 * tcp packets in a too short timeframe (1 second).
1180 * XXX Removed. This code was crap. It does not scale to network
1181 * speed, and default values break NFS. Gone.
1186 * Segment received on connection.
1188 * Reset idle time and keep-alive timer. Don't waste time if less
1189 * then a second has elapsed.
1191 if ((int)(ticks - tp->t_rcvtime) > hz)
1192 tcp_timer_keep_activity(tp, thflags);
1196 * XXX this is tradtitional behavior, may need to be cleaned up.
1198 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0, th->th_ack);
1199 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1200 if ((to.to_flags & TOF_SCALE) && (tp->t_flags & TF_REQ_SCALE)) {
1201 tp->t_flags |= TF_RCVD_SCALE;
1202 tp->snd_scale = to.to_requested_s_scale;
1206 * Initial send window; will be updated upon next ACK
1208 tp->snd_wnd = th->th_win;
1210 if (to.to_flags & TOF_TS) {
1211 tp->t_flags |= TF_RCVD_TSTMP;
1212 tp->ts_recent = to.to_tsval;
1213 tp->ts_recent_age = ticks;
1215 if (!(to.to_flags & TOF_MSS))
1217 tcp_mss(tp, to.to_mss);
1219 * Only set the TF_SACK_PERMITTED per-connection flag
1220 * if we got a SACK_PERMITTED option from the other side
1221 * and the global tcp_do_sack variable is true.
1223 if (tcp_do_sack && (to.to_flags & TOF_SACK_PERMITTED))
1224 tp->t_flags |= TF_SACK_PERMITTED;
1228 * Header prediction: check for the two common cases
1229 * of a uni-directional data xfer. If the packet has
1230 * no control flags, is in-sequence, the window didn't
1231 * change and we're not retransmitting, it's a
1232 * candidate. If the length is zero and the ack moved
1233 * forward, we're the sender side of the xfer. Just
1234 * free the data acked & wake any higher level process
1235 * that was blocked waiting for space. If the length
1236 * is non-zero and the ack didn't move, we're the
1237 * receiver side. If we're getting packets in-order
1238 * (the reassembly queue is empty), add the data to
1239 * the socket buffer and note that we need a delayed ack.
1240 * Make sure that the hidden state-flags are also off.
1241 * Since we check for TCPS_ESTABLISHED above, it can only
1244 if (tp->t_state == TCPS_ESTABLISHED &&
1245 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1246 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1247 (!(to.to_flags & TOF_TS) ||
1248 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1249 th->th_seq == tp->rcv_nxt &&
1250 tp->snd_nxt == tp->snd_max) {
1253 * If last ACK falls within this segment's sequence numbers,
1254 * record the timestamp.
1255 * NOTE that the test is modified according to the latest
1256 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1258 if ((to.to_flags & TOF_TS) &&
1259 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1260 tp->ts_recent_age = ticks;
1261 tp->ts_recent = to.to_tsval;
1265 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1266 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1267 tp->snd_cwnd >= tp->snd_wnd &&
1268 !IN_FASTRECOVERY(tp)) {
1270 * This is a pure ack for outstanding data.
1272 ++tcpstat.tcps_predack;
1274 * "bad retransmit" recovery
1276 * If Eifel detection applies, then
1277 * it is deterministic, so use it
1278 * unconditionally over the old heuristic.
1279 * Otherwise, fall back to the old heuristic.
1281 if (tcp_do_eifel_detect &&
1282 (to.to_flags & TOF_TS) && to.to_tsecr &&
1283 (tp->rxt_flags & TRXT_F_FIRSTACCACK)) {
1284 /* Eifel detection applicable. */
1285 if (to.to_tsecr < tp->t_rexmtTS) {
1286 tcp_revert_congestion_state(tp);
1287 ++tcpstat.tcps_eifeldetected;
1288 if (tp->t_rxtshift != 1 ||
1289 ticks >= tp->t_badrxtwin)
1290 ++tcpstat.tcps_rttcantdetect;
1292 } else if (tp->t_rxtshift == 1 &&
1293 ticks < tp->t_badrxtwin) {
1294 tcp_revert_congestion_state(tp);
1295 ++tcpstat.tcps_rttdetected;
1297 tp->rxt_flags &= ~(TRXT_F_FIRSTACCACK |
1298 TRXT_F_FASTREXMT | TRXT_F_EARLYREXMT);
1300 * Recalculate the retransmit timer / rtt.
1302 * Some machines (certain windows boxes)
1303 * send broken timestamp replies during the
1304 * SYN+ACK phase, ignore timestamps of 0.
1306 if ((to.to_flags & TOF_TS) && to.to_tsecr) {
1308 ticks - to.to_tsecr + 1,
1310 } else if (tp->t_rtttime &&
1311 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1313 ticks - tp->t_rtttime,
1316 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1317 acked = th->th_ack - tp->snd_una;
1318 tcpstat.tcps_rcvackpack++;
1319 tcpstat.tcps_rcvackbyte += acked;
1320 sbdrop(&so->so_snd.sb, acked);
1321 tp->snd_recover = th->th_ack - 1;
1322 tp->snd_una = th->th_ack;
1325 * Update window information.
1327 if (tiwin != tp->snd_wnd &&
1328 acceptable_window_update(tp, th, tiwin)) {
1329 /* keep track of pure window updates */
1330 if (tp->snd_wl2 == th->th_ack &&
1331 tiwin > tp->snd_wnd)
1332 tcpstat.tcps_rcvwinupd++;
1333 tp->snd_wnd = tiwin;
1334 tp->snd_wl1 = th->th_seq;
1335 tp->snd_wl2 = th->th_ack;
1336 if (tp->snd_wnd > tp->max_sndwnd)
1337 tp->max_sndwnd = tp->snd_wnd;
1340 ND6_HINT(tp); /* some progress has been done */
1342 * If all outstanding data are acked, stop
1343 * retransmit timer, otherwise restart timer
1344 * using current (possibly backed-off) value.
1345 * If process is waiting for space,
1346 * wakeup/selwakeup/signal. If data
1347 * are ready to send, let tcp_output
1348 * decide between more output or persist.
1350 if (tp->snd_una == tp->snd_max) {
1351 tcp_callout_stop(tp, tp->tt_rexmt);
1352 } else if (!tcp_callout_active(tp,
1354 tcp_callout_reset(tp, tp->tt_rexmt,
1355 tp->t_rxtcur, tcp_timer_rexmt);
1358 if (so->so_snd.ssb_cc > 0 &&
1359 !tcp_output_pending(tp))
1360 tcp_output_fair(tp);
1361 return(IPPROTO_DONE);
1363 } else if (tiwin == tp->snd_wnd &&
1364 th->th_ack == tp->snd_una &&
1365 TAILQ_EMPTY(&tp->t_segq) &&
1366 tlen <= ssb_space(&so->so_rcv)) {
1367 u_long newsize = 0; /* automatic sockbuf scaling */
1369 * This is a pure, in-sequence data packet
1370 * with nothing on the reassembly queue and
1371 * we have enough buffer space to take it.
1373 ++tcpstat.tcps_preddat;
1374 tp->rcv_nxt += tlen;
1375 tcpstat.tcps_rcvpack++;
1376 tcpstat.tcps_rcvbyte += tlen;
1377 ND6_HINT(tp); /* some progress has been done */
1379 * Automatic sizing of receive socket buffer. Often the send
1380 * buffer size is not optimally adjusted to the actual network
1381 * conditions at hand (delay bandwidth product). Setting the
1382 * buffer size too small limits throughput on links with high
1383 * bandwidth and high delay (eg. trans-continental/oceanic links).
1385 * On the receive side the socket buffer memory is only rarely
1386 * used to any significant extent. This allows us to be much
1387 * more aggressive in scaling the receive socket buffer. For
1388 * the case that the buffer space is actually used to a large
1389 * extent and we run out of kernel memory we can simply drop
1390 * the new segments; TCP on the sender will just retransmit it
1391 * later. Setting the buffer size too big may only consume too
1392 * much kernel memory if the application doesn't read() from
1393 * the socket or packet loss or reordering makes use of the
1396 * The criteria to step up the receive buffer one notch are:
1397 * 1. the number of bytes received during the time it takes
1398 * one timestamp to be reflected back to us (the RTT);
1399 * 2. received bytes per RTT is within seven eighth of the
1400 * current socket buffer size;
1401 * 3. receive buffer size has not hit maximal automatic size;
1403 * This algorithm does one step per RTT at most and only if
1404 * we receive a bulk stream w/o packet losses or reorderings.
1405 * Shrinking the buffer during idle times is not necessary as
1406 * it doesn't consume any memory when idle.
1408 * TODO: Only step up if the application is actually serving
1409 * the buffer to better manage the socket buffer resources.
1411 if (tcp_do_autorcvbuf &&
1413 (so->so_rcv.ssb_flags & SSB_AUTOSIZE)) {
1414 if (to.to_tsecr > tp->rfbuf_ts &&
1415 to.to_tsecr - tp->rfbuf_ts < hz) {
1417 (so->so_rcv.ssb_hiwat / 8 * 7) &&
1418 so->so_rcv.ssb_hiwat <
1419 tcp_autorcvbuf_max) {
1421 ulmin(so->so_rcv.ssb_hiwat +
1423 tcp_autorcvbuf_max);
1425 /* Start over with next RTT. */
1429 tp->rfbuf_cnt += tlen; /* add up */
1432 * Add data to socket buffer.
1434 if (so->so_state & SS_CANTRCVMORE) {
1438 * Set new socket buffer size, give up when
1441 * Adjusting the size can mess up ACK
1442 * sequencing when pure window updates are
1443 * being avoided (which is the default),
1446 lwkt_gettoken(&so->so_rcv.ssb_token);
1448 tp->t_flags |= TF_RXRESIZED;
1449 if (!ssb_reserve(&so->so_rcv, newsize,
1451 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1454 (TCP_MAXWIN << tp->rcv_scale)) {
1455 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1458 m_adj(m, drop_hdrlen); /* delayed header drop */
1459 ssb_appendstream(&so->so_rcv, m);
1460 lwkt_reltoken(&so->so_rcv.ssb_token);
1464 * This code is responsible for most of the ACKs
1465 * the TCP stack sends back after receiving a data
1466 * packet. Note that the DELAY_ACK check fails if
1467 * the delack timer is already running, which results
1468 * in an ack being sent every other packet (which is
1471 * We then further aggregate acks by not actually
1472 * sending one until the protocol thread has completed
1473 * processing the current backlog of packets. This
1474 * does not delay the ack any further, but allows us
1475 * to take advantage of the packet aggregation that
1476 * high speed NICs do (usually blocks of 8-10 packets)
1477 * to send a single ack rather then four or five acks,
1478 * greatly reducing the ack rate, the return channel
1479 * bandwidth, and the protocol overhead on both ends.
1481 * Since this also has the effect of slowing down
1482 * the exponential slow-start ramp-up, systems with
1483 * very large bandwidth-delay products might want
1484 * to turn the feature off.
1486 if (DELAY_ACK(tp)) {
1487 tcp_callout_reset(tp, tp->tt_delack,
1488 tcp_delacktime, tcp_timer_delack);
1489 } else if (tcp_aggregate_acks) {
1490 tp->t_flags |= TF_ACKNOW;
1491 if (!(tp->t_flags & TF_ONOUTPUTQ)) {
1492 tp->t_flags |= TF_ONOUTPUTQ;
1493 tp->tt_cpu = mycpu->gd_cpuid;
1495 &tcpcbackq[tp->tt_cpu],
1499 tp->t_flags |= TF_ACKNOW;
1502 return(IPPROTO_DONE);
1507 * Calculate amount of space in receive window,
1508 * and then do TCP input processing.
1509 * Receive window is amount of space in rcv queue,
1510 * but not less than advertised window.
1512 recvwin = ssb_space(&so->so_rcv);
1515 tp->rcv_wnd = imax(recvwin, (int)(tp->rcv_adv - tp->rcv_nxt));
1517 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1521 switch (tp->t_state) {
1523 * If the state is SYN_RECEIVED:
1524 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1526 case TCPS_SYN_RECEIVED:
1527 if ((thflags & TH_ACK) &&
1528 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1529 SEQ_GT(th->th_ack, tp->snd_max))) {
1530 rstreason = BANDLIM_RST_OPENPORT;
1536 * If the state is SYN_SENT:
1537 * if seg contains an ACK, but not for our SYN, drop the input.
1538 * if seg contains a RST, then drop the connection.
1539 * if seg does not contain SYN, then drop it.
1540 * Otherwise this is an acceptable SYN segment
1541 * initialize tp->rcv_nxt and tp->irs
1542 * if seg contains ack then advance tp->snd_una
1543 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1544 * arrange for segment to be acked (eventually)
1545 * continue processing rest of data/controls, beginning with URG
1548 if ((thflags & TH_ACK) &&
1549 (SEQ_LEQ(th->th_ack, tp->iss) ||
1550 SEQ_GT(th->th_ack, tp->snd_max))) {
1551 rstreason = BANDLIM_UNLIMITED;
1554 if (thflags & TH_RST) {
1555 if (thflags & TH_ACK)
1556 tp = tcp_drop(tp, ECONNREFUSED);
1559 if (!(thflags & TH_SYN))
1562 tp->irs = th->th_seq;
1564 if (thflags & TH_ACK) {
1565 /* Our SYN was acked. */
1566 tcpstat.tcps_connects++;
1568 /* Do window scaling on this connection? */
1569 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1570 (TF_RCVD_SCALE | TF_REQ_SCALE))
1571 tp->rcv_scale = tp->request_r_scale;
1572 tp->rcv_adv += tp->rcv_wnd;
1573 tp->snd_una++; /* SYN is acked */
1574 tcp_callout_stop(tp, tp->tt_rexmt);
1576 * If there's data, delay ACK; if there's also a FIN
1577 * ACKNOW will be turned on later.
1579 if (DELAY_ACK(tp) && tlen != 0) {
1580 tcp_callout_reset(tp, tp->tt_delack,
1581 tcp_delacktime, tcp_timer_delack);
1583 tp->t_flags |= TF_ACKNOW;
1586 * Received <SYN,ACK> in SYN_SENT[*] state.
1588 * SYN_SENT --> ESTABLISHED
1589 * SYN_SENT* --> FIN_WAIT_1
1591 tp->t_starttime = ticks;
1592 if (tp->t_flags & TF_NEEDFIN) {
1593 tp->t_state = TCPS_FIN_WAIT_1;
1594 tp->t_flags &= ~TF_NEEDFIN;
1597 tcp_established(tp);
1601 * Received initial SYN in SYN-SENT[*] state =>
1602 * simultaneous open.
1603 * Do 3-way handshake:
1604 * SYN-SENT -> SYN-RECEIVED
1605 * SYN-SENT* -> SYN-RECEIVED*
1607 tp->t_flags |= TF_ACKNOW;
1608 tcp_callout_stop(tp, tp->tt_rexmt);
1609 tp->t_state = TCPS_SYN_RECEIVED;
1613 * Advance th->th_seq to correspond to first data byte.
1614 * If data, trim to stay within window,
1615 * dropping FIN if necessary.
1618 if (tlen > tp->rcv_wnd) {
1619 todrop = tlen - tp->rcv_wnd;
1623 tcpstat.tcps_rcvpackafterwin++;
1624 tcpstat.tcps_rcvbyteafterwin += todrop;
1626 tp->snd_wl1 = th->th_seq - 1;
1627 tp->rcv_up = th->th_seq;
1629 * Client side of transaction: already sent SYN and data.
1630 * If the remote host used T/TCP to validate the SYN,
1631 * our data will be ACK'd; if so, enter normal data segment
1632 * processing in the middle of step 5, ack processing.
1633 * Otherwise, goto step 6.
1635 if (thflags & TH_ACK)
1641 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1642 * do normal processing (we no longer bother with T/TCP).
1646 case TCPS_TIME_WAIT:
1647 break; /* continue normal processing */
1651 * States other than LISTEN or SYN_SENT.
1652 * First check the RST flag and sequence number since reset segments
1653 * are exempt from the timestamp and connection count tests. This
1654 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1655 * below which allowed reset segments in half the sequence space
1656 * to fall though and be processed (which gives forged reset
1657 * segments with a random sequence number a 50 percent chance of
1658 * killing a connection).
1659 * Then check timestamp, if present.
1660 * Then check the connection count, if present.
1661 * Then check that at least some bytes of segment are within
1662 * receive window. If segment begins before rcv_nxt,
1663 * drop leading data (and SYN); if nothing left, just ack.
1666 * If the RST bit is set, check the sequence number to see
1667 * if this is a valid reset segment.
1669 * In all states except SYN-SENT, all reset (RST) segments
1670 * are validated by checking their SEQ-fields. A reset is
1671 * valid if its sequence number is in the window.
1672 * Note: this does not take into account delayed ACKs, so
1673 * we should test against last_ack_sent instead of rcv_nxt.
1674 * The sequence number in the reset segment is normally an
1675 * echo of our outgoing acknowledgement numbers, but some hosts
1676 * send a reset with the sequence number at the rightmost edge
1677 * of our receive window, and we have to handle this case.
1678 * If we have multiple segments in flight, the intial reset
1679 * segment sequence numbers will be to the left of last_ack_sent,
1680 * but they will eventually catch up.
1681 * In any case, it never made sense to trim reset segments to
1682 * fit the receive window since RFC 1122 says:
1683 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1685 * A TCP SHOULD allow a received RST segment to include data.
1688 * It has been suggested that a RST segment could contain
1689 * ASCII text that encoded and explained the cause of the
1690 * RST. No standard has yet been established for such
1693 * If the reset segment passes the sequence number test examine
1695 * SYN_RECEIVED STATE:
1696 * If passive open, return to LISTEN state.
1697 * If active open, inform user that connection was refused.
1698 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1699 * Inform user that connection was reset, and close tcb.
1700 * CLOSING, LAST_ACK STATES:
1703 * Drop the segment - see Stevens, vol. 2, p. 964 and
1706 if (thflags & TH_RST) {
1707 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1708 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1709 switch (tp->t_state) {
1711 case TCPS_SYN_RECEIVED:
1712 so->so_error = ECONNREFUSED;
1715 case TCPS_ESTABLISHED:
1716 case TCPS_FIN_WAIT_1:
1717 case TCPS_FIN_WAIT_2:
1718 case TCPS_CLOSE_WAIT:
1719 so->so_error = ECONNRESET;
1721 tp->t_state = TCPS_CLOSED;
1722 tcpstat.tcps_drops++;
1731 case TCPS_TIME_WAIT:
1739 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1740 * and it's less than ts_recent, drop it.
1742 if ((to.to_flags & TOF_TS) && tp->ts_recent != 0 &&
1743 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1744 /* Check to see if ts_recent is over 24 days old. */
1745 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1747 * Invalidate ts_recent. If this segment updates
1748 * ts_recent, the age will be reset later and ts_recent
1749 * will get a valid value. If it does not, setting
1750 * ts_recent to zero will at least satisfy the
1751 * requirement that zero be placed in the timestamp
1752 * echo reply when ts_recent isn't valid. The
1753 * age isn't reset until we get a valid ts_recent
1754 * because we don't want out-of-order segments to be
1755 * dropped when ts_recent is old.
1758 } else if (tcp_paws_tolerance && tlen != 0 &&
1759 tp->t_state == TCPS_ESTABLISHED &&
1760 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK&&
1761 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1762 th->th_ack == tp->snd_una &&
1763 tiwin == tp->snd_wnd &&
1764 TSTMP_GEQ(to.to_tsval + tcp_paws_tolerance, tp->ts_recent)&&
1765 (th->th_seq == tp->rcv_nxt ||
1766 (SEQ_GT(th->th_seq, tp->rcv_nxt) &&
1767 tcp_paws_canreasslast(tp, th, tlen)))) {
1769 * This tends to prevent valid new segments from being
1770 * dropped by the reordered segments sent by the fast
1771 * retransmission algorithm on the sending side, i.e.
1772 * the fast retransmitted segment w/ larger timestamp
1773 * arrives earlier than the previously sent new segments
1774 * w/ smaller timestamp.
1776 * If following conditions are met, the segment is
1778 * - The segment contains data
1779 * - The connection is established
1780 * - The header does not contain important flags
1781 * - SYN or FIN is not needed
1782 * - It does not acknowledge new data
1783 * - Receive window is not changed
1784 * - The timestamp is within "acceptable" range
1785 * - The new segment is what we are expecting or
1786 * the new segment could be merged w/ the last
1787 * pending segment on the reassemble queue
1789 tcpstat.tcps_pawsaccept++;
1790 tcpstat.tcps_pawsdrop++;
1792 tcpstat.tcps_rcvduppack++;
1793 tcpstat.tcps_rcvdupbyte += tlen;
1794 tcpstat.tcps_pawsdrop++;
1802 * In the SYN-RECEIVED state, validate that the packet belongs to
1803 * this connection before trimming the data to fit the receive
1804 * window. Check the sequence number versus IRS since we know
1805 * the sequence numbers haven't wrapped. This is a partial fix
1806 * for the "LAND" DoS attack.
1808 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1809 rstreason = BANDLIM_RST_OPENPORT;
1813 todrop = tp->rcv_nxt - th->th_seq;
1815 if (TCP_DO_SACK(tp)) {
1816 /* Report duplicate segment at head of packet. */
1817 tp->reportblk.rblk_start = th->th_seq;
1818 tp->reportblk.rblk_end = TCP_SACK_BLKEND(
1819 th->th_seq + tlen, thflags);
1820 if (SEQ_GT(tp->reportblk.rblk_end, tp->rcv_nxt))
1821 tp->reportblk.rblk_end = tp->rcv_nxt;
1822 tp->sack_flags |= (TSACK_F_DUPSEG | TSACK_F_SACKLEFT);
1823 tp->t_flags |= TF_ACKNOW;
1825 if (thflags & TH_SYN) {
1835 * Following if statement from Stevens, vol. 2, p. 960.
1837 if (todrop > tlen ||
1838 (todrop == tlen && !(thflags & TH_FIN))) {
1840 * Any valid FIN must be to the left of the window.
1841 * At this point the FIN must be a duplicate or out
1842 * of sequence; drop it.
1847 * Send an ACK to resynchronize and drop any data.
1848 * But keep on processing for RST or ACK.
1850 tp->t_flags |= TF_ACKNOW;
1852 tcpstat.tcps_rcvduppack++;
1853 tcpstat.tcps_rcvdupbyte += todrop;
1855 tcpstat.tcps_rcvpartduppack++;
1856 tcpstat.tcps_rcvpartdupbyte += todrop;
1858 drop_hdrlen += todrop; /* drop from the top afterwards */
1859 th->th_seq += todrop;
1861 if (th->th_urp > todrop)
1862 th->th_urp -= todrop;
1870 * If new data are received on a connection after the
1871 * user processes are gone, then RST the other end.
1873 if ((so->so_state & SS_NOFDREF) &&
1874 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1876 tcpstat.tcps_rcvafterclose++;
1877 rstreason = BANDLIM_UNLIMITED;
1882 * If segment ends after window, drop trailing data
1883 * (and PUSH and FIN); if nothing left, just ACK.
1885 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1887 tcpstat.tcps_rcvpackafterwin++;
1888 if (todrop >= tlen) {
1889 tcpstat.tcps_rcvbyteafterwin += tlen;
1891 * If a new connection request is received
1892 * while in TIME_WAIT, drop the old connection
1893 * and start over if the sequence numbers
1894 * are above the previous ones.
1896 if (thflags & TH_SYN &&
1897 tp->t_state == TCPS_TIME_WAIT &&
1898 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1903 * If window is closed can only take segments at
1904 * window edge, and have to drop data and PUSH from
1905 * incoming segments. Continue processing, but
1906 * remember to ack. Otherwise, drop segment
1909 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1910 tp->t_flags |= TF_ACKNOW;
1911 tcpstat.tcps_rcvwinprobe++;
1915 tcpstat.tcps_rcvbyteafterwin += todrop;
1918 thflags &= ~(TH_PUSH | TH_FIN);
1922 * If last ACK falls within this segment's sequence numbers,
1923 * record its timestamp.
1925 * 1) That the test incorporates suggestions from the latest
1926 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1927 * 2) That updating only on newer timestamps interferes with
1928 * our earlier PAWS tests, so this check should be solely
1929 * predicated on the sequence space of this segment.
1930 * 3) That we modify the segment boundary check to be
1931 * Last.ACK.Sent <= SEG.SEQ + SEG.LEN
1932 * instead of RFC1323's
1933 * Last.ACK.Sent < SEG.SEQ + SEG.LEN,
1934 * This modified check allows us to overcome RFC1323's
1935 * limitations as described in Stevens TCP/IP Illustrated
1936 * Vol. 2 p.869. In such cases, we can still calculate the
1937 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1939 if ((to.to_flags & TOF_TS) && SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1940 SEQ_LEQ(tp->last_ack_sent, (th->th_seq + tlen
1941 + ((thflags & TH_SYN) != 0)
1942 + ((thflags & TH_FIN) != 0)))) {
1943 tp->ts_recent_age = ticks;
1944 tp->ts_recent = to.to_tsval;
1948 * If a SYN is in the window, then this is an
1949 * error and we send an RST and drop the connection.
1951 if (thflags & TH_SYN) {
1952 tp = tcp_drop(tp, ECONNRESET);
1953 rstreason = BANDLIM_UNLIMITED;
1958 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1959 * flag is on (half-synchronized state), then queue data for
1960 * later processing; else drop segment and return.
1962 if (!(thflags & TH_ACK)) {
1963 if (tp->t_state == TCPS_SYN_RECEIVED ||
1964 (tp->t_flags & TF_NEEDSYN))
1973 switch (tp->t_state) {
1975 * In SYN_RECEIVED state, the ACK acknowledges our SYN, so enter
1976 * ESTABLISHED state and continue processing.
1977 * The ACK was checked above.
1979 case TCPS_SYN_RECEIVED:
1981 tcpstat.tcps_connects++;
1983 /* Do window scaling? */
1984 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1985 (TF_RCVD_SCALE | TF_REQ_SCALE))
1986 tp->rcv_scale = tp->request_r_scale;
1989 * SYN-RECEIVED -> ESTABLISHED
1990 * SYN-RECEIVED* -> FIN-WAIT-1
1992 tp->t_starttime = ticks;
1993 if (tp->t_flags & TF_NEEDFIN) {
1994 tp->t_state = TCPS_FIN_WAIT_1;
1995 tp->t_flags &= ~TF_NEEDFIN;
1997 tcp_established(tp);
2000 * If segment contains data or ACK, will call tcp_reass()
2001 * later; if not, do so now to pass queued data to user.
2003 if (tlen == 0 && !(thflags & TH_FIN))
2004 tcp_reass(tp, NULL, NULL, NULL);
2008 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2009 * ACKs. If the ack is in the range
2010 * tp->snd_una < th->th_ack <= tp->snd_max
2011 * then advance tp->snd_una to th->th_ack and drop
2012 * data from the retransmission queue. If this ACK reflects
2013 * more up to date window information we update our window information.
2015 case TCPS_ESTABLISHED:
2016 case TCPS_FIN_WAIT_1:
2017 case TCPS_FIN_WAIT_2:
2018 case TCPS_CLOSE_WAIT:
2021 case TCPS_TIME_WAIT:
2023 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2024 boolean_t maynotdup = FALSE;
2026 if (TCP_DO_SACK(tp))
2027 tcp_sack_update_scoreboard(tp, &to);
2029 if (tlen != 0 || tiwin != tp->snd_wnd ||
2030 ((thflags & TH_FIN) && !(tp->t_flags & TF_SAWFIN)))
2033 if (!tcp_callout_active(tp, tp->tt_rexmt) ||
2034 th->th_ack != tp->snd_una) {
2036 tcpstat.tcps_rcvdupack++;
2041 #define DELAY_DUPACK \
2043 delayed_dupack = TRUE; \
2044 th_dupack = th->th_ack; \
2045 to_flags = to.to_flags; \
2048 if (!tcp_do_rfc6675 ||
2051 (TOF_SACK | TOF_SACK_REDUNDANT))
2059 if ((thflags & TH_FIN) && !(tp->t_flags & TF_QUEDFIN)) {
2061 * This could happen, if the reassemable
2062 * queue overflew or was drained. Don't
2063 * drop this FIN here; defer the duplicated
2064 * ACK processing until this FIN gets queued.
2071 if (tcp_recv_dupack(tp, th->th_ack, to.to_flags))
2077 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
2079 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2081 * Detected optimistic ACK attack.
2082 * Force slow-start to de-synchronize attack.
2084 tp->snd_cwnd = tp->t_maxseg;
2087 tcpstat.tcps_rcvacktoomuch++;
2091 * If we reach this point, ACK is not a duplicate,
2092 * i.e., it ACKs something we sent.
2094 if (tp->t_flags & TF_NEEDSYN) {
2096 * T/TCP: Connection was half-synchronized, and our
2097 * SYN has been ACK'd (so connection is now fully
2098 * synchronized). Go to non-starred state,
2099 * increment snd_una for ACK of SYN, and check if
2100 * we can do window scaling.
2102 tp->t_flags &= ~TF_NEEDSYN;
2104 /* Do window scaling? */
2105 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
2106 (TF_RCVD_SCALE | TF_REQ_SCALE))
2107 tp->rcv_scale = tp->request_r_scale;
2111 acked = th->th_ack - tp->snd_una;
2112 tcpstat.tcps_rcvackpack++;
2113 tcpstat.tcps_rcvackbyte += acked;
2115 if (tcp_do_eifel_detect && acked > 0 &&
2116 (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
2117 (tp->rxt_flags & TRXT_F_FIRSTACCACK)) {
2118 /* Eifel detection applicable. */
2119 if (to.to_tsecr < tp->t_rexmtTS) {
2120 ++tcpstat.tcps_eifeldetected;
2121 tcp_revert_congestion_state(tp);
2122 if (tp->t_rxtshift != 1 ||
2123 ticks >= tp->t_badrxtwin)
2124 ++tcpstat.tcps_rttcantdetect;
2126 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2128 * If we just performed our first retransmit,
2129 * and the ACK arrives within our recovery window,
2130 * then it was a mistake to do the retransmit
2131 * in the first place. Recover our original cwnd
2132 * and ssthresh, and proceed to transmit where we
2135 tcp_revert_congestion_state(tp);
2136 ++tcpstat.tcps_rttdetected;
2140 * If we have a timestamp reply, update smoothed
2141 * round trip time. If no timestamp is present but
2142 * transmit timer is running and timed sequence
2143 * number was acked, update smoothed round trip time.
2144 * Since we now have an rtt measurement, cancel the
2145 * timer backoff (cf., Phil Karn's retransmit alg.).
2146 * Recompute the initial retransmit timer.
2148 * Some machines (certain windows boxes) send broken
2149 * timestamp replies during the SYN+ACK phase, ignore
2152 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
2153 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1, th->th_ack);
2154 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2155 tcp_xmit_timer(tp, ticks - tp->t_rtttime, th->th_ack);
2156 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2159 * If no data (only SYN) was ACK'd,
2160 * skip rest of ACK processing.
2165 /* Stop looking for an acceptable ACK since one was received. */
2166 tp->rxt_flags &= ~(TRXT_F_FIRSTACCACK |
2167 TRXT_F_FASTREXMT | TRXT_F_EARLYREXMT);
2169 if (acked > so->so_snd.ssb_cc) {
2170 tp->snd_wnd -= so->so_snd.ssb_cc;
2171 sbdrop(&so->so_snd.sb, (int)so->so_snd.ssb_cc);
2172 ourfinisacked = TRUE;
2174 sbdrop(&so->so_snd.sb, acked);
2175 tp->snd_wnd -= acked;
2176 ourfinisacked = FALSE;
2181 * Update window information.
2183 if (acceptable_window_update(tp, th, tiwin)) {
2184 /* keep track of pure window updates */
2185 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2186 tiwin > tp->snd_wnd)
2187 tcpstat.tcps_rcvwinupd++;
2188 tp->snd_wnd = tiwin;
2189 tp->snd_wl1 = th->th_seq;
2190 tp->snd_wl2 = th->th_ack;
2191 if (tp->snd_wnd > tp->max_sndwnd)
2192 tp->max_sndwnd = tp->snd_wnd;
2196 tp->snd_una = th->th_ack;
2197 if (TCP_DO_SACK(tp))
2198 tcp_sack_update_scoreboard(tp, &to);
2199 if (IN_FASTRECOVERY(tp)) {
2200 if (SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2201 EXIT_FASTRECOVERY(tp);
2204 * If the congestion window was inflated
2205 * to account for the other side's
2206 * cached packets, retract it.
2208 if (!TCP_DO_SACK(tp))
2209 tp->snd_cwnd = tp->snd_ssthresh;
2212 * Window inflation should have left us
2213 * with approximately snd_ssthresh outstanding
2214 * data. But, in case we would be inclined
2215 * to send a burst, better do it using
2218 if (SEQ_GT(th->th_ack + tp->snd_cwnd,
2219 tp->snd_max + 2 * tp->t_maxseg))
2221 (tp->snd_max - tp->snd_una) +
2226 if (TCP_DO_SACK(tp)) {
2227 tp->snd_max_rexmt = tp->snd_max;
2229 tp->snd_una == tp->rexmt_high);
2231 tcp_newreno_partial_ack(tp, th, acked);
2237 * Open the congestion window. When in slow-start,
2238 * open exponentially: maxseg per packet. Otherwise,
2239 * open linearly: maxseg per window.
2241 if (tp->snd_cwnd <= tp->snd_ssthresh) {
2243 (SEQ_LT(tp->snd_nxt, tp->snd_max) ?
2244 tp->t_maxseg : 2 * tp->t_maxseg);
2247 tp->snd_cwnd += tcp_do_abc ?
2248 min(acked, abc_sslimit) : tp->t_maxseg;
2250 /* linear increase */
2251 tp->snd_wacked += tcp_do_abc ? acked :
2253 if (tp->snd_wacked >= tp->snd_cwnd) {
2254 tp->snd_wacked -= tp->snd_cwnd;
2255 tp->snd_cwnd += tp->t_maxseg;
2258 tp->snd_cwnd = min(tp->snd_cwnd,
2259 TCP_MAXWIN << tp->snd_scale);
2260 tp->snd_recover = th->th_ack - 1;
2262 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2263 tp->snd_nxt = tp->snd_una;
2266 * If all outstanding data is acked, stop retransmit
2267 * timer and remember to restart (more output or persist).
2268 * If there is more data to be acked, restart retransmit
2269 * timer, using current (possibly backed-off) value.
2271 if (th->th_ack == tp->snd_max) {
2272 tcp_callout_stop(tp, tp->tt_rexmt);
2274 } else if (!tcp_callout_active(tp, tp->tt_persist)) {
2275 tcp_callout_reset(tp, tp->tt_rexmt, tp->t_rxtcur,
2279 switch (tp->t_state) {
2281 * In FIN_WAIT_1 STATE in addition to the processing
2282 * for the ESTABLISHED state if our FIN is now acknowledged
2283 * then enter FIN_WAIT_2.
2285 case TCPS_FIN_WAIT_1:
2286 if (ourfinisacked) {
2288 * If we can't receive any more
2289 * data, then closing user can proceed.
2290 * Starting the timer is contrary to the
2291 * specification, but if we don't get a FIN
2292 * we'll hang forever.
2294 if (so->so_state & SS_CANTRCVMORE) {
2295 soisdisconnected(so);
2296 tcp_callout_reset(tp, tp->tt_2msl,
2297 tp->t_maxidle, tcp_timer_2msl);
2299 tp->t_state = TCPS_FIN_WAIT_2;
2304 * In CLOSING STATE in addition to the processing for
2305 * the ESTABLISHED state if the ACK acknowledges our FIN
2306 * then enter the TIME-WAIT state, otherwise ignore
2310 if (ourfinisacked) {
2311 tp->t_state = TCPS_TIME_WAIT;
2312 tcp_canceltimers(tp);
2313 tcp_callout_reset(tp, tp->tt_2msl,
2314 2 * tcp_rmx_msl(tp),
2316 soisdisconnected(so);
2321 * In LAST_ACK, we may still be waiting for data to drain
2322 * and/or to be acked, as well as for the ack of our FIN.
2323 * If our FIN is now acknowledged, delete the TCB,
2324 * enter the closed state and return.
2327 if (ourfinisacked) {
2334 * In TIME_WAIT state the only thing that should arrive
2335 * is a retransmission of the remote FIN. Acknowledge
2336 * it and restart the finack timer.
2338 case TCPS_TIME_WAIT:
2339 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2347 * Update window information.
2348 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2350 if ((thflags & TH_ACK) &&
2351 acceptable_window_update(tp, th, tiwin)) {
2352 /* keep track of pure window updates */
2353 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2354 tiwin > tp->snd_wnd)
2355 tcpstat.tcps_rcvwinupd++;
2356 tp->snd_wnd = tiwin;
2357 tp->snd_wl1 = th->th_seq;
2358 tp->snd_wl2 = th->th_ack;
2359 if (tp->snd_wnd > tp->max_sndwnd)
2360 tp->max_sndwnd = tp->snd_wnd;
2365 * Process segments with URG.
2367 if ((thflags & TH_URG) && th->th_urp &&
2368 !TCPS_HAVERCVDFIN(tp->t_state)) {
2370 * This is a kludge, but if we receive and accept
2371 * random urgent pointers, we'll crash in
2372 * soreceive. It's hard to imagine someone
2373 * actually wanting to send this much urgent data.
2375 if (th->th_urp + so->so_rcv.ssb_cc > sb_max) {
2376 th->th_urp = 0; /* XXX */
2377 thflags &= ~TH_URG; /* XXX */
2378 goto dodata; /* XXX */
2381 * If this segment advances the known urgent pointer,
2382 * then mark the data stream. This should not happen
2383 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2384 * a FIN has been received from the remote side.
2385 * In these states we ignore the URG.
2387 * According to RFC961 (Assigned Protocols),
2388 * the urgent pointer points to the last octet
2389 * of urgent data. We continue, however,
2390 * to consider it to indicate the first octet
2391 * of data past the urgent section as the original
2392 * spec states (in one of two places).
2394 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
2395 tp->rcv_up = th->th_seq + th->th_urp;
2396 so->so_oobmark = so->so_rcv.ssb_cc +
2397 (tp->rcv_up - tp->rcv_nxt) - 1;
2398 if (so->so_oobmark == 0)
2399 sosetstate(so, SS_RCVATMARK);
2401 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2404 * Remove out of band data so doesn't get presented to user.
2405 * This can happen independent of advancing the URG pointer,
2406 * but if two URG's are pending at once, some out-of-band
2407 * data may creep in... ick.
2409 if (th->th_urp <= (u_long)tlen &&
2410 !(so->so_options & SO_OOBINLINE)) {
2411 /* hdr drop is delayed */
2412 tcp_pulloutofband(so, th, m, drop_hdrlen);
2416 * If no out of band data is expected,
2417 * pull receive urgent pointer along
2418 * with the receive window.
2420 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2421 tp->rcv_up = tp->rcv_nxt;
2426 * Process the segment text, merging it into the TCP sequencing queue,
2427 * and arranging for acknowledgment of receipt if necessary.
2428 * This process logically involves adjusting tp->rcv_wnd as data
2429 * is presented to the user (this happens in tcp_usrreq.c,
2430 * case PRU_RCVD). If a FIN has already been received on this
2431 * connection then we just ignore the text.
2433 if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
2434 if (thflags & TH_FIN)
2435 tp->t_flags |= TF_SAWFIN;
2436 m_adj(m, drop_hdrlen); /* delayed header drop */
2438 * Insert segment which includes th into TCP reassembly queue
2439 * with control block tp. Set thflags to whether reassembly now
2440 * includes a segment with FIN. This handles the common case
2441 * inline (segment is the next to be received on an established
2442 * connection, and the queue is empty), avoiding linkage into
2443 * and removal from the queue and repetition of various
2445 * Set DELACK for segments received in order, but ack
2446 * immediately when segments are out of order (so
2447 * fast retransmit can work).
2449 if (th->th_seq == tp->rcv_nxt &&
2450 TAILQ_EMPTY(&tp->t_segq) &&
2451 TCPS_HAVEESTABLISHED(tp->t_state)) {
2452 if (thflags & TH_FIN)
2453 tp->t_flags |= TF_QUEDFIN;
2454 if (DELAY_ACK(tp)) {
2455 tcp_callout_reset(tp, tp->tt_delack,
2456 tcp_delacktime, tcp_timer_delack);
2458 tp->t_flags |= TF_ACKNOW;
2460 tp->rcv_nxt += tlen;
2461 thflags = th->th_flags & TH_FIN;
2462 tcpstat.tcps_rcvpack++;
2463 tcpstat.tcps_rcvbyte += tlen;
2465 if (so->so_state & SS_CANTRCVMORE) {
2468 lwkt_gettoken(&so->so_rcv.ssb_token);
2469 ssb_appendstream(&so->so_rcv, m);
2470 lwkt_reltoken(&so->so_rcv.ssb_token);
2474 if (!(tp->sack_flags & TSACK_F_DUPSEG)) {
2475 /* Initialize SACK report block. */
2476 tp->reportblk.rblk_start = th->th_seq;
2477 tp->reportblk.rblk_end = TCP_SACK_BLKEND(
2478 th->th_seq + tlen, thflags);
2480 thflags = tcp_reass(tp, th, &tlen, m);
2481 tp->t_flags |= TF_ACKNOW;
2485 * Note the amount of data that peer has sent into
2486 * our window, in order to estimate the sender's
2489 len = so->so_rcv.ssb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2496 * If FIN is received ACK the FIN and let the user know
2497 * that the connection is closing.
2499 if (thflags & TH_FIN) {
2500 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
2503 * If connection is half-synchronized
2504 * (ie NEEDSYN flag on) then delay ACK,
2505 * so it may be piggybacked when SYN is sent.
2506 * Otherwise, since we received a FIN then no
2507 * more input can be expected, send ACK now.
2509 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN)) {
2510 tcp_callout_reset(tp, tp->tt_delack,
2511 tcp_delacktime, tcp_timer_delack);
2513 tp->t_flags |= TF_ACKNOW;
2518 switch (tp->t_state) {
2520 * In SYN_RECEIVED and ESTABLISHED STATES
2521 * enter the CLOSE_WAIT state.
2523 case TCPS_SYN_RECEIVED:
2524 tp->t_starttime = ticks;
2526 case TCPS_ESTABLISHED:
2527 tp->t_state = TCPS_CLOSE_WAIT;
2531 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2532 * enter the CLOSING state.
2534 case TCPS_FIN_WAIT_1:
2535 tp->t_state = TCPS_CLOSING;
2539 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2540 * starting the time-wait timer, turning off the other
2543 case TCPS_FIN_WAIT_2:
2544 tp->t_state = TCPS_TIME_WAIT;
2545 tcp_canceltimers(tp);
2546 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2548 soisdisconnected(so);
2552 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2554 case TCPS_TIME_WAIT:
2555 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2562 if (so->so_options & SO_DEBUG)
2563 tcp_trace(TA_INPUT, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2567 * Delayed duplicated ACK processing
2569 if (delayed_dupack && tcp_recv_dupack(tp, th_dupack, to_flags))
2573 * Return any desired output.
2575 if ((tp->t_flags & TF_ACKNOW) ||
2576 (needoutput && tcp_sack_report_needed(tp))) {
2577 tcp_output_cancel(tp);
2578 tcp_output_fair(tp);
2579 } else if (needoutput && !tcp_output_pending(tp)) {
2580 tcp_output_fair(tp);
2582 tcp_sack_report_cleanup(tp);
2583 return(IPPROTO_DONE);
2587 * Generate an ACK dropping incoming segment if it occupies
2588 * sequence space, where the ACK reflects our state.
2590 * We can now skip the test for the RST flag since all
2591 * paths to this code happen after packets containing
2592 * RST have been dropped.
2594 * In the SYN-RECEIVED state, don't send an ACK unless the
2595 * segment we received passes the SYN-RECEIVED ACK test.
2596 * If it fails send a RST. This breaks the loop in the
2597 * "LAND" DoS attack, and also prevents an ACK storm
2598 * between two listening ports that have been sent forged
2599 * SYN segments, each with the source address of the other.
2601 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2602 (SEQ_GT(tp->snd_una, th->th_ack) ||
2603 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2604 rstreason = BANDLIM_RST_OPENPORT;
2608 if (so->so_options & SO_DEBUG)
2609 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2612 tp->t_flags |= TF_ACKNOW;
2614 tcp_sack_report_cleanup(tp);
2615 return(IPPROTO_DONE);
2619 * Generate a RST, dropping incoming segment.
2620 * Make ACK acceptable to originator of segment.
2621 * Don't bother to respond if destination was broadcast/multicast.
2623 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
2626 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2627 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2630 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2631 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2632 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2633 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2636 /* IPv6 anycast check is done at tcp6_input() */
2639 * Perform bandwidth limiting.
2642 if (badport_bandlim(rstreason) < 0)
2647 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2648 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2650 if (thflags & TH_ACK)
2651 /* mtod() below is safe as long as hdr dropping is delayed */
2652 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2655 if (thflags & TH_SYN)
2657 /* mtod() below is safe as long as hdr dropping is delayed */
2658 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2659 (tcp_seq)0, TH_RST | TH_ACK);
2662 tcp_sack_report_cleanup(tp);
2663 return(IPPROTO_DONE);
2667 * Drop space held by incoming segment and return.
2670 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2671 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2675 tcp_sack_report_cleanup(tp);
2676 return(IPPROTO_DONE);
2680 * Parse TCP options and place in tcpopt.
2683 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn,
2689 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2691 if (opt == TCPOPT_EOL)
2693 if (opt == TCPOPT_NOP)
2699 if (optlen < 2 || optlen > cnt)
2704 if (optlen != TCPOLEN_MAXSEG)
2708 to->to_flags |= TOF_MSS;
2709 bcopy(cp + 2, &to->to_mss, sizeof to->to_mss);
2710 to->to_mss = ntohs(to->to_mss);
2713 if (optlen != TCPOLEN_WINDOW)
2717 to->to_flags |= TOF_SCALE;
2718 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2720 case TCPOPT_TIMESTAMP:
2721 if (optlen != TCPOLEN_TIMESTAMP)
2723 to->to_flags |= TOF_TS;
2724 bcopy(cp + 2, &to->to_tsval, sizeof to->to_tsval);
2725 to->to_tsval = ntohl(to->to_tsval);
2726 bcopy(cp + 6, &to->to_tsecr, sizeof to->to_tsecr);
2727 to->to_tsecr = ntohl(to->to_tsecr);
2729 * If echoed timestamp is later than the current time,
2730 * fall back to non RFC1323 RTT calculation.
2732 if (to->to_tsecr != 0 && TSTMP_GT(to->to_tsecr, ticks))
2735 case TCPOPT_SACK_PERMITTED:
2736 if (optlen != TCPOLEN_SACK_PERMITTED)
2740 to->to_flags |= TOF_SACK_PERMITTED;
2743 if ((optlen - 2) & 0x07) /* not multiple of 8 */
2745 to->to_nsackblocks = (optlen - 2) / 8;
2746 to->to_sackblocks = (struct raw_sackblock *) (cp + 2);
2747 to->to_flags |= TOF_SACK;
2748 for (i = 0; i < to->to_nsackblocks; i++) {
2749 struct raw_sackblock *r = &to->to_sackblocks[i];
2751 r->rblk_start = ntohl(r->rblk_start);
2752 r->rblk_end = ntohl(r->rblk_end);
2754 if (SEQ_LEQ(r->rblk_end, r->rblk_start)) {
2756 * Invalid SACK block; discard all
2759 tcpstat.tcps_rcvbadsackopt++;
2760 to->to_nsackblocks = 0;
2761 to->to_sackblocks = NULL;
2762 to->to_flags &= ~TOF_SACK;
2766 if ((to->to_flags & TOF_SACK) &&
2767 tcp_sack_ndsack_blocks(to->to_sackblocks,
2768 to->to_nsackblocks, ack))
2769 to->to_flags |= TOF_DSACK;
2771 #ifdef TCP_SIGNATURE
2773 * XXX In order to reply to a host which has set the
2774 * TCP_SIGNATURE option in its initial SYN, we have to
2775 * record the fact that the option was observed here
2776 * for the syncache code to perform the correct response.
2778 case TCPOPT_SIGNATURE:
2779 if (optlen != TCPOLEN_SIGNATURE)
2781 to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2783 #endif /* TCP_SIGNATURE */
2791 * Pull out of band byte out of a segment so
2792 * it doesn't appear in the user's data queue.
2793 * It is still reflected in the segment length for
2794 * sequencing purposes.
2795 * "off" is the delayed to be dropped hdrlen.
2798 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
2800 int cnt = off + th->th_urp - 1;
2803 if (m->m_len > cnt) {
2804 char *cp = mtod(m, caddr_t) + cnt;
2805 struct tcpcb *tp = sototcpcb(so);
2808 tp->t_oobflags |= TCPOOB_HAVEDATA;
2809 bcopy(cp + 1, cp, m->m_len - cnt - 1);
2811 if (m->m_flags & M_PKTHDR)
2820 panic("tcp_pulloutofband");
2824 * Collect new round-trip time estimate
2825 * and update averages and current timeout.
2828 tcp_xmit_timer(struct tcpcb *tp, int rtt, tcp_seq ack)
2832 tcpstat.tcps_rttupdated++;
2834 if ((tp->rxt_flags & TRXT_F_REBASERTO) &&
2835 SEQ_GT(ack, tp->snd_max_prev)) {
2836 #ifdef DEBUG_EIFEL_RESPONSE
2837 kprintf("srtt/rttvar, prev %d/%d, cur %d/%d, ",
2838 tp->t_srtt_prev, tp->t_rttvar_prev,
2839 tp->t_srtt, tp->t_rttvar);
2842 tcpstat.tcps_eifelresponse++;
2844 tp->rxt_flags &= ~TRXT_F_REBASERTO;
2845 tp->t_srtt = max(tp->t_srtt_prev, (rtt << TCP_RTT_SHIFT));
2846 tp->t_rttvar = max(tp->t_rttvar_prev,
2847 (rtt << (TCP_RTTVAR_SHIFT - 1)));
2848 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2849 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2851 #ifdef DEBUG_EIFEL_RESPONSE
2852 kprintf("new %d/%d ", tp->t_srtt, tp->t_rttvar);
2854 } else if (tp->t_srtt != 0) {
2858 * srtt is stored as fixed point with 5 bits after the
2859 * binary point (i.e., scaled by 8). The following magic
2860 * is equivalent to the smoothing algorithm in rfc793 with
2861 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2862 * point). Adjust rtt to origin 0.
2864 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2865 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2867 if ((tp->t_srtt += delta) <= 0)
2871 * We accumulate a smoothed rtt variance (actually, a
2872 * smoothed mean difference), then set the retransmit
2873 * timer to smoothed rtt + 4 times the smoothed variance.
2874 * rttvar is stored as fixed point with 4 bits after the
2875 * binary point (scaled by 16). The following is
2876 * equivalent to rfc793 smoothing with an alpha of .75
2877 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2878 * rfc793's wired-in beta.
2882 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2883 if ((tp->t_rttvar += delta) <= 0)
2885 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2886 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2889 * No rtt measurement yet - use the unsmoothed rtt.
2890 * Set the variance to half the rtt (so our first
2891 * retransmit happens at 3*rtt).
2893 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2894 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2895 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2900 #ifdef DEBUG_EIFEL_RESPONSE
2902 kprintf("| rxtcur prev %d, old %d, ",
2903 tp->t_rxtcur_prev, tp->t_rxtcur);
2908 * the retransmit should happen at rtt + 4 * rttvar.
2909 * Because of the way we do the smoothing, srtt and rttvar
2910 * will each average +1/2 tick of bias. When we compute
2911 * the retransmit timer, we want 1/2 tick of rounding and
2912 * 1 extra tick because of +-1/2 tick uncertainty in the
2913 * firing of the timer. The bias will give us exactly the
2914 * 1.5 tick we need. But, because the bias is
2915 * statistical, we have to test that we don't drop below
2916 * the minimum feasible timer (which is 2 ticks).
2918 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2919 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2922 if (tp->t_rxtcur < tp->t_rxtcur_prev + tcp_eifel_rtoinc) {
2924 * RFC4015 requires that the new RTO is at least
2925 * 2*G (tcp_eifel_rtoinc) greater then the RTO
2926 * (t_rxtcur_prev) when the spurious retransmit
2929 * The above condition could be true, if the SRTT
2930 * and RTTVAR used to calculate t_rxtcur_prev
2931 * resulted in a value less than t_rttmin. So
2932 * simply increasing SRTT by tcp_eifel_rtoinc when
2933 * preparing for the Eifel response could not ensure
2934 * that the new RTO will be tcp_eifel_rtoinc greater
2937 tp->t_rxtcur = tp->t_rxtcur_prev + tcp_eifel_rtoinc;
2939 #ifdef DEBUG_EIFEL_RESPONSE
2940 kprintf("new %d\n", tp->t_rxtcur);
2945 * We received an ack for a packet that wasn't retransmitted;
2946 * it is probably safe to discard any error indications we've
2947 * received recently. This isn't quite right, but close enough
2948 * for now (a route might have failed after we sent a segment,
2949 * and the return path might not be symmetrical).
2951 tp->t_softerror = 0;
2955 * Determine a reasonable value for maxseg size.
2956 * If the route is known, check route for mtu.
2957 * If none, use an mss that can be handled on the outgoing
2958 * interface without forcing IP to fragment; if bigger than
2959 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2960 * to utilize large mbufs. If no route is found, route has no mtu,
2961 * or the destination isn't local, use a default, hopefully conservative
2962 * size (usually 512 or the default IP max size, but no more than the mtu
2963 * of the interface), as we can't discover anything about intervening
2964 * gateways or networks. We also initialize the congestion/slow start
2965 * window to be a single segment if the destination isn't local.
2966 * While looking at the routing entry, we also initialize other path-dependent
2967 * parameters from pre-set or cached values in the routing entry.
2969 * Also take into account the space needed for options that we
2970 * send regularly. Make maxseg shorter by that amount to assure
2971 * that we can send maxseg amount of data even when the options
2972 * are present. Store the upper limit of the length of options plus
2975 * NOTE that this routine is only called when we process an incoming
2976 * segment, for outgoing segments only tcp_mssopt is called.
2979 tcp_mss(struct tcpcb *tp, int offer)
2985 struct inpcb *inp = tp->t_inpcb;
2988 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2989 size_t min_protoh = isipv6 ?
2990 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2991 sizeof(struct tcpiphdr);
2993 const boolean_t isipv6 = FALSE;
2994 const size_t min_protoh = sizeof(struct tcpiphdr);
2998 rt = tcp_rtlookup6(&inp->inp_inc);
3000 rt = tcp_rtlookup(&inp->inp_inc);
3002 tp->t_maxopd = tp->t_maxseg =
3003 (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3007 so = inp->inp_socket;
3010 * Offer == 0 means that there was no MSS on the SYN segment,
3011 * in this case we use either the interface mtu or tcp_mssdflt.
3013 * An offer which is too large will be cut down later.
3017 if (in6_localaddr(&inp->in6p_faddr)) {
3018 offer = ND_IFINFO(rt->rt_ifp)->linkmtu -
3021 offer = tcp_v6mssdflt;
3024 if (in_localaddr(inp->inp_faddr))
3025 offer = ifp->if_mtu - min_protoh;
3027 offer = tcp_mssdflt;
3032 * Prevent DoS attack with too small MSS. Round up
3033 * to at least minmss.
3035 * Sanity check: make sure that maxopd will be large
3036 * enough to allow some data on segments even is the
3037 * all the option space is used (40bytes). Otherwise
3038 * funny things may happen in tcp_output.
3040 offer = max(offer, tcp_minmss);
3041 offer = max(offer, 64);
3043 rt->rt_rmx.rmx_mssopt = offer;
3046 * While we're here, check if there's an initial rtt
3047 * or rttvar. Convert from the route-table units
3048 * to scaled multiples of the slow timeout timer.
3050 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
3052 * XXX the lock bit for RTT indicates that the value
3053 * is also a minimum value; this is subject to time.
3055 if (rt->rt_rmx.rmx_locks & RTV_RTT)
3056 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
3057 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
3058 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3059 tcpstat.tcps_usedrtt++;
3060 if (rt->rt_rmx.rmx_rttvar) {
3061 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
3062 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
3063 tcpstat.tcps_usedrttvar++;
3065 /* default variation is +- 1 rtt */
3067 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3069 TCPT_RANGESET(tp->t_rxtcur,
3070 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3071 tp->t_rttmin, TCPTV_REXMTMAX);
3075 * if there's an mtu associated with the route, use it
3076 * else, use the link mtu. Take the smaller of mss or offer
3079 if (rt->rt_rmx.rmx_mtu) {
3080 mss = rt->rt_rmx.rmx_mtu - min_protoh;
3083 mss = ND_IFINFO(rt->rt_ifp)->linkmtu - min_protoh;
3085 mss = ifp->if_mtu - min_protoh;
3087 mss = min(mss, offer);
3090 * maxopd stores the maximum length of data AND options
3091 * in a segment; maxseg is the amount of data in a normal
3092 * segment. We need to store this value (maxopd) apart
3093 * from maxseg, because now every segment carries options
3094 * and thus we normally have somewhat less data in segments.
3098 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
3099 ((tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3100 mss -= TCPOLEN_TSTAMP_APPA;
3102 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3104 mss &= ~(MCLBYTES-1);
3107 mss = mss / MCLBYTES * MCLBYTES;
3110 * If there's a pipesize, change the socket buffer
3111 * to that size. Make the socket buffers an integral
3112 * number of mss units; if the mss is larger than
3113 * the socket buffer, decrease the mss.
3116 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
3118 bufsize = so->so_snd.ssb_hiwat;
3122 bufsize = roundup(bufsize, mss);
3123 if (bufsize > sb_max)
3125 if (bufsize > so->so_snd.ssb_hiwat)
3126 ssb_reserve(&so->so_snd, bufsize, so, NULL);
3131 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
3133 bufsize = so->so_rcv.ssb_hiwat;
3134 if (bufsize > mss) {
3135 bufsize = roundup(bufsize, mss);
3136 if (bufsize > sb_max)
3138 if (bufsize > so->so_rcv.ssb_hiwat) {
3139 lwkt_gettoken(&so->so_rcv.ssb_token);
3140 ssb_reserve(&so->so_rcv, bufsize, so, NULL);
3141 lwkt_reltoken(&so->so_rcv.ssb_token);
3146 * Set the slow-start flight size
3148 * NOTE: t_maxseg must have been configured!
3150 tp->snd_cwnd = tcp_initial_window(tp);
3152 if (rt->rt_rmx.rmx_ssthresh) {
3154 * There's some sort of gateway or interface
3155 * buffer limit on the path. Use this to set
3156 * the slow start threshhold, but set the
3157 * threshold to no less than 2*mss.
3159 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3160 tcpstat.tcps_usedssthresh++;
3165 * Determine the MSS option to send on an outgoing SYN.
3168 tcp_mssopt(struct tcpcb *tp)
3173 ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3174 int min_protoh = isipv6 ?
3175 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
3176 sizeof(struct tcpiphdr);
3178 const boolean_t isipv6 = FALSE;
3179 const size_t min_protoh = sizeof(struct tcpiphdr);
3183 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
3185 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
3187 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3189 return (rt->rt_ifp->if_mtu - min_protoh);
3193 * When a partial ack arrives, force the retransmission of the
3194 * next unacknowledged segment. Do not exit Fast Recovery.
3196 * Implement the Slow-but-Steady variant of NewReno by restarting the
3197 * the retransmission timer. Turn it off here so it can be restarted
3198 * later in tcp_output().
3201 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th, int acked)
3203 tcp_seq old_snd_nxt = tp->snd_nxt;
3204 u_long ocwnd = tp->snd_cwnd;
3206 tcp_callout_stop(tp, tp->tt_rexmt);
3208 tp->snd_nxt = th->th_ack;
3209 /* Set snd_cwnd to one segment beyond acknowledged offset. */
3210 tp->snd_cwnd = tp->t_maxseg;
3211 tp->t_flags |= TF_ACKNOW;
3213 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3214 tp->snd_nxt = old_snd_nxt;
3215 /* partial window deflation */
3217 tp->snd_cwnd = ocwnd - acked + tp->t_maxseg;
3219 tp->snd_cwnd = tp->t_maxseg;
3223 * In contrast to the Slow-but-Steady NewReno variant,
3224 * we do not reset the retransmission timer for SACK retransmissions,
3225 * except when retransmitting snd_una.
3228 tcp_sack_rexmt(struct tcpcb *tp, boolean_t force)
3230 tcp_seq old_snd_nxt = tp->snd_nxt;
3231 u_long ocwnd = tp->snd_cwnd;
3233 int nseg = 0; /* consecutive new segments */
3234 int nseg_rexmt = 0; /* retransmitted segments */
3238 uint32_t unsacked = tcp_sack_first_unsacked_len(tp);
3241 * Try to fill the first hole in the receiver's
3244 maxrexmt = howmany(unsacked, tp->t_maxseg);
3245 if (maxrexmt > tcp_force_sackrxt)
3246 maxrexmt = tcp_force_sackrxt;
3250 pipe = tcp_sack_compute_pipe(tp);
3251 while (((tcp_seq_diff_t)(ocwnd - pipe) >= (tcp_seq_diff_t)tp->t_maxseg
3252 || (force && nseg_rexmt < maxrexmt && nseg == 0)) &&
3253 (!tcp_do_smartsack || nseg < TCP_SACK_MAXBURST)) {
3254 tcp_seq old_snd_max, old_rexmt_high, nextrexmt;
3255 uint32_t sent, seglen;
3259 old_rexmt_high = tp->rexmt_high;
3260 if (!tcp_sack_nextseg(tp, &nextrexmt, &seglen, &rescue)) {
3261 tp->rexmt_high = old_rexmt_high;
3266 * If the next tranmission is a rescue retranmission,
3267 * we check whether we have already sent some data
3268 * (either new segments or retransmitted segments)
3269 * into the the network or not. Since the idea of rescue
3270 * retransmission is to sustain ACK clock, as long as
3271 * some segments are in the network, ACK clock will be
3274 if (rescue && (nseg_rexmt > 0 || nseg > 0)) {
3275 tp->rexmt_high = old_rexmt_high;
3279 if (nextrexmt == tp->snd_max)
3283 tp->snd_nxt = nextrexmt;
3284 tp->snd_cwnd = nextrexmt - tp->snd_una + seglen;
3285 old_snd_max = tp->snd_max;
3286 if (nextrexmt == tp->snd_una)
3287 tcp_callout_stop(tp, tp->tt_rexmt);
3288 tp->t_flags |= TF_XMITNOW;
3289 error = tcp_output(tp);
3291 tp->rexmt_high = old_rexmt_high;
3294 sent = tp->snd_nxt - nextrexmt;
3296 tp->rexmt_high = old_rexmt_high;
3300 tcpstat.tcps_sndsackpack++;
3301 tcpstat.tcps_sndsackbyte += sent;
3304 tcpstat.tcps_sackrescue++;
3305 tp->rexmt_rescue = tp->snd_nxt;
3306 tp->sack_flags |= TSACK_F_SACKRESCUED;
3309 if (SEQ_LT(nextrexmt, old_snd_max) &&
3310 SEQ_LT(tp->rexmt_high, tp->snd_nxt)) {
3311 tp->rexmt_high = seq_min(tp->snd_nxt, old_snd_max);
3312 if (tcp_aggressive_rescuesack &&
3313 (tp->sack_flags & TSACK_F_SACKRESCUED) &&
3314 SEQ_LT(tp->rexmt_rescue, tp->rexmt_high)) {
3315 /* Drag RescueRxt along with HighRxt */
3316 tp->rexmt_rescue = tp->rexmt_high;
3320 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3321 tp->snd_nxt = old_snd_nxt;
3322 tp->snd_cwnd = ocwnd;
3326 * Return TRUE, if some new segments are sent
3329 tcp_sack_limitedxmit(struct tcpcb *tp)
3331 tcp_seq oldsndnxt = tp->snd_nxt;
3332 tcp_seq oldsndmax = tp->snd_max;
3333 u_long ocwnd = tp->snd_cwnd;
3334 uint32_t pipe, sent;
3335 boolean_t ret = FALSE;
3336 tcp_seq_diff_t cwnd_left;
3339 tp->rexmt_high = tp->snd_una - 1;
3340 pipe = tcp_sack_compute_pipe(tp);
3341 cwnd_left = (tcp_seq_diff_t)(ocwnd - pipe);
3342 if (cwnd_left < (tcp_seq_diff_t)tp->t_maxseg)
3345 if (tcp_do_smartsack)
3346 cwnd_left = ulmin(cwnd_left, tp->t_maxseg * TCP_SACK_MAXBURST);
3348 next = tp->snd_nxt = tp->snd_max;
3349 tp->snd_cwnd = tp->snd_nxt - tp->snd_una +
3350 rounddown(cwnd_left, tp->t_maxseg);
3352 tp->t_flags |= TF_XMITNOW;
3355 sent = tp->snd_nxt - next;
3357 tcpstat.tcps_sndlimited += howmany(sent, tp->t_maxseg);
3361 if (SEQ_LT(oldsndnxt, oldsndmax)) {
3362 KASSERT(SEQ_GEQ(oldsndnxt, tp->snd_una),
3363 ("snd_una moved in other threads"));
3364 tp->snd_nxt = oldsndnxt;
3366 tp->snd_cwnd = ocwnd;
3368 if (ret && TCP_DO_NCR(tp))
3369 tcp_ncr_update_rxtthresh(tp);
3375 * Reset idle time and keep-alive timer, typically called when a valid
3376 * tcp packet is received but may also be called when FASTKEEP is set
3377 * to prevent the previous long-timeout from calculating to a drop.
3379 * Only update t_rcvtime for non-SYN packets.
3381 * Handle the case where one side thinks the connection is established
3382 * but the other side has, say, rebooted without cleaning out the
3383 * connection. The SYNs could be construed as an attack and wind
3384 * up ignored, but in case it isn't an attack we can validate the
3385 * connection by forcing a keepalive.
3388 tcp_timer_keep_activity(struct tcpcb *tp, int thflags)
3390 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3391 if ((thflags & (TH_SYN | TH_ACK)) == TH_SYN) {
3392 tp->t_flags |= TF_KEEPALIVE;
3393 tcp_callout_reset(tp, tp->tt_keep, hz / 2,
3396 tp->t_rcvtime = ticks;
3397 tp->t_flags &= ~TF_KEEPALIVE;
3398 tcp_callout_reset(tp, tp->tt_keep,
3406 tcp_rmx_msl(const struct tcpcb *tp)
3409 struct inpcb *inp = tp->t_inpcb;
3412 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3414 const boolean_t isipv6 = FALSE;
3418 rt = tcp_rtlookup6(&inp->inp_inc);
3420 rt = tcp_rtlookup(&inp->inp_inc);
3421 if (rt == NULL || rt->rt_rmx.rmx_msl == 0)
3424 msl = (rt->rt_rmx.rmx_msl * hz) / 1000;
3432 tcp_established(struct tcpcb *tp)
3434 tp->t_state = TCPS_ESTABLISHED;
3435 tcp_callout_reset(tp, tp->tt_keep, tp->t_keepidle, tcp_timer_keep);
3437 if (tp->t_rxtsyn > 0) {
3440 * "If the timer expires awaiting the ACK of a SYN segment
3441 * and the TCP implementation is using an RTO less than 3
3442 * seconds, the RTO MUST be re-initialized to 3 seconds
3443 * when data transmission begins"
3445 if (tp->t_rxtcur < TCPTV_RTOBASE3)
3446 tp->t_rxtcur = TCPTV_RTOBASE3;
3451 * Returns TRUE, if the ACK should be dropped
3454 tcp_recv_dupack(struct tcpcb *tp, tcp_seq th_ack, u_int to_flags)
3456 boolean_t fast_sack_rexmt = TRUE;
3458 tcpstat.tcps_rcvdupack++;
3461 * We have outstanding data (other than a window probe),
3462 * this is a completely duplicate ack (ie, window info
3463 * didn't change), the ack is the biggest we've seen and
3464 * we've seen exactly our rexmt threshhold of them, so
3465 * assume a packet has been dropped and retransmit it.
3466 * Kludge snd_nxt & the congestion window so we send only
3469 if (IN_FASTRECOVERY(tp)) {
3470 if (TCP_DO_SACK(tp)) {
3471 boolean_t force = FALSE;
3473 if (tp->snd_una == tp->rexmt_high &&
3474 (to_flags & (TOF_SACK | TOF_SACK_REDUNDANT)) ==
3477 * New segments got SACKed and
3478 * no retransmit yet.
3483 /* No artifical cwnd inflation. */
3484 tcp_sack_rexmt(tp, force);
3487 * Dup acks mean that packets have left
3488 * the network (they're now cached at the
3489 * receiver) so bump cwnd by the amount in
3490 * the receiver to keep a constant cwnd
3491 * packets in the network.
3493 tp->snd_cwnd += tp->t_maxseg;
3497 } else if (SEQ_LT(th_ack, tp->snd_recover)) {
3500 } else if (tcp_ignore_redun_dsack && TCP_DO_SACK(tp) &&
3501 (to_flags & (TOF_DSACK | TOF_SACK_REDUNDANT)) ==
3502 (TOF_DSACK | TOF_SACK_REDUNDANT)) {
3504 * If the ACK carries DSACK and other SACK blocks
3505 * carry information that we have already known,
3506 * don't count this ACK as duplicate ACK. This
3507 * prevents spurious early retransmit and fast
3508 * retransmit. This also meets the requirement of
3509 * RFC3042 that new segments should not be sent if
3510 * the SACK blocks do not contain new information
3511 * (XXX we actually loosen the requirment that only
3512 * DSACK is checked here).
3514 * This kind of ACKs are usually sent after spurious
3517 /* Do nothing; don't change t_dupacks */
3519 } else if (tp->t_dupacks == 0 && TCP_DO_NCR(tp)) {
3520 tcp_ncr_update_rxtthresh(tp);
3523 if (++tp->t_dupacks == tp->t_rxtthresh) {
3524 tcp_seq old_snd_nxt;
3528 if (tcp_do_eifel_detect && (tp->t_flags & TF_RCVD_TSTMP)) {
3529 tcp_save_congestion_state(tp);
3530 tp->rxt_flags |= TRXT_F_FASTREXMT;
3533 * We know we're losing at the current window size,
3534 * so do congestion avoidance: set ssthresh to half
3535 * the current window and pull our congestion window
3536 * back to the new ssthresh.
3538 win = min(tp->snd_wnd, tp->snd_cwnd) / 2 / tp->t_maxseg;
3541 tp->snd_ssthresh = win * tp->t_maxseg;
3542 ENTER_FASTRECOVERY(tp);
3543 tp->snd_recover = tp->snd_max;
3544 tcp_callout_stop(tp, tp->tt_rexmt);
3546 old_snd_nxt = tp->snd_nxt;
3547 tp->snd_nxt = th_ack;
3548 if (TCP_DO_SACK(tp)) {
3551 rxtlen = tcp_sack_first_unsacked_len(tp);
3552 if (rxtlen > tp->t_maxseg)
3553 rxtlen = tp->t_maxseg;
3554 tp->snd_cwnd = rxtlen;
3556 tp->snd_cwnd = tp->t_maxseg;
3559 ++tcpstat.tcps_sndfastrexmit;
3560 tp->snd_cwnd = tp->snd_ssthresh;
3561 tp->rexmt_high = tp->snd_nxt;
3562 tp->sack_flags &= ~TSACK_F_SACKRESCUED;
3563 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3564 tp->snd_nxt = old_snd_nxt;
3565 KASSERT(tp->snd_limited <= 2, ("tp->snd_limited too big"));
3566 if (TCP_DO_SACK(tp)) {
3567 if (fast_sack_rexmt)
3568 tcp_sack_rexmt(tp, FALSE);
3570 tp->snd_cwnd += tp->t_maxseg *
3571 (tp->t_dupacks - tp->snd_limited);
3573 } else if ((tcp_do_rfc6675 && TCP_DO_SACK(tp)) || TCP_DO_NCR(tp)) {
3575 * The RFC6675 recommends to reduce the byte threshold,
3576 * and enter fast retransmit if IsLost(snd_una). However,
3577 * if we use IsLost(snd_una) based fast retransmit here,
3578 * segments reordering will cause spurious retransmit. So
3579 * we defer the IsLost(snd_una) based fast retransmit until
3580 * the extended limited transmit can't send any segments and
3581 * early retransmit can't be done.
3583 if (tcp_rfc6675_rxt && tcp_do_rfc6675 &&
3584 tcp_sack_islost(&tp->scb, tp->snd_una))
3585 goto fastretransmit;
3587 if (tcp_do_limitedtransmit || TCP_DO_NCR(tp)) {
3588 if (!tcp_sack_limitedxmit(tp)) {
3589 /* outstanding data */
3590 uint32_t ownd = tp->snd_max - tp->snd_una;
3592 if (need_early_retransmit(tp, ownd)) {
3593 ++tcpstat.tcps_sndearlyrexmit;
3594 tp->rxt_flags |= TRXT_F_EARLYREXMT;
3595 goto fastretransmit;
3596 } else if (tcp_do_rfc6675 &&
3597 tcp_sack_islost(&tp->scb, tp->snd_una)) {
3598 fast_sack_rexmt = FALSE;
3599 goto fastretransmit;
3603 } else if (tcp_do_limitedtransmit) {
3604 u_long oldcwnd = tp->snd_cwnd;
3605 tcp_seq oldsndmax = tp->snd_max;
3606 tcp_seq oldsndnxt = tp->snd_nxt;
3607 /* outstanding data */
3608 uint32_t ownd = tp->snd_max - tp->snd_una;
3611 KASSERT(tp->t_dupacks == 1 || tp->t_dupacks == 2,
3612 ("dupacks not 1 or 2"));
3613 if (tp->t_dupacks == 1)
3614 tp->snd_limited = 0;
3615 tp->snd_nxt = tp->snd_max;
3616 tp->snd_cwnd = ownd +
3617 (tp->t_dupacks - tp->snd_limited) * tp->t_maxseg;
3618 tp->t_flags |= TF_XMITNOW;
3621 if (SEQ_LT(oldsndnxt, oldsndmax)) {
3622 KASSERT(SEQ_GEQ(oldsndnxt, tp->snd_una),
3623 ("snd_una moved in other threads"));
3624 tp->snd_nxt = oldsndnxt;
3626 tp->snd_cwnd = oldcwnd;
3627 sent = tp->snd_max - oldsndmax;
3628 if (sent > tp->t_maxseg) {
3629 KASSERT((tp->t_dupacks == 2 && tp->snd_limited == 0) ||
3630 (sent == tp->t_maxseg + 1 &&
3631 (tp->t_flags & TF_SENTFIN)),
3633 KASSERT(sent <= tp->t_maxseg * 2,
3634 ("sent too many segments"));
3635 tp->snd_limited = 2;
3636 tcpstat.tcps_sndlimited += 2;
3637 } else if (sent > 0) {
3639 ++tcpstat.tcps_sndlimited;
3640 } else if (need_early_retransmit(tp, ownd)) {
3641 ++tcpstat.tcps_sndearlyrexmit;
3642 tp->rxt_flags |= TRXT_F_EARLYREXMT;
3643 goto fastretransmit;