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"
40 #include <sys/param.h>
41 #include <sys/kernel.h>
42 #include <sys/malloc.h>
44 #include <sys/proc.h> /* for proc0 declaration */
45 #include <sys/protosw.h>
46 #include <sys/signalvar.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/sysctl.h>
50 #include <sys/syslog.h>
51 #include <sys/systm.h>
53 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
58 #include <net/route.h>
60 #include <netinet/in.h>
61 #include <netinet/in_pcb.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/in_var.h>
64 #include <netinet/ip.h>
65 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
66 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
67 #include <netinet/ip_var.h>
68 #include <netinet/ip_options.h>
69 #include <netinet/ip6.h>
70 #include <netinet/icmp6.h>
71 #include <netinet6/in6_pcb.h>
72 #include <netinet6/ip6_var.h>
73 #include <netinet6/nd6.h>
74 #include <netinet/tcp.h>
75 #include <netinet/tcp_fsm.h>
76 #include <netinet/tcp_seq.h>
77 #include <netinet/tcp_timer.h>
78 #include <netinet/tcp_var.h>
79 #include <netinet6/tcp6_var.h>
80 #include <netinet/tcpip.h>
82 #include <netinet/tcp_debug.h>
86 #include <netipsec/ipsec.h>
87 #include <netipsec/ipsec6.h>
91 #include <netinet6/ipsec.h>
92 #include <netinet6/ipsec6.h>
93 #include <netkey/key.h>
96 #include <machine/in_cksum.h>
98 #include <security/mac/mac_framework.h>
100 static const int tcprexmtthresh = 3;
102 struct tcpstat tcpstat;
103 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
104 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
106 static int tcp_log_in_vain = 0;
107 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
108 &tcp_log_in_vain, 0, "Log all incoming TCP segments to closed ports");
110 static int blackhole = 0;
111 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
112 &blackhole, 0, "Do not send RST on segments to closed ports");
114 int tcp_delack_enabled = 1;
115 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
116 &tcp_delack_enabled, 0,
117 "Delay ACK to try and piggyback it onto a data packet");
119 static int drop_synfin = 0;
120 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
121 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
123 static int tcp_do_rfc3042 = 1;
124 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
125 &tcp_do_rfc3042, 0, "Enable RFC 3042 (Limited Transmit)");
127 static int tcp_do_rfc3390 = 1;
128 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
130 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
132 static int tcp_insecure_rst = 0;
133 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
134 &tcp_insecure_rst, 0,
135 "Follow the old (insecure) criteria for accepting RST packets");
137 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
138 "TCP Segment Reassembly Queue");
140 static int tcp_reass_maxseg = 0;
141 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RDTUN,
142 &tcp_reass_maxseg, 0,
143 "Global maximum number of TCP Segments in Reassembly Queue");
145 int tcp_reass_qsize = 0;
146 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
148 "Global number of TCP Segments currently in Reassembly Queue");
150 static int tcp_reass_maxqlen = 48;
151 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxqlen, CTLFLAG_RW,
152 &tcp_reass_maxqlen, 0,
153 "Maximum number of TCP Segments per individual Reassembly Queue");
155 static int tcp_reass_overflows = 0;
156 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
157 &tcp_reass_overflows, 0,
158 "Global number of TCP Segment Reassembly Queue Overflows");
160 int tcp_do_autorcvbuf = 1;
161 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
162 &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
164 int tcp_autorcvbuf_inc = 16*1024;
165 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
166 &tcp_autorcvbuf_inc, 0,
167 "Incrementor step size of automatic receive buffer");
169 int tcp_autorcvbuf_max = 256*1024;
170 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
171 &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
173 struct inpcbhead tcb;
174 #define tcb6 tcb /* for KAME src sync over BSD*'s */
175 struct inpcbinfo tcbinfo;
176 struct mtx *tcbinfo_mtx;
178 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
179 static int tcp_do_segment(struct mbuf *, struct tcphdr *,
180 struct socket *, struct tcpcb *, int, int);
181 static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
182 struct tcpcb *, int, int);
183 static void tcp_pulloutofband(struct socket *,
184 struct tcphdr *, struct mbuf *, int);
185 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
187 static void tcp_xmit_timer(struct tcpcb *, int);
188 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
189 static int tcp_timewait(struct inpcb *, struct tcpopt *,
190 struct tcphdr *, struct mbuf *, int);
192 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
194 #define ND6_HINT(tp) \
196 if ((tp) && (tp)->t_inpcb && \
197 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
198 nd6_nud_hint(NULL, NULL, 0); \
205 * Indicate whether this ack should be delayed. We can delay the ack if
206 * - there is no delayed ack timer in progress and
207 * - our last ack wasn't a 0-sized window. We never want to delay
208 * the ack that opens up a 0-sized window and
209 * - delayed acks are enabled or
210 * - this is a half-synchronized T/TCP connection.
212 #define DELAY_ACK(tp) \
213 ((!callout_active(tp->tt_delack) && \
214 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
215 (tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
217 /* Initialize TCP reassembly queue */
219 tcp_reass_zone_change(void *tag)
222 tcp_reass_maxseg = nmbclusters / 16;
223 uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
226 uma_zone_t tcp_reass_zone;
230 tcp_reass_maxseg = nmbclusters / 16;
231 TUNABLE_INT_FETCH("net.inet.tcp.reass.maxsegments",
233 tcp_reass_zone = uma_zcreate("tcpreass", sizeof (struct tseg_qent),
234 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
235 uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
236 EVENTHANDLER_REGISTER(nmbclusters_change,
237 tcp_reass_zone_change, NULL, EVENTHANDLER_PRI_ANY);
241 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
244 struct tseg_qent *p = NULL;
245 struct tseg_qent *nq;
246 struct tseg_qent *te = NULL;
247 struct socket *so = tp->t_inpcb->inp_socket;
250 INP_LOCK_ASSERT(tp->t_inpcb);
253 * XXX: tcp_reass() is rather inefficient with its data structures
254 * and should be rewritten (see NetBSD for optimizations). While
255 * doing that it should move to its own file tcp_reass.c.
259 * Call with th==NULL after become established to
260 * force pre-ESTABLISHED data up to user socket.
266 * Limit the number of segments in the reassembly queue to prevent
267 * holding on to too many segments (and thus running out of mbufs).
268 * Make sure to let the missing segment through which caused this
269 * queue. Always keep one global queue entry spare to be able to
270 * process the missing segment.
272 if (th->th_seq != tp->rcv_nxt &&
273 (tcp_reass_qsize + 1 >= tcp_reass_maxseg ||
274 tp->t_segqlen >= tcp_reass_maxqlen)) {
275 tcp_reass_overflows++;
276 tcpstat.tcps_rcvmemdrop++;
283 * Allocate a new queue entry. If we can't, or hit the zone limit
286 te = uma_zalloc(tcp_reass_zone, M_NOWAIT);
288 tcpstat.tcps_rcvmemdrop++;
297 * Find a segment which begins after this one does.
299 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
300 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
306 * If there is a preceding segment, it may provide some of
307 * our data already. If so, drop the data from the incoming
308 * segment. If it provides all of our data, drop us.
312 /* conversion to int (in i) handles seq wraparound */
313 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
316 tcpstat.tcps_rcvduppack++;
317 tcpstat.tcps_rcvdupbyte += *tlenp;
319 uma_zfree(tcp_reass_zone, te);
323 * Try to present any queued data
324 * at the left window edge to the user.
325 * This is needed after the 3-WHS
328 goto present; /* ??? */
335 tcpstat.tcps_rcvoopack++;
336 tcpstat.tcps_rcvoobyte += *tlenp;
339 * While we overlap succeeding segments trim them or,
340 * if they are completely covered, dequeue them.
343 int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
346 if (i < q->tqe_len) {
347 q->tqe_th->th_seq += i;
353 nq = LIST_NEXT(q, tqe_q);
354 LIST_REMOVE(q, tqe_q);
356 uma_zfree(tcp_reass_zone, q);
362 /* Insert the new segment queue entry into place. */
365 te->tqe_len = *tlenp;
368 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
370 LIST_INSERT_AFTER(p, te, tqe_q);
375 * Present data to user, advancing rcv_nxt through
376 * completed sequence space.
378 if (!TCPS_HAVEESTABLISHED(tp->t_state))
380 q = LIST_FIRST(&tp->t_segq);
381 if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
383 SOCKBUF_LOCK(&so->so_rcv);
385 tp->rcv_nxt += q->tqe_len;
386 flags = q->tqe_th->th_flags & TH_FIN;
387 nq = LIST_NEXT(q, tqe_q);
388 LIST_REMOVE(q, tqe_q);
389 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
392 sbappendstream_locked(&so->so_rcv, q->tqe_m);
393 uma_zfree(tcp_reass_zone, q);
397 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
399 sorwakeup_locked(so);
404 * TCP input routine, follows pages 65-76 of the
405 * protocol specification dated September, 1981 very closely.
409 tcp6_input(struct mbuf **mp, int *offp, int proto)
411 struct mbuf *m = *mp;
412 struct in6_ifaddr *ia6;
414 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
417 * draft-itojun-ipv6-tcp-to-anycast
418 * better place to put this in?
420 ia6 = ip6_getdstifaddr(m);
421 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
424 ip6 = mtod(m, struct ip6_hdr *);
425 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
426 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
436 tcp_input(struct mbuf *m, int off0)
439 struct ip *ip = NULL;
441 struct inpcb *inp = NULL;
442 struct tcpcb *tp = NULL;
443 struct socket *so = NULL;
449 int rstreason = 0; /* For badport_bandlim accounting purposes */
450 #ifdef IPFIREWALL_FORWARD
451 struct m_tag *fwd_tag;
454 struct ip6_hdr *ip6 = NULL;
456 char ip6buf[INET6_ADDRSTRLEN];
458 const int isipv6 = 0;
460 struct tcpopt to; /* options in this segment */
464 * The size of tcp_saveipgen must be the size of the max ip header,
467 u_char tcp_saveipgen[IP6_HDR_LEN];
468 struct tcphdr tcp_savetcp;
473 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
477 tcpstat.tcps_rcvtotal++;
481 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
482 ip6 = mtod(m, struct ip6_hdr *);
483 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
484 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
485 tcpstat.tcps_rcvbadsum++;
488 th = (struct tcphdr *)((caddr_t)ip6 + off0);
491 * Be proactive about unspecified IPv6 address in source.
492 * As we use all-zero to indicate unbounded/unconnected pcb,
493 * unspecified IPv6 address can be used to confuse us.
495 * Note that packets with unspecified IPv6 destination is
496 * already dropped in ip6_input.
498 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
503 th = NULL; /* XXX: avoid compiler warning */
507 * Get IP and TCP header together in first mbuf.
508 * Note: IP leaves IP header in first mbuf.
510 if (off0 > sizeof (struct ip)) {
511 ip_stripoptions(m, (struct mbuf *)0);
512 off0 = sizeof(struct ip);
514 if (m->m_len < sizeof (struct tcpiphdr)) {
515 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
517 tcpstat.tcps_rcvshort++;
521 ip = mtod(m, struct ip *);
522 ipov = (struct ipovly *)ip;
523 th = (struct tcphdr *)((caddr_t)ip + off0);
526 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
527 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
528 th->th_sum = m->m_pkthdr.csum_data;
530 th->th_sum = in_pseudo(ip->ip_src.s_addr,
532 htonl(m->m_pkthdr.csum_data +
535 th->th_sum ^= 0xffff;
537 ipov->ih_len = (u_short)tlen;
538 ipov->ih_len = htons(ipov->ih_len);
542 * Checksum extended TCP header and data.
544 len = sizeof (struct ip) + tlen;
545 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
546 ipov->ih_len = (u_short)tlen;
547 ipov->ih_len = htons(ipov->ih_len);
548 th->th_sum = in_cksum(m, len);
551 tcpstat.tcps_rcvbadsum++;
554 /* Re-initialization for later version check */
555 ip->ip_v = IPVERSION;
559 * Check that TCP offset makes sense,
560 * pull out TCP options and adjust length. XXX
562 off = th->th_off << 2;
563 if (off < sizeof (struct tcphdr) || off > tlen) {
564 tcpstat.tcps_rcvbadoff++;
567 tlen -= off; /* tlen is used instead of ti->ti_len */
568 if (off > sizeof (struct tcphdr)) {
571 IP6_EXTHDR_CHECK(m, off0, off, );
572 ip6 = mtod(m, struct ip6_hdr *);
573 th = (struct tcphdr *)((caddr_t)ip6 + off0);
576 if (m->m_len < sizeof(struct ip) + off) {
577 if ((m = m_pullup(m, sizeof (struct ip) + off))
579 tcpstat.tcps_rcvshort++;
582 ip = mtod(m, struct ip *);
583 ipov = (struct ipovly *)ip;
584 th = (struct tcphdr *)((caddr_t)ip + off0);
587 optlen = off - sizeof (struct tcphdr);
588 optp = (u_char *)(th + 1);
590 thflags = th->th_flags;
593 * If the drop_synfin option is enabled, drop all packets with
594 * both the SYN and FIN bits set. This prevents e.g. nmap from
595 * identifying the TCP/IP stack.
597 * This is a violation of the TCP specification.
599 if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
603 * Convert TCP protocol specific fields to host format.
605 th->th_seq = ntohl(th->th_seq);
606 th->th_ack = ntohl(th->th_ack);
607 th->th_win = ntohs(th->th_win);
608 th->th_urp = ntohs(th->th_urp);
611 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
613 drop_hdrlen = off0 + off;
616 * Locate pcb for segment.
618 INP_INFO_WLOCK(&tcbinfo);
620 INP_INFO_WLOCK_ASSERT(&tcbinfo);
621 #ifdef IPFIREWALL_FORWARD
622 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
623 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
625 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
626 struct sockaddr_in *next_hop;
628 next_hop = (struct sockaddr_in *)(fwd_tag+1);
630 * Transparently forwarded. Pretend to be the destination.
631 * already got one like this?
633 inp = in_pcblookup_hash(&tcbinfo,
634 ip->ip_src, th->th_sport,
635 ip->ip_dst, th->th_dport,
636 0, m->m_pkthdr.rcvif);
638 /* It's new. Try to find the ambushing socket. */
639 inp = in_pcblookup_hash(&tcbinfo,
640 ip->ip_src, th->th_sport,
643 ntohs(next_hop->sin_port) :
648 /* Remove the tag from the packet. We don't need it anymore. */
649 m_tag_delete(m, fwd_tag);
651 #endif /* IPFIREWALL_FORWARD */
655 inp = in6_pcblookup_hash(&tcbinfo,
656 &ip6->ip6_src, th->th_sport,
657 &ip6->ip6_dst, th->th_dport,
662 inp = in_pcblookup_hash(&tcbinfo,
663 ip->ip_src, th->th_sport,
664 ip->ip_dst, th->th_dport,
669 #if defined(IPSEC) || defined(FAST_IPSEC)
671 if (isipv6 && inp != NULL && ipsec6_in_reject(m, inp)) {
673 ipsec6stat.in_polvio++;
678 if (inp != NULL && ipsec4_in_reject(m, inp)) {
680 ipsecstat.in_polvio++;
684 #endif /*IPSEC || FAST_IPSEC*/
687 * If the INPCB does not exist then all data in the incoming
688 * segment is discarded and an appropriate RST is sent back.
692 * Log communication attempts to ports that are not
695 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
696 tcp_log_in_vain == 2) {
698 char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
700 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
704 ip6_sprintf(ip6buf, &ip6->ip6_dst));
708 ip6_sprintf(ip6buf, &ip6->ip6_src));
713 strcpy(dbuf, inet_ntoa(ip->ip_dst));
714 strcpy(sbuf, inet_ntoa(ip->ip_src));
717 "Connection attempt to TCP %s:%d "
718 "from %s:%d flags:0x%02x\n",
719 dbuf, ntohs(th->th_dport), sbuf,
720 ntohs(th->th_sport), thflags);
723 * When blackholing do not respond with a RST but
724 * completely ignore the segment and drop it.
726 if ((blackhole == 1 && (thflags & TH_SYN)) ||
730 rstreason = BANDLIM_RST_CLOSEDPORT;
735 /* Check the minimum TTL for socket. */
736 if (inp->inp_ip_minttl != 0) {
738 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
742 if (inp->inp_ip_minttl > ip->ip_ttl)
747 * A previous connection in TIMEWAIT state is supposed to catch
748 * stray or duplicate segments arriving late. If this segment
749 * was a legitimate new connection attempt the old INPCB gets
750 * removed and we can try again to find a listening socket.
752 if (inp->inp_vflag & INP_TIMEWAIT) {
753 if (thflags & TH_SYN)
754 tcp_dooptions(&to, optp, optlen, TO_SYN);
755 if (tcp_timewait(inp, &to, th, m, tlen))
757 /* tcp_timewait unlocks inp. */
758 INP_INFO_WUNLOCK(&tcbinfo);
762 * The TCPCB may no longer exist if the connection is winding
763 * down or it is in the CLOSED state. Either way we drop the
764 * segment and send an appropriate response.
769 rstreason = BANDLIM_RST_CLOSEDPORT;
772 if (tp->t_state == TCPS_CLOSED)
773 goto dropunlock; /* XXX: dropwithreset??? */
776 INP_LOCK_ASSERT(inp);
777 if (mac_check_inpcb_deliver(inp, m))
780 so = inp->inp_socket;
781 KASSERT(so != NULL, ("%s: so == NULL", __func__));
783 if (so->so_options & SO_DEBUG) {
784 ostate = tp->t_state;
786 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
788 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
793 * When the socket is accepting connections (the INPCB is in LISTEN
794 * state) we look into the SYN cache if this is a new connection
795 * attempt or the completion of a previous one.
797 if (so->so_options & SO_ACCEPTCONN) {
798 struct in_conninfo inc;
800 bzero(&inc, sizeof(inc));
801 inc.inc_isipv6 = isipv6;
804 inc.inc6_faddr = ip6->ip6_src;
805 inc.inc6_laddr = ip6->ip6_dst;
809 inc.inc_faddr = ip->ip_src;
810 inc.inc_laddr = ip->ip_dst;
812 inc.inc_fport = th->th_sport;
813 inc.inc_lport = th->th_dport;
816 * If the state is LISTEN then ignore segment if it contains
817 * a RST. If the segment contains an ACK then it is bad and
818 * send a RST. If it does not contain a SYN then it is not
819 * interesting; drop it.
821 * If the state is SYN_RECEIVED (syncache) and seg contains
822 * an ACK, but not for our SYN/ACK, send a RST. If the seg
823 * contains a RST, check the sequence number to see if it
824 * is a valid reset segment.
826 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
827 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
829 * Parse the TCP options here because
830 * syncookies need access to the reflected
833 tcp_dooptions(&to, optp, optlen, 0);
834 if (!syncache_expand(&inc, &to, th, &so, m)) {
836 * No syncache entry, or ACK was not
837 * for our SYN/ACK. Send a RST.
839 tcpstat.tcps_badsyn++;
840 rstreason = BANDLIM_RST_OPENPORT;
845 * Could not complete 3-way handshake,
846 * connection is being closed down, and
847 * syncache has free'd mbuf.
850 INP_INFO_WUNLOCK(&tcbinfo);
854 * Socket is created in state SYN_RECEIVED.
855 * Continue processing segment.
857 INP_UNLOCK(inp); /* listen socket */
859 INP_LOCK(inp); /* new connection */
862 * Process the segment and the data it
863 * contains. tcp_do_segment() consumes
864 * the mbuf chain and unlocks the inpcb.
865 * XXX: The potential return value of
866 * TIME_WAIT nuked is supposed to be
869 if (tcp_do_segment(m, th, so, tp,
871 goto findpcb; /* TIME_WAIT nuked */
874 if (thflags & TH_RST) {
875 syncache_chkrst(&inc, th);
878 if (thflags & TH_ACK) {
879 syncache_badack(&inc);
880 tcpstat.tcps_badsyn++;
881 rstreason = BANDLIM_RST_OPENPORT;
888 * Segment's flags are (SYN) or (SYN|FIN).
892 * If deprecated address is forbidden,
893 * we do not accept SYN to deprecated interface
894 * address to prevent any new inbound connection from
895 * getting established.
896 * When we do not accept SYN, we send a TCP RST,
897 * with deprecated source address (instead of dropping
898 * it). We compromise it as it is much better for peer
899 * to send a RST, and RST will be the final packet
902 * If we do not forbid deprecated addresses, we accept
903 * the SYN packet. RFC2462 does not suggest dropping
905 * If we decipher RFC2462 5.5.4, it says like this:
906 * 1. use of deprecated addr with existing
907 * communication is okay - "SHOULD continue to be
909 * 2. use of it with new communication:
910 * (2a) "SHOULD NOT be used if alternate address
911 * with sufficient scope is available"
912 * (2b) nothing mentioned otherwise.
913 * Here we fall into (2b) case as we have no choice in
914 * our source address selection - we must obey the peer.
916 * The wording in RFC2462 is confusing, and there are
917 * multiple description text for deprecated address
918 * handling - worse, they are not exactly the same.
919 * I believe 5.5.4 is the best one, so we follow 5.5.4.
921 if (isipv6 && !ip6_use_deprecated) {
922 struct in6_ifaddr *ia6;
924 if ((ia6 = ip6_getdstifaddr(m)) &&
925 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
928 rstreason = BANDLIM_RST_OPENPORT;
934 * Basic sanity checks on incoming SYN requests:
936 * Don't bother responding if the destination was a
937 * broadcast according to RFC1122 4.2.3.10, p. 104.
939 * If it is from this socket, drop it, it must be forged.
941 * Note that it is quite possible to receive unicast
942 * link-layer packets with a broadcast IP address. Use
943 * in_broadcast() to find them.
945 if (m->m_flags & (M_BCAST|M_MCAST))
949 if (th->th_dport == th->th_sport &&
950 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src))
952 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
953 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
957 if (th->th_dport == th->th_sport &&
958 ip->ip_dst.s_addr == ip->ip_src.s_addr)
960 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
961 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
962 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
963 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
967 * SYN appears to be valid. Create compressed TCP state
970 if (so->so_qlen <= so->so_qlimit) {
972 if (so->so_options & SO_DEBUG)
973 tcp_trace(TA_INPUT, ostate, tp,
974 (void *)tcp_saveipgen, &tcp_savetcp, 0);
976 tcp_dooptions(&to, optp, optlen, TO_SYN);
977 if (!syncache_add(&inc, &to, th, inp, &so, m))
980 * Entry added to syncache, mbuf used to
981 * send SYN-ACK packet. Everything unlocked
986 /* Catch all. Everthing that makes it down here is junk. */
991 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or
992 * later state. tcp_do_segment() always consumes the mbuf chain
993 * and unlocks the inpcb.
995 if (tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen))
996 goto findpcb; /* XXX: TIME_WAIT was nuked. */
1000 INP_INFO_WLOCK_ASSERT(&tcbinfo);
1001 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1002 m = NULL; /* mbuf chain got consumed. */
1004 INP_INFO_WLOCK_ASSERT(&tcbinfo);
1007 INP_INFO_WUNLOCK(&tcbinfo);
1009 INP_INFO_UNLOCK_ASSERT(&tcbinfo);
1016 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1017 struct tcpcb *tp, int drop_hdrlen, int tlen)
1019 int thflags, acked, ourfinisacked, needoutput = 0;
1021 int rstreason, todrop, win;
1027 * The size of tcp_saveipgen must be the size of the max ip header,
1030 u_char tcp_saveipgen[IP6_HDR_LEN];
1031 struct tcphdr tcp_savetcp;
1034 thflags = th->th_flags;
1036 INP_INFO_WLOCK_ASSERT(&tcbinfo);
1037 INP_LOCK_ASSERT(tp->t_inpcb);
1038 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN", __func__));
1041 * Segment received on connection.
1042 * Reset idle time and keep-alive timer.
1044 tp->t_rcvtime = ticks;
1045 if (TCPS_HAVEESTABLISHED(tp->t_state))
1046 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
1049 * Unscale the window into a 32-bit value.
1050 * This value is bogus for the TCPS_SYN_SENT state
1051 * and is overwritten later.
1053 tiwin = th->th_win << tp->snd_scale;
1056 * Parse options on any incoming segment.
1058 tcp_dooptions(&to, (u_char *)(th + 1),
1059 (th->th_off << 2) - sizeof(struct tcphdr),
1060 (thflags & TH_SYN) ? TO_SYN : 0);
1063 * If echoed timestamp is later than the current time,
1064 * fall back to non RFC1323 RTT calculation. Normalize
1065 * timestamp if syncookies were used when this connection
1068 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1069 to.to_tsecr -= tp->ts_offset;
1070 if (TSTMP_GT(to.to_tsecr, ticks))
1075 * Process options only when we get SYN/ACK back. The SYN case
1076 * for incoming connections is handled in tcp_syncache.
1077 * XXX this is traditional behavior, may need to be cleaned up.
1079 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1080 if ((to.to_flags & TOF_SCALE) &&
1081 (tp->t_flags & TF_REQ_SCALE)) {
1082 tp->t_flags |= TF_RCVD_SCALE;
1083 tp->snd_scale = to.to_wscale;
1084 tp->snd_wnd = th->th_win << tp->snd_scale;
1085 tiwin = tp->snd_wnd;
1087 if (to.to_flags & TOF_TS) {
1088 tp->t_flags |= TF_RCVD_TSTMP;
1089 tp->ts_recent = to.to_tsval;
1090 tp->ts_recent_age = ticks;
1092 /* Initial send window, already scaled. */
1093 tp->snd_wnd = th->th_win;
1094 if (to.to_flags & TOF_MSS)
1095 tcp_mss(tp, to.to_mss);
1096 if (tp->sack_enable) {
1097 if (!(to.to_flags & TOF_SACKPERM))
1098 tp->sack_enable = 0;
1100 tp->t_flags |= TF_SACK_PERMIT;
1106 * Header prediction: check for the two common cases
1107 * of a uni-directional data xfer. If the packet has
1108 * no control flags, is in-sequence, the window didn't
1109 * change and we're not retransmitting, it's a
1110 * candidate. If the length is zero and the ack moved
1111 * forward, we're the sender side of the xfer. Just
1112 * free the data acked & wake any higher level process
1113 * that was blocked waiting for space. If the length
1114 * is non-zero and the ack didn't move, we're the
1115 * receiver side. If we're getting packets in-order
1116 * (the reassembly queue is empty), add the data to
1117 * the socket buffer and note that we need a delayed ack.
1118 * Make sure that the hidden state-flags are also off.
1119 * Since we check for TCPS_ESTABLISHED above, it can only
1122 if (tp->t_state == TCPS_ESTABLISHED &&
1123 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1124 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1125 ((to.to_flags & TOF_TS) == 0 ||
1126 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1127 th->th_seq == tp->rcv_nxt && tiwin && tiwin == tp->snd_wnd &&
1128 tp->snd_nxt == tp->snd_max) {
1131 * If last ACK falls within this segment's sequence numbers,
1132 * record the timestamp.
1133 * NOTE that the test is modified according to the latest
1134 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1136 if ((to.to_flags & TOF_TS) != 0 &&
1137 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1138 tp->ts_recent_age = ticks;
1139 tp->ts_recent = to.to_tsval;
1143 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1144 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1145 tp->snd_cwnd >= tp->snd_wnd &&
1146 ((!tcp_do_newreno && !tp->sack_enable &&
1147 tp->t_dupacks < tcprexmtthresh) ||
1148 ((tcp_do_newreno || tp->sack_enable) &&
1149 !IN_FASTRECOVERY(tp) &&
1150 (to.to_flags & TOF_SACK) == 0 &&
1151 TAILQ_EMPTY(&tp->snd_holes)))) {
1153 ("%s: headlocked", __func__));
1154 INP_INFO_WUNLOCK(&tcbinfo);
1157 * this is a pure ack for outstanding data.
1159 ++tcpstat.tcps_predack;
1161 * "bad retransmit" recovery
1163 if (tp->t_rxtshift == 1 &&
1164 ticks < tp->t_badrxtwin) {
1165 ++tcpstat.tcps_sndrexmitbad;
1166 tp->snd_cwnd = tp->snd_cwnd_prev;
1168 tp->snd_ssthresh_prev;
1169 tp->snd_recover = tp->snd_recover_prev;
1170 if (tp->t_flags & TF_WASFRECOVERY)
1171 ENTER_FASTRECOVERY(tp);
1172 tp->snd_nxt = tp->snd_max;
1173 tp->t_badrxtwin = 0;
1177 * Recalculate the transmit timer / rtt.
1179 * Some boxes send broken timestamp replies
1180 * during the SYN+ACK phase, ignore
1181 * timestamps of 0 or we could calculate a
1182 * huge RTT and blow up the retransmit timer.
1184 if ((to.to_flags & TOF_TS) != 0 &&
1186 if (!tp->t_rttlow ||
1187 tp->t_rttlow > ticks - to.to_tsecr)
1188 tp->t_rttlow = ticks - to.to_tsecr;
1190 ticks - to.to_tsecr + 1);
1191 } else if (tp->t_rtttime &&
1192 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1193 if (!tp->t_rttlow ||
1194 tp->t_rttlow > ticks - tp->t_rtttime)
1195 tp->t_rttlow = ticks - tp->t_rtttime;
1197 ticks - tp->t_rtttime);
1199 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1200 acked = th->th_ack - tp->snd_una;
1201 tcpstat.tcps_rcvackpack++;
1202 tcpstat.tcps_rcvackbyte += acked;
1203 sbdrop(&so->so_snd, acked);
1204 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1205 SEQ_LEQ(th->th_ack, tp->snd_recover))
1206 tp->snd_recover = th->th_ack - 1;
1207 tp->snd_una = th->th_ack;
1209 * pull snd_wl2 up to prevent seq wrap relative
1212 tp->snd_wl2 = th->th_ack;
1215 ND6_HINT(tp); /* some progress has been done */
1218 * If all outstanding data are acked, stop
1219 * retransmit timer, otherwise restart timer
1220 * using current (possibly backed-off) value.
1221 * If process is waiting for space,
1222 * wakeup/selwakeup/signal. If data
1223 * are ready to send, let tcp_output
1224 * decide between more output or persist.
1227 if (so->so_options & SO_DEBUG)
1228 tcp_trace(TA_INPUT, ostate, tp,
1229 (void *)tcp_saveipgen,
1233 if (tp->snd_una == tp->snd_max)
1234 callout_stop(tp->tt_rexmt);
1235 else if (!callout_active(tp->tt_persist))
1236 callout_reset(tp->tt_rexmt,
1238 tcp_timer_rexmt, tp);
1241 if (so->so_snd.sb_cc)
1242 (void) tcp_output(tp);
1245 } else if (th->th_ack == tp->snd_una &&
1246 LIST_EMPTY(&tp->t_segq) &&
1247 tlen <= sbspace(&so->so_rcv)) {
1248 int newsize = 0; /* automatic sockbuf scaling */
1250 KASSERT(headlocked, ("%s: headlocked", __func__));
1251 INP_INFO_WUNLOCK(&tcbinfo);
1254 * this is a pure, in-sequence data packet
1255 * with nothing on the reassembly queue and
1256 * we have enough buffer space to take it.
1258 /* Clean receiver SACK report if present */
1259 if (tp->sack_enable && tp->rcv_numsacks)
1260 tcp_clean_sackreport(tp);
1261 ++tcpstat.tcps_preddat;
1262 tp->rcv_nxt += tlen;
1264 * Pull snd_wl1 up to prevent seq wrap relative to
1267 tp->snd_wl1 = th->th_seq;
1269 * Pull rcv_up up to prevent seq wrap relative to
1272 tp->rcv_up = tp->rcv_nxt;
1273 tcpstat.tcps_rcvpack++;
1274 tcpstat.tcps_rcvbyte += tlen;
1275 ND6_HINT(tp); /* some progress has been done */
1277 if (so->so_options & SO_DEBUG)
1278 tcp_trace(TA_INPUT, ostate, tp,
1279 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1282 * Automatic sizing of receive socket buffer. Often the send
1283 * buffer size is not optimally adjusted to the actual network
1284 * conditions at hand (delay bandwidth product). Setting the
1285 * buffer size too small limits throughput on links with high
1286 * bandwidth and high delay (eg. trans-continental/oceanic links).
1288 * On the receive side the socket buffer memory is only rarely
1289 * used to any significant extent. This allows us to be much
1290 * more aggressive in scaling the receive socket buffer. For
1291 * the case that the buffer space is actually used to a large
1292 * extent and we run out of kernel memory we can simply drop
1293 * the new segments; TCP on the sender will just retransmit it
1294 * later. Setting the buffer size too big may only consume too
1295 * much kernel memory if the application doesn't read() from
1296 * the socket or packet loss or reordering makes use of the
1299 * The criteria to step up the receive buffer one notch are:
1300 * 1. the number of bytes received during the time it takes
1301 * one timestamp to be reflected back to us (the RTT);
1302 * 2. received bytes per RTT is within seven eighth of the
1303 * current socket buffer size;
1304 * 3. receive buffer size has not hit maximal automatic size;
1306 * This algorithm does one step per RTT at most and only if
1307 * we receive a bulk stream w/o packet losses or reorderings.
1308 * Shrinking the buffer during idle times is not necessary as
1309 * it doesn't consume any memory when idle.
1311 * TODO: Only step up if the application is actually serving
1312 * the buffer to better manage the socket buffer resources.
1314 if (tcp_do_autorcvbuf &&
1316 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1317 if (to.to_tsecr > tp->rfbuf_ts &&
1318 to.to_tsecr - tp->rfbuf_ts < hz) {
1320 (so->so_rcv.sb_hiwat / 8 * 7) &&
1321 so->so_rcv.sb_hiwat <
1322 tcp_autorcvbuf_max) {
1324 min(so->so_rcv.sb_hiwat +
1326 tcp_autorcvbuf_max);
1328 /* Start over with next RTT. */
1332 tp->rfbuf_cnt += tlen; /* add up */
1335 /* Add data to socket buffer. */
1336 SOCKBUF_LOCK(&so->so_rcv);
1337 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1341 * Set new socket buffer size.
1342 * Give up when limit is reached.
1345 if (!sbreserve_locked(&so->so_rcv,
1346 newsize, so, curthread))
1347 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1348 m_adj(m, drop_hdrlen); /* delayed header drop */
1349 sbappendstream_locked(&so->so_rcv, m);
1351 sorwakeup_locked(so);
1352 if (DELAY_ACK(tp)) {
1353 tp->t_flags |= TF_DELACK;
1355 tp->t_flags |= TF_ACKNOW;
1363 * Calculate amount of space in receive window,
1364 * and then do TCP input processing.
1365 * Receive window is amount of space in rcv queue,
1366 * but not less than advertised window.
1368 win = sbspace(&so->so_rcv);
1371 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1373 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1377 switch (tp->t_state) {
1380 * If the state is SYN_RECEIVED:
1381 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1383 case TCPS_SYN_RECEIVED:
1384 if ((thflags & TH_ACK) &&
1385 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1386 SEQ_GT(th->th_ack, tp->snd_max))) {
1387 rstreason = BANDLIM_RST_OPENPORT;
1393 * If the state is SYN_SENT:
1394 * if seg contains an ACK, but not for our SYN, drop the input.
1395 * if seg contains a RST, then drop the connection.
1396 * if seg does not contain SYN, then drop it.
1397 * Otherwise this is an acceptable SYN segment
1398 * initialize tp->rcv_nxt and tp->irs
1399 * if seg contains ack then advance tp->snd_una
1400 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1401 * arrange for segment to be acked (eventually)
1402 * continue processing rest of data/controls, beginning with URG
1405 if ((thflags & TH_ACK) &&
1406 (SEQ_LEQ(th->th_ack, tp->iss) ||
1407 SEQ_GT(th->th_ack, tp->snd_max))) {
1408 rstreason = BANDLIM_UNLIMITED;
1411 if (thflags & TH_RST) {
1412 if (thflags & TH_ACK) {
1413 KASSERT(headlocked, ("%s: after_listen: "
1414 "tcp_drop.2: head not locked", __func__));
1415 tp = tcp_drop(tp, ECONNREFUSED);
1419 if ((thflags & TH_SYN) == 0)
1422 tp->irs = th->th_seq;
1424 if (thflags & TH_ACK) {
1425 tcpstat.tcps_connects++;
1429 mac_set_socket_peer_from_mbuf(m, so);
1432 /* Do window scaling on this connection? */
1433 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1434 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1435 tp->rcv_scale = tp->request_r_scale;
1437 tp->rcv_adv += tp->rcv_wnd;
1438 tp->snd_una++; /* SYN is acked */
1440 * If there's data, delay ACK; if there's also a FIN
1441 * ACKNOW will be turned on later.
1443 if (DELAY_ACK(tp) && tlen != 0)
1444 callout_reset(tp->tt_delack, tcp_delacktime,
1445 tcp_timer_delack, tp);
1447 tp->t_flags |= TF_ACKNOW;
1449 * Received <SYN,ACK> in SYN_SENT[*] state.
1451 * SYN_SENT --> ESTABLISHED
1452 * SYN_SENT* --> FIN_WAIT_1
1454 tp->t_starttime = ticks;
1455 if (tp->t_flags & TF_NEEDFIN) {
1456 tp->t_state = TCPS_FIN_WAIT_1;
1457 tp->t_flags &= ~TF_NEEDFIN;
1460 tp->t_state = TCPS_ESTABLISHED;
1461 callout_reset(tp->tt_keep, tcp_keepidle,
1462 tcp_timer_keep, tp);
1466 * Received initial SYN in SYN-SENT[*] state =>
1467 * simultaneous open. If segment contains CC option
1468 * and there is a cached CC, apply TAO test.
1469 * If it succeeds, connection is * half-synchronized.
1470 * Otherwise, do 3-way handshake:
1471 * SYN-SENT -> SYN-RECEIVED
1472 * SYN-SENT* -> SYN-RECEIVED*
1473 * If there was no CC option, clear cached CC value.
1475 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1476 callout_stop(tp->tt_rexmt);
1477 tp->t_state = TCPS_SYN_RECEIVED;
1480 KASSERT(headlocked, ("%s: trimthenstep6: head not locked",
1482 INP_LOCK_ASSERT(tp->t_inpcb);
1485 * Advance th->th_seq to correspond to first data byte.
1486 * If data, trim to stay within window,
1487 * dropping FIN if necessary.
1490 if (tlen > tp->rcv_wnd) {
1491 todrop = tlen - tp->rcv_wnd;
1495 tcpstat.tcps_rcvpackafterwin++;
1496 tcpstat.tcps_rcvbyteafterwin += todrop;
1498 tp->snd_wl1 = th->th_seq - 1;
1499 tp->rcv_up = th->th_seq;
1501 * Client side of transaction: already sent SYN and data.
1502 * If the remote host used T/TCP to validate the SYN,
1503 * our data will be ACK'd; if so, enter normal data segment
1504 * processing in the middle of step 5, ack processing.
1505 * Otherwise, goto step 6.
1507 if (thflags & TH_ACK)
1513 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1514 * do normal processing.
1516 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1520 case TCPS_TIME_WAIT:
1521 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: timewait",
1523 break; /* continue normal processing */
1527 * States other than LISTEN or SYN_SENT.
1528 * First check the RST flag and sequence number since reset segments
1529 * are exempt from the timestamp and connection count tests. This
1530 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1531 * below which allowed reset segments in half the sequence space
1532 * to fall though and be processed (which gives forged reset
1533 * segments with a random sequence number a 50 percent chance of
1534 * killing a connection).
1535 * Then check timestamp, if present.
1536 * Then check the connection count, if present.
1537 * Then check that at least some bytes of segment are within
1538 * receive window. If segment begins before rcv_nxt,
1539 * drop leading data (and SYN); if nothing left, just ack.
1542 * If the RST bit is set, check the sequence number to see
1543 * if this is a valid reset segment.
1545 * In all states except SYN-SENT, all reset (RST) segments
1546 * are validated by checking their SEQ-fields. A reset is
1547 * valid if its sequence number is in the window.
1548 * Note: this does not take into account delayed ACKs, so
1549 * we should test against last_ack_sent instead of rcv_nxt.
1550 * The sequence number in the reset segment is normally an
1551 * echo of our outgoing acknowlegement numbers, but some hosts
1552 * send a reset with the sequence number at the rightmost edge
1553 * of our receive window, and we have to handle this case.
1554 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1555 * that brute force RST attacks are possible. To combat this,
1556 * we use a much stricter check while in the ESTABLISHED state,
1557 * only accepting RSTs where the sequence number is equal to
1558 * last_ack_sent. In all other states (the states in which a
1559 * RST is more likely), the more permissive check is used.
1560 * If we have multiple segments in flight, the intial reset
1561 * segment sequence numbers will be to the left of last_ack_sent,
1562 * but they will eventually catch up.
1563 * In any case, it never made sense to trim reset segments to
1564 * fit the receive window since RFC 1122 says:
1565 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1567 * A TCP SHOULD allow a received RST segment to include data.
1570 * It has been suggested that a RST segment could contain
1571 * ASCII text that encoded and explained the cause of the
1572 * RST. No standard has yet been established for such
1575 * If the reset segment passes the sequence number test examine
1577 * SYN_RECEIVED STATE:
1578 * If passive open, return to LISTEN state.
1579 * If active open, inform user that connection was refused.
1580 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1581 * Inform user that connection was reset, and close tcb.
1582 * CLOSING, LAST_ACK STATES:
1585 * Drop the segment - see Stevens, vol. 2, p. 964 and
1588 if (thflags & TH_RST) {
1589 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1590 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1591 switch (tp->t_state) {
1593 case TCPS_SYN_RECEIVED:
1594 so->so_error = ECONNREFUSED;
1597 case TCPS_ESTABLISHED:
1598 if (tcp_insecure_rst == 0 &&
1599 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1600 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1601 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1602 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1603 tcpstat.tcps_badrst++;
1606 case TCPS_FIN_WAIT_1:
1607 case TCPS_FIN_WAIT_2:
1608 case TCPS_CLOSE_WAIT:
1609 so->so_error = ECONNRESET;
1611 tp->t_state = TCPS_CLOSED;
1612 tcpstat.tcps_drops++;
1613 KASSERT(headlocked, ("%s: trimthenstep6: "
1614 "tcp_close: head not locked", __func__));
1620 KASSERT(headlocked, ("%s: trimthenstep6: "
1621 "tcp_close.2: head not locked", __func__));
1625 case TCPS_TIME_WAIT:
1626 KASSERT(tp->t_state != TCPS_TIME_WAIT,
1627 ("%s: timewait", __func__));
1635 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1636 * and it's less than ts_recent, drop it.
1638 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1639 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1641 /* Check to see if ts_recent is over 24 days old. */
1642 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1644 * Invalidate ts_recent. If this segment updates
1645 * ts_recent, the age will be reset later and ts_recent
1646 * will get a valid value. If it does not, setting
1647 * ts_recent to zero will at least satisfy the
1648 * requirement that zero be placed in the timestamp
1649 * echo reply when ts_recent isn't valid. The
1650 * age isn't reset until we get a valid ts_recent
1651 * because we don't want out-of-order segments to be
1652 * dropped when ts_recent is old.
1656 tcpstat.tcps_rcvduppack++;
1657 tcpstat.tcps_rcvdupbyte += tlen;
1658 tcpstat.tcps_pawsdrop++;
1666 * In the SYN-RECEIVED state, validate that the packet belongs to
1667 * this connection before trimming the data to fit the receive
1668 * window. Check the sequence number versus IRS since we know
1669 * the sequence numbers haven't wrapped. This is a partial fix
1670 * for the "LAND" DoS attack.
1672 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1673 rstreason = BANDLIM_RST_OPENPORT;
1677 todrop = tp->rcv_nxt - th->th_seq;
1679 if (thflags & TH_SYN) {
1689 * Following if statement from Stevens, vol. 2, p. 960.
1692 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1694 * Any valid FIN must be to the left of the window.
1695 * At this point the FIN must be a duplicate or out
1696 * of sequence; drop it.
1701 * Send an ACK to resynchronize and drop any data.
1702 * But keep on processing for RST or ACK.
1704 tp->t_flags |= TF_ACKNOW;
1706 tcpstat.tcps_rcvduppack++;
1707 tcpstat.tcps_rcvdupbyte += todrop;
1709 tcpstat.tcps_rcvpartduppack++;
1710 tcpstat.tcps_rcvpartdupbyte += todrop;
1712 drop_hdrlen += todrop; /* drop from the top afterwards */
1713 th->th_seq += todrop;
1715 if (th->th_urp > todrop)
1716 th->th_urp -= todrop;
1724 * If new data are received on a connection after the
1725 * user processes are gone, then RST the other end.
1727 if ((so->so_state & SS_NOFDREF) &&
1728 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1729 KASSERT(headlocked, ("%s: trimthenstep6: tcp_close.3: head "
1730 "not locked", __func__));
1732 tcpstat.tcps_rcvafterclose++;
1733 rstreason = BANDLIM_UNLIMITED;
1738 * If segment ends after window, drop trailing data
1739 * (and PUSH and FIN); if nothing left, just ACK.
1741 todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1743 tcpstat.tcps_rcvpackafterwin++;
1744 if (todrop >= tlen) {
1745 tcpstat.tcps_rcvbyteafterwin += tlen;
1747 * If a new connection request is received
1748 * while in TIME_WAIT, drop the old connection
1749 * and start over if the sequence numbers
1750 * are above the previous ones.
1752 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: timewait",
1754 if (thflags & TH_SYN &&
1755 tp->t_state == TCPS_TIME_WAIT &&
1756 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1757 KASSERT(headlocked, ("%s: trimthenstep6: "
1758 "tcp_close.4: head not locked", __func__));
1760 /* XXX: Shouldn't be possible. */
1764 * If window is closed can only take segments at
1765 * window edge, and have to drop data and PUSH from
1766 * incoming segments. Continue processing, but
1767 * remember to ack. Otherwise, drop segment
1770 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1771 tp->t_flags |= TF_ACKNOW;
1772 tcpstat.tcps_rcvwinprobe++;
1776 tcpstat.tcps_rcvbyteafterwin += todrop;
1779 thflags &= ~(TH_PUSH|TH_FIN);
1783 * If last ACK falls within this segment's sequence numbers,
1784 * record its timestamp.
1786 * 1) That the test incorporates suggestions from the latest
1787 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1788 * 2) That updating only on newer timestamps interferes with
1789 * our earlier PAWS tests, so this check should be solely
1790 * predicated on the sequence space of this segment.
1791 * 3) That we modify the segment boundary check to be
1792 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1793 * instead of RFC1323's
1794 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1795 * This modified check allows us to overcome RFC1323's
1796 * limitations as described in Stevens TCP/IP Illustrated
1797 * Vol. 2 p.869. In such cases, we can still calculate the
1798 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1800 if ((to.to_flags & TOF_TS) != 0 &&
1801 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1802 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1803 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
1804 tp->ts_recent_age = ticks;
1805 tp->ts_recent = to.to_tsval;
1809 * If a SYN is in the window, then this is an
1810 * error and we send an RST and drop the connection.
1812 if (thflags & TH_SYN) {
1813 KASSERT(headlocked, ("%s: tcp_drop: trimthenstep6: "
1814 "head not locked", __func__));
1815 tp = tcp_drop(tp, ECONNRESET);
1816 rstreason = BANDLIM_UNLIMITED;
1821 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1822 * flag is on (half-synchronized state), then queue data for
1823 * later processing; else drop segment and return.
1825 if ((thflags & TH_ACK) == 0) {
1826 if (tp->t_state == TCPS_SYN_RECEIVED ||
1827 (tp->t_flags & TF_NEEDSYN))
1829 else if (tp->t_flags & TF_ACKNOW)
1838 switch (tp->t_state) {
1841 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1842 * ESTABLISHED state and continue processing.
1843 * The ACK was checked above.
1845 case TCPS_SYN_RECEIVED:
1847 tcpstat.tcps_connects++;
1849 /* Do window scaling? */
1850 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1851 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1852 tp->rcv_scale = tp->request_r_scale;
1853 tp->snd_wnd = tiwin;
1857 * SYN-RECEIVED -> ESTABLISHED
1858 * SYN-RECEIVED* -> FIN-WAIT-1
1860 tp->t_starttime = ticks;
1861 if (tp->t_flags & TF_NEEDFIN) {
1862 tp->t_state = TCPS_FIN_WAIT_1;
1863 tp->t_flags &= ~TF_NEEDFIN;
1865 tp->t_state = TCPS_ESTABLISHED;
1866 callout_reset(tp->tt_keep, tcp_keepidle,
1867 tcp_timer_keep, tp);
1870 * If segment contains data or ACK, will call tcp_reass()
1871 * later; if not, do so now to pass queued data to user.
1873 if (tlen == 0 && (thflags & TH_FIN) == 0)
1874 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1876 tp->snd_wl1 = th->th_seq - 1;
1880 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1881 * ACKs. If the ack is in the range
1882 * tp->snd_una < th->th_ack <= tp->snd_max
1883 * then advance tp->snd_una to th->th_ack and drop
1884 * data from the retransmission queue. If this ACK reflects
1885 * more up to date window information we update our window information.
1887 case TCPS_ESTABLISHED:
1888 case TCPS_FIN_WAIT_1:
1889 case TCPS_FIN_WAIT_2:
1890 case TCPS_CLOSE_WAIT:
1893 case TCPS_TIME_WAIT:
1894 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: timewait",
1896 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1897 tcpstat.tcps_rcvacktoomuch++;
1900 if (tp->sack_enable &&
1901 ((to.to_flags & TOF_SACK) ||
1902 !TAILQ_EMPTY(&tp->snd_holes)))
1903 tcp_sack_doack(tp, &to, th->th_ack);
1904 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1905 if (tlen == 0 && tiwin == tp->snd_wnd) {
1906 tcpstat.tcps_rcvdupack++;
1908 * If we have outstanding data (other than
1909 * a window probe), this is a completely
1910 * duplicate ack (ie, window info didn't
1911 * change), the ack is the biggest we've
1912 * seen and we've seen exactly our rexmt
1913 * threshhold of them, assume a packet
1914 * has been dropped and retransmit it.
1915 * Kludge snd_nxt & the congestion
1916 * window so we send only this one
1919 * We know we're losing at the current
1920 * window size so do congestion avoidance
1921 * (set ssthresh to half the current window
1922 * and pull our congestion window back to
1923 * the new ssthresh).
1925 * Dup acks mean that packets have left the
1926 * network (they're now cached at the receiver)
1927 * so bump cwnd by the amount in the receiver
1928 * to keep a constant cwnd packets in the
1931 if (!callout_active(tp->tt_rexmt) ||
1932 th->th_ack != tp->snd_una)
1934 else if (++tp->t_dupacks > tcprexmtthresh ||
1935 ((tcp_do_newreno || tp->sack_enable) &&
1936 IN_FASTRECOVERY(tp))) {
1937 if (tp->sack_enable && IN_FASTRECOVERY(tp)) {
1941 * Compute the amount of data in flight first.
1942 * We can inject new data into the pipe iff
1943 * we have less than 1/2 the original window's
1944 * worth of data in flight.
1946 awnd = (tp->snd_nxt - tp->snd_fack) +
1947 tp->sackhint.sack_bytes_rexmit;
1948 if (awnd < tp->snd_ssthresh) {
1949 tp->snd_cwnd += tp->t_maxseg;
1950 if (tp->snd_cwnd > tp->snd_ssthresh)
1951 tp->snd_cwnd = tp->snd_ssthresh;
1954 tp->snd_cwnd += tp->t_maxseg;
1955 (void) tcp_output(tp);
1957 } else if (tp->t_dupacks == tcprexmtthresh) {
1958 tcp_seq onxt = tp->snd_nxt;
1962 * If we're doing sack, check to
1963 * see if we're already in sack
1964 * recovery. If we're not doing sack,
1965 * check to see if we're in newreno
1968 if (tp->sack_enable) {
1969 if (IN_FASTRECOVERY(tp)) {
1973 } else if (tcp_do_newreno) {
1974 if (SEQ_LEQ(th->th_ack,
1980 win = min(tp->snd_wnd, tp->snd_cwnd) /
1984 tp->snd_ssthresh = win * tp->t_maxseg;
1985 ENTER_FASTRECOVERY(tp);
1986 tp->snd_recover = tp->snd_max;
1987 callout_stop(tp->tt_rexmt);
1989 if (tp->sack_enable) {
1990 tcpstat.tcps_sack_recovery_episode++;
1991 tp->sack_newdata = tp->snd_nxt;
1992 tp->snd_cwnd = tp->t_maxseg;
1993 (void) tcp_output(tp);
1996 tp->snd_nxt = th->th_ack;
1997 tp->snd_cwnd = tp->t_maxseg;
1998 (void) tcp_output(tp);
1999 KASSERT(tp->snd_limited <= 2,
2000 ("%s: tp->snd_limited too big",
2002 tp->snd_cwnd = tp->snd_ssthresh +
2004 (tp->t_dupacks - tp->snd_limited);
2005 if (SEQ_GT(onxt, tp->snd_nxt))
2008 } else if (tcp_do_rfc3042) {
2009 u_long oldcwnd = tp->snd_cwnd;
2010 tcp_seq oldsndmax = tp->snd_max;
2013 KASSERT(tp->t_dupacks == 1 ||
2015 ("%s: dupacks not 1 or 2",
2017 if (tp->t_dupacks == 1)
2018 tp->snd_limited = 0;
2020 (tp->snd_nxt - tp->snd_una) +
2021 (tp->t_dupacks - tp->snd_limited) *
2023 (void) tcp_output(tp);
2024 sent = tp->snd_max - oldsndmax;
2025 if (sent > tp->t_maxseg) {
2026 KASSERT((tp->t_dupacks == 2 &&
2027 tp->snd_limited == 0) ||
2028 (sent == tp->t_maxseg + 1 &&
2029 tp->t_flags & TF_SENTFIN),
2030 ("%s: sent too much",
2032 tp->snd_limited = 2;
2033 } else if (sent > 0)
2035 tp->snd_cwnd = oldcwnd;
2043 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2044 ("%s: th_ack <= snd_una", __func__));
2047 * If the congestion window was inflated to account
2048 * for the other side's cached packets, retract it.
2050 if (tcp_do_newreno || tp->sack_enable) {
2051 if (IN_FASTRECOVERY(tp)) {
2052 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2053 if (tp->sack_enable)
2054 tcp_sack_partialack(tp, th);
2056 tcp_newreno_partial_ack(tp, th);
2059 * Out of fast recovery.
2060 * Window inflation should have left us
2061 * with approximately snd_ssthresh
2063 * But in case we would be inclined to
2064 * send a burst, better to do it via
2065 * the slow start mechanism.
2067 if (SEQ_GT(th->th_ack +
2070 tp->snd_cwnd = tp->snd_max -
2074 tp->snd_cwnd = tp->snd_ssthresh;
2078 if (tp->t_dupacks >= tcprexmtthresh &&
2079 tp->snd_cwnd > tp->snd_ssthresh)
2080 tp->snd_cwnd = tp->snd_ssthresh;
2084 * If we reach this point, ACK is not a duplicate,
2085 * i.e., it ACKs something we sent.
2087 if (tp->t_flags & TF_NEEDSYN) {
2089 * T/TCP: Connection was half-synchronized, and our
2090 * SYN has been ACK'd (so connection is now fully
2091 * synchronized). Go to non-starred state,
2092 * increment snd_una for ACK of SYN, and check if
2093 * we can do window scaling.
2095 tp->t_flags &= ~TF_NEEDSYN;
2097 /* Do window scaling? */
2098 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2099 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2100 tp->rcv_scale = tp->request_r_scale;
2101 /* Send window already scaled. */
2106 KASSERT(headlocked, ("%s: process_ACK: head not locked",
2108 INP_LOCK_ASSERT(tp->t_inpcb);
2110 acked = th->th_ack - tp->snd_una;
2111 tcpstat.tcps_rcvackpack++;
2112 tcpstat.tcps_rcvackbyte += acked;
2115 * If we just performed our first retransmit, and the ACK
2116 * arrives within our recovery window, then it was a mistake
2117 * to do the retransmit in the first place. Recover our
2118 * original cwnd and ssthresh, and proceed to transmit where
2121 if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2122 ++tcpstat.tcps_sndrexmitbad;
2123 tp->snd_cwnd = tp->snd_cwnd_prev;
2124 tp->snd_ssthresh = tp->snd_ssthresh_prev;
2125 tp->snd_recover = tp->snd_recover_prev;
2126 if (tp->t_flags & TF_WASFRECOVERY)
2127 ENTER_FASTRECOVERY(tp);
2128 tp->snd_nxt = tp->snd_max;
2129 tp->t_badrxtwin = 0; /* XXX probably not required */
2133 * If we have a timestamp reply, update smoothed
2134 * round trip time. If no timestamp is present but
2135 * transmit timer is running and timed sequence
2136 * number was acked, update smoothed round trip time.
2137 * Since we now have an rtt measurement, cancel the
2138 * timer backoff (cf., Phil Karn's retransmit alg.).
2139 * Recompute the initial retransmit timer.
2141 * Some boxes send broken timestamp replies
2142 * during the SYN+ACK phase, ignore
2143 * timestamps of 0 or we could calculate a
2144 * huge RTT and blow up the retransmit timer.
2146 if ((to.to_flags & TOF_TS) != 0 &&
2148 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2149 tp->t_rttlow = ticks - to.to_tsecr;
2150 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2151 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2152 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2153 tp->t_rttlow = ticks - tp->t_rtttime;
2154 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2156 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2159 * If all outstanding data is acked, stop retransmit
2160 * timer and remember to restart (more output or persist).
2161 * If there is more data to be acked, restart retransmit
2162 * timer, using current (possibly backed-off) value.
2164 if (th->th_ack == tp->snd_max) {
2165 callout_stop(tp->tt_rexmt);
2167 } else if (!callout_active(tp->tt_persist))
2168 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
2169 tcp_timer_rexmt, tp);
2172 * If no data (only SYN) was ACK'd,
2173 * skip rest of ACK processing.
2179 * When new data is acked, open the congestion window.
2180 * If the window gives us less than ssthresh packets
2181 * in flight, open exponentially (maxseg per packet).
2182 * Otherwise open linearly: maxseg per window
2183 * (maxseg^2 / cwnd per packet).
2185 if ((!tcp_do_newreno && !tp->sack_enable) ||
2186 !IN_FASTRECOVERY(tp)) {
2187 u_int cw = tp->snd_cwnd;
2188 u_int incr = tp->t_maxseg;
2189 if (cw > tp->snd_ssthresh)
2190 incr = incr * incr / cw;
2191 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2193 SOCKBUF_LOCK(&so->so_snd);
2194 if (acked > so->so_snd.sb_cc) {
2195 tp->snd_wnd -= so->so_snd.sb_cc;
2196 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2199 sbdrop_locked(&so->so_snd, acked);
2200 tp->snd_wnd -= acked;
2203 sowwakeup_locked(so);
2204 /* detect una wraparound */
2205 if ((tcp_do_newreno || tp->sack_enable) &&
2206 !IN_FASTRECOVERY(tp) &&
2207 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2208 SEQ_LEQ(th->th_ack, tp->snd_recover))
2209 tp->snd_recover = th->th_ack - 1;
2210 if ((tcp_do_newreno || tp->sack_enable) &&
2211 IN_FASTRECOVERY(tp) &&
2212 SEQ_GEQ(th->th_ack, tp->snd_recover))
2213 EXIT_FASTRECOVERY(tp);
2214 tp->snd_una = th->th_ack;
2215 if (tp->sack_enable) {
2216 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2217 tp->snd_recover = tp->snd_una;
2219 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2220 tp->snd_nxt = tp->snd_una;
2222 switch (tp->t_state) {
2225 * In FIN_WAIT_1 STATE in addition to the processing
2226 * for the ESTABLISHED state if our FIN is now acknowledged
2227 * then enter FIN_WAIT_2.
2229 case TCPS_FIN_WAIT_1:
2230 if (ourfinisacked) {
2232 * If we can't receive any more
2233 * data, then closing user can proceed.
2234 * Starting the timer is contrary to the
2235 * specification, but if we don't get a FIN
2236 * we'll hang forever.
2239 * we should release the tp also, and use a
2242 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2245 soisdisconnected(so);
2246 timeout = (tcp_fast_finwait2_recycle) ?
2247 tcp_finwait2_timeout : tcp_maxidle;
2248 callout_reset(tp->tt_2msl, timeout,
2249 tcp_timer_2msl, tp);
2251 tp->t_state = TCPS_FIN_WAIT_2;
2256 * In CLOSING STATE in addition to the processing for
2257 * the ESTABLISHED state if the ACK acknowledges our FIN
2258 * then enter the TIME-WAIT state, otherwise ignore
2262 if (ourfinisacked) {
2263 KASSERT(headlocked, ("%s: process_ACK: "
2264 "head not locked", __func__));
2266 INP_INFO_WUNLOCK(&tcbinfo);
2274 * In LAST_ACK, we may still be waiting for data to drain
2275 * and/or to be acked, as well as for the ack of our FIN.
2276 * If our FIN is now acknowledged, delete the TCB,
2277 * enter the closed state and return.
2280 if (ourfinisacked) {
2281 KASSERT(headlocked, ("%s: process_ACK: "
2282 "tcp_close: head not locked", __func__));
2289 * In TIME_WAIT state the only thing that should arrive
2290 * is a retransmission of the remote FIN. Acknowledge
2291 * it and restart the finack timer.
2293 case TCPS_TIME_WAIT:
2294 KASSERT(tp->t_state != TCPS_TIME_WAIT,
2295 ("%s: timewait", __func__));
2296 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2297 tcp_timer_2msl, tp);
2303 KASSERT(headlocked, ("%s: step6: head not locked", __func__));
2304 INP_LOCK_ASSERT(tp->t_inpcb);
2307 * Update window information.
2308 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2310 if ((thflags & TH_ACK) &&
2311 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2312 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2313 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2314 /* keep track of pure window updates */
2316 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2317 tcpstat.tcps_rcvwinupd++;
2318 tp->snd_wnd = tiwin;
2319 tp->snd_wl1 = th->th_seq;
2320 tp->snd_wl2 = th->th_ack;
2321 if (tp->snd_wnd > tp->max_sndwnd)
2322 tp->max_sndwnd = tp->snd_wnd;
2327 * Process segments with URG.
2329 if ((thflags & TH_URG) && th->th_urp &&
2330 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2332 * This is a kludge, but if we receive and accept
2333 * random urgent pointers, we'll crash in
2334 * soreceive. It's hard to imagine someone
2335 * actually wanting to send this much urgent data.
2337 SOCKBUF_LOCK(&so->so_rcv);
2338 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2339 th->th_urp = 0; /* XXX */
2340 thflags &= ~TH_URG; /* XXX */
2341 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2342 goto dodata; /* XXX */
2345 * If this segment advances the known urgent pointer,
2346 * then mark the data stream. This should not happen
2347 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2348 * a FIN has been received from the remote side.
2349 * In these states we ignore the URG.
2351 * According to RFC961 (Assigned Protocols),
2352 * the urgent pointer points to the last octet
2353 * of urgent data. We continue, however,
2354 * to consider it to indicate the first octet
2355 * of data past the urgent section as the original
2356 * spec states (in one of two places).
2358 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2359 tp->rcv_up = th->th_seq + th->th_urp;
2360 so->so_oobmark = so->so_rcv.sb_cc +
2361 (tp->rcv_up - tp->rcv_nxt) - 1;
2362 if (so->so_oobmark == 0)
2363 so->so_rcv.sb_state |= SBS_RCVATMARK;
2365 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2367 SOCKBUF_UNLOCK(&so->so_rcv);
2369 * Remove out of band data so doesn't get presented to user.
2370 * This can happen independent of advancing the URG pointer,
2371 * but if two URG's are pending at once, some out-of-band
2372 * data may creep in... ick.
2374 if (th->th_urp <= (u_long)tlen &&
2375 !(so->so_options & SO_OOBINLINE)) {
2376 /* hdr drop is delayed */
2377 tcp_pulloutofband(so, th, m, drop_hdrlen);
2381 * If no out of band data is expected,
2382 * pull receive urgent pointer along
2383 * with the receive window.
2385 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2386 tp->rcv_up = tp->rcv_nxt;
2389 KASSERT(headlocked, ("%s: dodata: head not locked", __func__));
2390 INP_LOCK_ASSERT(tp->t_inpcb);
2393 * Process the segment text, merging it into the TCP sequencing queue,
2394 * and arranging for acknowledgment of receipt if necessary.
2395 * This process logically involves adjusting tp->rcv_wnd as data
2396 * is presented to the user (this happens in tcp_usrreq.c,
2397 * case PRU_RCVD). If a FIN has already been received on this
2398 * connection then we just ignore the text.
2400 if ((tlen || (thflags & TH_FIN)) &&
2401 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2402 tcp_seq save_start = th->th_seq;
2403 tcp_seq save_end = th->th_seq + tlen;
2404 m_adj(m, drop_hdrlen); /* delayed header drop */
2406 * Insert segment which includes th into TCP reassembly queue
2407 * with control block tp. Set thflags to whether reassembly now
2408 * includes a segment with FIN. This handles the common case
2409 * inline (segment is the next to be received on an established
2410 * connection, and the queue is empty), avoiding linkage into
2411 * and removal from the queue and repetition of various
2413 * Set DELACK for segments received in order, but ack
2414 * immediately when segments are out of order (so
2415 * fast retransmit can work).
2417 if (th->th_seq == tp->rcv_nxt &&
2418 LIST_EMPTY(&tp->t_segq) &&
2419 TCPS_HAVEESTABLISHED(tp->t_state)) {
2421 tp->t_flags |= TF_DELACK;
2423 tp->t_flags |= TF_ACKNOW;
2424 tp->rcv_nxt += tlen;
2425 thflags = th->th_flags & TH_FIN;
2426 tcpstat.tcps_rcvpack++;
2427 tcpstat.tcps_rcvbyte += tlen;
2429 SOCKBUF_LOCK(&so->so_rcv);
2430 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2433 sbappendstream_locked(&so->so_rcv, m);
2434 sorwakeup_locked(so);
2436 thflags = tcp_reass(tp, th, &tlen, m);
2437 tp->t_flags |= TF_ACKNOW;
2439 if (tlen > 0 && tp->sack_enable)
2440 tcp_update_sack_list(tp, save_start, save_end);
2443 * Note the amount of data that peer has sent into
2444 * our window, in order to estimate the sender's
2448 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2456 * If FIN is received ACK the FIN and let the user know
2457 * that the connection is closing.
2459 if (thflags & TH_FIN) {
2460 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2463 * If connection is half-synchronized
2464 * (ie NEEDSYN flag on) then delay ACK,
2465 * so it may be piggybacked when SYN is sent.
2466 * Otherwise, since we received a FIN then no
2467 * more input can be expected, send ACK now.
2469 if (tp->t_flags & TF_NEEDSYN)
2470 tp->t_flags |= TF_DELACK;
2472 tp->t_flags |= TF_ACKNOW;
2475 switch (tp->t_state) {
2478 * In SYN_RECEIVED and ESTABLISHED STATES
2479 * enter the CLOSE_WAIT state.
2481 case TCPS_SYN_RECEIVED:
2482 tp->t_starttime = ticks;
2484 case TCPS_ESTABLISHED:
2485 tp->t_state = TCPS_CLOSE_WAIT;
2489 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2490 * enter the CLOSING state.
2492 case TCPS_FIN_WAIT_1:
2493 tp->t_state = TCPS_CLOSING;
2497 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2498 * starting the time-wait timer, turning off the other
2501 case TCPS_FIN_WAIT_2:
2502 KASSERT(headlocked == 1, ("%s: dodata: "
2503 "TCP_FIN_WAIT_2: head not locked", __func__));
2505 INP_INFO_WUNLOCK(&tcbinfo);
2509 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2511 case TCPS_TIME_WAIT:
2512 KASSERT(tp->t_state != TCPS_TIME_WAIT,
2513 ("%s: timewait", __func__));
2514 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2515 tcp_timer_2msl, tp);
2519 INP_INFO_WUNLOCK(&tcbinfo);
2522 if (so->so_options & SO_DEBUG)
2523 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2528 * Return any desired output.
2530 if (needoutput || (tp->t_flags & TF_ACKNOW))
2531 (void) tcp_output(tp);
2534 KASSERT(headlocked == 0, ("%s: check_delack: head locked",
2536 INP_LOCK_ASSERT(tp->t_inpcb);
2537 if (tp->t_flags & TF_DELACK) {
2538 tp->t_flags &= ~TF_DELACK;
2539 callout_reset(tp->tt_delack, tcp_delacktime,
2540 tcp_timer_delack, tp);
2542 INP_UNLOCK(tp->t_inpcb);
2546 KASSERT(headlocked, ("%s: dropafterack: head not locked", __func__));
2548 * Generate an ACK dropping incoming segment if it occupies
2549 * sequence space, where the ACK reflects our state.
2551 * We can now skip the test for the RST flag since all
2552 * paths to this code happen after packets containing
2553 * RST have been dropped.
2555 * In the SYN-RECEIVED state, don't send an ACK unless the
2556 * segment we received passes the SYN-RECEIVED ACK test.
2557 * If it fails send a RST. This breaks the loop in the
2558 * "LAND" DoS attack, and also prevents an ACK storm
2559 * between two listening ports that have been sent forged
2560 * SYN segments, each with the source address of the other.
2562 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2563 (SEQ_GT(tp->snd_una, th->th_ack) ||
2564 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2565 rstreason = BANDLIM_RST_OPENPORT;
2569 if (so->so_options & SO_DEBUG)
2570 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2573 KASSERT(headlocked, ("%s: headlocked should be 1", __func__));
2574 INP_INFO_WUNLOCK(&tcbinfo);
2575 tp->t_flags |= TF_ACKNOW;
2576 (void) tcp_output(tp);
2577 INP_UNLOCK(tp->t_inpcb);
2582 KASSERT(headlocked, ("%s: dropwithreset: head not locked", __func__));
2584 tcp_dropwithreset(m, th, tp, tlen, rstreason);
2587 INP_UNLOCK(tp->t_inpcb);
2589 INP_INFO_WUNLOCK(&tcbinfo);
2594 * Drop space held by incoming segment and return.
2597 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2598 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2602 INP_UNLOCK(tp->t_inpcb);
2604 INP_INFO_WUNLOCK(&tcbinfo);
2611 * Issue RST on TCP segment. The mbuf must still include the original
2615 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2616 int tlen, int rstreason)
2620 struct ip6_hdr *ip6;
2624 * Generate a RST, dropping incoming segment.
2625 * Make ACK acceptable to originator of segment.
2626 * Don't bother to respond if destination was broadcast/multicast.
2628 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2631 if (mtod(m, struct ip *)->ip_v == 6) {
2632 ip6 = mtod(m, struct ip6_hdr *);
2633 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2634 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2636 /* IPv6 anycast check is done at tcp6_input() */
2640 ip = mtod(m, struct ip *);
2641 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2642 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2643 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2644 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2648 /* Perform bandwidth limiting. */
2649 if (badport_bandlim(rstreason) < 0)
2652 /* tcp_respond consumes the mbuf chain. */
2653 if (th->th_flags & TH_ACK) {
2654 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
2655 th->th_ack, TH_RST);
2657 if (th->th_flags & TH_SYN)
2659 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2660 (tcp_seq)0, TH_RST|TH_ACK);
2669 * Parse TCP options and place in tcpopt.
2672 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
2677 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2679 if (opt == TCPOPT_EOL)
2681 if (opt == TCPOPT_NOP)
2687 if (optlen < 2 || optlen > cnt)
2692 if (optlen != TCPOLEN_MAXSEG)
2694 if (!(flags & TO_SYN))
2696 to->to_flags |= TOF_MSS;
2697 bcopy((char *)cp + 2,
2698 (char *)&to->to_mss, sizeof(to->to_mss));
2699 to->to_mss = ntohs(to->to_mss);
2702 if (optlen != TCPOLEN_WINDOW)
2704 if (!(flags & TO_SYN))
2706 to->to_flags |= TOF_SCALE;
2707 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2709 case TCPOPT_TIMESTAMP:
2710 if (optlen != TCPOLEN_TIMESTAMP)
2712 to->to_flags |= TOF_TS;
2713 bcopy((char *)cp + 2,
2714 (char *)&to->to_tsval, sizeof(to->to_tsval));
2715 to->to_tsval = ntohl(to->to_tsval);
2716 bcopy((char *)cp + 6,
2717 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2718 to->to_tsecr = ntohl(to->to_tsecr);
2720 #ifdef TCP_SIGNATURE
2722 * XXX In order to reply to a host which has set the
2723 * TCP_SIGNATURE option in its initial SYN, we have to
2724 * record the fact that the option was observed here
2725 * for the syncache code to perform the correct response.
2727 case TCPOPT_SIGNATURE:
2728 if (optlen != TCPOLEN_SIGNATURE)
2730 to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2733 case TCPOPT_SACK_PERMITTED:
2734 if (optlen != TCPOLEN_SACK_PERMITTED)
2736 if (!(flags & TO_SYN))
2740 to->to_flags |= TOF_SACKPERM;
2743 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2747 to->to_flags |= TOF_SACK;
2748 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2749 to->to_sacks = cp + 2;
2750 tcpstat.tcps_sack_rcv_blocks++;
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.
2765 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
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, (unsigned)(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 INP_LOCK_ASSERT(tp->t_inpcb);
2802 tcpstat.tcps_rttupdated++;
2804 if (tp->t_srtt != 0) {
2806 * srtt is stored as fixed point with 5 bits after the
2807 * binary point (i.e., scaled by 8). The following magic
2808 * is equivalent to the smoothing algorithm in rfc793 with
2809 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2810 * point). Adjust rtt to origin 0.
2812 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2813 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2815 if ((tp->t_srtt += delta) <= 0)
2819 * We accumulate a smoothed rtt variance (actually, a
2820 * smoothed mean difference), then set the retransmit
2821 * timer to smoothed rtt + 4 times the smoothed variance.
2822 * rttvar is stored as fixed point with 4 bits after the
2823 * binary point (scaled by 16). The following is
2824 * equivalent to rfc793 smoothing with an alpha of .75
2825 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2826 * rfc793's wired-in beta.
2830 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2831 if ((tp->t_rttvar += delta) <= 0)
2833 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2834 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2837 * No rtt measurement yet - use the unsmoothed rtt.
2838 * Set the variance to half the rtt (so our first
2839 * retransmit happens at 3*rtt).
2841 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2842 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2843 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2849 * the retransmit should happen at rtt + 4 * rttvar.
2850 * Because of the way we do the smoothing, srtt and rttvar
2851 * will each average +1/2 tick of bias. When we compute
2852 * the retransmit timer, we want 1/2 tick of rounding and
2853 * 1 extra tick because of +-1/2 tick uncertainty in the
2854 * firing of the timer. The bias will give us exactly the
2855 * 1.5 tick we need. But, because the bias is
2856 * statistical, we have to test that we don't drop below
2857 * the minimum feasible timer (which is 2 ticks).
2859 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2860 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2863 * We received an ack for a packet that wasn't retransmitted;
2864 * it is probably safe to discard any error indications we've
2865 * received recently. This isn't quite right, but close enough
2866 * for now (a route might have failed after we sent a segment,
2867 * and the return path might not be symmetrical).
2869 tp->t_softerror = 0;
2873 * Determine a reasonable value for maxseg size.
2874 * If the route is known, check route for mtu.
2875 * If none, use an mss that can be handled on the outgoing
2876 * interface without forcing IP to fragment; if bigger than
2877 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2878 * to utilize large mbufs. If no route is found, route has no mtu,
2879 * or the destination isn't local, use a default, hopefully conservative
2880 * size (usually 512 or the default IP max size, but no more than the mtu
2881 * of the interface), as we can't discover anything about intervening
2882 * gateways or networks. We also initialize the congestion/slow start
2883 * window to be a single segment if the destination isn't local.
2884 * While looking at the routing entry, we also initialize other path-dependent
2885 * parameters from pre-set or cached values in the routing entry.
2887 * Also take into account the space needed for options that we
2888 * send regularly. Make maxseg shorter by that amount to assure
2889 * that we can send maxseg amount of data even when the options
2890 * are present. Store the upper limit of the length of options plus
2894 * In case of T/TCP, we call this routine during implicit connection
2895 * setup as well (offer = -1), to initialize maxseg from the cached
2898 * NOTE that this routine is only called when we process an incoming
2899 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
2902 tcp_mss(struct tcpcb *tp, int offer)
2907 struct inpcb *inp = tp->t_inpcb;
2909 struct hc_metrics_lite metrics;
2910 int origoffer = offer;
2913 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2914 size_t min_protoh = isipv6 ?
2915 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2916 sizeof (struct tcpiphdr);
2918 const size_t min_protoh = sizeof(struct tcpiphdr);
2924 maxmtu = tcp_maxmtu6(&inp->inp_inc, &mtuflags);
2925 tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
2929 maxmtu = tcp_maxmtu(&inp->inp_inc, &mtuflags);
2930 tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2932 so = inp->inp_socket;
2935 * no route to sender, stay with default mss and return
2940 /* what have we got? */
2944 * Offer == 0 means that there was no MSS on the SYN
2945 * segment, in this case we use tcp_mssdflt.
2949 isipv6 ? tcp_v6mssdflt :
2956 * Offer == -1 means that we didn't receive SYN yet.
2962 * Prevent DoS attack with too small MSS. Round up
2963 * to at least minmss.
2965 offer = max(offer, tcp_minmss);
2967 * Sanity check: make sure that maxopd will be large
2968 * enough to allow some data on segments even if the
2969 * all the option space is used (40bytes). Otherwise
2970 * funny things may happen in tcp_output.
2972 offer = max(offer, 64);
2976 * rmx information is now retrieved from tcp_hostcache
2978 tcp_hc_get(&inp->inp_inc, &metrics);
2981 * if there's a discovered mtu int tcp hostcache, use it
2982 * else, use the link mtu.
2984 if (metrics.rmx_mtu)
2985 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
2989 mss = maxmtu - min_protoh;
2990 if (!path_mtu_discovery &&
2991 !in6_localaddr(&inp->in6p_faddr))
2992 mss = min(mss, tcp_v6mssdflt);
2996 mss = maxmtu - min_protoh;
2997 if (!path_mtu_discovery &&
2998 !in_localaddr(inp->inp_faddr))
2999 mss = min(mss, tcp_mssdflt);
3002 mss = min(mss, offer);
3005 * maxopd stores the maximum length of data AND options
3006 * in a segment; maxseg is the amount of data in a normal
3007 * segment. We need to store this value (maxopd) apart
3008 * from maxseg, because now every segment carries options
3009 * and thus we normally have somewhat less data in segments.
3014 * origoffer==-1 indicates, that no segments were received yet.
3015 * In this case we just guess.
3017 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3019 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3020 mss -= TCPOLEN_TSTAMP_APPA;
3023 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3025 mss &= ~(MCLBYTES-1);
3028 mss = mss / MCLBYTES * MCLBYTES;
3033 * If there's a pipesize, change the socket buffer to that size,
3034 * don't change if sb_hiwat is different than default (then it
3035 * has been changed on purpose with setsockopt).
3036 * Make the socket buffers an integral number of mss units;
3037 * if the mss is larger than the socket buffer, decrease the mss.
3039 SOCKBUF_LOCK(&so->so_snd);
3040 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
3041 bufsize = metrics.rmx_sendpipe;
3043 bufsize = so->so_snd.sb_hiwat;
3047 bufsize = roundup(bufsize, mss);
3048 if (bufsize > sb_max)
3050 if (bufsize > so->so_snd.sb_hiwat)
3051 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3053 SOCKBUF_UNLOCK(&so->so_snd);
3056 SOCKBUF_LOCK(&so->so_rcv);
3057 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
3058 bufsize = metrics.rmx_recvpipe;
3060 bufsize = so->so_rcv.sb_hiwat;
3061 if (bufsize > mss) {
3062 bufsize = roundup(bufsize, mss);
3063 if (bufsize > sb_max)
3065 if (bufsize > so->so_rcv.sb_hiwat)
3066 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3068 SOCKBUF_UNLOCK(&so->so_rcv);
3070 * While we're here, check the others too
3072 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
3074 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3075 tcpstat.tcps_usedrtt++;
3076 if (metrics.rmx_rttvar) {
3077 tp->t_rttvar = metrics.rmx_rttvar;
3078 tcpstat.tcps_usedrttvar++;
3080 /* default variation is +- 1 rtt */
3082 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3084 TCPT_RANGESET(tp->t_rxtcur,
3085 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3086 tp->t_rttmin, TCPTV_REXMTMAX);
3088 if (metrics.rmx_ssthresh) {
3090 * There's some sort of gateway or interface
3091 * buffer limit on the path. Use this to set
3092 * the slow start threshhold, but set the
3093 * threshold to no less than 2*mss.
3095 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
3096 tcpstat.tcps_usedssthresh++;
3098 if (metrics.rmx_bandwidth)
3099 tp->snd_bandwidth = metrics.rmx_bandwidth;
3102 * Set the slow-start flight size depending on whether this
3103 * is a local network or not.
3105 * Extend this so we cache the cwnd too and retrieve it here.
3106 * Make cwnd even bigger than RFC3390 suggests but only if we
3107 * have previous experience with the remote host. Be careful
3108 * not make cwnd bigger than remote receive window or our own
3109 * send socket buffer. Maybe put some additional upper bound
3110 * on the retrieved cwnd. Should do incremental updates to
3111 * hostcache when cwnd collapses so next connection doesn't
3112 * overloads the path again.
3114 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
3115 * We currently check only in syncache_socket for that.
3117 #define TCP_METRICS_CWND
3118 #ifdef TCP_METRICS_CWND
3119 if (metrics.rmx_cwnd)
3120 tp->snd_cwnd = max(mss,
3121 min(metrics.rmx_cwnd / 2,
3122 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
3126 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3128 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
3129 (!isipv6 && in_localaddr(inp->inp_faddr)))
3131 else if (in_localaddr(inp->inp_faddr))
3133 tp->snd_cwnd = mss * ss_fltsz_local;
3135 tp->snd_cwnd = mss * ss_fltsz;
3137 /* Check the interface for TSO capabilities. */
3138 if (mtuflags & CSUM_TSO)
3139 tp->t_flags |= TF_TSO;
3143 * Determine the MSS option to send on an outgoing SYN.
3146 tcp_mssopt(struct in_conninfo *inc)
3153 int isipv6 = inc->inc_isipv6 ? 1 : 0;
3156 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3160 mss = tcp_v6mssdflt;
3161 maxmtu = tcp_maxmtu6(inc, NULL);
3162 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3163 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3168 maxmtu = tcp_maxmtu(inc, NULL);
3169 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3170 min_protoh = sizeof(struct tcpiphdr);
3172 if (maxmtu && thcmtu)
3173 mss = min(maxmtu, thcmtu) - min_protoh;
3174 else if (maxmtu || thcmtu)
3175 mss = max(maxmtu, thcmtu) - min_protoh;
3182 * On a partial ack arrives, force the retransmission of the
3183 * next unacknowledged segment. Do not clear tp->t_dupacks.
3184 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3188 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3190 tcp_seq onxt = tp->snd_nxt;
3191 u_long ocwnd = tp->snd_cwnd;
3193 callout_stop(tp->tt_rexmt);
3195 tp->snd_nxt = th->th_ack;
3197 * Set snd_cwnd to one segment beyond acknowledged offset.
3198 * (tp->snd_una has not yet been updated when this function is called.)
3200 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3201 tp->t_flags |= TF_ACKNOW;
3202 (void) tcp_output(tp);
3203 tp->snd_cwnd = ocwnd;
3204 if (SEQ_GT(onxt, tp->snd_nxt))
3207 * Partial window deflation. Relies on fact that tp->snd_una
3210 if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3211 tp->snd_cwnd -= th->th_ack - tp->snd_una;
3214 tp->snd_cwnd += tp->t_maxseg;
3218 * Returns 1 if the TIME_WAIT state was killed and we should start over,
3219 * looking for a pcb in the listen state. Returns 0 otherwise.
3222 tcp_timewait(struct inpcb *inp, struct tcpopt *to, struct tcphdr *th,
3223 struct mbuf *m, int tlen)
3229 int isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
3231 const int isipv6 = 0;
3234 /* tcbinfo lock required for tcp_twclose(), tcp_timer_2msl_reset(). */
3235 INP_INFO_WLOCK_ASSERT(&tcbinfo);
3236 INP_LOCK_ASSERT(inp);
3239 * XXXRW: Time wait state for inpcb has been recycled, but inpcb is
3240 * still present. This is undesirable, but temporarily necessary
3241 * until we work out how to handle inpcb's who's timewait state has
3248 thflags = th->th_flags;
3251 * NOTE: for FIN_WAIT_2 (to be added later),
3252 * must validate sequence number before accepting RST
3256 * If the segment contains RST:
3257 * Drop the segment - see Stevens, vol. 2, p. 964 and
3260 if (thflags & TH_RST)
3264 /* PAWS not needed at the moment */
3266 * RFC 1323 PAWS: If we have a timestamp reply on this segment
3267 * and it's less than ts_recent, drop it.
3269 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
3270 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
3271 if ((thflags & TH_ACK) == 0)
3276 * ts_recent is never updated because we never accept new segments.
3281 * If a new connection request is received
3282 * while in TIME_WAIT, drop the old connection
3283 * and start over if the sequence numbers
3284 * are above the previous ones.
3286 if ((thflags & TH_SYN) && SEQ_GT(th->th_seq, tw->rcv_nxt)) {
3292 * Drop the the segment if it does not contain an ACK.
3294 if ((thflags & TH_ACK) == 0)
3298 * Reset the 2MSL timer if this is a duplicate FIN.
3300 if (thflags & TH_FIN) {
3301 seq = th->th_seq + tlen + (thflags & TH_SYN ? 1 : 0);
3302 if (seq + 1 == tw->rcv_nxt)
3303 tcp_timer_2msl_reset(tw, 1);
3307 * Acknowledge the segment if it has data or is not a duplicate ACK.
3309 if (thflags != TH_ACK || tlen != 0 ||
3310 th->th_seq != tw->rcv_nxt || th->th_ack != tw->snd_nxt)
3311 tcp_twrespond(tw, TH_ACK);
3315 * Generate a RST, dropping incoming segment.
3316 * Make ACK acceptable to originator of segment.
3317 * Don't bother to respond if destination was broadcast/multicast.
3319 if (m->m_flags & (M_BCAST|M_MCAST))
3322 struct ip6_hdr *ip6;
3324 /* IPv6 anycast check is done at tcp6_input() */
3325 ip6 = mtod(m, struct ip6_hdr *);
3326 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3327 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3332 ip = mtod(m, struct ip *);
3333 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3334 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3335 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3336 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3339 if (thflags & TH_ACK) {
3341 mtod(m, void *), th, m, 0, th->th_ack, TH_RST);
3343 seq = th->th_seq + (thflags & TH_SYN ? 1 : 0);
3345 mtod(m, void *), th, m, seq, 0, TH_RST|TH_ACK);