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 static int tcp_do_eifel_detect = 1;
171 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
172 &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
174 static int tcp_do_abc = 1;
175 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc, CTLFLAG_RW,
177 "TCP Appropriate Byte Counting (RFC 3465)");
180 * Define as tunable for easy testing with SACK on and off.
181 * Warning: do not change setting in the middle of an existing active TCP flow,
182 * else strange things might happen to that flow.
185 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sack, CTLFLAG_RW,
186 &tcp_do_sack, 0, "Enable SACK Algorithms");
188 int tcp_do_smartsack = 1;
189 SYSCTL_INT(_net_inet_tcp, OID_AUTO, smartsack, CTLFLAG_RW,
190 &tcp_do_smartsack, 0, "Enable Smart SACK Algorithms");
192 int tcp_do_rescuesack = 1;
193 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rescuesack, CTLFLAG_RW,
194 &tcp_do_rescuesack, 0, "Rescue retransmission for SACK");
196 int tcp_aggressive_rescuesack = 1;
197 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rescuesack_agg, CTLFLAG_RW,
198 &tcp_aggressive_rescuesack, 0, "Aggressive rescue retransmission for SACK");
200 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
201 "TCP Segment Reassembly Queue");
203 int tcp_reass_maxseg = 0;
204 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
205 &tcp_reass_maxseg, 0,
206 "Global maximum number of TCP Segments in Reassembly Queue");
208 int tcp_reass_qsize = 0;
209 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
211 "Global number of TCP Segments currently in Reassembly Queue");
213 static int tcp_reass_overflows = 0;
214 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
215 &tcp_reass_overflows, 0,
216 "Global number of TCP Segment Reassembly Queue Overflows");
218 int tcp_do_autorcvbuf = 1;
219 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
220 &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
222 int tcp_autorcvbuf_inc = 16*1024;
223 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
224 &tcp_autorcvbuf_inc, 0,
225 "Incrementor step size of automatic receive buffer");
227 int tcp_autorcvbuf_max = 2*1024*1024;
228 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
229 &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
231 int tcp_sosend_agglim = 2;
232 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sosend_agglim, CTLFLAG_RW,
233 &tcp_sosend_agglim, 0, "TCP sosend mbuf aggregation limit");
235 int tcp_sosend_async = 1;
236 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sosend_async, CTLFLAG_RW,
237 &tcp_sosend_async, 0, "TCP asynchronized pru_send");
239 static void tcp_dooptions(struct tcpopt *, u_char *, int, boolean_t);
240 static void tcp_pulloutofband(struct socket *,
241 struct tcphdr *, struct mbuf *, int);
242 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
244 static void tcp_xmit_timer(struct tcpcb *, int, tcp_seq);
245 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *, int);
246 static void tcp_sack_rexmt(struct tcpcb *, struct tcphdr *);
247 static int tcp_rmx_msl(const struct tcpcb *);
248 static void tcp_established(struct tcpcb *);
250 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
252 #define ND6_HINT(tp) \
254 if ((tp) && (tp)->t_inpcb && \
255 ((tp)->t_inpcb->inp_vflag & INP_IPV6) && \
256 (tp)->t_inpcb->in6p_route.ro_rt) \
257 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
264 * Indicate whether this ack should be delayed. We can delay the ack if
265 * - delayed acks are enabled and
266 * - there is no delayed ack timer in progress and
267 * - our last ack wasn't a 0-sized window. We never want to delay
268 * the ack that opens up a 0-sized window.
270 #define DELAY_ACK(tp) \
271 (tcp_delack_enabled && !tcp_callout_pending(tp, tp->tt_delack) && \
272 !(tp->t_flags & TF_RXWIN0SENT))
274 #define acceptable_window_update(tp, th, tiwin) \
275 (SEQ_LT(tp->snd_wl1, th->th_seq) || \
276 (tp->snd_wl1 == th->th_seq && \
277 (SEQ_LT(tp->snd_wl2, th->th_ack) || \
278 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))
281 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
284 struct tseg_qent *p = NULL;
285 struct tseg_qent *te;
286 struct socket *so = tp->t_inpcb->inp_socket;
290 * Call with th == NULL after become established to
291 * force pre-ESTABLISHED data up to user socket.
297 * Limit the number of segments in the reassembly queue to prevent
298 * holding on to too many segments (and thus running out of mbufs).
299 * Make sure to let the missing segment through which caused this
300 * queue. Always keep one global queue entry spare to be able to
301 * process the missing segment.
303 if (th->th_seq != tp->rcv_nxt &&
304 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
305 tcp_reass_overflows++;
306 tcpstat.tcps_rcvmemdrop++;
308 /* no SACK block to report */
309 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
313 /* Allocate a new queue entry. */
314 te = kmalloc(sizeof(struct tseg_qent), M_TSEGQ, M_INTWAIT | M_NULLOK);
316 tcpstat.tcps_rcvmemdrop++;
318 /* no SACK block to report */
319 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
322 atomic_add_int(&tcp_reass_qsize, 1);
325 * Find a segment which begins after this one does.
327 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
328 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
334 * If there is a preceding segment, it may provide some of
335 * our data already. If so, drop the data from the incoming
336 * segment. If it provides all of our data, drop us.
341 /* conversion to int (in i) handles seq wraparound */
342 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
343 if (i > 0) { /* overlaps preceding segment */
344 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
345 /* enclosing block starts w/ preceding segment */
346 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
348 /* preceding encloses incoming segment */
349 tp->encloseblk.rblk_end = TCP_SACK_BLKEND(
350 p->tqe_th->th_seq + p->tqe_len,
351 p->tqe_th->th_flags);
352 tcpstat.tcps_rcvduppack++;
353 tcpstat.tcps_rcvdupbyte += *tlenp;
356 atomic_add_int(&tcp_reass_qsize, -1);
358 * Try to present any queued data
359 * at the left window edge to the user.
360 * This is needed after the 3-WHS
363 goto present; /* ??? */
368 /* incoming segment end is enclosing block end */
369 tp->encloseblk.rblk_end = TCP_SACK_BLKEND(
370 th->th_seq + *tlenp, th->th_flags);
371 /* trim end of reported D-SACK block */
372 tp->reportblk.rblk_end = th->th_seq;
375 tcpstat.tcps_rcvoopack++;
376 tcpstat.tcps_rcvoobyte += *tlenp;
379 * While we overlap succeeding segments trim them or,
380 * if they are completely covered, dequeue them.
383 tcp_seq_diff_t i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
384 tcp_seq qend = q->tqe_th->th_seq + q->tqe_len;
385 tcp_seq qend_sack = TCP_SACK_BLKEND(qend, q->tqe_th->th_flags);
386 struct tseg_qent *nq;
390 if (!(tp->t_flags & TF_DUPSEG)) { /* first time through */
391 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
392 tp->encloseblk = tp->reportblk;
393 /* report trailing duplicate D-SACK segment */
394 tp->reportblk.rblk_start = q->tqe_th->th_seq;
396 if ((tp->t_flags & TF_ENCLOSESEG) &&
397 SEQ_GT(qend_sack, tp->encloseblk.rblk_end)) {
398 /* extend enclosing block if one exists */
399 tp->encloseblk.rblk_end = qend_sack;
401 if (i < q->tqe_len) {
402 q->tqe_th->th_seq += i;
408 nq = LIST_NEXT(q, tqe_q);
409 LIST_REMOVE(q, tqe_q);
412 atomic_add_int(&tcp_reass_qsize, -1);
416 /* Insert the new segment queue entry into place. */
419 te->tqe_len = *tlenp;
421 /* check if can coalesce with following segment */
422 if (q != NULL && (th->th_seq + *tlenp == q->tqe_th->th_seq)) {
423 tcp_seq tend = te->tqe_th->th_seq + te->tqe_len;
424 tcp_seq tend_sack = TCP_SACK_BLKEND(tend, te->tqe_th->th_flags);
426 te->tqe_len += q->tqe_len;
427 if (q->tqe_th->th_flags & TH_FIN)
428 te->tqe_th->th_flags |= TH_FIN;
429 m_cat(te->tqe_m, q->tqe_m);
430 tp->encloseblk.rblk_end = tend_sack;
432 * When not reporting a duplicate segment, use
433 * the larger enclosing block as the SACK block.
435 if (!(tp->t_flags & TF_DUPSEG))
436 tp->reportblk.rblk_end = tend_sack;
437 LIST_REMOVE(q, tqe_q);
439 atomic_add_int(&tcp_reass_qsize, -1);
443 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
445 /* check if can coalesce with preceding segment */
446 if (p->tqe_th->th_seq + p->tqe_len == th->th_seq) {
447 p->tqe_len += te->tqe_len;
448 m_cat(p->tqe_m, te->tqe_m);
449 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
451 * When not reporting a duplicate segment, use
452 * the larger enclosing block as the SACK block.
454 if (!(tp->t_flags & TF_DUPSEG))
455 tp->reportblk.rblk_start = p->tqe_th->th_seq;
457 atomic_add_int(&tcp_reass_qsize, -1);
459 LIST_INSERT_AFTER(p, te, tqe_q);
465 * Present data to user, advancing rcv_nxt through
466 * completed sequence space.
468 if (!TCPS_HAVEESTABLISHED(tp->t_state))
470 q = LIST_FIRST(&tp->t_segq);
471 if (q == NULL || q->tqe_th->th_seq != tp->rcv_nxt)
473 tp->rcv_nxt += q->tqe_len;
474 if (!(tp->t_flags & TF_DUPSEG)) {
475 /* no SACK block to report since ACK advanced */
476 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
478 /* no enclosing block to report since ACK advanced */
479 tp->t_flags &= ~TF_ENCLOSESEG;
480 flags = q->tqe_th->th_flags & TH_FIN;
481 LIST_REMOVE(q, tqe_q);
482 KASSERT(LIST_EMPTY(&tp->t_segq) ||
483 LIST_FIRST(&tp->t_segq)->tqe_th->th_seq != tp->rcv_nxt,
484 ("segment not coalesced"));
485 if (so->so_state & SS_CANTRCVMORE) {
488 lwkt_gettoken(&so->so_rcv.ssb_token);
489 ssb_appendstream(&so->so_rcv, q->tqe_m);
490 lwkt_reltoken(&so->so_rcv.ssb_token);
493 atomic_add_int(&tcp_reass_qsize, -1);
500 * TCP input routine, follows pages 65-76 of the
501 * protocol specification dated September, 1981 very closely.
505 tcp6_input(struct mbuf **mp, int *offp, int proto)
507 struct mbuf *m = *mp;
508 struct in6_ifaddr *ia6;
510 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
513 * draft-itojun-ipv6-tcp-to-anycast
514 * better place to put this in?
516 ia6 = ip6_getdstifaddr(m);
517 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
520 ip6 = mtod(m, struct ip6_hdr *);
521 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
522 offsetof(struct ip6_hdr, ip6_dst));
523 return (IPPROTO_DONE);
526 tcp_input(mp, offp, proto);
527 return (IPPROTO_DONE);
532 tcp_input(struct mbuf **mp, int *offp, int proto)
536 struct ip *ip = NULL;
538 struct inpcb *inp = NULL;
544 struct tcpcb *tp = NULL;
546 struct socket *so = NULL;
548 boolean_t ourfinisacked, needoutput = FALSE;
551 struct tcpopt to; /* options in this segment */
552 struct sockaddr_in *next_hop = NULL;
553 int rstreason; /* For badport_bandlim accounting purposes */
555 struct ip6_hdr *ip6 = NULL;
560 const boolean_t isipv6 = FALSE;
570 tcpstat.tcps_rcvtotal++;
572 if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
575 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
576 KKASSERT(mtag != NULL);
577 next_hop = m_tag_data(mtag);
581 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
585 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
586 ip6 = mtod(m, struct ip6_hdr *);
587 tlen = (sizeof *ip6) + ntohs(ip6->ip6_plen) - off0;
588 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
589 tcpstat.tcps_rcvbadsum++;
592 th = (struct tcphdr *)((caddr_t)ip6 + off0);
595 * Be proactive about unspecified IPv6 address in source.
596 * As we use all-zero to indicate unbounded/unconnected pcb,
597 * unspecified IPv6 address can be used to confuse us.
599 * Note that packets with unspecified IPv6 destination is
600 * already dropped in ip6_input.
602 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
608 * Get IP and TCP header together in first mbuf.
609 * Note: IP leaves IP header in first mbuf.
611 if (off0 > sizeof(struct ip)) {
613 off0 = sizeof(struct ip);
615 /* already checked and pulled up in ip_demux() */
616 KASSERT(m->m_len >= sizeof(struct tcpiphdr),
617 ("TCP header not in one mbuf: m->m_len %d", m->m_len));
618 ip = mtod(m, struct ip *);
619 ipov = (struct ipovly *)ip;
620 th = (struct tcphdr *)((caddr_t)ip + off0);
623 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
624 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
625 th->th_sum = m->m_pkthdr.csum_data;
627 th->th_sum = in_pseudo(ip->ip_src.s_addr,
629 htonl(m->m_pkthdr.csum_data +
632 th->th_sum ^= 0xffff;
635 * Checksum extended TCP header and data.
637 len = sizeof(struct ip) + tlen;
638 bzero(ipov->ih_x1, sizeof ipov->ih_x1);
639 ipov->ih_len = (u_short)tlen;
640 ipov->ih_len = htons(ipov->ih_len);
641 th->th_sum = in_cksum(m, len);
644 tcpstat.tcps_rcvbadsum++;
648 /* Re-initialization for later version check */
649 ip->ip_v = IPVERSION;
654 * Check that TCP offset makes sense,
655 * pull out TCP options and adjust length. XXX
657 off = th->th_off << 2;
658 /* already checked and pulled up in ip_demux() */
659 KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
660 ("bad TCP data offset %d (tlen %d)", off, tlen));
661 tlen -= off; /* tlen is used instead of ti->ti_len */
662 if (off > sizeof(struct tcphdr)) {
664 IP6_EXTHDR_CHECK(m, off0, off, IPPROTO_DONE);
665 ip6 = mtod(m, struct ip6_hdr *);
666 th = (struct tcphdr *)((caddr_t)ip6 + off0);
668 /* already pulled up in ip_demux() */
669 KASSERT(m->m_len >= sizeof(struct ip) + off,
670 ("TCP header and options not in one mbuf: "
671 "m_len %d, off %d", m->m_len, off));
673 optlen = off - sizeof(struct tcphdr);
674 optp = (u_char *)(th + 1);
676 thflags = th->th_flags;
678 #ifdef TCP_DROP_SYNFIN
680 * If the drop_synfin option is enabled, drop all packets with
681 * both the SYN and FIN bits set. This prevents e.g. nmap from
682 * identifying the TCP/IP stack.
684 * This is a violation of the TCP specification.
686 if (drop_synfin && (thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN))
691 * Convert TCP protocol specific fields to host format.
693 th->th_seq = ntohl(th->th_seq);
694 th->th_ack = ntohl(th->th_ack);
695 th->th_win = ntohs(th->th_win);
696 th->th_urp = ntohs(th->th_urp);
699 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
700 * until after ip6_savecontrol() is called and before other functions
701 * which don't want those proto headers.
702 * Because ip6_savecontrol() is going to parse the mbuf to
703 * search for data to be passed up to user-land, it wants mbuf
704 * parameters to be unchanged.
705 * XXX: the call of ip6_savecontrol() has been obsoleted based on
706 * latest version of the advanced API (20020110).
708 drop_hdrlen = off0 + off;
711 * Locate pcb for segment.
714 /* IPFIREWALL_FORWARD section */
715 if (next_hop != NULL && !isipv6) { /* IPv6 support is not there yet */
717 * Transparently forwarded. Pretend to be the destination.
718 * already got one like this?
720 cpu = mycpu->gd_cpuid;
721 inp = in_pcblookup_hash(&tcbinfo[cpu],
722 ip->ip_src, th->th_sport,
723 ip->ip_dst, th->th_dport,
724 0, m->m_pkthdr.rcvif);
727 * It's new. Try to find the ambushing socket.
731 * The rest of the ipfw code stores the port in
733 * (The IP address is still in network order.)
735 in_port_t dport = next_hop->sin_port ?
736 htons(next_hop->sin_port) :
739 cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
740 next_hop->sin_addr.s_addr, dport);
741 inp = in_pcblookup_hash(&tcbinfo[cpu],
742 ip->ip_src, th->th_sport,
743 next_hop->sin_addr, dport,
744 1, m->m_pkthdr.rcvif);
748 inp = in6_pcblookup_hash(&tcbinfo[0],
749 &ip6->ip6_src, th->th_sport,
750 &ip6->ip6_dst, th->th_dport,
751 1, m->m_pkthdr.rcvif);
753 cpu = mycpu->gd_cpuid;
754 inp = in_pcblookup_hash(&tcbinfo[cpu],
755 ip->ip_src, th->th_sport,
756 ip->ip_dst, th->th_dport,
757 1, m->m_pkthdr.rcvif);
762 * If the state is CLOSED (i.e., TCB does not exist) then
763 * all data in the incoming segment is discarded.
764 * If the TCB exists but is in CLOSED state, it is embryonic,
765 * but should either do a listen or a connect soon.
770 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
772 char dbuf[sizeof "aaa.bbb.ccc.ddd"];
773 char sbuf[sizeof "aaa.bbb.ccc.ddd"];
777 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
780 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
783 strcpy(dbuf, inet_ntoa(ip->ip_dst));
784 strcpy(sbuf, inet_ntoa(ip->ip_src));
786 switch (log_in_vain) {
788 if (!(thflags & TH_SYN))
792 "Connection attempt to TCP %s:%d "
793 "from %s:%d flags:0x%02x\n",
794 dbuf, ntohs(th->th_dport), sbuf,
795 ntohs(th->th_sport), thflags);
804 if (thflags & TH_SYN)
813 rstreason = BANDLIM_RST_CLOSEDPORT;
819 if (ipsec6_in_reject_so(m, inp->inp_socket)) {
820 ipsec6stat.in_polvio++;
824 if (ipsec4_in_reject_so(m, inp->inp_socket)) {
825 ipsecstat.in_polvio++;
832 if (ipsec6_in_reject(m, inp))
835 if (ipsec4_in_reject(m, inp))
839 /* Check the minimum TTL for socket. */
841 if ((isipv6 ? ip6->ip6_hlim : ip->ip_ttl) < inp->inp_ip_minttl)
847 rstreason = BANDLIM_RST_CLOSEDPORT;
850 if (tp->t_state <= TCPS_CLOSED)
853 so = inp->inp_socket;
856 if (so->so_options & SO_DEBUG) {
857 ostate = tp->t_state;
859 bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
861 bcopy(ip, tcp_saveipgen, sizeof(*ip));
866 bzero(&to, sizeof to);
868 if (so->so_options & SO_ACCEPTCONN) {
869 struct in_conninfo inc;
872 inc.inc_isipv6 = (isipv6 == TRUE);
875 inc.inc6_faddr = ip6->ip6_src;
876 inc.inc6_laddr = ip6->ip6_dst;
877 inc.inc6_route.ro_rt = NULL; /* XXX */
879 inc.inc_faddr = ip->ip_src;
880 inc.inc_laddr = ip->ip_dst;
881 inc.inc_route.ro_rt = NULL; /* XXX */
883 inc.inc_fport = th->th_sport;
884 inc.inc_lport = th->th_dport;
887 * If the state is LISTEN then ignore segment if it contains
888 * a RST. If the segment contains an ACK then it is bad and
889 * send a RST. If it does not contain a SYN then it is not
890 * interesting; drop it.
892 * If the state is SYN_RECEIVED (syncache) and seg contains
893 * an ACK, but not for our SYN/ACK, send a RST. If the seg
894 * contains a RST, check the sequence number to see if it
895 * is a valid reset segment.
897 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
898 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) == TH_ACK) {
899 if (!syncache_expand(&inc, th, &so, m)) {
901 * No syncache entry, or ACK was not
902 * for our SYN/ACK. Send a RST.
904 tcpstat.tcps_badsyn++;
905 rstreason = BANDLIM_RST_OPENPORT;
910 * Could not complete 3-way handshake,
911 * connection is being closed down, and
912 * syncache will free mbuf.
915 return(IPPROTO_DONE);
918 * We must be in the correct protocol thread
919 * for this connection.
921 KKASSERT(so->so_port == &curthread->td_msgport);
924 * Socket is created in state SYN_RECEIVED.
925 * Continue processing segment.
930 * This is what would have happened in
931 * tcp_output() when the SYN,ACK was sent.
933 tp->snd_up = tp->snd_una;
934 tp->snd_max = tp->snd_nxt = tp->iss + 1;
935 tp->last_ack_sent = tp->rcv_nxt;
939 if (thflags & TH_RST) {
940 syncache_chkrst(&inc, th);
943 if (thflags & TH_ACK) {
944 syncache_badack(&inc);
945 tcpstat.tcps_badsyn++;
946 rstreason = BANDLIM_RST_OPENPORT;
953 * Segment's flags are (SYN) or (SYN | FIN).
957 * If deprecated address is forbidden,
958 * we do not accept SYN to deprecated interface
959 * address to prevent any new inbound connection from
960 * getting established.
961 * When we do not accept SYN, we send a TCP RST,
962 * with deprecated source address (instead of dropping
963 * it). We compromise it as it is much better for peer
964 * to send a RST, and RST will be the final packet
967 * If we do not forbid deprecated addresses, we accept
968 * the SYN packet. RFC2462 does not suggest dropping
970 * If we decipher RFC2462 5.5.4, it says like this:
971 * 1. use of deprecated addr with existing
972 * communication is okay - "SHOULD continue to be
974 * 2. use of it with new communication:
975 * (2a) "SHOULD NOT be used if alternate address
976 * with sufficient scope is available"
977 * (2b) nothing mentioned otherwise.
978 * Here we fall into (2b) case as we have no choice in
979 * our source address selection - we must obey the peer.
981 * The wording in RFC2462 is confusing, and there are
982 * multiple description text for deprecated address
983 * handling - worse, they are not exactly the same.
984 * I believe 5.5.4 is the best one, so we follow 5.5.4.
986 if (isipv6 && !ip6_use_deprecated) {
987 struct in6_ifaddr *ia6;
989 if ((ia6 = ip6_getdstifaddr(m)) &&
990 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
992 rstreason = BANDLIM_RST_OPENPORT;
998 * If it is from this socket, drop it, it must be forged.
999 * Don't bother responding if the destination was a broadcast.
1001 if (th->th_dport == th->th_sport) {
1003 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
1007 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
1012 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1014 * Note that it is quite possible to receive unicast
1015 * link-layer packets with a broadcast IP address. Use
1016 * in_broadcast() to find them.
1018 if (m->m_flags & (M_BCAST | M_MCAST))
1021 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1022 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
1025 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1026 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1027 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1028 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1032 * SYN appears to be valid; create compressed TCP state
1033 * for syncache, or perform t/tcp connection.
1035 if (so->so_qlen <= so->so_qlimit) {
1036 tcp_dooptions(&to, optp, optlen, TRUE);
1037 if (!syncache_add(&inc, &to, th, so, m))
1041 * Entry added to syncache, mbuf used to
1042 * send SYN,ACK packet.
1044 return(IPPROTO_DONE);
1051 * Should not happen - syncache should pick up these connections.
1053 * Once we are past handling listen sockets we must be in the
1054 * correct protocol processing thread.
1056 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN state"));
1057 KKASSERT(so->so_port == &curthread->td_msgport);
1059 /* Unscale the window into a 32-bit value. */
1060 if (!(thflags & TH_SYN))
1061 tiwin = th->th_win << tp->snd_scale;
1066 * This is the second part of the MSS DoS prevention code (after
1067 * minmss on the sending side) and it deals with too many too small
1068 * tcp packets in a too short timeframe (1 second).
1070 * XXX Removed. This code was crap. It does not scale to network
1071 * speed, and default values break NFS. Gone.
1076 * Segment received on connection.
1078 * Reset idle time and keep-alive timer. Don't waste time if less
1079 * then a second has elapsed.
1081 if ((int)(ticks - tp->t_rcvtime) > hz)
1082 tcp_timer_keep_activity(tp, thflags);
1086 * XXX this is tradtitional behavior, may need to be cleaned up.
1088 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0);
1089 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1090 if ((to.to_flags & TOF_SCALE) && (tp->t_flags & TF_REQ_SCALE)) {
1091 tp->t_flags |= TF_RCVD_SCALE;
1092 tp->snd_scale = to.to_requested_s_scale;
1096 * Initial send window; will be updated upon next ACK
1098 tp->snd_wnd = th->th_win;
1100 if (to.to_flags & TOF_TS) {
1101 tp->t_flags |= TF_RCVD_TSTMP;
1102 tp->ts_recent = to.to_tsval;
1103 tp->ts_recent_age = ticks;
1105 if (!(to.to_flags & TOF_MSS))
1107 tcp_mss(tp, to.to_mss);
1109 * Only set the TF_SACK_PERMITTED per-connection flag
1110 * if we got a SACK_PERMITTED option from the other side
1111 * and the global tcp_do_sack variable is true.
1113 if (tcp_do_sack && (to.to_flags & TOF_SACK_PERMITTED))
1114 tp->t_flags |= TF_SACK_PERMITTED;
1118 * Header prediction: check for the two common cases
1119 * of a uni-directional data xfer. If the packet has
1120 * no control flags, is in-sequence, the window didn't
1121 * change and we're not retransmitting, it's a
1122 * candidate. If the length is zero and the ack moved
1123 * forward, we're the sender side of the xfer. Just
1124 * free the data acked & wake any higher level process
1125 * that was blocked waiting for space. If the length
1126 * is non-zero and the ack didn't move, we're the
1127 * receiver side. If we're getting packets in-order
1128 * (the reassembly queue is empty), add the data to
1129 * the socket buffer and note that we need a delayed ack.
1130 * Make sure that the hidden state-flags are also off.
1131 * Since we check for TCPS_ESTABLISHED above, it can only
1134 if (tp->t_state == TCPS_ESTABLISHED &&
1135 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1136 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1137 (!(to.to_flags & TOF_TS) ||
1138 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1139 th->th_seq == tp->rcv_nxt &&
1140 tp->snd_nxt == tp->snd_max) {
1143 * If last ACK falls within this segment's sequence numbers,
1144 * record the timestamp.
1145 * NOTE that the test is modified according to the latest
1146 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1148 if ((to.to_flags & TOF_TS) &&
1149 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1150 tp->ts_recent_age = ticks;
1151 tp->ts_recent = to.to_tsval;
1155 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1156 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1157 tp->snd_cwnd >= tp->snd_wnd &&
1158 !IN_FASTRECOVERY(tp)) {
1160 * This is a pure ack for outstanding data.
1162 ++tcpstat.tcps_predack;
1164 * "bad retransmit" recovery
1166 * If Eifel detection applies, then
1167 * it is deterministic, so use it
1168 * unconditionally over the old heuristic.
1169 * Otherwise, fall back to the old heuristic.
1171 if (tcp_do_eifel_detect &&
1172 (to.to_flags & TOF_TS) && to.to_tsecr &&
1173 (tp->t_flags & TF_FIRSTACCACK)) {
1174 /* Eifel detection applicable. */
1175 if (to.to_tsecr < tp->t_rexmtTS) {
1176 tcp_revert_congestion_state(tp);
1177 ++tcpstat.tcps_eifeldetected;
1178 if (tp->t_rxtshift != 1 ||
1179 ticks >= tp->t_badrxtwin)
1180 ++tcpstat.tcps_rttcantdetect;
1182 } else if (tp->t_rxtshift == 1 &&
1183 ticks < tp->t_badrxtwin) {
1184 tcp_revert_congestion_state(tp);
1185 ++tcpstat.tcps_rttdetected;
1187 tp->t_flags &= ~(TF_FIRSTACCACK |
1188 TF_FASTREXMT | TF_EARLYREXMT);
1190 * Recalculate the retransmit timer / rtt.
1192 * Some machines (certain windows boxes)
1193 * send broken timestamp replies during the
1194 * SYN+ACK phase, ignore timestamps of 0.
1196 if ((to.to_flags & TOF_TS) && to.to_tsecr) {
1198 ticks - to.to_tsecr + 1,
1200 } else if (tp->t_rtttime &&
1201 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1203 ticks - tp->t_rtttime,
1206 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1207 acked = th->th_ack - tp->snd_una;
1208 tcpstat.tcps_rcvackpack++;
1209 tcpstat.tcps_rcvackbyte += acked;
1210 sbdrop(&so->so_snd.sb, acked);
1211 tp->snd_recover = th->th_ack - 1;
1212 tp->snd_una = th->th_ack;
1215 * Update window information.
1217 if (tiwin != tp->snd_wnd &&
1218 acceptable_window_update(tp, th, tiwin)) {
1219 /* keep track of pure window updates */
1220 if (tp->snd_wl2 == th->th_ack &&
1221 tiwin > tp->snd_wnd)
1222 tcpstat.tcps_rcvwinupd++;
1223 tp->snd_wnd = tiwin;
1224 tp->snd_wl1 = th->th_seq;
1225 tp->snd_wl2 = th->th_ack;
1226 if (tp->snd_wnd > tp->max_sndwnd)
1227 tp->max_sndwnd = tp->snd_wnd;
1230 ND6_HINT(tp); /* some progress has been done */
1232 * If all outstanding data are acked, stop
1233 * retransmit timer, otherwise restart timer
1234 * using current (possibly backed-off) value.
1235 * If process is waiting for space,
1236 * wakeup/selwakeup/signal. If data
1237 * are ready to send, let tcp_output
1238 * decide between more output or persist.
1240 if (tp->snd_una == tp->snd_max) {
1241 tcp_callout_stop(tp, tp->tt_rexmt);
1242 } else if (!tcp_callout_active(tp,
1244 tcp_callout_reset(tp, tp->tt_rexmt,
1245 tp->t_rxtcur, tcp_timer_rexmt);
1248 if (so->so_snd.ssb_cc > 0)
1250 return(IPPROTO_DONE);
1252 } else if (tiwin == tp->snd_wnd &&
1253 th->th_ack == tp->snd_una &&
1254 LIST_EMPTY(&tp->t_segq) &&
1255 tlen <= ssb_space(&so->so_rcv)) {
1256 u_long newsize = 0; /* automatic sockbuf scaling */
1258 * This is a pure, in-sequence data packet
1259 * with nothing on the reassembly queue and
1260 * we have enough buffer space to take it.
1262 ++tcpstat.tcps_preddat;
1263 tp->rcv_nxt += tlen;
1264 tcpstat.tcps_rcvpack++;
1265 tcpstat.tcps_rcvbyte += tlen;
1266 ND6_HINT(tp); /* some progress has been done */
1268 * Automatic sizing of receive socket buffer. Often the send
1269 * buffer size is not optimally adjusted to the actual network
1270 * conditions at hand (delay bandwidth product). Setting the
1271 * buffer size too small limits throughput on links with high
1272 * bandwidth and high delay (eg. trans-continental/oceanic links).
1274 * On the receive side the socket buffer memory is only rarely
1275 * used to any significant extent. This allows us to be much
1276 * more aggressive in scaling the receive socket buffer. For
1277 * the case that the buffer space is actually used to a large
1278 * extent and we run out of kernel memory we can simply drop
1279 * the new segments; TCP on the sender will just retransmit it
1280 * later. Setting the buffer size too big may only consume too
1281 * much kernel memory if the application doesn't read() from
1282 * the socket or packet loss or reordering makes use of the
1285 * The criteria to step up the receive buffer one notch are:
1286 * 1. the number of bytes received during the time it takes
1287 * one timestamp to be reflected back to us (the RTT);
1288 * 2. received bytes per RTT is within seven eighth of the
1289 * current socket buffer size;
1290 * 3. receive buffer size has not hit maximal automatic size;
1292 * This algorithm does one step per RTT at most and only if
1293 * we receive a bulk stream w/o packet losses or reorderings.
1294 * Shrinking the buffer during idle times is not necessary as
1295 * it doesn't consume any memory when idle.
1297 * TODO: Only step up if the application is actually serving
1298 * the buffer to better manage the socket buffer resources.
1300 if (tcp_do_autorcvbuf &&
1302 (so->so_rcv.ssb_flags & SSB_AUTOSIZE)) {
1303 if (to.to_tsecr > tp->rfbuf_ts &&
1304 to.to_tsecr - tp->rfbuf_ts < hz) {
1306 (so->so_rcv.ssb_hiwat / 8 * 7) &&
1307 so->so_rcv.ssb_hiwat <
1308 tcp_autorcvbuf_max) {
1310 ulmin(so->so_rcv.ssb_hiwat +
1312 tcp_autorcvbuf_max);
1314 /* Start over with next RTT. */
1318 tp->rfbuf_cnt += tlen; /* add up */
1321 * Add data to socket buffer.
1323 if (so->so_state & SS_CANTRCVMORE) {
1327 * Set new socket buffer size, give up when
1330 * Adjusting the size can mess up ACK
1331 * sequencing when pure window updates are
1332 * being avoided (which is the default),
1335 lwkt_gettoken(&so->so_rcv.ssb_token);
1337 tp->t_flags |= TF_RXRESIZED;
1338 if (!ssb_reserve(&so->so_rcv, newsize,
1340 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1343 (TCP_MAXWIN << tp->rcv_scale)) {
1344 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1347 m_adj(m, drop_hdrlen); /* delayed header drop */
1348 ssb_appendstream(&so->so_rcv, m);
1349 lwkt_reltoken(&so->so_rcv.ssb_token);
1353 * This code is responsible for most of the ACKs
1354 * the TCP stack sends back after receiving a data
1355 * packet. Note that the DELAY_ACK check fails if
1356 * the delack timer is already running, which results
1357 * in an ack being sent every other packet (which is
1360 * We then further aggregate acks by not actually
1361 * sending one until the protocol thread has completed
1362 * processing the current backlog of packets. This
1363 * does not delay the ack any further, but allows us
1364 * to take advantage of the packet aggregation that
1365 * high speed NICs do (usually blocks of 8-10 packets)
1366 * to send a single ack rather then four or five acks,
1367 * greatly reducing the ack rate, the return channel
1368 * bandwidth, and the protocol overhead on both ends.
1370 * Since this also has the effect of slowing down
1371 * the exponential slow-start ramp-up, systems with
1372 * very large bandwidth-delay products might want
1373 * to turn the feature off.
1375 if (DELAY_ACK(tp)) {
1376 tcp_callout_reset(tp, tp->tt_delack,
1377 tcp_delacktime, tcp_timer_delack);
1378 } else if (tcp_aggregate_acks) {
1379 tp->t_flags |= TF_ACKNOW;
1380 if (!(tp->t_flags & TF_ONOUTPUTQ)) {
1381 tp->t_flags |= TF_ONOUTPUTQ;
1382 tp->tt_cpu = mycpu->gd_cpuid;
1384 &tcpcbackq[tp->tt_cpu],
1388 tp->t_flags |= TF_ACKNOW;
1391 return(IPPROTO_DONE);
1396 * Calculate amount of space in receive window,
1397 * and then do TCP input processing.
1398 * Receive window is amount of space in rcv queue,
1399 * but not less than advertised window.
1401 recvwin = ssb_space(&so->so_rcv);
1404 tp->rcv_wnd = imax(recvwin, (int)(tp->rcv_adv - tp->rcv_nxt));
1406 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1410 switch (tp->t_state) {
1412 * If the state is SYN_RECEIVED:
1413 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1415 case TCPS_SYN_RECEIVED:
1416 if ((thflags & TH_ACK) &&
1417 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1418 SEQ_GT(th->th_ack, tp->snd_max))) {
1419 rstreason = BANDLIM_RST_OPENPORT;
1425 * If the state is SYN_SENT:
1426 * if seg contains an ACK, but not for our SYN, drop the input.
1427 * if seg contains a RST, then drop the connection.
1428 * if seg does not contain SYN, then drop it.
1429 * Otherwise this is an acceptable SYN segment
1430 * initialize tp->rcv_nxt and tp->irs
1431 * if seg contains ack then advance tp->snd_una
1432 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1433 * arrange for segment to be acked (eventually)
1434 * continue processing rest of data/controls, beginning with URG
1437 if ((thflags & TH_ACK) &&
1438 (SEQ_LEQ(th->th_ack, tp->iss) ||
1439 SEQ_GT(th->th_ack, tp->snd_max))) {
1440 rstreason = BANDLIM_UNLIMITED;
1443 if (thflags & TH_RST) {
1444 if (thflags & TH_ACK)
1445 tp = tcp_drop(tp, ECONNREFUSED);
1448 if (!(thflags & TH_SYN))
1451 tp->irs = th->th_seq;
1453 if (thflags & TH_ACK) {
1454 /* Our SYN was acked. */
1455 tcpstat.tcps_connects++;
1457 /* Do window scaling on this connection? */
1458 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1459 (TF_RCVD_SCALE | TF_REQ_SCALE))
1460 tp->rcv_scale = tp->request_r_scale;
1461 tp->rcv_adv += tp->rcv_wnd;
1462 tp->snd_una++; /* SYN is acked */
1463 tcp_callout_stop(tp, tp->tt_rexmt);
1465 * If there's data, delay ACK; if there's also a FIN
1466 * ACKNOW will be turned on later.
1468 if (DELAY_ACK(tp) && tlen != 0) {
1469 tcp_callout_reset(tp, tp->tt_delack,
1470 tcp_delacktime, tcp_timer_delack);
1472 tp->t_flags |= TF_ACKNOW;
1475 * Received <SYN,ACK> in SYN_SENT[*] state.
1477 * SYN_SENT --> ESTABLISHED
1478 * SYN_SENT* --> FIN_WAIT_1
1480 tp->t_starttime = ticks;
1481 if (tp->t_flags & TF_NEEDFIN) {
1482 tp->t_state = TCPS_FIN_WAIT_1;
1483 tp->t_flags &= ~TF_NEEDFIN;
1486 tcp_established(tp);
1490 * Received initial SYN in SYN-SENT[*] state =>
1491 * simultaneous open.
1492 * Do 3-way handshake:
1493 * SYN-SENT -> SYN-RECEIVED
1494 * SYN-SENT* -> SYN-RECEIVED*
1496 tp->t_flags |= TF_ACKNOW;
1497 tcp_callout_stop(tp, tp->tt_rexmt);
1498 tp->t_state = TCPS_SYN_RECEIVED;
1502 * Advance th->th_seq to correspond to first data byte.
1503 * If data, trim to stay within window,
1504 * dropping FIN if necessary.
1507 if (tlen > tp->rcv_wnd) {
1508 todrop = tlen - tp->rcv_wnd;
1512 tcpstat.tcps_rcvpackafterwin++;
1513 tcpstat.tcps_rcvbyteafterwin += todrop;
1515 tp->snd_wl1 = th->th_seq - 1;
1516 tp->rcv_up = th->th_seq;
1518 * Client side of transaction: already sent SYN and data.
1519 * If the remote host used T/TCP to validate the SYN,
1520 * our data will be ACK'd; if so, enter normal data segment
1521 * processing in the middle of step 5, ack processing.
1522 * Otherwise, goto step 6.
1524 if (thflags & TH_ACK)
1530 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1531 * do normal processing (we no longer bother with T/TCP).
1535 case TCPS_TIME_WAIT:
1536 break; /* continue normal processing */
1540 * States other than LISTEN or SYN_SENT.
1541 * First check the RST flag and sequence number since reset segments
1542 * are exempt from the timestamp and connection count tests. This
1543 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1544 * below which allowed reset segments in half the sequence space
1545 * to fall though and be processed (which gives forged reset
1546 * segments with a random sequence number a 50 percent chance of
1547 * killing a connection).
1548 * Then check timestamp, if present.
1549 * Then check the connection count, if present.
1550 * Then check that at least some bytes of segment are within
1551 * receive window. If segment begins before rcv_nxt,
1552 * drop leading data (and SYN); if nothing left, just ack.
1555 * If the RST bit is set, check the sequence number to see
1556 * if this is a valid reset segment.
1558 * In all states except SYN-SENT, all reset (RST) segments
1559 * are validated by checking their SEQ-fields. A reset is
1560 * valid if its sequence number is in the window.
1561 * Note: this does not take into account delayed ACKs, so
1562 * we should test against last_ack_sent instead of rcv_nxt.
1563 * The sequence number in the reset segment is normally an
1564 * echo of our outgoing acknowledgement numbers, but some hosts
1565 * send a reset with the sequence number at the rightmost edge
1566 * of our receive window, and we have to handle this case.
1567 * If we have multiple segments in flight, the intial reset
1568 * segment sequence numbers will be to the left of last_ack_sent,
1569 * but they will eventually catch up.
1570 * In any case, it never made sense to trim reset segments to
1571 * fit the receive window since RFC 1122 says:
1572 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1574 * A TCP SHOULD allow a received RST segment to include data.
1577 * It has been suggested that a RST segment could contain
1578 * ASCII text that encoded and explained the cause of the
1579 * RST. No standard has yet been established for such
1582 * If the reset segment passes the sequence number test examine
1584 * SYN_RECEIVED STATE:
1585 * If passive open, return to LISTEN state.
1586 * If active open, inform user that connection was refused.
1587 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1588 * Inform user that connection was reset, and close tcb.
1589 * CLOSING, LAST_ACK STATES:
1592 * Drop the segment - see Stevens, vol. 2, p. 964 and
1595 if (thflags & TH_RST) {
1596 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1597 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1598 switch (tp->t_state) {
1600 case TCPS_SYN_RECEIVED:
1601 so->so_error = ECONNREFUSED;
1604 case TCPS_ESTABLISHED:
1605 case TCPS_FIN_WAIT_1:
1606 case TCPS_FIN_WAIT_2:
1607 case TCPS_CLOSE_WAIT:
1608 so->so_error = ECONNRESET;
1610 tp->t_state = TCPS_CLOSED;
1611 tcpstat.tcps_drops++;
1620 case TCPS_TIME_WAIT:
1628 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1629 * and it's less than ts_recent, drop it.
1631 if ((to.to_flags & TOF_TS) && tp->ts_recent != 0 &&
1632 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1634 /* Check to see if ts_recent is over 24 days old. */
1635 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1637 * Invalidate ts_recent. If this segment updates
1638 * ts_recent, the age will be reset later and ts_recent
1639 * will get a valid value. If it does not, setting
1640 * ts_recent to zero will at least satisfy the
1641 * requirement that zero be placed in the timestamp
1642 * echo reply when ts_recent isn't valid. The
1643 * age isn't reset until we get a valid ts_recent
1644 * because we don't want out-of-order segments to be
1645 * dropped when ts_recent is old.
1649 tcpstat.tcps_rcvduppack++;
1650 tcpstat.tcps_rcvdupbyte += tlen;
1651 tcpstat.tcps_pawsdrop++;
1659 * In the SYN-RECEIVED state, validate that the packet belongs to
1660 * this connection before trimming the data to fit the receive
1661 * window. Check the sequence number versus IRS since we know
1662 * the sequence numbers haven't wrapped. This is a partial fix
1663 * for the "LAND" DoS attack.
1665 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1666 rstreason = BANDLIM_RST_OPENPORT;
1670 todrop = tp->rcv_nxt - th->th_seq;
1672 if (TCP_DO_SACK(tp)) {
1673 /* Report duplicate segment at head of packet. */
1674 tp->reportblk.rblk_start = th->th_seq;
1675 tp->reportblk.rblk_end = TCP_SACK_BLKEND(
1676 th->th_seq + tlen, thflags);
1677 if (SEQ_GT(tp->reportblk.rblk_end, tp->rcv_nxt))
1678 tp->reportblk.rblk_end = tp->rcv_nxt;
1679 tp->t_flags |= (TF_DUPSEG | TF_SACKLEFT | TF_ACKNOW);
1681 if (thflags & TH_SYN) {
1691 * Following if statement from Stevens, vol. 2, p. 960.
1693 if (todrop > tlen ||
1694 (todrop == tlen && !(thflags & TH_FIN))) {
1696 * Any valid FIN must be to the left of the window.
1697 * At this point the FIN must be a duplicate or out
1698 * of sequence; drop it.
1703 * Send an ACK to resynchronize and drop any data.
1704 * But keep on processing for RST or ACK.
1706 tp->t_flags |= TF_ACKNOW;
1708 tcpstat.tcps_rcvduppack++;
1709 tcpstat.tcps_rcvdupbyte += todrop;
1711 tcpstat.tcps_rcvpartduppack++;
1712 tcpstat.tcps_rcvpartdupbyte += todrop;
1714 drop_hdrlen += todrop; /* drop from the top afterwards */
1715 th->th_seq += todrop;
1717 if (th->th_urp > todrop)
1718 th->th_urp -= todrop;
1726 * If new data are received on a connection after the
1727 * user processes are gone, then RST the other end.
1729 if ((so->so_state & SS_NOFDREF) &&
1730 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1732 tcpstat.tcps_rcvafterclose++;
1733 rstreason = BANDLIM_UNLIMITED;
1738 * If segment ends after window, drop trailing data
1739 * (and PUSH and FIN); if nothing left, just ACK.
1741 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1743 tcpstat.tcps_rcvpackafterwin++;
1744 if (todrop >= tlen) {
1745 tcpstat.tcps_rcvbyteafterwin += tlen;
1747 * If a new connection request is received
1748 * while in TIME_WAIT, drop the old connection
1749 * and start over if the sequence numbers
1750 * are above the previous ones.
1752 if (thflags & TH_SYN &&
1753 tp->t_state == TCPS_TIME_WAIT &&
1754 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1759 * If window is closed can only take segments at
1760 * window edge, and have to drop data and PUSH from
1761 * incoming segments. Continue processing, but
1762 * remember to ack. Otherwise, drop segment
1765 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1766 tp->t_flags |= TF_ACKNOW;
1767 tcpstat.tcps_rcvwinprobe++;
1771 tcpstat.tcps_rcvbyteafterwin += todrop;
1774 thflags &= ~(TH_PUSH | TH_FIN);
1778 * If last ACK falls within this segment's sequence numbers,
1779 * record its timestamp.
1781 * 1) That the test incorporates suggestions from the latest
1782 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1783 * 2) That updating only on newer timestamps interferes with
1784 * our earlier PAWS tests, so this check should be solely
1785 * predicated on the sequence space of this segment.
1786 * 3) That we modify the segment boundary check to be
1787 * Last.ACK.Sent <= SEG.SEQ + SEG.LEN
1788 * instead of RFC1323's
1789 * Last.ACK.Sent < SEG.SEQ + SEG.LEN,
1790 * This modified check allows us to overcome RFC1323's
1791 * limitations as described in Stevens TCP/IP Illustrated
1792 * Vol. 2 p.869. In such cases, we can still calculate the
1793 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1795 if ((to.to_flags & TOF_TS) && SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1796 SEQ_LEQ(tp->last_ack_sent, (th->th_seq + tlen
1797 + ((thflags & TH_SYN) != 0)
1798 + ((thflags & TH_FIN) != 0)))) {
1799 tp->ts_recent_age = ticks;
1800 tp->ts_recent = to.to_tsval;
1804 * If a SYN is in the window, then this is an
1805 * error and we send an RST and drop the connection.
1807 if (thflags & TH_SYN) {
1808 tp = tcp_drop(tp, ECONNRESET);
1809 rstreason = BANDLIM_UNLIMITED;
1814 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1815 * flag is on (half-synchronized state), then queue data for
1816 * later processing; else drop segment and return.
1818 if (!(thflags & TH_ACK)) {
1819 if (tp->t_state == TCPS_SYN_RECEIVED ||
1820 (tp->t_flags & TF_NEEDSYN))
1829 switch (tp->t_state) {
1831 * In SYN_RECEIVED state, the ACK acknowledges our SYN, so enter
1832 * ESTABLISHED state and continue processing.
1833 * The ACK was checked above.
1835 case TCPS_SYN_RECEIVED:
1837 tcpstat.tcps_connects++;
1839 /* Do window scaling? */
1840 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1841 (TF_RCVD_SCALE | TF_REQ_SCALE))
1842 tp->rcv_scale = tp->request_r_scale;
1845 * SYN-RECEIVED -> ESTABLISHED
1846 * SYN-RECEIVED* -> FIN-WAIT-1
1848 tp->t_starttime = ticks;
1849 if (tp->t_flags & TF_NEEDFIN) {
1850 tp->t_state = TCPS_FIN_WAIT_1;
1851 tp->t_flags &= ~TF_NEEDFIN;
1853 tcp_established(tp);
1856 * If segment contains data or ACK, will call tcp_reass()
1857 * later; if not, do so now to pass queued data to user.
1859 if (tlen == 0 && !(thflags & TH_FIN))
1860 tcp_reass(tp, NULL, NULL, NULL);
1864 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1865 * ACKs. If the ack is in the range
1866 * tp->snd_una < th->th_ack <= tp->snd_max
1867 * then advance tp->snd_una to th->th_ack and drop
1868 * data from the retransmission queue. If this ACK reflects
1869 * more up to date window information we update our window information.
1871 case TCPS_ESTABLISHED:
1872 case TCPS_FIN_WAIT_1:
1873 case TCPS_FIN_WAIT_2:
1874 case TCPS_CLOSE_WAIT:
1877 case TCPS_TIME_WAIT:
1879 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1880 if (TCP_DO_SACK(tp))
1881 tcp_sack_update_scoreboard(tp, &to);
1882 if (tlen != 0 || tiwin != tp->snd_wnd) {
1886 tcpstat.tcps_rcvdupack++;
1887 if (!tcp_callout_active(tp, tp->tt_rexmt) ||
1888 th->th_ack != tp->snd_una) {
1893 * We have outstanding data (other than
1894 * a window probe), this is a completely
1895 * duplicate ack (ie, window info didn't
1896 * change), the ack is the biggest we've
1897 * seen and we've seen exactly our rexmt
1898 * threshhold of them, so assume a packet
1899 * has been dropped and retransmit it.
1900 * Kludge snd_nxt & the congestion
1901 * window so we send only this one
1904 if (IN_FASTRECOVERY(tp)) {
1905 if (TCP_DO_SACK(tp)) {
1906 /* No artifical cwnd inflation. */
1907 tcp_sack_rexmt(tp, th);
1910 * Dup acks mean that packets
1911 * have left the network
1912 * (they're now cached at the
1913 * receiver) so bump cwnd by
1914 * the amount in the receiver
1915 * to keep a constant cwnd
1916 * packets in the network.
1918 tp->snd_cwnd += tp->t_maxseg;
1921 } else if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1924 } else if (++tp->t_dupacks == tcprexmtthresh) {
1925 tcp_seq old_snd_nxt;
1929 if (tcp_do_eifel_detect &&
1930 (tp->t_flags & TF_RCVD_TSTMP)) {
1931 tcp_save_congestion_state(tp);
1932 tp->t_flags |= TF_FASTREXMT;
1935 * We know we're losing at the current
1936 * window size, so do congestion avoidance:
1937 * set ssthresh to half the current window
1938 * and pull our congestion window back to the
1941 win = min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1945 tp->snd_ssthresh = win * tp->t_maxseg;
1946 ENTER_FASTRECOVERY(tp);
1947 tp->snd_recover = tp->snd_max;
1948 tcp_callout_stop(tp, tp->tt_rexmt);
1950 old_snd_nxt = tp->snd_nxt;
1951 tp->snd_nxt = th->th_ack;
1952 tp->snd_cwnd = tp->t_maxseg;
1954 ++tcpstat.tcps_sndfastrexmit;
1955 tp->snd_cwnd = tp->snd_ssthresh;
1956 tp->rexmt_high = tp->snd_nxt;
1957 tp->t_flags &= ~TF_SACKRESCUED;
1958 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
1959 tp->snd_nxt = old_snd_nxt;
1960 KASSERT(tp->snd_limited <= 2,
1961 ("tp->snd_limited too big"));
1962 if (TCP_DO_SACK(tp))
1963 tcp_sack_rexmt(tp, th);
1965 tp->snd_cwnd += tp->t_maxseg *
1966 (tp->t_dupacks - tp->snd_limited);
1967 } else if (tcp_do_limitedtransmit) {
1968 u_long oldcwnd = tp->snd_cwnd;
1969 tcp_seq oldsndmax = tp->snd_max;
1970 tcp_seq oldsndnxt = tp->snd_nxt;
1971 /* outstanding data */
1972 uint32_t ownd = tp->snd_max - tp->snd_una;
1975 #define iceildiv(n, d) (((n)+(d)-1) / (d))
1977 KASSERT(tp->t_dupacks == 1 ||
1979 ("dupacks not 1 or 2"));
1980 if (tp->t_dupacks == 1)
1981 tp->snd_limited = 0;
1982 tp->snd_nxt = tp->snd_max;
1983 tp->snd_cwnd = ownd +
1984 (tp->t_dupacks - tp->snd_limited) *
1988 if (SEQ_LT(oldsndnxt, oldsndmax)) {
1989 KASSERT(SEQ_GEQ(oldsndnxt, tp->snd_una),
1990 ("snd_una moved in other threads"));
1991 tp->snd_nxt = oldsndnxt;
1993 tp->snd_cwnd = oldcwnd;
1994 sent = tp->snd_max - oldsndmax;
1995 if (sent > tp->t_maxseg) {
1996 KASSERT((tp->t_dupacks == 2 &&
1997 tp->snd_limited == 0) ||
1998 (sent == tp->t_maxseg + 1 &&
1999 tp->t_flags & TF_SENTFIN),
2001 KASSERT(sent <= tp->t_maxseg * 2,
2002 ("sent too many segments"));
2003 tp->snd_limited = 2;
2004 tcpstat.tcps_sndlimited += 2;
2005 } else if (sent > 0) {
2007 ++tcpstat.tcps_sndlimited;
2008 } else if (tcp_do_early_retransmit &&
2009 (tcp_do_eifel_detect &&
2010 (tp->t_flags & TF_RCVD_TSTMP)) &&
2011 ownd < 4 * tp->t_maxseg &&
2012 tp->t_dupacks + 1 >=
2013 iceildiv(ownd, tp->t_maxseg) &&
2014 (!TCP_DO_SACK(tp) ||
2015 ownd <= tp->t_maxseg ||
2016 tcp_sack_has_sacked(&tp->scb,
2017 ownd - tp->t_maxseg))) {
2018 ++tcpstat.tcps_sndearlyrexmit;
2019 tp->t_flags |= TF_EARLYREXMT;
2020 goto fastretransmit;
2026 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
2028 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2030 * Detected optimistic ACK attack.
2031 * Force slow-start to de-synchronize attack.
2033 tp->snd_cwnd = tp->t_maxseg;
2036 tcpstat.tcps_rcvacktoomuch++;
2040 * If we reach this point, ACK is not a duplicate,
2041 * i.e., it ACKs something we sent.
2043 if (tp->t_flags & TF_NEEDSYN) {
2045 * T/TCP: Connection was half-synchronized, and our
2046 * SYN has been ACK'd (so connection is now fully
2047 * synchronized). Go to non-starred state,
2048 * increment snd_una for ACK of SYN, and check if
2049 * we can do window scaling.
2051 tp->t_flags &= ~TF_NEEDSYN;
2053 /* Do window scaling? */
2054 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
2055 (TF_RCVD_SCALE | TF_REQ_SCALE))
2056 tp->rcv_scale = tp->request_r_scale;
2060 acked = th->th_ack - tp->snd_una;
2061 tcpstat.tcps_rcvackpack++;
2062 tcpstat.tcps_rcvackbyte += acked;
2064 if (tcp_do_eifel_detect && acked > 0 &&
2065 (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
2066 (tp->t_flags & TF_FIRSTACCACK)) {
2067 /* Eifel detection applicable. */
2068 if (to.to_tsecr < tp->t_rexmtTS) {
2069 ++tcpstat.tcps_eifeldetected;
2070 tcp_revert_congestion_state(tp);
2071 if (tp->t_rxtshift != 1 ||
2072 ticks >= tp->t_badrxtwin)
2073 ++tcpstat.tcps_rttcantdetect;
2075 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2077 * If we just performed our first retransmit,
2078 * and the ACK arrives within our recovery window,
2079 * then it was a mistake to do the retransmit
2080 * in the first place. Recover our original cwnd
2081 * and ssthresh, and proceed to transmit where we
2084 tcp_revert_congestion_state(tp);
2085 ++tcpstat.tcps_rttdetected;
2089 * If we have a timestamp reply, update smoothed
2090 * round trip time. If no timestamp is present but
2091 * transmit timer is running and timed sequence
2092 * number was acked, update smoothed round trip time.
2093 * Since we now have an rtt measurement, cancel the
2094 * timer backoff (cf., Phil Karn's retransmit alg.).
2095 * Recompute the initial retransmit timer.
2097 * Some machines (certain windows boxes) send broken
2098 * timestamp replies during the SYN+ACK phase, ignore
2101 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
2102 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1, th->th_ack);
2103 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2104 tcp_xmit_timer(tp, ticks - tp->t_rtttime, th->th_ack);
2105 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2108 * If no data (only SYN) was ACK'd,
2109 * skip rest of ACK processing.
2114 /* Stop looking for an acceptable ACK since one was received. */
2115 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT | TF_EARLYREXMT);
2117 if (acked > so->so_snd.ssb_cc) {
2118 tp->snd_wnd -= so->so_snd.ssb_cc;
2119 sbdrop(&so->so_snd.sb, (int)so->so_snd.ssb_cc);
2120 ourfinisacked = TRUE;
2122 sbdrop(&so->so_snd.sb, acked);
2123 tp->snd_wnd -= acked;
2124 ourfinisacked = FALSE;
2129 * Update window information.
2131 if (acceptable_window_update(tp, th, tiwin)) {
2132 /* keep track of pure window updates */
2133 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2134 tiwin > tp->snd_wnd)
2135 tcpstat.tcps_rcvwinupd++;
2136 tp->snd_wnd = tiwin;
2137 tp->snd_wl1 = th->th_seq;
2138 tp->snd_wl2 = th->th_ack;
2139 if (tp->snd_wnd > tp->max_sndwnd)
2140 tp->max_sndwnd = tp->snd_wnd;
2144 tp->snd_una = th->th_ack;
2145 if (TCP_DO_SACK(tp))
2146 tcp_sack_update_scoreboard(tp, &to);
2147 if (IN_FASTRECOVERY(tp)) {
2148 if (SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2149 EXIT_FASTRECOVERY(tp);
2152 * If the congestion window was inflated
2153 * to account for the other side's
2154 * cached packets, retract it.
2156 if (!TCP_DO_SACK(tp))
2157 tp->snd_cwnd = tp->snd_ssthresh;
2160 * Window inflation should have left us
2161 * with approximately snd_ssthresh outstanding
2162 * data. But, in case we would be inclined
2163 * to send a burst, better do it using
2166 if (SEQ_GT(th->th_ack + tp->snd_cwnd,
2167 tp->snd_max + 2 * tp->t_maxseg))
2169 (tp->snd_max - tp->snd_una) +
2174 if (TCP_DO_SACK(tp)) {
2175 tp->snd_max_rexmt = tp->snd_max;
2176 tcp_sack_rexmt(tp, th);
2178 tcp_newreno_partial_ack(tp, th, acked);
2184 * Open the congestion window. When in slow-start,
2185 * open exponentially: maxseg per packet. Otherwise,
2186 * open linearly: maxseg per window.
2188 if (tp->snd_cwnd <= tp->snd_ssthresh) {
2190 (SEQ_LT(tp->snd_nxt, tp->snd_max) ?
2191 tp->t_maxseg : 2 * tp->t_maxseg);
2194 tp->snd_cwnd += tcp_do_abc ?
2195 min(acked, abc_sslimit) : tp->t_maxseg;
2197 /* linear increase */
2198 tp->snd_wacked += tcp_do_abc ? acked :
2200 if (tp->snd_wacked >= tp->snd_cwnd) {
2201 tp->snd_wacked -= tp->snd_cwnd;
2202 tp->snd_cwnd += tp->t_maxseg;
2205 tp->snd_cwnd = min(tp->snd_cwnd,
2206 TCP_MAXWIN << tp->snd_scale);
2207 tp->snd_recover = th->th_ack - 1;
2209 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2210 tp->snd_nxt = tp->snd_una;
2213 * If all outstanding data is acked, stop retransmit
2214 * timer and remember to restart (more output or persist).
2215 * If there is more data to be acked, restart retransmit
2216 * timer, using current (possibly backed-off) value.
2218 if (th->th_ack == tp->snd_max) {
2219 tcp_callout_stop(tp, tp->tt_rexmt);
2221 } else if (!tcp_callout_active(tp, tp->tt_persist)) {
2222 tcp_callout_reset(tp, tp->tt_rexmt, tp->t_rxtcur,
2226 switch (tp->t_state) {
2228 * In FIN_WAIT_1 STATE in addition to the processing
2229 * for the ESTABLISHED state if our FIN is now acknowledged
2230 * then enter FIN_WAIT_2.
2232 case TCPS_FIN_WAIT_1:
2233 if (ourfinisacked) {
2235 * If we can't receive any more
2236 * data, then closing user can proceed.
2237 * Starting the timer is contrary to the
2238 * specification, but if we don't get a FIN
2239 * we'll hang forever.
2241 if (so->so_state & SS_CANTRCVMORE) {
2242 soisdisconnected(so);
2243 tcp_callout_reset(tp, tp->tt_2msl,
2244 tp->t_maxidle, tcp_timer_2msl);
2246 tp->t_state = TCPS_FIN_WAIT_2;
2251 * In CLOSING STATE in addition to the processing for
2252 * the ESTABLISHED state if the ACK acknowledges our FIN
2253 * then enter the TIME-WAIT state, otherwise ignore
2257 if (ourfinisacked) {
2258 tp->t_state = TCPS_TIME_WAIT;
2259 tcp_canceltimers(tp);
2260 tcp_callout_reset(tp, tp->tt_2msl,
2261 2 * tcp_rmx_msl(tp),
2263 soisdisconnected(so);
2268 * In LAST_ACK, we may still be waiting for data to drain
2269 * and/or to be acked, as well as for the ack of our FIN.
2270 * If our FIN is now acknowledged, delete the TCB,
2271 * enter the closed state and return.
2274 if (ourfinisacked) {
2281 * In TIME_WAIT state the only thing that should arrive
2282 * is a retransmission of the remote FIN. Acknowledge
2283 * it and restart the finack timer.
2285 case TCPS_TIME_WAIT:
2286 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2294 * Update window information.
2295 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2297 if ((thflags & TH_ACK) &&
2298 acceptable_window_update(tp, th, tiwin)) {
2299 /* keep track of pure window updates */
2300 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2301 tiwin > tp->snd_wnd)
2302 tcpstat.tcps_rcvwinupd++;
2303 tp->snd_wnd = tiwin;
2304 tp->snd_wl1 = th->th_seq;
2305 tp->snd_wl2 = th->th_ack;
2306 if (tp->snd_wnd > tp->max_sndwnd)
2307 tp->max_sndwnd = tp->snd_wnd;
2312 * Process segments with URG.
2314 if ((thflags & TH_URG) && th->th_urp &&
2315 !TCPS_HAVERCVDFIN(tp->t_state)) {
2317 * This is a kludge, but if we receive and accept
2318 * random urgent pointers, we'll crash in
2319 * soreceive. It's hard to imagine someone
2320 * actually wanting to send this much urgent data.
2322 if (th->th_urp + so->so_rcv.ssb_cc > sb_max) {
2323 th->th_urp = 0; /* XXX */
2324 thflags &= ~TH_URG; /* XXX */
2325 goto dodata; /* XXX */
2328 * If this segment advances the known urgent pointer,
2329 * then mark the data stream. This should not happen
2330 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2331 * a FIN has been received from the remote side.
2332 * In these states we ignore the URG.
2334 * According to RFC961 (Assigned Protocols),
2335 * the urgent pointer points to the last octet
2336 * of urgent data. We continue, however,
2337 * to consider it to indicate the first octet
2338 * of data past the urgent section as the original
2339 * spec states (in one of two places).
2341 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
2342 tp->rcv_up = th->th_seq + th->th_urp;
2343 so->so_oobmark = so->so_rcv.ssb_cc +
2344 (tp->rcv_up - tp->rcv_nxt) - 1;
2345 if (so->so_oobmark == 0)
2346 sosetstate(so, SS_RCVATMARK);
2348 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2351 * Remove out of band data so doesn't get presented to user.
2352 * This can happen independent of advancing the URG pointer,
2353 * but if two URG's are pending at once, some out-of-band
2354 * data may creep in... ick.
2356 if (th->th_urp <= (u_long)tlen &&
2357 !(so->so_options & SO_OOBINLINE)) {
2358 /* hdr drop is delayed */
2359 tcp_pulloutofband(so, th, m, drop_hdrlen);
2363 * If no out of band data is expected,
2364 * pull receive urgent pointer along
2365 * with the receive window.
2367 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2368 tp->rcv_up = tp->rcv_nxt;
2373 * Process the segment text, merging it into the TCP sequencing queue,
2374 * and arranging for acknowledgment of receipt if necessary.
2375 * This process logically involves adjusting tp->rcv_wnd as data
2376 * is presented to the user (this happens in tcp_usrreq.c,
2377 * case PRU_RCVD). If a FIN has already been received on this
2378 * connection then we just ignore the text.
2380 if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
2381 m_adj(m, drop_hdrlen); /* delayed header drop */
2383 * Insert segment which includes th into TCP reassembly queue
2384 * with control block tp. Set thflags to whether reassembly now
2385 * includes a segment with FIN. This handles the common case
2386 * inline (segment is the next to be received on an established
2387 * connection, and the queue is empty), avoiding linkage into
2388 * and removal from the queue and repetition of various
2390 * Set DELACK for segments received in order, but ack
2391 * immediately when segments are out of order (so
2392 * fast retransmit can work).
2394 if (th->th_seq == tp->rcv_nxt &&
2395 LIST_EMPTY(&tp->t_segq) &&
2396 TCPS_HAVEESTABLISHED(tp->t_state)) {
2397 if (DELAY_ACK(tp)) {
2398 tcp_callout_reset(tp, tp->tt_delack,
2399 tcp_delacktime, tcp_timer_delack);
2401 tp->t_flags |= TF_ACKNOW;
2403 tp->rcv_nxt += tlen;
2404 thflags = th->th_flags & TH_FIN;
2405 tcpstat.tcps_rcvpack++;
2406 tcpstat.tcps_rcvbyte += tlen;
2408 if (so->so_state & SS_CANTRCVMORE) {
2411 lwkt_gettoken(&so->so_rcv.ssb_token);
2412 ssb_appendstream(&so->so_rcv, m);
2413 lwkt_reltoken(&so->so_rcv.ssb_token);
2417 if (!(tp->t_flags & TF_DUPSEG)) {
2418 /* Initialize SACK report block. */
2419 tp->reportblk.rblk_start = th->th_seq;
2420 tp->reportblk.rblk_end = TCP_SACK_BLKEND(
2421 th->th_seq + tlen, thflags);
2423 thflags = tcp_reass(tp, th, &tlen, m);
2424 tp->t_flags |= TF_ACKNOW;
2428 * Note the amount of data that peer has sent into
2429 * our window, in order to estimate the sender's
2432 len = so->so_rcv.ssb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2439 * If FIN is received ACK the FIN and let the user know
2440 * that the connection is closing.
2442 if (thflags & TH_FIN) {
2443 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
2446 * If connection is half-synchronized
2447 * (ie NEEDSYN flag on) then delay ACK,
2448 * so it may be piggybacked when SYN is sent.
2449 * Otherwise, since we received a FIN then no
2450 * more input can be expected, send ACK now.
2452 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN)) {
2453 tcp_callout_reset(tp, tp->tt_delack,
2454 tcp_delacktime, tcp_timer_delack);
2456 tp->t_flags |= TF_ACKNOW;
2461 switch (tp->t_state) {
2463 * In SYN_RECEIVED and ESTABLISHED STATES
2464 * enter the CLOSE_WAIT state.
2466 case TCPS_SYN_RECEIVED:
2467 tp->t_starttime = ticks;
2469 case TCPS_ESTABLISHED:
2470 tp->t_state = TCPS_CLOSE_WAIT;
2474 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2475 * enter the CLOSING state.
2477 case TCPS_FIN_WAIT_1:
2478 tp->t_state = TCPS_CLOSING;
2482 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2483 * starting the time-wait timer, turning off the other
2486 case TCPS_FIN_WAIT_2:
2487 tp->t_state = TCPS_TIME_WAIT;
2488 tcp_canceltimers(tp);
2489 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2491 soisdisconnected(so);
2495 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2497 case TCPS_TIME_WAIT:
2498 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2505 if (so->so_options & SO_DEBUG)
2506 tcp_trace(TA_INPUT, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2510 * Return any desired output.
2512 if (needoutput || (tp->t_flags & TF_ACKNOW))
2514 tcp_sack_report_cleanup(tp);
2515 return(IPPROTO_DONE);
2519 * Generate an ACK dropping incoming segment if it occupies
2520 * sequence space, where the ACK reflects our state.
2522 * We can now skip the test for the RST flag since all
2523 * paths to this code happen after packets containing
2524 * RST have been dropped.
2526 * In the SYN-RECEIVED state, don't send an ACK unless the
2527 * segment we received passes the SYN-RECEIVED ACK test.
2528 * If it fails send a RST. This breaks the loop in the
2529 * "LAND" DoS attack, and also prevents an ACK storm
2530 * between two listening ports that have been sent forged
2531 * SYN segments, each with the source address of the other.
2533 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2534 (SEQ_GT(tp->snd_una, th->th_ack) ||
2535 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2536 rstreason = BANDLIM_RST_OPENPORT;
2540 if (so->so_options & SO_DEBUG)
2541 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2544 tp->t_flags |= TF_ACKNOW;
2546 tcp_sack_report_cleanup(tp);
2547 return(IPPROTO_DONE);
2551 * Generate a RST, dropping incoming segment.
2552 * Make ACK acceptable to originator of segment.
2553 * Don't bother to respond if destination was broadcast/multicast.
2555 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
2558 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2559 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2562 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2563 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2564 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2565 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2568 /* IPv6 anycast check is done at tcp6_input() */
2571 * Perform bandwidth limiting.
2574 if (badport_bandlim(rstreason) < 0)
2579 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2580 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2582 if (thflags & TH_ACK)
2583 /* mtod() below is safe as long as hdr dropping is delayed */
2584 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2587 if (thflags & TH_SYN)
2589 /* mtod() below is safe as long as hdr dropping is delayed */
2590 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2591 (tcp_seq)0, TH_RST | TH_ACK);
2594 tcp_sack_report_cleanup(tp);
2595 return(IPPROTO_DONE);
2599 * Drop space held by incoming segment and return.
2602 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2603 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2607 tcp_sack_report_cleanup(tp);
2608 return(IPPROTO_DONE);
2612 * Parse TCP options and place in tcpopt.
2615 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn)
2620 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2622 if (opt == TCPOPT_EOL)
2624 if (opt == TCPOPT_NOP)
2630 if (optlen < 2 || optlen > cnt)
2635 if (optlen != TCPOLEN_MAXSEG)
2639 to->to_flags |= TOF_MSS;
2640 bcopy(cp + 2, &to->to_mss, sizeof to->to_mss);
2641 to->to_mss = ntohs(to->to_mss);
2644 if (optlen != TCPOLEN_WINDOW)
2648 to->to_flags |= TOF_SCALE;
2649 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2651 case TCPOPT_TIMESTAMP:
2652 if (optlen != TCPOLEN_TIMESTAMP)
2654 to->to_flags |= TOF_TS;
2655 bcopy(cp + 2, &to->to_tsval, sizeof to->to_tsval);
2656 to->to_tsval = ntohl(to->to_tsval);
2657 bcopy(cp + 6, &to->to_tsecr, sizeof to->to_tsecr);
2658 to->to_tsecr = ntohl(to->to_tsecr);
2660 * If echoed timestamp is later than the current time,
2661 * fall back to non RFC1323 RTT calculation.
2663 if (to->to_tsecr != 0 && TSTMP_GT(to->to_tsecr, ticks))
2666 case TCPOPT_SACK_PERMITTED:
2667 if (optlen != TCPOLEN_SACK_PERMITTED)
2671 to->to_flags |= TOF_SACK_PERMITTED;
2674 if ((optlen - 2) & 0x07) /* not multiple of 8 */
2676 to->to_nsackblocks = (optlen - 2) / 8;
2677 to->to_sackblocks = (struct raw_sackblock *) (cp + 2);
2678 to->to_flags |= TOF_SACK;
2679 for (i = 0; i < to->to_nsackblocks; i++) {
2680 struct raw_sackblock *r = &to->to_sackblocks[i];
2682 r->rblk_start = ntohl(r->rblk_start);
2683 r->rblk_end = ntohl(r->rblk_end);
2685 if (SEQ_LEQ(r->rblk_end, r->rblk_start)) {
2687 * Invalid SACK block; discard all
2690 tcpstat.tcps_rcvbadsackopt++;
2691 to->to_nsackblocks = 0;
2692 to->to_sackblocks = NULL;
2693 to->to_flags &= ~TOF_SACK;
2698 #ifdef TCP_SIGNATURE
2700 * XXX In order to reply to a host which has set the
2701 * TCP_SIGNATURE option in its initial SYN, we have to
2702 * record the fact that the option was observed here
2703 * for the syncache code to perform the correct response.
2705 case TCPOPT_SIGNATURE:
2706 if (optlen != TCPOLEN_SIGNATURE)
2708 to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2710 #endif /* TCP_SIGNATURE */
2718 * Pull out of band byte out of a segment so
2719 * it doesn't appear in the user's data queue.
2720 * It is still reflected in the segment length for
2721 * sequencing purposes.
2722 * "off" is the delayed to be dropped hdrlen.
2725 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
2727 int cnt = off + th->th_urp - 1;
2730 if (m->m_len > cnt) {
2731 char *cp = mtod(m, caddr_t) + cnt;
2732 struct tcpcb *tp = sototcpcb(so);
2735 tp->t_oobflags |= TCPOOB_HAVEDATA;
2736 bcopy(cp + 1, cp, m->m_len - cnt - 1);
2738 if (m->m_flags & M_PKTHDR)
2747 panic("tcp_pulloutofband");
2751 * Collect new round-trip time estimate
2752 * and update averages and current timeout.
2755 tcp_xmit_timer(struct tcpcb *tp, int rtt, tcp_seq ack)
2759 tcpstat.tcps_rttupdated++;
2761 if ((tp->t_flags & TF_REBASERTO) && SEQ_GT(ack, tp->snd_max_prev)) {
2762 #ifdef DEBUG_EIFEL_RESPONSE
2763 kprintf("srtt/rttvar, prev %d/%d, cur %d/%d, ",
2764 tp->t_srtt_prev, tp->t_rttvar_prev,
2765 tp->t_srtt, tp->t_rttvar);
2768 tcpstat.tcps_eifelresponse++;
2770 tp->t_flags &= ~TF_REBASERTO;
2771 tp->t_srtt = max(tp->t_srtt_prev, (rtt << TCP_RTT_SHIFT));
2772 tp->t_rttvar = max(tp->t_rttvar_prev,
2773 (rtt << (TCP_RTTVAR_SHIFT - 1)));
2774 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2775 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2777 #ifdef DEBUG_EIFEL_RESPONSE
2778 kprintf("new %d/%d ", tp->t_srtt, tp->t_rttvar);
2780 } else if (tp->t_srtt != 0) {
2784 * srtt is stored as fixed point with 5 bits after the
2785 * binary point (i.e., scaled by 8). The following magic
2786 * is equivalent to the smoothing algorithm in rfc793 with
2787 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2788 * point). Adjust rtt to origin 0.
2790 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2791 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2793 if ((tp->t_srtt += delta) <= 0)
2797 * We accumulate a smoothed rtt variance (actually, a
2798 * smoothed mean difference), then set the retransmit
2799 * timer to smoothed rtt + 4 times the smoothed variance.
2800 * rttvar is stored as fixed point with 4 bits after the
2801 * binary point (scaled by 16). The following is
2802 * equivalent to rfc793 smoothing with an alpha of .75
2803 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2804 * rfc793's wired-in beta.
2808 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2809 if ((tp->t_rttvar += delta) <= 0)
2811 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2812 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2815 * No rtt measurement yet - use the unsmoothed rtt.
2816 * Set the variance to half the rtt (so our first
2817 * retransmit happens at 3*rtt).
2819 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2820 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2821 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2826 #ifdef DEBUG_EIFEL_RESPONSE
2828 kprintf("| rxtcur prev %d, old %d, ",
2829 tp->t_rxtcur_prev, tp->t_rxtcur);
2834 * the retransmit should happen at rtt + 4 * rttvar.
2835 * Because of the way we do the smoothing, srtt and rttvar
2836 * will each average +1/2 tick of bias. When we compute
2837 * the retransmit timer, we want 1/2 tick of rounding and
2838 * 1 extra tick because of +-1/2 tick uncertainty in the
2839 * firing of the timer. The bias will give us exactly the
2840 * 1.5 tick we need. But, because the bias is
2841 * statistical, we have to test that we don't drop below
2842 * the minimum feasible timer (which is 2 ticks).
2844 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2845 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2848 if (tp->t_rxtcur < tp->t_rxtcur_prev + tcp_eifel_rtoinc) {
2850 * RFC4015 requires that the new RTO is at least
2851 * 2*G (tcp_eifel_rtoinc) greater then the RTO
2852 * (t_rxtcur_prev) when the spurious retransmit
2855 * The above condition could be true, if the SRTT
2856 * and RTTVAR used to calculate t_rxtcur_prev
2857 * resulted in a value less than t_rttmin. So
2858 * simply increasing SRTT by tcp_eifel_rtoinc when
2859 * preparing for the Eifel response in
2860 * tcp_save_congestion_state() could not ensure
2861 * that the new RTO will be tcp_eifel_rtoinc greater
2864 tp->t_rxtcur = tp->t_rxtcur_prev + tcp_eifel_rtoinc;
2866 #ifdef DEBUG_EIFEL_RESPONSE
2867 kprintf("new %d\n", tp->t_rxtcur);
2872 * We received an ack for a packet that wasn't retransmitted;
2873 * it is probably safe to discard any error indications we've
2874 * received recently. This isn't quite right, but close enough
2875 * for now (a route might have failed after we sent a segment,
2876 * and the return path might not be symmetrical).
2878 tp->t_softerror = 0;
2882 * Determine a reasonable value for maxseg size.
2883 * If the route is known, check route for mtu.
2884 * If none, use an mss that can be handled on the outgoing
2885 * interface without forcing IP to fragment; if bigger than
2886 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2887 * to utilize large mbufs. If no route is found, route has no mtu,
2888 * or the destination isn't local, use a default, hopefully conservative
2889 * size (usually 512 or the default IP max size, but no more than the mtu
2890 * of the interface), as we can't discover anything about intervening
2891 * gateways or networks. We also initialize the congestion/slow start
2892 * window to be a single segment if the destination isn't local.
2893 * While looking at the routing entry, we also initialize other path-dependent
2894 * parameters from pre-set or cached values in the routing entry.
2896 * Also take into account the space needed for options that we
2897 * send regularly. Make maxseg shorter by that amount to assure
2898 * that we can send maxseg amount of data even when the options
2899 * are present. Store the upper limit of the length of options plus
2902 * NOTE that this routine is only called when we process an incoming
2903 * segment, for outgoing segments only tcp_mssopt is called.
2906 tcp_mss(struct tcpcb *tp, int offer)
2912 struct inpcb *inp = tp->t_inpcb;
2915 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2916 size_t min_protoh = isipv6 ?
2917 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2918 sizeof(struct tcpiphdr);
2920 const boolean_t isipv6 = FALSE;
2921 const size_t min_protoh = sizeof(struct tcpiphdr);
2925 rt = tcp_rtlookup6(&inp->inp_inc);
2927 rt = tcp_rtlookup(&inp->inp_inc);
2929 tp->t_maxopd = tp->t_maxseg =
2930 (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2934 so = inp->inp_socket;
2937 * Offer == 0 means that there was no MSS on the SYN segment,
2938 * in this case we use either the interface mtu or tcp_mssdflt.
2940 * An offer which is too large will be cut down later.
2944 if (in6_localaddr(&inp->in6p_faddr)) {
2945 offer = ND_IFINFO(rt->rt_ifp)->linkmtu -
2948 offer = tcp_v6mssdflt;
2951 if (in_localaddr(inp->inp_faddr))
2952 offer = ifp->if_mtu - min_protoh;
2954 offer = tcp_mssdflt;
2959 * Prevent DoS attack with too small MSS. Round up
2960 * to at least minmss.
2962 * Sanity check: make sure that maxopd will be large
2963 * enough to allow some data on segments even is the
2964 * all the option space is used (40bytes). Otherwise
2965 * funny things may happen in tcp_output.
2967 offer = max(offer, tcp_minmss);
2968 offer = max(offer, 64);
2970 rt->rt_rmx.rmx_mssopt = offer;
2973 * While we're here, check if there's an initial rtt
2974 * or rttvar. Convert from the route-table units
2975 * to scaled multiples of the slow timeout timer.
2977 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2979 * XXX the lock bit for RTT indicates that the value
2980 * is also a minimum value; this is subject to time.
2982 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2983 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2984 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2985 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2986 tcpstat.tcps_usedrtt++;
2987 if (rt->rt_rmx.rmx_rttvar) {
2988 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2989 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2990 tcpstat.tcps_usedrttvar++;
2992 /* default variation is +- 1 rtt */
2994 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2996 TCPT_RANGESET(tp->t_rxtcur,
2997 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2998 tp->t_rttmin, TCPTV_REXMTMAX);
3002 * if there's an mtu associated with the route, use it
3003 * else, use the link mtu. Take the smaller of mss or offer
3006 if (rt->rt_rmx.rmx_mtu) {
3007 mss = rt->rt_rmx.rmx_mtu - min_protoh;
3010 mss = ND_IFINFO(rt->rt_ifp)->linkmtu - min_protoh;
3012 mss = ifp->if_mtu - min_protoh;
3014 mss = min(mss, offer);
3017 * maxopd stores the maximum length of data AND options
3018 * in a segment; maxseg is the amount of data in a normal
3019 * segment. We need to store this value (maxopd) apart
3020 * from maxseg, because now every segment carries options
3021 * and thus we normally have somewhat less data in segments.
3025 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
3026 ((tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3027 mss -= TCPOLEN_TSTAMP_APPA;
3029 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3031 mss &= ~(MCLBYTES-1);
3034 mss = mss / MCLBYTES * MCLBYTES;
3037 * If there's a pipesize, change the socket buffer
3038 * to that size. Make the socket buffers an integral
3039 * number of mss units; if the mss is larger than
3040 * the socket buffer, decrease the mss.
3043 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
3045 bufsize = so->so_snd.ssb_hiwat;
3049 bufsize = roundup(bufsize, mss);
3050 if (bufsize > sb_max)
3052 if (bufsize > so->so_snd.ssb_hiwat)
3053 ssb_reserve(&so->so_snd, bufsize, so, NULL);
3058 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
3060 bufsize = so->so_rcv.ssb_hiwat;
3061 if (bufsize > mss) {
3062 bufsize = roundup(bufsize, mss);
3063 if (bufsize > sb_max)
3065 if (bufsize > so->so_rcv.ssb_hiwat) {
3066 lwkt_gettoken(&so->so_rcv.ssb_token);
3067 ssb_reserve(&so->so_rcv, bufsize, so, NULL);
3068 lwkt_reltoken(&so->so_rcv.ssb_token);
3073 * Set the slow-start flight size
3075 * NOTE: t_maxseg must have been configured!
3077 tp->snd_cwnd = tcp_initial_window(tp);
3079 if (rt->rt_rmx.rmx_ssthresh) {
3081 * There's some sort of gateway or interface
3082 * buffer limit on the path. Use this to set
3083 * the slow start threshhold, but set the
3084 * threshold to no less than 2*mss.
3086 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3087 tcpstat.tcps_usedssthresh++;
3092 * Determine the MSS option to send on an outgoing SYN.
3095 tcp_mssopt(struct tcpcb *tp)
3100 ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3101 int min_protoh = isipv6 ?
3102 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
3103 sizeof(struct tcpiphdr);
3105 const boolean_t isipv6 = FALSE;
3106 const size_t min_protoh = sizeof(struct tcpiphdr);
3110 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
3112 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
3114 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3116 return (rt->rt_ifp->if_mtu - min_protoh);
3120 * When a partial ack arrives, force the retransmission of the
3121 * next unacknowledged segment. Do not exit Fast Recovery.
3123 * Implement the Slow-but-Steady variant of NewReno by restarting the
3124 * the retransmission timer. Turn it off here so it can be restarted
3125 * later in tcp_output().
3128 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th, int acked)
3130 tcp_seq old_snd_nxt = tp->snd_nxt;
3131 u_long ocwnd = tp->snd_cwnd;
3133 tcp_callout_stop(tp, tp->tt_rexmt);
3135 tp->snd_nxt = th->th_ack;
3136 /* Set snd_cwnd to one segment beyond acknowledged offset. */
3137 tp->snd_cwnd = tp->t_maxseg;
3138 tp->t_flags |= TF_ACKNOW;
3140 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3141 tp->snd_nxt = old_snd_nxt;
3142 /* partial window deflation */
3144 tp->snd_cwnd = ocwnd - acked + tp->t_maxseg;
3146 tp->snd_cwnd = tp->t_maxseg;
3150 * In contrast to the Slow-but-Steady NewReno variant,
3151 * we do not reset the retransmission timer for SACK retransmissions,
3152 * except when retransmitting snd_una.
3155 tcp_sack_rexmt(struct tcpcb *tp, struct tcphdr *th)
3157 tcp_seq old_snd_nxt = tp->snd_nxt;
3158 u_long ocwnd = tp->snd_cwnd;
3160 int nseg = 0; /* consecutive new segments */
3161 int nseg_rexmt = 0; /* retransmitted segments */
3162 #define MAXBURST 4 /* limit burst of new packets on partial ack */
3165 pipe = tcp_sack_compute_pipe(tp);
3166 while ((tcp_seq_diff_t)(ocwnd - pipe) >= (tcp_seq_diff_t)tp->t_maxseg &&
3167 (!tcp_do_smartsack || nseg < MAXBURST)) {
3168 tcp_seq old_snd_max, old_rexmt_high, nextrexmt;
3169 uint32_t sent, seglen;
3173 old_rexmt_high = tp->rexmt_high;
3174 if (!tcp_sack_nextseg(tp, &nextrexmt, &seglen, &rescue)) {
3175 tp->rexmt_high = old_rexmt_high;
3180 * If the next tranmission is a rescue retranmission,
3181 * we check whether we have already sent some data
3182 * (either new segments or retransmitted segments)
3183 * into the the network or not. Since the idea of rescue
3184 * retransmission is to sustain ACK clock, as long as
3185 * some segments are in the network, ACK clock will be
3188 if (rescue && (nseg_rexmt > 0 || nseg > 0)) {
3189 tp->rexmt_high = old_rexmt_high;
3193 if (nextrexmt == tp->snd_max)
3197 tp->snd_nxt = nextrexmt;
3198 tp->snd_cwnd = nextrexmt - tp->snd_una + seglen;
3199 old_snd_max = tp->snd_max;
3200 if (nextrexmt == tp->snd_una)
3201 tcp_callout_stop(tp, tp->tt_rexmt);
3202 error = tcp_output(tp);
3204 tp->rexmt_high = old_rexmt_high;
3207 sent = tp->snd_nxt - nextrexmt;
3209 tp->rexmt_high = old_rexmt_high;
3213 tcpstat.tcps_sndsackpack++;
3214 tcpstat.tcps_sndsackbyte += sent;
3217 tcpstat.tcps_sackrescue++;
3218 tp->rexmt_rescue = tp->snd_nxt;
3219 tp->t_flags |= TF_SACKRESCUED;
3222 if (SEQ_LT(nextrexmt, old_snd_max) &&
3223 SEQ_LT(tp->rexmt_high, tp->snd_nxt)) {
3224 tp->rexmt_high = seq_min(tp->snd_nxt, old_snd_max);
3225 if ((tp->t_flags & TF_SACKRESCUED) &&
3226 SEQ_LT(tp->rexmt_rescue, tp->rexmt_high)) {
3227 /* Drag RescueRxt along with HighRxt */
3228 tp->rexmt_rescue = tp->rexmt_high;
3232 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3233 tp->snd_nxt = old_snd_nxt;
3234 tp->snd_cwnd = ocwnd;
3238 * Reset idle time and keep-alive timer, typically called when a valid
3239 * tcp packet is received but may also be called when FASTKEEP is set
3240 * to prevent the previous long-timeout from calculating to a drop.
3242 * Only update t_rcvtime for non-SYN packets.
3244 * Handle the case where one side thinks the connection is established
3245 * but the other side has, say, rebooted without cleaning out the
3246 * connection. The SYNs could be construed as an attack and wind
3247 * up ignored, but in case it isn't an attack we can validate the
3248 * connection by forcing a keepalive.
3251 tcp_timer_keep_activity(struct tcpcb *tp, int thflags)
3253 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3254 if ((thflags & (TH_SYN | TH_ACK)) == TH_SYN) {
3255 tp->t_flags |= TF_KEEPALIVE;
3256 tcp_callout_reset(tp, tp->tt_keep, hz / 2,
3259 tp->t_rcvtime = ticks;
3260 tp->t_flags &= ~TF_KEEPALIVE;
3261 tcp_callout_reset(tp, tp->tt_keep,
3269 tcp_rmx_msl(const struct tcpcb *tp)
3272 struct inpcb *inp = tp->t_inpcb;
3275 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3277 const boolean_t isipv6 = FALSE;
3281 rt = tcp_rtlookup6(&inp->inp_inc);
3283 rt = tcp_rtlookup(&inp->inp_inc);
3284 if (rt == NULL || rt->rt_rmx.rmx_msl == 0)
3287 msl = (rt->rt_rmx.rmx_msl * hz) / 1000;
3295 tcp_established(struct tcpcb *tp)
3297 tp->t_state = TCPS_ESTABLISHED;
3298 tcp_callout_reset(tp, tp->tt_keep, tp->t_keepidle, tcp_timer_keep);
3300 if (tp->t_rxtsyn > 0) {
3303 * "If the timer expires awaiting the ACK of a SYN segment
3304 * and the TCP implementation is using an RTO less than 3
3305 * seconds, the RTO MUST be re-initialized to 3 seconds
3306 * when data transmission begins"
3308 if (tp->t_rxtcur < TCPTV_RTOBASE3)
3309 tp->t_rxtcur = TCPTV_RTOBASE3;