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.64 2007/03/04 18:51:59 swildner 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 sbappendstream(&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 /* Grab info from and strip MT_TAG mbufs prepended to the chain. */
542 while (m->m_type == MT_TAG) {
543 if (m->_m_tag_id == PACKET_TAG_IPFORWARD)
544 next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
549 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
553 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
554 ip6 = mtod(m, struct ip6_hdr *);
555 tlen = (sizeof *ip6) + ntohs(ip6->ip6_plen) - off0;
556 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
557 tcpstat.tcps_rcvbadsum++;
560 th = (struct tcphdr *)((caddr_t)ip6 + off0);
563 * Be proactive about unspecified IPv6 address in source.
564 * As we use all-zero to indicate unbounded/unconnected pcb,
565 * unspecified IPv6 address can be used to confuse us.
567 * Note that packets with unspecified IPv6 destination is
568 * already dropped in ip6_input.
570 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
576 * Get IP and TCP header together in first mbuf.
577 * Note: IP leaves IP header in first mbuf.
579 if (off0 > sizeof(struct ip)) {
581 off0 = sizeof(struct ip);
583 /* already checked and pulled up in ip_demux() */
584 KASSERT(m->m_len >= sizeof(struct tcpiphdr),
585 ("TCP header not in one mbuf: m->m_len %d", m->m_len));
586 ip = mtod(m, struct ip *);
587 ipov = (struct ipovly *)ip;
588 th = (struct tcphdr *)((caddr_t)ip + off0);
591 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
592 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
593 th->th_sum = m->m_pkthdr.csum_data;
595 th->th_sum = in_pseudo(ip->ip_src.s_addr,
597 htonl(m->m_pkthdr.csum_data +
600 th->th_sum ^= 0xffff;
603 * Checksum extended TCP header and data.
605 len = sizeof(struct ip) + tlen;
606 bzero(ipov->ih_x1, sizeof ipov->ih_x1);
607 ipov->ih_len = (u_short)tlen;
608 ipov->ih_len = htons(ipov->ih_len);
609 th->th_sum = in_cksum(m, len);
612 tcpstat.tcps_rcvbadsum++;
616 /* Re-initialization for later version check */
617 ip->ip_v = IPVERSION;
622 * Check that TCP offset makes sense,
623 * pull out TCP options and adjust length. XXX
625 off = th->th_off << 2;
626 /* already checked and pulled up in ip_demux() */
627 KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
628 ("bad TCP data offset %d (tlen %d)", off, tlen));
629 tlen -= off; /* tlen is used instead of ti->ti_len */
630 if (off > sizeof(struct tcphdr)) {
632 IP6_EXTHDR_CHECK(m, off0, off, );
633 ip6 = mtod(m, struct ip6_hdr *);
634 th = (struct tcphdr *)((caddr_t)ip6 + off0);
636 /* already pulled up in ip_demux() */
637 KASSERT(m->m_len >= sizeof(struct ip) + off,
638 ("TCP header and options not in one mbuf: "
639 "m_len %d, off %d", m->m_len, off));
641 optlen = off - sizeof(struct tcphdr);
642 optp = (u_char *)(th + 1);
644 thflags = th->th_flags;
646 #ifdef TCP_DROP_SYNFIN
648 * If the drop_synfin option is enabled, drop all packets with
649 * both the SYN and FIN bits set. This prevents e.g. nmap from
650 * identifying the TCP/IP stack.
652 * This is a violation of the TCP specification.
654 if (drop_synfin && (thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN))
659 * Convert TCP protocol specific fields to host format.
661 th->th_seq = ntohl(th->th_seq);
662 th->th_ack = ntohl(th->th_ack);
663 th->th_win = ntohs(th->th_win);
664 th->th_urp = ntohs(th->th_urp);
667 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
668 * until after ip6_savecontrol() is called and before other functions
669 * which don't want those proto headers.
670 * Because ip6_savecontrol() is going to parse the mbuf to
671 * search for data to be passed up to user-land, it wants mbuf
672 * parameters to be unchanged.
673 * XXX: the call of ip6_savecontrol() has been obsoleted based on
674 * latest version of the advanced API (20020110).
676 drop_hdrlen = off0 + off;
679 * Locate pcb for segment.
682 /* IPFIREWALL_FORWARD section */
683 if (next_hop != NULL && !isipv6) { /* IPv6 support is not there yet */
685 * Transparently forwarded. Pretend to be the destination.
686 * already got one like this?
688 cpu = mycpu->gd_cpuid;
689 inp = in_pcblookup_hash(&tcbinfo[cpu],
690 ip->ip_src, th->th_sport,
691 ip->ip_dst, th->th_dport,
692 0, m->m_pkthdr.rcvif);
695 * It's new. Try to find the ambushing socket.
699 * The rest of the ipfw code stores the port in
701 * (The IP address is still in network order.)
703 in_port_t dport = next_hop->sin_port ?
704 htons(next_hop->sin_port) :
707 cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
708 next_hop->sin_addr.s_addr, dport);
709 inp = in_pcblookup_hash(&tcbinfo[cpu],
710 ip->ip_src, th->th_sport,
711 next_hop->sin_addr, dport,
712 1, m->m_pkthdr.rcvif);
716 inp = in6_pcblookup_hash(&tcbinfo[0],
717 &ip6->ip6_src, th->th_sport,
718 &ip6->ip6_dst, th->th_dport,
719 1, m->m_pkthdr.rcvif);
721 cpu = mycpu->gd_cpuid;
722 inp = in_pcblookup_hash(&tcbinfo[cpu],
723 ip->ip_src, th->th_sport,
724 ip->ip_dst, th->th_dport,
725 1, m->m_pkthdr.rcvif);
730 * If the state is CLOSED (i.e., TCB does not exist) then
731 * all data in the incoming segment is discarded.
732 * If the TCB exists but is in CLOSED state, it is embryonic,
733 * but should either do a listen or a connect soon.
738 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
740 char dbuf[sizeof "aaa.bbb.ccc.ddd"];
741 char sbuf[sizeof "aaa.bbb.ccc.ddd"];
745 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
748 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
751 strcpy(dbuf, inet_ntoa(ip->ip_dst));
752 strcpy(sbuf, inet_ntoa(ip->ip_src));
754 switch (log_in_vain) {
756 if (!(thflags & TH_SYN))
760 "Connection attempt to TCP %s:%d "
761 "from %s:%d flags:0x%02x\n",
762 dbuf, ntohs(th->th_dport), sbuf,
763 ntohs(th->th_sport), thflags);
772 if (thflags & TH_SYN)
781 rstreason = BANDLIM_RST_CLOSEDPORT;
787 if (ipsec6_in_reject_so(m, inp->inp_socket)) {
788 ipsec6stat.in_polvio++;
792 if (ipsec4_in_reject_so(m, inp->inp_socket)) {
793 ipsecstat.in_polvio++;
800 if (ipsec6_in_reject(m, inp))
803 if (ipsec4_in_reject(m, inp))
810 rstreason = BANDLIM_RST_CLOSEDPORT;
813 if (tp->t_state <= TCPS_CLOSED)
816 /* Unscale the window into a 32-bit value. */
817 if (!(thflags & TH_SYN))
818 tiwin = th->th_win << tp->snd_scale;
822 so = inp->inp_socket;
825 if (so->so_options & SO_DEBUG) {
826 ostate = tp->t_state;
828 bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
830 bcopy(ip, tcp_saveipgen, sizeof(*ip));
835 bzero(&to, sizeof to);
837 if (so->so_options & SO_ACCEPTCONN) {
838 struct in_conninfo inc;
841 inc.inc_isipv6 = (isipv6 == TRUE);
844 inc.inc6_faddr = ip6->ip6_src;
845 inc.inc6_laddr = ip6->ip6_dst;
846 inc.inc6_route.ro_rt = NULL; /* XXX */
848 inc.inc_faddr = ip->ip_src;
849 inc.inc_laddr = ip->ip_dst;
850 inc.inc_route.ro_rt = NULL; /* XXX */
852 inc.inc_fport = th->th_sport;
853 inc.inc_lport = th->th_dport;
856 * If the state is LISTEN then ignore segment if it contains
857 * a RST. If the segment contains an ACK then it is bad and
858 * send a RST. If it does not contain a SYN then it is not
859 * interesting; drop it.
861 * If the state is SYN_RECEIVED (syncache) and seg contains
862 * an ACK, but not for our SYN/ACK, send a RST. If the seg
863 * contains a RST, check the sequence number to see if it
864 * is a valid reset segment.
866 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
867 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) == TH_ACK) {
868 if (!syncache_expand(&inc, th, &so, m)) {
870 * No syncache entry, or ACK was not
871 * for our SYN/ACK. Send a RST.
873 tcpstat.tcps_badsyn++;
874 rstreason = BANDLIM_RST_OPENPORT;
879 * Could not complete 3-way handshake,
880 * connection is being closed down, and
881 * syncache will free mbuf.
885 * Socket is created in state SYN_RECEIVED.
886 * Continue processing segment.
891 * This is what would have happened in
892 * tcp_output() when the SYN,ACK was sent.
894 tp->snd_up = tp->snd_una;
895 tp->snd_max = tp->snd_nxt = tp->iss + 1;
896 tp->last_ack_sent = tp->rcv_nxt;
898 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
899 * until the _second_ ACK is received:
900 * rcv SYN (set wscale opts) --> send SYN/ACK, set snd_wnd = window.
901 * rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
902 * move to ESTAB, set snd_wnd to tiwin.
904 tp->snd_wnd = tiwin; /* unscaled */
907 if (thflags & TH_RST) {
908 syncache_chkrst(&inc, th);
911 if (thflags & TH_ACK) {
912 syncache_badack(&inc);
913 tcpstat.tcps_badsyn++;
914 rstreason = BANDLIM_RST_OPENPORT;
921 * Segment's flags are (SYN) or (SYN | FIN).
925 * If deprecated address is forbidden,
926 * we do not accept SYN to deprecated interface
927 * address to prevent any new inbound connection from
928 * getting established.
929 * When we do not accept SYN, we send a TCP RST,
930 * with deprecated source address (instead of dropping
931 * it). We compromise it as it is much better for peer
932 * to send a RST, and RST will be the final packet
935 * If we do not forbid deprecated addresses, we accept
936 * the SYN packet. RFC2462 does not suggest dropping
938 * If we decipher RFC2462 5.5.4, it says like this:
939 * 1. use of deprecated addr with existing
940 * communication is okay - "SHOULD continue to be
942 * 2. use of it with new communication:
943 * (2a) "SHOULD NOT be used if alternate address
944 * with sufficient scope is available"
945 * (2b) nothing mentioned otherwise.
946 * Here we fall into (2b) case as we have no choice in
947 * our source address selection - we must obey the peer.
949 * The wording in RFC2462 is confusing, and there are
950 * multiple description text for deprecated address
951 * handling - worse, they are not exactly the same.
952 * I believe 5.5.4 is the best one, so we follow 5.5.4.
954 if (isipv6 && !ip6_use_deprecated) {
955 struct in6_ifaddr *ia6;
957 if ((ia6 = ip6_getdstifaddr(m)) &&
958 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
960 rstreason = BANDLIM_RST_OPENPORT;
966 * If it is from this socket, drop it, it must be forged.
967 * Don't bother responding if the destination was a broadcast.
969 if (th->th_dport == th->th_sport) {
971 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
975 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
980 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
982 * Note that it is quite possible to receive unicast
983 * link-layer packets with a broadcast IP address. Use
984 * in_broadcast() to find them.
986 if (m->m_flags & (M_BCAST | M_MCAST))
989 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
990 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
993 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
994 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
995 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
996 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1000 * SYN appears to be valid; create compressed TCP state
1001 * for syncache, or perform t/tcp connection.
1003 if (so->so_qlen <= so->so_qlimit) {
1004 tcp_dooptions(&to, optp, optlen, TRUE);
1005 if (!syncache_add(&inc, &to, th, &so, m))
1009 * Entry added to syncache, mbuf used to
1010 * send SYN,ACK packet.
1014 * Segment passed TAO tests.
1017 tp = intotcpcb(inp);
1018 tp->snd_wnd = tiwin;
1019 tp->t_starttime = ticks;
1020 tp->t_state = TCPS_ESTABLISHED;
1023 * If there is a FIN, or if there is data and the
1024 * connection is local, then delay SYN,ACK(SYN) in
1025 * the hope of piggy-backing it on a response
1026 * segment. Otherwise must send ACK now in case
1027 * the other side is slow starting.
1029 if (DELAY_ACK(tp) &&
1030 ((thflags & TH_FIN) ||
1032 ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
1033 (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
1034 callout_reset(tp->tt_delack, tcp_delacktime,
1035 tcp_timer_delack, tp);
1036 tp->t_flags |= TF_NEEDSYN;
1038 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1040 tcpstat.tcps_connects++;
1048 /* should not happen - syncache should pick up these connections */
1049 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN state"));
1052 * Segment received on connection.
1053 * Reset idle time and keep-alive timer.
1055 tp->t_rcvtime = ticks;
1056 if (TCPS_HAVEESTABLISHED(tp->t_state))
1057 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
1061 * XXX this is tradtitional behavior, may need to be cleaned up.
1063 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0);
1064 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1065 if (to.to_flags & TOF_SCALE) {
1066 tp->t_flags |= TF_RCVD_SCALE;
1067 tp->requested_s_scale = to.to_requested_s_scale;
1069 if (to.to_flags & TOF_TS) {
1070 tp->t_flags |= TF_RCVD_TSTMP;
1071 tp->ts_recent = to.to_tsval;
1072 tp->ts_recent_age = ticks;
1074 if (to.to_flags & (TOF_CC | TOF_CCNEW))
1075 tp->t_flags |= TF_RCVD_CC;
1076 if (to.to_flags & TOF_MSS)
1077 tcp_mss(tp, to.to_mss);
1079 * Only set the TF_SACK_PERMITTED per-connection flag
1080 * if we got a SACK_PERMITTED option from the other side
1081 * and the global tcp_do_sack variable is true.
1083 if (tcp_do_sack && (to.to_flags & TOF_SACK_PERMITTED))
1084 tp->t_flags |= TF_SACK_PERMITTED;
1088 * Header prediction: check for the two common cases
1089 * of a uni-directional data xfer. If the packet has
1090 * no control flags, is in-sequence, the window didn't
1091 * change and we're not retransmitting, it's a
1092 * candidate. If the length is zero and the ack moved
1093 * forward, we're the sender side of the xfer. Just
1094 * free the data acked & wake any higher level process
1095 * that was blocked waiting for space. If the length
1096 * is non-zero and the ack didn't move, we're the
1097 * receiver side. If we're getting packets in-order
1098 * (the reassembly queue is empty), add the data to
1099 * the socket buffer and note that we need a delayed ack.
1100 * Make sure that the hidden state-flags are also off.
1101 * Since we check for TCPS_ESTABLISHED above, it can only
1104 if (tp->t_state == TCPS_ESTABLISHED &&
1105 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1106 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1107 (!(to.to_flags & TOF_TS) ||
1108 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1110 * Using the CC option is compulsory if once started:
1111 * the segment is OK if no T/TCP was negotiated or
1112 * if the segment has a CC option equal to CCrecv
1114 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
1115 ((to.to_flags & TOF_CC) && to.to_cc == tp->cc_recv)) &&
1116 th->th_seq == tp->rcv_nxt &&
1117 tp->snd_nxt == tp->snd_max) {
1120 * If last ACK falls within this segment's sequence numbers,
1121 * record the timestamp.
1122 * NOTE that the test is modified according to the latest
1123 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1125 if ((to.to_flags & TOF_TS) &&
1126 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1127 tp->ts_recent_age = ticks;
1128 tp->ts_recent = to.to_tsval;
1132 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1133 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1134 tp->snd_cwnd >= tp->snd_wnd &&
1135 !IN_FASTRECOVERY(tp)) {
1137 * This is a pure ack for outstanding data.
1139 ++tcpstat.tcps_predack;
1141 * "bad retransmit" recovery
1143 * If Eifel detection applies, then
1144 * it is deterministic, so use it
1145 * unconditionally over the old heuristic.
1146 * Otherwise, fall back to the old heuristic.
1148 if (tcp_do_eifel_detect &&
1149 (to.to_flags & TOF_TS) && to.to_tsecr &&
1150 (tp->t_flags & TF_FIRSTACCACK)) {
1151 /* Eifel detection applicable. */
1152 if (to.to_tsecr < tp->t_rexmtTS) {
1153 tcp_revert_congestion_state(tp);
1154 ++tcpstat.tcps_eifeldetected;
1156 } else if (tp->t_rxtshift == 1 &&
1157 ticks < tp->t_badrxtwin) {
1158 tcp_revert_congestion_state(tp);
1159 ++tcpstat.tcps_rttdetected;
1161 tp->t_flags &= ~(TF_FIRSTACCACK |
1162 TF_FASTREXMT | TF_EARLYREXMT);
1164 * Recalculate the retransmit timer / rtt.
1166 * Some machines (certain windows boxes)
1167 * send broken timestamp replies during the
1168 * SYN+ACK phase, ignore timestamps of 0.
1170 if ((to.to_flags & TOF_TS) && to.to_tsecr) {
1172 ticks - to.to_tsecr + 1);
1173 } else if (tp->t_rtttime &&
1174 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1176 ticks - tp->t_rtttime);
1178 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1179 acked = th->th_ack - tp->snd_una;
1180 tcpstat.tcps_rcvackpack++;
1181 tcpstat.tcps_rcvackbyte += acked;
1182 sbdrop(&so->so_snd, acked);
1183 tp->snd_recover = th->th_ack - 1;
1184 tp->snd_una = th->th_ack;
1187 * Update window information.
1189 if (tiwin != tp->snd_wnd &&
1190 acceptable_window_update(tp, th, tiwin)) {
1191 /* keep track of pure window updates */
1192 if (tp->snd_wl2 == th->th_ack &&
1193 tiwin > tp->snd_wnd)
1194 tcpstat.tcps_rcvwinupd++;
1195 tp->snd_wnd = tiwin;
1196 tp->snd_wl1 = th->th_seq;
1197 tp->snd_wl2 = th->th_ack;
1198 if (tp->snd_wnd > tp->max_sndwnd)
1199 tp->max_sndwnd = tp->snd_wnd;
1202 ND6_HINT(tp); /* some progress has been done */
1204 * If all outstanding data are acked, stop
1205 * retransmit timer, otherwise restart timer
1206 * using current (possibly backed-off) value.
1207 * If process is waiting for space,
1208 * wakeup/selwakeup/signal. If data
1209 * are ready to send, let tcp_output
1210 * decide between more output or persist.
1212 if (tp->snd_una == tp->snd_max)
1213 callout_stop(tp->tt_rexmt);
1214 else if (!callout_active(tp->tt_persist))
1215 callout_reset(tp->tt_rexmt,
1217 tcp_timer_rexmt, tp);
1219 if (so->so_snd.sb_cc > 0)
1223 } else if (tiwin == tp->snd_wnd &&
1224 th->th_ack == tp->snd_una &&
1225 LIST_EMPTY(&tp->t_segq) &&
1226 tlen <= sbspace(&so->so_rcv)) {
1228 * This is a pure, in-sequence data packet
1229 * with nothing on the reassembly queue and
1230 * we have enough buffer space to take it.
1232 ++tcpstat.tcps_preddat;
1233 tp->rcv_nxt += tlen;
1234 tcpstat.tcps_rcvpack++;
1235 tcpstat.tcps_rcvbyte += tlen;
1236 ND6_HINT(tp); /* some progress has been done */
1238 * Add data to socket buffer.
1240 if (so->so_state & SS_CANTRCVMORE) {
1243 m_adj(m, drop_hdrlen); /* delayed header drop */
1244 sbappendstream(&so->so_rcv, m);
1248 * This code is responsible for most of the ACKs
1249 * the TCP stack sends back after receiving a data
1250 * packet. Note that the DELAY_ACK check fails if
1251 * the delack timer is already running, which results
1252 * in an ack being sent every other packet (which is
1255 * We then further aggregate acks by not actually
1256 * sending one until the protocol thread has completed
1257 * processing the current backlog of packets. This
1258 * does not delay the ack any further, but allows us
1259 * to take advantage of the packet aggregation that
1260 * high speed NICs do (usually blocks of 8-10 packets)
1261 * to send a single ack rather then four or five acks,
1262 * greatly reducing the ack rate, the return channel
1263 * bandwidth, and the protocol overhead on both ends.
1265 * Since this also has the effect of slowing down
1266 * the exponential slow-start ramp-up, systems with
1267 * very large bandwidth-delay products might want
1268 * to turn the feature off.
1270 if (DELAY_ACK(tp)) {
1271 callout_reset(tp->tt_delack, tcp_delacktime,
1272 tcp_timer_delack, tp);
1273 } else if (tcp_aggregate_acks) {
1274 tp->t_flags |= TF_ACKNOW;
1275 if (!(tp->t_flags & TF_ONOUTPUTQ)) {
1276 tp->t_flags |= TF_ONOUTPUTQ;
1277 tp->tt_cpu = mycpu->gd_cpuid;
1279 &tcpcbackq[tp->tt_cpu],
1283 tp->t_flags |= TF_ACKNOW;
1291 * Calculate amount of space in receive window,
1292 * and then do TCP input processing.
1293 * Receive window is amount of space in rcv queue,
1294 * but not less than advertised window.
1296 recvwin = sbspace(&so->so_rcv);
1299 tp->rcv_wnd = imax(recvwin, (int)(tp->rcv_adv - tp->rcv_nxt));
1301 switch (tp->t_state) {
1303 * If the state is SYN_RECEIVED:
1304 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1306 case TCPS_SYN_RECEIVED:
1307 if ((thflags & TH_ACK) &&
1308 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1309 SEQ_GT(th->th_ack, tp->snd_max))) {
1310 rstreason = BANDLIM_RST_OPENPORT;
1316 * If the state is SYN_SENT:
1317 * if seg contains an ACK, but not for our SYN, drop the input.
1318 * if seg contains a RST, then drop the connection.
1319 * if seg does not contain SYN, then drop it.
1320 * Otherwise this is an acceptable SYN segment
1321 * initialize tp->rcv_nxt and tp->irs
1322 * if seg contains ack then advance tp->snd_una
1323 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1324 * arrange for segment to be acked (eventually)
1325 * continue processing rest of data/controls, beginning with URG
1328 if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1329 taop = &tao_noncached;
1330 bzero(taop, sizeof *taop);
1333 if ((thflags & TH_ACK) &&
1334 (SEQ_LEQ(th->th_ack, tp->iss) ||
1335 SEQ_GT(th->th_ack, tp->snd_max))) {
1337 * If we have a cached CCsent for the remote host,
1338 * hence we haven't just crashed and restarted,
1339 * do not send a RST. This may be a retransmission
1340 * from the other side after our earlier ACK was lost.
1341 * Our new SYN, when it arrives, will serve as the
1344 if (taop->tao_ccsent != 0)
1347 rstreason = BANDLIM_UNLIMITED;
1351 if (thflags & TH_RST) {
1352 if (thflags & TH_ACK)
1353 tp = tcp_drop(tp, ECONNREFUSED);
1356 if (!(thflags & TH_SYN))
1358 tp->snd_wnd = th->th_win; /* initial send window */
1359 tp->cc_recv = to.to_cc; /* foreign CC */
1361 tp->irs = th->th_seq;
1363 if (thflags & TH_ACK) {
1365 * Our SYN was acked. If segment contains CC.ECHO
1366 * option, check it to make sure this segment really
1367 * matches our SYN. If not, just drop it as old
1368 * duplicate, but send an RST if we're still playing
1369 * by the old rules. If no CC.ECHO option, make sure
1370 * we don't get fooled into using T/TCP.
1372 if (to.to_flags & TOF_CCECHO) {
1373 if (tp->cc_send != to.to_ccecho) {
1374 if (taop->tao_ccsent != 0)
1377 rstreason = BANDLIM_UNLIMITED;
1382 tp->t_flags &= ~TF_RCVD_CC;
1383 tcpstat.tcps_connects++;
1385 /* Do window scaling on this connection? */
1386 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1387 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1388 tp->snd_scale = tp->requested_s_scale;
1389 tp->rcv_scale = tp->request_r_scale;
1391 /* Segment is acceptable, update cache if undefined. */
1392 if (taop->tao_ccsent == 0)
1393 taop->tao_ccsent = to.to_ccecho;
1395 tp->rcv_adv += tp->rcv_wnd;
1396 tp->snd_una++; /* SYN is acked */
1397 callout_stop(tp->tt_rexmt);
1399 * If there's data, delay ACK; if there's also a FIN
1400 * ACKNOW will be turned on later.
1402 if (DELAY_ACK(tp) && tlen != 0)
1403 callout_reset(tp->tt_delack, tcp_delacktime,
1404 tcp_timer_delack, tp);
1406 tp->t_flags |= TF_ACKNOW;
1408 * Received <SYN,ACK> in SYN_SENT[*] state.
1410 * SYN_SENT --> ESTABLISHED
1411 * SYN_SENT* --> FIN_WAIT_1
1413 tp->t_starttime = ticks;
1414 if (tp->t_flags & TF_NEEDFIN) {
1415 tp->t_state = TCPS_FIN_WAIT_1;
1416 tp->t_flags &= ~TF_NEEDFIN;
1419 tp->t_state = TCPS_ESTABLISHED;
1420 callout_reset(tp->tt_keep, tcp_keepidle,
1421 tcp_timer_keep, tp);
1425 * Received initial SYN in SYN-SENT[*] state =>
1426 * simultaneous open. If segment contains CC option
1427 * and there is a cached CC, apply TAO test.
1428 * If it succeeds, connection is * half-synchronized.
1429 * Otherwise, do 3-way handshake:
1430 * SYN-SENT -> SYN-RECEIVED
1431 * SYN-SENT* -> SYN-RECEIVED*
1432 * If there was no CC option, clear cached CC value.
1434 tp->t_flags |= TF_ACKNOW;
1435 callout_stop(tp->tt_rexmt);
1436 if (to.to_flags & TOF_CC) {
1437 if (taop->tao_cc != 0 &&
1438 CC_GT(to.to_cc, taop->tao_cc)) {
1440 * update cache and make transition:
1441 * SYN-SENT -> ESTABLISHED*
1442 * SYN-SENT* -> FIN-WAIT-1*
1444 taop->tao_cc = to.to_cc;
1445 tp->t_starttime = ticks;
1446 if (tp->t_flags & TF_NEEDFIN) {
1447 tp->t_state = TCPS_FIN_WAIT_1;
1448 tp->t_flags &= ~TF_NEEDFIN;
1450 tp->t_state = TCPS_ESTABLISHED;
1451 callout_reset(tp->tt_keep,
1456 tp->t_flags |= TF_NEEDSYN;
1458 tp->t_state = TCPS_SYN_RECEIVED;
1460 /* CC.NEW or no option => invalidate cache */
1462 tp->t_state = TCPS_SYN_RECEIVED;
1468 * Advance th->th_seq to correspond to first data byte.
1469 * If data, trim to stay within window,
1470 * dropping FIN if necessary.
1473 if (tlen > tp->rcv_wnd) {
1474 todrop = tlen - tp->rcv_wnd;
1478 tcpstat.tcps_rcvpackafterwin++;
1479 tcpstat.tcps_rcvbyteafterwin += todrop;
1481 tp->snd_wl1 = th->th_seq - 1;
1482 tp->rcv_up = th->th_seq;
1484 * Client side of transaction: already sent SYN and data.
1485 * If the remote host used T/TCP to validate the SYN,
1486 * our data will be ACK'd; if so, enter normal data segment
1487 * processing in the middle of step 5, ack processing.
1488 * Otherwise, goto step 6.
1490 if (thflags & TH_ACK)
1496 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1497 * if segment contains a SYN and CC [not CC.NEW] option:
1498 * if state == TIME_WAIT and connection duration > MSL,
1499 * drop packet and send RST;
1501 * if SEG.CC > CCrecv then is new SYN, and can implicitly
1502 * ack the FIN (and data) in retransmission queue.
1503 * Complete close and delete TCPCB. Then reprocess
1504 * segment, hoping to find new TCPCB in LISTEN state;
1506 * else must be old SYN; drop it.
1507 * else do normal processing.
1511 case TCPS_TIME_WAIT:
1512 if ((thflags & TH_SYN) &&
1513 (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1514 if (tp->t_state == TCPS_TIME_WAIT &&
1515 (ticks - tp->t_starttime) > tcp_msl) {
1516 rstreason = BANDLIM_UNLIMITED;
1519 if (CC_GT(to.to_cc, tp->cc_recv)) {
1526 break; /* continue normal processing */
1530 * States other than LISTEN or SYN_SENT.
1531 * First check the RST flag and sequence number since reset segments
1532 * are exempt from the timestamp and connection count tests. This
1533 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1534 * below which allowed reset segments in half the sequence space
1535 * to fall though and be processed (which gives forged reset
1536 * segments with a random sequence number a 50 percent chance of
1537 * killing a connection).
1538 * Then check timestamp, if present.
1539 * Then check the connection count, if present.
1540 * Then check that at least some bytes of segment are within
1541 * receive window. If segment begins before rcv_nxt,
1542 * drop leading data (and SYN); if nothing left, just ack.
1545 * If the RST bit is set, check the sequence number to see
1546 * if this is a valid reset segment.
1548 * In all states except SYN-SENT, all reset (RST) segments
1549 * are validated by checking their SEQ-fields. A reset is
1550 * valid if its sequence number is in the window.
1551 * Note: this does not take into account delayed ACKs, so
1552 * we should test against last_ack_sent instead of rcv_nxt.
1553 * The sequence number in the reset segment is normally an
1554 * echo of our outgoing acknowledgement numbers, but some hosts
1555 * send a reset with the sequence number at the rightmost edge
1556 * of our receive window, and we have to handle this case.
1557 * If we have multiple segments in flight, the intial reset
1558 * segment sequence numbers will be to the left of last_ack_sent,
1559 * but they will eventually catch up.
1560 * In any case, it never made sense to trim reset segments to
1561 * fit the receive window since RFC 1122 says:
1562 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1564 * A TCP SHOULD allow a received RST segment to include data.
1567 * It has been suggested that a RST segment could contain
1568 * ASCII text that encoded and explained the cause of the
1569 * RST. No standard has yet been established for such
1572 * If the reset segment passes the sequence number test examine
1574 * SYN_RECEIVED STATE:
1575 * If passive open, return to LISTEN state.
1576 * If active open, inform user that connection was refused.
1577 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1578 * Inform user that connection was reset, and close tcb.
1579 * CLOSING, LAST_ACK STATES:
1582 * Drop the segment - see Stevens, vol. 2, p. 964 and
1585 if (thflags & TH_RST) {
1586 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1587 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1588 switch (tp->t_state) {
1590 case TCPS_SYN_RECEIVED:
1591 so->so_error = ECONNREFUSED;
1594 case TCPS_ESTABLISHED:
1595 case TCPS_FIN_WAIT_1:
1596 case TCPS_FIN_WAIT_2:
1597 case TCPS_CLOSE_WAIT:
1598 so->so_error = ECONNRESET;
1600 tp->t_state = TCPS_CLOSED;
1601 tcpstat.tcps_drops++;
1610 case TCPS_TIME_WAIT:
1618 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1619 * and it's less than ts_recent, drop it.
1621 if ((to.to_flags & TOF_TS) && tp->ts_recent != 0 &&
1622 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1624 /* Check to see if ts_recent is over 24 days old. */
1625 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1627 * Invalidate ts_recent. If this segment updates
1628 * ts_recent, the age will be reset later and ts_recent
1629 * will get a valid value. If it does not, setting
1630 * ts_recent to zero will at least satisfy the
1631 * requirement that zero be placed in the timestamp
1632 * echo reply when ts_recent isn't valid. The
1633 * age isn't reset until we get a valid ts_recent
1634 * because we don't want out-of-order segments to be
1635 * dropped when ts_recent is old.
1639 tcpstat.tcps_rcvduppack++;
1640 tcpstat.tcps_rcvdupbyte += tlen;
1641 tcpstat.tcps_pawsdrop++;
1650 * If T/TCP was negotiated and the segment doesn't have CC,
1651 * or if its CC is wrong then drop the segment.
1652 * RST segments do not have to comply with this.
1654 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1655 (!(to.to_flags & TOF_CC) || tp->cc_recv != to.to_cc))
1659 * In the SYN-RECEIVED state, validate that the packet belongs to
1660 * this connection before trimming the data to fit the receive
1661 * window. Check the sequence number versus IRS since we know
1662 * the sequence numbers haven't wrapped. This is a partial fix
1663 * for the "LAND" DoS attack.
1665 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1666 rstreason = BANDLIM_RST_OPENPORT;
1670 todrop = tp->rcv_nxt - th->th_seq;
1672 if (TCP_DO_SACK(tp)) {
1673 /* Report duplicate segment at head of packet. */
1674 tp->reportblk.rblk_start = th->th_seq;
1675 tp->reportblk.rblk_end = th->th_seq + tlen;
1676 if (thflags & TH_FIN)
1677 ++tp->reportblk.rblk_end;
1678 if (SEQ_GT(tp->reportblk.rblk_end, tp->rcv_nxt))
1679 tp->reportblk.rblk_end = tp->rcv_nxt;
1680 tp->t_flags |= (TF_DUPSEG | TF_SACKLEFT | TF_ACKNOW);
1682 if (thflags & TH_SYN) {
1692 * Following if statement from Stevens, vol. 2, p. 960.
1694 if (todrop > tlen ||
1695 (todrop == tlen && !(thflags & TH_FIN))) {
1697 * Any valid FIN must be to the left of the window.
1698 * At this point the FIN must be a duplicate or out
1699 * of sequence; drop it.
1704 * Send an ACK to resynchronize and drop any data.
1705 * But keep on processing for RST or ACK.
1707 tp->t_flags |= TF_ACKNOW;
1709 tcpstat.tcps_rcvduppack++;
1710 tcpstat.tcps_rcvdupbyte += todrop;
1712 tcpstat.tcps_rcvpartduppack++;
1713 tcpstat.tcps_rcvpartdupbyte += todrop;
1715 drop_hdrlen += todrop; /* drop from the top afterwards */
1716 th->th_seq += todrop;
1718 if (th->th_urp > todrop)
1719 th->th_urp -= todrop;
1727 * If new data are received on a connection after the
1728 * user processes are gone, then RST the other end.
1730 if ((so->so_state & SS_NOFDREF) &&
1731 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1733 tcpstat.tcps_rcvafterclose++;
1734 rstreason = BANDLIM_UNLIMITED;
1739 * If segment ends after window, drop trailing data
1740 * (and PUSH and FIN); if nothing left, just ACK.
1742 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1744 tcpstat.tcps_rcvpackafterwin++;
1745 if (todrop >= tlen) {
1746 tcpstat.tcps_rcvbyteafterwin += tlen;
1748 * If a new connection request is received
1749 * while in TIME_WAIT, drop the old connection
1750 * and start over if the sequence numbers
1751 * are above the previous ones.
1753 if (thflags & TH_SYN &&
1754 tp->t_state == TCPS_TIME_WAIT &&
1755 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1760 * If window is closed can only take segments at
1761 * window edge, and have to drop data and PUSH from
1762 * incoming segments. Continue processing, but
1763 * remember to ack. Otherwise, drop segment
1766 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1767 tp->t_flags |= TF_ACKNOW;
1768 tcpstat.tcps_rcvwinprobe++;
1772 tcpstat.tcps_rcvbyteafterwin += todrop;
1775 thflags &= ~(TH_PUSH | TH_FIN);
1779 * If last ACK falls within this segment's sequence numbers,
1780 * record its timestamp.
1782 * 1) That the test incorporates suggestions from the latest
1783 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1784 * 2) That updating only on newer timestamps interferes with
1785 * our earlier PAWS tests, so this check should be solely
1786 * predicated on the sequence space of this segment.
1787 * 3) That we modify the segment boundary check to be
1788 * Last.ACK.Sent <= SEG.SEQ + SEG.LEN
1789 * instead of RFC1323's
1790 * Last.ACK.Sent < SEG.SEQ + SEG.LEN,
1791 * This modified check allows us to overcome RFC1323's
1792 * limitations as described in Stevens TCP/IP Illustrated
1793 * Vol. 2 p.869. In such cases, we can still calculate the
1794 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1796 if ((to.to_flags & TOF_TS) && SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1797 SEQ_LEQ(tp->last_ack_sent, (th->th_seq + tlen
1798 + ((thflags & TH_SYN) != 0)
1799 + ((thflags & TH_FIN) != 0)))) {
1800 tp->ts_recent_age = ticks;
1801 tp->ts_recent = to.to_tsval;
1805 * If a SYN is in the window, then this is an
1806 * error and we send an RST and drop the connection.
1808 if (thflags & TH_SYN) {
1809 tp = tcp_drop(tp, ECONNRESET);
1810 rstreason = BANDLIM_UNLIMITED;
1815 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1816 * flag is on (half-synchronized state), then queue data for
1817 * later processing; else drop segment and return.
1819 if (!(thflags & TH_ACK)) {
1820 if (tp->t_state == TCPS_SYN_RECEIVED ||
1821 (tp->t_flags & TF_NEEDSYN))
1830 switch (tp->t_state) {
1832 * In SYN_RECEIVED state, the ACK acknowledges our SYN, so enter
1833 * ESTABLISHED state and continue processing.
1834 * The ACK was checked above.
1836 case TCPS_SYN_RECEIVED:
1838 tcpstat.tcps_connects++;
1840 /* Do window scaling? */
1841 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1842 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1843 tp->snd_scale = tp->requested_s_scale;
1844 tp->rcv_scale = tp->request_r_scale;
1847 * Upon successful completion of 3-way handshake,
1848 * update cache.CC if it was undefined, pass any queued
1849 * data to the user, and advance state appropriately.
1851 if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1853 taop->tao_cc = tp->cc_recv;
1857 * SYN-RECEIVED -> ESTABLISHED
1858 * SYN-RECEIVED* -> FIN-WAIT-1
1860 tp->t_starttime = ticks;
1861 if (tp->t_flags & TF_NEEDFIN) {
1862 tp->t_state = TCPS_FIN_WAIT_1;
1863 tp->t_flags &= ~TF_NEEDFIN;
1865 tp->t_state = TCPS_ESTABLISHED;
1866 callout_reset(tp->tt_keep, tcp_keepidle,
1867 tcp_timer_keep, tp);
1870 * If segment contains data or ACK, will call tcp_reass()
1871 * later; if not, do so now to pass queued data to user.
1873 if (tlen == 0 && !(thflags & TH_FIN))
1874 tcp_reass(tp, NULL, NULL, NULL);
1878 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1879 * ACKs. If the ack is in the range
1880 * tp->snd_una < th->th_ack <= tp->snd_max
1881 * then advance tp->snd_una to th->th_ack and drop
1882 * data from the retransmission queue. If this ACK reflects
1883 * more up to date window information we update our window information.
1885 case TCPS_ESTABLISHED:
1886 case TCPS_FIN_WAIT_1:
1887 case TCPS_FIN_WAIT_2:
1888 case TCPS_CLOSE_WAIT:
1891 case TCPS_TIME_WAIT:
1893 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1894 if (TCP_DO_SACK(tp))
1895 tcp_sack_update_scoreboard(tp, &to);
1896 if (tlen != 0 || tiwin != tp->snd_wnd) {
1900 tcpstat.tcps_rcvdupack++;
1901 if (!callout_active(tp->tt_rexmt) ||
1902 th->th_ack != tp->snd_una) {
1907 * We have outstanding data (other than
1908 * a window probe), this is a completely
1909 * duplicate ack (ie, window info didn't
1910 * change), the ack is the biggest we've
1911 * seen and we've seen exactly our rexmt
1912 * threshhold of them, so assume a packet
1913 * has been dropped and retransmit it.
1914 * Kludge snd_nxt & the congestion
1915 * window so we send only this one
1918 if (IN_FASTRECOVERY(tp)) {
1919 if (TCP_DO_SACK(tp)) {
1920 /* No artifical cwnd inflation. */
1921 tcp_sack_rexmt(tp, th);
1924 * Dup acks mean that packets
1925 * have left the network
1926 * (they're now cached at the
1927 * receiver) so bump cwnd by
1928 * the amount in the receiver
1929 * to keep a constant cwnd
1930 * packets in the network.
1932 tp->snd_cwnd += tp->t_maxseg;
1935 } else if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1938 } else if (++tp->t_dupacks == tcprexmtthresh) {
1939 tcp_seq old_snd_nxt;
1943 if (tcp_do_eifel_detect &&
1944 (tp->t_flags & TF_RCVD_TSTMP)) {
1945 tcp_save_congestion_state(tp);
1946 tp->t_flags |= TF_FASTREXMT;
1949 * We know we're losing at the current
1950 * window size, so do congestion avoidance:
1951 * set ssthresh to half the current window
1952 * and pull our congestion window back to the
1955 win = min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1959 tp->snd_ssthresh = win * tp->t_maxseg;
1960 ENTER_FASTRECOVERY(tp);
1961 tp->snd_recover = tp->snd_max;
1962 callout_stop(tp->tt_rexmt);
1964 old_snd_nxt = tp->snd_nxt;
1965 tp->snd_nxt = th->th_ack;
1966 tp->snd_cwnd = tp->t_maxseg;
1968 ++tcpstat.tcps_sndfastrexmit;
1969 tp->snd_cwnd = tp->snd_ssthresh;
1970 tp->rexmt_high = tp->snd_nxt;
1971 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
1972 tp->snd_nxt = old_snd_nxt;
1973 KASSERT(tp->snd_limited <= 2,
1974 ("tp->snd_limited too big"));
1975 if (TCP_DO_SACK(tp))
1976 tcp_sack_rexmt(tp, th);
1978 tp->snd_cwnd += tp->t_maxseg *
1979 (tp->t_dupacks - tp->snd_limited);
1980 } else if (tcp_do_limitedtransmit) {
1981 u_long oldcwnd = tp->snd_cwnd;
1982 tcp_seq oldsndmax = tp->snd_max;
1983 tcp_seq oldsndnxt = tp->snd_nxt;
1984 /* outstanding data */
1985 uint32_t ownd = tp->snd_max - tp->snd_una;
1988 #define iceildiv(n, d) (((n)+(d)-1) / (d))
1990 KASSERT(tp->t_dupacks == 1 ||
1992 ("dupacks not 1 or 2"));
1993 if (tp->t_dupacks == 1)
1994 tp->snd_limited = 0;
1995 tp->snd_nxt = tp->snd_max;
1996 tp->snd_cwnd = ownd +
1997 (tp->t_dupacks - tp->snd_limited) *
2000 if (SEQ_LT(oldsndnxt, oldsndmax))
2001 tp->snd_nxt = oldsndnxt;
2002 tp->snd_cwnd = oldcwnd;
2003 sent = tp->snd_max - oldsndmax;
2004 if (sent > tp->t_maxseg) {
2005 KASSERT((tp->t_dupacks == 2 &&
2006 tp->snd_limited == 0) ||
2007 (sent == tp->t_maxseg + 1 &&
2008 tp->t_flags & TF_SENTFIN),
2010 KASSERT(sent <= tp->t_maxseg * 2,
2011 ("sent too many segments"));
2012 tp->snd_limited = 2;
2013 tcpstat.tcps_sndlimited += 2;
2014 } else if (sent > 0) {
2016 ++tcpstat.tcps_sndlimited;
2017 } else if (tcp_do_early_retransmit &&
2018 (tcp_do_eifel_detect &&
2019 (tp->t_flags & TF_RCVD_TSTMP)) &&
2020 ownd < 4 * tp->t_maxseg &&
2021 tp->t_dupacks + 1 >=
2022 iceildiv(ownd, tp->t_maxseg) &&
2023 (!TCP_DO_SACK(tp) ||
2024 ownd <= tp->t_maxseg ||
2025 tcp_sack_has_sacked(&tp->scb,
2026 ownd - tp->t_maxseg))) {
2027 ++tcpstat.tcps_sndearlyrexmit;
2028 tp->t_flags |= TF_EARLYREXMT;
2029 goto fastretransmit;
2035 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
2037 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2039 * Detected optimistic ACK attack.
2040 * Force slow-start to de-synchronize attack.
2042 tp->snd_cwnd = tp->t_maxseg;
2045 tcpstat.tcps_rcvacktoomuch++;
2049 * If we reach this point, ACK is not a duplicate,
2050 * i.e., it ACKs something we sent.
2052 if (tp->t_flags & TF_NEEDSYN) {
2054 * T/TCP: Connection was half-synchronized, and our
2055 * SYN has been ACK'd (so connection is now fully
2056 * synchronized). Go to non-starred state,
2057 * increment snd_una for ACK of SYN, and check if
2058 * we can do window scaling.
2060 tp->t_flags &= ~TF_NEEDSYN;
2062 /* Do window scaling? */
2063 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
2064 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
2065 tp->snd_scale = tp->requested_s_scale;
2066 tp->rcv_scale = tp->request_r_scale;
2071 acked = th->th_ack - tp->snd_una;
2072 tcpstat.tcps_rcvackpack++;
2073 tcpstat.tcps_rcvackbyte += acked;
2075 if (tcp_do_eifel_detect && acked > 0 &&
2076 (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
2077 (tp->t_flags & TF_FIRSTACCACK)) {
2078 /* Eifel detection applicable. */
2079 if (to.to_tsecr < tp->t_rexmtTS) {
2080 ++tcpstat.tcps_eifeldetected;
2081 tcp_revert_congestion_state(tp);
2082 if (tp->t_rxtshift == 1 &&
2083 ticks >= tp->t_badrxtwin)
2084 ++tcpstat.tcps_rttcantdetect;
2086 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2088 * If we just performed our first retransmit,
2089 * and the ACK arrives within our recovery window,
2090 * then it was a mistake to do the retransmit
2091 * in the first place. Recover our original cwnd
2092 * and ssthresh, and proceed to transmit where we
2095 tcp_revert_congestion_state(tp);
2096 ++tcpstat.tcps_rttdetected;
2100 * If we have a timestamp reply, update smoothed
2101 * round trip time. If no timestamp is present but
2102 * transmit timer is running and timed sequence
2103 * number was acked, update smoothed round trip time.
2104 * Since we now have an rtt measurement, cancel the
2105 * timer backoff (cf., Phil Karn's retransmit alg.).
2106 * Recompute the initial retransmit timer.
2108 * Some machines (certain windows boxes) send broken
2109 * timestamp replies during the SYN+ACK phase, ignore
2112 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
2113 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2114 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2115 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2116 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2119 * If no data (only SYN) was ACK'd,
2120 * skip rest of ACK processing.
2125 /* Stop looking for an acceptable ACK since one was received. */
2126 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT | TF_EARLYREXMT);
2128 if (acked > so->so_snd.sb_cc) {
2129 tp->snd_wnd -= so->so_snd.sb_cc;
2130 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2131 ourfinisacked = TRUE;
2133 sbdrop(&so->so_snd, acked);
2134 tp->snd_wnd -= acked;
2135 ourfinisacked = FALSE;
2140 * Update window information.
2141 * Don't look at window if no ACK:
2142 * TAC's send garbage on first SYN.
2144 if (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2145 (tp->snd_wl1 == th->th_seq &&
2146 (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2147 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)))) {
2148 /* keep track of pure window updates */
2149 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2150 tiwin > tp->snd_wnd)
2151 tcpstat.tcps_rcvwinupd++;
2152 tp->snd_wnd = tiwin;
2153 tp->snd_wl1 = th->th_seq;
2154 tp->snd_wl2 = th->th_ack;
2155 if (tp->snd_wnd > tp->max_sndwnd)
2156 tp->max_sndwnd = tp->snd_wnd;
2160 tp->snd_una = th->th_ack;
2161 if (TCP_DO_SACK(tp))
2162 tcp_sack_update_scoreboard(tp, &to);
2163 if (IN_FASTRECOVERY(tp)) {
2164 if (SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2165 EXIT_FASTRECOVERY(tp);
2168 * If the congestion window was inflated
2169 * to account for the other side's
2170 * cached packets, retract it.
2172 if (!TCP_DO_SACK(tp))
2173 tp->snd_cwnd = tp->snd_ssthresh;
2176 * Window inflation should have left us
2177 * with approximately snd_ssthresh outstanding
2178 * data. But, in case we would be inclined
2179 * to send a burst, better do it using
2182 if (SEQ_GT(th->th_ack + tp->snd_cwnd,
2183 tp->snd_max + 2 * tp->t_maxseg))
2185 (tp->snd_max - tp->snd_una) +
2190 if (TCP_DO_SACK(tp)) {
2191 tp->snd_max_rexmt = tp->snd_max;
2192 tcp_sack_rexmt(tp, th);
2194 tcp_newreno_partial_ack(tp, th, acked);
2200 * Open the congestion window. When in slow-start,
2201 * open exponentially: maxseg per packet. Otherwise,
2202 * open linearly: maxseg per window.
2204 if (tp->snd_cwnd <= tp->snd_ssthresh) {
2206 (SEQ_LT(tp->snd_nxt, tp->snd_max) ?
2207 tp->t_maxseg : 2 * tp->t_maxseg);
2210 tp->snd_cwnd += tcp_do_abc ?
2211 min(acked, abc_sslimit) : tp->t_maxseg;
2213 /* linear increase */
2214 tp->snd_wacked += tcp_do_abc ? acked :
2216 if (tp->snd_wacked >= tp->snd_cwnd) {
2217 tp->snd_wacked -= tp->snd_cwnd;
2218 tp->snd_cwnd += tp->t_maxseg;
2221 tp->snd_cwnd = min(tp->snd_cwnd,
2222 TCP_MAXWIN << tp->snd_scale);
2223 tp->snd_recover = th->th_ack - 1;
2225 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2226 tp->snd_nxt = tp->snd_una;
2229 * If all outstanding data is acked, stop retransmit
2230 * timer and remember to restart (more output or persist).
2231 * If there is more data to be acked, restart retransmit
2232 * timer, using current (possibly backed-off) value.
2234 if (th->th_ack == tp->snd_max) {
2235 callout_stop(tp->tt_rexmt);
2237 } else if (!callout_active(tp->tt_persist))
2238 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
2239 tcp_timer_rexmt, tp);
2241 switch (tp->t_state) {
2243 * In FIN_WAIT_1 STATE in addition to the processing
2244 * for the ESTABLISHED state if our FIN is now acknowledged
2245 * then enter FIN_WAIT_2.
2247 case TCPS_FIN_WAIT_1:
2248 if (ourfinisacked) {
2250 * If we can't receive any more
2251 * data, then closing user can proceed.
2252 * Starting the timer is contrary to the
2253 * specification, but if we don't get a FIN
2254 * we'll hang forever.
2256 if (so->so_state & SS_CANTRCVMORE) {
2257 soisdisconnected(so);
2258 callout_reset(tp->tt_2msl, tcp_maxidle,
2259 tcp_timer_2msl, tp);
2261 tp->t_state = TCPS_FIN_WAIT_2;
2266 * In CLOSING STATE in addition to the processing for
2267 * the ESTABLISHED state if the ACK acknowledges our FIN
2268 * then enter the TIME-WAIT state, otherwise ignore
2272 if (ourfinisacked) {
2273 tp->t_state = TCPS_TIME_WAIT;
2274 tcp_canceltimers(tp);
2275 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2276 if (tp->cc_recv != 0 &&
2277 (ticks - tp->t_starttime) < tcp_msl)
2278 callout_reset(tp->tt_2msl,
2279 tp->t_rxtcur * TCPTV_TWTRUNC,
2280 tcp_timer_2msl, tp);
2282 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2283 tcp_timer_2msl, tp);
2284 soisdisconnected(so);
2289 * In LAST_ACK, we may still be waiting for data to drain
2290 * and/or to be acked, as well as for the ack of our FIN.
2291 * If our FIN is now acknowledged, delete the TCB,
2292 * enter the closed state and return.
2295 if (ourfinisacked) {
2302 * In TIME_WAIT state the only thing that should arrive
2303 * is a retransmission of the remote FIN. Acknowledge
2304 * it and restart the finack timer.
2306 case TCPS_TIME_WAIT:
2307 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2308 tcp_timer_2msl, tp);
2315 * Update window information.
2316 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2318 if ((thflags & TH_ACK) &&
2319 acceptable_window_update(tp, th, tiwin)) {
2320 /* keep track of pure window updates */
2321 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2322 tiwin > tp->snd_wnd)
2323 tcpstat.tcps_rcvwinupd++;
2324 tp->snd_wnd = tiwin;
2325 tp->snd_wl1 = th->th_seq;
2326 tp->snd_wl2 = th->th_ack;
2327 if (tp->snd_wnd > tp->max_sndwnd)
2328 tp->max_sndwnd = tp->snd_wnd;
2333 * Process segments with URG.
2335 if ((thflags & TH_URG) && th->th_urp &&
2336 !TCPS_HAVERCVDFIN(tp->t_state)) {
2338 * This is a kludge, but if we receive and accept
2339 * random urgent pointers, we'll crash in
2340 * soreceive. It's hard to imagine someone
2341 * actually wanting to send this much urgent data.
2343 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2344 th->th_urp = 0; /* XXX */
2345 thflags &= ~TH_URG; /* XXX */
2346 goto dodata; /* XXX */
2349 * If this segment advances the known urgent pointer,
2350 * then mark the data stream. This should not happen
2351 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2352 * a FIN has been received from the remote side.
2353 * In these states we ignore the URG.
2355 * According to RFC961 (Assigned Protocols),
2356 * the urgent pointer points to the last octet
2357 * of urgent data. We continue, however,
2358 * to consider it to indicate the first octet
2359 * of data past the urgent section as the original
2360 * spec states (in one of two places).
2362 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
2363 tp->rcv_up = th->th_seq + th->th_urp;
2364 so->so_oobmark = so->so_rcv.sb_cc +
2365 (tp->rcv_up - tp->rcv_nxt) - 1;
2366 if (so->so_oobmark == 0)
2367 so->so_state |= SS_RCVATMARK;
2369 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2372 * Remove out of band data so doesn't get presented to user.
2373 * This can happen independent of advancing the URG pointer,
2374 * but if two URG's are pending at once, some out-of-band
2375 * data may creep in... ick.
2377 if (th->th_urp <= (u_long)tlen &&
2378 !(so->so_options & SO_OOBINLINE)) {
2379 /* hdr drop is delayed */
2380 tcp_pulloutofband(so, th, m, drop_hdrlen);
2384 * If no out of band data is expected,
2385 * pull receive urgent pointer along
2386 * with the receive window.
2388 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2389 tp->rcv_up = tp->rcv_nxt;
2394 * Process the segment text, merging it into the TCP sequencing queue,
2395 * and arranging for acknowledgment of receipt if necessary.
2396 * This process logically involves adjusting tp->rcv_wnd as data
2397 * is presented to the user (this happens in tcp_usrreq.c,
2398 * case PRU_RCVD). If a FIN has already been received on this
2399 * connection then we just ignore the text.
2401 if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
2402 m_adj(m, drop_hdrlen); /* delayed header drop */
2404 * Insert segment which includes th into TCP reassembly queue
2405 * with control block tp. Set thflags to whether reassembly now
2406 * includes a segment with FIN. This handles the common case
2407 * inline (segment is the next to be received on an established
2408 * connection, and the queue is empty), avoiding linkage into
2409 * and removal from the queue and repetition of various
2411 * Set DELACK for segments received in order, but ack
2412 * immediately when segments are out of order (so
2413 * fast retransmit can work).
2415 if (th->th_seq == tp->rcv_nxt &&
2416 LIST_EMPTY(&tp->t_segq) &&
2417 TCPS_HAVEESTABLISHED(tp->t_state)) {
2419 callout_reset(tp->tt_delack, tcp_delacktime,
2420 tcp_timer_delack, tp);
2422 tp->t_flags |= TF_ACKNOW;
2423 tp->rcv_nxt += tlen;
2424 thflags = th->th_flags & TH_FIN;
2425 tcpstat.tcps_rcvpack++;
2426 tcpstat.tcps_rcvbyte += tlen;
2428 if (so->so_state & SS_CANTRCVMORE)
2431 sbappendstream(&so->so_rcv, m);
2434 if (!(tp->t_flags & TF_DUPSEG)) {
2435 /* Initialize SACK report block. */
2436 tp->reportblk.rblk_start = th->th_seq;
2437 tp->reportblk.rblk_end = th->th_seq + tlen +
2438 ((thflags & TH_FIN) != 0);
2440 thflags = tcp_reass(tp, th, &tlen, m);
2441 tp->t_flags |= TF_ACKNOW;
2445 * Note the amount of data that peer has sent into
2446 * our window, in order to estimate the sender's
2449 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2456 * If FIN is received ACK the FIN and let the user know
2457 * that the connection is closing.
2459 if (thflags & TH_FIN) {
2460 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
2463 * If connection is half-synchronized
2464 * (ie NEEDSYN flag on) then delay ACK,
2465 * so it may be piggybacked when SYN is sent.
2466 * Otherwise, since we received a FIN then no
2467 * more input can be expected, send ACK now.
2469 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2470 callout_reset(tp->tt_delack, tcp_delacktime,
2471 tcp_timer_delack, tp);
2473 tp->t_flags |= TF_ACKNOW;
2477 switch (tp->t_state) {
2479 * In SYN_RECEIVED and ESTABLISHED STATES
2480 * enter the CLOSE_WAIT state.
2482 case TCPS_SYN_RECEIVED:
2483 tp->t_starttime = ticks;
2485 case TCPS_ESTABLISHED:
2486 tp->t_state = TCPS_CLOSE_WAIT;
2490 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2491 * enter the CLOSING state.
2493 case TCPS_FIN_WAIT_1:
2494 tp->t_state = TCPS_CLOSING;
2498 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2499 * starting the time-wait timer, turning off the other
2502 case TCPS_FIN_WAIT_2:
2503 tp->t_state = TCPS_TIME_WAIT;
2504 tcp_canceltimers(tp);
2505 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2506 if (tp->cc_recv != 0 &&
2507 (ticks - tp->t_starttime) < tcp_msl) {
2508 callout_reset(tp->tt_2msl,
2509 tp->t_rxtcur * TCPTV_TWTRUNC,
2510 tcp_timer_2msl, tp);
2511 /* For transaction client, force ACK now. */
2512 tp->t_flags |= TF_ACKNOW;
2515 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2516 tcp_timer_2msl, tp);
2517 soisdisconnected(so);
2521 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2523 case TCPS_TIME_WAIT:
2524 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2525 tcp_timer_2msl, tp);
2531 if (so->so_options & SO_DEBUG)
2532 tcp_trace(TA_INPUT, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2536 * Return any desired output.
2538 if (needoutput || (tp->t_flags & TF_ACKNOW))
2544 * Generate an ACK dropping incoming segment if it occupies
2545 * sequence space, where the ACK reflects our state.
2547 * We can now skip the test for the RST flag since all
2548 * paths to this code happen after packets containing
2549 * RST have been dropped.
2551 * In the SYN-RECEIVED state, don't send an ACK unless the
2552 * segment we received passes the SYN-RECEIVED ACK test.
2553 * If it fails send a RST. This breaks the loop in the
2554 * "LAND" DoS attack, and also prevents an ACK storm
2555 * between two listening ports that have been sent forged
2556 * SYN segments, each with the source address of the other.
2558 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2559 (SEQ_GT(tp->snd_una, th->th_ack) ||
2560 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2561 rstreason = BANDLIM_RST_OPENPORT;
2565 if (so->so_options & SO_DEBUG)
2566 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2569 tp->t_flags |= TF_ACKNOW;
2575 * Generate a RST, dropping incoming segment.
2576 * Make ACK acceptable to originator of segment.
2577 * Don't bother to respond if destination was broadcast/multicast.
2579 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
2582 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2583 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2586 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2587 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2588 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2589 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2592 /* IPv6 anycast check is done at tcp6_input() */
2595 * Perform bandwidth limiting.
2598 if (badport_bandlim(rstreason) < 0)
2603 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2604 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2606 if (thflags & TH_ACK)
2607 /* mtod() below is safe as long as hdr dropping is delayed */
2608 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2611 if (thflags & TH_SYN)
2613 /* mtod() below is safe as long as hdr dropping is delayed */
2614 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2615 (tcp_seq)0, TH_RST | TH_ACK);
2621 * Drop space held by incoming segment and return.
2624 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2625 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2632 * Parse TCP options and place in tcpopt.
2635 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn)
2640 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2642 if (opt == TCPOPT_EOL)
2644 if (opt == TCPOPT_NOP)
2650 if (optlen < 2 || optlen > cnt)
2655 if (optlen != TCPOLEN_MAXSEG)
2659 to->to_flags |= TOF_MSS;
2660 bcopy(cp + 2, &to->to_mss, sizeof to->to_mss);
2661 to->to_mss = ntohs(to->to_mss);
2664 if (optlen != TCPOLEN_WINDOW)
2668 to->to_flags |= TOF_SCALE;
2669 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2671 case TCPOPT_TIMESTAMP:
2672 if (optlen != TCPOLEN_TIMESTAMP)
2674 to->to_flags |= TOF_TS;
2675 bcopy(cp + 2, &to->to_tsval, sizeof to->to_tsval);
2676 to->to_tsval = ntohl(to->to_tsval);
2677 bcopy(cp + 6, &to->to_tsecr, sizeof to->to_tsecr);
2678 to->to_tsecr = ntohl(to->to_tsecr);
2680 * If echoed timestamp is later than the current time,
2681 * fall back to non RFC1323 RTT calculation.
2683 if (to->to_tsecr != 0 && TSTMP_GT(to->to_tsecr, ticks))
2687 if (optlen != TCPOLEN_CC)
2689 to->to_flags |= TOF_CC;
2690 bcopy(cp + 2, &to->to_cc, sizeof to->to_cc);
2691 to->to_cc = ntohl(to->to_cc);
2694 if (optlen != TCPOLEN_CC)
2698 to->to_flags |= TOF_CCNEW;
2699 bcopy(cp + 2, &to->to_cc, sizeof to->to_cc);
2700 to->to_cc = ntohl(to->to_cc);
2703 if (optlen != TCPOLEN_CC)
2707 to->to_flags |= TOF_CCECHO;
2708 bcopy(cp + 2, &to->to_ccecho, sizeof to->to_ccecho);
2709 to->to_ccecho = ntohl(to->to_ccecho);
2711 case TCPOPT_SACK_PERMITTED:
2712 if (optlen != TCPOLEN_SACK_PERMITTED)
2716 to->to_flags |= TOF_SACK_PERMITTED;
2719 if ((optlen - 2) & 0x07) /* not multiple of 8 */
2721 to->to_nsackblocks = (optlen - 2) / 8;
2722 to->to_sackblocks = (struct raw_sackblock *) (cp + 2);
2723 to->to_flags |= TOF_SACK;
2724 for (i = 0; i < to->to_nsackblocks; i++) {
2725 struct raw_sackblock *r = &to->to_sackblocks[i];
2727 r->rblk_start = ntohl(r->rblk_start);
2728 r->rblk_end = ntohl(r->rblk_end);
2738 * Pull out of band byte out of a segment so
2739 * it doesn't appear in the user's data queue.
2740 * It is still reflected in the segment length for
2741 * sequencing purposes.
2742 * "off" is the delayed to be dropped hdrlen.
2745 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
2747 int cnt = off + th->th_urp - 1;
2750 if (m->m_len > cnt) {
2751 char *cp = mtod(m, caddr_t) + cnt;
2752 struct tcpcb *tp = sototcpcb(so);
2755 tp->t_oobflags |= TCPOOB_HAVEDATA;
2756 bcopy(cp + 1, cp, m->m_len - cnt - 1);
2758 if (m->m_flags & M_PKTHDR)
2767 panic("tcp_pulloutofband");
2771 * Collect new round-trip time estimate
2772 * and update averages and current timeout.
2775 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2779 tcpstat.tcps_rttupdated++;
2781 if (tp->t_srtt != 0) {
2783 * srtt is stored as fixed point with 5 bits after the
2784 * binary point (i.e., scaled by 8). The following magic
2785 * is equivalent to the smoothing algorithm in rfc793 with
2786 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2787 * point). Adjust rtt to origin 0.
2789 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2790 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2792 if ((tp->t_srtt += delta) <= 0)
2796 * We accumulate a smoothed rtt variance (actually, a
2797 * smoothed mean difference), then set the retransmit
2798 * timer to smoothed rtt + 4 times the smoothed variance.
2799 * rttvar is stored as fixed point with 4 bits after the
2800 * binary point (scaled by 16). The following is
2801 * equivalent to rfc793 smoothing with an alpha of .75
2802 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2803 * rfc793's wired-in beta.
2807 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2808 if ((tp->t_rttvar += delta) <= 0)
2810 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2811 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2814 * No rtt measurement yet - use the unsmoothed rtt.
2815 * Set the variance to half the rtt (so our first
2816 * retransmit happens at 3*rtt).
2818 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2819 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2820 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2826 * the retransmit should happen at rtt + 4 * rttvar.
2827 * Because of the way we do the smoothing, srtt and rttvar
2828 * will each average +1/2 tick of bias. When we compute
2829 * the retransmit timer, we want 1/2 tick of rounding and
2830 * 1 extra tick because of +-1/2 tick uncertainty in the
2831 * firing of the timer. The bias will give us exactly the
2832 * 1.5 tick we need. But, because the bias is
2833 * statistical, we have to test that we don't drop below
2834 * the minimum feasible timer (which is 2 ticks).
2836 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2837 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2840 * We received an ack for a packet that wasn't retransmitted;
2841 * it is probably safe to discard any error indications we've
2842 * received recently. This isn't quite right, but close enough
2843 * for now (a route might have failed after we sent a segment,
2844 * and the return path might not be symmetrical).
2846 tp->t_softerror = 0;
2850 * Determine a reasonable value for maxseg size.
2851 * If the route is known, check route for mtu.
2852 * If none, use an mss that can be handled on the outgoing
2853 * interface without forcing IP to fragment; if bigger than
2854 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2855 * to utilize large mbufs. If no route is found, route has no mtu,
2856 * or the destination isn't local, use a default, hopefully conservative
2857 * size (usually 512 or the default IP max size, but no more than the mtu
2858 * of the interface), as we can't discover anything about intervening
2859 * gateways or networks. We also initialize the congestion/slow start
2860 * window to be a single segment if the destination isn't local.
2861 * While looking at the routing entry, we also initialize other path-dependent
2862 * parameters from pre-set or cached values in the routing entry.
2864 * Also take into account the space needed for options that we
2865 * send regularly. Make maxseg shorter by that amount to assure
2866 * that we can send maxseg amount of data even when the options
2867 * are present. Store the upper limit of the length of options plus
2870 * NOTE that this routine is only called when we process an incoming
2871 * segment, for outgoing segments only tcp_mssopt is called.
2873 * In case of T/TCP, we call this routine during implicit connection
2874 * setup as well (offer = -1), to initialize maxseg from the cached
2878 tcp_mss(struct tcpcb *tp, int offer)
2884 struct inpcb *inp = tp->t_inpcb;
2886 struct rmxp_tao *taop;
2887 int origoffer = offer;
2889 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2890 size_t min_protoh = isipv6 ?
2891 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2892 sizeof(struct tcpiphdr);
2894 const boolean_t isipv6 = FALSE;
2895 const size_t min_protoh = sizeof(struct tcpiphdr);
2899 rt = tcp_rtlookup6(&inp->inp_inc);
2901 rt = tcp_rtlookup(&inp->inp_inc);
2903 tp->t_maxopd = tp->t_maxseg =
2904 (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2908 so = inp->inp_socket;
2910 taop = rmx_taop(rt->rt_rmx);
2912 * Offer == -1 means that we didn't receive SYN yet,
2913 * use cached value in that case;
2916 offer = taop->tao_mssopt;
2918 * Offer == 0 means that there was no MSS on the SYN segment,
2919 * in this case we use tcp_mssdflt.
2922 offer = (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2925 * Sanity check: make sure that maxopd will be large
2926 * enough to allow some data on segments even is the
2927 * all the option space is used (40bytes). Otherwise
2928 * funny things may happen in tcp_output.
2930 offer = max(offer, 64);
2931 taop->tao_mssopt = offer;
2934 * While we're here, check if there's an initial rtt
2935 * or rttvar. Convert from the route-table units
2936 * to scaled multiples of the slow timeout timer.
2938 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2940 * XXX the lock bit for RTT indicates that the value
2941 * is also a minimum value; this is subject to time.
2943 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2944 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2945 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2946 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2947 tcpstat.tcps_usedrtt++;
2948 if (rt->rt_rmx.rmx_rttvar) {
2949 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2950 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2951 tcpstat.tcps_usedrttvar++;
2953 /* default variation is +- 1 rtt */
2955 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2957 TCPT_RANGESET(tp->t_rxtcur,
2958 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2959 tp->t_rttmin, TCPTV_REXMTMAX);
2962 * if there's an mtu associated with the route, use it
2963 * else, use the link mtu.
2965 if (rt->rt_rmx.rmx_mtu)
2966 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2969 mss = ND_IFINFO(rt->rt_ifp)->linkmtu - min_protoh;
2970 if (!in6_localaddr(&inp->in6p_faddr))
2971 mss = min(mss, tcp_v6mssdflt);
2973 mss = ifp->if_mtu - min_protoh;
2974 if (!in_localaddr(inp->inp_faddr))
2975 mss = min(mss, tcp_mssdflt);
2978 mss = min(mss, offer);
2980 * maxopd stores the maximum length of data AND options
2981 * in a segment; maxseg is the amount of data in a normal
2982 * segment. We need to store this value (maxopd) apart
2983 * from maxseg, because now every segment carries options
2984 * and thus we normally have somewhat less data in segments.
2989 * In case of T/TCP, origoffer==-1 indicates, that no segments
2990 * were received yet. In this case we just guess, otherwise
2991 * we do the same as before T/TCP.
2993 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
2995 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2996 mss -= TCPOLEN_TSTAMP_APPA;
2997 if ((tp->t_flags & (TF_REQ_CC | TF_NOOPT)) == TF_REQ_CC &&
2999 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
3000 mss -= TCPOLEN_CC_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.sb_hiwat;
3022 bufsize = roundup(bufsize, mss);
3023 if (bufsize > sb_max)
3025 if (bufsize > so->so_snd.sb_hiwat)
3026 sbreserve(&so->so_snd, bufsize, so, NULL);
3031 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
3033 bufsize = so->so_rcv.sb_hiwat;
3034 if (bufsize > mss) {
3035 bufsize = roundup(bufsize, mss);
3036 if (bufsize > sb_max)
3038 if (bufsize > so->so_rcv.sb_hiwat)
3039 sbreserve(&so->so_rcv, bufsize, so, NULL);
3043 * Set the slow-start flight size depending on whether this
3044 * is a local network or not.
3047 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3051 if (rt->rt_rmx.rmx_ssthresh) {
3053 * There's some sort of gateway or interface
3054 * buffer limit on the path. Use this to set
3055 * the slow start threshhold, but set the
3056 * threshold to no less than 2*mss.
3058 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3059 tcpstat.tcps_usedssthresh++;
3064 * Determine the MSS option to send on an outgoing SYN.
3067 tcp_mssopt(struct tcpcb *tp)
3072 ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3073 int min_protoh = isipv6 ?
3074 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
3075 sizeof(struct tcpiphdr);
3077 const boolean_t isipv6 = FALSE;
3078 const size_t min_protoh = sizeof(struct tcpiphdr);
3082 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
3084 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
3086 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3088 return (rt->rt_ifp->if_mtu - min_protoh);
3092 * When a partial ack arrives, force the retransmission of the
3093 * next unacknowledged segment. Do not exit Fast Recovery.
3095 * Implement the Slow-but-Steady variant of NewReno by restarting the
3096 * the retransmission timer. Turn it off here so it can be restarted
3097 * later in tcp_output().
3100 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th, int acked)
3102 tcp_seq old_snd_nxt = tp->snd_nxt;
3103 u_long ocwnd = tp->snd_cwnd;
3105 callout_stop(tp->tt_rexmt);
3107 tp->snd_nxt = th->th_ack;
3108 /* Set snd_cwnd to one segment beyond acknowledged offset. */
3109 tp->snd_cwnd = tp->t_maxseg;
3110 tp->t_flags |= TF_ACKNOW;
3112 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3113 tp->snd_nxt = old_snd_nxt;
3114 /* partial window deflation */
3116 tp->snd_cwnd = ocwnd - acked + tp->t_maxseg;
3118 tp->snd_cwnd = tp->t_maxseg;
3122 * In contrast to the Slow-but-Steady NewReno variant,
3123 * we do not reset the retransmission timer for SACK retransmissions,
3124 * except when retransmitting snd_una.
3127 tcp_sack_rexmt(struct tcpcb *tp, struct tcphdr *th)
3129 uint32_t pipe, seglen;
3132 tcp_seq old_snd_nxt = tp->snd_nxt;
3133 u_long ocwnd = tp->snd_cwnd;
3134 int nseg = 0; /* consecutive new segments */
3135 #define MAXBURST 4 /* limit burst of new packets on partial ack */
3138 pipe = tcp_sack_compute_pipe(tp);
3139 while ((tcp_seq_diff_t)(ocwnd - pipe) >= (tcp_seq_diff_t)tp->t_maxseg &&
3140 (!tcp_do_smartsack || nseg < MAXBURST) &&
3141 tcp_sack_nextseg(tp, &nextrexmt, &seglen, &lostdup)) {
3143 tcp_seq old_snd_max;
3146 if (nextrexmt == tp->snd_max) ++nseg;
3147 tp->snd_nxt = nextrexmt;
3148 tp->snd_cwnd = nextrexmt - tp->snd_una + seglen;
3149 old_snd_max = tp->snd_max;
3150 if (nextrexmt == tp->snd_una)
3151 callout_stop(tp->tt_rexmt);
3152 error = tcp_output(tp);
3155 sent = tp->snd_nxt - nextrexmt;
3160 tcpstat.tcps_sndsackpack++;
3161 tcpstat.tcps_sndsackbyte += sent;
3162 if (SEQ_LT(nextrexmt, old_snd_max) &&
3163 SEQ_LT(tp->rexmt_high, tp->snd_nxt))
3164 tp->rexmt_high = seq_min(tp->snd_nxt, old_snd_max);
3166 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3167 tp->snd_nxt = old_snd_nxt;
3168 tp->snd_cwnd = ocwnd;