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 */
72 #include "opt_inet6.h"
73 #include "opt_ipsec.h"
74 #include "opt_tcpdebug.h"
75 #include "opt_tcp_input.h"
77 #include <sys/param.h>
78 #include <sys/systm.h>
79 #include <sys/kernel.h>
80 #include <sys/sysctl.h>
81 #include <sys/malloc.h>
83 #include <sys/proc.h> /* for proc0 declaration */
84 #include <sys/protosw.h>
85 #include <sys/socket.h>
86 #include <sys/socketvar.h>
87 #include <sys/syslog.h>
88 #include <sys/in_cksum.h>
90 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
91 #include <machine/stdarg.h>
94 #include <net/route.h>
96 #include <netinet/in.h>
97 #include <netinet/in_systm.h>
98 #include <netinet/ip.h>
99 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
100 #include <netinet/in_var.h>
101 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
102 #include <netinet/in_pcb.h>
103 #include <netinet/ip_var.h>
104 #include <netinet/ip6.h>
105 #include <netinet/icmp6.h>
106 #include <netinet6/nd6.h>
107 #include <netinet6/ip6_var.h>
108 #include <netinet6/in6_pcb.h>
109 #include <netinet/tcp.h>
110 #include <netinet/tcp_fsm.h>
111 #include <netinet/tcp_seq.h>
112 #include <netinet/tcp_timer.h>
113 #include <netinet/tcp_var.h>
114 #include <netinet6/tcp6_var.h>
115 #include <netinet/tcpip.h>
118 #include <netinet/tcp_debug.h>
120 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
121 struct tcphdr tcp_savetcp;
125 #include <netproto/ipsec/ipsec.h>
126 #include <netproto/ipsec/ipsec6.h>
130 #include <netinet6/ipsec.h>
131 #include <netinet6/ipsec6.h>
132 #include <netproto/key/key.h>
135 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
138 static int log_in_vain = 0;
139 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
140 &log_in_vain, 0, "Log all incoming TCP connections");
142 static int blackhole = 0;
143 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
144 &blackhole, 0, "Do not send RST when dropping refused connections");
146 int tcp_delack_enabled = 1;
147 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
148 &tcp_delack_enabled, 0,
149 "Delay ACK to try and piggyback it onto a data packet");
151 #ifdef TCP_DROP_SYNFIN
152 static int drop_synfin = 0;
153 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
154 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
157 static int tcp_do_limitedtransmit = 1;
158 SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
159 &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
161 static int tcp_do_early_retransmit = 1;
162 SYSCTL_INT(_net_inet_tcp, OID_AUTO, earlyretransmit, CTLFLAG_RW,
163 &tcp_do_early_retransmit, 0, "Early retransmit");
165 int tcp_aggregate_acks = 1;
166 SYSCTL_INT(_net_inet_tcp, OID_AUTO, aggregate_acks, CTLFLAG_RW,
167 &tcp_aggregate_acks, 0, "Aggregate built-up acks into one ack");
169 int tcp_do_rfc3390 = 1;
170 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
172 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
174 static int tcp_do_eifel_detect = 1;
175 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
176 &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
178 static int tcp_do_abc = 1;
179 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc, CTLFLAG_RW,
181 "TCP Appropriate Byte Counting (RFC 3465)");
184 * Define as tunable for easy testing with SACK on and off.
185 * Warning: do not change setting in the middle of an existing active TCP flow,
186 * else strange things might happen to that flow.
189 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sack, CTLFLAG_RW,
190 &tcp_do_sack, 0, "Enable SACK Algorithms");
192 int tcp_do_smartsack = 1;
193 SYSCTL_INT(_net_inet_tcp, OID_AUTO, smartsack, CTLFLAG_RW,
194 &tcp_do_smartsack, 0, "Enable Smart SACK Algorithms");
196 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
197 "TCP Segment Reassembly Queue");
199 int tcp_reass_maxseg = 0;
200 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
201 &tcp_reass_maxseg, 0,
202 "Global maximum number of TCP Segments in Reassembly Queue");
204 int tcp_reass_qsize = 0;
205 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
207 "Global number of TCP Segments currently in Reassembly Queue");
209 static int tcp_reass_overflows = 0;
210 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
211 &tcp_reass_overflows, 0,
212 "Global number of TCP Segment Reassembly Queue Overflows");
214 static void tcp_dooptions(struct tcpopt *, u_char *, int, boolean_t);
215 static void tcp_pulloutofband(struct socket *,
216 struct tcphdr *, struct mbuf *, int);
217 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
219 static void tcp_xmit_timer(struct tcpcb *, int);
220 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *, int);
221 static void tcp_sack_rexmt(struct tcpcb *, struct tcphdr *);
223 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
225 #define ND6_HINT(tp) \
227 if ((tp) && (tp)->t_inpcb && \
228 ((tp)->t_inpcb->inp_vflag & INP_IPV6) && \
229 (tp)->t_inpcb->in6p_route.ro_rt) \
230 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
237 * Indicate whether this ack should be delayed. We can delay the ack if
238 * - delayed acks are enabled and
239 * - there is no delayed ack timer in progress and
240 * - our last ack wasn't a 0-sized window. We never want to delay
241 * the ack that opens up a 0-sized window.
243 #define DELAY_ACK(tp) \
244 (tcp_delack_enabled && !callout_pending(tp->tt_delack) && \
245 !(tp->t_flags & TF_RXWIN0SENT))
247 #define acceptable_window_update(tp, th, tiwin) \
248 (SEQ_LT(tp->snd_wl1, th->th_seq) || \
249 (tp->snd_wl1 == th->th_seq && \
250 (SEQ_LT(tp->snd_wl2, th->th_ack) || \
251 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))
254 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
257 struct tseg_qent *p = NULL;
258 struct tseg_qent *te;
259 struct socket *so = tp->t_inpcb->inp_socket;
263 * Call with th == NULL after become established to
264 * force pre-ESTABLISHED data up to user socket.
270 * Limit the number of segments in the reassembly queue to prevent
271 * holding on to too many segments (and thus running out of mbufs).
272 * Make sure to let the missing segment through which caused this
273 * queue. Always keep one global queue entry spare to be able to
274 * process the missing segment.
276 if (th->th_seq != tp->rcv_nxt &&
277 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
278 tcp_reass_overflows++;
279 tcpstat.tcps_rcvmemdrop++;
281 /* no SACK block to report */
282 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
286 /* Allocate a new queue entry. */
287 MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
288 M_INTWAIT | M_NULLOK);
290 tcpstat.tcps_rcvmemdrop++;
292 /* no SACK block to report */
293 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
299 * Find a segment which begins after this one does.
301 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
302 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
308 * If there is a preceding segment, it may provide some of
309 * our data already. If so, drop the data from the incoming
310 * segment. If it provides all of our data, drop us.
315 /* conversion to int (in i) handles seq wraparound */
316 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
317 if (i > 0) { /* overlaps preceding segment */
318 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
319 /* enclosing block starts w/ preceding segment */
320 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
322 /* preceding encloses incoming segment */
323 tp->encloseblk.rblk_end = p->tqe_th->th_seq +
325 tcpstat.tcps_rcvduppack++;
326 tcpstat.tcps_rcvdupbyte += *tlenp;
331 * Try to present any queued data
332 * at the left window edge to the user.
333 * This is needed after the 3-WHS
336 goto present; /* ??? */
341 /* incoming segment end is enclosing block end */
342 tp->encloseblk.rblk_end = th->th_seq + *tlenp +
343 ((th->th_flags & TH_FIN) != 0);
344 /* trim end of reported D-SACK block */
345 tp->reportblk.rblk_end = th->th_seq;
348 tcpstat.tcps_rcvoopack++;
349 tcpstat.tcps_rcvoobyte += *tlenp;
352 * While we overlap succeeding segments trim them or,
353 * if they are completely covered, dequeue them.
356 tcp_seq_diff_t i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
357 tcp_seq qend = q->tqe_th->th_seq + q->tqe_len;
358 struct tseg_qent *nq;
362 if (!(tp->t_flags & TF_DUPSEG)) { /* first time through */
363 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
364 tp->encloseblk = tp->reportblk;
365 /* report trailing duplicate D-SACK segment */
366 tp->reportblk.rblk_start = q->tqe_th->th_seq;
368 if ((tp->t_flags & TF_ENCLOSESEG) &&
369 SEQ_GT(qend, tp->encloseblk.rblk_end)) {
370 /* extend enclosing block if one exists */
371 tp->encloseblk.rblk_end = qend;
373 if (i < q->tqe_len) {
374 q->tqe_th->th_seq += i;
380 nq = LIST_NEXT(q, tqe_q);
381 LIST_REMOVE(q, tqe_q);
388 /* Insert the new segment queue entry into place. */
391 te->tqe_len = *tlenp;
393 /* check if can coalesce with following segment */
394 if (q != NULL && (th->th_seq + *tlenp == q->tqe_th->th_seq)) {
395 tcp_seq tend = te->tqe_th->th_seq + te->tqe_len;
397 te->tqe_len += q->tqe_len;
398 if (q->tqe_th->th_flags & TH_FIN)
399 te->tqe_th->th_flags |= TH_FIN;
400 m_cat(te->tqe_m, q->tqe_m);
401 tp->encloseblk.rblk_end = tend;
403 * When not reporting a duplicate segment, use
404 * the larger enclosing block as the SACK block.
406 if (!(tp->t_flags & TF_DUPSEG))
407 tp->reportblk.rblk_end = tend;
408 LIST_REMOVE(q, tqe_q);
414 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
416 /* check if can coalesce with preceding segment */
417 if (p->tqe_th->th_seq + p->tqe_len == th->th_seq) {
418 p->tqe_len += te->tqe_len;
419 m_cat(p->tqe_m, te->tqe_m);
420 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
422 * When not reporting a duplicate segment, use
423 * the larger enclosing block as the SACK block.
425 if (!(tp->t_flags & TF_DUPSEG))
426 tp->reportblk.rblk_start = p->tqe_th->th_seq;
430 LIST_INSERT_AFTER(p, te, tqe_q);
435 * Present data to user, advancing rcv_nxt through
436 * completed sequence space.
438 if (!TCPS_HAVEESTABLISHED(tp->t_state))
440 q = LIST_FIRST(&tp->t_segq);
441 if (q == NULL || q->tqe_th->th_seq != tp->rcv_nxt)
443 tp->rcv_nxt += q->tqe_len;
444 if (!(tp->t_flags & TF_DUPSEG)) {
445 /* no SACK block to report since ACK advanced */
446 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
448 /* no enclosing block to report since ACK advanced */
449 tp->t_flags &= ~TF_ENCLOSESEG;
450 flags = q->tqe_th->th_flags & TH_FIN;
451 LIST_REMOVE(q, tqe_q);
452 KASSERT(LIST_EMPTY(&tp->t_segq) ||
453 LIST_FIRST(&tp->t_segq)->tqe_th->th_seq != tp->rcv_nxt,
454 ("segment not coalesced"));
455 if (so->so_state & SS_CANTRCVMORE)
458 ssb_appendstream(&so->so_rcv, q->tqe_m);
467 * TCP input routine, follows pages 65-76 of the
468 * protocol specification dated September, 1981 very closely.
472 tcp6_input(struct mbuf **mp, int *offp, int proto)
474 struct mbuf *m = *mp;
475 struct in6_ifaddr *ia6;
477 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
480 * draft-itojun-ipv6-tcp-to-anycast
481 * better place to put this in?
483 ia6 = ip6_getdstifaddr(m);
484 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
487 ip6 = mtod(m, struct ip6_hdr *);
488 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
489 offsetof(struct ip6_hdr, ip6_dst));
490 return (IPPROTO_DONE);
493 tcp_input(m, *offp, proto);
494 return (IPPROTO_DONE);
499 tcp_input(struct mbuf *m, ...)
504 struct ip *ip = NULL;
506 struct inpcb *inp = NULL;
511 struct tcpcb *tp = NULL;
513 struct socket *so = 0;
515 boolean_t ourfinisacked, needoutput = FALSE;
518 struct tcpopt to; /* options in this segment */
519 struct rmxp_tao *taop; /* pointer to our TAO cache entry */
520 struct rmxp_tao tao_noncached; /* in case there's no cached entry */
521 struct sockaddr_in *next_hop = NULL;
522 int rstreason; /* For badport_bandlim accounting purposes */
524 struct ip6_hdr *ip6 = NULL;
528 const boolean_t isipv6 = FALSE;
535 off0 = __va_arg(ap, int);
536 proto = __va_arg(ap, int);
539 tcpstat.tcps_rcvtotal++;
541 if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
544 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
545 KKASSERT(mtag != NULL);
546 next_hop = m_tag_data(mtag);
550 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
554 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
555 ip6 = mtod(m, struct ip6_hdr *);
556 tlen = (sizeof *ip6) + ntohs(ip6->ip6_plen) - off0;
557 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
558 tcpstat.tcps_rcvbadsum++;
561 th = (struct tcphdr *)((caddr_t)ip6 + off0);
564 * Be proactive about unspecified IPv6 address in source.
565 * As we use all-zero to indicate unbounded/unconnected pcb,
566 * unspecified IPv6 address can be used to confuse us.
568 * Note that packets with unspecified IPv6 destination is
569 * already dropped in ip6_input.
571 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
577 * Get IP and TCP header together in first mbuf.
578 * Note: IP leaves IP header in first mbuf.
580 if (off0 > sizeof(struct ip)) {
582 off0 = sizeof(struct ip);
584 /* already checked and pulled up in ip_demux() */
585 KASSERT(m->m_len >= sizeof(struct tcpiphdr),
586 ("TCP header not in one mbuf: m->m_len %d", m->m_len));
587 ip = mtod(m, struct ip *);
588 ipov = (struct ipovly *)ip;
589 th = (struct tcphdr *)((caddr_t)ip + off0);
592 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
593 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
594 th->th_sum = m->m_pkthdr.csum_data;
596 th->th_sum = in_pseudo(ip->ip_src.s_addr,
598 htonl(m->m_pkthdr.csum_data +
601 th->th_sum ^= 0xffff;
604 * Checksum extended TCP header and data.
606 len = sizeof(struct ip) + tlen;
607 bzero(ipov->ih_x1, sizeof ipov->ih_x1);
608 ipov->ih_len = (u_short)tlen;
609 ipov->ih_len = htons(ipov->ih_len);
610 th->th_sum = in_cksum(m, len);
613 tcpstat.tcps_rcvbadsum++;
617 /* Re-initialization for later version check */
618 ip->ip_v = IPVERSION;
623 * Check that TCP offset makes sense,
624 * pull out TCP options and adjust length. XXX
626 off = th->th_off << 2;
627 /* already checked and pulled up in ip_demux() */
628 KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
629 ("bad TCP data offset %d (tlen %d)", off, tlen));
630 tlen -= off; /* tlen is used instead of ti->ti_len */
631 if (off > sizeof(struct tcphdr)) {
633 IP6_EXTHDR_CHECK(m, off0, off, );
634 ip6 = mtod(m, struct ip6_hdr *);
635 th = (struct tcphdr *)((caddr_t)ip6 + off0);
637 /* already pulled up in ip_demux() */
638 KASSERT(m->m_len >= sizeof(struct ip) + off,
639 ("TCP header and options not in one mbuf: "
640 "m_len %d, off %d", m->m_len, off));
642 optlen = off - sizeof(struct tcphdr);
643 optp = (u_char *)(th + 1);
645 thflags = th->th_flags;
647 #ifdef TCP_DROP_SYNFIN
649 * If the drop_synfin option is enabled, drop all packets with
650 * both the SYN and FIN bits set. This prevents e.g. nmap from
651 * identifying the TCP/IP stack.
653 * This is a violation of the TCP specification.
655 if (drop_synfin && (thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN))
660 * Convert TCP protocol specific fields to host format.
662 th->th_seq = ntohl(th->th_seq);
663 th->th_ack = ntohl(th->th_ack);
664 th->th_win = ntohs(th->th_win);
665 th->th_urp = ntohs(th->th_urp);
668 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
669 * until after ip6_savecontrol() is called and before other functions
670 * which don't want those proto headers.
671 * Because ip6_savecontrol() is going to parse the mbuf to
672 * search for data to be passed up to user-land, it wants mbuf
673 * parameters to be unchanged.
674 * XXX: the call of ip6_savecontrol() has been obsoleted based on
675 * latest version of the advanced API (20020110).
677 drop_hdrlen = off0 + off;
680 * Locate pcb for segment.
683 /* IPFIREWALL_FORWARD section */
684 if (next_hop != NULL && !isipv6) { /* IPv6 support is not there yet */
686 * Transparently forwarded. Pretend to be the destination.
687 * already got one like this?
689 cpu = mycpu->gd_cpuid;
690 inp = in_pcblookup_hash(&tcbinfo[cpu],
691 ip->ip_src, th->th_sport,
692 ip->ip_dst, th->th_dport,
693 0, m->m_pkthdr.rcvif);
696 * It's new. Try to find the ambushing socket.
700 * The rest of the ipfw code stores the port in
702 * (The IP address is still in network order.)
704 in_port_t dport = next_hop->sin_port ?
705 htons(next_hop->sin_port) :
708 cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
709 next_hop->sin_addr.s_addr, dport);
710 inp = in_pcblookup_hash(&tcbinfo[cpu],
711 ip->ip_src, th->th_sport,
712 next_hop->sin_addr, dport,
713 1, m->m_pkthdr.rcvif);
717 inp = in6_pcblookup_hash(&tcbinfo[0],
718 &ip6->ip6_src, th->th_sport,
719 &ip6->ip6_dst, th->th_dport,
720 1, m->m_pkthdr.rcvif);
722 cpu = mycpu->gd_cpuid;
723 inp = in_pcblookup_hash(&tcbinfo[cpu],
724 ip->ip_src, th->th_sport,
725 ip->ip_dst, th->th_dport,
726 1, m->m_pkthdr.rcvif);
731 * If the state is CLOSED (i.e., TCB does not exist) then
732 * all data in the incoming segment is discarded.
733 * If the TCB exists but is in CLOSED state, it is embryonic,
734 * but should either do a listen or a connect soon.
739 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
741 char dbuf[sizeof "aaa.bbb.ccc.ddd"];
742 char sbuf[sizeof "aaa.bbb.ccc.ddd"];
746 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
749 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
752 strcpy(dbuf, inet_ntoa(ip->ip_dst));
753 strcpy(sbuf, inet_ntoa(ip->ip_src));
755 switch (log_in_vain) {
757 if (!(thflags & TH_SYN))
761 "Connection attempt to TCP %s:%d "
762 "from %s:%d flags:0x%02x\n",
763 dbuf, ntohs(th->th_dport), sbuf,
764 ntohs(th->th_sport), thflags);
773 if (thflags & TH_SYN)
782 rstreason = BANDLIM_RST_CLOSEDPORT;
788 if (ipsec6_in_reject_so(m, inp->inp_socket)) {
789 ipsec6stat.in_polvio++;
793 if (ipsec4_in_reject_so(m, inp->inp_socket)) {
794 ipsecstat.in_polvio++;
801 if (ipsec6_in_reject(m, inp))
804 if (ipsec4_in_reject(m, inp))
808 /* Check the minimum TTL for socket. */
810 if ((isipv6 ? ip6->ip6_hlim : ip->ip_ttl) < inp->inp_ip_minttl)
816 rstreason = BANDLIM_RST_CLOSEDPORT;
819 if (tp->t_state <= TCPS_CLOSED)
822 /* Unscale the window into a 32-bit value. */
823 if (!(thflags & TH_SYN))
824 tiwin = th->th_win << tp->snd_scale;
828 so = inp->inp_socket;
831 if (so->so_options & SO_DEBUG) {
832 ostate = tp->t_state;
834 bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
836 bcopy(ip, tcp_saveipgen, sizeof(*ip));
841 bzero(&to, sizeof to);
843 if (so->so_options & SO_ACCEPTCONN) {
844 struct in_conninfo inc;
847 inc.inc_isipv6 = (isipv6 == TRUE);
850 inc.inc6_faddr = ip6->ip6_src;
851 inc.inc6_laddr = ip6->ip6_dst;
852 inc.inc6_route.ro_rt = NULL; /* XXX */
854 inc.inc_faddr = ip->ip_src;
855 inc.inc_laddr = ip->ip_dst;
856 inc.inc_route.ro_rt = NULL; /* XXX */
858 inc.inc_fport = th->th_sport;
859 inc.inc_lport = th->th_dport;
862 * If the state is LISTEN then ignore segment if it contains
863 * a RST. If the segment contains an ACK then it is bad and
864 * send a RST. If it does not contain a SYN then it is not
865 * interesting; drop it.
867 * If the state is SYN_RECEIVED (syncache) and seg contains
868 * an ACK, but not for our SYN/ACK, send a RST. If the seg
869 * contains a RST, check the sequence number to see if it
870 * is a valid reset segment.
872 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
873 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) == TH_ACK) {
874 if (!syncache_expand(&inc, th, &so, m)) {
876 * No syncache entry, or ACK was not
877 * for our SYN/ACK. Send a RST.
879 tcpstat.tcps_badsyn++;
880 rstreason = BANDLIM_RST_OPENPORT;
885 * Could not complete 3-way handshake,
886 * connection is being closed down, and
887 * syncache will free mbuf.
891 * Socket is created in state SYN_RECEIVED.
892 * Continue processing segment.
897 * This is what would have happened in
898 * tcp_output() when the SYN,ACK was sent.
900 tp->snd_up = tp->snd_una;
901 tp->snd_max = tp->snd_nxt = tp->iss + 1;
902 tp->last_ack_sent = tp->rcv_nxt;
904 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
905 * until the _second_ ACK is received:
906 * rcv SYN (set wscale opts) --> send SYN/ACK, set snd_wnd = window.
907 * rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
908 * move to ESTAB, set snd_wnd to tiwin.
910 tp->snd_wnd = tiwin; /* unscaled */
913 if (thflags & TH_RST) {
914 syncache_chkrst(&inc, th);
917 if (thflags & TH_ACK) {
918 syncache_badack(&inc);
919 tcpstat.tcps_badsyn++;
920 rstreason = BANDLIM_RST_OPENPORT;
927 * Segment's flags are (SYN) or (SYN | FIN).
931 * If deprecated address is forbidden,
932 * we do not accept SYN to deprecated interface
933 * address to prevent any new inbound connection from
934 * getting established.
935 * When we do not accept SYN, we send a TCP RST,
936 * with deprecated source address (instead of dropping
937 * it). We compromise it as it is much better for peer
938 * to send a RST, and RST will be the final packet
941 * If we do not forbid deprecated addresses, we accept
942 * the SYN packet. RFC2462 does not suggest dropping
944 * If we decipher RFC2462 5.5.4, it says like this:
945 * 1. use of deprecated addr with existing
946 * communication is okay - "SHOULD continue to be
948 * 2. use of it with new communication:
949 * (2a) "SHOULD NOT be used if alternate address
950 * with sufficient scope is available"
951 * (2b) nothing mentioned otherwise.
952 * Here we fall into (2b) case as we have no choice in
953 * our source address selection - we must obey the peer.
955 * The wording in RFC2462 is confusing, and there are
956 * multiple description text for deprecated address
957 * handling - worse, they are not exactly the same.
958 * I believe 5.5.4 is the best one, so we follow 5.5.4.
960 if (isipv6 && !ip6_use_deprecated) {
961 struct in6_ifaddr *ia6;
963 if ((ia6 = ip6_getdstifaddr(m)) &&
964 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
966 rstreason = BANDLIM_RST_OPENPORT;
972 * If it is from this socket, drop it, it must be forged.
973 * Don't bother responding if the destination was a broadcast.
975 if (th->th_dport == th->th_sport) {
977 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
981 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
986 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
988 * Note that it is quite possible to receive unicast
989 * link-layer packets with a broadcast IP address. Use
990 * in_broadcast() to find them.
992 if (m->m_flags & (M_BCAST | M_MCAST))
995 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
996 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
999 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1000 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1001 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1002 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1006 * SYN appears to be valid; create compressed TCP state
1007 * for syncache, or perform t/tcp connection.
1009 if (so->so_qlen <= so->so_qlimit) {
1010 tcp_dooptions(&to, optp, optlen, TRUE);
1011 if (!syncache_add(&inc, &to, th, &so, m))
1015 * Entry added to syncache, mbuf used to
1016 * send SYN,ACK packet.
1020 * Segment passed TAO tests.
1023 tp = intotcpcb(inp);
1024 tp->snd_wnd = tiwin;
1025 tp->t_starttime = ticks;
1026 tp->t_state = TCPS_ESTABLISHED;
1029 * If there is a FIN, or if there is data and the
1030 * connection is local, then delay SYN,ACK(SYN) in
1031 * the hope of piggy-backing it on a response
1032 * segment. Otherwise must send ACK now in case
1033 * the other side is slow starting.
1035 if (DELAY_ACK(tp) &&
1036 ((thflags & TH_FIN) ||
1038 ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
1039 (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
1040 callout_reset(tp->tt_delack, tcp_delacktime,
1041 tcp_timer_delack, tp);
1042 tp->t_flags |= TF_NEEDSYN;
1044 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1046 tcpstat.tcps_connects++;
1054 /* should not happen - syncache should pick up these connections */
1055 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN state"));
1058 * Segment received on connection.
1059 * Reset idle time and keep-alive timer.
1061 tp->t_rcvtime = ticks;
1062 if (TCPS_HAVEESTABLISHED(tp->t_state))
1063 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
1067 * XXX this is tradtitional behavior, may need to be cleaned up.
1069 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0);
1070 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1071 if (to.to_flags & TOF_SCALE) {
1072 tp->t_flags |= TF_RCVD_SCALE;
1073 tp->requested_s_scale = to.to_requested_s_scale;
1075 if (to.to_flags & TOF_TS) {
1076 tp->t_flags |= TF_RCVD_TSTMP;
1077 tp->ts_recent = to.to_tsval;
1078 tp->ts_recent_age = ticks;
1080 if (to.to_flags & (TOF_CC | TOF_CCNEW))
1081 tp->t_flags |= TF_RCVD_CC;
1082 if (to.to_flags & TOF_MSS)
1083 tcp_mss(tp, to.to_mss);
1085 * Only set the TF_SACK_PERMITTED per-connection flag
1086 * if we got a SACK_PERMITTED option from the other side
1087 * and the global tcp_do_sack variable is true.
1089 if (tcp_do_sack && (to.to_flags & TOF_SACK_PERMITTED))
1090 tp->t_flags |= TF_SACK_PERMITTED;
1094 * Header prediction: check for the two common cases
1095 * of a uni-directional data xfer. If the packet has
1096 * no control flags, is in-sequence, the window didn't
1097 * change and we're not retransmitting, it's a
1098 * candidate. If the length is zero and the ack moved
1099 * forward, we're the sender side of the xfer. Just
1100 * free the data acked & wake any higher level process
1101 * that was blocked waiting for space. If the length
1102 * is non-zero and the ack didn't move, we're the
1103 * receiver side. If we're getting packets in-order
1104 * (the reassembly queue is empty), add the data to
1105 * the socket buffer and note that we need a delayed ack.
1106 * Make sure that the hidden state-flags are also off.
1107 * Since we check for TCPS_ESTABLISHED above, it can only
1110 if (tp->t_state == TCPS_ESTABLISHED &&
1111 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1112 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1113 (!(to.to_flags & TOF_TS) ||
1114 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1116 * Using the CC option is compulsory if once started:
1117 * the segment is OK if no T/TCP was negotiated or
1118 * if the segment has a CC option equal to CCrecv
1120 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
1121 ((to.to_flags & TOF_CC) && to.to_cc == tp->cc_recv)) &&
1122 th->th_seq == tp->rcv_nxt &&
1123 tp->snd_nxt == tp->snd_max) {
1126 * If last ACK falls within this segment's sequence numbers,
1127 * record the timestamp.
1128 * NOTE that the test is modified according to the latest
1129 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1131 if ((to.to_flags & TOF_TS) &&
1132 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1133 tp->ts_recent_age = ticks;
1134 tp->ts_recent = to.to_tsval;
1138 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1139 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1140 tp->snd_cwnd >= tp->snd_wnd &&
1141 !IN_FASTRECOVERY(tp)) {
1143 * This is a pure ack for outstanding data.
1145 ++tcpstat.tcps_predack;
1147 * "bad retransmit" recovery
1149 * If Eifel detection applies, then
1150 * it is deterministic, so use it
1151 * unconditionally over the old heuristic.
1152 * Otherwise, fall back to the old heuristic.
1154 if (tcp_do_eifel_detect &&
1155 (to.to_flags & TOF_TS) && to.to_tsecr &&
1156 (tp->t_flags & TF_FIRSTACCACK)) {
1157 /* Eifel detection applicable. */
1158 if (to.to_tsecr < tp->t_rexmtTS) {
1159 tcp_revert_congestion_state(tp);
1160 ++tcpstat.tcps_eifeldetected;
1162 } else if (tp->t_rxtshift == 1 &&
1163 ticks < tp->t_badrxtwin) {
1164 tcp_revert_congestion_state(tp);
1165 ++tcpstat.tcps_rttdetected;
1167 tp->t_flags &= ~(TF_FIRSTACCACK |
1168 TF_FASTREXMT | TF_EARLYREXMT);
1170 * Recalculate the retransmit timer / rtt.
1172 * Some machines (certain windows boxes)
1173 * send broken timestamp replies during the
1174 * SYN+ACK phase, ignore timestamps of 0.
1176 if ((to.to_flags & TOF_TS) && to.to_tsecr) {
1178 ticks - to.to_tsecr + 1);
1179 } else if (tp->t_rtttime &&
1180 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1182 ticks - tp->t_rtttime);
1184 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1185 acked = th->th_ack - tp->snd_una;
1186 tcpstat.tcps_rcvackpack++;
1187 tcpstat.tcps_rcvackbyte += acked;
1188 sbdrop(&so->so_snd.sb, acked);
1189 tp->snd_recover = th->th_ack - 1;
1190 tp->snd_una = th->th_ack;
1193 * Update window information.
1195 if (tiwin != tp->snd_wnd &&
1196 acceptable_window_update(tp, th, tiwin)) {
1197 /* keep track of pure window updates */
1198 if (tp->snd_wl2 == th->th_ack &&
1199 tiwin > tp->snd_wnd)
1200 tcpstat.tcps_rcvwinupd++;
1201 tp->snd_wnd = tiwin;
1202 tp->snd_wl1 = th->th_seq;
1203 tp->snd_wl2 = th->th_ack;
1204 if (tp->snd_wnd > tp->max_sndwnd)
1205 tp->max_sndwnd = tp->snd_wnd;
1208 ND6_HINT(tp); /* some progress has been done */
1210 * If all outstanding data are acked, stop
1211 * retransmit timer, otherwise restart timer
1212 * using current (possibly backed-off) value.
1213 * If process is waiting for space,
1214 * wakeup/selwakeup/signal. If data
1215 * are ready to send, let tcp_output
1216 * decide between more output or persist.
1218 if (tp->snd_una == tp->snd_max)
1219 callout_stop(tp->tt_rexmt);
1220 else if (!callout_active(tp->tt_persist))
1221 callout_reset(tp->tt_rexmt,
1223 tcp_timer_rexmt, tp);
1225 if (so->so_snd.ssb_cc > 0)
1229 } else if (tiwin == tp->snd_wnd &&
1230 th->th_ack == tp->snd_una &&
1231 LIST_EMPTY(&tp->t_segq) &&
1232 tlen <= ssb_space(&so->so_rcv)) {
1234 * This is a pure, in-sequence data packet
1235 * with nothing on the reassembly queue and
1236 * we have enough buffer space to take it.
1238 ++tcpstat.tcps_preddat;
1239 tp->rcv_nxt += tlen;
1240 tcpstat.tcps_rcvpack++;
1241 tcpstat.tcps_rcvbyte += tlen;
1242 ND6_HINT(tp); /* some progress has been done */
1244 * Add data to socket buffer.
1246 if (so->so_state & SS_CANTRCVMORE) {
1249 m_adj(m, drop_hdrlen); /* delayed header drop */
1250 ssb_appendstream(&so->so_rcv, m);
1254 * This code is responsible for most of the ACKs
1255 * the TCP stack sends back after receiving a data
1256 * packet. Note that the DELAY_ACK check fails if
1257 * the delack timer is already running, which results
1258 * in an ack being sent every other packet (which is
1261 * We then further aggregate acks by not actually
1262 * sending one until the protocol thread has completed
1263 * processing the current backlog of packets. This
1264 * does not delay the ack any further, but allows us
1265 * to take advantage of the packet aggregation that
1266 * high speed NICs do (usually blocks of 8-10 packets)
1267 * to send a single ack rather then four or five acks,
1268 * greatly reducing the ack rate, the return channel
1269 * bandwidth, and the protocol overhead on both ends.
1271 * Since this also has the effect of slowing down
1272 * the exponential slow-start ramp-up, systems with
1273 * very large bandwidth-delay products might want
1274 * to turn the feature off.
1276 if (DELAY_ACK(tp)) {
1277 callout_reset(tp->tt_delack, tcp_delacktime,
1278 tcp_timer_delack, tp);
1279 } else if (tcp_aggregate_acks) {
1280 tp->t_flags |= TF_ACKNOW;
1281 if (!(tp->t_flags & TF_ONOUTPUTQ)) {
1282 tp->t_flags |= TF_ONOUTPUTQ;
1283 tp->tt_cpu = mycpu->gd_cpuid;
1285 &tcpcbackq[tp->tt_cpu],
1289 tp->t_flags |= TF_ACKNOW;
1297 * Calculate amount of space in receive window,
1298 * and then do TCP input processing.
1299 * Receive window is amount of space in rcv queue,
1300 * but not less than advertised window.
1302 recvwin = ssb_space(&so->so_rcv);
1305 tp->rcv_wnd = imax(recvwin, (int)(tp->rcv_adv - tp->rcv_nxt));
1307 switch (tp->t_state) {
1309 * If the state is SYN_RECEIVED:
1310 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1312 case TCPS_SYN_RECEIVED:
1313 if ((thflags & TH_ACK) &&
1314 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1315 SEQ_GT(th->th_ack, tp->snd_max))) {
1316 rstreason = BANDLIM_RST_OPENPORT;
1322 * If the state is SYN_SENT:
1323 * if seg contains an ACK, but not for our SYN, drop the input.
1324 * if seg contains a RST, then drop the connection.
1325 * if seg does not contain SYN, then drop it.
1326 * Otherwise this is an acceptable SYN segment
1327 * initialize tp->rcv_nxt and tp->irs
1328 * if seg contains ack then advance tp->snd_una
1329 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1330 * arrange for segment to be acked (eventually)
1331 * continue processing rest of data/controls, beginning with URG
1334 if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1335 taop = &tao_noncached;
1336 bzero(taop, sizeof *taop);
1339 if ((thflags & TH_ACK) &&
1340 (SEQ_LEQ(th->th_ack, tp->iss) ||
1341 SEQ_GT(th->th_ack, tp->snd_max))) {
1343 * If we have a cached CCsent for the remote host,
1344 * hence we haven't just crashed and restarted,
1345 * do not send a RST. This may be a retransmission
1346 * from the other side after our earlier ACK was lost.
1347 * Our new SYN, when it arrives, will serve as the
1350 if (taop->tao_ccsent != 0)
1353 rstreason = BANDLIM_UNLIMITED;
1357 if (thflags & TH_RST) {
1358 if (thflags & TH_ACK)
1359 tp = tcp_drop(tp, ECONNREFUSED);
1362 if (!(thflags & TH_SYN))
1364 tp->snd_wnd = th->th_win; /* initial send window */
1365 tp->cc_recv = to.to_cc; /* foreign CC */
1367 tp->irs = th->th_seq;
1369 if (thflags & TH_ACK) {
1371 * Our SYN was acked. If segment contains CC.ECHO
1372 * option, check it to make sure this segment really
1373 * matches our SYN. If not, just drop it as old
1374 * duplicate, but send an RST if we're still playing
1375 * by the old rules. If no CC.ECHO option, make sure
1376 * we don't get fooled into using T/TCP.
1378 if (to.to_flags & TOF_CCECHO) {
1379 if (tp->cc_send != to.to_ccecho) {
1380 if (taop->tao_ccsent != 0)
1383 rstreason = BANDLIM_UNLIMITED;
1388 tp->t_flags &= ~TF_RCVD_CC;
1389 tcpstat.tcps_connects++;
1391 /* Do window scaling on this connection? */
1392 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1393 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1394 tp->snd_scale = tp->requested_s_scale;
1395 tp->rcv_scale = tp->request_r_scale;
1397 /* Segment is acceptable, update cache if undefined. */
1398 if (taop->tao_ccsent == 0)
1399 taop->tao_ccsent = to.to_ccecho;
1401 tp->rcv_adv += tp->rcv_wnd;
1402 tp->snd_una++; /* SYN is acked */
1403 callout_stop(tp->tt_rexmt);
1405 * If there's data, delay ACK; if there's also a FIN
1406 * ACKNOW will be turned on later.
1408 if (DELAY_ACK(tp) && tlen != 0)
1409 callout_reset(tp->tt_delack, tcp_delacktime,
1410 tcp_timer_delack, tp);
1412 tp->t_flags |= TF_ACKNOW;
1414 * Received <SYN,ACK> in SYN_SENT[*] state.
1416 * SYN_SENT --> ESTABLISHED
1417 * SYN_SENT* --> FIN_WAIT_1
1419 tp->t_starttime = ticks;
1420 if (tp->t_flags & TF_NEEDFIN) {
1421 tp->t_state = TCPS_FIN_WAIT_1;
1422 tp->t_flags &= ~TF_NEEDFIN;
1425 tp->t_state = TCPS_ESTABLISHED;
1426 callout_reset(tp->tt_keep, tcp_keepidle,
1427 tcp_timer_keep, tp);
1431 * Received initial SYN in SYN-SENT[*] state =>
1432 * simultaneous open. If segment contains CC option
1433 * and there is a cached CC, apply TAO test.
1434 * If it succeeds, connection is * half-synchronized.
1435 * Otherwise, do 3-way handshake:
1436 * SYN-SENT -> SYN-RECEIVED
1437 * SYN-SENT* -> SYN-RECEIVED*
1438 * If there was no CC option, clear cached CC value.
1440 tp->t_flags |= TF_ACKNOW;
1441 callout_stop(tp->tt_rexmt);
1442 if (to.to_flags & TOF_CC) {
1443 if (taop->tao_cc != 0 &&
1444 CC_GT(to.to_cc, taop->tao_cc)) {
1446 * update cache and make transition:
1447 * SYN-SENT -> ESTABLISHED*
1448 * SYN-SENT* -> FIN-WAIT-1*
1450 taop->tao_cc = to.to_cc;
1451 tp->t_starttime = ticks;
1452 if (tp->t_flags & TF_NEEDFIN) {
1453 tp->t_state = TCPS_FIN_WAIT_1;
1454 tp->t_flags &= ~TF_NEEDFIN;
1456 tp->t_state = TCPS_ESTABLISHED;
1457 callout_reset(tp->tt_keep,
1462 tp->t_flags |= TF_NEEDSYN;
1464 tp->t_state = TCPS_SYN_RECEIVED;
1466 /* CC.NEW or no option => invalidate cache */
1468 tp->t_state = TCPS_SYN_RECEIVED;
1474 * Advance th->th_seq to correspond to first data byte.
1475 * If data, trim to stay within window,
1476 * dropping FIN if necessary.
1479 if (tlen > tp->rcv_wnd) {
1480 todrop = tlen - tp->rcv_wnd;
1484 tcpstat.tcps_rcvpackafterwin++;
1485 tcpstat.tcps_rcvbyteafterwin += todrop;
1487 tp->snd_wl1 = th->th_seq - 1;
1488 tp->rcv_up = th->th_seq;
1490 * Client side of transaction: already sent SYN and data.
1491 * If the remote host used T/TCP to validate the SYN,
1492 * our data will be ACK'd; if so, enter normal data segment
1493 * processing in the middle of step 5, ack processing.
1494 * Otherwise, goto step 6.
1496 if (thflags & TH_ACK)
1502 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1503 * if segment contains a SYN and CC [not CC.NEW] option:
1504 * if state == TIME_WAIT and connection duration > MSL,
1505 * drop packet and send RST;
1507 * if SEG.CC > CCrecv then is new SYN, and can implicitly
1508 * ack the FIN (and data) in retransmission queue.
1509 * Complete close and delete TCPCB. Then reprocess
1510 * segment, hoping to find new TCPCB in LISTEN state;
1512 * else must be old SYN; drop it.
1513 * else do normal processing.
1517 case TCPS_TIME_WAIT:
1518 if ((thflags & TH_SYN) &&
1519 (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1520 if (tp->t_state == TCPS_TIME_WAIT &&
1521 (ticks - tp->t_starttime) > tcp_msl) {
1522 rstreason = BANDLIM_UNLIMITED;
1525 if (CC_GT(to.to_cc, tp->cc_recv)) {
1532 break; /* continue normal processing */
1536 * States other than LISTEN or SYN_SENT.
1537 * First check the RST flag and sequence number since reset segments
1538 * are exempt from the timestamp and connection count tests. This
1539 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1540 * below which allowed reset segments in half the sequence space
1541 * to fall though and be processed (which gives forged reset
1542 * segments with a random sequence number a 50 percent chance of
1543 * killing a connection).
1544 * Then check timestamp, if present.
1545 * Then check the connection count, if present.
1546 * Then check that at least some bytes of segment are within
1547 * receive window. If segment begins before rcv_nxt,
1548 * drop leading data (and SYN); if nothing left, just ack.
1551 * If the RST bit is set, check the sequence number to see
1552 * if this is a valid reset segment.
1554 * In all states except SYN-SENT, all reset (RST) segments
1555 * are validated by checking their SEQ-fields. A reset is
1556 * valid if its sequence number is in the window.
1557 * Note: this does not take into account delayed ACKs, so
1558 * we should test against last_ack_sent instead of rcv_nxt.
1559 * The sequence number in the reset segment is normally an
1560 * echo of our outgoing acknowledgement numbers, but some hosts
1561 * send a reset with the sequence number at the rightmost edge
1562 * of our receive window, and we have to handle this case.
1563 * If we have multiple segments in flight, the intial reset
1564 * segment sequence numbers will be to the left of last_ack_sent,
1565 * but they will eventually catch up.
1566 * In any case, it never made sense to trim reset segments to
1567 * fit the receive window since RFC 1122 says:
1568 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1570 * A TCP SHOULD allow a received RST segment to include data.
1573 * It has been suggested that a RST segment could contain
1574 * ASCII text that encoded and explained the cause of the
1575 * RST. No standard has yet been established for such
1578 * If the reset segment passes the sequence number test examine
1580 * SYN_RECEIVED STATE:
1581 * If passive open, return to LISTEN state.
1582 * If active open, inform user that connection was refused.
1583 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1584 * Inform user that connection was reset, and close tcb.
1585 * CLOSING, LAST_ACK STATES:
1588 * Drop the segment - see Stevens, vol. 2, p. 964 and
1591 if (thflags & TH_RST) {
1592 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1593 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1594 switch (tp->t_state) {
1596 case TCPS_SYN_RECEIVED:
1597 so->so_error = ECONNREFUSED;
1600 case TCPS_ESTABLISHED:
1601 case TCPS_FIN_WAIT_1:
1602 case TCPS_FIN_WAIT_2:
1603 case TCPS_CLOSE_WAIT:
1604 so->so_error = ECONNRESET;
1606 tp->t_state = TCPS_CLOSED;
1607 tcpstat.tcps_drops++;
1616 case TCPS_TIME_WAIT:
1624 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1625 * and it's less than ts_recent, drop it.
1627 if ((to.to_flags & TOF_TS) && tp->ts_recent != 0 &&
1628 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1630 /* Check to see if ts_recent is over 24 days old. */
1631 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1633 * Invalidate ts_recent. If this segment updates
1634 * ts_recent, the age will be reset later and ts_recent
1635 * will get a valid value. If it does not, setting
1636 * ts_recent to zero will at least satisfy the
1637 * requirement that zero be placed in the timestamp
1638 * echo reply when ts_recent isn't valid. The
1639 * age isn't reset until we get a valid ts_recent
1640 * because we don't want out-of-order segments to be
1641 * dropped when ts_recent is old.
1645 tcpstat.tcps_rcvduppack++;
1646 tcpstat.tcps_rcvdupbyte += tlen;
1647 tcpstat.tcps_pawsdrop++;
1656 * If T/TCP was negotiated and the segment doesn't have CC,
1657 * or if its CC is wrong then drop the segment.
1658 * RST segments do not have to comply with this.
1660 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1661 (!(to.to_flags & TOF_CC) || tp->cc_recv != to.to_cc))
1665 * In the SYN-RECEIVED state, validate that the packet belongs to
1666 * this connection before trimming the data to fit the receive
1667 * window. Check the sequence number versus IRS since we know
1668 * the sequence numbers haven't wrapped. This is a partial fix
1669 * for the "LAND" DoS attack.
1671 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1672 rstreason = BANDLIM_RST_OPENPORT;
1676 todrop = tp->rcv_nxt - th->th_seq;
1678 if (TCP_DO_SACK(tp)) {
1679 /* Report duplicate segment at head of packet. */
1680 tp->reportblk.rblk_start = th->th_seq;
1681 tp->reportblk.rblk_end = th->th_seq + tlen;
1682 if (thflags & TH_FIN)
1683 ++tp->reportblk.rblk_end;
1684 if (SEQ_GT(tp->reportblk.rblk_end, tp->rcv_nxt))
1685 tp->reportblk.rblk_end = tp->rcv_nxt;
1686 tp->t_flags |= (TF_DUPSEG | TF_SACKLEFT | TF_ACKNOW);
1688 if (thflags & TH_SYN) {
1698 * Following if statement from Stevens, vol. 2, p. 960.
1700 if (todrop > tlen ||
1701 (todrop == tlen && !(thflags & TH_FIN))) {
1703 * Any valid FIN must be to the left of the window.
1704 * At this point the FIN must be a duplicate or out
1705 * of sequence; drop it.
1710 * Send an ACK to resynchronize and drop any data.
1711 * But keep on processing for RST or ACK.
1713 tp->t_flags |= TF_ACKNOW;
1715 tcpstat.tcps_rcvduppack++;
1716 tcpstat.tcps_rcvdupbyte += todrop;
1718 tcpstat.tcps_rcvpartduppack++;
1719 tcpstat.tcps_rcvpartdupbyte += todrop;
1721 drop_hdrlen += todrop; /* drop from the top afterwards */
1722 th->th_seq += todrop;
1724 if (th->th_urp > todrop)
1725 th->th_urp -= todrop;
1733 * If new data are received on a connection after the
1734 * user processes are gone, then RST the other end.
1736 if ((so->so_state & SS_NOFDREF) &&
1737 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1739 tcpstat.tcps_rcvafterclose++;
1740 rstreason = BANDLIM_UNLIMITED;
1745 * If segment ends after window, drop trailing data
1746 * (and PUSH and FIN); if nothing left, just ACK.
1748 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1750 tcpstat.tcps_rcvpackafterwin++;
1751 if (todrop >= tlen) {
1752 tcpstat.tcps_rcvbyteafterwin += tlen;
1754 * If a new connection request is received
1755 * while in TIME_WAIT, drop the old connection
1756 * and start over if the sequence numbers
1757 * are above the previous ones.
1759 if (thflags & TH_SYN &&
1760 tp->t_state == TCPS_TIME_WAIT &&
1761 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1766 * If window is closed can only take segments at
1767 * window edge, and have to drop data and PUSH from
1768 * incoming segments. Continue processing, but
1769 * remember to ack. Otherwise, drop segment
1772 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1773 tp->t_flags |= TF_ACKNOW;
1774 tcpstat.tcps_rcvwinprobe++;
1778 tcpstat.tcps_rcvbyteafterwin += todrop;
1781 thflags &= ~(TH_PUSH | TH_FIN);
1785 * If last ACK falls within this segment's sequence numbers,
1786 * record its timestamp.
1788 * 1) That the test incorporates suggestions from the latest
1789 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1790 * 2) That updating only on newer timestamps interferes with
1791 * our earlier PAWS tests, so this check should be solely
1792 * predicated on the sequence space of this segment.
1793 * 3) That we modify the segment boundary check to be
1794 * Last.ACK.Sent <= SEG.SEQ + SEG.LEN
1795 * instead of RFC1323's
1796 * Last.ACK.Sent < SEG.SEQ + SEG.LEN,
1797 * This modified check allows us to overcome RFC1323's
1798 * limitations as described in Stevens TCP/IP Illustrated
1799 * Vol. 2 p.869. In such cases, we can still calculate the
1800 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1802 if ((to.to_flags & TOF_TS) && SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1803 SEQ_LEQ(tp->last_ack_sent, (th->th_seq + tlen
1804 + ((thflags & TH_SYN) != 0)
1805 + ((thflags & TH_FIN) != 0)))) {
1806 tp->ts_recent_age = ticks;
1807 tp->ts_recent = to.to_tsval;
1811 * If a SYN is in the window, then this is an
1812 * error and we send an RST and drop the connection.
1814 if (thflags & TH_SYN) {
1815 tp = tcp_drop(tp, ECONNRESET);
1816 rstreason = BANDLIM_UNLIMITED;
1821 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1822 * flag is on (half-synchronized state), then queue data for
1823 * later processing; else drop segment and return.
1825 if (!(thflags & TH_ACK)) {
1826 if (tp->t_state == TCPS_SYN_RECEIVED ||
1827 (tp->t_flags & TF_NEEDSYN))
1836 switch (tp->t_state) {
1838 * In SYN_RECEIVED state, the ACK acknowledges our SYN, so enter
1839 * ESTABLISHED state and continue processing.
1840 * The ACK was checked above.
1842 case TCPS_SYN_RECEIVED:
1844 tcpstat.tcps_connects++;
1846 /* Do window scaling? */
1847 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1848 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1849 tp->snd_scale = tp->requested_s_scale;
1850 tp->rcv_scale = tp->request_r_scale;
1853 * Upon successful completion of 3-way handshake,
1854 * update cache.CC if it was undefined, pass any queued
1855 * data to the user, and advance state appropriately.
1857 if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1859 taop->tao_cc = tp->cc_recv;
1863 * SYN-RECEIVED -> ESTABLISHED
1864 * SYN-RECEIVED* -> FIN-WAIT-1
1866 tp->t_starttime = ticks;
1867 if (tp->t_flags & TF_NEEDFIN) {
1868 tp->t_state = TCPS_FIN_WAIT_1;
1869 tp->t_flags &= ~TF_NEEDFIN;
1871 tp->t_state = TCPS_ESTABLISHED;
1872 callout_reset(tp->tt_keep, tcp_keepidle,
1873 tcp_timer_keep, tp);
1876 * If segment contains data or ACK, will call tcp_reass()
1877 * later; if not, do so now to pass queued data to user.
1879 if (tlen == 0 && !(thflags & TH_FIN))
1880 tcp_reass(tp, NULL, NULL, NULL);
1884 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1885 * ACKs. If the ack is in the range
1886 * tp->snd_una < th->th_ack <= tp->snd_max
1887 * then advance tp->snd_una to th->th_ack and drop
1888 * data from the retransmission queue. If this ACK reflects
1889 * more up to date window information we update our window information.
1891 case TCPS_ESTABLISHED:
1892 case TCPS_FIN_WAIT_1:
1893 case TCPS_FIN_WAIT_2:
1894 case TCPS_CLOSE_WAIT:
1897 case TCPS_TIME_WAIT:
1899 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1900 if (TCP_DO_SACK(tp))
1901 tcp_sack_update_scoreboard(tp, &to);
1902 if (tlen != 0 || tiwin != tp->snd_wnd) {
1906 tcpstat.tcps_rcvdupack++;
1907 if (!callout_active(tp->tt_rexmt) ||
1908 th->th_ack != tp->snd_una) {
1913 * We have outstanding data (other than
1914 * a window probe), this is a completely
1915 * duplicate ack (ie, window info didn't
1916 * change), the ack is the biggest we've
1917 * seen and we've seen exactly our rexmt
1918 * threshhold of them, so assume a packet
1919 * has been dropped and retransmit it.
1920 * Kludge snd_nxt & the congestion
1921 * window so we send only this one
1924 if (IN_FASTRECOVERY(tp)) {
1925 if (TCP_DO_SACK(tp)) {
1926 /* No artifical cwnd inflation. */
1927 tcp_sack_rexmt(tp, th);
1930 * Dup acks mean that packets
1931 * have left the network
1932 * (they're now cached at the
1933 * receiver) so bump cwnd by
1934 * the amount in the receiver
1935 * to keep a constant cwnd
1936 * packets in the network.
1938 tp->snd_cwnd += tp->t_maxseg;
1941 } else if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1944 } else if (++tp->t_dupacks == tcprexmtthresh) {
1945 tcp_seq old_snd_nxt;
1949 if (tcp_do_eifel_detect &&
1950 (tp->t_flags & TF_RCVD_TSTMP)) {
1951 tcp_save_congestion_state(tp);
1952 tp->t_flags |= TF_FASTREXMT;
1955 * We know we're losing at the current
1956 * window size, so do congestion avoidance:
1957 * set ssthresh to half the current window
1958 * and pull our congestion window back to the
1961 win = min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1965 tp->snd_ssthresh = win * tp->t_maxseg;
1966 ENTER_FASTRECOVERY(tp);
1967 tp->snd_recover = tp->snd_max;
1968 callout_stop(tp->tt_rexmt);
1970 old_snd_nxt = tp->snd_nxt;
1971 tp->snd_nxt = th->th_ack;
1972 tp->snd_cwnd = tp->t_maxseg;
1974 ++tcpstat.tcps_sndfastrexmit;
1975 tp->snd_cwnd = tp->snd_ssthresh;
1976 tp->rexmt_high = tp->snd_nxt;
1977 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
1978 tp->snd_nxt = old_snd_nxt;
1979 KASSERT(tp->snd_limited <= 2,
1980 ("tp->snd_limited too big"));
1981 if (TCP_DO_SACK(tp))
1982 tcp_sack_rexmt(tp, th);
1984 tp->snd_cwnd += tp->t_maxseg *
1985 (tp->t_dupacks - tp->snd_limited);
1986 } else if (tcp_do_limitedtransmit) {
1987 u_long oldcwnd = tp->snd_cwnd;
1988 tcp_seq oldsndmax = tp->snd_max;
1989 tcp_seq oldsndnxt = tp->snd_nxt;
1990 /* outstanding data */
1991 uint32_t ownd = tp->snd_max - tp->snd_una;
1994 #define iceildiv(n, d) (((n)+(d)-1) / (d))
1996 KASSERT(tp->t_dupacks == 1 ||
1998 ("dupacks not 1 or 2"));
1999 if (tp->t_dupacks == 1)
2000 tp->snd_limited = 0;
2001 tp->snd_nxt = tp->snd_max;
2002 tp->snd_cwnd = ownd +
2003 (tp->t_dupacks - tp->snd_limited) *
2008 * Other acks may have been processed,
2009 * snd_nxt cannot be reset to a value less
2012 if (SEQ_LT(oldsndnxt, oldsndmax)) {
2013 if (SEQ_GT(oldsndnxt, tp->snd_una))
2014 tp->snd_nxt = oldsndnxt;
2016 tp->snd_nxt = tp->snd_una;
2018 tp->snd_cwnd = oldcwnd;
2019 sent = tp->snd_max - oldsndmax;
2020 if (sent > tp->t_maxseg) {
2021 KASSERT((tp->t_dupacks == 2 &&
2022 tp->snd_limited == 0) ||
2023 (sent == tp->t_maxseg + 1 &&
2024 tp->t_flags & TF_SENTFIN),
2026 KASSERT(sent <= tp->t_maxseg * 2,
2027 ("sent too many segments"));
2028 tp->snd_limited = 2;
2029 tcpstat.tcps_sndlimited += 2;
2030 } else if (sent > 0) {
2032 ++tcpstat.tcps_sndlimited;
2033 } else if (tcp_do_early_retransmit &&
2034 (tcp_do_eifel_detect &&
2035 (tp->t_flags & TF_RCVD_TSTMP)) &&
2036 ownd < 4 * tp->t_maxseg &&
2037 tp->t_dupacks + 1 >=
2038 iceildiv(ownd, tp->t_maxseg) &&
2039 (!TCP_DO_SACK(tp) ||
2040 ownd <= tp->t_maxseg ||
2041 tcp_sack_has_sacked(&tp->scb,
2042 ownd - tp->t_maxseg))) {
2043 ++tcpstat.tcps_sndearlyrexmit;
2044 tp->t_flags |= TF_EARLYREXMT;
2045 goto fastretransmit;
2051 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
2053 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2055 * Detected optimistic ACK attack.
2056 * Force slow-start to de-synchronize attack.
2058 tp->snd_cwnd = tp->t_maxseg;
2061 tcpstat.tcps_rcvacktoomuch++;
2065 * If we reach this point, ACK is not a duplicate,
2066 * i.e., it ACKs something we sent.
2068 if (tp->t_flags & TF_NEEDSYN) {
2070 * T/TCP: Connection was half-synchronized, and our
2071 * SYN has been ACK'd (so connection is now fully
2072 * synchronized). Go to non-starred state,
2073 * increment snd_una for ACK of SYN, and check if
2074 * we can do window scaling.
2076 tp->t_flags &= ~TF_NEEDSYN;
2078 /* Do window scaling? */
2079 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
2080 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
2081 tp->snd_scale = tp->requested_s_scale;
2082 tp->rcv_scale = tp->request_r_scale;
2087 acked = th->th_ack - tp->snd_una;
2088 tcpstat.tcps_rcvackpack++;
2089 tcpstat.tcps_rcvackbyte += acked;
2091 if (tcp_do_eifel_detect && acked > 0 &&
2092 (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
2093 (tp->t_flags & TF_FIRSTACCACK)) {
2094 /* Eifel detection applicable. */
2095 if (to.to_tsecr < tp->t_rexmtTS) {
2096 ++tcpstat.tcps_eifeldetected;
2097 tcp_revert_congestion_state(tp);
2098 if (tp->t_rxtshift == 1 &&
2099 ticks >= tp->t_badrxtwin)
2100 ++tcpstat.tcps_rttcantdetect;
2102 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2104 * If we just performed our first retransmit,
2105 * and the ACK arrives within our recovery window,
2106 * then it was a mistake to do the retransmit
2107 * in the first place. Recover our original cwnd
2108 * and ssthresh, and proceed to transmit where we
2111 tcp_revert_congestion_state(tp);
2112 ++tcpstat.tcps_rttdetected;
2116 * If we have a timestamp reply, update smoothed
2117 * round trip time. If no timestamp is present but
2118 * transmit timer is running and timed sequence
2119 * number was acked, update smoothed round trip time.
2120 * Since we now have an rtt measurement, cancel the
2121 * timer backoff (cf., Phil Karn's retransmit alg.).
2122 * Recompute the initial retransmit timer.
2124 * Some machines (certain windows boxes) send broken
2125 * timestamp replies during the SYN+ACK phase, ignore
2128 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
2129 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2130 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2131 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2132 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2135 * If no data (only SYN) was ACK'd,
2136 * skip rest of ACK processing.
2141 /* Stop looking for an acceptable ACK since one was received. */
2142 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT | TF_EARLYREXMT);
2144 if (acked > so->so_snd.ssb_cc) {
2145 tp->snd_wnd -= so->so_snd.ssb_cc;
2146 sbdrop(&so->so_snd.sb, (int)so->so_snd.ssb_cc);
2147 ourfinisacked = TRUE;
2149 sbdrop(&so->so_snd.sb, acked);
2150 tp->snd_wnd -= acked;
2151 ourfinisacked = FALSE;
2156 * Update window information.
2157 * Don't look at window if no ACK:
2158 * TAC's send garbage on first SYN.
2160 if (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2161 (tp->snd_wl1 == th->th_seq &&
2162 (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2163 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)))) {
2164 /* keep track of pure window updates */
2165 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2166 tiwin > tp->snd_wnd)
2167 tcpstat.tcps_rcvwinupd++;
2168 tp->snd_wnd = tiwin;
2169 tp->snd_wl1 = th->th_seq;
2170 tp->snd_wl2 = th->th_ack;
2171 if (tp->snd_wnd > tp->max_sndwnd)
2172 tp->max_sndwnd = tp->snd_wnd;
2176 tp->snd_una = th->th_ack;
2177 if (TCP_DO_SACK(tp))
2178 tcp_sack_update_scoreboard(tp, &to);
2179 if (IN_FASTRECOVERY(tp)) {
2180 if (SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2181 EXIT_FASTRECOVERY(tp);
2184 * If the congestion window was inflated
2185 * to account for the other side's
2186 * cached packets, retract it.
2188 if (!TCP_DO_SACK(tp))
2189 tp->snd_cwnd = tp->snd_ssthresh;
2192 * Window inflation should have left us
2193 * with approximately snd_ssthresh outstanding
2194 * data. But, in case we would be inclined
2195 * to send a burst, better do it using
2198 if (SEQ_GT(th->th_ack + tp->snd_cwnd,
2199 tp->snd_max + 2 * tp->t_maxseg))
2201 (tp->snd_max - tp->snd_una) +
2206 if (TCP_DO_SACK(tp)) {
2207 tp->snd_max_rexmt = tp->snd_max;
2208 tcp_sack_rexmt(tp, th);
2210 tcp_newreno_partial_ack(tp, th, acked);
2216 * Open the congestion window. When in slow-start,
2217 * open exponentially: maxseg per packet. Otherwise,
2218 * open linearly: maxseg per window.
2220 if (tp->snd_cwnd <= tp->snd_ssthresh) {
2222 (SEQ_LT(tp->snd_nxt, tp->snd_max) ?
2223 tp->t_maxseg : 2 * tp->t_maxseg);
2226 tp->snd_cwnd += tcp_do_abc ?
2227 min(acked, abc_sslimit) : tp->t_maxseg;
2229 /* linear increase */
2230 tp->snd_wacked += tcp_do_abc ? acked :
2232 if (tp->snd_wacked >= tp->snd_cwnd) {
2233 tp->snd_wacked -= tp->snd_cwnd;
2234 tp->snd_cwnd += tp->t_maxseg;
2237 tp->snd_cwnd = min(tp->snd_cwnd,
2238 TCP_MAXWIN << tp->snd_scale);
2239 tp->snd_recover = th->th_ack - 1;
2241 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2242 tp->snd_nxt = tp->snd_una;
2245 * If all outstanding data is acked, stop retransmit
2246 * timer and remember to restart (more output or persist).
2247 * If there is more data to be acked, restart retransmit
2248 * timer, using current (possibly backed-off) value.
2250 if (th->th_ack == tp->snd_max) {
2251 callout_stop(tp->tt_rexmt);
2253 } else if (!callout_active(tp->tt_persist))
2254 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
2255 tcp_timer_rexmt, tp);
2257 switch (tp->t_state) {
2259 * In FIN_WAIT_1 STATE in addition to the processing
2260 * for the ESTABLISHED state if our FIN is now acknowledged
2261 * then enter FIN_WAIT_2.
2263 case TCPS_FIN_WAIT_1:
2264 if (ourfinisacked) {
2266 * If we can't receive any more
2267 * data, then closing user can proceed.
2268 * Starting the timer is contrary to the
2269 * specification, but if we don't get a FIN
2270 * we'll hang forever.
2272 if (so->so_state & SS_CANTRCVMORE) {
2273 soisdisconnected(so);
2274 callout_reset(tp->tt_2msl, tcp_maxidle,
2275 tcp_timer_2msl, tp);
2277 tp->t_state = TCPS_FIN_WAIT_2;
2282 * In CLOSING STATE in addition to the processing for
2283 * the ESTABLISHED state if the ACK acknowledges our FIN
2284 * then enter the TIME-WAIT state, otherwise ignore
2288 if (ourfinisacked) {
2289 tp->t_state = TCPS_TIME_WAIT;
2290 tcp_canceltimers(tp);
2291 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2292 if (tp->cc_recv != 0 &&
2293 (ticks - tp->t_starttime) < tcp_msl)
2294 callout_reset(tp->tt_2msl,
2295 tp->t_rxtcur * TCPTV_TWTRUNC,
2296 tcp_timer_2msl, tp);
2298 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2299 tcp_timer_2msl, tp);
2300 soisdisconnected(so);
2305 * In LAST_ACK, we may still be waiting for data to drain
2306 * and/or to be acked, as well as for the ack of our FIN.
2307 * If our FIN is now acknowledged, delete the TCB,
2308 * enter the closed state and return.
2311 if (ourfinisacked) {
2318 * In TIME_WAIT state the only thing that should arrive
2319 * is a retransmission of the remote FIN. Acknowledge
2320 * it and restart the finack timer.
2322 case TCPS_TIME_WAIT:
2323 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2324 tcp_timer_2msl, tp);
2331 * Update window information.
2332 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2334 if ((thflags & TH_ACK) &&
2335 acceptable_window_update(tp, th, tiwin)) {
2336 /* keep track of pure window updates */
2337 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2338 tiwin > tp->snd_wnd)
2339 tcpstat.tcps_rcvwinupd++;
2340 tp->snd_wnd = tiwin;
2341 tp->snd_wl1 = th->th_seq;
2342 tp->snd_wl2 = th->th_ack;
2343 if (tp->snd_wnd > tp->max_sndwnd)
2344 tp->max_sndwnd = tp->snd_wnd;
2349 * Process segments with URG.
2351 if ((thflags & TH_URG) && th->th_urp &&
2352 !TCPS_HAVERCVDFIN(tp->t_state)) {
2354 * This is a kludge, but if we receive and accept
2355 * random urgent pointers, we'll crash in
2356 * soreceive. It's hard to imagine someone
2357 * actually wanting to send this much urgent data.
2359 if (th->th_urp + so->so_rcv.ssb_cc > sb_max) {
2360 th->th_urp = 0; /* XXX */
2361 thflags &= ~TH_URG; /* XXX */
2362 goto dodata; /* XXX */
2365 * If this segment advances the known urgent pointer,
2366 * then mark the data stream. This should not happen
2367 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2368 * a FIN has been received from the remote side.
2369 * In these states we ignore the URG.
2371 * According to RFC961 (Assigned Protocols),
2372 * the urgent pointer points to the last octet
2373 * of urgent data. We continue, however,
2374 * to consider it to indicate the first octet
2375 * of data past the urgent section as the original
2376 * spec states (in one of two places).
2378 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
2379 tp->rcv_up = th->th_seq + th->th_urp;
2380 so->so_oobmark = so->so_rcv.ssb_cc +
2381 (tp->rcv_up - tp->rcv_nxt) - 1;
2382 if (so->so_oobmark == 0)
2383 so->so_state |= SS_RCVATMARK;
2385 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2388 * Remove out of band data so doesn't get presented to user.
2389 * This can happen independent of advancing the URG pointer,
2390 * but if two URG's are pending at once, some out-of-band
2391 * data may creep in... ick.
2393 if (th->th_urp <= (u_long)tlen &&
2394 !(so->so_options & SO_OOBINLINE)) {
2395 /* hdr drop is delayed */
2396 tcp_pulloutofband(so, th, m, drop_hdrlen);
2400 * If no out of band data is expected,
2401 * pull receive urgent pointer along
2402 * with the receive window.
2404 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2405 tp->rcv_up = tp->rcv_nxt;
2410 * Process the segment text, merging it into the TCP sequencing queue,
2411 * and arranging for acknowledgment of receipt if necessary.
2412 * This process logically involves adjusting tp->rcv_wnd as data
2413 * is presented to the user (this happens in tcp_usrreq.c,
2414 * case PRU_RCVD). If a FIN has already been received on this
2415 * connection then we just ignore the text.
2417 if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
2418 m_adj(m, drop_hdrlen); /* delayed header drop */
2420 * Insert segment which includes th into TCP reassembly queue
2421 * with control block tp. Set thflags to whether reassembly now
2422 * includes a segment with FIN. This handles the common case
2423 * inline (segment is the next to be received on an established
2424 * connection, and the queue is empty), avoiding linkage into
2425 * and removal from the queue and repetition of various
2427 * Set DELACK for segments received in order, but ack
2428 * immediately when segments are out of order (so
2429 * fast retransmit can work).
2431 if (th->th_seq == tp->rcv_nxt &&
2432 LIST_EMPTY(&tp->t_segq) &&
2433 TCPS_HAVEESTABLISHED(tp->t_state)) {
2435 callout_reset(tp->tt_delack, tcp_delacktime,
2436 tcp_timer_delack, tp);
2438 tp->t_flags |= TF_ACKNOW;
2439 tp->rcv_nxt += tlen;
2440 thflags = th->th_flags & TH_FIN;
2441 tcpstat.tcps_rcvpack++;
2442 tcpstat.tcps_rcvbyte += tlen;
2444 if (so->so_state & SS_CANTRCVMORE)
2447 ssb_appendstream(&so->so_rcv, m);
2450 if (!(tp->t_flags & TF_DUPSEG)) {
2451 /* Initialize SACK report block. */
2452 tp->reportblk.rblk_start = th->th_seq;
2453 tp->reportblk.rblk_end = th->th_seq + tlen +
2454 ((thflags & TH_FIN) != 0);
2456 thflags = tcp_reass(tp, th, &tlen, m);
2457 tp->t_flags |= TF_ACKNOW;
2461 * Note the amount of data that peer has sent into
2462 * our window, in order to estimate the sender's
2465 len = so->so_rcv.ssb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2472 * If FIN is received ACK the FIN and let the user know
2473 * that the connection is closing.
2475 if (thflags & TH_FIN) {
2476 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
2479 * If connection is half-synchronized
2480 * (ie NEEDSYN flag on) then delay ACK,
2481 * so it may be piggybacked when SYN is sent.
2482 * Otherwise, since we received a FIN then no
2483 * more input can be expected, send ACK now.
2485 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2486 callout_reset(tp->tt_delack, tcp_delacktime,
2487 tcp_timer_delack, tp);
2489 tp->t_flags |= TF_ACKNOW;
2493 switch (tp->t_state) {
2495 * In SYN_RECEIVED and ESTABLISHED STATES
2496 * enter the CLOSE_WAIT state.
2498 case TCPS_SYN_RECEIVED:
2499 tp->t_starttime = ticks;
2501 case TCPS_ESTABLISHED:
2502 tp->t_state = TCPS_CLOSE_WAIT;
2506 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2507 * enter the CLOSING state.
2509 case TCPS_FIN_WAIT_1:
2510 tp->t_state = TCPS_CLOSING;
2514 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2515 * starting the time-wait timer, turning off the other
2518 case TCPS_FIN_WAIT_2:
2519 tp->t_state = TCPS_TIME_WAIT;
2520 tcp_canceltimers(tp);
2521 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2522 if (tp->cc_recv != 0 &&
2523 (ticks - tp->t_starttime) < tcp_msl) {
2524 callout_reset(tp->tt_2msl,
2525 tp->t_rxtcur * TCPTV_TWTRUNC,
2526 tcp_timer_2msl, tp);
2527 /* For transaction client, force ACK now. */
2528 tp->t_flags |= TF_ACKNOW;
2531 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2532 tcp_timer_2msl, tp);
2533 soisdisconnected(so);
2537 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2539 case TCPS_TIME_WAIT:
2540 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2541 tcp_timer_2msl, tp);
2547 if (so->so_options & SO_DEBUG)
2548 tcp_trace(TA_INPUT, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2552 * Return any desired output.
2554 if (needoutput || (tp->t_flags & TF_ACKNOW))
2560 * Generate an ACK dropping incoming segment if it occupies
2561 * sequence space, where the ACK reflects our state.
2563 * We can now skip the test for the RST flag since all
2564 * paths to this code happen after packets containing
2565 * RST have been dropped.
2567 * In the SYN-RECEIVED state, don't send an ACK unless the
2568 * segment we received passes the SYN-RECEIVED ACK test.
2569 * If it fails send a RST. This breaks the loop in the
2570 * "LAND" DoS attack, and also prevents an ACK storm
2571 * between two listening ports that have been sent forged
2572 * SYN segments, each with the source address of the other.
2574 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2575 (SEQ_GT(tp->snd_una, th->th_ack) ||
2576 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2577 rstreason = BANDLIM_RST_OPENPORT;
2581 if (so->so_options & SO_DEBUG)
2582 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2585 tp->t_flags |= TF_ACKNOW;
2591 * Generate a RST, dropping incoming segment.
2592 * Make ACK acceptable to originator of segment.
2593 * Don't bother to respond if destination was broadcast/multicast.
2595 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
2598 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2599 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2602 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2603 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2604 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2605 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2608 /* IPv6 anycast check is done at tcp6_input() */
2611 * Perform bandwidth limiting.
2614 if (badport_bandlim(rstreason) < 0)
2619 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2620 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2622 if (thflags & TH_ACK)
2623 /* mtod() below is safe as long as hdr dropping is delayed */
2624 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2627 if (thflags & TH_SYN)
2629 /* mtod() below is safe as long as hdr dropping is delayed */
2630 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2631 (tcp_seq)0, TH_RST | TH_ACK);
2637 * Drop space held by incoming segment and return.
2640 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2641 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2648 * Parse TCP options and place in tcpopt.
2651 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn)
2656 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2658 if (opt == TCPOPT_EOL)
2660 if (opt == TCPOPT_NOP)
2666 if (optlen < 2 || optlen > cnt)
2671 if (optlen != TCPOLEN_MAXSEG)
2675 to->to_flags |= TOF_MSS;
2676 bcopy(cp + 2, &to->to_mss, sizeof to->to_mss);
2677 to->to_mss = ntohs(to->to_mss);
2680 if (optlen != TCPOLEN_WINDOW)
2684 to->to_flags |= TOF_SCALE;
2685 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2687 case TCPOPT_TIMESTAMP:
2688 if (optlen != TCPOLEN_TIMESTAMP)
2690 to->to_flags |= TOF_TS;
2691 bcopy(cp + 2, &to->to_tsval, sizeof to->to_tsval);
2692 to->to_tsval = ntohl(to->to_tsval);
2693 bcopy(cp + 6, &to->to_tsecr, sizeof to->to_tsecr);
2694 to->to_tsecr = ntohl(to->to_tsecr);
2696 * If echoed timestamp is later than the current time,
2697 * fall back to non RFC1323 RTT calculation.
2699 if (to->to_tsecr != 0 && TSTMP_GT(to->to_tsecr, ticks))
2703 if (optlen != TCPOLEN_CC)
2705 to->to_flags |= TOF_CC;
2706 bcopy(cp + 2, &to->to_cc, sizeof to->to_cc);
2707 to->to_cc = ntohl(to->to_cc);
2710 if (optlen != TCPOLEN_CC)
2714 to->to_flags |= TOF_CCNEW;
2715 bcopy(cp + 2, &to->to_cc, sizeof to->to_cc);
2716 to->to_cc = ntohl(to->to_cc);
2719 if (optlen != TCPOLEN_CC)
2723 to->to_flags |= TOF_CCECHO;
2724 bcopy(cp + 2, &to->to_ccecho, sizeof to->to_ccecho);
2725 to->to_ccecho = ntohl(to->to_ccecho);
2727 case TCPOPT_SACK_PERMITTED:
2728 if (optlen != TCPOLEN_SACK_PERMITTED)
2732 to->to_flags |= TOF_SACK_PERMITTED;
2735 if ((optlen - 2) & 0x07) /* not multiple of 8 */
2737 to->to_nsackblocks = (optlen - 2) / 8;
2738 to->to_sackblocks = (struct raw_sackblock *) (cp + 2);
2739 to->to_flags |= TOF_SACK;
2740 for (i = 0; i < to->to_nsackblocks; i++) {
2741 struct raw_sackblock *r = &to->to_sackblocks[i];
2743 r->rblk_start = ntohl(r->rblk_start);
2744 r->rblk_end = ntohl(r->rblk_end);
2754 * Pull out of band byte out of a segment so
2755 * it doesn't appear in the user's data queue.
2756 * It is still reflected in the segment length for
2757 * sequencing purposes.
2758 * "off" is the delayed to be dropped hdrlen.
2761 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
2763 int cnt = off + th->th_urp - 1;
2766 if (m->m_len > cnt) {
2767 char *cp = mtod(m, caddr_t) + cnt;
2768 struct tcpcb *tp = sototcpcb(so);
2771 tp->t_oobflags |= TCPOOB_HAVEDATA;
2772 bcopy(cp + 1, cp, m->m_len - cnt - 1);
2774 if (m->m_flags & M_PKTHDR)
2783 panic("tcp_pulloutofband");
2787 * Collect new round-trip time estimate
2788 * and update averages and current timeout.
2791 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2795 tcpstat.tcps_rttupdated++;
2797 if (tp->t_srtt != 0) {
2799 * srtt is stored as fixed point with 5 bits after the
2800 * binary point (i.e., scaled by 8). The following magic
2801 * is equivalent to the smoothing algorithm in rfc793 with
2802 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2803 * point). Adjust rtt to origin 0.
2805 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2806 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2808 if ((tp->t_srtt += delta) <= 0)
2812 * We accumulate a smoothed rtt variance (actually, a
2813 * smoothed mean difference), then set the retransmit
2814 * timer to smoothed rtt + 4 times the smoothed variance.
2815 * rttvar is stored as fixed point with 4 bits after the
2816 * binary point (scaled by 16). The following is
2817 * equivalent to rfc793 smoothing with an alpha of .75
2818 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2819 * rfc793's wired-in beta.
2823 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2824 if ((tp->t_rttvar += delta) <= 0)
2826 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2827 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2830 * No rtt measurement yet - use the unsmoothed rtt.
2831 * Set the variance to half the rtt (so our first
2832 * retransmit happens at 3*rtt).
2834 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2835 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2836 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2842 * the retransmit should happen at rtt + 4 * rttvar.
2843 * Because of the way we do the smoothing, srtt and rttvar
2844 * will each average +1/2 tick of bias. When we compute
2845 * the retransmit timer, we want 1/2 tick of rounding and
2846 * 1 extra tick because of +-1/2 tick uncertainty in the
2847 * firing of the timer. The bias will give us exactly the
2848 * 1.5 tick we need. But, because the bias is
2849 * statistical, we have to test that we don't drop below
2850 * the minimum feasible timer (which is 2 ticks).
2852 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2853 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2856 * We received an ack for a packet that wasn't retransmitted;
2857 * it is probably safe to discard any error indications we've
2858 * received recently. This isn't quite right, but close enough
2859 * for now (a route might have failed after we sent a segment,
2860 * and the return path might not be symmetrical).
2862 tp->t_softerror = 0;
2866 * Determine a reasonable value for maxseg size.
2867 * If the route is known, check route for mtu.
2868 * If none, use an mss that can be handled on the outgoing
2869 * interface without forcing IP to fragment; if bigger than
2870 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2871 * to utilize large mbufs. If no route is found, route has no mtu,
2872 * or the destination isn't local, use a default, hopefully conservative
2873 * size (usually 512 or the default IP max size, but no more than the mtu
2874 * of the interface), as we can't discover anything about intervening
2875 * gateways or networks. We also initialize the congestion/slow start
2876 * window to be a single segment if the destination isn't local.
2877 * While looking at the routing entry, we also initialize other path-dependent
2878 * parameters from pre-set or cached values in the routing entry.
2880 * Also take into account the space needed for options that we
2881 * send regularly. Make maxseg shorter by that amount to assure
2882 * that we can send maxseg amount of data even when the options
2883 * are present. Store the upper limit of the length of options plus
2886 * NOTE that this routine is only called when we process an incoming
2887 * segment, for outgoing segments only tcp_mssopt is called.
2889 * In case of T/TCP, we call this routine during implicit connection
2890 * setup as well (offer = -1), to initialize maxseg from the cached
2894 tcp_mss(struct tcpcb *tp, int offer)
2900 struct inpcb *inp = tp->t_inpcb;
2902 struct rmxp_tao *taop;
2903 int origoffer = offer;
2905 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2906 size_t min_protoh = isipv6 ?
2907 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2908 sizeof(struct tcpiphdr);
2910 const boolean_t isipv6 = FALSE;
2911 const size_t min_protoh = sizeof(struct tcpiphdr);
2915 rt = tcp_rtlookup6(&inp->inp_inc);
2917 rt = tcp_rtlookup(&inp->inp_inc);
2919 tp->t_maxopd = tp->t_maxseg =
2920 (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2924 so = inp->inp_socket;
2926 taop = rmx_taop(rt->rt_rmx);
2928 * Offer == -1 means that we didn't receive SYN yet,
2929 * use cached value in that case;
2932 offer = taop->tao_mssopt;
2934 * Offer == 0 means that there was no MSS on the SYN segment,
2935 * in this case we use tcp_mssdflt.
2938 offer = (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2941 * Sanity check: make sure that maxopd will be large
2942 * enough to allow some data on segments even is the
2943 * all the option space is used (40bytes). Otherwise
2944 * funny things may happen in tcp_output.
2946 offer = max(offer, 64);
2947 taop->tao_mssopt = offer;
2950 * While we're here, check if there's an initial rtt
2951 * or rttvar. Convert from the route-table units
2952 * to scaled multiples of the slow timeout timer.
2954 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2956 * XXX the lock bit for RTT indicates that the value
2957 * is also a minimum value; this is subject to time.
2959 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2960 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2961 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2962 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2963 tcpstat.tcps_usedrtt++;
2964 if (rt->rt_rmx.rmx_rttvar) {
2965 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2966 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2967 tcpstat.tcps_usedrttvar++;
2969 /* default variation is +- 1 rtt */
2971 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2973 TCPT_RANGESET(tp->t_rxtcur,
2974 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2975 tp->t_rttmin, TCPTV_REXMTMAX);
2978 * if there's an mtu associated with the route, use it
2979 * else, use the link mtu.
2981 if (rt->rt_rmx.rmx_mtu)
2982 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2985 mss = ND_IFINFO(rt->rt_ifp)->linkmtu - min_protoh;
2986 if (!in6_localaddr(&inp->in6p_faddr))
2987 mss = min(mss, tcp_v6mssdflt);
2989 mss = ifp->if_mtu - min_protoh;
2990 if (!in_localaddr(inp->inp_faddr))
2991 mss = min(mss, tcp_mssdflt);
2994 mss = min(mss, offer);
2996 * maxopd stores the maximum length of data AND options
2997 * in a segment; maxseg is the amount of data in a normal
2998 * segment. We need to store this value (maxopd) apart
2999 * from maxseg, because now every segment carries options
3000 * and thus we normally have somewhat less data in segments.
3005 * In case of T/TCP, origoffer==-1 indicates, that no segments
3006 * were received yet. In this case we just guess, otherwise
3007 * we do the same as before T/TCP.
3009 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
3011 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3012 mss -= TCPOLEN_TSTAMP_APPA;
3013 if ((tp->t_flags & (TF_REQ_CC | TF_NOOPT)) == TF_REQ_CC &&
3015 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
3016 mss -= TCPOLEN_CC_APPA;
3018 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3020 mss &= ~(MCLBYTES-1);
3023 mss = mss / MCLBYTES * MCLBYTES;
3026 * If there's a pipesize, change the socket buffer
3027 * to that size. Make the socket buffers an integral
3028 * number of mss units; if the mss is larger than
3029 * the socket buffer, decrease the mss.
3032 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
3034 bufsize = so->so_snd.ssb_hiwat;
3038 bufsize = roundup(bufsize, mss);
3039 if (bufsize > sb_max)
3041 if (bufsize > so->so_snd.ssb_hiwat)
3042 ssb_reserve(&so->so_snd, bufsize, so, NULL);
3047 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
3049 bufsize = so->so_rcv.ssb_hiwat;
3050 if (bufsize > mss) {
3051 bufsize = roundup(bufsize, mss);
3052 if (bufsize > sb_max)
3054 if (bufsize > so->so_rcv.ssb_hiwat)
3055 ssb_reserve(&so->so_rcv, bufsize, so, NULL);
3059 * Set the slow-start flight size depending on whether this
3060 * is a local network or not.
3063 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3067 if (rt->rt_rmx.rmx_ssthresh) {
3069 * There's some sort of gateway or interface
3070 * buffer limit on the path. Use this to set
3071 * the slow start threshhold, but set the
3072 * threshold to no less than 2*mss.
3074 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3075 tcpstat.tcps_usedssthresh++;
3080 * Determine the MSS option to send on an outgoing SYN.
3083 tcp_mssopt(struct tcpcb *tp)
3088 ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3089 int min_protoh = isipv6 ?
3090 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
3091 sizeof(struct tcpiphdr);
3093 const boolean_t isipv6 = FALSE;
3094 const size_t min_protoh = sizeof(struct tcpiphdr);
3098 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
3100 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
3102 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3104 return (rt->rt_ifp->if_mtu - min_protoh);
3108 * When a partial ack arrives, force the retransmission of the
3109 * next unacknowledged segment. Do not exit Fast Recovery.
3111 * Implement the Slow-but-Steady variant of NewReno by restarting the
3112 * the retransmission timer. Turn it off here so it can be restarted
3113 * later in tcp_output().
3116 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th, int acked)
3118 tcp_seq old_snd_nxt = tp->snd_nxt;
3119 u_long ocwnd = tp->snd_cwnd;
3121 callout_stop(tp->tt_rexmt);
3123 tp->snd_nxt = th->th_ack;
3124 /* Set snd_cwnd to one segment beyond acknowledged offset. */
3125 tp->snd_cwnd = tp->t_maxseg;
3126 tp->t_flags |= TF_ACKNOW;
3128 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3129 tp->snd_nxt = old_snd_nxt;
3130 /* partial window deflation */
3132 tp->snd_cwnd = ocwnd - acked + tp->t_maxseg;
3134 tp->snd_cwnd = tp->t_maxseg;
3138 * In contrast to the Slow-but-Steady NewReno variant,
3139 * we do not reset the retransmission timer for SACK retransmissions,
3140 * except when retransmitting snd_una.
3143 tcp_sack_rexmt(struct tcpcb *tp, struct tcphdr *th)
3145 uint32_t pipe, seglen;
3148 tcp_seq old_snd_nxt = tp->snd_nxt;
3149 u_long ocwnd = tp->snd_cwnd;
3150 int nseg = 0; /* consecutive new segments */
3151 #define MAXBURST 4 /* limit burst of new packets on partial ack */
3154 pipe = tcp_sack_compute_pipe(tp);
3155 while ((tcp_seq_diff_t)(ocwnd - pipe) >= (tcp_seq_diff_t)tp->t_maxseg &&
3156 (!tcp_do_smartsack || nseg < MAXBURST) &&
3157 tcp_sack_nextseg(tp, &nextrexmt, &seglen, &lostdup)) {
3159 tcp_seq old_snd_max;
3162 if (nextrexmt == tp->snd_max)
3164 tp->snd_nxt = nextrexmt;
3165 tp->snd_cwnd = nextrexmt - tp->snd_una + seglen;
3166 old_snd_max = tp->snd_max;
3167 if (nextrexmt == tp->snd_una)
3168 callout_stop(tp->tt_rexmt);
3169 error = tcp_output(tp);
3172 sent = tp->snd_nxt - nextrexmt;
3177 tcpstat.tcps_sndsackpack++;
3178 tcpstat.tcps_sndsackbyte += sent;
3179 if (SEQ_LT(nextrexmt, old_snd_max) &&
3180 SEQ_LT(tp->rexmt_high, tp->snd_nxt))
3181 tp->rexmt_high = seq_min(tp->snd_nxt, old_snd_max);
3183 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3184 tp->snd_nxt = old_snd_nxt;
3185 tp->snd_cwnd = ocwnd;