2 * Copyright (c) 2002, 2003, 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2002, 2003, 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
36 * The Regents of the University of California. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
67 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
71 #include "opt_inet6.h"
72 #include "opt_ipsec.h"
73 #include "opt_tcpdebug.h"
74 #include "opt_tcp_input.h"
76 #include <sys/param.h>
77 #include <sys/systm.h>
78 #include <sys/kernel.h>
79 #include <sys/sysctl.h>
80 #include <sys/malloc.h>
82 #include <sys/proc.h> /* for proc0 declaration */
83 #include <sys/protosw.h>
84 #include <sys/socket.h>
85 #include <sys/socketvar.h>
86 #include <sys/syslog.h>
87 #include <sys/in_cksum.h>
89 #include <sys/socketvar2.h>
91 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
92 #include <machine/stdarg.h>
95 #include <net/route.h>
97 #include <netinet/in.h>
98 #include <netinet/in_systm.h>
99 #include <netinet/ip.h>
100 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
101 #include <netinet/in_var.h>
102 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
103 #include <netinet/in_pcb.h>
104 #include <netinet/ip_var.h>
105 #include <netinet/ip6.h>
106 #include <netinet/icmp6.h>
107 #include <netinet6/nd6.h>
108 #include <netinet6/ip6_var.h>
109 #include <netinet6/in6_pcb.h>
110 #include <netinet/tcp.h>
111 #include <netinet/tcp_fsm.h>
112 #include <netinet/tcp_seq.h>
113 #include <netinet/tcp_timer.h>
114 #include <netinet/tcp_timer2.h>
115 #include <netinet/tcp_var.h>
116 #include <netinet6/tcp6_var.h>
117 #include <netinet/tcpip.h>
120 #include <netinet/tcp_debug.h>
122 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
123 struct tcphdr tcp_savetcp;
127 #include <netproto/ipsec/ipsec.h>
128 #include <netproto/ipsec/ipsec6.h>
132 #include <netinet6/ipsec.h>
133 #include <netinet6/ipsec6.h>
134 #include <netproto/key/key.h>
137 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
139 static int log_in_vain = 0;
140 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
141 &log_in_vain, 0, "Log all incoming TCP connections");
143 static int blackhole = 0;
144 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
145 &blackhole, 0, "Do not send RST when dropping refused connections");
147 int tcp_delack_enabled = 1;
148 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
149 &tcp_delack_enabled, 0,
150 "Delay ACK to try and piggyback it onto a data packet");
152 #ifdef TCP_DROP_SYNFIN
153 static int drop_synfin = 0;
154 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
155 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
158 static int tcp_do_limitedtransmit = 1;
159 SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
160 &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
162 static int tcp_do_early_retransmit = 1;
163 SYSCTL_INT(_net_inet_tcp, OID_AUTO, earlyretransmit, CTLFLAG_RW,
164 &tcp_do_early_retransmit, 0, "Early retransmit");
166 int tcp_aggregate_acks = 1;
167 SYSCTL_INT(_net_inet_tcp, OID_AUTO, aggregate_acks, CTLFLAG_RW,
168 &tcp_aggregate_acks, 0, "Aggregate built-up acks into one ack");
170 int tcp_do_rfc3390 = 1;
171 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
173 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
175 static int tcp_do_eifel_detect = 1;
176 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
177 &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
179 static int tcp_do_abc = 1;
180 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc, CTLFLAG_RW,
182 "TCP Appropriate Byte Counting (RFC 3465)");
185 * Define as tunable for easy testing with SACK on and off.
186 * Warning: do not change setting in the middle of an existing active TCP flow,
187 * else strange things might happen to that flow.
190 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sack, CTLFLAG_RW,
191 &tcp_do_sack, 0, "Enable SACK Algorithms");
193 int tcp_do_smartsack = 1;
194 SYSCTL_INT(_net_inet_tcp, OID_AUTO, smartsack, CTLFLAG_RW,
195 &tcp_do_smartsack, 0, "Enable Smart SACK Algorithms");
197 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
198 "TCP Segment Reassembly Queue");
200 int tcp_reass_maxseg = 0;
201 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
202 &tcp_reass_maxseg, 0,
203 "Global maximum number of TCP Segments in Reassembly Queue");
205 int tcp_reass_qsize = 0;
206 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
208 "Global number of TCP Segments currently in Reassembly Queue");
210 static int tcp_reass_overflows = 0;
211 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
212 &tcp_reass_overflows, 0,
213 "Global number of TCP Segment Reassembly Queue Overflows");
215 int tcp_do_autorcvbuf = 1;
216 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
217 &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
219 int tcp_autorcvbuf_inc = 16*1024;
220 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
221 &tcp_autorcvbuf_inc, 0,
222 "Incrementor step size of automatic receive buffer");
224 int tcp_autorcvbuf_max = 2*1024*1024;
225 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
226 &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
228 int tcp_sosnd_agglim = 2;
229 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sosnd_agglim, CTLFLAG_RW,
230 &tcp_sosnd_agglim, 0, "TCP sosend mbuf aggregation limit");
232 int tcp_sosnd_async = 1;
233 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sosnd_async, CTLFLAG_RW,
234 &tcp_sosnd_async, 0, "TCP asynchronized pru_send");
236 static void tcp_dooptions(struct tcpopt *, u_char *, int, boolean_t);
237 static void tcp_pulloutofband(struct socket *,
238 struct tcphdr *, struct mbuf *, int);
239 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
241 static void tcp_xmit_timer(struct tcpcb *, int);
242 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *, int);
243 static void tcp_sack_rexmt(struct tcpcb *, struct tcphdr *);
244 static int tcp_rmx_msl(const struct tcpcb *);
246 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
248 #define ND6_HINT(tp) \
250 if ((tp) && (tp)->t_inpcb && \
251 ((tp)->t_inpcb->inp_vflag & INP_IPV6) && \
252 (tp)->t_inpcb->in6p_route.ro_rt) \
253 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
260 * Indicate whether this ack should be delayed. We can delay the ack if
261 * - delayed acks are enabled and
262 * - there is no delayed ack timer in progress and
263 * - our last ack wasn't a 0-sized window. We never want to delay
264 * the ack that opens up a 0-sized window.
266 #define DELAY_ACK(tp) \
267 (tcp_delack_enabled && !tcp_callout_pending(tp, tp->tt_delack) && \
268 !(tp->t_flags & TF_RXWIN0SENT))
270 #define acceptable_window_update(tp, th, tiwin) \
271 (SEQ_LT(tp->snd_wl1, th->th_seq) || \
272 (tp->snd_wl1 == th->th_seq && \
273 (SEQ_LT(tp->snd_wl2, th->th_ack) || \
274 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))
277 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
280 struct tseg_qent *p = NULL;
281 struct tseg_qent *te;
282 struct socket *so = tp->t_inpcb->inp_socket;
286 * Call with th == NULL after become established to
287 * force pre-ESTABLISHED data up to user socket.
293 * Limit the number of segments in the reassembly queue to prevent
294 * holding on to too many segments (and thus running out of mbufs).
295 * Make sure to let the missing segment through which caused this
296 * queue. Always keep one global queue entry spare to be able to
297 * process the missing segment.
299 if (th->th_seq != tp->rcv_nxt &&
300 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
301 tcp_reass_overflows++;
302 tcpstat.tcps_rcvmemdrop++;
304 /* no SACK block to report */
305 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
309 /* Allocate a new queue entry. */
310 te = kmalloc(sizeof(struct tseg_qent), M_TSEGQ, M_INTWAIT | M_NULLOK);
312 tcpstat.tcps_rcvmemdrop++;
314 /* no SACK block to report */
315 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
318 atomic_add_int(&tcp_reass_qsize, 1);
321 * Find a segment which begins after this one does.
323 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
324 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
330 * If there is a preceding segment, it may provide some of
331 * our data already. If so, drop the data from the incoming
332 * segment. If it provides all of our data, drop us.
337 /* conversion to int (in i) handles seq wraparound */
338 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
339 if (i > 0) { /* overlaps preceding segment */
340 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
341 /* enclosing block starts w/ preceding segment */
342 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
344 /* preceding encloses incoming segment */
345 tp->encloseblk.rblk_end = p->tqe_th->th_seq +
347 tcpstat.tcps_rcvduppack++;
348 tcpstat.tcps_rcvdupbyte += *tlenp;
351 atomic_add_int(&tcp_reass_qsize, -1);
353 * Try to present any queued data
354 * at the left window edge to the user.
355 * This is needed after the 3-WHS
358 goto present; /* ??? */
363 /* incoming segment end is enclosing block end */
364 tp->encloseblk.rblk_end = th->th_seq + *tlenp +
365 ((th->th_flags & TH_FIN) != 0);
366 /* trim end of reported D-SACK block */
367 tp->reportblk.rblk_end = th->th_seq;
370 tcpstat.tcps_rcvoopack++;
371 tcpstat.tcps_rcvoobyte += *tlenp;
374 * While we overlap succeeding segments trim them or,
375 * if they are completely covered, dequeue them.
378 tcp_seq_diff_t i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
379 tcp_seq qend = q->tqe_th->th_seq + q->tqe_len;
380 struct tseg_qent *nq;
384 if (!(tp->t_flags & TF_DUPSEG)) { /* first time through */
385 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
386 tp->encloseblk = tp->reportblk;
387 /* report trailing duplicate D-SACK segment */
388 tp->reportblk.rblk_start = q->tqe_th->th_seq;
390 if ((tp->t_flags & TF_ENCLOSESEG) &&
391 SEQ_GT(qend, tp->encloseblk.rblk_end)) {
392 /* extend enclosing block if one exists */
393 tp->encloseblk.rblk_end = qend;
395 if (i < q->tqe_len) {
396 q->tqe_th->th_seq += i;
402 nq = LIST_NEXT(q, tqe_q);
403 LIST_REMOVE(q, tqe_q);
406 atomic_add_int(&tcp_reass_qsize, -1);
410 /* Insert the new segment queue entry into place. */
413 te->tqe_len = *tlenp;
415 /* check if can coalesce with following segment */
416 if (q != NULL && (th->th_seq + *tlenp == q->tqe_th->th_seq)) {
417 tcp_seq tend = te->tqe_th->th_seq + te->tqe_len;
419 te->tqe_len += q->tqe_len;
420 if (q->tqe_th->th_flags & TH_FIN)
421 te->tqe_th->th_flags |= TH_FIN;
422 m_cat(te->tqe_m, q->tqe_m);
423 tp->encloseblk.rblk_end = tend;
425 * When not reporting a duplicate segment, use
426 * the larger enclosing block as the SACK block.
428 if (!(tp->t_flags & TF_DUPSEG))
429 tp->reportblk.rblk_end = tend;
430 LIST_REMOVE(q, tqe_q);
432 atomic_add_int(&tcp_reass_qsize, -1);
436 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
438 /* check if can coalesce with preceding segment */
439 if (p->tqe_th->th_seq + p->tqe_len == th->th_seq) {
440 p->tqe_len += te->tqe_len;
441 m_cat(p->tqe_m, te->tqe_m);
442 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
444 * When not reporting a duplicate segment, use
445 * the larger enclosing block as the SACK block.
447 if (!(tp->t_flags & TF_DUPSEG))
448 tp->reportblk.rblk_start = p->tqe_th->th_seq;
450 atomic_add_int(&tcp_reass_qsize, -1);
452 LIST_INSERT_AFTER(p, te, tqe_q);
458 * Present data to user, advancing rcv_nxt through
459 * completed sequence space.
461 if (!TCPS_HAVEESTABLISHED(tp->t_state))
463 q = LIST_FIRST(&tp->t_segq);
464 if (q == NULL || q->tqe_th->th_seq != tp->rcv_nxt)
466 tp->rcv_nxt += q->tqe_len;
467 if (!(tp->t_flags & TF_DUPSEG)) {
468 /* no SACK block to report since ACK advanced */
469 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
471 /* no enclosing block to report since ACK advanced */
472 tp->t_flags &= ~TF_ENCLOSESEG;
473 flags = q->tqe_th->th_flags & TH_FIN;
474 LIST_REMOVE(q, tqe_q);
475 KASSERT(LIST_EMPTY(&tp->t_segq) ||
476 LIST_FIRST(&tp->t_segq)->tqe_th->th_seq != tp->rcv_nxt,
477 ("segment not coalesced"));
478 if (so->so_state & SS_CANTRCVMORE) {
481 lwkt_gettoken(&so->so_rcv.ssb_token);
482 ssb_appendstream(&so->so_rcv, q->tqe_m);
483 lwkt_reltoken(&so->so_rcv.ssb_token);
486 atomic_add_int(&tcp_reass_qsize, -1);
493 * TCP input routine, follows pages 65-76 of the
494 * protocol specification dated September, 1981 very closely.
498 tcp6_input(struct mbuf **mp, int *offp, int proto)
500 struct mbuf *m = *mp;
501 struct in6_ifaddr *ia6;
503 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
506 * draft-itojun-ipv6-tcp-to-anycast
507 * better place to put this in?
509 ia6 = ip6_getdstifaddr(m);
510 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
513 ip6 = mtod(m, struct ip6_hdr *);
514 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
515 offsetof(struct ip6_hdr, ip6_dst));
516 return (IPPROTO_DONE);
519 tcp_input(mp, offp, proto);
520 return (IPPROTO_DONE);
525 tcp_input(struct mbuf **mp, int *offp, int proto)
529 struct ip *ip = NULL;
531 struct inpcb *inp = NULL;
537 struct tcpcb *tp = NULL;
539 struct socket *so = NULL;
541 boolean_t ourfinisacked, needoutput = FALSE;
544 struct tcpopt to; /* options in this segment */
545 struct sockaddr_in *next_hop = NULL;
546 int rstreason; /* For badport_bandlim accounting purposes */
548 struct ip6_hdr *ip6 = NULL;
553 const boolean_t isipv6 = FALSE;
563 tcpstat.tcps_rcvtotal++;
565 if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
568 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
569 KKASSERT(mtag != NULL);
570 next_hop = m_tag_data(mtag);
574 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
578 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
579 ip6 = mtod(m, struct ip6_hdr *);
580 tlen = (sizeof *ip6) + ntohs(ip6->ip6_plen) - off0;
581 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
582 tcpstat.tcps_rcvbadsum++;
585 th = (struct tcphdr *)((caddr_t)ip6 + off0);
588 * Be proactive about unspecified IPv6 address in source.
589 * As we use all-zero to indicate unbounded/unconnected pcb,
590 * unspecified IPv6 address can be used to confuse us.
592 * Note that packets with unspecified IPv6 destination is
593 * already dropped in ip6_input.
595 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
601 * Get IP and TCP header together in first mbuf.
602 * Note: IP leaves IP header in first mbuf.
604 if (off0 > sizeof(struct ip)) {
606 off0 = sizeof(struct ip);
608 /* already checked and pulled up in ip_demux() */
609 KASSERT(m->m_len >= sizeof(struct tcpiphdr),
610 ("TCP header not in one mbuf: m->m_len %d", m->m_len));
611 ip = mtod(m, struct ip *);
612 ipov = (struct ipovly *)ip;
613 th = (struct tcphdr *)((caddr_t)ip + off0);
616 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
617 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
618 th->th_sum = m->m_pkthdr.csum_data;
620 th->th_sum = in_pseudo(ip->ip_src.s_addr,
622 htonl(m->m_pkthdr.csum_data +
625 th->th_sum ^= 0xffff;
628 * Checksum extended TCP header and data.
630 len = sizeof(struct ip) + tlen;
631 bzero(ipov->ih_x1, sizeof ipov->ih_x1);
632 ipov->ih_len = (u_short)tlen;
633 ipov->ih_len = htons(ipov->ih_len);
634 th->th_sum = in_cksum(m, len);
637 tcpstat.tcps_rcvbadsum++;
641 /* Re-initialization for later version check */
642 ip->ip_v = IPVERSION;
647 * Check that TCP offset makes sense,
648 * pull out TCP options and adjust length. XXX
650 off = th->th_off << 2;
651 /* already checked and pulled up in ip_demux() */
652 KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
653 ("bad TCP data offset %d (tlen %d)", off, tlen));
654 tlen -= off; /* tlen is used instead of ti->ti_len */
655 if (off > sizeof(struct tcphdr)) {
657 IP6_EXTHDR_CHECK(m, off0, off, IPPROTO_DONE);
658 ip6 = mtod(m, struct ip6_hdr *);
659 th = (struct tcphdr *)((caddr_t)ip6 + off0);
661 /* already pulled up in ip_demux() */
662 KASSERT(m->m_len >= sizeof(struct ip) + off,
663 ("TCP header and options not in one mbuf: "
664 "m_len %d, off %d", m->m_len, off));
666 optlen = off - sizeof(struct tcphdr);
667 optp = (u_char *)(th + 1);
669 thflags = th->th_flags;
671 #ifdef TCP_DROP_SYNFIN
673 * If the drop_synfin option is enabled, drop all packets with
674 * both the SYN and FIN bits set. This prevents e.g. nmap from
675 * identifying the TCP/IP stack.
677 * This is a violation of the TCP specification.
679 if (drop_synfin && (thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN))
684 * Convert TCP protocol specific fields to host format.
686 th->th_seq = ntohl(th->th_seq);
687 th->th_ack = ntohl(th->th_ack);
688 th->th_win = ntohs(th->th_win);
689 th->th_urp = ntohs(th->th_urp);
692 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
693 * until after ip6_savecontrol() is called and before other functions
694 * which don't want those proto headers.
695 * Because ip6_savecontrol() is going to parse the mbuf to
696 * search for data to be passed up to user-land, it wants mbuf
697 * parameters to be unchanged.
698 * XXX: the call of ip6_savecontrol() has been obsoleted based on
699 * latest version of the advanced API (20020110).
701 drop_hdrlen = off0 + off;
704 * Locate pcb for segment.
707 /* IPFIREWALL_FORWARD section */
708 if (next_hop != NULL && !isipv6) { /* IPv6 support is not there yet */
710 * Transparently forwarded. Pretend to be the destination.
711 * already got one like this?
713 cpu = mycpu->gd_cpuid;
714 inp = in_pcblookup_hash(&tcbinfo[cpu],
715 ip->ip_src, th->th_sport,
716 ip->ip_dst, th->th_dport,
717 0, m->m_pkthdr.rcvif);
720 * It's new. Try to find the ambushing socket.
724 * The rest of the ipfw code stores the port in
726 * (The IP address is still in network order.)
728 in_port_t dport = next_hop->sin_port ?
729 htons(next_hop->sin_port) :
732 cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
733 next_hop->sin_addr.s_addr, dport);
734 inp = in_pcblookup_hash(&tcbinfo[cpu],
735 ip->ip_src, th->th_sport,
736 next_hop->sin_addr, dport,
737 1, m->m_pkthdr.rcvif);
741 inp = in6_pcblookup_hash(&tcbinfo[0],
742 &ip6->ip6_src, th->th_sport,
743 &ip6->ip6_dst, th->th_dport,
744 1, m->m_pkthdr.rcvif);
746 cpu = mycpu->gd_cpuid;
747 inp = in_pcblookup_hash(&tcbinfo[cpu],
748 ip->ip_src, th->th_sport,
749 ip->ip_dst, th->th_dport,
750 1, m->m_pkthdr.rcvif);
755 * If the state is CLOSED (i.e., TCB does not exist) then
756 * all data in the incoming segment is discarded.
757 * If the TCB exists but is in CLOSED state, it is embryonic,
758 * but should either do a listen or a connect soon.
763 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
765 char dbuf[sizeof "aaa.bbb.ccc.ddd"];
766 char sbuf[sizeof "aaa.bbb.ccc.ddd"];
770 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
773 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
776 strcpy(dbuf, inet_ntoa(ip->ip_dst));
777 strcpy(sbuf, inet_ntoa(ip->ip_src));
779 switch (log_in_vain) {
781 if (!(thflags & TH_SYN))
785 "Connection attempt to TCP %s:%d "
786 "from %s:%d flags:0x%02x\n",
787 dbuf, ntohs(th->th_dport), sbuf,
788 ntohs(th->th_sport), thflags);
797 if (thflags & TH_SYN)
806 rstreason = BANDLIM_RST_CLOSEDPORT;
812 if (ipsec6_in_reject_so(m, inp->inp_socket)) {
813 ipsec6stat.in_polvio++;
817 if (ipsec4_in_reject_so(m, inp->inp_socket)) {
818 ipsecstat.in_polvio++;
825 if (ipsec6_in_reject(m, inp))
828 if (ipsec4_in_reject(m, inp))
832 /* Check the minimum TTL for socket. */
834 if ((isipv6 ? ip6->ip6_hlim : ip->ip_ttl) < inp->inp_ip_minttl)
840 rstreason = BANDLIM_RST_CLOSEDPORT;
843 if (tp->t_state <= TCPS_CLOSED)
846 /* Unscale the window into a 32-bit value. */
847 if (!(thflags & TH_SYN))
848 tiwin = th->th_win << tp->snd_scale;
852 so = inp->inp_socket;
855 if (so->so_options & SO_DEBUG) {
856 ostate = tp->t_state;
858 bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
860 bcopy(ip, tcp_saveipgen, sizeof(*ip));
865 bzero(&to, sizeof to);
867 if (so->so_options & SO_ACCEPTCONN) {
868 struct in_conninfo inc;
871 inc.inc_isipv6 = (isipv6 == TRUE);
874 inc.inc6_faddr = ip6->ip6_src;
875 inc.inc6_laddr = ip6->ip6_dst;
876 inc.inc6_route.ro_rt = NULL; /* XXX */
878 inc.inc_faddr = ip->ip_src;
879 inc.inc_laddr = ip->ip_dst;
880 inc.inc_route.ro_rt = NULL; /* XXX */
882 inc.inc_fport = th->th_sport;
883 inc.inc_lport = th->th_dport;
886 * If the state is LISTEN then ignore segment if it contains
887 * a RST. If the segment contains an ACK then it is bad and
888 * send a RST. If it does not contain a SYN then it is not
889 * interesting; drop it.
891 * If the state is SYN_RECEIVED (syncache) and seg contains
892 * an ACK, but not for our SYN/ACK, send a RST. If the seg
893 * contains a RST, check the sequence number to see if it
894 * is a valid reset segment.
896 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
897 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) == TH_ACK) {
898 if (!syncache_expand(&inc, th, &so, m)) {
900 * No syncache entry, or ACK was not
901 * for our SYN/ACK. Send a RST.
903 tcpstat.tcps_badsyn++;
904 rstreason = BANDLIM_RST_OPENPORT;
909 * Could not complete 3-way handshake,
910 * connection is being closed down, and
911 * syncache will free mbuf.
914 return(IPPROTO_DONE);
917 * We must be in the correct protocol thread
918 * for this connection.
920 KKASSERT(so->so_port == &curthread->td_msgport);
923 * Socket is created in state SYN_RECEIVED.
924 * Continue processing segment.
929 * This is what would have happened in
930 * tcp_output() when the SYN,ACK was sent.
932 tp->snd_up = tp->snd_una;
933 tp->snd_max = tp->snd_nxt = tp->iss + 1;
934 tp->last_ack_sent = tp->rcv_nxt;
936 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
937 * until the _second_ ACK is received:
938 * rcv SYN (set wscale opts) --> send SYN/ACK, set snd_wnd = window.
939 * rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
940 * move to ESTAB, set snd_wnd to tiwin.
942 tp->snd_wnd = tiwin; /* unscaled */
945 if (thflags & TH_RST) {
946 syncache_chkrst(&inc, th);
949 if (thflags & TH_ACK) {
950 syncache_badack(&inc);
951 tcpstat.tcps_badsyn++;
952 rstreason = BANDLIM_RST_OPENPORT;
959 * Segment's flags are (SYN) or (SYN | FIN).
963 * If deprecated address is forbidden,
964 * we do not accept SYN to deprecated interface
965 * address to prevent any new inbound connection from
966 * getting established.
967 * When we do not accept SYN, we send a TCP RST,
968 * with deprecated source address (instead of dropping
969 * it). We compromise it as it is much better for peer
970 * to send a RST, and RST will be the final packet
973 * If we do not forbid deprecated addresses, we accept
974 * the SYN packet. RFC2462 does not suggest dropping
976 * If we decipher RFC2462 5.5.4, it says like this:
977 * 1. use of deprecated addr with existing
978 * communication is okay - "SHOULD continue to be
980 * 2. use of it with new communication:
981 * (2a) "SHOULD NOT be used if alternate address
982 * with sufficient scope is available"
983 * (2b) nothing mentioned otherwise.
984 * Here we fall into (2b) case as we have no choice in
985 * our source address selection - we must obey the peer.
987 * The wording in RFC2462 is confusing, and there are
988 * multiple description text for deprecated address
989 * handling - worse, they are not exactly the same.
990 * I believe 5.5.4 is the best one, so we follow 5.5.4.
992 if (isipv6 && !ip6_use_deprecated) {
993 struct in6_ifaddr *ia6;
995 if ((ia6 = ip6_getdstifaddr(m)) &&
996 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
998 rstreason = BANDLIM_RST_OPENPORT;
1004 * If it is from this socket, drop it, it must be forged.
1005 * Don't bother responding if the destination was a broadcast.
1007 if (th->th_dport == th->th_sport) {
1009 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
1013 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
1018 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1020 * Note that it is quite possible to receive unicast
1021 * link-layer packets with a broadcast IP address. Use
1022 * in_broadcast() to find them.
1024 if (m->m_flags & (M_BCAST | M_MCAST))
1027 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1028 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
1031 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1032 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1033 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1034 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1038 * SYN appears to be valid; create compressed TCP state
1039 * for syncache, or perform t/tcp connection.
1041 if (so->so_qlen <= so->so_qlimit) {
1042 tcp_dooptions(&to, optp, optlen, TRUE);
1043 if (!syncache_add(&inc, &to, th, &so, m))
1047 * Entry added to syncache, mbuf used to
1048 * send SYN,ACK packet.
1051 return(IPPROTO_DONE);
1054 * We must be in the correct protocol thread for
1057 KKASSERT(so->so_port == &curthread->td_msgport);
1060 tp = intotcpcb(inp);
1061 tp->snd_wnd = tiwin;
1062 tp->t_starttime = ticks;
1063 tp->t_state = TCPS_ESTABLISHED;
1066 * If there is a FIN, or if there is data and the
1067 * connection is local, then delay SYN,ACK(SYN) in
1068 * the hope of piggy-backing it on a response
1069 * segment. Otherwise must send ACK now in case
1070 * the other side is slow starting.
1072 if (DELAY_ACK(tp) &&
1073 ((thflags & TH_FIN) ||
1075 ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
1076 (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
1077 tcp_callout_reset(tp, tp->tt_delack,
1078 tcp_delacktime, tcp_timer_delack);
1079 tp->t_flags |= TF_NEEDSYN;
1081 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1084 tcpstat.tcps_connects++;
1093 * Should not happen - syncache should pick up these connections.
1095 * Once we are past handling listen sockets we must be in the
1096 * correct protocol processing thread.
1098 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN state"));
1099 KKASSERT(so->so_port == &curthread->td_msgport);
1102 * This is the second part of the MSS DoS prevention code (after
1103 * minmss on the sending side) and it deals with too many too small
1104 * tcp packets in a too short timeframe (1 second).
1106 * XXX Removed. This code was crap. It does not scale to network
1107 * speed, and default values break NFS. Gone.
1112 * Segment received on connection.
1114 * Reset idle time and keep-alive timer. Don't waste time if less
1115 * then a second has elapsed.
1117 if ((int)(ticks - tp->t_rcvtime) > hz)
1118 tcp_timer_keep_activity(tp, thflags);
1122 * XXX this is tradtitional behavior, may need to be cleaned up.
1124 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0);
1125 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1126 if (to.to_flags & TOF_SCALE) {
1127 tp->t_flags |= TF_RCVD_SCALE;
1128 tp->requested_s_scale = to.to_requested_s_scale;
1130 if (to.to_flags & TOF_TS) {
1131 tp->t_flags |= TF_RCVD_TSTMP;
1132 tp->ts_recent = to.to_tsval;
1133 tp->ts_recent_age = ticks;
1135 if (to.to_flags & TOF_MSS)
1136 tcp_mss(tp, to.to_mss);
1138 * Only set the TF_SACK_PERMITTED per-connection flag
1139 * if we got a SACK_PERMITTED option from the other side
1140 * and the global tcp_do_sack variable is true.
1142 if (tcp_do_sack && (to.to_flags & TOF_SACK_PERMITTED))
1143 tp->t_flags |= TF_SACK_PERMITTED;
1147 * Header prediction: check for the two common cases
1148 * of a uni-directional data xfer. If the packet has
1149 * no control flags, is in-sequence, the window didn't
1150 * change and we're not retransmitting, it's a
1151 * candidate. If the length is zero and the ack moved
1152 * forward, we're the sender side of the xfer. Just
1153 * free the data acked & wake any higher level process
1154 * that was blocked waiting for space. If the length
1155 * is non-zero and the ack didn't move, we're the
1156 * receiver side. If we're getting packets in-order
1157 * (the reassembly queue is empty), add the data to
1158 * the socket buffer and note that we need a delayed ack.
1159 * Make sure that the hidden state-flags are also off.
1160 * Since we check for TCPS_ESTABLISHED above, it can only
1163 if (tp->t_state == TCPS_ESTABLISHED &&
1164 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1165 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1166 (!(to.to_flags & TOF_TS) ||
1167 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1168 th->th_seq == tp->rcv_nxt &&
1169 tp->snd_nxt == tp->snd_max) {
1172 * If last ACK falls within this segment's sequence numbers,
1173 * record the timestamp.
1174 * NOTE that the test is modified according to the latest
1175 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1177 if ((to.to_flags & TOF_TS) &&
1178 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1179 tp->ts_recent_age = ticks;
1180 tp->ts_recent = to.to_tsval;
1184 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1185 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1186 tp->snd_cwnd >= tp->snd_wnd &&
1187 !IN_FASTRECOVERY(tp)) {
1189 * This is a pure ack for outstanding data.
1191 ++tcpstat.tcps_predack;
1193 * "bad retransmit" recovery
1195 * If Eifel detection applies, then
1196 * it is deterministic, so use it
1197 * unconditionally over the old heuristic.
1198 * Otherwise, fall back to the old heuristic.
1200 if (tcp_do_eifel_detect &&
1201 (to.to_flags & TOF_TS) && to.to_tsecr &&
1202 (tp->t_flags & TF_FIRSTACCACK)) {
1203 /* Eifel detection applicable. */
1204 if (to.to_tsecr < tp->t_rexmtTS) {
1205 tcp_revert_congestion_state(tp);
1206 ++tcpstat.tcps_eifeldetected;
1208 } else if (tp->t_rxtshift == 1 &&
1209 ticks < tp->t_badrxtwin) {
1210 tcp_revert_congestion_state(tp);
1211 ++tcpstat.tcps_rttdetected;
1213 tp->t_flags &= ~(TF_FIRSTACCACK |
1214 TF_FASTREXMT | TF_EARLYREXMT);
1216 * Recalculate the retransmit timer / rtt.
1218 * Some machines (certain windows boxes)
1219 * send broken timestamp replies during the
1220 * SYN+ACK phase, ignore timestamps of 0.
1222 if ((to.to_flags & TOF_TS) && to.to_tsecr) {
1224 ticks - to.to_tsecr + 1);
1225 } else if (tp->t_rtttime &&
1226 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1228 ticks - tp->t_rtttime);
1230 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1231 acked = th->th_ack - tp->snd_una;
1232 tcpstat.tcps_rcvackpack++;
1233 tcpstat.tcps_rcvackbyte += acked;
1234 sbdrop(&so->so_snd.sb, acked);
1235 tp->snd_recover = th->th_ack - 1;
1236 tp->snd_una = th->th_ack;
1239 * Update window information.
1241 if (tiwin != tp->snd_wnd &&
1242 acceptable_window_update(tp, th, tiwin)) {
1243 /* keep track of pure window updates */
1244 if (tp->snd_wl2 == th->th_ack &&
1245 tiwin > tp->snd_wnd)
1246 tcpstat.tcps_rcvwinupd++;
1247 tp->snd_wnd = tiwin;
1248 tp->snd_wl1 = th->th_seq;
1249 tp->snd_wl2 = th->th_ack;
1250 if (tp->snd_wnd > tp->max_sndwnd)
1251 tp->max_sndwnd = tp->snd_wnd;
1254 ND6_HINT(tp); /* some progress has been done */
1256 * If all outstanding data are acked, stop
1257 * retransmit timer, otherwise restart timer
1258 * using current (possibly backed-off) value.
1259 * If process is waiting for space,
1260 * wakeup/selwakeup/signal. If data
1261 * are ready to send, let tcp_output
1262 * decide between more output or persist.
1264 if (tp->snd_una == tp->snd_max) {
1265 tcp_callout_stop(tp, tp->tt_rexmt);
1266 } else if (!tcp_callout_active(tp,
1268 tcp_callout_reset(tp, tp->tt_rexmt,
1269 tp->t_rxtcur, tcp_timer_rexmt);
1272 if (so->so_snd.ssb_cc > 0)
1274 return(IPPROTO_DONE);
1276 } else if (tiwin == tp->snd_wnd &&
1277 th->th_ack == tp->snd_una &&
1278 LIST_EMPTY(&tp->t_segq) &&
1279 tlen <= ssb_space(&so->so_rcv)) {
1280 u_long newsize = 0; /* automatic sockbuf scaling */
1282 * This is a pure, in-sequence data packet
1283 * with nothing on the reassembly queue and
1284 * we have enough buffer space to take it.
1286 ++tcpstat.tcps_preddat;
1287 tp->rcv_nxt += tlen;
1288 tcpstat.tcps_rcvpack++;
1289 tcpstat.tcps_rcvbyte += tlen;
1290 ND6_HINT(tp); /* some progress has been done */
1292 * Automatic sizing of receive socket buffer. Often the send
1293 * buffer size is not optimally adjusted to the actual network
1294 * conditions at hand (delay bandwidth product). Setting the
1295 * buffer size too small limits throughput on links with high
1296 * bandwidth and high delay (eg. trans-continental/oceanic links).
1298 * On the receive side the socket buffer memory is only rarely
1299 * used to any significant extent. This allows us to be much
1300 * more aggressive in scaling the receive socket buffer. For
1301 * the case that the buffer space is actually used to a large
1302 * extent and we run out of kernel memory we can simply drop
1303 * the new segments; TCP on the sender will just retransmit it
1304 * later. Setting the buffer size too big may only consume too
1305 * much kernel memory if the application doesn't read() from
1306 * the socket or packet loss or reordering makes use of the
1309 * The criteria to step up the receive buffer one notch are:
1310 * 1. the number of bytes received during the time it takes
1311 * one timestamp to be reflected back to us (the RTT);
1312 * 2. received bytes per RTT is within seven eighth of the
1313 * current socket buffer size;
1314 * 3. receive buffer size has not hit maximal automatic size;
1316 * This algorithm does one step per RTT at most and only if
1317 * we receive a bulk stream w/o packet losses or reorderings.
1318 * Shrinking the buffer during idle times is not necessary as
1319 * it doesn't consume any memory when idle.
1321 * TODO: Only step up if the application is actually serving
1322 * the buffer to better manage the socket buffer resources.
1324 if (tcp_do_autorcvbuf &&
1326 (so->so_rcv.ssb_flags & SSB_AUTOSIZE)) {
1327 if (to.to_tsecr > tp->rfbuf_ts &&
1328 to.to_tsecr - tp->rfbuf_ts < hz) {
1330 (so->so_rcv.ssb_hiwat / 8 * 7) &&
1331 so->so_rcv.ssb_hiwat <
1332 tcp_autorcvbuf_max) {
1334 ulmin(so->so_rcv.ssb_hiwat +
1336 tcp_autorcvbuf_max);
1338 /* Start over with next RTT. */
1342 tp->rfbuf_cnt += tlen; /* add up */
1345 * Add data to socket buffer.
1347 if (so->so_state & SS_CANTRCVMORE) {
1351 * Set new socket buffer size, give up when
1354 * Adjusting the size can mess up ACK
1355 * sequencing when pure window updates are
1356 * being avoided (which is the default),
1359 lwkt_gettoken(&so->so_rcv.ssb_token);
1361 tp->t_flags |= TF_RXRESIZED;
1362 if (!ssb_reserve(&so->so_rcv, newsize,
1364 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1367 (TCP_MAXWIN << tp->rcv_scale)) {
1368 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1371 m_adj(m, drop_hdrlen); /* delayed header drop */
1372 ssb_appendstream(&so->so_rcv, m);
1373 lwkt_reltoken(&so->so_rcv.ssb_token);
1377 * This code is responsible for most of the ACKs
1378 * the TCP stack sends back after receiving a data
1379 * packet. Note that the DELAY_ACK check fails if
1380 * the delack timer is already running, which results
1381 * in an ack being sent every other packet (which is
1384 * We then further aggregate acks by not actually
1385 * sending one until the protocol thread has completed
1386 * processing the current backlog of packets. This
1387 * does not delay the ack any further, but allows us
1388 * to take advantage of the packet aggregation that
1389 * high speed NICs do (usually blocks of 8-10 packets)
1390 * to send a single ack rather then four or five acks,
1391 * greatly reducing the ack rate, the return channel
1392 * bandwidth, and the protocol overhead on both ends.
1394 * Since this also has the effect of slowing down
1395 * the exponential slow-start ramp-up, systems with
1396 * very large bandwidth-delay products might want
1397 * to turn the feature off.
1399 if (DELAY_ACK(tp)) {
1400 tcp_callout_reset(tp, tp->tt_delack,
1401 tcp_delacktime, tcp_timer_delack);
1402 } else if (tcp_aggregate_acks) {
1403 tp->t_flags |= TF_ACKNOW;
1404 if (!(tp->t_flags & TF_ONOUTPUTQ)) {
1405 tp->t_flags |= TF_ONOUTPUTQ;
1406 tp->tt_cpu = mycpu->gd_cpuid;
1408 &tcpcbackq[tp->tt_cpu],
1412 tp->t_flags |= TF_ACKNOW;
1415 return(IPPROTO_DONE);
1420 * Calculate amount of space in receive window,
1421 * and then do TCP input processing.
1422 * Receive window is amount of space in rcv queue,
1423 * but not less than advertised window.
1425 recvwin = ssb_space(&so->so_rcv);
1428 tp->rcv_wnd = imax(recvwin, (int)(tp->rcv_adv - tp->rcv_nxt));
1430 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1434 switch (tp->t_state) {
1436 * If the state is SYN_RECEIVED:
1437 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1439 case TCPS_SYN_RECEIVED:
1440 if ((thflags & TH_ACK) &&
1441 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1442 SEQ_GT(th->th_ack, tp->snd_max))) {
1443 rstreason = BANDLIM_RST_OPENPORT;
1449 * If the state is SYN_SENT:
1450 * if seg contains an ACK, but not for our SYN, drop the input.
1451 * if seg contains a RST, then drop the connection.
1452 * if seg does not contain SYN, then drop it.
1453 * Otherwise this is an acceptable SYN segment
1454 * initialize tp->rcv_nxt and tp->irs
1455 * if seg contains ack then advance tp->snd_una
1456 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1457 * arrange for segment to be acked (eventually)
1458 * continue processing rest of data/controls, beginning with URG
1461 if ((thflags & TH_ACK) &&
1462 (SEQ_LEQ(th->th_ack, tp->iss) ||
1463 SEQ_GT(th->th_ack, tp->snd_max))) {
1464 rstreason = BANDLIM_UNLIMITED;
1467 if (thflags & TH_RST) {
1468 if (thflags & TH_ACK)
1469 tp = tcp_drop(tp, ECONNREFUSED);
1472 if (!(thflags & TH_SYN))
1474 tp->snd_wnd = th->th_win; /* initial send window */
1476 tp->irs = th->th_seq;
1478 if (thflags & TH_ACK) {
1479 /* Our SYN was acked. */
1480 tcpstat.tcps_connects++;
1482 /* Do window scaling on this connection? */
1483 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1484 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1485 tp->snd_scale = tp->requested_s_scale;
1486 tp->rcv_scale = tp->request_r_scale;
1488 tp->rcv_adv += tp->rcv_wnd;
1489 tp->snd_una++; /* SYN is acked */
1490 tcp_callout_stop(tp, tp->tt_rexmt);
1492 * If there's data, delay ACK; if there's also a FIN
1493 * ACKNOW will be turned on later.
1495 if (DELAY_ACK(tp) && tlen != 0) {
1496 tcp_callout_reset(tp, tp->tt_delack,
1497 tcp_delacktime, tcp_timer_delack);
1499 tp->t_flags |= TF_ACKNOW;
1502 * Received <SYN,ACK> in SYN_SENT[*] state.
1504 * SYN_SENT --> ESTABLISHED
1505 * SYN_SENT* --> FIN_WAIT_1
1507 tp->t_starttime = ticks;
1508 if (tp->t_flags & TF_NEEDFIN) {
1509 tp->t_state = TCPS_FIN_WAIT_1;
1510 tp->t_flags &= ~TF_NEEDFIN;
1513 tp->t_state = TCPS_ESTABLISHED;
1514 tcp_callout_reset(tp, tp->tt_keep,
1515 tcp_getkeepidle(tp),
1520 * Received initial SYN in SYN-SENT[*] state =>
1521 * simultaneous open.
1522 * Do 3-way handshake:
1523 * SYN-SENT -> SYN-RECEIVED
1524 * SYN-SENT* -> SYN-RECEIVED*
1526 tp->t_flags |= TF_ACKNOW;
1527 tcp_callout_stop(tp, tp->tt_rexmt);
1528 tp->t_state = TCPS_SYN_RECEIVED;
1533 * Advance th->th_seq to correspond to first data byte.
1534 * If data, trim to stay within window,
1535 * dropping FIN if necessary.
1538 if (tlen > tp->rcv_wnd) {
1539 todrop = tlen - tp->rcv_wnd;
1543 tcpstat.tcps_rcvpackafterwin++;
1544 tcpstat.tcps_rcvbyteafterwin += todrop;
1546 tp->snd_wl1 = th->th_seq - 1;
1547 tp->rcv_up = th->th_seq;
1549 * Client side of transaction: already sent SYN and data.
1550 * If the remote host used T/TCP to validate the SYN,
1551 * our data will be ACK'd; if so, enter normal data segment
1552 * processing in the middle of step 5, ack processing.
1553 * Otherwise, goto step 6.
1555 if (thflags & TH_ACK)
1561 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1562 * do normal processing (we no longer bother with T/TCP).
1566 case TCPS_TIME_WAIT:
1567 break; /* continue normal processing */
1571 * States other than LISTEN or SYN_SENT.
1572 * First check the RST flag and sequence number since reset segments
1573 * are exempt from the timestamp and connection count tests. This
1574 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1575 * below which allowed reset segments in half the sequence space
1576 * to fall though and be processed (which gives forged reset
1577 * segments with a random sequence number a 50 percent chance of
1578 * killing a connection).
1579 * Then check timestamp, if present.
1580 * Then check the connection count, if present.
1581 * Then check that at least some bytes of segment are within
1582 * receive window. If segment begins before rcv_nxt,
1583 * drop leading data (and SYN); if nothing left, just ack.
1586 * If the RST bit is set, check the sequence number to see
1587 * if this is a valid reset segment.
1589 * In all states except SYN-SENT, all reset (RST) segments
1590 * are validated by checking their SEQ-fields. A reset is
1591 * valid if its sequence number is in the window.
1592 * Note: this does not take into account delayed ACKs, so
1593 * we should test against last_ack_sent instead of rcv_nxt.
1594 * The sequence number in the reset segment is normally an
1595 * echo of our outgoing acknowledgement numbers, but some hosts
1596 * send a reset with the sequence number at the rightmost edge
1597 * of our receive window, and we have to handle this case.
1598 * If we have multiple segments in flight, the intial reset
1599 * segment sequence numbers will be to the left of last_ack_sent,
1600 * but they will eventually catch up.
1601 * In any case, it never made sense to trim reset segments to
1602 * fit the receive window since RFC 1122 says:
1603 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1605 * A TCP SHOULD allow a received RST segment to include data.
1608 * It has been suggested that a RST segment could contain
1609 * ASCII text that encoded and explained the cause of the
1610 * RST. No standard has yet been established for such
1613 * If the reset segment passes the sequence number test examine
1615 * SYN_RECEIVED STATE:
1616 * If passive open, return to LISTEN state.
1617 * If active open, inform user that connection was refused.
1618 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1619 * Inform user that connection was reset, and close tcb.
1620 * CLOSING, LAST_ACK STATES:
1623 * Drop the segment - see Stevens, vol. 2, p. 964 and
1626 if (thflags & TH_RST) {
1627 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1628 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1629 switch (tp->t_state) {
1631 case TCPS_SYN_RECEIVED:
1632 so->so_error = ECONNREFUSED;
1635 case TCPS_ESTABLISHED:
1636 case TCPS_FIN_WAIT_1:
1637 case TCPS_FIN_WAIT_2:
1638 case TCPS_CLOSE_WAIT:
1639 so->so_error = ECONNRESET;
1641 tp->t_state = TCPS_CLOSED;
1642 tcpstat.tcps_drops++;
1651 case TCPS_TIME_WAIT:
1659 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1660 * and it's less than ts_recent, drop it.
1662 if ((to.to_flags & TOF_TS) && tp->ts_recent != 0 &&
1663 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1665 /* Check to see if ts_recent is over 24 days old. */
1666 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1668 * Invalidate ts_recent. If this segment updates
1669 * ts_recent, the age will be reset later and ts_recent
1670 * will get a valid value. If it does not, setting
1671 * ts_recent to zero will at least satisfy the
1672 * requirement that zero be placed in the timestamp
1673 * echo reply when ts_recent isn't valid. The
1674 * age isn't reset until we get a valid ts_recent
1675 * because we don't want out-of-order segments to be
1676 * dropped when ts_recent is old.
1680 tcpstat.tcps_rcvduppack++;
1681 tcpstat.tcps_rcvdupbyte += tlen;
1682 tcpstat.tcps_pawsdrop++;
1690 * In the SYN-RECEIVED state, validate that the packet belongs to
1691 * this connection before trimming the data to fit the receive
1692 * window. Check the sequence number versus IRS since we know
1693 * the sequence numbers haven't wrapped. This is a partial fix
1694 * for the "LAND" DoS attack.
1696 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1697 rstreason = BANDLIM_RST_OPENPORT;
1701 todrop = tp->rcv_nxt - th->th_seq;
1703 if (TCP_DO_SACK(tp)) {
1704 /* Report duplicate segment at head of packet. */
1705 tp->reportblk.rblk_start = th->th_seq;
1706 tp->reportblk.rblk_end = th->th_seq + tlen;
1707 if (thflags & TH_FIN)
1708 ++tp->reportblk.rblk_end;
1709 if (SEQ_GT(tp->reportblk.rblk_end, tp->rcv_nxt))
1710 tp->reportblk.rblk_end = tp->rcv_nxt;
1711 tp->t_flags |= (TF_DUPSEG | TF_SACKLEFT | TF_ACKNOW);
1713 if (thflags & TH_SYN) {
1723 * Following if statement from Stevens, vol. 2, p. 960.
1725 if (todrop > tlen ||
1726 (todrop == tlen && !(thflags & TH_FIN))) {
1728 * Any valid FIN must be to the left of the window.
1729 * At this point the FIN must be a duplicate or out
1730 * of sequence; drop it.
1735 * Send an ACK to resynchronize and drop any data.
1736 * But keep on processing for RST or ACK.
1738 tp->t_flags |= TF_ACKNOW;
1740 tcpstat.tcps_rcvduppack++;
1741 tcpstat.tcps_rcvdupbyte += todrop;
1743 tcpstat.tcps_rcvpartduppack++;
1744 tcpstat.tcps_rcvpartdupbyte += todrop;
1746 drop_hdrlen += todrop; /* drop from the top afterwards */
1747 th->th_seq += todrop;
1749 if (th->th_urp > todrop)
1750 th->th_urp -= todrop;
1758 * If new data are received on a connection after the
1759 * user processes are gone, then RST the other end.
1761 if ((so->so_state & SS_NOFDREF) &&
1762 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1764 tcpstat.tcps_rcvafterclose++;
1765 rstreason = BANDLIM_UNLIMITED;
1770 * If segment ends after window, drop trailing data
1771 * (and PUSH and FIN); if nothing left, just ACK.
1773 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1775 tcpstat.tcps_rcvpackafterwin++;
1776 if (todrop >= tlen) {
1777 tcpstat.tcps_rcvbyteafterwin += tlen;
1779 * If a new connection request is received
1780 * while in TIME_WAIT, drop the old connection
1781 * and start over if the sequence numbers
1782 * are above the previous ones.
1784 if (thflags & TH_SYN &&
1785 tp->t_state == TCPS_TIME_WAIT &&
1786 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1791 * If window is closed can only take segments at
1792 * window edge, and have to drop data and PUSH from
1793 * incoming segments. Continue processing, but
1794 * remember to ack. Otherwise, drop segment
1797 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1798 tp->t_flags |= TF_ACKNOW;
1799 tcpstat.tcps_rcvwinprobe++;
1803 tcpstat.tcps_rcvbyteafterwin += todrop;
1806 thflags &= ~(TH_PUSH | TH_FIN);
1810 * If last ACK falls within this segment's sequence numbers,
1811 * record its timestamp.
1813 * 1) That the test incorporates suggestions from the latest
1814 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1815 * 2) That updating only on newer timestamps interferes with
1816 * our earlier PAWS tests, so this check should be solely
1817 * predicated on the sequence space of this segment.
1818 * 3) That we modify the segment boundary check to be
1819 * Last.ACK.Sent <= SEG.SEQ + SEG.LEN
1820 * instead of RFC1323's
1821 * Last.ACK.Sent < SEG.SEQ + SEG.LEN,
1822 * This modified check allows us to overcome RFC1323's
1823 * limitations as described in Stevens TCP/IP Illustrated
1824 * Vol. 2 p.869. In such cases, we can still calculate the
1825 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1827 if ((to.to_flags & TOF_TS) && SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1828 SEQ_LEQ(tp->last_ack_sent, (th->th_seq + tlen
1829 + ((thflags & TH_SYN) != 0)
1830 + ((thflags & TH_FIN) != 0)))) {
1831 tp->ts_recent_age = ticks;
1832 tp->ts_recent = to.to_tsval;
1836 * If a SYN is in the window, then this is an
1837 * error and we send an RST and drop the connection.
1839 if (thflags & TH_SYN) {
1840 tp = tcp_drop(tp, ECONNRESET);
1841 rstreason = BANDLIM_UNLIMITED;
1846 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1847 * flag is on (half-synchronized state), then queue data for
1848 * later processing; else drop segment and return.
1850 if (!(thflags & TH_ACK)) {
1851 if (tp->t_state == TCPS_SYN_RECEIVED ||
1852 (tp->t_flags & TF_NEEDSYN))
1861 switch (tp->t_state) {
1863 * In SYN_RECEIVED state, the ACK acknowledges our SYN, so enter
1864 * ESTABLISHED state and continue processing.
1865 * The ACK was checked above.
1867 case TCPS_SYN_RECEIVED:
1869 tcpstat.tcps_connects++;
1871 /* Do window scaling? */
1872 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1873 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1874 tp->snd_scale = tp->requested_s_scale;
1875 tp->rcv_scale = tp->request_r_scale;
1879 * SYN-RECEIVED -> ESTABLISHED
1880 * SYN-RECEIVED* -> FIN-WAIT-1
1882 tp->t_starttime = ticks;
1883 if (tp->t_flags & TF_NEEDFIN) {
1884 tp->t_state = TCPS_FIN_WAIT_1;
1885 tp->t_flags &= ~TF_NEEDFIN;
1887 tp->t_state = TCPS_ESTABLISHED;
1888 tcp_callout_reset(tp, tp->tt_keep,
1889 tcp_getkeepidle(tp),
1893 * If segment contains data or ACK, will call tcp_reass()
1894 * later; if not, do so now to pass queued data to user.
1896 if (tlen == 0 && !(thflags & TH_FIN))
1897 tcp_reass(tp, NULL, NULL, NULL);
1901 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1902 * ACKs. If the ack is in the range
1903 * tp->snd_una < th->th_ack <= tp->snd_max
1904 * then advance tp->snd_una to th->th_ack and drop
1905 * data from the retransmission queue. If this ACK reflects
1906 * more up to date window information we update our window information.
1908 case TCPS_ESTABLISHED:
1909 case TCPS_FIN_WAIT_1:
1910 case TCPS_FIN_WAIT_2:
1911 case TCPS_CLOSE_WAIT:
1914 case TCPS_TIME_WAIT:
1916 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1917 if (TCP_DO_SACK(tp))
1918 tcp_sack_update_scoreboard(tp, &to);
1919 if (tlen != 0 || tiwin != tp->snd_wnd) {
1923 tcpstat.tcps_rcvdupack++;
1924 if (!tcp_callout_active(tp, tp->tt_rexmt) ||
1925 th->th_ack != tp->snd_una) {
1930 * We have outstanding data (other than
1931 * a window probe), this is a completely
1932 * duplicate ack (ie, window info didn't
1933 * change), the ack is the biggest we've
1934 * seen and we've seen exactly our rexmt
1935 * threshhold of them, so assume a packet
1936 * has been dropped and retransmit it.
1937 * Kludge snd_nxt & the congestion
1938 * window so we send only this one
1941 if (IN_FASTRECOVERY(tp)) {
1942 if (TCP_DO_SACK(tp)) {
1943 /* No artifical cwnd inflation. */
1944 tcp_sack_rexmt(tp, th);
1947 * Dup acks mean that packets
1948 * have left the network
1949 * (they're now cached at the
1950 * receiver) so bump cwnd by
1951 * the amount in the receiver
1952 * to keep a constant cwnd
1953 * packets in the network.
1955 tp->snd_cwnd += tp->t_maxseg;
1958 } else if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1961 } else if (++tp->t_dupacks == tcprexmtthresh) {
1962 tcp_seq old_snd_nxt;
1966 if (tcp_do_eifel_detect &&
1967 (tp->t_flags & TF_RCVD_TSTMP)) {
1968 tcp_save_congestion_state(tp);
1969 tp->t_flags |= TF_FASTREXMT;
1972 * We know we're losing at the current
1973 * window size, so do congestion avoidance:
1974 * set ssthresh to half the current window
1975 * and pull our congestion window back to the
1978 win = min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1982 tp->snd_ssthresh = win * tp->t_maxseg;
1983 ENTER_FASTRECOVERY(tp);
1984 tp->snd_recover = tp->snd_max;
1985 tcp_callout_stop(tp, tp->tt_rexmt);
1987 old_snd_nxt = tp->snd_nxt;
1988 tp->snd_nxt = th->th_ack;
1989 tp->snd_cwnd = tp->t_maxseg;
1991 ++tcpstat.tcps_sndfastrexmit;
1992 tp->snd_cwnd = tp->snd_ssthresh;
1993 tp->rexmt_high = tp->snd_nxt;
1994 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
1995 tp->snd_nxt = old_snd_nxt;
1996 KASSERT(tp->snd_limited <= 2,
1997 ("tp->snd_limited too big"));
1998 if (TCP_DO_SACK(tp))
1999 tcp_sack_rexmt(tp, th);
2001 tp->snd_cwnd += tp->t_maxseg *
2002 (tp->t_dupacks - tp->snd_limited);
2003 } else if (tcp_do_limitedtransmit) {
2004 u_long oldcwnd = tp->snd_cwnd;
2005 tcp_seq oldsndmax = tp->snd_max;
2006 tcp_seq oldsndnxt = tp->snd_nxt;
2007 /* outstanding data */
2008 uint32_t ownd = tp->snd_max - tp->snd_una;
2011 #define iceildiv(n, d) (((n)+(d)-1) / (d))
2013 KASSERT(tp->t_dupacks == 1 ||
2015 ("dupacks not 1 or 2"));
2016 if (tp->t_dupacks == 1)
2017 tp->snd_limited = 0;
2018 tp->snd_nxt = tp->snd_max;
2019 tp->snd_cwnd = ownd +
2020 (tp->t_dupacks - tp->snd_limited) *
2025 * Other acks may have been processed,
2026 * snd_nxt cannot be reset to a value less
2029 if (SEQ_LT(oldsndnxt, oldsndmax)) {
2030 if (SEQ_GT(oldsndnxt, tp->snd_una))
2031 tp->snd_nxt = oldsndnxt;
2033 tp->snd_nxt = tp->snd_una;
2035 tp->snd_cwnd = oldcwnd;
2036 sent = tp->snd_max - oldsndmax;
2037 if (sent > tp->t_maxseg) {
2038 KASSERT((tp->t_dupacks == 2 &&
2039 tp->snd_limited == 0) ||
2040 (sent == tp->t_maxseg + 1 &&
2041 tp->t_flags & TF_SENTFIN),
2043 KASSERT(sent <= tp->t_maxseg * 2,
2044 ("sent too many segments"));
2045 tp->snd_limited = 2;
2046 tcpstat.tcps_sndlimited += 2;
2047 } else if (sent > 0) {
2049 ++tcpstat.tcps_sndlimited;
2050 } else if (tcp_do_early_retransmit &&
2051 (tcp_do_eifel_detect &&
2052 (tp->t_flags & TF_RCVD_TSTMP)) &&
2053 ownd < 4 * tp->t_maxseg &&
2054 tp->t_dupacks + 1 >=
2055 iceildiv(ownd, tp->t_maxseg) &&
2056 (!TCP_DO_SACK(tp) ||
2057 ownd <= tp->t_maxseg ||
2058 tcp_sack_has_sacked(&tp->scb,
2059 ownd - tp->t_maxseg))) {
2060 ++tcpstat.tcps_sndearlyrexmit;
2061 tp->t_flags |= TF_EARLYREXMT;
2062 goto fastretransmit;
2068 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
2070 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2072 * Detected optimistic ACK attack.
2073 * Force slow-start to de-synchronize attack.
2075 tp->snd_cwnd = tp->t_maxseg;
2078 tcpstat.tcps_rcvacktoomuch++;
2082 * If we reach this point, ACK is not a duplicate,
2083 * i.e., it ACKs something we sent.
2085 if (tp->t_flags & TF_NEEDSYN) {
2087 * T/TCP: Connection was half-synchronized, and our
2088 * SYN has been ACK'd (so connection is now fully
2089 * synchronized). Go to non-starred state,
2090 * increment snd_una for ACK of SYN, and check if
2091 * we can do window scaling.
2093 tp->t_flags &= ~TF_NEEDSYN;
2095 /* Do window scaling? */
2096 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
2097 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
2098 tp->snd_scale = tp->requested_s_scale;
2099 tp->rcv_scale = tp->request_r_scale;
2104 acked = th->th_ack - tp->snd_una;
2105 tcpstat.tcps_rcvackpack++;
2106 tcpstat.tcps_rcvackbyte += acked;
2108 if (tcp_do_eifel_detect && acked > 0 &&
2109 (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
2110 (tp->t_flags & TF_FIRSTACCACK)) {
2111 /* Eifel detection applicable. */
2112 if (to.to_tsecr < tp->t_rexmtTS) {
2113 ++tcpstat.tcps_eifeldetected;
2114 tcp_revert_congestion_state(tp);
2115 if (tp->t_rxtshift == 1 &&
2116 ticks >= tp->t_badrxtwin)
2117 ++tcpstat.tcps_rttcantdetect;
2119 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2121 * If we just performed our first retransmit,
2122 * and the ACK arrives within our recovery window,
2123 * then it was a mistake to do the retransmit
2124 * in the first place. Recover our original cwnd
2125 * and ssthresh, and proceed to transmit where we
2128 tcp_revert_congestion_state(tp);
2129 ++tcpstat.tcps_rttdetected;
2133 * If we have a timestamp reply, update smoothed
2134 * round trip time. If no timestamp is present but
2135 * transmit timer is running and timed sequence
2136 * number was acked, update smoothed round trip time.
2137 * Since we now have an rtt measurement, cancel the
2138 * timer backoff (cf., Phil Karn's retransmit alg.).
2139 * Recompute the initial retransmit timer.
2141 * Some machines (certain windows boxes) send broken
2142 * timestamp replies during the SYN+ACK phase, ignore
2145 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
2146 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2147 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2148 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2149 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2152 * If no data (only SYN) was ACK'd,
2153 * skip rest of ACK processing.
2158 /* Stop looking for an acceptable ACK since one was received. */
2159 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT | TF_EARLYREXMT);
2161 if (acked > so->so_snd.ssb_cc) {
2162 tp->snd_wnd -= so->so_snd.ssb_cc;
2163 sbdrop(&so->so_snd.sb, (int)so->so_snd.ssb_cc);
2164 ourfinisacked = TRUE;
2166 sbdrop(&so->so_snd.sb, acked);
2167 tp->snd_wnd -= acked;
2168 ourfinisacked = FALSE;
2173 * Update window information.
2174 * Don't look at window if no ACK:
2175 * TAC's send garbage on first SYN.
2177 if (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2178 (tp->snd_wl1 == th->th_seq &&
2179 (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2180 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)))) {
2181 /* keep track of pure window updates */
2182 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2183 tiwin > tp->snd_wnd)
2184 tcpstat.tcps_rcvwinupd++;
2185 tp->snd_wnd = tiwin;
2186 tp->snd_wl1 = th->th_seq;
2187 tp->snd_wl2 = th->th_ack;
2188 if (tp->snd_wnd > tp->max_sndwnd)
2189 tp->max_sndwnd = tp->snd_wnd;
2193 tp->snd_una = th->th_ack;
2194 if (TCP_DO_SACK(tp))
2195 tcp_sack_update_scoreboard(tp, &to);
2196 if (IN_FASTRECOVERY(tp)) {
2197 if (SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2198 EXIT_FASTRECOVERY(tp);
2201 * If the congestion window was inflated
2202 * to account for the other side's
2203 * cached packets, retract it.
2205 if (!TCP_DO_SACK(tp))
2206 tp->snd_cwnd = tp->snd_ssthresh;
2209 * Window inflation should have left us
2210 * with approximately snd_ssthresh outstanding
2211 * data. But, in case we would be inclined
2212 * to send a burst, better do it using
2215 if (SEQ_GT(th->th_ack + tp->snd_cwnd,
2216 tp->snd_max + 2 * tp->t_maxseg))
2218 (tp->snd_max - tp->snd_una) +
2223 if (TCP_DO_SACK(tp)) {
2224 tp->snd_max_rexmt = tp->snd_max;
2225 tcp_sack_rexmt(tp, th);
2227 tcp_newreno_partial_ack(tp, th, acked);
2233 * Open the congestion window. When in slow-start,
2234 * open exponentially: maxseg per packet. Otherwise,
2235 * open linearly: maxseg per window.
2237 if (tp->snd_cwnd <= tp->snd_ssthresh) {
2239 (SEQ_LT(tp->snd_nxt, tp->snd_max) ?
2240 tp->t_maxseg : 2 * tp->t_maxseg);
2243 tp->snd_cwnd += tcp_do_abc ?
2244 min(acked, abc_sslimit) : tp->t_maxseg;
2246 /* linear increase */
2247 tp->snd_wacked += tcp_do_abc ? acked :
2249 if (tp->snd_wacked >= tp->snd_cwnd) {
2250 tp->snd_wacked -= tp->snd_cwnd;
2251 tp->snd_cwnd += tp->t_maxseg;
2254 tp->snd_cwnd = min(tp->snd_cwnd,
2255 TCP_MAXWIN << tp->snd_scale);
2256 tp->snd_recover = th->th_ack - 1;
2258 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2259 tp->snd_nxt = tp->snd_una;
2262 * If all outstanding data is acked, stop retransmit
2263 * timer and remember to restart (more output or persist).
2264 * If there is more data to be acked, restart retransmit
2265 * timer, using current (possibly backed-off) value.
2267 if (th->th_ack == tp->snd_max) {
2268 tcp_callout_stop(tp, tp->tt_rexmt);
2270 } else if (!tcp_callout_active(tp, tp->tt_persist)) {
2271 tcp_callout_reset(tp, tp->tt_rexmt, tp->t_rxtcur,
2275 switch (tp->t_state) {
2277 * In FIN_WAIT_1 STATE in addition to the processing
2278 * for the ESTABLISHED state if our FIN is now acknowledged
2279 * then enter FIN_WAIT_2.
2281 case TCPS_FIN_WAIT_1:
2282 if (ourfinisacked) {
2284 * If we can't receive any more
2285 * data, then closing user can proceed.
2286 * Starting the timer is contrary to the
2287 * specification, but if we don't get a FIN
2288 * we'll hang forever.
2290 if (so->so_state & SS_CANTRCVMORE) {
2291 soisdisconnected(so);
2292 tcp_callout_reset(tp, tp->tt_2msl,
2293 tp->t_maxidle, tcp_timer_2msl);
2295 tp->t_state = TCPS_FIN_WAIT_2;
2300 * In CLOSING STATE in addition to the processing for
2301 * the ESTABLISHED state if the ACK acknowledges our FIN
2302 * then enter the TIME-WAIT state, otherwise ignore
2306 if (ourfinisacked) {
2307 tp->t_state = TCPS_TIME_WAIT;
2308 tcp_canceltimers(tp);
2309 tcp_callout_reset(tp, tp->tt_2msl,
2310 2 * tcp_rmx_msl(tp),
2312 soisdisconnected(so);
2317 * In LAST_ACK, we may still be waiting for data to drain
2318 * and/or to be acked, as well as for the ack of our FIN.
2319 * If our FIN is now acknowledged, delete the TCB,
2320 * enter the closed state and return.
2323 if (ourfinisacked) {
2330 * In TIME_WAIT state the only thing that should arrive
2331 * is a retransmission of the remote FIN. Acknowledge
2332 * it and restart the finack timer.
2334 case TCPS_TIME_WAIT:
2335 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2343 * Update window information.
2344 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2346 if ((thflags & TH_ACK) &&
2347 acceptable_window_update(tp, th, tiwin)) {
2348 /* keep track of pure window updates */
2349 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2350 tiwin > tp->snd_wnd)
2351 tcpstat.tcps_rcvwinupd++;
2352 tp->snd_wnd = tiwin;
2353 tp->snd_wl1 = th->th_seq;
2354 tp->snd_wl2 = th->th_ack;
2355 if (tp->snd_wnd > tp->max_sndwnd)
2356 tp->max_sndwnd = tp->snd_wnd;
2361 * Process segments with URG.
2363 if ((thflags & TH_URG) && th->th_urp &&
2364 !TCPS_HAVERCVDFIN(tp->t_state)) {
2366 * This is a kludge, but if we receive and accept
2367 * random urgent pointers, we'll crash in
2368 * soreceive. It's hard to imagine someone
2369 * actually wanting to send this much urgent data.
2371 if (th->th_urp + so->so_rcv.ssb_cc > sb_max) {
2372 th->th_urp = 0; /* XXX */
2373 thflags &= ~TH_URG; /* XXX */
2374 goto dodata; /* XXX */
2377 * If this segment advances the known urgent pointer,
2378 * then mark the data stream. This should not happen
2379 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2380 * a FIN has been received from the remote side.
2381 * In these states we ignore the URG.
2383 * According to RFC961 (Assigned Protocols),
2384 * the urgent pointer points to the last octet
2385 * of urgent data. We continue, however,
2386 * to consider it to indicate the first octet
2387 * of data past the urgent section as the original
2388 * spec states (in one of two places).
2390 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
2391 tp->rcv_up = th->th_seq + th->th_urp;
2392 so->so_oobmark = so->so_rcv.ssb_cc +
2393 (tp->rcv_up - tp->rcv_nxt) - 1;
2394 if (so->so_oobmark == 0)
2395 sosetstate(so, SS_RCVATMARK);
2397 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2400 * Remove out of band data so doesn't get presented to user.
2401 * This can happen independent of advancing the URG pointer,
2402 * but if two URG's are pending at once, some out-of-band
2403 * data may creep in... ick.
2405 if (th->th_urp <= (u_long)tlen &&
2406 !(so->so_options & SO_OOBINLINE)) {
2407 /* hdr drop is delayed */
2408 tcp_pulloutofband(so, th, m, drop_hdrlen);
2412 * If no out of band data is expected,
2413 * pull receive urgent pointer along
2414 * with the receive window.
2416 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2417 tp->rcv_up = tp->rcv_nxt;
2422 * Process the segment text, merging it into the TCP sequencing queue,
2423 * and arranging for acknowledgment of receipt if necessary.
2424 * This process logically involves adjusting tp->rcv_wnd as data
2425 * is presented to the user (this happens in tcp_usrreq.c,
2426 * case PRU_RCVD). If a FIN has already been received on this
2427 * connection then we just ignore the text.
2429 if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
2430 m_adj(m, drop_hdrlen); /* delayed header drop */
2432 * Insert segment which includes th into TCP reassembly queue
2433 * with control block tp. Set thflags to whether reassembly now
2434 * includes a segment with FIN. This handles the common case
2435 * inline (segment is the next to be received on an established
2436 * connection, and the queue is empty), avoiding linkage into
2437 * and removal from the queue and repetition of various
2439 * Set DELACK for segments received in order, but ack
2440 * immediately when segments are out of order (so
2441 * fast retransmit can work).
2443 if (th->th_seq == tp->rcv_nxt &&
2444 LIST_EMPTY(&tp->t_segq) &&
2445 TCPS_HAVEESTABLISHED(tp->t_state)) {
2446 if (DELAY_ACK(tp)) {
2447 tcp_callout_reset(tp, tp->tt_delack,
2448 tcp_delacktime, tcp_timer_delack);
2450 tp->t_flags |= TF_ACKNOW;
2452 tp->rcv_nxt += tlen;
2453 thflags = th->th_flags & TH_FIN;
2454 tcpstat.tcps_rcvpack++;
2455 tcpstat.tcps_rcvbyte += tlen;
2457 if (so->so_state & SS_CANTRCVMORE) {
2460 lwkt_gettoken(&so->so_rcv.ssb_token);
2461 ssb_appendstream(&so->so_rcv, m);
2462 lwkt_reltoken(&so->so_rcv.ssb_token);
2466 if (!(tp->t_flags & TF_DUPSEG)) {
2467 /* Initialize SACK report block. */
2468 tp->reportblk.rblk_start = th->th_seq;
2469 tp->reportblk.rblk_end = th->th_seq + tlen +
2470 ((thflags & TH_FIN) != 0);
2472 thflags = tcp_reass(tp, th, &tlen, m);
2473 tp->t_flags |= TF_ACKNOW;
2477 * Note the amount of data that peer has sent into
2478 * our window, in order to estimate the sender's
2481 len = so->so_rcv.ssb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2488 * If FIN is received ACK the FIN and let the user know
2489 * that the connection is closing.
2491 if (thflags & TH_FIN) {
2492 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
2495 * If connection is half-synchronized
2496 * (ie NEEDSYN flag on) then delay ACK,
2497 * so it may be piggybacked when SYN is sent.
2498 * Otherwise, since we received a FIN then no
2499 * more input can be expected, send ACK now.
2501 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN)) {
2502 tcp_callout_reset(tp, tp->tt_delack,
2503 tcp_delacktime, tcp_timer_delack);
2505 tp->t_flags |= TF_ACKNOW;
2510 switch (tp->t_state) {
2512 * In SYN_RECEIVED and ESTABLISHED STATES
2513 * enter the CLOSE_WAIT state.
2515 case TCPS_SYN_RECEIVED:
2516 tp->t_starttime = ticks;
2518 case TCPS_ESTABLISHED:
2519 tp->t_state = TCPS_CLOSE_WAIT;
2523 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2524 * enter the CLOSING state.
2526 case TCPS_FIN_WAIT_1:
2527 tp->t_state = TCPS_CLOSING;
2531 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2532 * starting the time-wait timer, turning off the other
2535 case TCPS_FIN_WAIT_2:
2536 tp->t_state = TCPS_TIME_WAIT;
2537 tcp_canceltimers(tp);
2538 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2540 soisdisconnected(so);
2544 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2546 case TCPS_TIME_WAIT:
2547 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2554 if (so->so_options & SO_DEBUG)
2555 tcp_trace(TA_INPUT, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2559 * Return any desired output.
2561 if (needoutput || (tp->t_flags & TF_ACKNOW))
2563 return(IPPROTO_DONE);
2567 * Generate an ACK dropping incoming segment if it occupies
2568 * sequence space, where the ACK reflects our state.
2570 * We can now skip the test for the RST flag since all
2571 * paths to this code happen after packets containing
2572 * RST have been dropped.
2574 * In the SYN-RECEIVED state, don't send an ACK unless the
2575 * segment we received passes the SYN-RECEIVED ACK test.
2576 * If it fails send a RST. This breaks the loop in the
2577 * "LAND" DoS attack, and also prevents an ACK storm
2578 * between two listening ports that have been sent forged
2579 * SYN segments, each with the source address of the other.
2581 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2582 (SEQ_GT(tp->snd_una, th->th_ack) ||
2583 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2584 rstreason = BANDLIM_RST_OPENPORT;
2588 if (so->so_options & SO_DEBUG)
2589 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2592 tp->t_flags |= TF_ACKNOW;
2594 return(IPPROTO_DONE);
2598 * Generate a RST, dropping incoming segment.
2599 * Make ACK acceptable to originator of segment.
2600 * Don't bother to respond if destination was broadcast/multicast.
2602 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
2605 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2606 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2609 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2610 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2611 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2612 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2615 /* IPv6 anycast check is done at tcp6_input() */
2618 * Perform bandwidth limiting.
2621 if (badport_bandlim(rstreason) < 0)
2626 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2627 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2629 if (thflags & TH_ACK)
2630 /* mtod() below is safe as long as hdr dropping is delayed */
2631 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2634 if (thflags & TH_SYN)
2636 /* mtod() below is safe as long as hdr dropping is delayed */
2637 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2638 (tcp_seq)0, TH_RST | TH_ACK);
2640 return(IPPROTO_DONE);
2644 * Drop space held by incoming segment and return.
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);
2651 return(IPPROTO_DONE);
2655 * Parse TCP options and place in tcpopt.
2658 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn)
2663 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2665 if (opt == TCPOPT_EOL)
2667 if (opt == TCPOPT_NOP)
2673 if (optlen < 2 || optlen > cnt)
2678 if (optlen != TCPOLEN_MAXSEG)
2682 to->to_flags |= TOF_MSS;
2683 bcopy(cp + 2, &to->to_mss, sizeof to->to_mss);
2684 to->to_mss = ntohs(to->to_mss);
2687 if (optlen != TCPOLEN_WINDOW)
2691 to->to_flags |= TOF_SCALE;
2692 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2694 case TCPOPT_TIMESTAMP:
2695 if (optlen != TCPOLEN_TIMESTAMP)
2697 to->to_flags |= TOF_TS;
2698 bcopy(cp + 2, &to->to_tsval, sizeof to->to_tsval);
2699 to->to_tsval = ntohl(to->to_tsval);
2700 bcopy(cp + 6, &to->to_tsecr, sizeof to->to_tsecr);
2701 to->to_tsecr = ntohl(to->to_tsecr);
2703 * If echoed timestamp is later than the current time,
2704 * fall back to non RFC1323 RTT calculation.
2706 if (to->to_tsecr != 0 && TSTMP_GT(to->to_tsecr, ticks))
2709 case TCPOPT_SACK_PERMITTED:
2710 if (optlen != TCPOLEN_SACK_PERMITTED)
2714 to->to_flags |= TOF_SACK_PERMITTED;
2717 if ((optlen - 2) & 0x07) /* not multiple of 8 */
2719 to->to_nsackblocks = (optlen - 2) / 8;
2720 to->to_sackblocks = (struct raw_sackblock *) (cp + 2);
2721 to->to_flags |= TOF_SACK;
2722 for (i = 0; i < to->to_nsackblocks; i++) {
2723 struct raw_sackblock *r = &to->to_sackblocks[i];
2725 r->rblk_start = ntohl(r->rblk_start);
2726 r->rblk_end = ntohl(r->rblk_end);
2729 #ifdef TCP_SIGNATURE
2731 * XXX In order to reply to a host which has set the
2732 * TCP_SIGNATURE option in its initial SYN, we have to
2733 * record the fact that the option was observed here
2734 * for the syncache code to perform the correct response.
2736 case TCPOPT_SIGNATURE:
2737 if (optlen != TCPOLEN_SIGNATURE)
2739 to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2741 #endif /* TCP_SIGNATURE */
2749 * Pull out of band byte out of a segment so
2750 * it doesn't appear in the user's data queue.
2751 * It is still reflected in the segment length for
2752 * sequencing purposes.
2753 * "off" is the delayed to be dropped hdrlen.
2756 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
2758 int cnt = off + th->th_urp - 1;
2761 if (m->m_len > cnt) {
2762 char *cp = mtod(m, caddr_t) + cnt;
2763 struct tcpcb *tp = sototcpcb(so);
2766 tp->t_oobflags |= TCPOOB_HAVEDATA;
2767 bcopy(cp + 1, cp, m->m_len - cnt - 1);
2769 if (m->m_flags & M_PKTHDR)
2778 panic("tcp_pulloutofband");
2782 * Collect new round-trip time estimate
2783 * and update averages and current timeout.
2786 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2790 tcpstat.tcps_rttupdated++;
2792 if (tp->t_srtt != 0) {
2794 * srtt is stored as fixed point with 5 bits after the
2795 * binary point (i.e., scaled by 8). The following magic
2796 * is equivalent to the smoothing algorithm in rfc793 with
2797 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2798 * point). Adjust rtt to origin 0.
2800 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2801 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2803 if ((tp->t_srtt += delta) <= 0)
2807 * We accumulate a smoothed rtt variance (actually, a
2808 * smoothed mean difference), then set the retransmit
2809 * timer to smoothed rtt + 4 times the smoothed variance.
2810 * rttvar is stored as fixed point with 4 bits after the
2811 * binary point (scaled by 16). The following is
2812 * equivalent to rfc793 smoothing with an alpha of .75
2813 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2814 * rfc793's wired-in beta.
2818 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2819 if ((tp->t_rttvar += delta) <= 0)
2821 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2822 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2825 * No rtt measurement yet - use the unsmoothed rtt.
2826 * Set the variance to half the rtt (so our first
2827 * retransmit happens at 3*rtt).
2829 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2830 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2831 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2837 * the retransmit should happen at rtt + 4 * rttvar.
2838 * Because of the way we do the smoothing, srtt and rttvar
2839 * will each average +1/2 tick of bias. When we compute
2840 * the retransmit timer, we want 1/2 tick of rounding and
2841 * 1 extra tick because of +-1/2 tick uncertainty in the
2842 * firing of the timer. The bias will give us exactly the
2843 * 1.5 tick we need. But, because the bias is
2844 * statistical, we have to test that we don't drop below
2845 * the minimum feasible timer (which is 2 ticks).
2847 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2848 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2851 * We received an ack for a packet that wasn't retransmitted;
2852 * it is probably safe to discard any error indications we've
2853 * received recently. This isn't quite right, but close enough
2854 * for now (a route might have failed after we sent a segment,
2855 * and the return path might not be symmetrical).
2857 tp->t_softerror = 0;
2861 * Determine a reasonable value for maxseg size.
2862 * If the route is known, check route for mtu.
2863 * If none, use an mss that can be handled on the outgoing
2864 * interface without forcing IP to fragment; if bigger than
2865 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2866 * to utilize large mbufs. If no route is found, route has no mtu,
2867 * or the destination isn't local, use a default, hopefully conservative
2868 * size (usually 512 or the default IP max size, but no more than the mtu
2869 * of the interface), as we can't discover anything about intervening
2870 * gateways or networks. We also initialize the congestion/slow start
2871 * window to be a single segment if the destination isn't local.
2872 * While looking at the routing entry, we also initialize other path-dependent
2873 * parameters from pre-set or cached values in the routing entry.
2875 * Also take into account the space needed for options that we
2876 * send regularly. Make maxseg shorter by that amount to assure
2877 * that we can send maxseg amount of data even when the options
2878 * are present. Store the upper limit of the length of options plus
2881 * NOTE that this routine is only called when we process an incoming
2882 * segment, for outgoing segments only tcp_mssopt is called.
2885 tcp_mss(struct tcpcb *tp, int offer)
2891 struct inpcb *inp = tp->t_inpcb;
2894 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2895 size_t min_protoh = isipv6 ?
2896 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2897 sizeof(struct tcpiphdr);
2899 const boolean_t isipv6 = FALSE;
2900 const size_t min_protoh = sizeof(struct tcpiphdr);
2904 rt = tcp_rtlookup6(&inp->inp_inc);
2906 rt = tcp_rtlookup(&inp->inp_inc);
2908 tp->t_maxopd = tp->t_maxseg =
2909 (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2913 so = inp->inp_socket;
2916 * Offer == 0 means that there was no MSS on the SYN segment,
2917 * in this case we use either the interface mtu or tcp_mssdflt.
2919 * An offer which is too large will be cut down later.
2923 if (in6_localaddr(&inp->in6p_faddr)) {
2924 offer = ND_IFINFO(rt->rt_ifp)->linkmtu -
2927 offer = tcp_v6mssdflt;
2930 if (in_localaddr(inp->inp_faddr))
2931 offer = ifp->if_mtu - min_protoh;
2933 offer = tcp_mssdflt;
2938 * Prevent DoS attack with too small MSS. Round up
2939 * to at least minmss.
2941 * Sanity check: make sure that maxopd will be large
2942 * enough to allow some data on segments even is the
2943 * all the option space is used (40bytes). Otherwise
2944 * funny things may happen in tcp_output.
2946 offer = max(offer, tcp_minmss);
2947 offer = max(offer, 64);
2949 rt->rt_rmx.rmx_mssopt = offer;
2952 * While we're here, check if there's an initial rtt
2953 * or rttvar. Convert from the route-table units
2954 * to scaled multiples of the slow timeout timer.
2956 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2958 * XXX the lock bit for RTT indicates that the value
2959 * is also a minimum value; this is subject to time.
2961 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2962 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2963 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2964 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2965 tcpstat.tcps_usedrtt++;
2966 if (rt->rt_rmx.rmx_rttvar) {
2967 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2968 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2969 tcpstat.tcps_usedrttvar++;
2971 /* default variation is +- 1 rtt */
2973 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2975 TCPT_RANGESET(tp->t_rxtcur,
2976 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2977 tp->t_rttmin, TCPTV_REXMTMAX);
2981 * if there's an mtu associated with the route, use it
2982 * else, use the link mtu. Take the smaller of mss or offer
2985 if (rt->rt_rmx.rmx_mtu) {
2986 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2989 mss = ND_IFINFO(rt->rt_ifp)->linkmtu - min_protoh;
2991 mss = ifp->if_mtu - min_protoh;
2993 mss = min(mss, offer);
2996 * maxopd stores the maximum length of data AND options
2997 * in a segment; maxseg is the amount of data in a normal
2998 * segment. We need to store this value (maxopd) apart
2999 * from maxseg, because now every segment carries options
3000 * and thus we normally have somewhat less data in segments.
3004 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
3005 ((tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3006 mss -= TCPOLEN_TSTAMP_APPA;
3008 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3010 mss &= ~(MCLBYTES-1);
3013 mss = mss / MCLBYTES * MCLBYTES;
3016 * If there's a pipesize, change the socket buffer
3017 * to that size. Make the socket buffers an integral
3018 * number of mss units; if the mss is larger than
3019 * the socket buffer, decrease the mss.
3022 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
3024 bufsize = so->so_snd.ssb_hiwat;
3028 bufsize = roundup(bufsize, mss);
3029 if (bufsize > sb_max)
3031 if (bufsize > so->so_snd.ssb_hiwat)
3032 ssb_reserve(&so->so_snd, bufsize, so, NULL);
3037 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
3039 bufsize = so->so_rcv.ssb_hiwat;
3040 if (bufsize > mss) {
3041 bufsize = roundup(bufsize, mss);
3042 if (bufsize > sb_max)
3044 if (bufsize > so->so_rcv.ssb_hiwat) {
3045 lwkt_gettoken(&so->so_rcv.ssb_token);
3046 ssb_reserve(&so->so_rcv, bufsize, so, NULL);
3047 lwkt_reltoken(&so->so_rcv.ssb_token);
3052 * Set the slow-start flight size depending on whether this
3053 * is a local network or not.
3056 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3060 if (rt->rt_rmx.rmx_ssthresh) {
3062 * There's some sort of gateway or interface
3063 * buffer limit on the path. Use this to set
3064 * the slow start threshhold, but set the
3065 * threshold to no less than 2*mss.
3067 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3068 tcpstat.tcps_usedssthresh++;
3073 * Determine the MSS option to send on an outgoing SYN.
3076 tcp_mssopt(struct tcpcb *tp)
3081 ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3082 int min_protoh = isipv6 ?
3083 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
3084 sizeof(struct tcpiphdr);
3086 const boolean_t isipv6 = FALSE;
3087 const size_t min_protoh = sizeof(struct tcpiphdr);
3091 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
3093 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
3095 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3097 return (rt->rt_ifp->if_mtu - min_protoh);
3101 * When a partial ack arrives, force the retransmission of the
3102 * next unacknowledged segment. Do not exit Fast Recovery.
3104 * Implement the Slow-but-Steady variant of NewReno by restarting the
3105 * the retransmission timer. Turn it off here so it can be restarted
3106 * later in tcp_output().
3109 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th, int acked)
3111 tcp_seq old_snd_nxt = tp->snd_nxt;
3112 u_long ocwnd = tp->snd_cwnd;
3114 tcp_callout_stop(tp, tp->tt_rexmt);
3116 tp->snd_nxt = th->th_ack;
3117 /* Set snd_cwnd to one segment beyond acknowledged offset. */
3118 tp->snd_cwnd = tp->t_maxseg;
3119 tp->t_flags |= TF_ACKNOW;
3121 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3122 tp->snd_nxt = old_snd_nxt;
3123 /* partial window deflation */
3125 tp->snd_cwnd = ocwnd - acked + tp->t_maxseg;
3127 tp->snd_cwnd = tp->t_maxseg;
3131 * In contrast to the Slow-but-Steady NewReno variant,
3132 * we do not reset the retransmission timer for SACK retransmissions,
3133 * except when retransmitting snd_una.
3136 tcp_sack_rexmt(struct tcpcb *tp, struct tcphdr *th)
3138 uint32_t pipe, seglen;
3141 tcp_seq old_snd_nxt = tp->snd_nxt;
3142 u_long ocwnd = tp->snd_cwnd;
3143 int nseg = 0; /* consecutive new segments */
3144 #define MAXBURST 4 /* limit burst of new packets on partial ack */
3147 pipe = tcp_sack_compute_pipe(tp);
3148 while ((tcp_seq_diff_t)(ocwnd - pipe) >= (tcp_seq_diff_t)tp->t_maxseg &&
3149 (!tcp_do_smartsack || nseg < MAXBURST) &&
3150 tcp_sack_nextseg(tp, &nextrexmt, &seglen, &lostdup)) {
3152 tcp_seq old_snd_max;
3155 if (nextrexmt == tp->snd_max)
3157 tp->snd_nxt = nextrexmt;
3158 tp->snd_cwnd = nextrexmt - tp->snd_una + seglen;
3159 old_snd_max = tp->snd_max;
3160 if (nextrexmt == tp->snd_una)
3161 tcp_callout_stop(tp, tp->tt_rexmt);
3162 error = tcp_output(tp);
3165 sent = tp->snd_nxt - nextrexmt;
3170 tcpstat.tcps_sndsackpack++;
3171 tcpstat.tcps_sndsackbyte += sent;
3172 if (SEQ_LT(nextrexmt, old_snd_max) &&
3173 SEQ_LT(tp->rexmt_high, tp->snd_nxt))
3174 tp->rexmt_high = seq_min(tp->snd_nxt, old_snd_max);
3176 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3177 tp->snd_nxt = old_snd_nxt;
3178 tp->snd_cwnd = ocwnd;
3182 * Reset idle time and keep-alive timer, typically called when a valid
3183 * tcp packet is received but may also be called when FASTKEEP is set
3184 * to prevent the previous long-timeout from calculating to a drop.
3186 * Only update t_rcvtime for non-SYN packets.
3188 * Handle the case where one side thinks the connection is established
3189 * but the other side has, say, rebooted without cleaning out the
3190 * connection. The SYNs could be construed as an attack and wind
3191 * up ignored, but in case it isn't an attack we can validate the
3192 * connection by forcing a keepalive.
3195 tcp_timer_keep_activity(struct tcpcb *tp, int thflags)
3197 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3198 if ((thflags & (TH_SYN | TH_ACK)) == TH_SYN) {
3199 tp->t_flags |= TF_KEEPALIVE;
3200 tcp_callout_reset(tp, tp->tt_keep, hz / 2,
3203 tp->t_rcvtime = ticks;
3204 tp->t_flags &= ~TF_KEEPALIVE;
3205 tcp_callout_reset(tp, tp->tt_keep,
3206 tcp_getkeepidle(tp),
3213 tcp_rmx_msl(const struct tcpcb *tp)
3216 struct inpcb *inp = tp->t_inpcb;
3219 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3221 const boolean_t isipv6 = FALSE;
3225 rt = tcp_rtlookup6(&inp->inp_inc);
3227 rt = tcp_rtlookup(&inp->inp_inc);
3228 if (rt == NULL || rt->rt_rmx.rmx_msl == 0)
3231 msl = (rt->rt_rmx.rmx_msl * hz) / 1000;