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) 2002, 2003, 2004 Jeffrey M. Hsu. All rights reserved.
37 * License terms: all terms for the DragonFly license above plus the following:
39 * 4. All advertising materials mentioning features or use of this software
40 * must display the following acknowledgement:
42 * This product includes software developed by Jeffrey M. Hsu
43 * for the DragonFly Project.
45 * This requirement may be waived with permission from Jeffrey Hsu.
46 * This requirement will sunset and may be removed on July 8 2005,
47 * after which the standard DragonFly license (as shown above) will
52 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
53 * The Regents of the University of California. All rights reserved.
55 * Redistribution and use in source and binary forms, with or without
56 * modification, are permitted provided that the following conditions
58 * 1. Redistributions of source code must retain the above copyright
59 * notice, this list of conditions and the following disclaimer.
60 * 2. Redistributions in binary form must reproduce the above copyright
61 * notice, this list of conditions and the following disclaimer in the
62 * documentation and/or other materials provided with the distribution.
63 * 3. All advertising materials mentioning features or use of this software
64 * must display the following acknowledgement:
65 * This product includes software developed by the University of
66 * California, Berkeley and its contributors.
67 * 4. Neither the name of the University nor the names of its contributors
68 * may be used to endorse or promote products derived from this software
69 * without specific prior written permission.
71 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
72 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
75 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
76 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
77 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
78 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
79 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
80 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
83 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
84 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
85 * $DragonFly: src/sys/netinet/tcp_input.c,v 1.40 2004/11/17 20:51:16 hsu Exp $
88 #include "opt_ipfw.h" /* for ipfw_fwd */
89 #include "opt_inet6.h"
90 #include "opt_ipsec.h"
91 #include "opt_tcpdebug.h"
92 #include "opt_tcp_input.h"
94 #include <sys/param.h>
95 #include <sys/systm.h>
96 #include <sys/kernel.h>
97 #include <sys/sysctl.h>
98 #include <sys/malloc.h>
100 #include <sys/proc.h> /* for proc0 declaration */
101 #include <sys/protosw.h>
102 #include <sys/socket.h>
103 #include <sys/socketvar.h>
104 #include <sys/syslog.h>
105 #include <sys/in_cksum.h>
107 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
108 #include <machine/stdarg.h>
111 #include <net/route.h>
113 #include <netinet/in.h>
114 #include <netinet/in_systm.h>
115 #include <netinet/ip.h>
116 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
117 #include <netinet/in_var.h>
118 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
119 #include <netinet/in_pcb.h>
120 #include <netinet/ip_var.h>
121 #include <netinet/ip6.h>
122 #include <netinet/icmp6.h>
123 #include <netinet6/nd6.h>
124 #include <netinet6/ip6_var.h>
125 #include <netinet6/in6_pcb.h>
126 #include <netinet/tcp.h>
127 #include <netinet/tcp_fsm.h>
128 #include <netinet/tcp_seq.h>
129 #include <netinet/tcp_timer.h>
130 #include <netinet/tcp_var.h>
131 #include <netinet6/tcp6_var.h>
132 #include <netinet/tcpip.h>
135 #include <netinet/tcp_debug.h>
137 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
138 struct tcphdr tcp_savetcp;
142 #include <netproto/ipsec/ipsec.h>
143 #include <netproto/ipsec/ipsec6.h>
147 #include <netinet6/ipsec.h>
148 #include <netinet6/ipsec6.h>
149 #include <netproto/key/key.h>
152 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
155 static int log_in_vain = 0;
156 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
157 &log_in_vain, 0, "Log all incoming TCP connections");
159 static int blackhole = 0;
160 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
161 &blackhole, 0, "Do not send RST when dropping refused connections");
163 int tcp_delack_enabled = 1;
164 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
165 &tcp_delack_enabled, 0,
166 "Delay ACK to try and piggyback it onto a data packet");
168 #ifdef TCP_DROP_SYNFIN
169 static int drop_synfin = 0;
170 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
171 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
174 static int tcp_do_limitedtransmit = 1;
175 SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
176 &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
178 static int tcp_do_early_retransmit = 1;
179 SYSCTL_INT(_net_inet_tcp, OID_AUTO, earlyretransmit, CTLFLAG_RW,
180 &tcp_do_early_retransmit, 0, "Early retransmit");
182 static int tcp_do_rfc3390 = 1;
183 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
185 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
187 static int tcp_do_eifel_detect = 1;
188 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
189 &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
192 * Define as tunable for easy testing with SACK on and off.
193 * Warning: do not change setting in the middle of an existing active TCP flow,
194 * else strange things might happen to that flow.
197 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sack, CTLFLAG_RW,
198 &tcp_do_sack, 0, "Enable SACK Algorithms");
200 int tcp_do_smartsack = 1;
201 SYSCTL_INT(_net_inet_tcp, OID_AUTO, smartsack, CTLFLAG_RW,
202 &tcp_do_smartsack, 0, "Enable Smart SACK Algorithms");
204 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
205 "TCP Segment Reassembly Queue");
207 int tcp_reass_maxseg = 0;
208 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
209 &tcp_reass_maxseg, 0,
210 "Global maximum number of TCP Segments in Reassembly Queue");
212 int tcp_reass_qsize = 0;
213 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
215 "Global number of TCP Segments currently in Reassembly Queue");
217 static int tcp_reass_overflows = 0;
218 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
219 &tcp_reass_overflows, 0,
220 "Global number of TCP Segment Reassembly Queue Overflows");
222 static void tcp_dooptions(struct tcpopt *, u_char *, int, boolean_t);
223 static void tcp_pulloutofband(struct socket *,
224 struct tcphdr *, struct mbuf *, int);
225 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
227 static void tcp_xmit_timer(struct tcpcb *, int);
228 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *, int);
229 static void tcp_sack_rexmt(struct tcpcb *, struct tcphdr *);
231 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
233 #define ND6_HINT(tp) \
235 if ((tp) && (tp)->t_inpcb && \
236 ((tp)->t_inpcb->inp_vflag & INP_IPV6) && \
237 (tp)->t_inpcb->in6p_route.ro_rt) \
238 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
245 * Indicate whether this ack should be delayed. We can delay the ack if
246 * - delayed acks are enabled and
247 * - there is no delayed ack timer in progress and
248 * - our last ack wasn't a 0-sized window. We never want to delay
249 * the ack that opens up a 0-sized window.
251 #define DELAY_ACK(tp) \
252 (tcp_delack_enabled && !callout_pending(tp->tt_delack) && \
253 !(tp->t_flags & TF_RXWIN0SENT))
256 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
259 struct tseg_qent *p = NULL;
260 struct tseg_qent *te;
261 struct socket *so = tp->t_inpcb->inp_socket;
265 * Call with th == NULL after become established to
266 * force pre-ESTABLISHED data up to user socket.
272 * Limit the number of segments in the reassembly queue to prevent
273 * holding on to too many segments (and thus running out of mbufs).
274 * Make sure to let the missing segment through which caused this
275 * queue. Always keep one global queue entry spare to be able to
276 * process the missing segment.
278 if (th->th_seq != tp->rcv_nxt &&
279 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
280 tcp_reass_overflows++;
281 tcpstat.tcps_rcvmemdrop++;
283 /* no SACK block to report */
284 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
288 /* Allocate a new queue entry. */
289 MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
290 M_INTWAIT | M_NULLOK);
292 tcpstat.tcps_rcvmemdrop++;
294 /* no SACK block to report */
295 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
301 * Find a segment which begins after this one does.
303 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
304 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
310 * If there is a preceding segment, it may provide some of
311 * our data already. If so, drop the data from the incoming
312 * segment. If it provides all of our data, drop us.
317 /* conversion to int (in i) handles seq wraparound */
318 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
319 if (i > 0) { /* overlaps preceding segment */
320 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
321 /* enclosing block starts w/ preceding segment */
322 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
324 /* preceding encloses incoming segment */
325 tp->encloseblk.rblk_end = p->tqe_th->th_seq +
327 tcpstat.tcps_rcvduppack++;
328 tcpstat.tcps_rcvdupbyte += *tlenp;
333 * Try to present any queued data
334 * at the left window edge to the user.
335 * This is needed after the 3-WHS
338 goto present; /* ??? */
343 /* incoming segment end is enclosing block end */
344 tp->encloseblk.rblk_end = th->th_seq + *tlenp +
345 ((th->th_flags & TH_FIN) != 0);
346 /* trim end of reported D-SACK block */
347 tp->reportblk.rblk_end = th->th_seq;
350 tcpstat.tcps_rcvoopack++;
351 tcpstat.tcps_rcvoobyte += *tlenp;
354 * While we overlap succeeding segments trim them or,
355 * if they are completely covered, dequeue them.
358 int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
359 tcp_seq qend = q->tqe_th->th_seq + q->tqe_len;
360 struct tseg_qent *nq;
364 if (!(tp->t_flags & TF_DUPSEG)) { /* first time through */
365 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
366 tp->encloseblk = tp->reportblk;
367 /* report trailing duplicate D-SACK segment */
368 tp->reportblk.rblk_start = q->tqe_th->th_seq;
370 if ((tp->t_flags & TF_ENCLOSESEG) &&
371 SEQ_GT(qend, tp->encloseblk.rblk_end)) {
372 /* extend enclosing block if one exists */
373 tp->encloseblk.rblk_end = qend;
375 if (i < q->tqe_len) {
376 q->tqe_th->th_seq += i;
382 nq = LIST_NEXT(q, tqe_q);
383 LIST_REMOVE(q, tqe_q);
390 /* Insert the new segment queue entry into place. */
393 te->tqe_len = *tlenp;
395 /* check if can coalesce with following segment */
396 if (q != NULL && (th->th_seq + *tlenp == q->tqe_th->th_seq)) {
397 tcp_seq tend = te->tqe_th->th_seq + te->tqe_len;
399 te->tqe_len += q->tqe_len;
400 if (q->tqe_th->th_flags & TH_FIN)
401 te->tqe_th->th_flags &= TH_FIN;
402 m_cat(te->tqe_m, q->tqe_m);
403 tp->encloseblk.rblk_end = tend;
405 * When not reporting a duplicate segment, use
406 * the larger enclosing block as the SACK block.
408 if (!(tp->t_flags & TF_DUPSEG))
409 tp->reportblk.rblk_end = tend;
410 LIST_REMOVE(q, tqe_q);
416 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
418 /* check if can coalesce with preceding segment */
419 if (p->tqe_th->th_seq + p->tqe_len == th->th_seq) {
420 p->tqe_len += te->tqe_len;
421 m_cat(p->tqe_m, te->tqe_m);
422 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
424 * When not reporting a duplicate segment, use
425 * the larger enclosing block as the SACK block.
427 if (!(tp->t_flags & TF_DUPSEG))
428 tp->reportblk.rblk_start = p->tqe_th->th_seq;
432 LIST_INSERT_AFTER(p, te, tqe_q);
437 * Present data to user, advancing rcv_nxt through
438 * completed sequence space.
440 if (!TCPS_HAVEESTABLISHED(tp->t_state))
442 q = LIST_FIRST(&tp->t_segq);
443 if (q == NULL || q->tqe_th->th_seq != tp->rcv_nxt)
445 tp->rcv_nxt += q->tqe_len;
446 if (!(tp->t_flags & TF_DUPSEG)) {
447 /* no SACK block to report since ACK advanced */
448 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
450 /* no enclosing block to report since ACK advanced */
451 tp->t_flags &= ~TF_ENCLOSESEG;
452 flags = q->tqe_th->th_flags & TH_FIN;
453 LIST_REMOVE(q, tqe_q);
454 KASSERT(LIST_EMPTY(&tp->t_segq) ||
455 LIST_FIRST(&tp->t_segq)->tqe_th->th_seq != tp->rcv_nxt,
456 ("segment not coalesced"));
457 if (so->so_state & SS_CANTRCVMORE)
460 sbappend(&so->so_rcv, q->tqe_m);
469 * TCP input routine, follows pages 65-76 of the
470 * protocol specification dated September, 1981 very closely.
474 tcp6_input(struct mbuf **mp, int *offp, int proto)
476 struct mbuf *m = *mp;
477 struct in6_ifaddr *ia6;
479 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
482 * draft-itojun-ipv6-tcp-to-anycast
483 * better place to put this in?
485 ia6 = ip6_getdstifaddr(m);
486 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
489 ip6 = mtod(m, struct ip6_hdr *);
490 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
491 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
492 return (IPPROTO_DONE);
495 tcp_input(m, *offp, proto);
496 return (IPPROTO_DONE);
501 tcp_input(struct mbuf *m, ...)
506 struct ip *ip = NULL;
508 struct inpcb *inp = NULL;
513 struct tcpcb *tp = NULL;
515 struct socket *so = 0;
517 boolean_t ourfinisacked, needoutput = FALSE;
520 struct tcpopt to; /* options in this segment */
521 struct rmxp_tao *taop; /* pointer to our TAO cache entry */
522 struct rmxp_tao tao_noncached; /* in case there's no cached entry */
523 struct sockaddr_in *next_hop = NULL;
524 int rstreason; /* For badport_bandlim accounting purposes */
526 struct ip6_hdr *ip6 = NULL;
530 const boolean_t isipv6 = FALSE;
537 off0 = __va_arg(ap, int);
538 proto = __va_arg(ap, int);
541 tcpstat.tcps_rcvtotal++;
543 /* Grab info from and strip MT_TAG mbufs prepended to the chain. */
544 while (m->m_type == MT_TAG) {
545 if (m->_m_tag_id == PACKET_TAG_IPFORWARD)
546 next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
551 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
555 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
556 ip6 = mtod(m, struct ip6_hdr *);
557 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
558 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
559 tcpstat.tcps_rcvbadsum++;
562 th = (struct tcphdr *)((caddr_t)ip6 + off0);
565 * Be proactive about unspecified IPv6 address in source.
566 * As we use all-zero to indicate unbounded/unconnected pcb,
567 * unspecified IPv6 address can be used to confuse us.
569 * Note that packets with unspecified IPv6 destination is
570 * already dropped in ip6_input.
572 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
578 * Get IP and TCP header together in first mbuf.
579 * Note: IP leaves IP header in first mbuf.
581 if (off0 > sizeof(struct ip)) {
583 off0 = sizeof(struct ip);
585 /* already checked and pulled up in ip_demux() */
586 KASSERT(m->m_len >= sizeof(struct tcpiphdr),
587 ("TCP header not in one mbuf: m->m_len %d", m->m_len));
588 ip = mtod(m, struct ip *);
589 ipov = (struct ipovly *)ip;
590 th = (struct tcphdr *)((caddr_t)ip + off0);
593 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
594 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
595 th->th_sum = m->m_pkthdr.csum_data;
597 th->th_sum = in_pseudo(ip->ip_src.s_addr,
599 htonl(m->m_pkthdr.csum_data +
602 th->th_sum ^= 0xffff;
605 * Checksum extended TCP header and data.
607 len = sizeof(struct ip) + tlen;
608 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
609 ipov->ih_len = (u_short)tlen;
610 ipov->ih_len = htons(ipov->ih_len);
611 th->th_sum = in_cksum(m, len);
614 tcpstat.tcps_rcvbadsum++;
618 /* Re-initialization for later version check */
619 ip->ip_v = IPVERSION;
624 * Check that TCP offset makes sense,
625 * pull out TCP options and adjust length. XXX
627 off = th->th_off << 2;
628 /* already checked and pulled up in ip_demux() */
629 KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
630 ("bad TCP data offset %d (tlen %d)", off, tlen));
631 tlen -= off; /* tlen is used instead of ti->ti_len */
632 if (off > sizeof(struct tcphdr)) {
634 IP6_EXTHDR_CHECK(m, off0, off, );
635 ip6 = mtod(m, struct ip6_hdr *);
636 th = (struct tcphdr *)((caddr_t)ip6 + off0);
638 /* already pulled up in ip_demux() */
639 KASSERT(m->m_len >= sizeof(struct ip) + off,
640 ("TCP header and options not in one mbuf: "
641 "m_len %d, off %d", m->m_len, off));
643 optlen = off - sizeof(struct tcphdr);
644 optp = (u_char *)(th + 1);
646 thflags = th->th_flags;
648 #ifdef TCP_DROP_SYNFIN
650 * If the drop_synfin option is enabled, drop all packets with
651 * both the SYN and FIN bits set. This prevents e.g. nmap from
652 * identifying the TCP/IP stack.
654 * This is a violation of the TCP specification.
656 if (drop_synfin && (thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN))
661 * Convert TCP protocol specific fields to host format.
663 th->th_seq = ntohl(th->th_seq);
664 th->th_ack = ntohl(th->th_ack);
665 th->th_win = ntohs(th->th_win);
666 th->th_urp = ntohs(th->th_urp);
669 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
670 * until after ip6_savecontrol() is called and before other functions
671 * which don't want those proto headers.
672 * Because ip6_savecontrol() is going to parse the mbuf to
673 * search for data to be passed up to user-land, it wants mbuf
674 * parameters to be unchanged.
675 * XXX: the call of ip6_savecontrol() has been obsoleted based on
676 * latest version of the advanced API (20020110).
678 drop_hdrlen = off0 + off;
681 * Locate pcb for segment.
684 /* IPFIREWALL_FORWARD section */
685 if (next_hop != NULL && !isipv6) { /* IPv6 support is not there yet */
687 * Transparently forwarded. Pretend to be the destination.
688 * already got one like this?
690 cpu = mycpu->gd_cpuid;
691 inp = in_pcblookup_hash(&tcbinfo[cpu],
692 ip->ip_src, th->th_sport,
693 ip->ip_dst, th->th_dport,
694 0, m->m_pkthdr.rcvif);
697 * It's new. Try to find the ambushing socket.
701 * The rest of the ipfw code stores the port in
703 * (The IP address is still in network order.)
705 in_port_t dport = next_hop->sin_port ?
706 htons(next_hop->sin_port) :
709 cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
710 next_hop->sin_addr.s_addr, dport);
711 inp = in_pcblookup_hash(&tcbinfo[cpu],
712 ip->ip_src, th->th_sport,
713 next_hop->sin_addr, dport,
714 1, m->m_pkthdr.rcvif);
718 inp = in6_pcblookup_hash(&tcbinfo[0],
719 &ip6->ip6_src, th->th_sport,
720 &ip6->ip6_dst, th->th_dport,
721 1, m->m_pkthdr.rcvif);
723 cpu = mycpu->gd_cpuid;
724 inp = in_pcblookup_hash(&tcbinfo[cpu],
725 ip->ip_src, th->th_sport,
726 ip->ip_dst, th->th_dport,
727 1, m->m_pkthdr.rcvif);
732 * If the state is CLOSED (i.e., TCB does not exist) then
733 * all data in the incoming segment is discarded.
734 * If the TCB exists but is in CLOSED state, it is embryonic,
735 * but should either do a listen or a connect soon.
740 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
742 char dbuf[4 * sizeof "123"], sbuf[4 * sizeof "123"];
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))
811 rstreason = BANDLIM_RST_CLOSEDPORT;
814 if (tp->t_state <= TCPS_CLOSED)
817 /* Unscale the window into a 32-bit value. */
818 if (!(thflags & TH_SYN))
819 tiwin = th->th_win << tp->snd_scale;
823 so = inp->inp_socket;
826 if (so->so_options & SO_DEBUG) {
827 ostate = tp->t_state;
829 bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
831 bcopy(ip, tcp_saveipgen, sizeof(*ip));
836 bzero(&to, sizeof(to));
838 if (so->so_options & SO_ACCEPTCONN) {
839 struct in_conninfo inc;
842 inc.inc_isipv6 = (isipv6 == TRUE);
845 inc.inc6_faddr = ip6->ip6_src;
846 inc.inc6_laddr = ip6->ip6_dst;
847 inc.inc6_route.ro_rt = NULL; /* XXX */
849 inc.inc_faddr = ip->ip_src;
850 inc.inc_laddr = ip->ip_dst;
851 inc.inc_route.ro_rt = NULL; /* XXX */
853 inc.inc_fport = th->th_sport;
854 inc.inc_lport = th->th_dport;
857 * If the state is LISTEN then ignore segment if it contains
858 * a RST. If the segment contains an ACK then it is bad and
859 * send a RST. If it does not contain a SYN then it is not
860 * interesting; drop it.
862 * If the state is SYN_RECEIVED (syncache) and seg contains
863 * an ACK, but not for our SYN/ACK, send a RST. If the seg
864 * contains a RST, check the sequence number to see if it
865 * is a valid reset segment.
867 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
868 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) == TH_ACK) {
869 if (!syncache_expand(&inc, th, &so, m)) {
871 * No syncache entry, or ACK was not
872 * for our SYN/ACK. Send a RST.
874 tcpstat.tcps_badsyn++;
875 rstreason = BANDLIM_RST_OPENPORT;
880 * Could not complete 3-way handshake,
881 * connection is being closed down, and
882 * syncache will free mbuf.
886 * Socket is created in state SYN_RECEIVED.
887 * Continue processing segment.
892 * This is what would have happened in
893 * tcp_output() when the SYN,ACK was sent.
895 tp->snd_up = tp->snd_una;
896 tp->snd_max = tp->snd_nxt = tp->iss + 1;
897 tp->last_ack_sent = tp->rcv_nxt;
899 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
900 * until the _second_ ACK is received:
901 * rcv SYN (set wscale opts) --> send SYN/ACK, set snd_wnd = window.
902 * rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
903 * move to ESTAB, set snd_wnd to tiwin.
905 tp->snd_wnd = tiwin; /* unscaled */
908 if (thflags & TH_RST) {
909 syncache_chkrst(&inc, th);
912 if (thflags & TH_ACK) {
913 syncache_badack(&inc);
914 tcpstat.tcps_badsyn++;
915 rstreason = BANDLIM_RST_OPENPORT;
922 * Segment's flags are (SYN) or (SYN | FIN).
926 * If deprecated address is forbidden,
927 * we do not accept SYN to deprecated interface
928 * address to prevent any new inbound connection from
929 * getting established.
930 * When we do not accept SYN, we send a TCP RST,
931 * with deprecated source address (instead of dropping
932 * it). We compromise it as it is much better for peer
933 * to send a RST, and RST will be the final packet
936 * If we do not forbid deprecated addresses, we accept
937 * the SYN packet. RFC2462 does not suggest dropping
939 * If we decipher RFC2462 5.5.4, it says like this:
940 * 1. use of deprecated addr with existing
941 * communication is okay - "SHOULD continue to be
943 * 2. use of it with new communication:
944 * (2a) "SHOULD NOT be used if alternate address
945 * with sufficient scope is available"
946 * (2b) nothing mentioned otherwise.
947 * Here we fall into (2b) case as we have no choice in
948 * our source address selection - we must obey the peer.
950 * The wording in RFC2462 is confusing, and there are
951 * multiple description text for deprecated address
952 * handling - worse, they are not exactly the same.
953 * I believe 5.5.4 is the best one, so we follow 5.5.4.
955 if (isipv6 && !ip6_use_deprecated) {
956 struct in6_ifaddr *ia6;
958 if ((ia6 = ip6_getdstifaddr(m)) &&
959 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
961 rstreason = BANDLIM_RST_OPENPORT;
967 * If it is from this socket, drop it, it must be forged.
968 * Don't bother responding if the destination was a broadcast.
970 if (th->th_dport == th->th_sport) {
972 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
976 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
981 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
983 * Note that it is quite possible to receive unicast
984 * link-layer packets with a broadcast IP address. Use
985 * in_broadcast() to find them.
987 if (m->m_flags & (M_BCAST | M_MCAST))
990 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
991 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
994 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
995 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
996 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
997 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1001 * SYN appears to be valid; create compressed TCP state
1002 * for syncache, or perform t/tcp connection.
1004 if (so->so_qlen <= so->so_qlimit) {
1005 tcp_dooptions(&to, optp, optlen, TRUE);
1006 if (!syncache_add(&inc, &to, th, &so, m))
1010 * Entry added to syncache, mbuf used to
1011 * send SYN,ACK packet.
1015 * Segment passed TAO tests.
1017 inp = sotoinpcb(so);
1018 tp = intotcpcb(inp);
1019 tp->snd_wnd = tiwin;
1020 tp->t_starttime = ticks;
1021 tp->t_state = TCPS_ESTABLISHED;
1024 * If there is a FIN, or if there is data and the
1025 * connection is local, then delay SYN,ACK(SYN) in
1026 * the hope of piggy-backing it on a response
1027 * segment. Otherwise must send ACK now in case
1028 * the other side is slow starting.
1030 if (DELAY_ACK(tp) &&
1031 ((thflags & TH_FIN) ||
1033 ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
1034 (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
1035 callout_reset(tp->tt_delack, tcp_delacktime,
1036 tcp_timer_delack, tp);
1037 tp->t_flags |= TF_NEEDSYN;
1039 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1041 tcpstat.tcps_connects++;
1049 /* should not happen - syncache should pick up these connections */
1050 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN state"));
1053 * Segment received on connection.
1054 * Reset idle time and keep-alive timer.
1056 tp->t_rcvtime = ticks;
1057 if (TCPS_HAVEESTABLISHED(tp->t_state))
1058 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
1062 * XXX this is tradtitional behavior, may need to be cleaned up.
1064 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0);
1065 if (thflags & TH_SYN) {
1066 if (to.to_flags & TOF_SCALE) {
1067 tp->t_flags |= TF_RCVD_SCALE;
1068 tp->requested_s_scale = to.to_requested_s_scale;
1070 if (to.to_flags & TOF_TS) {
1071 tp->t_flags |= TF_RCVD_TSTMP;
1072 tp->ts_recent = to.to_tsval;
1073 tp->ts_recent_age = ticks;
1075 if (to.to_flags & (TOF_CC | TOF_CCNEW))
1076 tp->t_flags |= TF_RCVD_CC;
1077 if (to.to_flags & TOF_MSS)
1078 tcp_mss(tp, to.to_mss);
1080 * Only set the TF_SACK_PERMITTED per-connection flag
1081 * if we got a SACK_PERMITTED option from the other side
1082 * and the global tcp_do_sack variable is true.
1084 if (tcp_do_sack && (to.to_flags & TOF_SACK_PERMITTED))
1085 tp->t_flags |= TF_SACK_PERMITTED;
1089 * Header prediction: check for the two common cases
1090 * of a uni-directional data xfer. If the packet has
1091 * no control flags, is in-sequence, the window didn't
1092 * change and we're not retransmitting, it's a
1093 * candidate. If the length is zero and the ack moved
1094 * forward, we're the sender side of the xfer. Just
1095 * free the data acked & wake any higher level process
1096 * that was blocked waiting for space. If the length
1097 * is non-zero and the ack didn't move, we're the
1098 * receiver side. If we're getting packets in-order
1099 * (the reassembly queue is empty), add the data to
1100 * the socket buffer and note that we need a delayed ack.
1101 * Make sure that the hidden state-flags are also off.
1102 * Since we check for TCPS_ESTABLISHED above, it can only
1105 if (tp->t_state == TCPS_ESTABLISHED &&
1106 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1107 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1108 (!(to.to_flags & TOF_TS) ||
1109 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1111 * Using the CC option is compulsory if once started:
1112 * the segment is OK if no T/TCP was negotiated or
1113 * if the segment has a CC option equal to CCrecv
1115 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
1116 ((to.to_flags & TOF_CC) && to.to_cc == tp->cc_recv)) &&
1117 th->th_seq == tp->rcv_nxt &&
1118 tiwin && tiwin == tp->snd_wnd &&
1119 tp->snd_nxt == tp->snd_max) {
1122 * If last ACK falls within this segment's sequence numbers,
1123 * record the timestamp.
1124 * NOTE that the test is modified according to the latest
1125 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1127 if ((to.to_flags & TOF_TS) &&
1128 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1129 tp->ts_recent_age = ticks;
1130 tp->ts_recent = to.to_tsval;
1134 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1135 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1136 tp->snd_cwnd >= tp->snd_wnd &&
1137 !IN_FASTRECOVERY(tp)) {
1139 * this is a pure ack for outstanding data.
1141 ++tcpstat.tcps_predack;
1143 * "bad retransmit" recovery
1145 * If Eifel detection applies, then
1146 * it is deterministic, so use it
1147 * unconditionally over the old heuristic.
1148 * Otherwise, fall back to the old heuristic.
1150 if (tcp_do_eifel_detect &&
1151 (to.to_flags & TOF_TS) && to.to_tsecr &&
1152 (tp->t_flags & TF_FIRSTACCACK)) {
1153 /* Eifel detection applicable. */
1154 if (to.to_tsecr < tp->t_rexmtTS) {
1155 tcp_revert_congestion_state(tp);
1156 ++tcpstat.tcps_eifeldetected;
1158 } else if (tp->t_rxtshift == 1 &&
1159 ticks < tp->t_badrxtwin) {
1160 tcp_revert_congestion_state(tp);
1161 ++tcpstat.tcps_rttdetected;
1163 tp->t_flags &= ~(TF_FIRSTACCACK |
1164 TF_FASTREXMT | TF_EARLYREXMT);
1166 * Recalculate the retransmit timer / rtt.
1168 * Some machines (certain windows boxes)
1169 * send broken timestamp replies during the
1170 * SYN+ACK phase, ignore timestamps of 0.
1172 if ((to.to_flags & TOF_TS) && to.to_tsecr) {
1174 ticks - to.to_tsecr + 1);
1175 } else if (tp->t_rtttime &&
1176 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1178 ticks - tp->t_rtttime);
1180 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1181 acked = th->th_ack - tp->snd_una;
1182 tcpstat.tcps_rcvackpack++;
1183 tcpstat.tcps_rcvackbyte += acked;
1184 sbdrop(&so->so_snd, acked);
1185 tp->snd_recover = th->th_ack - 1;
1186 tp->snd_una = th->th_ack;
1189 ND6_HINT(tp); /* some progress has been done */
1192 * If all outstanding data are acked, stop
1193 * retransmit timer, otherwise restart timer
1194 * using current (possibly backed-off) value.
1195 * If process is waiting for space,
1196 * wakeup/selwakeup/signal. If data
1197 * are ready to send, let tcp_output
1198 * decide between more output or persist.
1200 if (tp->snd_una == tp->snd_max)
1201 callout_stop(tp->tt_rexmt);
1202 else if (!callout_active(tp->tt_persist))
1203 callout_reset(tp->tt_rexmt,
1205 tcp_timer_rexmt, tp);
1208 if (so->so_snd.sb_cc)
1209 (void) tcp_output(tp);
1212 } else if (th->th_ack == tp->snd_una &&
1213 LIST_EMPTY(&tp->t_segq) &&
1214 tlen <= sbspace(&so->so_rcv)) {
1216 * this is a pure, in-sequence data packet
1217 * with nothing on the reassembly queue and
1218 * we have enough buffer space to take it.
1220 ++tcpstat.tcps_preddat;
1221 tp->rcv_nxt += tlen;
1222 tcpstat.tcps_rcvpack++;
1223 tcpstat.tcps_rcvbyte += tlen;
1224 ND6_HINT(tp); /* some progress has been done */
1226 * Add data to socket buffer.
1228 if (so->so_state & SS_CANTRCVMORE) {
1231 m_adj(m, drop_hdrlen); /* delayed header drop */
1232 sbappend(&so->so_rcv, m);
1237 * This code is responsible for most of the ACKs
1238 * the TCP stack sends back after receiving a data
1239 * packet. Note that the DELAY_ACK check fails if
1240 * the delack timer is already running, which results
1241 * in an ack being sent every other packet (which is
1244 if (DELAY_ACK(tp)) {
1245 callout_reset(tp->tt_delack, tcp_delacktime,
1246 tcp_timer_delack, tp);
1248 tp->t_flags |= TF_ACKNOW;
1249 if (!(tp->t_flags & TF_ONOUTPUTQ)) {
1250 tp->t_flags |= TF_ONOUTPUTQ;
1251 tp->tt_cpu = mycpu->gd_cpuid;
1253 &tcpcbackq[tp->tt_cpu],
1262 * Calculate amount of space in receive window,
1263 * and then do TCP input processing.
1264 * Receive window is amount of space in rcv queue,
1265 * but not less than advertised window.
1267 recvwin = sbspace(&so->so_rcv);
1270 tp->rcv_wnd = imax(recvwin, (int)(tp->rcv_adv - tp->rcv_nxt));
1272 switch (tp->t_state) {
1274 * If the state is SYN_RECEIVED:
1275 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1277 case TCPS_SYN_RECEIVED:
1278 if ((thflags & TH_ACK) &&
1279 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1280 SEQ_GT(th->th_ack, tp->snd_max))) {
1281 rstreason = BANDLIM_RST_OPENPORT;
1287 * If the state is SYN_SENT:
1288 * if seg contains an ACK, but not for our SYN, drop the input.
1289 * if seg contains a RST, then drop the connection.
1290 * if seg does not contain SYN, then drop it.
1291 * Otherwise this is an acceptable SYN segment
1292 * initialize tp->rcv_nxt and tp->irs
1293 * if seg contains ack then advance tp->snd_una
1294 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1295 * arrange for segment to be acked (eventually)
1296 * continue processing rest of data/controls, beginning with URG
1299 if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1300 taop = &tao_noncached;
1301 bzero(taop, sizeof(*taop));
1304 if ((thflags & TH_ACK) &&
1305 (SEQ_LEQ(th->th_ack, tp->iss) ||
1306 SEQ_GT(th->th_ack, tp->snd_max))) {
1308 * If we have a cached CCsent for the remote host,
1309 * hence we haven't just crashed and restarted,
1310 * do not send a RST. This may be a retransmission
1311 * from the other side after our earlier ACK was lost.
1312 * Our new SYN, when it arrives, will serve as the
1315 if (taop->tao_ccsent != 0)
1318 rstreason = BANDLIM_UNLIMITED;
1322 if (thflags & TH_RST) {
1323 if (thflags & TH_ACK)
1324 tp = tcp_drop(tp, ECONNREFUSED);
1327 if (!(thflags & TH_SYN))
1329 tp->snd_wnd = th->th_win; /* initial send window */
1330 tp->cc_recv = to.to_cc; /* foreign CC */
1332 tp->irs = th->th_seq;
1334 if (thflags & TH_ACK) {
1336 * Our SYN was acked. If segment contains CC.ECHO
1337 * option, check it to make sure this segment really
1338 * matches our SYN. If not, just drop it as old
1339 * duplicate, but send an RST if we're still playing
1340 * by the old rules. If no CC.ECHO option, make sure
1341 * we don't get fooled into using T/TCP.
1343 if (to.to_flags & TOF_CCECHO) {
1344 if (tp->cc_send != to.to_ccecho) {
1345 if (taop->tao_ccsent != 0)
1348 rstreason = BANDLIM_UNLIMITED;
1353 tp->t_flags &= ~TF_RCVD_CC;
1354 tcpstat.tcps_connects++;
1356 /* Do window scaling on this connection? */
1357 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1358 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1359 tp->snd_scale = tp->requested_s_scale;
1360 tp->rcv_scale = tp->request_r_scale;
1362 /* Segment is acceptable, update cache if undefined. */
1363 if (taop->tao_ccsent == 0)
1364 taop->tao_ccsent = to.to_ccecho;
1366 tp->rcv_adv += tp->rcv_wnd;
1367 tp->snd_una++; /* SYN is acked */
1368 callout_stop(tp->tt_rexmt);
1370 * If there's data, delay ACK; if there's also a FIN
1371 * ACKNOW will be turned on later.
1373 if (DELAY_ACK(tp) && tlen != 0)
1374 callout_reset(tp->tt_delack, tcp_delacktime,
1375 tcp_timer_delack, tp);
1377 tp->t_flags |= TF_ACKNOW;
1379 * Received <SYN,ACK> in SYN_SENT[*] state.
1381 * SYN_SENT --> ESTABLISHED
1382 * SYN_SENT* --> FIN_WAIT_1
1384 tp->t_starttime = ticks;
1385 if (tp->t_flags & TF_NEEDFIN) {
1386 tp->t_state = TCPS_FIN_WAIT_1;
1387 tp->t_flags &= ~TF_NEEDFIN;
1390 tp->t_state = TCPS_ESTABLISHED;
1391 callout_reset(tp->tt_keep, tcp_keepidle,
1392 tcp_timer_keep, tp);
1396 * Received initial SYN in SYN-SENT[*] state =>
1397 * simultaneous open. If segment contains CC option
1398 * and there is a cached CC, apply TAO test.
1399 * If it succeeds, connection is * half-synchronized.
1400 * Otherwise, do 3-way handshake:
1401 * SYN-SENT -> SYN-RECEIVED
1402 * SYN-SENT* -> SYN-RECEIVED*
1403 * If there was no CC option, clear cached CC value.
1405 tp->t_flags |= TF_ACKNOW;
1406 callout_stop(tp->tt_rexmt);
1407 if (to.to_flags & TOF_CC) {
1408 if (taop->tao_cc != 0 &&
1409 CC_GT(to.to_cc, taop->tao_cc)) {
1411 * update cache and make transition:
1412 * SYN-SENT -> ESTABLISHED*
1413 * SYN-SENT* -> FIN-WAIT-1*
1415 taop->tao_cc = to.to_cc;
1416 tp->t_starttime = ticks;
1417 if (tp->t_flags & TF_NEEDFIN) {
1418 tp->t_state = TCPS_FIN_WAIT_1;
1419 tp->t_flags &= ~TF_NEEDFIN;
1421 tp->t_state = TCPS_ESTABLISHED;
1422 callout_reset(tp->tt_keep,
1427 tp->t_flags |= TF_NEEDSYN;
1429 tp->t_state = TCPS_SYN_RECEIVED;
1431 /* CC.NEW or no option => invalidate cache */
1433 tp->t_state = TCPS_SYN_RECEIVED;
1439 * Advance th->th_seq to correspond to first data byte.
1440 * If data, trim to stay within window,
1441 * dropping FIN if necessary.
1444 if (tlen > tp->rcv_wnd) {
1445 todrop = tlen - tp->rcv_wnd;
1449 tcpstat.tcps_rcvpackafterwin++;
1450 tcpstat.tcps_rcvbyteafterwin += todrop;
1452 tp->snd_wl1 = th->th_seq - 1;
1453 tp->rcv_up = th->th_seq;
1455 * Client side of transaction: already sent SYN and data.
1456 * If the remote host used T/TCP to validate the SYN,
1457 * our data will be ACK'd; if so, enter normal data segment
1458 * processing in the middle of step 5, ack processing.
1459 * Otherwise, goto step 6.
1461 if (thflags & TH_ACK)
1467 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1468 * if segment contains a SYN and CC [not CC.NEW] option:
1469 * if state == TIME_WAIT and connection duration > MSL,
1470 * drop packet and send RST;
1472 * if SEG.CC > CCrecv then is new SYN, and can implicitly
1473 * ack the FIN (and data) in retransmission queue.
1474 * Complete close and delete TCPCB. Then reprocess
1475 * segment, hoping to find new TCPCB in LISTEN state;
1477 * else must be old SYN; drop it.
1478 * else do normal processing.
1482 case TCPS_TIME_WAIT:
1483 if ((thflags & TH_SYN) &&
1484 (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1485 if (tp->t_state == TCPS_TIME_WAIT &&
1486 (ticks - tp->t_starttime) > tcp_msl) {
1487 rstreason = BANDLIM_UNLIMITED;
1490 if (CC_GT(to.to_cc, tp->cc_recv)) {
1497 break; /* continue normal processing */
1501 * States other than LISTEN or SYN_SENT.
1502 * First check the RST flag and sequence number since reset segments
1503 * are exempt from the timestamp and connection count tests. This
1504 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1505 * below which allowed reset segments in half the sequence space
1506 * to fall though and be processed (which gives forged reset
1507 * segments with a random sequence number a 50 percent chance of
1508 * killing a connection).
1509 * Then check timestamp, if present.
1510 * Then check the connection count, if present.
1511 * Then check that at least some bytes of segment are within
1512 * receive window. If segment begins before rcv_nxt,
1513 * drop leading data (and SYN); if nothing left, just ack.
1516 * If the RST bit is set, check the sequence number to see
1517 * if this is a valid reset segment.
1519 * In all states except SYN-SENT, all reset (RST) segments
1520 * are validated by checking their SEQ-fields. A reset is
1521 * valid if its sequence number is in the window.
1522 * Note: this does not take into account delayed ACKs, so
1523 * we should test against last_ack_sent instead of rcv_nxt.
1524 * The sequence number in the reset segment is normally an
1525 * echo of our outgoing acknowledgement numbers, but some hosts
1526 * send a reset with the sequence number at the rightmost edge
1527 * of our receive window, and we have to handle this case.
1528 * If we have multiple segments in flight, the intial reset
1529 * segment sequence numbers will be to the left of last_ack_sent,
1530 * but they will eventually catch up.
1531 * In any case, it never made sense to trim reset segments to
1532 * fit the receive window since RFC 1122 says:
1533 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1535 * A TCP SHOULD allow a received RST segment to include data.
1538 * It has been suggested that a RST segment could contain
1539 * ASCII text that encoded and explained the cause of the
1540 * RST. No standard has yet been established for such
1543 * If the reset segment passes the sequence number test examine
1545 * SYN_RECEIVED STATE:
1546 * If passive open, return to LISTEN state.
1547 * If active open, inform user that connection was refused.
1548 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1549 * Inform user that connection was reset, and close tcb.
1550 * CLOSING, LAST_ACK STATES:
1553 * Drop the segment - see Stevens, vol. 2, p. 964 and
1556 if (thflags & TH_RST) {
1557 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1558 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1559 switch (tp->t_state) {
1561 case TCPS_SYN_RECEIVED:
1562 so->so_error = ECONNREFUSED;
1565 case TCPS_ESTABLISHED:
1566 case TCPS_FIN_WAIT_1:
1567 case TCPS_FIN_WAIT_2:
1568 case TCPS_CLOSE_WAIT:
1569 so->so_error = ECONNRESET;
1571 tp->t_state = TCPS_CLOSED;
1572 tcpstat.tcps_drops++;
1581 case TCPS_TIME_WAIT:
1589 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1590 * and it's less than ts_recent, drop it.
1592 if ((to.to_flags & TOF_TS) && tp->ts_recent != 0 &&
1593 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1595 /* Check to see if ts_recent is over 24 days old. */
1596 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1598 * Invalidate ts_recent. If this segment updates
1599 * ts_recent, the age will be reset later and ts_recent
1600 * will get a valid value. If it does not, setting
1601 * ts_recent to zero will at least satisfy the
1602 * requirement that zero be placed in the timestamp
1603 * echo reply when ts_recent isn't valid. The
1604 * age isn't reset until we get a valid ts_recent
1605 * because we don't want out-of-order segments to be
1606 * dropped when ts_recent is old.
1610 tcpstat.tcps_rcvduppack++;
1611 tcpstat.tcps_rcvdupbyte += tlen;
1612 tcpstat.tcps_pawsdrop++;
1621 * If T/TCP was negotiated and the segment doesn't have CC,
1622 * or if its CC is wrong then drop the segment.
1623 * RST segments do not have to comply with this.
1625 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1626 (!(to.to_flags & TOF_CC) || tp->cc_recv != to.to_cc))
1630 * In the SYN-RECEIVED state, validate that the packet belongs to
1631 * this connection before trimming the data to fit the receive
1632 * window. Check the sequence number versus IRS since we know
1633 * the sequence numbers haven't wrapped. This is a partial fix
1634 * for the "LAND" DoS attack.
1636 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1637 rstreason = BANDLIM_RST_OPENPORT;
1641 todrop = tp->rcv_nxt - th->th_seq;
1643 if (TCP_DO_SACK(tp)) {
1644 /* Report duplicate segment at head of packet. */
1645 tp->reportblk.rblk_start = th->th_seq;
1646 tp->reportblk.rblk_end = th->th_seq + tlen;
1647 if (thflags & TH_FIN)
1648 ++tp->reportblk.rblk_end;
1649 if (SEQ_GT(tp->reportblk.rblk_end, tp->rcv_nxt))
1650 tp->reportblk.rblk_end = tp->rcv_nxt;
1651 tp->t_flags |= (TF_DUPSEG | TF_SACKLEFT | TF_ACKNOW);
1653 if (thflags & TH_SYN) {
1663 * Following if statement from Stevens, vol. 2, p. 960.
1665 if (todrop > tlen ||
1666 (todrop == tlen && !(thflags & TH_FIN))) {
1668 * Any valid FIN must be to the left of the window.
1669 * At this point the FIN must be a duplicate or out
1670 * of sequence; drop it.
1675 * Send an ACK to resynchronize and drop any data.
1676 * But keep on processing for RST or ACK.
1678 tp->t_flags |= TF_ACKNOW;
1680 tcpstat.tcps_rcvduppack++;
1681 tcpstat.tcps_rcvdupbyte += todrop;
1683 tcpstat.tcps_rcvpartduppack++;
1684 tcpstat.tcps_rcvpartdupbyte += todrop;
1686 drop_hdrlen += todrop; /* drop from the top afterwards */
1687 th->th_seq += todrop;
1689 if (th->th_urp > todrop)
1690 th->th_urp -= todrop;
1698 * If new data are received on a connection after the
1699 * user processes are gone, then RST the other end.
1701 if ((so->so_state & SS_NOFDREF) &&
1702 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1704 tcpstat.tcps_rcvafterclose++;
1705 rstreason = BANDLIM_UNLIMITED;
1710 * If segment ends after window, drop trailing data
1711 * (and PUSH and FIN); if nothing left, just ACK.
1713 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1715 tcpstat.tcps_rcvpackafterwin++;
1716 if (todrop >= tlen) {
1717 tcpstat.tcps_rcvbyteafterwin += tlen;
1719 * If a new connection request is received
1720 * while in TIME_WAIT, drop the old connection
1721 * and start over if the sequence numbers
1722 * are above the previous ones.
1724 if (thflags & TH_SYN &&
1725 tp->t_state == TCPS_TIME_WAIT &&
1726 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1731 * If window is closed can only take segments at
1732 * window edge, and have to drop data and PUSH from
1733 * incoming segments. Continue processing, but
1734 * remember to ack. Otherwise, drop segment
1737 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1738 tp->t_flags |= TF_ACKNOW;
1739 tcpstat.tcps_rcvwinprobe++;
1743 tcpstat.tcps_rcvbyteafterwin += todrop;
1746 thflags &= ~(TH_PUSH | TH_FIN);
1750 * If last ACK falls within this segment's sequence numbers,
1751 * record its timestamp.
1752 * NOTE that the test is modified according to the latest
1753 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1755 if ((to.to_flags & TOF_TS) && SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1756 tp->ts_recent_age = ticks;
1757 tp->ts_recent = to.to_tsval;
1761 * If a SYN is in the window, then this is an
1762 * error and we send an RST and drop the connection.
1764 if (thflags & TH_SYN) {
1765 tp = tcp_drop(tp, ECONNRESET);
1766 rstreason = BANDLIM_UNLIMITED;
1771 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1772 * flag is on (half-synchronized state), then queue data for
1773 * later processing; else drop segment and return.
1775 if (!(thflags & TH_ACK)) {
1776 if (tp->t_state == TCPS_SYN_RECEIVED ||
1777 (tp->t_flags & TF_NEEDSYN))
1786 switch (tp->t_state) {
1788 * In SYN_RECEIVED state, the ACK acknowledges our SYN, so enter
1789 * ESTABLISHED state and continue processing.
1790 * The ACK was checked above.
1792 case TCPS_SYN_RECEIVED:
1794 tcpstat.tcps_connects++;
1796 /* Do window scaling? */
1797 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1798 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1799 tp->snd_scale = tp->requested_s_scale;
1800 tp->rcv_scale = tp->request_r_scale;
1803 * Upon successful completion of 3-way handshake,
1804 * update cache.CC if it was undefined, pass any queued
1805 * data to the user, and advance state appropriately.
1807 if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1809 taop->tao_cc = tp->cc_recv;
1813 * SYN-RECEIVED -> ESTABLISHED
1814 * SYN-RECEIVED* -> FIN-WAIT-1
1816 tp->t_starttime = ticks;
1817 if (tp->t_flags & TF_NEEDFIN) {
1818 tp->t_state = TCPS_FIN_WAIT_1;
1819 tp->t_flags &= ~TF_NEEDFIN;
1821 tp->t_state = TCPS_ESTABLISHED;
1822 callout_reset(tp->tt_keep, tcp_keepidle,
1823 tcp_timer_keep, tp);
1826 * If segment contains data or ACK, will call tcp_reass()
1827 * later; if not, do so now to pass queued data to user.
1829 if (tlen == 0 && !(thflags & TH_FIN))
1830 (void) tcp_reass(tp, NULL, NULL, NULL);
1834 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1835 * ACKs. If the ack is in the range
1836 * tp->snd_una < th->th_ack <= tp->snd_max
1837 * then advance tp->snd_una to th->th_ack and drop
1838 * data from the retransmission queue. If this ACK reflects
1839 * more up to date window information we update our window information.
1841 case TCPS_ESTABLISHED:
1842 case TCPS_FIN_WAIT_1:
1843 case TCPS_FIN_WAIT_2:
1844 case TCPS_CLOSE_WAIT:
1847 case TCPS_TIME_WAIT:
1849 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1850 if (TCP_DO_SACK(tp))
1851 tcp_sack_update_scoreboard(tp, &to);
1852 if (tlen != 0 || tiwin != tp->snd_wnd) {
1856 tcpstat.tcps_rcvdupack++;
1857 if (!callout_active(tp->tt_rexmt) ||
1858 th->th_ack != tp->snd_una) {
1863 * We have outstanding data (other than
1864 * a window probe), this is a completely
1865 * duplicate ack (ie, window info didn't
1866 * change), the ack is the biggest we've
1867 * seen and we've seen exactly our rexmt
1868 * threshhold of them, so assume a packet
1869 * has been dropped and retransmit it.
1870 * Kludge snd_nxt & the congestion
1871 * window so we send only this one
1874 if (IN_FASTRECOVERY(tp)) {
1875 if (TCP_DO_SACK(tp)) {
1876 /* No artifical cwnd inflation. */
1877 tcp_sack_rexmt(tp, th);
1880 * Dup acks mean that packets
1881 * have left the network
1882 * (they're now cached at the
1883 * receiver) so bump cwnd by
1884 * the amount in the receiver
1885 * to keep a constant cwnd
1886 * packets in the network.
1888 tp->snd_cwnd += tp->t_maxseg;
1889 (void) tcp_output(tp);
1891 } else if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1894 } else if (++tp->t_dupacks == tcprexmtthresh) {
1895 tcp_seq old_snd_nxt;
1899 if (tcp_do_eifel_detect &&
1900 (tp->t_flags & TF_RCVD_TSTMP)) {
1901 tcp_save_congestion_state(tp);
1902 tp->t_flags |= TF_FASTREXMT;
1905 * We know we're losing at the current
1906 * window size, so do congestion avoidance:
1907 * set ssthresh to half the current window
1908 * and pull our congestion window back to the
1911 win = min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1915 tp->snd_ssthresh = win * tp->t_maxseg;
1916 ENTER_FASTRECOVERY(tp);
1917 tp->snd_recover = tp->snd_max;
1918 callout_stop(tp->tt_rexmt);
1920 old_snd_nxt = tp->snd_nxt;
1921 tp->snd_nxt = th->th_ack;
1922 tp->snd_cwnd = tp->t_maxseg;
1923 (void) tcp_output(tp);
1924 ++tcpstat.tcps_sndfastrexmit;
1925 tp->snd_cwnd = tp->snd_ssthresh;
1926 tp->rexmt_high = tp->snd_nxt;
1927 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
1928 tp->snd_nxt = old_snd_nxt;
1929 KASSERT(tp->snd_limited <= 2,
1930 ("tp->snd_limited too big"));
1931 if (TCP_DO_SACK(tp))
1932 tcp_sack_rexmt(tp, th);
1934 tp->snd_cwnd += tp->t_maxseg *
1935 (tp->t_dupacks - tp->snd_limited);
1936 } else if (tcp_do_limitedtransmit) {
1937 u_long oldcwnd = tp->snd_cwnd;
1938 tcp_seq oldsndmax = tp->snd_max;
1939 /* outstanding data */
1940 uint32_t ownd = tp->snd_max - tp->snd_una;
1943 #define iceildiv(n, d) (((n)+(d)-1) / (d))
1945 KASSERT(tp->t_dupacks == 1 ||
1947 ("dupacks not 1 or 2"));
1948 if (tp->t_dupacks == 1)
1949 tp->snd_limited = 0;
1950 tp->snd_cwnd = ownd +
1951 (tp->t_dupacks - tp->snd_limited) *
1953 (void) tcp_output(tp);
1954 tp->snd_cwnd = oldcwnd;
1955 sent = tp->snd_max - oldsndmax;
1956 if (sent > tp->t_maxseg) {
1957 KASSERT((tp->t_dupacks == 2 &&
1958 tp->snd_limited == 0) ||
1959 (sent == tp->t_maxseg + 1 &&
1960 tp->t_flags & TF_SENTFIN),
1962 KASSERT(sent <= tp->t_maxseg * 2,
1963 ("sent too many segments"));
1964 tp->snd_limited = 2;
1965 tcpstat.tcps_sndlimited += 2;
1966 } else if (sent > 0) {
1968 ++tcpstat.tcps_sndlimited;
1969 } else if (tcp_do_early_retransmit &&
1970 (tcp_do_eifel_detect &&
1971 (tp->t_flags & TF_RCVD_TSTMP)) &&
1972 ownd < 4 * tp->t_maxseg &&
1973 tp->t_dupacks + 1 >=
1974 iceildiv(ownd, tp->t_maxseg) &&
1975 (!TCP_DO_SACK(tp) ||
1976 ownd <= tp->t_maxseg ||
1977 tcp_sack_has_sacked(&tp->scb,
1978 ownd - tp->t_maxseg))) {
1979 ++tcpstat.tcps_sndearlyrexmit;
1980 tp->t_flags |= TF_EARLYREXMT;
1981 goto fastretransmit;
1987 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
1989 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1991 * Detected optimistic ACK attack.
1992 * Force slow-start to de-synchronize attack.
1994 tp->snd_cwnd = tp->t_maxseg;
1996 tcpstat.tcps_rcvacktoomuch++;
2000 * If we reach this point, ACK is not a duplicate,
2001 * i.e., it ACKs something we sent.
2003 if (tp->t_flags & TF_NEEDSYN) {
2005 * T/TCP: Connection was half-synchronized, and our
2006 * SYN has been ACK'd (so connection is now fully
2007 * synchronized). Go to non-starred state,
2008 * increment snd_una for ACK of SYN, and check if
2009 * we can do window scaling.
2011 tp->t_flags &= ~TF_NEEDSYN;
2013 /* Do window scaling? */
2014 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
2015 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
2016 tp->snd_scale = tp->requested_s_scale;
2017 tp->rcv_scale = tp->request_r_scale;
2022 acked = th->th_ack - tp->snd_una;
2023 tcpstat.tcps_rcvackpack++;
2024 tcpstat.tcps_rcvackbyte += acked;
2026 if (tcp_do_eifel_detect && acked > 0 &&
2027 (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
2028 (tp->t_flags & TF_FIRSTACCACK)) {
2029 /* Eifel detection applicable. */
2030 if (to.to_tsecr < tp->t_rexmtTS) {
2031 ++tcpstat.tcps_eifeldetected;
2032 tcp_revert_congestion_state(tp);
2033 if (tp->t_rxtshift == 1 &&
2034 ticks >= tp->t_badrxtwin)
2035 ++tcpstat.tcps_rttcantdetect;
2037 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2039 * If we just performed our first retransmit,
2040 * and the ACK arrives within our recovery window,
2041 * then it was a mistake to do the retransmit
2042 * in the first place. Recover our original cwnd
2043 * and ssthresh, and proceed to transmit where we
2046 tcp_revert_congestion_state(tp);
2047 ++tcpstat.tcps_rttdetected;
2051 * If we have a timestamp reply, update smoothed
2052 * round trip time. If no timestamp is present but
2053 * transmit timer is running and timed sequence
2054 * number was acked, update smoothed round trip time.
2055 * Since we now have an rtt measurement, cancel the
2056 * timer backoff (cf., Phil Karn's retransmit alg.).
2057 * Recompute the initial retransmit timer.
2059 * Some machines (certain windows boxes) send broken
2060 * timestamp replies during the SYN+ACK phase, ignore
2063 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
2064 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2065 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2066 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2067 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2070 * If no data (only SYN) was ACK'd,
2071 * skip rest of ACK processing.
2076 /* Stop looking for an acceptable ACK since one was received. */
2077 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT | TF_EARLYREXMT);
2079 if (acked > so->so_snd.sb_cc) {
2080 tp->snd_wnd -= so->so_snd.sb_cc;
2081 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2082 ourfinisacked = TRUE;
2084 sbdrop(&so->so_snd, acked);
2085 tp->snd_wnd -= acked;
2086 ourfinisacked = FALSE;
2091 * Update window information.
2092 * Don't look at window if no ACK:
2093 * TAC's send garbage on first SYN.
2095 if (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2096 (tp->snd_wl1 == th->th_seq &&
2097 (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2098 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)))) {
2099 /* keep track of pure window updates */
2100 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2101 tiwin > tp->snd_wnd)
2102 tcpstat.tcps_rcvwinupd++;
2103 tp->snd_wnd = tiwin;
2104 tp->snd_wl1 = th->th_seq;
2105 tp->snd_wl2 = th->th_ack;
2106 if (tp->snd_wnd > tp->max_sndwnd)
2107 tp->max_sndwnd = tp->snd_wnd;
2111 tp->snd_una = th->th_ack;
2112 if (TCP_DO_SACK(tp))
2113 tcp_sack_update_scoreboard(tp, &to);
2114 if (IN_FASTRECOVERY(tp)) {
2115 if (SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2116 EXIT_FASTRECOVERY(tp);
2119 * If the congestion window was inflated
2120 * to account for the other side's
2121 * cached packets, retract it.
2123 * Window inflation should have left us
2124 * with approximately snd_ssthresh outstanding
2125 * data. But, in case we would be inclined
2126 * to send a burst, better do it using
2129 if (!TCP_DO_SACK(tp))
2130 tp->snd_cwnd = tp->snd_ssthresh;
2132 if (SEQ_GT(th->th_ack + tp->snd_cwnd,
2133 tp->snd_max + 2 * tp->t_maxseg))
2135 (tp->snd_max - tp->snd_una) +
2138 if (TCP_DO_SACK(tp)) {
2139 tp->snd_max_rexmt = tp->snd_max;
2140 tcp_sack_rexmt(tp, th);
2142 tcp_newreno_partial_ack(tp, th, acked);
2148 * When new data is acked, open the congestion window.
2149 * If the window gives us less than ssthresh packets
2150 * in flight, open exponentially (maxseg per packet).
2151 * Otherwise open linearly: maxseg per window
2152 * (maxseg^2 / cwnd per packet).
2154 u_int cw = tp->snd_cwnd;
2157 if (cw > tp->snd_ssthresh)
2158 incr = tp->t_maxseg * tp->t_maxseg / cw;
2160 incr = tp->t_maxseg;
2161 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2162 tp->snd_recover = th->th_ack - 1;
2164 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2165 tp->snd_nxt = tp->snd_una;
2168 * If all outstanding data is acked, stop retransmit
2169 * timer and remember to restart (more output or persist).
2170 * If there is more data to be acked, restart retransmit
2171 * timer, using current (possibly backed-off) value.
2173 if (th->th_ack == tp->snd_max) {
2174 callout_stop(tp->tt_rexmt);
2176 } else if (!callout_active(tp->tt_persist))
2177 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
2178 tcp_timer_rexmt, tp);
2180 switch (tp->t_state) {
2182 * In FIN_WAIT_1 STATE in addition to the processing
2183 * for the ESTABLISHED state if our FIN is now acknowledged
2184 * then enter FIN_WAIT_2.
2186 case TCPS_FIN_WAIT_1:
2187 if (ourfinisacked) {
2189 * If we can't receive any more
2190 * data, then closing user can proceed.
2191 * Starting the timer is contrary to the
2192 * specification, but if we don't get a FIN
2193 * we'll hang forever.
2195 if (so->so_state & SS_CANTRCVMORE) {
2196 soisdisconnected(so);
2197 callout_reset(tp->tt_2msl, tcp_maxidle,
2198 tcp_timer_2msl, tp);
2200 tp->t_state = TCPS_FIN_WAIT_2;
2205 * In CLOSING STATE in addition to the processing for
2206 * the ESTABLISHED state if the ACK acknowledges our FIN
2207 * then enter the TIME-WAIT state, otherwise ignore
2211 if (ourfinisacked) {
2212 tp->t_state = TCPS_TIME_WAIT;
2213 tcp_canceltimers(tp);
2214 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2215 if (tp->cc_recv != 0 &&
2216 (ticks - tp->t_starttime) < tcp_msl)
2217 callout_reset(tp->tt_2msl,
2218 tp->t_rxtcur * TCPTV_TWTRUNC,
2219 tcp_timer_2msl, tp);
2221 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2222 tcp_timer_2msl, tp);
2223 soisdisconnected(so);
2228 * In LAST_ACK, we may still be waiting for data to drain
2229 * and/or to be acked, as well as for the ack of our FIN.
2230 * If our FIN is now acknowledged, delete the TCB,
2231 * enter the closed state and return.
2234 if (ourfinisacked) {
2241 * In TIME_WAIT state the only thing that should arrive
2242 * is a retransmission of the remote FIN. Acknowledge
2243 * it and restart the finack timer.
2245 case TCPS_TIME_WAIT:
2246 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2247 tcp_timer_2msl, tp);
2254 * Update window information.
2255 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2257 if ((thflags & TH_ACK) &&
2258 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2259 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2260 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2261 /* keep track of pure window updates */
2262 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2263 tiwin > tp->snd_wnd)
2264 tcpstat.tcps_rcvwinupd++;
2265 tp->snd_wnd = tiwin;
2266 tp->snd_wl1 = th->th_seq;
2267 tp->snd_wl2 = th->th_ack;
2268 if (tp->snd_wnd > tp->max_sndwnd)
2269 tp->max_sndwnd = tp->snd_wnd;
2274 * Process segments with URG.
2276 if ((thflags & TH_URG) && th->th_urp &&
2277 !TCPS_HAVERCVDFIN(tp->t_state)) {
2279 * This is a kludge, but if we receive and accept
2280 * random urgent pointers, we'll crash in
2281 * soreceive. It's hard to imagine someone
2282 * actually wanting to send this much urgent data.
2284 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2285 th->th_urp = 0; /* XXX */
2286 thflags &= ~TH_URG; /* XXX */
2287 goto dodata; /* XXX */
2290 * If this segment advances the known urgent pointer,
2291 * then mark the data stream. This should not happen
2292 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2293 * a FIN has been received from the remote side.
2294 * In these states we ignore the URG.
2296 * According to RFC961 (Assigned Protocols),
2297 * the urgent pointer points to the last octet
2298 * of urgent data. We continue, however,
2299 * to consider it to indicate the first octet
2300 * of data past the urgent section as the original
2301 * spec states (in one of two places).
2303 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
2304 tp->rcv_up = th->th_seq + th->th_urp;
2305 so->so_oobmark = so->so_rcv.sb_cc +
2306 (tp->rcv_up - tp->rcv_nxt) - 1;
2307 if (so->so_oobmark == 0)
2308 so->so_state |= SS_RCVATMARK;
2310 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2313 * Remove out of band data so doesn't get presented to user.
2314 * This can happen independent of advancing the URG pointer,
2315 * but if two URG's are pending at once, some out-of-band
2316 * data may creep in... ick.
2318 if (th->th_urp <= (u_long)tlen &&
2319 !(so->so_options & SO_OOBINLINE)) {
2320 /* hdr drop is delayed */
2321 tcp_pulloutofband(so, th, m, drop_hdrlen);
2325 * If no out of band data is expected,
2326 * pull receive urgent pointer along
2327 * with the receive window.
2329 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2330 tp->rcv_up = tp->rcv_nxt;
2335 * Process the segment text, merging it into the TCP sequencing queue,
2336 * and arranging for acknowledgment of receipt if necessary.
2337 * This process logically involves adjusting tp->rcv_wnd as data
2338 * is presented to the user (this happens in tcp_usrreq.c,
2339 * case PRU_RCVD). If a FIN has already been received on this
2340 * connection then we just ignore the text.
2342 if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
2343 m_adj(m, drop_hdrlen); /* delayed header drop */
2345 * Insert segment which includes th into TCP reassembly queue
2346 * with control block tp. Set thflags to whether reassembly now
2347 * includes a segment with FIN. This handles the common case
2348 * inline (segment is the next to be received on an established
2349 * connection, and the queue is empty), avoiding linkage into
2350 * and removal from the queue and repetition of various
2352 * Set DELACK for segments received in order, but ack
2353 * immediately when segments are out of order (so
2354 * fast retransmit can work).
2356 if (th->th_seq == tp->rcv_nxt &&
2357 LIST_EMPTY(&tp->t_segq) &&
2358 TCPS_HAVEESTABLISHED(tp->t_state)) {
2360 callout_reset(tp->tt_delack, tcp_delacktime,
2361 tcp_timer_delack, tp);
2363 tp->t_flags |= TF_ACKNOW;
2364 tp->rcv_nxt += tlen;
2365 thflags = th->th_flags & TH_FIN;
2366 tcpstat.tcps_rcvpack++;
2367 tcpstat.tcps_rcvbyte += tlen;
2369 if (so->so_state & SS_CANTRCVMORE)
2372 sbappend(&so->so_rcv, m);
2375 if (!(tp->t_flags & TF_DUPSEG)) {
2376 /* Initialize SACK report block. */
2377 tp->reportblk.rblk_start = th->th_seq;
2378 tp->reportblk.rblk_end = th->th_seq + tlen +
2379 ((thflags & TH_FIN) != 0);
2381 thflags = tcp_reass(tp, th, &tlen, m);
2382 tp->t_flags |= TF_ACKNOW;
2386 * Note the amount of data that peer has sent into
2387 * our window, in order to estimate the sender's
2390 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2397 * If FIN is received ACK the FIN and let the user know
2398 * that the connection is closing.
2400 if (thflags & TH_FIN) {
2401 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
2404 * If connection is half-synchronized
2405 * (ie NEEDSYN flag on) then delay ACK,
2406 * so it may be piggybacked when SYN is sent.
2407 * Otherwise, since we received a FIN then no
2408 * more input can be expected, send ACK now.
2410 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2411 callout_reset(tp->tt_delack, tcp_delacktime,
2412 tcp_timer_delack, tp);
2414 tp->t_flags |= TF_ACKNOW;
2418 switch (tp->t_state) {
2420 * In SYN_RECEIVED and ESTABLISHED STATES
2421 * enter the CLOSE_WAIT state.
2423 case TCPS_SYN_RECEIVED:
2424 tp->t_starttime = ticks;
2426 case TCPS_ESTABLISHED:
2427 tp->t_state = TCPS_CLOSE_WAIT;
2431 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2432 * enter the CLOSING state.
2434 case TCPS_FIN_WAIT_1:
2435 tp->t_state = TCPS_CLOSING;
2439 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2440 * starting the time-wait timer, turning off the other
2443 case TCPS_FIN_WAIT_2:
2444 tp->t_state = TCPS_TIME_WAIT;
2445 tcp_canceltimers(tp);
2446 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2447 if (tp->cc_recv != 0 &&
2448 (ticks - tp->t_starttime) < tcp_msl) {
2449 callout_reset(tp->tt_2msl,
2450 tp->t_rxtcur * TCPTV_TWTRUNC,
2451 tcp_timer_2msl, tp);
2452 /* For transaction client, force ACK now. */
2453 tp->t_flags |= TF_ACKNOW;
2456 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2457 tcp_timer_2msl, tp);
2458 soisdisconnected(so);
2462 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2464 case TCPS_TIME_WAIT:
2465 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2466 tcp_timer_2msl, tp);
2472 if (so->so_options & SO_DEBUG)
2473 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2478 * Return any desired output.
2480 if (needoutput || (tp->t_flags & TF_ACKNOW))
2481 (void) tcp_output(tp);
2486 * Generate an ACK dropping incoming segment if it occupies
2487 * sequence space, where the ACK reflects our state.
2489 * We can now skip the test for the RST flag since all
2490 * paths to this code happen after packets containing
2491 * RST have been dropped.
2493 * In the SYN-RECEIVED state, don't send an ACK unless the
2494 * segment we received passes the SYN-RECEIVED ACK test.
2495 * If it fails send a RST. This breaks the loop in the
2496 * "LAND" DoS attack, and also prevents an ACK storm
2497 * between two listening ports that have been sent forged
2498 * SYN segments, each with the source address of the other.
2500 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2501 (SEQ_GT(tp->snd_una, th->th_ack) ||
2502 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2503 rstreason = BANDLIM_RST_OPENPORT;
2507 if (so->so_options & SO_DEBUG)
2508 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2512 tp->t_flags |= TF_ACKNOW;
2513 (void) tcp_output(tp);
2518 * Generate a RST, dropping incoming segment.
2519 * Make ACK acceptable to originator of segment.
2520 * Don't bother to respond if destination was broadcast/multicast.
2522 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
2525 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2526 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2529 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2530 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2531 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2532 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2535 /* IPv6 anycast check is done at tcp6_input() */
2538 * Perform bandwidth limiting.
2541 if (badport_bandlim(rstreason) < 0)
2546 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2547 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2550 if (thflags & TH_ACK)
2551 /* mtod() below is safe as long as hdr dropping is delayed */
2552 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2555 if (thflags & TH_SYN)
2557 /* mtod() below is safe as long as hdr dropping is delayed */
2558 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2559 (tcp_seq)0, TH_RST | TH_ACK);
2565 * Drop space held by incoming segment and return.
2568 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2569 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2577 * Parse TCP options and place in tcpopt.
2580 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn)
2585 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2587 if (opt == TCPOPT_EOL)
2589 if (opt == TCPOPT_NOP)
2595 if (optlen < 2 || optlen > cnt)
2600 if (optlen != TCPOLEN_MAXSEG)
2604 to->to_flags |= TOF_MSS;
2605 bcopy(cp + 2, &to->to_mss, sizeof(to->to_mss));
2606 to->to_mss = ntohs(to->to_mss);
2609 if (optlen != TCPOLEN_WINDOW)
2613 to->to_flags |= TOF_SCALE;
2614 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2616 case TCPOPT_TIMESTAMP:
2617 if (optlen != TCPOLEN_TIMESTAMP)
2619 to->to_flags |= TOF_TS;
2620 bcopy(cp + 2, &to->to_tsval, sizeof(to->to_tsval));
2621 to->to_tsval = ntohl(to->to_tsval);
2622 bcopy(cp + 6, &to->to_tsecr, sizeof(to->to_tsecr));
2623 to->to_tsecr = ntohl(to->to_tsecr);
2626 if (optlen != TCPOLEN_CC)
2628 to->to_flags |= TOF_CC;
2629 bcopy(cp + 2, &to->to_cc, sizeof(to->to_cc));
2630 to->to_cc = ntohl(to->to_cc);
2633 if (optlen != TCPOLEN_CC)
2637 to->to_flags |= TOF_CCNEW;
2638 bcopy(cp + 2, &to->to_cc, sizeof(to->to_cc));
2639 to->to_cc = ntohl(to->to_cc);
2642 if (optlen != TCPOLEN_CC)
2646 to->to_flags |= TOF_CCECHO;
2647 bcopy(cp + 2, &to->to_ccecho, sizeof(to->to_ccecho));
2648 to->to_ccecho = ntohl(to->to_ccecho);
2650 case TCPOPT_SACK_PERMITTED:
2651 if (optlen != TCPOLEN_SACK_PERMITTED)
2655 to->to_flags |= TOF_SACK_PERMITTED;
2658 if ((optlen - 2) & 0x07) /* not multiple of 8 */
2660 to->to_nsackblocks = (optlen - 2) / 8;
2661 to->to_sackblocks = (struct raw_sackblock *) (cp + 2);
2662 to->to_flags |= TOF_SACK;
2663 for (i = 0; i < to->to_nsackblocks; i++) {
2664 struct raw_sackblock *r = &to->to_sackblocks[i];
2666 r->rblk_start = ntohl(r->rblk_start);
2667 r->rblk_end = ntohl(r->rblk_end);
2677 * Pull out of band byte out of a segment so
2678 * it doesn't appear in the user's data queue.
2679 * It is still reflected in the segment length for
2680 * sequencing purposes.
2681 * "off" is the delayed to be dropped hdrlen.
2684 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
2686 int cnt = off + th->th_urp - 1;
2689 if (m->m_len > cnt) {
2690 char *cp = mtod(m, caddr_t) + cnt;
2691 struct tcpcb *tp = sototcpcb(so);
2694 tp->t_oobflags |= TCPOOB_HAVEDATA;
2695 bcopy(cp + 1, cp, m->m_len - cnt - 1);
2697 if (m->m_flags & M_PKTHDR)
2706 panic("tcp_pulloutofband");
2710 * Collect new round-trip time estimate
2711 * and update averages and current timeout.
2714 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2718 tcpstat.tcps_rttupdated++;
2720 if (tp->t_srtt != 0) {
2722 * srtt is stored as fixed point with 5 bits after the
2723 * binary point (i.e., scaled by 8). The following magic
2724 * is equivalent to the smoothing algorithm in rfc793 with
2725 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2726 * point). Adjust rtt to origin 0.
2728 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2729 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2731 if ((tp->t_srtt += delta) <= 0)
2735 * We accumulate a smoothed rtt variance (actually, a
2736 * smoothed mean difference), then set the retransmit
2737 * timer to smoothed rtt + 4 times the smoothed variance.
2738 * rttvar is stored as fixed point with 4 bits after the
2739 * binary point (scaled by 16). The following is
2740 * equivalent to rfc793 smoothing with an alpha of .75
2741 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2742 * rfc793's wired-in beta.
2746 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2747 if ((tp->t_rttvar += delta) <= 0)
2749 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2750 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2753 * No rtt measurement yet - use the unsmoothed rtt.
2754 * Set the variance to half the rtt (so our first
2755 * retransmit happens at 3*rtt).
2757 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2758 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2759 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2765 * the retransmit should happen at rtt + 4 * rttvar.
2766 * Because of the way we do the smoothing, srtt and rttvar
2767 * will each average +1/2 tick of bias. When we compute
2768 * the retransmit timer, we want 1/2 tick of rounding and
2769 * 1 extra tick because of +-1/2 tick uncertainty in the
2770 * firing of the timer. The bias will give us exactly the
2771 * 1.5 tick we need. But, because the bias is
2772 * statistical, we have to test that we don't drop below
2773 * the minimum feasible timer (which is 2 ticks).
2775 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2776 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2779 * We received an ack for a packet that wasn't retransmitted;
2780 * it is probably safe to discard any error indications we've
2781 * received recently. This isn't quite right, but close enough
2782 * for now (a route might have failed after we sent a segment,
2783 * and the return path might not be symmetrical).
2785 tp->t_softerror = 0;
2789 * Determine a reasonable value for maxseg size.
2790 * If the route is known, check route for mtu.
2791 * If none, use an mss that can be handled on the outgoing
2792 * interface without forcing IP to fragment; if bigger than
2793 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2794 * to utilize large mbufs. If no route is found, route has no mtu,
2795 * or the destination isn't local, use a default, hopefully conservative
2796 * size (usually 512 or the default IP max size, but no more than the mtu
2797 * of the interface), as we can't discover anything about intervening
2798 * gateways or networks. We also initialize the congestion/slow start
2799 * window to be a single segment if the destination isn't local.
2800 * While looking at the routing entry, we also initialize other path-dependent
2801 * parameters from pre-set or cached values in the routing entry.
2803 * Also take into account the space needed for options that we
2804 * send regularly. Make maxseg shorter by that amount to assure
2805 * that we can send maxseg amount of data even when the options
2806 * are present. Store the upper limit of the length of options plus
2809 * NOTE that this routine is only called when we process an incoming
2810 * segment, for outgoing segments only tcp_mssopt is called.
2812 * In case of T/TCP, we call this routine during implicit connection
2813 * setup as well (offer = -1), to initialize maxseg from the cached
2817 tcp_mss(struct tcpcb *tp, int offer)
2823 struct inpcb *inp = tp->t_inpcb;
2825 struct rmxp_tao *taop;
2826 int origoffer = offer;
2828 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2829 size_t min_protoh = isipv6 ?
2830 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2831 sizeof(struct tcpiphdr);
2833 const boolean_t isipv6 = FALSE;
2834 const size_t min_protoh = sizeof(struct tcpiphdr);
2838 rt = tcp_rtlookup6(&inp->inp_inc);
2840 rt = tcp_rtlookup(&inp->inp_inc);
2842 tp->t_maxopd = tp->t_maxseg =
2843 (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2847 so = inp->inp_socket;
2849 taop = rmx_taop(rt->rt_rmx);
2851 * Offer == -1 means that we didn't receive SYN yet,
2852 * use cached value in that case;
2855 offer = taop->tao_mssopt;
2857 * Offer == 0 means that there was no MSS on the SYN segment,
2858 * in this case we use tcp_mssdflt.
2861 offer = (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2864 * Sanity check: make sure that maxopd will be large
2865 * enough to allow some data on segments even is the
2866 * all the option space is used (40bytes). Otherwise
2867 * funny things may happen in tcp_output.
2869 offer = max(offer, 64);
2870 taop->tao_mssopt = offer;
2873 * While we're here, check if there's an initial rtt
2874 * or rttvar. Convert from the route-table units
2875 * to scaled multiples of the slow timeout timer.
2877 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2879 * XXX the lock bit for RTT indicates that the value
2880 * is also a minimum value; this is subject to time.
2882 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2883 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2884 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2885 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2886 tcpstat.tcps_usedrtt++;
2887 if (rt->rt_rmx.rmx_rttvar) {
2888 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2889 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2890 tcpstat.tcps_usedrttvar++;
2892 /* default variation is +- 1 rtt */
2894 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2896 TCPT_RANGESET(tp->t_rxtcur,
2897 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2898 tp->t_rttmin, TCPTV_REXMTMAX);
2901 * if there's an mtu associated with the route, use it
2902 * else, use the link mtu.
2904 if (rt->rt_rmx.rmx_mtu)
2905 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2908 mss = nd_ifinfo[rt->rt_ifp->if_index].linkmtu -
2910 if (!in6_localaddr(&inp->in6p_faddr))
2911 mss = min(mss, tcp_v6mssdflt);
2913 mss = ifp->if_mtu - min_protoh;
2914 if (!in_localaddr(inp->inp_faddr))
2915 mss = min(mss, tcp_mssdflt);
2918 mss = min(mss, offer);
2920 * maxopd stores the maximum length of data AND options
2921 * in a segment; maxseg is the amount of data in a normal
2922 * segment. We need to store this value (maxopd) apart
2923 * from maxseg, because now every segment carries options
2924 * and thus we normally have somewhat less data in segments.
2929 * In case of T/TCP, origoffer==-1 indicates, that no segments
2930 * were received yet. In this case we just guess, otherwise
2931 * we do the same as before T/TCP.
2933 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
2935 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2936 mss -= TCPOLEN_TSTAMP_APPA;
2937 if ((tp->t_flags & (TF_REQ_CC | TF_NOOPT)) == TF_REQ_CC &&
2939 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2940 mss -= TCPOLEN_CC_APPA;
2942 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2944 mss &= ~(MCLBYTES-1);
2947 mss = mss / MCLBYTES * MCLBYTES;
2950 * If there's a pipesize, change the socket buffer
2951 * to that size. Make the socket buffers an integral
2952 * number of mss units; if the mss is larger than
2953 * the socket buffer, decrease the mss.
2956 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2958 bufsize = so->so_snd.sb_hiwat;
2962 bufsize = roundup(bufsize, mss);
2963 if (bufsize > sb_max)
2965 if (bufsize > so->so_snd.sb_hiwat)
2966 (void)sbreserve(&so->so_snd, bufsize, so, NULL);
2971 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2973 bufsize = so->so_rcv.sb_hiwat;
2974 if (bufsize > mss) {
2975 bufsize = roundup(bufsize, mss);
2976 if (bufsize > sb_max)
2978 if (bufsize > so->so_rcv.sb_hiwat)
2979 (void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2983 * Set the slow-start flight size depending on whether this
2984 * is a local network or not.
2987 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
2988 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2989 (!isipv6 && in_localaddr(inp->inp_faddr)))
2990 tp->snd_cwnd = mss * ss_fltsz_local;
2992 tp->snd_cwnd = mss * ss_fltsz;
2994 if (rt->rt_rmx.rmx_ssthresh) {
2996 * There's some sort of gateway or interface
2997 * buffer limit on the path. Use this to set
2998 * the slow start threshhold, but set the
2999 * threshold to no less than 2*mss.
3001 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3002 tcpstat.tcps_usedssthresh++;
3007 * Determine the MSS option to send on an outgoing SYN.
3010 tcp_mssopt(struct tcpcb *tp)
3015 ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3016 int min_protoh = isipv6 ?
3017 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
3018 sizeof(struct tcpiphdr);
3020 const boolean_t isipv6 = FALSE;
3021 const size_t min_protoh = sizeof(struct tcpiphdr);
3025 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
3027 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
3029 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3031 return (rt->rt_ifp->if_mtu - min_protoh);
3035 * When a partial ack arrives, force the retransmission of the
3036 * next unacknowledged segment. Do not exit Fast Recovery.
3038 * Implement the Slow-but-Steady variant of NewReno by restarting the
3039 * the retransmission timer. Turn it off here so it can be restarted
3040 * later in tcp_output().
3043 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th, int acked)
3045 tcp_seq old_snd_nxt = tp->snd_nxt;
3046 u_long ocwnd = tp->snd_cwnd;
3048 callout_stop(tp->tt_rexmt);
3050 tp->snd_nxt = th->th_ack;
3051 /* Set snd_cwnd to one segment beyond acknowledged offset. */
3052 tp->snd_cwnd = tp->t_maxseg;
3053 tp->t_flags |= TF_ACKNOW;
3054 (void) tcp_output(tp);
3055 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3056 tp->snd_nxt = old_snd_nxt;
3057 /* partial window deflation */
3058 tp->snd_cwnd = ocwnd - acked + tp->t_maxseg;
3062 * In contrast to the Slow-but-Steady NewReno variant,
3063 * we do not reset the retransmission timer for SACK retransmissions,
3064 * except when retransmitting snd_una.
3067 tcp_sack_rexmt(struct tcpcb *tp, struct tcphdr *th)
3069 uint32_t pipe, seglen;
3072 tcp_seq old_snd_nxt = tp->snd_nxt;
3073 u_long ocwnd = tp->snd_cwnd;
3074 int nseg = 0; /* consecutive new segments */
3075 #define MAXBURST 4 /* limit burst of new packets on partial ack */
3078 pipe = tcp_sack_compute_pipe(tp);
3079 while ((tcp_seq_diff_t)(ocwnd - pipe) >= (tcp_seq_diff_t)tp->t_maxseg &&
3080 (!tcp_do_smartsack || nseg < MAXBURST) &&
3081 tcp_sack_nextseg(tp, &nextrexmt, &seglen, &lostdup)) {
3083 tcp_seq old_snd_max;
3086 if (nextrexmt == tp->snd_max) ++nseg;
3087 tp->snd_nxt = nextrexmt;
3088 tp->snd_cwnd = nextrexmt - tp->snd_una + seglen;
3089 old_snd_max = tp->snd_max;
3090 if (nextrexmt == tp->snd_una)
3091 callout_stop(tp->tt_rexmt);
3092 error = tcp_output(tp);
3095 sent = tp->snd_nxt - nextrexmt;
3100 tcpstat.tcps_sndsackpack++;
3101 tcpstat.tcps_sndsackbyte += sent;
3102 if (SEQ_LT(nextrexmt, old_snd_max) &&
3103 SEQ_LT(tp->rexmt_high, tp->snd_nxt))
3104 tp->rexmt_high = seq_min(tp->snd_nxt, old_snd_max);
3106 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3107 tp->snd_nxt = old_snd_nxt;
3108 tp->snd_cwnd = ocwnd;