2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
33 #include "opt_ipfw.h" /* for ipfw_fwd */
35 #include "opt_inet6.h"
36 #include "opt_ipsec.h"
38 #include "opt_tcpdebug.h"
39 #include "opt_tcp_input.h"
40 #include "opt_tcp_sack.h"
42 #include <sys/param.h>
43 #include <sys/kernel.h>
44 #include <sys/malloc.h>
46 #include <sys/proc.h> /* for proc0 declaration */
47 #include <sys/protosw.h>
48 #include <sys/signalvar.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/syslog.h>
53 #include <sys/systm.h>
55 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
60 #include <net/route.h>
62 #include <netinet/in.h>
63 #include <netinet/in_pcb.h>
64 #include <netinet/in_systm.h>
65 #include <netinet/in_var.h>
66 #include <netinet/ip.h>
67 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
68 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
69 #include <netinet/ip_var.h>
70 #include <netinet/ip_options.h>
71 #include <netinet/ip6.h>
72 #include <netinet/icmp6.h>
73 #include <netinet6/in6_pcb.h>
74 #include <netinet6/ip6_var.h>
75 #include <netinet6/nd6.h>
76 #include <netinet/tcp.h>
77 #include <netinet/tcp_fsm.h>
78 #include <netinet/tcp_seq.h>
79 #include <netinet/tcp_timer.h>
80 #include <netinet/tcp_var.h>
81 #include <netinet6/tcp6_var.h>
82 #include <netinet/tcpip.h>
84 #include <netinet/tcp_debug.h>
88 #include <netipsec/ipsec.h>
89 #include <netipsec/ipsec6.h>
93 #include <netinet6/ipsec.h>
94 #include <netinet6/ipsec6.h>
95 #include <netkey/key.h>
98 #include <machine/in_cksum.h>
100 #include <security/mac/mac_framework.h>
102 static const int tcprexmtthresh = 3;
104 struct tcpstat tcpstat;
105 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
106 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
108 static int tcp_log_in_vain = 0;
109 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
110 &tcp_log_in_vain, 0, "Log all incoming TCP connections");
112 static int blackhole = 0;
113 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
114 &blackhole, 0, "Do not send RST when dropping refused connections");
116 int tcp_delack_enabled = 1;
117 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
118 &tcp_delack_enabled, 0,
119 "Delay ACK to try and piggyback it onto a data packet");
121 #ifdef TCP_DROP_SYNFIN
122 static int drop_synfin = 0;
123 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
124 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
127 static int tcp_do_rfc3042 = 1;
128 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
129 &tcp_do_rfc3042, 0, "Enable RFC 3042 (Limited Transmit)");
131 static int tcp_do_rfc3390 = 1;
132 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
134 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
136 static int tcp_insecure_rst = 0;
137 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
138 &tcp_insecure_rst, 0,
139 "Follow the old (insecure) criteria for accepting RST packets");
141 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
142 "TCP Segment Reassembly Queue");
144 static int tcp_reass_maxseg = 0;
145 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RDTUN,
146 &tcp_reass_maxseg, 0,
147 "Global maximum number of TCP Segments in Reassembly Queue");
149 int tcp_reass_qsize = 0;
150 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
152 "Global number of TCP Segments currently in Reassembly Queue");
154 static int tcp_reass_maxqlen = 48;
155 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxqlen, CTLFLAG_RW,
156 &tcp_reass_maxqlen, 0,
157 "Maximum number of TCP Segments per individual Reassembly Queue");
159 static int tcp_reass_overflows = 0;
160 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
161 &tcp_reass_overflows, 0,
162 "Global number of TCP Segment Reassembly Queue Overflows");
164 int tcp_do_autorcvbuf = 1;
165 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
166 &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
168 int tcp_autorcvbuf_inc = 16*1024;
169 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
170 &tcp_autorcvbuf_inc, 0,
171 "Incrementor step size of automatic receive buffer");
173 int tcp_autorcvbuf_max = 256*1024;
174 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
175 &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
177 struct inpcbhead tcb;
178 #define tcb6 tcb /* for KAME src sync over BSD*'s */
179 struct inpcbinfo tcbinfo;
180 struct mtx *tcbinfo_mtx;
182 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
184 static void tcp_pulloutofband(struct socket *,
185 struct tcphdr *, struct mbuf *, int);
186 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
188 static void tcp_xmit_timer(struct tcpcb *, int);
189 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
190 static int tcp_timewait(struct inpcb *, struct tcpopt *,
191 struct tcphdr *, struct mbuf *, int);
193 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
195 #define ND6_HINT(tp) \
197 if ((tp) && (tp)->t_inpcb && \
198 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
199 nd6_nud_hint(NULL, NULL, 0); \
206 * Indicate whether this ack should be delayed. We can delay the ack if
207 * - there is no delayed ack timer in progress and
208 * - our last ack wasn't a 0-sized window. We never want to delay
209 * the ack that opens up a 0-sized window and
210 * - delayed acks are enabled or
211 * - this is a half-synchronized T/TCP connection.
213 #define DELAY_ACK(tp) \
214 ((!callout_active(tp->tt_delack) && \
215 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
216 (tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
218 /* Initialize TCP reassembly queue */
220 tcp_reass_zone_change(void *tag)
223 tcp_reass_maxseg = nmbclusters / 16;
224 uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
227 uma_zone_t tcp_reass_zone;
231 tcp_reass_maxseg = nmbclusters / 16;
232 TUNABLE_INT_FETCH("net.inet.tcp.reass.maxsegments",
234 tcp_reass_zone = uma_zcreate("tcpreass", sizeof (struct tseg_qent),
235 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
236 uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
237 EVENTHANDLER_REGISTER(nmbclusters_change,
238 tcp_reass_zone_change, NULL, EVENTHANDLER_PRI_ANY);
242 tcp_reass(tp, th, tlenp, m)
243 register struct tcpcb *tp;
244 register struct tcphdr *th;
249 struct tseg_qent *p = NULL;
250 struct tseg_qent *nq;
251 struct tseg_qent *te = NULL;
252 struct socket *so = tp->t_inpcb->inp_socket;
255 INP_LOCK_ASSERT(tp->t_inpcb);
258 * XXX: tcp_reass() is rather inefficient with its data structures
259 * and should be rewritten (see NetBSD for optimizations). While
260 * doing that it should move to its own file tcp_reass.c.
264 * Call with th==NULL after become established to
265 * force pre-ESTABLISHED data up to user socket.
271 * Limit the number of segments in the reassembly queue to prevent
272 * holding on to too many segments (and thus running out of mbufs).
273 * Make sure to let the missing segment through which caused this
274 * queue. Always keep one global queue entry spare to be able to
275 * process the missing segment.
277 if (th->th_seq != tp->rcv_nxt &&
278 (tcp_reass_qsize + 1 >= tcp_reass_maxseg ||
279 tp->t_segqlen >= tcp_reass_maxqlen)) {
280 tcp_reass_overflows++;
281 tcpstat.tcps_rcvmemdrop++;
288 * Allocate a new queue entry. If we can't, or hit the zone limit
291 te = uma_zalloc(tcp_reass_zone, M_NOWAIT);
293 tcpstat.tcps_rcvmemdrop++;
302 * Find a segment which begins after this one does.
304 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
305 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
311 * If there is a preceding segment, it may provide some of
312 * our data already. If so, drop the data from the incoming
313 * 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;
321 tcpstat.tcps_rcvduppack++;
322 tcpstat.tcps_rcvdupbyte += *tlenp;
324 uma_zfree(tcp_reass_zone, te);
328 * Try to present any queued data
329 * at the left window edge to the user.
330 * This is needed after the 3-WHS
333 goto present; /* ??? */
340 tcpstat.tcps_rcvoopack++;
341 tcpstat.tcps_rcvoobyte += *tlenp;
344 * While we overlap succeeding segments trim them or,
345 * if they are completely covered, dequeue them.
348 register int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
351 if (i < q->tqe_len) {
352 q->tqe_th->th_seq += i;
358 nq = LIST_NEXT(q, tqe_q);
359 LIST_REMOVE(q, tqe_q);
361 uma_zfree(tcp_reass_zone, q);
367 /* Insert the new segment queue entry into place. */
370 te->tqe_len = *tlenp;
373 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
375 LIST_INSERT_AFTER(p, te, tqe_q);
380 * Present data to user, advancing rcv_nxt through
381 * completed sequence space.
383 if (!TCPS_HAVEESTABLISHED(tp->t_state))
385 q = LIST_FIRST(&tp->t_segq);
386 if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
388 SOCKBUF_LOCK(&so->so_rcv);
390 tp->rcv_nxt += q->tqe_len;
391 flags = q->tqe_th->th_flags & TH_FIN;
392 nq = LIST_NEXT(q, tqe_q);
393 LIST_REMOVE(q, tqe_q);
394 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
397 sbappendstream_locked(&so->so_rcv, q->tqe_m);
398 uma_zfree(tcp_reass_zone, q);
402 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
404 sorwakeup_locked(so);
409 * TCP input routine, follows pages 65-76 of the
410 * protocol specification dated September, 1981 very closely.
414 tcp6_input(mp, offp, proto)
418 register struct mbuf *m = *mp;
419 struct in6_ifaddr *ia6;
421 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
424 * draft-itojun-ipv6-tcp-to-anycast
425 * better place to put this in?
427 ia6 = ip6_getdstifaddr(m);
428 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
431 ip6 = mtod(m, struct ip6_hdr *);
432 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
433 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
444 register struct mbuf *m;
447 register struct tcphdr *th;
448 register struct ip *ip = NULL;
449 register struct ipovly *ipov;
450 register struct inpcb *inp = NULL;
455 register struct tcpcb *tp = 0;
456 register int thflags;
457 struct socket *so = 0;
458 int todrop, acked, ourfinisacked, needoutput = 0;
460 struct tcpopt to; /* options in this segment */
462 #ifdef IPFIREWALL_FORWARD
463 struct m_tag *fwd_tag;
465 int rstreason; /* For badport_bandlim accounting purposes */
467 struct ip6_hdr *ip6 = NULL;
470 char ip6buf[INET6_ADDRSTRLEN];
472 const int isipv6 = 0;
477 * The size of tcp_saveipgen must be the size of the max ip header,
480 u_char tcp_saveipgen[40];
481 struct tcphdr tcp_savetcp;
486 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
488 bzero((char *)&to, sizeof(to));
490 tcpstat.tcps_rcvtotal++;
494 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
495 ip6 = mtod(m, struct ip6_hdr *);
496 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
497 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
498 tcpstat.tcps_rcvbadsum++;
501 th = (struct tcphdr *)((caddr_t)ip6 + off0);
504 * Be proactive about unspecified IPv6 address in source.
505 * As we use all-zero to indicate unbounded/unconnected pcb,
506 * unspecified IPv6 address can be used to confuse us.
508 * Note that packets with unspecified IPv6 destination is
509 * already dropped in ip6_input.
511 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
516 th = NULL; /* XXX: avoid compiler warning */
520 * Get IP and TCP header together in first mbuf.
521 * Note: IP leaves IP header in first mbuf.
523 if (off0 > sizeof (struct ip)) {
524 ip_stripoptions(m, (struct mbuf *)0);
525 off0 = sizeof(struct ip);
527 if (m->m_len < sizeof (struct tcpiphdr)) {
528 if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
529 tcpstat.tcps_rcvshort++;
533 ip = mtod(m, struct ip *);
534 ipov = (struct ipovly *)ip;
535 th = (struct tcphdr *)((caddr_t)ip + off0);
538 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
539 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
540 th->th_sum = m->m_pkthdr.csum_data;
542 th->th_sum = in_pseudo(ip->ip_src.s_addr,
544 htonl(m->m_pkthdr.csum_data +
547 th->th_sum ^= 0xffff;
549 ipov->ih_len = (u_short)tlen;
550 ipov->ih_len = htons(ipov->ih_len);
554 * Checksum extended TCP header and data.
556 len = sizeof (struct ip) + tlen;
557 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
558 ipov->ih_len = (u_short)tlen;
559 ipov->ih_len = htons(ipov->ih_len);
560 th->th_sum = in_cksum(m, len);
563 tcpstat.tcps_rcvbadsum++;
566 /* Re-initialization for later version check */
567 ip->ip_v = IPVERSION;
571 * Check that TCP offset makes sense,
572 * pull out TCP options and adjust length. XXX
574 off = th->th_off << 2;
575 if (off < sizeof (struct tcphdr) || off > tlen) {
576 tcpstat.tcps_rcvbadoff++;
579 tlen -= off; /* tlen is used instead of ti->ti_len */
580 if (off > sizeof (struct tcphdr)) {
583 IP6_EXTHDR_CHECK(m, off0, off, );
584 ip6 = mtod(m, struct ip6_hdr *);
585 th = (struct tcphdr *)((caddr_t)ip6 + off0);
588 if (m->m_len < sizeof(struct ip) + off) {
589 if ((m = m_pullup(m, sizeof (struct ip) + off))
591 tcpstat.tcps_rcvshort++;
594 ip = mtod(m, struct ip *);
595 ipov = (struct ipovly *)ip;
596 th = (struct tcphdr *)((caddr_t)ip + off0);
599 optlen = off - sizeof (struct tcphdr);
600 optp = (u_char *)(th + 1);
602 thflags = th->th_flags;
604 #ifdef TCP_DROP_SYNFIN
606 * If the drop_synfin option is enabled, drop all packets with
607 * both the SYN and FIN bits set. This prevents e.g. nmap from
608 * identifying the TCP/IP stack.
610 * This is a violation of the TCP specification.
612 if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
617 * Convert TCP protocol specific fields to host format.
619 th->th_seq = ntohl(th->th_seq);
620 th->th_ack = ntohl(th->th_ack);
621 th->th_win = ntohs(th->th_win);
622 th->th_urp = ntohs(th->th_urp);
625 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
626 * until after ip6_savecontrol() is called and before other functions
627 * which don't want those proto headers.
628 * Because ip6_savecontrol() is going to parse the mbuf to
629 * search for data to be passed up to user-land, it wants mbuf
630 * parameters to be unchanged.
631 * XXX: the call of ip6_savecontrol() has been obsoleted based on
632 * latest version of the advanced API (20020110).
634 drop_hdrlen = off0 + off;
637 * Locate pcb for segment.
639 INP_INFO_WLOCK(&tcbinfo);
642 KASSERT(headlocked, ("tcp_input: findpcb: head not locked"));
643 #ifdef IPFIREWALL_FORWARD
644 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
645 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
647 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
648 struct sockaddr_in *next_hop;
650 next_hop = (struct sockaddr_in *)(fwd_tag+1);
652 * Transparently forwarded. Pretend to be the destination.
653 * already got one like this?
655 inp = in_pcblookup_hash(&tcbinfo,
656 ip->ip_src, th->th_sport,
657 ip->ip_dst, th->th_dport,
658 0, m->m_pkthdr.rcvif);
660 /* It's new. Try to find the ambushing socket. */
661 inp = in_pcblookup_hash(&tcbinfo,
662 ip->ip_src, th->th_sport,
665 ntohs(next_hop->sin_port) :
670 /* Remove the tag from the packet. We don't need it anymore. */
671 m_tag_delete(m, fwd_tag);
673 #endif /* IPFIREWALL_FORWARD */
676 inp = in6_pcblookup_hash(&tcbinfo,
677 &ip6->ip6_src, th->th_sport,
678 &ip6->ip6_dst, th->th_dport,
683 inp = in_pcblookup_hash(&tcbinfo,
684 ip->ip_src, th->th_sport,
685 ip->ip_dst, th->th_dport,
688 #ifdef IPFIREWALL_FORWARD
690 #endif /* IPFIREWALL_FORWARD */
692 #if defined(IPSEC) || defined(FAST_IPSEC)
695 if (inp != NULL && ipsec6_in_reject(m, inp)) {
697 ipsec6stat.in_polvio++;
703 if (inp != NULL && ipsec4_in_reject(m, inp)) {
705 ipsecstat.in_polvio++;
709 #endif /*IPSEC || FAST_IPSEC*/
712 * If the state is CLOSED (i.e., TCB does not exist) then
713 * all data in the incoming segment is discarded.
714 * If the TCB exists but is in CLOSED state, it is embryonic,
715 * but should either do a listen or a connect soon.
718 if (tcp_log_in_vain) {
720 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
722 char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
730 ip6_sprintf(ip6buf, &ip6->ip6_dst));
732 ip6_sprintf(ip6buf, &ip6->ip6_src));
737 strcpy(dbuf, inet_ntoa(ip->ip_dst));
738 strcpy(sbuf, inet_ntoa(ip->ip_src));
740 switch (tcp_log_in_vain) {
742 if ((thflags & TH_SYN) == 0)
747 "Connection attempt to TCP %s:%d "
748 "from %s:%d flags:0x%02x\n",
749 dbuf, ntohs(th->th_dport), sbuf,
750 ntohs(th->th_sport), thflags);
759 if (thflags & TH_SYN)
768 rstreason = BANDLIM_RST_CLOSEDPORT;
773 /* Check the minimum TTL for socket. */
774 if (inp->inp_ip_minttl != 0) {
776 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
780 if (inp->inp_ip_minttl > ip->ip_ttl)
784 if (inp->inp_vflag & INP_TIMEWAIT) {
786 * The only option of relevance is TOF_CC, and only if
787 * present in a SYN segment. See tcp_timewait().
789 if (thflags & TH_SYN)
790 tcp_dooptions(&to, optp, optlen, TO_SYN);
791 if (tcp_timewait(inp, &to, th, m, tlen))
794 * tcp_timewait unlocks inp.
796 INP_INFO_WUNLOCK(&tcbinfo);
802 rstreason = BANDLIM_RST_CLOSEDPORT;
805 if (tp->t_state == TCPS_CLOSED)
809 INP_LOCK_ASSERT(inp);
810 if (mac_check_inpcb_deliver(inp, m))
813 so = inp->inp_socket;
814 KASSERT(so != NULL, ("tcp_input: so == NULL"));
816 if (so->so_options & SO_DEBUG) {
817 ostate = tp->t_state;
819 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
821 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
825 if (so->so_options & SO_ACCEPTCONN) {
826 struct in_conninfo inc;
828 bzero(&inc, sizeof(inc));
830 inc.inc_isipv6 = isipv6;
833 inc.inc6_faddr = ip6->ip6_src;
834 inc.inc6_laddr = ip6->ip6_dst;
836 inc.inc_faddr = ip->ip_src;
837 inc.inc_laddr = ip->ip_dst;
839 inc.inc_fport = th->th_sport;
840 inc.inc_lport = th->th_dport;
843 * If the state is LISTEN then ignore segment if it contains
844 * a RST. If the segment contains an ACK then it is bad and
845 * send a RST. If it does not contain a SYN then it is not
846 * interesting; drop it.
848 * If the state is SYN_RECEIVED (syncache) and seg contains
849 * an ACK, but not for our SYN/ACK, send a RST. If the seg
850 * contains a RST, check the sequence number to see if it
851 * is a valid reset segment.
853 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
854 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
856 * Parse the TCP options here because
857 * syncookies need access to the reflected
860 tcp_dooptions(&to, optp, optlen, 0);
861 if (!syncache_expand(&inc, &to, th, &so, m)) {
863 * No syncache entry, or ACK was not
864 * for our SYN/ACK. Send a RST.
866 tcpstat.tcps_badsyn++;
867 rstreason = BANDLIM_RST_OPENPORT;
872 * Could not complete 3-way handshake,
873 * connection is being closed down, and
874 * syncache has free'd mbuf.
877 INP_INFO_WUNLOCK(&tcbinfo);
881 * Socket is created in state SYN_RECEIVED.
882 * Continue processing segment.
889 * This is what would have happened in
890 * tcp_output() when the SYN,ACK was sent.
892 tp->snd_up = tp->snd_una;
893 tp->snd_max = tp->snd_nxt = tp->iss + 1;
894 tp->last_ack_sent = tp->rcv_nxt;
897 if (thflags & TH_RST) {
898 syncache_chkrst(&inc, th);
901 if (thflags & TH_ACK) {
902 syncache_badack(&inc);
903 tcpstat.tcps_badsyn++;
904 rstreason = BANDLIM_RST_OPENPORT;
911 * Segment's flags are (SYN) or (SYN|FIN).
915 * If deprecated address is forbidden,
916 * we do not accept SYN to deprecated interface
917 * address to prevent any new inbound connection from
918 * getting established.
919 * When we do not accept SYN, we send a TCP RST,
920 * with deprecated source address (instead of dropping
921 * it). We compromise it as it is much better for peer
922 * to send a RST, and RST will be the final packet
925 * If we do not forbid deprecated addresses, we accept
926 * the SYN packet. RFC2462 does not suggest dropping
928 * If we decipher RFC2462 5.5.4, it says like this:
929 * 1. use of deprecated addr with existing
930 * communication is okay - "SHOULD continue to be
932 * 2. use of it with new communication:
933 * (2a) "SHOULD NOT be used if alternate address
934 * with sufficient scope is available"
935 * (2b) nothing mentioned otherwise.
936 * Here we fall into (2b) case as we have no choice in
937 * our source address selection - we must obey the peer.
939 * The wording in RFC2462 is confusing, and there are
940 * multiple description text for deprecated address
941 * handling - worse, they are not exactly the same.
942 * I believe 5.5.4 is the best one, so we follow 5.5.4.
944 if (isipv6 && !ip6_use_deprecated) {
945 struct in6_ifaddr *ia6;
947 if ((ia6 = ip6_getdstifaddr(m)) &&
948 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
951 rstreason = BANDLIM_RST_OPENPORT;
957 * If it is from this socket, drop it, it must be forged.
958 * Don't bother responding if the destination was a broadcast.
960 if (th->th_dport == th->th_sport) {
962 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
966 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
971 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
973 * Note that it is quite possible to receive unicast
974 * link-layer packets with a broadcast IP address. Use
975 * in_broadcast() to find them.
977 if (m->m_flags & (M_BCAST|M_MCAST))
980 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
981 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
984 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
985 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
986 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
987 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
991 * SYN appears to be valid; create compressed TCP state
992 * for syncache, or perform t/tcp connection.
994 if (so->so_qlen <= so->so_qlimit) {
996 if (so->so_options & SO_DEBUG)
997 tcp_trace(TA_INPUT, ostate, tp,
998 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1000 tcp_dooptions(&to, optp, optlen, TO_SYN);
1001 if (!syncache_add(&inc, &to, th, inp, &so, m))
1002 goto drop; /* XXX: does not happen */
1005 * Entry added to syncache, mbuf used to
1006 * send SYN,ACK packet. Everything unlocked
1011 panic("T/TCP not supported at the moment");
1014 * Segment passed TAO tests.
1015 * XXX: Can't happen at the moment.
1018 inp = sotoinpcb(so);
1020 tp = intotcpcb(inp);
1021 tp->t_starttime = ticks;
1022 tp->t_state = TCPS_ESTABLISHED;
1026 * If there is a FIN or if there is data, then
1027 * delay SYN,ACK(SYN) in the hope of piggy-backing
1028 * it on a response segment. Otherwise must send
1029 * ACK now in case the other side is slow starting.
1031 if (thflags & TH_FIN || tlen != 0)
1032 tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
1034 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1035 tiwin = th->th_win << tp->snd_scale;
1036 tcpstat.tcps_connects++;
1044 KASSERT(headlocked, ("tcp_input: after_listen: head not locked"));
1045 INP_LOCK_ASSERT(inp);
1047 /* Syncache takes care of sockets in the listen state. */
1048 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN"));
1051 * This is the second part of the MSS DoS prevention code (after
1052 * minmss on the sending side) and it deals with too many too small
1053 * tcp packets in a too short timeframe (1 second).
1055 * For every full second we count the number of received packets
1056 * and bytes. If we get a lot of packets per second for this connection
1057 * (tcp_minmssoverload) we take a closer look at it and compute the
1058 * average packet size for the past second. If that is less than
1059 * tcp_minmss we get too many packets with very small payload which
1060 * is not good and burdens our system (and every packet generates
1061 * a wakeup to the process connected to our socket). We can reasonable
1062 * expect this to be small packet DoS attack to exhaust our CPU
1065 * Care has to be taken for the minimum packet overload value. This
1066 * value defines the minimum number of packets per second before we
1067 * start to worry. This must not be too low to avoid killing for
1068 * example interactive connections with many small packets like
1071 * Setting either tcp_minmssoverload or tcp_minmss to "0" disables
1074 * Account for packet if payload packet, skip over ACK, etc.
1076 if (tcp_minmss && tcp_minmssoverload &&
1077 tp->t_state == TCPS_ESTABLISHED && tlen > 0) {
1078 if ((unsigned int)(tp->rcv_second - ticks) < hz) {
1080 tp->rcv_byps += tlen + off;
1081 if (tp->rcv_pps > tcp_minmssoverload) {
1082 if ((tp->rcv_byps / tp->rcv_pps) < tcp_minmss) {
1083 printf("too many small tcp packets from "
1084 "%s:%u, av. %lubyte/packet, "
1085 "dropping connection\n",
1089 &inp->inp_inc.inc6_faddr) :
1091 inet_ntoa(inp->inp_inc.inc_faddr),
1092 inp->inp_inc.inc_fport,
1093 tp->rcv_byps / tp->rcv_pps);
1094 KASSERT(headlocked, ("tcp_input: "
1095 "after_listen: tcp_drop: head "
1097 tp = tcp_drop(tp, ECONNRESET);
1098 tcpstat.tcps_minmssdrops++;
1103 tp->rcv_second = ticks + hz;
1105 tp->rcv_byps = tlen + off;
1110 * Segment received on connection.
1111 * Reset idle time and keep-alive timer.
1113 tp->t_rcvtime = ticks;
1114 if (TCPS_HAVEESTABLISHED(tp->t_state))
1115 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
1118 * Unscale the window into a 32-bit value.
1119 * This value is bogus for the TCPS_SYN_SENT state
1120 * and is overwritten later.
1122 tiwin = th->th_win << tp->snd_scale;
1125 * Parse options on any incoming segment.
1127 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) ? TO_SYN : 0);
1130 * If echoed timestamp is later than the current time,
1131 * fall back to non RFC1323 RTT calculation. Normalize
1132 * timestamp if syncookies were used when this connection
1135 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1136 to.to_tsecr -= tp->ts_offset;
1137 if (TSTMP_GT(to.to_tsecr, ticks))
1142 * Process options only when we get SYN/ACK back. The SYN case
1143 * for incoming connections is handled in tcp_syncache.
1144 * XXX this is traditional behavior, may need to be cleaned up.
1146 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1147 if ((to.to_flags & TOF_SCALE) &&
1148 (tp->t_flags & TF_REQ_SCALE)) {
1149 tp->t_flags |= TF_RCVD_SCALE;
1150 tp->snd_scale = to.to_wscale;
1151 tp->snd_wnd = th->th_win << tp->snd_scale;
1152 tiwin = tp->snd_wnd;
1154 if (to.to_flags & TOF_TS) {
1155 tp->t_flags |= TF_RCVD_TSTMP;
1156 tp->ts_recent = to.to_tsval;
1157 tp->ts_recent_age = ticks;
1159 /* Initial send window, already scaled. */
1160 tp->snd_wnd = th->th_win;
1161 if (to.to_flags & TOF_MSS)
1162 tcp_mss(tp, to.to_mss);
1163 if (tp->sack_enable) {
1164 if (!(to.to_flags & TOF_SACK))
1165 tp->sack_enable = 0;
1167 tp->t_flags |= TF_SACK_PERMIT;
1173 * Header prediction: check for the two common cases
1174 * of a uni-directional data xfer. If the packet has
1175 * no control flags, is in-sequence, the window didn't
1176 * change and we're not retransmitting, it's a
1177 * candidate. If the length is zero and the ack moved
1178 * forward, we're the sender side of the xfer. Just
1179 * free the data acked & wake any higher level process
1180 * that was blocked waiting for space. If the length
1181 * is non-zero and the ack didn't move, we're the
1182 * receiver side. If we're getting packets in-order
1183 * (the reassembly queue is empty), add the data to
1184 * the socket buffer and note that we need a delayed ack.
1185 * Make sure that the hidden state-flags are also off.
1186 * Since we check for TCPS_ESTABLISHED above, it can only
1189 if (tp->t_state == TCPS_ESTABLISHED &&
1190 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1191 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1192 ((to.to_flags & TOF_TS) == 0 ||
1193 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1194 th->th_seq == tp->rcv_nxt && tiwin && tiwin == tp->snd_wnd &&
1195 tp->snd_nxt == tp->snd_max) {
1198 * If last ACK falls within this segment's sequence numbers,
1199 * record the timestamp.
1200 * NOTE that the test is modified according to the latest
1201 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1203 if ((to.to_flags & TOF_TS) != 0 &&
1204 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1205 tp->ts_recent_age = ticks;
1206 tp->ts_recent = to.to_tsval;
1210 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1211 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1212 tp->snd_cwnd >= tp->snd_wnd &&
1213 ((!tcp_do_newreno && !tp->sack_enable &&
1214 tp->t_dupacks < tcprexmtthresh) ||
1215 ((tcp_do_newreno || tp->sack_enable) &&
1216 !IN_FASTRECOVERY(tp) && to.to_nsacks == 0 &&
1217 TAILQ_EMPTY(&tp->snd_holes)))) {
1218 KASSERT(headlocked, ("headlocked"));
1219 INP_INFO_WUNLOCK(&tcbinfo);
1222 * this is a pure ack for outstanding data.
1224 ++tcpstat.tcps_predack;
1226 * "bad retransmit" recovery
1228 if (tp->t_rxtshift == 1 &&
1229 ticks < tp->t_badrxtwin) {
1230 ++tcpstat.tcps_sndrexmitbad;
1231 tp->snd_cwnd = tp->snd_cwnd_prev;
1233 tp->snd_ssthresh_prev;
1234 tp->snd_recover = tp->snd_recover_prev;
1235 if (tp->t_flags & TF_WASFRECOVERY)
1236 ENTER_FASTRECOVERY(tp);
1237 tp->snd_nxt = tp->snd_max;
1238 tp->t_badrxtwin = 0;
1242 * Recalculate the transmit timer / rtt.
1244 * Some boxes send broken timestamp replies
1245 * during the SYN+ACK phase, ignore
1246 * timestamps of 0 or we could calculate a
1247 * huge RTT and blow up the retransmit timer.
1249 if ((to.to_flags & TOF_TS) != 0 &&
1251 if (!tp->t_rttlow ||
1252 tp->t_rttlow > ticks - to.to_tsecr)
1253 tp->t_rttlow = ticks - to.to_tsecr;
1255 ticks - to.to_tsecr + 1);
1256 } else if (tp->t_rtttime &&
1257 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1258 if (!tp->t_rttlow ||
1259 tp->t_rttlow > ticks - tp->t_rtttime)
1260 tp->t_rttlow = ticks - tp->t_rtttime;
1262 ticks - tp->t_rtttime);
1264 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1265 acked = th->th_ack - tp->snd_una;
1266 tcpstat.tcps_rcvackpack++;
1267 tcpstat.tcps_rcvackbyte += acked;
1268 sbdrop(&so->so_snd, acked);
1269 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1270 SEQ_LEQ(th->th_ack, tp->snd_recover))
1271 tp->snd_recover = th->th_ack - 1;
1272 tp->snd_una = th->th_ack;
1274 * pull snd_wl2 up to prevent seq wrap relative
1277 tp->snd_wl2 = th->th_ack;
1280 ND6_HINT(tp); /* some progress has been done */
1283 * If all outstanding data are acked, stop
1284 * retransmit timer, otherwise restart timer
1285 * using current (possibly backed-off) value.
1286 * If process is waiting for space,
1287 * wakeup/selwakeup/signal. If data
1288 * are ready to send, let tcp_output
1289 * decide between more output or persist.
1292 if (so->so_options & SO_DEBUG)
1293 tcp_trace(TA_INPUT, ostate, tp,
1294 (void *)tcp_saveipgen,
1298 if (tp->snd_una == tp->snd_max)
1299 callout_stop(tp->tt_rexmt);
1300 else if (!callout_active(tp->tt_persist))
1301 callout_reset(tp->tt_rexmt,
1303 tcp_timer_rexmt, tp);
1306 if (so->so_snd.sb_cc)
1307 (void) tcp_output(tp);
1310 } else if (th->th_ack == tp->snd_una &&
1311 LIST_EMPTY(&tp->t_segq) &&
1312 tlen <= sbspace(&so->so_rcv)) {
1313 int newsize = 0; /* automatic sockbuf scaling */
1315 KASSERT(headlocked, ("headlocked"));
1316 INP_INFO_WUNLOCK(&tcbinfo);
1319 * this is a pure, in-sequence data packet
1320 * with nothing on the reassembly queue and
1321 * we have enough buffer space to take it.
1323 /* Clean receiver SACK report if present */
1324 if (tp->sack_enable && tp->rcv_numsacks)
1325 tcp_clean_sackreport(tp);
1326 ++tcpstat.tcps_preddat;
1327 tp->rcv_nxt += tlen;
1329 * Pull snd_wl1 up to prevent seq wrap relative to
1332 tp->snd_wl1 = th->th_seq;
1334 * Pull rcv_up up to prevent seq wrap relative to
1337 tp->rcv_up = tp->rcv_nxt;
1338 tcpstat.tcps_rcvpack++;
1339 tcpstat.tcps_rcvbyte += tlen;
1340 ND6_HINT(tp); /* some progress has been done */
1342 if (so->so_options & SO_DEBUG)
1343 tcp_trace(TA_INPUT, ostate, tp,
1344 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1347 * Automatic sizing of receive socket buffer. Often the send
1348 * buffer size is not optimally adjusted to the actual network
1349 * conditions at hand (delay bandwidth product). Setting the
1350 * buffer size too small limits throughput on links with high
1351 * bandwidth and high delay (eg. trans-continental/oceanic links).
1353 * On the receive side the socket buffer memory is only rarely
1354 * used to any significant extent. This allows us to be much
1355 * more aggressive in scaling the receive socket buffer. For
1356 * the case that the buffer space is actually used to a large
1357 * extent and we run out of kernel memory we can simply drop
1358 * the new segments; TCP on the sender will just retransmit it
1359 * later. Setting the buffer size too big may only consume too
1360 * much kernel memory if the application doesn't read() from
1361 * the socket or packet loss or reordering makes use of the
1364 * The criteria to step up the receive buffer one notch are:
1365 * 1. the number of bytes received during the time it takes
1366 * one timestamp to be reflected back to us (the RTT);
1367 * 2. received bytes per RTT is within seven eighth of the
1368 * current socket buffer size;
1369 * 3. receive buffer size has not hit maximal automatic size;
1371 * This algorithm does one step per RTT at most and only if
1372 * we receive a bulk stream w/o packet losses or reorderings.
1373 * Shrinking the buffer during idle times is not necessary as
1374 * it doesn't consume any memory when idle.
1376 * TODO: Only step up if the application is actually serving
1377 * the buffer to better manage the socket buffer resources.
1379 if (tcp_do_autorcvbuf &&
1381 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1382 if (to.to_tsecr > tp->rfbuf_ts &&
1383 to.to_tsecr - tp->rfbuf_ts < hz) {
1385 (so->so_rcv.sb_hiwat / 8 * 7) &&
1386 so->so_rcv.sb_hiwat <
1387 tcp_autorcvbuf_max) {
1389 min(so->so_rcv.sb_hiwat +
1391 tcp_autorcvbuf_max);
1393 /* Start over with next RTT. */
1397 tp->rfbuf_cnt += tlen; /* add up */
1400 /* Add data to socket buffer. */
1401 SOCKBUF_LOCK(&so->so_rcv);
1402 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1406 * Set new socket buffer size.
1407 * Give up when limit is reached.
1410 if (!sbreserve_locked(&so->so_rcv,
1411 newsize, so, curthread))
1412 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1413 m_adj(m, drop_hdrlen); /* delayed header drop */
1414 sbappendstream_locked(&so->so_rcv, m);
1416 sorwakeup_locked(so);
1417 if (DELAY_ACK(tp)) {
1418 tp->t_flags |= TF_DELACK;
1420 tp->t_flags |= TF_ACKNOW;
1428 * Calculate amount of space in receive window,
1429 * and then do TCP input processing.
1430 * Receive window is amount of space in rcv queue,
1431 * but not less than advertised window.
1435 win = sbspace(&so->so_rcv);
1438 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1441 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1445 switch (tp->t_state) {
1448 * If the state is SYN_RECEIVED:
1449 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1451 case TCPS_SYN_RECEIVED:
1452 if ((thflags & TH_ACK) &&
1453 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1454 SEQ_GT(th->th_ack, tp->snd_max))) {
1455 rstreason = BANDLIM_RST_OPENPORT;
1461 * If the state is SYN_SENT:
1462 * if seg contains an ACK, but not for our SYN, drop the input.
1463 * if seg contains a RST, then drop the connection.
1464 * if seg does not contain SYN, then drop it.
1465 * Otherwise this is an acceptable SYN segment
1466 * initialize tp->rcv_nxt and tp->irs
1467 * if seg contains ack then advance tp->snd_una
1468 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1469 * arrange for segment to be acked (eventually)
1470 * continue processing rest of data/controls, beginning with URG
1473 if ((thflags & TH_ACK) &&
1474 (SEQ_LEQ(th->th_ack, tp->iss) ||
1475 SEQ_GT(th->th_ack, tp->snd_max))) {
1476 rstreason = BANDLIM_UNLIMITED;
1479 if (thflags & TH_RST) {
1480 if (thflags & TH_ACK) {
1481 KASSERT(headlocked, ("tcp_input: after_listen"
1482 ": tcp_drop.2: head not locked"));
1483 tp = tcp_drop(tp, ECONNREFUSED);
1487 if ((thflags & TH_SYN) == 0)
1490 tp->irs = th->th_seq;
1492 if (thflags & TH_ACK) {
1493 tcpstat.tcps_connects++;
1497 mac_set_socket_peer_from_mbuf(m, so);
1500 /* Do window scaling on this connection? */
1501 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1502 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1503 tp->rcv_scale = tp->request_r_scale;
1505 tp->rcv_adv += tp->rcv_wnd;
1506 tp->snd_una++; /* SYN is acked */
1508 * If there's data, delay ACK; if there's also a FIN
1509 * ACKNOW will be turned on later.
1511 if (DELAY_ACK(tp) && tlen != 0)
1512 callout_reset(tp->tt_delack, tcp_delacktime,
1513 tcp_timer_delack, tp);
1515 tp->t_flags |= TF_ACKNOW;
1517 * Received <SYN,ACK> in SYN_SENT[*] state.
1519 * SYN_SENT --> ESTABLISHED
1520 * SYN_SENT* --> FIN_WAIT_1
1522 tp->t_starttime = ticks;
1523 if (tp->t_flags & TF_NEEDFIN) {
1524 tp->t_state = TCPS_FIN_WAIT_1;
1525 tp->t_flags &= ~TF_NEEDFIN;
1528 tp->t_state = TCPS_ESTABLISHED;
1529 callout_reset(tp->tt_keep, tcp_keepidle,
1530 tcp_timer_keep, tp);
1534 * Received initial SYN in SYN-SENT[*] state =>
1535 * simultaneous open. If segment contains CC option
1536 * and there is a cached CC, apply TAO test.
1537 * If it succeeds, connection is * half-synchronized.
1538 * Otherwise, do 3-way handshake:
1539 * SYN-SENT -> SYN-RECEIVED
1540 * SYN-SENT* -> SYN-RECEIVED*
1541 * If there was no CC option, clear cached CC value.
1543 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1544 callout_stop(tp->tt_rexmt);
1545 tp->t_state = TCPS_SYN_RECEIVED;
1551 KASSERT(headlocked, ("tcp_input: trimthenstep6: head not "
1553 INP_LOCK_ASSERT(inp);
1556 * Advance th->th_seq to correspond to first data byte.
1557 * If data, trim to stay within window,
1558 * dropping FIN if necessary.
1561 if (tlen > tp->rcv_wnd) {
1562 todrop = tlen - tp->rcv_wnd;
1566 tcpstat.tcps_rcvpackafterwin++;
1567 tcpstat.tcps_rcvbyteafterwin += todrop;
1569 tp->snd_wl1 = th->th_seq - 1;
1570 tp->rcv_up = th->th_seq;
1572 * Client side of transaction: already sent SYN and data.
1573 * If the remote host used T/TCP to validate the SYN,
1574 * our data will be ACK'd; if so, enter normal data segment
1575 * processing in the middle of step 5, ack processing.
1576 * Otherwise, goto step 6.
1578 if (thflags & TH_ACK)
1584 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1585 * do normal processing.
1587 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1591 case TCPS_TIME_WAIT:
1592 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1593 break; /* continue normal processing */
1597 * States other than LISTEN or SYN_SENT.
1598 * First check the RST flag and sequence number since reset segments
1599 * are exempt from the timestamp and connection count tests. This
1600 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1601 * below which allowed reset segments in half the sequence space
1602 * to fall though and be processed (which gives forged reset
1603 * segments with a random sequence number a 50 percent chance of
1604 * killing a connection).
1605 * Then check timestamp, if present.
1606 * Then check the connection count, if present.
1607 * Then check that at least some bytes of segment are within
1608 * receive window. If segment begins before rcv_nxt,
1609 * drop leading data (and SYN); if nothing left, just ack.
1612 * If the RST bit is set, check the sequence number to see
1613 * if this is a valid reset segment.
1615 * In all states except SYN-SENT, all reset (RST) segments
1616 * are validated by checking their SEQ-fields. A reset is
1617 * valid if its sequence number is in the window.
1618 * Note: this does not take into account delayed ACKs, so
1619 * we should test against last_ack_sent instead of rcv_nxt.
1620 * The sequence number in the reset segment is normally an
1621 * echo of our outgoing acknowlegement numbers, but some hosts
1622 * send a reset with the sequence number at the rightmost edge
1623 * of our receive window, and we have to handle this case.
1624 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1625 * that brute force RST attacks are possible. To combat this,
1626 * we use a much stricter check while in the ESTABLISHED state,
1627 * only accepting RSTs where the sequence number is equal to
1628 * last_ack_sent. In all other states (the states in which a
1629 * RST is more likely), the more permissive check is used.
1630 * If we have multiple segments in flight, the intial reset
1631 * segment sequence numbers will be to the left of last_ack_sent,
1632 * but they will eventually catch up.
1633 * In any case, it never made sense to trim reset segments to
1634 * fit the receive window since RFC 1122 says:
1635 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1637 * A TCP SHOULD allow a received RST segment to include data.
1640 * It has been suggested that a RST segment could contain
1641 * ASCII text that encoded and explained the cause of the
1642 * RST. No standard has yet been established for such
1645 * If the reset segment passes the sequence number test examine
1647 * SYN_RECEIVED STATE:
1648 * If passive open, return to LISTEN state.
1649 * If active open, inform user that connection was refused.
1650 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1651 * Inform user that connection was reset, and close tcb.
1652 * CLOSING, LAST_ACK STATES:
1655 * Drop the segment - see Stevens, vol. 2, p. 964 and
1658 if (thflags & TH_RST) {
1659 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1660 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1661 switch (tp->t_state) {
1663 case TCPS_SYN_RECEIVED:
1664 so->so_error = ECONNREFUSED;
1667 case TCPS_ESTABLISHED:
1668 if (tcp_insecure_rst == 0 &&
1669 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1670 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1671 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1672 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1673 tcpstat.tcps_badrst++;
1676 case TCPS_FIN_WAIT_1:
1677 case TCPS_FIN_WAIT_2:
1678 case TCPS_CLOSE_WAIT:
1679 so->so_error = ECONNRESET;
1681 tp->t_state = TCPS_CLOSED;
1682 tcpstat.tcps_drops++;
1683 KASSERT(headlocked, ("tcp_input: "
1684 "trimthenstep6: tcp_close: head not "
1691 KASSERT(headlocked, ("trimthenstep6: "
1692 "tcp_close.2: head not locked"));
1696 case TCPS_TIME_WAIT:
1697 KASSERT(tp->t_state != TCPS_TIME_WAIT,
1706 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1707 * and it's less than ts_recent, drop it.
1709 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1710 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1712 /* Check to see if ts_recent is over 24 days old. */
1713 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1715 * Invalidate ts_recent. If this segment updates
1716 * ts_recent, the age will be reset later and ts_recent
1717 * will get a valid value. If it does not, setting
1718 * ts_recent to zero will at least satisfy the
1719 * requirement that zero be placed in the timestamp
1720 * echo reply when ts_recent isn't valid. The
1721 * age isn't reset until we get a valid ts_recent
1722 * because we don't want out-of-order segments to be
1723 * dropped when ts_recent is old.
1727 tcpstat.tcps_rcvduppack++;
1728 tcpstat.tcps_rcvdupbyte += tlen;
1729 tcpstat.tcps_pawsdrop++;
1737 * In the SYN-RECEIVED state, validate that the packet belongs to
1738 * this connection before trimming the data to fit the receive
1739 * window. Check the sequence number versus IRS since we know
1740 * the sequence numbers haven't wrapped. This is a partial fix
1741 * for the "LAND" DoS attack.
1743 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1744 rstreason = BANDLIM_RST_OPENPORT;
1748 todrop = tp->rcv_nxt - th->th_seq;
1750 if (thflags & TH_SYN) {
1760 * Following if statement from Stevens, vol. 2, p. 960.
1763 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1765 * Any valid FIN must be to the left of the window.
1766 * At this point the FIN must be a duplicate or out
1767 * of sequence; drop it.
1772 * Send an ACK to resynchronize and drop any data.
1773 * But keep on processing for RST or ACK.
1775 tp->t_flags |= TF_ACKNOW;
1777 tcpstat.tcps_rcvduppack++;
1778 tcpstat.tcps_rcvdupbyte += todrop;
1780 tcpstat.tcps_rcvpartduppack++;
1781 tcpstat.tcps_rcvpartdupbyte += todrop;
1783 drop_hdrlen += todrop; /* drop from the top afterwards */
1784 th->th_seq += todrop;
1786 if (th->th_urp > todrop)
1787 th->th_urp -= todrop;
1795 * If new data are received on a connection after the
1796 * user processes are gone, then RST the other end.
1798 if ((so->so_state & SS_NOFDREF) &&
1799 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1800 KASSERT(headlocked, ("trimthenstep6: tcp_close.3: head not "
1803 tcpstat.tcps_rcvafterclose++;
1804 rstreason = BANDLIM_UNLIMITED;
1809 * If segment ends after window, drop trailing data
1810 * (and PUSH and FIN); if nothing left, just ACK.
1812 todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1814 tcpstat.tcps_rcvpackafterwin++;
1815 if (todrop >= tlen) {
1816 tcpstat.tcps_rcvbyteafterwin += tlen;
1818 * If a new connection request is received
1819 * while in TIME_WAIT, drop the old connection
1820 * and start over if the sequence numbers
1821 * are above the previous ones.
1823 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1824 if (thflags & TH_SYN &&
1825 tp->t_state == TCPS_TIME_WAIT &&
1826 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1827 KASSERT(headlocked, ("trimthenstep6: "
1828 "tcp_close.4: head not locked"));
1833 * If window is closed can only take segments at
1834 * window edge, and have to drop data and PUSH from
1835 * incoming segments. Continue processing, but
1836 * remember to ack. Otherwise, drop segment
1839 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1840 tp->t_flags |= TF_ACKNOW;
1841 tcpstat.tcps_rcvwinprobe++;
1845 tcpstat.tcps_rcvbyteafterwin += todrop;
1848 thflags &= ~(TH_PUSH|TH_FIN);
1852 * If last ACK falls within this segment's sequence numbers,
1853 * record its timestamp.
1855 * 1) That the test incorporates suggestions from the latest
1856 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1857 * 2) That updating only on newer timestamps interferes with
1858 * our earlier PAWS tests, so this check should be solely
1859 * predicated on the sequence space of this segment.
1860 * 3) That we modify the segment boundary check to be
1861 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1862 * instead of RFC1323's
1863 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1864 * This modified check allows us to overcome RFC1323's
1865 * limitations as described in Stevens TCP/IP Illustrated
1866 * Vol. 2 p.869. In such cases, we can still calculate the
1867 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1869 if ((to.to_flags & TOF_TS) != 0 &&
1870 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1871 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1872 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
1873 tp->ts_recent_age = ticks;
1874 tp->ts_recent = to.to_tsval;
1878 * If a SYN is in the window, then this is an
1879 * error and we send an RST and drop the connection.
1881 if (thflags & TH_SYN) {
1882 KASSERT(headlocked, ("tcp_input: tcp_drop: trimthenstep6: "
1883 "head not locked"));
1884 tp = tcp_drop(tp, ECONNRESET);
1885 rstreason = BANDLIM_UNLIMITED;
1890 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1891 * flag is on (half-synchronized state), then queue data for
1892 * later processing; else drop segment and return.
1894 if ((thflags & TH_ACK) == 0) {
1895 if (tp->t_state == TCPS_SYN_RECEIVED ||
1896 (tp->t_flags & TF_NEEDSYN))
1898 else if (tp->t_flags & TF_ACKNOW)
1907 switch (tp->t_state) {
1910 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1911 * ESTABLISHED state and continue processing.
1912 * The ACK was checked above.
1914 case TCPS_SYN_RECEIVED:
1916 tcpstat.tcps_connects++;
1918 /* Do window scaling? */
1919 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1920 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1921 tp->rcv_scale = tp->request_r_scale;
1922 tp->snd_wnd = tiwin;
1926 * SYN-RECEIVED -> ESTABLISHED
1927 * SYN-RECEIVED* -> FIN-WAIT-1
1929 tp->t_starttime = ticks;
1930 if (tp->t_flags & TF_NEEDFIN) {
1931 tp->t_state = TCPS_FIN_WAIT_1;
1932 tp->t_flags &= ~TF_NEEDFIN;
1934 tp->t_state = TCPS_ESTABLISHED;
1935 callout_reset(tp->tt_keep, tcp_keepidle,
1936 tcp_timer_keep, tp);
1939 * If segment contains data or ACK, will call tcp_reass()
1940 * later; if not, do so now to pass queued data to user.
1942 if (tlen == 0 && (thflags & TH_FIN) == 0)
1943 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1945 tp->snd_wl1 = th->th_seq - 1;
1949 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1950 * ACKs. If the ack is in the range
1951 * tp->snd_una < th->th_ack <= tp->snd_max
1952 * then advance tp->snd_una to th->th_ack and drop
1953 * data from the retransmission queue. If this ACK reflects
1954 * more up to date window information we update our window information.
1956 case TCPS_ESTABLISHED:
1957 case TCPS_FIN_WAIT_1:
1958 case TCPS_FIN_WAIT_2:
1959 case TCPS_CLOSE_WAIT:
1962 case TCPS_TIME_WAIT:
1963 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1964 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1965 tcpstat.tcps_rcvacktoomuch++;
1968 if (tp->sack_enable &&
1969 (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes)))
1970 tcp_sack_doack(tp, &to, th->th_ack);
1971 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1972 if (tlen == 0 && tiwin == tp->snd_wnd) {
1973 tcpstat.tcps_rcvdupack++;
1975 * If we have outstanding data (other than
1976 * a window probe), this is a completely
1977 * duplicate ack (ie, window info didn't
1978 * change), the ack is the biggest we've
1979 * seen and we've seen exactly our rexmt
1980 * threshhold of them, assume a packet
1981 * has been dropped and retransmit it.
1982 * Kludge snd_nxt & the congestion
1983 * window so we send only this one
1986 * We know we're losing at the current
1987 * window size so do congestion avoidance
1988 * (set ssthresh to half the current window
1989 * and pull our congestion window back to
1990 * the new ssthresh).
1992 * Dup acks mean that packets have left the
1993 * network (they're now cached at the receiver)
1994 * so bump cwnd by the amount in the receiver
1995 * to keep a constant cwnd packets in the
1998 if (!callout_active(tp->tt_rexmt) ||
1999 th->th_ack != tp->snd_una)
2001 else if (++tp->t_dupacks > tcprexmtthresh ||
2002 ((tcp_do_newreno || tp->sack_enable) &&
2003 IN_FASTRECOVERY(tp))) {
2004 if (tp->sack_enable && IN_FASTRECOVERY(tp)) {
2008 * Compute the amount of data in flight first.
2009 * We can inject new data into the pipe iff
2010 * we have less than 1/2 the original window's
2011 * worth of data in flight.
2013 awnd = (tp->snd_nxt - tp->snd_fack) +
2014 tp->sackhint.sack_bytes_rexmit;
2015 if (awnd < tp->snd_ssthresh) {
2016 tp->snd_cwnd += tp->t_maxseg;
2017 if (tp->snd_cwnd > tp->snd_ssthresh)
2018 tp->snd_cwnd = tp->snd_ssthresh;
2021 tp->snd_cwnd += tp->t_maxseg;
2022 (void) tcp_output(tp);
2024 } else if (tp->t_dupacks == tcprexmtthresh) {
2025 tcp_seq onxt = tp->snd_nxt;
2029 * If we're doing sack, check to
2030 * see if we're already in sack
2031 * recovery. If we're not doing sack,
2032 * check to see if we're in newreno
2035 if (tp->sack_enable) {
2036 if (IN_FASTRECOVERY(tp)) {
2040 } else if (tcp_do_newreno) {
2041 if (SEQ_LEQ(th->th_ack,
2047 win = min(tp->snd_wnd, tp->snd_cwnd) /
2051 tp->snd_ssthresh = win * tp->t_maxseg;
2052 ENTER_FASTRECOVERY(tp);
2053 tp->snd_recover = tp->snd_max;
2054 callout_stop(tp->tt_rexmt);
2056 if (tp->sack_enable) {
2057 tcpstat.tcps_sack_recovery_episode++;
2058 tp->sack_newdata = tp->snd_nxt;
2059 tp->snd_cwnd = tp->t_maxseg;
2060 (void) tcp_output(tp);
2063 tp->snd_nxt = th->th_ack;
2064 tp->snd_cwnd = tp->t_maxseg;
2065 (void) tcp_output(tp);
2066 KASSERT(tp->snd_limited <= 2,
2067 ("tp->snd_limited too big"));
2068 tp->snd_cwnd = tp->snd_ssthresh +
2070 (tp->t_dupacks - tp->snd_limited);
2071 if (SEQ_GT(onxt, tp->snd_nxt))
2074 } else if (tcp_do_rfc3042) {
2075 u_long oldcwnd = tp->snd_cwnd;
2076 tcp_seq oldsndmax = tp->snd_max;
2079 KASSERT(tp->t_dupacks == 1 ||
2081 ("dupacks not 1 or 2"));
2082 if (tp->t_dupacks == 1)
2083 tp->snd_limited = 0;
2085 (tp->snd_nxt - tp->snd_una) +
2086 (tp->t_dupacks - tp->snd_limited) *
2088 (void) tcp_output(tp);
2089 sent = tp->snd_max - oldsndmax;
2090 if (sent > tp->t_maxseg) {
2091 KASSERT((tp->t_dupacks == 2 &&
2092 tp->snd_limited == 0) ||
2093 (sent == tp->t_maxseg + 1 &&
2094 tp->t_flags & TF_SENTFIN),
2096 tp->snd_limited = 2;
2097 } else if (sent > 0)
2099 tp->snd_cwnd = oldcwnd;
2107 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
2110 * If the congestion window was inflated to account
2111 * for the other side's cached packets, retract it.
2113 if (tcp_do_newreno || tp->sack_enable) {
2114 if (IN_FASTRECOVERY(tp)) {
2115 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2116 if (tp->sack_enable)
2117 tcp_sack_partialack(tp, th);
2119 tcp_newreno_partial_ack(tp, th);
2122 * Out of fast recovery.
2123 * Window inflation should have left us
2124 * with approximately snd_ssthresh
2126 * But in case we would be inclined to
2127 * send a burst, better to do it via
2128 * the slow start mechanism.
2130 if (SEQ_GT(th->th_ack +
2133 tp->snd_cwnd = tp->snd_max -
2137 tp->snd_cwnd = tp->snd_ssthresh;
2141 if (tp->t_dupacks >= tcprexmtthresh &&
2142 tp->snd_cwnd > tp->snd_ssthresh)
2143 tp->snd_cwnd = tp->snd_ssthresh;
2147 * If we reach this point, ACK is not a duplicate,
2148 * i.e., it ACKs something we sent.
2150 if (tp->t_flags & TF_NEEDSYN) {
2152 * T/TCP: Connection was half-synchronized, and our
2153 * SYN has been ACK'd (so connection is now fully
2154 * synchronized). Go to non-starred state,
2155 * increment snd_una for ACK of SYN, and check if
2156 * we can do window scaling.
2158 tp->t_flags &= ~TF_NEEDSYN;
2160 /* Do window scaling? */
2161 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2162 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2163 tp->rcv_scale = tp->request_r_scale;
2164 /* Send window already scaled. */
2169 KASSERT(headlocked, ("tcp_input: process_ACK: head not "
2171 INP_LOCK_ASSERT(inp);
2173 acked = th->th_ack - tp->snd_una;
2174 tcpstat.tcps_rcvackpack++;
2175 tcpstat.tcps_rcvackbyte += acked;
2178 * If we just performed our first retransmit, and the ACK
2179 * arrives within our recovery window, then it was a mistake
2180 * to do the retransmit in the first place. Recover our
2181 * original cwnd and ssthresh, and proceed to transmit where
2184 if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2185 ++tcpstat.tcps_sndrexmitbad;
2186 tp->snd_cwnd = tp->snd_cwnd_prev;
2187 tp->snd_ssthresh = tp->snd_ssthresh_prev;
2188 tp->snd_recover = tp->snd_recover_prev;
2189 if (tp->t_flags & TF_WASFRECOVERY)
2190 ENTER_FASTRECOVERY(tp);
2191 tp->snd_nxt = tp->snd_max;
2192 tp->t_badrxtwin = 0; /* XXX probably not required */
2196 * If we have a timestamp reply, update smoothed
2197 * round trip time. If no timestamp is present but
2198 * transmit timer is running and timed sequence
2199 * number was acked, update smoothed round trip time.
2200 * Since we now have an rtt measurement, cancel the
2201 * timer backoff (cf., Phil Karn's retransmit alg.).
2202 * Recompute the initial retransmit timer.
2204 * Some boxes send broken timestamp replies
2205 * during the SYN+ACK phase, ignore
2206 * timestamps of 0 or we could calculate a
2207 * huge RTT and blow up the retransmit timer.
2209 if ((to.to_flags & TOF_TS) != 0 &&
2211 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2212 tp->t_rttlow = ticks - to.to_tsecr;
2213 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2214 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2215 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2216 tp->t_rttlow = ticks - tp->t_rtttime;
2217 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2219 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2222 * If all outstanding data is acked, stop retransmit
2223 * timer and remember to restart (more output or persist).
2224 * If there is more data to be acked, restart retransmit
2225 * timer, using current (possibly backed-off) value.
2227 if (th->th_ack == tp->snd_max) {
2228 callout_stop(tp->tt_rexmt);
2230 } else if (!callout_active(tp->tt_persist))
2231 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
2232 tcp_timer_rexmt, tp);
2235 * If no data (only SYN) was ACK'd,
2236 * skip rest of ACK processing.
2242 * When new data is acked, open the congestion window.
2243 * If the window gives us less than ssthresh packets
2244 * in flight, open exponentially (maxseg per packet).
2245 * Otherwise open linearly: maxseg per window
2246 * (maxseg^2 / cwnd per packet).
2248 if ((!tcp_do_newreno && !tp->sack_enable) ||
2249 !IN_FASTRECOVERY(tp)) {
2250 register u_int cw = tp->snd_cwnd;
2251 register u_int incr = tp->t_maxseg;
2252 if (cw > tp->snd_ssthresh)
2253 incr = incr * incr / cw;
2254 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2256 SOCKBUF_LOCK(&so->so_snd);
2257 if (acked > so->so_snd.sb_cc) {
2258 tp->snd_wnd -= so->so_snd.sb_cc;
2259 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2262 sbdrop_locked(&so->so_snd, acked);
2263 tp->snd_wnd -= acked;
2266 sowwakeup_locked(so);
2267 /* detect una wraparound */
2268 if ((tcp_do_newreno || tp->sack_enable) &&
2269 !IN_FASTRECOVERY(tp) &&
2270 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2271 SEQ_LEQ(th->th_ack, tp->snd_recover))
2272 tp->snd_recover = th->th_ack - 1;
2273 if ((tcp_do_newreno || tp->sack_enable) &&
2274 IN_FASTRECOVERY(tp) &&
2275 SEQ_GEQ(th->th_ack, tp->snd_recover))
2276 EXIT_FASTRECOVERY(tp);
2277 tp->snd_una = th->th_ack;
2278 if (tp->sack_enable) {
2279 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2280 tp->snd_recover = tp->snd_una;
2282 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2283 tp->snd_nxt = tp->snd_una;
2285 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.
2302 * we should release the tp also, and use a
2305 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2308 soisdisconnected(so);
2309 timeout = (tcp_fast_finwait2_recycle) ?
2310 tcp_finwait2_timeout : tcp_maxidle;
2311 callout_reset(tp->tt_2msl, timeout,
2312 tcp_timer_2msl, tp);
2314 tp->t_state = TCPS_FIN_WAIT_2;
2319 * In CLOSING STATE in addition to the processing for
2320 * the ESTABLISHED state if the ACK acknowledges our FIN
2321 * then enter the TIME-WAIT state, otherwise ignore
2325 if (ourfinisacked) {
2326 KASSERT(headlocked, ("tcp_input: process_ACK: "
2327 "head not locked"));
2329 INP_INFO_WUNLOCK(&tcbinfo);
2336 * In LAST_ACK, we may still be waiting for data to drain
2337 * and/or to be acked, as well as for the ack of our FIN.
2338 * If our FIN is now acknowledged, delete the TCB,
2339 * enter the closed state and return.
2342 if (ourfinisacked) {
2343 KASSERT(headlocked, ("tcp_input: process_ACK:"
2344 " tcp_close: head not locked"));
2351 * In TIME_WAIT state the only thing that should arrive
2352 * is a retransmission of the remote FIN. Acknowledge
2353 * it and restart the finack timer.
2355 case TCPS_TIME_WAIT:
2356 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
2357 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2358 tcp_timer_2msl, tp);
2364 KASSERT(headlocked, ("tcp_input: step6: head not locked"));
2365 INP_LOCK_ASSERT(inp);
2368 * Update window information.
2369 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2371 if ((thflags & TH_ACK) &&
2372 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2373 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2374 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2375 /* keep track of pure window updates */
2377 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2378 tcpstat.tcps_rcvwinupd++;
2379 tp->snd_wnd = tiwin;
2380 tp->snd_wl1 = th->th_seq;
2381 tp->snd_wl2 = th->th_ack;
2382 if (tp->snd_wnd > tp->max_sndwnd)
2383 tp->max_sndwnd = tp->snd_wnd;
2388 * Process segments with URG.
2390 if ((thflags & TH_URG) && th->th_urp &&
2391 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2393 * This is a kludge, but if we receive and accept
2394 * random urgent pointers, we'll crash in
2395 * soreceive. It's hard to imagine someone
2396 * actually wanting to send this much urgent data.
2398 SOCKBUF_LOCK(&so->so_rcv);
2399 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2400 th->th_urp = 0; /* XXX */
2401 thflags &= ~TH_URG; /* XXX */
2402 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2403 goto dodata; /* XXX */
2406 * If this segment advances the known urgent pointer,
2407 * then mark the data stream. This should not happen
2408 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2409 * a FIN has been received from the remote side.
2410 * In these states we ignore the URG.
2412 * According to RFC961 (Assigned Protocols),
2413 * the urgent pointer points to the last octet
2414 * of urgent data. We continue, however,
2415 * to consider it to indicate the first octet
2416 * of data past the urgent section as the original
2417 * spec states (in one of two places).
2419 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2420 tp->rcv_up = th->th_seq + th->th_urp;
2421 so->so_oobmark = so->so_rcv.sb_cc +
2422 (tp->rcv_up - tp->rcv_nxt) - 1;
2423 if (so->so_oobmark == 0)
2424 so->so_rcv.sb_state |= SBS_RCVATMARK;
2426 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2428 SOCKBUF_UNLOCK(&so->so_rcv);
2430 * Remove out of band data so doesn't get presented to user.
2431 * This can happen independent of advancing the URG pointer,
2432 * but if two URG's are pending at once, some out-of-band
2433 * data may creep in... ick.
2435 if (th->th_urp <= (u_long)tlen &&
2436 !(so->so_options & SO_OOBINLINE)) {
2437 /* hdr drop is delayed */
2438 tcp_pulloutofband(so, th, m, drop_hdrlen);
2442 * If no out of band data is expected,
2443 * pull receive urgent pointer along
2444 * with the receive window.
2446 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2447 tp->rcv_up = tp->rcv_nxt;
2450 KASSERT(headlocked, ("tcp_input: dodata: head not locked"));
2451 INP_LOCK_ASSERT(inp);
2454 * Process the segment text, merging it into the TCP sequencing queue,
2455 * and arranging for acknowledgment of receipt if necessary.
2456 * This process logically involves adjusting tp->rcv_wnd as data
2457 * is presented to the user (this happens in tcp_usrreq.c,
2458 * case PRU_RCVD). If a FIN has already been received on this
2459 * connection then we just ignore the text.
2461 if ((tlen || (thflags & TH_FIN)) &&
2462 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2463 tcp_seq save_start = th->th_seq;
2464 tcp_seq save_end = th->th_seq + tlen;
2465 m_adj(m, drop_hdrlen); /* delayed header drop */
2467 * Insert segment which includes th into TCP reassembly queue
2468 * with control block tp. Set thflags to whether reassembly now
2469 * includes a segment with FIN. This handles the common case
2470 * inline (segment is the next to be received on an established
2471 * connection, and the queue is empty), avoiding linkage into
2472 * and removal from the queue and repetition of various
2474 * Set DELACK for segments received in order, but ack
2475 * immediately when segments are out of order (so
2476 * fast retransmit can work).
2478 if (th->th_seq == tp->rcv_nxt &&
2479 LIST_EMPTY(&tp->t_segq) &&
2480 TCPS_HAVEESTABLISHED(tp->t_state)) {
2482 tp->t_flags |= TF_DELACK;
2484 tp->t_flags |= TF_ACKNOW;
2485 tp->rcv_nxt += tlen;
2486 thflags = th->th_flags & TH_FIN;
2487 tcpstat.tcps_rcvpack++;
2488 tcpstat.tcps_rcvbyte += tlen;
2490 SOCKBUF_LOCK(&so->so_rcv);
2491 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2494 sbappendstream_locked(&so->so_rcv, m);
2495 sorwakeup_locked(so);
2497 thflags = tcp_reass(tp, th, &tlen, m);
2498 tp->t_flags |= TF_ACKNOW;
2500 if (tlen > 0 && tp->sack_enable)
2501 tcp_update_sack_list(tp, save_start, save_end);
2503 * Note the amount of data that peer has sent into
2504 * our window, in order to estimate the sender's
2507 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2514 * If FIN is received ACK the FIN and let the user know
2515 * that the connection is closing.
2517 if (thflags & TH_FIN) {
2518 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2521 * If connection is half-synchronized
2522 * (ie NEEDSYN flag on) then delay ACK,
2523 * so it may be piggybacked when SYN is sent.
2524 * Otherwise, since we received a FIN then no
2525 * more input can be expected, send ACK now.
2527 if (tp->t_flags & TF_NEEDSYN)
2528 tp->t_flags |= TF_DELACK;
2530 tp->t_flags |= TF_ACKNOW;
2533 switch (tp->t_state) {
2536 * In SYN_RECEIVED and ESTABLISHED STATES
2537 * enter the CLOSE_WAIT state.
2539 case TCPS_SYN_RECEIVED:
2540 tp->t_starttime = ticks;
2542 case TCPS_ESTABLISHED:
2543 tp->t_state = TCPS_CLOSE_WAIT;
2547 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2548 * enter the CLOSING state.
2550 case TCPS_FIN_WAIT_1:
2551 tp->t_state = TCPS_CLOSING;
2555 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2556 * starting the time-wait timer, turning off the other
2559 case TCPS_FIN_WAIT_2:
2560 KASSERT(headlocked == 1, ("tcp_input: dodata: "
2561 "TCP_FIN_WAIT_2: head not locked"));
2563 INP_INFO_WUNLOCK(&tcbinfo);
2567 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2569 case TCPS_TIME_WAIT:
2570 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
2571 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2572 tcp_timer_2msl, tp);
2576 INP_INFO_WUNLOCK(&tcbinfo);
2579 if (so->so_options & SO_DEBUG)
2580 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2585 * Return any desired output.
2587 if (needoutput || (tp->t_flags & TF_ACKNOW))
2588 (void) tcp_output(tp);
2591 KASSERT(headlocked == 0, ("tcp_input: check_delack: head locked"));
2592 INP_LOCK_ASSERT(inp);
2593 if (tp->t_flags & TF_DELACK) {
2594 tp->t_flags &= ~TF_DELACK;
2595 callout_reset(tp->tt_delack, tcp_delacktime,
2596 tcp_timer_delack, tp);
2602 KASSERT(headlocked, ("tcp_input: dropafterack: head not locked"));
2604 * Generate an ACK dropping incoming segment if it occupies
2605 * sequence space, where the ACK reflects our state.
2607 * We can now skip the test for the RST flag since all
2608 * paths to this code happen after packets containing
2609 * RST have been dropped.
2611 * In the SYN-RECEIVED state, don't send an ACK unless the
2612 * segment we received passes the SYN-RECEIVED ACK test.
2613 * If it fails send a RST. This breaks the loop in the
2614 * "LAND" DoS attack, and also prevents an ACK storm
2615 * between two listening ports that have been sent forged
2616 * SYN segments, each with the source address of the other.
2618 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2619 (SEQ_GT(tp->snd_una, th->th_ack) ||
2620 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2621 rstreason = BANDLIM_RST_OPENPORT;
2625 if (so->so_options & SO_DEBUG)
2626 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2629 KASSERT(headlocked, ("headlocked should be 1"));
2630 INP_INFO_WUNLOCK(&tcbinfo);
2631 tp->t_flags |= TF_ACKNOW;
2632 (void) tcp_output(tp);
2638 KASSERT(headlocked, ("tcp_input: dropwithreset: head not locked"));
2640 * Generate a RST, dropping incoming segment.
2641 * Make ACK acceptable to originator of segment.
2642 * Don't bother to respond if destination was broadcast/multicast.
2644 if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2647 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2648 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2651 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2652 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2653 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2654 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2657 /* IPv6 anycast check is done at tcp6_input() */
2660 * Perform bandwidth limiting.
2662 if (badport_bandlim(rstreason) < 0)
2666 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2667 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2671 if (thflags & TH_ACK)
2672 /* mtod() below is safe as long as hdr dropping is delayed */
2673 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2676 if (thflags & TH_SYN)
2678 /* mtod() below is safe as long as hdr dropping is delayed */
2679 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2680 (tcp_seq)0, TH_RST|TH_ACK);
2686 INP_INFO_WUNLOCK(&tcbinfo);
2691 * Drop space held by incoming segment and return.
2694 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2695 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2701 INP_INFO_WUNLOCK(&tcbinfo);
2707 * Parse TCP options and place in tcpopt.
2710 tcp_dooptions(to, cp, cnt, flags)
2719 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2721 if (opt == TCPOPT_EOL)
2723 if (opt == TCPOPT_NOP)
2729 if (optlen < 2 || optlen > cnt)
2734 if (optlen != TCPOLEN_MAXSEG)
2736 if (!(flags & TO_SYN))
2738 to->to_flags |= TOF_MSS;
2739 bcopy((char *)cp + 2,
2740 (char *)&to->to_mss, sizeof(to->to_mss));
2741 to->to_mss = ntohs(to->to_mss);
2744 if (optlen != TCPOLEN_WINDOW)
2746 if (!(flags & TO_SYN))
2748 to->to_flags |= TOF_SCALE;
2749 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2751 case TCPOPT_TIMESTAMP:
2752 if (optlen != TCPOLEN_TIMESTAMP)
2754 to->to_flags |= TOF_TS;
2755 bcopy((char *)cp + 2,
2756 (char *)&to->to_tsval, sizeof(to->to_tsval));
2757 to->to_tsval = ntohl(to->to_tsval);
2758 bcopy((char *)cp + 6,
2759 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2760 to->to_tsecr = ntohl(to->to_tsecr);
2762 #ifdef TCP_SIGNATURE
2764 * XXX In order to reply to a host which has set the
2765 * TCP_SIGNATURE option in its initial SYN, we have to
2766 * record the fact that the option was observed here
2767 * for the syncache code to perform the correct response.
2769 case TCPOPT_SIGNATURE:
2770 if (optlen != TCPOLEN_SIGNATURE)
2772 to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2775 case TCPOPT_SACK_PERMITTED:
2776 if (optlen != TCPOLEN_SACK_PERMITTED)
2778 if (!(flags & TO_SYN))
2782 to->to_flags |= TOF_SACK;
2785 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2787 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2788 to->to_sacks = cp + 2;
2789 tcpstat.tcps_sack_rcv_blocks++;
2798 * Pull out of band byte out of a segment so
2799 * it doesn't appear in the user's data queue.
2800 * It is still reflected in the segment length for
2801 * sequencing purposes.
2804 tcp_pulloutofband(so, th, m, off)
2807 register struct mbuf *m;
2808 int off; /* delayed to be droped hdrlen */
2810 int cnt = off + th->th_urp - 1;
2813 if (m->m_len > cnt) {
2814 char *cp = mtod(m, caddr_t) + cnt;
2815 struct tcpcb *tp = sototcpcb(so);
2818 tp->t_oobflags |= TCPOOB_HAVEDATA;
2819 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2821 if (m->m_flags & M_PKTHDR)
2830 panic("tcp_pulloutofband");
2834 * Collect new round-trip time estimate
2835 * and update averages and current timeout.
2838 tcp_xmit_timer(tp, rtt)
2839 register struct tcpcb *tp;
2844 INP_LOCK_ASSERT(tp->t_inpcb);
2846 tcpstat.tcps_rttupdated++;
2848 if (tp->t_srtt != 0) {
2850 * srtt is stored as fixed point with 5 bits after the
2851 * binary point (i.e., scaled by 8). The following magic
2852 * is equivalent to the smoothing algorithm in rfc793 with
2853 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2854 * point). Adjust rtt to origin 0.
2856 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2857 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2859 if ((tp->t_srtt += delta) <= 0)
2863 * We accumulate a smoothed rtt variance (actually, a
2864 * smoothed mean difference), then set the retransmit
2865 * timer to smoothed rtt + 4 times the smoothed variance.
2866 * rttvar is stored as fixed point with 4 bits after the
2867 * binary point (scaled by 16). The following is
2868 * equivalent to rfc793 smoothing with an alpha of .75
2869 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2870 * rfc793's wired-in beta.
2874 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2875 if ((tp->t_rttvar += delta) <= 0)
2877 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2878 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2881 * No rtt measurement yet - use the unsmoothed rtt.
2882 * Set the variance to half the rtt (so our first
2883 * retransmit happens at 3*rtt).
2885 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2886 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2887 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2893 * the retransmit should happen at rtt + 4 * rttvar.
2894 * Because of the way we do the smoothing, srtt and rttvar
2895 * will each average +1/2 tick of bias. When we compute
2896 * the retransmit timer, we want 1/2 tick of rounding and
2897 * 1 extra tick because of +-1/2 tick uncertainty in the
2898 * firing of the timer. The bias will give us exactly the
2899 * 1.5 tick we need. But, because the bias is
2900 * statistical, we have to test that we don't drop below
2901 * the minimum feasible timer (which is 2 ticks).
2903 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2904 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2907 * We received an ack for a packet that wasn't retransmitted;
2908 * it is probably safe to discard any error indications we've
2909 * received recently. This isn't quite right, but close enough
2910 * for now (a route might have failed after we sent a segment,
2911 * and the return path might not be symmetrical).
2913 tp->t_softerror = 0;
2917 * Determine a reasonable value for maxseg size.
2918 * If the route is known, check route for mtu.
2919 * If none, use an mss that can be handled on the outgoing
2920 * interface without forcing IP to fragment; if bigger than
2921 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2922 * to utilize large mbufs. If no route is found, route has no mtu,
2923 * or the destination isn't local, use a default, hopefully conservative
2924 * size (usually 512 or the default IP max size, but no more than the mtu
2925 * of the interface), as we can't discover anything about intervening
2926 * gateways or networks. We also initialize the congestion/slow start
2927 * window to be a single segment if the destination isn't local.
2928 * While looking at the routing entry, we also initialize other path-dependent
2929 * parameters from pre-set or cached values in the routing entry.
2931 * Also take into account the space needed for options that we
2932 * send regularly. Make maxseg shorter by that amount to assure
2933 * that we can send maxseg amount of data even when the options
2934 * are present. Store the upper limit of the length of options plus
2938 * In case of T/TCP, we call this routine during implicit connection
2939 * setup as well (offer = -1), to initialize maxseg from the cached
2942 * NOTE that this routine is only called when we process an incoming
2943 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
2953 struct inpcb *inp = tp->t_inpcb;
2955 struct hc_metrics_lite metrics;
2956 int origoffer = offer;
2959 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2960 size_t min_protoh = isipv6 ?
2961 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2962 sizeof (struct tcpiphdr);
2964 const size_t min_protoh = sizeof(struct tcpiphdr);
2970 maxmtu = tcp_maxmtu6(&inp->inp_inc, &mtuflags);
2971 tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
2975 maxmtu = tcp_maxmtu(&inp->inp_inc, &mtuflags);
2976 tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2978 so = inp->inp_socket;
2981 * no route to sender, stay with default mss and return
2986 /* what have we got? */
2990 * Offer == 0 means that there was no MSS on the SYN
2991 * segment, in this case we use tcp_mssdflt.
2995 isipv6 ? tcp_v6mssdflt :
3002 * Offer == -1 means that we didn't receive SYN yet.
3008 * Prevent DoS attack with too small MSS. Round up
3009 * to at least minmss.
3011 offer = max(offer, tcp_minmss);
3013 * Sanity check: make sure that maxopd will be large
3014 * enough to allow some data on segments even if the
3015 * all the option space is used (40bytes). Otherwise
3016 * funny things may happen in tcp_output.
3018 offer = max(offer, 64);
3022 * rmx information is now retrieved from tcp_hostcache
3024 tcp_hc_get(&inp->inp_inc, &metrics);
3027 * if there's a discovered mtu int tcp hostcache, use it
3028 * else, use the link mtu.
3030 if (metrics.rmx_mtu)
3031 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3035 mss = maxmtu - min_protoh;
3036 if (!path_mtu_discovery &&
3037 !in6_localaddr(&inp->in6p_faddr))
3038 mss = min(mss, tcp_v6mssdflt);
3042 mss = maxmtu - min_protoh;
3043 if (!path_mtu_discovery &&
3044 !in_localaddr(inp->inp_faddr))
3045 mss = min(mss, tcp_mssdflt);
3048 mss = min(mss, offer);
3051 * maxopd stores the maximum length of data AND options
3052 * in a segment; maxseg is the amount of data in a normal
3053 * segment. We need to store this value (maxopd) apart
3054 * from maxseg, because now every segment carries options
3055 * and thus we normally have somewhat less data in segments.
3060 * origoffer==-1 indicates, that no segments were received yet.
3061 * In this case we just guess.
3063 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3065 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3066 mss -= TCPOLEN_TSTAMP_APPA;
3069 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3071 mss &= ~(MCLBYTES-1);
3074 mss = mss / MCLBYTES * MCLBYTES;
3079 * If there's a pipesize, change the socket buffer to that size,
3080 * don't change if sb_hiwat is different than default (then it
3081 * has been changed on purpose with setsockopt).
3082 * Make the socket buffers an integral number of mss units;
3083 * if the mss is larger than the socket buffer, decrease the mss.
3085 SOCKBUF_LOCK(&so->so_snd);
3086 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
3087 bufsize = metrics.rmx_sendpipe;
3089 bufsize = so->so_snd.sb_hiwat;
3093 bufsize = roundup(bufsize, mss);
3094 if (bufsize > sb_max)
3096 if (bufsize > so->so_snd.sb_hiwat)
3097 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3099 SOCKBUF_UNLOCK(&so->so_snd);
3102 SOCKBUF_LOCK(&so->so_rcv);
3103 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
3104 bufsize = metrics.rmx_recvpipe;
3106 bufsize = so->so_rcv.sb_hiwat;
3107 if (bufsize > mss) {
3108 bufsize = roundup(bufsize, mss);
3109 if (bufsize > sb_max)
3111 if (bufsize > so->so_rcv.sb_hiwat)
3112 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3114 SOCKBUF_UNLOCK(&so->so_rcv);
3116 * While we're here, check the others too
3118 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
3120 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3121 tcpstat.tcps_usedrtt++;
3122 if (metrics.rmx_rttvar) {
3123 tp->t_rttvar = metrics.rmx_rttvar;
3124 tcpstat.tcps_usedrttvar++;
3126 /* default variation is +- 1 rtt */
3128 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3130 TCPT_RANGESET(tp->t_rxtcur,
3131 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3132 tp->t_rttmin, TCPTV_REXMTMAX);
3134 if (metrics.rmx_ssthresh) {
3136 * There's some sort of gateway or interface
3137 * buffer limit on the path. Use this to set
3138 * the slow start threshhold, but set the
3139 * threshold to no less than 2*mss.
3141 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
3142 tcpstat.tcps_usedssthresh++;
3144 if (metrics.rmx_bandwidth)
3145 tp->snd_bandwidth = metrics.rmx_bandwidth;
3148 * Set the slow-start flight size depending on whether this
3149 * is a local network or not.
3151 * Extend this so we cache the cwnd too and retrieve it here.
3152 * Make cwnd even bigger than RFC3390 suggests but only if we
3153 * have previous experience with the remote host. Be careful
3154 * not make cwnd bigger than remote receive window or our own
3155 * send socket buffer. Maybe put some additional upper bound
3156 * on the retrieved cwnd. Should do incremental updates to
3157 * hostcache when cwnd collapses so next connection doesn't
3158 * overloads the path again.
3160 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
3161 * We currently check only in syncache_socket for that.
3163 #define TCP_METRICS_CWND
3164 #ifdef TCP_METRICS_CWND
3165 if (metrics.rmx_cwnd)
3166 tp->snd_cwnd = max(mss,
3167 min(metrics.rmx_cwnd / 2,
3168 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
3172 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3174 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
3175 (!isipv6 && in_localaddr(inp->inp_faddr)))
3177 else if (in_localaddr(inp->inp_faddr))
3179 tp->snd_cwnd = mss * ss_fltsz_local;
3181 tp->snd_cwnd = mss * ss_fltsz;
3183 /* Check the interface for TSO capabilities. */
3184 if (mtuflags & CSUM_TSO)
3185 tp->t_flags |= TF_TSO;
3189 * Determine the MSS option to send on an outgoing SYN.
3193 struct in_conninfo *inc;
3200 int isipv6 = inc->inc_isipv6 ? 1 : 0;
3203 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3207 mss = tcp_v6mssdflt;
3208 maxmtu = tcp_maxmtu6(inc, NULL);
3209 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3210 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3215 maxmtu = tcp_maxmtu(inc, NULL);
3216 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3217 min_protoh = sizeof(struct tcpiphdr);
3219 if (maxmtu && thcmtu)
3220 mss = min(maxmtu, thcmtu) - min_protoh;
3221 else if (maxmtu || thcmtu)
3222 mss = max(maxmtu, thcmtu) - min_protoh;
3229 * On a partial ack arrives, force the retransmission of the
3230 * next unacknowledged segment. Do not clear tp->t_dupacks.
3231 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3235 tcp_newreno_partial_ack(tp, th)
3239 tcp_seq onxt = tp->snd_nxt;
3240 u_long ocwnd = tp->snd_cwnd;
3242 callout_stop(tp->tt_rexmt);
3244 tp->snd_nxt = th->th_ack;
3246 * Set snd_cwnd to one segment beyond acknowledged offset.
3247 * (tp->snd_una has not yet been updated when this function is called.)
3249 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3250 tp->t_flags |= TF_ACKNOW;
3251 (void) tcp_output(tp);
3252 tp->snd_cwnd = ocwnd;
3253 if (SEQ_GT(onxt, tp->snd_nxt))
3256 * Partial window deflation. Relies on fact that tp->snd_una
3259 if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3260 tp->snd_cwnd -= th->th_ack - tp->snd_una;
3263 tp->snd_cwnd += tp->t_maxseg;
3267 * Returns 1 if the TIME_WAIT state was killed and we should start over,
3268 * looking for a pcb in the listen state. Returns 0 otherwise.
3271 tcp_timewait(inp, to, th, m, tlen)
3282 int isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
3284 const int isipv6 = 0;
3287 /* tcbinfo lock required for tcp_twclose(), tcp_timer_2msl_reset(). */
3288 INP_INFO_WLOCK_ASSERT(&tcbinfo);
3289 INP_LOCK_ASSERT(inp);
3292 * XXXRW: Time wait state for inpcb has been recycled, but inpcb is
3293 * still present. This is undesirable, but temporarily necessary
3294 * until we work out how to handle inpcb's who's timewait state has
3301 thflags = th->th_flags;
3304 * NOTE: for FIN_WAIT_2 (to be added later),
3305 * must validate sequence number before accepting RST
3309 * If the segment contains RST:
3310 * Drop the segment - see Stevens, vol. 2, p. 964 and
3313 if (thflags & TH_RST)
3317 /* PAWS not needed at the moment */
3319 * RFC 1323 PAWS: If we have a timestamp reply on this segment
3320 * and it's less than ts_recent, drop it.
3322 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
3323 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
3324 if ((thflags & TH_ACK) == 0)
3329 * ts_recent is never updated because we never accept new segments.
3334 * If a new connection request is received
3335 * while in TIME_WAIT, drop the old connection
3336 * and start over if the sequence numbers
3337 * are above the previous ones.
3339 if ((thflags & TH_SYN) && SEQ_GT(th->th_seq, tw->rcv_nxt)) {
3345 * Drop the the segment if it does not contain an ACK.
3347 if ((thflags & TH_ACK) == 0)
3351 * Reset the 2MSL timer if this is a duplicate FIN.
3353 if (thflags & TH_FIN) {
3354 seq = th->th_seq + tlen + (thflags & TH_SYN ? 1 : 0);
3355 if (seq + 1 == tw->rcv_nxt)
3356 tcp_timer_2msl_reset(tw, 1);
3360 * Acknowledge the segment if it has data or is not a duplicate ACK.
3362 if (thflags != TH_ACK || tlen != 0 ||
3363 th->th_seq != tw->rcv_nxt || th->th_ack != tw->snd_nxt)
3364 tcp_twrespond(tw, TH_ACK);
3368 * Generate a RST, dropping incoming segment.
3369 * Make ACK acceptable to originator of segment.
3370 * Don't bother to respond if destination was broadcast/multicast.
3372 if (m->m_flags & (M_BCAST|M_MCAST))
3375 struct ip6_hdr *ip6;
3377 /* IPv6 anycast check is done at tcp6_input() */
3378 ip6 = mtod(m, struct ip6_hdr *);
3379 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3380 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3385 ip = mtod(m, struct ip *);
3386 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3387 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3388 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3389 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3392 if (thflags & TH_ACK) {
3394 mtod(m, void *), th, m, 0, th->th_ack, TH_RST);
3396 seq = th->th_seq + (thflags & TH_SYN ? 1 : 0);
3398 mtod(m, void *), th, m, seq, 0, TH_RST|TH_ACK);