2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 2007-2008,2010
5 * Swinburne University of Technology, Melbourne, Australia.
6 * Copyright (c) 2009-2010 Lawrence Stewart <lstewart@freebsd.org>
7 * Copyright (c) 2010 The FreeBSD Foundation
10 * Portions of this software were developed at the Centre for Advanced Internet
11 * Architectures, Swinburne University, by Lawrence Stewart, James Healy and
12 * David Hayes, made possible in part by a grant from the Cisco University
13 * Research Program Fund at Community Foundation Silicon Valley.
15 * Portions of this software were developed at the Centre for Advanced
16 * Internet Architectures, Swinburne University of Technology, Melbourne,
17 * Australia by David Hayes under sponsorship from the FreeBSD Foundation.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
27 * 4. Neither the name of the University nor the names of its contributors
28 * may be used to endorse or promote products derived from this software
29 * without specific prior written permission.
31 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
49 #include "opt_ipfw.h" /* for ipfw_fwd */
51 #include "opt_inet6.h"
52 #include "opt_ipsec.h"
53 #include "opt_tcpdebug.h"
55 #include <sys/param.h>
56 #include <sys/kernel.h>
57 #include <sys/malloc.h>
59 #include <sys/proc.h> /* for proc0 declaration */
60 #include <sys/protosw.h>
61 #include <sys/signalvar.h>
62 #include <sys/socket.h>
63 #include <sys/socketvar.h>
64 #include <sys/sysctl.h>
65 #include <sys/syslog.h>
66 #include <sys/systm.h>
68 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
73 #include <net/route.h>
76 #define TCPSTATES /* for logging */
78 #include <netinet/cc.h>
79 #include <netinet/in.h>
80 #include <netinet/in_pcb.h>
81 #include <netinet/in_systm.h>
82 #include <netinet/in_var.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
85 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
86 #include <netinet/ip_var.h>
87 #include <netinet/ip_options.h>
88 #include <netinet/ip6.h>
89 #include <netinet/icmp6.h>
90 #include <netinet6/in6_pcb.h>
91 #include <netinet6/ip6_var.h>
92 #include <netinet6/nd6.h>
93 #include <netinet/tcp_fsm.h>
94 #include <netinet/tcp_seq.h>
95 #include <netinet/tcp_timer.h>
96 #include <netinet/tcp_var.h>
97 #include <netinet6/tcp6_var.h>
98 #include <netinet/tcpip.h>
99 #include <netinet/tcp_syncache.h>
101 #include <netinet/tcp_debug.h>
102 #endif /* TCPDEBUG */
105 #include <netipsec/ipsec.h>
106 #include <netipsec/ipsec6.h>
109 #include <machine/in_cksum.h>
111 #include <security/mac/mac_framework.h>
113 const int tcprexmtthresh = 3;
115 VNET_DEFINE(struct tcpstat, tcpstat);
116 SYSCTL_VNET_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
117 &VNET_NAME(tcpstat), tcpstat,
118 "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
120 int tcp_log_in_vain = 0;
121 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
123 "Log all incoming TCP segments to closed ports");
125 VNET_DEFINE(int, blackhole) = 0;
126 #define V_blackhole VNET(blackhole)
127 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
128 &VNET_NAME(blackhole), 0,
129 "Do not send RST on segments to closed ports");
131 VNET_DEFINE(int, tcp_delack_enabled) = 1;
132 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
133 &VNET_NAME(tcp_delack_enabled), 0,
134 "Delay ACK to try and piggyback it onto a data packet");
136 VNET_DEFINE(int, drop_synfin) = 0;
137 #define V_drop_synfin VNET(drop_synfin)
138 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
139 &VNET_NAME(drop_synfin), 0,
140 "Drop TCP packets with SYN+FIN set");
142 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
143 #define V_tcp_do_rfc3042 VNET(tcp_do_rfc3042)
144 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
145 &VNET_NAME(tcp_do_rfc3042), 0,
146 "Enable RFC 3042 (Limited Transmit)");
148 VNET_DEFINE(int, tcp_do_rfc3390) = 1;
149 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
150 &VNET_NAME(tcp_do_rfc3390), 0,
151 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
153 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
154 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_RW,
155 &VNET_NAME(tcp_do_rfc3465), 0,
156 "Enable RFC 3465 (Appropriate Byte Counting)");
158 VNET_DEFINE(int, tcp_abc_l_var) = 2;
159 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_RW,
160 &VNET_NAME(tcp_abc_l_var), 2,
161 "Cap the max cwnd increment during slow-start to this number of segments");
163 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
165 VNET_DEFINE(int, tcp_do_ecn) = 0;
166 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_RW,
167 &VNET_NAME(tcp_do_ecn), 0,
170 VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
171 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_RW,
172 &VNET_NAME(tcp_ecn_maxretries), 0,
173 "Max retries before giving up on ECN");
175 VNET_DEFINE(int, tcp_insecure_rst) = 0;
176 #define V_tcp_insecure_rst VNET(tcp_insecure_rst)
177 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
178 &VNET_NAME(tcp_insecure_rst), 0,
179 "Follow the old (insecure) criteria for accepting RST packets");
181 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
182 #define V_tcp_do_autorcvbuf VNET(tcp_do_autorcvbuf)
183 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
184 &VNET_NAME(tcp_do_autorcvbuf), 0,
185 "Enable automatic receive buffer sizing");
187 VNET_DEFINE(int, tcp_autorcvbuf_inc) = 16*1024;
188 #define V_tcp_autorcvbuf_inc VNET(tcp_autorcvbuf_inc)
189 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
190 &VNET_NAME(tcp_autorcvbuf_inc), 0,
191 "Incrementor step size of automatic receive buffer");
193 VNET_DEFINE(int, tcp_autorcvbuf_max) = 256*1024;
194 #define V_tcp_autorcvbuf_max VNET(tcp_autorcvbuf_max)
195 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
196 &VNET_NAME(tcp_autorcvbuf_max), 0,
197 "Max size of automatic receive buffer");
199 int tcp_read_locking = 1;
200 SYSCTL_INT(_net_inet_tcp, OID_AUTO, read_locking, CTLFLAG_RW,
201 &tcp_read_locking, 0, "Enable read locking strategy");
203 VNET_DEFINE(struct inpcbhead, tcb);
204 #define tcb6 tcb /* for KAME src sync over BSD*'s */
205 VNET_DEFINE(struct inpcbinfo, tcbinfo);
207 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
208 static void tcp_do_segment(struct mbuf *, struct tcphdr *,
209 struct socket *, struct tcpcb *, int, int, uint8_t,
211 static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
212 struct tcpcb *, int, int);
213 static void tcp_pulloutofband(struct socket *,
214 struct tcphdr *, struct mbuf *, int);
215 static void tcp_xmit_timer(struct tcpcb *, int);
216 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
217 static void inline cc_ack_received(struct tcpcb *tp, struct tcphdr *th,
219 static void inline cc_conn_init(struct tcpcb *tp);
220 static void inline cc_post_recovery(struct tcpcb *tp, struct tcphdr *th);
221 static void inline tcp_fields_to_host(struct tcphdr *);
223 static void inline tcp_fields_to_net(struct tcphdr *);
224 static int inline tcp_signature_verify_input(struct mbuf *, int, int,
225 int, struct tcpopt *, struct tcphdr *, u_int);
229 * Kernel module interface for updating tcpstat. The argument is an index
230 * into tcpstat treated as an array of u_long. While this encodes the
231 * general layout of tcpstat into the caller, it doesn't encode its location,
232 * so that future changes to add, for example, per-CPU stats support won't
233 * cause binary compatibility problems for kernel modules.
236 kmod_tcpstat_inc(int statnum)
239 (*((u_long *)&V_tcpstat + statnum))++;
243 * CC wrapper hook functions
246 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t type)
248 INP_WLOCK_ASSERT(tp->t_inpcb);
250 tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
251 if (tp->snd_cwnd == min(tp->snd_cwnd, tp->snd_wnd))
252 tp->ccv->flags |= CCF_CWND_LIMITED;
254 tp->ccv->flags &= ~CCF_CWND_LIMITED;
256 if (type == CC_ACK) {
257 if (tp->snd_cwnd > tp->snd_ssthresh) {
258 tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
259 V_tcp_abc_l_var * tp->t_maxseg);
260 if (tp->t_bytes_acked >= tp->snd_cwnd) {
261 tp->t_bytes_acked -= tp->snd_cwnd;
262 tp->ccv->flags |= CCF_ABC_SENTAWND;
265 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
266 tp->t_bytes_acked = 0;
270 if (CC_ALGO(tp)->ack_received != NULL) {
271 /* XXXLAS: Find a way to live without this */
272 tp->ccv->curack = th->th_ack;
273 CC_ALGO(tp)->ack_received(tp->ccv, type);
278 cc_conn_init(struct tcpcb *tp)
280 struct hc_metrics_lite metrics;
281 struct inpcb *inp = tp->t_inpcb;
284 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
287 INP_WLOCK_ASSERT(tp->t_inpcb);
289 tcp_hc_get(&inp->inp_inc, &metrics);
291 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
293 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
294 TCPSTAT_INC(tcps_usedrtt);
295 if (metrics.rmx_rttvar) {
296 tp->t_rttvar = metrics.rmx_rttvar;
297 TCPSTAT_INC(tcps_usedrttvar);
299 /* default variation is +- 1 rtt */
301 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
303 TCPT_RANGESET(tp->t_rxtcur,
304 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
305 tp->t_rttmin, TCPTV_REXMTMAX);
307 if (metrics.rmx_ssthresh) {
309 * There's some sort of gateway or interface
310 * buffer limit on the path. Use this to set
311 * the slow start threshhold, but set the
312 * threshold to no less than 2*mss.
314 tp->snd_ssthresh = max(2 * tp->t_maxseg, metrics.rmx_ssthresh);
315 TCPSTAT_INC(tcps_usedssthresh);
319 * Set the slow-start flight size depending on whether this
320 * is a local network or not.
322 * Extend this so we cache the cwnd too and retrieve it here.
323 * Make cwnd even bigger than RFC3390 suggests but only if we
324 * have previous experience with the remote host. Be careful
325 * not make cwnd bigger than remote receive window or our own
326 * send socket buffer. Maybe put some additional upper bound
327 * on the retrieved cwnd. Should do incremental updates to
328 * hostcache when cwnd collapses so next connection doesn't
329 * overloads the path again.
331 * XXXAO: Initializing the CWND from the hostcache is broken
332 * and in its current form not RFC conformant. It is disabled
333 * until fixed or removed entirely.
335 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
336 * We currently check only in syncache_socket for that.
338 /* #define TCP_METRICS_CWND */
339 #ifdef TCP_METRICS_CWND
340 if (metrics.rmx_cwnd)
341 tp->snd_cwnd = max(tp->t_maxseg, min(metrics.rmx_cwnd / 2,
342 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
345 if (V_tcp_do_rfc3390)
346 tp->snd_cwnd = min(4 * tp->t_maxseg,
347 max(2 * tp->t_maxseg, 4380));
349 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
350 (!isipv6 && in_localaddr(inp->inp_faddr)))
352 else if (in_localaddr(inp->inp_faddr))
354 tp->snd_cwnd = tp->t_maxseg * V_ss_fltsz_local;
356 tp->snd_cwnd = tp->t_maxseg * V_ss_fltsz;
358 if (CC_ALGO(tp)->conn_init != NULL)
359 CC_ALGO(tp)->conn_init(tp->ccv);
363 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
365 INP_WLOCK_ASSERT(tp->t_inpcb);
369 if (!IN_FASTRECOVERY(tp->t_flags)) {
370 tp->snd_recover = tp->snd_max;
371 if (tp->t_flags & TF_ECN_PERMIT)
372 tp->t_flags |= TF_ECN_SND_CWR;
376 if (!IN_CONGRECOVERY(tp->t_flags)) {
377 TCPSTAT_INC(tcps_ecn_rcwnd);
378 tp->snd_recover = tp->snd_max;
379 if (tp->t_flags & TF_ECN_PERMIT)
380 tp->t_flags |= TF_ECN_SND_CWR;
385 tp->t_bytes_acked = 0;
386 EXIT_RECOVERY(tp->t_flags);
387 tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
388 tp->t_maxseg) * tp->t_maxseg;
389 tp->snd_cwnd = tp->t_maxseg;
392 TCPSTAT_INC(tcps_sndrexmitbad);
393 /* RTO was unnecessary, so reset everything. */
394 tp->snd_cwnd = tp->snd_cwnd_prev;
395 tp->snd_ssthresh = tp->snd_ssthresh_prev;
396 tp->snd_recover = tp->snd_recover_prev;
397 if (tp->t_flags & TF_WASFRECOVERY)
398 ENTER_FASTRECOVERY(tp->t_flags);
399 if (tp->t_flags & TF_WASCRECOVERY)
400 ENTER_CONGRECOVERY(tp->t_flags);
401 tp->snd_nxt = tp->snd_max;
406 if (CC_ALGO(tp)->cong_signal != NULL) {
408 tp->ccv->curack = th->th_ack;
409 CC_ALGO(tp)->cong_signal(tp->ccv, type);
414 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
416 INP_WLOCK_ASSERT(tp->t_inpcb);
418 /* XXXLAS: KASSERT that we're in recovery? */
420 if (CC_ALGO(tp)->post_recovery != NULL) {
421 tp->ccv->curack = th->th_ack;
422 CC_ALGO(tp)->post_recovery(tp->ccv);
424 /* XXXLAS: EXIT_RECOVERY ? */
425 tp->t_bytes_acked = 0;
429 tcp_fields_to_host(struct tcphdr *th)
432 th->th_seq = ntohl(th->th_seq);
433 th->th_ack = ntohl(th->th_ack);
434 th->th_win = ntohs(th->th_win);
435 th->th_urp = ntohs(th->th_urp);
440 tcp_fields_to_net(struct tcphdr *th)
443 th->th_seq = htonl(th->th_seq);
444 th->th_ack = htonl(th->th_ack);
445 th->th_win = htons(th->th_win);
446 th->th_urp = htons(th->th_urp);
450 tcp_signature_verify_input(struct mbuf *m, int off0, int tlen, int optlen,
451 struct tcpopt *to, struct tcphdr *th, u_int tcpbflag)
455 tcp_fields_to_net(th);
456 ret = tcp_signature_verify(m, off0, tlen, optlen, to, th, tcpbflag);
457 tcp_fields_to_host(th);
462 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
464 #define ND6_HINT(tp) \
466 if ((tp) && (tp)->t_inpcb && \
467 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
468 nd6_nud_hint(NULL, NULL, 0); \
475 * Indicate whether this ack should be delayed. We can delay the ack if
476 * - there is no delayed ack timer in progress and
477 * - our last ack wasn't a 0-sized window. We never want to delay
478 * the ack that opens up a 0-sized window and
479 * - delayed acks are enabled or
480 * - this is a half-synchronized T/TCP connection.
482 #define DELAY_ACK(tp) \
483 ((!tcp_timer_active(tp, TT_DELACK) && \
484 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
485 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
488 * TCP input handling is split into multiple parts:
489 * tcp6_input is a thin wrapper around tcp_input for the extended
490 * ip6_protox[] call format in ip6_input
491 * tcp_input handles primary segment validation, inpcb lookup and
492 * SYN processing on listen sockets
493 * tcp_do_segment processes the ACK and text of the segment for
494 * establishing, established and closing connections
498 tcp6_input(struct mbuf **mp, int *offp, int proto)
500 struct mbuf *m = *mp;
501 struct in6_ifaddr *ia6;
503 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
506 * draft-itojun-ipv6-tcp-to-anycast
507 * better place to put this in?
509 ia6 = ip6_getdstifaddr(m);
510 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
513 ifa_free(&ia6->ia_ifa);
514 ip6 = mtod(m, struct ip6_hdr *);
515 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
516 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
526 tcp_input(struct mbuf *m, int off0)
529 struct ip *ip = NULL;
531 struct inpcb *inp = NULL;
532 struct tcpcb *tp = NULL;
533 struct socket *so = NULL;
539 int rstreason = 0; /* For badport_bandlim accounting purposes */
542 uint8_t sig_checked = 0;
544 #ifdef IPFIREWALL_FORWARD
545 struct m_tag *fwd_tag;
548 struct ip6_hdr *ip6 = NULL;
551 const void *ip6 = NULL;
552 const int isipv6 = 0;
554 struct tcpopt to; /* options in this segment */
555 char *s = NULL; /* address and port logging */
557 #define TI_UNLOCKED 1
563 * The size of tcp_saveipgen must be the size of the max ip header,
566 u_char tcp_saveipgen[IP6_HDR_LEN];
567 struct tcphdr tcp_savetcp;
572 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
576 TCPSTAT_INC(tcps_rcvtotal);
580 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
581 ip6 = mtod(m, struct ip6_hdr *);
582 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
583 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
584 TCPSTAT_INC(tcps_rcvbadsum);
587 th = (struct tcphdr *)((caddr_t)ip6 + off0);
590 * Be proactive about unspecified IPv6 address in source.
591 * As we use all-zero to indicate unbounded/unconnected pcb,
592 * unspecified IPv6 address can be used to confuse us.
594 * Note that packets with unspecified IPv6 destination is
595 * already dropped in ip6_input.
597 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
602 th = NULL; /* XXX: Avoid compiler warning. */
606 * Get IP and TCP header together in first mbuf.
607 * Note: IP leaves IP header in first mbuf.
609 if (off0 > sizeof (struct ip)) {
610 ip_stripoptions(m, (struct mbuf *)0);
611 off0 = sizeof(struct ip);
613 if (m->m_len < sizeof (struct tcpiphdr)) {
614 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
616 TCPSTAT_INC(tcps_rcvshort);
620 ip = mtod(m, struct ip *);
621 ipov = (struct ipovly *)ip;
622 th = (struct tcphdr *)((caddr_t)ip + off0);
625 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
626 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
627 th->th_sum = m->m_pkthdr.csum_data;
629 th->th_sum = in_pseudo(ip->ip_src.s_addr,
631 htonl(m->m_pkthdr.csum_data +
634 th->th_sum ^= 0xffff;
636 ipov->ih_len = (u_short)tlen;
637 ipov->ih_len = htons(ipov->ih_len);
641 * Checksum extended TCP header and data.
643 len = sizeof (struct ip) + tlen;
644 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
645 ipov->ih_len = (u_short)tlen;
646 ipov->ih_len = htons(ipov->ih_len);
647 th->th_sum = in_cksum(m, len);
650 TCPSTAT_INC(tcps_rcvbadsum);
653 /* Re-initialization for later version check */
654 ip->ip_v = IPVERSION;
659 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
665 * Check that TCP offset makes sense,
666 * pull out TCP options and adjust length. XXX
668 off = th->th_off << 2;
669 if (off < sizeof (struct tcphdr) || off > tlen) {
670 TCPSTAT_INC(tcps_rcvbadoff);
673 tlen -= off; /* tlen is used instead of ti->ti_len */
674 if (off > sizeof (struct tcphdr)) {
677 IP6_EXTHDR_CHECK(m, off0, off, );
678 ip6 = mtod(m, struct ip6_hdr *);
679 th = (struct tcphdr *)((caddr_t)ip6 + off0);
682 if (m->m_len < sizeof(struct ip) + off) {
683 if ((m = m_pullup(m, sizeof (struct ip) + off))
685 TCPSTAT_INC(tcps_rcvshort);
688 ip = mtod(m, struct ip *);
689 ipov = (struct ipovly *)ip;
690 th = (struct tcphdr *)((caddr_t)ip + off0);
693 optlen = off - sizeof (struct tcphdr);
694 optp = (u_char *)(th + 1);
696 thflags = th->th_flags;
699 * Convert TCP protocol specific fields to host format.
701 tcp_fields_to_host(th);
704 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
706 drop_hdrlen = off0 + off;
709 * Locate pcb for segment, which requires a lock on tcbinfo.
710 * Optimisticaly acquire a global read lock rather than a write lock
711 * unless header flags necessarily imply a state change. There are
712 * two cases where we might discover later we need a write lock
713 * despite the flags: ACKs moving a connection out of the syncache,
714 * and ACKs for a connection in TIMEWAIT.
716 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
717 tcp_read_locking == 0) {
718 INP_INFO_WLOCK(&V_tcbinfo);
719 ti_locked = TI_WLOCKED;
721 INP_INFO_RLOCK(&V_tcbinfo);
722 ti_locked = TI_RLOCKED;
727 if (ti_locked == TI_RLOCKED)
728 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
729 else if (ti_locked == TI_WLOCKED)
730 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
732 panic("%s: findpcb ti_locked %d\n", __func__, ti_locked);
735 #ifdef IPFIREWALL_FORWARD
737 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
739 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
741 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
742 struct sockaddr_in *next_hop;
744 next_hop = (struct sockaddr_in *)(fwd_tag+1);
746 * Transparently forwarded. Pretend to be the destination.
747 * already got one like this?
749 inp = in_pcblookup_hash(&V_tcbinfo,
750 ip->ip_src, th->th_sport,
751 ip->ip_dst, th->th_dport,
752 0, m->m_pkthdr.rcvif);
754 /* It's new. Try to find the ambushing socket. */
755 inp = in_pcblookup_hash(&V_tcbinfo,
756 ip->ip_src, th->th_sport,
759 ntohs(next_hop->sin_port) :
764 /* Remove the tag from the packet. We don't need it anymore. */
765 m_tag_delete(m, fwd_tag);
767 #endif /* IPFIREWALL_FORWARD */
771 inp = in6_pcblookup_hash(&V_tcbinfo,
772 &ip6->ip6_src, th->th_sport,
773 &ip6->ip6_dst, th->th_dport,
778 inp = in_pcblookup_hash(&V_tcbinfo,
779 ip->ip_src, th->th_sport,
780 ip->ip_dst, th->th_dport,
786 * If the INPCB does not exist then all data in the incoming
787 * segment is discarded and an appropriate RST is sent back.
788 * XXX MRT Send RST using which routing table?
792 * Log communication attempts to ports that are not
795 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
796 tcp_log_in_vain == 2) {
797 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
798 log(LOG_INFO, "%s; %s: Connection attempt "
799 "to closed port\n", s, __func__);
802 * When blackholing do not respond with a RST but
803 * completely ignore the segment and drop it.
805 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
809 rstreason = BANDLIM_RST_CLOSEDPORT;
813 if (!(inp->inp_flags & INP_HW_FLOWID)
814 && (m->m_flags & M_FLOWID)
815 && ((inp->inp_socket == NULL)
816 || !(inp->inp_socket->so_options & SO_ACCEPTCONN))) {
817 inp->inp_flags |= INP_HW_FLOWID;
818 inp->inp_flags &= ~INP_SW_FLOWID;
819 inp->inp_flowid = m->m_pkthdr.flowid;
823 if (isipv6 && ipsec6_in_reject(m, inp)) {
824 V_ipsec6stat.in_polvio++;
828 if (ipsec4_in_reject(m, inp) != 0) {
829 V_ipsec4stat.in_polvio++;
835 * Check the minimum TTL for socket.
837 if (inp->inp_ip_minttl != 0) {
839 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
843 if (inp->inp_ip_minttl > ip->ip_ttl)
848 * A previous connection in TIMEWAIT state is supposed to catch stray
849 * or duplicate segments arriving late. If this segment was a
850 * legitimate new connection attempt the old INPCB gets removed and
851 * we can try again to find a listening socket.
853 * At this point, due to earlier optimism, we may hold a read lock on
854 * the inpcbinfo, rather than a write lock. If so, we need to
855 * upgrade, or if that fails, acquire a reference on the inpcb, drop
856 * all locks, acquire a global write lock, and then re-acquire the
857 * inpcb lock. We may at that point discover that another thread has
858 * tried to free the inpcb, in which case we need to loop back and
859 * try to find a new inpcb to deliver to.
862 if (inp->inp_flags & INP_TIMEWAIT) {
863 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
864 ("%s: INP_TIMEWAIT ti_locked %d", __func__, ti_locked));
866 if (ti_locked == TI_RLOCKED) {
867 if (INP_INFO_TRY_UPGRADE(&V_tcbinfo) == 0) {
870 INP_INFO_RUNLOCK(&V_tcbinfo);
871 INP_INFO_WLOCK(&V_tcbinfo);
872 ti_locked = TI_WLOCKED;
874 if (in_pcbrele(inp)) {
879 ti_locked = TI_WLOCKED;
881 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
884 tcp_dooptions(&to, optp, optlen,
885 (thflags & TH_SYN) ? TO_SYN : 0);
886 if (sig_checked == 0) {
888 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
889 rstreason = BANDLIM_RST_CLOSEDPORT;
892 if (!tcp_signature_verify_input(m, off0, tlen, optlen,
893 &to, th, tp->t_flags))
898 if (thflags & TH_SYN)
899 tcp_dooptions(&to, optp, optlen, TO_SYN);
902 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
904 if (tcp_twcheck(inp, &to, th, m, tlen))
906 INP_INFO_WUNLOCK(&V_tcbinfo);
910 * The TCPCB may no longer exist if the connection is winding
911 * down or it is in the CLOSED state. Either way we drop the
912 * segment and send an appropriate response.
915 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
916 rstreason = BANDLIM_RST_CLOSEDPORT;
921 * We've identified a valid inpcb, but it could be that we need an
922 * inpcbinfo write lock and have only a read lock. In this case,
923 * attempt to upgrade/relock using the same strategy as the TIMEWAIT
924 * case above. If we relock, we have to jump back to 'relocked' as
925 * the connection might now be in TIMEWAIT.
927 if (tp->t_state != TCPS_ESTABLISHED ||
928 (thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
929 tcp_read_locking == 0) {
930 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
931 ("%s: upgrade check ti_locked %d", __func__, ti_locked));
933 if (ti_locked == TI_RLOCKED) {
934 if (INP_INFO_TRY_UPGRADE(&V_tcbinfo) == 0) {
937 INP_INFO_RUNLOCK(&V_tcbinfo);
938 INP_INFO_WLOCK(&V_tcbinfo);
939 ti_locked = TI_WLOCKED;
941 if (in_pcbrele(inp)) {
947 ti_locked = TI_WLOCKED;
949 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
953 INP_WLOCK_ASSERT(inp);
954 if (mac_inpcb_check_deliver(inp, m))
957 so = inp->inp_socket;
958 KASSERT(so != NULL, ("%s: so == NULL", __func__));
960 if (so->so_options & SO_DEBUG) {
961 ostate = tp->t_state;
964 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
967 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
972 * When the socket is accepting connections (the INPCB is in LISTEN
973 * state) we look into the SYN cache if this is a new connection
974 * attempt or the completion of a previous one.
976 if (so->so_options & SO_ACCEPTCONN) {
977 struct in_conninfo inc;
979 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
980 "tp not listening", __func__));
982 bzero(&inc, sizeof(inc));
985 inc.inc_flags |= INC_ISIPV6;
986 inc.inc6_faddr = ip6->ip6_src;
987 inc.inc6_laddr = ip6->ip6_dst;
991 inc.inc_faddr = ip->ip_src;
992 inc.inc_laddr = ip->ip_dst;
994 inc.inc_fport = th->th_sport;
995 inc.inc_lport = th->th_dport;
996 inc.inc_fibnum = so->so_fibnum;
999 * Check for an existing connection attempt in syncache if
1000 * the flag is only ACK. A successful lookup creates a new
1001 * socket appended to the listen queue in SYN_RECEIVED state.
1003 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1005 * Parse the TCP options here because
1006 * syncookies need access to the reflected
1009 tcp_dooptions(&to, optp, optlen, 0);
1011 * NB: syncache_expand() doesn't unlock
1012 * inp and tcpinfo locks.
1014 if (!syncache_expand(&inc, &to, th, &so, m)) {
1016 * No syncache entry or ACK was not
1017 * for our SYN/ACK. Send a RST.
1018 * NB: syncache did its own logging
1019 * of the failure cause.
1021 rstreason = BANDLIM_RST_OPENPORT;
1026 * We completed the 3-way handshake
1027 * but could not allocate a socket
1028 * either due to memory shortage,
1029 * listen queue length limits or
1030 * global socket limits. Send RST
1031 * or wait and have the remote end
1032 * retransmit the ACK for another
1035 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1036 log(LOG_DEBUG, "%s; %s: Listen socket: "
1037 "Socket allocation failed due to "
1038 "limits or memory shortage, %s\n",
1040 V_tcp_sc_rst_sock_fail ?
1041 "sending RST" : "try again");
1042 if (V_tcp_sc_rst_sock_fail) {
1043 rstreason = BANDLIM_UNLIMITED;
1049 * Socket is created in state SYN_RECEIVED.
1050 * Unlock the listen socket, lock the newly
1051 * created socket and update the tp variable.
1053 INP_WUNLOCK(inp); /* listen socket */
1054 inp = sotoinpcb(so);
1055 INP_WLOCK(inp); /* new connection */
1056 tp = intotcpcb(inp);
1057 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
1058 ("%s: ", __func__));
1059 #ifdef TCP_SIGNATURE
1060 if (sig_checked == 0) {
1061 tcp_dooptions(&to, optp, optlen,
1062 (thflags & TH_SYN) ? TO_SYN : 0);
1063 if (!tcp_signature_verify_input(m, off0, tlen,
1064 optlen, &to, th, tp->t_flags)) {
1067 * In SYN_SENT state if it receives an
1068 * RST, it is allowed for further
1071 if ((thflags & TH_RST) == 0 ||
1072 (tp->t_state == TCPS_SYN_SENT) == 0)
1080 * Process the segment and the data it
1081 * contains. tcp_do_segment() consumes
1082 * the mbuf chain and unlocks the inpcb.
1084 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
1086 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1090 * Segment flag validation for new connection attempts:
1092 * Our (SYN|ACK) response was rejected.
1093 * Check with syncache and remove entry to prevent
1096 * NB: syncache_chkrst does its own logging of failure
1099 if (thflags & TH_RST) {
1100 syncache_chkrst(&inc, th);
1104 * We can't do anything without SYN.
1106 if ((thflags & TH_SYN) == 0) {
1107 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1108 log(LOG_DEBUG, "%s; %s: Listen socket: "
1109 "SYN is missing, segment ignored\n",
1111 TCPSTAT_INC(tcps_badsyn);
1115 * (SYN|ACK) is bogus on a listen socket.
1117 if (thflags & TH_ACK) {
1118 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1119 log(LOG_DEBUG, "%s; %s: Listen socket: "
1120 "SYN|ACK invalid, segment rejected\n",
1122 syncache_badack(&inc); /* XXX: Not needed! */
1123 TCPSTAT_INC(tcps_badsyn);
1124 rstreason = BANDLIM_RST_OPENPORT;
1128 * If the drop_synfin option is enabled, drop all
1129 * segments with both the SYN and FIN bits set.
1130 * This prevents e.g. nmap from identifying the
1132 * XXX: Poor reasoning. nmap has other methods
1133 * and is constantly refining its stack detection
1135 * XXX: This is a violation of the TCP specification
1136 * and was used by RFC1644.
1138 if ((thflags & TH_FIN) && V_drop_synfin) {
1139 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1140 log(LOG_DEBUG, "%s; %s: Listen socket: "
1141 "SYN|FIN segment ignored (based on "
1142 "sysctl setting)\n", s, __func__);
1143 TCPSTAT_INC(tcps_badsyn);
1147 * Segment's flags are (SYN) or (SYN|FIN).
1149 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1150 * as they do not affect the state of the TCP FSM.
1151 * The data pointed to by TH_URG and th_urp is ignored.
1153 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1154 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1155 KASSERT(thflags & (TH_SYN),
1156 ("%s: Listen socket: TH_SYN not set", __func__));
1159 * If deprecated address is forbidden,
1160 * we do not accept SYN to deprecated interface
1161 * address to prevent any new inbound connection from
1162 * getting established.
1163 * When we do not accept SYN, we send a TCP RST,
1164 * with deprecated source address (instead of dropping
1165 * it). We compromise it as it is much better for peer
1166 * to send a RST, and RST will be the final packet
1169 * If we do not forbid deprecated addresses, we accept
1170 * the SYN packet. RFC2462 does not suggest dropping
1172 * If we decipher RFC2462 5.5.4, it says like this:
1173 * 1. use of deprecated addr with existing
1174 * communication is okay - "SHOULD continue to be
1176 * 2. use of it with new communication:
1177 * (2a) "SHOULD NOT be used if alternate address
1178 * with sufficient scope is available"
1179 * (2b) nothing mentioned otherwise.
1180 * Here we fall into (2b) case as we have no choice in
1181 * our source address selection - we must obey the peer.
1183 * The wording in RFC2462 is confusing, and there are
1184 * multiple description text for deprecated address
1185 * handling - worse, they are not exactly the same.
1186 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1188 if (isipv6 && !V_ip6_use_deprecated) {
1189 struct in6_ifaddr *ia6;
1191 ia6 = ip6_getdstifaddr(m);
1193 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1194 ifa_free(&ia6->ia_ifa);
1195 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1196 log(LOG_DEBUG, "%s; %s: Listen socket: "
1197 "Connection attempt to deprecated "
1198 "IPv6 address rejected\n",
1200 rstreason = BANDLIM_RST_OPENPORT;
1203 ifa_free(&ia6->ia_ifa);
1207 * Basic sanity checks on incoming SYN requests:
1208 * Don't respond if the destination is a link layer
1209 * broadcast according to RFC1122 4.2.3.10, p. 104.
1210 * If it is from this socket it must be forged.
1211 * Don't respond if the source or destination is a
1212 * global or subnet broad- or multicast address.
1213 * Note that it is quite possible to receive unicast
1214 * link-layer packets with a broadcast IP address. Use
1215 * in_broadcast() to find them.
1217 if (m->m_flags & (M_BCAST|M_MCAST)) {
1218 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1219 log(LOG_DEBUG, "%s; %s: Listen socket: "
1220 "Connection attempt from broad- or multicast "
1221 "link layer address ignored\n", s, __func__);
1226 if (th->th_dport == th->th_sport &&
1227 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1228 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1229 log(LOG_DEBUG, "%s; %s: Listen socket: "
1230 "Connection attempt to/from self "
1231 "ignored\n", s, __func__);
1234 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1235 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1236 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1237 log(LOG_DEBUG, "%s; %s: Listen socket: "
1238 "Connection attempt from/to multicast "
1239 "address ignored\n", s, __func__);
1244 if (th->th_dport == th->th_sport &&
1245 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1246 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1247 log(LOG_DEBUG, "%s; %s: Listen socket: "
1248 "Connection attempt from/to self "
1249 "ignored\n", s, __func__);
1252 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1253 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1254 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1255 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1256 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1257 log(LOG_DEBUG, "%s; %s: Listen socket: "
1258 "Connection attempt from/to broad- "
1259 "or multicast address ignored\n",
1265 * SYN appears to be valid. Create compressed TCP state
1269 if (so->so_options & SO_DEBUG)
1270 tcp_trace(TA_INPUT, ostate, tp,
1271 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1273 tcp_dooptions(&to, optp, optlen, TO_SYN);
1274 syncache_add(&inc, &to, th, inp, &so, m);
1276 * Entry added to syncache and mbuf consumed.
1277 * Everything already unlocked by syncache_add().
1279 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1283 #ifdef TCP_SIGNATURE
1284 if (sig_checked == 0) {
1285 tcp_dooptions(&to, optp, optlen,
1286 (thflags & TH_SYN) ? TO_SYN : 0);
1287 if (!tcp_signature_verify_input(m, off0, tlen, optlen, &to,
1291 * In SYN_SENT state if it receives an RST, it is
1292 * allowed for further processing.
1294 if ((thflags & TH_RST) == 0 ||
1295 (tp->t_state == TCPS_SYN_SENT) == 0)
1303 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1304 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1305 * the inpcb, and unlocks pcbinfo.
1307 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
1308 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1312 if (ti_locked == TI_RLOCKED)
1313 INP_INFO_RUNLOCK(&V_tcbinfo);
1314 else if (ti_locked == TI_WLOCKED)
1315 INP_INFO_WUNLOCK(&V_tcbinfo);
1317 panic("%s: dropwithreset ti_locked %d", __func__, ti_locked);
1318 ti_locked = TI_UNLOCKED;
1321 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1324 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1325 m = NULL; /* mbuf chain got consumed. */
1329 if (ti_locked == TI_RLOCKED)
1330 INP_INFO_RUNLOCK(&V_tcbinfo);
1331 else if (ti_locked == TI_WLOCKED)
1332 INP_INFO_WUNLOCK(&V_tcbinfo);
1334 panic("%s: dropunlock ti_locked %d", __func__, ti_locked);
1335 ti_locked = TI_UNLOCKED;
1341 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1349 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1350 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1353 int thflags, acked, ourfinisacked, needoutput = 0;
1354 int rstreason, todrop, win;
1360 * The size of tcp_saveipgen must be the size of the max ip header,
1363 u_char tcp_saveipgen[IP6_HDR_LEN];
1364 struct tcphdr tcp_savetcp;
1367 thflags = th->th_flags;
1368 tp->sackhint.last_sack_ack = 0;
1371 * If this is either a state-changing packet or current state isn't
1372 * established, we require a write lock on tcbinfo. Otherwise, we
1373 * allow either a read lock or a write lock, as we may have acquired
1374 * a write lock due to a race.
1376 * Require a global write lock for SYN/FIN/RST segments or
1377 * non-established connections; otherwise accept either a read or
1378 * write lock, as we may have conservatively acquired a write lock in
1379 * certain cases in tcp_input() (is this still true?). Currently we
1380 * will never enter with no lock, so we try to drop it quickly in the
1381 * common pure ack/pure data cases.
1383 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1384 tp->t_state != TCPS_ESTABLISHED) {
1385 KASSERT(ti_locked == TI_WLOCKED, ("%s ti_locked %d for "
1386 "SYN/FIN/RST/!EST", __func__, ti_locked));
1387 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1390 if (ti_locked == TI_RLOCKED)
1391 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1392 else if (ti_locked == TI_WLOCKED)
1393 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1395 panic("%s: ti_locked %d for EST", __func__,
1399 INP_WLOCK_ASSERT(tp->t_inpcb);
1400 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1402 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1406 * Segment received on connection.
1407 * Reset idle time and keep-alive timer.
1408 * XXX: This should be done after segment
1409 * validation to ignore broken/spoofed segs.
1411 tp->t_rcvtime = ticks;
1412 if (TCPS_HAVEESTABLISHED(tp->t_state))
1413 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1416 * Unscale the window into a 32-bit value.
1417 * For the SYN_SENT state the scale is zero.
1419 tiwin = th->th_win << tp->snd_scale;
1422 * TCP ECN processing.
1424 if (tp->t_flags & TF_ECN_PERMIT) {
1425 if (thflags & TH_CWR)
1426 tp->t_flags &= ~TF_ECN_SND_ECE;
1427 switch (iptos & IPTOS_ECN_MASK) {
1429 tp->t_flags |= TF_ECN_SND_ECE;
1430 TCPSTAT_INC(tcps_ecn_ce);
1432 case IPTOS_ECN_ECT0:
1433 TCPSTAT_INC(tcps_ecn_ect0);
1435 case IPTOS_ECN_ECT1:
1436 TCPSTAT_INC(tcps_ecn_ect1);
1439 /* Congestion experienced. */
1440 if (thflags & TH_ECE) {
1441 cc_cong_signal(tp, th, CC_ECN);
1446 * Parse options on any incoming segment.
1448 tcp_dooptions(&to, (u_char *)(th + 1),
1449 (th->th_off << 2) - sizeof(struct tcphdr),
1450 (thflags & TH_SYN) ? TO_SYN : 0);
1453 * If echoed timestamp is later than the current time,
1454 * fall back to non RFC1323 RTT calculation. Normalize
1455 * timestamp if syncookies were used when this connection
1458 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1459 to.to_tsecr -= tp->ts_offset;
1460 if (TSTMP_GT(to.to_tsecr, ticks))
1465 * Process options only when we get SYN/ACK back. The SYN case
1466 * for incoming connections is handled in tcp_syncache.
1467 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1468 * or <SYN,ACK>) segment itself is never scaled.
1469 * XXX this is traditional behavior, may need to be cleaned up.
1471 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1472 if ((to.to_flags & TOF_SCALE) &&
1473 (tp->t_flags & TF_REQ_SCALE)) {
1474 tp->t_flags |= TF_RCVD_SCALE;
1475 tp->snd_scale = to.to_wscale;
1478 * Initial send window. It will be updated with
1479 * the next incoming segment to the scaled value.
1481 tp->snd_wnd = th->th_win;
1482 if (to.to_flags & TOF_TS) {
1483 tp->t_flags |= TF_RCVD_TSTMP;
1484 tp->ts_recent = to.to_tsval;
1485 tp->ts_recent_age = ticks;
1487 if (to.to_flags & TOF_MSS)
1488 tcp_mss(tp, to.to_mss);
1489 if ((tp->t_flags & TF_SACK_PERMIT) &&
1490 (to.to_flags & TOF_SACKPERM) == 0)
1491 tp->t_flags &= ~TF_SACK_PERMIT;
1495 * Header prediction: check for the two common cases
1496 * of a uni-directional data xfer. If the packet has
1497 * no control flags, is in-sequence, the window didn't
1498 * change and we're not retransmitting, it's a
1499 * candidate. If the length is zero and the ack moved
1500 * forward, we're the sender side of the xfer. Just
1501 * free the data acked & wake any higher level process
1502 * that was blocked waiting for space. If the length
1503 * is non-zero and the ack didn't move, we're the
1504 * receiver side. If we're getting packets in-order
1505 * (the reassembly queue is empty), add the data to
1506 * the socket buffer and note that we need a delayed ack.
1507 * Make sure that the hidden state-flags are also off.
1508 * Since we check for TCPS_ESTABLISHED first, it can only
1511 if (tp->t_state == TCPS_ESTABLISHED &&
1512 th->th_seq == tp->rcv_nxt &&
1513 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1514 tp->snd_nxt == tp->snd_max &&
1515 tiwin && tiwin == tp->snd_wnd &&
1516 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1517 LIST_EMPTY(&tp->t_segq) &&
1518 ((to.to_flags & TOF_TS) == 0 ||
1519 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1522 * If last ACK falls within this segment's sequence numbers,
1523 * record the timestamp.
1524 * NOTE that the test is modified according to the latest
1525 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1527 if ((to.to_flags & TOF_TS) != 0 &&
1528 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1529 tp->ts_recent_age = ticks;
1530 tp->ts_recent = to.to_tsval;
1534 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1535 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1536 !IN_RECOVERY(tp->t_flags) &&
1537 (to.to_flags & TOF_SACK) == 0 &&
1538 TAILQ_EMPTY(&tp->snd_holes)) {
1540 * This is a pure ack for outstanding data.
1542 if (ti_locked == TI_RLOCKED)
1543 INP_INFO_RUNLOCK(&V_tcbinfo);
1544 else if (ti_locked == TI_WLOCKED)
1545 INP_INFO_WUNLOCK(&V_tcbinfo);
1547 panic("%s: ti_locked %d on pure ACK",
1548 __func__, ti_locked);
1549 ti_locked = TI_UNLOCKED;
1551 TCPSTAT_INC(tcps_predack);
1554 * "bad retransmit" recovery.
1556 if (tp->t_rxtshift == 1 &&
1557 (int)(ticks - tp->t_badrxtwin) < 0) {
1558 cc_cong_signal(tp, th, CC_RTO_ERR);
1562 * Recalculate the transmit timer / rtt.
1564 * Some boxes send broken timestamp replies
1565 * during the SYN+ACK phase, ignore
1566 * timestamps of 0 or we could calculate a
1567 * huge RTT and blow up the retransmit timer.
1569 if ((to.to_flags & TOF_TS) != 0 &&
1571 if (!tp->t_rttlow ||
1572 tp->t_rttlow > ticks - to.to_tsecr)
1573 tp->t_rttlow = ticks - to.to_tsecr;
1575 ticks - to.to_tsecr + 1);
1576 } else if (tp->t_rtttime &&
1577 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1578 if (!tp->t_rttlow ||
1579 tp->t_rttlow > ticks - tp->t_rtttime)
1580 tp->t_rttlow = ticks - tp->t_rtttime;
1582 ticks - tp->t_rtttime);
1584 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1585 acked = BYTES_THIS_ACK(tp, th);
1586 TCPSTAT_INC(tcps_rcvackpack);
1587 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1588 sbdrop(&so->so_snd, acked);
1589 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1590 SEQ_LEQ(th->th_ack, tp->snd_recover))
1591 tp->snd_recover = th->th_ack - 1;
1594 * Let the congestion control algorithm update
1595 * congestion control related information. This
1596 * typically means increasing the congestion
1599 cc_ack_received(tp, th, CC_ACK);
1601 tp->snd_una = th->th_ack;
1603 * Pull snd_wl2 up to prevent seq wrap relative
1606 tp->snd_wl2 = th->th_ack;
1609 ND6_HINT(tp); /* Some progress has been made. */
1612 * If all outstanding data are acked, stop
1613 * retransmit timer, otherwise restart timer
1614 * using current (possibly backed-off) value.
1615 * If process is waiting for space,
1616 * wakeup/selwakeup/signal. If data
1617 * are ready to send, let tcp_output
1618 * decide between more output or persist.
1621 if (so->so_options & SO_DEBUG)
1622 tcp_trace(TA_INPUT, ostate, tp,
1623 (void *)tcp_saveipgen,
1626 if (tp->snd_una == tp->snd_max)
1627 tcp_timer_activate(tp, TT_REXMT, 0);
1628 else if (!tcp_timer_active(tp, TT_PERSIST))
1629 tcp_timer_activate(tp, TT_REXMT,
1632 if (so->so_snd.sb_cc)
1633 (void) tcp_output(tp);
1636 } else if (th->th_ack == tp->snd_una &&
1637 tlen <= sbspace(&so->so_rcv)) {
1638 int newsize = 0; /* automatic sockbuf scaling */
1641 * This is a pure, in-sequence data packet with
1642 * nothing on the reassembly queue and we have enough
1643 * buffer space to take it.
1645 if (ti_locked == TI_RLOCKED)
1646 INP_INFO_RUNLOCK(&V_tcbinfo);
1647 else if (ti_locked == TI_WLOCKED)
1648 INP_INFO_WUNLOCK(&V_tcbinfo);
1650 panic("%s: ti_locked %d on pure data "
1651 "segment", __func__, ti_locked);
1652 ti_locked = TI_UNLOCKED;
1654 /* Clean receiver SACK report if present */
1655 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1656 tcp_clean_sackreport(tp);
1657 TCPSTAT_INC(tcps_preddat);
1658 tp->rcv_nxt += tlen;
1660 * Pull snd_wl1 up to prevent seq wrap relative to
1663 tp->snd_wl1 = th->th_seq;
1665 * Pull rcv_up up to prevent seq wrap relative to
1668 tp->rcv_up = tp->rcv_nxt;
1669 TCPSTAT_INC(tcps_rcvpack);
1670 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1671 ND6_HINT(tp); /* Some progress has been made */
1673 if (so->so_options & SO_DEBUG)
1674 tcp_trace(TA_INPUT, ostate, tp,
1675 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1678 * Automatic sizing of receive socket buffer. Often the send
1679 * buffer size is not optimally adjusted to the actual network
1680 * conditions at hand (delay bandwidth product). Setting the
1681 * buffer size too small limits throughput on links with high
1682 * bandwidth and high delay (eg. trans-continental/oceanic links).
1684 * On the receive side the socket buffer memory is only rarely
1685 * used to any significant extent. This allows us to be much
1686 * more aggressive in scaling the receive socket buffer. For
1687 * the case that the buffer space is actually used to a large
1688 * extent and we run out of kernel memory we can simply drop
1689 * the new segments; TCP on the sender will just retransmit it
1690 * later. Setting the buffer size too big may only consume too
1691 * much kernel memory if the application doesn't read() from
1692 * the socket or packet loss or reordering makes use of the
1695 * The criteria to step up the receive buffer one notch are:
1696 * 1. the number of bytes received during the time it takes
1697 * one timestamp to be reflected back to us (the RTT);
1698 * 2. received bytes per RTT is within seven eighth of the
1699 * current socket buffer size;
1700 * 3. receive buffer size has not hit maximal automatic size;
1702 * This algorithm does one step per RTT at most and only if
1703 * we receive a bulk stream w/o packet losses or reorderings.
1704 * Shrinking the buffer during idle times is not necessary as
1705 * it doesn't consume any memory when idle.
1707 * TODO: Only step up if the application is actually serving
1708 * the buffer to better manage the socket buffer resources.
1710 if (V_tcp_do_autorcvbuf &&
1712 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1713 if (TSTMP_GT(to.to_tsecr, tp->rfbuf_ts) &&
1714 to.to_tsecr - tp->rfbuf_ts < hz) {
1716 (so->so_rcv.sb_hiwat / 8 * 7) &&
1717 so->so_rcv.sb_hiwat <
1718 V_tcp_autorcvbuf_max) {
1720 min(so->so_rcv.sb_hiwat +
1721 V_tcp_autorcvbuf_inc,
1722 V_tcp_autorcvbuf_max);
1724 /* Start over with next RTT. */
1728 tp->rfbuf_cnt += tlen; /* add up */
1731 /* Add data to socket buffer. */
1732 SOCKBUF_LOCK(&so->so_rcv);
1733 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1737 * Set new socket buffer size.
1738 * Give up when limit is reached.
1741 if (!sbreserve_locked(&so->so_rcv,
1743 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1744 m_adj(m, drop_hdrlen); /* delayed header drop */
1745 sbappendstream_locked(&so->so_rcv, m);
1747 /* NB: sorwakeup_locked() does an implicit unlock. */
1748 sorwakeup_locked(so);
1749 if (DELAY_ACK(tp)) {
1750 tp->t_flags |= TF_DELACK;
1752 tp->t_flags |= TF_ACKNOW;
1760 * Calculate amount of space in receive window,
1761 * and then do TCP input processing.
1762 * Receive window is amount of space in rcv queue,
1763 * but not less than advertised window.
1765 win = sbspace(&so->so_rcv);
1768 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1770 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1774 switch (tp->t_state) {
1777 * If the state is SYN_RECEIVED:
1778 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1780 case TCPS_SYN_RECEIVED:
1781 if ((thflags & TH_ACK) &&
1782 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1783 SEQ_GT(th->th_ack, tp->snd_max))) {
1784 rstreason = BANDLIM_RST_OPENPORT;
1790 * If the state is SYN_SENT:
1791 * if seg contains an ACK, but not for our SYN, drop the input.
1792 * if seg contains a RST, then drop the connection.
1793 * if seg does not contain SYN, then drop it.
1794 * Otherwise this is an acceptable SYN segment
1795 * initialize tp->rcv_nxt and tp->irs
1796 * if seg contains ack then advance tp->snd_una
1797 * if seg contains an ECE and ECN support is enabled, the stream
1799 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1800 * arrange for segment to be acked (eventually)
1801 * continue processing rest of data/controls, beginning with URG
1804 if ((thflags & TH_ACK) &&
1805 (SEQ_LEQ(th->th_ack, tp->iss) ||
1806 SEQ_GT(th->th_ack, tp->snd_max))) {
1807 rstreason = BANDLIM_UNLIMITED;
1810 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
1811 tp = tcp_drop(tp, ECONNREFUSED);
1812 if (thflags & TH_RST)
1814 if (!(thflags & TH_SYN))
1817 tp->irs = th->th_seq;
1819 if (thflags & TH_ACK) {
1820 TCPSTAT_INC(tcps_connects);
1823 mac_socketpeer_set_from_mbuf(m, so);
1825 /* Do window scaling on this connection? */
1826 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1827 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1828 tp->rcv_scale = tp->request_r_scale;
1830 tp->rcv_adv += imin(tp->rcv_wnd,
1831 TCP_MAXWIN << tp->rcv_scale);
1832 tp->snd_una++; /* SYN is acked */
1834 * If there's data, delay ACK; if there's also a FIN
1835 * ACKNOW will be turned on later.
1837 if (DELAY_ACK(tp) && tlen != 0)
1838 tcp_timer_activate(tp, TT_DELACK,
1841 tp->t_flags |= TF_ACKNOW;
1843 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
1844 tp->t_flags |= TF_ECN_PERMIT;
1845 TCPSTAT_INC(tcps_ecn_shs);
1849 * Received <SYN,ACK> in SYN_SENT[*] state.
1851 * SYN_SENT --> ESTABLISHED
1852 * SYN_SENT* --> FIN_WAIT_1
1854 tp->t_starttime = ticks;
1855 if (tp->t_flags & TF_NEEDFIN) {
1856 tp->t_state = TCPS_FIN_WAIT_1;
1857 tp->t_flags &= ~TF_NEEDFIN;
1860 tp->t_state = TCPS_ESTABLISHED;
1862 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1866 * Received initial SYN in SYN-SENT[*] state =>
1867 * simultaneous open. If segment contains CC option
1868 * and there is a cached CC, apply TAO test.
1869 * If it succeeds, connection is * half-synchronized.
1870 * Otherwise, do 3-way handshake:
1871 * SYN-SENT -> SYN-RECEIVED
1872 * SYN-SENT* -> SYN-RECEIVED*
1873 * If there was no CC option, clear cached CC value.
1875 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1876 tcp_timer_activate(tp, TT_REXMT, 0);
1877 tp->t_state = TCPS_SYN_RECEIVED;
1880 KASSERT(ti_locked == TI_WLOCKED, ("%s: trimthenstep6: "
1881 "ti_locked %d", __func__, ti_locked));
1882 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1883 INP_WLOCK_ASSERT(tp->t_inpcb);
1886 * Advance th->th_seq to correspond to first data byte.
1887 * If data, trim to stay within window,
1888 * dropping FIN if necessary.
1891 if (tlen > tp->rcv_wnd) {
1892 todrop = tlen - tp->rcv_wnd;
1896 TCPSTAT_INC(tcps_rcvpackafterwin);
1897 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1899 tp->snd_wl1 = th->th_seq - 1;
1900 tp->rcv_up = th->th_seq;
1902 * Client side of transaction: already sent SYN and data.
1903 * If the remote host used T/TCP to validate the SYN,
1904 * our data will be ACK'd; if so, enter normal data segment
1905 * processing in the middle of step 5, ack processing.
1906 * Otherwise, goto step 6.
1908 if (thflags & TH_ACK)
1914 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1915 * do normal processing.
1917 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1921 break; /* continue normal processing */
1925 * States other than LISTEN or SYN_SENT.
1926 * First check the RST flag and sequence number since reset segments
1927 * are exempt from the timestamp and connection count tests. This
1928 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1929 * below which allowed reset segments in half the sequence space
1930 * to fall though and be processed (which gives forged reset
1931 * segments with a random sequence number a 50 percent chance of
1932 * killing a connection).
1933 * Then check timestamp, if present.
1934 * Then check the connection count, if present.
1935 * Then check that at least some bytes of segment are within
1936 * receive window. If segment begins before rcv_nxt,
1937 * drop leading data (and SYN); if nothing left, just ack.
1940 * If the RST bit is set, check the sequence number to see
1941 * if this is a valid reset segment.
1943 * In all states except SYN-SENT, all reset (RST) segments
1944 * are validated by checking their SEQ-fields. A reset is
1945 * valid if its sequence number is in the window.
1946 * Note: this does not take into account delayed ACKs, so
1947 * we should test against last_ack_sent instead of rcv_nxt.
1948 * The sequence number in the reset segment is normally an
1949 * echo of our outgoing acknowlegement numbers, but some hosts
1950 * send a reset with the sequence number at the rightmost edge
1951 * of our receive window, and we have to handle this case.
1952 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1953 * that brute force RST attacks are possible. To combat this,
1954 * we use a much stricter check while in the ESTABLISHED state,
1955 * only accepting RSTs where the sequence number is equal to
1956 * last_ack_sent. In all other states (the states in which a
1957 * RST is more likely), the more permissive check is used.
1958 * If we have multiple segments in flight, the initial reset
1959 * segment sequence numbers will be to the left of last_ack_sent,
1960 * but they will eventually catch up.
1961 * In any case, it never made sense to trim reset segments to
1962 * fit the receive window since RFC 1122 says:
1963 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1965 * A TCP SHOULD allow a received RST segment to include data.
1968 * It has been suggested that a RST segment could contain
1969 * ASCII text that encoded and explained the cause of the
1970 * RST. No standard has yet been established for such
1973 * If the reset segment passes the sequence number test examine
1975 * SYN_RECEIVED STATE:
1976 * If passive open, return to LISTEN state.
1977 * If active open, inform user that connection was refused.
1978 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1979 * Inform user that connection was reset, and close tcb.
1980 * CLOSING, LAST_ACK STATES:
1983 * Drop the segment - see Stevens, vol. 2, p. 964 and
1986 if (thflags & TH_RST) {
1987 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1988 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1989 switch (tp->t_state) {
1991 case TCPS_SYN_RECEIVED:
1992 so->so_error = ECONNREFUSED;
1995 case TCPS_ESTABLISHED:
1996 if (V_tcp_insecure_rst == 0 &&
1997 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1998 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1999 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
2000 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
2001 TCPSTAT_INC(tcps_badrst);
2005 case TCPS_FIN_WAIT_1:
2006 case TCPS_FIN_WAIT_2:
2007 case TCPS_CLOSE_WAIT:
2008 so->so_error = ECONNRESET;
2010 KASSERT(ti_locked == TI_WLOCKED,
2011 ("tcp_do_segment: TH_RST 1 ti_locked %d",
2013 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2015 tp->t_state = TCPS_CLOSED;
2016 TCPSTAT_INC(tcps_drops);
2022 KASSERT(ti_locked == TI_WLOCKED,
2023 ("tcp_do_segment: TH_RST 2 ti_locked %d",
2025 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2035 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2036 * and it's less than ts_recent, drop it.
2038 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2039 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2041 /* Check to see if ts_recent is over 24 days old. */
2042 if (ticks - tp->ts_recent_age > TCP_PAWS_IDLE) {
2044 * Invalidate ts_recent. If this segment updates
2045 * ts_recent, the age will be reset later and ts_recent
2046 * will get a valid value. If it does not, setting
2047 * ts_recent to zero will at least satisfy the
2048 * requirement that zero be placed in the timestamp
2049 * echo reply when ts_recent isn't valid. The
2050 * age isn't reset until we get a valid ts_recent
2051 * because we don't want out-of-order segments to be
2052 * dropped when ts_recent is old.
2056 TCPSTAT_INC(tcps_rcvduppack);
2057 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
2058 TCPSTAT_INC(tcps_pawsdrop);
2066 * In the SYN-RECEIVED state, validate that the packet belongs to
2067 * this connection before trimming the data to fit the receive
2068 * window. Check the sequence number versus IRS since we know
2069 * the sequence numbers haven't wrapped. This is a partial fix
2070 * for the "LAND" DoS attack.
2072 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2073 rstreason = BANDLIM_RST_OPENPORT;
2077 todrop = tp->rcv_nxt - th->th_seq;
2080 * If this is a duplicate SYN for our current connection,
2081 * advance over it and pretend and it's not a SYN.
2083 if (thflags & TH_SYN && th->th_seq == tp->irs) {
2093 * Following if statement from Stevens, vol. 2, p. 960.
2096 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2098 * Any valid FIN must be to the left of the window.
2099 * At this point the FIN must be a duplicate or out
2100 * of sequence; drop it.
2105 * Send an ACK to resynchronize and drop any data.
2106 * But keep on processing for RST or ACK.
2108 tp->t_flags |= TF_ACKNOW;
2110 TCPSTAT_INC(tcps_rcvduppack);
2111 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2113 TCPSTAT_INC(tcps_rcvpartduppack);
2114 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2116 drop_hdrlen += todrop; /* drop from the top afterwards */
2117 th->th_seq += todrop;
2119 if (th->th_urp > todrop)
2120 th->th_urp -= todrop;
2128 * If new data are received on a connection after the
2129 * user processes are gone, then RST the other end.
2131 if ((so->so_state & SS_NOFDREF) &&
2132 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2135 KASSERT(ti_locked == TI_WLOCKED, ("%s: SS_NOFDEREF && "
2136 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
2137 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2139 if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
2140 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data after socket "
2141 "was closed, sending RST and removing tcpcb\n",
2142 s, __func__, tcpstates[tp->t_state], tlen);
2146 TCPSTAT_INC(tcps_rcvafterclose);
2147 rstreason = BANDLIM_UNLIMITED;
2152 * If segment ends after window, drop trailing data
2153 * (and PUSH and FIN); if nothing left, just ACK.
2155 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2157 TCPSTAT_INC(tcps_rcvpackafterwin);
2158 if (todrop >= tlen) {
2159 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2161 * If window is closed can only take segments at
2162 * window edge, and have to drop data and PUSH from
2163 * incoming segments. Continue processing, but
2164 * remember to ack. Otherwise, drop segment
2167 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2168 tp->t_flags |= TF_ACKNOW;
2169 TCPSTAT_INC(tcps_rcvwinprobe);
2173 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2176 thflags &= ~(TH_PUSH|TH_FIN);
2180 * If last ACK falls within this segment's sequence numbers,
2181 * record its timestamp.
2183 * 1) That the test incorporates suggestions from the latest
2184 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2185 * 2) That updating only on newer timestamps interferes with
2186 * our earlier PAWS tests, so this check should be solely
2187 * predicated on the sequence space of this segment.
2188 * 3) That we modify the segment boundary check to be
2189 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2190 * instead of RFC1323's
2191 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2192 * This modified check allows us to overcome RFC1323's
2193 * limitations as described in Stevens TCP/IP Illustrated
2194 * Vol. 2 p.869. In such cases, we can still calculate the
2195 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2197 if ((to.to_flags & TOF_TS) != 0 &&
2198 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2199 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2200 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2201 tp->ts_recent_age = ticks;
2202 tp->ts_recent = to.to_tsval;
2206 * If a SYN is in the window, then this is an
2207 * error and we send an RST and drop the connection.
2209 if (thflags & TH_SYN) {
2210 KASSERT(ti_locked == TI_WLOCKED,
2211 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
2212 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2214 tp = tcp_drop(tp, ECONNRESET);
2215 rstreason = BANDLIM_UNLIMITED;
2220 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2221 * flag is on (half-synchronized state), then queue data for
2222 * later processing; else drop segment and return.
2224 if ((thflags & TH_ACK) == 0) {
2225 if (tp->t_state == TCPS_SYN_RECEIVED ||
2226 (tp->t_flags & TF_NEEDSYN))
2228 else if (tp->t_flags & TF_ACKNOW)
2237 switch (tp->t_state) {
2240 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2241 * ESTABLISHED state and continue processing.
2242 * The ACK was checked above.
2244 case TCPS_SYN_RECEIVED:
2246 TCPSTAT_INC(tcps_connects);
2248 /* Do window scaling? */
2249 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2250 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2251 tp->rcv_scale = tp->request_r_scale;
2252 tp->snd_wnd = tiwin;
2256 * SYN-RECEIVED -> ESTABLISHED
2257 * SYN-RECEIVED* -> FIN-WAIT-1
2259 tp->t_starttime = ticks;
2260 if (tp->t_flags & TF_NEEDFIN) {
2261 tp->t_state = TCPS_FIN_WAIT_1;
2262 tp->t_flags &= ~TF_NEEDFIN;
2264 tp->t_state = TCPS_ESTABLISHED;
2266 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
2269 * If segment contains data or ACK, will call tcp_reass()
2270 * later; if not, do so now to pass queued data to user.
2272 if (tlen == 0 && (thflags & TH_FIN) == 0)
2273 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
2275 tp->snd_wl1 = th->th_seq - 1;
2279 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2280 * ACKs. If the ack is in the range
2281 * tp->snd_una < th->th_ack <= tp->snd_max
2282 * then advance tp->snd_una to th->th_ack and drop
2283 * data from the retransmission queue. If this ACK reflects
2284 * more up to date window information we update our window information.
2286 case TCPS_ESTABLISHED:
2287 case TCPS_FIN_WAIT_1:
2288 case TCPS_FIN_WAIT_2:
2289 case TCPS_CLOSE_WAIT:
2292 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2293 TCPSTAT_INC(tcps_rcvacktoomuch);
2296 if ((tp->t_flags & TF_SACK_PERMIT) &&
2297 ((to.to_flags & TOF_SACK) ||
2298 !TAILQ_EMPTY(&tp->snd_holes)))
2299 tcp_sack_doack(tp, &to, th->th_ack);
2300 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2301 if (tlen == 0 && tiwin == tp->snd_wnd) {
2302 TCPSTAT_INC(tcps_rcvdupack);
2304 * If we have outstanding data (other than
2305 * a window probe), this is a completely
2306 * duplicate ack (ie, window info didn't
2307 * change), the ack is the biggest we've
2308 * seen and we've seen exactly our rexmt
2309 * threshhold of them, assume a packet
2310 * has been dropped and retransmit it.
2311 * Kludge snd_nxt & the congestion
2312 * window so we send only this one
2315 * We know we're losing at the current
2316 * window size so do congestion avoidance
2317 * (set ssthresh to half the current window
2318 * and pull our congestion window back to
2319 * the new ssthresh).
2321 * Dup acks mean that packets have left the
2322 * network (they're now cached at the receiver)
2323 * so bump cwnd by the amount in the receiver
2324 * to keep a constant cwnd packets in the
2327 * When using TCP ECN, notify the peer that
2328 * we reduced the cwnd.
2330 if (!tcp_timer_active(tp, TT_REXMT) ||
2331 th->th_ack != tp->snd_una)
2333 else if (++tp->t_dupacks > tcprexmtthresh ||
2334 IN_FASTRECOVERY(tp->t_flags)) {
2335 cc_ack_received(tp, th, CC_DUPACK);
2336 if ((tp->t_flags & TF_SACK_PERMIT) &&
2337 IN_FASTRECOVERY(tp->t_flags)) {
2341 * Compute the amount of data in flight first.
2342 * We can inject new data into the pipe iff
2343 * we have less than 1/2 the original window's
2344 * worth of data in flight.
2346 awnd = (tp->snd_nxt - tp->snd_fack) +
2347 tp->sackhint.sack_bytes_rexmit;
2348 if (awnd < tp->snd_ssthresh) {
2349 tp->snd_cwnd += tp->t_maxseg;
2350 if (tp->snd_cwnd > tp->snd_ssthresh)
2351 tp->snd_cwnd = tp->snd_ssthresh;
2354 tp->snd_cwnd += tp->t_maxseg;
2355 (void) tcp_output(tp);
2357 } else if (tp->t_dupacks == tcprexmtthresh) {
2358 tcp_seq onxt = tp->snd_nxt;
2361 * If we're doing sack, check to
2362 * see if we're already in sack
2363 * recovery. If we're not doing sack,
2364 * check to see if we're in newreno
2367 if (tp->t_flags & TF_SACK_PERMIT) {
2368 if (IN_FASTRECOVERY(tp->t_flags)) {
2373 if (SEQ_LEQ(th->th_ack,
2379 /* Congestion signal before ack. */
2380 cc_cong_signal(tp, th, CC_NDUPACK);
2381 cc_ack_received(tp, th, CC_DUPACK);
2382 tcp_timer_activate(tp, TT_REXMT, 0);
2384 if (tp->t_flags & TF_SACK_PERMIT) {
2386 tcps_sack_recovery_episode);
2387 tp->sack_newdata = tp->snd_nxt;
2388 tp->snd_cwnd = tp->t_maxseg;
2389 (void) tcp_output(tp);
2392 tp->snd_nxt = th->th_ack;
2393 tp->snd_cwnd = tp->t_maxseg;
2394 (void) tcp_output(tp);
2395 KASSERT(tp->snd_limited <= 2,
2396 ("%s: tp->snd_limited too big",
2398 tp->snd_cwnd = tp->snd_ssthresh +
2400 (tp->t_dupacks - tp->snd_limited);
2401 if (SEQ_GT(onxt, tp->snd_nxt))
2404 } else if (V_tcp_do_rfc3042) {
2405 cc_ack_received(tp, th, CC_DUPACK);
2406 u_long oldcwnd = tp->snd_cwnd;
2407 tcp_seq oldsndmax = tp->snd_max;
2410 KASSERT(tp->t_dupacks == 1 ||
2412 ("%s: dupacks not 1 or 2",
2414 if (tp->t_dupacks == 1)
2415 tp->snd_limited = 0;
2417 (tp->snd_nxt - tp->snd_una) +
2418 (tp->t_dupacks - tp->snd_limited) *
2420 (void) tcp_output(tp);
2421 sent = tp->snd_max - oldsndmax;
2422 if (sent > tp->t_maxseg) {
2423 KASSERT((tp->t_dupacks == 2 &&
2424 tp->snd_limited == 0) ||
2425 (sent == tp->t_maxseg + 1 &&
2426 tp->t_flags & TF_SENTFIN),
2427 ("%s: sent too much",
2429 tp->snd_limited = 2;
2430 } else if (sent > 0)
2432 tp->snd_cwnd = oldcwnd;
2440 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2441 ("%s: th_ack <= snd_una", __func__));
2444 * If the congestion window was inflated to account
2445 * for the other side's cached packets, retract it.
2447 if (IN_FASTRECOVERY(tp->t_flags)) {
2448 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2449 if (tp->t_flags & TF_SACK_PERMIT)
2450 tcp_sack_partialack(tp, th);
2452 tcp_newreno_partial_ack(tp, th);
2454 cc_post_recovery(tp, th);
2458 * If we reach this point, ACK is not a duplicate,
2459 * i.e., it ACKs something we sent.
2461 if (tp->t_flags & TF_NEEDSYN) {
2463 * T/TCP: Connection was half-synchronized, and our
2464 * SYN has been ACK'd (so connection is now fully
2465 * synchronized). Go to non-starred state,
2466 * increment snd_una for ACK of SYN, and check if
2467 * we can do window scaling.
2469 tp->t_flags &= ~TF_NEEDSYN;
2471 /* Do window scaling? */
2472 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2473 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2474 tp->rcv_scale = tp->request_r_scale;
2475 /* Send window already scaled. */
2480 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2481 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2482 ("tcp_input: process_ACK ti_locked %d", ti_locked));
2483 INP_WLOCK_ASSERT(tp->t_inpcb);
2485 acked = BYTES_THIS_ACK(tp, th);
2486 TCPSTAT_INC(tcps_rcvackpack);
2487 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2490 * If we just performed our first retransmit, and the ACK
2491 * arrives within our recovery window, then it was a mistake
2492 * to do the retransmit in the first place. Recover our
2493 * original cwnd and ssthresh, and proceed to transmit where
2496 if (tp->t_rxtshift == 1 && (int)(ticks - tp->t_badrxtwin) < 0)
2497 cc_cong_signal(tp, th, CC_RTO_ERR);
2500 * If we have a timestamp reply, update smoothed
2501 * round trip time. If no timestamp is present but
2502 * transmit timer is running and timed sequence
2503 * number was acked, update smoothed round trip time.
2504 * Since we now have an rtt measurement, cancel the
2505 * timer backoff (cf., Phil Karn's retransmit alg.).
2506 * Recompute the initial retransmit timer.
2508 * Some boxes send broken timestamp replies
2509 * during the SYN+ACK phase, ignore
2510 * timestamps of 0 or we could calculate a
2511 * huge RTT and blow up the retransmit timer.
2513 if ((to.to_flags & TOF_TS) != 0 &&
2515 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2516 tp->t_rttlow = ticks - to.to_tsecr;
2517 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2518 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2519 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2520 tp->t_rttlow = ticks - tp->t_rtttime;
2521 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2523 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2526 * If all outstanding data is acked, stop retransmit
2527 * timer and remember to restart (more output or persist).
2528 * If there is more data to be acked, restart retransmit
2529 * timer, using current (possibly backed-off) value.
2531 if (th->th_ack == tp->snd_max) {
2532 tcp_timer_activate(tp, TT_REXMT, 0);
2534 } else if (!tcp_timer_active(tp, TT_PERSIST))
2535 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2538 * If no data (only SYN) was ACK'd,
2539 * skip rest of ACK processing.
2545 * Let the congestion control algorithm update congestion
2546 * control related information. This typically means increasing
2547 * the congestion window.
2549 cc_ack_received(tp, th, CC_ACK);
2551 SOCKBUF_LOCK(&so->so_snd);
2552 if (acked > so->so_snd.sb_cc) {
2553 tp->snd_wnd -= so->so_snd.sb_cc;
2554 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2557 sbdrop_locked(&so->so_snd, acked);
2558 tp->snd_wnd -= acked;
2561 /* NB: sowwakeup_locked() does an implicit unlock. */
2562 sowwakeup_locked(so);
2563 /* Detect una wraparound. */
2564 if (!IN_RECOVERY(tp->t_flags) &&
2565 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2566 SEQ_LEQ(th->th_ack, tp->snd_recover))
2567 tp->snd_recover = th->th_ack - 1;
2568 /* XXXLAS: Can this be moved up into cc_post_recovery? */
2569 if (IN_RECOVERY(tp->t_flags) &&
2570 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2571 EXIT_RECOVERY(tp->t_flags);
2573 tp->snd_una = th->th_ack;
2574 if (tp->t_flags & TF_SACK_PERMIT) {
2575 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2576 tp->snd_recover = tp->snd_una;
2578 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2579 tp->snd_nxt = tp->snd_una;
2581 switch (tp->t_state) {
2584 * In FIN_WAIT_1 STATE in addition to the processing
2585 * for the ESTABLISHED state if our FIN is now acknowledged
2586 * then enter FIN_WAIT_2.
2588 case TCPS_FIN_WAIT_1:
2589 if (ourfinisacked) {
2591 * If we can't receive any more
2592 * data, then closing user can proceed.
2593 * Starting the timer is contrary to the
2594 * specification, but if we don't get a FIN
2595 * we'll hang forever.
2598 * we should release the tp also, and use a
2601 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2604 soisdisconnected(so);
2605 timeout = (tcp_fast_finwait2_recycle) ?
2606 tcp_finwait2_timeout : tcp_maxidle;
2607 tcp_timer_activate(tp, TT_2MSL, timeout);
2609 tp->t_state = TCPS_FIN_WAIT_2;
2614 * In CLOSING STATE in addition to the processing for
2615 * the ESTABLISHED state if the ACK acknowledges our FIN
2616 * then enter the TIME-WAIT state, otherwise ignore
2620 if (ourfinisacked) {
2621 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2623 INP_INFO_WUNLOCK(&V_tcbinfo);
2630 * In LAST_ACK, we may still be waiting for data to drain
2631 * and/or to be acked, as well as for the ack of our FIN.
2632 * If our FIN is now acknowledged, delete the TCB,
2633 * enter the closed state and return.
2636 if (ourfinisacked) {
2637 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2646 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2647 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2648 ("tcp_do_segment: step6 ti_locked %d", ti_locked));
2649 INP_WLOCK_ASSERT(tp->t_inpcb);
2652 * Update window information.
2653 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2655 if ((thflags & TH_ACK) &&
2656 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2657 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2658 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2659 /* keep track of pure window updates */
2661 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2662 TCPSTAT_INC(tcps_rcvwinupd);
2663 tp->snd_wnd = tiwin;
2664 tp->snd_wl1 = th->th_seq;
2665 tp->snd_wl2 = th->th_ack;
2666 if (tp->snd_wnd > tp->max_sndwnd)
2667 tp->max_sndwnd = tp->snd_wnd;
2672 * Process segments with URG.
2674 if ((thflags & TH_URG) && th->th_urp &&
2675 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2677 * This is a kludge, but if we receive and accept
2678 * random urgent pointers, we'll crash in
2679 * soreceive. It's hard to imagine someone
2680 * actually wanting to send this much urgent data.
2682 SOCKBUF_LOCK(&so->so_rcv);
2683 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2684 th->th_urp = 0; /* XXX */
2685 thflags &= ~TH_URG; /* XXX */
2686 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2687 goto dodata; /* XXX */
2690 * If this segment advances the known urgent pointer,
2691 * then mark the data stream. This should not happen
2692 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2693 * a FIN has been received from the remote side.
2694 * In these states we ignore the URG.
2696 * According to RFC961 (Assigned Protocols),
2697 * the urgent pointer points to the last octet
2698 * of urgent data. We continue, however,
2699 * to consider it to indicate the first octet
2700 * of data past the urgent section as the original
2701 * spec states (in one of two places).
2703 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2704 tp->rcv_up = th->th_seq + th->th_urp;
2705 so->so_oobmark = so->so_rcv.sb_cc +
2706 (tp->rcv_up - tp->rcv_nxt) - 1;
2707 if (so->so_oobmark == 0)
2708 so->so_rcv.sb_state |= SBS_RCVATMARK;
2710 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2712 SOCKBUF_UNLOCK(&so->so_rcv);
2714 * Remove out of band data so doesn't get presented to user.
2715 * This can happen independent of advancing the URG pointer,
2716 * but if two URG's are pending at once, some out-of-band
2717 * data may creep in... ick.
2719 if (th->th_urp <= (u_long)tlen &&
2720 !(so->so_options & SO_OOBINLINE)) {
2721 /* hdr drop is delayed */
2722 tcp_pulloutofband(so, th, m, drop_hdrlen);
2726 * If no out of band data is expected,
2727 * pull receive urgent pointer along
2728 * with the receive window.
2730 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2731 tp->rcv_up = tp->rcv_nxt;
2734 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2735 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2736 ("tcp_do_segment: dodata ti_locked %d", ti_locked));
2737 INP_WLOCK_ASSERT(tp->t_inpcb);
2740 * Process the segment text, merging it into the TCP sequencing queue,
2741 * and arranging for acknowledgment of receipt if necessary.
2742 * This process logically involves adjusting tp->rcv_wnd as data
2743 * is presented to the user (this happens in tcp_usrreq.c,
2744 * case PRU_RCVD). If a FIN has already been received on this
2745 * connection then we just ignore the text.
2747 if ((tlen || (thflags & TH_FIN)) &&
2748 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2749 tcp_seq save_start = th->th_seq;
2750 m_adj(m, drop_hdrlen); /* delayed header drop */
2752 * Insert segment which includes th into TCP reassembly queue
2753 * with control block tp. Set thflags to whether reassembly now
2754 * includes a segment with FIN. This handles the common case
2755 * inline (segment is the next to be received on an established
2756 * connection, and the queue is empty), avoiding linkage into
2757 * and removal from the queue and repetition of various
2759 * Set DELACK for segments received in order, but ack
2760 * immediately when segments are out of order (so
2761 * fast retransmit can work).
2763 if (th->th_seq == tp->rcv_nxt &&
2764 LIST_EMPTY(&tp->t_segq) &&
2765 TCPS_HAVEESTABLISHED(tp->t_state)) {
2767 tp->t_flags |= TF_DELACK;
2769 tp->t_flags |= TF_ACKNOW;
2770 tp->rcv_nxt += tlen;
2771 thflags = th->th_flags & TH_FIN;
2772 TCPSTAT_INC(tcps_rcvpack);
2773 TCPSTAT_ADD(tcps_rcvbyte, tlen);
2775 SOCKBUF_LOCK(&so->so_rcv);
2776 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2779 sbappendstream_locked(&so->so_rcv, m);
2780 /* NB: sorwakeup_locked() does an implicit unlock. */
2781 sorwakeup_locked(so);
2784 * XXX: Due to the header drop above "th" is
2785 * theoretically invalid by now. Fortunately
2786 * m_adj() doesn't actually frees any mbufs
2787 * when trimming from the head.
2789 thflags = tcp_reass(tp, th, &tlen, m);
2790 tp->t_flags |= TF_ACKNOW;
2792 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2793 tcp_update_sack_list(tp, save_start, save_start + tlen);
2796 * Note the amount of data that peer has sent into
2797 * our window, in order to estimate the sender's
2801 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2809 * If FIN is received ACK the FIN and let the user know
2810 * that the connection is closing.
2812 if (thflags & TH_FIN) {
2813 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2816 * If connection is half-synchronized
2817 * (ie NEEDSYN flag on) then delay ACK,
2818 * so it may be piggybacked when SYN is sent.
2819 * Otherwise, since we received a FIN then no
2820 * more input can be expected, send ACK now.
2822 if (tp->t_flags & TF_NEEDSYN)
2823 tp->t_flags |= TF_DELACK;
2825 tp->t_flags |= TF_ACKNOW;
2828 switch (tp->t_state) {
2831 * In SYN_RECEIVED and ESTABLISHED STATES
2832 * enter the CLOSE_WAIT state.
2834 case TCPS_SYN_RECEIVED:
2835 tp->t_starttime = ticks;
2837 case TCPS_ESTABLISHED:
2838 tp->t_state = TCPS_CLOSE_WAIT;
2842 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2843 * enter the CLOSING state.
2845 case TCPS_FIN_WAIT_1:
2846 tp->t_state = TCPS_CLOSING;
2850 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2851 * starting the time-wait timer, turning off the other
2854 case TCPS_FIN_WAIT_2:
2855 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2856 KASSERT(ti_locked == TI_WLOCKED, ("%s: dodata "
2857 "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
2861 INP_INFO_WUNLOCK(&V_tcbinfo);
2865 if (ti_locked == TI_RLOCKED)
2866 INP_INFO_RUNLOCK(&V_tcbinfo);
2867 else if (ti_locked == TI_WLOCKED)
2868 INP_INFO_WUNLOCK(&V_tcbinfo);
2870 panic("%s: dodata epilogue ti_locked %d", __func__,
2872 ti_locked = TI_UNLOCKED;
2875 if (so->so_options & SO_DEBUG)
2876 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2881 * Return any desired output.
2883 if (needoutput || (tp->t_flags & TF_ACKNOW))
2884 (void) tcp_output(tp);
2887 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
2888 __func__, ti_locked));
2889 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2890 INP_WLOCK_ASSERT(tp->t_inpcb);
2892 if (tp->t_flags & TF_DELACK) {
2893 tp->t_flags &= ~TF_DELACK;
2894 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2896 INP_WUNLOCK(tp->t_inpcb);
2900 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2901 ("tcp_do_segment: dropafterack ti_locked %d", ti_locked));
2904 * Generate an ACK dropping incoming segment if it occupies
2905 * sequence space, where the ACK reflects our state.
2907 * We can now skip the test for the RST flag since all
2908 * paths to this code happen after packets containing
2909 * RST have been dropped.
2911 * In the SYN-RECEIVED state, don't send an ACK unless the
2912 * segment we received passes the SYN-RECEIVED ACK test.
2913 * If it fails send a RST. This breaks the loop in the
2914 * "LAND" DoS attack, and also prevents an ACK storm
2915 * between two listening ports that have been sent forged
2916 * SYN segments, each with the source address of the other.
2918 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2919 (SEQ_GT(tp->snd_una, th->th_ack) ||
2920 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2921 rstreason = BANDLIM_RST_OPENPORT;
2925 if (so->so_options & SO_DEBUG)
2926 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2929 if (ti_locked == TI_RLOCKED)
2930 INP_INFO_RUNLOCK(&V_tcbinfo);
2931 else if (ti_locked == TI_WLOCKED)
2932 INP_INFO_WUNLOCK(&V_tcbinfo);
2934 panic("%s: dropafterack epilogue ti_locked %d", __func__,
2936 ti_locked = TI_UNLOCKED;
2938 tp->t_flags |= TF_ACKNOW;
2939 (void) tcp_output(tp);
2940 INP_WUNLOCK(tp->t_inpcb);
2945 if (ti_locked == TI_RLOCKED)
2946 INP_INFO_RUNLOCK(&V_tcbinfo);
2947 else if (ti_locked == TI_WLOCKED)
2948 INP_INFO_WUNLOCK(&V_tcbinfo);
2950 panic("%s: dropwithreset ti_locked %d", __func__, ti_locked);
2951 ti_locked = TI_UNLOCKED;
2954 tcp_dropwithreset(m, th, tp, tlen, rstreason);
2955 INP_WUNLOCK(tp->t_inpcb);
2957 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
2961 if (ti_locked == TI_RLOCKED)
2962 INP_INFO_RUNLOCK(&V_tcbinfo);
2963 else if (ti_locked == TI_WLOCKED)
2964 INP_INFO_WUNLOCK(&V_tcbinfo);
2967 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2969 ti_locked = TI_UNLOCKED;
2972 * Drop space held by incoming segment and return.
2975 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2976 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2980 INP_WUNLOCK(tp->t_inpcb);
2985 * Issue RST and make ACK acceptable to originator of segment.
2986 * The mbuf must still include the original packet header.
2990 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2991 int tlen, int rstreason)
2995 struct ip6_hdr *ip6;
2999 INP_WLOCK_ASSERT(tp->t_inpcb);
3002 /* Don't bother if destination was broadcast/multicast. */
3003 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3006 if (mtod(m, struct ip *)->ip_v == 6) {
3007 ip6 = mtod(m, struct ip6_hdr *);
3008 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3009 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3011 /* IPv6 anycast check is done at tcp6_input() */
3015 ip = mtod(m, struct ip *);
3016 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3017 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3018 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3019 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3023 /* Perform bandwidth limiting. */
3024 if (badport_bandlim(rstreason) < 0)
3027 /* tcp_respond consumes the mbuf chain. */
3028 if (th->th_flags & TH_ACK) {
3029 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3030 th->th_ack, TH_RST);
3032 if (th->th_flags & TH_SYN)
3034 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3035 (tcp_seq)0, TH_RST|TH_ACK);
3043 * Parse TCP options and place in tcpopt.
3046 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3051 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3053 if (opt == TCPOPT_EOL)
3055 if (opt == TCPOPT_NOP)
3061 if (optlen < 2 || optlen > cnt)
3066 if (optlen != TCPOLEN_MAXSEG)
3068 if (!(flags & TO_SYN))
3070 to->to_flags |= TOF_MSS;
3071 bcopy((char *)cp + 2,
3072 (char *)&to->to_mss, sizeof(to->to_mss));
3073 to->to_mss = ntohs(to->to_mss);
3076 if (optlen != TCPOLEN_WINDOW)
3078 if (!(flags & TO_SYN))
3080 to->to_flags |= TOF_SCALE;
3081 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3083 case TCPOPT_TIMESTAMP:
3084 if (optlen != TCPOLEN_TIMESTAMP)
3086 to->to_flags |= TOF_TS;
3087 bcopy((char *)cp + 2,
3088 (char *)&to->to_tsval, sizeof(to->to_tsval));
3089 to->to_tsval = ntohl(to->to_tsval);
3090 bcopy((char *)cp + 6,
3091 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3092 to->to_tsecr = ntohl(to->to_tsecr);
3094 #ifdef TCP_SIGNATURE
3096 * XXX In order to reply to a host which has set the
3097 * TCP_SIGNATURE option in its initial SYN, we have to
3098 * record the fact that the option was observed here
3099 * for the syncache code to perform the correct response.
3101 case TCPOPT_SIGNATURE:
3102 if (optlen != TCPOLEN_SIGNATURE)
3104 to->to_flags |= TOF_SIGNATURE;
3105 to->to_signature = cp + 2;
3108 case TCPOPT_SACK_PERMITTED:
3109 if (optlen != TCPOLEN_SACK_PERMITTED)
3111 if (!(flags & TO_SYN))
3115 to->to_flags |= TOF_SACKPERM;
3118 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3122 to->to_flags |= TOF_SACK;
3123 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3124 to->to_sacks = cp + 2;
3125 TCPSTAT_INC(tcps_sack_rcv_blocks);
3134 * Pull out of band byte out of a segment so
3135 * it doesn't appear in the user's data queue.
3136 * It is still reflected in the segment length for
3137 * sequencing purposes.
3140 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3143 int cnt = off + th->th_urp - 1;
3146 if (m->m_len > cnt) {
3147 char *cp = mtod(m, caddr_t) + cnt;
3148 struct tcpcb *tp = sototcpcb(so);
3150 INP_WLOCK_ASSERT(tp->t_inpcb);
3153 tp->t_oobflags |= TCPOOB_HAVEDATA;
3154 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3156 if (m->m_flags & M_PKTHDR)
3165 panic("tcp_pulloutofband");
3169 * Collect new round-trip time estimate
3170 * and update averages and current timeout.
3173 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3177 INP_WLOCK_ASSERT(tp->t_inpcb);
3179 TCPSTAT_INC(tcps_rttupdated);
3181 if (tp->t_srtt != 0) {
3183 * srtt is stored as fixed point with 5 bits after the
3184 * binary point (i.e., scaled by 8). The following magic
3185 * is equivalent to the smoothing algorithm in rfc793 with
3186 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3187 * point). Adjust rtt to origin 0.
3189 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3190 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3192 if ((tp->t_srtt += delta) <= 0)
3196 * We accumulate a smoothed rtt variance (actually, a
3197 * smoothed mean difference), then set the retransmit
3198 * timer to smoothed rtt + 4 times the smoothed variance.
3199 * rttvar is stored as fixed point with 4 bits after the
3200 * binary point (scaled by 16). The following is
3201 * equivalent to rfc793 smoothing with an alpha of .75
3202 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3203 * rfc793's wired-in beta.
3207 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3208 if ((tp->t_rttvar += delta) <= 0)
3210 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3211 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3214 * No rtt measurement yet - use the unsmoothed rtt.
3215 * Set the variance to half the rtt (so our first
3216 * retransmit happens at 3*rtt).
3218 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3219 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3220 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3226 * the retransmit should happen at rtt + 4 * rttvar.
3227 * Because of the way we do the smoothing, srtt and rttvar
3228 * will each average +1/2 tick of bias. When we compute
3229 * the retransmit timer, we want 1/2 tick of rounding and
3230 * 1 extra tick because of +-1/2 tick uncertainty in the
3231 * firing of the timer. The bias will give us exactly the
3232 * 1.5 tick we need. But, because the bias is
3233 * statistical, we have to test that we don't drop below
3234 * the minimum feasible timer (which is 2 ticks).
3236 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3237 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3240 * We received an ack for a packet that wasn't retransmitted;
3241 * it is probably safe to discard any error indications we've
3242 * received recently. This isn't quite right, but close enough
3243 * for now (a route might have failed after we sent a segment,
3244 * and the return path might not be symmetrical).
3246 tp->t_softerror = 0;
3250 * Determine a reasonable value for maxseg size.
3251 * If the route is known, check route for mtu.
3252 * If none, use an mss that can be handled on the outgoing
3253 * interface without forcing IP to fragment; if bigger than
3254 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3255 * to utilize large mbufs. If no route is found, route has no mtu,
3256 * or the destination isn't local, use a default, hopefully conservative
3257 * size (usually 512 or the default IP max size, but no more than the mtu
3258 * of the interface), as we can't discover anything about intervening
3259 * gateways or networks. We also initialize the congestion/slow start
3260 * window to be a single segment if the destination isn't local.
3261 * While looking at the routing entry, we also initialize other path-dependent
3262 * parameters from pre-set or cached values in the routing entry.
3264 * Also take into account the space needed for options that we
3265 * send regularly. Make maxseg shorter by that amount to assure
3266 * that we can send maxseg amount of data even when the options
3267 * are present. Store the upper limit of the length of options plus
3270 * In case of T/TCP, we call this routine during implicit connection
3271 * setup as well (offer = -1), to initialize maxseg from the cached
3274 * NOTE that this routine is only called when we process an incoming
3275 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
3278 tcp_mss_update(struct tcpcb *tp, int offer,
3279 struct hc_metrics_lite *metricptr, int *mtuflags)
3283 struct inpcb *inp = tp->t_inpcb;
3284 struct hc_metrics_lite metrics;
3285 int origoffer = offer;
3287 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3288 size_t min_protoh = isipv6 ?
3289 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3290 sizeof (struct tcpiphdr);
3292 const size_t min_protoh = sizeof(struct tcpiphdr);
3295 INP_WLOCK_ASSERT(tp->t_inpcb);
3300 maxmtu = tcp_maxmtu6(&inp->inp_inc, mtuflags);
3301 tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt;
3305 maxmtu = tcp_maxmtu(&inp->inp_inc, mtuflags);
3306 tp->t_maxopd = tp->t_maxseg = V_tcp_mssdflt;
3310 * No route to sender, stay with default mss and return.
3314 * In case we return early we need to initialize metrics
3315 * to a defined state as tcp_hc_get() would do for us
3316 * if there was no cache hit.
3318 if (metricptr != NULL)
3319 bzero(metricptr, sizeof(struct hc_metrics_lite));
3323 /* What have we got? */
3327 * Offer == 0 means that there was no MSS on the SYN
3328 * segment, in this case we use tcp_mssdflt as
3329 * already assigned to t_maxopd above.
3331 offer = tp->t_maxopd;
3336 * Offer == -1 means that we didn't receive SYN yet.
3342 * Prevent DoS attack with too small MSS. Round up
3343 * to at least minmss.
3345 offer = max(offer, V_tcp_minmss);
3349 * rmx information is now retrieved from tcp_hostcache.
3351 tcp_hc_get(&inp->inp_inc, &metrics);
3352 if (metricptr != NULL)
3353 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3356 * If there's a discovered mtu int tcp hostcache, use it
3357 * else, use the link mtu.
3359 if (metrics.rmx_mtu)
3360 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3364 mss = maxmtu - min_protoh;
3365 if (!V_path_mtu_discovery &&
3366 !in6_localaddr(&inp->in6p_faddr))
3367 mss = min(mss, V_tcp_v6mssdflt);
3371 mss = maxmtu - min_protoh;
3372 if (!V_path_mtu_discovery &&
3373 !in_localaddr(inp->inp_faddr))
3374 mss = min(mss, V_tcp_mssdflt);
3377 * XXX - The above conditional (mss = maxmtu - min_protoh)
3378 * probably violates the TCP spec.
3379 * The problem is that, since we don't know the
3380 * other end's MSS, we are supposed to use a conservative
3381 * default. But, if we do that, then MTU discovery will
3382 * never actually take place, because the conservative
3383 * default is much less than the MTUs typically seen
3384 * on the Internet today. For the moment, we'll sweep
3385 * this under the carpet.
3387 * The conservative default might not actually be a problem
3388 * if the only case this occurs is when sending an initial
3389 * SYN with options and data to a host we've never talked
3390 * to before. Then, they will reply with an MSS value which
3391 * will get recorded and the new parameters should get
3392 * recomputed. For Further Study.
3395 mss = min(mss, offer);
3398 * Sanity check: make sure that maxopd will be large
3399 * enough to allow some data on segments even if the
3400 * all the option space is used (40bytes). Otherwise
3401 * funny things may happen in tcp_output.
3406 * maxopd stores the maximum length of data AND options
3407 * in a segment; maxseg is the amount of data in a normal
3408 * segment. We need to store this value (maxopd) apart
3409 * from maxseg, because now every segment carries options
3410 * and thus we normally have somewhat less data in segments.
3415 * origoffer==-1 indicates that no segments were received yet.
3416 * In this case we just guess.
3418 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3420 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3421 mss -= TCPOLEN_TSTAMP_APPA;
3423 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3425 mss &= ~(MCLBYTES-1);
3428 mss = mss / MCLBYTES * MCLBYTES;
3434 tcp_mss(struct tcpcb *tp, int offer)
3440 struct hc_metrics_lite metrics;
3443 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3445 tcp_mss_update(tp, offer, &metrics, &mtuflags);
3451 * If there's a pipesize, change the socket buffer to that size,
3452 * don't change if sb_hiwat is different than default (then it
3453 * has been changed on purpose with setsockopt).
3454 * Make the socket buffers an integral number of mss units;
3455 * if the mss is larger than the socket buffer, decrease the mss.
3457 so = inp->inp_socket;
3458 SOCKBUF_LOCK(&so->so_snd);
3459 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
3460 bufsize = metrics.rmx_sendpipe;
3462 bufsize = so->so_snd.sb_hiwat;
3466 bufsize = roundup(bufsize, mss);
3467 if (bufsize > sb_max)
3469 if (bufsize > so->so_snd.sb_hiwat)
3470 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3472 SOCKBUF_UNLOCK(&so->so_snd);
3475 SOCKBUF_LOCK(&so->so_rcv);
3476 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
3477 bufsize = metrics.rmx_recvpipe;
3479 bufsize = so->so_rcv.sb_hiwat;
3480 if (bufsize > mss) {
3481 bufsize = roundup(bufsize, mss);
3482 if (bufsize > sb_max)
3484 if (bufsize > so->so_rcv.sb_hiwat)
3485 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3487 SOCKBUF_UNLOCK(&so->so_rcv);
3489 /* Check the interface for TSO capabilities. */
3490 if (mtuflags & CSUM_TSO)
3491 tp->t_flags |= TF_TSO;
3495 * Determine the MSS option to send on an outgoing SYN.
3498 tcp_mssopt(struct in_conninfo *inc)
3505 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3508 if (inc->inc_flags & INC_ISIPV6) {
3509 mss = V_tcp_v6mssdflt;
3510 maxmtu = tcp_maxmtu6(inc, NULL);
3511 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3512 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3516 mss = V_tcp_mssdflt;
3517 maxmtu = tcp_maxmtu(inc, NULL);
3518 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3519 min_protoh = sizeof(struct tcpiphdr);
3521 if (maxmtu && thcmtu)
3522 mss = min(maxmtu, thcmtu) - min_protoh;
3523 else if (maxmtu || thcmtu)
3524 mss = max(maxmtu, thcmtu) - min_protoh;
3531 * On a partial ack arrives, force the retransmission of the
3532 * next unacknowledged segment. Do not clear tp->t_dupacks.
3533 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3537 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3539 tcp_seq onxt = tp->snd_nxt;
3540 u_long ocwnd = tp->snd_cwnd;
3542 INP_WLOCK_ASSERT(tp->t_inpcb);
3544 tcp_timer_activate(tp, TT_REXMT, 0);
3546 tp->snd_nxt = th->th_ack;
3548 * Set snd_cwnd to one segment beyond acknowledged offset.
3549 * (tp->snd_una has not yet been updated when this function is called.)
3551 tp->snd_cwnd = tp->t_maxseg + BYTES_THIS_ACK(tp, th);
3552 tp->t_flags |= TF_ACKNOW;
3553 (void) tcp_output(tp);
3554 tp->snd_cwnd = ocwnd;
3555 if (SEQ_GT(onxt, tp->snd_nxt))
3558 * Partial window deflation. Relies on fact that tp->snd_una
3561 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3562 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3565 tp->snd_cwnd += tp->t_maxseg;