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 $
68 * $DragonFly: src/sys/netinet/tcp_input.c,v 1.68 2008/08/22 09:14:17 sephe Exp $
71 #include "opt_ipfw.h" /* for ipfw_fwd */
73 #include "opt_inet6.h"
74 #include "opt_ipsec.h"
75 #include "opt_tcpdebug.h"
76 #include "opt_tcp_input.h"
78 #include <sys/param.h>
79 #include <sys/systm.h>
80 #include <sys/kernel.h>
81 #include <sys/sysctl.h>
82 #include <sys/malloc.h>
84 #include <sys/proc.h> /* for proc0 declaration */
85 #include <sys/protosw.h>
86 #include <sys/socket.h>
87 #include <sys/socketvar.h>
88 #include <sys/syslog.h>
89 #include <sys/in_cksum.h>
91 #include <sys/socketvar2.h>
93 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
94 #include <machine/stdarg.h>
97 #include <net/route.h>
99 #include <netinet/in.h>
100 #include <netinet/in_systm.h>
101 #include <netinet/ip.h>
102 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
103 #include <netinet/in_var.h>
104 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
105 #include <netinet/in_pcb.h>
106 #include <netinet/ip_var.h>
107 #include <netinet/ip6.h>
108 #include <netinet/icmp6.h>
109 #include <netinet6/nd6.h>
110 #include <netinet6/ip6_var.h>
111 #include <netinet6/in6_pcb.h>
112 #include <netinet/tcp.h>
113 #include <netinet/tcp_fsm.h>
114 #include <netinet/tcp_seq.h>
115 #include <netinet/tcp_timer.h>
116 #include <netinet/tcp_timer2.h>
117 #include <netinet/tcp_var.h>
118 #include <netinet6/tcp6_var.h>
119 #include <netinet/tcpip.h>
122 #include <netinet/tcp_debug.h>
124 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
125 struct tcphdr tcp_savetcp;
129 #include <netproto/ipsec/ipsec.h>
130 #include <netproto/ipsec/ipsec6.h>
134 #include <netinet6/ipsec.h>
135 #include <netinet6/ipsec6.h>
136 #include <netproto/key/key.h>
139 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
141 static int log_in_vain = 0;
142 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
143 &log_in_vain, 0, "Log all incoming TCP connections");
145 static int blackhole = 0;
146 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
147 &blackhole, 0, "Do not send RST when dropping refused connections");
149 int tcp_delack_enabled = 1;
150 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
151 &tcp_delack_enabled, 0,
152 "Delay ACK to try and piggyback it onto a data packet");
154 #ifdef TCP_DROP_SYNFIN
155 static int drop_synfin = 0;
156 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
157 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
160 static int tcp_do_limitedtransmit = 1;
161 SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
162 &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
164 static int tcp_do_early_retransmit = 1;
165 SYSCTL_INT(_net_inet_tcp, OID_AUTO, earlyretransmit, CTLFLAG_RW,
166 &tcp_do_early_retransmit, 0, "Early retransmit");
168 int tcp_aggregate_acks = 1;
169 SYSCTL_INT(_net_inet_tcp, OID_AUTO, aggregate_acks, CTLFLAG_RW,
170 &tcp_aggregate_acks, 0, "Aggregate built-up acks into one ack");
172 int tcp_do_rfc3390 = 1;
173 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
175 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
177 static int tcp_do_eifel_detect = 1;
178 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
179 &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
181 static int tcp_do_abc = 1;
182 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc, CTLFLAG_RW,
184 "TCP Appropriate Byte Counting (RFC 3465)");
187 * Define as tunable for easy testing with SACK on and off.
188 * Warning: do not change setting in the middle of an existing active TCP flow,
189 * else strange things might happen to that flow.
192 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sack, CTLFLAG_RW,
193 &tcp_do_sack, 0, "Enable SACK Algorithms");
195 int tcp_do_smartsack = 1;
196 SYSCTL_INT(_net_inet_tcp, OID_AUTO, smartsack, CTLFLAG_RW,
197 &tcp_do_smartsack, 0, "Enable Smart SACK Algorithms");
199 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
200 "TCP Segment Reassembly Queue");
202 int tcp_reass_maxseg = 0;
203 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
204 &tcp_reass_maxseg, 0,
205 "Global maximum number of TCP Segments in Reassembly Queue");
207 int tcp_reass_qsize = 0;
208 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
210 "Global number of TCP Segments currently in Reassembly Queue");
212 static int tcp_reass_overflows = 0;
213 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
214 &tcp_reass_overflows, 0,
215 "Global number of TCP Segment Reassembly Queue Overflows");
217 int tcp_do_autorcvbuf = 1;
218 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
219 &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
221 int tcp_autorcvbuf_inc = 16*1024;
222 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
223 &tcp_autorcvbuf_inc, 0,
224 "Incrementor step size of automatic receive buffer");
226 int tcp_autorcvbuf_max = 2*1024*1024;
227 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
228 &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
231 static void tcp_dooptions(struct tcpopt *, u_char *, int, boolean_t);
232 static void tcp_pulloutofband(struct socket *,
233 struct tcphdr *, struct mbuf *, int);
234 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
236 static void tcp_xmit_timer(struct tcpcb *, int);
237 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *, int);
238 static void tcp_sack_rexmt(struct tcpcb *, struct tcphdr *);
240 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
242 #define ND6_HINT(tp) \
244 if ((tp) && (tp)->t_inpcb && \
245 ((tp)->t_inpcb->inp_vflag & INP_IPV6) && \
246 (tp)->t_inpcb->in6p_route.ro_rt) \
247 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
254 * Indicate whether this ack should be delayed. We can delay the ack if
255 * - delayed acks are enabled and
256 * - there is no delayed ack timer in progress and
257 * - our last ack wasn't a 0-sized window. We never want to delay
258 * the ack that opens up a 0-sized window.
260 #define DELAY_ACK(tp) \
261 (tcp_delack_enabled && !tcp_callout_pending(tp, tp->tt_delack) && \
262 !(tp->t_flags & TF_RXWIN0SENT))
264 #define acceptable_window_update(tp, th, tiwin) \
265 (SEQ_LT(tp->snd_wl1, th->th_seq) || \
266 (tp->snd_wl1 == th->th_seq && \
267 (SEQ_LT(tp->snd_wl2, th->th_ack) || \
268 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))
271 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
274 struct tseg_qent *p = NULL;
275 struct tseg_qent *te;
276 struct socket *so = tp->t_inpcb->inp_socket;
280 * Call with th == NULL after become established to
281 * force pre-ESTABLISHED data up to user socket.
287 * Limit the number of segments in the reassembly queue to prevent
288 * holding on to too many segments (and thus running out of mbufs).
289 * Make sure to let the missing segment through which caused this
290 * queue. Always keep one global queue entry spare to be able to
291 * process the missing segment.
293 if (th->th_seq != tp->rcv_nxt &&
294 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
295 tcp_reass_overflows++;
296 tcpstat.tcps_rcvmemdrop++;
298 /* no SACK block to report */
299 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
303 /* Allocate a new queue entry. */
304 MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
305 M_INTWAIT | M_NULLOK);
307 tcpstat.tcps_rcvmemdrop++;
309 /* no SACK block to report */
310 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
313 atomic_add_int(&tcp_reass_qsize, 1);
316 * Find a segment which begins after this one does.
318 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
319 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
325 * If there is a preceding segment, it may provide some of
326 * our data already. If so, drop the data from the incoming
327 * segment. If it provides all of our data, drop us.
332 /* conversion to int (in i) handles seq wraparound */
333 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
334 if (i > 0) { /* overlaps preceding segment */
335 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
336 /* enclosing block starts w/ preceding segment */
337 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
339 /* preceding encloses incoming segment */
340 tp->encloseblk.rblk_end = p->tqe_th->th_seq +
342 tcpstat.tcps_rcvduppack++;
343 tcpstat.tcps_rcvdupbyte += *tlenp;
346 atomic_add_int(&tcp_reass_qsize, -1);
348 * Try to present any queued data
349 * at the left window edge to the user.
350 * This is needed after the 3-WHS
353 goto present; /* ??? */
358 /* incoming segment end is enclosing block end */
359 tp->encloseblk.rblk_end = th->th_seq + *tlenp +
360 ((th->th_flags & TH_FIN) != 0);
361 /* trim end of reported D-SACK block */
362 tp->reportblk.rblk_end = th->th_seq;
365 tcpstat.tcps_rcvoopack++;
366 tcpstat.tcps_rcvoobyte += *tlenp;
369 * While we overlap succeeding segments trim them or,
370 * if they are completely covered, dequeue them.
373 tcp_seq_diff_t i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
374 tcp_seq qend = q->tqe_th->th_seq + q->tqe_len;
375 struct tseg_qent *nq;
379 if (!(tp->t_flags & TF_DUPSEG)) { /* first time through */
380 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
381 tp->encloseblk = tp->reportblk;
382 /* report trailing duplicate D-SACK segment */
383 tp->reportblk.rblk_start = q->tqe_th->th_seq;
385 if ((tp->t_flags & TF_ENCLOSESEG) &&
386 SEQ_GT(qend, tp->encloseblk.rblk_end)) {
387 /* extend enclosing block if one exists */
388 tp->encloseblk.rblk_end = qend;
390 if (i < q->tqe_len) {
391 q->tqe_th->th_seq += i;
397 nq = LIST_NEXT(q, tqe_q);
398 LIST_REMOVE(q, tqe_q);
401 atomic_add_int(&tcp_reass_qsize, -1);
405 /* Insert the new segment queue entry into place. */
408 te->tqe_len = *tlenp;
410 /* check if can coalesce with following segment */
411 if (q != NULL && (th->th_seq + *tlenp == q->tqe_th->th_seq)) {
412 tcp_seq tend = te->tqe_th->th_seq + te->tqe_len;
414 te->tqe_len += q->tqe_len;
415 if (q->tqe_th->th_flags & TH_FIN)
416 te->tqe_th->th_flags |= TH_FIN;
417 m_cat(te->tqe_m, q->tqe_m);
418 tp->encloseblk.rblk_end = tend;
420 * When not reporting a duplicate segment, use
421 * the larger enclosing block as the SACK block.
423 if (!(tp->t_flags & TF_DUPSEG))
424 tp->reportblk.rblk_end = tend;
425 LIST_REMOVE(q, tqe_q);
427 atomic_add_int(&tcp_reass_qsize, -1);
431 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
433 /* check if can coalesce with preceding segment */
434 if (p->tqe_th->th_seq + p->tqe_len == th->th_seq) {
435 p->tqe_len += te->tqe_len;
436 m_cat(p->tqe_m, te->tqe_m);
437 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
439 * When not reporting a duplicate segment, use
440 * the larger enclosing block as the SACK block.
442 if (!(tp->t_flags & TF_DUPSEG))
443 tp->reportblk.rblk_start = p->tqe_th->th_seq;
445 atomic_add_int(&tcp_reass_qsize, -1);
447 LIST_INSERT_AFTER(p, te, tqe_q);
453 * Present data to user, advancing rcv_nxt through
454 * completed sequence space.
456 if (!TCPS_HAVEESTABLISHED(tp->t_state))
458 q = LIST_FIRST(&tp->t_segq);
459 if (q == NULL || q->tqe_th->th_seq != tp->rcv_nxt)
461 tp->rcv_nxt += q->tqe_len;
462 if (!(tp->t_flags & TF_DUPSEG)) {
463 /* no SACK block to report since ACK advanced */
464 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
466 /* no enclosing block to report since ACK advanced */
467 tp->t_flags &= ~TF_ENCLOSESEG;
468 flags = q->tqe_th->th_flags & TH_FIN;
469 LIST_REMOVE(q, tqe_q);
470 KASSERT(LIST_EMPTY(&tp->t_segq) ||
471 LIST_FIRST(&tp->t_segq)->tqe_th->th_seq != tp->rcv_nxt,
472 ("segment not coalesced"));
473 if (so->so_state & SS_CANTRCVMORE) {
476 lwkt_gettoken(&so->so_rcv.ssb_token);
477 ssb_appendstream(&so->so_rcv, q->tqe_m);
478 lwkt_reltoken(&so->so_rcv.ssb_token);
481 atomic_add_int(&tcp_reass_qsize, -1);
488 * TCP input routine, follows pages 65-76 of the
489 * protocol specification dated September, 1981 very closely.
493 tcp6_input(struct mbuf **mp, int *offp, int proto)
495 struct mbuf *m = *mp;
496 struct in6_ifaddr *ia6;
498 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
501 * draft-itojun-ipv6-tcp-to-anycast
502 * better place to put this in?
504 ia6 = ip6_getdstifaddr(m);
505 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
508 ip6 = mtod(m, struct ip6_hdr *);
509 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
510 offsetof(struct ip6_hdr, ip6_dst));
511 return (IPPROTO_DONE);
514 tcp_input(mp, offp, proto);
515 return (IPPROTO_DONE);
520 tcp_input(struct mbuf **mp, int *offp, int proto)
524 struct ip *ip = NULL;
526 struct inpcb *inp = NULL;
532 struct tcpcb *tp = NULL;
534 struct socket *so = 0;
536 boolean_t ourfinisacked, needoutput = FALSE;
539 struct tcpopt to; /* options in this segment */
540 struct sockaddr_in *next_hop = NULL;
541 int rstreason; /* For badport_bandlim accounting purposes */
543 struct ip6_hdr *ip6 = NULL;
548 const boolean_t isipv6 = FALSE;
558 tcpstat.tcps_rcvtotal++;
560 if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
563 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
564 KKASSERT(mtag != NULL);
565 next_hop = m_tag_data(mtag);
569 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
573 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
574 ip6 = mtod(m, struct ip6_hdr *);
575 tlen = (sizeof *ip6) + ntohs(ip6->ip6_plen) - off0;
576 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
577 tcpstat.tcps_rcvbadsum++;
580 th = (struct tcphdr *)((caddr_t)ip6 + off0);
583 * Be proactive about unspecified IPv6 address in source.
584 * As we use all-zero to indicate unbounded/unconnected pcb,
585 * unspecified IPv6 address can be used to confuse us.
587 * Note that packets with unspecified IPv6 destination is
588 * already dropped in ip6_input.
590 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
596 * Get IP and TCP header together in first mbuf.
597 * Note: IP leaves IP header in first mbuf.
599 if (off0 > sizeof(struct ip)) {
601 off0 = sizeof(struct ip);
603 /* already checked and pulled up in ip_demux() */
604 KASSERT(m->m_len >= sizeof(struct tcpiphdr),
605 ("TCP header not in one mbuf: m->m_len %d", m->m_len));
606 ip = mtod(m, struct ip *);
607 ipov = (struct ipovly *)ip;
608 th = (struct tcphdr *)((caddr_t)ip + off0);
611 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
612 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
613 th->th_sum = m->m_pkthdr.csum_data;
615 th->th_sum = in_pseudo(ip->ip_src.s_addr,
617 htonl(m->m_pkthdr.csum_data +
620 th->th_sum ^= 0xffff;
623 * Checksum extended TCP header and data.
625 len = sizeof(struct ip) + tlen;
626 bzero(ipov->ih_x1, sizeof ipov->ih_x1);
627 ipov->ih_len = (u_short)tlen;
628 ipov->ih_len = htons(ipov->ih_len);
629 th->th_sum = in_cksum(m, len);
632 tcpstat.tcps_rcvbadsum++;
636 /* Re-initialization for later version check */
637 ip->ip_v = IPVERSION;
642 * Check that TCP offset makes sense,
643 * pull out TCP options and adjust length. XXX
645 off = th->th_off << 2;
646 /* already checked and pulled up in ip_demux() */
647 KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
648 ("bad TCP data offset %d (tlen %d)", off, tlen));
649 tlen -= off; /* tlen is used instead of ti->ti_len */
650 if (off > sizeof(struct tcphdr)) {
652 IP6_EXTHDR_CHECK(m, off0, off, IPPROTO_DONE);
653 ip6 = mtod(m, struct ip6_hdr *);
654 th = (struct tcphdr *)((caddr_t)ip6 + off0);
656 /* already pulled up in ip_demux() */
657 KASSERT(m->m_len >= sizeof(struct ip) + off,
658 ("TCP header and options not in one mbuf: "
659 "m_len %d, off %d", m->m_len, off));
661 optlen = off - sizeof(struct tcphdr);
662 optp = (u_char *)(th + 1);
664 thflags = th->th_flags;
666 #ifdef TCP_DROP_SYNFIN
668 * If the drop_synfin option is enabled, drop all packets with
669 * both the SYN and FIN bits set. This prevents e.g. nmap from
670 * identifying the TCP/IP stack.
672 * This is a violation of the TCP specification.
674 if (drop_synfin && (thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN))
679 * Convert TCP protocol specific fields to host format.
681 th->th_seq = ntohl(th->th_seq);
682 th->th_ack = ntohl(th->th_ack);
683 th->th_win = ntohs(th->th_win);
684 th->th_urp = ntohs(th->th_urp);
687 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
688 * until after ip6_savecontrol() is called and before other functions
689 * which don't want those proto headers.
690 * Because ip6_savecontrol() is going to parse the mbuf to
691 * search for data to be passed up to user-land, it wants mbuf
692 * parameters to be unchanged.
693 * XXX: the call of ip6_savecontrol() has been obsoleted based on
694 * latest version of the advanced API (20020110).
696 drop_hdrlen = off0 + off;
699 * Locate pcb for segment.
702 /* IPFIREWALL_FORWARD section */
703 if (next_hop != NULL && !isipv6) { /* IPv6 support is not there yet */
705 * Transparently forwarded. Pretend to be the destination.
706 * already got one like this?
708 cpu = mycpu->gd_cpuid;
709 inp = in_pcblookup_hash(&tcbinfo[cpu],
710 ip->ip_src, th->th_sport,
711 ip->ip_dst, th->th_dport,
712 0, m->m_pkthdr.rcvif);
715 * It's new. Try to find the ambushing socket.
719 * The rest of the ipfw code stores the port in
721 * (The IP address is still in network order.)
723 in_port_t dport = next_hop->sin_port ?
724 htons(next_hop->sin_port) :
727 cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
728 next_hop->sin_addr.s_addr, dport);
729 inp = in_pcblookup_hash(&tcbinfo[cpu],
730 ip->ip_src, th->th_sport,
731 next_hop->sin_addr, dport,
732 1, m->m_pkthdr.rcvif);
736 inp = in6_pcblookup_hash(&tcbinfo[0],
737 &ip6->ip6_src, th->th_sport,
738 &ip6->ip6_dst, th->th_dport,
739 1, m->m_pkthdr.rcvif);
741 cpu = mycpu->gd_cpuid;
742 inp = in_pcblookup_hash(&tcbinfo[cpu],
743 ip->ip_src, th->th_sport,
744 ip->ip_dst, th->th_dport,
745 1, m->m_pkthdr.rcvif);
750 * If the state is CLOSED (i.e., TCB does not exist) then
751 * all data in the incoming segment is discarded.
752 * If the TCB exists but is in CLOSED state, it is embryonic,
753 * but should either do a listen or a connect soon.
758 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
760 char dbuf[sizeof "aaa.bbb.ccc.ddd"];
761 char sbuf[sizeof "aaa.bbb.ccc.ddd"];
765 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
768 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
771 strcpy(dbuf, inet_ntoa(ip->ip_dst));
772 strcpy(sbuf, inet_ntoa(ip->ip_src));
774 switch (log_in_vain) {
776 if (!(thflags & TH_SYN))
780 "Connection attempt to TCP %s:%d "
781 "from %s:%d flags:0x%02x\n",
782 dbuf, ntohs(th->th_dport), sbuf,
783 ntohs(th->th_sport), thflags);
792 if (thflags & TH_SYN)
801 rstreason = BANDLIM_RST_CLOSEDPORT;
807 if (ipsec6_in_reject_so(m, inp->inp_socket)) {
808 ipsec6stat.in_polvio++;
812 if (ipsec4_in_reject_so(m, inp->inp_socket)) {
813 ipsecstat.in_polvio++;
820 if (ipsec6_in_reject(m, inp))
823 if (ipsec4_in_reject(m, inp))
827 /* Check the minimum TTL for socket. */
829 if ((isipv6 ? ip6->ip6_hlim : ip->ip_ttl) < inp->inp_ip_minttl)
835 rstreason = BANDLIM_RST_CLOSEDPORT;
838 if (tp->t_state <= TCPS_CLOSED)
841 /* Unscale the window into a 32-bit value. */
842 if (!(thflags & TH_SYN))
843 tiwin = th->th_win << tp->snd_scale;
847 so = inp->inp_socket;
850 if (so->so_options & SO_DEBUG) {
851 ostate = tp->t_state;
853 bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
855 bcopy(ip, tcp_saveipgen, sizeof(*ip));
860 bzero(&to, sizeof to);
862 if (so->so_options & SO_ACCEPTCONN) {
863 struct in_conninfo inc;
866 inc.inc_isipv6 = (isipv6 == TRUE);
869 inc.inc6_faddr = ip6->ip6_src;
870 inc.inc6_laddr = ip6->ip6_dst;
871 inc.inc6_route.ro_rt = NULL; /* XXX */
873 inc.inc_faddr = ip->ip_src;
874 inc.inc_laddr = ip->ip_dst;
875 inc.inc_route.ro_rt = NULL; /* XXX */
877 inc.inc_fport = th->th_sport;
878 inc.inc_lport = th->th_dport;
881 * If the state is LISTEN then ignore segment if it contains
882 * a RST. If the segment contains an ACK then it is bad and
883 * send a RST. If it does not contain a SYN then it is not
884 * interesting; drop it.
886 * If the state is SYN_RECEIVED (syncache) and seg contains
887 * an ACK, but not for our SYN/ACK, send a RST. If the seg
888 * contains a RST, check the sequence number to see if it
889 * is a valid reset segment.
891 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
892 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) == TH_ACK) {
893 if (!syncache_expand(&inc, th, &so, m)) {
895 * No syncache entry, or ACK was not
896 * for our SYN/ACK. Send a RST.
898 tcpstat.tcps_badsyn++;
899 rstreason = BANDLIM_RST_OPENPORT;
904 * Could not complete 3-way handshake,
905 * connection is being closed down, and
906 * syncache will free mbuf.
909 return(IPPROTO_DONE);
912 * We must be in the correct protocol thread
913 * for this connection.
915 KKASSERT(so->so_port == &curthread->td_msgport);
918 * Socket is created in state SYN_RECEIVED.
919 * Continue processing segment.
924 * This is what would have happened in
925 * tcp_output() when the SYN,ACK was sent.
927 tp->snd_up = tp->snd_una;
928 tp->snd_max = tp->snd_nxt = tp->iss + 1;
929 tp->last_ack_sent = tp->rcv_nxt;
931 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
932 * until the _second_ ACK is received:
933 * rcv SYN (set wscale opts) --> send SYN/ACK, set snd_wnd = window.
934 * rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
935 * move to ESTAB, set snd_wnd to tiwin.
937 tp->snd_wnd = tiwin; /* unscaled */
940 if (thflags & TH_RST) {
941 syncache_chkrst(&inc, th);
944 if (thflags & TH_ACK) {
945 syncache_badack(&inc);
946 tcpstat.tcps_badsyn++;
947 rstreason = BANDLIM_RST_OPENPORT;
954 * Segment's flags are (SYN) or (SYN | FIN).
958 * If deprecated address is forbidden,
959 * we do not accept SYN to deprecated interface
960 * address to prevent any new inbound connection from
961 * getting established.
962 * When we do not accept SYN, we send a TCP RST,
963 * with deprecated source address (instead of dropping
964 * it). We compromise it as it is much better for peer
965 * to send a RST, and RST will be the final packet
968 * If we do not forbid deprecated addresses, we accept
969 * the SYN packet. RFC2462 does not suggest dropping
971 * If we decipher RFC2462 5.5.4, it says like this:
972 * 1. use of deprecated addr with existing
973 * communication is okay - "SHOULD continue to be
975 * 2. use of it with new communication:
976 * (2a) "SHOULD NOT be used if alternate address
977 * with sufficient scope is available"
978 * (2b) nothing mentioned otherwise.
979 * Here we fall into (2b) case as we have no choice in
980 * our source address selection - we must obey the peer.
982 * The wording in RFC2462 is confusing, and there are
983 * multiple description text for deprecated address
984 * handling - worse, they are not exactly the same.
985 * I believe 5.5.4 is the best one, so we follow 5.5.4.
987 if (isipv6 && !ip6_use_deprecated) {
988 struct in6_ifaddr *ia6;
990 if ((ia6 = ip6_getdstifaddr(m)) &&
991 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
993 rstreason = BANDLIM_RST_OPENPORT;
999 * If it is from this socket, drop it, it must be forged.
1000 * Don't bother responding if the destination was a broadcast.
1002 if (th->th_dport == th->th_sport) {
1004 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
1008 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
1013 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1015 * Note that it is quite possible to receive unicast
1016 * link-layer packets with a broadcast IP address. Use
1017 * in_broadcast() to find them.
1019 if (m->m_flags & (M_BCAST | M_MCAST))
1022 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1023 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
1026 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1027 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1028 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1029 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1033 * SYN appears to be valid; create compressed TCP state
1034 * for syncache, or perform t/tcp connection.
1036 if (so->so_qlen <= so->so_qlimit) {
1037 tcp_dooptions(&to, optp, optlen, TRUE);
1038 if (!syncache_add(&inc, &to, th, &so, m))
1042 * Entry added to syncache, mbuf used to
1043 * send SYN,ACK packet.
1046 return(IPPROTO_DONE);
1049 * We must be in the correct protocol thread for
1052 KKASSERT(so->so_port == &curthread->td_msgport);
1055 tp = intotcpcb(inp);
1056 tp->snd_wnd = tiwin;
1057 tp->t_starttime = ticks;
1058 tp->t_state = TCPS_ESTABLISHED;
1061 * If there is a FIN, or if there is data and the
1062 * connection is local, then delay SYN,ACK(SYN) in
1063 * the hope of piggy-backing it on a response
1064 * segment. Otherwise must send ACK now in case
1065 * the other side is slow starting.
1067 if (DELAY_ACK(tp) &&
1068 ((thflags & TH_FIN) ||
1070 ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
1071 (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
1072 tcp_callout_reset(tp, tp->tt_delack,
1073 tcp_delacktime, tcp_timer_delack);
1074 tp->t_flags |= TF_NEEDSYN;
1076 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1079 tcpstat.tcps_connects++;
1088 * Should not happen - syncache should pick up these connections.
1090 * Once we are past handling listen sockets we must be in the
1091 * correct protocol processing thread.
1093 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN state"));
1094 KKASSERT(so->so_port == &curthread->td_msgport);
1097 * This is the second part of the MSS DoS prevention code (after
1098 * minmss on the sending side) and it deals with too many too small
1099 * tcp packets in a too short timeframe (1 second).
1101 * XXX Removed. This code was crap. It does not scale to network
1102 * speed, and default values break NFS. Gone.
1107 * Segment received on connection.
1109 * Reset idle time and keep-alive timer. Don't waste time if less
1110 * then a second has elapsed.
1112 if ((int)(ticks - tp->t_rcvtime) > hz)
1113 tcp_timer_keep_activity(tp, thflags);
1117 * XXX this is tradtitional behavior, may need to be cleaned up.
1119 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0);
1120 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1121 if (to.to_flags & TOF_SCALE) {
1122 tp->t_flags |= TF_RCVD_SCALE;
1123 tp->requested_s_scale = to.to_requested_s_scale;
1125 if (to.to_flags & TOF_TS) {
1126 tp->t_flags |= TF_RCVD_TSTMP;
1127 tp->ts_recent = to.to_tsval;
1128 tp->ts_recent_age = ticks;
1130 if (to.to_flags & TOF_MSS)
1131 tcp_mss(tp, to.to_mss);
1133 * Only set the TF_SACK_PERMITTED per-connection flag
1134 * if we got a SACK_PERMITTED option from the other side
1135 * and the global tcp_do_sack variable is true.
1137 if (tcp_do_sack && (to.to_flags & TOF_SACK_PERMITTED))
1138 tp->t_flags |= TF_SACK_PERMITTED;
1142 * Header prediction: check for the two common cases
1143 * of a uni-directional data xfer. If the packet has
1144 * no control flags, is in-sequence, the window didn't
1145 * change and we're not retransmitting, it's a
1146 * candidate. If the length is zero and the ack moved
1147 * forward, we're the sender side of the xfer. Just
1148 * free the data acked & wake any higher level process
1149 * that was blocked waiting for space. If the length
1150 * is non-zero and the ack didn't move, we're the
1151 * receiver side. If we're getting packets in-order
1152 * (the reassembly queue is empty), add the data to
1153 * the socket buffer and note that we need a delayed ack.
1154 * Make sure that the hidden state-flags are also off.
1155 * Since we check for TCPS_ESTABLISHED above, it can only
1158 if (tp->t_state == TCPS_ESTABLISHED &&
1159 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1160 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1161 (!(to.to_flags & TOF_TS) ||
1162 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1163 th->th_seq == tp->rcv_nxt &&
1164 tp->snd_nxt == tp->snd_max) {
1167 * If last ACK falls within this segment's sequence numbers,
1168 * record the timestamp.
1169 * NOTE that the test is modified according to the latest
1170 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1172 if ((to.to_flags & TOF_TS) &&
1173 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1174 tp->ts_recent_age = ticks;
1175 tp->ts_recent = to.to_tsval;
1179 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1180 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1181 tp->snd_cwnd >= tp->snd_wnd &&
1182 !IN_FASTRECOVERY(tp)) {
1184 * This is a pure ack for outstanding data.
1186 ++tcpstat.tcps_predack;
1188 * "bad retransmit" recovery
1190 * If Eifel detection applies, then
1191 * it is deterministic, so use it
1192 * unconditionally over the old heuristic.
1193 * Otherwise, fall back to the old heuristic.
1195 if (tcp_do_eifel_detect &&
1196 (to.to_flags & TOF_TS) && to.to_tsecr &&
1197 (tp->t_flags & TF_FIRSTACCACK)) {
1198 /* Eifel detection applicable. */
1199 if (to.to_tsecr < tp->t_rexmtTS) {
1200 tcp_revert_congestion_state(tp);
1201 ++tcpstat.tcps_eifeldetected;
1203 } else if (tp->t_rxtshift == 1 &&
1204 ticks < tp->t_badrxtwin) {
1205 tcp_revert_congestion_state(tp);
1206 ++tcpstat.tcps_rttdetected;
1208 tp->t_flags &= ~(TF_FIRSTACCACK |
1209 TF_FASTREXMT | TF_EARLYREXMT);
1211 * Recalculate the retransmit timer / rtt.
1213 * Some machines (certain windows boxes)
1214 * send broken timestamp replies during the
1215 * SYN+ACK phase, ignore timestamps of 0.
1217 if ((to.to_flags & TOF_TS) && to.to_tsecr) {
1219 ticks - to.to_tsecr + 1);
1220 } else if (tp->t_rtttime &&
1221 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1223 ticks - tp->t_rtttime);
1225 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1226 acked = th->th_ack - tp->snd_una;
1227 tcpstat.tcps_rcvackpack++;
1228 tcpstat.tcps_rcvackbyte += acked;
1229 sbdrop(&so->so_snd.sb, acked);
1230 tp->snd_recover = th->th_ack - 1;
1231 tp->snd_una = th->th_ack;
1234 * Update window information.
1236 if (tiwin != tp->snd_wnd &&
1237 acceptable_window_update(tp, th, tiwin)) {
1238 /* keep track of pure window updates */
1239 if (tp->snd_wl2 == th->th_ack &&
1240 tiwin > tp->snd_wnd)
1241 tcpstat.tcps_rcvwinupd++;
1242 tp->snd_wnd = tiwin;
1243 tp->snd_wl1 = th->th_seq;
1244 tp->snd_wl2 = th->th_ack;
1245 if (tp->snd_wnd > tp->max_sndwnd)
1246 tp->max_sndwnd = tp->snd_wnd;
1249 ND6_HINT(tp); /* some progress has been done */
1251 * If all outstanding data are acked, stop
1252 * retransmit timer, otherwise restart timer
1253 * using current (possibly backed-off) value.
1254 * If process is waiting for space,
1255 * wakeup/selwakeup/signal. If data
1256 * are ready to send, let tcp_output
1257 * decide between more output or persist.
1259 if (tp->snd_una == tp->snd_max) {
1260 tcp_callout_stop(tp, tp->tt_rexmt);
1261 } else if (!tcp_callout_active(tp,
1263 tcp_callout_reset(tp, tp->tt_rexmt,
1264 tp->t_rxtcur, tcp_timer_rexmt);
1267 if (so->so_snd.ssb_cc > 0)
1269 return(IPPROTO_DONE);
1271 } else if (tiwin == tp->snd_wnd &&
1272 th->th_ack == tp->snd_una &&
1273 LIST_EMPTY(&tp->t_segq) &&
1274 tlen <= ssb_space(&so->so_rcv)) {
1275 u_long newsize = 0; /* automatic sockbuf scaling */
1277 * This is a pure, in-sequence data packet
1278 * with nothing on the reassembly queue and
1279 * we have enough buffer space to take it.
1281 ++tcpstat.tcps_preddat;
1282 tp->rcv_nxt += tlen;
1283 tcpstat.tcps_rcvpack++;
1284 tcpstat.tcps_rcvbyte += tlen;
1285 ND6_HINT(tp); /* some progress has been done */
1287 * Automatic sizing of receive socket buffer. Often the send
1288 * buffer size is not optimally adjusted to the actual network
1289 * conditions at hand (delay bandwidth product). Setting the
1290 * buffer size too small limits throughput on links with high
1291 * bandwidth and high delay (eg. trans-continental/oceanic links).
1293 * On the receive side the socket buffer memory is only rarely
1294 * used to any significant extent. This allows us to be much
1295 * more aggressive in scaling the receive socket buffer. For
1296 * the case that the buffer space is actually used to a large
1297 * extent and we run out of kernel memory we can simply drop
1298 * the new segments; TCP on the sender will just retransmit it
1299 * later. Setting the buffer size too big may only consume too
1300 * much kernel memory if the application doesn't read() from
1301 * the socket or packet loss or reordering makes use of the
1304 * The criteria to step up the receive buffer one notch are:
1305 * 1. the number of bytes received during the time it takes
1306 * one timestamp to be reflected back to us (the RTT);
1307 * 2. received bytes per RTT is within seven eighth of the
1308 * current socket buffer size;
1309 * 3. receive buffer size has not hit maximal automatic size;
1311 * This algorithm does one step per RTT at most and only if
1312 * we receive a bulk stream w/o packet losses or reorderings.
1313 * Shrinking the buffer during idle times is not necessary as
1314 * it doesn't consume any memory when idle.
1316 * TODO: Only step up if the application is actually serving
1317 * the buffer to better manage the socket buffer resources.
1319 if (tcp_do_autorcvbuf &&
1321 (so->so_rcv.ssb_flags & SSB_AUTOSIZE)) {
1322 if (to.to_tsecr > tp->rfbuf_ts &&
1323 to.to_tsecr - tp->rfbuf_ts < hz) {
1325 (so->so_rcv.ssb_hiwat / 8 * 7) &&
1326 so->so_rcv.ssb_hiwat <
1327 tcp_autorcvbuf_max) {
1329 ulmin(so->so_rcv.ssb_hiwat +
1331 tcp_autorcvbuf_max);
1333 /* Start over with next RTT. */
1337 tp->rfbuf_cnt += tlen; /* add up */
1340 * Add data to socket buffer.
1342 if (so->so_state & SS_CANTRCVMORE) {
1346 * Set new socket buffer size, give up when
1349 * Adjusting the size can mess up ACK
1350 * sequencing when pure window updates are
1351 * being avoided (which is the default),
1354 lwkt_gettoken(&so->so_rcv.ssb_token);
1356 tp->t_flags |= TF_RXRESIZED;
1357 if (!ssb_reserve(&so->so_rcv, newsize,
1359 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1362 (TCP_MAXWIN << tp->rcv_scale)) {
1363 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1366 m_adj(m, drop_hdrlen); /* delayed header drop */
1367 ssb_appendstream(&so->so_rcv, m);
1368 lwkt_reltoken(&so->so_rcv.ssb_token);
1372 * This code is responsible for most of the ACKs
1373 * the TCP stack sends back after receiving a data
1374 * packet. Note that the DELAY_ACK check fails if
1375 * the delack timer is already running, which results
1376 * in an ack being sent every other packet (which is
1379 * We then further aggregate acks by not actually
1380 * sending one until the protocol thread has completed
1381 * processing the current backlog of packets. This
1382 * does not delay the ack any further, but allows us
1383 * to take advantage of the packet aggregation that
1384 * high speed NICs do (usually blocks of 8-10 packets)
1385 * to send a single ack rather then four or five acks,
1386 * greatly reducing the ack rate, the return channel
1387 * bandwidth, and the protocol overhead on both ends.
1389 * Since this also has the effect of slowing down
1390 * the exponential slow-start ramp-up, systems with
1391 * very large bandwidth-delay products might want
1392 * to turn the feature off.
1394 if (DELAY_ACK(tp)) {
1395 tcp_callout_reset(tp, tp->tt_delack,
1396 tcp_delacktime, tcp_timer_delack);
1397 } else if (tcp_aggregate_acks) {
1398 tp->t_flags |= TF_ACKNOW;
1399 if (!(tp->t_flags & TF_ONOUTPUTQ)) {
1400 tp->t_flags |= TF_ONOUTPUTQ;
1401 tp->tt_cpu = mycpu->gd_cpuid;
1403 &tcpcbackq[tp->tt_cpu],
1407 tp->t_flags |= TF_ACKNOW;
1410 return(IPPROTO_DONE);
1415 * Calculate amount of space in receive window,
1416 * and then do TCP input processing.
1417 * Receive window is amount of space in rcv queue,
1418 * but not less than advertised window.
1420 recvwin = ssb_space(&so->so_rcv);
1423 tp->rcv_wnd = imax(recvwin, (int)(tp->rcv_adv - tp->rcv_nxt));
1425 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1429 switch (tp->t_state) {
1431 * If the state is SYN_RECEIVED:
1432 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1434 case TCPS_SYN_RECEIVED:
1435 if ((thflags & TH_ACK) &&
1436 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1437 SEQ_GT(th->th_ack, tp->snd_max))) {
1438 rstreason = BANDLIM_RST_OPENPORT;
1444 * If the state is SYN_SENT:
1445 * if seg contains an ACK, but not for our SYN, drop the input.
1446 * if seg contains a RST, then drop the connection.
1447 * if seg does not contain SYN, then drop it.
1448 * Otherwise this is an acceptable SYN segment
1449 * initialize tp->rcv_nxt and tp->irs
1450 * if seg contains ack then advance tp->snd_una
1451 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1452 * arrange for segment to be acked (eventually)
1453 * continue processing rest of data/controls, beginning with URG
1456 if ((thflags & TH_ACK) &&
1457 (SEQ_LEQ(th->th_ack, tp->iss) ||
1458 SEQ_GT(th->th_ack, tp->snd_max))) {
1459 rstreason = BANDLIM_UNLIMITED;
1462 if (thflags & TH_RST) {
1463 if (thflags & TH_ACK)
1464 tp = tcp_drop(tp, ECONNREFUSED);
1467 if (!(thflags & TH_SYN))
1469 tp->snd_wnd = th->th_win; /* initial send window */
1471 tp->irs = th->th_seq;
1473 if (thflags & TH_ACK) {
1474 /* Our SYN was acked. */
1475 tcpstat.tcps_connects++;
1477 /* Do window scaling on this connection? */
1478 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1479 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1480 tp->snd_scale = tp->requested_s_scale;
1481 tp->rcv_scale = tp->request_r_scale;
1483 tp->rcv_adv += tp->rcv_wnd;
1484 tp->snd_una++; /* SYN is acked */
1485 tcp_callout_stop(tp, tp->tt_rexmt);
1487 * If there's data, delay ACK; if there's also a FIN
1488 * ACKNOW will be turned on later.
1490 if (DELAY_ACK(tp) && tlen != 0) {
1491 tcp_callout_reset(tp, tp->tt_delack,
1492 tcp_delacktime, tcp_timer_delack);
1494 tp->t_flags |= TF_ACKNOW;
1497 * Received <SYN,ACK> in SYN_SENT[*] state.
1499 * SYN_SENT --> ESTABLISHED
1500 * SYN_SENT* --> FIN_WAIT_1
1502 tp->t_starttime = ticks;
1503 if (tp->t_flags & TF_NEEDFIN) {
1504 tp->t_state = TCPS_FIN_WAIT_1;
1505 tp->t_flags &= ~TF_NEEDFIN;
1508 tp->t_state = TCPS_ESTABLISHED;
1509 tcp_callout_reset(tp, tp->tt_keep,
1510 tcp_getkeepidle(tp),
1515 * Received initial SYN in SYN-SENT[*] state =>
1516 * simultaneous open.
1517 * Do 3-way handshake:
1518 * SYN-SENT -> SYN-RECEIVED
1519 * SYN-SENT* -> SYN-RECEIVED*
1521 tp->t_flags |= TF_ACKNOW;
1522 tcp_callout_stop(tp, tp->tt_rexmt);
1523 tp->t_state = TCPS_SYN_RECEIVED;
1528 * Advance th->th_seq to correspond to first data byte.
1529 * If data, trim to stay within window,
1530 * dropping FIN if necessary.
1533 if (tlen > tp->rcv_wnd) {
1534 todrop = tlen - tp->rcv_wnd;
1538 tcpstat.tcps_rcvpackafterwin++;
1539 tcpstat.tcps_rcvbyteafterwin += todrop;
1541 tp->snd_wl1 = th->th_seq - 1;
1542 tp->rcv_up = th->th_seq;
1544 * Client side of transaction: already sent SYN and data.
1545 * If the remote host used T/TCP to validate the SYN,
1546 * our data will be ACK'd; if so, enter normal data segment
1547 * processing in the middle of step 5, ack processing.
1548 * Otherwise, goto step 6.
1550 if (thflags & TH_ACK)
1556 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1557 * do normal processing (we no longer bother with T/TCP).
1561 case TCPS_TIME_WAIT:
1562 break; /* continue normal processing */
1566 * States other than LISTEN or SYN_SENT.
1567 * First check the RST flag and sequence number since reset segments
1568 * are exempt from the timestamp and connection count tests. This
1569 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1570 * below which allowed reset segments in half the sequence space
1571 * to fall though and be processed (which gives forged reset
1572 * segments with a random sequence number a 50 percent chance of
1573 * killing a connection).
1574 * Then check timestamp, if present.
1575 * Then check the connection count, if present.
1576 * Then check that at least some bytes of segment are within
1577 * receive window. If segment begins before rcv_nxt,
1578 * drop leading data (and SYN); if nothing left, just ack.
1581 * If the RST bit is set, check the sequence number to see
1582 * if this is a valid reset segment.
1584 * In all states except SYN-SENT, all reset (RST) segments
1585 * are validated by checking their SEQ-fields. A reset is
1586 * valid if its sequence number is in the window.
1587 * Note: this does not take into account delayed ACKs, so
1588 * we should test against last_ack_sent instead of rcv_nxt.
1589 * The sequence number in the reset segment is normally an
1590 * echo of our outgoing acknowledgement numbers, but some hosts
1591 * send a reset with the sequence number at the rightmost edge
1592 * of our receive window, and we have to handle this case.
1593 * If we have multiple segments in flight, the intial reset
1594 * segment sequence numbers will be to the left of last_ack_sent,
1595 * but they will eventually catch up.
1596 * In any case, it never made sense to trim reset segments to
1597 * fit the receive window since RFC 1122 says:
1598 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1600 * A TCP SHOULD allow a received RST segment to include data.
1603 * It has been suggested that a RST segment could contain
1604 * ASCII text that encoded and explained the cause of the
1605 * RST. No standard has yet been established for such
1608 * If the reset segment passes the sequence number test examine
1610 * SYN_RECEIVED STATE:
1611 * If passive open, return to LISTEN state.
1612 * If active open, inform user that connection was refused.
1613 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1614 * Inform user that connection was reset, and close tcb.
1615 * CLOSING, LAST_ACK STATES:
1618 * Drop the segment - see Stevens, vol. 2, p. 964 and
1621 if (thflags & TH_RST) {
1622 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1623 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1624 switch (tp->t_state) {
1626 case TCPS_SYN_RECEIVED:
1627 so->so_error = ECONNREFUSED;
1630 case TCPS_ESTABLISHED:
1631 case TCPS_FIN_WAIT_1:
1632 case TCPS_FIN_WAIT_2:
1633 case TCPS_CLOSE_WAIT:
1634 so->so_error = ECONNRESET;
1636 tp->t_state = TCPS_CLOSED;
1637 tcpstat.tcps_drops++;
1646 case TCPS_TIME_WAIT:
1654 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1655 * and it's less than ts_recent, drop it.
1657 if ((to.to_flags & TOF_TS) && tp->ts_recent != 0 &&
1658 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1660 /* Check to see if ts_recent is over 24 days old. */
1661 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1663 * Invalidate ts_recent. If this segment updates
1664 * ts_recent, the age will be reset later and ts_recent
1665 * will get a valid value. If it does not, setting
1666 * ts_recent to zero will at least satisfy the
1667 * requirement that zero be placed in the timestamp
1668 * echo reply when ts_recent isn't valid. The
1669 * age isn't reset until we get a valid ts_recent
1670 * because we don't want out-of-order segments to be
1671 * dropped when ts_recent is old.
1675 tcpstat.tcps_rcvduppack++;
1676 tcpstat.tcps_rcvdupbyte += tlen;
1677 tcpstat.tcps_pawsdrop++;
1685 * In the SYN-RECEIVED state, validate that the packet belongs to
1686 * this connection before trimming the data to fit the receive
1687 * window. Check the sequence number versus IRS since we know
1688 * the sequence numbers haven't wrapped. This is a partial fix
1689 * for the "LAND" DoS attack.
1691 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1692 rstreason = BANDLIM_RST_OPENPORT;
1696 todrop = tp->rcv_nxt - th->th_seq;
1698 if (TCP_DO_SACK(tp)) {
1699 /* Report duplicate segment at head of packet. */
1700 tp->reportblk.rblk_start = th->th_seq;
1701 tp->reportblk.rblk_end = th->th_seq + tlen;
1702 if (thflags & TH_FIN)
1703 ++tp->reportblk.rblk_end;
1704 if (SEQ_GT(tp->reportblk.rblk_end, tp->rcv_nxt))
1705 tp->reportblk.rblk_end = tp->rcv_nxt;
1706 tp->t_flags |= (TF_DUPSEG | TF_SACKLEFT | TF_ACKNOW);
1708 if (thflags & TH_SYN) {
1718 * Following if statement from Stevens, vol. 2, p. 960.
1720 if (todrop > tlen ||
1721 (todrop == tlen && !(thflags & TH_FIN))) {
1723 * Any valid FIN must be to the left of the window.
1724 * At this point the FIN must be a duplicate or out
1725 * of sequence; drop it.
1730 * Send an ACK to resynchronize and drop any data.
1731 * But keep on processing for RST or ACK.
1733 tp->t_flags |= TF_ACKNOW;
1735 tcpstat.tcps_rcvduppack++;
1736 tcpstat.tcps_rcvdupbyte += todrop;
1738 tcpstat.tcps_rcvpartduppack++;
1739 tcpstat.tcps_rcvpartdupbyte += todrop;
1741 drop_hdrlen += todrop; /* drop from the top afterwards */
1742 th->th_seq += todrop;
1744 if (th->th_urp > todrop)
1745 th->th_urp -= todrop;
1753 * If new data are received on a connection after the
1754 * user processes are gone, then RST the other end.
1756 if ((so->so_state & SS_NOFDREF) &&
1757 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1759 tcpstat.tcps_rcvafterclose++;
1760 rstreason = BANDLIM_UNLIMITED;
1765 * If segment ends after window, drop trailing data
1766 * (and PUSH and FIN); if nothing left, just ACK.
1768 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1770 tcpstat.tcps_rcvpackafterwin++;
1771 if (todrop >= tlen) {
1772 tcpstat.tcps_rcvbyteafterwin += tlen;
1774 * If a new connection request is received
1775 * while in TIME_WAIT, drop the old connection
1776 * and start over if the sequence numbers
1777 * are above the previous ones.
1779 if (thflags & TH_SYN &&
1780 tp->t_state == TCPS_TIME_WAIT &&
1781 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1786 * If window is closed can only take segments at
1787 * window edge, and have to drop data and PUSH from
1788 * incoming segments. Continue processing, but
1789 * remember to ack. Otherwise, drop segment
1792 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1793 tp->t_flags |= TF_ACKNOW;
1794 tcpstat.tcps_rcvwinprobe++;
1798 tcpstat.tcps_rcvbyteafterwin += todrop;
1801 thflags &= ~(TH_PUSH | TH_FIN);
1805 * If last ACK falls within this segment's sequence numbers,
1806 * record its timestamp.
1808 * 1) That the test incorporates suggestions from the latest
1809 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1810 * 2) That updating only on newer timestamps interferes with
1811 * our earlier PAWS tests, so this check should be solely
1812 * predicated on the sequence space of this segment.
1813 * 3) That we modify the segment boundary check to be
1814 * Last.ACK.Sent <= SEG.SEQ + SEG.LEN
1815 * instead of RFC1323's
1816 * Last.ACK.Sent < SEG.SEQ + SEG.LEN,
1817 * This modified check allows us to overcome RFC1323's
1818 * limitations as described in Stevens TCP/IP Illustrated
1819 * Vol. 2 p.869. In such cases, we can still calculate the
1820 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1822 if ((to.to_flags & TOF_TS) && SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1823 SEQ_LEQ(tp->last_ack_sent, (th->th_seq + tlen
1824 + ((thflags & TH_SYN) != 0)
1825 + ((thflags & TH_FIN) != 0)))) {
1826 tp->ts_recent_age = ticks;
1827 tp->ts_recent = to.to_tsval;
1831 * If a SYN is in the window, then this is an
1832 * error and we send an RST and drop the connection.
1834 if (thflags & TH_SYN) {
1835 tp = tcp_drop(tp, ECONNRESET);
1836 rstreason = BANDLIM_UNLIMITED;
1841 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1842 * flag is on (half-synchronized state), then queue data for
1843 * later processing; else drop segment and return.
1845 if (!(thflags & TH_ACK)) {
1846 if (tp->t_state == TCPS_SYN_RECEIVED ||
1847 (tp->t_flags & TF_NEEDSYN))
1856 switch (tp->t_state) {
1858 * In SYN_RECEIVED state, the ACK acknowledges our SYN, so enter
1859 * ESTABLISHED state and continue processing.
1860 * The ACK was checked above.
1862 case TCPS_SYN_RECEIVED:
1864 tcpstat.tcps_connects++;
1866 /* Do window scaling? */
1867 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1868 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1869 tp->snd_scale = tp->requested_s_scale;
1870 tp->rcv_scale = tp->request_r_scale;
1874 * SYN-RECEIVED -> ESTABLISHED
1875 * SYN-RECEIVED* -> FIN-WAIT-1
1877 tp->t_starttime = ticks;
1878 if (tp->t_flags & TF_NEEDFIN) {
1879 tp->t_state = TCPS_FIN_WAIT_1;
1880 tp->t_flags &= ~TF_NEEDFIN;
1882 tp->t_state = TCPS_ESTABLISHED;
1883 tcp_callout_reset(tp, tp->tt_keep,
1884 tcp_getkeepidle(tp),
1888 * If segment contains data or ACK, will call tcp_reass()
1889 * later; if not, do so now to pass queued data to user.
1891 if (tlen == 0 && !(thflags & TH_FIN))
1892 tcp_reass(tp, NULL, NULL, NULL);
1896 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1897 * ACKs. If the ack is in the range
1898 * tp->snd_una < th->th_ack <= tp->snd_max
1899 * then advance tp->snd_una to th->th_ack and drop
1900 * data from the retransmission queue. If this ACK reflects
1901 * more up to date window information we update our window information.
1903 case TCPS_ESTABLISHED:
1904 case TCPS_FIN_WAIT_1:
1905 case TCPS_FIN_WAIT_2:
1906 case TCPS_CLOSE_WAIT:
1909 case TCPS_TIME_WAIT:
1911 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1912 if (TCP_DO_SACK(tp))
1913 tcp_sack_update_scoreboard(tp, &to);
1914 if (tlen != 0 || tiwin != tp->snd_wnd) {
1918 tcpstat.tcps_rcvdupack++;
1919 if (!tcp_callout_active(tp, tp->tt_rexmt) ||
1920 th->th_ack != tp->snd_una) {
1925 * We have outstanding data (other than
1926 * a window probe), this is a completely
1927 * duplicate ack (ie, window info didn't
1928 * change), the ack is the biggest we've
1929 * seen and we've seen exactly our rexmt
1930 * threshhold of them, so assume a packet
1931 * has been dropped and retransmit it.
1932 * Kludge snd_nxt & the congestion
1933 * window so we send only this one
1936 if (IN_FASTRECOVERY(tp)) {
1937 if (TCP_DO_SACK(tp)) {
1938 /* No artifical cwnd inflation. */
1939 tcp_sack_rexmt(tp, th);
1942 * Dup acks mean that packets
1943 * have left the network
1944 * (they're now cached at the
1945 * receiver) so bump cwnd by
1946 * the amount in the receiver
1947 * to keep a constant cwnd
1948 * packets in the network.
1950 tp->snd_cwnd += tp->t_maxseg;
1953 } else if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1956 } else if (++tp->t_dupacks == tcprexmtthresh) {
1957 tcp_seq old_snd_nxt;
1961 if (tcp_do_eifel_detect &&
1962 (tp->t_flags & TF_RCVD_TSTMP)) {
1963 tcp_save_congestion_state(tp);
1964 tp->t_flags |= TF_FASTREXMT;
1967 * We know we're losing at the current
1968 * window size, so do congestion avoidance:
1969 * set ssthresh to half the current window
1970 * and pull our congestion window back to the
1973 win = min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1977 tp->snd_ssthresh = win * tp->t_maxseg;
1978 ENTER_FASTRECOVERY(tp);
1979 tp->snd_recover = tp->snd_max;
1980 tcp_callout_stop(tp, tp->tt_rexmt);
1982 old_snd_nxt = tp->snd_nxt;
1983 tp->snd_nxt = th->th_ack;
1984 tp->snd_cwnd = tp->t_maxseg;
1986 ++tcpstat.tcps_sndfastrexmit;
1987 tp->snd_cwnd = tp->snd_ssthresh;
1988 tp->rexmt_high = tp->snd_nxt;
1989 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
1990 tp->snd_nxt = old_snd_nxt;
1991 KASSERT(tp->snd_limited <= 2,
1992 ("tp->snd_limited too big"));
1993 if (TCP_DO_SACK(tp))
1994 tcp_sack_rexmt(tp, th);
1996 tp->snd_cwnd += tp->t_maxseg *
1997 (tp->t_dupacks - tp->snd_limited);
1998 } else if (tcp_do_limitedtransmit) {
1999 u_long oldcwnd = tp->snd_cwnd;
2000 tcp_seq oldsndmax = tp->snd_max;
2001 tcp_seq oldsndnxt = tp->snd_nxt;
2002 /* outstanding data */
2003 uint32_t ownd = tp->snd_max - tp->snd_una;
2006 #define iceildiv(n, d) (((n)+(d)-1) / (d))
2008 KASSERT(tp->t_dupacks == 1 ||
2010 ("dupacks not 1 or 2"));
2011 if (tp->t_dupacks == 1)
2012 tp->snd_limited = 0;
2013 tp->snd_nxt = tp->snd_max;
2014 tp->snd_cwnd = ownd +
2015 (tp->t_dupacks - tp->snd_limited) *
2020 * Other acks may have been processed,
2021 * snd_nxt cannot be reset to a value less
2024 if (SEQ_LT(oldsndnxt, oldsndmax)) {
2025 if (SEQ_GT(oldsndnxt, tp->snd_una))
2026 tp->snd_nxt = oldsndnxt;
2028 tp->snd_nxt = tp->snd_una;
2030 tp->snd_cwnd = oldcwnd;
2031 sent = tp->snd_max - oldsndmax;
2032 if (sent > tp->t_maxseg) {
2033 KASSERT((tp->t_dupacks == 2 &&
2034 tp->snd_limited == 0) ||
2035 (sent == tp->t_maxseg + 1 &&
2036 tp->t_flags & TF_SENTFIN),
2038 KASSERT(sent <= tp->t_maxseg * 2,
2039 ("sent too many segments"));
2040 tp->snd_limited = 2;
2041 tcpstat.tcps_sndlimited += 2;
2042 } else if (sent > 0) {
2044 ++tcpstat.tcps_sndlimited;
2045 } else if (tcp_do_early_retransmit &&
2046 (tcp_do_eifel_detect &&
2047 (tp->t_flags & TF_RCVD_TSTMP)) &&
2048 ownd < 4 * tp->t_maxseg &&
2049 tp->t_dupacks + 1 >=
2050 iceildiv(ownd, tp->t_maxseg) &&
2051 (!TCP_DO_SACK(tp) ||
2052 ownd <= tp->t_maxseg ||
2053 tcp_sack_has_sacked(&tp->scb,
2054 ownd - tp->t_maxseg))) {
2055 ++tcpstat.tcps_sndearlyrexmit;
2056 tp->t_flags |= TF_EARLYREXMT;
2057 goto fastretransmit;
2063 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
2065 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2067 * Detected optimistic ACK attack.
2068 * Force slow-start to de-synchronize attack.
2070 tp->snd_cwnd = tp->t_maxseg;
2073 tcpstat.tcps_rcvacktoomuch++;
2077 * If we reach this point, ACK is not a duplicate,
2078 * i.e., it ACKs something we sent.
2080 if (tp->t_flags & TF_NEEDSYN) {
2082 * T/TCP: Connection was half-synchronized, and our
2083 * SYN has been ACK'd (so connection is now fully
2084 * synchronized). Go to non-starred state,
2085 * increment snd_una for ACK of SYN, and check if
2086 * we can do window scaling.
2088 tp->t_flags &= ~TF_NEEDSYN;
2090 /* Do window scaling? */
2091 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
2092 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
2093 tp->snd_scale = tp->requested_s_scale;
2094 tp->rcv_scale = tp->request_r_scale;
2099 acked = th->th_ack - tp->snd_una;
2100 tcpstat.tcps_rcvackpack++;
2101 tcpstat.tcps_rcvackbyte += acked;
2103 if (tcp_do_eifel_detect && acked > 0 &&
2104 (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
2105 (tp->t_flags & TF_FIRSTACCACK)) {
2106 /* Eifel detection applicable. */
2107 if (to.to_tsecr < tp->t_rexmtTS) {
2108 ++tcpstat.tcps_eifeldetected;
2109 tcp_revert_congestion_state(tp);
2110 if (tp->t_rxtshift == 1 &&
2111 ticks >= tp->t_badrxtwin)
2112 ++tcpstat.tcps_rttcantdetect;
2114 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2116 * If we just performed our first retransmit,
2117 * and the ACK arrives within our recovery window,
2118 * then it was a mistake to do the retransmit
2119 * in the first place. Recover our original cwnd
2120 * and ssthresh, and proceed to transmit where we
2123 tcp_revert_congestion_state(tp);
2124 ++tcpstat.tcps_rttdetected;
2128 * If we have a timestamp reply, update smoothed
2129 * round trip time. If no timestamp is present but
2130 * transmit timer is running and timed sequence
2131 * number was acked, update smoothed round trip time.
2132 * Since we now have an rtt measurement, cancel the
2133 * timer backoff (cf., Phil Karn's retransmit alg.).
2134 * Recompute the initial retransmit timer.
2136 * Some machines (certain windows boxes) send broken
2137 * timestamp replies during the SYN+ACK phase, ignore
2140 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
2141 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2142 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2143 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2144 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2147 * If no data (only SYN) was ACK'd,
2148 * skip rest of ACK processing.
2153 /* Stop looking for an acceptable ACK since one was received. */
2154 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT | TF_EARLYREXMT);
2156 if (acked > so->so_snd.ssb_cc) {
2157 tp->snd_wnd -= so->so_snd.ssb_cc;
2158 sbdrop(&so->so_snd.sb, (int)so->so_snd.ssb_cc);
2159 ourfinisacked = TRUE;
2161 sbdrop(&so->so_snd.sb, acked);
2162 tp->snd_wnd -= acked;
2163 ourfinisacked = FALSE;
2168 * Update window information.
2169 * Don't look at window if no ACK:
2170 * TAC's send garbage on first SYN.
2172 if (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2173 (tp->snd_wl1 == th->th_seq &&
2174 (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2175 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)))) {
2176 /* keep track of pure window updates */
2177 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2178 tiwin > tp->snd_wnd)
2179 tcpstat.tcps_rcvwinupd++;
2180 tp->snd_wnd = tiwin;
2181 tp->snd_wl1 = th->th_seq;
2182 tp->snd_wl2 = th->th_ack;
2183 if (tp->snd_wnd > tp->max_sndwnd)
2184 tp->max_sndwnd = tp->snd_wnd;
2188 tp->snd_una = th->th_ack;
2189 if (TCP_DO_SACK(tp))
2190 tcp_sack_update_scoreboard(tp, &to);
2191 if (IN_FASTRECOVERY(tp)) {
2192 if (SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2193 EXIT_FASTRECOVERY(tp);
2196 * If the congestion window was inflated
2197 * to account for the other side's
2198 * cached packets, retract it.
2200 if (!TCP_DO_SACK(tp))
2201 tp->snd_cwnd = tp->snd_ssthresh;
2204 * Window inflation should have left us
2205 * with approximately snd_ssthresh outstanding
2206 * data. But, in case we would be inclined
2207 * to send a burst, better do it using
2210 if (SEQ_GT(th->th_ack + tp->snd_cwnd,
2211 tp->snd_max + 2 * tp->t_maxseg))
2213 (tp->snd_max - tp->snd_una) +
2218 if (TCP_DO_SACK(tp)) {
2219 tp->snd_max_rexmt = tp->snd_max;
2220 tcp_sack_rexmt(tp, th);
2222 tcp_newreno_partial_ack(tp, th, acked);
2228 * Open the congestion window. When in slow-start,
2229 * open exponentially: maxseg per packet. Otherwise,
2230 * open linearly: maxseg per window.
2232 if (tp->snd_cwnd <= tp->snd_ssthresh) {
2234 (SEQ_LT(tp->snd_nxt, tp->snd_max) ?
2235 tp->t_maxseg : 2 * tp->t_maxseg);
2238 tp->snd_cwnd += tcp_do_abc ?
2239 min(acked, abc_sslimit) : tp->t_maxseg;
2241 /* linear increase */
2242 tp->snd_wacked += tcp_do_abc ? acked :
2244 if (tp->snd_wacked >= tp->snd_cwnd) {
2245 tp->snd_wacked -= tp->snd_cwnd;
2246 tp->snd_cwnd += tp->t_maxseg;
2249 tp->snd_cwnd = min(tp->snd_cwnd,
2250 TCP_MAXWIN << tp->snd_scale);
2251 tp->snd_recover = th->th_ack - 1;
2253 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2254 tp->snd_nxt = tp->snd_una;
2257 * If all outstanding data is acked, stop retransmit
2258 * timer and remember to restart (more output or persist).
2259 * If there is more data to be acked, restart retransmit
2260 * timer, using current (possibly backed-off) value.
2262 if (th->th_ack == tp->snd_max) {
2263 tcp_callout_stop(tp, tp->tt_rexmt);
2265 } else if (!tcp_callout_active(tp, tp->tt_persist)) {
2266 tcp_callout_reset(tp, tp->tt_rexmt, tp->t_rxtcur,
2270 switch (tp->t_state) {
2272 * In FIN_WAIT_1 STATE in addition to the processing
2273 * for the ESTABLISHED state if our FIN is now acknowledged
2274 * then enter FIN_WAIT_2.
2276 case TCPS_FIN_WAIT_1:
2277 if (ourfinisacked) {
2279 * If we can't receive any more
2280 * data, then closing user can proceed.
2281 * Starting the timer is contrary to the
2282 * specification, but if we don't get a FIN
2283 * we'll hang forever.
2285 if (so->so_state & SS_CANTRCVMORE) {
2286 soisdisconnected(so);
2287 tcp_callout_reset(tp, tp->tt_2msl,
2288 tcp_maxidle, tcp_timer_2msl);
2290 tp->t_state = TCPS_FIN_WAIT_2;
2295 * In CLOSING STATE in addition to the processing for
2296 * the ESTABLISHED state if the ACK acknowledges our FIN
2297 * then enter the TIME-WAIT state, otherwise ignore
2301 if (ourfinisacked) {
2302 tp->t_state = TCPS_TIME_WAIT;
2303 tcp_canceltimers(tp);
2304 tcp_callout_reset(tp, tp->tt_2msl,
2305 2 * tcp_msl, tcp_timer_2msl);
2306 soisdisconnected(so);
2311 * In LAST_ACK, we may still be waiting for data to drain
2312 * and/or to be acked, as well as for the ack of our FIN.
2313 * If our FIN is now acknowledged, delete the TCB,
2314 * enter the closed state and return.
2317 if (ourfinisacked) {
2324 * In TIME_WAIT state the only thing that should arrive
2325 * is a retransmission of the remote FIN. Acknowledge
2326 * it and restart the finack timer.
2328 case TCPS_TIME_WAIT:
2329 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_msl,
2337 * Update window information.
2338 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2340 if ((thflags & TH_ACK) &&
2341 acceptable_window_update(tp, th, tiwin)) {
2342 /* keep track of pure window updates */
2343 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2344 tiwin > tp->snd_wnd)
2345 tcpstat.tcps_rcvwinupd++;
2346 tp->snd_wnd = tiwin;
2347 tp->snd_wl1 = th->th_seq;
2348 tp->snd_wl2 = th->th_ack;
2349 if (tp->snd_wnd > tp->max_sndwnd)
2350 tp->max_sndwnd = tp->snd_wnd;
2355 * Process segments with URG.
2357 if ((thflags & TH_URG) && th->th_urp &&
2358 !TCPS_HAVERCVDFIN(tp->t_state)) {
2360 * This is a kludge, but if we receive and accept
2361 * random urgent pointers, we'll crash in
2362 * soreceive. It's hard to imagine someone
2363 * actually wanting to send this much urgent data.
2365 if (th->th_urp + so->so_rcv.ssb_cc > sb_max) {
2366 th->th_urp = 0; /* XXX */
2367 thflags &= ~TH_URG; /* XXX */
2368 goto dodata; /* XXX */
2371 * If this segment advances the known urgent pointer,
2372 * then mark the data stream. This should not happen
2373 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2374 * a FIN has been received from the remote side.
2375 * In these states we ignore the URG.
2377 * According to RFC961 (Assigned Protocols),
2378 * the urgent pointer points to the last octet
2379 * of urgent data. We continue, however,
2380 * to consider it to indicate the first octet
2381 * of data past the urgent section as the original
2382 * spec states (in one of two places).
2384 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
2385 tp->rcv_up = th->th_seq + th->th_urp;
2386 so->so_oobmark = so->so_rcv.ssb_cc +
2387 (tp->rcv_up - tp->rcv_nxt) - 1;
2388 if (so->so_oobmark == 0)
2389 sosetstate(so, SS_RCVATMARK);
2391 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2394 * Remove out of band data so doesn't get presented to user.
2395 * This can happen independent of advancing the URG pointer,
2396 * but if two URG's are pending at once, some out-of-band
2397 * data may creep in... ick.
2399 if (th->th_urp <= (u_long)tlen &&
2400 !(so->so_options & SO_OOBINLINE)) {
2401 /* hdr drop is delayed */
2402 tcp_pulloutofband(so, th, m, drop_hdrlen);
2406 * If no out of band data is expected,
2407 * pull receive urgent pointer along
2408 * with the receive window.
2410 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2411 tp->rcv_up = tp->rcv_nxt;
2416 * Process the segment text, merging it into the TCP sequencing queue,
2417 * and arranging for acknowledgment of receipt if necessary.
2418 * This process logically involves adjusting tp->rcv_wnd as data
2419 * is presented to the user (this happens in tcp_usrreq.c,
2420 * case PRU_RCVD). If a FIN has already been received on this
2421 * connection then we just ignore the text.
2423 if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
2424 m_adj(m, drop_hdrlen); /* delayed header drop */
2426 * Insert segment which includes th into TCP reassembly queue
2427 * with control block tp. Set thflags to whether reassembly now
2428 * includes a segment with FIN. This handles the common case
2429 * inline (segment is the next to be received on an established
2430 * connection, and the queue is empty), avoiding linkage into
2431 * and removal from the queue and repetition of various
2433 * Set DELACK for segments received in order, but ack
2434 * immediately when segments are out of order (so
2435 * fast retransmit can work).
2437 if (th->th_seq == tp->rcv_nxt &&
2438 LIST_EMPTY(&tp->t_segq) &&
2439 TCPS_HAVEESTABLISHED(tp->t_state)) {
2440 if (DELAY_ACK(tp)) {
2441 tcp_callout_reset(tp, tp->tt_delack,
2442 tcp_delacktime, tcp_timer_delack);
2444 tp->t_flags |= TF_ACKNOW;
2446 tp->rcv_nxt += tlen;
2447 thflags = th->th_flags & TH_FIN;
2448 tcpstat.tcps_rcvpack++;
2449 tcpstat.tcps_rcvbyte += tlen;
2451 if (so->so_state & SS_CANTRCVMORE) {
2454 lwkt_gettoken(&so->so_rcv.ssb_token);
2455 ssb_appendstream(&so->so_rcv, m);
2456 lwkt_reltoken(&so->so_rcv.ssb_token);
2460 if (!(tp->t_flags & TF_DUPSEG)) {
2461 /* Initialize SACK report block. */
2462 tp->reportblk.rblk_start = th->th_seq;
2463 tp->reportblk.rblk_end = th->th_seq + tlen +
2464 ((thflags & TH_FIN) != 0);
2466 thflags = tcp_reass(tp, th, &tlen, m);
2467 tp->t_flags |= TF_ACKNOW;
2471 * Note the amount of data that peer has sent into
2472 * our window, in order to estimate the sender's
2475 len = so->so_rcv.ssb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2482 * If FIN is received ACK the FIN and let the user know
2483 * that the connection is closing.
2485 if (thflags & TH_FIN) {
2486 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
2489 * If connection is half-synchronized
2490 * (ie NEEDSYN flag on) then delay ACK,
2491 * so it may be piggybacked when SYN is sent.
2492 * Otherwise, since we received a FIN then no
2493 * more input can be expected, send ACK now.
2495 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN)) {
2496 tcp_callout_reset(tp, tp->tt_delack,
2497 tcp_delacktime, tcp_timer_delack);
2499 tp->t_flags |= TF_ACKNOW;
2504 switch (tp->t_state) {
2506 * In SYN_RECEIVED and ESTABLISHED STATES
2507 * enter the CLOSE_WAIT state.
2509 case TCPS_SYN_RECEIVED:
2510 tp->t_starttime = ticks;
2512 case TCPS_ESTABLISHED:
2513 tp->t_state = TCPS_CLOSE_WAIT;
2517 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2518 * enter the CLOSING state.
2520 case TCPS_FIN_WAIT_1:
2521 tp->t_state = TCPS_CLOSING;
2525 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2526 * starting the time-wait timer, turning off the other
2529 case TCPS_FIN_WAIT_2:
2530 tp->t_state = TCPS_TIME_WAIT;
2531 tcp_canceltimers(tp);
2532 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_msl,
2534 soisdisconnected(so);
2538 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2540 case TCPS_TIME_WAIT:
2541 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_msl,
2548 if (so->so_options & SO_DEBUG)
2549 tcp_trace(TA_INPUT, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2553 * Return any desired output.
2555 if (needoutput || (tp->t_flags & TF_ACKNOW))
2557 return(IPPROTO_DONE);
2561 * Generate an ACK dropping incoming segment if it occupies
2562 * sequence space, where the ACK reflects our state.
2564 * We can now skip the test for the RST flag since all
2565 * paths to this code happen after packets containing
2566 * RST have been dropped.
2568 * In the SYN-RECEIVED state, don't send an ACK unless the
2569 * segment we received passes the SYN-RECEIVED ACK test.
2570 * If it fails send a RST. This breaks the loop in the
2571 * "LAND" DoS attack, and also prevents an ACK storm
2572 * between two listening ports that have been sent forged
2573 * SYN segments, each with the source address of the other.
2575 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2576 (SEQ_GT(tp->snd_una, th->th_ack) ||
2577 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2578 rstreason = BANDLIM_RST_OPENPORT;
2582 if (so->so_options & SO_DEBUG)
2583 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2586 tp->t_flags |= TF_ACKNOW;
2588 return(IPPROTO_DONE);
2592 * Generate a RST, dropping incoming segment.
2593 * Make ACK acceptable to originator of segment.
2594 * Don't bother to respond if destination was broadcast/multicast.
2596 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
2599 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2600 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2603 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2604 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2605 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2606 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2609 /* IPv6 anycast check is done at tcp6_input() */
2612 * Perform bandwidth limiting.
2615 if (badport_bandlim(rstreason) < 0)
2620 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2621 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2623 if (thflags & TH_ACK)
2624 /* mtod() below is safe as long as hdr dropping is delayed */
2625 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2628 if (thflags & TH_SYN)
2630 /* mtod() below is safe as long as hdr dropping is delayed */
2631 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2632 (tcp_seq)0, TH_RST | TH_ACK);
2634 return(IPPROTO_DONE);
2638 * Drop space held by incoming segment and return.
2641 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2642 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2645 return(IPPROTO_DONE);
2649 * Parse TCP options and place in tcpopt.
2652 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn)
2657 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2659 if (opt == TCPOPT_EOL)
2661 if (opt == TCPOPT_NOP)
2667 if (optlen < 2 || optlen > cnt)
2672 if (optlen != TCPOLEN_MAXSEG)
2676 to->to_flags |= TOF_MSS;
2677 bcopy(cp + 2, &to->to_mss, sizeof to->to_mss);
2678 to->to_mss = ntohs(to->to_mss);
2681 if (optlen != TCPOLEN_WINDOW)
2685 to->to_flags |= TOF_SCALE;
2686 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2688 case TCPOPT_TIMESTAMP:
2689 if (optlen != TCPOLEN_TIMESTAMP)
2691 to->to_flags |= TOF_TS;
2692 bcopy(cp + 2, &to->to_tsval, sizeof to->to_tsval);
2693 to->to_tsval = ntohl(to->to_tsval);
2694 bcopy(cp + 6, &to->to_tsecr, sizeof to->to_tsecr);
2695 to->to_tsecr = ntohl(to->to_tsecr);
2697 * If echoed timestamp is later than the current time,
2698 * fall back to non RFC1323 RTT calculation.
2700 if (to->to_tsecr != 0 && TSTMP_GT(to->to_tsecr, ticks))
2703 case TCPOPT_SACK_PERMITTED:
2704 if (optlen != TCPOLEN_SACK_PERMITTED)
2708 to->to_flags |= TOF_SACK_PERMITTED;
2711 if ((optlen - 2) & 0x07) /* not multiple of 8 */
2713 to->to_nsackblocks = (optlen - 2) / 8;
2714 to->to_sackblocks = (struct raw_sackblock *) (cp + 2);
2715 to->to_flags |= TOF_SACK;
2716 for (i = 0; i < to->to_nsackblocks; i++) {
2717 struct raw_sackblock *r = &to->to_sackblocks[i];
2719 r->rblk_start = ntohl(r->rblk_start);
2720 r->rblk_end = ntohl(r->rblk_end);
2723 #ifdef TCP_SIGNATURE
2725 * XXX In order to reply to a host which has set the
2726 * TCP_SIGNATURE option in its initial SYN, we have to
2727 * record the fact that the option was observed here
2728 * for the syncache code to perform the correct response.
2730 case TCPOPT_SIGNATURE:
2731 if (optlen != TCPOLEN_SIGNATURE)
2733 to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2735 #endif /* TCP_SIGNATURE */
2743 * Pull out of band byte out of a segment so
2744 * it doesn't appear in the user's data queue.
2745 * It is still reflected in the segment length for
2746 * sequencing purposes.
2747 * "off" is the delayed to be dropped hdrlen.
2750 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
2752 int cnt = off + th->th_urp - 1;
2755 if (m->m_len > cnt) {
2756 char *cp = mtod(m, caddr_t) + cnt;
2757 struct tcpcb *tp = sototcpcb(so);
2760 tp->t_oobflags |= TCPOOB_HAVEDATA;
2761 bcopy(cp + 1, cp, m->m_len - cnt - 1);
2763 if (m->m_flags & M_PKTHDR)
2772 panic("tcp_pulloutofband");
2776 * Collect new round-trip time estimate
2777 * and update averages and current timeout.
2780 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2784 tcpstat.tcps_rttupdated++;
2786 if (tp->t_srtt != 0) {
2788 * srtt is stored as fixed point with 5 bits after the
2789 * binary point (i.e., scaled by 8). The following magic
2790 * is equivalent to the smoothing algorithm in rfc793 with
2791 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2792 * point). Adjust rtt to origin 0.
2794 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2795 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2797 if ((tp->t_srtt += delta) <= 0)
2801 * We accumulate a smoothed rtt variance (actually, a
2802 * smoothed mean difference), then set the retransmit
2803 * timer to smoothed rtt + 4 times the smoothed variance.
2804 * rttvar is stored as fixed point with 4 bits after the
2805 * binary point (scaled by 16). The following is
2806 * equivalent to rfc793 smoothing with an alpha of .75
2807 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2808 * rfc793's wired-in beta.
2812 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2813 if ((tp->t_rttvar += delta) <= 0)
2815 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2816 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2819 * No rtt measurement yet - use the unsmoothed rtt.
2820 * Set the variance to half the rtt (so our first
2821 * retransmit happens at 3*rtt).
2823 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2824 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2825 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2831 * the retransmit should happen at rtt + 4 * rttvar.
2832 * Because of the way we do the smoothing, srtt and rttvar
2833 * will each average +1/2 tick of bias. When we compute
2834 * the retransmit timer, we want 1/2 tick of rounding and
2835 * 1 extra tick because of +-1/2 tick uncertainty in the
2836 * firing of the timer. The bias will give us exactly the
2837 * 1.5 tick we need. But, because the bias is
2838 * statistical, we have to test that we don't drop below
2839 * the minimum feasible timer (which is 2 ticks).
2841 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2842 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2845 * We received an ack for a packet that wasn't retransmitted;
2846 * it is probably safe to discard any error indications we've
2847 * received recently. This isn't quite right, but close enough
2848 * for now (a route might have failed after we sent a segment,
2849 * and the return path might not be symmetrical).
2851 tp->t_softerror = 0;
2855 * Determine a reasonable value for maxseg size.
2856 * If the route is known, check route for mtu.
2857 * If none, use an mss that can be handled on the outgoing
2858 * interface without forcing IP to fragment; if bigger than
2859 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2860 * to utilize large mbufs. If no route is found, route has no mtu,
2861 * or the destination isn't local, use a default, hopefully conservative
2862 * size (usually 512 or the default IP max size, but no more than the mtu
2863 * of the interface), as we can't discover anything about intervening
2864 * gateways or networks. We also initialize the congestion/slow start
2865 * window to be a single segment if the destination isn't local.
2866 * While looking at the routing entry, we also initialize other path-dependent
2867 * parameters from pre-set or cached values in the routing entry.
2869 * Also take into account the space needed for options that we
2870 * send regularly. Make maxseg shorter by that amount to assure
2871 * that we can send maxseg amount of data even when the options
2872 * are present. Store the upper limit of the length of options plus
2875 * NOTE that this routine is only called when we process an incoming
2876 * segment, for outgoing segments only tcp_mssopt is called.
2879 tcp_mss(struct tcpcb *tp, int offer)
2885 struct inpcb *inp = tp->t_inpcb;
2888 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2889 size_t min_protoh = isipv6 ?
2890 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2891 sizeof(struct tcpiphdr);
2893 const boolean_t isipv6 = FALSE;
2894 const size_t min_protoh = sizeof(struct tcpiphdr);
2898 rt = tcp_rtlookup6(&inp->inp_inc);
2900 rt = tcp_rtlookup(&inp->inp_inc);
2902 tp->t_maxopd = tp->t_maxseg =
2903 (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2907 so = inp->inp_socket;
2910 * Offer == 0 means that there was no MSS on the SYN segment,
2911 * in this case we use either the interface mtu or tcp_mssdflt.
2913 * An offer which is too large will be cut down later.
2917 if (in6_localaddr(&inp->in6p_faddr)) {
2918 offer = ND_IFINFO(rt->rt_ifp)->linkmtu -
2921 offer = tcp_v6mssdflt;
2924 if (in_localaddr(inp->inp_faddr))
2925 offer = ifp->if_mtu - min_protoh;
2927 offer = tcp_mssdflt;
2932 * Prevent DoS attack with too small MSS. Round up
2933 * to at least minmss.
2935 * Sanity check: make sure that maxopd will be large
2936 * enough to allow some data on segments even is the
2937 * all the option space is used (40bytes). Otherwise
2938 * funny things may happen in tcp_output.
2940 offer = max(offer, tcp_minmss);
2941 offer = max(offer, 64);
2943 rt->rt_rmx.rmx_mssopt = offer;
2946 * While we're here, check if there's an initial rtt
2947 * or rttvar. Convert from the route-table units
2948 * to scaled multiples of the slow timeout timer.
2950 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2952 * XXX the lock bit for RTT indicates that the value
2953 * is also a minimum value; this is subject to time.
2955 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2956 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2957 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2958 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2959 tcpstat.tcps_usedrtt++;
2960 if (rt->rt_rmx.rmx_rttvar) {
2961 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2962 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2963 tcpstat.tcps_usedrttvar++;
2965 /* default variation is +- 1 rtt */
2967 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2969 TCPT_RANGESET(tp->t_rxtcur,
2970 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2971 tp->t_rttmin, TCPTV_REXMTMAX);
2975 * if there's an mtu associated with the route, use it
2976 * else, use the link mtu. Take the smaller of mss or offer
2979 if (rt->rt_rmx.rmx_mtu) {
2980 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2983 mss = ND_IFINFO(rt->rt_ifp)->linkmtu - min_protoh;
2985 mss = ifp->if_mtu - min_protoh;
2987 mss = min(mss, offer);
2990 * maxopd stores the maximum length of data AND options
2991 * in a segment; maxseg is the amount of data in a normal
2992 * segment. We need to store this value (maxopd) apart
2993 * from maxseg, because now every segment carries options
2994 * and thus we normally have somewhat less data in segments.
2998 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
2999 ((tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3000 mss -= TCPOLEN_TSTAMP_APPA;
3002 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3004 mss &= ~(MCLBYTES-1);
3007 mss = mss / MCLBYTES * MCLBYTES;
3010 * If there's a pipesize, change the socket buffer
3011 * to that size. Make the socket buffers an integral
3012 * number of mss units; if the mss is larger than
3013 * the socket buffer, decrease the mss.
3016 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
3018 bufsize = so->so_snd.ssb_hiwat;
3022 bufsize = roundup(bufsize, mss);
3023 if (bufsize > sb_max)
3025 if (bufsize > so->so_snd.ssb_hiwat)
3026 ssb_reserve(&so->so_snd, bufsize, so, NULL);
3031 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
3033 bufsize = so->so_rcv.ssb_hiwat;
3034 if (bufsize > mss) {
3035 bufsize = roundup(bufsize, mss);
3036 if (bufsize > sb_max)
3038 if (bufsize > so->so_rcv.ssb_hiwat) {
3039 lwkt_gettoken(&so->so_rcv.ssb_token);
3040 ssb_reserve(&so->so_rcv, bufsize, so, NULL);
3041 lwkt_reltoken(&so->so_rcv.ssb_token);
3046 * Set the slow-start flight size depending on whether this
3047 * is a local network or not.
3050 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3054 if (rt->rt_rmx.rmx_ssthresh) {
3056 * There's some sort of gateway or interface
3057 * buffer limit on the path. Use this to set
3058 * the slow start threshhold, but set the
3059 * threshold to no less than 2*mss.
3061 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3062 tcpstat.tcps_usedssthresh++;
3067 * Determine the MSS option to send on an outgoing SYN.
3070 tcp_mssopt(struct tcpcb *tp)
3075 ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3076 int min_protoh = isipv6 ?
3077 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
3078 sizeof(struct tcpiphdr);
3080 const boolean_t isipv6 = FALSE;
3081 const size_t min_protoh = sizeof(struct tcpiphdr);
3085 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
3087 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
3089 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3091 return (rt->rt_ifp->if_mtu - min_protoh);
3095 * When a partial ack arrives, force the retransmission of the
3096 * next unacknowledged segment. Do not exit Fast Recovery.
3098 * Implement the Slow-but-Steady variant of NewReno by restarting the
3099 * the retransmission timer. Turn it off here so it can be restarted
3100 * later in tcp_output().
3103 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th, int acked)
3105 tcp_seq old_snd_nxt = tp->snd_nxt;
3106 u_long ocwnd = tp->snd_cwnd;
3108 tcp_callout_stop(tp, tp->tt_rexmt);
3110 tp->snd_nxt = th->th_ack;
3111 /* Set snd_cwnd to one segment beyond acknowledged offset. */
3112 tp->snd_cwnd = tp->t_maxseg;
3113 tp->t_flags |= TF_ACKNOW;
3115 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3116 tp->snd_nxt = old_snd_nxt;
3117 /* partial window deflation */
3119 tp->snd_cwnd = ocwnd - acked + tp->t_maxseg;
3121 tp->snd_cwnd = tp->t_maxseg;
3125 * In contrast to the Slow-but-Steady NewReno variant,
3126 * we do not reset the retransmission timer for SACK retransmissions,
3127 * except when retransmitting snd_una.
3130 tcp_sack_rexmt(struct tcpcb *tp, struct tcphdr *th)
3132 uint32_t pipe, seglen;
3135 tcp_seq old_snd_nxt = tp->snd_nxt;
3136 u_long ocwnd = tp->snd_cwnd;
3137 int nseg = 0; /* consecutive new segments */
3138 #define MAXBURST 4 /* limit burst of new packets on partial ack */
3141 pipe = tcp_sack_compute_pipe(tp);
3142 while ((tcp_seq_diff_t)(ocwnd - pipe) >= (tcp_seq_diff_t)tp->t_maxseg &&
3143 (!tcp_do_smartsack || nseg < MAXBURST) &&
3144 tcp_sack_nextseg(tp, &nextrexmt, &seglen, &lostdup)) {
3146 tcp_seq old_snd_max;
3149 if (nextrexmt == tp->snd_max)
3151 tp->snd_nxt = nextrexmt;
3152 tp->snd_cwnd = nextrexmt - tp->snd_una + seglen;
3153 old_snd_max = tp->snd_max;
3154 if (nextrexmt == tp->snd_una)
3155 tcp_callout_stop(tp, tp->tt_rexmt);
3156 error = tcp_output(tp);
3159 sent = tp->snd_nxt - nextrexmt;
3164 tcpstat.tcps_sndsackpack++;
3165 tcpstat.tcps_sndsackbyte += sent;
3166 if (SEQ_LT(nextrexmt, old_snd_max) &&
3167 SEQ_LT(tp->rexmt_high, tp->snd_nxt))
3168 tp->rexmt_high = seq_min(tp->snd_nxt, old_snd_max);
3170 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3171 tp->snd_nxt = old_snd_nxt;
3172 tp->snd_cwnd = ocwnd;
3176 * Reset idle time and keep-alive timer, typically called when a valid
3177 * tcp packet is received but may also be called when FASTKEEP is set
3178 * to prevent the previous long-timeout from calculating to a drop.
3180 * Only update t_rcvtime for non-SYN packets.
3182 * Handle the case where one side thinks the connection is established
3183 * but the other side has, say, rebooted without cleaning out the
3184 * connection. The SYNs could be construed as an attack and wind
3185 * up ignored, but in case it isn't an attack we can validate the
3186 * connection by forcing a keepalive.
3189 tcp_timer_keep_activity(struct tcpcb *tp, int thflags)
3191 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3192 if ((thflags & (TH_SYN | TH_ACK)) == TH_SYN) {
3193 tp->t_flags |= TF_KEEPALIVE;
3194 tcp_callout_reset(tp, tp->tt_keep, hz / 2,
3197 tp->t_rcvtime = ticks;
3198 tp->t_flags &= ~TF_KEEPALIVE;
3199 tcp_callout_reset(tp, tp->tt_keep,
3200 tcp_getkeepidle(tp),