2 * Copyright (c) 2000-2017 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
30 * The Regents of the University of California. All rights reserved.
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
35 * 1. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 * notice, this list of conditions and the following disclaimer in the
39 * documentation and/or other materials provided with the distribution.
40 * 3. All advertising materials mentioning features or use of this software
41 * must display the following acknowledgement:
42 * This product includes software developed by the University of
43 * California, Berkeley and its contributors.
44 * 4. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
61 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.16 2001/08/22 00:59:12 silby Exp $
64 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
65 * support for mandatory and extensible security protections. This notice
66 * is included in support of clause 2.2 (b) of the Apple Public License,
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/kernel.h>
73 #include <sys/sysctl.h>
74 #include <sys/malloc.h>
76 #include <sys/proc.h> /* for proc0 declaration */
77 #include <sys/protosw.h>
78 #include <sys/socket.h>
79 #include <sys/socketvar.h>
80 #include <sys/syslog.h>
81 #include <sys/mcache.h>
85 #include <sys/kauth.h>
86 #include <kern/cpu_number.h> /* before tcp_seq.h, for tcp_random18() */
88 #include <machine/endian.h>
91 #include <net/if_types.h>
92 #include <net/route.h>
93 #include <net/ntstat.h>
96 #include <netinet/in.h>
97 #include <netinet/in_systm.h>
98 #include <netinet/ip.h>
99 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
100 #include <netinet/in_var.h>
101 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
102 #include <netinet/in_pcb.h>
103 #include <netinet/ip_var.h>
104 #include <mach/sdt.h>
106 #include <netinet/ip6.h>
107 #include <netinet/icmp6.h>
108 #include <netinet6/nd6.h>
109 #include <netinet6/ip6_var.h>
110 #include <netinet6/in6_pcb.h>
112 #include <netinet/tcp.h>
113 #include <netinet/tcp_cache.h>
114 #include <netinet/tcp_fsm.h>
115 #include <netinet/tcp_seq.h>
116 #include <netinet/tcp_timer.h>
117 #include <netinet/tcp_var.h>
118 #include <netinet/tcp_cc.h>
119 #include <dev/random/randomdev.h>
120 #include <kern/zalloc.h>
122 #include <netinet6/tcp6_var.h>
124 #include <netinet/tcpip.h>
126 #include <netinet/tcp_debug.h>
127 u_char tcp_saveipgen
[40]; /* the size must be of max ip header, now IPv6 */
128 struct tcphdr tcp_savetcp
;
129 #endif /* TCPDEBUG */
132 #include <netinet6/ipsec.h>
134 #include <netinet6/ipsec6.h>
136 #include <netkey/key.h>
139 #if CONFIG_MACF_NET || CONFIG_MACF_SOCKET
140 #include <security/mac_framework.h>
141 #endif /* CONFIG_MACF_NET || CONFIG_MACF_SOCKET */
143 #include <sys/kdebug.h>
144 #include <netinet/lro_ext.h>
146 #include <netinet/mptcp_var.h>
147 #include <netinet/mptcp.h>
148 #include <netinet/mptcp_opt.h>
151 #include <corecrypto/ccaes.h>
153 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETTCP, 0)
154 #define DBG_LAYER_END NETDBG_CODE(DBG_NETTCP, 2)
155 #define DBG_FNC_TCP_INPUT NETDBG_CODE(DBG_NETTCP, (3 << 8))
156 #define DBG_FNC_TCP_NEWCONN NETDBG_CODE(DBG_NETTCP, (7 << 8))
158 #define TCP_RTT_HISTORY_EXPIRE_TIME (60 * TCP_RETRANSHZ)
159 #define TCP_RECV_THROTTLE_WIN (5 * TCP_RETRANSHZ)
160 #define TCP_STRETCHACK_ENABLE_PKTCNT 2000
162 struct tcpstat tcpstat
;
164 static int log_in_vain
= 0;
165 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, log_in_vain
,
166 CTLFLAG_RW
| CTLFLAG_LOCKED
, &log_in_vain
, 0,
167 "Log all incoming TCP connections");
169 static int blackhole
= 0;
170 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, blackhole
,
171 CTLFLAG_RW
| CTLFLAG_LOCKED
, &blackhole
, 0,
172 "Do not send RST when dropping refused connections");
174 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, delayed_ack
,
175 CTLFLAG_RW
| CTLFLAG_LOCKED
, int, tcp_delack_enabled
, 3,
176 "Delay ACK to try and piggyback it onto a data packet");
178 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, tcp_lq_overflow
,
179 CTLFLAG_RW
| CTLFLAG_LOCKED
, int, tcp_lq_overflow
, 1,
180 "Listen Queue Overflow");
182 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, recvbg
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
183 int, tcp_recv_bg
, 0, "Receive background");
186 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, drop_synfin
,
187 CTLFLAG_RW
| CTLFLAG_LOCKED
, static int, drop_synfin
, 1,
188 "Drop TCP packets with SYN+FIN set");
191 SYSCTL_NODE(_net_inet_tcp
, OID_AUTO
, reass
, CTLFLAG_RW
| CTLFLAG_LOCKED
, 0,
192 "TCP Segment Reassembly Queue");
194 static int tcp_reass_overflows
= 0;
195 SYSCTL_INT(_net_inet_tcp_reass
, OID_AUTO
, overflows
,
196 CTLFLAG_RD
| CTLFLAG_LOCKED
, &tcp_reass_overflows
, 0,
197 "Global number of TCP Segment Reassembly Queue Overflows");
200 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, slowlink_wsize
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
201 __private_extern__
int, slowlink_wsize
, 8192,
202 "Maximum advertised window size for slowlink");
204 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, maxseg_unacked
,
205 CTLFLAG_RW
| CTLFLAG_LOCKED
, int, maxseg_unacked
, 8,
206 "Maximum number of outstanding segments left unacked");
208 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, rfc3465
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
209 int, tcp_do_rfc3465
, 1, "");
211 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, rfc3465_lim2
,
212 CTLFLAG_RW
| CTLFLAG_LOCKED
, int, tcp_do_rfc3465_lim2
, 1,
213 "Appropriate bytes counting w/ L=2*SMSS");
215 int rtt_samples_per_slot
= 20;
217 int tcp_acc_iaj_high_thresh
= ACC_IAJ_HIGH_THRESH
;
218 u_int32_t tcp_autorcvbuf_inc_shift
= 3;
219 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, recv_allowed_iaj
,
220 CTLFLAG_RW
| CTLFLAG_LOCKED
, int, tcp_allowed_iaj
, ALLOWED_IAJ
,
221 "Allowed inter-packet arrival jiter");
222 #if (DEVELOPMENT || DEBUG)
223 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, acc_iaj_high_thresh
,
224 CTLFLAG_RW
| CTLFLAG_LOCKED
, &tcp_acc_iaj_high_thresh
, 0,
225 "Used in calculating maximum accumulated IAJ");
227 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, autorcvbufincshift
,
228 CTLFLAG_RW
| CTLFLAG_LOCKED
, &tcp_autorcvbuf_inc_shift
, 0,
229 "Shift for increment in receive socket buffer size");
230 #endif /* (DEVELOPMENT || DEBUG) */
232 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, doautorcvbuf
,
233 CTLFLAG_RW
| CTLFLAG_LOCKED
, u_int32_t
, tcp_do_autorcvbuf
, 1,
234 "Enable automatic socket buffer tuning");
236 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, autorcvbufmax
,
237 CTLFLAG_RW
| CTLFLAG_LOCKED
, u_int32_t
, tcp_autorcvbuf_max
, 512 * 1024,
238 "Maximum receive socket buffer size");
244 #endif /* !CONFIG_EMBEDDED */
245 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, lro
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
246 &sw_lro
, 0, "Used to coalesce TCP packets");
249 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, lrodbg
,
250 CTLFLAG_RW
| CTLFLAG_LOCKED
, &lrodebug
, 0,
251 "Used to debug SW LRO");
254 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, lro_startcnt
,
255 CTLFLAG_RW
| CTLFLAG_LOCKED
, &lro_start
, 0,
256 "Segments for starting LRO computed as power of 2");
258 int limited_txmt
= 1;
261 int tcp_dsack_enable
= 1;
263 #if (DEVELOPMENT || DEBUG)
264 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, limited_transmit
,
265 CTLFLAG_RW
| CTLFLAG_LOCKED
, &limited_txmt
, 0,
266 "Enable limited transmit");
268 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, early_rexmt
,
269 CTLFLAG_RW
| CTLFLAG_LOCKED
, &early_rexmt
, 0,
270 "Enable Early Retransmit");
272 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, sack_ackadv
,
273 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sack_ackadv
, 0,
274 "Use SACK with cumulative ack advancement as a dupack");
276 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, dsack_enable
,
277 CTLFLAG_RW
| CTLFLAG_LOCKED
, &tcp_dsack_enable
, 0,
278 "use DSACK TCP option to report duplicate segments");
280 #endif /* (DEVELOPMENT || DEBUG) */
281 int tcp_disable_access_to_stats
= 1;
282 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, disable_access_to_stats
,
283 CTLFLAG_RW
| CTLFLAG_LOCKED
, &tcp_disable_access_to_stats
, 0,
284 "Disable access to tcpstat");
286 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, challengeack_limit
,
287 CTLFLAG_RW
| CTLFLAG_LOCKED
, uint32_t, tcp_challengeack_limit
, 10,
288 "Maximum number of challenge ACKs per connection per second");
290 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, do_rfc5961
,
291 CTLFLAG_RW
| CTLFLAG_LOCKED
, static int, tcp_do_rfc5961
, 1,
292 "Enable/Disable full RFC 5961 compliance");
294 extern int tcp_TCPTV_MIN
;
295 extern int tcp_acc_iaj_high
;
296 extern int tcp_acc_iaj_react_limit
;
298 int tcprexmtthresh
= 3;
301 struct timeval tcp_uptime
; /* uptime when tcp_now was last updated */
302 lck_spin_t
*tcp_uptime_lock
; /* Used to sychronize updates to tcp_now */
304 struct inpcbhead tcb
;
305 #define tcb6 tcb /* for KAME src sync over BSD*'s */
306 struct inpcbinfo tcbinfo
;
308 static void tcp_dooptions(struct tcpcb
*, u_char
*, int, struct tcphdr
*,
310 static void tcp_finalize_options(struct tcpcb
*, struct tcpopt
*, unsigned int);
311 static void tcp_pulloutofband(struct socket
*,
312 struct tcphdr
*, struct mbuf
*, int);
313 static int tcp_reass(struct tcpcb
*, struct tcphdr
*, int *, struct mbuf
*,
315 static void tcp_xmit_timer(struct tcpcb
*, int, u_int32_t
, tcp_seq
);
316 static inline unsigned int tcp_maxmtu(struct rtentry
*);
317 static inline int tcp_stretch_ack_enable(struct tcpcb
*tp
, int thflags
);
318 static inline void tcp_adaptive_rwtimo_check(struct tcpcb
*, int);
321 static inline void update_iaj_state(struct tcpcb
*tp
, uint32_t tlen
,
323 void compute_iaj(struct tcpcb
*tp
, int nlropkts
, int lro_delay_factor
);
324 static void compute_iaj_meat(struct tcpcb
*tp
, uint32_t cur_iaj
);
325 #endif /* TRAFFIC_MGT */
328 static inline unsigned int tcp_maxmtu6(struct rtentry
*);
331 unsigned int get_maxmtu(struct rtentry
*);
333 static void tcp_sbrcv_grow(struct tcpcb
*tp
, struct sockbuf
*sb
,
334 struct tcpopt
*to
, u_int32_t tlen
, u_int32_t rcvbuf_max
);
335 void tcp_sbrcv_trim(struct tcpcb
*tp
, struct sockbuf
*sb
);
336 static void tcp_sbsnd_trim(struct sockbuf
*sbsnd
);
337 static inline void tcp_sbrcv_tstmp_check(struct tcpcb
*tp
);
338 static inline void tcp_sbrcv_reserve(struct tcpcb
*tp
, struct sockbuf
*sb
,
339 u_int32_t newsize
, u_int32_t idealsize
, u_int32_t rcvbuf_max
);
340 static void tcp_bad_rexmt_restore_state(struct tcpcb
*tp
, struct tcphdr
*th
);
341 static void tcp_compute_rtt(struct tcpcb
*tp
, struct tcpopt
*to
,
343 static void tcp_early_rexmt_check(struct tcpcb
*tp
, struct tcphdr
*th
);
344 static void tcp_bad_rexmt_check(struct tcpcb
*tp
, struct tcphdr
*th
,
347 * Constants used for resizing receive socket buffer
348 * when timestamps are not supported
350 #define TCPTV_RCVNOTS_QUANTUM 100
351 #define TCP_RCVNOTS_BYTELEVEL 204800
354 * Constants used for limiting early retransmits
357 #define TCP_EARLY_REXMT_WIN (60 * TCP_RETRANSHZ) /* 60 seconds */
358 #define TCP_EARLY_REXMT_LIMIT 10
360 extern void ipfwsyslog( int level
, const char *format
, ...);
361 extern int fw_verbose
;
364 extern void ipfw_stealth_stats_incr_tcp(void);
366 #define log_in_vain_log( a ) { \
367 if ( (log_in_vain == 3 ) && (fw_verbose == 2)) { /* Apple logging, log to ipfw.log */ \
369 } else if ( (log_in_vain == 4 ) && (fw_verbose == 2)) { \
370 ipfw_stealth_stats_incr_tcp(); \
375 #define log_in_vain_log( a ) { log a; }
378 int tcp_rcvunackwin
= TCPTV_UNACKWIN
;
379 int tcp_maxrcvidle
= TCPTV_MAXRCVIDLE
;
380 SYSCTL_SKMEM_TCP_INT(OID_AUTO
, rcvsspktcnt
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
381 int, tcp_rcvsspktcnt
, TCP_RCV_SS_PKTCOUNT
, "packets to be seen before receiver stretches acks");
383 #define DELAY_ACK(tp, th) \
384 (CC_ALGO(tp)->delay_ack != NULL && CC_ALGO(tp)->delay_ack(tp, th))
386 static int tcp_dropdropablreq(struct socket
*head
);
387 static void tcp_newreno_partial_ack(struct tcpcb
*tp
, struct tcphdr
*th
);
388 static void update_base_rtt(struct tcpcb
*tp
, uint32_t rtt
);
389 void tcp_set_background_cc(struct socket
*so
);
390 void tcp_set_foreground_cc(struct socket
*so
);
391 static void tcp_set_new_cc(struct socket
*so
, uint16_t cc_index
);
392 static void tcp_bwmeas_check(struct tcpcb
*tp
);
396 reset_acc_iaj(struct tcpcb
*tp
)
403 update_iaj_state(struct tcpcb
*tp
, uint32_t size
, int rst_size
)
408 if (tp
->iaj_size
== 0 || size
>= tp
->iaj_size
) {
410 tp
->iaj_rcv_ts
= tcp_now
;
411 tp
->iaj_small_pkt
= 0;
415 /* For every 32 bit unsigned integer(v), this function will find the
416 * largest integer n such that (n*n <= v). This takes at most 16 iterations
417 * irrespective of the value of v and does not involve multiplications.
420 isqrt(unsigned int val
)
422 unsigned int sqrt_cache
[11] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100};
423 unsigned int temp
, g
= 0, b
= 0x8000, bshft
= 15;
425 for (g
= 0; g
<= 10; ++g
) {
426 if (sqrt_cache
[g
] > val
) {
429 } else if (sqrt_cache
[g
] == val
) {
435 temp
= (((g
<< 1) + b
) << (bshft
--));
441 } while (b
> 0 && val
> 0);
447 * With LRO, roughly estimate the inter arrival time between
448 * each sub coalesced packet as an average. Count the delay
449 * cur_iaj to be the delay between the last packet received
450 * and the first packet of the LRO stream. Due to round off errors
451 * cur_iaj may be the same as lro_delay_factor. Averaging has
452 * round off errors too. lro_delay_factor may be close to 0
453 * in steady state leading to lower values fed to compute_iaj_meat.
456 compute_iaj(struct tcpcb
*tp
, int nlropkts
, int lro_delay_factor
)
458 uint32_t cur_iaj
= tcp_now
- tp
->iaj_rcv_ts
;
459 uint32_t timediff
= 0;
461 if (cur_iaj
>= lro_delay_factor
) {
462 cur_iaj
= cur_iaj
- lro_delay_factor
;
465 compute_iaj_meat(tp
, cur_iaj
);
473 timediff
= lro_delay_factor
/ nlropkts
;
475 while (nlropkts
> 0) {
476 compute_iaj_meat(tp
, timediff
);
483 compute_iaj_meat(struct tcpcb
*tp
, uint32_t cur_iaj
)
485 /* When accumulated IAJ reaches MAX_ACC_IAJ in milliseconds,
486 * throttle the receive window to a minimum of MIN_IAJ_WIN packets
488 #define MAX_ACC_IAJ (tcp_acc_iaj_high_thresh + tcp_acc_iaj_react_limit)
489 #define IAJ_DIV_SHIFT 4
490 #define IAJ_ROUNDUP_CONST (1 << (IAJ_DIV_SHIFT - 1))
492 uint32_t allowed_iaj
, acc_iaj
= 0;
497 cur_iaj_dev
= (cur_iaj
- tp
->avg_iaj
);
499 /* Allow a jitter of "allowed_iaj" milliseconds. Some connections
500 * may have a constant jitter more than that. We detect this by
501 * using standard deviation.
503 allowed_iaj
= tp
->avg_iaj
+ tp
->std_dev_iaj
;
504 if (allowed_iaj
< tcp_allowed_iaj
) {
505 allowed_iaj
= tcp_allowed_iaj
;
508 /* Initially when the connection starts, the senders congestion
509 * window is small. During this period we avoid throttling a
510 * connection because we do not have a good starting point for
511 * allowed_iaj. IAJ_IGNORE_PKTCNT is used to quietly gloss over
512 * the first few packets.
514 if (tp
->iaj_pktcnt
> IAJ_IGNORE_PKTCNT
) {
515 if (cur_iaj
<= allowed_iaj
) {
516 if (tp
->acc_iaj
>= 2) {
517 acc_iaj
= tp
->acc_iaj
- 2;
522 acc_iaj
= tp
->acc_iaj
+ (cur_iaj
- allowed_iaj
);
525 if (acc_iaj
> MAX_ACC_IAJ
) {
526 acc_iaj
= MAX_ACC_IAJ
;
528 tp
->acc_iaj
= acc_iaj
;
531 /* Compute weighted average where the history has a weight of
532 * 15 out of 16 and the current value has a weight of 1 out of 16.
533 * This will make the short-term measurements have more weight.
535 * The addition of 8 will help to round-up the value
536 * instead of round-down
538 tp
->avg_iaj
= (((tp
->avg_iaj
<< IAJ_DIV_SHIFT
) - tp
->avg_iaj
)
539 + cur_iaj
+ IAJ_ROUNDUP_CONST
) >> IAJ_DIV_SHIFT
;
541 /* Compute Root-mean-square of deviation where mean is a weighted
542 * average as described above.
544 temp
= tp
->std_dev_iaj
* tp
->std_dev_iaj
;
545 mean
= (((temp
<< IAJ_DIV_SHIFT
) - temp
)
546 + (cur_iaj_dev
* cur_iaj_dev
)
547 + IAJ_ROUNDUP_CONST
) >> IAJ_DIV_SHIFT
;
549 tp
->std_dev_iaj
= isqrt(mean
);
551 DTRACE_TCP3(iaj
, struct tcpcb
*, tp
, uint32_t, cur_iaj
,
552 uint32_t, allowed_iaj
);
556 #endif /* TRAFFIC_MGT */
559 * Perform rate limit check per connection per second
560 * tp->t_challengeack_last is the last_time diff was greater than 1sec
561 * tp->t_challengeack_count is the number of ACKs sent (within 1sec)
562 * Return TRUE if we shouldn't send the ACK due to rate limitation
563 * Return FALSE if it is still ok to send challenge ACK
566 tcp_is_ack_ratelimited(struct tcpcb
*tp
)
568 boolean_t ret
= TRUE
;
569 uint32_t now
= tcp_now
;
572 diff
= timer_diff(now
, 0, tp
->t_challengeack_last
, 0);
573 /* If it is first time or diff > 1000ms,
574 * update the challengeack_last and reset the
575 * current count of ACKs
577 if (tp
->t_challengeack_last
== 0 || diff
>= 1000) {
578 tp
->t_challengeack_last
= now
;
579 tp
->t_challengeack_count
= 0;
581 } else if (tp
->t_challengeack_count
< tcp_challengeack_limit
) {
585 /* Careful about wrap-around */
586 if (ret
== FALSE
&& (tp
->t_challengeack_count
+ 1 > 0)) {
587 tp
->t_challengeack_count
++;
593 /* Check if enough amount of data has been acknowledged since
594 * bw measurement was started
597 tcp_bwmeas_check(struct tcpcb
*tp
)
599 int32_t bw_meas_bytes
;
600 uint32_t bw
, bytes
, elapsed_time
;
602 if (SEQ_LEQ(tp
->snd_una
, tp
->t_bwmeas
->bw_start
)) {
606 bw_meas_bytes
= tp
->snd_una
- tp
->t_bwmeas
->bw_start
;
607 if ((tp
->t_flagsext
& TF_BWMEAS_INPROGRESS
) &&
608 bw_meas_bytes
>= (int32_t)(tp
->t_bwmeas
->bw_size
)) {
609 bytes
= bw_meas_bytes
;
610 elapsed_time
= tcp_now
- tp
->t_bwmeas
->bw_ts
;
611 if (elapsed_time
> 0) {
612 bw
= bytes
/ elapsed_time
;
614 if (tp
->t_bwmeas
->bw_sndbw
> 0) {
615 tp
->t_bwmeas
->bw_sndbw
=
616 (((tp
->t_bwmeas
->bw_sndbw
<< 3)
617 - tp
->t_bwmeas
->bw_sndbw
)
620 tp
->t_bwmeas
->bw_sndbw
= bw
;
623 /* Store the maximum value */
624 if (tp
->t_bwmeas
->bw_sndbw_max
== 0) {
625 tp
->t_bwmeas
->bw_sndbw_max
=
626 tp
->t_bwmeas
->bw_sndbw
;
628 tp
->t_bwmeas
->bw_sndbw_max
=
629 max(tp
->t_bwmeas
->bw_sndbw
,
630 tp
->t_bwmeas
->bw_sndbw_max
);
634 tp
->t_flagsext
&= ~(TF_BWMEAS_INPROGRESS
);
639 tcp_reass(struct tcpcb
*tp
, struct tcphdr
*th
, int *tlenp
, struct mbuf
*m
,
643 struct tseg_qent
*p
= NULL
;
644 struct tseg_qent
*nq
;
645 struct tseg_qent
*te
= NULL
;
646 struct inpcb
*inp
= tp
->t_inpcb
;
647 struct socket
*so
= inp
->inp_socket
;
650 struct mbuf
*oodata
= NULL
;
653 boolean_t cell
= IFNET_IS_CELLULAR(ifp
);
654 boolean_t wifi
= (!cell
&& IFNET_IS_WIFI(ifp
));
655 boolean_t wired
= (!wifi
&& IFNET_IS_WIRED(ifp
));
656 boolean_t dsack_set
= FALSE
;
659 * Call with th==0 after become established to
660 * force pre-ESTABLISHED data up to user socket.
667 * If the reassembly queue already has entries or if we are going
668 * to add a new one, then the connection has reached a loss state.
669 * Reset the stretch-ack algorithm at this point.
671 tcp_reset_stretch_ack(tp
);
674 if (tp
->acc_iaj
> 0) {
677 #endif /* TRAFFIC_MGT */
680 * Limit the number of segments in the reassembly queue to prevent
681 * holding on to too many segments (and thus running out of mbufs).
682 * Make sure to let the missing segment through which caused this
683 * queue. Always keep one global queue entry spare to be able to
684 * process the missing segment.
686 qlimit
= min(max(100, so
->so_rcv
.sb_hiwat
>> 10),
687 (TCP_AUTORCVBUF_MAX(ifp
) >> 10));
688 if (th
->th_seq
!= tp
->rcv_nxt
&&
689 (tp
->t_reassqlen
+ 1) >= qlimit
) {
690 tcp_reass_overflows
++;
691 tcpstat
.tcps_rcvmemdrop
++;
697 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
698 te
= (struct tseg_qent
*) zalloc(tcp_reass_zone
);
700 tcpstat
.tcps_rcvmemdrop
++;
707 * Find a segment which begins after this one does.
709 LIST_FOREACH(q
, &tp
->t_segq
, tqe_q
) {
710 if (SEQ_GT(q
->tqe_th
->th_seq
, th
->th_seq
)) {
717 * If there is a preceding segment, it may provide some of
718 * our data already. If so, drop the data from the incoming
719 * segment. If it provides all of our data, drop us.
723 /* conversion to int (in i) handles seq wraparound */
724 i
= p
->tqe_th
->th_seq
+ p
->tqe_len
- th
->th_seq
;
726 if (TCP_DSACK_ENABLED(tp
) && i
> 1) {
728 * Note duplicate data sequnce numbers
729 * to report in DSACK option
731 tp
->t_dsack_lseq
= th
->th_seq
;
732 tp
->t_dsack_rseq
= th
->th_seq
+
736 * Report only the first part of partial/
737 * non-contiguous duplicate sequence space
742 tcpstat
.tcps_rcvduppack
++;
743 tcpstat
.tcps_rcvdupbyte
+= *tlenp
;
745 nstat_route_rx(inp
->inp_route
.ro_rt
,
747 NSTAT_RX_FLAG_DUPLICATE
);
748 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
750 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
752 tp
->t_stat
.rxduplicatebytes
+= *tlenp
;
753 inp_set_activity_bitmap(inp
);
756 zfree(tcp_reass_zone
, te
);
760 * Try to present any queued data
761 * at the left window edge to the user.
762 * This is needed after the 3-WHS
773 tcpstat
.tcps_rcvoopack
++;
774 tcpstat
.tcps_rcvoobyte
+= *tlenp
;
776 nstat_route_rx(inp
->inp_route
.ro_rt
, 1, *tlenp
,
777 NSTAT_RX_FLAG_OUT_OF_ORDER
);
778 INP_ADD_STAT(inp
, cell
, wifi
, wired
, rxpackets
, 1);
779 INP_ADD_STAT(inp
, cell
, wifi
, wired
, rxbytes
, *tlenp
);
780 tp
->t_stat
.rxoutoforderbytes
+= *tlenp
;
781 inp_set_activity_bitmap(inp
);
785 * While we overlap succeeding segments trim them or,
786 * if they are completely covered, dequeue them.
789 int i
= (th
->th_seq
+ *tlenp
) - q
->tqe_th
->th_seq
;
795 * Report only the first part of partial/non-contiguous
796 * duplicate segment in dsack option. The variable
797 * dsack_set will be true if a previous entry has some of
798 * the duplicate sequence space.
800 if (TCP_DSACK_ENABLED(tp
) && i
> 1 && !dsack_set
) {
801 if (tp
->t_dsack_lseq
== 0) {
802 tp
->t_dsack_lseq
= q
->tqe_th
->th_seq
;
804 tp
->t_dsack_lseq
+ min(i
, q
->tqe_len
);
807 * this segment overlaps data in multple
808 * entries in the reassembly queue, move
809 * the right sequence number further.
812 tp
->t_dsack_rseq
+ min(i
, q
->tqe_len
);
815 if (i
< q
->tqe_len
) {
816 q
->tqe_th
->th_seq
+= i
;
822 nq
= LIST_NEXT(q
, tqe_q
);
823 LIST_REMOVE(q
, tqe_q
);
825 zfree(tcp_reass_zone
, q
);
830 /* Insert the new segment queue entry into place. */
833 te
->tqe_len
= *tlenp
;
836 LIST_INSERT_HEAD(&tp
->t_segq
, te
, tqe_q
);
838 LIST_INSERT_AFTER(p
, te
, tqe_q
);
842 * New out-of-order data exists, and is pointed to by
843 * queue entry te. Set copy_oodata to 1 so out-of-order data
844 * can be copied off to sockbuf after in-order data
847 if (!(so
->so_state
& SS_CANTRCVMORE
)) {
853 * Present data to user, advancing rcv_nxt through
854 * completed sequence space.
856 if (!TCPS_HAVEESTABLISHED(tp
->t_state
)) {
859 q
= LIST_FIRST(&tp
->t_segq
);
860 if (!q
|| q
->tqe_th
->th_seq
!= tp
->rcv_nxt
) {
861 /* Stop using LRO once out of order packets arrive */
862 if (tp
->t_flagsext
& TF_LRO_OFFLOADED
) {
863 tcp_lro_remove_state(inp
->inp_laddr
, inp
->inp_faddr
,
864 th
->th_dport
, th
->th_sport
);
865 tp
->t_flagsext
&= ~TF_LRO_OFFLOADED
;
869 * continue processing if out-of-order data
872 if (q
&& (so
->so_flags
& SOF_ENABLE_MSGS
)) {
873 goto msg_unordered_delivery
;
880 * If there is already another thread doing reassembly for this
881 * connection, it is better to let it finish the job --
884 if (tp
->t_flagsext
& TF_REASS_INPROG
) {
888 tp
->t_flagsext
|= TF_REASS_INPROG
;
889 /* lost packet was recovered, so ooo data can be returned */
890 tcpstat
.tcps_recovered_pkts
++;
893 tp
->rcv_nxt
+= q
->tqe_len
;
894 flags
= q
->tqe_th
->th_flags
& TH_FIN
;
895 LIST_REMOVE(q
, tqe_q
);
896 if (so
->so_state
& SS_CANTRCVMORE
) {
899 so_recv_data_stat(so
, q
->tqe_m
, 0); /* XXXX */
900 if (so
->so_flags
& SOF_ENABLE_MSGS
) {
902 * Append the inorder data as a message to the
903 * receive socket buffer. Also check to see if
904 * the data we are about to deliver is the same
905 * data that we wanted to pass up to the user
906 * out of order. If so, reset copy_oodata --
907 * the received data filled a gap, and
914 if (sbappendstream_rcvdemux(so
, q
->tqe_m
,
915 q
->tqe_th
->th_seq
- (tp
->irs
+ 1), 0)) {
918 if (tp
->t_flagsext
& TF_LRO_OFFLOADED
) {
919 tcp_update_lro_seq(tp
->rcv_nxt
,
920 inp
->inp_laddr
, inp
->inp_faddr
,
921 th
->th_dport
, th
->th_sport
);
924 zfree(tcp_reass_zone
, q
);
926 q
= LIST_FIRST(&tp
->t_segq
);
927 } while (q
&& q
->tqe_th
->th_seq
== tp
->rcv_nxt
);
928 tp
->t_flagsext
&= ~TF_REASS_INPROG
;
931 if ((inp
->inp_vflag
& INP_IPV6
) != 0) {
932 KERNEL_DEBUG(DBG_LAYER_BEG
,
933 ((inp
->inp_fport
<< 16) | inp
->inp_lport
),
934 (((inp
->in6p_laddr
.s6_addr16
[0] & 0xffff) << 16) |
935 (inp
->in6p_faddr
.s6_addr16
[0] & 0xffff)),
940 KERNEL_DEBUG(DBG_LAYER_BEG
,
941 ((inp
->inp_fport
<< 16) | inp
->inp_lport
),
942 (((inp
->inp_laddr
.s_addr
& 0xffff) << 16) |
943 (inp
->inp_faddr
.s_addr
& 0xffff)),
947 msg_unordered_delivery
:
948 /* Deliver out-of-order data as a message */
949 if (te
&& (so
->so_flags
& SOF_ENABLE_MSGS
) && copy_oodata
&& te
->tqe_len
) {
951 * make a copy of the mbuf to be delivered up to
952 * the user, and add it to the sockbuf
954 oodata
= m_copym(te
->tqe_m
, 0, M_COPYALL
, M_DONTWAIT
);
955 if (oodata
!= NULL
) {
956 if (sbappendmsgstream_rcv(&so
->so_rcv
, oodata
,
957 te
->tqe_th
->th_seq
- (tp
->irs
+ 1), 1)) {
959 tcpstat
.tcps_msg_unopkts
++;
961 tcpstat
.tcps_msg_unoappendfail
++;
967 sorwakeup(so
); /* done with socket lock held */
973 * Reduce congestion window -- used when ECN is seen or when a tail loss
974 * probe recovers the last packet.
977 tcp_reduce_congestion_window(
981 * If the current tcp cc module has
982 * defined a hook for tasks to run
983 * before entering FR, call it
985 if (CC_ALGO(tp
)->pre_fr
!= NULL
) {
986 CC_ALGO(tp
)->pre_fr(tp
);
988 ENTER_FASTRECOVERY(tp
);
989 if (tp
->t_flags
& TF_SENTFIN
) {
990 tp
->snd_recover
= tp
->snd_max
- 1;
992 tp
->snd_recover
= tp
->snd_max
;
994 tp
->t_timer
[TCPT_REXMT
] = 0;
995 tp
->t_timer
[TCPT_PTO
] = 0;
997 if (tp
->t_flagsext
& TF_CWND_NONVALIDATED
) {
998 tcp_cc_adjust_nonvalidated_cwnd(tp
);
1000 tp
->snd_cwnd
= tp
->snd_ssthresh
+
1001 tp
->t_maxseg
* tcprexmtthresh
;
1006 * This function is called upon reception of data on a socket. It's purpose is
1007 * to handle the adaptive keepalive timers that monitor whether the connection
1008 * is making progress. First the adaptive read-timer, second the TFO probe-timer.
1010 * The application wants to get an event if there is a stall during read.
1011 * Set the initial keepalive timeout to be equal to twice RTO.
1013 * If the outgoing interface is in marginal conditions, we need to
1014 * enable read probes for that too.
1017 tcp_adaptive_rwtimo_check(struct tcpcb
*tp
, int tlen
)
1019 struct ifnet
*outifp
= tp
->t_inpcb
->inp_last_outifp
;
1021 if ((tp
->t_adaptive_rtimo
> 0 ||
1023 (outifp
->if_eflags
& IFEF_PROBE_CONNECTIVITY
)))
1025 tp
->t_state
== TCPS_ESTABLISHED
) {
1026 tp
->t_timer
[TCPT_KEEP
] = OFFSET_FROM_START(tp
,
1027 (TCP_REXMTVAL(tp
) << 1));
1028 tp
->t_flagsext
|= TF_DETECT_READSTALL
;
1029 tp
->t_rtimo_probes
= 0;
1034 tcp_keepalive_reset(struct tcpcb
*tp
)
1036 tp
->t_timer
[TCPT_KEEP
] = OFFSET_FROM_START(tp
,
1037 TCP_CONN_KEEPIDLE(tp
));
1038 tp
->t_flagsext
&= ~(TF_DETECT_READSTALL
);
1039 tp
->t_rtimo_probes
= 0;
1043 * TCP input routine, follows pages 65-76 of the
1044 * protocol specification dated September, 1981 very closely.
1048 tcp6_input(struct mbuf
**mp
, int *offp
, int proto
)
1050 #pragma unused(proto)
1051 struct mbuf
*m
= *mp
;
1053 struct ifnet
*ifp
= m
->m_pkthdr
.rcvif
;
1055 IP6_EXTHDR_CHECK(m
, *offp
, sizeof(struct tcphdr
), return IPPROTO_DONE
);
1057 /* Expect 32-bit aligned data pointer on strict-align platforms */
1058 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m
);
1061 * draft-itojun-ipv6-tcp-to-anycast
1062 * better place to put this in?
1064 if (ip6_getdstifaddr_info(m
, NULL
, &ia6_flags
) == 0) {
1065 if (ia6_flags
& IN6_IFF_ANYCAST
) {
1066 struct ip6_hdr
*ip6
;
1068 ip6
= mtod(m
, struct ip6_hdr
*);
1069 icmp6_error(m
, ICMP6_DST_UNREACH
,
1070 ICMP6_DST_UNREACH_ADDR
,
1071 (caddr_t
)&ip6
->ip6_dst
- (caddr_t
)ip6
);
1073 IF_TCP_STATINC(ifp
, icmp6unreach
);
1075 return IPPROTO_DONE
;
1079 tcp_input(m
, *offp
);
1080 return IPPROTO_DONE
;
1084 /* Depending on the usage of mbuf space in the system, this function
1085 * will return true or false. This is used to determine if a socket
1086 * buffer can take more memory from the system for auto-tuning or not.
1089 tcp_cansbgrow(struct sockbuf
*sb
)
1091 /* Calculate the host level space limit in terms of MSIZE buffers.
1092 * We can use a maximum of half of the available mbuf space for
1095 u_int32_t mblim
= ((nmbclusters
>> 1) << (MCLSHIFT
- MSIZESHIFT
));
1097 /* Calculate per sb limit in terms of bytes. We optimize this limit
1098 * for upto 16 socket buffers.
1101 u_int32_t sbspacelim
= ((nmbclusters
>> 4) << MCLSHIFT
);
1103 if ((total_sbmb_cnt
< mblim
) &&
1104 (sb
->sb_hiwat
< sbspacelim
)) {
1107 OSIncrementAtomic64(&sbmb_limreached
);
1113 tcp_sbrcv_reserve(struct tcpcb
*tp
, struct sockbuf
*sbrcv
,
1114 u_int32_t newsize
, u_int32_t idealsize
, u_int32_t rcvbuf_max
)
1116 /* newsize should not exceed max */
1117 newsize
= min(newsize
, rcvbuf_max
);
1119 /* The receive window scale negotiated at the
1120 * beginning of the connection will also set a
1121 * limit on the socket buffer size
1123 newsize
= min(newsize
, TCP_MAXWIN
<< tp
->rcv_scale
);
1125 /* Set new socket buffer size */
1126 if (newsize
> sbrcv
->sb_hiwat
&&
1127 (sbreserve(sbrcv
, newsize
) == 1)) {
1128 sbrcv
->sb_idealsize
= min(max(sbrcv
->sb_idealsize
,
1129 (idealsize
!= 0) ? idealsize
: newsize
), rcvbuf_max
);
1131 /* Again check the limit set by the advertised
1134 sbrcv
->sb_idealsize
= min(sbrcv
->sb_idealsize
,
1135 TCP_MAXWIN
<< tp
->rcv_scale
);
1140 * This function is used to grow a receive socket buffer. It
1141 * will take into account system-level memory usage and the
1142 * bandwidth available on the link to make a decision.
1145 tcp_sbrcv_grow(struct tcpcb
*tp
, struct sockbuf
*sbrcv
,
1146 struct tcpopt
*to
, u_int32_t pktlen
, u_int32_t rcvbuf_max
)
1148 struct socket
*so
= sbrcv
->sb_so
;
1151 * Do not grow the receive socket buffer if
1152 * - auto resizing is disabled, globally or on this socket
1153 * - the high water mark already reached the maximum
1154 * - the stream is in background and receive side is being
1156 * - if there are segments in reassembly queue indicating loss,
1157 * do not need to increase recv window during recovery as more
1158 * data is not going to be sent. A duplicate ack sent during
1159 * recovery should not change the receive window
1161 if (tcp_do_autorcvbuf
== 0 ||
1162 (sbrcv
->sb_flags
& SB_AUTOSIZE
) == 0 ||
1163 tcp_cansbgrow(sbrcv
) == 0 ||
1164 sbrcv
->sb_hiwat
>= rcvbuf_max
||
1165 (tp
->t_flagsext
& TF_RECV_THROTTLE
) ||
1166 (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
) ||
1167 !LIST_EMPTY(&tp
->t_segq
)) {
1168 /* Can not resize the socket buffer, just return */
1172 if (TSTMP_GT(tcp_now
,
1173 tp
->rfbuf_ts
+ TCPTV_RCVBUFIDLE
)) {
1174 /* If there has been an idle period in the
1175 * connection, just restart the measurement
1180 if (!TSTMP_SUPPORTED(tp
)) {
1182 * Timestamp option is not supported on this connection.
1183 * If the connection reached a state to indicate that
1184 * the receive socket buffer needs to grow, increase
1185 * the high water mark.
1187 if (TSTMP_GEQ(tcp_now
,
1188 tp
->rfbuf_ts
+ TCPTV_RCVNOTS_QUANTUM
)) {
1189 if (tp
->rfbuf_cnt
>= TCP_RCVNOTS_BYTELEVEL
) {
1190 tcp_sbrcv_reserve(tp
, sbrcv
,
1191 tcp_autorcvbuf_max
, 0,
1192 tcp_autorcvbuf_max
);
1196 tp
->rfbuf_cnt
+= pktlen
;
1199 } else if (to
->to_tsecr
!= 0) {
1201 * If the timestamp shows that one RTT has
1202 * completed, we can stop counting the
1203 * bytes. Here we consider increasing
1204 * the socket buffer if the bandwidth measured in
1205 * last rtt, is more than half of sb_hiwat, this will
1206 * help to scale the buffer according to the bandwidth
1209 if (TSTMP_GEQ(to
->to_tsecr
, tp
->rfbuf_ts
)) {
1210 if (tp
->rfbuf_cnt
> (sbrcv
->sb_hiwat
-
1211 (sbrcv
->sb_hiwat
>> 1))) {
1212 int32_t rcvbuf_inc
, min_incr
;
1214 * Increment the receive window by a
1215 * multiple of maximum sized segments.
1216 * This will prevent a connection from
1217 * sending smaller segments on wire if it
1218 * is limited by the receive window.
1220 * Set the ideal size based on current
1221 * bandwidth measurements. We set the
1222 * ideal size on receive socket buffer to
1223 * be twice the bandwidth delay product.
1225 rcvbuf_inc
= (tp
->rfbuf_cnt
<< 1)
1229 * Make the increment equal to 8 segments
1232 min_incr
= tp
->t_maxseg
<< tcp_autorcvbuf_inc_shift
;
1233 if (rcvbuf_inc
< min_incr
) {
1234 rcvbuf_inc
= min_incr
;
1238 (rcvbuf_inc
/ tp
->t_maxseg
) * tp
->t_maxseg
;
1239 tcp_sbrcv_reserve(tp
, sbrcv
,
1240 sbrcv
->sb_hiwat
+ rcvbuf_inc
,
1241 (tp
->rfbuf_cnt
* 2), rcvbuf_max
);
1243 /* Measure instantaneous receive bandwidth */
1244 if (tp
->t_bwmeas
!= NULL
&& tp
->rfbuf_cnt
> 0 &&
1245 TSTMP_GT(tcp_now
, tp
->rfbuf_ts
)) {
1247 rcv_bw
= tp
->rfbuf_cnt
/
1248 (int)(tcp_now
- tp
->rfbuf_ts
);
1249 if (tp
->t_bwmeas
->bw_rcvbw_max
== 0) {
1250 tp
->t_bwmeas
->bw_rcvbw_max
= rcv_bw
;
1252 tp
->t_bwmeas
->bw_rcvbw_max
= max(
1253 tp
->t_bwmeas
->bw_rcvbw_max
, rcv_bw
);
1258 tp
->rfbuf_cnt
+= pktlen
;
1263 /* Restart the measurement */
1269 /* This function will trim the excess space added to the socket buffer
1270 * to help a slow-reading app. The ideal-size of a socket buffer depends
1271 * on the link bandwidth or it is set by an application and we aim to
1275 tcp_sbrcv_trim(struct tcpcb
*tp
, struct sockbuf
*sbrcv
)
1277 if (tcp_do_autorcvbuf
== 1 && sbrcv
->sb_idealsize
> 0 &&
1278 sbrcv
->sb_hiwat
> sbrcv
->sb_idealsize
) {
1280 /* compute the difference between ideal and current sizes */
1281 u_int32_t diff
= sbrcv
->sb_hiwat
- sbrcv
->sb_idealsize
;
1283 /* Compute the maximum advertised window for
1286 u_int32_t advwin
= tp
->rcv_adv
- tp
->rcv_nxt
;
1288 /* How much can we trim the receive socket buffer?
1289 * 1. it can not be trimmed beyond the max rcv win advertised
1290 * 2. if possible, leave 1/16 of bandwidth*delay to
1291 * avoid closing the win completely
1293 u_int32_t leave
= max(advwin
, (sbrcv
->sb_idealsize
>> 4));
1295 /* Sometimes leave can be zero, in that case leave at least
1296 * a few segments worth of space.
1299 leave
= tp
->t_maxseg
<< tcp_autorcvbuf_inc_shift
;
1302 trim
= sbrcv
->sb_hiwat
- (sbrcv
->sb_cc
+ leave
);
1303 trim
= imin(trim
, (int32_t)diff
);
1306 sbreserve(sbrcv
, (sbrcv
->sb_hiwat
- trim
));
1311 /* We may need to trim the send socket buffer size for two reasons:
1312 * 1. if the rtt seen on the connection is climbing up, we do not
1313 * want to fill the buffers any more.
1314 * 2. if the congestion win on the socket backed off, there is no need
1315 * to hold more mbufs for that connection than what the cwnd will allow.
1318 tcp_sbsnd_trim(struct sockbuf
*sbsnd
)
1320 if (tcp_do_autosendbuf
== 1 &&
1321 ((sbsnd
->sb_flags
& (SB_AUTOSIZE
| SB_TRIM
)) ==
1322 (SB_AUTOSIZE
| SB_TRIM
)) &&
1323 (sbsnd
->sb_idealsize
> 0) &&
1324 (sbsnd
->sb_hiwat
> sbsnd
->sb_idealsize
)) {
1326 if (sbsnd
->sb_cc
<= sbsnd
->sb_idealsize
) {
1327 trim
= sbsnd
->sb_hiwat
- sbsnd
->sb_idealsize
;
1329 trim
= sbsnd
->sb_hiwat
- sbsnd
->sb_cc
;
1331 sbreserve(sbsnd
, (sbsnd
->sb_hiwat
- trim
));
1333 if (sbsnd
->sb_hiwat
<= sbsnd
->sb_idealsize
) {
1334 sbsnd
->sb_flags
&= ~(SB_TRIM
);
1339 * If timestamp option was not negotiated on this connection
1340 * and this connection is on the receiving side of a stream
1341 * then we can not measure the delay on the link accurately.
1342 * Instead of enabling automatic receive socket buffer
1343 * resizing, just give more space to the receive socket buffer.
1346 tcp_sbrcv_tstmp_check(struct tcpcb
*tp
)
1348 struct socket
*so
= tp
->t_inpcb
->inp_socket
;
1349 u_int32_t newsize
= 2 * tcp_recvspace
;
1350 struct sockbuf
*sbrcv
= &so
->so_rcv
;
1352 if ((tp
->t_flags
& (TF_REQ_TSTMP
| TF_RCVD_TSTMP
)) !=
1353 (TF_REQ_TSTMP
| TF_RCVD_TSTMP
) &&
1354 (sbrcv
->sb_flags
& SB_AUTOSIZE
) != 0) {
1355 tcp_sbrcv_reserve(tp
, sbrcv
, newsize
, 0, newsize
);
1359 /* A receiver will evaluate the flow of packets on a connection
1360 * to see if it can reduce ack traffic. The receiver will start
1361 * stretching acks if all of the following conditions are met:
1362 * 1. tcp_delack_enabled is set to 3
1363 * 2. If the bytes received in the last 100ms is greater than a threshold
1364 * defined by maxseg_unacked
1365 * 3. If the connection has not been idle for tcp_maxrcvidle period.
1366 * 4. If the connection has seen enough packets to let the slow-start
1367 * finish after connection establishment or after some packet loss.
1369 * The receiver will stop stretching acks if there is congestion/reordering
1370 * as indicated by packets on reassembly queue or an ECN. If the delayed-ack
1371 * timer fires while stretching acks, it means that the packet flow has gone
1372 * below the threshold defined by maxseg_unacked and the receiver will stop
1373 * stretching acks. The receiver gets no indication when slow-start is completed
1374 * or when the connection reaches an idle state. That is why we use
1375 * tcp_rcvsspktcnt to cover slow-start and tcp_maxrcvidle to identify idle
1379 tcp_stretch_ack_enable(struct tcpcb
*tp
, int thflags
)
1381 if (tp
->rcv_by_unackwin
>= (maxseg_unacked
* tp
->t_maxseg
) &&
1382 TSTMP_GEQ(tp
->rcv_unackwin
, tcp_now
)) {
1383 tp
->t_flags
|= TF_STREAMING_ON
;
1385 tp
->t_flags
&= ~TF_STREAMING_ON
;
1388 /* If there has been an idle time, reset streaming detection */
1389 if (TSTMP_GT(tcp_now
, tp
->rcv_unackwin
+ tcp_maxrcvidle
)) {
1390 tp
->t_flags
&= ~TF_STREAMING_ON
;
1394 * If there are flags other than TH_ACK set, reset streaming
1397 if (thflags
& ~TH_ACK
) {
1398 tp
->t_flags
&= ~TF_STREAMING_ON
;
1401 if (tp
->t_flagsext
& TF_DISABLE_STRETCHACK
) {
1402 if (tp
->rcv_nostrack_pkts
>= TCP_STRETCHACK_ENABLE_PKTCNT
) {
1403 tp
->t_flagsext
&= ~TF_DISABLE_STRETCHACK
;
1404 tp
->rcv_nostrack_pkts
= 0;
1405 tp
->rcv_nostrack_ts
= 0;
1407 tp
->rcv_nostrack_pkts
++;
1411 if (!(tp
->t_flagsext
& (TF_NOSTRETCHACK
| TF_DISABLE_STRETCHACK
)) &&
1412 (tp
->t_flags
& TF_STREAMING_ON
) &&
1413 (!(tp
->t_flagsext
& TF_RCVUNACK_WAITSS
) ||
1414 (tp
->rcv_waitforss
>= tcp_rcvsspktcnt
))) {
1422 * Reset the state related to stretch-ack algorithm. This will make
1423 * the receiver generate an ack every other packet. The receiver
1424 * will start re-evaluating the rate at which packets come to decide
1425 * if it can benefit by lowering the ack traffic.
1428 tcp_reset_stretch_ack(struct tcpcb
*tp
)
1430 tp
->t_flags
&= ~(TF_STRETCHACK
| TF_STREAMING_ON
);
1431 tp
->rcv_by_unackwin
= 0;
1432 tp
->rcv_unackwin
= tcp_now
+ tcp_rcvunackwin
;
1435 * When there is packet loss or packet re-ordering or CWR due to
1436 * ECN, the sender's congestion window is reduced. In these states,
1437 * generate an ack for every other packet for some time to allow
1438 * the sender's congestion window to grow.
1440 tp
->t_flagsext
|= TF_RCVUNACK_WAITSS
;
1441 tp
->rcv_waitforss
= 0;
1445 * The last packet was a retransmission, check if this ack
1446 * indicates that the retransmission was spurious.
1448 * If the connection supports timestamps, we could use it to
1449 * detect if the last retransmit was not needed. Otherwise,
1450 * we check if the ACK arrived within RTT/2 window, then it
1451 * was a mistake to do the retransmit in the first place.
1453 * This function will return 1 if it is a spurious retransmit,
1457 tcp_detect_bad_rexmt(struct tcpcb
*tp
, struct tcphdr
*th
,
1458 struct tcpopt
*to
, u_int32_t rxtime
)
1460 int32_t tdiff
, bad_rexmt_win
;
1461 bad_rexmt_win
= (tp
->t_srtt
>> (TCP_RTT_SHIFT
+ 1));
1463 /* If the ack has ECN CE bit, then cwnd has to be adjusted */
1464 if (TCP_ECN_ENABLED(tp
) && (th
->th_flags
& TH_ECE
)) {
1467 if (TSTMP_SUPPORTED(tp
)) {
1468 if (rxtime
> 0 && (to
->to_flags
& TOF_TS
)
1469 && to
->to_tsecr
!= 0
1470 && TSTMP_LT(to
->to_tsecr
, rxtime
)) {
1474 if ((tp
->t_rxtshift
== 1
1475 || (tp
->t_flagsext
& TF_SENT_TLPROBE
))
1477 tdiff
= (int32_t)(tcp_now
- rxtime
);
1478 if (tdiff
< bad_rexmt_win
) {
1488 * Restore congestion window state if a spurious timeout
1492 tcp_bad_rexmt_restore_state(struct tcpcb
*tp
, struct tcphdr
*th
)
1494 if (TSTMP_SUPPORTED(tp
)) {
1495 u_int32_t fsize
, acked
;
1496 fsize
= tp
->snd_max
- th
->th_ack
;
1497 acked
= BYTES_ACKED(th
, tp
);
1500 * Implement bad retransmit recovery as
1501 * described in RFC 4015.
1503 tp
->snd_ssthresh
= tp
->snd_ssthresh_prev
;
1505 /* Initialize cwnd to the initial window */
1506 if (CC_ALGO(tp
)->cwnd_init
!= NULL
) {
1507 CC_ALGO(tp
)->cwnd_init(tp
);
1510 tp
->snd_cwnd
= fsize
+ min(acked
, tp
->snd_cwnd
);
1512 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
1513 tp
->snd_ssthresh
= tp
->snd_ssthresh_prev
;
1514 if (tp
->t_flags
& TF_WASFRECOVERY
) {
1515 ENTER_FASTRECOVERY(tp
);
1518 /* Do not use the loss flight size in this case */
1519 tp
->t_lossflightsize
= 0;
1521 tp
->snd_cwnd
= max(tp
->snd_cwnd
, TCP_CC_CWND_INIT_BYTES
);
1522 tp
->snd_recover
= tp
->snd_recover_prev
;
1523 tp
->snd_nxt
= tp
->snd_max
;
1525 /* Fix send socket buffer to reflect the change in cwnd */
1526 tcp_bad_rexmt_fix_sndbuf(tp
);
1529 * This RTT might reflect the extra delay induced
1530 * by the network. Skip using this sample for RTO
1531 * calculation and mark the connection so we can
1532 * recompute RTT when the next eligible sample is
1535 tp
->t_flagsext
|= TF_RECOMPUTE_RTT
;
1536 tp
->t_badrexmt_time
= tcp_now
;
1541 * If the previous packet was sent in retransmission timer, and it was
1542 * not needed, then restore the congestion window to the state before that
1545 * If the last packet was sent in tail loss probe timeout, check if that
1546 * recovered the last packet. If so, that will indicate a real loss and
1547 * the congestion window needs to be lowered.
1550 tcp_bad_rexmt_check(struct tcpcb
*tp
, struct tcphdr
*th
, struct tcpopt
*to
)
1552 if (tp
->t_rxtshift
> 0 &&
1553 tcp_detect_bad_rexmt(tp
, th
, to
, tp
->t_rxtstart
)) {
1554 ++tcpstat
.tcps_sndrexmitbad
;
1555 tcp_bad_rexmt_restore_state(tp
, th
);
1556 tcp_ccdbg_trace(tp
, th
, TCP_CC_BAD_REXMT_RECOVERY
);
1557 } else if ((tp
->t_flagsext
& TF_SENT_TLPROBE
)
1558 && tp
->t_tlphighrxt
> 0
1559 && SEQ_GEQ(th
->th_ack
, tp
->t_tlphighrxt
)
1560 && !tcp_detect_bad_rexmt(tp
, th
, to
, tp
->t_tlpstart
)) {
1562 * check DSACK information also to make sure that
1563 * the TLP was indeed needed
1565 if (tcp_rxtseg_dsack_for_tlp(tp
)) {
1567 * received a DSACK to indicate that TLP was
1570 tcp_rxtseg_clean(tp
);
1575 * The tail loss probe recovered the last packet and
1576 * we need to adjust the congestion window to take
1577 * this loss into account.
1579 ++tcpstat
.tcps_tlp_recoverlastpkt
;
1580 if (!IN_FASTRECOVERY(tp
)) {
1581 tcp_reduce_congestion_window(tp
);
1582 EXIT_FASTRECOVERY(tp
);
1584 tcp_ccdbg_trace(tp
, th
, TCP_CC_TLP_RECOVER_LASTPACKET
);
1585 } else if (tcp_rxtseg_detect_bad_rexmt(tp
, th
->th_ack
)) {
1587 * All of the retransmitted segments were duplicated, this
1588 * can be an indication of bad fast retransmit.
1590 tcpstat
.tcps_dsack_badrexmt
++;
1591 tcp_bad_rexmt_restore_state(tp
, th
);
1592 tcp_ccdbg_trace(tp
, th
, TCP_CC_DSACK_BAD_REXMT
);
1593 tcp_rxtseg_clean(tp
);
1596 tp
->t_flagsext
&= ~(TF_SENT_TLPROBE
);
1597 tp
->t_tlphighrxt
= 0;
1601 * check if the latest ack was for a segment sent during PMTU
1602 * blackhole detection. If the timestamp on the ack is before
1603 * PMTU blackhole detection, then revert the size of the max
1604 * segment to previous size.
1606 if (tp
->t_rxtshift
> 0 && (tp
->t_flags
& TF_BLACKHOLE
) &&
1607 tp
->t_pmtud_start_ts
> 0 && TSTMP_SUPPORTED(tp
)) {
1608 if ((to
->to_flags
& TOF_TS
) && to
->to_tsecr
!= 0
1609 && TSTMP_LT(to
->to_tsecr
, tp
->t_pmtud_start_ts
)) {
1610 tcp_pmtud_revert_segment_size(tp
);
1613 if (tp
->t_pmtud_start_ts
> 0) {
1614 tp
->t_pmtud_start_ts
= 0;
1619 * Check if early retransmit can be attempted according to RFC 5827.
1621 * If packet reordering is detected on a connection, fast recovery will
1622 * be delayed until it is clear that the packet was lost and not reordered.
1623 * But reordering detection is done only when SACK is enabled.
1625 * On connections that do not support SACK, there is a limit on the number
1626 * of early retransmits that can be done per minute. This limit is needed
1627 * to make sure that too many packets are not retransmitted when there is
1628 * packet reordering.
1631 tcp_early_rexmt_check(struct tcpcb
*tp
, struct tcphdr
*th
)
1633 u_int32_t obytes
, snd_off
;
1635 struct socket
*so
= tp
->t_inpcb
->inp_socket
;
1637 if (early_rexmt
&& (SACK_ENABLED(tp
) ||
1638 tp
->t_early_rexmt_count
< TCP_EARLY_REXMT_LIMIT
) &&
1639 SEQ_GT(tp
->snd_max
, tp
->snd_una
) &&
1640 (tp
->t_dupacks
== 1 ||
1641 (SACK_ENABLED(tp
) &&
1642 !TAILQ_EMPTY(&tp
->snd_holes
)))) {
1644 * If there are only a few outstanding
1645 * segments on the connection, we might need
1646 * to lower the retransmit threshold. This
1647 * will allow us to do Early Retransmit as
1648 * described in RFC 5827.
1650 if (SACK_ENABLED(tp
) &&
1651 !TAILQ_EMPTY(&tp
->snd_holes
)) {
1652 obytes
= (tp
->snd_max
- tp
->snd_fack
) +
1653 tp
->sackhint
.sack_bytes_rexmit
;
1655 obytes
= (tp
->snd_max
- tp
->snd_una
);
1659 * In order to lower retransmit threshold the
1660 * following two conditions must be met.
1661 * 1. the amount of outstanding data is less
1663 * 2. there is no unsent data ready for
1664 * transmission or the advertised window
1665 * will limit sending new segments.
1667 snd_off
= tp
->snd_max
- tp
->snd_una
;
1668 snd_len
= min(so
->so_snd
.sb_cc
, tp
->snd_wnd
) - snd_off
;
1669 if (obytes
< (tp
->t_maxseg
<< 2) &&
1673 osegs
= obytes
/ tp
->t_maxseg
;
1674 if ((osegs
* tp
->t_maxseg
) < obytes
) {
1679 * Since the connection might have already
1680 * received some dupacks, we add them to
1681 * to the outstanding segments count to get
1682 * the correct retransmit threshold.
1684 * By checking for early retransmit after
1685 * receiving some duplicate acks when SACK
1686 * is supported, the connection will
1687 * enter fast recovery even if multiple
1688 * segments are lost in the same window.
1690 osegs
+= tp
->t_dupacks
;
1693 ((osegs
- 1) > 1) ? (osegs
- 1) : 1;
1695 min(tp
->t_rexmtthresh
, tcprexmtthresh
);
1697 max(tp
->t_rexmtthresh
, tp
->t_dupacks
);
1699 if (tp
->t_early_rexmt_count
== 0) {
1700 tp
->t_early_rexmt_win
= tcp_now
;
1703 if (tp
->t_flagsext
& TF_SENT_TLPROBE
) {
1704 tcpstat
.tcps_tlp_recovery
++;
1705 tcp_ccdbg_trace(tp
, th
,
1706 TCP_CC_TLP_RECOVERY
);
1708 tcpstat
.tcps_early_rexmt
++;
1709 tp
->t_early_rexmt_count
++;
1710 tcp_ccdbg_trace(tp
, th
,
1711 TCP_CC_EARLY_RETRANSMIT
);
1718 * If we ever sent a TLP probe, the acknowledgement will trigger
1719 * early retransmit because the value of snd_fack will be close
1720 * to snd_max. This will take care of adjustments to the
1721 * congestion window. So we can reset TF_SENT_PROBE flag.
1723 tp
->t_flagsext
&= ~(TF_SENT_TLPROBE
);
1724 tp
->t_tlphighrxt
= 0;
1729 tcp_tfo_syn(struct tcpcb
*tp
, struct tcpopt
*to
)
1731 u_char out
[CCAES_BLOCK_SIZE
];
1734 if (!(to
->to_flags
& (TOF_TFO
| TOF_TFOREQ
)) ||
1735 !(tcp_fastopen
& TCP_FASTOPEN_SERVER
)) {
1739 if ((to
->to_flags
& TOF_TFOREQ
)) {
1740 tp
->t_tfo_flags
|= TFO_F_OFFER_COOKIE
;
1742 tp
->t_tfo_stats
|= TFO_S_COOKIEREQ_RECV
;
1743 tcpstat
.tcps_tfo_cookie_req_rcv
++;
1747 /* Ok, then it must be an offered cookie. We need to check that ... */
1748 tcp_tfo_gen_cookie(tp
->t_inpcb
, out
, sizeof(out
));
1750 len
= *to
->to_tfo
- TCPOLEN_FASTOPEN_REQ
;
1752 if (memcmp(out
, to
->to_tfo
, len
)) {
1753 /* Cookies are different! Let's return and offer a new cookie */
1754 tp
->t_tfo_flags
|= TFO_F_OFFER_COOKIE
;
1756 tp
->t_tfo_stats
|= TFO_S_COOKIE_INVALID
;
1757 tcpstat
.tcps_tfo_cookie_invalid
++;
1761 if (OSIncrementAtomic(&tcp_tfo_halfcnt
) >= tcp_tfo_backlog
) {
1762 /* Need to decrement again as we just increased it... */
1763 OSDecrementAtomic(&tcp_tfo_halfcnt
);
1767 tp
->t_tfo_flags
|= TFO_F_COOKIE_VALID
;
1769 tp
->t_tfo_stats
|= TFO_S_SYNDATA_RCV
;
1770 tcpstat
.tcps_tfo_syn_data_rcv
++;
1776 tcp_tfo_synack(struct tcpcb
*tp
, struct tcpopt
*to
)
1778 if (to
->to_flags
& TOF_TFO
) {
1779 unsigned char len
= *to
->to_tfo
- TCPOLEN_FASTOPEN_REQ
;
1782 * If this happens, things have gone terribly wrong. len should
1783 * have been checked in tcp_dooptions.
1785 VERIFY(len
<= TFO_COOKIE_LEN_MAX
);
1789 tcp_cache_set_cookie(tp
, to
->to_tfo
, len
);
1790 tcp_heuristic_tfo_success(tp
);
1792 tp
->t_tfo_stats
|= TFO_S_COOKIE_RCV
;
1793 tcpstat
.tcps_tfo_cookie_rcv
++;
1794 if (tp
->t_tfo_flags
& TFO_F_COOKIE_SENT
) {
1795 tcpstat
.tcps_tfo_cookie_wrong
++;
1796 tp
->t_tfo_stats
|= TFO_S_COOKIE_WRONG
;
1800 * Thus, no cookie in the response, but we either asked for one
1801 * or sent SYN+DATA. Now, we need to check whether we had to
1802 * rexmit the SYN. If that's the case, it's better to start
1803 * backing of TFO-cookie requests.
1805 if (tp
->t_tfo_flags
& TFO_F_SYN_LOSS
) {
1806 tp
->t_tfo_stats
|= TFO_S_SYN_LOSS
;
1807 tcpstat
.tcps_tfo_syn_loss
++;
1809 tcp_heuristic_tfo_loss(tp
);
1811 if (tp
->t_tfo_flags
& TFO_F_COOKIE_REQ
) {
1812 tp
->t_tfo_stats
|= TFO_S_NO_COOKIE_RCV
;
1813 tcpstat
.tcps_tfo_no_cookie_rcv
++;
1816 tcp_heuristic_tfo_success(tp
);
1822 tcp_tfo_rcv_probe(struct tcpcb
*tp
, int tlen
)
1828 tp
->t_tfo_probe_state
= TFO_PROBE_PROBING
;
1831 * We send the probe out rather quickly (after one RTO). It does not
1832 * really hurt that much, it's only one additional segment on the wire.
1834 tp
->t_timer
[TCPT_KEEP
] = OFFSET_FROM_START(tp
, (TCP_REXMTVAL(tp
)));
1838 tcp_tfo_rcv_data(struct tcpcb
*tp
)
1840 /* Transition from PROBING to NONE as data has been received */
1841 if (tp
->t_tfo_probe_state
>= TFO_PROBE_PROBING
) {
1842 tp
->t_tfo_probe_state
= TFO_PROBE_NONE
;
1847 tcp_tfo_rcv_ack(struct tcpcb
*tp
, struct tcphdr
*th
)
1849 if (tp
->t_tfo_probe_state
== TFO_PROBE_PROBING
&&
1850 tp
->t_tfo_probes
> 0) {
1851 if (th
->th_seq
== tp
->rcv_nxt
) {
1852 /* No hole, so stop probing */
1853 tp
->t_tfo_probe_state
= TFO_PROBE_NONE
;
1854 } else if (SEQ_GT(th
->th_seq
, tp
->rcv_nxt
)) {
1855 /* There is a hole! Wait a bit for data... */
1856 tp
->t_tfo_probe_state
= TFO_PROBE_WAIT_DATA
;
1857 tp
->t_timer
[TCPT_KEEP
] = OFFSET_FROM_START(tp
,
1864 * Update snd_wnd information.
1867 tcp_update_window(struct tcpcb
*tp
, int thflags
, struct tcphdr
* th
,
1868 u_int32_t tiwin
, int tlen
)
1870 /* Don't look at the window if there is no ACK flag */
1871 if ((thflags
& TH_ACK
) &&
1872 (SEQ_LT(tp
->snd_wl1
, th
->th_seq
) ||
1873 (tp
->snd_wl1
== th
->th_seq
&& (SEQ_LT(tp
->snd_wl2
, th
->th_ack
) ||
1874 (tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
))))) {
1875 /* keep track of pure window updates */
1877 tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
) {
1878 tcpstat
.tcps_rcvwinupd
++;
1880 tp
->snd_wnd
= tiwin
;
1881 tp
->snd_wl1
= th
->th_seq
;
1882 tp
->snd_wl2
= th
->th_ack
;
1883 if (tp
->snd_wnd
> tp
->max_sndwnd
) {
1884 tp
->max_sndwnd
= tp
->snd_wnd
;
1887 if (tp
->t_inpcb
->inp_socket
->so_flags
& SOF_MP_SUBFLOW
) {
1888 mptcp_update_window_wakeup(tp
);
1896 tcp_input(struct mbuf
*m
, int off0
)
1899 struct ip
*ip
= NULL
;
1901 u_char
*optp
= NULL
;
1905 struct tcpcb
*tp
= 0;
1907 struct socket
*so
= 0;
1908 int todrop
, acked
, ourfinisacked
, needoutput
= 0;
1909 struct in_addr laddr
;
1911 struct in6_addr laddr6
;
1914 int iss
= 0, nosock
= 0;
1915 u_int32_t tiwin
, sack_bytes_acked
= 0;
1916 struct tcpopt to
; /* options in this segment */
1921 struct sockaddr_in
*next_hop
= NULL
;
1922 struct m_tag
*fwd_tag
;
1923 #endif /* IPFIREWALL */
1924 u_char ip_ecn
= IPTOS_ECN_NOTECT
;
1925 unsigned int ifscope
;
1926 uint8_t isconnected
, isdisconnected
;
1927 struct ifnet
*ifp
= m
->m_pkthdr
.rcvif
;
1928 int pktf_sw_lro_pkt
= (m
->m_pkthdr
.pkt_flags
& PKTF_SW_LRO_PKT
) ? 1 : 0;
1929 int nlropkts
= (pktf_sw_lro_pkt
== 1) ? m
->m_pkthdr
.lro_npkts
: 1;
1930 int turnoff_lro
= 0, win
;
1932 struct mptcb
*mp_tp
= NULL
;
1934 boolean_t cell
= IFNET_IS_CELLULAR(ifp
);
1935 boolean_t wifi
= (!cell
&& IFNET_IS_WIFI(ifp
));
1936 boolean_t wired
= (!wifi
&& IFNET_IS_WIRED(ifp
));
1937 boolean_t recvd_dsack
= FALSE
;
1938 struct tcp_respond_args tra
;
1939 bool findpcb_iterated
= false;
1941 #define TCP_INC_VAR(stat, npkts) do { \
1945 TCP_INC_VAR(tcpstat
.tcps_rcvtotal
, nlropkts
);
1947 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
1948 if (!SLIST_EMPTY(&m
->m_pkthdr
.tags
)) {
1949 fwd_tag
= m_tag_locate(m
, KERNEL_MODULE_TAG_ID
,
1950 KERNEL_TAG_TYPE_IPFORWARD
, NULL
);
1954 if (fwd_tag
!= NULL
) {
1955 struct ip_fwd_tag
*ipfwd_tag
=
1956 (struct ip_fwd_tag
*)(fwd_tag
+ 1);
1958 next_hop
= ipfwd_tag
->next_hop
;
1959 m_tag_delete(m
, fwd_tag
);
1961 #endif /* IPFIREWALL */
1964 struct ip6_hdr
*ip6
= NULL
;
1967 int rstreason
; /* For badport_bandlim accounting purposes */
1968 struct proc
*proc0
= current_proc();
1970 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_START
, 0, 0, 0, 0, 0);
1973 isipv6
= (mtod(m
, struct ip
*)->ip_v
== 6) ? 1 : 0;
1975 bzero((char *)&to
, sizeof(to
));
1980 * Expect 32-bit aligned data pointer on
1981 * strict-align platforms
1983 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m
);
1985 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
1986 ip6
= mtod(m
, struct ip6_hdr
*);
1987 tlen
= sizeof(*ip6
) + ntohs(ip6
->ip6_plen
) - off0
;
1988 th
= (struct tcphdr
*)(void *)((caddr_t
)ip6
+ off0
);
1990 if (tcp_input_checksum(AF_INET6
, m
, th
, off0
, tlen
)) {
1994 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
1995 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
1996 th
->th_seq
, th
->th_ack
, th
->th_win
);
1998 * Be proactive about unspecified IPv6 address in source.
1999 * As we use all-zero to indicate unbounded/unconnected pcb,
2000 * unspecified IPv6 address can be used to confuse us.
2002 * Note that packets with unspecified IPv6 destination is
2003 * already dropped in ip6_input.
2005 if (IN6_IS_ADDR_UNSPECIFIED(&ip6
->ip6_src
)) {
2007 IF_TCP_STATINC(ifp
, unspecv6
);
2010 DTRACE_TCP5(receive
, struct mbuf
*, m
, struct inpcb
*, NULL
,
2011 struct ip6_hdr
*, ip6
, struct tcpcb
*, NULL
,
2012 struct tcphdr
*, th
);
2014 ip_ecn
= (ntohl(ip6
->ip6_flow
) >> 20) & IPTOS_ECN_MASK
;
2019 * Get IP and TCP header together in first mbuf.
2020 * Note: IP leaves IP header in first mbuf.
2022 if (off0
> sizeof(struct ip
)) {
2024 off0
= sizeof(struct ip
);
2026 if (m
->m_len
< sizeof(struct tcpiphdr
)) {
2027 if ((m
= m_pullup(m
, sizeof(struct tcpiphdr
))) == 0) {
2028 tcpstat
.tcps_rcvshort
++;
2033 /* Expect 32-bit aligned data pointer on strict-align platforms */
2034 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m
);
2036 ip
= mtod(m
, struct ip
*);
2037 th
= (struct tcphdr
*)(void *)((caddr_t
)ip
+ off0
);
2040 if (tcp_input_checksum(AF_INET
, m
, th
, off0
, tlen
)) {
2045 /* Re-initialization for later version check */
2046 ip
->ip_v
= IPVERSION
;
2048 ip_ecn
= (ip
->ip_tos
& IPTOS_ECN_MASK
);
2050 DTRACE_TCP5(receive
, struct mbuf
*, m
, struct inpcb
*, NULL
,
2051 struct ip
*, ip
, struct tcpcb
*, NULL
, struct tcphdr
*, th
);
2053 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
2054 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
2055 th
->th_seq
, th
->th_ack
, th
->th_win
);
2059 * Check that TCP offset makes sense,
2060 * pull out TCP options and adjust length.
2062 off
= th
->th_off
<< 2;
2063 if (off
< sizeof(struct tcphdr
) || off
> tlen
) {
2064 tcpstat
.tcps_rcvbadoff
++;
2065 IF_TCP_STATINC(ifp
, badformat
);
2068 tlen
-= off
; /* tlen is used instead of ti->ti_len */
2069 if (off
> sizeof(struct tcphdr
)) {
2072 IP6_EXTHDR_CHECK(m
, off0
, off
, return );
2073 ip6
= mtod(m
, struct ip6_hdr
*);
2074 th
= (struct tcphdr
*)(void *)((caddr_t
)ip6
+ off0
);
2078 if (m
->m_len
< sizeof(struct ip
) + off
) {
2079 if ((m
= m_pullup(m
, sizeof(struct ip
) + off
)) == 0) {
2080 tcpstat
.tcps_rcvshort
++;
2083 ip
= mtod(m
, struct ip
*);
2084 th
= (struct tcphdr
*)(void *)((caddr_t
)ip
+ off0
);
2087 optlen
= off
- sizeof(struct tcphdr
);
2088 optp
= (u_char
*)(th
+ 1);
2090 * Do quick retrieval of timestamp options ("options
2091 * prediction?"). If timestamp is the only option and it's
2092 * formatted as recommended in RFC 1323 appendix A, we
2093 * quickly get the values now and not bother calling
2094 * tcp_dooptions(), etc.
2096 if ((optlen
== TCPOLEN_TSTAMP_APPA
||
2097 (optlen
> TCPOLEN_TSTAMP_APPA
&&
2098 optp
[TCPOLEN_TSTAMP_APPA
] == TCPOPT_EOL
)) &&
2099 *(u_int32_t
*)(void *)optp
== htonl(TCPOPT_TSTAMP_HDR
) &&
2100 (th
->th_flags
& TH_SYN
) == 0) {
2101 to
.to_flags
|= TOF_TS
;
2102 to
.to_tsval
= ntohl(*(u_int32_t
*)(void *)(optp
+ 4));
2103 to
.to_tsecr
= ntohl(*(u_int32_t
*)(void *)(optp
+ 8));
2104 optp
= NULL
; /* we've parsed the options */
2107 thflags
= th
->th_flags
;
2111 * If the drop_synfin option is enabled, drop all packets with
2112 * both the SYN and FIN bits set. This prevents e.g. nmap from
2113 * identifying the TCP/IP stack.
2115 * This is a violation of the TCP specification.
2117 if (drop_synfin
&& (thflags
& (TH_SYN
| TH_FIN
)) == (TH_SYN
| TH_FIN
)) {
2118 IF_TCP_STATINC(ifp
, synfin
);
2124 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
2125 * until after ip6_savecontrol() is called and before other functions
2126 * which don't want those proto headers.
2127 * Because ip6_savecontrol() is going to parse the mbuf to
2128 * search for data to be passed up to user-land, it wants mbuf
2129 * parameters to be unchanged.
2131 drop_hdrlen
= off0
+ off
;
2133 /* Since this is an entry point for input processing of tcp packets, we
2134 * can update the tcp clock here.
2136 calculate_tcp_clock();
2139 * Record the interface where this segment arrived on; this does not
2140 * affect normal data output (for non-detached TCP) as it provides a
2141 * hint about which route and interface to use for sending in the
2142 * absence of a PCB, when scoped routing (and thus source interface
2143 * selection) are enabled.
2145 if ((m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
) || m
->m_pkthdr
.rcvif
== NULL
) {
2146 ifscope
= IFSCOPE_NONE
;
2148 ifscope
= m
->m_pkthdr
.rcvif
->if_index
;
2152 * Convert TCP protocol specific fields to host format.
2155 #if BYTE_ORDER != BIG_ENDIAN
2163 * Locate pcb for segment.
2167 isconnected
= FALSE
;
2168 isdisconnected
= FALSE
;
2170 #if IPFIREWALL_FORWARD
2171 if (next_hop
!= NULL
2173 && isipv6
== 0 /* IPv6 support is not yet */
2177 * Diverted. Pretend to be the destination.
2178 * already got one like this?
2180 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
2181 ip
->ip_dst
, th
->th_dport
, 0, m
->m_pkthdr
.rcvif
);
2184 * No, then it's new. Try find the ambushing socket
2186 if (!next_hop
->sin_port
) {
2187 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
,
2188 th
->th_sport
, next_hop
->sin_addr
,
2189 th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
2191 inp
= in_pcblookup_hash(&tcbinfo
,
2192 ip
->ip_src
, th
->th_sport
,
2194 ntohs(next_hop
->sin_port
), 1,
2199 #endif /* IPFIREWALL_FORWARD */
2203 inp
= in6_pcblookup_hash(&tcbinfo
, &ip6
->ip6_src
, th
->th_sport
,
2204 &ip6
->ip6_dst
, th
->th_dport
, 1,
2208 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
2209 ip
->ip_dst
, th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
2213 * Use the interface scope information from the PCB for outbound
2214 * segments. If the PCB isn't present and if scoped routing is
2215 * enabled, tcp_respond will use the scope of the interface where
2216 * the segment arrived on.
2218 if (inp
!= NULL
&& (inp
->inp_flags
& INP_BOUND_IF
)) {
2219 ifscope
= inp
->inp_boundifp
->if_index
;
2223 * If the state is CLOSED (i.e., TCB does not exist) then
2224 * all data in the incoming segment is discarded.
2225 * If the TCB exists but is in CLOSED state, it is embryonic,
2226 * but should either do a listen or a connect soon.
2231 char dbuf
[MAX_IPv6_STR_LEN
], sbuf
[MAX_IPv6_STR_LEN
];
2233 char dbuf
[MAX_IPv4_STR_LEN
], sbuf
[MAX_IPv4_STR_LEN
];
2238 inet_ntop(AF_INET6
, &ip6
->ip6_dst
, dbuf
, sizeof(dbuf
));
2239 inet_ntop(AF_INET6
, &ip6
->ip6_src
, sbuf
, sizeof(sbuf
));
2243 inet_ntop(AF_INET
, &ip
->ip_dst
, dbuf
, sizeof(dbuf
));
2244 inet_ntop(AF_INET
, &ip
->ip_src
, sbuf
, sizeof(sbuf
));
2246 switch (log_in_vain
) {
2248 if (thflags
& TH_SYN
) {
2250 "Connection attempt to TCP %s:%d from %s:%d\n",
2251 dbuf
, ntohs(th
->th_dport
),
2253 ntohs(th
->th_sport
));
2258 "Connection attempt to TCP %s:%d from %s:%d flags:0x%x\n",
2259 dbuf
, ntohs(th
->th_dport
), sbuf
,
2260 ntohs(th
->th_sport
), thflags
);
2264 if ((thflags
& TH_SYN
) && !(thflags
& TH_ACK
) &&
2265 !(m
->m_flags
& (M_BCAST
| M_MCAST
)) &&
2267 ((isipv6
&& !IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
, &ip6
->ip6_src
)) ||
2268 (!isipv6
&& ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
))
2270 ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
2273 log_in_vain_log((LOG_INFO
,
2274 "Stealth Mode connection attempt to TCP %s:%d from %s:%d\n",
2275 dbuf
, ntohs(th
->th_dport
),
2277 ntohs(th
->th_sport
)));
2285 if (m
->m_pkthdr
.rcvif
&& m
->m_pkthdr
.rcvif
->if_type
!= IFT_LOOP
) {
2286 switch (blackhole
) {
2288 if (thflags
& TH_SYN
) {
2299 rstreason
= BANDLIM_RST_CLOSEDPORT
;
2300 IF_TCP_STATINC(ifp
, noconnnolist
);
2301 goto dropwithresetnosock
;
2303 so
= inp
->inp_socket
;
2305 /* This case shouldn't happen as the socket shouldn't be null
2306 * if inp_state isn't set to INPCB_STATE_DEAD
2307 * But just in case, we pretend we didn't find the socket if we hit this case
2308 * as this isn't cause for a panic (the socket might be leaked however)...
2312 printf("tcp_input: no more socket for inp=%x. This shouldn't happen\n", inp
);
2318 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
2319 socket_unlock(so
, 1);
2320 inp
= NULL
; // pretend we didn't find it
2324 if (!isipv6
&& inp
->inp_faddr
.s_addr
!= INADDR_ANY
) {
2325 if (inp
->inp_faddr
.s_addr
!= ip
->ip_src
.s_addr
||
2326 inp
->inp_laddr
.s_addr
!= ip
->ip_dst
.s_addr
||
2327 inp
->inp_fport
!= th
->th_sport
||
2328 inp
->inp_lport
!= th
->th_dport
) {
2329 os_log_error(OS_LOG_DEFAULT
, "%s 5-tuple does not match: %u:%u %u:%u\n",
2331 ntohs(inp
->inp_fport
), ntohs(th
->th_sport
),
2332 ntohs(inp
->inp_lport
), ntohs(th
->th_dport
));
2333 if (findpcb_iterated
) {
2336 findpcb_iterated
= true;
2337 socket_unlock(so
, 1);
2341 } else if (isipv6
&& !IN6_IS_ADDR_UNSPECIFIED(&inp
->in6p_faddr
)) {
2342 if (!IN6_ARE_ADDR_EQUAL(&inp
->in6p_faddr
, &ip6
->ip6_src
) ||
2343 !IN6_ARE_ADDR_EQUAL(&inp
->in6p_laddr
, &ip6
->ip6_dst
) ||
2344 inp
->inp_fport
!= th
->th_sport
||
2345 inp
->inp_lport
!= th
->th_dport
) {
2346 os_log_error(OS_LOG_DEFAULT
, "%s 5-tuple does not match: %u:%u %u:%u\n",
2348 ntohs(inp
->inp_fport
), ntohs(th
->th_sport
),
2349 ntohs(inp
->inp_lport
), ntohs(th
->th_dport
));
2350 if (findpcb_iterated
) {
2353 findpcb_iterated
= true;
2354 socket_unlock(so
, 1);
2361 if (so
->so_state
& SS_ISCONNECTED
) {
2362 // Connected TCP sockets have a fully-bound local and remote,
2363 // so the policy check doesn't need to override addresses
2364 if (!necp_socket_is_allowed_to_send_recv(inp
, NULL
, NULL
, NULL
)) {
2365 IF_TCP_STATINC(ifp
, badformat
);
2371 if (!necp_socket_is_allowed_to_send_recv_v6(inp
,
2372 th
->th_dport
, th
->th_sport
, &ip6
->ip6_dst
,
2373 &ip6
->ip6_src
, ifp
, NULL
, NULL
, NULL
)) {
2374 IF_TCP_STATINC(ifp
, badformat
);
2380 if (!necp_socket_is_allowed_to_send_recv_v4(inp
,
2381 th
->th_dport
, th
->th_sport
, &ip
->ip_dst
, &ip
->ip_src
,
2382 ifp
, NULL
, NULL
, NULL
)) {
2383 IF_TCP_STATINC(ifp
, badformat
);
2390 tp
= intotcpcb(inp
);
2392 rstreason
= BANDLIM_RST_CLOSEDPORT
;
2393 IF_TCP_STATINC(ifp
, noconnlist
);
2396 if (tp
->t_state
== TCPS_CLOSED
) {
2400 /* If none of the FIN|SYN|RST|ACK flag is set, drop */
2401 if (tcp_do_rfc5961
&& (thflags
& TH_ACCEPT
) == 0) {
2405 /* Unscale the window into a 32-bit value. */
2406 if ((thflags
& TH_SYN
) == 0) {
2407 tiwin
= th
->th_win
<< tp
->snd_scale
;
2413 if (mac_inpcb_check_deliver(inp
, m
, AF_INET
, SOCK_STREAM
)) {
2418 /* Avoid processing packets while closing a listen socket */
2419 if (tp
->t_state
== TCPS_LISTEN
&&
2420 (so
->so_options
& SO_ACCEPTCONN
) == 0) {
2424 if (so
->so_options
& (SO_DEBUG
| SO_ACCEPTCONN
)) {
2426 if (so
->so_options
& SO_DEBUG
) {
2427 ostate
= tp
->t_state
;
2430 bcopy((char *)ip6
, (char *)tcp_saveipgen
,
2434 bcopy((char *)ip
, (char *)tcp_saveipgen
, sizeof(*ip
));
2438 if (so
->so_options
& SO_ACCEPTCONN
) {
2439 struct tcpcb
*tp0
= tp
;
2442 struct sockaddr_storage from
;
2444 struct inpcb
*oinp
= sotoinpcb(so
);
2446 struct ifnet
*head_ifscope
;
2447 unsigned int head_nocell
, head_recvanyif
,
2448 head_noexpensive
, head_awdl_unrestricted
,
2449 head_intcoproc_allowed
;
2451 /* Get listener's bound-to-interface, if any */
2452 head_ifscope
= (inp
->inp_flags
& INP_BOUND_IF
) ?
2453 inp
->inp_boundifp
: NULL
;
2454 /* Get listener's no-cellular information, if any */
2455 head_nocell
= INP_NO_CELLULAR(inp
);
2456 /* Get listener's recv-any-interface, if any */
2457 head_recvanyif
= (inp
->inp_flags
& INP_RECV_ANYIF
);
2458 /* Get listener's no-expensive information, if any */
2459 head_noexpensive
= INP_NO_EXPENSIVE(inp
);
2460 head_awdl_unrestricted
= INP_AWDL_UNRESTRICTED(inp
);
2461 head_intcoproc_allowed
= INP_INTCOPROC_ALLOWED(inp
);
2464 * If the state is LISTEN then ignore segment if it contains an RST.
2465 * If the segment contains an ACK then it is bad and send a RST.
2466 * If it does not contain a SYN then it is not interesting; drop it.
2467 * If it is from this socket, drop it, it must be forged.
2469 if ((thflags
& (TH_RST
| TH_ACK
| TH_SYN
)) != TH_SYN
) {
2470 IF_TCP_STATINC(ifp
, listbadsyn
);
2472 if (thflags
& TH_RST
) {
2475 if (thflags
& TH_ACK
) {
2477 tcpstat
.tcps_badsyn
++;
2478 rstreason
= BANDLIM_RST_OPENPORT
;
2482 /* We come here if there is no SYN set */
2483 tcpstat
.tcps_badsyn
++;
2486 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_START
, 0, 0, 0, 0, 0);
2487 if (th
->th_dport
== th
->th_sport
) {
2490 if (IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
,
2496 if (ip
->ip_dst
.s_addr
== ip
->ip_src
.s_addr
) {
2501 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
2502 * in_broadcast() should never return true on a received
2503 * packet with M_BCAST not set.
2505 * Packets with a multicast source address should also
2508 if (m
->m_flags
& (M_BCAST
| M_MCAST
)) {
2513 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
2514 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
)) {
2519 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
2520 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
2521 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
2522 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
)) {
2529 * If deprecated address is forbidden,
2530 * we do not accept SYN to deprecated interface
2531 * address to prevent any new inbound connection from
2532 * getting established.
2533 * When we do not accept SYN, we send a TCP RST,
2534 * with deprecated source address (instead of dropping
2535 * it). We compromise it as it is much better for peer
2536 * to send a RST, and RST will be the final packet
2539 * If we do not forbid deprecated addresses, we accept
2540 * the SYN packet. RFC 4862 forbids dropping SYN in
2543 if (isipv6
&& !ip6_use_deprecated
) {
2546 if (ip6_getdstifaddr_info(m
, NULL
,
2548 if (ia6_flags
& IN6_IFF_DEPRECATED
) {
2550 rstreason
= BANDLIM_RST_OPENPORT
;
2551 IF_TCP_STATINC(ifp
, deprecate6
);
2560 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&from
;
2562 sin6
->sin6_len
= sizeof(*sin6
);
2563 sin6
->sin6_family
= AF_INET6
;
2564 sin6
->sin6_port
= th
->th_sport
;
2565 sin6
->sin6_flowinfo
= 0;
2566 sin6
->sin6_addr
= ip6
->ip6_src
;
2567 sin6
->sin6_scope_id
= 0;
2571 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&from
;
2573 sin
->sin_len
= sizeof(*sin
);
2574 sin
->sin_family
= AF_INET
;
2575 sin
->sin_port
= th
->th_sport
;
2576 sin
->sin_addr
= ip
->ip_src
;
2578 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
2580 so2
= sonewconn(so
, 0, NULL
);
2583 tcpstat
.tcps_listendrop
++;
2584 if (tcp_dropdropablreq(so
)) {
2586 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
2588 so2
= sonewconn(so
, 0, NULL
);
2596 /* Point "inp" and "tp" in tandem to new socket */
2597 inp
= (struct inpcb
*)so2
->so_pcb
;
2598 tp
= intotcpcb(inp
);
2601 socket_unlock(so
, 0); /* Unlock but keep a reference on listener for now */
2606 * Mark socket as temporary until we're
2607 * committed to keeping it. The code at
2608 * ``drop'' and ``dropwithreset'' check the
2609 * flag dropsocket to see if the temporary
2610 * socket created here should be discarded.
2611 * We mark the socket as discardable until
2612 * we're committed to it below in TCPS_LISTEN.
2613 * There are some error conditions in which we
2614 * have to drop the temporary socket.
2618 * Inherit INP_BOUND_IF from listener; testing if
2619 * head_ifscope is non-NULL is sufficient, since it
2620 * can only be set to a non-zero value earlier if
2621 * the listener has such a flag set.
2623 if (head_ifscope
!= NULL
) {
2624 inp
->inp_flags
|= INP_BOUND_IF
;
2625 inp
->inp_boundifp
= head_ifscope
;
2627 inp
->inp_flags
&= ~INP_BOUND_IF
;
2630 * Inherit restrictions from listener.
2633 inp_set_nocellular(inp
);
2635 if (head_noexpensive
) {
2636 inp_set_noexpensive(inp
);
2638 if (head_awdl_unrestricted
) {
2639 inp_set_awdl_unrestricted(inp
);
2641 if (head_intcoproc_allowed
) {
2642 inp_set_intcoproc_allowed(inp
);
2645 * Inherit {IN,IN6}_RECV_ANYIF from listener.
2647 if (head_recvanyif
) {
2648 inp
->inp_flags
|= INP_RECV_ANYIF
;
2650 inp
->inp_flags
&= ~INP_RECV_ANYIF
;
2654 inp
->in6p_laddr
= ip6
->ip6_dst
;
2656 inp
->inp_vflag
&= ~INP_IPV6
;
2657 inp
->inp_vflag
|= INP_IPV4
;
2659 inp
->inp_laddr
= ip
->ip_dst
;
2663 inp
->inp_lport
= th
->th_dport
;
2664 if (in_pcbinshash(inp
, 0) != 0) {
2666 * Undo the assignments above if we failed to
2667 * put the PCB on the hash lists.
2671 inp
->in6p_laddr
= in6addr_any
;
2674 inp
->inp_laddr
.s_addr
= INADDR_ANY
;
2676 socket_lock(oso
, 0); /* release ref on parent */
2677 socket_unlock(oso
, 1);
2683 * Inherit socket options from the listening
2685 * Note that in6p_inputopts are not (even
2686 * should not be) copied, since it stores
2687 * previously received options and is used to
2688 * detect if each new option is different than
2689 * the previous one and hence should be passed
2691 * If we copied in6p_inputopts, a user would
2692 * not be able to receive options just after
2693 * calling the accept system call.
2696 oinp
->inp_flags
& INP_CONTROLOPTS
;
2697 if (oinp
->in6p_outputopts
) {
2698 inp
->in6p_outputopts
=
2699 ip6_copypktopts(oinp
->in6p_outputopts
,
2705 inp
->inp_options
= ip_srcroute();
2706 inp
->inp_ip_tos
= oinp
->inp_ip_tos
;
2708 socket_lock(oso
, 0);
2710 /* copy old policy into new socket's */
2711 if (sotoinpcb(oso
)->inp_sp
) {
2713 /* Is it a security hole here to silently fail to copy the policy? */
2714 if (inp
->inp_sp
!= NULL
) {
2715 error
= ipsec_init_policy(so
, &inp
->inp_sp
);
2717 if (error
!= 0 || ipsec_copy_policy(sotoinpcb(oso
)->inp_sp
, inp
->inp_sp
)) {
2718 printf("tcp_input: could not copy policy\n");
2722 /* inherit states from the listener */
2723 DTRACE_TCP4(state__change
, void, NULL
, struct inpcb
*, inp
,
2724 struct tcpcb
*, tp
, int32_t, TCPS_LISTEN
);
2725 tp
->t_state
= TCPS_LISTEN
;
2726 tp
->t_flags
|= tp0
->t_flags
& (TF_NOPUSH
| TF_NOOPT
| TF_NODELAY
);
2727 tp
->t_flagsext
|= (tp0
->t_flagsext
& (TF_RXTFINDROP
| TF_NOTIMEWAIT
| TF_FASTOPEN
));
2728 tp
->t_keepinit
= tp0
->t_keepinit
;
2729 tp
->t_keepcnt
= tp0
->t_keepcnt
;
2730 tp
->t_keepintvl
= tp0
->t_keepintvl
;
2731 tp
->t_adaptive_wtimo
= tp0
->t_adaptive_wtimo
;
2732 tp
->t_adaptive_rtimo
= tp0
->t_adaptive_rtimo
;
2733 tp
->t_inpcb
->inp_ip_ttl
= tp0
->t_inpcb
->inp_ip_ttl
;
2734 if ((so
->so_flags
& SOF_NOTSENT_LOWAT
) != 0) {
2735 tp
->t_notsent_lowat
= tp0
->t_notsent_lowat
;
2737 tp
->t_inpcb
->inp_flags2
|=
2738 tp0
->t_inpcb
->inp_flags2
& INP2_KEEPALIVE_OFFLOAD
;
2740 /* now drop the reference on the listener */
2741 socket_unlock(oso
, 1);
2743 tcp_set_max_rwinscale(tp
, so
, ifp
);
2745 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_END
, 0, 0, 0, 0, 0);
2748 socket_lock_assert_owned(so
);
2750 if (tp
->t_state
== TCPS_ESTABLISHED
&& tlen
> 0) {
2752 * Evaluate the rate of arrival of packets to see if the
2753 * receiver can reduce the ack traffic. The algorithm to
2754 * stretch acks will be enabled if the connection meets
2755 * certain criteria defined in tcp_stretch_ack_enable function.
2757 if ((tp
->t_flagsext
& TF_RCVUNACK_WAITSS
) != 0) {
2758 TCP_INC_VAR(tp
->rcv_waitforss
, nlropkts
);
2760 if (tcp_stretch_ack_enable(tp
, thflags
)) {
2761 tp
->t_flags
|= TF_STRETCHACK
;
2762 tp
->t_flagsext
&= ~(TF_RCVUNACK_WAITSS
);
2763 tp
->rcv_waitforss
= 0;
2765 tp
->t_flags
&= ~(TF_STRETCHACK
);
2767 if (TSTMP_GT(tp
->rcv_unackwin
, tcp_now
)) {
2768 tp
->rcv_by_unackwin
+= (tlen
+ off
);
2770 tp
->rcv_unackwin
= tcp_now
+ tcp_rcvunackwin
;
2771 tp
->rcv_by_unackwin
= tlen
+ off
;
2776 * Keep track of how many bytes were received in the LRO packet
2778 if ((pktf_sw_lro_pkt
) && (nlropkts
> 2)) {
2779 tp
->t_lropktlen
+= tlen
;
2782 * Explicit Congestion Notification - Flag that we need to send ECT if
2783 * + The IP Congestion experienced flag was set.
2784 * + Socket is in established state
2785 * + We negotiated ECN in the TCP setup
2786 * + This isn't a pure ack (tlen > 0)
2787 * + The data is in the valid window
2789 * TE_SENDECE will be cleared when we receive a packet with TH_CWR set.
2791 if (ip_ecn
== IPTOS_ECN_CE
&& tp
->t_state
== TCPS_ESTABLISHED
&&
2792 TCP_ECN_ENABLED(tp
) && tlen
> 0 &&
2793 SEQ_GEQ(th
->th_seq
, tp
->last_ack_sent
) &&
2794 SEQ_LT(th
->th_seq
, tp
->last_ack_sent
+ tp
->rcv_wnd
)) {
2795 tp
->t_ecn_recv_ce
++;
2796 tcpstat
.tcps_ecn_recv_ce
++;
2797 INP_INC_IFNET_STAT(inp
, ecn_recv_ce
);
2798 /* Mark this connection as it received CE from network */
2799 tp
->ecn_flags
|= TE_RECV_ECN_CE
;
2800 tp
->ecn_flags
|= TE_SENDECE
;
2804 * Clear TE_SENDECE if TH_CWR is set. This is harmless, so we don't
2805 * bother doing extensive checks for state and whatnot.
2807 if (thflags
& TH_CWR
) {
2808 tp
->ecn_flags
&= ~TE_SENDECE
;
2809 tp
->t_ecn_recv_cwr
++;
2813 * If we received an explicit notification of congestion in
2814 * ip tos ecn bits or by the CWR bit in TCP header flags, reset
2815 * the ack-strteching state. We need to handle ECN notification if
2816 * an ECN setup SYN was sent even once.
2818 if (tp
->t_state
== TCPS_ESTABLISHED
2819 && (tp
->ecn_flags
& TE_SETUPSENT
)
2820 && (ip_ecn
== IPTOS_ECN_CE
|| (thflags
& TH_CWR
))) {
2821 tcp_reset_stretch_ack(tp
);
2822 CLEAR_IAJ_STATE(tp
);
2825 if (ip_ecn
== IPTOS_ECN_CE
&& tp
->t_state
== TCPS_ESTABLISHED
&&
2826 !TCP_ECN_ENABLED(tp
) && !(tp
->ecn_flags
& TE_CEHEURI_SET
)) {
2827 tcpstat
.tcps_ecn_fallback_ce
++;
2828 tcp_heuristic_ecn_aggressive(tp
);
2829 tp
->ecn_flags
|= TE_CEHEURI_SET
;
2832 if (tp
->t_state
== TCPS_ESTABLISHED
&& TCP_ECN_ENABLED(tp
) &&
2833 ip_ecn
== IPTOS_ECN_CE
&& !(tp
->ecn_flags
& TE_CEHEURI_SET
)) {
2834 if (inp
->inp_stat
->rxpackets
< ECN_MIN_CE_PROBES
) {
2835 tp
->t_ecn_recv_ce_pkt
++;
2836 } else if (tp
->t_ecn_recv_ce_pkt
> ECN_MAX_CE_RATIO
) {
2837 tcpstat
.tcps_ecn_fallback_ce
++;
2838 tcp_heuristic_ecn_aggressive(tp
);
2839 tp
->ecn_flags
|= TE_CEHEURI_SET
;
2840 INP_INC_IFNET_STAT(inp
, ecn_fallback_ce
);
2842 /* We tracked the first ECN_MIN_CE_PROBES segments, we
2843 * now know that the path is good.
2845 tp
->ecn_flags
|= TE_CEHEURI_SET
;
2850 * Try to determine if we are receiving a packet after a long time.
2851 * Use our own approximation of idletime to roughly measure remote
2852 * end's idle time. Since slowstart is used after an idle period
2853 * we want to avoid doing LRO if the remote end is not up to date
2854 * on initial window support and starts with 1 or 2 packets as its IW.
2856 if (sw_lro
&& (tp
->t_flagsext
& TF_LRO_OFFLOADED
) &&
2857 ((tcp_now
- tp
->t_rcvtime
) >= (TCP_IDLETIMEOUT(tp
)))) {
2861 /* Update rcvtime as a new segment was received on the connection */
2862 tp
->t_rcvtime
= tcp_now
;
2865 * Segment received on connection.
2866 * Reset idle time and keep-alive timer.
2868 if (TCPS_HAVEESTABLISHED(tp
->t_state
)) {
2869 tcp_keepalive_reset(tp
);
2872 mptcp_reset_keepalive(tp
);
2877 * Process options if not in LISTEN state,
2878 * else do it below (after getting remote address).
2880 if (tp
->t_state
!= TCPS_LISTEN
&& optp
) {
2881 tcp_dooptions(tp
, optp
, optlen
, th
, &to
);
2884 if (tp
->t_state
!= TCPS_LISTEN
&& (so
->so_flags
& SOF_MP_SUBFLOW
) &&
2885 mptcp_input_preproc(tp
, m
, th
, drop_hdrlen
) != 0) {
2886 tp
->t_flags
|= TF_ACKNOW
;
2887 (void) tcp_output(tp
);
2888 tcp_check_timer_state(tp
);
2889 socket_unlock(so
, 1);
2890 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
|
2891 DBG_FUNC_END
, 0, 0, 0, 0, 0);
2895 if (tp
->t_state
== TCPS_SYN_SENT
&& (thflags
& TH_SYN
)) {
2896 if (!(thflags
& TH_ACK
) ||
2897 (SEQ_GT(th
->th_ack
, tp
->iss
) &&
2898 SEQ_LEQ(th
->th_ack
, tp
->snd_max
))) {
2899 tcp_finalize_options(tp
, &to
, ifscope
);
2905 * Compute inter-packet arrival jitter. According to RFC 3550,
2906 * inter-packet arrival jitter is defined as the difference in
2907 * packet spacing at the receiver compared to the sender for a
2908 * pair of packets. When two packets of maximum segment size come
2909 * one after the other with consecutive sequence numbers, we
2910 * consider them as packets sent together at the sender and use
2911 * them as a pair to compute inter-packet arrival jitter. This
2912 * metric indicates the delay induced by the network components due
2913 * to queuing in edge/access routers.
2915 if (tp
->t_state
== TCPS_ESTABLISHED
&&
2916 (thflags
& (TH_SYN
| TH_FIN
| TH_RST
| TH_URG
| TH_ACK
| TH_ECE
| TH_PUSH
)) == TH_ACK
&&
2917 ((tp
->t_flags
& (TF_NEEDSYN
| TF_NEEDFIN
)) == 0) &&
2918 ((to
.to_flags
& TOF_TS
) == 0 ||
2919 TSTMP_GEQ(to
.to_tsval
, tp
->ts_recent
)) &&
2920 th
->th_seq
== tp
->rcv_nxt
&& LIST_EMPTY(&tp
->t_segq
)) {
2921 int seg_size
= tlen
;
2922 if (tp
->iaj_pktcnt
<= IAJ_IGNORE_PKTCNT
) {
2923 TCP_INC_VAR(tp
->iaj_pktcnt
, nlropkts
);
2926 if (m
->m_pkthdr
.pkt_flags
& PKTF_SW_LRO_PKT
) {
2927 seg_size
= m
->m_pkthdr
.lro_pktlen
;
2929 if (tp
->iaj_size
== 0 || seg_size
> tp
->iaj_size
||
2930 (seg_size
== tp
->iaj_size
&& tp
->iaj_rcv_ts
== 0)) {
2932 * State related to inter-arrival jitter is
2933 * uninitialized or we are trying to find a good
2934 * first packet to start computing the metric
2936 update_iaj_state(tp
, seg_size
, 0);
2938 if (seg_size
== tp
->iaj_size
) {
2940 * Compute inter-arrival jitter taking
2941 * this packet as the second packet
2943 if (pktf_sw_lro_pkt
) {
2944 compute_iaj(tp
, nlropkts
,
2945 m
->m_pkthdr
.lro_elapsed
);
2947 compute_iaj(tp
, 1, 0);
2950 if (seg_size
< tp
->iaj_size
) {
2952 * There is a smaller packet in the stream.
2953 * Some times the maximum size supported
2954 * on a path can change if there is a new
2955 * link with smaller MTU. The receiver will
2956 * not know about this change. If there
2957 * are too many packets smaller than
2958 * iaj_size, we try to learn the iaj_size
2961 TCP_INC_VAR(tp
->iaj_small_pkt
, nlropkts
);
2962 if (tp
->iaj_small_pkt
> RESET_IAJ_SIZE_THRESH
) {
2963 update_iaj_state(tp
, seg_size
, 1);
2965 CLEAR_IAJ_STATE(tp
);
2968 update_iaj_state(tp
, seg_size
, 0);
2972 CLEAR_IAJ_STATE(tp
);
2974 #endif /* TRAFFIC_MGT */
2977 * Header prediction: check for the two common cases
2978 * of a uni-directional data xfer. If the packet has
2979 * no control flags, is in-sequence, the window didn't
2980 * change and we're not retransmitting, it's a
2981 * candidate. If the length is zero and the ack moved
2982 * forward, we're the sender side of the xfer. Just
2983 * free the data acked & wake any higher level process
2984 * that was blocked waiting for space. If the length
2985 * is non-zero and the ack didn't move, we're the
2986 * receiver side. If we're getting packets in-order
2987 * (the reassembly queue is empty), add the data to
2988 * the socket buffer and note that we need a delayed ack.
2989 * Make sure that the hidden state-flags are also off.
2990 * Since we check for TCPS_ESTABLISHED above, it can only
2993 if (tp
->t_state
== TCPS_ESTABLISHED
&&
2994 (thflags
& (TH_SYN
| TH_FIN
| TH_RST
| TH_URG
| TH_ACK
| TH_ECE
| TH_CWR
)) == TH_ACK
&&
2995 ((tp
->t_flags
& (TF_NEEDSYN
| TF_NEEDFIN
)) == 0) &&
2996 ((to
.to_flags
& TOF_TS
) == 0 ||
2997 TSTMP_GEQ(to
.to_tsval
, tp
->ts_recent
)) &&
2998 th
->th_seq
== tp
->rcv_nxt
&&
2999 tiwin
&& tiwin
== tp
->snd_wnd
&&
3000 tp
->snd_nxt
== tp
->snd_max
) {
3002 * If last ACK falls within this segment's sequence numbers,
3003 * record the timestamp.
3004 * NOTE that the test is modified according to the latest
3005 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
3007 if ((to
.to_flags
& TOF_TS
) != 0 &&
3008 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
)) {
3009 tp
->ts_recent_age
= tcp_now
;
3010 tp
->ts_recent
= to
.to_tsval
;
3014 if (SEQ_GT(th
->th_ack
, tp
->snd_una
) &&
3015 SEQ_LEQ(th
->th_ack
, tp
->snd_max
) &&
3016 tp
->snd_cwnd
>= tp
->snd_ssthresh
&&
3017 (!IN_FASTRECOVERY(tp
) &&
3018 ((!(SACK_ENABLED(tp
)) &&
3019 tp
->t_dupacks
< tp
->t_rexmtthresh
) ||
3020 (SACK_ENABLED(tp
) && to
.to_nsacks
== 0 &&
3021 TAILQ_EMPTY(&tp
->snd_holes
))))) {
3023 * this is a pure ack for outstanding data.
3025 ++tcpstat
.tcps_predack
;
3027 tcp_bad_rexmt_check(tp
, th
, &to
);
3029 /* Recalculate the RTT */
3030 tcp_compute_rtt(tp
, &to
, th
);
3032 VERIFY(SEQ_GEQ(th
->th_ack
, tp
->snd_una
));
3033 acked
= BYTES_ACKED(th
, tp
);
3034 tcpstat
.tcps_rcvackpack
++;
3035 tcpstat
.tcps_rcvackbyte
+= acked
;
3038 * Handle an ack that is in sequence during
3039 * congestion avoidance phase. The
3040 * calculations in this function
3041 * assume that snd_una is not updated yet.
3043 if (CC_ALGO(tp
)->congestion_avd
!= NULL
) {
3044 CC_ALGO(tp
)->congestion_avd(tp
, th
);
3046 tcp_ccdbg_trace(tp
, th
, TCP_CC_INSEQ_ACK_RCVD
);
3047 sbdrop(&so
->so_snd
, acked
);
3048 if (so
->so_flags
& SOF_ENABLE_MSGS
) {
3049 VERIFY(acked
<= so
->so_msg_state
->msg_serial_bytes
);
3050 so
->so_msg_state
->msg_serial_bytes
-= acked
;
3052 tcp_sbsnd_trim(&so
->so_snd
);
3054 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
3055 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
)) {
3056 tp
->snd_recover
= th
->th_ack
- 1;
3058 tp
->snd_una
= th
->th_ack
;
3060 TCP_RESET_REXMT_STATE(tp
);
3063 * pull snd_wl2 up to prevent seq wrap relative
3066 tp
->snd_wl2
= th
->th_ack
;
3068 if (tp
->t_dupacks
> 0) {
3070 tp
->t_rexmtthresh
= tcprexmtthresh
;
3076 * If all outstanding data are acked, stop
3077 * retransmit timer, otherwise restart timer
3078 * using current (possibly backed-off) value.
3079 * If process is waiting for space,
3080 * wakeup/selwakeup/signal. If data
3081 * are ready to send, let tcp_output
3082 * decide between more output or persist.
3084 if (tp
->snd_una
== tp
->snd_max
) {
3085 tp
->t_timer
[TCPT_REXMT
] = 0;
3086 tp
->t_timer
[TCPT_PTO
] = 0;
3087 } else if (tp
->t_timer
[TCPT_PERSIST
] == 0) {
3088 tp
->t_timer
[TCPT_REXMT
] =
3089 OFFSET_FROM_START(tp
,
3092 if (!SLIST_EMPTY(&tp
->t_rxt_segments
) &&
3093 !TCP_DSACK_SEQ_IN_WINDOW(tp
,
3094 tp
->t_dsack_lastuna
, tp
->snd_una
)) {
3095 tcp_rxtseg_clean(tp
);
3098 if ((tp
->t_flagsext
& TF_MEASURESNDBW
) != 0 &&
3099 tp
->t_bwmeas
!= NULL
) {
3100 tcp_bwmeas_check(tp
);
3103 sowwakeup(so
); /* has to be done with socket lock held */
3104 if (!SLIST_EMPTY(&tp
->t_notify_ack
)) {
3105 tcp_notify_acknowledgement(tp
, so
);
3108 if ((so
->so_snd
.sb_cc
) || (tp
->t_flags
& TF_ACKNOW
)) {
3109 (void) tcp_output(tp
);
3112 tcp_tfo_rcv_ack(tp
, th
);
3114 tcp_check_timer_state(tp
);
3115 socket_unlock(so
, 1);
3116 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
, 0, 0, 0, 0, 0);
3119 } else if (th
->th_ack
== tp
->snd_una
&&
3120 LIST_EMPTY(&tp
->t_segq
) &&
3121 tlen
<= tcp_sbspace(tp
)) {
3123 * this is a pure, in-sequence data packet
3124 * with nothing on the reassembly queue and
3125 * we have enough buffer space to take it.
3129 * If this is a connection in steady state, start
3130 * coalescing packets belonging to this flow.
3133 tcp_lro_remove_state(tp
->t_inpcb
->inp_laddr
,
3134 tp
->t_inpcb
->inp_faddr
,
3135 tp
->t_inpcb
->inp_lport
,
3136 tp
->t_inpcb
->inp_fport
);
3137 tp
->t_flagsext
&= ~TF_LRO_OFFLOADED
;
3138 tp
->t_idleat
= tp
->rcv_nxt
;
3139 } else if (sw_lro
&& !pktf_sw_lro_pkt
&& !isipv6
&&
3140 (so
->so_flags
& SOF_USELRO
) &&
3141 !IFNET_IS_CELLULAR(m
->m_pkthdr
.rcvif
) &&
3142 (m
->m_pkthdr
.rcvif
->if_type
!= IFT_LOOP
) &&
3143 ((th
->th_seq
- tp
->irs
) >
3144 (tp
->t_maxseg
<< lro_start
)) &&
3145 ((tp
->t_idleat
== 0) || ((th
->th_seq
-
3146 tp
->t_idleat
) > (tp
->t_maxseg
<< lro_start
)))) {
3147 tp
->t_flagsext
|= TF_LRO_OFFLOADED
;
3148 tcp_start_coalescing(ip
, th
, tlen
);
3152 /* Clean receiver SACK report if present */
3153 if (SACK_ENABLED(tp
) && tp
->rcv_numsacks
) {
3154 tcp_clean_sackreport(tp
);
3156 ++tcpstat
.tcps_preddat
;
3157 tp
->rcv_nxt
+= tlen
;
3159 * Pull snd_wl1 up to prevent seq wrap relative to
3162 tp
->snd_wl1
= th
->th_seq
;
3164 * Pull rcv_up up to prevent seq wrap relative to
3167 tp
->rcv_up
= tp
->rcv_nxt
;
3168 TCP_INC_VAR(tcpstat
.tcps_rcvpack
, nlropkts
);
3169 tcpstat
.tcps_rcvbyte
+= tlen
;
3170 if (nstat_collect
) {
3171 if (m
->m_pkthdr
.pkt_flags
& PKTF_SW_LRO_PKT
) {
3172 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
3173 rxpackets
, m
->m_pkthdr
.lro_npkts
);
3175 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
3178 INP_ADD_STAT(inp
, cell
, wifi
, wired
, rxbytes
,
3180 inp_set_activity_bitmap(inp
);
3184 * Calculate the RTT on the receiver only if the
3185 * connection is in streaming mode and the last
3186 * packet was not an end-of-write
3188 if (tp
->t_flags
& TF_STREAMING_ON
) {
3189 tcp_compute_rtt(tp
, &to
, th
);
3192 tcp_sbrcv_grow(tp
, &so
->so_rcv
, &to
, tlen
,
3193 TCP_AUTORCVBUF_MAX(ifp
));
3196 * Add data to socket buffer.
3198 so_recv_data_stat(so
, m
, 0);
3199 m_adj(m
, drop_hdrlen
); /* delayed header drop */
3202 * If message delivery (SOF_ENABLE_MSGS) is enabled on
3203 * this socket, deliver the packet received as an
3204 * in-order message with sequence number attached to it.
3206 if (sbappendstream_rcvdemux(so
, m
,
3207 th
->th_seq
- (tp
->irs
+ 1), 0)) {
3212 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
3213 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
3214 th
->th_seq
, th
->th_ack
, th
->th_win
);
3218 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
3219 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
3220 th
->th_seq
, th
->th_ack
, th
->th_win
);
3222 TCP_INC_VAR(tp
->t_unacksegs
, nlropkts
);
3223 if (DELAY_ACK(tp
, th
)) {
3224 if ((tp
->t_flags
& TF_DELACK
) == 0) {
3225 tp
->t_flags
|= TF_DELACK
;
3226 tp
->t_timer
[TCPT_DELACK
] = OFFSET_FROM_START(tp
, tcp_delack
);
3229 tp
->t_flags
|= TF_ACKNOW
;
3233 tcp_adaptive_rwtimo_check(tp
, tlen
);
3236 tcp_tfo_rcv_data(tp
);
3239 tcp_check_timer_state(tp
);
3240 socket_unlock(so
, 1);
3241 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
, 0, 0, 0, 0, 0);
3247 * Calculate amount of space in receive window,
3248 * and then do TCP input processing.
3249 * Receive window is amount of space in rcv queue,
3250 * but not less than advertised window.
3252 socket_lock_assert_owned(so
);
3253 win
= tcp_sbspace(tp
);
3256 } else { /* clip rcv window to 4K for modems */
3257 if (tp
->t_flags
& TF_SLOWLINK
&& slowlink_wsize
> 0) {
3258 win
= min(win
, slowlink_wsize
);
3261 tp
->rcv_wnd
= imax(win
, (int)(tp
->rcv_adv
- tp
->rcv_nxt
));
3264 * Ensure that the subflow receive window isn't greater
3265 * than the connection level receive window.
3267 if ((tp
->t_mpflags
& TMPF_MPTCP_TRUE
) &&
3268 (mp_tp
= tptomptp(tp
))) {
3269 mpte_lock_assert_held(mp_tp
->mpt_mpte
);
3270 if (tp
->rcv_wnd
> mp_tp
->mpt_rcvwnd
) {
3271 tp
->rcv_wnd
= imax(mp_tp
->mpt_rcvwnd
, (int)(tp
->rcv_adv
- tp
->rcv_nxt
));
3272 tcpstat
.tcps_mp_reducedwin
++;
3277 switch (tp
->t_state
) {
3279 * Initialize tp->rcv_nxt, and tp->irs, select an initial
3280 * tp->iss, and send a segment:
3281 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
3282 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
3283 * Fill in remote peer address fields if not previously specified.
3284 * Enter SYN_RECEIVED state, and process any other fields of this
3285 * segment in this state.
3288 struct sockaddr_in
*sin
;
3290 struct sockaddr_in6
*sin6
;
3293 socket_lock_assert_owned(so
);
3296 MALLOC(sin6
, struct sockaddr_in6
*, sizeof *sin6
,
3297 M_SONAME
, M_NOWAIT
);
3301 bzero(sin6
, sizeof(*sin6
));
3302 sin6
->sin6_family
= AF_INET6
;
3303 sin6
->sin6_len
= sizeof(*sin6
);
3304 sin6
->sin6_addr
= ip6
->ip6_src
;
3305 sin6
->sin6_port
= th
->th_sport
;
3306 laddr6
= inp
->in6p_laddr
;
3307 if (IN6_IS_ADDR_UNSPECIFIED(&inp
->in6p_laddr
)) {
3308 inp
->in6p_laddr
= ip6
->ip6_dst
;
3310 if (in6_pcbconnect(inp
, (struct sockaddr
*)sin6
,
3312 inp
->in6p_laddr
= laddr6
;
3313 FREE(sin6
, M_SONAME
);
3316 FREE(sin6
, M_SONAME
);
3320 socket_lock_assert_owned(so
);
3321 MALLOC(sin
, struct sockaddr_in
*, sizeof *sin
, M_SONAME
,
3326 sin
->sin_family
= AF_INET
;
3327 sin
->sin_len
= sizeof(*sin
);
3328 sin
->sin_addr
= ip
->ip_src
;
3329 sin
->sin_port
= th
->th_sport
;
3330 bzero((caddr_t
)sin
->sin_zero
, sizeof(sin
->sin_zero
));
3331 laddr
= inp
->inp_laddr
;
3332 if (inp
->inp_laddr
.s_addr
== INADDR_ANY
) {
3333 inp
->inp_laddr
= ip
->ip_dst
;
3335 if (in_pcbconnect(inp
, (struct sockaddr
*)sin
, proc0
,
3336 IFSCOPE_NONE
, NULL
)) {
3337 inp
->inp_laddr
= laddr
;
3338 FREE(sin
, M_SONAME
);
3341 FREE(sin
, M_SONAME
);
3344 tcp_dooptions(tp
, optp
, optlen
, th
, &to
);
3345 tcp_finalize_options(tp
, &to
, ifscope
);
3347 if (tfo_enabled(tp
) && tcp_tfo_syn(tp
, &to
)) {
3354 tp
->iss
= tcp_new_isn(tp
);
3356 tp
->irs
= th
->th_seq
;
3357 tcp_sendseqinit(tp
);
3359 tp
->snd_recover
= tp
->snd_una
;
3361 * Initialization of the tcpcb for transaction;
3362 * set SND.WND = SEG.WND,
3363 * initialize CCsend and CCrecv.
3365 tp
->snd_wnd
= tiwin
; /* initial send-window */
3366 tp
->max_sndwnd
= tp
->snd_wnd
;
3367 tp
->t_flags
|= TF_ACKNOW
;
3368 tp
->t_unacksegs
= 0;
3369 DTRACE_TCP4(state__change
, void, NULL
, struct inpcb
*, inp
,
3370 struct tcpcb
*, tp
, int32_t, TCPS_SYN_RECEIVED
);
3371 tp
->t_state
= TCPS_SYN_RECEIVED
;
3372 tp
->t_timer
[TCPT_KEEP
] = OFFSET_FROM_START(tp
,
3373 TCP_CONN_KEEPINIT(tp
));
3374 dropsocket
= 0; /* committed to socket */
3376 if (inp
->inp_flowhash
== 0) {
3377 inp
->inp_flowhash
= inp_calc_flowhash(inp
);
3380 /* update flowinfo - RFC 6437 */
3381 if (inp
->inp_flow
== 0 &&
3382 inp
->in6p_flags
& IN6P_AUTOFLOWLABEL
) {
3383 inp
->inp_flow
&= ~IPV6_FLOWLABEL_MASK
;
3385 (htonl(inp
->inp_flowhash
) & IPV6_FLOWLABEL_MASK
);
3389 /* reset the incomp processing flag */
3390 so
->so_flags
&= ~(SOF_INCOMP_INPROGRESS
);
3391 tcpstat
.tcps_accepts
++;
3392 if ((thflags
& (TH_ECE
| TH_CWR
)) == (TH_ECE
| TH_CWR
)) {
3394 tp
->ecn_flags
|= (TE_SETUPRECEIVED
| TE_SENDIPECT
);
3401 * If the state is SYN_RECEIVED and the seg contains an ACK,
3402 * but not for our SYN/ACK, send a RST.
3404 case TCPS_SYN_RECEIVED
:
3405 if ((thflags
& TH_ACK
) &&
3406 (SEQ_LEQ(th
->th_ack
, tp
->snd_una
) ||
3407 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
3408 rstreason
= BANDLIM_RST_OPENPORT
;
3409 IF_TCP_STATINC(ifp
, ooopacket
);
3414 * In SYN_RECEIVED state, if we recv some SYNS with
3415 * window scale and others without, window scaling should
3416 * be disabled. Otherwise the window advertised will be
3417 * lower if we assume scaling and the other end does not.
3419 if ((thflags
& TH_SYN
) &&
3420 (tp
->irs
== th
->th_seq
) &&
3421 !(to
.to_flags
& TOF_SCALE
)) {
3422 tp
->t_flags
&= ~TF_RCVD_SCALE
;
3427 * If the state is SYN_SENT:
3428 * if seg contains an ACK, but not for our SYN, drop the input.
3429 * if seg contains a RST, then drop the connection.
3430 * if seg does not contain SYN, then drop it.
3431 * Otherwise this is an acceptable SYN segment
3432 * initialize tp->rcv_nxt and tp->irs
3433 * if seg contains ack then advance tp->snd_una
3434 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
3435 * arrange for segment to be acked (eventually)
3436 * continue processing rest of data/controls, beginning with URG
3439 if ((thflags
& TH_ACK
) &&
3440 (SEQ_LEQ(th
->th_ack
, tp
->iss
) ||
3441 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
3442 rstreason
= BANDLIM_UNLIMITED
;
3443 IF_TCP_STATINC(ifp
, ooopacket
);
3446 if (thflags
& TH_RST
) {
3447 if ((thflags
& TH_ACK
) != 0) {
3448 if (tfo_enabled(tp
)) {
3449 tcp_heuristic_tfo_rst(tp
);
3451 if ((tp
->ecn_flags
& (TE_SETUPSENT
| TE_RCVD_SYN_RST
)) == TE_SETUPSENT
) {
3453 * On local connections, send
3454 * non-ECN syn one time before
3455 * dropping the connection
3457 if (tp
->t_flags
& TF_LOCAL
) {
3458 tp
->ecn_flags
|= TE_RCVD_SYN_RST
;
3461 tcp_heuristic_ecn_synrst(tp
);
3465 (SO_FILT_HINT_LOCKED
|
3466 SO_FILT_HINT_CONNRESET
));
3467 tp
= tcp_drop(tp
, ECONNREFUSED
);
3468 postevent(so
, 0, EV_RESET
);
3472 if ((thflags
& TH_SYN
) == 0) {
3475 tp
->snd_wnd
= th
->th_win
; /* initial send window */
3476 tp
->max_sndwnd
= tp
->snd_wnd
;
3478 tp
->irs
= th
->th_seq
;
3480 if (thflags
& TH_ACK
) {
3481 tcpstat
.tcps_connects
++;
3483 if ((thflags
& (TH_ECE
| TH_CWR
)) == (TH_ECE
)) {
3484 /* ECN-setup SYN-ACK */
3485 tp
->ecn_flags
|= TE_SETUPRECEIVED
;
3486 if (TCP_ECN_ENABLED(tp
)) {
3487 tcp_heuristic_ecn_success(tp
);
3488 tcpstat
.tcps_ecn_client_success
++;
3491 if (tp
->ecn_flags
& TE_SETUPSENT
&&
3492 tp
->t_rxtshift
== 0) {
3493 tcp_heuristic_ecn_success(tp
);
3494 tcpstat
.tcps_ecn_not_supported
++;
3496 if (tp
->ecn_flags
& TE_SETUPSENT
&&
3497 tp
->t_rxtshift
> 0) {
3498 tcp_heuristic_ecn_loss(tp
);
3501 /* non-ECN-setup SYN-ACK */
3502 tp
->ecn_flags
&= ~TE_SENDIPECT
;
3505 #if CONFIG_MACF_NET && CONFIG_MACF_SOCKET
3506 /* XXXMAC: recursive lock: SOCK_LOCK(so); */
3507 mac_socketpeer_label_associate_mbuf(m
, so
);
3508 /* XXXMAC: SOCK_UNLOCK(so); */
3510 /* Do window scaling on this connection? */
3511 if (TCP_WINDOW_SCALE_ENABLED(tp
)) {
3512 tp
->snd_scale
= tp
->requested_s_scale
;
3513 tp
->rcv_scale
= tp
->request_r_scale
;
3516 tp
->rcv_adv
+= min(tp
->rcv_wnd
, TCP_MAXWIN
<< tp
->rcv_scale
);
3517 tp
->snd_una
++; /* SYN is acked */
3518 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
)) {
3519 tp
->snd_nxt
= tp
->snd_una
;
3523 * We have sent more in the SYN than what is being
3524 * acked. (e.g., TFO)
3525 * We should restart the sending from what the receiver
3526 * has acknowledged immediately.
3528 if (SEQ_GT(tp
->snd_nxt
, th
->th_ack
)) {
3530 * rdar://problem/33214601
3531 * There is a middlebox that acks all but one
3532 * byte and still drops the data.
3534 if ((tp
->t_tfo_stats
& TFO_S_SYN_DATA_SENT
) &&
3535 tp
->snd_max
== th
->th_ack
+ 1 &&
3536 tp
->snd_max
> tp
->snd_una
+ 1) {
3537 tcp_heuristic_tfo_middlebox(tp
);
3539 so
->so_error
= ENODATA
;
3541 tp
->t_tfo_stats
|= TFO_S_ONE_BYTE_PROXY
;
3544 tp
->snd_max
= tp
->snd_nxt
= th
->th_ack
;
3548 * If there's data, delay ACK; if there's also a FIN
3549 * ACKNOW will be turned on later.
3551 TCP_INC_VAR(tp
->t_unacksegs
, nlropkts
);
3552 if (DELAY_ACK(tp
, th
) && tlen
!= 0) {
3553 if ((tp
->t_flags
& TF_DELACK
) == 0) {
3554 tp
->t_flags
|= TF_DELACK
;
3555 tp
->t_timer
[TCPT_DELACK
] = OFFSET_FROM_START(tp
, tcp_delack
);
3558 tp
->t_flags
|= TF_ACKNOW
;
3561 * Received <SYN,ACK> in SYN_SENT[*] state.
3563 * SYN_SENT --> ESTABLISHED
3564 * SYN_SENT* --> FIN_WAIT_1
3566 tp
->t_starttime
= tcp_now
;
3567 tcp_sbrcv_tstmp_check(tp
);
3568 if (tp
->t_flags
& TF_NEEDFIN
) {
3569 DTRACE_TCP4(state__change
, void, NULL
,
3570 struct inpcb
*, inp
,
3571 struct tcpcb
*, tp
, int32_t,
3573 tp
->t_state
= TCPS_FIN_WAIT_1
;
3574 tp
->t_flags
&= ~TF_NEEDFIN
;
3577 DTRACE_TCP4(state__change
, void, NULL
,
3578 struct inpcb
*, inp
, struct tcpcb
*,
3579 tp
, int32_t, TCPS_ESTABLISHED
);
3580 tp
->t_state
= TCPS_ESTABLISHED
;
3581 tp
->t_timer
[TCPT_KEEP
] =
3582 OFFSET_FROM_START(tp
,
3583 TCP_CONN_KEEPIDLE(tp
));
3584 if (nstat_collect
) {
3585 nstat_route_connect_success(
3586 inp
->inp_route
.ro_rt
);
3589 * The SYN is acknowledged but una is not
3590 * updated yet. So pass the value of
3591 * ack to compute sndbytes correctly
3593 inp_count_sndbytes(inp
, th
->th_ack
);
3597 * Do not send the connect notification for additional
3598 * subflows until ACK for 3-way handshake arrives.
3600 if ((!(tp
->t_mpflags
& TMPF_MPTCP_TRUE
)) &&
3601 (tp
->t_mpflags
& TMPF_SENT_JOIN
)) {
3602 isconnected
= FALSE
;
3607 if ((tp
->t_tfo_flags
& (TFO_F_COOKIE_REQ
| TFO_F_COOKIE_SENT
)) ||
3608 (tp
->t_tfo_stats
& TFO_S_SYN_DATA_SENT
)) {
3609 tcp_tfo_synack(tp
, &to
);
3611 if ((tp
->t_tfo_stats
& TFO_S_SYN_DATA_SENT
) &&
3612 SEQ_LT(tp
->snd_una
, th
->th_ack
)) {
3613 tp
->t_tfo_stats
|= TFO_S_SYN_DATA_ACKED
;
3614 tcpstat
.tcps_tfo_syn_data_acked
++;
3616 if (so
->so_flags
& SOF_MP_SUBFLOW
) {
3617 so
->so_flags1
|= SOF1_TFO_REWIND
;
3620 tcp_tfo_rcv_probe(tp
, tlen
);
3625 * Received initial SYN in SYN-SENT[*] state => simul-
3626 * taneous open. If segment contains CC option and there is
3627 * a cached CC, apply TAO test; if it succeeds, connection is
3628 * half-synchronized. Otherwise, do 3-way handshake:
3629 * SYN-SENT -> SYN-RECEIVED
3630 * SYN-SENT* -> SYN-RECEIVED*
3632 tp
->t_flags
|= TF_ACKNOW
;
3633 tp
->t_timer
[TCPT_REXMT
] = 0;
3634 DTRACE_TCP4(state__change
, void, NULL
, struct inpcb
*, inp
,
3635 struct tcpcb
*, tp
, int32_t, TCPS_SYN_RECEIVED
);
3636 tp
->t_state
= TCPS_SYN_RECEIVED
;
3639 * During simultaneous open, TFO should not be used.
3640 * So, we disable it here, to prevent that data gets
3641 * sent on the SYN/ACK.
3643 tcp_disable_tfo(tp
);
3648 * Advance th->th_seq to correspond to first data byte.
3649 * If data, trim to stay within window,
3650 * dropping FIN if necessary.
3653 if (tlen
> tp
->rcv_wnd
) {
3654 todrop
= tlen
- tp
->rcv_wnd
;
3658 tcpstat
.tcps_rcvpackafterwin
++;
3659 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
3661 tp
->snd_wl1
= th
->th_seq
- 1;
3662 tp
->rcv_up
= th
->th_seq
;
3664 * Client side of transaction: already sent SYN and data.
3665 * If the remote host used T/TCP to validate the SYN,
3666 * our data will be ACK'd; if so, enter normal data segment
3667 * processing in the middle of step 5, ack processing.
3668 * Otherwise, goto step 6.
3670 if (thflags
& TH_ACK
) {
3675 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
3676 * do normal processing.
3678 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
3682 case TCPS_TIME_WAIT
:
3683 break; /* continue normal processing */
3685 /* Received a SYN while connection is already established.
3686 * This is a "half open connection and other anomalies" described
3687 * in RFC793 page 34, send an ACK so the remote reset the connection
3688 * or recovers by adjusting its sequence numbering. Sending an ACK is
3689 * in accordance with RFC 5961 Section 4.2
3691 case TCPS_ESTABLISHED
:
3692 if (thflags
& TH_SYN
) {
3693 /* Drop the packet silently if we have reached the limit */
3694 if (tcp_do_rfc5961
&& tcp_is_ack_ratelimited(tp
)) {
3697 /* Send challenge ACK */
3698 tcpstat
.tcps_synchallenge
++;
3706 * States other than LISTEN or SYN_SENT.
3707 * First check the RST flag and sequence number since reset segments
3708 * are exempt from the timestamp and connection count tests. This
3709 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
3710 * below which allowed reset segments in half the sequence space
3711 * to fall though and be processed (which gives forged reset
3712 * segments with a random sequence number a 50 percent chance of
3713 * killing a connection).
3714 * Then check timestamp, if present.
3715 * Then check the connection count, if present.
3716 * Then check that at least some bytes of segment are within
3717 * receive window. If segment begins before rcv_nxt,
3718 * drop leading data (and SYN); if nothing left, just ack.
3721 * If the RST bit is set, check the sequence number to see
3722 * if this is a valid reset segment.
3724 * In all states except SYN-SENT, all reset (RST) segments
3725 * are validated by checking their SEQ-fields. A reset is
3726 * valid if its sequence number is in the window.
3727 * Note: this does not take into account delayed ACKs, so
3728 * we should test against last_ack_sent instead of rcv_nxt.
3729 * The sequence number in the reset segment is normally an
3730 * echo of our outgoing acknowlegement numbers, but some hosts
3731 * send a reset with the sequence number at the rightmost edge
3732 * of our receive window, and we have to handle this case.
3733 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
3734 * that brute force RST attacks are possible. To combat this,
3735 * we use a much stricter check while in the ESTABLISHED state,
3736 * only accepting RSTs where the sequence number is equal to
3737 * last_ack_sent. In all other states (the states in which a
3738 * RST is more likely), the more permissive check is used.
3739 * RFC 5961 Section 3.2: if the RST bit is set, sequence # is
3740 * within the receive window and last_ack_sent == seq,
3741 * then reset the connection. Otherwise if the seq doesn't
3742 * match last_ack_sent, TCP must send challenge ACK. Perform
3743 * rate limitation when sending the challenge ACK.
3744 * If we have multiple segments in flight, the intial reset
3745 * segment sequence numbers will be to the left of last_ack_sent,
3746 * but they will eventually catch up.
3747 * In any case, it never made sense to trim reset segments to
3748 * fit the receive window since RFC 1122 says:
3749 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
3751 * A TCP SHOULD allow a received RST segment to include data.
3754 * It has been suggested that a RST segment could contain
3755 * ASCII text that encoded and explained the cause of the
3756 * RST. No standard has yet been established for such
3759 * If the reset segment passes the sequence number test examine
3761 * SYN_RECEIVED STATE:
3762 * If passive open, return to LISTEN state.
3763 * If active open, inform user that connection was refused.
3764 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
3765 * Inform user that connection was reset, and close tcb.
3766 * CLOSING, LAST_ACK STATES:
3769 * Drop the segment - see Stevens, vol. 2, p. 964 and
3772 * Radar 4803931: Allows for the case where we ACKed the FIN but
3773 * there is already a RST in flight from the peer.
3774 * In that case, accept the RST for non-established
3775 * state if it's one off from last_ack_sent.
3778 if (thflags
& TH_RST
) {
3779 if ((SEQ_GEQ(th
->th_seq
, tp
->last_ack_sent
) &&
3780 SEQ_LT(th
->th_seq
, tp
->last_ack_sent
+ tp
->rcv_wnd
)) ||
3781 (tp
->rcv_wnd
== 0 &&
3782 ((tp
->last_ack_sent
== th
->th_seq
) ||
3783 ((tp
->last_ack_sent
- 1) == th
->th_seq
)))) {
3784 if (tcp_do_rfc5961
== 0 || tp
->last_ack_sent
== th
->th_seq
) {
3785 switch (tp
->t_state
) {
3786 case TCPS_SYN_RECEIVED
:
3787 IF_TCP_STATINC(ifp
, rstinsynrcv
);
3788 so
->so_error
= ECONNREFUSED
;
3791 case TCPS_ESTABLISHED
:
3792 if (tcp_do_rfc5961
== 0 && tp
->last_ack_sent
!= th
->th_seq
) {
3793 tcpstat
.tcps_badrst
++;
3796 if (TCP_ECN_ENABLED(tp
) &&
3797 tp
->snd_una
== tp
->iss
+ 1 &&
3798 SEQ_GT(tp
->snd_max
, tp
->snd_una
)) {
3800 * If the first data packet on an
3801 * ECN connection, receives a RST
3802 * increment the heuristic
3804 tcp_heuristic_ecn_droprst(tp
);
3806 case TCPS_FIN_WAIT_1
:
3807 case TCPS_CLOSE_WAIT
:
3811 case TCPS_FIN_WAIT_2
:
3812 so
->so_error
= ECONNRESET
;
3814 postevent(so
, 0, EV_RESET
);
3816 (SO_FILT_HINT_LOCKED
|
3817 SO_FILT_HINT_CONNRESET
));
3819 tcpstat
.tcps_drops
++;
3828 case TCPS_TIME_WAIT
:
3831 } else if (tcp_do_rfc5961
) {
3832 tcpstat
.tcps_badrst
++;
3833 /* Drop if we have reached the ACK limit */
3834 if (tcp_is_ack_ratelimited(tp
)) {
3837 /* Send challenge ACK */
3838 tcpstat
.tcps_rstchallenge
++;
3847 * RFC 1323 PAWS: If we have a timestamp reply on this segment
3848 * and it's less than ts_recent, drop it.
3850 if ((to
.to_flags
& TOF_TS
) != 0 && tp
->ts_recent
&&
3851 TSTMP_LT(to
.to_tsval
, tp
->ts_recent
)) {
3852 /* Check to see if ts_recent is over 24 days old. */
3853 if ((int)(tcp_now
- tp
->ts_recent_age
) > TCP_PAWS_IDLE
) {
3855 * Invalidate ts_recent. If this segment updates
3856 * ts_recent, the age will be reset later and ts_recent
3857 * will get a valid value. If it does not, setting
3858 * ts_recent to zero will at least satisfy the
3859 * requirement that zero be placed in the timestamp
3860 * echo reply when ts_recent isn't valid. The
3861 * age isn't reset until we get a valid ts_recent
3862 * because we don't want out-of-order segments to be
3863 * dropped when ts_recent is old.
3867 tcpstat
.tcps_rcvduppack
++;
3868 tcpstat
.tcps_rcvdupbyte
+= tlen
;
3870 tcpstat
.tcps_pawsdrop
++;
3873 * PAWS-drop when ECN is being used? That indicates
3874 * that ECT-marked packets take a different path, with
3875 * different congestion-characteristics.
3877 * Only fallback when we did send less than 2GB as PAWS
3878 * really has no reason to kick in earlier.
3880 if (TCP_ECN_ENABLED(tp
) &&
3881 inp
->inp_stat
->rxbytes
< 2147483648) {
3882 INP_INC_IFNET_STAT(inp
, ecn_fallback_reorder
);
3883 tcpstat
.tcps_ecn_fallback_reorder
++;
3884 tcp_heuristic_ecn_aggressive(tp
);
3887 if (nstat_collect
) {
3888 nstat_route_rx(tp
->t_inpcb
->inp_route
.ro_rt
,
3889 1, tlen
, NSTAT_RX_FLAG_DUPLICATE
);
3890 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
3892 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
3894 tp
->t_stat
.rxduplicatebytes
+= tlen
;
3895 inp_set_activity_bitmap(inp
);
3905 * In the SYN-RECEIVED state, validate that the packet belongs to
3906 * this connection before trimming the data to fit the receive
3907 * window. Check the sequence number versus IRS since we know
3908 * the sequence numbers haven't wrapped. This is a partial fix
3909 * for the "LAND" DoS attack.
3911 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& SEQ_LT(th
->th_seq
, tp
->irs
)) {
3912 rstreason
= BANDLIM_RST_OPENPORT
;
3913 IF_TCP_STATINC(ifp
, dospacket
);
3918 * Check if there is old data at the beginning of the window
3919 * i.e. the sequence number is before rcv_nxt
3921 todrop
= tp
->rcv_nxt
- th
->th_seq
;
3923 boolean_t is_syn_set
= FALSE
;
3925 if (thflags
& TH_SYN
) {
3929 if (th
->th_urp
> 1) {
3937 * Following if statement from Stevens, vol. 2, p. 960.
3938 * The amount of duplicate data is greater than or equal
3939 * to the size of the segment - entire segment is duplicate
3942 || (todrop
== tlen
&& (thflags
& TH_FIN
) == 0)) {
3944 * Any valid FIN must be to the left of the window.
3945 * At this point the FIN must be a duplicate or out
3946 * of sequence; drop it.
3951 * Send an ACK to resynchronize and drop any data.
3952 * But keep on processing for RST or ACK.
3954 * If the SYN bit was originally set, then only send
3955 * an ACK if we are not rate-limiting this connection.
3957 if (tcp_do_rfc5961
&& is_syn_set
) {
3958 if (!tcp_is_ack_ratelimited(tp
)) {
3959 tcpstat
.tcps_synchallenge
++;
3960 tp
->t_flags
|= TF_ACKNOW
;
3963 tp
->t_flags
|= TF_ACKNOW
;
3967 /* This could be a keepalive */
3968 soevent(so
, SO_FILT_HINT_LOCKED
|
3969 SO_FILT_HINT_KEEPALIVE
);
3972 tcpstat
.tcps_rcvduppack
++;
3973 tcpstat
.tcps_rcvdupbyte
+= todrop
;
3975 tcpstat
.tcps_rcvpartduppack
++;
3976 tcpstat
.tcps_rcvpartdupbyte
+= todrop
;
3979 if (TCP_DSACK_ENABLED(tp
) && todrop
> 1) {
3981 * Note the duplicate data sequence space so that
3982 * it can be reported in DSACK option.
3984 tp
->t_dsack_lseq
= th
->th_seq
;
3985 tp
->t_dsack_rseq
= th
->th_seq
+ todrop
;
3986 tp
->t_flags
|= TF_ACKNOW
;
3988 if (nstat_collect
) {
3989 nstat_route_rx(tp
->t_inpcb
->inp_route
.ro_rt
, 1,
3990 todrop
, NSTAT_RX_FLAG_DUPLICATE
);
3991 INP_ADD_STAT(inp
, cell
, wifi
, wired
, rxpackets
, 1);
3992 INP_ADD_STAT(inp
, cell
, wifi
, wired
, rxbytes
, todrop
);
3993 tp
->t_stat
.rxduplicatebytes
+= todrop
;
3994 inp_set_activity_bitmap(inp
);
3996 drop_hdrlen
+= todrop
; /* drop from the top afterwards */
3997 th
->th_seq
+= todrop
;
3999 if (th
->th_urp
> todrop
) {
4000 th
->th_urp
-= todrop
;
4008 * If new data are received on a connection after the user
4009 * processes are gone, then RST the other end.
4010 * Send also a RST when we received a data segment after we've
4011 * sent our FIN when the socket is defunct.
4012 * Note that an MPTCP subflow socket would have SS_NOFDREF set
4013 * by default. So, if it's an MPTCP-subflow we rather check the
4014 * MPTCP-level's socket state for SS_NOFDREF.
4017 boolean_t close_it
= FALSE
;
4019 if (!(so
->so_flags
& SOF_MP_SUBFLOW
) && (so
->so_state
& SS_NOFDREF
) &&
4020 tp
->t_state
> TCPS_CLOSE_WAIT
) {
4024 if ((so
->so_flags
& SOF_MP_SUBFLOW
) && (mptetoso(tptomptp(tp
)->mpt_mpte
)->so_state
& SS_NOFDREF
) &&
4025 tp
->t_state
> TCPS_CLOSE_WAIT
) {
4029 if ((so
->so_flags
& SOF_DEFUNCT
) && tp
->t_state
> TCPS_FIN_WAIT_1
) {
4035 tcpstat
.tcps_rcvafterclose
++;
4036 rstreason
= BANDLIM_UNLIMITED
;
4037 IF_TCP_STATINC(ifp
, cleanup
);
4043 * If segment ends after window, drop trailing data
4044 * (and PUSH and FIN); if nothing left, just ACK.
4046 todrop
= (th
->th_seq
+ tlen
) - (tp
->rcv_nxt
+ tp
->rcv_wnd
);
4048 tcpstat
.tcps_rcvpackafterwin
++;
4049 if (todrop
>= tlen
) {
4050 tcpstat
.tcps_rcvbyteafterwin
+= tlen
;
4052 * If a new connection request is received
4053 * while in TIME_WAIT, drop the old connection
4054 * and start over if the sequence numbers
4055 * are above the previous ones.
4057 if (thflags
& TH_SYN
&&
4058 tp
->t_state
== TCPS_TIME_WAIT
&&
4059 SEQ_GT(th
->th_seq
, tp
->rcv_nxt
)) {
4060 iss
= tcp_new_isn(tp
);
4062 socket_unlock(so
, 1);
4066 * If window is closed can only take segments at
4067 * window edge, and have to drop data and PUSH from
4068 * incoming segments. Continue processing, but
4069 * remember to ack. Otherwise, drop segment
4072 if (tp
->rcv_wnd
== 0 && th
->th_seq
== tp
->rcv_nxt
) {
4073 tp
->t_flags
|= TF_ACKNOW
;
4074 tcpstat
.tcps_rcvwinprobe
++;
4079 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
4083 thflags
&= ~(TH_PUSH
| TH_FIN
);
4087 * If last ACK falls within this segment's sequence numbers,
4088 * record its timestamp.
4090 * 1) That the test incorporates suggestions from the latest
4091 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
4092 * 2) That updating only on newer timestamps interferes with
4093 * our earlier PAWS tests, so this check should be solely
4094 * predicated on the sequence space of this segment.
4095 * 3) That we modify the segment boundary check to be
4096 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
4097 * instead of RFC1323's
4098 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
4099 * This modified check allows us to overcome RFC1323's
4100 * limitations as described in Stevens TCP/IP Illustrated
4101 * Vol. 2 p.869. In such cases, we can still calculate the
4102 * RTT correctly when RCV.NXT == Last.ACK.Sent.
4104 if ((to
.to_flags
& TOF_TS
) != 0 &&
4105 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
) &&
4106 SEQ_LEQ(tp
->last_ack_sent
, th
->th_seq
+ tlen
+
4107 ((thflags
& (TH_SYN
| TH_FIN
)) != 0))) {
4108 tp
->ts_recent_age
= tcp_now
;
4109 tp
->ts_recent
= to
.to_tsval
;
4113 * Stevens: If a SYN is in the window, then this is an
4114 * error and we send an RST and drop the connection.
4116 * RFC 5961 Section 4.2
4117 * Send challenge ACK for any SYN in synchronized state
4118 * Perform rate limitation in doing so.
4120 if (thflags
& TH_SYN
) {
4121 if (tcp_do_rfc5961
) {
4122 tcpstat
.tcps_badsyn
++;
4123 /* Drop if we have reached ACK limit */
4124 if (tcp_is_ack_ratelimited(tp
)) {
4127 /* Send challenge ACK */
4128 tcpstat
.tcps_synchallenge
++;
4132 tp
= tcp_drop(tp
, ECONNRESET
);
4133 rstreason
= BANDLIM_UNLIMITED
;
4134 postevent(so
, 0, EV_RESET
);
4135 IF_TCP_STATINC(ifp
, synwindow
);
4141 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
4142 * flag is on (half-synchronized state), then queue data for
4143 * later processing; else drop segment and return.
4145 if ((thflags
& TH_ACK
) == 0) {
4146 if (tp
->t_state
== TCPS_SYN_RECEIVED
||
4147 (tp
->t_flags
& TF_NEEDSYN
)) {
4148 if ((tfo_enabled(tp
))) {
4150 * So, we received a valid segment while in
4151 * SYN-RECEIVED (TF_NEEDSYN is actually never
4152 * set, so this is dead code).
4153 * As this cannot be an RST (see that if a bit
4154 * higher), and it does not have the ACK-flag
4155 * set, we want to retransmit the SYN/ACK.
4156 * Thus, we have to reset snd_nxt to snd_una to
4157 * trigger the going back to sending of the
4158 * SYN/ACK. This is more consistent with the
4159 * behavior of tcp_output(), which expects
4160 * to send the segment that is pointed to by
4163 tp
->snd_nxt
= tp
->snd_una
;
4166 * We need to make absolutely sure that we are
4167 * going to reply upon a duplicate SYN-segment.
4169 if (th
->th_flags
& TH_SYN
) {
4175 } else if (tp
->t_flags
& TF_ACKNOW
) {
4186 switch (tp
->t_state
) {
4188 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
4189 * ESTABLISHED state and continue processing.
4190 * The ACK was checked above.
4192 case TCPS_SYN_RECEIVED
:
4194 tcpstat
.tcps_connects
++;
4196 /* Do window scaling? */
4197 if (TCP_WINDOW_SCALE_ENABLED(tp
)) {
4198 tp
->snd_scale
= tp
->requested_s_scale
;
4199 tp
->rcv_scale
= tp
->request_r_scale
;
4200 tp
->snd_wnd
= th
->th_win
<< tp
->snd_scale
;
4201 tp
->max_sndwnd
= tp
->snd_wnd
;
4202 tiwin
= tp
->snd_wnd
;
4206 * SYN-RECEIVED -> ESTABLISHED
4207 * SYN-RECEIVED* -> FIN-WAIT-1
4209 tp
->t_starttime
= tcp_now
;
4210 tcp_sbrcv_tstmp_check(tp
);
4211 if (tp
->t_flags
& TF_NEEDFIN
) {
4212 DTRACE_TCP4(state__change
, void, NULL
,
4213 struct inpcb
*, inp
,
4214 struct tcpcb
*, tp
, int32_t, TCPS_FIN_WAIT_1
);
4215 tp
->t_state
= TCPS_FIN_WAIT_1
;
4216 tp
->t_flags
&= ~TF_NEEDFIN
;
4218 DTRACE_TCP4(state__change
, void, NULL
,
4219 struct inpcb
*, inp
,
4220 struct tcpcb
*, tp
, int32_t, TCPS_ESTABLISHED
);
4221 tp
->t_state
= TCPS_ESTABLISHED
;
4222 tp
->t_timer
[TCPT_KEEP
] = OFFSET_FROM_START(tp
,
4223 TCP_CONN_KEEPIDLE(tp
));
4224 if (nstat_collect
) {
4225 nstat_route_connect_success(
4226 tp
->t_inpcb
->inp_route
.ro_rt
);
4229 * The SYN is acknowledged but una is not updated
4230 * yet. So pass the value of ack to compute
4231 * sndbytes correctly
4233 inp_count_sndbytes(inp
, th
->th_ack
);
4236 * If segment contains data or ACK, will call tcp_reass()
4237 * later; if not, do so now to pass queued data to user.
4239 if (tlen
== 0 && (thflags
& TH_FIN
) == 0) {
4240 (void) tcp_reass(tp
, (struct tcphdr
*)0, &tlen
,
4243 tp
->snd_wl1
= th
->th_seq
- 1;
4247 * Do not send the connect notification for additional subflows
4248 * until ACK for 3-way handshake arrives.
4250 if ((!(tp
->t_mpflags
& TMPF_MPTCP_TRUE
)) &&
4251 (tp
->t_mpflags
& TMPF_SENT_JOIN
)) {
4252 isconnected
= FALSE
;
4256 if ((tp
->t_tfo_flags
& TFO_F_COOKIE_VALID
)) {
4257 /* Done this when receiving the SYN */
4258 isconnected
= FALSE
;
4260 OSDecrementAtomic(&tcp_tfo_halfcnt
);
4262 /* Panic if something has gone terribly wrong. */
4263 VERIFY(tcp_tfo_halfcnt
>= 0);
4265 tp
->t_tfo_flags
&= ~TFO_F_COOKIE_VALID
;
4269 * In case there is data in the send-queue (e.g., TFO is being
4270 * used, or connectx+data has been done), then if we would
4271 * "FALLTHROUGH", we would handle this ACK as if data has been
4272 * acknowledged. But, we have to prevent this. And this
4273 * can be prevented by increasing snd_una by 1, so that the
4274 * SYN is not considered as data (snd_una++ is actually also
4275 * done in SYN_SENT-state as part of the regular TCP stack).
4277 * In case there is data on this ack as well, the data will be
4278 * handled by the label "dodata" right after step6.
4280 if (so
->so_snd
.sb_cc
) {
4281 tp
->snd_una
++; /* SYN is acked */
4282 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
)) {
4283 tp
->snd_nxt
= tp
->snd_una
;
4287 * No duplicate-ACK handling is needed. So, we
4288 * directly advance to processing the ACK (aka,
4289 * updating the RTT estimation,...)
4291 * But, we first need to handle eventual SACKs,
4292 * because TFO will start sending data with the
4293 * SYN/ACK, so it might be that the client
4294 * includes a SACK with its ACK.
4296 if (SACK_ENABLED(tp
) &&
4297 (to
.to_nsacks
> 0 ||
4298 !TAILQ_EMPTY(&tp
->snd_holes
))) {
4299 tcp_sack_doack(tp
, &to
, th
,
4309 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
4310 * ACKs. If the ack is in the range
4311 * tp->snd_una < th->th_ack <= tp->snd_max
4312 * then advance tp->snd_una to th->th_ack and drop
4313 * data from the retransmission queue. If this ACK reflects
4314 * more up to date window information we update our window information.
4316 case TCPS_ESTABLISHED
:
4317 case TCPS_FIN_WAIT_1
:
4318 case TCPS_FIN_WAIT_2
:
4319 case TCPS_CLOSE_WAIT
:
4322 case TCPS_TIME_WAIT
:
4323 if (SEQ_GT(th
->th_ack
, tp
->snd_max
)) {
4324 tcpstat
.tcps_rcvacktoomuch
++;
4325 if (tcp_do_rfc5961
&& tcp_is_ack_ratelimited(tp
)) {
4331 if (tcp_do_rfc5961
&& SEQ_LT(th
->th_ack
, tp
->snd_una
- tp
->max_sndwnd
)) {
4332 if (tcp_is_ack_ratelimited(tp
)) {
4338 if (SACK_ENABLED(tp
) && to
.to_nsacks
> 0) {
4339 recvd_dsack
= tcp_sack_process_dsack(tp
, &to
, th
);
4341 * If DSACK is received and this packet has no
4342 * other SACK information, it can be dropped.
4343 * We do not want to treat it as a duplicate ack.
4346 SEQ_LEQ(th
->th_ack
, tp
->snd_una
) &&
4347 to
.to_nsacks
== 0) {
4348 tcp_bad_rexmt_check(tp
, th
, &to
);
4353 if (SACK_ENABLED(tp
) &&
4354 (to
.to_nsacks
> 0 || !TAILQ_EMPTY(&tp
->snd_holes
))) {
4355 tcp_sack_doack(tp
, &to
, th
, &sack_bytes_acked
);
4359 if (tp
->t_mpuna
&& SEQ_GEQ(th
->th_ack
, tp
->t_mpuna
)) {
4360 if (tp
->t_mpflags
& TMPF_PREESTABLISHED
) {
4361 /* MP TCP establishment succeeded */
4363 if (tp
->t_mpflags
& TMPF_JOINED_FLOW
) {
4364 if (tp
->t_mpflags
& TMPF_SENT_JOIN
) {
4366 ~TMPF_PREESTABLISHED
;
4369 mptcplog((LOG_DEBUG
, "MPTCP "
4370 "Sockets: %s \n", __func__
),
4374 tp
->t_timer
[TCPT_JACK_RXMT
] = 0;
4375 tp
->t_mprxtshift
= 0;
4378 isconnected
= FALSE
;
4387 tcp_tfo_rcv_ack(tp
, th
);
4390 * If we have outstanding data (other than
4391 * a window probe), this is a completely
4392 * duplicate ack and the ack is the biggest we've seen.
4394 * Need to accommodate a change in window on duplicate acks
4395 * to allow operating systems that update window during
4396 * recovery with SACK
4398 if (SEQ_LEQ(th
->th_ack
, tp
->snd_una
)) {
4399 if (tlen
== 0 && (tiwin
== tp
->snd_wnd
||
4400 (to
.to_nsacks
> 0 && sack_bytes_acked
> 0))) {
4402 * If both ends send FIN at the same time,
4403 * then the ack will be a duplicate ack
4404 * but we have to process the FIN. Check
4405 * for this condition and process the FIN
4406 * instead of the dupack
4408 if ((thflags
& TH_FIN
) &&
4409 !TCPS_HAVERCVDFIN(tp
->t_state
)) {
4415 * MPTCP options that are ignored must
4416 * not be treated as duplicate ACKs.
4418 if (to
.to_flags
& TOF_MPTCP
) {
4422 if ((isconnected
) && (tp
->t_mpflags
& TMPF_JOINED_FLOW
)) {
4423 mptcplog((LOG_DEBUG
, "MPTCP "
4424 "Sockets: bypass ack recovery\n"),
4426 MPTCP_LOGLVL_VERBOSE
);
4431 * If a duplicate acknowledgement was seen
4432 * after ECN, it indicates packet loss in
4433 * addition to ECN. Reset INRECOVERY flag
4434 * so that we can process partial acks
4437 if (tp
->ecn_flags
& TE_INRECOVERY
) {
4438 tp
->ecn_flags
&= ~TE_INRECOVERY
;
4441 tcpstat
.tcps_rcvdupack
++;
4445 * Check if we need to reset the limit on
4448 if (tp
->t_early_rexmt_count
> 0 &&
4450 (tp
->t_early_rexmt_win
+
4451 TCP_EARLY_REXMT_WIN
))) {
4452 tp
->t_early_rexmt_count
= 0;
4456 * Is early retransmit needed? We check for
4457 * this when the connection is waiting for
4458 * duplicate acks to enter fast recovery.
4460 if (!IN_FASTRECOVERY(tp
)) {
4461 tcp_early_rexmt_check(tp
, th
);
4465 * If we've seen exactly rexmt threshold
4466 * of duplicate acks, assume a packet
4467 * has been dropped and retransmit it.
4468 * Kludge snd_nxt & the congestion
4469 * window so we send only this one
4472 * We know we're losing at the current
4473 * window size so do congestion avoidance
4474 * (set ssthresh to half the current window
4475 * and pull our congestion window back to
4476 * the new ssthresh).
4478 * Dup acks mean that packets have left the
4479 * network (they're now cached at the receiver)
4480 * so bump cwnd by the amount in the receiver
4481 * to keep a constant cwnd packets in the
4484 if (tp
->t_timer
[TCPT_REXMT
] == 0 ||
4485 (th
->th_ack
!= tp
->snd_una
4486 && sack_bytes_acked
== 0)) {
4488 tp
->t_rexmtthresh
= tcprexmtthresh
;
4489 } else if (tp
->t_dupacks
> tp
->t_rexmtthresh
||
4490 IN_FASTRECOVERY(tp
)) {
4492 * If this connection was seeing packet
4493 * reordering, then recovery might be
4494 * delayed to disambiguate between
4495 * reordering and loss
4497 if (SACK_ENABLED(tp
) && !IN_FASTRECOVERY(tp
) &&
4499 (TF_PKTS_REORDERED
| TF_DELAY_RECOVERY
)) ==
4500 (TF_PKTS_REORDERED
| TF_DELAY_RECOVERY
)) {
4502 * Since the SACK information is already
4503 * updated, this ACK will be dropped
4508 if (SACK_ENABLED(tp
)
4509 && IN_FASTRECOVERY(tp
)) {
4513 * Compute the amount of data in flight first.
4514 * We can inject new data into the pipe iff
4515 * we have less than 1/2 the original window's
4516 * worth of data in flight.
4518 awnd
= (tp
->snd_nxt
- tp
->snd_fack
) +
4519 tp
->sackhint
.sack_bytes_rexmit
;
4520 if (awnd
< tp
->snd_ssthresh
) {
4521 tp
->snd_cwnd
+= tp
->t_maxseg
;
4522 if (tp
->snd_cwnd
> tp
->snd_ssthresh
) {
4523 tp
->snd_cwnd
= tp
->snd_ssthresh
;
4527 tp
->snd_cwnd
+= tp
->t_maxseg
;
4530 /* Process any window updates */
4531 if (tiwin
> tp
->snd_wnd
) {
4532 tcp_update_window(tp
, thflags
,
4535 tcp_ccdbg_trace(tp
, th
,
4536 TCP_CC_IN_FASTRECOVERY
);
4538 (void) tcp_output(tp
);
4541 } else if (tp
->t_dupacks
== tp
->t_rexmtthresh
) {
4542 tcp_seq onxt
= tp
->snd_nxt
;
4545 * If we're doing sack, check to
4546 * see if we're already in sack
4547 * recovery. If we're not doing sack,
4548 * check to see if we're in newreno
4551 if (SACK_ENABLED(tp
)) {
4552 if (IN_FASTRECOVERY(tp
)) {
4555 } else if (tp
->t_flagsext
& TF_DELAY_RECOVERY
) {
4559 if (SEQ_LEQ(th
->th_ack
,
4565 if (tp
->t_flags
& TF_SENTFIN
) {
4566 tp
->snd_recover
= tp
->snd_max
- 1;
4568 tp
->snd_recover
= tp
->snd_max
;
4570 tp
->t_timer
[TCPT_PTO
] = 0;
4574 * If the connection has seen pkt
4575 * reordering, delay recovery until
4576 * it is clear that the packet
4579 if (SACK_ENABLED(tp
) &&
4581 (TF_PKTS_REORDERED
| TF_DELAY_RECOVERY
))
4582 == TF_PKTS_REORDERED
&&
4583 !IN_FASTRECOVERY(tp
) &&
4584 tp
->t_reorderwin
> 0 &&
4585 (tp
->t_state
== TCPS_ESTABLISHED
||
4586 tp
->t_state
== TCPS_FIN_WAIT_1
)) {
4587 tp
->t_timer
[TCPT_DELAYFR
] =
4588 OFFSET_FROM_START(tp
,
4590 tp
->t_flagsext
|= TF_DELAY_RECOVERY
;
4591 tcpstat
.tcps_delay_recovery
++;
4592 tcp_ccdbg_trace(tp
, th
,
4593 TCP_CC_DELAY_FASTRECOVERY
);
4597 tcp_rexmt_save_state(tp
);
4599 * If the current tcp cc module has
4600 * defined a hook for tasks to run
4601 * before entering FR, call it
4603 if (CC_ALGO(tp
)->pre_fr
!= NULL
) {
4604 CC_ALGO(tp
)->pre_fr(tp
);
4606 ENTER_FASTRECOVERY(tp
);
4607 tp
->t_timer
[TCPT_REXMT
] = 0;
4608 if (TCP_ECN_ENABLED(tp
)) {
4609 tp
->ecn_flags
|= TE_SENDCWR
;
4612 if (SACK_ENABLED(tp
)) {
4613 tcpstat
.tcps_sack_recovery_episode
++;
4614 tp
->t_sack_recovery_episode
++;
4615 tp
->sack_newdata
= tp
->snd_nxt
;
4616 tp
->snd_cwnd
= tp
->t_maxseg
;
4618 ~TF_CWND_NONVALIDATED
;
4620 /* Process any window updates */
4621 if (tiwin
> tp
->snd_wnd
) {
4627 tcp_ccdbg_trace(tp
, th
,
4628 TCP_CC_ENTER_FASTRECOVERY
);
4629 (void) tcp_output(tp
);
4632 tp
->snd_nxt
= th
->th_ack
;
4633 tp
->snd_cwnd
= tp
->t_maxseg
;
4635 /* Process any window updates */
4636 if (tiwin
> tp
->snd_wnd
) {
4637 tcp_update_window(tp
,
4642 (void) tcp_output(tp
);
4643 if (tp
->t_flagsext
& TF_CWND_NONVALIDATED
) {
4644 tcp_cc_adjust_nonvalidated_cwnd(tp
);
4646 tp
->snd_cwnd
= tp
->snd_ssthresh
+
4647 tp
->t_maxseg
* tp
->t_dupacks
;
4649 if (SEQ_GT(onxt
, tp
->snd_nxt
)) {
4653 tcp_ccdbg_trace(tp
, th
,
4654 TCP_CC_ENTER_FASTRECOVERY
);
4656 } else if (limited_txmt
&&
4657 ALLOW_LIMITED_TRANSMIT(tp
) &&
4658 (!(SACK_ENABLED(tp
)) || sack_bytes_acked
> 0) &&
4659 (so
->so_snd
.sb_cc
- (tp
->snd_max
- tp
->snd_una
)) > 0) {
4660 u_int32_t incr
= (tp
->t_maxseg
* tp
->t_dupacks
);
4662 /* Use Limited Transmit algorithm on the first two
4663 * duplicate acks when there is new data to transmit
4665 tp
->snd_cwnd
+= incr
;
4666 tcpstat
.tcps_limited_txt
++;
4667 (void) tcp_output(tp
);
4669 tcp_ccdbg_trace(tp
, th
, TCP_CC_LIMITED_TRANSMIT
);
4671 /* Reset snd_cwnd back to normal */
4672 tp
->snd_cwnd
-= incr
;
4678 * If the congestion window was inflated to account
4679 * for the other side's cached packets, retract it.
4681 if (IN_FASTRECOVERY(tp
)) {
4682 if (SEQ_LT(th
->th_ack
, tp
->snd_recover
)) {
4684 * If we received an ECE and entered
4685 * recovery, the subsequent ACKs should
4686 * not be treated as partial acks.
4688 if (tp
->ecn_flags
& TE_INRECOVERY
) {
4692 if (SACK_ENABLED(tp
)) {
4693 tcp_sack_partialack(tp
, th
);
4695 tcp_newreno_partial_ack(tp
, th
);
4697 tcp_ccdbg_trace(tp
, th
, TCP_CC_PARTIAL_ACK
);
4699 EXIT_FASTRECOVERY(tp
);
4700 if (CC_ALGO(tp
)->post_fr
!= NULL
) {
4701 CC_ALGO(tp
)->post_fr(tp
, th
);
4704 tcp_clear_pipeack_state(tp
);
4705 tcp_ccdbg_trace(tp
, th
,
4706 TCP_CC_EXIT_FASTRECOVERY
);
4708 } else if ((tp
->t_flagsext
&
4709 (TF_PKTS_REORDERED
| TF_DELAY_RECOVERY
))
4710 == (TF_PKTS_REORDERED
| TF_DELAY_RECOVERY
)) {
4712 * If the ack acknowledges upto snd_recover or if
4713 * it acknowledges all the snd holes, exit
4714 * recovery and cancel the timer. Otherwise,
4715 * this is a partial ack. Wait for recovery timer
4716 * to enter recovery. The snd_holes have already
4719 if (SEQ_GEQ(th
->th_ack
, tp
->snd_recover
) ||
4720 TAILQ_EMPTY(&tp
->snd_holes
)) {
4721 tp
->t_timer
[TCPT_DELAYFR
] = 0;
4722 tp
->t_flagsext
&= ~TF_DELAY_RECOVERY
;
4723 EXIT_FASTRECOVERY(tp
);
4724 tcp_ccdbg_trace(tp
, th
,
4725 TCP_CC_EXIT_FASTRECOVERY
);
4729 * We were not in fast recovery. Reset the
4730 * duplicate ack counter.
4733 tp
->t_rexmtthresh
= tcprexmtthresh
;
4738 * If we reach this point, ACK is not a duplicate,
4739 * i.e., it ACKs something we sent.
4741 if (tp
->t_flags
& TF_NEEDSYN
) {
4743 * T/TCP: Connection was half-synchronized, and our
4744 * SYN has been ACK'd (so connection is now fully
4745 * synchronized). Go to non-starred state,
4746 * increment snd_una for ACK of SYN, and check if
4747 * we can do window scaling.
4749 tp
->t_flags
&= ~TF_NEEDSYN
;
4751 /* Do window scaling? */
4752 if (TCP_WINDOW_SCALE_ENABLED(tp
)) {
4753 tp
->snd_scale
= tp
->requested_s_scale
;
4754 tp
->rcv_scale
= tp
->request_r_scale
;
4759 VERIFY(SEQ_GEQ(th
->th_ack
, tp
->snd_una
));
4760 acked
= BYTES_ACKED(th
, tp
);
4761 tcpstat
.tcps_rcvackpack
++;
4762 tcpstat
.tcps_rcvackbyte
+= acked
;
4765 * If the last packet was a retransmit, make sure
4766 * it was not spurious.
4768 * This will also take care of congestion window
4769 * adjustment if a last packet was recovered due to a
4772 tcp_bad_rexmt_check(tp
, th
, &to
);
4774 /* Recalculate the RTT */
4775 tcp_compute_rtt(tp
, &to
, th
);
4778 * If all outstanding data is acked, stop retransmit
4779 * timer and remember to restart (more output or persist).
4780 * If there is more data to be acked, restart retransmit
4781 * timer, using current (possibly backed-off) value.
4783 TCP_RESET_REXMT_STATE(tp
);
4784 TCPT_RANGESET(tp
->t_rxtcur
, TCP_REXMTVAL(tp
),
4785 tp
->t_rttmin
, TCPTV_REXMTMAX
,
4786 TCP_ADD_REXMTSLOP(tp
));
4787 if (th
->th_ack
== tp
->snd_max
) {
4788 tp
->t_timer
[TCPT_REXMT
] = 0;
4789 tp
->t_timer
[TCPT_PTO
] = 0;
4791 } else if (tp
->t_timer
[TCPT_PERSIST
] == 0) {
4792 tp
->t_timer
[TCPT_REXMT
] = OFFSET_FROM_START(tp
,
4797 * If no data (only SYN) was ACK'd, skip rest of ACK
4805 * When outgoing data has been acked (except the SYN+data), we
4806 * mark this connection as "sending good" for TFO.
4808 if ((tp
->t_tfo_stats
& TFO_S_SYN_DATA_SENT
) &&
4809 !(tp
->t_tfo_flags
& TFO_F_NO_SNDPROBING
) &&
4810 !(th
->th_flags
& TH_SYN
)) {
4811 tp
->t_tfo_flags
|= TFO_F_NO_SNDPROBING
;
4815 * If TH_ECE is received, make sure that ECN is enabled
4816 * on that connection and we have sent ECT on data packets.
4818 if ((thflags
& TH_ECE
) != 0 && TCP_ECN_ENABLED(tp
) &&
4819 (tp
->ecn_flags
& TE_SENDIPECT
)) {
4821 * Reduce the congestion window if we haven't
4824 if (!IN_FASTRECOVERY(tp
)) {
4825 tcp_reduce_congestion_window(tp
);
4826 tp
->ecn_flags
|= (TE_INRECOVERY
| TE_SENDCWR
);
4828 * Also note that the connection received
4831 tp
->ecn_flags
|= TE_RECV_ECN_ECE
;
4832 INP_INC_IFNET_STAT(inp
, ecn_recv_ece
);
4833 tcpstat
.tcps_ecn_recv_ece
++;
4834 tcp_ccdbg_trace(tp
, th
, TCP_CC_ECN_RCVD
);
4839 * When new data is acked, open the congestion window.
4840 * The specifics of how this is achieved are up to the
4841 * congestion control algorithm in use for this connection.
4843 * The calculations in this function assume that snd_una is
4846 if (!IN_FASTRECOVERY(tp
)) {
4847 if (CC_ALGO(tp
)->ack_rcvd
!= NULL
) {
4848 CC_ALGO(tp
)->ack_rcvd(tp
, th
);
4850 tcp_ccdbg_trace(tp
, th
, TCP_CC_ACK_RCVD
);
4852 if (acked
> so
->so_snd
.sb_cc
) {
4853 tp
->snd_wnd
-= so
->so_snd
.sb_cc
;
4854 sbdrop(&so
->so_snd
, (int)so
->so_snd
.sb_cc
);
4855 if (so
->so_flags
& SOF_ENABLE_MSGS
) {
4856 so
->so_msg_state
->msg_serial_bytes
-=
4857 (int)so
->so_snd
.sb_cc
;
4861 sbdrop(&so
->so_snd
, acked
);
4862 if (so
->so_flags
& SOF_ENABLE_MSGS
) {
4863 so
->so_msg_state
->msg_serial_bytes
-=
4866 tcp_sbsnd_trim(&so
->so_snd
);
4867 tp
->snd_wnd
-= acked
;
4870 /* detect una wraparound */
4871 if (!IN_FASTRECOVERY(tp
) &&
4872 SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
4873 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
)) {
4874 tp
->snd_recover
= th
->th_ack
- 1;
4877 if (IN_FASTRECOVERY(tp
) &&
4878 SEQ_GEQ(th
->th_ack
, tp
->snd_recover
)) {
4879 EXIT_FASTRECOVERY(tp
);
4882 tp
->snd_una
= th
->th_ack
;
4884 if (SACK_ENABLED(tp
)) {
4885 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
)) {
4886 tp
->snd_recover
= tp
->snd_una
;
4889 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
)) {
4890 tp
->snd_nxt
= tp
->snd_una
;
4892 if (!SLIST_EMPTY(&tp
->t_rxt_segments
) &&
4893 !TCP_DSACK_SEQ_IN_WINDOW(tp
, tp
->t_dsack_lastuna
,
4895 tcp_rxtseg_clean(tp
);
4897 if ((tp
->t_flagsext
& TF_MEASURESNDBW
) != 0 &&
4898 tp
->t_bwmeas
!= NULL
) {
4899 tcp_bwmeas_check(tp
);
4903 * sowwakeup must happen after snd_una, et al. are
4904 * updated so that the sequence numbers are in sync with
4909 if (!SLIST_EMPTY(&tp
->t_notify_ack
)) {
4910 tcp_notify_acknowledgement(tp
, so
);
4913 switch (tp
->t_state
) {
4915 * In FIN_WAIT_1 STATE in addition to the processing
4916 * for the ESTABLISHED state if our FIN is now acknowledged
4917 * then enter FIN_WAIT_2.
4919 case TCPS_FIN_WAIT_1
:
4920 if (ourfinisacked
) {
4922 * If we can't receive any more
4923 * data, then closing user can proceed.
4924 * Starting the TCPT_2MSL timer is contrary to the
4925 * specification, but if we don't get a FIN
4926 * we'll hang forever.
4928 if (so
->so_state
& SS_CANTRCVMORE
) {
4929 tp
->t_timer
[TCPT_2MSL
] = OFFSET_FROM_START(tp
,
4930 TCP_CONN_MAXIDLE(tp
));
4931 isconnected
= FALSE
;
4932 isdisconnected
= TRUE
;
4934 DTRACE_TCP4(state__change
, void, NULL
,
4935 struct inpcb
*, inp
,
4937 int32_t, TCPS_FIN_WAIT_2
);
4938 tp
->t_state
= TCPS_FIN_WAIT_2
;
4939 /* fall through and make sure we also recognize
4940 * data ACKed with the FIN
4946 * In CLOSING STATE in addition to the processing for
4947 * the ESTABLISHED state if the ACK acknowledges our FIN
4948 * then enter the TIME-WAIT state, otherwise ignore
4952 if (ourfinisacked
) {
4953 DTRACE_TCP4(state__change
, void, NULL
,
4954 struct inpcb
*, inp
,
4956 int32_t, TCPS_TIME_WAIT
);
4957 tp
->t_state
= TCPS_TIME_WAIT
;
4958 tcp_canceltimers(tp
);
4959 if (tp
->t_flagsext
& TF_NOTIMEWAIT
) {
4960 tp
->t_flags
|= TF_CLOSING
;
4962 add_to_time_wait(tp
, 2 * tcp_msl
);
4964 isconnected
= FALSE
;
4965 isdisconnected
= TRUE
;
4970 * In LAST_ACK, we may still be waiting for data to drain
4971 * and/or to be acked, as well as for the ack of our FIN.
4972 * If our FIN is now acknowledged, delete the TCB,
4973 * enter the closed state and return.
4976 if (ourfinisacked
) {
4983 * In TIME_WAIT state the only thing that should arrive
4984 * is a retransmission of the remote FIN. Acknowledge
4985 * it and restart the finack timer.
4987 case TCPS_TIME_WAIT
:
4988 add_to_time_wait(tp
, 2 * tcp_msl
);
4993 * If there is a SACK option on the ACK and we
4994 * haven't seen any duplicate acks before, count
4995 * it as a duplicate ack even if the cumulative
4996 * ack is advanced. If the receiver delayed an
4997 * ack and detected loss afterwards, then the ack
4998 * will advance cumulative ack and will also have
4999 * a SACK option. So counting it as one duplicate
5002 if (sack_ackadv
== 1 &&
5003 tp
->t_state
== TCPS_ESTABLISHED
&&
5004 SACK_ENABLED(tp
) && sack_bytes_acked
> 0 &&
5005 to
.to_nsacks
> 0 && tp
->t_dupacks
== 0 &&
5006 SEQ_LEQ(th
->th_ack
, tp
->snd_una
) && tlen
== 0 &&
5007 !(tp
->t_flagsext
& TF_PKTS_REORDERED
)) {
5008 tcpstat
.tcps_sack_ackadv
++;
5009 goto process_dupack
;
5015 * Update window information.
5017 if (tcp_update_window(tp
, thflags
, th
, tiwin
, tlen
)) {
5022 * Process segments with URG.
5024 if ((thflags
& TH_URG
) && th
->th_urp
&&
5025 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
5027 * This is a kludge, but if we receive and accept
5028 * random urgent pointers, we'll crash in
5029 * soreceive. It's hard to imagine someone
5030 * actually wanting to send this much urgent data.
5032 if (th
->th_urp
+ so
->so_rcv
.sb_cc
> sb_max
) {
5033 th
->th_urp
= 0; /* XXX */
5034 thflags
&= ~TH_URG
; /* XXX */
5035 goto dodata
; /* XXX */
5038 * If this segment advances the known urgent pointer,
5039 * then mark the data stream. This should not happen
5040 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
5041 * a FIN has been received from the remote side.
5042 * In these states we ignore the URG.
5044 * According to RFC961 (Assigned Protocols),
5045 * the urgent pointer points to the last octet
5046 * of urgent data. We continue, however,
5047 * to consider it to indicate the first octet
5048 * of data past the urgent section as the original
5049 * spec states (in one of two places).
5051 if (SEQ_GT(th
->th_seq
+ th
->th_urp
, tp
->rcv_up
)) {
5052 tp
->rcv_up
= th
->th_seq
+ th
->th_urp
;
5053 so
->so_oobmark
= so
->so_rcv
.sb_cc
+
5054 (tp
->rcv_up
- tp
->rcv_nxt
) - 1;
5055 if (so
->so_oobmark
== 0) {
5056 so
->so_state
|= SS_RCVATMARK
;
5057 postevent(so
, 0, EV_OOB
);
5060 tp
->t_oobflags
&= ~(TCPOOB_HAVEDATA
| TCPOOB_HADDATA
);
5063 * Remove out of band data so doesn't get presented to user.
5064 * This can happen independent of advancing the URG pointer,
5065 * but if two URG's are pending at once, some out-of-band
5066 * data may creep in... ick.
5068 if (th
->th_urp
<= (u_int32_t
)tlen
5070 && (so
->so_options
& SO_OOBINLINE
) == 0
5073 tcp_pulloutofband(so
, th
, m
,
5074 drop_hdrlen
); /* hdr drop is delayed */
5078 * If no out of band data is expected,
5079 * pull receive urgent pointer along
5080 * with the receive window.
5082 if (SEQ_GT(tp
->rcv_nxt
, tp
->rcv_up
)) {
5083 tp
->rcv_up
= tp
->rcv_nxt
;
5088 /* Set socket's connect or disconnect state correcly before doing data.
5089 * The following might unlock the socket if there is an upcall or a socket
5094 } else if (isdisconnected
) {
5095 soisdisconnected(so
);
5098 /* Let's check the state of pcb just to make sure that it did not get closed
5099 * when we unlocked above
5101 if (inp
->inp_state
== INPCB_STATE_DEAD
) {
5102 /* Just drop the packet that we are processing and return */
5107 * Process the segment text, merging it into the TCP sequencing queue,
5108 * and arranging for acknowledgment of receipt if necessary.
5109 * This process logically involves adjusting tp->rcv_wnd as data
5110 * is presented to the user (this happens in tcp_usrreq.c,
5111 * case PRU_RCVD). If a FIN has already been received on this
5112 * connection then we just ignore the text.
5114 * If we are in SYN-received state and got a valid TFO cookie, we want
5115 * to process the data.
5117 if ((tlen
|| (thflags
& TH_FIN
)) &&
5118 TCPS_HAVERCVDFIN(tp
->t_state
) == 0 &&
5119 (TCPS_HAVEESTABLISHED(tp
->t_state
) ||
5120 (tp
->t_state
== TCPS_SYN_RECEIVED
&&
5121 (tp
->t_tfo_flags
& TFO_F_COOKIE_VALID
)))) {
5122 tcp_seq save_start
= th
->th_seq
;
5123 tcp_seq save_end
= th
->th_seq
+ tlen
;
5124 m_adj(m
, drop_hdrlen
); /* delayed header drop */
5126 * Insert segment which includes th into TCP reassembly queue
5127 * with control block tp. Set thflags to whether reassembly now
5128 * includes a segment with FIN. This handles the common case
5129 * inline (segment is the next to be received on an established
5130 * connection, and the queue is empty), avoiding linkage into
5131 * and removal from the queue and repetition of various
5133 * Set DELACK for segments received in order, but ack
5134 * immediately when segments are out of order (so
5135 * fast retransmit can work).
5137 if (th
->th_seq
== tp
->rcv_nxt
&& LIST_EMPTY(&tp
->t_segq
)) {
5138 TCP_INC_VAR(tp
->t_unacksegs
, nlropkts
);
5140 * Calculate the RTT on the receiver only if the
5141 * connection is in streaming mode and the last
5142 * packet was not an end-of-write
5144 if (tp
->t_flags
& TF_STREAMING_ON
) {
5145 tcp_compute_rtt(tp
, &to
, th
);
5148 if (DELAY_ACK(tp
, th
) &&
5149 ((tp
->t_flags
& TF_ACKNOW
) == 0)) {
5150 if ((tp
->t_flags
& TF_DELACK
) == 0) {
5151 tp
->t_flags
|= TF_DELACK
;
5152 tp
->t_timer
[TCPT_DELACK
] =
5153 OFFSET_FROM_START(tp
, tcp_delack
);
5156 tp
->t_flags
|= TF_ACKNOW
;
5158 tp
->rcv_nxt
+= tlen
;
5159 thflags
= th
->th_flags
& TH_FIN
;
5160 TCP_INC_VAR(tcpstat
.tcps_rcvpack
, nlropkts
);
5161 tcpstat
.tcps_rcvbyte
+= tlen
;
5162 if (nstat_collect
) {
5163 if (m
->m_pkthdr
.pkt_flags
& PKTF_SW_LRO_PKT
) {
5164 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
5165 rxpackets
, m
->m_pkthdr
.lro_npkts
);
5167 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
5170 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
5172 inp_set_activity_bitmap(inp
);
5174 tcp_sbrcv_grow(tp
, &so
->so_rcv
, &to
, tlen
,
5175 TCP_AUTORCVBUF_MAX(ifp
));
5176 so_recv_data_stat(so
, m
, drop_hdrlen
);
5178 if (sbappendstream_rcvdemux(so
, m
,
5179 th
->th_seq
- (tp
->irs
+ 1), 0)) {
5183 thflags
= tcp_reass(tp
, th
, &tlen
, m
, ifp
);
5184 tp
->t_flags
|= TF_ACKNOW
;
5187 if ((tlen
> 0 || (th
->th_flags
& TH_FIN
)) && SACK_ENABLED(tp
)) {
5188 if (th
->th_flags
& TH_FIN
) {
5191 tcp_update_sack_list(tp
, save_start
, save_end
);
5194 tcp_adaptive_rwtimo_check(tp
, tlen
);
5197 tcp_tfo_rcv_data(tp
);
5200 if (tp
->t_flags
& TF_DELACK
) {
5203 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
5204 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
5205 th
->th_seq
, th
->th_ack
, th
->th_win
);
5209 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
5210 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
5211 th
->th_seq
, th
->th_ack
, th
->th_win
);
5215 if ((so
->so_flags
& SOF_MP_SUBFLOW
) && tlen
== 0 &&
5216 (m
->m_pkthdr
.pkt_flags
& PKTF_MPTCP_DFIN
) &&
5217 (m
->m_pkthdr
.pkt_flags
& PKTF_MPTCP
)) {
5218 m_adj(m
, drop_hdrlen
); /* delayed header drop */
5219 mptcp_input(tptomptp(tp
)->mpt_mpte
, m
);
5220 tp
->t_flags
|= TF_ACKNOW
;
5228 * If FIN is received ACK the FIN and let the user know
5229 * that the connection is closing.
5231 if (thflags
& TH_FIN
) {
5232 if (TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
5234 postevent(so
, 0, EV_FIN
);
5236 * If connection is half-synchronized
5237 * (ie NEEDSYN flag on) then delay ACK,
5238 * so it may be piggybacked when SYN is sent.
5239 * Otherwise, since we received a FIN then no
5240 * more input can be expected, send ACK now.
5242 TCP_INC_VAR(tp
->t_unacksegs
, nlropkts
);
5243 if (DELAY_ACK(tp
, th
) && (tp
->t_flags
& TF_NEEDSYN
)) {
5244 if ((tp
->t_flags
& TF_DELACK
) == 0) {
5245 tp
->t_flags
|= TF_DELACK
;
5246 tp
->t_timer
[TCPT_DELACK
] = OFFSET_FROM_START(tp
, tcp_delack
);
5249 tp
->t_flags
|= TF_ACKNOW
;
5253 switch (tp
->t_state
) {
5255 * In SYN_RECEIVED and ESTABLISHED STATES
5256 * enter the CLOSE_WAIT state.
5258 case TCPS_SYN_RECEIVED
:
5259 tp
->t_starttime
= tcp_now
;
5260 case TCPS_ESTABLISHED
:
5261 DTRACE_TCP4(state__change
, void, NULL
, struct inpcb
*, inp
,
5262 struct tcpcb
*, tp
, int32_t, TCPS_CLOSE_WAIT
);
5263 tp
->t_state
= TCPS_CLOSE_WAIT
;
5267 * If still in FIN_WAIT_1 STATE FIN has not been acked so
5268 * enter the CLOSING state.
5270 case TCPS_FIN_WAIT_1
:
5271 DTRACE_TCP4(state__change
, void, NULL
, struct inpcb
*, inp
,
5272 struct tcpcb
*, tp
, int32_t, TCPS_CLOSING
);
5273 tp
->t_state
= TCPS_CLOSING
;
5277 * In FIN_WAIT_2 state enter the TIME_WAIT state,
5278 * starting the time-wait timer, turning off the other
5281 case TCPS_FIN_WAIT_2
:
5282 DTRACE_TCP4(state__change
, void, NULL
,
5283 struct inpcb
*, inp
,
5285 int32_t, TCPS_TIME_WAIT
);
5286 tp
->t_state
= TCPS_TIME_WAIT
;
5287 tcp_canceltimers(tp
);
5288 tp
->t_flags
|= TF_ACKNOW
;
5289 if (tp
->t_flagsext
& TF_NOTIMEWAIT
) {
5290 tp
->t_flags
|= TF_CLOSING
;
5292 add_to_time_wait(tp
, 2 * tcp_msl
);
5294 soisdisconnected(so
);
5298 * In TIME_WAIT state restart the 2 MSL time_wait timer.
5300 case TCPS_TIME_WAIT
:
5301 add_to_time_wait(tp
, 2 * tcp_msl
);
5306 if (so
->so_options
& SO_DEBUG
) {
5307 tcp_trace(TA_INPUT
, ostate
, tp
, (void *)tcp_saveipgen
,
5313 * Return any desired output.
5315 if (needoutput
|| (tp
->t_flags
& TF_ACKNOW
)) {
5316 (void) tcp_output(tp
);
5319 tcp_check_timer_state(tp
);
5322 socket_unlock(so
, 1);
5323 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
, 0, 0, 0, 0, 0);
5328 * Generate an ACK dropping incoming segment if it occupies
5329 * sequence space, where the ACK reflects our state.
5331 * We can now skip the test for the RST flag since all
5332 * paths to this code happen after packets containing
5333 * RST have been dropped.
5335 * In the SYN-RECEIVED state, don't send an ACK unless the
5336 * segment we received passes the SYN-RECEIVED ACK test.
5337 * If it fails send a RST. This breaks the loop in the
5338 * "LAND" DoS attack, and also prevents an ACK storm
5339 * between two listening ports that have been sent forged
5340 * SYN segments, each with the source address of the other.
5342 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& (thflags
& TH_ACK
) &&
5343 (SEQ_GT(tp
->snd_una
, th
->th_ack
) ||
5344 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
5345 rstreason
= BANDLIM_RST_OPENPORT
;
5346 IF_TCP_STATINC(ifp
, dospacket
);
5350 if (so
->so_options
& SO_DEBUG
) {
5351 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
5356 tp
->t_flags
|= TF_ACKNOW
;
5357 (void) tcp_output(tp
);
5359 /* Don't need to check timer state as we should have done it during tcp_output */
5360 socket_unlock(so
, 1);
5361 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
, 0, 0, 0, 0, 0);
5363 dropwithresetnosock
:
5367 * Generate a RST, dropping incoming segment.
5368 * Make ACK acceptable to originator of segment.
5369 * Don't bother to respond if destination was broadcast/multicast.
5371 if ((thflags
& TH_RST
) || m
->m_flags
& (M_BCAST
| M_MCAST
)) {
5376 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
5377 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
)) {
5382 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
5383 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
5384 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
5385 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
)) {
5388 /* IPv6 anycast check is done at tcp6_input() */
5391 * Perform bandwidth limiting.
5394 if (badport_bandlim(rstreason
) < 0) {
5400 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
)) {
5401 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
5405 bzero(&tra
, sizeof(tra
));
5406 tra
.ifscope
= ifscope
;
5407 tra
.awdl_unrestricted
= 1;
5408 tra
.intcoproc_allowed
= 1;
5409 if (thflags
& TH_ACK
) {
5410 /* mtod() below is safe as long as hdr dropping is delayed */
5411 tcp_respond(tp
, mtod(m
, void *), th
, m
, (tcp_seq
)0, th
->th_ack
,
5414 if (thflags
& TH_SYN
) {
5417 /* mtod() below is safe as long as hdr dropping is delayed */
5418 tcp_respond(tp
, mtod(m
, void *), th
, m
, th
->th_seq
+ tlen
,
5419 (tcp_seq
)0, TH_RST
| TH_ACK
, &tra
);
5421 /* destroy temporarily created socket */
5424 socket_unlock(so
, 1);
5425 } else if ((inp
!= NULL
) && (nosock
== 0)) {
5426 socket_unlock(so
, 1);
5428 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
, 0, 0, 0, 0, 0);
5434 * Drop space held by incoming segment and return.
5437 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
)) {
5438 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
5443 /* destroy temporarily created socket */
5446 socket_unlock(so
, 1);
5447 } else if (nosock
== 0) {
5448 socket_unlock(so
, 1);
5450 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
, 0, 0, 0, 0, 0);
5455 * Parse TCP options and place in tcpopt.
5458 tcp_dooptions(struct tcpcb
*tp
, u_char
*cp
, int cnt
, struct tcphdr
*th
,
5464 for (; cnt
> 0; cnt
-= optlen
, cp
+= optlen
) {
5466 if (opt
== TCPOPT_EOL
) {
5469 if (opt
== TCPOPT_NOP
) {
5476 if (optlen
< 2 || optlen
> cnt
) {
5485 if (optlen
!= TCPOLEN_MAXSEG
) {
5488 if (!(th
->th_flags
& TH_SYN
)) {
5491 bcopy((char *) cp
+ 2, (char *) &mss
, sizeof(mss
));
5494 to
->to_flags
|= TOF_MSS
;
5498 if (optlen
!= TCPOLEN_WINDOW
) {
5501 if (!(th
->th_flags
& TH_SYN
)) {
5504 to
->to_flags
|= TOF_SCALE
;
5505 to
->to_requested_s_scale
= min(cp
[2], TCP_MAX_WINSHIFT
);
5508 case TCPOPT_TIMESTAMP
:
5509 if (optlen
!= TCPOLEN_TIMESTAMP
) {
5512 to
->to_flags
|= TOF_TS
;
5513 bcopy((char *)cp
+ 2,
5514 (char *)&to
->to_tsval
, sizeof(to
->to_tsval
));
5515 NTOHL(to
->to_tsval
);
5516 bcopy((char *)cp
+ 6,
5517 (char *)&to
->to_tsecr
, sizeof(to
->to_tsecr
));
5518 NTOHL(to
->to_tsecr
);
5519 /* Re-enable sending Timestamps if we received them */
5520 if (!(tp
->t_flags
& TF_REQ_TSTMP
) &&
5521 tcp_do_rfc1323
== 1) {
5522 tp
->t_flags
|= TF_REQ_TSTMP
;
5525 case TCPOPT_SACK_PERMITTED
:
5527 optlen
!= TCPOLEN_SACK_PERMITTED
) {
5530 if (th
->th_flags
& TH_SYN
) {
5531 to
->to_flags
|= TOF_SACK
;
5535 if (optlen
<= 2 || (optlen
- 2) % TCPOLEN_SACK
!= 0) {
5538 to
->to_nsacks
= (optlen
- 2) / TCPOLEN_SACK
;
5539 to
->to_sacks
= cp
+ 2;
5540 tcpstat
.tcps_sack_rcv_blocks
++;
5543 case TCPOPT_FASTOPEN
:
5544 if (optlen
== TCPOLEN_FASTOPEN_REQ
) {
5545 if (tp
->t_state
!= TCPS_LISTEN
) {
5549 to
->to_flags
|= TOF_TFOREQ
;
5551 if (optlen
< TCPOLEN_FASTOPEN_REQ
||
5552 (optlen
- TCPOLEN_FASTOPEN_REQ
) > TFO_COOKIE_LEN_MAX
||
5553 (optlen
- TCPOLEN_FASTOPEN_REQ
) < TFO_COOKIE_LEN_MIN
) {
5556 if (tp
->t_state
!= TCPS_LISTEN
&&
5557 tp
->t_state
!= TCPS_SYN_SENT
) {
5561 to
->to_flags
|= TOF_TFO
;
5562 to
->to_tfo
= cp
+ 1;
5567 case TCPOPT_MULTIPATH
:
5568 tcp_do_mptcp_options(tp
, cp
, th
, to
, optlen
);
5576 tcp_finalize_options(struct tcpcb
*tp
, struct tcpopt
*to
, unsigned int ifscope
)
5578 if (to
->to_flags
& TOF_TS
) {
5579 tp
->t_flags
|= TF_RCVD_TSTMP
;
5580 tp
->ts_recent
= to
->to_tsval
;
5581 tp
->ts_recent_age
= tcp_now
;
5583 if (to
->to_flags
& TOF_MSS
) {
5584 tcp_mss(tp
, to
->to_mss
, ifscope
);
5586 if (SACK_ENABLED(tp
)) {
5587 if (!(to
->to_flags
& TOF_SACK
)) {
5588 tp
->t_flagsext
&= ~(TF_SACK_ENABLE
);
5590 tp
->t_flags
|= TF_SACK_PERMIT
;
5593 if (to
->to_flags
& TOF_SCALE
) {
5594 tp
->t_flags
|= TF_RCVD_SCALE
;
5595 tp
->requested_s_scale
= to
->to_requested_s_scale
;
5597 /* Re-enable window scaling, if the option is received */
5598 if (tp
->request_r_scale
> 0) {
5599 tp
->t_flags
|= TF_REQ_SCALE
;
5605 * Pull out of band byte out of a segment so
5606 * it doesn't appear in the user's data queue.
5607 * It is still reflected in the segment length for
5608 * sequencing purposes.
5610 * @param off delayed to be droped hdrlen
5613 tcp_pulloutofband(struct socket
*so
, struct tcphdr
*th
, struct mbuf
*m
, int off
)
5615 int cnt
= off
+ th
->th_urp
- 1;
5618 if (m
->m_len
> cnt
) {
5619 char *cp
= mtod(m
, caddr_t
) + cnt
;
5620 struct tcpcb
*tp
= sototcpcb(so
);
5623 tp
->t_oobflags
|= TCPOOB_HAVEDATA
;
5624 bcopy(cp
+ 1, cp
, (unsigned)(m
->m_len
- cnt
- 1));
5626 if (m
->m_flags
& M_PKTHDR
) {
5637 panic("tcp_pulloutofband");
5641 get_base_rtt(struct tcpcb
*tp
)
5643 struct rtentry
*rt
= tp
->t_inpcb
->inp_route
.ro_rt
;
5644 return (rt
== NULL
) ? 0 : rt
->rtt_min
;
5647 /* Each value of RTT base represents the minimum RTT seen in a minute.
5648 * We keep upto N_RTT_BASE minutes worth of history.
5651 update_base_rtt(struct tcpcb
*tp
, uint32_t rtt
)
5653 u_int32_t base_rtt
, i
;
5656 if ((rt
= tp
->t_inpcb
->inp_route
.ro_rt
) == NULL
) {
5659 if (rt
->rtt_expire_ts
== 0) {
5661 if (rt
->rtt_expire_ts
!= 0) {
5665 rt
->rtt_expire_ts
= tcp_now
;
5667 rt
->rtt_hist
[0] = rtt
;
5675 * If the recv side is being throttled, check if the
5676 * current RTT is closer to the base RTT seen in
5677 * first (recent) two slots. If so, unthrottle the stream.
5679 if ((tp
->t_flagsext
& TF_RECV_THROTTLE
) &&
5680 (int)(tcp_now
- tp
->t_recv_throttle_ts
) >= TCP_RECV_THROTTLE_WIN
) {
5681 base_rtt
= rt
->rtt_min
;
5682 if (tp
->t_rttcur
<= (base_rtt
+ target_qdelay
)) {
5683 tp
->t_flagsext
&= ~TF_RECV_THROTTLE
;
5684 tp
->t_recv_throttle_ts
= 0;
5687 #endif /* TRAFFIC_MGT */
5688 if ((int)(tcp_now
- rt
->rtt_expire_ts
) >=
5689 TCP_RTT_HISTORY_EXPIRE_TIME
) {
5691 /* check the condition again to avoid race */
5692 if ((int)(tcp_now
- rt
->rtt_expire_ts
) >=
5693 TCP_RTT_HISTORY_EXPIRE_TIME
) {
5695 if (rt
->rtt_index
>= NRTT_HIST
) {
5698 rt
->rtt_hist
[rt
->rtt_index
] = rtt
;
5699 rt
->rtt_expire_ts
= tcp_now
;
5701 rt
->rtt_hist
[rt
->rtt_index
] =
5702 min(rt
->rtt_hist
[rt
->rtt_index
], rtt
);
5704 /* forget the old value and update minimum */
5706 for (i
= 0; i
< NRTT_HIST
; ++i
) {
5707 if (rt
->rtt_hist
[i
] != 0 &&
5708 (rt
->rtt_min
== 0 ||
5709 rt
->rtt_hist
[i
] < rt
->rtt_min
)) {
5710 rt
->rtt_min
= rt
->rtt_hist
[i
];
5715 rt
->rtt_hist
[rt
->rtt_index
] =
5716 min(rt
->rtt_hist
[rt
->rtt_index
], rtt
);
5717 if (rt
->rtt_min
== 0) {
5720 rt
->rtt_min
= min(rt
->rtt_min
, rtt
);
5726 * If we have a timestamp reply, update smoothed RTT. If no timestamp is
5727 * present but transmit timer is running and timed sequence number was
5728 * acked, update smoothed RTT.
5730 * If timestamps are supported, a receiver can update RTT even if
5731 * there is no outstanding data.
5733 * Some boxes send broken timestamp replies during the SYN+ACK phase,
5734 * ignore timestamps of 0or we could calculate a huge RTT and blow up
5735 * the retransmit timer.
5738 tcp_compute_rtt(struct tcpcb
*tp
, struct tcpopt
*to
, struct tcphdr
*th
)
5741 VERIFY(to
!= NULL
&& th
!= NULL
);
5742 if (tp
->t_rtttime
!= 0 && SEQ_GT(th
->th_ack
, tp
->t_rtseq
)) {
5743 u_int32_t pipe_ack_val
;
5744 rtt
= tcp_now
- tp
->t_rtttime
;
5746 * Compute pipe ack -- the amount of data acknowledged
5749 if (SEQ_GT(th
->th_ack
, tp
->t_pipeack_lastuna
)) {
5750 pipe_ack_val
= th
->th_ack
- tp
->t_pipeack_lastuna
;
5751 /* Update the sample */
5752 tp
->t_pipeack_sample
[tp
->t_pipeack_ind
++] =
5754 tp
->t_pipeack_ind
%= TCP_PIPEACK_SAMPLE_COUNT
;
5756 /* Compute the max of the pipeack samples */
5757 pipe_ack_val
= tcp_get_max_pipeack(tp
);
5758 tp
->t_pipeack
= (pipe_ack_val
>
5759 TCP_CC_CWND_INIT_BYTES
) ?
5762 /* start another measurement */
5765 if (((to
->to_flags
& TOF_TS
) != 0) &&
5766 (to
->to_tsecr
!= 0) &&
5767 TSTMP_GEQ(tcp_now
, to
->to_tsecr
)) {
5768 tcp_xmit_timer(tp
, (tcp_now
- to
->to_tsecr
),
5769 to
->to_tsecr
, th
->th_ack
);
5770 } else if (rtt
> 0) {
5771 tcp_xmit_timer(tp
, rtt
, 0, th
->th_ack
);
5776 * Collect new round-trip time estimate and update averages and
5780 tcp_xmit_timer(struct tcpcb
*tp
, int rtt
,
5781 u_int32_t tsecr
, tcp_seq th_ack
)
5786 * On AWDL interface, the initial RTT measurement on SYN
5787 * can be wrong due to peer caching. Avoid the first RTT
5788 * measurement as it might skew up the RTO.
5789 * <rdar://problem/28739046>
5791 if (tp
->t_inpcb
->inp_last_outifp
!= NULL
&&
5792 (tp
->t_inpcb
->inp_last_outifp
->if_eflags
& IFEF_AWDL
) &&
5793 th_ack
== tp
->iss
+ 1) {
5797 if (tp
->t_flagsext
& TF_RECOMPUTE_RTT
) {
5798 if (SEQ_GT(th_ack
, tp
->snd_una
) &&
5799 SEQ_LEQ(th_ack
, tp
->snd_max
) &&
5801 TSTMP_GEQ(tsecr
, tp
->t_badrexmt_time
))) {
5803 * We received a new ACk after a
5804 * spurious timeout. Adapt retransmission
5805 * timer as described in rfc 4015.
5807 tp
->t_flagsext
&= ~(TF_RECOMPUTE_RTT
);
5808 tp
->t_badrexmt_time
= 0;
5809 tp
->t_srtt
= max(tp
->t_srtt_prev
, rtt
);
5810 tp
->t_srtt
= tp
->t_srtt
<< TCP_RTT_SHIFT
;
5811 tp
->t_rttvar
= max(tp
->t_rttvar_prev
, (rtt
>> 1));
5812 tp
->t_rttvar
= tp
->t_rttvar
<< TCP_RTTVAR_SHIFT
;
5814 if (tp
->t_rttbest
> (tp
->t_srtt
+ tp
->t_rttvar
)) {
5815 tp
->t_rttbest
= tp
->t_srtt
+ tp
->t_rttvar
;
5824 tcpstat
.tcps_rttupdated
++;
5829 update_base_rtt(tp
, rtt
);
5832 if (tp
->t_srtt
!= 0) {
5834 * srtt is stored as fixed point with 5 bits after the
5835 * binary point (i.e., scaled by 32). The following magic
5836 * is equivalent to the smoothing algorithm in rfc793 with
5837 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
5840 * Freebsd adjusts rtt to origin 0 by subtracting 1
5841 * from the provided rtt value. This was required because
5842 * of the way t_rtttime was initiailised to 1 before.
5843 * Since we changed t_rtttime to be based on
5844 * tcp_now, this extra adjustment is not needed.
5846 delta
= (rtt
<< TCP_DELTA_SHIFT
)
5847 - (tp
->t_srtt
>> (TCP_RTT_SHIFT
- TCP_DELTA_SHIFT
));
5849 if ((tp
->t_srtt
+= delta
) <= 0) {
5854 * We accumulate a smoothed rtt variance (actually, a
5855 * smoothed mean difference), then set the retransmit
5856 * timer to smoothed rtt + 4 times the smoothed variance.
5857 * rttvar is stored as fixed point with 4 bits after the
5858 * binary point (scaled by 16). The following is
5859 * equivalent to rfc793 smoothing with an alpha of .75
5860 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
5861 * rfc793's wired-in beta.
5866 delta
-= tp
->t_rttvar
>> (TCP_RTTVAR_SHIFT
- TCP_DELTA_SHIFT
);
5867 if ((tp
->t_rttvar
+= delta
) <= 0) {
5870 if (tp
->t_rttbest
== 0 ||
5871 tp
->t_rttbest
> (tp
->t_srtt
+ tp
->t_rttvar
)) {
5872 tp
->t_rttbest
= tp
->t_srtt
+ tp
->t_rttvar
;
5876 * No rtt measurement yet - use the unsmoothed rtt.
5877 * Set the variance to half the rtt (so our first
5878 * retransmit happens at 3*rtt).
5880 tp
->t_srtt
= rtt
<< TCP_RTT_SHIFT
;
5881 tp
->t_rttvar
= rtt
<< (TCP_RTTVAR_SHIFT
- 1);
5885 nstat_route_rtt(tp
->t_inpcb
->inp_route
.ro_rt
, tp
->t_srtt
,
5889 * the retransmit should happen at rtt + 4 * rttvar.
5890 * Because of the way we do the smoothing, srtt and rttvar
5891 * will each average +1/2 tick of bias. When we compute
5892 * the retransmit timer, we want 1/2 tick of rounding and
5893 * 1 extra tick because of +-1/2 tick uncertainty in the
5894 * firing of the timer. The bias will give us exactly the
5895 * 1.5 tick we need. But, because the bias is
5896 * statistical, we have to test that we don't drop below
5897 * the minimum feasible timer (which is 2 ticks).
5899 TCPT_RANGESET(tp
->t_rxtcur
, TCP_REXMTVAL(tp
),
5900 max(tp
->t_rttmin
, rtt
+ 2), TCPTV_REXMTMAX
,
5901 TCP_ADD_REXMTSLOP(tp
));
5904 * We received an ack for a packet that wasn't retransmitted;
5905 * it is probably safe to discard any error indications we've
5906 * received recently. This isn't quite right, but close enough
5907 * for now (a route might have failed after we sent a segment,
5908 * and the return path might not be symmetrical).
5910 tp
->t_softerror
= 0;
5913 static inline unsigned int
5914 tcp_maxmtu(struct rtentry
*rt
)
5916 unsigned int maxmtu
;
5917 int interface_mtu
= 0;
5919 RT_LOCK_ASSERT_HELD(rt
);
5920 interface_mtu
= rt
->rt_ifp
->if_mtu
;
5922 if (rt_key(rt
)->sa_family
== AF_INET
&&
5923 INTF_ADJUST_MTU_FOR_CLAT46(rt
->rt_ifp
)) {
5924 interface_mtu
= IN6_LINKMTU(rt
->rt_ifp
);
5925 /* Further adjust the size for CLAT46 expansion */
5926 interface_mtu
-= CLAT46_HDR_EXPANSION_OVERHD
;
5929 if (rt
->rt_rmx
.rmx_mtu
== 0) {
5930 maxmtu
= interface_mtu
;
5932 maxmtu
= MIN(rt
->rt_rmx
.rmx_mtu
, interface_mtu
);
5939 static inline unsigned int
5940 tcp_maxmtu6(struct rtentry
*rt
)
5942 unsigned int maxmtu
;
5943 struct nd_ifinfo
*ndi
= NULL
;
5945 RT_LOCK_ASSERT_HELD(rt
);
5946 if ((ndi
= ND_IFINFO(rt
->rt_ifp
)) != NULL
&& !ndi
->initialized
) {
5950 lck_mtx_lock(&ndi
->lock
);
5952 if (rt
->rt_rmx
.rmx_mtu
== 0) {
5953 maxmtu
= IN6_LINKMTU(rt
->rt_ifp
);
5955 maxmtu
= MIN(rt
->rt_rmx
.rmx_mtu
, IN6_LINKMTU(rt
->rt_ifp
));
5958 lck_mtx_unlock(&ndi
->lock
);
5966 get_maxmtu(struct rtentry
*rt
)
5968 unsigned int maxmtu
= 0;
5970 RT_LOCK_ASSERT_NOTHELD(rt
);
5974 if (rt_key(rt
)->sa_family
== AF_INET6
) {
5975 maxmtu
= tcp_maxmtu6(rt
);
5977 maxmtu
= tcp_maxmtu(rt
);
5986 * Determine a reasonable value for maxseg size.
5987 * If the route is known, check route for mtu.
5988 * If none, use an mss that can be handled on the outgoing
5989 * interface without forcing IP to fragment; if bigger than
5990 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
5991 * to utilize large mbufs. If no route is found, route has no mtu,
5992 * or the destination isn't local, use a default, hopefully conservative
5993 * size (usually 512 or the default IP max size, but no more than the mtu
5994 * of the interface), as we can't discover anything about intervening
5995 * gateways or networks. We also initialize the congestion/slow start
5996 * window. While looking at the routing entry, we also initialize
5997 * other path-dependent parameters from pre-set or cached values
5998 * in the routing entry.
6000 * Also take into account the space needed for options that we
6001 * send regularly. Make maxseg shorter by that amount to assure
6002 * that we can send maxseg amount of data even when the options
6003 * are present. Store the upper limit of the length of options plus
6006 * NOTE that this routine is only called when we process an incoming
6007 * segment, for outgoing segments only tcp_mssopt is called.
6011 tcp_mss(struct tcpcb
*tp
, int offer
, unsigned int input_ifscope
)
6019 struct rmxp_tao
*taop
;
6020 int origoffer
= offer
;
6021 u_int32_t sb_max_corrected
;
6030 isipv6
= ((inp
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
6031 min_protoh
= isipv6
? sizeof(struct ip6_hdr
) + sizeof(struct tcphdr
)
6032 : sizeof(struct tcpiphdr
);
6034 #define min_protoh (sizeof (struct tcpiphdr))
6039 rt
= tcp_rtlookup6(inp
, input_ifscope
);
6043 rt
= tcp_rtlookup(inp
, input_ifscope
);
6045 isnetlocal
= (tp
->t_flags
& TF_LOCAL
);
6048 tp
->t_maxopd
= tp
->t_maxseg
=
6050 isipv6
? tcp_v6mssdflt
:
6057 * Slower link window correction:
6058 * If a value is specificied for slowlink_wsize use it for
6059 * PPP links believed to be on a serial modem (speed <128Kbps).
6060 * Excludes 9600bps as it is the default value adversized
6061 * by pseudo-devices over ppp.
6063 if (ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
6064 ifp
->if_baudrate
> 9600 && ifp
->if_baudrate
<= 128000) {
6065 tp
->t_flags
|= TF_SLOWLINK
;
6067 so
= inp
->inp_socket
;
6069 taop
= rmx_taop(rt
->rt_rmx
);
6071 * Offer == -1 means that we didn't receive SYN yet,
6072 * use cached value in that case;
6075 offer
= taop
->tao_mssopt
;
6078 * Offer == 0 means that there was no MSS on the SYN segment,
6079 * in this case we use tcp_mssdflt.
6084 isipv6
? tcp_v6mssdflt
:
6089 * Prevent DoS attack with too small MSS. Round up
6090 * to at least minmss.
6092 offer
= max(offer
, tcp_minmss
);
6094 * Sanity check: make sure that maxopd will be large
6095 * enough to allow some data on segments even is the
6096 * all the option space is used (40bytes). Otherwise
6097 * funny things may happen in tcp_output.
6099 offer
= max(offer
, 64);
6101 taop
->tao_mssopt
= offer
;
6104 * While we're here, check if there's an initial rtt
6105 * or rttvar. Convert from the route-table units
6106 * to scaled multiples of the slow timeout timer.
6108 if (tp
->t_srtt
== 0 && (rtt
= rt
->rt_rmx
.rmx_rtt
) != 0) {
6109 tcp_getrt_rtt(tp
, rt
);
6111 tp
->t_rttmin
= isnetlocal
? tcp_TCPTV_MIN
: TCPTV_REXMTMIN
;
6115 mss
= (isipv6
? tcp_maxmtu6(rt
) : tcp_maxmtu(rt
));
6117 mss
= tcp_maxmtu(rt
);
6121 // At this point, the mss is just the MTU. Adjust if necessary.
6122 mss
= necp_socket_get_effective_mtu(inp
, mss
);
6127 if (rt
->rt_rmx
.rmx_mtu
== 0) {
6131 mss
= min(mss
, tcp_v6mssdflt
);
6136 mss
= min(mss
, tcp_mssdflt
);
6140 mss
= min(mss
, offer
);
6142 * maxopd stores the maximum length of data AND options
6143 * in a segment; maxseg is the amount of data in a normal
6144 * segment. We need to store this value (maxopd) apart
6145 * from maxseg, because now every segment carries options
6146 * and thus we normally have somewhat less data in segments.
6151 * origoffer==-1 indicates, that no segments were received yet.
6152 * In this case we just guess.
6154 if ((tp
->t_flags
& (TF_REQ_TSTMP
| TF_NOOPT
)) == TF_REQ_TSTMP
&&
6156 (tp
->t_flags
& TF_RCVD_TSTMP
) == TF_RCVD_TSTMP
)) {
6157 mss
-= TCPOLEN_TSTAMP_APPA
;
6161 mss
-= mptcp_adj_mss(tp
, FALSE
);
6166 * Calculate corrected value for sb_max; ensure to upgrade the
6167 * numerator for large sb_max values else it will overflow.
6169 sb_max_corrected
= (sb_max
* (u_int64_t
)MCLBYTES
) / (MSIZE
+ MCLBYTES
);
6172 * If there's a pipesize (ie loopback), change the socket
6173 * buffer to that size only if it's bigger than the current
6174 * sockbuf size. Make the socket buffers an integral
6175 * number of mss units; if the mss is larger than
6176 * the socket buffer, decrease the mss.
6179 bufsize
= rt
->rt_rmx
.rmx_sendpipe
;
6180 if (bufsize
< so
->so_snd
.sb_hiwat
)
6182 bufsize
= so
->so_snd
.sb_hiwat
;
6183 if (bufsize
< mss
) {
6186 bufsize
= (((bufsize
+ (u_int64_t
)mss
- 1) / (u_int64_t
)mss
) * (u_int64_t
)mss
);
6187 if (bufsize
> sb_max_corrected
) {
6188 bufsize
= sb_max_corrected
;
6190 (void)sbreserve(&so
->so_snd
, bufsize
);
6194 ASSERT(tp
->t_maxseg
);
6197 * Update MSS using recommendation from link status report. This is
6200 tcp_update_mss_locked(so
, ifp
);
6203 bufsize
= rt
->rt_rmx
.rmx_recvpipe
;
6204 if (bufsize
< so
->so_rcv
.sb_hiwat
)
6206 bufsize
= so
->so_rcv
.sb_hiwat
;
6207 if (bufsize
> mss
) {
6208 bufsize
= (((bufsize
+ (u_int64_t
)mss
- 1) / (u_int64_t
)mss
) * (u_int64_t
)mss
);
6209 if (bufsize
> sb_max_corrected
) {
6210 bufsize
= sb_max_corrected
;
6212 (void)sbreserve(&so
->so_rcv
, bufsize
);
6215 set_tcp_stream_priority(so
);
6217 if (rt
->rt_rmx
.rmx_ssthresh
) {
6219 * There's some sort of gateway or interface
6220 * buffer limit on the path. Use this to set
6221 * slow-start threshold, but set the threshold to
6222 * no less than 2*mss.
6224 tp
->snd_ssthresh
= max(2 * mss
, rt
->rt_rmx
.rmx_ssthresh
);
6225 tcpstat
.tcps_usedssthresh
++;
6227 tp
->snd_ssthresh
= TCP_MAXWIN
<< TCP_MAX_WINSHIFT
;
6231 * Set the slow-start flight size depending on whether this
6232 * is a local network or not.
6234 if (CC_ALGO(tp
)->cwnd_init
!= NULL
) {
6235 CC_ALGO(tp
)->cwnd_init(tp
);
6238 tcp_ccdbg_trace(tp
, NULL
, TCP_CC_CWND_INIT
);
6240 /* Route locked during lookup above */
6245 * Determine the MSS option to send on an outgoing SYN.
6248 tcp_mssopt(struct tcpcb
*tp
)
6258 isipv6
= ((tp
->t_inpcb
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
6259 min_protoh
= isipv6
? sizeof(struct ip6_hdr
) + sizeof(struct tcphdr
)
6260 : sizeof(struct tcpiphdr
);
6262 #define min_protoh (sizeof (struct tcpiphdr))
6267 rt
= tcp_rtlookup6(tp
->t_inpcb
, IFSCOPE_NONE
);
6270 rt
= tcp_rtlookup(tp
->t_inpcb
, IFSCOPE_NONE
);
6274 isipv6
? tcp_v6mssdflt
:
6279 * Slower link window correction:
6280 * If a value is specificied for slowlink_wsize use it for PPP links
6281 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
6282 * it is the default value adversized by pseudo-devices over ppp.
6284 if (rt
->rt_ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
6285 rt
->rt_ifp
->if_baudrate
> 9600 && rt
->rt_ifp
->if_baudrate
<= 128000) {
6286 tp
->t_flags
|= TF_SLOWLINK
;
6290 mss
= (isipv6
? tcp_maxmtu6(rt
) : tcp_maxmtu(rt
));
6292 mss
= tcp_maxmtu(rt
);
6294 /* Route locked during lookup above */
6298 // At this point, the mss is just the MTU. Adjust if necessary.
6299 mss
= necp_socket_get_effective_mtu(tp
->t_inpcb
, mss
);
6302 return mss
- min_protoh
;
6306 * On a partial ack arrives, force the retransmission of the
6307 * next unacknowledged segment. Do not clear tp->t_dupacks.
6308 * By setting snd_nxt to th_ack, this forces retransmission timer to
6312 tcp_newreno_partial_ack(struct tcpcb
*tp
, struct tcphdr
*th
)
6314 tcp_seq onxt
= tp
->snd_nxt
;
6315 u_int32_t ocwnd
= tp
->snd_cwnd
;
6316 tp
->t_timer
[TCPT_REXMT
] = 0;
6317 tp
->t_timer
[TCPT_PTO
] = 0;
6319 tp
->snd_nxt
= th
->th_ack
;
6321 * Set snd_cwnd to one segment beyond acknowledged offset
6322 * (tp->snd_una has not yet been updated when this function
6325 tp
->snd_cwnd
= tp
->t_maxseg
+ BYTES_ACKED(th
, tp
);
6326 tp
->t_flags
|= TF_ACKNOW
;
6327 (void) tcp_output(tp
);
6328 tp
->snd_cwnd
= ocwnd
;
6329 if (SEQ_GT(onxt
, tp
->snd_nxt
)) {
6333 * Partial window deflation. Relies on fact that tp->snd_una
6336 if (tp
->snd_cwnd
> BYTES_ACKED(th
, tp
)) {
6337 tp
->snd_cwnd
-= BYTES_ACKED(th
, tp
);
6341 tp
->snd_cwnd
+= tp
->t_maxseg
;
6345 * Drop a random TCP connection that hasn't been serviced yet and
6346 * is eligible for discard. There is a one in qlen chance that
6347 * we will return a null, saying that there are no dropable
6348 * requests. In this case, the protocol specific code should drop
6349 * the new request. This insures fairness.
6351 * The listening TCP socket "head" must be locked
6354 tcp_dropdropablreq(struct socket
*head
)
6356 struct socket
*so
, *sonext
;
6357 unsigned int i
, j
, qlen
;
6358 static u_int32_t rnd
= 0;
6359 static u_int64_t old_runtime
;
6360 static unsigned int cur_cnt
, old_cnt
;
6362 struct inpcb
*inp
= NULL
;
6365 if ((head
->so_options
& SO_ACCEPTCONN
) == 0) {
6369 if (TAILQ_EMPTY(&head
->so_incomp
)) {
6373 so_acquire_accept_list(head
, NULL
);
6374 socket_unlock(head
, 0);
6377 * Check if there is any socket in the incomp queue
6378 * that is closed because of a reset from the peer and is
6379 * waiting to be garbage collected. If so, pick that as
6382 TAILQ_FOREACH_SAFE(so
, &head
->so_incomp
, so_list
, sonext
) {
6383 inp
= sotoinpcb(so
);
6384 tp
= intotcpcb(inp
);
6385 if (tp
!= NULL
&& tp
->t_state
== TCPS_CLOSED
&&
6386 so
->so_head
!= NULL
&&
6387 (so
->so_state
& (SS_INCOMP
| SS_CANTSENDMORE
| SS_CANTRCVMORE
)) ==
6388 (SS_INCOMP
| SS_CANTSENDMORE
| SS_CANTRCVMORE
)) {
6390 * The listen socket is already locked but we
6391 * can lock this socket here without lock ordering
6392 * issues because it is in the incomp queue and
6393 * is not visible to others.
6395 if (socket_try_lock(so
)) {
6404 so
= TAILQ_FIRST(&head
->so_incomp
);
6406 now_sec
= net_uptime();
6407 if ((i
= (now_sec
- old_runtime
)) != 0) {
6408 old_runtime
= now_sec
;
6409 old_cnt
= cur_cnt
/ i
;
6413 qlen
= head
->so_incqlen
;
6415 rnd
= RandomULong();
6418 if (++cur_cnt
> qlen
|| old_cnt
> qlen
) {
6419 rnd
= (314159 * rnd
+ 66329) & 0xffff;
6420 j
= ((qlen
+ 1) * rnd
) >> 16;
6423 so
= TAILQ_NEXT(so
, so_list
);
6426 /* Find a connection that is not already closing (or being served) */
6428 inp
= (struct inpcb
*)so
->so_pcb
;
6430 sonext
= TAILQ_NEXT(so
, so_list
);
6432 if (in_pcb_checkstate(inp
, WNT_ACQUIRE
, 0) != WNT_STOPUSING
) {
6434 * Avoid the issue of a socket being accepted
6435 * by one input thread and being dropped by
6436 * another input thread. If we can't get a hold
6437 * on this mutex, then grab the next socket in
6440 if (socket_try_lock(so
)) {
6442 if ((so
->so_usecount
== 2) &&
6443 (so
->so_state
& SS_INCOMP
) &&
6444 !(so
->so_flags
& SOF_INCOMP_INPROGRESS
)) {
6448 * don't use if being accepted or
6449 * used in any other way
6451 in_pcb_checkstate(inp
, WNT_RELEASE
, 1);
6452 socket_unlock(so
, 1);
6456 * do not try to lock the inp in
6457 * in_pcb_checkstate because the lock
6458 * is already held in some other thread.
6459 * Only drop the inp_wntcnt reference.
6461 in_pcb_checkstate(inp
, WNT_RELEASE
, 1);
6467 socket_lock(head
, 0);
6468 so_release_accept_list(head
);
6472 /* Makes sure socket is still in the right state to be discarded */
6474 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
6475 socket_unlock(so
, 1);
6476 socket_lock(head
, 0);
6477 so_release_accept_list(head
);
6482 if (so
->so_usecount
!= 2 || !(so
->so_state
& SS_INCOMP
)) {
6483 /* do not discard: that socket is being accepted */
6484 socket_unlock(so
, 1);
6485 socket_lock(head
, 0);
6486 so_release_accept_list(head
);
6490 socket_lock(head
, 0);
6491 TAILQ_REMOVE(&head
->so_incomp
, so
, so_list
);
6494 so
->so_state
&= ~SS_INCOMP
;
6495 so
->so_flags
|= SOF_OVERFLOW
;
6497 so_release_accept_list(head
);
6498 socket_unlock(head
, 0);
6500 socket_lock_assert_owned(so
);
6504 if (inp
->inp_wantcnt
> 0 && inp
->inp_wantcnt
!= WNT_STOPUSING
) {
6506 * Some one has a wantcnt on this pcb. Since WNT_ACQUIRE
6507 * doesn't require a lock, it could have happened while
6508 * we are holding the lock. This pcb will have to
6509 * be garbage collected later.
6510 * Release the reference held for so_incomp queue
6512 VERIFY(so
->so_usecount
> 0);
6514 socket_unlock(so
, 1);
6517 * Unlock this socket and leave the reference on.
6518 * We need to acquire the pcbinfo lock in order to
6519 * fully dispose it off
6521 socket_unlock(so
, 0);
6523 lck_rw_lock_exclusive(tcbinfo
.ipi_lock
);
6526 /* Release the reference held for so_incomp queue */
6527 VERIFY(so
->so_usecount
> 0);
6530 if (so
->so_usecount
!= 1 ||
6531 (inp
->inp_wantcnt
> 0 &&
6532 inp
->inp_wantcnt
!= WNT_STOPUSING
)) {
6534 * There is an extra wantcount or usecount
6535 * that must have been added when the socket
6536 * was unlocked. This socket will have to be
6537 * garbage collected later
6539 socket_unlock(so
, 1);
6541 /* Drop the reference held for this function */
6542 VERIFY(so
->so_usecount
> 0);
6547 lck_rw_done(tcbinfo
.ipi_lock
);
6549 tcpstat
.tcps_drops
++;
6551 socket_lock(head
, 0);
6555 /* Set background congestion control on a socket */
6557 tcp_set_background_cc(struct socket
*so
)
6559 tcp_set_new_cc(so
, TCP_CC_ALGO_BACKGROUND_INDEX
);
6562 /* Set foreground congestion control on a socket */
6564 tcp_set_foreground_cc(struct socket
*so
)
6566 if (tcp_use_newreno
) {
6567 tcp_set_new_cc(so
, TCP_CC_ALGO_NEWRENO_INDEX
);
6569 tcp_set_new_cc(so
, TCP_CC_ALGO_CUBIC_INDEX
);
6574 tcp_set_new_cc(struct socket
*so
, uint16_t cc_index
)
6576 struct inpcb
*inp
= sotoinpcb(so
);
6577 struct tcpcb
*tp
= intotcpcb(inp
);
6578 u_char old_cc_index
= 0;
6579 if (tp
->tcp_cc_index
!= cc_index
) {
6580 old_cc_index
= tp
->tcp_cc_index
;
6582 if (CC_ALGO(tp
)->cleanup
!= NULL
) {
6583 CC_ALGO(tp
)->cleanup(tp
);
6585 tp
->tcp_cc_index
= cc_index
;
6587 tcp_cc_allocate_state(tp
);
6589 if (CC_ALGO(tp
)->switch_to
!= NULL
) {
6590 CC_ALGO(tp
)->switch_to(tp
, old_cc_index
);
6593 tcp_ccdbg_trace(tp
, NULL
, TCP_CC_CHANGE_ALGO
);
6598 tcp_set_recv_bg(struct socket
*so
)
6600 if (!IS_TCP_RECV_BG(so
)) {
6601 so
->so_flags1
|= SOF1_TRAFFIC_MGT_TCP_RECVBG
;
6604 /* Unset Large Receive Offload on background sockets */
6605 so_set_lro(so
, SO_TC_BK
);
6609 tcp_clear_recv_bg(struct socket
*so
)
6611 if (IS_TCP_RECV_BG(so
)) {
6612 so
->so_flags1
&= ~(SOF1_TRAFFIC_MGT_TCP_RECVBG
);
6616 * Set/unset use of Large Receive Offload depending on
6619 so_set_lro(so
, so
->so_traffic_class
);
6623 inp_fc_unthrottle_tcp(struct inpcb
*inp
)
6625 struct tcpcb
*tp
= inp
->inp_ppcb
;
6627 * Back off the slow-start threshold and enter
6628 * congestion avoidance phase
6630 if (CC_ALGO(tp
)->pre_fr
!= NULL
) {
6631 CC_ALGO(tp
)->pre_fr(tp
);
6634 tp
->snd_cwnd
= tp
->snd_ssthresh
;
6635 tp
->t_flagsext
&= ~TF_CWND_NONVALIDATED
;
6637 * Restart counting for ABC as we changed the
6638 * congestion window just now.
6640 tp
->t_bytes_acked
= 0;
6642 /* Reset retransmit shift as we know that the reason
6643 * for delay in sending a packet is due to flow
6644 * control on the outgoing interface. There is no need
6645 * to backoff retransmit timer.
6647 TCP_RESET_REXMT_STATE(tp
);
6650 * Start the output stream again. Since we are
6651 * not retransmitting data, do not reset the
6652 * retransmit timer or rtt calculation.
6658 tcp_getstat SYSCTL_HANDLER_ARGS
6660 #pragma unused(oidp, arg1, arg2)
6663 struct tcpstat
*stat
;
6665 #if !CONFIG_EMBEDDED
6666 proc_t caller
= PROC_NULL
;
6667 proc_t caller_parent
= PROC_NULL
;
6668 char command_name
[MAXCOMLEN
+ 1] = "";
6669 char parent_name
[MAXCOMLEN
+ 1] = "";
6670 struct tcpstat zero_stat
;
6671 if ((caller
= proc_self()) != PROC_NULL
) {
6672 /* get process name */
6673 strlcpy(command_name
, caller
->p_comm
, sizeof(command_name
));
6675 /* get parent process name if possible */
6676 if ((caller_parent
= proc_find(caller
->p_ppid
)) != PROC_NULL
) {
6677 strlcpy(parent_name
, caller_parent
->p_comm
,
6678 sizeof(parent_name
));
6679 proc_rele(caller_parent
);
6682 if ((escape_str(command_name
, strlen(command_name
) + 1,
6683 sizeof(command_name
)) == 0) &&
6684 (escape_str(parent_name
, strlen(parent_name
) + 1,
6685 sizeof(parent_name
)) == 0)) {
6686 kern_asl_msg(LOG_DEBUG
, "messagetracer",
6688 "com.apple.message.domain",
6689 "com.apple.kernel.tcpstat", /* 1 */
6690 "com.apple.message.signature",
6692 "com.apple.message.signature2", command_name
, /* 3 */
6693 "com.apple.message.signature3", parent_name
, /* 4 */
6694 "com.apple.message.summarize", "YES", /* 5 */
6698 if (caller
!= PROC_NULL
) {
6701 if (tcp_disable_access_to_stats
&&
6702 !kauth_cred_issuser(kauth_cred_get())) {
6703 bzero(&zero_stat
, sizeof(zero_stat
));
6707 #endif /* !CONFIG_EMBEDDED */
6709 if (req
->oldptr
== 0) {
6710 req
->oldlen
= (size_t)sizeof(struct tcpstat
);
6713 error
= SYSCTL_OUT(req
, stat
, MIN(sizeof(tcpstat
), req
->oldlen
));
6719 * Checksum extended TCP header and data.
6722 tcp_input_checksum(int af
, struct mbuf
*m
, struct tcphdr
*th
, int off
, int tlen
)
6724 struct ifnet
*ifp
= m
->m_pkthdr
.rcvif
;
6728 struct ip
*ip
= mtod(m
, struct ip
*);
6729 struct ipovly
*ipov
= (struct ipovly
*)ip
;
6731 if (m
->m_pkthdr
.pkt_flags
& PKTF_SW_LRO_DID_CSUM
) {
6735 /* ip_stripoptions() must have been called before we get here */
6736 ASSERT((ip
->ip_hl
<< 2) == sizeof(*ip
));
6738 if ((hwcksum_rx
|| (ifp
->if_flags
& IFF_LOOPBACK
) ||
6739 (m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) &&
6740 (m
->m_pkthdr
.csum_flags
& CSUM_DATA_VALID
)) {
6741 if (m
->m_pkthdr
.csum_flags
& CSUM_PSEUDO_HDR
) {
6742 th
->th_sum
= m
->m_pkthdr
.csum_rx_val
;
6744 uint32_t sum
= m
->m_pkthdr
.csum_rx_val
;
6745 uint32_t start
= m
->m_pkthdr
.csum_rx_start
;
6746 int32_t trailer
= (m_pktlen(m
) - (off
+ tlen
));
6749 * Perform 1's complement adjustment of octets
6750 * that got included/excluded in the hardware-
6751 * calculated checksum value. Ignore cases
6752 * where the value already includes the entire
6753 * IP header span, as the sum for those octets
6754 * would already be 0 by the time we get here;
6755 * IP has already performed its header checksum
6756 * checks. If we do need to adjust, restore
6757 * the original fields in the IP header when
6758 * computing the adjustment value. Also take
6759 * care of any trailing bytes and subtract out
6760 * their partial sum.
6762 ASSERT(trailer
>= 0);
6763 if ((m
->m_pkthdr
.csum_flags
& CSUM_PARTIAL
) &&
6764 ((start
!= 0 && start
!= off
) || trailer
)) {
6765 uint32_t swbytes
= (uint32_t)trailer
;
6768 ip
->ip_len
+= sizeof(*ip
);
6769 #if BYTE_ORDER != BIG_ENDIAN
6772 #endif /* BYTE_ORDER != BIG_ENDIAN */
6774 /* callee folds in sum */
6775 sum
= m_adj_sum16(m
, start
, off
,
6778 swbytes
+= (off
- start
);
6780 swbytes
+= (start
- off
);
6784 #if BYTE_ORDER != BIG_ENDIAN
6787 #endif /* BYTE_ORDER != BIG_ENDIAN */
6788 ip
->ip_len
-= sizeof(*ip
);
6792 tcp_in_cksum_stats(swbytes
);
6799 /* callee folds in sum */
6800 th
->th_sum
= in_pseudo(ip
->ip_src
.s_addr
,
6802 sum
+ htonl(tlen
+ IPPROTO_TCP
));
6804 th
->th_sum
^= 0xffff;
6810 bcopy(ipov
->ih_x1
, b
, sizeof(ipov
->ih_x1
));
6811 bzero(ipov
->ih_x1
, sizeof(ipov
->ih_x1
));
6812 ip_sum
= ipov
->ih_len
;
6813 ipov
->ih_len
= (u_short
)tlen
;
6814 #if BYTE_ORDER != BIG_ENDIAN
6815 HTONS(ipov
->ih_len
);
6817 len
= sizeof(struct ip
) + tlen
;
6818 th
->th_sum
= in_cksum(m
, len
);
6819 bcopy(b
, ipov
->ih_x1
, sizeof(ipov
->ih_x1
));
6820 ipov
->ih_len
= ip_sum
;
6822 tcp_in_cksum_stats(len
);
6828 struct ip6_hdr
*ip6
= mtod(m
, struct ip6_hdr
*);
6830 if (m
->m_pkthdr
.pkt_flags
& PKTF_SW_LRO_DID_CSUM
) {
6834 if ((hwcksum_rx
|| (ifp
->if_flags
& IFF_LOOPBACK
) ||
6835 (m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) &&
6836 (m
->m_pkthdr
.csum_flags
& CSUM_DATA_VALID
)) {
6837 if (m
->m_pkthdr
.csum_flags
& CSUM_PSEUDO_HDR
) {
6838 th
->th_sum
= m
->m_pkthdr
.csum_rx_val
;
6840 uint32_t sum
= m
->m_pkthdr
.csum_rx_val
;
6841 uint32_t start
= m
->m_pkthdr
.csum_rx_start
;
6842 int32_t trailer
= (m_pktlen(m
) - (off
+ tlen
));
6845 * Perform 1's complement adjustment of octets
6846 * that got included/excluded in the hardware-
6847 * calculated checksum value. Also take care
6848 * of any trailing bytes and subtract out their
6851 ASSERT(trailer
>= 0);
6852 if ((m
->m_pkthdr
.csum_flags
& CSUM_PARTIAL
) &&
6853 (start
!= off
|| trailer
!= 0)) {
6854 uint16_t s
= 0, d
= 0;
6855 uint32_t swbytes
= (uint32_t)trailer
;
6857 if (IN6_IS_SCOPE_EMBED(&ip6
->ip6_src
)) {
6858 s
= ip6
->ip6_src
.s6_addr16
[1];
6859 ip6
->ip6_src
.s6_addr16
[1] = 0;
6861 if (IN6_IS_SCOPE_EMBED(&ip6
->ip6_dst
)) {
6862 d
= ip6
->ip6_dst
.s6_addr16
[1];
6863 ip6
->ip6_dst
.s6_addr16
[1] = 0;
6866 /* callee folds in sum */
6867 sum
= m_adj_sum16(m
, start
, off
,
6870 swbytes
+= (off
- start
);
6872 swbytes
+= (start
- off
);
6875 if (IN6_IS_SCOPE_EMBED(&ip6
->ip6_src
)) {
6876 ip6
->ip6_src
.s6_addr16
[1] = s
;
6878 if (IN6_IS_SCOPE_EMBED(&ip6
->ip6_dst
)) {
6879 ip6
->ip6_dst
.s6_addr16
[1] = d
;
6883 tcp_in6_cksum_stats(swbytes
);
6890 th
->th_sum
= in6_pseudo(
6891 &ip6
->ip6_src
, &ip6
->ip6_dst
,
6892 sum
+ htonl(tlen
+ IPPROTO_TCP
));
6894 th
->th_sum
^= 0xffff;
6896 tcp_in6_cksum_stats(tlen
);
6897 th
->th_sum
= in6_cksum(m
, IPPROTO_TCP
, off
, tlen
);
6907 if (th
->th_sum
!= 0) {
6908 tcpstat
.tcps_rcvbadsum
++;
6909 IF_TCP_STATINC(ifp
, badformat
);
6917 SYSCTL_PROC(_net_inet_tcp
, TCPCTL_STATS
, stats
,
6918 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
, 0, 0, tcp_getstat
,
6919 "S,tcpstat", "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
6922 sysctl_rexmtthresh SYSCTL_HANDLER_ARGS
6924 #pragma unused(arg1, arg2)
6926 int error
, val
= tcprexmtthresh
;
6928 error
= sysctl_handle_int(oidp
, &val
, 0, req
);
6929 if (error
|| !req
->newptr
) {
6934 * Constrain the number of duplicate ACKs
6935 * to consider for TCP fast retransmit
6939 if (val
< 2 || val
> 3) {
6943 tcprexmtthresh
= val
;
6948 SYSCTL_PROC(_net_inet_tcp
, OID_AUTO
, rexmt_thresh
, CTLTYPE_INT
| CTLFLAG_RW
|
6949 CTLFLAG_LOCKED
, &tcprexmtthresh
, 0, &sysctl_rexmtthresh
, "I",
6950 "Duplicate ACK Threshold for Fast Retransmit");