2 * Copyright (c) 2002, 2003, 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2002, 2003, 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
36 * The Regents of the University of California. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
67 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
68 * $DragonFly: src/sys/netinet/tcp_input.c,v 1.68 2008/08/22 09:14:17 sephe Exp $
71 #include "opt_ipfw.h" /* for ipfw_fwd */
73 #include "opt_inet6.h"
74 #include "opt_ipsec.h"
75 #include "opt_tcpdebug.h"
76 #include "opt_tcp_input.h"
78 #include <sys/param.h>
79 #include <sys/systm.h>
80 #include <sys/kernel.h>
81 #include <sys/sysctl.h>
82 #include <sys/malloc.h>
84 #include <sys/proc.h> /* for proc0 declaration */
85 #include <sys/protosw.h>
86 #include <sys/socket.h>
87 #include <sys/socketvar.h>
88 #include <sys/syslog.h>
89 #include <sys/in_cksum.h>
91 #include <sys/socketvar2.h>
93 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
94 #include <machine/stdarg.h>
97 #include <net/route.h>
99 #include <netinet/in.h>
100 #include <netinet/in_systm.h>
101 #include <netinet/ip.h>
102 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
103 #include <netinet/in_var.h>
104 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
105 #include <netinet/in_pcb.h>
106 #include <netinet/ip_var.h>
107 #include <netinet/ip6.h>
108 #include <netinet/icmp6.h>
109 #include <netinet6/nd6.h>
110 #include <netinet6/ip6_var.h>
111 #include <netinet6/in6_pcb.h>
112 #include <netinet/tcp.h>
113 #include <netinet/tcp_fsm.h>
114 #include <netinet/tcp_seq.h>
115 #include <netinet/tcp_timer.h>
116 #include <netinet/tcp_timer2.h>
117 #include <netinet/tcp_var.h>
118 #include <netinet6/tcp6_var.h>
119 #include <netinet/tcpip.h>
122 #include <netinet/tcp_debug.h>
124 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
125 struct tcphdr tcp_savetcp;
129 #include <netproto/ipsec/ipsec.h>
130 #include <netproto/ipsec/ipsec6.h>
134 #include <netinet6/ipsec.h>
135 #include <netinet6/ipsec6.h>
136 #include <netproto/key/key.h>
139 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
141 static int log_in_vain = 0;
142 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
143 &log_in_vain, 0, "Log all incoming TCP connections");
145 static int blackhole = 0;
146 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
147 &blackhole, 0, "Do not send RST when dropping refused connections");
149 int tcp_delack_enabled = 1;
150 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
151 &tcp_delack_enabled, 0,
152 "Delay ACK to try and piggyback it onto a data packet");
154 #ifdef TCP_DROP_SYNFIN
155 static int drop_synfin = 0;
156 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
157 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
160 static int tcp_do_limitedtransmit = 1;
161 SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
162 &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
164 static int tcp_do_early_retransmit = 1;
165 SYSCTL_INT(_net_inet_tcp, OID_AUTO, earlyretransmit, CTLFLAG_RW,
166 &tcp_do_early_retransmit, 0, "Early retransmit");
168 int tcp_aggregate_acks = 1;
169 SYSCTL_INT(_net_inet_tcp, OID_AUTO, aggregate_acks, CTLFLAG_RW,
170 &tcp_aggregate_acks, 0, "Aggregate built-up acks into one ack");
172 int tcp_do_rfc3390 = 1;
173 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
175 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
177 static int tcp_do_eifel_detect = 1;
178 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
179 &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
181 static int tcp_do_abc = 1;
182 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc, CTLFLAG_RW,
184 "TCP Appropriate Byte Counting (RFC 3465)");
187 * Define as tunable for easy testing with SACK on and off.
188 * Warning: do not change setting in the middle of an existing active TCP flow,
189 * else strange things might happen to that flow.
192 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sack, CTLFLAG_RW,
193 &tcp_do_sack, 0, "Enable SACK Algorithms");
195 int tcp_do_smartsack = 1;
196 SYSCTL_INT(_net_inet_tcp, OID_AUTO, smartsack, CTLFLAG_RW,
197 &tcp_do_smartsack, 0, "Enable Smart SACK Algorithms");
199 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
200 "TCP Segment Reassembly Queue");
202 int tcp_reass_maxseg = 0;
203 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
204 &tcp_reass_maxseg, 0,
205 "Global maximum number of TCP Segments in Reassembly Queue");
207 int tcp_reass_qsize = 0;
208 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
210 "Global number of TCP Segments currently in Reassembly Queue");
212 static int tcp_reass_overflows = 0;
213 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
214 &tcp_reass_overflows, 0,
215 "Global number of TCP Segment Reassembly Queue Overflows");
217 int tcp_do_autorcvbuf = 1;
218 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
219 &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
221 int tcp_autorcvbuf_inc = 16*1024;
222 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
223 &tcp_autorcvbuf_inc, 0,
224 "Incrementor step size of automatic receive buffer");
226 int tcp_autorcvbuf_max = 2*1024*1024;
227 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
228 &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
231 static void tcp_dooptions(struct tcpopt *, u_char *, int, boolean_t);
232 static void tcp_pulloutofband(struct socket *,
233 struct tcphdr *, struct mbuf *, int);
234 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
236 static void tcp_xmit_timer(struct tcpcb *, int);
237 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *, int);
238 static void tcp_sack_rexmt(struct tcpcb *, struct tcphdr *);
240 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
242 #define ND6_HINT(tp) \
244 if ((tp) && (tp)->t_inpcb && \
245 ((tp)->t_inpcb->inp_vflag & INP_IPV6) && \
246 (tp)->t_inpcb->in6p_route.ro_rt) \
247 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
254 * Indicate whether this ack should be delayed. We can delay the ack if
255 * - delayed acks are enabled and
256 * - there is no delayed ack timer in progress and
257 * - our last ack wasn't a 0-sized window. We never want to delay
258 * the ack that opens up a 0-sized window.
260 #define DELAY_ACK(tp) \
261 (tcp_delack_enabled && !tcp_callout_pending(tp, tp->tt_delack) && \
262 !(tp->t_flags & TF_RXWIN0SENT))
264 #define acceptable_window_update(tp, th, tiwin) \
265 (SEQ_LT(tp->snd_wl1, th->th_seq) || \
266 (tp->snd_wl1 == th->th_seq && \
267 (SEQ_LT(tp->snd_wl2, th->th_ack) || \
268 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))
271 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
274 struct tseg_qent *p = NULL;
275 struct tseg_qent *te;
276 struct socket *so = tp->t_inpcb->inp_socket;
280 * Call with th == NULL after become established to
281 * force pre-ESTABLISHED data up to user socket.
287 * Limit the number of segments in the reassembly queue to prevent
288 * holding on to too many segments (and thus running out of mbufs).
289 * Make sure to let the missing segment through which caused this
290 * queue. Always keep one global queue entry spare to be able to
291 * process the missing segment.
293 if (th->th_seq != tp->rcv_nxt &&
294 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
295 tcp_reass_overflows++;
296 tcpstat.tcps_rcvmemdrop++;
298 /* no SACK block to report */
299 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
303 /* Allocate a new queue entry. */
304 MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
305 M_INTWAIT | M_NULLOK);
307 tcpstat.tcps_rcvmemdrop++;
309 /* no SACK block to report */
310 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
313 atomic_add_int(&tcp_reass_qsize, 1);
316 * Find a segment which begins after this one does.
318 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
319 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
325 * If there is a preceding segment, it may provide some of
326 * our data already. If so, drop the data from the incoming
327 * segment. If it provides all of our data, drop us.
332 /* conversion to int (in i) handles seq wraparound */
333 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
334 if (i > 0) { /* overlaps preceding segment */
335 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
336 /* enclosing block starts w/ preceding segment */
337 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
339 /* preceding encloses incoming segment */
340 tp->encloseblk.rblk_end = p->tqe_th->th_seq +
342 tcpstat.tcps_rcvduppack++;
343 tcpstat.tcps_rcvdupbyte += *tlenp;
346 atomic_add_int(&tcp_reass_qsize, -1);
348 * Try to present any queued data
349 * at the left window edge to the user.
350 * This is needed after the 3-WHS
353 goto present; /* ??? */
358 /* incoming segment end is enclosing block end */
359 tp->encloseblk.rblk_end = th->th_seq + *tlenp +
360 ((th->th_flags & TH_FIN) != 0);
361 /* trim end of reported D-SACK block */
362 tp->reportblk.rblk_end = th->th_seq;
365 tcpstat.tcps_rcvoopack++;
366 tcpstat.tcps_rcvoobyte += *tlenp;
369 * While we overlap succeeding segments trim them or,
370 * if they are completely covered, dequeue them.
373 tcp_seq_diff_t i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
374 tcp_seq qend = q->tqe_th->th_seq + q->tqe_len;
375 struct tseg_qent *nq;
379 if (!(tp->t_flags & TF_DUPSEG)) { /* first time through */
380 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
381 tp->encloseblk = tp->reportblk;
382 /* report trailing duplicate D-SACK segment */
383 tp->reportblk.rblk_start = q->tqe_th->th_seq;
385 if ((tp->t_flags & TF_ENCLOSESEG) &&
386 SEQ_GT(qend, tp->encloseblk.rblk_end)) {
387 /* extend enclosing block if one exists */
388 tp->encloseblk.rblk_end = qend;
390 if (i < q->tqe_len) {
391 q->tqe_th->th_seq += i;
397 nq = LIST_NEXT(q, tqe_q);
398 LIST_REMOVE(q, tqe_q);
401 atomic_add_int(&tcp_reass_qsize, -1);
405 /* Insert the new segment queue entry into place. */
408 te->tqe_len = *tlenp;
410 /* check if can coalesce with following segment */
411 if (q != NULL && (th->th_seq + *tlenp == q->tqe_th->th_seq)) {
412 tcp_seq tend = te->tqe_th->th_seq + te->tqe_len;
414 te->tqe_len += q->tqe_len;
415 if (q->tqe_th->th_flags & TH_FIN)
416 te->tqe_th->th_flags |= TH_FIN;
417 m_cat(te->tqe_m, q->tqe_m);
418 tp->encloseblk.rblk_end = tend;
420 * When not reporting a duplicate segment, use
421 * the larger enclosing block as the SACK block.
423 if (!(tp->t_flags & TF_DUPSEG))
424 tp->reportblk.rblk_end = tend;
425 LIST_REMOVE(q, tqe_q);
427 atomic_add_int(&tcp_reass_qsize, -1);
431 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
433 /* check if can coalesce with preceding segment */
434 if (p->tqe_th->th_seq + p->tqe_len == th->th_seq) {
435 p->tqe_len += te->tqe_len;
436 m_cat(p->tqe_m, te->tqe_m);
437 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
439 * When not reporting a duplicate segment, use
440 * the larger enclosing block as the SACK block.
442 if (!(tp->t_flags & TF_DUPSEG))
443 tp->reportblk.rblk_start = p->tqe_th->th_seq;
445 atomic_add_int(&tcp_reass_qsize, -1);
447 LIST_INSERT_AFTER(p, te, tqe_q);
453 * Present data to user, advancing rcv_nxt through
454 * completed sequence space.
456 if (!TCPS_HAVEESTABLISHED(tp->t_state))
458 q = LIST_FIRST(&tp->t_segq);
459 if (q == NULL || q->tqe_th->th_seq != tp->rcv_nxt)
461 tp->rcv_nxt += q->tqe_len;
462 if (!(tp->t_flags & TF_DUPSEG)) {
463 /* no SACK block to report since ACK advanced */
464 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
466 /* no enclosing block to report since ACK advanced */
467 tp->t_flags &= ~TF_ENCLOSESEG;
468 flags = q->tqe_th->th_flags & TH_FIN;
469 LIST_REMOVE(q, tqe_q);
470 KASSERT(LIST_EMPTY(&tp->t_segq) ||
471 LIST_FIRST(&tp->t_segq)->tqe_th->th_seq != tp->rcv_nxt,
472 ("segment not coalesced"));
473 if (so->so_state & SS_CANTRCVMORE) {
476 lwkt_gettoken(&so->so_rcv.ssb_token);
477 ssb_appendstream(&so->so_rcv, q->tqe_m);
478 lwkt_reltoken(&so->so_rcv.ssb_token);
481 atomic_add_int(&tcp_reass_qsize, -1);
488 * TCP input routine, follows pages 65-76 of the
489 * protocol specification dated September, 1981 very closely.
493 tcp6_input(struct mbuf **mp, int *offp, int proto)
495 struct mbuf *m = *mp;
496 struct in6_ifaddr *ia6;
498 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
501 * draft-itojun-ipv6-tcp-to-anycast
502 * better place to put this in?
504 ia6 = ip6_getdstifaddr(m);
505 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
508 ip6 = mtod(m, struct ip6_hdr *);
509 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
510 offsetof(struct ip6_hdr, ip6_dst));
511 return (IPPROTO_DONE);
514 tcp_input(m, *offp, proto);
515 return (IPPROTO_DONE);
520 tcp_input(struct mbuf *m, ...)
525 struct ip *ip = NULL;
527 struct inpcb *inp = NULL;
533 struct tcpcb *tp = NULL;
535 struct socket *so = 0;
537 boolean_t ourfinisacked, needoutput = FALSE;
540 struct tcpopt to; /* options in this segment */
541 struct sockaddr_in *next_hop = NULL;
542 int rstreason; /* For badport_bandlim accounting purposes */
544 struct ip6_hdr *ip6 = NULL;
548 const boolean_t isipv6 = FALSE;
555 off0 = __va_arg(ap, int);
556 proto = __va_arg(ap, int);
559 tcpstat.tcps_rcvtotal++;
561 if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
564 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
565 KKASSERT(mtag != NULL);
566 next_hop = m_tag_data(mtag);
570 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
574 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
575 ip6 = mtod(m, struct ip6_hdr *);
576 tlen = (sizeof *ip6) + ntohs(ip6->ip6_plen) - off0;
577 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
578 tcpstat.tcps_rcvbadsum++;
581 th = (struct tcphdr *)((caddr_t)ip6 + off0);
584 * Be proactive about unspecified IPv6 address in source.
585 * As we use all-zero to indicate unbounded/unconnected pcb,
586 * unspecified IPv6 address can be used to confuse us.
588 * Note that packets with unspecified IPv6 destination is
589 * already dropped in ip6_input.
591 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
597 * Get IP and TCP header together in first mbuf.
598 * Note: IP leaves IP header in first mbuf.
600 if (off0 > sizeof(struct ip)) {
602 off0 = sizeof(struct ip);
604 /* already checked and pulled up in ip_demux() */
605 KASSERT(m->m_len >= sizeof(struct tcpiphdr),
606 ("TCP header not in one mbuf: m->m_len %d", m->m_len));
607 ip = mtod(m, struct ip *);
608 ipov = (struct ipovly *)ip;
609 th = (struct tcphdr *)((caddr_t)ip + off0);
612 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
613 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
614 th->th_sum = m->m_pkthdr.csum_data;
616 th->th_sum = in_pseudo(ip->ip_src.s_addr,
618 htonl(m->m_pkthdr.csum_data +
621 th->th_sum ^= 0xffff;
624 * Checksum extended TCP header and data.
626 len = sizeof(struct ip) + tlen;
627 bzero(ipov->ih_x1, sizeof ipov->ih_x1);
628 ipov->ih_len = (u_short)tlen;
629 ipov->ih_len = htons(ipov->ih_len);
630 th->th_sum = in_cksum(m, len);
633 tcpstat.tcps_rcvbadsum++;
637 /* Re-initialization for later version check */
638 ip->ip_v = IPVERSION;
643 * Check that TCP offset makes sense,
644 * pull out TCP options and adjust length. XXX
646 off = th->th_off << 2;
647 /* already checked and pulled up in ip_demux() */
648 KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
649 ("bad TCP data offset %d (tlen %d)", off, tlen));
650 tlen -= off; /* tlen is used instead of ti->ti_len */
651 if (off > sizeof(struct tcphdr)) {
653 IP6_EXTHDR_CHECK(m, off0, off, );
654 ip6 = mtod(m, struct ip6_hdr *);
655 th = (struct tcphdr *)((caddr_t)ip6 + off0);
657 /* already pulled up in ip_demux() */
658 KASSERT(m->m_len >= sizeof(struct ip) + off,
659 ("TCP header and options not in one mbuf: "
660 "m_len %d, off %d", m->m_len, off));
662 optlen = off - sizeof(struct tcphdr);
663 optp = (u_char *)(th + 1);
665 thflags = th->th_flags;
667 #ifdef TCP_DROP_SYNFIN
669 * If the drop_synfin option is enabled, drop all packets with
670 * both the SYN and FIN bits set. This prevents e.g. nmap from
671 * identifying the TCP/IP stack.
673 * This is a violation of the TCP specification.
675 if (drop_synfin && (thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN))
680 * Convert TCP protocol specific fields to host format.
682 th->th_seq = ntohl(th->th_seq);
683 th->th_ack = ntohl(th->th_ack);
684 th->th_win = ntohs(th->th_win);
685 th->th_urp = ntohs(th->th_urp);
688 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
689 * until after ip6_savecontrol() is called and before other functions
690 * which don't want those proto headers.
691 * Because ip6_savecontrol() is going to parse the mbuf to
692 * search for data to be passed up to user-land, it wants mbuf
693 * parameters to be unchanged.
694 * XXX: the call of ip6_savecontrol() has been obsoleted based on
695 * latest version of the advanced API (20020110).
697 drop_hdrlen = off0 + off;
700 * Locate pcb for segment.
703 /* IPFIREWALL_FORWARD section */
704 if (next_hop != NULL && !isipv6) { /* IPv6 support is not there yet */
706 * Transparently forwarded. Pretend to be the destination.
707 * already got one like this?
709 cpu = mycpu->gd_cpuid;
710 inp = in_pcblookup_hash(&tcbinfo[cpu],
711 ip->ip_src, th->th_sport,
712 ip->ip_dst, th->th_dport,
713 0, m->m_pkthdr.rcvif);
716 * It's new. Try to find the ambushing socket.
720 * The rest of the ipfw code stores the port in
722 * (The IP address is still in network order.)
724 in_port_t dport = next_hop->sin_port ?
725 htons(next_hop->sin_port) :
728 cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
729 next_hop->sin_addr.s_addr, dport);
730 inp = in_pcblookup_hash(&tcbinfo[cpu],
731 ip->ip_src, th->th_sport,
732 next_hop->sin_addr, dport,
733 1, m->m_pkthdr.rcvif);
737 inp = in6_pcblookup_hash(&tcbinfo[0],
738 &ip6->ip6_src, th->th_sport,
739 &ip6->ip6_dst, th->th_dport,
740 1, m->m_pkthdr.rcvif);
742 cpu = mycpu->gd_cpuid;
743 inp = in_pcblookup_hash(&tcbinfo[cpu],
744 ip->ip_src, th->th_sport,
745 ip->ip_dst, th->th_dport,
746 1, m->m_pkthdr.rcvif);
751 * If the state is CLOSED (i.e., TCB does not exist) then
752 * all data in the incoming segment is discarded.
753 * If the TCB exists but is in CLOSED state, it is embryonic,
754 * but should either do a listen or a connect soon.
759 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
761 char dbuf[sizeof "aaa.bbb.ccc.ddd"];
762 char sbuf[sizeof "aaa.bbb.ccc.ddd"];
766 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
769 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
772 strcpy(dbuf, inet_ntoa(ip->ip_dst));
773 strcpy(sbuf, inet_ntoa(ip->ip_src));
775 switch (log_in_vain) {
777 if (!(thflags & TH_SYN))
781 "Connection attempt to TCP %s:%d "
782 "from %s:%d flags:0x%02x\n",
783 dbuf, ntohs(th->th_dport), sbuf,
784 ntohs(th->th_sport), thflags);
793 if (thflags & TH_SYN)
802 rstreason = BANDLIM_RST_CLOSEDPORT;
808 if (ipsec6_in_reject_so(m, inp->inp_socket)) {
809 ipsec6stat.in_polvio++;
813 if (ipsec4_in_reject_so(m, inp->inp_socket)) {
814 ipsecstat.in_polvio++;
821 if (ipsec6_in_reject(m, inp))
824 if (ipsec4_in_reject(m, inp))
828 /* Check the minimum TTL for socket. */
830 if ((isipv6 ? ip6->ip6_hlim : ip->ip_ttl) < inp->inp_ip_minttl)
836 rstreason = BANDLIM_RST_CLOSEDPORT;
839 if (tp->t_state <= TCPS_CLOSED)
842 /* Unscale the window into a 32-bit value. */
843 if (!(thflags & TH_SYN))
844 tiwin = th->th_win << tp->snd_scale;
848 so = inp->inp_socket;
851 if (so->so_options & SO_DEBUG) {
852 ostate = tp->t_state;
854 bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
856 bcopy(ip, tcp_saveipgen, sizeof(*ip));
861 bzero(&to, sizeof to);
863 if (so->so_options & SO_ACCEPTCONN) {
864 struct in_conninfo inc;
867 inc.inc_isipv6 = (isipv6 == TRUE);
870 inc.inc6_faddr = ip6->ip6_src;
871 inc.inc6_laddr = ip6->ip6_dst;
872 inc.inc6_route.ro_rt = NULL; /* XXX */
874 inc.inc_faddr = ip->ip_src;
875 inc.inc_laddr = ip->ip_dst;
876 inc.inc_route.ro_rt = NULL; /* XXX */
878 inc.inc_fport = th->th_sport;
879 inc.inc_lport = th->th_dport;
882 * If the state is LISTEN then ignore segment if it contains
883 * a RST. If the segment contains an ACK then it is bad and
884 * send a RST. If it does not contain a SYN then it is not
885 * interesting; drop it.
887 * If the state is SYN_RECEIVED (syncache) and seg contains
888 * an ACK, but not for our SYN/ACK, send a RST. If the seg
889 * contains a RST, check the sequence number to see if it
890 * is a valid reset segment.
892 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
893 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) == TH_ACK) {
894 if (!syncache_expand(&inc, th, &so, m)) {
896 * No syncache entry, or ACK was not
897 * for our SYN/ACK. Send a RST.
899 tcpstat.tcps_badsyn++;
900 rstreason = BANDLIM_RST_OPENPORT;
905 * Could not complete 3-way handshake,
906 * connection is being closed down, and
907 * syncache will free mbuf.
913 * We must be in the correct protocol thread
914 * for this connection.
916 KKASSERT(so->so_port == &curthread->td_msgport);
919 * Socket is created in state SYN_RECEIVED.
920 * Continue processing segment.
925 * This is what would have happened in
926 * tcp_output() when the SYN,ACK was sent.
928 tp->snd_up = tp->snd_una;
929 tp->snd_max = tp->snd_nxt = tp->iss + 1;
930 tp->last_ack_sent = tp->rcv_nxt;
932 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
933 * until the _second_ ACK is received:
934 * rcv SYN (set wscale opts) --> send SYN/ACK, set snd_wnd = window.
935 * rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
936 * move to ESTAB, set snd_wnd to tiwin.
938 tp->snd_wnd = tiwin; /* unscaled */
941 if (thflags & TH_RST) {
942 syncache_chkrst(&inc, th);
945 if (thflags & TH_ACK) {
946 syncache_badack(&inc);
947 tcpstat.tcps_badsyn++;
948 rstreason = BANDLIM_RST_OPENPORT;
955 * Segment's flags are (SYN) or (SYN | FIN).
959 * If deprecated address is forbidden,
960 * we do not accept SYN to deprecated interface
961 * address to prevent any new inbound connection from
962 * getting established.
963 * When we do not accept SYN, we send a TCP RST,
964 * with deprecated source address (instead of dropping
965 * it). We compromise it as it is much better for peer
966 * to send a RST, and RST will be the final packet
969 * If we do not forbid deprecated addresses, we accept
970 * the SYN packet. RFC2462 does not suggest dropping
972 * If we decipher RFC2462 5.5.4, it says like this:
973 * 1. use of deprecated addr with existing
974 * communication is okay - "SHOULD continue to be
976 * 2. use of it with new communication:
977 * (2a) "SHOULD NOT be used if alternate address
978 * with sufficient scope is available"
979 * (2b) nothing mentioned otherwise.
980 * Here we fall into (2b) case as we have no choice in
981 * our source address selection - we must obey the peer.
983 * The wording in RFC2462 is confusing, and there are
984 * multiple description text for deprecated address
985 * handling - worse, they are not exactly the same.
986 * I believe 5.5.4 is the best one, so we follow 5.5.4.
988 if (isipv6 && !ip6_use_deprecated) {
989 struct in6_ifaddr *ia6;
991 if ((ia6 = ip6_getdstifaddr(m)) &&
992 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
994 rstreason = BANDLIM_RST_OPENPORT;
1000 * If it is from this socket, drop it, it must be forged.
1001 * Don't bother responding if the destination was a broadcast.
1003 if (th->th_dport == th->th_sport) {
1005 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
1009 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
1014 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1016 * Note that it is quite possible to receive unicast
1017 * link-layer packets with a broadcast IP address. Use
1018 * in_broadcast() to find them.
1020 if (m->m_flags & (M_BCAST | M_MCAST))
1023 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1024 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
1027 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1028 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1029 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1030 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1034 * SYN appears to be valid; create compressed TCP state
1035 * for syncache, or perform t/tcp connection.
1037 if (so->so_qlen <= so->so_qlimit) {
1038 tcp_dooptions(&to, optp, optlen, TRUE);
1039 if (!syncache_add(&inc, &to, th, &so, m))
1043 * Entry added to syncache, mbuf used to
1044 * send SYN,ACK packet.
1050 * We must be in the correct protocol thread for
1053 KKASSERT(so->so_port == &curthread->td_msgport);
1056 tp = intotcpcb(inp);
1057 tp->snd_wnd = tiwin;
1058 tp->t_starttime = ticks;
1059 tp->t_state = TCPS_ESTABLISHED;
1062 * If there is a FIN, or if there is data and the
1063 * connection is local, then delay SYN,ACK(SYN) in
1064 * the hope of piggy-backing it on a response
1065 * segment. Otherwise must send ACK now in case
1066 * the other side is slow starting.
1068 if (DELAY_ACK(tp) &&
1069 ((thflags & TH_FIN) ||
1071 ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
1072 (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
1073 tcp_callout_reset(tp, tp->tt_delack,
1074 tcp_delacktime, tcp_timer_delack);
1075 tp->t_flags |= TF_NEEDSYN;
1077 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1080 tcpstat.tcps_connects++;
1089 * Should not happen - syncache should pick up these connections.
1091 * Once we are past handling listen sockets we must be in the
1092 * correct protocol processing thread.
1094 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN state"));
1095 KKASSERT(so->so_port == &curthread->td_msgport);
1098 * This is the second part of the MSS DoS prevention code (after
1099 * minmss on the sending side) and it deals with too many too small
1100 * tcp packets in a too short timeframe (1 second).
1102 * XXX Removed. This code was crap. It does not scale to network
1103 * speed, and default values break NFS. Gone.
1108 * Segment received on connection.
1110 * Reset idle time and keep-alive timer. Don't waste time if less
1111 * then a second has elapsed. Only update t_rcvtime for non-SYN
1114 * Handle the case where one side thinks the connection is established
1115 * but the other side has, say, rebooted without cleaning out the
1116 * connection. The SYNs could be construed as an attack and wind
1117 * up ignored, but in case it isn't an attack we can validate the
1118 * connection by forcing a keepalive.
1120 if (TCPS_HAVEESTABLISHED(tp->t_state) && (ticks - tp->t_rcvtime) > hz) {
1121 if ((thflags & (TH_SYN | TH_ACK)) == TH_SYN) {
1122 tp->t_flags |= TF_KEEPALIVE;
1123 tcp_callout_reset(tp, tp->tt_keep, hz / 2,
1126 tp->t_rcvtime = ticks;
1127 tp->t_flags &= ~TF_KEEPALIVE;
1128 tcp_callout_reset(tp, tp->tt_keep, tcp_keepidle,
1135 * XXX this is tradtitional behavior, may need to be cleaned up.
1137 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0);
1138 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1139 if (to.to_flags & TOF_SCALE) {
1140 tp->t_flags |= TF_RCVD_SCALE;
1141 tp->requested_s_scale = to.to_requested_s_scale;
1143 if (to.to_flags & TOF_TS) {
1144 tp->t_flags |= TF_RCVD_TSTMP;
1145 tp->ts_recent = to.to_tsval;
1146 tp->ts_recent_age = ticks;
1148 if (to.to_flags & TOF_MSS)
1149 tcp_mss(tp, to.to_mss);
1151 * Only set the TF_SACK_PERMITTED per-connection flag
1152 * if we got a SACK_PERMITTED option from the other side
1153 * and the global tcp_do_sack variable is true.
1155 if (tcp_do_sack && (to.to_flags & TOF_SACK_PERMITTED))
1156 tp->t_flags |= TF_SACK_PERMITTED;
1160 * Header prediction: check for the two common cases
1161 * of a uni-directional data xfer. If the packet has
1162 * no control flags, is in-sequence, the window didn't
1163 * change and we're not retransmitting, it's a
1164 * candidate. If the length is zero and the ack moved
1165 * forward, we're the sender side of the xfer. Just
1166 * free the data acked & wake any higher level process
1167 * that was blocked waiting for space. If the length
1168 * is non-zero and the ack didn't move, we're the
1169 * receiver side. If we're getting packets in-order
1170 * (the reassembly queue is empty), add the data to
1171 * the socket buffer and note that we need a delayed ack.
1172 * Make sure that the hidden state-flags are also off.
1173 * Since we check for TCPS_ESTABLISHED above, it can only
1176 if (tp->t_state == TCPS_ESTABLISHED &&
1177 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1178 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1179 (!(to.to_flags & TOF_TS) ||
1180 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1181 th->th_seq == tp->rcv_nxt &&
1182 tp->snd_nxt == tp->snd_max) {
1185 * If last ACK falls within this segment's sequence numbers,
1186 * record the timestamp.
1187 * NOTE that the test is modified according to the latest
1188 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1190 if ((to.to_flags & TOF_TS) &&
1191 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1192 tp->ts_recent_age = ticks;
1193 tp->ts_recent = to.to_tsval;
1197 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1198 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1199 tp->snd_cwnd >= tp->snd_wnd &&
1200 !IN_FASTRECOVERY(tp)) {
1202 * This is a pure ack for outstanding data.
1204 ++tcpstat.tcps_predack;
1206 * "bad retransmit" recovery
1208 * If Eifel detection applies, then
1209 * it is deterministic, so use it
1210 * unconditionally over the old heuristic.
1211 * Otherwise, fall back to the old heuristic.
1213 if (tcp_do_eifel_detect &&
1214 (to.to_flags & TOF_TS) && to.to_tsecr &&
1215 (tp->t_flags & TF_FIRSTACCACK)) {
1216 /* Eifel detection applicable. */
1217 if (to.to_tsecr < tp->t_rexmtTS) {
1218 tcp_revert_congestion_state(tp);
1219 ++tcpstat.tcps_eifeldetected;
1221 } else if (tp->t_rxtshift == 1 &&
1222 ticks < tp->t_badrxtwin) {
1223 tcp_revert_congestion_state(tp);
1224 ++tcpstat.tcps_rttdetected;
1226 tp->t_flags &= ~(TF_FIRSTACCACK |
1227 TF_FASTREXMT | TF_EARLYREXMT);
1229 * Recalculate the retransmit timer / rtt.
1231 * Some machines (certain windows boxes)
1232 * send broken timestamp replies during the
1233 * SYN+ACK phase, ignore timestamps of 0.
1235 if ((to.to_flags & TOF_TS) && to.to_tsecr) {
1237 ticks - to.to_tsecr + 1);
1238 } else if (tp->t_rtttime &&
1239 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1241 ticks - tp->t_rtttime);
1243 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1244 acked = th->th_ack - tp->snd_una;
1245 tcpstat.tcps_rcvackpack++;
1246 tcpstat.tcps_rcvackbyte += acked;
1247 sbdrop(&so->so_snd.sb, acked);
1248 tp->snd_recover = th->th_ack - 1;
1249 tp->snd_una = th->th_ack;
1252 * Update window information.
1254 if (tiwin != tp->snd_wnd &&
1255 acceptable_window_update(tp, th, tiwin)) {
1256 /* keep track of pure window updates */
1257 if (tp->snd_wl2 == th->th_ack &&
1258 tiwin > tp->snd_wnd)
1259 tcpstat.tcps_rcvwinupd++;
1260 tp->snd_wnd = tiwin;
1261 tp->snd_wl1 = th->th_seq;
1262 tp->snd_wl2 = th->th_ack;
1263 if (tp->snd_wnd > tp->max_sndwnd)
1264 tp->max_sndwnd = tp->snd_wnd;
1267 ND6_HINT(tp); /* some progress has been done */
1269 * If all outstanding data are acked, stop
1270 * retransmit timer, otherwise restart timer
1271 * using current (possibly backed-off) value.
1272 * If process is waiting for space,
1273 * wakeup/selwakeup/signal. If data
1274 * are ready to send, let tcp_output
1275 * decide between more output or persist.
1277 if (tp->snd_una == tp->snd_max) {
1278 tcp_callout_stop(tp, tp->tt_rexmt);
1279 } else if (!tcp_callout_active(tp,
1281 tcp_callout_reset(tp, tp->tt_rexmt,
1282 tp->t_rxtcur, tcp_timer_rexmt);
1285 if (so->so_snd.ssb_cc > 0)
1289 } else if (tiwin == tp->snd_wnd &&
1290 th->th_ack == tp->snd_una &&
1291 LIST_EMPTY(&tp->t_segq) &&
1292 tlen <= ssb_space(&so->so_rcv)) {
1293 u_long newsize = 0; /* automatic sockbuf scaling */
1295 * This is a pure, in-sequence data packet
1296 * with nothing on the reassembly queue and
1297 * we have enough buffer space to take it.
1299 ++tcpstat.tcps_preddat;
1300 tp->rcv_nxt += tlen;
1301 tcpstat.tcps_rcvpack++;
1302 tcpstat.tcps_rcvbyte += tlen;
1303 ND6_HINT(tp); /* some progress has been done */
1305 * Automatic sizing of receive socket buffer. Often the send
1306 * buffer size is not optimally adjusted to the actual network
1307 * conditions at hand (delay bandwidth product). Setting the
1308 * buffer size too small limits throughput on links with high
1309 * bandwidth and high delay (eg. trans-continental/oceanic links).
1311 * On the receive side the socket buffer memory is only rarely
1312 * used to any significant extent. This allows us to be much
1313 * more aggressive in scaling the receive socket buffer. For
1314 * the case that the buffer space is actually used to a large
1315 * extent and we run out of kernel memory we can simply drop
1316 * the new segments; TCP on the sender will just retransmit it
1317 * later. Setting the buffer size too big may only consume too
1318 * much kernel memory if the application doesn't read() from
1319 * the socket or packet loss or reordering makes use of the
1322 * The criteria to step up the receive buffer one notch are:
1323 * 1. the number of bytes received during the time it takes
1324 * one timestamp to be reflected back to us (the RTT);
1325 * 2. received bytes per RTT is within seven eighth of the
1326 * current socket buffer size;
1327 * 3. receive buffer size has not hit maximal automatic size;
1329 * This algorithm does one step per RTT at most and only if
1330 * we receive a bulk stream w/o packet losses or reorderings.
1331 * Shrinking the buffer during idle times is not necessary as
1332 * it doesn't consume any memory when idle.
1334 * TODO: Only step up if the application is actually serving
1335 * the buffer to better manage the socket buffer resources.
1337 if (tcp_do_autorcvbuf &&
1339 (so->so_rcv.ssb_flags & SSB_AUTOSIZE)) {
1340 if (to.to_tsecr > tp->rfbuf_ts &&
1341 to.to_tsecr - tp->rfbuf_ts < hz) {
1343 (so->so_rcv.ssb_hiwat / 8 * 7) &&
1344 so->so_rcv.ssb_hiwat <
1345 tcp_autorcvbuf_max) {
1347 ulmin(so->so_rcv.ssb_hiwat +
1349 tcp_autorcvbuf_max);
1351 /* Start over with next RTT. */
1355 tp->rfbuf_cnt += tlen; /* add up */
1358 * Add data to socket buffer.
1360 if (so->so_state & SS_CANTRCVMORE) {
1364 * Set new socket buffer size, give up when
1367 * Adjusting the size can mess up ACK
1368 * sequencing when pure window updates are
1369 * being avoided (which is the default),
1372 lwkt_gettoken(&so->so_rcv.ssb_token);
1374 tp->t_flags |= TF_RXRESIZED;
1375 if (!ssb_reserve(&so->so_rcv, newsize,
1377 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1380 (TCP_MAXWIN << tp->rcv_scale)) {
1381 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1384 m_adj(m, drop_hdrlen); /* delayed header drop */
1385 ssb_appendstream(&so->so_rcv, m);
1386 lwkt_reltoken(&so->so_rcv.ssb_token);
1390 * This code is responsible for most of the ACKs
1391 * the TCP stack sends back after receiving a data
1392 * packet. Note that the DELAY_ACK check fails if
1393 * the delack timer is already running, which results
1394 * in an ack being sent every other packet (which is
1397 * We then further aggregate acks by not actually
1398 * sending one until the protocol thread has completed
1399 * processing the current backlog of packets. This
1400 * does not delay the ack any further, but allows us
1401 * to take advantage of the packet aggregation that
1402 * high speed NICs do (usually blocks of 8-10 packets)
1403 * to send a single ack rather then four or five acks,
1404 * greatly reducing the ack rate, the return channel
1405 * bandwidth, and the protocol overhead on both ends.
1407 * Since this also has the effect of slowing down
1408 * the exponential slow-start ramp-up, systems with
1409 * very large bandwidth-delay products might want
1410 * to turn the feature off.
1412 if (DELAY_ACK(tp)) {
1413 tcp_callout_reset(tp, tp->tt_delack,
1414 tcp_delacktime, tcp_timer_delack);
1415 } else if (tcp_aggregate_acks) {
1416 tp->t_flags |= TF_ACKNOW;
1417 if (!(tp->t_flags & TF_ONOUTPUTQ)) {
1418 tp->t_flags |= TF_ONOUTPUTQ;
1419 tp->tt_cpu = mycpu->gd_cpuid;
1421 &tcpcbackq[tp->tt_cpu],
1425 tp->t_flags |= TF_ACKNOW;
1433 * Calculate amount of space in receive window,
1434 * and then do TCP input processing.
1435 * Receive window is amount of space in rcv queue,
1436 * but not less than advertised window.
1438 recvwin = ssb_space(&so->so_rcv);
1441 tp->rcv_wnd = imax(recvwin, (int)(tp->rcv_adv - tp->rcv_nxt));
1443 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1447 switch (tp->t_state) {
1449 * If the state is SYN_RECEIVED:
1450 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1452 case TCPS_SYN_RECEIVED:
1453 if ((thflags & TH_ACK) &&
1454 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1455 SEQ_GT(th->th_ack, tp->snd_max))) {
1456 rstreason = BANDLIM_RST_OPENPORT;
1462 * If the state is SYN_SENT:
1463 * if seg contains an ACK, but not for our SYN, drop the input.
1464 * if seg contains a RST, then drop the connection.
1465 * if seg does not contain SYN, then drop it.
1466 * Otherwise this is an acceptable SYN segment
1467 * initialize tp->rcv_nxt and tp->irs
1468 * if seg contains ack then advance tp->snd_una
1469 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1470 * arrange for segment to be acked (eventually)
1471 * continue processing rest of data/controls, beginning with URG
1474 if ((thflags & TH_ACK) &&
1475 (SEQ_LEQ(th->th_ack, tp->iss) ||
1476 SEQ_GT(th->th_ack, tp->snd_max))) {
1477 rstreason = BANDLIM_UNLIMITED;
1480 if (thflags & TH_RST) {
1481 if (thflags & TH_ACK)
1482 tp = tcp_drop(tp, ECONNREFUSED);
1485 if (!(thflags & TH_SYN))
1487 tp->snd_wnd = th->th_win; /* initial send window */
1489 tp->irs = th->th_seq;
1491 if (thflags & TH_ACK) {
1492 /* Our SYN was acked. */
1493 tcpstat.tcps_connects++;
1495 /* Do window scaling on this connection? */
1496 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1497 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1498 tp->snd_scale = tp->requested_s_scale;
1499 tp->rcv_scale = tp->request_r_scale;
1501 tp->rcv_adv += tp->rcv_wnd;
1502 tp->snd_una++; /* SYN is acked */
1503 tcp_callout_stop(tp, tp->tt_rexmt);
1505 * If there's data, delay ACK; if there's also a FIN
1506 * ACKNOW will be turned on later.
1508 if (DELAY_ACK(tp) && tlen != 0) {
1509 tcp_callout_reset(tp, tp->tt_delack,
1510 tcp_delacktime, tcp_timer_delack);
1512 tp->t_flags |= TF_ACKNOW;
1515 * Received <SYN,ACK> in SYN_SENT[*] state.
1517 * SYN_SENT --> ESTABLISHED
1518 * SYN_SENT* --> FIN_WAIT_1
1520 tp->t_starttime = ticks;
1521 if (tp->t_flags & TF_NEEDFIN) {
1522 tp->t_state = TCPS_FIN_WAIT_1;
1523 tp->t_flags &= ~TF_NEEDFIN;
1526 tp->t_state = TCPS_ESTABLISHED;
1527 tcp_callout_reset(tp, tp->tt_keep, tcp_keepidle,
1532 * Received initial SYN in SYN-SENT[*] state =>
1533 * simultaneous open.
1534 * Do 3-way handshake:
1535 * SYN-SENT -> SYN-RECEIVED
1536 * SYN-SENT* -> SYN-RECEIVED*
1538 tp->t_flags |= TF_ACKNOW;
1539 tcp_callout_stop(tp, tp->tt_rexmt);
1540 tp->t_state = TCPS_SYN_RECEIVED;
1545 * Advance th->th_seq to correspond to first data byte.
1546 * If data, trim to stay within window,
1547 * dropping FIN if necessary.
1550 if (tlen > tp->rcv_wnd) {
1551 todrop = tlen - tp->rcv_wnd;
1555 tcpstat.tcps_rcvpackafterwin++;
1556 tcpstat.tcps_rcvbyteafterwin += todrop;
1558 tp->snd_wl1 = th->th_seq - 1;
1559 tp->rcv_up = th->th_seq;
1561 * Client side of transaction: already sent SYN and data.
1562 * If the remote host used T/TCP to validate the SYN,
1563 * our data will be ACK'd; if so, enter normal data segment
1564 * processing in the middle of step 5, ack processing.
1565 * Otherwise, goto step 6.
1567 if (thflags & TH_ACK)
1573 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1574 * do normal processing (we no longer bother with T/TCP).
1578 case TCPS_TIME_WAIT:
1579 break; /* continue normal processing */
1583 * States other than LISTEN or SYN_SENT.
1584 * First check the RST flag and sequence number since reset segments
1585 * are exempt from the timestamp and connection count tests. This
1586 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1587 * below which allowed reset segments in half the sequence space
1588 * to fall though and be processed (which gives forged reset
1589 * segments with a random sequence number a 50 percent chance of
1590 * killing a connection).
1591 * Then check timestamp, if present.
1592 * Then check the connection count, if present.
1593 * Then check that at least some bytes of segment are within
1594 * receive window. If segment begins before rcv_nxt,
1595 * drop leading data (and SYN); if nothing left, just ack.
1598 * If the RST bit is set, check the sequence number to see
1599 * if this is a valid reset segment.
1601 * In all states except SYN-SENT, all reset (RST) segments
1602 * are validated by checking their SEQ-fields. A reset is
1603 * valid if its sequence number is in the window.
1604 * Note: this does not take into account delayed ACKs, so
1605 * we should test against last_ack_sent instead of rcv_nxt.
1606 * The sequence number in the reset segment is normally an
1607 * echo of our outgoing acknowledgement numbers, but some hosts
1608 * send a reset with the sequence number at the rightmost edge
1609 * of our receive window, and we have to handle this case.
1610 * If we have multiple segments in flight, the intial reset
1611 * segment sequence numbers will be to the left of last_ack_sent,
1612 * but they will eventually catch up.
1613 * In any case, it never made sense to trim reset segments to
1614 * fit the receive window since RFC 1122 says:
1615 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1617 * A TCP SHOULD allow a received RST segment to include data.
1620 * It has been suggested that a RST segment could contain
1621 * ASCII text that encoded and explained the cause of the
1622 * RST. No standard has yet been established for such
1625 * If the reset segment passes the sequence number test examine
1627 * SYN_RECEIVED STATE:
1628 * If passive open, return to LISTEN state.
1629 * If active open, inform user that connection was refused.
1630 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1631 * Inform user that connection was reset, and close tcb.
1632 * CLOSING, LAST_ACK STATES:
1635 * Drop the segment - see Stevens, vol. 2, p. 964 and
1638 if (thflags & TH_RST) {
1639 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1640 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1641 switch (tp->t_state) {
1643 case TCPS_SYN_RECEIVED:
1644 so->so_error = ECONNREFUSED;
1647 case TCPS_ESTABLISHED:
1648 case TCPS_FIN_WAIT_1:
1649 case TCPS_FIN_WAIT_2:
1650 case TCPS_CLOSE_WAIT:
1651 so->so_error = ECONNRESET;
1653 tp->t_state = TCPS_CLOSED;
1654 tcpstat.tcps_drops++;
1663 case TCPS_TIME_WAIT:
1671 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1672 * and it's less than ts_recent, drop it.
1674 if ((to.to_flags & TOF_TS) && tp->ts_recent != 0 &&
1675 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1677 /* Check to see if ts_recent is over 24 days old. */
1678 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1680 * Invalidate ts_recent. If this segment updates
1681 * ts_recent, the age will be reset later and ts_recent
1682 * will get a valid value. If it does not, setting
1683 * ts_recent to zero will at least satisfy the
1684 * requirement that zero be placed in the timestamp
1685 * echo reply when ts_recent isn't valid. The
1686 * age isn't reset until we get a valid ts_recent
1687 * because we don't want out-of-order segments to be
1688 * dropped when ts_recent is old.
1692 tcpstat.tcps_rcvduppack++;
1693 tcpstat.tcps_rcvdupbyte += tlen;
1694 tcpstat.tcps_pawsdrop++;
1702 * In the SYN-RECEIVED state, validate that the packet belongs to
1703 * this connection before trimming the data to fit the receive
1704 * window. Check the sequence number versus IRS since we know
1705 * the sequence numbers haven't wrapped. This is a partial fix
1706 * for the "LAND" DoS attack.
1708 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1709 rstreason = BANDLIM_RST_OPENPORT;
1713 todrop = tp->rcv_nxt - th->th_seq;
1715 if (TCP_DO_SACK(tp)) {
1716 /* Report duplicate segment at head of packet. */
1717 tp->reportblk.rblk_start = th->th_seq;
1718 tp->reportblk.rblk_end = th->th_seq + tlen;
1719 if (thflags & TH_FIN)
1720 ++tp->reportblk.rblk_end;
1721 if (SEQ_GT(tp->reportblk.rblk_end, tp->rcv_nxt))
1722 tp->reportblk.rblk_end = tp->rcv_nxt;
1723 tp->t_flags |= (TF_DUPSEG | TF_SACKLEFT | TF_ACKNOW);
1725 if (thflags & TH_SYN) {
1735 * Following if statement from Stevens, vol. 2, p. 960.
1737 if (todrop > tlen ||
1738 (todrop == tlen && !(thflags & TH_FIN))) {
1740 * Any valid FIN must be to the left of the window.
1741 * At this point the FIN must be a duplicate or out
1742 * of sequence; drop it.
1747 * Send an ACK to resynchronize and drop any data.
1748 * But keep on processing for RST or ACK.
1750 tp->t_flags |= TF_ACKNOW;
1752 tcpstat.tcps_rcvduppack++;
1753 tcpstat.tcps_rcvdupbyte += todrop;
1755 tcpstat.tcps_rcvpartduppack++;
1756 tcpstat.tcps_rcvpartdupbyte += todrop;
1758 drop_hdrlen += todrop; /* drop from the top afterwards */
1759 th->th_seq += todrop;
1761 if (th->th_urp > todrop)
1762 th->th_urp -= todrop;
1770 * If new data are received on a connection after the
1771 * user processes are gone, then RST the other end.
1773 if ((so->so_state & SS_NOFDREF) &&
1774 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1776 tcpstat.tcps_rcvafterclose++;
1777 rstreason = BANDLIM_UNLIMITED;
1782 * If segment ends after window, drop trailing data
1783 * (and PUSH and FIN); if nothing left, just ACK.
1785 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1787 tcpstat.tcps_rcvpackafterwin++;
1788 if (todrop >= tlen) {
1789 tcpstat.tcps_rcvbyteafterwin += tlen;
1791 * If a new connection request is received
1792 * while in TIME_WAIT, drop the old connection
1793 * and start over if the sequence numbers
1794 * are above the previous ones.
1796 if (thflags & TH_SYN &&
1797 tp->t_state == TCPS_TIME_WAIT &&
1798 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1803 * If window is closed can only take segments at
1804 * window edge, and have to drop data and PUSH from
1805 * incoming segments. Continue processing, but
1806 * remember to ack. Otherwise, drop segment
1809 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1810 tp->t_flags |= TF_ACKNOW;
1811 tcpstat.tcps_rcvwinprobe++;
1815 tcpstat.tcps_rcvbyteafterwin += todrop;
1818 thflags &= ~(TH_PUSH | TH_FIN);
1822 * If last ACK falls within this segment's sequence numbers,
1823 * record its timestamp.
1825 * 1) That the test incorporates suggestions from the latest
1826 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1827 * 2) That updating only on newer timestamps interferes with
1828 * our earlier PAWS tests, so this check should be solely
1829 * predicated on the sequence space of this segment.
1830 * 3) That we modify the segment boundary check to be
1831 * Last.ACK.Sent <= SEG.SEQ + SEG.LEN
1832 * instead of RFC1323's
1833 * Last.ACK.Sent < SEG.SEQ + SEG.LEN,
1834 * This modified check allows us to overcome RFC1323's
1835 * limitations as described in Stevens TCP/IP Illustrated
1836 * Vol. 2 p.869. In such cases, we can still calculate the
1837 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1839 if ((to.to_flags & TOF_TS) && SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1840 SEQ_LEQ(tp->last_ack_sent, (th->th_seq + tlen
1841 + ((thflags & TH_SYN) != 0)
1842 + ((thflags & TH_FIN) != 0)))) {
1843 tp->ts_recent_age = ticks;
1844 tp->ts_recent = to.to_tsval;
1848 * If a SYN is in the window, then this is an
1849 * error and we send an RST and drop the connection.
1851 if (thflags & TH_SYN) {
1852 tp = tcp_drop(tp, ECONNRESET);
1853 rstreason = BANDLIM_UNLIMITED;
1858 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1859 * flag is on (half-synchronized state), then queue data for
1860 * later processing; else drop segment and return.
1862 if (!(thflags & TH_ACK)) {
1863 if (tp->t_state == TCPS_SYN_RECEIVED ||
1864 (tp->t_flags & TF_NEEDSYN))
1873 switch (tp->t_state) {
1875 * In SYN_RECEIVED state, the ACK acknowledges our SYN, so enter
1876 * ESTABLISHED state and continue processing.
1877 * The ACK was checked above.
1879 case TCPS_SYN_RECEIVED:
1881 tcpstat.tcps_connects++;
1883 /* Do window scaling? */
1884 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1885 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
1886 tp->snd_scale = tp->requested_s_scale;
1887 tp->rcv_scale = tp->request_r_scale;
1891 * SYN-RECEIVED -> ESTABLISHED
1892 * SYN-RECEIVED* -> FIN-WAIT-1
1894 tp->t_starttime = ticks;
1895 if (tp->t_flags & TF_NEEDFIN) {
1896 tp->t_state = TCPS_FIN_WAIT_1;
1897 tp->t_flags &= ~TF_NEEDFIN;
1899 tp->t_state = TCPS_ESTABLISHED;
1900 tcp_callout_reset(tp, tp->tt_keep, tcp_keepidle,
1904 * If segment contains data or ACK, will call tcp_reass()
1905 * later; if not, do so now to pass queued data to user.
1907 if (tlen == 0 && !(thflags & TH_FIN))
1908 tcp_reass(tp, NULL, NULL, NULL);
1912 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1913 * ACKs. If the ack is in the range
1914 * tp->snd_una < th->th_ack <= tp->snd_max
1915 * then advance tp->snd_una to th->th_ack and drop
1916 * data from the retransmission queue. If this ACK reflects
1917 * more up to date window information we update our window information.
1919 case TCPS_ESTABLISHED:
1920 case TCPS_FIN_WAIT_1:
1921 case TCPS_FIN_WAIT_2:
1922 case TCPS_CLOSE_WAIT:
1925 case TCPS_TIME_WAIT:
1927 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1928 if (TCP_DO_SACK(tp))
1929 tcp_sack_update_scoreboard(tp, &to);
1930 if (tlen != 0 || tiwin != tp->snd_wnd) {
1934 tcpstat.tcps_rcvdupack++;
1935 if (!tcp_callout_active(tp, tp->tt_rexmt) ||
1936 th->th_ack != tp->snd_una) {
1941 * We have outstanding data (other than
1942 * a window probe), this is a completely
1943 * duplicate ack (ie, window info didn't
1944 * change), the ack is the biggest we've
1945 * seen and we've seen exactly our rexmt
1946 * threshhold of them, so assume a packet
1947 * has been dropped and retransmit it.
1948 * Kludge snd_nxt & the congestion
1949 * window so we send only this one
1952 if (IN_FASTRECOVERY(tp)) {
1953 if (TCP_DO_SACK(tp)) {
1954 /* No artifical cwnd inflation. */
1955 tcp_sack_rexmt(tp, th);
1958 * Dup acks mean that packets
1959 * have left the network
1960 * (they're now cached at the
1961 * receiver) so bump cwnd by
1962 * the amount in the receiver
1963 * to keep a constant cwnd
1964 * packets in the network.
1966 tp->snd_cwnd += tp->t_maxseg;
1969 } else if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1972 } else if (++tp->t_dupacks == tcprexmtthresh) {
1973 tcp_seq old_snd_nxt;
1977 if (tcp_do_eifel_detect &&
1978 (tp->t_flags & TF_RCVD_TSTMP)) {
1979 tcp_save_congestion_state(tp);
1980 tp->t_flags |= TF_FASTREXMT;
1983 * We know we're losing at the current
1984 * window size, so do congestion avoidance:
1985 * set ssthresh to half the current window
1986 * and pull our congestion window back to the
1989 win = min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1993 tp->snd_ssthresh = win * tp->t_maxseg;
1994 ENTER_FASTRECOVERY(tp);
1995 tp->snd_recover = tp->snd_max;
1996 tcp_callout_stop(tp, tp->tt_rexmt);
1998 old_snd_nxt = tp->snd_nxt;
1999 tp->snd_nxt = th->th_ack;
2000 tp->snd_cwnd = tp->t_maxseg;
2002 ++tcpstat.tcps_sndfastrexmit;
2003 tp->snd_cwnd = tp->snd_ssthresh;
2004 tp->rexmt_high = tp->snd_nxt;
2005 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
2006 tp->snd_nxt = old_snd_nxt;
2007 KASSERT(tp->snd_limited <= 2,
2008 ("tp->snd_limited too big"));
2009 if (TCP_DO_SACK(tp))
2010 tcp_sack_rexmt(tp, th);
2012 tp->snd_cwnd += tp->t_maxseg *
2013 (tp->t_dupacks - tp->snd_limited);
2014 } else if (tcp_do_limitedtransmit) {
2015 u_long oldcwnd = tp->snd_cwnd;
2016 tcp_seq oldsndmax = tp->snd_max;
2017 tcp_seq oldsndnxt = tp->snd_nxt;
2018 /* outstanding data */
2019 uint32_t ownd = tp->snd_max - tp->snd_una;
2022 #define iceildiv(n, d) (((n)+(d)-1) / (d))
2024 KASSERT(tp->t_dupacks == 1 ||
2026 ("dupacks not 1 or 2"));
2027 if (tp->t_dupacks == 1)
2028 tp->snd_limited = 0;
2029 tp->snd_nxt = tp->snd_max;
2030 tp->snd_cwnd = ownd +
2031 (tp->t_dupacks - tp->snd_limited) *
2036 * Other acks may have been processed,
2037 * snd_nxt cannot be reset to a value less
2040 if (SEQ_LT(oldsndnxt, oldsndmax)) {
2041 if (SEQ_GT(oldsndnxt, tp->snd_una))
2042 tp->snd_nxt = oldsndnxt;
2044 tp->snd_nxt = tp->snd_una;
2046 tp->snd_cwnd = oldcwnd;
2047 sent = tp->snd_max - oldsndmax;
2048 if (sent > tp->t_maxseg) {
2049 KASSERT((tp->t_dupacks == 2 &&
2050 tp->snd_limited == 0) ||
2051 (sent == tp->t_maxseg + 1 &&
2052 tp->t_flags & TF_SENTFIN),
2054 KASSERT(sent <= tp->t_maxseg * 2,
2055 ("sent too many segments"));
2056 tp->snd_limited = 2;
2057 tcpstat.tcps_sndlimited += 2;
2058 } else if (sent > 0) {
2060 ++tcpstat.tcps_sndlimited;
2061 } else if (tcp_do_early_retransmit &&
2062 (tcp_do_eifel_detect &&
2063 (tp->t_flags & TF_RCVD_TSTMP)) &&
2064 ownd < 4 * tp->t_maxseg &&
2065 tp->t_dupacks + 1 >=
2066 iceildiv(ownd, tp->t_maxseg) &&
2067 (!TCP_DO_SACK(tp) ||
2068 ownd <= tp->t_maxseg ||
2069 tcp_sack_has_sacked(&tp->scb,
2070 ownd - tp->t_maxseg))) {
2071 ++tcpstat.tcps_sndearlyrexmit;
2072 tp->t_flags |= TF_EARLYREXMT;
2073 goto fastretransmit;
2079 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
2081 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2083 * Detected optimistic ACK attack.
2084 * Force slow-start to de-synchronize attack.
2086 tp->snd_cwnd = tp->t_maxseg;
2089 tcpstat.tcps_rcvacktoomuch++;
2093 * If we reach this point, ACK is not a duplicate,
2094 * i.e., it ACKs something we sent.
2096 if (tp->t_flags & TF_NEEDSYN) {
2098 * T/TCP: Connection was half-synchronized, and our
2099 * SYN has been ACK'd (so connection is now fully
2100 * synchronized). Go to non-starred state,
2101 * increment snd_una for ACK of SYN, and check if
2102 * we can do window scaling.
2104 tp->t_flags &= ~TF_NEEDSYN;
2106 /* Do window scaling? */
2107 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
2108 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
2109 tp->snd_scale = tp->requested_s_scale;
2110 tp->rcv_scale = tp->request_r_scale;
2115 acked = th->th_ack - tp->snd_una;
2116 tcpstat.tcps_rcvackpack++;
2117 tcpstat.tcps_rcvackbyte += acked;
2119 if (tcp_do_eifel_detect && acked > 0 &&
2120 (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
2121 (tp->t_flags & TF_FIRSTACCACK)) {
2122 /* Eifel detection applicable. */
2123 if (to.to_tsecr < tp->t_rexmtTS) {
2124 ++tcpstat.tcps_eifeldetected;
2125 tcp_revert_congestion_state(tp);
2126 if (tp->t_rxtshift == 1 &&
2127 ticks >= tp->t_badrxtwin)
2128 ++tcpstat.tcps_rttcantdetect;
2130 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2132 * If we just performed our first retransmit,
2133 * and the ACK arrives within our recovery window,
2134 * then it was a mistake to do the retransmit
2135 * in the first place. Recover our original cwnd
2136 * and ssthresh, and proceed to transmit where we
2139 tcp_revert_congestion_state(tp);
2140 ++tcpstat.tcps_rttdetected;
2144 * If we have a timestamp reply, update smoothed
2145 * round trip time. If no timestamp is present but
2146 * transmit timer is running and timed sequence
2147 * number was acked, update smoothed round trip time.
2148 * Since we now have an rtt measurement, cancel the
2149 * timer backoff (cf., Phil Karn's retransmit alg.).
2150 * Recompute the initial retransmit timer.
2152 * Some machines (certain windows boxes) send broken
2153 * timestamp replies during the SYN+ACK phase, ignore
2156 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
2157 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2158 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2159 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2160 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2163 * If no data (only SYN) was ACK'd,
2164 * skip rest of ACK processing.
2169 /* Stop looking for an acceptable ACK since one was received. */
2170 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT | TF_EARLYREXMT);
2172 if (acked > so->so_snd.ssb_cc) {
2173 tp->snd_wnd -= so->so_snd.ssb_cc;
2174 sbdrop(&so->so_snd.sb, (int)so->so_snd.ssb_cc);
2175 ourfinisacked = TRUE;
2177 sbdrop(&so->so_snd.sb, acked);
2178 tp->snd_wnd -= acked;
2179 ourfinisacked = FALSE;
2184 * Update window information.
2185 * Don't look at window if no ACK:
2186 * TAC's send garbage on first SYN.
2188 if (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2189 (tp->snd_wl1 == th->th_seq &&
2190 (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2191 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)))) {
2192 /* keep track of pure window updates */
2193 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2194 tiwin > tp->snd_wnd)
2195 tcpstat.tcps_rcvwinupd++;
2196 tp->snd_wnd = tiwin;
2197 tp->snd_wl1 = th->th_seq;
2198 tp->snd_wl2 = th->th_ack;
2199 if (tp->snd_wnd > tp->max_sndwnd)
2200 tp->max_sndwnd = tp->snd_wnd;
2204 tp->snd_una = th->th_ack;
2205 if (TCP_DO_SACK(tp))
2206 tcp_sack_update_scoreboard(tp, &to);
2207 if (IN_FASTRECOVERY(tp)) {
2208 if (SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2209 EXIT_FASTRECOVERY(tp);
2212 * If the congestion window was inflated
2213 * to account for the other side's
2214 * cached packets, retract it.
2216 if (!TCP_DO_SACK(tp))
2217 tp->snd_cwnd = tp->snd_ssthresh;
2220 * Window inflation should have left us
2221 * with approximately snd_ssthresh outstanding
2222 * data. But, in case we would be inclined
2223 * to send a burst, better do it using
2226 if (SEQ_GT(th->th_ack + tp->snd_cwnd,
2227 tp->snd_max + 2 * tp->t_maxseg))
2229 (tp->snd_max - tp->snd_una) +
2234 if (TCP_DO_SACK(tp)) {
2235 tp->snd_max_rexmt = tp->snd_max;
2236 tcp_sack_rexmt(tp, th);
2238 tcp_newreno_partial_ack(tp, th, acked);
2244 * Open the congestion window. When in slow-start,
2245 * open exponentially: maxseg per packet. Otherwise,
2246 * open linearly: maxseg per window.
2248 if (tp->snd_cwnd <= tp->snd_ssthresh) {
2250 (SEQ_LT(tp->snd_nxt, tp->snd_max) ?
2251 tp->t_maxseg : 2 * tp->t_maxseg);
2254 tp->snd_cwnd += tcp_do_abc ?
2255 min(acked, abc_sslimit) : tp->t_maxseg;
2257 /* linear increase */
2258 tp->snd_wacked += tcp_do_abc ? acked :
2260 if (tp->snd_wacked >= tp->snd_cwnd) {
2261 tp->snd_wacked -= tp->snd_cwnd;
2262 tp->snd_cwnd += tp->t_maxseg;
2265 tp->snd_cwnd = min(tp->snd_cwnd,
2266 TCP_MAXWIN << tp->snd_scale);
2267 tp->snd_recover = th->th_ack - 1;
2269 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2270 tp->snd_nxt = tp->snd_una;
2273 * If all outstanding data is acked, stop retransmit
2274 * timer and remember to restart (more output or persist).
2275 * If there is more data to be acked, restart retransmit
2276 * timer, using current (possibly backed-off) value.
2278 if (th->th_ack == tp->snd_max) {
2279 tcp_callout_stop(tp, tp->tt_rexmt);
2281 } else if (!tcp_callout_active(tp, tp->tt_persist)) {
2282 tcp_callout_reset(tp, tp->tt_rexmt, tp->t_rxtcur,
2286 switch (tp->t_state) {
2288 * In FIN_WAIT_1 STATE in addition to the processing
2289 * for the ESTABLISHED state if our FIN is now acknowledged
2290 * then enter FIN_WAIT_2.
2292 case TCPS_FIN_WAIT_1:
2293 if (ourfinisacked) {
2295 * If we can't receive any more
2296 * data, then closing user can proceed.
2297 * Starting the timer is contrary to the
2298 * specification, but if we don't get a FIN
2299 * we'll hang forever.
2301 if (so->so_state & SS_CANTRCVMORE) {
2302 soisdisconnected(so);
2303 tcp_callout_reset(tp, tp->tt_2msl,
2304 tcp_maxidle, tcp_timer_2msl);
2306 tp->t_state = TCPS_FIN_WAIT_2;
2311 * In CLOSING STATE in addition to the processing for
2312 * the ESTABLISHED state if the ACK acknowledges our FIN
2313 * then enter the TIME-WAIT state, otherwise ignore
2317 if (ourfinisacked) {
2318 tp->t_state = TCPS_TIME_WAIT;
2319 tcp_canceltimers(tp);
2320 tcp_callout_reset(tp, tp->tt_2msl,
2321 2 * tcp_msl, tcp_timer_2msl);
2322 soisdisconnected(so);
2327 * In LAST_ACK, we may still be waiting for data to drain
2328 * and/or to be acked, as well as for the ack of our FIN.
2329 * If our FIN is now acknowledged, delete the TCB,
2330 * enter the closed state and return.
2333 if (ourfinisacked) {
2340 * In TIME_WAIT state the only thing that should arrive
2341 * is a retransmission of the remote FIN. Acknowledge
2342 * it and restart the finack timer.
2344 case TCPS_TIME_WAIT:
2345 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_msl,
2353 * Update window information.
2354 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2356 if ((thflags & TH_ACK) &&
2357 acceptable_window_update(tp, th, tiwin)) {
2358 /* keep track of pure window updates */
2359 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2360 tiwin > tp->snd_wnd)
2361 tcpstat.tcps_rcvwinupd++;
2362 tp->snd_wnd = tiwin;
2363 tp->snd_wl1 = th->th_seq;
2364 tp->snd_wl2 = th->th_ack;
2365 if (tp->snd_wnd > tp->max_sndwnd)
2366 tp->max_sndwnd = tp->snd_wnd;
2371 * Process segments with URG.
2373 if ((thflags & TH_URG) && th->th_urp &&
2374 !TCPS_HAVERCVDFIN(tp->t_state)) {
2376 * This is a kludge, but if we receive and accept
2377 * random urgent pointers, we'll crash in
2378 * soreceive. It's hard to imagine someone
2379 * actually wanting to send this much urgent data.
2381 if (th->th_urp + so->so_rcv.ssb_cc > sb_max) {
2382 th->th_urp = 0; /* XXX */
2383 thflags &= ~TH_URG; /* XXX */
2384 goto dodata; /* XXX */
2387 * If this segment advances the known urgent pointer,
2388 * then mark the data stream. This should not happen
2389 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2390 * a FIN has been received from the remote side.
2391 * In these states we ignore the URG.
2393 * According to RFC961 (Assigned Protocols),
2394 * the urgent pointer points to the last octet
2395 * of urgent data. We continue, however,
2396 * to consider it to indicate the first octet
2397 * of data past the urgent section as the original
2398 * spec states (in one of two places).
2400 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
2401 tp->rcv_up = th->th_seq + th->th_urp;
2402 so->so_oobmark = so->so_rcv.ssb_cc +
2403 (tp->rcv_up - tp->rcv_nxt) - 1;
2404 if (so->so_oobmark == 0)
2405 sosetstate(so, SS_RCVATMARK);
2407 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2410 * Remove out of band data so doesn't get presented to user.
2411 * This can happen independent of advancing the URG pointer,
2412 * but if two URG's are pending at once, some out-of-band
2413 * data may creep in... ick.
2415 if (th->th_urp <= (u_long)tlen &&
2416 !(so->so_options & SO_OOBINLINE)) {
2417 /* hdr drop is delayed */
2418 tcp_pulloutofband(so, th, m, drop_hdrlen);
2422 * If no out of band data is expected,
2423 * pull receive urgent pointer along
2424 * with the receive window.
2426 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2427 tp->rcv_up = tp->rcv_nxt;
2432 * Process the segment text, merging it into the TCP sequencing queue,
2433 * and arranging for acknowledgment of receipt if necessary.
2434 * This process logically involves adjusting tp->rcv_wnd as data
2435 * is presented to the user (this happens in tcp_usrreq.c,
2436 * case PRU_RCVD). If a FIN has already been received on this
2437 * connection then we just ignore the text.
2439 if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
2440 m_adj(m, drop_hdrlen); /* delayed header drop */
2442 * Insert segment which includes th into TCP reassembly queue
2443 * with control block tp. Set thflags to whether reassembly now
2444 * includes a segment with FIN. This handles the common case
2445 * inline (segment is the next to be received on an established
2446 * connection, and the queue is empty), avoiding linkage into
2447 * and removal from the queue and repetition of various
2449 * Set DELACK for segments received in order, but ack
2450 * immediately when segments are out of order (so
2451 * fast retransmit can work).
2453 if (th->th_seq == tp->rcv_nxt &&
2454 LIST_EMPTY(&tp->t_segq) &&
2455 TCPS_HAVEESTABLISHED(tp->t_state)) {
2456 if (DELAY_ACK(tp)) {
2457 tcp_callout_reset(tp, tp->tt_delack,
2458 tcp_delacktime, tcp_timer_delack);
2460 tp->t_flags |= TF_ACKNOW;
2462 tp->rcv_nxt += tlen;
2463 thflags = th->th_flags & TH_FIN;
2464 tcpstat.tcps_rcvpack++;
2465 tcpstat.tcps_rcvbyte += tlen;
2467 if (so->so_state & SS_CANTRCVMORE) {
2470 lwkt_gettoken(&so->so_rcv.ssb_token);
2471 ssb_appendstream(&so->so_rcv, m);
2472 lwkt_reltoken(&so->so_rcv.ssb_token);
2476 if (!(tp->t_flags & TF_DUPSEG)) {
2477 /* Initialize SACK report block. */
2478 tp->reportblk.rblk_start = th->th_seq;
2479 tp->reportblk.rblk_end = th->th_seq + tlen +
2480 ((thflags & TH_FIN) != 0);
2482 thflags = tcp_reass(tp, th, &tlen, m);
2483 tp->t_flags |= TF_ACKNOW;
2487 * Note the amount of data that peer has sent into
2488 * our window, in order to estimate the sender's
2491 len = so->so_rcv.ssb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2498 * If FIN is received ACK the FIN and let the user know
2499 * that the connection is closing.
2501 if (thflags & TH_FIN) {
2502 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
2505 * If connection is half-synchronized
2506 * (ie NEEDSYN flag on) then delay ACK,
2507 * so it may be piggybacked when SYN is sent.
2508 * Otherwise, since we received a FIN then no
2509 * more input can be expected, send ACK now.
2511 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN)) {
2512 tcp_callout_reset(tp, tp->tt_delack,
2513 tcp_delacktime, tcp_timer_delack);
2515 tp->t_flags |= TF_ACKNOW;
2520 switch (tp->t_state) {
2522 * In SYN_RECEIVED and ESTABLISHED STATES
2523 * enter the CLOSE_WAIT state.
2525 case TCPS_SYN_RECEIVED:
2526 tp->t_starttime = ticks;
2528 case TCPS_ESTABLISHED:
2529 tp->t_state = TCPS_CLOSE_WAIT;
2533 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2534 * enter the CLOSING state.
2536 case TCPS_FIN_WAIT_1:
2537 tp->t_state = TCPS_CLOSING;
2541 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2542 * starting the time-wait timer, turning off the other
2545 case TCPS_FIN_WAIT_2:
2546 tp->t_state = TCPS_TIME_WAIT;
2547 tcp_canceltimers(tp);
2548 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_msl,
2550 soisdisconnected(so);
2554 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2556 case TCPS_TIME_WAIT:
2557 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_msl,
2564 if (so->so_options & SO_DEBUG)
2565 tcp_trace(TA_INPUT, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2569 * Return any desired output.
2571 if (needoutput || (tp->t_flags & TF_ACKNOW))
2577 * Generate an ACK dropping incoming segment if it occupies
2578 * sequence space, where the ACK reflects our state.
2580 * We can now skip the test for the RST flag since all
2581 * paths to this code happen after packets containing
2582 * RST have been dropped.
2584 * In the SYN-RECEIVED state, don't send an ACK unless the
2585 * segment we received passes the SYN-RECEIVED ACK test.
2586 * If it fails send a RST. This breaks the loop in the
2587 * "LAND" DoS attack, and also prevents an ACK storm
2588 * between two listening ports that have been sent forged
2589 * SYN segments, each with the source address of the other.
2591 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2592 (SEQ_GT(tp->snd_una, th->th_ack) ||
2593 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2594 rstreason = BANDLIM_RST_OPENPORT;
2598 if (so->so_options & SO_DEBUG)
2599 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2602 tp->t_flags |= TF_ACKNOW;
2608 * Generate a RST, dropping incoming segment.
2609 * Make ACK acceptable to originator of segment.
2610 * Don't bother to respond if destination was broadcast/multicast.
2612 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
2615 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2616 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2619 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2620 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2621 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2622 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2625 /* IPv6 anycast check is done at tcp6_input() */
2628 * Perform bandwidth limiting.
2631 if (badport_bandlim(rstreason) < 0)
2636 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2637 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2639 if (thflags & TH_ACK)
2640 /* mtod() below is safe as long as hdr dropping is delayed */
2641 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2644 if (thflags & TH_SYN)
2646 /* mtod() below is safe as long as hdr dropping is delayed */
2647 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2648 (tcp_seq)0, TH_RST | TH_ACK);
2654 * Drop space held by incoming segment and return.
2657 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2658 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2665 * Parse TCP options and place in tcpopt.
2668 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn)
2673 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2675 if (opt == TCPOPT_EOL)
2677 if (opt == TCPOPT_NOP)
2683 if (optlen < 2 || optlen > cnt)
2688 if (optlen != TCPOLEN_MAXSEG)
2692 to->to_flags |= TOF_MSS;
2693 bcopy(cp + 2, &to->to_mss, sizeof to->to_mss);
2694 to->to_mss = ntohs(to->to_mss);
2697 if (optlen != TCPOLEN_WINDOW)
2701 to->to_flags |= TOF_SCALE;
2702 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2704 case TCPOPT_TIMESTAMP:
2705 if (optlen != TCPOLEN_TIMESTAMP)
2707 to->to_flags |= TOF_TS;
2708 bcopy(cp + 2, &to->to_tsval, sizeof to->to_tsval);
2709 to->to_tsval = ntohl(to->to_tsval);
2710 bcopy(cp + 6, &to->to_tsecr, sizeof to->to_tsecr);
2711 to->to_tsecr = ntohl(to->to_tsecr);
2713 * If echoed timestamp is later than the current time,
2714 * fall back to non RFC1323 RTT calculation.
2716 if (to->to_tsecr != 0 && TSTMP_GT(to->to_tsecr, ticks))
2719 case TCPOPT_SACK_PERMITTED:
2720 if (optlen != TCPOLEN_SACK_PERMITTED)
2724 to->to_flags |= TOF_SACK_PERMITTED;
2727 if ((optlen - 2) & 0x07) /* not multiple of 8 */
2729 to->to_nsackblocks = (optlen - 2) / 8;
2730 to->to_sackblocks = (struct raw_sackblock *) (cp + 2);
2731 to->to_flags |= TOF_SACK;
2732 for (i = 0; i < to->to_nsackblocks; i++) {
2733 struct raw_sackblock *r = &to->to_sackblocks[i];
2735 r->rblk_start = ntohl(r->rblk_start);
2736 r->rblk_end = ntohl(r->rblk_end);
2739 #ifdef TCP_SIGNATURE
2741 * XXX In order to reply to a host which has set the
2742 * TCP_SIGNATURE option in its initial SYN, we have to
2743 * record the fact that the option was observed here
2744 * for the syncache code to perform the correct response.
2746 case TCPOPT_SIGNATURE:
2747 if (optlen != TCPOLEN_SIGNATURE)
2749 to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2751 #endif /* TCP_SIGNATURE */
2759 * Pull out of band byte out of a segment so
2760 * it doesn't appear in the user's data queue.
2761 * It is still reflected in the segment length for
2762 * sequencing purposes.
2763 * "off" is the delayed to be dropped hdrlen.
2766 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
2768 int cnt = off + th->th_urp - 1;
2771 if (m->m_len > cnt) {
2772 char *cp = mtod(m, caddr_t) + cnt;
2773 struct tcpcb *tp = sototcpcb(so);
2776 tp->t_oobflags |= TCPOOB_HAVEDATA;
2777 bcopy(cp + 1, cp, m->m_len - cnt - 1);
2779 if (m->m_flags & M_PKTHDR)
2788 panic("tcp_pulloutofband");
2792 * Collect new round-trip time estimate
2793 * and update averages and current timeout.
2796 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2800 tcpstat.tcps_rttupdated++;
2802 if (tp->t_srtt != 0) {
2804 * srtt is stored as fixed point with 5 bits after the
2805 * binary point (i.e., scaled by 8). The following magic
2806 * is equivalent to the smoothing algorithm in rfc793 with
2807 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2808 * point). Adjust rtt to origin 0.
2810 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2811 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2813 if ((tp->t_srtt += delta) <= 0)
2817 * We accumulate a smoothed rtt variance (actually, a
2818 * smoothed mean difference), then set the retransmit
2819 * timer to smoothed rtt + 4 times the smoothed variance.
2820 * rttvar is stored as fixed point with 4 bits after the
2821 * binary point (scaled by 16). The following is
2822 * equivalent to rfc793 smoothing with an alpha of .75
2823 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2824 * rfc793's wired-in beta.
2828 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2829 if ((tp->t_rttvar += delta) <= 0)
2831 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2832 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2835 * No rtt measurement yet - use the unsmoothed rtt.
2836 * Set the variance to half the rtt (so our first
2837 * retransmit happens at 3*rtt).
2839 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2840 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2841 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2847 * the retransmit should happen at rtt + 4 * rttvar.
2848 * Because of the way we do the smoothing, srtt and rttvar
2849 * will each average +1/2 tick of bias. When we compute
2850 * the retransmit timer, we want 1/2 tick of rounding and
2851 * 1 extra tick because of +-1/2 tick uncertainty in the
2852 * firing of the timer. The bias will give us exactly the
2853 * 1.5 tick we need. But, because the bias is
2854 * statistical, we have to test that we don't drop below
2855 * the minimum feasible timer (which is 2 ticks).
2857 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2858 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2861 * We received an ack for a packet that wasn't retransmitted;
2862 * it is probably safe to discard any error indications we've
2863 * received recently. This isn't quite right, but close enough
2864 * for now (a route might have failed after we sent a segment,
2865 * and the return path might not be symmetrical).
2867 tp->t_softerror = 0;
2871 * Determine a reasonable value for maxseg size.
2872 * If the route is known, check route for mtu.
2873 * If none, use an mss that can be handled on the outgoing
2874 * interface without forcing IP to fragment; if bigger than
2875 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2876 * to utilize large mbufs. If no route is found, route has no mtu,
2877 * or the destination isn't local, use a default, hopefully conservative
2878 * size (usually 512 or the default IP max size, but no more than the mtu
2879 * of the interface), as we can't discover anything about intervening
2880 * gateways or networks. We also initialize the congestion/slow start
2881 * window to be a single segment if the destination isn't local.
2882 * While looking at the routing entry, we also initialize other path-dependent
2883 * parameters from pre-set or cached values in the routing entry.
2885 * Also take into account the space needed for options that we
2886 * send regularly. Make maxseg shorter by that amount to assure
2887 * that we can send maxseg amount of data even when the options
2888 * are present. Store the upper limit of the length of options plus
2891 * NOTE that this routine is only called when we process an incoming
2892 * segment, for outgoing segments only tcp_mssopt is called.
2895 tcp_mss(struct tcpcb *tp, int offer)
2901 struct inpcb *inp = tp->t_inpcb;
2904 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2905 size_t min_protoh = isipv6 ?
2906 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2907 sizeof(struct tcpiphdr);
2909 const boolean_t isipv6 = FALSE;
2910 const size_t min_protoh = sizeof(struct tcpiphdr);
2914 rt = tcp_rtlookup6(&inp->inp_inc);
2916 rt = tcp_rtlookup(&inp->inp_inc);
2918 tp->t_maxopd = tp->t_maxseg =
2919 (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2923 so = inp->inp_socket;
2926 * Offer == 0 means that there was no MSS on the SYN segment,
2927 * in this case we use either the interface mtu or tcp_mssdflt.
2929 * An offer which is too large will be cut down later.
2933 if (in6_localaddr(&inp->in6p_faddr)) {
2934 offer = ND_IFINFO(rt->rt_ifp)->linkmtu -
2937 offer = tcp_v6mssdflt;
2940 if (in_localaddr(inp->inp_faddr))
2941 offer = ifp->if_mtu - min_protoh;
2943 offer = tcp_mssdflt;
2948 * Prevent DoS attack with too small MSS. Round up
2949 * to at least minmss.
2951 * Sanity check: make sure that maxopd will be large
2952 * enough to allow some data on segments even is the
2953 * all the option space is used (40bytes). Otherwise
2954 * funny things may happen in tcp_output.
2956 offer = max(offer, tcp_minmss);
2957 offer = max(offer, 64);
2959 rt->rt_rmx.rmx_mssopt = offer;
2962 * While we're here, check if there's an initial rtt
2963 * or rttvar. Convert from the route-table units
2964 * to scaled multiples of the slow timeout timer.
2966 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2968 * XXX the lock bit for RTT indicates that the value
2969 * is also a minimum value; this is subject to time.
2971 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2972 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2973 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2974 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2975 tcpstat.tcps_usedrtt++;
2976 if (rt->rt_rmx.rmx_rttvar) {
2977 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2978 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2979 tcpstat.tcps_usedrttvar++;
2981 /* default variation is +- 1 rtt */
2983 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2985 TCPT_RANGESET(tp->t_rxtcur,
2986 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2987 tp->t_rttmin, TCPTV_REXMTMAX);
2991 * if there's an mtu associated with the route, use it
2992 * else, use the link mtu. Take the smaller of mss or offer
2995 if (rt->rt_rmx.rmx_mtu) {
2996 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2999 mss = ND_IFINFO(rt->rt_ifp)->linkmtu - min_protoh;
3001 mss = ifp->if_mtu - min_protoh;
3003 mss = min(mss, offer);
3006 * maxopd stores the maximum length of data AND options
3007 * in a segment; maxseg is the amount of data in a normal
3008 * segment. We need to store this value (maxopd) apart
3009 * from maxseg, because now every segment carries options
3010 * and thus we normally have somewhat less data in segments.
3014 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
3015 ((tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3016 mss -= TCPOLEN_TSTAMP_APPA;
3018 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3020 mss &= ~(MCLBYTES-1);
3023 mss = mss / MCLBYTES * MCLBYTES;
3026 * If there's a pipesize, change the socket buffer
3027 * to that size. Make the socket buffers an integral
3028 * number of mss units; if the mss is larger than
3029 * the socket buffer, decrease the mss.
3032 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
3034 bufsize = so->so_snd.ssb_hiwat;
3038 bufsize = roundup(bufsize, mss);
3039 if (bufsize > sb_max)
3041 if (bufsize > so->so_snd.ssb_hiwat)
3042 ssb_reserve(&so->so_snd, bufsize, so, NULL);
3047 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
3049 bufsize = so->so_rcv.ssb_hiwat;
3050 if (bufsize > mss) {
3051 bufsize = roundup(bufsize, mss);
3052 if (bufsize > sb_max)
3054 if (bufsize > so->so_rcv.ssb_hiwat) {
3055 lwkt_gettoken(&so->so_rcv.ssb_token);
3056 ssb_reserve(&so->so_rcv, bufsize, so, NULL);
3057 lwkt_reltoken(&so->so_rcv.ssb_token);
3062 * Set the slow-start flight size depending on whether this
3063 * is a local network or not.
3066 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3070 if (rt->rt_rmx.rmx_ssthresh) {
3072 * There's some sort of gateway or interface
3073 * buffer limit on the path. Use this to set
3074 * the slow start threshhold, but set the
3075 * threshold to no less than 2*mss.
3077 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3078 tcpstat.tcps_usedssthresh++;
3083 * Determine the MSS option to send on an outgoing SYN.
3086 tcp_mssopt(struct tcpcb *tp)
3091 ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3092 int min_protoh = isipv6 ?
3093 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
3094 sizeof(struct tcpiphdr);
3096 const boolean_t isipv6 = FALSE;
3097 const size_t min_protoh = sizeof(struct tcpiphdr);
3101 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
3103 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
3105 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3107 return (rt->rt_ifp->if_mtu - min_protoh);
3111 * When a partial ack arrives, force the retransmission of the
3112 * next unacknowledged segment. Do not exit Fast Recovery.
3114 * Implement the Slow-but-Steady variant of NewReno by restarting the
3115 * the retransmission timer. Turn it off here so it can be restarted
3116 * later in tcp_output().
3119 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th, int acked)
3121 tcp_seq old_snd_nxt = tp->snd_nxt;
3122 u_long ocwnd = tp->snd_cwnd;
3124 tcp_callout_stop(tp, tp->tt_rexmt);
3126 tp->snd_nxt = th->th_ack;
3127 /* Set snd_cwnd to one segment beyond acknowledged offset. */
3128 tp->snd_cwnd = tp->t_maxseg;
3129 tp->t_flags |= TF_ACKNOW;
3131 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3132 tp->snd_nxt = old_snd_nxt;
3133 /* partial window deflation */
3135 tp->snd_cwnd = ocwnd - acked + tp->t_maxseg;
3137 tp->snd_cwnd = tp->t_maxseg;
3141 * In contrast to the Slow-but-Steady NewReno variant,
3142 * we do not reset the retransmission timer for SACK retransmissions,
3143 * except when retransmitting snd_una.
3146 tcp_sack_rexmt(struct tcpcb *tp, struct tcphdr *th)
3148 uint32_t pipe, seglen;
3151 tcp_seq old_snd_nxt = tp->snd_nxt;
3152 u_long ocwnd = tp->snd_cwnd;
3153 int nseg = 0; /* consecutive new segments */
3154 #define MAXBURST 4 /* limit burst of new packets on partial ack */
3157 pipe = tcp_sack_compute_pipe(tp);
3158 while ((tcp_seq_diff_t)(ocwnd - pipe) >= (tcp_seq_diff_t)tp->t_maxseg &&
3159 (!tcp_do_smartsack || nseg < MAXBURST) &&
3160 tcp_sack_nextseg(tp, &nextrexmt, &seglen, &lostdup)) {
3162 tcp_seq old_snd_max;
3165 if (nextrexmt == tp->snd_max)
3167 tp->snd_nxt = nextrexmt;
3168 tp->snd_cwnd = nextrexmt - tp->snd_una + seglen;
3169 old_snd_max = tp->snd_max;
3170 if (nextrexmt == tp->snd_una)
3171 tcp_callout_stop(tp, tp->tt_rexmt);
3172 error = tcp_output(tp);
3175 sent = tp->snd_nxt - nextrexmt;
3180 tcpstat.tcps_sndsackpack++;
3181 tcpstat.tcps_sndsackbyte += sent;
3182 if (SEQ_LT(nextrexmt, old_snd_max) &&
3183 SEQ_LT(tp->rexmt_high, tp->snd_nxt))
3184 tp->rexmt_high = seq_min(tp->snd_nxt, old_snd_max);
3186 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3187 tp->snd_nxt = old_snd_nxt;
3188 tp->snd_cwnd = ocwnd;