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
8 * Copyright (c) 2010-2011 Juniper Networks, Inc.
11 * Portions of this software were developed at the Centre for Advanced Internet
12 * Architectures, Swinburne University of Technology, by Lawrence Stewart,
13 * James Healy and David Hayes, made possible in part by a grant from the Cisco
14 * University Research Program Fund at Community Foundation Silicon Valley.
16 * Portions of this software were developed at the Centre for Advanced
17 * Internet Architectures, Swinburne University of Technology, Melbourne,
18 * Australia by David Hayes under sponsorship from the FreeBSD Foundation.
20 * Portions of this software were developed by Robert N. M. Watson under
21 * contract to Juniper Networks, Inc.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 4. Neither the name of the University nor the names of its contributors
32 * may be used to endorse or promote products derived from this software
33 * without specific prior written permission.
35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
53 #include "opt_ipfw.h" /* for ipfw_fwd */
55 #include "opt_inet6.h"
56 #include "opt_ipsec.h"
57 #include "opt_tcpdebug.h"
59 #include <sys/param.h>
60 #include <sys/kernel.h>
61 #include <sys/hhook.h>
62 #include <sys/malloc.h>
64 #include <sys/proc.h> /* for proc0 declaration */
65 #include <sys/protosw.h>
67 #include <sys/signalvar.h>
68 #include <sys/socket.h>
69 #include <sys/socketvar.h>
70 #include <sys/sysctl.h>
71 #include <sys/syslog.h>
72 #include <sys/systm.h>
74 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
79 #include <net/if_var.h>
80 #include <net/route.h>
83 #define TCPSTATES /* for logging */
85 #include <netinet/cc.h>
86 #include <netinet/in.h>
87 #include <netinet/in_kdtrace.h>
88 #include <netinet/in_pcb.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/in_var.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
93 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
94 #include <netinet/ip_var.h>
95 #include <netinet/ip_options.h>
96 #include <netinet/ip6.h>
97 #include <netinet/icmp6.h>
98 #include <netinet6/in6_pcb.h>
99 #include <netinet6/ip6_var.h>
100 #include <netinet6/nd6.h>
101 #include <netinet/tcp_fsm.h>
102 #include <netinet/tcp_seq.h>
103 #include <netinet/tcp_timer.h>
104 #include <netinet/tcp_var.h>
105 #include <netinet6/tcp6_var.h>
106 #include <netinet/tcpip.h>
108 #include <netinet/tcp_pcap.h>
110 #include <netinet/tcp_syncache.h>
112 #include <netinet/tcp_debug.h>
113 #endif /* TCPDEBUG */
115 #include <netinet/tcp_offload.h>
119 #include <netipsec/ipsec.h>
120 #include <netipsec/ipsec6.h>
123 #include <machine/in_cksum.h>
125 #include <security/mac/mac_framework.h>
127 const int tcprexmtthresh = 3;
129 int tcp_log_in_vain = 0;
130 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
132 "Log all incoming TCP segments to closed ports");
134 VNET_DEFINE(int, blackhole) = 0;
135 #define V_blackhole VNET(blackhole)
136 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_VNET | CTLFLAG_RW,
137 &VNET_NAME(blackhole), 0,
138 "Do not send RST on segments to closed ports");
140 VNET_DEFINE(int, tcp_delack_enabled) = 1;
141 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_VNET | CTLFLAG_RW,
142 &VNET_NAME(tcp_delack_enabled), 0,
143 "Delay ACK to try and piggyback it onto a data packet");
145 VNET_DEFINE(int, drop_synfin) = 0;
146 #define V_drop_synfin VNET(drop_synfin)
147 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_VNET | CTLFLAG_RW,
148 &VNET_NAME(drop_synfin), 0,
149 "Drop TCP packets with SYN+FIN set");
151 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
152 #define V_tcp_do_rfc3042 VNET(tcp_do_rfc3042)
153 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_VNET | CTLFLAG_RW,
154 &VNET_NAME(tcp_do_rfc3042), 0,
155 "Enable RFC 3042 (Limited Transmit)");
157 VNET_DEFINE(int, tcp_do_rfc3390) = 1;
158 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_VNET | CTLFLAG_RW,
159 &VNET_NAME(tcp_do_rfc3390), 0,
160 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
162 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, experimental, CTLFLAG_RW, 0,
163 "Experimental TCP extensions");
165 VNET_DEFINE(int, tcp_do_initcwnd10) = 1;
166 SYSCTL_INT(_net_inet_tcp_experimental, OID_AUTO, initcwnd10, CTLFLAG_VNET | CTLFLAG_RW,
167 &VNET_NAME(tcp_do_initcwnd10), 0,
168 "Enable RFC 6928 (Increasing initial CWND to 10)");
170 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
171 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_VNET | CTLFLAG_RW,
172 &VNET_NAME(tcp_do_rfc3465), 0,
173 "Enable RFC 3465 (Appropriate Byte Counting)");
175 VNET_DEFINE(int, tcp_abc_l_var) = 2;
176 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_VNET | CTLFLAG_RW,
177 &VNET_NAME(tcp_abc_l_var), 2,
178 "Cap the max cwnd increment during slow-start to this number of segments");
180 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
182 VNET_DEFINE(int, tcp_do_ecn) = 0;
183 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW,
184 &VNET_NAME(tcp_do_ecn), 0,
187 VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
188 SYSCTL_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_VNET | CTLFLAG_RW,
189 &VNET_NAME(tcp_ecn_maxretries), 0,
190 "Max retries before giving up on ECN");
192 VNET_DEFINE(int, tcp_insecure_syn) = 0;
193 #define V_tcp_insecure_syn VNET(tcp_insecure_syn)
194 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_syn, CTLFLAG_VNET | CTLFLAG_RW,
195 &VNET_NAME(tcp_insecure_syn), 0,
196 "Follow RFC793 instead of RFC5961 criteria for accepting SYN packets");
198 VNET_DEFINE(int, tcp_insecure_rst) = 0;
199 #define V_tcp_insecure_rst VNET(tcp_insecure_rst)
200 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_VNET | CTLFLAG_RW,
201 &VNET_NAME(tcp_insecure_rst), 0,
202 "Follow RFC793 instead of RFC5961 criteria for accepting RST packets");
204 VNET_DEFINE(int, tcp_recvspace) = 1024*64;
205 #define V_tcp_recvspace VNET(tcp_recvspace)
206 SYSCTL_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_VNET | CTLFLAG_RW,
207 &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
209 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
210 #define V_tcp_do_autorcvbuf VNET(tcp_do_autorcvbuf)
211 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_VNET | CTLFLAG_RW,
212 &VNET_NAME(tcp_do_autorcvbuf), 0,
213 "Enable automatic receive buffer sizing");
215 VNET_DEFINE(int, tcp_autorcvbuf_inc) = 16*1024;
216 #define V_tcp_autorcvbuf_inc VNET(tcp_autorcvbuf_inc)
217 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_VNET | CTLFLAG_RW,
218 &VNET_NAME(tcp_autorcvbuf_inc), 0,
219 "Incrementor step size of automatic receive buffer");
221 VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
222 #define V_tcp_autorcvbuf_max VNET(tcp_autorcvbuf_max)
223 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_VNET | CTLFLAG_RW,
224 &VNET_NAME(tcp_autorcvbuf_max), 0,
225 "Max size of automatic receive buffer");
227 VNET_DEFINE(struct inpcbhead, tcb);
228 #define tcb6 tcb /* for KAME src sync over BSD*'s */
229 VNET_DEFINE(struct inpcbinfo, tcbinfo);
231 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
232 static void tcp_do_segment(struct mbuf *, struct tcphdr *,
233 struct socket *, struct tcpcb *, int, int, uint8_t,
235 static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
236 struct tcpcb *, int, int);
237 static void tcp_pulloutofband(struct socket *,
238 struct tcphdr *, struct mbuf *, int);
239 static void tcp_xmit_timer(struct tcpcb *, int);
240 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
241 static void inline cc_ack_received(struct tcpcb *tp, struct tcphdr *th,
243 static void inline cc_conn_init(struct tcpcb *tp);
244 static void inline cc_post_recovery(struct tcpcb *tp, struct tcphdr *th);
245 static void inline hhook_run_tcp_est_in(struct tcpcb *tp,
246 struct tcphdr *th, struct tcpopt *to);
249 * TCP statistics are stored in an "array" of counter(9)s.
251 VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
252 VNET_PCPUSTAT_SYSINIT(tcpstat);
253 SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
254 tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
257 VNET_PCPUSTAT_SYSUNINIT(tcpstat);
260 * Kernel module interface for updating tcpstat. The argument is an index
261 * into tcpstat treated as an array.
264 kmod_tcpstat_inc(int statnum)
267 counter_u64_add(VNET(tcpstat)[statnum], 1);
271 * Wrapper for the TCP established input helper hook.
274 hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
276 struct tcp_hhook_data hhook_data;
278 if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
283 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
289 * CC wrapper hook functions
292 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t type)
294 INP_WLOCK_ASSERT(tp->t_inpcb);
296 tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
297 if (tp->snd_cwnd <= tp->snd_wnd)
298 tp->ccv->flags |= CCF_CWND_LIMITED;
300 tp->ccv->flags &= ~CCF_CWND_LIMITED;
302 if (type == CC_ACK) {
303 if (tp->snd_cwnd > tp->snd_ssthresh) {
304 tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
305 V_tcp_abc_l_var * tp->t_maxseg);
306 if (tp->t_bytes_acked >= tp->snd_cwnd) {
307 tp->t_bytes_acked -= tp->snd_cwnd;
308 tp->ccv->flags |= CCF_ABC_SENTAWND;
311 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
312 tp->t_bytes_acked = 0;
316 if (CC_ALGO(tp)->ack_received != NULL) {
317 /* XXXLAS: Find a way to live without this */
318 tp->ccv->curack = th->th_ack;
319 CC_ALGO(tp)->ack_received(tp->ccv, type);
324 cc_conn_init(struct tcpcb *tp)
326 struct hc_metrics_lite metrics;
327 struct inpcb *inp = tp->t_inpcb;
330 INP_WLOCK_ASSERT(tp->t_inpcb);
332 tcp_hc_get(&inp->inp_inc, &metrics);
334 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
336 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
337 TCPSTAT_INC(tcps_usedrtt);
338 if (metrics.rmx_rttvar) {
339 tp->t_rttvar = metrics.rmx_rttvar;
340 TCPSTAT_INC(tcps_usedrttvar);
342 /* default variation is +- 1 rtt */
344 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
346 TCPT_RANGESET(tp->t_rxtcur,
347 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
348 tp->t_rttmin, TCPTV_REXMTMAX);
350 if (metrics.rmx_ssthresh) {
352 * There's some sort of gateway or interface
353 * buffer limit on the path. Use this to set
354 * the slow start threshhold, but set the
355 * threshold to no less than 2*mss.
357 tp->snd_ssthresh = max(2 * tp->t_maxseg, metrics.rmx_ssthresh);
358 TCPSTAT_INC(tcps_usedssthresh);
362 * Set the initial slow-start flight size.
364 * RFC5681 Section 3.1 specifies the default conservative values.
365 * RFC3390 specifies slightly more aggressive values.
366 * RFC6928 increases it to ten segments.
368 * If a SYN or SYN/ACK was lost and retransmitted, we have to
369 * reduce the initial CWND to one segment as congestion is likely
370 * requiring us to be cautious.
372 if (tp->snd_cwnd == 1)
373 tp->snd_cwnd = tp->t_maxseg; /* SYN(-ACK) lost */
374 else if (V_tcp_do_initcwnd10)
375 tp->snd_cwnd = min(10 * tp->t_maxseg,
376 max(2 * tp->t_maxseg, 14600));
377 else if (V_tcp_do_rfc3390)
378 tp->snd_cwnd = min(4 * tp->t_maxseg,
379 max(2 * tp->t_maxseg, 4380));
381 /* Per RFC5681 Section 3.1 */
382 if (tp->t_maxseg > 2190)
383 tp->snd_cwnd = 2 * tp->t_maxseg;
384 else if (tp->t_maxseg > 1095)
385 tp->snd_cwnd = 3 * tp->t_maxseg;
387 tp->snd_cwnd = 4 * tp->t_maxseg;
390 if (CC_ALGO(tp)->conn_init != NULL)
391 CC_ALGO(tp)->conn_init(tp->ccv);
395 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
397 INP_WLOCK_ASSERT(tp->t_inpcb);
401 if (!IN_FASTRECOVERY(tp->t_flags)) {
402 tp->snd_recover = tp->snd_max;
403 if (tp->t_flags & TF_ECN_PERMIT)
404 tp->t_flags |= TF_ECN_SND_CWR;
408 if (!IN_CONGRECOVERY(tp->t_flags)) {
409 TCPSTAT_INC(tcps_ecn_rcwnd);
410 tp->snd_recover = tp->snd_max;
411 if (tp->t_flags & TF_ECN_PERMIT)
412 tp->t_flags |= TF_ECN_SND_CWR;
417 tp->t_bytes_acked = 0;
418 EXIT_RECOVERY(tp->t_flags);
419 tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
420 tp->t_maxseg) * tp->t_maxseg;
421 tp->snd_cwnd = tp->t_maxseg;
424 TCPSTAT_INC(tcps_sndrexmitbad);
425 /* RTO was unnecessary, so reset everything. */
426 tp->snd_cwnd = tp->snd_cwnd_prev;
427 tp->snd_ssthresh = tp->snd_ssthresh_prev;
428 tp->snd_recover = tp->snd_recover_prev;
429 if (tp->t_flags & TF_WASFRECOVERY)
430 ENTER_FASTRECOVERY(tp->t_flags);
431 if (tp->t_flags & TF_WASCRECOVERY)
432 ENTER_CONGRECOVERY(tp->t_flags);
433 tp->snd_nxt = tp->snd_max;
434 tp->t_flags &= ~TF_PREVVALID;
439 if (CC_ALGO(tp)->cong_signal != NULL) {
441 tp->ccv->curack = th->th_ack;
442 CC_ALGO(tp)->cong_signal(tp->ccv, type);
447 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
449 INP_WLOCK_ASSERT(tp->t_inpcb);
451 /* XXXLAS: KASSERT that we're in recovery? */
453 if (CC_ALGO(tp)->post_recovery != NULL) {
454 tp->ccv->curack = th->th_ack;
455 CC_ALGO(tp)->post_recovery(tp->ccv);
457 /* XXXLAS: EXIT_RECOVERY ? */
458 tp->t_bytes_acked = 0;
463 tcp_signature_verify_input(struct mbuf *m, int off0, int tlen, int optlen,
464 struct tcpopt *to, struct tcphdr *th, u_int tcpbflag)
468 tcp_fields_to_net(th);
469 ret = tcp_signature_verify(m, off0, tlen, optlen, to, th, tcpbflag);
470 tcp_fields_to_host(th);
476 * Indicate whether this ack should be delayed. We can delay the ack if
477 * following conditions are met:
478 * - There is no delayed ack timer in progress.
479 * - Our last ack wasn't a 0-sized window. We never want to delay
480 * the ack that opens up a 0-sized window.
481 * - LRO wasn't used for this segment. We make sure by checking that the
482 * segment size is not larger than the MSS.
483 * - Delayed acks are enabled or this is a half-synchronized T/TCP
486 #define DELAY_ACK(tp, tlen) \
487 ((!tcp_timer_active(tp, TT_DELACK) && \
488 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
489 (tlen <= tp->t_maxopd) && \
490 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
493 cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos)
495 INP_WLOCK_ASSERT(tp->t_inpcb);
497 if (CC_ALGO(tp)->ecnpkt_handler != NULL) {
498 switch (iptos & IPTOS_ECN_MASK) {
500 tp->ccv->flags |= CCF_IPHDR_CE;
503 tp->ccv->flags &= ~CCF_IPHDR_CE;
506 tp->ccv->flags &= ~CCF_IPHDR_CE;
510 if (th->th_flags & TH_CWR)
511 tp->ccv->flags |= CCF_TCPHDR_CWR;
513 tp->ccv->flags &= ~CCF_TCPHDR_CWR;
515 if (tp->t_flags & TF_DELACK)
516 tp->ccv->flags |= CCF_DELACK;
518 tp->ccv->flags &= ~CCF_DELACK;
520 CC_ALGO(tp)->ecnpkt_handler(tp->ccv);
522 if (tp->ccv->flags & CCF_ACKNOW)
523 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
528 * TCP input handling is split into multiple parts:
529 * tcp6_input is a thin wrapper around tcp_input for the extended
530 * ip6_protox[] call format in ip6_input
531 * tcp_input handles primary segment validation, inpcb lookup and
532 * SYN processing on listen sockets
533 * tcp_do_segment processes the ACK and text of the segment for
534 * establishing, established and closing connections
538 tcp6_input(struct mbuf **mp, int *offp, int proto)
540 struct mbuf *m = *mp;
541 struct in6_ifaddr *ia6;
544 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
547 * draft-itojun-ipv6-tcp-to-anycast
548 * better place to put this in?
550 ip6 = mtod(m, struct ip6_hdr *);
551 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
552 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
555 ifa_free(&ia6->ia_ifa);
556 ip6 = mtod(m, struct ip6_hdr *);
557 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
558 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
559 return (IPPROTO_DONE);
562 ifa_free(&ia6->ia_ifa);
564 return (tcp_input(mp, offp, proto));
569 tcp_input(struct mbuf **mp, int *offp, int proto)
571 struct mbuf *m = *mp;
572 struct tcphdr *th = NULL;
573 struct ip *ip = NULL;
574 struct inpcb *inp = NULL;
575 struct tcpcb *tp = NULL;
576 struct socket *so = NULL;
586 int rstreason = 0; /* For badport_bandlim accounting purposes */
588 uint8_t sig_checked = 0;
591 struct m_tag *fwd_tag = NULL;
593 struct ip6_hdr *ip6 = NULL;
596 const void *ip6 = NULL;
598 struct tcpopt to; /* options in this segment */
599 char *s = NULL; /* address and port logging */
601 #define TI_UNLOCKED 1
606 * The size of tcp_saveipgen must be the size of the max ip header,
609 u_char tcp_saveipgen[IP6_HDR_LEN];
610 struct tcphdr tcp_savetcp;
615 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
622 TCPSTAT_INC(tcps_rcvtotal);
626 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
628 if (m->m_len < (sizeof(*ip6) + sizeof(*th))) {
629 m = m_pullup(m, sizeof(*ip6) + sizeof(*th));
631 TCPSTAT_INC(tcps_rcvshort);
632 return (IPPROTO_DONE);
636 ip6 = mtod(m, struct ip6_hdr *);
637 th = (struct tcphdr *)((caddr_t)ip6 + off0);
638 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
639 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
640 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
641 th->th_sum = m->m_pkthdr.csum_data;
643 th->th_sum = in6_cksum_pseudo(ip6, tlen,
644 IPPROTO_TCP, m->m_pkthdr.csum_data);
645 th->th_sum ^= 0xffff;
647 th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
649 TCPSTAT_INC(tcps_rcvbadsum);
654 * Be proactive about unspecified IPv6 address in source.
655 * As we use all-zero to indicate unbounded/unconnected pcb,
656 * unspecified IPv6 address can be used to confuse us.
658 * Note that packets with unspecified IPv6 destination is
659 * already dropped in ip6_input.
661 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
667 #if defined(INET) && defined(INET6)
673 * Get IP and TCP header together in first mbuf.
674 * Note: IP leaves IP header in first mbuf.
676 if (off0 > sizeof (struct ip)) {
678 off0 = sizeof(struct ip);
680 if (m->m_len < sizeof (struct tcpiphdr)) {
681 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
683 TCPSTAT_INC(tcps_rcvshort);
684 return (IPPROTO_DONE);
687 ip = mtod(m, struct ip *);
688 th = (struct tcphdr *)((caddr_t)ip + off0);
689 tlen = ntohs(ip->ip_len) - off0;
691 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
692 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
693 th->th_sum = m->m_pkthdr.csum_data;
695 th->th_sum = in_pseudo(ip->ip_src.s_addr,
697 htonl(m->m_pkthdr.csum_data + tlen +
699 th->th_sum ^= 0xffff;
701 struct ipovly *ipov = (struct ipovly *)ip;
704 * Checksum extended TCP header and data.
707 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
708 ipov->ih_len = htons(tlen);
709 th->th_sum = in_cksum(m, len);
710 /* Reset length for SDT probes. */
711 ip->ip_len = htons(tlen + off0);
715 TCPSTAT_INC(tcps_rcvbadsum);
718 /* Re-initialization for later version check */
719 ip->ip_v = IPVERSION;
725 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
727 #if defined(INET) && defined(INET6)
735 * Check that TCP offset makes sense,
736 * pull out TCP options and adjust length. XXX
738 off = th->th_off << 2;
739 if (off < sizeof (struct tcphdr) || off > tlen) {
740 TCPSTAT_INC(tcps_rcvbadoff);
743 tlen -= off; /* tlen is used instead of ti->ti_len */
744 if (off > sizeof (struct tcphdr)) {
747 IP6_EXTHDR_CHECK(m, off0, off, IPPROTO_DONE);
748 ip6 = mtod(m, struct ip6_hdr *);
749 th = (struct tcphdr *)((caddr_t)ip6 + off0);
752 #if defined(INET) && defined(INET6)
757 if (m->m_len < sizeof(struct ip) + off) {
758 if ((m = m_pullup(m, sizeof (struct ip) + off))
760 TCPSTAT_INC(tcps_rcvshort);
761 return (IPPROTO_DONE);
763 ip = mtod(m, struct ip *);
764 th = (struct tcphdr *)((caddr_t)ip + off0);
768 optlen = off - sizeof (struct tcphdr);
769 optp = (u_char *)(th + 1);
771 thflags = th->th_flags;
774 * Convert TCP protocol specific fields to host format.
776 tcp_fields_to_host(th);
779 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
781 drop_hdrlen = off0 + off;
784 * Locate pcb for segment; if we're likely to add or remove a
785 * connection then first acquire pcbinfo lock. There are three cases
786 * where we might discover later we need a write lock despite the
787 * flags: ACKs moving a connection out of the syncache, ACKs for a
788 * connection in TIMEWAIT and SYNs not targeting a listening socket.
790 if ((thflags & (TH_FIN | TH_RST)) != 0) {
791 INP_INFO_RLOCK(&V_tcbinfo);
792 ti_locked = TI_RLOCKED;
794 ti_locked = TI_UNLOCKED;
797 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
801 (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
803 || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
806 #if defined(INET) && !defined(INET6)
807 (m->m_flags & M_IP_NEXTHOP)
810 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
814 if (ti_locked == TI_RLOCKED) {
815 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
817 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
821 if (isipv6 && fwd_tag != NULL) {
822 struct sockaddr_in6 *next_hop6;
824 next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
826 * Transparently forwarded. Pretend to be the destination.
827 * Already got one like this?
829 inp = in6_pcblookup_mbuf(&V_tcbinfo,
830 &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
831 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif, m);
834 * It's new. Try to find the ambushing socket.
835 * Because we've rewritten the destination address,
836 * any hardware-generated hash is ignored.
838 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
839 th->th_sport, &next_hop6->sin6_addr,
840 next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
841 th->th_dport, INPLOOKUP_WILDCARD |
842 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
845 inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
846 th->th_sport, &ip6->ip6_dst, th->th_dport,
847 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
848 m->m_pkthdr.rcvif, m);
851 #if defined(INET6) && defined(INET)
855 if (fwd_tag != NULL) {
856 struct sockaddr_in *next_hop;
858 next_hop = (struct sockaddr_in *)(fwd_tag+1);
860 * Transparently forwarded. Pretend to be the destination.
861 * already got one like this?
863 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
864 ip->ip_dst, th->th_dport, INPLOOKUP_WLOCKPCB,
865 m->m_pkthdr.rcvif, m);
868 * It's new. Try to find the ambushing socket.
869 * Because we've rewritten the destination address,
870 * any hardware-generated hash is ignored.
872 inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
873 th->th_sport, next_hop->sin_addr,
874 next_hop->sin_port ? ntohs(next_hop->sin_port) :
875 th->th_dport, INPLOOKUP_WILDCARD |
876 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
879 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
880 th->th_sport, ip->ip_dst, th->th_dport,
881 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
882 m->m_pkthdr.rcvif, m);
886 * If the INPCB does not exist then all data in the incoming
887 * segment is discarded and an appropriate RST is sent back.
888 * XXX MRT Send RST using which routing table?
892 * Log communication attempts to ports that are not
895 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
896 tcp_log_in_vain == 2) {
897 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
898 log(LOG_INFO, "%s; %s: Connection attempt "
899 "to closed port\n", s, __func__);
902 * When blackholing do not respond with a RST but
903 * completely ignore the segment and drop it.
905 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
909 rstreason = BANDLIM_RST_CLOSEDPORT;
912 INP_WLOCK_ASSERT(inp);
913 if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
914 (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) &&
915 ((inp->inp_socket == NULL) ||
916 (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0)) {
917 inp->inp_flowid = m->m_pkthdr.flowid;
918 inp->inp_flowtype = M_HASHTYPE_GET(m);
922 if (isipv6 && ipsec6_in_reject(m, inp)) {
926 if (ipsec4_in_reject(m, inp) != 0) {
932 * Check the minimum TTL for socket.
934 if (inp->inp_ip_minttl != 0) {
936 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
940 if (inp->inp_ip_minttl > ip->ip_ttl)
945 * A previous connection in TIMEWAIT state is supposed to catch stray
946 * or duplicate segments arriving late. If this segment was a
947 * legitimate new connection attempt, the old INPCB gets removed and
948 * we can try again to find a listening socket.
950 * At this point, due to earlier optimism, we may hold only an inpcb
951 * lock, and not the inpcbinfo write lock. If so, we need to try to
952 * acquire it, or if that fails, acquire a reference on the inpcb,
953 * drop all locks, acquire a global write lock, and then re-acquire
954 * the inpcb lock. We may at that point discover that another thread
955 * has tried to free the inpcb, in which case we need to loop back
956 * and try to find a new inpcb to deliver to.
958 * XXXRW: It may be time to rethink timewait locking.
961 if (inp->inp_flags & INP_TIMEWAIT) {
962 if (ti_locked == TI_UNLOCKED) {
963 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
966 INP_INFO_RLOCK(&V_tcbinfo);
967 ti_locked = TI_RLOCKED;
969 if (in_pcbrele_wlocked(inp)) {
974 ti_locked = TI_RLOCKED;
976 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
978 if (thflags & TH_SYN)
979 tcp_dooptions(&to, optp, optlen, TO_SYN);
981 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
983 if (tcp_twcheck(inp, &to, th, m, tlen))
985 INP_INFO_RUNLOCK(&V_tcbinfo);
986 return (IPPROTO_DONE);
989 * The TCPCB may no longer exist if the connection is winding
990 * down or it is in the CLOSED state. Either way we drop the
991 * segment and send an appropriate response.
994 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
995 rstreason = BANDLIM_RST_CLOSEDPORT;
1000 if (tp->t_flags & TF_TOE) {
1001 tcp_offload_input(tp, m);
1002 m = NULL; /* consumed by the TOE driver */
1008 * We've identified a valid inpcb, but it could be that we need an
1009 * inpcbinfo write lock but don't hold it. In this case, attempt to
1010 * acquire using the same strategy as the TIMEWAIT case above. If we
1011 * relock, we have to jump back to 'relocked' as the connection might
1012 * now be in TIMEWAIT.
1015 if ((thflags & (TH_FIN | TH_RST)) != 0)
1016 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1018 if (!((tp->t_state == TCPS_ESTABLISHED && (thflags & TH_SYN) == 0) ||
1019 (tp->t_state == TCPS_LISTEN && (thflags & TH_SYN)))) {
1020 if (ti_locked == TI_UNLOCKED) {
1021 if (INP_INFO_TRY_RLOCK(&V_tcbinfo) == 0) {
1024 INP_INFO_RLOCK(&V_tcbinfo);
1025 ti_locked = TI_RLOCKED;
1027 if (in_pcbrele_wlocked(inp)) {
1033 ti_locked = TI_RLOCKED;
1035 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1039 INP_WLOCK_ASSERT(inp);
1040 if (mac_inpcb_check_deliver(inp, m))
1043 so = inp->inp_socket;
1044 KASSERT(so != NULL, ("%s: so == NULL", __func__));
1046 if (so->so_options & SO_DEBUG) {
1047 ostate = tp->t_state;
1050 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
1053 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1056 #endif /* TCPDEBUG */
1058 * When the socket is accepting connections (the INPCB is in LISTEN
1059 * state) we look into the SYN cache if this is a new connection
1060 * attempt or the completion of a previous one.
1062 if (so->so_options & SO_ACCEPTCONN) {
1063 struct in_conninfo inc;
1065 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
1066 "tp not listening", __func__));
1067 bzero(&inc, sizeof(inc));
1070 inc.inc_flags |= INC_ISIPV6;
1071 inc.inc6_faddr = ip6->ip6_src;
1072 inc.inc6_laddr = ip6->ip6_dst;
1076 inc.inc_faddr = ip->ip_src;
1077 inc.inc_laddr = ip->ip_dst;
1079 inc.inc_fport = th->th_sport;
1080 inc.inc_lport = th->th_dport;
1081 inc.inc_fibnum = so->so_fibnum;
1084 * Check for an existing connection attempt in syncache if
1085 * the flag is only ACK. A successful lookup creates a new
1086 * socket appended to the listen queue in SYN_RECEIVED state.
1088 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1090 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1092 * Parse the TCP options here because
1093 * syncookies need access to the reflected
1096 tcp_dooptions(&to, optp, optlen, 0);
1098 * NB: syncache_expand() doesn't unlock
1099 * inp and tcpinfo locks.
1101 if (!syncache_expand(&inc, &to, th, &so, m)) {
1103 * No syncache entry or ACK was not
1104 * for our SYN/ACK. Send a RST.
1105 * NB: syncache did its own logging
1106 * of the failure cause.
1108 rstreason = BANDLIM_RST_OPENPORT;
1113 * We completed the 3-way handshake
1114 * but could not allocate a socket
1115 * either due to memory shortage,
1116 * listen queue length limits or
1117 * global socket limits. Send RST
1118 * or wait and have the remote end
1119 * retransmit the ACK for another
1122 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1123 log(LOG_DEBUG, "%s; %s: Listen socket: "
1124 "Socket allocation failed due to "
1125 "limits or memory shortage, %s\n",
1127 V_tcp_sc_rst_sock_fail ?
1128 "sending RST" : "try again");
1129 if (V_tcp_sc_rst_sock_fail) {
1130 rstreason = BANDLIM_UNLIMITED;
1136 * Socket is created in state SYN_RECEIVED.
1137 * Unlock the listen socket, lock the newly
1138 * created socket and update the tp variable.
1140 INP_WUNLOCK(inp); /* listen socket */
1141 inp = sotoinpcb(so);
1143 * New connection inpcb is already locked by
1144 * syncache_expand().
1146 INP_WLOCK_ASSERT(inp);
1147 tp = intotcpcb(inp);
1148 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
1149 ("%s: ", __func__));
1150 #ifdef TCP_SIGNATURE
1151 if (sig_checked == 0) {
1152 tcp_dooptions(&to, optp, optlen,
1153 (thflags & TH_SYN) ? TO_SYN : 0);
1154 if (!tcp_signature_verify_input(m, off0, tlen,
1155 optlen, &to, th, tp->t_flags)) {
1158 * In SYN_SENT state if it receives an
1159 * RST, it is allowed for further
1162 if ((thflags & TH_RST) == 0 ||
1163 (tp->t_state == TCPS_SYN_SENT) == 0)
1171 * Process the segment and the data it
1172 * contains. tcp_do_segment() consumes
1173 * the mbuf chain and unlocks the inpcb.
1175 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
1177 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1178 return (IPPROTO_DONE);
1181 * Segment flag validation for new connection attempts:
1183 * Our (SYN|ACK) response was rejected.
1184 * Check with syncache and remove entry to prevent
1187 * NB: syncache_chkrst does its own logging of failure
1190 if (thflags & TH_RST) {
1191 syncache_chkrst(&inc, th);
1195 * We can't do anything without SYN.
1197 if ((thflags & TH_SYN) == 0) {
1198 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1199 log(LOG_DEBUG, "%s; %s: Listen socket: "
1200 "SYN is missing, segment ignored\n",
1202 TCPSTAT_INC(tcps_badsyn);
1206 * (SYN|ACK) is bogus on a listen socket.
1208 if (thflags & TH_ACK) {
1209 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1210 log(LOG_DEBUG, "%s; %s: Listen socket: "
1211 "SYN|ACK invalid, segment rejected\n",
1213 syncache_badack(&inc); /* XXX: Not needed! */
1214 TCPSTAT_INC(tcps_badsyn);
1215 rstreason = BANDLIM_RST_OPENPORT;
1219 * If the drop_synfin option is enabled, drop all
1220 * segments with both the SYN and FIN bits set.
1221 * This prevents e.g. nmap from identifying the
1223 * XXX: Poor reasoning. nmap has other methods
1224 * and is constantly refining its stack detection
1226 * XXX: This is a violation of the TCP specification
1227 * and was used by RFC1644.
1229 if ((thflags & TH_FIN) && V_drop_synfin) {
1230 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1231 log(LOG_DEBUG, "%s; %s: Listen socket: "
1232 "SYN|FIN segment ignored (based on "
1233 "sysctl setting)\n", s, __func__);
1234 TCPSTAT_INC(tcps_badsyn);
1238 * Segment's flags are (SYN) or (SYN|FIN).
1240 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1241 * as they do not affect the state of the TCP FSM.
1242 * The data pointed to by TH_URG and th_urp is ignored.
1244 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1245 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1246 KASSERT(thflags & (TH_SYN),
1247 ("%s: Listen socket: TH_SYN not set", __func__));
1250 * If deprecated address is forbidden,
1251 * we do not accept SYN to deprecated interface
1252 * address to prevent any new inbound connection from
1253 * getting established.
1254 * When we do not accept SYN, we send a TCP RST,
1255 * with deprecated source address (instead of dropping
1256 * it). We compromise it as it is much better for peer
1257 * to send a RST, and RST will be the final packet
1260 * If we do not forbid deprecated addresses, we accept
1261 * the SYN packet. RFC2462 does not suggest dropping
1263 * If we decipher RFC2462 5.5.4, it says like this:
1264 * 1. use of deprecated addr with existing
1265 * communication is okay - "SHOULD continue to be
1267 * 2. use of it with new communication:
1268 * (2a) "SHOULD NOT be used if alternate address
1269 * with sufficient scope is available"
1270 * (2b) nothing mentioned otherwise.
1271 * Here we fall into (2b) case as we have no choice in
1272 * our source address selection - we must obey the peer.
1274 * The wording in RFC2462 is confusing, and there are
1275 * multiple description text for deprecated address
1276 * handling - worse, they are not exactly the same.
1277 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1279 if (isipv6 && !V_ip6_use_deprecated) {
1280 struct in6_ifaddr *ia6;
1282 ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
1284 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1285 ifa_free(&ia6->ia_ifa);
1286 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1287 log(LOG_DEBUG, "%s; %s: Listen socket: "
1288 "Connection attempt to deprecated "
1289 "IPv6 address rejected\n",
1291 rstreason = BANDLIM_RST_OPENPORT;
1295 ifa_free(&ia6->ia_ifa);
1299 * Basic sanity checks on incoming SYN requests:
1300 * Don't respond if the destination is a link layer
1301 * broadcast according to RFC1122 4.2.3.10, p. 104.
1302 * If it is from this socket it must be forged.
1303 * Don't respond if the source or destination is a
1304 * global or subnet broad- or multicast address.
1305 * Note that it is quite possible to receive unicast
1306 * link-layer packets with a broadcast IP address. Use
1307 * in_broadcast() to find them.
1309 if (m->m_flags & (M_BCAST|M_MCAST)) {
1310 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1311 log(LOG_DEBUG, "%s; %s: Listen socket: "
1312 "Connection attempt from broad- or multicast "
1313 "link layer address ignored\n", s, __func__);
1318 if (th->th_dport == th->th_sport &&
1319 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1320 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1321 log(LOG_DEBUG, "%s; %s: Listen socket: "
1322 "Connection attempt to/from self "
1323 "ignored\n", s, __func__);
1326 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1327 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1328 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1329 log(LOG_DEBUG, "%s; %s: Listen socket: "
1330 "Connection attempt from/to multicast "
1331 "address ignored\n", s, __func__);
1336 #if defined(INET) && defined(INET6)
1341 if (th->th_dport == th->th_sport &&
1342 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1343 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1344 log(LOG_DEBUG, "%s; %s: Listen socket: "
1345 "Connection attempt from/to self "
1346 "ignored\n", s, __func__);
1349 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1350 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1351 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1352 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1353 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1354 log(LOG_DEBUG, "%s; %s: Listen socket: "
1355 "Connection attempt from/to broad- "
1356 "or multicast address ignored\n",
1363 * SYN appears to be valid. Create compressed TCP state
1367 if (so->so_options & SO_DEBUG)
1368 tcp_trace(TA_INPUT, ostate, tp,
1369 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1371 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
1372 tcp_dooptions(&to, optp, optlen, TO_SYN);
1373 syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL);
1375 * Entry added to syncache and mbuf consumed.
1376 * Only the listen socket is unlocked by syncache_add().
1378 if (ti_locked == TI_RLOCKED) {
1379 INP_INFO_RUNLOCK(&V_tcbinfo);
1380 ti_locked = TI_UNLOCKED;
1382 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1383 return (IPPROTO_DONE);
1384 } else if (tp->t_state == TCPS_LISTEN) {
1386 * When a listen socket is torn down the SO_ACCEPTCONN
1387 * flag is removed first while connections are drained
1388 * from the accept queue in a unlock/lock cycle of the
1389 * ACCEPT_LOCK, opening a race condition allowing a SYN
1390 * attempt go through unhandled.
1395 #ifdef TCP_SIGNATURE
1396 if (sig_checked == 0) {
1397 tcp_dooptions(&to, optp, optlen,
1398 (thflags & TH_SYN) ? TO_SYN : 0);
1399 if (!tcp_signature_verify_input(m, off0, tlen, optlen, &to,
1403 * In SYN_SENT state if it receives an RST, it is
1404 * allowed for further processing.
1406 if ((thflags & TH_RST) == 0 ||
1407 (tp->t_state == TCPS_SYN_SENT) == 0)
1414 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
1417 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1418 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1419 * the inpcb, and unlocks pcbinfo.
1421 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
1422 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1423 return (IPPROTO_DONE);
1426 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
1428 if (ti_locked == TI_RLOCKED) {
1429 INP_INFO_RUNLOCK(&V_tcbinfo);
1430 ti_locked = TI_UNLOCKED;
1434 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropwithreset "
1435 "ti_locked: %d", __func__, ti_locked));
1436 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1441 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1444 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1445 m = NULL; /* mbuf chain got consumed. */
1450 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
1452 if (ti_locked == TI_RLOCKED) {
1453 INP_INFO_RUNLOCK(&V_tcbinfo);
1454 ti_locked = TI_UNLOCKED;
1458 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropunlock "
1459 "ti_locked: %d", __func__, ti_locked));
1460 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1468 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1473 return (IPPROTO_DONE);
1477 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1478 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1481 int thflags, acked, ourfinisacked, needoutput = 0;
1482 int rstreason, todrop, win;
1485 struct in_conninfo *inc;
1491 * The size of tcp_saveipgen must be the size of the max ip header,
1494 u_char tcp_saveipgen[IP6_HDR_LEN];
1495 struct tcphdr tcp_savetcp;
1498 thflags = th->th_flags;
1499 inc = &tp->t_inpcb->inp_inc;
1500 tp->sackhint.last_sack_ack = 0;
1503 * If this is either a state-changing packet or current state isn't
1504 * established, we require a write lock on tcbinfo. Otherwise, we
1505 * allow the tcbinfo to be in either alocked or unlocked, as the
1506 * caller may have unnecessarily acquired a write lock due to a race.
1508 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1509 tp->t_state != TCPS_ESTABLISHED) {
1510 KASSERT(ti_locked == TI_RLOCKED, ("%s ti_locked %d for "
1511 "SYN/FIN/RST/!EST", __func__, ti_locked));
1512 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1515 if (ti_locked == TI_RLOCKED)
1516 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1518 KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST "
1519 "ti_locked: %d", __func__, ti_locked));
1520 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1524 INP_WLOCK_ASSERT(tp->t_inpcb);
1525 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1527 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1531 /* Save segment, if requested. */
1532 tcp_pcap_add(th, m, &(tp->t_inpkts));
1536 * Segment received on connection.
1537 * Reset idle time and keep-alive timer.
1538 * XXX: This should be done after segment
1539 * validation to ignore broken/spoofed segs.
1541 tp->t_rcvtime = ticks;
1542 if (TCPS_HAVEESTABLISHED(tp->t_state))
1543 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
1546 * Scale up the window into a 32-bit value.
1547 * For the SYN_SENT state the scale is zero.
1549 tiwin = th->th_win << tp->snd_scale;
1552 * TCP ECN processing.
1554 if (tp->t_flags & TF_ECN_PERMIT) {
1555 if (thflags & TH_CWR)
1556 tp->t_flags &= ~TF_ECN_SND_ECE;
1557 switch (iptos & IPTOS_ECN_MASK) {
1559 tp->t_flags |= TF_ECN_SND_ECE;
1560 TCPSTAT_INC(tcps_ecn_ce);
1562 case IPTOS_ECN_ECT0:
1563 TCPSTAT_INC(tcps_ecn_ect0);
1565 case IPTOS_ECN_ECT1:
1566 TCPSTAT_INC(tcps_ecn_ect1);
1570 /* Process a packet differently from RFC3168. */
1571 cc_ecnpkt_handler(tp, th, iptos);
1573 /* Congestion experienced. */
1574 if (thflags & TH_ECE) {
1575 cc_cong_signal(tp, th, CC_ECN);
1580 * Parse options on any incoming segment.
1582 tcp_dooptions(&to, (u_char *)(th + 1),
1583 (th->th_off << 2) - sizeof(struct tcphdr),
1584 (thflags & TH_SYN) ? TO_SYN : 0);
1587 * If echoed timestamp is later than the current time,
1588 * fall back to non RFC1323 RTT calculation. Normalize
1589 * timestamp if syncookies were used when this connection
1592 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1593 to.to_tsecr -= tp->ts_offset;
1594 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1598 * If timestamps were negotiated during SYN/ACK they should
1599 * appear on every segment during this session and vice versa.
1601 if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1602 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1603 log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1604 "no action\n", s, __func__);
1608 if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
1609 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1610 log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1611 "no action\n", s, __func__);
1617 * Process options only when we get SYN/ACK back. The SYN case
1618 * for incoming connections is handled in tcp_syncache.
1619 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1620 * or <SYN,ACK>) segment itself is never scaled.
1621 * XXX this is traditional behavior, may need to be cleaned up.
1623 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1624 if ((to.to_flags & TOF_SCALE) &&
1625 (tp->t_flags & TF_REQ_SCALE)) {
1626 tp->t_flags |= TF_RCVD_SCALE;
1627 tp->snd_scale = to.to_wscale;
1630 * Initial send window. It will be updated with
1631 * the next incoming segment to the scaled value.
1633 tp->snd_wnd = th->th_win;
1634 if (to.to_flags & TOF_TS) {
1635 tp->t_flags |= TF_RCVD_TSTMP;
1636 tp->ts_recent = to.to_tsval;
1637 tp->ts_recent_age = tcp_ts_getticks();
1639 if (to.to_flags & TOF_MSS)
1640 tcp_mss(tp, to.to_mss);
1641 if ((tp->t_flags & TF_SACK_PERMIT) &&
1642 (to.to_flags & TOF_SACKPERM) == 0)
1643 tp->t_flags &= ~TF_SACK_PERMIT;
1647 * Header prediction: check for the two common cases
1648 * of a uni-directional data xfer. If the packet has
1649 * no control flags, is in-sequence, the window didn't
1650 * change and we're not retransmitting, it's a
1651 * candidate. If the length is zero and the ack moved
1652 * forward, we're the sender side of the xfer. Just
1653 * free the data acked & wake any higher level process
1654 * that was blocked waiting for space. If the length
1655 * is non-zero and the ack didn't move, we're the
1656 * receiver side. If we're getting packets in-order
1657 * (the reassembly queue is empty), add the data to
1658 * the socket buffer and note that we need a delayed ack.
1659 * Make sure that the hidden state-flags are also off.
1660 * Since we check for TCPS_ESTABLISHED first, it can only
1663 if (tp->t_state == TCPS_ESTABLISHED &&
1664 th->th_seq == tp->rcv_nxt &&
1665 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1666 tp->snd_nxt == tp->snd_max &&
1667 tiwin && tiwin == tp->snd_wnd &&
1668 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1669 LIST_EMPTY(&tp->t_segq) &&
1670 ((to.to_flags & TOF_TS) == 0 ||
1671 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1674 * If last ACK falls within this segment's sequence numbers,
1675 * record the timestamp.
1676 * NOTE that the test is modified according to the latest
1677 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1679 if ((to.to_flags & TOF_TS) != 0 &&
1680 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1681 tp->ts_recent_age = tcp_ts_getticks();
1682 tp->ts_recent = to.to_tsval;
1686 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1687 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1688 !IN_RECOVERY(tp->t_flags) &&
1689 (to.to_flags & TOF_SACK) == 0 &&
1690 TAILQ_EMPTY(&tp->snd_holes)) {
1692 * This is a pure ack for outstanding data.
1694 if (ti_locked == TI_RLOCKED)
1695 INP_INFO_RUNLOCK(&V_tcbinfo);
1696 ti_locked = TI_UNLOCKED;
1698 TCPSTAT_INC(tcps_predack);
1701 * "bad retransmit" recovery.
1703 if (tp->t_rxtshift == 1 &&
1704 tp->t_flags & TF_PREVVALID &&
1705 (int)(ticks - tp->t_badrxtwin) < 0) {
1706 cc_cong_signal(tp, th, CC_RTO_ERR);
1710 * Recalculate the transmit timer / rtt.
1712 * Some boxes send broken timestamp replies
1713 * during the SYN+ACK phase, ignore
1714 * timestamps of 0 or we could calculate a
1715 * huge RTT and blow up the retransmit timer.
1717 if ((to.to_flags & TOF_TS) != 0 &&
1721 t = tcp_ts_getticks() - to.to_tsecr;
1722 if (!tp->t_rttlow || tp->t_rttlow > t)
1725 TCP_TS_TO_TICKS(t) + 1);
1726 } else if (tp->t_rtttime &&
1727 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1728 if (!tp->t_rttlow ||
1729 tp->t_rttlow > ticks - tp->t_rtttime)
1730 tp->t_rttlow = ticks - tp->t_rtttime;
1732 ticks - tp->t_rtttime);
1734 acked = BYTES_THIS_ACK(tp, th);
1736 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1737 hhook_run_tcp_est_in(tp, th, &to);
1739 TCPSTAT_INC(tcps_rcvackpack);
1740 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1741 sbdrop(&so->so_snd, acked);
1742 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1743 SEQ_LEQ(th->th_ack, tp->snd_recover))
1744 tp->snd_recover = th->th_ack - 1;
1747 * Let the congestion control algorithm update
1748 * congestion control related information. This
1749 * typically means increasing the congestion
1752 cc_ack_received(tp, th, CC_ACK);
1754 tp->snd_una = th->th_ack;
1756 * Pull snd_wl2 up to prevent seq wrap relative
1759 tp->snd_wl2 = th->th_ack;
1764 * If all outstanding data are acked, stop
1765 * retransmit timer, otherwise restart timer
1766 * using current (possibly backed-off) value.
1767 * If process is waiting for space,
1768 * wakeup/selwakeup/signal. If data
1769 * are ready to send, let tcp_output
1770 * decide between more output or persist.
1773 if (so->so_options & SO_DEBUG)
1774 tcp_trace(TA_INPUT, ostate, tp,
1775 (void *)tcp_saveipgen,
1778 TCP_PROBE3(debug__input, tp, th,
1779 mtod(m, const char *));
1780 if (tp->snd_una == tp->snd_max)
1781 tcp_timer_activate(tp, TT_REXMT, 0);
1782 else if (!tcp_timer_active(tp, TT_PERSIST))
1783 tcp_timer_activate(tp, TT_REXMT,
1786 if (sbavail(&so->so_snd))
1787 (void) tcp_output(tp);
1790 } else if (th->th_ack == tp->snd_una &&
1791 tlen <= sbspace(&so->so_rcv)) {
1792 int newsize = 0; /* automatic sockbuf scaling */
1795 * This is a pure, in-sequence data packet with
1796 * nothing on the reassembly queue and we have enough
1797 * buffer space to take it.
1799 if (ti_locked == TI_RLOCKED)
1800 INP_INFO_RUNLOCK(&V_tcbinfo);
1801 ti_locked = TI_UNLOCKED;
1803 /* Clean receiver SACK report if present */
1804 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1805 tcp_clean_sackreport(tp);
1806 TCPSTAT_INC(tcps_preddat);
1807 tp->rcv_nxt += tlen;
1809 * Pull snd_wl1 up to prevent seq wrap relative to
1812 tp->snd_wl1 = th->th_seq;
1814 * Pull rcv_up up to prevent seq wrap relative to
1817 tp->rcv_up = tp->rcv_nxt;
1818 TCPSTAT_INC(tcps_rcvpack);
1819 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1821 if (so->so_options & SO_DEBUG)
1822 tcp_trace(TA_INPUT, ostate, tp,
1823 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1825 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
1828 * Automatic sizing of receive socket buffer. Often the send
1829 * buffer size is not optimally adjusted to the actual network
1830 * conditions at hand (delay bandwidth product). Setting the
1831 * buffer size too small limits throughput on links with high
1832 * bandwidth and high delay (eg. trans-continental/oceanic links).
1834 * On the receive side the socket buffer memory is only rarely
1835 * used to any significant extent. This allows us to be much
1836 * more aggressive in scaling the receive socket buffer. For
1837 * the case that the buffer space is actually used to a large
1838 * extent and we run out of kernel memory we can simply drop
1839 * the new segments; TCP on the sender will just retransmit it
1840 * later. Setting the buffer size too big may only consume too
1841 * much kernel memory if the application doesn't read() from
1842 * the socket or packet loss or reordering makes use of the
1845 * The criteria to step up the receive buffer one notch are:
1846 * 1. Application has not set receive buffer size with
1847 * SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
1848 * 2. the number of bytes received during the time it takes
1849 * one timestamp to be reflected back to us (the RTT);
1850 * 3. received bytes per RTT is within seven eighth of the
1851 * current socket buffer size;
1852 * 4. receive buffer size has not hit maximal automatic size;
1854 * This algorithm does one step per RTT at most and only if
1855 * we receive a bulk stream w/o packet losses or reorderings.
1856 * Shrinking the buffer during idle times is not necessary as
1857 * it doesn't consume any memory when idle.
1859 * TODO: Only step up if the application is actually serving
1860 * the buffer to better manage the socket buffer resources.
1862 if (V_tcp_do_autorcvbuf &&
1863 (to.to_flags & TOF_TS) &&
1865 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1866 if (TSTMP_GT(to.to_tsecr, tp->rfbuf_ts) &&
1867 to.to_tsecr - tp->rfbuf_ts < hz) {
1869 (so->so_rcv.sb_hiwat / 8 * 7) &&
1870 so->so_rcv.sb_hiwat <
1871 V_tcp_autorcvbuf_max) {
1873 min(so->so_rcv.sb_hiwat +
1874 V_tcp_autorcvbuf_inc,
1875 V_tcp_autorcvbuf_max);
1877 /* Start over with next RTT. */
1881 tp->rfbuf_cnt += tlen; /* add up */
1884 /* Add data to socket buffer. */
1885 SOCKBUF_LOCK(&so->so_rcv);
1886 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1890 * Set new socket buffer size.
1891 * Give up when limit is reached.
1894 if (!sbreserve_locked(&so->so_rcv,
1896 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1897 m_adj(m, drop_hdrlen); /* delayed header drop */
1898 sbappendstream_locked(&so->so_rcv, m, 0);
1900 /* NB: sorwakeup_locked() does an implicit unlock. */
1901 sorwakeup_locked(so);
1902 if (DELAY_ACK(tp, tlen)) {
1903 tp->t_flags |= TF_DELACK;
1905 tp->t_flags |= TF_ACKNOW;
1913 * Calculate amount of space in receive window,
1914 * and then do TCP input processing.
1915 * Receive window is amount of space in rcv queue,
1916 * but not less than advertised window.
1918 win = sbspace(&so->so_rcv);
1921 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1923 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1927 switch (tp->t_state) {
1930 * If the state is SYN_RECEIVED:
1931 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1933 case TCPS_SYN_RECEIVED:
1934 if ((thflags & TH_ACK) &&
1935 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1936 SEQ_GT(th->th_ack, tp->snd_max))) {
1937 rstreason = BANDLIM_RST_OPENPORT;
1943 * If the state is SYN_SENT:
1944 * if seg contains an ACK, but not for our SYN, drop the input.
1945 * if seg contains a RST, then drop the connection.
1946 * if seg does not contain SYN, then drop it.
1947 * Otherwise this is an acceptable SYN segment
1948 * initialize tp->rcv_nxt and tp->irs
1949 * if seg contains ack then advance tp->snd_una
1950 * if seg contains an ECE and ECN support is enabled, the stream
1952 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1953 * arrange for segment to be acked (eventually)
1954 * continue processing rest of data/controls, beginning with URG
1957 if ((thflags & TH_ACK) &&
1958 (SEQ_LEQ(th->th_ack, tp->iss) ||
1959 SEQ_GT(th->th_ack, tp->snd_max))) {
1960 rstreason = BANDLIM_UNLIMITED;
1963 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
1964 TCP_PROBE5(connect__refused, NULL, tp,
1965 mtod(m, const char *), tp, th);
1966 tp = tcp_drop(tp, ECONNREFUSED);
1968 if (thflags & TH_RST)
1970 if (!(thflags & TH_SYN))
1973 tp->irs = th->th_seq;
1975 if (thflags & TH_ACK) {
1976 TCPSTAT_INC(tcps_connects);
1979 mac_socketpeer_set_from_mbuf(m, so);
1981 /* Do window scaling on this connection? */
1982 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1983 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1984 tp->rcv_scale = tp->request_r_scale;
1986 tp->rcv_adv += imin(tp->rcv_wnd,
1987 TCP_MAXWIN << tp->rcv_scale);
1988 tp->snd_una++; /* SYN is acked */
1990 * If there's data, delay ACK; if there's also a FIN
1991 * ACKNOW will be turned on later.
1993 if (DELAY_ACK(tp, tlen) && tlen != 0)
1994 tcp_timer_activate(tp, TT_DELACK,
1997 tp->t_flags |= TF_ACKNOW;
1999 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
2000 tp->t_flags |= TF_ECN_PERMIT;
2001 TCPSTAT_INC(tcps_ecn_shs);
2005 * Received <SYN,ACK> in SYN_SENT[*] state.
2007 * SYN_SENT --> ESTABLISHED
2008 * SYN_SENT* --> FIN_WAIT_1
2010 tp->t_starttime = ticks;
2011 if (tp->t_flags & TF_NEEDFIN) {
2012 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2013 tp->t_flags &= ~TF_NEEDFIN;
2016 tcp_state_change(tp, TCPS_ESTABLISHED);
2017 TCP_PROBE5(connect__established, NULL, tp,
2018 mtod(m, const char *), tp, th);
2020 tcp_timer_activate(tp, TT_KEEP,
2025 * Received initial SYN in SYN-SENT[*] state =>
2026 * simultaneous open.
2027 * If it succeeds, connection is * half-synchronized.
2028 * Otherwise, do 3-way handshake:
2029 * SYN-SENT -> SYN-RECEIVED
2030 * SYN-SENT* -> SYN-RECEIVED*
2032 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
2033 tcp_timer_activate(tp, TT_REXMT, 0);
2034 tcp_state_change(tp, TCPS_SYN_RECEIVED);
2037 KASSERT(ti_locked == TI_RLOCKED, ("%s: trimthenstep6: "
2038 "ti_locked %d", __func__, ti_locked));
2039 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2040 INP_WLOCK_ASSERT(tp->t_inpcb);
2043 * Advance th->th_seq to correspond to first data byte.
2044 * If data, trim to stay within window,
2045 * dropping FIN if necessary.
2048 if (tlen > tp->rcv_wnd) {
2049 todrop = tlen - tp->rcv_wnd;
2053 TCPSTAT_INC(tcps_rcvpackafterwin);
2054 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2056 tp->snd_wl1 = th->th_seq - 1;
2057 tp->rcv_up = th->th_seq;
2059 * Client side of transaction: already sent SYN and data.
2060 * If the remote host used T/TCP to validate the SYN,
2061 * our data will be ACK'd; if so, enter normal data segment
2062 * processing in the middle of step 5, ack processing.
2063 * Otherwise, goto step 6.
2065 if (thflags & TH_ACK)
2071 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
2072 * do normal processing.
2074 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
2078 break; /* continue normal processing */
2082 * States other than LISTEN or SYN_SENT.
2083 * First check the RST flag and sequence number since reset segments
2084 * are exempt from the timestamp and connection count tests. This
2085 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
2086 * below which allowed reset segments in half the sequence space
2087 * to fall though and be processed (which gives forged reset
2088 * segments with a random sequence number a 50 percent chance of
2089 * killing a connection).
2090 * Then check timestamp, if present.
2091 * Then check the connection count, if present.
2092 * Then check that at least some bytes of segment are within
2093 * receive window. If segment begins before rcv_nxt,
2094 * drop leading data (and SYN); if nothing left, just ack.
2096 if (thflags & TH_RST) {
2098 * RFC5961 Section 3.2
2100 * - RST drops connection only if SEG.SEQ == RCV.NXT.
2101 * - If RST is in window, we send challenge ACK.
2103 * Note: to take into account delayed ACKs, we should
2104 * test against last_ack_sent instead of rcv_nxt.
2105 * Note 2: we handle special case of closed window, not
2106 * covered by the RFC.
2108 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2109 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
2110 (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
2112 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2113 KASSERT(ti_locked == TI_RLOCKED,
2114 ("%s: TH_RST ti_locked %d, th %p tp %p",
2115 __func__, ti_locked, th, tp));
2116 KASSERT(tp->t_state != TCPS_SYN_SENT,
2117 ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
2120 if (V_tcp_insecure_rst ||
2121 tp->last_ack_sent == th->th_seq) {
2122 TCPSTAT_INC(tcps_drops);
2123 /* Drop the connection. */
2124 switch (tp->t_state) {
2125 case TCPS_SYN_RECEIVED:
2126 so->so_error = ECONNREFUSED;
2128 case TCPS_ESTABLISHED:
2129 case TCPS_FIN_WAIT_1:
2130 case TCPS_FIN_WAIT_2:
2131 case TCPS_CLOSE_WAIT:
2132 so->so_error = ECONNRESET;
2134 tcp_state_change(tp, TCPS_CLOSED);
2140 TCPSTAT_INC(tcps_badrst);
2141 /* Send challenge ACK. */
2142 tcp_respond(tp, mtod(m, void *), th, m,
2143 tp->rcv_nxt, tp->snd_nxt, TH_ACK);
2144 tp->last_ack_sent = tp->rcv_nxt;
2152 * RFC5961 Section 4.2
2153 * Send challenge ACK for any SYN in synchronized state.
2155 if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT) {
2156 KASSERT(ti_locked == TI_RLOCKED,
2157 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
2158 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2160 TCPSTAT_INC(tcps_badsyn);
2161 if (V_tcp_insecure_syn &&
2162 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2163 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2164 tp = tcp_drop(tp, ECONNRESET);
2165 rstreason = BANDLIM_UNLIMITED;
2167 /* Send challenge ACK. */
2168 tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
2169 tp->snd_nxt, TH_ACK);
2170 tp->last_ack_sent = tp->rcv_nxt;
2177 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2178 * and it's less than ts_recent, drop it.
2180 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2181 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2183 /* Check to see if ts_recent is over 24 days old. */
2184 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2186 * Invalidate ts_recent. If this segment updates
2187 * ts_recent, the age will be reset later and ts_recent
2188 * will get a valid value. If it does not, setting
2189 * ts_recent to zero will at least satisfy the
2190 * requirement that zero be placed in the timestamp
2191 * echo reply when ts_recent isn't valid. The
2192 * age isn't reset until we get a valid ts_recent
2193 * because we don't want out-of-order segments to be
2194 * dropped when ts_recent is old.
2198 TCPSTAT_INC(tcps_rcvduppack);
2199 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
2200 TCPSTAT_INC(tcps_pawsdrop);
2208 * In the SYN-RECEIVED state, validate that the packet belongs to
2209 * this connection before trimming the data to fit the receive
2210 * window. Check the sequence number versus IRS since we know
2211 * the sequence numbers haven't wrapped. This is a partial fix
2212 * for the "LAND" DoS attack.
2214 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2215 rstreason = BANDLIM_RST_OPENPORT;
2219 todrop = tp->rcv_nxt - th->th_seq;
2221 if (thflags & TH_SYN) {
2231 * Following if statement from Stevens, vol. 2, p. 960.
2234 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2236 * Any valid FIN must be to the left of the window.
2237 * At this point the FIN must be a duplicate or out
2238 * of sequence; drop it.
2243 * Send an ACK to resynchronize and drop any data.
2244 * But keep on processing for RST or ACK.
2246 tp->t_flags |= TF_ACKNOW;
2248 TCPSTAT_INC(tcps_rcvduppack);
2249 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2251 TCPSTAT_INC(tcps_rcvpartduppack);
2252 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2254 drop_hdrlen += todrop; /* drop from the top afterwards */
2255 th->th_seq += todrop;
2257 if (th->th_urp > todrop)
2258 th->th_urp -= todrop;
2266 * If new data are received on a connection after the
2267 * user processes are gone, then RST the other end.
2269 if ((so->so_state & SS_NOFDREF) &&
2270 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2271 KASSERT(ti_locked == TI_RLOCKED, ("%s: SS_NOFDEREF && "
2272 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
2273 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2275 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
2276 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
2277 "after socket was closed, "
2278 "sending RST and removing tcpcb\n",
2279 s, __func__, tcpstates[tp->t_state], tlen);
2283 TCPSTAT_INC(tcps_rcvafterclose);
2284 rstreason = BANDLIM_UNLIMITED;
2289 * If segment ends after window, drop trailing data
2290 * (and PUSH and FIN); if nothing left, just ACK.
2292 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2294 TCPSTAT_INC(tcps_rcvpackafterwin);
2295 if (todrop >= tlen) {
2296 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2298 * If window is closed can only take segments at
2299 * window edge, and have to drop data and PUSH from
2300 * incoming segments. Continue processing, but
2301 * remember to ack. Otherwise, drop segment
2304 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2305 tp->t_flags |= TF_ACKNOW;
2306 TCPSTAT_INC(tcps_rcvwinprobe);
2310 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2313 thflags &= ~(TH_PUSH|TH_FIN);
2317 * If last ACK falls within this segment's sequence numbers,
2318 * record its timestamp.
2320 * 1) That the test incorporates suggestions from the latest
2321 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2322 * 2) That updating only on newer timestamps interferes with
2323 * our earlier PAWS tests, so this check should be solely
2324 * predicated on the sequence space of this segment.
2325 * 3) That we modify the segment boundary check to be
2326 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2327 * instead of RFC1323's
2328 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2329 * This modified check allows us to overcome RFC1323's
2330 * limitations as described in Stevens TCP/IP Illustrated
2331 * Vol. 2 p.869. In such cases, we can still calculate the
2332 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2334 if ((to.to_flags & TOF_TS) != 0 &&
2335 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2336 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2337 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2338 tp->ts_recent_age = tcp_ts_getticks();
2339 tp->ts_recent = to.to_tsval;
2343 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2344 * flag is on (half-synchronized state), then queue data for
2345 * later processing; else drop segment and return.
2347 if ((thflags & TH_ACK) == 0) {
2348 if (tp->t_state == TCPS_SYN_RECEIVED ||
2349 (tp->t_flags & TF_NEEDSYN))
2351 else if (tp->t_flags & TF_ACKNOW)
2360 switch (tp->t_state) {
2363 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2364 * ESTABLISHED state and continue processing.
2365 * The ACK was checked above.
2367 case TCPS_SYN_RECEIVED:
2369 TCPSTAT_INC(tcps_connects);
2371 /* Do window scaling? */
2372 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2373 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2374 tp->rcv_scale = tp->request_r_scale;
2375 tp->snd_wnd = tiwin;
2379 * SYN-RECEIVED -> ESTABLISHED
2380 * SYN-RECEIVED* -> FIN-WAIT-1
2382 tp->t_starttime = ticks;
2383 if (tp->t_flags & TF_NEEDFIN) {
2384 tcp_state_change(tp, TCPS_FIN_WAIT_1);
2385 tp->t_flags &= ~TF_NEEDFIN;
2387 tcp_state_change(tp, TCPS_ESTABLISHED);
2388 TCP_PROBE5(accept__established, NULL, tp,
2389 mtod(m, const char *), tp, th);
2391 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2394 * If segment contains data or ACK, will call tcp_reass()
2395 * later; if not, do so now to pass queued data to user.
2397 if (tlen == 0 && (thflags & TH_FIN) == 0)
2398 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
2400 tp->snd_wl1 = th->th_seq - 1;
2404 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2405 * ACKs. If the ack is in the range
2406 * tp->snd_una < th->th_ack <= tp->snd_max
2407 * then advance tp->snd_una to th->th_ack and drop
2408 * data from the retransmission queue. If this ACK reflects
2409 * more up to date window information we update our window information.
2411 case TCPS_ESTABLISHED:
2412 case TCPS_FIN_WAIT_1:
2413 case TCPS_FIN_WAIT_2:
2414 case TCPS_CLOSE_WAIT:
2417 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2418 TCPSTAT_INC(tcps_rcvacktoomuch);
2421 if ((tp->t_flags & TF_SACK_PERMIT) &&
2422 ((to.to_flags & TOF_SACK) ||
2423 !TAILQ_EMPTY(&tp->snd_holes)))
2424 tcp_sack_doack(tp, &to, th->th_ack);
2426 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2427 hhook_run_tcp_est_in(tp, th, &to);
2429 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2430 if (tlen == 0 && tiwin == tp->snd_wnd) {
2432 * If this is the first time we've seen a
2433 * FIN from the remote, this is not a
2434 * duplicate and it needs to be processed
2435 * normally. This happens during a
2436 * simultaneous close.
2438 if ((thflags & TH_FIN) &&
2439 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2443 TCPSTAT_INC(tcps_rcvdupack);
2445 * If we have outstanding data (other than
2446 * a window probe), this is a completely
2447 * duplicate ack (ie, window info didn't
2448 * change and FIN isn't set),
2449 * the ack is the biggest we've
2450 * seen and we've seen exactly our rexmt
2451 * threshhold of them, assume a packet
2452 * has been dropped and retransmit it.
2453 * Kludge snd_nxt & the congestion
2454 * window so we send only this one
2457 * We know we're losing at the current
2458 * window size so do congestion avoidance
2459 * (set ssthresh to half the current window
2460 * and pull our congestion window back to
2461 * the new ssthresh).
2463 * Dup acks mean that packets have left the
2464 * network (they're now cached at the receiver)
2465 * so bump cwnd by the amount in the receiver
2466 * to keep a constant cwnd packets in the
2469 * When using TCP ECN, notify the peer that
2470 * we reduced the cwnd.
2472 if (!tcp_timer_active(tp, TT_REXMT) ||
2473 th->th_ack != tp->snd_una)
2475 else if (++tp->t_dupacks > tcprexmtthresh ||
2476 IN_FASTRECOVERY(tp->t_flags)) {
2477 cc_ack_received(tp, th, CC_DUPACK);
2478 if ((tp->t_flags & TF_SACK_PERMIT) &&
2479 IN_FASTRECOVERY(tp->t_flags)) {
2483 * Compute the amount of data in flight first.
2484 * We can inject new data into the pipe iff
2485 * we have less than 1/2 the original window's
2486 * worth of data in flight.
2488 awnd = (tp->snd_nxt - tp->snd_fack) +
2489 tp->sackhint.sack_bytes_rexmit;
2490 if (awnd < tp->snd_ssthresh) {
2491 tp->snd_cwnd += tp->t_maxseg;
2492 if (tp->snd_cwnd > tp->snd_ssthresh)
2493 tp->snd_cwnd = tp->snd_ssthresh;
2496 tp->snd_cwnd += tp->t_maxseg;
2497 (void) tcp_output(tp);
2499 } else if (tp->t_dupacks == tcprexmtthresh) {
2500 tcp_seq onxt = tp->snd_nxt;
2503 * If we're doing sack, check to
2504 * see if we're already in sack
2505 * recovery. If we're not doing sack,
2506 * check to see if we're in newreno
2509 if (tp->t_flags & TF_SACK_PERMIT) {
2510 if (IN_FASTRECOVERY(tp->t_flags)) {
2515 if (SEQ_LEQ(th->th_ack,
2521 /* Congestion signal before ack. */
2522 cc_cong_signal(tp, th, CC_NDUPACK);
2523 cc_ack_received(tp, th, CC_DUPACK);
2524 tcp_timer_activate(tp, TT_REXMT, 0);
2526 if (tp->t_flags & TF_SACK_PERMIT) {
2528 tcps_sack_recovery_episode);
2529 tp->sack_newdata = tp->snd_nxt;
2530 tp->snd_cwnd = tp->t_maxseg;
2531 (void) tcp_output(tp);
2534 tp->snd_nxt = th->th_ack;
2535 tp->snd_cwnd = tp->t_maxseg;
2536 (void) tcp_output(tp);
2537 KASSERT(tp->snd_limited <= 2,
2538 ("%s: tp->snd_limited too big",
2540 tp->snd_cwnd = tp->snd_ssthresh +
2542 (tp->t_dupacks - tp->snd_limited);
2543 if (SEQ_GT(onxt, tp->snd_nxt))
2546 } else if (V_tcp_do_rfc3042) {
2548 * Process first and second duplicate
2549 * ACKs. Each indicates a segment
2550 * leaving the network, creating room
2551 * for more. Make sure we can send a
2552 * packet on reception of each duplicate
2553 * ACK by increasing snd_cwnd by one
2554 * segment. Restore the original
2555 * snd_cwnd after packet transmission.
2557 cc_ack_received(tp, th, CC_DUPACK);
2558 u_long oldcwnd = tp->snd_cwnd;
2559 tcp_seq oldsndmax = tp->snd_max;
2563 KASSERT(tp->t_dupacks == 1 ||
2565 ("%s: dupacks not 1 or 2",
2567 if (tp->t_dupacks == 1)
2568 tp->snd_limited = 0;
2570 (tp->snd_nxt - tp->snd_una) +
2571 (tp->t_dupacks - tp->snd_limited) *
2574 * Only call tcp_output when there
2575 * is new data available to be sent.
2576 * Otherwise we would send pure ACKs.
2578 SOCKBUF_LOCK(&so->so_snd);
2579 avail = sbavail(&so->so_snd) -
2580 (tp->snd_nxt - tp->snd_una);
2581 SOCKBUF_UNLOCK(&so->so_snd);
2583 (void) tcp_output(tp);
2584 sent = tp->snd_max - oldsndmax;
2585 if (sent > tp->t_maxseg) {
2586 KASSERT((tp->t_dupacks == 2 &&
2587 tp->snd_limited == 0) ||
2588 (sent == tp->t_maxseg + 1 &&
2589 tp->t_flags & TF_SENTFIN),
2590 ("%s: sent too much",
2592 tp->snd_limited = 2;
2593 } else if (sent > 0)
2595 tp->snd_cwnd = oldcwnd;
2603 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2604 ("%s: th_ack <= snd_una", __func__));
2607 * If the congestion window was inflated to account
2608 * for the other side's cached packets, retract it.
2610 if (IN_FASTRECOVERY(tp->t_flags)) {
2611 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2612 if (tp->t_flags & TF_SACK_PERMIT)
2613 tcp_sack_partialack(tp, th);
2615 tcp_newreno_partial_ack(tp, th);
2617 cc_post_recovery(tp, th);
2621 * If we reach this point, ACK is not a duplicate,
2622 * i.e., it ACKs something we sent.
2624 if (tp->t_flags & TF_NEEDSYN) {
2626 * T/TCP: Connection was half-synchronized, and our
2627 * SYN has been ACK'd (so connection is now fully
2628 * synchronized). Go to non-starred state,
2629 * increment snd_una for ACK of SYN, and check if
2630 * we can do window scaling.
2632 tp->t_flags &= ~TF_NEEDSYN;
2634 /* Do window scaling? */
2635 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2636 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2637 tp->rcv_scale = tp->request_r_scale;
2638 /* Send window already scaled. */
2643 INP_WLOCK_ASSERT(tp->t_inpcb);
2645 acked = BYTES_THIS_ACK(tp, th);
2646 TCPSTAT_INC(tcps_rcvackpack);
2647 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2650 * If we just performed our first retransmit, and the ACK
2651 * arrives within our recovery window, then it was a mistake
2652 * to do the retransmit in the first place. Recover our
2653 * original cwnd and ssthresh, and proceed to transmit where
2656 if (tp->t_rxtshift == 1 && tp->t_flags & TF_PREVVALID &&
2657 (int)(ticks - tp->t_badrxtwin) < 0)
2658 cc_cong_signal(tp, th, CC_RTO_ERR);
2661 * If we have a timestamp reply, update smoothed
2662 * round trip time. If no timestamp is present but
2663 * transmit timer is running and timed sequence
2664 * number was acked, update smoothed round trip time.
2665 * Since we now have an rtt measurement, cancel the
2666 * timer backoff (cf., Phil Karn's retransmit alg.).
2667 * Recompute the initial retransmit timer.
2669 * Some boxes send broken timestamp replies
2670 * during the SYN+ACK phase, ignore
2671 * timestamps of 0 or we could calculate a
2672 * huge RTT and blow up the retransmit timer.
2674 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
2677 t = tcp_ts_getticks() - to.to_tsecr;
2678 if (!tp->t_rttlow || tp->t_rttlow > t)
2680 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2681 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2682 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2683 tp->t_rttlow = ticks - tp->t_rtttime;
2684 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2688 * If all outstanding data is acked, stop retransmit
2689 * timer and remember to restart (more output or persist).
2690 * If there is more data to be acked, restart retransmit
2691 * timer, using current (possibly backed-off) value.
2693 if (th->th_ack == tp->snd_max) {
2694 tcp_timer_activate(tp, TT_REXMT, 0);
2696 } else if (!tcp_timer_active(tp, TT_PERSIST))
2697 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2700 * If no data (only SYN) was ACK'd,
2701 * skip rest of ACK processing.
2707 * Let the congestion control algorithm update congestion
2708 * control related information. This typically means increasing
2709 * the congestion window.
2711 cc_ack_received(tp, th, CC_ACK);
2713 SOCKBUF_LOCK(&so->so_snd);
2714 if (acked > sbavail(&so->so_snd)) {
2715 tp->snd_wnd -= sbavail(&so->so_snd);
2716 mfree = sbcut_locked(&so->so_snd,
2717 (int)sbavail(&so->so_snd));
2720 mfree = sbcut_locked(&so->so_snd, acked);
2721 tp->snd_wnd -= acked;
2724 /* NB: sowwakeup_locked() does an implicit unlock. */
2725 sowwakeup_locked(so);
2727 /* Detect una wraparound. */
2728 if (!IN_RECOVERY(tp->t_flags) &&
2729 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2730 SEQ_LEQ(th->th_ack, tp->snd_recover))
2731 tp->snd_recover = th->th_ack - 1;
2732 /* XXXLAS: Can this be moved up into cc_post_recovery? */
2733 if (IN_RECOVERY(tp->t_flags) &&
2734 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2735 EXIT_RECOVERY(tp->t_flags);
2737 tp->snd_una = th->th_ack;
2738 if (tp->t_flags & TF_SACK_PERMIT) {
2739 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2740 tp->snd_recover = tp->snd_una;
2742 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2743 tp->snd_nxt = tp->snd_una;
2745 switch (tp->t_state) {
2748 * In FIN_WAIT_1 STATE in addition to the processing
2749 * for the ESTABLISHED state if our FIN is now acknowledged
2750 * then enter FIN_WAIT_2.
2752 case TCPS_FIN_WAIT_1:
2753 if (ourfinisacked) {
2755 * If we can't receive any more
2756 * data, then closing user can proceed.
2757 * Starting the timer is contrary to the
2758 * specification, but if we don't get a FIN
2759 * we'll hang forever.
2762 * we should release the tp also, and use a
2765 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2766 soisdisconnected(so);
2767 tcp_timer_activate(tp, TT_2MSL,
2768 (tcp_fast_finwait2_recycle ?
2769 tcp_finwait2_timeout :
2772 tcp_state_change(tp, TCPS_FIN_WAIT_2);
2777 * In CLOSING STATE in addition to the processing for
2778 * the ESTABLISHED state if the ACK acknowledges our FIN
2779 * then enter the TIME-WAIT state, otherwise ignore
2783 if (ourfinisacked) {
2784 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2786 INP_INFO_RUNLOCK(&V_tcbinfo);
2793 * In LAST_ACK, we may still be waiting for data to drain
2794 * and/or to be acked, as well as for the ack of our FIN.
2795 * If our FIN is now acknowledged, delete the TCB,
2796 * enter the closed state and return.
2799 if (ourfinisacked) {
2800 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2809 INP_WLOCK_ASSERT(tp->t_inpcb);
2812 * Update window information.
2813 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2815 if ((thflags & TH_ACK) &&
2816 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2817 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2818 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2819 /* keep track of pure window updates */
2821 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2822 TCPSTAT_INC(tcps_rcvwinupd);
2823 tp->snd_wnd = tiwin;
2824 tp->snd_wl1 = th->th_seq;
2825 tp->snd_wl2 = th->th_ack;
2826 if (tp->snd_wnd > tp->max_sndwnd)
2827 tp->max_sndwnd = tp->snd_wnd;
2832 * Process segments with URG.
2834 if ((thflags & TH_URG) && th->th_urp &&
2835 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2837 * This is a kludge, but if we receive and accept
2838 * random urgent pointers, we'll crash in
2839 * soreceive. It's hard to imagine someone
2840 * actually wanting to send this much urgent data.
2842 SOCKBUF_LOCK(&so->so_rcv);
2843 if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
2844 th->th_urp = 0; /* XXX */
2845 thflags &= ~TH_URG; /* XXX */
2846 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2847 goto dodata; /* XXX */
2850 * If this segment advances the known urgent pointer,
2851 * then mark the data stream. This should not happen
2852 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2853 * a FIN has been received from the remote side.
2854 * In these states we ignore the URG.
2856 * According to RFC961 (Assigned Protocols),
2857 * the urgent pointer points to the last octet
2858 * of urgent data. We continue, however,
2859 * to consider it to indicate the first octet
2860 * of data past the urgent section as the original
2861 * spec states (in one of two places).
2863 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2864 tp->rcv_up = th->th_seq + th->th_urp;
2865 so->so_oobmark = sbavail(&so->so_rcv) +
2866 (tp->rcv_up - tp->rcv_nxt) - 1;
2867 if (so->so_oobmark == 0)
2868 so->so_rcv.sb_state |= SBS_RCVATMARK;
2870 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2872 SOCKBUF_UNLOCK(&so->so_rcv);
2874 * Remove out of band data so doesn't get presented to user.
2875 * This can happen independent of advancing the URG pointer,
2876 * but if two URG's are pending at once, some out-of-band
2877 * data may creep in... ick.
2879 if (th->th_urp <= (u_long)tlen &&
2880 !(so->so_options & SO_OOBINLINE)) {
2881 /* hdr drop is delayed */
2882 tcp_pulloutofband(so, th, m, drop_hdrlen);
2886 * If no out of band data is expected,
2887 * pull receive urgent pointer along
2888 * with the receive window.
2890 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2891 tp->rcv_up = tp->rcv_nxt;
2894 INP_WLOCK_ASSERT(tp->t_inpcb);
2897 * Process the segment text, merging it into the TCP sequencing queue,
2898 * and arranging for acknowledgment of receipt if necessary.
2899 * This process logically involves adjusting tp->rcv_wnd as data
2900 * is presented to the user (this happens in tcp_usrreq.c,
2901 * case PRU_RCVD). If a FIN has already been received on this
2902 * connection then we just ignore the text.
2904 if ((tlen || (thflags & TH_FIN)) &&
2905 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2906 tcp_seq save_start = th->th_seq;
2907 m_adj(m, drop_hdrlen); /* delayed header drop */
2909 * Insert segment which includes th into TCP reassembly queue
2910 * with control block tp. Set thflags to whether reassembly now
2911 * includes a segment with FIN. This handles the common case
2912 * inline (segment is the next to be received on an established
2913 * connection, and the queue is empty), avoiding linkage into
2914 * and removal from the queue and repetition of various
2916 * Set DELACK for segments received in order, but ack
2917 * immediately when segments are out of order (so
2918 * fast retransmit can work).
2920 if (th->th_seq == tp->rcv_nxt &&
2921 LIST_EMPTY(&tp->t_segq) &&
2922 TCPS_HAVEESTABLISHED(tp->t_state)) {
2923 if (DELAY_ACK(tp, tlen))
2924 tp->t_flags |= TF_DELACK;
2926 tp->t_flags |= TF_ACKNOW;
2927 tp->rcv_nxt += tlen;
2928 thflags = th->th_flags & TH_FIN;
2929 TCPSTAT_INC(tcps_rcvpack);
2930 TCPSTAT_ADD(tcps_rcvbyte, tlen);
2931 SOCKBUF_LOCK(&so->so_rcv);
2932 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2935 sbappendstream_locked(&so->so_rcv, m, 0);
2936 /* NB: sorwakeup_locked() does an implicit unlock. */
2937 sorwakeup_locked(so);
2940 * XXX: Due to the header drop above "th" is
2941 * theoretically invalid by now. Fortunately
2942 * m_adj() doesn't actually frees any mbufs
2943 * when trimming from the head.
2945 thflags = tcp_reass(tp, th, &tlen, m);
2946 tp->t_flags |= TF_ACKNOW;
2948 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2949 tcp_update_sack_list(tp, save_start, save_start + tlen);
2952 * Note the amount of data that peer has sent into
2953 * our window, in order to estimate the sender's
2957 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
2958 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2960 len = so->so_rcv.sb_hiwat;
2968 * If FIN is received ACK the FIN and let the user know
2969 * that the connection is closing.
2971 if (thflags & TH_FIN) {
2972 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2975 * If connection is half-synchronized
2976 * (ie NEEDSYN flag on) then delay ACK,
2977 * so it may be piggybacked when SYN is sent.
2978 * Otherwise, since we received a FIN then no
2979 * more input can be expected, send ACK now.
2981 if (tp->t_flags & TF_NEEDSYN)
2982 tp->t_flags |= TF_DELACK;
2984 tp->t_flags |= TF_ACKNOW;
2987 switch (tp->t_state) {
2990 * In SYN_RECEIVED and ESTABLISHED STATES
2991 * enter the CLOSE_WAIT state.
2993 case TCPS_SYN_RECEIVED:
2994 tp->t_starttime = ticks;
2996 case TCPS_ESTABLISHED:
2997 tcp_state_change(tp, TCPS_CLOSE_WAIT);
3001 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3002 * enter the CLOSING state.
3004 case TCPS_FIN_WAIT_1:
3005 tcp_state_change(tp, TCPS_CLOSING);
3009 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3010 * starting the time-wait timer, turning off the other
3013 case TCPS_FIN_WAIT_2:
3014 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
3015 KASSERT(ti_locked == TI_RLOCKED, ("%s: dodata "
3016 "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
3020 INP_INFO_RUNLOCK(&V_tcbinfo);
3024 if (ti_locked == TI_RLOCKED)
3025 INP_INFO_RUNLOCK(&V_tcbinfo);
3026 ti_locked = TI_UNLOCKED;
3029 if (so->so_options & SO_DEBUG)
3030 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3033 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
3036 * Return any desired output.
3038 if (needoutput || (tp->t_flags & TF_ACKNOW))
3039 (void) tcp_output(tp);
3042 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
3043 __func__, ti_locked));
3044 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3045 INP_WLOCK_ASSERT(tp->t_inpcb);
3047 if (tp->t_flags & TF_DELACK) {
3048 tp->t_flags &= ~TF_DELACK;
3049 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
3051 INP_WUNLOCK(tp->t_inpcb);
3056 * Generate an ACK dropping incoming segment if it occupies
3057 * sequence space, where the ACK reflects our state.
3059 * We can now skip the test for the RST flag since all
3060 * paths to this code happen after packets containing
3061 * RST have been dropped.
3063 * In the SYN-RECEIVED state, don't send an ACK unless the
3064 * segment we received passes the SYN-RECEIVED ACK test.
3065 * If it fails send a RST. This breaks the loop in the
3066 * "LAND" DoS attack, and also prevents an ACK storm
3067 * between two listening ports that have been sent forged
3068 * SYN segments, each with the source address of the other.
3070 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3071 (SEQ_GT(tp->snd_una, th->th_ack) ||
3072 SEQ_GT(th->th_ack, tp->snd_max)) ) {
3073 rstreason = BANDLIM_RST_OPENPORT;
3077 if (so->so_options & SO_DEBUG)
3078 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3081 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
3082 if (ti_locked == TI_RLOCKED)
3083 INP_INFO_RUNLOCK(&V_tcbinfo);
3084 ti_locked = TI_UNLOCKED;
3086 tp->t_flags |= TF_ACKNOW;
3087 (void) tcp_output(tp);
3088 INP_WUNLOCK(tp->t_inpcb);
3093 if (ti_locked == TI_RLOCKED)
3094 INP_INFO_RUNLOCK(&V_tcbinfo);
3095 ti_locked = TI_UNLOCKED;
3098 tcp_dropwithreset(m, th, tp, tlen, rstreason);
3099 INP_WUNLOCK(tp->t_inpcb);
3101 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3105 if (ti_locked == TI_RLOCKED) {
3106 INP_INFO_RUNLOCK(&V_tcbinfo);
3107 ti_locked = TI_UNLOCKED;
3111 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3115 * Drop space held by incoming segment and return.
3118 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3119 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3122 TCP_PROBE3(debug__input, tp, th, mtod(m, const char *));
3124 INP_WUNLOCK(tp->t_inpcb);
3129 * Issue RST and make ACK acceptable to originator of segment.
3130 * The mbuf must still include the original packet header.
3134 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3135 int tlen, int rstreason)
3141 struct ip6_hdr *ip6;
3145 INP_WLOCK_ASSERT(tp->t_inpcb);
3148 /* Don't bother if destination was broadcast/multicast. */
3149 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3152 if (mtod(m, struct ip *)->ip_v == 6) {
3153 ip6 = mtod(m, struct ip6_hdr *);
3154 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3155 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3157 /* IPv6 anycast check is done at tcp6_input() */
3160 #if defined(INET) && defined(INET6)
3165 ip = mtod(m, struct ip *);
3166 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3167 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3168 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3169 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3174 /* Perform bandwidth limiting. */
3175 if (badport_bandlim(rstreason) < 0)
3178 /* tcp_respond consumes the mbuf chain. */
3179 if (th->th_flags & TH_ACK) {
3180 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3181 th->th_ack, TH_RST);
3183 if (th->th_flags & TH_SYN)
3185 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3186 (tcp_seq)0, TH_RST|TH_ACK);
3194 * Parse TCP options and place in tcpopt.
3197 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3202 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3204 if (opt == TCPOPT_EOL)
3206 if (opt == TCPOPT_NOP)
3212 if (optlen < 2 || optlen > cnt)
3217 if (optlen != TCPOLEN_MAXSEG)
3219 if (!(flags & TO_SYN))
3221 to->to_flags |= TOF_MSS;
3222 bcopy((char *)cp + 2,
3223 (char *)&to->to_mss, sizeof(to->to_mss));
3224 to->to_mss = ntohs(to->to_mss);
3227 if (optlen != TCPOLEN_WINDOW)
3229 if (!(flags & TO_SYN))
3231 to->to_flags |= TOF_SCALE;
3232 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3234 case TCPOPT_TIMESTAMP:
3235 if (optlen != TCPOLEN_TIMESTAMP)
3237 to->to_flags |= TOF_TS;
3238 bcopy((char *)cp + 2,
3239 (char *)&to->to_tsval, sizeof(to->to_tsval));
3240 to->to_tsval = ntohl(to->to_tsval);
3241 bcopy((char *)cp + 6,
3242 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3243 to->to_tsecr = ntohl(to->to_tsecr);
3245 #ifdef TCP_SIGNATURE
3247 * XXX In order to reply to a host which has set the
3248 * TCP_SIGNATURE option in its initial SYN, we have to
3249 * record the fact that the option was observed here
3250 * for the syncache code to perform the correct response.
3252 case TCPOPT_SIGNATURE:
3253 if (optlen != TCPOLEN_SIGNATURE)
3255 to->to_flags |= TOF_SIGNATURE;
3256 to->to_signature = cp + 2;
3259 case TCPOPT_SACK_PERMITTED:
3260 if (optlen != TCPOLEN_SACK_PERMITTED)
3262 if (!(flags & TO_SYN))
3266 to->to_flags |= TOF_SACKPERM;
3269 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3273 to->to_flags |= TOF_SACK;
3274 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3275 to->to_sacks = cp + 2;
3276 TCPSTAT_INC(tcps_sack_rcv_blocks);
3285 * Pull out of band byte out of a segment so
3286 * it doesn't appear in the user's data queue.
3287 * It is still reflected in the segment length for
3288 * sequencing purposes.
3291 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3294 int cnt = off + th->th_urp - 1;
3297 if (m->m_len > cnt) {
3298 char *cp = mtod(m, caddr_t) + cnt;
3299 struct tcpcb *tp = sototcpcb(so);
3301 INP_WLOCK_ASSERT(tp->t_inpcb);
3304 tp->t_oobflags |= TCPOOB_HAVEDATA;
3305 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3307 if (m->m_flags & M_PKTHDR)
3316 panic("tcp_pulloutofband");
3320 * Collect new round-trip time estimate
3321 * and update averages and current timeout.
3324 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3328 INP_WLOCK_ASSERT(tp->t_inpcb);
3330 TCPSTAT_INC(tcps_rttupdated);
3332 if (tp->t_srtt != 0) {
3334 * srtt is stored as fixed point with 5 bits after the
3335 * binary point (i.e., scaled by 8). The following magic
3336 * is equivalent to the smoothing algorithm in rfc793 with
3337 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3338 * point). Adjust rtt to origin 0.
3340 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3341 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3343 if ((tp->t_srtt += delta) <= 0)
3347 * We accumulate a smoothed rtt variance (actually, a
3348 * smoothed mean difference), then set the retransmit
3349 * timer to smoothed rtt + 4 times the smoothed variance.
3350 * rttvar is stored as fixed point with 4 bits after the
3351 * binary point (scaled by 16). The following is
3352 * equivalent to rfc793 smoothing with an alpha of .75
3353 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3354 * rfc793's wired-in beta.
3358 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3359 if ((tp->t_rttvar += delta) <= 0)
3361 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3362 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3365 * No rtt measurement yet - use the unsmoothed rtt.
3366 * Set the variance to half the rtt (so our first
3367 * retransmit happens at 3*rtt).
3369 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3370 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3371 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3377 * the retransmit should happen at rtt + 4 * rttvar.
3378 * Because of the way we do the smoothing, srtt and rttvar
3379 * will each average +1/2 tick of bias. When we compute
3380 * the retransmit timer, we want 1/2 tick of rounding and
3381 * 1 extra tick because of +-1/2 tick uncertainty in the
3382 * firing of the timer. The bias will give us exactly the
3383 * 1.5 tick we need. But, because the bias is
3384 * statistical, we have to test that we don't drop below
3385 * the minimum feasible timer (which is 2 ticks).
3387 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3388 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3391 * We received an ack for a packet that wasn't retransmitted;
3392 * it is probably safe to discard any error indications we've
3393 * received recently. This isn't quite right, but close enough
3394 * for now (a route might have failed after we sent a segment,
3395 * and the return path might not be symmetrical).
3397 tp->t_softerror = 0;
3401 * Determine a reasonable value for maxseg size.
3402 * If the route is known, check route for mtu.
3403 * If none, use an mss that can be handled on the outgoing interface
3404 * without forcing IP to fragment. If no route is found, route has no mtu,
3405 * or the destination isn't local, use a default, hopefully conservative
3406 * size (usually 512 or the default IP max size, but no more than the mtu
3407 * of the interface), as we can't discover anything about intervening
3408 * gateways or networks. We also initialize the congestion/slow start
3409 * window to be a single segment if the destination isn't local.
3410 * While looking at the routing entry, we also initialize other path-dependent
3411 * parameters from pre-set or cached values in the routing entry.
3413 * Also take into account the space needed for options that we
3414 * send regularly. Make maxseg shorter by that amount to assure
3415 * that we can send maxseg amount of data even when the options
3416 * are present. Store the upper limit of the length of options plus
3419 * NOTE that this routine is only called when we process an incoming
3420 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3421 * settings are handled in tcp_mssopt().
3424 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
3425 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3429 struct inpcb *inp = tp->t_inpcb;
3430 struct hc_metrics_lite metrics;
3433 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3434 size_t min_protoh = isipv6 ?
3435 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3436 sizeof (struct tcpiphdr);
3438 const size_t min_protoh = sizeof(struct tcpiphdr);
3441 INP_WLOCK_ASSERT(tp->t_inpcb);
3443 if (mtuoffer != -1) {
3444 KASSERT(offer == -1, ("%s: conflict", __func__));
3445 offer = mtuoffer - min_protoh;
3452 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
3453 tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt;
3456 #if defined(INET) && defined(INET6)
3461 maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
3462 tp->t_maxopd = tp->t_maxseg = V_tcp_mssdflt;
3467 * No route to sender, stay with default mss and return.
3471 * In case we return early we need to initialize metrics
3472 * to a defined state as tcp_hc_get() would do for us
3473 * if there was no cache hit.
3475 if (metricptr != NULL)
3476 bzero(metricptr, sizeof(struct hc_metrics_lite));
3480 /* What have we got? */
3484 * Offer == 0 means that there was no MSS on the SYN
3485 * segment, in this case we use tcp_mssdflt as
3486 * already assigned to t_maxopd above.
3488 offer = tp->t_maxopd;
3493 * Offer == -1 means that we didn't receive SYN yet.
3499 * Prevent DoS attack with too small MSS. Round up
3500 * to at least minmss.
3502 offer = max(offer, V_tcp_minmss);
3506 * rmx information is now retrieved from tcp_hostcache.
3508 tcp_hc_get(&inp->inp_inc, &metrics);
3509 if (metricptr != NULL)
3510 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3513 * If there's a discovered mtu in tcp hostcache, use it.
3514 * Else, use the link mtu.
3516 if (metrics.rmx_mtu)
3517 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3521 mss = maxmtu - min_protoh;
3522 if (!V_path_mtu_discovery &&
3523 !in6_localaddr(&inp->in6p_faddr))
3524 mss = min(mss, V_tcp_v6mssdflt);
3527 #if defined(INET) && defined(INET6)
3532 mss = maxmtu - min_protoh;
3533 if (!V_path_mtu_discovery &&
3534 !in_localaddr(inp->inp_faddr))
3535 mss = min(mss, V_tcp_mssdflt);
3539 * XXX - The above conditional (mss = maxmtu - min_protoh)
3540 * probably violates the TCP spec.
3541 * The problem is that, since we don't know the
3542 * other end's MSS, we are supposed to use a conservative
3543 * default. But, if we do that, then MTU discovery will
3544 * never actually take place, because the conservative
3545 * default is much less than the MTUs typically seen
3546 * on the Internet today. For the moment, we'll sweep
3547 * this under the carpet.
3549 * The conservative default might not actually be a problem
3550 * if the only case this occurs is when sending an initial
3551 * SYN with options and data to a host we've never talked
3552 * to before. Then, they will reply with an MSS value which
3553 * will get recorded and the new parameters should get
3554 * recomputed. For Further Study.
3557 mss = min(mss, offer);
3560 * Sanity check: make sure that maxopd will be large
3561 * enough to allow some data on segments even if the
3562 * all the option space is used (40bytes). Otherwise
3563 * funny things may happen in tcp_output.
3568 * maxopd stores the maximum length of data AND options
3569 * in a segment; maxseg is the amount of data in a normal
3570 * segment. We need to store this value (maxopd) apart
3571 * from maxseg, because now every segment carries options
3572 * and thus we normally have somewhat less data in segments.
3577 * origoffer==-1 indicates that no segments were received yet.
3578 * In this case we just guess.
3580 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3582 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3583 mss -= TCPOLEN_TSTAMP_APPA;
3589 tcp_mss(struct tcpcb *tp, int offer)
3595 struct hc_metrics_lite metrics;
3596 struct tcp_ifcap cap;
3598 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3600 bzero(&cap, sizeof(cap));
3601 tcp_mss_update(tp, offer, -1, &metrics, &cap);
3607 * If there's a pipesize, change the socket buffer to that size,
3608 * don't change if sb_hiwat is different than default (then it
3609 * has been changed on purpose with setsockopt).
3610 * Make the socket buffers an integral number of mss units;
3611 * if the mss is larger than the socket buffer, decrease the mss.
3613 so = inp->inp_socket;
3614 SOCKBUF_LOCK(&so->so_snd);
3615 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
3616 bufsize = metrics.rmx_sendpipe;
3618 bufsize = so->so_snd.sb_hiwat;
3622 bufsize = roundup(bufsize, mss);
3623 if (bufsize > sb_max)
3625 if (bufsize > so->so_snd.sb_hiwat)
3626 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3628 SOCKBUF_UNLOCK(&so->so_snd);
3631 SOCKBUF_LOCK(&so->so_rcv);
3632 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
3633 bufsize = metrics.rmx_recvpipe;
3635 bufsize = so->so_rcv.sb_hiwat;
3636 if (bufsize > mss) {
3637 bufsize = roundup(bufsize, mss);
3638 if (bufsize > sb_max)
3640 if (bufsize > so->so_rcv.sb_hiwat)
3641 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3643 SOCKBUF_UNLOCK(&so->so_rcv);
3645 /* Check the interface for TSO capabilities. */
3646 if (cap.ifcap & CSUM_TSO) {
3647 tp->t_flags |= TF_TSO;
3648 tp->t_tsomax = cap.tsomax;
3649 tp->t_tsomaxsegcount = cap.tsomaxsegcount;
3650 tp->t_tsomaxsegsize = cap.tsomaxsegsize;
3655 * Determine the MSS option to send on an outgoing SYN.
3658 tcp_mssopt(struct in_conninfo *inc)
3665 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3668 if (inc->inc_flags & INC_ISIPV6) {
3669 mss = V_tcp_v6mssdflt;
3670 maxmtu = tcp_maxmtu6(inc, NULL);
3671 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3674 #if defined(INET) && defined(INET6)
3679 mss = V_tcp_mssdflt;
3680 maxmtu = tcp_maxmtu(inc, NULL);
3681 min_protoh = sizeof(struct tcpiphdr);
3684 #if defined(INET6) || defined(INET)
3685 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3688 if (maxmtu && thcmtu)
3689 mss = min(maxmtu, thcmtu) - min_protoh;
3690 else if (maxmtu || thcmtu)
3691 mss = max(maxmtu, thcmtu) - min_protoh;
3698 * On a partial ack arrives, force the retransmission of the
3699 * next unacknowledged segment. Do not clear tp->t_dupacks.
3700 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3704 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3706 tcp_seq onxt = tp->snd_nxt;
3707 u_long ocwnd = tp->snd_cwnd;
3709 INP_WLOCK_ASSERT(tp->t_inpcb);
3711 tcp_timer_activate(tp, TT_REXMT, 0);
3713 tp->snd_nxt = th->th_ack;
3715 * Set snd_cwnd to one segment beyond acknowledged offset.
3716 * (tp->snd_una has not yet been updated when this function is called.)
3718 tp->snd_cwnd = tp->t_maxseg + BYTES_THIS_ACK(tp, th);
3719 tp->t_flags |= TF_ACKNOW;
3720 (void) tcp_output(tp);
3721 tp->snd_cwnd = ocwnd;
3722 if (SEQ_GT(onxt, tp->snd_nxt))
3725 * Partial window deflation. Relies on fact that tp->snd_una
3728 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3729 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3732 tp->snd_cwnd += tp->t_maxseg;