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
)
407 if (tp
->iaj_size
== 0 || size
>= tp
->iaj_size
) {
409 tp
->iaj_rcv_ts
= tcp_now
;
410 tp
->iaj_small_pkt
= 0;
414 /* For every 32 bit unsigned integer(v), this function will find the
415 * largest integer n such that (n*n <= v). This takes at most 16 iterations
416 * irrespective of the value of v and does not involve multiplications.
419 isqrt(unsigned int val
)
421 unsigned int sqrt_cache
[11] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100};
422 unsigned int temp
, g
=0, b
=0x8000, bshft
=15;
424 for (g
= 0; g
<= 10; ++g
) {
425 if (sqrt_cache
[g
] > val
) {
428 } else if (sqrt_cache
[g
] == val
) {
434 temp
= (((g
<< 1) + b
) << (bshft
--));
440 } while ( b
> 0 && val
> 0);
446 * With LRO, roughly estimate the inter arrival time between
447 * each sub coalesced packet as an average. Count the delay
448 * cur_iaj to be the delay between the last packet received
449 * and the first packet of the LRO stream. Due to round off errors
450 * cur_iaj may be the same as lro_delay_factor. Averaging has
451 * round off errors too. lro_delay_factor may be close to 0
452 * in steady state leading to lower values fed to compute_iaj_meat.
455 compute_iaj(struct tcpcb
*tp
, int nlropkts
, int lro_delay_factor
)
457 uint32_t cur_iaj
= tcp_now
- tp
->iaj_rcv_ts
;
458 uint32_t timediff
= 0;
460 if (cur_iaj
>= lro_delay_factor
) {
461 cur_iaj
= cur_iaj
- lro_delay_factor
;
464 compute_iaj_meat(tp
, cur_iaj
);
471 timediff
= lro_delay_factor
/nlropkts
;
475 compute_iaj_meat(tp
, timediff
);
481 void compute_iaj_meat(struct tcpcb
*tp
, uint32_t cur_iaj
)
483 /* When accumulated IAJ reaches MAX_ACC_IAJ in milliseconds,
484 * throttle the receive window to a minimum of MIN_IAJ_WIN packets
486 #define MAX_ACC_IAJ (tcp_acc_iaj_high_thresh + tcp_acc_iaj_react_limit)
487 #define IAJ_DIV_SHIFT 4
488 #define IAJ_ROUNDUP_CONST (1 << (IAJ_DIV_SHIFT - 1))
490 uint32_t allowed_iaj
, acc_iaj
= 0;
495 cur_iaj_dev
= (cur_iaj
- tp
->avg_iaj
);
497 /* Allow a jitter of "allowed_iaj" milliseconds. Some connections
498 * may have a constant jitter more than that. We detect this by
499 * using standard deviation.
501 allowed_iaj
= tp
->avg_iaj
+ tp
->std_dev_iaj
;
502 if (allowed_iaj
< tcp_allowed_iaj
)
503 allowed_iaj
= tcp_allowed_iaj
;
505 /* Initially when the connection starts, the senders congestion
506 * window is small. During this period we avoid throttling a
507 * connection because we do not have a good starting point for
508 * allowed_iaj. IAJ_IGNORE_PKTCNT is used to quietly gloss over
509 * the first few packets.
511 if (tp
->iaj_pktcnt
> IAJ_IGNORE_PKTCNT
) {
512 if ( cur_iaj
<= allowed_iaj
) {
513 if (tp
->acc_iaj
>= 2)
514 acc_iaj
= tp
->acc_iaj
- 2;
519 acc_iaj
= tp
->acc_iaj
+ (cur_iaj
- allowed_iaj
);
522 if (acc_iaj
> MAX_ACC_IAJ
)
523 acc_iaj
= MAX_ACC_IAJ
;
524 tp
->acc_iaj
= acc_iaj
;
527 /* Compute weighted average where the history has a weight of
528 * 15 out of 16 and the current value has a weight of 1 out of 16.
529 * This will make the short-term measurements have more weight.
531 * The addition of 8 will help to round-up the value
532 * instead of round-down
534 tp
->avg_iaj
= (((tp
->avg_iaj
<< IAJ_DIV_SHIFT
) - tp
->avg_iaj
)
535 + cur_iaj
+ IAJ_ROUNDUP_CONST
) >> IAJ_DIV_SHIFT
;
537 /* Compute Root-mean-square of deviation where mean is a weighted
538 * average as described above.
540 temp
= tp
->std_dev_iaj
* tp
->std_dev_iaj
;
541 mean
= (((temp
<< IAJ_DIV_SHIFT
) - temp
)
542 + (cur_iaj_dev
* cur_iaj_dev
)
543 + IAJ_ROUNDUP_CONST
) >> IAJ_DIV_SHIFT
;
545 tp
->std_dev_iaj
= isqrt(mean
);
547 DTRACE_TCP3(iaj
, struct tcpcb
*, tp
, uint32_t, cur_iaj
,
548 uint32_t, allowed_iaj
);
552 #endif /* TRAFFIC_MGT */
555 * Perform rate limit check per connection per second
556 * tp->t_challengeack_last is the last_time diff was greater than 1sec
557 * tp->t_challengeack_count is the number of ACKs sent (within 1sec)
558 * Return TRUE if we shouldn't send the ACK due to rate limitation
559 * Return FALSE if it is still ok to send challenge ACK
562 tcp_is_ack_ratelimited(struct tcpcb
*tp
)
564 boolean_t ret
= TRUE
;
565 uint32_t now
= tcp_now
;
568 diff
= timer_diff(now
, 0, tp
->t_challengeack_last
, 0);
569 /* If it is first time or diff > 1000ms,
570 * update the challengeack_last and reset the
571 * current count of ACKs
573 if (tp
->t_challengeack_last
== 0 || diff
>= 1000) {
574 tp
->t_challengeack_last
= now
;
575 tp
->t_challengeack_count
= 0;
577 } else if (tp
->t_challengeack_count
< tcp_challengeack_limit
) {
581 /* Careful about wrap-around */
582 if (ret
== FALSE
&& (tp
->t_challengeack_count
+ 1 > 0))
583 tp
->t_challengeack_count
++;
588 /* Check if enough amount of data has been acknowledged since
589 * bw measurement was started
592 tcp_bwmeas_check(struct tcpcb
*tp
)
594 int32_t bw_meas_bytes
;
595 uint32_t bw
, bytes
, elapsed_time
;
597 if (SEQ_LEQ(tp
->snd_una
, tp
->t_bwmeas
->bw_start
))
600 bw_meas_bytes
= tp
->snd_una
- tp
->t_bwmeas
->bw_start
;
601 if ((tp
->t_flagsext
& TF_BWMEAS_INPROGRESS
) &&
602 bw_meas_bytes
>= (int32_t)(tp
->t_bwmeas
->bw_size
)) {
603 bytes
= bw_meas_bytes
;
604 elapsed_time
= tcp_now
- tp
->t_bwmeas
->bw_ts
;
605 if (elapsed_time
> 0) {
606 bw
= bytes
/ elapsed_time
;
608 if (tp
->t_bwmeas
->bw_sndbw
> 0) {
609 tp
->t_bwmeas
->bw_sndbw
=
610 (((tp
->t_bwmeas
->bw_sndbw
<< 3)
611 - tp
->t_bwmeas
->bw_sndbw
)
614 tp
->t_bwmeas
->bw_sndbw
= bw
;
617 /* Store the maximum value */
618 if (tp
->t_bwmeas
->bw_sndbw_max
== 0) {
619 tp
->t_bwmeas
->bw_sndbw_max
=
620 tp
->t_bwmeas
->bw_sndbw
;
622 tp
->t_bwmeas
->bw_sndbw_max
=
623 max(tp
->t_bwmeas
->bw_sndbw
,
624 tp
->t_bwmeas
->bw_sndbw_max
);
628 tp
->t_flagsext
&= ~(TF_BWMEAS_INPROGRESS
);
633 tcp_reass(struct tcpcb
*tp
, struct tcphdr
*th
, int *tlenp
, struct mbuf
*m
,
637 struct tseg_qent
*p
= NULL
;
638 struct tseg_qent
*nq
;
639 struct tseg_qent
*te
= NULL
;
640 struct inpcb
*inp
= tp
->t_inpcb
;
641 struct socket
*so
= inp
->inp_socket
;
644 struct mbuf
*oodata
= NULL
;
647 boolean_t cell
= IFNET_IS_CELLULAR(ifp
);
648 boolean_t wifi
= (!cell
&& IFNET_IS_WIFI(ifp
));
649 boolean_t wired
= (!wifi
&& IFNET_IS_WIRED(ifp
));
650 boolean_t dsack_set
= FALSE
;
653 * Call with th==0 after become established to
654 * force pre-ESTABLISHED data up to user socket.
660 * If the reassembly queue already has entries or if we are going
661 * to add a new one, then the connection has reached a loss state.
662 * Reset the stretch-ack algorithm at this point.
664 tcp_reset_stretch_ack(tp
);
669 #endif /* TRAFFIC_MGT */
672 * Limit the number of segments in the reassembly queue to prevent
673 * holding on to too many segments (and thus running out of mbufs).
674 * Make sure to let the missing segment through which caused this
675 * queue. Always keep one global queue entry spare to be able to
676 * process the missing segment.
678 qlimit
= min(max(100, so
->so_rcv
.sb_hiwat
>> 10),
679 (TCP_AUTORCVBUF_MAX(ifp
) >> 10));
680 if (th
->th_seq
!= tp
->rcv_nxt
&&
681 (tp
->t_reassqlen
+ 1) >= qlimit
) {
682 tcp_reass_overflows
++;
683 tcpstat
.tcps_rcvmemdrop
++;
689 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
690 te
= (struct tseg_qent
*) zalloc(tcp_reass_zone
);
692 tcpstat
.tcps_rcvmemdrop
++;
699 * Find a segment which begins after this one does.
701 LIST_FOREACH(q
, &tp
->t_segq
, tqe_q
) {
702 if (SEQ_GT(q
->tqe_th
->th_seq
, th
->th_seq
))
708 * If there is a preceding segment, it may provide some of
709 * our data already. If so, drop the data from the incoming
710 * segment. If it provides all of our data, drop us.
714 /* conversion to int (in i) handles seq wraparound */
715 i
= p
->tqe_th
->th_seq
+ p
->tqe_len
- th
->th_seq
;
717 if (TCP_DSACK_ENABLED(tp
) && i
> 1) {
719 * Note duplicate data sequnce numbers
720 * to report in DSACK option
722 tp
->t_dsack_lseq
= th
->th_seq
;
723 tp
->t_dsack_rseq
= th
->th_seq
+
727 * Report only the first part of partial/
728 * non-contiguous duplicate sequence space
733 tcpstat
.tcps_rcvduppack
++;
734 tcpstat
.tcps_rcvdupbyte
+= *tlenp
;
736 nstat_route_rx(inp
->inp_route
.ro_rt
,
738 NSTAT_RX_FLAG_DUPLICATE
);
739 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
741 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
743 tp
->t_stat
.rxduplicatebytes
+= *tlenp
;
744 inp_set_activity_bitmap(inp
);
747 zfree(tcp_reass_zone
, te
);
751 * Try to present any queued data
752 * at the left window edge to the user.
753 * This is needed after the 3-WHS
764 tcpstat
.tcps_rcvoopack
++;
765 tcpstat
.tcps_rcvoobyte
+= *tlenp
;
767 nstat_route_rx(inp
->inp_route
.ro_rt
, 1, *tlenp
,
768 NSTAT_RX_FLAG_OUT_OF_ORDER
);
769 INP_ADD_STAT(inp
, cell
, wifi
, wired
, rxpackets
, 1);
770 INP_ADD_STAT(inp
, cell
, wifi
, wired
, rxbytes
, *tlenp
);
771 tp
->t_stat
.rxoutoforderbytes
+= *tlenp
;
772 inp_set_activity_bitmap(inp
);
776 * While we overlap succeeding segments trim them or,
777 * if they are completely covered, dequeue them.
780 int i
= (th
->th_seq
+ *tlenp
) - q
->tqe_th
->th_seq
;
785 * Report only the first part of partial/non-contiguous
786 * duplicate segment in dsack option. The variable
787 * dsack_set will be true if a previous entry has some of
788 * the duplicate sequence space.
790 if (TCP_DSACK_ENABLED(tp
) && i
> 1 && !dsack_set
) {
791 if (tp
->t_dsack_lseq
== 0) {
792 tp
->t_dsack_lseq
= q
->tqe_th
->th_seq
;
794 tp
->t_dsack_lseq
+ min(i
, q
->tqe_len
);
797 * this segment overlaps data in multple
798 * entries in the reassembly queue, move
799 * the right sequence number further.
802 tp
->t_dsack_rseq
+ min(i
, q
->tqe_len
);
805 if (i
< q
->tqe_len
) {
806 q
->tqe_th
->th_seq
+= i
;
812 nq
= LIST_NEXT(q
, tqe_q
);
813 LIST_REMOVE(q
, tqe_q
);
815 zfree(tcp_reass_zone
, q
);
820 /* Insert the new segment queue entry into place. */
823 te
->tqe_len
= *tlenp
;
826 LIST_INSERT_HEAD(&tp
->t_segq
, te
, tqe_q
);
828 LIST_INSERT_AFTER(p
, te
, tqe_q
);
832 * New out-of-order data exists, and is pointed to by
833 * queue entry te. Set copy_oodata to 1 so out-of-order data
834 * can be copied off to sockbuf after in-order data
837 if (!(so
->so_state
& SS_CANTRCVMORE
))
842 * Present data to user, advancing rcv_nxt through
843 * completed sequence space.
845 if (!TCPS_HAVEESTABLISHED(tp
->t_state
))
847 q
= LIST_FIRST(&tp
->t_segq
);
848 if (!q
|| q
->tqe_th
->th_seq
!= tp
->rcv_nxt
) {
849 /* Stop using LRO once out of order packets arrive */
850 if (tp
->t_flagsext
& TF_LRO_OFFLOADED
) {
851 tcp_lro_remove_state(inp
->inp_laddr
, inp
->inp_faddr
,
852 th
->th_dport
, th
->th_sport
);
853 tp
->t_flagsext
&= ~TF_LRO_OFFLOADED
;
857 * continue processing if out-of-order data
860 if (q
&& (so
->so_flags
& SOF_ENABLE_MSGS
))
861 goto msg_unordered_delivery
;
867 * If there is already another thread doing reassembly for this
868 * connection, it is better to let it finish the job --
871 if (tp
->t_flagsext
& TF_REASS_INPROG
)
874 tp
->t_flagsext
|= TF_REASS_INPROG
;
875 /* lost packet was recovered, so ooo data can be returned */
876 tcpstat
.tcps_recovered_pkts
++;
879 tp
->rcv_nxt
+= q
->tqe_len
;
880 flags
= q
->tqe_th
->th_flags
& TH_FIN
;
881 LIST_REMOVE(q
, tqe_q
);
882 if (so
->so_state
& SS_CANTRCVMORE
) {
885 so_recv_data_stat(so
, q
->tqe_m
, 0); /* XXXX */
886 if (so
->so_flags
& SOF_ENABLE_MSGS
) {
888 * Append the inorder data as a message to the
889 * receive socket buffer. Also check to see if
890 * the data we are about to deliver is the same
891 * data that we wanted to pass up to the user
892 * out of order. If so, reset copy_oodata --
893 * the received data filled a gap, and
899 if (sbappendstream_rcvdemux(so
, q
->tqe_m
,
900 q
->tqe_th
->th_seq
- (tp
->irs
+ 1), 0))
902 if (tp
->t_flagsext
& TF_LRO_OFFLOADED
) {
903 tcp_update_lro_seq(tp
->rcv_nxt
,
904 inp
->inp_laddr
, inp
->inp_faddr
,
905 th
->th_dport
, th
->th_sport
);
908 zfree(tcp_reass_zone
, q
);
910 q
= LIST_FIRST(&tp
->t_segq
);
911 } while (q
&& q
->tqe_th
->th_seq
== tp
->rcv_nxt
);
912 tp
->t_flagsext
&= ~TF_REASS_INPROG
;
915 if ((inp
->inp_vflag
& INP_IPV6
) != 0) {
917 KERNEL_DEBUG(DBG_LAYER_BEG
,
918 ((inp
->inp_fport
<< 16) | inp
->inp_lport
),
919 (((inp
->in6p_laddr
.s6_addr16
[0] & 0xffff) << 16) |
920 (inp
->in6p_faddr
.s6_addr16
[0] & 0xffff)),
926 KERNEL_DEBUG(DBG_LAYER_BEG
,
927 ((inp
->inp_fport
<< 16) | inp
->inp_lport
),
928 (((inp
->inp_laddr
.s_addr
& 0xffff) << 16) |
929 (inp
->inp_faddr
.s_addr
& 0xffff)),
933 msg_unordered_delivery
:
934 /* Deliver out-of-order data as a message */
935 if (te
&& (so
->so_flags
& SOF_ENABLE_MSGS
) && copy_oodata
&& te
->tqe_len
) {
937 * make a copy of the mbuf to be delivered up to
938 * the user, and add it to the sockbuf
940 oodata
= m_copym(te
->tqe_m
, 0, M_COPYALL
, M_DONTWAIT
);
941 if (oodata
!= NULL
) {
942 if (sbappendmsgstream_rcv(&so
->so_rcv
, oodata
,
943 te
->tqe_th
->th_seq
- (tp
->irs
+ 1), 1)) {
945 tcpstat
.tcps_msg_unopkts
++;
947 tcpstat
.tcps_msg_unoappendfail
++;
953 sorwakeup(so
); /* done with socket lock held */
958 * Reduce congestion window -- used when ECN is seen or when a tail loss
959 * probe recovers the last packet.
962 tcp_reduce_congestion_window(
966 * If the current tcp cc module has
967 * defined a hook for tasks to run
968 * before entering FR, call it
970 if (CC_ALGO(tp
)->pre_fr
!= NULL
)
971 CC_ALGO(tp
)->pre_fr(tp
);
972 ENTER_FASTRECOVERY(tp
);
973 if (tp
->t_flags
& TF_SENTFIN
)
974 tp
->snd_recover
= tp
->snd_max
- 1;
976 tp
->snd_recover
= tp
->snd_max
;
977 tp
->t_timer
[TCPT_REXMT
] = 0;
978 tp
->t_timer
[TCPT_PTO
] = 0;
980 if (tp
->t_flagsext
& TF_CWND_NONVALIDATED
) {
981 tcp_cc_adjust_nonvalidated_cwnd(tp
);
983 tp
->snd_cwnd
= tp
->snd_ssthresh
+
984 tp
->t_maxseg
* tcprexmtthresh
;
989 * This function is called upon reception of data on a socket. It's purpose is
990 * to handle the adaptive keepalive timers that monitor whether the connection
991 * is making progress. First the adaptive read-timer, second the TFO probe-timer.
993 * The application wants to get an event if there is a stall during read.
994 * Set the initial keepalive timeout to be equal to twice RTO.
996 * If the outgoing interface is in marginal conditions, we need to
997 * enable read probes for that too.
1000 tcp_adaptive_rwtimo_check(struct tcpcb
*tp
, int tlen
)
1002 struct ifnet
*outifp
= tp
->t_inpcb
->inp_last_outifp
;
1004 if ((tp
->t_adaptive_rtimo
> 0 ||
1006 (outifp
->if_eflags
& IFEF_PROBE_CONNECTIVITY
)))
1008 tp
->t_state
== TCPS_ESTABLISHED
) {
1009 tp
->t_timer
[TCPT_KEEP
] = OFFSET_FROM_START(tp
,
1010 (TCP_REXMTVAL(tp
) << 1));
1011 tp
->t_flagsext
|= TF_DETECT_READSTALL
;
1012 tp
->t_rtimo_probes
= 0;
1017 tcp_keepalive_reset(struct tcpcb
*tp
)
1019 tp
->t_timer
[TCPT_KEEP
] = OFFSET_FROM_START(tp
,
1020 TCP_CONN_KEEPIDLE(tp
));
1021 tp
->t_flagsext
&= ~(TF_DETECT_READSTALL
);
1022 tp
->t_rtimo_probes
= 0;
1026 * TCP input routine, follows pages 65-76 of the
1027 * protocol specification dated September, 1981 very closely.
1031 tcp6_input(struct mbuf
**mp
, int *offp
, int proto
)
1033 #pragma unused(proto)
1034 struct mbuf
*m
= *mp
;
1036 struct ifnet
*ifp
= m
->m_pkthdr
.rcvif
;
1038 IP6_EXTHDR_CHECK(m
, *offp
, sizeof(struct tcphdr
), return IPPROTO_DONE
);
1040 /* Expect 32-bit aligned data pointer on strict-align platforms */
1041 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m
);
1044 * draft-itojun-ipv6-tcp-to-anycast
1045 * better place to put this in?
1047 if (ip6_getdstifaddr_info(m
, NULL
, &ia6_flags
) == 0) {
1048 if (ia6_flags
& IN6_IFF_ANYCAST
) {
1049 struct ip6_hdr
*ip6
;
1051 ip6
= mtod(m
, struct ip6_hdr
*);
1052 icmp6_error(m
, ICMP6_DST_UNREACH
,
1053 ICMP6_DST_UNREACH_ADDR
,
1054 (caddr_t
)&ip6
->ip6_dst
- (caddr_t
)ip6
);
1056 IF_TCP_STATINC(ifp
, icmp6unreach
);
1058 return (IPPROTO_DONE
);
1062 tcp_input(m
, *offp
);
1063 return (IPPROTO_DONE
);
1067 /* Depending on the usage of mbuf space in the system, this function
1068 * will return true or false. This is used to determine if a socket
1069 * buffer can take more memory from the system for auto-tuning or not.
1072 tcp_cansbgrow(struct sockbuf
*sb
)
1074 /* Calculate the host level space limit in terms of MSIZE buffers.
1075 * We can use a maximum of half of the available mbuf space for
1078 u_int32_t mblim
= ((nmbclusters
>> 1) << (MCLSHIFT
- MSIZESHIFT
));
1080 /* Calculate per sb limit in terms of bytes. We optimize this limit
1081 * for upto 16 socket buffers.
1084 u_int32_t sbspacelim
= ((nmbclusters
>> 4) << MCLSHIFT
);
1086 if ((total_sbmb_cnt
< mblim
) &&
1087 (sb
->sb_hiwat
< sbspacelim
)) {
1090 OSIncrementAtomic64(&sbmb_limreached
);
1096 tcp_sbrcv_reserve(struct tcpcb
*tp
, struct sockbuf
*sbrcv
,
1097 u_int32_t newsize
, u_int32_t idealsize
, u_int32_t rcvbuf_max
)
1099 /* newsize should not exceed max */
1100 newsize
= min(newsize
, rcvbuf_max
);
1102 /* The receive window scale negotiated at the
1103 * beginning of the connection will also set a
1104 * limit on the socket buffer size
1106 newsize
= min(newsize
, TCP_MAXWIN
<< tp
->rcv_scale
);
1108 /* Set new socket buffer size */
1109 if (newsize
> sbrcv
->sb_hiwat
&&
1110 (sbreserve(sbrcv
, newsize
) == 1)) {
1111 sbrcv
->sb_idealsize
= min(max(sbrcv
->sb_idealsize
,
1112 (idealsize
!= 0) ? idealsize
: newsize
), rcvbuf_max
);
1114 /* Again check the limit set by the advertised
1117 sbrcv
->sb_idealsize
= min(sbrcv
->sb_idealsize
,
1118 TCP_MAXWIN
<< tp
->rcv_scale
);
1123 * This function is used to grow a receive socket buffer. It
1124 * will take into account system-level memory usage and the
1125 * bandwidth available on the link to make a decision.
1128 tcp_sbrcv_grow(struct tcpcb
*tp
, struct sockbuf
*sbrcv
,
1129 struct tcpopt
*to
, u_int32_t pktlen
, u_int32_t rcvbuf_max
)
1131 struct socket
*so
= sbrcv
->sb_so
;
1134 * Do not grow the receive socket buffer if
1135 * - auto resizing is disabled, globally or on this socket
1136 * - the high water mark already reached the maximum
1137 * - the stream is in background and receive side is being
1139 * - if there are segments in reassembly queue indicating loss,
1140 * do not need to increase recv window during recovery as more
1141 * data is not going to be sent. A duplicate ack sent during
1142 * recovery should not change the receive window
1144 if (tcp_do_autorcvbuf
== 0 ||
1145 (sbrcv
->sb_flags
& SB_AUTOSIZE
) == 0 ||
1146 tcp_cansbgrow(sbrcv
) == 0 ||
1147 sbrcv
->sb_hiwat
>= rcvbuf_max
||
1148 (tp
->t_flagsext
& TF_RECV_THROTTLE
) ||
1149 (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
) ||
1150 !LIST_EMPTY(&tp
->t_segq
)) {
1151 /* Can not resize the socket buffer, just return */
1155 if (TSTMP_GT(tcp_now
,
1156 tp
->rfbuf_ts
+ TCPTV_RCVBUFIDLE
)) {
1157 /* If there has been an idle period in the
1158 * connection, just restart the measurement
1163 if (!TSTMP_SUPPORTED(tp
)) {
1165 * Timestamp option is not supported on this connection.
1166 * If the connection reached a state to indicate that
1167 * the receive socket buffer needs to grow, increase
1168 * the high water mark.
1170 if (TSTMP_GEQ(tcp_now
,
1171 tp
->rfbuf_ts
+ TCPTV_RCVNOTS_QUANTUM
)) {
1172 if (tp
->rfbuf_cnt
>= TCP_RCVNOTS_BYTELEVEL
) {
1173 tcp_sbrcv_reserve(tp
, sbrcv
,
1174 tcp_autorcvbuf_max
, 0,
1175 tcp_autorcvbuf_max
);
1179 tp
->rfbuf_cnt
+= pktlen
;
1182 } else if (to
->to_tsecr
!= 0) {
1184 * If the timestamp shows that one RTT has
1185 * completed, we can stop counting the
1186 * bytes. Here we consider increasing
1187 * the socket buffer if the bandwidth measured in
1188 * last rtt, is more than half of sb_hiwat, this will
1189 * help to scale the buffer according to the bandwidth
1192 if (TSTMP_GEQ(to
->to_tsecr
, tp
->rfbuf_ts
)) {
1193 if (tp
->rfbuf_cnt
> (sbrcv
->sb_hiwat
-
1194 (sbrcv
->sb_hiwat
>> 1))) {
1195 int32_t rcvbuf_inc
, min_incr
;
1197 * Increment the receive window by a
1198 * multiple of maximum sized segments.
1199 * This will prevent a connection from
1200 * sending smaller segments on wire if it
1201 * is limited by the receive window.
1203 * Set the ideal size based on current
1204 * bandwidth measurements. We set the
1205 * ideal size on receive socket buffer to
1206 * be twice the bandwidth delay product.
1208 rcvbuf_inc
= (tp
->rfbuf_cnt
<< 1)
1212 * Make the increment equal to 8 segments
1215 min_incr
= tp
->t_maxseg
<< tcp_autorcvbuf_inc_shift
;
1216 if (rcvbuf_inc
< min_incr
)
1217 rcvbuf_inc
= min_incr
;
1220 (rcvbuf_inc
/ tp
->t_maxseg
) * tp
->t_maxseg
;
1221 tcp_sbrcv_reserve(tp
, sbrcv
,
1222 sbrcv
->sb_hiwat
+ rcvbuf_inc
,
1223 (tp
->rfbuf_cnt
* 2), rcvbuf_max
);
1225 /* Measure instantaneous receive bandwidth */
1226 if (tp
->t_bwmeas
!= NULL
&& tp
->rfbuf_cnt
> 0 &&
1227 TSTMP_GT(tcp_now
, tp
->rfbuf_ts
)) {
1229 rcv_bw
= tp
->rfbuf_cnt
/
1230 (int)(tcp_now
- tp
->rfbuf_ts
);
1231 if (tp
->t_bwmeas
->bw_rcvbw_max
== 0) {
1232 tp
->t_bwmeas
->bw_rcvbw_max
= rcv_bw
;
1234 tp
->t_bwmeas
->bw_rcvbw_max
= max(
1235 tp
->t_bwmeas
->bw_rcvbw_max
, rcv_bw
);
1240 tp
->rfbuf_cnt
+= pktlen
;
1245 /* Restart the measurement */
1251 /* This function will trim the excess space added to the socket buffer
1252 * to help a slow-reading app. The ideal-size of a socket buffer depends
1253 * on the link bandwidth or it is set by an application and we aim to
1257 tcp_sbrcv_trim(struct tcpcb
*tp
, struct sockbuf
*sbrcv
)
1259 if (tcp_do_autorcvbuf
== 1 && sbrcv
->sb_idealsize
> 0 &&
1260 sbrcv
->sb_hiwat
> sbrcv
->sb_idealsize
) {
1262 /* compute the difference between ideal and current sizes */
1263 u_int32_t diff
= sbrcv
->sb_hiwat
- sbrcv
->sb_idealsize
;
1265 /* Compute the maximum advertised window for
1268 u_int32_t advwin
= tp
->rcv_adv
- tp
->rcv_nxt
;
1270 /* How much can we trim the receive socket buffer?
1271 * 1. it can not be trimmed beyond the max rcv win advertised
1272 * 2. if possible, leave 1/16 of bandwidth*delay to
1273 * avoid closing the win completely
1275 u_int32_t leave
= max(advwin
, (sbrcv
->sb_idealsize
>> 4));
1277 /* Sometimes leave can be zero, in that case leave at least
1278 * a few segments worth of space.
1281 leave
= tp
->t_maxseg
<< tcp_autorcvbuf_inc_shift
;
1283 trim
= sbrcv
->sb_hiwat
- (sbrcv
->sb_cc
+ leave
);
1284 trim
= imin(trim
, (int32_t)diff
);
1287 sbreserve(sbrcv
, (sbrcv
->sb_hiwat
- trim
));
1291 /* We may need to trim the send socket buffer size for two reasons:
1292 * 1. if the rtt seen on the connection is climbing up, we do not
1293 * want to fill the buffers any more.
1294 * 2. if the congestion win on the socket backed off, there is no need
1295 * to hold more mbufs for that connection than what the cwnd will allow.
1298 tcp_sbsnd_trim(struct sockbuf
*sbsnd
)
1300 if (tcp_do_autosendbuf
== 1 &&
1301 ((sbsnd
->sb_flags
& (SB_AUTOSIZE
| SB_TRIM
)) ==
1302 (SB_AUTOSIZE
| SB_TRIM
)) &&
1303 (sbsnd
->sb_idealsize
> 0) &&
1304 (sbsnd
->sb_hiwat
> sbsnd
->sb_idealsize
)) {
1306 if (sbsnd
->sb_cc
<= sbsnd
->sb_idealsize
) {
1307 trim
= sbsnd
->sb_hiwat
- sbsnd
->sb_idealsize
;
1309 trim
= sbsnd
->sb_hiwat
- sbsnd
->sb_cc
;
1311 sbreserve(sbsnd
, (sbsnd
->sb_hiwat
- trim
));
1313 if (sbsnd
->sb_hiwat
<= sbsnd
->sb_idealsize
)
1314 sbsnd
->sb_flags
&= ~(SB_TRIM
);
1318 * If timestamp option was not negotiated on this connection
1319 * and this connection is on the receiving side of a stream
1320 * then we can not measure the delay on the link accurately.
1321 * Instead of enabling automatic receive socket buffer
1322 * resizing, just give more space to the receive socket buffer.
1325 tcp_sbrcv_tstmp_check(struct tcpcb
*tp
)
1327 struct socket
*so
= tp
->t_inpcb
->inp_socket
;
1328 u_int32_t newsize
= 2 * tcp_recvspace
;
1329 struct sockbuf
*sbrcv
= &so
->so_rcv
;
1331 if ((tp
->t_flags
& (TF_REQ_TSTMP
| TF_RCVD_TSTMP
)) !=
1332 (TF_REQ_TSTMP
| TF_RCVD_TSTMP
) &&
1333 (sbrcv
->sb_flags
& SB_AUTOSIZE
) != 0) {
1334 tcp_sbrcv_reserve(tp
, sbrcv
, newsize
, 0, newsize
);
1338 /* A receiver will evaluate the flow of packets on a connection
1339 * to see if it can reduce ack traffic. The receiver will start
1340 * stretching acks if all of the following conditions are met:
1341 * 1. tcp_delack_enabled is set to 3
1342 * 2. If the bytes received in the last 100ms is greater than a threshold
1343 * defined by maxseg_unacked
1344 * 3. If the connection has not been idle for tcp_maxrcvidle period.
1345 * 4. If the connection has seen enough packets to let the slow-start
1346 * finish after connection establishment or after some packet loss.
1348 * The receiver will stop stretching acks if there is congestion/reordering
1349 * as indicated by packets on reassembly queue or an ECN. If the delayed-ack
1350 * timer fires while stretching acks, it means that the packet flow has gone
1351 * below the threshold defined by maxseg_unacked and the receiver will stop
1352 * stretching acks. The receiver gets no indication when slow-start is completed
1353 * or when the connection reaches an idle state. That is why we use
1354 * tcp_rcvsspktcnt to cover slow-start and tcp_maxrcvidle to identify idle
1358 tcp_stretch_ack_enable(struct tcpcb
*tp
, int thflags
)
1360 if (tp
->rcv_by_unackwin
>= (maxseg_unacked
* tp
->t_maxseg
) &&
1361 TSTMP_GEQ(tp
->rcv_unackwin
, tcp_now
))
1362 tp
->t_flags
|= TF_STREAMING_ON
;
1364 tp
->t_flags
&= ~TF_STREAMING_ON
;
1366 /* If there has been an idle time, reset streaming detection */
1367 if (TSTMP_GT(tcp_now
, tp
->rcv_unackwin
+ tcp_maxrcvidle
))
1368 tp
->t_flags
&= ~TF_STREAMING_ON
;
1371 * If there are flags other than TH_ACK set, reset streaming
1374 if (thflags
& ~TH_ACK
)
1375 tp
->t_flags
&= ~TF_STREAMING_ON
;
1377 if (tp
->t_flagsext
& TF_DISABLE_STRETCHACK
) {
1378 if (tp
->rcv_nostrack_pkts
>= TCP_STRETCHACK_ENABLE_PKTCNT
) {
1379 tp
->t_flagsext
&= ~TF_DISABLE_STRETCHACK
;
1380 tp
->rcv_nostrack_pkts
= 0;
1381 tp
->rcv_nostrack_ts
= 0;
1383 tp
->rcv_nostrack_pkts
++;
1387 if (!(tp
->t_flagsext
& (TF_NOSTRETCHACK
|TF_DISABLE_STRETCHACK
)) &&
1388 (tp
->t_flags
& TF_STREAMING_ON
) &&
1389 (!(tp
->t_flagsext
& TF_RCVUNACK_WAITSS
) ||
1390 (tp
->rcv_waitforss
>= tcp_rcvsspktcnt
))) {
1398 * Reset the state related to stretch-ack algorithm. This will make
1399 * the receiver generate an ack every other packet. The receiver
1400 * will start re-evaluating the rate at which packets come to decide
1401 * if it can benefit by lowering the ack traffic.
1404 tcp_reset_stretch_ack(struct tcpcb
*tp
)
1406 tp
->t_flags
&= ~(TF_STRETCHACK
|TF_STREAMING_ON
);
1407 tp
->rcv_by_unackwin
= 0;
1408 tp
->rcv_unackwin
= tcp_now
+ tcp_rcvunackwin
;
1411 * When there is packet loss or packet re-ordering or CWR due to
1412 * ECN, the sender's congestion window is reduced. In these states,
1413 * generate an ack for every other packet for some time to allow
1414 * the sender's congestion window to grow.
1416 tp
->t_flagsext
|= TF_RCVUNACK_WAITSS
;
1417 tp
->rcv_waitforss
= 0;
1421 * The last packet was a retransmission, check if this ack
1422 * indicates that the retransmission was spurious.
1424 * If the connection supports timestamps, we could use it to
1425 * detect if the last retransmit was not needed. Otherwise,
1426 * we check if the ACK arrived within RTT/2 window, then it
1427 * was a mistake to do the retransmit in the first place.
1429 * This function will return 1 if it is a spurious retransmit,
1433 tcp_detect_bad_rexmt(struct tcpcb
*tp
, struct tcphdr
*th
,
1434 struct tcpopt
*to
, u_int32_t rxtime
)
1436 int32_t tdiff
, bad_rexmt_win
;
1437 bad_rexmt_win
= (tp
->t_srtt
>> (TCP_RTT_SHIFT
+ 1));
1439 /* If the ack has ECN CE bit, then cwnd has to be adjusted */
1440 if (TCP_ECN_ENABLED(tp
) && (th
->th_flags
& TH_ECE
))
1442 if (TSTMP_SUPPORTED(tp
)) {
1443 if (rxtime
> 0 && (to
->to_flags
& TOF_TS
)
1444 && to
->to_tsecr
!= 0
1445 && TSTMP_LT(to
->to_tsecr
, rxtime
))
1448 if ((tp
->t_rxtshift
== 1
1449 || (tp
->t_flagsext
& TF_SENT_TLPROBE
))
1451 tdiff
= (int32_t)(tcp_now
- rxtime
);
1452 if (tdiff
< bad_rexmt_win
)
1461 * Restore congestion window state if a spurious timeout
1465 tcp_bad_rexmt_restore_state(struct tcpcb
*tp
, struct tcphdr
*th
)
1467 if (TSTMP_SUPPORTED(tp
)) {
1468 u_int32_t fsize
, acked
;
1469 fsize
= tp
->snd_max
- th
->th_ack
;
1470 acked
= BYTES_ACKED(th
, tp
);
1473 * Implement bad retransmit recovery as
1474 * described in RFC 4015.
1476 tp
->snd_ssthresh
= tp
->snd_ssthresh_prev
;
1478 /* Initialize cwnd to the initial window */
1479 if (CC_ALGO(tp
)->cwnd_init
!= NULL
)
1480 CC_ALGO(tp
)->cwnd_init(tp
);
1482 tp
->snd_cwnd
= fsize
+ min(acked
, tp
->snd_cwnd
);
1485 tp
->snd_cwnd
= tp
->snd_cwnd_prev
;
1486 tp
->snd_ssthresh
= tp
->snd_ssthresh_prev
;
1487 if (tp
->t_flags
& TF_WASFRECOVERY
)
1488 ENTER_FASTRECOVERY(tp
);
1490 /* Do not use the loss flight size in this case */
1491 tp
->t_lossflightsize
= 0;
1493 tp
->snd_cwnd
= max(tp
->snd_cwnd
, TCP_CC_CWND_INIT_BYTES
);
1494 tp
->snd_recover
= tp
->snd_recover_prev
;
1495 tp
->snd_nxt
= tp
->snd_max
;
1497 /* Fix send socket buffer to reflect the change in cwnd */
1498 tcp_bad_rexmt_fix_sndbuf(tp
);
1501 * This RTT might reflect the extra delay induced
1502 * by the network. Skip using this sample for RTO
1503 * calculation and mark the connection so we can
1504 * recompute RTT when the next eligible sample is
1507 tp
->t_flagsext
|= TF_RECOMPUTE_RTT
;
1508 tp
->t_badrexmt_time
= tcp_now
;
1513 * If the previous packet was sent in retransmission timer, and it was
1514 * not needed, then restore the congestion window to the state before that
1517 * If the last packet was sent in tail loss probe timeout, check if that
1518 * recovered the last packet. If so, that will indicate a real loss and
1519 * the congestion window needs to be lowered.
1522 tcp_bad_rexmt_check(struct tcpcb
*tp
, struct tcphdr
*th
, struct tcpopt
*to
)
1524 if (tp
->t_rxtshift
> 0 &&
1525 tcp_detect_bad_rexmt(tp
, th
, to
, tp
->t_rxtstart
)) {
1526 ++tcpstat
.tcps_sndrexmitbad
;
1527 tcp_bad_rexmt_restore_state(tp
, th
);
1528 tcp_ccdbg_trace(tp
, th
, TCP_CC_BAD_REXMT_RECOVERY
);
1529 } else if ((tp
->t_flagsext
& TF_SENT_TLPROBE
)
1530 && tp
->t_tlphighrxt
> 0
1531 && SEQ_GEQ(th
->th_ack
, tp
->t_tlphighrxt
)
1532 && !tcp_detect_bad_rexmt(tp
, th
, to
, tp
->t_tlpstart
)) {
1534 * check DSACK information also to make sure that
1535 * the TLP was indeed needed
1537 if (tcp_rxtseg_dsack_for_tlp(tp
)) {
1539 * received a DSACK to indicate that TLP was
1542 tcp_rxtseg_clean(tp
);
1547 * The tail loss probe recovered the last packet and
1548 * we need to adjust the congestion window to take
1549 * this loss into account.
1551 ++tcpstat
.tcps_tlp_recoverlastpkt
;
1552 if (!IN_FASTRECOVERY(tp
)) {
1553 tcp_reduce_congestion_window(tp
);
1554 EXIT_FASTRECOVERY(tp
);
1556 tcp_ccdbg_trace(tp
, th
, TCP_CC_TLP_RECOVER_LASTPACKET
);
1557 } else if (tcp_rxtseg_detect_bad_rexmt(tp
, th
->th_ack
)) {
1559 * All of the retransmitted segments were duplicated, this
1560 * can be an indication of bad fast retransmit.
1562 tcpstat
.tcps_dsack_badrexmt
++;
1563 tcp_bad_rexmt_restore_state(tp
, th
);
1564 tcp_ccdbg_trace(tp
, th
, TCP_CC_DSACK_BAD_REXMT
);
1565 tcp_rxtseg_clean(tp
);
1568 tp
->t_flagsext
&= ~(TF_SENT_TLPROBE
);
1569 tp
->t_tlphighrxt
= 0;
1573 * check if the latest ack was for a segment sent during PMTU
1574 * blackhole detection. If the timestamp on the ack is before
1575 * PMTU blackhole detection, then revert the size of the max
1576 * segment to previous size.
1578 if (tp
->t_rxtshift
> 0 && (tp
->t_flags
& TF_BLACKHOLE
) &&
1579 tp
->t_pmtud_start_ts
> 0 && TSTMP_SUPPORTED(tp
)) {
1580 if ((to
->to_flags
& TOF_TS
) && to
->to_tsecr
!= 0
1581 && TSTMP_LT(to
->to_tsecr
, tp
->t_pmtud_start_ts
)) {
1582 tcp_pmtud_revert_segment_size(tp
);
1585 if (tp
->t_pmtud_start_ts
> 0)
1586 tp
->t_pmtud_start_ts
= 0;
1590 * Check if early retransmit can be attempted according to RFC 5827.
1592 * If packet reordering is detected on a connection, fast recovery will
1593 * be delayed until it is clear that the packet was lost and not reordered.
1594 * But reordering detection is done only when SACK is enabled.
1596 * On connections that do not support SACK, there is a limit on the number
1597 * of early retransmits that can be done per minute. This limit is needed
1598 * to make sure that too many packets are not retransmitted when there is
1599 * packet reordering.
1602 tcp_early_rexmt_check (struct tcpcb
*tp
, struct tcphdr
*th
)
1604 u_int32_t obytes
, snd_off
;
1606 struct socket
*so
= tp
->t_inpcb
->inp_socket
;
1608 if (early_rexmt
&& (SACK_ENABLED(tp
) ||
1609 tp
->t_early_rexmt_count
< TCP_EARLY_REXMT_LIMIT
) &&
1610 SEQ_GT(tp
->snd_max
, tp
->snd_una
) &&
1611 (tp
->t_dupacks
== 1 ||
1612 (SACK_ENABLED(tp
) &&
1613 !TAILQ_EMPTY(&tp
->snd_holes
)))) {
1615 * If there are only a few outstanding
1616 * segments on the connection, we might need
1617 * to lower the retransmit threshold. This
1618 * will allow us to do Early Retransmit as
1619 * described in RFC 5827.
1621 if (SACK_ENABLED(tp
) &&
1622 !TAILQ_EMPTY(&tp
->snd_holes
)) {
1623 obytes
= (tp
->snd_max
- tp
->snd_fack
) +
1624 tp
->sackhint
.sack_bytes_rexmit
;
1626 obytes
= (tp
->snd_max
- tp
->snd_una
);
1630 * In order to lower retransmit threshold the
1631 * following two conditions must be met.
1632 * 1. the amount of outstanding data is less
1634 * 2. there is no unsent data ready for
1635 * transmission or the advertised window
1636 * will limit sending new segments.
1638 snd_off
= tp
->snd_max
- tp
->snd_una
;
1639 snd_len
= min(so
->so_snd
.sb_cc
, tp
->snd_wnd
) - snd_off
;
1640 if (obytes
< (tp
->t_maxseg
<< 2) &&
1644 osegs
= obytes
/ tp
->t_maxseg
;
1645 if ((osegs
* tp
->t_maxseg
) < obytes
)
1649 * Since the connection might have already
1650 * received some dupacks, we add them to
1651 * to the outstanding segments count to get
1652 * the correct retransmit threshold.
1654 * By checking for early retransmit after
1655 * receiving some duplicate acks when SACK
1656 * is supported, the connection will
1657 * enter fast recovery even if multiple
1658 * segments are lost in the same window.
1660 osegs
+= tp
->t_dupacks
;
1663 ((osegs
- 1) > 1) ? (osegs
- 1) : 1;
1665 min(tp
->t_rexmtthresh
, tcprexmtthresh
);
1667 max(tp
->t_rexmtthresh
, tp
->t_dupacks
);
1669 if (tp
->t_early_rexmt_count
== 0)
1670 tp
->t_early_rexmt_win
= tcp_now
;
1672 if (tp
->t_flagsext
& TF_SENT_TLPROBE
) {
1673 tcpstat
.tcps_tlp_recovery
++;
1674 tcp_ccdbg_trace(tp
, th
,
1675 TCP_CC_TLP_RECOVERY
);
1677 tcpstat
.tcps_early_rexmt
++;
1678 tp
->t_early_rexmt_count
++;
1679 tcp_ccdbg_trace(tp
, th
,
1680 TCP_CC_EARLY_RETRANSMIT
);
1687 * If we ever sent a TLP probe, the acknowledgement will trigger
1688 * early retransmit because the value of snd_fack will be close
1689 * to snd_max. This will take care of adjustments to the
1690 * congestion window. So we can reset TF_SENT_PROBE flag.
1692 tp
->t_flagsext
&= ~(TF_SENT_TLPROBE
);
1693 tp
->t_tlphighrxt
= 0;
1698 tcp_tfo_syn(struct tcpcb
*tp
, struct tcpopt
*to
)
1700 u_char out
[CCAES_BLOCK_SIZE
];
1703 if (!(to
->to_flags
& (TOF_TFO
| TOF_TFOREQ
)) ||
1704 !(tcp_fastopen
& TCP_FASTOPEN_SERVER
))
1707 if ((to
->to_flags
& TOF_TFOREQ
)) {
1708 tp
->t_tfo_flags
|= TFO_F_OFFER_COOKIE
;
1710 tp
->t_tfo_stats
|= TFO_S_COOKIEREQ_RECV
;
1711 tcpstat
.tcps_tfo_cookie_req_rcv
++;
1715 /* Ok, then it must be an offered cookie. We need to check that ... */
1716 tcp_tfo_gen_cookie(tp
->t_inpcb
, out
, sizeof(out
));
1718 len
= *to
->to_tfo
- TCPOLEN_FASTOPEN_REQ
;
1720 if (memcmp(out
, to
->to_tfo
, len
)) {
1721 /* Cookies are different! Let's return and offer a new cookie */
1722 tp
->t_tfo_flags
|= TFO_F_OFFER_COOKIE
;
1724 tp
->t_tfo_stats
|= TFO_S_COOKIE_INVALID
;
1725 tcpstat
.tcps_tfo_cookie_invalid
++;
1729 if (OSIncrementAtomic(&tcp_tfo_halfcnt
) >= tcp_tfo_backlog
) {
1730 /* Need to decrement again as we just increased it... */
1731 OSDecrementAtomic(&tcp_tfo_halfcnt
);
1735 tp
->t_tfo_flags
|= TFO_F_COOKIE_VALID
;
1737 tp
->t_tfo_stats
|= TFO_S_SYNDATA_RCV
;
1738 tcpstat
.tcps_tfo_syn_data_rcv
++;
1744 tcp_tfo_synack(struct tcpcb
*tp
, struct tcpopt
*to
)
1746 if (to
->to_flags
& TOF_TFO
) {
1747 unsigned char len
= *to
->to_tfo
- TCPOLEN_FASTOPEN_REQ
;
1750 * If this happens, things have gone terribly wrong. len should
1751 * have been checked in tcp_dooptions.
1753 VERIFY(len
<= TFO_COOKIE_LEN_MAX
);
1757 tcp_cache_set_cookie(tp
, to
->to_tfo
, len
);
1758 tcp_heuristic_tfo_success(tp
);
1760 tp
->t_tfo_stats
|= TFO_S_COOKIE_RCV
;
1761 tcpstat
.tcps_tfo_cookie_rcv
++;
1762 if (tp
->t_tfo_flags
& TFO_F_COOKIE_SENT
) {
1763 tcpstat
.tcps_tfo_cookie_wrong
++;
1764 tp
->t_tfo_stats
|= TFO_S_COOKIE_WRONG
;
1768 * Thus, no cookie in the response, but we either asked for one
1769 * or sent SYN+DATA. Now, we need to check whether we had to
1770 * rexmit the SYN. If that's the case, it's better to start
1771 * backing of TFO-cookie requests.
1773 if (tp
->t_tfo_flags
& TFO_F_SYN_LOSS
) {
1774 tp
->t_tfo_stats
|= TFO_S_SYN_LOSS
;
1775 tcpstat
.tcps_tfo_syn_loss
++;
1777 tcp_heuristic_tfo_loss(tp
);
1779 if (tp
->t_tfo_flags
& TFO_F_COOKIE_REQ
) {
1780 tp
->t_tfo_stats
|= TFO_S_NO_COOKIE_RCV
;
1781 tcpstat
.tcps_tfo_no_cookie_rcv
++;
1784 tcp_heuristic_tfo_success(tp
);
1790 tcp_tfo_rcv_probe(struct tcpcb
*tp
, int tlen
)
1795 tp
->t_tfo_probe_state
= TFO_PROBE_PROBING
;
1798 * We send the probe out rather quickly (after one RTO). It does not
1799 * really hurt that much, it's only one additional segment on the wire.
1801 tp
->t_timer
[TCPT_KEEP
] = OFFSET_FROM_START(tp
, (TCP_REXMTVAL(tp
)));
1805 tcp_tfo_rcv_data(struct tcpcb
*tp
)
1807 /* Transition from PROBING to NONE as data has been received */
1808 if (tp
->t_tfo_probe_state
>= TFO_PROBE_PROBING
)
1809 tp
->t_tfo_probe_state
= TFO_PROBE_NONE
;
1813 tcp_tfo_rcv_ack(struct tcpcb
*tp
, struct tcphdr
*th
)
1815 if (tp
->t_tfo_probe_state
== TFO_PROBE_PROBING
&&
1816 tp
->t_tfo_probes
> 0) {
1817 if (th
->th_seq
== tp
->rcv_nxt
) {
1818 /* No hole, so stop probing */
1819 tp
->t_tfo_probe_state
= TFO_PROBE_NONE
;
1820 } else if (SEQ_GT(th
->th_seq
, tp
->rcv_nxt
)) {
1821 /* There is a hole! Wait a bit for data... */
1822 tp
->t_tfo_probe_state
= TFO_PROBE_WAIT_DATA
;
1823 tp
->t_timer
[TCPT_KEEP
] = OFFSET_FROM_START(tp
,
1830 * Update snd_wnd information.
1833 tcp_update_window(struct tcpcb
*tp
, int thflags
, struct tcphdr
* th
,
1834 u_int32_t tiwin
, int tlen
)
1836 /* Don't look at the window if there is no ACK flag */
1837 if ((thflags
& TH_ACK
) &&
1838 (SEQ_LT(tp
->snd_wl1
, th
->th_seq
) ||
1839 (tp
->snd_wl1
== th
->th_seq
&& (SEQ_LT(tp
->snd_wl2
, th
->th_ack
) ||
1840 (tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
))))) {
1841 /* keep track of pure window updates */
1843 tp
->snd_wl2
== th
->th_ack
&& tiwin
> tp
->snd_wnd
)
1844 tcpstat
.tcps_rcvwinupd
++;
1845 tp
->snd_wnd
= tiwin
;
1846 tp
->snd_wl1
= th
->th_seq
;
1847 tp
->snd_wl2
= th
->th_ack
;
1848 if (tp
->snd_wnd
> tp
->max_sndwnd
)
1849 tp
->max_sndwnd
= tp
->snd_wnd
;
1851 if (tp
->t_inpcb
->inp_socket
->so_flags
& SOF_MP_SUBFLOW
)
1852 mptcp_update_window_wakeup(tp
);
1859 tcp_input(struct mbuf
*m
, int off0
)
1862 struct ip
*ip
= NULL
;
1864 u_char
*optp
= NULL
;
1868 struct tcpcb
*tp
= 0;
1870 struct socket
*so
= 0;
1871 int todrop
, acked
, ourfinisacked
, needoutput
= 0;
1872 struct in_addr laddr
;
1874 struct in6_addr laddr6
;
1877 int iss
= 0, nosock
= 0;
1878 u_int32_t tiwin
, sack_bytes_acked
= 0;
1879 struct tcpopt to
; /* options in this segment */
1884 struct sockaddr_in
*next_hop
= NULL
;
1885 struct m_tag
*fwd_tag
;
1886 #endif /* IPFIREWALL */
1887 u_char ip_ecn
= IPTOS_ECN_NOTECT
;
1888 unsigned int ifscope
;
1889 uint8_t isconnected
, isdisconnected
;
1890 struct ifnet
*ifp
= m
->m_pkthdr
.rcvif
;
1891 int pktf_sw_lro_pkt
= (m
->m_pkthdr
.pkt_flags
& PKTF_SW_LRO_PKT
) ? 1 : 0;
1892 int nlropkts
= (pktf_sw_lro_pkt
== 1) ? m
->m_pkthdr
.lro_npkts
: 1;
1893 int turnoff_lro
= 0, win
;
1895 struct mptcb
*mp_tp
= NULL
;
1897 boolean_t cell
= IFNET_IS_CELLULAR(ifp
);
1898 boolean_t wifi
= (!cell
&& IFNET_IS_WIFI(ifp
));
1899 boolean_t wired
= (!wifi
&& IFNET_IS_WIRED(ifp
));
1900 boolean_t recvd_dsack
= FALSE
;
1901 struct tcp_respond_args tra
;
1903 #define TCP_INC_VAR(stat, npkts) do { \
1907 TCP_INC_VAR(tcpstat
.tcps_rcvtotal
, nlropkts
);
1909 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
1910 if (!SLIST_EMPTY(&m
->m_pkthdr
.tags
)) {
1911 fwd_tag
= m_tag_locate(m
, KERNEL_MODULE_TAG_ID
,
1912 KERNEL_TAG_TYPE_IPFORWARD
, NULL
);
1916 if (fwd_tag
!= NULL
) {
1917 struct ip_fwd_tag
*ipfwd_tag
=
1918 (struct ip_fwd_tag
*)(fwd_tag
+1);
1920 next_hop
= ipfwd_tag
->next_hop
;
1921 m_tag_delete(m
, fwd_tag
);
1923 #endif /* IPFIREWALL */
1926 struct ip6_hdr
*ip6
= NULL
;
1929 int rstreason
; /* For badport_bandlim accounting purposes */
1930 struct proc
*proc0
=current_proc();
1932 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_START
,0,0,0,0,0);
1935 isipv6
= (mtod(m
, struct ip
*)->ip_v
== 6) ? 1 : 0;
1937 bzero((char *)&to
, sizeof(to
));
1942 * Expect 32-bit aligned data pointer on
1943 * strict-align platforms
1945 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m
);
1947 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
1948 ip6
= mtod(m
, struct ip6_hdr
*);
1949 tlen
= sizeof(*ip6
) + ntohs(ip6
->ip6_plen
) - off0
;
1950 th
= (struct tcphdr
*)(void *)((caddr_t
)ip6
+ off0
);
1952 if (tcp_input_checksum(AF_INET6
, m
, th
, off0
, tlen
))
1955 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
1956 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
1957 th
->th_seq
, th
->th_ack
, th
->th_win
);
1959 * Be proactive about unspecified IPv6 address in source.
1960 * As we use all-zero to indicate unbounded/unconnected pcb,
1961 * unspecified IPv6 address can be used to confuse us.
1963 * Note that packets with unspecified IPv6 destination is
1964 * already dropped in ip6_input.
1966 if (IN6_IS_ADDR_UNSPECIFIED(&ip6
->ip6_src
)) {
1968 IF_TCP_STATINC(ifp
, unspecv6
);
1971 DTRACE_TCP5(receive
, struct mbuf
*, m
, struct inpcb
*, NULL
,
1972 struct ip6_hdr
*, ip6
, struct tcpcb
*, NULL
,
1973 struct tcphdr
*, th
);
1975 ip_ecn
= (ntohl(ip6
->ip6_flow
) >> 20) & IPTOS_ECN_MASK
;
1980 * Get IP and TCP header together in first mbuf.
1981 * Note: IP leaves IP header in first mbuf.
1983 if (off0
> sizeof (struct ip
)) {
1985 off0
= sizeof(struct ip
);
1987 if (m
->m_len
< sizeof (struct tcpiphdr
)) {
1988 if ((m
= m_pullup(m
, sizeof (struct tcpiphdr
))) == 0) {
1989 tcpstat
.tcps_rcvshort
++;
1994 /* Expect 32-bit aligned data pointer on strict-align platforms */
1995 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m
);
1997 ip
= mtod(m
, struct ip
*);
1998 th
= (struct tcphdr
*)(void *)((caddr_t
)ip
+ off0
);
2001 if (tcp_input_checksum(AF_INET
, m
, th
, off0
, tlen
))
2005 /* Re-initialization for later version check */
2006 ip
->ip_v
= IPVERSION
;
2008 ip_ecn
= (ip
->ip_tos
& IPTOS_ECN_MASK
);
2010 DTRACE_TCP5(receive
, struct mbuf
*, m
, struct inpcb
*, NULL
,
2011 struct ip
*, ip
, struct tcpcb
*, NULL
, struct tcphdr
*, th
);
2013 KERNEL_DEBUG(DBG_LAYER_BEG
, ((th
->th_dport
<< 16) | th
->th_sport
),
2014 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
2015 th
->th_seq
, th
->th_ack
, th
->th_win
);
2020 * Check that TCP offset makes sense,
2021 * pull out TCP options and adjust length.
2023 off
= th
->th_off
<< 2;
2024 if (off
< sizeof (struct tcphdr
) || off
> tlen
) {
2025 tcpstat
.tcps_rcvbadoff
++;
2026 IF_TCP_STATINC(ifp
, badformat
);
2029 tlen
-= off
; /* tlen is used instead of ti->ti_len */
2030 if (off
> sizeof (struct tcphdr
)) {
2033 IP6_EXTHDR_CHECK(m
, off0
, off
, return);
2034 ip6
= mtod(m
, struct ip6_hdr
*);
2035 th
= (struct tcphdr
*)(void *)((caddr_t
)ip6
+ off0
);
2039 if (m
->m_len
< sizeof(struct ip
) + off
) {
2040 if ((m
= m_pullup(m
, sizeof (struct ip
) + off
)) == 0) {
2041 tcpstat
.tcps_rcvshort
++;
2044 ip
= mtod(m
, struct ip
*);
2045 th
= (struct tcphdr
*)(void *)((caddr_t
)ip
+ off0
);
2048 optlen
= off
- sizeof (struct tcphdr
);
2049 optp
= (u_char
*)(th
+ 1);
2051 * Do quick retrieval of timestamp options ("options
2052 * prediction?"). If timestamp is the only option and it's
2053 * formatted as recommended in RFC 1323 appendix A, we
2054 * quickly get the values now and not bother calling
2055 * tcp_dooptions(), etc.
2057 if ((optlen
== TCPOLEN_TSTAMP_APPA
||
2058 (optlen
> TCPOLEN_TSTAMP_APPA
&&
2059 optp
[TCPOLEN_TSTAMP_APPA
] == TCPOPT_EOL
)) &&
2060 *(u_int32_t
*)(void *)optp
== htonl(TCPOPT_TSTAMP_HDR
) &&
2061 (th
->th_flags
& TH_SYN
) == 0) {
2062 to
.to_flags
|= TOF_TS
;
2063 to
.to_tsval
= ntohl(*(u_int32_t
*)(void *)(optp
+ 4));
2064 to
.to_tsecr
= ntohl(*(u_int32_t
*)(void *)(optp
+ 8));
2065 optp
= NULL
; /* we've parsed the options */
2068 thflags
= th
->th_flags
;
2072 * If the drop_synfin option is enabled, drop all packets with
2073 * both the SYN and FIN bits set. This prevents e.g. nmap from
2074 * identifying the TCP/IP stack.
2076 * This is a violation of the TCP specification.
2078 if (drop_synfin
&& (thflags
& (TH_SYN
|TH_FIN
)) == (TH_SYN
|TH_FIN
)) {
2079 IF_TCP_STATINC(ifp
, synfin
);
2085 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
2086 * until after ip6_savecontrol() is called and before other functions
2087 * which don't want those proto headers.
2088 * Because ip6_savecontrol() is going to parse the mbuf to
2089 * search for data to be passed up to user-land, it wants mbuf
2090 * parameters to be unchanged.
2092 drop_hdrlen
= off0
+ off
;
2094 /* Since this is an entry point for input processing of tcp packets, we
2095 * can update the tcp clock here.
2097 calculate_tcp_clock();
2100 * Record the interface where this segment arrived on; this does not
2101 * affect normal data output (for non-detached TCP) as it provides a
2102 * hint about which route and interface to use for sending in the
2103 * absence of a PCB, when scoped routing (and thus source interface
2104 * selection) are enabled.
2106 if ((m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
) || m
->m_pkthdr
.rcvif
== NULL
)
2107 ifscope
= IFSCOPE_NONE
;
2109 ifscope
= m
->m_pkthdr
.rcvif
->if_index
;
2112 * Convert TCP protocol specific fields to host format.
2115 #if BYTE_ORDER != BIG_ENDIAN
2123 * Locate pcb for segment.
2127 isconnected
= FALSE
;
2128 isdisconnected
= FALSE
;
2130 #if IPFIREWALL_FORWARD
2131 if (next_hop
!= NULL
2133 && isipv6
== 0 /* IPv6 support is not yet */
2137 * Diverted. Pretend to be the destination.
2138 * already got one like this?
2140 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
2141 ip
->ip_dst
, th
->th_dport
, 0, m
->m_pkthdr
.rcvif
);
2144 * No, then it's new. Try find the ambushing socket
2146 if (!next_hop
->sin_port
) {
2147 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
,
2148 th
->th_sport
, next_hop
->sin_addr
,
2149 th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
2151 inp
= in_pcblookup_hash(&tcbinfo
,
2152 ip
->ip_src
, th
->th_sport
,
2154 ntohs(next_hop
->sin_port
), 1,
2159 #endif /* IPFIREWALL_FORWARD */
2163 inp
= in6_pcblookup_hash(&tcbinfo
, &ip6
->ip6_src
, th
->th_sport
,
2164 &ip6
->ip6_dst
, th
->th_dport
, 1,
2168 inp
= in_pcblookup_hash(&tcbinfo
, ip
->ip_src
, th
->th_sport
,
2169 ip
->ip_dst
, th
->th_dport
, 1, m
->m_pkthdr
.rcvif
);
2173 * Use the interface scope information from the PCB for outbound
2174 * segments. If the PCB isn't present and if scoped routing is
2175 * enabled, tcp_respond will use the scope of the interface where
2176 * the segment arrived on.
2178 if (inp
!= NULL
&& (inp
->inp_flags
& INP_BOUND_IF
))
2179 ifscope
= inp
->inp_boundifp
->if_index
;
2182 * If the state is CLOSED (i.e., TCB does not exist) then
2183 * all data in the incoming segment is discarded.
2184 * If the TCB exists but is in CLOSED state, it is embryonic,
2185 * but should either do a listen or a connect soon.
2190 char dbuf
[MAX_IPv6_STR_LEN
], sbuf
[MAX_IPv6_STR_LEN
];
2192 char dbuf
[MAX_IPv4_STR_LEN
], sbuf
[MAX_IPv4_STR_LEN
];
2197 inet_ntop(AF_INET6
, &ip6
->ip6_dst
, dbuf
, sizeof(dbuf
));
2198 inet_ntop(AF_INET6
, &ip6
->ip6_src
, sbuf
, sizeof(sbuf
));
2202 inet_ntop(AF_INET
, &ip
->ip_dst
, dbuf
, sizeof(dbuf
));
2203 inet_ntop(AF_INET
, &ip
->ip_src
, sbuf
, sizeof(sbuf
));
2205 switch (log_in_vain
) {
2207 if(thflags
& TH_SYN
)
2209 "Connection attempt to TCP %s:%d from %s:%d\n",
2210 dbuf
, ntohs(th
->th_dport
),
2212 ntohs(th
->th_sport
));
2216 "Connection attempt to TCP %s:%d from %s:%d flags:0x%x\n",
2217 dbuf
, ntohs(th
->th_dport
), sbuf
,
2218 ntohs(th
->th_sport
), thflags
);
2222 if ((thflags
& TH_SYN
) && !(thflags
& TH_ACK
) &&
2223 !(m
->m_flags
& (M_BCAST
| M_MCAST
)) &&
2225 ((isipv6
&& !IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
, &ip6
->ip6_src
)) ||
2226 (!isipv6
&& ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
))
2228 ip
->ip_dst
.s_addr
!= ip
->ip_src
.s_addr
2231 log_in_vain_log((LOG_INFO
,
2232 "Stealth Mode connection attempt to TCP %s:%d from %s:%d\n",
2233 dbuf
, ntohs(th
->th_dport
),
2235 ntohs(th
->th_sport
)));
2242 if (m
->m_pkthdr
.rcvif
&& m
->m_pkthdr
.rcvif
->if_type
!= IFT_LOOP
)
2244 switch (blackhole
) {
2246 if (thflags
& TH_SYN
)
2255 rstreason
= BANDLIM_RST_CLOSEDPORT
;
2256 IF_TCP_STATINC(ifp
, noconnnolist
);
2257 goto dropwithresetnosock
;
2259 so
= inp
->inp_socket
;
2261 /* This case shouldn't happen as the socket shouldn't be null
2262 * if inp_state isn't set to INPCB_STATE_DEAD
2263 * But just in case, we pretend we didn't find the socket if we hit this case
2264 * as this isn't cause for a panic (the socket might be leaked however)...
2268 printf("tcp_input: no more socket for inp=%x. This shouldn't happen\n", inp
);
2274 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
2275 socket_unlock(so
, 1);
2276 inp
= NULL
; // pretend we didn't find it
2281 if (so
->so_state
& SS_ISCONNECTED
) {
2282 // Connected TCP sockets have a fully-bound local and remote,
2283 // so the policy check doesn't need to override addresses
2284 if (!necp_socket_is_allowed_to_send_recv(inp
, NULL
, NULL
, NULL
)) {
2285 IF_TCP_STATINC(ifp
, badformat
);
2291 if (!necp_socket_is_allowed_to_send_recv_v6(inp
,
2292 th
->th_dport
, th
->th_sport
, &ip6
->ip6_dst
,
2293 &ip6
->ip6_src
, ifp
, NULL
, NULL
, NULL
)) {
2294 IF_TCP_STATINC(ifp
, badformat
);
2300 if (!necp_socket_is_allowed_to_send_recv_v4(inp
,
2301 th
->th_dport
, th
->th_sport
, &ip
->ip_dst
, &ip
->ip_src
,
2302 ifp
, NULL
, NULL
, NULL
)) {
2303 IF_TCP_STATINC(ifp
, badformat
);
2310 tp
= intotcpcb(inp
);
2312 rstreason
= BANDLIM_RST_CLOSEDPORT
;
2313 IF_TCP_STATINC(ifp
, noconnlist
);
2316 if (tp
->t_state
== TCPS_CLOSED
)
2319 /* If none of the FIN|SYN|RST|ACK flag is set, drop */
2320 if (tcp_do_rfc5961
&& (thflags
& TH_ACCEPT
) == 0)
2323 /* Unscale the window into a 32-bit value. */
2324 if ((thflags
& TH_SYN
) == 0)
2325 tiwin
= th
->th_win
<< tp
->snd_scale
;
2330 if (mac_inpcb_check_deliver(inp
, m
, AF_INET
, SOCK_STREAM
))
2334 /* Avoid processing packets while closing a listen socket */
2335 if (tp
->t_state
== TCPS_LISTEN
&&
2336 (so
->so_options
& SO_ACCEPTCONN
) == 0)
2339 if (so
->so_options
& (SO_DEBUG
|SO_ACCEPTCONN
)) {
2341 if (so
->so_options
& SO_DEBUG
) {
2342 ostate
= tp
->t_state
;
2345 bcopy((char *)ip6
, (char *)tcp_saveipgen
,
2349 bcopy((char *)ip
, (char *)tcp_saveipgen
, sizeof(*ip
));
2353 if (so
->so_options
& SO_ACCEPTCONN
) {
2354 struct tcpcb
*tp0
= tp
;
2357 struct sockaddr_storage from
;
2359 struct inpcb
*oinp
= sotoinpcb(so
);
2361 struct ifnet
*head_ifscope
;
2362 unsigned int head_nocell
, head_recvanyif
,
2363 head_noexpensive
, head_awdl_unrestricted
,
2364 head_intcoproc_allowed
;
2366 /* Get listener's bound-to-interface, if any */
2367 head_ifscope
= (inp
->inp_flags
& INP_BOUND_IF
) ?
2368 inp
->inp_boundifp
: NULL
;
2369 /* Get listener's no-cellular information, if any */
2370 head_nocell
= INP_NO_CELLULAR(inp
);
2371 /* Get listener's recv-any-interface, if any */
2372 head_recvanyif
= (inp
->inp_flags
& INP_RECV_ANYIF
);
2373 /* Get listener's no-expensive information, if any */
2374 head_noexpensive
= INP_NO_EXPENSIVE(inp
);
2375 head_awdl_unrestricted
= INP_AWDL_UNRESTRICTED(inp
);
2376 head_intcoproc_allowed
= INP_INTCOPROC_ALLOWED(inp
);
2379 * If the state is LISTEN then ignore segment if it contains an RST.
2380 * If the segment contains an ACK then it is bad and send a RST.
2381 * If it does not contain a SYN then it is not interesting; drop it.
2382 * If it is from this socket, drop it, it must be forged.
2384 if ((thflags
& (TH_RST
|TH_ACK
|TH_SYN
)) != TH_SYN
) {
2385 IF_TCP_STATINC(ifp
, listbadsyn
);
2387 if (thflags
& TH_RST
) {
2390 if (thflags
& TH_ACK
) {
2392 tcpstat
.tcps_badsyn
++;
2393 rstreason
= BANDLIM_RST_OPENPORT
;
2397 /* We come here if there is no SYN set */
2398 tcpstat
.tcps_badsyn
++;
2401 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_START
,0,0,0,0,0);
2402 if (th
->th_dport
== th
->th_sport
) {
2405 if (IN6_ARE_ADDR_EQUAL(&ip6
->ip6_dst
,
2410 if (ip
->ip_dst
.s_addr
== ip
->ip_src
.s_addr
)
2414 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
2415 * in_broadcast() should never return true on a received
2416 * packet with M_BCAST not set.
2418 * Packets with a multicast source address should also
2421 if (m
->m_flags
& (M_BCAST
|M_MCAST
))
2425 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
2426 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
2430 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
2431 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
2432 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
2433 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
2439 * If deprecated address is forbidden,
2440 * we do not accept SYN to deprecated interface
2441 * address to prevent any new inbound connection from
2442 * getting established.
2443 * When we do not accept SYN, we send a TCP RST,
2444 * with deprecated source address (instead of dropping
2445 * it). We compromise it as it is much better for peer
2446 * to send a RST, and RST will be the final packet
2449 * If we do not forbid deprecated addresses, we accept
2450 * the SYN packet. RFC 4862 forbids dropping SYN in
2453 if (isipv6
&& !ip6_use_deprecated
) {
2456 if (ip6_getdstifaddr_info(m
, NULL
,
2458 if (ia6_flags
& IN6_IFF_DEPRECATED
) {
2460 rstreason
= BANDLIM_RST_OPENPORT
;
2461 IF_TCP_STATINC(ifp
, deprecate6
);
2470 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&from
;
2472 sin6
->sin6_len
= sizeof(*sin6
);
2473 sin6
->sin6_family
= AF_INET6
;
2474 sin6
->sin6_port
= th
->th_sport
;
2475 sin6
->sin6_flowinfo
= 0;
2476 sin6
->sin6_addr
= ip6
->ip6_src
;
2477 sin6
->sin6_scope_id
= 0;
2482 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&from
;
2484 sin
->sin_len
= sizeof(*sin
);
2485 sin
->sin_family
= AF_INET
;
2486 sin
->sin_port
= th
->th_sport
;
2487 sin
->sin_addr
= ip
->ip_src
;
2489 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
2491 so2
= sonewconn(so
, 0, NULL
);
2494 tcpstat
.tcps_listendrop
++;
2495 if (tcp_dropdropablreq(so
)) {
2497 so2
= sonewconn(so
, 0, (struct sockaddr
*)&from
);
2499 so2
= sonewconn(so
, 0, NULL
);
2505 /* Point "inp" and "tp" in tandem to new socket */
2506 inp
= (struct inpcb
*)so2
->so_pcb
;
2507 tp
= intotcpcb(inp
);
2510 socket_unlock(so
, 0); /* Unlock but keep a reference on listener for now */
2515 * Mark socket as temporary until we're
2516 * committed to keeping it. The code at
2517 * ``drop'' and ``dropwithreset'' check the
2518 * flag dropsocket to see if the temporary
2519 * socket created here should be discarded.
2520 * We mark the socket as discardable until
2521 * we're committed to it below in TCPS_LISTEN.
2522 * There are some error conditions in which we
2523 * have to drop the temporary socket.
2527 * Inherit INP_BOUND_IF from listener; testing if
2528 * head_ifscope is non-NULL is sufficient, since it
2529 * can only be set to a non-zero value earlier if
2530 * the listener has such a flag set.
2532 if (head_ifscope
!= NULL
) {
2533 inp
->inp_flags
|= INP_BOUND_IF
;
2534 inp
->inp_boundifp
= head_ifscope
;
2536 inp
->inp_flags
&= ~INP_BOUND_IF
;
2539 * Inherit restrictions from listener.
2542 inp_set_nocellular(inp
);
2543 if (head_noexpensive
)
2544 inp_set_noexpensive(inp
);
2545 if (head_awdl_unrestricted
)
2546 inp_set_awdl_unrestricted(inp
);
2547 if (head_intcoproc_allowed
)
2548 inp_set_intcoproc_allowed(inp
);
2550 * Inherit {IN,IN6}_RECV_ANYIF from listener.
2553 inp
->inp_flags
|= INP_RECV_ANYIF
;
2555 inp
->inp_flags
&= ~INP_RECV_ANYIF
;
2558 inp
->in6p_laddr
= ip6
->ip6_dst
;
2560 inp
->inp_vflag
&= ~INP_IPV6
;
2561 inp
->inp_vflag
|= INP_IPV4
;
2563 inp
->inp_laddr
= ip
->ip_dst
;
2567 inp
->inp_lport
= th
->th_dport
;
2568 if (in_pcbinshash(inp
, 0) != 0) {
2570 * Undo the assignments above if we failed to
2571 * put the PCB on the hash lists.
2575 inp
->in6p_laddr
= in6addr_any
;
2578 inp
->inp_laddr
.s_addr
= INADDR_ANY
;
2580 socket_lock(oso
, 0); /* release ref on parent */
2581 socket_unlock(oso
, 1);
2587 * Inherit socket options from the listening
2589 * Note that in6p_inputopts are not (even
2590 * should not be) copied, since it stores
2591 * previously received options and is used to
2592 * detect if each new option is different than
2593 * the previous one and hence should be passed
2595 * If we copied in6p_inputopts, a user would
2596 * not be able to receive options just after
2597 * calling the accept system call.
2600 oinp
->inp_flags
& INP_CONTROLOPTS
;
2601 if (oinp
->in6p_outputopts
)
2602 inp
->in6p_outputopts
=
2603 ip6_copypktopts(oinp
->in6p_outputopts
,
2608 inp
->inp_options
= ip_srcroute();
2609 inp
->inp_ip_tos
= oinp
->inp_ip_tos
;
2611 socket_lock(oso
, 0);
2613 /* copy old policy into new socket's */
2614 if (sotoinpcb(oso
)->inp_sp
)
2617 /* Is it a security hole here to silently fail to copy the policy? */
2618 if (inp
->inp_sp
!= NULL
)
2619 error
= ipsec_init_policy(so
, &inp
->inp_sp
);
2620 if (error
!= 0 || ipsec_copy_policy(sotoinpcb(oso
)->inp_sp
, inp
->inp_sp
))
2621 printf("tcp_input: could not copy policy\n");
2624 /* inherit states from the listener */
2625 DTRACE_TCP4(state__change
, void, NULL
, struct inpcb
*, inp
,
2626 struct tcpcb
*, tp
, int32_t, TCPS_LISTEN
);
2627 tp
->t_state
= TCPS_LISTEN
;
2628 tp
->t_flags
|= tp0
->t_flags
& (TF_NOPUSH
|TF_NOOPT
|TF_NODELAY
);
2629 tp
->t_flagsext
|= (tp0
->t_flagsext
& (TF_RXTFINDROP
|TF_NOTIMEWAIT
|TF_FASTOPEN
));
2630 tp
->t_keepinit
= tp0
->t_keepinit
;
2631 tp
->t_keepcnt
= tp0
->t_keepcnt
;
2632 tp
->t_keepintvl
= tp0
->t_keepintvl
;
2633 tp
->t_adaptive_wtimo
= tp0
->t_adaptive_wtimo
;
2634 tp
->t_adaptive_rtimo
= tp0
->t_adaptive_rtimo
;
2635 tp
->t_inpcb
->inp_ip_ttl
= tp0
->t_inpcb
->inp_ip_ttl
;
2636 if ((so
->so_flags
& SOF_NOTSENT_LOWAT
) != 0)
2637 tp
->t_notsent_lowat
= tp0
->t_notsent_lowat
;
2638 tp
->t_inpcb
->inp_flags2
|=
2639 tp0
->t_inpcb
->inp_flags2
& INP2_KEEPALIVE_OFFLOAD
;
2641 /* now drop the reference on the listener */
2642 socket_unlock(oso
, 1);
2644 tcp_set_max_rwinscale(tp
, so
, ifp
);
2646 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN
| DBG_FUNC_END
,0,0,0,0,0);
2649 socket_lock_assert_owned(so
);
2651 if (tp
->t_state
== TCPS_ESTABLISHED
&& tlen
> 0) {
2653 * Evaluate the rate of arrival of packets to see if the
2654 * receiver can reduce the ack traffic. The algorithm to
2655 * stretch acks will be enabled if the connection meets
2656 * certain criteria defined in tcp_stretch_ack_enable function.
2658 if ((tp
->t_flagsext
& TF_RCVUNACK_WAITSS
) != 0) {
2659 TCP_INC_VAR(tp
->rcv_waitforss
, nlropkts
);
2661 if (tcp_stretch_ack_enable(tp
, thflags
)) {
2662 tp
->t_flags
|= TF_STRETCHACK
;
2663 tp
->t_flagsext
&= ~(TF_RCVUNACK_WAITSS
);
2664 tp
->rcv_waitforss
= 0;
2666 tp
->t_flags
&= ~(TF_STRETCHACK
);
2668 if (TSTMP_GT(tp
->rcv_unackwin
, tcp_now
)) {
2669 tp
->rcv_by_unackwin
+= (tlen
+ off
);
2671 tp
->rcv_unackwin
= tcp_now
+ tcp_rcvunackwin
;
2672 tp
->rcv_by_unackwin
= tlen
+ off
;
2677 * Keep track of how many bytes were received in the LRO packet
2679 if ((pktf_sw_lro_pkt
) && (nlropkts
> 2)) {
2680 tp
->t_lropktlen
+= tlen
;
2683 * Explicit Congestion Notification - Flag that we need to send ECT if
2684 * + The IP Congestion experienced flag was set.
2685 * + Socket is in established state
2686 * + We negotiated ECN in the TCP setup
2687 * + This isn't a pure ack (tlen > 0)
2688 * + The data is in the valid window
2690 * TE_SENDECE will be cleared when we receive a packet with TH_CWR set.
2692 if (ip_ecn
== IPTOS_ECN_CE
&& tp
->t_state
== TCPS_ESTABLISHED
&&
2693 TCP_ECN_ENABLED(tp
) && tlen
> 0 &&
2694 SEQ_GEQ(th
->th_seq
, tp
->last_ack_sent
) &&
2695 SEQ_LT(th
->th_seq
, tp
->last_ack_sent
+ tp
->rcv_wnd
)) {
2696 tp
->t_ecn_recv_ce
++;
2697 tcpstat
.tcps_ecn_recv_ce
++;
2698 INP_INC_IFNET_STAT(inp
, ecn_recv_ce
);
2699 /* Mark this connection as it received CE from network */
2700 tp
->ecn_flags
|= TE_RECV_ECN_CE
;
2701 tp
->ecn_flags
|= TE_SENDECE
;
2705 * Clear TE_SENDECE if TH_CWR is set. This is harmless, so we don't
2706 * bother doing extensive checks for state and whatnot.
2708 if (thflags
& TH_CWR
) {
2709 tp
->ecn_flags
&= ~TE_SENDECE
;
2710 tp
->t_ecn_recv_cwr
++;
2714 * If we received an explicit notification of congestion in
2715 * ip tos ecn bits or by the CWR bit in TCP header flags, reset
2716 * the ack-strteching state. We need to handle ECN notification if
2717 * an ECN setup SYN was sent even once.
2719 if (tp
->t_state
== TCPS_ESTABLISHED
2720 && (tp
->ecn_flags
& TE_SETUPSENT
)
2721 && (ip_ecn
== IPTOS_ECN_CE
|| (thflags
& TH_CWR
))) {
2722 tcp_reset_stretch_ack(tp
);
2723 CLEAR_IAJ_STATE(tp
);
2726 if (ip_ecn
== IPTOS_ECN_CE
&& tp
->t_state
== TCPS_ESTABLISHED
&&
2727 !TCP_ECN_ENABLED(tp
) && !(tp
->ecn_flags
& TE_CEHEURI_SET
)) {
2728 tcpstat
.tcps_ecn_fallback_ce
++;
2729 tcp_heuristic_ecn_aggressive(tp
);
2730 tp
->ecn_flags
|= TE_CEHEURI_SET
;
2733 if (tp
->t_state
== TCPS_ESTABLISHED
&& TCP_ECN_ENABLED(tp
) &&
2734 ip_ecn
== IPTOS_ECN_CE
&& !(tp
->ecn_flags
& TE_CEHEURI_SET
)) {
2735 if (inp
->inp_stat
->rxpackets
< ECN_MIN_CE_PROBES
) {
2736 tp
->t_ecn_recv_ce_pkt
++;
2737 } else if (tp
->t_ecn_recv_ce_pkt
> ECN_MAX_CE_RATIO
) {
2738 tcpstat
.tcps_ecn_fallback_ce
++;
2739 tcp_heuristic_ecn_aggressive(tp
);
2740 tp
->ecn_flags
|= TE_CEHEURI_SET
;
2741 INP_INC_IFNET_STAT(inp
,ecn_fallback_ce
);
2743 /* We tracked the first ECN_MIN_CE_PROBES segments, we
2744 * now know that the path is good.
2746 tp
->ecn_flags
|= TE_CEHEURI_SET
;
2751 * Try to determine if we are receiving a packet after a long time.
2752 * Use our own approximation of idletime to roughly measure remote
2753 * end's idle time. Since slowstart is used after an idle period
2754 * we want to avoid doing LRO if the remote end is not up to date
2755 * on initial window support and starts with 1 or 2 packets as its IW.
2757 if (sw_lro
&& (tp
->t_flagsext
& TF_LRO_OFFLOADED
) &&
2758 ((tcp_now
- tp
->t_rcvtime
) >= (TCP_IDLETIMEOUT(tp
)))) {
2762 /* Update rcvtime as a new segment was received on the connection */
2763 tp
->t_rcvtime
= tcp_now
;
2766 * Segment received on connection.
2767 * Reset idle time and keep-alive timer.
2769 if (TCPS_HAVEESTABLISHED(tp
->t_state
)) {
2770 tcp_keepalive_reset(tp
);
2773 mptcp_reset_keepalive(tp
);
2777 * Process options if not in LISTEN state,
2778 * else do it below (after getting remote address).
2780 if (tp
->t_state
!= TCPS_LISTEN
&& optp
) {
2781 tcp_dooptions(tp
, optp
, optlen
, th
, &to
);
2784 if (tp
->t_state
!= TCPS_LISTEN
&& (so
->so_flags
& SOF_MP_SUBFLOW
) &&
2785 mptcp_input_preproc(tp
, m
, th
, drop_hdrlen
) != 0) {
2786 tp
->t_flags
|= TF_ACKNOW
;
2787 (void) tcp_output(tp
);
2788 tcp_check_timer_state(tp
);
2789 socket_unlock(so
, 1);
2790 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
|
2791 DBG_FUNC_END
,0,0,0,0,0);
2795 if (tp
->t_state
== TCPS_SYN_SENT
&& (thflags
& TH_SYN
)) {
2796 if (!(thflags
& TH_ACK
) ||
2797 (SEQ_GT(th
->th_ack
, tp
->iss
) &&
2798 SEQ_LEQ(th
->th_ack
, tp
->snd_max
)))
2799 tcp_finalize_options(tp
, &to
, ifscope
);
2804 * Compute inter-packet arrival jitter. According to RFC 3550,
2805 * inter-packet arrival jitter is defined as the difference in
2806 * packet spacing at the receiver compared to the sender for a
2807 * pair of packets. When two packets of maximum segment size come
2808 * one after the other with consecutive sequence numbers, we
2809 * consider them as packets sent together at the sender and use
2810 * them as a pair to compute inter-packet arrival jitter. This
2811 * metric indicates the delay induced by the network components due
2812 * to queuing in edge/access routers.
2814 if (tp
->t_state
== TCPS_ESTABLISHED
&&
2815 (thflags
& (TH_SYN
|TH_FIN
|TH_RST
|TH_URG
|TH_ACK
|TH_ECE
|TH_PUSH
)) == TH_ACK
&&
2816 ((tp
->t_flags
& (TF_NEEDSYN
|TF_NEEDFIN
)) == 0) &&
2817 ((to
.to_flags
& TOF_TS
) == 0 ||
2818 TSTMP_GEQ(to
.to_tsval
, tp
->ts_recent
)) &&
2819 th
->th_seq
== tp
->rcv_nxt
&& LIST_EMPTY(&tp
->t_segq
)) {
2820 int seg_size
= tlen
;
2821 if (tp
->iaj_pktcnt
<= IAJ_IGNORE_PKTCNT
) {
2822 TCP_INC_VAR(tp
->iaj_pktcnt
, nlropkts
);
2825 if (m
->m_pkthdr
.pkt_flags
& PKTF_SW_LRO_PKT
) {
2826 seg_size
= m
->m_pkthdr
.lro_pktlen
;
2828 if ( tp
->iaj_size
== 0 || seg_size
> tp
->iaj_size
||
2829 (seg_size
== tp
->iaj_size
&& tp
->iaj_rcv_ts
== 0)) {
2831 * State related to inter-arrival jitter is
2832 * uninitialized or we are trying to find a good
2833 * first packet to start computing the metric
2835 update_iaj_state(tp
, seg_size
, 0);
2837 if (seg_size
== tp
->iaj_size
) {
2839 * Compute inter-arrival jitter taking
2840 * this packet as the second packet
2842 if (pktf_sw_lro_pkt
)
2843 compute_iaj(tp
, nlropkts
,
2844 m
->m_pkthdr
.lro_elapsed
);
2846 compute_iaj(tp
, 1, 0);
2848 if (seg_size
< tp
->iaj_size
) {
2850 * There is a smaller packet in the stream.
2851 * Some times the maximum size supported
2852 * on a path can change if there is a new
2853 * link with smaller MTU. The receiver will
2854 * not know about this change. If there
2855 * are too many packets smaller than
2856 * iaj_size, we try to learn the iaj_size
2859 TCP_INC_VAR(tp
->iaj_small_pkt
, nlropkts
);
2860 if (tp
->iaj_small_pkt
> RESET_IAJ_SIZE_THRESH
) {
2861 update_iaj_state(tp
, seg_size
, 1);
2863 CLEAR_IAJ_STATE(tp
);
2866 update_iaj_state(tp
, seg_size
, 0);
2870 CLEAR_IAJ_STATE(tp
);
2872 #endif /* TRAFFIC_MGT */
2875 * Header prediction: check for the two common cases
2876 * of a uni-directional data xfer. If the packet has
2877 * no control flags, is in-sequence, the window didn't
2878 * change and we're not retransmitting, it's a
2879 * candidate. If the length is zero and the ack moved
2880 * forward, we're the sender side of the xfer. Just
2881 * free the data acked & wake any higher level process
2882 * that was blocked waiting for space. If the length
2883 * is non-zero and the ack didn't move, we're the
2884 * receiver side. If we're getting packets in-order
2885 * (the reassembly queue is empty), add the data to
2886 * the socket buffer and note that we need a delayed ack.
2887 * Make sure that the hidden state-flags are also off.
2888 * Since we check for TCPS_ESTABLISHED above, it can only
2891 if (tp
->t_state
== TCPS_ESTABLISHED
&&
2892 (thflags
& (TH_SYN
|TH_FIN
|TH_RST
|TH_URG
|TH_ACK
|TH_ECE
|TH_CWR
)) == TH_ACK
&&
2893 ((tp
->t_flags
& (TF_NEEDSYN
|TF_NEEDFIN
)) == 0) &&
2894 ((to
.to_flags
& TOF_TS
) == 0 ||
2895 TSTMP_GEQ(to
.to_tsval
, tp
->ts_recent
)) &&
2896 th
->th_seq
== tp
->rcv_nxt
&&
2897 tiwin
&& tiwin
== tp
->snd_wnd
&&
2898 tp
->snd_nxt
== tp
->snd_max
) {
2901 * If last ACK falls within this segment's sequence numbers,
2902 * record the timestamp.
2903 * NOTE that the test is modified according to the latest
2904 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2906 if ((to
.to_flags
& TOF_TS
) != 0 &&
2907 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
)) {
2908 tp
->ts_recent_age
= tcp_now
;
2909 tp
->ts_recent
= to
.to_tsval
;
2913 if (SEQ_GT(th
->th_ack
, tp
->snd_una
) &&
2914 SEQ_LEQ(th
->th_ack
, tp
->snd_max
) &&
2915 tp
->snd_cwnd
>= tp
->snd_ssthresh
&&
2916 (!IN_FASTRECOVERY(tp
) &&
2917 ((!(SACK_ENABLED(tp
)) &&
2918 tp
->t_dupacks
< tp
->t_rexmtthresh
) ||
2919 (SACK_ENABLED(tp
) && to
.to_nsacks
== 0 &&
2920 TAILQ_EMPTY(&tp
->snd_holes
))))) {
2922 * this is a pure ack for outstanding data.
2924 ++tcpstat
.tcps_predack
;
2926 tcp_bad_rexmt_check(tp
, th
, &to
);
2928 /* Recalculate the RTT */
2929 tcp_compute_rtt(tp
, &to
, th
);
2931 VERIFY(SEQ_GEQ(th
->th_ack
, tp
->snd_una
));
2932 acked
= BYTES_ACKED(th
, tp
);
2933 tcpstat
.tcps_rcvackpack
++;
2934 tcpstat
.tcps_rcvackbyte
+= acked
;
2937 * Handle an ack that is in sequence during
2938 * congestion avoidance phase. The
2939 * calculations in this function
2940 * assume that snd_una is not updated yet.
2942 if (CC_ALGO(tp
)->congestion_avd
!= NULL
)
2943 CC_ALGO(tp
)->congestion_avd(tp
, th
);
2944 tcp_ccdbg_trace(tp
, th
, TCP_CC_INSEQ_ACK_RCVD
);
2945 sbdrop(&so
->so_snd
, acked
);
2946 if (so
->so_flags
& SOF_ENABLE_MSGS
) {
2947 VERIFY(acked
<= so
->so_msg_state
->msg_serial_bytes
);
2948 so
->so_msg_state
->msg_serial_bytes
-= acked
;
2950 tcp_sbsnd_trim(&so
->so_snd
);
2952 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
2953 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))
2954 tp
->snd_recover
= th
->th_ack
- 1;
2955 tp
->snd_una
= th
->th_ack
;
2957 TCP_RESET_REXMT_STATE(tp
);
2960 * pull snd_wl2 up to prevent seq wrap relative
2963 tp
->snd_wl2
= th
->th_ack
;
2965 if (tp
->t_dupacks
> 0) {
2967 tp
->t_rexmtthresh
= tcprexmtthresh
;
2973 * If all outstanding data are acked, stop
2974 * retransmit timer, otherwise restart timer
2975 * using current (possibly backed-off) value.
2976 * If process is waiting for space,
2977 * wakeup/selwakeup/signal. If data
2978 * are ready to send, let tcp_output
2979 * decide between more output or persist.
2981 if (tp
->snd_una
== tp
->snd_max
) {
2982 tp
->t_timer
[TCPT_REXMT
] = 0;
2983 tp
->t_timer
[TCPT_PTO
] = 0;
2984 } else if (tp
->t_timer
[TCPT_PERSIST
] == 0) {
2985 tp
->t_timer
[TCPT_REXMT
] =
2986 OFFSET_FROM_START(tp
,
2989 if (!SLIST_EMPTY(&tp
->t_rxt_segments
) &&
2990 !TCP_DSACK_SEQ_IN_WINDOW(tp
,
2991 tp
->t_dsack_lastuna
, tp
->snd_una
))
2992 tcp_rxtseg_clean(tp
);
2994 if ((tp
->t_flagsext
& TF_MEASURESNDBW
) != 0 &&
2995 tp
->t_bwmeas
!= NULL
)
2996 tcp_bwmeas_check(tp
);
2998 sowwakeup(so
); /* has to be done with socket lock held */
2999 if (!SLIST_EMPTY(&tp
->t_notify_ack
))
3000 tcp_notify_acknowledgement(tp
, so
);
3002 if ((so
->so_snd
.sb_cc
) || (tp
->t_flags
& TF_ACKNOW
)) {
3003 (void) tcp_output(tp
);
3006 tcp_tfo_rcv_ack(tp
, th
);
3008 tcp_check_timer_state(tp
);
3009 socket_unlock(so
, 1);
3010 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
3013 } else if (th
->th_ack
== tp
->snd_una
&&
3014 LIST_EMPTY(&tp
->t_segq
) &&
3015 tlen
<= tcp_sbspace(tp
)) {
3017 * this is a pure, in-sequence data packet
3018 * with nothing on the reassembly queue and
3019 * we have enough buffer space to take it.
3023 * If this is a connection in steady state, start
3024 * coalescing packets belonging to this flow.
3027 tcp_lro_remove_state(tp
->t_inpcb
->inp_laddr
,
3028 tp
->t_inpcb
->inp_faddr
,
3029 tp
->t_inpcb
->inp_lport
,
3030 tp
->t_inpcb
->inp_fport
);
3031 tp
->t_flagsext
&= ~TF_LRO_OFFLOADED
;
3032 tp
->t_idleat
= tp
->rcv_nxt
;
3033 } else if (sw_lro
&& !pktf_sw_lro_pkt
&& !isipv6
&&
3034 (so
->so_flags
& SOF_USELRO
) &&
3035 !IFNET_IS_CELLULAR(m
->m_pkthdr
.rcvif
) &&
3036 (m
->m_pkthdr
.rcvif
->if_type
!= IFT_LOOP
) &&
3037 ((th
->th_seq
- tp
->irs
) >
3038 (tp
->t_maxseg
<< lro_start
)) &&
3039 ((tp
->t_idleat
== 0) || ((th
->th_seq
-
3040 tp
->t_idleat
) > (tp
->t_maxseg
<< lro_start
)))) {
3041 tp
->t_flagsext
|= TF_LRO_OFFLOADED
;
3042 tcp_start_coalescing(ip
, th
, tlen
);
3046 /* Clean receiver SACK report if present */
3047 if (SACK_ENABLED(tp
) && tp
->rcv_numsacks
)
3048 tcp_clean_sackreport(tp
);
3049 ++tcpstat
.tcps_preddat
;
3050 tp
->rcv_nxt
+= tlen
;
3052 * Pull snd_wl1 up to prevent seq wrap relative to
3055 tp
->snd_wl1
= th
->th_seq
;
3057 * Pull rcv_up up to prevent seq wrap relative to
3060 tp
->rcv_up
= tp
->rcv_nxt
;
3061 TCP_INC_VAR(tcpstat
.tcps_rcvpack
, nlropkts
);
3062 tcpstat
.tcps_rcvbyte
+= tlen
;
3063 if (nstat_collect
) {
3064 if (m
->m_pkthdr
.pkt_flags
& PKTF_SW_LRO_PKT
) {
3065 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
3066 rxpackets
, m
->m_pkthdr
.lro_npkts
);
3068 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
3071 INP_ADD_STAT(inp
, cell
, wifi
, wired
,rxbytes
,
3073 inp_set_activity_bitmap(inp
);
3077 * Calculate the RTT on the receiver only if the
3078 * connection is in streaming mode and the last
3079 * packet was not an end-of-write
3081 if (tp
->t_flags
& TF_STREAMING_ON
)
3082 tcp_compute_rtt(tp
, &to
, th
);
3084 tcp_sbrcv_grow(tp
, &so
->so_rcv
, &to
, tlen
,
3085 TCP_AUTORCVBUF_MAX(ifp
));
3088 * Add data to socket buffer.
3090 so_recv_data_stat(so
, m
, 0);
3091 m_adj(m
, drop_hdrlen
); /* delayed header drop */
3094 * If message delivery (SOF_ENABLE_MSGS) is enabled on
3095 * this socket, deliver the packet received as an
3096 * in-order message with sequence number attached to it.
3098 if (sbappendstream_rcvdemux(so
, m
,
3099 th
->th_seq
- (tp
->irs
+ 1), 0)) {
3104 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
3105 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
3106 th
->th_seq
, th
->th_ack
, th
->th_win
);
3111 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
3112 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
3113 th
->th_seq
, th
->th_ack
, th
->th_win
);
3115 TCP_INC_VAR(tp
->t_unacksegs
, nlropkts
);
3116 if (DELAY_ACK(tp
, th
)) {
3117 if ((tp
->t_flags
& TF_DELACK
) == 0) {
3118 tp
->t_flags
|= TF_DELACK
;
3119 tp
->t_timer
[TCPT_DELACK
] = OFFSET_FROM_START(tp
, tcp_delack
);
3122 tp
->t_flags
|= TF_ACKNOW
;
3126 tcp_adaptive_rwtimo_check(tp
, tlen
);
3129 tcp_tfo_rcv_data(tp
);
3131 tcp_check_timer_state(tp
);
3132 socket_unlock(so
, 1);
3133 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
3139 * Calculate amount of space in receive window,
3140 * and then do TCP input processing.
3141 * Receive window is amount of space in rcv queue,
3142 * but not less than advertised window.
3144 socket_lock_assert_owned(so
);
3145 win
= tcp_sbspace(tp
);
3148 else { /* clip rcv window to 4K for modems */
3149 if (tp
->t_flags
& TF_SLOWLINK
&& slowlink_wsize
> 0)
3150 win
= min(win
, slowlink_wsize
);
3152 tp
->rcv_wnd
= imax(win
, (int)(tp
->rcv_adv
- tp
->rcv_nxt
));
3155 * Ensure that the subflow receive window isn't greater
3156 * than the connection level receive window.
3158 if ((tp
->t_mpflags
& TMPF_MPTCP_TRUE
) &&
3159 (mp_tp
= tptomptp(tp
))) {
3160 mpte_lock_assert_held(mp_tp
->mpt_mpte
);
3161 if (tp
->rcv_wnd
> mp_tp
->mpt_rcvwnd
) {
3162 tp
->rcv_wnd
= imax(mp_tp
->mpt_rcvwnd
, (int)(tp
->rcv_adv
- tp
->rcv_nxt
));
3163 tcpstat
.tcps_mp_reducedwin
++;
3168 switch (tp
->t_state
) {
3171 * Initialize tp->rcv_nxt, and tp->irs, select an initial
3172 * tp->iss, and send a segment:
3173 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
3174 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
3175 * Fill in remote peer address fields if not previously specified.
3176 * Enter SYN_RECEIVED state, and process any other fields of this
3177 * segment in this state.
3180 struct sockaddr_in
*sin
;
3182 struct sockaddr_in6
*sin6
;
3185 socket_lock_assert_owned(so
);
3188 MALLOC(sin6
, struct sockaddr_in6
*, sizeof *sin6
,
3189 M_SONAME
, M_NOWAIT
);
3192 bzero(sin6
, sizeof(*sin6
));
3193 sin6
->sin6_family
= AF_INET6
;
3194 sin6
->sin6_len
= sizeof(*sin6
);
3195 sin6
->sin6_addr
= ip6
->ip6_src
;
3196 sin6
->sin6_port
= th
->th_sport
;
3197 laddr6
= inp
->in6p_laddr
;
3198 if (IN6_IS_ADDR_UNSPECIFIED(&inp
->in6p_laddr
))
3199 inp
->in6p_laddr
= ip6
->ip6_dst
;
3200 if (in6_pcbconnect(inp
, (struct sockaddr
*)sin6
,
3202 inp
->in6p_laddr
= laddr6
;
3203 FREE(sin6
, M_SONAME
);
3206 FREE(sin6
, M_SONAME
);
3210 socket_lock_assert_owned(so
);
3211 MALLOC(sin
, struct sockaddr_in
*, sizeof *sin
, M_SONAME
,
3215 sin
->sin_family
= AF_INET
;
3216 sin
->sin_len
= sizeof(*sin
);
3217 sin
->sin_addr
= ip
->ip_src
;
3218 sin
->sin_port
= th
->th_sport
;
3219 bzero((caddr_t
)sin
->sin_zero
, sizeof(sin
->sin_zero
));
3220 laddr
= inp
->inp_laddr
;
3221 if (inp
->inp_laddr
.s_addr
== INADDR_ANY
)
3222 inp
->inp_laddr
= ip
->ip_dst
;
3223 if (in_pcbconnect(inp
, (struct sockaddr
*)sin
, proc0
,
3224 IFSCOPE_NONE
, NULL
)) {
3225 inp
->inp_laddr
= laddr
;
3226 FREE(sin
, M_SONAME
);
3229 FREE(sin
, M_SONAME
);
3232 tcp_dooptions(tp
, optp
, optlen
, th
, &to
);
3233 tcp_finalize_options(tp
, &to
, ifscope
);
3235 if (tfo_enabled(tp
) && tcp_tfo_syn(tp
, &to
))
3241 tp
->iss
= tcp_new_isn(tp
);
3243 tp
->irs
= th
->th_seq
;
3244 tcp_sendseqinit(tp
);
3246 tp
->snd_recover
= tp
->snd_una
;
3248 * Initialization of the tcpcb for transaction;
3249 * set SND.WND = SEG.WND,
3250 * initialize CCsend and CCrecv.
3252 tp
->snd_wnd
= tiwin
; /* initial send-window */
3253 tp
->max_sndwnd
= tp
->snd_wnd
;
3254 tp
->t_flags
|= TF_ACKNOW
;
3255 tp
->t_unacksegs
= 0;
3256 DTRACE_TCP4(state__change
, void, NULL
, struct inpcb
*, inp
,
3257 struct tcpcb
*, tp
, int32_t, TCPS_SYN_RECEIVED
);
3258 tp
->t_state
= TCPS_SYN_RECEIVED
;
3259 tp
->t_timer
[TCPT_KEEP
] = OFFSET_FROM_START(tp
,
3260 TCP_CONN_KEEPINIT(tp
));
3261 dropsocket
= 0; /* committed to socket */
3263 if (inp
->inp_flowhash
== 0)
3264 inp
->inp_flowhash
= inp_calc_flowhash(inp
);
3266 /* update flowinfo - RFC 6437 */
3267 if (inp
->inp_flow
== 0 &&
3268 inp
->in6p_flags
& IN6P_AUTOFLOWLABEL
) {
3269 inp
->inp_flow
&= ~IPV6_FLOWLABEL_MASK
;
3271 (htonl(inp
->inp_flowhash
) & IPV6_FLOWLABEL_MASK
);
3275 /* reset the incomp processing flag */
3276 so
->so_flags
&= ~(SOF_INCOMP_INPROGRESS
);
3277 tcpstat
.tcps_accepts
++;
3278 if ((thflags
& (TH_ECE
| TH_CWR
)) == (TH_ECE
| TH_CWR
)) {
3280 tp
->ecn_flags
|= (TE_SETUPRECEIVED
| TE_SENDIPECT
);
3287 * If the state is SYN_RECEIVED and the seg contains an ACK,
3288 * but not for our SYN/ACK, send a RST.
3290 case TCPS_SYN_RECEIVED
:
3291 if ((thflags
& TH_ACK
) &&
3292 (SEQ_LEQ(th
->th_ack
, tp
->snd_una
) ||
3293 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
3294 rstreason
= BANDLIM_RST_OPENPORT
;
3295 IF_TCP_STATINC(ifp
, ooopacket
);
3300 * In SYN_RECEIVED state, if we recv some SYNS with
3301 * window scale and others without, window scaling should
3302 * be disabled. Otherwise the window advertised will be
3303 * lower if we assume scaling and the other end does not.
3305 if ((thflags
& TH_SYN
) &&
3306 (tp
->irs
== th
->th_seq
) &&
3307 !(to
.to_flags
& TOF_SCALE
))
3308 tp
->t_flags
&= ~TF_RCVD_SCALE
;
3312 * If the state is SYN_SENT:
3313 * if seg contains an ACK, but not for our SYN, drop the input.
3314 * if seg contains a RST, then drop the connection.
3315 * if seg does not contain SYN, then drop it.
3316 * Otherwise this is an acceptable SYN segment
3317 * initialize tp->rcv_nxt and tp->irs
3318 * if seg contains ack then advance tp->snd_una
3319 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
3320 * arrange for segment to be acked (eventually)
3321 * continue processing rest of data/controls, beginning with URG
3324 if ((thflags
& TH_ACK
) &&
3325 (SEQ_LEQ(th
->th_ack
, tp
->iss
) ||
3326 SEQ_GT(th
->th_ack
, tp
->snd_max
))) {
3327 rstreason
= BANDLIM_UNLIMITED
;
3328 IF_TCP_STATINC(ifp
, ooopacket
);
3331 if (thflags
& TH_RST
) {
3332 if ((thflags
& TH_ACK
) != 0) {
3333 if (tfo_enabled(tp
))
3334 tcp_heuristic_tfo_rst(tp
);
3335 if ((tp
->ecn_flags
& (TE_SETUPSENT
| TE_RCVD_SYN_RST
)) == TE_SETUPSENT
) {
3337 * On local connections, send
3338 * non-ECN syn one time before
3339 * dropping the connection
3341 if (tp
->t_flags
& TF_LOCAL
) {
3342 tp
->ecn_flags
|= TE_RCVD_SYN_RST
;
3345 tcp_heuristic_ecn_synrst(tp
);
3349 (SO_FILT_HINT_LOCKED
|
3350 SO_FILT_HINT_CONNRESET
));
3351 tp
= tcp_drop(tp
, ECONNREFUSED
);
3352 postevent(so
, 0, EV_RESET
);
3356 if ((thflags
& TH_SYN
) == 0)
3358 tp
->snd_wnd
= th
->th_win
; /* initial send window */
3359 tp
->max_sndwnd
= tp
->snd_wnd
;
3361 tp
->irs
= th
->th_seq
;
3363 if (thflags
& TH_ACK
) {
3364 tcpstat
.tcps_connects
++;
3366 if ((thflags
& (TH_ECE
| TH_CWR
)) == (TH_ECE
)) {
3367 /* ECN-setup SYN-ACK */
3368 tp
->ecn_flags
|= TE_SETUPRECEIVED
;
3369 if (TCP_ECN_ENABLED(tp
)) {
3370 tcp_heuristic_ecn_success(tp
);
3371 tcpstat
.tcps_ecn_client_success
++;
3374 if (tp
->ecn_flags
& TE_SETUPSENT
&&
3375 tp
->t_rxtshift
== 0) {
3376 tcp_heuristic_ecn_success(tp
);
3377 tcpstat
.tcps_ecn_not_supported
++;
3379 if (tp
->ecn_flags
& TE_SETUPSENT
&&
3381 tcp_heuristic_ecn_loss(tp
);
3383 /* non-ECN-setup SYN-ACK */
3384 tp
->ecn_flags
&= ~TE_SENDIPECT
;
3387 #if CONFIG_MACF_NET && CONFIG_MACF_SOCKET
3388 /* XXXMAC: recursive lock: SOCK_LOCK(so); */
3389 mac_socketpeer_label_associate_mbuf(m
, so
);
3390 /* XXXMAC: SOCK_UNLOCK(so); */
3392 /* Do window scaling on this connection? */
3393 if (TCP_WINDOW_SCALE_ENABLED(tp
)) {
3394 tp
->snd_scale
= tp
->requested_s_scale
;
3395 tp
->rcv_scale
= tp
->request_r_scale
;
3398 tp
->rcv_adv
+= min(tp
->rcv_wnd
, TCP_MAXWIN
<< tp
->rcv_scale
);
3399 tp
->snd_una
++; /* SYN is acked */
3400 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
))
3401 tp
->snd_nxt
= tp
->snd_una
;
3404 * We have sent more in the SYN than what is being
3405 * acked. (e.g., TFO)
3406 * We should restart the sending from what the receiver
3407 * has acknowledged immediately.
3409 if (SEQ_GT(tp
->snd_nxt
, th
->th_ack
)) {
3411 * rdar://problem/33214601
3412 * There is a middlebox that acks all but one
3413 * byte and still drops the data.
3415 if ((tp
->t_tfo_stats
& TFO_S_SYN_DATA_SENT
) &&
3416 tp
->snd_max
== th
->th_ack
+ 1 &&
3417 tp
->snd_max
> tp
->snd_una
+ 1) {
3418 tcp_heuristic_tfo_middlebox(tp
);
3420 so
->so_error
= ENODATA
;
3422 tp
->t_tfo_stats
|= TFO_S_ONE_BYTE_PROXY
;
3425 tp
->snd_max
= tp
->snd_nxt
= th
->th_ack
;
3429 * If there's data, delay ACK; if there's also a FIN
3430 * ACKNOW will be turned on later.
3432 TCP_INC_VAR(tp
->t_unacksegs
, nlropkts
);
3433 if (DELAY_ACK(tp
, th
) && tlen
!= 0 ) {
3434 if ((tp
->t_flags
& TF_DELACK
) == 0) {
3435 tp
->t_flags
|= TF_DELACK
;
3436 tp
->t_timer
[TCPT_DELACK
] = OFFSET_FROM_START(tp
, tcp_delack
);
3440 tp
->t_flags
|= TF_ACKNOW
;
3443 * Received <SYN,ACK> in SYN_SENT[*] state.
3445 * SYN_SENT --> ESTABLISHED
3446 * SYN_SENT* --> FIN_WAIT_1
3448 tp
->t_starttime
= tcp_now
;
3449 tcp_sbrcv_tstmp_check(tp
);
3450 if (tp
->t_flags
& TF_NEEDFIN
) {
3451 DTRACE_TCP4(state__change
, void, NULL
,
3452 struct inpcb
*, inp
,
3453 struct tcpcb
*, tp
, int32_t,
3455 tp
->t_state
= TCPS_FIN_WAIT_1
;
3456 tp
->t_flags
&= ~TF_NEEDFIN
;
3459 DTRACE_TCP4(state__change
, void, NULL
,
3460 struct inpcb
*, inp
, struct tcpcb
*,
3461 tp
, int32_t, TCPS_ESTABLISHED
);
3462 tp
->t_state
= TCPS_ESTABLISHED
;
3463 tp
->t_timer
[TCPT_KEEP
] =
3464 OFFSET_FROM_START(tp
,
3465 TCP_CONN_KEEPIDLE(tp
));
3467 nstat_route_connect_success(
3468 inp
->inp_route
.ro_rt
);
3470 * The SYN is acknowledged but una is not
3471 * updated yet. So pass the value of
3472 * ack to compute sndbytes correctly
3474 inp_count_sndbytes(inp
, th
->th_ack
);
3478 * Do not send the connect notification for additional
3479 * subflows until ACK for 3-way handshake arrives.
3481 if ((!(tp
->t_mpflags
& TMPF_MPTCP_TRUE
)) &&
3482 (tp
->t_mpflags
& TMPF_SENT_JOIN
)) {
3483 isconnected
= FALSE
;
3488 if ((tp
->t_tfo_flags
& (TFO_F_COOKIE_REQ
| TFO_F_COOKIE_SENT
)) ||
3489 (tp
->t_tfo_stats
& TFO_S_SYN_DATA_SENT
)) {
3490 tcp_tfo_synack(tp
, &to
);
3492 if ((tp
->t_tfo_stats
& TFO_S_SYN_DATA_SENT
) &&
3493 SEQ_LT(tp
->snd_una
, th
->th_ack
)) {
3494 tp
->t_tfo_stats
|= TFO_S_SYN_DATA_ACKED
;
3495 tcpstat
.tcps_tfo_syn_data_acked
++;
3497 if (so
->so_flags
& SOF_MP_SUBFLOW
)
3498 so
->so_flags1
|= SOF1_TFO_REWIND
;
3500 tcp_tfo_rcv_probe(tp
, tlen
);
3505 * Received initial SYN in SYN-SENT[*] state => simul-
3506 * taneous open. If segment contains CC option and there is
3507 * a cached CC, apply TAO test; if it succeeds, connection is
3508 * half-synchronized. Otherwise, do 3-way handshake:
3509 * SYN-SENT -> SYN-RECEIVED
3510 * SYN-SENT* -> SYN-RECEIVED*
3512 tp
->t_flags
|= TF_ACKNOW
;
3513 tp
->t_timer
[TCPT_REXMT
] = 0;
3514 DTRACE_TCP4(state__change
, void, NULL
, struct inpcb
*, inp
,
3515 struct tcpcb
*, tp
, int32_t, TCPS_SYN_RECEIVED
);
3516 tp
->t_state
= TCPS_SYN_RECEIVED
;
3519 * During simultaneous open, TFO should not be used.
3520 * So, we disable it here, to prevent that data gets
3521 * sent on the SYN/ACK.
3523 tcp_disable_tfo(tp
);
3528 * Advance th->th_seq to correspond to first data byte.
3529 * If data, trim to stay within window,
3530 * dropping FIN if necessary.
3533 if (tlen
> tp
->rcv_wnd
) {
3534 todrop
= tlen
- tp
->rcv_wnd
;
3538 tcpstat
.tcps_rcvpackafterwin
++;
3539 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
3541 tp
->snd_wl1
= th
->th_seq
- 1;
3542 tp
->rcv_up
= th
->th_seq
;
3544 * Client side of transaction: already sent SYN and data.
3545 * If the remote host used T/TCP to validate the SYN,
3546 * our data will be ACK'd; if so, enter normal data segment
3547 * processing in the middle of step 5, ack processing.
3548 * Otherwise, goto step 6.
3550 if (thflags
& TH_ACK
)
3554 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
3555 * do normal processing.
3557 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
3561 case TCPS_TIME_WAIT
:
3562 break; /* continue normal processing */
3564 /* Received a SYN while connection is already established.
3565 * This is a "half open connection and other anomalies" described
3566 * in RFC793 page 34, send an ACK so the remote reset the connection
3567 * or recovers by adjusting its sequence numbering. Sending an ACK is
3568 * in accordance with RFC 5961 Section 4.2
3570 case TCPS_ESTABLISHED
:
3571 if (thflags
& TH_SYN
) {
3572 /* Drop the packet silently if we have reached the limit */
3573 if (tcp_do_rfc5961
&& tcp_is_ack_ratelimited(tp
)) {
3576 /* Send challenge ACK */
3577 tcpstat
.tcps_synchallenge
++;
3585 * States other than LISTEN or SYN_SENT.
3586 * First check the RST flag and sequence number since reset segments
3587 * are exempt from the timestamp and connection count tests. This
3588 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
3589 * below which allowed reset segments in half the sequence space
3590 * to fall though and be processed (which gives forged reset
3591 * segments with a random sequence number a 50 percent chance of
3592 * killing a connection).
3593 * Then check timestamp, if present.
3594 * Then check the connection count, if present.
3595 * Then check that at least some bytes of segment are within
3596 * receive window. If segment begins before rcv_nxt,
3597 * drop leading data (and SYN); if nothing left, just ack.
3600 * If the RST bit is set, check the sequence number to see
3601 * if this is a valid reset segment.
3603 * In all states except SYN-SENT, all reset (RST) segments
3604 * are validated by checking their SEQ-fields. A reset is
3605 * valid if its sequence number is in the window.
3606 * Note: this does not take into account delayed ACKs, so
3607 * we should test against last_ack_sent instead of rcv_nxt.
3608 * The sequence number in the reset segment is normally an
3609 * echo of our outgoing acknowlegement numbers, but some hosts
3610 * send a reset with the sequence number at the rightmost edge
3611 * of our receive window, and we have to handle this case.
3612 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
3613 * that brute force RST attacks are possible. To combat this,
3614 * we use a much stricter check while in the ESTABLISHED state,
3615 * only accepting RSTs where the sequence number is equal to
3616 * last_ack_sent. In all other states (the states in which a
3617 * RST is more likely), the more permissive check is used.
3618 * RFC 5961 Section 3.2: if the RST bit is set, sequence # is
3619 * within the receive window and last_ack_sent == seq,
3620 * then reset the connection. Otherwise if the seq doesn't
3621 * match last_ack_sent, TCP must send challenge ACK. Perform
3622 * rate limitation when sending the challenge ACK.
3623 * If we have multiple segments in flight, the intial reset
3624 * segment sequence numbers will be to the left of last_ack_sent,
3625 * but they will eventually catch up.
3626 * In any case, it never made sense to trim reset segments to
3627 * fit the receive window since RFC 1122 says:
3628 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
3630 * A TCP SHOULD allow a received RST segment to include data.
3633 * It has been suggested that a RST segment could contain
3634 * ASCII text that encoded and explained the cause of the
3635 * RST. No standard has yet been established for such
3638 * If the reset segment passes the sequence number test examine
3640 * SYN_RECEIVED STATE:
3641 * If passive open, return to LISTEN state.
3642 * If active open, inform user that connection was refused.
3643 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
3644 * Inform user that connection was reset, and close tcb.
3645 * CLOSING, LAST_ACK STATES:
3648 * Drop the segment - see Stevens, vol. 2, p. 964 and
3651 * Radar 4803931: Allows for the case where we ACKed the FIN but
3652 * there is already a RST in flight from the peer.
3653 * In that case, accept the RST for non-established
3654 * state if it's one off from last_ack_sent.
3657 if (thflags
& TH_RST
) {
3658 if ((SEQ_GEQ(th
->th_seq
, tp
->last_ack_sent
) &&
3659 SEQ_LT(th
->th_seq
, tp
->last_ack_sent
+ tp
->rcv_wnd
)) ||
3660 (tp
->rcv_wnd
== 0 &&
3661 ((tp
->last_ack_sent
== th
->th_seq
) ||
3662 ((tp
->last_ack_sent
-1) == th
->th_seq
)))) {
3663 if (tcp_do_rfc5961
== 0 || tp
->last_ack_sent
== th
->th_seq
) {
3664 switch (tp
->t_state
) {
3666 case TCPS_SYN_RECEIVED
:
3667 IF_TCP_STATINC(ifp
, rstinsynrcv
);
3668 so
->so_error
= ECONNREFUSED
;
3671 case TCPS_ESTABLISHED
:
3672 if (tcp_do_rfc5961
== 0 && tp
->last_ack_sent
!= th
->th_seq
) {
3673 tcpstat
.tcps_badrst
++;
3676 if (TCP_ECN_ENABLED(tp
) &&
3677 tp
->snd_una
== tp
->iss
+ 1 &&
3678 SEQ_GT(tp
->snd_max
, tp
->snd_una
)) {
3680 * If the first data packet on an
3681 * ECN connection, receives a RST
3682 * increment the heuristic
3684 tcp_heuristic_ecn_droprst(tp
);
3686 case TCPS_FIN_WAIT_1
:
3687 case TCPS_CLOSE_WAIT
:
3691 case TCPS_FIN_WAIT_2
:
3692 so
->so_error
= ECONNRESET
;
3694 postevent(so
, 0, EV_RESET
);
3696 (SO_FILT_HINT_LOCKED
|
3697 SO_FILT_HINT_CONNRESET
));
3699 tcpstat
.tcps_drops
++;
3708 case TCPS_TIME_WAIT
:
3711 } else if (tcp_do_rfc5961
) {
3712 tcpstat
.tcps_badrst
++;
3713 /* Drop if we have reached the ACK limit */
3714 if (tcp_is_ack_ratelimited(tp
)) {
3717 /* Send challenge ACK */
3718 tcpstat
.tcps_rstchallenge
++;
3727 * RFC 1323 PAWS: If we have a timestamp reply on this segment
3728 * and it's less than ts_recent, drop it.
3730 if ((to
.to_flags
& TOF_TS
) != 0 && tp
->ts_recent
&&
3731 TSTMP_LT(to
.to_tsval
, tp
->ts_recent
)) {
3733 /* Check to see if ts_recent is over 24 days old. */
3734 if ((int)(tcp_now
- tp
->ts_recent_age
) > TCP_PAWS_IDLE
) {
3736 * Invalidate ts_recent. If this segment updates
3737 * ts_recent, the age will be reset later and ts_recent
3738 * will get a valid value. If it does not, setting
3739 * ts_recent to zero will at least satisfy the
3740 * requirement that zero be placed in the timestamp
3741 * echo reply when ts_recent isn't valid. The
3742 * age isn't reset until we get a valid ts_recent
3743 * because we don't want out-of-order segments to be
3744 * dropped when ts_recent is old.
3748 tcpstat
.tcps_rcvduppack
++;
3749 tcpstat
.tcps_rcvdupbyte
+= tlen
;
3751 tcpstat
.tcps_pawsdrop
++;
3754 * PAWS-drop when ECN is being used? That indicates
3755 * that ECT-marked packets take a different path, with
3756 * different congestion-characteristics.
3758 * Only fallback when we did send less than 2GB as PAWS
3759 * really has no reason to kick in earlier.
3761 if (TCP_ECN_ENABLED(tp
) &&
3762 inp
->inp_stat
->rxbytes
< 2147483648) {
3763 INP_INC_IFNET_STAT(inp
, ecn_fallback_reorder
);
3764 tcpstat
.tcps_ecn_fallback_reorder
++;
3765 tcp_heuristic_ecn_aggressive(tp
);
3768 if (nstat_collect
) {
3769 nstat_route_rx(tp
->t_inpcb
->inp_route
.ro_rt
,
3770 1, tlen
, NSTAT_RX_FLAG_DUPLICATE
);
3771 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
3773 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
3775 tp
->t_stat
.rxduplicatebytes
+= tlen
;
3776 inp_set_activity_bitmap(inp
);
3785 * In the SYN-RECEIVED state, validate that the packet belongs to
3786 * this connection before trimming the data to fit the receive
3787 * window. Check the sequence number versus IRS since we know
3788 * the sequence numbers haven't wrapped. This is a partial fix
3789 * for the "LAND" DoS attack.
3791 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& SEQ_LT(th
->th_seq
, tp
->irs
)) {
3792 rstreason
= BANDLIM_RST_OPENPORT
;
3793 IF_TCP_STATINC(ifp
, dospacket
);
3798 * Check if there is old data at the beginning of the window
3799 * i.e. the sequence number is before rcv_nxt
3801 todrop
= tp
->rcv_nxt
- th
->th_seq
;
3803 boolean_t is_syn_set
= FALSE
;
3805 if (thflags
& TH_SYN
) {
3816 * Following if statement from Stevens, vol. 2, p. 960.
3817 * The amount of duplicate data is greater than or equal
3818 * to the size of the segment - entire segment is duplicate
3821 || (todrop
== tlen
&& (thflags
& TH_FIN
) == 0)) {
3823 * Any valid FIN must be to the left of the window.
3824 * At this point the FIN must be a duplicate or out
3825 * of sequence; drop it.
3830 * Send an ACK to resynchronize and drop any data.
3831 * But keep on processing for RST or ACK.
3833 * If the SYN bit was originally set, then only send
3834 * an ACK if we are not rate-limiting this connection.
3836 if (tcp_do_rfc5961
&& is_syn_set
) {
3837 if (!tcp_is_ack_ratelimited(tp
)) {
3838 tcpstat
.tcps_synchallenge
++;
3839 tp
->t_flags
|= TF_ACKNOW
;
3842 tp
->t_flags
|= TF_ACKNOW
;
3846 /* This could be a keepalive */
3847 soevent(so
, SO_FILT_HINT_LOCKED
|
3848 SO_FILT_HINT_KEEPALIVE
);
3851 tcpstat
.tcps_rcvduppack
++;
3852 tcpstat
.tcps_rcvdupbyte
+= todrop
;
3854 tcpstat
.tcps_rcvpartduppack
++;
3855 tcpstat
.tcps_rcvpartdupbyte
+= todrop
;
3858 if (TCP_DSACK_ENABLED(tp
) && todrop
> 1) {
3860 * Note the duplicate data sequence space so that
3861 * it can be reported in DSACK option.
3863 tp
->t_dsack_lseq
= th
->th_seq
;
3864 tp
->t_dsack_rseq
= th
->th_seq
+ todrop
;
3865 tp
->t_flags
|= TF_ACKNOW
;
3867 if (nstat_collect
) {
3868 nstat_route_rx(tp
->t_inpcb
->inp_route
.ro_rt
, 1,
3869 todrop
, NSTAT_RX_FLAG_DUPLICATE
);
3870 INP_ADD_STAT(inp
, cell
, wifi
, wired
, rxpackets
, 1);
3871 INP_ADD_STAT(inp
, cell
, wifi
, wired
, rxbytes
, todrop
);
3872 tp
->t_stat
.rxduplicatebytes
+= todrop
;
3873 inp_set_activity_bitmap(inp
);
3875 drop_hdrlen
+= todrop
; /* drop from the top afterwards */
3876 th
->th_seq
+= todrop
;
3878 if (th
->th_urp
> todrop
)
3879 th
->th_urp
-= todrop
;
3887 * If new data are received on a connection after the user
3888 * processes are gone, then RST the other end.
3889 * Send also a RST when we received a data segment after we've
3890 * sent our FIN when the socket is defunct.
3891 * Note that an MPTCP subflow socket would have SS_NOFDREF set
3892 * by default. So, if it's an MPTCP-subflow we rather check the
3893 * MPTCP-level's socket state for SS_NOFDREF.
3896 boolean_t close_it
= FALSE
;
3898 if (!(so
->so_flags
& SOF_MP_SUBFLOW
) && (so
->so_state
& SS_NOFDREF
) &&
3899 tp
->t_state
> TCPS_CLOSE_WAIT
)
3902 if ((so
->so_flags
& SOF_MP_SUBFLOW
) && (mptetoso(tptomptp(tp
)->mpt_mpte
)->so_state
& SS_NOFDREF
) &&
3903 tp
->t_state
> TCPS_CLOSE_WAIT
)
3906 if ((so
->so_flags
& SOF_DEFUNCT
) && tp
->t_state
> TCPS_FIN_WAIT_1
)
3911 tcpstat
.tcps_rcvafterclose
++;
3912 rstreason
= BANDLIM_UNLIMITED
;
3913 IF_TCP_STATINC(ifp
, cleanup
);
3919 * If segment ends after window, drop trailing data
3920 * (and PUSH and FIN); if nothing left, just ACK.
3922 todrop
= (th
->th_seq
+tlen
) - (tp
->rcv_nxt
+tp
->rcv_wnd
);
3924 tcpstat
.tcps_rcvpackafterwin
++;
3925 if (todrop
>= tlen
) {
3926 tcpstat
.tcps_rcvbyteafterwin
+= tlen
;
3928 * If a new connection request is received
3929 * while in TIME_WAIT, drop the old connection
3930 * and start over if the sequence numbers
3931 * are above the previous ones.
3933 if (thflags
& TH_SYN
&&
3934 tp
->t_state
== TCPS_TIME_WAIT
&&
3935 SEQ_GT(th
->th_seq
, tp
->rcv_nxt
)) {
3936 iss
= tcp_new_isn(tp
);
3938 socket_unlock(so
, 1);
3942 * If window is closed can only take segments at
3943 * window edge, and have to drop data and PUSH from
3944 * incoming segments. Continue processing, but
3945 * remember to ack. Otherwise, drop segment
3948 if (tp
->rcv_wnd
== 0 && th
->th_seq
== tp
->rcv_nxt
) {
3949 tp
->t_flags
|= TF_ACKNOW
;
3950 tcpstat
.tcps_rcvwinprobe
++;
3954 tcpstat
.tcps_rcvbyteafterwin
+= todrop
;
3957 thflags
&= ~(TH_PUSH
|TH_FIN
);
3961 * If last ACK falls within this segment's sequence numbers,
3962 * record its timestamp.
3964 * 1) That the test incorporates suggestions from the latest
3965 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
3966 * 2) That updating only on newer timestamps interferes with
3967 * our earlier PAWS tests, so this check should be solely
3968 * predicated on the sequence space of this segment.
3969 * 3) That we modify the segment boundary check to be
3970 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
3971 * instead of RFC1323's
3972 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
3973 * This modified check allows us to overcome RFC1323's
3974 * limitations as described in Stevens TCP/IP Illustrated
3975 * Vol. 2 p.869. In such cases, we can still calculate the
3976 * RTT correctly when RCV.NXT == Last.ACK.Sent.
3978 if ((to
.to_flags
& TOF_TS
) != 0 &&
3979 SEQ_LEQ(th
->th_seq
, tp
->last_ack_sent
) &&
3980 SEQ_LEQ(tp
->last_ack_sent
, th
->th_seq
+ tlen
+
3981 ((thflags
& (TH_SYN
|TH_FIN
)) != 0))) {
3982 tp
->ts_recent_age
= tcp_now
;
3983 tp
->ts_recent
= to
.to_tsval
;
3987 * Stevens: If a SYN is in the window, then this is an
3988 * error and we send an RST and drop the connection.
3990 * RFC 5961 Section 4.2
3991 * Send challenge ACK for any SYN in synchronized state
3992 * Perform rate limitation in doing so.
3994 if (thflags
& TH_SYN
) {
3995 if (tcp_do_rfc5961
) {
3996 tcpstat
.tcps_badsyn
++;
3997 /* Drop if we have reached ACK limit */
3998 if (tcp_is_ack_ratelimited(tp
)) {
4001 /* Send challenge ACK */
4002 tcpstat
.tcps_synchallenge
++;
4006 tp
= tcp_drop(tp
, ECONNRESET
);
4007 rstreason
= BANDLIM_UNLIMITED
;
4008 postevent(so
, 0, EV_RESET
);
4009 IF_TCP_STATINC(ifp
, synwindow
);
4015 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
4016 * flag is on (half-synchronized state), then queue data for
4017 * later processing; else drop segment and return.
4019 if ((thflags
& TH_ACK
) == 0) {
4020 if (tp
->t_state
== TCPS_SYN_RECEIVED
||
4021 (tp
->t_flags
& TF_NEEDSYN
)) {
4022 if ((tfo_enabled(tp
))) {
4024 * So, we received a valid segment while in
4025 * SYN-RECEIVED (TF_NEEDSYN is actually never
4026 * set, so this is dead code).
4027 * As this cannot be an RST (see that if a bit
4028 * higher), and it does not have the ACK-flag
4029 * set, we want to retransmit the SYN/ACK.
4030 * Thus, we have to reset snd_nxt to snd_una to
4031 * trigger the going back to sending of the
4032 * SYN/ACK. This is more consistent with the
4033 * behavior of tcp_output(), which expects
4034 * to send the segment that is pointed to by
4037 tp
->snd_nxt
= tp
->snd_una
;
4040 * We need to make absolutely sure that we are
4041 * going to reply upon a duplicate SYN-segment.
4043 if (th
->th_flags
& TH_SYN
)
4048 } else if (tp
->t_flags
& TF_ACKNOW
)
4058 switch (tp
->t_state
) {
4061 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
4062 * ESTABLISHED state and continue processing.
4063 * The ACK was checked above.
4065 case TCPS_SYN_RECEIVED
:
4067 tcpstat
.tcps_connects
++;
4069 /* Do window scaling? */
4070 if (TCP_WINDOW_SCALE_ENABLED(tp
)) {
4071 tp
->snd_scale
= tp
->requested_s_scale
;
4072 tp
->rcv_scale
= tp
->request_r_scale
;
4073 tp
->snd_wnd
= th
->th_win
<< tp
->snd_scale
;
4074 tp
->max_sndwnd
= tp
->snd_wnd
;
4075 tiwin
= tp
->snd_wnd
;
4079 * SYN-RECEIVED -> ESTABLISHED
4080 * SYN-RECEIVED* -> FIN-WAIT-1
4082 tp
->t_starttime
= tcp_now
;
4083 tcp_sbrcv_tstmp_check(tp
);
4084 if (tp
->t_flags
& TF_NEEDFIN
) {
4085 DTRACE_TCP4(state__change
, void, NULL
,
4086 struct inpcb
*, inp
,
4087 struct tcpcb
*, tp
, int32_t, TCPS_FIN_WAIT_1
);
4088 tp
->t_state
= TCPS_FIN_WAIT_1
;
4089 tp
->t_flags
&= ~TF_NEEDFIN
;
4091 DTRACE_TCP4(state__change
, void, NULL
,
4092 struct inpcb
*, inp
,
4093 struct tcpcb
*, tp
, int32_t, TCPS_ESTABLISHED
);
4094 tp
->t_state
= TCPS_ESTABLISHED
;
4095 tp
->t_timer
[TCPT_KEEP
] = OFFSET_FROM_START(tp
,
4096 TCP_CONN_KEEPIDLE(tp
));
4098 nstat_route_connect_success(
4099 tp
->t_inpcb
->inp_route
.ro_rt
);
4101 * The SYN is acknowledged but una is not updated
4102 * yet. So pass the value of ack to compute
4103 * sndbytes correctly
4105 inp_count_sndbytes(inp
, th
->th_ack
);
4108 * If segment contains data or ACK, will call tcp_reass()
4109 * later; if not, do so now to pass queued data to user.
4111 if (tlen
== 0 && (thflags
& TH_FIN
) == 0)
4112 (void) tcp_reass(tp
, (struct tcphdr
*)0, &tlen
,
4114 tp
->snd_wl1
= th
->th_seq
- 1;
4118 * Do not send the connect notification for additional subflows
4119 * until ACK for 3-way handshake arrives.
4121 if ((!(tp
->t_mpflags
& TMPF_MPTCP_TRUE
)) &&
4122 (tp
->t_mpflags
& TMPF_SENT_JOIN
)) {
4123 isconnected
= FALSE
;
4127 if ((tp
->t_tfo_flags
& TFO_F_COOKIE_VALID
)) {
4128 /* Done this when receiving the SYN */
4129 isconnected
= FALSE
;
4131 OSDecrementAtomic(&tcp_tfo_halfcnt
);
4133 /* Panic if something has gone terribly wrong. */
4134 VERIFY(tcp_tfo_halfcnt
>= 0);
4136 tp
->t_tfo_flags
&= ~TFO_F_COOKIE_VALID
;
4140 * In case there is data in the send-queue (e.g., TFO is being
4141 * used, or connectx+data has been done), then if we would
4142 * "FALLTHROUGH", we would handle this ACK as if data has been
4143 * acknowledged. But, we have to prevent this. And this
4144 * can be prevented by increasing snd_una by 1, so that the
4145 * SYN is not considered as data (snd_una++ is actually also
4146 * done in SYN_SENT-state as part of the regular TCP stack).
4148 * In case there is data on this ack as well, the data will be
4149 * handled by the label "dodata" right after step6.
4151 if (so
->so_snd
.sb_cc
) {
4152 tp
->snd_una
++; /* SYN is acked */
4153 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
))
4154 tp
->snd_nxt
= tp
->snd_una
;
4157 * No duplicate-ACK handling is needed. So, we
4158 * directly advance to processing the ACK (aka,
4159 * updating the RTT estimation,...)
4161 * But, we first need to handle eventual SACKs,
4162 * because TFO will start sending data with the
4163 * SYN/ACK, so it might be that the client
4164 * includes a SACK with its ACK.
4166 if (SACK_ENABLED(tp
) &&
4167 (to
.to_nsacks
> 0 ||
4168 !TAILQ_EMPTY(&tp
->snd_holes
)))
4169 tcp_sack_doack(tp
, &to
, th
,
4178 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
4179 * ACKs. If the ack is in the range
4180 * tp->snd_una < th->th_ack <= tp->snd_max
4181 * then advance tp->snd_una to th->th_ack and drop
4182 * data from the retransmission queue. If this ACK reflects
4183 * more up to date window information we update our window information.
4185 case TCPS_ESTABLISHED
:
4186 case TCPS_FIN_WAIT_1
:
4187 case TCPS_FIN_WAIT_2
:
4188 case TCPS_CLOSE_WAIT
:
4191 case TCPS_TIME_WAIT
:
4192 if (SEQ_GT(th
->th_ack
, tp
->snd_max
)) {
4193 tcpstat
.tcps_rcvacktoomuch
++;
4194 if (tcp_do_rfc5961
&& tcp_is_ack_ratelimited(tp
)) {
4200 if (tcp_do_rfc5961
&& SEQ_LT(th
->th_ack
, tp
->snd_una
- tp
->max_sndwnd
)) {
4201 if (tcp_is_ack_ratelimited(tp
)) {
4207 if (SACK_ENABLED(tp
) && to
.to_nsacks
> 0) {
4208 recvd_dsack
= tcp_sack_process_dsack(tp
, &to
, th
);
4210 * If DSACK is received and this packet has no
4211 * other SACK information, it can be dropped.
4212 * We do not want to treat it as a duplicate ack.
4215 SEQ_LEQ(th
->th_ack
, tp
->snd_una
) &&
4216 to
.to_nsacks
== 0) {
4217 tcp_bad_rexmt_check(tp
, th
, &to
);
4222 if (SACK_ENABLED(tp
) &&
4223 (to
.to_nsacks
> 0 || !TAILQ_EMPTY(&tp
->snd_holes
)))
4224 tcp_sack_doack(tp
, &to
, th
, &sack_bytes_acked
);
4227 if (tp
->t_mpuna
&& SEQ_GEQ(th
->th_ack
, tp
->t_mpuna
)) {
4228 if (tp
->t_mpflags
& TMPF_PREESTABLISHED
) {
4229 /* MP TCP establishment succeeded */
4231 if (tp
->t_mpflags
& TMPF_JOINED_FLOW
) {
4232 if (tp
->t_mpflags
& TMPF_SENT_JOIN
) {
4234 ~TMPF_PREESTABLISHED
;
4237 mptcplog((LOG_DEBUG
, "MPTCP "
4238 "Sockets: %s \n",__func__
),
4242 tp
->t_timer
[TCPT_JACK_RXMT
] = 0;
4243 tp
->t_mprxtshift
= 0;
4246 isconnected
= FALSE
;
4255 tcp_tfo_rcv_ack(tp
, th
);
4258 * If we have outstanding data (other than
4259 * a window probe), this is a completely
4260 * duplicate ack and the ack is the biggest we've seen.
4262 * Need to accommodate a change in window on duplicate acks
4263 * to allow operating systems that update window during
4264 * recovery with SACK
4266 if (SEQ_LEQ(th
->th_ack
, tp
->snd_una
)) {
4267 if (tlen
== 0 && (tiwin
== tp
->snd_wnd
||
4268 (to
.to_nsacks
> 0 && sack_bytes_acked
> 0))) {
4270 * If both ends send FIN at the same time,
4271 * then the ack will be a duplicate ack
4272 * but we have to process the FIN. Check
4273 * for this condition and process the FIN
4274 * instead of the dupack
4276 if ((thflags
& TH_FIN
) &&
4277 !TCPS_HAVERCVDFIN(tp
->t_state
))
4282 * MPTCP options that are ignored must
4283 * not be treated as duplicate ACKs.
4285 if (to
.to_flags
& TOF_MPTCP
) {
4289 if ((isconnected
) && (tp
->t_mpflags
& TMPF_JOINED_FLOW
)) {
4290 mptcplog((LOG_DEBUG
, "MPTCP "
4291 "Sockets: bypass ack recovery\n"),
4293 MPTCP_LOGLVL_VERBOSE
);
4298 * If a duplicate acknowledgement was seen
4299 * after ECN, it indicates packet loss in
4300 * addition to ECN. Reset INRECOVERY flag
4301 * so that we can process partial acks
4304 if (tp
->ecn_flags
& TE_INRECOVERY
)
4305 tp
->ecn_flags
&= ~TE_INRECOVERY
;
4307 tcpstat
.tcps_rcvdupack
++;
4311 * Check if we need to reset the limit on
4314 if (tp
->t_early_rexmt_count
> 0 &&
4316 (tp
->t_early_rexmt_win
+
4317 TCP_EARLY_REXMT_WIN
)))
4318 tp
->t_early_rexmt_count
= 0;
4321 * Is early retransmit needed? We check for
4322 * this when the connection is waiting for
4323 * duplicate acks to enter fast recovery.
4325 if (!IN_FASTRECOVERY(tp
))
4326 tcp_early_rexmt_check(tp
, th
);
4329 * If we've seen exactly rexmt threshold
4330 * of duplicate acks, assume a packet
4331 * has been dropped and retransmit it.
4332 * Kludge snd_nxt & the congestion
4333 * window so we send only this one
4336 * We know we're losing at the current
4337 * window size so do congestion avoidance
4338 * (set ssthresh to half the current window
4339 * and pull our congestion window back to
4340 * the new ssthresh).
4342 * Dup acks mean that packets have left the
4343 * network (they're now cached at the receiver)
4344 * so bump cwnd by the amount in the receiver
4345 * to keep a constant cwnd packets in the
4348 if (tp
->t_timer
[TCPT_REXMT
] == 0 ||
4349 (th
->th_ack
!= tp
->snd_una
4350 && sack_bytes_acked
== 0)) {
4352 tp
->t_rexmtthresh
= tcprexmtthresh
;
4353 } else if (tp
->t_dupacks
> tp
->t_rexmtthresh
||
4354 IN_FASTRECOVERY(tp
)) {
4357 * If this connection was seeing packet
4358 * reordering, then recovery might be
4359 * delayed to disambiguate between
4360 * reordering and loss
4362 if (SACK_ENABLED(tp
) && !IN_FASTRECOVERY(tp
) &&
4364 (TF_PKTS_REORDERED
|TF_DELAY_RECOVERY
)) ==
4365 (TF_PKTS_REORDERED
|TF_DELAY_RECOVERY
)) {
4367 * Since the SACK information is already
4368 * updated, this ACK will be dropped
4373 if (SACK_ENABLED(tp
)
4374 && IN_FASTRECOVERY(tp
)) {
4378 * Compute the amount of data in flight first.
4379 * We can inject new data into the pipe iff
4380 * we have less than 1/2 the original window's
4381 * worth of data in flight.
4383 awnd
= (tp
->snd_nxt
- tp
->snd_fack
) +
4384 tp
->sackhint
.sack_bytes_rexmit
;
4385 if (awnd
< tp
->snd_ssthresh
) {
4386 tp
->snd_cwnd
+= tp
->t_maxseg
;
4387 if (tp
->snd_cwnd
> tp
->snd_ssthresh
)
4388 tp
->snd_cwnd
= tp
->snd_ssthresh
;
4391 tp
->snd_cwnd
+= tp
->t_maxseg
;
4394 /* Process any window updates */
4395 if (tiwin
> tp
->snd_wnd
)
4396 tcp_update_window(tp
, thflags
,
4398 tcp_ccdbg_trace(tp
, th
,
4399 TCP_CC_IN_FASTRECOVERY
);
4401 (void) tcp_output(tp
);
4404 } else if (tp
->t_dupacks
== tp
->t_rexmtthresh
) {
4405 tcp_seq onxt
= tp
->snd_nxt
;
4408 * If we're doing sack, check to
4409 * see if we're already in sack
4410 * recovery. If we're not doing sack,
4411 * check to see if we're in newreno
4414 if (SACK_ENABLED(tp
)) {
4415 if (IN_FASTRECOVERY(tp
)) {
4418 } else if (tp
->t_flagsext
& TF_DELAY_RECOVERY
) {
4422 if (SEQ_LEQ(th
->th_ack
,
4428 if (tp
->t_flags
& TF_SENTFIN
)
4429 tp
->snd_recover
= tp
->snd_max
- 1;
4431 tp
->snd_recover
= tp
->snd_max
;
4432 tp
->t_timer
[TCPT_PTO
] = 0;
4436 * If the connection has seen pkt
4437 * reordering, delay recovery until
4438 * it is clear that the packet
4441 if (SACK_ENABLED(tp
) &&
4443 (TF_PKTS_REORDERED
|TF_DELAY_RECOVERY
))
4444 == TF_PKTS_REORDERED
&&
4445 !IN_FASTRECOVERY(tp
) &&
4446 tp
->t_reorderwin
> 0 &&
4447 (tp
->t_state
== TCPS_ESTABLISHED
||
4448 tp
->t_state
== TCPS_FIN_WAIT_1
)) {
4449 tp
->t_timer
[TCPT_DELAYFR
] =
4450 OFFSET_FROM_START(tp
,
4452 tp
->t_flagsext
|= TF_DELAY_RECOVERY
;
4453 tcpstat
.tcps_delay_recovery
++;
4454 tcp_ccdbg_trace(tp
, th
,
4455 TCP_CC_DELAY_FASTRECOVERY
);
4459 tcp_rexmt_save_state(tp
);
4461 * If the current tcp cc module has
4462 * defined a hook for tasks to run
4463 * before entering FR, call it
4465 if (CC_ALGO(tp
)->pre_fr
!= NULL
)
4466 CC_ALGO(tp
)->pre_fr(tp
);
4467 ENTER_FASTRECOVERY(tp
);
4468 tp
->t_timer
[TCPT_REXMT
] = 0;
4469 if (TCP_ECN_ENABLED(tp
))
4470 tp
->ecn_flags
|= TE_SENDCWR
;
4472 if (SACK_ENABLED(tp
)) {
4473 tcpstat
.tcps_sack_recovery_episode
++;
4474 tp
->t_sack_recovery_episode
++;
4475 tp
->sack_newdata
= tp
->snd_nxt
;
4476 tp
->snd_cwnd
= tp
->t_maxseg
;
4478 ~TF_CWND_NONVALIDATED
;
4480 /* Process any window updates */
4481 if (tiwin
> tp
->snd_wnd
)
4486 tcp_ccdbg_trace(tp
, th
,
4487 TCP_CC_ENTER_FASTRECOVERY
);
4488 (void) tcp_output(tp
);
4491 tp
->snd_nxt
= th
->th_ack
;
4492 tp
->snd_cwnd
= tp
->t_maxseg
;
4494 /* Process any window updates */
4495 if (tiwin
> tp
->snd_wnd
)
4496 tcp_update_window(tp
,
4500 (void) tcp_output(tp
);
4501 if (tp
->t_flagsext
& TF_CWND_NONVALIDATED
) {
4502 tcp_cc_adjust_nonvalidated_cwnd(tp
);
4504 tp
->snd_cwnd
= tp
->snd_ssthresh
+
4505 tp
->t_maxseg
* tp
->t_dupacks
;
4507 if (SEQ_GT(onxt
, tp
->snd_nxt
))
4510 tcp_ccdbg_trace(tp
, th
,
4511 TCP_CC_ENTER_FASTRECOVERY
);
4513 } else if (limited_txmt
&&
4514 ALLOW_LIMITED_TRANSMIT(tp
) &&
4515 (!(SACK_ENABLED(tp
)) || sack_bytes_acked
> 0) &&
4516 (so
->so_snd
.sb_cc
- (tp
->snd_max
- tp
->snd_una
)) > 0) {
4517 u_int32_t incr
= (tp
->t_maxseg
* tp
->t_dupacks
);
4519 /* Use Limited Transmit algorithm on the first two
4520 * duplicate acks when there is new data to transmit
4522 tp
->snd_cwnd
+= incr
;
4523 tcpstat
.tcps_limited_txt
++;
4524 (void) tcp_output(tp
);
4526 tcp_ccdbg_trace(tp
, th
, TCP_CC_LIMITED_TRANSMIT
);
4528 /* Reset snd_cwnd back to normal */
4529 tp
->snd_cwnd
-= incr
;
4535 * If the congestion window was inflated to account
4536 * for the other side's cached packets, retract it.
4538 if (IN_FASTRECOVERY(tp
)) {
4539 if (SEQ_LT(th
->th_ack
, tp
->snd_recover
)) {
4541 * If we received an ECE and entered
4542 * recovery, the subsequent ACKs should
4543 * not be treated as partial acks.
4545 if (tp
->ecn_flags
& TE_INRECOVERY
)
4548 if (SACK_ENABLED(tp
))
4549 tcp_sack_partialack(tp
, th
);
4551 tcp_newreno_partial_ack(tp
, th
);
4552 tcp_ccdbg_trace(tp
, th
, TCP_CC_PARTIAL_ACK
);
4554 EXIT_FASTRECOVERY(tp
);
4555 if (CC_ALGO(tp
)->post_fr
!= NULL
)
4556 CC_ALGO(tp
)->post_fr(tp
, th
);
4558 tcp_clear_pipeack_state(tp
);
4559 tcp_ccdbg_trace(tp
, th
,
4560 TCP_CC_EXIT_FASTRECOVERY
);
4562 } else if ((tp
->t_flagsext
&
4563 (TF_PKTS_REORDERED
|TF_DELAY_RECOVERY
))
4564 == (TF_PKTS_REORDERED
|TF_DELAY_RECOVERY
)) {
4566 * If the ack acknowledges upto snd_recover or if
4567 * it acknowledges all the snd holes, exit
4568 * recovery and cancel the timer. Otherwise,
4569 * this is a partial ack. Wait for recovery timer
4570 * to enter recovery. The snd_holes have already
4573 if (SEQ_GEQ(th
->th_ack
, tp
->snd_recover
) ||
4574 TAILQ_EMPTY(&tp
->snd_holes
)) {
4575 tp
->t_timer
[TCPT_DELAYFR
] = 0;
4576 tp
->t_flagsext
&= ~TF_DELAY_RECOVERY
;
4577 EXIT_FASTRECOVERY(tp
);
4578 tcp_ccdbg_trace(tp
, th
,
4579 TCP_CC_EXIT_FASTRECOVERY
);
4583 * We were not in fast recovery. Reset the
4584 * duplicate ack counter.
4587 tp
->t_rexmtthresh
= tcprexmtthresh
;
4592 * If we reach this point, ACK is not a duplicate,
4593 * i.e., it ACKs something we sent.
4595 if (tp
->t_flags
& TF_NEEDSYN
) {
4597 * T/TCP: Connection was half-synchronized, and our
4598 * SYN has been ACK'd (so connection is now fully
4599 * synchronized). Go to non-starred state,
4600 * increment snd_una for ACK of SYN, and check if
4601 * we can do window scaling.
4603 tp
->t_flags
&= ~TF_NEEDSYN
;
4605 /* Do window scaling? */
4606 if (TCP_WINDOW_SCALE_ENABLED(tp
)) {
4607 tp
->snd_scale
= tp
->requested_s_scale
;
4608 tp
->rcv_scale
= tp
->request_r_scale
;
4613 VERIFY(SEQ_GEQ(th
->th_ack
, tp
->snd_una
));
4614 acked
= BYTES_ACKED(th
, tp
);
4615 tcpstat
.tcps_rcvackpack
++;
4616 tcpstat
.tcps_rcvackbyte
+= acked
;
4619 * If the last packet was a retransmit, make sure
4620 * it was not spurious.
4622 * This will also take care of congestion window
4623 * adjustment if a last packet was recovered due to a
4626 tcp_bad_rexmt_check(tp
, th
, &to
);
4628 /* Recalculate the RTT */
4629 tcp_compute_rtt(tp
, &to
, th
);
4632 * If all outstanding data is acked, stop retransmit
4633 * timer and remember to restart (more output or persist).
4634 * If there is more data to be acked, restart retransmit
4635 * timer, using current (possibly backed-off) value.
4637 TCP_RESET_REXMT_STATE(tp
);
4638 TCPT_RANGESET(tp
->t_rxtcur
, TCP_REXMTVAL(tp
),
4639 tp
->t_rttmin
, TCPTV_REXMTMAX
,
4640 TCP_ADD_REXMTSLOP(tp
));
4641 if (th
->th_ack
== tp
->snd_max
) {
4642 tp
->t_timer
[TCPT_REXMT
] = 0;
4643 tp
->t_timer
[TCPT_PTO
] = 0;
4645 } else if (tp
->t_timer
[TCPT_PERSIST
] == 0)
4646 tp
->t_timer
[TCPT_REXMT
] = OFFSET_FROM_START(tp
,
4650 * If no data (only SYN) was ACK'd, skip rest of ACK
4657 * When outgoing data has been acked (except the SYN+data), we
4658 * mark this connection as "sending good" for TFO.
4660 if ((tp
->t_tfo_stats
& TFO_S_SYN_DATA_SENT
) &&
4661 !(tp
->t_tfo_flags
& TFO_F_NO_SNDPROBING
) &&
4662 !(th
->th_flags
& TH_SYN
))
4663 tp
->t_tfo_flags
|= TFO_F_NO_SNDPROBING
;
4666 * If TH_ECE is received, make sure that ECN is enabled
4667 * on that connection and we have sent ECT on data packets.
4669 if ((thflags
& TH_ECE
) != 0 && TCP_ECN_ENABLED(tp
) &&
4670 (tp
->ecn_flags
& TE_SENDIPECT
)) {
4672 * Reduce the congestion window if we haven't
4675 if (!IN_FASTRECOVERY(tp
)) {
4676 tcp_reduce_congestion_window(tp
);
4677 tp
->ecn_flags
|= (TE_INRECOVERY
|TE_SENDCWR
);
4679 * Also note that the connection received
4682 tp
->ecn_flags
|= TE_RECV_ECN_ECE
;
4683 INP_INC_IFNET_STAT(inp
, ecn_recv_ece
);
4684 tcpstat
.tcps_ecn_recv_ece
++;
4685 tcp_ccdbg_trace(tp
, th
, TCP_CC_ECN_RCVD
);
4690 * When new data is acked, open the congestion window.
4691 * The specifics of how this is achieved are up to the
4692 * congestion control algorithm in use for this connection.
4694 * The calculations in this function assume that snd_una is
4697 if (!IN_FASTRECOVERY(tp
)) {
4698 if (CC_ALGO(tp
)->ack_rcvd
!= NULL
)
4699 CC_ALGO(tp
)->ack_rcvd(tp
, th
);
4700 tcp_ccdbg_trace(tp
, th
, TCP_CC_ACK_RCVD
);
4702 if (acked
> so
->so_snd
.sb_cc
) {
4703 tp
->snd_wnd
-= so
->so_snd
.sb_cc
;
4704 sbdrop(&so
->so_snd
, (int)so
->so_snd
.sb_cc
);
4705 if (so
->so_flags
& SOF_ENABLE_MSGS
) {
4706 so
->so_msg_state
->msg_serial_bytes
-=
4707 (int)so
->so_snd
.sb_cc
;
4711 sbdrop(&so
->so_snd
, acked
);
4712 if (so
->so_flags
& SOF_ENABLE_MSGS
) {
4713 so
->so_msg_state
->msg_serial_bytes
-=
4716 tcp_sbsnd_trim(&so
->so_snd
);
4717 tp
->snd_wnd
-= acked
;
4720 /* detect una wraparound */
4721 if ( !IN_FASTRECOVERY(tp
) &&
4722 SEQ_GT(tp
->snd_una
, tp
->snd_recover
) &&
4723 SEQ_LEQ(th
->th_ack
, tp
->snd_recover
))
4724 tp
->snd_recover
= th
->th_ack
- 1;
4726 if (IN_FASTRECOVERY(tp
) &&
4727 SEQ_GEQ(th
->th_ack
, tp
->snd_recover
))
4728 EXIT_FASTRECOVERY(tp
);
4730 tp
->snd_una
= th
->th_ack
;
4732 if (SACK_ENABLED(tp
)) {
4733 if (SEQ_GT(tp
->snd_una
, tp
->snd_recover
))
4734 tp
->snd_recover
= tp
->snd_una
;
4736 if (SEQ_LT(tp
->snd_nxt
, tp
->snd_una
))
4737 tp
->snd_nxt
= tp
->snd_una
;
4738 if (!SLIST_EMPTY(&tp
->t_rxt_segments
) &&
4739 !TCP_DSACK_SEQ_IN_WINDOW(tp
, tp
->t_dsack_lastuna
,
4741 tcp_rxtseg_clean(tp
);
4742 if ((tp
->t_flagsext
& TF_MEASURESNDBW
) != 0 &&
4743 tp
->t_bwmeas
!= NULL
)
4744 tcp_bwmeas_check(tp
);
4747 * sowwakeup must happen after snd_una, et al. are
4748 * updated so that the sequence numbers are in sync with
4753 if (!SLIST_EMPTY(&tp
->t_notify_ack
))
4754 tcp_notify_acknowledgement(tp
, so
);
4756 switch (tp
->t_state
) {
4759 * In FIN_WAIT_1 STATE in addition to the processing
4760 * for the ESTABLISHED state if our FIN is now acknowledged
4761 * then enter FIN_WAIT_2.
4763 case TCPS_FIN_WAIT_1
:
4764 if (ourfinisacked
) {
4766 * If we can't receive any more
4767 * data, then closing user can proceed.
4768 * Starting the TCPT_2MSL timer is contrary to the
4769 * specification, but if we don't get a FIN
4770 * we'll hang forever.
4772 if (so
->so_state
& SS_CANTRCVMORE
) {
4773 tp
->t_timer
[TCPT_2MSL
] = OFFSET_FROM_START(tp
,
4774 TCP_CONN_MAXIDLE(tp
));
4775 isconnected
= FALSE
;
4776 isdisconnected
= TRUE
;
4778 DTRACE_TCP4(state__change
, void, NULL
,
4779 struct inpcb
*, inp
,
4781 int32_t, TCPS_FIN_WAIT_2
);
4782 tp
->t_state
= TCPS_FIN_WAIT_2
;
4783 /* fall through and make sure we also recognize
4784 * data ACKed with the FIN
4790 * In CLOSING STATE in addition to the processing for
4791 * the ESTABLISHED state if the ACK acknowledges our FIN
4792 * then enter the TIME-WAIT state, otherwise ignore
4796 if (ourfinisacked
) {
4797 DTRACE_TCP4(state__change
, void, NULL
,
4798 struct inpcb
*, inp
,
4800 int32_t, TCPS_TIME_WAIT
);
4801 tp
->t_state
= TCPS_TIME_WAIT
;
4802 tcp_canceltimers(tp
);
4803 if (tp
->t_flagsext
& TF_NOTIMEWAIT
) {
4804 tp
->t_flags
|= TF_CLOSING
;
4806 add_to_time_wait(tp
, 2 * tcp_msl
);
4808 isconnected
= FALSE
;
4809 isdisconnected
= TRUE
;
4814 * In LAST_ACK, we may still be waiting for data to drain
4815 * and/or to be acked, as well as for the ack of our FIN.
4816 * If our FIN is now acknowledged, delete the TCB,
4817 * enter the closed state and return.
4820 if (ourfinisacked
) {
4827 * In TIME_WAIT state the only thing that should arrive
4828 * is a retransmission of the remote FIN. Acknowledge
4829 * it and restart the finack timer.
4831 case TCPS_TIME_WAIT
:
4832 add_to_time_wait(tp
, 2 * tcp_msl
);
4837 * If there is a SACK option on the ACK and we
4838 * haven't seen any duplicate acks before, count
4839 * it as a duplicate ack even if the cumulative
4840 * ack is advanced. If the receiver delayed an
4841 * ack and detected loss afterwards, then the ack
4842 * will advance cumulative ack and will also have
4843 * a SACK option. So counting it as one duplicate
4846 if (sack_ackadv
== 1 &&
4847 tp
->t_state
== TCPS_ESTABLISHED
&&
4848 SACK_ENABLED(tp
) && sack_bytes_acked
> 0 &&
4849 to
.to_nsacks
> 0 && tp
->t_dupacks
== 0 &&
4850 SEQ_LEQ(th
->th_ack
, tp
->snd_una
) && tlen
== 0 &&
4851 !(tp
->t_flagsext
& TF_PKTS_REORDERED
)) {
4852 tcpstat
.tcps_sack_ackadv
++;
4853 goto process_dupack
;
4859 * Update window information.
4861 if (tcp_update_window(tp
, thflags
, th
, tiwin
, tlen
))
4865 * Process segments with URG.
4867 if ((thflags
& TH_URG
) && th
->th_urp
&&
4868 TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
4870 * This is a kludge, but if we receive and accept
4871 * random urgent pointers, we'll crash in
4872 * soreceive. It's hard to imagine someone
4873 * actually wanting to send this much urgent data.
4875 if (th
->th_urp
+ so
->so_rcv
.sb_cc
> sb_max
) {
4876 th
->th_urp
= 0; /* XXX */
4877 thflags
&= ~TH_URG
; /* XXX */
4878 goto dodata
; /* XXX */
4881 * If this segment advances the known urgent pointer,
4882 * then mark the data stream. This should not happen
4883 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
4884 * a FIN has been received from the remote side.
4885 * In these states we ignore the URG.
4887 * According to RFC961 (Assigned Protocols),
4888 * the urgent pointer points to the last octet
4889 * of urgent data. We continue, however,
4890 * to consider it to indicate the first octet
4891 * of data past the urgent section as the original
4892 * spec states (in one of two places).
4894 if (SEQ_GT(th
->th_seq
+th
->th_urp
, tp
->rcv_up
)) {
4895 tp
->rcv_up
= th
->th_seq
+ th
->th_urp
;
4896 so
->so_oobmark
= so
->so_rcv
.sb_cc
+
4897 (tp
->rcv_up
- tp
->rcv_nxt
) - 1;
4898 if (so
->so_oobmark
== 0) {
4899 so
->so_state
|= SS_RCVATMARK
;
4900 postevent(so
, 0, EV_OOB
);
4903 tp
->t_oobflags
&= ~(TCPOOB_HAVEDATA
| TCPOOB_HADDATA
);
4906 * Remove out of band data so doesn't get presented to user.
4907 * This can happen independent of advancing the URG pointer,
4908 * but if two URG's are pending at once, some out-of-band
4909 * data may creep in... ick.
4911 if (th
->th_urp
<= (u_int32_t
)tlen
4913 && (so
->so_options
& SO_OOBINLINE
) == 0
4916 tcp_pulloutofband(so
, th
, m
,
4917 drop_hdrlen
); /* hdr drop is delayed */
4920 * If no out of band data is expected,
4921 * pull receive urgent pointer along
4922 * with the receive window.
4924 if (SEQ_GT(tp
->rcv_nxt
, tp
->rcv_up
))
4925 tp
->rcv_up
= tp
->rcv_nxt
;
4929 /* Set socket's connect or disconnect state correcly before doing data.
4930 * The following might unlock the socket if there is an upcall or a socket
4935 } else if (isdisconnected
) {
4936 soisdisconnected(so
);
4939 /* Let's check the state of pcb just to make sure that it did not get closed
4940 * when we unlocked above
4942 if (inp
->inp_state
== INPCB_STATE_DEAD
) {
4943 /* Just drop the packet that we are processing and return */
4948 * Process the segment text, merging it into the TCP sequencing queue,
4949 * and arranging for acknowledgment of receipt if necessary.
4950 * This process logically involves adjusting tp->rcv_wnd as data
4951 * is presented to the user (this happens in tcp_usrreq.c,
4952 * case PRU_RCVD). If a FIN has already been received on this
4953 * connection then we just ignore the text.
4955 * If we are in SYN-received state and got a valid TFO cookie, we want
4956 * to process the data.
4958 if ((tlen
|| (thflags
& TH_FIN
)) &&
4959 TCPS_HAVERCVDFIN(tp
->t_state
) == 0 &&
4960 (TCPS_HAVEESTABLISHED(tp
->t_state
) ||
4961 (tp
->t_state
== TCPS_SYN_RECEIVED
&&
4962 (tp
->t_tfo_flags
& TFO_F_COOKIE_VALID
)))) {
4963 tcp_seq save_start
= th
->th_seq
;
4964 tcp_seq save_end
= th
->th_seq
+ tlen
;
4965 m_adj(m
, drop_hdrlen
); /* delayed header drop */
4967 * Insert segment which includes th into TCP reassembly queue
4968 * with control block tp. Set thflags to whether reassembly now
4969 * includes a segment with FIN. This handles the common case
4970 * inline (segment is the next to be received on an established
4971 * connection, and the queue is empty), avoiding linkage into
4972 * and removal from the queue and repetition of various
4974 * Set DELACK for segments received in order, but ack
4975 * immediately when segments are out of order (so
4976 * fast retransmit can work).
4978 if (th
->th_seq
== tp
->rcv_nxt
&& LIST_EMPTY(&tp
->t_segq
)) {
4979 TCP_INC_VAR(tp
->t_unacksegs
, nlropkts
);
4981 * Calculate the RTT on the receiver only if the
4982 * connection is in streaming mode and the last
4983 * packet was not an end-of-write
4985 if (tp
->t_flags
& TF_STREAMING_ON
)
4986 tcp_compute_rtt(tp
, &to
, th
);
4988 if (DELAY_ACK(tp
, th
) &&
4989 ((tp
->t_flags
& TF_ACKNOW
) == 0) ) {
4990 if ((tp
->t_flags
& TF_DELACK
) == 0) {
4991 tp
->t_flags
|= TF_DELACK
;
4992 tp
->t_timer
[TCPT_DELACK
] =
4993 OFFSET_FROM_START(tp
, tcp_delack
);
4997 tp
->t_flags
|= TF_ACKNOW
;
4999 tp
->rcv_nxt
+= tlen
;
5000 thflags
= th
->th_flags
& TH_FIN
;
5001 TCP_INC_VAR(tcpstat
.tcps_rcvpack
, nlropkts
);
5002 tcpstat
.tcps_rcvbyte
+= tlen
;
5003 if (nstat_collect
) {
5004 if (m
->m_pkthdr
.pkt_flags
& PKTF_SW_LRO_PKT
) {
5005 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
5006 rxpackets
, m
->m_pkthdr
.lro_npkts
);
5008 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
5011 INP_ADD_STAT(inp
, cell
, wifi
, wired
,
5013 inp_set_activity_bitmap(inp
);
5015 tcp_sbrcv_grow(tp
, &so
->so_rcv
, &to
, tlen
,
5016 TCP_AUTORCVBUF_MAX(ifp
));
5017 so_recv_data_stat(so
, m
, drop_hdrlen
);
5019 if (sbappendstream_rcvdemux(so
, m
,
5020 th
->th_seq
- (tp
->irs
+ 1), 0)) {
5024 thflags
= tcp_reass(tp
, th
, &tlen
, m
, ifp
);
5025 tp
->t_flags
|= TF_ACKNOW
;
5028 if ((tlen
> 0 || (th
->th_flags
& TH_FIN
)) && SACK_ENABLED(tp
)) {
5029 if (th
->th_flags
& TH_FIN
)
5031 tcp_update_sack_list(tp
, save_start
, save_end
);
5034 tcp_adaptive_rwtimo_check(tp
, tlen
);
5037 tcp_tfo_rcv_data(tp
);
5039 if (tp
->t_flags
& TF_DELACK
)
5043 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
5044 (((ip6
->ip6_src
.s6_addr16
[0]) << 16) | (ip6
->ip6_dst
.s6_addr16
[0])),
5045 th
->th_seq
, th
->th_ack
, th
->th_win
);
5050 KERNEL_DEBUG(DBG_LAYER_END
, ((th
->th_dport
<< 16) | th
->th_sport
),
5051 (((ip
->ip_src
.s_addr
& 0xffff) << 16) | (ip
->ip_dst
.s_addr
& 0xffff)),
5052 th
->th_seq
, th
->th_ack
, th
->th_win
);
5057 if ((so
->so_flags
& SOF_MP_SUBFLOW
) && tlen
== 0 &&
5058 (m
->m_pkthdr
.pkt_flags
& PKTF_MPTCP_DFIN
) &&
5059 (m
->m_pkthdr
.pkt_flags
& PKTF_MPTCP
)) {
5060 m_adj(m
, drop_hdrlen
); /* delayed header drop */
5061 mptcp_input(tptomptp(tp
)->mpt_mpte
, m
);
5062 tp
->t_flags
|= TF_ACKNOW
;
5070 * If FIN is received ACK the FIN and let the user know
5071 * that the connection is closing.
5073 if (thflags
& TH_FIN
) {
5074 if (TCPS_HAVERCVDFIN(tp
->t_state
) == 0) {
5076 postevent(so
, 0, EV_FIN
);
5078 * If connection is half-synchronized
5079 * (ie NEEDSYN flag on) then delay ACK,
5080 * so it may be piggybacked when SYN is sent.
5081 * Otherwise, since we received a FIN then no
5082 * more input can be expected, send ACK now.
5084 TCP_INC_VAR(tp
->t_unacksegs
, nlropkts
);
5085 if (DELAY_ACK(tp
, th
) && (tp
->t_flags
& TF_NEEDSYN
)) {
5086 if ((tp
->t_flags
& TF_DELACK
) == 0) {
5087 tp
->t_flags
|= TF_DELACK
;
5088 tp
->t_timer
[TCPT_DELACK
] = OFFSET_FROM_START(tp
, tcp_delack
);
5091 tp
->t_flags
|= TF_ACKNOW
;
5095 switch (tp
->t_state
) {
5098 * In SYN_RECEIVED and ESTABLISHED STATES
5099 * enter the CLOSE_WAIT state.
5101 case TCPS_SYN_RECEIVED
:
5102 tp
->t_starttime
= tcp_now
;
5103 case TCPS_ESTABLISHED
:
5104 DTRACE_TCP4(state__change
, void, NULL
, struct inpcb
*, inp
,
5105 struct tcpcb
*, tp
, int32_t, TCPS_CLOSE_WAIT
);
5106 tp
->t_state
= TCPS_CLOSE_WAIT
;
5110 * If still in FIN_WAIT_1 STATE FIN has not been acked so
5111 * enter the CLOSING state.
5113 case TCPS_FIN_WAIT_1
:
5114 DTRACE_TCP4(state__change
, void, NULL
, struct inpcb
*, inp
,
5115 struct tcpcb
*, tp
, int32_t, TCPS_CLOSING
);
5116 tp
->t_state
= TCPS_CLOSING
;
5120 * In FIN_WAIT_2 state enter the TIME_WAIT state,
5121 * starting the time-wait timer, turning off the other
5124 case TCPS_FIN_WAIT_2
:
5125 DTRACE_TCP4(state__change
, void, NULL
,
5126 struct inpcb
*, inp
,
5128 int32_t, TCPS_TIME_WAIT
);
5129 tp
->t_state
= TCPS_TIME_WAIT
;
5130 tcp_canceltimers(tp
);
5131 tp
->t_flags
|= TF_ACKNOW
;
5132 if (tp
->t_flagsext
& TF_NOTIMEWAIT
) {
5133 tp
->t_flags
|= TF_CLOSING
;
5135 add_to_time_wait(tp
, 2 * tcp_msl
);
5137 soisdisconnected(so
);
5141 * In TIME_WAIT state restart the 2 MSL time_wait timer.
5143 case TCPS_TIME_WAIT
:
5144 add_to_time_wait(tp
, 2 * tcp_msl
);
5149 if (so
->so_options
& SO_DEBUG
)
5150 tcp_trace(TA_INPUT
, ostate
, tp
, (void *)tcp_saveipgen
,
5155 * Return any desired output.
5157 if (needoutput
|| (tp
->t_flags
& TF_ACKNOW
)) {
5158 (void) tcp_output(tp
);
5161 tcp_check_timer_state(tp
);
5164 socket_unlock(so
, 1);
5165 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
5170 * Generate an ACK dropping incoming segment if it occupies
5171 * sequence space, where the ACK reflects our state.
5173 * We can now skip the test for the RST flag since all
5174 * paths to this code happen after packets containing
5175 * RST have been dropped.
5177 * In the SYN-RECEIVED state, don't send an ACK unless the
5178 * segment we received passes the SYN-RECEIVED ACK test.
5179 * If it fails send a RST. This breaks the loop in the
5180 * "LAND" DoS attack, and also prevents an ACK storm
5181 * between two listening ports that have been sent forged
5182 * SYN segments, each with the source address of the other.
5184 if (tp
->t_state
== TCPS_SYN_RECEIVED
&& (thflags
& TH_ACK
) &&
5185 (SEQ_GT(tp
->snd_una
, th
->th_ack
) ||
5186 SEQ_GT(th
->th_ack
, tp
->snd_max
)) ) {
5187 rstreason
= BANDLIM_RST_OPENPORT
;
5188 IF_TCP_STATINC(ifp
, dospacket
);
5192 if (so
->so_options
& SO_DEBUG
)
5193 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
5197 tp
->t_flags
|= TF_ACKNOW
;
5198 (void) tcp_output(tp
);
5200 /* Don't need to check timer state as we should have done it during tcp_output */
5201 socket_unlock(so
, 1);
5202 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
5204 dropwithresetnosock
:
5208 * Generate a RST, dropping incoming segment.
5209 * Make ACK acceptable to originator of segment.
5210 * Don't bother to respond if destination was broadcast/multicast.
5212 if ((thflags
& TH_RST
) || m
->m_flags
& (M_BCAST
|M_MCAST
))
5216 if (IN6_IS_ADDR_MULTICAST(&ip6
->ip6_dst
) ||
5217 IN6_IS_ADDR_MULTICAST(&ip6
->ip6_src
))
5221 if (IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
)) ||
5222 IN_MULTICAST(ntohl(ip
->ip_src
.s_addr
)) ||
5223 ip
->ip_src
.s_addr
== htonl(INADDR_BROADCAST
) ||
5224 in_broadcast(ip
->ip_dst
, m
->m_pkthdr
.rcvif
))
5226 /* IPv6 anycast check is done at tcp6_input() */
5229 * Perform bandwidth limiting.
5232 if (badport_bandlim(rstreason
) < 0)
5237 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
5238 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
5241 bzero(&tra
, sizeof(tra
));
5242 tra
.ifscope
= ifscope
;
5243 tra
.awdl_unrestricted
= 1;
5244 tra
.intcoproc_allowed
= 1;
5245 if (thflags
& TH_ACK
)
5246 /* mtod() below is safe as long as hdr dropping is delayed */
5247 tcp_respond(tp
, mtod(m
, void *), th
, m
, (tcp_seq
)0, th
->th_ack
,
5250 if (thflags
& TH_SYN
)
5252 /* mtod() below is safe as long as hdr dropping is delayed */
5253 tcp_respond(tp
, mtod(m
, void *), th
, m
, th
->th_seq
+tlen
,
5254 (tcp_seq
)0, TH_RST
|TH_ACK
, &tra
);
5256 /* destroy temporarily created socket */
5259 socket_unlock(so
, 1);
5260 } else if ((inp
!= NULL
) && (nosock
== 0)) {
5261 socket_unlock(so
, 1);
5263 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
5269 * Drop space held by incoming segment and return.
5272 if (tp
== 0 || (tp
->t_inpcb
->inp_socket
->so_options
& SO_DEBUG
))
5273 tcp_trace(TA_DROP
, ostate
, tp
, (void *)tcp_saveipgen
,
5277 /* destroy temporarily created socket */
5280 socket_unlock(so
, 1);
5282 else if (nosock
== 0) {
5283 socket_unlock(so
, 1);
5285 KERNEL_DEBUG(DBG_FNC_TCP_INPUT
| DBG_FUNC_END
,0,0,0,0,0);
5290 * Parse TCP options and place in tcpopt.
5293 tcp_dooptions(struct tcpcb
*tp
, u_char
*cp
, int cnt
, struct tcphdr
*th
,
5299 for (; cnt
> 0; cnt
-= optlen
, cp
+= optlen
) {
5301 if (opt
== TCPOPT_EOL
)
5303 if (opt
== TCPOPT_NOP
)
5309 if (optlen
< 2 || optlen
> cnt
)
5318 if (optlen
!= TCPOLEN_MAXSEG
)
5320 if (!(th
->th_flags
& TH_SYN
))
5322 bcopy((char *) cp
+ 2, (char *) &mss
, sizeof(mss
));
5325 to
->to_flags
|= TOF_MSS
;
5329 if (optlen
!= TCPOLEN_WINDOW
)
5331 if (!(th
->th_flags
& TH_SYN
))
5333 to
->to_flags
|= TOF_SCALE
;
5334 to
->to_requested_s_scale
= min(cp
[2], TCP_MAX_WINSHIFT
);
5337 case TCPOPT_TIMESTAMP
:
5338 if (optlen
!= TCPOLEN_TIMESTAMP
)
5340 to
->to_flags
|= TOF_TS
;
5341 bcopy((char *)cp
+ 2,
5342 (char *)&to
->to_tsval
, sizeof(to
->to_tsval
));
5343 NTOHL(to
->to_tsval
);
5344 bcopy((char *)cp
+ 6,
5345 (char *)&to
->to_tsecr
, sizeof(to
->to_tsecr
));
5346 NTOHL(to
->to_tsecr
);
5347 /* Re-enable sending Timestamps if we received them */
5348 if (!(tp
->t_flags
& TF_REQ_TSTMP
) &&
5349 tcp_do_rfc1323
== 1)
5350 tp
->t_flags
|= TF_REQ_TSTMP
;
5352 case TCPOPT_SACK_PERMITTED
:
5354 optlen
!= TCPOLEN_SACK_PERMITTED
)
5356 if (th
->th_flags
& TH_SYN
)
5357 to
->to_flags
|= TOF_SACK
;
5360 if (optlen
<= 2 || (optlen
- 2) % TCPOLEN_SACK
!= 0)
5362 to
->to_nsacks
= (optlen
- 2) / TCPOLEN_SACK
;
5363 to
->to_sacks
= cp
+ 2;
5364 tcpstat
.tcps_sack_rcv_blocks
++;
5367 case TCPOPT_FASTOPEN
:
5368 if (optlen
== TCPOLEN_FASTOPEN_REQ
) {
5369 if (tp
->t_state
!= TCPS_LISTEN
)
5372 to
->to_flags
|= TOF_TFOREQ
;
5374 if (optlen
< TCPOLEN_FASTOPEN_REQ
||
5375 (optlen
- TCPOLEN_FASTOPEN_REQ
) > TFO_COOKIE_LEN_MAX
||
5376 (optlen
- TCPOLEN_FASTOPEN_REQ
) < TFO_COOKIE_LEN_MIN
)
5378 if (tp
->t_state
!= TCPS_LISTEN
&&
5379 tp
->t_state
!= TCPS_SYN_SENT
)
5382 to
->to_flags
|= TOF_TFO
;
5383 to
->to_tfo
= cp
+ 1;
5388 case TCPOPT_MULTIPATH
:
5389 tcp_do_mptcp_options(tp
, cp
, th
, to
, optlen
);
5397 tcp_finalize_options(struct tcpcb
*tp
, struct tcpopt
*to
, unsigned int ifscope
)
5399 if (to
->to_flags
& TOF_TS
) {
5400 tp
->t_flags
|= TF_RCVD_TSTMP
;
5401 tp
->ts_recent
= to
->to_tsval
;
5402 tp
->ts_recent_age
= tcp_now
;
5405 if (to
->to_flags
& TOF_MSS
)
5406 tcp_mss(tp
, to
->to_mss
, ifscope
);
5407 if (SACK_ENABLED(tp
)) {
5408 if (!(to
->to_flags
& TOF_SACK
))
5409 tp
->t_flagsext
&= ~(TF_SACK_ENABLE
);
5411 tp
->t_flags
|= TF_SACK_PERMIT
;
5413 if (to
->to_flags
& TOF_SCALE
) {
5414 tp
->t_flags
|= TF_RCVD_SCALE
;
5415 tp
->requested_s_scale
= to
->to_requested_s_scale
;
5417 /* Re-enable window scaling, if the option is received */
5418 if (tp
->request_r_scale
> 0)
5419 tp
->t_flags
|= TF_REQ_SCALE
;
5424 * Pull out of band byte out of a segment so
5425 * it doesn't appear in the user's data queue.
5426 * It is still reflected in the segment length for
5427 * sequencing purposes.
5429 * @param off delayed to be droped hdrlen
5432 tcp_pulloutofband(struct socket
*so
, struct tcphdr
*th
, struct mbuf
*m
, int off
)
5434 int cnt
= off
+ th
->th_urp
- 1;
5437 if (m
->m_len
> cnt
) {
5438 char *cp
= mtod(m
, caddr_t
) + cnt
;
5439 struct tcpcb
*tp
= sototcpcb(so
);
5442 tp
->t_oobflags
|= TCPOOB_HAVEDATA
;
5443 bcopy(cp
+1, cp
, (unsigned)(m
->m_len
- cnt
- 1));
5445 if (m
->m_flags
& M_PKTHDR
)
5454 panic("tcp_pulloutofband");
5458 get_base_rtt(struct tcpcb
*tp
)
5460 struct rtentry
*rt
= tp
->t_inpcb
->inp_route
.ro_rt
;
5461 return ((rt
== NULL
) ? 0 : rt
->rtt_min
);
5464 /* Each value of RTT base represents the minimum RTT seen in a minute.
5465 * We keep upto N_RTT_BASE minutes worth of history.
5468 update_base_rtt(struct tcpcb
*tp
, uint32_t rtt
)
5470 u_int32_t base_rtt
, i
;
5473 if ((rt
= tp
->t_inpcb
->inp_route
.ro_rt
) == NULL
)
5475 if (rt
->rtt_expire_ts
== 0) {
5477 if (rt
->rtt_expire_ts
!= 0) {
5481 rt
->rtt_expire_ts
= tcp_now
;
5483 rt
->rtt_hist
[0] = rtt
;
5491 * If the recv side is being throttled, check if the
5492 * current RTT is closer to the base RTT seen in
5493 * first (recent) two slots. If so, unthrottle the stream.
5495 if ((tp
->t_flagsext
& TF_RECV_THROTTLE
) &&
5496 (int)(tcp_now
- tp
->t_recv_throttle_ts
) >= TCP_RECV_THROTTLE_WIN
) {
5497 base_rtt
= rt
->rtt_min
;
5498 if (tp
->t_rttcur
<= (base_rtt
+ target_qdelay
)) {
5499 tp
->t_flagsext
&= ~TF_RECV_THROTTLE
;
5500 tp
->t_recv_throttle_ts
= 0;
5503 #endif /* TRAFFIC_MGT */
5504 if ((int)(tcp_now
- rt
->rtt_expire_ts
) >=
5505 TCP_RTT_HISTORY_EXPIRE_TIME
) {
5507 /* check the condition again to avoid race */
5508 if ((int)(tcp_now
- rt
->rtt_expire_ts
) >=
5509 TCP_RTT_HISTORY_EXPIRE_TIME
) {
5511 if (rt
->rtt_index
>= NRTT_HIST
)
5513 rt
->rtt_hist
[rt
->rtt_index
] = rtt
;
5514 rt
->rtt_expire_ts
= tcp_now
;
5516 rt
->rtt_hist
[rt
->rtt_index
] =
5517 min(rt
->rtt_hist
[rt
->rtt_index
], rtt
);
5519 /* forget the old value and update minimum */
5521 for (i
= 0; i
< NRTT_HIST
; ++i
) {
5522 if (rt
->rtt_hist
[i
] != 0 &&
5523 (rt
->rtt_min
== 0 ||
5524 rt
->rtt_hist
[i
] < rt
->rtt_min
))
5525 rt
->rtt_min
= rt
->rtt_hist
[i
];
5529 rt
->rtt_hist
[rt
->rtt_index
] =
5530 min(rt
->rtt_hist
[rt
->rtt_index
], rtt
);
5531 if (rt
->rtt_min
== 0)
5534 rt
->rtt_min
= min(rt
->rtt_min
, rtt
);
5539 * If we have a timestamp reply, update smoothed RTT. If no timestamp is
5540 * present but transmit timer is running and timed sequence number was
5541 * acked, update smoothed RTT.
5543 * If timestamps are supported, a receiver can update RTT even if
5544 * there is no outstanding data.
5546 * Some boxes send broken timestamp replies during the SYN+ACK phase,
5547 * ignore timestamps of 0or we could calculate a huge RTT and blow up
5548 * the retransmit timer.
5551 tcp_compute_rtt(struct tcpcb
*tp
, struct tcpopt
*to
, struct tcphdr
*th
)
5554 VERIFY(to
!= NULL
&& th
!= NULL
);
5555 if (tp
->t_rtttime
!= 0 && SEQ_GT(th
->th_ack
, tp
->t_rtseq
)) {
5556 u_int32_t pipe_ack_val
;
5557 rtt
= tcp_now
- tp
->t_rtttime
;
5559 * Compute pipe ack -- the amount of data acknowledged
5562 if (SEQ_GT(th
->th_ack
, tp
->t_pipeack_lastuna
)) {
5563 pipe_ack_val
= th
->th_ack
- tp
->t_pipeack_lastuna
;
5564 /* Update the sample */
5565 tp
->t_pipeack_sample
[tp
->t_pipeack_ind
++] =
5567 tp
->t_pipeack_ind
%= TCP_PIPEACK_SAMPLE_COUNT
;
5569 /* Compute the max of the pipeack samples */
5570 pipe_ack_val
= tcp_get_max_pipeack(tp
);
5571 tp
->t_pipeack
= (pipe_ack_val
>
5572 TCP_CC_CWND_INIT_BYTES
) ?
5575 /* start another measurement */
5578 if (((to
->to_flags
& TOF_TS
) != 0) &&
5579 (to
->to_tsecr
!= 0) &&
5580 TSTMP_GEQ(tcp_now
, to
->to_tsecr
)) {
5581 tcp_xmit_timer(tp
, (tcp_now
- to
->to_tsecr
),
5582 to
->to_tsecr
, th
->th_ack
);
5583 } else if (rtt
> 0) {
5584 tcp_xmit_timer(tp
, rtt
, 0, th
->th_ack
);
5589 * Collect new round-trip time estimate and update averages and
5593 tcp_xmit_timer(struct tcpcb
*tp
, int rtt
,
5594 u_int32_t tsecr
, tcp_seq th_ack
)
5599 * On AWDL interface, the initial RTT measurement on SYN
5600 * can be wrong due to peer caching. Avoid the first RTT
5601 * measurement as it might skew up the RTO.
5602 * <rdar://problem/28739046>
5604 if (tp
->t_inpcb
->inp_last_outifp
!= NULL
&&
5605 (tp
->t_inpcb
->inp_last_outifp
->if_eflags
& IFEF_AWDL
) &&
5606 th_ack
== tp
->iss
+ 1)
5609 if (tp
->t_flagsext
& TF_RECOMPUTE_RTT
) {
5610 if (SEQ_GT(th_ack
, tp
->snd_una
) &&
5611 SEQ_LEQ(th_ack
, tp
->snd_max
) &&
5613 TSTMP_GEQ(tsecr
, tp
->t_badrexmt_time
))) {
5615 * We received a new ACk after a
5616 * spurious timeout. Adapt retransmission
5617 * timer as described in rfc 4015.
5619 tp
->t_flagsext
&= ~(TF_RECOMPUTE_RTT
);
5620 tp
->t_badrexmt_time
= 0;
5621 tp
->t_srtt
= max(tp
->t_srtt_prev
, rtt
);
5622 tp
->t_srtt
= tp
->t_srtt
<< TCP_RTT_SHIFT
;
5623 tp
->t_rttvar
= max(tp
->t_rttvar_prev
, (rtt
>> 1));
5624 tp
->t_rttvar
= tp
->t_rttvar
<< TCP_RTTVAR_SHIFT
;
5626 if (tp
->t_rttbest
> (tp
->t_srtt
+ tp
->t_rttvar
))
5627 tp
->t_rttbest
= tp
->t_srtt
+ tp
->t_rttvar
;
5635 tcpstat
.tcps_rttupdated
++;
5640 update_base_rtt(tp
, rtt
);
5643 if (tp
->t_srtt
!= 0) {
5645 * srtt is stored as fixed point with 5 bits after the
5646 * binary point (i.e., scaled by 32). The following magic
5647 * is equivalent to the smoothing algorithm in rfc793 with
5648 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
5651 * Freebsd adjusts rtt to origin 0 by subtracting 1
5652 * from the provided rtt value. This was required because
5653 * of the way t_rtttime was initiailised to 1 before.
5654 * Since we changed t_rtttime to be based on
5655 * tcp_now, this extra adjustment is not needed.
5657 delta
= (rtt
<< TCP_DELTA_SHIFT
)
5658 - (tp
->t_srtt
>> (TCP_RTT_SHIFT
- TCP_DELTA_SHIFT
));
5660 if ((tp
->t_srtt
+= delta
) <= 0)
5664 * We accumulate a smoothed rtt variance (actually, a
5665 * smoothed mean difference), then set the retransmit
5666 * timer to smoothed rtt + 4 times the smoothed variance.
5667 * rttvar is stored as fixed point with 4 bits after the
5668 * binary point (scaled by 16). The following is
5669 * equivalent to rfc793 smoothing with an alpha of .75
5670 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
5671 * rfc793's wired-in beta.
5675 delta
-= tp
->t_rttvar
>> (TCP_RTTVAR_SHIFT
- TCP_DELTA_SHIFT
);
5676 if ((tp
->t_rttvar
+= delta
) <= 0)
5678 if (tp
->t_rttbest
== 0 ||
5679 tp
->t_rttbest
> (tp
->t_srtt
+ tp
->t_rttvar
))
5680 tp
->t_rttbest
= tp
->t_srtt
+ tp
->t_rttvar
;
5683 * No rtt measurement yet - use the unsmoothed rtt.
5684 * Set the variance to half the rtt (so our first
5685 * retransmit happens at 3*rtt).
5687 tp
->t_srtt
= rtt
<< TCP_RTT_SHIFT
;
5688 tp
->t_rttvar
= rtt
<< (TCP_RTTVAR_SHIFT
- 1);
5692 nstat_route_rtt(tp
->t_inpcb
->inp_route
.ro_rt
, tp
->t_srtt
,
5696 * the retransmit should happen at rtt + 4 * rttvar.
5697 * Because of the way we do the smoothing, srtt and rttvar
5698 * will each average +1/2 tick of bias. When we compute
5699 * the retransmit timer, we want 1/2 tick of rounding and
5700 * 1 extra tick because of +-1/2 tick uncertainty in the
5701 * firing of the timer. The bias will give us exactly the
5702 * 1.5 tick we need. But, because the bias is
5703 * statistical, we have to test that we don't drop below
5704 * the minimum feasible timer (which is 2 ticks).
5706 TCPT_RANGESET(tp
->t_rxtcur
, TCP_REXMTVAL(tp
),
5707 max(tp
->t_rttmin
, rtt
+ 2), TCPTV_REXMTMAX
,
5708 TCP_ADD_REXMTSLOP(tp
));
5711 * We received an ack for a packet that wasn't retransmitted;
5712 * it is probably safe to discard any error indications we've
5713 * received recently. This isn't quite right, but close enough
5714 * for now (a route might have failed after we sent a segment,
5715 * and the return path might not be symmetrical).
5717 tp
->t_softerror
= 0;
5720 static inline unsigned int
5721 tcp_maxmtu(struct rtentry
*rt
)
5723 unsigned int maxmtu
;
5724 int interface_mtu
= 0;
5726 RT_LOCK_ASSERT_HELD(rt
);
5727 interface_mtu
= rt
->rt_ifp
->if_mtu
;
5729 if (rt_key(rt
)->sa_family
== AF_INET
&&
5730 INTF_ADJUST_MTU_FOR_CLAT46(rt
->rt_ifp
)) {
5731 interface_mtu
= IN6_LINKMTU(rt
->rt_ifp
);
5732 /* Further adjust the size for CLAT46 expansion */
5733 interface_mtu
-= CLAT46_HDR_EXPANSION_OVERHD
;
5736 if (rt
->rt_rmx
.rmx_mtu
== 0)
5737 maxmtu
= interface_mtu
;
5739 maxmtu
= MIN(rt
->rt_rmx
.rmx_mtu
, interface_mtu
);
5745 static inline unsigned int
5746 tcp_maxmtu6(struct rtentry
*rt
)
5748 unsigned int maxmtu
;
5749 struct nd_ifinfo
*ndi
= NULL
;
5751 RT_LOCK_ASSERT_HELD(rt
);
5752 if ((ndi
= ND_IFINFO(rt
->rt_ifp
)) != NULL
&& !ndi
->initialized
)
5755 lck_mtx_lock(&ndi
->lock
);
5756 if (rt
->rt_rmx
.rmx_mtu
== 0)
5757 maxmtu
= IN6_LINKMTU(rt
->rt_ifp
);
5759 maxmtu
= MIN(rt
->rt_rmx
.rmx_mtu
, IN6_LINKMTU(rt
->rt_ifp
));
5761 lck_mtx_unlock(&ndi
->lock
);
5768 get_maxmtu(struct rtentry
*rt
)
5770 unsigned int maxmtu
= 0;
5772 RT_LOCK_ASSERT_NOTHELD(rt
);
5776 if (rt_key(rt
)->sa_family
== AF_INET6
) {
5777 maxmtu
= tcp_maxmtu6(rt
);
5779 maxmtu
= tcp_maxmtu(rt
);
5788 * Determine a reasonable value for maxseg size.
5789 * If the route is known, check route for mtu.
5790 * If none, use an mss that can be handled on the outgoing
5791 * interface without forcing IP to fragment; if bigger than
5792 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
5793 * to utilize large mbufs. If no route is found, route has no mtu,
5794 * or the destination isn't local, use a default, hopefully conservative
5795 * size (usually 512 or the default IP max size, but no more than the mtu
5796 * of the interface), as we can't discover anything about intervening
5797 * gateways or networks. We also initialize the congestion/slow start
5798 * window. While looking at the routing entry, we also initialize
5799 * other path-dependent parameters from pre-set or cached values
5800 * in the routing entry.
5802 * Also take into account the space needed for options that we
5803 * send regularly. Make maxseg shorter by that amount to assure
5804 * that we can send maxseg amount of data even when the options
5805 * are present. Store the upper limit of the length of options plus
5808 * NOTE that this routine is only called when we process an incoming
5809 * segment, for outgoing segments only tcp_mssopt is called.
5813 tcp_mss(struct tcpcb
*tp
, int offer
, unsigned int input_ifscope
)
5821 struct rmxp_tao
*taop
;
5822 int origoffer
= offer
;
5823 u_int32_t sb_max_corrected
;
5832 isipv6
= ((inp
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
5833 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
5834 : sizeof (struct tcpiphdr
);
5836 #define min_protoh (sizeof (struct tcpiphdr))
5841 rt
= tcp_rtlookup6(inp
, input_ifscope
);
5846 rt
= tcp_rtlookup(inp
, input_ifscope
);
5848 isnetlocal
= (tp
->t_flags
& TF_LOCAL
);
5851 tp
->t_maxopd
= tp
->t_maxseg
=
5853 isipv6
? tcp_v6mssdflt
:
5860 * Slower link window correction:
5861 * If a value is specificied for slowlink_wsize use it for
5862 * PPP links believed to be on a serial modem (speed <128Kbps).
5863 * Excludes 9600bps as it is the default value adversized
5864 * by pseudo-devices over ppp.
5866 if (ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
5867 ifp
->if_baudrate
> 9600 && ifp
->if_baudrate
<= 128000) {
5868 tp
->t_flags
|= TF_SLOWLINK
;
5870 so
= inp
->inp_socket
;
5872 taop
= rmx_taop(rt
->rt_rmx
);
5874 * Offer == -1 means that we didn't receive SYN yet,
5875 * use cached value in that case;
5878 offer
= taop
->tao_mssopt
;
5880 * Offer == 0 means that there was no MSS on the SYN segment,
5881 * in this case we use tcp_mssdflt.
5886 isipv6
? tcp_v6mssdflt
:
5891 * Prevent DoS attack with too small MSS. Round up
5892 * to at least minmss.
5894 offer
= max(offer
, tcp_minmss
);
5896 * Sanity check: make sure that maxopd will be large
5897 * enough to allow some data on segments even is the
5898 * all the option space is used (40bytes). Otherwise
5899 * funny things may happen in tcp_output.
5901 offer
= max(offer
, 64);
5903 taop
->tao_mssopt
= offer
;
5906 * While we're here, check if there's an initial rtt
5907 * or rttvar. Convert from the route-table units
5908 * to scaled multiples of the slow timeout timer.
5910 if (tp
->t_srtt
== 0 && (rtt
= rt
->rt_rmx
.rmx_rtt
) != 0) {
5911 tcp_getrt_rtt(tp
, rt
);
5913 tp
->t_rttmin
= isnetlocal
? tcp_TCPTV_MIN
: TCPTV_REXMTMIN
;
5917 mss
= (isipv6
? tcp_maxmtu6(rt
) : tcp_maxmtu(rt
));
5919 mss
= tcp_maxmtu(rt
);
5923 // At this point, the mss is just the MTU. Adjust if necessary.
5924 mss
= necp_socket_get_effective_mtu(inp
, mss
);
5929 if (rt
->rt_rmx
.rmx_mtu
== 0) {
5933 mss
= min(mss
, tcp_v6mssdflt
);
5937 mss
= min(mss
, tcp_mssdflt
);
5940 mss
= min(mss
, offer
);
5942 * maxopd stores the maximum length of data AND options
5943 * in a segment; maxseg is the amount of data in a normal
5944 * segment. We need to store this value (maxopd) apart
5945 * from maxseg, because now every segment carries options
5946 * and thus we normally have somewhat less data in segments.
5951 * origoffer==-1 indicates, that no segments were received yet.
5952 * In this case we just guess.
5954 if ((tp
->t_flags
& (TF_REQ_TSTMP
|TF_NOOPT
)) == TF_REQ_TSTMP
&&
5956 (tp
->t_flags
& TF_RCVD_TSTMP
) == TF_RCVD_TSTMP
))
5957 mss
-= TCPOLEN_TSTAMP_APPA
;
5960 mss
-= mptcp_adj_mss(tp
, FALSE
);
5965 * Calculate corrected value for sb_max; ensure to upgrade the
5966 * numerator for large sb_max values else it will overflow.
5968 sb_max_corrected
= (sb_max
* (u_int64_t
)MCLBYTES
) / (MSIZE
+ MCLBYTES
);
5971 * If there's a pipesize (ie loopback), change the socket
5972 * buffer to that size only if it's bigger than the current
5973 * sockbuf size. Make the socket buffers an integral
5974 * number of mss units; if the mss is larger than
5975 * the socket buffer, decrease the mss.
5978 bufsize
= rt
->rt_rmx
.rmx_sendpipe
;
5979 if (bufsize
< so
->so_snd
.sb_hiwat
)
5981 bufsize
= so
->so_snd
.sb_hiwat
;
5985 bufsize
= (((bufsize
+ (u_int64_t
)mss
- 1) / (u_int64_t
)mss
) * (u_int64_t
)mss
);
5986 if (bufsize
> sb_max_corrected
)
5987 bufsize
= sb_max_corrected
;
5988 (void)sbreserve(&so
->so_snd
, bufsize
);
5992 ASSERT(tp
->t_maxseg
);
5995 * Update MSS using recommendation from link status report. This is
5998 tcp_update_mss_locked(so
, ifp
);
6001 bufsize
= rt
->rt_rmx
.rmx_recvpipe
;
6002 if (bufsize
< so
->so_rcv
.sb_hiwat
)
6004 bufsize
= so
->so_rcv
.sb_hiwat
;
6005 if (bufsize
> mss
) {
6006 bufsize
= (((bufsize
+ (u_int64_t
)mss
- 1) / (u_int64_t
)mss
) * (u_int64_t
)mss
);
6007 if (bufsize
> sb_max_corrected
)
6008 bufsize
= sb_max_corrected
;
6009 (void)sbreserve(&so
->so_rcv
, bufsize
);
6012 set_tcp_stream_priority(so
);
6014 if (rt
->rt_rmx
.rmx_ssthresh
) {
6016 * There's some sort of gateway or interface
6017 * buffer limit on the path. Use this to set
6018 * slow-start threshold, but set the threshold to
6019 * no less than 2*mss.
6021 tp
->snd_ssthresh
= max(2 * mss
, rt
->rt_rmx
.rmx_ssthresh
);
6022 tcpstat
.tcps_usedssthresh
++;
6024 tp
->snd_ssthresh
= TCP_MAXWIN
<< TCP_MAX_WINSHIFT
;
6028 * Set the slow-start flight size depending on whether this
6029 * is a local network or not.
6031 if (CC_ALGO(tp
)->cwnd_init
!= NULL
)
6032 CC_ALGO(tp
)->cwnd_init(tp
);
6034 tcp_ccdbg_trace(tp
, NULL
, TCP_CC_CWND_INIT
);
6036 /* Route locked during lookup above */
6041 * Determine the MSS option to send on an outgoing SYN.
6044 tcp_mssopt(struct tcpcb
*tp
)
6054 isipv6
= ((tp
->t_inpcb
->inp_vflag
& INP_IPV6
) != 0) ? 1 : 0;
6055 min_protoh
= isipv6
? sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
)
6056 : sizeof (struct tcpiphdr
);
6058 #define min_protoh (sizeof (struct tcpiphdr))
6063 rt
= tcp_rtlookup6(tp
->t_inpcb
, IFSCOPE_NONE
);
6066 rt
= tcp_rtlookup(tp
->t_inpcb
, IFSCOPE_NONE
);
6070 isipv6
? tcp_v6mssdflt
:
6075 * Slower link window correction:
6076 * If a value is specificied for slowlink_wsize use it for PPP links
6077 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
6078 * it is the default value adversized by pseudo-devices over ppp.
6080 if (rt
->rt_ifp
->if_type
== IFT_PPP
&& slowlink_wsize
> 0 &&
6081 rt
->rt_ifp
->if_baudrate
> 9600 && rt
->rt_ifp
->if_baudrate
<= 128000) {
6082 tp
->t_flags
|= TF_SLOWLINK
;
6086 mss
= (isipv6
? tcp_maxmtu6(rt
) : tcp_maxmtu(rt
));
6088 mss
= tcp_maxmtu(rt
);
6090 /* Route locked during lookup above */
6094 // At this point, the mss is just the MTU. Adjust if necessary.
6095 mss
= necp_socket_get_effective_mtu(tp
->t_inpcb
, mss
);
6098 return (mss
- min_protoh
);
6102 * On a partial ack arrives, force the retransmission of the
6103 * next unacknowledged segment. Do not clear tp->t_dupacks.
6104 * By setting snd_nxt to th_ack, this forces retransmission timer to
6108 tcp_newreno_partial_ack(struct tcpcb
*tp
, struct tcphdr
*th
)
6110 tcp_seq onxt
= tp
->snd_nxt
;
6111 u_int32_t ocwnd
= tp
->snd_cwnd
;
6112 tp
->t_timer
[TCPT_REXMT
] = 0;
6113 tp
->t_timer
[TCPT_PTO
] = 0;
6115 tp
->snd_nxt
= th
->th_ack
;
6117 * Set snd_cwnd to one segment beyond acknowledged offset
6118 * (tp->snd_una has not yet been updated when this function
6121 tp
->snd_cwnd
= tp
->t_maxseg
+ BYTES_ACKED(th
, tp
);
6122 tp
->t_flags
|= TF_ACKNOW
;
6123 (void) tcp_output(tp
);
6124 tp
->snd_cwnd
= ocwnd
;
6125 if (SEQ_GT(onxt
, tp
->snd_nxt
))
6128 * Partial window deflation. Relies on fact that tp->snd_una
6131 if (tp
->snd_cwnd
> BYTES_ACKED(th
, tp
))
6132 tp
->snd_cwnd
-= BYTES_ACKED(th
, tp
);
6135 tp
->snd_cwnd
+= tp
->t_maxseg
;
6139 * Drop a random TCP connection that hasn't been serviced yet and
6140 * is eligible for discard. There is a one in qlen chance that
6141 * we will return a null, saying that there are no dropable
6142 * requests. In this case, the protocol specific code should drop
6143 * the new request. This insures fairness.
6145 * The listening TCP socket "head" must be locked
6148 tcp_dropdropablreq(struct socket
*head
)
6150 struct socket
*so
, *sonext
;
6151 unsigned int i
, j
, qlen
;
6152 static u_int32_t rnd
= 0;
6153 static u_int64_t old_runtime
;
6154 static unsigned int cur_cnt
, old_cnt
;
6156 struct inpcb
*inp
= NULL
;
6159 if ((head
->so_options
& SO_ACCEPTCONN
) == 0)
6162 if (TAILQ_EMPTY(&head
->so_incomp
))
6165 so_acquire_accept_list(head
, NULL
);
6166 socket_unlock(head
, 0);
6169 * Check if there is any socket in the incomp queue
6170 * that is closed because of a reset from the peer and is
6171 * waiting to be garbage collected. If so, pick that as
6174 TAILQ_FOREACH_SAFE(so
, &head
->so_incomp
, so_list
, sonext
) {
6175 inp
= sotoinpcb(so
);
6176 tp
= intotcpcb(inp
);
6177 if (tp
!= NULL
&& tp
->t_state
== TCPS_CLOSED
&&
6178 so
->so_head
!= NULL
&&
6179 (so
->so_state
& (SS_INCOMP
|SS_CANTSENDMORE
|SS_CANTRCVMORE
)) ==
6180 (SS_INCOMP
|SS_CANTSENDMORE
|SS_CANTRCVMORE
)) {
6182 * The listen socket is already locked but we
6183 * can lock this socket here without lock ordering
6184 * issues because it is in the incomp queue and
6185 * is not visible to others.
6187 if (socket_try_lock(so
)) {
6196 so
= TAILQ_FIRST(&head
->so_incomp
);
6198 now_sec
= net_uptime();
6199 if ((i
= (now_sec
- old_runtime
)) != 0) {
6200 old_runtime
= now_sec
;
6201 old_cnt
= cur_cnt
/ i
;
6205 qlen
= head
->so_incqlen
;
6207 rnd
= RandomULong();
6209 if (++cur_cnt
> qlen
|| old_cnt
> qlen
) {
6210 rnd
= (314159 * rnd
+ 66329) & 0xffff;
6211 j
= ((qlen
+ 1) * rnd
) >> 16;
6214 so
= TAILQ_NEXT(so
, so_list
);
6216 /* Find a connection that is not already closing (or being served) */
6218 inp
= (struct inpcb
*)so
->so_pcb
;
6220 sonext
= TAILQ_NEXT(so
, so_list
);
6222 if (in_pcb_checkstate(inp
, WNT_ACQUIRE
, 0) != WNT_STOPUSING
) {
6224 * Avoid the issue of a socket being accepted
6225 * by one input thread and being dropped by
6226 * another input thread. If we can't get a hold
6227 * on this mutex, then grab the next socket in
6230 if (socket_try_lock(so
)) {
6232 if ((so
->so_usecount
== 2) &&
6233 (so
->so_state
& SS_INCOMP
) &&
6234 !(so
->so_flags
& SOF_INCOMP_INPROGRESS
)) {
6238 * don't use if being accepted or
6239 * used in any other way
6241 in_pcb_checkstate(inp
, WNT_RELEASE
, 1);
6242 socket_unlock(so
, 1);
6246 * do not try to lock the inp in
6247 * in_pcb_checkstate because the lock
6248 * is already held in some other thread.
6249 * Only drop the inp_wntcnt reference.
6251 in_pcb_checkstate(inp
, WNT_RELEASE
, 1);
6257 socket_lock(head
, 0);
6258 so_release_accept_list(head
);
6262 /* Makes sure socket is still in the right state to be discarded */
6264 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1) == WNT_STOPUSING
) {
6265 socket_unlock(so
, 1);
6266 socket_lock(head
, 0);
6267 so_release_accept_list(head
);
6272 if (so
->so_usecount
!= 2 || !(so
->so_state
& SS_INCOMP
)) {
6273 /* do not discard: that socket is being accepted */
6274 socket_unlock(so
, 1);
6275 socket_lock(head
, 0);
6276 so_release_accept_list(head
);
6280 socket_lock(head
, 0);
6281 TAILQ_REMOVE(&head
->so_incomp
, so
, so_list
);
6284 so
->so_state
&= ~SS_INCOMP
;
6285 so
->so_flags
|= SOF_OVERFLOW
;
6287 so_release_accept_list(head
);
6288 socket_unlock(head
, 0);
6290 socket_lock_assert_owned(so
);
6294 if (inp
->inp_wantcnt
> 0 && inp
->inp_wantcnt
!= WNT_STOPUSING
) {
6296 * Some one has a wantcnt on this pcb. Since WNT_ACQUIRE
6297 * doesn't require a lock, it could have happened while
6298 * we are holding the lock. This pcb will have to
6299 * be garbage collected later.
6300 * Release the reference held for so_incomp queue
6302 VERIFY(so
->so_usecount
> 0);
6304 socket_unlock(so
, 1);
6307 * Unlock this socket and leave the reference on.
6308 * We need to acquire the pcbinfo lock in order to
6309 * fully dispose it off
6311 socket_unlock(so
, 0);
6313 lck_rw_lock_exclusive(tcbinfo
.ipi_lock
);
6316 /* Release the reference held for so_incomp queue */
6317 VERIFY(so
->so_usecount
> 0);
6320 if (so
->so_usecount
!= 1 ||
6321 (inp
->inp_wantcnt
> 0 &&
6322 inp
->inp_wantcnt
!= WNT_STOPUSING
)) {
6324 * There is an extra wantcount or usecount
6325 * that must have been added when the socket
6326 * was unlocked. This socket will have to be
6327 * garbage collected later
6329 socket_unlock(so
, 1);
6331 /* Drop the reference held for this function */
6332 VERIFY(so
->so_usecount
> 0);
6337 lck_rw_done(tcbinfo
.ipi_lock
);
6339 tcpstat
.tcps_drops
++;
6341 socket_lock(head
, 0);
6345 /* Set background congestion control on a socket */
6347 tcp_set_background_cc(struct socket
*so
)
6349 tcp_set_new_cc(so
, TCP_CC_ALGO_BACKGROUND_INDEX
);
6352 /* Set foreground congestion control on a socket */
6354 tcp_set_foreground_cc(struct socket
*so
)
6356 if (tcp_use_newreno
)
6357 tcp_set_new_cc(so
, TCP_CC_ALGO_NEWRENO_INDEX
);
6359 tcp_set_new_cc(so
, TCP_CC_ALGO_CUBIC_INDEX
);
6363 tcp_set_new_cc(struct socket
*so
, uint16_t cc_index
)
6365 struct inpcb
*inp
= sotoinpcb(so
);
6366 struct tcpcb
*tp
= intotcpcb(inp
);
6367 u_char old_cc_index
= 0;
6368 if (tp
->tcp_cc_index
!= cc_index
) {
6370 old_cc_index
= tp
->tcp_cc_index
;
6372 if (CC_ALGO(tp
)->cleanup
!= NULL
)
6373 CC_ALGO(tp
)->cleanup(tp
);
6374 tp
->tcp_cc_index
= cc_index
;
6376 tcp_cc_allocate_state(tp
);
6378 if (CC_ALGO(tp
)->switch_to
!= NULL
)
6379 CC_ALGO(tp
)->switch_to(tp
, old_cc_index
);
6381 tcp_ccdbg_trace(tp
, NULL
, TCP_CC_CHANGE_ALGO
);
6386 tcp_set_recv_bg(struct socket
*so
)
6388 if (!IS_TCP_RECV_BG(so
))
6389 so
->so_flags1
|= SOF1_TRAFFIC_MGT_TCP_RECVBG
;
6391 /* Unset Large Receive Offload on background sockets */
6392 so_set_lro(so
, SO_TC_BK
);
6396 tcp_clear_recv_bg(struct socket
*so
)
6398 if (IS_TCP_RECV_BG(so
))
6399 so
->so_flags1
&= ~(SOF1_TRAFFIC_MGT_TCP_RECVBG
);
6402 * Set/unset use of Large Receive Offload depending on
6405 so_set_lro(so
, so
->so_traffic_class
);
6409 inp_fc_unthrottle_tcp(struct inpcb
*inp
)
6411 struct tcpcb
*tp
= inp
->inp_ppcb
;
6413 * Back off the slow-start threshold and enter
6414 * congestion avoidance phase
6416 if (CC_ALGO(tp
)->pre_fr
!= NULL
)
6417 CC_ALGO(tp
)->pre_fr(tp
);
6419 tp
->snd_cwnd
= tp
->snd_ssthresh
;
6420 tp
->t_flagsext
&= ~TF_CWND_NONVALIDATED
;
6422 * Restart counting for ABC as we changed the
6423 * congestion window just now.
6425 tp
->t_bytes_acked
= 0;
6427 /* Reset retransmit shift as we know that the reason
6428 * for delay in sending a packet is due to flow
6429 * control on the outgoing interface. There is no need
6430 * to backoff retransmit timer.
6432 TCP_RESET_REXMT_STATE(tp
);
6435 * Start the output stream again. Since we are
6436 * not retransmitting data, do not reset the
6437 * retransmit timer or rtt calculation.
6443 tcp_getstat SYSCTL_HANDLER_ARGS
6445 #pragma unused(oidp, arg1, arg2)
6448 struct tcpstat
*stat
;
6450 #if !CONFIG_EMBEDDED
6451 proc_t caller
= PROC_NULL
;
6452 proc_t caller_parent
= PROC_NULL
;
6453 char command_name
[MAXCOMLEN
+ 1] = "";
6454 char parent_name
[MAXCOMLEN
+ 1] = "";
6455 struct tcpstat zero_stat
;
6456 if ((caller
= proc_self()) != PROC_NULL
) {
6457 /* get process name */
6458 strlcpy(command_name
, caller
->p_comm
, sizeof(command_name
));
6460 /* get parent process name if possible */
6461 if ((caller_parent
= proc_find(caller
->p_ppid
)) != PROC_NULL
) {
6462 strlcpy(parent_name
, caller_parent
->p_comm
,
6463 sizeof(parent_name
));
6464 proc_rele(caller_parent
);
6467 if ((escape_str(command_name
, strlen(command_name
) + 1,
6468 sizeof(command_name
)) == 0) &&
6469 (escape_str(parent_name
, strlen(parent_name
) + 1,
6470 sizeof(parent_name
)) == 0)) {
6471 kern_asl_msg(LOG_DEBUG
, "messagetracer",
6473 "com.apple.message.domain",
6474 "com.apple.kernel.tcpstat", /* 1 */
6475 "com.apple.message.signature",
6477 "com.apple.message.signature2", command_name
, /* 3 */
6478 "com.apple.message.signature3", parent_name
, /* 4 */
6479 "com.apple.message.summarize", "YES", /* 5 */
6483 if (caller
!= PROC_NULL
)
6485 if (tcp_disable_access_to_stats
&&
6486 !kauth_cred_issuser(kauth_cred_get())) {
6487 bzero(&zero_stat
, sizeof(zero_stat
));
6491 #endif /* !CONFIG_EMBEDDED */
6493 if (req
->oldptr
== 0) {
6494 req
->oldlen
= (size_t)sizeof(struct tcpstat
);
6497 error
= SYSCTL_OUT(req
, stat
, MIN(sizeof (tcpstat
), req
->oldlen
));
6504 * Checksum extended TCP header and data.
6507 tcp_input_checksum(int af
, struct mbuf
*m
, struct tcphdr
*th
, int off
, int tlen
)
6509 struct ifnet
*ifp
= m
->m_pkthdr
.rcvif
;
6513 struct ip
*ip
= mtod(m
, struct ip
*);
6514 struct ipovly
*ipov
= (struct ipovly
*)ip
;
6516 if (m
->m_pkthdr
.pkt_flags
& PKTF_SW_LRO_DID_CSUM
)
6519 /* ip_stripoptions() must have been called before we get here */
6520 ASSERT((ip
->ip_hl
<< 2) == sizeof (*ip
));
6522 if ((hwcksum_rx
|| (ifp
->if_flags
& IFF_LOOPBACK
) ||
6523 (m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) &&
6524 (m
->m_pkthdr
.csum_flags
& CSUM_DATA_VALID
)) {
6525 if (m
->m_pkthdr
.csum_flags
& CSUM_PSEUDO_HDR
) {
6526 th
->th_sum
= m
->m_pkthdr
.csum_rx_val
;
6528 uint32_t sum
= m
->m_pkthdr
.csum_rx_val
;
6529 uint32_t start
= m
->m_pkthdr
.csum_rx_start
;
6530 int32_t trailer
= (m_pktlen(m
) - (off
+ tlen
));
6533 * Perform 1's complement adjustment of octets
6534 * that got included/excluded in the hardware-
6535 * calculated checksum value. Ignore cases
6536 * where the value already includes the entire
6537 * IP header span, as the sum for those octets
6538 * would already be 0 by the time we get here;
6539 * IP has already performed its header checksum
6540 * checks. If we do need to adjust, restore
6541 * the original fields in the IP header when
6542 * computing the adjustment value. Also take
6543 * care of any trailing bytes and subtract out
6544 * their partial sum.
6546 ASSERT(trailer
>= 0);
6547 if ((m
->m_pkthdr
.csum_flags
& CSUM_PARTIAL
) &&
6548 ((start
!= 0 && start
!= off
) || trailer
)) {
6549 uint32_t swbytes
= (uint32_t)trailer
;
6552 ip
->ip_len
+= sizeof (*ip
);
6553 #if BYTE_ORDER != BIG_ENDIAN
6556 #endif /* BYTE_ORDER != BIG_ENDIAN */
6558 /* callee folds in sum */
6559 sum
= m_adj_sum16(m
, start
, off
,
6562 swbytes
+= (off
- start
);
6564 swbytes
+= (start
- off
);
6567 #if BYTE_ORDER != BIG_ENDIAN
6570 #endif /* BYTE_ORDER != BIG_ENDIAN */
6571 ip
->ip_len
-= sizeof (*ip
);
6575 tcp_in_cksum_stats(swbytes
);
6580 /* callee folds in sum */
6581 th
->th_sum
= in_pseudo(ip
->ip_src
.s_addr
,
6583 sum
+ htonl(tlen
+ IPPROTO_TCP
));
6585 th
->th_sum
^= 0xffff;
6591 bcopy(ipov
->ih_x1
, b
, sizeof (ipov
->ih_x1
));
6592 bzero(ipov
->ih_x1
, sizeof (ipov
->ih_x1
));
6593 ip_sum
= ipov
->ih_len
;
6594 ipov
->ih_len
= (u_short
)tlen
;
6595 #if BYTE_ORDER != BIG_ENDIAN
6596 HTONS(ipov
->ih_len
);
6598 len
= sizeof (struct ip
) + tlen
;
6599 th
->th_sum
= in_cksum(m
, len
);
6600 bcopy(b
, ipov
->ih_x1
, sizeof (ipov
->ih_x1
));
6601 ipov
->ih_len
= ip_sum
;
6603 tcp_in_cksum_stats(len
);
6609 struct ip6_hdr
*ip6
= mtod(m
, struct ip6_hdr
*);
6611 if (m
->m_pkthdr
.pkt_flags
& PKTF_SW_LRO_DID_CSUM
)
6614 if ((hwcksum_rx
|| (ifp
->if_flags
& IFF_LOOPBACK
) ||
6615 (m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) &&
6616 (m
->m_pkthdr
.csum_flags
& CSUM_DATA_VALID
)) {
6617 if (m
->m_pkthdr
.csum_flags
& CSUM_PSEUDO_HDR
) {
6618 th
->th_sum
= m
->m_pkthdr
.csum_rx_val
;
6620 uint32_t sum
= m
->m_pkthdr
.csum_rx_val
;
6621 uint32_t start
= m
->m_pkthdr
.csum_rx_start
;
6622 int32_t trailer
= (m_pktlen(m
) - (off
+ tlen
));
6625 * Perform 1's complement adjustment of octets
6626 * that got included/excluded in the hardware-
6627 * calculated checksum value. Also take care
6628 * of any trailing bytes and subtract out their
6631 ASSERT(trailer
>= 0);
6632 if ((m
->m_pkthdr
.csum_flags
& CSUM_PARTIAL
) &&
6633 (start
!= off
|| trailer
!= 0)) {
6634 uint16_t s
= 0, d
= 0;
6635 uint32_t swbytes
= (uint32_t)trailer
;
6637 if (IN6_IS_SCOPE_EMBED(&ip6
->ip6_src
)) {
6638 s
= ip6
->ip6_src
.s6_addr16
[1];
6639 ip6
->ip6_src
.s6_addr16
[1] = 0 ;
6641 if (IN6_IS_SCOPE_EMBED(&ip6
->ip6_dst
)) {
6642 d
= ip6
->ip6_dst
.s6_addr16
[1];
6643 ip6
->ip6_dst
.s6_addr16
[1] = 0;
6646 /* callee folds in sum */
6647 sum
= m_adj_sum16(m
, start
, off
,
6650 swbytes
+= (off
- start
);
6652 swbytes
+= (start
- off
);
6654 if (IN6_IS_SCOPE_EMBED(&ip6
->ip6_src
))
6655 ip6
->ip6_src
.s6_addr16
[1] = s
;
6656 if (IN6_IS_SCOPE_EMBED(&ip6
->ip6_dst
))
6657 ip6
->ip6_dst
.s6_addr16
[1] = d
;
6660 tcp_in6_cksum_stats(swbytes
);
6665 th
->th_sum
= in6_pseudo(
6666 &ip6
->ip6_src
, &ip6
->ip6_dst
,
6667 sum
+ htonl(tlen
+ IPPROTO_TCP
));
6669 th
->th_sum
^= 0xffff;
6671 tcp_in6_cksum_stats(tlen
);
6672 th
->th_sum
= in6_cksum(m
, IPPROTO_TCP
, off
, tlen
);
6682 if (th
->th_sum
!= 0) {
6683 tcpstat
.tcps_rcvbadsum
++;
6684 IF_TCP_STATINC(ifp
, badformat
);
6692 SYSCTL_PROC(_net_inet_tcp
, TCPCTL_STATS
, stats
,
6693 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
, 0, 0, tcp_getstat
,
6694 "S,tcpstat", "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
6697 sysctl_rexmtthresh SYSCTL_HANDLER_ARGS
6699 #pragma unused(arg1, arg2)
6701 int error
, val
= tcprexmtthresh
;
6703 error
= sysctl_handle_int(oidp
, &val
, 0, req
);
6704 if (error
|| !req
->newptr
)
6708 * Constrain the number of duplicate ACKs
6709 * to consider for TCP fast retransmit
6713 if (val
< 2 || val
> 3)
6716 tcprexmtthresh
= val
;
6721 SYSCTL_PROC(_net_inet_tcp
, OID_AUTO
, rexmt_thresh
, CTLTYPE_INT
| CTLFLAG_RW
|
6722 CTLFLAG_LOCKED
, &tcprexmtthresh
, 0, &sysctl_rexmtthresh
, "I",
6723 "Duplicate ACK Threshold for Fast Retransmit");