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>
66 #include <sys/signalvar.h>
67 #include <sys/socket.h>
68 #include <sys/socketvar.h>
69 #include <sys/sysctl.h>
70 #include <sys/syslog.h>
71 #include <sys/systm.h>
73 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
78 #include <net/route.h>
81 #define TCPSTATES /* for logging */
83 #include <netinet/cc.h>
84 #include <netinet/in.h>
85 #include <netinet/in_pcb.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/in_var.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> /* required for icmp_var.h */
90 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
91 #include <netinet/ip_var.h>
92 #include <netinet/ip_options.h>
93 #include <netinet/ip6.h>
94 #include <netinet/icmp6.h>
95 #include <netinet6/in6_pcb.h>
96 #include <netinet6/ip6_var.h>
97 #include <netinet6/nd6.h>
98 #include <netinet/tcp_fsm.h>
99 #include <netinet/tcp_seq.h>
100 #include <netinet/tcp_timer.h>
101 #include <netinet/tcp_var.h>
102 #include <netinet6/tcp6_var.h>
103 #include <netinet/tcpip.h>
104 #include <netinet/tcp_syncache.h>
106 #include <netinet/tcp_debug.h>
107 #endif /* TCPDEBUG */
109 #include <netinet/tcp_offload.h>
113 #include <netipsec/ipsec.h>
114 #include <netipsec/ipsec6.h>
117 #include <machine/in_cksum.h>
119 #include <security/mac/mac_framework.h>
121 const int tcprexmtthresh = 3;
123 int tcp_log_in_vain = 0;
124 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
126 "Log all incoming TCP segments to closed ports");
128 VNET_DEFINE(int, blackhole) = 0;
129 #define V_blackhole VNET(blackhole)
130 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
131 &VNET_NAME(blackhole), 0,
132 "Do not send RST on segments to closed ports");
134 VNET_DEFINE(int, tcp_delack_enabled) = 1;
135 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
136 &VNET_NAME(tcp_delack_enabled), 0,
137 "Delay ACK to try and piggyback it onto a data packet");
139 VNET_DEFINE(int, drop_synfin) = 0;
140 #define V_drop_synfin VNET(drop_synfin)
141 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
142 &VNET_NAME(drop_synfin), 0,
143 "Drop TCP packets with SYN+FIN set");
145 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
146 #define V_tcp_do_rfc3042 VNET(tcp_do_rfc3042)
147 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
148 &VNET_NAME(tcp_do_rfc3042), 0,
149 "Enable RFC 3042 (Limited Transmit)");
151 VNET_DEFINE(int, tcp_do_rfc3390) = 1;
152 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
153 &VNET_NAME(tcp_do_rfc3390), 0,
154 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
156 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, experimental, CTLFLAG_RW, 0,
157 "Experimental TCP extensions");
159 VNET_DEFINE(int, tcp_do_initcwnd10) = 1;
160 SYSCTL_VNET_INT(_net_inet_tcp_experimental, OID_AUTO, initcwnd10, CTLFLAG_RW,
161 &VNET_NAME(tcp_do_initcwnd10), 0,
162 "Enable draft-ietf-tcpm-initcwnd-05 (Increasing initial CWND to 10)");
164 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
165 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_RW,
166 &VNET_NAME(tcp_do_rfc3465), 0,
167 "Enable RFC 3465 (Appropriate Byte Counting)");
169 VNET_DEFINE(int, tcp_abc_l_var) = 2;
170 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_RW,
171 &VNET_NAME(tcp_abc_l_var), 2,
172 "Cap the max cwnd increment during slow-start to this number of segments");
174 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
176 VNET_DEFINE(int, tcp_do_ecn) = 0;
177 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_RW,
178 &VNET_NAME(tcp_do_ecn), 0,
181 VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
182 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_RW,
183 &VNET_NAME(tcp_ecn_maxretries), 0,
184 "Max retries before giving up on ECN");
186 VNET_DEFINE(int, tcp_insecure_rst) = 0;
187 #define V_tcp_insecure_rst VNET(tcp_insecure_rst)
188 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
189 &VNET_NAME(tcp_insecure_rst), 0,
190 "Follow the old (insecure) criteria for accepting RST packets");
192 VNET_DEFINE(int, tcp_recvspace) = 1024*64;
193 #define V_tcp_recvspace VNET(tcp_recvspace)
194 SYSCTL_VNET_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
195 &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
197 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
198 #define V_tcp_do_autorcvbuf VNET(tcp_do_autorcvbuf)
199 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
200 &VNET_NAME(tcp_do_autorcvbuf), 0,
201 "Enable automatic receive buffer sizing");
203 VNET_DEFINE(int, tcp_autorcvbuf_inc) = 16*1024;
204 #define V_tcp_autorcvbuf_inc VNET(tcp_autorcvbuf_inc)
205 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
206 &VNET_NAME(tcp_autorcvbuf_inc), 0,
207 "Incrementor step size of automatic receive buffer");
209 VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
210 #define V_tcp_autorcvbuf_max VNET(tcp_autorcvbuf_max)
211 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
212 &VNET_NAME(tcp_autorcvbuf_max), 0,
213 "Max size of automatic receive buffer");
215 VNET_DEFINE(struct inpcbhead, tcb);
216 #define tcb6 tcb /* for KAME src sync over BSD*'s */
217 VNET_DEFINE(struct inpcbinfo, tcbinfo);
219 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
220 static void tcp_do_segment(struct mbuf *, struct tcphdr *,
221 struct socket *, struct tcpcb *, int, int, uint8_t,
223 static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
224 struct tcpcb *, int, int);
225 static void tcp_pulloutofband(struct socket *,
226 struct tcphdr *, struct mbuf *, int);
227 static void tcp_xmit_timer(struct tcpcb *, int);
228 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
229 static void inline tcp_fields_to_host(struct tcphdr *);
231 static void inline tcp_fields_to_net(struct tcphdr *);
232 static int inline tcp_signature_verify_input(struct mbuf *, int, int,
233 int, struct tcpopt *, struct tcphdr *, u_int);
235 static void inline cc_ack_received(struct tcpcb *tp, struct tcphdr *th,
237 static void inline cc_conn_init(struct tcpcb *tp);
238 static void inline cc_post_recovery(struct tcpcb *tp, struct tcphdr *th);
239 static void inline hhook_run_tcp_est_in(struct tcpcb *tp,
240 struct tcphdr *th, struct tcpopt *to);
243 * TCP statistics are stored in struct tcpstat_p, which is
244 * an "array" of counter(9)s. Although it isn't a real
245 * array, we treat it as array to reduce code bloat.
247 VNET_DEFINE(struct tcpstat_p, tcpstatp);
250 vnet_tcpstatp_init(const void *unused)
255 for (i = 0, c = (counter_u64_t *)&V_tcpstatp;
256 i < sizeof(V_tcpstatp) / sizeof(counter_u64_t);
258 *c = counter_u64_alloc(M_WAITOK);
259 counter_u64_zero(*c);
262 VNET_SYSINIT(vnet_tcpstatp_init, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
263 vnet_tcpstatp_init, NULL);
267 vnet_tcpstatp_uninit(const void *unused)
272 for (i = 0, c = (counter_u64_t *)&V_tcpstatp;
273 i < sizeof(V_tcpstatp) / sizeof(counter_u64_t);
275 counter_u64_free(*c);
277 VNET_SYSUNINIT(vnet_tcpstatp_uninit, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
278 vnet_tcpstatp_uninit, NULL);
282 tcpstat_sysctl(SYSCTL_HANDLER_ARGS)
284 struct tcpstat tcpstat;
289 for (i = 0, c = (counter_u64_t *)&V_tcpstatp, v = (uint64_t *)&tcpstat;
290 i < sizeof(V_tcpstatp) / sizeof(counter_u64_t);
292 *v = counter_u64_fetch(*c);
294 counter_u64_zero(*c);
297 return (SYSCTL_OUT(req, &tcpstat, sizeof(tcpstat)));
300 SYSCTL_VNET_PROC(_net_inet_tcp, TCPCTL_STATS, stats, CTLTYPE_OPAQUE |
301 CTLFLAG_RW, NULL, 0, tcpstat_sysctl, "I",
302 "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
305 * Kernel module interface for updating tcpstat. The argument is an index
306 * into tcpstat treated as an array.
309 kmod_tcpstat_inc(int statnum)
312 counter_u64_add(*((counter_u64_t *)&V_tcpstatp + statnum), 1);
316 * Wrapper for the TCP established input helper hook.
319 hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
321 struct tcp_hhook_data hhook_data;
323 if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
328 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
334 * CC wrapper hook functions
337 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t type)
339 INP_WLOCK_ASSERT(tp->t_inpcb);
341 tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
342 if (tp->snd_cwnd <= tp->snd_wnd)
343 tp->ccv->flags |= CCF_CWND_LIMITED;
345 tp->ccv->flags &= ~CCF_CWND_LIMITED;
347 if (type == CC_ACK) {
348 if (tp->snd_cwnd > tp->snd_ssthresh) {
349 tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
350 V_tcp_abc_l_var * tp->t_maxseg);
351 if (tp->t_bytes_acked >= tp->snd_cwnd) {
352 tp->t_bytes_acked -= tp->snd_cwnd;
353 tp->ccv->flags |= CCF_ABC_SENTAWND;
356 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
357 tp->t_bytes_acked = 0;
361 if (CC_ALGO(tp)->ack_received != NULL) {
362 /* XXXLAS: Find a way to live without this */
363 tp->ccv->curack = th->th_ack;
364 CC_ALGO(tp)->ack_received(tp->ccv, type);
369 cc_conn_init(struct tcpcb *tp)
371 struct hc_metrics_lite metrics;
372 struct inpcb *inp = tp->t_inpcb;
375 INP_WLOCK_ASSERT(tp->t_inpcb);
377 tcp_hc_get(&inp->inp_inc, &metrics);
379 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
381 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
382 TCPSTAT_INC(tcps_usedrtt);
383 if (metrics.rmx_rttvar) {
384 tp->t_rttvar = metrics.rmx_rttvar;
385 TCPSTAT_INC(tcps_usedrttvar);
387 /* default variation is +- 1 rtt */
389 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
391 TCPT_RANGESET(tp->t_rxtcur,
392 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
393 tp->t_rttmin, TCPTV_REXMTMAX);
395 if (metrics.rmx_ssthresh) {
397 * There's some sort of gateway or interface
398 * buffer limit on the path. Use this to set
399 * the slow start threshhold, but set the
400 * threshold to no less than 2*mss.
402 tp->snd_ssthresh = max(2 * tp->t_maxseg, metrics.rmx_ssthresh);
403 TCPSTAT_INC(tcps_usedssthresh);
407 * Set the initial slow-start flight size.
409 * RFC5681 Section 3.1 specifies the default conservative values.
410 * RFC3390 specifies slightly more aggressive values.
411 * Draft-ietf-tcpm-initcwnd-05 increases it to ten segments.
413 * If a SYN or SYN/ACK was lost and retransmitted, we have to
414 * reduce the initial CWND to one segment as congestion is likely
415 * requiring us to be cautious.
417 if (tp->snd_cwnd == 1)
418 tp->snd_cwnd = tp->t_maxseg; /* SYN(-ACK) lost */
419 else if (V_tcp_do_initcwnd10)
420 tp->snd_cwnd = min(10 * tp->t_maxseg,
421 max(2 * tp->t_maxseg, 14600));
422 else if (V_tcp_do_rfc3390)
423 tp->snd_cwnd = min(4 * tp->t_maxseg,
424 max(2 * tp->t_maxseg, 4380));
426 /* Per RFC5681 Section 3.1 */
427 if (tp->t_maxseg > 2190)
428 tp->snd_cwnd = 2 * tp->t_maxseg;
429 else if (tp->t_maxseg > 1095)
430 tp->snd_cwnd = 3 * tp->t_maxseg;
432 tp->snd_cwnd = 4 * tp->t_maxseg;
435 if (CC_ALGO(tp)->conn_init != NULL)
436 CC_ALGO(tp)->conn_init(tp->ccv);
440 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
442 INP_WLOCK_ASSERT(tp->t_inpcb);
446 if (!IN_FASTRECOVERY(tp->t_flags)) {
447 tp->snd_recover = tp->snd_max;
448 if (tp->t_flags & TF_ECN_PERMIT)
449 tp->t_flags |= TF_ECN_SND_CWR;
453 if (!IN_CONGRECOVERY(tp->t_flags)) {
454 TCPSTAT_INC(tcps_ecn_rcwnd);
455 tp->snd_recover = tp->snd_max;
456 if (tp->t_flags & TF_ECN_PERMIT)
457 tp->t_flags |= TF_ECN_SND_CWR;
462 tp->t_bytes_acked = 0;
463 EXIT_RECOVERY(tp->t_flags);
464 tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
465 tp->t_maxseg) * tp->t_maxseg;
466 tp->snd_cwnd = tp->t_maxseg;
469 TCPSTAT_INC(tcps_sndrexmitbad);
470 /* RTO was unnecessary, so reset everything. */
471 tp->snd_cwnd = tp->snd_cwnd_prev;
472 tp->snd_ssthresh = tp->snd_ssthresh_prev;
473 tp->snd_recover = tp->snd_recover_prev;
474 if (tp->t_flags & TF_WASFRECOVERY)
475 ENTER_FASTRECOVERY(tp->t_flags);
476 if (tp->t_flags & TF_WASCRECOVERY)
477 ENTER_CONGRECOVERY(tp->t_flags);
478 tp->snd_nxt = tp->snd_max;
479 tp->t_flags &= ~TF_PREVVALID;
484 if (CC_ALGO(tp)->cong_signal != NULL) {
486 tp->ccv->curack = th->th_ack;
487 CC_ALGO(tp)->cong_signal(tp->ccv, type);
492 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
494 INP_WLOCK_ASSERT(tp->t_inpcb);
496 /* XXXLAS: KASSERT that we're in recovery? */
498 if (CC_ALGO(tp)->post_recovery != NULL) {
499 tp->ccv->curack = th->th_ack;
500 CC_ALGO(tp)->post_recovery(tp->ccv);
502 /* XXXLAS: EXIT_RECOVERY ? */
503 tp->t_bytes_acked = 0;
507 tcp_fields_to_host(struct tcphdr *th)
510 th->th_seq = ntohl(th->th_seq);
511 th->th_ack = ntohl(th->th_ack);
512 th->th_win = ntohs(th->th_win);
513 th->th_urp = ntohs(th->th_urp);
518 tcp_fields_to_net(struct tcphdr *th)
521 th->th_seq = htonl(th->th_seq);
522 th->th_ack = htonl(th->th_ack);
523 th->th_win = htons(th->th_win);
524 th->th_urp = htons(th->th_urp);
528 tcp_signature_verify_input(struct mbuf *m, int off0, int tlen, int optlen,
529 struct tcpopt *to, struct tcphdr *th, u_int tcpbflag)
533 tcp_fields_to_net(th);
534 ret = tcp_signature_verify(m, off0, tlen, optlen, to, th, tcpbflag);
535 tcp_fields_to_host(th);
540 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
542 #define ND6_HINT(tp) \
544 if ((tp) && (tp)->t_inpcb && \
545 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
546 nd6_nud_hint(NULL, NULL, 0); \
553 * Indicate whether this ack should be delayed. We can delay the ack if
554 * - there is no delayed ack timer in progress and
555 * - our last ack wasn't a 0-sized window. We never want to delay
556 * the ack that opens up a 0-sized window and
557 * - delayed acks are enabled or
558 * - this is a half-synchronized T/TCP connection.
560 #define DELAY_ACK(tp) \
561 ((!tcp_timer_active(tp, TT_DELACK) && \
562 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
563 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
566 * TCP input handling is split into multiple parts:
567 * tcp6_input is a thin wrapper around tcp_input for the extended
568 * ip6_protox[] call format in ip6_input
569 * tcp_input handles primary segment validation, inpcb lookup and
570 * SYN processing on listen sockets
571 * tcp_do_segment processes the ACK and text of the segment for
572 * establishing, established and closing connections
576 tcp6_input(struct mbuf **mp, int *offp, int proto)
578 struct mbuf *m = *mp;
579 struct in6_ifaddr *ia6;
581 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
584 * draft-itojun-ipv6-tcp-to-anycast
585 * better place to put this in?
587 ia6 = ip6_getdstifaddr(m);
588 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
591 ifa_free(&ia6->ia_ifa);
592 ip6 = mtod(m, struct ip6_hdr *);
593 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
594 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
598 ifa_free(&ia6->ia_ifa);
606 tcp_input(struct mbuf *m, int off0)
608 struct tcphdr *th = NULL;
609 struct ip *ip = NULL;
610 struct inpcb *inp = NULL;
611 struct tcpcb *tp = NULL;
612 struct socket *so = NULL;
621 int rstreason = 0; /* For badport_bandlim accounting purposes */
623 uint8_t sig_checked = 0;
626 struct m_tag *fwd_tag = NULL;
628 struct ip6_hdr *ip6 = NULL;
631 const void *ip6 = NULL;
633 struct tcpopt to; /* options in this segment */
634 char *s = NULL; /* address and port logging */
636 #define TI_UNLOCKED 1
641 * The size of tcp_saveipgen must be the size of the max ip header,
644 u_char tcp_saveipgen[IP6_HDR_LEN];
645 struct tcphdr tcp_savetcp;
650 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
654 TCPSTAT_INC(tcps_rcvtotal);
658 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
660 if (m->m_len < (sizeof(*ip6) + sizeof(*th))) {
661 m = m_pullup(m, sizeof(*ip6) + sizeof(*th));
663 TCPSTAT_INC(tcps_rcvshort);
668 ip6 = mtod(m, struct ip6_hdr *);
669 th = (struct tcphdr *)((caddr_t)ip6 + off0);
670 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
671 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
672 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
673 th->th_sum = m->m_pkthdr.csum_data;
675 th->th_sum = in6_cksum_pseudo(ip6, tlen,
676 IPPROTO_TCP, m->m_pkthdr.csum_data);
677 th->th_sum ^= 0xffff;
679 th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
681 TCPSTAT_INC(tcps_rcvbadsum);
686 * Be proactive about unspecified IPv6 address in source.
687 * As we use all-zero to indicate unbounded/unconnected pcb,
688 * unspecified IPv6 address can be used to confuse us.
690 * Note that packets with unspecified IPv6 destination is
691 * already dropped in ip6_input.
693 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
699 #if defined(INET) && defined(INET6)
705 * Get IP and TCP header together in first mbuf.
706 * Note: IP leaves IP header in first mbuf.
708 if (off0 > sizeof (struct ip)) {
710 off0 = sizeof(struct ip);
712 if (m->m_len < sizeof (struct tcpiphdr)) {
713 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
715 TCPSTAT_INC(tcps_rcvshort);
719 ip = mtod(m, struct ip *);
720 th = (struct tcphdr *)((caddr_t)ip + off0);
721 tlen = ntohs(ip->ip_len) - off0;
723 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
724 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
725 th->th_sum = m->m_pkthdr.csum_data;
727 th->th_sum = in_pseudo(ip->ip_src.s_addr,
729 htonl(m->m_pkthdr.csum_data + tlen +
731 th->th_sum ^= 0xffff;
733 struct ipovly *ipov = (struct ipovly *)ip;
736 * Checksum extended TCP header and data.
739 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
740 ipov->ih_len = htons(tlen);
741 th->th_sum = in_cksum(m, len);
744 TCPSTAT_INC(tcps_rcvbadsum);
747 /* Re-initialization for later version check */
748 ip->ip_v = IPVERSION;
754 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
756 #if defined(INET) && defined(INET6)
764 * Check that TCP offset makes sense,
765 * pull out TCP options and adjust length. XXX
767 off = th->th_off << 2;
768 if (off < sizeof (struct tcphdr) || off > tlen) {
769 TCPSTAT_INC(tcps_rcvbadoff);
772 tlen -= off; /* tlen is used instead of ti->ti_len */
773 if (off > sizeof (struct tcphdr)) {
776 IP6_EXTHDR_CHECK(m, off0, off, );
777 ip6 = mtod(m, struct ip6_hdr *);
778 th = (struct tcphdr *)((caddr_t)ip6 + off0);
781 #if defined(INET) && defined(INET6)
786 if (m->m_len < sizeof(struct ip) + off) {
787 if ((m = m_pullup(m, sizeof (struct ip) + off))
789 TCPSTAT_INC(tcps_rcvshort);
792 ip = mtod(m, struct ip *);
793 th = (struct tcphdr *)((caddr_t)ip + off0);
797 optlen = off - sizeof (struct tcphdr);
798 optp = (u_char *)(th + 1);
800 thflags = th->th_flags;
803 * Convert TCP protocol specific fields to host format.
805 tcp_fields_to_host(th);
808 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
810 drop_hdrlen = off0 + off;
813 * Locate pcb for segment; if we're likely to add or remove a
814 * connection then first acquire pcbinfo lock. There are two cases
815 * where we might discover later we need a write lock despite the
816 * flags: ACKs moving a connection out of the syncache, and ACKs for
817 * a connection in TIMEWAIT.
819 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0) {
820 INP_INFO_WLOCK(&V_tcbinfo);
821 ti_locked = TI_WLOCKED;
823 ti_locked = TI_UNLOCKED;
826 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
830 (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
832 || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
835 #if defined(INET) && !defined(INET6)
836 (m->m_flags & M_IP_NEXTHOP)
839 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
843 if (ti_locked == TI_WLOCKED) {
844 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
846 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
850 if (isipv6 && fwd_tag != NULL) {
851 struct sockaddr_in6 *next_hop6;
853 next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
855 * Transparently forwarded. Pretend to be the destination.
856 * Already got one like this?
858 inp = in6_pcblookup_mbuf(&V_tcbinfo,
859 &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
860 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif, m);
863 * It's new. Try to find the ambushing socket.
864 * Because we've rewritten the destination address,
865 * any hardware-generated hash is ignored.
867 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
868 th->th_sport, &next_hop6->sin6_addr,
869 next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
870 th->th_dport, INPLOOKUP_WILDCARD |
871 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
874 inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
875 th->th_sport, &ip6->ip6_dst, th->th_dport,
876 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
877 m->m_pkthdr.rcvif, m);
880 #if defined(INET6) && defined(INET)
884 if (fwd_tag != NULL) {
885 struct sockaddr_in *next_hop;
887 next_hop = (struct sockaddr_in *)(fwd_tag+1);
889 * Transparently forwarded. Pretend to be the destination.
890 * already got one like this?
892 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
893 ip->ip_dst, th->th_dport, INPLOOKUP_WLOCKPCB,
894 m->m_pkthdr.rcvif, m);
897 * It's new. Try to find the ambushing socket.
898 * Because we've rewritten the destination address,
899 * any hardware-generated hash is ignored.
901 inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
902 th->th_sport, next_hop->sin_addr,
903 next_hop->sin_port ? ntohs(next_hop->sin_port) :
904 th->th_dport, INPLOOKUP_WILDCARD |
905 INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
908 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
909 th->th_sport, ip->ip_dst, th->th_dport,
910 INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
911 m->m_pkthdr.rcvif, m);
915 * If the INPCB does not exist then all data in the incoming
916 * segment is discarded and an appropriate RST is sent back.
917 * XXX MRT Send RST using which routing table?
921 * Log communication attempts to ports that are not
924 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
925 tcp_log_in_vain == 2) {
926 if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
927 log(LOG_INFO, "%s; %s: Connection attempt "
928 "to closed port\n", s, __func__);
931 * When blackholing do not respond with a RST but
932 * completely ignore the segment and drop it.
934 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
938 rstreason = BANDLIM_RST_CLOSEDPORT;
941 INP_WLOCK_ASSERT(inp);
942 if (!(inp->inp_flags & INP_HW_FLOWID)
943 && (m->m_flags & M_FLOWID)
944 && ((inp->inp_socket == NULL)
945 || !(inp->inp_socket->so_options & SO_ACCEPTCONN))) {
946 inp->inp_flags |= INP_HW_FLOWID;
947 inp->inp_flags &= ~INP_SW_FLOWID;
948 inp->inp_flowid = m->m_pkthdr.flowid;
952 if (isipv6 && ipsec6_in_reject(m, inp)) {
953 IPSEC6STAT_INC(in_polvio);
957 if (ipsec4_in_reject(m, inp) != 0) {
958 IPSECSTAT_INC(in_polvio);
964 * Check the minimum TTL for socket.
966 if (inp->inp_ip_minttl != 0) {
968 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
972 if (inp->inp_ip_minttl > ip->ip_ttl)
977 * A previous connection in TIMEWAIT state is supposed to catch stray
978 * or duplicate segments arriving late. If this segment was a
979 * legitimate new connection attempt, the old INPCB gets removed and
980 * we can try again to find a listening socket.
982 * At this point, due to earlier optimism, we may hold only an inpcb
983 * lock, and not the inpcbinfo write lock. If so, we need to try to
984 * acquire it, or if that fails, acquire a reference on the inpcb,
985 * drop all locks, acquire a global write lock, and then re-acquire
986 * the inpcb lock. We may at that point discover that another thread
987 * has tried to free the inpcb, in which case we need to loop back
988 * and try to find a new inpcb to deliver to.
990 * XXXRW: It may be time to rethink timewait locking.
993 if (inp->inp_flags & INP_TIMEWAIT) {
994 if (ti_locked == TI_UNLOCKED) {
995 if (INP_INFO_TRY_WLOCK(&V_tcbinfo) == 0) {
998 INP_INFO_WLOCK(&V_tcbinfo);
999 ti_locked = TI_WLOCKED;
1001 if (in_pcbrele_wlocked(inp)) {
1006 ti_locked = TI_WLOCKED;
1008 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1010 if (thflags & TH_SYN)
1011 tcp_dooptions(&to, optp, optlen, TO_SYN);
1013 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
1015 if (tcp_twcheck(inp, &to, th, m, tlen))
1017 INP_INFO_WUNLOCK(&V_tcbinfo);
1021 * The TCPCB may no longer exist if the connection is winding
1022 * down or it is in the CLOSED state. Either way we drop the
1023 * segment and send an appropriate response.
1025 tp = intotcpcb(inp);
1026 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
1027 rstreason = BANDLIM_RST_CLOSEDPORT;
1032 if (tp->t_flags & TF_TOE) {
1033 tcp_offload_input(tp, m);
1034 m = NULL; /* consumed by the TOE driver */
1040 * We've identified a valid inpcb, but it could be that we need an
1041 * inpcbinfo write lock but don't hold it. In this case, attempt to
1042 * acquire using the same strategy as the TIMEWAIT case above. If we
1043 * relock, we have to jump back to 'relocked' as the connection might
1044 * now be in TIMEWAIT.
1047 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0)
1048 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1050 if (tp->t_state != TCPS_ESTABLISHED) {
1051 if (ti_locked == TI_UNLOCKED) {
1052 if (INP_INFO_TRY_WLOCK(&V_tcbinfo) == 0) {
1055 INP_INFO_WLOCK(&V_tcbinfo);
1056 ti_locked = TI_WLOCKED;
1058 if (in_pcbrele_wlocked(inp)) {
1064 ti_locked = TI_WLOCKED;
1066 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1070 INP_WLOCK_ASSERT(inp);
1071 if (mac_inpcb_check_deliver(inp, m))
1074 so = inp->inp_socket;
1075 KASSERT(so != NULL, ("%s: so == NULL", __func__));
1077 if (so->so_options & SO_DEBUG) {
1078 ostate = tp->t_state;
1081 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
1084 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1087 #endif /* TCPDEBUG */
1089 * When the socket is accepting connections (the INPCB is in LISTEN
1090 * state) we look into the SYN cache if this is a new connection
1091 * attempt or the completion of a previous one. Because listen
1092 * sockets are never in TCPS_ESTABLISHED, the V_tcbinfo lock will be
1093 * held in this case.
1095 if (so->so_options & SO_ACCEPTCONN) {
1096 struct in_conninfo inc;
1098 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
1099 "tp not listening", __func__));
1100 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1102 bzero(&inc, sizeof(inc));
1105 inc.inc_flags |= INC_ISIPV6;
1106 inc.inc6_faddr = ip6->ip6_src;
1107 inc.inc6_laddr = ip6->ip6_dst;
1111 inc.inc_faddr = ip->ip_src;
1112 inc.inc_laddr = ip->ip_dst;
1114 inc.inc_fport = th->th_sport;
1115 inc.inc_lport = th->th_dport;
1116 inc.inc_fibnum = so->so_fibnum;
1119 * Check for an existing connection attempt in syncache if
1120 * the flag is only ACK. A successful lookup creates a new
1121 * socket appended to the listen queue in SYN_RECEIVED state.
1123 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1125 * Parse the TCP options here because
1126 * syncookies need access to the reflected
1129 tcp_dooptions(&to, optp, optlen, 0);
1131 * NB: syncache_expand() doesn't unlock
1132 * inp and tcpinfo locks.
1134 if (!syncache_expand(&inc, &to, th, &so, m)) {
1136 * No syncache entry or ACK was not
1137 * for our SYN/ACK. Send a RST.
1138 * NB: syncache did its own logging
1139 * of the failure cause.
1141 rstreason = BANDLIM_RST_OPENPORT;
1146 * We completed the 3-way handshake
1147 * but could not allocate a socket
1148 * either due to memory shortage,
1149 * listen queue length limits or
1150 * global socket limits. Send RST
1151 * or wait and have the remote end
1152 * retransmit the ACK for another
1155 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1156 log(LOG_DEBUG, "%s; %s: Listen socket: "
1157 "Socket allocation failed due to "
1158 "limits or memory shortage, %s\n",
1160 V_tcp_sc_rst_sock_fail ?
1161 "sending RST" : "try again");
1162 if (V_tcp_sc_rst_sock_fail) {
1163 rstreason = BANDLIM_UNLIMITED;
1169 * Socket is created in state SYN_RECEIVED.
1170 * Unlock the listen socket, lock the newly
1171 * created socket and update the tp variable.
1173 INP_WUNLOCK(inp); /* listen socket */
1174 inp = sotoinpcb(so);
1175 INP_WLOCK(inp); /* new connection */
1176 tp = intotcpcb(inp);
1177 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
1178 ("%s: ", __func__));
1179 #ifdef TCP_SIGNATURE
1180 if (sig_checked == 0) {
1181 tcp_dooptions(&to, optp, optlen,
1182 (thflags & TH_SYN) ? TO_SYN : 0);
1183 if (!tcp_signature_verify_input(m, off0, tlen,
1184 optlen, &to, th, tp->t_flags)) {
1187 * In SYN_SENT state if it receives an
1188 * RST, it is allowed for further
1191 if ((thflags & TH_RST) == 0 ||
1192 (tp->t_state == TCPS_SYN_SENT) == 0)
1200 * Process the segment and the data it
1201 * contains. tcp_do_segment() consumes
1202 * the mbuf chain and unlocks the inpcb.
1204 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
1206 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1210 * Segment flag validation for new connection attempts:
1212 * Our (SYN|ACK) response was rejected.
1213 * Check with syncache and remove entry to prevent
1216 * NB: syncache_chkrst does its own logging of failure
1219 if (thflags & TH_RST) {
1220 syncache_chkrst(&inc, th);
1224 * We can't do anything without SYN.
1226 if ((thflags & TH_SYN) == 0) {
1227 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1228 log(LOG_DEBUG, "%s; %s: Listen socket: "
1229 "SYN is missing, segment ignored\n",
1231 TCPSTAT_INC(tcps_badsyn);
1235 * (SYN|ACK) is bogus on a listen socket.
1237 if (thflags & TH_ACK) {
1238 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1239 log(LOG_DEBUG, "%s; %s: Listen socket: "
1240 "SYN|ACK invalid, segment rejected\n",
1242 syncache_badack(&inc); /* XXX: Not needed! */
1243 TCPSTAT_INC(tcps_badsyn);
1244 rstreason = BANDLIM_RST_OPENPORT;
1248 * If the drop_synfin option is enabled, drop all
1249 * segments with both the SYN and FIN bits set.
1250 * This prevents e.g. nmap from identifying the
1252 * XXX: Poor reasoning. nmap has other methods
1253 * and is constantly refining its stack detection
1255 * XXX: This is a violation of the TCP specification
1256 * and was used by RFC1644.
1258 if ((thflags & TH_FIN) && V_drop_synfin) {
1259 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1260 log(LOG_DEBUG, "%s; %s: Listen socket: "
1261 "SYN|FIN segment ignored (based on "
1262 "sysctl setting)\n", s, __func__);
1263 TCPSTAT_INC(tcps_badsyn);
1267 * Segment's flags are (SYN) or (SYN|FIN).
1269 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1270 * as they do not affect the state of the TCP FSM.
1271 * The data pointed to by TH_URG and th_urp is ignored.
1273 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1274 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1275 KASSERT(thflags & (TH_SYN),
1276 ("%s: Listen socket: TH_SYN not set", __func__));
1279 * If deprecated address is forbidden,
1280 * we do not accept SYN to deprecated interface
1281 * address to prevent any new inbound connection from
1282 * getting established.
1283 * When we do not accept SYN, we send a TCP RST,
1284 * with deprecated source address (instead of dropping
1285 * it). We compromise it as it is much better for peer
1286 * to send a RST, and RST will be the final packet
1289 * If we do not forbid deprecated addresses, we accept
1290 * the SYN packet. RFC2462 does not suggest dropping
1292 * If we decipher RFC2462 5.5.4, it says like this:
1293 * 1. use of deprecated addr with existing
1294 * communication is okay - "SHOULD continue to be
1296 * 2. use of it with new communication:
1297 * (2a) "SHOULD NOT be used if alternate address
1298 * with sufficient scope is available"
1299 * (2b) nothing mentioned otherwise.
1300 * Here we fall into (2b) case as we have no choice in
1301 * our source address selection - we must obey the peer.
1303 * The wording in RFC2462 is confusing, and there are
1304 * multiple description text for deprecated address
1305 * handling - worse, they are not exactly the same.
1306 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1308 if (isipv6 && !V_ip6_use_deprecated) {
1309 struct in6_ifaddr *ia6;
1311 ia6 = ip6_getdstifaddr(m);
1313 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1314 ifa_free(&ia6->ia_ifa);
1315 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1316 log(LOG_DEBUG, "%s; %s: Listen socket: "
1317 "Connection attempt to deprecated "
1318 "IPv6 address rejected\n",
1320 rstreason = BANDLIM_RST_OPENPORT;
1324 ifa_free(&ia6->ia_ifa);
1328 * Basic sanity checks on incoming SYN requests:
1329 * Don't respond if the destination is a link layer
1330 * broadcast according to RFC1122 4.2.3.10, p. 104.
1331 * If it is from this socket it must be forged.
1332 * Don't respond if the source or destination is a
1333 * global or subnet broad- or multicast address.
1334 * Note that it is quite possible to receive unicast
1335 * link-layer packets with a broadcast IP address. Use
1336 * in_broadcast() to find them.
1338 if (m->m_flags & (M_BCAST|M_MCAST)) {
1339 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1340 log(LOG_DEBUG, "%s; %s: Listen socket: "
1341 "Connection attempt from broad- or multicast "
1342 "link layer address ignored\n", s, __func__);
1347 if (th->th_dport == th->th_sport &&
1348 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1349 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1350 log(LOG_DEBUG, "%s; %s: Listen socket: "
1351 "Connection attempt to/from self "
1352 "ignored\n", s, __func__);
1355 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1356 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1357 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1358 log(LOG_DEBUG, "%s; %s: Listen socket: "
1359 "Connection attempt from/to multicast "
1360 "address ignored\n", s, __func__);
1365 #if defined(INET) && defined(INET6)
1370 if (th->th_dport == th->th_sport &&
1371 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1372 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1373 log(LOG_DEBUG, "%s; %s: Listen socket: "
1374 "Connection attempt from/to self "
1375 "ignored\n", s, __func__);
1378 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1379 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1380 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1381 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1382 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1383 log(LOG_DEBUG, "%s; %s: Listen socket: "
1384 "Connection attempt from/to broad- "
1385 "or multicast address ignored\n",
1392 * SYN appears to be valid. Create compressed TCP state
1396 if (so->so_options & SO_DEBUG)
1397 tcp_trace(TA_INPUT, ostate, tp,
1398 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1400 tcp_dooptions(&to, optp, optlen, TO_SYN);
1401 syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL);
1403 * Entry added to syncache and mbuf consumed.
1404 * Everything already unlocked by syncache_add().
1406 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1408 } else if (tp->t_state == TCPS_LISTEN) {
1410 * When a listen socket is torn down the SO_ACCEPTCONN
1411 * flag is removed first while connections are drained
1412 * from the accept queue in a unlock/lock cycle of the
1413 * ACCEPT_LOCK, opening a race condition allowing a SYN
1414 * attempt go through unhandled.
1419 #ifdef TCP_SIGNATURE
1420 if (sig_checked == 0) {
1421 tcp_dooptions(&to, optp, optlen,
1422 (thflags & TH_SYN) ? TO_SYN : 0);
1423 if (!tcp_signature_verify_input(m, off0, tlen, optlen, &to,
1427 * In SYN_SENT state if it receives an RST, it is
1428 * allowed for further processing.
1430 if ((thflags & TH_RST) == 0 ||
1431 (tp->t_state == TCPS_SYN_SENT) == 0)
1439 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1440 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1441 * the inpcb, and unlocks pcbinfo.
1443 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
1444 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1448 if (ti_locked == TI_WLOCKED) {
1449 INP_INFO_WUNLOCK(&V_tcbinfo);
1450 ti_locked = TI_UNLOCKED;
1454 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropwithreset "
1455 "ti_locked: %d", __func__, ti_locked));
1456 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1461 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1464 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1465 m = NULL; /* mbuf chain got consumed. */
1469 if (ti_locked == TI_WLOCKED) {
1470 INP_INFO_WUNLOCK(&V_tcbinfo);
1471 ti_locked = TI_UNLOCKED;
1475 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropunlock "
1476 "ti_locked: %d", __func__, ti_locked));
1477 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1485 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1493 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1494 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1497 int thflags, acked, ourfinisacked, needoutput = 0;
1498 int rstreason, todrop, win;
1504 * The size of tcp_saveipgen must be the size of the max ip header,
1507 u_char tcp_saveipgen[IP6_HDR_LEN];
1508 struct tcphdr tcp_savetcp;
1511 thflags = th->th_flags;
1512 tp->sackhint.last_sack_ack = 0;
1515 * If this is either a state-changing packet or current state isn't
1516 * established, we require a write lock on tcbinfo. Otherwise, we
1517 * allow the tcbinfo to be in either alocked or unlocked, as the
1518 * caller may have unnecessarily acquired a write lock due to a race.
1520 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1521 tp->t_state != TCPS_ESTABLISHED) {
1522 KASSERT(ti_locked == TI_WLOCKED, ("%s ti_locked %d for "
1523 "SYN/FIN/RST/!EST", __func__, ti_locked));
1524 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1527 if (ti_locked == TI_WLOCKED)
1528 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1530 KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST "
1531 "ti_locked: %d", __func__, ti_locked));
1532 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1536 INP_WLOCK_ASSERT(tp->t_inpcb);
1537 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1539 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1543 * Segment received on connection.
1544 * Reset idle time and keep-alive timer.
1545 * XXX: This should be done after segment
1546 * validation to ignore broken/spoofed segs.
1548 tp->t_rcvtime = ticks;
1549 if (TCPS_HAVEESTABLISHED(tp->t_state))
1550 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
1553 * Unscale the window into a 32-bit value.
1554 * For the SYN_SENT state the scale is zero.
1556 tiwin = th->th_win << tp->snd_scale;
1559 * TCP ECN processing.
1561 if (tp->t_flags & TF_ECN_PERMIT) {
1562 if (thflags & TH_CWR)
1563 tp->t_flags &= ~TF_ECN_SND_ECE;
1564 switch (iptos & IPTOS_ECN_MASK) {
1566 tp->t_flags |= TF_ECN_SND_ECE;
1567 TCPSTAT_INC(tcps_ecn_ce);
1569 case IPTOS_ECN_ECT0:
1570 TCPSTAT_INC(tcps_ecn_ect0);
1572 case IPTOS_ECN_ECT1:
1573 TCPSTAT_INC(tcps_ecn_ect1);
1576 /* Congestion experienced. */
1577 if (thflags & TH_ECE) {
1578 cc_cong_signal(tp, th, CC_ECN);
1583 * Parse options on any incoming segment.
1585 tcp_dooptions(&to, (u_char *)(th + 1),
1586 (th->th_off << 2) - sizeof(struct tcphdr),
1587 (thflags & TH_SYN) ? TO_SYN : 0);
1590 * If echoed timestamp is later than the current time,
1591 * fall back to non RFC1323 RTT calculation. Normalize
1592 * timestamp if syncookies were used when this connection
1595 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1596 to.to_tsecr -= tp->ts_offset;
1597 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1602 * Process options only when we get SYN/ACK back. The SYN case
1603 * for incoming connections is handled in tcp_syncache.
1604 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1605 * or <SYN,ACK>) segment itself is never scaled.
1606 * XXX this is traditional behavior, may need to be cleaned up.
1608 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1609 if ((to.to_flags & TOF_SCALE) &&
1610 (tp->t_flags & TF_REQ_SCALE)) {
1611 tp->t_flags |= TF_RCVD_SCALE;
1612 tp->snd_scale = to.to_wscale;
1615 * Initial send window. It will be updated with
1616 * the next incoming segment to the scaled value.
1618 tp->snd_wnd = th->th_win;
1619 if (to.to_flags & TOF_TS) {
1620 tp->t_flags |= TF_RCVD_TSTMP;
1621 tp->ts_recent = to.to_tsval;
1622 tp->ts_recent_age = tcp_ts_getticks();
1624 if (to.to_flags & TOF_MSS)
1625 tcp_mss(tp, to.to_mss);
1626 if ((tp->t_flags & TF_SACK_PERMIT) &&
1627 (to.to_flags & TOF_SACKPERM) == 0)
1628 tp->t_flags &= ~TF_SACK_PERMIT;
1632 * Header prediction: check for the two common cases
1633 * of a uni-directional data xfer. If the packet has
1634 * no control flags, is in-sequence, the window didn't
1635 * change and we're not retransmitting, it's a
1636 * candidate. If the length is zero and the ack moved
1637 * forward, we're the sender side of the xfer. Just
1638 * free the data acked & wake any higher level process
1639 * that was blocked waiting for space. If the length
1640 * is non-zero and the ack didn't move, we're the
1641 * receiver side. If we're getting packets in-order
1642 * (the reassembly queue is empty), add the data to
1643 * the socket buffer and note that we need a delayed ack.
1644 * Make sure that the hidden state-flags are also off.
1645 * Since we check for TCPS_ESTABLISHED first, it can only
1648 if (tp->t_state == TCPS_ESTABLISHED &&
1649 th->th_seq == tp->rcv_nxt &&
1650 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1651 tp->snd_nxt == tp->snd_max &&
1652 tiwin && tiwin == tp->snd_wnd &&
1653 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1654 LIST_EMPTY(&tp->t_segq) &&
1655 ((to.to_flags & TOF_TS) == 0 ||
1656 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1659 * If last ACK falls within this segment's sequence numbers,
1660 * record the timestamp.
1661 * NOTE that the test is modified according to the latest
1662 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1664 if ((to.to_flags & TOF_TS) != 0 &&
1665 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1666 tp->ts_recent_age = tcp_ts_getticks();
1667 tp->ts_recent = to.to_tsval;
1671 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1672 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1673 !IN_RECOVERY(tp->t_flags) &&
1674 (to.to_flags & TOF_SACK) == 0 &&
1675 TAILQ_EMPTY(&tp->snd_holes)) {
1677 * This is a pure ack for outstanding data.
1679 if (ti_locked == TI_WLOCKED)
1680 INP_INFO_WUNLOCK(&V_tcbinfo);
1681 ti_locked = TI_UNLOCKED;
1683 TCPSTAT_INC(tcps_predack);
1686 * "bad retransmit" recovery.
1688 if (tp->t_rxtshift == 1 &&
1689 tp->t_flags & TF_PREVVALID &&
1690 (int)(ticks - tp->t_badrxtwin) < 0) {
1691 cc_cong_signal(tp, th, CC_RTO_ERR);
1695 * Recalculate the transmit timer / rtt.
1697 * Some boxes send broken timestamp replies
1698 * during the SYN+ACK phase, ignore
1699 * timestamps of 0 or we could calculate a
1700 * huge RTT and blow up the retransmit timer.
1702 if ((to.to_flags & TOF_TS) != 0 &&
1706 t = tcp_ts_getticks() - to.to_tsecr;
1707 if (!tp->t_rttlow || tp->t_rttlow > t)
1710 TCP_TS_TO_TICKS(t) + 1);
1711 } else if (tp->t_rtttime &&
1712 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1713 if (!tp->t_rttlow ||
1714 tp->t_rttlow > ticks - tp->t_rtttime)
1715 tp->t_rttlow = ticks - tp->t_rtttime;
1717 ticks - tp->t_rtttime);
1719 acked = BYTES_THIS_ACK(tp, th);
1721 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1722 hhook_run_tcp_est_in(tp, th, &to);
1724 TCPSTAT_INC(tcps_rcvackpack);
1725 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1726 sbdrop(&so->so_snd, acked);
1727 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1728 SEQ_LEQ(th->th_ack, tp->snd_recover))
1729 tp->snd_recover = th->th_ack - 1;
1732 * Let the congestion control algorithm update
1733 * congestion control related information. This
1734 * typically means increasing the congestion
1737 cc_ack_received(tp, th, CC_ACK);
1739 tp->snd_una = th->th_ack;
1741 * Pull snd_wl2 up to prevent seq wrap relative
1744 tp->snd_wl2 = th->th_ack;
1747 ND6_HINT(tp); /* Some progress has been made. */
1750 * If all outstanding data are acked, stop
1751 * retransmit timer, otherwise restart timer
1752 * using current (possibly backed-off) value.
1753 * If process is waiting for space,
1754 * wakeup/selwakeup/signal. If data
1755 * are ready to send, let tcp_output
1756 * decide between more output or persist.
1759 if (so->so_options & SO_DEBUG)
1760 tcp_trace(TA_INPUT, ostate, tp,
1761 (void *)tcp_saveipgen,
1764 if (tp->snd_una == tp->snd_max)
1765 tcp_timer_activate(tp, TT_REXMT, 0);
1766 else if (!tcp_timer_active(tp, TT_PERSIST))
1767 tcp_timer_activate(tp, TT_REXMT,
1770 if (so->so_snd.sb_cc)
1771 (void) tcp_output(tp);
1774 } else if (th->th_ack == tp->snd_una &&
1775 tlen <= sbspace(&so->so_rcv)) {
1776 int newsize = 0; /* automatic sockbuf scaling */
1779 * This is a pure, in-sequence data packet with
1780 * nothing on the reassembly queue and we have enough
1781 * buffer space to take it.
1783 if (ti_locked == TI_WLOCKED)
1784 INP_INFO_WUNLOCK(&V_tcbinfo);
1785 ti_locked = TI_UNLOCKED;
1787 /* Clean receiver SACK report if present */
1788 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1789 tcp_clean_sackreport(tp);
1790 TCPSTAT_INC(tcps_preddat);
1791 tp->rcv_nxt += tlen;
1793 * Pull snd_wl1 up to prevent seq wrap relative to
1796 tp->snd_wl1 = th->th_seq;
1798 * Pull rcv_up up to prevent seq wrap relative to
1801 tp->rcv_up = tp->rcv_nxt;
1802 TCPSTAT_INC(tcps_rcvpack);
1803 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1804 ND6_HINT(tp); /* Some progress has been made */
1806 if (so->so_options & SO_DEBUG)
1807 tcp_trace(TA_INPUT, ostate, tp,
1808 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1811 * Automatic sizing of receive socket buffer. Often the send
1812 * buffer size is not optimally adjusted to the actual network
1813 * conditions at hand (delay bandwidth product). Setting the
1814 * buffer size too small limits throughput on links with high
1815 * bandwidth and high delay (eg. trans-continental/oceanic links).
1817 * On the receive side the socket buffer memory is only rarely
1818 * used to any significant extent. This allows us to be much
1819 * more aggressive in scaling the receive socket buffer. For
1820 * the case that the buffer space is actually used to a large
1821 * extent and we run out of kernel memory we can simply drop
1822 * the new segments; TCP on the sender will just retransmit it
1823 * later. Setting the buffer size too big may only consume too
1824 * much kernel memory if the application doesn't read() from
1825 * the socket or packet loss or reordering makes use of the
1828 * The criteria to step up the receive buffer one notch are:
1829 * 1. the number of bytes received during the time it takes
1830 * one timestamp to be reflected back to us (the RTT);
1831 * 2. received bytes per RTT is within seven eighth of the
1832 * current socket buffer size;
1833 * 3. receive buffer size has not hit maximal automatic size;
1835 * This algorithm does one step per RTT at most and only if
1836 * we receive a bulk stream w/o packet losses or reorderings.
1837 * Shrinking the buffer during idle times is not necessary as
1838 * it doesn't consume any memory when idle.
1840 * TODO: Only step up if the application is actually serving
1841 * the buffer to better manage the socket buffer resources.
1843 if (V_tcp_do_autorcvbuf &&
1845 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1846 if (TSTMP_GT(to.to_tsecr, tp->rfbuf_ts) &&
1847 to.to_tsecr - tp->rfbuf_ts < hz) {
1849 (so->so_rcv.sb_hiwat / 8 * 7) &&
1850 so->so_rcv.sb_hiwat <
1851 V_tcp_autorcvbuf_max) {
1853 min(so->so_rcv.sb_hiwat +
1854 V_tcp_autorcvbuf_inc,
1855 V_tcp_autorcvbuf_max);
1857 /* Start over with next RTT. */
1861 tp->rfbuf_cnt += tlen; /* add up */
1864 /* Add data to socket buffer. */
1865 SOCKBUF_LOCK(&so->so_rcv);
1866 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1870 * Set new socket buffer size.
1871 * Give up when limit is reached.
1874 if (!sbreserve_locked(&so->so_rcv,
1876 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1877 m_adj(m, drop_hdrlen); /* delayed header drop */
1878 sbappendstream_locked(&so->so_rcv, m);
1880 /* NB: sorwakeup_locked() does an implicit unlock. */
1881 sorwakeup_locked(so);
1882 if (DELAY_ACK(tp)) {
1883 tp->t_flags |= TF_DELACK;
1885 tp->t_flags |= TF_ACKNOW;
1893 * Calculate amount of space in receive window,
1894 * and then do TCP input processing.
1895 * Receive window is amount of space in rcv queue,
1896 * but not less than advertised window.
1898 win = sbspace(&so->so_rcv);
1901 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1903 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1907 switch (tp->t_state) {
1910 * If the state is SYN_RECEIVED:
1911 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1913 case TCPS_SYN_RECEIVED:
1914 if ((thflags & TH_ACK) &&
1915 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1916 SEQ_GT(th->th_ack, tp->snd_max))) {
1917 rstreason = BANDLIM_RST_OPENPORT;
1923 * If the state is SYN_SENT:
1924 * if seg contains an ACK, but not for our SYN, drop the input.
1925 * if seg contains a RST, then drop the connection.
1926 * if seg does not contain SYN, then drop it.
1927 * Otherwise this is an acceptable SYN segment
1928 * initialize tp->rcv_nxt and tp->irs
1929 * if seg contains ack then advance tp->snd_una
1930 * if seg contains an ECE and ECN support is enabled, the stream
1932 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1933 * arrange for segment to be acked (eventually)
1934 * continue processing rest of data/controls, beginning with URG
1937 if ((thflags & TH_ACK) &&
1938 (SEQ_LEQ(th->th_ack, tp->iss) ||
1939 SEQ_GT(th->th_ack, tp->snd_max))) {
1940 rstreason = BANDLIM_UNLIMITED;
1943 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
1944 tp = tcp_drop(tp, ECONNREFUSED);
1945 if (thflags & TH_RST)
1947 if (!(thflags & TH_SYN))
1950 tp->irs = th->th_seq;
1952 if (thflags & TH_ACK) {
1953 TCPSTAT_INC(tcps_connects);
1956 mac_socketpeer_set_from_mbuf(m, so);
1958 /* Do window scaling on this connection? */
1959 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1960 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1961 tp->rcv_scale = tp->request_r_scale;
1963 tp->rcv_adv += imin(tp->rcv_wnd,
1964 TCP_MAXWIN << tp->rcv_scale);
1965 tp->snd_una++; /* SYN is acked */
1967 * If there's data, delay ACK; if there's also a FIN
1968 * ACKNOW will be turned on later.
1970 if (DELAY_ACK(tp) && tlen != 0)
1971 tcp_timer_activate(tp, TT_DELACK,
1974 tp->t_flags |= TF_ACKNOW;
1976 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
1977 tp->t_flags |= TF_ECN_PERMIT;
1978 TCPSTAT_INC(tcps_ecn_shs);
1982 * Received <SYN,ACK> in SYN_SENT[*] state.
1984 * SYN_SENT --> ESTABLISHED
1985 * SYN_SENT* --> FIN_WAIT_1
1987 tp->t_starttime = ticks;
1988 if (tp->t_flags & TF_NEEDFIN) {
1989 tp->t_state = TCPS_FIN_WAIT_1;
1990 tp->t_flags &= ~TF_NEEDFIN;
1993 tp->t_state = TCPS_ESTABLISHED;
1995 tcp_timer_activate(tp, TT_KEEP,
2000 * Received initial SYN in SYN-SENT[*] state =>
2001 * simultaneous open. If segment contains CC option
2002 * and there is a cached CC, apply TAO test.
2003 * If it succeeds, connection is * half-synchronized.
2004 * Otherwise, do 3-way handshake:
2005 * SYN-SENT -> SYN-RECEIVED
2006 * SYN-SENT* -> SYN-RECEIVED*
2007 * If there was no CC option, clear cached CC value.
2009 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
2010 tcp_timer_activate(tp, TT_REXMT, 0);
2011 tp->t_state = TCPS_SYN_RECEIVED;
2014 KASSERT(ti_locked == TI_WLOCKED, ("%s: trimthenstep6: "
2015 "ti_locked %d", __func__, ti_locked));
2016 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2017 INP_WLOCK_ASSERT(tp->t_inpcb);
2020 * Advance th->th_seq to correspond to first data byte.
2021 * If data, trim to stay within window,
2022 * dropping FIN if necessary.
2025 if (tlen > tp->rcv_wnd) {
2026 todrop = tlen - tp->rcv_wnd;
2030 TCPSTAT_INC(tcps_rcvpackafterwin);
2031 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2033 tp->snd_wl1 = th->th_seq - 1;
2034 tp->rcv_up = th->th_seq;
2036 * Client side of transaction: already sent SYN and data.
2037 * If the remote host used T/TCP to validate the SYN,
2038 * our data will be ACK'd; if so, enter normal data segment
2039 * processing in the middle of step 5, ack processing.
2040 * Otherwise, goto step 6.
2042 if (thflags & TH_ACK)
2048 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
2049 * do normal processing.
2051 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
2055 break; /* continue normal processing */
2059 * States other than LISTEN or SYN_SENT.
2060 * First check the RST flag and sequence number since reset segments
2061 * are exempt from the timestamp and connection count tests. This
2062 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
2063 * below which allowed reset segments in half the sequence space
2064 * to fall though and be processed (which gives forged reset
2065 * segments with a random sequence number a 50 percent chance of
2066 * killing a connection).
2067 * Then check timestamp, if present.
2068 * Then check the connection count, if present.
2069 * Then check that at least some bytes of segment are within
2070 * receive window. If segment begins before rcv_nxt,
2071 * drop leading data (and SYN); if nothing left, just ack.
2074 * If the RST bit is set, check the sequence number to see
2075 * if this is a valid reset segment.
2077 * In all states except SYN-SENT, all reset (RST) segments
2078 * are validated by checking their SEQ-fields. A reset is
2079 * valid if its sequence number is in the window.
2080 * Note: this does not take into account delayed ACKs, so
2081 * we should test against last_ack_sent instead of rcv_nxt.
2082 * The sequence number in the reset segment is normally an
2083 * echo of our outgoing acknowlegement numbers, but some hosts
2084 * send a reset with the sequence number at the rightmost edge
2085 * of our receive window, and we have to handle this case.
2086 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
2087 * that brute force RST attacks are possible. To combat this,
2088 * we use a much stricter check while in the ESTABLISHED state,
2089 * only accepting RSTs where the sequence number is equal to
2090 * last_ack_sent. In all other states (the states in which a
2091 * RST is more likely), the more permissive check is used.
2092 * If we have multiple segments in flight, the initial reset
2093 * segment sequence numbers will be to the left of last_ack_sent,
2094 * but they will eventually catch up.
2095 * In any case, it never made sense to trim reset segments to
2096 * fit the receive window since RFC 1122 says:
2097 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
2099 * A TCP SHOULD allow a received RST segment to include data.
2102 * It has been suggested that a RST segment could contain
2103 * ASCII text that encoded and explained the cause of the
2104 * RST. No standard has yet been established for such
2107 * If the reset segment passes the sequence number test examine
2109 * SYN_RECEIVED STATE:
2110 * If passive open, return to LISTEN state.
2111 * If active open, inform user that connection was refused.
2112 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
2113 * Inform user that connection was reset, and close tcb.
2114 * CLOSING, LAST_ACK STATES:
2117 * Drop the segment - see Stevens, vol. 2, p. 964 and
2120 if (thflags & TH_RST) {
2121 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
2122 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2123 switch (tp->t_state) {
2125 case TCPS_SYN_RECEIVED:
2126 so->so_error = ECONNREFUSED;
2129 case TCPS_ESTABLISHED:
2130 if (V_tcp_insecure_rst == 0 &&
2131 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
2132 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
2133 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
2134 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
2135 TCPSTAT_INC(tcps_badrst);
2139 case TCPS_FIN_WAIT_1:
2140 case TCPS_FIN_WAIT_2:
2141 case TCPS_CLOSE_WAIT:
2142 so->so_error = ECONNRESET;
2144 KASSERT(ti_locked == TI_WLOCKED,
2145 ("tcp_do_segment: TH_RST 1 ti_locked %d",
2147 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2149 tp->t_state = TCPS_CLOSED;
2150 TCPSTAT_INC(tcps_drops);
2156 KASSERT(ti_locked == TI_WLOCKED,
2157 ("tcp_do_segment: TH_RST 2 ti_locked %d",
2159 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2169 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2170 * and it's less than ts_recent, drop it.
2172 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2173 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2175 /* Check to see if ts_recent is over 24 days old. */
2176 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2178 * Invalidate ts_recent. If this segment updates
2179 * ts_recent, the age will be reset later and ts_recent
2180 * will get a valid value. If it does not, setting
2181 * ts_recent to zero will at least satisfy the
2182 * requirement that zero be placed in the timestamp
2183 * echo reply when ts_recent isn't valid. The
2184 * age isn't reset until we get a valid ts_recent
2185 * because we don't want out-of-order segments to be
2186 * dropped when ts_recent is old.
2190 TCPSTAT_INC(tcps_rcvduppack);
2191 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
2192 TCPSTAT_INC(tcps_pawsdrop);
2200 * In the SYN-RECEIVED state, validate that the packet belongs to
2201 * this connection before trimming the data to fit the receive
2202 * window. Check the sequence number versus IRS since we know
2203 * the sequence numbers haven't wrapped. This is a partial fix
2204 * for the "LAND" DoS attack.
2206 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2207 rstreason = BANDLIM_RST_OPENPORT;
2211 todrop = tp->rcv_nxt - th->th_seq;
2214 * If this is a duplicate SYN for our current connection,
2215 * advance over it and pretend and it's not a SYN.
2217 if (thflags & TH_SYN && th->th_seq == tp->irs) {
2227 * Following if statement from Stevens, vol. 2, p. 960.
2230 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2232 * Any valid FIN must be to the left of the window.
2233 * At this point the FIN must be a duplicate or out
2234 * of sequence; drop it.
2239 * Send an ACK to resynchronize and drop any data.
2240 * But keep on processing for RST or ACK.
2242 tp->t_flags |= TF_ACKNOW;
2244 TCPSTAT_INC(tcps_rcvduppack);
2245 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2247 TCPSTAT_INC(tcps_rcvpartduppack);
2248 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2250 drop_hdrlen += todrop; /* drop from the top afterwards */
2251 th->th_seq += todrop;
2253 if (th->th_urp > todrop)
2254 th->th_urp -= todrop;
2262 * If new data are received on a connection after the
2263 * user processes are gone, then RST the other end.
2265 if ((so->so_state & SS_NOFDREF) &&
2266 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2269 KASSERT(ti_locked == TI_WLOCKED, ("%s: SS_NOFDEREF && "
2270 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
2271 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2273 if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
2274 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data after socket "
2275 "was closed, sending RST and removing tcpcb\n",
2276 s, __func__, tcpstates[tp->t_state], tlen);
2280 TCPSTAT_INC(tcps_rcvafterclose);
2281 rstreason = BANDLIM_UNLIMITED;
2286 * If segment ends after window, drop trailing data
2287 * (and PUSH and FIN); if nothing left, just ACK.
2289 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2291 TCPSTAT_INC(tcps_rcvpackafterwin);
2292 if (todrop >= tlen) {
2293 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2295 * If window is closed can only take segments at
2296 * window edge, and have to drop data and PUSH from
2297 * incoming segments. Continue processing, but
2298 * remember to ack. Otherwise, drop segment
2301 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2302 tp->t_flags |= TF_ACKNOW;
2303 TCPSTAT_INC(tcps_rcvwinprobe);
2307 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2310 thflags &= ~(TH_PUSH|TH_FIN);
2314 * If last ACK falls within this segment's sequence numbers,
2315 * record its timestamp.
2317 * 1) That the test incorporates suggestions from the latest
2318 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2319 * 2) That updating only on newer timestamps interferes with
2320 * our earlier PAWS tests, so this check should be solely
2321 * predicated on the sequence space of this segment.
2322 * 3) That we modify the segment boundary check to be
2323 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2324 * instead of RFC1323's
2325 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2326 * This modified check allows us to overcome RFC1323's
2327 * limitations as described in Stevens TCP/IP Illustrated
2328 * Vol. 2 p.869. In such cases, we can still calculate the
2329 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2331 if ((to.to_flags & TOF_TS) != 0 &&
2332 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2333 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2334 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2335 tp->ts_recent_age = tcp_ts_getticks();
2336 tp->ts_recent = to.to_tsval;
2340 * If a SYN is in the window, then this is an
2341 * error and we send an RST and drop the connection.
2343 if (thflags & TH_SYN) {
2344 KASSERT(ti_locked == TI_WLOCKED,
2345 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
2346 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2348 tp = tcp_drop(tp, ECONNRESET);
2349 rstreason = BANDLIM_UNLIMITED;
2354 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2355 * flag is on (half-synchronized state), then queue data for
2356 * later processing; else drop segment and return.
2358 if ((thflags & TH_ACK) == 0) {
2359 if (tp->t_state == TCPS_SYN_RECEIVED ||
2360 (tp->t_flags & TF_NEEDSYN))
2362 else if (tp->t_flags & TF_ACKNOW)
2371 switch (tp->t_state) {
2374 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2375 * ESTABLISHED state and continue processing.
2376 * The ACK was checked above.
2378 case TCPS_SYN_RECEIVED:
2380 TCPSTAT_INC(tcps_connects);
2382 /* Do window scaling? */
2383 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2384 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2385 tp->rcv_scale = tp->request_r_scale;
2386 tp->snd_wnd = tiwin;
2390 * SYN-RECEIVED -> ESTABLISHED
2391 * SYN-RECEIVED* -> FIN-WAIT-1
2393 tp->t_starttime = ticks;
2394 if (tp->t_flags & TF_NEEDFIN) {
2395 tp->t_state = TCPS_FIN_WAIT_1;
2396 tp->t_flags &= ~TF_NEEDFIN;
2398 tp->t_state = TCPS_ESTABLISHED;
2400 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2403 * If segment contains data or ACK, will call tcp_reass()
2404 * later; if not, do so now to pass queued data to user.
2406 if (tlen == 0 && (thflags & TH_FIN) == 0)
2407 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
2409 tp->snd_wl1 = th->th_seq - 1;
2413 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2414 * ACKs. If the ack is in the range
2415 * tp->snd_una < th->th_ack <= tp->snd_max
2416 * then advance tp->snd_una to th->th_ack and drop
2417 * data from the retransmission queue. If this ACK reflects
2418 * more up to date window information we update our window information.
2420 case TCPS_ESTABLISHED:
2421 case TCPS_FIN_WAIT_1:
2422 case TCPS_FIN_WAIT_2:
2423 case TCPS_CLOSE_WAIT:
2426 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2427 TCPSTAT_INC(tcps_rcvacktoomuch);
2430 if ((tp->t_flags & TF_SACK_PERMIT) &&
2431 ((to.to_flags & TOF_SACK) ||
2432 !TAILQ_EMPTY(&tp->snd_holes)))
2433 tcp_sack_doack(tp, &to, th->th_ack);
2435 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2436 hhook_run_tcp_est_in(tp, th, &to);
2438 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2439 if (tlen == 0 && tiwin == tp->snd_wnd) {
2440 TCPSTAT_INC(tcps_rcvdupack);
2442 * If we have outstanding data (other than
2443 * a window probe), this is a completely
2444 * duplicate ack (ie, window info didn't
2445 * change), the ack is the biggest we've
2446 * seen and we've seen exactly our rexmt
2447 * threshhold of them, assume a packet
2448 * has been dropped and retransmit it.
2449 * Kludge snd_nxt & the congestion
2450 * window so we send only this one
2453 * We know we're losing at the current
2454 * window size so do congestion avoidance
2455 * (set ssthresh to half the current window
2456 * and pull our congestion window back to
2457 * the new ssthresh).
2459 * Dup acks mean that packets have left the
2460 * network (they're now cached at the receiver)
2461 * so bump cwnd by the amount in the receiver
2462 * to keep a constant cwnd packets in the
2465 * When using TCP ECN, notify the peer that
2466 * we reduced the cwnd.
2468 if (!tcp_timer_active(tp, TT_REXMT) ||
2469 th->th_ack != tp->snd_una)
2471 else if (++tp->t_dupacks > tcprexmtthresh ||
2472 IN_FASTRECOVERY(tp->t_flags)) {
2473 cc_ack_received(tp, th, CC_DUPACK);
2474 if ((tp->t_flags & TF_SACK_PERMIT) &&
2475 IN_FASTRECOVERY(tp->t_flags)) {
2479 * Compute the amount of data in flight first.
2480 * We can inject new data into the pipe iff
2481 * we have less than 1/2 the original window's
2482 * worth of data in flight.
2484 awnd = (tp->snd_nxt - tp->snd_fack) +
2485 tp->sackhint.sack_bytes_rexmit;
2486 if (awnd < tp->snd_ssthresh) {
2487 tp->snd_cwnd += tp->t_maxseg;
2488 if (tp->snd_cwnd > tp->snd_ssthresh)
2489 tp->snd_cwnd = tp->snd_ssthresh;
2492 tp->snd_cwnd += tp->t_maxseg;
2493 if ((thflags & TH_FIN) &&
2494 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2496 * If its a fin we need to process
2497 * it to avoid a race where both
2498 * sides enter FIN-WAIT and send FIN|ACK
2503 (void) tcp_output(tp);
2505 } else if (tp->t_dupacks == tcprexmtthresh) {
2506 tcp_seq onxt = tp->snd_nxt;
2509 * If we're doing sack, check to
2510 * see if we're already in sack
2511 * recovery. If we're not doing sack,
2512 * check to see if we're in newreno
2515 if (tp->t_flags & TF_SACK_PERMIT) {
2516 if (IN_FASTRECOVERY(tp->t_flags)) {
2521 if (SEQ_LEQ(th->th_ack,
2527 /* Congestion signal before ack. */
2528 cc_cong_signal(tp, th, CC_NDUPACK);
2529 cc_ack_received(tp, th, CC_DUPACK);
2530 tcp_timer_activate(tp, TT_REXMT, 0);
2532 if (tp->t_flags & TF_SACK_PERMIT) {
2534 tcps_sack_recovery_episode);
2535 tp->sack_newdata = tp->snd_nxt;
2536 tp->snd_cwnd = tp->t_maxseg;
2537 (void) tcp_output(tp);
2540 tp->snd_nxt = th->th_ack;
2541 tp->snd_cwnd = tp->t_maxseg;
2542 if ((thflags & TH_FIN) &&
2543 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2545 * If its a fin we need to process
2546 * it to avoid a race where both
2547 * sides enter FIN-WAIT and send FIN|ACK
2552 (void) tcp_output(tp);
2553 KASSERT(tp->snd_limited <= 2,
2554 ("%s: tp->snd_limited too big",
2556 tp->snd_cwnd = tp->snd_ssthresh +
2558 (tp->t_dupacks - tp->snd_limited);
2559 if (SEQ_GT(onxt, tp->snd_nxt))
2562 } else if (V_tcp_do_rfc3042) {
2563 cc_ack_received(tp, th, CC_DUPACK);
2564 u_long oldcwnd = tp->snd_cwnd;
2565 tcp_seq oldsndmax = tp->snd_max;
2569 KASSERT(tp->t_dupacks == 1 ||
2571 ("%s: dupacks not 1 or 2",
2573 if (tp->t_dupacks == 1)
2574 tp->snd_limited = 0;
2576 (tp->snd_nxt - tp->snd_una) +
2577 (tp->t_dupacks - tp->snd_limited) *
2579 if ((thflags & TH_FIN) &&
2580 (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2582 * If its a fin we need to process
2583 * it to avoid a race where both
2584 * sides enter FIN-WAIT and send FIN|ACK
2590 * Only call tcp_output when there
2591 * is new data available to be sent.
2592 * Otherwise we would send pure ACKs.
2594 SOCKBUF_LOCK(&so->so_snd);
2595 avail = so->so_snd.sb_cc -
2596 (tp->snd_nxt - tp->snd_una);
2597 SOCKBUF_UNLOCK(&so->so_snd);
2599 (void) tcp_output(tp);
2600 sent = tp->snd_max - oldsndmax;
2601 if (sent > tp->t_maxseg) {
2602 KASSERT((tp->t_dupacks == 2 &&
2603 tp->snd_limited == 0) ||
2604 (sent == tp->t_maxseg + 1 &&
2605 tp->t_flags & TF_SENTFIN),
2606 ("%s: sent too much",
2608 tp->snd_limited = 2;
2609 } else if (sent > 0)
2611 tp->snd_cwnd = oldcwnd;
2619 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2620 ("%s: th_ack <= snd_una", __func__));
2623 * If the congestion window was inflated to account
2624 * for the other side's cached packets, retract it.
2626 if (IN_FASTRECOVERY(tp->t_flags)) {
2627 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2628 if (tp->t_flags & TF_SACK_PERMIT)
2629 tcp_sack_partialack(tp, th);
2631 tcp_newreno_partial_ack(tp, th);
2633 cc_post_recovery(tp, th);
2637 * If we reach this point, ACK is not a duplicate,
2638 * i.e., it ACKs something we sent.
2640 if (tp->t_flags & TF_NEEDSYN) {
2642 * T/TCP: Connection was half-synchronized, and our
2643 * SYN has been ACK'd (so connection is now fully
2644 * synchronized). Go to non-starred state,
2645 * increment snd_una for ACK of SYN, and check if
2646 * we can do window scaling.
2648 tp->t_flags &= ~TF_NEEDSYN;
2650 /* Do window scaling? */
2651 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2652 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2653 tp->rcv_scale = tp->request_r_scale;
2654 /* Send window already scaled. */
2659 INP_WLOCK_ASSERT(tp->t_inpcb);
2661 acked = BYTES_THIS_ACK(tp, th);
2662 TCPSTAT_INC(tcps_rcvackpack);
2663 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2666 * If we just performed our first retransmit, and the ACK
2667 * arrives within our recovery window, then it was a mistake
2668 * to do the retransmit in the first place. Recover our
2669 * original cwnd and ssthresh, and proceed to transmit where
2672 if (tp->t_rxtshift == 1 && tp->t_flags & TF_PREVVALID &&
2673 (int)(ticks - tp->t_badrxtwin) < 0)
2674 cc_cong_signal(tp, th, CC_RTO_ERR);
2677 * If we have a timestamp reply, update smoothed
2678 * round trip time. If no timestamp is present but
2679 * transmit timer is running and timed sequence
2680 * number was acked, update smoothed round trip time.
2681 * Since we now have an rtt measurement, cancel the
2682 * timer backoff (cf., Phil Karn's retransmit alg.).
2683 * Recompute the initial retransmit timer.
2685 * Some boxes send broken timestamp replies
2686 * during the SYN+ACK phase, ignore
2687 * timestamps of 0 or we could calculate a
2688 * huge RTT and blow up the retransmit timer.
2690 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
2693 t = tcp_ts_getticks() - to.to_tsecr;
2694 if (!tp->t_rttlow || tp->t_rttlow > t)
2696 tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2697 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2698 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2699 tp->t_rttlow = ticks - tp->t_rtttime;
2700 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2704 * If all outstanding data is acked, stop retransmit
2705 * timer and remember to restart (more output or persist).
2706 * If there is more data to be acked, restart retransmit
2707 * timer, using current (possibly backed-off) value.
2709 if (th->th_ack == tp->snd_max) {
2710 tcp_timer_activate(tp, TT_REXMT, 0);
2712 } else if (!tcp_timer_active(tp, TT_PERSIST))
2713 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2716 * If no data (only SYN) was ACK'd,
2717 * skip rest of ACK processing.
2723 * Let the congestion control algorithm update congestion
2724 * control related information. This typically means increasing
2725 * the congestion window.
2727 cc_ack_received(tp, th, CC_ACK);
2729 SOCKBUF_LOCK(&so->so_snd);
2730 if (acked > so->so_snd.sb_cc) {
2731 tp->snd_wnd -= so->so_snd.sb_cc;
2732 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2735 sbdrop_locked(&so->so_snd, acked);
2736 tp->snd_wnd -= acked;
2739 /* NB: sowwakeup_locked() does an implicit unlock. */
2740 sowwakeup_locked(so);
2741 /* Detect una wraparound. */
2742 if (!IN_RECOVERY(tp->t_flags) &&
2743 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2744 SEQ_LEQ(th->th_ack, tp->snd_recover))
2745 tp->snd_recover = th->th_ack - 1;
2746 /* XXXLAS: Can this be moved up into cc_post_recovery? */
2747 if (IN_RECOVERY(tp->t_flags) &&
2748 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2749 EXIT_RECOVERY(tp->t_flags);
2751 tp->snd_una = th->th_ack;
2752 if (tp->t_flags & TF_SACK_PERMIT) {
2753 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2754 tp->snd_recover = tp->snd_una;
2756 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2757 tp->snd_nxt = tp->snd_una;
2759 switch (tp->t_state) {
2762 * In FIN_WAIT_1 STATE in addition to the processing
2763 * for the ESTABLISHED state if our FIN is now acknowledged
2764 * then enter FIN_WAIT_2.
2766 case TCPS_FIN_WAIT_1:
2767 if (ourfinisacked) {
2769 * If we can't receive any more
2770 * data, then closing user can proceed.
2771 * Starting the timer is contrary to the
2772 * specification, but if we don't get a FIN
2773 * we'll hang forever.
2776 * we should release the tp also, and use a
2779 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2780 soisdisconnected(so);
2781 tcp_timer_activate(tp, TT_2MSL,
2782 (tcp_fast_finwait2_recycle ?
2783 tcp_finwait2_timeout :
2786 tp->t_state = TCPS_FIN_WAIT_2;
2791 * In CLOSING STATE in addition to the processing for
2792 * the ESTABLISHED state if the ACK acknowledges our FIN
2793 * then enter the TIME-WAIT state, otherwise ignore
2797 if (ourfinisacked) {
2798 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2800 INP_INFO_WUNLOCK(&V_tcbinfo);
2807 * In LAST_ACK, we may still be waiting for data to drain
2808 * and/or to be acked, as well as for the ack of our FIN.
2809 * If our FIN is now acknowledged, delete the TCB,
2810 * enter the closed state and return.
2813 if (ourfinisacked) {
2814 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2823 INP_WLOCK_ASSERT(tp->t_inpcb);
2826 * Update window information.
2827 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2829 if ((thflags & TH_ACK) &&
2830 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2831 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2832 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2833 /* keep track of pure window updates */
2835 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2836 TCPSTAT_INC(tcps_rcvwinupd);
2837 tp->snd_wnd = tiwin;
2838 tp->snd_wl1 = th->th_seq;
2839 tp->snd_wl2 = th->th_ack;
2840 if (tp->snd_wnd > tp->max_sndwnd)
2841 tp->max_sndwnd = tp->snd_wnd;
2846 * Process segments with URG.
2848 if ((thflags & TH_URG) && th->th_urp &&
2849 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2851 * This is a kludge, but if we receive and accept
2852 * random urgent pointers, we'll crash in
2853 * soreceive. It's hard to imagine someone
2854 * actually wanting to send this much urgent data.
2856 SOCKBUF_LOCK(&so->so_rcv);
2857 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2858 th->th_urp = 0; /* XXX */
2859 thflags &= ~TH_URG; /* XXX */
2860 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2861 goto dodata; /* XXX */
2864 * If this segment advances the known urgent pointer,
2865 * then mark the data stream. This should not happen
2866 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2867 * a FIN has been received from the remote side.
2868 * In these states we ignore the URG.
2870 * According to RFC961 (Assigned Protocols),
2871 * the urgent pointer points to the last octet
2872 * of urgent data. We continue, however,
2873 * to consider it to indicate the first octet
2874 * of data past the urgent section as the original
2875 * spec states (in one of two places).
2877 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2878 tp->rcv_up = th->th_seq + th->th_urp;
2879 so->so_oobmark = so->so_rcv.sb_cc +
2880 (tp->rcv_up - tp->rcv_nxt) - 1;
2881 if (so->so_oobmark == 0)
2882 so->so_rcv.sb_state |= SBS_RCVATMARK;
2884 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2886 SOCKBUF_UNLOCK(&so->so_rcv);
2888 * Remove out of band data so doesn't get presented to user.
2889 * This can happen independent of advancing the URG pointer,
2890 * but if two URG's are pending at once, some out-of-band
2891 * data may creep in... ick.
2893 if (th->th_urp <= (u_long)tlen &&
2894 !(so->so_options & SO_OOBINLINE)) {
2895 /* hdr drop is delayed */
2896 tcp_pulloutofband(so, th, m, drop_hdrlen);
2900 * If no out of band data is expected,
2901 * pull receive urgent pointer along
2902 * with the receive window.
2904 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2905 tp->rcv_up = tp->rcv_nxt;
2908 INP_WLOCK_ASSERT(tp->t_inpcb);
2911 * Process the segment text, merging it into the TCP sequencing queue,
2912 * and arranging for acknowledgment of receipt if necessary.
2913 * This process logically involves adjusting tp->rcv_wnd as data
2914 * is presented to the user (this happens in tcp_usrreq.c,
2915 * case PRU_RCVD). If a FIN has already been received on this
2916 * connection then we just ignore the text.
2918 if ((tlen || (thflags & TH_FIN)) &&
2919 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2920 tcp_seq save_start = th->th_seq;
2921 m_adj(m, drop_hdrlen); /* delayed header drop */
2923 * Insert segment which includes th into TCP reassembly queue
2924 * with control block tp. Set thflags to whether reassembly now
2925 * includes a segment with FIN. This handles the common case
2926 * inline (segment is the next to be received on an established
2927 * connection, and the queue is empty), avoiding linkage into
2928 * and removal from the queue and repetition of various
2930 * Set DELACK for segments received in order, but ack
2931 * immediately when segments are out of order (so
2932 * fast retransmit can work).
2934 if (th->th_seq == tp->rcv_nxt &&
2935 LIST_EMPTY(&tp->t_segq) &&
2936 TCPS_HAVEESTABLISHED(tp->t_state)) {
2938 tp->t_flags |= TF_DELACK;
2940 tp->t_flags |= TF_ACKNOW;
2941 tp->rcv_nxt += tlen;
2942 thflags = th->th_flags & TH_FIN;
2943 TCPSTAT_INC(tcps_rcvpack);
2944 TCPSTAT_ADD(tcps_rcvbyte, tlen);
2946 SOCKBUF_LOCK(&so->so_rcv);
2947 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2950 sbappendstream_locked(&so->so_rcv, m);
2951 /* NB: sorwakeup_locked() does an implicit unlock. */
2952 sorwakeup_locked(so);
2955 * XXX: Due to the header drop above "th" is
2956 * theoretically invalid by now. Fortunately
2957 * m_adj() doesn't actually frees any mbufs
2958 * when trimming from the head.
2960 thflags = tcp_reass(tp, th, &tlen, m);
2961 tp->t_flags |= TF_ACKNOW;
2963 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2964 tcp_update_sack_list(tp, save_start, save_start + tlen);
2967 * Note the amount of data that peer has sent into
2968 * our window, in order to estimate the sender's
2972 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
2973 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2975 len = so->so_rcv.sb_hiwat;
2983 * If FIN is received ACK the FIN and let the user know
2984 * that the connection is closing.
2986 if (thflags & TH_FIN) {
2987 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2990 * If connection is half-synchronized
2991 * (ie NEEDSYN flag on) then delay ACK,
2992 * so it may be piggybacked when SYN is sent.
2993 * Otherwise, since we received a FIN then no
2994 * more input can be expected, send ACK now.
2996 if (tp->t_flags & TF_NEEDSYN)
2997 tp->t_flags |= TF_DELACK;
2999 tp->t_flags |= TF_ACKNOW;
3002 switch (tp->t_state) {
3005 * In SYN_RECEIVED and ESTABLISHED STATES
3006 * enter the CLOSE_WAIT state.
3008 case TCPS_SYN_RECEIVED:
3009 tp->t_starttime = ticks;
3011 case TCPS_ESTABLISHED:
3012 tp->t_state = TCPS_CLOSE_WAIT;
3016 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3017 * enter the CLOSING state.
3019 case TCPS_FIN_WAIT_1:
3020 tp->t_state = TCPS_CLOSING;
3024 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3025 * starting the time-wait timer, turning off the other
3028 case TCPS_FIN_WAIT_2:
3029 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
3030 KASSERT(ti_locked == TI_WLOCKED, ("%s: dodata "
3031 "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
3035 INP_INFO_WUNLOCK(&V_tcbinfo);
3039 if (ti_locked == TI_WLOCKED)
3040 INP_INFO_WUNLOCK(&V_tcbinfo);
3041 ti_locked = TI_UNLOCKED;
3044 if (so->so_options & SO_DEBUG)
3045 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3050 * Return any desired output.
3052 if (needoutput || (tp->t_flags & TF_ACKNOW))
3053 (void) tcp_output(tp);
3056 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
3057 __func__, ti_locked));
3058 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3059 INP_WLOCK_ASSERT(tp->t_inpcb);
3061 if (tp->t_flags & TF_DELACK) {
3062 tp->t_flags &= ~TF_DELACK;
3063 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
3065 INP_WUNLOCK(tp->t_inpcb);
3070 * Generate an ACK dropping incoming segment if it occupies
3071 * sequence space, where the ACK reflects our state.
3073 * We can now skip the test for the RST flag since all
3074 * paths to this code happen after packets containing
3075 * RST have been dropped.
3077 * In the SYN-RECEIVED state, don't send an ACK unless the
3078 * segment we received passes the SYN-RECEIVED ACK test.
3079 * If it fails send a RST. This breaks the loop in the
3080 * "LAND" DoS attack, and also prevents an ACK storm
3081 * between two listening ports that have been sent forged
3082 * SYN segments, each with the source address of the other.
3084 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3085 (SEQ_GT(tp->snd_una, th->th_ack) ||
3086 SEQ_GT(th->th_ack, tp->snd_max)) ) {
3087 rstreason = BANDLIM_RST_OPENPORT;
3091 if (so->so_options & SO_DEBUG)
3092 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3095 if (ti_locked == TI_WLOCKED)
3096 INP_INFO_WUNLOCK(&V_tcbinfo);
3097 ti_locked = TI_UNLOCKED;
3099 tp->t_flags |= TF_ACKNOW;
3100 (void) tcp_output(tp);
3101 INP_WUNLOCK(tp->t_inpcb);
3106 if (ti_locked == TI_WLOCKED)
3107 INP_INFO_WUNLOCK(&V_tcbinfo);
3108 ti_locked = TI_UNLOCKED;
3111 tcp_dropwithreset(m, th, tp, tlen, rstreason);
3112 INP_WUNLOCK(tp->t_inpcb);
3114 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3118 if (ti_locked == TI_WLOCKED) {
3119 INP_INFO_WUNLOCK(&V_tcbinfo);
3120 ti_locked = TI_UNLOCKED;
3124 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3128 * Drop space held by incoming segment and return.
3131 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3132 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3136 INP_WUNLOCK(tp->t_inpcb);
3141 * Issue RST and make ACK acceptable to originator of segment.
3142 * The mbuf must still include the original packet header.
3146 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3147 int tlen, int rstreason)
3153 struct ip6_hdr *ip6;
3157 INP_WLOCK_ASSERT(tp->t_inpcb);
3160 /* Don't bother if destination was broadcast/multicast. */
3161 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3164 if (mtod(m, struct ip *)->ip_v == 6) {
3165 ip6 = mtod(m, struct ip6_hdr *);
3166 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3167 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3169 /* IPv6 anycast check is done at tcp6_input() */
3172 #if defined(INET) && defined(INET6)
3177 ip = mtod(m, struct ip *);
3178 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3179 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3180 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3181 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3186 /* Perform bandwidth limiting. */
3187 if (badport_bandlim(rstreason) < 0)
3190 /* tcp_respond consumes the mbuf chain. */
3191 if (th->th_flags & TH_ACK) {
3192 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3193 th->th_ack, TH_RST);
3195 if (th->th_flags & TH_SYN)
3197 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3198 (tcp_seq)0, TH_RST|TH_ACK);
3206 * Parse TCP options and place in tcpopt.
3209 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3214 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3216 if (opt == TCPOPT_EOL)
3218 if (opt == TCPOPT_NOP)
3224 if (optlen < 2 || optlen > cnt)
3229 if (optlen != TCPOLEN_MAXSEG)
3231 if (!(flags & TO_SYN))
3233 to->to_flags |= TOF_MSS;
3234 bcopy((char *)cp + 2,
3235 (char *)&to->to_mss, sizeof(to->to_mss));
3236 to->to_mss = ntohs(to->to_mss);
3239 if (optlen != TCPOLEN_WINDOW)
3241 if (!(flags & TO_SYN))
3243 to->to_flags |= TOF_SCALE;
3244 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3246 case TCPOPT_TIMESTAMP:
3247 if (optlen != TCPOLEN_TIMESTAMP)
3249 to->to_flags |= TOF_TS;
3250 bcopy((char *)cp + 2,
3251 (char *)&to->to_tsval, sizeof(to->to_tsval));
3252 to->to_tsval = ntohl(to->to_tsval);
3253 bcopy((char *)cp + 6,
3254 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3255 to->to_tsecr = ntohl(to->to_tsecr);
3257 #ifdef TCP_SIGNATURE
3259 * XXX In order to reply to a host which has set the
3260 * TCP_SIGNATURE option in its initial SYN, we have to
3261 * record the fact that the option was observed here
3262 * for the syncache code to perform the correct response.
3264 case TCPOPT_SIGNATURE:
3265 if (optlen != TCPOLEN_SIGNATURE)
3267 to->to_flags |= TOF_SIGNATURE;
3268 to->to_signature = cp + 2;
3271 case TCPOPT_SACK_PERMITTED:
3272 if (optlen != TCPOLEN_SACK_PERMITTED)
3274 if (!(flags & TO_SYN))
3278 to->to_flags |= TOF_SACKPERM;
3281 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3285 to->to_flags |= TOF_SACK;
3286 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3287 to->to_sacks = cp + 2;
3288 TCPSTAT_INC(tcps_sack_rcv_blocks);
3297 * Pull out of band byte out of a segment so
3298 * it doesn't appear in the user's data queue.
3299 * It is still reflected in the segment length for
3300 * sequencing purposes.
3303 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3306 int cnt = off + th->th_urp - 1;
3309 if (m->m_len > cnt) {
3310 char *cp = mtod(m, caddr_t) + cnt;
3311 struct tcpcb *tp = sototcpcb(so);
3313 INP_WLOCK_ASSERT(tp->t_inpcb);
3316 tp->t_oobflags |= TCPOOB_HAVEDATA;
3317 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3319 if (m->m_flags & M_PKTHDR)
3328 panic("tcp_pulloutofband");
3332 * Collect new round-trip time estimate
3333 * and update averages and current timeout.
3336 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3340 INP_WLOCK_ASSERT(tp->t_inpcb);
3342 TCPSTAT_INC(tcps_rttupdated);
3344 if (tp->t_srtt != 0) {
3346 * srtt is stored as fixed point with 5 bits after the
3347 * binary point (i.e., scaled by 8). The following magic
3348 * is equivalent to the smoothing algorithm in rfc793 with
3349 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3350 * point). Adjust rtt to origin 0.
3352 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3353 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3355 if ((tp->t_srtt += delta) <= 0)
3359 * We accumulate a smoothed rtt variance (actually, a
3360 * smoothed mean difference), then set the retransmit
3361 * timer to smoothed rtt + 4 times the smoothed variance.
3362 * rttvar is stored as fixed point with 4 bits after the
3363 * binary point (scaled by 16). The following is
3364 * equivalent to rfc793 smoothing with an alpha of .75
3365 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3366 * rfc793's wired-in beta.
3370 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3371 if ((tp->t_rttvar += delta) <= 0)
3373 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3374 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3377 * No rtt measurement yet - use the unsmoothed rtt.
3378 * Set the variance to half the rtt (so our first
3379 * retransmit happens at 3*rtt).
3381 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3382 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3383 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3389 * the retransmit should happen at rtt + 4 * rttvar.
3390 * Because of the way we do the smoothing, srtt and rttvar
3391 * will each average +1/2 tick of bias. When we compute
3392 * the retransmit timer, we want 1/2 tick of rounding and
3393 * 1 extra tick because of +-1/2 tick uncertainty in the
3394 * firing of the timer. The bias will give us exactly the
3395 * 1.5 tick we need. But, because the bias is
3396 * statistical, we have to test that we don't drop below
3397 * the minimum feasible timer (which is 2 ticks).
3399 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3400 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3403 * We received an ack for a packet that wasn't retransmitted;
3404 * it is probably safe to discard any error indications we've
3405 * received recently. This isn't quite right, but close enough
3406 * for now (a route might have failed after we sent a segment,
3407 * and the return path might not be symmetrical).
3409 tp->t_softerror = 0;
3413 * Determine a reasonable value for maxseg size.
3414 * If the route is known, check route for mtu.
3415 * If none, use an mss that can be handled on the outgoing interface
3416 * without forcing IP to fragment. If no route is found, route has no mtu,
3417 * or the destination isn't local, use a default, hopefully conservative
3418 * size (usually 512 or the default IP max size, but no more than the mtu
3419 * of the interface), as we can't discover anything about intervening
3420 * gateways or networks. We also initialize the congestion/slow start
3421 * window to be a single segment if the destination isn't local.
3422 * While looking at the routing entry, we also initialize other path-dependent
3423 * parameters from pre-set or cached values in the routing entry.
3425 * Also take into account the space needed for options that we
3426 * send regularly. Make maxseg shorter by that amount to assure
3427 * that we can send maxseg amount of data even when the options
3428 * are present. Store the upper limit of the length of options plus
3431 * NOTE that this routine is only called when we process an incoming
3432 * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3433 * settings are handled in tcp_mssopt().
3436 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
3437 struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3441 struct inpcb *inp = tp->t_inpcb;
3442 struct hc_metrics_lite metrics;
3445 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3446 size_t min_protoh = isipv6 ?
3447 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3448 sizeof (struct tcpiphdr);
3450 const size_t min_protoh = sizeof(struct tcpiphdr);
3453 INP_WLOCK_ASSERT(tp->t_inpcb);
3455 if (mtuoffer != -1) {
3456 KASSERT(offer == -1, ("%s: conflict", __func__));
3457 offer = mtuoffer - min_protoh;
3464 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
3465 tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt;
3468 #if defined(INET) && defined(INET6)
3473 maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
3474 tp->t_maxopd = tp->t_maxseg = V_tcp_mssdflt;
3479 * No route to sender, stay with default mss and return.
3483 * In case we return early we need to initialize metrics
3484 * to a defined state as tcp_hc_get() would do for us
3485 * if there was no cache hit.
3487 if (metricptr != NULL)
3488 bzero(metricptr, sizeof(struct hc_metrics_lite));
3492 /* What have we got? */
3496 * Offer == 0 means that there was no MSS on the SYN
3497 * segment, in this case we use tcp_mssdflt as
3498 * already assigned to t_maxopd above.
3500 offer = tp->t_maxopd;
3505 * Offer == -1 means that we didn't receive SYN yet.
3511 * Prevent DoS attack with too small MSS. Round up
3512 * to at least minmss.
3514 offer = max(offer, V_tcp_minmss);
3518 * rmx information is now retrieved from tcp_hostcache.
3520 tcp_hc_get(&inp->inp_inc, &metrics);
3521 if (metricptr != NULL)
3522 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3525 * If there's a discovered mtu int tcp hostcache, use it
3526 * else, use the link mtu.
3528 if (metrics.rmx_mtu)
3529 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3533 mss = maxmtu - min_protoh;
3534 if (!V_path_mtu_discovery &&
3535 !in6_localaddr(&inp->in6p_faddr))
3536 mss = min(mss, V_tcp_v6mssdflt);
3539 #if defined(INET) && defined(INET6)
3544 mss = maxmtu - min_protoh;
3545 if (!V_path_mtu_discovery &&
3546 !in_localaddr(inp->inp_faddr))
3547 mss = min(mss, V_tcp_mssdflt);
3551 * XXX - The above conditional (mss = maxmtu - min_protoh)
3552 * probably violates the TCP spec.
3553 * The problem is that, since we don't know the
3554 * other end's MSS, we are supposed to use a conservative
3555 * default. But, if we do that, then MTU discovery will
3556 * never actually take place, because the conservative
3557 * default is much less than the MTUs typically seen
3558 * on the Internet today. For the moment, we'll sweep
3559 * this under the carpet.
3561 * The conservative default might not actually be a problem
3562 * if the only case this occurs is when sending an initial
3563 * SYN with options and data to a host we've never talked
3564 * to before. Then, they will reply with an MSS value which
3565 * will get recorded and the new parameters should get
3566 * recomputed. For Further Study.
3569 mss = min(mss, offer);
3572 * Sanity check: make sure that maxopd will be large
3573 * enough to allow some data on segments even if the
3574 * all the option space is used (40bytes). Otherwise
3575 * funny things may happen in tcp_output.
3580 * maxopd stores the maximum length of data AND options
3581 * in a segment; maxseg is the amount of data in a normal
3582 * segment. We need to store this value (maxopd) apart
3583 * from maxseg, because now every segment carries options
3584 * and thus we normally have somewhat less data in segments.
3589 * origoffer==-1 indicates that no segments were received yet.
3590 * In this case we just guess.
3592 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3594 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3595 mss -= TCPOLEN_TSTAMP_APPA;
3601 tcp_mss(struct tcpcb *tp, int offer)
3607 struct hc_metrics_lite metrics;
3608 struct tcp_ifcap cap;
3610 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3612 bzero(&cap, sizeof(cap));
3613 tcp_mss_update(tp, offer, -1, &metrics, &cap);
3619 * If there's a pipesize, change the socket buffer to that size,
3620 * don't change if sb_hiwat is different than default (then it
3621 * has been changed on purpose with setsockopt).
3622 * Make the socket buffers an integral number of mss units;
3623 * if the mss is larger than the socket buffer, decrease the mss.
3625 so = inp->inp_socket;
3626 SOCKBUF_LOCK(&so->so_snd);
3627 if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
3628 bufsize = metrics.rmx_sendpipe;
3630 bufsize = so->so_snd.sb_hiwat;
3634 bufsize = roundup(bufsize, mss);
3635 if (bufsize > sb_max)
3637 if (bufsize > so->so_snd.sb_hiwat)
3638 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3640 SOCKBUF_UNLOCK(&so->so_snd);
3643 SOCKBUF_LOCK(&so->so_rcv);
3644 if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
3645 bufsize = metrics.rmx_recvpipe;
3647 bufsize = so->so_rcv.sb_hiwat;
3648 if (bufsize > mss) {
3649 bufsize = roundup(bufsize, mss);
3650 if (bufsize > sb_max)
3652 if (bufsize > so->so_rcv.sb_hiwat)
3653 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3655 SOCKBUF_UNLOCK(&so->so_rcv);
3657 /* Check the interface for TSO capabilities. */
3658 if (cap.ifcap & CSUM_TSO) {
3659 tp->t_flags |= TF_TSO;
3660 tp->t_tsomax = cap.tsomax;
3665 * Determine the MSS option to send on an outgoing SYN.
3668 tcp_mssopt(struct in_conninfo *inc)
3675 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3678 if (inc->inc_flags & INC_ISIPV6) {
3679 mss = V_tcp_v6mssdflt;
3680 maxmtu = tcp_maxmtu6(inc, NULL);
3681 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3684 #if defined(INET) && defined(INET6)
3689 mss = V_tcp_mssdflt;
3690 maxmtu = tcp_maxmtu(inc, NULL);
3691 min_protoh = sizeof(struct tcpiphdr);
3694 #if defined(INET6) || defined(INET)
3695 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3698 if (maxmtu && thcmtu)
3699 mss = min(maxmtu, thcmtu) - min_protoh;
3700 else if (maxmtu || thcmtu)
3701 mss = max(maxmtu, thcmtu) - min_protoh;
3708 * On a partial ack arrives, force the retransmission of the
3709 * next unacknowledged segment. Do not clear tp->t_dupacks.
3710 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3714 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3716 tcp_seq onxt = tp->snd_nxt;
3717 u_long ocwnd = tp->snd_cwnd;
3719 INP_WLOCK_ASSERT(tp->t_inpcb);
3721 tcp_timer_activate(tp, TT_REXMT, 0);
3723 tp->snd_nxt = th->th_ack;
3725 * Set snd_cwnd to one segment beyond acknowledged offset.
3726 * (tp->snd_una has not yet been updated when this function is called.)
3728 tp->snd_cwnd = tp->t_maxseg + BYTES_THIS_ACK(tp, th);
3729 tp->t_flags |= TF_ACKNOW;
3730 (void) tcp_output(tp);
3731 tp->snd_cwnd = ocwnd;
3732 if (SEQ_GT(onxt, tp->snd_nxt))
3735 * Partial window deflation. Relies on fact that tp->snd_una
3738 if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3739 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3742 tp->snd_cwnd += tp->t_maxseg;